Coverage Report

Created: 2026-08-31 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/ssl/statem/extensions.c
Line
Count
Source
1
/*
2
 * Copyright 2016-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#if defined(__TANDEM) && defined(_SPT_MODEL_)
11
#include <spthread.h>
12
#include <spt_extensions.h> /* timeval */
13
#endif
14
15
#include <string.h>
16
#include "internal/nelem.h"
17
#include "internal/cryptlib.h"
18
#include "internal/ssl_unwrap.h"
19
#include "../ssl_local.h"
20
#include "statem_local.h"
21
#include <openssl/ocsp.h>
22
#include <openssl/core_names.h>
23
24
/*
25
 * values for ext_defs ech_handling field
26
 * exceptionally, we don't conditionally compile that field to avoid a pile of
27
 * ifndefs all over the ext_defs values
28
 */
29
0
#define OSSL_ECH_HANDLING_CALL_BOTH 1 /* call constructor both times */
30
0
#define OSSL_ECH_HANDLING_COMPRESS 2 /* compress outer value into inner */
31
#define OSSL_ECH_HANDLING_DUPLICATE 3 /* same value in inner and outer */
32
/*
33
 * DUPLICATE isn't really useful other than to show we can,
34
 * and for debugging/tests/coverage so may disappear. Changes mostly
35
 * won't affect the outer CH size, due to padding, but might for some
36
 * larger extensions.
37
 *
38
 * Note there is a co-dependency with test/recipes/75-test_quicapi.t:
39
 * If you change an |ech_handling| value, that may well affect the order
40
 * of extensions in a ClientHello, which is reflected in the test data
41
 * in test/recipes/75-test_quicapi_data/\*.txt files. To fix, you need
42
 * to look in test-runs/test_quicapi for the "new" files and then edit
43
 * (replacing actual octets with "?" in relevant places), and copy the
44
 * result back over to test/recipes/75-test_quicapi_data/. The reason
45
 * this happens is the ECH COMPRESS'd extensions need to be contiguous
46
 * in the ClientHello, so changes to/from COMPRESS affect extension
47
 * order, in inner and outer CH. There doesn't seem to be an easy,
48
 * generic, way to reconcile these compile-time changes with having
49
 * fixed value test files. Likely the best option is to decide on the
50
 * disposition of ECH COMPRESS or not and consider that an at least
51
 * medium-term thing. (But still allow other builds to vary at
52
 * compile time if they need something different.)
53
 */
54
#ifndef OPENSSL_NO_ECH
55
static int init_ech(SSL_CONNECTION *s, unsigned int context);
56
static int final_ech(SSL_CONNECTION *s, unsigned int context, int sent);
57
#endif /* OPENSSL_NO_ECH */
58
59
static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent);
60
static int init_server_name(SSL_CONNECTION *s, unsigned int context);
61
static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent);
62
static int init_session_ticket(SSL_CONNECTION *s, unsigned int context);
63
#ifndef OPENSSL_NO_OCSP
64
static int init_status_request(SSL_CONNECTION *s, unsigned int context);
65
#endif
66
#ifndef OPENSSL_NO_NEXTPROTONEG
67
static int init_npn(SSL_CONNECTION *s, unsigned int context);
68
#endif
69
static int init_alpn(SSL_CONNECTION *s, unsigned int context);
70
static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent);
71
static int init_sig_algs_cert(SSL_CONNECTION *s, unsigned int context);
72
static int init_sig_algs(SSL_CONNECTION *s, unsigned int context);
73
static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context);
74
static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context);
75
static int init_certificate_authorities(SSL_CONNECTION *s,
76
    unsigned int context);
77
static EXT_RETURN tls_construct_certificate_authorities(SSL_CONNECTION *s,
78
    WPACKET *pkt,
79
    unsigned int context,
80
    X509 *x,
81
    size_t chainidx);
82
static int tls_parse_certificate_authorities(SSL_CONNECTION *s, PACKET *pkt,
83
    unsigned int context, X509 *x,
84
    size_t chainidx);
85
#ifndef OPENSSL_NO_SRP
86
static int init_srp(SSL_CONNECTION *s, unsigned int context);
87
#endif
88
static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context);
89
static int init_etm(SSL_CONNECTION *s, unsigned int context);
90
static int init_ems(SSL_CONNECTION *s, unsigned int context);
91
static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent);
92
static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context);
93
static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent);
94
#ifndef OPENSSL_NO_SRTP
95
static int init_srtp(SSL_CONNECTION *s, unsigned int context);
96
#endif
97
static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent);
98
static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,
99
    int sent);
100
static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent);
101
static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,
102
    int sent);
103
static int init_post_handshake_auth(SSL_CONNECTION *s, unsigned int context);
104
static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent);
105
static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context);
106
static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,
107
    unsigned int context,
108
    X509 *x, size_t chainidx);
109
static int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt,
110
    unsigned int context,
111
    X509 *x, size_t chainidx);
112
static int tls_parse_ec_pt_formats(SSL_CONNECTION *s, PACKET *pkt,
113
    unsigned int context,
114
    X509 *x, size_t chainidx);
115
116
/* Structure to define a built-in extension */
117
typedef struct extensions_definition_st {
118
    /* The defined type for the extension */
119
    unsigned int type;
120
    /*
121
     * The context that this extension applies to, e.g. what messages and
122
     * protocol versions
123
     */
124
    unsigned int context;
125
    /*
126
     * exceptionally, we don't conditionally compile this field to avoid a
127
     * pile of ifndefs all over the ext_defs values
128
     */
129
    int ech_handling; /* how to handle ECH for this extension type */
130
    /*
131
     * Initialise extension before parsing. Always called for relevant contexts
132
     * even if extension not present
133
     */
134
    int (*init)(SSL_CONNECTION *s, unsigned int context);
135
    /* Parse extension sent from client to server */
136
    int (*parse_ctos)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,
137
        X509 *x, size_t chainidx);
138
    /* Parse extension send from server to client */
139
    int (*parse_stoc)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,
140
        X509 *x, size_t chainidx);
141
    /* Construct extension sent from server to client */
142
    EXT_RETURN (*construct_stoc)(SSL_CONNECTION *s, WPACKET *pkt,
143
        unsigned int context,
144
        X509 *x, size_t chainidx);
145
    /* Construct extension sent from client to server */
146
    EXT_RETURN (*construct_ctos)(SSL_CONNECTION *s, WPACKET *pkt,
147
        unsigned int context,
148
        X509 *x, size_t chainidx);
149
    /*
150
     * Finalise extension after parsing. Always called where an extensions was
151
     * initialised even if the extension was not present. |sent| is set to 1 if
152
     * the extension was seen, or 0 otherwise.
153
     */
154
    int (*final)(SSL_CONNECTION *s, unsigned int context, int sent);
155
} EXTENSION_DEFINITION;
156
157
/*
158
 * Definitions of all built-in extensions. NOTE: Changes in the number or order
159
 * of these extensions should be mirrored with equivalent changes to the
160
 * indexes ( TLSEXT_IDX_* ) defined in ssl_local.h.
161
 * Extensions should be added to test/ext_internal_test.c as well, as that
162
 * tests the ordering of the extensions.
163
 *
164
 * Each extension has an initialiser, a client and
165
 * server side parser and a finaliser. The initialiser is called (if the
166
 * extension is relevant to the given context) even if we did not see the
167
 * extension in the message that we received. The parser functions are only
168
 * called if we see the extension in the message. The finalisers are always
169
 * called if the initialiser was called.
170
 * There are also server and client side constructor functions which are always
171
 * called during message construction if the extension is relevant for the
172
 * given context.
173
 * The initialisation, parsing, finalisation and construction functions are
174
 * always called in the order defined in this list. Some extensions may depend
175
 * on others having been processed first, so the order of this list is
176
 * significant.
177
 * The extension context is defined by a series of flags which specify which
178
 * messages the extension is relevant to. These flags also specify whether the
179
 * extension is relevant to a particular protocol or protocol version.
180
 *
181
 * NOTE: WebSphere Application Server 7+ cannot handle empty extensions at
182
 * the end, keep these extensions before signature_algorithm.
183
 */
