1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
57 /* ====================================================================
58 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in
69 * the documentation and/or other materials provided with the
72 * 3. All advertising materials mentioning features or use of this
73 * software must display the following acknowledgment:
74 * "This product includes software developed by the OpenSSL Project
75 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 * endorse or promote products derived from this software without
79 * prior written permission. For written permission, please contact
80 * openssl-core@openssl.org.
82 * 5. Products derived from this software may not be called "OpenSSL"
83 * nor may "OpenSSL" appear in their names without prior written
84 * permission of the OpenSSL Project.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com). This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com).
110 /* ====================================================================
111 * Copyright 2005 Nokia. All rights reserved.
113 * The portions of the attached software ("Contribution") is developed by
114 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
117 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
118 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
119 * support (see RFC 4279) to OpenSSL.
121 * No patent licenses or other rights except those expressly stated in
122 * the OpenSSL open source license shall be deemed granted or received
123 * expressly, by implication, estoppel, or otherwise.
125 * No assurances are provided by Nokia that the Contribution does not
126 * infringe the patent or other intellectual property rights of any third
127 * party or that the license provides you with all the necessary rights
128 * to make use of the Contribution.
130 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
131 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
132 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
133 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
139 #include <openssl/err.h>
140 #include <openssl/evp.h>
141 #include <openssl/hmac.h>
142 #include <openssl/md5.h>
143 #include <openssl/mem.h>
144 #include <openssl/obj.h>
145 #include <openssl/rand.h>
147 #include "ssl_locl.h"
149 /* seed1 through seed5 are virtually concatenated */
150 static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
152 const void *seed1, int seed1_len,
153 const void *seed2, int seed2_len,
154 const void *seed3, int seed3_len,
155 const void *seed4, int seed4_len,
156 const void *seed5, int seed5_len,
157 unsigned char *out, int olen)
161 EVP_MD_CTX ctx, ctx_tmp, ctx_init;
163 unsigned char A1[EVP_MAX_MD_SIZE];
167 chunk=EVP_MD_size(md);
169 EVP_MD_CTX_init(&ctx);
170 EVP_MD_CTX_init(&ctx_tmp);
171 EVP_MD_CTX_init(&ctx_init);
172 mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
175 if (!EVP_DigestSignInit(&ctx_init,NULL,md, NULL, mac_key))
177 if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
179 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
181 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
183 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
185 if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
187 if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
189 A1_len = EVP_MAX_MD_SIZE;
190 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
195 /* Reinit mac contexts */
196 if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
198 if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
200 if (olen>chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp,&ctx))
202 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
204 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
206 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
208 if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
210 if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
216 if (!EVP_DigestSignFinal(&ctx,out,&j))
220 /* calc the next A1 value */
221 A1_len = EVP_MAX_MD_SIZE;
222 if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
227 A1_len = EVP_MAX_MD_SIZE;
228 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
236 EVP_PKEY_free(mac_key);
237 EVP_MD_CTX_cleanup(&ctx);
238 EVP_MD_CTX_cleanup(&ctx_tmp);
239 EVP_MD_CTX_cleanup(&ctx_init);
240 OPENSSL_cleanse(A1,sizeof(A1));
244 /* seed1 through seed5 are virtually concatenated */
245 static int tls1_PRF(long digest_mask,
246 const void *seed1, int seed1_len,
247 const void *seed2, int seed2_len,
248 const void *seed3, int seed3_len,
249 const void *seed4, int seed4_len,
250 const void *seed5, int seed5_len,
251 const unsigned char *sec, int slen,
253 unsigned char *out2, int olen)
256 const unsigned char *S1;
261 /* Count number of digests and partition sec evenly */
263 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
264 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
271 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
272 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
274 OPENSSL_PUT_ERROR(SSL, tls1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
277 if (!tls1_P_hash(md ,S1,len+(slen&1),
278 seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,seed4,seed4_len,seed5,seed5_len,
282 for (i=0; i<olen; i++)
293 static int tls1_generate_key_block(SSL *s, unsigned char *km,
294 unsigned char *tmp, int num)
297 ret = tls1_PRF(ssl_get_algorithm2(s),
298 TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE,
299 s->s3->server_random,SSL3_RANDOM_SIZE,
300 s->s3->client_random,SSL3_RANDOM_SIZE,
302 s->session->master_key,s->session->master_key_length,
305 printf("tls1_generate_key_block() ==> %d byte master_key =\n\t",
306 s->session->master_key_length);
309 for (i=0; i < s->session->master_key_length; i++)
311 printf("%02X", s->session->master_key[i]);
314 #endif /* KSSL_DEBUG */
318 /* tls1_aead_ctx_init allocates |*aead_ctx|, if needed and returns 1. It
319 * returns 0 on malloc error. */
320 static int tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
322 if (*aead_ctx != NULL)
323 EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
326 *aead_ctx = (SSL_AEAD_CTX*) OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
327 if (*aead_ctx == NULL)
329 OPENSSL_PUT_ERROR(SSL, tls1_aead_ctx_init, ERR_R_MALLOC_FAILURE);
337 static int tls1_change_cipher_state_aead(SSL *s, char is_read,
338 const unsigned char *key, unsigned key_len,
339 const unsigned char *iv, unsigned iv_len,
340 const unsigned char *mac_secret, unsigned mac_secret_len)
342 const EVP_AEAD *aead = s->s3->tmp.new_aead;
343 SSL_AEAD_CTX *aead_ctx;
344 /* mac_key_and_key is used to merge the MAC and cipher keys for an AEAD
345 * which simulates pre-AEAD cipher suites. It needs to be large enough
346 * to cope with the largest pair of keys. */
347 uint8_t mac_key_and_key[32 /* HMAC(SHA256) */ + 32 /* AES-256 */];
349 if (mac_secret_len > 0)
351 /* This is a "stateful" AEAD (for compatibility with pre-AEAD
353 if (mac_secret_len + key_len > sizeof(mac_key_and_key))
355 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
358 memcpy(mac_key_and_key, mac_secret, mac_secret_len);
359 memcpy(mac_key_and_key + mac_secret_len, key, key_len);
360 key = mac_key_and_key;
361 key_len += mac_secret_len;
366 if (!tls1_aead_ctx_init(&s->aead_read_ctx))
368 aead_ctx = s->aead_read_ctx;
372 if (!tls1_aead_ctx_init(&s->aead_write_ctx))
374 aead_ctx = s->aead_write_ctx;
377 if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
378 EVP_AEAD_DEFAULT_TAG_LENGTH, NULL /* engine */))
380 if (iv_len > sizeof(aead_ctx->fixed_nonce))
382 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
385 memcpy(aead_ctx->fixed_nonce, iv, iv_len);
386 aead_ctx->fixed_nonce_len = iv_len;
387 aead_ctx->variable_nonce_len = 8; /* correct for all true AEADs so far. */
388 if (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)
389 aead_ctx->variable_nonce_len = 0;
390 aead_ctx->variable_nonce_included_in_record =
391 (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_INCLUDED_IN_RECORD) != 0;
392 if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len != EVP_AEAD_nonce_length(aead))
394 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
397 aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
402 /* tls1_change_cipher_state_cipher performs the work needed to switch cipher
403 * states when using EVP_CIPHER. The argument |is_read| is true iff this
404 * function is being called due to reading, as opposed to writing, a
405 * ChangeCipherSpec message. In order to support export ciphersuites,
406 * use_client_keys indicates whether the key material provided is in the
407 * "client write" direction. */
408 static int tls1_change_cipher_state_cipher(
409 SSL *s, char is_read, char use_client_keys,
410 const unsigned char *mac_secret, unsigned mac_secret_len,
411 const unsigned char *key, unsigned key_len,
412 const unsigned char *iv, unsigned iv_len)
414 const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
415 EVP_CIPHER_CTX *cipher_ctx;
420 if (s->enc_read_ctx != NULL && !SSL_IS_DTLS(s))
421 EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
422 else if ((s->enc_read_ctx=EVP_CIPHER_CTX_new()) == NULL)
425 cipher_ctx = s->enc_read_ctx;
426 mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
428 memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
429 s->s3->read_mac_secret_size = mac_secret_len;
433 /* When updating the write contexts for DTLS, we do not wish to
434 * free the old ones because DTLS stores pointers to them in
435 * order to implement retransmission. */
437 if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
438 EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
439 else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
442 /* make sure it's intialized in case we exit later with an error */
443 EVP_CIPHER_CTX_init(s->enc_write_ctx);
445 cipher_ctx = s->enc_write_ctx;
448 /* This is the same as ssl_replace_hash, but doesn't
449 * free the old |s->write_hash|. */
450 mac_ctx = EVP_MD_CTX_create();
453 s->write_hash = mac_ctx;
456 mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
458 memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
459 s->s3->write_mac_secret_size = mac_secret_len;
463 EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
464 NULL, mac_secret, mac_secret_len);
467 EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
468 EVP_PKEY_free(mac_key);
470 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
475 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_cipher, ERR_R_MALLOC_FAILURE);
479 int tls1_change_cipher_state(SSL *s, int which)
481 /* is_read is true if we have just read a ChangeCipherSpec message -
482 * i.e. we need to update the read cipherspec. Otherwise we have just
484 const char is_read = (which & SSL3_CC_READ) != 0;
485 /* use_client_keys is true if we wish to use the keys for the "client
486 * write" direction. This is the case if we're a client sending a
487 * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec. */
488 const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
489 which == SSL3_CHANGE_CIPHER_SERVER_READ;
490 const unsigned char *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
491 const unsigned char *client_write_key, *server_write_key, *key;
492 const unsigned char *client_write_iv, *server_write_iv, *iv;
493 const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
494 const EVP_AEAD *aead = s->s3->tmp.new_aead;
495 unsigned key_len, iv_len, mac_secret_len;
496 const unsigned char *key_data;
498 /* Reset sequence number to zero. */
499 if (s->version != DTLS1_VERSION)
500 memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
502 /* key_arg is used for SSLv2. We don't need it for TLS. */
503 s->session->key_arg_length = 0;
505 mac_secret_len = s->s3->tmp.new_mac_secret_size;
509 key_len = EVP_AEAD_key_length(aead);
510 /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
511 * cipher suites) the key length reported by
512 * |EVP_AEAD_key_length| will include the MAC key bytes. */
513 if (key_len < mac_secret_len)
515 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
518 key_len -= mac_secret_len;
519 iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
523 key_len = EVP_CIPHER_key_length(cipher);
525 if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
526 iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
528 iv_len = EVP_CIPHER_iv_length(cipher);
531 key_data = s->s3->tmp.key_block;
532 client_write_mac_secret = key_data; key_data += mac_secret_len;
533 server_write_mac_secret = key_data; key_data += mac_secret_len;
534 client_write_key = key_data; key_data += key_len;
535 server_write_key = key_data; key_data += key_len;
536 client_write_iv = key_data; key_data += iv_len;
537 server_write_iv = key_data; key_data += iv_len;
541 mac_secret = client_write_mac_secret;
542 key = client_write_key;
543 iv = client_write_iv;
547 mac_secret = server_write_mac_secret;
548 key = server_write_key;
549 iv = server_write_iv;
552 if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
554 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
560 if (!tls1_change_cipher_state_aead(s, is_read,
561 key, key_len, iv, iv_len,
562 mac_secret, mac_secret_len))
567 if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
568 mac_secret, mac_secret_len,
577 int tls1_setup_key_block(SSL *s)
579 unsigned char *p1,*p2=NULL;
580 const EVP_CIPHER *c = NULL;
581 const EVP_MD *hash = NULL;
582 const EVP_AEAD *aead = NULL;
584 int mac_type= NID_undef,mac_secret_size=0;
586 unsigned key_len, iv_len;
589 printf ("tls1_setup_key_block()\n");
590 #endif /* KSSL_DEBUG */
592 if (s->s3->tmp.key_block_length != 0)
595 if (s->session->cipher &&
596 ((s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD) ||
597 (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)))
599 if (!ssl_cipher_get_evp_aead(s->session, &aead))
600 goto cipher_unavailable_err;
601 key_len = EVP_AEAD_key_length(aead);
602 iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
603 if (!ssl_cipher_get_mac(s->session, &hash, &mac_type, &mac_secret_size))
604 goto cipher_unavailable_err;
605 /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
606 * cipher suites) the key length reported by
607 * |EVP_AEAD_key_length| will include the MAC key bytes. */
608 if (key_len < mac_secret_size)
610 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
613 key_len -= mac_secret_size;
617 if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size))
618 goto cipher_unavailable_err;
619 key_len = EVP_CIPHER_key_length(c);
621 if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
622 iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
624 iv_len = EVP_CIPHER_iv_length(c);
627 s->s3->tmp.new_aead=aead;
628 s->s3->tmp.new_sym_enc=c;
629 s->s3->tmp.new_hash=hash;
630 s->s3->tmp.new_mac_pkey_type = mac_type;
631 s->s3->tmp.new_mac_secret_size = mac_secret_size;
633 num=key_len+mac_secret_size+iv_len;
636 ssl3_cleanup_key_block(s);
638 if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
640 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
644 s->s3->tmp.key_block_length=num;
645 s->s3->tmp.key_block=p1;
647 if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
649 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
654 printf("client random\n");
655 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
656 printf("server random\n");
657 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
658 printf("pre-master\n");
659 { int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
661 if (!tls1_generate_key_block(s,p1,p2,num))
664 printf("\nkey block\n");
665 { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
668 if (s->method->version <= TLS1_VERSION &&
669 (s->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0)
671 /* enable vulnerability countermeasure for CBC ciphers with
672 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
674 s->s3->need_record_splitting = 1;
676 if (s->session->cipher != NULL)
678 if (s->session->cipher->algorithm_enc == SSL_eNULL)
679 s->s3->need_record_splitting = 0;
681 #ifndef OPENSSL_NO_RC4
682 if (s->session->cipher->algorithm_enc == SSL_RC4)
683 s->s3->need_record_splitting = 0;
692 OPENSSL_cleanse(p2,num);
697 cipher_unavailable_err:
698 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
702 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
705 * 0: (in non-constant time) if the record is publically invalid (i.e. too
707 * 1: if the record's padding is valid / the encryption was successful.
708 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
709 * an internal error occured.
711 int tls1_enc(SSL *s, int send)
716 int bs,i,j,k,pad=0,ret,mac_size=0;
717 const EVP_CIPHER *enc;
718 const SSL_AEAD_CTX *aead;
726 aead = s->aead_write_ctx;
728 aead = s->aead_read_ctx;
732 unsigned char ad[13], *seq, *in, *out, nonce[16];
736 seq = send ? s->s3->write_sequence : s->s3->read_sequence;
738 if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
740 unsigned char dtlsseq[9], *p = dtlsseq;
742 s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
743 memcpy(p, &seq[2], 6);
744 memcpy(ad, dtlsseq, 8);
749 for (i=7; i>=0; i--) /* increment */
758 ad[9] = (unsigned char)(s->version>>8);
759 ad[10] = (unsigned char)(s->version);
761 if (aead->fixed_nonce_len + aead->variable_nonce_len > sizeof(nonce) ||
762 aead->variable_nonce_len > 8)
763 return -1; /* internal error - should never happen. */
765 memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
766 nonce_used = aead->fixed_nonce_len;
770 size_t len = rec->length;
775 /* When sending we use the sequence number as the
776 * variable part of the nonce. */
777 if (aead->variable_nonce_len > 8)
779 memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
780 nonce_used += aead->variable_nonce_len;
782 /* in do_ssl3_write, rec->input is moved forward by
783 * variable_nonce_len in order to leave space for the
784 * variable nonce. Thus we can copy the sequence number
785 * bytes into place without overwriting any of the
787 if (aead->variable_nonce_included_in_record)
789 memcpy(out, ad, aead->variable_nonce_len);
790 len -= aead->variable_nonce_len;
791 eivlen = aead->variable_nonce_len;
797 if (!EVP_AEAD_CTX_seal(
799 out + eivlen, &n, len + aead->tag_len,
806 if (aead->variable_nonce_included_in_record)
807 n += aead->variable_nonce_len;
812 size_t len = rec->length;
814 if (rec->data != rec->input)
815 return -1; /* internal error - should never happen. */
816 out = in = rec->input;
818 if (len < aead->variable_nonce_len)
820 memcpy(nonce + nonce_used,
821 aead->variable_nonce_included_in_record ? in : ad,
822 aead->variable_nonce_len);
823 nonce_used += aead->variable_nonce_len;
825 if (aead->variable_nonce_included_in_record)
827 in += aead->variable_nonce_len;
828 len -= aead->variable_nonce_len;
829 out += aead->variable_nonce_len;
832 if (len < aead->tag_len)
834 len -= aead->tag_len;
839 if (!EVP_AEAD_CTX_open(
843 in, len + aead->tag_len,
849 rec->data = rec->input = out;
860 if (s->enc_write_ctx == NULL)
865 enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
866 /* For TLSv1.1 and later explicit IV */
867 if (SSL_USE_EXPLICIT_IV(s)
868 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
869 ivlen = EVP_CIPHER_iv_length(enc);
874 if ( rec->data != rec->input)
875 /* we can't write into the input stream:
876 * Can this ever happen?? (steve)
879 "%s:%d: rec->data != rec->input\n",
881 else if (RAND_bytes(rec->input, ivlen) <= 0)
890 if (s->enc_read_ctx == NULL)
893 enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
897 printf("tls1_enc(%d)\n", send);
898 #endif /* KSSL_DEBUG */
900 if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
902 memmove(rec->data,rec->input,rec->length);
903 rec->input=rec->data;
909 bs=EVP_CIPHER_block_size(ds->cipher);
911 if ((bs != 1) && send)
915 /* Add weird padding of upto 256 bytes */
917 /* we need to add 'i' padding bytes of value j */
919 if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)
921 if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
924 for (k=(int)l; k<(int)(l+i); k++)
933 printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
934 ds,rec->data,rec->input,l);
935 printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n",
936 ds->buf_len, ds->cipher->key_len,
937 DES_KEY_SZ, DES_SCHEDULE_SZ,
940 for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]);
942 printf("\trec->input=");
943 for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]);
946 #endif /* KSSL_DEBUG */
950 if (l == 0 || l%bs != 0)
954 i = EVP_Cipher(ds,rec->data,rec->input,l);
955 if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
958 return -1; /* AEAD can fail to verify MAC */
959 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send)
961 rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
962 rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
963 rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
969 printf("\trec->data=");
971 printf(" %02x", rec->data[i]); printf("\n");
973 #endif /* KSSL_DEBUG */
976 if (EVP_MD_CTX_md(s->read_hash) != NULL)
977 mac_size = EVP_MD_CTX_size(s->read_hash);
978 if ((bs != 1) && !send)
979 ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
986 int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
989 EVP_MD_CTX ctx, *d=NULL;
992 if (s->s3->handshake_buffer)
993 if (!ssl3_digest_cached_records(s))
996 for (i=0;i<SSL_MAX_DIGEST;i++)
998 if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid)
1000 d=s->s3->handshake_dgst[i];
1005 OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
1009 EVP_MD_CTX_init(&ctx);
1010 EVP_MD_CTX_copy_ex(&ctx,d);
1011 EVP_DigestFinal_ex(&ctx,out,&ret);
1012 EVP_MD_CTX_cleanup(&ctx);
1016 /* tls1_handshake_digest calculates the current handshake hash and writes it to
1017 * |out|, which has space for |out_len| bytes. It returns the number of bytes
1018 * written or -1 in the event of an error. This function works on a copy of the
1019 * underlying digests so can be called multiple times and prior to the final
1021 int tls1_handshake_digest(SSL *s, unsigned char *out, size_t out_len)
1025 int i, err = 0, len = 0;
1028 EVP_MD_CTX_init(&ctx);
1030 for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++)
1033 unsigned int digest_len;
1034 EVP_MD_CTX *hdgst = s->s3->handshake_dgst[i];
1036 if ((mask & ssl_get_algorithm2(s)) == 0)
1039 hash_size = EVP_MD_size(md);
1040 if (!hdgst || hash_size < 0 || (size_t)hash_size > out_len)
1046 if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
1047 !EVP_DigestFinal_ex(&ctx, out, &digest_len) ||
1048 digest_len != (unsigned int)hash_size) /* internal error */
1054 out_len -= digest_len;
1058 EVP_MD_CTX_cleanup(&ctx);
1065 int tls1_final_finish_mac(SSL *s,
1066 const char *str, int slen, unsigned char *out)
1068 unsigned char buf[2*EVP_MAX_MD_SIZE];
1069 unsigned char buf2[12];
1073 if (s->s3->handshake_buffer)
1074 if (!ssl3_digest_cached_records(s))
1077 digests_len = tls1_handshake_digest(s, buf, sizeof(buf));
1078 if (digests_len < 0)
1084 if (!tls1_PRF(ssl_get_algorithm2(s),
1085 str,slen, buf, digests_len, NULL,0, NULL,0, NULL,0,
1086 s->session->master_key,s->session->master_key_length,
1087 out,buf2,sizeof buf2))
1096 int tls1_mac(SSL *ssl, unsigned char *md, int send)
1101 size_t md_size, orig_len;
1103 EVP_MD_CTX hmac, *mac_ctx;
1104 unsigned char header[13];
1109 rec= &(ssl->s3->wrec);
1110 seq= &(ssl->s3->write_sequence[0]);
1111 hash=ssl->write_hash;
1115 rec= &(ssl->s3->rrec);
1116 seq= &(ssl->s3->read_sequence[0]);
1117 hash=ssl->read_hash;
1120 t=EVP_MD_CTX_size(hash);
1124 if (!EVP_MD_CTX_copy(&hmac,hash))
1128 if (SSL_IS_DTLS(ssl))
1130 unsigned char dtlsseq[8],*p=dtlsseq;
1132 s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
1133 memcpy (p,&seq[2],6);
1135 memcpy(header, dtlsseq, 8);
1138 memcpy(header, seq, 8);
1140 /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1141 orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
1144 header[8]=rec->type;
1145 header[9]=(unsigned char)(ssl->version>>8);
1146 header[10]=(unsigned char)(ssl->version);
1147 header[11]=(rec->length)>>8;
1148 header[12]=(rec->length)&0xff;
1151 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1152 ssl3_cbc_record_digest_supported(mac_ctx))
1154 /* This is a CBC-encrypted record. We must avoid leaking any
1155 * timing-side channel information about how many blocks of
1156 * data we are hashing because that gives an attacker a
1158 ssl3_cbc_digest_record(
1162 rec->length + md_size, orig_len,
1163 ssl->s3->read_mac_secret,
1164 ssl->s3->read_mac_secret_size,
1169 EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
1170 EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
1171 t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
1175 EVP_MD_CTX_cleanup(&hmac);
1177 if (!SSL_IS_DTLS(ssl))
1179 for (i=7; i>=0; i--)
1182 if (seq[i] != 0) break;
1189 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1192 unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1193 const void *co = NULL, *so = NULL;
1194 int col = 0, sol = 0;
1198 printf ("tls1_generate_master_secret(%p,%p, %p, %d)\n", s,out, p,len);
1199 #endif /* KSSL_DEBUG */
1201 tls1_PRF(ssl_get_algorithm2(s),
1202 TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
1203 s->s3->client_random,SSL3_RANDOM_SIZE,
1205 s->s3->server_random,SSL3_RANDOM_SIZE,
1208 s->session->master_key,buff,sizeof buff);
1210 fprintf(stderr, "Premaster Secret:\n");
1211 BIO_dump_fp(stderr, (char *)p, len);
1212 fprintf(stderr, "Client Random:\n");
1213 BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
1214 fprintf(stderr, "Server Random:\n");
1215 BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
1216 fprintf(stderr, "Master Secret:\n");
1217 BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
1220 #ifdef OPENSSL_SSL_TRACE_CRYPTO
1221 if (s->msg_callback)
1223 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
1224 p, len, s, s->msg_callback_arg);
1225 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
1226 s->s3->client_random, SSL3_RANDOM_SIZE,
1227 s, s->msg_callback_arg);
1228 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
1229 s->s3->server_random, SSL3_RANDOM_SIZE,
1230 s, s->msg_callback_arg);
1231 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
1232 s->session->master_key,
1233 SSL3_MASTER_SECRET_SIZE,
1234 s, s->msg_callback_arg);
1239 printf ("tls1_generate_master_secret() complete\n");
1240 #endif /* KSSL_DEBUG */
1241 return(SSL3_MASTER_SECRET_SIZE);
1244 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1245 const char *label, size_t llen, const unsigned char *context,
1246 size_t contextlen, int use_context)
1248 unsigned char *buff;
1249 unsigned char *val = NULL;
1250 size_t vallen, currentvalpos;
1254 printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen);
1255 #endif /* KSSL_DEBUG */
1257 buff = OPENSSL_malloc(olen);
1258 if (buff == NULL) goto err2;
1260 /* construct PRF arguments
1261 * we construct the PRF argument ourself rather than passing separate
1262 * values into the TLS PRF to ensure that the concatenation of values
1263 * does not create a prohibited label.
1265 vallen = llen + SSL3_RANDOM_SIZE * 2;
1268 vallen += 2 + contextlen;
1271 val = OPENSSL_malloc(vallen);
1272 if (val == NULL) goto err2;
1274 memcpy(val + currentvalpos, (unsigned char *) label, llen);
1275 currentvalpos += llen;
1276 memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1277 currentvalpos += SSL3_RANDOM_SIZE;
1278 memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1279 currentvalpos += SSL3_RANDOM_SIZE;
1283 val[currentvalpos] = (contextlen >> 8) & 0xff;
1285 val[currentvalpos] = contextlen & 0xff;
1287 if ((contextlen > 0) || (context != NULL))
1289 memcpy(val + currentvalpos, context, contextlen);
1293 /* disallow prohibited labels
1294 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1295 * 15, so size of val > max(prohibited label len) = 15 and the
1296 * comparisons won't have buffer overflow
1298 if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1299 TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
1300 if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1301 TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
1302 if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1303 TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
1304 if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1305 TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
1307 rv = tls1_PRF(ssl_get_algorithm2(s),
1313 s->session->master_key,s->session->master_key_length,
1317 printf ("tls1_export_keying_material() complete\n");
1318 #endif /* KSSL_DEBUG */
1321 OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1325 OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
1328 if (buff != NULL) OPENSSL_free(buff);
1329 if (val != NULL) OPENSSL_free(val);
1333 int tls1_alert_code(int code)
1337 case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY);
1338 case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
1339 case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC);
1340 case SSL_AD_DECRYPTION_FAILED: return(TLS1_AD_DECRYPTION_FAILED);
1341 case SSL_AD_RECORD_OVERFLOW: return(TLS1_AD_RECORD_OVERFLOW);
1342 case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
1343 case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE);
1344 case SSL_AD_NO_CERTIFICATE: return(-1);
1345 case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE);
1346 case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
1347 case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
1348 case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
1349 case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
1350 case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER);
1351 case SSL_AD_UNKNOWN_CA: return(TLS1_AD_UNKNOWN_CA);
1352 case SSL_AD_ACCESS_DENIED: return(TLS1_AD_ACCESS_DENIED);
1353 case SSL_AD_DECODE_ERROR: return(TLS1_AD_DECODE_ERROR);
1354 case SSL_AD_DECRYPT_ERROR: return(TLS1_AD_DECRYPT_ERROR);
1355 case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
1356 case SSL_AD_PROTOCOL_VERSION: return(TLS1_AD_PROTOCOL_VERSION);
1357 case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
1358 case SSL_AD_INTERNAL_ERROR: return(TLS1_AD_INTERNAL_ERROR);
1359 case SSL_AD_USER_CANCELLED: return(TLS1_AD_USER_CANCELLED);
1360 case SSL_AD_NO_RENEGOTIATION: return(TLS1_AD_NO_RENEGOTIATION);
1361 case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
1362 case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1363 case SSL_AD_UNRECOGNIZED_NAME: return(TLS1_AD_UNRECOGNIZED_NAME);
1364 case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1365 case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1366 case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
1367 case SSL_AD_INAPPROPRIATE_FALLBACK:return(SSL3_AD_INAPPROPRIATE_FALLBACK);
1368 #if 0 /* not appropriate for TLS, not used for DTLS */
1369 case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE: return
1370 (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1372 default: return(-1);