Make ssl3_cbc_digest_record() use the real data_size
[openssl.git] / ssl / s3_cbc.c
1 /*
2  * Copyright 2012-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /*
11  * This file has no dependencies on the rest of libssl because it is shared
12  * with the providers. It contains functions for low level MAC calculations.
13  * Responsibility for this lies with the HMAC implementation in the
14  * providers. However there are legacy code paths in libssl which also need to
15  * do this. In time those legacy code paths can be removed and this file can be
16  * moved out of libssl.
17  */
18
19
20 /*
21  * MD5 and SHA-1 low level APIs are deprecated for public use, but still ok for
22  * internal use.
23  */
24 #include "internal/deprecated.h"
25
26 #include "internal/constant_time.h"
27 #include "internal/cryptlib.h"
28
29 #include <openssl/evp.h>
30 #include <openssl/md5.h>
31 #include <openssl/sha.h>
32
33 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx);
34 int ssl3_cbc_digest_record(const EVP_MD *md,
35                            unsigned char *md_out,
36                            size_t *md_out_size,
37                            const unsigned char header[13],
38                            const unsigned char *data,
39                            size_t data_size,
40                            size_t data_plus_mac_plus_padding_size,
41                            const unsigned char *mac_secret,
42                            size_t mac_secret_length, char is_sslv3);
43
44 # define l2n(l,c)        (*((c)++)=(unsigned char)(((l)>>24)&0xff), \
45                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
46                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
47                          *((c)++)=(unsigned char)(((l)    )&0xff))
48
49 # define l2n6(l,c)       (*((c)++)=(unsigned char)(((l)>>40)&0xff), \
50                          *((c)++)=(unsigned char)(((l)>>32)&0xff), \
51                          *((c)++)=(unsigned char)(((l)>>24)&0xff), \
52                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
53                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
54                          *((c)++)=(unsigned char)(((l)    )&0xff))
55
56 # define l2n8(l,c)       (*((c)++)=(unsigned char)(((l)>>56)&0xff), \
57                          *((c)++)=(unsigned char)(((l)>>48)&0xff), \
58                          *((c)++)=(unsigned char)(((l)>>40)&0xff), \
59                          *((c)++)=(unsigned char)(((l)>>32)&0xff), \
60                          *((c)++)=(unsigned char)(((l)>>24)&0xff), \
61                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
62                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
63                          *((c)++)=(unsigned char)(((l)    )&0xff))
64
65 /*
66  * MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's
67  * length field. (SHA-384/512 have 128-bit length.)
68  */
69 #define MAX_HASH_BIT_COUNT_BYTES 16
70
71 /*
72  * MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
73  * Currently SHA-384/512 has a 128-byte block size and that's the largest
74  * supported by TLS.)
75  */
76 #define MAX_HASH_BLOCK_SIZE 128
77
78 /*
79  * u32toLE serializes an unsigned, 32-bit number (n) as four bytes at (p) in
80  * little-endian order. The value of p is advanced by four.
81  */
82 #define u32toLE(n, p) \
83         (*((p)++)=(unsigned char)(n), \
84          *((p)++)=(unsigned char)(n>>8), \
85          *((p)++)=(unsigned char)(n>>16), \
86          *((p)++)=(unsigned char)(n>>24))
87
88 /*
89  * These functions serialize the state of a hash and thus perform the
90  * standard "final" operation without adding the padding and length that such
91  * a function typically does.
92  */
93 static void tls1_md5_final_raw(void *ctx, unsigned char *md_out)
94 {
95     MD5_CTX *md5 = ctx;
96     u32toLE(md5->A, md_out);
97     u32toLE(md5->B, md_out);
98     u32toLE(md5->C, md_out);
99     u32toLE(md5->D, md_out);
100 }
101
102 static void tls1_sha1_final_raw(void *ctx, unsigned char *md_out)
103 {
104     SHA_CTX *sha1 = ctx;
105     l2n(sha1->h0, md_out);
106     l2n(sha1->h1, md_out);
107     l2n(sha1->h2, md_out);
108     l2n(sha1->h3, md_out);
109     l2n(sha1->h4, md_out);
110 }
111
112 static void tls1_sha256_final_raw(void *ctx, unsigned char *md_out)
113 {
114     SHA256_CTX *sha256 = ctx;
115     unsigned i;
116
117     for (i = 0; i < 8; i++) {
118         l2n(sha256->h[i], md_out);
119     }
120 }
121
122 static void tls1_sha512_final_raw(void *ctx, unsigned char *md_out)
123 {
124     SHA512_CTX *sha512 = ctx;
125     unsigned i;
126
127     for (i = 0; i < 8; i++) {
128         l2n8(sha512->h[i], md_out);
129     }
130 }
131
132 #undef  LARGEST_DIGEST_CTX
133 #define LARGEST_DIGEST_CTX SHA512_CTX
134
135 /*
136  * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
137  * which ssl3_cbc_digest_record supports.
138  */
139 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
140 {
141     switch (EVP_MD_CTX_type(ctx)) {
142     case NID_md5:
143     case NID_sha1:
144     case NID_sha224:
145     case NID_sha256:
146     case NID_sha384:
147     case NID_sha512:
148         return 1;
149     default:
150         return 0;
151     }
152 }
153
154 /*-
155  * ssl3_cbc_digest_record computes the MAC of a decrypted, padded SSLv3/TLS
156  * record.
157  *
158  *   ctx: the EVP_MD_CTX from which we take the hash function.
159  *     ssl3_cbc_record_digest_supported must return true for this EVP_MD_CTX.
160  *   md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
161  *   md_out_size: if non-NULL, the number of output bytes is written here.
162  *   header: the 13-byte, TLS record header.
163  *   data: the record data itself, less any preceding explicit IV.
164  *   data_size: the secret, reported length of the data once the MAC and padding
165  *              has been removed.
166  *   data_plus_mac_plus_padding_size: the public length of the whole
167  *     record, including MAC and padding.
168  *   is_sslv3: non-zero if we are to use SSLv3. Otherwise, TLS.
169  *
170  * On entry: we know that data is data_plus_mac_plus_padding_size in length
171  * Returns 1 on success or 0 on error
172  */
173 int ssl3_cbc_digest_record(const EVP_MD *md,
174                            unsigned char *md_out,
175                            size_t *md_out_size,
176                            const unsigned char header[13],
177                            const unsigned char *data,
178                            size_t data_size,
179                            size_t data_plus_mac_plus_padding_size,
180                            const unsigned char *mac_secret,
181                            size_t mac_secret_length, char is_sslv3)
182 {
183     union {
184         OSSL_UNION_ALIGN;
185         unsigned char c[sizeof(LARGEST_DIGEST_CTX)];
186     } md_state;
187     void (*md_final_raw) (void *ctx, unsigned char *md_out);
188     void (*md_transform) (void *ctx, const unsigned char *block);
189     size_t md_size, md_block_size = 64;
190     size_t sslv3_pad_length = 40, header_length, variance_blocks,
191         len, max_mac_bytes, num_blocks,
192         num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
193     size_t bits;          /* at most 18 bits */
194     unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
195     /* hmac_pad is the masked HMAC key. */
196     unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
197     unsigned char first_block[MAX_HASH_BLOCK_SIZE];
198     unsigned char mac_out[EVP_MAX_MD_SIZE];
199     size_t i, j;
200     unsigned md_out_size_u;
201     EVP_MD_CTX *md_ctx = NULL;
202     /*
203      * mdLengthSize is the number of bytes in the length field that
204      * terminates * the hash.
205      */
206     size_t md_length_size = 8;
207     char length_is_big_endian = 1;
208     int ret = 0;
209
210     /*
211      * This is a, hopefully redundant, check that allows us to forget about
212      * many possible overflows later in this function.
213      */
214     if (!ossl_assert(data_plus_mac_plus_padding_size < 1024 * 1024))
215         return 0;
216
217     switch (EVP_MD_type(md)) {
218     case NID_md5:
219         if (MD5_Init((MD5_CTX *)md_state.c) <= 0)
220             return 0;
221         md_final_raw = tls1_md5_final_raw;
222         md_transform =
223             (void (*)(void *ctx, const unsigned char *block))MD5_Transform;
224         md_size = 16;
225         sslv3_pad_length = 48;
226         length_is_big_endian = 0;
227         break;
228     case NID_sha1:
229         if (SHA1_Init((SHA_CTX *)md_state.c) <= 0)
230             return 0;
231         md_final_raw = tls1_sha1_final_raw;
232         md_transform =
233             (void (*)(void *ctx, const unsigned char *block))SHA1_Transform;
234         md_size = 20;
235         break;
236     case NID_sha224:
237         if (SHA224_Init((SHA256_CTX *)md_state.c) <= 0)
238             return 0;
239         md_final_raw = tls1_sha256_final_raw;
240         md_transform =
241             (void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
242         md_size = 224 / 8;
243         break;
244     case NID_sha256:
245         if (SHA256_Init((SHA256_CTX *)md_state.c) <= 0)
246             return 0;
247         md_final_raw = tls1_sha256_final_raw;
248         md_transform =
249             (void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
250         md_size = 32;
251         break;
252     case NID_sha384:
253         if (SHA384_Init((SHA512_CTX *)md_state.c) <= 0)
254             return 0;
255         md_final_raw = tls1_sha512_final_raw;
256         md_transform =
257             (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
258         md_size = 384 / 8;
259         md_block_size = 128;
260         md_length_size = 16;
261         break;
262     case NID_sha512:
263         if (SHA512_Init((SHA512_CTX *)md_state.c) <= 0)
264             return 0;
265         md_final_raw = tls1_sha512_final_raw;
266         md_transform =
267             (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
268         md_size = 64;
269         md_block_size = 128;
270         md_length_size = 16;
271         break;
272     default:
273         /*
274          * ssl3_cbc_record_digest_supported should have been called first to
275          * check that the hash function is supported.
276          */
277         if (md_out_size != NULL)
278             *md_out_size = 0;
279         return ossl_assert(0);
280     }
281
282     if (!ossl_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES)
283             || !ossl_assert(md_block_size <= MAX_HASH_BLOCK_SIZE)
284             || !ossl_assert(md_size <= EVP_MAX_MD_SIZE))
285         return 0;
286
287     header_length = 13;
288     if (is_sslv3) {
289         header_length = mac_secret_length + sslv3_pad_length + 8 /* sequence
290                                                                   * number */  +
291             1 /* record type */  +
292             2 /* record length */ ;
293     }
294
295     /*
296      * variance_blocks is the number of blocks of the hash that we have to
297      * calculate in constant time because they could be altered by the
298      * padding value. In SSLv3, the padding must be minimal so the end of
299      * the plaintext varies by, at most, 15+20 = 35 bytes. (We conservatively
300      * assume that the MAC size varies from 0..20 bytes.) In case the 9 bytes
301      * of hash termination (0x80 + 64-bit length) don't fit in the final
302      * block, we say that the final two blocks can vary based on the padding.
303      * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
304      * required to be minimal. Therefore we say that the final |variance_blocks|
305      * blocks can
306      * vary based on the padding. Later in the function, if the message is
307      * short and there obviously cannot be this many blocks then
308      * variance_blocks can be reduced.
309      */
310     variance_blocks = is_sslv3 ? 2 : ( ((255 + 1 + md_size + md_block_size - 1) / md_block_size) + 1);
311     /*
312      * From now on we're dealing with the MAC, which conceptually has 13
313      * bytes of `header' before the start of the data (TLS) or 71/75 bytes
314      * (SSLv3)
315      */
316     len = data_plus_mac_plus_padding_size + header_length;
317     /*
318      * max_mac_bytes contains the maximum bytes of bytes in the MAC,
319      * including * |header|, assuming that there's no padding.
320      */
321     max_mac_bytes = len - md_size - 1;
322     /* num_blocks is the maximum number of hash blocks. */
323     num_blocks =
324         (max_mac_bytes + 1 + md_length_size + md_block_size -
325          1) / md_block_size;
326     /*
327      * In order to calculate the MAC in constant time we have to handle the
328      * final blocks specially because the padding value could cause the end
329      * to appear somewhere in the final |variance_blocks| blocks and we can't
330      * leak where. However, |num_starting_blocks| worth of data can be hashed
331      * right away because no padding value can affect whether they are
332      * plaintext.
333      */
334     num_starting_blocks = 0;
335     /*
336      * k is the starting byte offset into the conceptual header||data where
337      * we start processing.
338      */
339     k = 0;
340     /*
341      * mac_end_offset is the index just past the end of the data to be MACed.
342      */
343     mac_end_offset = data_size + header_length;
344     /*
345      * c is the index of the 0x80 byte in the final hash block that contains
346      * application data.
347      */
348     c = mac_end_offset % md_block_size;
349     /*
350      * index_a is the hash block number that contains the 0x80 terminating
351      * value.
352      */
353     index_a = mac_end_offset / md_block_size;
354     /*
355      * index_b is the hash block number that contains the 64-bit hash length,
356      * in bits.
357      */
358     index_b = (mac_end_offset + md_length_size) / md_block_size;
359     /*
360      * bits is the hash-length in bits. It includes the additional hash block
361      * for the masked HMAC key, or whole of |header| in the case of SSLv3.
362      */
363
364     /*
365      * For SSLv3, if we're going to have any starting blocks then we need at
366      * least two because the header is larger than a single block.
367      */
368     if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) {
369         num_starting_blocks = num_blocks - variance_blocks;
370         k = md_block_size * num_starting_blocks;
371     }
372
373     bits = 8 * mac_end_offset;
374     if (!is_sslv3) {
375         /*
376          * Compute the initial HMAC block. For SSLv3, the padding and secret
377          * bytes are included in |header| because they take more than a
378          * single block.
379          */
380         bits += 8 * md_block_size;
381         memset(hmac_pad, 0, md_block_size);
382         if (!ossl_assert(mac_secret_length <= sizeof(hmac_pad)))
383             return 0;
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             size_t 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_s(i, index_a);
451         unsigned char is_block_b = constant_time_eq_8_s(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_s(j, c);
461             is_past_cp1 = is_block_a & constant_time_ge_8_s(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 block contains the end of the application data
470              * 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     md_ctx = EVP_MD_CTX_new();
501     if (md_ctx == NULL)
502         goto err;
503
504     if (EVP_DigestInit_ex(md_ctx, md, NULL /* engine */ ) <= 0)
505         goto err;
506     if (is_sslv3) {
507         /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */
508         memset(hmac_pad, 0x5c, sslv3_pad_length);
509
510         if (EVP_DigestUpdate(md_ctx, mac_secret, mac_secret_length) <= 0
511             || EVP_DigestUpdate(md_ctx, hmac_pad, sslv3_pad_length) <= 0
512             || EVP_DigestUpdate(md_ctx, mac_out, md_size) <= 0)
513             goto err;
514     } else {
515         /* Complete the HMAC in the standard manner. */
516         for (i = 0; i < md_block_size; i++)
517             hmac_pad[i] ^= 0x6a;
518
519         if (EVP_DigestUpdate(md_ctx, hmac_pad, md_block_size) <= 0
520             || EVP_DigestUpdate(md_ctx, mac_out, md_size) <= 0)
521             goto err;
522     }
523     /* TODO(size_t): Convert me */
524     ret = EVP_DigestFinal(md_ctx, md_out, &md_out_size_u);
525     if (ret && md_out_size)
526         *md_out_size = md_out_size_u;
527
528     ret = 1;
529  err:
530     EVP_MD_CTX_free(md_ctx);
531     return ret;
532 }