Coverage Report

Created: 2026-11-16 07:12

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
    /*
1191
     * With ECH, the outer ClientHello reuses the custom extensions added
1192
     * to the inner one, so only reset their flags for the inner. That has
1193
     * to happen for every inner, as after a HelloRetryRequest the flags
1194
     * would still be set from the first ClientHello.
1195
     */
1196
0
    if ((context & SSL_EXT_CLIENT_HELLO) != 0
1197
0
        && (s->ext.ech.attempted == 0 || s->ext.ech.ch_depth == 1))
1198
        /* On the server side with initialise during ClientHello parsing */
1199
0
        custom_ext_init(&s->cert->custext);
1200
#else
1201
    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
1202
        /* On the server side with initialise during ClientHello parsing */
1203
        custom_ext_init(&s->cert->custext);
1204
#endif
1205
0
    if (!custom_ext_add(s, context, pkt, x, chainidx, max_version)) {
1206
        /* SSLfatal() already called */
1207
0
        return 0;
1208
0
    }
1209
1210
0
#ifndef OPENSSL_NO_ECH
1211
    /*
1212
     * Two passes if doing real ECH - we first construct the
1213
     * to-be-ECH-compressed extensions, and then go around again
1214
     * constructing those that aren't to be ECH-compressed. We
1215
     * need to ensure this ordering so that all the ECH-compressed
1216
     * extensions are contiguous in the encoding. The actual
1217
     * compression happens later in ech_encode_inner().
1218
     */
1219
0
    for (pass = 0; pass <= 1; pass++)
1220
0
#endif
1221
1222
0
        for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);
1223
0
            i++, thisexd++) {
1224
0
            EXT_RETURN (*construct)(SSL_CONNECTION *s, WPACKET *pkt,
1225
0
                unsigned int context,
1226
0
                X509 *x, size_t chainidx);
1227
0
            EXT_RETURN ret;
1228
1229
0
#ifndef OPENSSL_NO_ECH
1230
            /* do compressed in pass 0, non-compressed in pass 1 */
1231
0
            if (ossl_ech_2bcompressed((int)i) == pass)
1232
0
                continue;
1233
            /* stash index - needed for COMPRESS ECH handling */
1234
0
            s->ext.ech.ext_ind = (int)i;
1235
0
#endif
1236
            /* Skip if not relevant for our context */
1237
0
            if (!should_add_extension(s, thisexd->context, context, max_version))
1238
0
                continue;
1239
1240
0
            construct = s->server ? thisexd->construct_stoc
1241
0
                                  : thisexd->construct_ctos;
1242
1243
0
            if (construct == NULL)
1244
0
                continue;
1245
1246
0
            ret = construct(s, pkt, context, x, chainidx);
1247
0
            if (ret == EXT_RETURN_FAIL) {
1248
                /* SSLfatal() already called */
1249
0
                return 0;
1250
0
            }
1251
0
            if (ret == EXT_RETURN_SENT
1252
0
                && (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) != 0)
1253
0
                s->ext.extflags[i] |= SSL_EXT_FLAG_SENT;
1254
0
        }
1255
1256
0
#ifndef OPENSSL_NO_ECH
1257
    /*
1258
     * don't close yet if client in the middle of doing ECH, we'll
1259
     * eventually close this in ech_aad_and_encrypt() after we add
1260
     * the real ECH extension value
1261
     */
1262
0
    if (s->server
1263
0
        || context != SSL_EXT_CLIENT_HELLO
1264
0
        || s->ext.ech.attempted == 0
1265
0
        || s->ext.ech.ch_depth == 1
1266
0
        || s->ext.ech.grease == OSSL_ECH_IS_GREASE) {
1267
0
        if (!WPACKET_close(pkt)) {
1268
0
            if (!for_comp)
1269
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1270
0
            return 0;
1271
0
        }
1272
0
    }
1273
#else
1274
    if (!WPACKET_close(pkt)) {
1275
        if (!for_comp)
1276
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1277
        return 0;
1278
    }
1279
#endif
1280
0
    return 1;
1281
0
}
1282
1283
/*
1284
 * Built in extension finalisation and initialisation functions. All initialise
1285
 * or finalise the associated extension type for the given |context|. For
1286
 * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
1287
 * otherwise. These functions return 1 on success or 0 on failure.
1288
 */
1289
1290
static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent)
1291
0
{
1292
0
    if (!s->server) {
1293
        /*
1294
         * Check if we can connect to a server that doesn't support safe
1295
         * renegotiation
1296
         */
1297
0
        if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
1298
0
            && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
1299
0
            && !sent) {
1300
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1301
0
                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1302
0
            return 0;
1303
0
        }
1304
1305
0
        return 1;
1306
0
    }
1307
1308
    /* Need RI if renegotiating */
1309
0
    if (s->renegotiate
1310
0
        && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
1311
0
        && !sent) {
1312
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1313
0
            SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1314
0
        return 0;
1315
0
    }
1316
1317
0
    return 1;
1318
0
}
1319
1320
static ossl_inline void ssl_tsan_decr(const SSL_CTX *ctx,
1321
    TSAN_QUALIFIER int *stat)
1322
0
{
1323
0
    if (ssl_tsan_lock(ctx)) {
1324
0
        tsan_decr(stat);
1325
0
        ssl_tsan_unlock(ctx);
1326
0
    }
1327
0
}
1328
1329
static int init_server_name(SSL_CONNECTION *s, unsigned int context)
1330
0
{
1331
0
    if (s->server) {
1332
0
        s->servername_done = 0;
1333
1334
0
        OPENSSL_free(s->ext.hostname);
1335
0
        s->ext.hostname = NULL;
1336
0
    }
1337
1338
0
    return 1;
1339
0
}
1340
1341
#ifndef OPENSSL_NO_ECH
1342
/*
1343
 * Just note that ech is not yet done
1344
 * return 1 for good, 0 otherwise
1345
 */
