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