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