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