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-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief Use OpenSSL to implement AES_CTR.
13 #include "lib/crypt_ops/aes.h"
14 #include "lib/crypt_ops/crypto_util.h"
15 #include "lib/log/util_bug.h"
16 #include "lib/arch/bytes.h"
18 #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
23 #include "lib/crypt_ops/compat_openssl.h"
24 #include <openssl/opensslv.h>
25 #include "lib/crypt_ops/crypto_openssl_mgt.h"
27 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,0,0)
28 #error "We require OpenSSL >= 1.0.0"
31 DISABLE_GCC_WARNING("-Wredundant-decls")
35 #include <openssl/aes.h>
36 #include <openssl/evp.h>
37 #include <openssl/engine.h>
38 #include <openssl/modes.h>
40 ENABLE_GCC_WARNING("-Wredundant-decls")
42 #include "lib/log/log.h"
43 #include "lib/ctime/di_ops.h"
45 #ifdef OPENSSL_NO_ENGINE
46 /* Android's OpenSSL seems to have removed all of its Engine support. */
47 #define DISABLE_ENGINES
50 /* We have five strategies for implementing AES counter mode.
52 * Best with x86 and x86_64: Use EVP_aes_*_ctr() and EVP_EncryptUpdate().
53 * This is possible with OpenSSL 1.0.1, where the counter-mode implementation
54 * can use bit-sliced or vectorized AES or AESNI as appropriate.
56 * Otherwise: Pick the best possible AES block implementation that OpenSSL
57 * gives us, and the best possible counter-mode implementation, and combine
60 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,1,0)
62 /* With newer OpenSSL versions, the older fallback modes don't compile. So
63 * don't use them, even if we lack specific acceleration. */
65 #define USE_EVP_AES_CTR
67 #elif OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,0,1) && \
68 (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
69 defined(__x86_64) || defined(__x86_64__) || \
70 defined(_M_AMD64) || defined(_M_X64) || defined(__INTEL__))
72 #define USE_EVP_AES_CTR
74 #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,1,0) || ... */
76 /* We have 2 strategies for getting the AES block cipher: Via OpenSSL's
77 * AES_encrypt function, or via OpenSSL's EVP_EncryptUpdate function.
79 * If there's any hardware acceleration in play, we want to be using EVP_* so
80 * we can get it. Otherwise, we'll want AES_*, which seems to be about 5%
81 * faster than indirecting through the EVP layer.
84 /* We have 2 strategies for getting a plug-in counter mode: use our own, or
87 * Here we have a counter mode that's faster than the one shipping with
88 * OpenSSL pre-1.0 (by about 10%!). But OpenSSL 1.0.0 added a counter mode
89 * implementation faster than the one here (by about 7%). So we pick which
90 * one to used based on the Openssl version above. (OpenSSL 1.0.0a fixed a
91 * critical bug in that counter mode implementation, so we need to test to
92 * make sure that we have a fixed version.)
95 #ifdef USE_EVP_AES_CTR
97 /* We don't actually define the struct here. */
100 aes_new_cipher(const uint8_t *key
, const uint8_t *iv
, int key_bits
)
102 EVP_CIPHER_CTX
*cipher
= EVP_CIPHER_CTX_new();
103 const EVP_CIPHER
*c
= NULL
;
105 case 128: c
= EVP_aes_128_ctr(); break;
106 case 192: c
= EVP_aes_192_ctr(); break;
107 case 256: c
= EVP_aes_256_ctr(); break;
108 default: tor_assert_unreached(); // LCOV_EXCL_LINE
110 EVP_EncryptInit(cipher
, c
, key
, iv
);
111 return (aes_cnt_cipher_t
*) cipher
;
114 aes_cipher_free_(aes_cnt_cipher_t
*cipher_
)
118 EVP_CIPHER_CTX
*cipher
= (EVP_CIPHER_CTX
*) cipher_
;
119 #ifdef OPENSSL_1_1_API
120 EVP_CIPHER_CTX_reset(cipher
);
122 EVP_CIPHER_CTX_cleanup(cipher
);
124 EVP_CIPHER_CTX_free(cipher
);
127 aes_crypt_inplace(aes_cnt_cipher_t
*cipher_
, char *data
, size_t len
)
130 EVP_CIPHER_CTX
*cipher
= (EVP_CIPHER_CTX
*) cipher_
;
132 tor_assert(len
< INT_MAX
);
134 EVP_EncryptUpdate(cipher
, (unsigned char*)data
,
135 &outl
, (unsigned char*)data
, (int)len
);
138 evaluate_evp_for_aes(int force_val
)
141 log_info(LD_CRYPTO
, "This version of OpenSSL has a known-good EVP "
142 "counter-mode implementation. Using it.");
146 evaluate_ctr_for_aes(void)
150 #else /* !defined(USE_EVP_AES_CTR) */
152 /*======================================================================*/
153 /* Interface to AES code, and counter implementation */
155 /** Implements an AES counter-mode cipher. */
156 struct aes_cnt_cipher_t
{
157 /** This next element (however it's defined) is the AES key. */
163 #if !defined(WORDS_BIGENDIAN)
164 #define USING_COUNTER_VARS
165 /** These four values, together, implement a 128-bit counter, with
166 * counter0 as the low-order word and counter3 as the high-order word. */
171 #endif /* !defined(WORDS_BIGENDIAN) */
174 /** The counter, in big-endian order, as bytes. */
176 /** The counter, in big-endian order, as big-endian words. Note that
177 * on big-endian platforms, this is redundant with counter3...0,
178 * so we just use these values instead. */
182 /** The encrypted value of ctr_buf. */
184 /** Our current stream position within buf. */
187 /** True iff we're using the evp implementation of this cipher. */
191 /** True iff we should prefer the EVP implementation for AES, either because
192 * we're testing it or because we have hardware acceleration configured */
193 static int should_use_EVP
= 0;
195 /** Check whether we should use the EVP interface for AES. If <b>force_val</b>
196 * is nonnegative, we use use EVP iff it is true. Otherwise, we use EVP
197 * if there is an engine enabled for aes-ecb. */
199 evaluate_evp_for_aes(int force_val
)
203 if (force_val
>= 0) {
204 should_use_EVP
= force_val
;
207 #ifdef DISABLE_ENGINES
210 e
= ENGINE_get_cipher_engine(NID_aes_128_ecb
);
213 log_info(LD_CRYPTO
, "AES engine \"%s\" found; using EVP_* functions.",
217 log_info(LD_CRYPTO
, "No AES engine found; using AES_* functions.");
220 #endif /* defined(DISABLE_ENGINES) */
225 /** Test the OpenSSL counter mode implementation to see whether it has the
226 * counter-mode bug from OpenSSL 1.0.0. If the implementation works, then
227 * we will use it for future encryption/decryption operations.
229 * We can't just look at the OpenSSL version, since some distributions update
230 * their OpenSSL packages without changing the version number.
233 evaluate_ctr_for_aes(void)
235 /* Result of encrypting an all-zero block with an all-zero 128-bit AES key.
236 * This should be the same as encrypting an all-zero block with an all-zero
237 * 128-bit AES key in counter mode, starting at position 0 of the stream.
239 static const unsigned char encrypt_zero
[] =
240 "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e";
241 unsigned char zero
[16];
242 unsigned char output
[16];
243 unsigned char ivec
[16];
244 unsigned char ivec_tmp
[16];
247 memset(zero
, 0, sizeof(zero
));
248 memset(ivec
, 0, sizeof(ivec
));
249 AES_set_encrypt_key(zero
, 128, &key
);
252 /* Encrypting a block one byte at a time should make the error manifest
253 * itself for known bogus openssl versions. */
255 AES_ctr128_encrypt(&zero
[i
], &output
[i
], 1, &key
, ivec
, ivec_tmp
, &pos
);
257 if (fast_memneq(output
, encrypt_zero
, 16)) {
258 /* Counter mode is buggy */
259 /* LCOV_EXCL_START */
260 log_err(LD_CRYPTO
, "This OpenSSL has a buggy version of counter mode; "
262 exit(1); // exit ok: openssl is broken.
268 #if !defined(USING_COUNTER_VARS)
269 #define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
271 #define COUNTER(c, n) ((c)->counter ## n)
274 static void aes_set_key(aes_cnt_cipher_t
*cipher
, const uint8_t *key
,
276 static void aes_set_iv(aes_cnt_cipher_t
*cipher
, const uint8_t *iv
);
279 * Return a newly allocated counter-mode AES128 cipher implementation,
280 * using the 128-bit key <b>key</b> and the 128-bit IV <b>iv</b>.
283 aes_new_cipher(const uint8_t *key
, const uint8_t *iv
, int bits
)
285 aes_cnt_cipher_t
* result
= tor_malloc_zero(sizeof(aes_cnt_cipher_t
));
287 aes_set_key(result
, key
, bits
);
288 aes_set_iv(result
, iv
);
293 /** Set the key of <b>cipher</b> to <b>key</b>, which is
294 * <b>key_bits</b> bits long (must be 128, 192, or 256). Also resets
298 aes_set_key(aes_cnt_cipher_t
*cipher
, const uint8_t *key
, int key_bits
)
300 if (should_use_EVP
) {
301 const EVP_CIPHER
*c
= 0;
303 case 128: c
= EVP_aes_128_ecb(); break;
304 case 192: c
= EVP_aes_192_ecb(); break;
305 case 256: c
= EVP_aes_256_ecb(); break;
306 default: tor_assert(0); // LCOV_EXCL_LINE
308 EVP_EncryptInit(&cipher
->key
.evp
, c
, key
, NULL
);
309 cipher
->using_evp
= 1;
311 AES_set_encrypt_key(key
, key_bits
,&cipher
->key
.aes
);
312 cipher
->using_evp
= 0;
315 #ifdef USING_COUNTER_VARS
316 cipher
->counter0
= 0;
317 cipher
->counter1
= 0;
318 cipher
->counter2
= 0;
319 cipher
->counter3
= 0;
320 #endif /* defined(USING_COUNTER_VARS) */
322 memset(cipher
->ctr_buf
.buf
, 0, sizeof(cipher
->ctr_buf
.buf
));
326 memset(cipher
->buf
, 0, sizeof(cipher
->buf
));
329 /** Release storage held by <b>cipher</b>
332 aes_cipher_free_(aes_cnt_cipher_t
*cipher
)
336 if (cipher
->using_evp
) {
337 EVP_CIPHER_CTX_cleanup(&cipher
->key
.evp
);
339 memwipe(cipher
, 0, sizeof(aes_cnt_cipher_t
));
343 #if defined(USING_COUNTER_VARS)
344 #define UPDATE_CTR_BUF(c, n) STMT_BEGIN \
345 (c)->ctr_buf.buf32[3-(n)] = htonl((c)->counter ## n); \
348 #define UPDATE_CTR_BUF(c, n)
349 #endif /* defined(USING_COUNTER_VARS) */
351 /* Helper function to use EVP with openssl's counter-mode wrapper. */
353 evp_block128_fn(const uint8_t in
[16],
357 EVP_CIPHER_CTX
*ctx
= (void*)key
;
359 EVP_EncryptUpdate(ctx
, out
, &outl
, in
, inl
);
362 /** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
363 * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
367 aes_crypt_inplace(aes_cnt_cipher_t
*cipher
, char *data
, size_t len
)
369 /* Note that the "128" below refers to the length of the counter,
370 * not the length of the AES key. */
371 if (cipher
->using_evp
) {
372 /* In openssl 1.0.0, there's an if'd out EVP_aes_128_ctr in evp.h. If
373 * it weren't disabled, it might be better just to use that.
375 CRYPTO_ctr128_encrypt((const unsigned char *)data
,
376 (unsigned char *)data
,
384 AES_ctr128_encrypt((const unsigned char *)data
,
385 (unsigned char *)data
,
394 /** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
397 aes_set_iv(aes_cnt_cipher_t
*cipher
, const uint8_t *iv
)
399 #ifdef USING_COUNTER_VARS
400 cipher
->counter3
= tor_ntohl(get_uint32(iv
));
401 cipher
->counter2
= tor_ntohl(get_uint32(iv
+4));
402 cipher
->counter1
= tor_ntohl(get_uint32(iv
+8));
403 cipher
->counter0
= tor_ntohl(get_uint32(iv
+12));
404 #endif /* defined(USING_COUNTER_VARS) */
406 memcpy(cipher
->ctr_buf
.buf
, iv
, 16);
409 #endif /* defined(USE_EVP_AES_CTR) */