xref: /openbsd-src/lib/libssl/t1_enc.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /* $OpenBSD: t1_enc.c,v 1.67 2014/07/10 10:09:54 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * 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 #include "ssl_locl.h"
140 #include <openssl/evp.h>
141 #include <openssl/hmac.h>
142 #include <openssl/md5.h>
143 #include <openssl/rand.h>
144 
145 /* seed1 through seed5 are virtually concatenated */
146 static int
147 tls1_P_hash(const EVP_MD *md, const unsigned char *sec, int sec_len,
148     const void *seed1, int seed1_len, const void *seed2, int seed2_len,
149     const void *seed3, int seed3_len, const void *seed4, int seed4_len,
150     const void *seed5, int seed5_len, unsigned char *out, int olen)
151 {
152 	int chunk;
153 	size_t j;
154 	EVP_MD_CTX ctx, ctx_tmp;
155 	EVP_PKEY *mac_key;
156 	unsigned char A1[EVP_MAX_MD_SIZE];
157 	size_t A1_len;
158 	int ret = 0;
159 
160 	chunk = EVP_MD_size(md);
161 	OPENSSL_assert(chunk >= 0);
162 
163 	EVP_MD_CTX_init(&ctx);
164 	EVP_MD_CTX_init(&ctx_tmp);
165 	mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
166 	if (!mac_key)
167 		goto err;
168 	if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
169 		goto err;
170 	if (!EVP_DigestSignInit(&ctx_tmp, NULL, md, NULL, mac_key))
171 		goto err;
172 	if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
173 		goto err;
174 	if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
175 		goto err;
176 	if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
177 		goto err;
178 	if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
179 		goto err;
180 	if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
181 		goto err;
182 	if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
183 		goto err;
184 
185 	for (;;) {
186 		/* Reinit mac contexts */
187 		if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
188 			goto err;
189 		if (!EVP_DigestSignInit(&ctx_tmp, NULL, md, NULL, mac_key))
190 			goto err;
191 		if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
192 			goto err;
193 		if (!EVP_DigestSignUpdate(&ctx_tmp, A1, A1_len))
194 			goto err;
195 		if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
196 			goto err;
197 		if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
198 			goto err;
199 		if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
200 			goto err;
201 		if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
202 			goto err;
203 		if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
204 			goto err;
205 
206 		if (olen > chunk) {
207 			if (!EVP_DigestSignFinal(&ctx, out, &j))
208 				goto err;
209 			out += j;
210 			olen -= j;
211 			/* calc the next A1 value */
212 			if (!EVP_DigestSignFinal(&ctx_tmp, A1, &A1_len))
213 				goto err;
214 		} else {
215 			/* last one */
216 			if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
217 				goto err;
218 			memcpy(out, A1, olen);
219 			break;
220 		}
221 	}
222 	ret = 1;
223 
224 err:
225 	EVP_PKEY_free(mac_key);
226 	EVP_MD_CTX_cleanup(&ctx);
227 	EVP_MD_CTX_cleanup(&ctx_tmp);
228 	OPENSSL_cleanse(A1, sizeof(A1));
229 	return ret;
230 }
231 
232 /* seed1 through seed5 are virtually concatenated */
233 static int
234 tls1_PRF(long digest_mask, const void *seed1, int seed1_len, const void *seed2,
235     int seed2_len, const void *seed3, int seed3_len, const void *seed4,
236     int seed4_len, const void *seed5, int seed5_len, const unsigned char *sec,
237     int slen, unsigned char *out1, unsigned char *out2, int olen)
238 {
239 	int len, i, idx, count;
240 	const unsigned char *S1;
241 	long m;
242 	const EVP_MD *md;
243 	int ret = 0;
244 
245 	/* Count number of digests and partition sec evenly */
246 	count = 0;
247 	for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
248 		if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask)
249 			count++;
250 	}
251 	if (count == 0) {
252 		SSLerr(SSL_F_TLS1_PRF,
253 		    SSL_R_SSL_HANDSHAKE_FAILURE);
254 		goto err;
255 	}
256 	len = slen / count;
257 	if (count == 1)
258 		slen = 0;
259 	S1 = sec;
260 	memset(out1, 0, olen);
261 	for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
262 		if ((m << TLS1_PRF_DGST_SHIFT) & digest_mask) {
263 			if (!md) {
264 				SSLerr(SSL_F_TLS1_PRF,
265 				    SSL_R_UNSUPPORTED_DIGEST_TYPE);
266 				goto err;
267 			}
268 			if (!tls1_P_hash(md , S1, len + (slen&1), seed1,
269 			    seed1_len, seed2, seed2_len, seed3, seed3_len,
270 			    seed4, seed4_len, seed5, seed5_len, out2, olen))
271 				goto err;
272 			S1 += len;
273 			for (i = 0; i < olen; i++) {
274 				out1[i] ^= out2[i];
275 			}
276 		}
277 	}
278 	ret = 1;
279 
280 err:
281 	return ret;
282 }
283 
284 static int
285 tls1_generate_key_block(SSL *s, unsigned char *km, unsigned char *tmp, int num)
286 {
287 	int ret;
288 
289 	ret = tls1_PRF(ssl_get_algorithm2(s),
290 	    TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
291 	    s->s3->server_random, SSL3_RANDOM_SIZE,
292 	    s->s3->client_random, SSL3_RANDOM_SIZE,
293 	    NULL, 0, NULL, 0,
294 	    s->session->master_key, s->session->master_key_length,
295 	    km, tmp, num);
296 	return ret;
297 }
298 
299 /*
300  * tls1_aead_ctx_init allocates aead_ctx, if needed. It returns 1 on success
301  * and 0 on failure.
302  */
303 static int
304 tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
305 {
306 	if (*aead_ctx != NULL) {
307 		EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
308 		return (1);
309 	}
310 
311 	*aead_ctx = malloc(sizeof(SSL_AEAD_CTX));
312 	if (*aead_ctx == NULL) {
313 		SSLerr(SSL_F_TLS1_AEAD_CTX_INIT, ERR_R_MALLOC_FAILURE);
314 		return (0);
315 	}
316 
317 	return (1);
318 }
319 
320 static int
321 tls1_change_cipher_state_aead(SSL *s, char is_read, const unsigned char *key,
322     unsigned key_len, const unsigned char *iv, unsigned iv_len)
323 {
324 	const EVP_AEAD *aead = s->s3->tmp.new_aead;
325 	SSL_AEAD_CTX *aead_ctx;
326 
327 	if (is_read) {
328 		if (!tls1_aead_ctx_init(&s->aead_read_ctx))
329 			return 0;
330 		aead_ctx = s->aead_read_ctx;
331 	} else {
332 		if (!tls1_aead_ctx_init(&s->aead_write_ctx))
333 			return 0;
334 		aead_ctx = s->aead_write_ctx;
335 	}
336 
337 	if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
338 	    EVP_AEAD_DEFAULT_TAG_LENGTH, NULL))
339 		return (0);
340 	if (iv_len > sizeof(aead_ctx->fixed_nonce)) {
341 		SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_AEAD,
342 		    ERR_R_INTERNAL_ERROR);
343 		return (0);
344 	}
345 	memcpy(aead_ctx->fixed_nonce, iv, iv_len);
346 	aead_ctx->fixed_nonce_len = iv_len;
347 	aead_ctx->variable_nonce_len = 8;  /* always the case, currently. */
348 	aead_ctx->variable_nonce_in_record =
349 	    (s->s3->tmp.new_cipher->algorithm2 &
350 	    SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_IN_RECORD) != 0;
351 	if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len !=
352 	    EVP_AEAD_nonce_length(aead)) {
353 		SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_AEAD,
354 		    ERR_R_INTERNAL_ERROR);
355 		return (0);
356 	}
357 	aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
358 
359 	return (1);
360 }
361 
362 /*
363  * tls1_change_cipher_state_cipher performs the work needed to switch cipher
364  * states when using EVP_CIPHER. The argument is_read is true iff this function
365  * is being called due to reading, as opposed to writing, a ChangeCipherSpec
366  * message. In order to support export ciphersuites, use_client_keys indicates
367  * whether the key material provided is in the "client write" direction.
368  */
369 static int
370 tls1_change_cipher_state_cipher(SSL *s, char is_read, char use_client_keys,
371     const unsigned char *mac_secret, unsigned int mac_secret_size,
372     const unsigned char *key, unsigned int key_len, const unsigned char *iv,
373     unsigned int iv_len)
374 {
375 	EVP_CIPHER_CTX *cipher_ctx;
376 	const EVP_CIPHER *cipher;
377 	EVP_MD_CTX *mac_ctx;
378 	const EVP_MD *mac;
379 	int mac_type;
380 
381 	cipher = s->s3->tmp.new_sym_enc;
382 	mac = s->s3->tmp.new_hash;
383 	mac_type = s->s3->tmp.new_mac_pkey_type;
384 
385 	if (is_read) {
386 		if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
387 			s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
388 		else
389 			s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
390 
391 		EVP_CIPHER_CTX_free(s->enc_read_ctx);
392 		s->enc_read_ctx = NULL;
393 		EVP_MD_CTX_destroy(s->read_hash);
394 		s->read_hash = NULL;
395 
396 		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
397 			goto err;
398 		s->enc_read_ctx = cipher_ctx;
399 		if ((mac_ctx = EVP_MD_CTX_create()) == NULL)
400 			goto err;
401 		s->read_hash = mac_ctx;
402 	} else {
403 		if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
404 			s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
405 		else
406 			s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
407 
408 		/*
409 		 * DTLS fragments retain a pointer to the compression, cipher
410 		 * and hash contexts, so that it can restore state in order
411 		 * to perform retransmissions. As such, we cannot free write
412 		 * contexts that are used for DTLS - these are instead freed
413 		 * by DTLS when its frees a ChangeCipherSpec fragment.
414 		 */
415 		if (!SSL_IS_DTLS(s)) {
416 			EVP_CIPHER_CTX_free(s->enc_write_ctx);
417 			s->enc_write_ctx = NULL;
418 			EVP_MD_CTX_destroy(s->write_hash);
419 			s->write_hash = NULL;
420 		}
421 		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
422 			goto err;
423 		s->enc_write_ctx = cipher_ctx;
424 		if ((mac_ctx = EVP_MD_CTX_create()) == NULL)
425 			goto err;
426 		s->write_hash = mac_ctx;
427 	}
428 
429 	if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE) {
430 		EVP_CipherInit_ex(cipher_ctx, cipher, NULL, key, NULL,
431 		    !is_read);
432 		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GCM_SET_IV_FIXED,
433 		    iv_len, (unsigned char *)iv);
434 	} else
435 		EVP_CipherInit_ex(cipher_ctx, cipher, NULL, key, iv, !is_read);
436 
437 	if (!(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
438 		EVP_PKEY *mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
439 		    mac_secret, mac_secret_size);
440 		if (mac_key == NULL)
441 			goto err;
442 		EVP_DigestSignInit(mac_ctx, NULL, mac, NULL, mac_key);
443 		EVP_PKEY_free(mac_key);
444 	} else if (mac_secret_size > 0) {
445 		/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
446 		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
447 		    mac_secret_size, (unsigned char *)mac_secret);
448 	}
449 
450 	return (1);
451 
452 err:
453 	SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_CIPHER, ERR_R_MALLOC_FAILURE);
454 	return (0);
455 }
456 
457 int
458 tls1_change_cipher_state(SSL *s, int which)
459 {
460 	const unsigned char *client_write_mac_secret, *server_write_mac_secret;
461 	const unsigned char *client_write_key, *server_write_key;
462 	const unsigned char *client_write_iv, *server_write_iv;
463 	const unsigned char *mac_secret, *key, *iv;
464 	int mac_secret_size, key_len, iv_len;
465 	unsigned char *key_block, *seq;
466 	const EVP_CIPHER *cipher;
467 	const EVP_AEAD *aead;
468 	char is_read, use_client_keys;
469 
470 
471 	cipher = s->s3->tmp.new_sym_enc;
472 	aead = s->s3->tmp.new_aead;
473 
474 	/*
475 	 * is_read is true if we have just read a ChangeCipherSpec message,
476 	 * that is we need to update the read cipherspec. Otherwise we have
477 	 * just written one.
478 	 */
479 	is_read = (which & SSL3_CC_READ) != 0;
480 
481 	/*
482 	 * use_client_keys is true if we wish to use the keys for the "client
483 	 * write" direction. This is the case if we're a client sending a
484 	 * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec.
485 	 */
486 	use_client_keys = ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
487 	    (which == SSL3_CHANGE_CIPHER_SERVER_READ));
488 
489 
490 	/*
491 	 * Reset sequence number to zero - for DTLS this is handled in
492 	 * dtls1_reset_seq_numbers().
493 	 */
494 	if (!SSL_IS_DTLS(s)) {
495 		seq = is_read ? s->s3->read_sequence : s->s3->write_sequence;
496 		memset(seq, 0, SSL3_SEQUENCE_SIZE);
497 	}
498 
499 	if (aead != NULL) {
500 		key_len = EVP_AEAD_key_length(aead);
501 		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
502 	} else {
503 		key_len = EVP_CIPHER_key_length(cipher);
504 		iv_len = EVP_CIPHER_iv_length(cipher);
505 
506 		/* If GCM mode only part of IV comes from PRF. */
507 		if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
508 			iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
509 	}
510 
511 	mac_secret_size = s->s3->tmp.new_mac_secret_size;
512 
513 	key_block = s->s3->tmp.key_block;
514 	client_write_mac_secret = key_block;
515 	key_block += mac_secret_size;
516 	server_write_mac_secret = key_block;
517 	key_block += mac_secret_size;
518 	client_write_key = key_block;
519 	key_block += key_len;
520 	server_write_key = key_block;
521 	key_block += key_len;
522 	client_write_iv = key_block;
523 	key_block += iv_len;
524 	server_write_iv = key_block;
525 	key_block += iv_len;
526 
527 	if (use_client_keys) {
528 		mac_secret = client_write_mac_secret;
529 		key = client_write_key;
530 		iv = client_write_iv;
531 	} else {
532 		mac_secret = server_write_mac_secret;
533 		key = server_write_key;
534 		iv = server_write_iv;
535 	}
536 
537 	if (key_block - s->s3->tmp.key_block != s->s3->tmp.key_block_length) {
538 		SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
539 		goto err2;
540 	}
541 
542 	if (is_read) {
543 		memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_size);
544 		s->s3->read_mac_secret_size = mac_secret_size;
545 	} else {
546 		memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_size);
547 		s->s3->write_mac_secret_size = mac_secret_size;
548 	}
549 
550 	if (aead != NULL) {
551 		return tls1_change_cipher_state_aead(s, is_read, key, key_len,
552 		    iv, iv_len);
553 	}
554 
555 	return tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
556 	    mac_secret, mac_secret_size, key, key_len, iv, iv_len);
557 
558 err2:
559 	return (0);
560 }
561 
562 int
563 tls1_setup_key_block(SSL *s)
564 {
565 	unsigned char *key_block, *tmp_block = NULL;
566 	int mac_type = NID_undef, mac_secret_size = 0;
567 	int key_block_len, key_len, iv_len;
568 	const EVP_CIPHER *cipher = NULL;
569 	const EVP_AEAD *aead = NULL;
570 	const EVP_MD *mac = NULL;
571 	int ret = 0;
572 
573 	if (s->s3->tmp.key_block_length != 0)
574 		return (1);
575 
576 	if (s->session->cipher &&
577 	    (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD)) {
578 		if (!ssl_cipher_get_evp_aead(s->session, &aead)) {
579 			SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,
580 			    SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
581 			return (0);
582 		}
583 		key_len = EVP_AEAD_key_length(aead);
584 		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
585 	} else {
586 		if (!ssl_cipher_get_evp(s->session, &cipher, &mac, &mac_type,
587 		    &mac_secret_size)) {
588 			SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,
589 			    SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
590 			return (0);
591 		}
592 		key_len = EVP_CIPHER_key_length(cipher);
593 		iv_len = EVP_CIPHER_iv_length(cipher);
594 
595 		/* If GCM mode only part of IV comes from PRF. */
596 		if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
597 			iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
598 	}
599 
600 	s->s3->tmp.new_aead = aead;
601 	s->s3->tmp.new_sym_enc = cipher;
602 	s->s3->tmp.new_hash = mac;
603 	s->s3->tmp.new_mac_pkey_type = mac_type;
604 	s->s3->tmp.new_mac_secret_size = mac_secret_size;
605 
606 	key_block_len = (mac_secret_size + key_len + iv_len) * 2;
607 
608 	ssl3_cleanup_key_block(s);
609 
610 	if ((key_block = malloc(key_block_len)) == NULL) {
611 		SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
612 		goto err;
613 	}
614 
615 	s->s3->tmp.key_block_length = key_block_len;
616 	s->s3->tmp.key_block = key_block;
617 
618 	if ((tmp_block = malloc(key_block_len)) == NULL) {
619 		SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
620 		goto err;
621 	}
622 
623 	if (!tls1_generate_key_block(s, key_block, tmp_block, key_block_len))
624 		goto err;
625 
626 	if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) &&
627 	    s->method->version <= TLS1_VERSION) {
628 		/*
629 		 * Enable vulnerability countermeasure for CBC ciphers with
630 		 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
631 		 */
632 		s->s3->need_empty_fragments = 1;
633 
634 		if (s->session->cipher != NULL) {
635 			if (s->session->cipher->algorithm_enc == SSL_eNULL)
636 				s->s3->need_empty_fragments = 0;
637 
638 #ifndef OPENSSL_NO_RC4
639 			if (s->session->cipher->algorithm_enc == SSL_RC4)
640 				s->s3->need_empty_fragments = 0;
641 #endif
642 		}
643 	}
644 
645 	ret = 1;
646 
647 err:
648 	if (tmp_block) {
649 		OPENSSL_cleanse(tmp_block, key_block_len);
650 		free(tmp_block);
651 	}
652 	return (ret);
653 }
654 
655 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
656  *
657  * Returns:
658  *   0: (in non-constant time) if the record is publically invalid (i.e. too
659  *       short etc).
660  *   1: if the record's padding is valid / the encryption was successful.
661  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
662  *       an internal error occured.
663  */
664 int
665 tls1_enc(SSL *s, int send)
666 {
667 	const SSL_AEAD_CTX *aead;
668 	const EVP_CIPHER *enc;
669 	EVP_CIPHER_CTX *ds;
670 	SSL3_RECORD *rec;
671 	unsigned char *seq;
672 	unsigned long l;
673 	int bs, i, j, k, pad = 0, ret, mac_size = 0;
674 
675 	if (send) {
676 		aead = s->aead_write_ctx;
677 		rec = &s->s3->wrec;
678 		seq = s->s3->write_sequence;
679 	} else {
680 		aead = s->aead_read_ctx;
681 		rec = &s->s3->rrec;
682 		seq = s->s3->read_sequence;
683 	}
684 
685 	if (aead) {
686 		unsigned char ad[13], *in, *out, nonce[16];
687 		unsigned nonce_used;
688 		ssize_t n;
689 
690 		if (SSL_IS_DTLS(s)) {
691 			dtls1_build_sequence_number(ad, seq,
692 			    send ? s->d1->w_epoch : s->d1->r_epoch);
693 		} else {
694 			memcpy(ad, seq, SSL3_SEQUENCE_SIZE);
695 			ssl3_record_sequence_increment(seq);
696 		}
697 
698 		ad[8] = rec->type;
699 		ad[9] = (unsigned char)(s->version >> 8);
700 		ad[10] = (unsigned char)(s->version);
701 
702 		if (aead->fixed_nonce_len +
703 		    aead->variable_nonce_len > sizeof(nonce) ||
704 		    aead->variable_nonce_len > 8)
705 			return -1;  /* internal error - should never happen. */
706 
707 		memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
708 		nonce_used = aead->fixed_nonce_len;
709 
710 		if (send) {
711 			size_t len = rec->length;
712 			size_t eivlen = 0;
713 			in = rec->input;
714 			out = rec->data;
715 
716 			/*
717 			 * When sending we use the sequence number as the
718 			 * variable part of the nonce.
719 			 */
720 			if (aead->variable_nonce_len > 8)
721 				return -1;
722 			memcpy(nonce + nonce_used, ad,
723 			    aead->variable_nonce_len);
724 			nonce_used += aead->variable_nonce_len;
725 
726 			/*
727 			 * In do_ssl3_write, rec->input is moved forward by
728 			 * variable_nonce_len in order to leave space for the
729 			 * variable nonce. Thus we can copy the sequence number
730 			 * bytes into place without overwriting any of the
731 			 * plaintext.
732 			 */
733 			if (aead->variable_nonce_in_record) {
734 				memcpy(out, ad, aead->variable_nonce_len);
735 				len -= aead->variable_nonce_len;
736 				eivlen = aead->variable_nonce_len;
737 			}
738 
739 			ad[11] = len >> 8;
740 			ad[12] = len & 0xff;
741 
742 			if (!EVP_AEAD_CTX_seal(&aead->ctx,
743 			    out + eivlen, &n, len + aead->tag_len, nonce,
744 			    nonce_used, in + eivlen, len, ad, sizeof(ad)))
745 				return -1;
746 			if (n >= 0 && aead->variable_nonce_in_record)
747 				n += aead->variable_nonce_len;
748 		} else {
749 			/* receive */
750 			size_t len = rec->length;
751 
752 			if (rec->data != rec->input)
753 				return -1;  /* internal error - should never happen. */
754 			out = in = rec->input;
755 
756 			if (len < aead->variable_nonce_len)
757 				return 0;
758 			memcpy(nonce + nonce_used,
759 			    aead->variable_nonce_in_record ? in : ad,
760 			    aead->variable_nonce_len);
761 			nonce_used += aead->variable_nonce_len;
762 
763 			if (aead->variable_nonce_in_record) {
764 				in += aead->variable_nonce_len;
765 				len -= aead->variable_nonce_len;
766 				out += aead->variable_nonce_len;
767 			}
768 
769 			if (len < aead->tag_len)
770 				return 0;
771 			len -= aead->tag_len;
772 
773 			ad[11] = len >> 8;
774 			ad[12] = len & 0xff;
775 
776 			if (!EVP_AEAD_CTX_open(&aead->ctx, out, &n, len, nonce,
777 			    nonce_used, in, len + aead->tag_len, ad,
778 			    sizeof(ad)))
779 				return -1;
780 
781 			rec->data = rec->input = out;
782 		}
783 
784 		if (n == -1)
785 			return -1;
786 		rec->length = n;
787 
788 		return 1;
789 	}
790 
791 	if (send) {
792 		if (EVP_MD_CTX_md(s->write_hash)) {
793 			int n = EVP_MD_CTX_size(s->write_hash);
794 			OPENSSL_assert(n >= 0);
795 		}
796 		ds = s->enc_write_ctx;
797 		if (s->enc_write_ctx == NULL)
798 			enc = NULL;
799 		else {
800 			int ivlen = 0;
801 			enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
802 			if (SSL_USE_EXPLICIT_IV(s) &&
803 			    EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
804 				ivlen = EVP_CIPHER_iv_length(enc);
805 			if (ivlen > 1) {
806 				if (rec->data != rec->input)
807 					/* we can't write into the input stream:
808 					 * Can this ever happen?? (steve)
809 					 */
810 					fprintf(stderr,
811 					    "%s:%d: rec->data != rec->input\n",
812 					    __FILE__, __LINE__);
813 				else if (RAND_bytes(rec->input, ivlen) <= 0)
814 					return -1;
815 			}
816 		}
817 	} else {
818 		if (EVP_MD_CTX_md(s->read_hash)) {
819 			int n = EVP_MD_CTX_size(s->read_hash);
820 			OPENSSL_assert(n >= 0);
821 		}
822 		ds = s->enc_read_ctx;
823 		if (s->enc_read_ctx == NULL)
824 			enc = NULL;
825 		else
826 			enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
827 	}
828 
829 	if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
830 		memmove(rec->data, rec->input, rec->length);
831 		rec->input = rec->data;
832 		ret = 1;
833 	} else {
834 		l = rec->length;
835 		bs = EVP_CIPHER_block_size(ds->cipher);
836 
837 		if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
838 			unsigned char buf[13];
839 
840 			if (SSL_IS_DTLS(s)) {
841 				dtls1_build_sequence_number(buf, seq,
842 				    send ? s->d1->w_epoch : s->d1->r_epoch);
843 			} else {
844 				memcpy(buf, seq, SSL3_SEQUENCE_SIZE);
845 				ssl3_record_sequence_increment(seq);
846 			}
847 
848 			buf[8] = rec->type;
849 			buf[9] = (unsigned char)(s->version >> 8);
850 			buf[10] = (unsigned char)(s->version);
851 			buf[11] = rec->length >> 8;
852 			buf[12] = rec->length & 0xff;
853 			pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD, 13, buf);
854 			if (send) {
855 				l += pad;
856 				rec->length += pad;
857 			}
858 		} else if ((bs != 1) && send) {
859 			i = bs - ((int)l % bs);
860 
861 			/* Add weird padding of upto 256 bytes */
862 
863 			/* we need to add 'i' padding bytes of value j */
864 			j = i - 1;
865 			if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) {
866 				if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
867 					j++;
868 			}
869 			for (k = (int)l; k < (int)(l + i); k++)
870 				rec->input[k] = j;
871 			l += i;
872 			rec->length += i;
873 		}
874 
875 		if (!send) {
876 			if (l == 0 || l % bs != 0)
877 				return 0;
878 		}
879 
880 		i = EVP_Cipher(ds, rec->data, rec->input, l);
881 		if ((EVP_CIPHER_flags(ds->cipher) &
882 		    EVP_CIPH_FLAG_CUSTOM_CIPHER) ? (i < 0) : (i == 0))
883 			return -1;	/* AEAD can fail to verify MAC */
884 		if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
885 			rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
886 			rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
887 			rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
888 		}
889 
890 		ret = 1;
891 		if (EVP_MD_CTX_md(s->read_hash) != NULL)
892 			mac_size = EVP_MD_CTX_size(s->read_hash);
893 		if ((bs != 1) && !send)
894 			ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
895 		if (pad && !send)
896 			rec->length -= pad;
897 	}
898 	return ret;
899 }
900 
901 int
902 tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
903 {
904 	EVP_MD_CTX ctx, *d = NULL;
905 	unsigned int ret;
906 	int i;
907 
908 	if (s->s3->handshake_buffer)
909 		if (!ssl3_digest_cached_records(s))
910 			return 0;
911 
912 	for (i = 0; i < SSL_MAX_DIGEST; i++) {
913 		if (s->s3->handshake_dgst[i] &&
914 		    EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) {
915 			d = s->s3->handshake_dgst[i];
916 			break;
917 		}
918 	}
919 	if (d == NULL) {
920 		SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC, SSL_R_NO_REQUIRED_DIGEST);
921 		return 0;
922 	}
923 
924 	EVP_MD_CTX_init(&ctx);
925 	if (!EVP_MD_CTX_copy_ex(&ctx, d))
926 		return 0;
927 	EVP_DigestFinal_ex(&ctx, out, &ret);
928 	EVP_MD_CTX_cleanup(&ctx);
929 
930 	return ((int)ret);
931 }
932 
933 int
934 tls1_final_finish_mac(SSL *s, const char *str, int slen, unsigned char *out)
935 {
936 	unsigned int i;
937 	EVP_MD_CTX ctx;
938 	unsigned char buf[2*EVP_MAX_MD_SIZE];
939 	unsigned char *q, buf2[12];
940 	int idx;
941 	long mask;
942 	int err = 0;
943 	const EVP_MD *md;
944 
945 	q = buf;
946 
947 	if (s->s3->handshake_buffer)
948 		if (!ssl3_digest_cached_records(s))
949 			return 0;
950 
951 	EVP_MD_CTX_init(&ctx);
952 
953 	for (idx = 0; ssl_get_handshake_digest(idx, &mask, &md); idx++) {
954 		if (ssl_get_algorithm2(s) & mask) {
955 			int hashsize = EVP_MD_size(md);
956 			EVP_MD_CTX *hdgst = s->s3->handshake_dgst[idx];
957 			if (!hdgst || hashsize < 0 ||
958 			    hashsize > (int)(sizeof buf - (size_t)(q - buf))) {
959 				/* internal error: 'buf' is too small for this cipersuite! */
960 				err = 1;
961 			} else {
962 				if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
963 				    !EVP_DigestFinal_ex(&ctx, q, &i) ||
964 				    (i != (unsigned int)hashsize))
965 					err = 1;
966 				q += hashsize;
967 			}
968 		}
969 	}
970 
971 	if (!tls1_PRF(ssl_get_algorithm2(s), str, slen, buf, (int)(q - buf),
972 	    NULL, 0, NULL, 0, NULL, 0,
973 	    s->session->master_key, s->session->master_key_length,
974 	    out, buf2, sizeof buf2))
975 		err = 1;
976 	EVP_MD_CTX_cleanup(&ctx);
977 
978 	if (err)
979 		return 0;
980 	else
981 		return sizeof buf2;
982 }
983 
984 int
985 tls1_mac(SSL *ssl, unsigned char *md, int send)
986 {
987 	SSL3_RECORD *rec;
988 	unsigned char *seq;
989 	EVP_MD_CTX *hash;
990 	size_t md_size, orig_len;
991 	EVP_MD_CTX hmac, *mac_ctx;
992 	unsigned char header[13];
993 	int stream_mac = (send ?
994 	    (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) :
995 	    (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
996 	int t;
997 
998 	if (send) {
999 		rec = &(ssl->s3->wrec);
1000 		seq = &(ssl->s3->write_sequence[0]);
1001 		hash = ssl->write_hash;
1002 	} else {
1003 		rec = &(ssl->s3->rrec);
1004 		seq = &(ssl->s3->read_sequence[0]);
1005 		hash = ssl->read_hash;
1006 	}
1007 
1008 	t = EVP_MD_CTX_size(hash);
1009 	OPENSSL_assert(t >= 0);
1010 	md_size = t;
1011 
1012 	/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1013 	if (stream_mac) {
1014 		mac_ctx = hash;
1015 	} else {
1016 		if (!EVP_MD_CTX_copy(&hmac, hash))
1017 			return -1;
1018 		mac_ctx = &hmac;
1019 	}
1020 
1021 	if (SSL_IS_DTLS(ssl))
1022 		dtls1_build_sequence_number(header, seq,
1023 		    send ? ssl->d1->w_epoch : ssl->d1->r_epoch);
1024 	else
1025 		memcpy(header, seq, SSL3_SEQUENCE_SIZE);
1026 
1027 	/* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1028 	orig_len = rec->length + md_size + ((unsigned int)rec->type >> 8);
1029 	rec->type &= 0xff;
1030 
1031 	header[8] = rec->type;
1032 	header[9] = (unsigned char)(ssl->version >> 8);
1033 	header[10] = (unsigned char)(ssl->version);
1034 	header[11] = (rec->length) >> 8;
1035 	header[12] = (rec->length) & 0xff;
1036 
1037 	if (!send &&
1038 	    EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1039 	    ssl3_cbc_record_digest_supported(mac_ctx)) {
1040 		/* This is a CBC-encrypted record. We must avoid leaking any
1041 		 * timing-side channel information about how many blocks of
1042 		 * data we are hashing because that gives an attacker a
1043 		 * timing-oracle. */
1044 		ssl3_cbc_digest_record(mac_ctx,
1045 		    md, &md_size, header, rec->input,
1046 		    rec->length + md_size, orig_len,
1047 		    ssl->s3->read_mac_secret,
1048 		    ssl->s3->read_mac_secret_size,
1049 		    0 /* not SSLv3 */);
1050 	} else {
1051 		EVP_DigestSignUpdate(mac_ctx, header, sizeof(header));
1052 		EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length);
1053 		t = EVP_DigestSignFinal(mac_ctx, md, &md_size);
1054 		OPENSSL_assert(t > 0);
1055 	}
1056 
1057 	if (!stream_mac)
1058 		EVP_MD_CTX_cleanup(&hmac);
1059 
1060 	if (!SSL_IS_DTLS(ssl))
1061 		ssl3_record_sequence_increment(seq);
1062 
1063 	return (md_size);
1064 }
1065 
1066 int
1067 tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1068     int len)
1069 {
1070 	unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1071 	const void *co = NULL, *so = NULL;
1072 	int col = 0, sol = 0;
1073 
1074 	tls1_PRF(ssl_get_algorithm2(s),
1075 	    TLS_MD_MASTER_SECRET_CONST, TLS_MD_MASTER_SECRET_CONST_SIZE,
1076 	    s->s3->client_random, SSL3_RANDOM_SIZE, co, col,
1077 	    s->s3->server_random, SSL3_RANDOM_SIZE, so, sol,
1078 	    p, len, s->session->master_key, buff, sizeof buff);
1079 
1080 	return (SSL3_MASTER_SECRET_SIZE);
1081 }
1082 
1083 int
1084 tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1085     const char *label, size_t llen, const unsigned char *context,
1086     size_t contextlen, int use_context)
1087 {
1088 	unsigned char *buff;
1089 	unsigned char *val = NULL;
1090 	size_t vallen, currentvalpos;
1091 	int rv;
1092 
1093 	buff = malloc(olen);
1094 	if (buff == NULL)
1095 		goto err2;
1096 
1097 	/* construct PRF arguments
1098 	 * we construct the PRF argument ourself rather than passing separate
1099 	 * values into the TLS PRF to ensure that the concatenation of values
1100 	 * does not create a prohibited label.
1101 	 */
1102 	vallen = llen + SSL3_RANDOM_SIZE * 2;
1103 	if (use_context) {
1104 		vallen += 2 + contextlen;
1105 	}
1106 
1107 	val = malloc(vallen);
1108 	if (val == NULL)
1109 		goto err2;
1110 	currentvalpos = 0;
1111 	memcpy(val + currentvalpos, (unsigned char *) label, llen);
1112 	currentvalpos += llen;
1113 	memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1114 	currentvalpos += SSL3_RANDOM_SIZE;
1115 	memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1116 	currentvalpos += SSL3_RANDOM_SIZE;
1117 
1118 	if (use_context) {
1119 		val[currentvalpos] = (contextlen >> 8) & 0xff;
1120 		currentvalpos++;
1121 		val[currentvalpos] = contextlen & 0xff;
1122 		currentvalpos++;
1123 		if ((contextlen > 0) || (context != NULL)) {
1124 			memcpy(val + currentvalpos, context, contextlen);
1125 		}
1126 	}
1127 
1128 	/* disallow prohibited labels
1129 	 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1130 	 * 15, so size of val > max(prohibited label len) = 15 and the
1131 	 * comparisons won't have buffer overflow
1132 	 */
1133 	if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1134 	    TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
1135 		goto err1;
1136 	if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1137 	    TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
1138 		goto err1;
1139 	if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1140 	    TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
1141 		goto err1;
1142 	if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1143 	    TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
1144 		goto err1;
1145 
1146 	rv = tls1_PRF(ssl_get_algorithm2(s),
1147 	    val, vallen, NULL, 0, NULL, 0, NULL, 0, NULL, 0,
1148 	    s->session->master_key, s->session->master_key_length,
1149 	    out, buff, olen);
1150 
1151 	goto ret;
1152 err1:
1153 	SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL,
1154 	    SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1155 	rv = 0;
1156 	goto ret;
1157 err2:
1158 	SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
1159 	rv = 0;
1160 ret:
1161 	free(buff);
1162 	free(val);
1163 
1164 	return (rv);
1165 }
1166 
1167 int
1168 tls1_alert_code(int code)
1169 {
1170 	switch (code) {
1171 	case SSL_AD_CLOSE_NOTIFY:
1172 		return (SSL3_AD_CLOSE_NOTIFY);
1173 	case SSL_AD_UNEXPECTED_MESSAGE:
1174 		return (SSL3_AD_UNEXPECTED_MESSAGE);
1175 	case SSL_AD_BAD_RECORD_MAC:
1176 		return (SSL3_AD_BAD_RECORD_MAC);
1177 	case SSL_AD_DECRYPTION_FAILED:
1178 		return (TLS1_AD_DECRYPTION_FAILED);
1179 	case SSL_AD_RECORD_OVERFLOW:
1180 		return (TLS1_AD_RECORD_OVERFLOW);
1181 	case SSL_AD_DECOMPRESSION_FAILURE:
1182 		return (SSL3_AD_DECOMPRESSION_FAILURE);
1183 	case SSL_AD_HANDSHAKE_FAILURE:
1184 		return (SSL3_AD_HANDSHAKE_FAILURE);
1185 	case SSL_AD_NO_CERTIFICATE:
1186 		return (-1);
1187 	case SSL_AD_BAD_CERTIFICATE:
1188 		return (SSL3_AD_BAD_CERTIFICATE);
1189 	case SSL_AD_UNSUPPORTED_CERTIFICATE:
1190 		return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
1191 	case SSL_AD_CERTIFICATE_REVOKED:
1192 		return (SSL3_AD_CERTIFICATE_REVOKED);
1193 	case SSL_AD_CERTIFICATE_EXPIRED:
1194 		return (SSL3_AD_CERTIFICATE_EXPIRED);
1195 	case SSL_AD_CERTIFICATE_UNKNOWN:
1196 		return (SSL3_AD_CERTIFICATE_UNKNOWN);
1197 	case SSL_AD_ILLEGAL_PARAMETER:
1198 		return (SSL3_AD_ILLEGAL_PARAMETER);
1199 	case SSL_AD_UNKNOWN_CA:
1200 		return (TLS1_AD_UNKNOWN_CA);
1201 	case SSL_AD_ACCESS_DENIED:
1202 		return (TLS1_AD_ACCESS_DENIED);
1203 	case SSL_AD_DECODE_ERROR:
1204 		return (TLS1_AD_DECODE_ERROR);
1205 	case SSL_AD_DECRYPT_ERROR:
1206 		return (TLS1_AD_DECRYPT_ERROR);
1207 	case SSL_AD_EXPORT_RESTRICTION:
1208 		return (TLS1_AD_EXPORT_RESTRICTION);
1209 	case SSL_AD_PROTOCOL_VERSION:
1210 		return (TLS1_AD_PROTOCOL_VERSION);
1211 	case SSL_AD_INSUFFICIENT_SECURITY:
1212 		return (TLS1_AD_INSUFFICIENT_SECURITY);
1213 	case SSL_AD_INTERNAL_ERROR:
1214 		return (TLS1_AD_INTERNAL_ERROR);
1215 	case SSL_AD_USER_CANCELLED:
1216 		return (TLS1_AD_USER_CANCELLED);
1217 	case SSL_AD_NO_RENEGOTIATION:
1218 		return (TLS1_AD_NO_RENEGOTIATION);
1219 	case SSL_AD_UNSUPPORTED_EXTENSION:
1220 		return (TLS1_AD_UNSUPPORTED_EXTENSION);
1221 	case SSL_AD_CERTIFICATE_UNOBTAINABLE:
1222 		return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1223 	case SSL_AD_UNRECOGNIZED_NAME:
1224 		return (TLS1_AD_UNRECOGNIZED_NAME);
1225 	case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
1226 		return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1227 	case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
1228 		return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1229 	case SSL_AD_UNKNOWN_PSK_IDENTITY:
1230 		return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
1231 	default:
1232 		return (-1);
1233 	}
1234 }
1235