184
#define INVALID_EXTENSION { TLSEXT_TYPE_invalid, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL }
185
186
static const EXTENSION_DEFINITION ext_defs[] = {
187
    { TLSEXT_TYPE_renegotiate,
188
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
189
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
190
        OSSL_ECH_HANDLING_COMPRESS,
191
        NULL, tls_parse_ctos_renegotiate, tls_parse_stoc_renegotiate,
192
        tls_construct_stoc_renegotiate, tls_construct_ctos_renegotiate,
193
        final_renegotiate },
194
    { TLSEXT_TYPE_server_name,
195
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
196
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
197
        OSSL_ECH_HANDLING_CALL_BOTH,
198
        init_server_name,
199
        tls_parse_ctos_server_name, tls_parse_stoc_server_name,
200
        tls_construct_stoc_server_name, tls_construct_ctos_server_name,
201
        final_server_name },
202
    { TLSEXT_TYPE_max_fragment_length,
203
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
204
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
205
        OSSL_ECH_HANDLING_COMPRESS,
206
        NULL, tls_parse_ctos_maxfragmentlen, tls_parse_stoc_maxfragmentlen,
207
        tls_construct_stoc_maxfragmentlen, tls_construct_ctos_maxfragmentlen,
208
        final_maxfragmentlen },
209
#ifndef OPENSSL_NO_SRP
210
    { TLSEXT_TYPE_srp,
211
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
212
        OSSL_ECH_HANDLING_COMPRESS,
213
        init_srp, tls_parse_ctos_srp, NULL, NULL, tls_construct_ctos_srp, NULL },
214
#else
215
    INVALID_EXTENSION,
216
#endif
217
    { TLSEXT_TYPE_ec_point_formats,
218
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
219
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
220
        OSSL_ECH_HANDLING_COMPRESS,
221
        init_ec_point_formats, tls_parse_ec_pt_formats, tls_parse_ec_pt_formats,
222
        tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,
223
        NULL },
224
    { /*
225
       * "supported_groups" is spread across several specifications.
226
       * It was originally specified as "elliptic_curves" in RFC 4492,
227
       * and broadened to include named FFDH groups by RFC 7919.
228
       * Both RFCs 4492 and 7919 do not include a provision for the server
229
       * to indicate to the client the complete list of groups supported
230
       * by the server, with the server instead just indicating the
231
       * selected group for this connection in the ServerKeyExchange
232
       * message. (D)TLS 1.3 adds a scheme for the server to indicate
233
       * to the client its list of supported groups in the
234
       * EncryptedExtensions message, but none of the relevant
235
       * specifications permit sending supported_groups in the ServerHello.
236
       * Nonetheless (possibly due to the close proximity to the
237
       * "ec_point_formats" extension, which is allowed in the ServerHello),
238
       * there are several servers that send this extension in the
239
       * ServerHello anyway.  Up to and including the 1.1.0 release,
240
       * we did not check for the presence of nonpermitted extensions,
241
       * so to avoid a regression, we must permit this extension in the
242
       * (D)TLS 1.2 ServerHello as well.
243
       *
244
       * Note that there is no tls_parse_stoc_supported_groups function,
245
       * so we do not perform any additional parsing, validation, or
246
       * processing on the server's group list -- this is just a minimal
247
       * change to preserve compatibility with these misbehaving servers.
248
       */
249
        TLSEXT_TYPE_supported_groups,
250
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
251
            | SSL_EXT_TLS1_2_SERVER_HELLO,
252
        OSSL_ECH_HANDLING_COMPRESS,
253
        NULL, tls_parse_ctos_supported_groups, NULL,
254
        tls_construct_stoc_supported_groups,
255
        tls_construct_ctos_supported_groups, NULL },
256
    { TLSEXT_TYPE_session_ticket,
257
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
258
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
259
        OSSL_ECH_HANDLING_COMPRESS,
260
        init_session_ticket, tls_parse_ctos_session_ticket,
261
        tls_parse_stoc_session_ticket, tls_construct_stoc_session_ticket,
262
        tls_construct_ctos_session_ticket, NULL },
263
#ifndef OPENSSL_NO_OCSP
264
    { TLSEXT_TYPE_status_request,
265
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
266
            | SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
267
        OSSL_ECH_HANDLING_COMPRESS,
268
        init_status_request, tls_parse_ctos_status_request,
269
        tls_parse_stoc_status_request, tls_construct_stoc_status_request,
270
        tls_construct_ctos_status_request, NULL },
271
#else
272
    INVALID_EXTENSION,
273
#endif
274
#ifndef OPENSSL_NO_NEXTPROTONEG
275
    { TLSEXT_TYPE_next_proto_neg,
276
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
277
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
278
        OSSL_ECH_HANDLING_COMPRESS,
279
        init_npn, tls_parse_ctos_npn, tls_parse_stoc_npn,
280
        tls_construct_stoc_next_proto_neg, tls_construct_ctos_npn, NULL },
281
#else
282
    INVALID_EXTENSION,
283
#endif
284
    { /*
285
       * Must appear in this list after server_name so that finalisation
286
       * happens after server_name callbacks
287
       */
288
        TLSEXT_TYPE_application_layer_protocol_negotiation,
289
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
290
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
291
        OSSL_ECH_HANDLING_CALL_BOTH,
292
        init_alpn, tls_parse_ctos_alpn, tls_parse_stoc_alpn,
293
        tls_construct_stoc_alpn, tls_construct_ctos_alpn, final_alpn },
294
#ifndef OPENSSL_NO_SRTP
295
    { TLSEXT_TYPE_use_srtp,
296
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
297
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS | SSL_EXT_DTLS_ONLY,
298
        OSSL_ECH_HANDLING_COMPRESS,
299
        init_srtp, tls_parse_ctos_use_srtp, tls_parse_stoc_use_srtp,
300
        tls_construct_stoc_use_srtp, tls_construct_ctos_use_srtp, NULL },
301
#else
302
    INVALID_EXTENSION,
303
#endif
304
    { TLSEXT_TYPE_encrypt_then_mac,
305
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
306
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
307
        /*
308
         * If you want to demonstrate/exercise duplicate, then
309
         * this does that and has no effect on sizes, but it
310
         * will break the quicapi test (see above). Probably
311
         * best done in local tests and not committed to any
312
         * upstream.
313
         * OSSL_ECH_HANDLING_DUPLICATE,
314
         */
315
        OSSL_ECH_HANDLING_COMPRESS,
316
        init_etm, tls_parse_ctos_etm, tls_parse_stoc_etm,
317
        tls_construct_stoc_etm, tls_construct_ctos_etm, NULL },
318
#ifndef OPENSSL_NO_CT
319
    { TLSEXT_TYPE_signed_certificate_timestamp,
320
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
321
            | SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
322
        OSSL_ECH_HANDLING_COMPRESS,
323
        NULL,
324
        /*
325
         * No server side support for this, but can be provided by a custom
326
         * extension. This is an exception to the rule that custom extensions
327
         * cannot override built in ones.
328
         */
329
        NULL, tls_parse_stoc_sct, NULL, tls_construct_ctos_sct, NULL },
330
#else
331
    INVALID_EXTENSION,
332
#endif
333
    { TLSEXT_TYPE_extended_master_secret,
334
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
335
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
336
        OSSL_ECH_HANDLING_COMPRESS,
337
        init_ems, tls_parse_ctos_ems, tls_parse_stoc_ems,
338
        tls_construct_stoc_ems, tls_construct_ctos_ems, final_ems },
339
    { TLSEXT_TYPE_signature_algorithms_cert,
340
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
341
        OSSL_ECH_HANDLING_COMPRESS,
342
        init_sig_algs_cert, tls_parse_ctos_sig_algs_cert,
343
        tls_parse_ctos_sig_algs_cert,
344
        /* We do not generate signature_algorithms_cert at present. */
345
        NULL, NULL, NULL },
346
    {
347
        TLSEXT_TYPE_post_handshake_auth,
348
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY,
349
        OSSL_ECH_HANDLING_COMPRESS,
350
        init_post_handshake_auth,
351
        tls_parse_ctos_post_handshake_auth,
352
        NULL,
353
        NULL,
354
        tls_construct_ctos_post_handshake_auth,
355
        NULL,
356
    },
357
    { TLSEXT_TYPE_client_cert_type,
358
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
359
            | SSL_EXT_TLS1_2_SERVER_HELLO,
360
        OSSL_ECH_HANDLING_CALL_BOTH,
361
        init_client_cert_type,
362
        tls_parse_ctos_client_cert_type, tls_parse_stoc_client_cert_type,
363
        tls_construct_stoc_client_cert_type, tls_construct_ctos_client_cert_type,
364
        NULL },
365
    { TLSEXT_TYPE_server_cert_type,
366
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
367
            | SSL_EXT_TLS1_2_SERVER_HELLO,
368
        OSSL_ECH_HANDLING_CALL_BOTH,
369
        init_server_cert_type,
370
        tls_parse_ctos_server_cert_type, tls_parse_stoc_server_cert_type,
371
        tls_construct_stoc_server_cert_type, tls_construct_ctos_server_cert_type,
372
        NULL },
373
    { TLSEXT_TYPE_signature_algorithms,
374
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
375
        OSSL_ECH_HANDLING_COMPRESS,
376
        init_sig_algs, tls_parse_ctos_sig_algs,
377
        tls_parse_ctos_sig_algs, tls_construct_ctos_sig_algs,
378
        tls_construct_ctos_sig_algs, final_sig_algs },
379
    { TLSEXT_TYPE_supported_versions,
380
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
381
            | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
382
        OSSL_ECH_HANDLING_COMPRESS,
383
        NULL,
384
        /* Processed inline as part of version selection */
385
        NULL, tls_parse_stoc_supported_versions,
386
        tls_construct_stoc_supported_versions,
387
        tls_construct_ctos_supported_versions, final_supported_versions },
388
    { TLSEXT_TYPE_psk_kex_modes,
389
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY,
390
        OSSL_ECH_HANDLING_COMPRESS,
391
        init_psk_kex_modes, tls_parse_ctos_psk_kex_modes, NULL, NULL,
392
        tls_construct_ctos_psk_kex_modes, NULL },
393
    { /*
394
       * Must be in this list after supported_groups. We need that to have
395
       * been parsed before we do this one.
396
       */
397
        TLSEXT_TYPE_key_share,
398
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
399
            | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
400
            | SSL_EXT_TLS1_3_ONLY,
401
        OSSL_ECH_HANDLING_COMPRESS,
402
        NULL, tls_parse_ctos_key_share, tls_parse_stoc_key_share,
403
        tls_construct_stoc_key_share, tls_construct_ctos_key_share,
404
        final_key_share },
405
    { /* Must be after key_share */
406
        TLSEXT_TYPE_cookie,
407
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
408
            | SSL_EXT_TLS1_3_ONLY,
409
        OSSL_ECH_HANDLING_COMPRESS,
410
        NULL, tls_parse_ctos_cookie, tls_parse_stoc_cookie,
411
        tls_construct_stoc_cookie, tls_construct_ctos_cookie, NULL },
412
    { /*
413
       * Special unsolicited ServerHello extension only used when
414
       * SSL_OP_CRYPTOPRO_TLSEXT_BUG is set. We allow it in a ClientHello but
415
       * ignore it.
416
       */
417
        TLSEXT_TYPE_cryptopro_bug,
418
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
419
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
420
        OSSL_ECH_HANDLING_COMPRESS,
421
        NULL, NULL, NULL, tls_construct_stoc_cryptopro_bug, NULL, NULL },
422
    { TLSEXT_TYPE_compress_certificate,
423
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
424
            | SSL_EXT_TLS1_3_ONLY,
425
        OSSL_ECH_HANDLING_COMPRESS,
426
        tls_init_compress_certificate,
427
        tls_parse_compress_certificate, tls_parse_compress_certificate,
428
        tls_construct_compress_certificate, tls_construct_compress_certificate,
429
        NULL },
430
    { TLSEXT_TYPE_early_data,
431
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
432
            | SSL_EXT_TLS1_3_NEW_SESSION_TICKET | SSL_EXT_TLS1_3_ONLY,
433
        OSSL_ECH_HANDLING_CALL_BOTH,
434
        NULL, tls_parse_ctos_early_data, tls_parse_stoc_early_data,
435
        tls_construct_stoc_early_data, tls_construct_ctos_early_data,
436
        final_early_data },
437
    {
438
        TLSEXT_TYPE_certificate_authorities,
439
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
440
            | SSL_EXT_TLS1_3_ONLY,
441
        OSSL_ECH_HANDLING_COMPRESS,
442
        init_certificate_authorities,
443
        tls_parse_certificate_authorities,
444
        tls_parse_certificate_authorities,
445
        tls_construct_certificate_authorities,
446
        tls_construct_certificate_authorities,
447
        NULL,
448
    },
449
#ifndef OPENSSL_NO_ECH
450
    { TLSEXT_TYPE_ech,
451
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
452
        OSSL_ECH_HANDLING_CALL_BOTH,
453
        init_ech,
454
        tls_parse_ctos_ech, tls_parse_stoc_ech,
455
        tls_construct_stoc_ech, tls_construct_ctos_ech,
456
        final_ech },
457
    { TLSEXT_TYPE_outer_extensions,
458
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY,
459
        OSSL_ECH_HANDLING_CALL_BOTH,
460
        NULL,
461
        NULL, NULL,
462
        NULL, NULL,
463
        NULL },
464
#else /* OPENSSL_NO_ECH */
465
    INVALID_EXTENSION,
466
    INVALID_EXTENSION,
467
#endif /* END_OPENSSL_NO_ECH */
468
    { /* RFC 8701 GREASE extension 1 - type is dynamic */
469
        TLSEXT_TYPE_grease1,
470
        SSL_EXT_CLIENT_HELLO,
471
        0,
472
        NULL,
473
        NULL, NULL, NULL, tls_construct_ctos_grease1, NULL },
474
    { /* RFC 8701 GREASE extension 2 - type is dynamic */
475
        TLSEXT_TYPE_grease2,
476
        SSL_EXT_CLIENT_HELLO,
477
        0,
478
        NULL,
479
        NULL, NULL, NULL, tls_construct_ctos_grease2, NULL },
480
    { /* Required by the (D)TLSv1.3 spec to always be the last extension */
481
        TLSEXT_TYPE_psk,
482
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
483
            | SSL_EXT_TLS1_3_ONLY,
484
        OSSL_ECH_HANDLING_CALL_BOTH,
485
        NULL, tls_parse_ctos_psk, tls_parse_stoc_psk, tls_construct_stoc_psk,
486
        tls_construct_ctos_psk, final_psk }
487
};
488
489
#ifndef OPENSSL_NO_ECH
490
/*
491
 * Copy an inner extension value to outer.
492
 * inner CH must have been pre-decoded into s->clienthello->pre_proc_exts
493
 * already.
494
 */
495
int ossl_ech_copy_inner2outer(SSL_CONNECTION *s, uint16_t ext_type,
496
    int ind, WPACKET *pkt)
