Create a RECORD_LAYER structure and move read_ahead into it.
[openssl.git] / ssl / s3_enc.c
1 /* ssl/s3_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 #include <openssl/evp.h>
141 #include <openssl/md5.h>
142
143 static const unsigned char ssl3_pad_1[48] = {
144     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
145     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
146     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
147     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
148     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
149     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
150 };
151
152 static const unsigned char ssl3_pad_2[48] = {
153     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
154     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
155     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
156     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
157     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
158     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
159 };
160
161 static int ssl3_handshake_mac(SSL *s, int md_nid,
162                               const char *sender, int len, unsigned char *p);
163 static int ssl3_generate_key_block(SSL *s, unsigned char *km, int num)
164 {
165     EVP_MD_CTX m5;
166     EVP_MD_CTX s1;
167     unsigned char buf[16], smd[SHA_DIGEST_LENGTH];
168     unsigned char c = 'A';
169     unsigned int i, j, k;
170
171 #ifdef CHARSET_EBCDIC
172     c = os_toascii[c];          /* 'A' in ASCII */
173 #endif
174     k = 0;
175     EVP_MD_CTX_init(&m5);
176     EVP_MD_CTX_set_flags(&m5, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
177     EVP_MD_CTX_init(&s1);
178     for (i = 0; (int)i < num; i += MD5_DIGEST_LENGTH) {
179         k++;
180         if (k > sizeof buf) {
181             /* bug: 'buf' is too small for this ciphersuite */
182             SSLerr(SSL_F_SSL3_GENERATE_KEY_BLOCK, ERR_R_INTERNAL_ERROR);
183             return 0;
184         }
185
186         for (j = 0; j < k; j++)
187             buf[j] = c;
188         c++;
189         EVP_DigestInit_ex(&s1, EVP_sha1(), NULL);
190         EVP_DigestUpdate(&s1, buf, k);
191         EVP_DigestUpdate(&s1, s->session->master_key,
192                          s->session->master_key_length);
193         EVP_DigestUpdate(&s1, s->s3->server_random, SSL3_RANDOM_SIZE);
194         EVP_DigestUpdate(&s1, s->s3->client_random, SSL3_RANDOM_SIZE);
195         EVP_DigestFinal_ex(&s1, smd, NULL);
196
197         EVP_DigestInit_ex(&m5, EVP_md5(), NULL);
198         EVP_DigestUpdate(&m5, s->session->master_key,
199                          s->session->master_key_length);
200         EVP_DigestUpdate(&m5, smd, SHA_DIGEST_LENGTH);
201         if ((int)(i + MD5_DIGEST_LENGTH) > num) {
202             EVP_DigestFinal_ex(&m5, smd, NULL);
203             memcpy(km, smd, (num - i));
204         } else
205             EVP_DigestFinal_ex(&m5, km, NULL);
206
207         km += MD5_DIGEST_LENGTH;
208     }
209     OPENSSL_cleanse(smd, SHA_DIGEST_LENGTH);
210     EVP_MD_CTX_cleanup(&m5);
211     EVP_MD_CTX_cleanup(&s1);
212     return 1;
213 }
214
215 int ssl3_change_cipher_state(SSL *s, int which)
216 {
217     unsigned char *p, *mac_secret;
218     unsigned char exp_key[EVP_MAX_KEY_LENGTH];
219     unsigned char exp_iv[EVP_MAX_IV_LENGTH];
220     unsigned char *ms, *key, *iv, *er1, *er2;
221     EVP_CIPHER_CTX *dd;
222     const EVP_CIPHER *c;
223 #ifndef OPENSSL_NO_COMP
224     COMP_METHOD *comp;
225 #endif
226     const EVP_MD *m;
227     EVP_MD_CTX md;
228     int is_exp, n, i, j, k, cl;
229     int reuse_dd = 0;
230
231     is_exp = SSL_C_IS_EXPORT(s->s3->tmp.new_cipher);
232     c = s->s3->tmp.new_sym_enc;
233     m = s->s3->tmp.new_hash;
234     /* m == NULL will lead to a crash later */
235     OPENSSL_assert(m);
236 #ifndef OPENSSL_NO_COMP
237     if (s->s3->tmp.new_compression == NULL)
238         comp = NULL;
239     else
240         comp = s->s3->tmp.new_compression->method;
241 #endif
242
243     if (which & SSL3_CC_READ) {
244         if (s->enc_read_ctx != NULL)
245             reuse_dd = 1;
246         else if ((s->enc_read_ctx =
247                   OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
248             goto err;
249         else
250             /*
251              * make sure it's intialized in case we exit later with an error
252              */
253             EVP_CIPHER_CTX_init(s->enc_read_ctx);
254         dd = s->enc_read_ctx;
255
256         if(!ssl_replace_hash(&s->read_hash, m)) {
257                 SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
258                 goto err2;
259         }
260 #ifndef OPENSSL_NO_COMP
261         /* COMPRESS */
262         if (s->expand != NULL) {
263             COMP_CTX_free(s->expand);
264             s->expand = NULL;
265         }
266         if (comp != NULL) {
267             s->expand = COMP_CTX_new(comp);
268             if (s->expand == NULL) {
269                 SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,
270                        SSL_R_COMPRESSION_LIBRARY_ERROR);
271                 goto err2;
272             }
273             if (s->s3->rrec.comp == NULL)
274                 s->s3->rrec.comp = (unsigned char *)
275                     OPENSSL_malloc(SSL3_RT_MAX_PLAIN_LENGTH);
276             if (s->s3->rrec.comp == NULL)
277                 goto err;
278         }
279 #endif
280         memset(&(s->s3->read_sequence[0]), 0, 8);
281         mac_secret = &(s->s3->read_mac_secret[0]);
282     } else {
283         if (s->enc_write_ctx != NULL)
284             reuse_dd = 1;
285         else if ((s->enc_write_ctx =
286                   OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
287             goto err;
288         else
289             /*
290              * make sure it's intialized in case we exit later with an error
291              */
292             EVP_CIPHER_CTX_init(s->enc_write_ctx);
293         dd = s->enc_write_ctx;
294         if(!ssl_replace_hash(&s->write_hash, m)) {
295                 SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
296                 goto err2;
297         }
298 #ifndef OPENSSL_NO_COMP
299         /* COMPRESS */
300         if (s->compress != NULL) {
301             COMP_CTX_free(s->compress);
302             s->compress = NULL;
303         }
304         if (comp != NULL) {
305             s->compress = COMP_CTX_new(comp);
306             if (s->compress == NULL) {
307                 SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE,
308                        SSL_R_COMPRESSION_LIBRARY_ERROR);
309                 goto err2;
310             }
311         }
312 #endif
313         memset(&(s->s3->write_sequence[0]), 0, 8);
314         mac_secret = &(s->s3->write_mac_secret[0]);
315     }
316
317     if (reuse_dd)
318         EVP_CIPHER_CTX_cleanup(dd);
319
320     p = s->s3->tmp.key_block;
321     i = EVP_MD_size(m);
322     if (i < 0)
323         goto err2;
324     cl = EVP_CIPHER_key_length(c);
325     j = is_exp ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ?
326                   cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl;
327     /* Was j=(is_exp)?5:EVP_CIPHER_key_length(c); */
328     k = EVP_CIPHER_iv_length(c);
329     if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
330         (which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
331         ms = &(p[0]);
332         n = i + i;
333         key = &(p[n]);
334         n += j + j;
335         iv = &(p[n]);
336         n += k + k;
337         er1 = &(s->s3->client_random[0]);
338         er2 = &(s->s3->server_random[0]);
339     } else {
340         n = i;
341         ms = &(p[n]);
342         n += i + j;
343         key = &(p[n]);
344         n += j + k;
345         iv = &(p[n]);
346         n += k;
347         er1 = &(s->s3->server_random[0]);
348         er2 = &(s->s3->client_random[0]);
349     }
350
351     if (n > s->s3->tmp.key_block_length) {
352         SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
353         goto err2;
354     }
355
356     EVP_MD_CTX_init(&md);
357     memcpy(mac_secret, ms, i);
358     if (is_exp) {
359         /*
360          * In here I set both the read and write key/iv to the same value
361          * since only the correct one will be used :-).
362          */
363         EVP_DigestInit_ex(&md, EVP_md5(), NULL);
364         EVP_DigestUpdate(&md, key, j);
365         EVP_DigestUpdate(&md, er1, SSL3_RANDOM_SIZE);
366         EVP_DigestUpdate(&md, er2, SSL3_RANDOM_SIZE);
367         EVP_DigestFinal_ex(&md, &(exp_key[0]), NULL);
368         key = &(exp_key[0]);
369
370         if (k > 0) {
371             EVP_DigestInit_ex(&md, EVP_md5(), NULL);
372             EVP_DigestUpdate(&md, er1, SSL3_RANDOM_SIZE);
373             EVP_DigestUpdate(&md, er2, SSL3_RANDOM_SIZE);
374             EVP_DigestFinal_ex(&md, &(exp_iv[0]), NULL);
375             iv = &(exp_iv[0]);
376         }
377     }
378
379     EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE));
380
381 #ifdef OPENSSL_SSL_TRACE_CRYPTO
382     if (s->msg_callback) {
383
384         int wh = which & SSL3_CC_WRITE ?
385             TLS1_RT_CRYPTO_WRITE : TLS1_RT_CRYPTO_READ;
386         s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
387                         mac_secret, EVP_MD_size(m), s, s->msg_callback_arg);
388         if (c->key_len)
389             s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
390                             key, c->key_len, s, s->msg_callback_arg);
391         if (k) {
392             s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_IV,
393                             iv, k, s, s->msg_callback_arg);
394         }
395     }
396 #endif
397
398     OPENSSL_cleanse(&(exp_key[0]), sizeof(exp_key));
399     OPENSSL_cleanse(&(exp_iv[0]), sizeof(exp_iv));
400     EVP_MD_CTX_cleanup(&md);
401     return (1);
402  err:
403     SSLerr(SSL_F_SSL3_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
404  err2:
405     return (0);
406 }
407
408 int ssl3_setup_key_block(SSL *s)
409 {
410     unsigned char *p;
411     const EVP_CIPHER *c;
412     const EVP_MD *hash;
413     int num;
414     int ret = 0;
415     SSL_COMP *comp;
416
417     if (s->s3->tmp.key_block_length != 0)
418         return (1);
419
420     if (!ssl_cipher_get_evp(s->session, &c, &hash, NULL, NULL, &comp, 0)) {
421         SSLerr(SSL_F_SSL3_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
422         return (0);
423     }
424
425     s->s3->tmp.new_sym_enc = c;
426     s->s3->tmp.new_hash = hash;
427 #ifdef OPENSSL_NO_COMP
428     s->s3->tmp.new_compression = NULL;
429 #else
430     s->s3->tmp.new_compression = comp;
431 #endif
432
433     num = EVP_MD_size(hash);
434     if (num < 0)
435         return 0;
436
437     num = EVP_CIPHER_key_length(c) + num + EVP_CIPHER_iv_length(c);
438     num *= 2;
439
440     ssl3_cleanup_key_block(s);
441
442     if ((p = OPENSSL_malloc(num)) == NULL)
443         goto err;
444
445     s->s3->tmp.key_block_length = num;
446     s->s3->tmp.key_block = p;
447
448     ret = ssl3_generate_key_block(s, p, num);
449
450     if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)) {
451         /*
452          * enable vulnerability countermeasure for CBC ciphers with known-IV
453          * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
454          */
455         s->s3->need_empty_fragments = 1;
456
457         if (s->session->cipher != NULL) {
458             if (s->session->cipher->algorithm_enc == SSL_eNULL)
459                 s->s3->need_empty_fragments = 0;
460
461 #ifndef OPENSSL_NO_RC4
462             if (s->session->cipher->algorithm_enc == SSL_RC4)
463                 s->s3->need_empty_fragments = 0;
464 #endif
465         }
466     }
467
468     return ret;
469
470  err:
471     SSLerr(SSL_F_SSL3_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
472     return (0);
473 }
474
475 void ssl3_cleanup_key_block(SSL *s)
476 {
477     if (s->s3->tmp.key_block != NULL) {
478         OPENSSL_cleanse(s->s3->tmp.key_block, s->s3->tmp.key_block_length);
479         OPENSSL_free(s->s3->tmp.key_block);
480         s->s3->tmp.key_block = NULL;
481     }
482     s->s3->tmp.key_block_length = 0;
483 }
484
485 /*-
486  * ssl3_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
487  *
488  * Returns:
489  *   0: (in non-constant time) if the record is publically invalid (i.e. too
490  *       short etc).
491  *   1: if the record's padding is valid / the encryption was successful.
492  *   -1: if the record's padding is invalid or, if sending, an internal error
493  *       occurred.
494  */
495 int ssl3_enc(SSL *s, int send)
496 {
497     SSL3_RECORD *rec;
498     EVP_CIPHER_CTX *ds;
499     unsigned long l;
500     int bs, i, mac_size = 0;
501     const EVP_CIPHER *enc;
502
503     if (send) {
504         ds = s->enc_write_ctx;
505         rec = &(s->s3->wrec);
506         if (s->enc_write_ctx == NULL)
507             enc = NULL;
508         else
509             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
510     } else {
511         ds = s->enc_read_ctx;
512         rec = &(s->s3->rrec);
513         if (s->enc_read_ctx == NULL)
514             enc = NULL;
515         else
516             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
517     }
518
519     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
520         memmove(rec->data, rec->input, rec->length);
521         rec->input = rec->data;
522     } else {
523         l = rec->length;
524         bs = EVP_CIPHER_block_size(ds->cipher);
525
526         /* COMPRESS */
527
528         if ((bs != 1) && send) {
529             i = bs - ((int)l % bs);
530
531             /* we need to add 'i-1' padding bytes */
532             l += i;
533             /*
534              * the last of these zero bytes will be overwritten with the
535              * padding length.
536              */
537             memset(&rec->input[rec->length], 0, i);
538             rec->length += i;
539             rec->input[l - 1] = (i - 1);
540         }
541
542         if (!send) {
543             if (l == 0 || l % bs != 0)
544                 return 0;
545             /* otherwise, rec->length >= bs */
546         }
547
548         if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
549             return -1;
550
551         if (EVP_MD_CTX_md(s->read_hash) != NULL)
552             mac_size = EVP_MD_CTX_size(s->read_hash);
553         if ((bs != 1) && !send)
554             return ssl3_cbc_remove_padding(s, rec, bs, mac_size);
555     }
556     return (1);
557 }
558
559 void ssl3_init_finished_mac(SSL *s)
560 {
561     BIO_free(s->s3->handshake_buffer);
562     if (s->s3->handshake_dgst)
563         ssl3_free_digest_list(s);
564     s->s3->handshake_buffer = BIO_new(BIO_s_mem());
565     (void)BIO_set_close(s->s3->handshake_buffer, BIO_CLOSE);
566 }
567
568 void ssl3_free_digest_list(SSL *s)
569 {
570     int i;
571     if (!s->s3->handshake_dgst)
572         return;
573     for (i = 0; i < SSL_MAX_DIGEST; i++) {
574         if (s->s3->handshake_dgst[i])
575             EVP_MD_CTX_destroy(s->s3->handshake_dgst[i]);
576     }
577     OPENSSL_free(s->s3->handshake_dgst);
578     s->s3->handshake_dgst = NULL;
579 }
580
581 void ssl3_finish_mac(SSL *s, const unsigned char *buf, int len)
582 {
583     if (s->s3->handshake_buffer
584         && !(s->s3->flags & TLS1_FLAGS_KEEP_HANDSHAKE)) {
585         BIO_write(s->s3->handshake_buffer, (void *)buf, len);
586     } else {
587         int i;
588         for (i = 0; i < SSL_MAX_DIGEST; i++) {
589             if (s->s3->handshake_dgst[i] != NULL)
590                 EVP_DigestUpdate(s->s3->handshake_dgst[i], buf, len);
591         }
592     }
593 }
594
595 int ssl3_digest_cached_records(SSL *s)
596 {
597     int i;
598     long mask;
599     const EVP_MD *md;
600     long hdatalen;
601     void *hdata;
602
603     /* Allocate handshake_dgst array */
604     ssl3_free_digest_list(s);
605     s->s3->handshake_dgst =
606         OPENSSL_malloc(SSL_MAX_DIGEST * sizeof(EVP_MD_CTX *));
607     if (s->s3->handshake_dgst == NULL) {
608         SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, ERR_R_MALLOC_FAILURE);
609         return 0;
610     }
611     memset(s->s3->handshake_dgst, 0, SSL_MAX_DIGEST * sizeof(EVP_MD_CTX *));
612     hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
613     if (hdatalen <= 0) {
614         SSLerr(SSL_F_SSL3_DIGEST_CACHED_RECORDS, SSL_R_BAD_HANDSHAKE_LENGTH);
615         return 0;
616     }
617
618     /* Loop through bitso of algorithm2 field and create MD_CTX-es */
619     for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++) {
620         if ((mask & ssl_get_algorithm2(s)) && md) {
621             s->s3->handshake_dgst[i] = EVP_MD_CTX_create();
622             if (EVP_MD_nid(md) == NID_md5) {
623                 EVP_MD_CTX_set_flags(s->s3->handshake_dgst[i],
624                                      EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
625             }
626             EVP_DigestInit_ex(s->s3->handshake_dgst[i], md, NULL);
627             EVP_DigestUpdate(s->s3->handshake_dgst[i], hdata, hdatalen);
628         } else {
629             s->s3->handshake_dgst[i] = NULL;
630         }
631     }
632     if (!(s->s3->flags & TLS1_FLAGS_KEEP_HANDSHAKE)) {
633         /* Free handshake_buffer BIO */
634         BIO_free(s->s3->handshake_buffer);
635         s->s3->handshake_buffer = NULL;
636     }
637
638     return 1;
639 }
640
641 int ssl3_cert_verify_mac(SSL *s, int md_nid, unsigned char *p)
642 {
643     return (ssl3_handshake_mac(s, md_nid, NULL, 0, p));
644 }
645
646 int ssl3_final_finish_mac(SSL *s,
647                           const char *sender, int len, unsigned char *p)
648 {
649     int ret, sha1len;
650     ret = ssl3_handshake_mac(s, NID_md5, sender, len, p);
651     if (ret == 0)
652         return 0;
653
654     p += ret;
655
656     sha1len = ssl3_handshake_mac(s, NID_sha1, sender, len, p);
657     if (sha1len == 0)
658         return 0;
659
660     ret += sha1len;
661     return (ret);
662 }
663
664 static int ssl3_handshake_mac(SSL *s, int md_nid,
665                               const char *sender, int len, unsigned char *p)
666 {
667     unsigned int ret;
668     int npad, n;
669     unsigned int i;
670     unsigned char md_buf[EVP_MAX_MD_SIZE];
671     EVP_MD_CTX ctx, *d = NULL;
672
673     if (s->s3->handshake_buffer)
674         if (!ssl3_digest_cached_records(s))
675             return 0;
676
677     /*
678      * Search for digest of specified type in the handshake_dgst array
679      */
680     for (i = 0; i < SSL_MAX_DIGEST; i++) {
681         if (s->s3->handshake_dgst[i]
682             && EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) {
683             d = s->s3->handshake_dgst[i];
684             break;
685         }
686     }
687     if (!d) {
688         SSLerr(SSL_F_SSL3_HANDSHAKE_MAC, SSL_R_NO_REQUIRED_DIGEST);
689         return 0;
690     }
691     EVP_MD_CTX_init(&ctx);
692     EVP_MD_CTX_set_flags(&ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
693     EVP_MD_CTX_copy_ex(&ctx, d);
694     n = EVP_MD_CTX_size(&ctx);
695     if (n < 0)
696         return 0;
697
698     npad = (48 / n) * n;
699     if (sender != NULL)
700         EVP_DigestUpdate(&ctx, sender, len);
701     EVP_DigestUpdate(&ctx, s->session->master_key,
702                      s->session->master_key_length);
703     EVP_DigestUpdate(&ctx, ssl3_pad_1, npad);
704     EVP_DigestFinal_ex(&ctx, md_buf, &i);
705
706     EVP_DigestInit_ex(&ctx, EVP_MD_CTX_md(&ctx), NULL);
707     EVP_DigestUpdate(&ctx, s->session->master_key,
708                      s->session->master_key_length);
709     EVP_DigestUpdate(&ctx, ssl3_pad_2, npad);
710     EVP_DigestUpdate(&ctx, md_buf, i);
711     EVP_DigestFinal_ex(&ctx, p, &ret);
712
713     EVP_MD_CTX_cleanup(&ctx);
714
715     return ((int)ret);
716 }
717
718 int n_ssl3_mac(SSL *ssl, unsigned char *md, int send)
719 {
720     SSL3_RECORD *rec;
721     unsigned char *mac_sec, *seq;
722     EVP_MD_CTX md_ctx;
723     const EVP_MD_CTX *hash;
724     unsigned char *p, rec_char;
725     size_t md_size;
726     int npad;
727     int t;
728
729     if (send) {
730         rec = &(ssl->s3->wrec);
731         mac_sec = &(ssl->s3->write_mac_secret[0]);
732         seq = &(ssl->s3->write_sequence[0]);
733         hash = ssl->write_hash;
734     } else {
735         rec = &(ssl->s3->rrec);
736         mac_sec = &(ssl->s3->read_mac_secret[0]);
737         seq = &(ssl->s3->read_sequence[0]);
738         hash = ssl->read_hash;
739     }
740
741     t = EVP_MD_CTX_size(hash);
742     if (t < 0)
743         return -1;
744     md_size = t;
745     npad = (48 / md_size) * md_size;
746
747     if (!send &&
748         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
749         ssl3_cbc_record_digest_supported(hash)) {
750         /*
751          * This is a CBC-encrypted record. We must avoid leaking any
752          * timing-side channel information about how many blocks of data we
753          * are hashing because that gives an attacker a timing-oracle.
754          */
755
756         /*-
757          * npad is, at most, 48 bytes and that's with MD5:
758          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
759          *
760          * With SHA-1 (the largest hash speced for SSLv3) the hash size
761          * goes up 4, but npad goes down by 8, resulting in a smaller
762          * total size.
763          */
764         unsigned char header[75];
765         unsigned j = 0;
766         memcpy(header + j, mac_sec, md_size);
767         j += md_size;
768         memcpy(header + j, ssl3_pad_1, npad);
769         j += npad;
770         memcpy(header + j, seq, 8);
771         j += 8;
772         header[j++] = rec->type;
773         header[j++] = rec->length >> 8;
774         header[j++] = rec->length & 0xff;
775
776         /* Final param == is SSLv3 */
777         ssl3_cbc_digest_record(hash,
778                                md, &md_size,
779                                header, rec->input,
780                                rec->length + md_size, rec->orig_len,
781                                mac_sec, md_size, 1);
782     } else {
783         unsigned int md_size_u;
784         /* Chop the digest off the end :-) */
785         EVP_MD_CTX_init(&md_ctx);
786
787         EVP_MD_CTX_copy_ex(&md_ctx, hash);
788         EVP_DigestUpdate(&md_ctx, mac_sec, md_size);
789         EVP_DigestUpdate(&md_ctx, ssl3_pad_1, npad);
790         EVP_DigestUpdate(&md_ctx, seq, 8);
791         rec_char = rec->type;
792         EVP_DigestUpdate(&md_ctx, &rec_char, 1);
793         p = md;
794         s2n(rec->length, p);
795         EVP_DigestUpdate(&md_ctx, md, 2);
796         EVP_DigestUpdate(&md_ctx, rec->input, rec->length);
797         EVP_DigestFinal_ex(&md_ctx, md, NULL);
798
799         EVP_MD_CTX_copy_ex(&md_ctx, hash);
800         EVP_DigestUpdate(&md_ctx, mac_sec, md_size);
801         EVP_DigestUpdate(&md_ctx, ssl3_pad_2, npad);
802         EVP_DigestUpdate(&md_ctx, md, md_size);
803         EVP_DigestFinal_ex(&md_ctx, md, &md_size_u);
804         md_size = md_size_u;
805
806         EVP_MD_CTX_cleanup(&md_ctx);
807     }
808
809     ssl3_record_sequence_update(seq);
810     return (md_size);
811 }
812
813 void ssl3_record_sequence_update(unsigned char *seq)
814 {
815     int i;
816
817     for (i = 7; i >= 0; i--) {
818         ++seq[i];
819         if (seq[i] != 0)
820             break;
821     }
822 }
823
824 int ssl3_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
825                                 int len)
826 {
827     static const unsigned char *salt[3] = {
828 #ifndef CHARSET_EBCDIC
829         (const unsigned char *)"A",
830         (const unsigned char *)"BB",
831         (const unsigned char *)"CCC",
832 #else
833         (const unsigned char *)"\x41",
834         (const unsigned char *)"\x42\x42",
835         (const unsigned char *)"\x43\x43\x43",
836 #endif
837     };
838     unsigned char buf[EVP_MAX_MD_SIZE];
839     EVP_MD_CTX ctx;
840     int i, ret = 0;
841     unsigned int n;
842 #ifdef OPENSSL_SSL_TRACE_CRYPTO
843     unsigned char *tmpout = out;
844 #endif
845
846     EVP_MD_CTX_init(&ctx);
847     for (i = 0; i < 3; i++) {
848         EVP_DigestInit_ex(&ctx, s->ctx->sha1, NULL);
849         EVP_DigestUpdate(&ctx, salt[i], strlen((const char *)salt[i]));
850         EVP_DigestUpdate(&ctx, p, len);
851         EVP_DigestUpdate(&ctx, &(s->s3->client_random[0]), SSL3_RANDOM_SIZE);
852         EVP_DigestUpdate(&ctx, &(s->s3->server_random[0]), SSL3_RANDOM_SIZE);
853         EVP_DigestFinal_ex(&ctx, buf, &n);
854
855         EVP_DigestInit_ex(&ctx, s->ctx->md5, NULL);
856         EVP_DigestUpdate(&ctx, p, len);
857         EVP_DigestUpdate(&ctx, buf, n);
858         EVP_DigestFinal_ex(&ctx, out, &n);
859         out += n;
860         ret += n;
861     }
862     EVP_MD_CTX_cleanup(&ctx);
863
864 #ifdef OPENSSL_SSL_TRACE_CRYPTO
865     if (s->msg_callback) {
866         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
867                         p, len, s, s->msg_callback_arg);
868         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
869                         s->s3->client_random, SSL3_RANDOM_SIZE,
870                         s, s->msg_callback_arg);
871         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
872                         s->s3->server_random, SSL3_RANDOM_SIZE,
873                         s, s->msg_callback_arg);
874         s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
875                         tmpout, SSL3_MASTER_SECRET_SIZE,
876                         s, s->msg_callback_arg);
877     }
878 #endif
879     OPENSSL_cleanse(buf, sizeof buf);
880     return (ret);
881 }
882
883 int ssl3_alert_code(int code)
884 {
885     switch (code) {
886     case SSL_AD_CLOSE_NOTIFY:
887         return (SSL3_AD_CLOSE_NOTIFY);
888     case SSL_AD_UNEXPECTED_MESSAGE:
889         return (SSL3_AD_UNEXPECTED_MESSAGE);
890     case SSL_AD_BAD_RECORD_MAC:
891         return (SSL3_AD_BAD_RECORD_MAC);
892     case SSL_AD_DECRYPTION_FAILED:
893         return (SSL3_AD_BAD_RECORD_MAC);
894     case SSL_AD_RECORD_OVERFLOW:
895         return (SSL3_AD_BAD_RECORD_MAC);
896     case SSL_AD_DECOMPRESSION_FAILURE:
897         return (SSL3_AD_DECOMPRESSION_FAILURE);
898     case SSL_AD_HANDSHAKE_FAILURE:
899         return (SSL3_AD_HANDSHAKE_FAILURE);
900     case SSL_AD_NO_CERTIFICATE:
901         return (SSL3_AD_NO_CERTIFICATE);
902     case SSL_AD_BAD_CERTIFICATE:
903         return (SSL3_AD_BAD_CERTIFICATE);
904     case SSL_AD_UNSUPPORTED_CERTIFICATE:
905         return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
906     case SSL_AD_CERTIFICATE_REVOKED:
907         return (SSL3_AD_CERTIFICATE_REVOKED);
908     case SSL_AD_CERTIFICATE_EXPIRED:
909         return (SSL3_AD_CERTIFICATE_EXPIRED);
910     case SSL_AD_CERTIFICATE_UNKNOWN:
911         return (SSL3_AD_CERTIFICATE_UNKNOWN);
912     case SSL_AD_ILLEGAL_PARAMETER:
913         return (SSL3_AD_ILLEGAL_PARAMETER);
914     case SSL_AD_UNKNOWN_CA:
915         return (SSL3_AD_BAD_CERTIFICATE);
916     case SSL_AD_ACCESS_DENIED:
917         return (SSL3_AD_HANDSHAKE_FAILURE);
918     case SSL_AD_DECODE_ERROR:
919         return (SSL3_AD_HANDSHAKE_FAILURE);
920     case SSL_AD_DECRYPT_ERROR:
921         return (SSL3_AD_HANDSHAKE_FAILURE);
922     case SSL_AD_EXPORT_RESTRICTION:
923         return (SSL3_AD_HANDSHAKE_FAILURE);
924     case SSL_AD_PROTOCOL_VERSION:
925         return (SSL3_AD_HANDSHAKE_FAILURE);
926     case SSL_AD_INSUFFICIENT_SECURITY:
927         return (SSL3_AD_HANDSHAKE_FAILURE);
928     case SSL_AD_INTERNAL_ERROR:
929         return (SSL3_AD_HANDSHAKE_FAILURE);
930     case SSL_AD_USER_CANCELLED:
931         return (SSL3_AD_HANDSHAKE_FAILURE);
932     case SSL_AD_NO_RENEGOTIATION:
933         return (-1);            /* Don't send it :-) */
934     case SSL_AD_UNSUPPORTED_EXTENSION:
935         return (SSL3_AD_HANDSHAKE_FAILURE);
936     case SSL_AD_CERTIFICATE_UNOBTAINABLE:
937         return (SSL3_AD_HANDSHAKE_FAILURE);
938     case SSL_AD_UNRECOGNIZED_NAME:
939         return (SSL3_AD_HANDSHAKE_FAILURE);
940     case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
941         return (SSL3_AD_HANDSHAKE_FAILURE);
942     case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
943         return (SSL3_AD_HANDSHAKE_FAILURE);
944     case SSL_AD_UNKNOWN_PSK_IDENTITY:
945         return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
946     case SSL_AD_INAPPROPRIATE_FALLBACK:
947         return (TLS1_AD_INAPPROPRIATE_FALLBACK);
948     default:
949         return (-1);
950     }
951 }