1346
static int init_ech(SSL_CONNECTION *s, unsigned int context)
1347
0
{
1348
0
    const int nexts = OSSL_NELEM(ext_defs);
1349
1350
    /* we don't need this assert everywhere - anywhere is fine */
1351
0
    if (!ossl_assert(TLSEXT_IDX_num_builtins == nexts)) {
1352
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1353
0
        return 0;
1354
0
    }
1355
0
    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
1356
0
        s->ext.ech.done = 0;
1357
0
    return 1;
1358
0
}
1359
1360
static int final_ech(SSL_CONNECTION *s, unsigned int context, int sent)
1361
0
{
1362
0
    if (s->server && s->ext.ech.success == 1
1363
0
        && s->ext.ech.inner_ech_seen_ok != 1) {
1364
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_ECH_REQUIRED);
1365
0
        return 0;
1366
0
    }
1367
0
    return 1;
1368
0
}
1369
#endif /* OPENSSL_NO_ECH */
1370
1371
static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent)
1372
0
{
1373
0
    int ret = SSL_TLSEXT_ERR_NOACK;
1374
0
    int altmp = SSL_AD_UNRECOGNIZED_NAME;
1375
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1376
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1377
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1378
0
    int was_ticket = (SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0;
1379
1380
0
    if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {
1381
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1382
0
        return 0;
1383
0
    }
1384
1385
0
    if (sctx->ext.servername_cb != NULL)
1386
0
        ret = sctx->ext.servername_cb(ussl, &altmp,
1387
0
            sctx->ext.servername_arg);
1388
0
    else if (s->session_ctx->ext.servername_cb != NULL)
1389
0
        ret = s->session_ctx->ext.servername_cb(ussl, &altmp,
1390
0
            s->session_ctx->ext.servername_arg);
1391
1392
    /*
1393
     * For servers, propagate the SNI hostname from the temporary
1394
     * storage in the SSL to the persistent SSL_SESSION, now that we
1395
     * know we accepted it.
1396
     * Clients make this copy when parsing the server's response to
1397
     * the extension, which is when they find out that the negotiation
1398
     * was successful.
1399
     */
1400
0
    if (s->server) {
1401
0
        if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {
1402
            /* Only store the hostname in the session if we accepted it. */
1403
0
            OPENSSL_free(s->session->ext.hostname);
1404
0
            s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
1405
0
            if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {
1406
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1407
0
            }
1408
0
        }
1409
0
    }
1410
1411
    /*
1412
     * If we switched contexts (whether here or in the client_hello callback),
1413
     * move the sess_accept increment from the session_ctx to the new
1414
     * context, to avoid the confusing situation of having sess_accept_good
1415
     * exceed sess_accept (zero) for the new context.
1416
     */
1417
0
    if (SSL_IS_FIRST_HANDSHAKE(s) && sctx != s->session_ctx
1418
0
        && s->hello_retry_request == SSL_HRR_NONE) {
1419
0
        ssl_tsan_counter(sctx, &sctx->stats.sess_accept);
1420
0
        ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);
1421
0
    }
1422
1423
    /*
1424
     * If we're expecting to send a ticket, and tickets were previously enabled,
1425
     * and now tickets are disabled, then turn off expected ticket.
1426
     * Also, if this is not a resumption, create a new session ID
1427
     */
1428
0
    if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected
1429
0
        && was_ticket && (SSL_get_options(ssl) & SSL_OP_NO_TICKET) != 0) {
1430
0
        s->ext.ticket_expected = 0;
1431
0
        if (!s->hit) {
1432
0
            SSL_SESSION *ss = SSL_get_session(ssl);
1433
1434
0
            if (ss != NULL) {
1435
0
                OPENSSL_free(ss->ext.tick);
1436
0
                ss->ext.tick = NULL;
1437
0
                ss->ext.ticklen = 0;
1438
0
                ss->ext.tick_lifetime_hint = 0;
1439
0
                ss->ext.tick_age_add = 0;
1440
0
                if (!ssl_generate_session_id(s, ss)) {
1441
                    /* SSLfatal() already called */
1442
0
                    return 0;
1443
0
                }
1444
0
            } else {
1445
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1446
0
                return 0;
1447
0
            }
1448
0
        }
1449
0
    }
1450
1451
0
    switch (ret) {
1452
0
    case SSL_TLSEXT_ERR_ALERT_FATAL:
1453
0
        SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);
1454
0
        return 0;
1455
1456
0
    case SSL_TLSEXT_ERR_ALERT_WARNING:
1457
        /* (D)TLSv1.3 doesn't have warning alerts so we suppress this */
1458
0
        if (!SSL_CONNECTION_IS_VERSION13(s))
1459
0
            ssl3_send_alert(s, SSL3_AL_WARNING, altmp);
1460
0
        s->servername_done = 0;
1461
0
        return 1;
1462
1463
0
    case SSL_TLSEXT_ERR_NOACK:
1464
0
        s->servername_done = 0;
1465
0
        return 1;
1466
1467
0
    default:
1468
0
        return 1;
1469
0
    }
