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