Coverage Report

Created: 2026-02-14 07:20

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