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