Coverage Report

Created: 2025-06-24 07:26

/src/msquic/submodules/quictls/ssl/statem/extensions.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2016-2024 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 "../ssl_local.h"
19
#include "statem_local.h"
20
21
static int final_renegotiate(SSL *s, unsigned int context, int sent);
22
static int init_server_name(SSL *s, unsigned int context);
23
static int final_server_name(SSL *s, unsigned int context, int sent);
24
static int final_ec_pt_formats(SSL *s, unsigned int context, int sent);
25
static int init_session_ticket(SSL *s, unsigned int context);
26
#ifndef OPENSSL_NO_OCSP
27
static int init_status_request(SSL *s, unsigned int context);
28
#endif
29
#ifndef OPENSSL_NO_NEXTPROTONEG
30
static int init_npn(SSL *s, unsigned int context);
31
#endif
32
static int init_alpn(SSL *s, unsigned int context);
33
static int final_alpn(SSL *s, unsigned int context, int sent);
34
static int init_sig_algs_cert(SSL *s, unsigned int context);
35
static int init_sig_algs(SSL *s, unsigned int context);
36
static int init_certificate_authorities(SSL *s, unsigned int context);
37
static EXT_RETURN tls_construct_certificate_authorities(SSL *s, WPACKET *pkt,
38
                                                        unsigned int context,
39
                                                        X509 *x,
40
                                                        size_t chainidx);
41
static int tls_parse_certificate_authorities(SSL *s, PACKET *pkt,
42
                                             unsigned int context, X509 *x,
43
                                             size_t chainidx);
44
#ifndef OPENSSL_NO_SRP
45
static int init_srp(SSL *s, unsigned int context);
46
#endif
47
static int init_ec_point_formats(SSL *s, unsigned int context);
48
static int init_etm(SSL *s, unsigned int context);
49
static int init_ems(SSL *s, unsigned int context);
50
static int final_ems(SSL *s, unsigned int context, int sent);
51
static int init_psk_kex_modes(SSL *s, unsigned int context);
52
static int final_key_share(SSL *s, unsigned int context, int sent);
53
#ifndef OPENSSL_NO_SRTP
54
static int init_srtp(SSL *s, unsigned int context);
55
#endif
56
static int final_sig_algs(SSL *s, unsigned int context, int sent);
57
static int final_early_data(SSL *s, unsigned int context, int sent);
58
static int final_maxfragmentlen(SSL *s, unsigned int context, int sent);
59
static int init_post_handshake_auth(SSL *s, unsigned int context);
60
static int final_psk(SSL *s, unsigned int context, int sent);
61
#ifndef OPENSSL_NO_QUIC
62
static int init_quic_transport_params(SSL *s, unsigned int context);
63
static int final_quic_transport_params_draft(SSL *s, unsigned int context, int sent);
64
static int final_quic_transport_params(SSL *s, unsigned int context, int sent);
65
#endif
66
67
/* Structure to define a built-in extension */
68
typedef struct extensions_definition_st {
69
    /* The defined type for the extension */
70
    unsigned int type;
71
    /*
72
     * The context that this extension applies to, e.g. what messages and
73
     * protocol versions
74
     */
75
    unsigned int context;
76
    /*
77
     * Initialise extension before parsing. Always called for relevant contexts
78
     * even if extension not present
79
     */
80
    int (*init)(SSL *s, unsigned int context);
81
    /* Parse extension sent from client to server */
82
    int (*parse_ctos)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
83
                      size_t chainidx);
84
    /* Parse extension send from server to client */
85
    int (*parse_stoc)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
86
                      size_t chainidx);
87
    /* Construct extension sent from server to client */
88
    EXT_RETURN (*construct_stoc)(SSL *s, WPACKET *pkt, unsigned int context,
89
                                 X509 *x, size_t chainidx);
90
    /* Construct extension sent from client to server */
91
    EXT_RETURN (*construct_ctos)(SSL *s, WPACKET *pkt, unsigned int context,
92
                                 X509 *x, size_t chainidx);
93
    /*
94
     * Finalise extension after parsing. Always called where an extensions was
95
     * initialised even if the extension was not present. |sent| is set to 1 if
96
     * the extension was seen, or 0 otherwise.
97
     */
98
    int (*final)(SSL *s, unsigned int context, int sent);
99
} EXTENSION_DEFINITION;
100
101
/*
102
 * Definitions of all built-in extensions. NOTE: Changes in the number or order
103
 * of these extensions should be mirrored with equivalent changes to the
104
 * indexes ( TLSEXT_IDX_* ) defined in ssl_local.h.
105
 * Extensions should be added to test/ext_internal_test.c as well, as that
106
 * tests the ordering of the extensions.
107
 *
108
 * Each extension has an initialiser, a client and
109
 * server side parser and a finaliser. The initialiser is called (if the
110
 * extension is relevant to the given context) even if we did not see the
111
 * extension in the message that we received. The parser functions are only
112
 * called if we see the extension in the message. The finalisers are always
113
 * called if the initialiser was called.
114
 * There are also server and client side constructor functions which are always
115
 * called during message construction if the extension is relevant for the
116
 * given context.
117
 * The initialisation, parsing, finalisation and construction functions are
118
 * always called in the order defined in this list. Some extensions may depend
119
 * on others having been processed first, so the order of this list is
120
 * significant.
121
 * The extension context is defined by a series of flags which specify which
122
 * messages the extension is relevant to. These flags also specify whether the
123
 * extension is relevant to a particular protocol or protocol version.
124
 *
125
 * NOTE: WebSphere Application Server 7+ cannot handle empty extensions at
126
 * the end, keep these extensions before signature_algorithm.
127
 */