497
0
{
498
0
    RAW_EXTENSION *myext = NULL, *raws = NULL;
499
500
0
    if (s == NULL || s->clienthello == NULL)
501
0
        return OSSL_ECH_SAME_EXT_ERR;
502
0
    raws = s->clienthello->pre_proc_exts;
503
0
    if (raws == NULL)
504
0
        return OSSL_ECH_SAME_EXT_ERR;
505
0
    myext = &raws[ind];
506
0
    OSSL_TRACE_BEGIN(TLS)
507
0
    {
508
0
        BIO_printf(trc_out, "inner2outer: Copying ext type %d to outer\n",
509
0
            ext_type);
510
0
    }
511
0
    OSSL_TRACE_END(TLS);
512
513
    /*
514
     * copy inner value to outer
515
     */
516
0
    if (PACKET_data(&myext->data) != NULL
517
0
        && PACKET_remaining(&myext->data) > 0) {
518
0
        if (!WPACKET_put_bytes_u16(pkt, ext_type)
519
0
            || !WPACKET_sub_memcpy_u16(pkt, PACKET_data(&myext->data),
520
0
                PACKET_remaining(&myext->data)))
521
0
            return OSSL_ECH_SAME_EXT_ERR;
522
0
    } else {
523
        /* empty extension */
524
0
        if (!WPACKET_put_bytes_u16(pkt, ext_type)
525
0
            || !WPACKET_put_bytes_u16(pkt, 0))
526
0
            return OSSL_ECH_SAME_EXT_ERR;
527
0
    }
528
0
    return 1;
529
0
}
530
531
/*
532
 * DUPEMALL is useful for testing - this turns off compression and
533
 * causes two calls to each extension constructor, which'd be the same
534
 * as making all entries in ext_tab use the CALL_BOTH value
535
 */
536
#undef DUPEMALL
537
538
/*
539
 * Check if we're using the same/different key shares
540
 * return 1 if same key share in inner and outer, 0 otherwise
541
 */
542
int ossl_ech_same_key_share(void)
543
0
{
544
#ifdef DUPEMALL
545
    return 0;
546
#endif
547
0
    return ext_defs[TLSEXT_IDX_key_share].ech_handling
548
0
        != OSSL_ECH_HANDLING_CALL_BOTH;
549
0
}
550
551
/*
552
 * say if extension at index |ind| in ext_defs is to be ECH compressed
553
 * return 1 if this one is to be compressed, 0 if not, -1 for error
554
 */
555
int ossl_ech_2bcompressed(size_t ind)
556
0
{
557
0
    const size_t nexts = OSSL_NELEM(ext_defs);
558
559
#ifdef DUPEMALL
560
    return 0;
561
#endif
562
0
    if (ind >= nexts)
563
0
        return -1;
564
0
    return ext_defs[ind].ech_handling == OSSL_ECH_HANDLING_COMPRESS;
565
0
}
566
567
/* as needed, repeat extension from inner in outer handling compression */
568
int ossl_ech_same_ext(SSL_CONNECTION *s, WPACKET *pkt)
569
0
{
570
0
    unsigned int type = 0;
571
0
    int tind = 0, nexts = OSSL_NELEM(ext_defs);
572
573
#ifdef DUPEMALL
574
    return OSSL_ECH_SAME_EXT_CONTINUE;
575
#endif
576
0
    if (s == NULL || s->ext.ech.es == NULL)
577
0
        return OSSL_ECH_SAME_EXT_CONTINUE; /* nothing to do */
578
    /*
579
     * We store/access the index of the extension handler in
580
     * s->ext.ech.ext_ind, as we'd otherwise not know it here.
581
     * Be nice were there a better way to handle that.
582
     */
583
0
    tind = s->ext.ech.ext_ind;
584
    /* If this index'd extension won't be compressed, we're done */
585
0
    if (tind < 0 || tind >= nexts)
586
0
        return OSSL_ECH_SAME_EXT_ERR;
587
0
    type = ext_defs[tind].type;
588
0
    if (s->ext.ech.ch_depth == 1) {
589
        /* inner CH - just note compression as configured */
590
0
        if (ext_defs[tind].ech_handling != OSSL_ECH_HANDLING_COMPRESS)
591
0
            return OSSL_ECH_SAME_EXT_CONTINUE;
592
        /* mark this one to be "compressed" */
593
0
        if (s->ext.ech.n_outer_only >= OSSL_ECH_OUTERS_MAX)
594
0
            return OSSL_ECH_SAME_EXT_ERR;
595
0
        s->ext.ech.outer_only[s->ext.ech.n_outer_only] = type;
596
0
        s->ext.ech.n_outer_only++;
597
0
        OSSL_TRACE_BEGIN(TLS)
598
0
        {
599
0
            BIO_printf(trc_out, "ech_same_ext: Marking (type %u, ind %d "
600
0
                                "tot-comp %d) for compression\n",
601
0
                type, tind,
602
0
                (int)s->ext.ech.n_outer_only);
603
0
        }
604
0
        OSSL_TRACE_END(TLS);
605
0
        return OSSL_ECH_SAME_EXT_CONTINUE;
606
0
    } else {
607
        /* Copy value from inner to outer, or indicate a new value needed */
608
0
        if (s->clienthello == NULL || pkt == NULL)
609
0
            return OSSL_ECH_SAME_EXT_ERR;
610
0
        if (ext_defs[tind].ech_handling == OSSL_ECH_HANDLING_CALL_BOTH)
611
0
            return OSSL_ECH_SAME_EXT_CONTINUE;
612
0
        else
613
0
            return ossl_ech_copy_inner2outer(s, type, tind, pkt);
614
0
    }
615
    /* just in case - shouldn't happen */
616
0
    return OSSL_ECH_SAME_EXT_ERR;
617
0
}
618
#endif
619
620
/* Returns a TLSEXT_TYPE for the given index */
621
unsigned int ossl_get_extension_type(size_t idx)
622
0
{
623
0
    size_t num_exts = OSSL_NELEM(ext_defs);
624
625
0
    if (idx >= num_exts)
626
0
        return TLSEXT_TYPE_out_of_range;
627
628
0
    return ext_defs[idx].type;
629
0
}
630
631
/* Check whether an extension's context matches the current context */
632
static int validate_context(SSL_CONNECTION *s, unsigned int extctx,
633
    unsigned int thisctx)
634
0
{
635
    /* Check we're allowed to use this extension in this context */
636
0
    if ((thisctx & extctx) == 0)
637
0
        return 0;
638
639
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
640
0
        if ((extctx & SSL_EXT_TLS_ONLY) != 0)
641
0
            return 0;
642
0
    } else if ((extctx & SSL_EXT_DTLS_ONLY) != 0) {
643
0
        return 0;
644
0
    }
645
646
0
    return 1;
647
0
}
648
649
int tls_validate_all_contexts(SSL_CONNECTION *s, unsigned int thisctx,
650
    RAW_EXTENSION *exts)
