GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: lib/libssl/t1_enc.c Lines: 452 590 76.6 %
Date: 2017-11-13 Branches: 221 377 58.6 %

Line Branch Exec Source
1
/* $OpenBSD: t1_enc.c,v 1.109 2017/05/06 22:24:58 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 <limits.h>
139
#include <stdio.h>
140
141
#include "ssl_locl.h"
142
143
#include <openssl/evp.h>
144
#include <openssl/hmac.h>
145
#include <openssl/md5.h>
146
147
int tls1_PRF(SSL *s, const unsigned char *secret, size_t secret_len,
148
    const void *seed1, size_t seed1_len, const void *seed2, size_t seed2_len,
149
    const void *seed3, size_t seed3_len, const void *seed4, size_t seed4_len,
150
    const void *seed5, size_t seed5_len, unsigned char *out, size_t out_len);
151
152
void
153
tls1_cleanup_key_block(SSL *s)
154
{
155
110142
	freezero(S3I(s)->hs.key_block, S3I(s)->hs.key_block_len);
156
55071
	S3I(s)->hs.key_block = NULL;
157
55071
	S3I(s)->hs.key_block_len = 0;
158
55071
}
159
160
int
161
tls1_init_finished_mac(SSL *s)
162
{
163
32204
	BIO_free(S3I(s)->handshake_buffer);
164
165
16102
	S3I(s)->handshake_buffer = BIO_new(BIO_s_mem());
166
16102
	if (S3I(s)->handshake_buffer == NULL)
167
		return (0);
168
169
16102
	(void)BIO_set_close(S3I(s)->handshake_buffer, BIO_CLOSE);
170
171
16102
	return (1);
172
16102
}
173
174
int
175
tls1_finish_mac(SSL *s, const unsigned char *buf, int len)
176
{
177
143520
	if (len < 0)
178
		return 0;
179
180
71760
	if (!tls1_handshake_hash_update(s, buf, len))
181
		return 0;
182
183

136649
	if (S3I(s)->handshake_buffer &&
184
64889
	    !(s->s3->flags & TLS1_FLAGS_KEEP_HANDSHAKE)) {
185
64874
		BIO_write(S3I(s)->handshake_buffer, (void *)buf, len);
186
64874
		return 1;
187
	}
188
189
6886
	return 1;
190
71760
}
191
192
int
193
tls1_digest_cached_records(SSL *s)
194
{
195
	long hdatalen;
196
2996
	void *hdata;
197
198
1498
	hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
199
1498
	if (hdatalen <= 0) {
200
		SSLerror(s, SSL_R_BAD_HANDSHAKE_LENGTH);
201
		goto err;
202
	}
203
204
1498
	if (!(s->s3->flags & TLS1_FLAGS_KEEP_HANDSHAKE)) {
205
1483
		BIO_free(S3I(s)->handshake_buffer);
206
1483
		S3I(s)->handshake_buffer = NULL;
207
1483
	}
208
209
1498
	return 1;
210
211
 err:
212
	return 0;
213
1498
}
214
215
void
216
tls1_record_sequence_increment(unsigned char *seq)
217
{
218
	int i;
219
220
100974
	for (i = SSL3_SEQUENCE_SIZE - 1; i >= 0; i--) {
221
33658
		if (++seq[i] != 0)
222
			break;
223
	}
224
33658
}
225
226
/*
227
 * TLS P_hash() data expansion function - see RFC 5246, section 5.
228
 */
229
static int
230
tls1_P_hash(const EVP_MD *md, const unsigned char *secret, size_t secret_len,
231
    const void *seed1, size_t seed1_len, const void *seed2, size_t seed2_len,
232
    const void *seed3, size_t seed3_len, const void *seed4, size_t seed4_len,
233
    const void *seed5, size_t seed5_len, unsigned char *out, size_t out_len)
234
{
235
137608
	unsigned char A1[EVP_MAX_MD_SIZE], hmac[EVP_MAX_MD_SIZE];
236
68804
	size_t A1_len, hmac_len;
237
68804
	EVP_MD_CTX ctx;
238
	EVP_PKEY *mac_key;
239
	int ret = 0;
240
	int chunk;
241
	size_t i;
242
243
68804
	chunk = EVP_MD_size(md);
244
68804
	OPENSSL_assert(chunk >= 0);
245
246
68804
	EVP_MD_CTX_init(&ctx);
247
248
68804
	mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
249
68804
	if (!mac_key)
250
		goto err;
251
68804
	if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
252
		goto err;
253

137608
	if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
254
		goto err;
255

137608
	if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
256
		goto err;
257

87351
	if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
258
		goto err;
259

72780
	if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
260
		goto err;
261

71108
	if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
262
		goto err;
263
68804
	if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
264
		goto err;
265
266
92391
	for (;;) {
267
92391
		if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
268
			goto err;
269
92391
		if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
270
			goto err;
271

184782
		if (seed1 && !EVP_DigestSignUpdate(&ctx, seed1, seed1_len))
272
			goto err;
273

184782
		if (seed2 && !EVP_DigestSignUpdate(&ctx, seed2, seed2_len))
274
			goto err;
275

133715
		if (seed3 && !EVP_DigestSignUpdate(&ctx, seed3, seed3_len))
276
			goto err;
277

101629
		if (seed4 && !EVP_DigestSignUpdate(&ctx, seed4, seed4_len))
278
			goto err;
279

99147
		if (seed5 && !EVP_DigestSignUpdate(&ctx, seed5, seed5_len))
280
			goto err;
281
92391
		if (!EVP_DigestSignFinal(&ctx, hmac, &hmac_len))
282
			goto err;
283
284
92391
		if (hmac_len > out_len)
285
67240
			hmac_len = out_len;
286
287
4193142
		for (i = 0; i < hmac_len; i++)
288
2004180
			out[i] ^= hmac[i];
289
290
92391
		out += hmac_len;
291
92391
		out_len -= hmac_len;
292
293
92391
		if (out_len == 0)
294
			break;
295
296
23587
		if (!EVP_DigestSignInit(&ctx, NULL, md, NULL, mac_key))
297
			goto err;
298
23587
		if (!EVP_DigestSignUpdate(&ctx, A1, A1_len))
299
			goto err;
300
23587
		if (!EVP_DigestSignFinal(&ctx, A1, &A1_len))
301
			goto err;
302
	}
303
68804
	ret = 1;
304
305
 err:
306
68804
	EVP_PKEY_free(mac_key);
307
68804
	EVP_MD_CTX_cleanup(&ctx);
308
309
68804
	explicit_bzero(A1, sizeof(A1));
310
68804
	explicit_bzero(hmac, sizeof(hmac));
311
312
68804
	return ret;
313
68804
}
314
315
int
316
tls1_PRF(SSL *s, const unsigned char *secret, size_t secret_len,
317
    const void *seed1, size_t seed1_len, const void *seed2, size_t seed2_len,
318
    const void *seed3, size_t seed3_len, const void *seed4, size_t seed4_len,
319
    const void *seed5, size_t seed5_len, unsigned char *out, size_t out_len)
