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