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