651
0
{
652
0
    size_t i, num_exts, builtin_num = OSSL_NELEM(ext_defs), offset;
653
0
    RAW_EXTENSION *thisext;
654
0
    unsigned int context;
655
0
    ENDPOINT role = ENDPOINT_BOTH;
656
657
0
    if ((thisctx & SSL_EXT_CLIENT_HELLO) != 0)
658
0
        role = ENDPOINT_SERVER;
659
0
    else if ((thisctx & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
660
0
        role = ENDPOINT_CLIENT;
661
662
    /* Calculate the number of extensions in the extensions list */
663
0
    num_exts = builtin_num + s->cert->custext.meths_count;
664
665
0
    for (thisext = exts, i = 0; i < num_exts; i++, thisext++) {
666
0
        if (!thisext->present)
667
0
            continue;
668
669
0
        if (i < builtin_num) {
670
0
            context = ext_defs[i].context;
671
0
        } else {
672
0
            custom_ext_method *meth = NULL;
673
674
0
            meth = custom_ext_find(&s->cert->custext, role, thisext->type,
675
0
                &offset);
676
0
            if (!ossl_assert(meth != NULL))
677
0
                return 0;
678
0
            context = meth->context;
679
0
        }
680
681
0
        if (!validate_context(s, context, thisctx))
682
0
            return 0;
683
0
    }
684
685
0
    return 1;
686
0
}
687
688
/*
689
 * Verify whether we are allowed to use the extension |type| in the current
690
 * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
691
 * indicate the extension is not allowed. If returning 1 then |*found| is set to
692
 * the definition for the extension we found.
693
 */
694
static int verify_extension(SSL_CONNECTION *s, unsigned int context,
695
    unsigned int type, custom_ext_methods *meths,
696
    RAW_EXTENSION *rawexlist, RAW_EXTENSION **found)
697
0
{
698
0
    size_t i;
699
0
    size_t builtin_num = OSSL_NELEM(ext_defs);
700
0
    const EXTENSION_DEFINITION *thisext;
701
702
0
    for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {
703
0
        if (type == thisext->type) {
704
0
            if (!validate_context(s, thisext->context, context))
705
0
                return 0;
706
707
0
            *found = &rawexlist[i];
708
0
            return 1;
709
0
        }
710
0
    }
711
712
    /* Check the custom extensions */
713
0
    if (meths != NULL) {
714
0
        size_t offset = 0;
715
0
        ENDPOINT role = ENDPOINT_BOTH;
716
0
        custom_ext_method *meth = NULL;
717
718
0
        if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
719
0
#ifndef OPENSSL_NO_ECH
720
0
            if (s->ext.ech.attempted == 1 && s->ext.ech.ch_depth == 1)
721
0
                role = ENDPOINT_CLIENT;
722
0
            else
723
0
                role = ENDPOINT_SERVER;
724
#else
725
            role = ENDPOINT_SERVER;
726
#endif
727
0
        } else if ((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
728
0
            role = ENDPOINT_CLIENT;
729
730
0
        meth = custom_ext_find(meths, role, type, &offset);
731
0
        if (meth != NULL) {
732
0
            if (!validate_context(s, meth->context, context))
733
0
                return 0;
734
0
            *found = &rawexlist[offset + builtin_num];
735
0
            return 1;
736
0
        }
737
0
    }
738
739
    /* Unknown extension. We allow it */
740
0
    *found = NULL;
741
0
    return 1;
742
0
}
743
744
/*
745
 * Parse an ec_point_formats extension off the wire (one function for
746
 * both sides).  The peer's list is retained verbatim for
747
 * SSL_get0_ec_point_formats() and for the RFC 4492/8422 section 5.1.2
748
 * 'uncompressed must be present' check.
749
 *
750
 * The check is gated on the negotiated ciphersuite -- a TLS 1.3
751
 * handshake or a non-ECC TLS 1.2 ciphersuite makes the extension moot
752
 * and any missing 'uncompressed' codepoint is ignored.  On the client
753
 * the chosen ciphersuite is already locked in by the time we parse
754
 * ServerHello, so the check happens inline here.  On the server it's
755
 * deferred to tls_construct_stoc_ec_pt_formats(), the first point at
756
 * which s->s3.tmp.new_cipher is set for TLS 1.2.
757
 */
758
static int tls_parse_ec_pt_formats(SSL_CONNECTION *s, PACKET *pkt,
759
    unsigned int context, X509 *x, size_t chainidx)
760
0
{
761
0
    PACKET list;
762
763
0
    if (!PACKET_as_length_prefixed_1(pkt, &list)
764
0
        || PACKET_remaining(&list) == 0) {
765
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
766
0
        return 0;
767
0
    }
768
0
    if (!s->hit
769
0
        && !PACKET_memdup(&list, &s->ext.peer_ecpointformats,
770
0
            &s->ext.peer_ecpointformats_len)) {
771
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
772
0
        return 0;
773
0
    }
774
775
0
    if (!s->server) {
776
0
        unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
777
0
        unsigned long alg_a = s->s3.tmp.new_cipher->algorithm_auth;
778
779
0
        if (((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))
780
0
            && memchr(PACKET_data(&list),
781
0
                   TLSEXT_ECPOINTFORMAT_uncompressed,
782
0
                   PACKET_remaining(&list))
783
0
                == NULL) {
784
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
785
0
                SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
786
0
            return 0;
787
0
        }
788
0
    }
789
790
0
    return 1;
791
0
}
792
793
/*
794
 * Verify that all extensions in |packet| are known built-in or custom
795
 * extension types. This is used for TLS 1.3 server extension responses where
796
 * unknown extensions are not ignored.
797
 */
798
int tls_validate_no_unknown_extensions(SSL_CONNECTION *s, PACKET *packet,
799
    unsigned int context)
800
0
{
801
0
    PACKET extensions = *packet;
802
0
    custom_ext_methods *exts = &s->cert->custext;
803
0
    ENDPOINT role = ENDPOINT_BOTH;
804
805
0
    if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
806
0
#ifndef OPENSSL_NO_ECH
807
0
        if (s->ext.ech.attempted == 1 && s->ext.ech.ch_depth == 1)
808
0
            role = ENDPOINT_CLIENT;
809
0
        else
810
0
            role = ENDPOINT_SERVER;
811
#else
812
        role = ENDPOINT_SERVER;
813
#endif
814
0
    } else if ((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0) {
815
0
        role = ENDPOINT_CLIENT;
816
0
    }
817
818
0
    while (PACKET_remaining(&extensions) > 0) {
819
0
        unsigned int type;
820
0
        size_t i;
821
0
        PACKET extension;
822
0
        const EXTENSION_DEFINITION *thisext;
823
824
0
        if (!PACKET_get_net_2(&extensions, &type)
825
0
            || !PACKET_get_length_prefixed_2(&extensions, &extension)) {
826
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
827
0
            return 0;
828
0
        }
829
830
0
        for (i = 0, thisext = ext_defs; i < OSSL_NELEM(ext_defs);
831
0
            i++, thisext++) {
832
0
            if (type == thisext->type)
833
0
                break;
834
0
        }
835
0
        if (i < OSSL_NELEM(ext_defs))
836
0
            continue;
837
838
0
        if (exts != NULL && custom_ext_find(exts, role, type, NULL) != NULL)
839
0
            continue;
840
841
0
        SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION,
842
0
            SSL_R_UNSOLICITED_EXTENSION);
843
0
        return 0;
844
0
    }
845
846
0
    return 1;
847
0
}
848
849
/*
850
 * Check whether the context defined for an extension |extctx| means whether
851
 * the extension is relevant for the current context |thisctx| or not. Returns
852
 * 1 if the extension is relevant for this context, and 0 otherwise
853
 */
854
int extension_is_relevant(SSL_CONNECTION *s, unsigned int extctx,
855
    unsigned int thisctx)
856
0
{
857
0
    int is_version13;
858
859
    /*
860
     * For HRR we haven't selected the version yet but we know it will be
861
     * (D)TLSv1.3
862
     */
863
0
    if ((thisctx & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
864
0
        is_version13 = 1;
865
0
    else
866
0
        is_version13 = SSL_CONNECTION_IS_VERSION13(s);
867
868
0
    if ((SSL_CONNECTION_IS_DTLS(s)
869
0
            && (extctx & SSL_EXT_TLS_IMPLEMENTATION_ONLY) != 0)
870
        /*
871
         * Note that is_version13 means "(D)TLS 1.3 has been negotiated",
872
         * which is never true when generating the ClientHello.
873
         * However, version negotiation *has* occurred by the time the
874
         * ClientHello extensions are being parsed.
875
         * Be careful to allow (D)TLS 1.3-only extensions when generating
876
         * the ClientHello.
877
         */
878
0
        || (is_version13 && (extctx & SSL_EXT_TLS1_2_AND_BELOW_ONLY) != 0)
879
0
        || (!is_version13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0
880
0
            && (thisctx & SSL_EXT_CLIENT_HELLO) == 0)
881
0
        || (s->server && !is_version13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0)
882
0
        || (s->hit && (extctx & SSL_EXT_IGNORE_ON_RESUMPTION) != 0))
883
0
        return 0;
884
0
    return 1;
885
0
}
886
887
/*
888
 * Gather a list of all the extensions from the data in |packet]. |context|
889
 * tells us which message this extension is for. The raw extension data is
890
 * stored in |*res| on success. We don't actually process the content of the
891
 * extensions yet, except to check their types. This function also runs the
892
 * initialiser functions for all known extensions if |init| is nonzero (whether
893
 * we have collected them or not). If successful the caller is responsible for
894
 * freeing the contents of |*res|.
895
 *
896
 * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
897
 * more than one extension of the same type in a ClientHello or ServerHello.
898
 * This function returns 1 if all extensions are unique and we have parsed their
899
 * types, and 0 if the extensions contain duplicates, could not be successfully
900
 * found, or an internal error occurred. We only check duplicates for
901
 * extensions that we know about. We ignore others.
902
 */
903
int tls_collect_extensions(SSL_CONNECTION *s, PACKET *packet,
904
    unsigned int context,
905
    RAW_EXTENSION **res, size_t *len, int init)
906
0
{
907
0
    PACKET extensions = *packet;
908
0
    size_t i = 0;
909
0
    size_t num_exts;
910
0
    custom_ext_methods *exts = &s->cert->custext;
911
0
    RAW_EXTENSION *raw_extensions = NULL;
912
0
    const EXTENSION_DEFINITION *thisexd;
913
914
0
    *res = NULL;
915
916
    /*
917
     * Initialise server side custom extensions. Client side is done during
918
     * construction of extensions for the ClientHello.
919
     */
920
0
#ifndef OPENSSL_NO_ECH
921
0
    if ((context & SSL_EXT_CLIENT_HELLO) != 0 && s->ext.ech.attempted == 0)
922
0
        custom_ext_init(&s->cert->custext);
923
#else
924
    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
925
        custom_ext_init(&s->cert->custext);
926
#endif
927
928
0
    num_exts = OSSL_NELEM(ext_defs) + (exts != NULL ? exts->meths_count : 0);
929
0
    raw_extensions = OPENSSL_calloc(num_exts, sizeof(*raw_extensions));
930
0
    if (raw_extensions == NULL) {
931
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
932
0
        return 0;
933
0
    }
934
935
0
    i = 0;
936
0
    while (PACKET_remaining(&extensions) > 0) {
937
0
        unsigned int type, idx;
938
0
        PACKET extension;
939
0
        RAW_EXTENSION *thisex;
940
941
0
        if (!PACKET_get_net_2(&extensions, &type) || !PACKET_get_length_prefixed_2(&extensions, &extension)) {
942
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
943
0
            goto err;
944
0
        }
945
        /*
946
         * Verify this extension is allowed. We only check duplicates for
947
         * extensions that we recognise. We also have a special case for the
948
         * PSK extension, which must be the last one in the ClientHello.
949
         */
950
0
        if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)
951
0
            || (thisex != NULL && thisex->present == 1)
952
0
            || (type == TLSEXT_TYPE_psk
953
0
                && (context & SSL_EXT_CLIENT_HELLO) != 0
954
0
                && PACKET_remaining(&extensions) != 0)) {
955
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
956
0
            goto err;
957
0
        }
958
        /* The server must tolerate the unknown extension and complete. */
959
0
        if (thisex == NULL)
960
0
            continue;
961
962
0
        idx = (unsigned int)(thisex - raw_extensions);
963
        /*-
964
         * Check that we requested this extension (if appropriate). Requests can
965
         * be sent in the ClientHello and CertificateRequest. Unsolicited
966
         * extensions can be sent in the NewSessionTicket. We only do this for
967
         * the built-in extensions. Custom extensions have a different but
968
         * similar check elsewhere.
969
         * Special cases:
970
         * - The HRR cookie extension is unsolicited
971
         * - The renegotiate extension is unsolicited (the client signals
972
         *   support via an SCSV)
973
         * - The signed_certificate_timestamp extension can be provided by a
974
         * custom extension or by the built-in version. We let the extension
975
         * itself handle unsolicited response checks.
976
         */
977
0
        if (idx < OSSL_NELEM(ext_defs)
978
0
            && (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) == 0
979
0
            && type != TLSEXT_TYPE_cookie
980
0
            && type != TLSEXT_TYPE_renegotiate
981
0
            && type != TLSEXT_TYPE_signed_certificate_timestamp
982
0
            && (s->ext.extflags[idx] & SSL_EXT_FLAG_SENT) == 0
983
0
#ifndef OPENSSL_NO_GOST
984
0
            && !((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0
985
0
                && type == TLSEXT_TYPE_cryptopro_bug)
986
0
#endif
987
0
        ) {
988
0
            SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION,
989
0
                SSL_R_UNSOLICITED_EXTENSION);
990
0
            goto err;
991
0
        }
992
0
        thisex->data = extension;
993
0
        thisex->present = 1;
994
0
        thisex->type = type;
995
0
        thisex->received_order = i++;
996
0
        if (s->ext.debug_cb)
997
0
            s->ext.debug_cb(SSL_CONNECTION_GET_USER_SSL(s), !s->server,
998
0
                thisex->type, PACKET_data(&thisex->data),
999
0
                (int)PACKET_remaining(&thisex->data),
1000
0
                s->ext.debug_arg);
1001
0
    }
1002
1003
0
    if (init) {
1004
        /*
1005
         * Initialise all known extensions relevant to this context,
1006
         * whether we have found them or not
1007
         */
1008
0
        for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs);
1009
0
            i++, thisexd++) {
1010
0
            if (thisexd->init != NULL && (thisexd->context & context) != 0
1011
0
                && extension_is_relevant(s, thisexd->context, context)
1012
0
                && !thisexd->init(s, context)) {
1013
                /* SSLfatal() already called */
1014
0
                goto err;
1015
0
            }
1016
0
        }
1017
0
    }
1018
1019
0
    *res = raw_extensions;
1020
0
    if (len != NULL)
1021
0
        *len = num_exts;
1022
0
    return 1;
1023
1024
0
err:
1025
0
    OPENSSL_free(raw_extensions);
1026
0
    return 0;
1027
0
}
1028
1029
/*
1030
 * Runs the parser for a given extension with index |idx|. |exts| contains the
1031
 * list of all parsed extensions previously collected by
1032
 * tls_collect_extensions(). The parser is only run if it is applicable for the
1033
 * given |context| and the parser has not already been run. If this is for a
1034
 * Certificate message, then we also provide the parser with the relevant
1035
 * Certificate |x| and its position in the |chainidx| with 0 being the first
1036
 * Certificate. Returns 1 on success or 0 on failure. If an extension is not
1037
 * present this counted as success.
1038
 */
1039
int tls_parse_extension(SSL_CONNECTION *s, TLSEXT_INDEX idx, int context,
1040
    RAW_EXTENSION *exts, X509 *x, size_t chainidx)
1041
0
{
1042
0
    RAW_EXTENSION *currext = &exts[idx];
1043
0
    int (*parser)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context, X509 *x,
1044
0
        size_t chainidx)
1045
0
        = NULL;
1046
1047
    /* Skip if the extension is not present */
1048
0
    if (!currext->present)
1049
0
        return 1;
1050
1051
    /* Skip if we've already parsed this extension */
1052
0
    if (currext->parsed)
1053
0
        return 1;
1054
1055
0
    currext->parsed = 1;
1056
1057
0
    if (idx < OSSL_NELEM(ext_defs)) {
1058
        /* We are handling a built-in extension */
1059
0
        const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
1060
1061
        /* Check if extension is defined for our protocol. If not, skip */
1062
0
        if (!extension_is_relevant(s, extdef->context, context))
1063
0
            return 1;
1064
1065
0
        parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
1066
1067
0
        if (parser != NULL)
1068
0
            return parser(s, &currext->data, context, x, chainidx);
1069
1070
        /*
1071
         * If the parser is NULL we fall through to the custom extension
1072
         * processing
1073
         */
1074
0
    }
