Coverage Report

Created: 2026-07-23 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl35/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
22
static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent);
23
static int init_server_name(SSL_CONNECTION *s, unsigned int context);
24
static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent);
25
static int final_ec_pt_formats(SSL_CONNECTION *s, unsigned int context,
26
    int sent);
27
static int init_session_ticket(SSL_CONNECTION *s, unsigned int context);
28
#ifndef OPENSSL_NO_OCSP
29
static int init_status_request(SSL_CONNECTION *s, unsigned int context);
30
#endif
31
#ifndef OPENSSL_NO_NEXTPROTONEG
32
static int init_npn(SSL_CONNECTION *s, unsigned int context);
33
#endif
34
static int init_alpn(SSL_CONNECTION *s, unsigned int context);
35
static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent);
36
static int init_sig_algs_cert(SSL_CONNECTION *s, unsigned int context);
37
static int init_sig_algs(SSL_CONNECTION *s, unsigned int context);
38
static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context);
39
static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context);
40
static int init_certificate_authorities(SSL_CONNECTION *s,
41
    unsigned int context);
42
static EXT_RETURN tls_construct_certificate_authorities(SSL_CONNECTION *s,
43
    WPACKET *pkt,
44
    unsigned int context,
45
    X509 *x,
46
    size_t chainidx);
47
static int tls_parse_certificate_authorities(SSL_CONNECTION *s, PACKET *pkt,
48
    unsigned int context, X509 *x,
49
    size_t chainidx);
50
#ifndef OPENSSL_NO_SRP
51
static int init_srp(SSL_CONNECTION *s, unsigned int context);
52
#endif
53
static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context);
54
static int init_etm(SSL_CONNECTION *s, unsigned int context);
55
static int init_ems(SSL_CONNECTION *s, unsigned int context);
56
static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent);
57
static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context);
58
static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent);
59
#ifndef OPENSSL_NO_SRTP
60
static int init_srtp(SSL_CONNECTION *s, unsigned int context);
61
#endif
62
static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent);
63
static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,
64
    int sent);
65
static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent);
66
static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,
67
    int sent);
68
static int init_post_handshake_auth(SSL_CONNECTION *s, unsigned int context);
69
static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent);
70
static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context);
71
static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,
72
    unsigned int context,
73
    X509 *x, size_t chainidx);
74
static int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt,
75
    unsigned int context,
76
    X509 *x, size_t chainidx);
77
78
/* Structure to define a built-in extension */
79
typedef struct extensions_definition_st {
80
    /* The defined type for the extension */
81
    unsigned int type;
82
    /*
83
     * The context that this extension applies to, e.g. what messages and
84
     * protocol versions
85
     */
86
    unsigned int context;
87
    /*
88
     * Initialise extension before parsing. Always called for relevant contexts
89
     * even if extension not present
90
     */
91
    int (*init)(SSL_CONNECTION *s, unsigned int context);
92
    /* Parse extension sent from client to server */
93
    int (*parse_ctos)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,
94
        X509 *x, size_t chainidx);
95
    /* Parse extension send from server to client */
96
    int (*parse_stoc)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context,
97
        X509 *x, size_t chainidx);
98
    /* Construct extension sent from server to client */
99
    EXT_RETURN (*construct_stoc)(SSL_CONNECTION *s, WPACKET *pkt,
100
        unsigned int context,
101
        X509 *x, size_t chainidx);
102
    /* Construct extension sent from client to server */
103
    EXT_RETURN (*construct_ctos)(SSL_CONNECTION *s, WPACKET *pkt,
104
        unsigned int context,
105
        X509 *x, size_t chainidx);
106
    /*
107
     * Finalise extension after parsing. Always called where an extensions was
108
     * initialised even if the extension was not present. |sent| is set to 1 if
109
     * the extension was seen, or 0 otherwise.
110
     */
111
    int (*final)(SSL_CONNECTION *s, unsigned int context, int sent);
112
} EXTENSION_DEFINITION;
113
114
/*
115
 * Definitions of all built-in extensions. NOTE: Changes in the number or order
116
 * of these extensions should be mirrored with equivalent changes to the
117
 * indexes ( TLSEXT_IDX_* ) defined in ssl_local.h.
118
 * Extensions should be added to test/ext_internal_test.c as well, as that
119
 * tests the ordering of the extensions.
120
 *
121
 * Each extension has an initialiser, a client and
122
 * server side parser and a finaliser. The initialiser is called (if the
123
 * extension is relevant to the given context) even if we did not see the
124
 * extension in the message that we received. The parser functions are only
125
 * called if we see the extension in the message. The finalisers are always
126
 * called if the initialiser was called.
127
 * There are also server and client side constructor functions which are always
128
 * called during message construction if the extension is relevant for the
129
 * given context.
130
 * The initialisation, parsing, finalisation and construction functions are
131
 * always called in the order defined in this list. Some extensions may depend
132
 * on others having been processed first, so the order of this list is
133
 * significant.
134
 * The extension context is defined by a series of flags which specify which
135
 * messages the extension is relevant to. These flags also specify whether the
136
 * extension is relevant to a particular protocol or protocol version.
137
 *
138
 * NOTE: WebSphere Application Server 7+ cannot handle empty extensions at
139
 * the end, keep these extensions before signature_algorithm.
140
 */
