Coverage Report

Created: 2025-08-28 07:07

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