Rework tls1_change_cipher_state.
[openssl.git] / ssl / t1_enc.c
1 /* ssl/t1_enc.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2005 Nokia. All rights reserved.
113  *
114  * The portions of the attached software ("Contribution") is developed by
115  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116  * license.
117  *
118  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120  * support (see RFC 4279) to OpenSSL.
121  *
122  * No patent licenses or other rights except those expressly stated in
123  * the OpenSSL open source license shall be deemed granted or received
124  * expressly, by implication, estoppel, or otherwise.
125  *
126  * No assurances are provided by Nokia that the Contribution does not
127  * infringe the patent or other intellectual property rights of any third
128  * party or that the license provides you with all the necessary rights
129  * to make use of the Contribution.
130  *
131  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135  * OTHERWISE.
136  */
137
138 #include <stdio.h>
139 #include "ssl_locl.h"
140 #ifndef OPENSSL_NO_COMP
141 #include <openssl/comp.h>
142 #endif
143 #include <openssl/evp.h>
144 #include <openssl/hmac.h>
145 #include <openssl/md5.h>
146 #include <openssl/rand.h>
147 #ifdef KSSL_DEBUG
148 #include <openssl/des.h>
149 #endif
150
151 /* seed1 through seed5 are virtually concatenated */
152 static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
153                         int sec_len,
154                         const void *seed1, int seed1_len,
155                         const void *seed2, int seed2_len,
156                         const void *seed3, int seed3_len,
157                         const void *seed4, int seed4_len,
158                         const void *seed5, int seed5_len,
159                         unsigned char *out, int olen)
160         {
161         int chunk;
162         size_t j;
163         EVP_MD_CTX ctx, ctx_tmp;
164         EVP_PKEY *mac_key;
165         unsigned char A1[EVP_MAX_MD_SIZE];
166         size_t A1_len;
167         int ret = 0;
168         
169         chunk=EVP_MD_size(md);
170         OPENSSL_assert(chunk >= 0);
171
172         EVP_MD_CTX_init(&ctx);
173         EVP_MD_CTX_init(&ctx_tmp);
174         EVP_MD_CTX_set_flags(&ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
175         EVP_MD_CTX_set_flags(&ctx_tmp, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
176         mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
177         if (!mac_key)
178                 goto err;
179         if (!EVP_DigestSignInit(&ctx,NULL,md, NULL, mac_key))
180                 goto err;
181         if (!EVP_DigestSignInit(&ctx_tmp,NULL,md, NULL, mac_key))
182                 goto err;
183         if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
184                 goto err;
185         if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
186                 goto err;
187         if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
188                 goto err;
189         if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
190                 goto err;
191         if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
192                 goto err;
193         if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
194                 goto err;
195
196         for (;;)
197                 {
198                 /* Reinit mac contexts */
199                 if (!EVP_DigestSignInit(&ctx,NULL,md, NULL, mac_key))
200                         goto err;
201                 if (!EVP_DigestSignInit(&ctx_tmp,NULL,md, NULL, mac_key))
202                         goto err;
203                 if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
204                         goto err;
205                 if (!EVP_DigestSignUpdate(&ctx_tmp,A1,A1_len))
206                         goto err;
207                 if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
208                         goto err;
209                 if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
210                         goto err;
211                 if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
212                         goto err;
213                 if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
214                         goto err;
215                 if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
216                         goto err;
217
218                 if (olen > chunk)
219                         {
220                         if (!EVP_DigestSignFinal(&ctx,out,&j))
221                                 goto err;
222                         out+=j;
223                         olen-=j;
224                         /* calc the next A1 value */
225                         if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
226                                 goto err;
227                         }
228                 else    /* last one */
229                         {
230                         if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
231                                 goto err;
232                         memcpy(out,A1,olen);
233                         break;
234                         }
235                 }
236         ret = 1;
237 err:
238         EVP_PKEY_free(mac_key);
239         EVP_MD_CTX_cleanup(&ctx);
240         EVP_MD_CTX_cleanup(&ctx_tmp);
241         OPENSSL_cleanse(A1,sizeof(A1));
242         return ret;
243         }
244
245 /* seed1 through seed5 are virtually concatenated */
246 static int tls1_PRF(long digest_mask,
247                      const void *seed1, int seed1_len,
248                      const void *seed2, int seed2_len,
249                      const void *seed3, int seed3_len,
250                      const void *seed4, int seed4_len,
251                      const void *seed5, int seed5_len,
252                      const unsigned char *sec, int slen,
253                      unsigned char *out1,
254                      unsigned char *out2, int olen)
255         {
256         int len,i,idx,count;
257         const unsigned char *S1;
258         long m;
259         const EVP_MD *md;
260         int ret = 0;
261
262         /* Count number of digests and partition sec evenly */
263         count=0;
264         for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
265                 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
266         }       
267         len=slen/count;
268         if (count == 1)
269                 slen = 0;
270         S1=sec;
271         memset(out1,0,olen);
272         for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
273                 if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
274                         if (!md) {
275                                 SSLerr(SSL_F_TLS1_PRF,
276                                 SSL_R_UNSUPPORTED_DIGEST_TYPE);
277                                 goto err;                               
278                         }
279                         if (!tls1_P_hash(md ,S1,len+(slen&1),
280                                         seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,seed4,seed4_len,seed5,seed5_len,
281                                         out2,olen))
282                                 goto err;
283                         S1+=len;
284                         for (i=0; i<olen; i++)
285                         {
286                                 out1[i]^=out2[i];
287                         }
288                 }
289         }
290         ret = 1;
291 err:
292         return ret;
293 }
294 static int tls1_generate_key_block(SSL *s, unsigned char *km,
295              unsigned char *tmp, int num)
296         {
297         int ret;
298         ret = tls1_PRF(ssl_get_algorithm2(s),
299                  TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE,
300                  s->s3->server_random,SSL3_RANDOM_SIZE,
301                  s->s3->client_random,SSL3_RANDOM_SIZE,
302                  NULL,0,NULL,0,
303                  s->session->master_key,s->session->master_key_length,
304                  km,tmp,num);
305 #ifdef KSSL_DEBUG
306         printf("tls1_generate_key_block() ==> %d byte master_key =\n\t",
307                 s->session->master_key_length);
308         {
309         int i;
310         for (i=0; i < s->session->master_key_length; i++)
311                 {
312                 printf("%02X", s->session->master_key[i]);
313                 }
314         printf("\n");  }
315 #endif    /* KSSL_DEBUG */
316         return ret;
317         }
318
319 /* tls1_change_cipher_state_cipher performs the work needed to switch cipher
320  * states when using EVP_CIPHER. The argument |is_read| is true iff this
321  * function is being called due to reading, as opposed to writing, a
322  * ChangeCipherSpec message. In order to support export ciphersuites,
323  * use_client_keys indicates whether the key material provided is in the
324  * "client write" direction. */
325 static int tls1_change_cipher_state_cipher(SSL *s,
326         char is_read, char use_client_keys,
327         const unsigned char *mac_secret, unsigned mac_secret_len,
328         const unsigned char *key, unsigned key_len,
329         const unsigned char *iv, unsigned iv_len)
330         {
331         const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
332         const char is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) != 0;
333         EVP_CIPHER_CTX *cipher_ctx;
334         EVP_MD_CTX *mac_ctx;
335         char is_aead_cipher;
336
337         unsigned char export_tmp1[EVP_MAX_KEY_LENGTH];
338         unsigned char export_tmp2[EVP_MAX_KEY_LENGTH];
339         unsigned char export_iv1[EVP_MAX_IV_LENGTH * 2];
340         unsigned char export_iv2[EVP_MAX_IV_LENGTH * 2];
341
342         if (is_read)
343                 {
344                 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
345                         s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
346                 else
347                         s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
348
349                 if (s->enc_read_ctx != NULL)
350                         EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
351                 else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
352                         goto err;
353                 else
354                         /* make sure it's intialized in case we exit later with an error */
355                         EVP_CIPHER_CTX_init(s->enc_read_ctx);
356
357                 cipher_ctx = s->enc_read_ctx;
358                 mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
359
360                 memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
361                 s->s3->read_mac_secret_size = mac_secret_len;
362                 }
363         else
364                 {
365                 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
366                         s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
367                 else
368                         s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
369
370                 if (s->enc_write_ctx != NULL)
371                         EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
372                 else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
373                         goto err;
374                 else
375                         /* make sure it's intialized in case we exit later with an error */
376                         EVP_CIPHER_CTX_init(s->enc_write_ctx);
377
378                 cipher_ctx = s->enc_write_ctx;
379                 mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
380
381                 memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
382                 s->s3->write_mac_secret_size = mac_secret_len;
383                 }
384
385         if (is_export)
386                 {
387                 /* In here I set both the read and write key/iv to the
388                  * same value since only the correct one will be used :-).
389                  */
390                 const unsigned char *label;
391                 unsigned label_len;
392
393                 if (use_client_keys)
394                         {
395                         label = (const unsigned char*) TLS_MD_CLIENT_WRITE_KEY_CONST;
396                         label_len = TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
397                         }
398                 else
399                         {
400                         label = (const unsigned char*) TLS_MD_SERVER_WRITE_KEY_CONST;
401                         label_len = TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
402                         }
403
404                 if (!tls1_PRF(ssl_get_algorithm2(s),
405                                 label, label_len,
406                                 s->s3->client_random, SSL3_RANDOM_SIZE,
407                                 s->s3->server_random, SSL3_RANDOM_SIZE,
408                                 NULL, 0, NULL, 0,
409                                 key /* secret */, key_len /* secret length */,
410                                 export_tmp1 /* output */,
411                                 export_tmp2 /* scratch space */,
412                                 EVP_CIPHER_key_length(s->s3->tmp.new_sym_enc) /* output length */))
413                         return 0;
414                 key = export_tmp1;
415
416                 if (iv_len > 0)
417                         {
418                         static const unsigned char empty[] = "";
419
420                         if (!tls1_PRF(ssl_get_algorithm2(s),
421                                         TLS_MD_IV_BLOCK_CONST, TLS_MD_IV_BLOCK_CONST_SIZE,
422                                         s->s3->client_random, SSL3_RANDOM_SIZE,
423                                         s->s3->server_random, SSL3_RANDOM_SIZE,
424                                         NULL, 0, NULL, 0,
425                                         empty /* secret */ ,0 /* secret length */,
426                                         export_iv1 /* output */,
427                                         export_iv2 /* scratch space */,
428                                         iv_len * 2 /* output length */))
429                                 return 0;
430
431                         if (use_client_keys)
432                                 iv = export_iv1;
433                         else
434                                 iv = &export_iv1[iv_len];
435                         }
436                 }
437
438         /* is_aead_cipher indicates whether the EVP_CIPHER implements an AEAD
439          * interface. This is different from the newer EVP_AEAD interface. */
440         is_aead_cipher = (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0;
441
442         if (!is_aead_cipher)
443                 {
444                 EVP_PKEY *mac_key =
445                         EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
446                                              NULL, mac_secret, mac_secret_len);
447                 if (!mac_key)
448                         return 0;
449                 EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
450                 EVP_PKEY_free(mac_key);
451                 }
452
453         if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
454                 {
455                 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key,
456                                   NULL /* iv */, !is_read);
457                 EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GCM_SET_IV_FIXED, iv_len, (void*) iv);
458                 }
459         else
460                 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
461
462         /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
463         if (is_aead_cipher && mac_secret_len > 0)
464                 EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
465                                     mac_secret_len, (void*) mac_secret);
466
467         if (is_export)
468                 {
469                 OPENSSL_cleanse(export_tmp1, sizeof(export_tmp1));
470                 OPENSSL_cleanse(export_tmp2, sizeof(export_tmp1));
471                 OPENSSL_cleanse(export_iv1, sizeof(export_iv1));
472                 OPENSSL_cleanse(export_iv2, sizeof(export_iv2));
473                 }
474
475         return 1;
476
477 err:
478         SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_CIPHER, ERR_R_MALLOC_FAILURE);
479         return 0;
480         }
481
482 int tls1_change_cipher_state(SSL *s, int which)
483         {
484         /* is_read is true if we have just read a ChangeCipherSpec message -
485          * i.e. we need to update the read cipherspec. Otherwise we have just
486          * written one. */
487         const char is_read = (which & SSL3_CC_READ) != 0;
488         /* use_client_keys is true if we wish to use the keys for the "client
489          * write" direction. This is the case if we're a client sending a
490          * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec. */
491         const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
492                                      which == SSL3_CHANGE_CIPHER_SERVER_READ;
493         const unsigned char *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
494         const unsigned char *client_write_key, *server_write_key, *key;
495         const unsigned char *client_write_iv, *server_write_iv, *iv;
496         const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
497         unsigned key_len, iv_len, mac_secret_len;
498         const unsigned char *key_data;
499         const char is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) != 0;
500
501         /* Update compression contexts. */
502 #ifndef OPENSSL_NO_COMP
503         const SSL_COMP *comp = s->s3->tmp.new_compression;
504
505         if (is_read)
506                 {
507                 if (s->expand != NULL)
508                         {
509                         COMP_CTX_free(s->expand);
510                         s->expand = NULL;
511                         }
512                 if (comp != NULL)
513                         {
514                         s->expand=COMP_CTX_new(comp->method);
515                         if (s->expand == NULL)
516                                 {
517                                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
518                                 return 0;
519                                 }
520                         if (s->s3->rrec.comp == NULL)
521                                 s->s3->rrec.comp =
522                                         (unsigned char *)OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
523                         if (s->s3->rrec.comp == NULL)
524                                 goto err;
525                         }
526                 }
527         else
528                 {
529                 if (s->compress != NULL)
530                         {
531                         COMP_CTX_free(s->compress);
532                         s->compress = NULL;
533                         }
534                 if (comp != NULL)
535                         {
536                         s->compress = COMP_CTX_new(comp->method);
537                         if (s->compress == NULL)
538                                 {
539                                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
540                                 return 0;
541                                 }
542                         }
543                 }
544 #endif  /* OPENSSL_NO_COMP */
545
546         /* Reset sequence number to zero. */
547         memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
548
549         /* key_arg is used for SSLv2. We don't need it for TLS. */
550         s->session->key_arg_length = 0;
551
552         mac_secret_len = s->s3->tmp.new_mac_secret_size;
553
554         key_len = EVP_CIPHER_key_length(cipher);
555         if (is_export && key_len > SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher))
556                 key_len = SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher);
557
558         if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
559                 iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
560         else
561                 iv_len = EVP_CIPHER_iv_length(cipher);
562
563         key_data = s->s3->tmp.key_block;
564         client_write_mac_secret = key_data; key_data += mac_secret_len;
565         server_write_mac_secret = key_data; key_data += mac_secret_len;
566         client_write_key =        key_data; key_data += key_len;
567         server_write_key =        key_data; key_data += key_len;
568         client_write_iv  =        key_data; key_data += iv_len;
569         server_write_iv  =        key_data; key_data += iv_len;
570
571         if (use_client_keys)
572                 {
573                 mac_secret = client_write_mac_secret;
574                 key = client_write_key;
575                 iv = client_write_iv;
576                 }
577         else
578                 {
579                 mac_secret = server_write_mac_secret;
580                 key = server_write_key;
581                 iv = server_write_iv;
582                 }
583
584         if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
585                 {
586                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR);
587                 return 0;
588                 }
589
590         if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
591                                              mac_secret, mac_secret_len,
592                                              key, key_len,
593                                              iv, iv_len)) {
594                 return 0;
595         }
596
597 #ifdef OPENSSL_SSL_TRACE_CRYPTO
598         if (s->msg_callback)
599                 {
600                 int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
601                 if (mac_secret_len)
602                         s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
603                                                 mac_secret, mac_secret_len,
604                                                 s, s->msg_callback_arg);
605                 if (key_len)
606                         s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
607                                                 key, key_len,
608                                                 s, s->msg_callback_arg);
609                 if (iv_len)
610                         {
611                         if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
612                                 wh |= TLS1_RT_CRYPTO_FIXED_IV;
613                         else
614                                 wh |= TLS1_RT_CRYPTO_IV;
615                         s->msg_callback(2, s->version, wh, iv, iv_len,
616                                                 s, s->msg_callback_arg);
617                         }
618                 }
619 #endif
620
621         return 1;
622 err:
623         SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
624         return 0;
625         }
626
627 int tls1_setup_key_block(SSL *s)
628         {
629         unsigned char *p1,*p2=NULL;
630         const EVP_CIPHER *c;
631         const EVP_MD *hash;
632         int num;
633         SSL_COMP *comp;
634         int mac_type= NID_undef,mac_secret_size=0;
635         int ret=0;
636         int iv_len;
637
638 #ifdef KSSL_DEBUG
639         printf ("tls1_setup_key_block()\n");
640 #endif  /* KSSL_DEBUG */
641
642         if (s->s3->tmp.key_block_length != 0)
643                 return(1);
644
645         if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size,&comp))
646                 {
647                 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
648                 return(0);
649                 }
650
651         if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
652                 iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
653         else
654                 iv_len = EVP_CIPHER_iv_length(c);
655
656         s->s3->tmp.new_sym_enc=c;
657         s->s3->tmp.new_hash=hash;
658         s->s3->tmp.new_mac_pkey_type = mac_type;
659         s->s3->tmp.new_mac_secret_size = mac_secret_size;
660         num=EVP_CIPHER_key_length(c)+mac_secret_size+iv_len;
661         num*=2;
662
663         ssl3_cleanup_key_block(s);
664
665         if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
666                 {
667                 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE);
668                 goto err;
669                 }
670
671         s->s3->tmp.key_block_length=num;
672         s->s3->tmp.key_block=p1;
673
674         if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
675                 {
676                 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE);
677                 goto err;
678                 }
679
680 #ifdef TLS_DEBUG
681 printf("client random\n");
682 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
683 printf("server random\n");
684 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
685 printf("pre-master\n");
686 { int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
687 #endif
688         if (!tls1_generate_key_block(s,p1,p2,num))
689                 goto err;
690 #ifdef TLS_DEBUG
691 printf("\nkey block\n");
692 { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
693 #endif
694
695         if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
696                 && s->method->version <= TLS1_VERSION)
697                 {
698                 /* enable vulnerability countermeasure for CBC ciphers with
699                  * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
700                  */
701                 s->s3->need_empty_fragments = 1;
702
703                 if (s->session->cipher != NULL)
704                         {
705                         if (s->session->cipher->algorithm_enc == SSL_eNULL)
706                                 s->s3->need_empty_fragments = 0;
707                         
708 #ifndef OPENSSL_NO_RC4
709                         if (s->session->cipher->algorithm_enc == SSL_RC4)
710                                 s->s3->need_empty_fragments = 0;
711 #endif
712                         }
713                 }
714                 
715         ret = 1;
716 err:
717         if (p2)
718                 {
719                 OPENSSL_cleanse(p2,num);
720                 OPENSSL_free(p2);
721                 }
722         return(ret);
723         }
724
725 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
726  *
727  * Returns:
728  *   0: (in non-constant time) if the record is publically invalid (i.e. too
729  *       short etc).
730  *   1: if the record's padding is valid / the encryption was successful.
731  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
732  *       an internal error occured.
733  */
734 int tls1_enc(SSL *s, int send)
735         {
736         SSL3_RECORD *rec;
737         EVP_CIPHER_CTX *ds;
738         unsigned long l;
739         int bs,i,j,k,pad=0,ret,mac_size=0;
740         const EVP_CIPHER *enc;
741
742         if (send)
743                 {
744                 if (EVP_MD_CTX_md(s->write_hash))
745                         {
746                         int n=EVP_MD_CTX_size(s->write_hash);
747                         OPENSSL_assert(n >= 0);
748                         }
749                 ds=s->enc_write_ctx;
750                 rec= &(s->s3->wrec);
751                 if (s->enc_write_ctx == NULL)
752                         enc=NULL;
753                 else
754                         {
755                         int ivlen;
756                         enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
757                         /* For TLSv1.1 and later explicit IV */
758                         if (SSL_USE_EXPLICIT_IV(s)
759                                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
760                                 ivlen = EVP_CIPHER_iv_length(enc);
761                         else
762                                 ivlen = 0;
763                         if (ivlen > 1)
764                                 {
765                                 if ( rec->data != rec->input)
766                                         /* we can't write into the input stream:
767                                          * Can this ever happen?? (steve)
768                                          */
769                                         fprintf(stderr,
770                                                 "%s:%d: rec->data != rec->input\n",
771                                                 __FILE__, __LINE__);
772                                 else if (RAND_bytes(rec->input, ivlen) <= 0)
773                                         return -1;
774                                 }
775                         }
776                 }
777         else
778                 {
779                 if (EVP_MD_CTX_md(s->read_hash))
780                         {
781                         int n=EVP_MD_CTX_size(s->read_hash);
782                         OPENSSL_assert(n >= 0);
783                         }
784                 ds=s->enc_read_ctx;
785                 rec= &(s->s3->rrec);
786                 if (s->enc_read_ctx == NULL)
787                         enc=NULL;
788                 else
789                         enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
790                 }
791
792 #ifdef KSSL_DEBUG
793         printf("tls1_enc(%d)\n", send);
794 #endif    /* KSSL_DEBUG */
795
796         if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
797                 {
798                 memmove(rec->data,rec->input,rec->length);
799                 rec->input=rec->data;
800                 ret = 1;
801                 }
802         else
803                 {
804                 l=rec->length;
805                 bs=EVP_CIPHER_block_size(ds->cipher);
806
807                 if (EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_AEAD_CIPHER)
808                         {
809                         unsigned char buf[13],*seq;
810
811                         seq = send?s->s3->write_sequence:s->s3->read_sequence;
812
813                         if (SSL_IS_DTLS(s))
814                                 {
815                                 unsigned char dtlsseq[9],*p=dtlsseq;
816
817                                 s2n(send?s->d1->w_epoch:s->d1->r_epoch,p);
818                                 memcpy(p,&seq[2],6);
819                                 memcpy(buf,dtlsseq,8);
820                                 }
821                         else
822                                 {
823                                 memcpy(buf,seq,8);
824                                 for (i=7; i>=0; i--)    /* increment */
825                                         {
826                                         ++seq[i];
827                                         if (seq[i] != 0) break; 
828                                         }
829                                 }
830
831                         buf[8]=rec->type;
832                         buf[9]=(unsigned char)(s->version>>8);
833                         buf[10]=(unsigned char)(s->version);
834                         buf[11]=rec->length>>8;
835                         buf[12]=rec->length&0xff;
836                         pad=EVP_CIPHER_CTX_ctrl(ds,EVP_CTRL_AEAD_TLS1_AAD,13,buf);
837                         if (send)
838                                 {
839                                 l+=pad;
840                                 rec->length+=pad;
841                                 }
842                         }
843                 else if ((bs != 1) && send)
844                         {
845                         i=bs-((int)l%bs);
846
847                         /* Add weird padding of upto 256 bytes */
848
849                         /* we need to add 'i' padding bytes of value j */
850                         j=i-1;
851                         if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)
852                                 {
853                                 if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
854                                         j++;
855                                 }
856                         for (k=(int)l; k<(int)(l+i); k++)
857                                 rec->input[k]=j;
858                         l+=i;
859                         rec->length+=i;
860                         }
861
862 #ifdef KSSL_DEBUG
863                 {
864                 unsigned long ui;
865                 printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
866                         ds,rec->data,rec->input,l);
867                 printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n",
868                         ds->buf_len, ds->cipher->key_len,
869                         DES_KEY_SZ, DES_SCHEDULE_SZ,
870                         ds->cipher->iv_len);
871                 printf("\t\tIV: ");
872                 for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]);
873                 printf("\n");
874                 printf("\trec->input=");
875                 for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]);
876                 printf("\n");
877                 }
878 #endif  /* KSSL_DEBUG */
879
880                 if (!send)
881                         {
882                         if (l == 0 || l%bs != 0)
883                                 return 0;
884                         }
885                 
886                 i = EVP_Cipher(ds,rec->data,rec->input,l);
887                 if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
888                                                 ?(i<0)
889                                                 :(i==0))
890                         return -1;      /* AEAD can fail to verify MAC */
891                 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send)
892                         {
893                         rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
894                         rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
895                         rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
896                         }
897
898 #ifdef KSSL_DEBUG
899                 {
900                 unsigned long i;
901                 printf("\trec->data=");
902                 for (i=0; i<l; i++)
903                         printf(" %02x", rec->data[i]);  printf("\n");
904                 }
905 #endif  /* KSSL_DEBUG */
906
907                 ret = 1;
908                 if (EVP_MD_CTX_md(s->read_hash) != NULL)
909                         mac_size = EVP_MD_CTX_size(s->read_hash);
910                 if ((bs != 1) && !send)
911                         ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
912                 if (pad && !send)
913                         rec->length -= pad;
914                 }
915         return ret;
916         }
917
918 int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
919         {
920         unsigned int ret;
921         EVP_MD_CTX ctx, *d=NULL;
922         int i;
923
924         if (s->s3->handshake_buffer) 
925                 if (!ssl3_digest_cached_records(s))
926                         return 0;
927
928         for (i=0;i<SSL_MAX_DIGEST;i++) 
929                 {
930                   if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid) 
931                         {
932                         d=s->s3->handshake_dgst[i];
933                         break;
934                         }
935                 }
936         if (!d) {
937                 SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC,SSL_R_NO_REQUIRED_DIGEST);
938                 return 0;
939         }       
940
941         EVP_MD_CTX_init(&ctx);
942         EVP_MD_CTX_copy_ex(&ctx,d);
943         EVP_DigestFinal_ex(&ctx,out,&ret);
944         EVP_MD_CTX_cleanup(&ctx);
945         return((int)ret);
946         }
947
948 int tls1_final_finish_mac(SSL *s,
949              const char *str, int slen, unsigned char *out)
950         {
951         unsigned int i;
952         EVP_MD_CTX ctx;
953         unsigned char buf[2*EVP_MAX_MD_SIZE];
954         unsigned char *q,buf2[12];
955         int idx;
956         long mask;
957         int err=0;
958         const EVP_MD *md; 
959
960         q=buf;
961
962         if (s->s3->handshake_buffer) 
963                 if (!ssl3_digest_cached_records(s))
964                         return 0;
965
966         EVP_MD_CTX_init(&ctx);
967
968         for (idx=0;ssl_get_handshake_digest(idx,&mask,&md);idx++)
969                 {
970                 if (mask & ssl_get_algorithm2(s))
971                         {
972                         int hashsize = EVP_MD_size(md);
973                         if (hashsize < 0 || hashsize > (int)(sizeof buf - (size_t)(q-buf)))
974                                 {
975                                 /* internal error: 'buf' is too small for this cipersuite! */
976                                 err = 1;
977                                 }
978                         else
979                                 {
980                                 EVP_MD_CTX_copy_ex(&ctx,s->s3->handshake_dgst[idx]);
981                                 EVP_DigestFinal_ex(&ctx,q,&i);
982                                 if (i != (unsigned int)hashsize) /* can't really happen */
983                                         err = 1;
984                                 q+=i;
985                                 }
986                         }
987                 }
988                 
989         if (!tls1_PRF(ssl_get_algorithm2(s),
990                         str,slen, buf,(int)(q-buf), NULL,0, NULL,0, NULL,0,
991                         s->session->master_key,s->session->master_key_length,
992                         out,buf2,sizeof buf2))
993                 err = 1;
994         EVP_MD_CTX_cleanup(&ctx);
995
996         if (err)
997                 return 0;
998         else
999                 return sizeof buf2;
1000         }
1001
1002 int tls1_mac(SSL *ssl, unsigned char *md, int send)
1003         {
1004         SSL3_RECORD *rec;
1005         unsigned char *seq;
1006         EVP_MD_CTX *hash;
1007         size_t md_size, orig_len;
1008         int i;
1009         EVP_MD_CTX hmac, *mac_ctx;
1010         unsigned char header[13];
1011         int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM));
1012         int t;
1013
1014         if (send)
1015                 {
1016                 rec= &(ssl->s3->wrec);
1017                 seq= &(ssl->s3->write_sequence[0]);
1018                 hash=ssl->write_hash;
1019                 }
1020         else
1021                 {
1022                 rec= &(ssl->s3->rrec);
1023                 seq= &(ssl->s3->read_sequence[0]);
1024                 hash=ssl->read_hash;
1025                 }
1026
1027         t=EVP_MD_CTX_size(hash);
1028         OPENSSL_assert(t >= 0);
1029         md_size=t;
1030
1031         /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1032         if (stream_mac) 
1033                 {
1034                         mac_ctx = hash;
1035                 }
1036                 else
1037                 {
1038                         EVP_MD_CTX_copy(&hmac,hash);
1039                         mac_ctx = &hmac;
1040                 }
1041
1042         if (SSL_IS_DTLS(ssl))
1043                 {
1044                 unsigned char dtlsseq[8],*p=dtlsseq;
1045
1046                 s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
1047                 memcpy (p,&seq[2],6);
1048
1049                 memcpy(header, dtlsseq, 8);
1050                 }
1051         else
1052                 memcpy(header, seq, 8);
1053
1054         /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1055         orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
1056         rec->type &= 0xff;
1057
1058         header[8]=rec->type;
1059         header[9]=(unsigned char)(ssl->version>>8);
1060         header[10]=(unsigned char)(ssl->version);
1061         header[11]=(rec->length)>>8;
1062         header[12]=(rec->length)&0xff;
1063
1064         if (!send &&
1065             EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1066             ssl3_cbc_record_digest_supported(mac_ctx))
1067                 {
1068                 /* This is a CBC-encrypted record. We must avoid leaking any
1069                  * timing-side channel information about how many blocks of
1070                  * data we are hashing because that gives an attacker a
1071                  * timing-oracle. */
1072                 ssl3_cbc_digest_record(
1073                         mac_ctx,
1074                         md, &md_size,
1075                         header, rec->input,
1076                         rec->length + md_size, orig_len,
1077                         ssl->s3->read_mac_secret,
1078                         ssl->s3->read_mac_secret_size,
1079                         0 /* not SSLv3 */);
1080                 }
1081         else
1082                 {
1083                 EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
1084                 EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
1085                 t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
1086                 OPENSSL_assert(t > 0);
1087 #ifdef OPENSSL_FIPS
1088                 if (!send && FIPS_mode())
1089                         tls_fips_digest_extra(
1090                                         ssl->enc_read_ctx,
1091                                         mac_ctx, rec->input,
1092                                         rec->length, orig_len);
1093 #endif
1094                 }
1095                 
1096         if (!stream_mac)
1097                 EVP_MD_CTX_cleanup(&hmac);
1098 #ifdef TLS_DEBUG
1099 printf("sec=");
1100 {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); }
1101 printf("seq=");
1102 {int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); }
1103 printf("buf=");
1104 {int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); }
1105 printf("rec=");
1106 {unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); }
1107 #endif
1108
1109         if (!SSL_IS_DTLS(ssl))
1110                 {
1111                 for (i=7; i>=0; i--)
1112                         {
1113                         ++seq[i];
1114                         if (seq[i] != 0) break; 
1115                         }
1116                 }
1117
1118 #ifdef TLS_DEBUG
1119 {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); }
1120 #endif
1121         return(md_size);
1122         }
1123
1124 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1125              int len)
1126         {
1127         unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1128         const void *co = NULL, *so = NULL;
1129         int col = 0, sol = 0;
1130
1131
1132 #ifdef KSSL_DEBUG
1133         printf ("tls1_generate_master_secret(%p,%p, %p, %d)\n", s,out, p,len);
1134 #endif  /* KSSL_DEBUG */
1135
1136 #ifdef TLSEXT_TYPE_opaque_prf_input
1137         if (s->s3->client_opaque_prf_input != NULL && s->s3->server_opaque_prf_input != NULL &&
1138             s->s3->client_opaque_prf_input_len > 0 &&
1139             s->s3->client_opaque_prf_input_len == s->s3->server_opaque_prf_input_len)
1140                 {
1141                 co = s->s3->client_opaque_prf_input;
1142                 col = s->s3->server_opaque_prf_input_len;
1143                 so = s->s3->server_opaque_prf_input;
1144                 sol = s->s3->client_opaque_prf_input_len; /* must be same as col (see draft-rescorla-tls-opaque-prf-input-00.txt, section 3.1) */
1145                 }
1146 #endif
1147
1148         tls1_PRF(ssl_get_algorithm2(s),
1149                 TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
1150                 s->s3->client_random,SSL3_RANDOM_SIZE,
1151                 co, col,
1152                 s->s3->server_random,SSL3_RANDOM_SIZE,
1153                 so, sol,
1154                 p,len,
1155                 s->session->master_key,buff,sizeof buff);
1156 #ifdef SSL_DEBUG
1157         fprintf(stderr, "Premaster Secret:\n");
1158         BIO_dump_fp(stderr, (char *)p, len);
1159         fprintf(stderr, "Client Random:\n");
1160         BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
1161         fprintf(stderr, "Server Random:\n");
1162         BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
1163         fprintf(stderr, "Master Secret:\n");
1164         BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
1165 #endif
1166
1167 #ifdef OPENSSL_SSL_TRACE_CRYPTO
1168         if (s->msg_callback)
1169                 {
1170                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
1171                                                 p, len, s, s->msg_callback_arg);
1172                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
1173                                         s->s3->client_random, SSL3_RANDOM_SIZE,
1174                                                 s, s->msg_callback_arg);
1175                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
1176                                         s->s3->server_random, SSL3_RANDOM_SIZE,
1177                                         s, s->msg_callback_arg);
1178                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
1179                                         s->session->master_key,
1180                                         SSL3_MASTER_SECRET_SIZE,
1181                                         s, s->msg_callback_arg);
1182                 }
1183 #endif
1184
1185 #ifdef KSSL_DEBUG
1186         printf ("tls1_generate_master_secret() complete\n");
1187 #endif  /* KSSL_DEBUG */
1188         return(SSL3_MASTER_SECRET_SIZE);
1189         }
1190
1191 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1192          const char *label, size_t llen, const unsigned char *context,
1193          size_t contextlen, int use_context)
1194         {
1195         unsigned char *buff;
1196         unsigned char *val = NULL;
1197         size_t vallen, currentvalpos;
1198         int rv;
1199
1200 #ifdef KSSL_DEBUG
1201         printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen);
1202 #endif  /* KSSL_DEBUG */
1203
1204         buff = OPENSSL_malloc(olen);
1205         if (buff == NULL) goto err2;
1206
1207         /* construct PRF arguments
1208          * we construct the PRF argument ourself rather than passing separate
1209          * values into the TLS PRF to ensure that the concatenation of values
1210          * does not create a prohibited label.
1211          */
1212         vallen = llen + SSL3_RANDOM_SIZE * 2;
1213         if (use_context)
1214                 {
1215                 vallen += 2 + contextlen;
1216                 }
1217
1218         val = OPENSSL_malloc(vallen);
1219         if (val == NULL) goto err2;
1220         currentvalpos = 0;
1221         memcpy(val + currentvalpos, (unsigned char *) label, llen);
1222         currentvalpos += llen;
1223         memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1224         currentvalpos += SSL3_RANDOM_SIZE;
1225         memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1226         currentvalpos += SSL3_RANDOM_SIZE;
1227
1228         if (use_context)
1229                 {
1230                 val[currentvalpos] = (contextlen >> 8) & 0xff;
1231                 currentvalpos++;
1232                 val[currentvalpos] = contextlen & 0xff;
1233                 currentvalpos++;
1234                 if ((contextlen > 0) || (context != NULL))
1235                         {
1236                         memcpy(val + currentvalpos, context, contextlen);
1237                         }
1238                 }
1239
1240         /* disallow prohibited labels
1241          * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1242          * 15, so size of val > max(prohibited label len) = 15 and the
1243          * comparisons won't have buffer overflow
1244          */
1245         if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1246                  TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
1247         if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1248                  TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
1249         if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1250                  TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
1251         if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1252                  TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
1253
1254         rv = tls1_PRF(s->s3->tmp.new_cipher->algorithm2,
1255                       val, vallen,
1256                       NULL, 0,
1257                       NULL, 0,
1258                       NULL, 0,
1259                       NULL, 0,
1260                       s->session->master_key,s->session->master_key_length,
1261                       out,buff,olen);
1262
1263 #ifdef KSSL_DEBUG
1264         printf ("tls1_export_keying_material() complete\n");
1265 #endif  /* KSSL_DEBUG */
1266         goto ret;
1267 err1:
1268         SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1269         rv = 0;
1270         goto ret;
1271 err2:
1272         SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
1273         rv = 0;
1274 ret:
1275         if (buff != NULL) OPENSSL_free(buff);
1276         if (val != NULL) OPENSSL_free(val);
1277         return(rv);
1278         }
1279
1280 int tls1_alert_code(int code)
1281         {
1282         switch (code)
1283                 {
1284         case SSL_AD_CLOSE_NOTIFY:       return(SSL3_AD_CLOSE_NOTIFY);
1285         case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
1286         case SSL_AD_BAD_RECORD_MAC:     return(SSL3_AD_BAD_RECORD_MAC);
1287         case SSL_AD_DECRYPTION_FAILED:  return(TLS1_AD_DECRYPTION_FAILED);
1288         case SSL_AD_RECORD_OVERFLOW:    return(TLS1_AD_RECORD_OVERFLOW);
1289         case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
1290         case SSL_AD_HANDSHAKE_FAILURE:  return(SSL3_AD_HANDSHAKE_FAILURE);
1291         case SSL_AD_NO_CERTIFICATE:     return(-1);
1292         case SSL_AD_BAD_CERTIFICATE:    return(SSL3_AD_BAD_CERTIFICATE);
1293         case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
1294         case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
1295         case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
1296         case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
1297         case SSL_AD_ILLEGAL_PARAMETER:  return(SSL3_AD_ILLEGAL_PARAMETER);
1298         case SSL_AD_UNKNOWN_CA:         return(TLS1_AD_UNKNOWN_CA);
1299         case SSL_AD_ACCESS_DENIED:      return(TLS1_AD_ACCESS_DENIED);
1300         case SSL_AD_DECODE_ERROR:       return(TLS1_AD_DECODE_ERROR);
1301         case SSL_AD_DECRYPT_ERROR:      return(TLS1_AD_DECRYPT_ERROR);
1302         case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
1303         case SSL_AD_PROTOCOL_VERSION:   return(TLS1_AD_PROTOCOL_VERSION);
1304         case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
1305         case SSL_AD_INTERNAL_ERROR:     return(TLS1_AD_INTERNAL_ERROR);
1306         case SSL_AD_USER_CANCELLED:     return(TLS1_AD_USER_CANCELLED);
1307         case SSL_AD_NO_RENEGOTIATION:   return(TLS1_AD_NO_RENEGOTIATION);
1308         case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
1309         case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1310         case SSL_AD_UNRECOGNIZED_NAME:  return(TLS1_AD_UNRECOGNIZED_NAME);
1311         case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1312         case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1313         case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
1314 #if 0 /* not appropriate for TLS, not used for DTLS */
1315         case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE: return 
1316                                           (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1317 #endif
1318         default:                        return(-1);
1319                 }
1320         }