1470
0
}
1471
1472
static int init_session_ticket(SSL_CONNECTION *s, unsigned int context)
1473
0
{
1474
0
    if (!s->server)
1475
0
        s->ext.ticket_expected = 0;
1476
1477
0
    return 1;
1478
0
}
1479
1480
#ifndef OPENSSL_NO_OCSP
1481
static int init_status_request(SSL_CONNECTION *s, unsigned int context)
1482
0
{
1483
0
    if (s->server) {
1484
0
        s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
1485
0
    } else {
1486
        /*
1487
         * Ensure we get sensible values passed to tlsext_status_cb in the event
1488
         * that we don't receive a status message
1489
         */
1490
0
        OPENSSL_free(s->ext.ocsp.resp);
1491
0
        s->ext.ocsp.resp = NULL;
1492
0
        s->ext.ocsp.resp_len = 0;
1493
1494
0
        sk_OCSP_RESPONSE_pop_free(s->ext.ocsp.resp_ex, OCSP_RESPONSE_free);
1495
0
        s->ext.ocsp.resp_ex = NULL;
1496
0
    }
1497
1498
0
    return 1;
1499
0
}
1500
#endif
1501
1502
#ifndef OPENSSL_NO_NEXTPROTONEG
1503
static int init_npn(SSL_CONNECTION *s, unsigned int context)
1504
0
{
1505
0
    s->s3.npn_seen = 0;
1506
1507
0
    return 1;
1508
0
}
1509
#endif
1510
1511
static int init_alpn(SSL_CONNECTION *s, unsigned int context)
1512
0
{
1513
0
    OPENSSL_free(s->s3.alpn_selected);
1514
0
    s->s3.alpn_selected = NULL;
1515
0
    s->s3.alpn_selected_len = 0;
1516
0
    if (s->server) {
1517
0
        OPENSSL_free(s->s3.alpn_proposed);
1518
0
        s->s3.alpn_proposed = NULL;
1519
0
        s->s3.alpn_proposed_len = 0;
1520
0
    }
1521
0
    return 1;
1522
0
}
1523
1524
static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent)
1525
0
{
1526
0
    if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
1527
0
        s->ext.early_data_ok = 0;
1528
1529
0
    if (!s->server || !SSL_CONNECTION_IS_VERSION13(s))
1530
0
        return 1;
1531
1532
    /*
1533
     * Call alpn_select callback if needed.  Has to be done after SNI and
1534
     * cipher negotiation (HTTP/2 restricts permitted ciphers). In (D)TLSv1.3
1535
     * we also have to do this before we decide whether to accept early_data.
1536
     * In (D)TLSv1.3 we've already negotiated our cipher so we do this call now.
1537
     * For < (D)TLSv1.3 we defer it until after cipher negotiation.
1538
     *
1539
     * On failure SSLfatal() already called.
1540
     */
1541
0
    return tls_handle_alpn(s);
1542
0
}
1543
1544
static int init_sig_algs(SSL_CONNECTION *s, unsigned int context)
1545
0
{
1546
    /* Clear any signature algorithms extension received */
1547
0
    OPENSSL_free(s->s3.tmp.peer_sigalgs);
1548
0
    s->s3.tmp.peer_sigalgs = NULL;
1549
0
    s->s3.tmp.peer_sigalgslen = 0;
1550
1551
0
    return 1;
1552
0
}
1553
1554
static int init_sig_algs_cert(SSL_CONNECTION *s,
1555
    ossl_unused unsigned int context)
1556
0
{
1557
    /* Clear any signature algorithms extension received */
1558
0
    OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);
1559
0
    s->s3.tmp.peer_cert_sigalgs = NULL;
1560
0
    s->s3.tmp.peer_cert_sigalgslen = 0;
1561
1562
0
    return 1;
1563
0
}
1564
1565
#ifndef OPENSSL_NO_SRP
1566
static int init_srp(SSL_CONNECTION *s, unsigned int context)
1567
0
{
1568
0
    OPENSSL_free(s->srp_ctx.login);
1569
0
    s->srp_ctx.login = NULL;
1570
1571
0
    return 1;
1572
0
}
1573
#endif
1574
1575
static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context)
1576
0
{
1577
0
    OPENSSL_free(s->ext.peer_ecpointformats);
1578
0
    s->ext.peer_ecpointformats = NULL;
1579
0
    s->ext.peer_ecpointformats_len = 0;
1580
1581
0
    return 1;
1582
0
}
1583
1584
static int init_etm(SSL_CONNECTION *s, unsigned int context)
1585
0
{
1586
0
    s->ext.use_etm = 0;
1587
1588
0
    return 1;
1589
0
}
1590
1591
static int init_ems(SSL_CONNECTION *s, unsigned int context)
1592
0
{
1593
0
    if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
1594
0
        s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
1595
0
        s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;
1596
0
    }
1597
1598
0
    return 1;
1599
0
}
1600
1601
static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent)
1602
0
{
1603
    /*
1604
     * Check extended master secret extension is not dropped on
1605
     * renegotiation.
1606
     */
1607
0
    if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
1608
0
        && (s->s3.flags & TLS1_FLAGS_REQUIRED_EXTMS)) {
1609
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1610
0
        return 0;
1611
0
    }
1612
0
    if (!s->server && s->hit) {
1613
        /*
1614
         * Check extended master secret extension is consistent with
1615
         * original session.
1616
         */
1617
0
        if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) != !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
1618
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1619
0
            return 0;
1620
0
        }
1621
0
    }
1622
1623
0
    return 1;
1624
0
}
1625
1626
static int init_certificate_authorities(SSL_CONNECTION *s, unsigned int context)
1627
0
{
1628
0
    sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
1629
0
    s->s3.tmp.peer_ca_names = NULL;
1630
0
    return 1;
1631
0
}
1632
1633
static EXT_RETURN tls_construct_certificate_authorities(SSL_CONNECTION *s,
1634
    WPACKET *pkt,
1635
    unsigned int context,
1636
    X509 *x,
1637
    size_t chainidx)
