PRF and handshake hash revision.
[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 "internal/constant_time_locl.h"
57 #include "ssl_locl.h"
58
59 #include <openssl/md5.h>
60 #include <openssl/sha.h>
61
62 /*
63  * MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's
64  * length field. (SHA-384/512 have 128-bit length.)
65  */
66 #define MAX_HASH_BIT_COUNT_BYTES 16
67
68 /*
69  * MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
70  * Currently SHA-384/512 has a 128-byte block size and that's the largest
71  * supported by TLS.)
72  */
73 #define MAX_HASH_BLOCK_SIZE 128
74
75
76
77 /*
78  * u32toLE serialises an unsigned, 32-bit number (n) as four bytes at (p) in
79  * little-endian order. The value of p is advanced by four.
80  */
81 #define u32toLE(n, p) \
82         (*((p)++)=(unsigned char)(n), \
83          *((p)++)=(unsigned char)(n>>8), \
84          *((p)++)=(unsigned char)(n>>16), \
85          *((p)++)=(unsigned char)(n>>24))
86
87 /*
88  * These functions serialize the state of a hash and thus perform the
89  * standard "final" operation without adding the padding and length that such
90  * a function typically does.
91  */
92 static void tls1_md5_final_raw(void *ctx, unsigned char *md_out)
93 {
94     MD5_CTX *md5 = ctx;
95     u32toLE(md5->A, md_out);
96     u32toLE(md5->B, md_out);
97     u32toLE(md5->C, md_out);
98     u32toLE(md5->D, md_out);
99 }
100
101 static void tls1_sha1_final_raw(void *ctx, unsigned char *md_out)
102 {
103     SHA_CTX *sha1 = ctx;
104     l2n(sha1->h0, md_out);
105     l2n(sha1->h1, md_out);
106     l2n(sha1->h2, md_out);
107     l2n(sha1->h3, md_out);
108     l2n(sha1->h4, md_out);
109 }
110
111 static void tls1_sha256_final_raw(void *ctx, unsigned char *md_out)
112 {
113     SHA256_CTX *sha256 = ctx;
114     unsigned i;
115
116     for (i = 0; i < 8; i++) {
117         l2n(sha256->h[i], md_out);
118     }
119 }
120
121 static void tls1_sha512_final_raw(void *ctx, unsigned char *md_out)
122 {
123     SHA512_CTX *sha512 = ctx;
124     unsigned i;
125
126     for (i = 0; i < 8; i++) {
127         l2n8(sha512->h[i], md_out);
128     }
129 }
130
131 #undef  LARGEST_DIGEST_CTX
132 #define LARGEST_DIGEST_CTX SHA512_CTX
133
134 /*
135  * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
136  * which ssl3_cbc_digest_record supports.
137  */
138 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
139 {
140     if (FIPS_mode())
141         return 0;
142     switch (EVP_MD_CTX_type(ctx)) {
143     case NID_md5:
144     case NID_sha1:
145     case NID_sha224:
146     case NID_sha256:
147     case NID_sha384:
148     case NID_sha512:
149         return 1;
150     default:
151         return 0;
152     }
153 }
154
155 /*-
156  * ssl3_cbc_digest_record computes the MAC of a decrypted, padded SSLv3/TLS
157  * record.
158  *
159  *   ctx: the EVP_MD_CTX from which we take the hash function.
160  *     ssl3_cbc_record_digest_supported must return true for this EVP_MD_CTX.
161  *   md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
162  *   md_out_size: if non-NULL, the number of output bytes is written here.
163  *   header: the 13-byte, TLS record header.
164  *   data: the record data itself, less any preceding explicit IV.
165  *   data_plus_mac_size: the secret, reported length of the data and MAC
166  *     once the padding has been removed.
167  *   data_plus_mac_plus_padding_size: the public length of the whole
168  *     record, including padding.
169  *   is_sslv3: non-zero if we are to use SSLv3. Otherwise, TLS.
170  *
171  * On entry: by virtue of having been through one of the remove_padding
172  * functions, above, we know that data_plus_mac_size is large enough to contain
173  * a padding byte and MAC. (If the padding was invalid, it might contain the
174  * padding too. )
175  * Returns 1 on success or 0 on error
176  */
177 int ssl3_cbc_digest_record(const EVP_MD_CTX *ctx,
178                             unsigned char *md_out,
179                             size_t *md_out_size,
180                             const unsigned char header[13],
181                             const unsigned char *data,
182                             size_t data_plus_mac_size,
183                             size_t data_plus_mac_plus_padding_size,
184                             const unsigned char *mac_secret,
185                             unsigned mac_secret_length, char is_sslv3)
186 {
187     union {
188         double align;
189         unsigned char c[sizeof(LARGEST_DIGEST_CTX)];
190     } md_state;
191     void (*md_final_raw) (void *ctx, unsigned char *md_out);
192     void (*md_transform) (void *ctx, const unsigned char *block);
193     unsigned md_size, md_block_size = 64;
194     unsigned sslv3_pad_length = 40, header_length, variance_blocks,
195         len, max_mac_bytes, num_blocks,
196         num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
197     unsigned int bits;          /* at most 18 bits */
198     unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
199     /* hmac_pad is the masked HMAC key. */
200     unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
201     unsigned char first_block[MAX_HASH_BLOCK_SIZE];
202     unsigned char mac_out[EVP_MAX_MD_SIZE];
203     unsigned i, j, md_out_size_u;
204     EVP_MD_CTX md_ctx;
205     /*
206      * mdLengthSize is the number of bytes in the length field that
207      * terminates * the hash.
208      */
209     unsigned md_length_size = 8;
210     char length_is_big_endian = 1;
211     int ret;
212
213     /*
214      * This is a, hopefully redundant, check that allows us to forget about
215      * many possible overflows later in this function.
216      */
217     OPENSSL_assert(data_plus_mac_plus_padding_size < 1024 * 1024);
218
219     switch (EVP_MD_CTX_type(ctx)) {
220     case NID_md5:
221         if (MD5_Init((MD5_CTX *)md_state.c) <= 0)
222             return 0;
223         md_final_raw = tls1_md5_final_raw;
224         md_transform =
225             (void (*)(void *ctx, const unsigned char *block))MD5_Transform;
226         md_size = 16;
227         sslv3_pad_length = 48;
228         length_is_big_endian = 0;
229         break;
230     case NID_sha1:
231         if (SHA1_Init((SHA_CTX *)md_state.c) <= 0)
232             return 0;
233         md_final_raw = tls1_sha1_final_raw;
234         md_transform =
235             (void (*)(void *ctx, const unsigned char *block))SHA1_Transform;
236         md_size = 20;
237         break;
238     case NID_sha224:
239         if (SHA224_Init((SHA256_CTX *)md_state.c) <= 0)
240             return 0;
241         md_final_raw = tls1_sha256_final_raw;
242         md_transform =
243             (void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
244         md_size = 224 / 8;
245         break;
246     case NID_sha256:
247         if (SHA256_Init((SHA256_CTX *)md_state.c) <= 0)
248             return 0;
249         md_final_raw = tls1_sha256_final_raw;
250         md_transform =
251             (void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
252         md_size = 32;
253         break;
254     case NID_sha384:
255         if (SHA384_Init((SHA512_CTX *)md_state.c) <= 0)
256             return 0;
257         md_final_raw = tls1_sha512_final_raw;
258         md_transform =
259             (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
260         md_size = 384 / 8;
261         md_block_size = 128;
262         md_length_size = 16;
263         break;
264     case NID_sha512:
265         if (SHA512_Init((SHA512_CTX *)md_state.c) <= 0)
266             return 0;
267         md_final_raw = tls1_sha512_final_raw;
268         md_transform =
269             (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
270         md_size = 64;
271         md_block_size = 128;
272         md_length_size = 16;
273         break;
274     default:
275         /*
276          * ssl3_cbc_record_digest_supported should have been called first to
277          * check that the hash function is supported.
278          */
279         OPENSSL_assert(0);
280         if (md_out_size)
281             *md_out_size = 0;
282         return 0;
283     }
284
285     OPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES);
286     OPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE);
287     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
288
289     header_length = 13;
290     if (is_sslv3) {
291         header_length = mac_secret_length + sslv3_pad_length + 8 /* sequence
292                                                                   * number */  +
293             1 /* record type */  +
294             2 /* record length */ ;
295     }
296
297     /*
298      * variance_blocks is the number of blocks of the hash that we have to
299      * calculate in constant time because they could be altered by the
300      * padding value. In SSLv3, the padding must be minimal so the end of
301      * the plaintext varies by, at most, 15+20 = 35 bytes. (We conservatively
302      * assume that the MAC size varies from 0..20 bytes.) In case the 9 bytes
303      * of hash termination (0x80 + 64-bit length) don't fit in the final
304      * block, we say that the final two blocks can vary based on the padding.
305      * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
306      * required to be minimal. Therefore we say that the final six blocks can
307      * vary based on the padding. Later in the function, if the message is
308      * short and there obviously cannot be this many blocks then
309      * variance_blocks can be reduced.
310      */
311     variance_blocks = is_sslv3 ? 2 : 6;
312     /*
313      * From now on we're dealing with the MAC, which conceptually has 13
314      * bytes of `header' before the start of the data (TLS) or 71/75 bytes
315      * (SSLv3)
316      */
317     len = data_plus_mac_plus_padding_size + header_length;
318     /*
319      * max_mac_bytes contains the maximum bytes of bytes in the MAC,
320      * including * |header|, assuming that there's no padding.
321      */
322     max_mac_bytes = len - md_size - 1;
323     /* num_blocks is the maximum number of hash blocks. */
324     num_blocks =
325         (max_mac_bytes + 1 + md_length_size + md_block_size -
326          1) / md_block_size;
327     /*
328      * In order to calculate the MAC in constant time we have to handle the
329      * final blocks specially because the padding value could cause the end
330      * to appear somewhere in the final |variance_blocks| blocks and we can't
331      * leak where. However, |num_starting_blocks| worth of data can be hashed
332      * right away because no padding value can affect whether they are
333      * plaintext.
334      */
335     num_starting_blocks = 0;
336     /*
337      * k is the starting byte offset into the conceptual header||data where
338      * we start processing.
339      */
340     k = 0;
341     /*
342      * mac_end_offset is the index just past the end of the data to be MACed.
343      */
344     mac_end_offset = data_plus_mac_size + header_length - md_size;
345     /*
346      * c is the index of the 0x80 byte in the final hash block that contains
347      * application data.
348      */
349     c = mac_end_offset % md_block_size;
350     /*
351      * index_a is the hash block number that contains the 0x80 terminating
352      * value.
353      */
354     index_a = mac_end_offset / md_block_size;
355     /*
356      * index_b is the hash block number that contains the 64-bit hash length,
357      * in bits.
358      */
359     index_b = (mac_end_offset + md_length_size) / md_block_size;
360     /*
361      * bits is the hash-length in bits. It includes the additional hash block
362      * for the masked HMAC key, or whole of |header| in the case of SSLv3.
363      */
364
365     /*
366      * For SSLv3, if we're going to have any starting blocks then we need at
367      * least two because the header is larger than a single block.
368      */
369     if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) {
370         num_starting_blocks = num_blocks - variance_blocks;
371         k = md_block_size * num_starting_blocks;
372     }
373
374     bits = 8 * mac_end_offset;
375     if (!is_sslv3) {
376         /*
377          * Compute the initial HMAC block. For SSLv3, the padding and secret
378          * bytes are included in |header| because they take more than a
379          * single block.
380          */
381         bits += 8 * md_block_size;
382         memset(hmac_pad, 0, md_block_size);
383         OPENSSL_assert(mac_secret_length <= sizeof(hmac_pad));
384         memcpy(hmac_pad, mac_secret, mac_secret_length);
385         for (i = 0; i < md_block_size; i++)
386             hmac_pad[i] ^= 0x36;
387
388         md_transform(md_state.c, hmac_pad);
389     }
390
391     if (length_is_big_endian) {
392         memset(length_bytes, 0, md_length_size - 4);
393         length_bytes[md_length_size - 4] = (unsigned char)(bits >> 24);
394         length_bytes[md_length_size - 3] = (unsigned char)(bits >> 16);
395         length_bytes[md_length_size - 2] = (unsigned char)(bits >> 8);
396         length_bytes[md_length_size - 1] = (unsigned char)bits;
397     } else {
398         memset(length_bytes, 0, md_length_size);
399         length_bytes[md_length_size - 5] = (unsigned char)(bits >> 24);
400         length_bytes[md_length_size - 6] = (unsigned char)(bits >> 16);
401         length_bytes[md_length_size - 7] = (unsigned char)(bits >> 8);
402         length_bytes[md_length_size - 8] = (unsigned char)bits;
403     }
404
405     if (k > 0) {
406         if (is_sslv3) {
407             unsigned overhang;
408
409             /*
410              * The SSLv3 header is larger than a single block. overhang is
411              * the number of bytes beyond a single block that the header
412              * consumes: either 7 bytes (SHA1) or 11 bytes (MD5). There are no
413              * ciphersuites in SSLv3 that are not SHA1 or MD5 based and
414              * therefore we can be confident that the header_length will be
415              * greater than |md_block_size|. However we add a sanity check just
416              * in case
417              */
418             if (header_length <= md_block_size) {
419                 /* Should never happen */
420                 return 0;
421             }
422             overhang = header_length - md_block_size;
423             md_transform(md_state.c, header);
424             memcpy(first_block, header + md_block_size, overhang);
425             memcpy(first_block + overhang, data, md_block_size - overhang);
426             md_transform(md_state.c, first_block);
427             for (i = 1; i < k / md_block_size - 1; i++)
428                 md_transform(md_state.c, data + md_block_size * i - overhang);
429         } else {
430             /* k is a multiple of md_block_size. */
431             memcpy(first_block, header, 13);
432             memcpy(first_block + 13, data, md_block_size - 13);
433             md_transform(md_state.c, first_block);
434             for (i = 1; i < k / md_block_size; i++)
435                 md_transform(md_state.c, data + md_block_size * i - 13);
436         }
437     }
438
439     memset(mac_out, 0, sizeof(mac_out));
440
441     /*
442      * We now process the final hash blocks. For each block, we construct it
443      * in constant time. If the |i==index_a| then we'll include the 0x80
444      * bytes and zero pad etc. For each block we selectively copy it, in
445      * constant time, to |mac_out|.
446      */
447     for (i = num_starting_blocks; i <= num_starting_blocks + variance_blocks;
448          i++) {
449         unsigned char block[MAX_HASH_BLOCK_SIZE];
450         unsigned char is_block_a = constant_time_eq_8(i, index_a);
451         unsigned char is_block_b = constant_time_eq_8(i, index_b);
452         for (j = 0; j < md_block_size; j++) {
453             unsigned char b = 0, is_past_c, is_past_cp1;
454             if (k < header_length)
455                 b = header[k];
456             else if (k < data_plus_mac_plus_padding_size + header_length)
457                 b = data[k - header_length];
458             k++;
459
460             is_past_c = is_block_a & constant_time_ge_8(j, c);
461             is_past_cp1 = is_block_a & constant_time_ge_8(j, c + 1);
462             /*
463              * If this is the block containing the end of the application
464              * data, and we are at the offset for the 0x80 value, then
465              * overwrite b with 0x80.
466              */
467             b = constant_time_select_8(is_past_c, 0x80, b);
468             /*
469              * If this the the block containing the end of the application
470              * data and we're past the 0x80 value then just write zero.
471              */
472             b = b & ~is_past_cp1;
473             /*
474              * If this is index_b (the final block), but not index_a (the end
475              * of the data), then the 64-bit length didn't fit into index_a
476              * and we're having to add an extra block of zeros.
477              */
478             b &= ~is_block_b | is_block_a;
479
480             /*
481              * The final bytes of one of the blocks contains the length.
482              */
483             if (j >= md_block_size - md_length_size) {
484                 /* If this is index_b, write a length byte. */
485                 b = constant_time_select_8(is_block_b,
486                                            length_bytes[j -
487                                                         (md_block_size -
488                                                          md_length_size)], b);
489             }
490             block[j] = b;
491         }
492
493         md_transform(md_state.c, block);
494         md_final_raw(md_state.c, block);
495         /* If this is index_b, copy the hash value to |mac_out|. */
496         for (j = 0; j < md_size; j++)
497             mac_out[j] |= block[j] & is_block_b;
498     }
499
500     EVP_MD_CTX_init(&md_ctx);
501     if (EVP_DigestInit_ex(&md_ctx, ctx->digest, NULL /* engine */ ) <= 0)
502         goto err;
503     if (is_sslv3) {
504         /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */
505         memset(hmac_pad, 0x5c, sslv3_pad_length);
506
507         if (EVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length) <= 0
508                 || EVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length) <= 0
509                 || EVP_DigestUpdate(&md_ctx, mac_out, md_size) <= 0)
510             goto err;
511     } else {
512         /* Complete the HMAC in the standard manner. */
513         for (i = 0; i < md_block_size; i++)
514             hmac_pad[i] ^= 0x6a;
515
516         if (EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size) <= 0
517                 || EVP_DigestUpdate(&md_ctx, mac_out, md_size) <= 0)
518             goto err;
519     }
520     ret = EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u);
521     if (ret && md_out_size)
522         *md_out_size = md_out_size_u;
523     EVP_MD_CTX_cleanup(&md_ctx);
524
525     return 1;
526 err:
527     EVP_MD_CTX_cleanup(&md_ctx);
528     return 0;
529 }
530
531 /*
532  * Due to the need to use EVP in FIPS mode we can't reimplement digests but
533  * we can ensure the number of blocks processed is equal for all cases by
534  * digesting additional data.
535  */
536
537 void tls_fips_digest_extra(const EVP_CIPHER_CTX *cipher_ctx,
538                            EVP_MD_CTX *mac_ctx, const unsigned char *data,
539                            size_t data_len, size_t orig_len)
540 {
541     size_t block_size, digest_pad, blocks_data, blocks_orig;
542     if (EVP_CIPHER_CTX_mode(cipher_ctx) != EVP_CIPH_CBC_MODE)
543         return;
544     block_size = EVP_MD_CTX_block_size(mac_ctx);
545     /*-
546      * We are in FIPS mode if we get this far so we know we have only SHA*
547      * digests and TLS to deal with.
548      * Minimum digest padding length is 17 for SHA384/SHA512 and 9
549      * otherwise.
550      * Additional header is 13 bytes. To get the number of digest blocks
551      * processed round up the amount of data plus padding to the nearest
552      * block length. Block length is 128 for SHA384/SHA512 and 64 otherwise.
553      * So we have:
554      * blocks = (payload_len + digest_pad + 13 + block_size - 1)/block_size
555      * equivalently:
556      * blocks = (payload_len + digest_pad + 12)/block_size + 1
557      * HMAC adds a constant overhead.
558      * We're ultimately only interested in differences so this becomes
559      * blocks = (payload_len + 29)/128
560      * for SHA384/SHA512 and
561      * blocks = (payload_len + 21)/64
562      * otherwise.
563      */
564     digest_pad = block_size == 64 ? 21 : 29;
565     blocks_orig = (orig_len + digest_pad) / block_size;
566     blocks_data = (data_len + digest_pad) / block_size;
567     /*
568      * MAC enough blocks to make up the difference between the original and
569      * actual lengths plus one extra block to ensure this is never a no op.
570      * The "data" pointer should always have enough space to perform this
571      * operation as it is large enough for a maximum length TLS buffer.
572      */
573     EVP_DigestSignUpdate(mac_ctx, data,
574                          (blocks_orig - blocks_data + 1) * block_size);
575 }