TLS: remove legacy code path supporting special CBC mode
[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 #ifndef OPENSSL_NO_DEPRECATED_3_0
35 int ssl3_cbc_digest_record(const EVP_MD *md,
36                            unsigned char *md_out,
37                            size_t *md_out_size,
38                            const unsigned char header[13],
39                            const unsigned char *data,
40                            size_t data_size,
41                            size_t data_plus_mac_plus_padding_size,
42                            const unsigned char *mac_secret,
43                            size_t mac_secret_length, char is_sslv3);
44
45 # define l2n(l,c)        (*((c)++)=(unsigned char)(((l)>>24)&0xff), \
46                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
47                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
48                          *((c)++)=(unsigned char)(((l)    )&0xff))
49
50 # define l2n6(l,c)       (*((c)++)=(unsigned char)(((l)>>40)&0xff), \
51                          *((c)++)=(unsigned char)(((l)>>32)&0xff), \
52                          *((c)++)=(unsigned char)(((l)>>24)&0xff), \
53                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
54                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
55                          *((c)++)=(unsigned char)(((l)    )&0xff))
56
57 # define l2n8(l,c)       (*((c)++)=(unsigned char)(((l)>>56)&0xff), \
58                          *((c)++)=(unsigned char)(((l)>>48)&0xff), \
59                          *((c)++)=(unsigned char)(((l)>>40)&0xff), \
60                          *((c)++)=(unsigned char)(((l)>>32)&0xff), \
61                          *((c)++)=(unsigned char)(((l)>>24)&0xff), \
62                          *((c)++)=(unsigned char)(((l)>>16)&0xff), \
63                          *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
64                          *((c)++)=(unsigned char)(((l)    )&0xff))
65
66 /*
67  * MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's
68  * length field. (SHA-384/512 have 128-bit length.)
69  */
70 #define MAX_HASH_BIT_COUNT_BYTES 16
71
72 /*
73  * MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
74  * Currently SHA-384/512 has a 128-byte block size and that's the largest
75  * supported by TLS.)
76  */
77 #define MAX_HASH_BLOCK_SIZE 128
78
79 /*
80  * u32toLE serializes an unsigned, 32-bit number (n) as four bytes at (p) in
81  * little-endian order. The value of p is advanced by four.
82  */
83 #define u32toLE(n, p) \
84         (*((p)++)=(unsigned char)(n), \
85          *((p)++)=(unsigned char)(n>>8), \
86          *((p)++)=(unsigned char)(n>>16), \
87          *((p)++)=(unsigned char)(n>>24))
88
89 /*
90  * These functions serialize the state of a hash and thus perform the
91  * standard "final" operation without adding the padding and length that such
92  * a function typically does.
93  */
94 static void tls1_md5_final_raw(void *ctx, unsigned char *md_out)
95 {
96     MD5_CTX *md5 = ctx;
97     u32toLE(md5->A, md_out);
98     u32toLE(md5->B, md_out);
99     u32toLE(md5->C, md_out);
100     u32toLE(md5->D, md_out);
101 }
102
103 static void tls1_sha1_final_raw(void *ctx, unsigned char *md_out)
104 {
105     SHA_CTX *sha1 = ctx;
106     l2n(sha1->h0, md_out);
107     l2n(sha1->h1, md_out);
108     l2n(sha1->h2, md_out);
109     l2n(sha1->h3, md_out);
110     l2n(sha1->h4, md_out);
111 }
112
113 static void tls1_sha256_final_raw(void *ctx, unsigned char *md_out)
114 {
115     SHA256_CTX *sha256 = ctx;
116     unsigned i;
117
118     for (i = 0; i < 8; i++) {
119         l2n(sha256->h[i], md_out);
120     }
121 }
122
123 static void tls1_sha512_final_raw(void *ctx, unsigned char *md_out)
124 {
125     SHA512_CTX *sha512 = ctx;
126     unsigned i;
127
128     for (i = 0; i < 8; i++) {
129         l2n8(sha512->h[i], md_out);
130     }
131 }
132 #endif
133
134 #undef  LARGEST_DIGEST_CTX
135 #define LARGEST_DIGEST_CTX SHA512_CTX
136
137 /*
138  * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
139  * which ssl3_cbc_digest_record supports.
140  */
141 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
142 {
143     switch (EVP_MD_CTX_type(ctx)) {
144     case NID_md5:
145     case NID_sha1:
146     case NID_sha224:
147     case NID_sha256:
148     case NID_sha384:
149     case NID_sha512:
150         return 1;
151     default:
152         return 0;
153     }
154 }
155
156 #ifndef OPENSSL_NO_DEPRECATED_3_0
157 /*-
158  * ssl3_cbc_digest_record computes the MAC of a decrypted, padded SSLv3/TLS
159  * record.
160  *
161  *   ctx: the EVP_MD_CTX from which we take the hash function.
162  *     ssl3_cbc_record_digest_supported must return true for this EVP_MD_CTX.
163  *   md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
164  *   md_out_size: if non-NULL, the number of output bytes is written here.
165  *   header: the 13-byte, TLS record header.
166  *   data: the record data itself, less any preceding explicit IV.
167  *   data_size: the secret, reported length of the data once the MAC and padding
168  *              has been removed.
169  *   data_plus_mac_plus_padding_size: the public length of the whole
170  *     record, including MAC and padding.
171  *   is_sslv3: non-zero if we are to use SSLv3. Otherwise, TLS.
172  *
173  * On entry: we know that data is data_plus_mac_plus_padding_size in length
174  * Returns 1 on success or 0 on error
175  */
176 int ssl3_cbc_digest_record(const EVP_MD *md,
177                            unsigned char *md_out,
178                            size_t *md_out_size,
179                            const unsigned char header[13],
180                            const unsigned char *data,
181                            size_t data_size,
182                            size_t data_plus_mac_plus_padding_size,
183                            const unsigned char *mac_secret,
184                            size_t mac_secret_length, char is_sslv3)
185 {
186     union {
187         OSSL_UNION_ALIGN;
188         unsigned char c[sizeof(LARGEST_DIGEST_CTX)];
189     } md_state;
190     void (*md_final_raw) (void *ctx, unsigned char *md_out);
191     void (*md_transform) (void *ctx, const unsigned char *block);
192     size_t md_size, md_block_size = 64;
193     size_t sslv3_pad_length = 40, header_length, variance_blocks,
194         len, max_mac_bytes, num_blocks,
195         num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
196     size_t bits;          /* at most 18 bits */
197     unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
198     /* hmac_pad is the masked HMAC key. */
199     unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
200     unsigned char first_block[MAX_HASH_BLOCK_SIZE];
201     unsigned char mac_out[EVP_MAX_MD_SIZE];
202     size_t i, j;
203     unsigned md_out_size_u;
204     EVP_MD_CTX *md_ctx = NULL;
205     /*
206      * mdLengthSize is the number of bytes in the length field that
207      * terminates * the hash.
208      */
209     size_t md_length_size = 8;
210     char length_is_big_endian = 1;
211     int ret = 0;
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     if (!ossl_assert(data_plus_mac_plus_padding_size < 1024 * 1024))
218         return 0;
219
220     if (EVP_MD_is_a(md, "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     } else if (EVP_MD_is_a(md, "SHA1")) {
230         if (SHA1_Init((SHA_CTX *)md_state.c) <= 0)
231             return 0;
232         md_final_raw = tls1_sha1_final_raw;
233         md_transform =
234             (void (*)(void *ctx, const unsigned char *block))SHA1_Transform;
235         md_size = 20;
236     } else if (EVP_MD_is_a(md, "SHA2-224")) {
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      } else if (EVP_MD_is_a(md, "SHA2-256")) {
244         if (SHA256_Init((SHA256_CTX *)md_state.c) <= 0)
245             return 0;
246         md_final_raw = tls1_sha256_final_raw;
247         md_transform =
248             (void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
249         md_size = 32;
250      } else if (EVP_MD_is_a(md, "SHA2-384")) {
251         if (SHA384_Init((SHA512_CTX *)md_state.c) <= 0)
252             return 0;
253         md_final_raw = tls1_sha512_final_raw;
254         md_transform =
255             (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
256         md_size = 384 / 8;
257         md_block_size = 128;
258         md_length_size = 16;
259     } else if (EVP_MD_is_a(md, "SHA2-512")) {
260         if (SHA512_Init((SHA512_CTX *)md_state.c) <= 0)
261             return 0;
262         md_final_raw = tls1_sha512_final_raw;
263         md_transform =
264             (void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
265         md_size = 64;
266         md_block_size = 128;
267         md_length_size = 16;
268     } else {
269         /*
270          * ssl3_cbc_record_digest_supported should have been called first to
271          * check that the hash function is supported.
272          */
273         if (md_out_size != NULL)
274             *md_out_size = 0;
275         return ossl_assert(0);
276     }
277
278     if (!ossl_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES)
279             || !ossl_assert(md_block_size <= MAX_HASH_BLOCK_SIZE)
280             || !ossl_assert(md_size <= EVP_MAX_MD_SIZE))
281         return 0;
282
283     header_length = 13;
284     if (is_sslv3) {
285         header_length = mac_secret_length + sslv3_pad_length + 8 /* sequence
286                                                                   * number */  +
287             1 /* record type */  +
288             2 /* record length */ ;
289     }
290
291     /*
292      * variance_blocks is the number of blocks of the hash that we have to
293      * calculate in constant time because they could be altered by the
294      * padding value. In SSLv3, the padding must be minimal so the end of
295      * the plaintext varies by, at most, 15+20 = 35 bytes. (We conservatively
296      * assume that the MAC size varies from 0..20 bytes.) In case the 9 bytes
297      * of hash termination (0x80 + 64-bit length) don't fit in the final
298      * block, we say that the final two blocks can vary based on the padding.
299      * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
300      * required to be minimal. Therefore we say that the final |variance_blocks|
301      * blocks can
302      * vary based on the padding. Later in the function, if the message is
303      * short and there obviously cannot be this many blocks then
304      * variance_blocks can be reduced.
305      */
306     variance_blocks = is_sslv3 ? 2 : ( ((255 + 1 + md_size + md_block_size - 1) / md_block_size) + 1);
307     /*
308      * From now on we're dealing with the MAC, which conceptually has 13
309      * bytes of `header' before the start of the data (TLS) or 71/75 bytes
310      * (SSLv3)
311      */
312     len = data_plus_mac_plus_padding_size + header_length;
313     /*
314      * max_mac_bytes contains the maximum bytes of bytes in the MAC,
315      * including * |header|, assuming that there's no padding.
316      */
317     max_mac_bytes = len - md_size - 1;
318     /* num_blocks is the maximum number of hash blocks. */
319     num_blocks =
320         (max_mac_bytes + 1 + md_length_size + md_block_size -
321          1) / md_block_size;
322     /*
323      * In order to calculate the MAC in constant time we have to handle the
324      * final blocks specially because the padding value could cause the end
325      * to appear somewhere in the final |variance_blocks| blocks and we can't
326      * leak where. However, |num_starting_blocks| worth of data can be hashed
327      * right away because no padding value can affect whether they are
328      * plaintext.
329      */
330     num_starting_blocks = 0;
331     /*
332      * k is the starting byte offset into the conceptual header||data where
333      * we start processing.
334      */
335     k = 0;
336     /*
337      * mac_end_offset is the index just past the end of the data to be MACed.
338      */
339     mac_end_offset = data_size + header_length;
340     /*
341      * c is the index of the 0x80 byte in the final hash block that contains
342      * application data.
343      */
344     c = mac_end_offset % md_block_size;
345     /*
346      * index_a is the hash block number that contains the 0x80 terminating
347      * value.
348      */
349     index_a = mac_end_offset / md_block_size;
350     /*
351      * index_b is the hash block number that contains the 64-bit hash length,
352      * in bits.
353      */
354     index_b = (mac_end_offset + md_length_size) / md_block_size;
355     /*
356      * bits is the hash-length in bits. It includes the additional hash block
357      * for the masked HMAC key, or whole of |header| in the case of SSLv3.
358      */
359
360     /*
361      * For SSLv3, if we're going to have any starting blocks then we need at
362      * least two because the header is larger than a single block.
363      */
364     if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) {
365         num_starting_blocks = num_blocks - variance_blocks;
366         k = md_block_size * num_starting_blocks;
367     }
368
369     bits = 8 * mac_end_offset;
370     if (!is_sslv3) {
371         /*
372          * Compute the initial HMAC block. For SSLv3, the padding and secret
373          * bytes are included in |header| because they take more than a
374          * single block.
375          */
376         bits += 8 * md_block_size;
377         memset(hmac_pad, 0, md_block_size);
378         if (!ossl_assert(mac_secret_length <= sizeof(hmac_pad)))
379             return 0;
380         memcpy(hmac_pad, mac_secret, mac_secret_length);
381         for (i = 0; i < md_block_size; i++)
382             hmac_pad[i] ^= 0x36;
383
384         md_transform(md_state.c, hmac_pad);
385     }
386
387     if (length_is_big_endian) {
388         memset(length_bytes, 0, md_length_size - 4);
389         length_bytes[md_length_size - 4] = (unsigned char)(bits >> 24);
390         length_bytes[md_length_size - 3] = (unsigned char)(bits >> 16);
391         length_bytes[md_length_size - 2] = (unsigned char)(bits >> 8);
392         length_bytes[md_length_size - 1] = (unsigned char)bits;
393     } else {
394         memset(length_bytes, 0, md_length_size);
395         length_bytes[md_length_size - 5] = (unsigned char)(bits >> 24);
396         length_bytes[md_length_size - 6] = (unsigned char)(bits >> 16);
397         length_bytes[md_length_size - 7] = (unsigned char)(bits >> 8);
398         length_bytes[md_length_size - 8] = (unsigned char)bits;
399     }
400
401     if (k > 0) {
402         if (is_sslv3) {
403             size_t overhang;
404
405             /*
406              * The SSLv3 header is larger than a single block. overhang is
407              * the number of bytes beyond a single block that the header
408              * consumes: either 7 bytes (SHA1) or 11 bytes (MD5). There are no
409              * ciphersuites in SSLv3 that are not SHA1 or MD5 based and
410              * therefore we can be confident that the header_length will be
411              * greater than |md_block_size|. However we add a sanity check just
412              * in case
413              */
414             if (header_length <= md_block_size) {
415                 /* Should never happen */
416                 return 0;
417             }
418             overhang = header_length - md_block_size;
419             md_transform(md_state.c, header);
420             memcpy(first_block, header + md_block_size, overhang);
421             memcpy(first_block + overhang, data, md_block_size - overhang);
422             md_transform(md_state.c, first_block);
423             for (i = 1; i < k / md_block_size - 1; i++)
424                 md_transform(md_state.c, data + md_block_size * i - overhang);
425         } else {
426             /* k is a multiple of md_block_size. */
427             memcpy(first_block, header, 13);
428             memcpy(first_block + 13, data, md_block_size - 13);
429             md_transform(md_state.c, first_block);
430             for (i = 1; i < k / md_block_size; i++)
431                 md_transform(md_state.c, data + md_block_size * i - 13);
432         }
433     }
434
435     memset(mac_out, 0, sizeof(mac_out));
436
437     /*
438      * We now process the final hash blocks. For each block, we construct it
439      * in constant time. If the |i==index_a| then we'll include the 0x80
440      * bytes and zero pad etc. For each block we selectively copy it, in
441      * constant time, to |mac_out|.
442      */
443     for (i = num_starting_blocks; i <= num_starting_blocks + variance_blocks;
444          i++) {
445         unsigned char block[MAX_HASH_BLOCK_SIZE];
446         unsigned char is_block_a = constant_time_eq_8_s(i, index_a);
447         unsigned char is_block_b = constant_time_eq_8_s(i, index_b);
448         for (j = 0; j < md_block_size; j++) {
449             unsigned char b = 0, is_past_c, is_past_cp1;
450             if (k < header_length)
451                 b = header[k];
452             else if (k < data_plus_mac_plus_padding_size + header_length)
453                 b = data[k - header_length];
454             k++;
455
456             is_past_c = is_block_a & constant_time_ge_8_s(j, c);
457             is_past_cp1 = is_block_a & constant_time_ge_8_s(j, c + 1);
458             /*
459              * If this is the block containing the end of the application
460              * data, and we are at the offset for the 0x80 value, then
461              * overwrite b with 0x80.
462              */
463             b = constant_time_select_8(is_past_c, 0x80, b);
464             /*
465              * If this block contains the end of the application data
466              * and we're past the 0x80 value then just write zero.
467              */
468             b = b & ~is_past_cp1;
469             /*
470              * If this is index_b (the final block), but not index_a (the end
471              * of the data), then the 64-bit length didn't fit into index_a
472              * and we're having to add an extra block of zeros.
473              */
474             b &= ~is_block_b | is_block_a;
475
476             /*
477              * The final bytes of one of the blocks contains the length.
478              */
479             if (j >= md_block_size - md_length_size) {
480                 /* If this is index_b, write a length byte. */
481                 b = constant_time_select_8(is_block_b,
482                                            length_bytes[j -
483                                                         (md_block_size -
484                                                          md_length_size)], b);
485             }
486             block[j] = b;
487         }
488
489         md_transform(md_state.c, block);
490         md_final_raw(md_state.c, block);
491         /* If this is index_b, copy the hash value to |mac_out|. */
492         for (j = 0; j < md_size; j++)
493             mac_out[j] |= block[j] & is_block_b;
494     }
495
496     md_ctx = EVP_MD_CTX_new();
497     if (md_ctx == NULL)
498         goto err;
499
500     if (EVP_DigestInit_ex(md_ctx, md, NULL /* engine */ ) <= 0)
501         goto err;
502     if (is_sslv3) {
503         /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */
504         memset(hmac_pad, 0x5c, sslv3_pad_length);
505
506         if (EVP_DigestUpdate(md_ctx, mac_secret, mac_secret_length) <= 0
507             || EVP_DigestUpdate(md_ctx, hmac_pad, sslv3_pad_length) <= 0
508             || EVP_DigestUpdate(md_ctx, mac_out, md_size) <= 0)
509             goto err;
510     } else {
511         /* Complete the HMAC in the standard manner. */
512         for (i = 0; i < md_block_size; i++)
513             hmac_pad[i] ^= 0x6a;
514
515         if (EVP_DigestUpdate(md_ctx, hmac_pad, md_block_size) <= 0
516             || EVP_DigestUpdate(md_ctx, mac_out, md_size) <= 0)
517             goto err;
518     }
519     /* TODO(size_t): Convert me */
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
524     ret = 1;
525  err:
526     EVP_MD_CTX_free(md_ctx);
527     return ret;
528 }
529 #endif