1075
1076
    /* Parse custom extensions */
1077
0
    return custom_ext_parse(s, context, currext->type,
1078
0
        PACKET_data(&currext->data),
1079
0
        PACKET_remaining(&currext->data),
1080
0
        x, chainidx);
1081
0
}
1082
1083
/*
1084
 * Parse all remaining extensions that have not yet been parsed. Also calls the
1085
 * finalisation for all extensions at the end if |fin| is nonzero, whether we
1086
 * collected them or not. Returns 1 for success or 0 for failure. If we are
1087
 * working on a Certificate message then we also pass the Certificate |x| and
1088
 * its position in the |chainidx|, with 0 being the first certificate.
1089
 */
1090
int tls_parse_all_extensions(SSL_CONNECTION *s, int context,
1091
    RAW_EXTENSION *exts, X509 *x,
1092
    size_t chainidx, int fin)
1093
0
{
1094
0
    size_t i, numexts = OSSL_NELEM(ext_defs);
1095
0
    const EXTENSION_DEFINITION *thisexd;
1096
1097
    /* Calculate the number of extensions in the extensions list */
1098
0
    numexts += s->cert->custext.meths_count;
1099
1100
    /* Parse each extension in turn */
1101
0
    for (i = 0; i < numexts; i++) {
1102
0
        if (!tls_parse_extension(s, i, context, exts, x, chainidx)) {
1103
            /* SSLfatal() already called */
1104
0
            return 0;
1105
0
        }
1106
0
    }
1107
1108
0
    if (fin) {
1109
        /*
1110
         * Finalise all known extensions relevant to this context,
1111
         * whether we have found them or not
1112
         */
1113
0
        for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);
1114
0
            i++, thisexd++) {
1115
0
            if (thisexd->final != NULL && (thisexd->context & context) != 0
1116
0
                && !thisexd->final(s, context, exts[i].present)) {
1117
                /* SSLfatal() already called */
1118
0
                return 0;
1119
0
            }
1120
0
        }
1121
0
    }
1122
1123
0
    return 1;
1124
0
}
1125
1126
int should_add_extension(SSL_CONNECTION *s, unsigned int extctx,
1127
    unsigned int thisctx, int max_version)
1128
0
{
1129
0
    const int version1_3 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_3_VERSION : TLS1_3_VERSION;
1130
1131
    /* Skip if not relevant for our context */
1132
0
    if ((extctx & thisctx) == 0)
1133
0
        return 0;
1134
1135
    /* Check if this extension is defined for our protocol. If not, skip */
1136
0
    if (!extension_is_relevant(s, extctx, thisctx)
1137
0
        || ((extctx & SSL_EXT_TLS1_3_ONLY) != 0
1138
0
            && (thisctx & SSL_EXT_CLIENT_HELLO) != 0
1139
0
            && ssl_version_cmp(s, max_version, version1_3) < 0))
1140
0
        return 0;
1141
1142
0
    return 1;
1143
0
}
1144
1145
/*
1146
 * Construct all the extensions relevant to the current |context| and write
1147
 * them to |pkt|. If this is an extension for a Certificate in a Certificate
1148
 * message, then |x| will be set to the Certificate we are handling, and
1149
 * |chainidx| will indicate the position in the chainidx we are processing (with
1150
 * 0 being the first in the chain). Returns 1 on success or 0 on failure. On a
1151
 * failure construction stops at the first extension to fail to construct.
1152
 */
1153
int tls_construct_extensions(SSL_CONNECTION *s, WPACKET *pkt,
1154
    unsigned int context,
1155
    X509 *x, size_t chainidx)
1156
0
{
1157
0
    size_t i;
1158
0
    int min_version, max_version = 0, reason;
1159
0
    const EXTENSION_DEFINITION *thisexd;
1160
0
    int for_comp = (context & SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION) != 0;
1161
0
#ifndef OPENSSL_NO_ECH
1162
0
    int pass;
1163
0
#endif
1164
1165
0
    if (!WPACKET_start_sub_packet_u16(pkt)
1166
        /*
1167
         * If extensions are of zero length then we don't even add the
1168
         * extensions length bytes to a ClientHello/ServerHello
1169
         * (for non-(D)TLSv1.3).
1170
         */
1171
0
        || ((context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO)) != 0
1172
0
            && !WPACKET_set_flags(pkt,
1173
0
                WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
1174
0
        if (!for_comp)
1175
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1176
0
        return 0;
1177
0
    }
1178
1179
0
    if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
1180
0
        reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
1181
0
        if (reason != 0) {
1182
0
            if (!for_comp)
1183
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
1184
0
            return 0;
1185
0
        }
1186
0
    }
1187
1188
    /* Add custom extensions first */
1189
0
#ifndef OPENSSL_NO_ECH
1190
0
    if ((context & SSL_EXT_CLIENT_HELLO) != 0 && s->ext.ech.attempted == 0)
1191
        /* On the server side with initialise during ClientHello parsing */
1192
0
        custom_ext_init(&s->cert->custext);
1193
#else
1194
    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
1195
        /* On the server side with initialise during ClientHello parsing */
1196
        custom_ext_init(&s->cert->custext);
1197
#endif
1198
0
    if (!custom_ext_add(s, context, pkt, x, chainidx, max_version)) {
1199
        /* SSLfatal() already called */
1200
0
        return 0;
1201
0
    }
1202
1203
0
#ifndef OPENSSL_NO_ECH
1204
    /*
1205
     * Two passes if doing real ECH - we first construct the
1206
     * to-be-ECH-compressed extensions, and then go around again
1207
     * constructing those that aren't to be ECH-compressed. We
1208
     * need to ensure this ordering so that all the ECH-compressed
1209
     * extensions are contiguous in the encoding. The actual
1210
     * compression happens later in ech_encode_inner().
1211
     */
1212
0
    for (pass = 0; pass <= 1; pass++)
1213
0
#endif
1214
1215
0
        for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);
1216
0
            i++, thisexd++) {
1217
0
            EXT_RETURN (*construct)(SSL_CONNECTION *s, WPACKET *pkt,
1218
0
                unsigned int context,
1219
0
                X509 *x, size_t chainidx);
1220
0
            EXT_RETURN ret;
1221
1222
0
#ifndef OPENSSL_NO_ECH
1223
            /* do compressed in pass 0, non-compressed in pass 1 */
1224
0
            if (ossl_ech_2bcompressed((int)i) == pass)
1225
0
                continue;
1226
            /* stash index - needed for COMPRESS ECH handling */
1227
0
            s->ext.ech.ext_ind = (int)i;
1228
0
#endif
1229
            /* Skip if not relevant for our context */
1230
0
            if (!should_add_extension(s, thisexd->context, context, max_version))
1231
0
                continue;
1232
1233
0
            construct = s->server ? thisexd->construct_stoc
1234
0
                                  : thisexd->construct_ctos;
1235
1236
0
            if (construct == NULL)
1237
0
                continue;
1238
1239
0
            ret = construct(s, pkt, context, x, chainidx);
1240
0
            if (ret == EXT_RETURN_FAIL) {
1241
                /* SSLfatal() already called */
1242
0
                return 0;
1243
0
            }
1244
0
            if (ret == EXT_RETURN_SENT
1245
0
                && (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) != 0)
1246
0
                s->ext.extflags[i] |= SSL_EXT_FLAG_SENT;
1247
0
        }
1248
1249
0
#ifndef OPENSSL_NO_ECH
1250
    /*
1251
     * don't close yet if client in the middle of doing ECH, we'll
1252
     * eventually close this in ech_aad_and_encrypt() after we add
1253
     * the real ECH extension value
1254
     */
1255
0
    if (s->server
1256
0
        || context != SSL_EXT_CLIENT_HELLO
1257
0
        || s->ext.ech.attempted == 0
1258
0
        || s->ext.ech.ch_depth == 1
1259
0
        || s->ext.ech.grease == OSSL_ECH_IS_GREASE) {
1260
0
        if (!WPACKET_close(pkt)) {
1261
0
            if (!for_comp)
1262
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1263
0
            return 0;
1264
0
        }
1265
0
    }
1266
#else
1267
    if (!WPACKET_close(pkt)) {
1268
        if (!for_comp)
1269
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1270
        return 0;
1271
    }
1272
#endif
1273
0
    return 1;
1274
0
}
1275
1276
/*
1277
 * Built in extension finalisation and initialisation functions. All initialise
1278
 * or finalise the associated extension type for the given |context|. For
1279
 * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
1280
 * otherwise. These functions return 1 on success or 0 on failure.
1281
 */
1282
1283
static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent)
1284
0
{
1285
0
    if (!s->server) {
1286
        /*
1287
         * Check if we can connect to a server that doesn't support safe
1288
         * renegotiation
1289
         */
1290
0
        if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
1291
0
            && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
1292
0
            && !sent) {
1293
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1294
0
                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1295
0
            return 0;
1296
0
        }
1297
1298
0
        return 1;
1299
0
    }
1300
1301
    /* Need RI if renegotiating */
1302
0
    if (s->renegotiate
1303
0
        && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
1304
0
        && !sent) {
1305
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1306
0
            SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1307
0
        return 0;
1308
0
    }
1309
1310
0
    return 1;
1311
0
}
1312
1313
static ossl_inline void ssl_tsan_decr(const SSL_CTX *ctx,
1314
    TSAN_QUALIFIER int *stat)
1315
0
{
1316
0
    if (ssl_tsan_lock(ctx)) {
1317
0
        tsan_decr(stat);
1318
0
        ssl_tsan_unlock(ctx);
1319
0
    }
1320
0
}
1321
1322
static int init_server_name(SSL_CONNECTION *s, unsigned int context)
1323
0
{
1324
0
    if (s->server) {
1325
0
        s->servername_done = 0;
1326
1327
0
        OPENSSL_free(s->ext.hostname);
1328
0
        s->ext.hostname = NULL;
1329
0
    }
1330
1331
0
    return 1;
1332
0
}
1333
1334
#ifndef OPENSSL_NO_ECH
1335
/*
1336
 * Just note that ech is not yet done
1337
 * return 1 for good, 0 otherwise
1338
 */
1339
static int init_ech(SSL_CONNECTION *s, unsigned int context)
1340
0
{
1341
0
    const int nexts = OSSL_NELEM(ext_defs);
1342
1343
    /* we don't need this assert everywhere - anywhere is fine */
1344
0
    if (!ossl_assert(TLSEXT_IDX_num_builtins == nexts)) {
1345
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1346
0
        return 0;
1347
0
    }
1348
0
    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
1349
0
        s->ext.ech.done = 0;
1350
0
    return 1;
1351
0
}
1352
1353
static int final_ech(SSL_CONNECTION *s, unsigned int context, int sent)
1354
0
{
1355
0
    if (s->server && s->ext.ech.success == 1
1356
0
        && s->ext.ech.inner_ech_seen_ok != 1) {
1357
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_ECH_REQUIRED);
1358
0
        return 0;
1359
0
    }
1360
0
    return 1;
