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