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