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