Merge branch 'OpenSSL_1_0_2-stable' into agl-1.0.2aead
[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_aead_ctx_init allocates |*aead_ctx|, if needed and returns 1. It
320  * returns 0 on malloc error. */
321 static int tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
322         {
323         if (*aead_ctx != NULL)
324                 EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
325         else
326                 {
327                 *aead_ctx = (SSL_AEAD_CTX*) OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
328                 if (*aead_ctx == NULL)
329                         {
330                         SSLerr(SSL_F_TLS1_AEAD_CTX_INIT, ERR_R_MALLOC_FAILURE);
331                         return 0;
332                         }
333                 }
334
335         return 1;
336         }
337
338 static int tls1_change_cipher_state_aead(SSL *s, char is_read,
339         const unsigned char *key, unsigned key_len,
340         const unsigned char *iv, unsigned iv_len)
341         {
342         const EVP_AEAD *aead = s->s3->tmp.new_aead;
343         SSL_AEAD_CTX *aead_ctx;
344
345         if (is_read)
346                 {
347                 if (!tls1_aead_ctx_init(&s->aead_read_ctx))
348                         return 0;
349                 aead_ctx = s->aead_read_ctx;
350                 }
351         else
352                 {
353                 if (!tls1_aead_ctx_init(&s->aead_write_ctx))
354                         return 0;
355                 aead_ctx = s->aead_write_ctx;
356                 }
357
358         if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
359                                EVP_AEAD_DEFAULT_TAG_LENGTH, NULL /* engine */))
360                 return 0;
361         if (iv_len > sizeof(aead_ctx->fixed_nonce))
362                 {
363                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_AEAD, ERR_R_INTERNAL_ERROR);
364                 return 0;
365                 }
366         memcpy(aead_ctx->fixed_nonce, iv, iv_len);
367         aead_ctx->fixed_nonce_len = iv_len;
368         aead_ctx->variable_nonce_len = 8;  /* always the case, currently. */
369         aead_ctx->variable_nonce_included_in_record =
370                 (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_INCLUDED_IN_RECORD) != 0;
371         if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len != EVP_AEAD_nonce_length(aead))
372                 {
373                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_AEAD, ERR_R_INTERNAL_ERROR);
374                 return 0;
375                 }
376         aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
377
378         return 1;
379         }
380
381 /* tls1_change_cipher_state_cipher performs the work needed to switch cipher
382  * states when using EVP_CIPHER. The argument |is_read| is true iff this
383  * function is being called due to reading, as opposed to writing, a
384  * ChangeCipherSpec message. In order to support export ciphersuites,
385  * use_client_keys indicates whether the key material provided is in the
386  * "client write" direction. */
387 static int tls1_change_cipher_state_cipher(SSL *s,
388         char is_read, char use_client_keys,
389         const unsigned char *mac_secret, unsigned mac_secret_len,
390         const unsigned char *key, unsigned key_len,
391         const unsigned char *iv, unsigned iv_len)
392         {
393         const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
394         const char is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) != 0;
395         EVP_CIPHER_CTX *cipher_ctx;
396         EVP_MD_CTX *mac_ctx;
397         char is_aead_cipher;
398
399         unsigned char export_tmp1[EVP_MAX_KEY_LENGTH];
400         unsigned char export_tmp2[EVP_MAX_KEY_LENGTH];
401         unsigned char export_iv1[EVP_MAX_IV_LENGTH * 2];
402         unsigned char export_iv2[EVP_MAX_IV_LENGTH * 2];
403
404         if (is_read)
405                 {
406                 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
407                         s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
408                 else
409                         s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
410
411                 if (s->enc_read_ctx != NULL)
412                         EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
413                 else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
414                         goto err;
415                 else
416                         /* make sure it's intialized in case we exit later with an error */
417                         EVP_CIPHER_CTX_init(s->enc_read_ctx);
418
419                 cipher_ctx = s->enc_read_ctx;
420                 mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
421
422                 memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
423                 s->s3->read_mac_secret_size = mac_secret_len;
424                 }
425         else
426                 {
427                 if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
428                         s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
429                 else
430                         s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
431
432                 if (s->enc_write_ctx != NULL)
433                         EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
434                 else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
435                         goto err;
436                 else
437                         /* make sure it's intialized in case we exit later with an error */
438                         EVP_CIPHER_CTX_init(s->enc_write_ctx);
439
440                 cipher_ctx = s->enc_write_ctx;
441                 mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
442
443                 memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
444                 s->s3->write_mac_secret_size = mac_secret_len;
445                 }
446
447         if (is_export)
448                 {
449                 /* In here I set both the read and write key/iv to the
450                  * same value since only the correct one will be used :-).
451                  */
452                 const unsigned char *label;
453                 unsigned label_len;
454
455                 if (use_client_keys)
456                         {
457                         label = (const unsigned char*) TLS_MD_CLIENT_WRITE_KEY_CONST;
458                         label_len = TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE;
459                         }
460                 else
461                         {
462                         label = (const unsigned char*) TLS_MD_SERVER_WRITE_KEY_CONST;
463                         label_len = TLS_MD_SERVER_WRITE_KEY_CONST_SIZE;
464                         }
465
466                 if (!tls1_PRF(ssl_get_algorithm2(s),
467                                 label, label_len,
468                                 s->s3->client_random, SSL3_RANDOM_SIZE,
469                                 s->s3->server_random, SSL3_RANDOM_SIZE,
470                                 NULL, 0, NULL, 0,
471                                 key /* secret */, key_len /* secret length */,
472                                 export_tmp1 /* output */,
473                                 export_tmp2 /* scratch space */,
474                                 EVP_CIPHER_key_length(s->s3->tmp.new_sym_enc) /* output length */))
475                         return 0;
476                 key = export_tmp1;
477
478                 if (iv_len > 0)
479                         {
480                         static const unsigned char empty[] = "";
481
482                         if (!tls1_PRF(ssl_get_algorithm2(s),
483                                         TLS_MD_IV_BLOCK_CONST, TLS_MD_IV_BLOCK_CONST_SIZE,
484                                         s->s3->client_random, SSL3_RANDOM_SIZE,
485                                         s->s3->server_random, SSL3_RANDOM_SIZE,
486                                         NULL, 0, NULL, 0,
487                                         empty /* secret */ ,0 /* secret length */,
488                                         export_iv1 /* output */,
489                                         export_iv2 /* scratch space */,
490                                         iv_len * 2 /* output length */))
491                                 return 0;
492
493                         if (use_client_keys)
494                                 iv = export_iv1;
495                         else
496                                 iv = &export_iv1[iv_len];
497                         }
498                 }
499
500         /* is_aead_cipher indicates whether the EVP_CIPHER implements an AEAD
501          * interface. This is different from the newer EVP_AEAD interface. */
502         is_aead_cipher = (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0;
503
504         if (!is_aead_cipher)
505                 {
506                 EVP_PKEY *mac_key =
507                         EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
508                                              NULL, mac_secret, mac_secret_len);
509                 if (!mac_key)
510                         return 0;
511                 EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
512                 EVP_PKEY_free(mac_key);
513                 }
514
515         if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
516                 {
517                 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key,
518                                   NULL /* iv */, !is_read);
519                 EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_GCM_SET_IV_FIXED, iv_len, (void*) iv);
520                 }
521         else
522                 EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
523
524         /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
525         if (is_aead_cipher && mac_secret_len > 0)
526                 EVP_CIPHER_CTX_ctrl(cipher_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
527                                     mac_secret_len, (void*) mac_secret);
528
529         if (is_export)
530                 {
531                 OPENSSL_cleanse(export_tmp1, sizeof(export_tmp1));
532                 OPENSSL_cleanse(export_tmp2, sizeof(export_tmp1));
533                 OPENSSL_cleanse(export_iv1, sizeof(export_iv1));
534                 OPENSSL_cleanse(export_iv2, sizeof(export_iv2));
535                 }
536
537         return 1;
538
539 err:
540         SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE_CIPHER, ERR_R_MALLOC_FAILURE);
541         return 0;
542         }
543
544 int tls1_change_cipher_state(SSL *s, int which)
545         {
546         /* is_read is true if we have just read a ChangeCipherSpec message -
547          * i.e. we need to update the read cipherspec. Otherwise we have just
548          * written one. */
549         const char is_read = (which & SSL3_CC_READ) != 0;
550         /* use_client_keys is true if we wish to use the keys for the "client
551          * write" direction. This is the case if we're a client sending a
552          * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec. */
553         const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
554                                      which == SSL3_CHANGE_CIPHER_SERVER_READ;
555         const unsigned char *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
556         const unsigned char *client_write_key, *server_write_key, *key;
557         const unsigned char *client_write_iv, *server_write_iv, *iv;
558         const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
559         const EVP_AEAD *aead = s->s3->tmp.new_aead;
560         unsigned key_len, iv_len, mac_secret_len;
561         const unsigned char *key_data;
562         const char is_export = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) != 0;
563
564         /* Update compression contexts. */
565 #ifndef OPENSSL_NO_COMP
566         const SSL_COMP *comp = s->s3->tmp.new_compression;
567
568         if (is_read)
569                 {
570                 if (s->expand != NULL)
571                         {
572                         COMP_CTX_free(s->expand);
573                         s->expand = NULL;
574                         }
575                 if (comp != NULL)
576                         {
577                         s->expand=COMP_CTX_new(comp->method);
578                         if (s->expand == NULL)
579                                 {
580                                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
581                                 return 0;
582                                 }
583                         if (s->s3->rrec.comp == NULL)
584                                 s->s3->rrec.comp =
585                                         (unsigned char *)OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
586                         if (s->s3->rrec.comp == NULL)
587                                 goto err;
588                         }
589                 }
590         else
591                 {
592                 if (s->compress != NULL)
593                         {
594                         COMP_CTX_free(s->compress);
595                         s->compress = NULL;
596                         }
597                 if (comp != NULL)
598                         {
599                         s->compress = COMP_CTX_new(comp->method);
600                         if (s->compress == NULL)
601                                 {
602                                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR);
603                                 return 0;
604                                 }
605                         }
606                 }
607 #endif  /* OPENSSL_NO_COMP */
608
609         /* Reset sequence number to zero. */
610         memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
611
612         /* key_arg is used for SSLv2. We don't need it for TLS. */
613         s->session->key_arg_length = 0;
614
615         mac_secret_len = s->s3->tmp.new_mac_secret_size;
616
617         if (aead != NULL)
618                 {
619                 key_len = EVP_AEAD_key_length(aead);
620                 iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
621                 }
622         else
623                 {
624                 key_len = EVP_CIPHER_key_length(cipher);
625                 if (is_export && key_len > SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher))
626                         key_len = SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher);
627
628                 if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
629                         iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
630                 else
631                         iv_len = EVP_CIPHER_iv_length(cipher);
632                 }
633
634         key_data = s->s3->tmp.key_block;
635         client_write_mac_secret = key_data; key_data += mac_secret_len;
636         server_write_mac_secret = key_data; key_data += mac_secret_len;
637         client_write_key =        key_data; key_data += key_len;
638         server_write_key =        key_data; key_data += key_len;
639         client_write_iv  =        key_data; key_data += iv_len;
640         server_write_iv  =        key_data; key_data += iv_len;
641
642         if (use_client_keys)
643                 {
644                 mac_secret = client_write_mac_secret;
645                 key = client_write_key;
646                 iv = client_write_iv;
647                 }
648         else
649                 {
650                 mac_secret = server_write_mac_secret;
651                 key = server_write_key;
652                 iv = server_write_iv;
653                 }
654
655         if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
656                 {
657                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR);
658                 return 0;
659                 }
660
661         if (aead != NULL)
662                 {
663                 if (!tls1_change_cipher_state_aead(s, is_read,
664                                                    key, key_len, iv, iv_len))
665                         return 0;
666                 }
667         else
668                 {
669                 if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
670                                                      mac_secret, mac_secret_len,
671                                                      key, key_len,
672                                                      iv, iv_len))
673                         return 0;
674                 }
675
676 #ifdef OPENSSL_SSL_TRACE_CRYPTO
677         if (s->msg_callback)
678                 {
679                 int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
680                 if (mac_secret_len)
681                         s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
682                                                 mac_secret, mac_secret_len,
683                                                 s, s->msg_callback_arg);
684                 if (key_len)
685                         s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
686                                                 key, key_len,
687                                                 s, s->msg_callback_arg);
688                 if (iv_len)
689                         {
690                         if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
691                                 wh |= TLS1_RT_CRYPTO_FIXED_IV;
692                         else
693                                 wh |= TLS1_RT_CRYPTO_IV;
694                         s->msg_callback(2, s->version, wh, iv, iv_len,
695                                                 s, s->msg_callback_arg);
696                         }
697                 }
698 #endif
699
700         return 1;
701 err:
702         SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
703         return 0;
704         }
705
706 int tls1_setup_key_block(SSL *s)
707         {
708         unsigned char *p1,*p2=NULL;
709         const EVP_CIPHER *c = NULL;
710         const EVP_MD *hash = NULL;
711         const EVP_AEAD *aead = NULL;
712         int num;
713         SSL_COMP *comp;
714         int mac_type= NID_undef,mac_secret_size=0;
715         int ret=0;
716         unsigned key_len, iv_len;
717
718 #ifdef KSSL_DEBUG
719         printf ("tls1_setup_key_block()\n");
720 #endif  /* KSSL_DEBUG */
721
722         if (s->s3->tmp.key_block_length != 0)
723                 return(1);
724
725         if (!ssl_cipher_get_comp(s->session, &comp))
726                 goto cipher_unavailable_err;
727
728         if (s->session->cipher &&
729             (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD))
730                 {
731                 if (!ssl_cipher_get_evp_aead(s->session, &aead))
732                         goto cipher_unavailable_err;
733                 key_len = EVP_AEAD_key_length(aead);
734                 iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
735                 }
736         else
737                 {
738                 if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size))
739                         goto cipher_unavailable_err;
740                 key_len = EVP_CIPHER_key_length(c);
741
742                 if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
743                         iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
744                 else
745                         iv_len = EVP_CIPHER_iv_length(c);
746                 }
747
748         s->s3->tmp.new_aead=aead;
749         s->s3->tmp.new_sym_enc=c;
750         s->s3->tmp.new_hash=hash;
751         s->s3->tmp.new_mac_pkey_type = mac_type;
752         s->s3->tmp.new_mac_secret_size = mac_secret_size;
753
754         num=key_len+mac_secret_size+iv_len;
755         num*=2;
756
757         ssl3_cleanup_key_block(s);
758
759         if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
760                 {
761                 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE);
762                 goto err;
763                 }
764
765         s->s3->tmp.key_block_length=num;
766         s->s3->tmp.key_block=p1;
767
768         if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
769                 {
770                 SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,ERR_R_MALLOC_FAILURE);
771                 goto err;
772                 }
773
774 #ifdef TLS_DEBUG
775 printf("client random\n");
776 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
777 printf("server random\n");
778 { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
779 printf("pre-master\n");
780 { int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
781 #endif
782         if (!tls1_generate_key_block(s,p1,p2,num))
783                 goto err;
784 #ifdef TLS_DEBUG
785 printf("\nkey block\n");
786 { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
787 #endif
788
789         if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
790                 && s->method->version <= TLS1_VERSION)
791                 {
792                 /* enable vulnerability countermeasure for CBC ciphers with
793                  * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
794                  */
795                 s->s3->need_empty_fragments = 1;
796
797                 if (s->session->cipher != NULL)
798                         {
799                         if (s->session->cipher->algorithm_enc == SSL_eNULL)
800                                 s->s3->need_empty_fragments = 0;
801                         
802 #ifndef OPENSSL_NO_RC4
803                         if (s->session->cipher->algorithm_enc == SSL_RC4)
804                                 s->s3->need_empty_fragments = 0;
805 #endif
806                         }
807                 }
808                 
809         ret = 1;
810 err:
811         if (p2)
812                 {
813                 OPENSSL_cleanse(p2,num);
814                 OPENSSL_free(p2);
815                 }
816         return(ret);
817
818 cipher_unavailable_err:
819         SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK,SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
820         return 0;
821         }
822
823 /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
824  *
825  * Returns:
826  *   0: (in non-constant time) if the record is publically invalid (i.e. too
827  *       short etc).
828  *   1: if the record's padding is valid / the encryption was successful.
829  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
830  *       an internal error occured.
831  */
832 int tls1_enc(SSL *s, int send)
833         {
834         SSL3_RECORD *rec;
835         EVP_CIPHER_CTX *ds;
836         unsigned long l;
837         int bs,i,j,k,pad=0,ret,mac_size=0;
838         const EVP_CIPHER *enc;
839         const SSL_AEAD_CTX *aead;
840
841         if (send)
842                 rec = &s->s3->wrec;
843         else
844                 rec = &s->s3->rrec;
845
846         if (send)
847                 aead = s->aead_write_ctx;
848         else
849                 aead = s->aead_read_ctx;
850
851         if (aead)
852                 {
853                 unsigned char ad[13], *seq, *in, *out, nonce[16];
854                 unsigned nonce_used;
855                 ssize_t n;
856
857                 seq = send ? s->s3->write_sequence : s->s3->read_sequence;
858
859                 if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
860                         {
861                         unsigned char dtlsseq[9], *p = dtlsseq;
862
863                         s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
864                         memcpy(p, &seq[2], 6);
865                         memcpy(ad, dtlsseq, 8);
866                         }
867                 else
868                         {
869                         memcpy(ad, seq, 8);
870                         for (i=7; i>=0; i--)    /* increment */
871                                 {
872                                 ++seq[i];
873                                 if (seq[i] != 0)
874                                         break;
875                                 }
876                         }
877
878                 ad[8]  = rec->type;
879                 ad[9]  = (unsigned char)(s->version>>8);
880                 ad[10] = (unsigned char)(s->version);
881
882                 if (aead->fixed_nonce_len + aead->variable_nonce_len > sizeof(nonce) ||
883                     aead->variable_nonce_len > 8)
884                         return -1;  /* internal error - should never happen. */
885
886                 memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
887                 nonce_used = aead->fixed_nonce_len;
888
889                 if (send)
890                         {
891                         size_t len = rec->length;
892                         size_t eivlen = 0;
893                         in = rec->input;
894                         out = rec->data;
895
896                         /* When sending we use the sequence number as the
897                          * variable part of the nonce. */
898                         if (aead->variable_nonce_len > 8)
899                                 return -1;
900                         memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
901                         nonce_used += aead->variable_nonce_len;
902
903                         /* in do_ssl3_write, rec->input is moved forward by
904                          * variable_nonce_len in order to leave space for the
905                          * variable nonce. Thus we can copy the sequence number
906                          * bytes into place without overwriting any of the
907                          * plaintext. */
908                         if (aead->variable_nonce_included_in_record)
909                                 {
910                                 memcpy(out, ad, aead->variable_nonce_len);
911                                 len -= aead->variable_nonce_len;
912                                 eivlen = aead->variable_nonce_len;
913                                 }
914
915                         ad[11] = len >> 8;
916                         ad[12] = len & 0xff;
917
918                         n = EVP_AEAD_CTX_seal(&aead->ctx,
919                                               out + eivlen, len + aead->tag_len,
920                                               nonce, nonce_used,
921                                               in + eivlen, len,
922                                               ad, sizeof(ad));
923                         if (n >= 0 && aead->variable_nonce_included_in_record)
924                                 n += aead->variable_nonce_len;
925                         }
926                 else
927                         {
928                         /* receive */
929                         size_t len = rec->length;
930
931                         if (rec->data != rec->input)
932                                 return -1;  /* internal error - should never happen. */
933                         out = in = rec->input;
934
935                         if (len < aead->variable_nonce_len)
936                                 return 0;
937                         memcpy(nonce + nonce_used,
938                                aead->variable_nonce_included_in_record ? in : ad,
939                                aead->variable_nonce_len);
940                         nonce_used += aead->variable_nonce_len;
941
942                         if (aead->variable_nonce_included_in_record)
943                                 {
944                                 in += aead->variable_nonce_len;
945                                 len -= aead->variable_nonce_len;
946                                 out += aead->variable_nonce_len;
947                                 }
948
949                         if (len < aead->tag_len)
950                                 return 0;
951                         len -= aead->tag_len;
952
953                         ad[11] = len >> 8;
954                         ad[12] = len & 0xff;
955
956                         n = EVP_AEAD_CTX_open(&aead->ctx, out, len, nonce, nonce_used,
957                                               in, len + aead->tag_len, ad, sizeof(ad));
958
959                         rec->data = rec->input = out;
960                         }
961
962                 if (n == -1)
963                         return -1;
964                 rec->length = n;
965                 return 1;
966                 }
967
968         if (send)
969                 {
970                 if (EVP_MD_CTX_md(s->write_hash))
971                         {
972                         int n=EVP_MD_CTX_size(s->write_hash);
973                         OPENSSL_assert(n >= 0);
974                         }
975                 ds=s->enc_write_ctx;
976                 rec= &(s->s3->wrec);
977                 if (s->enc_write_ctx == NULL)
978                         enc=NULL;
979                 else
980                         {
981                         int ivlen;
982                         enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
983                         /* For TLSv1.1 and later explicit IV */
984                         if (SSL_USE_EXPLICIT_IV(s)
985                                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
986                                 ivlen = EVP_CIPHER_iv_length(enc);
987                         else
988                                 ivlen = 0;
989                         if (ivlen > 1)
990                                 {
991                                 if ( rec->data != rec->input)
992                                         /* we can't write into the input stream:
993                                          * Can this ever happen?? (steve)
994                                          */
995                                         fprintf(stderr,
996                                                 "%s:%d: rec->data != rec->input\n",
997                                                 __FILE__, __LINE__);
998                                 else if (RAND_bytes(rec->input, ivlen) <= 0)
999                                         return -1;
1000                                 }
1001                         }
1002                 }
1003         else
1004                 {
1005                 if (EVP_MD_CTX_md(s->read_hash))
1006                         {
1007                         int n=EVP_MD_CTX_size(s->read_hash);
1008                         OPENSSL_assert(n >= 0);
1009                         }
1010                 ds=s->enc_read_ctx;
1011                 rec= &(s->s3->rrec);
1012                 if (s->enc_read_ctx == NULL)
1013                         enc=NULL;
1014                 else
1015                         enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
1016                 }
1017
1018 #ifdef KSSL_DEBUG
1019         printf("tls1_enc(%d)\n", send);
1020 #endif    /* KSSL_DEBUG */
1021
1022         if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
1023                 {
1024                 memmove(rec->data,rec->input,rec->length);
1025                 rec->input=rec->data;
1026                 ret = 1;
1027                 }
1028         else
1029                 {
1030                 l=rec->length;
1031                 bs=EVP_CIPHER_block_size(ds->cipher);
1032
1033                 if (EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_AEAD_CIPHER)
1034                         {
1035                         unsigned char buf[13],*seq;
1036
1037                         seq = send?s->s3->write_sequence:s->s3->read_sequence;
1038
1039                         if (SSL_IS_DTLS(s))
1040                                 {
1041                                 unsigned char dtlsseq[9],*p=dtlsseq;
1042
1043                                 s2n(send?s->d1->w_epoch:s->d1->r_epoch,p);
1044                                 memcpy(p,&seq[2],6);
1045                                 memcpy(buf,dtlsseq,8);
1046                                 }
1047                         else
1048                                 {
1049                                 memcpy(buf,seq,8);
1050                                 for (i=7; i>=0; i--)    /* increment */
1051                                         {
1052                                         ++seq[i];
1053                                         if (seq[i] != 0) break; 
1054                                         }
1055                                 }
1056
1057                         buf[8]=rec->type;
1058                         buf[9]=(unsigned char)(s->version>>8);
1059                         buf[10]=(unsigned char)(s->version);
1060                         buf[11]=rec->length>>8;
1061                         buf[12]=rec->length&0xff;
1062                         pad=EVP_CIPHER_CTX_ctrl(ds,EVP_CTRL_AEAD_TLS1_AAD,13,buf);
1063                         if (send)
1064                                 {
1065                                 l+=pad;
1066                                 rec->length+=pad;
1067                                 }
1068                         }
1069                 else if ((bs != 1) && send)
1070                         {
1071                         i=bs-((int)l%bs);
1072
1073                         /* Add weird padding of upto 256 bytes */
1074
1075                         /* we need to add 'i' padding bytes of value j */
1076                         j=i-1;
1077                         if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)
1078                                 {
1079                                 if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
1080                                         j++;
1081                                 }
1082                         for (k=(int)l; k<(int)(l+i); k++)
1083                                 rec->input[k]=j;
1084                         l+=i;
1085                         rec->length+=i;
1086                         }
1087
1088 #ifdef KSSL_DEBUG
1089                 {
1090                 unsigned long ui;
1091                 printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
1092                         ds,rec->data,rec->input,l);
1093                 printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n",
1094                         ds->buf_len, ds->cipher->key_len,
1095                         DES_KEY_SZ, DES_SCHEDULE_SZ,
1096                         ds->cipher->iv_len);
1097                 printf("\t\tIV: ");
1098                 for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]);
1099                 printf("\n");
1100                 printf("\trec->input=");
1101                 for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]);
1102                 printf("\n");
1103                 }
1104 #endif  /* KSSL_DEBUG */
1105
1106                 if (!send)
1107                         {
1108                         if (l == 0 || l%bs != 0)
1109                                 return 0;
1110                         }
1111                 
1112                 i = EVP_Cipher(ds,rec->data,rec->input,l);
1113                 if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
1114                                                 ?(i<0)
1115                                                 :(i==0))
1116                         return -1;      /* AEAD can fail to verify MAC */
1117                 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send)
1118                         {
1119                         rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1120                         rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1121                         rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1122                         }
1123
1124 #ifdef KSSL_DEBUG
1125                 {
1126                 unsigned long i;
1127                 printf("\trec->data=");
1128                 for (i=0; i<l; i++)
1129                         printf(" %02x", rec->data[i]);  printf("\n");
1130                 }
1131 #endif  /* KSSL_DEBUG */
1132
1133                 ret = 1;
1134                 if (EVP_MD_CTX_md(s->read_hash) != NULL)
1135                         mac_size = EVP_MD_CTX_size(s->read_hash);
1136                 if ((bs != 1) && !send)
1137                         ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
1138                 if (pad && !send)
1139                         rec->length -= pad;
1140                 }
1141         return ret;
1142         }
1143
1144 int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
1145         {
1146         unsigned int ret;
1147         EVP_MD_CTX ctx, *d=NULL;
1148         int i;
1149
1150         if (s->s3->handshake_buffer) 
1151                 if (!ssl3_digest_cached_records(s))
1152                         return 0;
1153
1154         for (i=0;i<SSL_MAX_DIGEST;i++) 
1155                 {
1156                   if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid) 
1157                         {
1158                         d=s->s3->handshake_dgst[i];
1159                         break;
1160                         }
1161                 }
1162         if (!d) {
1163                 SSLerr(SSL_F_TLS1_CERT_VERIFY_MAC,SSL_R_NO_REQUIRED_DIGEST);
1164                 return 0;
1165         }       
1166
1167         EVP_MD_CTX_init(&ctx);
1168         EVP_MD_CTX_copy_ex(&ctx,d);
1169         EVP_DigestFinal_ex(&ctx,out,&ret);
1170         EVP_MD_CTX_cleanup(&ctx);
1171         return((int)ret);
1172         }
1173
1174 int tls1_final_finish_mac(SSL *s,
1175              const char *str, int slen, unsigned char *out)
1176         {
1177         unsigned int i;
1178         EVP_MD_CTX ctx;
1179         unsigned char buf[2*EVP_MAX_MD_SIZE];
1180         unsigned char *q,buf2[12];
1181         int idx;
1182         long mask;
1183         int err=0;
1184         const EVP_MD *md; 
1185
1186         q=buf;
1187
1188         if (s->s3->handshake_buffer) 
1189                 if (!ssl3_digest_cached_records(s))
1190                         return 0;
1191
1192         EVP_MD_CTX_init(&ctx);
1193
1194         for (idx=0;ssl_get_handshake_digest(idx,&mask,&md);idx++)
1195                 {
1196                 if (mask & ssl_get_algorithm2(s))
1197                         {
1198                         int hashsize = EVP_MD_size(md);
1199                         if (hashsize < 0 || hashsize > (int)(sizeof buf - (size_t)(q-buf)))
1200                                 {
1201                                 /* internal error: 'buf' is too small for this cipersuite! */
1202                                 err = 1;
1203                                 }
1204                         else
1205                                 {
1206                                 EVP_MD_CTX_copy_ex(&ctx,s->s3->handshake_dgst[idx]);
1207                                 EVP_DigestFinal_ex(&ctx,q,&i);
1208                                 if (i != (unsigned int)hashsize) /* can't really happen */
1209                                         err = 1;
1210                                 q+=i;
1211                                 }
1212                         }
1213                 }
1214                 
1215         if (!tls1_PRF(ssl_get_algorithm2(s),
1216                         str,slen, buf,(int)(q-buf), NULL,0, NULL,0, NULL,0,
1217                         s->session->master_key,s->session->master_key_length,
1218                         out,buf2,sizeof buf2))
1219                 err = 1;
1220         EVP_MD_CTX_cleanup(&ctx);
1221
1222         if (err)
1223                 return 0;
1224         else
1225                 return sizeof buf2;
1226         }
1227
1228 int tls1_mac(SSL *ssl, unsigned char *md, int send)
1229         {
1230         SSL3_RECORD *rec;
1231         unsigned char *seq;
1232         EVP_MD_CTX *hash;
1233         size_t md_size, orig_len;
1234         int i;
1235         EVP_MD_CTX hmac, *mac_ctx;
1236         unsigned char header[13];
1237         int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM));
1238         int t;
1239
1240         if (send)
1241                 {
1242                 rec= &(ssl->s3->wrec);
1243                 seq= &(ssl->s3->write_sequence[0]);
1244                 hash=ssl->write_hash;
1245                 }
1246         else
1247                 {
1248                 rec= &(ssl->s3->rrec);
1249                 seq= &(ssl->s3->read_sequence[0]);
1250                 hash=ssl->read_hash;
1251                 }
1252
1253         t=EVP_MD_CTX_size(hash);
1254         OPENSSL_assert(t >= 0);
1255         md_size=t;
1256
1257         /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1258         if (stream_mac) 
1259                 {
1260                         mac_ctx = hash;
1261                 }
1262                 else
1263                 {
1264                         EVP_MD_CTX_copy(&hmac,hash);
1265                         mac_ctx = &hmac;
1266                 }
1267
1268         if (SSL_IS_DTLS(ssl))
1269                 {
1270                 unsigned char dtlsseq[8],*p=dtlsseq;
1271
1272                 s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
1273                 memcpy (p,&seq[2],6);
1274
1275                 memcpy(header, dtlsseq, 8);
1276                 }
1277         else
1278                 memcpy(header, seq, 8);
1279
1280         /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
1281         orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
1282         rec->type &= 0xff;
1283
1284         header[8]=rec->type;
1285         header[9]=(unsigned char)(ssl->version>>8);
1286         header[10]=(unsigned char)(ssl->version);
1287         header[11]=(rec->length)>>8;
1288         header[12]=(rec->length)&0xff;
1289
1290         if (!send &&
1291             EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1292             ssl3_cbc_record_digest_supported(mac_ctx))
1293                 {
1294                 /* This is a CBC-encrypted record. We must avoid leaking any
1295                  * timing-side channel information about how many blocks of
1296                  * data we are hashing because that gives an attacker a
1297                  * timing-oracle. */
1298                 ssl3_cbc_digest_record(
1299                         mac_ctx,
1300                         md, &md_size,
1301                         header, rec->input,
1302                         rec->length + md_size, orig_len,
1303                         ssl->s3->read_mac_secret,
1304                         ssl->s3->read_mac_secret_size,
1305                         0 /* not SSLv3 */);
1306                 }
1307         else
1308                 {
1309                 EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
1310                 EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
1311                 t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
1312                 OPENSSL_assert(t > 0);
1313 #ifdef OPENSSL_FIPS
1314                 if (!send && FIPS_mode())
1315                         tls_fips_digest_extra(
1316                                         ssl->enc_read_ctx,
1317                                         mac_ctx, rec->input,
1318                                         rec->length, orig_len);
1319 #endif
1320                 }
1321                 
1322         if (!stream_mac)
1323                 EVP_MD_CTX_cleanup(&hmac);
1324 #ifdef TLS_DEBUG
1325 printf("sec=");
1326 {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); }
1327 printf("seq=");
1328 {int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); }
1329 printf("buf=");
1330 {int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); }
1331 printf("rec=");
1332 {unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); }
1333 #endif
1334
1335         if (!SSL_IS_DTLS(ssl))
1336                 {
1337                 for (i=7; i>=0; i--)
1338                         {
1339                         ++seq[i];
1340                         if (seq[i] != 0) break; 
1341                         }
1342                 }
1343
1344 #ifdef TLS_DEBUG
1345 {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); }
1346 #endif
1347         return(md_size);
1348         }
1349
1350 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
1351              int len)
1352         {
1353         unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
1354         const void *co = NULL, *so = NULL;
1355         int col = 0, sol = 0;
1356
1357
1358 #ifdef KSSL_DEBUG
1359         printf ("tls1_generate_master_secret(%p,%p, %p, %d)\n", s,out, p,len);
1360 #endif  /* KSSL_DEBUG */
1361
1362 #ifdef TLSEXT_TYPE_opaque_prf_input
1363         if (s->s3->client_opaque_prf_input != NULL && s->s3->server_opaque_prf_input != NULL &&
1364             s->s3->client_opaque_prf_input_len > 0 &&
1365             s->s3->client_opaque_prf_input_len == s->s3->server_opaque_prf_input_len)
1366                 {
1367                 co = s->s3->client_opaque_prf_input;
1368                 col = s->s3->server_opaque_prf_input_len;
1369                 so = s->s3->server_opaque_prf_input;
1370                 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) */
1371                 }
1372 #endif
1373
1374         tls1_PRF(ssl_get_algorithm2(s),
1375                 TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
1376                 s->s3->client_random,SSL3_RANDOM_SIZE,
1377                 co, col,
1378                 s->s3->server_random,SSL3_RANDOM_SIZE,
1379                 so, sol,
1380                 p,len,
1381                 s->session->master_key,buff,sizeof buff);
1382 #ifdef SSL_DEBUG
1383         fprintf(stderr, "Premaster Secret:\n");
1384         BIO_dump_fp(stderr, (char *)p, len);
1385         fprintf(stderr, "Client Random:\n");
1386         BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
1387         fprintf(stderr, "Server Random:\n");
1388         BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
1389         fprintf(stderr, "Master Secret:\n");
1390         BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
1391 #endif
1392
1393 #ifdef OPENSSL_SSL_TRACE_CRYPTO
1394         if (s->msg_callback)
1395                 {
1396                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
1397                                                 p, len, s, s->msg_callback_arg);
1398                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
1399                                         s->s3->client_random, SSL3_RANDOM_SIZE,
1400                                                 s, s->msg_callback_arg);
1401                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
1402                                         s->s3->server_random, SSL3_RANDOM_SIZE,
1403                                         s, s->msg_callback_arg);
1404                 s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
1405                                         s->session->master_key,
1406                                         SSL3_MASTER_SECRET_SIZE,
1407                                         s, s->msg_callback_arg);
1408                 }
1409 #endif
1410
1411 #ifdef KSSL_DEBUG
1412         printf ("tls1_generate_master_secret() complete\n");
1413 #endif  /* KSSL_DEBUG */
1414         return(SSL3_MASTER_SECRET_SIZE);
1415         }
1416
1417 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
1418          const char *label, size_t llen, const unsigned char *context,
1419          size_t contextlen, int use_context)
1420         {
1421         unsigned char *buff;
1422         unsigned char *val = NULL;
1423         size_t vallen, currentvalpos;
1424         int rv;
1425
1426 #ifdef KSSL_DEBUG
1427         printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen);
1428 #endif  /* KSSL_DEBUG */
1429
1430         buff = OPENSSL_malloc(olen);
1431         if (buff == NULL) goto err2;
1432
1433         /* construct PRF arguments
1434          * we construct the PRF argument ourself rather than passing separate
1435          * values into the TLS PRF to ensure that the concatenation of values
1436          * does not create a prohibited label.
1437          */
1438         vallen = llen + SSL3_RANDOM_SIZE * 2;
1439         if (use_context)
1440                 {
1441                 vallen += 2 + contextlen;
1442                 }
1443
1444         val = OPENSSL_malloc(vallen);
1445         if (val == NULL) goto err2;
1446         currentvalpos = 0;
1447         memcpy(val + currentvalpos, (unsigned char *) label, llen);
1448         currentvalpos += llen;
1449         memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
1450         currentvalpos += SSL3_RANDOM_SIZE;
1451         memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
1452         currentvalpos += SSL3_RANDOM_SIZE;
1453
1454         if (use_context)
1455                 {
1456                 val[currentvalpos] = (contextlen >> 8) & 0xff;
1457                 currentvalpos++;
1458                 val[currentvalpos] = contextlen & 0xff;
1459                 currentvalpos++;
1460                 if ((contextlen > 0) || (context != NULL))
1461                         {
1462                         memcpy(val + currentvalpos, context, contextlen);
1463                         }
1464                 }
1465
1466         /* disallow prohibited labels
1467          * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
1468          * 15, so size of val > max(prohibited label len) = 15 and the
1469          * comparisons won't have buffer overflow
1470          */
1471         if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
1472                  TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
1473         if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
1474                  TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
1475         if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
1476                  TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
1477         if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
1478                  TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
1479
1480         rv = tls1_PRF(s->s3->tmp.new_cipher->algorithm2,
1481                       val, vallen,
1482                       NULL, 0,
1483                       NULL, 0,
1484                       NULL, 0,
1485                       NULL, 0,
1486                       s->session->master_key,s->session->master_key_length,
1487                       out,buff,olen);
1488
1489 #ifdef KSSL_DEBUG
1490         printf ("tls1_export_keying_material() complete\n");
1491 #endif  /* KSSL_DEBUG */
1492         goto ret;
1493 err1:
1494         SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
1495         rv = 0;
1496         goto ret;
1497 err2:
1498         SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
1499         rv = 0;
1500 ret:
1501         if (buff != NULL) OPENSSL_free(buff);
1502         if (val != NULL) OPENSSL_free(val);
1503         return(rv);
1504         }
1505
1506 int tls1_alert_code(int code)
1507         {
1508         switch (code)
1509                 {
1510         case SSL_AD_CLOSE_NOTIFY:       return(SSL3_AD_CLOSE_NOTIFY);
1511         case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
1512         case SSL_AD_BAD_RECORD_MAC:     return(SSL3_AD_BAD_RECORD_MAC);
1513         case SSL_AD_DECRYPTION_FAILED:  return(TLS1_AD_DECRYPTION_FAILED);
1514         case SSL_AD_RECORD_OVERFLOW:    return(TLS1_AD_RECORD_OVERFLOW);
1515         case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
1516         case SSL_AD_HANDSHAKE_FAILURE:  return(SSL3_AD_HANDSHAKE_FAILURE);
1517         case SSL_AD_NO_CERTIFICATE:     return(-1);
1518         case SSL_AD_BAD_CERTIFICATE:    return(SSL3_AD_BAD_CERTIFICATE);
1519         case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
1520         case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
1521         case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
1522         case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
1523         case SSL_AD_ILLEGAL_PARAMETER:  return(SSL3_AD_ILLEGAL_PARAMETER);
1524         case SSL_AD_UNKNOWN_CA:         return(TLS1_AD_UNKNOWN_CA);
1525         case SSL_AD_ACCESS_DENIED:      return(TLS1_AD_ACCESS_DENIED);
1526         case SSL_AD_DECODE_ERROR:       return(TLS1_AD_DECODE_ERROR);
1527         case SSL_AD_DECRYPT_ERROR:      return(TLS1_AD_DECRYPT_ERROR);
1528         case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
1529         case SSL_AD_PROTOCOL_VERSION:   return(TLS1_AD_PROTOCOL_VERSION);
1530         case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
1531         case SSL_AD_INTERNAL_ERROR:     return(TLS1_AD_INTERNAL_ERROR);
1532         case SSL_AD_USER_CANCELLED:     return(TLS1_AD_USER_CANCELLED);
1533         case SSL_AD_NO_RENEGOTIATION:   return(TLS1_AD_NO_RENEGOTIATION);
1534         case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
1535         case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
1536         case SSL_AD_UNRECOGNIZED_NAME:  return(TLS1_AD_UNRECOGNIZED_NAME);
1537         case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
1538         case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
1539         case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
1540 #if 0 /* not appropriate for TLS, not used for DTLS */
1541         case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE: return 
1542                                           (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1543 #endif
1544         default:                        return(-1);
1545                 }
1546         }