141
#define INVALID_EXTENSION { TLSEXT_TYPE_invalid, 0, NULL, NULL, NULL, NULL, NULL, NULL }
142
static const EXTENSION_DEFINITION ext_defs[] = {
143
    { TLSEXT_TYPE_renegotiate,
144
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
145
            | SSL_EXT_SSL3_ALLOWED | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
146
        NULL, tls_parse_ctos_renegotiate, tls_parse_stoc_renegotiate,
147
        tls_construct_stoc_renegotiate, tls_construct_ctos_renegotiate,
148
        final_renegotiate },
149
    { TLSEXT_TYPE_server_name,
150
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
151
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
152
        init_server_name,
153
        tls_parse_ctos_server_name, tls_parse_stoc_server_name,
154
        tls_construct_stoc_server_name, tls_construct_ctos_server_name,
155
        final_server_name },
156
    { TLSEXT_TYPE_max_fragment_length,
157
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
158
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
159
        NULL, tls_parse_ctos_maxfragmentlen, tls_parse_stoc_maxfragmentlen,
160
        tls_construct_stoc_maxfragmentlen, tls_construct_ctos_maxfragmentlen,
161
        final_maxfragmentlen },
162
#ifndef OPENSSL_NO_SRP
163
    { TLSEXT_TYPE_srp,
164
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
165
        init_srp, tls_parse_ctos_srp, NULL, NULL, tls_construct_ctos_srp, NULL },
166
#else
167
    INVALID_EXTENSION,
168
#endif
169
    { TLSEXT_TYPE_ec_point_formats,
170
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
171
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
172
        init_ec_point_formats, tls_parse_ctos_ec_pt_formats, tls_parse_stoc_ec_pt_formats,
173
        tls_construct_stoc_ec_pt_formats, tls_construct_ctos_ec_pt_formats,
174
        final_ec_pt_formats },
175
    { /*
176
       * "supported_groups" is spread across several specifications.
177
       * It was originally specified as "elliptic_curves" in RFC 4492,
178
       * and broadened to include named FFDH groups by RFC 7919.
179
       * Both RFCs 4492 and 7919 do not include a provision for the server
180
       * to indicate to the client the complete list of groups supported
181
       * by the server, with the server instead just indicating the
182
       * selected group for this connection in the ServerKeyExchange
183
       * message.  TLS 1.3 adds a scheme for the server to indicate
184
       * to the client its list of supported groups in the
185
       * EncryptedExtensions message, but none of the relevant
186
       * specifications permit sending supported_groups in the ServerHello.
187
       * Nonetheless (possibly due to the close proximity to the
188
       * "ec_point_formats" extension, which is allowed in the ServerHello),
189
       * there are several servers that send this extension in the
190
       * ServerHello anyway.  Up to and including the 1.1.0 release,
191
       * we did not check for the presence of nonpermitted extensions,
192
       * so to avoid a regression, we must permit this extension in the
193
       * TLS 1.2 ServerHello as well.
194
       *
195
       * Note that there is no tls_parse_stoc_supported_groups function,
196
       * so we do not perform any additional parsing, validation, or
197
       * processing on the server's group list -- this is just a minimal
198
       * change to preserve compatibility with these misbehaving servers.
199
       */
200
        TLSEXT_TYPE_supported_groups,
201
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
202
            | SSL_EXT_TLS1_2_SERVER_HELLO,
203
        NULL, tls_parse_ctos_supported_groups, NULL,
204
        tls_construct_stoc_supported_groups,
205
        tls_construct_ctos_supported_groups, NULL },
206
    { TLSEXT_TYPE_session_ticket,
207
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
208
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
209
        init_session_ticket, tls_parse_ctos_session_ticket,
210
        tls_parse_stoc_session_ticket, tls_construct_stoc_session_ticket,
211
        tls_construct_ctos_session_ticket, NULL },
212
#ifndef OPENSSL_NO_OCSP
213
    { TLSEXT_TYPE_status_request,
214
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
215
            | SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
216
        init_status_request, tls_parse_ctos_status_request,
217
        tls_parse_stoc_status_request, tls_construct_stoc_status_request,
218
        tls_construct_ctos_status_request, NULL },
219
#else
220
    INVALID_EXTENSION,
221
#endif
222
#ifndef OPENSSL_NO_NEXTPROTONEG
223
    { TLSEXT_TYPE_next_proto_neg,
224
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
225
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
226
        init_npn, tls_parse_ctos_npn, tls_parse_stoc_npn,
227
        tls_construct_stoc_next_proto_neg, tls_construct_ctos_npn, NULL },
228
#else
229
    INVALID_EXTENSION,
230
#endif
231
    { /*
232
       * Must appear in this list after server_name so that finalisation
233
       * happens after server_name callbacks
234
       */
235
        TLSEXT_TYPE_application_layer_protocol_negotiation,
236
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
237
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
238
        init_alpn, tls_parse_ctos_alpn, tls_parse_stoc_alpn,
239
        tls_construct_stoc_alpn, tls_construct_ctos_alpn, final_alpn },
240
#ifndef OPENSSL_NO_SRTP
241
    { TLSEXT_TYPE_use_srtp,
242
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
243
            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS | SSL_EXT_DTLS_ONLY,
244
        init_srtp, tls_parse_ctos_use_srtp, tls_parse_stoc_use_srtp,
245
        tls_construct_stoc_use_srtp, tls_construct_ctos_use_srtp, NULL },
246
#else
247
    INVALID_EXTENSION,
248
#endif
249
    { TLSEXT_TYPE_encrypt_then_mac,
250
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
251
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
252
        init_etm, tls_parse_ctos_etm, tls_parse_stoc_etm,
253
        tls_construct_stoc_etm, tls_construct_ctos_etm, NULL },
254
#ifndef OPENSSL_NO_CT
255
    { TLSEXT_TYPE_signed_certificate_timestamp,
256
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
257
            | SSL_EXT_TLS1_3_CERTIFICATE | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
258
        NULL,
259
        /*
260
         * No server side support for this, but can be provided by a custom
261
         * extension. This is an exception to the rule that custom extensions
262
         * cannot override built in ones.
263
         */
264
        NULL, tls_parse_stoc_sct, NULL, tls_construct_ctos_sct, NULL },
265
#else
266
    INVALID_EXTENSION,
267
#endif
268
    { TLSEXT_TYPE_extended_master_secret,
269
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
270
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
271
        init_ems, tls_parse_ctos_ems, tls_parse_stoc_ems,
272
        tls_construct_stoc_ems, tls_construct_ctos_ems, final_ems },
273
    { TLSEXT_TYPE_signature_algorithms_cert,
274
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
275
        init_sig_algs_cert, tls_parse_ctos_sig_algs_cert,
276
        tls_parse_ctos_sig_algs_cert,
277
        /* We do not generate signature_algorithms_cert at present. */
278
        NULL, NULL, NULL },
279
    {
280
        TLSEXT_TYPE_post_handshake_auth,
281
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ONLY,
282
        init_post_handshake_auth,
283
        tls_parse_ctos_post_handshake_auth,
284
        NULL,
285
        NULL,
286
        tls_construct_ctos_post_handshake_auth,
287
        NULL,
288
    },
289
    { TLSEXT_TYPE_client_cert_type,
290
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
291
            | SSL_EXT_TLS1_2_SERVER_HELLO,
292
        init_client_cert_type,
293
        tls_parse_ctos_client_cert_type, tls_parse_stoc_client_cert_type,
294
        tls_construct_stoc_client_cert_type, tls_construct_ctos_client_cert_type,
295
        NULL },
296
    { TLSEXT_TYPE_server_cert_type,
297
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
298
            | SSL_EXT_TLS1_2_SERVER_HELLO,
299
        init_server_cert_type,
300
        tls_parse_ctos_server_cert_type, tls_parse_stoc_server_cert_type,
301
        tls_construct_stoc_server_cert_type, tls_construct_ctos_server_cert_type,
302
        NULL },
303
    { TLSEXT_TYPE_signature_algorithms,
304
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
305
        init_sig_algs, tls_parse_ctos_sig_algs,
306
        tls_parse_ctos_sig_algs, tls_construct_ctos_sig_algs,
307
        tls_construct_ctos_sig_algs, final_sig_algs },
308
    { TLSEXT_TYPE_supported_versions,
309
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
310
            | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY,
311
        NULL,
312
        /* Processed inline as part of version selection */
313
        NULL, tls_parse_stoc_supported_versions,
314
        tls_construct_stoc_supported_versions,
315
        tls_construct_ctos_supported_versions, final_supported_versions },
316
    { TLSEXT_TYPE_psk_kex_modes,
317
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS_IMPLEMENTATION_ONLY
318
            | SSL_EXT_TLS1_3_ONLY,
319
        init_psk_kex_modes, tls_parse_ctos_psk_kex_modes, NULL, NULL,
320
        tls_construct_ctos_psk_kex_modes, NULL },
321
    { /*
322
       * Must be in this list after supported_groups. We need that to have
323
       * been parsed before we do this one.
324
       */
325
        TLSEXT_TYPE_key_share,
326
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
327
            | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST | SSL_EXT_TLS_IMPLEMENTATION_ONLY
328
            | SSL_EXT_TLS1_3_ONLY,
329
        NULL, tls_parse_ctos_key_share, tls_parse_stoc_key_share,
330
        tls_construct_stoc_key_share, tls_construct_ctos_key_share,
331
        final_key_share },
332
    { /* Must be after key_share */
333
        TLSEXT_TYPE_cookie,
334
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
335
            | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
336
        NULL, tls_parse_ctos_cookie, tls_parse_stoc_cookie,
337
        tls_construct_stoc_cookie, tls_construct_ctos_cookie, NULL },
338
    { /*
339
       * Special unsolicited ServerHello extension only used when
340
       * SSL_OP_CRYPTOPRO_TLSEXT_BUG is set. We allow it in a ClientHello but
341
       * ignore it.
342
       */
343
        TLSEXT_TYPE_cryptopro_bug,
344
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO
345
            | SSL_EXT_TLS1_2_AND_BELOW_ONLY,
346
        NULL, NULL, NULL, tls_construct_stoc_cryptopro_bug, NULL, NULL },
347
    { TLSEXT_TYPE_compress_certificate,
348
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
349
            | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
350
        tls_init_compress_certificate,
351
        tls_parse_compress_certificate, tls_parse_compress_certificate,
352
        tls_construct_compress_certificate, tls_construct_compress_certificate,
353
        NULL },
354
    { TLSEXT_TYPE_early_data,
355
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
356
            | SSL_EXT_TLS1_3_NEW_SESSION_TICKET | SSL_EXT_TLS1_3_ONLY,
357
        NULL, tls_parse_ctos_early_data, tls_parse_stoc_early_data,
358
        tls_construct_stoc_early_data, tls_construct_ctos_early_data,
359
        final_early_data },
360
    {
361
        TLSEXT_TYPE_certificate_authorities,
362
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST
363
            | SSL_EXT_TLS1_3_ONLY,
364
        init_certificate_authorities,
365
        tls_parse_certificate_authorities,
366
        tls_parse_certificate_authorities,
367
        tls_construct_certificate_authorities,
368
        tls_construct_certificate_authorities,
369
        NULL,
370
    },
371
    { /* Must be immediately before pre_shared_key */
372
        TLSEXT_TYPE_padding,
373
        SSL_EXT_CLIENT_HELLO,
374
        NULL,
375
        /* We send this, but don't read it */
376
        NULL, NULL, NULL, tls_construct_ctos_padding, NULL },
377
    { /* Required by the TLSv1.3 spec to always be the last extension */
378
        TLSEXT_TYPE_psk,
379
        SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_SERVER_HELLO
380
            | SSL_EXT_TLS_IMPLEMENTATION_ONLY | SSL_EXT_TLS1_3_ONLY,
381
        NULL, tls_parse_ctos_psk, tls_parse_stoc_psk, tls_construct_stoc_psk,
382
        tls_construct_ctos_psk, final_psk }
383
};
384
385
/* Returns a TLSEXT_TYPE for the given index */
386
unsigned int ossl_get_extension_type(size_t idx)
387
0
{
388
0
    size_t num_exts = OSSL_NELEM(ext_defs);
389
390
0
    if (idx >= num_exts)
391
0
        return TLSEXT_TYPE_out_of_range;
392
393
0
    return ext_defs[idx].type;
394
0
}
395
396
/* Check whether an extension's context matches the current context */
397
static int validate_context(SSL_CONNECTION *s, unsigned int extctx,
398
    unsigned int thisctx)