128
#define INVALID_EXTENSION { TLSEXT_TYPE_invalid, 0, NULL, NULL, NULL, NULL, NULL, NULL }
129
static const EXTENSION_DEFINITION ext_defs[] = {
130
    {
131
        TLSEXT_TYPE_renegotiate,
132
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
133
        | SSL_EXT_SSL3_ALLOWED | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
134
        NULL, tls_parse_ctos_renegotiate, tls_parse_stoc_renegotiate,
135
        tls_construct_stoc_renegotiate, tls_construct_ctos_renegotiate,
136
        final_renegotiate
137
    },
138
    {
139
        TLSEXT_TYPE_server_name,
140
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
141
        | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
142
        init_server_name,
143
        tls_parse_ctos_server_name, tls_parse_stoc_server_name,
144
        tls_construct_stoc_server_name, tls_construct_ctos_server_name,
145
        final_server_name
146
    },
147
    {
148
        TLSEXT_TYPE_max_fragment_length,
149
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
150
        | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
151
        NULL, tls_parse_ctos_maxfragmentlen, tls_parse_stoc_maxfragmentlen,
152
        tls_construct_stoc_maxfragmentlen, tls_construct_ctos_maxfragmentlen,
153
        final_maxfragmentlen
154
    },
155
#ifndef OPENSSL_NO_SRP
156
    {
157
        TLSEXT_TYPE_srp,
158
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
159
        init_srp, tls_parse_ctos_srp, NULL, NULL, tls_construct_ctos_srp, NULL
160
    },
161
#else
162
    INVALID_EXTENSION,
163
#endif
164
    {
165
        TLSEXT_TYPE_ec_point_formats,
166
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
167
        | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
168
        init_ec_point_formats, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,
169
        tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,
170
        final_ec_pt_formats
171
    },
172
    {
173
        /*
174
         * "supported_groups" is spread across several specifications.
175
         * It was originally specified as "elliptic_curves" in RFC 4492,
176
         * and broadened to include named FFDH groups by RFC 7919.
177
         * Both RFCs 4492 and 7919 do not include a provision for the server
178
         * to indicate to the client the complete list of groups supported
179
         * by the server, with the server instead just indicating the
180
         * selected group for this connection in the ServerKeyExchange
181
         * message.  TLS 1.3 adds a scheme for the server to indicate
182
         * to the client its list of supported groups in the
183
         * EncryptedExtensions message, but none of the relevant
184
         * specifications permit sending supported_groups in the ServerHello.
185
         * Nonetheless (possibly due to the close proximity to the
186
         * "ec_point_formats" extension, which is allowed in the ServerHello),
187
         * there are several servers that send this extension in the
188
         * ServerHello anyway.  Up to and including the 1.1.0 release,
189
         * we did not check for the presence of nonpermitted extensions,
190
         * so to avoid a regression, we must permit this extension in the
191
         * TLS 1.2 ServerHello as well.
192
         *
193
         * Note that there is no tls_parse_stoc_supported_groups function,
194
         * so we do not perform any additional parsing, validation, or
195
         * processing on the server's group list -- this is just a minimal
196
         * change to preserve compatibility with these misbehaving servers.
197
         */
198
        TLSEXT_TYPE_supported_groups,
199
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
200
        | SSL_EXT_TLS1_2_SERVER_HELLO,
201
        NULL, tls_parse_ctos_supported_groups, NULL,
202
        tls_construct_stoc_supported_groups,
203
        tls_construct_ctos_supported_groups, NULL
204
    },
205
    {
206
        TLSEXT_TYPE_session_ticket,
207
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
208
        | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
209
        init_session_ticket, tls_parse_ctos_session_ticket,
210
        tls_parse_stoc_session_ticket, tls_construct_stoc_session_ticket,
211
        tls_construct_ctos_session_ticket, NULL
212
    },
213
#ifndef OPENSSL_NO_OCSP
214
    {
215
        TLSEXT_TYPE_status_request,
216
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
217
        | SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
218
        init_status_request, tls_parse_ctos_status_request,
219
        tls_parse_stoc_status_request, tls_construct_stoc_status_request,
220
        tls_construct_ctos_status_request, NULL
221
    },
222
#else
223
    INVALID_EXTENSION,
224
#endif
225
#ifndef OPENSSL_NO_NEXTPROTONEG
226
    {
227
        TLSEXT_TYPE_next_proto_neg,
228
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
229
        | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
230
        init_npn, tls_parse_ctos_npn, tls_parse_stoc_npn,
231
        tls_construct_stoc_next_proto_neg, tls_construct_ctos_npn, NULL
232
    },
233
#else
234
    INVALID_EXTENSION,
235
#endif
236
    {
237
        /*
238
         * Must appear in this list after server_name so that finalisation
239
         * happens after server_name callbacks
240
         */
241
        TLSEXT_TYPE_application_layer_protocol_negotiation,
242
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
243
        | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
244
        init_alpn, tls_parse_ctos_alpn, tls_parse_stoc_alpn,
245
        tls_construct_stoc_alpn, tls_construct_ctos_alpn, final_alpn
246
    },
247
#ifndef OPENSSL_NO_SRTP
248
    {
249
        TLSEXT_TYPE_use_srtp,
250
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
251
        | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS | SSL_EXT_DTLS_ONLY,
252
        init_srtp, tls_parse_ctos_use_srtp, tls_parse_stoc_use_srtp,
253
        tls_construct_stoc_use_srtp, tls_construct_ctos_use_srtp, NULL
254
    },
255
#else
256
    INVALID_EXTENSION,
257
#endif
258
    {
259
        TLSEXT_TYPE_encrypt_then_mac,
260
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
261
        | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
262
        init_etm, tls_parse_ctos_etm, tls_parse_stoc_etm,
263
        tls_construct_stoc_etm, tls_construct_ctos_etm, NULL
264
    },
265
#ifndef OPENSSL_NO_CT
266
    {
267
        TLSEXT_TYPE_signed_certificate_timestamp,
268
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
269
        | SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
270
        NULL,
271
        /*
272
         * No server side support for this, but can be provided by a custom
273
         * extension. This is an exception to the rule that custom extensions
274
         * cannot override built in ones.
275
         */
276
        NULL, tls_parse_stoc_sct, NULL, tls_construct_ctos_sct,  NULL
277
    },
278
#else
279
    INVALID_EXTENSION,
280
#endif
281
    {
282
        TLSEXT_TYPE_extended_master_secret,
283
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
284
        | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
285
        init_ems, tls_parse_ctos_ems, tls_parse_stoc_ems,
286
        tls_construct_stoc_ems, tls_construct_ctos_ems, final_ems
287
    },
288
    {
289
        TLSEXT_TYPE_signature_algorithms_cert,
290
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
291
        init_sig_algs_cert, tls_parse_ctos_sig_algs_cert,
292
        tls_parse_ctos_sig_algs_cert,
293
        /* We do not generate signature_algorithms_cert at present. */
294
        NULL, NULL, NULL
295
    },
296
    {
297
        TLSEXT_TYPE_post_handshake_auth,
298
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY,
299
        init_post_handshake_auth,
300
        tls_parse_ctos_post_handshake_auth, NULL,
301
        NULL, tls_construct_ctos_post_handshake_auth,
302
        NULL,
303
    },
304
    {
305
        TLSEXT_TYPE_signature_algorithms,
306
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
307
        init_sig_algs, tls_parse_ctos_sig_algs,
308
        tls_parse_ctos_sig_algs, tls_construct_ctos_sig_algs,
309
        tls_construct_ctos_sig_algs, final_sig_algs
310
    },
311
    {
312
        TLSEXT_TYPE_supported_versions,
313
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
314
        | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY,
315
        NULL,
316
        /* Processed inline as part of version selection */
317
        NULL, tls_parse_stoc_supported_versions,
318
        tls_construct_stoc_supported_versions,
319
        tls_construct_ctos_supported_versions, NULL
320
    },
321
    {
322
        TLSEXT_TYPE_psk_kex_modes,
323
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS_IMPLEMENTATION_ONLY
324
        | SSL_EXT_TLS1_3_ONLY,
325
        init_psk_kex_modes, tls_parse_ctos_psk_kex_modes, NULL, NULL,
326
        tls_construct_ctos_psk_kex_modes, NULL
327
    },
328
    {
329
        /*
330
         * Must be in this list after supported_groups. We need that to have
331
         * been parsed before we do this one.
332
         */
333
        TLSEXT_TYPE_key_share,
334
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
335
        | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY
336
        | SSL_EXT_TLS1_3_ONLY,
337
        NULL, tls_parse_ctos_key_share, tls_parse_stoc_key_share,
338
        tls_construct_stoc_key_share, tls_construct_ctos_key_share,
339
        final_key_share
340
    },
341
    {
342
        /* Must be after key_share */
343
        TLSEXT_TYPE_cookie,
344
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
345
        | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
346
        NULL, tls_parse_ctos_cookie, tls_parse_stoc_cookie,
347
        tls_construct_stoc_cookie, tls_construct_ctos_cookie, NULL
348
    },
349
    {
350
        /*
351
         * Special unsolicited ServerHello extension only used when
352
         * SSL_OP_CRYPTOPRO_TLSEXT_BUG is set. We allow it in a ClientHello but
353
         * ignore it.
354
         */
355
        TLSEXT_TYPE_cryptopro_bug,
356
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
357
        | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
358
        NULL, NULL, NULL, tls_construct_stoc_cryptopro_bug, NULL, NULL
359
    },
360
    {
361
        TLSEXT_TYPE_early_data,
362
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
363
        | SSL_EXT_TLS1_3_NEW_SESSION_TICKET | SSL_EXT_TLS1_3_ONLY,
364
        NULL, tls_parse_ctos_early_data, tls_parse_stoc_early_data,
365
        tls_construct_stoc_early_data, tls_construct_ctos_early_data,
366
        final_early_data
367
    },
368
    {
369
        TLSEXT_TYPE_certificate_authorities,
370
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
371
        | SSL_EXT_TLS1_3_ONLY,
372
        init_certificate_authorities,
373
        tls_parse_certificate_authorities, tls_parse_certificate_authorities,
374
        tls_construct_certificate_authorities,
375
        tls_construct_certificate_authorities, NULL,
376
    },
377
#ifndef OPENSSL_NO_QUIC
378
    {
379
        TLSEXT_TYPE_quic_transport_parameters_draft,
380
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
381
        | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
382
        init_quic_transport_params,
383
        tls_parse_ctos_quic_transport_params_draft, tls_parse_stoc_quic_transport_params_draft,
384
        tls_construct_stoc_quic_transport_params_draft, tls_construct_ctos_quic_transport_params_draft,
385
        final_quic_transport_params_draft,
386
    },
387
    {
388
        TLSEXT_TYPE_quic_transport_parameters,
389
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
390
        | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
391
        init_quic_transport_params,
392
        tls_parse_ctos_quic_transport_params, tls_parse_stoc_quic_transport_params,
393
        tls_construct_stoc_quic_transport_params, tls_construct_ctos_quic_transport_params,
394
        final_quic_transport_params,
395
    },
396
#else
397
    INVALID_EXTENSION,
398
    INVALID_EXTENSION,
399
#endif
400
    {
401
        /* Must be immediately before pre_shared_key */
402
        TLSEXT_TYPE_padding,
403
        SSL_EXT_CLIENT_HELLO,
404
        NULL,
405
        /* We send this, but don't read it */
406
        NULL, NULL, NULL, tls_construct_ctos_padding, NULL
407
    },
408
    {
409
        /* Required by the TLSv1.3 spec to always be the last extension */
410
        TLSEXT_TYPE_psk,
411
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
412
        | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
413
        NULL, tls_parse_ctos_psk, tls_parse_stoc_psk, tls_construct_stoc_psk,
414
        tls_construct_ctos_psk, final_psk
415
    }
416
};
417
418
/* Returns a TLSEXT_TYPE for the given index */
419
unsigned int ossl_get_extension_type(size_t idx)
420
0
{
421
0
    size_t num_exts = OSSL_NELEM(ext_defs);
422
423
0
    if (idx >= num_exts)
424
0
        return TLSEXT_TYPE_out_of_range;
425
426
0
    return ext_defs[idx].type;
427
0
}
428
429
/* Check whether an extension's context matches the current context */
430
static int validate_context(SSL *s, unsigned int extctx, unsigned int thisctx)
431
44.5k
{
432
    /* Check we're allowed to use this extension in this context */
433
44.5k
    if ((thisctx & extctx) == 0)
434
0
        return 0;
435
436
44.5k
    if (SSL_IS_DTLS(s)) {
437
0
        if ((extctx & SSL_EXT_TLS_ONLY) != 0)
438
0
            return 0;
439
44.5k
    } else if ((extctx & SSL_EXT_DTLS_ONLY) != 0) {
440
0
        return 0;
441
0
    }
442
443
44.5k
    return 1;
444
44.5k
}
445
446
int tls_validate_all_contexts(SSL *s, unsigned int thisctx, RAW_EXTENSION *exts)
447
2.31k
{
448
2.31k
    size_t i, num_exts, builtin_num = OSSL_NELEM(ext_defs), offset;
449
2.31k
    RAW_EXTENSION *thisext;
450
2.31k
    unsigned int context;
451
2.31k
    ENDPOINT role = ENDPOINT_BOTH;
452
453
2.31k
    if ((thisctx & SSL_EXT_CLIENT_HELLO) != 0)
454
0
        role = ENDPOINT_SERVER;
455
2.31k
    else if ((thisctx & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
456
0
        role = ENDPOINT_CLIENT;
457
458
    /* Calculate the number of extensions in the extensions list */
459
2.31k
    num_exts = builtin_num + s->cert->custext.meths_count;
460
461
67.0k
    for (thisext = exts, i = 0; i < num_exts; i++, thisext++) {
462
64.7k
        if (!thisext->present)
463
60.0k
            continue;
464
465
4.62k
        if (i < builtin_num) {
466
4.62k
            context = ext_defs[i].context;
467
4.62k
        } else {
468
0
            custom_ext_method *meth = NULL;
469
470
0
            meth = custom_ext_find(&s->cert->custext, role, thisext->type,
471
0
                                   &offset);
472
0
            if (!ossl_assert(meth != NULL))
473
0
                return 0;
474
0
            context = meth->context;
475
0
        }
476
477
4.62k
        if (!validate_context(s, context, thisctx))
478
0
            return 0;
479
4.62k
    }
480
481
2.31k
    return 1;
482
2.31k
}
483
484
/*
485
 * Verify whether we are allowed to use the extension |type| in the current
486
 * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
487
 * indicate the extension is not allowed. If returning 1 then |*found| is set to
488
 * the definition for the extension we found.
489
 */
490
static int verify_extension(SSL *s, unsigned int context, unsigned int type,
491
                            custom_ext_methods *meths, RAW_EXTENSION *rawexlist,
492
                            RAW_EXTENSION **found)
493
39.8k
{
494
39.8k
    size_t i;
495
39.8k
    size_t builtin_num = OSSL_NELEM(ext_defs);
496
39.8k
    const EXTENSION_DEFINITION *thisext;
497
498
569k
    for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {
499
569k
        if (type == thisext->type) {
500
39.8k
            if (!validate_context(s, thisext->context, context))
501
0
                return 0;
502
503
39.8k
            *found = &rawexlist[i];
504
39.8k
            return 1;
505
39.8k
        }
506
569k
    }
507
508
    /* Check the custom extensions */
509
0
    if (meths != NULL) {
510
0
        size_t offset = 0;
511
0
        ENDPOINT role = ENDPOINT_BOTH;
512
0
        custom_ext_method *meth = NULL;
513
514
0
        if ((context & SSL_EXT_CLIENT_HELLO) != 0)
515
0
            role = ENDPOINT_SERVER;
516
0
        else if ((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
517
0
            role = ENDPOINT_CLIENT;
518
519
0
        meth = custom_ext_find(meths, role, type, &offset);
520
0
        if (meth != NULL) {
521
0
            if (!validate_context(s, meth->context, context))
522
0
                return 0;
523
0
            *found = &rawexlist[offset + builtin_num];
524
0
            return 1;
525
0
        }
526
0
    }
527
528
    /* Unknown extension. We allow it */
529
0
    *found = NULL;
530
0
    return 1;
531
0
}
532
533
/*
534
 * Check whether the context defined for an extension |extctx| means whether
535
 * the extension is relevant for the current context |thisctx| or not. Returns
536
 * 1 if the extension is relevant for this context, and 0 otherwise
537
 */
538
int extension_is_relevant(SSL *s, unsigned int extctx, unsigned int thisctx)
539
1.24M
{
540
1.24M
    int is_tls13;
541
542
    /*
543
     * For HRR we haven't selected the version yet but we know it will be
544
     * TLSv1.3
545
     */
546
1.24M
    if ((thisctx & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
547
0
        is_tls13 = 1;
548
1.24M
    else
549
1.24M
        is_tls13 = SSL_IS_TLS13(s);
550
551
1.24M
    if ((SSL_IS_DTLS(s)
552
1.24M
                && (extctx & SSL_EXT_TLS_IMPLEMENTATION_ONLY) != 0)
553
1.24M
            || (s->version == SSL3_VERSION
554
1.24M
                    && (extctx & SSL_EXT_SSL3_ALLOWED) == 0)
555
            /*
556
             * Note that SSL_IS_TLS13() means "TLS 1.3 has been negotiated",
557
             * which is never true when generating the ClientHello.
558
             * However, version negotiation *has* occurred by the time the
559
             * ClientHello extensions are being parsed.
560
             * Be careful to allow TLS 1.3-only extensions when generating
561
             * the ClientHello.
562
             */
563
1.24M
            || (is_tls13 && (extctx & SSL_EXT_TLS1_2_AND_BELOW_ONLY) != 0)
564
1.24M
            || (!is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0
565
1.23M
                && (thisctx & SSL_EXT_CLIENT_HELLO) == 0)
566
1.24M
            || (s->server && !is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0)
567
1.24M
            || (s->hit && (extctx & SSL_EXT_IGNORE_ON_RESUMPTION) != 0))
568
22.9k
        return 0;
569
1.22M
    return 1;
570
1.24M
}
571
572
/*
573
 * Gather a list of all the extensions from the data in |packet]. |context|
574
 * tells us which message this extension is for. The raw extension data is
575
 * stored in |*res| on success. We don't actually process the content of the
576
 * extensions yet, except to check their types. This function also runs the
577
 * initialiser functions for all known extensions if |init| is nonzero (whether
578
 * we have collected them or not). If successful the caller is responsible for
579
 * freeing the contents of |*res|.
580
 *
581
 * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
582
 * more than one extension of the same type in a ClientHello or ServerHello.
583
 * This function returns 1 if all extensions are unique and we have parsed their
584
 * types, and 0 if the extensions contain duplicates, could not be successfully
585
 * found, or an internal error occurred. We only check duplicates for
586
 * extensions that we know about. We ignore others.
587
 */
588
int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
589
                           RAW_EXTENSION **res, size_t *len, int init)
590
9.48k
{
591
9.48k
    PACKET extensions = *packet;
592
9.48k
    size_t i = 0;
593
9.48k
    size_t num_exts;
594
9.48k
    custom_ext_methods *exts = &s->cert->custext;
595
9.48k
    RAW_EXTENSION *raw_extensions = NULL;
596
9.48k
    const EXTENSION_DEFINITION *thisexd;
597
598
9.48k
    *res = NULL;
599
600
    /*
601
     * Initialise server side custom extensions. Client side is done during
602
     * construction of extensions for the ClientHello.
603
     */
604
9.48k
    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
605
2.55k
        custom_ext_init(&s->cert->custext);
606
607
9.48k
    num_exts = OSSL_NELEM(ext_defs) + (exts != NULL ? exts->meths_count : 0);
608
9.48k
    raw_extensions = OPENSSL_zalloc(num_exts * sizeof(*raw_extensions));
609
9.48k
    if (raw_extensions == NULL) {
610
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
611
0
        return 0;
612
0
    }
613
614
9.48k
    i = 0;
615
49.3k
    while (PACKET_remaining(&extensions) > 0) {
616
39.8k
        unsigned int type, idx;
617
39.8k
        PACKET extension;
618
39.8k
        RAW_EXTENSION *thisex;
619
620
39.8k
        if (!PACKET_get_net_2(&extensions, &type) ||
621
39.8k
            !PACKET_get_length_prefixed_2(&extensions, &extension)) {
622
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
623
0
            goto err;
624
0
        }
625
        /*
626
         * Verify this extension is allowed. We only check duplicates for
627
         * extensions that we recognise. We also have a special case for the
628
         * PSK extension, which must be the last one in the ClientHello.
629
         */
630
39.8k
        if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)
631
39.8k
                || (thisex != NULL && thisex->present == 1)
632
39.8k
                || (type == TLSEXT_TYPE_psk
633
39.8k
                    && (context & SSL_EXT_CLIENT_HELLO) != 0
634
39.8k
                    && PACKET_remaining(&extensions) != 0)) {
635
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
636
0
            goto err;
637
0
        }
638
39.8k
        idx = thisex - raw_extensions;
639
        /*-
640
         * Check that we requested this extension (if appropriate). Requests can
641
         * be sent in the ClientHello and CertificateRequest. Unsolicited
642
         * extensions can be sent in the NewSessionTicket. We only do this for
643
         * the built-in extensions. Custom extensions have a different but
644
         * similar check elsewhere.
645
         * Special cases:
646
         * - The HRR cookie extension is unsolicited
647
         * - The renegotiate extension is unsolicited (the client signals
648
         *   support via an SCSV)
649
         * - The signed_certificate_timestamp extension can be provided by a
650
         * custom extension or by the built-in version. We let the extension
651
         * itself handle unsolicited response checks.
652
         */
653
39.8k
        if (idx < OSSL_NELEM(ext_defs)
654
39.8k
                && (context & (SSL_EXT_CLIENT_HELLO
655
39.8k
                               | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
656
39.8k
                               | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) == 0
657
39.8k
                && type != TLSEXT_TYPE_cookie
658
39.8k
                && type != TLSEXT_TYPE_renegotiate
659
39.8k
                && type != TLSEXT_TYPE_signed_certificate_timestamp
660
39.8k
                && (s->ext.extflags[idx] & SSL_EXT_FLAG_SENT) == 0
661
#ifndef OPENSSL_NO_GOST
662
                && !((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0
663
                     && type == TLSEXT_TYPE_cryptopro_bug)
664
#endif
665
39.8k
                                                                ) {
666
0
            SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION,
667
0
                     SSL_R_UNSOLICITED_EXTENSION);
668
0
            goto err;
669
0
        }
670
39.8k
        if (thisex != NULL) {
671
39.8k
            thisex->data = extension;
672
39.8k
            thisex->present = 1;
673
39.8k
            thisex->type = type;
674
39.8k
            thisex->received_order = i++;
675
39.8k
            if (s->ext.debug_cb)
676
0
                s->ext.debug_cb(s, !s->server, thisex->type,
677
0
                                PACKET_data(&thisex->data),
678
0
                                PACKET_remaining(&thisex->data),
679
0
                                s->ext.debug_arg);
680
39.8k
        }
681
39.8k
    }
682
683
9.48k
    if (init) {
684
        /*
685
         * Initialise all known extensions relevant to this context,
686
         * whether we have found them or not
687
         */
688
274k
        for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs);
689
265k
             i++, thisexd++) {
690
265k
            if (thisexd->init != NULL && (thisexd->context & context) != 0
691
265k
                && extension_is_relevant(s, thisexd->context, context)
692
265k
                && !thisexd->init(s, context)) {
693
                /* SSLfatal() already called */
694
0
                goto err;
695
0
            }
696
265k
        }
697
9.48k
    }
698
699
9.48k
    *res = raw_extensions;
700
9.48k
    if (len != NULL)
701
2.55k
        *len = num_exts;
702
9.48k
    return 1;
703
704
0
 err:
705
0
    OPENSSL_free(raw_extensions);
706
0
    return 0;
707
9.48k
}
708
709
/*
710
 * Runs the parser for a given extension with index |idx|. |exts| contains the
711
 * list of all parsed extensions previously collected by
712
 * tls_collect_extensions(). The parser is only run if it is applicable for the
713
 * given |context| and the parser has not already been run. If this is for a
714
 * Certificate message, then we also provide the parser with the relevant
715
 * Certificate |x| and its position in the |chainidx| with 0 being the first
716
 * Certificate. Returns 1 on success or 0 on failure. If an extension is not
717
 * present this counted as success.
718
 */
719
int tls_parse_extension(SSL *s, TLSEXT_INDEX idx, int context,
720
                        RAW_EXTENSION *exts, X509 *x, size_t chainidx)
721
277k
{
722
277k
    RAW_EXTENSION *currext = &exts[idx];
723
277k
    int (*parser)(SSL *s, PACKET *pkt, unsigned int context, X509 *x,
724
277k
                  size_t chainidx) = NULL;
725
726
    /* Skip if the extension is not present */
727
277k
    if (!currext->present)
728
230k
        return 1;
729
730
    /* Skip if we've already parsed this extension */
731
47.3k
    if (currext->parsed)
732
9.97k
        return 1;
733
734
37.3k
    currext->parsed = 1;
735
736
37.3k
    if (idx < OSSL_NELEM(ext_defs)) {
737
        /* We are handling a built-in extension */
738
37.3k
        const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
739
740
        /* Check if extension is defined for our protocol. If not, skip */
741
37.3k
        if (!extension_is_relevant(s, extdef->context, context))
742
10.2k
            return 1;
743
744
27.1k
        parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
745
746
27.1k
        if (parser != NULL)
747
27.1k
            return parser(s, &currext->data, context, x, chainidx);
748
749
        /*
750
         * If the parser is NULL we fall through to the custom extension
751
         * processing
752
         */
753
27.1k
    }
754
755
    /* Parse custom extensions */
756
0
    return custom_ext_parse(s, context, currext->type,
757
0
                            PACKET_data(&currext->data),
758
0
                            PACKET_remaining(&currext->data),
759
0
                            x, chainidx);
760
37.3k
}
761
762
/*
763
 * Parse all remaining extensions that have not yet been parsed. Also calls the
764
 * finalisation for all extensions at the end if |fin| is nonzero, whether we
765
 * collected them or not. Returns 1 for success or 0 for failure. If we are
766
 * working on a Certificate message then we also pass the Certificate |x| and
767
 * its position in the |chainidx|, with 0 being the first certificate.
768
 */
769
int tls_parse_all_extensions(SSL *s, int context, RAW_EXTENSION *exts, X509 *x,
770
                             size_t chainidx, int fin)
771
9.48k
{
772
9.48k
    size_t i, numexts = OSSL_NELEM(ext_defs);
773
9.48k
    const EXTENSION_DEFINITION *thisexd;
774
775
    /* Calculate the number of extensions in the extensions list */
776
9.48k
    numexts += s->cert->custext.meths_count;
777
778
    /* Parse each extension in turn */
779
274k
    for (i = 0; i < numexts; i++) {
780
265k
        if (!tls_parse_extension(s, i, context, exts, x, chainidx)) {
781
            /* SSLfatal() already called */
782
0
            return 0;
783
0
        }
784
265k
    }
785
786
9.48k
    if (fin) {
787
        /*
788
         * Finalise all known extensions relevant to this context,
789
         * whether we have found them or not
790
         */
791
274k
        for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);
792
265k
             i++, thisexd++) {
793
265k
            if (thisexd->final != NULL && (thisexd->context & context) != 0
794
265k
                && !thisexd->final(s, context, exts[i].present)) {
795
                /* SSLfatal() already called */
796
0
                return 0;
797
0
            }
798
265k
        }
799
9.48k
    }
800
801
9.48k
    return 1;
802
9.48k
}
803
804
int should_add_extension(SSL *s, unsigned int extctx, unsigned int thisctx,
805
                         int max_version)
