2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
58 /* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
87 * 6. Redistributions of any form whatsoever must retain the following
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
114 #include <openssl/bio.h>
115 #include <openssl/bn.h>
116 #include <openssl/objects.h>
117 #include <openssl/evp.h>
118 #include <openssl/hmac.h>
119 #include <openssl/ocsp.h>
120 #include <openssl/rand.h>
121 #include "ssl_locl.h"
123 const char tls1_version_str[]="TLSv1" OPENSSL_VERSION_PTEXT;
125 #ifndef OPENSSL_NO_TLSEXT
126 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
127 const unsigned char *sess_id, int sesslen,
128 SSL_SESSION **psess);
129 static int ssl_check_clienthello_tlsext_early(SSL *s);
130 int ssl_check_serverhello_tlsext(SSL *s);
133 SSL3_ENC_METHOD TLSv1_enc_data={
136 tls1_setup_key_block,
137 tls1_generate_master_secret,
138 tls1_change_cipher_state,
139 tls1_final_finish_mac,
140 TLS1_FINISH_MAC_LENGTH,
141 tls1_cert_verify_mac,
142 TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
143 TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
145 tls1_export_keying_material,
147 SSL3_HM_HEADER_LENGTH,
148 ssl3_set_handshake_header,
152 SSL3_ENC_METHOD TLSv1_1_enc_data={
155 tls1_setup_key_block,
156 tls1_generate_master_secret,
157 tls1_change_cipher_state,
158 tls1_final_finish_mac,
159 TLS1_FINISH_MAC_LENGTH,
160 tls1_cert_verify_mac,
161 TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
162 TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
164 tls1_export_keying_material,
165 SSL_ENC_FLAG_EXPLICIT_IV,
166 SSL3_HM_HEADER_LENGTH,
167 ssl3_set_handshake_header,
171 SSL3_ENC_METHOD TLSv1_2_enc_data={
174 tls1_setup_key_block,
175 tls1_generate_master_secret,
176 tls1_change_cipher_state,
177 tls1_final_finish_mac,
178 TLS1_FINISH_MAC_LENGTH,
179 tls1_cert_verify_mac,
180 TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
181 TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
183 tls1_export_keying_material,
184 SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS|SSL_ENC_FLAG_SHA256_PRF
185 |SSL_ENC_FLAG_TLS1_2_CIPHERS,
186 SSL3_HM_HEADER_LENGTH,
187 ssl3_set_handshake_header,
191 long tls1_default_timeout(void)
193 /* 2 hours, the 24 hours mentioned in the TLSv1 spec
194 * is way too long for http, the cache would over fill */
200 if (!ssl3_new(s)) return(0);
201 s->method->ssl_clear(s);
205 void tls1_free(SSL *s)
207 #ifndef OPENSSL_NO_TLSEXT
208 if (s->tlsext_session_ticket)
210 OPENSSL_free(s->tlsext_session_ticket);
212 #endif /* OPENSSL_NO_TLSEXT */
216 void tls1_clear(SSL *s)
219 s->version = s->method->version;
222 #ifndef OPENSSL_NO_EC
224 static int nid_list[] =
226 NID_sect163k1, /* sect163k1 (1) */
227 NID_sect163r1, /* sect163r1 (2) */
228 NID_sect163r2, /* sect163r2 (3) */
229 NID_sect193r1, /* sect193r1 (4) */
230 NID_sect193r2, /* sect193r2 (5) */
231 NID_sect233k1, /* sect233k1 (6) */
232 NID_sect233r1, /* sect233r1 (7) */
233 NID_sect239k1, /* sect239k1 (8) */
234 NID_sect283k1, /* sect283k1 (9) */
235 NID_sect283r1, /* sect283r1 (10) */
236 NID_sect409k1, /* sect409k1 (11) */
237 NID_sect409r1, /* sect409r1 (12) */
238 NID_sect571k1, /* sect571k1 (13) */
239 NID_sect571r1, /* sect571r1 (14) */
240 NID_secp160k1, /* secp160k1 (15) */
241 NID_secp160r1, /* secp160r1 (16) */
242 NID_secp160r2, /* secp160r2 (17) */
243 NID_secp192k1, /* secp192k1 (18) */
244 NID_X9_62_prime192v1, /* secp192r1 (19) */
245 NID_secp224k1, /* secp224k1 (20) */
246 NID_secp224r1, /* secp224r1 (21) */
247 NID_secp256k1, /* secp256k1 (22) */
248 NID_X9_62_prime256v1, /* secp256r1 (23) */
249 NID_secp384r1, /* secp384r1 (24) */
250 NID_secp521r1, /* secp521r1 (25) */
251 NID_brainpoolP256r1, /* brainpoolP256r1 (26) */
252 NID_brainpoolP384r1, /* brainpoolP384r1 (27) */
253 NID_brainpoolP512r1 /* brainpool512r1 (28) */
257 static const unsigned char ecformats_default[] =
259 TLSEXT_ECPOINTFORMAT_uncompressed,
260 TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
261 TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
264 static const unsigned char eccurves_default[] =
266 0,14, /* sect571r1 (14) */
267 0,13, /* sect571k1 (13) */
268 0,25, /* secp521r1 (25) */
269 0,28, /* brainpool512r1 (28) */
270 0,11, /* sect409k1 (11) */
271 0,12, /* sect409r1 (12) */
272 0,27, /* brainpoolP384r1 (27) */
273 0,24, /* secp384r1 (24) */
274 0,9, /* sect283k1 (9) */
275 0,10, /* sect283r1 (10) */
276 0,26, /* brainpoolP256r1 (26) */
277 0,22, /* secp256k1 (22) */
278 0,23, /* secp256r1 (23) */
279 0,8, /* sect239k1 (8) */
280 0,6, /* sect233k1 (6) */
281 0,7, /* sect233r1 (7) */
282 0,20, /* secp224k1 (20) */
283 0,21, /* secp224r1 (21) */
284 0,4, /* sect193r1 (4) */
285 0,5, /* sect193r2 (5) */
286 0,18, /* secp192k1 (18) */
287 0,19, /* secp192r1 (19) */
288 0,1, /* sect163k1 (1) */
289 0,2, /* sect163r1 (2) */
290 0,3, /* sect163r2 (3) */
291 0,15, /* secp160k1 (15) */
292 0,16, /* secp160r1 (16) */
293 0,17, /* secp160r2 (17) */
296 static const unsigned char suiteb_curves[] =
298 0, TLSEXT_curve_P_256,
299 0, TLSEXT_curve_P_384
302 int tls1_ec_curve_id2nid(int curve_id)
304 /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
305 if ((curve_id < 1) || ((unsigned int)curve_id >
306 sizeof(nid_list)/sizeof(nid_list[0])))
308 return nid_list[curve_id-1];
311 int tls1_ec_nid2curve_id(int nid)
313 /* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
316 case NID_sect163k1: /* sect163k1 (1) */
318 case NID_sect163r1: /* sect163r1 (2) */
320 case NID_sect163r2: /* sect163r2 (3) */
322 case NID_sect193r1: /* sect193r1 (4) */
324 case NID_sect193r2: /* sect193r2 (5) */
326 case NID_sect233k1: /* sect233k1 (6) */
328 case NID_sect233r1: /* sect233r1 (7) */
330 case NID_sect239k1: /* sect239k1 (8) */
332 case NID_sect283k1: /* sect283k1 (9) */
334 case NID_sect283r1: /* sect283r1 (10) */
336 case NID_sect409k1: /* sect409k1 (11) */
338 case NID_sect409r1: /* sect409r1 (12) */
340 case NID_sect571k1: /* sect571k1 (13) */
342 case NID_sect571r1: /* sect571r1 (14) */
344 case NID_secp160k1: /* secp160k1 (15) */
346 case NID_secp160r1: /* secp160r1 (16) */
348 case NID_secp160r2: /* secp160r2 (17) */
350 case NID_secp192k1: /* secp192k1 (18) */
352 case NID_X9_62_prime192v1: /* secp192r1 (19) */
354 case NID_secp224k1: /* secp224k1 (20) */
356 case NID_secp224r1: /* secp224r1 (21) */
358 case NID_secp256k1: /* secp256k1 (22) */
360 case NID_X9_62_prime256v1: /* secp256r1 (23) */
362 case NID_secp384r1: /* secp384r1 (24) */
364 case NID_secp521r1: /* secp521r1 (25) */
366 case NID_brainpoolP256r1: /* brainpoolP256r1 (26) */
368 case NID_brainpoolP384r1: /* brainpoolP384r1 (27) */
370 case NID_brainpoolP512r1: /* brainpool512r1 (28) */
376 /* Get curves list, if "sess" is set return client curves otherwise
379 static void tls1_get_curvelist(SSL *s, int sess,
380 const unsigned char **pcurves,
385 *pcurves = s->session->tlsext_ellipticcurvelist;
386 *pcurveslen = s->session->tlsext_ellipticcurvelist_length;
389 /* For Suite B mode only include P-256, P-384 */
390 switch (tls1_suiteb(s))
392 case SSL_CERT_FLAG_SUITEB_128_LOS:
393 *pcurves = suiteb_curves;
394 *pcurveslen = sizeof(suiteb_curves);
397 case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
398 *pcurves = suiteb_curves;
402 case SSL_CERT_FLAG_SUITEB_192_LOS:
403 *pcurves = suiteb_curves + 2;
407 *pcurves = s->tlsext_ellipticcurvelist;
408 *pcurveslen = s->tlsext_ellipticcurvelist_length;
412 *pcurves = eccurves_default;
413 *pcurveslen = sizeof(eccurves_default);
416 /* Check a curve is one of our preferences */
417 int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
419 const unsigned char *curves;
421 unsigned int suiteb_flags = tls1_suiteb(s);
422 if (len != 3 || p[0] != NAMED_CURVE_TYPE)
424 /* Check curve matches Suite B preferences */
427 unsigned long cid = s->s3->tmp.new_cipher->id;
430 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
432 if (p[2] != TLSEXT_curve_P_256)
435 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
437 if (p[2] != TLSEXT_curve_P_384)
440 else /* Should never happen */
443 tls1_get_curvelist(s, 0, &curves, &curveslen);
444 for (i = 0; i < curveslen; i += 2, curves += 2)
446 if (p[1] == curves[0] && p[2] == curves[1])
452 /* Return nth shared curve. If nmatch == -1 return number of
453 * matches. For nmatch == -2 return the NID of the curve to use for
457 int tls1_shared_curve(SSL *s, int nmatch)
459 const unsigned char *pref, *supp;
460 size_t preflen, supplen, i, j;
462 /* Can't do anything on client side */
469 /* For Suite B ciphersuite determines curve: we
470 * already know these are acceptable due to previous
473 unsigned long cid = s->s3->tmp.new_cipher->id;
474 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
475 return NID_X9_62_prime256v1; /* P-256 */
476 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
477 return NID_secp384r1; /* P-384 */
478 /* Should never happen */
481 /* If not Suite B just return first preference shared curve */
484 tls1_get_curvelist(s, !!(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
486 tls1_get_curvelist(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
491 for (i = 0; i < preflen; i++, pref+=2)
493 const unsigned char *tsupp = supp;
494 for (j = 0; j < supplen; j++, tsupp+=2)
496 if (pref[0] == tsupp[0] && pref[1] == tsupp[1])
500 int id = (pref[0] << 8) | pref[1];
501 return tls1_ec_curve_id2nid(id);
512 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
513 int *curves, size_t ncurves)
515 unsigned char *clist, *p;
517 /* Bitmap of curves included to detect duplicates: only works
518 * while curve ids < 32
520 unsigned long dup_list = 0;
521 clist = OPENSSL_malloc(ncurves * 2);
524 for (i = 0, p = clist; i < ncurves; i++)
526 unsigned long idmask;
528 id = tls1_ec_nid2curve_id(curves[i]);
530 if (!id || (dup_list & idmask))
541 *pextlen = ncurves * 2;
545 #define MAX_CURVELIST 28
550 int nid_arr[MAX_CURVELIST];
553 static int nid_cb(const char *elem, int len, void *arg)
555 nid_cb_st *narg = arg;
559 if (narg->nidcnt == MAX_CURVELIST)
561 if (len > (int)(sizeof(etmp) - 1))
563 memcpy(etmp, elem, len);
565 nid = EC_curve_nist2nid(etmp);
566 if (nid == NID_undef)
567 nid = OBJ_sn2nid(etmp);
568 if (nid == NID_undef)
569 nid = OBJ_ln2nid(etmp);
570 if (nid == NID_undef)
572 for (i = 0; i < narg->nidcnt; i++)
573 if (narg->nid_arr[i] == nid)
575 narg->nid_arr[narg->nidcnt++] = nid;
578 /* Set curves based on a colon separate list */
579 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen,
584 if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
588 return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
590 /* For an EC key set TLS id and required compression based on parameters */
591 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
596 const EC_METHOD *meth;
599 /* Determine if it is a prime field */
600 grp = EC_KEY_get0_group(ec);
603 meth = EC_GROUP_method_of(grp);
606 if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
610 /* Determine curve ID */
611 id = EC_GROUP_get_curve_name(grp);
612 id = tls1_ec_nid2curve_id(id);
613 /* If we have an ID set it, otherwise set arbitrary explicit curve */
617 curve_id[1] = (unsigned char)id;
629 if (EC_KEY_get0_public_key(ec) == NULL)
631 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
634 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
636 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
639 *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
643 /* Check an EC key is compatible with extensions */
644 static int tls1_check_ec_key(SSL *s,
645 unsigned char *curve_id, unsigned char *comp_id)
647 const unsigned char *p;
650 /* If point formats extension present check it, otherwise everything
651 * is supported (see RFC4492).
653 if (comp_id && s->session->tlsext_ecpointformatlist)
655 p = s->session->tlsext_ecpointformatlist;
656 plen = s->session->tlsext_ecpointformatlist_length;
657 for (i = 0; i < plen; i++, p++)
667 /* Check curve is consistent with client and server preferences */
668 for (j = 0; j <= 1; j++)
670 tls1_get_curvelist(s, j, &p, &plen);
671 for (i = 0; i < plen; i+=2, p+=2)
673 if (p[0] == curve_id[0] && p[1] == curve_id[1])
678 /* For clients can only check sent curve list */
685 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
688 /* If we have a custom point format list use it otherwise
690 if (s->tlsext_ecpointformatlist)
692 *pformats = s->tlsext_ecpointformatlist;
693 *pformatslen = s->tlsext_ecpointformatlist_length;
697 *pformats = ecformats_default;
698 /* For Suite B we don't support char2 fields */
700 *pformatslen = sizeof(ecformats_default) - 1;
702 *pformatslen = sizeof(ecformats_default);
706 /* Check cert parameters compatible with extensions: currently just checks
707 * EC certificates have compatible curves and compression.
709 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
711 unsigned char comp_id, curve_id[2];
714 pkey = X509_get_pubkey(x);
717 /* If not EC nothing to do */
718 if (pkey->type != EVP_PKEY_EC)
723 rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
727 /* Can't check curve_id for client certs as we don't have a
728 * supported curves extension.
730 rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
733 /* Special case for suite B. We *MUST* sign using SHA256+P-256 or
734 * SHA384+P-384, adjust digest if necessary.
736 if (set_ee_md && tls1_suiteb(s))
743 /* Check to see we have necessary signing algorithm */
744 if (curve_id[1] == TLSEXT_curve_P_256)
745 check_md = NID_ecdsa_with_SHA256;
746 else if (curve_id[1] == TLSEXT_curve_P_384)
747 check_md = NID_ecdsa_with_SHA384;
749 return 0; /* Should never happen */
750 for (i = 0; i < c->shared_sigalgslen; i++)
751 if (check_md == c->shared_sigalgs[i].signandhash_nid)
753 if (i == c->shared_sigalgslen)
757 if (check_md == NID_ecdsa_with_SHA256)
758 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
760 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
765 /* Check EC temporary key is compatible with client extensions */
766 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
768 unsigned char curve_id[2];
769 EC_KEY *ec = s->cert->ecdh_tmp;
770 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
771 /* Allow any curve: not just those peer supports */
772 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
775 /* If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384,
776 * no other curves permitted.
780 /* Curve to check determined by ciphersuite */
781 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
782 curve_id[1] = TLSEXT_curve_P_256;
783 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
784 curve_id[1] = TLSEXT_curve_P_384;
788 /* Check this curve is acceptable */
789 if (!tls1_check_ec_key(s, curve_id, NULL))
791 /* If auto or setting curve from callback assume OK */
792 if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
794 /* Otherwise check curve is acceptable */
797 unsigned char curve_tmp[2];
800 if (!tls1_set_ec_id(curve_tmp, NULL, ec))
802 if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
808 if (s->cert->ecdh_tmp_auto)
810 /* Need a shared curve */
811 if (tls1_shared_curve(s, 0))
817 if (s->cert->ecdh_tmp_cb)
822 if (!tls1_set_ec_id(curve_id, NULL, ec))
824 /* Set this to allow use of invalid curves for testing */
828 return tls1_check_ec_key(s, curve_id, NULL);
834 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
839 #endif /* OPENSSL_NO_EC */
841 #ifndef OPENSSL_NO_TLSEXT
843 /* List of supported signature algorithms and hashes. Should make this
844 * customisable at some point, for now include everything we support.
847 #ifdef OPENSSL_NO_RSA
848 #define tlsext_sigalg_rsa(md) /* */
850 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
853 #ifdef OPENSSL_NO_DSA
854 #define tlsext_sigalg_dsa(md) /* */
856 #define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
859 #ifdef OPENSSL_NO_ECDSA
860 #define tlsext_sigalg_ecdsa(md) /* */
862 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
865 #define tlsext_sigalg(md) \
866 tlsext_sigalg_rsa(md) \
867 tlsext_sigalg_dsa(md) \
868 tlsext_sigalg_ecdsa(md)
870 static unsigned char tls12_sigalgs[] = {
871 #ifndef OPENSSL_NO_SHA512
872 tlsext_sigalg(TLSEXT_hash_sha512)
873 tlsext_sigalg(TLSEXT_hash_sha384)
875 #ifndef OPENSSL_NO_SHA256
876 tlsext_sigalg(TLSEXT_hash_sha256)
877 tlsext_sigalg(TLSEXT_hash_sha224)
879 #ifndef OPENSSL_NO_SHA
880 tlsext_sigalg(TLSEXT_hash_sha1)
883 #ifndef OPENSSL_NO_ECDSA
884 static unsigned char suiteb_sigalgs[] = {
885 tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
886 tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
889 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
891 /* If Suite B mode use Suite B sigalgs only, ignore any other
894 #ifndef OPENSSL_NO_EC
895 switch (tls1_suiteb(s))
897 case SSL_CERT_FLAG_SUITEB_128_LOS:
898 *psigs = suiteb_sigalgs;
899 return sizeof(suiteb_sigalgs);
901 case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
902 *psigs = suiteb_sigalgs;
905 case SSL_CERT_FLAG_SUITEB_192_LOS:
906 *psigs = suiteb_sigalgs + 2;
910 /* If server use client authentication sigalgs if not NULL */
911 if (s->server && s->cert->client_sigalgs)
913 *psigs = s->cert->client_sigalgs;
914 return s->cert->client_sigalgslen;
916 else if (s->cert->conf_sigalgs)
918 *psigs = s->cert->conf_sigalgs;
919 return s->cert->conf_sigalgslen;
923 *psigs = tls12_sigalgs;
924 return sizeof(tls12_sigalgs);
927 /* Check signature algorithm is consistent with sent supported signature
928 * algorithms and if so return relevant digest.
930 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
931 const unsigned char *sig, EVP_PKEY *pkey)
933 const unsigned char *sent_sigs;
934 size_t sent_sigslen, i;
935 int sigalg = tls12_get_sigid(pkey);
936 /* Should never happen */
939 /* Check key type is consistent with signature */
940 if (sigalg != (int)sig[1])
942 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
945 #ifndef OPENSSL_NO_EC
946 if (pkey->type == EVP_PKEY_EC)
948 unsigned char curve_id[2], comp_id;
949 /* Check compression and curve matches extensions */
950 if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
952 if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id))
954 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_CURVE);
957 /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
962 if (curve_id[1] == TLSEXT_curve_P_256)
964 if (sig[0] != TLSEXT_hash_sha256)
966 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
967 SSL_R_ILLEGAL_SUITEB_DIGEST);
971 else if (curve_id[1] == TLSEXT_curve_P_384)
973 if (sig[0] != TLSEXT_hash_sha384)
975 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
976 SSL_R_ILLEGAL_SUITEB_DIGEST);
984 else if (tls1_suiteb(s))
988 /* Check signature matches a type we sent */
989 sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
990 for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
992 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
995 /* Allow fallback to SHA1 if not strict mode */
996 if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
998 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_WRONG_SIGNATURE_TYPE);
1001 *pmd = tls12_get_hash(sig[0]);
1004 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,SSL_R_UNKNOWN_DIGEST);
1007 /* Store the digest used so applications can retrieve it if they
1010 if (s->session && s->session->sess_cert)
1011 s->session->sess_cert->peer_key->digest = *pmd;
1014 /* Get a mask of disabled algorithms: an algorithm is disabled
1015 * if it isn't supported or doesn't appear in supported signature
1016 * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
1017 * session and not global settings.
1020 void ssl_set_client_disabled(SSL *s)
1023 const unsigned char *sigalgs;
1024 size_t i, sigalgslen;
1025 int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
1028 /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
1029 if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
1030 c->mask_ssl = SSL_TLSV1_2;
1033 /* Now go through all signature algorithms seeing if we support
1034 * any for RSA, DSA, ECDSA. Do this for all versions not just
1037 sigalgslen = tls12_get_psigalgs(s, &sigalgs);
1038 for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
1042 #ifndef OPENSSL_NO_RSA
1043 case TLSEXT_signature_rsa:
1047 #ifndef OPENSSL_NO_DSA
1048 case TLSEXT_signature_dsa:
1052 #ifndef OPENSSL_NO_ECDSA
1053 case TLSEXT_signature_ecdsa:
1059 /* Disable auth and static DH if we don't include any appropriate
1060 * signature algorithms.
1064 c->mask_a |= SSL_aRSA;
1065 c->mask_k |= SSL_kDHr|SSL_kECDHr;
1069 c->mask_a |= SSL_aDSS;
1070 c->mask_k |= SSL_kDHd;
1074 c->mask_a |= SSL_aECDSA;
1075 c->mask_k |= SSL_kECDHe;
1077 #ifndef OPENSSL_NO_KRB5
1078 if (!kssl_tgt_is_available(s->kssl_ctx))
1080 c->mask_a |= SSL_aKRB5;
1081 c->mask_k |= SSL_kKRB5;
1084 #ifndef OPENSSL_NO_PSK
1085 /* with PSK there must be client callback set */
1086 if (!s->psk_client_callback)
1088 c->mask_a |= SSL_aPSK;
1089 c->mask_k |= SSL_kPSK;
1091 #endif /* OPENSSL_NO_PSK */
1095 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *p, unsigned char *limit, int *al)
1098 unsigned char *ret = p;
1099 #ifndef OPENSSL_NO_EC
1100 /* See if we support any ECC ciphersuites */
1102 if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s))
1105 unsigned long alg_k, alg_a;
1106 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1108 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
1110 SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1112 alg_k = c->algorithm_mkey;
1113 alg_a = c->algorithm_auth;
1114 if ((alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)
1115 || (alg_a & SSL_aECDSA)))
1124 /* don't add extensions for SSLv3 unless doing secure renegotiation */
1125 if (s->client_version == SSL3_VERSION
1126 && !s->s3->send_connection_binding)
1131 if (ret>=limit) return NULL; /* this really never occurs, but ... */
1133 if (s->tlsext_hostname != NULL)
1135 /* Add TLS extension servername to the Client Hello message */
1136 unsigned long size_str;
1139 /* check for enough space.
1140 4 for the servername type and entension length
1141 2 for servernamelist length
1142 1 for the hostname type
1143 2 for hostname length
1147 if ((lenmax = limit - ret - 9) < 0
1148 || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
1151 /* extension type and length */
1152 s2n(TLSEXT_TYPE_server_name,ret);
1153 s2n(size_str+5,ret);
1155 /* length of servername list */
1156 s2n(size_str+3,ret);
1158 /* hostname type, length and hostname */
1159 *(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
1161 memcpy(ret, s->tlsext_hostname, size_str);
1165 /* Add RI if renegotiating */
1170 if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
1172 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1176 if((limit - p - 4 - el) < 0) return NULL;
1178 s2n(TLSEXT_TYPE_renegotiate,ret);
1181 if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
1183 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1190 #ifndef OPENSSL_NO_SRP
1191 /* Add SRP username if there is one */
1192 if (s->srp_ctx.login != NULL)
1193 { /* Add TLS extension SRP username to the Client Hello message */
1195 int login_len = strlen(s->srp_ctx.login);
1196 if (login_len > 255 || login_len == 0)
1198 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1202 /* check for enough space.
1203 4 for the srp type type and entension length
1204 1 for the srp user identity
1205 + srp user identity length
1207 if ((limit - ret - 5 - login_len) < 0) return NULL;
1209 /* fill in the extension */
1210 s2n(TLSEXT_TYPE_srp,ret);
1211 s2n(login_len+1,ret);
1212 (*ret++) = (unsigned char) login_len;
1213 memcpy(ret, s->srp_ctx.login, login_len);
1218 #ifndef OPENSSL_NO_EC
1221 /* Add TLS extension ECPointFormats to the ClientHello message */
1223 const unsigned char *plist;
1226 tls1_get_formatlist(s, &plist, &plistlen);
1228 if ((lenmax = limit - ret - 5) < 0) return NULL;
1229 if (plistlen > (size_t)lenmax) return NULL;
1232 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1236 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1237 s2n(plistlen + 1,ret);
1238 *(ret++) = (unsigned char)plistlen ;
1239 memcpy(ret, plist, plistlen);
1242 /* Add TLS extension EllipticCurves to the ClientHello message */
1243 plist = s->tlsext_ellipticcurvelist;
1244 tls1_get_curvelist(s, 0, &plist, &plistlen);
1246 if ((lenmax = limit - ret - 6) < 0) return NULL;
1247 if (plistlen > (size_t)lenmax) return NULL;
1248 if (plistlen > 65532)
1250 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1254 s2n(TLSEXT_TYPE_elliptic_curves,ret);
1255 s2n(plistlen + 2, ret);
1257 /* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
1258 * elliptic_curve_list, but the examples use two bytes.
1259 * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
1260 * resolves this to two bytes.
1263 memcpy(ret, plist, plistlen);
1266 #endif /* OPENSSL_NO_EC */
1268 if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
1271 if (!s->new_session && s->session && s->session->tlsext_tick)
1272 ticklen = s->session->tlsext_ticklen;
1273 else if (s->session && s->tlsext_session_ticket &&
1274 s->tlsext_session_ticket->data)
1276 ticklen = s->tlsext_session_ticket->length;
1277 s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1278 if (!s->session->tlsext_tick)
1280 memcpy(s->session->tlsext_tick,
1281 s->tlsext_session_ticket->data,
1283 s->session->tlsext_ticklen = ticklen;
1287 if (ticklen == 0 && s->tlsext_session_ticket &&
1288 s->tlsext_session_ticket->data == NULL)
1290 /* Check for enough room 2 for extension type, 2 for len
1293 if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
1294 s2n(TLSEXT_TYPE_session_ticket,ret);
1298 memcpy(ret, s->session->tlsext_tick, ticklen);
1304 if (SSL_USE_SIGALGS(s))
1307 const unsigned char *salg;
1308 salglen = tls12_get_psigalgs(s, &salg);
1309 if ((size_t)(limit - ret) < salglen + 6)
1311 s2n(TLSEXT_TYPE_signature_algorithms,ret);
1312 s2n(salglen + 2, ret);
1314 memcpy(ret, salg, salglen);
1318 #ifdef TLSEXT_TYPE_opaque_prf_input
1319 if (s->s3->client_opaque_prf_input != NULL)
1321 size_t col = s->s3->client_opaque_prf_input_len;
1323 if ((long)(limit - ret - 6 - col < 0))
1325 if (col > 0xFFFD) /* can't happen */
1328 s2n(TLSEXT_TYPE_opaque_prf_input, ret);
1331 memcpy(ret, s->s3->client_opaque_prf_input, col);
1336 if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
1339 long extlen, idlen, itmp;
1343 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1345 id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1346 itmp = i2d_OCSP_RESPID(id, NULL);
1352 if (s->tlsext_ocsp_exts)
1354 extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1361 if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
1362 s2n(TLSEXT_TYPE_status_request, ret);
1363 if (extlen + idlen > 0xFFF0)
1365 s2n(extlen + idlen + 5, ret);
1366 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1368 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
1370 /* save position of id len */
1371 unsigned char *q = ret;
1372 id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1373 /* skip over id len */
1375 itmp = i2d_OCSP_RESPID(id, &ret);
1381 i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1384 #ifndef OPENSSL_NO_HEARTBEATS
1385 /* Add Heartbeat extension */
1386 s2n(TLSEXT_TYPE_heartbeat,ret);
1389 * 1: peer may send requests
1390 * 2: peer not allowed to send requests
1392 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1393 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1395 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1398 #ifndef OPENSSL_NO_NEXTPROTONEG
1399 if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
1401 /* The client advertises an emtpy extension to indicate its
1402 * support for Next Protocol Negotiation */
1403 if (limit - ret - 4 < 0)
1405 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1410 if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len)
1412 if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
1414 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1415 s2n(2 + s->alpn_client_proto_list_len,ret);
1416 s2n(s->alpn_client_proto_list_len,ret);
1417 memcpy(ret, s->alpn_client_proto_list,
1418 s->alpn_client_proto_list_len);
1419 ret += s->alpn_client_proto_list_len;
1422 if(SSL_get_srtp_profiles(s))
1426 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
1428 if((limit - p - 4 - el) < 0) return NULL;
1430 s2n(TLSEXT_TYPE_use_srtp,ret);
1433 if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
1435 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1441 /* Add custom TLS Extensions to ClientHello */
1442 if (s->ctx->custom_cli_ext_records_count)
1445 custom_cli_ext_record* record;
1447 for (i = 0; i < s->ctx->custom_cli_ext_records_count; i++)
1449 const unsigned char* out = NULL;
1450 unsigned short outlen = 0;
1452 record = &s->ctx->custom_cli_ext_records[i];
1453 /* NULL callback sends empty extension */
1454 /* -1 from callback omits extension */
1458 cb_retval = record->fn1(s, record->ext_type,
1462 return NULL; /* error */
1463 if (cb_retval == -1)
1464 continue; /* skip this extension */
1466 if (limit < ret + 4 + outlen)
1468 s2n(record->ext_type, ret);
1470 memcpy(ret, out, outlen);
1474 #ifdef TLSEXT_TYPE_encrypt_then_mac
1475 s2n(TLSEXT_TYPE_encrypt_then_mac,ret);
1478 #ifdef TLSEXT_TYPE_padding
1479 /* Add padding to workaround bugs in F5 terminators.
1480 * See https://tools.ietf.org/html/draft-agl-tls-padding-02
1482 * NB: because this code works out the length of all existing
1483 * extensions it MUST always appear last.
1486 int hlen = ret - (unsigned char *)s->init_buf->data;
1487 /* The code in s23_clnt.c to build ClientHello messages includes the
1488 * 5-byte record header in the buffer, while the code in s3_clnt.c does
1490 if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1492 if (hlen > 0xff && hlen < 0x200)
1494 hlen = 0x200 - hlen;
1500 s2n(TLSEXT_TYPE_padding, ret);
1502 memset(ret, 0, hlen);
1508 if ((extdatalen = ret-p-2) == 0)
1515 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *p, unsigned char *limit, int *al)
1518 unsigned char *ret = p;
1520 custom_srv_ext_record *record;
1521 #ifndef OPENSSL_NO_NEXTPROTONEG
1522 int next_proto_neg_seen;
1524 #ifndef OPENSSL_NO_EC
1525 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1526 unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1527 int using_ecc = (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA);
1528 using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1530 /* don't add extensions for SSLv3, unless doing secure renegotiation */
1531 if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
1535 if (ret>=limit) return NULL; /* this really never occurs, but ... */
1537 if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL)
1539 if ((long)(limit - ret - 4) < 0) return NULL;
1541 s2n(TLSEXT_TYPE_server_name,ret);
1545 if(s->s3->send_connection_binding)
1549 if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
1551 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1555 if((limit - p - 4 - el) < 0) return NULL;
1557 s2n(TLSEXT_TYPE_renegotiate,ret);
1560 if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
1562 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1569 #ifndef OPENSSL_NO_EC
1572 const unsigned char *plist;
1574 /* Add TLS extension ECPointFormats to the ServerHello message */
1577 tls1_get_formatlist(s, &plist, &plistlen);
1579 if ((lenmax = limit - ret - 5) < 0) return NULL;
1580 if (plistlen > (size_t)lenmax) return NULL;
1583 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1587 s2n(TLSEXT_TYPE_ec_point_formats,ret);
1588 s2n(plistlen + 1,ret);
1589 *(ret++) = (unsigned char) plistlen;
1590 memcpy(ret, plist, plistlen);
1594 /* Currently the server should not respond with a SupportedCurves extension */
1595 #endif /* OPENSSL_NO_EC */
1597 if (s->tlsext_ticket_expected
1598 && !(SSL_get_options(s) & SSL_OP_NO_TICKET))
1600 if ((long)(limit - ret - 4) < 0) return NULL;
1601 s2n(TLSEXT_TYPE_session_ticket,ret);
1605 if (s->tlsext_status_expected)
1607 if ((long)(limit - ret - 4) < 0) return NULL;
1608 s2n(TLSEXT_TYPE_status_request,ret);
1612 #ifdef TLSEXT_TYPE_opaque_prf_input
1613 if (s->s3->server_opaque_prf_input != NULL)
1615 size_t sol = s->s3->server_opaque_prf_input_len;
1617 if ((long)(limit - ret - 6 - sol) < 0)
1619 if (sol > 0xFFFD) /* can't happen */
1622 s2n(TLSEXT_TYPE_opaque_prf_input, ret);
1625 memcpy(ret, s->s3->server_opaque_prf_input, sol);
1634 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
1636 if((limit - p - 4 - el) < 0) return NULL;
1638 s2n(TLSEXT_TYPE_use_srtp,ret);
1641 if(ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
1643 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1649 if (((s->s3->tmp.new_cipher->id & 0xFFFF)==0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF)==0x81)
1650 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG))
1651 { const unsigned char cryptopro_ext[36] = {
1652 0xfd, 0xe8, /*65000*/
1653 0x00, 0x20, /*32 bytes length*/
1654 0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1655 0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1656 0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1657 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17};
1658 if (limit-ret<36) return NULL;
1659 memcpy(ret,cryptopro_ext,36);
1664 #ifndef OPENSSL_NO_HEARTBEATS
1665 /* Add Heartbeat extension if we've received one */
1666 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED)
1668 s2n(TLSEXT_TYPE_heartbeat,ret);
1671 * 1: peer may send requests
1672 * 2: peer not allowed to send requests
1674 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1675 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1677 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1682 #ifndef OPENSSL_NO_NEXTPROTONEG
1683 next_proto_neg_seen = s->s3->next_proto_neg_seen;
1684 s->s3->next_proto_neg_seen = 0;
1685 if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
1687 const unsigned char *npa;
1688 unsigned int npalen;
1691 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
1692 if (r == SSL_TLSEXT_ERR_OK)
1694 if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
1695 s2n(TLSEXT_TYPE_next_proto_neg,ret);
1697 memcpy(ret, npa, npalen);
1699 s->s3->next_proto_neg_seen = 1;
1704 for (i = 0; i < s->ctx->custom_srv_ext_records_count; i++)
1706 const unsigned char *out = NULL;
1707 unsigned short outlen = 0;
1710 record = &s->ctx->custom_srv_ext_records[i];
1712 /* NULL callback or -1 omits extension */
1715 cb_retval = record->fn2(s, record->ext_type,
1719 return NULL; /* error */
1720 if (cb_retval == -1)
1721 continue; /* skip this extension */
1722 if (limit < ret + 4 + outlen)
1724 s2n(record->ext_type, ret);
1726 memcpy(ret, out, outlen);
1729 #ifdef TLSEXT_TYPE_encrypt_then_mac
1730 if (s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC)
1732 /* Don't use encrypt_then_mac if AEAD: might want
1733 * to disable for other ciphersuites too.
1735 if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD)
1736 s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
1739 s2n(TLSEXT_TYPE_encrypt_then_mac,ret);
1745 if (s->s3->alpn_selected)
1747 const unsigned char *selected = s->s3->alpn_selected;
1748 unsigned len = s->s3->alpn_selected_len;
1750 if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
1752 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
1756 memcpy(ret, selected, len);
1760 if ((extdatalen = ret-p-2)== 0)
1767 /* tls1_alpn_handle_client_hello is called to process the ALPN extension in a
1769 * data: the contents of the extension, not including the type and length.
1770 * data_len: the number of bytes in |data|
1771 * al: a pointer to the alert value to send in the event of a non-zero
1774 * returns: 0 on success. */
1775 static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
1776 unsigned data_len, int *al)
1780 const unsigned char *selected;
1781 unsigned char selected_len;
1784 if (s->ctx->alpn_select_cb == NULL)
1790 /* data should contain a uint16 length followed by a series of 8-bit,
1791 * length-prefixed strings. */
1792 i = ((unsigned) data[0]) << 8 |
1793 ((unsigned) data[1]);
1802 for (i = 0; i < data_len;)
1804 proto_len = data[i];
1810 if (i + proto_len < i || i + proto_len > data_len)
1816 r = s->ctx->alpn_select_cb(s, &selected, &selected_len, data, data_len,
1817 s->ctx->alpn_select_cb_arg);
1818 if (r == SSL_TLSEXT_ERR_OK) {
1819 if (s->s3->alpn_selected)
1820 OPENSSL_free(s->s3->alpn_selected);
1821 s->s3->alpn_selected = OPENSSL_malloc(selected_len);
1822 if (!s->s3->alpn_selected)
1824 *al = SSL_AD_INTERNAL_ERROR;
1827 memcpy(s->s3->alpn_selected, selected, selected_len);
1828 s->s3->alpn_selected_len = selected_len;
1833 *al = SSL_AD_DECODE_ERROR;
1837 #ifndef OPENSSL_NO_EC
1838 /* ssl_check_for_safari attempts to fingerprint Safari using OS X
1839 * SecureTransport using the TLS extension block in |d|, of length |n|.
1840 * Safari, since 10.6, sends exactly these extensions, in this order:
1845 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1846 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1847 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1848 * 10.8..10.8.3 (which don't work).
1850 static void ssl_check_for_safari(SSL *s, const unsigned char *data, const unsigned char *d, int n) {
1851 unsigned short type, size;
1852 static const unsigned char kSafariExtensionsBlock[] = {
1853 0x00, 0x0a, /* elliptic_curves extension */
1854 0x00, 0x08, /* 8 bytes */
1855 0x00, 0x06, /* 6 bytes of curve ids */
1856 0x00, 0x17, /* P-256 */
1857 0x00, 0x18, /* P-384 */
1858 0x00, 0x19, /* P-521 */
1860 0x00, 0x0b, /* ec_point_formats */
1861 0x00, 0x02, /* 2 bytes */
1862 0x01, /* 1 point format */
1863 0x00, /* uncompressed */
1866 /* The following is only present in TLS 1.2 */
1867 static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1868 0x00, 0x0d, /* signature_algorithms */
1869 0x00, 0x0c, /* 12 bytes */
1870 0x00, 0x0a, /* 10 bytes */
1871 0x05, 0x01, /* SHA-384/RSA */
1872 0x04, 0x01, /* SHA-256/RSA */
1873 0x02, 0x01, /* SHA-1/RSA */
1874 0x04, 0x03, /* SHA-256/ECDSA */
1875 0x02, 0x03, /* SHA-1/ECDSA */
1878 if (data >= (d+n-2))
1887 if (type != TLSEXT_TYPE_server_name)
1890 if (data+size > d+n)
1894 if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
1896 const size_t len1 = sizeof(kSafariExtensionsBlock);
1897 const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1899 if (data + len1 + len2 != d+n)
1901 if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
1903 if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
1908 const size_t len = sizeof(kSafariExtensionsBlock);
1910 if (data + len != d+n)
1912 if (memcmp(data, kSafariExtensionsBlock, len) != 0)
1916 s->s3->is_probably_safari = 1;
1918 #endif /* !OPENSSL_NO_EC */
1920 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
1922 unsigned short type;
1923 unsigned short size;
1925 unsigned char *data = *p;
1926 int renegotiate_seen = 0;
1929 s->servername_done = 0;
1930 s->tlsext_status_type = -1;
1931 #ifndef OPENSSL_NO_NEXTPROTONEG
1932 s->s3->next_proto_neg_seen = 0;
1935 if (s->s3->alpn_selected)
1937 OPENSSL_free(s->s3->alpn_selected);
1938 s->s3->alpn_selected = NULL;
1941 /* Clear observed custom extensions */
1942 s->s3->serverinfo_client_tlsext_custom_types_count = 0;
1943 if (s->s3->serverinfo_client_tlsext_custom_types != NULL)
1945 OPENSSL_free(s->s3->serverinfo_client_tlsext_custom_types);
1946 s->s3->serverinfo_client_tlsext_custom_types = NULL;
1949 #ifndef OPENSSL_NO_HEARTBEATS
1950 s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1951 SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1954 #ifndef OPENSSL_NO_EC
1955 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1956 ssl_check_for_safari(s, data, d, n);
1957 #endif /* !OPENSSL_NO_EC */
1959 /* Clear any signature algorithms extension received */
1960 if (s->cert->peer_sigalgs)
1962 OPENSSL_free(s->cert->peer_sigalgs);
1963 s->cert->peer_sigalgs = NULL;
1965 /* Clear any shared sigtnature algorithms */
1966 if (s->cert->shared_sigalgs)
1968 OPENSSL_free(s->cert->shared_sigalgs);
1969 s->cert->shared_sigalgs = NULL;
1971 /* Clear certificate digests and validity flags */
1972 for (i = 0; i < SSL_PKEY_NUM; i++)
1974 s->cert->pkeys[i].digest = NULL;
1975 s->cert->pkeys[i].valid_flags = 0;
1978 #ifdef TLSEXT_TYPE_encrypt_then_mac
1979 s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
1982 if (data >= (d+n-2))
1986 if (data > (d+n-len))
1989 while (data <= (d+n-4))
1994 if (data+size > (d+n))
1997 fprintf(stderr,"Received extension type %d size %d\n",type,size);
1999 if (s->tlsext_debug_cb)
2000 s->tlsext_debug_cb(s, 0, type, data, size,
2001 s->tlsext_debug_arg);
2002 /* The servername extension is treated as follows:
2004 - Only the hostname type is supported with a maximum length of 255.
2005 - The servername is rejected if too long or if it contains zeros,
2006 in which case an fatal alert is generated.
2007 - The servername field is maintained together with the session cache.
2008 - When a session is resumed, the servername call back invoked in order
2009 to allow the application to position itself to the right context.
2010 - The servername is acknowledged if it is new for a session or when
2011 it is identical to a previously used for the same session.
2012 Applications can control the behaviour. They can at any time
2013 set a 'desirable' servername for a new SSL object. This can be the
2014 case for example with HTTPS when a Host: header field is received and
2015 a renegotiation is requested. In this case, a possible servername
2016 presented in the new client hello is only acknowledged if it matches
2017 the value of the Host: field.
2018 - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
2019 if they provide for changing an explicit servername context for the session,
2020 i.e. when the session has been established with a servername extension.
2021 - On session reconnect, the servername extension may be absent.
2025 if (type == TLSEXT_TYPE_server_name)
2027 unsigned char *sdata;
2033 *al = SSL_AD_DECODE_ERROR;
2040 *al = SSL_AD_DECODE_ERROR;
2047 servname_type = *(sdata++);
2053 *al = SSL_AD_DECODE_ERROR;
2056 if (s->servername_done == 0)
2057 switch (servname_type)
2059 case TLSEXT_NAMETYPE_host_name:
2062 if(s->session->tlsext_hostname)
2064 *al = SSL_AD_DECODE_ERROR;
2067 if (len > TLSEXT_MAXLEN_host_name)
2069 *al = TLS1_AD_UNRECOGNIZED_NAME;
2072 if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
2074 *al = TLS1_AD_INTERNAL_ERROR;
2077 memcpy(s->session->tlsext_hostname, sdata, len);
2078 s->session->tlsext_hostname[len]='\0';
2079 if (strlen(s->session->tlsext_hostname) != len) {
2080 OPENSSL_free(s->session->tlsext_hostname);
2081 s->session->tlsext_hostname = NULL;
2082 *al = TLS1_AD_UNRECOGNIZED_NAME;
2085 s->servername_done = 1;
2089 s->servername_done = s->session->tlsext_hostname
2090 && strlen(s->session->tlsext_hostname) == len
2091 && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
2103 *al = SSL_AD_DECODE_ERROR;
2108 #ifndef OPENSSL_NO_SRP
2109 else if (type == TLSEXT_TYPE_srp)
2111 if (size <= 0 || ((len = data[0])) != (size -1))
2113 *al = SSL_AD_DECODE_ERROR;
2116 if (s->srp_ctx.login != NULL)
2118 *al = SSL_AD_DECODE_ERROR;
2121 if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
2123 memcpy(s->srp_ctx.login, &data[1], len);
2124 s->srp_ctx.login[len]='\0';
2126 if (strlen(s->srp_ctx.login) != len)
2128 *al = SSL_AD_DECODE_ERROR;
2134 #ifndef OPENSSL_NO_EC
2135 else if (type == TLSEXT_TYPE_ec_point_formats)
2137 unsigned char *sdata = data;
2138 int ecpointformatlist_length = *(sdata++);
2140 if (ecpointformatlist_length != size - 1 ||
2141 ecpointformatlist_length < 1)
2143 *al = TLS1_AD_DECODE_ERROR;
2148 if(s->session->tlsext_ecpointformatlist)
2150 OPENSSL_free(s->session->tlsext_ecpointformatlist);
2151 s->session->tlsext_ecpointformatlist = NULL;
2153 s->session->tlsext_ecpointformatlist_length = 0;
2154 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2156 *al = TLS1_AD_INTERNAL_ERROR;
2159 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2160 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2163 fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
2164 sdata = s->session->tlsext_ecpointformatlist;
2165 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2166 fprintf(stderr,"%i ",*(sdata++));
2167 fprintf(stderr,"\n");
2170 else if (type == TLSEXT_TYPE_elliptic_curves)
2172 unsigned char *sdata = data;
2173 int ellipticcurvelist_length = (*(sdata++) << 8);
2174 ellipticcurvelist_length += (*(sdata++));
2176 if (ellipticcurvelist_length != size - 2 ||
2177 ellipticcurvelist_length < 1)
2179 *al = TLS1_AD_DECODE_ERROR;
2184 if(s->session->tlsext_ellipticcurvelist)
2186 *al = TLS1_AD_DECODE_ERROR;
2189 s->session->tlsext_ellipticcurvelist_length = 0;
2190 if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
2192 *al = TLS1_AD_INTERNAL_ERROR;
2195 s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
2196 memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
2199 fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
2200 sdata = s->session->tlsext_ellipticcurvelist;
2201 for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
2202 fprintf(stderr,"%i ",*(sdata++));
2203 fprintf(stderr,"\n");
2206 #endif /* OPENSSL_NO_EC */
2207 #ifdef TLSEXT_TYPE_opaque_prf_input
2208 else if (type == TLSEXT_TYPE_opaque_prf_input)
2210 unsigned char *sdata = data;
2214 *al = SSL_AD_DECODE_ERROR;
2217 n2s(sdata, s->s3->client_opaque_prf_input_len);
2218 if (s->s3->client_opaque_prf_input_len != size - 2)
2220 *al = SSL_AD_DECODE_ERROR;
2224 if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2225 OPENSSL_free(s->s3->client_opaque_prf_input);
2226 if (s->s3->client_opaque_prf_input_len == 0)
2227 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2229 s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
2230 if (s->s3->client_opaque_prf_input == NULL)
2232 *al = TLS1_AD_INTERNAL_ERROR;
2237 else if (type == TLSEXT_TYPE_session_ticket)
2239 if (s->tls_session_ticket_ext_cb &&
2240 !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2242 *al = TLS1_AD_INTERNAL_ERROR;
2246 else if (type == TLSEXT_TYPE_renegotiate)
2248 if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
2250 renegotiate_seen = 1;
2252 else if (type == TLSEXT_TYPE_signature_algorithms)
2255 if (s->cert->peer_sigalgs || size < 2)
2257 *al = SSL_AD_DECODE_ERROR;
2262 if (dsize != size || dsize & 1 || !dsize)
2264 *al = SSL_AD_DECODE_ERROR;
2267 if (!tls1_process_sigalgs(s, data, dsize))
2269 *al = SSL_AD_DECODE_ERROR;
2272 /* If sigalgs received and no shared algorithms fatal
2275 if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
2277 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2278 SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
2279 *al = SSL_AD_ILLEGAL_PARAMETER;
2283 else if (type == TLSEXT_TYPE_status_request)
2288 *al = SSL_AD_DECODE_ERROR;
2292 s->tlsext_status_type = *data++;
2294 if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
2296 const unsigned char *sdata;
2298 /* Read in responder_id_list */
2303 *al = SSL_AD_DECODE_ERROR;
2312 *al = SSL_AD_DECODE_ERROR;
2316 dsize -= 2 + idsize;
2320 *al = SSL_AD_DECODE_ERROR;
2325 id = d2i_OCSP_RESPID(NULL,
2329 *al = SSL_AD_DECODE_ERROR;
2334 OCSP_RESPID_free(id);
2335 *al = SSL_AD_DECODE_ERROR;
2338 if (!s->tlsext_ocsp_ids
2339 && !(s->tlsext_ocsp_ids =
2340 sk_OCSP_RESPID_new_null()))
2342 OCSP_RESPID_free(id);
2343 *al = SSL_AD_INTERNAL_ERROR;
2346 if (!sk_OCSP_RESPID_push(
2347 s->tlsext_ocsp_ids, id))
2349 OCSP_RESPID_free(id);
2350 *al = SSL_AD_INTERNAL_ERROR;
2355 /* Read in request_extensions */
2358 *al = SSL_AD_DECODE_ERROR;
2365 *al = SSL_AD_DECODE_ERROR;
2371 if (s->tlsext_ocsp_exts)
2373 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2374 X509_EXTENSION_free);
2377 s->tlsext_ocsp_exts =
2378 d2i_X509_EXTENSIONS(NULL,
2380 if (!s->tlsext_ocsp_exts
2381 || (data + dsize != sdata))
2383 *al = SSL_AD_DECODE_ERROR;
2388 /* We don't know what to do with any other type
2392 s->tlsext_status_type = -1;
2394 #ifndef OPENSSL_NO_HEARTBEATS
2395 else if (type == TLSEXT_TYPE_heartbeat)
2399 case 0x01: /* Client allows us to send HB requests */
2400 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2402 case 0x02: /* Client doesn't accept HB requests */
2403 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2404 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2406 default: *al = SSL_AD_ILLEGAL_PARAMETER;
2411 #ifndef OPENSSL_NO_NEXTPROTONEG
2412 else if (type == TLSEXT_TYPE_next_proto_neg &&
2413 s->s3->tmp.finish_md_len == 0 &&
2414 s->s3->alpn_selected == NULL)
2416 /* We shouldn't accept this extension on a
2419 * s->new_session will be set on renegotiation, but we
2420 * probably shouldn't rely that it couldn't be set on
2421 * the initial renegotation too in certain cases (when
2422 * there's some other reason to disallow resuming an
2423 * earlier session -- the current code won't be doing
2424 * anything like that, but this might change).
2426 * A valid sign that there's been a previous handshake
2427 * in this connection is if s->s3->tmp.finish_md_len >
2428 * 0. (We are talking about a check that will happen
2429 * in the Hello protocol round, well before a new
2430 * Finished message could have been computed.) */
2431 s->s3->next_proto_neg_seen = 1;
2435 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2436 s->ctx->alpn_select_cb &&
2437 s->s3->tmp.finish_md_len == 0)
2439 if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2441 #ifndef OPENSSL_NO_NEXTPROTONEG
2442 /* ALPN takes precedence over NPN. */
2443 s->s3->next_proto_neg_seen = 0;
2447 /* session ticket processed earlier */
2448 else if (type == TLSEXT_TYPE_use_srtp)
2450 if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
2454 /* If this ClientHello extension was unhandled and this is
2455 * a nonresumed connection, check whether the extension is a
2456 * custom TLS Extension (has a custom_srv_ext_record), and if
2457 * so call the callback and record the extension number so that
2458 * an appropriate ServerHello may be later returned.
2460 else if (!s->hit && s->ctx->custom_srv_ext_records_count)
2462 custom_srv_ext_record *record;
2464 for (i=0; i < s->ctx->custom_srv_ext_records_count; i++)
2466 record = &s->ctx->custom_srv_ext_records[i];
2467 if (type == record->ext_type)
2469 if (record->fn1 && !record->fn1(s, type, data, size, al, record->arg))
2474 #ifdef TLSEXT_TYPE_encrypt_then_mac
2475 else if (type == TLSEXT_TYPE_encrypt_then_mac)
2476 s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
2486 /* Need RI if renegotiating */
2488 if (!renegotiate_seen && s->renegotiate &&
2489 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2491 *al = SSL_AD_HANDSHAKE_FAILURE;
2492 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2493 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2496 /* If no signature algorithms extension set default values */
2497 if (!s->cert->peer_sigalgs)
2498 ssl_cert_set_default_md(s->cert);
2503 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n)
2506 if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0)
2508 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2512 if (ssl_check_clienthello_tlsext_early(s) <= 0)
2514 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,SSL_R_CLIENTHELLO_TLSEXT);
2520 #ifndef OPENSSL_NO_NEXTPROTONEG
2521 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2522 * elements of zero length are allowed and the set of elements must exactly fill
2523 * the length of the block. */
2524 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2526 unsigned int off = 0;
2540 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
2542 unsigned short length;
2543 unsigned short type;
2544 unsigned short size;
2545 unsigned char *data = *p;
2546 int tlsext_servername = 0;
2547 int renegotiate_seen = 0;
2549 #ifndef OPENSSL_NO_NEXTPROTONEG
2550 s->s3->next_proto_neg_seen = 0;
2553 if (s->s3->alpn_selected)
2555 OPENSSL_free(s->s3->alpn_selected);
2556 s->s3->alpn_selected = NULL;
2559 #ifndef OPENSSL_NO_HEARTBEATS
2560 s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2561 SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2564 #ifdef TLSEXT_TYPE_encrypt_then_mac
2565 s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
2568 if (data >= (d+n-2))
2572 if (data+length != d+n)
2574 *al = SSL_AD_DECODE_ERROR;
2578 while(data <= (d+n-4))
2583 if (data+size > (d+n))
2586 if (s->tlsext_debug_cb)
2587 s->tlsext_debug_cb(s, 1, type, data, size,
2588 s->tlsext_debug_arg);
2590 if (type == TLSEXT_TYPE_server_name)
2592 if (s->tlsext_hostname == NULL || size > 0)
2594 *al = TLS1_AD_UNRECOGNIZED_NAME;
2597 tlsext_servername = 1;
2600 #ifndef OPENSSL_NO_EC
2601 else if (type == TLSEXT_TYPE_ec_point_formats)
2603 unsigned char *sdata = data;
2604 int ecpointformatlist_length = *(sdata++);
2606 if (ecpointformatlist_length != size - 1)
2608 *al = TLS1_AD_DECODE_ERROR;
2611 s->session->tlsext_ecpointformatlist_length = 0;
2612 if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist);
2613 if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
2615 *al = TLS1_AD_INTERNAL_ERROR;
2618 s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
2619 memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
2621 fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist ");
2622 sdata = s->session->tlsext_ecpointformatlist;
2623 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
2624 fprintf(stderr,"%i ",*(sdata++));
2625 fprintf(stderr,"\n");
2628 #endif /* OPENSSL_NO_EC */
2630 else if (type == TLSEXT_TYPE_session_ticket)
2632 if (s->tls_session_ticket_ext_cb &&
2633 !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
2635 *al = TLS1_AD_INTERNAL_ERROR;
2638 if ((SSL_get_options(s) & SSL_OP_NO_TICKET)
2641 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2644 s->tlsext_ticket_expected = 1;
2646 #ifdef TLSEXT_TYPE_opaque_prf_input
2647 else if (type == TLSEXT_TYPE_opaque_prf_input)
2649 unsigned char *sdata = data;
2653 *al = SSL_AD_DECODE_ERROR;
2656 n2s(sdata, s->s3->server_opaque_prf_input_len);
2657 if (s->s3->server_opaque_prf_input_len != size - 2)
2659 *al = SSL_AD_DECODE_ERROR;
2663 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2664 OPENSSL_free(s->s3->server_opaque_prf_input);
2665 if (s->s3->server_opaque_prf_input_len == 0)
2666 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2668 s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len);
2670 if (s->s3->server_opaque_prf_input == NULL)
2672 *al = TLS1_AD_INTERNAL_ERROR;
2677 else if (type == TLSEXT_TYPE_status_request)
2679 /* MUST be empty and only sent if we've requested
2680 * a status request message.
2682 if ((s->tlsext_status_type == -1) || (size > 0))
2684 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2687 /* Set flag to expect CertificateStatus message */
2688 s->tlsext_status_expected = 1;
2690 #ifndef OPENSSL_NO_NEXTPROTONEG
2691 else if (type == TLSEXT_TYPE_next_proto_neg &&
2692 s->s3->tmp.finish_md_len == 0)
2694 unsigned char *selected;
2695 unsigned char selected_len;
2697 /* We must have requested it. */
2698 if (s->ctx->next_proto_select_cb == NULL)
2700 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2703 /* The data must be valid */
2704 if (!ssl_next_proto_validate(data, size))
2706 *al = TLS1_AD_DECODE_ERROR;
2709 if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
2711 *al = TLS1_AD_INTERNAL_ERROR;
2714 s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2715 if (!s->next_proto_negotiated)
2717 *al = TLS1_AD_INTERNAL_ERROR;
2720 memcpy(s->next_proto_negotiated, selected, selected_len);
2721 s->next_proto_negotiated_len = selected_len;
2722 s->s3->next_proto_neg_seen = 1;
2726 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
2730 /* We must have requested it. */
2731 if (s->alpn_client_proto_list == NULL)
2733 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2738 *al = TLS1_AD_DECODE_ERROR;
2741 /* The extension data consists of:
2742 * uint16 list_length
2743 * uint8 proto_length;
2744 * uint8 proto[proto_length]; */
2748 if (len != (unsigned) size - 2)
2750 *al = TLS1_AD_DECODE_ERROR;
2754 if (len != (unsigned) size - 3)
2756 *al = TLS1_AD_DECODE_ERROR;
2759 if (s->s3->alpn_selected)
2760 OPENSSL_free(s->s3->alpn_selected);
2761 s->s3->alpn_selected = OPENSSL_malloc(len);
2762 if (!s->s3->alpn_selected)
2764 *al = TLS1_AD_INTERNAL_ERROR;
2767 memcpy(s->s3->alpn_selected, data + 3, len);
2768 s->s3->alpn_selected_len = len;
2771 else if (type == TLSEXT_TYPE_renegotiate)
2773 if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2775 renegotiate_seen = 1;
2777 #ifndef OPENSSL_NO_HEARTBEATS
2778 else if (type == TLSEXT_TYPE_heartbeat)
2782 case 0x01: /* Server allows us to send HB requests */
2783 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2785 case 0x02: /* Server doesn't accept HB requests */
2786 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2787 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2789 default: *al = SSL_AD_ILLEGAL_PARAMETER;
2794 else if (type == TLSEXT_TYPE_use_srtp)
2796 if(ssl_parse_serverhello_use_srtp_ext(s, data, size,
2800 /* If this extension type was not otherwise handled, but
2801 * matches a custom_cli_ext_record, then send it to the c
2803 else if (s->ctx->custom_cli_ext_records_count)
2806 custom_cli_ext_record* record;
2808 for (i = 0; i < s->ctx->custom_cli_ext_records_count; i++)
2810 record = &s->ctx->custom_cli_ext_records[i];
2811 if (record->ext_type == type)
2813 if (record->fn2 && !record->fn2(s, type, data, size, al, record->arg))
2819 #ifdef TLSEXT_TYPE_encrypt_then_mac
2820 else if (type == TLSEXT_TYPE_encrypt_then_mac)
2822 /* Ignore if inappropriate ciphersuite */
2823 if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD)
2824 s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
2833 *al = SSL_AD_DECODE_ERROR;
2837 if (!s->hit && tlsext_servername == 1)
2839 if (s->tlsext_hostname)
2841 if (s->session->tlsext_hostname == NULL)
2843 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
2844 if (!s->session->tlsext_hostname)
2846 *al = SSL_AD_UNRECOGNIZED_NAME;
2852 *al = SSL_AD_DECODE_ERROR;
2862 /* Determine if we need to see RI. Strictly speaking if we want to
2863 * avoid an attack we should *always* see RI even on initial server
2864 * hello because the client doesn't see any renegotiation during an
2865 * attack. However this would mean we could not connect to any server
2866 * which doesn't support RI so for the immediate future tolerate RI
2867 * absence on initial connect only.
2869 if (!renegotiate_seen
2870 && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2871 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
2873 *al = SSL_AD_HANDSHAKE_FAILURE;
2874 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2875 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2883 int ssl_prepare_clienthello_tlsext(SSL *s)
2886 #ifdef TLSEXT_TYPE_opaque_prf_input
2890 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2892 r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2897 if (s->tlsext_opaque_prf_input != NULL)
2899 if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
2900 OPENSSL_free(s->s3->client_opaque_prf_input);
2902 if (s->tlsext_opaque_prf_input_len == 0)
2903 s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2905 s->s3->client_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2906 if (s->s3->client_opaque_prf_input == NULL)
2908 SSLerr(SSL_F_SSL_PREPARE_CLIENTHELLO_TLSEXT,ERR_R_MALLOC_FAILURE);
2911 s->s3->client_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2915 /* at callback's request, insist on receiving an appropriate server opaque PRF input */
2916 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2923 int ssl_prepare_serverhello_tlsext(SSL *s)
2928 static int ssl_check_clienthello_tlsext_early(SSL *s)
2930 int ret=SSL_TLSEXT_ERR_NOACK;
2931 int al = SSL_AD_UNRECOGNIZED_NAME;
2933 #ifndef OPENSSL_NO_EC
2934 /* The handling of the ECPointFormats extension is done elsewhere, namely in
2935 * ssl3_choose_cipher in s3_lib.c.
2937 /* The handling of the EllipticCurves extension is done elsewhere, namely in
2938 * ssl3_choose_cipher in s3_lib.c.
2942 if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
2943 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
2944 else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)
2945 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
2947 #ifdef TLSEXT_TYPE_opaque_prf_input
2949 /* This sort of belongs into ssl_prepare_serverhello_tlsext(),
2950 * but we might be sending an alert in response to the client hello,
2951 * so this has to happen here in
2952 * ssl_check_clienthello_tlsext_early(). */
2956 if (s->ctx->tlsext_opaque_prf_input_callback != 0)
2958 r = s->ctx->tlsext_opaque_prf_input_callback(s, NULL, 0, s->ctx->tlsext_opaque_prf_input_callback_arg);
2961 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2962 al = SSL_AD_INTERNAL_ERROR;
2967 if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */
2968 OPENSSL_free(s->s3->server_opaque_prf_input);
2969 s->s3->server_opaque_prf_input = NULL;
2971 if (s->tlsext_opaque_prf_input != NULL)
2973 if (s->s3->client_opaque_prf_input != NULL &&
2974 s->s3->client_opaque_prf_input_len == s->tlsext_opaque_prf_input_len)
2976 /* can only use this extension if we have a server opaque PRF input
2977 * of the same length as the client opaque PRF input! */
2979 if (s->tlsext_opaque_prf_input_len == 0)
2980 s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
2982 s->s3->server_opaque_prf_input = BUF_memdup(s->tlsext_opaque_prf_input, s->tlsext_opaque_prf_input_len);
2983 if (s->s3->server_opaque_prf_input == NULL)
2985 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2986 al = SSL_AD_INTERNAL_ERROR;
2989 s->s3->server_opaque_prf_input_len = s->tlsext_opaque_prf_input_len;
2993 if (r == 2 && s->s3->server_opaque_prf_input == NULL)
2995 /* The callback wants to enforce use of the extension,
2996 * but we can't do that with the client opaque PRF input;
2997 * abort the handshake.
2999 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3000 al = SSL_AD_HANDSHAKE_FAILURE;
3008 case SSL_TLSEXT_ERR_ALERT_FATAL:
3009 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3012 case SSL_TLSEXT_ERR_ALERT_WARNING:
3013 ssl3_send_alert(s,SSL3_AL_WARNING,al);
3016 case SSL_TLSEXT_ERR_NOACK:
3017 s->servername_done=0;
3023 int ssl_check_clienthello_tlsext_late(SSL *s)
3025 int ret = SSL_TLSEXT_ERR_OK;
3028 /* If status request then ask callback what to do.
3029 * Note: this must be called after servername callbacks in case
3030 * the certificate has changed, and must be called after the cipher
3031 * has been chosen because this may influence which certificate is sent
3033 if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb)
3036 CERT_PKEY *certpkey;
3037 certpkey = ssl_get_server_send_pkey(s);
3038 /* If no certificate can't return certificate status */
3039 if (certpkey == NULL)
3041 s->tlsext_status_expected = 0;
3044 /* Set current certificate to one we will use so
3045 * SSL_get_certificate et al can pick it up.
3047 s->cert->key = certpkey;
3048 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3051 /* We don't want to send a status request response */
3052 case SSL_TLSEXT_ERR_NOACK:
3053 s->tlsext_status_expected = 0;
3055 /* status request response should be sent */
3056 case SSL_TLSEXT_ERR_OK:
3057 if (s->tlsext_ocsp_resp)
3058 s->tlsext_status_expected = 1;
3060 s->tlsext_status_expected = 0;
3062 /* something bad happened */
3063 case SSL_TLSEXT_ERR_ALERT_FATAL:
3064 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3065 al = SSL_AD_INTERNAL_ERROR;
3070 s->tlsext_status_expected = 0;
3075 case SSL_TLSEXT_ERR_ALERT_FATAL:
3076 ssl3_send_alert(s, SSL3_AL_FATAL, al);
3079 case SSL_TLSEXT_ERR_ALERT_WARNING:
3080 ssl3_send_alert(s, SSL3_AL_WARNING, al);
3088 int ssl_check_serverhello_tlsext(SSL *s)
3090 int ret=SSL_TLSEXT_ERR_NOACK;
3091 int al = SSL_AD_UNRECOGNIZED_NAME;
3093 #ifndef OPENSSL_NO_EC
3094 /* If we are client and using an elliptic curve cryptography cipher
3095 * suite, then if server returns an EC point formats lists extension
3096 * it must contain uncompressed.
3098 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3099 unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3100 if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) &&
3101 (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) &&
3102 ((alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) || (alg_a & SSL_aECDSA)))
3104 /* we are using an ECC cipher */
3106 unsigned char *list;
3107 int found_uncompressed = 0;
3108 list = s->session->tlsext_ecpointformatlist;
3109 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
3111 if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
3113 found_uncompressed = 1;
3117 if (!found_uncompressed)
3119 SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
3123 ret = SSL_TLSEXT_ERR_OK;
3124 #endif /* OPENSSL_NO_EC */
3126 if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
3127 ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
3128 else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)
3129 ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
3131 #ifdef TLSEXT_TYPE_opaque_prf_input
3132 if (s->s3->server_opaque_prf_input_len > 0)
3134 /* This case may indicate that we, as a client, want to insist on using opaque PRF inputs.
3135 * So first verify that we really have a value from the server too. */
3137 if (s->s3->server_opaque_prf_input == NULL)
3139 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3140 al = SSL_AD_HANDSHAKE_FAILURE;
3143 /* Anytime the server *has* sent an opaque PRF input, we need to check
3144 * that we have a client opaque PRF input of the same size. */
3145 if (s->s3->client_opaque_prf_input == NULL ||
3146 s->s3->client_opaque_prf_input_len != s->s3->server_opaque_prf_input_len)
3148 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3149 al = SSL_AD_ILLEGAL_PARAMETER;
3154 /* If we've requested certificate status and we wont get one
3157 if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
3158 && s->ctx && s->ctx->tlsext_status_cb)
3161 /* Set resp to NULL, resplen to -1 so callback knows
3162 * there is no response.
3164 if (s->tlsext_ocsp_resp)
3166 OPENSSL_free(s->tlsext_ocsp_resp);
3167 s->tlsext_ocsp_resp = NULL;
3169 s->tlsext_ocsp_resplen = -1;
3170 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
3173 al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
3174 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3178 al = SSL_AD_INTERNAL_ERROR;
3179 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3185 case SSL_TLSEXT_ERR_ALERT_FATAL:
3186 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3189 case SSL_TLSEXT_ERR_ALERT_WARNING:
3190 ssl3_send_alert(s,SSL3_AL_WARNING,al);
3193 case SSL_TLSEXT_ERR_NOACK:
3194 s->servername_done=0;
3200 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n)
3203 if (s->version < SSL3_VERSION)
3205 if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0)
3207 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3211 if (ssl_check_serverhello_tlsext(s) <= 0)
3213 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT,SSL_R_SERVERHELLO_TLSEXT);
3219 /* Since the server cache lookup is done early on in the processing of the
3220 * ClientHello, and other operations depend on the result, we need to handle
3221 * any TLS session ticket extension at the same time.
3223 * session_id: points at the session ID in the ClientHello. This code will
3224 * read past the end of this in order to parse out the session ticket
3225 * extension, if any.
3226 * len: the length of the session ID.
3227 * limit: a pointer to the first byte after the ClientHello.
3228 * ret: (output) on return, if a ticket was decrypted, then this is set to
3229 * point to the resulting session.
3231 * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
3232 * ciphersuite, in which case we have no use for session tickets and one will
3233 * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
3236 * -1: fatal error, either from parsing or decrypting the ticket.
3237 * 0: no ticket was found (or was ignored, based on settings).
3238 * 1: a zero length extension was found, indicating that the client supports
3239 * session tickets but doesn't currently have one to offer.
3240 * 2: either s->tls_session_secret_cb was set, or a ticket was offered but
3241 * couldn't be decrypted because of a non-fatal error.
3242 * 3: a ticket was successfully decrypted and *ret was set.
3245 * Sets s->tlsext_ticket_expected to 1 if the server will have to issue
3246 * a new session ticket to the client because the client indicated support
3247 * (and s->tls_session_secret_cb is NULL) but the client either doesn't have
3248 * a session ticket or we couldn't use the one it gave us, or if
3249 * s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
3250 * Otherwise, s->tlsext_ticket_expected is set to 0.
3252 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
3253 const unsigned char *limit, SSL_SESSION **ret)
3255 /* Point after session ID in client hello */
3256 const unsigned char *p = session_id + len;
3260 s->tlsext_ticket_expected = 0;
3262 /* If tickets disabled behave as if no ticket present
3263 * to permit stateful resumption.
3265 if (SSL_get_options(s) & SSL_OP_NO_TICKET)
3267 if ((s->version <= SSL3_VERSION) || !limit)
3271 /* Skip past DTLS cookie */
3279 /* Skip past cipher list */
3284 /* Skip past compression algorithm list */
3289 /* Now at start of extensions */
3290 if ((p + 2) >= limit)
3293 while ((p + 4) <= limit)
3295 unsigned short type, size;
3298 if (p + size > limit)
3300 if (type == TLSEXT_TYPE_session_ticket)
3305 /* The client will accept a ticket but doesn't
3306 * currently have one. */
3307 s->tlsext_ticket_expected = 1;
3310 if (s->tls_session_secret_cb)
3312 /* Indicate that the ticket couldn't be
3313 * decrypted rather than generating the session
3314 * from ticket now, trigger abbreviated
3315 * handshake based on external mechanism to
3316 * calculate the master secret later. */
3319 r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3322 case 2: /* ticket couldn't be decrypted */
3323 s->tlsext_ticket_expected = 1;
3325 case 3: /* ticket was decrypted */
3327 case 4: /* ticket decrypted but need to renew */
3328 s->tlsext_ticket_expected = 1;
3330 default: /* fatal error */
3339 /* tls_decrypt_ticket attempts to decrypt a session ticket.
3341 * etick: points to the body of the session ticket extension.
3342 * eticklen: the length of the session tickets extenion.
3343 * sess_id: points at the session ID.
3344 * sesslen: the length of the session ID.
3345 * psess: (output) on return, if a ticket was decrypted, then this is set to
3346 * point to the resulting session.
3349 * -1: fatal error, either from parsing or decrypting the ticket.
3350 * 2: the ticket couldn't be decrypted.
3351 * 3: a ticket was successfully decrypted and *psess was set.
3352 * 4: same as 3, but the ticket needs to be renewed.
3354 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
3355 const unsigned char *sess_id, int sesslen,
3356 SSL_SESSION **psess)
3359 unsigned char *sdec;
3360 const unsigned char *p;
3361 int slen, mlen, renew_ticket = 0;
3362 unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3365 SSL_CTX *tctx = s->initial_ctx;
3366 /* Need at least keyname + iv + some encrypted data */
3369 /* Initialize session ticket encryption and HMAC contexts */
3370 HMAC_CTX_init(&hctx);
3371 EVP_CIPHER_CTX_init(&ctx);
3372 if (tctx->tlsext_ticket_key_cb)
3374 unsigned char *nctick = (unsigned char *)etick;
3375 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3386 /* Check key name matches */
3387 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3389 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3390 tlsext_tick_md(), NULL);
3391 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3392 tctx->tlsext_tick_aes_key, etick + 16);
3394 /* Attempt to process session ticket, first conduct sanity and
3395 * integrity checks on ticket.
3397 mlen = HMAC_size(&hctx);
3400 EVP_CIPHER_CTX_cleanup(&ctx);
3404 /* Check HMAC of encrypted ticket */
3405 HMAC_Update(&hctx, etick, eticklen);
3406 HMAC_Final(&hctx, tick_hmac, NULL);
3407 HMAC_CTX_cleanup(&hctx);
3408 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
3410 /* Attempt to decrypt session data */
3411 /* Move p after IV to start of encrypted ticket, update length */
3412 p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3413 eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3414 sdec = OPENSSL_malloc(eticklen);
3417 EVP_CIPHER_CTX_cleanup(&ctx);
3420 EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3421 if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
3424 EVP_CIPHER_CTX_cleanup(&ctx);
3427 sess = d2i_SSL_SESSION(NULL, &p, slen);
3431 /* The session ID, if non-empty, is used by some clients to
3432 * detect that the ticket has been accepted. So we copy it to
3433 * the session structure. If it is empty set length to zero
3434 * as required by standard.
3437 memcpy(sess->session_id, sess_id, sesslen);
3438 sess->session_id_length = sesslen;
3446 /* For session parse failure, indicate that we need to send a new
3451 /* Tables to translate from NIDs to TLS v1.2 ids */
3459 static tls12_lookup tls12_md[] = {
3460 {NID_md5, TLSEXT_hash_md5},
3461 {NID_sha1, TLSEXT_hash_sha1},
3462 {NID_sha224, TLSEXT_hash_sha224},
3463 {NID_sha256, TLSEXT_hash_sha256},
3464 {NID_sha384, TLSEXT_hash_sha384},
3465 {NID_sha512, TLSEXT_hash_sha512}
3468 static tls12_lookup tls12_sig[] = {
3469 {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3470 {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3471 {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3474 static int tls12_find_id(int nid, tls12_lookup *table, size_t tlen)
3477 for (i = 0; i < tlen; i++)
3479 if (table[i].nid == nid)
3485 static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
3488 for (i = 0; i < tlen; i++)
3490 if ((table[i].id) == id)
3491 return table[i].nid;
3496 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
3501 md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3502 sizeof(tls12_md)/sizeof(tls12_lookup));
3505 sig_id = tls12_get_sigid(pk);
3508 p[0] = (unsigned char)md_id;
3509 p[1] = (unsigned char)sig_id;
3513 int tls12_get_sigid(const EVP_PKEY *pk)
3515 return tls12_find_id(pk->type, tls12_sig,
3516 sizeof(tls12_sig)/sizeof(tls12_lookup));
3519 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3523 #ifndef OPENSSL_NO_MD5
3524 case TLSEXT_hash_md5:
3531 #ifndef OPENSSL_NO_SHA
3532 case TLSEXT_hash_sha1:
3535 #ifndef OPENSSL_NO_SHA256
3536 case TLSEXT_hash_sha224:
3537 return EVP_sha224();
3539 case TLSEXT_hash_sha256:
3540 return EVP_sha256();
3542 #ifndef OPENSSL_NO_SHA512
3543 case TLSEXT_hash_sha384:
3544 return EVP_sha384();
3546 case TLSEXT_hash_sha512:
3547 return EVP_sha512();
3555 static int tls12_get_pkey_idx(unsigned char sig_alg)
3559 #ifndef OPENSSL_NO_RSA
3560 case TLSEXT_signature_rsa:
3561 return SSL_PKEY_RSA_SIGN;
3563 #ifndef OPENSSL_NO_DSA
3564 case TLSEXT_signature_dsa:
3565 return SSL_PKEY_DSA_SIGN;
3567 #ifndef OPENSSL_NO_ECDSA
3568 case TLSEXT_signature_ecdsa:
3569 return SSL_PKEY_ECC;
3575 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3576 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3577 int *psignhash_nid, const unsigned char *data)
3579 int sign_nid = 0, hash_nid = 0;
3580 if (!phash_nid && !psign_nid && !psignhash_nid)
3582 if (phash_nid || psignhash_nid)
3584 hash_nid = tls12_find_nid(data[0], tls12_md,
3585 sizeof(tls12_md)/sizeof(tls12_lookup));
3587 *phash_nid = hash_nid;
3589 if (psign_nid || psignhash_nid)
3591 sign_nid = tls12_find_nid(data[1], tls12_sig,
3592 sizeof(tls12_sig)/sizeof(tls12_lookup));
3594 *psign_nid = sign_nid;
3598 if (sign_nid && hash_nid)
3599 OBJ_find_sigid_by_algs(psignhash_nid,
3600 hash_nid, sign_nid);
3602 *psignhash_nid = NID_undef;
3605 /* Given preference and allowed sigalgs set shared sigalgs */
3606 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
3607 const unsigned char *pref, size_t preflen,
3608 const unsigned char *allow, size_t allowlen)
3610 const unsigned char *ptmp, *atmp;
3611 size_t i, j, nmatch = 0;
3612 for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
3614 /* Skip disabled hashes or signature algorithms */
3615 if (tls12_get_hash(ptmp[0]) == NULL)
3617 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3619 for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
3621 if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
3626 shsig->rhash = ptmp[0];
3627 shsig->rsign = ptmp[1];
3628 tls1_lookup_sigalg(&shsig->hash_nid,
3630 &shsig->signandhash_nid,
3641 /* Set shared signature algorithms for SSL structures */
3642 static int tls1_set_shared_sigalgs(SSL *s)
3644 const unsigned char *pref, *allow, *conf;
3645 size_t preflen, allowlen, conflen;
3647 TLS_SIGALGS *salgs = NULL;
3649 unsigned int is_suiteb = tls1_suiteb(s);
3650 /* If client use client signature algorithms if not NULL */
3651 if (!s->server && c->client_sigalgs && !is_suiteb)
3653 conf = c->client_sigalgs;
3654 conflen = c->client_sigalgslen;
3656 else if (c->conf_sigalgs && !is_suiteb)
3658 conf = c->conf_sigalgs;
3659 conflen = c->conf_sigalgslen;
3662 conflen = tls12_get_psigalgs(s, &conf);
3663 if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb)
3667 allow = c->peer_sigalgs;
3668 allowlen = c->peer_sigalgslen;
3674 pref = c->peer_sigalgs;
3675 preflen = c->peer_sigalgslen;
3677 nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
3680 salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3683 nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
3684 c->shared_sigalgs = salgs;
3685 c->shared_sigalgslen = nmatch;
3690 /* Set preferred digest for each key type */
3692 int tls1_process_sigalgs(SSL *s, const unsigned char *data, int dsize)
3698 TLS_SIGALGS *sigptr;
3699 /* Extension ignored for inappropriate versions */
3700 if (!SSL_USE_SIGALGS(s))
3702 /* Should never happen */
3706 c->peer_sigalgs = OPENSSL_malloc(dsize);
3707 if (!c->peer_sigalgs)
3709 c->peer_sigalgslen = dsize;
3710 memcpy(c->peer_sigalgs, data, dsize);
3712 tls1_set_shared_sigalgs(s);
3714 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3715 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
3717 /* Use first set signature preference to force message
3718 * digest, ignoring any peer preferences.
3720 const unsigned char *sigs = NULL;
3722 sigs = c->conf_sigalgs;
3724 sigs = c->client_sigalgs;
3727 idx = tls12_get_pkey_idx(sigs[1]);
3728 md = tls12_get_hash(sigs[0]);
3729 c->pkeys[idx].digest = md;
3730 c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3731 if (idx == SSL_PKEY_RSA_SIGN)
3733 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3734 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3740 for (i = 0, sigptr = c->shared_sigalgs;
3741 i < c->shared_sigalgslen; i++, sigptr++)
3743 idx = tls12_get_pkey_idx(sigptr->rsign);
3744 if (idx > 0 && c->pkeys[idx].digest == NULL)
3746 md = tls12_get_hash(sigptr->rhash);
3747 c->pkeys[idx].digest = md;
3748 c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3749 if (idx == SSL_PKEY_RSA_SIGN)
3751 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3752 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3757 /* In strict mode leave unset digests as NULL to indicate we can't
3758 * use the certificate for signing.
3760 if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
3762 /* Set any remaining keys to default values. NOTE: if alg is
3763 * not supported it stays as NULL.
3765 #ifndef OPENSSL_NO_DSA
3766 if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3767 c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3769 #ifndef OPENSSL_NO_RSA
3770 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
3772 c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3773 c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3776 #ifndef OPENSSL_NO_ECDSA
3777 if (!c->pkeys[SSL_PKEY_ECC].digest)
3778 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3785 int SSL_get_sigalgs(SSL *s, int idx,
3786 int *psign, int *phash, int *psignhash,
3787 unsigned char *rsig, unsigned char *rhash)
3789 const unsigned char *psig = s->cert->peer_sigalgs;
3795 if (idx >= (int)s->cert->peer_sigalgslen)
3802 tls1_lookup_sigalg(phash, psign, psignhash, psig);
3804 return s->cert->peer_sigalgslen / 2;
3807 int SSL_get_shared_sigalgs(SSL *s, int idx,
3808 int *psign, int *phash, int *psignhash,
3809 unsigned char *rsig, unsigned char *rhash)
3811 TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3812 if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3816 *phash = shsigalgs->hash_nid;
3818 *psign = shsigalgs->sign_nid;
3820 *psignhash = shsigalgs->signandhash_nid;
3822 *rsig = shsigalgs->rsign;
3824 *rhash = shsigalgs->rhash;
3825 return s->cert->shared_sigalgslen;
3829 #ifndef OPENSSL_NO_HEARTBEATS
3831 tls1_process_heartbeat(SSL *s)
3833 unsigned char *p = &s->s3->rrec.data[0], *pl;
3834 unsigned short hbtype;
3835 unsigned int payload;
3836 unsigned int padding = 16; /* Use minimum padding */
3838 /* Read type and payload length first */
3843 if (s->msg_callback)
3844 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3845 &s->s3->rrec.data[0], s->s3->rrec.length,
3846 s, s->msg_callback_arg);
3848 if (hbtype == TLS1_HB_REQUEST)
3850 unsigned char *buffer, *bp;
3853 /* Allocate memory for the response, size is 1 bytes
3854 * message type, plus 2 bytes payload length, plus
3855 * payload, plus padding
3857 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
3860 /* Enter response type, length and copy payload */
3861 *bp++ = TLS1_HB_RESPONSE;
3863 memcpy(bp, pl, payload);
3865 /* Random padding */
3866 RAND_pseudo_bytes(bp, padding);
3868 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
3870 if (r >= 0 && s->msg_callback)
3871 s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3872 buffer, 3 + payload + padding,
3873 s, s->msg_callback_arg);
3875 OPENSSL_free(buffer);
3880 else if (hbtype == TLS1_HB_RESPONSE)
3884 /* We only send sequence numbers (2 bytes unsigned int),
3885 * and 16 random bytes, so we just try to read the
3886 * sequence number */
3889 if (payload == 18 && seq == s->tlsext_hb_seq)
3892 s->tlsext_hb_pending = 0;
3900 tls1_heartbeat(SSL *s)
3902 unsigned char *buf, *p;
3904 unsigned int payload = 18; /* Sequence number + random bytes */
3905 unsigned int padding = 16; /* Use minimum padding */
3907 /* Only send if peer supports and accepts HB requests... */
3908 if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
3909 s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
3911 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
3915 /* ...and there is none in flight yet... */
3916 if (s->tlsext_hb_pending)
3918 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
3922 /* ...and no handshake in progress. */
3923 if (SSL_in_init(s) || s->in_handshake)
3925 SSLerr(SSL_F_TLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
3929 /* Check if padding is too long, payload and padding
3930 * must not exceed 2^14 - 3 = 16381 bytes in total.
3932 OPENSSL_assert(payload + padding <= 16381);
3934 /* Create HeartBeat message, we just use a sequence number
3935 * as payload to distuingish different messages and add
3936 * some random stuff.
3937 * - Message Type, 1 byte
3938 * - Payload Length, 2 bytes (unsigned int)
3939 * - Payload, the sequence number (2 bytes uint)
3940 * - Payload, random bytes (16 bytes uint)
3943 buf = OPENSSL_malloc(1 + 2 + payload + padding);
3946 *p++ = TLS1_HB_REQUEST;
3947 /* Payload length (18 bytes here) */
3949 /* Sequence number */
3950 s2n(s->tlsext_hb_seq, p);
3951 /* 16 random bytes */
3952 RAND_pseudo_bytes(p, 16);
3954 /* Random padding */
3955 RAND_pseudo_bytes(p, padding);
3957 ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
3960 if (s->msg_callback)
3961 s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3962 buf, 3 + payload + padding,
3963 s, s->msg_callback_arg);
3965 s->tlsext_hb_pending = 1;
3974 #define MAX_SIGALGLEN (TLSEXT_hash_num * TLSEXT_signature_num * 2)
3979 int sigalgs[MAX_SIGALGLEN];
3982 static int sig_cb(const char *elem, int len, void *arg)
3984 sig_cb_st *sarg = arg;
3987 int sig_alg, hash_alg;
3988 if (sarg->sigalgcnt == MAX_SIGALGLEN)
3990 if (len > (int)(sizeof(etmp) - 1))
3992 memcpy(etmp, elem, len);
3994 p = strchr(etmp, '+');
4002 if (!strcmp(etmp, "RSA"))
4003 sig_alg = EVP_PKEY_RSA;
4004 else if (!strcmp(etmp, "DSA"))
4005 sig_alg = EVP_PKEY_DSA;
4006 else if (!strcmp(etmp, "ECDSA"))
4007 sig_alg = EVP_PKEY_EC;
4010 hash_alg = OBJ_sn2nid(p);
4011 if (hash_alg == NID_undef)
4012 hash_alg = OBJ_ln2nid(p);
4013 if (hash_alg == NID_undef)
4016 for (i = 0; i < sarg->sigalgcnt; i+=2)
4018 if (sarg->sigalgs[i] == sig_alg
4019 && sarg->sigalgs[i + 1] == hash_alg)
4022 sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
4023 sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
4027 /* Set suppored signature algorithms based on a colon separated list
4028 * of the form sig+hash e.g. RSA+SHA512:DSA+SHA512 */
4029 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
4033 if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
4037 return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
4040 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
4042 unsigned char *sigalgs, *sptr;
4047 sigalgs = OPENSSL_malloc(salglen);
4048 if (sigalgs == NULL)
4050 for (i = 0, sptr = sigalgs; i < salglen; i+=2)
4052 rhash = tls12_find_id(*psig_nids++, tls12_md,
4053 sizeof(tls12_md)/sizeof(tls12_lookup));
4054 rsign = tls12_find_id(*psig_nids++, tls12_sig,
4055 sizeof(tls12_sig)/sizeof(tls12_lookup));
4057 if (rhash == -1 || rsign == -1)
4065 if (c->client_sigalgs)
4066 OPENSSL_free(c->client_sigalgs);
4067 c->client_sigalgs = sigalgs;
4068 c->client_sigalgslen = salglen;
4072 if (c->conf_sigalgs)
4073 OPENSSL_free(c->conf_sigalgs);
4074 c->conf_sigalgs = sigalgs;
4075 c->conf_sigalgslen = salglen;
4081 OPENSSL_free(sigalgs);
4085 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
4089 if (default_nid == -1)
4091 sig_nid = X509_get_signature_nid(x);
4093 return sig_nid == default_nid ? 1 : 0;
4094 for (i = 0; i < c->shared_sigalgslen; i++)
4095 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
4099 /* Check to see if a certificate issuer name matches list of CA names */
4100 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
4104 nm = X509_get_issuer_name(x);
4105 for (i = 0; i < sk_X509_NAME_num(names); i++)
4107 if(!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
4113 /* Check certificate chain is consistent with TLS extensions and is
4114 * usable by server. This servers two purposes: it allows users to
4115 * check chains before passing them to the server and it allows the
4116 * server to check chains before attempting to use them.
4119 /* Flags which need to be set for a certificate when stict mode not set */
4121 #define CERT_PKEY_VALID_FLAGS \
4122 (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
4123 /* Strict mode flags */
4124 #define CERT_PKEY_STRICT_FLAGS \
4125 (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
4126 | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
4128 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
4133 int check_flags = 0, strict_mode;
4134 CERT_PKEY *cpk = NULL;
4136 unsigned int suiteb_flags = tls1_suiteb(s);
4137 /* idx == -1 means checking server chains */
4140 /* idx == -2 means checking client certificate chains */
4144 idx = cpk - c->pkeys;
4147 cpk = c->pkeys + idx;
4149 pk = cpk->privatekey;
4151 strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
4152 /* If no cert or key, forget it */
4155 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
4156 /* Allow any certificate to pass test */
4157 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
4159 rv = CERT_PKEY_STRICT_FLAGS|CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_VALID|CERT_PKEY_SIGN;
4160 cpk->valid_flags = rv;
4169 idx = ssl_cert_type(x, pk);
4172 cpk = c->pkeys + idx;
4173 if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
4174 check_flags = CERT_PKEY_STRICT_FLAGS;
4176 check_flags = CERT_PKEY_VALID_FLAGS;
4184 check_flags |= CERT_PKEY_SUITEB;
4185 ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
4186 if (ok != X509_V_OK)
4189 rv |= CERT_PKEY_SUITEB;
4195 /* Check all signature algorithms are consistent with
4196 * signature algorithms extension if TLS 1.2 or later
4199 if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode)
4202 unsigned char rsign = 0;
4203 if (c->peer_sigalgs)
4205 /* If no sigalgs extension use defaults from RFC5246 */
4210 case SSL_PKEY_RSA_ENC:
4211 case SSL_PKEY_RSA_SIGN:
4212 case SSL_PKEY_DH_RSA:
4213 rsign = TLSEXT_signature_rsa;
4214 default_nid = NID_sha1WithRSAEncryption;
4217 case SSL_PKEY_DSA_SIGN:
4218 case SSL_PKEY_DH_DSA:
4219 rsign = TLSEXT_signature_dsa;
4220 default_nid = NID_dsaWithSHA1;
4224 rsign = TLSEXT_signature_ecdsa;
4225 default_nid = NID_ecdsa_with_SHA1;
4233 /* If peer sent no signature algorithms extension and we
4234 * have set preferred signature algorithms check we support
4237 if (default_nid > 0 && c->conf_sigalgs)
4240 const unsigned char *p = c->conf_sigalgs;
4241 for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2)
4243 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4246 if (j == c->conf_sigalgslen)
4254 /* Check signature algorithm of each cert in chain */
4255 if (!tls1_check_sig_alg(c, x, default_nid))
4257 if (!check_flags) goto end;
4260 rv |= CERT_PKEY_EE_SIGNATURE;
4261 rv |= CERT_PKEY_CA_SIGNATURE;
4262 for (i = 0; i < sk_X509_num(chain); i++)
4264 if (!tls1_check_sig_alg(c, sk_X509_value(chain, i),
4269 rv &= ~CERT_PKEY_CA_SIGNATURE;
4277 /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4278 else if(check_flags)
4279 rv |= CERT_PKEY_EE_SIGNATURE|CERT_PKEY_CA_SIGNATURE;
4281 /* Check cert parameters are consistent */
4282 if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4283 rv |= CERT_PKEY_EE_PARAM;
4284 else if (!check_flags)
4287 rv |= CERT_PKEY_CA_PARAM;
4288 /* In strict mode check rest of chain too */
4289 else if (strict_mode)
4291 rv |= CERT_PKEY_CA_PARAM;
4292 for (i = 0; i < sk_X509_num(chain); i++)
4294 X509 *ca = sk_X509_value(chain, i);
4295 if (!tls1_check_cert_param(s, ca, 0))
4299 rv &= ~CERT_PKEY_CA_PARAM;
4307 if (!s->server && strict_mode)
4309 STACK_OF(X509_NAME) *ca_dn;
4314 check_type = TLS_CT_RSA_SIGN;
4317 check_type = TLS_CT_DSS_SIGN;
4320 check_type = TLS_CT_ECDSA_SIGN;
4325 int cert_type = X509_certificate_type(x, pk);
4326 if (cert_type & EVP_PKS_RSA)
4327 check_type = TLS_CT_RSA_FIXED_DH;
4328 if (cert_type & EVP_PKS_DSA)
4329 check_type = TLS_CT_DSS_FIXED_DH;
4334 const unsigned char *ctypes;
4339 ctypelen = (int)c->ctype_num;
4343 ctypes = (unsigned char *)s->s3->tmp.ctype;
4344 ctypelen = s->s3->tmp.ctype_num;
4346 for (i = 0; i < ctypelen; i++)
4348 if (ctypes[i] == check_type)
4350 rv |= CERT_PKEY_CERT_TYPE;
4354 if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4358 rv |= CERT_PKEY_CERT_TYPE;
4361 ca_dn = s->s3->tmp.ca_names;
4363 if (!sk_X509_NAME_num(ca_dn))
4364 rv |= CERT_PKEY_ISSUER_NAME;
4366 if (!(rv & CERT_PKEY_ISSUER_NAME))
4368 if (ssl_check_ca_name(ca_dn, x))
4369 rv |= CERT_PKEY_ISSUER_NAME;
4371 if (!(rv & CERT_PKEY_ISSUER_NAME))
4373 for (i = 0; i < sk_X509_num(chain); i++)
4375 X509 *xtmp = sk_X509_value(chain, i);
4376 if (ssl_check_ca_name(ca_dn, xtmp))
4378 rv |= CERT_PKEY_ISSUER_NAME;
4383 if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4387 rv |= CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE;
4389 if (!check_flags || (rv & check_flags) == check_flags)
4390 rv |= CERT_PKEY_VALID;
4394 if (TLS1_get_version(s) >= TLS1_2_VERSION)
4396 if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4397 rv |= CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_SIGN;
4398 else if (cpk->digest)
4399 rv |= CERT_PKEY_SIGN;
4402 rv |= CERT_PKEY_SIGN|CERT_PKEY_EXPLICIT_SIGN;
4404 /* When checking a CERT_PKEY structure all flags are irrelevant
4405 * if the chain is invalid.
4409 if (rv & CERT_PKEY_VALID)
4410 cpk->valid_flags = rv;
4413 /* Preserve explicit sign flag, clear rest */
4414 cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4421 /* Set validity of certificates in an SSL structure */
4422 void tls1_set_cert_validity(SSL *s)
4424 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4425 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4426 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4427 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4428 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4429 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4431 /* User level utiity function to check a chain is suitable */
4432 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4434 return tls1_check_chain(s, x, pk, chain, -1);
4439 /* RFC6962 Signed Certificate Timestamp List X.509 extension parser */
4440 static int i2r_sctlist(X509V3_EXT_METHOD *method, ASN1_OCTET_STRING *oct,
4441 BIO *out, int indent)
4443 BN_ULLONG timestamp;
4445 time_t unix_epoch = 0;
4446 unsigned char* data = oct->data;
4448 unsigned short listlen, sctlen = 0, fieldlen;
4451 if (oct->length < 2)
4454 if (listlen != oct->length - 2)
4464 if ((sctlen < 1) || (sctlen > listlen))
4468 BIO_printf(out, "%*sSigned Certificate Timestamp:", indent,
4471 if (*data == 0) /* SCT v1 */
4473 /* Fixed-length header:
4475 * (1 byte) Version sct_version;
4476 * (32 bytes) LogID id;
4477 * (8 bytes) uint64 timestamp;
4478 * (2 bytes + ?) CtExtensions extensions;
4484 BIO_printf(out, "\n%*sVersion : v1(0)", indent + 4,
4487 BIO_printf(out, "\n%*sLog ID : ", indent + 4, "");
4488 BIO_hex_string(out, indent + 16, 16, data + 1, 32);
4491 n2l8(data, timestamp);
4492 OPENSSL_gmtime(&unix_epoch, &tm1);
4493 OPENSSL_gmtime_adj(&tm1, timestamp / 86400000,
4494 (timestamp % 86400000) / 1000);
4495 strftime(month, 4, "%b", &tm1);
4496 BIO_printf(out, "\n%*sTimestamp : ", indent + 4, "");
4497 BIO_printf(out, "%s %2d %02d:%02d:%02d.%03u %d UTC",
4498 month, tm1.tm_mday, tm1.tm_hour,
4499 tm1.tm_min, tm1.tm_sec,
4500 (unsigned int)(timestamp % 1000),
4501 tm1.tm_year + 1900);
4503 n2s(data, fieldlen);
4504 if (sctlen < fieldlen)
4507 BIO_printf(out, "\n%*sExtensions: ", indent + 4, "");
4509 BIO_printf(out, "none");
4511 BIO_hex_string(out, indent + 16, 16, data,
4515 /* digitally-signed struct header:
4516 * (1 byte) Hash algorithm
4517 * (1 byte) Signature algorithm
4518 * (2 bytes + ?) Signature
4524 tls1_lookup_sigalg(NULL, NULL, &signhash_nid, data);
4526 n2s(data, fieldlen);
4527 if (sctlen != fieldlen)
4529 BIO_printf(out, "\n%*sSignature : ", indent + 4, "");
4530 BIO_printf(out, "%s", OBJ_nid2ln(signhash_nid));
4531 BIO_printf(out, "\n%*s ", indent + 4, "");
4532 BIO_hex_string(out, indent + 16, 16, data, fieldlen);
4533 if (listlen > 0) BIO_printf(out, "\n");
4541 static X509V3_EXT_METHOD ext_method_ct_precert_scts =
4543 NID_ct_precert_scts, 0, ASN1_ITEM_ref(ASN1_OCTET_STRING),
4544 0, 0, 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2R)i2r_sctlist, NULL, NULL
4547 static X509V3_EXT_METHOD ext_method_ct_cert_scts =
4549 NID_ct_cert_scts, 0, ASN1_ITEM_ref(ASN1_OCTET_STRING),
4550 0, 0, 0, 0, 0, 0, 0, 0, (X509V3_EXT_I2R)i2r_sctlist, NULL, NULL
4553 int X509V3_EXT_add_rfc6962(void)
4555 if (!X509V3_EXT_add(&ext_method_ct_precert_scts))
4557 if (!X509V3_EXT_add(&ext_method_ct_cert_scts))