Home | History | Annotate | Download | only in ssl
      1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      2  * All rights reserved.
      3  *
      4  * This package is an SSL implementation written
      5  * by Eric Young (eay (at) cryptsoft.com).
      6  * The implementation was written so as to conform with Netscapes SSL.
      7  *
      8  * This library is free for commercial and non-commercial use as long as
      9  * the following conditions are aheared to.  The following conditions
     10  * apply to all code found in this distribution, be it the RC4, RSA,
     11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
     12  * included with this distribution is covered by the same copyright terms
     13  * except that the holder is Tim Hudson (tjh (at) cryptsoft.com).
     14  *
     15  * Copyright remains Eric Young's, and as such any Copyright notices in
     16  * the code are not to be removed.
     17  * If this package is used in a product, Eric Young should be given attribution
     18  * as the author of the parts of the library used.
     19  * This can be in the form of a textual message at program startup or
     20  * in documentation (online or textual) provided with the package.
     21  *
     22  * Redistribution and use in source and binary forms, with or without
     23  * modification, are permitted provided that the following conditions
     24  * are met:
     25  * 1. Redistributions of source code must retain the copyright
     26  *    notice, this list of conditions and the following disclaimer.
     27  * 2. Redistributions in binary form must reproduce the above copyright
     28  *    notice, this list of conditions and the following disclaimer in the
     29  *    documentation and/or other materials provided with the distribution.
     30  * 3. All advertising materials mentioning features or use of this software
     31  *    must display the following acknowledgement:
     32  *    "This product includes cryptographic software written by
     33  *     Eric Young (eay (at) cryptsoft.com)"
     34  *    The word 'cryptographic' can be left out if the rouines from the library
     35  *    being used are not cryptographic related :-).
     36  * 4. If you include any Windows specific code (or a derivative thereof) from
     37  *    the apps directory (application code) you must include an acknowledgement:
     38  *    "This product includes software written by Tim Hudson (tjh (at) cryptsoft.com)"
     39  *
     40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
     41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     50  * SUCH DAMAGE.
     51  *
     52  * The licence and distribution terms for any publically available version or
     53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
     54  * copied and put under another distribution licence
     55  * [including the GNU Public Licence.]
     56  */
     57 /* ====================================================================
     58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
     59  *
     60  * Redistribution and use in source and binary forms, with or without
     61  * modification, are permitted provided that the following conditions
     62  * are met:
     63  *
     64  * 1. Redistributions of source code must retain the above copyright
     65  *    notice, this list of conditions and the following disclaimer.
     66  *
     67  * 2. Redistributions in binary form must reproduce the above copyright
     68  *    notice, this list of conditions and the following disclaimer in
     69  *    the documentation and/or other materials provided with the
     70  *    distribution.
     71  *
     72  * 3. All advertising materials mentioning features or use of this
     73  *    software must display the following acknowledgment:
     74  *    "This product includes software developed by the OpenSSL Project
     75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
     76  *
     77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
     78  *    endorse or promote products derived from this software without
     79  *    prior written permission. For written permission, please contact
     80  *    openssl-core (at) openssl.org.
     81  *
     82  * 5. Products derived from this software may not be called "OpenSSL"
     83  *    nor may "OpenSSL" appear in their names without prior written
     84  *    permission of the OpenSSL Project.
     85  *
     86  * 6. Redistributions of any form whatsoever must retain the following
     87  *    acknowledgment:
     88  *    "This product includes software developed by the OpenSSL Project
     89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
     90  *
     91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
     92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
     95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    102  * OF THE POSSIBILITY OF SUCH DAMAGE.
    103  * ====================================================================
    104  *
    105  * This product includes cryptographic software written by Eric Young
    106  * (eay (at) cryptsoft.com).  This product includes software written by Tim
    107  * Hudson (tjh (at) cryptsoft.com). */
    108 
    109 #include <stdio.h>
    110 #include <stdlib.h>
    111 #include <assert.h>
    112 
    113 #include <openssl/bytestring.h>
    114 #include <openssl/evp.h>
    115 #include <openssl/hmac.h>
    116 #include <openssl/mem.h>
    117 #include <openssl/obj.h>
    118 #include <openssl/rand.h>
    119 
    120 #include "ssl_locl.h"
    121 static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen,
    122 				const unsigned char *sess_id, int sesslen,
    123 				SSL_SESSION **psess);
    124 static int ssl_check_clienthello_tlsext(SSL *s);
    125 static int ssl_check_serverhello_tlsext(SSL *s);
    126 
    127 SSL3_ENC_METHOD TLSv1_enc_data={
    128 	tls1_enc,
    129 	tls1_mac,
    130 	tls1_setup_key_block,
    131 	tls1_generate_master_secret,
    132 	tls1_change_cipher_state,
    133 	tls1_final_finish_mac,
    134 	TLS1_FINISH_MAC_LENGTH,
    135 	tls1_cert_verify_mac,
    136 	TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
    137 	TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
    138 	tls1_alert_code,
    139 	tls1_export_keying_material,
    140 	0,
    141 	SSL3_HM_HEADER_LENGTH,
    142 	ssl3_set_handshake_header,
    143 	ssl3_handshake_write
    144 	};
    145 
    146 SSL3_ENC_METHOD TLSv1_1_enc_data={
    147 	tls1_enc,
    148 	tls1_mac,
    149 	tls1_setup_key_block,
    150 	tls1_generate_master_secret,
    151 	tls1_change_cipher_state,
    152 	tls1_final_finish_mac,
    153 	TLS1_FINISH_MAC_LENGTH,
    154 	tls1_cert_verify_mac,
    155 	TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
    156 	TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
    157 	tls1_alert_code,
    158 	tls1_export_keying_material,
    159 	SSL_ENC_FLAG_EXPLICIT_IV,
    160 	SSL3_HM_HEADER_LENGTH,
    161 	ssl3_set_handshake_header,
    162 	ssl3_handshake_write
    163 	};
    164 
    165 SSL3_ENC_METHOD TLSv1_2_enc_data={
    166 	tls1_enc,
    167 	tls1_mac,
    168 	tls1_setup_key_block,
    169 	tls1_generate_master_secret,
    170 	tls1_change_cipher_state,
    171 	tls1_final_finish_mac,
    172 	TLS1_FINISH_MAC_LENGTH,
    173 	tls1_cert_verify_mac,
    174 	TLS_MD_CLIENT_FINISH_CONST,TLS_MD_CLIENT_FINISH_CONST_SIZE,
    175 	TLS_MD_SERVER_FINISH_CONST,TLS_MD_SERVER_FINISH_CONST_SIZE,
    176 	tls1_alert_code,
    177 	tls1_export_keying_material,
    178 	SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS|SSL_ENC_FLAG_SHA256_PRF
    179 		|SSL_ENC_FLAG_TLS1_2_CIPHERS,
    180 	SSL3_HM_HEADER_LENGTH,
    181 	ssl3_set_handshake_header,
    182 	ssl3_handshake_write
    183 	};
    184 
    185 static int compare_uint16_t(const void *p1, const void *p2)
    186 	{
    187 	uint16_t u1 = *((const uint16_t*)p1);
    188 	uint16_t u2 = *((const uint16_t*)p2);
    189 	if (u1 < u2)
    190 		{
    191 		return -1;
    192 		}
    193 	else if (u1 > u2)
    194 		{
    195 		return 1;
    196 		}
    197 	else
    198 		{
    199 		return 0;
    200 		}
    201 	}
    202 
    203 /* Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be more
    204  * than one extension of the same type in a ClientHello or ServerHello. This
    205  * function does an initial scan over the extensions block to filter those
    206  * out. */
    207 static int tls1_check_duplicate_extensions(const CBS *cbs)
    208 	{
    209 	CBS extensions = *cbs;
    210 	size_t num_extensions = 0, i = 0;
    211 	uint16_t *extension_types = NULL;
    212 	int ret = 0;
    213 
    214 	/* First pass: count the extensions. */
    215 	while (CBS_len(&extensions) > 0)
    216 		{
    217 		uint16_t type;
    218 		CBS extension;
    219 
    220 		if (!CBS_get_u16(&extensions, &type) ||
    221 			!CBS_get_u16_length_prefixed(&extensions, &extension))
    222 			{
    223 			goto done;
    224 			}
    225 
    226 		num_extensions++;
    227 		}
    228 
    229 	if (num_extensions == 0)
    230 		{
    231 		return 1;
    232 		}
    233 
    234 	extension_types = (uint16_t*)OPENSSL_malloc(sizeof(uint16_t) * num_extensions);
    235 	if (extension_types == NULL)
    236 		{
    237 		OPENSSL_PUT_ERROR(SSL, tls1_check_duplicate_extensions, ERR_R_MALLOC_FAILURE);
    238 		goto done;
    239 		}
    240 
    241 	/* Second pass: gather the extension types. */
    242 	extensions = *cbs;
    243 	for (i = 0; i < num_extensions; i++)
    244 		{
    245 		CBS extension;
    246 
    247 		if (!CBS_get_u16(&extensions, &extension_types[i]) ||
    248 			!CBS_get_u16_length_prefixed(&extensions, &extension))
    249 			{
    250 			/* This should not happen. */
    251 			goto done;
    252 			}
    253 		}
    254 	assert(CBS_len(&extensions) == 0);
    255 
    256 	/* Sort the extensions and make sure there are no duplicates. */
    257 	qsort(extension_types, num_extensions, sizeof(uint16_t), compare_uint16_t);
    258 	for (i = 1; i < num_extensions; i++)
    259 		{
    260 		if (extension_types[i-1] == extension_types[i])
    261 			{
    262 			goto done;
    263 			}
    264 		}
    265 
    266 	ret = 1;
    267 done:
    268 	if (extension_types)
    269 		OPENSSL_free(extension_types);
    270 	return ret;
    271 	}
    272 
    273 char ssl_early_callback_init(struct ssl_early_callback_ctx *ctx)
    274 	{
    275 	CBS client_hello, session_id, cipher_suites, compression_methods, extensions;
    276 
    277 	CBS_init(&client_hello, ctx->client_hello, ctx->client_hello_len);
    278 
    279 	/* Skip client version. */
    280 	if (!CBS_skip(&client_hello, 2))
    281 		return 0;
    282 
    283 	/* Skip client nonce. */
    284 	if (!CBS_skip(&client_hello, 32))
    285 		return 0;
    286 
    287 	/* Extract session_id. */
    288 	if (!CBS_get_u8_length_prefixed(&client_hello, &session_id))
    289 		return 0;
    290 	ctx->session_id = CBS_data(&session_id);
    291 	ctx->session_id_len = CBS_len(&session_id);
    292 
    293 	/* Skip past DTLS cookie */
    294 	if (SSL_IS_DTLS(ctx->ssl))
    295 		{
    296 		CBS cookie;
    297 
    298 		if (!CBS_get_u8_length_prefixed(&client_hello, &cookie))
    299 			return 0;
    300 		}
    301 
    302 	/* Extract cipher_suites. */
    303 	if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
    304 		CBS_len(&cipher_suites) < 2 ||
    305 		(CBS_len(&cipher_suites) & 1) != 0)
    306 		return 0;
    307 	ctx->cipher_suites = CBS_data(&cipher_suites);
    308 	ctx->cipher_suites_len = CBS_len(&cipher_suites);
    309 
    310 	/* Extract compression_methods. */
    311 	if (!CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
    312 		CBS_len(&compression_methods) < 1)
    313 		return 0;
    314 	ctx->compression_methods = CBS_data(&compression_methods);
    315 	ctx->compression_methods_len = CBS_len(&compression_methods);
    316 
    317 	/* If the ClientHello ends here then it's valid, but doesn't have any
    318 	 * extensions. (E.g. SSLv3.) */
    319 	if (CBS_len(&client_hello) == 0)
    320 		{
    321 		ctx->extensions = NULL;
    322 		ctx->extensions_len = 0;
    323 		return 1;
    324 		}
    325 
    326 	/* Extract extensions and check it is valid. */
    327 	if (!CBS_get_u16_length_prefixed(&client_hello, &extensions) ||
    328 		!tls1_check_duplicate_extensions(&extensions) ||
    329 		CBS_len(&client_hello) != 0)
    330 		return 0;
    331 	ctx->extensions = CBS_data(&extensions);
    332 	ctx->extensions_len = CBS_len(&extensions);
    333 
    334 	return 1;
    335 	}
    336 
    337 char
    338 SSL_early_callback_ctx_extension_get(const struct ssl_early_callback_ctx *ctx,
    339 				     uint16_t extension_type,
    340 				     const unsigned char **out_data,
    341 				     size_t *out_len)
    342 	{
    343 	CBS extensions;
    344 
    345 	CBS_init(&extensions, ctx->extensions, ctx->extensions_len);
    346 
    347 	while (CBS_len(&extensions) != 0)
    348 		{
    349 		uint16_t type;
    350 		CBS extension;
    351 
    352 		/* Decode the next extension. */
    353 		if (!CBS_get_u16(&extensions, &type) ||
    354 			!CBS_get_u16_length_prefixed(&extensions, &extension))
    355 			return 0;
    356 
    357 		if (type == extension_type)
    358 			{
    359 			*out_data = CBS_data(&extension);
    360 			*out_len = CBS_len(&extension);
    361 			return 1;
    362 			}
    363 		}
    364 
    365 	return 0;
    366 	}
    367 
    368 
    369 static const int nid_list[] =
    370 	{
    371 		NID_sect163k1, /* sect163k1 (1) */
    372 		NID_sect163r1, /* sect163r1 (2) */
    373 		NID_sect163r2, /* sect163r2 (3) */
    374 		NID_sect193r1, /* sect193r1 (4) */
    375 		NID_sect193r2, /* sect193r2 (5) */
    376 		NID_sect233k1, /* sect233k1 (6) */
    377 		NID_sect233r1, /* sect233r1 (7) */
    378 		NID_sect239k1, /* sect239k1 (8) */
    379 		NID_sect283k1, /* sect283k1 (9) */
    380 		NID_sect283r1, /* sect283r1 (10) */
    381 		NID_sect409k1, /* sect409k1 (11) */
    382 		NID_sect409r1, /* sect409r1 (12) */
    383 		NID_sect571k1, /* sect571k1 (13) */
    384 		NID_sect571r1, /* sect571r1 (14) */
    385 		NID_secp160k1, /* secp160k1 (15) */
    386 		NID_secp160r1, /* secp160r1 (16) */
    387 		NID_secp160r2, /* secp160r2 (17) */
    388 		NID_secp192k1, /* secp192k1 (18) */
    389 		NID_X9_62_prime192v1, /* secp192r1 (19) */
    390 		NID_secp224k1, /* secp224k1 (20) */
    391 		NID_secp224r1, /* secp224r1 (21) */
    392 		NID_secp256k1, /* secp256k1 (22) */
    393 		NID_X9_62_prime256v1, /* secp256r1 (23) */
    394 		NID_secp384r1, /* secp384r1 (24) */
    395 		NID_secp521r1,  /* secp521r1 (25) */
    396 		NID_brainpoolP256r1,  /* brainpoolP256r1 (26) */
    397 		NID_brainpoolP384r1,  /* brainpoolP384r1 (27) */
    398 		NID_brainpoolP512r1  /* brainpool512r1 (28) */
    399 	};
    400 
    401 static const uint8_t ecformats_default[] =
    402 	{
    403 	TLSEXT_ECPOINTFORMAT_uncompressed,
    404 	};
    405 
    406 static const uint16_t eccurves_default[] =
    407 	{
    408 		23, /* secp256r1 (23) */
    409 		24, /* secp384r1 (24) */
    410 		25, /* secp521r1 (25) */
    411 	};
    412 
    413 int tls1_ec_curve_id2nid(uint16_t curve_id)
    414 	{
    415 	/* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
    416 	if (curve_id < 1 || curve_id > sizeof(nid_list)/sizeof(nid_list[0]))
    417 		return OBJ_undef;
    418 	return nid_list[curve_id-1];
    419 	}
    420 
    421 uint16_t tls1_ec_nid2curve_id(int nid)
    422 	{
    423 	size_t i;
    424 	for (i = 0; i < sizeof(nid_list)/sizeof(nid_list[0]); i++)
    425 		{
    426 		/* nid_list[i] stores the NID corresponding to curve ID i+1. */
    427 		if (nid == nid_list[i])
    428 			return i + 1;
    429 		}
    430 	/* Use 0 for non-existent curve ID. Note: this assumes that curve ID 0
    431 	 * will never be allocated. */
    432 	return 0;
    433 	}
    434 
    435 /* tls1_get_curvelist sets |*out_curve_ids| and |*out_curve_ids_len| to the list
    436  * of allowed curve IDs. If |get_client_curves| is non-zero, return the client
    437  * curve list. Otherwise, return the preferred list. */
    438 static void tls1_get_curvelist(SSL *s, int get_client_curves,
    439 	const uint16_t **out_curve_ids, size_t *out_curve_ids_len)
    440 	{
    441 	if (get_client_curves)
    442 		{
    443 		*out_curve_ids = s->session->tlsext_ellipticcurvelist;
    444 		*out_curve_ids_len = s->session->tlsext_ellipticcurvelist_length;
    445 		return;
    446 		}
    447 
    448 	*out_curve_ids = s->tlsext_ellipticcurvelist;
    449 	*out_curve_ids_len = s->tlsext_ellipticcurvelist_length;
    450 	if (!*out_curve_ids)
    451 		{
    452 		*out_curve_ids = eccurves_default;
    453 		*out_curve_ids_len = sizeof(eccurves_default) / sizeof(eccurves_default[0]);
    454 		}
    455 	}
    456 
    457 int tls1_check_curve(SSL *s, CBS *cbs, uint16_t *out_curve_id)
    458 	{
    459 	uint8_t curve_type;
    460 	uint16_t curve_id;
    461 	const uint16_t *curves;
    462 	size_t curves_len, i;
    463 
    464 	/* Only support named curves. */
    465 	if (!CBS_get_u8(cbs, &curve_type) ||
    466 		curve_type != NAMED_CURVE_TYPE ||
    467 		!CBS_get_u16(cbs, &curve_id))
    468 		return 0;
    469 
    470 	tls1_get_curvelist(s, 0, &curves, &curves_len);
    471 	for (i = 0; i < curves_len; i++)
    472 		{
    473 		if (curve_id == curves[i])
    474 			{
    475 			*out_curve_id = curve_id;
    476 			return 1;
    477 			}
    478 		}
    479 	return 0;
    480 	}
    481 
    482 int tls1_get_shared_curve(SSL *s)
    483 	{
    484 	const uint16_t *pref, *supp;
    485 	size_t preflen, supplen, i, j;
    486 
    487 	/* Can't do anything on client side */
    488 	if (s->server == 0)
    489 		return NID_undef;
    490 
    491 	/* Return first preference shared curve */
    492 	tls1_get_curvelist(s, !!(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
    493 				&supp, &supplen);
    494 	tls1_get_curvelist(s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE),
    495 				&pref, &preflen);
    496 	for (i = 0; i < preflen; i++)
    497 		{
    498 		for (j = 0; j < supplen; j++)
    499 			{
    500 			if (pref[i] == supp[j])
    501 				return tls1_ec_curve_id2nid(pref[i]);
    502 			}
    503 		}
    504 	return NID_undef;
    505 	}
    506 
    507 /* NOTE: tls1_ec_curve_id2nid and tls1_set_curves assume that
    508  *
    509  * (a) 0 is not a valid curve ID.
    510  *
    511  * (b) The largest curve ID is 31.
    512  *
    513  * Those implementations must be revised before adding support for curve IDs
    514  * that break these assumptions. */
    515 OPENSSL_COMPILE_ASSERT(
    516 	(sizeof(nid_list) / sizeof(nid_list[0])) < 32, small_curve_ids);
    517 
    518 int tls1_set_curves(uint16_t **out_curve_ids, size_t *out_curve_ids_len,
    519 	const int *curves, size_t ncurves)
    520 	{
    521 	uint16_t *curve_ids;
    522 	size_t i;
    523 	/* Bitmap of curves included to detect duplicates: only works
    524 	 * while curve ids < 32
    525 	 */
    526 	uint32_t dup_list = 0;
    527 	curve_ids = (uint16_t*)OPENSSL_malloc(ncurves * sizeof(uint16_t));
    528 	if (!curve_ids)
    529 		return 0;
    530 	for (i = 0; i < ncurves; i++)
    531 		{
    532 		uint32_t idmask;
    533 		uint16_t id;
    534 		id = tls1_ec_nid2curve_id(curves[i]);
    535 		idmask = ((uint32_t)1) << id;
    536 		if (!id || (dup_list & idmask))
    537 			{
    538 			OPENSSL_free(curve_ids);
    539 			return 0;
    540 			}
    541 		dup_list |= idmask;
    542 		curve_ids[i] = id;
    543 		}
    544 	if (*out_curve_ids)
    545 		OPENSSL_free(*out_curve_ids);
    546 	*out_curve_ids = curve_ids;
    547 	*out_curve_ids_len = ncurves;
    548 	return 1;
    549 	}
    550 
    551 /* tls1_curve_params_from_ec_key sets |*out_curve_id| and |*out_comp_id| to the
    552  * TLS curve ID and point format, respectively, for |ec|. It returns one on
    553  * success and zero on failure. */
    554 static int tls1_curve_params_from_ec_key(uint16_t *out_curve_id, uint8_t *out_comp_id, EC_KEY *ec)
    555 	{
    556 	int nid;
    557 	uint16_t id;
    558 	const EC_GROUP *grp;
    559 	if (!ec)
    560 		return 0;
    561 
    562 	grp = EC_KEY_get0_group(ec);
    563 	if (!grp)
    564 		return 0;
    565 
    566 	/* Determine curve ID */
    567 	nid = EC_GROUP_get_curve_name(grp);
    568 	id = tls1_ec_nid2curve_id(nid);
    569 	if (!id)
    570 		return 0;
    571 
    572 	/* Set the named curve ID. Arbitrary explicit curves are not
    573 	 * supported. */
    574 	*out_curve_id = id;
    575 
    576 	if (out_comp_id)
    577 		{
    578         	if (EC_KEY_get0_public_key(ec) == NULL)
    579 			return 0;
    580 		if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED)
    581 			*out_comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime;
    582 		else
    583 			*out_comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
    584 		}
    585 	return 1;
    586 	}
    587 
    588 /* Check an EC key is compatible with extensions */
    589 static int tls1_check_ec_key(SSL *s,
    590 	const uint16_t *curve_id, const uint8_t *comp_id)
    591 	{
    592 	const uint16_t *curves;
    593 	size_t curves_len, i;
    594 	int j;
    595 	/* If point formats extension present check it, otherwise everything
    596 	 * is supported (see RFC4492).
    597 	 */
    598 	if (comp_id && s->session->tlsext_ecpointformatlist)
    599 		{
    600 		uint8_t *p = s->session->tlsext_ecpointformatlist;
    601 		size_t plen = s->session->tlsext_ecpointformatlist_length;
    602 		for (i = 0; i < plen; i++)
    603 			{
    604 			if (*comp_id == p[i])
    605 				break;
    606 			}
    607 		if (i == plen)
    608 			return 0;
    609 		}
    610 	if (!curve_id)
    611 		return 1;
    612 	/* Check curve is consistent with client and server preferences */
    613 	for (j = 0; j <= 1; j++)
    614 		{
    615 		tls1_get_curvelist(s, j, &curves, &curves_len);
    616 		for (i = 0; i < curves_len; i++)
    617 			{
    618 			if (curves[i] == *curve_id)
    619 				break;
    620 			}
    621 		if (i == curves_len)
    622 			return 0;
    623 		/* For clients can only check sent curve list */
    624 		if (!s->server)
    625 			return 1;
    626 		}
    627 	return 1;
    628 	}
    629 
    630 static void tls1_get_formatlist(SSL *s, const unsigned char **pformats,
    631 					size_t *pformatslen)
    632 	{
    633 	/* If we have a custom point format list use it otherwise
    634 	 * use default */
    635 	if (s->tlsext_ecpointformatlist)
    636 		{
    637 		*pformats = s->tlsext_ecpointformatlist;
    638 		*pformatslen = s->tlsext_ecpointformatlist_length;
    639 		}
    640 	else
    641 		{
    642 		*pformats = ecformats_default;
    643 		*pformatslen = sizeof(ecformats_default);
    644 		}
    645 	}
    646 
    647 /* Check cert parameters compatible with extensions: currently just checks
    648  * EC certificates have compatible curves and compression.
    649  */
    650 static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md)
    651 	{
    652 	uint8_t comp_id;
    653 	uint16_t curve_id;
    654 	EVP_PKEY *pkey;
    655 	int rv;
    656 	pkey = X509_get_pubkey(x);
    657 	if (!pkey)
    658 		return 0;
    659 	/* If not EC nothing to do */
    660 	if (pkey->type != EVP_PKEY_EC)
    661 		{
    662 		EVP_PKEY_free(pkey);
    663 		return 1;
    664 		}
    665 	rv = tls1_curve_params_from_ec_key(&curve_id, &comp_id, pkey->pkey.ec);
    666 	EVP_PKEY_free(pkey);
    667 	if (!rv)
    668 		return 0;
    669 	/* Can't check curve_id for client certs as we don't have a
    670 	 * supported curves extension.
    671 	 */
    672 	return tls1_check_ec_key(s, s->server ? &curve_id : NULL, &comp_id);
    673 	}
    674 /* Check EC temporary key is compatible with client extensions */
    675 int tls1_check_ec_tmp_key(SSL *s, unsigned long cid)
    676 	{
    677 	uint16_t curve_id;
    678 	EC_KEY *ec = s->cert->ecdh_tmp;
    679 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
    680 	/* Allow any curve: not just those peer supports */
    681 	if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
    682 		return 1;
    683 #endif
    684 	if (s->cert->ecdh_tmp_auto)
    685 		{
    686 		/* Need a shared curve */
    687 		return tls1_get_shared_curve(s) != NID_undef;
    688 		}
    689 	if (!ec)
    690 		{
    691 		if (s->cert->ecdh_tmp_cb)
    692 			return 1;
    693 		else
    694 			return 0;
    695 		}
    696 	if (!tls1_curve_params_from_ec_key(&curve_id, NULL, ec))
    697 		return 0;
    698 /* Set this to allow use of invalid curves for testing */
    699 #if 0
    700 	return 1;
    701 #else
    702 	return tls1_check_ec_key(s, &curve_id, NULL);
    703 #endif
    704 	}
    705 
    706 
    707 
    708 /* List of supported signature algorithms and hashes. Should make this
    709  * customisable at some point, for now include everything we support.
    710  */
    711 
    712 #define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa,
    713 
    714 #define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa,
    715 
    716 #define tlsext_sigalg(md) \
    717 		tlsext_sigalg_rsa(md) \
    718 		tlsext_sigalg_ecdsa(md)
    719 
    720 static const uint8_t tls12_sigalgs[] = {
    721 	tlsext_sigalg(TLSEXT_hash_sha512)
    722 	tlsext_sigalg(TLSEXT_hash_sha384)
    723 	tlsext_sigalg(TLSEXT_hash_sha256)
    724 	tlsext_sigalg(TLSEXT_hash_sha224)
    725 	tlsext_sigalg(TLSEXT_hash_sha1)
    726 };
    727 size_t tls12_get_psigalgs(SSL *s, const unsigned char **psigs)
    728 	{
    729 	/* If server use client authentication sigalgs if not NULL */
    730 	if (s->server && s->cert->client_sigalgs)
    731 		{
    732 		*psigs = s->cert->client_sigalgs;
    733 		return s->cert->client_sigalgslen;
    734 		}
    735 	else if (s->cert->conf_sigalgs)
    736 		{
    737 		*psigs = s->cert->conf_sigalgs;
    738 		return s->cert->conf_sigalgslen;
    739 		}
    740 	else
    741 		{
    742 		*psigs = tls12_sigalgs;
    743 		return sizeof(tls12_sigalgs);
    744 		}
    745 	}
    746 
    747 /* tls12_check_peer_sigalg parses a SignatureAndHashAlgorithm out of
    748  * |cbs|. It checks it is consistent with |s|'s sent supported
    749  * signature algorithms and, if so, writes the relevant digest into
    750  * |*out_md| and returns 1. Otherwise it returns 0 and writes an alert
    751  * into |*out_alert|.
    752  */
    753 int tls12_check_peer_sigalg(const EVP_MD **out_md, int *out_alert,
    754 	SSL *s, CBS *cbs, EVP_PKEY *pkey)
    755 	{
    756 	const unsigned char *sent_sigs;
    757 	size_t sent_sigslen, i;
    758 	int sigalg = tls12_get_sigid(pkey);
    759 	uint8_t hash, signature;
    760 	/* Should never happen */
    761 	if (sigalg == -1)
    762 		{
    763 		OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, ERR_R_INTERNAL_ERROR);
    764 		*out_alert = SSL_AD_INTERNAL_ERROR;
    765 		return 0;
    766 		}
    767 	if (!CBS_get_u8(cbs, &hash) ||
    768 		!CBS_get_u8(cbs, &signature))
    769 		{
    770 		OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_DECODE_ERROR);
    771 		*out_alert = SSL_AD_DECODE_ERROR;
    772 		return 0;
    773 		}
    774 	/* Check key type is consistent with signature */
    775 	if (sigalg != signature)
    776 		{
    777 		OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_WRONG_SIGNATURE_TYPE);
    778 		*out_alert = SSL_AD_ILLEGAL_PARAMETER;
    779 		return 0;
    780 		}
    781 	if (pkey->type == EVP_PKEY_EC)
    782 		{
    783 		uint16_t curve_id;
    784 		uint8_t comp_id;
    785 		/* Check compression and curve matches extensions */
    786 		if (!tls1_curve_params_from_ec_key(&curve_id, &comp_id, pkey->pkey.ec))
    787 			{
    788 			*out_alert = SSL_AD_INTERNAL_ERROR;
    789 			return 0;
    790 			}
    791 		if (!s->server && !tls1_check_ec_key(s, &curve_id, &comp_id))
    792 			{
    793 			OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_WRONG_CURVE);
    794 			*out_alert = SSL_AD_ILLEGAL_PARAMETER;
    795 			return 0;
    796 			}
    797 		}
    798 
    799 	/* Check signature matches a type we sent */
    800 	sent_sigslen = tls12_get_psigalgs(s, &sent_sigs);
    801 	for (i = 0; i < sent_sigslen; i+=2, sent_sigs+=2)
    802 		{
    803 		if (hash == sent_sigs[0] && signature == sent_sigs[1])
    804 			break;
    805 		}
    806 	/* Allow fallback to SHA1 if not strict mode */
    807 	if (i == sent_sigslen && (hash != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
    808 		{
    809 		OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_WRONG_SIGNATURE_TYPE);
    810 		*out_alert = SSL_AD_ILLEGAL_PARAMETER;
    811 		return 0;
    812 		}
    813 	*out_md = tls12_get_hash(hash);
    814 	if (*out_md == NULL)
    815 		{
    816 		OPENSSL_PUT_ERROR(SSL, tls12_check_peer_sigalg, SSL_R_UNKNOWN_DIGEST);
    817 		*out_alert = SSL_AD_ILLEGAL_PARAMETER;
    818 		return 0;
    819 		}
    820 	/* Store the digest used so applications can retrieve it if they
    821 	 * wish.
    822 	 */
    823 	if (s->session && s->session->sess_cert)
    824 		s->session->sess_cert->peer_key->digest = *out_md;
    825 	return 1;
    826 	}
    827 /* Get a mask of disabled algorithms: an algorithm is disabled
    828  * if it isn't supported or doesn't appear in supported signature
    829  * algorithms. Unlike ssl_cipher_get_disabled this applies to a specific
    830  * session and not global settings.
    831  *
    832  */
    833 void ssl_set_client_disabled(SSL *s)
    834 	{
    835 	CERT *c = s->cert;
    836 	const unsigned char *sigalgs;
    837 	size_t i, sigalgslen;
    838 	int have_rsa = 0, have_ecdsa = 0;
    839 	c->mask_a = 0;
    840 	c->mask_k = 0;
    841 	/* Don't allow TLS 1.2 only ciphers if we don't suppport them */
    842 	if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s))
    843 		c->mask_ssl = SSL_TLSV1_2;
    844 	else
    845 		c->mask_ssl = 0;
    846 	/* Now go through all signature algorithms seeing if we support
    847 	 * any for RSA, DSA, ECDSA. Do this for all versions not just
    848 	 * TLS 1.2.
    849 	 */
    850 	sigalgslen = tls12_get_psigalgs(s, &sigalgs);
    851 	for (i = 0; i < sigalgslen; i += 2, sigalgs += 2)
    852 		{
    853 		switch(sigalgs[1])
    854 			{
    855 		case TLSEXT_signature_rsa:
    856 			have_rsa = 1;
    857 			break;
    858 		case TLSEXT_signature_ecdsa:
    859 			have_ecdsa = 1;
    860 			break;
    861 			}
    862 		}
    863 	/* Disable auth if we don't include any appropriate signature
    864 	 * algorithms.
    865 	 */
    866 	if (!have_rsa)
    867 		{
    868 		c->mask_a |= SSL_aRSA;
    869 		}
    870 	if (!have_ecdsa)
    871 		{
    872 		c->mask_a |= SSL_aECDSA;
    873 		}
    874 	/* with PSK there must be client callback set */
    875 	if (!s->psk_client_callback)
    876 		{
    877 		c->mask_a |= SSL_aPSK;
    878 		c->mask_k |= SSL_kPSK;
    879 		}
    880 	c->valid = 1;
    881 	}
    882 
    883 /* header_len is the length of the ClientHello header written so far, used to
    884  * compute padding. It does not include the record header. Pass 0 if no padding
    885  * is to be done. */
    886 unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, size_t header_len)
    887 	{
    888 	int extdatalen=0;
    889 	unsigned char *ret = buf;
    890 	unsigned char *orig = buf;
    891 	/* See if we support any ECC ciphersuites */
    892 	int using_ecc = 0;
    893 	if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s))
    894 		{
    895 		int i;
    896 		unsigned long alg_k, alg_a;
    897 		STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s);
    898 
    899 		for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++)
    900 			{
    901 			const SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i);
    902 
    903 			alg_k = c->algorithm_mkey;
    904 			alg_a = c->algorithm_auth;
    905 			if ((alg_k & SSL_kEECDH) || (alg_a & SSL_aECDSA))
    906 				{
    907 				using_ecc = 1;
    908 				break;
    909 				}
    910 			}
    911 		}
    912 
    913 	/* don't add extensions for SSLv3 unless doing secure renegotiation */
    914 	if (s->client_version == SSL3_VERSION
    915 					&& !s->s3->send_connection_binding)
    916 		return orig;
    917 
    918 	ret+=2;
    919 
    920 	if (ret>=limit) return NULL; /* this really never occurs, but ... */
    921 
    922  	if (s->tlsext_hostname != NULL)
    923 		{
    924 		/* Add TLS extension servername to the Client Hello message */
    925 		unsigned long size_str;
    926 		long lenmax;
    927 
    928 		/* check for enough space.
    929 		   4 for the servername type and entension length
    930 		   2 for servernamelist length
    931 		   1 for the hostname type
    932 		   2 for hostname length
    933 		   + hostname length
    934 		*/
    935 
    936 		if ((lenmax = limit - ret - 9) < 0
    937 		    || (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
    938 			return NULL;
    939 
    940 		/* extension type and length */
    941 		s2n(TLSEXT_TYPE_server_name,ret);
    942 		s2n(size_str+5,ret);
    943 
    944 		/* length of servername list */
    945 		s2n(size_str+3,ret);
    946 
    947 		/* hostname type, length and hostname */
    948 		*(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
    949 		s2n(size_str,ret);
    950 		memcpy(ret, s->tlsext_hostname, size_str);
    951 		ret+=size_str;
    952 		}
    953 
    954         /* Add RI if renegotiating */
    955         if (s->renegotiate)
    956           {
    957           int el;
    958 
    959           if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
    960               {
    961               OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
    962               return NULL;
    963               }
    964 
    965           if((limit - ret - 4 - el) < 0) return NULL;
    966 
    967           s2n(TLSEXT_TYPE_renegotiate,ret);
    968           s2n(el,ret);
    969 
    970           if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
    971               {
    972               OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
    973               return NULL;
    974               }
    975 
    976           ret += el;
    977         }
    978 
    979 	if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
    980 		{
    981 		int ticklen;
    982 		if (!s->new_session && s->session && s->session->tlsext_tick)
    983 			ticklen = s->session->tlsext_ticklen;
    984 		else if (s->session && s->tlsext_session_ticket &&
    985 			 s->tlsext_session_ticket->data)
    986 			{
    987 			s->session->tlsext_tick = BUF_memdup(
    988 			       s->tlsext_session_ticket->data,
    989 			       s->tlsext_session_ticket->length);
    990 			if (!s->session->tlsext_tick)
    991 				return NULL;
    992 			ticklen = s->tlsext_session_ticket->length;
    993 			s->session->tlsext_ticklen = ticklen;
    994 			}
    995 		else
    996 			ticklen = 0;
    997 		if (ticklen == 0 && s->tlsext_session_ticket &&
    998 		    s->tlsext_session_ticket->data == NULL)
    999 			goto skip_ext;
   1000 		/* Check for enough room 2 for extension type, 2 for len
   1001  		 * rest for ticket
   1002   		 */
   1003 		if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
   1004 		s2n(TLSEXT_TYPE_session_ticket,ret);
   1005 		s2n(ticklen,ret);
   1006 		if (ticklen)
   1007 			{
   1008 			memcpy(ret, s->session->tlsext_tick, ticklen);
   1009 			ret += ticklen;
   1010 			}
   1011 		}
   1012 		skip_ext:
   1013 
   1014 	if (SSL_USE_SIGALGS(s))
   1015 		{
   1016 		size_t salglen;
   1017 		const unsigned char *salg;
   1018 		salglen = tls12_get_psigalgs(s, &salg);
   1019 		if ((size_t)(limit - ret) < salglen + 6)
   1020 			return NULL;
   1021 		s2n(TLSEXT_TYPE_signature_algorithms,ret);
   1022 		s2n(salglen + 2, ret);
   1023 		s2n(salglen, ret);
   1024 		memcpy(ret, salg, salglen);
   1025 		ret += salglen;
   1026 		}
   1027 
   1028 	if (s->ocsp_stapling_enabled)
   1029 		{
   1030 		/* The status_request extension is excessively extensible at
   1031 		 * every layer. On the client, only support requesting OCSP
   1032 		 * responses with an empty responder_id_list and no
   1033 		 * extensions. */
   1034 		if (limit - ret - 4 - 1 - 2 - 2 < 0) return NULL;
   1035 
   1036 		s2n(TLSEXT_TYPE_status_request, ret);
   1037 		s2n(1 + 2 + 2, ret);
   1038 		/* status_type */
   1039 		*(ret++) = TLSEXT_STATUSTYPE_ocsp;
   1040 		/* responder_id_list - empty */
   1041 		s2n(0, ret);
   1042 		/* request_extensions - empty */
   1043 		s2n(0, ret);
   1044 		}
   1045 
   1046 	if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
   1047 		{
   1048 		/* The client advertises an emtpy extension to indicate its
   1049 		 * support for Next Protocol Negotiation */
   1050 		if (limit - ret - 4 < 0)
   1051 			return NULL;
   1052 		s2n(TLSEXT_TYPE_next_proto_neg,ret);
   1053 		s2n(0,ret);
   1054 		}
   1055 
   1056 	if (s->signed_cert_timestamps_enabled && !s->s3->tmp.finish_md_len)
   1057 		{
   1058 		/* The client advertises an empty extension to indicate its support for
   1059 		 * certificate timestamps. */
   1060 		if (limit - ret - 4 < 0)
   1061 			return NULL;
   1062 		s2n(TLSEXT_TYPE_certificate_timestamp,ret);
   1063 		s2n(0,ret);
   1064 		}
   1065 
   1066 	if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len)
   1067 		{
   1068 		if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len)
   1069 			return NULL;
   1070 		s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
   1071 		s2n(2 + s->alpn_client_proto_list_len,ret);
   1072 		s2n(s->alpn_client_proto_list_len,ret);
   1073 		memcpy(ret, s->alpn_client_proto_list,
   1074 		       s->alpn_client_proto_list_len);
   1075 		ret += s->alpn_client_proto_list_len;
   1076 		}
   1077 
   1078 	if (s->tlsext_channel_id_enabled)
   1079 		{
   1080 		/* The client advertises an emtpy extension to indicate its
   1081 		 * support for Channel ID. */
   1082 		if (limit - ret - 4 < 0)
   1083 			return NULL;
   1084 		if (s->ctx->tlsext_channel_id_enabled_new)
   1085 			s2n(TLSEXT_TYPE_channel_id_new,ret);
   1086 		else
   1087 			s2n(TLSEXT_TYPE_channel_id,ret);
   1088 		s2n(0,ret);
   1089 		}
   1090 
   1091         if(SSL_get_srtp_profiles(s))
   1092                 {
   1093                 int el;
   1094 
   1095                 ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
   1096 
   1097                 if((limit - ret - 4 - el) < 0) return NULL;
   1098 
   1099                 s2n(TLSEXT_TYPE_use_srtp,ret);
   1100                 s2n(el,ret);
   1101 
   1102                 if(!ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
   1103 			{
   1104 			OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
   1105 			return NULL;
   1106 			}
   1107                 ret += el;
   1108                 }
   1109 
   1110 	if (using_ecc)
   1111 		{
   1112 		/* Add TLS extension ECPointFormats to the ClientHello message */
   1113 		long lenmax;
   1114 		const uint8_t *formats;
   1115 		const uint16_t *curves;
   1116 		size_t formats_len, curves_len, i;
   1117 
   1118 		tls1_get_formatlist(s, &formats, &formats_len);
   1119 
   1120 		if ((lenmax = limit - ret - 5) < 0) return NULL;
   1121 		if (formats_len > (size_t)lenmax) return NULL;
   1122 		if (formats_len > 255)
   1123 			{
   1124 			OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
   1125 			return NULL;
   1126 			}
   1127 
   1128 		s2n(TLSEXT_TYPE_ec_point_formats,ret);
   1129 		s2n(formats_len + 1,ret);
   1130 		*(ret++) = (unsigned char)formats_len;
   1131 		memcpy(ret, formats, formats_len);
   1132 		ret+=formats_len;
   1133 
   1134 		/* Add TLS extension EllipticCurves to the ClientHello message */
   1135 		tls1_get_curvelist(s, 0, &curves, &curves_len);
   1136 
   1137 		if ((lenmax = limit - ret - 6) < 0) return NULL;
   1138 		if ((curves_len * 2) > (size_t)lenmax) return NULL;
   1139 		if ((curves_len * 2) > 65532)
   1140 			{
   1141 			OPENSSL_PUT_ERROR(SSL, ssl_add_clienthello_tlsext, ERR_R_INTERNAL_ERROR);
   1142 			return NULL;
   1143 			}
   1144 
   1145 		s2n(TLSEXT_TYPE_elliptic_curves,ret);
   1146 		s2n((curves_len * 2) + 2, ret);
   1147 
   1148 		/* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
   1149 		 * elliptic_curve_list, but the examples use two bytes.
   1150 		 * http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
   1151 		 * resolves this to two bytes.
   1152 		 */
   1153 		s2n(curves_len * 2, ret);
   1154 		for (i = 0; i < curves_len; i++)
   1155 			{
   1156 			s2n(curves[i], ret);
   1157 			}
   1158 		}
   1159 
   1160 #ifdef TLSEXT_TYPE_padding
   1161 	/* Add padding to workaround bugs in F5 terminators.
   1162 	 * See https://tools.ietf.org/html/draft-agl-tls-padding-03
   1163 	 *
   1164 	 * NB: because this code works out the length of all existing
   1165 	 * extensions it MUST always appear last. */
   1166 	if (header_len > 0)
   1167 		{
   1168 		header_len += ret - orig;
   1169 		if (header_len > 0xff && header_len < 0x200)
   1170 			{
   1171 			size_t padding_len = 0x200 - header_len;
   1172 			/* Extensions take at least four bytes to encode. Always
   1173 			 * include least one byte of data if including the
   1174 			 * extension. WebSphere Application Server 7.0 is
   1175 			 * intolerant to the last extension being zero-length. */
   1176 			if (padding_len >= 4 + 1)
   1177 				padding_len -= 4;
   1178 			else
   1179 				padding_len = 1;
   1180 			if (limit - ret - 4 - (long)padding_len < 0)
   1181 				return NULL;
   1182 
   1183 			s2n(TLSEXT_TYPE_padding, ret);
   1184 			s2n(padding_len, ret);
   1185 			memset(ret, 0, padding_len);
   1186 			ret += padding_len;
   1187 			}
   1188 		}
   1189 #endif
   1190 
   1191 	if ((extdatalen = ret-orig-2)== 0)
   1192 		return orig;
   1193 
   1194 	s2n(extdatalen, orig);
   1195 	return ret;
   1196 	}
   1197 
   1198 unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit)
   1199 	{
   1200 	int extdatalen=0;
   1201 	unsigned char *orig = buf;
   1202 	unsigned char *ret = buf;
   1203 	int next_proto_neg_seen;
   1204 	unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
   1205 	unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
   1206 	int using_ecc = (alg_k & SSL_kEECDH) || (alg_a & SSL_aECDSA);
   1207 	using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL);
   1208 	/* don't add extensions for SSLv3, unless doing secure renegotiation */
   1209 	if (s->version == SSL3_VERSION && !s->s3->send_connection_binding)
   1210 		return orig;
   1211 
   1212 	ret+=2;
   1213 	if (ret>=limit) return NULL; /* this really never occurs, but ... */
   1214 
   1215 	if (!s->hit && s->should_ack_sni && s->session->tlsext_hostname != NULL)
   1216 		{
   1217 		if ((long)(limit - ret - 4) < 0) return NULL;
   1218 
   1219 		s2n(TLSEXT_TYPE_server_name,ret);
   1220 		s2n(0,ret);
   1221 		}
   1222 
   1223 	if(s->s3->send_connection_binding)
   1224         {
   1225           int el;
   1226 
   1227           if(!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0))
   1228               {
   1229               OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
   1230               return NULL;
   1231               }
   1232 
   1233           if((limit - ret - 4 - el) < 0) return NULL;
   1234 
   1235           s2n(TLSEXT_TYPE_renegotiate,ret);
   1236           s2n(el,ret);
   1237 
   1238           if(!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el))
   1239               {
   1240               OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
   1241               return NULL;
   1242               }
   1243 
   1244           ret += el;
   1245         }
   1246 
   1247 	if (using_ecc)
   1248 		{
   1249 		const unsigned char *plist;
   1250 		size_t plistlen;
   1251 		/* Add TLS extension ECPointFormats to the ServerHello message */
   1252 		long lenmax;
   1253 
   1254 		tls1_get_formatlist(s, &plist, &plistlen);
   1255 
   1256 		if ((lenmax = limit - ret - 5) < 0) return NULL;
   1257 		if (plistlen > (size_t)lenmax) return NULL;
   1258 		if (plistlen > 255)
   1259 			{
   1260 			OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
   1261 			return NULL;
   1262 			}
   1263 
   1264 		s2n(TLSEXT_TYPE_ec_point_formats,ret);
   1265 		s2n(plistlen + 1,ret);
   1266 		*(ret++) = (unsigned char) plistlen;
   1267 		memcpy(ret, plist, plistlen);
   1268 		ret+=plistlen;
   1269 
   1270 		}
   1271 	/* Currently the server should not respond with a SupportedCurves extension */
   1272 
   1273 	if (s->tlsext_ticket_expected
   1274 		&& !(SSL_get_options(s) & SSL_OP_NO_TICKET))
   1275 		{
   1276 		if ((long)(limit - ret - 4) < 0) return NULL;
   1277 		s2n(TLSEXT_TYPE_session_ticket,ret);
   1278 		s2n(0,ret);
   1279 		}
   1280 
   1281 	if (s->s3->tmp.certificate_status_expected)
   1282 		{
   1283 		if ((long)(limit - ret - 4) < 0) return NULL;
   1284 		s2n(TLSEXT_TYPE_status_request,ret);
   1285 		s2n(0,ret);
   1286 		}
   1287 
   1288         if(s->srtp_profile)
   1289                 {
   1290                 int el;
   1291 
   1292                 ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0);
   1293 
   1294                 if((limit - ret - 4 - el) < 0) return NULL;
   1295 
   1296                 s2n(TLSEXT_TYPE_use_srtp,ret);
   1297                 s2n(el,ret);
   1298 
   1299                 if(!ssl_add_serverhello_use_srtp_ext(s, ret, &el, el))
   1300 			{
   1301 			OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, ERR_R_INTERNAL_ERROR);
   1302 			return NULL;
   1303 			}
   1304                 ret+=el;
   1305                 }
   1306 
   1307 	next_proto_neg_seen = s->s3->next_proto_neg_seen;
   1308 	s->s3->next_proto_neg_seen = 0;
   1309 	if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb)
   1310 		{
   1311 		const unsigned char *npa;
   1312 		unsigned int npalen;
   1313 		int r;
   1314 
   1315 		r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s->ctx->next_protos_advertised_cb_arg);
   1316 		if (r == SSL_TLSEXT_ERR_OK)
   1317 			{
   1318 			if ((long)(limit - ret - 4 - npalen) < 0) return NULL;
   1319 			s2n(TLSEXT_TYPE_next_proto_neg,ret);
   1320 			s2n(npalen,ret);
   1321 			memcpy(ret, npa, npalen);
   1322 			ret += npalen;
   1323 			s->s3->next_proto_neg_seen = 1;
   1324 			}
   1325 		}
   1326 
   1327 	if (s->s3->alpn_selected)
   1328 		{
   1329 		const uint8_t *selected = s->s3->alpn_selected;
   1330 		size_t len = s->s3->alpn_selected_len;
   1331 
   1332 		if ((long)(limit - ret - 4 - 2 - 1 - len) < 0)
   1333 			return NULL;
   1334 		s2n(TLSEXT_TYPE_application_layer_protocol_negotiation,ret);
   1335 		s2n(3 + len,ret);
   1336 		s2n(1 + len,ret);
   1337 		*ret++ = len;
   1338 		memcpy(ret, selected, len);
   1339 		ret += len;
   1340 		}
   1341 
   1342 	/* If the client advertised support for Channel ID, and we have it
   1343 	 * enabled, then we want to echo it back. */
   1344 	if (s->s3->tlsext_channel_id_valid)
   1345 		{
   1346 		if (limit - ret - 4 < 0)
   1347 			return NULL;
   1348 		if (s->s3->tlsext_channel_id_new)
   1349 			s2n(TLSEXT_TYPE_channel_id_new,ret);
   1350 		else
   1351 			s2n(TLSEXT_TYPE_channel_id,ret);
   1352 		s2n(0,ret);
   1353 		}
   1354 
   1355 	if ((extdatalen = ret-orig-2) == 0)
   1356 		return orig;
   1357 
   1358 	s2n(extdatalen, orig);
   1359 	return ret;
   1360 	}
   1361 
   1362 /* tls1_alpn_handle_client_hello is called to process the ALPN extension in a
   1363  * ClientHello.
   1364  *   cbs: the contents of the extension, not including the type and length.
   1365  *   out_alert: a pointer to the alert value to send in the event of a zero
   1366  *       return.
   1367  *
   1368  *   returns: 1 on success. */
   1369 static int tls1_alpn_handle_client_hello(SSL *s, CBS *cbs, int *out_alert)
   1370 	{
   1371 	CBS protocol_name_list, protocol_name_list_copy;
   1372 	const unsigned char *selected;
   1373 	unsigned char selected_len;
   1374 	int r;
   1375 
   1376 	if (s->ctx->alpn_select_cb == NULL)
   1377 		return 1;
   1378 
   1379 	if (!CBS_get_u16_length_prefixed(cbs, &protocol_name_list) ||
   1380 		CBS_len(cbs) != 0 ||
   1381 		CBS_len(&protocol_name_list) < 2)
   1382 		goto parse_error;
   1383 
   1384 	/* Validate the protocol list. */
   1385 	protocol_name_list_copy = protocol_name_list;
   1386 	while (CBS_len(&protocol_name_list_copy) > 0)
   1387 		{
   1388 		CBS protocol_name;
   1389 
   1390 		if (!CBS_get_u8_length_prefixed(&protocol_name_list_copy, &protocol_name))
   1391 			goto parse_error;
   1392 		}
   1393 
   1394 	r = s->ctx->alpn_select_cb(s, &selected, &selected_len,
   1395 		CBS_data(&protocol_name_list), CBS_len(&protocol_name_list),
   1396 		s->ctx->alpn_select_cb_arg);
   1397 	if (r == SSL_TLSEXT_ERR_OK) {
   1398 		if (s->s3->alpn_selected)
   1399 			OPENSSL_free(s->s3->alpn_selected);
   1400 		s->s3->alpn_selected = BUF_memdup(selected, selected_len);
   1401 		if (!s->s3->alpn_selected)
   1402 			{
   1403 			*out_alert = SSL_AD_INTERNAL_ERROR;
   1404 			return 0;
   1405 			}
   1406 		s->s3->alpn_selected_len = selected_len;
   1407 	}
   1408 	return 1;
   1409 
   1410 parse_error:
   1411 	*out_alert = SSL_AD_DECODE_ERROR;
   1412 	return 0;
   1413 	}
   1414 
   1415 static int ssl_scan_clienthello_tlsext(SSL *s, CBS *cbs, int *out_alert)
   1416 	{
   1417 	int renegotiate_seen = 0;
   1418 	CBS extensions;
   1419 	size_t i;
   1420 
   1421 	s->should_ack_sni = 0;
   1422 	s->s3->next_proto_neg_seen = 0;
   1423 	s->s3->tmp.certificate_status_expected = 0;
   1424 
   1425 	if (s->s3->alpn_selected)
   1426 		{
   1427 		OPENSSL_free(s->s3->alpn_selected);
   1428 		s->s3->alpn_selected = NULL;
   1429 		}
   1430 
   1431 	/* Clear any signature algorithms extension received */
   1432 	if (s->cert->peer_sigalgs)
   1433 		{
   1434 		OPENSSL_free(s->cert->peer_sigalgs);
   1435 		s->cert->peer_sigalgs = NULL;
   1436 		}
   1437 	/* Clear any shared sigtnature algorithms */
   1438 	if (s->cert->shared_sigalgs)
   1439 		{
   1440 		OPENSSL_free(s->cert->shared_sigalgs);
   1441 		s->cert->shared_sigalgs = NULL;
   1442 		}
   1443 	/* Clear certificate digests and validity flags */
   1444 	for (i = 0; i < SSL_PKEY_NUM; i++)
   1445 		{
   1446 		s->cert->pkeys[i].digest = NULL;
   1447 		s->cert->pkeys[i].valid_flags = 0;
   1448 		}
   1449 
   1450 	/* There may be no extensions. */
   1451 	if (CBS_len(cbs) == 0)
   1452 		{
   1453 		goto ri_check;
   1454 		}
   1455 
   1456 	/* Decode the extensions block and check it is valid. */
   1457 	if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
   1458 		!tls1_check_duplicate_extensions(&extensions))
   1459 		{
   1460 		*out_alert = SSL_AD_DECODE_ERROR;
   1461 		return 0;
   1462 		}
   1463 
   1464 	while (CBS_len(&extensions) != 0)
   1465 		{
   1466 		uint16_t type;
   1467 		CBS extension;
   1468 
   1469 		/* Decode the next extension. */
   1470 		if (!CBS_get_u16(&extensions, &type) ||
   1471 			!CBS_get_u16_length_prefixed(&extensions, &extension))
   1472 			{
   1473 			*out_alert = SSL_AD_DECODE_ERROR;
   1474 			return 0;
   1475 			}
   1476 
   1477 		if (s->tlsext_debug_cb)
   1478 			{
   1479 			s->tlsext_debug_cb(s, 0, type, (unsigned char*)CBS_data(&extension),
   1480 				CBS_len(&extension), s->tlsext_debug_arg);
   1481 			}
   1482 
   1483 /* The servername extension is treated as follows:
   1484 
   1485    - Only the hostname type is supported with a maximum length of 255.
   1486    - The servername is rejected if too long or if it contains zeros,
   1487      in which case an fatal alert is generated.
   1488    - The servername field is maintained together with the session cache.
   1489    - When a session is resumed, the servername call back invoked in order
   1490      to allow the application to position itself to the right context.
   1491    - The servername is acknowledged if it is new for a session or when
   1492      it is identical to a previously used for the same session.
   1493      Applications can control the behaviour.  They can at any time
   1494      set a 'desirable' servername for a new SSL object. This can be the
   1495      case for example with HTTPS when a Host: header field is received and
   1496      a renegotiation is requested. In this case, a possible servername
   1497      presented in the new client hello is only acknowledged if it matches
   1498      the value of the Host: field.
   1499    - Applications must  use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
   1500      if they provide for changing an explicit servername context for the session,
   1501      i.e. when the session has been established with a servername extension.
   1502    - On session reconnect, the servername extension may be absent.
   1503 
   1504 */
   1505 
   1506 		if (type == TLSEXT_TYPE_server_name)
   1507 			{
   1508 			CBS server_name_list;
   1509 			char have_seen_host_name = 0;
   1510 
   1511 			if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
   1512 				CBS_len(&server_name_list) < 1 ||
   1513 				CBS_len(&extension) != 0)
   1514 				{
   1515 				*out_alert = SSL_AD_DECODE_ERROR;
   1516 				return 0;
   1517 				}
   1518 
   1519 			/* Decode each ServerName in the extension. */
   1520 			while (CBS_len(&server_name_list) > 0)
   1521 				{
   1522 				uint8_t name_type;
   1523 				CBS host_name;
   1524 
   1525 				/* Decode the NameType. */
   1526 				if (!CBS_get_u8(&server_name_list, &name_type))
   1527 					{
   1528 					*out_alert = SSL_AD_DECODE_ERROR;
   1529 					return 0;
   1530 					}
   1531 
   1532 				/* Only host_name is supported. */
   1533 				if (name_type != TLSEXT_NAMETYPE_host_name)
   1534 					continue;
   1535 
   1536 				if (have_seen_host_name)
   1537 					{
   1538 					/* The ServerNameList MUST NOT contain
   1539 					 * more than one name of the same
   1540 					 * name_type. */
   1541 					*out_alert = SSL_AD_DECODE_ERROR;
   1542 					return 0;
   1543 					}
   1544 
   1545 				have_seen_host_name = 1;
   1546 
   1547 				if (!CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
   1548 					CBS_len(&host_name) < 1)
   1549 					{
   1550 					*out_alert = SSL_AD_DECODE_ERROR;
   1551 					return 0;
   1552 					}
   1553 
   1554 				if (CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||
   1555 					CBS_contains_zero_byte(&host_name))
   1556 					{
   1557 					*out_alert = SSL_AD_UNRECOGNIZED_NAME;
   1558 					return 0;
   1559 					}
   1560 
   1561 				if (!s->hit)
   1562 					{
   1563 					assert(s->session->tlsext_hostname == NULL);
   1564 					if (s->session->tlsext_hostname)
   1565 						{
   1566 						/* This should be impossible. */
   1567 						*out_alert = SSL_AD_DECODE_ERROR;
   1568 						return 0;
   1569 						}
   1570 
   1571 					/* Copy the hostname as a string. */
   1572 					if (!CBS_strdup(&host_name, &s->session->tlsext_hostname))
   1573 						{
   1574 						*out_alert = SSL_AD_INTERNAL_ERROR;
   1575 						return 0;
   1576 						}
   1577 
   1578 					s->should_ack_sni = 1;
   1579 					}
   1580 				}
   1581 			}
   1582 
   1583 		else if (type == TLSEXT_TYPE_ec_point_formats)
   1584 			{
   1585 			CBS ec_point_format_list;
   1586 
   1587 			if (!CBS_get_u8_length_prefixed(&extension, &ec_point_format_list) ||
   1588 				CBS_len(&extension) != 0)
   1589 				{
   1590 				*out_alert = SSL_AD_DECODE_ERROR;
   1591 				return 0;
   1592 				}
   1593 
   1594 			if (!s->hit)
   1595 				{
   1596 				if (!CBS_stow(&ec_point_format_list,
   1597 						&s->session->tlsext_ecpointformatlist,
   1598 						&s->session->tlsext_ecpointformatlist_length))
   1599 					{
   1600 					*out_alert = SSL_AD_INTERNAL_ERROR;
   1601 					return 0;
   1602 					}
   1603 				}
   1604 			}
   1605 		else if (type == TLSEXT_TYPE_elliptic_curves)
   1606 			{
   1607 			CBS elliptic_curve_list;
   1608 			size_t i, num_curves;
   1609 
   1610 			if (!CBS_get_u16_length_prefixed(&extension, &elliptic_curve_list) ||
   1611 				CBS_len(&elliptic_curve_list) == 0 ||
   1612 				(CBS_len(&elliptic_curve_list) & 1) != 0 ||
   1613 				CBS_len(&extension) != 0)
   1614 				{
   1615 				*out_alert = SSL_AD_DECODE_ERROR;
   1616 				return 0;
   1617 				}
   1618 
   1619 			if (!s->hit)
   1620 				{
   1621 				if (s->session->tlsext_ellipticcurvelist)
   1622 					{
   1623 					OPENSSL_free(s->session->tlsext_ellipticcurvelist);
   1624 					s->session->tlsext_ellipticcurvelist_length = 0;
   1625 					}
   1626 				s->session->tlsext_ellipticcurvelist =
   1627 					(uint16_t*)OPENSSL_malloc(CBS_len(&elliptic_curve_list));
   1628 				if (s->session->tlsext_ellipticcurvelist == NULL)
   1629 					{
   1630 					*out_alert = SSL_AD_INTERNAL_ERROR;
   1631 					return 0;
   1632 					}
   1633 				num_curves = CBS_len(&elliptic_curve_list) / 2;
   1634 				for (i = 0; i < num_curves; i++)
   1635 					{
   1636 					if (!CBS_get_u16(&elliptic_curve_list,
   1637 							&s->session->tlsext_ellipticcurvelist[i]))
   1638 						{
   1639 						*out_alert = SSL_AD_INTERNAL_ERROR;
   1640 						return 0;
   1641 						}
   1642 					}
   1643 				if (CBS_len(&elliptic_curve_list) != 0)
   1644 					{
   1645 					*out_alert = SSL_AD_INTERNAL_ERROR;
   1646 					return 0;
   1647 					}
   1648 				s->session->tlsext_ellipticcurvelist_length = num_curves;
   1649 				}
   1650 			}
   1651 		else if (type == TLSEXT_TYPE_session_ticket)
   1652 			{
   1653 			if (s->tls_session_ticket_ext_cb &&
   1654 				!s->tls_session_ticket_ext_cb(s, CBS_data(&extension), CBS_len(&extension), s->tls_session_ticket_ext_cb_arg))
   1655 				{
   1656 				*out_alert = SSL_AD_INTERNAL_ERROR;
   1657 				return 0;
   1658 				}
   1659 			}
   1660 		else if (type == TLSEXT_TYPE_renegotiate)
   1661 			{
   1662 			if (!ssl_parse_clienthello_renegotiate_ext(s, &extension, out_alert))
   1663 				return 0;
   1664 			renegotiate_seen = 1;
   1665 			}
   1666 		else if (type == TLSEXT_TYPE_signature_algorithms)
   1667 			{
   1668 			CBS supported_signature_algorithms;
   1669 
   1670 			if (!CBS_get_u16_length_prefixed(&extension, &supported_signature_algorithms) ||
   1671 				CBS_len(&extension) != 0)
   1672 				{
   1673 				*out_alert = SSL_AD_DECODE_ERROR;
   1674 				return 0;
   1675 				}
   1676 
   1677 			/* Ensure the signature algorithms are non-empty. It
   1678 			 * contains a list of SignatureAndHashAlgorithms
   1679 			 * which are two bytes each. */
   1680 			if (CBS_len(&supported_signature_algorithms) == 0 ||
   1681 				(CBS_len(&supported_signature_algorithms) % 2) != 0)
   1682 				{
   1683 				*out_alert = SSL_AD_DECODE_ERROR;
   1684 				return 0;
   1685 				}
   1686 
   1687 			if (!tls1_process_sigalgs(s, &supported_signature_algorithms))
   1688 				{
   1689 				*out_alert = SSL_AD_DECODE_ERROR;
   1690 				return 0;
   1691 				}
   1692 			/* If sigalgs received and no shared algorithms fatal
   1693 			 * error.
   1694 			 */
   1695 			if (s->cert->peer_sigalgs && !s->cert->shared_sigalgs)
   1696 				{
   1697 				OPENSSL_PUT_ERROR(SSL, ssl_add_serverhello_tlsext, SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
   1698 				*out_alert = SSL_AD_ILLEGAL_PARAMETER;
   1699 				return 0;
   1700 				}
   1701 			}
   1702 
   1703 		else if (type == TLSEXT_TYPE_next_proto_neg &&
   1704 			 s->s3->tmp.finish_md_len == 0 &&
   1705 			 s->s3->alpn_selected == NULL)
   1706 			{
   1707 			/* The extension must be empty. */
   1708 			if (CBS_len(&extension) != 0)
   1709 				{
   1710 				*out_alert = SSL_AD_DECODE_ERROR;
   1711 				return 0;
   1712 				}
   1713 
   1714 			/* We shouldn't accept this extension on a
   1715 			 * renegotiation.
   1716 			 *
   1717 			 * s->new_session will be set on renegotiation, but we
   1718 			 * probably shouldn't rely that it couldn't be set on
   1719 			 * the initial renegotation too in certain cases (when
   1720 			 * there's some other reason to disallow resuming an
   1721 			 * earlier session -- the current code won't be doing
   1722 			 * anything like that, but this might change).
   1723 
   1724 			 * A valid sign that there's been a previous handshake
   1725 			 * in this connection is if s->s3->tmp.finish_md_len >
   1726 			 * 0.  (We are talking about a check that will happen
   1727 			 * in the Hello protocol round, well before a new
   1728 			 * Finished message could have been computed.) */
   1729 			s->s3->next_proto_neg_seen = 1;
   1730 			}
   1731 
   1732 		else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation &&
   1733 			 s->ctx->alpn_select_cb &&
   1734 			 s->s3->tmp.finish_md_len == 0)
   1735 			{
   1736 			if (!tls1_alpn_handle_client_hello(s, &extension, out_alert))
   1737 				return 0;
   1738 			/* ALPN takes precedence over NPN. */
   1739 			s->s3->next_proto_neg_seen = 0;
   1740 			}
   1741 
   1742 		else if (type == TLSEXT_TYPE_channel_id &&
   1743 			 s->tlsext_channel_id_enabled)
   1744 			{
   1745 			/* The extension must be empty. */
   1746 			if (CBS_len(&extension) != 0)
   1747 				{
   1748 				*out_alert = SSL_AD_DECODE_ERROR;
   1749 				return 0;
   1750 				}
   1751 
   1752 			s->s3->tlsext_channel_id_valid = 1;
   1753 			}
   1754 
   1755 		else if (type == TLSEXT_TYPE_channel_id_new &&
   1756 			 s->tlsext_channel_id_enabled)
   1757 			{
   1758 			/* The extension must be empty. */
   1759 			if (CBS_len(&extension) != 0)
   1760 				{
   1761 				*out_alert = SSL_AD_DECODE_ERROR;
   1762 				return 0;
   1763 				}
   1764 
   1765 			s->s3->tlsext_channel_id_valid = 1;
   1766 			s->s3->tlsext_channel_id_new = 1;
   1767 			}
   1768 
   1769 
   1770 		/* session ticket processed earlier */
   1771 		else if (type == TLSEXT_TYPE_use_srtp)
   1772                         {
   1773 			if (!ssl_parse_clienthello_use_srtp_ext(s, &extension, out_alert))
   1774 				return 0;
   1775                         }
   1776 		}
   1777 
   1778 	ri_check:
   1779 
   1780 	/* Need RI if renegotiating */
   1781 
   1782 	if (!renegotiate_seen && s->renegotiate &&
   1783 		!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
   1784 		{
   1785 		*out_alert = SSL_AD_HANDSHAKE_FAILURE;
   1786 		OPENSSL_PUT_ERROR(SSL, ssl_scan_clienthello_tlsext, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
   1787 		return 0;
   1788 		}
   1789 	/* If no signature algorithms extension set default values */
   1790 	if (!s->cert->peer_sigalgs)
   1791 		ssl_cert_set_default_md(s->cert);
   1792 
   1793 	return 1;
   1794 	}
   1795 
   1796 int ssl_parse_clienthello_tlsext(SSL *s, CBS *cbs)
   1797 	{
   1798 	int alert = -1;
   1799 	if (ssl_scan_clienthello_tlsext(s, cbs, &alert) <= 0)
   1800 		{
   1801 		ssl3_send_alert(s, SSL3_AL_FATAL, alert);
   1802 		return 0;
   1803 		}
   1804 
   1805 	if (ssl_check_clienthello_tlsext(s) <= 0)
   1806 		{
   1807 		OPENSSL_PUT_ERROR(SSL, ssl_parse_clienthello_tlsext, SSL_R_CLIENTHELLO_TLSEXT);
   1808 		return 0;
   1809 		}
   1810 	return 1;
   1811 	}
   1812 
   1813 /* ssl_next_proto_validate validates a Next Protocol Negotiation block. No
   1814  * elements of zero length are allowed and the set of elements must exactly fill
   1815  * the length of the block. */
   1816 static char ssl_next_proto_validate(const CBS *cbs)
   1817 	{
   1818 	CBS copy = *cbs;
   1819 
   1820 	while (CBS_len(&copy) != 0)
   1821 		{
   1822 		CBS proto;
   1823 		if (!CBS_get_u8_length_prefixed(&copy, &proto) ||
   1824 			CBS_len(&proto) == 0)
   1825 			{
   1826 			return 0;
   1827 			}
   1828 		}
   1829 	return 1;
   1830 	}
   1831 
   1832 static int ssl_scan_serverhello_tlsext(SSL *s, CBS *cbs, int *out_alert)
   1833 	{
   1834 	int tlsext_servername = 0;
   1835 	int renegotiate_seen = 0;
   1836 	CBS extensions;
   1837 
   1838 	/* TODO(davidben): Move all of these to some per-handshake state that
   1839 	 * gets systematically reset on a new handshake; perhaps allocate it
   1840 	 * fresh each time so it's not even kept around post-handshake. */
   1841 	s->s3->next_proto_neg_seen = 0;
   1842 
   1843 	s->tlsext_ticket_expected = 0;
   1844 	s->s3->tmp.certificate_status_expected = 0;
   1845 
   1846 	if (s->s3->alpn_selected)
   1847 		{
   1848 		OPENSSL_free(s->s3->alpn_selected);
   1849 		s->s3->alpn_selected = NULL;
   1850 		}
   1851 
   1852 	/* There may be no extensions. */
   1853 	if (CBS_len(cbs) == 0)
   1854 		{
   1855 		goto ri_check;
   1856 		}
   1857 
   1858 	/* Decode the extensions block and check it is valid. */
   1859 	if (!CBS_get_u16_length_prefixed(cbs, &extensions) ||
   1860 		!tls1_check_duplicate_extensions(&extensions))
   1861 		{
   1862 		*out_alert = SSL_AD_DECODE_ERROR;
   1863 		return 0;
   1864 		}
   1865 
   1866 	while (CBS_len(&extensions) != 0)
   1867 		{
   1868 		uint16_t type;
   1869 		CBS extension;
   1870 
   1871 		/* Decode the next extension. */
   1872 		if (!CBS_get_u16(&extensions, &type) ||
   1873 			!CBS_get_u16_length_prefixed(&extensions, &extension))
   1874 			{
   1875 			*out_alert = SSL_AD_DECODE_ERROR;
   1876 			return 0;
   1877 			}
   1878 
   1879 		if (s->tlsext_debug_cb)
   1880 			{
   1881 			s->tlsext_debug_cb(s, 1, type, (unsigned char*)CBS_data(&extension),
   1882 				CBS_len(&extension), s->tlsext_debug_arg);
   1883 			}
   1884 
   1885 		if (type == TLSEXT_TYPE_server_name)
   1886 			{
   1887 			/* The extension must be empty. */
   1888 			if (CBS_len(&extension) != 0)
   1889 				{
   1890 				*out_alert = SSL_AD_DECODE_ERROR;
   1891 				return 0;
   1892 				}
   1893 			/* We must have sent it in ClientHello. */
   1894 			if (s->tlsext_hostname == NULL)
   1895 				{
   1896 				*out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   1897 				return 0;
   1898 				}
   1899 			tlsext_servername = 1;
   1900 			}
   1901 		else if (type == TLSEXT_TYPE_ec_point_formats)
   1902 			{
   1903 			CBS ec_point_format_list;
   1904 
   1905 			if (!CBS_get_u8_length_prefixed(&extension, &ec_point_format_list) ||
   1906 				CBS_len(&extension) != 0)
   1907 				{
   1908 				*out_alert = SSL_AD_DECODE_ERROR;
   1909 				return 0;
   1910 				}
   1911 
   1912 			if (!s->hit)
   1913 				{
   1914 				if (!CBS_stow(&ec_point_format_list,
   1915 						&s->session->tlsext_ecpointformatlist,
   1916 						&s->session->tlsext_ecpointformatlist_length))
   1917 					{
   1918 					*out_alert = SSL_AD_INTERNAL_ERROR;
   1919 					return 0;
   1920 					}
   1921 				}
   1922 			}
   1923 		else if (type == TLSEXT_TYPE_session_ticket)
   1924 			{
   1925 			if (s->tls_session_ticket_ext_cb &&
   1926 				!s->tls_session_ticket_ext_cb(s, CBS_data(&extension), CBS_len(&extension),
   1927                                         s->tls_session_ticket_ext_cb_arg))
   1928 				{
   1929 				*out_alert = SSL_AD_INTERNAL_ERROR;
   1930 				return 0;
   1931 				}
   1932 
   1933 			if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || CBS_len(&extension) > 0)
   1934 				{
   1935 				*out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   1936 				return 0;
   1937 				}
   1938 
   1939 			s->tlsext_ticket_expected = 1;
   1940 			}
   1941 		else if (type == TLSEXT_TYPE_status_request)
   1942 			{
   1943 			/* The extension MUST be empty and may only sent if
   1944 			 * we've requested a status request message. */
   1945 			if (CBS_len(&extension) != 0)
   1946 				{
   1947 				*out_alert = SSL_AD_DECODE_ERROR;
   1948 				return 0;
   1949 				}
   1950 			if (!s->ocsp_stapling_enabled)
   1951 				{
   1952 				*out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   1953 				return 0;
   1954 				}
   1955 			/* Set a flag to expect a CertificateStatus message */
   1956 			s->s3->tmp.certificate_status_expected = 1;
   1957 			}
   1958 		else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) {
   1959 		unsigned char *selected;
   1960 		unsigned char selected_len;
   1961 
   1962 		/* We must have requested it. */
   1963 		if (s->ctx->next_proto_select_cb == NULL)
   1964 			{
   1965 			*out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   1966 			return 0;
   1967 			}
   1968 
   1969 		/* The data must be valid. */
   1970 		if (!ssl_next_proto_validate(&extension))
   1971 			{
   1972 			*out_alert = SSL_AD_DECODE_ERROR;
   1973 			return 0;
   1974 			}
   1975 
   1976 		if (s->ctx->next_proto_select_cb(s, &selected, &selected_len,
   1977 				CBS_data(&extension), CBS_len(&extension),
   1978 				s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK)
   1979 			{
   1980 			*out_alert = SSL_AD_INTERNAL_ERROR;
   1981 			return 0;
   1982 			}
   1983 
   1984 		s->next_proto_negotiated = BUF_memdup(selected, selected_len);
   1985 		if (s->next_proto_negotiated == NULL)
   1986 			{
   1987 			*out_alert = SSL_AD_INTERNAL_ERROR;
   1988 			return 0;
   1989 			}
   1990 		s->next_proto_negotiated_len = selected_len;
   1991 		s->s3->next_proto_neg_seen = 1;
   1992 		}
   1993 		else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation)
   1994 			{
   1995 			CBS protocol_name_list, protocol_name;
   1996 
   1997 			/* We must have requested it. */
   1998 			if (s->alpn_client_proto_list == NULL)
   1999 				{
   2000 				*out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
   2001 				return 0;
   2002 				}
   2003 
   2004 			/* The extension data consists of a ProtocolNameList
   2005 			 * which must have exactly one ProtocolName. Each of
   2006 			 * these is length-prefixed. */
   2007 			if (!CBS_get_u16_length_prefixed(&extension, &protocol_name_list) ||
   2008 				CBS_len(&extension) != 0 ||
   2009 				!CBS_get_u8_length_prefixed(&protocol_name_list, &protocol_name) ||
   2010 				CBS_len(&protocol_name_list) != 0)
   2011 				{
   2012 				*out_alert = SSL_AD_DECODE_ERROR;
   2013 				return 0;
   2014 				}
   2015 
   2016 			if (!CBS_stow(&protocol_name,
   2017 					&s->s3->alpn_selected,
   2018 					&s->s3->alpn_selected_len))
   2019 				{
   2020 				*out_alert = SSL_AD_INTERNAL_ERROR;
   2021 				return 0;
   2022 				}
   2023 			}
   2024 
   2025 		else if (type == TLSEXT_TYPE_channel_id)
   2026 			{
   2027 			if (CBS_len(&extension) != 0)
   2028 				{
   2029 				*out_alert = SSL_AD_DECODE_ERROR;
   2030 				return 0;
   2031 				}
   2032 			s->s3->tlsext_channel_id_valid = 1;
   2033 			}
   2034 		else if (type == TLSEXT_TYPE_channel_id_new)
   2035 			{
   2036 			if (CBS_len(&extension) != 0)
   2037 				{
   2038 				*out_alert = SSL_AD_DECODE_ERROR;
   2039 				return 0;
   2040 				}
   2041 			s->s3->tlsext_channel_id_valid = 1;
   2042 			s->s3->tlsext_channel_id_new = 1;
   2043 			}
   2044 		else if (type == TLSEXT_TYPE_certificate_timestamp)
   2045 			{
   2046 			if (CBS_len(&extension) == 0)
   2047 				{
   2048 				*out_alert = SSL_AD_DECODE_ERROR;
   2049 				return 0;
   2050 				}
   2051 
   2052 			/* Session resumption uses the original session information. */
   2053 			if (!s->hit)
   2054 				{
   2055 				if (!CBS_stow(&extension,
   2056 					&s->session->tlsext_signed_cert_timestamp_list,
   2057 					&s->session->tlsext_signed_cert_timestamp_list_length))
   2058 					{
   2059 					*out_alert = SSL_AD_INTERNAL_ERROR;
   2060 					return 0;
   2061 					}
   2062 				}
   2063 			}
   2064 		else if (type == TLSEXT_TYPE_renegotiate)
   2065 			{
   2066 			if (!ssl_parse_serverhello_renegotiate_ext(s, &extension, out_alert))
   2067 				return 0;
   2068 			renegotiate_seen = 1;
   2069 			}
   2070 		else if (type == TLSEXT_TYPE_use_srtp)
   2071                         {
   2072                         if (!ssl_parse_serverhello_use_srtp_ext(s, &extension, out_alert))
   2073                                 return 0;
   2074                         }
   2075 		}
   2076 
   2077 	if (!s->hit && tlsext_servername == 1)
   2078 		{
   2079  		if (s->tlsext_hostname)
   2080 			{
   2081 			if (s->session->tlsext_hostname == NULL)
   2082 				{
   2083 				s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
   2084 				if (!s->session->tlsext_hostname)
   2085 					{
   2086 					*out_alert = SSL_AD_UNRECOGNIZED_NAME;
   2087 					return 0;
   2088 					}
   2089 				}
   2090 			else
   2091 				{
   2092 				*out_alert = SSL_AD_DECODE_ERROR;
   2093 				return 0;
   2094 				}
   2095 			}
   2096 		}
   2097 
   2098 	ri_check:
   2099 
   2100 	/* Determine if we need to see RI. Strictly speaking if we want to
   2101 	 * avoid an attack we should *always* see RI even on initial server
   2102 	 * hello because the client doesn't see any renegotiation during an
   2103 	 * attack. However this would mean we could not connect to any server
   2104 	 * which doesn't support RI so for the immediate future tolerate RI
   2105 	 * absence on initial connect only.
   2106 	 */
   2107 	if (!renegotiate_seen
   2108 		&& !(s->options & SSL_OP_LEGACY_SERVER_CONNECT)
   2109 		&& !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
   2110 		{
   2111 		*out_alert = SSL_AD_HANDSHAKE_FAILURE;
   2112 		OPENSSL_PUT_ERROR(SSL, ssl_scan_serverhello_tlsext, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
   2113 		return 0;
   2114 		}
   2115 
   2116 	return 1;
   2117 	}
   2118 
   2119 
   2120 int ssl_prepare_clienthello_tlsext(SSL *s)
   2121 	{
   2122 	return 1;
   2123 	}
   2124 
   2125 int ssl_prepare_serverhello_tlsext(SSL *s)
   2126 	{
   2127 	return 1;
   2128 	}
   2129 
   2130 static int ssl_check_clienthello_tlsext(SSL *s)
   2131 	{
   2132 	int ret=SSL_TLSEXT_ERR_NOACK;
   2133 	int al = SSL_AD_UNRECOGNIZED_NAME;
   2134 
   2135 	/* The handling of the ECPointFormats extension is done elsewhere, namely in
   2136 	 * ssl3_choose_cipher in s3_lib.c.
   2137 	 */
   2138 	/* The handling of the EllipticCurves extension is done elsewhere, namely in
   2139 	 * ssl3_choose_cipher in s3_lib.c.
   2140 	 */
   2141 
   2142 	if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
   2143 		ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
   2144 	else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)
   2145 		ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
   2146 
   2147 	switch (ret)
   2148 		{
   2149 		case SSL_TLSEXT_ERR_ALERT_FATAL:
   2150 			ssl3_send_alert(s,SSL3_AL_FATAL,al);
   2151 			return -1;
   2152 
   2153 		case SSL_TLSEXT_ERR_ALERT_WARNING:
   2154 			ssl3_send_alert(s,SSL3_AL_WARNING,al);
   2155 			return 1;
   2156 
   2157 		case SSL_TLSEXT_ERR_NOACK:
   2158 			s->should_ack_sni = 0;
   2159 			return 1;
   2160 
   2161 		default:
   2162 			return 1;
   2163 		}
   2164 	}
   2165 
   2166 static int ssl_check_serverhello_tlsext(SSL *s)
   2167 	{
   2168 	int ret=SSL_TLSEXT_ERR_NOACK;
   2169 	int al = SSL_AD_UNRECOGNIZED_NAME;
   2170 
   2171 	/* If we are client and using an elliptic curve cryptography cipher
   2172 	 * suite, then if server returns an EC point formats lists extension
   2173 	 * it must contain uncompressed.
   2174 	 */
   2175 	unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
   2176 	unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth;
   2177 	if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) &&
   2178 	    (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) &&
   2179 	    ((alg_k & SSL_kEECDH) || (alg_a & SSL_aECDSA)))
   2180 		{
   2181 		/* we are using an ECC cipher */
   2182 		size_t i;
   2183 		unsigned char *list;
   2184 		int found_uncompressed = 0;
   2185 		list = s->session->tlsext_ecpointformatlist;
   2186 		for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
   2187 			{
   2188 			if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed)
   2189 				{
   2190 				found_uncompressed = 1;
   2191 				break;
   2192 				}
   2193 			}
   2194 		if (!found_uncompressed)
   2195 			{
   2196 			OPENSSL_PUT_ERROR(SSL, ssl_check_serverhello_tlsext, SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST);
   2197 			return -1;
   2198 			}
   2199 		}
   2200 	ret = SSL_TLSEXT_ERR_OK;
   2201 
   2202 	if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0)
   2203 		ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg);
   2204 	else if (s->initial_ctx != NULL && s->initial_ctx->tlsext_servername_callback != 0)
   2205 		ret = s->initial_ctx->tlsext_servername_callback(s, &al, s->initial_ctx->tlsext_servername_arg);
   2206 
   2207 	switch (ret)
   2208 		{
   2209 		case SSL_TLSEXT_ERR_ALERT_FATAL:
   2210 			ssl3_send_alert(s,SSL3_AL_FATAL,al);
   2211 			return -1;
   2212 
   2213 		case SSL_TLSEXT_ERR_ALERT_WARNING:
   2214 			ssl3_send_alert(s,SSL3_AL_WARNING,al);
   2215 			return 1;
   2216 
   2217 		default:
   2218 			return 1;
   2219 		}
   2220 	}
   2221 
   2222 int ssl_parse_serverhello_tlsext(SSL *s, CBS *cbs)
   2223 	{
   2224 	int alert = -1;
   2225 	if (s->version < SSL3_VERSION)
   2226 		return 1;
   2227 
   2228 	if (ssl_scan_serverhello_tlsext(s, cbs, &alert) <= 0)
   2229 		{
   2230 		ssl3_send_alert(s, SSL3_AL_FATAL, alert);
   2231 		return 0;
   2232 		}
   2233 
   2234 	if (ssl_check_serverhello_tlsext(s) <= 0)
   2235 		{
   2236 		OPENSSL_PUT_ERROR(SSL, ssl_parse_serverhello_tlsext, SSL_R_SERVERHELLO_TLSEXT);
   2237 		return 0;
   2238 		}
   2239 
   2240 	return 1;
   2241 	}
   2242 
   2243 /* Since the server cache lookup is done early on in the processing of the
   2244  * ClientHello, and other operations depend on the result, we need to handle
   2245  * any TLS session ticket extension at the same time.
   2246  *
   2247  *   ctx: contains the early callback context, which is the result of a
   2248  *       shallow parse of the ClientHello.
   2249  *   ret: (output) on return, if a ticket was decrypted, then this is set to
   2250  *       point to the resulting session.
   2251  *
   2252  * If s->tls_session_secret_cb is set then we are expecting a pre-shared key
   2253  * ciphersuite, in which case we have no use for session tickets and one will
   2254  * never be decrypted, nor will s->tlsext_ticket_expected be set to 1.
   2255  *
   2256  * Returns:
   2257  *   -1: fatal error, either from parsing or decrypting the ticket.
   2258  *    0: no ticket was found (or was ignored, based on settings).
   2259  *    1: a zero length extension was found, indicating that the client supports
   2260  *       session tickets but doesn't currently have one to offer.
   2261  *    2: either s->tls_session_secret_cb was set, or a ticket was offered but
   2262  *       couldn't be decrypted because of a non-fatal error.
   2263  *    3: a ticket was successfully decrypted and *ret was set.
   2264  *
   2265  * Side effects:
   2266  *   Sets s->tlsext_ticket_expected to 1 if the server will have to issue
   2267  *   a new session ticket to the client because the client indicated support
   2268  *   (and s->tls_session_secret_cb is NULL) but the client either doesn't have
   2269  *   a session ticket or we couldn't use the one it gave us, or if
   2270  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
   2271  *   Otherwise, s->tlsext_ticket_expected is set to 0.
   2272  */
   2273 int tls1_process_ticket(SSL *s, const struct ssl_early_callback_ctx *ctx,
   2274 			SSL_SESSION **ret)
   2275 	{
   2276 	*ret = NULL;
   2277 	s->tlsext_ticket_expected = 0;
   2278 	const unsigned char *data;
   2279 	size_t len;
   2280 	int r;
   2281 
   2282 	/* If tickets disabled behave as if no ticket present
   2283 	 * to permit stateful resumption.
   2284 	 */
   2285 	if (SSL_get_options(s) & SSL_OP_NO_TICKET)
   2286 		return 0;
   2287 	if ((s->version <= SSL3_VERSION) && !ctx->extensions)
   2288 		return 0;
   2289 	if (!SSL_early_callback_ctx_extension_get(
   2290 		ctx, TLSEXT_TYPE_session_ticket, &data, &len))
   2291 		{
   2292 		return 0;
   2293 		}
   2294 	if (len == 0)
   2295 		{
   2296 		/* The client will accept a ticket but doesn't
   2297 		 * currently have one. */
   2298 		s->tlsext_ticket_expected = 1;
   2299 		return 1;
   2300 		}
   2301 	if (s->tls_session_secret_cb)
   2302 		{
   2303 		/* Indicate that the ticket couldn't be
   2304 		 * decrypted rather than generating the session
   2305 		 * from ticket now, trigger abbreviated
   2306 		 * handshake based on external mechanism to
   2307 		 * calculate the master secret later. */
   2308 		return 2;
   2309 		}
   2310 	r = tls_decrypt_ticket(s, data, len, ctx->session_id,
   2311 			       ctx->session_id_len, ret);
   2312 	switch (r)
   2313 		{
   2314 		case 2: /* ticket couldn't be decrypted */
   2315 			s->tlsext_ticket_expected = 1;
   2316 			return 2;
   2317 		case 3: /* ticket was decrypted */
   2318 			return r;
   2319 		case 4: /* ticket decrypted but need to renew */
   2320 			s->tlsext_ticket_expected = 1;
   2321 			return 3;
   2322 		default: /* fatal error */
   2323 			return -1;
   2324 		}
   2325 	}
   2326 
   2327 /* tls_decrypt_ticket attempts to decrypt a session ticket.
   2328  *
   2329  *   etick: points to the body of the session ticket extension.
   2330  *   eticklen: the length of the session tickets extenion.
   2331  *   sess_id: points at the session ID.
   2332  *   sesslen: the length of the session ID.
   2333  *   psess: (output) on return, if a ticket was decrypted, then this is set to
   2334  *       point to the resulting session.
   2335  *
   2336  * Returns:
   2337  *   -1: fatal error, either from parsing or decrypting the ticket.
   2338  *    2: the ticket couldn't be decrypted.
   2339  *    3: a ticket was successfully decrypted and *psess was set.
   2340  *    4: same as 3, but the ticket needs to be renewed.
   2341  */
   2342 static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
   2343 				const unsigned char *sess_id, int sesslen,
   2344 				SSL_SESSION **psess)
   2345 	{
   2346 	SSL_SESSION *sess;
   2347 	unsigned char *sdec;
   2348 	const unsigned char *p;
   2349 	int slen, mlen, renew_ticket = 0;
   2350 	unsigned char tick_hmac[EVP_MAX_MD_SIZE];
   2351 	HMAC_CTX hctx;
   2352 	EVP_CIPHER_CTX ctx;
   2353 	SSL_CTX *tctx = s->initial_ctx;
   2354 	/* Need at least keyname + iv + some encrypted data */
   2355 	if (eticklen < 48)
   2356 		return 2;
   2357 	/* Initialize session ticket encryption and HMAC contexts */
   2358 	HMAC_CTX_init(&hctx);
   2359 	EVP_CIPHER_CTX_init(&ctx);
   2360 	if (tctx->tlsext_ticket_key_cb)
   2361 		{
   2362 		unsigned char *nctick = (unsigned char *)etick;
   2363 		int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
   2364 							&ctx, &hctx, 0);
   2365 		if (rv < 0)
   2366 			return -1;
   2367 		if (rv == 0)
   2368 			return 2;
   2369 		if (rv == 2)
   2370 			renew_ticket = 1;
   2371 		}
   2372 	else
   2373 		{
   2374 		/* Check key name matches */
   2375 		if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
   2376 			return 2;
   2377 		HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
   2378 					tlsext_tick_md(), NULL);
   2379 		EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
   2380 				tctx->tlsext_tick_aes_key, etick + 16);
   2381 		}
   2382 	/* Attempt to process session ticket, first conduct sanity and
   2383 	 * integrity checks on ticket.
   2384 	 */
   2385 	mlen = HMAC_size(&hctx);
   2386 	if (mlen < 0)
   2387 		{
   2388 		EVP_CIPHER_CTX_cleanup(&ctx);
   2389 		return -1;
   2390 		}
   2391 	eticklen -= mlen;
   2392 	/* Check HMAC of encrypted ticket */
   2393 	HMAC_Update(&hctx, etick, eticklen);
   2394 	HMAC_Final(&hctx, tick_hmac, NULL);
   2395 	HMAC_CTX_cleanup(&hctx);
   2396 	if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
   2397 		return 2;
   2398 	/* Attempt to decrypt session data */
   2399 	/* Move p after IV to start of encrypted ticket, update length */
   2400 	p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
   2401 	eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
   2402 	sdec = OPENSSL_malloc(eticklen);
   2403 	if (!sdec)
   2404 		{
   2405 		EVP_CIPHER_CTX_cleanup(&ctx);
   2406 		return -1;
   2407 		}
   2408 	EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
   2409 	if (EVP_DecryptFinal_ex(&ctx, sdec + slen, &mlen) <= 0)
   2410 		{
   2411 		EVP_CIPHER_CTX_cleanup(&ctx);
   2412 		OPENSSL_free(sdec);
   2413 		return 2;
   2414 		}
   2415 	slen += mlen;
   2416 	EVP_CIPHER_CTX_cleanup(&ctx);
   2417 	p = sdec;
   2418 
   2419 	sess = d2i_SSL_SESSION(NULL, &p, slen);
   2420 	OPENSSL_free(sdec);
   2421 	if (sess)
   2422 		{
   2423 		/* The session ID, if non-empty, is used by some clients to
   2424 		 * detect that the ticket has been accepted. So we copy it to
   2425 		 * the session structure. If it is empty set length to zero
   2426 		 * as required by standard.
   2427 		 */
   2428 		if (sesslen)
   2429 			memcpy(sess->session_id, sess_id, sesslen);
   2430 		sess->session_id_length = sesslen;
   2431 		*psess = sess;
   2432 		if (renew_ticket)
   2433 			return 4;
   2434 		else
   2435 			return 3;
   2436 		}
   2437         ERR_clear_error();
   2438 	/* For session parse failure, indicate that we need to send a new
   2439 	 * ticket. */
   2440 	return 2;
   2441 	}
   2442 
   2443 /* Tables to translate from NIDs to TLS v1.2 ids */
   2444 
   2445 typedef struct
   2446 	{
   2447 	int nid;
   2448 	int id;
   2449 	} tls12_lookup;
   2450 
   2451 static const tls12_lookup tls12_md[] = {
   2452 	{NID_md5, TLSEXT_hash_md5},
   2453 	{NID_sha1, TLSEXT_hash_sha1},
   2454 	{NID_sha224, TLSEXT_hash_sha224},
   2455 	{NID_sha256, TLSEXT_hash_sha256},
   2456 	{NID_sha384, TLSEXT_hash_sha384},
   2457 	{NID_sha512, TLSEXT_hash_sha512}
   2458 };
   2459 
   2460 static const tls12_lookup tls12_sig[] = {
   2461 	{EVP_PKEY_RSA, TLSEXT_signature_rsa},
   2462 	{EVP_PKEY_EC, TLSEXT_signature_ecdsa}
   2463 };
   2464 
   2465 static int tls12_find_id(int nid, const tls12_lookup *table, size_t tlen)
   2466 	{
   2467 	size_t i;
   2468 	for (i = 0; i < tlen; i++)
   2469 		{
   2470 		if (table[i].nid == nid)
   2471 			return table[i].id;
   2472 		}
   2473 	return -1;
   2474 	}
   2475 
   2476 static int tls12_find_nid(int id, const tls12_lookup *table, size_t tlen)
   2477 	{
   2478 	size_t i;
   2479 	for (i = 0; i < tlen; i++)
   2480 		{
   2481 		if ((table[i].id) == id)
   2482 			return table[i].nid;
   2483 		}
   2484 	return NID_undef;
   2485 	}
   2486 
   2487 int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md)
   2488 	{
   2489 	int sig_id, md_id;
   2490 	if (!md)
   2491 		return 0;
   2492 	md_id = tls12_find_id(EVP_MD_type(md), tls12_md,
   2493 				sizeof(tls12_md)/sizeof(tls12_lookup));
   2494 	if (md_id == -1)
   2495 		return 0;
   2496 	sig_id = tls12_get_sigid(pk);
   2497 	if (sig_id == -1)
   2498 		return 0;
   2499 	p[0] = (unsigned char)md_id;
   2500 	p[1] = (unsigned char)sig_id;
   2501 	return 1;
   2502 	}
   2503 
   2504 int tls12_get_sigid(const EVP_PKEY *pk)
   2505 	{
   2506 	return tls12_find_id(pk->type, tls12_sig,
   2507 				sizeof(tls12_sig)/sizeof(tls12_lookup));
   2508 	}
   2509 
   2510 const EVP_MD *tls12_get_hash(unsigned char hash_alg)
   2511 	{
   2512 	switch(hash_alg)
   2513 		{
   2514 		case TLSEXT_hash_md5:
   2515 		return EVP_md5();
   2516 		case TLSEXT_hash_sha1:
   2517 		return EVP_sha1();
   2518 		case TLSEXT_hash_sha224:
   2519 		return EVP_sha224();
   2520 
   2521 		case TLSEXT_hash_sha256:
   2522 		return EVP_sha256();
   2523 		case TLSEXT_hash_sha384:
   2524 		return EVP_sha384();
   2525 
   2526 		case TLSEXT_hash_sha512:
   2527 		return EVP_sha512();
   2528 		default:
   2529 		return NULL;
   2530 
   2531 		}
   2532 	}
   2533 
   2534 static int tls12_get_pkey_idx(unsigned char sig_alg)
   2535 	{
   2536 	switch(sig_alg)
   2537 		{
   2538 	case TLSEXT_signature_rsa:
   2539 		return SSL_PKEY_RSA_SIGN;
   2540 	case TLSEXT_signature_ecdsa:
   2541 		return SSL_PKEY_ECC;
   2542 		}
   2543 	return -1;
   2544 	}
   2545 
   2546 /* Convert TLS 1.2 signature algorithm extension values into NIDs */
   2547 static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid,
   2548 			int *psignhash_nid, const unsigned char *data)
   2549 	{
   2550 	int sign_nid = 0, hash_nid = 0;
   2551 	if (!phash_nid && !psign_nid && !psignhash_nid)
   2552 		return;
   2553 	if (phash_nid || psignhash_nid)
   2554 		{
   2555 		hash_nid = tls12_find_nid(data[0], tls12_md,
   2556 					sizeof(tls12_md)/sizeof(tls12_lookup));
   2557 		if (phash_nid)
   2558 			*phash_nid = hash_nid;
   2559 		}
   2560 	if (psign_nid || psignhash_nid)
   2561 		{
   2562 		sign_nid = tls12_find_nid(data[1], tls12_sig,
   2563 					sizeof(tls12_sig)/sizeof(tls12_lookup));
   2564 		if (psign_nid)
   2565 			*psign_nid = sign_nid;
   2566 		}
   2567 	if (psignhash_nid)
   2568 		{
   2569 		if (sign_nid && hash_nid)
   2570 			OBJ_find_sigid_by_algs(psignhash_nid,
   2571 							hash_nid, sign_nid);
   2572 		else
   2573 			*psignhash_nid = NID_undef;
   2574 		}
   2575 	}
   2576 /* Given preference and allowed sigalgs set shared sigalgs */
   2577 static int tls12_do_shared_sigalgs(TLS_SIGALGS *shsig,
   2578 				const unsigned char *pref, size_t preflen,
   2579 				const unsigned char *allow, size_t allowlen)
   2580 	{
   2581 	const unsigned char *ptmp, *atmp;
   2582 	size_t i, j, nmatch = 0;
   2583 	for (i = 0, ptmp = pref; i < preflen; i+=2, ptmp+=2)
   2584 		{
   2585 		/* Skip disabled hashes or signature algorithms */
   2586 		if (tls12_get_hash(ptmp[0]) == NULL)
   2587 			continue;
   2588 		if (tls12_get_pkey_idx(ptmp[1]) == -1)
   2589 			continue;
   2590 		for (j = 0, atmp = allow; j < allowlen; j+=2, atmp+=2)
   2591 			{
   2592 			if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1])
   2593 				{
   2594 				nmatch++;
   2595 				if (shsig)
   2596 					{
   2597 					shsig->rhash = ptmp[0];
   2598 					shsig->rsign = ptmp[1];
   2599 					tls1_lookup_sigalg(&shsig->hash_nid,
   2600 						&shsig->sign_nid,
   2601 						&shsig->signandhash_nid,
   2602 						ptmp);
   2603 					shsig++;
   2604 					}
   2605 				break;
   2606 				}
   2607 			}
   2608 		}
   2609 	return nmatch;
   2610 	}
   2611 
   2612 /* Set shared signature algorithms for SSL structures */
   2613 static int tls1_set_shared_sigalgs(SSL *s)
   2614 	{
   2615 	const unsigned char *pref, *allow, *conf;
   2616 	size_t preflen, allowlen, conflen;
   2617 	size_t nmatch;
   2618 	TLS_SIGALGS *salgs = NULL;
   2619 	CERT *c = s->cert;
   2620 	if (c->shared_sigalgs)
   2621 		{
   2622 		OPENSSL_free(c->shared_sigalgs);
   2623 		c->shared_sigalgs = NULL;
   2624 		}
   2625 	/* If client use client signature algorithms if not NULL */
   2626 	if (!s->server && c->client_sigalgs)
   2627 		{
   2628 		conf = c->client_sigalgs;
   2629 		conflen = c->client_sigalgslen;
   2630 		}
   2631 	else if (c->conf_sigalgs)
   2632 		{
   2633 		conf = c->conf_sigalgs;
   2634 		conflen = c->conf_sigalgslen;
   2635 		}
   2636 	else
   2637 		conflen = tls12_get_psigalgs(s, &conf);
   2638 	if(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE)
   2639 		{
   2640 		pref = conf;
   2641 		preflen = conflen;
   2642 		allow = c->peer_sigalgs;
   2643 		allowlen = c->peer_sigalgslen;
   2644 		}
   2645 	else
   2646 		{
   2647 		allow = conf;
   2648 		allowlen = conflen;
   2649 		pref = c->peer_sigalgs;
   2650 		preflen = c->peer_sigalgslen;
   2651 		}
   2652 	nmatch = tls12_do_shared_sigalgs(NULL, pref, preflen, allow, allowlen);
   2653 	if (!nmatch)
   2654 		return 1;
   2655 	salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS));
   2656 	if (!salgs)
   2657 		return 0;
   2658 	nmatch = tls12_do_shared_sigalgs(salgs, pref, preflen, allow, allowlen);
   2659 	c->shared_sigalgs = salgs;
   2660 	c->shared_sigalgslen = nmatch;
   2661 	return 1;
   2662 	}
   2663 
   2664 
   2665 /* Set preferred digest for each key type */
   2666 
   2667 int tls1_process_sigalgs(SSL *s, const CBS *sigalgs)
   2668 	{
   2669 	int idx;
   2670 	size_t i;
   2671 	const EVP_MD *md;
   2672 	CERT *c = s->cert;
   2673 	TLS_SIGALGS *sigptr;
   2674 
   2675 	/* Extension ignored for inappropriate versions */
   2676 	if (!SSL_USE_SIGALGS(s))
   2677 		return 1;
   2678 	/* Length must be even */
   2679 	if (CBS_len(sigalgs) % 2 != 0)
   2680 		return 0;
   2681 	/* Should never happen */
   2682 	if (!c)
   2683 		return 0;
   2684 
   2685 	if (!CBS_stow(sigalgs, &c->peer_sigalgs, &c->peer_sigalgslen))
   2686 		return 0;
   2687 
   2688 	tls1_set_shared_sigalgs(s);
   2689 
   2690 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
   2691 	if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
   2692 		{
   2693 		/* Use first set signature preference to force message
   2694 		 * digest, ignoring any peer preferences.
   2695 		 */
   2696 		const unsigned char *sigs = NULL;
   2697 		if (s->server)
   2698 			sigs = c->conf_sigalgs;
   2699 		else
   2700 			sigs = c->client_sigalgs;
   2701 		if (sigs)
   2702 			{
   2703 			idx = tls12_get_pkey_idx(sigs[1]);
   2704 			md = tls12_get_hash(sigs[0]);
   2705 			c->pkeys[idx].digest = md;
   2706 			c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
   2707 			if (idx == SSL_PKEY_RSA_SIGN)
   2708 				{
   2709 				c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
   2710 				c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
   2711 				}
   2712 			}
   2713 		}
   2714 #endif
   2715 
   2716 	for (i = 0, sigptr = c->shared_sigalgs;
   2717 			i < c->shared_sigalgslen; i++, sigptr++)
   2718 		{
   2719 		idx = tls12_get_pkey_idx(sigptr->rsign);
   2720 		if (idx > 0 && c->pkeys[idx].digest == NULL)
   2721 			{
   2722 			md = tls12_get_hash(sigptr->rhash);
   2723 			c->pkeys[idx].digest = md;
   2724 			c->pkeys[idx].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
   2725 			if (idx == SSL_PKEY_RSA_SIGN)
   2726 				{
   2727 				c->pkeys[SSL_PKEY_RSA_ENC].valid_flags = CERT_PKEY_EXPLICIT_SIGN;
   2728 				c->pkeys[SSL_PKEY_RSA_ENC].digest = md;
   2729 				}
   2730 			}
   2731 
   2732 		}
   2733 	/* In strict mode leave unset digests as NULL to indicate we can't
   2734 	 * use the certificate for signing.
   2735 	 */
   2736 	if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT))
   2737 		{
   2738 		/* Set any remaining keys to default values. NOTE: if alg is
   2739 		 * not supported it stays as NULL.
   2740 	 	 */
   2741 		if (!c->pkeys[SSL_PKEY_RSA_SIGN].digest)
   2742 			{
   2743 			c->pkeys[SSL_PKEY_RSA_SIGN].digest = EVP_sha1();
   2744 			c->pkeys[SSL_PKEY_RSA_ENC].digest = EVP_sha1();
   2745 			}
   2746 		if (!c->pkeys[SSL_PKEY_ECC].digest)
   2747 			c->pkeys[SSL_PKEY_ECC].digest = EVP_sha1();
   2748 		}
   2749 	return 1;
   2750 	}
   2751 
   2752 
   2753 int SSL_get_sigalgs(SSL *s, int idx,
   2754 			int *psign, int *phash, int *psignhash,
   2755 			unsigned char *rsig, unsigned char *rhash)
   2756 	{
   2757 	const unsigned char *psig = s->cert->peer_sigalgs;
   2758 	if (psig == NULL)
   2759 		return 0;
   2760 	if (idx >= 0)
   2761 		{
   2762 		idx <<= 1;
   2763 		if (idx >= (int)s->cert->peer_sigalgslen)
   2764 			return 0;
   2765 		psig += idx;
   2766 		if (rhash)
   2767 			*rhash = psig[0];
   2768 		if (rsig)
   2769 			*rsig = psig[1];
   2770 		tls1_lookup_sigalg(phash, psign, psignhash, psig);
   2771 		}
   2772 	return s->cert->peer_sigalgslen / 2;
   2773 	}
   2774 
   2775 int SSL_get_shared_sigalgs(SSL *s, int idx,
   2776 			int *psign, int *phash, int *psignhash,
   2777 			unsigned char *rsig, unsigned char *rhash)
   2778 	{
   2779 	TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs;
   2780 	if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen)
   2781 		return 0;
   2782 	shsigalgs += idx;
   2783 	if (phash)
   2784 		*phash = shsigalgs->hash_nid;
   2785 	if (psign)
   2786 		*psign = shsigalgs->sign_nid;
   2787 	if (psignhash)
   2788 		*psignhash = shsigalgs->signandhash_nid;
   2789 	if (rsig)
   2790 		*rsig = shsigalgs->rsign;
   2791 	if (rhash)
   2792 		*rhash = shsigalgs->rhash;
   2793 	return s->cert->shared_sigalgslen;
   2794 	}
   2795 
   2796 /* tls1_channel_id_hash calculates the signed data for a Channel ID on the given
   2797  * SSL connection and writes it to |md|. */
   2798 int
   2799 tls1_channel_id_hash(EVP_MD_CTX *md, SSL *s)
   2800 	{
   2801 	EVP_MD_CTX ctx;
   2802 	unsigned char temp_digest[EVP_MAX_MD_SIZE];
   2803 	unsigned temp_digest_len;
   2804 	int i;
   2805 	static const char kClientIDMagic[] = "TLS Channel ID signature";
   2806 
   2807 	if (s->s3->handshake_buffer)
   2808 		if (!ssl3_digest_cached_records(s))
   2809 			return 0;
   2810 
   2811 	EVP_DigestUpdate(md, kClientIDMagic, sizeof(kClientIDMagic));
   2812 
   2813 	if (s->hit && s->s3->tlsext_channel_id_new)
   2814 		{
   2815 		static const char kResumptionMagic[] = "Resumption";
   2816 		EVP_DigestUpdate(md, kResumptionMagic,
   2817 				 sizeof(kResumptionMagic));
   2818 		if (s->session->original_handshake_hash_len == 0)
   2819 			return 0;
   2820 		EVP_DigestUpdate(md, s->session->original_handshake_hash,
   2821 				 s->session->original_handshake_hash_len);
   2822 		}
   2823 
   2824 	EVP_MD_CTX_init(&ctx);
   2825 	for (i = 0; i < SSL_MAX_DIGEST; i++)
   2826 		{
   2827 		if (s->s3->handshake_dgst[i] == NULL)
   2828 			continue;
   2829 		EVP_MD_CTX_copy_ex(&ctx, s->s3->handshake_dgst[i]);
   2830 		EVP_DigestFinal_ex(&ctx, temp_digest, &temp_digest_len);
   2831 		EVP_DigestUpdate(md, temp_digest, temp_digest_len);
   2832 		}
   2833 	EVP_MD_CTX_cleanup(&ctx);
   2834 
   2835 	return 1;
   2836 	}
   2837 
   2838 /* tls1_record_handshake_hashes_for_channel_id records the current handshake
   2839  * hashes in |s->session| so that Channel ID resumptions can sign that data. */
   2840 int tls1_record_handshake_hashes_for_channel_id(SSL *s)
   2841 	{
   2842 	int digest_len;
   2843 	/* This function should never be called for a resumed session because
   2844 	 * the handshake hashes that we wish to record are for the original,
   2845 	 * full handshake. */
   2846 	if (s->hit)
   2847 		return -1;
   2848 	/* It only makes sense to call this function if Channel IDs have been
   2849 	 * negotiated. */
   2850 	if (!s->s3->tlsext_channel_id_new)
   2851 		return -1;
   2852 
   2853 	digest_len = tls1_handshake_digest(
   2854 		s, s->session->original_handshake_hash,
   2855 		sizeof(s->session->original_handshake_hash));
   2856 	if (digest_len < 0)
   2857 		return -1;
   2858 
   2859 	s->session->original_handshake_hash_len = digest_len;
   2860 
   2861 	return 1;
   2862 	}
   2863 
   2864 int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
   2865 	{
   2866 	unsigned char *sigalgs, *sptr;
   2867 	int rhash, rsign;
   2868 	size_t i;
   2869 	if (salglen & 1)
   2870 		return 0;
   2871 	sigalgs = OPENSSL_malloc(salglen);
   2872 	if (sigalgs == NULL)
   2873 		return 0;
   2874 	for (i = 0, sptr = sigalgs; i < salglen; i+=2)
   2875 		{
   2876 		rhash = tls12_find_id(*psig_nids++, tls12_md,
   2877 					sizeof(tls12_md)/sizeof(tls12_lookup));
   2878 		rsign = tls12_find_id(*psig_nids++, tls12_sig,
   2879 				sizeof(tls12_sig)/sizeof(tls12_lookup));
   2880 
   2881 		if (rhash == -1 || rsign == -1)
   2882 			goto err;
   2883 		*sptr++ = rhash;
   2884 		*sptr++ = rsign;
   2885 		}
   2886 
   2887 	if (client)
   2888 		{
   2889 		if (c->client_sigalgs)
   2890 			OPENSSL_free(c->client_sigalgs);
   2891 		c->client_sigalgs = sigalgs;
   2892 		c->client_sigalgslen = salglen;
   2893 		}
   2894 	else
   2895 		{
   2896 		if (c->conf_sigalgs)
   2897 			OPENSSL_free(c->conf_sigalgs);
   2898 		c->conf_sigalgs = sigalgs;
   2899 		c->conf_sigalgslen = salglen;
   2900 		}
   2901 
   2902 	return 1;
   2903 
   2904 	err:
   2905 	OPENSSL_free(sigalgs);
   2906 	return 0;
   2907 	}
   2908 
   2909 static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid)
   2910 	{
   2911 	int sig_nid;
   2912 	size_t i;
   2913 	if (default_nid == -1)
   2914 		return 1;
   2915 	sig_nid = X509_get_signature_nid(x);
   2916 	if (default_nid)
   2917 		return sig_nid == default_nid ? 1 : 0;
   2918 	for (i = 0; i < c->shared_sigalgslen; i++)
   2919 		if (sig_nid == c->shared_sigalgs[i].signandhash_nid)
   2920 			return 1;
   2921 	return 0;
   2922 	}
   2923 /* Check to see if a certificate issuer name matches list of CA names */
   2924 static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x)
   2925 	{
   2926 	X509_NAME *nm;
   2927 	int i;
   2928 	nm = X509_get_issuer_name(x);
   2929 	for (i = 0; i < sk_X509_NAME_num(names); i++)
   2930 		{
   2931 		if(!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i)))
   2932 			return 1;
   2933 		}
   2934 	return 0;
   2935 	}
   2936 
   2937 /* Check certificate chain is consistent with TLS extensions and is
   2938  * usable by server. This servers two purposes: it allows users to
   2939  * check chains before passing them to the server and it allows the
   2940  * server to check chains before attempting to use them.
   2941  */
   2942 
   2943 /* Flags which need to be set for a certificate when stict mode not set */
   2944 
   2945 #define CERT_PKEY_VALID_FLAGS \
   2946 	(CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM)
   2947 /* Strict mode flags */
   2948 #define CERT_PKEY_STRICT_FLAGS \
   2949 	 (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \
   2950 	 | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE)
   2951 
   2952 int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain,
   2953 									int idx)
   2954 	{
   2955 	int i;
   2956 	int rv = 0;
   2957 	int check_flags = 0, strict_mode;
   2958 	CERT_PKEY *cpk = NULL;
   2959 	CERT *c = s->cert;
   2960 	/* idx == -1 means checking server chains */
   2961 	if (idx != -1)
   2962 		{
   2963 		/* idx == -2 means checking client certificate chains */
   2964 		if (idx == -2)
   2965 			{
   2966 			cpk = c->key;
   2967 			idx = cpk - c->pkeys;
   2968 			}
   2969 		else
   2970 			cpk = c->pkeys + idx;
   2971 		x = cpk->x509;
   2972 		pk = cpk->privatekey;
   2973 		chain = cpk->chain;
   2974 		strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT;
   2975 		/* If no cert or key, forget it */
   2976 		if (!x || !pk)
   2977 			goto end;
   2978 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
   2979 		/* Allow any certificate to pass test */
   2980 		if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL)
   2981 			{
   2982 			rv = CERT_PKEY_STRICT_FLAGS|CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_VALID|CERT_PKEY_SIGN;
   2983 			cpk->valid_flags = rv;
   2984 			return rv;
   2985 			}
   2986 #endif
   2987 		}
   2988 	else
   2989 		{
   2990 		if (!x || !pk)
   2991 			goto end;
   2992 		idx = ssl_cert_type(x, pk);
   2993 		if (idx == -1)
   2994 			goto end;
   2995 		cpk = c->pkeys + idx;
   2996 		if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)
   2997 			check_flags = CERT_PKEY_STRICT_FLAGS;
   2998 		else
   2999 			check_flags = CERT_PKEY_VALID_FLAGS;
   3000 		strict_mode = 1;
   3001 		}
   3002 
   3003 	/* Check all signature algorithms are consistent with
   3004 	 * signature algorithms extension if TLS 1.2 or later
   3005 	 * and strict mode.
   3006 	 */
   3007 	if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode)
   3008 		{
   3009 		int default_nid;
   3010 		unsigned char rsign = 0;
   3011 		if (c->peer_sigalgs)
   3012 			default_nid = 0;
   3013 		/* If no sigalgs extension use defaults from RFC5246 */
   3014 		else
   3015 			{
   3016 			switch(idx)
   3017 				{
   3018 			case SSL_PKEY_RSA_ENC:
   3019 			case SSL_PKEY_RSA_SIGN:
   3020 				rsign = TLSEXT_signature_rsa;
   3021 				default_nid = NID_sha1WithRSAEncryption;
   3022 				break;
   3023 
   3024 			case SSL_PKEY_ECC:
   3025 				rsign = TLSEXT_signature_ecdsa;
   3026 				default_nid = NID_ecdsa_with_SHA1;
   3027 				break;
   3028 
   3029 			default:
   3030 				default_nid = -1;
   3031 				break;
   3032 				}
   3033 			}
   3034 		/* If peer sent no signature algorithms extension and we
   3035 		 * have set preferred signature algorithms check we support
   3036 		 * sha1.
   3037 		 */
   3038 		if (default_nid > 0 && c->conf_sigalgs)
   3039 			{
   3040 			size_t j;
   3041 			const unsigned char *p = c->conf_sigalgs;
   3042 			for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2)
   3043 				{
   3044 				if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign)
   3045 					break;
   3046 				}
   3047 			if (j == c->conf_sigalgslen)
   3048 				{
   3049 				if (check_flags)
   3050 					goto skip_sigs;
   3051 				else
   3052 					goto end;
   3053 				}
   3054 			}
   3055 		/* Check signature algorithm of each cert in chain */
   3056 		if (!tls1_check_sig_alg(c, x, default_nid))
   3057 			{
   3058 			if (!check_flags) goto end;
   3059 			}
   3060 		else
   3061 			rv |= CERT_PKEY_EE_SIGNATURE;
   3062 		rv |= CERT_PKEY_CA_SIGNATURE;
   3063 		for (i = 0; i < sk_X509_num(chain); i++)
   3064 			{
   3065 			if (!tls1_check_sig_alg(c, sk_X509_value(chain, i),
   3066 							default_nid))
   3067 				{
   3068 				if (check_flags)
   3069 					{
   3070 					rv &= ~CERT_PKEY_CA_SIGNATURE;
   3071 					break;
   3072 					}
   3073 				else
   3074 					goto end;
   3075 				}
   3076 			}
   3077 		}
   3078 	/* Else not TLS 1.2, so mark EE and CA signing algorithms OK */
   3079 	else if(check_flags)
   3080 		rv |= CERT_PKEY_EE_SIGNATURE|CERT_PKEY_CA_SIGNATURE;
   3081 	skip_sigs:
   3082 	/* Check cert parameters are consistent */
   3083 	if (tls1_check_cert_param(s, x, check_flags ? 1 : 2))
   3084 		rv |= CERT_PKEY_EE_PARAM;
   3085 	else if (!check_flags)
   3086 		goto end;
   3087 	if (!s->server)
   3088 		rv |= CERT_PKEY_CA_PARAM;
   3089 	/* In strict mode check rest of chain too */
   3090 	else if (strict_mode)
   3091 		{
   3092 		rv |= CERT_PKEY_CA_PARAM;
   3093 		for (i = 0; i < sk_X509_num(chain); i++)
   3094 			{
   3095 			X509 *ca = sk_X509_value(chain, i);
   3096 			if (!tls1_check_cert_param(s, ca, 0))
   3097 				{
   3098 				if (check_flags)
   3099 					{
   3100 					rv &= ~CERT_PKEY_CA_PARAM;
   3101 					break;
   3102 					}
   3103 				else
   3104 					goto end;
   3105 				}
   3106 			}
   3107 		}
   3108 	if (!s->server && strict_mode)
   3109 		{
   3110 		STACK_OF(X509_NAME) *ca_dn;
   3111 		uint8_t check_type = 0;
   3112 		switch (pk->type)
   3113 			{
   3114 		case EVP_PKEY_RSA:
   3115 			check_type = TLS_CT_RSA_SIGN;
   3116 			break;
   3117 		case EVP_PKEY_EC:
   3118 			check_type = TLS_CT_ECDSA_SIGN;
   3119 			break;
   3120 			}
   3121 		if (check_type)
   3122 			{
   3123 			if (s->s3->tmp.certificate_types &&
   3124 				memchr(s->s3->tmp.certificate_types, check_type, s->s3->tmp.num_certificate_types))
   3125 				{
   3126 					rv |= CERT_PKEY_CERT_TYPE;
   3127 				}
   3128 			if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags)
   3129 				goto end;
   3130 			}
   3131 		else
   3132 			rv |= CERT_PKEY_CERT_TYPE;
   3133 
   3134 
   3135 		ca_dn = s->s3->tmp.ca_names;
   3136 
   3137 		if (!sk_X509_NAME_num(ca_dn))
   3138 			rv |= CERT_PKEY_ISSUER_NAME;
   3139 
   3140 		if (!(rv & CERT_PKEY_ISSUER_NAME))
   3141 			{
   3142 			if (ssl_check_ca_name(ca_dn, x))
   3143 				rv |= CERT_PKEY_ISSUER_NAME;
   3144 			}
   3145 		if (!(rv & CERT_PKEY_ISSUER_NAME))
   3146 			{
   3147 			for (i = 0; i < sk_X509_num(chain); i++)
   3148 				{
   3149 				X509 *xtmp = sk_X509_value(chain, i);
   3150 				if (ssl_check_ca_name(ca_dn, xtmp))
   3151 					{
   3152 					rv |= CERT_PKEY_ISSUER_NAME;
   3153 					break;
   3154 					}
   3155 				}
   3156 			}
   3157 		if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME))
   3158 			goto end;
   3159 		}
   3160 	else
   3161 		rv |= CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE;
   3162 
   3163 	if (!check_flags || (rv & check_flags) == check_flags)
   3164 		rv |= CERT_PKEY_VALID;
   3165 
   3166 	end:
   3167 
   3168 	if (TLS1_get_version(s) >= TLS1_2_VERSION)
   3169 		{
   3170 		if (cpk->valid_flags & CERT_PKEY_EXPLICIT_SIGN)
   3171 			rv |= CERT_PKEY_EXPLICIT_SIGN|CERT_PKEY_SIGN;
   3172 		else if (cpk->digest)
   3173 			rv |= CERT_PKEY_SIGN;
   3174 		}
   3175 	else
   3176 		rv |= CERT_PKEY_SIGN|CERT_PKEY_EXPLICIT_SIGN;
   3177 
   3178 	/* When checking a CERT_PKEY structure all flags are irrelevant
   3179 	 * if the chain is invalid.
   3180 	 */
   3181 	if (!check_flags)
   3182 		{
   3183 		if (rv & CERT_PKEY_VALID)
   3184 			cpk->valid_flags = rv;
   3185 		else
   3186 			{
   3187 			/* Preserve explicit sign flag, clear rest */
   3188 			cpk->valid_flags &= CERT_PKEY_EXPLICIT_SIGN;
   3189 			return 0;
   3190 			}
   3191 		}
   3192 	return rv;
   3193 	}
   3194 
   3195 /* Set validity of certificates in an SSL structure */
   3196 void tls1_set_cert_validity(SSL *s)
   3197 	{
   3198 	tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC);
   3199 	tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN);
   3200 	tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC);
   3201 	}
   3202 /* User level utiity function to check a chain is suitable */
   3203 int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain)
   3204 	{
   3205 	return tls1_check_chain(s, x, pk, chain, -1);
   3206 	}
   3207 
   3208