1361
0
}
1362
#endif /* OPENSSL_NO_ECH */
1363
1364
static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent)
1365
0
{
1366
0
    int ret = SSL_TLSEXT_ERR_NOACK;
1367
0
    int altmp = SSL_AD_UNRECOGNIZED_NAME;
1368
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1369
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1370
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1371
0
    int was_ticket = (SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0;
1372
1373
0
    if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {
1374
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1375
0
        return 0;
1376
0
    }
1377
1378
0
    if (sctx->ext.servername_cb != NULL)
1379
0
        ret = sctx->ext.servername_cb(ussl, &altmp,
1380
0
            sctx->ext.servername_arg);
1381
0
    else if (s->session_ctx->ext.servername_cb != NULL)
1382
0
        ret = s->session_ctx->ext.servername_cb(ussl, &altmp,
1383
0
            s->session_ctx->ext.servername_arg);
1384
1385
    /*
1386
     * For servers, propagate the SNI hostname from the temporary
1387
     * storage in the SSL to the persistent SSL_SESSION, now that we
1388
     * know we accepted it.
1389
     * Clients make this copy when parsing the server's response to
1390
     * the extension, which is when they find out that the negotiation
1391
     * was successful.
1392
     */
1393
0
    if (s->server) {
1394
0
        if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {
1395
            /* Only store the hostname in the session if we accepted it. */
1396
0
            OPENSSL_free(s->session->ext.hostname);
1397
0
            s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
1398
0
            if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {
1399
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1400
0
            }
1401
0
        }
1402
0
    }
1403
1404
    /*
1405
     * If we switched contexts (whether here or in the client_hello callback),
1406
     * move the sess_accept increment from the session_ctx to the new
1407
     * context, to avoid the confusing situation of having sess_accept_good
1408
     * exceed sess_accept (zero) for the new context.
1409
     */
1410
0
    if (SSL_IS_FIRST_HANDSHAKE(s) && sctx != s->session_ctx
1411
0
        && s->hello_retry_request == SSL_HRR_NONE) {
1412
0
        ssl_tsan_counter(sctx, &sctx->stats.sess_accept);
1413
0
        ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);
1414
0
    }
1415
1416
    /*
1417
     * If we're expecting to send a ticket, and tickets were previously enabled,
1418
     * and now tickets are disabled, then turn off expected ticket.
1419
     * Also, if this is not a resumption, create a new session ID
1420
     */
1421
0
    if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected
1422
0
        && was_ticket && (SSL_get_options(ssl) & SSL_OP_NO_TICKET) != 0) {
1423
0
        s->ext.ticket_expected = 0;
1424
0
        if (!s->hit) {
1425
0
            SSL_SESSION *ss = SSL_get_session(ssl);
1426
1427
0
            if (ss != NULL) {
1428
0
                OPENSSL_free(ss->ext.tick);
1429
0
                ss->ext.tick = NULL;
1430
0
                ss->ext.ticklen = 0;
1431
0
                ss->ext.tick_lifetime_hint = 0;
1432
0
                ss->ext.tick_age_add = 0;
1433
0
                if (!ssl_generate_session_id(s, ss)) {
1434
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1435
0
                    return 0;
1436
0
                }
1437
0
            } else {
1438
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1439
0
                return 0;
1440
0
            }
1441
0
        }
1442
0
    }
1443
1444
0
    switch (ret) {
1445
0
    case SSL_TLSEXT_ERR_ALERT_FATAL:
1446
0
        SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);
1447
0
        return 0;
1448
1449
0
    case SSL_TLSEXT_ERR_ALERT_WARNING:
1450
        /* (D)TLSv1.3 doesn't have warning alerts so we suppress this */
1451
0
        if (!SSL_CONNECTION_IS_VERSION13(s))
1452
0
            ssl3_send_alert(s, SSL3_AL_WARNING, altmp);
1453
0
        s->servername_done = 0;
1454
0
        return 1;
1455
1456
0
    case SSL_TLSEXT_ERR_NOACK:
1457
0
        s->servername_done = 0;
1458
0
        return 1;
1459
1460
0
    default:
1461
0
        return 1;
1462
0
    }
1463
0
}
1464
1465
static int init_session_ticket(SSL_CONNECTION *s, unsigned int context)
1466
0
{
1467
0
    if (!s->server)
1468
0
        s->ext.ticket_expected = 0;
1469
1470
0
    return 1;
1471
0
}
1472
1473
#ifndef OPENSSL_NO_OCSP
1474
static int init_status_request(SSL_CONNECTION *s, unsigned int context)
1475
0
{
1476
0
    if (s->server) {
1477
0
        s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
1478
0
    } else {
1479
        /*
1480
         * Ensure we get sensible values passed to tlsext_status_cb in the event
1481
         * that we don't receive a status message
1482
         */
1483
0
        OPENSSL_free(s->ext.ocsp.resp);
1484
0
        s->ext.ocsp.resp = NULL;
1485
0
        s->ext.ocsp.resp_len = 0;
1486
1487
0
        sk_OCSP_RESPONSE_pop_free(s->ext.ocsp.resp_ex, OCSP_RESPONSE_free);
1488
0
        s->ext.ocsp.resp_ex = NULL;
1489
0
    }
1490
1491
0
    return 1;
1492
0
}
1493
#endif
1494
1495
#ifndef OPENSSL_NO_NEXTPROTONEG
1496
static int init_npn(SSL_CONNECTION *s, unsigned int context)
1497
0
{
1498
0
    s->s3.npn_seen = 0;
1499
1500
0
    return 1;
1501
0
}
1502
#endif
1503
1504
static int init_alpn(SSL_CONNECTION *s, unsigned int context)
1505
0
{
1506
0
    OPENSSL_free(s->s3.alpn_selected);
1507
0
    s->s3.alpn_selected = NULL;
1508
0
    s->s3.alpn_selected_len = 0;
1509
0
    if (s->server) {
1510
0
        OPENSSL_free(s->s3.alpn_proposed);
1511
0
        s->s3.alpn_proposed = NULL;
1512
0
        s->s3.alpn_proposed_len = 0;
1513
0
    }
1514
0
    return 1;
1515
0
}
1516
1517
static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent)
1518
0
{
1519
0
    if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
1520
0
        s->ext.early_data_ok = 0;
1521
1522
0
    if (!s->server || !SSL_CONNECTION_IS_VERSION13(s))
1523
0
        return 1;
1524
1525
    /*
1526
     * Call alpn_select callback if needed.  Has to be done after SNI and
1527
     * cipher negotiation (HTTP/2 restricts permitted ciphers). In (D)TLSv1.3
1528
     * we also have to do this before we decide whether to accept early_data.
1529
     * In (D)TLSv1.3 we've already negotiated our cipher so we do this call now.
1530
     * For < (D)TLSv1.3 we defer it until after cipher negotiation.
1531
     *
1532
     * On failure SSLfatal() already called.
1533
     */
1534
0
    return tls_handle_alpn(s);
1535
0
}
1536
1537
static int init_sig_algs(SSL_CONNECTION *s, unsigned int context)
1538
0
{
1539
    /* Clear any signature algorithms extension received */
1540
0
    OPENSSL_free(s->s3.tmp.peer_sigalgs);
1541
0
    s->s3.tmp.peer_sigalgs = NULL;
1542
0
    s->s3.tmp.peer_sigalgslen = 0;
1543
1544
0
    return 1;
1545
0
}
1546
1547
static int init_sig_algs_cert(SSL_CONNECTION *s,
1548
    ossl_unused unsigned int context)
1549
0
{
1550
    /* Clear any signature algorithms extension received */
1551
0
    OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);
1552
0
    s->s3.tmp.peer_cert_sigalgs = NULL;
1553
0
    s->s3.tmp.peer_cert_sigalgslen = 0;
1554
1555
0
    return 1;
1556
0
}
1557
1558
#ifndef OPENSSL_NO_SRP
1559
static int init_srp(SSL_CONNECTION *s, unsigned int context)
1560
0
{
1561
0
    OPENSSL_free(s->srp_ctx.login);
1562
0
    s->srp_ctx.login = NULL;
1563
1564
0
    return 1;
1565
0
}
1566
#endif
1567
1568
static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context)
1569
0
{
1570
0
    OPENSSL_free(s->ext.peer_ecpointformats);
1571
0
    s->ext.peer_ecpointformats = NULL;
1572
0
    s->ext.peer_ecpointformats_len = 0;
1573
1574
0
    return 1;
1575
0
}
1576
1577
static int init_etm(SSL_CONNECTION *s, unsigned int context)
1578
0
{
1579
0
    s->ext.use_etm = 0;
1580
1581
0
    return 1;
1582
0
}
1583
1584
static int init_ems(SSL_CONNECTION *s, unsigned int context)
1585
0
{
1586
0
    if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
1587
0
        s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
1588
0
        s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;
1589
0
    }
1590
1591
0
    return 1;
1592
0
}
1593
1594
static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent)
1595
0
{
1596
    /*
1597
     * Check extended master secret extension is not dropped on
1598
     * renegotiation.
1599
     */
1600
0
    if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
1601
0
        && (s->s3.flags & TLS1_FLAGS_REQUIRED_EXTMS)) {
1602
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1603
0
        return 0;
1604
0
    }
1605
0
    if (!s->server && s->hit) {
1606
        /*
1607
         * Check extended master secret extension is consistent with
1608
         * original session.
1609
         */
1610
0
        if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) != !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
1611
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1612
0
            return 0;
1613
0
        }
1614
0
    }
1615
1616
0
    return 1;
1617
0
}
1618
1619
static int init_certificate_authorities(SSL_CONNECTION *s, unsigned int context)
1620
0
{
1621
0
    sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
1622
0
    s->s3.tmp.peer_ca_names = NULL;
1623
0
    return 1;
1624
0
}
1625
1626
static EXT_RETURN tls_construct_certificate_authorities(SSL_CONNECTION *s,
1627
    WPACKET *pkt,
1628
    unsigned int context,
1629
    X509 *x,
1630
    size_t chainidx)
1631
0
{
1632
0
    const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);
1633
1634
0
    if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
1635
0
        return EXT_RETURN_NOT_SENT;
1636
1637
0
    if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)
1638
0
        || !WPACKET_start_sub_packet_u16(pkt)) {
1639
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1640
0
        return EXT_RETURN_FAIL;
1641
0
    }
1642
1643
0
    if (!construct_ca_names(s, ca_sk, pkt)) {
1644
        /* SSLfatal() already called */
1645
0
        return EXT_RETURN_FAIL;
1646
0
    }
1647
1648
0
    if (!WPACKET_close(pkt)) {
1649
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1650
0
        return EXT_RETURN_FAIL;
1651
0
    }
1652
1653
0
    return EXT_RETURN_SENT;
1654
0
}
1655
1656
static int tls_parse_certificate_authorities(SSL_CONNECTION *s, PACKET *pkt,
1657
    unsigned int context, X509 *x,
1658
    size_t chainidx)
1659
0
{
1660
0
    if (!parse_ca_names(s, pkt))
1661
0
        return 0;
1662
0
    if (PACKET_remaining(pkt) != 0) {
1663
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1664
0
        return 0;
1665
0
    }
1666
0
    return 1;
1667
0
}
1668
1669
#ifndef OPENSSL_NO_SRTP
1670
static int init_srtp(SSL_CONNECTION *s, unsigned int context)
1671
0
{
1672
0
    if (s->server)
1673
0
        s->srtp_profile = NULL;
1674
1675
0
    return 1;
1676
0
}
1677
#endif
1678
1679
static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent)
1680
0
{
1681
0
    if (!sent && SSL_CONNECTION_IS_VERSION13(s) && !s->hit) {
1682
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1683
0
            SSL_R_MISSING_SIGALGS_EXTENSION);
1684
0
        return 0;
1685
0
    }
1686
1687
0
    return 1;
1688
0
}
1689
1690
static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,
1691
    int sent)
1692
0
{
1693
0
    if (!sent && context == SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) {
1694
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1695
0
            SSL_R_MISSING_SUPPORTED_VERSIONS_EXTENSION);
1696
0
        return 0;
1697
0
    }
