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