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