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 unsigned char *out, int olen)
159 EVP_MD_CTX ctx, ctx_tmp, ctx_init;
161 unsigned char A1[EVP_MAX_MD_SIZE];
165 chunk=EVP_MD_size(md);
167 EVP_MD_CTX_init(&ctx);
168 EVP_MD_CTX_init(&ctx_tmp);
169 EVP_MD_CTX_init(&ctx_init);
170 mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
173 if (!EVP_DigestSignInit(&ctx_init,NULL,md, NULL, mac_key))
175 if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
177 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
179 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
181 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
183 A1_len = EVP_MAX_MD_SIZE;
184 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
189 /* Reinit mac contexts */
190 if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
192 if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
194 if (olen>chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp,&ctx))
196 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
198 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
200 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
206 if (!EVP_DigestSignFinal(&ctx,out,&j))
210 /* calc the next A1 value */
211 A1_len = EVP_MAX_MD_SIZE;
212 if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
217 A1_len = EVP_MAX_MD_SIZE;
218 if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
226 EVP_PKEY_free(mac_key);
227 EVP_MD_CTX_cleanup(&ctx);
228 EVP_MD_CTX_cleanup(&ctx_tmp);
229 EVP_MD_CTX_cleanup(&ctx_init);
230 OPENSSL_cleanse(A1,sizeof(A1));
234 /* seed1 through seed5 are virtually concatenated */
235 static int tls1_PRF(long digest_mask,
236 const void *seed1, int seed1_len,
237 const void *seed2, int seed2_len,
238 const void *seed3, int seed3_len,
239 const unsigned char *sec, int slen,
241 unsigned char *out2, int olen)
244 const unsigned char *S1;
249 /* Count number of digests and partition sec evenly */
251 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
252 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
259 for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
260 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
262 OPENSSL_PUT_ERROR(SSL, tls1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
265 if (!tls1_P_hash(md ,S1,len+(slen&1),
266 seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,
270 for (i=0; i<olen; i++)
281 static int tls1_generate_key_block(SSL *s, unsigned char *km,
282 unsigned char *tmp, int num)
285 ret = tls1_PRF(ssl_get_algorithm2(s),
286 TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE,
287 s->s3->server_random,SSL3_RANDOM_SIZE,
288 s->s3->client_random,SSL3_RANDOM_SIZE,
289 s->session->master_key,s->session->master_key_length,
294 /* tls1_aead_ctx_init allocates |*aead_ctx|, if needed and returns 1. It
295 * returns 0 on malloc error. */
296 static int tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
298 if (*aead_ctx != NULL)
299 EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
302 *aead_ctx = (SSL_AEAD_CTX*) OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
303 if (*aead_ctx == NULL)
305 OPENSSL_PUT_ERROR(SSL, tls1_aead_ctx_init, ERR_R_MALLOC_FAILURE);
313 static void tls1_cleanup_enc_ctx(EVP_CIPHER_CTX **ctx)
316 EVP_CIPHER_CTX_free(*ctx);
320 static void tls1_cleanup_hash_ctx(EVP_MD_CTX **ctx)
323 EVP_MD_CTX_destroy(*ctx);
327 static int tls1_change_cipher_state_aead(SSL *s, char is_read,
328 const unsigned char *key, unsigned key_len,
329 const unsigned char *iv, unsigned iv_len,
330 const unsigned char *mac_secret, unsigned mac_secret_len)
332 const EVP_AEAD *aead = s->s3->tmp.new_aead;
333 SSL_AEAD_CTX *aead_ctx;
334 /* mac_key_and_key is used to merge the MAC and cipher keys for an AEAD
335 * which simulates pre-AEAD cipher suites. It needs to be large enough
336 * to cope with the largest pair of keys. */
337 uint8_t mac_key_and_key[32 /* HMAC(SHA256) */ + 32 /* AES-256 */];
341 tls1_cleanup_enc_ctx(&s->enc_read_ctx);
342 tls1_cleanup_hash_ctx(&s->read_hash);
346 tls1_cleanup_enc_ctx(&s->enc_write_ctx);
347 tls1_cleanup_hash_ctx(&s->write_hash);
350 if (mac_secret_len > 0)
352 /* This is a "stateful" AEAD (for compatibility with pre-AEAD
354 if (mac_secret_len + key_len > sizeof(mac_key_and_key))
356 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
359 memcpy(mac_key_and_key, mac_secret, mac_secret_len);
360 memcpy(mac_key_and_key + mac_secret_len, key, key_len);
361 key = mac_key_and_key;
362 key_len += mac_secret_len;
367 if (!tls1_aead_ctx_init(&s->aead_read_ctx))
369 aead_ctx = s->aead_read_ctx;
373 if (!tls1_aead_ctx_init(&s->aead_write_ctx))
375 aead_ctx = s->aead_write_ctx;
378 if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
379 EVP_AEAD_DEFAULT_TAG_LENGTH, NULL /* engine */))
381 OPENSSL_free(aead_ctx);
383 s->aead_read_ctx = NULL;
385 s->aead_write_ctx = NULL;
388 if (iv_len > sizeof(aead_ctx->fixed_nonce))
390 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
393 memcpy(aead_ctx->fixed_nonce, iv, iv_len);
394 aead_ctx->fixed_nonce_len = iv_len;
395 aead_ctx->variable_nonce_len = 8; /* correct for all true AEADs so far. */
396 if (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)
397 aead_ctx->variable_nonce_len = 0;
398 aead_ctx->variable_nonce_included_in_record =
399 (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_INCLUDED_IN_RECORD) != 0;
400 if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len != EVP_AEAD_nonce_length(aead))
402 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
405 aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
410 static void tls1_cleanup_aead_ctx(SSL_AEAD_CTX **ctx)
414 EVP_AEAD_CTX_cleanup(&(*ctx)->ctx);
420 /* tls1_change_cipher_state_cipher performs the work needed to switch cipher
421 * states when using EVP_CIPHER. The argument |is_read| is true iff this
422 * function is being called due to reading, as opposed to writing, a
423 * ChangeCipherSpec message. In order to support export ciphersuites,
424 * use_client_keys indicates whether the key material provided is in the
425 * "client write" direction. */
426 static int tls1_change_cipher_state_cipher(
427 SSL *s, char is_read, char use_client_keys,
428 const unsigned char *mac_secret, unsigned mac_secret_len,
429 const unsigned char *key, unsigned key_len,
430 const unsigned char *iv, unsigned iv_len)
432 const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
433 EVP_CIPHER_CTX *cipher_ctx;
437 tls1_cleanup_aead_ctx(&s->aead_read_ctx);
439 tls1_cleanup_aead_ctx(&s->aead_write_ctx);
443 if (s->enc_read_ctx != NULL && !SSL_IS_DTLS(s))
444 EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
445 else if ((s->enc_read_ctx=EVP_CIPHER_CTX_new()) == NULL)
448 cipher_ctx = s->enc_read_ctx;
449 mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
451 memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
452 s->s3->read_mac_secret_size = mac_secret_len;
456 /* When updating the write contexts for DTLS, we do not wish to
457 * free the old ones because DTLS stores pointers to them in
458 * order to implement retransmission. */
460 if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
461 EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
462 else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
465 /* make sure it's intialized in case we exit later with an error */
466 EVP_CIPHER_CTX_init(s->enc_write_ctx);
468 cipher_ctx = s->enc_write_ctx;
471 /* This is the same as ssl_replace_hash, but doesn't
472 * free the old |s->write_hash|. */
473 mac_ctx = EVP_MD_CTX_create();
476 s->write_hash = mac_ctx;
479 mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
481 memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
482 s->s3->write_mac_secret_size = mac_secret_len;
486 EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
487 NULL, mac_secret, mac_secret_len);
490 EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
491 EVP_PKEY_free(mac_key);
493 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
498 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_cipher, ERR_R_MALLOC_FAILURE);
502 int tls1_change_cipher_state(SSL *s, int which)
504 /* is_read is true if we have just read a ChangeCipherSpec message -
505 * i.e. we need to update the read cipherspec. Otherwise we have just
507 const char is_read = (which & SSL3_CC_READ) != 0;
508 /* use_client_keys is true if we wish to use the keys for the "client
509 * write" direction. This is the case if we're a client sending a
510 * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec. */
511 const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
512 which == SSL3_CHANGE_CIPHER_SERVER_READ;
513 const unsigned char *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
514 const unsigned char *client_write_key, *server_write_key, *key;
515 const unsigned char *client_write_iv, *server_write_iv, *iv;
516 const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
517 const EVP_AEAD *aead = s->s3->tmp.new_aead;
518 unsigned key_len, iv_len, mac_secret_len;
519 const unsigned char *key_data;
521 /* Reset sequence number to zero. */
523 memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
525 mac_secret_len = s->s3->tmp.new_mac_secret_size;
529 key_len = EVP_AEAD_key_length(aead);
530 /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
531 * cipher suites) the key length reported by
532 * |EVP_AEAD_key_length| will include the MAC key bytes. */
533 if (key_len < mac_secret_len)
535 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
538 key_len -= mac_secret_len;
539 iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
543 key_len = EVP_CIPHER_key_length(cipher);
544 iv_len = EVP_CIPHER_iv_length(cipher);
547 key_data = s->s3->tmp.key_block;
548 client_write_mac_secret = key_data; key_data += mac_secret_len;
549 server_write_mac_secret = key_data; key_data += mac_secret_len;
550 client_write_key = key_data; key_data += key_len;
551 server_write_key = key_data; key_data += key_len;
552 client_write_iv = key_data; key_data += iv_len;
553 server_write_iv = key_data; key_data += iv_len;
557 mac_secret = client_write_mac_secret;
558 key = client_write_key;
559 iv = client_write_iv;
563 mac_secret = server_write_mac_secret;
564 key = server_write_key;
565 iv = server_write_iv;
568 if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
570 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
576 if (!tls1_change_cipher_state_aead(s, is_read,
577 key, key_len, iv, iv_len,
578 mac_secret, mac_secret_len))
583 if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
584 mac_secret, mac_secret_len,
593 int tls1_setup_key_block(SSL *s)
595 unsigned char *p1,*p2=NULL;
596 const EVP_CIPHER *c = NULL;
597 const EVP_MD *hash = NULL;
598 const EVP_AEAD *aead = NULL;
600 int mac_type= NID_undef,mac_secret_size=0;
602 unsigned key_len, iv_len;
605 if (s->s3->tmp.key_block_length != 0)
608 if (s->session->cipher &&
609 ((s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD) ||
610 (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)))
612 if (!ssl_cipher_get_evp_aead(s->session, &aead))
613 goto cipher_unavailable_err;
614 key_len = EVP_AEAD_key_length(aead);
615 iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
616 if ((s->session->cipher->algorithm2 &
617 SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD) &&
618 !ssl_cipher_get_mac(s->session, &hash, &mac_type, &mac_secret_size))
619 goto cipher_unavailable_err;
620 /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
621 * cipher suites) the key length reported by
622 * |EVP_AEAD_key_length| will include the MAC key bytes. */
623 if (key_len < (size_t)mac_secret_size)
625 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
628 key_len -= mac_secret_size;
632 if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size))
633 goto cipher_unavailable_err;
634 key_len = EVP_CIPHER_key_length(c);
635 iv_len = EVP_CIPHER_iv_length(c);
638 s->s3->tmp.new_aead=aead;
639 s->s3->tmp.new_sym_enc=c;
640 s->s3->tmp.new_hash=hash;
641 s->s3->tmp.new_mac_pkey_type = mac_type;
642 s->s3->tmp.new_mac_secret_size = mac_secret_size;
644 num=key_len+mac_secret_size+iv_len;
647 ssl3_cleanup_key_block(s);
649 if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
651 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
655 s->s3->tmp.key_block_length=num;
656 s->s3->tmp.key_block=p1;
658 if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
660 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
665 printf("client random\n");
666 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
667 printf("server random\n");
668 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
669 printf("pre-master\n");
670 { int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
672 if (!tls1_generate_key_block(s,p1,p2,num))
675 printf("\nkey block\n");
676 { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
679 if (s->method->version <= TLS1_VERSION &&
680 (s->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0)
682 /* enable vulnerability countermeasure for CBC ciphers with
683 * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
685 s->s3->need_record_splitting = 1;
687 if (s->session->cipher != NULL)
689 if (s->session->cipher->algorithm_enc == SSL_RC4)
690 s->s3->need_record_splitting = 0;
698 OPENSSL_cleanse(p2,num);
703 cipher_unavailable_err:
704 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
708 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
711 * 0: (in non-constant time) if the record is publically invalid (i.e. too
713 * 1: if the record's padding is valid / the encryption was successful.
714 * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
715 * an internal error occured.
717 int tls1_enc(SSL *s, int send)
722 int bs,i,j,k,pad=0,ret,mac_size=0;
723 const EVP_CIPHER *enc;
724 const SSL_AEAD_CTX *aead;
732 aead = s->aead_write_ctx;
734 aead = s->aead_read_ctx;
738 unsigned char ad[13], *seq, *in, *out, nonce[16];
742 seq = send ? s->s3->write_sequence : s->s3->read_sequence;
746 unsigned char dtlsseq[9], *p = dtlsseq;
748 s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
749 memcpy(p, &seq[2], 6);
750 memcpy(ad, dtlsseq, 8);
755 for (i=7; i>=0; i--) /* increment */
764 ad[9] = (unsigned char)(s->version>>8);
765 ad[10] = (unsigned char)(s->version);
767 if (aead->fixed_nonce_len + aead->variable_nonce_len > sizeof(nonce) ||
768 aead->variable_nonce_len > 8)
769 return -1; /* internal error - should never happen. */
771 memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
772 nonce_used = aead->fixed_nonce_len;
776 size_t len = rec->length;
781 /* When sending we use the sequence number as the
782 * variable part of the nonce. */
783 if (aead->variable_nonce_len > 8)
785 memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
786 nonce_used += aead->variable_nonce_len;
788 /* in do_ssl3_write, rec->input is moved forward by
789 * variable_nonce_len in order to leave space for the
790 * variable nonce. Thus we can copy the sequence number
791 * bytes into place without overwriting any of the
793 if (aead->variable_nonce_included_in_record)
795 memcpy(out, ad, aead->variable_nonce_len);
796 len -= aead->variable_nonce_len;
797 eivlen = aead->variable_nonce_len;
803 if (!EVP_AEAD_CTX_seal(
805 out + eivlen, &n, len + aead->tag_len,
812 if (aead->variable_nonce_included_in_record)
813 n += aead->variable_nonce_len;
818 size_t len = rec->length;
820 if (rec->data != rec->input)
821 return -1; /* internal error - should never happen. */
822 out = in = rec->input;
824 if (len < aead->variable_nonce_len)
826 memcpy(nonce + nonce_used,
827 aead->variable_nonce_included_in_record ? in : ad,
828 aead->variable_nonce_len);
829 nonce_used += aead->variable_nonce_len;
831 if (aead->variable_nonce_included_in_record)
833 in += aead->variable_nonce_len;
834 len -= aead->variable_nonce_len;
835 out += aead->variable_nonce_len;
838 if (len < aead->tag_len)
840 len -= aead->tag_len;
845 if (!EVP_AEAD_CTX_open(
849 in, len + aead->tag_len,
855 rec->data = rec->input = out;
866 if (s->enc_write_ctx == NULL)
871 enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
872 /* For TLSv1.1 and later explicit IV */
873 if (SSL_USE_EXPLICIT_IV(s)
874 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
875 ivlen = EVP_CIPHER_iv_length(enc);
880 if ( rec->data != rec->input)
881 /* we can't write into the input stream:
882 * Can this ever happen?? (steve)
885 "%s:%d: rec->data != rec->input\n",
887 else if (RAND_bytes(rec->input, ivlen) <= 0)
896 if (s->enc_read_ctx == NULL)
899 enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
902 if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
904 memmove(rec->data,rec->input,rec->length);
905 rec->input=rec->data;
911 bs=EVP_CIPHER_block_size(ds->cipher);
913 if ((bs != 1) && send)
917 /* Add weird padding of upto 256 bytes */
919 /* we need to add 'i' padding bytes of value j */
921 for (k=(int)l; k<(int)(l+i); k++)
929 if (l == 0 || l%bs != 0)
933 i = EVP_Cipher(ds,rec->data,rec->input,l);
934 if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
937 return -1; /* AEAD can fail to verify MAC */
940 if (EVP_MD_CTX_md(s->read_hash) != NULL)
941 mac_size = EVP_MD_CTX_size(s->read_hash);
942 if ((bs != 1) && !send)
943 ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
950 int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
953 EVP_MD_CTX ctx, *d=NULL;
956 if (s->s3->handshake_buffer)
957 if (!ssl3_digest_cached_records(s, free_handshake_buffer))
960 for (i=0;i<SSL_MAX_DIGEST;i++)
962 if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid)
964 d=s->s3->handshake_dgst[i];
969 OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
973 EVP_MD_CTX_init(&ctx);
974 EVP_MD_CTX_copy_ex(&ctx,d);
975 EVP_DigestFinal_ex(&ctx,out,&ret);
976 EVP_MD_CTX_cleanup(&ctx);
980 /* tls1_handshake_digest calculates the current handshake hash and writes it to
981 * |out|, which has space for |out_len| bytes. It returns the number of bytes
982 * written or -1 in the event of an error. This function works on a copy of the
983 * underlying digests so can be called multiple times and prior to the final
985 int tls1_handshake_digest(SSL *s, unsigned char *out, size_t out_len)
989 int i, err = 0, len = 0;
992 EVP_MD_CTX_init(&ctx);
994 for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++)
997 unsigned int digest_len;
998 EVP_MD_CTX *hdgst = s->s3->handshake_dgst[i];
1000 if ((mask & ssl_get_algorithm2(s)) == 0)
1003 hash_size = EVP_MD_size(md);
1004 if (!hdgst || hash_size < 0 || (size_t)hash_size > out_len)
1010 if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
1011 !EVP_DigestFinal_ex(&ctx, out, &digest_len) ||
1012 digest_len != (unsigned int)hash_size) /* internal error */
1018 out_len -= digest_len;
1022 EVP_MD_CTX_cleanup(&ctx);
1029 int tls1_final_finish_mac(SSL *s,
1030 const char *str, int slen, unsigned char *out)
1032 unsigned char buf[2*EVP_MAX_MD_SIZE];
1033 unsigned char buf2[12];
1037 if (s->s3->handshake_buffer)
1038 if (!ssl3_digest_cached_records(s, free_handshake_buffer))
1041 digests_len = tls1_handshake_digest(s, buf, sizeof(buf));
1042 if (digests_len < 0)
1048 if (!tls1_PRF(ssl_get_algorithm2(s),
1049 str,slen, buf, digests_len, NULL,0,
1050 s->session->master_key,s->session->master_key_length,
1051 out,buf2,sizeof buf2))
1060 int tls1_mac(SSL *ssl, unsigned char *md, int send)
1065 size_t md_size, orig_len;
1067 EVP_MD_CTX hmac, *mac_ctx;
1068 unsigned char header[13];
1073 rec= &(ssl->s3->wrec);
1074 seq= &(ssl->s3->write_sequence[0]);
1075 hash=ssl->write_hash;
1079 rec= &(ssl->s3->rrec);
1080 seq= &(ssl->s3->read_sequence[0]);
1081 hash=ssl->read_hash;
1084 t=EVP_MD_CTX_size(hash);
1088 if (!EVP_MD_CTX_copy(&hmac,hash))
1092 if (SSL_IS_DTLS(ssl))
1094 unsigned char dtlsseq[8],*p=dtlsseq;
1096 s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
1097 memcpy (p,&seq[2],6);
1099 memcpy(header, dtlsseq, 8);
1102 memcpy(header, seq, 8);
1104 /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1105 orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
1108 header[8]=rec->type;
1109 header[9]=(unsigned char)(ssl->version>>8);
1110 header[10]=(unsigned char)(ssl->version);
1111 header[11]=(rec->length)>>8;
1112 header[12]=(rec->length)&0xff;
1115 EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1116 ssl3_cbc_record_digest_supported(mac_ctx))
1118 /* This is a CBC-encrypted record. We must avoid leaking any
1119 * timing-side channel information about how many blocks of
1120 * data we are hashing because that gives an attacker a
1122 ssl3_cbc_digest_record(
1126 rec->length + md_size, orig_len,
1127 ssl->s3->read_mac_secret,
1128 ssl->s3->read_mac_secret_size,
1133 EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
1134 EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
1135 t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
1139 EVP_MD_CTX_cleanup(&hmac);
1141 if (!SSL_IS_DTLS(ssl))
1143 for (i=7; i>=0; i--)
1146 if (seq[i] != 0) break;
1153 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1156 unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1158 if (s->s3->tmp.extended_master_secret)
1160 uint8_t digests[2*EVP_MAX_MD_SIZE];
1163 if (s->s3->handshake_buffer)
1165 /* The master secret is based on the handshake hash
1166 * just after sending the ClientKeyExchange. However,
1167 * we might have a client certificate to send, in which
1168 * case we might need different hashes for the
1169 * verification and thus still need the handshake
1170 * buffer around. Keeping both a handshake buffer *and*
1171 * running hashes isn't yet supported so, when it comes
1172 * to calculating the Finished hash, we'll have to hash
1173 * the handshake buffer again. */
1174 if (!ssl3_digest_cached_records(s, dont_free_handshake_buffer))
1178 digests_len = tls1_handshake_digest(s, digests, sizeof(digests));
1180 if (digests_len == -1)
1185 tls1_PRF(ssl_get_algorithm2(s),
1186 TLS_MD_EXTENDED_MASTER_SECRET_CONST,
1187 TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
1188 digests, digests_len,
1191 s->session->master_key,
1192 buff, sizeof(buff));
1196 tls1_PRF(ssl_get_algorithm2(s),
1197 TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
1198 s->s3->client_random,SSL3_RANDOM_SIZE,
1199 s->s3->server_random,SSL3_RANDOM_SIZE,
1201 s->session->master_key,buff,sizeof buff);
1205 fprintf(stderr, "Premaster Secret:\n");
1206 BIO_dump_fp(stderr, (char *)p, len);
1207 fprintf(stderr, "Client Random:\n");
1208 BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
1209 fprintf(stderr, "Server Random:\n");
1210 BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
1211 fprintf(stderr, "Master Secret:\n");
1212 BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
1215 #ifdef OPENSSL_SSL_TRACE_CRYPTO
1216 if (s->msg_callback)
1218 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
1219 p, len, s, s->msg_callback_arg);
1220 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
1221 s->s3->client_random, SSL3_RANDOM_SIZE,
1222 s, s->msg_callback_arg);
1223 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
1224 s->s3->server_random, SSL3_RANDOM_SIZE,
1225 s, s->msg_callback_arg);
1226 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
1227 s->session->master_key,
1228 SSL3_MASTER_SECRET_SIZE,
1229 s, s->msg_callback_arg);
1233 return(SSL3_MASTER_SECRET_SIZE);
1236 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1237 const char *label, size_t llen, const unsigned char *context,
1238 size_t contextlen, int use_context)
1240 unsigned char *buff;
1241 unsigned char *val = NULL;
1242 size_t vallen, currentvalpos;
1245 buff = OPENSSL_malloc(olen);
1246 if (buff == NULL) goto err2;
1248 /* construct PRF arguments
1249 * we construct the PRF argument ourself rather than passing separate
1250 * values into the TLS PRF to ensure that the concatenation of values
1251 * does not create a prohibited label.
1253 vallen = llen + SSL3_RANDOM_SIZE * 2;
1256 vallen += 2 + contextlen;
1259 val = OPENSSL_malloc(vallen);
1260 if (val == NULL) goto err2;
1262 memcpy(val + currentvalpos, (unsigned char *) label, llen);
1263 currentvalpos += llen;
1264 memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1265 currentvalpos += SSL3_RANDOM_SIZE;
1266 memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1267 currentvalpos += SSL3_RANDOM_SIZE;
1271 val[currentvalpos] = (contextlen >> 8) & 0xff;
1273 val[currentvalpos] = contextlen & 0xff;
1275 if ((contextlen > 0) || (context != NULL))
1277 memcpy(val + currentvalpos, context, contextlen);
1281 /* disallow prohibited labels
1282 * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1283 * 15, so size of val > max(prohibited label len) = 15 and the
1284 * comparisons won't have buffer overflow
1286 if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1287 TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
1288 if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1289 TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
1290 if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1291 TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
1292 if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1293 TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
1295 rv = tls1_PRF(ssl_get_algorithm2(s),
1299 s->session->master_key,s->session->master_key_length,
1304 OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1308 OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
1311 if (buff != NULL) OPENSSL_free(buff);
1312 if (val != NULL) OPENSSL_free(val);
1316 int tls1_alert_code(int code)
1320 case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY);
1321 case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
1322 case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC);
1323 case SSL_AD_DECRYPTION_FAILED: return(TLS1_AD_DECRYPTION_FAILED);
1324 case SSL_AD_RECORD_OVERFLOW: return(TLS1_AD_RECORD_OVERFLOW);
1325 case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
1326 case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE);
1327 case SSL_AD_NO_CERTIFICATE: return(-1);
1328 case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE);
1329 case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
1330 case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
1331 case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
1332 case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
1333 case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER);
1334 case SSL_AD_UNKNOWN_CA: return(TLS1_AD_UNKNOWN_CA);
1335 case SSL_AD_ACCESS_DENIED: return(TLS1_AD_ACCESS_DENIED);
1336 case SSL_AD_DECODE_ERROR: return(TLS1_AD_DECODE_ERROR);
1337 case SSL_AD_DECRYPT_ERROR: return(TLS1_AD_DECRYPT_ERROR);
1338 case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
1339 case SSL_AD_PROTOCOL_VERSION: return(TLS1_AD_PROTOCOL_VERSION);
1340 case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
1341 case SSL_AD_INTERNAL_ERROR: return(TLS1_AD_INTERNAL_ERROR);
1342 case SSL_AD_USER_CANCELLED: return(TLS1_AD_USER_CANCELLED);
1343 case SSL_AD_NO_RENEGOTIATION: return(TLS1_AD_NO_RENEGOTIATION);
1344 case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
1345 case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1346 case SSL_AD_UNRECOGNIZED_NAME: return(TLS1_AD_UNRECOGNIZED_NAME);
1347 case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1348 case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1349 case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
1350 case SSL_AD_INAPPROPRIATE_FALLBACK:return(SSL3_AD_INAPPROPRIATE_FALLBACK);
1351 default: return(-1);