399
432k
{
400
    /* Check we're allowed to use this extension in this context */
401
432k
    if ((thisctx & extctx) == 0)
402
111
        return 0;
403
404
432k
    if (SSL_CONNECTION_IS_DTLS(s)) {
405
85.0k
        if ((extctx & SSL_EXT_TLS_ONLY) != 0)
406
0
            return 0;
407
347k
    } else if ((extctx & SSL_EXT_DTLS_ONLY) != 0) {
408
19
        return 0;
409
19
    }
410
411
432k
    return 1;
412
432k
}
413
414
int tls_validate_all_contexts(SSL_CONNECTION *s, unsigned int thisctx,
415
    RAW_EXTENSION *exts)
416
79.0k
{
417
79.0k
    size_t i, num_exts, builtin_num = OSSL_NELEM(ext_defs), offset;
418
79.0k
    RAW_EXTENSION *thisext;
419
79.0k
    unsigned int context;
420
79.0k
    ENDPOINT role = ENDPOINT_BOTH;
421
422
79.0k
    if ((thisctx & SSL_EXT_CLIENT_HELLO) != 0)
423
0
        role = ENDPOINT_SERVER;
424
79.0k
    else if ((thisctx & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
425
53.4k
        role = ENDPOINT_CLIENT;
426
427
    /* Calculate the number of extensions in the extensions list */
428
79.0k
    num_exts = builtin_num + s->cert->custext.meths_count;
429
430
2.43M
    for (thisext = exts, i = 0; i < num_exts; i++, thisext++) {
431
2.35M
        if (!thisext->present)
432
2.21M
            continue;
433
434
141k
        if (i < builtin_num) {
435
141k
            context = ext_defs[i].context;
436
141k
        } else {
437
0
            custom_ext_method *meth = NULL;
438
439
0
            meth = custom_ext_find(&s->cert->custext, role, thisext->type,
440
0
                &offset);
441
0
            if (!ossl_assert(meth != NULL))
442
0
                return 0;
443
0
            context = meth->context;
444
0
        }
445
446
141k
        if (!validate_context(s, context, thisctx))
447
46
            return 0;
448
141k
    }
449
450
79.0k
    return 1;
451
79.0k
}
452
453
/*
454
 * Verify whether we are allowed to use the extension |type| in the current
455
 * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
456
 * indicate the extension is not allowed. If returning 1 then |*found| is set to
457
 * the definition for the extension we found.
458
 */
459
static int verify_extension(SSL_CONNECTION *s, unsigned int context,
460
    unsigned int type, custom_ext_methods *meths,
461
    RAW_EXTENSION *rawexlist, RAW_EXTENSION **found)
462
328k
{
463
328k
    size_t i;
464
328k
    size_t builtin_num = OSSL_NELEM(ext_defs);
465
328k
    const EXTENSION_DEFINITION *thisext;
466
467
5.45M
    for (i = 0, thisext = ext_defs; i < builtin_num; i++, thisext++) {
468
5.34M
        if (type == thisext->type) {
469
223k
            if (!validate_context(s, thisext->context, context))
470
59
                return 0;
471
472
223k
            *found = &rawexlist[i];
473
223k
            return 1;
474
223k
        }
475
5.34M
    }
476
477
    /* Check the custom extensions */
478
104k
    if (meths != NULL) {
479
104k
        size_t offset = 0;
480
104k
        ENDPOINT role = ENDPOINT_BOTH;
481
104k
        custom_ext_method *meth = NULL;
482
483
104k
        if ((context & SSL_EXT_CLIENT_HELLO) != 0)
484
36.6k
            role = ENDPOINT_SERVER;
485
67.7k
        else if ((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0)
486
48.3k
            role = ENDPOINT_CLIENT;
487
488
104k
        meth = custom_ext_find(meths, role, type, &offset);
489
104k
        if (meth != NULL) {
490
16.7k
            if (!validate_context(s, meth->context, context))
491
9
                return 0;
492
16.7k
            *found = &rawexlist[offset + builtin_num];
493
16.7k
            return 1;
494
16.7k
        }
495
104k
    }
496
497
    /* Unknown extension. We allow it */
498
87.7k
    *found = NULL;
499
87.7k
    return 1;
500
104k
}
501
502
/*
503
 * Check whether the context defined for an extension |extctx| means whether
504
 * the extension is relevant for the current context |thisctx| or not. Returns
505
 * 1 if the extension is relevant for this context, and 0 otherwise
506
 */
507
int extension_is_relevant(SSL_CONNECTION *s, unsigned int extctx,
508
    unsigned int thisctx)
509
4.94M
{
510
4.94M
    int is_tls13;
511
512
    /*
513
     * For HRR we haven't selected the version yet but we know it will be
514
     * TLSv1.3
515
     */
516
4.94M
    if ((thisctx & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
517
2.69k
        is_tls13 = 1;
518
4.94M
    else
519
4.94M
        is_tls13 = SSL_CONNECTION_IS_TLS13(s);
520
521
4.94M
    if ((SSL_CONNECTION_IS_DTLS(s)
522
1.29M
            && (extctx & SSL_EXT_TLS_IMPLEMENTATION_ONLY) != 0)
523
4.77M
        || (s->version == SSL3_VERSION
524
11
            && (extctx & SSL_EXT_SSL3_ALLOWED) == 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
4.77M
        || (is_tls13 && (extctx & SSL_EXT_TLS1_2_AND_BELOW_ONLY) != 0)
534
4.76M
        || (!is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0
535
827k
            && (thisctx & SSL_EXT_CLIENT_HELLO) == 0)
536
4.76M
        || (s->server && !is_tls13 && (extctx & SSL_EXT_TLS1_3_ONLY) != 0)
537
4.66M
        || (s->hit && (extctx & SSL_EXT_IGNORE_ON_RESUMPTION) != 0))
538
283k
        return 0;
539
4.66M
    return 1;
540
4.94M
}
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
90.6k
{
562
90.6k
    PACKET extensions = *packet;
563
90.6k
    size_t i = 0;
564
90.6k
    size_t num_exts;
565
90.6k
    custom_ext_methods *exts = &s->cert->custext;
566
90.6k
    RAW_EXTENSION *raw_extensions = NULL;
567
90.6k
    const EXTENSION_DEFINITION *thisexd;
568
569
90.6k
    *res = NULL;
570
571
    /*
572
     * Initialise server side custom extensions. Client side is done during
573
     * construction of extensions for the ClientHello.
574
     */
575
90.6k
    if ((context & SSL_EXT_CLIENT_HELLO) != 0)
576
21.7k
        custom_ext_init(&s->cert->custext);
577
578
90.6k
    num_exts = OSSL_NELEM(ext_defs) + (exts != NULL ? exts->meths_count : 0);
579
90.6k
    raw_extensions = OPENSSL_zalloc(num_exts * sizeof(*raw_extensions));
580
90.6k
    if (raw_extensions == NULL) {
581
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
582
0
        return 0;
583
0
    }
584
585
90.6k
    i = 0;
586
306k
    while (PACKET_remaining(&extensions) > 0) {
587
216k
        unsigned int type, idx;
588
216k
        PACKET extension;
589
216k
        RAW_EXTENSION *thisex;
590
591
216k
        if (!PACKET_get_net_2(&extensions, &type) || !PACKET_get_length_prefixed_2(&extensions, &extension)) {
592
360
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
593
360
            goto err;
594
360
        }
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
215k
        if (!verify_extension(s, context, type, exts, raw_extensions, &thisex)
601
215k
            || (thisex != NULL && thisex->present == 1)
602
215k
            || (type == TLSEXT_TYPE_psk
603
454
                && (context & SSL_EXT_CLIENT_HELLO) != 0
604
443
                && PACKET_remaining(&extensions) != 0)) {
605
108
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
606
108
            goto err;
607
108
        }
608
609
        /* The server must tolerate the unknown extension and complete. */
610
215k
        if (thisex == NULL)
611
55.5k
            continue;
612
613
160k
        idx = thisex - raw_extensions;
614
        /*-
615
         * Check that we requested this extension (if appropriate). Requests can
616
         * be sent in the ClientHello and CertificateRequest. Unsolicited
617
         * extensions can be sent in the NewSessionTicket. We only do this for
618
         * the built-in extensions. Custom extensions have a different but
619
         * similar check elsewhere.
620
         * Special cases:
621
         * - The HRR cookie extension is unsolicited
622
         * - The renegotiate extension is unsolicited (the client signals
623
         *   support via an SCSV)
624
         * - The signed_certificate_timestamp extension can be provided by a
625
         * custom extension or by the built-in version. We let the extension
626
         * itself handle unsolicited response checks.
627
         */
628
160k
        if (idx < OSSL_NELEM(ext_defs)
629
148k
            && (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) == 0
630
89.7k
            && type != TLSEXT_TYPE_cookie
631
89.6k
            && type != TLSEXT_TYPE_renegotiate
632
61.8k
            && type != TLSEXT_TYPE_signed_certificate_timestamp
633
61.7k
            && (s->ext.extflags[idx] & SSL_EXT_FLAG_SENT) == 0
634
333
#ifndef OPENSSL_NO_GOST
635
333
            && !((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0
636
330
                && type == TLSEXT_TYPE_cryptopro_bug)
637
160k
#endif
638
160k
        ) {
639
69
            SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION,
640
69
                SSL_R_UNSOLICITED_EXTENSION);
641
69
            goto err;
642
69
        }
643
160k
        thisex->data = extension;
644
160k
        thisex->present = 1;
645
160k
        thisex->type = type;
646
160k
        thisex->received_order = i++;
647
160k
        if (s->ext.debug_cb)
648
0
            s->ext.debug_cb(SSL_CONNECTION_GET_USER_SSL(s), !s->server,
649
0
                thisex->type, PACKET_data(&thisex->data),
650
0
                (int)PACKET_remaining(&thisex->data),
651
0
                s->ext.debug_arg);
652
160k
    }
653
654
90.0k
    if (init) {
655
        /*
656
         * Initialise all known extensions relevant to this context,
657
         * whether we have found them or not
658
         */
659
2.70M
        for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs);
660
2.61M
            i++, thisexd++) {
661
2.61M
            if (thisexd->init != NULL && (thisexd->context & context) != 0
662
945k
                && extension_is_relevant(s, thisexd->context, context)
663
858k
                && !thisexd->init(s, context)) {
664
                /* SSLfatal() already called */
665
0
                goto err;
666
0
            }
667
2.61M
        }
668
90.0k
    }
669
670
90.0k
    *res = raw_extensions;
671
90.0k
    if (len != NULL)
672
21.6k
        *len = num_exts;
673
90.0k
    return 1;
674
675
537
err:
676
537
    OPENSSL_free(raw_extensions);
677
537
    return 0;
678
90.0k
}
679
680
/*
681
 * Runs the parser for a given extension with index |idx|. |exts| contains the
682
 * list of all parsed extensions previously collected by
683
 * tls_collect_extensions(). The parser is only run if it is applicable for the
684
 * given |context| and the parser has not already been run. If this is for a
685
 * Certificate message, then we also provide the parser with the relevant
686
 * Certificate |x| and its position in the |chainidx| with 0 being the first
687
 * Certificate. Returns 1 on success or 0 on failure. If an extension is not
688
 * present this counted as success.
689
 */
690
int tls_parse_extension(SSL_CONNECTION *s, TLSEXT_INDEX idx, int context,
691
    RAW_EXTENSION *exts, X509 *x, size_t chainidx)
692
4.75M
{
693
4.75M
    RAW_EXTENSION *currext = &exts[idx];
694
4.75M
    int (*parser)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context, X509 *x,
695
4.75M
        size_t chainidx)
696
4.75M
        = NULL;
697
698
    /* Skip if the extension is not present */
699
4.75M
    if (!currext->present)
700
4.43M
        return 1;
701
702
    /* Skip if we've already parsed this extension */
703
314k
    if (currext->parsed)
704
36.9k
        return 1;
705
706
278k
    currext->parsed = 1;
707
708
278k
    if (idx < OSSL_NELEM(ext_defs)) {
709
        /* We are handling a built-in extension */
710
258k
        const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
711
712
        /* Check if extension is defined for our protocol. If not, skip */
713
258k
        if (!extension_is_relevant(s, extdef->context, context))
714
9.69k
            return 1;
715
716
248k
        parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
717
718
248k
        if (parser != NULL)
719
243k
            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
248k
    }
726
727
    /* Parse custom extensions */
728
24.7k
    return custom_ext_parse(s, context, currext->type,
729
24.7k
        PACKET_data(&currext->data),
730
24.7k
        PACKET_remaining(&currext->data),
731
24.7k
        x, chainidx);
732
278k
}
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_CONNECTION *s, int context,
742
    RAW_EXTENSION *exts, X509 *x,
743
    size_t chainidx, int fin)
744
158k
{
745
158k
    size_t i, numexts = OSSL_NELEM(ext_defs);
746
158k
    const EXTENSION_DEFINITION *thisexd;
747
748
    /* Calculate the number of extensions in the extensions list */
749
158k
    numexts += s->cert->custext.meths_count;
750
751
    /* Parse each extension in turn */
752
4.74M
    for (i = 0; i < numexts; i++) {
753
4.59M
        if (!tls_parse_extension(s, i, context, exts, x, chainidx)) {
754
            /* SSLfatal() already called */
755
8.69k
            return 0;
756
8.69k
        }
757
4.59M
    }
758
759
149k
    if (fin) {
760
        /*
761
         * Finalise all known extensions relevant to this context,
762
         * whether we have found them or not
763
         */
764
4.56M
        for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);
765
4.41M
            i++, thisexd++) {
766
4.41M
            if (thisexd->final != NULL && (thisexd->context & context) != 0
767
803k
                && !thisexd->final(s, context, exts[i].present)) {
768
                /* SSLfatal() already called */
769
432
                return 0;
770
432
            }
771
4.41M
        }
772
149k
    }
773
774
149k
    return 1;
775
149k
}
776
777
int should_add_extension(SSL_CONNECTION *s, unsigned int extctx,
778
    unsigned int thisctx, int max_version)
