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