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