806
1.46M
{
807
    /* Skip if not relevant for our context */
808
1.46M
    if ((extctx & thisctx) == 0)
809
320k
        return 0;
810
811
    /* Check if this extension is defined for our protocol. If not, skip */
812
1.14M
    if (!extension_is_relevant(s, extctx, thisctx)
813
1.14M
            || ((extctx & SSL_EXT_TLS1_3_ONLY) != 0
814
1.14M
                && (thisctx & SSL_EXT_CLIENT_HELLO) != 0
815
1.14M
                && (SSL_IS_DTLS(s) || max_version < TLS1_3_VERSION)))
816
0
        return 0;
817
818
1.14M
    return 1;
819
1.14M
}
820
821
/*
822
 * Construct all the extensions relevant to the current |context| and write
823
 * them to |pkt|. If this is an extension for a Certificate in a Certificate
824
 * message, then |x| will be set to the Certificate we are handling, and
825
 * |chainidx| will indicate the position in the chainidx we are processing (with
826
 * 0 being the first in the chain). Returns 1 on success or 0 on failure. On a
827
 * failure construction stops at the first extension to fail to construct.
828
 */
829
int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
830
                             X509 *x, size_t chainidx)
831
52.2k
{
832
52.2k
    size_t i;
833
52.2k
    int min_version, max_version = 0, reason;
834
52.2k
    const EXTENSION_DEFINITION *thisexd;
835
836
52.2k
    if (!WPACKET_start_sub_packet_u16(pkt)
837
               /*
838
                * If extensions are of zero length then we don't even add the
839
                * extensions length bytes to a ClientHello/ServerHello
840
                * (for non-TLSv1.3).
841
                */
842
52.2k
            || ((context &
843
52.2k
                 (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO)) != 0
844
52.2k
                && !WPACKET_set_flags(pkt,
845
44.5k
                                     WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
846
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
847
0
        return 0;
848
0
    }
849
850
52.2k
    if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
851
44.5k
        reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
852
44.5k
        if (reason != 0) {
853
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
854
0
            return 0;
855
0
        }
856
44.5k
    }
857
858
    /* Add custom extensions first */
859
52.2k
    if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
860
        /* On the server side with initialise during ClientHello parsing */
861
44.5k
        custom_ext_init(&s->cert->custext);
862
44.5k
    }
863
52.2k
    if (!custom_ext_add(s, context, pkt, x, chainidx, max_version)) {
864
        /* SSLfatal() already called */
865
0
        return 0;
866
0
    }
867
868
1.51M
    for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
869
1.46M
        EXT_RETURN (*construct)(SSL *s, WPACKET *pkt, unsigned int context,
870
1.46M
                                X509 *x, size_t chainidx);
871
1.46M
        EXT_RETURN ret;
872
873
        /* Skip if not relevant for our context */
874
1.46M
        if (!should_add_extension(s, thisexd->context, context, max_version))
875
320k
            continue;
876
877
1.14M
        construct = s->server ? thisexd->construct_stoc
878
1.14M
                              : thisexd->construct_ctos;
879
880
1.14M
        if (construct == NULL)
881
89.0k
            continue;
882
883
1.05M
        ret = construct(s, pkt, context, x, chainidx);
884
1.05M
        if (ret == EXT_RETURN_FAIL) {
885
            /* SSLfatal() already called */
886
0
            return 0;
887
0
        }
888
1.05M
        if (ret == EXT_RETURN_SENT
889
1.05M
                && (context & (SSL_EXT_CLIENT_HELLO
890
544k
                               | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
891
544k
                               | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) != 0)
892
534k
            s->ext.extflags[i] |= SSL_EXT_FLAG_SENT;
893
1.05M
    }
894
895
52.2k
    if (!WPACKET_close(pkt)) {
896
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
897
0
        return 0;
898
0
    }
899
900
52.2k
    return 1;
901
52.2k
}
902
903
/*
904
 * Built in extension finalisation and initialisation functions. All initialise
905
 * or finalise the associated extension type for the given |context|. For
906
 * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
907
 * otherwise. These functions return 1 on success or 0 on failure.
908
 */
