s3_cbc.c revision 296341
11541Srgrimes/* ssl/s3_cbc.c */
21541Srgrimes/* ====================================================================
31541Srgrimes * Copyright (c) 2012 The OpenSSL Project.  All rights reserved.
45455Sdg *
55455Sdg * Redistribution and use in source and binary forms, with or without
61541Srgrimes * modification, are permitted provided that the following conditions
71541Srgrimes * are met:
81541Srgrimes *
91541Srgrimes * 1. Redistributions of source code must retain the above copyright
101541Srgrimes *    notice, this list of conditions and the following disclaimer.
111541Srgrimes *
121541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
131541Srgrimes *    notice, this list of conditions and the following disclaimer in
141541Srgrimes *    the documentation and/or other materials provided with the
151541Srgrimes *    distribution.
161541Srgrimes *
171541Srgrimes * 3. All advertising materials mentioning features or use of this
181541Srgrimes *    software must display the following acknowledgment:
191541Srgrimes *    "This product includes software developed by the OpenSSL Project
201541Srgrimes *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
211541Srgrimes *
221541Srgrimes * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
231541Srgrimes *    endorse or promote products derived from this software without
241541Srgrimes *    prior written permission. For written permission, please contact
251541Srgrimes *    openssl-core@openssl.org.
261541Srgrimes *
271541Srgrimes * 5. Products derived from this software may not be called "OpenSSL"
281541Srgrimes *    nor may "OpenSSL" appear in their names without prior written
291541Srgrimes *    permission of the OpenSSL Project.
301541Srgrimes *
311541Srgrimes * 6. Redistributions of any form whatsoever must retain the following
321541Srgrimes *    acknowledgment:
331541Srgrimes *    "This product includes software developed by the OpenSSL Project
34116182Sobrien *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35116182Sobrien *
36116182Sobrien * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
3732929Seivind * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3832929Seivind * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
391541Srgrimes * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
401549Srgrimes * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
4141168Sbde * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
421541Srgrimes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
4360041Sphk * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
441541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
451541Srgrimes * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
4641124Sdg * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
471541Srgrimes * OF THE POSSIBILITY OF SUCH DAMAGE.
481541Srgrimes * ====================================================================
4968885Sdillon *
506621Sdg * This product includes cryptographic software written by Eric Young
5110541Sdyson * (eay@cryptsoft.com).  This product includes software written by Tim
5210541Sdyson * Hudson (tjh@cryptsoft.com).
5348545Smckusick *
541541Srgrimes */
5521002Sdyson
5621002Sdyson#include "../crypto/constant_time_locl.h"
5791690Seivind#include "ssl_locl.h"
5891690Seivind
5921002Sdyson#include <openssl/md5.h>
6021002Sdyson#include <openssl/sha.h>
61167214Swkoszek
6241124Sdg/*
63251897Sscottl * MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's
64251897Sscottl * length field. (SHA-384/512 have 128-bit length.)
65251897Sscottl */
66251897Sscottl#define MAX_HASH_BIT_COUNT_BYTES 16
67251897Sscottl
68141628Sphk/*
691541Srgrimes * MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
7048545Smckusick * Currently SHA-384/512 has a 128-byte block size and that's the largest
7191690Seivind * supported by TLS.)
7291690Seivind */
7348545Smckusick#define MAX_HASH_BLOCK_SIZE 128
74219699Sivoras
75112080Sjeff/*-
76112080Sjeff * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
77112080Sjeff * record in |rec| by updating |rec->length| in constant time.
78250906Sscottl *
79250906Sscottl * block_size: the block size of the cipher used to encrypt the record.
80250906Sscottl * returns:
81250906Sscottl *   0: (in non-constant time) if the record is publicly invalid.
8291690Seivind *   1: if the padding was valid
8312973Sbde *  -1: otherwise.
845455Sdg */
8591690Seivindint ssl3_cbc_remove_padding(const SSL *s,
8691690Seivind                            SSL3_RECORD *rec,
8791690Seivind                            unsigned block_size, unsigned mac_size)
8810541Sdyson{
891549Srgrimes    unsigned padding_length, good;
90251144Sscottl    const unsigned overhead = 1 /* padding length byte */  + mac_size;
91251144Sscottl
921541Srgrimes    /*
93251144Sscottl     * These lengths are all public so we can test them in non-constant time.
94251144Sscottl     */
95251144Sscottl    if (overhead > rec->length)
96251144Sscottl        return 0;
97251144Sscottl
98251144Sscottl    padding_length = rec->data[rec->length - 1];
99251144Sscottl    good = constant_time_ge(rec->length, padding_length + overhead);
100251144Sscottl    /* SSLv3 requires that the padding is minimal. */
101251144Sscottl    good &= constant_time_ge(block_size, padding_length + 1);
102251144Sscottl    padding_length = good & (padding_length + 1);
10321002Sdyson    rec->length -= padding_length;
104177493Sjeff    rec->type |= padding_length << 8; /* kludge: pass padding length */
10596572Sphk    return constant_time_select_int(good, 1, -1);
106112080Sjeff}
107112080Sjeff
10810541Sdyson/*-
1091541Srgrimes * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1101541Srgrimes * record in |rec| in constant time and returns 1 if the padding is valid and
111177493Sjeff * -1 otherwise. It also removes any explicit IV from the start of the record
112251897Sscottl * without leaking any timing about whether there was enough space after the
113251897Sscottl * padding was removed.
11421002Sdyson *
1155455Sdg * block_size: the block size of the cipher used to encrypt the record.
11621002Sdyson * returns:
11721002Sdyson *   0: (in non-constant time) if the record is publicly invalid.
11821002Sdyson *   1: if the padding was valid
11951797Sphk *  -1: otherwise.
120112080Sjeff */
121112080Sjeffint tls1_cbc_remove_padding(const SSL *s,
122112080Sjeff                            SSL3_RECORD *rec,
123112080Sjeff                            unsigned block_size, unsigned mac_size)
124112080Sjeff{
12521002Sdyson    unsigned padding_length, good, to_check, i;
12621002Sdyson    const unsigned overhead = 1 /* padding length byte */  + mac_size;
1275455Sdg    /* Check if version requires explicit IV */
1285455Sdg    if (s->version >= TLS1_1_VERSION || s->version == DTLS1_BAD_VER) {
129251897Sscottl        /*
13021002Sdyson         * These lengths are all public so we can test them in non-constant
13112767Sdyson         * time.
1325455Sdg         */
1335455Sdg        if (overhead + block_size > rec->length)
1345455Sdg            return 0;
1355455Sdg        /* We can now safely skip explicit IV */
1365455Sdg        rec->data += block_size;
1371541Srgrimes        rec->input += block_size;
13821002Sdyson        rec->length -= block_size;
1395455Sdg    } else if (overhead > rec->length)
14021002Sdyson        return 0;
14121002Sdyson
14221002Sdyson    padding_length = rec->data[rec->length - 1];
14321002Sdyson
144177493Sjeff    /*
14548225Smckusick     * NB: if compression is in operation the first packet may not be of even
14699737Sdillon     * length so the padding bug check cannot be performed. This bug
14799737Sdillon     * workaround has been around since SSLeay so hopefully it is either
14899737Sdillon     * fixed now or no buggy implementation supports compression [steve]
14999737Sdillon     */
150136767Sphk    if ((s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) && !s->expand) {
151112080Sjeff        /* First packet is even in size, so check */
15221002Sdyson        if ((CRYPTO_memcmp(s->s3->read_sequence, "\0\0\0\0\0\0\0\0", 8) == 0) &&
15321002Sdyson            !(padding_length & 1)) {
15421002Sdyson            s->s3->flags |= TLS1_FLAGS_TLS_PADDING_BUG;
15548677Smckusick        }
156151621Sups        if ((s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) && padding_length > 0) {
157151621Sups            padding_length--;
15821002Sdyson        }
159151621Sups    }
160151621Sups
161151621Sups    if (EVP_CIPHER_flags(s->enc_read_ctx->cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
162151621Sups        /* padding is already verified */
163112080Sjeff        rec->length -= padding_length + 1;
164151621Sups        return 1;
165151621Sups    }
16621002Sdyson
167177493Sjeff    good = constant_time_ge(rec->length, overhead + padding_length);
16821002Sdyson    /*
1695839Sdg     * The padding consists of a length byte at the end of the record and
17010541Sdyson     * then that many bytes of padding, all with the same value as the length
17121002Sdyson     * byte. Thus, with the length byte included, there are i+1 bytes of
17221002Sdyson     * padding. We can't check just |padding_length+1| bytes because that
17321002Sdyson     * leaks decrypted information. Therefore we always have to check the
174111886Sjeff     * maximum amount of padding possible. (Again, the length of the record
175111886Sjeff     * is public information so we can use it.)
176111886Sjeff     */
177111886Sjeff    to_check = 255;             /* maximum amount of padding. */
17821002Sdyson    if (to_check > rec->length - 1)
17942453Seivind        to_check = rec->length - 1;
180111886Sjeff
181250906Sscottl    for (i = 0; i < to_check; i++) {
18242453Seivind        unsigned char mask = constant_time_ge_8(padding_length, i);
18342408Seivind        unsigned char b = rec->data[rec->length - 1 - i];
18442453Seivind        /*
185111886Sjeff         * The final |padding_length+1| bytes should all have the value
186112080Sjeff         * |padding_length|. Therefore the XOR should be zero.
187111886Sjeff         */
188111886Sjeff        good &= ~(mask & (padding_length ^ b));
189250906Sscottl    }
190250906Sscottl
191250906Sscottl    /*
192250906Sscottl     * If any of the final |padding_length+1| bytes had the wrong value, one
193250906Sscottl     * or more of the lower eight bits of |good| will be cleared.
194250906Sscottl     */
195250906Sscottl    good = constant_time_eq(0xff, good & 0xff);
196111886Sjeff    padding_length = good & (padding_length + 1);
197111886Sjeff    rec->length -= padding_length;
198111886Sjeff    rec->type |= padding_length << 8; /* kludge: pass padding length */
19921002Sdyson
20021002Sdyson    return constant_time_select_int(good, 1, -1);
201111886Sjeff}
202111886Sjeff
203111886Sjeff/*-
20421002Sdyson * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
205111886Sjeff * constant time (independent of the concrete value of rec->length, which may
206111886Sjeff * vary within a 256-byte window).
207111886Sjeff *
208111886Sjeff * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
20921002Sdyson * this function.
210112080Sjeff *
211111886Sjeff * On entry:
212111886Sjeff *   rec->orig_len >= md_size
213111886Sjeff *   md_size <= EVP_MAX_MD_SIZE
214111886Sjeff *
215112080Sjeff * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
216111886Sjeff * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
21721002Sdyson * a single or pair of cache-lines, then the variable memory accesses don't
218111886Sjeff * actually affect the timing. CPUs with smaller cache-lines [if any] are
219111886Sjeff * not multi-core and are not considered vulnerable to cache-timing attacks.
220111886Sjeff */
221111886Sjeff#define CBC_MAC_ROTATE_IN_PLACE
222112080Sjeff
223111886Sjeffvoid ssl3_cbc_copy_mac(unsigned char *out,
224112080Sjeff                       const SSL3_RECORD *rec,
225112080Sjeff                       unsigned md_size, unsigned orig_len)
226112080Sjeff{
22721002Sdyson#if defined(CBC_MAC_ROTATE_IN_PLACE)
228251897Sscottl    unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
22934694Sdyson    unsigned char *rotated_mac;
23010541Sdyson#else
23158345Sphk    unsigned char rotated_mac[EVP_MAX_MD_SIZE];
23258345Sphk#endif
23310541Sdyson
2348876Srgrimes    /*
2351541Srgrimes     * mac_end is the index of |rec->data| just after the end of the MAC.
2365455Sdg     */
2375455Sdg    unsigned mac_end = rec->length;
238112080Sjeff    unsigned mac_start = mac_end - md_size;
2395455Sdg    /*
2405455Sdg     * scan_start contains the number of bytes that we can ignore because the
24170374Sdillon     * MAC's position can only vary by 255 bytes.
24236275Sdyson     */
24370374Sdillon    unsigned scan_start = 0;
24458934Sphk    unsigned i, j;
24558934Sphk    unsigned div_spoiler;
24658345Sphk    unsigned rotate_offset;
24748333Speter
248121205Sphk    OPENSSL_assert(orig_len >= md_size);
249136927Sphk    OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
250170174Sjeff
2515455Sdg#if defined(CBC_MAC_ROTATE_IN_PLACE)
25234611Sdyson    rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
2535455Sdg#endif
254112080Sjeff
2555455Sdg    /* This information is public so it's safe to branch based on it. */
256112080Sjeff    if (orig_len > md_size + 255 + 1)
257112080Sjeff        scan_start = orig_len - (md_size + 255 + 1);
258112080Sjeff    /*
259112080Sjeff     * div_spoiler contains a multiple of md_size that is used to cause the
260112080Sjeff     * modulo operation to be constant time. Without this, the time varies
261112080Sjeff     * based on the amount of padding when running on Intel chips at least.
262112080Sjeff     * The aim of right-shifting md_size is so that the compiler doesn't
263112080Sjeff     * figure out that it can remove div_spoiler as that would require it to
264112080Sjeff     * prove that md_size is always even, which I hope is beyond it.
265112080Sjeff     */
266112080Sjeff    div_spoiler = md_size >> 1;
267112080Sjeff    div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
268112080Sjeff    rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
269112080Sjeff
270112080Sjeff    memset(rotated_mac, 0, md_size);
271112080Sjeff    for (i = scan_start, j = 0; i < orig_len; i++) {
272251897Sscottl        unsigned char mac_started = constant_time_ge_8(i, mac_start);
273112080Sjeff        unsigned char mac_ended = constant_time_ge_8(i, mac_end);
274112838Sjeff        unsigned char b = rec->data[i];
275112838Sjeff        rotated_mac[j++] |= b & mac_started & ~mac_ended;
276112838Sjeff        j &= constant_time_lt(j, md_size);
277112838Sjeff    }
278112080Sjeff
279251897Sscottl    /* Now rotate the MAC */
280112838Sjeff#if defined(CBC_MAC_ROTATE_IN_PLACE)
281112838Sjeff    j = 0;
282112838Sjeff    for (i = 0; i < md_size; i++) {
283112838Sjeff        /* in case cache-line is 32 bytes, touch second line */
284112838Sjeff        ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
285112080Sjeff        out[j++] = rotated_mac[rotate_offset++];
286112080Sjeff        rotate_offset &= constant_time_lt(rotate_offset, md_size);
287112080Sjeff    }
288112080Sjeff#else
289112080Sjeff    memset(out, 0, md_size);
29058345Sphk    rotate_offset = md_size - rotate_offset;
29113490Sdyson    rotate_offset &= constant_time_lt(rotate_offset, md_size);
292112080Sjeff    for (i = 0; i < md_size; i++) {
2935455Sdg        for (j = 0; j < md_size; j++)
294112080Sjeff            out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
295112080Sjeff        rotate_offset++;
296112080Sjeff        rotate_offset &= constant_time_lt(rotate_offset, md_size);
297112080Sjeff    }
298112080Sjeff#endif
299112080Sjeff}
300112080Sjeff
301121205Sphk/*
302136927Sphk * u32toLE serialises an unsigned, 32-bit number (n) as four bytes at (p) in
303170174Sjeff * little-endian order. The value of p is advanced by four.
3045455Sdg */
305112080Sjeff#define u32toLE(n, p) \
30621002Sdyson        (*((p)++)=(unsigned char)(n), \
30759762Sphk         *((p)++)=(unsigned char)(n>>8), \
30821002Sdyson         *((p)++)=(unsigned char)(n>>16), \
30921002Sdyson         *((p)++)=(unsigned char)(n>>24))
3101541Srgrimes
3111541Srgrimes/*
3121541Srgrimes * These functions serialize the state of a hash and thus perform the
3131541Srgrimes * standard "final" operation without adding the padding and length that such
3141541Srgrimes * a function typically does.
3151541Srgrimes */
3161541Srgrimesstatic void tls1_md5_final_raw(void *ctx, unsigned char *md_out)
31710541Sdyson{
318251897Sscottl    MD5_CTX *md5 = ctx;
319251897Sscottl    u32toLE(md5->A, md_out);
3201541Srgrimes    u32toLE(md5->B, md_out);
321177493Sjeff    u32toLE(md5->C, md_out);
32210541Sdyson    u32toLE(md5->D, md_out);
3231541Srgrimes}
324195122Salc
325195122Salcstatic void tls1_sha1_final_raw(void *ctx, unsigned char *md_out)
326195122Salc{
3271541Srgrimes    SHA_CTX *sha1 = ctx;
32842408Seivind    l2n(sha1->h0, md_out);
329122537Smckusick    l2n(sha1->h1, md_out);
330122537Smckusick    l2n(sha1->h2, md_out);
33142453Seivind    l2n(sha1->h3, md_out);
33212767Sdyson    l2n(sha1->h4, md_out);
33312767Sdyson}
33412767Sdyson
33512767Sdyson#define LARGEST_DIGEST_CTX SHA_CTX
3361541Srgrimes
33712767Sdyson#ifndef OPENSSL_NO_SHA256
33810541Sdysonstatic void tls1_sha256_final_raw(void *ctx, unsigned char *md_out)
33921002Sdyson{
34021002Sdyson    SHA256_CTX *sha256 = ctx;
34158345Sphk    unsigned i;
34221002Sdyson
343251897Sscottl    for (i = 0; i < 8; i++) {
34421002Sdyson        l2n(sha256->h[i], md_out);
34521002Sdyson    }
34658345Sphk}
34758345Sphk
34821002Sdyson# undef  LARGEST_DIGEST_CTX
34910541Sdyson# define LARGEST_DIGEST_CTX SHA256_CTX
35016086Sdyson#endif
35116086Sdyson
35210541Sdyson#ifndef OPENSSL_NO_SHA512
35310541Sdysonstatic void tls1_sha512_final_raw(void *ctx, unsigned char *md_out)
35442957Sdillon{
35510541Sdyson    SHA512_CTX *sha512 = ctx;
35610541Sdyson    unsigned i;
35710541Sdyson
35885272Sdillon    for (i = 0; i < 8; i++) {
35985272Sdillon        l2n8(sha512->h[i], md_out);
36085272Sdillon    }
36185272Sdillon}
36285272Sdillon
36385272Sdillon# undef  LARGEST_DIGEST_CTX
36458345Sphk# define LARGEST_DIGEST_CTX SHA512_CTX
365251897Sscottl#endif
366251897Sscottl
367251897Sscottl/*
368251897Sscottl * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
369251897Sscottl * which ssl3_cbc_digest_record supports.
370251897Sscottl */
371251897Sscottlchar ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
37258345Sphk{
3735455Sdg#ifdef OPENSSL_FIPS
3745455Sdg    if (FIPS_mode())
3755455Sdg        return 0;
37634611Sdyson#endif
37742453Seivind    switch (EVP_MD_CTX_type(ctx)) {
3785455Sdg    case NID_md5:
3791541Srgrimes    case NID_sha1:
38012404Sdyson#ifndef OPENSSL_NO_SHA256
3811541Srgrimes    case NID_sha224:
3825455Sdg    case NID_sha256:
3835455Sdg#endif
3845455Sdg#ifndef OPENSSL_NO_SHA512
3855455Sdg    case NID_sha384:
3861541Srgrimes    case NID_sha512:
387177493Sjeff#endif
38810541Sdyson        return 1;
3895455Sdg    default:
39012767Sdyson        return 0;
39185272Sdillon    }
39210541Sdyson}
39385272Sdillon
39410978Sdyson/*-
395251897Sscottl * ssl3_cbc_digest_record computes the MAC of a decrypted, padded SSLv3/TLS
396251897Sscottl * record.
39712767Sdyson *
398111886Sjeff *   ctx: the EVP_MD_CTX from which we take the hash function.
399111886Sjeff *     ssl3_cbc_record_digest_supported must return true for this EVP_MD_CTX.
400111886Sjeff *   md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
40134611Sdyson *   md_out_size: if non-NULL, the number of output bytes is written here.
40271230Sdillon *   header: the 13-byte, TLS record header.
40385272Sdillon *   data: the record data itself, less any preceeding explicit IV.
40485272Sdillon *   data_plus_mac_size: the secret, reported length of the data and MAC
40585272Sdillon *     once the padding has been removed.
40685272Sdillon *   data_plus_mac_plus_padding_size: the public length of the whole
40785272Sdillon *     record, including padding.
40871230Sdillon *   is_sslv3: non-zero if we are to use SSLv3. Otherwise, TLS.
409177493Sjeff *
410119521Sjeff * On entry: by virtue of having been through one of the remove_padding
411119521Sjeff * functions, above, we know that data_plus_mac_size is large enough to contain
412119521Sjeff * a padding byte and MAC. (If the padding was invalid, it might contain the
413177493Sjeff * padding too. )
41413490Sdyson */
4155455Sdgvoid ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
4165455Sdg                            unsigned char *md_out,
417177493Sjeff                            size_t *md_out_size,
41810541Sdyson                            const unsigned char header[13],
41985272Sdillon                            const unsigned char *data,
42085272Sdillon                            size_t data_plus_mac_size,
42185272Sdillon                            size_t data_plus_mac_plus_padding_size,
42285272Sdillon                            const unsigned char *mac_secret,
42385272Sdillon                            unsigned mac_secret_length, char is_sslv3)
424195122Salc{
425195122Salc    union {
426137010Sphk        double align;
427195122Salc        unsigned char c[sizeof(LARGEST_DIGEST_CTX)];
428195122Salc    } md_state;
429195122Salc    void (*md_final_raw) (void *ctx, unsigned char *md_out);
430195122Salc    void (*md_transform) (void *ctx, const unsigned char *block);
431195122Salc    unsigned md_size, md_block_size = 64;
432121269Salc    unsigned sslv3_pad_length = 40, header_length, variance_blocks,
433121269Salc        len, max_mac_bytes, num_blocks,
434195122Salc        num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
435195122Salc    unsigned int bits;          /* at most 18 bits */
43610541Sdyson    unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
437195122Salc    /* hmac_pad is the masked HMAC key. */
438195122Salc    unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
43971230Sdillon    unsigned char first_block[MAX_HASH_BLOCK_SIZE];
440137010Sphk    unsigned char mac_out[EVP_MAX_MD_SIZE];
441195122Salc    unsigned i, j, md_out_size_u;
44234611Sdyson    EVP_MD_CTX md_ctx;
44310541Sdyson    /*
44410541Sdyson     * mdLengthSize is the number of bytes in the length field that
44510541Sdyson     * terminates * the hash.
44685272Sdillon     */
44785272Sdillon    unsigned md_length_size = 8;
44885272Sdillon    char length_is_big_endian = 1;
44921002Sdyson
45021002Sdyson    /*
45185272Sdillon     * This is a, hopefully redundant, check that allows us to forget about
45285272Sdillon     * many possible overflows later in this function.
45385272Sdillon     */
45485272Sdillon    OPENSSL_assert(data_plus_mac_plus_padding_size < 1024 * 1024);
45585272Sdillon
45685272Sdillon    switch (EVP_MD_CTX_type(ctx)) {
45785272Sdillon    case NID_md5:
45885272Sdillon        MD5_Init((MD5_CTX *)md_state.c);
45958345Sphk        md_final_raw = tls1_md5_final_raw;
46058345Sphk        md_transform =
46112767Sdyson            (void (*)(void *ctx, const unsigned char *block))MD5_Transform;
46210541Sdyson        md_size = 16;
46310541Sdyson        sslv3_pad_length = 48;
46410541Sdyson        length_is_big_endian = 0;
46510541Sdyson        break;
46610541Sdyson    case NID_sha1:
4671541Srgrimes        SHA1_Init((SHA_CTX *)md_state.c);
46848333Speter        md_final_raw = tls1_sha1_final_raw;
46948333Speter        md_transform =
47048333Speter            (void (*)(void *ctx, const unsigned char *block))SHA1_Transform;
47148333Speter        md_size = 20;
47248333Speter        break;
47312404Sdyson#ifndef OPENSSL_NO_SHA256
47412404Sdyson    case NID_sha224:
475137010Sphk        SHA224_Init((SHA256_CTX *)md_state.c);
4765455Sdg        md_final_raw = tls1_sha256_final_raw;
47710541Sdyson        md_transform =
47810541Sdyson            (void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
47938799Sdfr        md_size = 224 / 8;
48038517Sdfr        break;
48110541Sdyson    case NID_sha256:
48212413Sdyson        SHA256_Init((SHA256_CTX *)md_state.c);
48310541Sdyson        md_final_raw = tls1_sha256_final_raw;
48410541Sdyson        md_transform =
48510541Sdyson            (void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
486193643Salc        md_size = 32;
48718737Sdyson        break;
4881541Srgrimes#endif
489137010Sphk#ifndef OPENSSL_NO_SHA512
49085511Sdillon    case NID_sha384:
49185511Sdillon        SHA384_Init((SHA512_CTX *)md_state.c);
49285511Sdillon        md_final_raw = tls1_sha512_final_raw;
49385511Sdillon        md_transform =
49485511Sdillon            (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
49585511Sdillon        md_size = 384 / 8;
49685511Sdillon        md_block_size = 128;
49785511Sdillon        md_length_size = 16;
49885511Sdillon        break;
49985511Sdillon    case NID_sha512:
50085511Sdillon        SHA512_Init((SHA512_CTX *)md_state.c);
5011541Srgrimes        md_final_raw = tls1_sha512_final_raw;
50218737Sdyson        md_transform =
50385272Sdillon            (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
50485272Sdillon        md_size = 64;
50585272Sdillon        md_block_size = 128;
50685272Sdillon        md_length_size = 16;
507137010Sphk        break;
50885272Sdillon#endif
509121269Salc    default:
510193643Salc        /*
51118737Sdyson         * ssl3_cbc_record_digest_supported should have been called first to
51218737Sdyson         * check that the hash function is supported.
513137010Sphk         */
51420054Sdyson        OPENSSL_assert(0);
51537559Sbde        if (md_out_size)
51637559Sbde            *md_out_size = -1;
51720054Sdyson        return;
51818737Sdyson    }
519251897Sscottl
520251897Sscottl    OPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES);
521251897Sscottl    OPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE);
522251897Sscottl    OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
5235455Sdg
5241541Srgrimes    header_length = 13;
5251541Srgrimes    if (is_sslv3) {
5261541Srgrimes        header_length = mac_secret_length + sslv3_pad_length + 8 /* sequence
5271541Srgrimes                                                                  * number */  +
5281541Srgrimes            1 /* record type */  +
5291541Srgrimes            2 /* record length */ ;
5301541Srgrimes    }
5311541Srgrimes
532141628Sphk    /*
5331541Srgrimes     * variance_blocks is the number of blocks of the hash that we have to
5341541Srgrimes     * calculate in constant time because they could be altered by the
5351541Srgrimes     * padding value. In SSLv3, the padding must be minimal so the end of
53612404Sdyson     * the plaintext varies by, at most, 15+20 = 35 bytes. (We conservatively
5371541Srgrimes     * assume that the MAC size varies from 0..20 bytes.) In case the 9 bytes
5381541Srgrimes     * of hash termination (0x80 + 64-bit length) don't fit in the final
5391541Srgrimes     * block, we say that the final two blocks can vary based on the padding.
5401541Srgrimes     * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
5411541Srgrimes     * required to be minimal. Therefore we say that the final six blocks can
54258934Sphk     * vary based on the padding. Later in the function, if the message is
5431541Srgrimes     * short and there obviously cannot be this many blocks then
5441541Srgrimes     * variance_blocks can be reduced.
545251897Sscottl     */
546251897Sscottl    variance_blocks = is_sslv3 ? 2 : 6;
547251897Sscottl    /*
548251897Sscottl     * From now on we're dealing with the MAC, which conceptually has 13
5491541Srgrimes     * bytes of `header' before the start of the data (TLS) or 71/75 bytes
5501541Srgrimes     * (SSLv3)
5511541Srgrimes     */
5521541Srgrimes    len = data_plus_mac_plus_padding_size + header_length;
55321002Sdyson    /*
55412404Sdyson     * max_mac_bytes contains the maximum bytes of bytes in the MAC,
55521002Sdyson     * including * |header|, assuming that there's no padding.
5561541Srgrimes     */
55758934Sphk    max_mac_bytes = len - md_size - 1;
5581541Srgrimes    /* num_blocks is the maximum number of hash blocks. */
55946349Salc    num_blocks =
56046349Salc        (max_mac_bytes + 1 + md_length_size + md_block_size -
56158934Sphk         1) / md_block_size;
56258934Sphk    /*
56377115Sdillon     * In order to calculate the MAC in constant time we have to handle the
56477115Sdillon     * final blocks specially because the padding value could cause the end
56577115Sdillon     * to appear somewhere in the final |variance_blocks| blocks and we can't
56677115Sdillon     * leak where. However, |num_starting_blocks| worth of data can be hashed
56777115Sdillon     * right away because no padding value can affect whether they are
56877115Sdillon     * plaintext.
56977115Sdillon     */
57077115Sdillon    num_starting_blocks = 0;
57177115Sdillon    /*
57246349Salc     * k is the starting byte offset into the conceptual header||data where
57359249Sphk     * we start processing.
5741541Srgrimes     */
575137719Sphk    k = 0;
57642957Sdillon    /*
5771541Srgrimes     * mac_end_offset is the index just past the end of the data to be MACed.
5781541Srgrimes     */
5791541Srgrimes    mac_end_offset = data_plus_mac_size + header_length - md_size;
58048545Smckusick    /*
58148545Smckusick     * c is the index of the 0x80 byte in the final hash block that contains
58248545Smckusick     * application data.
58348545Smckusick     */
58448545Smckusick    c = mac_end_offset % md_block_size;
58548545Smckusick    /*
58648545Smckusick     * index_a is the hash block number that contains the 0x80 terminating
58748545Smckusick     * value.
58848545Smckusick     */
58948545Smckusick    index_a = mac_end_offset / md_block_size;
590251897Sscottl    /*
591251897Sscottl     * index_b is the hash block number that contains the 64-bit hash length,
59248545Smckusick     * in bits.
59348545Smckusick     */
59448545Smckusick    index_b = (mac_end_offset + md_length_size) / md_block_size;
595250947Sscottl    /*
59648545Smckusick     * bits is the hash-length in bits. It includes the additional hash block
59748545Smckusick     * for the masked HMAC key, or whole of |header| in the case of SSLv3.
59848545Smckusick     */
59948545Smckusick
600102412Scharnier    /*
60148545Smckusick     * For SSLv3, if we're going to have any starting blocks then we need at
602251897Sscottl     * least two because the header is larger than a single block.
603102412Scharnier     */
60448545Smckusick    if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) {
605102412Scharnier        num_starting_blocks = num_blocks - variance_blocks;
60648545Smckusick        k = md_block_size * num_starting_blocks;
60748545Smckusick    }
60848545Smckusick
60948545Smckusick    bits = 8 * mac_end_offset;
61048545Smckusick    if (!is_sslv3) {
61148545Smckusick        /*
6121541Srgrimes         * Compute the initial HMAC block. For SSLv3, the padding and secret
6131541Srgrimes         * bytes are included in |header| because they take more than a
6141541Srgrimes         * single block.
6151541Srgrimes         */
6161541Srgrimes        bits += 8 * md_block_size;
6171541Srgrimes        memset(hmac_pad, 0, md_block_size);
6181541Srgrimes        OPENSSL_assert(mac_secret_length <= sizeof(hmac_pad));
6191541Srgrimes        memcpy(hmac_pad, mac_secret, mac_secret_length);
6201541Srgrimes        for (i = 0; i < md_block_size; i++)
6211541Srgrimes            hmac_pad[i] ^= 0x36;
622135858Sphk
6231541Srgrimes        md_transform(md_state.c, hmac_pad);
624251144Sscottl    }
625251144Sscottl
626251144Sscottl    if (length_is_big_endian) {
627251144Sscottl        memset(length_bytes, 0, md_length_size - 4);
628251144Sscottl        length_bytes[md_length_size - 4] = (unsigned char)(bits >> 24);
629251144Sscottl        length_bytes[md_length_size - 3] = (unsigned char)(bits >> 16);
630251144Sscottl        length_bytes[md_length_size - 2] = (unsigned char)(bits >> 8);
631251144Sscottl        length_bytes[md_length_size - 1] = (unsigned char)bits;
6325455Sdg    } else {
6335455Sdg        memset(length_bytes, 0, md_length_size);
6345455Sdg        length_bytes[md_length_size - 5] = (unsigned char)(bits >> 24);
63512404Sdyson        length_bytes[md_length_size - 6] = (unsigned char)(bits >> 16);
6361541Srgrimes        length_bytes[md_length_size - 7] = (unsigned char)(bits >> 8);
637251897Sscottl        length_bytes[md_length_size - 8] = (unsigned char)bits;
638251897Sscottl    }
639251897Sscottl
64032286Sdyson    if (k > 0) {
641231936Skib        if (is_sslv3) {
64232286Sdyson            unsigned overhang;
64332286Sdyson
64432286Sdyson            /*
64532286Sdyson             * The SSLv3 header is larger than a single block. overhang is
64632286Sdyson             * the number of bytes beyond a single block that the header
6475455Sdg             * consumes: either 7 bytes (SHA1) or 11 bytes (MD5). There are no
64842408Seivind             * ciphersuites in SSLv3 that are not SHA1 or MD5 based and
64934694Sdyson             * therefore we can be confident that the header_length will be
6501541Srgrimes             * greater than |md_block_size|. However we add a sanity check just
6511541Srgrimes             * in case
6521541Srgrimes             */
6531541Srgrimes            if (header_length <= md_block_size) {
6545455Sdg                /* Should never happen */
6555455Sdg                return;
65651797Sphk            }
6571541Srgrimes            overhang = header_length - md_block_size;
6581541Srgrimes            md_transform(md_state.c, header);
6591541Srgrimes            memcpy(first_block, header + md_block_size, overhang);
6608876Srgrimes            memcpy(first_block + overhang, data, md_block_size - overhang);
6611541Srgrimes            md_transform(md_state.c, first_block);
6625455Sdg            for (i = 1; i < k / md_block_size - 1; i++)
6635455Sdg                md_transform(md_state.c, data + md_block_size * i - overhang);
6645455Sdg        } else {
6655455Sdg            /* k is a multiple of md_block_size. */
66658909Sdillon            memcpy(first_block, header, 13);
66758909Sdillon            memcpy(first_block + 13, data, md_block_size - 13);
66858909Sdillon            md_transform(md_state.c, first_block);
66958909Sdillon            for (i = 1; i < k / md_block_size; i++)
67058909Sdillon                md_transform(md_state.c, data + md_block_size * i - 13);
67158909Sdillon        }
67258909Sdillon    }
6731541Srgrimes
6741541Srgrimes    memset(mac_out, 0, sizeof(mac_out));
67534611Sdyson
67610541Sdyson    /*
67758909Sdillon     * We now process the final hash blocks. For each block, we construct it
67848677Smckusick     * in constant time. If the |i==index_a| then we'll include the 0x80
679251897Sscottl     * bytes and zero pad etc. For each block we selectively copy it, in
68058909Sdillon     * constant time, to |mac_out|.
68110541Sdyson     */
68210541Sdyson    for (i = num_starting_blocks; i <= num_starting_blocks + variance_blocks;
68310541Sdyson         i++) {
68410541Sdyson        unsigned char block[MAX_HASH_BLOCK_SIZE];
685251897Sscottl        unsigned char is_block_a = constant_time_eq_8(i, index_a);
68610541Sdyson        unsigned char is_block_b = constant_time_eq_8(i, index_b);
68710541Sdyson        for (j = 0; j < md_block_size; j++) {
68810541Sdyson            unsigned char b = 0, is_past_c, is_past_cp1;
68910541Sdyson            if (k < header_length)
69058909Sdillon                b = header[k];
69158909Sdillon            else if (k < data_plus_mac_plus_padding_size + header_length)
69258909Sdillon                b = data[k - header_length];
69358909Sdillon            k++;
69458909Sdillon
69558909Sdillon            is_past_c = is_block_a & constant_time_ge_8(j, c);
69610541Sdyson            is_past_cp1 = is_block_a & constant_time_ge_8(j, c + 1);
69710541Sdyson            /*
69810541Sdyson             * If this is the block containing the end of the application
69910541Sdyson             * data, and we are at the offset for the 0x80 value, then
70010541Sdyson             * overwrite b with 0x80.
70158909Sdillon             */
70258909Sdillon            b = constant_time_select_8(is_past_c, 0x80, b);
70358909Sdillon            /*
704251897Sscottl             * If this the the block containing the end of the application
70558909Sdillon             * data and we're past the 0x80 value then just write zero.
70610541Sdyson             */
70710541Sdyson            b = b & ~is_past_cp1;
70810541Sdyson            /*
70910541Sdyson             * If this is index_b (the final block), but not index_a (the end
71010541Sdyson             * of the data), then the 64-bit length didn't fit into index_a
71110541Sdyson             * and we're having to add an extra block of zeros.
71210541Sdyson             */
71310541Sdyson            b &= ~is_block_b | is_block_a;
71410541Sdyson
71510541Sdyson            /*
71610541Sdyson             * The final bytes of one of the blocks contains the length.
71710541Sdyson             */
71810541Sdyson            if (j >= md_block_size - md_length_size) {
7191541Srgrimes                /* If this is index_b, write a length byte. */
7201541Srgrimes                b = constant_time_select_8(is_block_b,
7215455Sdg                                           length_bytes[j -
7225455Sdg                                                        (md_block_size -
7235455Sdg                                                         md_length_size)], b);
7241541Srgrimes            }
72532286Sdyson            block[j] = b;
72634611Sdyson        }
7277613Sdg
72810551Sdyson        md_transform(md_state.c, block);
72910541Sdyson        md_final_raw(md_state.c, block);
7301541Srgrimes        /* If this is index_b, copy the hash value to |mac_out|. */
7311541Srgrimes        for (j = 0; j < md_size; j++)
7321541Srgrimes            mac_out[j] |= block[j] & is_block_b;
7331541Srgrimes    }
7341541Srgrimes
7351541Srgrimes    EVP_MD_CTX_init(&md_ctx);
7361541Srgrimes    EVP_DigestInit_ex(&md_ctx, ctx->digest, NULL /* engine */ );
7375455Sdg    if (is_sslv3) {
73812404Sdyson        /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */
7391541Srgrimes        memset(hmac_pad, 0x5c, sslv3_pad_length);
74013490Sdyson
7415455Sdg        EVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length);
7421541Srgrimes        EVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length);
7435455Sdg        EVP_DigestUpdate(&md_ctx, mac_out, md_size);
7441541Srgrimes    } else {
7451541Srgrimes        /* Complete the HMAC in the standard manner. */
7461541Srgrimes        for (i = 0; i < md_block_size; i++)
74758909Sdillon            hmac_pad[i] ^= 0x6a;
74858909Sdillon
74958909Sdillon        EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size);
7501541Srgrimes        EVP_DigestUpdate(&md_ctx, mac_out, md_size);
75112404Sdyson    }
752251897Sscottl    EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u);
753251897Sscottl    if (md_out_size)
754251897Sscottl        *md_out_size = md_out_size_u;
755251897Sscottl    EVP_MD_CTX_cleanup(&md_ctx);
7561541Srgrimes}
7571541Srgrimes
75868885Sdillon#ifdef OPENSSL_FIPS
75968885Sdillon
76068885Sdillon/*
76168885Sdillon * Due to the need to use EVP in FIPS mode we can't reimplement digests but
76268885Sdillon * we can ensure the number of blocks processed is equal for all cases by
76358909Sdillon * digesting additional data.
7641541Srgrimes */
7655455Sdg
7661541Srgrimesvoid tls_fips_digest_extra(const EVP_CIPHER_CTX *cipher_ctx,
7671541Srgrimes                           EVP_MD_CTX *mac_ctx, const unsigned char *data,
76858909Sdillon                           size_t data_len, size_t orig_len)
7691541Srgrimes{
7701541Srgrimes    size_t block_size, digest_pad, blocks_data, blocks_orig;
7711541Srgrimes    if (EVP_CIPHER_CTX_mode(cipher_ctx) != EVP_CIPH_CBC_MODE)
7721541Srgrimes        return;
7731541Srgrimes    block_size = EVP_MD_CTX_block_size(mac_ctx);
7741541Srgrimes    /*-
7751541Srgrimes     * We are in FIPS mode if we get this far so we know we have only SHA*
7761541Srgrimes     * digests and TLS to deal with.
7771541Srgrimes     * Minimum digest padding length is 17 for SHA384/SHA512 and 9
7781541Srgrimes     * otherwise.
7791541Srgrimes     * Additional header is 13 bytes. To get the number of digest blocks
78012767Sdyson     * processed round up the amount of data plus padding to the nearest
781251144Sscottl     * block length. Block length is 128 for SHA384/SHA512 and 64 otherwise.
7821541Srgrimes     * So we have:
783251144Sscottl     * blocks = (payload_len + digest_pad + 13 + block_size - 1)/block_size
784251144Sscottl     * equivalently:
785251144Sscottl     * blocks = (payload_len + digest_pad + 12)/block_size + 1
786251144Sscottl     * HMAC adds a constant overhead.
787251144Sscottl     * We're ultimately only interested in differences so this becomes
788251144Sscottl     * blocks = (payload_len + 29)/128
789251144Sscottl     * for SHA384/SHA512 and
790251144Sscottl     * blocks = (payload_len + 21)/64
79112404Sdyson     * otherwise.
792177493Sjeff     */
793145734Sjeff    digest_pad = block_size == 64 ? 21 : 29;
79412767Sdyson    blocks_orig = (orig_len + digest_pad) / block_size;
79512404Sdyson    blocks_data = (data_len + digest_pad) / block_size;
79635595Sbde    /*
797251897Sscottl     * MAC enough blocks to make up the difference between the original and
798251897Sscottl     * actual lengths plus one extra block to ensure this is never a no op.
799251897Sscottl     * The "data" pointer should always have enough space to perform this
800177493Sjeff     * operation as it is large enough for a maximum length TLS buffer.
80112767Sdyson     */
80271230Sdillon    EVP_DigestSignUpdate(mac_ctx, data,
80371230Sdillon                         (blocks_orig - blocks_data + 1) * block_size);
80471230Sdillon}
80572080Sasmodai#endif
80671230Sdillon