Coverage Report

Created: 2025-06-13 06:58

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