Coverage Report

Created: 2025-07-11 06:57

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