xref: /freebsd/crypto/openssl/ssl/statem/extensions.c (revision 78e936b2d0b5e6554425009199be31e76bc67c10)
1 /*
2  * Copyright 2016-2026 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 
609         /* The server must tolerate the unknown extension and complete. */
610         if (thisex == NULL)
611             continue;
612 
613         idx = thisex - raw_extensions;
614         /*-
615          * Check that we requested this extension (if appropriate). Requests can
616          * be sent in the ClientHello and CertificateRequest. Unsolicited
617          * extensions can be sent in the NewSessionTicket. We only do this for
618          * the built-in extensions. Custom extensions have a different but
619          * similar check elsewhere.
620          * Special cases:
621          * - The HRR cookie extension is unsolicited
622          * - The renegotiate extension is unsolicited (the client signals
623          *   support via an SCSV)
624          * - The signed_certificate_timestamp extension can be provided by a
625          * custom extension or by the built-in version. We let the extension
626          * itself handle unsolicited response checks.
627          */
628         if (idx < OSSL_NELEM(ext_defs)
629             && (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) == 0
630             && type != TLSEXT_TYPE_cookie
631             && type != TLSEXT_TYPE_renegotiate
632             && type != TLSEXT_TYPE_signed_certificate_timestamp
633             && (s->ext.extflags[idx] & SSL_EXT_FLAG_SENT) == 0
634 #ifndef OPENSSL_NO_GOST
635             && !((context & SSL_EXT_TLS1_2_SERVER_HELLO) != 0
636                 && type == TLSEXT_TYPE_cryptopro_bug)
637 #endif
638         ) {
639             SSLfatal(s, SSL_AD_UNSUPPORTED_EXTENSION,
640                 SSL_R_UNSOLICITED_EXTENSION);
641             goto err;
642         }
643         thisex->data = extension;
644         thisex->present = 1;
645         thisex->type = type;
646         thisex->received_order = i++;
647         if (s->ext.debug_cb)
648             s->ext.debug_cb(SSL_CONNECTION_GET_USER_SSL(s), !s->server,
649                 thisex->type, PACKET_data(&thisex->data),
650                 (int)PACKET_remaining(&thisex->data),
651                 s->ext.debug_arg);
652     }
653 
654     if (init) {
655         /*
656          * Initialise all known extensions relevant to this context,
657          * whether we have found them or not
658          */
659         for (thisexd = ext_defs, i = 0; i < OSSL_NELEM(ext_defs);
660             i++, thisexd++) {
661             if (thisexd->init != NULL && (thisexd->context & context) != 0
662                 && extension_is_relevant(s, thisexd->context, context)
663                 && !thisexd->init(s, context)) {
664                 /* SSLfatal() already called */
665                 goto err;
666             }
667         }
668     }
669 
670     *res = raw_extensions;
671     if (len != NULL)
672         *len = num_exts;
673     return 1;
674 
675 err:
676     OPENSSL_free(raw_extensions);
677     return 0;
678 }
679 
680 /*
681  * Runs the parser for a given extension with index |idx|. |exts| contains the
682  * list of all parsed extensions previously collected by
683  * tls_collect_extensions(). The parser is only run if it is applicable for the
684  * given |context| and the parser has not already been run. If this is for a
685  * Certificate message, then we also provide the parser with the relevant
686  * Certificate |x| and its position in the |chainidx| with 0 being the first
687  * Certificate. Returns 1 on success or 0 on failure. If an extension is not
688  * present this counted as success.
689  */
tls_parse_extension(SSL_CONNECTION * s,TLSEXT_INDEX idx,int context,RAW_EXTENSION * exts,X509 * x,size_t chainidx)690 int tls_parse_extension(SSL_CONNECTION *s, TLSEXT_INDEX idx, int context,
691     RAW_EXTENSION *exts, X509 *x, size_t chainidx)
692 {
693     RAW_EXTENSION *currext = &exts[idx];
694     int (*parser)(SSL_CONNECTION *s, PACKET *pkt, unsigned int context, X509 *x,
695         size_t chainidx)
696         = NULL;
697 
698     /* Skip if the extension is not present */
699     if (!currext->present)
700         return 1;
701 
702     /* Skip if we've already parsed this extension */
703     if (currext->parsed)
704         return 1;
705 
706     currext->parsed = 1;
707 
708     if (idx < OSSL_NELEM(ext_defs)) {
709         /* We are handling a built-in extension */
710         const EXTENSION_DEFINITION *extdef = &ext_defs[idx];
711 
712         /* Check if extension is defined for our protocol. If not, skip */
713         if (!extension_is_relevant(s, extdef->context, context))
714             return 1;
715 
716         parser = s->server ? extdef->parse_ctos : extdef->parse_stoc;
717 
718         if (parser != NULL)
719             return parser(s, &currext->data, context, x, chainidx);
720 
721         /*
722          * If the parser is NULL we fall through to the custom extension
723          * processing
724          */
725     }
726 
727     /* Parse custom extensions */
728     return custom_ext_parse(s, context, currext->type,
729         PACKET_data(&currext->data),
730         PACKET_remaining(&currext->data),
731         x, chainidx);
732 }
733 
734 /*
735  * Parse all remaining extensions that have not yet been parsed. Also calls the
736  * finalisation for all extensions at the end if |fin| is nonzero, whether we
737  * collected them or not. Returns 1 for success or 0 for failure. If we are
738  * working on a Certificate message then we also pass the Certificate |x| and
739  * its position in the |chainidx|, with 0 being the first certificate.
740  */
tls_parse_all_extensions(SSL_CONNECTION * s,int context,RAW_EXTENSION * exts,X509 * x,size_t chainidx,int fin)741 int tls_parse_all_extensions(SSL_CONNECTION *s, int context,
742     RAW_EXTENSION *exts, X509 *x,
743     size_t chainidx, int fin)
744 {
745     size_t i, numexts = OSSL_NELEM(ext_defs);
746     const EXTENSION_DEFINITION *thisexd;
747 
748     /* Calculate the number of extensions in the extensions list */
749     numexts += s->cert->custext.meths_count;
750 
751     /* Parse each extension in turn */
752     for (i = 0; i < numexts; i++) {
753         if (!tls_parse_extension(s, i, context, exts, x, chainidx)) {
754             /* SSLfatal() already called */
755             return 0;
756         }
757     }
758 
759     if (fin) {
760         /*
761          * Finalise all known extensions relevant to this context,
762          * whether we have found them or not
763          */
764         for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs);
765             i++, thisexd++) {
766             if (thisexd->final != NULL && (thisexd->context & context) != 0
767                 && !thisexd->final(s, context, exts[i].present)) {
768                 /* SSLfatal() already called */
769                 return 0;
770             }
771         }
772     }
773 
774     return 1;
775 }
776 
should_add_extension(SSL_CONNECTION * s,unsigned int extctx,unsigned int thisctx,int max_version)777 int should_add_extension(SSL_CONNECTION *s, unsigned int extctx,
778     unsigned int thisctx, int max_version)
779 {
780     /* Skip if not relevant for our context */
781     if ((extctx & thisctx) == 0)
782         return 0;
783 
784     /* Check if this extension is defined for our protocol. If not, skip */
785     if (!extension_is_relevant(s, extctx, thisctx)
786         || ((extctx & SSL_EXT_TLS1_3_ONLY) != 0
787             && (thisctx & SSL_EXT_CLIENT_HELLO) != 0
788             && (SSL_CONNECTION_IS_DTLS(s) || max_version < TLS1_3_VERSION)))
789         return 0;
790 
791     return 1;
792 }
793 
794 /*
795  * Construct all the extensions relevant to the current |context| and write
796  * them to |pkt|. If this is an extension for a Certificate in a Certificate
797  * message, then |x| will be set to the Certificate we are handling, and
798  * |chainidx| will indicate the position in the chainidx we are processing (with
799  * 0 being the first in the chain). Returns 1 on success or 0 on failure. On a
800  * failure construction stops at the first extension to fail to construct.
801  */
tls_construct_extensions(SSL_CONNECTION * s,WPACKET * pkt,unsigned int context,X509 * x,size_t chainidx)802 int tls_construct_extensions(SSL_CONNECTION *s, WPACKET *pkt,
803     unsigned int context,
804     X509 *x, size_t chainidx)
805 {
806     size_t i;
807     int min_version, max_version = 0, reason;
808     const EXTENSION_DEFINITION *thisexd;
809     int for_comp = (context & SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION) != 0;
810 
811     if (!WPACKET_start_sub_packet_u16(pkt)
812         /*
813          * If extensions are of zero length then we don't even add the
814          * extensions length bytes to a ClientHello/ServerHello
815          * (for non-TLSv1.3).
816          */
817         || ((context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO)) != 0
818             && !WPACKET_set_flags(pkt,
819                 WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
820         if (!for_comp)
821             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
822         return 0;
823     }
824 
825     if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
826         reason = ssl_get_min_max_version(s, &min_version, &max_version, NULL);
827         if (reason != 0) {
828             if (!for_comp)
829                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, reason);
830             return 0;
831         }
832     }
833 
834     /* Add custom extensions first */
835     if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
836         /* On the server side with initialise during ClientHello parsing */
837         custom_ext_init(&s->cert->custext);
838     }
839     if (!custom_ext_add(s, context, pkt, x, chainidx, max_version)) {
840         /* SSLfatal() already called */
841         return 0;
842     }
843 
844     for (i = 0, thisexd = ext_defs; i < OSSL_NELEM(ext_defs); i++, thisexd++) {
845         EXT_RETURN (*construct)(SSL_CONNECTION *s, WPACKET *pkt,
846             unsigned int context,
847             X509 *x, size_t chainidx);
848         EXT_RETURN ret;
849 
850         /* Skip if not relevant for our context */
851         if (!should_add_extension(s, thisexd->context, context, max_version))
852             continue;
853 
854         construct = s->server ? thisexd->construct_stoc
855                               : thisexd->construct_ctos;
856 
857         if (construct == NULL)
858             continue;
859 
860         ret = construct(s, pkt, context, x, chainidx);
861         if (ret == EXT_RETURN_FAIL) {
862             /* SSLfatal() already called */
863             return 0;
864         }
865         if (ret == EXT_RETURN_SENT
866             && (context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST | SSL_EXT_TLS1_3_NEW_SESSION_TICKET)) != 0)
867             s->ext.extflags[i] |= SSL_EXT_FLAG_SENT;
868     }
869 
870     if (!WPACKET_close(pkt)) {
871         if (!for_comp)
872             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
873         return 0;
874     }
875 
876     return 1;
877 }
878 
879 /*
880  * Built in extension finalisation and initialisation functions. All initialise
881  * or finalise the associated extension type for the given |context|. For
882  * finalisers |sent| is set to 1 if we saw the extension during parsing, and 0
883  * otherwise. These functions return 1 on success or 0 on failure.
884  */
885 
final_renegotiate(SSL_CONNECTION * s,unsigned int context,int sent)886 static int final_renegotiate(SSL_CONNECTION *s, unsigned int context, int sent)
887 {
888     if (!s->server) {
889         /*
890          * Check if we can connect to a server that doesn't support safe
891          * renegotiation
892          */
893         if (!(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
894             && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
895             && !sent) {
896             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
897                 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
898             return 0;
899         }
900 
901         return 1;
902     }
903 
904     /* Need RI if renegotiating */
905     if (s->renegotiate
906         && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
907         && !sent) {
908         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
909             SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
910         return 0;
911     }
912 
913     return 1;
914 }
915 
ssl_tsan_decr(const SSL_CTX * ctx,TSAN_QUALIFIER int * stat)916 static ossl_inline void ssl_tsan_decr(const SSL_CTX *ctx,
917     TSAN_QUALIFIER int *stat)
918 {
919     if (ssl_tsan_lock(ctx)) {
920         tsan_decr(stat);
921         ssl_tsan_unlock(ctx);
922     }
923 }
924 
init_server_name(SSL_CONNECTION * s,unsigned int context)925 static int init_server_name(SSL_CONNECTION *s, unsigned int context)
926 {
927     if (s->server) {
928         s->servername_done = 0;
929 
930         OPENSSL_free(s->ext.hostname);
931         s->ext.hostname = NULL;
932     }
933 
934     return 1;
935 }
936 
final_server_name(SSL_CONNECTION * s,unsigned int context,int sent)937 static int final_server_name(SSL_CONNECTION *s, unsigned int context, int sent)
938 {
939     int ret = SSL_TLSEXT_ERR_NOACK;
940     int altmp = SSL_AD_UNRECOGNIZED_NAME;
941     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
942     SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
943     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
944     int was_ticket = (SSL_get_options(ssl) & SSL_OP_NO_TICKET) == 0;
945 
946     if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {
947         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
948         return 0;
949     }
950 
951     if (sctx->ext.servername_cb != NULL)
952         ret = sctx->ext.servername_cb(ussl, &altmp,
953             sctx->ext.servername_arg);
954     else if (s->session_ctx->ext.servername_cb != NULL)
955         ret = s->session_ctx->ext.servername_cb(ussl, &altmp,
956             s->session_ctx->ext.servername_arg);
957 
958     /*
959      * For servers, propagate the SNI hostname from the temporary
960      * storage in the SSL to the persistent SSL_SESSION, now that we
961      * know we accepted it.
962      * Clients make this copy when parsing the server's response to
963      * the extension, which is when they find out that the negotiation
964      * was successful.
965      */
966     if (s->server) {
967         if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {
968             /* Only store the hostname in the session if we accepted it. */
969             OPENSSL_free(s->session->ext.hostname);
970             s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
971             if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {
972                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
973             }
974         }
975     }
976 
977     /*
978      * If we switched contexts (whether here or in the client_hello callback),
979      * move the sess_accept increment from the session_ctx to the new
980      * context, to avoid the confusing situation of having sess_accept_good
981      * exceed sess_accept (zero) for the new context.
982      */
983     if (SSL_IS_FIRST_HANDSHAKE(s) && sctx != s->session_ctx
984         && s->hello_retry_request == SSL_HRR_NONE) {
985         ssl_tsan_counter(sctx, &sctx->stats.sess_accept);
986         ssl_tsan_decr(s->session_ctx, &s->session_ctx->stats.sess_accept);
987     }
988 
989     /*
990      * If we're expecting to send a ticket, and tickets were previously enabled,
991      * and now tickets are disabled, then turn off expected ticket.
992      * Also, if this is not a resumption, create a new session ID
993      */
994     if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected
995         && was_ticket && (SSL_get_options(ssl) & SSL_OP_NO_TICKET) != 0) {
996         s->ext.ticket_expected = 0;
997         if (!s->hit) {
998             SSL_SESSION *ss = SSL_get_session(ssl);
999 
1000             if (ss != NULL) {
1001                 OPENSSL_free(ss->ext.tick);
1002                 ss->ext.tick = NULL;
1003                 ss->ext.ticklen = 0;
1004                 ss->ext.tick_lifetime_hint = 0;
1005                 ss->ext.tick_age_add = 0;
1006                 if (!ssl_generate_session_id(s, ss)) {
1007                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1008                     return 0;
1009                 }
1010             } else {
1011                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1012                 return 0;
1013             }
1014         }
1015     }
1016 
1017     switch (ret) {
1018     case SSL_TLSEXT_ERR_ALERT_FATAL:
1019         SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);
1020         return 0;
1021 
1022     case SSL_TLSEXT_ERR_ALERT_WARNING:
1023         /* TLSv1.3 doesn't have warning alerts so we suppress this */
1024         if (!SSL_CONNECTION_IS_TLS13(s))
1025             ssl3_send_alert(s, SSL3_AL_WARNING, altmp);
1026         s->servername_done = 0;
1027         return 1;
1028 
1029     case SSL_TLSEXT_ERR_NOACK:
1030         s->servername_done = 0;
1031         return 1;
1032 
1033     default:
1034         return 1;
1035     }
1036 }
1037 
final_ec_pt_formats(SSL_CONNECTION * s,unsigned int context,int sent)1038 static int final_ec_pt_formats(SSL_CONNECTION *s, unsigned int context,
1039     int sent)
1040 {
1041     unsigned long alg_k, alg_a;
1042 
1043     if (s->server)
1044         return 1;
1045 
1046     alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
1047     alg_a = s->s3.tmp.new_cipher->algorithm_auth;
1048 
1049     /*
1050      * If we are client and using an elliptic curve cryptography cipher
1051      * suite, then if server returns an EC point formats lists extension it
1052      * must contain uncompressed.
1053      */
1054     if (s->ext.ecpointformats != NULL
1055         && s->ext.ecpointformats_len > 0
1056         && s->ext.peer_ecpointformats != NULL
1057         && s->ext.peer_ecpointformats_len > 0
1058         && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
1059         /* we are using an ECC cipher */
1060         size_t i;
1061         unsigned char *list = s->ext.peer_ecpointformats;
1062 
1063         for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {
1064             if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
1065                 break;
1066         }
1067         if (i == s->ext.peer_ecpointformats_len) {
1068             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1069                 SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
1070             return 0;
1071         }
1072     }
1073 
1074     return 1;
1075 }
1076 
init_session_ticket(SSL_CONNECTION * s,unsigned int context)1077 static int init_session_ticket(SSL_CONNECTION *s, unsigned int context)
1078 {
1079     if (!s->server)
1080         s->ext.ticket_expected = 0;
1081 
1082     return 1;
1083 }
1084 
1085 #ifndef OPENSSL_NO_OCSP
init_status_request(SSL_CONNECTION * s,unsigned int context)1086 static int init_status_request(SSL_CONNECTION *s, unsigned int context)
1087 {
1088     if (s->server) {
1089         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
1090     } else {
1091         /*
1092          * Ensure we get sensible values passed to tlsext_status_cb in the event
1093          * that we don't receive a status message
1094          */
1095         OPENSSL_free(s->ext.ocsp.resp);
1096         s->ext.ocsp.resp = NULL;
1097         s->ext.ocsp.resp_len = 0;
1098     }
1099 
1100     return 1;
1101 }
1102 #endif
1103 
1104 #ifndef OPENSSL_NO_NEXTPROTONEG
init_npn(SSL_CONNECTION * s,unsigned int context)1105 static int init_npn(SSL_CONNECTION *s, unsigned int context)
1106 {
1107     s->s3.npn_seen = 0;
1108 
1109     return 1;
1110 }
1111 #endif
1112 
init_alpn(SSL_CONNECTION * s,unsigned int context)1113 static int init_alpn(SSL_CONNECTION *s, unsigned int context)
1114 {
1115     OPENSSL_free(s->s3.alpn_selected);
1116     s->s3.alpn_selected = NULL;
1117     s->s3.alpn_selected_len = 0;
1118     if (s->server) {
1119         OPENSSL_free(s->s3.alpn_proposed);
1120         s->s3.alpn_proposed = NULL;
1121         s->s3.alpn_proposed_len = 0;
1122     }
1123     return 1;
1124 }
1125 
final_alpn(SSL_CONNECTION * s,unsigned int context,int sent)1126 static int final_alpn(SSL_CONNECTION *s, unsigned int context, int sent)
1127 {
1128     if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
1129         s->ext.early_data_ok = 0;
1130 
1131     if (!s->server || !SSL_CONNECTION_IS_TLS13(s))
1132         return 1;
1133 
1134     /*
1135      * Call alpn_select callback if needed.  Has to be done after SNI and
1136      * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
1137      * we also have to do this before we decide whether to accept early_data.
1138      * In TLSv1.3 we've already negotiated our cipher so we do this call now.
1139      * For < TLSv1.3 we defer it until after cipher negotiation.
1140      *
1141      * On failure SSLfatal() already called.
1142      */
1143     return tls_handle_alpn(s);
1144 }
1145 
init_sig_algs(SSL_CONNECTION * s,unsigned int context)1146 static int init_sig_algs(SSL_CONNECTION *s, unsigned int context)
1147 {
1148     /* Clear any signature algorithms extension received */
1149     OPENSSL_free(s->s3.tmp.peer_sigalgs);
1150     s->s3.tmp.peer_sigalgs = NULL;
1151     s->s3.tmp.peer_sigalgslen = 0;
1152 
1153     return 1;
1154 }
1155 
init_sig_algs_cert(SSL_CONNECTION * s,ossl_unused unsigned int context)1156 static int init_sig_algs_cert(SSL_CONNECTION *s,
1157     ossl_unused unsigned int context)
1158 {
1159     /* Clear any signature algorithms extension received */
1160     OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);
1161     s->s3.tmp.peer_cert_sigalgs = NULL;
1162     s->s3.tmp.peer_cert_sigalgslen = 0;
1163 
1164     return 1;
1165 }
1166 
1167 #ifndef OPENSSL_NO_SRP
init_srp(SSL_CONNECTION * s,unsigned int context)1168 static int init_srp(SSL_CONNECTION *s, unsigned int context)
1169 {
1170     OPENSSL_free(s->srp_ctx.login);
1171     s->srp_ctx.login = NULL;
1172 
1173     return 1;
1174 }
1175 #endif
1176 
init_ec_point_formats(SSL_CONNECTION * s,unsigned int context)1177 static int init_ec_point_formats(SSL_CONNECTION *s, unsigned int context)
1178 {
1179     OPENSSL_free(s->ext.peer_ecpointformats);
1180     s->ext.peer_ecpointformats = NULL;
1181     s->ext.peer_ecpointformats_len = 0;
1182 
1183     return 1;
1184 }
1185 
init_etm(SSL_CONNECTION * s,unsigned int context)1186 static int init_etm(SSL_CONNECTION *s, unsigned int context)
1187 {
1188     s->ext.use_etm = 0;
1189 
1190     return 1;
1191 }
1192 
init_ems(SSL_CONNECTION * s,unsigned int context)1193 static int init_ems(SSL_CONNECTION *s, unsigned int context)
1194 {
1195     if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
1196         s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
1197         s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;
1198     }
1199 
1200     return 1;
1201 }
1202 
final_ems(SSL_CONNECTION * s,unsigned int context,int sent)1203 static int final_ems(SSL_CONNECTION *s, unsigned int context, int sent)
1204 {
1205     /*
1206      * Check extended master secret extension is not dropped on
1207      * renegotiation.
1208      */
1209     if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
1210         && (s->s3.flags & TLS1_FLAGS_REQUIRED_EXTMS)) {
1211         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1212         return 0;
1213     }
1214     if (!s->server && s->hit) {
1215         /*
1216          * Check extended master secret extension is consistent with
1217          * original session.
1218          */
1219         if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) != !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
1220             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1221             return 0;
1222         }
1223     }
1224 
1225     return 1;
1226 }
1227 
init_certificate_authorities(SSL_CONNECTION * s,unsigned int context)1228 static int init_certificate_authorities(SSL_CONNECTION *s, unsigned int context)
1229 {
1230     sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
1231     s->s3.tmp.peer_ca_names = NULL;
1232     return 1;
1233 }
1234 
tls_construct_certificate_authorities(SSL_CONNECTION * s,WPACKET * pkt,unsigned int context,X509 * x,size_t chainidx)1235 static EXT_RETURN tls_construct_certificate_authorities(SSL_CONNECTION *s,
1236     WPACKET *pkt,
1237     unsigned int context,
1238     X509 *x,
1239     size_t chainidx)
1240 {
1241     const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);
1242 
1243     if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
1244         return EXT_RETURN_NOT_SENT;
1245 
1246     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)
1247         || !WPACKET_start_sub_packet_u16(pkt)) {
1248         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1249         return EXT_RETURN_FAIL;
1250     }
1251 
1252     if (!construct_ca_names(s, ca_sk, pkt)) {
1253         /* SSLfatal() already called */
1254         return EXT_RETURN_FAIL;
1255     }
1256 
1257     if (!WPACKET_close(pkt)) {
1258         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1259         return EXT_RETURN_FAIL;
1260     }
1261 
1262     return EXT_RETURN_SENT;
1263 }
1264 
tls_parse_certificate_authorities(SSL_CONNECTION * s,PACKET * pkt,unsigned int context,X509 * x,size_t chainidx)1265 static int tls_parse_certificate_authorities(SSL_CONNECTION *s, PACKET *pkt,
1266     unsigned int context, X509 *x,
1267     size_t chainidx)
1268 {
1269     if (!parse_ca_names(s, pkt))
1270         return 0;
1271     if (PACKET_remaining(pkt) != 0) {
1272         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1273         return 0;
1274     }
1275     return 1;
1276 }
1277 
1278 #ifndef OPENSSL_NO_SRTP
init_srtp(SSL_CONNECTION * s,unsigned int context)1279 static int init_srtp(SSL_CONNECTION *s, unsigned int context)
1280 {
1281     if (s->server)
1282         s->srtp_profile = NULL;
1283 
1284     return 1;
1285 }
1286 #endif
1287 
final_sig_algs(SSL_CONNECTION * s,unsigned int context,int sent)1288 static int final_sig_algs(SSL_CONNECTION *s, unsigned int context, int sent)
1289 {
1290     if (!sent && SSL_CONNECTION_IS_TLS13(s) && !s->hit) {
1291         SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1292             SSL_R_MISSING_SIGALGS_EXTENSION);
1293         return 0;
1294     }
1295 
1296     return 1;
1297 }
1298 
final_supported_versions(SSL_CONNECTION * s,unsigned int context,int sent)1299 static int final_supported_versions(SSL_CONNECTION *s, unsigned int context,
1300     int sent)
1301 {
1302     if (!sent && context == SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) {
1303         SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1304             SSL_R_MISSING_SUPPORTED_VERSIONS_EXTENSION);
1305         return 0;
1306     }
1307 
1308     return 1;
1309 }
1310 
final_key_share(SSL_CONNECTION * s,unsigned int context,int sent)1311 static int final_key_share(SSL_CONNECTION *s, unsigned int context, int sent)
1312 {
1313 #if !defined(OPENSSL_NO_TLS1_3)
1314     if (!SSL_CONNECTION_IS_TLS13(s))
1315         return 1;
1316 
1317     /* Nothing to do for key_share in an HRR */
1318     if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
1319         return 1;
1320 
1321     /*
1322      * If
1323      *     we are a client
1324      *     AND
1325      *     we have no key_share
1326      *     AND
1327      *     (we are not resuming
1328      *      OR the kex_mode doesn't allow non key_share resumes)
1329      * THEN
1330      *     fail;
1331      */
1332     if (!s->server
1333         && !sent) {
1334         if ((s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1335             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_SUITABLE_KEY_SHARE);
1336             return 0;
1337         }
1338         if (!s->hit) {
1339             SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_NO_SUITABLE_KEY_SHARE);
1340             return 0;
1341         }
1342     }
1343     /*
1344      * IF
1345      *     we are a server
1346      * THEN
1347      *     IF
1348      *         we have a suitable key_share
1349      *     THEN
1350      *         IF
1351      *             we are stateless AND we have no cookie
1352      *         THEN
1353      *             send a HelloRetryRequest
1354      *     ELSE
1355      *         IF
1356      *             we didn't already send a HelloRetryRequest
1357      *             AND
1358      *             the client sent a key_share extension
1359      *             AND
1360      *             (we are not resuming
1361      *              OR the kex_mode allows key_share resumes)
1362      *             AND
1363      *             a shared group exists
1364      *         THEN
1365      *             send a HelloRetryRequest
1366      *         ELSE IF
1367      *             we are not resuming
1368      *             OR
1369      *             the kex_mode doesn't allow non key_share resumes
1370      *         THEN
1371      *             fail
1372      *         ELSE IF
1373      *             we are stateless AND we have no cookie
1374      *         THEN
1375      *             send a HelloRetryRequest
1376      */
1377     if (s->server) {
1378         if (s->s3.peer_tmp != NULL) {
1379             /* We have a suitable key_share */
1380             if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1381                 && !s->ext.cookieok) {
1382                 if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1383                     /*
1384                      * If we are stateless then we wouldn't know about any
1385                      * previously sent HRR - so how can this be anything other
1386                      * than 0?
1387                      */
1388                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1389                     return 0;
1390                 }
1391                 s->hello_retry_request = SSL_HRR_PENDING;
1392                 return 1;
1393             }
1394         } else {
1395             /* No suitable key_share */
1396             if (s->hello_retry_request == SSL_HRR_NONE && sent
1397                 && (!s->hit
1398                     || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE) != 0)) {
1399 
1400                 /* Did we detect group overlap in tls_parse_ctos_key_share ? */
1401                 if (s->s3.group_id_candidate != 0) {
1402                     /* A shared group exists so send a HelloRetryRequest */
1403                     s->s3.group_id = s->s3.group_id_candidate;
1404                     s->hello_retry_request = SSL_HRR_PENDING;
1405                     return 1;
1406                 }
1407             }
1408             if (!s->hit
1409                 || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1410                 /* Nothing left we can do - just fail */
1411                 SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE : SSL_AD_MISSING_EXTENSION,
1412                     SSL_R_NO_SUITABLE_KEY_SHARE);
1413                 return 0;
1414             }
1415 
1416             if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1417                 && !s->ext.cookieok) {
1418                 if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1419                     /*
1420                      * If we are stateless then we wouldn't know about any
1421                      * previously sent HRR - so how can this be anything other
1422                      * than 0?
1423                      */
1424                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1425                     return 0;
1426                 }
1427                 s->hello_retry_request = SSL_HRR_PENDING;
1428                 return 1;
1429             }
1430         }
1431 
1432         /*
1433          * We have a key_share so don't send any more HelloRetryRequest
1434          * messages
1435          */
1436         if (s->hello_retry_request == SSL_HRR_PENDING)
1437             s->hello_retry_request = SSL_HRR_COMPLETE;
1438     } else {
1439         /*
1440          * For a client side resumption with no key_share we need to generate
1441          * the handshake secret (otherwise this is done during key_share
1442          * processing).
1443          */
1444         if (!sent && !tls13_generate_handshake_secret(s, NULL, 0)) {
1445             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1446             return 0;
1447         }
1448     }
1449 #endif /* !defined(OPENSSL_NO_TLS1_3) */
1450     return 1;
1451 }
1452 
init_psk_kex_modes(SSL_CONNECTION * s,unsigned int context)1453 static int init_psk_kex_modes(SSL_CONNECTION *s, unsigned int context)
1454 {
1455     s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1456     return 1;
1457 }
1458 
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)1459 int tls_psk_do_binder(SSL_CONNECTION *s, const EVP_MD *md,
1460     const unsigned char *msgstart,
1461     size_t binderoffset, const unsigned char *binderin,
1462     unsigned char *binderout, SSL_SESSION *sess, int sign,
1463     int external)
1464 {
1465     EVP_PKEY *mackey = NULL;
1466     EVP_MD_CTX *mctx = NULL;
1467     unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1468     unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1469     unsigned char *early_secret;
1470     /* ASCII: "res binder", in hex for EBCDIC compatibility */
1471     static const unsigned char resumption_label[] = "\x72\x65\x73\x20\x62\x69\x6E\x64\x65\x72";
1472     /* ASCII: "ext binder", in hex for EBCDIC compatibility */
1473     static const unsigned char external_label[] = "\x65\x78\x74\x20\x62\x69\x6E\x64\x65\x72";
1474     const unsigned char *label;
1475     size_t bindersize, labelsize, hashsize;
1476     int hashsizei = EVP_MD_get_size(md);
1477     int ret = -1;
1478     int usepskfored = 0;
1479     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1480 
1481     /* Ensure cast to size_t is safe */
1482     if (!ossl_assert(hashsizei > 0)) {
1483         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1484         goto err;
1485     }
1486     hashsize = (size_t)hashsizei;
1487 
1488     if (external
1489         && s->early_data_state == SSL_EARLY_DATA_CONNECTING
1490         && s->session->ext.max_early_data == 0
1491         && sess->ext.max_early_data > 0)
1492         usepskfored = 1;
1493 
1494     if (external) {
1495         label = external_label;
1496         labelsize = sizeof(external_label) - 1;
1497     } else {
1498         label = resumption_label;
1499         labelsize = sizeof(resumption_label) - 1;
1500     }
1501 
1502     /*
1503      * Generate the early_secret. On the server side we've selected a PSK to
1504      * resume with (internal or external) so we always do this. On the client
1505      * side we do this for a non-external (i.e. resumption) PSK or external PSK
1506      * that will be used for early_data so that it is in place for sending early
1507      * data. For client side external PSK not being used for early_data we
1508      * generate it but store it away for later use.
1509      */
1510     if (s->server || !external || usepskfored)
1511         early_secret = (unsigned char *)s->early_secret;
1512     else
1513         early_secret = (unsigned char *)sess->early_secret;
1514 
1515     if (!tls13_generate_secret(s, md, NULL, sess->master_key,
1516             sess->master_key_length, early_secret)) {
1517         /* SSLfatal() already called */
1518         goto err;
1519     }
1520 
1521     /*
1522      * Create the handshake hash for the binder key...the messages so far are
1523      * empty!
1524      */
1525     mctx = EVP_MD_CTX_new();
1526     if (mctx == NULL
1527         || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1528         || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1529         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1530         goto err;
1531     }
1532 
1533     /* Generate the binder key */
1534     if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,
1535             hashsize, binderkey, hashsize, 1)) {
1536         /* SSLfatal() already called */
1537         goto err;
1538     }
1539 
1540     /* Generate the finished key */
1541     if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1542         /* SSLfatal() already called */
1543         goto err;
1544     }
1545 
1546     if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
1547         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1548         goto err;
1549     }
1550 
1551     /*
1552      * Get a hash of the ClientHello up to the start of the binders. If we are
1553      * following a HelloRetryRequest then this includes the hash of the first
1554      * ClientHello and the HelloRetryRequest itself.
1555      */
1556     if (s->hello_retry_request == SSL_HRR_PENDING) {
1557         size_t hdatalen;
1558         long hdatalen_l;
1559         void *hdata;
1560 
1561         hdatalen = hdatalen_l = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
1562         if (hdatalen_l <= 0) {
1563             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
1564             goto err;
1565         }
1566 
1567         /*
1568          * For servers the handshake buffer data will include the second
1569          * ClientHello - which we don't want - so we need to take that bit off.
1570          */
1571         if (s->server) {
1572             PACKET hashprefix, msg;
1573 
1574             /* Find how many bytes are left after the first two messages */
1575             if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
1576                 || !PACKET_forward(&hashprefix, 1)
1577                 || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
1578                 || !PACKET_forward(&hashprefix, 1)
1579                 || !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
1580                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1581                 goto err;
1582             }
1583             hdatalen -= PACKET_remaining(&hashprefix);
1584         }
1585 
1586         if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
1587             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1588             goto err;
1589         }
1590     }
1591 
1592     if (EVP_DigestUpdate(mctx, msgstart, binderoffset) <= 0
1593         || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1594         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1595         goto err;
1596     }
1597 
1598     mackey = EVP_PKEY_new_raw_private_key_ex(sctx->libctx, "HMAC",
1599         sctx->propq, finishedkey,
1600         hashsize);
1601     if (mackey == NULL) {
1602         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1603         goto err;
1604     }
1605 
1606     if (!sign)
1607         binderout = tmpbinder;
1608 
1609     bindersize = hashsize;
1610     if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), sctx->libctx,
1611             sctx->propq, mackey, NULL)
1612             <= 0
1613         || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
1614         || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
1615         || bindersize != hashsize) {
1616         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1617         goto err;
1618     }
1619 
1620     if (sign) {
1621         ret = 1;
1622     } else {
1623         /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
1624         ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
1625         if (!ret)
1626             SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BINDER_DOES_NOT_VERIFY);
1627     }
1628 
1629 err:
1630     OPENSSL_cleanse(binderkey, sizeof(binderkey));
1631     OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
1632     EVP_PKEY_free(mackey);
1633     EVP_MD_CTX_free(mctx);
1634 
1635     return ret;
1636 }
1637 
final_early_data(SSL_CONNECTION * s,unsigned int context,int sent)1638 static int final_early_data(SSL_CONNECTION *s, unsigned int context, int sent)
1639 {
1640     if (!sent)
1641         return 1;
1642 
1643     if (!s->server) {
1644         if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
1645             && sent
1646             && !s->ext.early_data_ok) {
1647             /*
1648              * If we get here then the server accepted our early_data but we
1649              * later realised that it shouldn't have done (e.g. inconsistent
1650              * ALPN)
1651              */
1652             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EARLY_DATA);
1653             return 0;
1654         }
1655 
1656         return 1;
1657     }
1658 
1659     if (s->max_early_data == 0
1660         || !s->hit
1661         || s->early_data_state != SSL_EARLY_DATA_ACCEPTING
1662         || !s->ext.early_data_ok
1663         || s->hello_retry_request != SSL_HRR_NONE
1664         || (s->allow_early_data_cb != NULL
1665             && !s->allow_early_data_cb(SSL_CONNECTION_GET_USER_SSL(s),
1666                 s->allow_early_data_cb_data))) {
1667         s->ext.early_data = SSL_EARLY_DATA_REJECTED;
1668     } else {
1669         s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
1670 
1671         if (!tls13_change_cipher_state(s,
1672                 SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {
1673             /* SSLfatal() already called */
1674             return 0;
1675         }
1676     }
1677 
1678     return 1;
1679 }
1680 
final_maxfragmentlen(SSL_CONNECTION * s,unsigned int context,int sent)1681 static int final_maxfragmentlen(SSL_CONNECTION *s, unsigned int context,
1682     int sent)
1683 {
1684     if (s->session == NULL)
1685         return 1;
1686 
1687     /* MaxFragmentLength defaults to disabled */
1688     if (s->session->ext.max_fragment_len_mode == TLSEXT_max_fragment_length_UNSPECIFIED)
1689         s->session->ext.max_fragment_len_mode = TLSEXT_max_fragment_length_DISABLED;
1690 
1691     if (USE_MAX_FRAGMENT_LENGTH_EXT(s->session)) {
1692         s->rlayer.rrlmethod->set_max_frag_len(s->rlayer.rrl,
1693             GET_MAX_FRAGMENT_LENGTH(s->session));
1694         s->rlayer.wrlmethod->set_max_frag_len(s->rlayer.wrl,
1695             ssl_get_max_send_fragment(s));
1696     }
1697 
1698     return 1;
1699 }
1700 
init_post_handshake_auth(SSL_CONNECTION * s,ossl_unused unsigned int context)1701 static int init_post_handshake_auth(SSL_CONNECTION *s,
1702     ossl_unused unsigned int context)
1703 {
1704     s->post_handshake_auth = SSL_PHA_NONE;
1705 
1706     return 1;
1707 }
1708 
1709 /*
1710  * If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
1711  * extension, servers MUST abort the handshake.
1712  */
final_psk(SSL_CONNECTION * s,unsigned int context,int sent)1713 static int final_psk(SSL_CONNECTION *s, unsigned int context, int sent)
1714 {
1715     if (s->server && sent && s->clienthello != NULL
1716         && !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
1717         SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1718             SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
1719         return 0;
1720     }
1721 
1722     return 1;
1723 }
1724 
tls_init_compress_certificate(SSL_CONNECTION * sc,unsigned int context)1725 static int tls_init_compress_certificate(SSL_CONNECTION *sc, unsigned int context)
1726 {
1727     memset(sc->ext.compress_certificate_from_peer, 0,
1728         sizeof(sc->ext.compress_certificate_from_peer));
1729     return 1;
1730 }
1731 
1732 /* 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)1733 static EXT_RETURN tls_construct_compress_certificate(SSL_CONNECTION *sc, WPACKET *pkt,
1734     unsigned int context,
1735     X509 *x, size_t chainidx)
1736 {
1737 #ifndef OPENSSL_NO_COMP_ALG
1738     int i;
1739 
1740     if (!ossl_comp_has_alg(0))
1741         return EXT_RETURN_NOT_SENT;
1742 
1743     /* Server: Don't attempt to compress a non-X509 (i.e. an RPK) */
1744     if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509) {
1745         sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
1746         return EXT_RETURN_NOT_SENT;
1747     }
1748 
1749     /* Client: If we sent a client cert-type extension, don't indicate compression */
1750     if (!sc->server && sc->ext.client_cert_type_ctos) {
1751         sc->cert_comp_prefs[0] = TLSEXT_comp_cert_none;
1752         return EXT_RETURN_NOT_SENT;
1753     }
1754 
1755     /* Do not indicate we support receiving compressed certificates */
1756     if ((sc->options & SSL_OP_NO_RX_CERTIFICATE_COMPRESSION) != 0)
1757         return EXT_RETURN_NOT_SENT;
1758 
1759     if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
1760         return EXT_RETURN_NOT_SENT;
1761 
1762     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_compress_certificate)
1763         || !WPACKET_start_sub_packet_u16(pkt)
1764         || !WPACKET_start_sub_packet_u8(pkt))
1765         goto err;
1766 
1767     for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
1768         if (!WPACKET_put_bytes_u16(pkt, sc->cert_comp_prefs[i]))
1769             goto err;
1770     }
1771     if (!WPACKET_close(pkt) || !WPACKET_close(pkt))
1772         goto err;
1773 
1774     sc->ext.compress_certificate_sent = 1;
1775     return EXT_RETURN_SENT;
1776 err:
1777     SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1778     return EXT_RETURN_FAIL;
1779 #else
1780     return EXT_RETURN_NOT_SENT;
1781 #endif
1782 }
1783 
1784 #ifndef OPENSSL_NO_COMP_ALG
tls_comp_in_pref(SSL_CONNECTION * sc,int alg)1785 static int tls_comp_in_pref(SSL_CONNECTION *sc, int alg)
1786 {
1787     int i;
1788 
1789     /* ossl_comp_has_alg() considers 0 as "any" */
1790     if (alg == 0)
1791         return 0;
1792     /* Make sure algorithm is enabled */
1793     if (!ossl_comp_has_alg(alg))
1794         return 0;
1795     /* If no preferences are set, it's ok */
1796     if (sc->cert_comp_prefs[0] == TLSEXT_comp_cert_none)
1797         return 1;
1798     /* Find the algorithm */
1799     for (i = 0; i < TLSEXT_comp_cert_limit; i++)
1800         if (sc->cert_comp_prefs[i] == alg)
1801             return 1;
1802     return 0;
1803 }
1804 #endif
1805 
tls_parse_compress_certificate(SSL_CONNECTION * sc,PACKET * pkt,unsigned int context,X509 * x,size_t chainidx)1806 int tls_parse_compress_certificate(SSL_CONNECTION *sc, PACKET *pkt, unsigned int context,
1807     X509 *x, size_t chainidx)
1808 {
1809 #ifndef OPENSSL_NO_COMP_ALG
1810     PACKET supported_comp_algs;
1811     unsigned int comp;
1812     int already_set[TLSEXT_comp_cert_limit];
1813     int j = 0;
1814 
1815     /* If no algorithms are available, ignore the extension */
1816     if (!ossl_comp_has_alg(0))
1817         return 1;
1818 
1819     /* Don't attempt to compress a non-X509 (i.e. an RPK) */
1820     if (sc->server && sc->ext.server_cert_type != TLSEXT_cert_type_x509)
1821         return 1;
1822     if (!sc->server && sc->ext.client_cert_type != TLSEXT_cert_type_x509)
1823         return 1;
1824 
1825     /* Ignore the extension and don't send compressed certificates */
1826     if ((sc->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
1827         return 1;
1828 
1829     if (!PACKET_as_length_prefixed_1(pkt, &supported_comp_algs)
1830         || PACKET_remaining(&supported_comp_algs) == 0) {
1831         SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1832         return 0;
1833     }
1834 
1835     memset(already_set, 0, sizeof(already_set));
1836     /*
1837      * The preference array has real values, so take a look at each
1838      * value coming in, and make sure it's in our preference list
1839      * The array is 0 (i.e. "none") terminated
1840      * The preference list only contains supported algorithms
1841      */
1842     while (PACKET_get_net_2(&supported_comp_algs, &comp)) {
1843         if (tls_comp_in_pref(sc, comp) && !already_set[comp]) {
1844             sc->ext.compress_certificate_from_peer[j++] = comp;
1845             already_set[comp] = 1;
1846         }
1847     }
1848     if (PACKET_remaining(&supported_comp_algs) != 0) {
1849         SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1850         return 0;
1851     }
1852 #endif
1853     return 1;
1854 }
1855 
init_server_cert_type(SSL_CONNECTION * sc,unsigned int context)1856 static int init_server_cert_type(SSL_CONNECTION *sc, unsigned int context)
1857 {
1858     /* Only reset when parsing client hello */
1859     if (sc->server) {
1860         sc->ext.server_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
1861         sc->ext.server_cert_type = TLSEXT_cert_type_x509;
1862     }
1863     return 1;
1864 }
1865 
init_client_cert_type(SSL_CONNECTION * sc,unsigned int context)1866 static int init_client_cert_type(SSL_CONNECTION *sc, unsigned int context)
1867 {
1868     /* Only reset when parsing client hello */
1869     if (sc->server) {
1870         sc->ext.client_cert_type_ctos = OSSL_CERT_TYPE_CTOS_NONE;
1871         sc->ext.client_cert_type = TLSEXT_cert_type_x509;
1872     }
1873     return 1;
1874 }
1875