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