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