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