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