1698
1699
0
    return 1;
1700
0
}
1701
1702
static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent)
1703
0
{
1704
0
#if !(defined(OPENSSL_NO_TLS1_3) && defined(OPENSSL_NO_DTLS1_3))
1705
0
    if (!SSL_CONNECTION_IS_VERSION13(s))
1706
0
        return 1;
1707
1708
    /* Nothing to do for key_share in an HRR */
1709
0
    if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
1710
0
        return 1;
1711
1712
    /*
1713
     * If
1714
     *     we are a client
1715
     *     AND
1716
     *     we have no key_share
1717
     *     AND
1718
     *     (we are not resuming
1719
     *      OR the kex_mode doesn't allow non key_share resumes)
1720
     * THEN
1721
     *     fail;
1722
     */
1723
0
    if (!s->server
1724
0
        && !sent) {
1725
0
        if ((s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1726
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_SUITABLE_KEY_SHARE);
1727
0
            return 0;
1728
0
        }
1729
0
        if (!s->hit) {
1730
0
            SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_NO_SUITABLE_KEY_SHARE);
1731
0
            return 0;
1732
0
        }
1733
0
    }
1734
    /*
1735
     * IF
1736
     *     we are a server
1737
     * THEN
1738
     *     IF
1739
     *         we have a suitable key_share
1740
     *     THEN
1741
     *         IF
1742
     *             we are stateless AND we have no cookie
1743
     *         THEN
1744
     *             send a HelloRetryRequest
1745
     *     ELSE
1746
     *         IF
1747
     *             we didn't already send a HelloRetryRequest
1748
     *             AND
1749
     *             the client sent a key_share extension
1750
     *             AND
1751
     *             (we are not resuming
1752
     *              OR the kex_mode allows key_share resumes)
1753
     *             AND
1754
     *             a shared group exists
1755
     *         THEN
1756
     *             send a HelloRetryRequest
1757
     *         ELSE IF
1758
     *             we are not resuming
1759
     *             OR
1760
     *             the kex_mode doesn't allow non key_share resumes
1761
     *         THEN
1762
     *             fail
1763
     *         ELSE IF
1764
     *             we are stateless AND we have no cookie
1765
     *         THEN
1766
     *             send a HelloRetryRequest
1767
     */
1768
0
    if (s->server) {
1769
0
        if (s->s3.peer_tmp != NULL) {
1770
            /* We have a suitable key_share */
1771
0
            if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1772
0
                && !s->ext.cookieok) {
1773
0
                if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1774
                    /*
1775
                     * If we are stateless then we wouldn't know about any
1776
                     * previously sent HRR - so how can this be anything other
1777
                     * than 0?
1778
                     */
1779
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1780
0
                    return 0;
1781
0
                }
1782
0
                s->hello_retry_request = SSL_HRR_PENDING;
1783
0
                return 1;
1784
0
            }
1785
0
        } else {
1786
            /* No suitable key_share */
1787
0
            if (s->hello_retry_request == SSL_HRR_NONE && sent
1788
0
                && (!s->hit
1789
0
                    || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) != 0)) {
1790
1791
                /* Did we detect group overlap in tls_parse_ctos_key_share ? */
1792
0
                if (s->s3.group_id_candidate != 0) {
1793
                    /* A shared group exists so send a HelloRetryRequest */
1794
0
                    s->s3.group_id = s->s3.group_id_candidate;
1795
0
                    s->hello_retry_request = SSL_HRR_PENDING;
1796
0
                    return 1;
1797
0
                }
1798
0
            }
1799
0
            if (!s->hit
1800
0
                || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1801
                /* Nothing left we can do - just fail */
1802
0
                SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE : SSL_AD_MISSING_EXTENSION,
1803
0
                    SSL_R_NO_SUITABLE_KEY_SHARE);
1804
0
                return 0;
1805
0
            }
1806
1807
0
            if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1808
0
                && !s->ext.cookieok) {
1809
0
                if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1810
                    /*
1811
                     * If we are stateless then we wouldn't know about any
1812
                     * previously sent HRR - so how can this be anything other
1813
                     * than 0?
1814
                     */
1815
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1816
0
                    return 0;
1817
0
                }
1818
0
                s->hello_retry_request = SSL_HRR_PENDING;
1819
0
                return 1;
1820
0
            }
1821
0
        }
1822
1823
        /*
1824
         * We have a key_share so don't send any more HelloRetryRequest
1825
         * messages
1826
         */
1827
0
        if (s->hello_retry_request == SSL_HRR_PENDING)
1828
0
            s->hello_retry_request = SSL_HRR_COMPLETE;
1829
0
    } else {
1830
        /*
1831
         * For a client side resumption with no key_share we need to generate
1832
         * the handshake secret (otherwise this is done during key_share
1833
         * processing).
1834
         */
1835
0
        if (!sent && !tls13_generate_handshake_secret(s, NULL, 0)) {
1836
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1837
0
            return 0;
1838
0
        }
1839
0
    }
1840
0
#endif /* !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_DTLS1_3) */
1841
0
    return 1;
1842
0
}
1843
1844
static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context)
1845
0
{
1846
0
    s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1847
0
    return 1;
1848
0
}
1849
1850
int tls_psk_do_binder(SSL_CONNECTION *s, const EVP_MD *md,
1851
    const unsigned char *msgstart,
1852
    size_t binderoffset, const unsigned char *binderin,
1853
    unsigned char *binderout, SSL_SESSION *sess, int sign,
1854
    int external)
1855
0
{
1856
0
    EVP_PKEY *mackey = NULL;
1857
0
    EVP_MD_CTX *mctx = NULL;
1858
0
    unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1859
0
    unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1860
0
    unsigned char *early_secret;
1861
    /* ASCII: "res binder", in hex for EBCDIC compatibility */
1862
0
    static const unsigned char resumption_label[] = "\x72\x65\x73\x20\x62\x69\x6E\x64\x65\x72";
1863
    /* ASCII: "ext binder", in hex for EBCDIC compatibility */
1864
0
    static const unsigned char external_label[] = "\x65\x78\x74\x20\x62\x69\x6E\x64\x65\x72";
1865
0
    const unsigned char *label, *msgbodystart;
1866
0
    size_t bindersize, labelsize, hashsize, msgbodylen;
1867
0
    int hashsizei = EVP_MD_get_size(md);
1868
0
    int ret = -1;
1869
0
    int usepskfored = 0;
1870
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1871
0
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1872
1873
    /* Ensure cast to size_t is safe */
1874
0
    if (!ossl_assert(hashsizei > 0)) {
1875
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1876
0
        goto err;
1877
0
    }
1878
0
    hashsize = (size_t)hashsizei;
1879
1880
0
    if (external
1881
0
        && s->early_data_state == SSL_EARLY_DATA_CONNECTING
1882
0
        && sess == s->ext.early_data_session)
1883
0
        usepskfored = 1;
1884
1885
0
    if (external) {
1886
0
        label = external_label;
1887
0
        labelsize = sizeof(external_label) - 1;
1888
0
    } else {
1889
0
        label = resumption_label;
1890
0
        labelsize = sizeof(resumption_label) - 1;
1891
0
    }
1892
1893
    /*
1894
     * Generate the early_secret. On the server side we've selected a PSK to
1895
     * resume with (internal or external) so we always do this. On the client
1896
     * side we do this for a non-external (i.e. resumption) PSK or external PSK
1897
     * that will be used for early_data so that it is in place for sending early
1898
     * data. For client side external PSK not being used for early_data we
1899
     * generate it but store it away for later use.
1900
     */
1901
0
    if (s->server || !external || usepskfored)
1902
0
        early_secret = (unsigned char *)s->early_secret;
1903
0
    else
1904
0
        early_secret = (unsigned char *)sess->early_secret;
1905
1906
0
    if (!tls13_generate_secret(s, md, NULL, sess->master_key,
1907
0
            sess->master_key_length, early_secret)) {
1908
        /* SSLfatal() already called */
1909
0
        goto err;
1910
0
    }
1911
1912
    /*
1913
     * Create the handshake hash for the binder key...the messages so far are
1914
     * empty!
1915
     */
1916
0
    mctx = EVP_MD_CTX_new();
1917
0
    if (mctx == NULL
1918
0
        || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1919
0
        || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1920
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1921
0
        goto err;
1922
0
    }
1923
1924
    /* Generate the binder key */
1925
0
    if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,
1926
0
            hashsize, binderkey, hashsize, 1)) {
1927
        /* SSLfatal() already called */
1928
0
        goto err;
1929
0
    }
1930
1931
    /* Generate the finished key */
1932
0
    if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1933
        /* SSLfatal() already called */
1934
0
        goto err;
1935
0
    }
1936
1937
0
    if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
1938
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1939
0
        goto err;
1940
0
    }
1941
1942
    /*
1943
     * Get a hash of the ClientHello up to the start of the binders. If we are
1944
     * following a HelloRetryRequest then this includes the hash of the first
1945
     * ClientHello and the HelloRetryRequest itself.
1946
     */
1947
0
    if (s->hello_retry_request == SSL_HRR_PENDING) {
1948
0
        size_t hdatalen;
1949
0
        long hdatalen_l;
1950
0
        unsigned char *hdata;
1951
1952
0
#ifndef OPENSSL_NO_ECH
1953
        /* handle the hashing as per ECH needs (on client) */
1954
0
        if (s->ext.ech.attempted == 1 && s->ext.ech.ch_depth == 1) {
1955
0
            if (ossl_ech_intbuf_fetch(s, (unsigned char **)&hdata, &hdatalen) != 1) {
1956
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1957
0
                goto err;
1958
0
            }
1959
0
        } else {
1960
0
#endif
1961
0
            hdatalen = hdatalen_l = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
1962
0
            if (hdatalen_l <= 0) {
1963
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
1964
0
                goto err;
1965
0
            }
1966
0
#ifndef OPENSSL_NO_ECH
1967
0
        }
1968
0
#endif
1969
1970
0
        if (s->negotiated_version == DTLS1_3_VERSION) {
1971
0
            PACKET hashprefix, msg;
1972
0
            unsigned long dtlsbodylen;
1973
0
            unsigned int dtls_offset = DTLS1_HM_HEADER_LENGTH - SSL3_HM_HEADER_LENGTH;
1974
1975
            /*
1976
             * RFC 9147 states that for DTLS 1.3 all transcripts should be
1977
             * calculated without the message_seq, fragment_offset and
1978
             * fragment_length values. See Section 5.2
1979
             *
1980
             * Since the data is coming from handshake_buffer it hasn't
1981
             * been processed in ssl3_finish_mac where these values are
1982
             * removed. Therefore for both the server and client we will
1983
             * need to not supply them to the Digest Update
1984
             */
1985
0
            if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
1986
0
                || !PACKET_forward(&hashprefix, 1)
1987
0
                || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
1988
0
                || !PACKET_forward(&hashprefix, 1)
1989
0
                || !PACKET_get_net_3(&hashprefix, &dtlsbodylen)) {
1990
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1991
0
                goto err;
1992
0
            }
1993
1994
0
            hdatalen -= PACKET_remaining(&hashprefix);
1995
1996
0
            if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
1997
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1998
0
                goto err;
1999
0
            }
2000
2001
            /*
2002
             * Now skip the four bytes for the part of the DTLS header to not
2003
             * include in the transcript.
2004
             */
2005
0
            if (EVP_DigestUpdate(mctx, hdata + hdatalen + dtls_offset, dtlsbodylen) <= 0) {
2006
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2007
0
                goto err;
2008
0
            }
