aes.c 12 KB

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