aes.c 14 KB

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