320
{
321
135184
	const EVP_MD *md;
322
	size_t half_len;
323
324
67592
	memset(out, 0, out_len);
325
326
67592
	if (!ssl_get_handshake_evp_md(s, &md))
327
		return (0);
328
329
67592
	if (md->type == NID_md5_sha1) {
330
		/*
331
		 * Partition secret between MD5 and SHA1, then XOR result.
332
		 * If the secret length is odd, a one byte overlap is used.
333
		 */
334
1212
		half_len = secret_len - (secret_len / 2);
335
1212
		if (!tls1_P_hash(EVP_md5(), secret, half_len, seed1, seed1_len,
336
		    seed2, seed2_len, seed3, seed3_len, seed4, seed4_len,
337
		    seed5, seed5_len, out, out_len))
338
			return (0);
339
340
1212
		secret += secret_len - half_len;
341
1212
		if (!tls1_P_hash(EVP_sha1(), secret, half_len, seed1, seed1_len,
342
		    seed2, seed2_len, seed3, seed3_len, seed4, seed4_len,
343
		    seed5, seed5_len, out, out_len))
344
			return (0);
345
346
1212
		return (1);
347
	}
348
349
66380
	if (!tls1_P_hash(md, secret, secret_len, seed1, seed1_len,
350
	    seed2, seed2_len, seed3, seed3_len, seed4, seed4_len,
351
	    seed5, seed5_len, out, out_len))
352
		return (0);
353
354
66380
	return (1);
355
67592
}
356
357
static int
358
tls1_generate_key_block(SSL *s, unsigned char *km, int num)
359
{
360
32126
	if (num < 0)
361
		return (0);
362
363
16063
	return tls1_PRF(s,
364
16063
	    s->session->master_key, s->session->master_key_length,
365
	    TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
366
16063
	    s->s3->server_random, SSL3_RANDOM_SIZE,
367
16063
	    s->s3->client_random, SSL3_RANDOM_SIZE,
368
16063
	    NULL, 0, NULL, 0, km, num);
369
16063
}
370
371
/*
372
 * tls1_aead_ctx_init allocates aead_ctx, if needed. It returns 1 on success
373
 * and 0 on failure.
374
 */
375
static int
376
tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
377
{
378
63268
	if (*aead_ctx != NULL) {
379
		EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
380
		return (1);
381
	}
382
383
31634
	*aead_ctx = malloc(sizeof(SSL_AEAD_CTX));
384
31634
	if (*aead_ctx == NULL) {
385
		SSLerrorx(ERR_R_MALLOC_FAILURE);
386
		return (0);
387
	}
388
389
31634
	return (1);
390
31634
}
391
392
static int
393
tls1_change_cipher_state_aead(SSL *s, char is_read, const unsigned char *key,
394
    unsigned key_len, const unsigned char *iv, unsigned iv_len)
395
{
396
63268
	const EVP_AEAD *aead = S3I(s)->tmp.new_aead;
397
	SSL_AEAD_CTX *aead_ctx;
398
399
31634
	if (is_read) {
400
15817
		if (!tls1_aead_ctx_init(&s->internal->aead_read_ctx))
401
			return 0;
402
15817
		aead_ctx = s->internal->aead_read_ctx;
403
15817
	} else {
404
15817
		if (!tls1_aead_ctx_init(&s->internal->aead_write_ctx))
405
			return 0;
406
15817
		aead_ctx = s->internal->aead_write_ctx;
407
	}
408
409
31634
	if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
410
	    EVP_AEAD_DEFAULT_TAG_LENGTH, NULL))
411
		return (0);
412
31634
	if (iv_len > sizeof(aead_ctx->fixed_nonce)) {
413
		SSLerrorx(ERR_R_INTERNAL_ERROR);
414
		return (0);
415
	}
416
31634
	memcpy(aead_ctx->fixed_nonce, iv, iv_len);
417
31634
	aead_ctx->fixed_nonce_len = iv_len;
418
31634
	aead_ctx->variable_nonce_len = 8;  /* always the case, currently. */
419
31634
	aead_ctx->variable_nonce_in_record =
420
63268
	    (S3I(s)->hs.new_cipher->algorithm2 &
421
31634
	    SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_IN_RECORD) != 0;
422
31634
	aead_ctx->xor_fixed_nonce =
423
31634
	    S3I(s)->hs.new_cipher->algorithm_enc == SSL_CHACHA20POLY1305;
424
31634
	aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
425
426
31634
	if (aead_ctx->xor_fixed_nonce) {
427

48
		if (aead_ctx->fixed_nonce_len != EVP_AEAD_nonce_length(aead) ||
428
24
		    aead_ctx->variable_nonce_len > EVP_AEAD_nonce_length(aead)) {
429
			SSLerrorx(ERR_R_INTERNAL_ERROR);
430
			return (0);
431
		}
432
	} else {
433
63220
		if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len !=
434
31610
		    EVP_AEAD_nonce_length(aead)) {
435
			SSLerrorx(ERR_R_INTERNAL_ERROR);
436
			return (0);
437
		}