909
910
static int final_renegotiate(SSL *s, unsigned int context, int sent)
911
2.55k
{
912
2.55k
    if (!s->server) {
913
        /*
914
         * Check if we can connect to a server that doesn't support safe
915
         * renegotiation
916
         */
917
0
        if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
918
0
                && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
919
0
                && !sent) {
920
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
921
0
                     SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
922
0
            return 0;
923
0
        }
924
925
0
        return 1;
926
0
    }
927
928
    /* Need RI if renegotiating */
929
2.55k
    if (s->renegotiate
930
2.55k
            && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
931
2.55k
            && !sent) {
932
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
933
0
                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
934
0
        return 0;
935
0
    }
936
937
938
2.55k
    return 1;
939
2.55k
}
940
941
static ossl_inline void ssl_tsan_decr(const SSL_CTX *ctx,
942
                                      TSAN_QUALIFIER int *stat)
943
0
{
944
0
    if (ssl_tsan_lock(ctx)) {
945
0
        tsan_decr(stat);
946
0
        ssl_tsan_unlock(ctx);
947
0
    }
948
0
}
949
950
static int init_server_name(SSL *s, unsigned int context)
951
7.17k
{
952
7.17k
    if (s->server) {
953
2.55k
        s->servername_done = 0;
954
955
2.55k
        OPENSSL_free(s->ext.hostname);
956
2.55k
        s->ext.hostname = NULL;
957
2.55k
    }
958
959
7.17k
    return 1;
960
7.17k
}
961
962
static int final_server_name(SSL *s, unsigned int context, int sent)
963
4.86k
{
964
4.86k
    int ret = SSL_TLSEXT_ERR_NOACK;
965
4.86k
    int altmp = SSL_AD_UNRECOGNIZED_NAME;
966
4.86k
    int was_ticket = (SSL_get_options(s) & SSL_OP_NO_TICKET) == 0;
967
968
4.86k
    if (!ossl_assert(s->ctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {
969
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
970
0
        return 0;
971
0
    }
972
973
4.86k
    if (s->ctx->ext.servername_cb != NULL)
974
0
        ret = s->ctx->ext.servername_cb(s, &altmp,
975
0
                                        s->ctx->ext.servername_arg);
976
4.86k
    else if (s->session_ctx->ext.servername_cb != NULL)
977
0
        ret = s->session_ctx->ext.servername_cb(s, &altmp,
978
0
                                       s->session_ctx->ext.servername_arg);
979
980
    /*
981
     * For servers, propagate the SNI hostname from the temporary
982
     * storage in the SSL to the persistent SSL_SESSION, now that we
983
     * know we accepted it.
984
     * Clients make this copy when parsing the server's response to
985
     * the extension, which is when they find out that the negotiation
986
     * was successful.
987
     */
988
4.86k
    if (s->server) {
989
2.55k
        if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {
990
            /* Only store the hostname in the session if we accepted it. */
991
0
            OPENSSL_free(s->session->ext.hostname);
992
0
            s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
993
0
            if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {
994
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
995
0
            }
996
0
        }
997
2.55k
    }
998
999
    /*
1000
     * If we switched contexts (whether here or in the client_hello callback),
1001
     * move the sess_accept increment from the session_ctx to the new
1002
     * context, to avoid the confusing situation of having sess_accept_good
1003
     * exceed sess_accept (zero) for the new context.
1004
     */
1005
4.86k
    if (SSL_IS_FIRST_HANDSHAKE(s) && s->ctx != s->session_ctx
1006
4.86k
            && s->hello_retry_request == SSL_HRR_NONE) {
1007
0
        ssl_tsan_counter(s->ctx, &s->ctx->stats.sess_accept);
1008
0
        ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);
1009
0
    }
1010
1011
    /*
1012
     * If we're expecting to send a ticket, and tickets were previously enabled,
1013
     * and now tickets are disabled, then turn off expected ticket.
1014
     * Also, if this is not a resumption, create a new session ID
1015
     */
1016
4.86k
    if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected
1017
4.86k
            && was_ticket && (SSL_get_options(s) & SSL_OP_NO_TICKET) != 0) {
1018
0
        s->ext.ticket_expected = 0;
1019
0
        if (!s->hit) {
1020
0
            SSL_SESSION* ss = SSL_get_session(s);
1021
1022
0
            if (ss != NULL) {
1023
0
                OPENSSL_free(ss->ext.tick);
1024
0
                ss->ext.tick = NULL;
1025
0
                ss->ext.ticklen = 0;
1026
0
                ss->ext.tick_lifetime_hint = 0;
1027
0
                ss->ext.tick_age_add = 0;
1028
0
                if (!ssl_generate_session_id(s, ss)) {
1029
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1030
0
                    return 0;
1031
0
                }
1032
0
            } else {
1033
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1034
0
                return 0;
1035
0
            }
1036
0
        }
1037
0
    }
1038
1039
4.86k
    switch (ret) {
1040
0
    case SSL_TLSEXT_ERR_ALERT_FATAL:
1041
0
        SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);
1042
0
        return 0;
1043
1044
0
    case SSL_TLSEXT_ERR_ALERT_WARNING:
1045
        /* TLSv1.3 doesn't have warning alerts so we suppress this */
1046
0
        if (!SSL_IS_TLS13(s))
1047
0
            ssl3_send_alert(s, SSL3_AL_WARNING, altmp);
1048
0
        s->servername_done = 0;
1049
0
        return 1;
1050
1051
4.86k
    case SSL_TLSEXT_ERR_NOACK:
1052
4.86k
        s->servername_done = 0;
1053
4.86k
        return 1;
1054
1055
0
    default:
1056
0
        return 1;
1057
4.86k
    }
