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