1638
0
{
1639
0
    const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);
1640
1641
0
    if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
1642
0
        return EXT_RETURN_NOT_SENT;
1643
1644
0
    if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)
1645
0
        || !WPACKET_start_sub_packet_u16(pkt)) {
1646
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1647
0
        return EXT_RETURN_FAIL;
1648
0
    }
1649
1650
0
    if (!construct_ca_names(s, ca_sk, pkt)) {
1651
        /* SSLfatal() already called */
1652
0
        return EXT_RETURN_FAIL;
1653
0
    }
1654
1655
0
    if (!WPACKET_close(pkt)) {
1656
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1657
0
        return EXT_RETURN_FAIL;
1658
0
    }
1659
1660
0
    return EXT_RETURN_SENT;
1661
0
}
1662
1663
static int tls_parse_certificate_authorities(SSL_CONNECTION *s, PACKET *pkt,
1664
    unsigned int context, X509 *x,
1665
    size_t chainidx)
1666
0
{
1667
0
    if (!parse_ca_names(s, pkt))
1668
0
        return 0;
1669
0
    if (PACKET_remaining(pkt) != 0) {
1670
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1671
0
        return 0;
1672
0
    }
1673
0
    return 1;
1674
0
}
1675
1676
#ifndef OPENSSL_NO_SRTP
1677
static int init_srtp(SSL_CONNECTION *s, unsigned int context)
1678
0
{
1679
0
    if (s->server)
1680
0
        s->srtp_profile = NULL;
1681
1682
0
    return 1;
1683
0
}
1684
#endif
1685
1686
static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent)
1687
0
{
1688
0
    if (!sent && SSL_CONNECTION_IS_VERSION13(s) && !s->hit) {
1689
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1690
0
            SSL_R_MISSING_SIGALGS_EXTENSION);
1691
0
        return 0;
1692
0
    }
1693
1694
0
    return 1;
1695
0
}
1696
1697
static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,
1698
    int sent)
1699
0
{
1700
0
    if (!sent && context == SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) {
1701
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1702
0
            SSL_R_MISSING_SUPPORTED_VERSIONS_EXTENSION);
1703
0
        return 0;
1704
0
    }
1705
1706
0
    return 1;
1707
0
}
1708
1709
/* Is a HelloRetryRequest cookie required before the handshake can proceed? */
1710
int tls_hrr_cookie_required(const SSL_CONNECTION *s)
1711
0
{
1712
0
    if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0)
1713
0
        return 1;
1714
1715
0
    return SSL_CONNECTION_IS_DTLS(s)
1716
0
        && (s->options & SSL_OP_COOKIE_EXCHANGE) != 0;
1717
0
}
1718
1719
static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent)
1720
0
{
1721
0
#if !(defined(OPENSSL_NO_TLS1_3) && defined(OPENSSL_NO_DTLS1_3))
1722
0
    if (!SSL_CONNECTION_IS_VERSION13(s))
1723
0
        return 1;
1724
1725
    /* Nothing to do for key_share in an HRR */
1726
0
    if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
1727
0
        return 1;
1728
1729
    /*
1730
     * If
1731
     *     we are a client
1732
     *     AND
1733
     *     we have no key_share
1734
     *     AND
1735
     *     (we are not resuming
1736
     *      OR the kex_mode doesn't allow non key_share resumes)
1737
     * THEN
1738
     *     fail;
1739
     */
1740
0
    if (!s->server
1741
0
        && !sent) {
1742
        /*
1743
         * In a full handshake the ServerHello must carry a key_share, so its
1744
         * absence is a missing_extension alert (RFC 8446, sections 4.2.8
1745
         * and 6.2). Only when resuming may the server legitimately omit it,
1746
         * and then only if we offered psk_ke.
1747
         */
1748
0
        if (!s->hit) {
1749
0
            SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_NO_SUITABLE_KEY_SHARE);
1750
0
            return 0;
1751
0
        }
1752
0
        if ((s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1753
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_SUITABLE_KEY_SHARE);
1754
0
            return 0;
1755
0
        }
1756
0
    }
1757
    /*
1758
     * IF
1759
     *     we are a server
1760
     * THEN
1761
     *     IF
1762
     *         we have a suitable key_share
1763
     *     THEN
1764
     *         IF
1765
     *             a cookie is required AND we have no cookie
1766
     *         THEN
1767
     *             send a HelloRetryRequest
1768
     *     ELSE
1769
     *         IF
1770
     *             we didn't already send a HelloRetryRequest
1771
     *             AND
1772
     *             the client sent a key_share extension
1773
     *             AND
1774
     *             (we are not resuming
1775
     *              OR the kex_mode allows key_share resumes)
1776
     *             AND
1777
     *             a shared group exists
1778
     *         THEN
1779
     *             send a HelloRetryRequest
1780
     *         ELSE IF
1781
     *             we are not resuming
1782
     *             OR
1783
     *             the kex_mode doesn't allow non key_share resumes
1784
     *         THEN
1785
     *             fail
1786
     *         ELSE IF
1787
     *             a cookie is required AND we have no cookie
1788
     *         THEN
1789
     *             send a HelloRetryRequest
1790
     */
