Coverage Report

Created: 2025-12-31 06:58

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