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 */
9 * \brief Implements a counter-mode stream cipher on top of AES.
14 #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
16 #define _WIN32_WINNT 0x0501
18 #define WIN32_LEAN_AND_MEAN
19 #if defined(_MSC_VER) && (_MSC_VER < 1300)
27 #include <openssl/opensslv.h>
31 #include <openssl/aes.h>
32 #include <openssl/evp.h>
33 #include <openssl/engine.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
47 /* Android's OpenSSL seems to have removed all of its Engine support. */
48 #define DISABLE_ENGINES
51 /* We have five strategies for implementing AES counter mode.
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.
57 * Otherwise: Pick the best possible AES block implementation that OpenSSL
58 * gives us, and the best possible counter-mode implementation, and combine
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__)) \
66 #define USE_EVP_AES_CTR
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.
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.
78 /* We have 2 strategies for getting a plug-in counter mode: use our own, or
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.)
89 #ifdef USE_EVP_AES_CTR
91 struct aes_cnt_cipher
{
96 aes_new_cipher(const char *key
, const char *iv
)
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
);
105 aes_cipher_free(aes_cnt_cipher_t
*cipher
)
109 EVP_CIPHER_CTX_cleanup(&cipher
->evp
);
110 memwipe(cipher
, 0, sizeof(aes_cnt_cipher_t
));
114 aes_crypt(aes_cnt_cipher_t
*cipher
, const char *input
, size_t len
,
119 tor_assert(len
< INT_MAX
);
121 EVP_EncryptUpdate(&cipher
->evp
, (unsigned char*)output
,
122 &outl
, (const unsigned char *)input
, (int)len
);
125 aes_crypt_inplace(aes_cnt_cipher_t
*cipher
, char *data
, size_t len
)
129 tor_assert(len
< INT_MAX
);
131 EVP_EncryptUpdate(&cipher
->evp
, (unsigned char*)data
,
132 &outl
, (unsigned char*)data
, (int)len
);
135 evaluate_evp_for_aes(int force_val
)
138 log_info(LD_CRYPTO
, "This version of OpenSSL has a known-good EVP "
139 "counter-mode implementation. Using it.");
143 evaluate_ctr_for_aes(void)
149 /*======================================================================*/
150 /* Interface to AES code, and counter implementation */
152 /** Implements an AES counter-mode cipher. */
153 struct aes_cnt_cipher
{
154 /** This next element (however it's defined) is the AES key. */
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. */
171 /** The counter, in big-endian order, as bytes. */
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. */
179 /** The encrypted value of ctr_buf. */
181 /** Our current stream position within buf. */
184 /** True iff we're using the evp implementation of this cipher. */
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;
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;
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. */
202 evaluate_evp_for_aes(int force_val
)
206 if (force_val
>= 0) {
207 should_use_EVP
= force_val
;
210 #ifdef DISABLE_ENGINES
213 e
= ENGINE_get_cipher_engine(NID_aes_128_ecb
);
216 log_info(LD_CRYPTO
, "AES engine \"%s\" found; using EVP_* functions.",
220 log_info(LD_CRYPTO
, "No AES engine found; using AES_* functions.");
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.
232 * We can't just look at the OpenSSL version, since some distributions update
233 * their OpenSSL packages without changing the version number.
236 evaluate_ctr_for_aes(void)
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.
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];
251 memset(zero
, 0, sizeof(zero
));
252 memset(ivec
, 0, sizeof(ivec
));
253 AES_set_encrypt_key(zero
, 128, &key
);
256 /* Encrypting a block one byte at a time should make the error manifest
257 * itself for known bogus openssl versions. */
259 AES_ctr128_encrypt(&zero
[i
], &output
[i
], 1, &key
, ivec
, ivec_tmp
, &pos
);
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; "
266 /* Counter mode is okay */
267 log_info(LD_CRYPTO
, "This OpenSSL has a good implementation of counter "
269 should_use_openssl_CTR
= 1;
272 log_info(LD_CRYPTO
, "This version of OpenSSL has a slow implementation of "
273 "counter mode; not using it.");
278 #if !defined(USING_COUNTER_VARS)
279 #define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
281 #define COUNTER(c, n) ((c)->counter ## n)
285 * Helper function: set <b>cipher</b>'s internal buffer to the encrypted
286 * value of the current counter.
289 aes_fill_buf_(aes_cnt_cipher_t
*cipher
)
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.
298 if (cipher
->using_evp
) {
300 EVP_EncryptUpdate(&cipher
->key
.evp
, cipher
->buf
, &outl
,
301 cipher
->ctr_buf
.buf
, inl
);
303 AES_encrypt(cipher
->ctr_buf
.buf
, cipher
->buf
, &cipher
->key
.aes
);
307 static void aes_set_key(aes_cnt_cipher_t
*cipher
, const char *key
,
309 static void aes_set_iv(aes_cnt_cipher_t
*cipher
, const char *iv
);
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>.
316 aes_new_cipher(const char *key
, const char *iv
)
318 aes_cnt_cipher_t
* result
= tor_malloc_zero(sizeof(aes_cnt_cipher_t
));
320 aes_set_key(result
, key
, 128);
321 aes_set_iv(result
, iv
);
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
331 aes_set_key(aes_cnt_cipher_t
*cipher
, const char *key
, int key_bits
)
333 if (should_use_EVP
) {
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);
341 EVP_EncryptInit(&cipher
->key
.evp
, c
, (const unsigned char*)key
, NULL
);
342 cipher
->using_evp
= 1;
344 AES_set_encrypt_key((const unsigned char *)key
, key_bits
,&cipher
->key
.aes
);
345 cipher
->using_evp
= 0;
348 #ifdef USING_COUNTER_VARS
349 cipher
->counter0
= 0;
350 cipher
->counter1
= 0;
351 cipher
->counter2
= 0;
352 cipher
->counter3
= 0;
355 memset(cipher
->ctr_buf
.buf
, 0, sizeof(cipher
->ctr_buf
.buf
));
359 #ifdef CAN_USE_OPENSSL_CTR
360 if (should_use_openssl_CTR
)
361 memset(cipher
->buf
, 0, sizeof(cipher
->buf
));
364 aes_fill_buf_(cipher
);
367 /** Release storage held by <b>cipher</b>
370 aes_cipher_free(aes_cnt_cipher_t
*cipher
)
374 if (cipher
->using_evp
) {
375 EVP_CIPHER_CTX_cleanup(&cipher
->key
.evp
);
377 memwipe(cipher
, 0, sizeof(aes_cnt_cipher_t
));
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); \
386 #define UPDATE_CTR_BUF(c, n)
389 #ifdef CAN_USE_OPENSSL_CTR
390 /* Helper function to use EVP with openssl's counter-mode wrapper. */
392 evp_block128_fn(const uint8_t in
[16],
396 EVP_CIPHER_CTX
*ctx
= (void*)key
;
398 EVP_EncryptUpdate(ctx
, out
, &outl
, in
, inl
);
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.
407 aes_crypt(aes_cnt_cipher_t
*cipher
, const char *input
, size_t len
,
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.
416 CRYPTO_ctr128_encrypt((const unsigned char *)input
,
417 (unsigned char *)output
,
425 AES_ctr128_encrypt((const unsigned char *)input
,
426 (unsigned char *)output
,
438 if (PREDICT_UNLIKELY(!len
)) return;
442 if (len
-- == 0) { cipher
->pos
= c
; return; }
443 *(output
++) = *(input
++) ^ cipher
->buf
[c
];
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);
452 UPDATE_CTR_BUF(cipher
, 2);
454 UPDATE_CTR_BUF(cipher
, 1);
456 UPDATE_CTR_BUF(cipher
, 0);
457 aes_fill_buf_(cipher
);
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
467 aes_crypt_inplace(aes_cnt_cipher_t
*cipher
, char *data
, size_t len
)
469 #ifdef CAN_USE_OPENSSL_CTR
470 if (should_use_openssl_CTR
) {
471 aes_crypt(cipher
, data
, len
, data
);
477 if (PREDICT_UNLIKELY(!len
)) return;
481 if (len
-- == 0) { cipher
->pos
= c
; return; }
482 *(data
++) ^= cipher
->buf
[c
];
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);
491 UPDATE_CTR_BUF(cipher
, 2);
493 UPDATE_CTR_BUF(cipher
, 1);
495 UPDATE_CTR_BUF(cipher
, 0);
496 aes_fill_buf_(cipher
);
501 /** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
504 aes_set_iv(aes_cnt_cipher_t
*cipher
, const char *iv
)
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));
513 memcpy(cipher
->ctr_buf
.buf
, iv
, 16);
515 #ifdef CAN_USE_OPENSSL_CTR
516 if (!should_use_openssl_CTR
)
518 aes_fill_buf_(cipher
);