1791
0
    if (s->server) {
1792
        /*
1793
         * RFC 8446, section 9.2: a ClientHello containing a supported_groups
1794
         * extension MUST also contain a key_share extension, and vice versa
1795
         * (an empty KeyShare.client_shares vector is permitted).  Servers
1796
         * MUST abort the handshake with a missing_extension alert otherwise.
1797
         */
1798
0
        if (s->clienthello != NULL) {
1799
0
            const RAW_EXTENSION *groups = &s->clienthello->pre_proc_exts[TLSEXT_IDX_supported_groups];
1800
1801
0
            if ((sent != 0) != (groups->present != 0)) {
1802
0
                SSLfatal(s, SSL_AD_MISSING_EXTENSION,
1803
0
                    sent ? SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION
1804
0
                         : SSL_R_NO_SUITABLE_KEY_SHARE);
1805
0
                return 0;
1806
0
            }
1807
0
        }
1808
1809
0
        if (s->s3.peer_tmp != NULL) {
1810
            /* We have a suitable key_share */
1811
0
            if (tls_hrr_cookie_required(s) && !s->ext.cookieok) {
1812
0
                if (s->hello_retry_request != SSL_HRR_NONE) {
1813
                    /* We already sent an HRR and still have no valid cookie */
1814
0
                    SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COOKIE_MISMATCH);
1815
0
                    return 0;
1816
0
                }
1817
0
                s->hello_retry_request = SSL_HRR_PENDING;
1818
0
                return 1;
1819
0
            }
1820
0
        } else {
1821
            /* No suitable key_share */
1822
0
            if (s->hello_retry_request == SSL_HRR_NONE && sent
1823
0
                && (!s->hit
1824
0
                    || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) != 0)) {
1825
1826
                /* Did we detect group overlap in tls_parse_ctos_key_share ? */
1827
0
                if (s->s3.group_id_candidate != 0) {
1828
                    /* A shared group exists so send a HelloRetryRequest */
1829
0
                    s->s3.group_id = s->s3.group_id_candidate;
1830
0
                    s->hello_retry_request = SSL_HRR_PENDING;
1831
0
                    return 1;
1832
0
                }
1833
0
            }
1834
0
            if (!s->hit
1835
0
                || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1836
                /* Nothing left we can do - just fail */
1837
0
                SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE : SSL_AD_MISSING_EXTENSION,
1838
0
                    SSL_R_NO_SUITABLE_KEY_SHARE);
1839
0
                return 0;
1840
0
            }
1841
1842
0
            if (tls_hrr_cookie_required(s) && !s->ext.cookieok) {
1843
0
                if (s->hello_retry_request != SSL_HRR_NONE) {
1844
                    /* We already sent an HRR and still have no valid cookie */
1845
0
                    SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COOKIE_MISMATCH);
1846
0
                    return 0;
1847
0
                }
1848
0
                s->hello_retry_request = SSL_HRR_PENDING;
1849
0
                return 1;
1850
0
            }
1851
0
        }
1852
1853
        /*
1854
         * We have a key_share so don't send any more HelloRetryRequest
1855
         * messages
1856
         */
1857
0
        if (s->hello_retry_request == SSL_HRR_PENDING)
1858
0
            s->hello_retry_request = SSL_HRR_COMPLETE;
1859
0
    } else {
1860
        /*
1861
         * For a client side resumption with no key_share we need to generate
1862
         * the handshake secret (otherwise this is done during key_share
1863
         * processing).
1864
         */
1865
0
        if (!sent && !tls13_generate_handshake_secret(s, NULL, 0)) {
1866
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1867
0
            return 0;
1868
0
        }
1869
0
    }
1870
0
#endif /* !defined(OPENSSL_NO_TLS1_3) && !defined(OPENSSL_NO_DTLS1_3) */
1871
0
    return 1;
1872
0
}
1873
1874
static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context)
1875
0
{
1876
0
    s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1877
0
    return 1;
1878
0
}
1879
1880
int tls_psk_do_binder(SSL_CONNECTION *s, const EVP_MD *md,
1881
    const unsigned char *msgstart,
1882
    size_t binderoffset, const unsigned char *binderin,
1883
    unsigned char *binderout, SSL_SESSION *sess, int sign,
1884
    int external)
1885
0
{
1886
0
    EVP_PKEY *mackey = NULL;
1887
0
    EVP_MD_CTX *mctx = NULL;
1888
0
    unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1889
0
    unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1890
0
    unsigned char *early_secret;
1891
    /* ASCII: "res binder", in hex for EBCDIC compatibility */
1892
0
    static const unsigned char resumption_label[] = "\x72\x65\x73\x20\x62\x69\x6E\x64\x65\x72";
1893
    /* ASCII: "ext binder", in hex for EBCDIC compatibility */
1894
0
    static const unsigned char external_label[] = "\x65\x78\x74\x20\x62\x69\x6E\x64\x65\x72";
1895
0
    const unsigned char *label, *msgbodystart;
1896
0
    size_t bindersize, labelsize, hashsize, msgbodylen;
1897
0
    int hashsizei = EVP_MD_get_size(md);
1898
0
    int ret = -1;
1899
0
    int usepskfored = 0;
1900
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1901
0
    OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1902
1903
    /* Ensure cast to size_t is safe */
1904
0
    if (!ossl_assert(hashsizei > 0)) {
1905
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1906
0
        goto err;
1907
0
    }
1908
0
    hashsize = (size_t)hashsizei;
1909
1910
0
    if (external
1911
0
        && s->early_data_state == SSL_EARLY_DATA_CONNECTING
1912
0
        && sess == s->ext.early_data_session)
1913
0
        usepskfored = 1;
1914
1915
0
    if (external) {
1916
0
        label = external_label;
1917
0
        labelsize = sizeof(external_label) - 1;
1918
0
    } else {
1919
0
        label = resumption_label;
1920
0
        labelsize = sizeof(resumption_label) - 1;
1921
0
    }
1922
1923
    /*
1924
     * Generate the early_secret. On the server side we've selected a PSK to
1925
     * resume with (internal or external) so we always do this. On the client
1926
     * side we do this for a non-external (i.e. resumption) PSK or external PSK
1927
     * that will be used for early_data so that it is in place for sending early
1928
     * data. For client side external PSK not being used for early_data we
1929
     * generate it but store it away for later use.
1930
     */
1931
0
    if (s->server || !external || usepskfored)
1932
0
        early_secret = (unsigned char *)s->early_secret;
1933
0
    else
1934
0
        early_secret = (unsigned char *)sess->early_secret;
1935
1936
0
    if (!tls13_generate_secret(s, md, NULL, sess->master_key,
1937
0
            sess->master_key_length, early_secret)) {
1938
        /* SSLfatal() already called */
1939
0
        goto err;
1940
0
    }
1941
1942
    /*
1943
     * Client-only: record that this flight's first-offered PSK has derived
1944
     * s->early_secret, so the early-write key install can refuse to key 0-RTT
1945
     * off an underived (zero) secret. early_secret aliases s->early_secret
1946
     * exactly for the identity that 0-RTT is keyed on (the resumption PSK, or
1947
     * an external PSK selected for early data via usepskfored).
1948
     */
1949
0
    if (!s->server && early_secret == (unsigned char *)s->early_secret)
1950
0
        s->ext.early_secret_derived = 1;
1951
1952
    /*
1953
     * Create the handshake hash for the binder key...the messages so far are
1954
     * empty!
1955
     */
1956
0
    mctx = EVP_MD_CTX_new();
1957
0
    if (mctx == NULL
1958
0
        || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1959
0
        || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1960
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1961
0
        goto err;
1962
0
    }
1963
1964
    /* Generate the binder key */
1965
0
    if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,
1966
0
            hashsize, binderkey, hashsize, 1)) {
1967
        /* SSLfatal() already called */
1968
0
        goto err;
1969
0
    }