779
4.67M
{
780
    /* Skip if not relevant for our context */
781
4.67M
    if ((extctx & thisctx) == 0)
782
569k
        return 0;
783
784
    /* Check if this extension is defined for our protocol. If not, skip */
785
4.10M
    if (!extension_is_relevant(s, extctx, thisctx)
786
3.91M
        || ((extctx & SSL_EXT_TLS1_3_ONLY) != 0
787
921k
            && (thisctx & SSL_EXT_CLIENT_HELLO) != 0
788
911k
            && (SSL_CONNECTION_IS_DTLS(s) || max_version < TLS1_3_VERSION)))
789
301k
        return 0;
790
791
3.80M
    return 1;
792
4.10M
}
793
794
/*
795
 * Construct all the extensions relevant to the current |context| and write
796
 * them to |pkt|. If this is an extension for a Certificate in a Certificate
797
 * message, then |x| will be set to the Certificate we are handling, and
798
 * |chainidx| will indicate the position in the chainidx we are processing (with
799
 * 0 being the first in the chain). Returns 1 on success or 0 on failure. On a
800
 * failure construction stops at the first extension to fail to construct.
801
 */
802
int tls_construct_extensions(SSL_CONNECTION *s, WPACKET *pkt,
803
    unsigned int context,
804
    X509 *x, size_t chainidx)
