aes_openssl.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file aes_openssl.c
  8. * \brief Use OpenSSL to implement AES_CTR.
  9. **/
  10. #include "orconfig.h"
  11. #include "lib/crypt_ops/aes.h"
  12. #include "lib/crypt_ops/crypto_util.h"
  13. #include "lib/log/util_bug.h"
  14. #include "lib/arch/bytes.h"
  15. #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
  16. #include <winsock2.h>
  17. #include <ws2tcpip.h>
  18. #endif
  19. #include "lib/crypt_ops/compat_openssl.h"
  20. #include <openssl/opensslv.h>
  21. #include "lib/crypt_ops/crypto_openssl_mgt.h"
  22. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,0,0)
  23. #error "We require OpenSSL >= 1.0.0"
  24. #endif
  25. DISABLE_GCC_WARNING(redundant-decls)
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <openssl/aes.h>
  29. #include <openssl/evp.h>
  30. #include <openssl/engine.h>
  31. #include <openssl/modes.h>
  32. ENABLE_GCC_WARNING(redundant-decls)
  33. #include "lib/crypt_ops/aes.h"
  34. #include "lib/log/log.h"
  35. #include "lib/ctime/di_ops.h"
  36. #ifdef OPENSSL_NO_ENGINE
  37. /* Android's OpenSSL seems to have removed all of its Engine support. */
  38. #define DISABLE_ENGINES
  39. #endif
  40. /* We have five strategies for implementing AES counter mode.
  41. *
  42. * Best with x86 and x86_64: Use EVP_aes_*_ctr() and EVP_EncryptUpdate().
  43. * This is possible with OpenSSL 1.0.1, where the counter-mode implementation
  44. * can use bit-sliced or vectorized AES or AESNI as appropriate.
  45. *
  46. * Otherwise: Pick the best possible AES block implementation that OpenSSL
  47. * gives us, and the best possible counter-mode implementation, and combine
  48. * them.
  49. */
  50. #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,1,0)
  51. /* With newer OpenSSL versions, the older fallback modes don't compile. So
  52. * don't use them, even if we lack specific acceleration. */
  53. #define USE_EVP_AES_CTR
  54. #elif OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,0,1) && \
  55. (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
  56. defined(__x86_64) || defined(__x86_64__) || \
  57. defined(_M_AMD64) || defined(_M_X64) || defined(__INTEL__))
  58. #define USE_EVP_AES_CTR
  59. #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,1,0) || ... */
  60. /* We have 2 strategies for getting the AES block cipher: Via OpenSSL's
  61. * AES_encrypt function, or via OpenSSL's EVP_EncryptUpdate function.
  62. *
  63. * If there's any hardware acceleration in play, we want to be using EVP_* so
  64. * we can get it. Otherwise, we'll want AES_*, which seems to be about 5%
  65. * faster than indirecting through the EVP layer.
  66. */
  67. /* We have 2 strategies for getting a plug-in counter mode: use our own, or
  68. * use OpenSSL's.
  69. *
  70. * Here we have a counter mode that's faster than the one shipping with
  71. * OpenSSL pre-1.0 (by about 10%!). But OpenSSL 1.0.0 added a counter mode
  72. * implementation faster than the one here (by about 7%). So we pick which
  73. * one to used based on the Openssl version above. (OpenSSL 1.0.0a fixed a
  74. * critical bug in that counter mode implementation, so we need to test to
  75. * make sure that we have a fixed version.)
  76. */
  77. #ifdef USE_EVP_AES_CTR
  78. /* We don't actually define the struct here. */
  79. aes_cnt_cipher_t *
  80. aes_new_cipher(const uint8_t *key, const uint8_t *iv, int key_bits)
  81. {
  82. EVP_CIPHER_CTX *cipher = EVP_CIPHER_CTX_new();
  83. const EVP_CIPHER *c = NULL;
  84. switch (key_bits) {
  85. case 128: c = EVP_aes_128_ctr(); break;
  86. case 192: c = EVP_aes_192_ctr(); break;
  87. case 256: c = EVP_aes_256_ctr(); break;
  88. default: tor_assert_unreached(); // LCOV_EXCL_LINE
  89. }
  90. EVP_EncryptInit(cipher, c, key, iv);
  91. return (aes_cnt_cipher_t *) cipher;
  92. }
  93. void
  94. aes_cipher_free_(aes_cnt_cipher_t *cipher_)
  95. {
  96. if (!cipher_)
  97. return;
  98. EVP_CIPHER_CTX *cipher = (EVP_CIPHER_CTX *) cipher_;
  99. #ifdef OPENSSL_1_1_API
  100. EVP_CIPHER_CTX_reset(cipher);
  101. #else
  102. EVP_CIPHER_CTX_cleanup(cipher);
  103. #endif
  104. EVP_CIPHER_CTX_free(cipher);
  105. }
  106. void
  107. aes_crypt_inplace(aes_cnt_cipher_t *cipher_, char *data, size_t len)
  108. {
  109. int outl;
  110. EVP_CIPHER_CTX *cipher = (EVP_CIPHER_CTX *) cipher_;
  111. tor_assert(len < INT_MAX);
  112. EVP_EncryptUpdate(cipher, (unsigned char*)data,
  113. &outl, (unsigned char*)data, (int)len);
  114. }
  115. int
  116. evaluate_evp_for_aes(int force_val)
  117. {
  118. (void) force_val;
  119. log_info(LD_CRYPTO, "This version of OpenSSL has a known-good EVP "
  120. "counter-mode implementation. Using it.");
  121. return 0;
  122. }
  123. int
  124. evaluate_ctr_for_aes(void)
  125. {
  126. return 0;
  127. }
  128. #else /* !(defined(USE_EVP_AES_CTR)) */
  129. /*======================================================================*/
  130. /* Interface to AES code, and counter implementation */
  131. /** Implements an AES counter-mode cipher. */
  132. struct aes_cnt_cipher {
  133. /** This next element (however it's defined) is the AES key. */
  134. union {
  135. EVP_CIPHER_CTX evp;
  136. AES_KEY aes;
  137. } key;
  138. #if !defined(WORDS_BIGENDIAN)
  139. #define USING_COUNTER_VARS
  140. /** These four values, together, implement a 128-bit counter, with
  141. * counter0 as the low-order word and counter3 as the high-order word. */
  142. uint32_t counter3;
  143. uint32_t counter2;
  144. uint32_t counter1;
  145. uint32_t counter0;
  146. #endif /* !defined(WORDS_BIGENDIAN) */
  147. union {
  148. /** The counter, in big-endian order, as bytes. */
  149. uint8_t buf[16];
  150. /** The counter, in big-endian order, as big-endian words. Note that
  151. * on big-endian platforms, this is redundant with counter3...0,
  152. * so we just use these values instead. */
  153. uint32_t buf32[4];
  154. } ctr_buf;
  155. /** The encrypted value of ctr_buf. */
  156. uint8_t buf[16];
  157. /** Our current stream position within buf. */
  158. unsigned int pos;
  159. /** True iff we're using the evp implementation of this cipher. */
  160. uint8_t using_evp;
  161. };
  162. /** True iff we should prefer the EVP implementation for AES, either because
  163. * we're testing it or because we have hardware acceleration configured */
  164. static int should_use_EVP = 0;
  165. /** Check whether we should use the EVP interface for AES. If <b>force_val</b>
  166. * is nonnegative, we use use EVP iff it is true. Otherwise, we use EVP
  167. * if there is an engine enabled for aes-ecb. */
  168. int
  169. evaluate_evp_for_aes(int force_val)
  170. {
  171. ENGINE *e;
  172. if (force_val >= 0) {
  173. should_use_EVP = force_val;
  174. return 0;
  175. }
  176. #ifdef DISABLE_ENGINES
  177. should_use_EVP = 0;
  178. #else
  179. e = ENGINE_get_cipher_engine(NID_aes_128_ecb);
  180. if (e) {
  181. log_info(LD_CRYPTO, "AES engine \"%s\" found; using EVP_* functions.",
  182. ENGINE_get_name(e));
  183. should_use_EVP = 1;
  184. } else {
  185. log_info(LD_CRYPTO, "No AES engine found; using AES_* functions.");
  186. should_use_EVP = 0;
  187. }
  188. #endif /* defined(DISABLE_ENGINES) */
  189. return 0;
  190. }
  191. /** Test the OpenSSL counter mode implementation to see whether it has the
  192. * counter-mode bug from OpenSSL 1.0.0. If the implementation works, then
  193. * we will use it for future encryption/decryption operations.
  194. *
  195. * We can't just look at the OpenSSL version, since some distributions update
  196. * their OpenSSL packages without changing the version number.
  197. **/
  198. int
  199. evaluate_ctr_for_aes(void)
  200. {
  201. /* Result of encrypting an all-zero block with an all-zero 128-bit AES key.
  202. * This should be the same as encrypting an all-zero block with an all-zero
  203. * 128-bit AES key in counter mode, starting at position 0 of the stream.
  204. */
  205. static const unsigned char encrypt_zero[] =
  206. "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e";
  207. unsigned char zero[16];
  208. unsigned char output[16];
  209. unsigned char ivec[16];
  210. unsigned char ivec_tmp[16];
  211. unsigned int pos, i;
  212. AES_KEY key;
  213. memset(zero, 0, sizeof(zero));
  214. memset(ivec, 0, sizeof(ivec));
  215. AES_set_encrypt_key(zero, 128, &key);
  216. pos = 0;
  217. /* Encrypting a block one byte at a time should make the error manifest
  218. * itself for known bogus openssl versions. */
  219. for (i=0; i<16; ++i)
  220. AES_ctr128_encrypt(&zero[i], &output[i], 1, &key, ivec, ivec_tmp, &pos);
  221. if (fast_memneq(output, encrypt_zero, 16)) {
  222. /* Counter mode is buggy */
  223. /* LCOV_EXCL_START */
  224. log_err(LD_CRYPTO, "This OpenSSL has a buggy version of counter mode; "
  225. "quitting tor.");
  226. exit(1); // exit ok: openssl is broken.
  227. /* LCOV_EXCL_STOP */
  228. }
  229. return 0;
  230. }
  231. #if !defined(USING_COUNTER_VARS)
  232. #define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
  233. #else
  234. #define COUNTER(c, n) ((c)->counter ## n)
  235. #endif
  236. static void aes_set_key(aes_cnt_cipher_t *cipher, const uint8_t *key,
  237. int key_bits);
  238. static void aes_set_iv(aes_cnt_cipher_t *cipher, const uint8_t *iv);
  239. /**
  240. * Return a newly allocated counter-mode AES128 cipher implementation,
  241. * using the 128-bit key <b>key</b> and the 128-bit IV <b>iv</b>.
  242. */
  243. aes_cnt_cipher_t*
  244. aes_new_cipher(const uint8_t *key, const uint8_t *iv, int bits)
  245. {
  246. aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
  247. aes_set_key(result, key, bits);
  248. aes_set_iv(result, iv);
  249. return result;
  250. }
  251. /** Set the key of <b>cipher</b> to <b>key</b>, which is
  252. * <b>key_bits</b> bits long (must be 128, 192, or 256). Also resets
  253. * the counter to 0.
  254. */
  255. static void
  256. aes_set_key(aes_cnt_cipher_t *cipher, const uint8_t *key, int key_bits)
  257. {
  258. if (should_use_EVP) {
  259. const EVP_CIPHER *c = 0;
  260. switch (key_bits) {
  261. case 128: c = EVP_aes_128_ecb(); break;
  262. case 192: c = EVP_aes_192_ecb(); break;
  263. case 256: c = EVP_aes_256_ecb(); break;
  264. default: tor_assert(0); // LCOV_EXCL_LINE
  265. }
  266. EVP_EncryptInit(&cipher->key.evp, c, key, NULL);
  267. cipher->using_evp = 1;
  268. } else {
  269. AES_set_encrypt_key(key, key_bits,&cipher->key.aes);
  270. cipher->using_evp = 0;
  271. }
  272. #ifdef USING_COUNTER_VARS
  273. cipher->counter0 = 0;
  274. cipher->counter1 = 0;
  275. cipher->counter2 = 0;
  276. cipher->counter3 = 0;
  277. #endif /* defined(USING_COUNTER_VARS) */
  278. memset(cipher->ctr_buf.buf, 0, sizeof(cipher->ctr_buf.buf));
  279. cipher->pos = 0;
  280. memset(cipher->buf, 0, sizeof(cipher->buf));
  281. }
  282. /** Release storage held by <b>cipher</b>
  283. */
  284. void
  285. aes_cipher_free_(aes_cnt_cipher_t *cipher)
  286. {
  287. if (!cipher)
  288. return;
  289. if (cipher->using_evp) {
  290. EVP_CIPHER_CTX_cleanup(&cipher->key.evp);
  291. }
  292. memwipe(cipher, 0, sizeof(aes_cnt_cipher_t));
  293. tor_free(cipher);
  294. }
  295. #if defined(USING_COUNTER_VARS)
  296. #define UPDATE_CTR_BUF(c, n) STMT_BEGIN \
  297. (c)->ctr_buf.buf32[3-(n)] = htonl((c)->counter ## n); \
  298. STMT_END
  299. #else
  300. #define UPDATE_CTR_BUF(c, n)
  301. #endif /* defined(USING_COUNTER_VARS) */
  302. /* Helper function to use EVP with openssl's counter-mode wrapper. */
  303. static void
  304. evp_block128_fn(const uint8_t in[16],
  305. uint8_t out[16],
  306. const void *key)
  307. {
  308. EVP_CIPHER_CTX *ctx = (void*)key;
  309. int inl=16, outl=16;
  310. EVP_EncryptUpdate(ctx, out, &outl, in, inl);
  311. }
  312. /** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
  313. * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
  314. * as it encrypts.
  315. */
  316. void
  317. aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
  318. {
  319. /* Note that the "128" below refers to the length of the counter,
  320. * not the length of the AES key. */
  321. if (cipher->using_evp) {
  322. /* In openssl 1.0.0, there's an if'd out EVP_aes_128_ctr in evp.h. If
  323. * it weren't disabled, it might be better just to use that.
  324. */
  325. CRYPTO_ctr128_encrypt((const unsigned char *)data,
  326. (unsigned char *)data,
  327. len,
  328. &cipher->key.evp,
  329. cipher->ctr_buf.buf,
  330. cipher->buf,
  331. &cipher->pos,
  332. evp_block128_fn);
  333. } else {
  334. AES_ctr128_encrypt((const unsigned char *)data,
  335. (unsigned char *)data,
  336. len,
  337. &cipher->key.aes,
  338. cipher->ctr_buf.buf,
  339. cipher->buf,
  340. &cipher->pos);
  341. }
  342. }
  343. /** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
  344. * in <b>iv</b>. */
  345. static void
  346. aes_set_iv(aes_cnt_cipher_t *cipher, const uint8_t *iv)
  347. {
  348. #ifdef USING_COUNTER_VARS
  349. cipher->counter3 = tor_ntohl(get_uint32(iv));
  350. cipher->counter2 = tor_ntohl(get_uint32(iv+4));
  351. cipher->counter1 = tor_ntohl(get_uint32(iv+8));
  352. cipher->counter0 = tor_ntohl(get_uint32(iv+12));
  353. #endif /* defined(USING_COUNTER_VARS) */
  354. cipher->pos = 0;
  355. memcpy(cipher->ctr_buf.buf, iv, 16);
  356. }
  357. #endif /* defined(USE_EVP_AES_CTR) */