1058
4.86k
}
1059
1060
static int final_ec_pt_formats(SSL *s, unsigned int context, int sent)
1061
2.55k
{
1062
2.55k
    unsigned long alg_k, alg_a;
1063
1064
2.55k
    if (s->server)
1065
2.55k
        return 1;
1066
1067
0
    alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
1068
0
    alg_a = s->s3.tmp.new_cipher->algorithm_auth;
1069
1070
    /*
1071
     * If we are client and using an elliptic curve cryptography cipher
1072
     * suite, then if server returns an EC point formats lists extension it
1073
     * must contain uncompressed.
1074
     */
1075
0
    if (s->ext.ecpointformats != NULL
1076
0
            && s->ext.ecpointformats_len > 0
1077
0
            && s->ext.peer_ecpointformats != NULL
1078
0
            && s->ext.peer_ecpointformats_len > 0
1079
0
            && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
1080
        /* we are using an ECC cipher */
1081
0
        size_t i;
1082
0
        unsigned char *list = s->ext.peer_ecpointformats;
1083
1084
0
        for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {
1085
0
            if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
1086
0
                break;
1087
0
        }
1088
0
        if (i == s->ext.peer_ecpointformats_len) {
1089
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1090
0
                     SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
1091
0
            return 0;
1092
0
        }
1093
0
    }
1094
1095
0
    return 1;
1096
0
}
1097
1098
static int init_session_ticket(SSL *s, unsigned int context)
1099
4.86k
{
1100
4.86k
    if (!s->server)
1101
2.31k
        s->ext.ticket_expected = 0;
1102
1103
4.86k
    return 1;
1104
4.86k
}
1105
1106
#ifndef OPENSSL_NO_OCSP
1107
static int init_status_request(SSL *s, unsigned int context)
1108
7.17k
{
1109
7.17k
    if (s->server) {
1110
2.55k
        s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
1111
4.61k
    } else {
1112
        /*
1113
         * Ensure we get sensible values passed to tlsext_status_cb in the event
1114
         * that we don't receive a status message
1115
         */
1116
4.61k
        OPENSSL_free(s->ext.ocsp.resp);
1117
4.61k
        s->ext.ocsp.resp = NULL;
1118
4.61k
        s->ext.ocsp.resp_len = 0;
1119
4.61k
    }
1120
1121
7.17k
    return 1;
1122
7.17k
}
1123
#endif
1124
1125
#ifndef OPENSSL_NO_NEXTPROTONEG
1126
static int init_npn(SSL *s, unsigned int context)
1127
4.86k
{
1128
4.86k
    s->s3.npn_seen = 0;
1129
1130
4.86k
    return 1;
1131
4.86k
}
1132
#endif
1133
1134
static int init_alpn(SSL *s, unsigned int context)
1135
7.17k
{
1136
7.17k
    OPENSSL_free(s->s3.alpn_selected);
1137
7.17k
    s->s3.alpn_selected = NULL;
1138
7.17k
    s->s3.alpn_selected_len = 0;
1139
7.17k
    if (s->server) {
1140
2.55k
        OPENSSL_free(s->s3.alpn_proposed);
1141
2.55k
        s->s3.alpn_proposed = NULL;
1142
2.55k
        s->s3.alpn_proposed_len = 0;
1143
2.55k
    }
1144
7.17k
    return 1;
1145
7.17k
}
1146
1147
static int final_alpn(SSL *s, unsigned int context, int sent)
1148
4.86k
{
1149
4.86k
    if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
1150
0
            s->ext.early_data_ok = 0;
1151
1152
4.86k
    if (!s->server || !SSL_IS_TLS13(s))
1153
2.30k
        return 1;
1154
1155
    /*
1156
     * Call alpn_select callback if needed.  Has to be done after SNI and
1157
     * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
1158
     * we also have to do this before we decide whether to accept early_data.
1159
     * In TLSv1.3 we've already negotiated our cipher so we do this call now.
1160
     * For < TLSv1.3 we defer it until after cipher negotiation.
1161
     *
1162
     * On failure SSLfatal() already called.
1163
     */
1164
2.55k
    return tls_handle_alpn(s);
1165
4.86k
}
1166
1167
static int init_sig_algs(SSL *s, unsigned int context)
1168
2.55k
{
1169
    /* Clear any signature algorithms extension received */
1170
2.55k
    OPENSSL_free(s->s3.tmp.peer_sigalgs);
1171
2.55k
    s->s3.tmp.peer_sigalgs = NULL;
1172
2.55k
    s->s3.tmp.peer_sigalgslen = 0;
1173
1174
2.55k
    return 1;
1175
2.55k
}
1176
1177
static int init_sig_algs_cert(SSL *s, ossl_unused unsigned int context)
1178
2.55k
{
1179
    /* Clear any signature algorithms extension received */
1180
2.55k
    OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);
