xref: /dragonfly/crypto/libressl/ssl/t1_lib.c (revision 66fa3dc1)
1 /* $OpenBSD: t1_lib.c,v 1.165 2020/03/10 17:02:21 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 
112 #include <stdio.h>
113 
114 #include <openssl/evp.h>
115 #include <openssl/hmac.h>
116 #include <openssl/objects.h>
117 #include <openssl/ocsp.h>
118 
119 #include "ssl_locl.h"
120 
121 #include "bytestring.h"
122 #include "ssl_sigalgs.h"
123 #include "ssl_tlsext.h"
124 
125 static int tls_decrypt_ticket(SSL *s, CBS *session_id, CBS *ticket,
126     SSL_SESSION **psess);
127 
128 SSL3_ENC_METHOD TLSv1_enc_data = {
129 	.enc_flags = 0,
130 };
131 
132 SSL3_ENC_METHOD TLSv1_1_enc_data = {
133 	.enc_flags = SSL_ENC_FLAG_EXPLICIT_IV,
134 };
135 
136 SSL3_ENC_METHOD TLSv1_2_enc_data = {
137 	.enc_flags = SSL_ENC_FLAG_EXPLICIT_IV|SSL_ENC_FLAG_SIGALGS|
138 	    SSL_ENC_FLAG_SHA256_PRF|SSL_ENC_FLAG_TLS1_2_CIPHERS,
139 };
140 
141 long
142 tls1_default_timeout(void)
143 {
144 	/* 2 hours, the 24 hours mentioned in the TLSv1 spec
145 	 * is way too long for http, the cache would over fill */
146 	return (60 * 60 * 2);
147 }
148 
149 int
150 tls1_new(SSL *s)
151 {
152 	if (!ssl3_new(s))
153 		return (0);
154 	s->method->internal->ssl_clear(s);
155 	return (1);
156 }
157 
158 void
159 tls1_free(SSL *s)
160 {
161 	if (s == NULL)
162 		return;
163 
164 	free(s->internal->tlsext_session_ticket);
165 	ssl3_free(s);
166 }
167 
168 void
169 tls1_clear(SSL *s)
170 {
171 	ssl3_clear(s);
172 	s->version = s->method->internal->version;
173 }
174 
175 static int nid_list[] = {
176 	NID_sect163k1,		/* sect163k1 (1) */
177 	NID_sect163r1,		/* sect163r1 (2) */
178 	NID_sect163r2,		/* sect163r2 (3) */
179 	NID_sect193r1,		/* sect193r1 (4) */
180 	NID_sect193r2,		/* sect193r2 (5) */
181 	NID_sect233k1,		/* sect233k1 (6) */
182 	NID_sect233r1,		/* sect233r1 (7) */
183 	NID_sect239k1,		/* sect239k1 (8) */
184 	NID_sect283k1,		/* sect283k1 (9) */
185 	NID_sect283r1,		/* sect283r1 (10) */
186 	NID_sect409k1,		/* sect409k1 (11) */
187 	NID_sect409r1,		/* sect409r1 (12) */
188 	NID_sect571k1,		/* sect571k1 (13) */
189 	NID_sect571r1,		/* sect571r1 (14) */
190 	NID_secp160k1,		/* secp160k1 (15) */
191 	NID_secp160r1,		/* secp160r1 (16) */
192 	NID_secp160r2,		/* secp160r2 (17) */
193 	NID_secp192k1,		/* secp192k1 (18) */
194 	NID_X9_62_prime192v1,	/* secp192r1 (19) */
195 	NID_secp224k1,		/* secp224k1 (20) */
196 	NID_secp224r1,		/* secp224r1 (21) */
197 	NID_secp256k1,		/* secp256k1 (22) */
198 	NID_X9_62_prime256v1,	/* secp256r1 (23) */
199 	NID_secp384r1,		/* secp384r1 (24) */
200 	NID_secp521r1,		/* secp521r1 (25) */
201 	NID_brainpoolP256r1,	/* brainpoolP256r1 (26) */
202 	NID_brainpoolP384r1,	/* brainpoolP384r1 (27) */
203 	NID_brainpoolP512r1,	/* brainpoolP512r1 (28) */
204 	NID_X25519,		/* X25519 (29) */
205 };
206 
207 #if 0
208 static const uint8_t ecformats_list[] = {
209 	TLSEXT_ECPOINTFORMAT_uncompressed,
210 	TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime,
211 	TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2
212 };
213 #endif
214 
215 static const uint8_t ecformats_default[] = {
216 	TLSEXT_ECPOINTFORMAT_uncompressed,
217 };
218 
219 #if 0
220 static const uint16_t eccurves_list[] = {
221 	29,			/* X25519 (29) */
222 	14,			/* sect571r1 (14) */
223 	13,			/* sect571k1 (13) */
224 	25,			/* secp521r1 (25) */
225 	28,			/* brainpoolP512r1 (28) */
226 	11,			/* sect409k1 (11) */
227 	12,			/* sect409r1 (12) */
228 	27,			/* brainpoolP384r1 (27) */
229 	24,			/* secp384r1 (24) */
230 	9,			/* sect283k1 (9) */
231 	10,			/* sect283r1 (10) */
232 	26,			/* brainpoolP256r1 (26) */
233 	22,			/* secp256k1 (22) */
234 	23,			/* secp256r1 (23) */
235 	8,			/* sect239k1 (8) */
236 	6,			/* sect233k1 (6) */
237 	7,			/* sect233r1 (7) */
238 	20,			/* secp224k1 (20) */
239 	21,			/* secp224r1 (21) */
240 	4,			/* sect193r1 (4) */
241 	5,			/* sect193r2 (5) */
242 	18,			/* secp192k1 (18) */
243 	19,			/* secp192r1 (19) */
244 	1,			/* sect163k1 (1) */
245 	2,			/* sect163r1 (2) */
246 	3,			/* sect163r2 (3) */
247 	15,			/* secp160k1 (15) */
248 	16,			/* secp160r1 (16) */
249 	17,			/* secp160r2 (17) */
250 };
251 #endif
252 
253 static const uint16_t eccurves_default[] = {
254 	29,			/* X25519 (29) */
255 	23,			/* secp256r1 (23) */
256 	24,			/* secp384r1 (24) */
257 };
258 
259 int
260 tls1_ec_curve_id2nid(const uint16_t curve_id)
261 {
262 	/* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
263 	if ((curve_id < 1) ||
264 	    ((unsigned int)curve_id > sizeof(nid_list) / sizeof(nid_list[0])))
265 		return 0;
266 	return nid_list[curve_id - 1];
267 }
268 
269 uint16_t
270 tls1_ec_nid2curve_id(const int nid)
271 {
272 	/* ECC curves from draft-ietf-tls-ecc-12.txt (Oct. 17, 2005) */
273 	switch (nid) {
274 	case NID_sect163k1: /* sect163k1 (1) */
275 		return 1;
276 	case NID_sect163r1: /* sect163r1 (2) */
277 		return 2;
278 	case NID_sect163r2: /* sect163r2 (3) */
279 		return 3;
280 	case NID_sect193r1: /* sect193r1 (4) */
281 		return 4;
282 	case NID_sect193r2: /* sect193r2 (5) */
283 		return 5;
284 	case NID_sect233k1: /* sect233k1 (6) */
285 		return 6;
286 	case NID_sect233r1: /* sect233r1 (7) */
287 		return 7;
288 	case NID_sect239k1: /* sect239k1 (8) */
289 		return 8;
290 	case NID_sect283k1: /* sect283k1 (9) */
291 		return 9;
292 	case NID_sect283r1: /* sect283r1 (10) */
293 		return 10;
294 	case NID_sect409k1: /* sect409k1 (11) */
295 		return 11;
296 	case NID_sect409r1: /* sect409r1 (12) */
297 		return 12;
298 	case NID_sect571k1: /* sect571k1 (13) */
299 		return 13;
300 	case NID_sect571r1: /* sect571r1 (14) */
301 		return 14;
302 	case NID_secp160k1: /* secp160k1 (15) */
303 		return 15;
304 	case NID_secp160r1: /* secp160r1 (16) */
305 		return 16;
306 	case NID_secp160r2: /* secp160r2 (17) */
307 		return 17;
308 	case NID_secp192k1: /* secp192k1 (18) */
309 		return 18;
310 	case NID_X9_62_prime192v1: /* secp192r1 (19) */
311 		return 19;
312 	case NID_secp224k1: /* secp224k1 (20) */
313 		return 20;
314 	case NID_secp224r1: /* secp224r1 (21) */
315 		return 21;
316 	case NID_secp256k1: /* secp256k1 (22) */
317 		return 22;
318 	case NID_X9_62_prime256v1: /* secp256r1 (23) */
319 		return 23;
320 	case NID_secp384r1: /* secp384r1 (24) */
321 		return 24;
322 	case NID_secp521r1: /* secp521r1 (25) */
323 		return 25;
324 	case NID_brainpoolP256r1: /* brainpoolP256r1 (26) */
325 		return 26;
326 	case NID_brainpoolP384r1: /* brainpoolP384r1 (27) */
327 		return 27;
328 	case NID_brainpoolP512r1: /* brainpoolP512r1 (28) */
329 		return 28;
330 	case NID_X25519:		/* X25519 (29) */
331 		return 29;
332 	default:
333 		return 0;
334 	}
335 }
336 
337 /*
338  * Return the appropriate format list. If client_formats is non-zero, return
339  * the client/session formats. Otherwise return the custom format list if one
340  * exists, or the default formats if a custom list has not been specified.
341  */
342 void
343 tls1_get_formatlist(SSL *s, int client_formats, const uint8_t **pformats,
344     size_t *pformatslen)
345 {
346 	if (client_formats != 0) {
347 		*pformats = SSI(s)->tlsext_ecpointformatlist;
348 		*pformatslen = SSI(s)->tlsext_ecpointformatlist_length;
349 		return;
350 	}
351 
352 	*pformats = s->internal->tlsext_ecpointformatlist;
353 	*pformatslen = s->internal->tlsext_ecpointformatlist_length;
354 	if (*pformats == NULL) {
355 		*pformats = ecformats_default;
356 		*pformatslen = sizeof(ecformats_default);
357 	}
358 }
359 
360 /*
361  * Return the appropriate group list. If client_groups is non-zero, return
362  * the client/session groups. Otherwise return the custom group list if one
363  * exists, or the default groups if a custom list has not been specified.
364  */
365 void
366 tls1_get_group_list(SSL *s, int client_groups, const uint16_t **pgroups,
367     size_t *pgroupslen)
368 {
369 	if (client_groups != 0) {
370 		*pgroups = SSI(s)->tlsext_supportedgroups;
371 		*pgroupslen = SSI(s)->tlsext_supportedgroups_length;
372 		return;
373 	}
374 
375 	*pgroups = s->internal->tlsext_supportedgroups;
376 	*pgroupslen = s->internal->tlsext_supportedgroups_length;
377 	if (*pgroups == NULL) {
378 		*pgroups = eccurves_default;
379 		*pgroupslen = sizeof(eccurves_default) / 2;
380 	}
381 }
382 
383 int
384 tls1_set_groups(uint16_t **out_group_ids, size_t *out_group_ids_len,
385     const int *groups, size_t ngroups)
386 {
387 	uint16_t *group_ids;
388 	size_t i;
389 
390 	group_ids = calloc(ngroups, sizeof(uint16_t));
391 	if (group_ids == NULL)
392 		return 0;
393 
394 	for (i = 0; i < ngroups; i++) {
395 		group_ids[i] = tls1_ec_nid2curve_id(groups[i]);
396 		if (group_ids[i] == 0) {
397 			free(group_ids);
398 			return 0;
399 		}
400 	}
401 
402 	free(*out_group_ids);
403 	*out_group_ids = group_ids;
404 	*out_group_ids_len = ngroups;
405 
406 	return 1;
407 }
408 
409 int
410 tls1_set_group_list(uint16_t **out_group_ids, size_t *out_group_ids_len,
411     const char *groups)
412 {
413 	uint16_t *new_group_ids, *group_ids = NULL;
414 	size_t ngroups = 0;
415 	char *gs, *p, *q;
416 	int nid;
417 
418 	if ((gs = strdup(groups)) == NULL)
419 		return 0;
420 
421 	q = gs;
422 	while ((p = strsep(&q, ":")) != NULL) {
423 		nid = OBJ_sn2nid(p);
424 		if (nid == NID_undef)
425 			nid = OBJ_ln2nid(p);
426 		if (nid == NID_undef)
427 			nid = EC_curve_nist2nid(p);
428 		if (nid == NID_undef)
429 			goto err;
430 
431 		if ((new_group_ids = reallocarray(group_ids, ngroups + 1,
432 		    sizeof(uint16_t))) == NULL)
433 			goto err;
434 		group_ids = new_group_ids;
435 
436 		group_ids[ngroups] = tls1_ec_nid2curve_id(nid);
437 		if (group_ids[ngroups] == 0)
438 			goto err;
439 
440 		ngroups++;
441 	}
442 
443 	free(gs);
444 	free(*out_group_ids);
445 	*out_group_ids = group_ids;
446 	*out_group_ids_len = ngroups;
447 
448 	return 1;
449 
450  err:
451 	free(gs);
452 	free(group_ids);
453 
454 	return 0;
455 }
456 
457 /* Check that a curve is one of our preferences. */
458 int
459 tls1_check_curve(SSL *s, const uint16_t curve_id)
460 {
461 	const uint16_t *groups;
462 	size_t groupslen, i;
463 
464 	tls1_get_group_list(s, 0, &groups, &groupslen);
465 
466 	for (i = 0; i < groupslen; i++) {
467 		if (groups[i] == curve_id)
468 			return (1);
469 	}
470 	return (0);
471 }
472 
473 int
474 tls1_get_shared_curve(SSL *s)
475 {
476 	size_t preflen, supplen, i, j;
477 	const uint16_t *pref, *supp;
478 	unsigned long server_pref;
479 
480 	/* Cannot do anything on the client side. */
481 	if (s->server == 0)
482 		return (NID_undef);
483 
484 	/* Return first preference shared curve. */
485 	server_pref = (s->internal->options & SSL_OP_CIPHER_SERVER_PREFERENCE);
486 	tls1_get_group_list(s, (server_pref == 0), &pref, &preflen);
487 	tls1_get_group_list(s, (server_pref != 0), &supp, &supplen);
488 
489 	for (i = 0; i < preflen; i++) {
490 		for (j = 0; j < supplen; j++) {
491 			if (pref[i] == supp[j])
492 				return (tls1_ec_curve_id2nid(pref[i]));
493 		}
494 	}
495 	return (NID_undef);
496 }
497 
498 /* For an EC key set TLS ID and required compression based on parameters. */
499 static int
500 tls1_set_ec_id(uint16_t *curve_id, uint8_t *comp_id, EC_KEY *ec)
501 {
502 	const EC_GROUP *grp;
503 	const EC_METHOD *meth;
504 	int is_prime = 0;
505 	int nid, id;
506 
507 	if (ec == NULL)
508 		return (0);
509 
510 	/* Determine if it is a prime field. */
511 	if ((grp = EC_KEY_get0_group(ec)) == NULL)
512 		return (0);
513 	if ((meth = EC_GROUP_method_of(grp)) == NULL)
514 		return (0);
515 	if (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field)
516 		is_prime = 1;
517 
518 	/* Determine curve ID. */
519 	nid = EC_GROUP_get_curve_name(grp);
520 	id = tls1_ec_nid2curve_id(nid);
521 
522 	/* If we have an ID set it, otherwise set arbitrary explicit curve. */
523 	if (id != 0)
524 		*curve_id = id;
525 	else
526 		*curve_id = is_prime ? 0xff01 : 0xff02;
527 
528 	/* Specify the compression identifier. */
529 	if (comp_id != NULL) {
530 		if (EC_KEY_get0_public_key(ec) == NULL)
531 			return (0);
532 
533 		if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_COMPRESSED) {
534 			*comp_id = is_prime ?
535 			    TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime :
536 			    TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2;
537 		} else {
538 			*comp_id = TLSEXT_ECPOINTFORMAT_uncompressed;
539 		}
540 	}
541 	return (1);
542 }
543 
544 /* Check that an EC key is compatible with extensions. */
545 static int
546 tls1_check_ec_key(SSL *s, const uint16_t *curve_id, const uint8_t *comp_id)
547 {
548 	size_t groupslen, formatslen, i;
549 	const uint16_t *groups;
550 	const uint8_t *formats;
551 
552 	/*
553 	 * Check point formats extension if present, otherwise everything
554 	 * is supported (see RFC4492).
555 	 */
556 	tls1_get_formatlist(s, 1, &formats, &formatslen);
557 	if (comp_id != NULL && formats != NULL) {
558 		for (i = 0; i < formatslen; i++) {
559 			if (formats[i] == *comp_id)
560 				break;
561 		}
562 		if (i == formatslen)
563 			return (0);
564 	}
565 
566 	/*
567 	 * Check curve list if present, otherwise everything is supported.
568 	 */
569 	tls1_get_group_list(s, 1, &groups, &groupslen);
570 	if (curve_id != NULL && groups != NULL) {
571 		for (i = 0; i < groupslen; i++) {
572 			if (groups[i] == *curve_id)
573 				break;
574 		}
575 		if (i == groupslen)
576 			return (0);
577 	}
578 
579 	return (1);
580 }
581 
582 /* Check EC server key is compatible with client extensions. */
583 int
584 tls1_check_ec_server_key(SSL *s)
585 {
586 	CERT_PKEY *cpk = s->cert->pkeys + SSL_PKEY_ECC;
587 	uint16_t curve_id;
588 	uint8_t comp_id;
589 	EVP_PKEY *pkey;
590 	int rv;
591 
592 	if (cpk->x509 == NULL || cpk->privatekey == NULL)
593 		return (0);
594 	if ((pkey = X509_get_pubkey(cpk->x509)) == NULL)
595 		return (0);
596 	rv = tls1_set_ec_id(&curve_id, &comp_id, pkey->pkey.ec);
597 	EVP_PKEY_free(pkey);
598 	if (rv != 1)
599 		return (0);
600 
601 	return tls1_check_ec_key(s, &curve_id, &comp_id);
602 }
603 
604 int
605 ssl_check_clienthello_tlsext_early(SSL *s)
606 {
607 	int ret = SSL_TLSEXT_ERR_NOACK;
608 	int al = SSL_AD_UNRECOGNIZED_NAME;
609 
610 	/* The handling of the ECPointFormats extension is done elsewhere, namely in
611 	 * ssl3_choose_cipher in s3_lib.c.
612 	 */
613 	/* The handling of the EllipticCurves extension is done elsewhere, namely in
614 	 * ssl3_choose_cipher in s3_lib.c.
615 	 */
616 
617 	if (s->ctx != NULL && s->ctx->internal->tlsext_servername_callback != 0)
618 		ret = s->ctx->internal->tlsext_servername_callback(s, &al,
619 		    s->ctx->internal->tlsext_servername_arg);
620 	else if (s->initial_ctx != NULL && s->initial_ctx->internal->tlsext_servername_callback != 0)
621 		ret = s->initial_ctx->internal->tlsext_servername_callback(s, &al,
622 		    s->initial_ctx->internal->tlsext_servername_arg);
623 
624 	switch (ret) {
625 	case SSL_TLSEXT_ERR_ALERT_FATAL:
626 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
627 		return -1;
628 	case SSL_TLSEXT_ERR_ALERT_WARNING:
629 		ssl3_send_alert(s, SSL3_AL_WARNING, al);
630 		return 1;
631 	case SSL_TLSEXT_ERR_NOACK:
632 		s->internal->servername_done = 0;
633 	default:
634 		return 1;
635 	}
636 }
637 
638 int
639 ssl_check_clienthello_tlsext_late(SSL *s)
640 {
641 	int ret = SSL_TLSEXT_ERR_OK;
642 	int al = 0;	/* XXX gcc3 */
643 
644 	/* If status request then ask callback what to do.
645  	 * Note: this must be called after servername callbacks in case
646  	 * the certificate has changed, and must be called after the cipher
647 	 * has been chosen because this may influence which certificate is sent
648  	 */
649 	if ((s->tlsext_status_type != -1) &&
650 	    s->ctx && s->ctx->internal->tlsext_status_cb) {
651 		int r;
652 		CERT_PKEY *certpkey;
653 		certpkey = ssl_get_server_send_pkey(s);
654 		/* If no certificate can't return certificate status */
655 		if (certpkey == NULL) {
656 			s->internal->tlsext_status_expected = 0;
657 			return 1;
658 		}
659 		/* Set current certificate to one we will use so
660 		 * SSL_get_certificate et al can pick it up.
661 		 */
662 		s->cert->key = certpkey;
663 		r = s->ctx->internal->tlsext_status_cb(s,
664 		    s->ctx->internal->tlsext_status_arg);
665 		switch (r) {
666 			/* We don't want to send a status request response */
667 		case SSL_TLSEXT_ERR_NOACK:
668 			s->internal->tlsext_status_expected = 0;
669 			break;
670 			/* status request response should be sent */
671 		case SSL_TLSEXT_ERR_OK:
672 			if (s->internal->tlsext_ocsp_resp)
673 				s->internal->tlsext_status_expected = 1;
674 			else
675 				s->internal->tlsext_status_expected = 0;
676 			break;
677 			/* something bad happened */
678 		case SSL_TLSEXT_ERR_ALERT_FATAL:
679 			ret = SSL_TLSEXT_ERR_ALERT_FATAL;
680 			al = SSL_AD_INTERNAL_ERROR;
681 			goto err;
682 		}
683 	} else
684 		s->internal->tlsext_status_expected = 0;
685 
686 err:
687 	switch (ret) {
688 	case SSL_TLSEXT_ERR_ALERT_FATAL:
689 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
690 		return -1;
691 	case SSL_TLSEXT_ERR_ALERT_WARNING:
692 		ssl3_send_alert(s, SSL3_AL_WARNING, al);
693 		return 1;
694 	default:
695 		return 1;
696 	}
697 }
698 
699 int
700 ssl_check_serverhello_tlsext(SSL *s)
701 {
702 	int ret = SSL_TLSEXT_ERR_NOACK;
703 	int al = SSL_AD_UNRECOGNIZED_NAME;
704 
705 	ret = SSL_TLSEXT_ERR_OK;
706 
707 	if (s->ctx != NULL && s->ctx->internal->tlsext_servername_callback != 0)
708 		ret = s->ctx->internal->tlsext_servername_callback(s, &al,
709 		    s->ctx->internal->tlsext_servername_arg);
710 	else if (s->initial_ctx != NULL && s->initial_ctx->internal->tlsext_servername_callback != 0)
711 		ret = s->initial_ctx->internal->tlsext_servername_callback(s, &al,
712 		    s->initial_ctx->internal->tlsext_servername_arg);
713 
714 	/* If we've requested certificate status and we wont get one
715  	 * tell the callback
716  	 */
717 	if ((s->tlsext_status_type != -1) && !(s->internal->tlsext_status_expected) &&
718 	    s->ctx && s->ctx->internal->tlsext_status_cb) {
719 		int r;
720 		/* Set resp to NULL, resplen to -1 so callback knows
721  		 * there is no response.
722  		 */
723 		free(s->internal->tlsext_ocsp_resp);
724 		s->internal->tlsext_ocsp_resp = NULL;
725 		s->internal->tlsext_ocsp_resplen = -1;
726 		r = s->ctx->internal->tlsext_status_cb(s,
727 		    s->ctx->internal->tlsext_status_arg);
728 		if (r == 0) {
729 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
730 			ret = SSL_TLSEXT_ERR_ALERT_FATAL;
731 		}
732 		if (r < 0) {
733 			al = SSL_AD_INTERNAL_ERROR;
734 			ret = SSL_TLSEXT_ERR_ALERT_FATAL;
735 		}
736 	}
737 
738 	switch (ret) {
739 	case SSL_TLSEXT_ERR_ALERT_FATAL:
740 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
741 
742 		return -1;
743 	case SSL_TLSEXT_ERR_ALERT_WARNING:
744 		ssl3_send_alert(s, SSL3_AL_WARNING, al);
745 
746 		return 1;
747 	case SSL_TLSEXT_ERR_NOACK:
748 		s->internal->servername_done = 0;
749 	default:
750 		return 1;
751 	}
752 }
753 
754 /* Since the server cache lookup is done early on in the processing of the
755  * ClientHello, and other operations depend on the result, we need to handle
756  * any TLS session ticket extension at the same time.
757  *
758  *   session_id: a CBS containing the session ID.
759  *   ext_block: a CBS for the ClientHello extensions block.
760  *   ret: (output) on return, if a ticket was decrypted, then this is set to
761  *       point to the resulting session.
762  *
763  * If s->internal->tls_session_secret_cb is set then we are expecting a pre-shared key
764  * ciphersuite, in which case we have no use for session tickets and one will
765  * never be decrypted, nor will s->internal->tlsext_ticket_expected be set to 1.
766  *
767  * Returns:
768  *   -1: fatal error, either from parsing or decrypting the ticket.
769  *    0: no ticket was found (or was ignored, based on settings).
770  *    1: a zero length extension was found, indicating that the client supports
771  *       session tickets but doesn't currently have one to offer.
772  *    2: either s->internal->tls_session_secret_cb was set, or a ticket was offered but
773  *       couldn't be decrypted because of a non-fatal error.
774  *    3: a ticket was successfully decrypted and *ret was set.
775  *
776  * Side effects:
777  *   Sets s->internal->tlsext_ticket_expected to 1 if the server will have to issue
778  *   a new session ticket to the client because the client indicated support
779  *   (and s->internal->tls_session_secret_cb is NULL) but the client either doesn't have
780  *   a session ticket or we couldn't use the one it gave us, or if
781  *   s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket.
782  *   Otherwise, s->internal->tlsext_ticket_expected is set to 0.
783  */
784 int
785 tls1_process_ticket(SSL *s, CBS *session_id, CBS *ext_block, SSL_SESSION **ret)
786 {
787 	CBS extensions, ext_data;
788 	uint16_t ext_type = 0;
789 	int r;
790 
791 	s->internal->tlsext_ticket_expected = 0;
792 	*ret = NULL;
793 
794 	/*
795 	 * If tickets disabled behave as if no ticket present to permit stateful
796 	 * resumption.
797 	 */
798 	if (SSL_get_options(s) & SSL_OP_NO_TICKET)
799 		return 0;
800 
801 	/*
802 	 * An empty extensions block is valid, but obviously does not contain
803 	 * a session ticket.
804 	 */
805 	if (CBS_len(ext_block) == 0)
806 		return 0;
807 
808 	if (!CBS_get_u16_length_prefixed(ext_block, &extensions))
809 		return -1;
810 
811 	while (CBS_len(&extensions) > 0) {
812 		if (!CBS_get_u16(&extensions, &ext_type) ||
813 		    !CBS_get_u16_length_prefixed(&extensions, &ext_data))
814 			return -1;
815 
816 		if (ext_type == TLSEXT_TYPE_session_ticket)
817 			break;
818 	}
819 
820 	if (ext_type != TLSEXT_TYPE_session_ticket)
821 		return 0;
822 
823 	if (CBS_len(&ext_data) == 0) {
824 		/*
825 		 * The client will accept a ticket but does not currently
826 		 * have one.
827 		 */
828 		s->internal->tlsext_ticket_expected = 1;
829 		return 1;
830 	}
831 
832 	if (s->internal->tls_session_secret_cb != NULL) {
833 		/*
834 		 * Indicate that the ticket could not be decrypted rather than
835 		 * generating the session from ticket now, trigger abbreviated
836 		 * handshake based on external mechanism to calculate the master
837 		 * secret later.
838 		 */
839 		return 2;
840 	}
841 
842 	r = tls_decrypt_ticket(s, session_id, &ext_data, ret);
843 	switch (r) {
844 	case 2: /* ticket couldn't be decrypted */
845 		s->internal->tlsext_ticket_expected = 1;
846 		return 2;
847 	case 3: /* ticket was decrypted */
848 		return r;
849 	case 4: /* ticket decrypted but need to renew */
850 		s->internal->tlsext_ticket_expected = 1;
851 		return 3;
852 	default: /* fatal error */
853 		return -1;
854 	}
855 }
856 
857 /* tls_decrypt_ticket attempts to decrypt a session ticket.
858  *
859  *   session_id: a CBS containing the session ID.
860  *   ticket: a CBS containing the body of the session ticket extension.
861  *   psess: (output) on return, if a ticket was decrypted, then this is set to
862  *       point to the resulting session.
863  *
864  * Returns:
865  *   -1: fatal error, either from parsing or decrypting the ticket.
866  *    2: the ticket couldn't be decrypted.
867  *    3: a ticket was successfully decrypted and *psess was set.
868  *    4: same as 3, but the ticket needs to be renewed.
869  */
870 static int
871 tls_decrypt_ticket(SSL *s, CBS *session_id, CBS *ticket, SSL_SESSION **psess)
872 {
873 	CBS ticket_name, ticket_iv, ticket_encdata, ticket_hmac;
874 	SSL_SESSION *sess = NULL;
875 	unsigned char *sdec = NULL;
876 	size_t sdec_len = 0;
877 	size_t session_id_len;
878 	const unsigned char *p;
879 	unsigned char hmac[EVP_MAX_MD_SIZE];
880 	HMAC_CTX *hctx = NULL;
881 	EVP_CIPHER_CTX *cctx = NULL;
882 	SSL_CTX *tctx = s->initial_ctx;
883 	int slen, hlen;
884 	int renew_ticket = 0;
885 	int ret = -1;
886 
887 	*psess = NULL;
888 
889 	if (!CBS_get_bytes(ticket, &ticket_name, 16))
890 		goto derr;
891 
892 	/*
893 	 * Initialize session ticket encryption and HMAC contexts.
894 	 */
895 	if ((cctx = EVP_CIPHER_CTX_new()) == NULL)
896 		goto err;
897 	if ((hctx = HMAC_CTX_new()) == NULL)
898 		goto err;
899 
900 	if (tctx->internal->tlsext_ticket_key_cb != NULL) {
901 		int rv;
902 
903 		/*
904 		 * The API guarantees EVP_MAX_IV_LENGTH bytes of space for
905 		 * the iv to tlsext_ticket_key_cb().  Since the total space
906 		 * required for a session cookie is never less than this,
907 		 * this check isn't too strict.  The exact check comes later.
908 		 */
909 		if (CBS_len(ticket) < EVP_MAX_IV_LENGTH)
910 			goto derr;
911 
912 		if ((rv = tctx->internal->tlsext_ticket_key_cb(s,
913 		    (unsigned char *)CBS_data(&ticket_name),
914 		    (unsigned char *)CBS_data(ticket), cctx, hctx, 0)) < 0)
915 			goto err;
916 		if (rv == 0)
917 			goto derr;
918 		if (rv == 2)
919 			renew_ticket = 1;
920 
921 		/*
922 		 * Now that the cipher context is initialised, we can extract
923 		 * the IV since its length is known.
924 		 */
925 		if (!CBS_get_bytes(ticket, &ticket_iv,
926 		    EVP_CIPHER_CTX_iv_length(cctx)))
927 			goto derr;
928 	} else {
929 		/* Check that the key name matches. */
930 		if (!CBS_mem_equal(&ticket_name,
931 		    tctx->internal->tlsext_tick_key_name,
932 		    sizeof(tctx->internal->tlsext_tick_key_name)))
933 			goto derr;
934 		if (!CBS_get_bytes(ticket, &ticket_iv,
935 		    EVP_CIPHER_iv_length(EVP_aes_128_cbc())))
936 			goto derr;
937 		if (!EVP_DecryptInit_ex(cctx, EVP_aes_128_cbc(), NULL,
938 		    tctx->internal->tlsext_tick_aes_key, CBS_data(&ticket_iv)))
939 			goto err;
940 		if (!HMAC_Init_ex(hctx, tctx->internal->tlsext_tick_hmac_key,
941 		    sizeof(tctx->internal->tlsext_tick_hmac_key), EVP_sha256(),
942 		    NULL))
943 			goto err;
944 	}
945 
946 	/*
947 	 * Attempt to process session ticket.
948 	 */
949 
950 	if ((hlen = HMAC_size(hctx)) < 0)
951 		goto err;
952 
953 	if (hlen > CBS_len(ticket))
954 		goto derr;
955 	if (!CBS_get_bytes(ticket, &ticket_encdata, CBS_len(ticket) - hlen))
956 		goto derr;
957 	if (!CBS_get_bytes(ticket, &ticket_hmac, hlen))
958 		goto derr;
959 	if (CBS_len(ticket) != 0)
960 		goto err;
961 
962 	/* Check HMAC of encrypted ticket. */
963 	if (HMAC_Update(hctx, CBS_data(&ticket_name),
964 	    CBS_len(&ticket_name)) <= 0)
965 		goto err;
966 	if (HMAC_Update(hctx, CBS_data(&ticket_iv),
967 	    CBS_len(&ticket_iv)) <= 0)
968 		goto err;
969 	if (HMAC_Update(hctx, CBS_data(&ticket_encdata),
970 	    CBS_len(&ticket_encdata)) <= 0)
971 		goto err;
972 	if (HMAC_Final(hctx, hmac, &hlen) <= 0)
973 		goto err;
974 
975 	if (!CBS_mem_equal(&ticket_hmac, hmac, hlen))
976 		goto derr;
977 
978 	/* Attempt to decrypt session data. */
979 	sdec_len = CBS_len(&ticket_encdata);
980 	if ((sdec = calloc(1, sdec_len)) == NULL)
981 		goto err;
982 	if (EVP_DecryptUpdate(cctx, sdec, &slen, CBS_data(&ticket_encdata),
983 	    CBS_len(&ticket_encdata)) <= 0)
984 		goto derr;
985 	if (EVP_DecryptFinal_ex(cctx, sdec + slen, &hlen) <= 0)
986 		goto derr;
987 
988 	slen += hlen;
989 
990 	/*
991 	 * For session parse failures, indicate that we need to send a new
992 	 * ticket.
993 	 */
994 	p = sdec;
995 	if ((sess = d2i_SSL_SESSION(NULL, &p, slen)) == NULL)
996 		goto derr;
997 
998 	/*
999 	 * The session ID, if non-empty, is used by some clients to detect that
1000 	 * the ticket has been accepted. So we copy it to the session structure.
1001 	 * If it is empty set length to zero as required by standard.
1002 	 */
1003 	if (!CBS_write_bytes(session_id, sess->session_id,
1004 	    sizeof(sess->session_id), &session_id_len))
1005 		goto err;
1006 	sess->session_id_length = (unsigned int)session_id_len;
1007 
1008 	*psess = sess;
1009 	sess = NULL;
1010 
1011 	if (renew_ticket)
1012 		ret = 4;
1013 	else
1014 		ret = 3;
1015 
1016 	goto done;
1017 
1018  derr:
1019 	ret = 2;
1020 	goto done;
1021 
1022  err:
1023 	ret = -1;
1024 	goto done;
1025 
1026  done:
1027 	freezero(sdec, sdec_len);
1028 	EVP_CIPHER_CTX_free(cctx);
1029 	HMAC_CTX_free(hctx);
1030 	SSL_SESSION_free(sess);
1031 
1032 	if (ret == 2)
1033 		ERR_clear_error();
1034 
1035 	return ret;
1036 }
1037