Keep old method in case of an unsupported protocol
[openssl.git] / ssl / s3_cbc.c
1 /* ssl/s3_cbc.c */
2 /* ====================================================================
3  * Copyright (c) 2012 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55
56 #include "../crypto/constant_time_locl.h"
57 #include "ssl_locl.h"
58
59 #include <openssl/md5.h>
60 #include <openssl/sha.h>
61
62 /* MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's length
63  * field. (SHA-384/512 have 128-bit length.) */
64 #define MAX_HASH_BIT_COUNT_BYTES 16
65
66 /* MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
67  * Currently SHA-384/512 has a 128-byte block size and that's the largest
68  * supported by TLS.) */
69 #define MAX_HASH_BLOCK_SIZE 128
70
71 /* ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
72  * record in |rec| by updating |rec->length| in constant time.
73  *
74  * block_size: the block size of the cipher used to encrypt the record.
75  * returns:
76  *   0: (in non-constant time) if the record is publicly invalid.
77  *   1: if the padding was valid
78  *  -1: otherwise. */
79 int ssl3_cbc_remove_padding(const SSL* s,
80                             SSL3_RECORD *rec,
81                             unsigned block_size,
82                             unsigned mac_size)
83         {
84         unsigned padding_length, good;
85         const unsigned overhead = 1 /* padding length byte */ + mac_size;
86
87         /* These lengths are all public so we can test them in non-constant
88          * time. */
89         if (overhead > rec->length)
90                 return 0;
91
92         padding_length = rec->data[rec->length-1];
93         good = constant_time_ge(rec->length, padding_length+overhead);
94         /* SSLv3 requires that the padding is minimal. */
95         good &= constant_time_ge(block_size, padding_length+1);
96         padding_length = good & (padding_length+1);
97         rec->length -= padding_length;
98         rec->type |= padding_length<<8; /* kludge: pass padding length */
99         return constant_time_select_int(good, 1, -1);
100         }
101
102 /* tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
103  * record in |rec| in constant time and returns 1 if the padding is valid and
104  * -1 otherwise. It also removes any explicit IV from the start of the record
105  * without leaking any timing about whether there was enough space after the
106  * padding was removed.
107  *
108  * block_size: the block size of the cipher used to encrypt the record.
109  * returns:
110  *   0: (in non-constant time) if the record is publicly invalid.
111  *   1: if the padding was valid
112  *  -1: otherwise. */
113 int tls1_cbc_remove_padding(const SSL* s,
114                             SSL3_RECORD *rec,
115                             unsigned block_size,
116                             unsigned mac_size)
117         {
118         unsigned padding_length, good, to_check, i;
119         const unsigned overhead = 1 /* padding length byte */ + mac_size;
120         /* Check if version requires explicit IV */
121         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
122                 {
123                 /* These lengths are all public so we can test them in
124                  * non-constant time.
125                  */
126                 if (overhead + block_size > rec->length)
127                         return 0;
128                 /* We can now safely skip explicit IV */
129                 rec->data += block_size;
130                 rec->input += block_size;
131                 rec->length -= block_size;
132                 }
133         else if (overhead > rec->length)
134                 return 0;
135
136         padding_length = rec->data[rec->length-1];
137
138         /* NB: if compression is in operation the first packet may not be of
139          * even length so the padding bug check cannot be performed. This bug
140          * workaround has been around since SSLeay so hopefully it is either
141          * fixed now or no buggy implementation supports compression [steve]
142          */
143         if ( (s->options&SSL_OP_TLS_BLOCK_PADDING_BUG) && !s->expand)
144                 {
145                 /* First packet is even in size, so check */
146                 if ((memcmp(s->s3->read_sequence, "\0\0\0\0\0\0\0\0",8) == 0) &&
147                     !(padding_length & 1))
148                         {
149                         s->s3->flags|=TLS1_FLAGS_TLS_PADDING_BUG;
150                         }
151                 if ((s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) &&
152                     padding_length > 0)
153                         {
154                         padding_length--;
155                         }
156                 }
157
158         good = constant_time_ge(rec->length, overhead+padding_length);
159         /* The padding consists of a length byte at the end of the record and
160          * then that many bytes of padding, all with the same value as the
161          * length byte. Thus, with the length byte included, there are i+1
162          * bytes of padding.
163          *
164          * We can't check just |padding_length+1| bytes because that leaks
165          * decrypted information. Therefore we always have to check the maximum
166          * amount of padding possible. (Again, the length of the record is
167          * public information so we can use it.) */
168         to_check = 255; /* maximum amount of padding. */
169         if (to_check > rec->length-1)
170                 to_check = rec->length-1;
171
172         for (i = 0; i < to_check; i++)
173                 {
174                 unsigned char mask = constant_time_ge_8(padding_length, i);
175                 unsigned char b = rec->data[rec->length-1-i];
176                 /* The final |padding_length+1| bytes should all have the value
177                  * |padding_length|. Therefore the XOR should be zero. */
178                 good &= ~(mask&(padding_length ^ b));
179                 }
180
181         /* If any of the final |padding_length+1| bytes had the wrong value,
182          * one or more of the lower eight bits of |good| will be cleared.
183          */
184         good = constant_time_eq(0xff, good & 0xff);
185         padding_length = good & (padding_length+1);
186         rec->length -= padding_length;
187         rec->type |= padding_length<<8; /* kludge: pass padding length */
188
189         return constant_time_select_int(good, 1, -1);
190         }
191
192 /* ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
193  * constant time (independent of the concrete value of rec->length, which may
194  * vary within a 256-byte window).
195  *
196  * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
197  * this function.
198  *
199  * On entry:
200  *   rec->orig_len >= md_size
201  *   md_size <= EVP_MAX_MD_SIZE
202  *
203  * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
204  * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
205  * a single or pair of cache-lines, then the variable memory accesses don't
206  * actually affect the timing. CPUs with smaller cache-lines [if any] are
207  * not multi-core and are not considered vulnerable to cache-timing attacks.
208  */
209 #define CBC_MAC_ROTATE_IN_PLACE
210
211 void ssl3_cbc_copy_mac(unsigned char* out,
212                        const SSL3_RECORD *rec,
213                        unsigned md_size,unsigned orig_len)
214         {
215 #if defined(CBC_MAC_ROTATE_IN_PLACE)
216         unsigned char rotated_mac_buf[64+EVP_MAX_MD_SIZE];
217         unsigned char *rotated_mac;
218 #else
219         unsigned char rotated_mac[EVP_MAX_MD_SIZE];
220 #endif
221
222         /* mac_end is the index of |rec->data| just after the end of the MAC. */
223         unsigned mac_end = rec->length;
224         unsigned mac_start = mac_end - md_size;
225         /* scan_start contains the number of bytes that we can ignore because
226          * the MAC's position can only vary by 255 bytes. */
227         unsigned scan_start = 0;
228         unsigned i, j;
229         unsigned div_spoiler;
230         unsigned rotate_offset;
231
232         OPENSSL_assert(orig_len >= md_size);
233         OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
234
235 #if defined(CBC_MAC_ROTATE_IN_PLACE)
236         rotated_mac = rotated_mac_buf + ((0-(size_t)rotated_mac_buf)&63);
237 #endif
238
239         /* This information is public so it's safe to branch based on it. */
240         if (orig_len > md_size + 255 + 1)
241                 scan_start = orig_len - (md_size + 255 + 1);
242         /* div_spoiler contains a multiple of md_size that is used to cause the
243          * modulo operation to be constant time. Without this, the time varies
244          * based on the amount of padding when running on Intel chips at least.
245          *
246          * The aim of right-shifting md_size is so that the compiler doesn't
247          * figure out that it can remove div_spoiler as that would require it
248          * to prove that md_size is always even, which I hope is beyond it. */
249         div_spoiler = md_size >> 1;
250         div_spoiler <<= (sizeof(div_spoiler)-1)*8;
251         rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
252
253         memset(rotated_mac, 0, md_size);
254         for (i = scan_start, j = 0; i < orig_len; i++)
255                 {
256                 unsigned char mac_started = constant_time_ge_8(i, mac_start);
257                 unsigned char mac_ended = constant_time_ge_8(i, mac_end);
258                 unsigned char b = rec->data[i];
259                 rotated_mac[j++] |= b & mac_started & ~mac_ended;
260                 j &= constant_time_lt(j,md_size);
261                 }
262
263         /* Now rotate the MAC */
264 #if defined(CBC_MAC_ROTATE_IN_PLACE)
265         j = 0;
266         for (i = 0; i < md_size; i++)
267                 {
268                 /* in case cache-line is 32 bytes, touch second line */
269                 ((volatile unsigned char *)rotated_mac)[rotate_offset^32];
270                 out[j++] = rotated_mac[rotate_offset++];
271                 rotate_offset &= constant_time_lt(rotate_offset,md_size);
272                 }
273 #else
274         memset(out, 0, md_size);
275         rotate_offset = md_size - rotate_offset;
276         rotate_offset &= constant_time_lt(rotate_offset,md_size);
277         for (i = 0; i < md_size; i++)
278                 {
279                 for (j = 0; j < md_size; j++)
280                         out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
281                 rotate_offset++;
282                 rotate_offset &= constant_time_lt(rotate_offset,md_size);
283                 }
284 #endif
285         }
286
287 /* u32toLE serialises an unsigned, 32-bit number (n) as four bytes at (p) in
288  * little-endian order. The value of p is advanced by four. */
289 #define u32toLE(n, p) \
290         (*((p)++)=(unsigned char)(n), \
291          *((p)++)=(unsigned char)(n>>8), \
292          *((p)++)=(unsigned char)(n>>16), \
293          *((p)++)=(unsigned char)(n>>24))
294
295 /* These functions serialize the state of a hash and thus perform the standard
296  * "final" operation without adding the padding and length that such a function
297  * typically does. */
298 static void tls1_md5_final_raw(void* ctx, unsigned char *md_out)
299         {
300         MD5_CTX *md5 = ctx;
301         u32toLE(md5->A, md_out);
302         u32toLE(md5->B, md_out);
303         u32toLE(md5->C, md_out);
304         u32toLE(md5->D, md_out);
305         }
306
307 static void tls1_sha1_final_raw(void* ctx, unsigned char *md_out)
308         {
309         SHA_CTX *sha1 = ctx;
310         l2n(sha1->h0, md_out);
311         l2n(sha1->h1, md_out);
312         l2n(sha1->h2, md_out);
313         l2n(sha1->h3, md_out);
314         l2n(sha1->h4, md_out);
315         }
316 #define LARGEST_DIGEST_CTX SHA_CTX
317
318 #ifndef OPENSSL_NO_SHA256
319 static void tls1_sha256_final_raw(void* ctx, unsigned char *md_out)
320         {
321         SHA256_CTX *sha256 = ctx;
322         unsigned i;
323
324         for (i = 0; i < 8; i++)
325                 {
326                 l2n(sha256->h[i], md_out);
327                 }
328         }
329 #undef  LARGEST_DIGEST_CTX
330 #define LARGEST_DIGEST_CTX SHA256_CTX
331 #endif
332
333 #ifndef OPENSSL_NO_SHA512
334 static void tls1_sha512_final_raw(void* ctx, unsigned char *md_out)
335         {
336         SHA512_CTX *sha512 = ctx;
337         unsigned i;
338
339         for (i = 0; i < 8; i++)
340                 {
341                 l2n8(sha512->h[i], md_out);
342                 }
343         }
344 #undef  LARGEST_DIGEST_CTX
345 #define LARGEST_DIGEST_CTX SHA512_CTX
346 #endif
347
348 /* ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
349  * which ssl3_cbc_digest_record supports. */
350 char ssl3_cbc_record_digest_supported(const EVP_MD *digest)
351         {
352 #ifdef OPENSSL_FIPS
353         if (FIPS_mode())
354                 return 0;
355 #endif
356         switch (EVP_MD_type(digest))
357                 {
358                 case NID_md5:
359                 case NID_sha1:
360 #ifndef OPENSSL_NO_SHA256
361                 case NID_sha224:
362                 case NID_sha256:
363 #endif
364 #ifndef OPENSSL_NO_SHA512
365                 case NID_sha384:
366                 case NID_sha512:
367 #endif
368                         return 1;
369                 default:
370                         return 0;
371                 }
372         }
373
374 /* ssl3_cbc_digest_record computes the MAC of a decrypted, padded SSLv3/TLS
375  * record.
376  *
377  *   ctx: the EVP_MD_CTX from which we take the hash function.
378  *     ssl3_cbc_record_digest_supported must return true for this EVP_MD_CTX.
379  *   md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
380  *   md_out_size: if non-NULL, the number of output bytes is written here.
381  *   header: the 13-byte, TLS record header.
382  *   data: the record data itself, less any preceeding explicit IV.
383  *   data_plus_mac_size: the secret, reported length of the data and MAC
384  *     once the padding has been removed.
385  *   data_plus_mac_plus_padding_size: the public length of the whole
386  *     record, including padding.
387  *   is_sslv3: non-zero if we are to use SSLv3. Otherwise, TLS.
388  *
389  * On entry: by virtue of having been through one of the remove_padding
390  * functions, above, we know that data_plus_mac_size is large enough to contain
391  * a padding byte and MAC. (If the padding was invalid, it might contain the
392  * padding too. ) */
393 void ssl3_cbc_digest_record(
394         const EVP_MD *digest,
395         unsigned char* md_out,
396         size_t* md_out_size,
397         const unsigned char header[13],
398         const unsigned char *data,
399         size_t data_plus_mac_size,
400         size_t data_plus_mac_plus_padding_size,
401         const unsigned char *mac_secret,
402         unsigned mac_secret_length,
403         char is_sslv3)
404         {
405         union { double align;
406                 unsigned char c[sizeof(LARGEST_DIGEST_CTX)]; } md_state;
407         void (*md_final_raw)(void *ctx, unsigned char *md_out);
408         void (*md_transform)(void *ctx, const unsigned char *block);
409         unsigned md_size, md_block_size = 64;
410         unsigned sslv3_pad_length = 40, header_length, variance_blocks,
411                  len, max_mac_bytes, num_blocks,
412                  num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
413         unsigned int bits;      /* at most 18 bits */
414         unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
415         /* hmac_pad is the masked HMAC key. */
416         unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
417         unsigned char first_block[MAX_HASH_BLOCK_SIZE];
418         unsigned char mac_out[EVP_MAX_MD_SIZE];
419         unsigned i, j, md_out_size_u;
420         EVP_MD_CTX md_ctx;
421         /* mdLengthSize is the number of bytes in the length field that terminates
422         * the hash. */
423         unsigned md_length_size = 8;
424         char length_is_big_endian = 1;
425
426         /* This is a, hopefully redundant, check that allows us to forget about
427          * many possible overflows later in this function. */
428         OPENSSL_assert(data_plus_mac_plus_padding_size < 1024*1024);
429
430         switch (EVP_MD_type(digest))
431                 {
432                 case NID_md5:
433                         MD5_Init((MD5_CTX*)md_state.c);
434                         md_final_raw = tls1_md5_final_raw;
435                         md_transform = (void(*)(void *ctx, const unsigned char *block)) MD5_Transform;
436                         md_size = 16;
437                         sslv3_pad_length = 48;
438                         length_is_big_endian = 0;
439                         break;
440                 case NID_sha1:
441                         SHA1_Init((SHA_CTX*)md_state.c);
442                         md_final_raw = tls1_sha1_final_raw;
443                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA1_Transform;
444                         md_size = 20;
445                         break;
446 #ifndef OPENSSL_NO_SHA256
447                 case NID_sha224:
448                         SHA224_Init((SHA256_CTX*)md_state.c);
449                         md_final_raw = tls1_sha256_final_raw;
450                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform;
451                         md_size = 224/8;
452                         break;
453                 case NID_sha256:
454                         SHA256_Init((SHA256_CTX*)md_state.c);
455                         md_final_raw = tls1_sha256_final_raw;
456                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform;
457                         md_size = 32;
458                         break;
459 #endif
460 #ifndef OPENSSL_NO_SHA512
461                 case NID_sha384:
462                         SHA384_Init((SHA512_CTX*)md_state.c);
463                         md_final_raw = tls1_sha512_final_raw;
464                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform;
465                         md_size = 384/8;
466                         md_block_size = 128;
467                         md_length_size = 16;
468                         break;
469                 case NID_sha512:
470                         SHA512_Init((SHA512_CTX*)md_state.c);
471                         md_final_raw = tls1_sha512_final_raw;
472                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform;
473                         md_size = 64;
474                         md_block_size = 128;
475                         md_length_size = 16;
476                         break;
477 #endif
478                 default:
479                         /* ssl3_cbc_record_digest_supported should have been
480                          * called first to check that the hash function is
481                          * supported. */
482                         OPENSSL_assert(0);
483                         if (md_out_size)
484                                 *md_out_size = -1;
485                         return;
486                 }
487
488         OPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES);
489         OPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE);
490         OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
491
492         header_length = 13;
493         if (is_sslv3)
494                 {
495                 header_length =
496                         mac_secret_length +
497                         sslv3_pad_length +
498                         8 /* sequence number */ +
499                         1 /* record type */ +
500                         2 /* record length */;
501                 }
502
503         /* variance_blocks is the number of blocks of the hash that we have to
504          * calculate in constant time because they could be altered by the
505          * padding value.
506          *
507          * In SSLv3, the padding must be minimal so the end of the plaintext
508          * varies by, at most, 15+20 = 35 bytes. (We conservatively assume that
509          * the MAC size varies from 0..20 bytes.) In case the 9 bytes of hash
510          * termination (0x80 + 64-bit length) don't fit in the final block, we
511          * say that the final two blocks can vary based on the padding.
512          *
513          * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
514          * required to be minimal. Therefore we say that the final six blocks
515          * can vary based on the padding.
516          *
517          * Later in the function, if the message is short and there obviously
518          * cannot be this many blocks then variance_blocks can be reduced. */
519         variance_blocks = is_sslv3 ? 2 : 6;
520         /* From now on we're dealing with the MAC, which conceptually has 13
521          * bytes of `header' before the start of the data (TLS) or 71/75 bytes
522          * (SSLv3) */
523         len = data_plus_mac_plus_padding_size + header_length;
524         /* max_mac_bytes contains the maximum bytes of bytes in the MAC, including
525         * |header|, assuming that there's no padding. */
526         max_mac_bytes = len - md_size - 1;
527         /* num_blocks is the maximum number of hash blocks. */
528         num_blocks = (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size;
529         /* In order to calculate the MAC in constant time we have to handle
530          * the final blocks specially because the padding value could cause the
531          * end to appear somewhere in the final |variance_blocks| blocks and we
532          * can't leak where. However, |num_starting_blocks| worth of data can
533          * be hashed right away because no padding value can affect whether
534          * they are plaintext. */
535         num_starting_blocks = 0;
536         /* k is the starting byte offset into the conceptual header||data where
537          * we start processing. */
538         k = 0;
539         /* mac_end_offset is the index just past the end of the data to be
540          * MACed. */
541         mac_end_offset = data_plus_mac_size + header_length - md_size;
542         /* c is the index of the 0x80 byte in the final hash block that
543          * contains application data. */
544         c = mac_end_offset % md_block_size;
545         /* index_a is the hash block number that contains the 0x80 terminating
546          * value. */
547         index_a = mac_end_offset / md_block_size;
548         /* index_b is the hash block number that contains the 64-bit hash
549          * length, in bits. */
550         index_b = (mac_end_offset + md_length_size) / md_block_size;
551         /* bits is the hash-length in bits. It includes the additional hash
552          * block for the masked HMAC key, or whole of |header| in the case of
553          * SSLv3. */
554
555         /* For SSLv3, if we're going to have any starting blocks then we need
556          * at least two because the header is larger than a single block. */
557         if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0))
558                 {
559                 num_starting_blocks = num_blocks - variance_blocks;
560                 k = md_block_size*num_starting_blocks;
561                 }
562
563         bits = 8*mac_end_offset;
564         if (!is_sslv3)
565                 {
566                 /* Compute the initial HMAC block. For SSLv3, the padding and
567                  * secret bytes are included in |header| because they take more
568                  * than a single block. */
569                 bits += 8*md_block_size;
570                 memset(hmac_pad, 0, md_block_size);
571                 OPENSSL_assert(mac_secret_length <= sizeof(hmac_pad));
572                 memcpy(hmac_pad, mac_secret, mac_secret_length);
573                 for (i = 0; i < md_block_size; i++)
574                         hmac_pad[i] ^= 0x36;
575
576                 md_transform(md_state.c, hmac_pad);
577                 }
578
579         if (length_is_big_endian)
580                 {
581                 memset(length_bytes,0,md_length_size-4);
582                 length_bytes[md_length_size-4] = (unsigned char)(bits>>24);
583                 length_bytes[md_length_size-3] = (unsigned char)(bits>>16);
584                 length_bytes[md_length_size-2] = (unsigned char)(bits>>8);
585                 length_bytes[md_length_size-1] = (unsigned char)bits;
586                 }
587         else
588                 {
589                 memset(length_bytes,0,md_length_size);
590                 length_bytes[md_length_size-5] = (unsigned char)(bits>>24);
591                 length_bytes[md_length_size-6] = (unsigned char)(bits>>16);
592                 length_bytes[md_length_size-7] = (unsigned char)(bits>>8);
593                 length_bytes[md_length_size-8] = (unsigned char)bits;
594                 }
595
596         if (k > 0)
597                 {
598                 if (is_sslv3)
599                         {
600                         /* The SSLv3 header is larger than a single block.
601                          * overhang is the number of bytes beyond a single
602                          * block that the header consumes: either 7 bytes
603                          * (SHA1) or 11 bytes (MD5). */
604                         unsigned overhang = header_length-md_block_size;
605                         md_transform(md_state.c, header);
606                         memcpy(first_block, header + md_block_size, overhang);
607                         memcpy(first_block + overhang, data, md_block_size-overhang);
608                         md_transform(md_state.c, first_block);
609                         for (i = 1; i < k/md_block_size - 1; i++)
610                                 md_transform(md_state.c, data + md_block_size*i - overhang);
611                         }
612                 else
613                         {
614                         /* k is a multiple of md_block_size. */
615                         memcpy(first_block, header, 13);
616                         memcpy(first_block+13, data, md_block_size-13);
617                         md_transform(md_state.c, first_block);
618                         for (i = 1; i < k/md_block_size; i++)
619                                 md_transform(md_state.c, data + md_block_size*i - 13);
620                         }
621                 }
622
623         memset(mac_out, 0, sizeof(mac_out));
624
625         /* We now process the final hash blocks. For each block, we construct
626          * it in constant time. If the |i==index_a| then we'll include the 0x80
627          * bytes and zero pad etc. For each block we selectively copy it, in
628          * constant time, to |mac_out|. */
629         for (i = num_starting_blocks; i <= num_starting_blocks+variance_blocks; i++)
630                 {
631                 unsigned char block[MAX_HASH_BLOCK_SIZE];
632                 unsigned char is_block_a = constant_time_eq_8(i, index_a);
633                 unsigned char is_block_b = constant_time_eq_8(i, index_b);
634                 for (j = 0; j < md_block_size; j++)
635                         {
636                         unsigned char b = 0, is_past_c, is_past_cp1;
637                         if (k < header_length)
638                                 b = header[k];
639                         else if (k < data_plus_mac_plus_padding_size + header_length)
640                                 b = data[k-header_length];
641                         k++;
642
643                         is_past_c = is_block_a & constant_time_ge_8(j, c);
644                         is_past_cp1 = is_block_a & constant_time_ge_8(j, c+1);
645                         /* If this is the block containing the end of the
646                          * application data, and we are at the offset for the
647                          * 0x80 value, then overwrite b with 0x80. */
648                         b =  constant_time_select_8(is_past_c, 0x80, b);
649                         /* If this the the block containing the end of the
650                          * application data and we're past the 0x80 value then
651                          * just write zero. */
652                         b = b&~is_past_cp1;
653                         /* If this is index_b (the final block), but not
654                          * index_a (the end of the data), then the 64-bit
655                          * length didn't fit into index_a and we're having to
656                          * add an extra block of zeros. */
657                         b &= ~is_block_b | is_block_a;
658
659                         /* The final bytes of one of the blocks contains the
660                          * length. */
661                         if (j >= md_block_size - md_length_size)
662                                 {
663                                 /* If this is index_b, write a length byte. */
664                                 b = constant_time_select_8(
665                                         is_block_b, length_bytes[j-(md_block_size-md_length_size)], b);
666                                 }
667                         block[j] = b;
668                         }
669
670                 md_transform(md_state.c, block);
671                 md_final_raw(md_state.c, block);
672                 /* If this is index_b, copy the hash value to |mac_out|. */
673                 for (j = 0; j < md_size; j++)
674                         mac_out[j] |= block[j]&is_block_b;
675                 }
676
677         EVP_MD_CTX_init(&md_ctx);
678         EVP_DigestInit_ex(&md_ctx, digest, NULL /* engine */);
679         if (is_sslv3)
680                 {
681                 /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */
682                 memset(hmac_pad, 0x5c, sslv3_pad_length);
683
684                 EVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length);
685                 EVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length);
686                 EVP_DigestUpdate(&md_ctx, mac_out, md_size);
687                 }
688         else
689                 {
690                 /* Complete the HMAC in the standard manner. */
691                 for (i = 0; i < md_block_size; i++)
692                         hmac_pad[i] ^= 0x6a;
693
694                 EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size);
695                 EVP_DigestUpdate(&md_ctx, mac_out, md_size);
696                 }
697         EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u);
698         if (md_out_size)
699                 *md_out_size = md_out_size_u;
700         EVP_MD_CTX_cleanup(&md_ctx);
701         }
702
703 #ifdef OPENSSL_FIPS
704
705 /* Due to the need to use EVP in FIPS mode we can't reimplement digests but
706  * we can ensure the number of blocks processed is equal for all cases
707  * by digesting additional data.
708  */
709
710 void tls_fips_digest_extra(
711         const EVP_CIPHER_CTX *cipher_ctx, const EVP_MD *hash, HMAC_CTX *hctx,
712         const unsigned char *data, size_t data_len, size_t orig_len)
713         {
714         size_t block_size, digest_pad, blocks_data, blocks_orig;
715         if (EVP_CIPHER_CTX_mode(cipher_ctx) != EVP_CIPH_CBC_MODE)
716                 return;
717         block_size = EVP_MD_block_size(hash);
718         /* We are in FIPS mode if we get this far so we know we have only SHA*
719          * digests and TLS to deal with.
720          * Minimum digest padding length is 17 for SHA384/SHA512 and 9
721          * otherwise.
722          * Additional header is 13 bytes. To get the number of digest blocks
723          * processed round up the amount of data plus padding to the nearest
724          * block length. Block length is 128 for SHA384/SHA512 and 64 otherwise.
725          * So we have:
726          * blocks = (payload_len + digest_pad + 13 + block_size - 1)/block_size
727          * equivalently:
728          * blocks = (payload_len + digest_pad + 12)/block_size + 1
729          * HMAC adds a constant overhead.
730          * We're ultimately only interested in differences so this becomes
731          * blocks = (payload_len + 29)/128
732          * for SHA384/SHA512 and
733          * blocks = (payload_len + 21)/64
734          * otherwise.
735          */
736         digest_pad = block_size == 64 ? 21 : 29;
737         blocks_orig = (orig_len + digest_pad)/block_size;
738         blocks_data = (data_len + digest_pad)/block_size;
739         /* MAC enough blocks to make up the difference between the original
740          * and actual lengths plus one extra block to ensure this is never a
741          * no op. The "data" pointer should always have enough space to
742          * perform this operation as it is large enough for a maximum
743          * length TLS buffer. 
744          */
745         HMAC_Update(hctx, data,
746                                 (blocks_orig - blocks_data + 1) * block_size);
747         }
748 #endif