Move client parsing of ServerHello extensions into new framework
[openssl.git] / ssl / statem / extensions_srvr.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 <openssl/ocsp.h>
11 #include "../ssl_locl.h"
12 #include "statem_locl.h"
13
14 /*
15  * Parse the client's renegotiation binding and abort if it's not right
16  */
17 int tls_parse_client_renegotiate(SSL *s, PACKET *pkt, int *al)
18 {
19     unsigned int ilen;
20     const unsigned char *data;
21
22     /* Parse the length byte */
23     if (!PACKET_get_1(pkt, &ilen)
24         || !PACKET_get_bytes(pkt, &data, ilen)) {
25         SSLerr(SSL_F_TLS_PARSE_CLIENT_RENEGOTIATE,
26                SSL_R_RENEGOTIATION_ENCODING_ERR);
27         *al = SSL_AD_ILLEGAL_PARAMETER;
28         return 0;
29     }
30
31     /* Check that the extension matches */
32     if (ilen != s->s3->previous_client_finished_len) {
33         SSLerr(SSL_F_TLS_PARSE_CLIENT_RENEGOTIATE,
34                SSL_R_RENEGOTIATION_MISMATCH);
35         *al = SSL_AD_HANDSHAKE_FAILURE;
36         return 0;
37     }
38
39     if (memcmp(data, s->s3->previous_client_finished,
40                s->s3->previous_client_finished_len)) {
41         SSLerr(SSL_F_TLS_PARSE_CLIENT_RENEGOTIATE,
42                SSL_R_RENEGOTIATION_MISMATCH);
43         *al = SSL_AD_HANDSHAKE_FAILURE;
44         return 0;
45     }
46
47     s->s3->send_connection_binding = 1;
48
49     return 1;
50 }
51
52 int tls_parse_client_server_name(SSL *s, PACKET *pkt, int *al)
53 {
54     unsigned int servname_type;
55     PACKET sni, hostname;
56
57     /*-
58      * The servername extension is treated as follows:
59      *
60      * - Only the hostname type is supported with a maximum length of 255.
61      * - The servername is rejected if too long or if it contains zeros,
62      *   in which case an fatal alert is generated.
63      * - The servername field is maintained together with the session cache.
64      * - When a session is resumed, the servername call back invoked in order
65      *   to allow the application to position itself to the right context.
66      * - The servername is acknowledged if it is new for a session or when
67      *   it is identical to a previously used for the same session.
68      *   Applications can control the behaviour.  They can at any time
69      *   set a 'desirable' servername for a new SSL object. This can be the
70      *   case for example with HTTPS when a Host: header field is received and
71      *   a renegotiation is requested. In this case, a possible servername
72      *   presented in the new client hello is only acknowledged if it matches
73      *   the value of the Host: field.
74      * - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
75      *   if they provide for changing an explicit servername context for the
76      *   session, i.e. when the session has been established with a servername
77      *   extension.
78      * - On session reconnect, the servername extension may be absent.
79      *
80      */
81     if (!PACKET_as_length_prefixed_2(pkt, &sni)
82         /* ServerNameList must be at least 1 byte long. */
83         || PACKET_remaining(&sni) == 0) {
84         *al = SSL_AD_DECODE_ERROR;
85         return 0;
86     }
87
88     /*
89      * Although the server_name extension was intended to be
90      * extensible to new name types, RFC 4366 defined the
91      * syntax inextensibility and OpenSSL 1.0.x parses it as
92      * such.
93      * RFC 6066 corrected the mistake but adding new name types
94      * is nevertheless no longer feasible, so act as if no other
95      * SNI types can exist, to simplify parsing.
96      *
97      * Also note that the RFC permits only one SNI value per type,
98      * i.e., we can only have a single hostname.
99      */
100     if (!PACKET_get_1(&sni, &servname_type)
101         || servname_type != TLSEXT_NAMETYPE_host_name
102         || !PACKET_as_length_prefixed_2(&sni, &hostname)) {
103         *al = SSL_AD_DECODE_ERROR;
104         return 0;
105     }
106
107     if (!s->hit) {
108         if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) {
109             *al = TLS1_AD_UNRECOGNIZED_NAME;
110             return 0;
111         }
112
113         if (PACKET_contains_zero_byte(&hostname)) {
114             *al = TLS1_AD_UNRECOGNIZED_NAME;
115             return 0;
116         }
117
118         if (!PACKET_strndup(&hostname, &s->session->tlsext_hostname)) {
119             *al = TLS1_AD_INTERNAL_ERROR;
120             return 0;
121         }
122
123         s->servername_done = 1;
124     } else {
125         /*
126          * TODO(openssl-team): if the SNI doesn't match, we MUST
127          * fall back to a full handshake.
128          */
129         s->servername_done = s->session->tlsext_hostname
130             && PACKET_equal(&hostname, s->session->tlsext_hostname,
131                             strlen(s->session->tlsext_hostname));
132     }
133
134     return 1;
135 }
136
137 #ifndef OPENSSL_NO_SRP
138 int tls_parse_client_srp(SSL *s, PACKET *pkt, int *al)
139 {
140     PACKET srp_I;
141
142     if (!PACKET_as_length_prefixed_1(pkt, &srp_I)
143             || PACKET_contains_zero_byte(&srp_I)) {
144         *al = SSL_AD_DECODE_ERROR;
145         return 0;
146     }
147
148     /*
149      * TODO(openssl-team): currently, we re-authenticate the user
150      * upon resumption. Instead, we MUST ignore the login.
151      */
152     if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) {
153         *al = TLS1_AD_INTERNAL_ERROR;
154         return 0;
155     }
156
157     return 1;
158 }
159 #endif
160
161 #ifndef OPENSSL_NO_EC
162 int tls_parse_client_ec_pt_formats(SSL *s, PACKET *pkt, int *al)
163 {
164     PACKET ec_point_format_list;
165
166     if (!PACKET_as_length_prefixed_1(pkt, &ec_point_format_list)
167         || PACKET_remaining(&ec_point_format_list) == 0) {
168         *al = SSL_AD_DECODE_ERROR;
169         return 0;
170     }
171
172     if (!s->hit) {
173         if (!PACKET_memdup(&ec_point_format_list,
174                            &s->session->tlsext_ecpointformatlist,
175                            &s->session->tlsext_ecpointformatlist_length)) {
176             *al = TLS1_AD_INTERNAL_ERROR;
177             return 0;
178         }
179     }
180
181     return 1;
182 }
183 #endif                          /* OPENSSL_NO_EC */
184
185 int tls_parse_client_session_ticket(SSL *s, PACKET *pkt, int *al)
186 {
187     if (s->tls_session_ticket_ext_cb &&
188             !s->tls_session_ticket_ext_cb(s, PACKET_data(pkt),
189                                           PACKET_remaining(pkt),
190                                           s->tls_session_ticket_ext_cb_arg)) {
191         *al = TLS1_AD_INTERNAL_ERROR;
192         return 0;
193     }
194
195     return 1;
196 }
197
198 int tls_parse_client_sig_algs(SSL *s, PACKET *pkt, int *al)
199 {
200     PACKET supported_sig_algs;
201
202     if (!PACKET_as_length_prefixed_2(pkt, &supported_sig_algs)
203             || (PACKET_remaining(&supported_sig_algs) % 2) != 0
204             || PACKET_remaining(&supported_sig_algs) == 0) {
205         *al = SSL_AD_DECODE_ERROR;
206         return 0;
207     }
208
209     if (!s->hit && !tls1_save_sigalgs(s, PACKET_data(&supported_sig_algs),
210                                       PACKET_remaining(&supported_sig_algs))) {
211         *al = TLS1_AD_INTERNAL_ERROR;
212         return 0;
213     }
214
215     return 1;
216 }
217
218 int tls_parse_client_status_request(SSL *s, PACKET *pkt, int *al)
219 {
220     if (!PACKET_get_1(pkt, (unsigned int *)&s->tlsext_status_type)) {
221         *al = SSL_AD_DECODE_ERROR;
222         return 0;
223     }
224 #ifndef OPENSSL_NO_OCSP
225     if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
226         const unsigned char *ext_data;
227         PACKET responder_id_list, exts;
228         if (!PACKET_get_length_prefixed_2 (pkt, &responder_id_list)) {
229             *al = SSL_AD_DECODE_ERROR;
230             return 0;
231         }
232
233         /*
234          * We remove any OCSP_RESPIDs from a previous handshake
235          * to prevent unbounded memory growth - CVE-2016-6304
236          */
237         sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
238         if (PACKET_remaining(&responder_id_list) > 0) {
239             s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null();
240             if (s->tlsext_ocsp_ids == NULL) {
241                 *al = SSL_AD_INTERNAL_ERROR;
242                 return 0;
243             }
244         } else {
245             s->tlsext_ocsp_ids = NULL;
246         }
247
248         while (PACKET_remaining(&responder_id_list) > 0) {
249             OCSP_RESPID *id;
250             PACKET responder_id;
251             const unsigned char *id_data;
252
253             if (!PACKET_get_length_prefixed_2(&responder_id_list,
254                                               &responder_id)
255                     || PACKET_remaining(&responder_id) == 0) {
256                 *al = SSL_AD_DECODE_ERROR;
257                 return 0;
258             }
259
260             id_data = PACKET_data(&responder_id);
261             /* TODO(size_t): Convert d2i_* to size_t */
262             id = d2i_OCSP_RESPID(NULL, &id_data,
263                                  (int)PACKET_remaining(&responder_id));
264             if (id == NULL) {
265                 *al = SSL_AD_DECODE_ERROR;
266                 return 0;
267             }
268
269             if (id_data != PACKET_end(&responder_id)) {
270                 OCSP_RESPID_free(id);
271                 *al = SSL_AD_DECODE_ERROR;
272                 return 0;
273             }
274
275             if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
276                 OCSP_RESPID_free(id);
277                 *al = SSL_AD_INTERNAL_ERROR;
278                 return 0;
279             }
280         }
281
282         /* Read in request_extensions */
283         if (!PACKET_as_length_prefixed_2(pkt, &exts)) {
284             *al = SSL_AD_DECODE_ERROR;
285             return 0;
286         }
287
288         if (PACKET_remaining(&exts) > 0) {
289             ext_data = PACKET_data(&exts);
290             sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
291                                        X509_EXTENSION_free);
292             s->tlsext_ocsp_exts =
293                 d2i_X509_EXTENSIONS(NULL, &ext_data,
294                                     (int)PACKET_remaining(&exts));
295             if (s->tlsext_ocsp_exts == NULL || ext_data != PACKET_end(&exts)) {
296                 *al = SSL_AD_DECODE_ERROR;
297                 return 0;
298             }
299         }
300     } else
301 #endif
302     {
303         /*
304          * We don't know what to do with any other type so ignore it.
305          */
306         s->tlsext_status_type = -1;
307     }
308
309     return 1;
310 }
311
312 #ifndef OPENSSL_NO_NEXTPROTONEG
313 int tls_parse_client_npn(SSL *s, PACKET *pkt, int *al)
314 {
315     if (s->s3->tmp.finish_md_len == 0) {
316         /*-
317          * We shouldn't accept this extension on a
318          * renegotiation.
319          *
320          * s->new_session will be set on renegotiation, but we
321          * probably shouldn't rely that it couldn't be set on
322          * the initial renegotiation too in certain cases (when
323          * there's some other reason to disallow resuming an
324          * earlier session -- the current code won't be doing
325          * anything like that, but this might change).
326          *
327          * A valid sign that there's been a previous handshake
328          * in this connection is if s->s3->tmp.finish_md_len >
329          * 0.  (We are talking about a check that will happen
330          * in the Hello protocol round, well before a new
331          * Finished message could have been computed.)
332          */
333         s->s3->next_proto_neg_seen = 1;
334     }
335
336     return 1;
337 }
338 #endif
339
340 /*
341  * Save the ALPN extension in a ClientHello.
342  * pkt: the contents of the ALPN extension, not including type and length.
343  * al: a pointer to the  alert value to send in the event of a failure.
344  * returns: 1 on success, 0 on error.
345  */
346 int tls_parse_client_alpn(SSL *s, PACKET *pkt, int *al)
347 {
348     PACKET protocol_list, save_protocol_list, protocol;
349
350     if (s->s3->tmp.finish_md_len != 0)
351         return 1;
352
353     if (!PACKET_as_length_prefixed_2(pkt, &protocol_list)
354         || PACKET_remaining(&protocol_list) < 2) {
355         *al = SSL_AD_DECODE_ERROR;
356         return 0;
357     }
358
359     save_protocol_list = protocol_list;
360     do {
361         /* Protocol names can't be empty. */
362         if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol)
363                 || PACKET_remaining(&protocol) == 0) {
364             *al = SSL_AD_DECODE_ERROR;
365             return 0;
366         }
367     } while (PACKET_remaining(&protocol_list) != 0);
368
369     if (!PACKET_memdup(&save_protocol_list,
370                        &s->s3->alpn_proposed, &s->s3->alpn_proposed_len)) {
371         *al = TLS1_AD_INTERNAL_ERROR;
372         return 0;
373     }
374
375     return 1;
376 }
377
378 #ifndef OPENSSL_NO_SRTP
379 int tls_parse_client_use_srtp(SSL *s, PACKET *pkt, int *al)
380 {
381     SRTP_PROTECTION_PROFILE *sprof;
382     STACK_OF(SRTP_PROTECTION_PROFILE) *srvr;
383     unsigned int ct, mki_len, id;
384     int i, srtp_pref;
385     PACKET subpkt;
386
387     /* Ignore this if we have no SRTP profiles */
388     if (SSL_get_srtp_profiles(s) == NULL)
389         return 1;
390
391     /* Pull off the length of the cipher suite list  and check it is even */
392     if (!PACKET_get_net_2(pkt, &ct)
393         || (ct & 1) != 0 || !PACKET_get_sub_packet(pkt, &subpkt, ct)) {
394         SSLerr(SSL_F_TLS_PARSE_CLIENT_USE_SRTP,
395                SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
396         *al = SSL_AD_DECODE_ERROR;
397         return 0;
398     }
399
400     srvr = SSL_get_srtp_profiles(s);
401     s->srtp_profile = NULL;
402     /* Search all profiles for a match initially */
403     srtp_pref = sk_SRTP_PROTECTION_PROFILE_num(srvr);
404
405     while (PACKET_remaining(&subpkt)) {
406         if (!PACKET_get_net_2(&subpkt, &id)) {
407             SSLerr(SSL_F_TLS_PARSE_CLIENT_USE_SRTP,
408                    SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
409             *al = SSL_AD_DECODE_ERROR;
410             return 0;
411         }
412
413         /*
414          * Only look for match in profiles of higher preference than
415          * current match.
416          * If no profiles have been have been configured then this
417          * does nothing.
418          */
419         for (i = 0; i < srtp_pref; i++) {
420             sprof = sk_SRTP_PROTECTION_PROFILE_value(srvr, i);
421             if (sprof->id == id) {
422                 s->srtp_profile = sprof;
423                 srtp_pref = i;
424                 break;
425             }
426         }
427     }
428
429     /*
430      * Now extract the MKI value as a sanity check, but discard it for now
431      */
432     if (!PACKET_get_1(pkt, &mki_len)) {
433         SSLerr(SSL_F_TLS_PARSE_CLIENT_USE_SRTP,
434                SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST);
435         *al = SSL_AD_DECODE_ERROR;
436         return 0;
437     }
438
439     if (!PACKET_forward(pkt, mki_len)
440         || PACKET_remaining(pkt)) {
441         SSLerr(SSL_F_TLS_PARSE_CLIENT_USE_SRTP, SSL_R_BAD_SRTP_MKI_VALUE);
442         *al = SSL_AD_DECODE_ERROR;
443         return 0;
444     }
445
446     return 1;
447 }
448 #endif
449
450 int tls_parse_client_etm(SSL *s, PACKET *pkt, int *al)
451 {
452     if (!(s->options & SSL_OP_NO_ENCRYPT_THEN_MAC))
453         s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
454
455     return 1;
456 }
457
458 /*
459  * Checks a list of |groups| to determine if the |group_id| is in it. If it is
460  * and |checkallow| is 1 then additionally check if the group is allowed to be
461  * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
462  * 1) or 0 otherwise.
463  */
464 static int check_in_list(SSL *s, unsigned int group_id,
465                          const unsigned char *groups, size_t num_groups,
466                          int checkallow)
467 {
468     size_t i;
469
470     if (groups == NULL || num_groups == 0)
471         return 0;
472
473     for (i = 0; i < num_groups; i++, groups += 2) {
474         unsigned int share_id = (groups[0] << 8) | (groups[1]);
475
476         if (group_id == share_id
477                 && (!checkallow || tls_curve_allowed(s, groups,
478                                                      SSL_SECOP_CURVE_CHECK))) {
479             break;
480         }
481     }
482
483     /* If i == num_groups then not in the list */
484     return i < num_groups;
485 }
486
487 /*
488  * Process a key_share extension received in the ClientHello. |pkt| contains
489  * the raw PACKET data for the extension. Returns 1 on success or 0 on failure.
490  * If a failure occurs then |*al| is set to an appropriate alert value.
491  */
492 int tls_parse_client_key_share(SSL *s, PACKET *pkt, int *al)
493 {
494     unsigned int group_id;
495     PACKET key_share_list, encoded_pt;
496     const unsigned char *clntcurves, *srvrcurves;
497     size_t clnt_num_curves, srvr_num_curves;
498     int group_nid, found = 0;
499     unsigned int curve_flags;
500
501     if (s->hit)
502         return 1;
503
504     /* Sanity check */
505     if (s->s3->peer_tmp != NULL) {
506         *al = SSL_AD_INTERNAL_ERROR;
507         SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, ERR_R_INTERNAL_ERROR);
508         return 0;
509     }
510
511     if (!PACKET_as_length_prefixed_2(pkt, &key_share_list)) {
512         *al = SSL_AD_HANDSHAKE_FAILURE;
513         SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, SSL_R_LENGTH_MISMATCH);
514         return 0;
515     }
516
517     /* Get our list of supported curves */
518     if (!tls1_get_curvelist(s, 0, &srvrcurves, &srvr_num_curves)) {
519         *al = SSL_AD_INTERNAL_ERROR;
520         SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, ERR_R_INTERNAL_ERROR);
521         return 0;
522     }
523
524     /* Get the clients list of supported curves */
525     if (!tls1_get_curvelist(s, 1, &clntcurves, &clnt_num_curves)) {
526         *al = SSL_AD_INTERNAL_ERROR;
527         SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, ERR_R_INTERNAL_ERROR);
528         return 0;
529     }
530
531     while (PACKET_remaining(&key_share_list) > 0) {
532         if (!PACKET_get_net_2(&key_share_list, &group_id)
533                 || !PACKET_get_length_prefixed_2(&key_share_list, &encoded_pt)
534                 || PACKET_remaining(&encoded_pt) == 0) {
535             *al = SSL_AD_HANDSHAKE_FAILURE;
536             SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE,
537                    SSL_R_LENGTH_MISMATCH);
538             return 0;
539         }
540
541         /*
542          * If we already found a suitable key_share we loop through the
543          * rest to verify the structure, but don't process them.
544          */
545         if (found)
546             continue;
547
548         /* Check if this share is in supported_groups sent from client */
549         if (!check_in_list(s, group_id, clntcurves, clnt_num_curves, 0)) {
550             *al = SSL_AD_HANDSHAKE_FAILURE;
551             SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, SSL_R_BAD_KEY_SHARE);
552             return 0;
553         }
554
555         /* Check if this share is for a group we can use */
556         if (!check_in_list(s, group_id, srvrcurves, srvr_num_curves, 1)) {
557             /* Share not suitable */
558             continue;
559         }
560
561         group_nid = tls1_ec_curve_id2nid(group_id, &curve_flags);
562
563         if (group_nid == 0) {
564             *al = SSL_AD_INTERNAL_ERROR;
565             SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE,
566                    SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
567             return 0;
568         }
569
570         if ((curve_flags & TLS_CURVE_TYPE) == TLS_CURVE_CUSTOM) {
571             /* Can happen for some curves, e.g. X25519 */
572             EVP_PKEY *key = EVP_PKEY_new();
573
574             if (key == NULL || !EVP_PKEY_set_type(key, group_nid)) {
575                 *al = SSL_AD_INTERNAL_ERROR;
576                 SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, ERR_R_EVP_LIB);
577                 EVP_PKEY_free(key);
578                 return 0;
579             }
580             s->s3->peer_tmp = key;
581         } else {
582             /* Set up EVP_PKEY with named curve as parameters */
583             EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL);
584             if (pctx == NULL
585                     || EVP_PKEY_paramgen_init(pctx) <= 0
586                     || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx,
587                                                               group_nid) <= 0
588                     || EVP_PKEY_paramgen(pctx, &s->s3->peer_tmp) <= 0) {
589                 *al = SSL_AD_INTERNAL_ERROR;
590                 SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, ERR_R_EVP_LIB);
591                 EVP_PKEY_CTX_free(pctx);
592                 return 0;
593             }
594             EVP_PKEY_CTX_free(pctx);
595             pctx = NULL;
596         }
597         s->s3->group_id = group_id;
598
599         if (!EVP_PKEY_set1_tls_encodedpoint(s->s3->peer_tmp,
600                 PACKET_data(&encoded_pt),
601                 PACKET_remaining(&encoded_pt))) {
602             *al = SSL_AD_DECODE_ERROR;
603             SSLerr(SSL_F_TLS_PARSE_CLIENT_KEY_SHARE, SSL_R_BAD_ECPOINT);
604             return 0;
605         }
606
607         found = 1;
608     }
609
610     return 1;
611 }
612
613 #ifndef OPENSSL_NO_EC
614 int tls_parse_client_supported_groups(SSL *s, PACKET *pkt, int *al)
615 {
616     PACKET supported_groups_list;
617
618     /* Each group is 2 bytes and we must have at least 1. */
619     if (!PACKET_as_length_prefixed_2(pkt, &supported_groups_list)
620             || PACKET_remaining(&supported_groups_list) == 0
621             || (PACKET_remaining(&supported_groups_list) % 2) != 0) {
622         *al = SSL_AD_DECODE_ERROR;
623         return 0;
624     }
625
626     if (!s->hit
627             && !PACKET_memdup(&supported_groups_list,
628                               &s->session->tlsext_supportedgroupslist,
629                               &s->session->tlsext_supportedgroupslist_length)) {
630         *al = SSL_AD_DECODE_ERROR;
631         return 0;
632     }
633
634     return 1;
635 }
636 #endif
637
638 int tls_parse_client_ems(SSL *s, PACKET *pkt, int *al)
639 {
640     /* The extension must always be empty */
641     if (PACKET_remaining(pkt) != 0) {
642         *al = SSL_AD_DECODE_ERROR;
643         return 0;
644     }
645
646     s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS;
647
648     return 1;
649 }
650
651 #ifndef OPENSSL_NO_EC
652 /*-
653  * ssl_check_for_safari attempts to fingerprint Safari using OS X
654  * SecureTransport using the TLS extension block in |hello|.
655  * Safari, since 10.6, sends exactly these extensions, in this order:
656  *   SNI,
657  *   elliptic_curves
658  *   ec_point_formats
659  *
660  * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
661  * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
662  * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
663  * 10.8..10.8.3 (which don't work).
664  */
665 static void ssl_check_for_safari(SSL *s, const CLIENTHELLO_MSG *hello)
666 {
667     unsigned int type;
668     PACKET sni, tmppkt;
669     size_t ext_len;
670
671     static const unsigned char kSafariExtensionsBlock[] = {
672         0x00, 0x0a,             /* elliptic_curves extension */
673         0x00, 0x08,             /* 8 bytes */
674         0x00, 0x06,             /* 6 bytes of curve ids */
675         0x00, 0x17,             /* P-256 */
676         0x00, 0x18,             /* P-384 */
677         0x00, 0x19,             /* P-521 */
678
679         0x00, 0x0b,             /* ec_point_formats */
680         0x00, 0x02,             /* 2 bytes */
681         0x01,                   /* 1 point format */
682         0x00,                   /* uncompressed */
683         /* The following is only present in TLS 1.2 */
684         0x00, 0x0d,             /* signature_algorithms */
685         0x00, 0x0c,             /* 12 bytes */
686         0x00, 0x0a,             /* 10 bytes */
687         0x05, 0x01,             /* SHA-384/RSA */
688         0x04, 0x01,             /* SHA-256/RSA */
689         0x02, 0x01,             /* SHA-1/RSA */
690         0x04, 0x03,             /* SHA-256/ECDSA */
691         0x02, 0x03,             /* SHA-1/ECDSA */
692     };
693
694     /* Length of the common prefix (first two extensions). */
695     static const size_t kSafariCommonExtensionsLength = 18;
696
697     tmppkt = hello->extensions;
698
699     if (!PACKET_forward(&tmppkt, 2)
700         || !PACKET_get_net_2(&tmppkt, &type)
701         || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
702         return;
703     }
704
705     if (type != TLSEXT_TYPE_server_name)
706         return;
707
708     ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ?
709         sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength;
710
711     s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
712                                              ext_len);
713 }
714 #endif                          /* !OPENSSL_NO_EC */
715
716 /*
717  * Process all remaining ClientHello extensions that we collected earlier and
718  * haven't already processed.
719  *
720  * Behaviour upon resumption is extension-specific. If the extension has no
721  * effect during resumption, it is parsed (to verify its format) but otherwise
722  * ignored. Returns 1 on success and 0 on failure. Upon failure, sets |al| to
723  * the appropriate alert.
724  */
725 int tls_scan_clienthello_tlsext(SSL *s, CLIENTHELLO_MSG *hello, int *al)
726 {
727     /* Reset various flags that might get set by extensions during parsing */
728     s->servername_done = 0;
729     s->tlsext_status_type = -1;
730 #ifndef OPENSSL_NO_NEXTPROTONEG
731     s->s3->next_proto_neg_seen = 0;
732 #endif
733
734     OPENSSL_free(s->s3->alpn_selected);
735     s->s3->alpn_selected = NULL;
736     s->s3->alpn_selected_len = 0;
737     OPENSSL_free(s->s3->alpn_proposed);
738     s->s3->alpn_proposed = NULL;
739     s->s3->alpn_proposed_len = 0;
740
741 #ifndef OPENSSL_NO_EC
742     if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
743         ssl_check_for_safari(s, hello);
744 #endif                          /* !OPENSSL_NO_EC */
745
746     /* Clear any signature algorithms extension received */
747     OPENSSL_free(s->s3->tmp.peer_sigalgs);
748     s->s3->tmp.peer_sigalgs = NULL;
749     s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
750
751 #ifndef OPENSSL_NO_SRP
752     OPENSSL_free(s->srp_ctx.login);
753     s->srp_ctx.login = NULL;
754 #endif
755
756     s->srtp_profile = NULL;
757
758     /*
759      * We process the supported_groups extension first so that is done before
760      * we get to key_share which needs to use the information in it.
761      */
762     if (!tls_parse_extension(s, TLSEXT_TYPE_supported_groups, EXT_CLIENT_HELLO,
763                              hello->pre_proc_exts, hello->num_extensions, al)) {
764         return 0;
765     }
766
767     /* Need RI if renegotiating */
768     if (s->renegotiate
769             && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
770             && tls_get_extension_by_type(hello->pre_proc_exts,
771                                          hello->num_extensions,
772                                          TLSEXT_TYPE_renegotiate) == NULL) {
773         *al = SSL_AD_HANDSHAKE_FAILURE;
774         SSLerr(SSL_F_TLS_SCAN_CLIENTHELLO_TLSEXT,
775                SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
776         return 0;
777     }
778
779     return tls_parse_all_extensions(s, EXT_CLIENT_HELLO, hello->pre_proc_exts,
780                                     hello->num_extensions, al);
781 }
782
783 /*
784  * Process the ALPN extension in a ClientHello.
785  * al: a pointer to the alert value to send in the event of a failure.
786  * returns 1 on success, 0 on error.
787  */
788 static int tls1_alpn_handle_client_hello_late(SSL *s, int *al)
789 {
790     const unsigned char *selected = NULL;
791     unsigned char selected_len = 0;
792
793     if (s->ctx->alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) {
794         int r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
795                                        s->s3->alpn_proposed,
796                                        (unsigned int)s->s3->alpn_proposed_len,
797                                        s->ctx->alpn_select_cb_arg);
798
799         if (r == SSL_TLSEXT_ERR_OK) {
800             OPENSSL_free(s->s3->alpn_selected);
801             s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len);
802             if (s->s3->alpn_selected == NULL) {
803                 *al = SSL_AD_INTERNAL_ERROR;
804                 return 0;
805             }
806             s->s3->alpn_selected_len = selected_len;
807 #ifndef OPENSSL_NO_NEXTPROTONEG
808             /* ALPN takes precedence over NPN. */
809             s->s3->next_proto_neg_seen = 0;
810 #endif
811         } else {
812             *al = SSL_AD_NO_APPLICATION_PROTOCOL;
813             return 0;
814         }
815     }
816
817     return 1;
818 }
819
820 /*
821  * Upon success, returns 1.
822  * Upon failure, returns 0 and sets |al| to the appropriate fatal alert.
823  */
824 int ssl_check_clienthello_tlsext_late(SSL *s, int *al)
825 {
826     s->tlsext_status_expected = 0;
827
828     /*
829      * If status request then ask callback what to do. Note: this must be
830      * called after servername callbacks in case the certificate has changed,
831      * and must be called after the cipher has been chosen because this may
832      * influence which certificate is sent
833      */
834     if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
835         int ret;
836         CERT_PKEY *certpkey;
837         certpkey = ssl_get_server_send_pkey(s);
838         /* If no certificate can't return certificate status */
839         if (certpkey != NULL) {
840             /*
841              * Set current certificate to one we will use so SSL_get_certificate
842              * et al can pick it up.
843              */
844             s->cert->key = certpkey;
845             ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
846             switch (ret) {
847                 /* We don't want to send a status request response */
848             case SSL_TLSEXT_ERR_NOACK:
849                 s->tlsext_status_expected = 0;
850                 break;
851                 /* status request response should be sent */
852             case SSL_TLSEXT_ERR_OK:
853                 if (s->tlsext_ocsp_resp)
854                     s->tlsext_status_expected = 1;
855                 break;
856                 /* something bad happened */
857             case SSL_TLSEXT_ERR_ALERT_FATAL:
858             default:
859                 *al = SSL_AD_INTERNAL_ERROR;
860                 return 0;
861             }
862         }
863     }
864
865     if (!tls1_alpn_handle_client_hello_late(s, al)) {
866         return 0;
867     }
868
869     return 1;
870 }
871
872 /* Add the server's renegotiation binding */
873 int tls_construct_server_renegotiate(SSL *s, WPACKET *pkt, int *al)
874 {
875     if (!s->s3->send_connection_binding)
876         return 1;
877
878     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_renegotiate)
879             || !WPACKET_start_sub_packet_u16(pkt)
880             || !WPACKET_start_sub_packet_u8(pkt)
881             || !WPACKET_memcpy(pkt, s->s3->previous_client_finished,
882                                s->s3->previous_client_finished_len)
883             || !WPACKET_memcpy(pkt, s->s3->previous_server_finished,
884                                s->s3->previous_server_finished_len)
885             || !WPACKET_close(pkt)
886             || !WPACKET_close(pkt)) {
887         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_RENEGOTIATE, ERR_R_INTERNAL_ERROR);
888         return 0;
889     }
890
891     return 1;
892 }
893
894 int tls_construct_server_server_name(SSL *s, WPACKET *pkt, int *al)
895 {
896     if (s->hit || s->servername_done != 1
897             || s->session->tlsext_hostname == NULL)
898         return 1;
899
900     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_server_name)
901             || !WPACKET_put_bytes_u16(pkt, 0)) {
902         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_SERVER_NAME, ERR_R_INTERNAL_ERROR);
903         return 0;
904     }
905
906     return 1;
907 }
908
909 #ifndef OPENSSL_NO_EC
910 int tls_construct_server_ec_pt_formats(SSL *s, WPACKET *pkt, int *al)
911 {
912     unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
913     unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
914     int using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA);
915     using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
916     const unsigned char *plist;
917     size_t plistlen;
918
919     if (!using_ecc)
920         return 1;
921
922     tls1_get_formatlist(s, &plist, &plistlen);
923
924     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_ec_point_formats)
925             || !WPACKET_start_sub_packet_u16(pkt)
926             || !WPACKET_sub_memcpy_u8(pkt, plist, plistlen)
927             || !WPACKET_close(pkt)) {
928         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_EC_PT_FORMATS, ERR_R_INTERNAL_ERROR);
929         return 0;
930     }
931
932     return 1;
933 }
934 #endif
935
936 int tls_construct_server_session_ticket(SSL *s, WPACKET *pkt, int *al)
937 {
938     if (!s->tlsext_ticket_expected || !tls_use_ticket(s)) {
939         s->tlsext_ticket_expected = 0;
940         return 1;
941     }
942
943     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_session_ticket)
944             || !WPACKET_put_bytes_u16(pkt, 0)) {
945         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
946         return 0;
947     }
948
949     return 1;
950 }
951
952 int tls_construct_server_status_request(SSL *s, WPACKET *pkt, int *al)
953 {
954     if (!s->tlsext_status_expected)
955         return 1;
956
957     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_status_request)
958             || !WPACKET_put_bytes_u16(pkt, 0)) {
959         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_STATUS_REQUEST, ERR_R_INTERNAL_ERROR);
960         return 0;
961     }
962
963     return 1;
964 }
965
966
967 #ifndef OPENSSL_NO_NEXTPROTONEG
968 int tls_construct_server_next_proto_neg(SSL *s, WPACKET *pkt, int *al)
969 {
970     const unsigned char *npa;
971     unsigned int npalen;
972     int ret;
973     int next_proto_neg_seen = s->s3->next_proto_neg_seen;
974
975     s->s3->next_proto_neg_seen = 0;
976     if (!next_proto_neg_seen || s->ctx->next_protos_advertised_cb == NULL)
977         return 1;
978
979     ret = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
980                                       s->ctx->next_protos_advertised_cb_arg);
981     if (ret == SSL_TLSEXT_ERR_OK) {
982         if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_next_proto_neg)
983                 || !WPACKET_sub_memcpy_u16(pkt, npa, npalen)) {
984             SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_NEXT_PROTO_NEG,
985                    ERR_R_INTERNAL_ERROR);
986             return 0;
987         }
988         s->s3->next_proto_neg_seen = 1;
989     }
990
991     return 1;
992 }
993 #endif
994
995 int tls_construct_server_alpn(SSL *s, WPACKET *pkt, int *al)
996 {
997     if (s->s3->alpn_selected == NULL)
998         return 1;
999
1000     if (!WPACKET_put_bytes_u16(pkt,
1001                 TLSEXT_TYPE_application_layer_protocol_negotiation)
1002             || !WPACKET_start_sub_packet_u16(pkt)
1003             || !WPACKET_start_sub_packet_u16(pkt)
1004             || !WPACKET_sub_memcpy_u8(pkt, s->s3->alpn_selected,
1005                                       s->s3->alpn_selected_len)
1006             || !WPACKET_close(pkt)
1007             || !WPACKET_close(pkt)) {
1008         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_ALPN, ERR_R_INTERNAL_ERROR);
1009         return 0;
1010     }
1011
1012     return 1;
1013 }
1014
1015 #ifndef OPENSSL_NO_SRTP
1016 int tls_construct_server_use_srtp(SSL *s, WPACKET *pkt, int *al)
1017 {
1018     if (s->srtp_profile == NULL)
1019         return 1;
1020         
1021     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_use_srtp)
1022             || !WPACKET_start_sub_packet_u16(pkt)
1023             || !WPACKET_put_bytes_u16(pkt, 2)
1024             || !WPACKET_put_bytes_u16(pkt, s->srtp_profile->id)
1025             || !WPACKET_put_bytes_u8(pkt, 0)
1026             || !WPACKET_close(pkt)) {
1027         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_USE_SRTP, ERR_R_INTERNAL_ERROR);
1028         return 0;
1029     }
1030
1031     return 1;
1032 }
1033 #endif
1034
1035 int tls_construct_server_etm(SSL *s, WPACKET *pkt, int *al)
1036 {
1037     if ((s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC) == 0)
1038         return 1;
1039
1040     /*
1041      * Don't use encrypt_then_mac if AEAD or RC4 might want to disable
1042      * for other cases too.
1043      */
1044     if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
1045         || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4
1046         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT
1047         || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12) {
1048         s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
1049         return 1;
1050     }
1051
1052     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_encrypt_then_mac)
1053             || !WPACKET_put_bytes_u16(pkt, 0)) {
1054         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_ETM, ERR_R_INTERNAL_ERROR);
1055         return 0;
1056     }
1057
1058     return 1;
1059 }
1060
1061 int tls_construct_server_ems(SSL *s, WPACKET *pkt, int *al)
1062 {
1063     if ((s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) == 0)
1064         return 1;
1065
1066     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_extended_master_secret)
1067             || !WPACKET_put_bytes_u16(pkt, 0)) {
1068         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_EMS, ERR_R_INTERNAL_ERROR);
1069         return 0;
1070     }
1071
1072     return 1;
1073 }
1074
1075 int tls_construct_server_key_share(SSL *s, WPACKET *pkt, int *al)
1076 {
1077     unsigned char *encodedPoint;
1078     size_t encoded_pt_len = 0;
1079     EVP_PKEY *ckey = s->s3->peer_tmp, *skey = NULL;
1080
1081     if (s->hit)
1082         return 1;
1083
1084     if (ckey == NULL) {
1085         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1086         return 0;
1087     }
1088
1089     if (!WPACKET_put_bytes_u16(pkt, TLSEXT_TYPE_key_share)
1090             || !WPACKET_start_sub_packet_u16(pkt)
1091             || !WPACKET_put_bytes_u16(pkt, s->s3->group_id)) {
1092         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1093         return 0;
1094     }
1095
1096     skey = ssl_generate_pkey(ckey);
1097     if (skey == NULL) {
1098         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_SHARE, ERR_R_MALLOC_FAILURE);
1099         return 0;
1100     }
1101
1102     /* Generate encoding of server key */
1103     encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(skey, &encodedPoint);
1104     if (encoded_pt_len == 0) {
1105         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_SHARE, ERR_R_EC_LIB);
1106         EVP_PKEY_free(skey);
1107         return 0;
1108     }
1109
1110     if (!WPACKET_sub_memcpy_u16(pkt, encodedPoint, encoded_pt_len)
1111             || !WPACKET_close(pkt)) {
1112         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1113         EVP_PKEY_free(skey);
1114         OPENSSL_free(encodedPoint);
1115         return 0;
1116     }
1117     OPENSSL_free(encodedPoint);
1118
1119     /* This causes the crypto state to be updated based on the derived keys */
1120     s->s3->tmp.pkey = skey;
1121     if (ssl_derive(s, skey, ckey, 1) == 0) {
1122         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_KEY_SHARE, ERR_R_INTERNAL_ERROR);
1123         return 0;
1124     }
1125
1126     return 1;
1127 }
1128
1129 int tls_construct_server_cryptopro_bug(SSL *s, WPACKET *pkt, int *al)
1130 {
1131     const unsigned char cryptopro_ext[36] = {
1132         0xfd, 0xe8,         /* 65000 */
1133         0x00, 0x20,         /* 32 bytes length */
1134         0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1135         0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1136         0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1137         0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1138     };
1139
1140     if (((s->s3->tmp.new_cipher->id & 0xFFFF) != 0x80
1141          && (s->s3->tmp.new_cipher->id & 0xFFFF) != 0x81)
1142             || (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG) == 0)
1143         return 1;
1144
1145     if (!WPACKET_memcpy(pkt, cryptopro_ext, sizeof(cryptopro_ext))) {
1146         SSLerr(SSL_F_TLS_CONSTRUCT_SERVER_CRYPTOPRO_BUG, ERR_R_INTERNAL_ERROR);
1147         return 0;
1148     }
1149
1150     return 1;
1151 }