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