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