ssl: fix indentation
[openssl.git] / ssl / statem / extensions.c
1 /*
2  * Copyright 2016-2021 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 int init_server_name(SSL *s, unsigned int context)
901 {
902     if (s->server) {
903         s->servername_done = 0;
904
905         OPENSSL_free(s->ext.hostname);
906         s->ext.hostname = NULL;
907     }
908
909     return 1;
910 }
911
912 static int final_server_name(SSL *s, unsigned int context, int sent)
913 {
914     int ret = SSL_TLSEXT_ERR_NOACK;
915     int altmp = SSL_AD_UNRECOGNIZED_NAME;
916     int was_ticket = (SSL_get_options(s) & SSL_OP_NO_TICKET) == 0;
917
918     if (!ossl_assert(s->ctx != NULL) || !ossl_assert(s->session_ctx != NULL)) {
919         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
920         return 0;
921     }
922
923     if (s->ctx->ext.servername_cb != NULL)
924         ret = s->ctx->ext.servername_cb(s, &altmp,
925                                         s->ctx->ext.servername_arg);
926     else if (s->session_ctx->ext.servername_cb != NULL)
927         ret = s->session_ctx->ext.servername_cb(s, &altmp,
928                                        s->session_ctx->ext.servername_arg);
929
930     /*
931      * For servers, propagate the SNI hostname from the temporary
932      * storage in the SSL to the persistent SSL_SESSION, now that we
933      * know we accepted it.
934      * Clients make this copy when parsing the server's response to
935      * the extension, which is when they find out that the negotiation
936      * was successful.
937      */
938     if (s->server) {
939         if (sent && ret == SSL_TLSEXT_ERR_OK && !s->hit) {
940             /* Only store the hostname in the session if we accepted it. */
941             OPENSSL_free(s->session->ext.hostname);
942             s->session->ext.hostname = OPENSSL_strdup(s->ext.hostname);
943             if (s->session->ext.hostname == NULL && s->ext.hostname != NULL) {
944                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
945             }
946         }
947     }
948
949     /*
950      * If we switched contexts (whether here or in the client_hello callback),
951      * move the sess_accept increment from the session_ctx to the new
952      * context, to avoid the confusing situation of having sess_accept_good
953      * exceed sess_accept (zero) for the new context.
954      */
955     if (SSL_IS_FIRST_HANDSHAKE(s) && s->ctx != s->session_ctx
956             && s->hello_retry_request == SSL_HRR_NONE) {
957         tsan_counter(&s->ctx->stats.sess_accept);
958         tsan_decr(&s->session_ctx->stats.sess_accept);
959     }
960
961     /*
962      * If we're expecting to send a ticket, and tickets were previously enabled,
963      * and now tickets are disabled, then turn off expected ticket.
964      * Also, if this is not a resumption, create a new session ID
965      */
966     if (ret == SSL_TLSEXT_ERR_OK && s->ext.ticket_expected
967             && was_ticket && (SSL_get_options(s) & SSL_OP_NO_TICKET) != 0) {
968         s->ext.ticket_expected = 0;
969         if (!s->hit) {
970             SSL_SESSION* ss = SSL_get_session(s);
971
972             if (ss != NULL) {
973                 OPENSSL_free(ss->ext.tick);
974                 ss->ext.tick = NULL;
975                 ss->ext.ticklen = 0;
976                 ss->ext.tick_lifetime_hint = 0;
977                 ss->ext.tick_age_add = 0;
978                 if (!ssl_generate_session_id(s, ss)) {
979                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
980                     return 0;
981                 }
982             } else {
983                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
984                 return 0;
985             }
986         }
987     }
988
989     switch (ret) {
990     case SSL_TLSEXT_ERR_ALERT_FATAL:
991         SSLfatal(s, altmp, SSL_R_CALLBACK_FAILED);
992         return 0;
993
994     case SSL_TLSEXT_ERR_ALERT_WARNING:
995         /* TLSv1.3 doesn't have warning alerts so we suppress this */
996         if (!SSL_IS_TLS13(s))
997             ssl3_send_alert(s, SSL3_AL_WARNING, altmp);
998         s->servername_done = 0;
999         return 1;
1000
1001     case SSL_TLSEXT_ERR_NOACK:
1002         s->servername_done = 0;
1003         return 1;
1004
1005     default:
1006         return 1;
1007     }
1008 }
1009
1010 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent)
1011 {
1012     unsigned long alg_k, alg_a;
1013
1014     if (s->server)
1015         return 1;
1016
1017     alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
1018     alg_a = s->s3.tmp.new_cipher->algorithm_auth;
1019
1020     /*
1021      * If we are client and using an elliptic curve cryptography cipher
1022      * suite, then if server returns an EC point formats lists extension it
1023      * must contain uncompressed.
1024      */
1025     if (s->ext.ecpointformats != NULL
1026             && s->ext.ecpointformats_len > 0
1027             && s->ext.peer_ecpointformats != NULL
1028             && s->ext.peer_ecpointformats_len > 0
1029             && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
1030         /* we are using an ECC cipher */
1031         size_t i;
1032         unsigned char *list = s->ext.peer_ecpointformats;
1033
1034         for (i = 0; i < s->ext.peer_ecpointformats_len; i++) {
1035             if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
1036                 break;
1037         }
1038         if (i == s->ext.peer_ecpointformats_len) {
1039             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1040                      SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
1041             return 0;
1042         }
1043     }
1044
1045     return 1;
1046 }
1047
1048 static int init_session_ticket(SSL *s, unsigned int context)
1049 {
1050     if (!s->server)
1051         s->ext.ticket_expected = 0;
1052
1053     return 1;
1054 }
1055
1056 #ifndef OPENSSL_NO_OCSP
1057 static int init_status_request(SSL *s, unsigned int context)
1058 {
1059     if (s->server) {
1060         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
1061     } else {
1062         /*
1063          * Ensure we get sensible values passed to tlsext_status_cb in the event
1064          * that we don't receive a status message
1065          */
1066         OPENSSL_free(s->ext.ocsp.resp);
1067         s->ext.ocsp.resp = NULL;
1068         s->ext.ocsp.resp_len = 0;
1069     }
1070
1071     return 1;
1072 }
1073 #endif
1074
1075 #ifndef OPENSSL_NO_NEXTPROTONEG
1076 static int init_npn(SSL *s, unsigned int context)
1077 {
1078     s->s3.npn_seen = 0;
1079
1080     return 1;
1081 }
1082 #endif
1083
1084 static int init_alpn(SSL *s, unsigned int context)
1085 {
1086     OPENSSL_free(s->s3.alpn_selected);
1087     s->s3.alpn_selected = NULL;
1088     s->s3.alpn_selected_len = 0;
1089     if (s->server) {
1090         OPENSSL_free(s->s3.alpn_proposed);
1091         s->s3.alpn_proposed = NULL;
1092         s->s3.alpn_proposed_len = 0;
1093     }
1094     return 1;
1095 }
1096
1097 static int final_alpn(SSL *s, unsigned int context, int sent)
1098 {
1099     if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
1100             s->ext.early_data_ok = 0;
1101
1102     if (!s->server || !SSL_IS_TLS13(s))
1103         return 1;
1104
1105     /*
1106      * Call alpn_select callback if needed.  Has to be done after SNI and
1107      * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
1108      * we also have to do this before we decide whether to accept early_data.
1109      * In TLSv1.3 we've already negotiated our cipher so we do this call now.
1110      * For < TLSv1.3 we defer it until after cipher negotiation.
1111      *
1112      * On failure SSLfatal() already called.
1113      */
1114     return tls_handle_alpn(s);
1115 }
1116
1117 static int init_sig_algs(SSL *s, unsigned int context)
1118 {
1119     /* Clear any signature algorithms extension received */
1120     OPENSSL_free(s->s3.tmp.peer_sigalgs);
1121     s->s3.tmp.peer_sigalgs = NULL;
1122     s->s3.tmp.peer_sigalgslen = 0;
1123
1124     return 1;
1125 }
1126
1127 static int init_sig_algs_cert(SSL *s, ossl_unused unsigned int context)
1128 {
1129     /* Clear any signature algorithms extension received */
1130     OPENSSL_free(s->s3.tmp.peer_cert_sigalgs);
1131     s->s3.tmp.peer_cert_sigalgs = NULL;
1132     s->s3.tmp.peer_cert_sigalgslen = 0;
1133
1134     return 1;
1135 }
1136
1137 #ifndef OPENSSL_NO_SRP
1138 static int init_srp(SSL *s, unsigned int context)
1139 {
1140     OPENSSL_free(s->srp_ctx.login);
1141     s->srp_ctx.login = NULL;
1142
1143     return 1;
1144 }
1145 #endif
1146
1147 static int init_ec_point_formats(SSL *s, unsigned int context)
1148 {
1149     OPENSSL_free(s->ext.peer_ecpointformats);
1150     s->ext.peer_ecpointformats = NULL;
1151     s->ext.peer_ecpointformats_len = 0;
1152
1153     return 1;
1154 }
1155
1156 static int init_etm(SSL *s, unsigned int context)
1157 {
1158     s->ext.use_etm = 0;
1159
1160     return 1;
1161 }
1162
1163 static int init_ems(SSL *s, unsigned int context)
1164 {
1165     if (s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) {
1166         s->s3.flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
1167         s->s3.flags |= TLS1_FLAGS_REQUIRED_EXTMS;
1168     }
1169
1170     return 1;
1171 }
1172
1173 static int final_ems(SSL *s, unsigned int context, int sent)
1174 {
1175     /*
1176      * Check extended master secret extension is not dropped on
1177      * renegotiation.
1178      */
1179     if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS)
1180         && (s->s3.flags & TLS1_FLAGS_REQUIRED_EXTMS)) {
1181         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1182         return 0;
1183     }
1184     if (!s->server && s->hit) {
1185         /*
1186          * Check extended master secret extension is consistent with
1187          * original session.
1188          */
1189         if (!(s->s3.flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
1190             !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
1191             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_EXTMS);
1192             return 0;
1193         }
1194     }
1195
1196     return 1;
1197 }
1198
1199 static int init_certificate_authorities(SSL *s, unsigned int context)
1200 {
1201     sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
1202     s->s3.tmp.peer_ca_names = NULL;
1203     return 1;
1204 }
1205
1206 static EXT_RETURN tls_construct_certificate_authorities(SSL *s, WPACKET *pkt,
1207                                                         unsigned int context,
1208                                                         X509 *x,
1209                                                         size_t chainidx)
1210 {
1211     const STACK_OF(X509_NAME) *ca_sk = get_ca_names(s);
1212
1213     if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
1214         return EXT_RETURN_NOT_SENT;
1215
1216     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)
1217         || !WPACKET_start_sub_packet_u16(pkt)) {
1218         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1219         return EXT_RETURN_FAIL;
1220     }
1221
1222     if (!construct_ca_names(s, ca_sk, pkt)) {
1223         /* SSLfatal() already called */
1224         return EXT_RETURN_FAIL;
1225     }
1226
1227     if (!WPACKET_close(pkt)) {
1228         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1229         return EXT_RETURN_FAIL;
1230     }
1231
1232     return EXT_RETURN_SENT;
1233 }
1234
1235 static int tls_parse_certificate_authorities(SSL *s, PACKET *pkt,
1236                                              unsigned int context, X509 *x,
1237                                              size_t chainidx)
1238 {
1239     if (!parse_ca_names(s, pkt))
1240         return 0;
1241     if (PACKET_remaining(pkt) != 0) {
1242         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_EXTENSION);
1243         return 0;
1244     }
1245     return 1;
1246 }
1247
1248 #ifndef OPENSSL_NO_SRTP
1249 static int init_srtp(SSL *s, unsigned int context)
1250 {
1251     if (s->server)
1252         s->srtp_profile = NULL;
1253
1254     return 1;
1255 }
1256 #endif
1257
1258 static int final_sig_algs(SSL *s, unsigned int context, int sent)
1259 {
1260     if (!sent && SSL_IS_TLS13(s) && !s->hit) {
1261         SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1262                  SSL_R_MISSING_SIGALGS_EXTENSION);
1263         return 0;
1264     }
1265
1266     return 1;
1267 }
1268
1269 static int final_key_share(SSL *s, unsigned int context, int sent)
1270 {
1271 #if !defined(OPENSSL_NO_TLS1_3)
1272     if (!SSL_IS_TLS13(s))
1273         return 1;
1274
1275     /* Nothing to do for key_share in an HRR */
1276     if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
1277         return 1;
1278
1279     /*
1280      * If
1281      *     we are a client
1282      *     AND
1283      *     we have no key_share
1284      *     AND
1285      *     (we are not resuming
1286      *      OR the kex_mode doesn't allow non key_share resumes)
1287      * THEN
1288      *     fail;
1289      */
1290     if (!s->server
1291             && !sent
1292             && (!s->hit
1293                 || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0)) {
1294         /* Nothing left we can do - just fail */
1295         SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_NO_SUITABLE_KEY_SHARE);
1296         return 0;
1297     }
1298     /*
1299      * IF
1300      *     we are a server
1301      * THEN
1302      *     IF
1303      *         we have a suitable key_share
1304      *     THEN
1305      *         IF
1306      *             we are stateless AND we have no cookie
1307      *         THEN
1308      *             send a HelloRetryRequest
1309      *     ELSE
1310      *         IF
1311      *             we didn't already send a HelloRetryRequest
1312      *             AND
1313      *             the client sent a key_share extension
1314      *             AND
1315      *             (we are not resuming
1316      *              OR the kex_mode allows key_share resumes)
1317      *             AND
1318      *             a shared group exists
1319      *         THEN
1320      *             send a HelloRetryRequest
1321      *         ELSE IF
1322      *             we are not resuming
1323      *             OR
1324      *             the kex_mode doesn't allow non key_share resumes
1325      *         THEN
1326      *             fail
1327      *         ELSE IF
1328      *             we are stateless AND we have no cookie
1329      *         THEN
1330      *             send a HelloRetryRequest
1331      */
1332     if (s->server) {
1333         if (s->s3.peer_tmp != NULL) {
1334             /* We have a suitable key_share */
1335             if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1336                     && !s->ext.cookieok) {
1337                 if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1338                     /*
1339                      * If we are stateless then we wouldn't know about any
1340                      * previously sent HRR - so how can this be anything other
1341                      * than 0?
1342                      */
1343                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1344                     return 0;
1345                 }
1346                 s->hello_retry_request = SSL_HRR_PENDING;
1347                 return 1;
1348             }
1349         } else {
1350             /* No suitable key_share */
1351             if (s->hello_retry_request == SSL_HRR_NONE && sent
1352                     && (!s->hit
1353                         || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE)
1354                            != 0)) {
1355                 const uint16_t *pgroups, *clntgroups;
1356                 size_t num_groups, clnt_num_groups, i;
1357                 unsigned int group_id = 0;
1358
1359                 /* Check if a shared group exists */
1360
1361                 /* Get the clients list of supported groups. */
1362                 tls1_get_peer_groups(s, &clntgroups, &clnt_num_groups);
1363                 tls1_get_supported_groups(s, &pgroups, &num_groups);
1364
1365                 /*
1366                  * Find the first group we allow that is also in client's list
1367                  */
1368                 for (i = 0; i < num_groups; i++) {
1369                     group_id = pgroups[i];
1370
1371                     if (check_in_list(s, group_id, clntgroups, clnt_num_groups,
1372                                       1))
1373                         break;
1374                 }
1375
1376                 if (i < num_groups) {
1377                     /* A shared group exists so send a HelloRetryRequest */
1378                     s->s3.group_id = group_id;
1379                     s->hello_retry_request = SSL_HRR_PENDING;
1380                     return 1;
1381                 }
1382             }
1383             if (!s->hit
1384                     || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1385                 /* Nothing left we can do - just fail */
1386                 SSLfatal(s, sent ? SSL_AD_HANDSHAKE_FAILURE
1387                                  : SSL_AD_MISSING_EXTENSION,
1388                          SSL_R_NO_SUITABLE_KEY_SHARE);
1389                 return 0;
1390             }
1391
1392             if ((s->s3.flags & TLS1_FLAGS_STATELESS) != 0
1393                     && !s->ext.cookieok) {
1394                 if (!ossl_assert(s->hello_retry_request == SSL_HRR_NONE)) {
1395                     /*
1396                      * If we are stateless then we wouldn't know about any
1397                      * previously sent HRR - so how can this be anything other
1398                      * than 0?
1399                      */
1400                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1401                     return 0;
1402                 }
1403                 s->hello_retry_request = SSL_HRR_PENDING;
1404                 return 1;
1405             }
1406         }
1407
1408         /*
1409          * We have a key_share so don't send any more HelloRetryRequest
1410          * messages
1411          */
1412         if (s->hello_retry_request == SSL_HRR_PENDING)
1413             s->hello_retry_request = SSL_HRR_COMPLETE;
1414     } else {
1415         /*
1416          * For a client side resumption with no key_share we need to generate
1417          * the handshake secret (otherwise this is done during key_share
1418          * processing).
1419          */
1420         if (!sent && !tls13_generate_handshake_secret(s, NULL, 0)) {
1421             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1422             return 0;
1423         }
1424     }
1425 #endif /* !defined(OPENSSL_NO_TLS1_3) */
1426     return 1;
1427 }
1428
1429 static int init_psk_kex_modes(SSL *s, unsigned int context)
1430 {
1431     s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1432     return 1;
1433 }
1434
1435 int tls_psk_do_binder(SSL *s, const EVP_MD *md, const unsigned char *msgstart,
1436                       size_t binderoffset, const unsigned char *binderin,
1437                       unsigned char *binderout, SSL_SESSION *sess, int sign,
1438                       int external)
1439 {
1440     EVP_PKEY *mackey = NULL;
1441     EVP_MD_CTX *mctx = NULL;
1442     unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1443     unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1444     unsigned char *early_secret;
1445 #ifdef CHARSET_EBCDIC
1446     static const unsigned char resumption_label[] = { 0x72, 0x65, 0x73, 0x20, 0x62, 0x69, 0x6E, 0x64, 0x65, 0x72, 0x00 };
1447     static const unsigned char external_label[]   = { 0x65, 0x78, 0x74, 0x20, 0x62, 0x69, 0x6E, 0x64, 0x65, 0x72, 0x00 };
1448 #else
1449     static const unsigned char resumption_label[] = "res binder";
1450     static const unsigned char external_label[] = "ext binder";
1451 #endif
1452     const unsigned char *label;
1453     size_t bindersize, labelsize, hashsize;
1454     int hashsizei = EVP_MD_get_size(md);
1455     int ret = -1;
1456     int usepskfored = 0;
1457
1458     /* Ensure cast to size_t is safe */
1459     if (!ossl_assert(hashsizei >= 0)) {
1460         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1461         goto err;
1462     }
1463     hashsize = (size_t)hashsizei;
1464
1465     if (external
1466             && s->early_data_state == SSL_EARLY_DATA_CONNECTING
1467             && s->session->ext.max_early_data == 0
1468             && sess->ext.max_early_data > 0)
1469         usepskfored = 1;
1470
1471     if (external) {
1472         label = external_label;
1473         labelsize = sizeof(external_label) - 1;
1474     } else {
1475         label = resumption_label;
1476         labelsize = sizeof(resumption_label) - 1;
1477     }
1478
1479     /*
1480      * Generate the early_secret. On the server side we've selected a PSK to
1481      * resume with (internal or external) so we always do this. On the client
1482      * side we do this for a non-external (i.e. resumption) PSK or external PSK
1483      * that will be used for early_data so that it is in place for sending early
1484      * data. For client side external PSK not being used for early_data we
1485      * generate it but store it away for later use.
1486      */
1487     if (s->server || !external || usepskfored)
1488         early_secret = (unsigned char *)s->early_secret;
1489     else
1490         early_secret = (unsigned char *)sess->early_secret;
1491
1492     if (!tls13_generate_secret(s, md, NULL, sess->master_key,
1493                                sess->master_key_length, early_secret)) {
1494         /* SSLfatal() already called */
1495         goto err;
1496     }
1497
1498     /*
1499      * Create the handshake hash for the binder key...the messages so far are
1500      * empty!
1501      */
1502     mctx = EVP_MD_CTX_new();
1503     if (mctx == NULL
1504             || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1505             || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1506         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1507         goto err;
1508     }
1509
1510     /* Generate the binder key */
1511     if (!tls13_hkdf_expand(s, md, early_secret, label, labelsize, hash,
1512                            hashsize, binderkey, hashsize, 1)) {
1513         /* SSLfatal() already called */
1514         goto err;
1515     }
1516
1517     /* Generate the finished key */
1518     if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1519         /* SSLfatal() already called */
1520         goto err;
1521     }
1522
1523     if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
1524         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1525         goto err;
1526     }
1527
1528     /*
1529      * Get a hash of the ClientHello up to the start of the binders. If we are
1530      * following a HelloRetryRequest then this includes the hash of the first
1531      * ClientHello and the HelloRetryRequest itself.
1532      */
1533     if (s->hello_retry_request == SSL_HRR_PENDING) {
1534         size_t hdatalen;
1535         long hdatalen_l;
1536         void *hdata;
1537
1538         hdatalen = hdatalen_l =
1539             BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
1540         if (hdatalen_l <= 0) {
1541             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
1542             goto err;
1543         }
1544
1545         /*
1546          * For servers the handshake buffer data will include the second
1547          * ClientHello - which we don't want - so we need to take that bit off.
1548          */
1549         if (s->server) {
1550             PACKET hashprefix, msg;
1551
1552             /* Find how many bytes are left after the first two messages */
1553             if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
1554                     || !PACKET_forward(&hashprefix, 1)
1555                     || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
1556                     || !PACKET_forward(&hashprefix, 1)
1557                     || !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
1558                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1559                 goto err;
1560             }
1561             hdatalen -= PACKET_remaining(&hashprefix);
1562         }
1563
1564         if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
1565             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1566             goto err;
1567         }
1568     }
1569
1570     if (EVP_DigestUpdate(mctx, msgstart, binderoffset) <= 0
1571             || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1572         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1573         goto err;
1574     }
1575
1576     mackey = EVP_PKEY_new_raw_private_key_ex(s->ctx->libctx, "HMAC",
1577                                              s->ctx->propq, finishedkey,
1578                                              hashsize);
1579     if (mackey == NULL) {
1580         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1581         goto err;
1582     }
1583
1584     if (!sign)
1585         binderout = tmpbinder;
1586
1587     bindersize = hashsize;
1588     if (EVP_DigestSignInit_ex(mctx, NULL, EVP_MD_get0_name(md), s->ctx->libctx,
1589                               s->ctx->propq, mackey, NULL) <= 0
1590             || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
1591             || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
1592             || bindersize != hashsize) {
1593         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1594         goto err;
1595     }
1596
1597     if (sign) {
1598         ret = 1;
1599     } else {
1600         /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
1601         ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
1602         if (!ret)
1603             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BINDER_DOES_NOT_VERIFY);
1604     }
1605
1606  err:
1607     OPENSSL_cleanse(binderkey, sizeof(binderkey));
1608     OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
1609     EVP_PKEY_free(mackey);
1610     EVP_MD_CTX_free(mctx);
1611
1612     return ret;
1613 }
1614
1615 static int final_early_data(SSL *s, unsigned int context, int sent)
1616 {
1617     if (!sent)
1618         return 1;
1619
1620     if (!s->server) {
1621         if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
1622                 && sent
1623                 && !s->ext.early_data_ok) {
1624             /*
1625              * If we get here then the server accepted our early_data but we
1626              * later realised that it shouldn't have done (e.g. inconsistent
1627              * ALPN)
1628              */
1629             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EARLY_DATA);
1630             return 0;
1631         }
1632
1633         return 1;
1634     }
1635
1636     if (s->max_early_data == 0
1637             || !s->hit
1638             || s->early_data_state != SSL_EARLY_DATA_ACCEPTING
1639             || !s->ext.early_data_ok
1640             || s->hello_retry_request != SSL_HRR_NONE
1641             || (s->allow_early_data_cb != NULL
1642                 && !s->allow_early_data_cb(s,
1643                                          s->allow_early_data_cb_data))) {
1644         s->ext.early_data = SSL_EARLY_DATA_REJECTED;
1645     } else {
1646         s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
1647
1648         if (!tls13_change_cipher_state(s,
1649                     SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {
1650             /* SSLfatal() already called */
1651             return 0;
1652         }
1653     }
1654
1655     return 1;
1656 }
1657
1658 static int final_maxfragmentlen(SSL *s, unsigned int context, int sent)
1659 {
1660     /*
1661      * Session resumption on server-side with MFL extension active
1662      *  BUT MFL extension packet was not resent (i.e. sent == 0)
1663      */
1664     if (s->server && s->hit && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1665             && !sent ) {
1666         SSLfatal(s, SSL_AD_MISSING_EXTENSION, SSL_R_BAD_EXTENSION);
1667         return 0;
1668     }
1669
1670     /* Current SSL buffer is lower than requested MFL */
1671     if (s->session && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1672             && s->max_send_fragment < GET_MAX_FRAGMENT_LENGTH(s->session))
1673         /* trigger a larger buffer reallocation */
1674         if (!ssl3_setup_buffers(s)) {
1675             /* SSLfatal() already called */
1676             return 0;
1677         }
1678
1679     return 1;
1680 }
1681
1682 static int init_post_handshake_auth(SSL *s, ossl_unused unsigned int context)
1683 {
1684     s->post_handshake_auth = SSL_PHA_NONE;
1685
1686     return 1;
1687 }
1688
1689 /*
1690  * If clients offer "pre_shared_key" without a "psk_key_exchange_modes"
1691  * extension, servers MUST abort the handshake.
1692  */
1693 static int final_psk(SSL *s, unsigned int context, int sent)
1694 {
1695     if (s->server && sent && s->clienthello != NULL
1696             && !s->clienthello->pre_proc_exts[TLSEXT_IDX_psk_kex_modes].present) {
1697         SSLfatal(s, TLS13_AD_MISSING_EXTENSION,
1698                  SSL_R_MISSING_PSK_KEX_MODES_EXTENSION);
1699         return 0;
1700     }
1701
1702     return 1;
1703 }