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).
113 #include <openssl/objects.h>
114 #include <openssl/evp.h>
115 #include <openssl/hmac.h>
116 #include <openssl/ocsp.h>
117 #include <openssl/rand.h>
118 #ifndef OPENSSL_NO_DH
119 # include <openssl/dh.h>
120 # include <openssl/bn.h>
122 #include "ssl_locl.h"
124 const char tls1_version_str[] = "TLSv1" OPENSSL_VERSION_PTEXT;
126 #ifndef OPENSSL_NO_TLSEXT
127 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
128 const unsigned char *sess_id, int sesslen,
129 SSL_SESSION **psess);
130 static int ssl_check_clienthello_tlsext_early(SSL *s);
131 int ssl_check_serverhello_tlsext(SSL *s);
134 SSL3_ENC_METHOD const TLSv1_enc_data = {
137 tls1_setup_key_block,
138 tls1_generate_master_secret,
139 tls1_change_cipher_state,
140 tls1_final_finish_mac,
141 TLS1_FINISH_MAC_LENGTH,
142 tls1_cert_verify_mac,
143 TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
144 TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
146 tls1_export_keying_material,
148 SSL3_HM_HEADER_LENGTH,
149 ssl3_set_handshake_header,
153 SSL3_ENC_METHOD const TLSv1_1_enc_data = {
156 tls1_setup_key_block,
157 tls1_generate_master_secret,
158 tls1_change_cipher_state,
159 tls1_final_finish_mac,
160 TLS1_FINISH_MAC_LENGTH,
161 tls1_cert_verify_mac,
162 TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
163 TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
165 tls1_export_keying_material,
166 SSL_ENC_FLAG_EXPLICIT_IV,
167 SSL3_HM_HEADER_LENGTH,
168 ssl3_set_handshake_header,
172 SSL3_ENC_METHOD const TLSv1_2_enc_data = {
175 tls1_setup_key_block,
176 tls1_generate_master_secret,
177 tls1_change_cipher_state,
178 tls1_final_finish_mac,
179 TLS1_FINISH_MAC_LENGTH,
180 tls1_cert_verify_mac,
181 TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
182 TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
184 tls1_export_keying_material,
185 SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF
186 | SSL_ENC_FLAG_TLS1_2_CIPHERS,
187 SSL3_HM_HEADER_LENGTH,
188 ssl3_set_handshake_header,
192 long tls1_default_timeout(void)
195 * 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for
196 * http, the cache would over fill
198 return (60 * 60 * 2);
205 s->method->ssl_clear(s);
209 void tls1_free(SSL *s)
211 #ifndef OPENSSL_NO_TLSEXT
212 if (s->tlsext_session_ticket) {
213 OPENSSL_free(s->tlsext_session_ticket);
215 #endif /* OPENSSL_NO_TLSEXT */
219 void tls1_clear(SSL *s)
222 s->version = s->method->version;
225 #ifndef OPENSSL_NO_EC
228 int nid; /* Curve NID */
229 int secbits; /* Bits of security (from SP800-57) */
230 unsigned int flags; /* Flags: currently just field type */
233 # define TLS_CURVE_CHAR2 0x1
234 # define TLS_CURVE_PRIME 0x0
236 static const tls_curve_info nid_list[] = {
237 {NID_sect163k1, 80, TLS_CURVE_CHAR2}, /* sect163k1 (1) */
238 {NID_sect163r1, 80, TLS_CURVE_CHAR2}, /* sect163r1 (2) */
239 {NID_sect163r2, 80, TLS_CURVE_CHAR2}, /* sect163r2 (3) */
240 {NID_sect193r1, 80, TLS_CURVE_CHAR2}, /* sect193r1 (4) */
241 {NID_sect193r2, 80, TLS_CURVE_CHAR2}, /* sect193r2 (5) */
242 {NID_sect233k1, 112, TLS_CURVE_CHAR2}, /* sect233k1 (6) */
243 {NID_sect233r1, 112, TLS_CURVE_CHAR2}, /* sect233r1 (7) */
244 {NID_sect239k1, 112, TLS_CURVE_CHAR2}, /* sect239k1 (8) */
245 {NID_sect283k1, 128, TLS_CURVE_CHAR2}, /* sect283k1 (9) */
246 {NID_sect283r1, 128, TLS_CURVE_CHAR2}, /* sect283r1 (10) */
247 {NID_sect409k1, 192, TLS_CURVE_CHAR2}, /* sect409k1 (11) */
248 {NID_sect409r1, 192, TLS_CURVE_CHAR2}, /* sect409r1 (12) */
249 {NID_sect571k1, 256, TLS_CURVE_CHAR2}, /* sect571k1 (13) */
250 {NID_sect571r1, 256, TLS_CURVE_CHAR2}, /* sect571r1 (14) */
251 {NID_secp160k1, 80, TLS_CURVE_PRIME}, /* secp160k1 (15) */
252 {NID_secp160r1, 80, TLS_CURVE_PRIME}, /* secp160r1 (16) */
253 {NID_secp160r2, 80, TLS_CURVE_PRIME}, /* secp160r2 (17) */
254 {NID_secp192k1, 80, TLS_CURVE_PRIME}, /* secp192k1 (18) */
255 {NID_X9_62_prime192v1, 80, TLS_CURVE_PRIME}, /* secp192r1 (19) */
256 {NID_secp224k1, 112, TLS_CURVE_PRIME}, /* secp224k1 (20) */
257 {NID_secp224r1, 112, TLS_CURVE_PRIME}, /* secp224r1 (21) */
258 {NID_secp256k1, 128, TLS_CURVE_PRIME}, /* secp256k1 (22) */
259 {NID_X9_62_prime256v1, 128, TLS_CURVE_PRIME}, /* secp256r1 (23) */
260 {NID_secp384r1, 192, TLS_CURVE_PRIME}, /* secp384r1 (24) */
261 {NID_secp521r1, 256, TLS_CURVE_PRIME}, /* secp521r1 (25) */
262 {NID_brainpoolP256r1, 128, TLS_CURVE_PRIME}, /* brainpoolP256r1 (26) */
263 {NID_brainpoolP384r1, 192, TLS_CURVE_PRIME}, /* brainpoolP384r1 (27) */
264 {NID_brainpoolP512r1, 256, TLS_CURVE_PRIME}, /* brainpool512r1 (28) */
267 static const unsigned char ecformats_default[] = {
268 TLSEXT_ECPOINTFORMAT_uncompressed,
269 TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
270 TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
273 static const unsigned char eccurves_default[] = {
274 0, 14, /* sect571r1 (14) */
275 0, 13, /* sect571k1 (13) */
276 0, 25, /* secp521r1 (25) */
277 0, 28, /* brainpool512r1 (28) */
278 0, 11, /* sect409k1 (11) */
279 0, 12, /* sect409r1 (12) */
280 0, 27, /* brainpoolP384r1 (27) */
281 0, 24, /* secp384r1 (24) */
282 0, 9, /* sect283k1 (9) */
283 0, 10, /* sect283r1 (10) */
284 0, 26, /* brainpoolP256r1 (26) */
285 0, 22, /* secp256k1 (22) */
286 0, 23, /* secp256r1 (23) */
287 0, 8, /* sect239k1 (8) */
288 0, 6, /* sect233k1 (6) */
289 0, 7, /* sect233r1 (7) */
290 0, 20, /* secp224k1 (20) */
291 0, 21, /* secp224r1 (21) */
292 0, 4, /* sect193r1 (4) */
293 0, 5, /* sect193r2 (5) */
294 0, 18, /* secp192k1 (18) */
295 0, 19, /* secp192r1 (19) */
296 0, 1, /* sect163k1 (1) */
297 0, 2, /* sect163r1 (2) */
298 0, 3, /* sect163r2 (3) */
299 0, 15, /* secp160k1 (15) */
300 0, 16, /* secp160r1 (16) */
301 0, 17, /* secp160r2 (17) */
304 static const unsigned char suiteb_curves[] = {
305 0, TLSEXT_curve_P_256,
306 0, TLSEXT_curve_P_384
309 int tls1_ec_curve_id2nid(int curve_id)
311 /* ECC curves from RFC 4492 and RFC 7027 */
312 if ((curve_id < 1) || ((unsigned int)curve_id >
313 sizeof(nid_list) / sizeof(nid_list[0])))
315 return nid_list[curve_id - 1].nid;
318 int tls1_ec_nid2curve_id(int nid)
320 /* ECC curves from RFC 4492 and RFC 7027 */
322 case NID_sect163k1: /* sect163k1 (1) */
324 case NID_sect163r1: /* sect163r1 (2) */
326 case NID_sect163r2: /* sect163r2 (3) */
328 case NID_sect193r1: /* sect193r1 (4) */
330 case NID_sect193r2: /* sect193r2 (5) */
332 case NID_sect233k1: /* sect233k1 (6) */
334 case NID_sect233r1: /* sect233r1 (7) */
336 case NID_sect239k1: /* sect239k1 (8) */
338 case NID_sect283k1: /* sect283k1 (9) */
340 case NID_sect283r1: /* sect283r1 (10) */
342 case NID_sect409k1: /* sect409k1 (11) */
344 case NID_sect409r1: /* sect409r1 (12) */
346 case NID_sect571k1: /* sect571k1 (13) */
348 case NID_sect571r1: /* sect571r1 (14) */
350 case NID_secp160k1: /* secp160k1 (15) */
352 case NID_secp160r1: /* secp160r1 (16) */
354 case NID_secp160r2: /* secp160r2 (17) */
356 case NID_secp192k1: /* secp192k1 (18) */
358 case NID_X9_62_prime192v1: /* secp192r1 (19) */
360 case NID_secp224k1: /* secp224k1 (20) */
362 case NID_secp224r1: /* secp224r1 (21) */
364 case NID_secp256k1: /* secp256k1 (22) */
366 case NID_X9_62_prime256v1: /* secp256r1 (23) */
368 case NID_secp384r1: /* secp384r1 (24) */
370 case NID_secp521r1: /* secp521r1 (25) */
372 case NID_brainpoolP256r1: /* brainpoolP256r1 (26) */
374 case NID_brainpoolP384r1: /* brainpoolP384r1 (27) */
376 case NID_brainpoolP512r1: /* brainpool512r1 (28) */
384 * Get curves list, if "sess" is set return client curves otherwise
386 * Sets |num_curves| to the number of curves in the list, i.e.,
387 * the length of |pcurves| is 2 * num_curves.
388 * Returns 1 on success and 0 if the client curves list has invalid format.
389 * The latter indicates an internal error: we should not be accepting such
390 * lists in the first place.
391 * TODO(emilia): we should really be storing the curves list in explicitly
392 * parsed form instead. (However, this would affect binary compatibility
393 * so cannot happen in the 1.0.x series.)
395 static int tls1_get_curvelist(SSL *s, int sess,
396 const unsigned char **pcurves,
399 size_t pcurveslen = 0;
401 *pcurves = s->session->tlsext_ellipticcurvelist;
402 pcurveslen = s->session->tlsext_ellipticcurvelist_length;
404 /* For Suite B mode only include P-256, P-384 */
405 switch (tls1_suiteb(s)) {
406 case SSL_CERT_FLAG_SUITEB_128_LOS:
407 *pcurves = suiteb_curves;
408 pcurveslen = sizeof(suiteb_curves);
411 case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
412 *pcurves = suiteb_curves;
416 case SSL_CERT_FLAG_SUITEB_192_LOS:
417 *pcurves = suiteb_curves + 2;
421 *pcurves = s->tlsext_ellipticcurvelist;
422 pcurveslen = s->tlsext_ellipticcurvelist_length;
425 *pcurves = eccurves_default;
426 pcurveslen = sizeof(eccurves_default);
430 /* We do not allow odd length arrays to enter the system. */
431 if (pcurveslen & 1) {
432 SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR);
436 *num_curves = pcurveslen / 2;
441 /* See if curve is allowed by security callback */
442 static int tls_curve_allowed(SSL *s, const unsigned char *curve, int op)
444 const tls_curve_info *cinfo;
447 if ((curve[1] < 1) || ((size_t)curve[1] >
448 sizeof(nid_list) / sizeof(nid_list[0])))
450 cinfo = &nid_list[curve[1] - 1];
451 # ifdef OPENSSL_NO_EC2M
452 if (cinfo->flags & TLS_CURVE_CHAR2)
455 return ssl_security(s, op, cinfo->secbits, cinfo->nid, (void *)curve);
458 /* Check a curve is one of our preferences */
459 int tls1_check_curve(SSL *s, const unsigned char *p, size_t len)
461 const unsigned char *curves;
462 size_t num_curves, i;
463 unsigned int suiteb_flags = tls1_suiteb(s);
464 if (len != 3 || p[0] != NAMED_CURVE_TYPE)
466 /* Check curve matches Suite B preferences */
468 unsigned long cid = s->s3->tmp.new_cipher->id;
471 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
472 if (p[2] != TLSEXT_curve_P_256)
474 } else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) {
475 if (p[2] != TLSEXT_curve_P_384)
477 } else /* Should never happen */
480 if (!tls1_get_curvelist(s, 0, &curves, &num_curves))
482 for (i = 0; i < num_curves; i++, curves += 2) {
483 if (p[1] == curves[0] && p[2] == curves[1])
484 return tls_curve_allowed(s, p + 1, SSL_SECOP_CURVE_CHECK);
490 * Return |nmatch|th shared curve or NID_undef if there is no match.
491 * For nmatch == -1, return number of matches
492 * For nmatch == -2, return the NID of the curve to use for
493 * an EC tmp key, or NID_undef if there is no match.
495 int tls1_shared_curve(SSL *s, int nmatch)
497 const unsigned char *pref, *supp;
498 size_t num_pref, num_supp, i, j;
500 /* Can't do anything on client side */
504 if (tls1_suiteb(s)) {
506 * For Suite B ciphersuite determines curve: we already know
507 * these are acceptable due to previous checks.
509 unsigned long cid = s->s3->tmp.new_cipher->id;
510 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
511 return NID_X9_62_prime256v1; /* P-256 */
512 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
513 return NID_secp384r1; /* P-384 */
514 /* Should never happen */
517 /* If not Suite B just return first preference shared curve */
521 * Avoid truncation. tls1_get_curvelist takes an int
522 * but s->options is a long...
524 if (!tls1_get_curvelist
525 (s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp,
527 /* In practice, NID_undef == 0 but let's be precise. */
528 return nmatch == -1 ? 0 : NID_undef;
529 if (!tls1_get_curvelist
530 (s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE), &pref,
532 return nmatch == -1 ? 0 : NID_undef;
534 for (i = 0; i < num_pref; i++, pref += 2) {
535 const unsigned char *tsupp = supp;
536 for (j = 0; j < num_supp; j++, tsupp += 2) {
537 if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) {
538 if (!tls_curve_allowed(s, pref, SSL_SECOP_CURVE_SHARED))
541 int id = (pref[0] << 8) | pref[1];
542 return tls1_ec_curve_id2nid(id);
550 /* Out of range (nmatch > k). */
554 int tls1_set_curves(unsigned char **pext, size_t *pextlen,
555 int *curves, size_t ncurves)
557 unsigned char *clist, *p;
560 * Bitmap of curves included to detect duplicates: only works while curve
563 unsigned long dup_list = 0;
564 clist = OPENSSL_malloc(ncurves * 2);
567 for (i = 0, p = clist; i < ncurves; i++) {
568 unsigned long idmask;
570 id = tls1_ec_nid2curve_id(curves[i]);
572 if (!id || (dup_list & idmask)) {
582 *pextlen = ncurves * 2;
586 # define MAX_CURVELIST 28
590 int nid_arr[MAX_CURVELIST];
593 static int nid_cb(const char *elem, int len, void *arg)
595 nid_cb_st *narg = arg;
601 if (narg->nidcnt == MAX_CURVELIST)
603 if (len > (int)(sizeof(etmp) - 1))
605 memcpy(etmp, elem, len);
607 nid = EC_curve_nist2nid(etmp);
608 if (nid == NID_undef)
609 nid = OBJ_sn2nid(etmp);
610 if (nid == NID_undef)
611 nid = OBJ_ln2nid(etmp);
612 if (nid == NID_undef)
614 for (i = 0; i < narg->nidcnt; i++)
615 if (narg->nid_arr[i] == nid)
617 narg->nid_arr[narg->nidcnt++] = nid;
621 /* Set curves based on a colon separate list */
622 int tls1_set_curves_list(unsigned char **pext, size_t *pextlen,
627 if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb))
631 return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt);
634 /* For an EC key set TLS id and required compression based on parameters */
635 static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id,
640 const EC_METHOD *meth;
643 /* Determine if it is a prime field */
644 grp = EC_KEY_get0_group(ec);
647 meth = EC_GROUP_method_of(grp);
650 if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
654 /* Determine curve ID */
655 id = EC_GROUP_get_curve_name(grp);
656 id = tls1_ec_nid2curve_id(id);
657 /* If we have an ID set it, otherwise set arbitrary explicit curve */
660 curve_id[1] = (unsigned char)id;
669 if (EC_KEY_get0_public_key(ec) == NULL)
671 if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
673 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
675 *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
677 *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
682 /* Check an EC key is compatible with extensions */
683 static int tls1_check_ec_key(SSL *s,
684 unsigned char *curve_id, unsigned char *comp_id)
686 const unsigned char *pformats, *pcurves;
687 size_t num_formats, num_curves, i;
690 * If point formats extension present check it, otherwise everything is
691 * supported (see RFC4492).
693 if (comp_id && s->session->tlsext_ecpointformatlist) {
694 pformats = s->session->tlsext_ecpointformatlist;
695 num_formats = s->session->tlsext_ecpointformatlist_length;
696 for (i = 0; i < num_formats; i++, pformats++) {
697 if (*comp_id == *pformats)
700 if (i == num_formats)
705 /* Check curve is consistent with client and server preferences */
706 for (j = 0; j <= 1; j++) {
707 if (!tls1_get_curvelist(s, j, &pcurves, &num_curves))
709 if (j == 1 && num_curves == 0) {
711 * If we've not received any curves then skip this check.
712 * RFC 4492 does not require the supported elliptic curves extension
713 * so if it is not sent we can just choose any curve.
714 * It is invalid to send an empty list in the elliptic curves
715 * extension, so num_curves == 0 always means no extension.
719 for (i = 0; i < num_curves; i++, pcurves += 2) {
720 if (pcurves[0] == curve_id[0] && pcurves[1] == curve_id[1])
725 /* For clients can only check sent curve list */
732 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
736 * If we have a custom point format list use it otherwise use default
738 if (s->tlsext_ecpointformatlist) {
739 *pformats = s->tlsext_ecpointformatlist;
740 *num_formats = s->tlsext_ecpointformatlist_length;
742 *pformats = ecformats_default;
743 /* For Suite B we don't support char2 fields */
745 *num_formats = sizeof(ecformats_default) - 1;
747 *num_formats = sizeof(ecformats_default);
752 * Check cert parameters compatible with extensions: currently just checks EC
753 * certificates have compatible curves and compression.
755 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
757 unsigned char comp_id, curve_id[2];
760 pkey = X509_get_pubkey(x);
763 /* If not EC nothing to do */
764 if (pkey->type != EVP_PKEY_EC) {
768 rv = tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec);
773 * Can't check curve_id for client certs as we don't have a supported
776 rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id);
780 * Special case for suite B. We *MUST* sign using SHA256+P-256 or
781 * SHA384+P-384, adjust digest if necessary.
783 if (set_ee_md && tls1_suiteb(s)) {
789 /* Check to see we have necessary signing algorithm */
790 if (curve_id[1] == TLSEXT_curve_P_256)
791 check_md = NID_ecdsa_with_SHA256;
792 else if (curve_id[1] == TLSEXT_curve_P_384)
793 check_md = NID_ecdsa_with_SHA384;
795 return 0; /* Should never happen */
796 for (i = 0; i < c->shared_sigalgslen; i++)
797 if (check_md == c->shared_sigalgs[i].signandhash_nid)
799 if (i == c->shared_sigalgslen)
801 if (set_ee_md == 2) {
802 if (check_md == NID_ecdsa_with_SHA256)
803 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha256();
805 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha384();
811 # ifndef OPENSSL_NO_EC
812 /* Check EC temporary key is compatible with client extensions */
813 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
815 unsigned char curve_id[2];
816 EC_KEY *ec = s->cert->ecdh_tmp;
817 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
818 /* Allow any curve: not just those peer supports */
819 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
823 * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other
826 if (tls1_suiteb(s)) {
827 /* Curve to check determined by ciphersuite */
828 if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)
829 curve_id[1] = TLSEXT_curve_P_256;
830 else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)
831 curve_id[1] = TLSEXT_curve_P_384;
835 /* Check this curve is acceptable */
836 if (!tls1_check_ec_key(s, curve_id, NULL))
838 /* If auto or setting curve from callback assume OK */
839 if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb)
841 /* Otherwise check curve is acceptable */
843 unsigned char curve_tmp[2];
846 if (!tls1_set_ec_id(curve_tmp, NULL, ec))
848 if (!curve_tmp[0] || curve_tmp[1] == curve_id[1])
854 if (s->cert->ecdh_tmp_auto) {
855 /* Need a shared curve */
856 if (tls1_shared_curve(s, 0))
862 if (s->cert->ecdh_tmp_cb)
867 if (!tls1_set_ec_id(curve_id, NULL, ec))
869 /* Set this to allow use of invalid curves for testing */
873 return tls1_check_ec_key(s, curve_id, NULL);
876 # endif /* OPENSSL_NO_EC */
880 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
885 #endif /* OPENSSL_NO_EC */
887 #ifndef OPENSSL_NO_TLSEXT
890 * List of supported signature algorithms and hashes. Should make this
891 * customisable at some point, for now include everything we support.
894 # ifdef OPENSSL_NO_RSA
895 # define tlsext_sigalg_rsa(md) /* */
897 # define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
900 # ifdef OPENSSL_NO_DSA
901 # define tlsext_sigalg_dsa(md) /* */
903 # define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa,
906 # ifdef OPENSSL_NO_EC
907 # define tlsext_sigalg_ecdsa(md) /* */
909 # define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
912 # define tlsext_sigalg(md) \
913 tlsext_sigalg_rsa(md) \
914 tlsext_sigalg_dsa(md) \
915 tlsext_sigalg_ecdsa(md)
917 static const unsigned char tls12_sigalgs[] = {
918 tlsext_sigalg(TLSEXT_hash_sha512)
919 tlsext_sigalg(TLSEXT_hash_sha384)
920 tlsext_sigalg(TLSEXT_hash_sha256)
921 tlsext_sigalg(TLSEXT_hash_sha224)
922 tlsext_sigalg(TLSEXT_hash_sha1)
925 # ifndef OPENSSL_NO_EC
926 static const unsigned char suiteb_sigalgs[] = {
927 tlsext_sigalg_ecdsa(TLSEXT_hash_sha256)
928 tlsext_sigalg_ecdsa(TLSEXT_hash_sha384)
931 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
934 * If Suite B mode use Suite B sigalgs only, ignore any other
937 # ifndef OPENSSL_NO_EC
938 switch (tls1_suiteb(s)) {
939 case SSL_CERT_FLAG_SUITEB_128_LOS:
940 *psigs = suiteb_sigalgs;
941 return sizeof(suiteb_sigalgs);
943 case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY:
944 *psigs = suiteb_sigalgs;
947 case SSL_CERT_FLAG_SUITEB_192_LOS:
948 *psigs = suiteb_sigalgs + 2;
952 /* If server use client authentication sigalgs if not NULL */
953 if (s->server && s->cert->client_sigalgs) {
954 *psigs = s->cert->client_sigalgs;
955 return s->cert->client_sigalgslen;
956 } else if (s->cert->conf_sigalgs) {
957 *psigs = s->cert->conf_sigalgs;
958 return s->cert->conf_sigalgslen;
960 *psigs = tls12_sigalgs;
961 return sizeof(tls12_sigalgs);
966 * Check signature algorithm is consistent with sent supported signature
967 * algorithms and if so return relevant digest.
969 int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s,
970 const unsigned char *sig, EVP_PKEY *pkey)
972 const unsigned char *sent_sigs;
973 size_t sent_sigslen, i;
974 int sigalg = tls12_get_sigid(pkey);
975 /* Should never happen */
978 /* Check key type is consistent with signature */
979 if (sigalg != (int)sig[1]) {
980 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
983 # ifndef OPENSSL_NO_EC
984 if (pkey->type == EVP_PKEY_EC) {
985 unsigned char curve_id[2], comp_id;
986 /* Check compression and curve matches extensions */
987 if (!tls1_set_ec_id(curve_id, &comp_id, pkey->pkey.ec))
989 if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) {
990 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE);
993 /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */
994 if (tls1_suiteb(s)) {
997 if (curve_id[1] == TLSEXT_curve_P_256) {
998 if (sig[0] != TLSEXT_hash_sha256) {
999 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1000 SSL_R_ILLEGAL_SUITEB_DIGEST);
1003 } else if (curve_id[1] == TLSEXT_curve_P_384) {
1004 if (sig[0] != TLSEXT_hash_sha384) {
1005 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG,
1006 SSL_R_ILLEGAL_SUITEB_DIGEST);
1012 } else if (tls1_suiteb(s))
1016 /* Check signature matches a type we sent */
1017 sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
1018 for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) {
1019 if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1])
1022 /* Allow fallback to SHA1 if not strict mode */
1023 if (i == sent_sigslen
1024 && (sig[0] != TLSEXT_hash_sha1
1025 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
1026 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
1029 *pmd = tls12_get_hash(sig[0]);
1031 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_UNKNOWN_DIGEST);
1034 /* Make sure security callback allows algorithm */
1035 if (!ssl_security(s, SSL_SECOP_SIGALG_CHECK,
1036 EVP_MD_size(*pmd) * 4, EVP_MD_type(*pmd),
1038 SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE);
1042 * Store the digest used so applications can retrieve it if they wish.
1044 if (s->session && s->session->sess_cert)
1045 s->session->sess_cert->peer_key->digest = *pmd;
1050 * Get a mask of disabled algorithms: an algorithm is disabled if it isn't
1051 * supported or doesn't appear in supported signature algorithms. Unlike
1052 * ssl_cipher_get_disabled this applies to a specific session and not global
1055 void ssl_set_client_disabled(SSL *s)
1060 /* Don't allow TLS 1.2 only ciphers if we don't suppport them */
1061 if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
1062 c->mask_ssl = SSL_TLSV1_2;
1065 ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK);
1067 * Disable static DH if we don't include any appropriate signature
1070 if (c->mask_a & SSL_aRSA)
1071 c->mask_k |= SSL_kDHr | SSL_kECDHr;
1072 if (c->mask_a & SSL_aDSS)
1073 c->mask_k |= SSL_kDHd;
1074 if (c->mask_a & SSL_aECDSA)
1075 c->mask_k |= SSL_kECDHe;
1076 # ifndef OPENSSL_NO_KRB5
1077 if (!kssl_tgt_is_available(s->kssl_ctx)) {
1078 c->mask_a |= SSL_aKRB5;
1079 c->mask_k |= SSL_kKRB5;
1082 # ifndef OPENSSL_NO_PSK
1083 /* with PSK there must be client callback set */
1084 if (!s->psk_client_callback) {
1085 c->mask_a |= SSL_aPSK;
1086 c->mask_k |= SSL_kPSK;
1088 # endif /* OPENSSL_NO_PSK */
1089 # ifndef OPENSSL_NO_SRP
1090 if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) {
1091 c->mask_a |= SSL_aSRP;
1092 c->mask_k |= SSL_kSRP;
1098 int ssl_cipher_disabled(SSL *s, const SSL_CIPHER *c, int op)
1101 if (c->algorithm_ssl & ct->mask_ssl || c->algorithm_mkey & ct->mask_k
1102 || c->algorithm_auth & ct->mask_a)
1104 return !ssl_security(s, op, c->strength_bits, 0, (void *)c);
1107 static int tls_use_ticket(SSL *s)
1109 if (s->options & SSL_OP_NO_TICKET)
1111 return ssl_security(s, SSL_SECOP_TICKET, 0, 0, NULL);
1114 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf,
1115 unsigned char *limit, int *al)
1118 unsigned char *orig = buf;
1119 unsigned char *ret = buf;
1120 # ifndef OPENSSL_NO_EC
1121 /* See if we support any ECC ciphersuites */
1123 if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) {
1125 unsigned long alg_k, alg_a;
1126 STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
1128 for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) {
1129 SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
1131 alg_k = c->algorithm_mkey;
1132 alg_a = c->algorithm_auth;
1133 if ((alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe)
1134 || (alg_a & SSL_aECDSA))) {
1145 return NULL; /* this really never occurs, but ... */
1147 /* Add RI if renegotiating */
1148 if (s->renegotiate) {
1151 if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) {
1152 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1156 if ((limit - ret - 4 - el) < 0)
1159 s2n(TLSEXT_TYPE_renegotiate, ret);
1162 if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) {
1163 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1169 /* Only add RI for SSLv3 */
1170 if (s->client_version == SSL3_VERSION)
1173 if (s->tlsext_hostname != NULL) {
1174 /* Add TLS extension servername to the Client Hello message */
1175 unsigned long size_str;
1179 * check for enough space.
1180 * 4 for the servername type and entension length
1181 * 2 for servernamelist length
1182 * 1 for the hostname type
1183 * 2 for hostname length
1187 if ((lenmax = limit - ret - 9) < 0
1189 strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
1192 /* extension type and length */
1193 s2n(TLSEXT_TYPE_server_name, ret);
1194 s2n(size_str + 5, ret);
1196 /* length of servername list */
1197 s2n(size_str + 3, ret);
1199 /* hostname type, length and hostname */
1200 *(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name;
1202 memcpy(ret, s->tlsext_hostname, size_str);
1205 # ifndef OPENSSL_NO_SRP
1206 /* Add SRP username if there is one */
1207 if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the
1208 * Client Hello message */
1210 int login_len = strlen(s->srp_ctx.login);
1211 if (login_len > 255 || login_len == 0) {
1212 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1217 * check for enough space.
1218 * 4 for the srp type type and entension length
1219 * 1 for the srp user identity
1220 * + srp user identity length
1222 if ((limit - ret - 5 - login_len) < 0)
1225 /* fill in the extension */
1226 s2n(TLSEXT_TYPE_srp, ret);
1227 s2n(login_len + 1, ret);
1228 (*ret++) = (unsigned char)login_len;
1229 memcpy(ret, s->srp_ctx.login, login_len);
1234 # ifndef OPENSSL_NO_EC
1237 * Add TLS extension ECPointFormats to the ClientHello message
1240 const unsigned char *pcurves, *pformats;
1241 size_t num_curves, num_formats, curves_list_len;
1243 unsigned char *etmp;
1245 tls1_get_formatlist(s, &pformats, &num_formats);
1247 if ((lenmax = limit - ret - 5) < 0)
1249 if (num_formats > (size_t)lenmax)
1251 if (num_formats > 255) {
1252 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1256 s2n(TLSEXT_TYPE_ec_point_formats, ret);
1257 /* The point format list has 1-byte length. */
1258 s2n(num_formats + 1, ret);
1259 *(ret++) = (unsigned char)num_formats;
1260 memcpy(ret, pformats, num_formats);
1264 * Add TLS extension EllipticCurves to the ClientHello message
1266 pcurves = s->tlsext_ellipticcurvelist;
1267 if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves))
1270 if ((lenmax = limit - ret - 6) < 0)
1272 if (num_curves > (size_t)lenmax / 2)
1274 if (num_curves > 65532 / 2) {
1275 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1279 s2n(TLSEXT_TYPE_elliptic_curves, ret);
1281 /* Copy curve ID if supported */
1282 for (i = 0; i < num_curves; i++, pcurves += 2) {
1283 if (tls_curve_allowed(s, pcurves, SSL_SECOP_CURVE_SUPPORTED)) {
1284 *etmp++ = pcurves[0];
1285 *etmp++ = pcurves[1];
1289 curves_list_len = etmp - ret - 4;
1291 s2n(curves_list_len + 2, ret);
1292 s2n(curves_list_len, ret);
1293 ret += curves_list_len;
1295 # endif /* OPENSSL_NO_EC */
1297 if (tls_use_ticket(s)) {
1299 if (!s->new_session && s->session && s->session->tlsext_tick)
1300 ticklen = s->session->tlsext_ticklen;
1301 else if (s->session && s->tlsext_session_ticket &&
1302 s->tlsext_session_ticket->data) {
1303 ticklen = s->tlsext_session_ticket->length;
1304 s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1305 if (!s->session->tlsext_tick)
1307 memcpy(s->session->tlsext_tick,
1308 s->tlsext_session_ticket->data, ticklen);
1309 s->session->tlsext_ticklen = ticklen;
1312 if (ticklen == 0 && s->tlsext_session_ticket &&
1313 s->tlsext_session_ticket->data == NULL)
1316 * Check for enough room 2 for extension type, 2 for len rest for
1319 if ((long)(limit - ret - 4 - ticklen) < 0)
1321 s2n(TLSEXT_TYPE_session_ticket, ret);
1324 memcpy(ret, s->session->tlsext_tick, ticklen);
1330 if (SSL_USE_SIGALGS(s)) {
1332 const unsigned char *salg;
1333 unsigned char *etmp;
1334 salglen = tls12_get_psigalgs(s, &salg);
1335 if ((size_t)(limit - ret) < salglen + 6)
1337 s2n(TLSEXT_TYPE_signature_algorithms, ret);
1339 /* Skip over lengths for now */
1341 salglen = tls12_copy_sigalgs(s, ret, salg, salglen);
1342 /* Fill in lengths */
1343 s2n(salglen + 2, etmp);
1348 if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
1350 long extlen, idlen, itmp;
1354 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
1355 id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1356 itmp = i2d_OCSP_RESPID(id, NULL);
1362 if (s->tlsext_ocsp_exts) {
1363 extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
1369 if ((long)(limit - ret - 7 - extlen - idlen) < 0)
1371 s2n(TLSEXT_TYPE_status_request, ret);
1372 if (extlen + idlen > 0xFFF0)
1374 s2n(extlen + idlen + 5, ret);
1375 *(ret++) = TLSEXT_STATUSTYPE_ocsp;
1377 for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) {
1378 /* save position of id len */
1379 unsigned char *q = ret;
1380 id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
1381 /* skip over id len */
1383 itmp = i2d_OCSP_RESPID(id, &ret);
1389 i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
1391 # ifndef OPENSSL_NO_HEARTBEATS
1392 /* Add Heartbeat extension */
1393 if ((limit - ret - 4 - 1) < 0)
1395 s2n(TLSEXT_TYPE_heartbeat, ret);
1399 * 1: peer may send requests
1400 * 2: peer not allowed to send requests
1402 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1403 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1405 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1408 # ifndef OPENSSL_NO_NEXTPROTONEG
1409 if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) {
1411 * The client advertises an emtpy extension to indicate its support
1412 * for Next Protocol Negotiation
1414 if (limit - ret - 4 < 0)
1416 s2n(TLSEXT_TYPE_next_proto_neg, ret);
1421 if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) {
1422 if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
1424 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1425 s2n(2 + s->alpn_client_proto_list_len, ret);
1426 s2n(s->alpn_client_proto_list_len, ret);
1427 memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len);
1428 ret += s->alpn_client_proto_list_len;
1430 # ifndef OPENSSL_NO_SRTP
1431 if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) {
1434 /* Returns 0 on success!! */
1435 if (ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0)) {
1436 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1440 if ((limit - ret - 4 - el) < 0)
1443 s2n(TLSEXT_TYPE_use_srtp, ret);
1446 if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) {
1447 SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1453 custom_ext_init(&s->cert->cli_ext);
1454 /* Add custom TLS Extensions to ClientHello */
1455 if (!custom_ext_add(s, 0, &ret, limit, al))
1457 # ifdef TLSEXT_TYPE_encrypt_then_mac
1458 s2n(TLSEXT_TYPE_encrypt_then_mac, ret);
1461 s2n(TLSEXT_TYPE_extended_master_secret, ret);
1465 * Add padding to workaround bugs in F5 terminators. See
1466 * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this
1467 * code works out the length of all existing extensions it MUST always
1470 if (s->options & SSL_OP_TLSEXT_PADDING) {
1471 int hlen = ret - (unsigned char *)s->init_buf->data;
1473 * The code in s23_clnt.c to build ClientHello messages includes the
1474 * 5-byte record header in the buffer, while the code in s3_clnt.c
1477 if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
1479 if (hlen > 0xff && hlen < 0x200) {
1480 hlen = 0x200 - hlen;
1486 s2n(TLSEXT_TYPE_padding, ret);
1488 memset(ret, 0, hlen);
1495 if ((extdatalen = ret - orig - 2) == 0)
1498 s2n(extdatalen, orig);
1502 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf,
1503 unsigned char *limit, int *al)
1506 unsigned char *orig = buf;
1507 unsigned char *ret = buf;
1508 # ifndef OPENSSL_NO_NEXTPROTONEG
1509 int next_proto_neg_seen;
1511 # ifndef OPENSSL_NO_EC
1512 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
1513 unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
1514 int using_ecc = (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe))
1515 || (alg_a & SSL_aECDSA);
1516 using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
1521 return NULL; /* this really never occurs, but ... */
1523 if (s->s3->send_connection_binding) {
1526 if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) {
1527 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1531 if ((limit - ret - 4 - el) < 0)
1534 s2n(TLSEXT_TYPE_renegotiate, ret);
1537 if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) {
1538 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1545 /* Only add RI for SSLv3 */
1546 if (s->version == SSL3_VERSION)
1549 if (!s->hit && s->servername_done == 1
1550 && s->session->tlsext_hostname != NULL) {
1551 if ((long)(limit - ret - 4) < 0)
1554 s2n(TLSEXT_TYPE_server_name, ret);
1557 # ifndef OPENSSL_NO_EC
1559 const unsigned char *plist;
1562 * Add TLS extension ECPointFormats to the ServerHello message
1566 tls1_get_formatlist(s, &plist, &plistlen);
1568 if ((lenmax = limit - ret - 5) < 0)
1570 if (plistlen > (size_t)lenmax)
1572 if (plistlen > 255) {
1573 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1577 s2n(TLSEXT_TYPE_ec_point_formats, ret);
1578 s2n(plistlen + 1, ret);
1579 *(ret++) = (unsigned char)plistlen;
1580 memcpy(ret, plist, plistlen);
1585 * Currently the server should not respond with a SupportedCurves
1588 # endif /* OPENSSL_NO_EC */
1590 if (s->tlsext_ticket_expected && tls_use_ticket(s)) {
1591 if ((long)(limit - ret - 4) < 0)
1593 s2n(TLSEXT_TYPE_session_ticket, ret);
1597 if (s->tlsext_status_expected) {
1598 if ((long)(limit - ret - 4) < 0)
1600 s2n(TLSEXT_TYPE_status_request, ret);
1604 # ifndef OPENSSL_NO_SRTP
1605 if (SSL_IS_DTLS(s) && s->srtp_profile) {
1608 /* Returns 0 on success!! */
1609 if(ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0)) {
1610 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1613 if ((limit - ret - 4 - el) < 0)
1616 s2n(TLSEXT_TYPE_use_srtp, ret);
1619 if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) {
1620 SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
1627 if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80
1628 || (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81)
1629 && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) {
1630 const unsigned char cryptopro_ext[36] = {
1631 0xfd, 0xe8, /* 65000 */
1632 0x00, 0x20, /* 32 bytes length */
1633 0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85,
1634 0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06,
1635 0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08,
1636 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17
1638 if (limit - ret < 36)
1640 memcpy(ret, cryptopro_ext, 36);
1644 # ifndef OPENSSL_NO_HEARTBEATS
1645 /* Add Heartbeat extension if we've received one */
1646 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) {
1647 if ((limit - ret - 4 - 1) < 0)
1649 s2n(TLSEXT_TYPE_heartbeat, ret);
1653 * 1: peer may send requests
1654 * 2: peer not allowed to send requests
1656 if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
1657 *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
1659 *(ret++) = SSL_TLSEXT_HB_ENABLED;
1664 # ifndef OPENSSL_NO_NEXTPROTONEG
1665 next_proto_neg_seen = s->s3->next_proto_neg_seen;
1666 s->s3->next_proto_neg_seen = 0;
1667 if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) {
1668 const unsigned char *npa;
1669 unsigned int npalen;
1672 r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen,
1674 ctx->next_protos_advertised_cb_arg);
1675 if (r == SSL_TLSEXT_ERR_OK) {
1676 if ((long)(limit - ret - 4 - npalen) < 0)
1678 s2n(TLSEXT_TYPE_next_proto_neg, ret);
1680 memcpy(ret, npa, npalen);
1682 s->s3->next_proto_neg_seen = 1;
1686 if (!custom_ext_add(s, 1, &ret, limit, al))
1688 # ifdef TLSEXT_TYPE_encrypt_then_mac
1689 if (s->s3->flags & TLS1_FLAGS_ENCRYPT_THEN_MAC) {
1691 * Don't use encrypt_then_mac if AEAD or RC4 might want to disable
1692 * for other cases too.
1694 if (s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD
1695 || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4)
1696 s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
1698 s2n(TLSEXT_TYPE_encrypt_then_mac, ret);
1703 if (!s->hit && s->session->flags & SSL_SESS_FLAG_EXTMS) {
1704 s2n(TLSEXT_TYPE_extended_master_secret, ret);
1708 if (s->s3->alpn_selected) {
1709 const unsigned char *selected = s->s3->alpn_selected;
1710 unsigned len = s->s3->alpn_selected_len;
1712 if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
1714 s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret);
1718 memcpy(ret, selected, len);
1724 if ((extdatalen = ret - orig - 2) == 0)
1727 s2n(extdatalen, orig);
1732 * tls1_alpn_handle_client_hello is called to process the ALPN extension in a
1733 * ClientHello. data: the contents of the extension, not including the type
1734 * and length. data_len: the number of bytes in |data| al: a pointer to the
1735 * alert value to send in the event of a non-zero return. returns: 0 on
1738 static int tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
1739 unsigned data_len, int *al)
1743 const unsigned char *selected;
1744 unsigned char selected_len;
1747 if (s->ctx->alpn_select_cb == NULL)
1754 * data should contain a uint16 length followed by a series of 8-bit,
1755 * length-prefixed strings.
1757 i = ((unsigned)data[0]) << 8 | ((unsigned)data[1]);
1766 for (i = 0; i < data_len;) {
1767 proto_len = data[i];
1773 if (i + proto_len < i || i + proto_len > data_len)
1779 r = s->ctx->alpn_select_cb(s, &selected, &selected_len, data, data_len,
1780 s->ctx->alpn_select_cb_arg);
1781 if (r == SSL_TLSEXT_ERR_OK) {
1782 if (s->s3->alpn_selected)
1783 OPENSSL_free(s->s3->alpn_selected);
1784 s->s3->alpn_selected = OPENSSL_malloc(selected_len);
1785 if (!s->s3->alpn_selected) {
1786 *al = SSL_AD_INTERNAL_ERROR;
1789 memcpy(s->s3->alpn_selected, selected, selected_len);
1790 s->s3->alpn_selected_len = selected_len;
1795 *al = SSL_AD_DECODE_ERROR;
1799 # ifndef OPENSSL_NO_EC
1801 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1802 * SecureTransport using the TLS extension block in |d|, of length |n|.
1803 * Safari, since 10.6, sends exactly these extensions, in this order:
1808 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1809 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1810 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1811 * 10.8..10.8.3 (which don't work).
1813 static void ssl_check_for_safari(SSL *s, const unsigned char *data,
1814 const unsigned char *d, int n)
1816 unsigned short type, size;
1817 static const unsigned char kSafariExtensionsBlock[] = {
1818 0x00, 0x0a, /* elliptic_curves extension */
1819 0x00, 0x08, /* 8 bytes */
1820 0x00, 0x06, /* 6 bytes of curve ids */
1821 0x00, 0x17, /* P-256 */
1822 0x00, 0x18, /* P-384 */
1823 0x00, 0x19, /* P-521 */
1825 0x00, 0x0b, /* ec_point_formats */
1826 0x00, 0x02, /* 2 bytes */
1827 0x01, /* 1 point format */
1828 0x00, /* uncompressed */
1831 /* The following is only present in TLS 1.2 */
1832 static const unsigned char kSafariTLS12ExtensionsBlock[] = {
1833 0x00, 0x0d, /* signature_algorithms */
1834 0x00, 0x0c, /* 12 bytes */
1835 0x00, 0x0a, /* 10 bytes */
1836 0x05, 0x01, /* SHA-384/RSA */
1837 0x04, 0x01, /* SHA-256/RSA */
1838 0x02, 0x01, /* SHA-1/RSA */
1839 0x04, 0x03, /* SHA-256/ECDSA */
1840 0x02, 0x03, /* SHA-1/ECDSA */
1843 if (data >= (d + n - 2))
1847 if (data > (d + n - 4))
1852 if (type != TLSEXT_TYPE_server_name)
1855 if (data + size > d + n)
1859 if (TLS1_get_client_version(s) >= TLS1_2_VERSION) {
1860 const size_t len1 = sizeof(kSafariExtensionsBlock);
1861 const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock);
1863 if (data + len1 + len2 != d + n)
1865 if (memcmp(data, kSafariExtensionsBlock, len1) != 0)
1867 if (memcmp(data + len1, kSafariTLS12ExtensionsBlock, len2) != 0)
1870 const size_t len = sizeof(kSafariExtensionsBlock);
1872 if (data + len != d + n)
1874 if (memcmp(data, kSafariExtensionsBlock, len) != 0)
1878 s->s3->is_probably_safari = 1;
1880 # endif /* !OPENSSL_NO_EC */
1882 static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p,
1883 unsigned char *d, int n, int *al)
1885 unsigned short type;
1886 unsigned short size;
1888 unsigned char *data = *p;
1889 int renegotiate_seen = 0;
1891 s->servername_done = 0;
1892 s->tlsext_status_type = -1;
1893 # ifndef OPENSSL_NO_NEXTPROTONEG
1894 s->s3->next_proto_neg_seen = 0;
1897 if (s->s3->alpn_selected) {
1898 OPENSSL_free(s->s3->alpn_selected);
1899 s->s3->alpn_selected = NULL;
1901 # ifndef OPENSSL_NO_HEARTBEATS
1902 s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
1903 SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
1906 # ifndef OPENSSL_NO_EC
1907 if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1908 ssl_check_for_safari(s, data, d, n);
1909 # endif /* !OPENSSL_NO_EC */
1911 /* Clear any signature algorithms extension received */
1912 if (s->cert->peer_sigalgs) {
1913 OPENSSL_free(s->cert->peer_sigalgs);
1914 s->cert->peer_sigalgs = NULL;
1916 # ifdef TLSEXT_TYPE_encrypt_then_mac
1917 s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
1920 # ifndef OPENSSL_NO_SRP
1921 if (s->srp_ctx.login != NULL) {
1922 OPENSSL_free(s->srp_ctx.login);
1923 s->srp_ctx.login = NULL;
1927 s->srtp_profile = NULL;
1929 if (data >= (d + n - 2))
1933 if (data > (d + n - len))
1936 while (data <= (d + n - 4)) {
1940 if (data + size > (d + n))
1942 if (s->tlsext_debug_cb)
1943 s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg);
1944 if (type == TLSEXT_TYPE_renegotiate) {
1945 if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
1947 renegotiate_seen = 1;
1948 } else if (s->version == SSL3_VERSION) {
1951 * The servername extension is treated as follows:
1953 * - Only the hostname type is supported with a maximum length of 255.
1954 * - The servername is rejected if too long or if it contains zeros,
1955 * in which case an fatal alert is generated.
1956 * - The servername field is maintained together with the session cache.
1957 * - When a session is resumed, the servername call back invoked in order
1958 * to allow the application to position itself to the right context.
1959 * - The servername is acknowledged if it is new for a session or when
1960 * it is identical to a previously used for the same session.
1961 * Applications can control the behaviour. They can at any time
1962 * set a 'desirable' servername for a new SSL object. This can be the
1963 * case for example with HTTPS when a Host: header field is received and
1964 * a renegotiation is requested. In this case, a possible servername
1965 * presented in the new client hello is only acknowledged if it matches
1966 * the value of the Host: field.
1967 * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1968 * if they provide for changing an explicit servername context for the
1969 * session, i.e. when the session has been established with a servername
1971 * - On session reconnect, the servername extension may be absent.
1975 else if (type == TLSEXT_TYPE_server_name) {
1976 unsigned char *sdata;
1981 *al = SSL_AD_DECODE_ERROR;
1987 *al = SSL_AD_DECODE_ERROR;
1993 servname_type = *(sdata++);
1998 *al = SSL_AD_DECODE_ERROR;
2001 if (s->servername_done == 0)
2002 switch (servname_type) {
2003 case TLSEXT_NAMETYPE_host_name:
2005 if (s->session->tlsext_hostname) {
2006 *al = SSL_AD_DECODE_ERROR;
2009 if (len > TLSEXT_MAXLEN_host_name) {
2010 *al = TLS1_AD_UNRECOGNIZED_NAME;
2013 if ((s->session->tlsext_hostname =
2014 OPENSSL_malloc(len + 1)) == NULL) {
2015 *al = TLS1_AD_INTERNAL_ERROR;
2018 memcpy(s->session->tlsext_hostname, sdata, len);
2019 s->session->tlsext_hostname[len] = '\0';
2020 if (strlen(s->session->tlsext_hostname) != len) {
2021 OPENSSL_free(s->session->tlsext_hostname);
2022 s->session->tlsext_hostname = NULL;
2023 *al = TLS1_AD_UNRECOGNIZED_NAME;
2026 s->servername_done = 1;
2029 s->servername_done = s->session->tlsext_hostname
2030 && strlen(s->session->tlsext_hostname) == len
2031 && strncmp(s->session->tlsext_hostname,
2032 (char *)sdata, len) == 0;
2043 *al = SSL_AD_DECODE_ERROR;
2048 # ifndef OPENSSL_NO_SRP
2049 else if (type == TLSEXT_TYPE_srp) {
2050 if (size <= 0 || ((len = data[0])) != (size - 1)) {
2051 *al = SSL_AD_DECODE_ERROR;
2054 if (s->srp_ctx.login != NULL) {
2055 *al = SSL_AD_DECODE_ERROR;
2058 if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL)
2060 memcpy(s->srp_ctx.login, &data[1], len);
2061 s->srp_ctx.login[len] = '\0';
2063 if (strlen(s->srp_ctx.login) != len) {
2064 *al = SSL_AD_DECODE_ERROR;
2070 # ifndef OPENSSL_NO_EC
2071 else if (type == TLSEXT_TYPE_ec_point_formats) {
2072 unsigned char *sdata = data;
2073 int ecpointformatlist_length = *(sdata++);
2075 if (ecpointformatlist_length != size - 1 ||
2076 ecpointformatlist_length < 1) {
2077 *al = TLS1_AD_DECODE_ERROR;
2081 if (s->session->tlsext_ecpointformatlist) {
2082 OPENSSL_free(s->session->tlsext_ecpointformatlist);
2083 s->session->tlsext_ecpointformatlist = NULL;
2085 s->session->tlsext_ecpointformatlist_length = 0;
2086 if ((s->session->tlsext_ecpointformatlist =
2087 OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2088 *al = TLS1_AD_INTERNAL_ERROR;
2091 s->session->tlsext_ecpointformatlist_length =
2092 ecpointformatlist_length;
2093 memcpy(s->session->tlsext_ecpointformatlist, sdata,
2094 ecpointformatlist_length);
2096 } else if (type == TLSEXT_TYPE_elliptic_curves) {
2097 unsigned char *sdata = data;
2098 int ellipticcurvelist_length = (*(sdata++) << 8);
2099 ellipticcurvelist_length += (*(sdata++));
2101 if (ellipticcurvelist_length != size - 2 ||
2102 ellipticcurvelist_length < 1 ||
2103 /* Each NamedCurve is 2 bytes. */
2104 ellipticcurvelist_length & 1) {
2105 *al = TLS1_AD_DECODE_ERROR;
2109 if (s->session->tlsext_ellipticcurvelist) {
2110 *al = TLS1_AD_DECODE_ERROR;
2113 s->session->tlsext_ellipticcurvelist_length = 0;
2114 if ((s->session->tlsext_ellipticcurvelist =
2115 OPENSSL_malloc(ellipticcurvelist_length)) == NULL) {
2116 *al = TLS1_AD_INTERNAL_ERROR;
2119 s->session->tlsext_ellipticcurvelist_length =
2120 ellipticcurvelist_length;
2121 memcpy(s->session->tlsext_ellipticcurvelist, sdata,
2122 ellipticcurvelist_length);
2125 # endif /* OPENSSL_NO_EC */
2126 else if (type == TLSEXT_TYPE_session_ticket) {
2127 if (s->tls_session_ticket_ext_cb &&
2128 !s->tls_session_ticket_ext_cb(s, data, size,
2129 s->tls_session_ticket_ext_cb_arg))
2131 *al = TLS1_AD_INTERNAL_ERROR;
2134 } else if (type == TLSEXT_TYPE_signature_algorithms) {
2136 if (s->cert->peer_sigalgs || size < 2) {
2137 *al = SSL_AD_DECODE_ERROR;
2142 if (dsize != size || dsize & 1 || !dsize) {
2143 *al = SSL_AD_DECODE_ERROR;
2146 if (!tls1_save_sigalgs(s, data, dsize)) {
2147 *al = SSL_AD_DECODE_ERROR;
2150 } else if (type == TLSEXT_TYPE_status_request) {
2153 *al = SSL_AD_DECODE_ERROR;
2157 s->tlsext_status_type = *data++;
2159 if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) {
2160 const unsigned char *sdata;
2162 /* Read in responder_id_list */
2166 *al = SSL_AD_DECODE_ERROR;
2173 *al = SSL_AD_DECODE_ERROR;
2177 dsize -= 2 + idsize;
2180 *al = SSL_AD_DECODE_ERROR;
2185 id = d2i_OCSP_RESPID(NULL, &sdata, idsize);
2187 *al = SSL_AD_DECODE_ERROR;
2190 if (data != sdata) {
2191 OCSP_RESPID_free(id);
2192 *al = SSL_AD_DECODE_ERROR;
2195 if (!s->tlsext_ocsp_ids
2196 && !(s->tlsext_ocsp_ids =
2197 sk_OCSP_RESPID_new_null())) {
2198 OCSP_RESPID_free(id);
2199 *al = SSL_AD_INTERNAL_ERROR;
2202 if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) {
2203 OCSP_RESPID_free(id);
2204 *al = SSL_AD_INTERNAL_ERROR;
2209 /* Read in request_extensions */
2211 *al = SSL_AD_DECODE_ERROR;
2216 if (dsize != size) {
2217 *al = SSL_AD_DECODE_ERROR;
2222 if (s->tlsext_ocsp_exts) {
2223 sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
2224 X509_EXTENSION_free);
2227 s->tlsext_ocsp_exts =
2228 d2i_X509_EXTENSIONS(NULL, &sdata, dsize);
2229 if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) {
2230 *al = SSL_AD_DECODE_ERROR;
2236 * We don't know what to do with any other type * so ignore it.
2239 s->tlsext_status_type = -1;
2241 # ifndef OPENSSL_NO_HEARTBEATS
2242 else if (type == TLSEXT_TYPE_heartbeat) {
2244 case 0x01: /* Client allows us to send HB requests */
2245 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2247 case 0x02: /* Client doesn't accept HB requests */
2248 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2249 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2252 *al = SSL_AD_ILLEGAL_PARAMETER;
2257 # ifndef OPENSSL_NO_NEXTPROTONEG
2258 else if (type == TLSEXT_TYPE_next_proto_neg &&
2259 s->s3->tmp.finish_md_len == 0 &&
2260 s->s3->alpn_selected == NULL) {
2262 * We shouldn't accept this extension on a
2265 * s->new_session will be set on renegotiation, but we
2266 * probably shouldn't rely that it couldn't be set on
2267 * the initial renegotation too in certain cases (when
2268 * there's some other reason to disallow resuming an
2269 * earlier session -- the current code won't be doing
2270 * anything like that, but this might change).
2272 * A valid sign that there's been a previous handshake
2273 * in this connection is if s->s3->tmp.finish_md_len >
2274 * 0. (We are talking about a check that will happen
2275 * in the Hello protocol round, well before a new
2276 * Finished message could have been computed.)
2278 s->s3->next_proto_neg_seen = 1;
2282 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
2283 s->ctx->alpn_select_cb && s->s3->tmp.finish_md_len == 0) {
2284 if (tls1_alpn_handle_client_hello(s, data, size, al) != 0)
2286 # ifndef OPENSSL_NO_NEXTPROTONEG
2287 /* ALPN takes precedence over NPN. */
2288 s->s3->next_proto_neg_seen = 0;
2292 /* session ticket processed earlier */
2293 # ifndef OPENSSL_NO_SRTP
2294 else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)
2295 && type == TLSEXT_TYPE_use_srtp) {
2296 if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al))
2300 # ifdef TLSEXT_TYPE_encrypt_then_mac
2301 else if (type == TLSEXT_TYPE_encrypt_then_mac)
2302 s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
2304 else if (type == TLSEXT_TYPE_extended_master_secret) {
2306 s->session->flags |= SSL_SESS_FLAG_EXTMS;
2309 * If this ClientHello extension was unhandled and this is a
2310 * nonresumed connection, check whether the extension is a custom
2311 * TLS Extension (has a custom_srv_ext_record), and if so call the
2312 * callback and record the extension number so that an appropriate
2313 * ServerHello may be later returned.
2316 if (custom_ext_parse(s, 1, type, data, size, al) <= 0)
2327 /* Need RI if renegotiating */
2329 if (!renegotiate_seen && s->renegotiate &&
2330 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2331 *al = SSL_AD_HANDSHAKE_FAILURE;
2332 SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT,
2333 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2340 int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
2344 custom_ext_init(&s->cert->srv_ext);
2345 if (ssl_scan_clienthello_tlsext(s, p, d, n, &al) <= 0) {
2346 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2350 if (ssl_check_clienthello_tlsext_early(s) <= 0) {
2351 SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT);
2357 # ifndef OPENSSL_NO_NEXTPROTONEG
2359 * ssl_next_proto_validate validates a Next Protocol Negotiation block. No
2360 * elements of zero length are allowed and the set of elements must exactly
2361 * fill the length of the block.
2363 static char ssl_next_proto_validate(unsigned char *d, unsigned len)
2365 unsigned int off = 0;
2378 static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p,
2379 unsigned char *d, int n, int *al)
2381 unsigned short length;
2382 unsigned short type;
2383 unsigned short size;
2384 unsigned char *data = *p;
2385 int tlsext_servername = 0;
2386 int renegotiate_seen = 0;
2388 # ifndef OPENSSL_NO_NEXTPROTONEG
2389 s->s3->next_proto_neg_seen = 0;
2391 s->tlsext_ticket_expected = 0;
2393 if (s->s3->alpn_selected) {
2394 OPENSSL_free(s->s3->alpn_selected);
2395 s->s3->alpn_selected = NULL;
2397 # ifndef OPENSSL_NO_HEARTBEATS
2398 s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
2399 SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
2402 # ifdef TLSEXT_TYPE_encrypt_then_mac
2403 s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC;
2406 if (data >= (d + n - 2))
2410 if (data + length != d + n) {
2411 *al = SSL_AD_DECODE_ERROR;
2415 while (data <= (d + n - 4)) {
2419 if (data + size > (d + n))
2422 if (s->tlsext_debug_cb)
2423 s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg);
2425 if (type == TLSEXT_TYPE_renegotiate) {
2426 if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al))
2428 renegotiate_seen = 1;
2429 } else if (s->version == SSL3_VERSION) {
2430 } else if (type == TLSEXT_TYPE_server_name) {
2431 if (s->tlsext_hostname == NULL || size > 0) {
2432 *al = TLS1_AD_UNRECOGNIZED_NAME;
2435 tlsext_servername = 1;
2437 # ifndef OPENSSL_NO_EC
2438 else if (type == TLSEXT_TYPE_ec_point_formats) {
2439 unsigned char *sdata = data;
2440 int ecpointformatlist_length = *(sdata++);
2442 if (ecpointformatlist_length != size - 1) {
2443 *al = TLS1_AD_DECODE_ERROR;
2447 s->session->tlsext_ecpointformatlist_length = 0;
2448 if (s->session->tlsext_ecpointformatlist != NULL)
2449 OPENSSL_free(s->session->tlsext_ecpointformatlist);
2450 if ((s->session->tlsext_ecpointformatlist =
2451 OPENSSL_malloc(ecpointformatlist_length)) == NULL) {
2452 *al = TLS1_AD_INTERNAL_ERROR;
2455 s->session->tlsext_ecpointformatlist_length =
2456 ecpointformatlist_length;
2457 memcpy(s->session->tlsext_ecpointformatlist, sdata,
2458 ecpointformatlist_length);
2461 # endif /* OPENSSL_NO_EC */
2463 else if (type == TLSEXT_TYPE_session_ticket) {
2464 if (s->tls_session_ticket_ext_cb &&
2465 !s->tls_session_ticket_ext_cb(s, data, size,
2466 s->tls_session_ticket_ext_cb_arg))
2468 *al = TLS1_AD_INTERNAL_ERROR;
2471 if (!tls_use_ticket(s) || (size > 0)) {
2472 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2475 s->tlsext_ticket_expected = 1;
2477 else if (type == TLSEXT_TYPE_status_request) {
2479 * MUST be empty and only sent if we've requested a status
2482 if ((s->tlsext_status_type == -1) || (size > 0)) {
2483 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2486 /* Set flag to expect CertificateStatus message */
2487 s->tlsext_status_expected = 1;
2489 # ifndef OPENSSL_NO_NEXTPROTONEG
2490 else if (type == TLSEXT_TYPE_next_proto_neg &&
2491 s->s3->tmp.finish_md_len == 0) {
2492 unsigned char *selected;
2493 unsigned char selected_len;
2495 /* We must have requested it. */
2496 if (s->ctx->next_proto_select_cb == NULL) {
2497 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2500 /* The data must be valid */
2501 if (!ssl_next_proto_validate(data, size)) {
2502 *al = TLS1_AD_DECODE_ERROR;
2506 ctx->next_proto_select_cb(s, &selected, &selected_len, data,
2508 s->ctx->next_proto_select_cb_arg) !=
2509 SSL_TLSEXT_ERR_OK) {
2510 *al = TLS1_AD_INTERNAL_ERROR;
2513 s->next_proto_negotiated = OPENSSL_malloc(selected_len);
2514 if (!s->next_proto_negotiated) {
2515 *al = TLS1_AD_INTERNAL_ERROR;
2518 memcpy(s->next_proto_negotiated, selected, selected_len);
2519 s->next_proto_negotiated_len = selected_len;
2520 s->s3->next_proto_neg_seen = 1;
2524 else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) {
2527 /* We must have requested it. */
2528 if (s->alpn_client_proto_list == NULL) {
2529 *al = TLS1_AD_UNSUPPORTED_EXTENSION;
2533 *al = TLS1_AD_DECODE_ERROR;
2537 * The extension data consists of:
2538 * uint16 list_length
2539 * uint8 proto_length;
2540 * uint8 proto[proto_length];
2545 if (len != (unsigned)size - 2) {
2546 *al = TLS1_AD_DECODE_ERROR;
2550 if (len != (unsigned)size - 3) {
2551 *al = TLS1_AD_DECODE_ERROR;
2554 if (s->s3->alpn_selected)
2555 OPENSSL_free(s->s3->alpn_selected);
2556 s->s3->alpn_selected = OPENSSL_malloc(len);
2557 if (!s->s3->alpn_selected) {
2558 *al = TLS1_AD_INTERNAL_ERROR;
2561 memcpy(s->s3->alpn_selected, data + 3, len);
2562 s->s3->alpn_selected_len = len;
2564 # ifndef OPENSSL_NO_HEARTBEATS
2565 else if (type == TLSEXT_TYPE_heartbeat) {
2567 case 0x01: /* Server allows us to send HB requests */
2568 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2570 case 0x02: /* Server doesn't accept HB requests */
2571 s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
2572 s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
2575 *al = SSL_AD_ILLEGAL_PARAMETER;
2580 # ifndef OPENSSL_NO_SRTP
2581 else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) {
2582 if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al))
2586 # ifdef TLSEXT_TYPE_encrypt_then_mac
2587 else if (type == TLSEXT_TYPE_encrypt_then_mac) {
2588 /* Ignore if inappropriate ciphersuite */
2589 if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD
2590 && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4)
2591 s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC;
2594 else if (type == TLSEXT_TYPE_extended_master_secret) {
2596 s->session->flags |= SSL_SESS_FLAG_EXTMS;
2599 * If this extension type was not otherwise handled, but matches a
2600 * custom_cli_ext_record, then send it to the c callback
2602 else if (custom_ext_parse(s, 0, type, data, size, al) <= 0)
2608 if (data != d + n) {
2609 *al = SSL_AD_DECODE_ERROR;
2613 if (!s->hit && tlsext_servername == 1) {
2614 if (s->tlsext_hostname) {
2615 if (s->session->tlsext_hostname == NULL) {
2616 s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
2617 if (!s->session->tlsext_hostname) {
2618 *al = SSL_AD_UNRECOGNIZED_NAME;
2622 *al = SSL_AD_DECODE_ERROR;
2633 * Determine if we need to see RI. Strictly speaking if we want to avoid
2634 * an attack we should *always* see RI even on initial server hello
2635 * because the client doesn't see any renegotiation during an attack.
2636 * However this would mean we could not connect to any server which
2637 * doesn't support RI so for the immediate future tolerate RI absence on
2638 * initial connect only.
2640 if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
2641 && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
2642 *al = SSL_AD_HANDSHAKE_FAILURE;
2643 SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT,
2644 SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
2651 int ssl_prepare_clienthello_tlsext(SSL *s)
2657 int ssl_prepare_serverhello_tlsext(SSL *s)
2662 static int ssl_check_clienthello_tlsext_early(SSL *s)
2664 int ret = SSL_TLSEXT_ERR_NOACK;
2665 int al = SSL_AD_UNRECOGNIZED_NAME;
2667 # ifndef OPENSSL_NO_EC
2669 * The handling of the ECPointFormats extension is done elsewhere, namely
2670 * in ssl3_choose_cipher in s3_lib.c.
2673 * The handling of the EllipticCurves extension is done elsewhere, namely
2674 * in ssl3_choose_cipher in s3_lib.c.
2678 if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
2680 s->ctx->tlsext_servername_callback(s, &al,
2681 s->ctx->tlsext_servername_arg);
2682 else if (s->initial_ctx != NULL
2683 && s->initial_ctx->tlsext_servername_callback != 0)
2685 s->initial_ctx->tlsext_servername_callback(s, &al,
2687 initial_ctx->tlsext_servername_arg);
2690 case SSL_TLSEXT_ERR_ALERT_FATAL:
2691 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2694 case SSL_TLSEXT_ERR_ALERT_WARNING:
2695 ssl3_send_alert(s, SSL3_AL_WARNING, al);
2698 case SSL_TLSEXT_ERR_NOACK:
2699 s->servername_done = 0;
2705 int tls1_set_server_sigalgs(SSL *s)
2709 /* Clear any shared sigtnature algorithms */
2710 if (s->cert->shared_sigalgs) {
2711 OPENSSL_free(s->cert->shared_sigalgs);
2712 s->cert->shared_sigalgs = NULL;
2713 s->cert->shared_sigalgslen = 0;
2715 /* Clear certificate digests and validity flags */
2716 for (i = 0; i < SSL_PKEY_NUM; i++) {
2717 s->cert->pkeys[i].digest = NULL;
2718 s->cert->pkeys[i].valid_flags = 0;
2721 /* If sigalgs received process it. */
2722 if (s->cert->peer_sigalgs) {
2723 if (!tls1_process_sigalgs(s)) {
2724 SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
2725 al = SSL_AD_INTERNAL_ERROR;
2728 /* Fatal error is no shared signature algorithms */
2729 if (!s->cert->shared_sigalgs) {
2730 SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
2731 SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
2732 al = SSL_AD_ILLEGAL_PARAMETER;
2736 ssl_cert_set_default_md(s->cert);
2739 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2743 int ssl_check_clienthello_tlsext_late(SSL *s)
2745 int ret = SSL_TLSEXT_ERR_OK;
2749 * If status request then ask callback what to do. Note: this must be
2750 * called after servername callbacks in case the certificate has changed,
2751 * and must be called after the cipher has been chosen because this may
2752 * influence which certificate is sent
2754 if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) {
2756 CERT_PKEY *certpkey;
2757 certpkey = ssl_get_server_send_pkey(s);
2758 /* If no certificate can't return certificate status */
2759 if (certpkey == NULL) {
2760 s->tlsext_status_expected = 0;
2764 * Set current certificate to one we will use so SSL_get_certificate
2765 * et al can pick it up.
2767 s->cert->key = certpkey;
2768 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2770 /* We don't want to send a status request response */
2771 case SSL_TLSEXT_ERR_NOACK:
2772 s->tlsext_status_expected = 0;
2774 /* status request response should be sent */
2775 case SSL_TLSEXT_ERR_OK:
2776 if (s->tlsext_ocsp_resp)
2777 s->tlsext_status_expected = 1;
2779 s->tlsext_status_expected = 0;
2781 /* something bad happened */
2782 case SSL_TLSEXT_ERR_ALERT_FATAL:
2783 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2784 al = SSL_AD_INTERNAL_ERROR;
2788 s->tlsext_status_expected = 0;
2792 case SSL_TLSEXT_ERR_ALERT_FATAL:
2793 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2796 case SSL_TLSEXT_ERR_ALERT_WARNING:
2797 ssl3_send_alert(s, SSL3_AL_WARNING, al);
2805 int ssl_check_serverhello_tlsext(SSL *s)
2807 int ret = SSL_TLSEXT_ERR_NOACK;
2808 int al = SSL_AD_UNRECOGNIZED_NAME;
2810 # ifndef OPENSSL_NO_EC
2812 * If we are client and using an elliptic curve cryptography cipher
2813 * suite, then if server returns an EC point formats lists extension it
2814 * must contain uncompressed.
2816 unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2817 unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2818 if ((s->tlsext_ecpointformatlist != NULL)
2819 && (s->tlsext_ecpointformatlist_length > 0)
2820 && (s->session->tlsext_ecpointformatlist != NULL)
2821 && (s->session->tlsext_ecpointformatlist_length > 0)
2822 && ((alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe))
2823 || (alg_a & SSL_aECDSA))) {
2824 /* we are using an ECC cipher */
2826 unsigned char *list;
2827 int found_uncompressed = 0;
2828 list = s->session->tlsext_ecpointformatlist;
2829 for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) {
2830 if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) {
2831 found_uncompressed = 1;
2835 if (!found_uncompressed) {
2836 SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT,
2837 SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
2841 ret = SSL_TLSEXT_ERR_OK;
2842 # endif /* OPENSSL_NO_EC */
2844 if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
2846 s->ctx->tlsext_servername_callback(s, &al,
2847 s->ctx->tlsext_servername_arg);
2848 else if (s->initial_ctx != NULL
2849 && s->initial_ctx->tlsext_servername_callback != 0)
2851 s->initial_ctx->tlsext_servername_callback(s, &al,
2853 initial_ctx->tlsext_servername_arg);
2856 * If we've requested certificate status and we wont get one tell the
2859 if ((s->tlsext_status_type != -1) && !(s->tlsext_status_expected)
2860 && s->ctx && s->ctx->tlsext_status_cb) {
2863 * Set resp to NULL, resplen to -1 so callback knows there is no
2866 if (s->tlsext_ocsp_resp) {
2867 OPENSSL_free(s->tlsext_ocsp_resp);
2868 s->tlsext_ocsp_resp = NULL;
2870 s->tlsext_ocsp_resplen = -1;
2871 r = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2873 al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2874 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2877 al = SSL_AD_INTERNAL_ERROR;
2878 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2883 case SSL_TLSEXT_ERR_ALERT_FATAL:
2884 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2887 case SSL_TLSEXT_ERR_ALERT_WARNING:
2888 ssl3_send_alert(s, SSL3_AL_WARNING, al);
2891 case SSL_TLSEXT_ERR_NOACK:
2892 s->servername_done = 0;
2898 int ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d,
2902 if (s->version < SSL3_VERSION)
2904 if (ssl_scan_serverhello_tlsext(s, p, d, n, &al) <= 0) {
2905 ssl3_send_alert(s, SSL3_AL_FATAL, al);
2909 if (ssl_check_serverhello_tlsext(s) <= 0) {
2910 SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT);
2917 * Since the server cache lookup is done early on in the processing of the
2918 * ClientHello, and other operations depend on the result, we need to handle
2919 * any TLS session ticket extension at the same time.
2921 * session_id: points at the session ID in the ClientHello. This code will
2922 * read past the end of this in order to parse out the session ticket
2923 * extension, if any.
2924 * len: the length of the session ID.
2925 * limit: a pointer to the first byte after the ClientHello.
2926 * ret: (output) on return, if a ticket was decrypted, then this is set to
2927 * point to the resulting session.
2929 * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
2930 * ciphersuite, in which case we have no use for session tickets and one will
2931 * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
2934 * -1: fatal error, either from parsing or decrypting the ticket.
2935 * 0: no ticket was found (or was ignored, based on settings).
2936 * 1: a zero length extension was found, indicating that the client supports
2937 * session tickets but doesn't currently have one to offer.
2938 * 2: either s->tls_session_secret_cb was set, or a ticket was offered but
2939 * couldn't be decrypted because of a non-fatal error.
2940 * 3: a ticket was successfully decrypted and *ret was set.
2943 * Sets s->tlsext_ticket_expected to 1 if the server will have to issue
2944 * a new session ticket to the client because the client indicated support
2945 * (and s->tls_session_secret_cb is NULL) but the client either doesn't have
2946 * a session ticket or we couldn't use the one it gave us, or if
2947 * s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
2948 * Otherwise, s->tlsext_ticket_expected is set to 0.
2950 int tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
2951 const unsigned char *limit, SSL_SESSION **ret)
2953 /* Point after session ID in client hello */
2954 const unsigned char *p = session_id + len;
2958 s->tlsext_ticket_expected = 0;
2961 * If tickets disabled behave as if no ticket present to permit stateful
2964 if (!tls_use_ticket(s))
2966 if ((s->version <= SSL3_VERSION) || !limit)
2970 /* Skip past DTLS cookie */
2971 if (SSL_IS_DTLS(s)) {
2977 /* Skip past cipher list */
2982 /* Skip past compression algorithm list */
2987 /* Now at start of extensions */
2988 if ((p + 2) >= limit)
2991 while ((p + 4) <= limit) {
2992 unsigned short type, size;
2995 if (p + size > limit)
2997 if (type == TLSEXT_TYPE_session_ticket) {
3001 * The client will accept a ticket but doesn't currently have
3004 s->tlsext_ticket_expected = 1;
3007 if (s->tls_session_secret_cb) {
3009 * Indicate that the ticket couldn't be decrypted rather than
3010 * generating the session from ticket now, trigger
3011 * abbreviated handshake based on external mechanism to
3012 * calculate the master secret later.
3016 r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
3018 case 2: /* ticket couldn't be decrypted */
3019 s->tlsext_ticket_expected = 1;
3021 case 3: /* ticket was decrypted */
3023 case 4: /* ticket decrypted but need to renew */
3024 s->tlsext_ticket_expected = 1;
3026 default: /* fatal error */
3036 * tls_decrypt_ticket attempts to decrypt a session ticket.
3038 * etick: points to the body of the session ticket extension.
3039 * eticklen: the length of the session tickets extenion.
3040 * sess_id: points at the session ID.
3041 * sesslen: the length of the session ID.
3042 * psess: (output) on return, if a ticket was decrypted, then this is set to
3043 * point to the resulting session.
3046 * -1: fatal error, either from parsing or decrypting the ticket.
3047 * 2: the ticket couldn't be decrypted.
3048 * 3: a ticket was successfully decrypted and *psess was set.
3049 * 4: same as 3, but the ticket needs to be renewed.
3051 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick,
3052 int eticklen, const unsigned char *sess_id,
3053 int sesslen, SSL_SESSION **psess)
3056 unsigned char *sdec;
3057 const unsigned char *p;
3058 int slen, mlen, renew_ticket = 0;
3059 unsigned char tick_hmac[EVP_MAX_MD_SIZE];
3062 SSL_CTX *tctx = s->initial_ctx;
3063 /* Need at least keyname + iv + some encrypted data */
3066 /* Initialize session ticket encryption and HMAC contexts */
3067 HMAC_CTX_init(&hctx);
3068 EVP_CIPHER_CTX_init(&ctx);
3069 if (tctx->tlsext_ticket_key_cb) {
3070 unsigned char *nctick = (unsigned char *)etick;
3071 int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
3080 /* Check key name matches */
3081 if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
3083 HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3084 EVP_sha256(), NULL);
3085 EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3086 tctx->tlsext_tick_aes_key, etick + 16);
3089 * Attempt to process session ticket, first conduct sanity and integrity
3092 mlen = HMAC_size(&hctx);
3094 EVP_CIPHER_CTX_cleanup(&ctx);
3098 /* Check HMAC of encrypted ticket */
3099 HMAC_Update(&hctx, etick, eticklen);
3100 HMAC_Final(&hctx, tick_hmac, NULL);
3101 HMAC_CTX_cleanup(&hctx);
3102 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) {
3103 EVP_CIPHER_CTX_cleanup(&ctx);
3106 /* Attempt to decrypt session data */
3107 /* Move p after IV to start of encrypted ticket, update length */
3108 p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3109 eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
3110 sdec = OPENSSL_malloc(eticklen);
3112 EVP_CIPHER_CTX_cleanup(&ctx);
3115 EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
3116 if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) {
3117 EVP_CIPHER_CTX_cleanup(&ctx);
3122 EVP_CIPHER_CTX_cleanup(&ctx);
3125 sess = d2i_SSL_SESSION(NULL, &p, slen);
3129 * The session ID, if non-empty, is used by some clients to detect
3130 * that the ticket has been accepted. So we copy it to the session
3131 * structure. If it is empty set length to zero as required by
3135 memcpy(sess->session_id, sess_id, sesslen);
3136 sess->session_id_length = sesslen;
3145 * For session parse failure, indicate that we need to send a new ticket.
3150 /* Tables to translate from NIDs to TLS v1.2 ids */
3157 static const tls12_lookup tls12_md[] = {
3158 {NID_md5, TLSEXT_hash_md5},
3159 {NID_sha1, TLSEXT_hash_sha1},
3160 {NID_sha224, TLSEXT_hash_sha224},
3161 {NID_sha256, TLSEXT_hash_sha256},
3162 {NID_sha384, TLSEXT_hash_sha384},
3163 {NID_sha512, TLSEXT_hash_sha512}
3166 static const tls12_lookup tls12_sig[] = {
3167 {EVP_PKEY_RSA, TLSEXT_signature_rsa},
3168 {EVP_PKEY_DSA, TLSEXT_signature_dsa},
3169 {EVP_PKEY_EC, TLSEXT_signature_ecdsa}
3172 static int tls12_find_id(int nid, const tls12_lookup *table, size_t tlen)
3175 for (i = 0; i < tlen; i++) {
3176 if (table[i].nid == nid)
3182 static int tls12_find_nid(int id, const tls12_lookup *table, size_t tlen)
3185 for (i = 0; i < tlen; i++) {
3186 if ((table[i].id) == id)
3187 return table[i].nid;
3192 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk,
3198 md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
3199 sizeof(tls12_md) / sizeof(tls12_lookup));
3202 sig_id = tls12_get_sigid(pk);
3205 p[0] = (unsigned char)md_id;
3206 p[1] = (unsigned char)sig_id;
3210 int tls12_get_sigid(const EVP_PKEY *pk)
3212 return tls12_find_id(pk->type, tls12_sig,
3213 sizeof(tls12_sig) / sizeof(tls12_lookup));
3219 const EVP_MD *(*mfunc) (void);
3222 static const tls12_hash_info tls12_md_info[] = {
3223 # ifdef OPENSSL_NO_MD5
3226 {NID_md5, 64, EVP_md5},
3228 {NID_sha1, 80, EVP_sha1},
3229 {NID_sha224, 112, EVP_sha224},
3230 {NID_sha256, 128, EVP_sha256},
3231 {NID_sha384, 192, EVP_sha384},
3232 {NID_sha512, 256, EVP_sha512}
3235 static const tls12_hash_info *tls12_get_hash_info(unsigned char hash_alg)
3239 if (hash_alg > sizeof(tls12_md_info) / sizeof(tls12_md_info[0]))
3241 return tls12_md_info + hash_alg - 1;
3244 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
3246 const tls12_hash_info *inf;
3247 if (hash_alg == TLSEXT_hash_md5 && FIPS_mode())
3249 inf = tls12_get_hash_info(hash_alg);
3250 if (!inf || !inf->mfunc)
3252 return inf->mfunc();
3255 static int tls12_get_pkey_idx(unsigned char sig_alg)
3258 # ifndef OPENSSL_NO_RSA
3259 case TLSEXT_signature_rsa:
3260 return SSL_PKEY_RSA_SIGN;
3262 # ifndef OPENSSL_NO_DSA
3263 case TLSEXT_signature_dsa:
3264 return SSL_PKEY_DSA_SIGN;
3266 # ifndef OPENSSL_NO_EC
3267 case TLSEXT_signature_ecdsa:
3268 return SSL_PKEY_ECC;
3274 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
3275 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
3276 int *psignhash_nid, const unsigned char *data)
3278 int sign_nid = 0, hash_nid = 0;
3279 if (!phash_nid && !psign_nid && !psignhash_nid)
3281 if (phash_nid || psignhash_nid) {
3282 hash_nid = tls12_find_nid(data[0], tls12_md,
3283 sizeof(tls12_md) / sizeof(tls12_lookup));
3285 *phash_nid = hash_nid;
3287 if (psign_nid || psignhash_nid) {
3288 sign_nid = tls12_find_nid(data[1], tls12_sig,
3289 sizeof(tls12_sig) / sizeof(tls12_lookup));
3291 *psign_nid = sign_nid;
3293 if (psignhash_nid) {
3294 if (sign_nid && hash_nid)
3295 OBJ_find_sigid_by_algs(psignhash_nid, hash_nid, sign_nid);
3297 *psignhash_nid = NID_undef;
3301 /* Check to see if a signature algorithm is allowed */
3302 static int tls12_sigalg_allowed(SSL *s, int op, const unsigned char *ptmp)
3304 /* See if we have an entry in the hash table and it is enabled */
3305 const tls12_hash_info *hinf = tls12_get_hash_info(ptmp[0]);
3306 if (!hinf || !hinf->mfunc)
3308 /* See if public key algorithm allowed */
3309 if (tls12_get_pkey_idx(ptmp[1]) == -1)
3311 /* Finally see if security callback allows it */
3312 return ssl_security(s, op, hinf->secbits, hinf->nid, (void *)ptmp);
3316 * Get a mask of disabled public key algorithms based on supported signature
3317 * algorithms. For example if no signature algorithm supports RSA then RSA is
3321 void ssl_set_sig_mask(unsigned long *pmask_a, SSL *s, int op)
3323 const unsigned char *sigalgs;
3324 size_t i, sigalgslen;
3325 int have_rsa = 0, have_dsa = 0, have_ecdsa = 0;
3327 * Now go through all signature algorithms seeing if we support any for
3328 * RSA, DSA, ECDSA. Do this for all versions not just TLS 1.2. To keep
3329 * down calls to security callback only check if we have to.
3331 sigalgslen = tls12_get_psigalgs(s, &sigalgs);
3332 for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) {
3333 switch (sigalgs[1]) {
3334 # ifndef OPENSSL_NO_RSA
3335 case TLSEXT_signature_rsa:
3336 if (!have_rsa && tls12_sigalg_allowed(s, op, sigalgs))
3340 # ifndef OPENSSL_NO_DSA
3341 case TLSEXT_signature_dsa:
3342 if (!have_dsa && tls12_sigalg_allowed(s, op, sigalgs))
3346 # ifndef OPENSSL_NO_EC
3347 case TLSEXT_signature_ecdsa:
3348 if (!have_ecdsa && tls12_sigalg_allowed(s, op, sigalgs))
3355 *pmask_a |= SSL_aRSA;
3357 *pmask_a |= SSL_aDSS;
3359 *pmask_a |= SSL_aECDSA;
3362 size_t tls12_copy_sigalgs(SSL *s, unsigned char *out,
3363 const unsigned char *psig, size_t psiglen)
3365 unsigned char *tmpout = out;
3367 for (i = 0; i < psiglen; i += 2, psig += 2) {
3368 if (tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, psig)) {
3369 *tmpout++ = psig[0];
3370 *tmpout++ = psig[1];
3373 return tmpout - out;
3376 /* Given preference and allowed sigalgs set shared sigalgs */
3377 static int tls12_shared_sigalgs(SSL *s, TLS_SIGALGS *shsig,
3378 const unsigned char *pref, size_t preflen,
3379 const unsigned char *allow, size_t allowlen)
3381 const unsigned char *ptmp, *atmp;
3382 size_t i, j, nmatch = 0;
3383 for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) {
3384 /* Skip disabled hashes or signature algorithms */
3385 if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SHARED, ptmp))
3387 for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) {
3388 if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) {
3391 shsig->rhash = ptmp[0];
3392 shsig->rsign = ptmp[1];
3393 tls1_lookup_sigalg(&shsig->hash_nid,
3395 &shsig->signandhash_nid, ptmp);
3405 /* Set shared signature algorithms for SSL structures */
3406 static int tls1_set_shared_sigalgs(SSL *s)
3408 const unsigned char *pref, *allow, *conf;
3409 size_t preflen, allowlen, conflen;
3411 TLS_SIGALGS *salgs = NULL;
3413 unsigned int is_suiteb = tls1_suiteb(s);
3414 if (c->shared_sigalgs) {
3415 OPENSSL_free(c->shared_sigalgs);
3416 c->shared_sigalgs = NULL;
3417 c->shared_sigalgslen = 0;
3419 /* If client use client signature algorithms if not NULL */
3420 if (!s->server && c->client_sigalgs && !is_suiteb) {
3421 conf = c->client_sigalgs;
3422 conflen = c->client_sigalgslen;
3423 } else if (c->conf_sigalgs && !is_suiteb) {
3424 conf = c->conf_sigalgs;
3425 conflen = c->conf_sigalgslen;
3427 conflen = tls12_get_psigalgs(s, &conf);
3428 if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) {
3431 allow = c->peer_sigalgs;
3432 allowlen = c->peer_sigalgslen;
3436 pref = c->peer_sigalgs;
3437 preflen = c->peer_sigalgslen;
3439 nmatch = tls12_shared_sigalgs(s, NULL, pref, preflen, allow, allowlen);
3441 salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
3444 nmatch = tls12_shared_sigalgs(s, salgs, pref, preflen, allow, allowlen);
3448 c->shared_sigalgs = salgs;
3449 c->shared_sigalgslen = nmatch;
3453 /* Set preferred digest for each key type */
3455 int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize)
3458 /* Extension ignored for inappropriate versions */
3459 if (!SSL_USE_SIGALGS(s))
3461 /* Should never happen */
3465 if (c->peer_sigalgs)
3466 OPENSSL_free(c->peer_sigalgs);
3467 c->peer_sigalgs = OPENSSL_malloc(dsize);
3468 if (!c->peer_sigalgs)
3470 c->peer_sigalgslen = dsize;
3471 memcpy(c->peer_sigalgs, data, dsize);
3475 int tls1_process_sigalgs(SSL *s)
3481 TLS_SIGALGS *sigptr;
3482 if (!tls1_set_shared_sigalgs(s))
3485 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3486 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
3488 * Use first set signature preference to force message digest,
3489 * ignoring any peer preferences.
3491 const unsigned char *sigs = NULL;
3493 sigs = c->conf_sigalgs;
3495 sigs = c->client_sigalgs;
3497 idx = tls12_get_pkey_idx(sigs[1]);
3498 md = tls12_get_hash(sigs[0]);
3499 c->pkeys[idx].digest = md;
3500 c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3501 if (idx == SSL_PKEY_RSA_SIGN) {
3502 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3503 CERT_PKEY_EXPLICIT_SIGN;
3504 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3510 for (i = 0, sigptr = c->shared_sigalgs;
3511 i < c->shared_sigalgslen; i++, sigptr++) {
3512 idx = tls12_get_pkey_idx(sigptr->rsign);
3513 if (idx > 0 && c->pkeys[idx].digest == NULL) {
3514 md = tls12_get_hash(sigptr->rhash);
3515 c->pkeys[idx].digest = md;
3516 c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
3517 if (idx == SSL_PKEY_RSA_SIGN) {
3518 c->pkeys[SSL_PKEY_RSA_ENC].valid_flags =
3519 CERT_PKEY_EXPLICIT_SIGN;
3520 c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
3526 * In strict mode leave unset digests as NULL to indicate we can't use
3527 * the certificate for signing.
3529 if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) {
3531 * Set any remaining keys to default values. NOTE: if alg is not
3532 * supported it stays as NULL.
3534 # ifndef OPENSSL_NO_DSA
3535 if (!c->pkeys[SSL_PKEY_DSA_SIGN].digest)
3536 c->pkeys[SSL_PKEY_DSA_SIGN].digest = EVP_sha1();
3538 # ifndef OPENSSL_NO_RSA
3539 if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest) {
3540 c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
3541 c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
3544 # ifndef OPENSSL_NO_EC
3545 if (!c->pkeys[SSL_PKEY_ECC].digest)
3546 c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
3552 int SSL_get_sigalgs(SSL *s, int idx,
3553 int *psign, int *phash, int *psignhash,
3554 unsigned char *rsig, unsigned char *rhash)
3556 const unsigned char *psig = s->cert->peer_sigalgs;
3561 if (idx >= (int)s->cert->peer_sigalgslen)
3568 tls1_lookup_sigalg(phash, psign, psignhash, psig);
3570 return s->cert->peer_sigalgslen / 2;
3573 int SSL_get_shared_sigalgs(SSL *s, int idx,
3574 int *psign, int *phash, int *psignhash,
3575 unsigned char *rsig, unsigned char *rhash)
3577 TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
3578 if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
3582 *phash = shsigalgs->hash_nid;
3584 *psign = shsigalgs->sign_nid;
3586 *psignhash = shsigalgs->signandhash_nid;
3588 *rsig = shsigalgs->rsign;
3590 *rhash = shsigalgs->rhash;
3591 return s->cert->shared_sigalgslen;
3594 # ifndef OPENSSL_NO_HEARTBEATS
3595 int tls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
3598 unsigned short hbtype;
3599 unsigned int payload;
3600 unsigned int padding = 16; /* Use minimum padding */
3602 if (s->msg_callback)
3603 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
3605 s, s->msg_callback_arg);
3607 /* Read type and payload length first */
3608 if (1 + 2 + 16 > length)
3609 return 0; /* silently discard */
3612 if (1 + 2 + payload + 16 > length)
3613 return 0; /* silently discard per RFC 6520 sec. 4 */
3616 if (hbtype == TLS1_HB_REQUEST) {
3617 unsigned char *buffer, *bp;
3621 * Allocate memory for the response, size is 1 bytes message type,
3622 * plus 2 bytes payload length, plus payload, plus padding
3624 buffer = OPENSSL_malloc(1 + 2 + payload + padding);
3625 if (buffer == NULL) {
3626 SSLerr(SSL_F_TLS1_PROCESS_HEARTBEAT, ERR_R_MALLOC_FAILURE);
3631 /* Enter response type, length and copy payload */
3632 *bp++ = TLS1_HB_RESPONSE;
3634 memcpy(bp, pl, payload);
3636 /* Random padding */
3637 if (RAND_bytes(bp, padding) <= 0) {
3638 OPENSSL_free(buffer);
3642 r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer,
3643 3 + payload + padding);
3645 if (r >= 0 && s->msg_callback)
3646 s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3647 buffer, 3 + payload + padding,
3648 s, s->msg_callback_arg);
3650 OPENSSL_free(buffer);
3654 } else if (hbtype == TLS1_HB_RESPONSE) {
3658 * We only send sequence numbers (2 bytes unsigned int), and 16
3659 * random bytes, so we just try to read the sequence number
3663 if (payload == 18 && seq == s->tlsext_hb_seq) {
3665 s->tlsext_hb_pending = 0;
3672 int tls1_heartbeat(SSL *s)
3674 unsigned char *buf, *p;
3676 unsigned int payload = 18; /* Sequence number + random bytes */
3677 unsigned int padding = 16; /* Use minimum padding */
3679 /* Only send if peer supports and accepts HB requests... */
3680 if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
3681 s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
3682 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
3686 /* ...and there is none in flight yet... */
3687 if (s->tlsext_hb_pending) {
3688 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
3692 /* ...and no handshake in progress. */
3693 if (SSL_in_init(s) || s->in_handshake) {
3694 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
3699 * Check if padding is too long, payload and padding must not exceed 2^14
3700 * - 3 = 16381 bytes in total.
3702 OPENSSL_assert(payload + padding <= 16381);
3705 * Create HeartBeat message, we just use a sequence number
3706 * as payload to distuingish different messages and add
3707 * some random stuff.
3708 * - Message Type, 1 byte
3709 * - Payload Length, 2 bytes (unsigned int)
3710 * - Payload, the sequence number (2 bytes uint)
3711 * - Payload, random bytes (16 bytes uint)
3714 buf = OPENSSL_malloc(1 + 2 + payload + padding);
3716 SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
3721 *p++ = TLS1_HB_REQUEST;
3722 /* Payload length (18 bytes here) */
3724 /* Sequence number */
3725 s2n(s->tlsext_hb_seq, p);
3726 /* 16 random bytes */
3727 if (RAND_bytes(p, 16) <= 0) {
3728 SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
3732 /* Random padding */
3733 if (RAND_bytes(p, padding) <= 0) {
3734 SSLerr(SSL_F_TLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
3738 ret = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
3740 if (s->msg_callback)
3741 s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
3742 buf, 3 + payload + padding,
3743 s, s->msg_callback_arg);
3745 s->tlsext_hb_pending = 1;
3754 # define MAX_SIGALGLEN (TLSEXT_hash_num * TLSEXT_signature_num * 2)
3758 int sigalgs[MAX_SIGALGLEN];
3761 static int sig_cb(const char *elem, int len, void *arg)
3763 sig_cb_st *sarg = arg;
3766 int sig_alg, hash_alg;
3769 if (sarg->sigalgcnt == MAX_SIGALGLEN)
3771 if (len > (int)(sizeof(etmp) - 1))
3773 memcpy(etmp, elem, len);
3775 p = strchr(etmp, '+');
3783 if (!strcmp(etmp, "RSA"))
3784 sig_alg = EVP_PKEY_RSA;
3785 else if (!strcmp(etmp, "DSA"))
3786 sig_alg = EVP_PKEY_DSA;
3787 else if (!strcmp(etmp, "ECDSA"))
3788 sig_alg = EVP_PKEY_EC;
3792 hash_alg = OBJ_sn2nid(p);
3793 if (hash_alg == NID_undef)
3794 hash_alg = OBJ_ln2nid(p);
3795 if (hash_alg == NID_undef)
3798 for (i = 0; i < sarg->sigalgcnt; i += 2) {
3799 if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg)
3802 sarg->sigalgs[sarg->sigalgcnt++] = hash_alg;
3803 sarg->sigalgs[sarg->sigalgcnt++] = sig_alg;
3808 * Set suppored signature algorithms based on a colon separated list of the
3809 * form sig+hash e.g. RSA+SHA512:DSA+SHA512
3811 int tls1_set_sigalgs_list(CERT *c, const char *str, int client)
3815 if (!CONF_parse_list(str, ':', 1, sig_cb, &sig))
3819 return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client);
3822 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen,
3825 unsigned char *sigalgs, *sptr;
3830 sigalgs = OPENSSL_malloc(salglen);
3831 if (sigalgs == NULL)
3833 for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
3834 rhash = tls12_find_id(*psig_nids++, tls12_md,
3835 sizeof(tls12_md) / sizeof(tls12_lookup));
3836 rsign = tls12_find_id(*psig_nids++, tls12_sig,
3837 sizeof(tls12_sig) / sizeof(tls12_lookup));
3839 if (rhash == -1 || rsign == -1)
3846 if (c->client_sigalgs)
3847 OPENSSL_free(c->client_sigalgs);
3848 c->client_sigalgs = sigalgs;
3849 c->client_sigalgslen = salglen;
3851 if (c->conf_sigalgs)
3852 OPENSSL_free(c->conf_sigalgs);
3853 c->conf_sigalgs = sigalgs;
3854 c->conf_sigalgslen = salglen;
3860 OPENSSL_free(sigalgs);
3864 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
3868 if (default_nid == -1)
3870 sig_nid = X509_get_signature_nid(x);
3872 return sig_nid == default_nid ? 1 : 0;
3873 for (i = 0; i < c->shared_sigalgslen; i++)
3874 if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
3879 /* Check to see if a certificate issuer name matches list of CA names */
3880 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
3884 nm = X509_get_issuer_name(x);
3885 for (i = 0; i < sk_X509_NAME_num(names); i++) {
3886 if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
3893 * Check certificate chain is consistent with TLS extensions and is usable by
3894 * server. This servers two purposes: it allows users to check chains before
3895 * passing them to the server and it allows the server to check chains before
3896 * attempting to use them.
3899 /* Flags which need to be set for a certificate when stict mode not set */
3901 # define CERT_PKEY_VALID_FLAGS \
3902 (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
3903 /* Strict mode flags */
3904 # define CERT_PKEY_STRICT_FLAGS \
3905 (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
3906 | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
3908 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
3913 int check_flags = 0, strict_mode;
3914 CERT_PKEY *cpk = NULL;
3916 unsigned int suiteb_flags = tls1_suiteb(s);
3917 /* idx == -1 means checking server chains */
3919 /* idx == -2 means checking client certificate chains */
3922 idx = cpk - c->pkeys;
3924 cpk = c->pkeys + idx;
3926 pk = cpk->privatekey;
3928 strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
3929 /* If no cert or key, forget it */
3932 # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
3933 /* Allow any certificate to pass test */
3934 if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) {
3935 rv = CERT_PKEY_STRICT_FLAGS | CERT_PKEY_EXPLICIT_SIGN |
3936 CERT_PKEY_VALID | CERT_PKEY_SIGN;
3937 cpk->valid_flags = rv;
3944 idx = ssl_cert_type(x, pk);
3947 cpk = c->pkeys + idx;
3948 if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
3949 check_flags = CERT_PKEY_STRICT_FLAGS;
3951 check_flags = CERT_PKEY_VALID_FLAGS;
3958 check_flags |= CERT_PKEY_SUITEB;
3959 ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags);
3960 if (ok == X509_V_OK)
3961 rv |= CERT_PKEY_SUITEB;
3962 else if (!check_flags)
3967 * Check all signature algorithms are consistent with signature
3968 * algorithms extension if TLS 1.2 or later and strict mode.
3970 if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) {
3972 unsigned char rsign = 0;
3973 if (c->peer_sigalgs)
3975 /* If no sigalgs extension use defaults from RFC5246 */
3978 case SSL_PKEY_RSA_ENC:
3979 case SSL_PKEY_RSA_SIGN:
3980 case SSL_PKEY_DH_RSA:
3981 rsign = TLSEXT_signature_rsa;
3982 default_nid = NID_sha1WithRSAEncryption;
3985 case SSL_PKEY_DSA_SIGN:
3986 case SSL_PKEY_DH_DSA:
3987 rsign = TLSEXT_signature_dsa;
3988 default_nid = NID_dsaWithSHA1;
3992 rsign = TLSEXT_signature_ecdsa;
3993 default_nid = NID_ecdsa_with_SHA1;
4002 * If peer sent no signature algorithms extension and we have set
4003 * preferred signature algorithms check we support sha1.
4005 if (default_nid > 0 && c->conf_sigalgs) {
4007 const unsigned char *p = c->conf_sigalgs;
4008 for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) {
4009 if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
4012 if (j == c->conf_sigalgslen) {
4019 /* Check signature algorithm of each cert in chain */
4020 if (!tls1_check_sig_alg(c, x, default_nid)) {
4024 rv |= CERT_PKEY_EE_SIGNATURE;
4025 rv |= CERT_PKEY_CA_SIGNATURE;
4026 for (i = 0; i < sk_X509_num(chain); i++) {
4027 if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) {
4029 rv &= ~CERT_PKEY_CA_SIGNATURE;
4036 /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
4037 else if (check_flags)
4038 rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE;
4040 /* Check cert parameters are consistent */
4041 if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
4042 rv |= CERT_PKEY_EE_PARAM;
4043 else if (!check_flags)
4046 rv |= CERT_PKEY_CA_PARAM;
4047 /* In strict mode check rest of chain too */
4048 else if (strict_mode) {
4049 rv |= CERT_PKEY_CA_PARAM;
4050 for (i = 0; i < sk_X509_num(chain); i++) {
4051 X509 *ca = sk_X509_value(chain, i);
4052 if (!tls1_check_cert_param(s, ca, 0)) {
4054 rv &= ~CERT_PKEY_CA_PARAM;
4061 if (!s->server && strict_mode) {
4062 STACK_OF(X509_NAME) *ca_dn;
4066 check_type = TLS_CT_RSA_SIGN;
4069 check_type = TLS_CT_DSS_SIGN;
4072 check_type = TLS_CT_ECDSA_SIGN;
4077 int cert_type = X509_certificate_type(x, pk);
4078 if (cert_type & EVP_PKS_RSA)
4079 check_type = TLS_CT_RSA_FIXED_DH;
4080 if (cert_type & EVP_PKS_DSA)
4081 check_type = TLS_CT_DSS_FIXED_DH;
4085 const unsigned char *ctypes;
4089 ctypelen = (int)c->ctype_num;
4091 ctypes = (unsigned char *)s->s3->tmp.ctype;
4092 ctypelen = s->s3->tmp.ctype_num;
4094 for (i = 0; i < ctypelen; i++) {
4095 if (ctypes[i] == check_type) {
4096 rv |= CERT_PKEY_CERT_TYPE;
4100 if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
4103 rv |= CERT_PKEY_CERT_TYPE;
4105 ca_dn = s->s3->tmp.ca_names;
4107 if (!sk_X509_NAME_num(ca_dn))
4108 rv |= CERT_PKEY_ISSUER_NAME;
4110 if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4111 if (ssl_check_ca_name(ca_dn, x))
4112 rv |= CERT_PKEY_ISSUER_NAME;
4114 if (!(rv & CERT_PKEY_ISSUER_NAME)) {
4115 for (i = 0; i < sk_X509_num(chain); i++) {
4116 X509 *xtmp = sk_X509_value(chain, i);
4117 if (ssl_check_ca_name(ca_dn, xtmp)) {
4118 rv |= CERT_PKEY_ISSUER_NAME;
4123 if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
4126 rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE;
4128 if (!check_flags || (rv & check_flags) == check_flags)
4129 rv |= CERT_PKEY_VALID;
4133 if (TLS1_get_version(s) >= TLS1_2_VERSION) {
4134 if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
4135 rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN;
4136 else if (cpk->digest)
4137 rv |= CERT_PKEY_SIGN;
4139 rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN;
4142 * When checking a CERT_PKEY structure all flags are irrelevant if the
4146 if (rv & CERT_PKEY_VALID)
4147 cpk->valid_flags = rv;
4149 /* Preserve explicit sign flag, clear rest */
4150 cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
4157 /* Set validity of certificates in an SSL structure */
4158 void tls1_set_cert_validity(SSL *s)
4160 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
4161 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
4162 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN);
4163 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_RSA);
4164 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DH_DSA);
4165 tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
4168 /* User level utiity function to check a chain is suitable */
4169 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
4171 return tls1_check_chain(s, x, pk, chain, -1);
4176 #ifndef OPENSSL_NO_DH
4177 DH *ssl_get_auto_dh(SSL *s)
4179 int dh_secbits = 80;
4180 if (s->cert->dh_tmp_auto == 2)
4181 return DH_get_1024_160();
4182 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
4183 if (s->s3->tmp.new_cipher->strength_bits == 256)
4188 CERT_PKEY *cpk = ssl_get_server_send_pkey(s);
4189 dh_secbits = EVP_PKEY_security_bits(cpk->privatekey);
4192 if (dh_secbits >= 128) {
4198 BN_set_word(dhp->g, 2);
4199 if (dh_secbits >= 192)
4200 dhp->p = get_rfc3526_prime_8192(NULL);
4202 dhp->p = get_rfc3526_prime_3072(NULL);
4203 if (!dhp->p || !dhp->g) {
4209 if (dh_secbits >= 112)
4210 return DH_get_2048_224();
4211 return DH_get_1024_160();
4215 static int ssl_security_cert_key(SSL *s, SSL_CTX *ctx, X509 *x, int op)
4218 EVP_PKEY *pkey = X509_get_pubkey(x);
4220 secbits = EVP_PKEY_security_bits(pkey);
4221 EVP_PKEY_free(pkey);
4225 return ssl_security(s, op, secbits, 0, x);
4227 return ssl_ctx_security(ctx, op, secbits, 0, x);
4230 static int ssl_security_cert_sig(SSL *s, SSL_CTX *ctx, X509 *x, int op)
4232 /* Lookup signature algorithm digest */
4233 int secbits = -1, md_nid = NID_undef, sig_nid;
4234 sig_nid = X509_get_signature_nid(x);
4235 if (sig_nid && OBJ_find_sigid_algs(sig_nid, &md_nid, NULL)) {
4237 if (md_nid && (md = EVP_get_digestbynid(md_nid)))
4238 secbits = EVP_MD_size(md) * 4;
4241 return ssl_security(s, op, secbits, md_nid, x);
4243 return ssl_ctx_security(ctx, op, secbits, md_nid, x);
4246 int ssl_security_cert(SSL *s, SSL_CTX *ctx, X509 *x, int vfy, int is_ee)
4249 vfy = SSL_SECOP_PEER;
4251 if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_EE_KEY | vfy))
4252 return SSL_R_EE_KEY_TOO_SMALL;
4254 if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_CA_KEY | vfy))
4255 return SSL_R_CA_KEY_TOO_SMALL;
4257 if (!ssl_security_cert_sig(s, ctx, x, SSL_SECOP_CA_MD | vfy))
4258 return SSL_R_CA_MD_TOO_WEAK;
4263 * Check security of a chain, if sk includes the end entity certificate then
4264 * x is NULL. If vfy is 1 then we are verifying a peer chain and not sending
4265 * one to the peer. Return values: 1 if ok otherwise error code to use
4268 int ssl_security_cert_chain(SSL *s, STACK_OF(X509) *sk, X509 *x, int vfy)
4270 int rv, start_idx, i;
4272 x = sk_X509_value(sk, 0);
4277 rv = ssl_security_cert(s, NULL, x, vfy, 1);
4281 for (i = start_idx; i < sk_X509_num(sk); i++) {
4282 x = sk_X509_value(sk, i);
4283 rv = ssl_security_cert(s, NULL, x, vfy, 0);