aes.c 12 KB

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