Merge remote-tracking branch 'public/bug9963_v2_024'
[tor.git] / src / common / aes.c
1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6
7 /**
8 * \file aes.c
9 * \brief Implements a counter-mode stream cipher on top of AES.
10 **/
11
12 #include "orconfig.h"
13
14 #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
15 #ifndef _WIN32_WINNT
16 #define _WIN32_WINNT 0x0501
17 #endif
18 #define WIN32_LEAN_AND_MEAN
19 #if defined(_MSC_VER) && (_MSC_VER < 1300)
20 #include <winsock.h>
21 #else
22 #include <winsock2.h>
23 #include <ws2tcpip.h>
24 #endif
25 #endif
26
27 #include <openssl/opensslv.h>
28 #include <assert.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <openssl/aes.h>
32 #include <openssl/evp.h>
33 #include <openssl/engine.h>
34 #include "crypto.h"
35 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0)
36 /* See comments about which counter mode implementation to use below. */
37 #include <openssl/modes.h>
38 #define CAN_USE_OPENSSL_CTR
39 #endif
40 #include "compat.h"
41 #include "aes.h"
42 #include "util.h"
43 #include "torlog.h"
44 #include "di_ops.h"
45
46 #ifdef ANDROID
47 /* Android's OpenSSL seems to have removed all of its Engine support. */
48 #define DISABLE_ENGINES
49 #endif
50
51 /* We have five strategies for implementing AES counter mode.
52 *
53 * Best with x86 and x86_64: Use EVP_aes_ctr128() and EVP_EncryptUpdate().
54 * This is possible with OpenSSL 1.0.1, where the counter-mode implementation
55 * can use bit-sliced or vectorized AES or AESNI as appropriate.
56 *
57 * Otherwise: Pick the best possible AES block implementation that OpenSSL
58 * gives us, and the best possible counter-mode implementation, and combine
59 * them.
60 */
61 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,0,1) && \
62 (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
63 defined(__x86_64) || defined(__x86_64__) || \
64 defined(_M_AMD64) || defined(_M_X64) || defined(__INTEL__)) \
65
66 #define USE_EVP_AES_CTR
67
68 #endif
69
70 /* We have 2 strategies for getting the AES block cipher: Via OpenSSL's
71 * AES_encrypt function, or via OpenSSL's EVP_EncryptUpdate function.
72 *
73 * If there's any hardware acceleration in play, we want to be using EVP_* so
74 * we can get it. Otherwise, we'll want AES_*, which seems to be about 5%
75 * faster than indirecting through the EVP layer.
76 */
77
78 /* We have 2 strategies for getting a plug-in counter mode: use our own, or
79 * use OpenSSL's.
80 *
81 * Here we have a counter mode that's faster than the one shipping with
82 * OpenSSL pre-1.0 (by about 10%!). But OpenSSL 1.0.0 added a counter mode
83 * implementation faster than the one here (by about 7%). So we pick which
84 * one to used based on the Openssl version above. (OpenSSL 1.0.0a fixed a
85 * critical bug in that counter mode implementation, so we need to test to
86 * make sure that we have a fixed version.)
87 */
88
89 #ifdef USE_EVP_AES_CTR
90
91 struct aes_cnt_cipher {
92 EVP_CIPHER_CTX evp;
93 };
94
95 aes_cnt_cipher_t *
96 aes_new_cipher(const char *key, const char *iv)
97 {
98 aes_cnt_cipher_t *cipher;
99 cipher = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
100 EVP_EncryptInit(&cipher->evp, EVP_aes_128_ctr(),
101 (const unsigned char*)key, (const unsigned char *)iv);
102 return cipher;
103 }
104 void
105 aes_cipher_free(aes_cnt_cipher_t *cipher)
106 {
107 if (!cipher)
108 return;
109 EVP_CIPHER_CTX_cleanup(&cipher->evp);
110 memwipe(cipher, 0, sizeof(aes_cnt_cipher_t));
111 tor_free(cipher);
112 }
113 void
114 aes_crypt(aes_cnt_cipher_t *cipher, const char *input, size_t len,
115 char *output)
116 {
117 int outl;
118
119 tor_assert(len < INT_MAX);
120
121 EVP_EncryptUpdate(&cipher->evp, (unsigned char*)output,
122 &outl, (const unsigned char *)input, (int)len);
123 }
124 void
125 aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
126 {
127 int outl;
128
129 tor_assert(len < INT_MAX);
130
131 EVP_EncryptUpdate(&cipher->evp, (unsigned char*)data,
132 &outl, (unsigned char*)data, (int)len);
133 }
134 int
135 evaluate_evp_for_aes(int force_val)
136 {
137 (void) force_val;
138 log_info(LD_CRYPTO, "This version of OpenSSL has a known-good EVP "
139 "counter-mode implementation. Using it.");
140 return 0;
141 }
142 int
143 evaluate_ctr_for_aes(void)
144 {
145 return 0;
146 }
147 #else
148
149 /*======================================================================*/
150 /* Interface to AES code, and counter implementation */
151
152 /** Implements an AES counter-mode cipher. */
153 struct aes_cnt_cipher {
154 /** This next element (however it's defined) is the AES key. */
155 union {
156 EVP_CIPHER_CTX evp;
157 AES_KEY aes;
158 } key;
159
160 #if !defined(WORDS_BIGENDIAN)
161 #define USING_COUNTER_VARS
162 /** These four values, together, implement a 128-bit counter, with
163 * counter0 as the low-order word and counter3 as the high-order word. */
164 uint32_t counter3;
165 uint32_t counter2;
166 uint32_t counter1;
167 uint32_t counter0;
168 #endif
169
170 union {
171 /** The counter, in big-endian order, as bytes. */
172 uint8_t buf[16];
173 /** The counter, in big-endian order, as big-endian words. Note that
174 * on big-endian platforms, this is redundant with counter3...0,
175 * so we just use these values instead. */
176 uint32_t buf32[4];
177 } ctr_buf;
178
179 /** The encrypted value of ctr_buf. */
180 uint8_t buf[16];
181 /** Our current stream position within buf. */
182 unsigned int pos;
183
184 /** True iff we're using the evp implementation of this cipher. */
185 uint8_t using_evp;
186 };
187
188 /** True iff we should prefer the EVP implementation for AES, either because
189 * we're testing it or because we have hardware acceleration configured */
190 static int should_use_EVP = 0;
191
192 #ifdef CAN_USE_OPENSSL_CTR
193 /** True iff we have tested the counter-mode implementation and found that it
194 * doesn't have the counter-mode bug from OpenSSL 1.0.0. */
195 static int should_use_openssl_CTR = 0;
196 #endif
197
198 /** Check whether we should use the EVP interface for AES. If <b>force_val</b>
199 * is nonnegative, we use use EVP iff it is true. Otherwise, we use EVP
200 * if there is an engine enabled for aes-ecb. */
201 int
202 evaluate_evp_for_aes(int force_val)
203 {
204 ENGINE *e;
205
206 if (force_val >= 0) {
207 should_use_EVP = force_val;
208 return 0;
209 }
210 #ifdef DISABLE_ENGINES
211 should_use_EVP = 0;
212 #else
213 e = ENGINE_get_cipher_engine(NID_aes_128_ecb);
214
215 if (e) {
216 log_info(LD_CRYPTO, "AES engine \"%s\" found; using EVP_* functions.",
217 ENGINE_get_name(e));
218 should_use_EVP = 1;
219 } else {
220 log_info(LD_CRYPTO, "No AES engine found; using AES_* functions.");
221 should_use_EVP = 0;
222 }
223 #endif
224
225 return 0;
226 }
227
228 /** Test the OpenSSL counter mode implementation to see whether it has the
229 * counter-mode bug from OpenSSL 1.0.0. If the implementation works, then
230 * we will use it for future encryption/decryption operations.
231 *
232 * We can't just look at the OpenSSL version, since some distributions update
233 * their OpenSSL packages without changing the version number.
234 **/
235 int
236 evaluate_ctr_for_aes(void)
237 {
238 #ifdef CAN_USE_OPENSSL_CTR
239 /* Result of encrypting an all-zero block with an all-zero 128-bit AES key.
240 * This should be the same as encrypting an all-zero block with an all-zero
241 * 128-bit AES key in counter mode, starting at position 0 of the stream.
242 */
243 static const unsigned char encrypt_zero[] =
244 "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e";
245 unsigned char zero[16];
246 unsigned char output[16];
247 unsigned char ivec[16];
248 unsigned char ivec_tmp[16];
249 unsigned int pos, i;
250 AES_KEY key;
251 memset(zero, 0, sizeof(zero));
252 memset(ivec, 0, sizeof(ivec));
253 AES_set_encrypt_key(zero, 128, &key);
254
255 pos = 0;
256 /* Encrypting a block one byte at a time should make the error manifest
257 * itself for known bogus openssl versions. */
258 for (i=0; i<16; ++i)
259 AES_ctr128_encrypt(&zero[i], &output[i], 1, &key, ivec, ivec_tmp, &pos);
260
261 if (fast_memneq(output, encrypt_zero, 16)) {
262 /* Counter mode is buggy */
263 log_notice(LD_CRYPTO, "This OpenSSL has a buggy version of counter mode; "
264 "not using it.");
265 } else {
266 /* Counter mode is okay */
267 log_info(LD_CRYPTO, "This OpenSSL has a good implementation of counter "
268 "mode; using it.");
269 should_use_openssl_CTR = 1;
270 }
271 #else
272 log_info(LD_CRYPTO, "This version of OpenSSL has a slow implementation of "
273 "counter mode; not using it.");
274 #endif
275 return 0;
276 }
277
278 #if !defined(USING_COUNTER_VARS)
279 #define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
280 #else
281 #define COUNTER(c, n) ((c)->counter ## n)
282 #endif
283
284 /**
285 * Helper function: set <b>cipher</b>'s internal buffer to the encrypted
286 * value of the current counter.
287 */
288 static INLINE void
289 aes_fill_buf_(aes_cnt_cipher_t *cipher)
290 {
291 /* We don't currently use OpenSSL's counter mode implementation because:
292 * 1) some versions have known bugs
293 * 2) its attitude towards IVs is not our own
294 * 3) changing the counter position was not trivial, last time I looked.
295 * None of these issues are insurmountable in principle.
296 */
297
298 if (cipher->using_evp) {
299 int outl=16, inl=16;
300 EVP_EncryptUpdate(&cipher->key.evp, cipher->buf, &outl,
301 cipher->ctr_buf.buf, inl);
302 } else {
303 AES_encrypt(cipher->ctr_buf.buf, cipher->buf, &cipher->key.aes);
304 }
305 }
306
307 static void aes_set_key(aes_cnt_cipher_t *cipher, const char *key,
308 int key_bits);
309 static void aes_set_iv(aes_cnt_cipher_t *cipher, const char *iv);
310
311 /**
312 * Return a newly allocated counter-mode AES128 cipher implementation,
313 * using the 128-bit key <b>key</b> and the 128-bit IV <b>iv</b>.
314 */
315 aes_cnt_cipher_t*
316 aes_new_cipher(const char *key, const char *iv)
317 {
318 aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
319
320 aes_set_key(result, key, 128);
321 aes_set_iv(result, iv);
322
323 return result;
324 }
325
326 /** Set the key of <b>cipher</b> to <b>key</b>, which is
327 * <b>key_bits</b> bits long (must be 128, 192, or 256). Also resets
328 * the counter to 0.
329 */
330 static void
331 aes_set_key(aes_cnt_cipher_t *cipher, const char *key, int key_bits)
332 {
333 if (should_use_EVP) {
334 const EVP_CIPHER *c;
335 switch (key_bits) {
336 case 128: c = EVP_aes_128_ecb(); break;
337 case 192: c = EVP_aes_192_ecb(); break;
338 case 256: c = EVP_aes_256_ecb(); break;
339 default: tor_assert(0);
340 }
341 EVP_EncryptInit(&cipher->key.evp, c, (const unsigned char*)key, NULL);
342 cipher->using_evp = 1;
343 } else {
344 AES_set_encrypt_key((const unsigned char *)key, key_bits,&cipher->key.aes);
345 cipher->using_evp = 0;
346 }
347
348 #ifdef USING_COUNTER_VARS
349 cipher->counter0 = 0;
350 cipher->counter1 = 0;
351 cipher->counter2 = 0;
352 cipher->counter3 = 0;
353 #endif
354
355 memset(cipher->ctr_buf.buf, 0, sizeof(cipher->ctr_buf.buf));
356
357 cipher->pos = 0;
358
359 #ifdef CAN_USE_OPENSSL_CTR
360 if (should_use_openssl_CTR)
361 memset(cipher->buf, 0, sizeof(cipher->buf));
362 else
363 #endif
364 aes_fill_buf_(cipher);
365 }
366
367 /** Release storage held by <b>cipher</b>
368 */
369 void
370 aes_cipher_free(aes_cnt_cipher_t *cipher)
371 {
372 if (!cipher)
373 return;
374 if (cipher->using_evp) {
375 EVP_CIPHER_CTX_cleanup(&cipher->key.evp);
376 }
377 memwipe(cipher, 0, sizeof(aes_cnt_cipher_t));
378 tor_free(cipher);
379 }
380
381 #if defined(USING_COUNTER_VARS)
382 #define UPDATE_CTR_BUF(c, n) STMT_BEGIN \
383 (c)->ctr_buf.buf32[3-(n)] = htonl((c)->counter ## n); \
384 STMT_END
385 #else
386 #define UPDATE_CTR_BUF(c, n)
387 #endif
388
389 #ifdef CAN_USE_OPENSSL_CTR
390 /* Helper function to use EVP with openssl's counter-mode wrapper. */
391 static void
392 evp_block128_fn(const uint8_t in[16],
393 uint8_t out[16],
394 const void *key)
395 {
396 EVP_CIPHER_CTX *ctx = (void*)key;
397 int inl=16, outl=16;
398 EVP_EncryptUpdate(ctx, out, &outl, in, inl);
399 }
400 #endif
401
402 /** Encrypt <b>len</b> bytes from <b>input</b>, storing the result in
403 * <b>output</b>. Uses the key in <b>cipher</b>, and advances the counter
404 * by <b>len</b> bytes as it encrypts.
405 */
406 void
407 aes_crypt(aes_cnt_cipher_t *cipher, const char *input, size_t len,
408 char *output)
409 {
410 #ifdef CAN_USE_OPENSSL_CTR
411 if (should_use_openssl_CTR) {
412 if (cipher->using_evp) {
413 /* In openssl 1.0.0, there's an if'd out EVP_aes_128_ctr in evp.h. If
414 * it weren't disabled, it might be better just to use that.
415 */
416 CRYPTO_ctr128_encrypt((const unsigned char *)input,
417 (unsigned char *)output,
418 len,
419 &cipher->key.evp,
420 cipher->ctr_buf.buf,
421 cipher->buf,
422 &cipher->pos,
423 evp_block128_fn);
424 } else {
425 AES_ctr128_encrypt((const unsigned char *)input,
426 (unsigned char *)output,
427 len,
428 &cipher->key.aes,
429 cipher->ctr_buf.buf,
430 cipher->buf,
431 &cipher->pos);
432 }
433 return;
434 } else
435 #endif
436 {
437 int c = cipher->pos;
438 if (PREDICT_UNLIKELY(!len)) return;
439
440 while (1) {
441 do {
442 if (len-- == 0) { cipher->pos = c; return; }
443 *(output++) = *(input++) ^ cipher->buf[c];
444 } while (++c != 16);
445 cipher->pos = c = 0;
446 if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
447 if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
448 if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
449 ++COUNTER(cipher, 3);
450 UPDATE_CTR_BUF(cipher, 3);
451 }
452 UPDATE_CTR_BUF(cipher, 2);
453 }
454 UPDATE_CTR_BUF(cipher, 1);
455 }
456 UPDATE_CTR_BUF(cipher, 0);
457 aes_fill_buf_(cipher);
458 }
459 }
460 }
461
462 /** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
463 * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
464 * as it encrypts.
465 */
466 void
467 aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
468 {
469 #ifdef CAN_USE_OPENSSL_CTR
470 if (should_use_openssl_CTR) {
471 aes_crypt(cipher, data, len, data);
472 return;
473 } else
474 #endif
475 {
476 int c = cipher->pos;
477 if (PREDICT_UNLIKELY(!len)) return;
478
479 while (1) {
480 do {
481 if (len-- == 0) { cipher->pos = c; return; }
482 *(data++) ^= cipher->buf[c];
483 } while (++c != 16);
484 cipher->pos = c = 0;
485 if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
486 if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
487 if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
488 ++COUNTER(cipher, 3);
489 UPDATE_CTR_BUF(cipher, 3);
490 }
491 UPDATE_CTR_BUF(cipher, 2);
492 }
493 UPDATE_CTR_BUF(cipher, 1);
494 }
495 UPDATE_CTR_BUF(cipher, 0);
496 aes_fill_buf_(cipher);
497 }
498 }
499 }
500
501 /** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
502 * in <b>iv</b>. */
503 static void
504 aes_set_iv(aes_cnt_cipher_t *cipher, const char *iv)
505 {
506 #ifdef USING_COUNTER_VARS
507 cipher->counter3 = ntohl(get_uint32(iv));
508 cipher->counter2 = ntohl(get_uint32(iv+4));
509 cipher->counter1 = ntohl(get_uint32(iv+8));
510 cipher->counter0 = ntohl(get_uint32(iv+12));
511 #endif
512 cipher->pos = 0;
513 memcpy(cipher->ctr_buf.buf, iv, 16);
514
515 #ifdef CAN_USE_OPENSSL_CTR
516 if (!should_use_openssl_CTR)
517 #endif
518 aes_fill_buf_(cipher);
519 }
520
521 #endif
522