xref: /openbsd-src/lib/libssl/t1_enc.c (revision b99ef4df7fac99f3475b694d6cd4990521c99ae6)
1 /* $OpenBSD: t1_enc.c,v 1.132 2021/02/03 15:14:44 tb 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  * Copyright 2005 Nokia. All rights reserved.
113  *
114  * The portions of the attached software ("Contribution") is developed by
115  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116  * license.
117  *
118  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120  * support (see RFC 4279) to OpenSSL.
121  *
122  * No patent licenses or other rights except those expressly stated in
123  * the OpenSSL open source license shall be deemed granted or received
124  * expressly, by implication, estoppel, or otherwise.
125  *
126  * No assurances are provided by Nokia that the Contribution does not
127  * infringe the patent or other intellectual property rights of any third
128  * party or that the license provides you with all the necessary rights
129  * to make use of the Contribution.
130  *
131  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135  * OTHERWISE.
136  */
137 
138 #include <limits.h>
139 #include <stdio.h>
140 
141 #include "ssl_locl.h"
142 
143 #include <openssl/evp.h>
144 #include <openssl/hmac.h>
145 #include <openssl/md5.h>
146 
147 int tls1_PRF(SSL *s, const unsigned char *secret, size_t secret_len,
148     const void *seed1, size_t seed1_len, const void *seed2, size_t seed2_len,
149     const void *seed3, size_t seed3_len, const void *seed4, size_t seed4_len,
150     const void *seed5, size_t seed5_len, unsigned char *out, size_t out_len);
151 
152 void
153 tls1_cleanup_key_block(SSL *s)
154 {
155 	freezero(S3I(s)->hs.key_block, S3I(s)->hs.key_block_len);
156 	S3I(s)->hs.key_block = NULL;
157 	S3I(s)->hs.key_block_len = 0;
158 }
159 
160 void
161 tls1_record_sequence_increment(unsigned char *seq)
162 {
163 	int i;
164 
165 	for (i = SSL3_SEQUENCE_SIZE - 1; i >= 0; i--) {
166 		if (++seq[i] != 0)
167 			break;
168 	}
169 }
170 
171 /*
172  * TLS P_hash() data expansion function - see RFC 5246, section 5.
173  */
174 static int
175 tls1_P_hash(const EVP_MD *md, const unsigned char *secret, size_t secret_len,
176     const void *seed1, size_t seed1_len, const void *seed2, size_t seed2_len,
177     const void *seed3, size_t seed3_len, const void *seed4, size_t seed4_len,
178     const void *seed5, size_t seed5_len, unsigned char *out, size_t out_len)
179 {
180 	unsigned char A1[EVP_MAX_MD_SIZE], hmac[EVP_MAX_MD_SIZE];
181 	size_t A1_len, hmac_len;
182 	EVP_MD_CTX ctx;
183 	EVP_PKEY *mac_key;
184 	int ret = 0;
185 	int chunk;
186 	size_t i;
187 
188 	chunk = EVP_MD_size(md);
189 	OPENSSL_assert(chunk >= 0);
190 
191 	EVP_MD_CTX_init(&ctx);
192 
193 	mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
194 	if (!mac_key)
195 		goto err;
196 	if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
197 		goto err;
198 	if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
199 		goto err;
200 	if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
201 		goto err;
202 	if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
203 		goto err;
204 	if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
205 		goto err;
206 	if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
207 		goto err;
208 	if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
209 		goto err;
210 
211 	for (;;) {
212 		if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
213 			goto err;
214 		if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
215 			goto err;
216 		if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
217 			goto err;
218 		if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
219 			goto err;
220 		if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
221 			goto err;
222 		if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
223 			goto err;
224 		if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
225 			goto err;
226 		if (!EVP_DigestSignFinal(&ctx, hmac, &hmac_len))
227 			goto err;
228 
229 		if (hmac_len > out_len)
230 			hmac_len = out_len;
231 
232 		for (i = 0; i < hmac_len; i++)
233 			out[i] ^= hmac[i];
234 
235 		out += hmac_len;
236 		out_len -= hmac_len;
237 
238 		if (out_len == 0)
239 			break;
240 
241 		if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
242 			goto err;
243 		if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
244 			goto err;
245 		if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
246 			goto err;
247 	}
248 	ret = 1;
249 
250  err:
251 	EVP_PKEY_free(mac_key);
252 	EVP_MD_CTX_cleanup(&ctx);
253 
254 	explicit_bzero(A1, sizeof(A1));
255 	explicit_bzero(hmac, sizeof(hmac));
256 
257 	return ret;
258 }
259 
260 int
261 tls1_PRF(SSL *s, const unsigned char *secret, size_t secret_len,
262     const void *seed1, size_t seed1_len, const void *seed2, size_t seed2_len,
263     const void *seed3, size_t seed3_len, const void *seed4, size_t seed4_len,
264     const void *seed5, size_t seed5_len, unsigned char *out, size_t out_len)
265 {
266 	const EVP_MD *md;
267 	size_t half_len;
268 
269 	memset(out, 0, out_len);
270 
271 	if (!ssl_get_handshake_evp_md(s, &md))
272 		return (0);
273 
274 	if (md->type == NID_md5_sha1) {
275 		/*
276 		 * Partition secret between MD5 and SHA1, then XOR result.
277 		 * If the secret length is odd, a one byte overlap is used.
278 		 */
279 		half_len = secret_len - (secret_len / 2);
280 		if (!tls1_P_hash(EVP_md5(), secret, half_len, seed1, seed1_len,
281 		    seed2, seed2_len, seed3, seed3_len, seed4, seed4_len,
282 		    seed5, seed5_len, out, out_len))
283 			return (0);
284 
285 		secret += secret_len - half_len;
286 		if (!tls1_P_hash(EVP_sha1(), secret, half_len, seed1, seed1_len,
287 		    seed2, seed2_len, seed3, seed3_len, seed4, seed4_len,
288 		    seed5, seed5_len, out, out_len))
289 			return (0);
290 
291 		return (1);
292 	}
293 
294 	if (!tls1_P_hash(md, secret, secret_len, seed1, seed1_len,
295 	    seed2, seed2_len, seed3, seed3_len, seed4, seed4_len,
296 	    seed5, seed5_len, out, out_len))
297 		return (0);
298 
299 	return (1);
300 }
301 
302 static int
303 tls1_generate_key_block(SSL *s, uint8_t *key_block, size_t key_block_len)
304 {
305 	return tls1_PRF(s,
306 	    s->session->master_key, s->session->master_key_length,
307 	    TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
308 	    s->s3->server_random, SSL3_RANDOM_SIZE,
309 	    s->s3->client_random, SSL3_RANDOM_SIZE,
310 	    NULL, 0, NULL, 0, key_block, key_block_len);
311 }
312 
313 /*
314  * tls1_change_cipher_state_cipher performs the work needed to switch cipher
315  * states when using EVP_CIPHER. The argument is_read is true iff this function
316  * is being called due to reading, as opposed to writing, a ChangeCipherSpec
317  * message.
318  */
319 static int
320 tls1_change_cipher_state_cipher(SSL *s, char is_read,
321     const unsigned char *mac_secret, unsigned int mac_secret_size,
322     const unsigned char *key, unsigned int key_len, const unsigned char *iv,
323     unsigned int iv_len)
324 {
325 	EVP_CIPHER_CTX *cipher_ctx;
326 	const EVP_CIPHER *cipher;
327 	EVP_MD_CTX *mac_ctx;
328 	EVP_PKEY *mac_key;
329 	const EVP_MD *mac;
330 	int stream_mac;
331 	int mac_type;
332 
333 	cipher = S3I(s)->tmp.new_sym_enc;
334 	mac = S3I(s)->tmp.new_hash;
335 	mac_type = S3I(s)->tmp.new_mac_pkey_type;
336 	stream_mac = S3I(s)->hs.new_cipher->algorithm2 & TLS1_STREAM_MAC;
337 
338 	if (is_read) {
339 		ssl_clear_cipher_read_state(s);
340 
341 		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
342 			goto err;
343 		s->enc_read_ctx = cipher_ctx;
344 		if ((mac_ctx = EVP_MD_CTX_new()) == NULL)
345 			goto err;
346 		s->read_hash = mac_ctx;
347 
348 		if (!tls12_record_layer_set_read_cipher_hash(s->internal->rl,
349 		    cipher_ctx, mac_ctx, stream_mac))
350 			goto err;
351 
352 		if (!tls12_record_layer_set_read_mac_key(s->internal->rl,
353 		    mac_secret, mac_secret_size))
354 			goto err;
355 	} else {
356 		/*
357 		 * DTLS fragments retain a pointer to the compression, cipher
358 		 * and hash contexts, so that it can restore state in order
359 		 * to perform retransmissions. As such, we cannot free write
360 		 * contexts that are used for DTLS - these are instead freed
361 		 * by DTLS when its frees a ChangeCipherSpec fragment.
362 		 */
363 		if (!SSL_is_dtls(s))
364 			ssl_clear_cipher_write_state(s);
365 
366 		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
367 			goto err;
368 		s->internal->enc_write_ctx = cipher_ctx;
369 		if ((mac_ctx = EVP_MD_CTX_new()) == NULL)
370 			goto err;
371 		s->internal->write_hash = mac_ctx;
372 
373 		if (!tls12_record_layer_set_write_cipher_hash(s->internal->rl,
374 		    cipher_ctx, mac_ctx, stream_mac))
375 			goto err;
376 	}
377 
378 	EVP_CipherInit_ex(cipher_ctx, cipher, NULL, key, iv, !is_read);
379 
380 	if ((mac_key = EVP_PKEY_new_mac_key(mac_type, NULL, mac_secret,
381 	    mac_secret_size)) == NULL)
382 		goto err;
383 	EVP_DigestSignInit(mac_ctx, NULL, mac, NULL, mac_key);
384 	EVP_PKEY_free(mac_key);
385 
386 	if (S3I(s)->hs.new_cipher->algorithm_enc == SSL_eGOST2814789CNT) {
387 		int nid;
388 		if (S3I(s)->hs.new_cipher->algorithm2 & SSL_HANDSHAKE_MAC_GOST94)
389 			nid = NID_id_Gost28147_89_CryptoPro_A_ParamSet;
390 		else
391 			nid = NID_id_tc26_gost_28147_param_Z;
392 
393 		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GOST_SET_SBOX, nid, 0);
394 		if (S3I(s)->hs.new_cipher->algorithm_mac == SSL_GOST89MAC)
395 			EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_GOST_SET_SBOX, nid, 0);
396 	}
397 
398 	return (1);
399 
400 err:
401 	SSLerrorx(ERR_R_MALLOC_FAILURE);
402 	return (0);
403 }
404 
405 int
406 tls1_change_cipher_state(SSL *s, int which)
407 {
408 	const unsigned char *client_write_mac_secret, *server_write_mac_secret;
409 	const unsigned char *client_write_key, *server_write_key;
410 	const unsigned char *client_write_iv, *server_write_iv;
411 	const unsigned char *mac_secret, *key, *iv;
412 	int mac_secret_size, key_len, iv_len;
413 	unsigned char *key_block;
414 	const EVP_CIPHER *cipher;
415 	const EVP_AEAD *aead;
416 	char is_read, use_client_keys;
417 
418 	cipher = S3I(s)->tmp.new_sym_enc;
419 	aead = S3I(s)->tmp.new_aead;
420 
421 	/*
422 	 * is_read is true if we have just read a ChangeCipherSpec message,
423 	 * that is we need to update the read cipherspec. Otherwise we have
424 	 * just written one.
425 	 */
426 	is_read = (which & SSL3_CC_READ) != 0;
427 
428 	/*
429 	 * use_client_keys is true if we wish to use the keys for the "client
430 	 * write" direction. This is the case if we're a client sending a
431 	 * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec.
432 	 */
433 	use_client_keys = ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
434 	    (which == SSL3_CHANGE_CIPHER_SERVER_READ));
435 
436 	if (aead != NULL) {
437 		key_len = EVP_AEAD_key_length(aead);
438 		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(S3I(s)->hs.new_cipher);
439 	} else {
440 		key_len = EVP_CIPHER_key_length(cipher);
441 		iv_len = EVP_CIPHER_iv_length(cipher);
442 	}
443 
444 	mac_secret_size = S3I(s)->tmp.new_mac_secret_size;
445 
446 	key_block = S3I(s)->hs.key_block;
447 	client_write_mac_secret = key_block;
448 	key_block += mac_secret_size;
449 	server_write_mac_secret = key_block;
450 	key_block += mac_secret_size;
451 	client_write_key = key_block;
452 	key_block += key_len;
453 	server_write_key = key_block;
454 	key_block += key_len;
455 	client_write_iv = key_block;
456 	key_block += iv_len;
457 	server_write_iv = key_block;
458 	key_block += iv_len;
459 
460 	if (use_client_keys) {
461 		mac_secret = client_write_mac_secret;
462 		key = client_write_key;
463 		iv = client_write_iv;
464 	} else {
465 		mac_secret = server_write_mac_secret;
466 		key = server_write_key;
467 		iv = server_write_iv;
468 	}
469 
470 	if (key_block - S3I(s)->hs.key_block != S3I(s)->hs.key_block_len) {
471 		SSLerror(s, ERR_R_INTERNAL_ERROR);
472 		goto err;
473 	}
474 
475 	if (is_read) {
476 		if (!tls12_record_layer_change_read_cipher_state(s->internal->rl,
477 		    mac_secret, mac_secret_size, key, key_len, iv, iv_len))
478 			goto err;
479 	} else {
480 		if (!tls12_record_layer_change_write_cipher_state(s->internal->rl,
481 		    mac_secret, mac_secret_size, key, key_len, iv, iv_len))
482 			goto err;
483 	}
484 
485 	if (aead != NULL)
486 		return 1;
487 
488 	return tls1_change_cipher_state_cipher(s, is_read,
489 	    mac_secret, mac_secret_size, key, key_len, iv, iv_len);
490 
491  err:
492 	return (0);
493 }
494 
495 int
496 tls1_setup_key_block(SSL *s)
497 {
498 	unsigned char *key_block;
499 	int mac_type = NID_undef, mac_secret_size = 0;
500 	size_t key_block_len;
501 	int key_len, iv_len;
502 	const EVP_CIPHER *cipher = NULL;
503 	const EVP_AEAD *aead = NULL;
504 	const EVP_MD *mac = NULL;
505 	int ret = 0;
506 
507 	if (S3I(s)->hs.key_block_len != 0)
508 		return (1);
509 
510 	if (s->session->cipher &&
511 	    (s->session->cipher->algorithm_mac & SSL_AEAD)) {
512 		if (!ssl_cipher_get_evp_aead(s->session, &aead)) {
513 			SSLerror(s, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
514 			return (0);
515 		}
516 		key_len = EVP_AEAD_key_length(aead);
517 		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
518 	} else {
519 		if (!ssl_cipher_get_evp(s->session, &cipher, &mac, &mac_type,
520 		    &mac_secret_size)) {
521 			SSLerror(s, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
522 			return (0);
523 		}
524 		key_len = EVP_CIPHER_key_length(cipher);
525 		iv_len = EVP_CIPHER_iv_length(cipher);
526 	}
527 
528 	S3I(s)->tmp.new_aead = aead;
529 	S3I(s)->tmp.new_sym_enc = cipher;
530 	S3I(s)->tmp.new_hash = mac;
531 	S3I(s)->tmp.new_mac_pkey_type = mac_type;
532 	S3I(s)->tmp.new_mac_secret_size = mac_secret_size;
533 
534 	tls12_record_layer_set_aead(s->internal->rl, aead);
535 
536 	tls1_cleanup_key_block(s);
537 
538 	if ((key_block = reallocarray(NULL, mac_secret_size + key_len + iv_len,
539 	    2)) == NULL) {
540 		SSLerror(s, ERR_R_MALLOC_FAILURE);
541 		goto err;
542 	}
543 	key_block_len = (mac_secret_size + key_len + iv_len) * 2;
544 
545 	S3I(s)->hs.key_block_len = key_block_len;
546 	S3I(s)->hs.key_block = key_block;
547 
548 	if (!tls1_generate_key_block(s, key_block, key_block_len))
549 		goto err;
550 
551 	if (!(s->internal->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) &&
552 	    s->method->internal->version <= TLS1_VERSION) {
553 		/*
554 		 * Enable vulnerability countermeasure for CBC ciphers with
555 		 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
556 		 */
557 		S3I(s)->need_empty_fragments = 1;
558 
559 		if (s->session->cipher != NULL) {
560 			if (s->session->cipher->algorithm_enc == SSL_eNULL)
561 				S3I(s)->need_empty_fragments = 0;
562 
563 #ifndef OPENSSL_NO_RC4
564 			if (s->session->cipher->algorithm_enc == SSL_RC4)
565 				S3I(s)->need_empty_fragments = 0;
566 #endif
567 		}
568 	}
569 
570 	ret = 1;
571 
572  err:
573 	return (ret);
574 }
575 
576 int
577 tls1_final_finish_mac(SSL *s, const char *str, int str_len, unsigned char *out)
578 {
579 	unsigned char buf[EVP_MAX_MD_SIZE];
580 	size_t hash_len;
581 
582 	if (str_len < 0)
583 		return 0;
584 
585 	if (!tls1_transcript_hash_value(s, buf, sizeof(buf), &hash_len))
586 		return 0;
587 
588 	if (!tls1_PRF(s, s->session->master_key, s->session->master_key_length,
589 	    str, str_len, buf, hash_len, NULL, 0, NULL, 0, NULL, 0,
590 	    out, TLS1_FINISH_MAC_LENGTH))
591 		return 0;
592 
593 	return TLS1_FINISH_MAC_LENGTH;
594 }
595 
596 int
597 tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
598     int len)
599 {
600 	if (len < 0)
601 		return 0;
602 
603 	if (!tls1_PRF(s, p, len,
604 	    TLS_MD_MASTER_SECRET_CONST, TLS_MD_MASTER_SECRET_CONST_SIZE,
605 	    s->s3->client_random, SSL3_RANDOM_SIZE, NULL, 0,
606 	    s->s3->server_random, SSL3_RANDOM_SIZE, NULL, 0,
607 	    s->session->master_key, SSL_MAX_MASTER_KEY_LENGTH))
608 		return 0;
609 
610 	return (SSL_MAX_MASTER_KEY_LENGTH);
611 }
612 
613 int
614 tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
615     const char *label, size_t llen, const unsigned char *context,
616     size_t contextlen, int use_context)
617 {
618 	unsigned char *val = NULL;
619 	size_t vallen, currentvalpos;
620 	int rv;
621 
622 	if (!SSL_is_init_finished(s)) {
623 		SSLerror(s, SSL_R_BAD_STATE);
624 		return 0;
625 	}
626 
627 	/* construct PRF arguments
628 	 * we construct the PRF argument ourself rather than passing separate
629 	 * values into the TLS PRF to ensure that the concatenation of values
630 	 * does not create a prohibited label.
631 	 */
632 	vallen = llen + SSL3_RANDOM_SIZE * 2;
633 	if (use_context) {
634 		vallen += 2 + contextlen;
635 	}
636 
637 	val = malloc(vallen);
638 	if (val == NULL)
639 		goto err2;
640 	currentvalpos = 0;
641 	memcpy(val + currentvalpos, (unsigned char *) label, llen);
642 	currentvalpos += llen;
643 	memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
644 	currentvalpos += SSL3_RANDOM_SIZE;
645 	memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
646 	currentvalpos += SSL3_RANDOM_SIZE;
647 
648 	if (use_context) {
649 		val[currentvalpos] = (contextlen >> 8) & 0xff;
650 		currentvalpos++;
651 		val[currentvalpos] = contextlen & 0xff;
652 		currentvalpos++;
653 		if ((contextlen > 0) || (context != NULL)) {
654 			memcpy(val + currentvalpos, context, contextlen);
655 		}
656 	}
657 
658 	/* disallow prohibited labels
659 	 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
660 	 * 15, so size of val > max(prohibited label len) = 15 and the
661 	 * comparisons won't have buffer overflow
662 	 */
663 	if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
664 	    TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
665 		goto err1;
666 	if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
667 	    TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
668 		goto err1;
669 	if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
670 	    TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
671 		goto err1;
672 	if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
673 	    TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
674 		goto err1;
675 
676 	rv = tls1_PRF(s, s->session->master_key, s->session->master_key_length,
677 	    val, vallen, NULL, 0, NULL, 0, NULL, 0, NULL, 0, out, olen);
678 
679 	goto ret;
680 err1:
681 	SSLerror(s, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
682 	rv = 0;
683 	goto ret;
684 err2:
685 	SSLerror(s, ERR_R_MALLOC_FAILURE);
686 	rv = 0;
687 ret:
688 	free(val);
689 
690 	return (rv);
691 }
692 
693 int
694 tls1_alert_code(int code)
695 {
696 	switch (code) {
697 	case SSL_AD_CLOSE_NOTIFY:
698 		return (SSL3_AD_CLOSE_NOTIFY);
699 	case SSL_AD_UNEXPECTED_MESSAGE:
700 		return (SSL3_AD_UNEXPECTED_MESSAGE);
701 	case SSL_AD_BAD_RECORD_MAC:
702 		return (SSL3_AD_BAD_RECORD_MAC);
703 	case SSL_AD_DECRYPTION_FAILED:
704 		return (TLS1_AD_DECRYPTION_FAILED);
705 	case SSL_AD_RECORD_OVERFLOW:
706 		return (TLS1_AD_RECORD_OVERFLOW);
707 	case SSL_AD_DECOMPRESSION_FAILURE:
708 		return (SSL3_AD_DECOMPRESSION_FAILURE);
709 	case SSL_AD_HANDSHAKE_FAILURE:
710 		return (SSL3_AD_HANDSHAKE_FAILURE);
711 	case SSL_AD_NO_CERTIFICATE:
712 		return (-1);
713 	case SSL_AD_BAD_CERTIFICATE:
714 		return (SSL3_AD_BAD_CERTIFICATE);
715 	case SSL_AD_UNSUPPORTED_CERTIFICATE:
716 		return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
717 	case SSL_AD_CERTIFICATE_REVOKED:
718 		return (SSL3_AD_CERTIFICATE_REVOKED);
719 	case SSL_AD_CERTIFICATE_EXPIRED:
720 		return (SSL3_AD_CERTIFICATE_EXPIRED);
721 	case SSL_AD_CERTIFICATE_UNKNOWN:
722 		return (SSL3_AD_CERTIFICATE_UNKNOWN);
723 	case SSL_AD_ILLEGAL_PARAMETER:
724 		return (SSL3_AD_ILLEGAL_PARAMETER);
725 	case SSL_AD_UNKNOWN_CA:
726 		return (TLS1_AD_UNKNOWN_CA);
727 	case SSL_AD_ACCESS_DENIED:
728 		return (TLS1_AD_ACCESS_DENIED);
729 	case SSL_AD_DECODE_ERROR:
730 		return (TLS1_AD_DECODE_ERROR);
731 	case SSL_AD_DECRYPT_ERROR:
732 		return (TLS1_AD_DECRYPT_ERROR);
733 	case SSL_AD_EXPORT_RESTRICTION:
734 		return (TLS1_AD_EXPORT_RESTRICTION);
735 	case SSL_AD_PROTOCOL_VERSION:
736 		return (TLS1_AD_PROTOCOL_VERSION);
737 	case SSL_AD_INSUFFICIENT_SECURITY:
738 		return (TLS1_AD_INSUFFICIENT_SECURITY);
739 	case SSL_AD_INTERNAL_ERROR:
740 		return (TLS1_AD_INTERNAL_ERROR);
741 	case SSL_AD_INAPPROPRIATE_FALLBACK:
742 		return(TLS1_AD_INAPPROPRIATE_FALLBACK);
743 	case SSL_AD_USER_CANCELLED:
744 		return (TLS1_AD_USER_CANCELLED);
745 	case SSL_AD_NO_RENEGOTIATION:
746 		return (TLS1_AD_NO_RENEGOTIATION);
747 	case SSL_AD_UNSUPPORTED_EXTENSION:
748 		return (TLS1_AD_UNSUPPORTED_EXTENSION);
749 	case SSL_AD_CERTIFICATE_UNOBTAINABLE:
750 		return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
751 	case SSL_AD_UNRECOGNIZED_NAME:
752 		return (TLS1_AD_UNRECOGNIZED_NAME);
753 	case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
754 		return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
755 	case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
756 		return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
757 	case SSL_AD_UNKNOWN_PSK_IDENTITY:
758 		return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
759 	default:
760 		return (-1);
761 	}
762 }
763