Constant-time utilities
[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 (int)((good & 1) | (~good & -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 (int)((good & 1) | (~good & -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_CTX *ctx)
351         {
352         switch (ctx->digest->type)
353                 {
354                 case NID_md5:
355                 case NID_sha1:
356 #ifndef OPENSSL_NO_SHA256
357                 case NID_sha224:
358                 case NID_sha256:
359 #endif
360 #ifndef OPENSSL_NO_SHA512
361                 case NID_sha384:
362                 case NID_sha512:
363 #endif
364                         return 1;
365                 default:
366                         return 0;
367                 }
368         }
369
370 /* ssl3_cbc_digest_record computes the MAC of a decrypted, padded SSLv3/TLS
371  * record.
372  *
373  *   ctx: the EVP_MD_CTX from which we take the hash function.
374  *     ssl3_cbc_record_digest_supported must return true for this EVP_MD_CTX.
375  *   md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
376  *   md_out_size: if non-NULL, the number of output bytes is written here.
377  *   header: the 13-byte, TLS record header.
378  *   data: the record data itself, less any preceeding explicit IV.
379  *   data_plus_mac_size: the secret, reported length of the data and MAC
380  *     once the padding has been removed.
381  *   data_plus_mac_plus_padding_size: the public length of the whole
382  *     record, including padding.
383  *   is_sslv3: non-zero if we are to use SSLv3. Otherwise, TLS.
384  *
385  * On entry: by virtue of having been through one of the remove_padding
386  * functions, above, we know that data_plus_mac_size is large enough to contain
387  * a padding byte and MAC. (If the padding was invalid, it might contain the
388  * padding too. ) */
389 void ssl3_cbc_digest_record(
390         const EVP_MD_CTX *ctx,
391         unsigned char* md_out,
392         size_t* md_out_size,
393         const unsigned char header[13],
394         const unsigned char *data,
395         size_t data_plus_mac_size,
396         size_t data_plus_mac_plus_padding_size,
397         const unsigned char *mac_secret,
398         unsigned mac_secret_length,
399         char is_sslv3)
400         {
401         union { double align;
402                 unsigned char c[sizeof(LARGEST_DIGEST_CTX)]; } md_state;
403         void (*md_final_raw)(void *ctx, unsigned char *md_out);
404         void (*md_transform)(void *ctx, const unsigned char *block);
405         unsigned md_size, md_block_size = 64;
406         unsigned sslv3_pad_length = 40, header_length, variance_blocks,
407                  len, max_mac_bytes, num_blocks,
408                  num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
409         unsigned int bits;      /* at most 18 bits */
410         unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
411         /* hmac_pad is the masked HMAC key. */
412         unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
413         unsigned char first_block[MAX_HASH_BLOCK_SIZE];
414         unsigned char mac_out[EVP_MAX_MD_SIZE];
415         unsigned i, j, md_out_size_u;
416         EVP_MD_CTX md_ctx;
417         /* mdLengthSize is the number of bytes in the length field that terminates
418         * the hash. */
419         unsigned md_length_size = 8;
420         char length_is_big_endian = 1;
421
422         /* This is a, hopefully redundant, check that allows us to forget about
423          * many possible overflows later in this function. */
424         OPENSSL_assert(data_plus_mac_plus_padding_size < 1024*1024);
425
426         switch (ctx->digest->type)
427                 {
428                 case NID_md5:
429                         MD5_Init((MD5_CTX*)md_state.c);
430                         md_final_raw = tls1_md5_final_raw;
431                         md_transform = (void(*)(void *ctx, const unsigned char *block)) MD5_Transform;
432                         md_size = 16;
433                         sslv3_pad_length = 48;
434                         length_is_big_endian = 0;
435                         break;
436                 case NID_sha1:
437                         SHA1_Init((SHA_CTX*)md_state.c);
438                         md_final_raw = tls1_sha1_final_raw;
439                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA1_Transform;
440                         md_size = 20;
441                         break;
442 #ifndef OPENSSL_NO_SHA256
443                 case NID_sha224:
444                         SHA224_Init((SHA256_CTX*)md_state.c);
445                         md_final_raw = tls1_sha256_final_raw;
446                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform;
447                         md_size = 224/8;
448                         break;
449                 case NID_sha256:
450                         SHA256_Init((SHA256_CTX*)md_state.c);
451                         md_final_raw = tls1_sha256_final_raw;
452                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform;
453                         md_size = 32;
454                         break;
455 #endif
456 #ifndef OPENSSL_NO_SHA512
457                 case NID_sha384:
458                         SHA384_Init((SHA512_CTX*)md_state.c);
459                         md_final_raw = tls1_sha512_final_raw;
460                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform;
461                         md_size = 384/8;
462                         md_block_size = 128;
463                         md_length_size = 16;
464                         break;
465                 case NID_sha512:
466                         SHA512_Init((SHA512_CTX*)md_state.c);
467                         md_final_raw = tls1_sha512_final_raw;
468                         md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform;
469                         md_size = 64;
470                         md_block_size = 128;
471                         md_length_size = 16;
472                         break;
473 #endif
474                 default:
475                         /* ssl3_cbc_record_digest_supported should have been
476                          * called first to check that the hash function is
477                          * supported. */
478                         OPENSSL_assert(0);
479                         if (md_out_size)
480                                 *md_out_size = -1;
481                         return;
482                 }
483
484         OPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES);
485         OPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE);
486         OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
487
488         header_length = 13;
489         if (is_sslv3)
490                 {
491                 header_length =
492                         mac_secret_length +
493                         sslv3_pad_length +
494                         8 /* sequence number */ +
495                         1 /* record type */ +
496                         2 /* record length */;
497                 }
498
499         /* variance_blocks is the number of blocks of the hash that we have to
500          * calculate in constant time because they could be altered by the
501          * padding value.
502          *
503          * In SSLv3, the padding must be minimal so the end of the plaintext
504          * varies by, at most, 15+20 = 35 bytes. (We conservatively assume that
505          * the MAC size varies from 0..20 bytes.) In case the 9 bytes of hash
506          * termination (0x80 + 64-bit length) don't fit in the final block, we
507          * say that the final two blocks can vary based on the padding.
508          *
509          * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
510          * required to be minimal. Therefore we say that the final six blocks
511          * can vary based on the padding.
512          *
513          * Later in the function, if the message is short and there obviously
514          * cannot be this many blocks then variance_blocks can be reduced. */
515         variance_blocks = is_sslv3 ? 2 : 6;
516         /* From now on we're dealing with the MAC, which conceptually has 13
517          * bytes of `header' before the start of the data (TLS) or 71/75 bytes
518          * (SSLv3) */
519         len = data_plus_mac_plus_padding_size + header_length;
520         /* max_mac_bytes contains the maximum bytes of bytes in the MAC, including
521         * |header|, assuming that there's no padding. */
522         max_mac_bytes = len - md_size - 1;
523         /* num_blocks is the maximum number of hash blocks. */
524         num_blocks = (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size;
525         /* In order to calculate the MAC in constant time we have to handle
526          * the final blocks specially because the padding value could cause the
527          * end to appear somewhere in the final |variance_blocks| blocks and we
528          * can't leak where. However, |num_starting_blocks| worth of data can
529          * be hashed right away because no padding value can affect whether
530          * they are plaintext. */
531         num_starting_blocks = 0;
532         /* k is the starting byte offset into the conceptual header||data where
533          * we start processing. */
534         k = 0;
535         /* mac_end_offset is the index just past the end of the data to be
536          * MACed. */
537         mac_end_offset = data_plus_mac_size + header_length - md_size;
538         /* c is the index of the 0x80 byte in the final hash block that
539          * contains application data. */
540         c = mac_end_offset % md_block_size;
541         /* index_a is the hash block number that contains the 0x80 terminating
542          * value. */
543         index_a = mac_end_offset / md_block_size;
544         /* index_b is the hash block number that contains the 64-bit hash
545          * length, in bits. */
546         index_b = (mac_end_offset + md_length_size) / md_block_size;
547         /* bits is the hash-length in bits. It includes the additional hash
548          * block for the masked HMAC key, or whole of |header| in the case of
549          * SSLv3. */
550
551         /* For SSLv3, if we're going to have any starting blocks then we need
552          * at least two because the header is larger than a single block. */
553         if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0))
554                 {
555                 num_starting_blocks = num_blocks - variance_blocks;
556                 k = md_block_size*num_starting_blocks;
557                 }
558
559         bits = 8*mac_end_offset;
560         if (!is_sslv3)
561                 {
562                 /* Compute the initial HMAC block. For SSLv3, the padding and
563                  * secret bytes are included in |header| because they take more
564                  * than a single block. */
565                 bits += 8*md_block_size;
566                 memset(hmac_pad, 0, md_block_size);
567                 OPENSSL_assert(mac_secret_length <= sizeof(hmac_pad));
568                 memcpy(hmac_pad, mac_secret, mac_secret_length);
569                 for (i = 0; i < md_block_size; i++)
570                         hmac_pad[i] ^= 0x36;
571
572                 md_transform(md_state.c, hmac_pad);
573                 }
574
575         if (length_is_big_endian)
576                 {
577                 memset(length_bytes,0,md_length_size-4);
578                 length_bytes[md_length_size-4] = (unsigned char)(bits>>24);
579                 length_bytes[md_length_size-3] = (unsigned char)(bits>>16);
580                 length_bytes[md_length_size-2] = (unsigned char)(bits>>8);
581                 length_bytes[md_length_size-1] = (unsigned char)bits;
582                 }
583         else
584                 {
585                 memset(length_bytes,0,md_length_size);
586                 length_bytes[md_length_size-5] = (unsigned char)(bits>>24);
587                 length_bytes[md_length_size-6] = (unsigned char)(bits>>16);
588                 length_bytes[md_length_size-7] = (unsigned char)(bits>>8);
589                 length_bytes[md_length_size-8] = (unsigned char)bits;
590                 }
591
592         if (k > 0)
593                 {
594                 if (is_sslv3)
595                         {
596                         /* The SSLv3 header is larger than a single block.
597                          * overhang is the number of bytes beyond a single
598                          * block that the header consumes: either 7 bytes
599                          * (SHA1) or 11 bytes (MD5). */
600                         unsigned overhang = header_length-md_block_size;
601                         md_transform(md_state.c, header);
602                         memcpy(first_block, header + md_block_size, overhang);
603                         memcpy(first_block + overhang, data, md_block_size-overhang);
604                         md_transform(md_state.c, first_block);
605                         for (i = 1; i < k/md_block_size - 1; i++)
606                                 md_transform(md_state.c, data + md_block_size*i - overhang);
607                         }
608                 else
609                         {
610                         /* k is a multiple of md_block_size. */
611                         memcpy(first_block, header, 13);
612                         memcpy(first_block+13, data, md_block_size-13);
613                         md_transform(md_state.c, first_block);
614                         for (i = 1; i < k/md_block_size; i++)
615                                 md_transform(md_state.c, data + md_block_size*i - 13);
616                         }
617                 }
618
619         memset(mac_out, 0, sizeof(mac_out));
620
621         /* We now process the final hash blocks. For each block, we construct
622          * it in constant time. If the |i==index_a| then we'll include the 0x80
623          * bytes and zero pad etc. For each block we selectively copy it, in
624          * constant time, to |mac_out|. */
625         for (i = num_starting_blocks; i <= num_starting_blocks+variance_blocks; i++)
626                 {
627                 unsigned char block[MAX_HASH_BLOCK_SIZE];
628                 unsigned char is_block_a = constant_time_eq_8(i, index_a);
629                 unsigned char is_block_b = constant_time_eq_8(i, index_b);
630                 for (j = 0; j < md_block_size; j++)
631                         {
632                         unsigned char b = 0, is_past_c, is_past_cp1;
633                         if (k < header_length)
634                                 b = header[k];
635                         else if (k < data_plus_mac_plus_padding_size + header_length)
636                                 b = data[k-header_length];
637                         k++;
638
639                         is_past_c = is_block_a & constant_time_ge_8(j, c);
640                         is_past_cp1 = is_block_a & constant_time_ge_8(j, c+1);
641                         /* If this is the block containing the end of the
642                          * application data, and we are at the offset for the
643                          * 0x80 value, then overwrite b with 0x80. */
644                         b = (b&~is_past_c) | (0x80&is_past_c);
645                         /* If this the the block containing the end of the
646                          * application data and we're past the 0x80 value then
647                          * just write zero. */
648                         b = b&~is_past_cp1;
649                         /* If this is index_b (the final block), but not
650                          * index_a (the end of the data), then the 64-bit
651                          * length didn't fit into index_a and we're having to
652                          * add an extra block of zeros. */
653                         b &= ~is_block_b | is_block_a;
654
655                         /* The final bytes of one of the blocks contains the
656                          * length. */
657                         if (j >= md_block_size - md_length_size)
658                                 {
659                                 /* If this is index_b, write a length byte. */
660                                 b = (b&~is_block_b) | (is_block_b&length_bytes[j-(md_block_size-md_length_size)]);
661                                 }
662                         block[j] = b;
663                         }
664
665                 md_transform(md_state.c, block);
666                 md_final_raw(md_state.c, block);
667                 /* If this is index_b, copy the hash value to |mac_out|. */
668                 for (j = 0; j < md_size; j++)
669                         mac_out[j] |= block[j]&is_block_b;
670                 }
671
672         EVP_MD_CTX_init(&md_ctx);
673         EVP_DigestInit_ex(&md_ctx, ctx->digest, NULL /* engine */);
674         if (is_sslv3)
675                 {
676                 /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */
677                 memset(hmac_pad, 0x5c, sslv3_pad_length);
678
679                 EVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length);
680                 EVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length);
681                 EVP_DigestUpdate(&md_ctx, mac_out, md_size);
682                 }
683         else
684                 {
685                 /* Complete the HMAC in the standard manner. */
686                 for (i = 0; i < md_block_size; i++)
687                         hmac_pad[i] ^= 0x6a;
688
689                 EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size);
690                 EVP_DigestUpdate(&md_ctx, mac_out, md_size);
691                 }
692         EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u);
693         if (md_out_size)
694                 *md_out_size = md_out_size_u;
695         EVP_MD_CTX_cleanup(&md_ctx);
696         }