aes.c 11 KB

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