805
119k
{
806
119k
    size_t i;
807
119k
    int min_version, max_version = 0, reason;
808
119k
    const EXTENSION_DEFINITION *thisexd;
809
119k
    int for_comp = (context & SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION) != 0;
810
811
119k
    if (!WPACKET_start_sub_packet_u16(pkt)
812
        /*
813
         * If extensions are of zero length then we don't even add the
814
         * extensions length bytes to a ClientHello/ServerHello
815
         * (for non-TLSv1.3).
816
         */
817
119k
        || ((context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO)) != 0
818
113k
            && !WPACKET_set_flags(pkt,
819
113k
                WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
820
0
        if (!for_comp)
821
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
822
0
        return 0;
823
0
    }
824
825
119k
    if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
826
94.6k
        reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
827
94.6k
        if (reason != 0) {
828
0
            if (!for_comp)
829
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
830
0
            return 0;
831
0
        }
832
94.6k
    }
833
834
    /* Add custom extensions first */
835
119k
    if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
836
        /* On the server side with initialise during ClientHello parsing */
837
94.6k
        custom_ext_init(&s->cert->custext);
838
94.6k
    }
839
119k
    if (!custom_ext_add(s, context, pkt, x, chainidx, max_version)) {
840
        /* SSLfatal() already called */
841
0
        return 0;
842
0
    }
843
844
3.57M
    for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
845
3.45M
        EXT_RETURN (*construct)(SSL_CONNECTION *s, WPACKET *pkt,
846
3.45M
            unsigned int context,
847
3.45M
            X509 *x, size_t chainidx);
848
3.45M
        EXT_RETURN ret;
849
850
        /* Skip if not relevant for our context */
851
3.45M
        if (!should_add_extension(s, thisexd->context, context, max_version))
852
613k
            continue;
853
854
2.84M
        construct = s->server ? thisexd->construct_stoc
855
2.84M
                              : thisexd->construct_ctos;
856
857
2.84M
        if (construct == NULL)
858
209k
            continue;
859
860
2.63M
        ret = construct(s, pkt, context, x, chainidx);
861
2.63M
        if (ret == EXT_RETURN_FAIL) {
862
            /* SSLfatal() already called */
863
10
            return 0;
864
10
        }
865
2.63M
        if (ret == EXT_RETURN_SENT
866
953k
            && (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) != 0)
867
930k
            s->ext.extflags[i] |= SSL_EXT_FLAG_SENT;
868
2.63M
    }
869
870
119k
    if (!WPACKET_close(pkt)) {
871
0
        if (!for_comp)
872
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
873
0
        return 0;
874
0
    }
875
876
119k
    return 1;
877
119k
}
878
879
/*
880
 * Built in extension finalisation and initialisation functions. All initialise
881
 * or finalise the associated extension type for the given |context|. For
882
 * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
883
 * otherwise. These functions return 1 on success or 0 on failure.
884
 */
885
886
static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent)
887
84.5k
{
888
84.5k
    if (!s->server) {
889
        /*
890
         * Check if we can connect to a server that doesn't support safe
891
         * renegotiation
892
         */
893
52.6k
        if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
894
52.6k
            && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
895
52.6k
            && !sent) {
896
119
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
897
119
                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
898
119
            return 0;
899
119
        }
900
901
52.4k
        return 1;
902
52.6k
    }
903
904
    /* Need RI if renegotiating */
905
31.9k
    if (s->renegotiate
906
0
        && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
907
0
        && !sent) {
908
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
909
0
            SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
910
0
        return 0;
911
0
    }
912
913
31.9k
    return 1;
914
31.9k
}
915
916
static ossl_inline void ssl_tsan_decr(const SSL_CTX *ctx,
917
    TSAN_QUALIFIER int *stat)
918
0
{
919
0
    if (ssl_tsan_lock(ctx)) {
920
0
        tsan_decr(stat);
921
0
        ssl_tsan_unlock(ctx);
922
0
    }
923
0
}
924
925
static int init_server_name(SSL_CONNECTION *s, unsigned int context)
926
141k
{
927
141k
    if (s->server) {
928
40.1k
        s->servername_done = 0;
929
930
40.1k
        OPENSSL_free(s->ext.hostname);
931
40.1k
        s->ext.hostname = NULL;
932
40.1k
    }
933
934
141k
    return 1;
935
141k
}
936
937
static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent)
938
104k
{
939
104k
    int ret = SSL_TLSEXT_ERR_NOACK;
940
104k
    int altmp = SSL_AD_UNRECOGNIZED_NAME;
941
104k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
942
104k
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
943
104k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
944
104k
    int was_ticket = (SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0;
945
946
104k
    if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {
947
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
948
0
        return 0;
949
0
    }
950
951
104k
    if (sctx->ext.servername_cb != NULL)
952
0
        ret = sctx->ext.servername_cb(ussl, &altmp,
953
0
            sctx->ext.servername_arg);
954
104k
    else if (s->session_ctx->ext.servername_cb != NULL)
955
0
        ret = s->session_ctx->ext.servername_cb(ussl, &altmp,
956
0
            s->session_ctx->ext.servername_arg);
957
958
    /*
959
     * For servers, propagate the SNI hostname from the temporary
960
     * storage in the SSL to the persistent SSL_SESSION, now that we
961
     * know we accepted it.
962
     * Clients make this copy when parsing the server's response to
963
     * the extension, which is when they find out that the negotiation
964
     * was successful.
965
     */
966
104k
    if (s->server) {
967
31.9k
        if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {
968
            /* Only store the hostname in the session if we accepted it. */
969
0
            OPENSSL_free(s->session->ext.hostname);
970
0
            s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
971
0
            if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {
972
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
973
0
            }
974
0
        }
975
31.9k
    }
976
977
    /*
978
     * If we switched contexts (whether here or in the client_hello callback),
979
     * move the sess_accept increment from the session_ctx to the new
980
     * context, to avoid the confusing situation of having sess_accept_good
981
     * exceed sess_accept (zero) for the new context.
982
     */
983
104k
    if (SSL_IS_FIRST_HANDSHAKE(s) && sctx != s->session_ctx
984
0
        && s->hello_retry_request == SSL_HRR_NONE) {
985
0
        ssl_tsan_counter(sctx, &sctx->stats.sess_accept);
986
0
        ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);
987
0
    }
988
989
    /*
990
     * If we're expecting to send a ticket, and tickets were previously enabled,
991
     * and now tickets are disabled, then turn off expected ticket.
992
     * Also, if this is not a resumption, create a new session ID
993
     */
994
104k
    if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected
995
0
        && was_ticket && (SSL_get_options(ssl) & SSL_OP_NO_TICKET) != 0) {
996
0
        s->ext.ticket_expected = 0;
997
0
        if (!s->hit) {
998
0
            SSL_SESSION *ss = SSL_get_session(ssl);
999
1000
0
            if (ss != NULL) {
1001
0
                OPENSSL_free(ss->ext.tick);
1002
0
                ss->ext.tick = NULL;
1003
0
                ss->ext.ticklen = 0;
1004
0
                ss->ext.tick_lifetime_hint = 0;
1005
0
                ss->ext.tick_age_add = 0;
1006
0
                if (!ssl_generate_session_id(s, ss)) {
1007
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1008
0
                    return 0;
1009
0
                }
1010
0
            } else {
1011
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1012
0
                return 0;
1013
0
            }
1014
0
        }
1015
0
    }
