xref: /dragonfly/crypto/libressl/ssl/t1_enc.c (revision 65cc0652)
1 /* $OpenBSD: t1_enc.c,v 1.84 2016/03/06 14:52:15 beck 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 <stdio.h>
139 
140 #include "ssl_locl.h"
141 
142 #include <openssl/evp.h>
143 #include <openssl/hmac.h>
144 #include <openssl/md5.h>
145 
146 void
147 tls1_cleanup_key_block(SSL *s)
148 {
149 	if (s->s3->tmp.key_block != NULL) {
150 		explicit_bzero(s->s3->tmp.key_block,
151 		    s->s3->tmp.key_block_length);
152 		free(s->s3->tmp.key_block);
153 		s->s3->tmp.key_block = NULL;
154 	}
155 	s->s3->tmp.key_block_length = 0;
156 }
157 
158 int
159 tls1_init_finished_mac(SSL *s)
160 {
161 	BIO_free(s->s3->handshake_buffer);
162 	tls1_free_digest_list(s);
163 
164 	s->s3->handshake_buffer = BIO_new(BIO_s_mem());
165 	if (s->s3->handshake_buffer == NULL)
166 		return (0);
167 
168 	(void)BIO_set_close(s->s3->handshake_buffer, BIO_CLOSE);
169 
170 	return (1);
171 }
172 
173 void
174 tls1_free_digest_list(SSL *s)
175 {
176 	int i;
177 
178 	if (s == NULL)
179 		return;
180 
181 	if (s->s3->handshake_dgst == NULL)
182 		return;
183 	for (i = 0; i < SSL_MAX_DIGEST; i++) {
184 		if (s->s3->handshake_dgst[i])
185 			EVP_MD_CTX_destroy(s->s3->handshake_dgst[i]);
186 	}
187 	free(s->s3->handshake_dgst);
188 	s->s3->handshake_dgst = NULL;
189 }
190 
191 void
192 tls1_finish_mac(SSL *s, const unsigned char *buf, int len)
193 {
194 	if (s->s3->handshake_buffer &&
195 	    !(s->s3->flags & TLS1_FLAGS_KEEP_HANDSHAKE)) {
196 		BIO_write(s->s3->handshake_buffer, (void *)buf, len);
197 	} else {
198 		int i;
199 		for (i = 0; i < SSL_MAX_DIGEST; i++) {
200 			if (s->s3->handshake_dgst[i]!= NULL)
201 				EVP_DigestUpdate(s->s3->handshake_dgst[i], buf, len);
202 		}
203 	}
204 }
205 
206 int
207 tls1_digest_cached_records(SSL *s)
208 {
209 	int i;
210 	long mask;
211 	const EVP_MD *md;
212 	long hdatalen;
213 	void *hdata;
214 
215 	tls1_free_digest_list(s);
216 
217 	s->s3->handshake_dgst = calloc(SSL_MAX_DIGEST, sizeof(EVP_MD_CTX *));
218 	if (s->s3->handshake_dgst == NULL) {
219 		SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_MALLOC_FAILURE);
220 		return 0;
221 	}
222 	hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
223 	if (hdatalen <= 0) {
224 		SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS,
225 		    SSL_R_BAD_HANDSHAKE_LENGTH);
226 		return 0;
227 	}
228 
229 	/* Loop through bits of the algorithm2 field and create MD contexts. */
230 	for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++) {
231 		if ((mask & ssl_get_algorithm2(s)) && md) {
232 			s->s3->handshake_dgst[i] = EVP_MD_CTX_create();
233 			if (s->s3->handshake_dgst[i] == NULL) {
234 				SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS,
235 				    ERR_R_MALLOC_FAILURE);
236 				return 0;
237 			}
238 			if (!EVP_DigestInit_ex(s->s3->handshake_dgst[i],
239 			    md, NULL)) {
240 				EVP_MD_CTX_destroy(s->s3->handshake_dgst[i]);
241 				return 0;
242 			}
243 			if (!EVP_DigestUpdate(s->s3->handshake_dgst[i], hdata,
244 			    hdatalen))
245 				return 0;
246 		}
247 	}
248 
249 	if (!(s->s3->flags & TLS1_FLAGS_KEEP_HANDSHAKE)) {
250 		BIO_free(s->s3->handshake_buffer);
251 		s->s3->handshake_buffer = NULL;
252 	}
253 
254 	return 1;
255 }
256 
257 void
258 tls1_record_sequence_increment(unsigned char *seq)
259 {
260 	int i;
261 
262 	for (i = SSL3_SEQUENCE_SIZE - 1; i >= 0; i--) {
263 		if (++seq[i] != 0)
264 			break;
265 	}
266 }
267 
268 /* seed1 through seed5 are virtually concatenated */
269 static int
270 tls1_P_hash(const EVP_MD *md, const unsigned char *sec, int sec_len,
271     const void *seed1, int seed1_len, const void *seed2, int seed2_len,
272     const void *seed3, int seed3_len, const void *seed4, int seed4_len,
273     const void *seed5, int seed5_len, unsigned char *out, int olen)
274 {
275 	int chunk;
276 	size_t j;
277 	EVP_MD_CTX ctx, ctx_tmp;
278 	EVP_PKEY *mac_key;
279 	unsigned char A1[EVP_MAX_MD_SIZE];
280 	size_t A1_len;
281 	int ret = 0;
282 
283 	chunk = EVP_MD_size(md);
284 	OPENSSL_assert(chunk >= 0);
285 
286 	EVP_MD_CTX_init(&ctx);
287 	EVP_MD_CTX_init(&ctx_tmp);
288 	mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
289 	if (!mac_key)
290 		goto err;
291 	if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
292 		goto err;
293 	if (!EVP_DigestSignInit(&ctx_tmp, NULL, md, NULL, mac_key))
294 		goto err;
295 	if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
296 		goto err;
297 	if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
298 		goto err;
299 	if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
300 		goto err;
301 	if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
302 		goto err;
303 	if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
304 		goto err;
305 	if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
306 		goto err;
307 
308 	for (;;) {
309 		/* Reinit mac contexts */
310 		if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
311 			goto err;
312 		if (!EVP_DigestSignInit(&ctx_tmp, NULL, md, NULL, mac_key))
313 			goto err;
314 		if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
315 			goto err;
316 		if (!EVP_DigestSignUpdate(&ctx_tmp, A1, A1_len))
317 			goto err;
318 		if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
319 			goto err;
320 		if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
321 			goto err;
322 		if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
323 			goto err;
324 		if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
325 			goto err;
326 		if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
327 			goto err;
328 
329 		if (olen > chunk) {
330 			if (!EVP_DigestSignFinal(&ctx, out, &j))
331 				goto err;
332 			out += j;
333 			olen -= j;
334 			/* calc the next A1 value */
335 			if (!EVP_DigestSignFinal(&ctx_tmp, A1, &A1_len))
336 				goto err;
337 		} else {
338 			/* last one */
339 			if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
340 				goto err;
341 			memcpy(out, A1, olen);
342 			break;
343 		}
344 	}
345 	ret = 1;
346 
347 err:
348 	EVP_PKEY_free(mac_key);
349 	EVP_MD_CTX_cleanup(&ctx);
350 	EVP_MD_CTX_cleanup(&ctx_tmp);
351 	explicit_bzero(A1, sizeof(A1));
352 	return ret;
353 }
354 
355 /* seed1 through seed5 are virtually concatenated */
356 static int
357 tls1_PRF(long digest_mask, const void *seed1, int seed1_len, const void *seed2,
358     int seed2_len, const void *seed3, int seed3_len, const void *seed4,
359     int seed4_len, const void *seed5, int seed5_len, const unsigned char *sec,
360     int slen, unsigned char *out1, unsigned char *out2, int olen)
361 {
362 	int len, i, idx, count;
363 	const unsigned char *S1;
364 	long m;
365 	const EVP_MD *md;
366 	int ret = 0;
367 
368 	/* Count number of digests and partition sec evenly */
369 	count = 0;
370 	for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
371 		if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask)
372 			count++;
373 	}
374 	if (count == 0) {
375 		SSLerr(SSL_F_TLS1_PRF,
376 		    SSL_R_SSL_HANDSHAKE_FAILURE);
377 		goto err;
378 	}
379 	len = slen / count;
380 	if (count == 1)
381 		slen = 0;
382 	S1 = sec;
383 	memset(out1, 0, olen);
384 	for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
385 		if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask) {
386 			if (!md) {
387 				SSLerr(SSL_F_TLS1_PRF,
388 				    SSL_R_UNSUPPORTED_DIGEST_TYPE);
389 				goto err;
390 			}
391 			if (!tls1_P_hash(md , S1, len + (slen&1), seed1,
392 			    seed1_len, seed2, seed2_len, seed3, seed3_len,
393 			    seed4, seed4_len, seed5, seed5_len, out2, olen))
394 				goto err;
395 			S1 += len;
396 			for (i = 0; i < olen; i++) {
397 				out1[i] ^= out2[i];
398 			}
399 		}
400 	}
401 	ret = 1;
402 
403 err:
404 	return ret;
405 }
406 
407 static int
408 tls1_generate_key_block(SSL *s, unsigned char *km, unsigned char *tmp, int num)
409 {
410 	int ret;
411 
412 	ret = tls1_PRF(ssl_get_algorithm2(s),
413 	    TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
414 	    s->s3->server_random, SSL3_RANDOM_SIZE,
415 	    s->s3->client_random, SSL3_RANDOM_SIZE,
416 	    NULL, 0, NULL, 0,
417 	    s->session->master_key, s->session->master_key_length,
418 	    km, tmp, num);
419 	return ret;
420 }
421 
422 /*
423  * tls1_aead_ctx_init allocates aead_ctx, if needed. It returns 1 on success
424  * and 0 on failure.
425  */
426 static int
427 tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
428 {
429 	if (*aead_ctx != NULL) {
430 		EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
431 		return (1);
432 	}
433 
434 	*aead_ctx = malloc(sizeof(SSL_AEAD_CTX));
435 	if (*aead_ctx == NULL) {
436 		SSLerr(SSL_F_TLS1_AEAD_CTX_INIT, ERR_R_MALLOC_FAILURE);
437 		return (0);
438 	}
439 
440 	return (1);
441 }
442 
443 static int
444 tls1_change_cipher_state_aead(SSL *s, char is_read, const unsigned char *key,
445     unsigned key_len, const unsigned char *iv, unsigned iv_len)
446 {
447 	const EVP_AEAD *aead = s->s3->tmp.new_aead;
448 	SSL_AEAD_CTX *aead_ctx;
449 
450 	if (is_read) {
451 		if (!tls1_aead_ctx_init(&s->aead_read_ctx))
452 			return 0;
453 		aead_ctx = s->aead_read_ctx;
454 	} else {
455 		if (!tls1_aead_ctx_init(&s->aead_write_ctx))
456 			return 0;
457 		aead_ctx = s->aead_write_ctx;
458 	}
459 
460 	if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
461 	    EVP_AEAD_DEFAULT_TAG_LENGTH, NULL))
462 		return (0);
463 	if (iv_len > sizeof(aead_ctx->fixed_nonce)) {
464 		SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_AEAD,
465 		    ERR_R_INTERNAL_ERROR);
466 		return (0);
467 	}
468 	memcpy(aead_ctx->fixed_nonce, iv, iv_len);
469 	aead_ctx->fixed_nonce_len = iv_len;
470 	aead_ctx->variable_nonce_len = 8;  /* always the case, currently. */
471 	aead_ctx->variable_nonce_in_record =
472 	    (s->s3->tmp.new_cipher->algorithm2 &
473 	    SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_IN_RECORD) != 0;
474 	aead_ctx->xor_fixed_nonce =
475 	    s->s3->tmp.new_cipher->algorithm_enc == SSL_CHACHA20POLY1305;
476 	aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
477 
478 	if (aead_ctx->xor_fixed_nonce) {
479 		if (aead_ctx->fixed_nonce_len != EVP_AEAD_nonce_length(aead) ||
480 		    aead_ctx->variable_nonce_len > EVP_AEAD_nonce_length(aead)) {
481 			SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_AEAD,
482 			    ERR_R_INTERNAL_ERROR);
483 			return (0);
484 		}
485 	} else {
486 		if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len !=
487 		    EVP_AEAD_nonce_length(aead)) {
488 			SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_AEAD,
489 			    ERR_R_INTERNAL_ERROR);
490 			return (0);
491 		}
492 	}
493 
494 	return (1);
495 }
496 
497 /*
498  * tls1_change_cipher_state_cipher performs the work needed to switch cipher
499  * states when using EVP_CIPHER. The argument is_read is true iff this function
500  * is being called due to reading, as opposed to writing, a ChangeCipherSpec
501  * message. In order to support export ciphersuites, use_client_keys indicates
502  * whether the key material provided is in the "client write" direction.
503  */
504 static int
505 tls1_change_cipher_state_cipher(SSL *s, char is_read, char use_client_keys,
506     const unsigned char *mac_secret, unsigned int mac_secret_size,
507     const unsigned char *key, unsigned int key_len, const unsigned char *iv,
508     unsigned int iv_len)
509 {
510 	EVP_CIPHER_CTX *cipher_ctx;
511 	const EVP_CIPHER *cipher;
512 	EVP_MD_CTX *mac_ctx;
513 	const EVP_MD *mac;
514 	int mac_type;
515 
516 	cipher = s->s3->tmp.new_sym_enc;
517 	mac = s->s3->tmp.new_hash;
518 	mac_type = s->s3->tmp.new_mac_pkey_type;
519 
520 	if (is_read) {
521 		if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
522 			s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
523 		else
524 			s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
525 
526 		EVP_CIPHER_CTX_free(s->enc_read_ctx);
527 		s->enc_read_ctx = NULL;
528 		EVP_MD_CTX_destroy(s->read_hash);
529 		s->read_hash = NULL;
530 
531 		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
532 			goto err;
533 		s->enc_read_ctx = cipher_ctx;
534 		if ((mac_ctx = EVP_MD_CTX_create()) == NULL)
535 			goto err;
536 		s->read_hash = mac_ctx;
537 	} else {
538 		if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
539 			s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
540 		else
541 			s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
542 
543 		/*
544 		 * DTLS fragments retain a pointer to the compression, cipher
545 		 * and hash contexts, so that it can restore state in order
546 		 * to perform retransmissions. As such, we cannot free write
547 		 * contexts that are used for DTLS - these are instead freed
548 		 * by DTLS when its frees a ChangeCipherSpec fragment.
549 		 */
550 		if (!SSL_IS_DTLS(s)) {
551 			EVP_CIPHER_CTX_free(s->enc_write_ctx);
552 			s->enc_write_ctx = NULL;
553 			EVP_MD_CTX_destroy(s->write_hash);
554 			s->write_hash = NULL;
555 		}
556 		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
557 			goto err;
558 		s->enc_write_ctx = cipher_ctx;
559 		if ((mac_ctx = EVP_MD_CTX_create()) == NULL)
560 			goto err;
561 		s->write_hash = mac_ctx;
562 	}
563 
564 	if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE) {
565 		EVP_CipherInit_ex(cipher_ctx, cipher, NULL, key, NULL,
566 		    !is_read);
567 		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GCM_SET_IV_FIXED,
568 		    iv_len, (unsigned char *)iv);
569 	} else
570 		EVP_CipherInit_ex(cipher_ctx, cipher, NULL, key, iv, !is_read);
571 
572 	if (!(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
573 		EVP_PKEY *mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
574 		    mac_secret, mac_secret_size);
575 		if (mac_key == NULL)
576 			goto err;
577 		EVP_DigestSignInit(mac_ctx, NULL, mac, NULL, mac_key);
578 		EVP_PKEY_free(mac_key);
579 	} else if (mac_secret_size > 0) {
580 		/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
581 		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
582 		    mac_secret_size, (unsigned char *)mac_secret);
583 	}
584 
585 	if (s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT) {
586 		int nid;
587 		if (s->s3->tmp.new_cipher->algorithm2 & SSL_HANDSHAKE_MAC_GOST94)
588 			nid = NID_id_Gost28147_89_CryptoPro_A_ParamSet;
589 		else
590 			nid = NID_id_tc26_gost_28147_param_Z;
591 
592 		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GOST_SET_SBOX, nid, 0);
593 		if (s->s3->tmp.new_cipher->algorithm_mac == SSL_GOST89MAC)
594 			EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_GOST_SET_SBOX, nid, 0);
595 	}
596 
597 	return (1);
598 
599 err:
600 	SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_CIPHER, ERR_R_MALLOC_FAILURE);
601 	return (0);
602 }
603 
604 int
605 tls1_change_cipher_state(SSL *s, int which)
606 {
607 	const unsigned char *client_write_mac_secret, *server_write_mac_secret;
608 	const unsigned char *client_write_key, *server_write_key;
609 	const unsigned char *client_write_iv, *server_write_iv;
610 	const unsigned char *mac_secret, *key, *iv;
611 	int mac_secret_size, key_len, iv_len;
612 	unsigned char *key_block, *seq;
613 	const EVP_CIPHER *cipher;
614 	const EVP_AEAD *aead;
615 	char is_read, use_client_keys;
616 
617 
618 	cipher = s->s3->tmp.new_sym_enc;
619 	aead = s->s3->tmp.new_aead;
620 
621 	/*
622 	 * is_read is true if we have just read a ChangeCipherSpec message,
623 	 * that is we need to update the read cipherspec. Otherwise we have
624 	 * just written one.
625 	 */
626 	is_read = (which & SSL3_CC_READ) != 0;
627 
628 	/*
629 	 * use_client_keys is true if we wish to use the keys for the "client
630 	 * write" direction. This is the case if we're a client sending a
631 	 * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec.
632 	 */
633 	use_client_keys = ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
634 	    (which == SSL3_CHANGE_CIPHER_SERVER_READ));
635 
636 
637 	/*
638 	 * Reset sequence number to zero - for DTLS this is handled in
639 	 * dtls1_reset_seq_numbers().
640 	 */
641 	if (!SSL_IS_DTLS(s)) {
642 		seq = is_read ? s->s3->read_sequence : s->s3->write_sequence;
643 		memset(seq, 0, SSL3_SEQUENCE_SIZE);
644 	}
645 
646 	if (aead != NULL) {
647 		key_len = EVP_AEAD_key_length(aead);
648 		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
649 	} else {
650 		key_len = EVP_CIPHER_key_length(cipher);
651 		iv_len = EVP_CIPHER_iv_length(cipher);
652 
653 		/* If GCM mode only part of IV comes from PRF. */
654 		if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
655 			iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
656 	}
657 
658 	mac_secret_size = s->s3->tmp.new_mac_secret_size;
659 
660 	key_block = s->s3->tmp.key_block;
661 	client_write_mac_secret = key_block;
662 	key_block += mac_secret_size;
663 	server_write_mac_secret = key_block;
664 	key_block += mac_secret_size;
665 	client_write_key = key_block;
666 	key_block += key_len;
667 	server_write_key = key_block;
668 	key_block += key_len;
669 	client_write_iv = key_block;
670 	key_block += iv_len;
671 	server_write_iv = key_block;
672 	key_block += iv_len;
673 
674 	if (use_client_keys) {
675 		mac_secret = client_write_mac_secret;
676 		key = client_write_key;
677 		iv = client_write_iv;
678 	} else {
679 		mac_secret = server_write_mac_secret;
680 		key = server_write_key;
681 		iv = server_write_iv;
682 	}
683 
684 	if (key_block - s->s3->tmp.key_block != s->s3->tmp.key_block_length) {
685 		SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
686 		goto err2;
687 	}
688 
689 	if (is_read) {
690 		memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_size);
691 		s->s3->read_mac_secret_size = mac_secret_size;
692 	} else {
693 		memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_size);
694 		s->s3->write_mac_secret_size = mac_secret_size;
695 	}
696 
697 	if (aead != NULL) {
698 		return tls1_change_cipher_state_aead(s, is_read, key, key_len,
699 		    iv, iv_len);
700 	}
701 
702 	return tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
703 	    mac_secret, mac_secret_size, key, key_len, iv, iv_len);
704 
705 err2:
706 	return (0);
707 }
708 
709 int
710 tls1_setup_key_block(SSL *s)
711 {
712 	unsigned char *key_block, *tmp_block = NULL;
713 	int mac_type = NID_undef, mac_secret_size = 0;
714 	int key_block_len, key_len, iv_len;
715 	const EVP_CIPHER *cipher = NULL;
716 	const EVP_AEAD *aead = NULL;
717 	const EVP_MD *mac = NULL;
718 	int ret = 0;
719 
720 	if (s->s3->tmp.key_block_length != 0)
721 		return (1);
722 
723 	if (s->session->cipher &&
724 	    (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD)) {
725 		if (!ssl_cipher_get_evp_aead(s->session, &aead)) {
726 			SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,
727 			    SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
728 			return (0);
729 		}
730 		key_len = EVP_AEAD_key_length(aead);
731 		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
732 	} else {
733 		if (!ssl_cipher_get_evp(s->session, &cipher, &mac, &mac_type,
734 		    &mac_secret_size)) {
735 			SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,
736 			    SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
737 			return (0);
738 		}
739 		key_len = EVP_CIPHER_key_length(cipher);
740 		iv_len = EVP_CIPHER_iv_length(cipher);
741 
742 		/* If GCM mode only part of IV comes from PRF. */
743 		if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
744 			iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
745 	}
746 
747 	s->s3->tmp.new_aead = aead;
748 	s->s3->tmp.new_sym_enc = cipher;
749 	s->s3->tmp.new_hash = mac;
750 	s->s3->tmp.new_mac_pkey_type = mac_type;
751 	s->s3->tmp.new_mac_secret_size = mac_secret_size;
752 
753 	tls1_cleanup_key_block(s);
754 
755 	if ((key_block = reallocarray(NULL, mac_secret_size + key_len + iv_len,
756 	    2)) == NULL) {
757 		SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
758 		goto err;
759 	}
760 	key_block_len = (mac_secret_size + key_len + iv_len) * 2;
761 
762 	s->s3->tmp.key_block_length = key_block_len;
763 	s->s3->tmp.key_block = key_block;
764 
765 	if ((tmp_block = malloc(key_block_len)) == NULL) {
766 		SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
767 		goto err;
768 	}
769 
770 	if (!tls1_generate_key_block(s, key_block, tmp_block, key_block_len))
771 		goto err;
772 
773 	if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) &&
774 	    s->method->version <= TLS1_VERSION) {
775 		/*
776 		 * Enable vulnerability countermeasure for CBC ciphers with
777 		 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
778 		 */
779 		s->s3->need_empty_fragments = 1;
780 
781 		if (s->session->cipher != NULL) {
782 			if (s->session->cipher->algorithm_enc == SSL_eNULL)
783 				s->s3->need_empty_fragments = 0;
784 
785 #ifndef OPENSSL_NO_RC4
786 			if (s->session->cipher->algorithm_enc == SSL_RC4)
787 				s->s3->need_empty_fragments = 0;
788 #endif
789 		}
790 	}
791 
792 	ret = 1;
793 
794 err:
795 	if (tmp_block) {
796 		explicit_bzero(tmp_block, key_block_len);
797 		free(tmp_block);
798 	}
799 	return (ret);
800 }
801 
802 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
803  *
804  * Returns:
805  *   0: (in non-constant time) if the record is publically invalid (i.e. too
806  *       short etc).
807  *   1: if the record's padding is valid / the encryption was successful.
808  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
809  *       an internal error occured.
810  */
811 int
812 tls1_enc(SSL *s, int send)
813 {
814 	const SSL_AEAD_CTX *aead;
815 	const EVP_CIPHER *enc;
816 	EVP_CIPHER_CTX *ds;
817 	SSL3_RECORD *rec;
818 	unsigned char *seq;
819 	unsigned long l;
820 	int bs, i, j, k, pad = 0, ret, mac_size = 0;
821 
822 	if (send) {
823 		aead = s->aead_write_ctx;
824 		rec = &s->s3->wrec;
825 		seq = s->s3->write_sequence;
826 	} else {
827 		aead = s->aead_read_ctx;
828 		rec = &s->s3->rrec;
829 		seq = s->s3->read_sequence;
830 	}
831 
832 	if (aead) {
833 		unsigned char ad[13], *in, *out, nonce[16];
834 		size_t out_len, pad_len = 0;
835 		unsigned int nonce_used;
836 
837 		if (SSL_IS_DTLS(s)) {
838 			dtls1_build_sequence_number(ad, seq,
839 			    send ? s->d1->w_epoch : s->d1->r_epoch);
840 		} else {
841 			memcpy(ad, seq, SSL3_SEQUENCE_SIZE);
842 			tls1_record_sequence_increment(seq);
843 		}
844 
845 		ad[8] = rec->type;
846 		ad[9] = (unsigned char)(s->version >> 8);
847 		ad[10] = (unsigned char)(s->version);
848 
849 		if (aead->variable_nonce_len > 8 ||
850 		    aead->variable_nonce_len > sizeof(nonce))
851 			return -1;
852 
853 		if (aead->xor_fixed_nonce) {
854 			if (aead->fixed_nonce_len > sizeof(nonce) ||
855 			    aead->variable_nonce_len > aead->fixed_nonce_len)
856 				return -1;  /* Should never happen. */
857 			pad_len = aead->fixed_nonce_len - aead->variable_nonce_len;
858 		} else {
859 			if (aead->fixed_nonce_len +
860 			    aead->variable_nonce_len > sizeof(nonce))
861 				return -1;  /* Should never happen. */
862 		}
863 
864 		if (send) {
865 			size_t len = rec->length;
866 			size_t eivlen = 0;
867 			in = rec->input;
868 			out = rec->data;
869 
870 			if (aead->xor_fixed_nonce) {
871 				/*
872 				 * The sequence number is left zero
873 				 * padded, then xored with the fixed
874 				 * nonce.
875 				 */
876 				memset(nonce, 0, pad_len);
877 				memcpy(nonce + pad_len, ad,
878 				    aead->variable_nonce_len);
879 				for (i = 0; i < aead->fixed_nonce_len; i++)
880 					nonce[i] ^= aead->fixed_nonce[i];
881 				nonce_used = aead->fixed_nonce_len;
882 			} else {
883 				/*
884 				 * When sending we use the sequence number as
885 				 * the variable part of the nonce.
886 				 */
887 				memcpy(nonce, aead->fixed_nonce,
888 				    aead->fixed_nonce_len);
889 				nonce_used = aead->fixed_nonce_len;
890 				memcpy(nonce + nonce_used, ad,
891 				    aead->variable_nonce_len);
892 				nonce_used += aead->variable_nonce_len;
893 			}
894 
895 			/*
896 			 * In do_ssl3_write, rec->input is moved forward by
897 			 * variable_nonce_len in order to leave space for the
898 			 * variable nonce. Thus we can copy the sequence number
899 			 * bytes into place without overwriting any of the
900 			 * plaintext.
901 			 */
902 			if (aead->variable_nonce_in_record) {
903 				memcpy(out, ad, aead->variable_nonce_len);
904 				len -= aead->variable_nonce_len;
905 				eivlen = aead->variable_nonce_len;
906 			}
907 
908 			ad[11] = len >> 8;
909 			ad[12] = len & 0xff;
910 
911 			if (!EVP_AEAD_CTX_seal(&aead->ctx,
912 			    out + eivlen, &out_len, len + aead->tag_len, nonce,
913 			    nonce_used, in + eivlen, len, ad, sizeof(ad)))
914 				return -1;
915 			if (aead->variable_nonce_in_record)
916 				out_len += aead->variable_nonce_len;
917 		} else {
918 			/* receive */
919 			size_t len = rec->length;
920 
921 			if (rec->data != rec->input)
922 				return -1;  /* internal error - should never happen. */
923 			out = in = rec->input;
924 
925 			if (len < aead->variable_nonce_len)
926 				return 0;
927 
928 			if (aead->xor_fixed_nonce) {
929 				/*
930 				 * The sequence number is left zero
931 				 * padded, then xored with the fixed
932 				 * nonce.
933 				 */
934 				memset(nonce, 0, pad_len);
935 				memcpy(nonce + pad_len, ad,
936 				    aead->variable_nonce_len);
937 				for (i = 0; i < aead->fixed_nonce_len; i++)
938 					nonce[i] ^= aead->fixed_nonce[i];
939 				nonce_used = aead->fixed_nonce_len;
940 			} else {
941 				memcpy(nonce, aead->fixed_nonce,
942 				    aead->fixed_nonce_len);
943 				nonce_used = aead->fixed_nonce_len;
944 
945 				memcpy(nonce + nonce_used,
946 				    aead->variable_nonce_in_record ? in : ad,
947 				    aead->variable_nonce_len);
948 				nonce_used += aead->variable_nonce_len;
949 			}
950 
951 			if (aead->variable_nonce_in_record) {
952 				in += aead->variable_nonce_len;
953 				len -= aead->variable_nonce_len;
954 				out += aead->variable_nonce_len;
955 			}
956 
957 			if (len < aead->tag_len)
958 				return 0;
959 			len -= aead->tag_len;
960 
961 			ad[11] = len >> 8;
962 			ad[12] = len & 0xff;
963 
964 			if (!EVP_AEAD_CTX_open(&aead->ctx, out, &out_len, len,
965 			    nonce, nonce_used, in, len + aead->tag_len, ad,
966 			    sizeof(ad)))
967 				return -1;
968 
969 			rec->data = rec->input = out;
970 		}
971 
972 		rec->length = out_len;
973 
974 		return 1;
975 	}
976 
977 	if (send) {
978 		if (EVP_MD_CTX_md(s->write_hash)) {
979 			int n = EVP_MD_CTX_size(s->write_hash);
980 			OPENSSL_assert(n >= 0);
981 		}
982 		ds = s->enc_write_ctx;
983 		if (s->enc_write_ctx == NULL)
984 			enc = NULL;
985 		else {
986 			int ivlen = 0;
987 			enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
988 			if (SSL_USE_EXPLICIT_IV(s) &&
989 			    EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
990 				ivlen = EVP_CIPHER_iv_length(enc);
991 			if (ivlen > 1) {
992 				if (rec->data != rec->input) {
993 #ifdef DEBUG
994 					/* we can't write into the input stream:
995 					 * Can this ever happen?? (steve)
996 					 */
997 					fprintf(stderr,
998 					    "%s:%d: rec->data != rec->input\n",
999 					    __FILE__, __LINE__);
1000 #endif
1001 				} else
1002 					arc4random_buf(rec->input, ivlen);
1003 			}
1004 		}
1005 	} else {
1006 		if (EVP_MD_CTX_md(s->read_hash)) {
1007 			int n = EVP_MD_CTX_size(s->read_hash);
1008 			OPENSSL_assert(n >= 0);
1009 		}
1010 		ds = s->enc_read_ctx;
1011 		if (s->enc_read_ctx == NULL)
1012 			enc = NULL;
1013 		else
1014 			enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
1015 	}
1016 
1017 	if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
1018 		memmove(rec->data, rec->input, rec->length);
1019 		rec->input = rec->data;
1020 		ret = 1;
1021 	} else {
1022 		l = rec->length;
1023 		bs = EVP_CIPHER_block_size(ds->cipher);
1024 
1025 		if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1026 			unsigned char buf[13];
1027 
1028 			if (SSL_IS_DTLS(s)) {
1029 				dtls1_build_sequence_number(buf, seq,
1030 				    send ? s->d1->w_epoch : s->d1->r_epoch);
1031 			} else {
1032 				memcpy(buf, seq, SSL3_SEQUENCE_SIZE);
1033 				tls1_record_sequence_increment(seq);
1034 			}
1035 
1036 			buf[8] = rec->type;
1037 			buf[9] = (unsigned char)(s->version >> 8);
1038 			buf[10] = (unsigned char)(s->version);
1039 			buf[11] = rec->length >> 8;
1040 			buf[12] = rec->length & 0xff;
1041 			pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD, 13, buf);
1042 			if (send) {
1043 				l += pad;
1044 				rec->length += pad;
1045 			}
1046 		} else if ((bs != 1) && send) {
1047 			i = bs - ((int)l % bs);
1048 
1049 			/* Add weird padding of upto 256 bytes */
1050 
1051 			/* we need to add 'i' padding bytes of value j */
1052 			j = i - 1;
1053 			for (k = (int)l; k < (int)(l + i); k++)
1054 				rec->input[k] = j;
1055 			l += i;
1056 			rec->length += i;
1057 		}
1058 
1059 		if (!send) {
1060 			if (l == 0 || l % bs != 0)
1061 				return 0;
1062 		}
1063 
1064 		i = EVP_Cipher(ds, rec->data, rec->input, l);
1065 		if ((EVP_CIPHER_flags(ds->cipher) &
1066 		    EVP_CIPH_FLAG_CUSTOM_CIPHER) ? (i < 0) : (i == 0))
1067 			return -1;	/* AEAD can fail to verify MAC */
1068 		if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
1069 			rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1070 			rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1071 			rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1072 		}
1073 
1074 		ret = 1;
1075 		if (EVP_MD_CTX_md(s->read_hash) != NULL)
1076 			mac_size = EVP_MD_CTX_size(s->read_hash);
1077 		if ((bs != 1) && !send)
1078 			ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
1079 		if (pad && !send)
1080 			rec->length -= pad;
1081 	}
1082 	return ret;
1083 }
1084 
1085 int
1086 tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
1087 {
1088 	EVP_MD_CTX ctx, *d = NULL;
1089 	unsigned int ret;
1090 	int i;
1091 
1092 	if (s->s3->handshake_buffer)
1093 		if (!tls1_digest_cached_records(s))
1094 			return 0;
1095 
1096 	for (i = 0; i < SSL_MAX_DIGEST; i++) {
1097 		if (s->s3->handshake_dgst[i] &&
1098 		    EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) {
1099 			d = s->s3->handshake_dgst[i];
1100 			break;
1101 		}
1102 	}
1103 	if (d == NULL) {
1104 		SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC, SSL_R_NO_REQUIRED_DIGEST);
1105 		return 0;
1106 	}
1107 
1108 	EVP_MD_CTX_init(&ctx);
1109 	if (!EVP_MD_CTX_copy_ex(&ctx, d))
1110 		return 0;
1111 	EVP_DigestFinal_ex(&ctx, out, &ret);
1112 	EVP_MD_CTX_cleanup(&ctx);
1113 
1114 	return ((int)ret);
1115 }
1116 
1117 int
1118 tls1_final_finish_mac(SSL *s, const char *str, int slen, unsigned char *out)
1119 {
1120 	unsigned int i;
1121 	EVP_MD_CTX ctx;
1122 	unsigned char buf[2*EVP_MAX_MD_SIZE];
1123 	unsigned char *q, buf2[12];
1124 	int idx;
1125 	long mask;
1126 	int err = 0;
1127 	const EVP_MD *md;
1128 
1129 	q = buf;
1130 
1131 	if (s->s3->handshake_buffer)
1132 		if (!tls1_digest_cached_records(s))
1133 			return 0;
1134 
1135 	EVP_MD_CTX_init(&ctx);
1136 
1137 	for (idx = 0; ssl_get_handshake_digest(idx, &mask, &md); idx++) {
1138 		if (ssl_get_algorithm2(s) & mask) {
1139 			int hashsize = EVP_MD_size(md);
1140 			EVP_MD_CTX *hdgst = s->s3->handshake_dgst[idx];
1141 			if (!hdgst || hashsize < 0 ||
1142 			    hashsize > (int)(sizeof buf - (size_t)(q - buf))) {
1143 				/* internal error: 'buf' is too small for this cipersuite! */
1144 				err = 1;
1145 			} else {
1146 				if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
1147 				    !EVP_DigestFinal_ex(&ctx, q, &i) ||
1148 				    (i != (unsigned int)hashsize))
1149 					err = 1;
1150 				q += hashsize;
1151 			}
1152 		}
1153 	}
1154 
1155 	if (!tls1_PRF(ssl_get_algorithm2(s), str, slen, buf, (int)(q - buf),
1156 	    NULL, 0, NULL, 0, NULL, 0,
1157 	    s->session->master_key, s->session->master_key_length,
1158 	    out, buf2, sizeof buf2))
1159 		err = 1;
1160 	EVP_MD_CTX_cleanup(&ctx);
1161 
1162 	if (err)
1163 		return 0;
1164 	else
1165 		return sizeof buf2;
1166 }
1167 
1168 int
1169 tls1_mac(SSL *ssl, unsigned char *md, int send)
1170 {
1171 	SSL3_RECORD *rec;
1172 	unsigned char *seq;
1173 	EVP_MD_CTX *hash;
1174 	size_t md_size, orig_len;
1175 	EVP_MD_CTX hmac, *mac_ctx;
1176 	unsigned char header[13];
1177 	int stream_mac = (send ?
1178 	    (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) :
1179 	    (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1180 	int t;
1181 
1182 	if (send) {
1183 		rec = &(ssl->s3->wrec);
1184 		seq = &(ssl->s3->write_sequence[0]);
1185 		hash = ssl->write_hash;
1186 	} else {
1187 		rec = &(ssl->s3->rrec);
1188 		seq = &(ssl->s3->read_sequence[0]);
1189 		hash = ssl->read_hash;
1190 	}
1191 
1192 	t = EVP_MD_CTX_size(hash);
1193 	OPENSSL_assert(t >= 0);
1194 	md_size = t;
1195 
1196 	/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1197 	if (stream_mac) {
1198 		mac_ctx = hash;
1199 	} else {
1200 		if (!EVP_MD_CTX_copy(&hmac, hash))
1201 			return -1;
1202 		mac_ctx = &hmac;
1203 	}
1204 
1205 	if (SSL_IS_DTLS(ssl))
1206 		dtls1_build_sequence_number(header, seq,
1207 		    send ? ssl->d1->w_epoch : ssl->d1->r_epoch);
1208 	else
1209 		memcpy(header, seq, SSL3_SEQUENCE_SIZE);
1210 
1211 	/* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1212 	orig_len = rec->length + md_size + ((unsigned int)rec->type >> 8);
1213 	rec->type &= 0xff;
1214 
1215 	header[8] = rec->type;
1216 	header[9] = (unsigned char)(ssl->version >> 8);
1217 	header[10] = (unsigned char)(ssl->version);
1218 	header[11] = (rec->length) >> 8;
1219 	header[12] = (rec->length) & 0xff;
1220 
1221 	if (!send &&
1222 	    EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1223 	    ssl3_cbc_record_digest_supported(mac_ctx)) {
1224 		/* This is a CBC-encrypted record. We must avoid leaking any
1225 		 * timing-side channel information about how many blocks of
1226 		 * data we are hashing because that gives an attacker a
1227 		 * timing-oracle. */
1228 		if (!ssl3_cbc_digest_record(mac_ctx,
1229 		    md, &md_size, header, rec->input,
1230 		    rec->length + md_size, orig_len,
1231 		    ssl->s3->read_mac_secret,
1232 		    ssl->s3->read_mac_secret_size,
1233 		    0 /* not SSLv3 */))
1234 			return -1;
1235 	} else {
1236 		EVP_DigestSignUpdate(mac_ctx, header, sizeof(header));
1237 		EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length);
1238 		t = EVP_DigestSignFinal(mac_ctx, md, &md_size);
1239 		OPENSSL_assert(t > 0);
1240 	}
1241 
1242 	if (!stream_mac)
1243 		EVP_MD_CTX_cleanup(&hmac);
1244 
1245 	if (!SSL_IS_DTLS(ssl))
1246 		tls1_record_sequence_increment(seq);
1247 
1248 	return (md_size);
1249 }
1250 
1251 int
1252 tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1253     int len)
1254 {
1255 	unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1256 
1257 	tls1_PRF(ssl_get_algorithm2(s),
1258 	    TLS_MD_MASTER_SECRET_CONST, TLS_MD_MASTER_SECRET_CONST_SIZE,
1259 	    s->s3->client_random, SSL3_RANDOM_SIZE, NULL, 0,
1260 	    s->s3->server_random, SSL3_RANDOM_SIZE, NULL, 0,
1261 	    p, len, s->session->master_key, buff, sizeof buff);
1262 
1263 	return (SSL3_MASTER_SECRET_SIZE);
1264 }
1265 
1266 int
1267 tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1268     const char *label, size_t llen, const unsigned char *context,
1269     size_t contextlen, int use_context)
1270 {
1271 	unsigned char *buff;
1272 	unsigned char *val = NULL;
1273 	size_t vallen, currentvalpos;
1274 	int rv;
1275 
1276 	buff = malloc(olen);
1277 	if (buff == NULL)
1278 		goto err2;
1279 
1280 	/* construct PRF arguments
1281 	 * we construct the PRF argument ourself rather than passing separate
1282 	 * values into the TLS PRF to ensure that the concatenation of values
1283 	 * does not create a prohibited label.
1284 	 */
1285 	vallen = llen + SSL3_RANDOM_SIZE * 2;
1286 	if (use_context) {
1287 		vallen += 2 + contextlen;
1288 	}
1289 
1290 	val = malloc(vallen);
1291 	if (val == NULL)
1292 		goto err2;
1293 	currentvalpos = 0;
1294 	memcpy(val + currentvalpos, (unsigned char *) label, llen);
1295 	currentvalpos += llen;
1296 	memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1297 	currentvalpos += SSL3_RANDOM_SIZE;
1298 	memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1299 	currentvalpos += SSL3_RANDOM_SIZE;
1300 
1301 	if (use_context) {
1302 		val[currentvalpos] = (contextlen >> 8) & 0xff;
1303 		currentvalpos++;
1304 		val[currentvalpos] = contextlen & 0xff;
1305 		currentvalpos++;
1306 		if ((contextlen > 0) || (context != NULL)) {
1307 			memcpy(val + currentvalpos, context, contextlen);
1308 		}
1309 	}
1310 
1311 	/* disallow prohibited labels
1312 	 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1313 	 * 15, so size of val > max(prohibited label len) = 15 and the
1314 	 * comparisons won't have buffer overflow
1315 	 */
1316 	if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1317 	    TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
1318 		goto err1;
1319 	if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1320 	    TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
1321 		goto err1;
1322 	if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1323 	    TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
1324 		goto err1;
1325 	if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1326 	    TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
1327 		goto err1;
1328 
1329 	rv = tls1_PRF(ssl_get_algorithm2(s),
1330 	    val, vallen, NULL, 0, NULL, 0, NULL, 0, NULL, 0,
1331 	    s->session->master_key, s->session->master_key_length,
1332 	    out, buff, olen);
1333 
1334 	goto ret;
1335 err1:
1336 	SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL,
1337 	    SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1338 	rv = 0;
1339 	goto ret;
1340 err2:
1341 	SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
1342 	rv = 0;
1343 ret:
1344 	free(buff);
1345 	free(val);
1346 
1347 	return (rv);
1348 }
1349 
1350 int
1351 tls1_alert_code(int code)
1352 {
1353 	switch (code) {
1354 	case SSL_AD_CLOSE_NOTIFY:
1355 		return (SSL3_AD_CLOSE_NOTIFY);
1356 	case SSL_AD_UNEXPECTED_MESSAGE:
1357 		return (SSL3_AD_UNEXPECTED_MESSAGE);
1358 	case SSL_AD_BAD_RECORD_MAC:
1359 		return (SSL3_AD_BAD_RECORD_MAC);
1360 	case SSL_AD_DECRYPTION_FAILED:
1361 		return (TLS1_AD_DECRYPTION_FAILED);
1362 	case SSL_AD_RECORD_OVERFLOW:
1363 		return (TLS1_AD_RECORD_OVERFLOW);
1364 	case SSL_AD_DECOMPRESSION_FAILURE:
1365 		return (SSL3_AD_DECOMPRESSION_FAILURE);
1366 	case SSL_AD_HANDSHAKE_FAILURE:
1367 		return (SSL3_AD_HANDSHAKE_FAILURE);
1368 	case SSL_AD_NO_CERTIFICATE:
1369 		return (-1);
1370 	case SSL_AD_BAD_CERTIFICATE:
1371 		return (SSL3_AD_BAD_CERTIFICATE);
1372 	case SSL_AD_UNSUPPORTED_CERTIFICATE:
1373 		return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
1374 	case SSL_AD_CERTIFICATE_REVOKED:
1375 		return (SSL3_AD_CERTIFICATE_REVOKED);
1376 	case SSL_AD_CERTIFICATE_EXPIRED:
1377 		return (SSL3_AD_CERTIFICATE_EXPIRED);
1378 	case SSL_AD_CERTIFICATE_UNKNOWN:
1379 		return (SSL3_AD_CERTIFICATE_UNKNOWN);
1380 	case SSL_AD_ILLEGAL_PARAMETER:
1381 		return (SSL3_AD_ILLEGAL_PARAMETER);
1382 	case SSL_AD_UNKNOWN_CA:
1383 		return (TLS1_AD_UNKNOWN_CA);
1384 	case SSL_AD_ACCESS_DENIED:
1385 		return (TLS1_AD_ACCESS_DENIED);
1386 	case SSL_AD_DECODE_ERROR:
1387 		return (TLS1_AD_DECODE_ERROR);
1388 	case SSL_AD_DECRYPT_ERROR:
1389 		return (TLS1_AD_DECRYPT_ERROR);
1390 	case SSL_AD_EXPORT_RESTRICTION:
1391 		return (TLS1_AD_EXPORT_RESTRICTION);
1392 	case SSL_AD_PROTOCOL_VERSION:
1393 		return (TLS1_AD_PROTOCOL_VERSION);
1394 	case SSL_AD_INSUFFICIENT_SECURITY:
1395 		return (TLS1_AD_INSUFFICIENT_SECURITY);
1396 	case SSL_AD_INTERNAL_ERROR:
1397 		return (TLS1_AD_INTERNAL_ERROR);
1398 	case SSL_AD_INAPPROPRIATE_FALLBACK:
1399 		return(TLS1_AD_INAPPROPRIATE_FALLBACK);
1400 	case SSL_AD_USER_CANCELLED:
1401 		return (TLS1_AD_USER_CANCELLED);
1402 	case SSL_AD_NO_RENEGOTIATION:
1403 		return (TLS1_AD_NO_RENEGOTIATION);
1404 	case SSL_AD_UNSUPPORTED_EXTENSION:
1405 		return (TLS1_AD_UNSUPPORTED_EXTENSION);
1406 	case SSL_AD_CERTIFICATE_UNOBTAINABLE:
1407 		return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1408 	case SSL_AD_UNRECOGNIZED_NAME:
1409 		return (TLS1_AD_UNRECOGNIZED_NAME);
1410 	case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
1411 		return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1412 	case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
1413 		return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1414 	case SSL_AD_UNKNOWN_PSK_IDENTITY:
1415 		return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
1416 	default:
1417 		return (-1);
1418 	}
1419 }
1420