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