2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
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.
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).
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.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
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)"
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
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.]
58 /* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
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
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/)"
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.
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.
87 * 6. Redistributions of any form whatsoever must retain the following
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
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 * ====================================================================
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).
111 /* ====================================================================
112 * Copyright 2005 Nokia. All rights reserved.
114 * The portions of the attached software ("Contribution") is developed by
115 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
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.
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.
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.
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
139 #include "ssl_locl.h"
140 #ifndef OPENSSL_NO_COMP
141 #include <openssl/comp.h>
143 #include <openssl/evp.h>
144 #include <openssl/hmac.h>
145 #include <openssl/md5.h>
146 #include <openssl/rand.h>
148 #include <openssl/des.h>
151 /* seed1 through seed5 are virtually concatenated */
152 static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
154 const void *seed1, int seed1_len,
155 const void *seed2, int seed2_len,
156 const void *seed3, int seed3_len,
157 const void *seed4, int seed4_len,
158 const void *seed5, int seed5_len,
159 unsigned char *out, int olen)
163 EVP_MD_CTX ctx, ctx_tmp;
165 unsigned char A1[EVP_MAX_MD_SIZE];
169 chunk=EVP_MD_size(md);
170 OPENSSL_assert(chunk >= 0);
172 EVP_MD_CTX_init(&ctx);
173 EVP_MD_CTX_init(&ctx_tmp);
174 EVP_MD_CTX_set_flags(&ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
175 EVP_MD_CTX_set_flags(&ctx_tmp, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
176 mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
179 if (!EVP_DigestSignInit(&ctx,NULL,md, NULL, mac_key))
181 if (!EVP_DigestSignInit(&ctx_tmp,NULL,md, NULL, mac_key))
183 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
185 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
187 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
189 if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
191 if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
193 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
198 /* Reinit mac contexts */
199 if (!EVP_DigestSignInit(&ctx,NULL,md, NULL, mac_key))
201 if (!EVP_DigestSignInit(&ctx_tmp,NULL,md, NULL, mac_key))
203 if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
205 if (!EVP_DigestSignUpdate(&ctx_tmp,A1,A1_len))
207 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
209 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
211 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
213 if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
215 if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
220 if (!EVP_DigestSignFinal(&ctx,out,&j))
224 /* calc the next A1 value */
225 if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
230 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
238 EVP_PKEY_free(mac_key);
239 EVP_MD_CTX_cleanup(&ctx);
240 EVP_MD_CTX_cleanup(&ctx_tmp);
241 OPENSSL_cleanse(A1,sizeof(A1));
245 /* seed1 through seed5 are virtually concatenated */
246 static int tls1_PRF(long digest_mask,
247 const void *seed1, int seed1_len,
248 const void *seed2, int seed2_len,
249 const void *seed3, int seed3_len,
250 const void *seed4, int seed4_len,
251 const void *seed5, int seed5_len,
252 const unsigned char *sec, int slen,
254 unsigned char *out2, int olen)
257 const unsigned char *S1;
262 /* Count number of digests and partition sec evenly */
264 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
265 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
272 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
273 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
275 SSLerr(SSL_F_TLS1_PRF,
276 SSL_R_UNSUPPORTED_DIGEST_TYPE);
279 if (!tls1_P_hash(md ,S1,len+(slen&1),
280 seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,seed4,seed4_len,seed5,seed5_len,
284 for (i=0; i<olen; i++)
294 static int tls1_generate_key_block(SSL *s, unsigned char *km,
295 unsigned char *tmp, int num)
298 ret = tls1_PRF(ssl_get_algorithm2(s),
299 TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE,
300 s->s3->server_random,SSL3_RANDOM_SIZE,
301 s->s3->client_random,SSL3_RANDOM_SIZE,
303 s->session->master_key,s->session->master_key_length,
306 printf("tls1_generate_key_block() ==> %d byte master_key =\n\t",
307 s->session->master_key_length);
310 for (i=0; i < s->session->master_key_length; i++)
312 printf("%02X", s->session->master_key[i]);
315 #endif /* KSSL_DEBUG */
319 /* tls1_change_cipher_state_cipher performs the work needed to switch cipher
320 * states when using EVP_CIPHER. The argument |is_read| is true iff this
321 * function is being called due to reading, as opposed to writing, a
322 * ChangeCipherSpec message. In order to support export ciphersuites,
323 * use_client_keys indicates whether the key material provided is in the
324 * "client write" direction. */
325 static int tls1_change_cipher_state_cipher(SSL *s,
326 char is_read, char use_client_keys,
327 const unsigned char *mac_secret, unsigned mac_secret_len,
328 const unsigned char *key, unsigned key_len,
329 const unsigned char *iv, unsigned iv_len)
331 const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
332 const char is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) != 0;
333 EVP_CIPHER_CTX *cipher_ctx;
337 unsigned char export_tmp1[EVP_MAX_KEY_LENGTH];
338 unsigned char export_tmp2[EVP_MAX_KEY_LENGTH];
339 unsigned char export_iv1[EVP_MAX_IV_LENGTH * 2];
340 unsigned char export_iv2[EVP_MAX_IV_LENGTH * 2];
344 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
345 s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
347 s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
349 if (s->enc_read_ctx != NULL)
350 EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
351 else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
354 /* make sure it's intialized in case we exit later with an error */
355 EVP_CIPHER_CTX_init(s->enc_read_ctx);
357 cipher_ctx = s->enc_read_ctx;
358 mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
360 memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
361 s->s3->read_mac_secret_size = mac_secret_len;
365 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
366 s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
368 s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
370 if (s->enc_write_ctx != NULL)
371 EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
372 else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
375 /* make sure it's intialized in case we exit later with an error */
376 EVP_CIPHER_CTX_init(s->enc_write_ctx);
378 cipher_ctx = s->enc_write_ctx;
379 mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
381 memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
382 s->s3->write_mac_secret_size = mac_secret_len;
387 /* In here I set both the read and write key/iv to the
388 * same value since only the correct one will be used :-).
390 const unsigned char *label;
395 label = (const unsigned char*) TLS_MD_CLIENT_WRITE_KEY_CONST;
396 label_len = TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
400 label = (const unsigned char*) TLS_MD_SERVER_WRITE_KEY_CONST;
401 label_len = TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
404 if (!tls1_PRF(ssl_get_algorithm2(s),
406 s->s3->client_random, SSL3_RANDOM_SIZE,
407 s->s3->server_random, SSL3_RANDOM_SIZE,
409 key /* secret */, key_len /* secret length */,
410 export_tmp1 /* output */,
411 export_tmp2 /* scratch space */,
412 EVP_CIPHER_key_length(s->s3->tmp.new_sym_enc) /* output length */))
418 static const unsigned char empty[] = "";
420 if (!tls1_PRF(ssl_get_algorithm2(s),
421 TLS_MD_IV_BLOCK_CONST, TLS_MD_IV_BLOCK_CONST_SIZE,
422 s->s3->client_random, SSL3_RANDOM_SIZE,
423 s->s3->server_random, SSL3_RANDOM_SIZE,
425 empty /* secret */ ,0 /* secret length */,
426 export_iv1 /* output */,
427 export_iv2 /* scratch space */,
428 iv_len * 2 /* output length */))
434 iv = &export_iv1[iv_len];
438 /* is_aead_cipher indicates whether the EVP_CIPHER implements an AEAD
439 * interface. This is different from the newer EVP_AEAD interface. */
440 is_aead_cipher = (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0;
445 EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
446 NULL, mac_secret, mac_secret_len);
449 EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
450 EVP_PKEY_free(mac_key);
453 if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
455 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key,
456 NULL /* iv */, !is_read);
457 EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GCM_SET_IV_FIXED, iv_len, (void*) iv);
460 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
462 /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
463 if (is_aead_cipher && mac_secret_len > 0)
464 EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
465 mac_secret_len, (void*) mac_secret);
469 OPENSSL_cleanse(export_tmp1, sizeof(export_tmp1));
470 OPENSSL_cleanse(export_tmp2, sizeof(export_tmp1));
471 OPENSSL_cleanse(export_iv1, sizeof(export_iv1));
472 OPENSSL_cleanse(export_iv2, sizeof(export_iv2));
478 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_CIPHER, ERR_R_MALLOC_FAILURE);
482 int tls1_change_cipher_state(SSL *s, int which)
484 /* is_read is true if we have just read a ChangeCipherSpec message -
485 * i.e. we need to update the read cipherspec. Otherwise we have just
487 const char is_read = (which & SSL3_CC_READ) != 0;
488 /* use_client_keys is true if we wish to use the keys for the "client
489 * write" direction. This is the case if we're a client sending a
490 * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec. */
491 const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
492 which == SSL3_CHANGE_CIPHER_SERVER_READ;
493 const unsigned char *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
494 const unsigned char *client_write_key, *server_write_key, *key;
495 const unsigned char *client_write_iv, *server_write_iv, *iv;
496 const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
497 unsigned key_len, iv_len, mac_secret_len;
498 const unsigned char *key_data;
499 const char is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) != 0;
501 /* Update compression contexts. */
502 #ifndef OPENSSL_NO_COMP
503 const SSL_COMP *comp = s->s3->tmp.new_compression;
507 if (s->expand != NULL)
509 COMP_CTX_free(s->expand);
514 s->expand=COMP_CTX_new(comp->method);
515 if (s->expand == NULL)
517 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
520 if (s->s3->rrec.comp == NULL)
522 (unsigned char *)OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
523 if (s->s3->rrec.comp == NULL)
529 if (s->compress != NULL)
531 COMP_CTX_free(s->compress);
536 s->compress = COMP_CTX_new(comp->method);
537 if (s->compress == NULL)
539 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
544 #endif /* OPENSSL_NO_COMP */
546 /* Reset sequence number to zero. */
547 memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
549 /* key_arg is used for SSLv2. We don't need it for TLS. */
550 s->session->key_arg_length = 0;
552 mac_secret_len = s->s3->tmp.new_mac_secret_size;
554 key_len = EVP_CIPHER_key_length(cipher);
555 if (is_export && key_len > SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher))
556 key_len = SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher);
558 if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
559 iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
561 iv_len = EVP_CIPHER_iv_length(cipher);
563 key_data = s->s3->tmp.key_block;
564 client_write_mac_secret = key_data; key_data += mac_secret_len;
565 server_write_mac_secret = key_data; key_data += mac_secret_len;
566 client_write_key = key_data; key_data += key_len;
567 server_write_key = key_data; key_data += key_len;
568 client_write_iv = key_data; key_data += iv_len;
569 server_write_iv = key_data; key_data += iv_len;
573 mac_secret = client_write_mac_secret;
574 key = client_write_key;
575 iv = client_write_iv;
579 mac_secret = server_write_mac_secret;
580 key = server_write_key;
581 iv = server_write_iv;
584 if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
586 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR);
590 if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
591 mac_secret, mac_secret_len,
597 #ifdef OPENSSL_SSL_TRACE_CRYPTO
600 int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
602 s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
603 mac_secret, mac_secret_len,
604 s, s->msg_callback_arg);
606 s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
608 s, s->msg_callback_arg);
611 if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
612 wh |= TLS1_RT_CRYPTO_FIXED_IV;
614 wh |= TLS1_RT_CRYPTO_IV;
615 s->msg_callback(2, s->version, wh, iv, iv_len,
616 s, s->msg_callback_arg);
623 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
627 int tls1_setup_key_block(SSL *s)
629 unsigned char *p1,*p2=NULL;
634 int mac_type= NID_undef,mac_secret_size=0;
639 printf ("tls1_setup_key_block()\n");
640 #endif /* KSSL_DEBUG */
642 if (s->s3->tmp.key_block_length != 0)
645 if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size,&comp))
647 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
651 if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
652 iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
654 iv_len = EVP_CIPHER_iv_length(c);
656 s->s3->tmp.new_sym_enc=c;
657 s->s3->tmp.new_hash=hash;
658 s->s3->tmp.new_mac_pkey_type = mac_type;
659 s->s3->tmp.new_mac_secret_size = mac_secret_size;
660 num=EVP_CIPHER_key_length(c)+mac_secret_size+iv_len;
663 ssl3_cleanup_key_block(s);
665 if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
667 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE);
671 s->s3->tmp.key_block_length=num;
672 s->s3->tmp.key_block=p1;
674 if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
676 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE);
681 printf("client random\n");
682 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
683 printf("server random\n");
684 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
685 printf("pre-master\n");
686 { int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
688 if (!tls1_generate_key_block(s,p1,p2,num))
691 printf("\nkey block\n");
692 { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
695 if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
696 && s->method->version <= TLS1_VERSION)
698 /* enable vulnerability countermeasure for CBC ciphers with
699 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
701 s->s3->need_empty_fragments = 1;
703 if (s->session->cipher != NULL)
705 if (s->session->cipher->algorithm_enc == SSL_eNULL)
706 s->s3->need_empty_fragments = 0;
708 #ifndef OPENSSL_NO_RC4
709 if (s->session->cipher->algorithm_enc == SSL_RC4)
710 s->s3->need_empty_fragments = 0;
719 OPENSSL_cleanse(p2,num);
725 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
728 * 0: (in non-constant time) if the record is publically invalid (i.e. too
730 * 1: if the record's padding is valid / the encryption was successful.
731 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
732 * an internal error occured.
734 int tls1_enc(SSL *s, int send)
739 int bs,i,j,k,pad=0,ret,mac_size=0;
740 const EVP_CIPHER *enc;
744 if (EVP_MD_CTX_md(s->write_hash))
746 int n=EVP_MD_CTX_size(s->write_hash);
747 OPENSSL_assert(n >= 0);
751 if (s->enc_write_ctx == NULL)
756 enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
757 /* For TLSv1.1 and later explicit IV */
758 if (SSL_USE_EXPLICIT_IV(s)
759 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
760 ivlen = EVP_CIPHER_iv_length(enc);
765 if ( rec->data != rec->input)
766 /* we can't write into the input stream:
767 * Can this ever happen?? (steve)
770 "%s:%d: rec->data != rec->input\n",
772 else if (RAND_bytes(rec->input, ivlen) <= 0)
779 if (EVP_MD_CTX_md(s->read_hash))
781 int n=EVP_MD_CTX_size(s->read_hash);
782 OPENSSL_assert(n >= 0);
786 if (s->enc_read_ctx == NULL)
789 enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
793 printf("tls1_enc(%d)\n", send);
794 #endif /* KSSL_DEBUG */
796 if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
798 memmove(rec->data,rec->input,rec->length);
799 rec->input=rec->data;
805 bs=EVP_CIPHER_block_size(ds->cipher);
807 if (EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_AEAD_CIPHER)
809 unsigned char buf[13],*seq;
811 seq = send?s->s3->write_sequence:s->s3->read_sequence;
815 unsigned char dtlsseq[9],*p=dtlsseq;
817 s2n(send?s->d1->w_epoch:s->d1->r_epoch,p);
819 memcpy(buf,dtlsseq,8);
824 for (i=7; i>=0; i--) /* increment */
827 if (seq[i] != 0) break;
832 buf[9]=(unsigned char)(s->version>>8);
833 buf[10]=(unsigned char)(s->version);
834 buf[11]=rec->length>>8;
835 buf[12]=rec->length&0xff;
836 pad=EVP_CIPHER_CTX_ctrl(ds,EVP_CTRL_AEAD_TLS1_AAD,13,buf);
843 else if ((bs != 1) && send)
847 /* Add weird padding of upto 256 bytes */
849 /* we need to add 'i' padding bytes of value j */
851 if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)
853 if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
856 for (k=(int)l; k<(int)(l+i); k++)
865 printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
866 ds,rec->data,rec->input,l);
867 printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n",
868 ds->buf_len, ds->cipher->key_len,
869 DES_KEY_SZ, DES_SCHEDULE_SZ,
872 for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]);
874 printf("\trec->input=");
875 for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]);
878 #endif /* KSSL_DEBUG */
882 if (l == 0 || l%bs != 0)
886 i = EVP_Cipher(ds,rec->data,rec->input,l);
887 if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
890 return -1; /* AEAD can fail to verify MAC */
891 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send)
893 rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
894 rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
895 rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
901 printf("\trec->data=");
903 printf(" %02x", rec->data[i]); printf("\n");
905 #endif /* KSSL_DEBUG */
908 if (EVP_MD_CTX_md(s->read_hash) != NULL)
909 mac_size = EVP_MD_CTX_size(s->read_hash);
910 if ((bs != 1) && !send)
911 ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
918 int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
921 EVP_MD_CTX ctx, *d=NULL;
924 if (s->s3->handshake_buffer)
925 if (!ssl3_digest_cached_records(s))
928 for (i=0;i<SSL_MAX_DIGEST;i++)
930 if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid)
932 d=s->s3->handshake_dgst[i];
937 SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC,SSL_R_NO_REQUIRED_DIGEST);
941 EVP_MD_CTX_init(&ctx);
942 EVP_MD_CTX_copy_ex(&ctx,d);
943 EVP_DigestFinal_ex(&ctx,out,&ret);
944 EVP_MD_CTX_cleanup(&ctx);
948 int tls1_final_finish_mac(SSL *s,
949 const char *str, int slen, unsigned char *out)
953 unsigned char buf[2*EVP_MAX_MD_SIZE];
954 unsigned char *q,buf2[12];
962 if (s->s3->handshake_buffer)
963 if (!ssl3_digest_cached_records(s))
966 EVP_MD_CTX_init(&ctx);
968 for (idx=0;ssl_get_handshake_digest(idx,&mask,&md);idx++)
970 if (mask & ssl_get_algorithm2(s))
972 int hashsize = EVP_MD_size(md);
973 if (hashsize < 0 || hashsize > (int)(sizeof buf - (size_t)(q-buf)))
975 /* internal error: 'buf' is too small for this cipersuite! */
980 EVP_MD_CTX_copy_ex(&ctx,s->s3->handshake_dgst[idx]);
981 EVP_DigestFinal_ex(&ctx,q,&i);
982 if (i != (unsigned int)hashsize) /* can't really happen */
989 if (!tls1_PRF(ssl_get_algorithm2(s),
990 str,slen, buf,(int)(q-buf), NULL,0, NULL,0, NULL,0,
991 s->session->master_key,s->session->master_key_length,
992 out,buf2,sizeof buf2))
994 EVP_MD_CTX_cleanup(&ctx);
1002 int tls1_mac(SSL *ssl, unsigned char *md, int send)
1007 size_t md_size, orig_len;
1009 EVP_MD_CTX hmac, *mac_ctx;
1010 unsigned char header[13];
1011 int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM));
1016 rec= &(ssl->s3->wrec);
1017 seq= &(ssl->s3->write_sequence[0]);
1018 hash=ssl->write_hash;
1022 rec= &(ssl->s3->rrec);
1023 seq= &(ssl->s3->read_sequence[0]);
1024 hash=ssl->read_hash;
1027 t=EVP_MD_CTX_size(hash);
1028 OPENSSL_assert(t >= 0);
1031 /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1038 EVP_MD_CTX_copy(&hmac,hash);
1042 if (SSL_IS_DTLS(ssl))
1044 unsigned char dtlsseq[8],*p=dtlsseq;
1046 s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
1047 memcpy (p,&seq[2],6);
1049 memcpy(header, dtlsseq, 8);
1052 memcpy(header, seq, 8);
1054 /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1055 orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
1058 header[8]=rec->type;
1059 header[9]=(unsigned char)(ssl->version>>8);
1060 header[10]=(unsigned char)(ssl->version);
1061 header[11]=(rec->length)>>8;
1062 header[12]=(rec->length)&0xff;
1065 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1066 ssl3_cbc_record_digest_supported(mac_ctx))
1068 /* This is a CBC-encrypted record. We must avoid leaking any
1069 * timing-side channel information about how many blocks of
1070 * data we are hashing because that gives an attacker a
1072 ssl3_cbc_digest_record(
1076 rec->length + md_size, orig_len,
1077 ssl->s3->read_mac_secret,
1078 ssl->s3->read_mac_secret_size,
1083 EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
1084 EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
1085 t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
1086 OPENSSL_assert(t > 0);
1088 if (!send && FIPS_mode())
1089 tls_fips_digest_extra(
1091 mac_ctx, rec->input,
1092 rec->length, orig_len);
1097 EVP_MD_CTX_cleanup(&hmac);
1100 {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); }
1102 {int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); }
1104 {int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); }
1106 {unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); }
1109 if (!SSL_IS_DTLS(ssl))
1111 for (i=7; i>=0; i--)
1114 if (seq[i] != 0) break;
1119 {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); }
1124 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1127 unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1128 const void *co = NULL, *so = NULL;
1129 int col = 0, sol = 0;
1133 printf ("tls1_generate_master_secret(%p,%p, %p, %d)\n", s,out, p,len);
1134 #endif /* KSSL_DEBUG */
1136 #ifdef TLSEXT_TYPE_opaque_prf_input
1137 if (s->s3->client_opaque_prf_input != NULL && s->s3->server_opaque_prf_input != NULL &&
1138 s->s3->client_opaque_prf_input_len > 0 &&
1139 s->s3->client_opaque_prf_input_len == s->s3->server_opaque_prf_input_len)
1141 co = s->s3->client_opaque_prf_input;
1142 col = s->s3->server_opaque_prf_input_len;
1143 so = s->s3->server_opaque_prf_input;
1144 sol = s->s3->client_opaque_prf_input_len; /* must be same as col (see draft-rescorla-tls-opaque-prf-input-00.txt, section 3.1) */
1148 tls1_PRF(ssl_get_algorithm2(s),
1149 TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
1150 s->s3->client_random,SSL3_RANDOM_SIZE,
1152 s->s3->server_random,SSL3_RANDOM_SIZE,
1155 s->session->master_key,buff,sizeof buff);
1157 fprintf(stderr, "Premaster Secret:\n");
1158 BIO_dump_fp(stderr, (char *)p, len);
1159 fprintf(stderr, "Client Random:\n");
1160 BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
1161 fprintf(stderr, "Server Random:\n");
1162 BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
1163 fprintf(stderr, "Master Secret:\n");
1164 BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
1167 #ifdef OPENSSL_SSL_TRACE_CRYPTO
1168 if (s->msg_callback)
1170 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
1171 p, len, s, s->msg_callback_arg);
1172 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
1173 s->s3->client_random, SSL3_RANDOM_SIZE,
1174 s, s->msg_callback_arg);
1175 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
1176 s->s3->server_random, SSL3_RANDOM_SIZE,
1177 s, s->msg_callback_arg);
1178 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
1179 s->session->master_key,
1180 SSL3_MASTER_SECRET_SIZE,
1181 s, s->msg_callback_arg);
1186 printf ("tls1_generate_master_secret() complete\n");
1187 #endif /* KSSL_DEBUG */
1188 return(SSL3_MASTER_SECRET_SIZE);
1191 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1192 const char *label, size_t llen, const unsigned char *context,
1193 size_t contextlen, int use_context)
1195 unsigned char *buff;
1196 unsigned char *val = NULL;
1197 size_t vallen, currentvalpos;
1201 printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen);
1202 #endif /* KSSL_DEBUG */
1204 buff = OPENSSL_malloc(olen);
1205 if (buff == NULL) goto err2;
1207 /* construct PRF arguments
1208 * we construct the PRF argument ourself rather than passing separate
1209 * values into the TLS PRF to ensure that the concatenation of values
1210 * does not create a prohibited label.
1212 vallen = llen + SSL3_RANDOM_SIZE * 2;
1215 vallen += 2 + contextlen;
1218 val = OPENSSL_malloc(vallen);
1219 if (val == NULL) goto err2;
1221 memcpy(val + currentvalpos, (unsigned char *) label, llen);
1222 currentvalpos += llen;
1223 memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1224 currentvalpos += SSL3_RANDOM_SIZE;
1225 memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1226 currentvalpos += SSL3_RANDOM_SIZE;
1230 val[currentvalpos] = (contextlen >> 8) & 0xff;
1232 val[currentvalpos] = contextlen & 0xff;
1234 if ((contextlen > 0) || (context != NULL))
1236 memcpy(val + currentvalpos, context, contextlen);
1240 /* disallow prohibited labels
1241 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1242 * 15, so size of val > max(prohibited label len) = 15 and the
1243 * comparisons won't have buffer overflow
1245 if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1246 TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
1247 if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1248 TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
1249 if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1250 TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
1251 if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1252 TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
1254 rv = tls1_PRF(s->s3->tmp.new_cipher->algorithm2,
1260 s->session->master_key,s->session->master_key_length,
1264 printf ("tls1_export_keying_material() complete\n");
1265 #endif /* KSSL_DEBUG */
1268 SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1272 SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
1275 if (buff != NULL) OPENSSL_free(buff);
1276 if (val != NULL) OPENSSL_free(val);
1280 int tls1_alert_code(int code)
1284 case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY);
1285 case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
1286 case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC);
1287 case SSL_AD_DECRYPTION_FAILED: return(TLS1_AD_DECRYPTION_FAILED);
1288 case SSL_AD_RECORD_OVERFLOW: return(TLS1_AD_RECORD_OVERFLOW);
1289 case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
1290 case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE);
1291 case SSL_AD_NO_CERTIFICATE: return(-1);
1292 case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE);
1293 case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
1294 case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
1295 case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
1296 case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
1297 case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER);
1298 case SSL_AD_UNKNOWN_CA: return(TLS1_AD_UNKNOWN_CA);
1299 case SSL_AD_ACCESS_DENIED: return(TLS1_AD_ACCESS_DENIED);
1300 case SSL_AD_DECODE_ERROR: return(TLS1_AD_DECODE_ERROR);
1301 case SSL_AD_DECRYPT_ERROR: return(TLS1_AD_DECRYPT_ERROR);
1302 case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
1303 case SSL_AD_PROTOCOL_VERSION: return(TLS1_AD_PROTOCOL_VERSION);
1304 case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
1305 case SSL_AD_INTERNAL_ERROR: return(TLS1_AD_INTERNAL_ERROR);
1306 case SSL_AD_USER_CANCELLED: return(TLS1_AD_USER_CANCELLED);
1307 case SSL_AD_NO_RENEGOTIATION: return(TLS1_AD_NO_RENEGOTIATION);
1308 case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
1309 case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1310 case SSL_AD_UNRECOGNIZED_NAME: return(TLS1_AD_UNRECOGNIZED_NAME);
1311 case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1312 case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1313 case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
1314 #if 0 /* not appropriate for TLS, not used for DTLS */
1315 case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE: return
1316 (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1318 default: return(-1);