1181
2.55k
    s->s3.tmp.peer_cert_sigalgs = NULL;
1182
2.55k
    s->s3.tmp.peer_cert_sigalgslen = 0;
1183
1184
2.55k
    return 1;
1185
2.55k
}
1186
1187
#ifndef OPENSSL_NO_SRP
1188
static int init_srp(SSL *s, unsigned int context)
1189
{
1190
    OPENSSL_free(s->srp_ctx.login);
1191
    s->srp_ctx.login = NULL;
1192
1193
    return 1;
1194
}
1195
#endif
1196
1197
static int init_ec_point_formats(SSL *s, unsigned int context)
1198
4.86k
{
1199
4.86k
    OPENSSL_free(s->ext.peer_ecpointformats);
1200
4.86k
    s->ext.peer_ecpointformats = NULL;
1201
4.86k
    s->ext.peer_ecpointformats_len = 0;
1202
1203
4.86k
    return 1;
1204
4.86k
}
1205
1206
static int init_etm(SSL *s, unsigned int context)
1207
4.86k
{
1208
4.86k
    s->ext.use_etm = 0;
1209
1210
4.86k
    return 1;
1211
4.86k
}
1212
1213
static int init_ems(SSL *s, unsigned int context)
1214
4.86k
{
1215
4.86k
    if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
1216
0
        s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
1217
0
        s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;
1218
0
    }
1219
1220
4.86k
    return 1;
1221
4.86k
}
1222
1223
static int final_ems(SSL *s, unsigned int context, int sent)
1224
2.55k
{
1225
    /*
1226
     * Check extended master secret extension is not dropped on
1227
     * renegotiation.
1228
     */
1229
2.55k
    if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
1230
2.55k
        && (s->s3.flags & TLS1_FLAGS_REQUIRED_EXTMS)) {
1231
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1232
0
        return 0;
1233
0
    }
1234
2.55k
    if (!s->server && s->hit) {
1235
        /*
1236
         * Check extended master secret extension is consistent with
1237
         * original session.
1238
         */
1239
0
        if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
1240
0
            !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
1241
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1242
0
            return 0;
1243
0
        }
1244
0
    }
1245
1246
2.55k
    return 1;
1247
2.55k
}
1248
1249
static int init_certificate_authorities(SSL *s, unsigned int context)
1250
0
{
1251
0
    sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
1252
0
    s->s3.tmp.peer_ca_names = NULL;
1253
0
    return 1;
1254
0
}
1255
1256
static EXT_RETURN tls_construct_certificate_authorities(SSL *s, WPACKET *pkt,
1257
                                                        unsigned int context,
1258
                                                        X509 *x,
1259
                                                        size_t chainidx)
1260
44.5k
{
1261
44.5k
    const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);
1262
1263
44.5k
    if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
1264
44.5k
        return EXT_RETURN_NOT_SENT;
1265
1266
0
    if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)
1267
0
        || !WPACKET_start_sub_packet_u16(pkt)) {
1268
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1269
0
        return EXT_RETURN_FAIL;
1270
0
    }
1271
1272
0
    if (!construct_ca_names(s, ca_sk, pkt)) {
1273
        /* SSLfatal() already called */
1274
0
        return EXT_RETURN_FAIL;
1275
0
    }
1276
1277
0
    if (!WPACKET_close(pkt)) {
1278
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1279
0
        return EXT_RETURN_FAIL;
1280
0
    }
1281
1282
0
    return EXT_RETURN_SENT;
1283
0
}
1284
1285
static int tls_parse_certificate_authorities(SSL *s, PACKET *pkt,
1286
                                             unsigned int context, X509 *x,
1287
                                             size_t chainidx)
1288
0
{
1289
0
    if (!parse_ca_names(s, pkt))
1290
0
        return 0;
1291
0
    if (PACKET_remaining(pkt) != 0) {
1292
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1293
0
        return 0;
1294
0
    }
1295
0
    return 1;
1296
0
}
1297
1298
#ifndef OPENSSL_NO_SRTP
1299
static int init_srtp(SSL *s, unsigned int context)
1300
{
1301
    if (s->server)
1302
        s->srtp_profile = NULL;
1303
1304
    return 1;
1305
}
1306
#endif
1307
1308
static int final_sig_algs(SSL *s, unsigned int context, int sent)
1309
2.55k
{
1310
2.55k
    if (!sent && SSL_IS_TLS13(s) && !s->hit) {
1311
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1312
0
                 SSL_R_MISSING_SIGALGS_EXTENSION);
1313
0
        return 0;
1314
0
    }
1315
1316
2.55k
    return 1;
