Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / third_party / boringssl / src / ssl / t1_enc.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
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.
7  *
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).
14  *
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.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
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)"
39  *
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
50  * SUCH DAMAGE.
51  *
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.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
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
70  *    distribution.
71  *
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/)"
76  *
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.
81  *
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.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
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  * ====================================================================
104  *
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).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2005 Nokia. All rights reserved.
112  *
113  * The portions of the attached software ("Contribution") is developed by
114  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
115  * license.
116  *
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.
120  *
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.
124  *
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.
129  *
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
134  * OTHERWISE. */
135
136 #include <stdio.h>
137 #include <assert.h>
138
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>
146
147 #include "ssl_locl.h"
148
149 /* seed1 through seed5 are virtually concatenated */
150 static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
151                         int sec_len,
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)
156         {
157         int chunk;
158         size_t j;
159         EVP_MD_CTX ctx, ctx_tmp, ctx_init;
160         EVP_PKEY *mac_key;
161         unsigned char A1[EVP_MAX_MD_SIZE];
162         size_t A1_len;
163         int ret = 0;
164         
165         chunk=EVP_MD_size(md);
166
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);
171         if (!mac_key)
172                 goto err;
173         if (!EVP_DigestSignInit(&ctx_init,NULL,md, NULL, mac_key))
174                 goto err;
175         if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
176                 goto err;
177         if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
178                 goto err;
179         if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
180                 goto err;
181         if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
182                 goto err;
183         A1_len = EVP_MAX_MD_SIZE;
184         if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
185                 goto err;
186
187         for (;;)
188                 {
189                 /* Reinit mac contexts */
190                 if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
191                         goto err;
192                 if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
193                         goto err;
194                 if (olen>chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp,&ctx))
195                         goto err;
196                 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
197                         goto err;
198                 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
199                         goto err;
200                 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
201                         goto err;
202
203                 if (olen > chunk)
204                         {
205                         j = olen;
206                         if (!EVP_DigestSignFinal(&ctx,out,&j))
207                                 goto err;
208                         out+=j;
209                         olen-=j;
210                         /* calc the next A1 value */
211                         A1_len = EVP_MAX_MD_SIZE;
212                         if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
213                                 goto err;
214                         }
215                 else    /* last one */
216                         {
217                         A1_len = EVP_MAX_MD_SIZE;
218                         if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
219                                 goto err;
220                         memcpy(out,A1,olen);
221                         break;
222                         }
223                 }
224         ret = 1;
225 err:
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));
231         return ret;
232         }
233
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,
240                      unsigned char *out1,
241                      unsigned char *out2, int olen)
242         {
243         int len,i,idx,count;
244         const unsigned char *S1;
245         long m;
246         const EVP_MD *md;
247         int ret = 0;
248
249         /* Count number of digests and partition sec evenly */
250         count=0;
251         for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
252                 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
253         }       
254         len=slen/count;
255         if (count == 1)
256                 slen = 0;
257         S1=sec;
258         memset(out1,0,olen);
259         for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
260                 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
261                         if (!md) {
262                                 OPENSSL_PUT_ERROR(SSL, tls1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
263                                 goto err;                               
264                         }
265                         if (!tls1_P_hash(md ,S1,len+(slen&1),
266                                         seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,
267                                         out2,olen))
268                                 goto err;
269                         S1+=len;
270                         for (i=0; i<olen; i++)
271                         {
272                                 out1[i]^=out2[i];
273                         }
274                 }
275         }
276         ret = 1;
277 err:
278         return ret;
279 }
280
281 static int tls1_generate_key_block(SSL *s, unsigned char *km,
282              unsigned char *tmp, int num)
283         {
284         int ret;
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,
290                  km,tmp,num);
291         return ret;
292         }
293
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)
297         {
298         if (*aead_ctx != NULL)
299                 EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
300         else
301                 {
302                 *aead_ctx = (SSL_AEAD_CTX*) OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
303                 if (*aead_ctx == NULL)
304                         {
305                         OPENSSL_PUT_ERROR(SSL, tls1_aead_ctx_init, ERR_R_MALLOC_FAILURE);
306                         return 0;
307                         }
308                 }
309
310         return 1;
311         }
312
313 static void tls1_cleanup_enc_ctx(EVP_CIPHER_CTX **ctx)
314         {
315         if (*ctx != NULL)
316                 EVP_CIPHER_CTX_free(*ctx);
317         *ctx = NULL;
318         }
319
320 static void tls1_cleanup_hash_ctx(EVP_MD_CTX **ctx)
321         {
322         if (*ctx != NULL)
323                 EVP_MD_CTX_destroy(*ctx);
324         *ctx = NULL;
325         }
326
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)
331         {
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 */];
338
339         if (is_read)
340                 {
341                 tls1_cleanup_enc_ctx(&s->enc_read_ctx);
342                 tls1_cleanup_hash_ctx(&s->read_hash);
343                 }
344         else
345                 {
346                 tls1_cleanup_enc_ctx(&s->enc_write_ctx);
347                 tls1_cleanup_hash_ctx(&s->write_hash);
348                 }
349
350         if (mac_secret_len > 0)
351                 {
352                 /* This is a "stateful" AEAD (for compatibility with pre-AEAD
353                  * cipher suites). */
354                 if (mac_secret_len + key_len > sizeof(mac_key_and_key))
355                         {
356                         OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
357                         return 0;
358                         }
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;
363                 }
364
365         if (is_read)
366                 {
367                 if (!tls1_aead_ctx_init(&s->aead_read_ctx))
368                         return 0;
369                 aead_ctx = s->aead_read_ctx;
370                 }
371         else
372                 {
373                 if (!tls1_aead_ctx_init(&s->aead_write_ctx))
374                         return 0;
375                 aead_ctx = s->aead_write_ctx;
376                 }
377
378         if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
379                                EVP_AEAD_DEFAULT_TAG_LENGTH, NULL /* engine */))
380                 {
381                 OPENSSL_free(aead_ctx);
382                 if (is_read)
383                         s->aead_read_ctx = NULL;
384                 else
385                         s->aead_write_ctx = NULL;
386                 return 0;
387                 }
388         if (iv_len > sizeof(aead_ctx->fixed_nonce))
389                 {
390                 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
391                 return 0;
392                 }
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))
401                 {
402                 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
403                 return 0;
404                 }
405         aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
406
407         return 1;
408         }
409
410 static void tls1_cleanup_aead_ctx(SSL_AEAD_CTX **ctx)
411         {
412         if (*ctx != NULL)
413                 {
414                 EVP_AEAD_CTX_cleanup(&(*ctx)->ctx);
415                 OPENSSL_free(*ctx);
416                 }
417         *ctx = NULL;
418         }
419
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)
431         {
432         const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
433         EVP_CIPHER_CTX *cipher_ctx;
434         EVP_MD_CTX *mac_ctx;
435
436         if (is_read)
437                 tls1_cleanup_aead_ctx(&s->aead_read_ctx);
438         else
439                 tls1_cleanup_aead_ctx(&s->aead_write_ctx);
440
441         if (is_read)
442                 {
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)
446                         goto err;
447
448                 cipher_ctx = s->enc_read_ctx;
449                 mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
450
451                 memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
452                 s->s3->read_mac_secret_size = mac_secret_len;
453                 }
454         else
455                 {
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. */
459
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)
463                         goto err;
464                 else
465                         /* make sure it's intialized in case we exit later with an error */
466                         EVP_CIPHER_CTX_init(s->enc_write_ctx);
467
468                 cipher_ctx = s->enc_write_ctx;
469                 if (SSL_IS_DTLS(s))
470                         {
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();
474                         if (!mac_ctx)
475                                 goto err;
476                         s->write_hash = mac_ctx;
477                         }
478                 else
479                         mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
480
481                 memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
482                 s->s3->write_mac_secret_size = mac_secret_len;
483                 }
484
485         EVP_PKEY *mac_key =
486                 EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
487                                      NULL, mac_secret, mac_secret_len);
488         if (!mac_key)
489                 return 0;
490         EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
491         EVP_PKEY_free(mac_key);
492
493         EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
494
495         return 1;
496
497 err:
498         OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_cipher, ERR_R_MALLOC_FAILURE);
499         return 0;
500         }
501
502 int tls1_change_cipher_state(SSL *s, int which)
503         {
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
506          * written one. */
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;
520
521         /* Reset sequence number to zero. */
522         if (!SSL_IS_DTLS(s))
523                 memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
524
525         mac_secret_len = s->s3->tmp.new_mac_secret_size;
526
527         if (aead != NULL)
528                 {
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)
534                         {
535                         OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
536                         return 0;
537                         }
538                 key_len -= mac_secret_len;
539                 iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
540                 }
541         else
542                 {
543                 key_len = EVP_CIPHER_key_length(cipher);
544                 iv_len = EVP_CIPHER_iv_length(cipher);
545                 }
546
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;
554
555         if (use_client_keys)
556                 {
557                 mac_secret = client_write_mac_secret;
558                 key = client_write_key;
559                 iv = client_write_iv;
560                 }
561         else
562                 {
563                 mac_secret = server_write_mac_secret;
564                 key = server_write_key;
565                 iv = server_write_iv;
566                 }
567
568         if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
569                 {
570                 OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
571                 return 0;
572                 }
573
574         if (aead != NULL)
575                 {
576                 if (!tls1_change_cipher_state_aead(s, is_read,
577                                                    key, key_len, iv, iv_len,
578                                                    mac_secret, mac_secret_len))
579                         return 0;
580                 }
581         else
582                 {
583                 if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
584                                                      mac_secret, mac_secret_len,
585                                                      key, key_len,
586                                                      iv, iv_len))
587                         return 0;
588                 }
589
590         return 1;
591         }
592
593 int tls1_setup_key_block(SSL *s)
594         {
595         unsigned char *p1,*p2=NULL;
596         const EVP_CIPHER *c = NULL;
597         const EVP_MD *hash = NULL;
598         const EVP_AEAD *aead = NULL;
599         int num;
600         int mac_type= NID_undef,mac_secret_size=0;
601         int ret=0;
602         unsigned key_len, iv_len;
603
604
605         if (s->s3->tmp.key_block_length != 0)
606                 return(1);
607
608         if (s->session->cipher &&
609             ((s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD) ||
610              (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)))
611                 {
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)
624                         {
625                         OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
626                         return 0;
627                         }
628                 key_len -= mac_secret_size;
629                 }
630         else
631                 {
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);
636                 }
637
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;
643
644         num=key_len+mac_secret_size+iv_len;
645         num*=2;
646
647         ssl3_cleanup_key_block(s);
648
649         if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
650                 {
651                 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
652                 goto err;
653                 }
654
655         s->s3->tmp.key_block_length=num;
656         s->s3->tmp.key_block=p1;
657
658         if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
659                 {
660                 OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
661                 goto err;
662                 }
663
664 #ifdef TLS_DEBUG
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'); }
671 #endif
672         if (!tls1_generate_key_block(s,p1,p2,num))
673                 goto err;
674 #ifdef TLS_DEBUG
675 printf("\nkey block\n");
676 { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
677 #endif
678
679         if (s->method->version <= TLS1_VERSION &&
680             (s->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0)
681                 {
682                 /* enable vulnerability countermeasure for CBC ciphers with
683                  * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
684                  */
685                 s->s3->need_record_splitting = 1;
686
687                 if (s->session->cipher != NULL)
688                         {
689                         if (s->session->cipher->algorithm_enc == SSL_RC4)
690                                 s->s3->need_record_splitting = 0;
691                         }
692                 }
693                 
694         ret = 1;
695 err:
696         if (p2)
697                 {
698                 OPENSSL_cleanse(p2,num);
699                 OPENSSL_free(p2);
700                 }
701         return(ret);
702
703 cipher_unavailable_err:
704         OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
705         return 0;
706         }
707
708 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
709  *
710  * Returns:
711  *   0: (in non-constant time) if the record is publically invalid (i.e. too
712  *       short etc).
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.
716  */
717 int tls1_enc(SSL *s, int send)
718         {
719         SSL3_RECORD *rec;
720         EVP_CIPHER_CTX *ds;
721         unsigned long l;
722         int bs,i,j,k,pad=0,ret,mac_size=0;
723         const EVP_CIPHER *enc;
724         const SSL_AEAD_CTX *aead;
725
726         if (send)
727                 rec = &s->s3->wrec;
728         else
729                 rec = &s->s3->rrec;
730
731         if (send)
732                 aead = s->aead_write_ctx;
733         else
734                 aead = s->aead_read_ctx;
735
736         if (aead)
737                 {
738                 unsigned char ad[13], *seq, *in, *out, nonce[16];
739                 unsigned nonce_used;
740                 size_t n;
741
742                 seq = send ? s->s3->write_sequence : s->s3->read_sequence;
743
744                 if (SSL_IS_DTLS(s))
745                         {
746                         unsigned char dtlsseq[9], *p = dtlsseq;
747
748                         s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
749                         memcpy(p, &seq[2], 6);
750                         memcpy(ad, dtlsseq, 8);
751                         }
752                 else
753                         {
754                         memcpy(ad, seq, 8);
755                         for (i=7; i>=0; i--)    /* increment */
756                                 {
757                                 ++seq[i];
758                                 if (seq[i] != 0)
759                                         break;
760                                 }
761                         }
762
763                 ad[8]  = rec->type;
764                 ad[9]  = (unsigned char)(s->version>>8);
765                 ad[10] = (unsigned char)(s->version);
766
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. */
770
771                 memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
772                 nonce_used = aead->fixed_nonce_len;
773
774                 if (send)
775                         {
776                         size_t len = rec->length;
777                         size_t eivlen = 0;
778                         in = rec->input;
779                         out = rec->data;
780
781                         /* When sending we use the sequence number as the
782                          * variable part of the nonce. */
783                         if (aead->variable_nonce_len > 8)
784                                 return -1;
785                         memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
786                         nonce_used += aead->variable_nonce_len;
787
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
792                          * plaintext. */
793                         if (aead->variable_nonce_included_in_record)
794                                 {
795                                 memcpy(out, ad, aead->variable_nonce_len);
796                                 len -= aead->variable_nonce_len;
797                                 eivlen = aead->variable_nonce_len;
798                                 }
799
800                         ad[11] = len >> 8;
801                         ad[12] = len & 0xff;
802
803                         if (!EVP_AEAD_CTX_seal(
804                                 &aead->ctx,
805                                 out + eivlen, &n, len + aead->tag_len,
806                                 nonce, nonce_used,
807                                 in + eivlen, len,
808                                 ad, sizeof(ad)))
809                                 {
810                                 return -1;
811                                 }
812                         if (aead->variable_nonce_included_in_record)
813                                 n += aead->variable_nonce_len;
814                         }
815                 else
816                         {
817                         /* receive */
818                         size_t len = rec->length;
819
820                         if (rec->data != rec->input)
821                                 return -1;  /* internal error - should never happen. */
822                         out = in = rec->input;
823
824                         if (len < aead->variable_nonce_len)
825                                 return 0;
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;
830
831                         if (aead->variable_nonce_included_in_record)
832                                 {
833                                 in += aead->variable_nonce_len;
834                                 len -= aead->variable_nonce_len;
835                                 out += aead->variable_nonce_len;
836                                 }
837
838                         if (len < aead->tag_len)
839                                 return 0;
840                         len -= aead->tag_len;
841
842                         ad[11] = len >> 8;
843                         ad[12] = len & 0xff;
844
845                         if (!EVP_AEAD_CTX_open(
846                                 &aead->ctx,
847                                 out, &n, len,
848                                 nonce, nonce_used,
849                                 in, len + aead->tag_len,
850                                 ad, sizeof(ad)))
851                                 {
852                                 return -1;
853                                 }
854
855                         rec->data = rec->input = out;
856                         }
857
858                 rec->length = n;
859                 return 1;
860                 }
861
862         if (send)
863                 {
864                 ds=s->enc_write_ctx;
865                 rec= &(s->s3->wrec);
866                 if (s->enc_write_ctx == NULL)
867                         enc=NULL;
868                 else
869                         {
870                         int ivlen;
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);
876                         else
877                                 ivlen = 0;
878                         if (ivlen > 1)
879                                 {
880                                 if ( rec->data != rec->input)
881                                         /* we can't write into the input stream:
882                                          * Can this ever happen?? (steve)
883                                          */
884                                         fprintf(stderr,
885                                                 "%s:%d: rec->data != rec->input\n",
886                                                 __FILE__, __LINE__);
887                                 else if (RAND_bytes(rec->input, ivlen) <= 0)
888                                         return -1;
889                                 }
890                         }
891                 }
892         else
893                 {
894                 ds=s->enc_read_ctx;
895                 rec= &(s->s3->rrec);
896                 if (s->enc_read_ctx == NULL)
897                         enc=NULL;
898                 else
899                         enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
900                 }
901
902         if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
903                 {
904                 memmove(rec->data,rec->input,rec->length);
905                 rec->input=rec->data;
906                 ret = 1;
907                 }
908         else
909                 {
910                 l=rec->length;
911                 bs=EVP_CIPHER_block_size(ds->cipher);
912
913                 if ((bs != 1) && send)
914                         {
915                         i=bs-((int)l%bs);
916
917                         /* Add weird padding of upto 256 bytes */
918
919                         /* we need to add 'i' padding bytes of value j */
920                         j=i-1;
921                         for (k=(int)l; k<(int)(l+i); k++)
922                                 rec->input[k]=j;
923                         l+=i;
924                         rec->length+=i;
925                         }
926
927                 if (!send)
928                         {
929                         if (l == 0 || l%bs != 0)
930                                 return 0;
931                         }
932                 
933                 i = EVP_Cipher(ds,rec->data,rec->input,l);
934                 if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
935                                                 ?(i<0)
936                                                 :(i==0))
937                         return -1;      /* AEAD can fail to verify MAC */
938
939                 ret = 1;
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);
944                 if (pad && !send)
945                         rec->length -= pad;
946                 }
947         return ret;
948         }
949
950 int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
951         {
952         unsigned int ret;
953         EVP_MD_CTX ctx, *d=NULL;
954         int i;
955
956         if (s->s3->handshake_buffer)
957                 if (!ssl3_digest_cached_records(s, free_handshake_buffer))
958                         return 0;
959
960         for (i=0;i<SSL_MAX_DIGEST;i++) 
961                 {
962                   if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid) 
963                         {
964                         d=s->s3->handshake_dgst[i];
965                         break;
966                         }
967                 }
968         if (!d) {
969                 OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
970                 return 0;
971         }       
972
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);
977         return((int)ret);
978         }
979
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
984  * update etc. */
985 int tls1_handshake_digest(SSL *s, unsigned char *out, size_t out_len)
986         {
987         const EVP_MD *md;
988         EVP_MD_CTX ctx;
989         int i, err = 0, len = 0;
990         long mask;
991
992         EVP_MD_CTX_init(&ctx);
993
994         for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++)
995                 {
996                 int hash_size;
997                 unsigned int digest_len;
998                 EVP_MD_CTX *hdgst = s->s3->handshake_dgst[i];
999
1000                 if ((mask & ssl_get_algorithm2(s)) == 0)
1001                         continue;
1002
1003                 hash_size = EVP_MD_size(md);
1004                 if (!hdgst || hash_size < 0 || (size_t)hash_size > out_len)
1005                         {
1006                         err = 1;
1007                         break;
1008                         }
1009
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 */
1013                         {
1014                         err = 1;
1015                         break;
1016                         }
1017                 out += digest_len;
1018                 out_len -= digest_len;
1019                 len += digest_len;
1020                 }
1021
1022         EVP_MD_CTX_cleanup(&ctx);
1023
1024         if (err != 0)
1025                 return -1;
1026         return len;
1027         }
1028
1029 int tls1_final_finish_mac(SSL *s,
1030              const char *str, int slen, unsigned char *out)
1031         {
1032         unsigned char buf[2*EVP_MAX_MD_SIZE];
1033         unsigned char buf2[12];
1034         int err=0;
1035         int digests_len;
1036
1037         if (s->s3->handshake_buffer)
1038                 if (!ssl3_digest_cached_records(s, free_handshake_buffer))
1039                         return 0;
1040
1041         digests_len = tls1_handshake_digest(s, buf, sizeof(buf));
1042         if (digests_len < 0)
1043                 {
1044                 err = 1;
1045                 digests_len = 0;
1046                 }
1047                 
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))
1052                 err = 1;
1053
1054         if (err)
1055                 return 0;
1056         else
1057                 return sizeof buf2;
1058         }
1059
1060 int tls1_mac(SSL *ssl, unsigned char *md, int send)
1061         {
1062         SSL3_RECORD *rec;
1063         unsigned char *seq;
1064         EVP_MD_CTX *hash;
1065         size_t md_size, orig_len;
1066         int i;
1067         EVP_MD_CTX hmac, *mac_ctx;
1068         unsigned char header[13];
1069         int t;
1070
1071         if (send)
1072                 {
1073                 rec= &(ssl->s3->wrec);
1074                 seq= &(ssl->s3->write_sequence[0]);
1075                 hash=ssl->write_hash;
1076                 }
1077         else
1078                 {
1079                 rec= &(ssl->s3->rrec);
1080                 seq= &(ssl->s3->read_sequence[0]);
1081                 hash=ssl->read_hash;
1082                 }
1083
1084         t=EVP_MD_CTX_size(hash);
1085         assert(t >= 0);
1086         md_size=t;
1087
1088         if (!EVP_MD_CTX_copy(&hmac,hash))
1089                 return -1;
1090         mac_ctx = &hmac;
1091
1092         if (SSL_IS_DTLS(ssl))
1093                 {
1094                 unsigned char dtlsseq[8],*p=dtlsseq;
1095
1096                 s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
1097                 memcpy (p,&seq[2],6);
1098
1099                 memcpy(header, dtlsseq, 8);
1100                 }
1101         else
1102                 memcpy(header, seq, 8);
1103
1104         /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1105         orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
1106         rec->type &= 0xff;
1107
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;
1113
1114         if (!send &&
1115             EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1116             ssl3_cbc_record_digest_supported(mac_ctx))
1117                 {
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
1121                  * timing-oracle. */
1122                 ssl3_cbc_digest_record(
1123                         mac_ctx,
1124                         md, &md_size,
1125                         header, rec->input,
1126                         rec->length + md_size, orig_len,
1127                         ssl->s3->read_mac_secret,
1128                         ssl->s3->read_mac_secret_size,
1129                         0 /* not SSLv3 */);
1130                 }
1131         else
1132                 {
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);
1136                 assert(t > 0);
1137                 }
1138                 
1139         EVP_MD_CTX_cleanup(&hmac);
1140
1141         if (!SSL_IS_DTLS(ssl))
1142                 {
1143                 for (i=7; i>=0; i--)
1144                         {
1145                         ++seq[i];
1146                         if (seq[i] != 0) break; 
1147                         }
1148                 }
1149
1150         return(md_size);
1151         }
1152
1153 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1154              int len)
1155         {
1156         unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1157
1158         if (s->s3->tmp.extended_master_secret)
1159                 {
1160                 uint8_t digests[2*EVP_MAX_MD_SIZE];
1161                 int digests_len;
1162
1163                 if (s->s3->handshake_buffer)
1164                         {
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))
1175                                 return 0;
1176                         }
1177
1178                 digests_len = tls1_handshake_digest(s, digests, sizeof(digests));
1179
1180                 if (digests_len == -1)
1181                         {
1182                         return 0;
1183                         }
1184
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,
1189                         NULL, 0,
1190                         p, len,
1191                         s->session->master_key,
1192                         buff, sizeof(buff));
1193                 }
1194         else
1195                 {
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,
1200                         p, len,
1201                         s->session->master_key,buff,sizeof buff);
1202                 }
1203
1204 #ifdef SSL_DEBUG
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);
1213 #endif
1214
1215 #ifdef OPENSSL_SSL_TRACE_CRYPTO
1216         if (s->msg_callback)
1217                 {
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);
1230                 }
1231 #endif
1232
1233         return(SSL3_MASTER_SECRET_SIZE);
1234         }
1235
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)
1239         {
1240         unsigned char *buff;
1241         unsigned char *val = NULL;
1242         size_t vallen, currentvalpos;
1243         int rv;
1244
1245         buff = OPENSSL_malloc(olen);
1246         if (buff == NULL) goto err2;
1247
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.
1252          */
1253         vallen = llen + SSL3_RANDOM_SIZE * 2;
1254         if (use_context)
1255                 {
1256                 vallen += 2 + contextlen;
1257                 }
1258
1259         val = OPENSSL_malloc(vallen);
1260         if (val == NULL) goto err2;
1261         currentvalpos = 0;
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;
1268
1269         if (use_context)
1270                 {
1271                 val[currentvalpos] = (contextlen >> 8) & 0xff;
1272                 currentvalpos++;
1273                 val[currentvalpos] = contextlen & 0xff;
1274                 currentvalpos++;
1275                 if ((contextlen > 0) || (context != NULL))
1276                         {
1277                         memcpy(val + currentvalpos, context, contextlen);
1278                         }
1279                 }
1280
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
1285          */
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;
1294
1295         rv = tls1_PRF(ssl_get_algorithm2(s),
1296                       val, vallen,
1297                       NULL, 0,
1298                       NULL, 0,
1299                       s->session->master_key,s->session->master_key_length,
1300                       out,buff,olen);
1301
1302         goto ret;
1303 err1:
1304         OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1305         rv = 0;
1306         goto ret;
1307 err2:
1308         OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
1309         rv = 0;
1310 ret:
1311         if (buff != NULL) OPENSSL_free(buff);
1312         if (val != NULL) OPENSSL_free(val);
1313         return(rv);
1314         }
1315
1316 int tls1_alert_code(int code)
1317         {
1318         switch (code)
1319                 {
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);
1352                 }
1353         }