1970
1971
    /* Generate the finished key */
1972
0
    if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1973
        /* SSLfatal() already called */
1974
0
        goto err;
1975
0
    }
1976
1977
0
    if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
1978
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1979
0
        goto err;
1980
0
    }
1981
1982
    /*
1983
     * Get a hash of the ClientHello up to the start of the binders. If we are
1984
     * following a HelloRetryRequest then this includes the hash of the first
1985
     * ClientHello and the HelloRetryRequest itself.
1986
     */
1987
0
    if (s->hello_retry_request == SSL_HRR_PENDING) {
1988
0
        size_t hdatalen;
1989
0
        long hdatalen_l;
1990
0
        unsigned char *hdata;
1991
1992
0
#ifndef OPENSSL_NO_ECH
1993
        /* handle the hashing as per ECH needs (on client) */
1994
0
        if (s->ext.ech.attempted == 1 && s->ext.ech.ch_depth == 1) {
1995
0
            if (ossl_ech_intbuf_fetch(s, (unsigned char **)&hdata, &hdatalen) != 1) {
1996
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1997
0
                goto err;
1998
0
            }
1999
0
        } else {
2000
0
#endif
2001
0
            hdatalen = hdatalen_l = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
2002
0
            if (hdatalen_l <= 0) {
2003
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
2004
0
                goto err;
2005
0
            }
2006
0
#ifndef OPENSSL_NO_ECH
2007
0
        }
2008
0
#endif
2009
2010
0
        if (s->negotiated_version == DTLS1_3_VERSION) {
2011
0
            PACKET hashprefix, msg;
2012
0
            unsigned long dtlsbodylen;
2013
0
            unsigned int dtls_offset = DTLS1_HM_HEADER_LENGTH - SSL3_HM_HEADER_LENGTH;
2014
2015
            /*
2016
             * RFC 9147 states that for DTLS 1.3 all transcripts should be
2017
             * calculated without the message_seq, fragment_offset and
2018
             * fragment_length values. See Section 5.2
2019
             *
2020
             * Since the data is coming from handshake_buffer it hasn't
2021
             * been processed in ssl3_finish_mac where these values are
2022
             * removed. Therefore for both the server and client we will
2023
             * need to not supply them to the Digest Update
2024
             */
2025
0
            if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
2026
0
                || !PACKET_forward(&hashprefix, 1)
2027
0
                || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
2028
0
                || !PACKET_forward(&hashprefix, 1)
2029
0
                || !PACKET_get_net_3(&hashprefix, &dtlsbodylen)) {
2030
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2031
0
                goto err;
2032
0
            }
2033
2034
0
            hdatalen -= PACKET_remaining(&hashprefix);
2035
2036
0
            if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
2037
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2038
0
                goto err;
2039
0
            }
2040
2041
            /*
2042
             * Now skip the four bytes for the part of the DTLS header to not
2043
             * include in the transcript.
2044
             */
2045
0
            if (EVP_DigestUpdate(mctx, hdata + hdatalen + dtls_offset, dtlsbodylen) <= 0) {
2046
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2047
0
                goto err;
2048
0
            }
2049
0
        } else {
2050
            /*
2051
             * For servers the handshake buffer data will include the second
2052
             * ClientHello - which we don't want - so we need to take that bit off.
2053
             */
2054
0
            if (s->server) {
2055
0
                PACKET hashprefix, msg;
2056
2057
                /* Find how many bytes are left after the first two messages */
2058
0
                if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
2059
0
                    || !PACKET_forward(&hashprefix, 1)
2060
0
                    || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
2061
0
                    || !PACKET_forward(&hashprefix, 1)
2062
0
                    || !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
2063
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2064
0
                    goto err;
2065
0
                }
2066
0
                hdatalen -= PACKET_remaining(&hashprefix);
2067
0
            }
2068
2069
0
            if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
