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