1016
1017
104k
    switch (ret) {
1018
0
    case SSL_TLSEXT_ERR_ALERT_FATAL:
1019
0
        SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);
1020
0
        return 0;
1021
1022
0
    case SSL_TLSEXT_ERR_ALERT_WARNING:
1023
        /* TLSv1.3 doesn't have warning alerts so we suppress this */
1024
0
        if (!SSL_CONNECTION_IS_TLS13(s))
1025
0
            ssl3_send_alert(s, SSL3_AL_WARNING, altmp);
1026
0
        s->servername_done = 0;
1027
0
        return 1;
1028
1029
104k
    case SSL_TLSEXT_ERR_NOACK:
1030
104k
        s->servername_done = 0;
1031
104k
        return 1;
1032
1033
0
    default:
1034
0
        return 1;
1035
104k
    }
1036
104k
}
1037
1038
static int final_ec_pt_formats(SSL_CONNECTION *s, unsigned int context,
1039
    int sent)
1040
68.8k
{
1041
68.8k
    unsigned long alg_k, alg_a;
1042
1043
68.8k
    if (s->server)
1044
26.0k
        return 1;
1045
1046
42.8k
    alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
1047
42.8k
    alg_a = s->s3.tmp.new_cipher->algorithm_auth;
1048
1049
    /*
1050
     * If we are client and using an elliptic curve cryptography cipher
1051
     * suite, then if server returns an EC point formats lists extension it
1052
     * must contain uncompressed.
1053
     */
1054
42.8k
    if (s->ext.ecpointformats != NULL
1055
0
        && s->ext.ecpointformats_len > 0
1056
0
        && s->ext.peer_ecpointformats != NULL
1057
0
        && s->ext.peer_ecpointformats_len > 0
1058
0
        && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
1059
        /* we are using an ECC cipher */
1060
0
        size_t i;
1061
0
        unsigned char *list = s->ext.peer_ecpointformats;
1062
1063
0
        for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {
1064
0
            if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
1065
0
                break;
1066
0
        }
1067
0
        if (i == s->ext.peer_ecpointformats_len) {
1068
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1069
0
                SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
1070
0
            return 0;
1071
0
        }
1072
0
    }
1073
1074
42.8k
    return 1;
1075
42.8k
}
1076
1077
static int init_session_ticket(SSL_CONNECTION *s, unsigned int context)
1078
119k
{
1079
119k
    if (!s->server)
1080
80.1k
        s->ext.ticket_expected = 0;
1081
1082
119k
    return 1;
1083
119k
}
1084
1085
#ifndef OPENSSL_NO_OCSP
1086
static int init_status_request(SSL_CONNECTION *s, unsigned int context)
1087
137k
{
1088
137k
    if (s->server) {
1089
40.1k
        s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
1090
97.3k
    } else {
1091
        /*
1092
         * Ensure we get sensible values passed to tlsext_status_cb in the event
1093
         * that we don't receive a status message
1094
         */
1095
97.3k
        OPENSSL_free(s->ext.ocsp.resp);
1096
97.3k
        s->ext.ocsp.resp = NULL;
1097
97.3k
        s->ext.ocsp.resp_len = 0;
1098
97.3k
    }
1099
1100
137k
    return 1;
1101
137k
}
1102
#endif
1103
1104
#ifndef OPENSSL_NO_NEXTPROTONEG
1105
static int init_npn(SSL_CONNECTION *s, unsigned int context)
1106
119k
{
1107
119k
    s->s3.npn_seen = 0;
1108
1109
119k
    return 1;
1110
119k
}
1111
#endif
1112
1113
static int init_alpn(SSL_CONNECTION *s, unsigned int context)
1114
141k
{
1115
141k
    OPENSSL_free(s->s3.alpn_selected);
1116
141k
    s->s3.alpn_selected = NULL;
1117
141k
    s->s3.alpn_selected_len = 0;
1118
141k
    if (s->server) {
1119
40.1k
        OPENSSL_free(s->s3.alpn_proposed);
1120
40.1k
        s->s3.alpn_proposed = NULL;
1121
40.1k
        s->s3.alpn_proposed_len = 0;
1122
40.1k
    }
1123
141k
    return 1;
1124
141k
}
1125
1126
static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent)
1127
104k
{
1128
104k
    if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
1129
0
        s->ext.early_data_ok = 0;
1130
1131
104k
    if (!s->server || !SSL_CONNECTION_IS_TLS13(s))
1132
100k
        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
3.85k
    return tls_handle_alpn(s);
1144
104k
}
1145
1146
static int init_sig_algs(SSL_CONNECTION *s, unsigned int context)
1147
40.3k
{
1148
    /* Clear any signature algorithms extension received */
1149
40.3k
    OPENSSL_free(s->s3.tmp.peer_sigalgs);
1150
40.3k
    s->s3.tmp.peer_sigalgs = NULL;
1151
40.3k
    s->s3.tmp.peer_sigalgslen = 0;
1152
1153
40.3k
    return 1;
1154
40.3k
}
1155
1156
static int init_sig_algs_cert(SSL_CONNECTION *s,
1157
    ossl_unused unsigned int context)
1158
40.3k
{
1159
    /* Clear any signature algorithms extension received */
1160
40.3k
    OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);
1161
40.3k
    s->s3.tmp.peer_cert_sigalgs = NULL;
1162
40.3k
    s->s3.tmp.peer_cert_sigalgslen = 0;
1163
1164
40.3k
    return 1;
1165
40.3k
}
1166
1167
#ifndef OPENSSL_NO_SRP
1168
static int init_srp(SSL_CONNECTION *s, unsigned int context)
1169
39.8k
{
1170
39.8k
    OPENSSL_free(s->srp_ctx.login);
1171
39.8k
    s->srp_ctx.login = NULL;
1172
1173
39.8k
    return 1;
1174
39.8k
}
1175
#endif
1176
1177
static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context)
1178
119k
{
1179
119k
    OPENSSL_free(s->ext.peer_ecpointformats);
1180
119k
    s->ext.peer_ecpointformats = NULL;
1181
119k
    s->ext.peer_ecpointformats_len = 0;
1182
1183
119k
    return 1;
1184
119k
}
1185
1186
static int init_etm(SSL_CONNECTION *s, unsigned int context)
1187
119k
{
1188
119k
    s->ext.use_etm = 0;
1189
1190
119k
    return 1;
1191
119k
}
1192
1193
static int init_ems(SSL_CONNECTION *s, unsigned int context)
1194
119k
{
1195
119k
    if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
1196
65
        s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
1197
65
        s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;
1198
65
    }
1199
1200
119k
    return 1;
1201
119k
}
1202
1203
static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent)
1204
84.4k
{
1205
    /*
1206
     * Check extended master secret extension is not dropped on
1207
     * renegotiation.
1208
     */
1209
84.4k
    if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
1210
71.3k
        && (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
84.4k
    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
84.4k
    return 1;
1226
84.4k
}
1227
1228
static int init_certificate_authorities(SSL_CONNECTION *s, unsigned int context)
1229
494
{
1230
494
    sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
1231
494
    s->s3.tmp.peer_ca_names = NULL;
1232
494
    return 1;
1233
494
}
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
90.2k
{
1241
90.2k
    const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);
1242
1243
90.2k
    if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
1244
90.2k
        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
388
{
1269
388
    if (!parse_ca_names(s, pkt))
1270
364
        return 0;
1271
24
    if (PACKET_remaining(pkt) != 0) {
1272
12
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1273
12
        return 0;
1274
12
    }
1275
12
    return 1;
1276
24
}
1277
1278
#ifndef OPENSSL_NO_SRTP
1279
static int init_srtp(SSL_CONNECTION *s, unsigned int context)
1280
141k
{
1281
141k
    if (s->server)
1282
40.1k
        s->srtp_profile = NULL;
1283
1284
141k
    return 1;
1285
141k
}
1286
#endif
1287
1288
static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent)
1289
31.9k
{
1290
31.9k
    if (!sent && SSL_CONNECTION_IS_TLS13(s) && !s->hit) {
1291
80
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1292
80
            SSL_R_MISSING_SIGALGS_EXTENSION);
1293
80
        return 0;
1294
80
    }