2070
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2071
0
                goto err;
2072
0
            }
2073
0
        }
2074
0
    }
2075
2076
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
2077
0
        msgbodystart = msgstart + DTLS1_HM_HEADER_LENGTH;
2078
0
        msgbodylen = binderoffset - DTLS1_HM_HEADER_LENGTH;
2079
0
    } else {
2080
0
        msgbodystart = msgstart + SSL3_HM_HEADER_LENGTH;
2081
0
        msgbodylen = binderoffset - SSL3_HM_HEADER_LENGTH;
2082
0
    }
2083
2084
    /*
2085
     * RFC9147 (DTLSv1.3)
2086
     * The transcript consists of complete TLS Handshake messages
2087
     * (reassembled as necessary). Note that this requires removing the
2088
     * message_seq, fragment_offset, and fragment_length fields to create
2089
     * the Handshake structure.
2090
     */
2091
0
    if (EVP_DigestUpdate(mctx, msgstart, SSL3_HM_HEADER_LENGTH) <= 0
2092
0
        || EVP_DigestUpdate(mctx, msgbodystart, msgbodylen) <= 0
2093
0
        || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
2094
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2095
0
        goto err;
2096
0
    }
2097
2098
0
    mackey = EVP_PKEY_new_raw_private_key_ex(sctx->libctx, "HMAC",
2099
0
        sctx->propq, finishedkey,
2100
0
        hashsize);
2101
0
    if (mackey == NULL) {
2102
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2103
0
        goto err;
2104
0
    }
2105
2106
0
    if (!sign)
2107
0
        binderout = tmpbinder;
2108
2109
0
    if (sctx->propq != NULL)
2110
0
        params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES,
2111
0
            (char *)sctx->propq, 0);
2112
0
    bindersize = hashsize;
2113
0
    if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), sctx->libctx,
2114
0
            sctx->propq, mackey, params)
2115
0
            <= 0
2116
0
        || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
2117
0
        || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
2118
0
        || bindersize != hashsize) {
2119
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2120
0
        goto err;
2121
0
    }
2122
2123
0
    if (sign) {
2124
0
        ret = 1;
2125
0
    } else {
2126
        /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
2127
0
        ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
2128
0
        if (!ret)
2129
0
            SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BINDER_DOES_NOT_VERIFY);
2130
0
    }
2131
2132
0
err:
2133
0
    OPENSSL_cleanse(binderkey, sizeof(binderkey));
2134
0
    OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
2135
0
    EVP_PKEY_free(mackey);
2136
0
    EVP_MD_CTX_free(mctx);
2137
0
    return ret;
2138
0
}
2139
2140
static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent)
2141
0
{
2142
0
    if (!sent)
2143
0
        return 1;
2144
2145
0
    if (!s->server) {
2146
0
        if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
2147
0
            && sent
2148
0
            && !s->ext.early_data_ok) {
2149
            /*
2150
             * If we get here then the server accepted our early_data but we
2151
             * later realised that it shouldn't have done (e.g. inconsistent
2152
             * ALPN)
2153
             */
2154
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EARLY_DATA);
2155
0
            return 0;
2156
0
        }
2157
2158
0
        return 1;
2159
0
    }
2160
2161
0
    if (s->max_early_data == 0
2162
0
        || !s->hit
2163
0
        || s->early_data_state != SSL_EARLY_DATA_ACCEPTING
2164
0
        || !s->ext.early_data_ok
2165
0
        || s->hello_retry_request != SSL_HRR_NONE
2166
0
        || (s->allow_early_data_cb != NULL
2167
0
            && !s->allow_early_data_cb(SSL_CONNECTION_GET_USER_SSL(s),
2168
0
                s->allow_early_data_cb_data))) {
2169
0
        s->ext.early_data = SSL_EARLY_DATA_REJECTED;
2170
0
    } else {
2171
0
        s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
2172
2173
0
        if (!tls13_change_cipher_state(s,
2174
0
                SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {
2175
            /* SSLfatal() already called */
2176
0
            return 0;
2177
0
        }
2178
0
    }
2179
2180
0
    return 1;
2181
0
}
2182
2183
static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,
2184
    int sent)
2185
0
{
2186
0
    if (s->session == NULL)
2187
0
        return 1;
2188
2189
    /* MaxFragmentLength defaults to disabled */
2190
0
    if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
2191
0
        s->session->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_DISABLED;
2192
2193
0
    if (USE_MAX_FRAGMENT_LENGTH_EXT(s->session)) {
2194
0
        s->rlayer.rrlmethod->set_max_frag_len(s->rlayer.rrl,
2195
0
            GET_MAX_FRAGMENT_LENGTH(s->session));
2196
0
        s->rlayer.wrlmethod->set_max_frag_len(s->rlayer.wrl,
2197
0
            ssl_get_max_send_fragment(s));
2198
0
    }
2199
2200
0
    return 1;
2201
0
}
2202
2203
static int init_post_handshake_auth(SSL_CONNECTION *s,
2204
    ossl_unused unsigned int context)
2205
0
{
2206
0
    s->post_handshake_auth = SSL_PHA_NONE;
2207
2208
0
    return 1;
2209
0
}
2210
2211
/*
2212
 * If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
2213
 * extension, servers MUST abort the handshake.
2214
 */
2215
static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent)
2216
0
{
2217
0
    if (s->server && sent && s->clienthello != NULL
2218
0
        && !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
2219
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
2220
0
            SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
2221
0
        return 0;
2222
0
    }
2223
2224
0
    return 1;
2225
0
}
2226
2227
static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context)
2228
0
{
2229
0
    memset(sc->ext.compress_certificate_from_peer, 0,
2230
0
        sizeof(sc->ext.compress_certificate_from_peer));
2231
0
    return 1;
2232
0
}
2233
2234
/* The order these are put into the packet imply a preference order: [brotli, zlib, zstd] */
2235
static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,
2236
    unsigned int context,
