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