aes.c 14 KB

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