2237
    X509 *x, size_t chainidx)
2238
0
{
2239
#ifndef OPENSSL_NO_COMP_ALG
2240
    int i;
2241
2242
    if (!ossl_comp_has_alg(0))
2243
        return EXT_RETURN_NOT_SENT;
2244
2245
    /* Server: Don't attempt to compress a non-X509 (i.e. an RPK) */
2246
    if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509) {
2247
        sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
2248
        return EXT_RETURN_NOT_SENT;
2249
    }
2250
2251
    /* Client: If we sent a client cert-type extension, don't indicate compression */
2252
    if (!sc->server && sc->ext.client_cert_type_ctos) {
2253
        sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
2254
        return EXT_RETURN_NOT_SENT;
2255
    }
2256
2257
    /* Do not indicate we support receiving compressed certificates */
2258
    if ((sc->options & SSL_OP_NO_RX_CERTIFICATE_COMPRESSION) != 0)
2259
        return EXT_RETURN_NOT_SENT;
2260
2261
    if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
2262
        return EXT_RETURN_NOT_SENT;
2263
#ifndef OPENSSL_NO_ECH
2264
    ECH_SAME_EXT(sc, context, pkt);
2265
#endif
2266
2267
    if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_compress_certificate)
2268
        || !WPACKET_start_sub_packet_u16(pkt)
2269
        || !WPACKET_start_sub_packet_u8(pkt))
2270
        goto err;
2271
2272
    for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2273
        if (!WPACKET_put_bytes_u16(pkt, sc->cert_comp_prefs[i]))
2274
            goto err;
2275
    }
2276
    if (!WPACKET_close(pkt) || !WPACKET_close(pkt))
2277
        goto err;
2278
2279
    sc->ext.compress_certificate_sent = 1;
2280
    return EXT_RETURN_SENT;
2281
err:
2282
    SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2283
    return EXT_RETURN_FAIL;
2284
#else
2285
0
    return EXT_RETURN_NOT_SENT;
2286
0
#endif
2287
0
}
2288
2289
#ifndef OPENSSL_NO_COMP_ALG
2290
static int tls_comp_in_pref(SSL_CONNECTION *sc, int alg)
2291
{
2292
    int i;
2293
2294
    /* ossl_comp_has_alg() considers 0 as "any" */
2295
    if (alg == 0)
2296
        return 0;
2297
    /* Make sure algorithm is enabled */
2298
    if (!ossl_comp_has_alg(alg))
2299
        return 0;
2300
    /* If no preferences are set, it's ok */
2301
    if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
2302
        return 1;
2303
    /* Find the algorithm */
2304
    for (i = 0; i < TLSEXT_comp_cert_limit; i++)
2305
        if (sc->cert_comp_prefs[i] == alg)
2306
            return 1;
2307
    return 0;
2308
}
2309
#endif
2310
2311
int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt, unsigned int context,
2312
    X509 *x, size_t chainidx)
2313
0
{
2314
#ifndef OPENSSL_NO_COMP_ALG
2315
    PACKET supported_comp_algs;
2316
    unsigned int comp;
2317
    int already_set[TLSEXT_comp_cert_limit];
2318
    int j = 0;
2319
2320
    /* If no algorithms are available, ignore the extension */
2321
    if (!ossl_comp_has_alg(0))
2322
        return 1;
2323
2324
    /* Don't attempt to compress a non-X509 (i.e. an RPK) */
2325
    if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509)
2326
        return 1;
2327
    if (!sc->server && sc->ext.client_cert_type != TLSEXT_cert_type_x509)
2328
        return 1;
2329
2330
    /* Ignore the extension and don't send compressed certificates */
2331
    if ((sc->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
2332
        return 1;
2333
2334
    if (!PACKET_as_length_prefixed_1(pkt, &supported_comp_algs)
2335
        || PACKET_remaining(&supported_comp_algs) == 0) {
2336
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
2337
        return 0;
2338
    }
2339
2340
    memset(already_set, 0, sizeof(already_set));
2341
    /*
2342
     * The preference array has real values, so take a look at each
2343
     * value coming in, and make sure it's in our preference list
2344
     * The array is 0 (i.e. "none") terminated
2345
     * The preference list only contains supported algorithms
2346
     */
2347
    while (PACKET_get_net_2(&supported_comp_algs, &comp)) {
2348
        if (tls_comp_in_pref(sc, comp) && !already_set[comp]) {
2349
            sc->ext.compress_certificate_from_peer[j++] = comp;
2350
            already_set[comp] = 1;
2351
        }
2352
    }
2353
    if (PACKET_remaining(&supported_comp_algs) != 0) {
2354
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
2355
        return 0;
2356
    }
2357
#endif
2358
0
    return 1;
2359
0
}
2360
2361
static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context)
2362
0
{
2363
    /* Only reset when parsing client hello */
2364
0
    if (sc->server) {
2365
0
        sc->ext.server_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
2366
0
        sc->ext.server_cert_type = TLSEXT_cert_type_x509;
2367
0
    }
2368
0
    return 1;
2369
0
}
2370
2371
static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context)
2372
0
{
2373
    /* Only reset when parsing client hello */
2374
0
    if (sc->server) {
2375
0
        sc->ext.client_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
2376
0
        sc->ext.client_cert_type = TLSEXT_cert_type_x509;
2377
0
    }
2378
0
    return 1;
2379
0
}