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