• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <assert.h>
54 #include <string.h>
55 
56 #include <openssl/digest.h>
57 #include <openssl/nid.h>
58 #include <openssl/sha.h>
59 
60 #include "../internal.h"
61 #include "internal.h"
62 
63 
64 /* TODO(davidben): unsigned should be size_t. The various constant_time
65  * functions need to be switched to size_t. */
66 
67 /* MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's length
68  * field. (SHA-384/512 have 128-bit length.) */
69 #define MAX_HASH_BIT_COUNT_BYTES 16
70 
71 /* MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
72  * Currently SHA-384/512 has a 128-byte block size and that's the largest
73  * supported by TLS.) */
74 #define MAX_HASH_BLOCK_SIZE 128
75 
EVP_tls_cbc_remove_padding(unsigned * out_padding_ok,unsigned * out_len,const uint8_t * in,unsigned in_len,unsigned block_size,unsigned mac_size)76 int EVP_tls_cbc_remove_padding(unsigned *out_padding_ok, unsigned *out_len,
77                                const uint8_t *in, unsigned in_len,
78                                unsigned block_size, unsigned mac_size) {
79   unsigned padding_length, good, to_check, i;
80   const unsigned overhead = 1 /* padding length byte */ + mac_size;
81 
82   /* These lengths are all public so we can test them in non-constant time. */
83   if (overhead > in_len) {
84     return 0;
85   }
86 
87   padding_length = in[in_len - 1];
88 
89   good = constant_time_ge(in_len, overhead + padding_length);
90   /* The padding consists of a length byte at the end of the record and
91    * then that many bytes of padding, all with the same value as the
92    * length byte. Thus, with the length byte included, there are i+1
93    * bytes of padding.
94    *
95    * We can't check just |padding_length+1| bytes because that leaks
96    * decrypted information. Therefore we always have to check the maximum
97    * amount of padding possible. (Again, the length of the record is
98    * public information so we can use it.) */
99   to_check = 256; /* maximum amount of padding, inc length byte. */
100   if (to_check > in_len) {
101     to_check = in_len;
102   }
103 
104   for (i = 0; i < to_check; i++) {
105     uint8_t mask = constant_time_ge_8(padding_length, i);
106     uint8_t b = in[in_len - 1 - i];
107     /* The final |padding_length+1| bytes should all have the value
108      * |padding_length|. Therefore the XOR should be zero. */
109     good &= ~(mask & (padding_length ^ b));
110   }
111 
112   /* If any of the final |padding_length+1| bytes had the wrong value,
113    * one or more of the lower eight bits of |good| will be cleared. */
114   good = constant_time_eq(0xff, good & 0xff);
115 
116   /* Always treat |padding_length| as zero on error. If, assuming block size of
117    * 16, a padding of [<15 arbitrary bytes> 15] treated |padding_length| as 16
118    * and returned -1, distinguishing good MAC and bad padding from bad MAC and
119    * bad padding would give POODLE's padding oracle. */
120   padding_length = good & (padding_length + 1);
121   *out_len = in_len - padding_length;
122   *out_padding_ok = good;
123   return 1;
124 }
125 
EVP_tls_cbc_copy_mac(uint8_t * out,unsigned md_size,const uint8_t * in,unsigned in_len,unsigned orig_len)126 void EVP_tls_cbc_copy_mac(uint8_t *out, unsigned md_size,
127                           const uint8_t *in, unsigned in_len,
128                           unsigned orig_len) {
129   uint8_t rotated_mac1[EVP_MAX_MD_SIZE], rotated_mac2[EVP_MAX_MD_SIZE];
130   uint8_t *rotated_mac = rotated_mac1;
131   uint8_t *rotated_mac_tmp = rotated_mac2;
132 
133   /* mac_end is the index of |in| just after the end of the MAC. */
134   unsigned mac_end = in_len;
135   unsigned mac_start = mac_end - md_size;
136 
137   assert(orig_len >= in_len);
138   assert(in_len >= md_size);
139   assert(md_size <= EVP_MAX_MD_SIZE);
140 
141   /* scan_start contains the number of bytes that we can ignore because
142    * the MAC's position can only vary by 255 bytes. */
143   unsigned scan_start = 0;
144   /* This information is public so it's safe to branch based on it. */
145   if (orig_len > md_size + 255 + 1) {
146     scan_start = orig_len - (md_size + 255 + 1);
147   }
148 
149   unsigned rotate_offset = 0;
150   uint8_t mac_started = 0;
151   OPENSSL_memset(rotated_mac, 0, md_size);
152   for (unsigned i = scan_start, j = 0; i < orig_len; i++, j++) {
153     if (j >= md_size) {
154       j -= md_size;
155     }
156     unsigned is_mac_start = constant_time_eq(i, mac_start);
157     mac_started |= is_mac_start;
158     uint8_t mac_ended = constant_time_ge_8(i, mac_end);
159     rotated_mac[j] |= in[i] & mac_started & ~mac_ended;
160     /* Save the offset that |mac_start| is mapped to. */
161     rotate_offset |= j & is_mac_start;
162   }
163 
164   /* Now rotate the MAC. We rotate in log(md_size) steps, one for each bit
165    * position. */
166   for (unsigned offset = 1; offset < md_size;
167        offset <<= 1, rotate_offset >>= 1) {
168     /* Rotate by |offset| iff the corresponding bit is set in
169      * |rotate_offset|, placing the result in |rotated_mac_tmp|. */
170     const uint8_t skip_rotate = (rotate_offset & 1) - 1;
171     for (unsigned i = 0, j = offset; i < md_size; i++, j++) {
172       if (j >= md_size) {
173         j -= md_size;
174       }
175       rotated_mac_tmp[i] =
176           constant_time_select_8(skip_rotate, rotated_mac[i], rotated_mac[j]);
177     }
178 
179     /* Swap pointers so |rotated_mac| contains the (possibly) rotated value.
180      * Note the number of iterations and thus the identity of these pointers is
181      * public information. */
182     uint8_t *tmp = rotated_mac;
183     rotated_mac = rotated_mac_tmp;
184     rotated_mac_tmp = tmp;
185   }
186 
187   OPENSSL_memcpy(out, rotated_mac, md_size);
188 }
189 
190 /* u32toBE serialises an unsigned, 32-bit number (n) as four bytes at (p) in
191  * big-endian order. The value of p is advanced by four. */
192 #define u32toBE(n, p)                \
193   do {                               \
194     *((p)++) = (uint8_t)((n) >> 24); \
195     *((p)++) = (uint8_t)((n) >> 16); \
196     *((p)++) = (uint8_t)((n) >> 8);  \
197     *((p)++) = (uint8_t)((n));       \
198   } while (0)
199 
200 /* u64toBE serialises an unsigned, 64-bit number (n) as eight bytes at (p) in
201  * big-endian order. The value of p is advanced by eight. */
202 #define u64toBE(n, p)                \
203   do {                               \
204     *((p)++) = (uint8_t)((n) >> 56); \
205     *((p)++) = (uint8_t)((n) >> 48); \
206     *((p)++) = (uint8_t)((n) >> 40); \
207     *((p)++) = (uint8_t)((n) >> 32); \
208     *((p)++) = (uint8_t)((n) >> 24); \
209     *((p)++) = (uint8_t)((n) >> 16); \
210     *((p)++) = (uint8_t)((n) >> 8);  \
211     *((p)++) = (uint8_t)((n));       \
212   } while (0)
213 
214 /* These functions serialize the state of a hash and thus perform the standard
215  * "final" operation without adding the padding and length that such a function
216  * typically does. */
tls1_sha1_final_raw(void * ctx,uint8_t * md_out)217 static void tls1_sha1_final_raw(void *ctx, uint8_t *md_out) {
218   SHA_CTX *sha1 = ctx;
219   u32toBE(sha1->h[0], md_out);
220   u32toBE(sha1->h[1], md_out);
221   u32toBE(sha1->h[2], md_out);
222   u32toBE(sha1->h[3], md_out);
223   u32toBE(sha1->h[4], md_out);
224 }
225 #define LARGEST_DIGEST_CTX SHA_CTX
226 
tls1_sha256_final_raw(void * ctx,uint8_t * md_out)227 static void tls1_sha256_final_raw(void *ctx, uint8_t *md_out) {
228   SHA256_CTX *sha256 = ctx;
229   unsigned i;
230 
231   for (i = 0; i < 8; i++) {
232     u32toBE(sha256->h[i], md_out);
233   }
234 }
235 #undef  LARGEST_DIGEST_CTX
236 #define LARGEST_DIGEST_CTX SHA256_CTX
237 
tls1_sha512_final_raw(void * ctx,uint8_t * md_out)238 static void tls1_sha512_final_raw(void *ctx, uint8_t *md_out) {
239   SHA512_CTX *sha512 = ctx;
240   unsigned i;
241 
242   for (i = 0; i < 8; i++) {
243     u64toBE(sha512->h[i], md_out);
244   }
245 }
246 #undef  LARGEST_DIGEST_CTX
247 #define LARGEST_DIGEST_CTX SHA512_CTX
248 
EVP_tls_cbc_record_digest_supported(const EVP_MD * md)249 int EVP_tls_cbc_record_digest_supported(const EVP_MD *md) {
250   switch (EVP_MD_type(md)) {
251     case NID_sha1:
252     case NID_sha256:
253     case NID_sha384:
254       return 1;
255 
256     default:
257       return 0;
258   }
259 }
260 
EVP_tls_cbc_digest_record(const EVP_MD * md,uint8_t * md_out,size_t * md_out_size,const uint8_t header[13],const uint8_t * data,size_t data_plus_mac_size,size_t data_plus_mac_plus_padding_size,const uint8_t * mac_secret,unsigned mac_secret_length)261 int EVP_tls_cbc_digest_record(const EVP_MD *md, uint8_t *md_out,
262                               size_t *md_out_size, const uint8_t header[13],
263                               const uint8_t *data, size_t data_plus_mac_size,
264                               size_t data_plus_mac_plus_padding_size,
265                               const uint8_t *mac_secret,
266                               unsigned mac_secret_length) {
267   union {
268     double align;
269     uint8_t c[sizeof(LARGEST_DIGEST_CTX)];
270   } md_state;
271   void (*md_final_raw)(void *ctx, uint8_t *md_out);
272   void (*md_transform)(void *ctx, const uint8_t *block);
273   unsigned md_size, md_block_size = 64;
274   unsigned len, max_mac_bytes, num_blocks, num_starting_blocks, k,
275            mac_end_offset, c, index_a, index_b;
276   unsigned int bits; /* at most 18 bits */
277   uint8_t length_bytes[MAX_HASH_BIT_COUNT_BYTES];
278   /* hmac_pad is the masked HMAC key. */
279   uint8_t hmac_pad[MAX_HASH_BLOCK_SIZE];
280   uint8_t first_block[MAX_HASH_BLOCK_SIZE];
281   uint8_t mac_out[EVP_MAX_MD_SIZE];
282   unsigned i, j, md_out_size_u;
283   EVP_MD_CTX md_ctx;
284   /* mdLengthSize is the number of bytes in the length field that terminates
285   * the hash. */
286   unsigned md_length_size = 8;
287 
288   /* This is a, hopefully redundant, check that allows us to forget about
289    * many possible overflows later in this function. */
290   assert(data_plus_mac_plus_padding_size < 1024 * 1024);
291 
292   switch (EVP_MD_type(md)) {
293     case NID_sha1:
294       SHA1_Init((SHA_CTX *)md_state.c);
295       md_final_raw = tls1_sha1_final_raw;
296       md_transform =
297           (void (*)(void *ctx, const uint8_t *block))SHA1_Transform;
298       md_size = 20;
299       break;
300 
301     case NID_sha256:
302       SHA256_Init((SHA256_CTX *)md_state.c);
303       md_final_raw = tls1_sha256_final_raw;
304       md_transform =
305           (void (*)(void *ctx, const uint8_t *block))SHA256_Transform;
306       md_size = 32;
307       break;
308 
309     case NID_sha384:
310       SHA384_Init((SHA512_CTX *)md_state.c);
311       md_final_raw = tls1_sha512_final_raw;
312       md_transform =
313           (void (*)(void *ctx, const uint8_t *block))SHA512_Transform;
314       md_size = 384 / 8;
315       md_block_size = 128;
316       md_length_size = 16;
317       break;
318 
319     default:
320       /* EVP_tls_cbc_record_digest_supported should have been called first to
321        * check that the hash function is supported. */
322       assert(0);
323       *md_out_size = 0;
324       return 0;
325   }
326 
327   assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES);
328   assert(md_block_size <= MAX_HASH_BLOCK_SIZE);
329   assert(md_size <= EVP_MAX_MD_SIZE);
330 
331   static const unsigned kHeaderLength = 13;
332 
333   /* kVarianceBlocks is the number of blocks of the hash that we have to
334    * calculate in constant time because they could be altered by the
335    * padding value.
336    *
337    * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
338    * required to be minimal. Therefore we say that the final six blocks
339    * can vary based on the padding. */
340   static const unsigned kVarianceBlocks = 6;
341 
342   /* From now on we're dealing with the MAC, which conceptually has 13
343    * bytes of `header' before the start of the data. */
344   len = data_plus_mac_plus_padding_size + kHeaderLength;
345   /* max_mac_bytes contains the maximum bytes of bytes in the MAC, including
346   * |header|, assuming that there's no padding. */
347   max_mac_bytes = len - md_size - 1;
348   /* num_blocks is the maximum number of hash blocks. */
349   num_blocks =
350       (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size;
351   /* In order to calculate the MAC in constant time we have to handle
352    * the final blocks specially because the padding value could cause the
353    * end to appear somewhere in the final |kVarianceBlocks| blocks and we
354    * can't leak where. However, |num_starting_blocks| worth of data can
355    * be hashed right away because no padding value can affect whether
356    * they are plaintext. */
357   num_starting_blocks = 0;
358   /* k is the starting byte offset into the conceptual header||data where
359    * we start processing. */
360   k = 0;
361   /* mac_end_offset is the index just past the end of the data to be
362    * MACed. */
363   mac_end_offset = data_plus_mac_size + kHeaderLength - md_size;
364   /* c is the index of the 0x80 byte in the final hash block that
365    * contains application data. */
366   c = mac_end_offset % md_block_size;
367   /* index_a is the hash block number that contains the 0x80 terminating
368    * value. */
369   index_a = mac_end_offset / md_block_size;
370   /* index_b is the hash block number that contains the 64-bit hash
371    * length, in bits. */
372   index_b = (mac_end_offset + md_length_size) / md_block_size;
373   /* bits is the hash-length in bits. It includes the additional hash
374    * block for the masked HMAC key. */
375 
376   if (num_blocks > kVarianceBlocks) {
377     num_starting_blocks = num_blocks - kVarianceBlocks;
378     k = md_block_size * num_starting_blocks;
379   }
380 
381   bits = 8 * mac_end_offset;
382 
383   /* Compute the initial HMAC block. */
384   bits += 8 * md_block_size;
385   OPENSSL_memset(hmac_pad, 0, md_block_size);
386   assert(mac_secret_length <= sizeof(hmac_pad));
387   OPENSSL_memcpy(hmac_pad, mac_secret, mac_secret_length);
388   for (i = 0; i < md_block_size; i++) {
389     hmac_pad[i] ^= 0x36;
390   }
391 
392   md_transform(md_state.c, hmac_pad);
393 
394   OPENSSL_memset(length_bytes, 0, md_length_size - 4);
395   length_bytes[md_length_size - 4] = (uint8_t)(bits >> 24);
396   length_bytes[md_length_size - 3] = (uint8_t)(bits >> 16);
397   length_bytes[md_length_size - 2] = (uint8_t)(bits >> 8);
398   length_bytes[md_length_size - 1] = (uint8_t)bits;
399 
400   if (k > 0) {
401     /* k is a multiple of md_block_size. */
402     OPENSSL_memcpy(first_block, header, 13);
403     OPENSSL_memcpy(first_block + 13, data, md_block_size - 13);
404     md_transform(md_state.c, first_block);
405     for (i = 1; i < k / md_block_size; i++) {
406       md_transform(md_state.c, data + md_block_size * i - 13);
407     }
408   }
409 
410   OPENSSL_memset(mac_out, 0, sizeof(mac_out));
411 
412   /* We now process the final hash blocks. For each block, we construct
413    * it in constant time. If the |i==index_a| then we'll include the 0x80
414    * bytes and zero pad etc. For each block we selectively copy it, in
415    * constant time, to |mac_out|. */
416   for (i = num_starting_blocks; i <= num_starting_blocks + kVarianceBlocks;
417        i++) {
418     uint8_t block[MAX_HASH_BLOCK_SIZE];
419     uint8_t is_block_a = constant_time_eq_8(i, index_a);
420     uint8_t is_block_b = constant_time_eq_8(i, index_b);
421     for (j = 0; j < md_block_size; j++) {
422       uint8_t b = 0, is_past_c, is_past_cp1;
423       if (k < kHeaderLength) {
424         b = header[k];
425       } else if (k < data_plus_mac_plus_padding_size + kHeaderLength) {
426         b = data[k - kHeaderLength];
427       }
428       k++;
429 
430       is_past_c = is_block_a & constant_time_ge_8(j, c);
431       is_past_cp1 = is_block_a & constant_time_ge_8(j, c + 1);
432       /* If this is the block containing the end of the
433        * application data, and we are at the offset for the
434        * 0x80 value, then overwrite b with 0x80. */
435       b = constant_time_select_8(is_past_c, 0x80, b);
436       /* If this the the block containing the end of the
437        * application data and we're past the 0x80 value then
438        * just write zero. */
439       b = b & ~is_past_cp1;
440       /* If this is index_b (the final block), but not
441        * index_a (the end of the data), then the 64-bit
442        * length didn't fit into index_a and we're having to
443        * add an extra block of zeros. */
444       b &= ~is_block_b | is_block_a;
445 
446       /* The final bytes of one of the blocks contains the
447        * length. */
448       if (j >= md_block_size - md_length_size) {
449         /* If this is index_b, write a length byte. */
450         b = constant_time_select_8(
451             is_block_b, length_bytes[j - (md_block_size - 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 
464   EVP_MD_CTX_init(&md_ctx);
465   if (!EVP_DigestInit_ex(&md_ctx, md, NULL /* engine */)) {
466     EVP_MD_CTX_cleanup(&md_ctx);
467     return 0;
468   }
469 
470   /* Complete the HMAC in the standard manner. */
471   for (i = 0; i < md_block_size; i++) {
472     hmac_pad[i] ^= 0x6a;
473   }
474 
475   EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size);
476   EVP_DigestUpdate(&md_ctx, mac_out, md_size);
477   EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u);
478   *md_out_size = md_out_size_u;
479   EVP_MD_CTX_cleanup(&md_ctx);
480 
481   return 1;
482 }
483