aes.c 15 KB

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