438
	}
439
440
31634
	return (1);
441
31634
}
442
443
/*
444
 * tls1_change_cipher_state_cipher performs the work needed to switch cipher
445
 * states when using EVP_CIPHER. The argument is_read is true iff this function
446
 * is being called due to reading, as opposed to writing, a ChangeCipherSpec
447
 * message. In order to support export ciphersuites, use_client_keys indicates
448
 * whether the key material provided is in the "client write" direction.
449
 */
450
static int
451
tls1_change_cipher_state_cipher(SSL *s, char is_read, char use_client_keys,
452
    const unsigned char *mac_secret, unsigned int mac_secret_size,
453
    const unsigned char *key, unsigned int key_len, const unsigned char *iv,
454
    unsigned int iv_len)
455
{
456
	EVP_CIPHER_CTX *cipher_ctx;
457
	const EVP_CIPHER *cipher;
458
	EVP_MD_CTX *mac_ctx;
459
	const EVP_MD *mac;
460
	int mac_type;
461
462
984
	cipher = S3I(s)->tmp.new_sym_enc;
463
492
	mac = S3I(s)->tmp.new_hash;
464
492
	mac_type = S3I(s)->tmp.new_mac_pkey_type;
465
466
492
	if (is_read) {
467
246
		if (S3I(s)->hs.new_cipher->algorithm2 & TLS1_STREAM_MAC)
468
246
			s->internal->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
469
		else
470
246
			s->internal->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
471
472
246
		EVP_CIPHER_CTX_free(s->enc_read_ctx);
473
246
		s->enc_read_ctx = NULL;
474
246
		EVP_MD_CTX_destroy(s->read_hash);
475
246
		s->read_hash = NULL;
476
477
246
		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
478
			goto err;
479
246
		s->enc_read_ctx = cipher_ctx;
480
246
		if ((mac_ctx = EVP_MD_CTX_create()) == NULL)
481
			goto err;
482
246
		s->read_hash = mac_ctx;
483
246
	} else {
484
246
		if (S3I(s)->hs.new_cipher->algorithm2 & TLS1_STREAM_MAC)
485
246
			s->internal->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
486
		else
487
246
			s->internal->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
488
489
		/*
490
		 * DTLS fragments retain a pointer to the compression, cipher
491
		 * and hash contexts, so that it can restore state in order
492
		 * to perform retransmissions. As such, we cannot free write
493
		 * contexts that are used for DTLS - these are instead freed
494
		 * by DTLS when its frees a ChangeCipherSpec fragment.
495
		 */
496
246
		if (!SSL_IS_DTLS(s)) {
497
174
			EVP_CIPHER_CTX_free(s->internal->enc_write_ctx);
498
174
			s->internal->enc_write_ctx = NULL;
499
174
			EVP_MD_CTX_destroy(s->internal->write_hash);
500
174
			s->internal->write_hash = NULL;
501
174
		}
502
246
		if ((cipher_ctx = EVP_CIPHER_CTX_new()) == NULL)
503
			goto err;
504
246
		s->internal->enc_write_ctx = cipher_ctx;
505
246
		if ((mac_ctx = EVP_MD_CTX_create()) == NULL)
506
			goto err;
507
246
		s->internal->write_hash = mac_ctx;
508
	}
509
510
492
	if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE) {
511
		EVP_CipherInit_ex(cipher_ctx, cipher, NULL, key, NULL,
512
		    !is_read);
513
		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GCM_SET_IV_FIXED,
514
		    iv_len, (unsigned char *)iv);
515
	} else
516
492
		EVP_CipherInit_ex(cipher_ctx, cipher, NULL, key, iv, !is_read);
517
518
492
	if (!(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
519
276
		EVP_PKEY *mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
520
		    mac_secret, mac_secret_size);
521
276
		if (mac_key == NULL)
522
			goto err;
523
276
		EVP_DigestSignInit(mac_ctx, NULL, mac, NULL, mac_key);
524
276
		EVP_PKEY_free(mac_key);
525

492
	} else if (mac_secret_size > 0) {
526
		/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
527
216
		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
528
		    mac_secret_size, (unsigned char *)mac_secret);
529
216
	}
530
531
492
	if (S3I(s)->hs.new_cipher->algorithm_enc == SSL_eGOST2814789CNT) {
532
		int nid;
533
		if (S3I(s)->hs.new_cipher->algorithm2 & SSL_HANDSHAKE_MAC_GOST94)
534
			nid = NID_id_Gost28147_89_CryptoPro_A_ParamSet;
535
		else
536
			nid = NID_id_tc26_gost_28147_param_Z;
537
538
		EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GOST_SET_SBOX, nid, 0);
539
		if (S3I(s)->hs.new_cipher->algorithm_mac == SSL_GOST89MAC)
540
			EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_GOST_SET_SBOX, nid, 0);
541
	}
542
543
492
	return (1);
544
545
err:
546
	SSLerrorx(ERR_R_MALLOC_FAILURE);
547
	return (0);
548
492
}
549
550
int
551
tls1_change_cipher_state(SSL *s, int which)
552
{
553
	const unsigned char *client_write_mac_secret, *server_write_mac_secret;
554
	const unsigned char *client_write_key, *server_write_key;
555
	const unsigned char *client_write_iv, *server_write_iv;
556
	const unsigned char *mac_secret, *key, *iv;
557
	int mac_secret_size, key_len, iv_len;
558
	unsigned char *key_block, *seq;
559
	const EVP_CIPHER *cipher;
560
	const EVP_AEAD *aead;
561
	char is_read, use_client_keys;
562
563
564
64252
	cipher = S3I(s)->tmp.new_sym_enc;
565
32126
	aead = S3I(s)->tmp.new_aead;
566
567
	/*
568
	 * is_read is true if we have just read a ChangeCipherSpec message,
569
	 * that is we need to update the read cipherspec. Otherwise we have
570
	 * just written one.
571
	 */
572
32126
	is_read = (which & SSL3_CC_READ) != 0;
573
574
	/*
575
	 * use_client_keys is true if we wish to use the keys for the "client
576
	 * write" direction. This is the case if we're a client sending a
577
	 * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec.
578
	 */
579
64252
	use_client_keys = ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
580
32126
	    (which == SSL3_CHANGE_CIPHER_SERVER_READ));