1317
2.55k
}
1318
1319
static int final_key_share(SSL *s, unsigned int context, int sent)
1320
4.86k
{
1321
4.86k
#if !defined(OPENSSL_NO_TLS1_3)
1322
4.86k
    if (!SSL_IS_TLS13(s))
1323
0
        return 1;
1324
1325
    /* Nothing to do for key_share in an HRR */
1326
4.86k
    if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
1327
0
        return 1;
1328
1329
    /*
1330
     * If
1331
     *     we are a client
1332
     *     AND
1333
     *     we have no key_share
1334
     *     AND
1335
     *     (we are not resuming
1336
     *      OR the kex_mode doesn't allow non key_share resumes)
1337
     * THEN
1338
     *     fail;
1339
     */
1340
4.86k
    if (!s->server
1341
4.86k
            && !sent
1342
4.86k
            && (!s->hit
1343
0
                || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0)) {
1344
        /* Nothing left we can do - just fail */
1345
0
        SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_NO_SUITABLE_KEY_SHARE);
1346
0
        return 0;
1347
0
    }
1348
    /*
1349
     * IF
1350
     *     we are a server
1351
     * THEN
1352
     *     IF
1353
     *         we have a suitable key_share
1354
     *     THEN
1355
     *         IF
1356
     *             we are stateless AND we have no cookie
1357
     *         THEN
1358
     *             send a HelloRetryRequest
1359
     *     ELSE
1360
     *         IF
1361
     *             we didn't already send a HelloRetryRequest
1362
     *             AND
1363
     *             the client sent a key_share extension
1364
     *             AND
1365
     *             (we are not resuming
1366
     *              OR the kex_mode allows key_share resumes)
1367
     *             AND
1368
     *             a shared group exists
1369
     *         THEN
1370
     *             send a HelloRetryRequest
1371
     *         ELSE IF
1372
     *             we are not resuming
1373
     *             OR
1374
     *             the kex_mode doesn't allow non key_share resumes
1375
     *         THEN
1376
     *             fail
1377
     *         ELSE IF
1378
     *             we are stateless AND we have no cookie
1379
     *         THEN
1380
     *             send a HelloRetryRequest
1381
     */
1382
4.86k
    if (s->server) {
1383
2.55k
        if (s->s3.peer_tmp != NULL) {
1384
            /* We have a suitable key_share */
1385
2.55k
            if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1386
2.55k
                    && !s->ext.cookieok) {
1387
0
                if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1388
                    /*
1389
                     * If we are stateless then we wouldn't know about any
1390
                     * previously sent HRR - so how can this be anything other
1391
                     * than 0?
1392
                     */
1393
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1394
0
                    return 0;
1395
0
                }
1396
0
                s->hello_retry_request = SSL_HRR_PENDING;
1397
0
                return 1;
1398
0
            }
1399
2.55k
        } else {
1400
            /* No suitable key_share */
1401
0
            if (s->hello_retry_request == SSL_HRR_NONE && sent
1402
0
                    && (!s->hit
1403
0
                        || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE)
1404
0
                           != 0)) {
1405
0
                const uint16_t *pgroups, *clntgroups;
1406
0
                size_t num_groups, clnt_num_groups, i;
1407
0
                unsigned int group_id = 0;
1408
1409
                /* Check if a shared group exists */
1410
1411
                /* Get the clients list of supported groups. */
1412
0
                tls1_get_peer_groups(s, &clntgroups, &clnt_num_groups);
1413
0
                tls1_get_supported_groups(s, &pgroups, &num_groups);
1414
1415
                /*
1416
                 * Find the first group we allow that is also in client's list
1417
                 */
1418
0
                for (i = 0; i < num_groups; i++) {
1419
0
                    group_id = pgroups[i];
1420
1421
0
                    if (check_in_list(s, group_id, clntgroups, clnt_num_groups,
1422
0
                                      1)
1423
0
                            && tls_group_allowed(s, group_id,
1424
0
                                                 SSL_SECOP_CURVE_SUPPORTED)
1425
0
                            && tls_valid_group(s, group_id, TLS1_3_VERSION,
1426
0
                                               TLS1_3_VERSION, 0, NULL))
1427
0
                        break;
1428
0
                }
1429
1430
0
                if (i < num_groups) {
1431
                    /* A shared group exists so send a HelloRetryRequest */
1432
0
                    s->s3.group_id = group_id;
1433
0
                    s->hello_retry_request = SSL_HRR_PENDING;
1434
0
                    return 1;
1435
0
                }
1436
0
            }
1437
0
            if (!s->hit
1438
0
                    || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1439
                /* Nothing left we can do - just fail */
1440
0
                SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE
1441
0
                                 : SSL_AD_MISSING_EXTENSION,
1442
0
                         SSL_R_NO_SUITABLE_KEY_SHARE);
1443
0
                return 0;
1444
0
            }
1445
1446
0
            if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1447
0
                    && !s->ext.cookieok) {
1448
0
                if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1449
                    /*
1450
                     * If we are stateless then we wouldn't know about any
1451
                     * previously sent HRR - so how can this be anything other
1452
                     * than 0?
1453
                     */
1454
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1455
0
                    return 0;
1456
0
                }
1457
0
                s->hello_retry_request = SSL_HRR_PENDING;
1458
0
                return 1;
1459
0
            }
1460
0
        }
1461
1462
        /*
1463
         * We have a key_share so don't send any more HelloRetryRequest
1464
         * messages
1465
         */
1466
2.55k
        if (s->hello_retry_request == SSL_HRR_PENDING)
1467
0
            s->hello_retry_request = SSL_HRR_COMPLETE;
1468
2.55k
    } else {
1469
        /*
1470
         * For a client side resumption with no key_share we need to generate
1471
         * the handshake secret (otherwise this is done during key_share
1472
         * processing).
1473
         */
1474
2.31k
        if (!sent && !tls13_generate_handshake_secret(s, NULL, 0)) {
1475
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1476
0
            return 0;
1477
0
        }
1478
2.31k
    }
1479
4.86k
#endif /* !defined(OPENSSL_NO_TLS1_3) */
1480
4.86k
    return 1;
1481
4.86k
}
1482
1483
static int init_psk_kex_modes(SSL *s, unsigned int context)
1484
0
{
1485
0
    s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1486
0
    return 1;
1487
0
}
1488
1489
int tls_psk_do_binder(SSL *s, const EVP_MD *md, const unsigned char *msgstart,
1490
                      size_t binderoffset, const unsigned char *binderin,
1491
                      unsigned char *binderout, SSL_SESSION *sess, int sign,
1492
                      int external)
1493
0
{
1494
0
    EVP_PKEY *mackey = NULL;
1495
0
    EVP_MD_CTX *mctx = NULL;
1496
0
    unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1497
0
    unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1498
0
    unsigned char *early_secret;
1499
    /* ASCII: "res binder", in hex for EBCDIC compatibility */
1500
0
    static const unsigned char resumption_label[] = "\x72\x65\x73\x20\x62\x69\x6E\x64\x65\x72";
1501
    /* ASCII: "ext binder", in hex for EBCDIC compatibility */
1502
0
    static const unsigned char external_label[] = "\x65\x78\x74\x20\x62\x69\x6E\x64\x65\x72";
1503
0
    const unsigned char *label;
1504
0
    size_t bindersize, labelsize, hashsize;
1505
0
    int hashsizei = EVP_MD_get_size(md);
1506
0
    int ret = -1;
1507
0
    int usepskfored = 0;
1508
1509
    /* Ensure cast to size_t is safe */
1510
0
    if (!ossl_assert(hashsizei >= 0)) {
1511
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1512
0
        goto err;
1513
0
    }
1514
0
    hashsize = (size_t)hashsizei;
1515
1516
0
    if (external
1517
0
            && s->early_data_state == SSL_EARLY_DATA_CONNECTING
1518
0
            && s->session->ext.max_early_data == 0
1519
0
            && sess->ext.max_early_data > 0)
1520
0
        usepskfored = 1;
1521
1522
0
    if (external) {
1523
0
        label = external_label;
1524
0
        labelsize = sizeof(external_label) - 1;
1525
0
    } else {
1526
0
        label = resumption_label;
1527
0
        labelsize = sizeof(resumption_label) - 1;
1528
0
    }
1529
1530
    /*
1531
     * Generate the early_secret. On the server side we've selected a PSK to
1532
     * resume with (internal or external) so we always do this. On the client
1533
     * side we do this for a non-external (i.e. resumption) PSK or external PSK
1534
     * that will be used for early_data so that it is in place for sending early
1535
     * data. For client side external PSK not being used for early_data we
1536
     * generate it but store it away for later use.
1537
     */
1538
0
    if (s->server || !external || usepskfored)
1539
0
        early_secret = (unsigned char *)s->early_secret;
1540
0
    else
1541
0
        early_secret = (unsigned char *)sess->early_secret;
1542
1543
0
    if (!tls13_generate_secret(s, md, NULL, sess->master_key,
1544
0
                               sess->master_key_length, early_secret)) {
1545
        /* SSLfatal() already called */
1546
0
        goto err;
1547
0
    }
1548
1549
    /*
1550
     * Create the handshake hash for the binder key...the messages so far are
1551
     * empty!
1552
     */
1553
0
    mctx = EVP_MD_CTX_new();
1554
0
    if (mctx == NULL
1555
0
            || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1556
0
            || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1557
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1558
0
        goto err;
1559
0
    }
1560
1561
    /* Generate the binder key */
1562
0
    if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,
1563
0
                           hashsize, binderkey, hashsize, 1)) {
1564
        /* SSLfatal() already called */
1565
0
        goto err;
1566
0
    }
