a72859c873da4f1caf393c25eb9d4b3bf678e6b9
[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         return 1;
915
916     default:
917         return 1;
918     }
919 }
920
921 #ifndef OPENSSL_NO_EC
922 static int final_ec_pt_formats(SSL *s, unsigned int context, int sent,
923                                        int *al)
924 {
925     unsigned long alg_k, alg_a;
926
927     if (s->server)
928         return 1;
929
930     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
931     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
932
933     /*
934      * If we are client and using an elliptic curve cryptography cipher
935      * suite, then if server returns an EC point formats lists extension it
936      * must contain uncompressed.
937      */
938     if (s->ext.ecpointformats != NULL
939             && s->ext.ecpointformats_len > 0
940             && s->session->ext.ecpointformats != NULL
941             && s->session->ext.ecpointformats_len > 0
942             && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) {
943         /* we are using an ECC cipher */
944         size_t i;
945         unsigned char *list = s->session->ext.ecpointformats;
946
947         for (i = 0; i < s->session->ext.ecpointformats_len; i++) {
948             if (*list++ == TLSEXT_ECPOINTFORMAT_uncompressed)
949                 break;
950         }
951         if (i == s->session->ext.ecpointformats_len) {
952             SSLerr(SSL_F_FINAL_EC_PT_FORMATS,
953                    SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
954             return 0;
955         }
956     }
957
958     return 1;
959 }
960 #endif
961
962 static int init_session_ticket(SSL *s, unsigned int context)
963 {
964     if (!s->server)
965         s->ext.ticket_expected = 0;
966
967     return 1;
968 }
969
970 #ifndef OPENSSL_NO_OCSP
971 static int init_status_request(SSL *s, unsigned int context)
972 {
973     if (s->server) {
974         s->ext.status_type = TLSEXT_STATUSTYPE_nothing;
975     } else {
976         /*
977          * Ensure we get sensible values passed to tlsext_status_cb in the event
978          * that we don't receive a status message
979          */
980         OPENSSL_free(s->ext.ocsp.resp);
981         s->ext.ocsp.resp = NULL;
982         s->ext.ocsp.resp_len = 0;
983     }
984
985     return 1;
986 }
987 #endif
988
989 #ifndef OPENSSL_NO_NEXTPROTONEG
990 static int init_npn(SSL *s, unsigned int context)
991 {
992     s->s3->npn_seen = 0;
993
994     return 1;
995 }
996 #endif
997
998 static int init_alpn(SSL *s, unsigned int context)
999 {
1000     OPENSSL_free(s->s3->alpn_selected);
1001     s->s3->alpn_selected = NULL;
1002     s->s3->alpn_selected_len = 0;
1003     if (s->server) {
1004         OPENSSL_free(s->s3->alpn_proposed);
1005         s->s3->alpn_proposed = NULL;
1006         s->s3->alpn_proposed_len = 0;
1007     }
1008     return 1;
1009 }
1010
1011 static int final_alpn(SSL *s, unsigned int context, int sent, int *al)
1012 {
1013     if (!s->server && !sent && s->session->ext.alpn_selected != NULL)
1014             s->ext.early_data_ok = 0;
1015
1016     if (!s->server || !SSL_IS_TLS13(s))
1017         return 1;
1018
1019     /*
1020      * Call alpn_select callback if needed.  Has to be done after SNI and
1021      * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
1022      * we also have to do this before we decide whether to accept early_data.
1023      * In TLSv1.3 we've already negotiated our cipher so we do this call now.
1024      * For < TLSv1.3 we defer it until after cipher negotiation.
1025      */
1026     return tls_handle_alpn(s, al);
1027 }
1028
1029 static int init_sig_algs(SSL *s, unsigned int context)
1030 {
1031     /* Clear any signature algorithms extension received */
1032     OPENSSL_free(s->s3->tmp.peer_sigalgs);
1033     s->s3->tmp.peer_sigalgs = NULL;
1034
1035     return 1;
1036 }
1037
1038 #ifndef OPENSSL_NO_SRP
1039 static int init_srp(SSL *s, unsigned int context)
1040 {
1041     OPENSSL_free(s->srp_ctx.login);
1042     s->srp_ctx.login = NULL;
1043
1044     return 1;
1045 }
1046 #endif
1047
1048 static int init_etm(SSL *s, unsigned int context)
1049 {
1050     s->ext.use_etm = 0;
1051
1052     return 1;
1053 }
1054
1055 static int init_ems(SSL *s, unsigned int context)
1056 {
1057     if (!s->server)
1058         s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS;
1059
1060     return 1;
1061 }
1062
1063 static int final_ems(SSL *s, unsigned int context, int sent, int *al)
1064 {
1065     if (!s->server && s->hit) {
1066         /*
1067          * Check extended master secret extension is consistent with
1068          * original session.
1069          */
1070         if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) !=
1071             !(s->session->flags & SSL_SESS_FLAG_EXTMS)) {
1072             *al = SSL_AD_HANDSHAKE_FAILURE;
1073             SSLerr(SSL_F_FINAL_EMS, SSL_R_INCONSISTENT_EXTMS);
1074             return 0;
1075         }
1076     }
1077
1078     return 1;
1079 }
1080
1081 static int init_certificate_authorities(SSL *s, unsigned int context)
1082 {
1083     sk_X509_NAME_pop_free(s->s3->tmp.peer_ca_names, X509_NAME_free);
1084     s->s3->tmp.peer_ca_names = NULL;
1085     return 1;
1086 }
1087
1088 static EXT_RETURN tls_construct_certificate_authorities(SSL *s, WPACKET *pkt,
1089                                                         unsigned int context,
1090                                                         X509 *x,
1091                                                         size_t chainidx,
1092                                                         int *al)
1093 {
1094     const STACK_OF(X509_NAME) *ca_sk = SSL_get0_CA_list(s);
1095
1096     if (ca_sk == NULL || sk_X509_NAME_num(ca_sk) == 0)
1097         return EXT_RETURN_NOT_SENT;
1098
1099     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_certificate_authorities)
1100         || !WPACKET_start_sub_packet_u16(pkt)
1101         || !construct_ca_names(s, pkt)
1102         || !WPACKET_close(pkt)) {
1103         SSLerr(SSL_F_TLS_CONSTRUCT_CERTIFICATE_AUTHORITIES,
1104                ERR_R_INTERNAL_ERROR);
1105         return EXT_RETURN_FAIL;
1106     }
1107
1108     return EXT_RETURN_SENT;
1109 }
1110
1111 static int tls_parse_certificate_authorities(SSL *s, PACKET *pkt,
1112                                              unsigned int context, X509 *x,
1113                                              size_t chainidx, int *al)
1114 {
1115     if (!parse_ca_names(s, pkt, al))
1116         return 0;
1117     if (PACKET_remaining(pkt) != 0) {
1118         *al = SSL_AD_DECODE_ERROR;
1119         return 0;
1120     }
1121     return 1;
1122 }
1123
1124 #ifndef OPENSSL_NO_SRTP
1125 static int init_srtp(SSL *s, unsigned int context)
1126 {
1127     if (s->server)
1128         s->srtp_profile = NULL;
1129
1130     return 1;
1131 }
1132 #endif
1133
1134 static int final_sig_algs(SSL *s, unsigned int context, int sent, int *al)
1135 {
1136     if (!sent && SSL_IS_TLS13(s) && !s->hit) {
1137         *al = TLS13_AD_MISSING_EXTENSION;
1138         SSLerr(SSL_F_FINAL_SIG_ALGS, SSL_R_MISSING_SIGALGS_EXTENSION);
1139         return 0;
1140     }
1141
1142     return 1;
1143 }
1144
1145 #ifndef OPENSSL_NO_EC
1146 static int final_key_share(SSL *s, unsigned int context, int sent, int *al)
1147 {
1148     if (!SSL_IS_TLS13(s))
1149         return 1;
1150
1151     /* Nothing to do for key_share in an HRR */
1152     if ((context & SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST) != 0)
1153         return 1;
1154
1155     /*
1156      * If
1157      *     we are a client
1158      *     AND
1159      *     we have no key_share
1160      *     AND
1161      *     (we are not resuming
1162      *      OR the kex_mode doesn't allow non key_share resumes)
1163      * THEN
1164      *     fail;
1165      */
1166     if (!s->server
1167             && !sent
1168             && (!s->hit
1169                 || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0)) {
1170         /* Nothing left we can do - just fail */
1171         *al = SSL_AD_MISSING_EXTENSION;
1172         SSLerr(SSL_F_FINAL_KEY_SHARE, SSL_R_NO_SUITABLE_KEY_SHARE);
1173         return 0;
1174     }
1175     /*
1176      * If
1177      *     we are a server
1178      *     AND
1179      *     we have no key_share
1180      * THEN
1181      *     If
1182      *         we didn't already send a HelloRetryRequest
1183      *         AND
1184      *         the client sent a key_share extension
1185      *         AND
1186      *         (we are not resuming
1187      *          OR the kex_mode allows key_share resumes)
1188      *         AND
1189      *         a shared group exists
1190      *     THEN
1191      *         send a HelloRetryRequest
1192      *     ELSE If
1193      *         we are not resuming
1194      *         OR
1195      *         the kex_mode doesn't allow non key_share resumes
1196      *     THEN
1197      *         fail;
1198      */
1199     if (s->server && s->s3->peer_tmp == NULL) {
1200         /* No suitable share */
1201         if (s->hello_retry_request == 0 && sent
1202                 && (!s->hit
1203                     || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE_DHE)
1204                        != 0)) {
1205             const uint16_t *pgroups, *clntgroups;
1206             size_t num_groups, clnt_num_groups, i;
1207             unsigned int group_id = 0;
1208
1209             /* Check if a shared group exists */
1210
1211             /* Get the clients list of supported groups. */
1212             tls1_get_peer_groups(s, &clntgroups, &clnt_num_groups);
1213             tls1_get_supported_groups(s, &pgroups, &num_groups);
1214
1215             /* Find the first group we allow that is also in client's list */
1216             for (i = 0; i < num_groups; i++) {
1217                 group_id = pgroups[i];
1218
1219                 if (check_in_list(s, group_id, clntgroups, clnt_num_groups, 1))
1220                     break;
1221             }
1222
1223             if (i < num_groups) {
1224                 /* A shared group exists so send a HelloRetryRequest */
1225                 s->s3->group_id = group_id;
1226                 s->hello_retry_request = 1;
1227                 return 1;
1228             }
1229         }
1230         if (!s->hit
1231                 || (s->ext.psk_kex_mode & TLSEXT_KEX_MODE_FLAG_KE) == 0) {
1232             /* Nothing left we can do - just fail */
1233             if (!sent)
1234                 *al = SSL_AD_MISSING_EXTENSION;
1235             else
1236                 *al = SSL_AD_HANDSHAKE_FAILURE;
1237             SSLerr(SSL_F_FINAL_KEY_SHARE, SSL_R_NO_SUITABLE_KEY_SHARE);
1238             return 0;
1239         }
1240     }
1241
1242     /* We have a key_share so don't send any more HelloRetryRequest messages */
1243     if (s->server)
1244         s->hello_retry_request = 0;
1245
1246     /*
1247      * For a client side resumption with no key_share we need to generate
1248      * the handshake secret (otherwise this is done during key_share
1249      * processing).
1250      */
1251     if (!sent && !s->server && !tls13_generate_handshake_secret(s, NULL, 0)) {
1252         *al = SSL_AD_INTERNAL_ERROR;
1253         SSLerr(SSL_F_FINAL_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1254         return 0;
1255     }
1256
1257     return 1;
1258 }
1259 #endif
1260
1261 static int init_psk_kex_modes(SSL *s, unsigned int context)
1262 {
1263     s->ext.psk_kex_mode = TLSEXT_KEX_MODE_FLAG_NONE;
1264     return 1;
1265 }
1266
1267 int tls_psk_do_binder(SSL *s, const EVP_MD *md, const unsigned char *msgstart,
1268                       size_t binderoffset, const unsigned char *binderin,
1269                       unsigned char *binderout, SSL_SESSION *sess, int sign,
1270                       int external)
1271 {
1272     EVP_PKEY *mackey = NULL;
1273     EVP_MD_CTX *mctx = NULL;
1274     unsigned char hash[EVP_MAX_MD_SIZE], binderkey[EVP_MAX_MD_SIZE];
1275     unsigned char finishedkey[EVP_MAX_MD_SIZE], tmpbinder[EVP_MAX_MD_SIZE];
1276     unsigned char tmppsk[EVP_MAX_MD_SIZE];
1277     unsigned char *early_secret, *psk;
1278     const char resumption_label[] = "res binder";
1279     const char external_label[] = "ext binder";
1280     const char nonce_label[] = "resumption";
1281     const char *label;
1282     size_t bindersize, labelsize, hashsize = EVP_MD_size(md);
1283     int ret = -1;
1284     int usepskfored = 0;
1285
1286     if (external
1287             && s->early_data_state == SSL_EARLY_DATA_CONNECTING
1288             && s->session->ext.max_early_data == 0
1289             && sess->ext.max_early_data > 0)
1290         usepskfored = 1;
1291
1292     if (external) {
1293         label = external_label;
1294         labelsize = sizeof(external_label) - 1;
1295     } else {
1296         label = resumption_label;
1297         labelsize = sizeof(resumption_label) - 1;
1298     }
1299
1300     if (sess->master_key_length != hashsize) {
1301         SSLerr(SSL_F_TLS_PSK_DO_BINDER, SSL_R_BAD_PSK);
1302         goto err;
1303     }
1304
1305     if (external) {
1306         psk = sess->master_key;
1307     } else {
1308         psk = tmppsk;
1309         if (!tls13_hkdf_expand(s, md, sess->master_key,
1310                                (const unsigned char *)nonce_label,
1311                                sizeof(nonce_label) - 1, sess->ext.tick_nonce,
1312                                sess->ext.tick_nonce_len, psk, hashsize)) {
1313             SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1314             goto err;
1315         }
1316     }
1317
1318     /*
1319      * Generate the early_secret. On the server side we've selected a PSK to
1320      * resume with (internal or external) so we always do this. On the client
1321      * side we do this for a non-external (i.e. resumption) PSK or external PSK
1322      * that will be used for early_data so that it is in place for sending early
1323      * data. For client side external PSK not being used for early_data we
1324      * generate it but store it away for later use.
1325      */
1326     if (s->server || !external || usepskfored)
1327         early_secret = (unsigned char *)s->early_secret;
1328     else
1329         early_secret = (unsigned char *)sess->early_secret;
1330     if (!tls13_generate_secret(s, md, NULL, psk, hashsize, early_secret)) {
1331         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1332         goto err;
1333     }
1334
1335     /*
1336      * Create the handshake hash for the binder key...the messages so far are
1337      * empty!
1338      */
1339     mctx = EVP_MD_CTX_new();
1340     if (mctx == NULL
1341             || EVP_DigestInit_ex(mctx, md, NULL) <= 0
1342             || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
1343         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1344         goto err;
1345     }
1346
1347     /* Generate the binder key */
1348     if (!tls13_hkdf_expand(s, md, early_secret, (unsigned char *)label,
1349                            labelsize, hash, hashsize, binderkey, hashsize)) {
1350         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1351         goto err;
1352     }
1353
1354     /* Generate the finished key */
1355     if (!tls13_derive_finishedkey(s, md, binderkey, finishedkey, hashsize)) {
1356         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1357         goto err;
1358     }
1359
1360     if (EVP_DigestInit_ex(mctx, md, NULL) <= 0) {
1361         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1362         goto err;
1363     }
1364
1365     /*
1366      * Get a hash of the ClientHello up to the start of the binders. If we are
1367      * following a HelloRetryRequest then this includes the hash of the first
1368      * ClientHello and the HelloRetryRequest itself.
1369      */
1370     if (s->hello_retry_request) {
1371         size_t hdatalen;
1372         void *hdata;
1373
1374         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
1375         if (hdatalen <= 0) {
1376             SSLerr(SSL_F_TLS_PSK_DO_BINDER, SSL_R_BAD_HANDSHAKE_LENGTH);
1377             goto err;
1378         }
1379
1380         /*
1381          * For servers the handshake buffer data will include the second
1382          * ClientHello - which we don't want - so we need to take that bit off.
1383          */
1384         if (s->server) {
1385             PACKET hashprefix, msg;
1386
1387             /* Find how many bytes are left after the first two messages */
1388             if (!PACKET_buf_init(&hashprefix, hdata, hdatalen)
1389                     || !PACKET_forward(&hashprefix, 1)
1390                     || !PACKET_get_length_prefixed_3(&hashprefix, &msg)
1391                     || !PACKET_forward(&hashprefix, 1)
1392                     || !PACKET_get_length_prefixed_3(&hashprefix, &msg)) {
1393                 SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1394                 goto err;
1395             }
1396             hdatalen -= PACKET_remaining(&hashprefix);
1397         }
1398
1399         if (EVP_DigestUpdate(mctx, hdata, hdatalen) <= 0) {
1400             SSLerr(SSL_F_TLS_PSK_DO_BINDER, 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         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1408         goto err;
1409     }
1410
1411     mackey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, finishedkey, hashsize);
1412     if (mackey == NULL) {
1413         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1414         goto err;
1415     }
1416
1417     if (!sign)
1418         binderout = tmpbinder;
1419
1420     bindersize = hashsize;
1421     if (EVP_DigestSignInit(mctx, NULL, md, NULL, mackey) <= 0
1422             || EVP_DigestSignUpdate(mctx, hash, hashsize) <= 0
1423             || EVP_DigestSignFinal(mctx, binderout, &bindersize) <= 0
1424             || bindersize != hashsize) {
1425         SSLerr(SSL_F_TLS_PSK_DO_BINDER, ERR_R_INTERNAL_ERROR);
1426         goto err;
1427     }
1428
1429     if (sign) {
1430         ret = 1;
1431     } else {
1432         /* HMAC keys can't do EVP_DigestVerify* - use CRYPTO_memcmp instead */
1433         ret = (CRYPTO_memcmp(binderin, binderout, hashsize) == 0);
1434     }
1435
1436  err:
1437     OPENSSL_cleanse(binderkey, sizeof(binderkey));
1438     OPENSSL_cleanse(finishedkey, sizeof(finishedkey));
1439     EVP_PKEY_free(mackey);
1440     EVP_MD_CTX_free(mctx);
1441
1442     return ret;
1443 }
1444
1445 static int final_early_data(SSL *s, unsigned int context, int sent, int *al)
1446 {
1447     if (!sent)
1448         return 1;
1449
1450     if (!s->server) {
1451         if (context == SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
1452                 && sent
1453                 && !s->ext.early_data_ok) {
1454             /*
1455              * If we get here then the server accepted our early_data but we
1456              * later realised that it shouldn't have done (e.g. inconsistent
1457              * ALPN)
1458              */
1459             *al = SSL_AD_ILLEGAL_PARAMETER;
1460             return 0;
1461         }
1462
1463         return 1;
1464     }
1465
1466     if (s->max_early_data == 0
1467             || !s->hit
1468             || s->session->ext.tick_identity != 0
1469             || s->early_data_state != SSL_EARLY_DATA_ACCEPTING
1470             || !s->ext.early_data_ok
1471             || s->hello_retry_request) {
1472         s->ext.early_data = SSL_EARLY_DATA_REJECTED;
1473     } else {
1474         s->ext.early_data = SSL_EARLY_DATA_ACCEPTED;
1475
1476         if (!tls13_change_cipher_state(s,
1477                     SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_SERVER_READ)) {
1478             *al = SSL_AD_INTERNAL_ERROR;
1479             return 0;
1480         }
1481     }
1482
1483     return 1;
1484 }
1485
1486 static int final_maxfragmentlen(SSL *ssl, unsigned int context, int sent, int *al)
1487 {
1488     /*
1489      * Session resumption on server-side with MFL extension active
1490      *  BUT MFL extension packet was not resent (i.e. sent == 0)
1491      */
1492     if (ssl->server && ssl->hit && USE_MAX_FRAGMENT_LENGTH_EXT(ssl->session)
1493             && !sent ) {
1494         *al = SSL_AD_MISSING_EXTENSION;
1495         return 0;
1496     }
1497
1498     /* Current SSL buffer is lower than requested MFL */
1499     if (ssl->session && USE_MAX_FRAGMENT_LENGTH_EXT(ssl->session)
1500             && ssl->max_send_fragment < GET_MAX_FRAGMENT_LENGTH(ssl->session))
1501         /* trigger a larger buffer reallocation */
1502         if (!ssl3_setup_buffers(ssl))   
1503             return 0;
1504
1505     return 1;
1506 }