1295
1296
31.8k
    return 1;
1297
31.9k
}
1298
1299
static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,
1300
    int sent)
1301
42.2k
{
1302
42.2k
    if (!sent && context == SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) {
1303
38
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1304
38
            SSL_R_MISSING_SUPPORTED_VERSIONS_EXTENSION);
1305
38
        return 0;
1306
38
    }
1307
1308
42.1k
    return 1;
1309
42.2k
}
1310
1311
static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent)
1312
30.9k
{
1313
30.9k
#if !defined(OPENSSL_NO_TLS1_3)
1314
30.9k
    if (!SSL_CONNECTION_IS_TLS13(s))
1315
15.1k
        return 1;
1316
1317
    /* Nothing to do for key_share in an HRR */
1318
15.7k
    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
15.7k
    if (!s->server
1333
13.7k
        && !sent) {
1334
13
        if ((s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1335
13
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_SUITABLE_KEY_SHARE);
1336
13
            return 0;
1337
13
        }
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
15.6k
    if (s->server) {
1378
1.91k
        if (s->s3.peer_tmp != NULL) {
1379
            /* We have a suitable key_share */
1380
1.46k
            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.46k
        } else {
1395
            /* No suitable key_share */
1396
442
            if (s->hello_retry_request == SSL_HRR_NONE && sent
1397
370
                && (!s->hit
1398
370
                    || (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
370
                if (s->s3.group_id_candidate != 0) {
1402
                    /* A shared group exists so send a HelloRetryRequest */
1403
364
                    s->s3.group_id = s->s3.group_id_candidate;
1404
364
                    s->hello_retry_request = SSL_HRR_PENDING;
1405
364
                    return 1;
1406
364
                }
1407
370
            }
1408
78
            if (!s->hit
1409
78
                || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1410
                /* Nothing left we can do - just fail */
1411
78
                SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE : SSL_AD_MISSING_EXTENSION,
1412
78
                    SSL_R_NO_SUITABLE_KEY_SHARE);
1413
78
                return 0;
1414
78
            }
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.46k
        if (s->hello_retry_request == SSL_HRR_PENDING)
1437
63
            s->hello_retry_request = SSL_HRR_COMPLETE;
1438
13.7k
    } 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
13.7k
        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
13.7k
    }
1449
15.2k
#endif /* !defined(OPENSSL_NO_TLS1_3) */
1450
15.2k
    return 1;
1451
15.6k
}
1452
1453
static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context)
1454
368
{
1455
368
    s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1456
368
    return 1;
1457
368
}
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
17
{
1465
17
    EVP_PKEY *mackey = NULL;
1466
17
    EVP_MD_CTX *mctx = NULL;
1467
17
    unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1468
17
    unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1469
17
    unsigned char *early_secret;
1470
    /* ASCII: "res binder", in hex for EBCDIC compatibility */
1471
17
    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
17
    static const unsigned char external_label[] = "\x65\x78\x74\x20\x62\x69\x6E\x64\x65\x72";
1474
17
    const unsigned char *label;
1475
17
    size_t bindersize, labelsize, hashsize;
1476
17
    int hashsizei = EVP_MD_get_size(md);
1477
17
    int ret = -1;
1478
17
    int usepskfored = 0;
1479
17
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1480
1481
    /* Ensure cast to size_t is safe */
1482
17
    if (!ossl_assert(hashsizei > 0)) {
1483
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1484
0
        goto err;
1485
0
    }
1486
17
    hashsize = (size_t)hashsizei;
1487
1488
17
    if (external
1489
0
        && s->early_data_state == SSL_EARLY_DATA_CONNECTING
1490
0
        && s->session->ext.max_early_data == 0
1491
0
        && sess->ext.max_early_data > 0)
1492
0
        usepskfored = 1;
1493
1494
17
    if (external) {
1495
0
        label = external_label;
1496
0
        labelsize = sizeof(external_label) - 1;
1497
17
    } else {
1498
17
        label = resumption_label;
1499
17
        labelsize = sizeof(resumption_label) - 1;
1500
17
    }
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
17
    if (s->server || !external || usepskfored)
1511
17
        early_secret = (unsigned char *)s->early_secret;
1512
0
    else
1513
0
        early_secret = (unsigned char *)sess->early_secret;
1514
1515
17
    if (!tls13_generate_secret(s, md, NULL, sess->master_key,
1516
17
            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
17
    mctx = EVP_MD_CTX_new();
1526
17
    if (mctx == NULL
1527
17
        || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1528
17
        || 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
17
    if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,
1535
17
            hashsize, binderkey, hashsize, 1)) {
1536
        /* SSLfatal() already called */
1537
0
        goto err;
1538
0
    }
1539
1540
    /* Generate the finished key */
1541
17
    if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1542
        /* SSLfatal() already called */
1543
0
        goto err;
1544
0
    }
1545
1546
17
    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
17
    if (s->hello_retry_request == SSL_HRR_PENDING) {
1557
0
        size_t hdatalen;
1558
0
        long hdatalen_l;
1559
0
        void *hdata;
1560
1561
0
        hdatalen = hdatalen_l = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
1562
0
        if (hdatalen_l <= 0) {
1563
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
1564
0
            goto err;
1565
0
        }
1566
1567
        /*
1568
         * For servers the handshake buffer data will include the second
1569
         * ClientHello - which we don't want - so we need to take that bit off.
1570
         */
1571
0
        if (s->server) {
1572
0
            PACKET hashprefix, msg;
1573
1574
            /* Find how many bytes are left after the first two messages */
1575
0
            if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
1576
0
                || !PACKET_forward(&hashprefix, 1)
1577
0
                || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
1578
0
                || !PACKET_forward(&hashprefix, 1)
1579
0
                || !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
1580
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1581
0
                goto err;
1582
0
            }
1583
0
            hdatalen -= PACKET_remaining(&hashprefix);
1584
0
        }
1585
1586
0
        if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
1587
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1588
0
            goto err;
1589
0
        }
1590
0
    }
1591
1592
17
    if (EVP_DigestUpdate(mctx, msgstart, binderoffset) <= 0
1593
17
        || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1594
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1595
0
        goto err;
1596
0
    }
1597
1598
17
    mackey = EVP_PKEY_new_raw_private_key_ex(sctx->libctx, "HMAC",
1599
17
        sctx->propq, finishedkey,
1600
17
        hashsize);
1601
17
    if (mackey == NULL) {
1602
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1603
0
        goto err;
1604
0
    }
1605
1606
17
    if (!sign)
1607
17
        binderout = tmpbinder;
1608
1609
17
    bindersize = hashsize;
1610
17
    if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), sctx->libctx,
1611
17
            sctx->propq, mackey, NULL)
1612
17
            <= 0
1613
17
        || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
1614
17
        || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
1615
17
        || bindersize != hashsize) {
1616
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1617
0
        goto err;
1618
0
    }
1619
1620
17
    if (sign) {
1621
0
        ret = 1;
1622
17
    } else {
1623
        /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
1624
17
        ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
1625
17
        if (!ret)
1626
17
            SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BINDER_DOES_NOT_VERIFY);
1627
17
    }
1628
1629
17
err:
1630
17
    OPENSSL_cleanse(binderkey, sizeof(binderkey));
1631
17
    OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
1632
17
    EVP_PKEY_free(mackey);
1633
17
    EVP_MD_CTX_free(mctx);
1634
1635
17
    return ret;
