Coverage Report

Created: 2026-07-23 06:28

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