2009
0
        } else {
2010
            /*
2011
             * For servers the handshake buffer data will include the second
2012
             * ClientHello - which we don't want - so we need to take that bit off.
2013
             */
2014
0
            if (s->server) {
2015
0
                PACKET hashprefix, msg;
2016
2017
                /* Find how many bytes are left after the first two messages */
2018
0
                if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
2019
0
                    || !PACKET_forward(&hashprefix, 1)
2020
0
                    || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
2021
0
                    || !PACKET_forward(&hashprefix, 1)
2022
0
                    || !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
2023
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2024
0
                    goto err;
2025
0
                }
2026
0
                hdatalen -= PACKET_remaining(&hashprefix);
2027
0
            }
2028
2029
0
            if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
2030
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2031
0
                goto err;
2032
0
            }
2033
0
        }
2034
0
    }
2035
2036
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
2037
0
        msgbodystart = msgstart + DTLS1_HM_HEADER_LENGTH;
2038
0
        msgbodylen = binderoffset - DTLS1_HM_HEADER_LENGTH;
2039
0
    } else {
2040
0
        msgbodystart = msgstart + SSL3_HM_HEADER_LENGTH;
2041
0
        msgbodylen = binderoffset - SSL3_HM_HEADER_LENGTH;
2042
0
    }
2043
2044
    /*
2045
     * RFC9147 (DTLSv1.3)
2046
     * The transcript consists of complete TLS Handshake messages
2047
     * (reassembled as necessary). Note that this requires removing the
2048
     * message_seq, fragment_offset, and fragment_length fields to create
2049
     * the Handshake structure.
2050
     */
2051
0
    if (EVP_DigestUpdate(mctx, msgstart, SSL3_HM_HEADER_LENGTH) <= 0
2052
0
        || EVP_DigestUpdate(mctx, msgbodystart, msgbodylen) <= 0
2053
0
        || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
2054
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2055
0
        goto err;
2056
0
    }
2057
2058
0
    mackey = EVP_PKEY_new_raw_private_key_ex(sctx->libctx, "HMAC",
2059
0
        sctx->propq, finishedkey,
2060
0
        hashsize);
2061
0
    if (mackey == NULL) {
2062
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2063
0
        goto err;
2064
0
    }
2065
2066
0
    if (!sign)
2067
0
        binderout = tmpbinder;
2068
2069
0
    if (sctx->propq != NULL)
2070
0
        params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES,
2071
0
            (char *)sctx->propq, 0);
2072
0
    bindersize = hashsize;
2073
0
    if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), sctx->libctx,
2074
0
            sctx->propq, mackey, params)
2075
0
            <= 0
2076
0
        || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
2077
0
        || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
2078
0
        || bindersize != hashsize) {
2079
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2080
0
        goto err;
2081
0
    }
2082
2083
0
    if (sign) {
2084
0
        ret = 1;
2085
0
    } else {
2086
        /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
2087
0
        ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
2088
0
        if (!ret)
2089
0
            SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BINDER_DOES_NOT_VERIFY);
2090
0
    }
2091
2092
0
err:
2093
0
    OPENSSL_cleanse(binderkey, sizeof(binderkey));
2094
0
    OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
2095
0
    EVP_PKEY_free(mackey);
2096
0
    EVP_MD_CTX_free(mctx);
2097
0
    return ret;
2098
0
}
2099
2100
static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent)
2101
0
{
2102
0
    if (!sent)
2103
0
        return 1;
2104
2105
0
    if (!s->server) {
2106
0
        if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
2107
0
            && sent
2108
0
            && !s->ext.early_data_ok) {
2109
            /*
2110
             * If we get here then the server accepted our early_data but we
2111
             * later realised that it shouldn't have done (e.g. inconsistent
2112
             * ALPN)
2113
             */
2114
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EARLY_DATA);
2115
0
            return 0;
2116
0
        }
2117
2118
0
        return 1;
2119
0
    }
2120
2121
0
    if (s->max_early_data == 0
2122
0
        || !s->hit
2123
0
        || s->early_data_state != SSL_EARLY_DATA_ACCEPTING
2124
0
        || !s->ext.early_data_ok
2125
0
        || s->hello_retry_request != SSL_HRR_NONE
2126
0
        || (s->allow_early_data_cb != NULL
2127
0
            && !s->allow_early_data_cb(SSL_CONNECTION_GET_USER_SSL(s),
2128
0
                s->allow_early_data_cb_data))) {
2129
0
        s->ext.early_data = SSL_EARLY_DATA_REJECTED;
2130
0
    } else {
2131
0
        s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
2132
2133
0
        if (!tls13_change_cipher_state(s,
2134
0
                SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {
2135
            /* SSLfatal() already called */
2136
0
            return 0;
2137
0
        }
2138
0
    }
2139
2140
0
    return 1;
2141
0
}
2142
2143
static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,
2144
    int sent)
2145
0
{
2146
0
    if (s->session == NULL)
2147
0
        return 1;
2148
2149
    /* MaxFragmentLength defaults to disabled */
2150
0
    if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
2151
0
        s->session->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_DISABLED;
2152
2153
0
    if (USE_MAX_FRAGMENT_LENGTH_EXT(s->session)) {
2154
0
        s->rlayer.rrlmethod->set_max_frag_len(s->rlayer.rrl,
2155
0
            GET_MAX_FRAGMENT_LENGTH(s->session));
2156
0
        s->rlayer.wrlmethod->set_max_frag_len(s->rlayer.wrl,
2157
0
            ssl_get_max_send_fragment(s));
2158
0
    }
2159
2160
0
    return 1;
2161
0
}
2162
2163
static int init_post_handshake_auth(SSL_CONNECTION *s,
2164
    ossl_unused unsigned int context)
2165
0
{
2166
0
    s->post_handshake_auth = SSL_PHA_NONE;
2167
2168
0
    return 1;
2169
0
}
2170
2171
/*
2172
 * If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
2173
 * extension, servers MUST abort the handshake.
2174
 */
2175
static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent)
2176
0
{
2177
0
    if (s->server && sent && s->clienthello != NULL
2178
0
        && !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
2179
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
2180
0
            SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
2181
0
        return 0;
2182
0
    }
2183
2184
0
    return 1;
2185
0
}
2186
2187
static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context)
2188
0
{
2189
0
    memset(sc->ext.compress_certificate_from_peer, 0,
2190
0
        sizeof(sc->ext.compress_certificate_from_peer));
2191
0
    return 1;
2192
0
}
2193
2194
/* The order these are put into the packet imply a preference order: [brotli, zlib, zstd] */
2195
static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,
2196
    unsigned int context,
2197
    X509 *x, size_t chainidx)
2198
0
{
2199
#ifndef OPENSSL_NO_COMP_ALG
2200
    int i;
2201
2202
    if (!ossl_comp_has_alg(0))
2203
        return EXT_RETURN_NOT_SENT;
2204
2205
    /* Server: Don't attempt to compress a non-X509 (i.e. an RPK) */
2206
    if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509) {
2207
        sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
2208
        return EXT_RETURN_NOT_SENT;
2209
    }
2210
2211
    /* Client: If we sent a client cert-type extension, don't indicate compression */
2212
    if (!sc->server && sc->ext.client_cert_type_ctos) {
2213
        sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
2214
        return EXT_RETURN_NOT_SENT;
2215
    }
2216
2217
    /* Do not indicate we support receiving compressed certificates */
2218
    if ((sc->options & SSL_OP_NO_RX_CERTIFICATE_COMPRESSION) != 0)
2219
        return EXT_RETURN_NOT_SENT;
2220
2221
    if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
2222
        return EXT_RETURN_NOT_SENT;
2223
#ifndef OPENSSL_NO_ECH
2224
    ECH_SAME_EXT(sc, context, pkt);
2225
#endif
2226
2227
    if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_compress_certificate)
2228
        || !WPACKET_start_sub_packet_u16(pkt)
2229
        || !WPACKET_start_sub_packet_u8(pkt))
2230
        goto err;
2231
2232
    for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2233
        if (!WPACKET_put_bytes_u16(pkt, sc->cert_comp_prefs[i]))
2234
            goto err;
2235
    }
2236
    if (!WPACKET_close(pkt) || !WPACKET_close(pkt))
2237
        goto err;
2238
2239
    sc->ext.compress_certificate_sent = 1;
2240
    return EXT_RETURN_SENT;
2241
err:
2242
    SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2243
    return EXT_RETURN_FAIL;
2244
#else
2245
0
    return EXT_RETURN_NOT_SENT;
2246
0
#endif
2247
0
}
2248
2249
#ifndef OPENSSL_NO_COMP_ALG
2250
static int tls_comp_in_pref(SSL_CONNECTION *sc, int alg)
2251
{
2252
    int i;
2253
2254
    /* ossl_comp_has_alg() considers 0 as "any" */
2255
    if (alg == 0)
2256
        return 0;
2257
    /* Make sure algorithm is enabled */
2258
    if (!ossl_comp_has_alg(alg))
2259
        return 0;
2260
    /* If no preferences are set, it's ok */
2261
    if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
2262
        return 1;
2263
    /* Find the algorithm */
2264
    for (i = 0; i < TLSEXT_comp_cert_limit; i++)
2265
        if (sc->cert_comp_prefs[i] == alg)
2266
            return 1;
2267
    return 0;
2268
}
2269
#endif
2270
2271
int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt, unsigned int context,
2272
    X509 *x, size_t chainidx)
2273
0
{
2274
#ifndef OPENSSL_NO_COMP_ALG
2275
    PACKET supported_comp_algs;
2276
    unsigned int comp;
2277
    int already_set[TLSEXT_comp_cert_limit];
2278
    int j = 0;
2279
2280
    /* If no algorithms are available, ignore the extension */
2281
    if (!ossl_comp_has_alg(0))
2282
        return 1;
2283
2284
    /* Don't attempt to compress a non-X509 (i.e. an RPK) */
2285
    if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509)
2286
        return 1;
2287
    if (!sc->server && sc->ext.client_cert_type != TLSEXT_cert_type_x509)
2288
        return 1;
2289
2290
    /* Ignore the extension and don't send compressed certificates */
2291
    if ((sc->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
2292
        return 1;
2293
2294
    if (!PACKET_as_length_prefixed_1(pkt, &supported_comp_algs)
2295
        || PACKET_remaining(&supported_comp_algs) == 0) {
2296
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
2297
        return 0;
2298
    }
2299
2300
    memset(already_set, 0, sizeof(already_set));
2301
    /*
2302
     * The preference array has real values, so take a look at each
2303
     * value coming in, and make sure it's in our preference list
2304
     * The array is 0 (i.e. "none") terminated
2305
     * The preference list only contains supported algorithms
2306
     */
2307
    while (PACKET_get_net_2(&supported_comp_algs, &comp)) {
2308
        if (tls_comp_in_pref(sc, comp) && !already_set[comp]) {
2309
            sc->ext.compress_certificate_from_peer[j++] = comp;
2310
            already_set[comp] = 1;
2311
        }
2312
    }
2313
    if (PACKET_remaining(&supported_comp_algs) != 0) {
2314
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
2315
        return 0;
2316
    }
2317
#endif
2318
0
    return 1;
2319
0
}
2320
2321
static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context)
2322
0
{
2323
    /* Only reset when parsing client hello */
2324
0
    if (sc->server) {
2325
0
        sc->ext.server_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
2326
0
        sc->ext.server_cert_type = TLSEXT_cert_type_x509;
2327
0
    }
2328
0
    return 1;
2329
0
}
2330
2331
static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context)
2332
0
{
2333
    /* Only reset when parsing client hello */
2334
0
    if (sc->server) {
2335
0
        sc->ext.client_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
2336
0
        sc->ext.client_cert_type = TLSEXT_cert_type_x509;
2337
0
    }
2338
0
    return 1;
2339
0
}