Continue the extensions refactor
[openssl.git] / ssl / statem / extensions.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdlib.h>
11 #include <openssl/ocsp.h>
12 #include "../ssl_locl.h"
13 #include "statem_locl.h"
14
15 static int tls_parse_clienthello_renegotiate(SSL *s, PACKET *pkt, int *al);
16 static int tls_parse_clienthello_server_name(SSL *s, PACKET *pkt, int *al);
17 #ifndef OPENSSL_NO_SRP
18 static int tls_parse_clienthello_srp(SSL *s, PACKET *pkt, int *al);
19 #endif
20 #ifndef OPENSSL_NO_EC
21 static int tls_parse_clienthello_ec_pt_formats(SSL *s, PACKET *pkt, int *al);
22 static int tls_parse_clienthello_supported_groups(SSL *s, PACKET *pkt, int *al);
23 #endif
24 static int tls_parse_clienthello_session_ticket(SSL *s, PACKET *pkt, int *al);
25 static int tls_parse_clienthello_sig_algs(SSL *s, PACKET *pkt, int *al);
26 static int tls_parse_clienthello_status_request(SSL *s, PACKET *pkt, int *al);
27 #ifndef OPENSSL_NO_NEXTPROTONEG
28 static int tls_parse_clienthello_npn(SSL *s, PACKET *pkt, int *al);
29 #endif
30 static int tls_parse_clienthello_alpn(SSL *s, PACKET *pkt, int *al);
31 #ifndef OPENSSL_NO_SRTP
32 static int tls_parse_clienthello_use_srtp(SSL *s, PACKET *pkt, int *al);
33 #endif
34 static int tls_parse_clienthello_etm(SSL *s, PACKET *pkt, int *al);
35 static int tls_parse_clienthello_key_share(SSL *s, PACKET *pkt, int *al);
36 static int tls_parse_clienthello_ems(SSL *s, PACKET *pkt, int *al);
37
38 typedef struct {
39     /* The ID for the extension */
40     unsigned int type;
41     int (*server_parse)(SSL *s, PACKET *pkt, int *al);
42     int (*client_parse)(SSL *s, PACKET *pkt, int *al);
43     int (*server_construct)(SSL *s, WPACKET *pkt, int *al);
44     int (*client_construct)(SSL *s, WPACKET *pkt, int *al);
45     unsigned int context;
46 } EXTENSION_DEFINITION;
47
48 static const EXTENSION_DEFINITION ext_defs[] = {
49     {
50         TLSEXT_TYPE_renegotiate,
51         tls_parse_clienthello_renegotiate,
52         NULL,
53         NULL,
54         NULL,
55         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_SSL3_ALLOWED
56         | EXT_TLS1_2_AND_BELOW_ONLY
57     },
58     {
59         TLSEXT_TYPE_server_name,
60         tls_parse_clienthello_server_name,
61         NULL,
62         NULL,
63         NULL,
64         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
65         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
66     },
67 #ifndef OPENSSL_NO_SRP
68     {
69         TLSEXT_TYPE_srp,
70         tls_parse_clienthello_srp,
71         NULL,
72         NULL,
73         NULL,
74         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
75     },
76 #endif
77 #ifndef OPENSSL_NO_EC
78     {
79         TLSEXT_TYPE_ec_point_formats,
80         tls_parse_clienthello_ec_pt_formats,
81         NULL,
82         NULL,
83         NULL,
84         EXT_CLIENT_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
85     },
86     {
87         TLSEXT_TYPE_supported_groups,
88         tls_parse_clienthello_supported_groups,
89         NULL,
90         NULL,
91         NULL,
92         EXT_CLIENT_HELLO | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
93     },
94 #endif
95     {
96         TLSEXT_TYPE_session_ticket,
97         tls_parse_clienthello_session_ticket,
98         NULL,
99         NULL,
100         NULL,
101         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
102     },
103     {
104         TLSEXT_TYPE_signature_algorithms,
105         tls_parse_clienthello_sig_algs,
106         NULL,
107         NULL,
108         NULL,
109         EXT_CLIENT_HELLO
110     },
111     {
112         TLSEXT_TYPE_status_request,
113         tls_parse_clienthello_status_request,
114         NULL,
115         NULL,
116         NULL,
117         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_3_CERTIFICATE
118     },
119 #ifndef OPENSSL_NO_NEXTPROTONEG
120     {
121         TLSEXT_TYPE_next_proto_neg,
122         tls_parse_clienthello_npn,
123         NULL,
124         NULL,
125         NULL,
126         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
127     },
128 #endif
129     {
130         TLSEXT_TYPE_application_layer_protocol_negotiation,
131         tls_parse_clienthello_alpn,
132         NULL,
133         NULL,
134         NULL,
135         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
136         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS
137     },
138     {
139         TLSEXT_TYPE_use_srtp,
140         tls_parse_clienthello_use_srtp,
141         NULL,
142         NULL,
143         NULL,
144         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO
145         | EXT_TLS1_3_ENCRYPTED_EXTENSIONS | EXT_DTLS_ONLY
146     },
147     {
148         TLSEXT_TYPE_encrypt_then_mac,
149         tls_parse_clienthello_etm,
150         NULL,
151         NULL,
152         NULL,
153         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
154     },
155     {
156         TLSEXT_TYPE_signed_certificate_timestamp,
157         /*
158          * No server side support for this, but can be provided by a custom
159          * extension. This is an exception to the rule that custom extensions
160          * cannot override built in ones.
161          */
162         NULL,
163         NULL,
164         NULL,
165         NULL,
166         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_3_CERTIFICATE
167     },
168     {
169         TLSEXT_TYPE_extended_master_secret,
170         tls_parse_clienthello_ems,
171         NULL,
172         EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO | EXT_TLS1_2_AND_BELOW_ONLY
173     },
174     {
175         TLSEXT_TYPE_supported_versions,
176         /* Processed inline as part of version selection */
177         NULL,
178         NULL,
179         NULL,
180         NULL,
181         EXT_CLIENT_HELLO | EXT_TLS_IMPLEMENTATION_ONLY
182     },
183     {
184         TLSEXT_TYPE_padding,
185         /* We send this, but don't read it */
186         NULL,
187         NULL,
188         NULL,
189         NULL,
190         EXT_CLIENT_HELLO
191     },
192     {
193         TLSEXT_TYPE_key_share,
194         tls_parse_clienthello_key_share,
195         NULL,
196         NULL,
197         NULL,
198         EXT_CLIENT_HELLO | EXT_TLS1_3_SERVER_HELLO
199         | EXT_TLS1_3_HELLO_RETRY_REQUEST | EXT_TLS_IMPLEMENTATION_ONLY
200         | EXT_TLS1_3_ONLY
201     }
202 };
203
204 /*
205  * Comparison function used in a call to qsort (see tls_collect_extensions()
206  * below.)
207  * The two arguments |p1| and |p2| are expected to be pointers to RAW_EXTENSIONs
208  *
209  * Returns:
210  *  1 if the type for p1 is greater than p2
211  *  0 if the type for p1 and p2 are the same
212  * -1 if the type for p1 is less than p2
213  */
214 static int compare_extensions(const void *p1, const void *p2)
215 {
216     const RAW_EXTENSION *e1 = (const RAW_EXTENSION *)p1;
217     const RAW_EXTENSION *e2 = (const RAW_EXTENSION *)p2;
218
219     if (e1->type < e2->type)
220         return -1;
221     else if (e1->type > e2->type)
222         return 1;
223
224     return 0;
225 }
226
227 /*
228  * Verify whether we are allowed to use the extension |type| in the current
229  * |context|. Returns 1 to indicate the extension is allowed or unknown or 0 to
230  * indicate the extension is not allowed.
231  */
232 static int verify_extension(SSL *s, unsigned int context, unsigned int type)
233 {
234     size_t i;
235
236     for (i = 0; i < OSSL_NELEM(ext_defs); i++) {
237         if (type == ext_defs[i].type) {
238             /* Check we're allowed to use this extension in this context */
239             if ((context & ext_defs[i].context) == 0)
240                 return 0;
241
242             if (SSL_IS_DTLS(s)) {
243                 if ((ext_defs[i].context & EXT_TLS_ONLY) != 0)
244                     return 0;
245             } else if ((ext_defs[i].context & EXT_DTLS_ONLY) != 0) {
246                     return 0;
247             }
248
249             return 1;
250         }
251     }
252
253     /* Unknown extension. We allow it */
254     return 1;
255 }
256
257 /*
258  * Finds an extension definition for the give extension |type|.
259  * Returns 1 if found and stores the definition in |*def|, or returns 0
260  * otherwise.
261  */
262 static int find_extension_definition(SSL *s, unsigned int type,
263                                      const EXTENSION_DEFINITION **def)
264 {
265     size_t i;
266
267     for (i = 0; i < OSSL_NELEM(ext_defs); i++) {
268         if (type == ext_defs[i].type) {
269             *def = &ext_defs[i];
270             return 1;
271         }
272     }
273
274     /* Unknown extension */
275     return 0;
276 }
277
278 /*
279  * Gather a list of all the extensions from the data in |packet]. |context|
280  * tells us which message this extension is for. The raw extension data is
281  * stored in |*res| with the number of found extensions in |*numfound|. In the
282  * event of an error the alert type to use is stored in |*ad|. We don't actually
283  * process the content of the extensions yet, except to check their types.
284  *
285  * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be
286  * more than one extension of the same type in a ClientHello or ServerHello.
287  * This function returns 1 if all extensions are unique and we have parsed their
288  * types, and 0 if the extensions contain duplicates, could not be successfully
289  * parsed, or an internal error occurred.
290  */
291 /*
292  * TODO(TLS1.3): Refactor ServerHello extension parsing to use this and then
293  * remove tls1_check_duplicate_extensions()
294  */
295 int tls_collect_extensions(SSL *s, PACKET *packet, unsigned int context,
296                            RAW_EXTENSION **res, size_t *numfound, int *ad)
297 {
298     PACKET extensions = *packet;
299     size_t num_extensions = 0, i = 0;
300     RAW_EXTENSION *raw_extensions = NULL;
301
302     /* First pass: count the extensions. */
303     while (PACKET_remaining(&extensions) > 0) {
304         unsigned int type;
305         PACKET extension;
306
307         if (!PACKET_get_net_2(&extensions, &type) ||
308             !PACKET_get_length_prefixed_2(&extensions, &extension)) {
309             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
310             *ad = SSL_AD_DECODE_ERROR;
311             goto err;
312         }
313         /* Verify this extension is allowed */
314         if (!verify_extension(s, context, type)) {
315             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_BAD_EXTENSION);
316             *ad = SSL_AD_ILLEGAL_PARAMETER;
317             goto err;
318         }
319         num_extensions++;
320     }
321
322     if (num_extensions > 0) {
323         raw_extensions = OPENSSL_zalloc(sizeof(*raw_extensions)
324                                         * num_extensions);
325         if (raw_extensions == NULL) {
326             *ad = SSL_AD_INTERNAL_ERROR;
327             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, ERR_R_MALLOC_FAILURE);
328             goto err;
329         }
330
331         /* Second pass: collect the extensions. */
332         for (i = 0; i < num_extensions; i++) {
333             if (!PACKET_get_net_2(packet, &raw_extensions[i].type) ||
334                 !PACKET_get_length_prefixed_2(packet,
335                                               &raw_extensions[i].data)) {
336                 /* This should not happen. */
337                 *ad = SSL_AD_INTERNAL_ERROR;
338                 SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
339                 goto err;
340             }
341         }
342
343         if (PACKET_remaining(packet) != 0) {
344             *ad = SSL_AD_DECODE_ERROR;
345             SSLerr(SSL_F_TLS_COLLECT_EXTENSIONS, SSL_R_LENGTH_MISMATCH);
346             goto err;
347         }
348         /* Sort the extensions and make sure there are no duplicates. */
349         qsort(raw_extensions, num_extensions, sizeof(*raw_extensions),
350               compare_extensions);
351         for (i = 1; i < num_extensions; i++) {
352             if (raw_extensions[i - 1].type == raw_extensions[i].type) {
353                 *ad = SSL_AD_DECODE_ERROR;
354                 goto err;
355             }
356         }
357     }
358
359     *res = raw_extensions;
360     *numfound = num_extensions;
361     return 1;
362
363  err:
364     OPENSSL_free(raw_extensions);
365     return 0;
366 }
367
368 int tls_parse_all_extensions(SSL *s, RAW_EXTENSION *exts, size_t numexts,
369                              int *al)
370 {
371     size_t loop;
372
373     for (loop = 0; loop < numexts; loop++) {
374         RAW_EXTENSION *currext = &exts[loop];
375         const EXTENSION_DEFINITION *extdef = NULL;
376         int (*parser)(SSL *s, PACKET *pkt, int *al) = NULL;
377
378         if (s->tlsext_debug_cb)
379             s->tlsext_debug_cb(s, 0, currext->type,
380                                PACKET_data(&currext->data),
381                                PACKET_remaining(&currext->data),
382                                s->tlsext_debug_arg);
383
384         /* Skip if we've already parsed this extension */
385         if (currext->parsed)
386             continue;
387
388         currext->parsed = 1;
389
390         parser = NULL;
391         if (find_extension_definition(s, currext->type, &extdef)) {
392             parser = s->server ? extdef->server_parse : extdef->client_parse;
393
394             /* Check if extension is defined for our protocol. If not, skip */
395             if ((SSL_IS_DTLS(s)
396                         && (extdef->context & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
397                     || (s->version == SSL3_VERSION
398                             && (extdef->context & EXT_SSL3_ALLOWED) == 0)
399                     || (SSL_IS_TLS13(s)
400                         && (extdef->context & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
401                     || (!SSL_IS_TLS13(s)
402                         && (extdef->context & EXT_TLS1_3_ONLY) != 0))
403                 continue;
404         }
405
406         if (parser == NULL) {
407             /*
408              * Could be a custom extension. We only allow this if it is a non
409              * resumed session on the server side.
410              * 
411              * TODO(TLS1.3): We only allow old style <=TLS1.2 custom extensions.
412              * We're going to need a new mechanism for TLS1.3 to specify which
413              * messages to add the custom extensions to.
414              */
415             if ((!s->hit || !s->server)
416                     && (context
417                         & (EXT_CLIENT_HELLO | EXT_TLS1_2_SERVER_HELLO)) != 0
418                     && custom_ext_parse(s, s->server, currext->type,
419                                         PACKET_data(&currext->data),
420                                         PACKET_remaining(&currext->data),
421                                         al) <= 0)
422                 return 0;
423
424             continue;
425         }
426
427         if (!parser(s, &currext->data, al))
428             return 0;
429     }
430
431     return 1;
432 }
433
434 /*
435  * Find a specific extension by |type| in the list |exts| containing |numexts|
436  * extensions, and the parse it immediately. Returns 1 on success, or 0 on
437  * failure. If a failure has occurred then |*al| will also be set to the alert
438  * to be sent.
439  */
440 int tls_parse_extension(SSL *s, int type,  RAW_EXTENSION *exts, size_t numexts,
441                         int *al)
442 {
443     RAW_EXTENSION *ext = tls_get_extension_by_type(exts, numexts, type);
444
445     if (ext == NULL)
446         return 1;
447
448     return tls_parse_all_extensions(s, ext, 1, al);
449 }
450
451 int tls_construct_extensions(SSL *s, WPACKET *pkt, unsigned int context,
452                              int *al)
453 {
454     size_t loop;
455     int addcustom = 0;
456
457     if (!WPACKET_start_sub_packet_u16(pkt)
458                /*
459                 * If extensions are of zero length then we don't even add the
460                 * extensions length bytes to a ClientHello
461                 */
462             || ((context & EXT_CLIENT_HELLO) != 0
463                && !WPACKET_set_flags(pkt,
464                                      WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH))) {
465         *al = SSL_AD_INTERNAL_ERROR;
466         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
467         return 0;
468     }
469
470     for (loop = 0; loop < OSSL_NELEM(ext_defs); loop++) {
471         /* Skip if not relevant for our context */
472         if ((ext_defs[loop].context & context) == 0)
473             continue;
474
475         construct = s->server ? extdef->server_construct
476                               : extdef->client_construct;
477
478         /* Check if this extension is defined for our protocol. If not, skip */
479         if ((SSL_IS_DTLS(s)
480                     && (extdef->context & EXT_TLS_IMPLEMENTATION_ONLY) != 0)
481                 || (s->version == SSL3_VERSION
482                         && (extdef->context & EXT_SSL3_ALLOWED) == 0)
483                 || (SSL_IS_TLS13(s)
484                     && (extdef->context & EXT_TLS1_2_AND_BELOW_ONLY) != 0)
485                 || (!SSL_IS_TLS13(s)
486                     && ((extdef->context & EXT_TLS1_3_ONLY) != 0
487                         || (context & EXT_CLIENT_HELLO) != 0))
488                 || construct == NULL)
489             continue;
490
491         if (!construct(s, pkt, al))
492             return 0;
493     }
494
495
496     /* Add custom extensions */
497     if ((context & EXT_CLIENT_HELLO) != 0) {
498         custom_ext_init(&s->cert->cli_ext);
499         addcustom = 1;
500     } else if (context & (EXT_TLS1_2_SERVER_HELLO) {
501         /*
502          * We already initialised the custom extensions during ClientHello
503          * parsing.
504          * 
505          * TODO(TLS1.3): We're going to need a new custom extension mechanism
506          * for TLS1.3, so that custom extensions can specify which of the
507          * multiple message they wish to add themselves to.
508          */
509         addcustom = 1;
510     }
511     if (addcustom && !custom_ext_add(s, s->server, pkt, al)) {
512         SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
513         return 0;
514     }
515
516     if (!WPACKET_close(pkt)) {
517         *sl = SSL_AD_INTERNAL_ERROR;
518         SSLerr(SSL_F_TLS_CONSTRUCT_EXTENSIONS, ERR_R_INTERNAL_ERROR);
519         return 0;
520     }
521
522     return 1;
523 }
524
525
526 /*
527  * Parse the client's renegotiation binding and abort if it's not right
528  */
529 static int tls_parse_clienthello_renegotiate(SSL *s, PACKET *pkt, int *al)
530 {
531     unsigned int ilen;
532     const unsigned char *data;
533
534     /* Parse the length byte */
535     if (!PACKET_get_1(pkt, &ilen)
536         || !PACKET_get_bytes(pkt, &data, ilen)) {
537         SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT,
538                SSL_R_RENEGOTIATION_ENCODING_ERR);
539         *al = SSL_AD_ILLEGAL_PARAMETER;
540         return 0;
541     }
542
543     /* Check that the extension matches */
544     if (ilen != s->s3->previous_client_finished_len) {
545         SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT,
546                SSL_R_RENEGOTIATION_MISMATCH);
547         *al = SSL_AD_HANDSHAKE_FAILURE;
548         return 0;
549     }
550
551     if (memcmp(data, s->s3->previous_client_finished,
552                s->s3->previous_client_finished_len)) {
553         SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT,
554                SSL_R_RENEGOTIATION_MISMATCH);
555         *al = SSL_AD_HANDSHAKE_FAILURE;
556         return 0;
557     }
558
559     s->s3->send_connection_binding = 1;
560
561     return 1;
562 }
563
564 static int tls_parse_clienthello_server_name(SSL *s, PACKET *pkt, int *al)
565 {
566     unsigned int servname_type;
567     PACKET sni, hostname;
568
569     /*-
570      * The servername extension is treated as follows:
571      *
572      * - Only the hostname type is supported with a maximum length of 255.
573      * - The servername is rejected if too long or if it contains zeros,
574      *   in which case an fatal alert is generated.
575      * - The servername field is maintained together with the session cache.
576      * - When a session is resumed, the servername call back invoked in order
577      *   to allow the application to position itself to the right context.
578      * - The servername is acknowledged if it is new for a session or when
579      *   it is identical to a previously used for the same session.
580      *   Applications can control the behaviour.  They can at any time
581      *   set a 'desirable' servername for a new SSL object. This can be the
582      *   case for example with HTTPS when a Host: header field is received and
583      *   a renegotiation is requested. In this case, a possible servername
584      *   presented in the new client hello is only acknowledged if it matches
585      *   the value of the Host: field.
586      * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
587      *   if they provide for changing an explicit servername context for the
588      *   session, i.e. when the session has been established with a servername
589      *   extension.
590      * - On session reconnect, the servername extension may be absent.
591      *
592      */
593     if (!PACKET_as_length_prefixed_2(pkt, &sni)
594         /* ServerNameList must be at least 1 byte long. */
595         || PACKET_remaining(&sni) == 0) {
596         *al = SSL_AD_DECODE_ERROR;
597         return 0;
598     }
599
600     /*
601      * Although the server_name extension was intended to be
602      * extensible to new name types, RFC 4366 defined the
603      * syntax inextensibility and OpenSSL 1.0.x parses it as
604      * such.
605      * RFC 6066 corrected the mistake but adding new name types
606      * is nevertheless no longer feasible, so act as if no other
607      * SNI types can exist, to simplify parsing.
608      *
609      * Also note that the RFC permits only one SNI value per type,
610      * i.e., we can only have a single hostname.
611      */
612     if (!PACKET_get_1(&sni, &servname_type)
613         || servname_type != TLSEXT_NAMETYPE_host_name
614         || !PACKET_as_length_prefixed_2(&sni, &hostname)) {
615         *al = SSL_AD_DECODE_ERROR;
616         return 0;
617     }
618
619     if (!s->hit) {
620         if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) {
621             *al = TLS1_AD_UNRECOGNIZED_NAME;
622             return 0;
623         }
624
625         if (PACKET_contains_zero_byte(&hostname)) {
626             *al = TLS1_AD_UNRECOGNIZED_NAME;
627             return 0;
628         }
629
630         if (!PACKET_strndup(&hostname, &s->session->tlsext_hostname)) {
631             *al = TLS1_AD_INTERNAL_ERROR;
632             return 0;
633         }
634
635         s->servername_done = 1;
636     } else {
637         /*
638          * TODO(openssl-team): if the SNI doesn't match, we MUST
639          * fall back to a full handshake.
640          */
641         s->servername_done = s->session->tlsext_hostname
642             && PACKET_equal(&hostname, s->session->tlsext_hostname,
643                             strlen(s->session->tlsext_hostname));
644     }
645
646     return 1;
647 }
648
649 #ifndef OPENSSL_NO_SRP
650 static int tls_parse_clienthello_srp(SSL *s, PACKET *pkt, int *al)
651 {
652     PACKET srp_I;
653
654     if (!PACKET_as_length_prefixed_1(pkt, &srp_I)
655             || PACKET_contains_zero_byte(&srp_I)) {
656         *al = SSL_AD_DECODE_ERROR;
657         return 0;
658     }
659
660     /*
661      * TODO(openssl-team): currently, we re-authenticate the user
662      * upon resumption. Instead, we MUST ignore the login.
663      */
664     if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) {
665         *al = TLS1_AD_INTERNAL_ERROR;
666         return 0;
667     }
668
669     return 1;
670 }
671 #endif
672
673 #ifndef OPENSSL_NO_EC
674 static int tls_parse_clienthello_ec_pt_formats(SSL *s, PACKET *pkt, int *al)
675 {
676     PACKET ec_point_format_list;
677
678     if (!PACKET_as_length_prefixed_1(pkt, &ec_point_format_list)
679         || PACKET_remaining(&ec_point_format_list) == 0) {
680         *al = SSL_AD_DECODE_ERROR;
681         return 0;
682     }
683
684     if (!s->hit) {
685         if (!PACKET_memdup(&ec_point_format_list,
686                            &s->session->tlsext_ecpointformatlist,
687                            &s->session->tlsext_ecpointformatlist_length)) {
688             *al = TLS1_AD_INTERNAL_ERROR;
689             return 0;
690         }
691     }
692
693     return 1;
694 }
695 #endif                          /* OPENSSL_NO_EC */
696
697 static int tls_parse_clienthello_session_ticket(SSL *s, PACKET *pkt, int *al)
698 {
699     if (s->tls_session_ticket_ext_cb &&
700             !s->tls_session_ticket_ext_cb(s, PACKET_data(pkt),
701                                           PACKET_remaining(pkt),
702                                           s->tls_session_ticket_ext_cb_arg)) {
703         *al = TLS1_AD_INTERNAL_ERROR;
704         return 0;
705     }
706
707     return 1;
708 }
709
710 static int tls_parse_clienthello_sig_algs(SSL *s, PACKET *pkt, int *al)
711 {
712     PACKET supported_sig_algs;
713
714     if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
715             || (PACKET_remaining(&supported_sig_algs) % 2) != 0
716             || PACKET_remaining(&supported_sig_algs) == 0) {
717         *al = SSL_AD_DECODE_ERROR;
718         return 0;
719     }
720
721     if (!s->hit && !tls1_save_sigalgs(s, PACKET_data(&supported_sig_algs),
722                                       PACKET_remaining(&supported_sig_algs))) {
723         *al = TLS1_AD_INTERNAL_ERROR;
724         return 0;
725     }
726
727     return 1;
728 }
729
730 static int tls_parse_clienthello_status_request(SSL *s, PACKET *pkt, int *al)
731 {
732     if (!PACKET_get_1(pkt, (unsigned int *)&s->tlsext_status_type)) {
733         *al = SSL_AD_DECODE_ERROR;
734         return 0;
735     }
736 #ifndef OPENSSL_NO_OCSP
737     if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
738         const unsigned char *ext_data;
739         PACKET responder_id_list, exts;
740         if (!PACKET_get_length_prefixed_2 (pkt, &responder_id_list)) {
741             *al = SSL_AD_DECODE_ERROR;
742             return 0;
743         }
744
745         /*
746          * We remove any OCSP_RESPIDs from a previous handshake
747          * to prevent unbounded memory growth - CVE-2016-6304
748          */
749         sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
750         if (PACKET_remaining(&responder_id_list) > 0) {
751             s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
752             if (s->tlsext_ocsp_ids == NULL) {
753                 *al = SSL_AD_INTERNAL_ERROR;
754                 return 0;
755             }
756         } else {
757             s->tlsext_ocsp_ids = NULL;
758         }
759
760         while (PACKET_remaining(&responder_id_list) > 0) {
761             OCSP_RESPID *id;
762             PACKET responder_id;
763             const unsigned char *id_data;
764
765             if (!PACKET_get_length_prefixed_2(&responder_id_list,
766                                               &responder_id)
767                     || PACKET_remaining(&responder_id) == 0) {
768                 *al = SSL_AD_DECODE_ERROR;
769                 return 0;
770             }
771
772             id_data = PACKET_data(&responder_id);
773             /* TODO(size_t): Convert d2i_* to size_t */
774             id = d2i_OCSP_RESPID(NULL, &id_data,
775                                  (int)PACKET_remaining(&responder_id));
776             if (id == NULL) {
777                 *al = SSL_AD_DECODE_ERROR;
778                 return 0;
779             }
780
781             if (id_data != PACKET_end(&responder_id)) {
782                 OCSP_RESPID_free(id);
783                 *al = SSL_AD_DECODE_ERROR;
784                 return 0;
785             }
786
787             if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
788                 OCSP_RESPID_free(id);
789                 *al = SSL_AD_INTERNAL_ERROR;
790                 return 0;
791             }
792         }
793
794         /* Read in request_extensions */
795         if (!PACKET_as_length_prefixed_2(pkt, &exts)) {
796             *al = SSL_AD_DECODE_ERROR;
797             return 0;
798         }
799
800         if (PACKET_remaining(&exts) > 0) {
801             ext_data = PACKET_data(&exts);
802             sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
803                                        X509_EXTENSION_free);
804             s->tlsext_ocsp_exts =
805                 d2i_X509_EXTENSIONS(NULL, &ext_data,
806                                     (int)PACKET_remaining(&exts));
807             if (s->tlsext_ocsp_exts == NULL || ext_data != PACKET_end(&exts)) {
808                 *al = SSL_AD_DECODE_ERROR;
809                 return 0;
810             }
811         }
812     } else
813 #endif
814     {
815         /*
816          * We don't know what to do with any other type so ignore it.
817          */
818         s->tlsext_status_type = -1;
819     }
820
821     return 1;
822 }
823
824 #ifndef OPENSSL_NO_NEXTPROTONEG
825 static int tls_parse_clienthello_npn(SSL *s, PACKET *pkt, int *al)
826 {
827     if (s->s3->tmp.finish_md_len == 0) {
828         /*-
829          * We shouldn't accept this extension on a
830          * renegotiation.
831          *
832          * s->new_session will be set on renegotiation, but we
833          * probably shouldn't rely that it couldn't be set on
834          * the initial renegotiation too in certain cases (when
835          * there's some other reason to disallow resuming an
836          * earlier session -- the current code won't be doing
837          * anything like that, but this might change).
838          *
839          * A valid sign that there's been a previous handshake
840          * in this connection is if s->s3->tmp.finish_md_len >
841          * 0.  (We are talking about a check that will happen
842          * in the Hello protocol round, well before a new
843          * Finished message could have been computed.)
844          */
845         s->s3->next_proto_neg_seen = 1;
846     }
847
848     return 1;
849 }
850 #endif
851
852 /*
853  * Save the ALPN extension in a ClientHello.
854  * pkt: the contents of the ALPN extension, not including type and length.
855  * al: a pointer to the  alert value to send in the event of a failure.
856  * returns: 1 on success, 0 on error.
857  */
858 static int tls_parse_clienthello_alpn(SSL *s, PACKET *pkt, int *al)
859 {
860     PACKET protocol_list, save_protocol_list, protocol;
861
862     if (s->s3->tmp.finish_md_len != 0)
863         return 1;
864
865     if (!PACKET_as_length_prefixed_2(pkt, &protocol_list)
866         || PACKET_remaining(&protocol_list) < 2) {
867         *al = SSL_AD_DECODE_ERROR;
868         return 0;
869     }
870
871     save_protocol_list = protocol_list;
872     do {
873         /* Protocol names can't be empty. */
874         if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol)
875                 || PACKET_remaining(&protocol) == 0) {
876             *al = SSL_AD_DECODE_ERROR;
877             return 0;
878         }
879     } while (PACKET_remaining(&protocol_list) != 0);
880
881     if (!PACKET_memdup(&save_protocol_list,
882                        &s->s3->alpn_proposed, &s->s3->alpn_proposed_len)) {
883         *al = TLS1_AD_INTERNAL_ERROR;
884         return 0;
885     }
886
887     return 1;
888 }
889
890 #ifndef OPENSSL_NO_SRTP
891 static int tls_parse_clienthello_use_srtp(SSL *s, PACKET *pkt, int *al)
892 {
893     SRTP_PROTECTION_PROFILE *sprof;
894     STACK_OF(SRTP_PROTECTION_PROFILE) *srvr;
895     unsigned int ct, mki_len, id;
896     int i, srtp_pref;
897     PACKET subpkt;
898
899     /* Ignore this if we have no SRTP profiles */
900     if (SSL_get_srtp_profiles(s) == NULL)
901         return 1;
902
903     /* Pull off the length of the cipher suite list  and check it is even */
904     if (!PACKET_get_net_2(pkt, &ct)
905         || (ct & 1) != 0 || !PACKET_get_sub_packet(pkt, &subpkt, ct)) {
906         SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP,
907                SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
908         *al = SSL_AD_DECODE_ERROR;
909         return 0;
910     }
911
912     srvr = SSL_get_srtp_profiles(s);
913     s->srtp_profile = NULL;
914     /* Search all profiles for a match initially */
915     srtp_pref = sk_SRTP_PROTECTION_PROFILE_num(srvr);
916
917     while (PACKET_remaining(&subpkt)) {
918         if (!PACKET_get_net_2(&subpkt, &id)) {
919             SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP,
920                    SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
921             *al = SSL_AD_DECODE_ERROR;
922             return 0;
923         }
924
925         /*
926          * Only look for match in profiles of higher preference than
927          * current match.
928          * If no profiles have been have been configured then this
929          * does nothing.
930          */
931         for (i = 0; i < srtp_pref; i++) {
932             sprof = sk_SRTP_PROTECTION_PROFILE_value(srvr, i);
933             if (sprof->id == id) {
934                 s->srtp_profile = sprof;
935                 srtp_pref = i;
936                 break;
937             }
938         }
939     }
940
941     /*
942      * Now extract the MKI value as a sanity check, but discard it for now
943      */
944     if (!PACKET_get_1(pkt, &mki_len)) {
945         SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP,
946                SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
947         *al = SSL_AD_DECODE_ERROR;
948         return 0;
949     }
950
951     if (!PACKET_forward(pkt, mki_len)
952         || PACKET_remaining(pkt)) {
953         SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_USE_SRTP, SSL_R_BAD_SRTP_MKI_VALUE);
954         *al = SSL_AD_DECODE_ERROR;
955         return 0;
956     }
957
958     return 1;
959 }
960 #endif
961
962 static int tls_parse_clienthello_etm(SSL *s, PACKET *pkt, int *al)
963 {
964     if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC))
965         s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
966
967     return 1;
968 }
969
970 /*
971  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
972  * and |checkallow| is 1 then additionally check if the group is allowed to be
973  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
974  * 1) or 0 otherwise.
975  */
976 static int check_in_list(SSL *s, unsigned int group_id,
977                          const unsigned char *groups, size_t num_groups,
978                          int checkallow)
979 {
980     size_t i;
981
982     if (groups == NULL || num_groups == 0)
983         return 0;
984
985     for (i = 0; i < num_groups; i++, groups += 2) {
986         unsigned int share_id = (groups[0] << 8) | (groups[1]);
987
988         if (group_id == share_id
989                 && (!checkallow || tls_curve_allowed(s, groups,
990                                                      SSL_SECOP_CURVE_CHECK))) {
991             break;
992         }
993     }
994
995     /* If i == num_groups then not in the list */
996     return i < num_groups;
997 }
998
999 /*
1000  * Process a key_share extension received in the ClientHello. |pkt| contains
1001  * the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
1002  * If a failure occurs then |*al| is set to an appropriate alert value.
1003  */
1004 static int tls_parse_clienthello_key_share(SSL *s, PACKET *pkt, int *al)
1005 {
1006     unsigned int group_id;
1007     PACKET key_share_list, encoded_pt;
1008     const unsigned char *clntcurves, *srvrcurves;
1009     size_t clnt_num_curves, srvr_num_curves;
1010     int group_nid, found = 0;
1011     unsigned int curve_flags;
1012
1013     if (s->hit)
1014         return 1;
1015
1016     /* Sanity check */
1017     if (s->s3->peer_tmp != NULL) {
1018         *al = SSL_AD_INTERNAL_ERROR;
1019         SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1020         return 0;
1021     }
1022
1023     if (!PACKET_as_length_prefixed_2(pkt, &key_share_list)) {
1024         *al = SSL_AD_HANDSHAKE_FAILURE;
1025         SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, SSL_R_LENGTH_MISMATCH);
1026         return 0;
1027     }
1028
1029     /* Get our list of supported curves */
1030     if (!tls1_get_curvelist(s, 0, &srvrcurves, &srvr_num_curves)) {
1031         *al = SSL_AD_INTERNAL_ERROR;
1032         SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1033         return 0;
1034     }
1035
1036     /* Get the clients list of supported curves */
1037     if (!tls1_get_curvelist(s, 1, &clntcurves, &clnt_num_curves)) {
1038         *al = SSL_AD_INTERNAL_ERROR;
1039         SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1040         return 0;
1041     }
1042
1043     while (PACKET_remaining(&key_share_list) > 0) {
1044         if (!PACKET_get_net_2(&key_share_list, &group_id)
1045                 || !PACKET_get_length_prefixed_2(&key_share_list, &encoded_pt)
1046                 || PACKET_remaining(&encoded_pt) == 0) {
1047             *al = SSL_AD_HANDSHAKE_FAILURE;
1048             SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE,
1049                    SSL_R_LENGTH_MISMATCH);
1050             return 0;
1051         }
1052
1053         /*
1054          * If we already found a suitable key_share we loop through the
1055          * rest to verify the structure, but don't process them.
1056          */
1057         if (found)
1058             continue;
1059
1060         /* Check if this share is in supported_groups sent from client */
1061         if (!check_in_list(s, group_id, clntcurves, clnt_num_curves, 0)) {
1062             *al = SSL_AD_HANDSHAKE_FAILURE;
1063             SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, SSL_R_BAD_KEY_SHARE);
1064             return 0;
1065         }
1066
1067         /* Check if this share is for a group we can use */
1068         if (!check_in_list(s, group_id, srvrcurves, srvr_num_curves, 1)) {
1069             /* Share not suitable */
1070             continue;
1071         }
1072
1073         group_nid = tls1_ec_curve_id2nid(group_id, &curve_flags);
1074
1075         if (group_nid == 0) {
1076             *al = SSL_AD_INTERNAL_ERROR;
1077             SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE,
1078                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1079             return 0;
1080         }
1081
1082         if ((curve_flags & TLS_CURVE_TYPE) == TLS_CURVE_CUSTOM) {
1083             /* Can happen for some curves, e.g. X25519 */
1084             EVP_PKEY *key = EVP_PKEY_new();
1085
1086             if (key == NULL || !EVP_PKEY_set_type(key, group_nid)) {
1087                 *al = SSL_AD_INTERNAL_ERROR;
1088                 SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_EVP_LIB);
1089                 EVP_PKEY_free(key);
1090                 return 0;
1091             }
1092             s->s3->peer_tmp = key;
1093         } else {
1094             /* Set up EVP_PKEY with named curve as parameters */
1095             EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
1096             if (pctx == NULL
1097                     || EVP_PKEY_paramgen_init(pctx) <= 0
1098                     || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
1099                                                               group_nid) <= 0
1100                     || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
1101                 *al = SSL_AD_INTERNAL_ERROR;
1102                 SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, ERR_R_EVP_LIB);
1103                 EVP_PKEY_CTX_free(pctx);
1104                 return 0;
1105             }
1106             EVP_PKEY_CTX_free(pctx);
1107             pctx = NULL;
1108         }
1109         s->s3->group_id = group_id;
1110
1111         if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
1112                 PACKET_data(&encoded_pt),
1113                 PACKET_remaining(&encoded_pt))) {
1114             *al = SSL_AD_DECODE_ERROR;
1115             SSLerr(SSL_F_TLS_PARSE_CLIENTHELLO_KEY_SHARE, SSL_R_BAD_ECPOINT);
1116             return 0;
1117         }
1118
1119         found = 1;
1120     }
1121
1122     return 1;
1123 }
1124
1125 #ifndef OPENSSL_NO_EC
1126 static int tls_parse_clienthello_supported_groups(SSL *s, PACKET *pkt, int *al)
1127 {
1128     PACKET supported_groups_list;
1129
1130     /* Each group is 2 bytes and we must have at least 1. */
1131     if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
1132             || PACKET_remaining(&supported_groups_list) == 0
1133             || (PACKET_remaining(&supported_groups_list) % 2) != 0) {
1134         *al = SSL_AD_DECODE_ERROR;
1135         return 0;
1136     }
1137
1138     if (!s->hit
1139             && !PACKET_memdup(&supported_groups_list,
1140                               &s->session->tlsext_supportedgroupslist,
1141                               &s->session->tlsext_supportedgroupslist_length)) {
1142         *al = SSL_AD_DECODE_ERROR;
1143         return 0;
1144     }
1145
1146     return 1;
1147 }
1148 #endif
1149
1150 static int tls_parse_clienthello_ems(SSL *s, PACKET *pkt, int *al)
1151 {
1152     /* The extension must always be empty */
1153     if (PACKET_remaining(pkt) != 0) {
1154         *al = SSL_AD_DECODE_ERROR;
1155         return 0;
1156     }
1157
1158     s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
1159
1160     return 1;
1161 }