1567
1568
    /* Generate the finished key */
1569
0
    if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1570
        /* SSLfatal() already called */
1571
0
        goto err;
1572
0
    }
1573
1574
0
    if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
1575
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1576
0
        goto err;
1577
0
    }
1578
1579
    /*
1580
     * Get a hash of the ClientHello up to the start of the binders. If we are
1581
     * following a HelloRetryRequest then this includes the hash of the first
1582
     * ClientHello and the HelloRetryRequest itself.
1583
     */
1584
0
    if (s->hello_retry_request == SSL_HRR_PENDING) {
1585
0
        size_t hdatalen;
1586
0
        long hdatalen_l;
1587
0
        void *hdata;
1588
1589
0
        hdatalen = hdatalen_l =
1590
0
            BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
1591
0
        if (hdatalen_l <= 0) {
1592
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
1593
0
            goto err;
1594
0
        }
1595
1596
        /*
1597
         * For servers the handshake buffer data will include the second
1598
         * ClientHello - which we don't want - so we need to take that bit off.
1599
         */
1600
0
        if (s->server) {
1601
0
            PACKET hashprefix, msg;
1602
1603
            /* Find how many bytes are left after the first two messages */
1604
0
            if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
1605
0
                    || !PACKET_forward(&hashprefix, 1)
1606
0
                    || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
1607
0
                    || !PACKET_forward(&hashprefix, 1)
1608
0
                    || !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
1609
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1610
0
                goto err;
1611
0
            }
1612
0
            hdatalen -= PACKET_remaining(&hashprefix);
1613
0
        }
1614
1615
0
        if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
1616
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1617
0
            goto err;
1618
0
        }
1619
0
    }
1620
1621
0
    if (EVP_DigestUpdate(mctx, msgstart, binderoffset) <= 0
1622
0
            || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1623
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1624
0
        goto err;
1625
0
    }
1626
1627
0
    mackey = EVP_PKEY_new_raw_private_key_ex(s->ctx->libctx, "HMAC",
1628
0
                                             s->ctx->propq, finishedkey,
1629
0
                                             hashsize);
1630
0
    if (mackey == NULL) {
1631
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1632
0
        goto err;
1633
0
    }
1634
1635
0
    if (!sign)
1636
0
        binderout = tmpbinder;
1637
1638
0
    bindersize = hashsize;
1639
0
    if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), s->ctx->libctx,
1640
0
                              s->ctx->propq, mackey, NULL) <= 0
1641
0
            || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
1642
0
            || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
1643
0
            || bindersize != hashsize) {
1644
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1645
0
        goto err;
1646
0
    }
1647
1648
0
    if (sign) {
1649
0
        ret = 1;
1650
0
    } else {
1651
        /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
1652
0
        ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
1653
0
        if (!ret)
1654
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BINDER_DOES_NOT_VERIFY);
1655
0
    }
1656
1657
0
 err:
1658
0
    OPENSSL_cleanse(binderkey, sizeof(binderkey));
1659
0
    OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
1660
0
    EVP_PKEY_free(mackey);
1661
0
    EVP_MD_CTX_free(mctx);
1662
1663
0
    return ret;
1664
0
}
1665
1666
static int final_early_data(SSL *s, unsigned int context, int sent)
1667
4.86k
{
1668
4.86k
    if (!sent)
1669
4.86k
        return 1;
1670
1671
0
    if (!s->server) {
1672
0
        if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
1673
0
                && sent
1674
0
                && !s->ext.early_data_ok) {
1675
            /*
1676
             * If we get here then the server accepted our early_data but we
1677
             * later realised that it shouldn't have done (e.g. inconsistent
1678
             * ALPN)
1679
             */
1680
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EARLY_DATA);
1681
0
            return 0;
1682
0
        }
1683
1684
0
        return 1;
1685
0
    }
1686
1687
0
    if (s->max_early_data == 0
1688
0
            || !s->hit
1689
0
            || s->early_data_state != SSL_EARLY_DATA_ACCEPTING
1690
0
            || !s->ext.early_data_ok
1691
0
            || s->hello_retry_request != SSL_HRR_NONE
1692
0
            || (s->allow_early_data_cb != NULL
1693
0
                && !s->allow_early_data_cb(s,
1694
0
                                         s->allow_early_data_cb_data))) {
1695
0
        s->ext.early_data = SSL_EARLY_DATA_REJECTED;
1696
0
    } else {
1697
0
        s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
1698
1699
0
        if (!tls13_change_cipher_state(s,
1700
0
                    SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {
1701
            /* SSLfatal() already called */
1702
0
            return 0;
1703
0
        }
1704
0
    }
1705
1706
0
    return 1;
1707
0
}
1708
1709
static int final_maxfragmentlen(SSL *s, unsigned int context, int sent)
1710
4.86k
{
1711
    /* MaxFragmentLength defaults to disabled */
1712
4.86k
    if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
1713
4.86k
        s->session->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_DISABLED;
1714
1715
    /* Current SSL buffer is lower than requested MFL */
1716
4.86k
    if (s->session && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1717
4.86k
            && s->max_send_fragment < GET_MAX_FRAGMENT_LENGTH(s->session))
1718
        /* trigger a larger buffer reallocation */
1719
0
        if (!ssl3_setup_buffers(s)) {
1720
            /* SSLfatal() already called */
1721
0
            return 0;
1722
0
        }
1723
1724
4.86k
    return 1;
1725
4.86k
}
1726
1727
static int init_post_handshake_auth(SSL *s, ossl_unused unsigned int context)
1728
0
{
1729
0
    s->post_handshake_auth = SSL_PHA_NONE;
1730
1731
0
    return 1;
1732
0
}
1733
1734
/*
1735
 * If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
1736
 * extension, servers MUST abort the handshake.
1737
 */
1738
static int final_psk(SSL *s, unsigned int context, int sent)
1739
4.86k
{
1740
4.86k
    if (s->server && sent && s->clienthello != NULL
1741
4.86k
            && !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
1742
0
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1743
0
                 SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
1744
0
        return 0;
1745
0
    }
1746
1747
4.86k
    return 1;
1748
4.86k
}
1749
1750
#ifndef OPENSSL_NO_QUIC
1751
static int init_quic_transport_params(SSL *s, unsigned int context)
1752
4.61k
{
1753
4.61k
    return 1;
1754
4.61k
}
1755
1756
static int final_quic_transport_params_draft(SSL *s, unsigned int context,
1757
                                             int sent)
1758
4.86k
{
1759
4.86k
    return 1;
1760
4.86k
}
1761
1762
static int final_quic_transport_params(SSL *s, unsigned int context, int sent)
1763
4.86k
{
1764
    /* called after final_quic_transport_params_draft */
1765
4.86k
    if (SSL_IS_QUIC(s)) {
1766
4.86k
        if (s->ext.peer_quic_transport_params_len == 0
1767
4.86k
                && s->ext.peer_quic_transport_params_draft_len == 0) {
1768
0
            SSLfatal(s, SSL_AD_MISSING_EXTENSION,
1769
0
                     SSL_R_MISSING_QUIC_TRANSPORT_PARAMETERS_EXTENSION);
1770
0
            return 0;
1771
0
        }
1772
        /* if we got both, discard the one we can't use */
1773
4.86k
        if (s->ext.peer_quic_transport_params_len != 0
1774
4.86k
                && s->ext.peer_quic_transport_params_draft_len != 0) {
1775
0
            if (s->quic_transport_version == TLSEXT_TYPE_quic_transport_parameters_draft) {
1776
0
                OPENSSL_free(s->ext.peer_quic_transport_params);
1777
0
                s->ext.peer_quic_transport_params = NULL;
1778
0
                s->ext.peer_quic_transport_params_len = 0;
1779
0
            } else {
1780
0
                OPENSSL_free(s->ext.peer_quic_transport_params_draft);
1781
0
                s->ext.peer_quic_transport_params_draft = NULL;
1782
0
                s->ext.peer_quic_transport_params_draft_len = 0;
1783
0
            }
1784
0
        }
1785
4.86k
    }
1786
1787
4.86k
    return 1;
1788
4.86k
}
1789
#endif