1636
17
}
1637
1638
static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent)
1639
53.9k
{
1640
53.9k
    if (!sent)
1641
51.1k
        return 1;
1642
1643
2.78k
    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
2.78k
    if (s->max_early_data == 0
1660
0
        || !s->hit
1661
0
        || s->early_data_state != SSL_EARLY_DATA_ACCEPTING
1662
0
        || !s->ext.early_data_ok
1663
0
        || s->hello_retry_request != SSL_HRR_NONE
1664
0
        || (s->allow_early_data_cb != NULL
1665
0
            && !s->allow_early_data_cb(SSL_CONNECTION_GET_USER_SSL(s),
1666
2.78k
                s->allow_early_data_cb_data))) {
1667
2.78k
        s->ext.early_data = SSL_EARLY_DATA_REJECTED;
1668
2.78k
    } 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
2.78k
    return 1;
1679
2.78k
}
1680
1681
static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,
1682
    int sent)
1683
96.7k
{
1684
96.7k
    if (s->session == NULL)
1685
0
        return 1;
1686
1687
    /* MaxFragmentLength defaults to disabled */
1688
96.7k
    if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
1689
95.2k
        s->session->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_DISABLED;
1690
1691
96.7k
    if (USE_MAX_FRAGMENT_LENGTH_EXT(s->session)) {
1692
1.35k
        s->rlayer.rrlmethod->set_max_frag_len(s->rlayer.rrl,
1693
1.35k
            GET_MAX_FRAGMENT_LENGTH(s->session));
1694
1.35k
        s->rlayer.wrlmethod->set_max_frag_len(s->rlayer.wrl,
1695
1.35k
            ssl_get_max_send_fragment(s));
1696
1.35k
    }
1697
1698
96.7k
    return 1;
1699
96.7k
}
1700
1701
static int init_post_handshake_auth(SSL_CONNECTION *s,
1702
    ossl_unused unsigned int context)
1703
368
{
1704
368
    s->post_handshake_auth = SSL_PHA_NONE;
1705
1706
368
    return 1;
1707
368
}
1708
1709
/*
1710
 * If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
1711
 * extension, servers MUST abort the handshake.
1712
 */
1713
static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent)
1714
56.8k
{
1715
56.8k
    if (s->server && sent && s->clienthello != NULL
1716
85
        && !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
1717
18
        SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1718
18
            SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
1719
18
        return 0;
1720
18
    }
1721
1722
56.8k
    return 1;
1723
56.8k
}
1724
1725
static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context)
1726
415
{
1727
415
    memset(sc->ext.compress_certificate_from_peer, 0,
1728
415
        sizeof(sc->ext.compress_certificate_from_peer));
1729
415
    return 1;
1730
415
}
1731
1732
/* The order these are put into the packet imply a preference order: [brotli, zlib, zstd] */
1733
static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,
1734
    unsigned int context,
1735
    X509 *x, size_t chainidx)
1736
84.0k
{
1737
#ifndef OPENSSL_NO_COMP_ALG
1738
    int i;
1739
1740
    if (!ossl_comp_has_alg(0))
1741
        return EXT_RETURN_NOT_SENT;
1742
1743
    /* Server: Don't attempt to compress a non-X509 (i.e. an RPK) */
1744
    if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509) {
1745
        sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
1746
        return EXT_RETURN_NOT_SENT;
1747
    }
1748
1749
    /* Client: If we sent a client cert-type extension, don't indicate compression */
1750
    if (!sc->server && sc->ext.client_cert_type_ctos) {
1751
        sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
1752
        return EXT_RETURN_NOT_SENT;
1753
    }
1754
1755
    /* Do not indicate we support receiving compressed certificates */
1756
    if ((sc->options & SSL_OP_NO_RX_CERTIFICATE_COMPRESSION) != 0)
1757
        return EXT_RETURN_NOT_SENT;
1758
1759
    if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
1760
        return EXT_RETURN_NOT_SENT;
1761
1762
    if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_compress_certificate)
1763
        || !WPACKET_start_sub_packet_u16(pkt)
1764
        || !WPACKET_start_sub_packet_u8(pkt))
1765
        goto err;
1766
1767
    for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
1768
        if (!WPACKET_put_bytes_u16(pkt, sc->cert_comp_prefs[i]))
1769
            goto err;
1770
    }
1771
    if (!WPACKET_close(pkt) || !WPACKET_close(pkt))
1772
        goto err;
1773
1774
    sc->ext.compress_certificate_sent = 1;
1775
    return EXT_RETURN_SENT;
1776
err:
1777
    SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1778
    return EXT_RETURN_FAIL;
1779
#else
1780
84.0k
    return EXT_RETURN_NOT_SENT;
1781
84.0k
#endif
1782
84.0k
}
1783
1784
#ifndef OPENSSL_NO_COMP_ALG
1785
static int tls_comp_in_pref(SSL_CONNECTION *sc, int alg)
1786
{
1787
    int i;
1788
1789
    /* ossl_comp_has_alg() considers 0 as "any" */
1790
    if (alg == 0)
1791
        return 0;
1792
    /* Make sure algorithm is enabled */
1793
    if (!ossl_comp_has_alg(alg))
1794
        return 0;
1795
    /* If no preferences are set, it's ok */
1796
    if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
1797
        return 1;
1798
    /* Find the algorithm */
1799
    for (i = 0; i < TLSEXT_comp_cert_limit; i++)
1800
        if (sc->cert_comp_prefs[i] == alg)
1801
            return 1;
1802
    return 0;
1803
}
1804
#endif
1805
1806
int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt, unsigned int context,
1807
    X509 *x, size_t chainidx)
1808
79
{
1809
#ifndef OPENSSL_NO_COMP_ALG
1810
    PACKET supported_comp_algs;
1811
    unsigned int comp;
1812
    int already_set[TLSEXT_comp_cert_limit];
1813
    int j = 0;
1814
1815
    /* If no algorithms are available, ignore the extension */
1816
    if (!ossl_comp_has_alg(0))
1817
        return 1;
1818
1819
    /* Don't attempt to compress a non-X509 (i.e. an RPK) */
1820
    if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509)
1821
        return 1;
1822
    if (!sc->server && sc->ext.client_cert_type != TLSEXT_cert_type_x509)
1823
        return 1;
1824
1825
    /* Ignore the extension and don't send compressed certificates */
1826
    if ((sc->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
1827
        return 1;
1828
1829
    if (!PACKET_as_length_prefixed_1(pkt, &supported_comp_algs)
1830
        || PACKET_remaining(&supported_comp_algs) == 0) {
1831
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1832
        return 0;
1833
    }
1834
1835
    memset(already_set, 0, sizeof(already_set));
1836
    /*
1837
     * The preference array has real values, so take a look at each
1838
     * value coming in, and make sure it's in our preference list
1839
     * The array is 0 (i.e. "none") terminated
1840
     * The preference list only contains supported algorithms
1841
     */
1842
    while (PACKET_get_net_2(&supported_comp_algs, &comp)) {
1843
        if (tls_comp_in_pref(sc, comp) && !already_set[comp]) {
1844
            sc->ext.compress_certificate_from_peer[j++] = comp;
1845
            already_set[comp] = 1;
1846
        }
1847
    }
1848
    if (PACKET_remaining(&supported_comp_algs) != 0) {
1849
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1850
        return 0;
1851
    }
1852
#endif
1853
79
    return 1;
1854
79
}
1855
1856
static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context)
1857
132k
{
1858
    /* Only reset when parsing client hello */
1859
132k
    if (sc->server) {
1860
36.4k
        sc->ext.server_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
1861
36.4k
        sc->ext.server_cert_type = TLSEXT_cert_type_x509;
1862
36.4k
    }
1863
132k
    return 1;
1864
132k
}
1865
1866
static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context)
1867
132k
{
1868
    /* Only reset when parsing client hello */
1869
132k
    if (sc->server) {
1870
36.4k
        sc->ext.client_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
1871
36.4k
        sc->ext.client_cert_type = TLSEXT_cert_type_x509;
1872
36.4k
    }
1873
132k
    return 1;
1874
132k
}