581
582
583
	/*
584
	 * Reset sequence number to zero - for DTLS this is handled in
585
	 * dtls1_reset_seq_numbers().
586
	 */
587
32126
	if (!SSL_IS_DTLS(s)) {
588
31982
		seq = is_read ? S3I(s)->read_sequence : S3I(s)->write_sequence;
589
31982
		memset(seq, 0, SSL3_SEQUENCE_SIZE);
590
31982
	}
591
592
32126
	if (aead != NULL) {
593
31634
		key_len = EVP_AEAD_key_length(aead);
594
31634
		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(S3I(s)->hs.new_cipher);
595
31634
	} else {
596
492
		key_len = EVP_CIPHER_key_length(cipher);
597
492
		iv_len = EVP_CIPHER_iv_length(cipher);
598
599
		/* If GCM mode only part of IV comes from PRF. */
600
492
		if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
601
			iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
602
	}
603
604
32126
	mac_secret_size = s->s3->tmp.new_mac_secret_size;
605
606
32126
	key_block = S3I(s)->hs.key_block;
607
	client_write_mac_secret = key_block;
608
32126
	key_block += mac_secret_size;
609
	server_write_mac_secret = key_block;
610
32126
	key_block += mac_secret_size;
611
	client_write_key = key_block;
612
32126
	key_block += key_len;
613
	server_write_key = key_block;
614
32126
	key_block += key_len;
615
	client_write_iv = key_block;
616
32126
	key_block += iv_len;
617
	server_write_iv = key_block;
618
32126
	key_block += iv_len;
619
620
32126
	if (use_client_keys) {
621
		mac_secret = client_write_mac_secret;
622
		key = client_write_key;
623
		iv = client_write_iv;
624
16063
	} else {
625
		mac_secret = server_write_mac_secret;
626
		key = server_write_key;
627
		iv = server_write_iv;
628
	}
629
630
32126
	if (key_block - S3I(s)->hs.key_block != S3I(s)->hs.key_block_len) {
631
		SSLerror(s, ERR_R_INTERNAL_ERROR);
632
		goto err2;
633
	}
634
635
32126
	if (is_read) {
636
16063
		memcpy(S3I(s)->read_mac_secret, mac_secret, mac_secret_size);
637
16063
		S3I(s)->read_mac_secret_size = mac_secret_size;
638
16063
	} else {
639
16063
		memcpy(S3I(s)->write_mac_secret, mac_secret, mac_secret_size);
640
16063
		S3I(s)->write_mac_secret_size = mac_secret_size;
641
	}
642
643
32126
	if (aead != NULL) {
644
31634
		return tls1_change_cipher_state_aead(s, is_read, key, key_len,
645
		    iv, iv_len);
646
	}
647
648
492
	return tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
649
	    mac_secret, mac_secret_size, key, key_len, iv, iv_len);
650
651
err2:
652
	return (0);
