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