Coverage Report

Created: 2025-12-31 06:58

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