653
32126
}
654
655
int
656
tls1_setup_key_block(SSL *s)
657
{
658
	unsigned char *key_block;
659
61652
	int mac_type = NID_undef, mac_secret_size = 0;
660
	int key_block_len, key_len, iv_len;
661
30826
	const EVP_CIPHER *cipher = NULL;
662
30826
	const EVP_AEAD *aead = NULL;
663
30826
	const EVP_MD *mac = NULL;
664
	int ret = 0;
665
666
30826
	if (S3I(s)->hs.key_block_len != 0)
667
14763
		return (1);
668
669

32126
	if (s->session->cipher &&
670
16063
	    (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD)) {
671
15817
		if (!ssl_cipher_get_evp_aead(s->session, &aead)) {
672
			SSLerror(s, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
673
			return (0);
674
		}
675
15817
		key_len = EVP_AEAD_key_length(aead);
676
15817
		iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
677
15817
	} else {
678
246
		if (!ssl_cipher_get_evp(s->session, &cipher, &mac, &mac_type,
679
		    &mac_secret_size)) {
680
			SSLerror(s, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
681
			return (0);
682
		}
683
246
		key_len = EVP_CIPHER_key_length(cipher);
684
246
		iv_len = EVP_CIPHER_iv_length(cipher);
685
686
		/* If GCM mode only part of IV comes from PRF. */
687
246
		if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
688
			iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
689
	}
690
691
16063
	S3I(s)->tmp.new_aead = aead;
692
16063
	S3I(s)->tmp.new_sym_enc = cipher;
693
16063
	S3I(s)->tmp.new_hash = mac;
694
16063
	S3I(s)->tmp.new_mac_pkey_type = mac_type;
695
16063
	s->s3->tmp.new_mac_secret_size = mac_secret_size;
696
697
16063
	tls1_cleanup_key_block(s);
698
699
32126
	if ((key_block = reallocarray(NULL, mac_secret_size + key_len + iv_len,
700
16063
	    2)) == NULL) {
701
		SSLerror(s, ERR_R_MALLOC_FAILURE);
702
		goto err;
703
	}
704
16063
	key_block_len = (mac_secret_size + key_len + iv_len) * 2;
705
706
16063
	S3I(s)->hs.key_block_len = key_block_len;
707
16063
	S3I(s)->hs.key_block = key_block;
708
709
16063
	if (!tls1_generate_key_block(s, key_block, key_block_len))
710
		goto err;
711
712

32126
	if (!(s->internal->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) &&
713
16063
	    s->method->internal->version <= TLS1_VERSION) {
714
		/*
715
		 * Enable vulnerability countermeasure for CBC ciphers with
716
		 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
717
		 */
718
108
		S3I(s)->need_empty_fragments = 1;
719
720
108
		if (s->session->cipher != NULL) {
721
108
			if (s->session->cipher->algorithm_enc == SSL_eNULL)
722
				S3I(s)->need_empty_fragments = 0;
723
724
#ifndef OPENSSL_NO_RC4
725
108
			if (s->session->cipher->algorithm_enc == SSL_RC4)
726
				S3I(s)->need_empty_fragments = 0;
727
#endif
728
		}
729
	}
730
731
16063
	ret = 1;
732
733
 err:
734
16063
	return (ret);
735
30826
}
736
737
/* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
738
 *
739
 * Returns:
740
 *   0: (in non-constant time) if the record is publically invalid (i.e. too
741
 *       short etc).
742
 *   1: if the record's padding is valid / the encryption was successful.
743
 *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
744
 *       an internal error occured.
745
 */
746
int
747
tls1_enc(SSL *s, int send)
748
{
749
	const SSL_AEAD_CTX *aead;
750
	const EVP_CIPHER *enc;
751
	EVP_CIPHER_CTX *ds;
752
	SSL3_RECORD *rec;
753
	unsigned char *seq;
754
	unsigned long l;
755
	int bs, i, j, k, pad = 0, ret, mac_size = 0;
756
757
208352
	if (send) {
758
50607
		aead = s->internal->aead_write_ctx;
759
50607
		rec = &S3I(s)->wrec;
760
50607
		seq = S3I(s)->write_sequence;
761
50607
	} else {
762
53569
		aead = s->internal->aead_read_ctx;
763
53569
		rec = &S3I(s)->rrec;
764
53569
		seq = S3I(s)->read_sequence;
765
	}
766
767
104176
	if (aead) {
768
32002
		unsigned char ad[13], *in, *out, nonce[16];
769
32002
		size_t out_len, pad_len = 0;
770
		unsigned int nonce_used;
771
772
32002
		if (SSL_IS_DTLS(s)) {
773
			dtls1_build_sequence_number(ad, seq,
774
			    send ? D1I(s)->w_epoch : D1I(s)->r_epoch);
775
		} else {
776
32002
			memcpy(ad, seq, SSL3_SEQUENCE_SIZE);
777
32002
			tls1_record_sequence_increment(seq);
778
		}
779
780
32002
		ad[8] = rec->type;
781
32002
		ad[9] = (unsigned char)(s->version >> 8);
782
32002
		ad[10] = (unsigned char)(s->version);
783
784

64004
		if (aead->variable_nonce_len > 8 ||
785
32002
		    aead->variable_nonce_len > sizeof(nonce))
786
			return -1;
787
788
32002
		if (aead->xor_fixed_nonce) {
789

120
			if (aead->fixed_nonce_len > sizeof(nonce) ||
790
60
			    aead->variable_nonce_len > aead->fixed_nonce_len)
791
				return -1;  /* Should never happen. */
792
60
			pad_len = aead->fixed_nonce_len - aead->variable_nonce_len;
793
60
		} else {
794
63884
			if (aead->fixed_nonce_len +
795
31942
			    aead->variable_nonce_len > sizeof(nonce))
796
				return -1;  /* Should never happen. */
797
		}
798
799
32002
		if (send) {
800
16071
			size_t len = rec->length;
801
			size_t eivlen = 0;
802
16071
			in = rec->input;
803
16071
			out = rec->data;
804
805
16071
			if (aead->xor_fixed_nonce) {
806
				/*
807
				 * The sequence number is left zero
808
				 * padded, then xored with the fixed
809
				 * nonce.
810
				 */
811
36
				memset(nonce, 0, pad_len);
812
72
				memcpy(nonce + pad_len, ad,
813
36
				    aead->variable_nonce_len);
814
936
				for (i = 0; i < aead->fixed_nonce_len; i++)
815
432
					nonce[i] ^= aead->fixed_nonce[i];
816
				nonce_used = aead->fixed_nonce_len;
817
36
			} else {
818
				/*
819
				 * When sending we use the sequence number as
820
				 * the variable part of the nonce.
821
				 */
822
32070
				memcpy(nonce, aead->fixed_nonce,
823
16035
				    aead->fixed_nonce_len);
824
16035
				nonce_used = aead->fixed_nonce_len;
825
32070
				memcpy(nonce + nonce_used, ad,
826
16035
				    aead->variable_nonce_len);
827
16035
				nonce_used += aead->variable_nonce_len;
828
			}
829
830
			/*
831
			 * In do_ssl3_write, rec->input is moved forward by
832
			 * variable_nonce_len in order to leave space for the
833
			 * variable nonce. Thus we can copy the sequence number
834
			 * bytes into place without overwriting any of the
835
			 * plaintext.
836
			 */
837
16071
			if (aead->variable_nonce_in_record) {
838
16035
				memcpy(out, ad, aead->variable_nonce_len);
839
16035
				len -= aead->variable_nonce_len;
840
				eivlen = aead->variable_nonce_len;
841
16035
			}
842
843
16071
			ad[11] = len >> 8;
844
16071
			ad[12] = len & 0xff;
845
846
32142
			if (!EVP_AEAD_CTX_seal(&aead->ctx,
847
16071
			    out + eivlen, &out_len, len + aead->tag_len, nonce,
848
16071
			    nonce_used, in + eivlen, len, ad, sizeof(ad)))
849
				return -1;
850
16071
			if (aead->variable_nonce_in_record)
851
16035
				out_len += aead->variable_nonce_len;
852
16071
		} else {
853
			/* receive */
854
15931
			size_t len = rec->length;
855
856
15931
			if (rec->data != rec->input)
857
				return -1;  /* internal error - should never happen. */
858
			out = in = rec->input;
859
860
15931
			if (len < aead->variable_nonce_len)
861
				return 0;
862
863
15931
			if (aead->xor_fixed_nonce) {
864
				/*
865
				 * The sequence number is left zero
866
				 * padded, then xored with the fixed
867
				 * nonce.
868
				 */
869
24
				memset(nonce, 0, pad_len);
870
48
				memcpy(nonce + pad_len, ad,
871
24
				    aead->variable_nonce_len);
872
624
				for (i = 0; i < aead->fixed_nonce_len; i++)
873
288
					nonce[i] ^= aead->fixed_nonce[i];
874
				nonce_used = aead->fixed_nonce_len;
875
24
			} else {
876
31814
				memcpy(nonce, aead->fixed_nonce,
877
15907
				    aead->fixed_nonce_len);
878
15907
				nonce_used = aead->fixed_nonce_len;
879
880
31814
				memcpy(nonce + nonce_used,
881
15907
				    aead->variable_nonce_in_record ? in : ad,
882
15907
				    aead->variable_nonce_len);
883
15907
				nonce_used += aead->variable_nonce_len;
884
			}
885
886
15931
			if (aead->variable_nonce_in_record) {
887
15907
				in += aead->variable_nonce_len;
888
15907
				len -= aead->variable_nonce_len;
889
				out += aead->variable_nonce_len;
890
15907
			}
891
892
15931
			if (len < aead->tag_len)
893
				return 0;
894
15931
			len -= aead->tag_len;
895
896
15931
			ad[11] = len >> 8;
897
15931
			ad[12] = len & 0xff;
898
899
31862
			if (!EVP_AEAD_CTX_open(&aead->ctx, out, &out_len, len,
900
15931
			    nonce, nonce_used, in, len + aead->tag_len, ad,
901
			    sizeof(ad)))
902
				return -1;
903
904
15931
			rec->data = rec->input = out;
905
15931
		}
906
907
32002
		rec->length = out_len;
908
909
32002
		return 1;
910
32002
	}
911
912
72174
	if (send) {
913
34536
		if (EVP_MD_CTX_md(s->internal->write_hash)) {
914
198
			int n = EVP_MD_CTX_size(s->internal->write_hash);
915
198
			OPENSSL_assert(n >= 0);
916
198
		}
917
34536
		ds = s->internal->enc_write_ctx;
918
34536
		if (s->internal->enc_write_ctx == NULL)
919
33906
			enc = NULL;
920
		else {
921
			int ivlen = 0;
922
630
			enc = EVP_CIPHER_CTX_cipher(s->internal->enc_write_ctx);
923

828
			if (SSL_USE_EXPLICIT_IV(s) &&
924
198
			    EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
925
180
				ivlen = EVP_CIPHER_iv_length(enc);
926
630
			if (ivlen > 1) {
927
180
				if (rec->data != rec->input) {
928
#ifdef DEBUG
929
					/* we can't write into the input stream:
930
					 * Can this ever happen?? (steve)
931
					 */
932
					fprintf(stderr,
933
					    "%s:%d: rec->data != rec->input\n",
934
					    __FILE__, __LINE__);
935
#endif
936
				} else
937
180
					arc4random_buf(rec->input, ivlen);
938
			}
939
		}
940
	} else {
941
37638
		if (EVP_MD_CTX_md(s->read_hash)) {
942
132
			int n = EVP_MD_CTX_size(s->read_hash);
943
132
			OPENSSL_assert(n >= 0);
944
132
		}
945
37638
		ds = s->enc_read_ctx;
946
37638
		if (s->enc_read_ctx == NULL)
947
37182
			enc = NULL;
948
		else
949
456
			enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
950
	}
951
952
72174
	if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
953
71088
		memmove(rec->data, rec->input, rec->length);
954
71088
		rec->input = rec->data;
955
		ret = 1;
956
71088
	} else {
957
1086
		l = rec->length;
958
1086
		bs = EVP_CIPHER_block_size(ds->cipher);
959
960
1086
		if (EVP_CIPHER_flags(ds->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
961
756
			unsigned char buf[13];
962
963
756
			if (SSL_IS_DTLS(s)) {
964
				dtls1_build_sequence_number(buf, seq,
965
				    send ? D1I(s)->w_epoch : D1I(s)->r_epoch);
966
			} else {
967
756
				memcpy(buf, seq, SSL3_SEQUENCE_SIZE);
968
756
				tls1_record_sequence_increment(seq);
969
			}
970
971
756
			buf[8] = rec->type;
972
756
			buf[9] = (unsigned char)(s->version >> 8);
973
756
			buf[10] = (unsigned char)(s->version);
974
756
			buf[11] = rec->length >> 8;
975
756
			buf[12] = rec->length & 0xff;
976
756
			pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD, 13, buf);
977
756
			if (send) {
978
432
				l += pad;
979
432
				rec->length += pad;
980
432
			}
981
1086
		} else if ((bs != 1) && send) {
982
180
			i = bs - ((int)l % bs);
983
984
			/* Add weird padding of upto 256 bytes */
985
986
			/* we need to add 'i' padding bytes of value j */
987
180
			j = i - 1;
988
5880
			for (k = (int)l; k < (int)(l + i); k++)
989
2760
				rec->input[k] = j;
990
			l += i;
991
180
			rec->length += i;
992
180
		}
993
994
1086
		if (!send) {
995

912
			if (l == 0 || l % bs != 0)
996
				return 0;
997
		}
998
999
1086
		i = EVP_Cipher(ds, rec->data, rec->input, l);
1000

2172
		if ((EVP_CIPHER_flags(ds->cipher) &
1001
1086
		    EVP_CIPH_FLAG_CUSTOM_CIPHER) ? (i < 0) : (i == 0))
1002
			return -1;	/* AEAD can fail to verify MAC */
1003
1086
		if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send) {
1004
			rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1005
			rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1006
			rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1007
		}
1008
1009
		ret = 1;
1010
1086
		if (EVP_MD_CTX_md(s->read_hash) != NULL)
1011
297
			mac_size = EVP_MD_CTX_size(s->read_hash);
1012
1086
		if ((bs != 1) && !send)
1013
444
			ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
1014
1086
		if (pad && !send)
1015
324
			rec->length -= pad;
1016
	}
1017
72174
	return ret;
1018
104176
}
1019
1020
int
1021
tls1_final_finish_mac(SSL *s, const char *str, int str_len, unsigned char *out)
1022
{
1023
96234
	unsigned char buf[EVP_MAX_MD_SIZE];
1024
48117
	size_t hash_len;
1025
1026
48117
	if (str_len < 0)
1027
		return 0;
1028
1029
48117
	if (!tls1_handshake_hash_value(s, buf, sizeof(buf), &hash_len))
1030
		return 0;
1031
1032
96234
	if (!tls1_PRF(s, s->session->master_key, s->session->master_key_length,
1033
48117
	    str, str_len, buf, hash_len, NULL, 0, NULL, 0, NULL, 0,
1034
	    out, TLS1_FINISH_MAC_LENGTH))
1035
		return 0;
1036
1037
48117
	return TLS1_FINISH_MAC_LENGTH;
1038
48117
}
1039
1040
int
1041
tls1_mac(SSL *ssl, unsigned char *md, int send)
1042
{
1043
	SSL3_RECORD *rec;
1044
	unsigned char *seq;
1045
	EVP_MD_CTX *hash;
1046
1380
	size_t md_size, orig_len;
1047
690
	EVP_MD_CTX hmac, *mac_ctx;
1048
690
	unsigned char header[13];
1049
690
	int stream_mac = (send ?
1050
	    (ssl->internal->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM) :
1051
	    (ssl->internal->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1052
	int t;
1053
1054
690
	if (send) {
1055
414
		rec = &(ssl->s3->internal->wrec);
1056
414
		seq = &(ssl->s3->internal->write_sequence[0]);
1057
414
		hash = ssl->internal->write_hash;
1058
414
	} else {
1059
276
		rec = &(ssl->s3->internal->rrec);
1060
276
		seq = &(ssl->s3->internal->read_sequence[0]);
1061
276
		hash = ssl->read_hash;
1062
	}
1063
1064
690
	t = EVP_MD_CTX_size(hash);
1065
690
	OPENSSL_assert(t >= 0);
1066
690
	md_size = t;
1067
1068
	/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1069
690
	if (stream_mac) {
1070
		mac_ctx = hash;
1071
	} else {
1072
690
		if (!EVP_MD_CTX_copy(&hmac, hash))
1073
			return -1;
1074
		mac_ctx = &hmac;
1075
	}
1076
1077
690
	if (SSL_IS_DTLS(ssl))
1078
360
		dtls1_build_sequence_number(header, seq,
1079
720
		    send ? D1I(ssl)->w_epoch : D1I(ssl)->r_epoch);
1080
	else
1081
330
		memcpy(header, seq, SSL3_SEQUENCE_SIZE);
1082
1083
	/* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1084
690
	orig_len = rec->length + md_size + ((unsigned int)rec->type >> 8);
1085
690
	rec->type &= 0xff;
1086
1087
690
	header[8] = rec->type;
1088
690
	header[9] = (unsigned char)(ssl->version >> 8);
1089
690
	header[10] = (unsigned char)(ssl->version);
1090
690
	header[11] = (rec->length) >> 8;
1091
690
	header[12] = (rec->length) & 0xff;
1092
1093

930
	if (!send &&
1094
276
	    EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1095
240
	    ssl3_cbc_record_digest_supported(mac_ctx)) {
1096
		/* This is a CBC-encrypted record. We must avoid leaking any
1097
		 * timing-side channel information about how many blocks of
1098
		 * data we are hashing because that gives an attacker a
1099
		 * timing-oracle. */
1100
240
		if (!ssl3_cbc_digest_record(mac_ctx,
1101
240
		    md, &md_size, header, rec->input,
1102
240
		    rec->length + md_size, orig_len,
1103
240
		    ssl->s3->internal->read_mac_secret,
1104
240
		    ssl->s3->internal->read_mac_secret_size))
1105
			return -1;
1106
	} else {
1107
450
		EVP_DigestSignUpdate(mac_ctx, header, sizeof(header));
1108
450
		EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length);
1109
450
		t = EVP_DigestSignFinal(mac_ctx, md, &md_size);
1110
450
		OPENSSL_assert(t > 0);
1111
	}
1112
1113
690
	if (!stream_mac)
1114
690
		EVP_MD_CTX_cleanup(&hmac);
1115
1116
690
	if (!SSL_IS_DTLS(ssl))
1117
330
		tls1_record_sequence_increment(seq);
1118
1119
690
	return (md_size);
1120
690
}
1121
1122
int
1123
tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1124
    int len)
