Adapt the rest of the source to the opaque HMAC_CTX
[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
148 /* seed1 through seed5 are virtually concatenated */
149 static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
150                        int sec_len,
151                        const void *seed1, int seed1_len,
152                        const void *seed2, int seed2_len,
153                        const void *seed3, int seed3_len,
154                        const void *seed4, int seed4_len,
155                        const void *seed5, int seed5_len,
156                        unsigned char *out, int olen)
157 {
158     int chunk;
159     size_t j;
160     EVP_MD_CTX *ctx, *ctx_tmp, *ctx_init;
161     EVP_PKEY *mac_key;
162     unsigned char A1[EVP_MAX_MD_SIZE];
163     size_t A1_len;
164     int ret = 0;
165
166     chunk = EVP_MD_size(md);
167     OPENSSL_assert(chunk >= 0);
168
169     ctx = EVP_MD_CTX_create();
170     ctx_tmp = EVP_MD_CTX_create();
171     ctx_init = EVP_MD_CTX_create();
172     if (ctx == NULL || ctx_tmp == NULL || ctx_init == NULL)
173         goto err;
174     EVP_MD_CTX_set_flags(ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
175     mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
176     if (!mac_key)
177         goto err;
178     if (!EVP_DigestSignInit(ctx_init, NULL, md, NULL, mac_key))
179         goto err;
180     if (!EVP_MD_CTX_copy_ex(ctx, ctx_init))
181         goto err;
182     if (seed1 && !EVP_DigestSignUpdate(ctx, seed1, seed1_len))
183         goto err;
184     if (seed2 && !EVP_DigestSignUpdate(ctx, seed2, seed2_len))
185         goto err;
186     if (seed3 && !EVP_DigestSignUpdate(ctx, seed3, seed3_len))
187         goto err;
188     if (seed4 && !EVP_DigestSignUpdate(ctx, seed4, seed4_len))
189         goto err;
190     if (seed5 && !EVP_DigestSignUpdate(ctx, seed5, seed5_len))
191         goto err;
192     if (!EVP_DigestSignFinal(ctx, A1, &A1_len))
193         goto err;
194
195     for (;;) {
196         /* Reinit mac contexts */
197         if (!EVP_MD_CTX_copy_ex(ctx, ctx_init))
198             goto err;
199         if (!EVP_DigestSignUpdate(ctx, A1, A1_len))
200             goto err;
201         if (olen > chunk && !EVP_MD_CTX_copy_ex(ctx_tmp, ctx))
202             goto err;
203         if (seed1 && !EVP_DigestSignUpdate(ctx, seed1, seed1_len))
204             goto err;
205         if (seed2 && !EVP_DigestSignUpdate(ctx, seed2, seed2_len))
206             goto err;
207         if (seed3 && !EVP_DigestSignUpdate(ctx, seed3, seed3_len))
208             goto err;
209         if (seed4 && !EVP_DigestSignUpdate(ctx, seed4, seed4_len))
210             goto err;
211         if (seed5 && !EVP_DigestSignUpdate(ctx, seed5, seed5_len))
212             goto err;
213
214         if (olen > chunk) {
215             if (!EVP_DigestSignFinal(ctx, out, &j))
216                 goto err;
217             out += j;
218             olen -= j;
219             /* calc the next A1 value */
220             if (!EVP_DigestSignFinal(ctx_tmp, A1, &A1_len))
221                 goto err;
222         } else {                /* last one */
223
224             if (!EVP_DigestSignFinal(ctx, A1, &A1_len))
225                 goto err;
226             memcpy(out, A1, olen);
227             break;
228         }
229     }
230     ret = 1;
231  err:
232     EVP_PKEY_free(mac_key);
233     EVP_MD_CTX_destroy(ctx);
234     EVP_MD_CTX_destroy(ctx_tmp);
235     EVP_MD_CTX_destroy(ctx_init);
236     OPENSSL_cleanse(A1, sizeof(A1));
237     return ret;
238 }
239
240 /* seed1 through seed5 are virtually concatenated */
241 static int tls1_PRF(SSL *s,
242                     const void *seed1, int seed1_len,
243                     const void *seed2, int seed2_len,
244                     const void *seed3, int seed3_len,
245                     const void *seed4, int seed4_len,
246                     const void *seed5, int seed5_len,
247                     const unsigned char *sec, int slen,
248                     unsigned char *out1, unsigned char *out2, int olen)
249 {
250     const EVP_MD *md = ssl_prf_md(s);
251
252     if (md == NULL) {
253         /* Should never happen */
254         SSLerr(SSL_F_TLS1_PRF, ERR_R_INTERNAL_ERROR);
255         return 0;
256     }
257     if (EVP_MD_type(md) == NID_md5_sha1) {
258         int i;
259         if (!tls1_P_hash(EVP_md5(), sec, slen/2 + (slen & 1),
260                          seed1, seed1_len, seed2, seed2_len, seed3,
261                          seed3_len, seed4, seed4_len, seed5, seed5_len,
262                          out1, olen))
263             return 0;
264         if (!tls1_P_hash(EVP_sha1(), sec + slen/2, slen/2 + (slen & 1),
265                          seed1, seed1_len, seed2, seed2_len, seed3,
266                          seed3_len, seed4, seed4_len, seed5, seed5_len,
267                          out2, olen))
268             return 0;
269         for (i = 0; i < olen; i++)
270             out1[i] ^= out2[i];
271         return 1;
272     }
273     memset(out2, 0, olen);
274     if (!tls1_P_hash(md, sec, slen,
275                      seed1, seed1_len, seed2, seed2_len, seed3,
276                      seed3_len, seed4, seed4_len, seed5, seed5_len,
277                      out1, olen))
278         return 0;
279
280     return 1;
281 }
282
283 static int tls1_generate_key_block(SSL *s, unsigned char *km,
284                                    unsigned char *tmp, int num)
285 {
286     int ret;
287     ret = tls1_PRF(s,
288                    TLS_MD_KEY_EXPANSION_CONST,
289                    TLS_MD_KEY_EXPANSION_CONST_SIZE, s->s3->server_random,
290                    SSL3_RANDOM_SIZE, s->s3->client_random, SSL3_RANDOM_SIZE,
291                    NULL, 0, NULL, 0, s->session->master_key,
292                    s->session->master_key_length, km, tmp, num);
293
294     return ret;
295 }
296
297 int tls1_change_cipher_state(SSL *s, int which)
298 {
299     unsigned char *p, *mac_secret;
300     unsigned char tmp1[EVP_MAX_KEY_LENGTH];
301     unsigned char tmp2[EVP_MAX_KEY_LENGTH];
302     unsigned char iv1[EVP_MAX_IV_LENGTH * 2];
303     unsigned char iv2[EVP_MAX_IV_LENGTH * 2];
304     unsigned char *ms, *key, *iv;
305     EVP_CIPHER_CTX *dd;
306     const EVP_CIPHER *c;
307 #ifndef OPENSSL_NO_COMP
308     const SSL_COMP *comp;
309 #endif
310     const EVP_MD *m;
311     int mac_type;
312     int *mac_secret_size;
313     EVP_MD_CTX *mac_ctx;
314     EVP_PKEY *mac_key;
315     int n, i, j, k, cl;
316     int reuse_dd = 0;
317
318     c = s->s3->tmp.new_sym_enc;
319     m = s->s3->tmp.new_hash;
320     mac_type = s->s3->tmp.new_mac_pkey_type;
321 #ifndef OPENSSL_NO_COMP
322     comp = s->s3->tmp.new_compression;
323 #endif
324
325     if (which & SSL3_CC_READ) {
326         if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
327             s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
328         else
329             s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
330
331         if (s->enc_read_ctx != NULL)
332             reuse_dd = 1;
333         else if ((s->enc_read_ctx =
334                   OPENSSL_malloc(sizeof(*s->enc_read_ctx))) == NULL)
335             goto err;
336         else
337             /*
338              * make sure it's intialized in case we exit later with an error
339              */
340             EVP_CIPHER_CTX_init(s->enc_read_ctx);
341         dd = s->enc_read_ctx;
342         mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
343         if (mac_ctx == NULL)
344             goto err;
345 #ifndef OPENSSL_NO_COMP
346         COMP_CTX_free(s->expand);
347         s->expand = NULL;
348         if (comp != NULL) {
349             s->expand = COMP_CTX_new(comp->method);
350             if (s->expand == NULL) {
351                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
352                        SSL_R_COMPRESSION_LIBRARY_ERROR);
353                 goto err2;
354             }
355             if (!RECORD_LAYER_setup_comp_buffer(&s->rlayer))
356                 goto err;
357         }
358 #endif
359         /*
360          * this is done by dtls1_reset_seq_numbers for DTLS
361          */
362         if (!SSL_IS_DTLS(s))
363             RECORD_LAYER_reset_read_sequence(&s->rlayer);
364         mac_secret = &(s->s3->read_mac_secret[0]);
365         mac_secret_size = &(s->s3->read_mac_secret_size);
366     } else {
367         if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
368             s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
369         else
370             s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
371         if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
372             reuse_dd = 1;
373         else if ((s->enc_write_ctx = EVP_CIPHER_CTX_new()) == NULL)
374             goto err;
375         dd = s->enc_write_ctx;
376         if (SSL_IS_DTLS(s)) {
377             mac_ctx = EVP_MD_CTX_create();
378             if (mac_ctx == NULL)
379                 goto err;
380             s->write_hash = mac_ctx;
381         } else {
382             mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
383             if (mac_ctx == NULL)
384                 goto err;
385         }
386 #ifndef OPENSSL_NO_COMP
387         COMP_CTX_free(s->compress);
388         s->compress = NULL;
389         if (comp != NULL) {
390             s->compress = COMP_CTX_new(comp->method);
391             if (s->compress == NULL) {
392                 SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
393                        SSL_R_COMPRESSION_LIBRARY_ERROR);
394                 goto err2;
395             }
396         }
397 #endif
398         /*
399          * this is done by dtls1_reset_seq_numbers for DTLS
400          */
401         if (!SSL_IS_DTLS(s))
402             RECORD_LAYER_reset_write_sequence(&s->rlayer);
403         mac_secret = &(s->s3->write_mac_secret[0]);
404         mac_secret_size = &(s->s3->write_mac_secret_size);
405     }
406
407     if (reuse_dd)
408         EVP_CIPHER_CTX_cleanup(dd);
409
410     p = s->s3->tmp.key_block;
411     i = *mac_secret_size = s->s3->tmp.new_mac_secret_size;
412
413     cl = EVP_CIPHER_key_length(c);
414     j = cl;
415     /* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
416     /* If GCM/CCM mode only part of IV comes from PRF */
417     if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
418         k = EVP_GCM_TLS_FIXED_IV_LEN;
419     else if (EVP_CIPHER_mode(c) == EVP_CIPH_CCM_MODE)
420         k = EVP_CCM_TLS_FIXED_IV_LEN;
421     else
422         k = EVP_CIPHER_iv_length(c);
423     if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
424         (which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
425         ms = &(p[0]);
426         n = i + i;
427         key = &(p[n]);
428         n += j + j;
429         iv = &(p[n]);
430         n += k + k;
431     } else {
432         n = i;
433         ms = &(p[n]);
434         n += i + j;
435         key = &(p[n]);
436         n += j + k;
437         iv = &(p[n]);
438         n += k;
439     }
440
441     if (n > s->s3->tmp.key_block_length) {
442         SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
443         goto err2;
444     }
445
446     memcpy(mac_secret, ms, i);
447
448     if (!(EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
449         mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
450                                        mac_secret, *mac_secret_size);
451         if (mac_key == NULL
452                 || EVP_DigestSignInit(mac_ctx, NULL, m, NULL, mac_key) <= 0) {
453             EVP_PKEY_free(mac_key);
454             SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
455             goto err2;
456         }
457         EVP_PKEY_free(mac_key);
458     }
459 #ifdef TLS_DEBUG
460     printf("which = %04X\nmac key=", which);
461     {
462         int z;
463         for (z = 0; z < i; z++)
464             printf("%02X%c", ms[z], ((z + 1) % 16) ? ' ' : '\n');
465     }
466 #endif
467
468     if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) {
469         if (!EVP_CipherInit_ex(dd, c, NULL, key, NULL, (which & SSL3_CC_WRITE))
470             || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv)) {
471             SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
472             goto err2;
473         }
474     } else if (EVP_CIPHER_mode(c) == EVP_CIPH_CCM_MODE) {
475         int taglen;
476         if (s->s3->tmp.new_cipher->algorithm_enc & (SSL_AES128CCM8|SSL_AES256CCM8))
477             taglen = 8;
478         else
479             taglen = 16;
480         if (!EVP_CipherInit_ex(dd, c, NULL, NULL, NULL, (which & SSL3_CC_WRITE))
481             || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_IVLEN, 12, NULL)
482             || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_TAG, taglen, NULL)
483             || !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_CCM_SET_IV_FIXED, k, iv)
484             || !EVP_CipherInit_ex(dd, NULL, NULL, key, NULL, -1)) {
485             SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
486             goto err2;
487         }
488     } else {
489         if (!EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE))) {
490             SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
491             goto err2;
492         }
493     }
494     /* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
495     if ((EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size
496         && !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_MAC_KEY,
497                                 *mac_secret_size, mac_secret)) {
498         SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
499         goto err2;
500     }
501 #ifdef OPENSSL_SSL_TRACE_CRYPTO
502     if (s->msg_callback) {
503         int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
504         if (*mac_secret_size)
505             s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
506                             mac_secret, *mac_secret_size,
507                             s, s->msg_callback_arg);
508         if (c->key_len)
509             s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
510                             key, c->key_len, s, s->msg_callback_arg);
511         if (k) {
512             if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
513                 wh |= TLS1_RT_CRYPTO_FIXED_IV;
514             else
515                 wh |= TLS1_RT_CRYPTO_IV;
516             s->msg_callback(2, s->version, wh, iv, k, s, s->msg_callback_arg);
517         }
518     }
519 #endif
520
521 #ifdef TLS_DEBUG
522     printf("which = %04X\nkey=", which);
523     {
524         int z;
525         for (z = 0; z < EVP_CIPHER_key_length(c); z++)
526             printf("%02X%c", key[z], ((z + 1) % 16) ? ' ' : '\n');
527     }
528     printf("\niv=");
529     {
530         int z;
531         for (z = 0; z < k; z++)
532             printf("%02X%c", iv[z], ((z + 1) % 16) ? ' ' : '\n');
533     }
534     printf("\n");
535 #endif
536
537     OPENSSL_cleanse(tmp1, sizeof(tmp1));
538     OPENSSL_cleanse(tmp2, sizeof(tmp1));
539     OPENSSL_cleanse(iv1, sizeof(iv1));
540     OPENSSL_cleanse(iv2, sizeof(iv2));
541     return (1);
542  err:
543     SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
544  err2:
545     OPENSSL_cleanse(tmp1, sizeof(tmp1));
546     OPENSSL_cleanse(tmp2, sizeof(tmp1));
547     OPENSSL_cleanse(iv1, sizeof(iv1));
548     OPENSSL_cleanse(iv2, sizeof(iv2));
549     return (0);
550 }
551
552 int tls1_setup_key_block(SSL *s)
553 {
554     unsigned char *p1, *p2 = NULL;
555     const EVP_CIPHER *c;
556     const EVP_MD *hash;
557     int num;
558     SSL_COMP *comp;
559     int mac_type = NID_undef, mac_secret_size = 0;
560     int ret = 0;
561
562     if (s->s3->tmp.key_block_length != 0)
563         return (1);
564
565     if (!ssl_cipher_get_evp
566         (s->session, &c, &hash, &mac_type, &mac_secret_size, &comp,
567          SSL_USE_ETM(s))) {
568         SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
569         return (0);
570     }
571
572     s->s3->tmp.new_sym_enc = c;
573     s->s3->tmp.new_hash = hash;
574     s->s3->tmp.new_mac_pkey_type = mac_type;
575     s->s3->tmp.new_mac_secret_size = mac_secret_size;
576     num =
577         EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
578     num *= 2;
579
580     ssl3_cleanup_key_block(s);
581
582     if ((p1 = OPENSSL_malloc(num)) == NULL) {
583         SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
584         goto err;
585     }
586
587     s->s3->tmp.key_block_length = num;
588     s->s3->tmp.key_block = p1;
589
590     if ((p2 = OPENSSL_malloc(num)) == NULL) {
591         SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
592         OPENSSL_free(p1);
593         goto err;
594     }
595 #ifdef TLS_DEBUG
596     printf("client random\n");
597     {
598         int z;
599         for (z = 0; z < SSL3_RANDOM_SIZE; z++)
600             printf("%02X%c", s->s3->client_random[z],
601                    ((z + 1) % 16) ? ' ' : '\n');
602     }
603     printf("server random\n");
604     {
605         int z;
606         for (z = 0; z < SSL3_RANDOM_SIZE; z++)
607             printf("%02X%c", s->s3->server_random[z],
608                    ((z + 1) % 16) ? ' ' : '\n');
609     }
610     printf("master key\n");
611     {
612         int z;
613         for (z = 0; z < s->session->master_key_length; z++)
614             printf("%02X%c", s->session->master_key[z],
615                    ((z + 1) % 16) ? ' ' : '\n');
616     }
617 #endif
618     if (!tls1_generate_key_block(s, p1, p2, num))
619         goto err;
620 #ifdef TLS_DEBUG
621     printf("\nkey block\n");
622     {
623         int z;
624         for (z = 0; z < num; z++)
625             printf("%02X%c", p1[z], ((z + 1) % 16) ? ' ' : '\n');
626     }
627 #endif
628
629     if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
630         && s->method->version <= TLS1_VERSION) {
631         /*
632          * enable vulnerability countermeasure for CBC ciphers with known-IV
633          * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
634          */
635         s->s3->need_empty_fragments = 1;
636
637         if (s->session->cipher != NULL) {
638             if (s->session->cipher->algorithm_enc == SSL_eNULL)
639                 s->s3->need_empty_fragments = 0;
640
641 #ifndef OPENSSL_NO_RC4
642             if (s->session->cipher->algorithm_enc == SSL_RC4)
643                 s->s3->need_empty_fragments = 0;
644 #endif
645         }
646     }
647
648     ret = 1;
649  err:
650     OPENSSL_clear_free(p2, num);
651     return (ret);
652 }
653
654 int tls1_final_finish_mac(SSL *s, const char *str, int slen,
655                           unsigned char *out)
656 {
657     int hashlen;
658     unsigned char hash[EVP_MAX_MD_SIZE];
659     unsigned char buf2[12];
660
661     if (!ssl3_digest_cached_records(s, 0))
662         return 0;
663
664     hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
665
666     if (hashlen == 0)
667         return 0;
668
669     if (!tls1_PRF(s,
670                   str, slen, hash, hashlen, NULL, 0, NULL, 0, NULL, 0,
671                   s->session->master_key, s->session->master_key_length,
672                   out, buf2, sizeof buf2))
673         return 0;
674     OPENSSL_cleanse(hash, hashlen);
675     OPENSSL_cleanse(buf2, sizeof(buf2));
676     return sizeof(buf2);
677 }
678
679 int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
680                                 int len)
681 {
682     unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
683
684     if (s->session->flags & SSL_SESS_FLAG_EXTMS) {
685         unsigned char hash[EVP_MAX_MD_SIZE * 2];
686         int hashlen;
687         /* Digest cached records keeping record buffer (if present):
688          * this wont affect client auth because we're freezing the buffer
689          * at the same point (after client key exchange and before certificate
690          * verify)
691          */
692         if (!ssl3_digest_cached_records(s, 1))
693             return -1;
694         hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
695 #ifdef SSL_DEBUG
696         fprintf(stderr, "Handshake hashes:\n");
697         BIO_dump_fp(stderr, (char *)hash, hashlen);
698 #endif
699         tls1_PRF(s,
700                  TLS_MD_EXTENDED_MASTER_SECRET_CONST,
701                  TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
702                  hash, hashlen,
703                  NULL, 0,
704                  NULL, 0,
705                  NULL, 0, p, len, s->session->master_key, buff, sizeof buff);
706         OPENSSL_cleanse(hash, hashlen);
707     } else {
708         tls1_PRF(s,
709                  TLS_MD_MASTER_SECRET_CONST,
710                  TLS_MD_MASTER_SECRET_CONST_SIZE,
711                  s->s3->client_random, SSL3_RANDOM_SIZE,
712                  NULL, 0,
713                  s->s3->server_random, SSL3_RANDOM_SIZE,
714                  NULL, 0, p, len, s->session->master_key, buff, sizeof buff);
715     }
716     OPENSSL_cleanse(buff, sizeof buff);
717 #ifdef SSL_DEBUG
718     fprintf(stderr, "Premaster Secret:\n");
719     BIO_dump_fp(stderr, (char *)p, len);
720     fprintf(stderr, "Client Random:\n");
721     BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
722     fprintf(stderr, "Server Random:\n");
723     BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
724     fprintf(stderr, "Master Secret:\n");
725     BIO_dump_fp(stderr, (char *)s->session->master_key,
726                 SSL3_MASTER_SECRET_SIZE);
727 #endif
728
729 #ifdef OPENSSL_SSL_TRACE_CRYPTO
730     if (s->msg_callback) {
731         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
732                         p, len, s, s->msg_callback_arg);
733         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
734                         s->s3->client_random, SSL3_RANDOM_SIZE,
735                         s, s->msg_callback_arg);
736         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
737                         s->s3->server_random, SSL3_RANDOM_SIZE,
738                         s, s->msg_callback_arg);
739         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
740                         s->session->master_key,
741                         SSL3_MASTER_SECRET_SIZE, s, s->msg_callback_arg);
742     }
743 #endif
744
745     return (SSL3_MASTER_SECRET_SIZE);
746 }
747
748 int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
749                                 const char *label, size_t llen,
750                                 const unsigned char *context,
751                                 size_t contextlen, int use_context)
752 {
753     unsigned char *buff;
754     unsigned char *val = NULL;
755     size_t vallen = 0, currentvalpos;
756     int rv;
757
758     buff = OPENSSL_malloc(olen);
759     if (buff == NULL)
760         goto err2;
761
762     /*
763      * construct PRF arguments we construct the PRF argument ourself rather
764      * than passing separate values into the TLS PRF to ensure that the
765      * concatenation of values does not create a prohibited label.
766      */
767     vallen = llen + SSL3_RANDOM_SIZE * 2;
768     if (use_context) {
769         vallen += 2 + contextlen;
770     }
771
772     val = OPENSSL_malloc(vallen);
773     if (val == NULL)
774         goto err2;
775     currentvalpos = 0;
776     memcpy(val + currentvalpos, (unsigned char *)label, llen);
777     currentvalpos += llen;
778     memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
779     currentvalpos += SSL3_RANDOM_SIZE;
780     memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
781     currentvalpos += SSL3_RANDOM_SIZE;
782
783     if (use_context) {
784         val[currentvalpos] = (contextlen >> 8) & 0xff;
785         currentvalpos++;
786         val[currentvalpos] = contextlen & 0xff;
787         currentvalpos++;
788         if ((contextlen > 0) || (context != NULL)) {
789             memcpy(val + currentvalpos, context, contextlen);
790         }
791     }
792
793     /*
794      * disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
795      * label len) = 15, so size of val > max(prohibited label len) = 15 and
796      * the comparisons won't have buffer overflow
797      */
798     if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
799                TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
800         goto err1;
801     if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
802                TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
803         goto err1;
804     if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
805                TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
806         goto err1;
807     if (memcmp(val, TLS_MD_EXTENDED_MASTER_SECRET_CONST,
808                TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE) == 0)
809         goto err1;
810     if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
811                TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
812         goto err1;
813
814     rv = tls1_PRF(s,
815                   val, vallen,
816                   NULL, 0,
817                   NULL, 0,
818                   NULL, 0,
819                   NULL, 0,
820                   s->session->master_key, s->session->master_key_length,
821                   out, buff, olen);
822
823     goto ret;
824  err1:
825     SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL,
826            SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
827     rv = 0;
828     goto ret;
829  err2:
830     SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
831     rv = 0;
832  ret:
833     CRYPTO_clear_free(val, vallen);
834     CRYPTO_clear_free(buff, olen);
835     return (rv);
836 }
837
838 int tls1_alert_code(int code)
839 {
840     switch (code) {
841     case SSL_AD_CLOSE_NOTIFY:
842         return (SSL3_AD_CLOSE_NOTIFY);
843     case SSL_AD_UNEXPECTED_MESSAGE:
844         return (SSL3_AD_UNEXPECTED_MESSAGE);
845     case SSL_AD_BAD_RECORD_MAC:
846         return (SSL3_AD_BAD_RECORD_MAC);
847     case SSL_AD_DECRYPTION_FAILED:
848         return (TLS1_AD_DECRYPTION_FAILED);
849     case SSL_AD_RECORD_OVERFLOW:
850         return (TLS1_AD_RECORD_OVERFLOW);
851     case SSL_AD_DECOMPRESSION_FAILURE:
852         return (SSL3_AD_DECOMPRESSION_FAILURE);
853     case SSL_AD_HANDSHAKE_FAILURE:
854         return (SSL3_AD_HANDSHAKE_FAILURE);
855     case SSL_AD_NO_CERTIFICATE:
856         return (-1);
857     case SSL_AD_BAD_CERTIFICATE:
858         return (SSL3_AD_BAD_CERTIFICATE);
859     case SSL_AD_UNSUPPORTED_CERTIFICATE:
860         return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
861     case SSL_AD_CERTIFICATE_REVOKED:
862         return (SSL3_AD_CERTIFICATE_REVOKED);
863     case SSL_AD_CERTIFICATE_EXPIRED:
864         return (SSL3_AD_CERTIFICATE_EXPIRED);
865     case SSL_AD_CERTIFICATE_UNKNOWN:
866         return (SSL3_AD_CERTIFICATE_UNKNOWN);
867     case SSL_AD_ILLEGAL_PARAMETER:
868         return (SSL3_AD_ILLEGAL_PARAMETER);
869     case SSL_AD_UNKNOWN_CA:
870         return (TLS1_AD_UNKNOWN_CA);
871     case SSL_AD_ACCESS_DENIED:
872         return (TLS1_AD_ACCESS_DENIED);
873     case SSL_AD_DECODE_ERROR:
874         return (TLS1_AD_DECODE_ERROR);
875     case SSL_AD_DECRYPT_ERROR:
876         return (TLS1_AD_DECRYPT_ERROR);
877     case SSL_AD_EXPORT_RESTRICTION:
878         return (TLS1_AD_EXPORT_RESTRICTION);
879     case SSL_AD_PROTOCOL_VERSION:
880         return (TLS1_AD_PROTOCOL_VERSION);
881     case SSL_AD_INSUFFICIENT_SECURITY:
882         return (TLS1_AD_INSUFFICIENT_SECURITY);
883     case SSL_AD_INTERNAL_ERROR:
884         return (TLS1_AD_INTERNAL_ERROR);
885     case SSL_AD_USER_CANCELLED:
886         return (TLS1_AD_USER_CANCELLED);
887     case SSL_AD_NO_RENEGOTIATION:
888         return (TLS1_AD_NO_RENEGOTIATION);
889     case SSL_AD_UNSUPPORTED_EXTENSION:
890         return (TLS1_AD_UNSUPPORTED_EXTENSION);
891     case SSL_AD_CERTIFICATE_UNOBTAINABLE:
892         return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
893     case SSL_AD_UNRECOGNIZED_NAME:
894         return (TLS1_AD_UNRECOGNIZED_NAME);
895     case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
896         return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
897     case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
898         return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
899     case SSL_AD_UNKNOWN_PSK_IDENTITY:
900         return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
901     case SSL_AD_INAPPROPRIATE_FALLBACK:
902         return (TLS1_AD_INAPPROPRIATE_FALLBACK);
903     default:
904         return (-1);
905     }
906 }