1125
{
1126
2984
	if (len < 0)
1127
		return 0;
1128
1129
2984
	if (!tls1_PRF(s, p, len,
1130
	    TLS_MD_MASTER_SECRET_CONST, TLS_MD_MASTER_SECRET_CONST_SIZE,
1131
1492
	    s->s3->client_random, SSL3_RANDOM_SIZE, NULL, 0,
1132
1492
	    s->s3->server_random, SSL3_RANDOM_SIZE, NULL, 0,
1133
1492
	    s->session->master_key, SSL_MAX_MASTER_KEY_LENGTH))
1134
		return 0;
1135
1136
1492
	return (SSL_MAX_MASTER_KEY_LENGTH);
1137
1492
}
1138
1139
int
1140
tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1141
    const char *label, size_t llen, const unsigned char *context,
1142
    size_t contextlen, int use_context)
1143
{
1144
	unsigned char *val = NULL;
1145
	size_t vallen, currentvalpos;
1146
	int rv;
1147
1148
	/* construct PRF arguments
1149
	 * we construct the PRF argument ourself rather than passing separate
1150
	 * values into the TLS PRF to ensure that the concatenation of values
1151
	 * does not create a prohibited label.
1152
	 */
1153
	vallen = llen + SSL3_RANDOM_SIZE * 2;
1154
	if (use_context) {
1155
		vallen += 2 + contextlen;
1156
	}
1157
1158
	val = malloc(vallen);
1159
	if (val == NULL)
1160
		goto err2;
1161
	currentvalpos = 0;
1162
	memcpy(val + currentvalpos, (unsigned char *) label, llen);
1163
	currentvalpos += llen;
1164
	memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1165
	currentvalpos += SSL3_RANDOM_SIZE;
1166
	memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1167
	currentvalpos += SSL3_RANDOM_SIZE;
1168
1169
	if (use_context) {
1170
		val[currentvalpos] = (contextlen >> 8) & 0xff;
1171
		currentvalpos++;
1172
		val[currentvalpos] = contextlen & 0xff;
1173
		currentvalpos++;
1174
		if ((contextlen > 0) || (context != NULL)) {
1175
			memcpy(val + currentvalpos, context, contextlen);
1176
		}
1177
	}
1178
1179
	/* disallow prohibited labels
1180
	 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1181
	 * 15, so size of val > max(prohibited label len) = 15 and the
1182
	 * comparisons won't have buffer overflow
1183
	 */
1184
	if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1185
	    TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
1186
		goto err1;
1187
	if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1188
	    TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
1189
		goto err1;
1190
	if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1191
	    TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
1192
		goto err1;
1193
	if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1194
	    TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
1195
		goto err1;
1196
1197
	rv = tls1_PRF(s, s->session->master_key, s->session->master_key_length,
1198
	    val, vallen, NULL, 0, NULL, 0, NULL, 0, NULL, 0, out, olen);
1199
1200
	goto ret;
1201
err1:
1202
	SSLerror(s, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1203
	rv = 0;
1204
	goto ret;
1205
err2:
1206
	SSLerror(s, ERR_R_MALLOC_FAILURE);
1207
	rv = 0;
1208
ret:
1209
	free(val);
1210
1211
	return (rv);
1212
}
1213
1214
int
1215
tls1_alert_code(int code)
1216
{
1217








772
	switch (code) {
1218
	case SSL_AD_CLOSE_NOTIFY:
1219
386
		return (SSL3_AD_CLOSE_NOTIFY);
1220
	case SSL_AD_UNEXPECTED_MESSAGE:
1221
		return (SSL3_AD_UNEXPECTED_MESSAGE);
1222
	case SSL_AD_BAD_RECORD_MAC:
1223
		return (SSL3_AD_BAD_RECORD_MAC);
1224
	case SSL_AD_DECRYPTION_FAILED:
1225
		return (TLS1_AD_DECRYPTION_FAILED);
1226
	case SSL_AD_RECORD_OVERFLOW:
1227
		return (TLS1_AD_RECORD_OVERFLOW);
1228
	case SSL_AD_DECOMPRESSION_FAILURE:
1229
		return (SSL3_AD_DECOMPRESSION_FAILURE);
1230
	case SSL_AD_HANDSHAKE_FAILURE:
1231
		return (SSL3_AD_HANDSHAKE_FAILURE);
1232
	case SSL_AD_NO_CERTIFICATE:
1233
		return (-1);
1234
	case SSL_AD_BAD_CERTIFICATE:
1235
		return (SSL3_AD_BAD_CERTIFICATE);
1236
	case SSL_AD_UNSUPPORTED_CERTIFICATE:
1237
		return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
1238
	case SSL_AD_CERTIFICATE_REVOKED:
1239
		return (SSL3_AD_CERTIFICATE_REVOKED);
1240
	case SSL_AD_CERTIFICATE_EXPIRED:
1241
		return (SSL3_AD_CERTIFICATE_EXPIRED);
1242
	case SSL_AD_CERTIFICATE_UNKNOWN:
1243
		return (SSL3_AD_CERTIFICATE_UNKNOWN);
1244
	case SSL_AD_ILLEGAL_PARAMETER:
1245
		return (SSL3_AD_ILLEGAL_PARAMETER);
1246
	case SSL_AD_UNKNOWN_CA:
1247
		return (TLS1_AD_UNKNOWN_CA);
1248
	case SSL_AD_ACCESS_DENIED:
1249
		return (TLS1_AD_ACCESS_DENIED);
1250
	case SSL_AD_DECODE_ERROR:
1251
		return (TLS1_AD_DECODE_ERROR);
1252
	case SSL_AD_DECRYPT_ERROR:
1253
		return (TLS1_AD_DECRYPT_ERROR);
1254
	case SSL_AD_EXPORT_RESTRICTION:
1255
		return (TLS1_AD_EXPORT_RESTRICTION);
1256
	case SSL_AD_PROTOCOL_VERSION:
1257
		return (TLS1_AD_PROTOCOL_VERSION);
1258
	case SSL_AD_INSUFFICIENT_SECURITY:
1259
		return (TLS1_AD_INSUFFICIENT_SECURITY);
1260
	case SSL_AD_INTERNAL_ERROR:
1261
		return (TLS1_AD_INTERNAL_ERROR);
1262
	case SSL_AD_INAPPROPRIATE_FALLBACK:
1263
		return(TLS1_AD_INAPPROPRIATE_FALLBACK);
1264
	case SSL_AD_USER_CANCELLED:
1265
		return (TLS1_AD_USER_CANCELLED);
1266
	case SSL_AD_NO_RENEGOTIATION:
1267
		return (TLS1_AD_NO_RENEGOTIATION);
1268
	case SSL_AD_UNSUPPORTED_EXTENSION:
1269
		return (TLS1_AD_UNSUPPORTED_EXTENSION);
1270
	case SSL_AD_CERTIFICATE_UNOBTAINABLE:
1271
		return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1272
	case SSL_AD_UNRECOGNIZED_NAME:
1273
		return (TLS1_AD_UNRECOGNIZED_NAME);
1274
	case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
1275
		return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1276
	case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
1277
		return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1278
	case SSL_AD_UNKNOWN_PSK_IDENTITY:
1279
		return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
1280
	default:
1281
		return (-1);
1282
	}
1283
386
}