aes.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 actually require
  46. * that one.)
  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 if 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. /**DOCDOC*/
  86. static int should_use_openssl_CTR = 0;
  87. #endif
  88. /** Check whether we should use the EVP interface for AES. If <b>force_val</b>
  89. * is nonnegative, we use use EVP iff it is true. Otherwise, we use EVP
  90. * if there is an engine enabled for aes-ecb. */
  91. int
  92. evaluate_evp_for_aes(int force_val)
  93. {
  94. ENGINE *e;
  95. if (force_val >= 0) {
  96. should_use_EVP = force_val;
  97. return 0;
  98. }
  99. #ifdef DISABLE_ENGINES
  100. should_use_EVP = 0;
  101. #else
  102. e = ENGINE_get_cipher_engine(NID_aes_128_ecb);
  103. if (e) {
  104. log_notice(LD_CRYPTO, "AES engine \"%s\" found; using EVP_* functions.",
  105. ENGINE_get_name(e));
  106. should_use_EVP = 1;
  107. } else {
  108. log_notice(LD_CRYPTO, "No AES engine found; using AES_* functions.");
  109. should_use_EVP = 0;
  110. }
  111. #endif
  112. return 0;
  113. }
  114. /**DOCDOC*/
  115. int
  116. evaluate_ctr_for_aes(void)
  117. {
  118. #ifdef CAN_USE_OPENSSL_CTR
  119. /* Result of encrypting an all-zero block with an all-zero 128-bit AES key.
  120. * This should be the same as encrypting an all-zero block with an all-zero
  121. * 128-bit AES key in counter mode, starting at position 0 of the stream.
  122. */
  123. static const unsigned char encrypt_zero[] =
  124. "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e";
  125. unsigned char zero[16];
  126. unsigned char output[16];
  127. unsigned char ivec[16];
  128. unsigned char ivec_tmp[16];
  129. unsigned int pos, i;
  130. AES_KEY key;
  131. memset(zero, 0, sizeof(zero));
  132. memset(ivec, 0, sizeof(ivec));
  133. AES_set_encrypt_key(zero, 128, &key);
  134. pos = 0;
  135. /* Encrypting a block one byte at a time should make the error manifest
  136. * itself for known bogus openssl versions. */
  137. for (i=0; i<16; ++i)
  138. AES_ctr128_encrypt(&zero[i], &output[i], 1, &key, ivec, ivec_tmp, &pos);
  139. if (memcmp(output, encrypt_zero, 16)) {
  140. /* Counter mode is buggy */
  141. log_notice(LD_CRYPTO, "This OpenSSL has a buggy version of counter mode; "
  142. "not using it.");
  143. } else {
  144. /* Counter mode is okay */
  145. log_notice(LD_CRYPTO, "This OpenSSL has a good implementation of counter "
  146. "mode; using it.");
  147. should_use_openssl_CTR = 1;
  148. }
  149. #else
  150. log_notice(LD_CRYPTO, "This version of OpenSSL has a slow implementation of "
  151. "counter mode; not using it.");
  152. #endif
  153. return 0;
  154. }
  155. #if !defined(USING_COUNTER_VARS)
  156. #define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
  157. #else
  158. #define COUNTER(c, n) ((c)->counter ## n)
  159. #endif
  160. /**
  161. * Helper function: set <b>cipher</b>'s internal buffer to the encrypted
  162. * value of the current counter.
  163. */
  164. static INLINE void
  165. _aes_fill_buf(aes_cnt_cipher_t *cipher)
  166. {
  167. /* We don't currently use OpenSSL's counter mode implementation because:
  168. * 1) some versions have known bugs
  169. * 2) its attitude towards IVs is not our own
  170. * 3) changing the counter position was not trivial, last time I looked.
  171. * None of these issues are insurmountable in principle.
  172. */
  173. if (cipher->using_evp) {
  174. int outl=16, inl=16;
  175. EVP_EncryptUpdate(&cipher->key.evp, cipher->buf, &outl,
  176. cipher->ctr_buf.buf, inl);
  177. } else {
  178. AES_encrypt(cipher->ctr_buf.buf, cipher->buf, &cipher->key.aes);
  179. }
  180. }
  181. /**
  182. * Return a newly allocated counter-mode AES128 cipher implementation.
  183. */
  184. aes_cnt_cipher_t*
  185. aes_new_cipher(void)
  186. {
  187. aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
  188. return result;
  189. }
  190. /** Set the key of <b>cipher</b> to <b>key</b>, which is
  191. * <b>key_bits</b> bits long (must be 128, 192, or 256). Also resets
  192. * the counter to 0.
  193. */
  194. void
  195. aes_set_key(aes_cnt_cipher_t *cipher, const char *key, int key_bits)
  196. {
  197. if (should_use_EVP) {
  198. const EVP_CIPHER *c;
  199. switch (key_bits) {
  200. case 128: c = EVP_aes_128_ecb(); break;
  201. case 192: c = EVP_aes_192_ecb(); break;
  202. case 256: c = EVP_aes_256_ecb(); break;
  203. default: tor_assert(0);
  204. }
  205. EVP_EncryptInit(&cipher->key.evp, c, (const unsigned char*)key, NULL);
  206. cipher->using_evp = 1;
  207. } else {
  208. AES_set_encrypt_key((const unsigned char *)key, key_bits, &cipher->key.aes);
  209. cipher->using_evp = 0;
  210. }
  211. #ifdef USING_COUNTER_VARS
  212. cipher->counter0 = 0;
  213. cipher->counter1 = 0;
  214. cipher->counter2 = 0;
  215. cipher->counter3 = 0;
  216. #endif
  217. memset(cipher->ctr_buf.buf, 0, sizeof(cipher->ctr_buf.buf));
  218. cipher->pos = 0;
  219. #ifdef CAN_USE_OPENSSL_CTR
  220. if (should_use_openssl_CTR)
  221. memset(cipher->buf, 0, sizeof(cipher->buf));
  222. else
  223. #endif
  224. _aes_fill_buf(cipher);
  225. }
  226. /** Release storage held by <b>cipher</b>
  227. */
  228. void
  229. aes_free_cipher(aes_cnt_cipher_t *cipher)
  230. {
  231. if (!cipher)
  232. return;
  233. if (cipher->using_evp) {
  234. EVP_CIPHER_CTX_cleanup(&cipher->key.evp);
  235. }
  236. memset(cipher, 0, sizeof(aes_cnt_cipher_t));
  237. tor_free(cipher);
  238. }
  239. #if defined(USING_COUNTER_VARS)
  240. #define UPDATE_CTR_BUF(c, n) STMT_BEGIN \
  241. (c)->ctr_buf.buf32[3-(n)] = htonl((c)->counter ## n); \
  242. STMT_END
  243. #else
  244. #define UPDATE_CTR_BUF(c, n)
  245. #endif
  246. #ifdef CAN_USE_OPENSSL_CTR
  247. /* Helper function to use EVP with openssl's counter-mode wrapper. */
  248. static void evp_block128_fn(const uint8_t in[16],
  249. uint8_t out[16],
  250. const void *key)
  251. {
  252. EVP_CIPHER_CTX *ctx = (void*)key;
  253. int inl=16, outl=16;
  254. EVP_EncryptUpdate(ctx, out, &outl, in, inl);
  255. }
  256. #endif
  257. /** Encrypt <b>len</b> bytes from <b>input</b>, storing the result in
  258. * <b>output</b>. Uses the key in <b>cipher</b>, and advances the counter
  259. * by <b>len</b> bytes as it encrypts.
  260. */
  261. void
  262. aes_crypt(aes_cnt_cipher_t *cipher, const char *input, size_t len,
  263. char *output)
  264. {
  265. #ifdef CAN_USE_OPENSSL_CTR
  266. if (should_use_openssl_CTR) {
  267. if (cipher->using_evp) {
  268. /* In openssl 1.0.0, there's an if'd out EVP_aes_128_ctr in evp.h. If
  269. * it weren't disabled, it might be better just to use that.
  270. */
  271. CRYPTO_ctr128_encrypt((const unsigned char *)input,
  272. (unsigned char *)output,
  273. len,
  274. &cipher->key.evp,
  275. cipher->ctr_buf.buf,
  276. cipher->buf,
  277. &cipher->pos,
  278. evp_block128_fn);
  279. } else {
  280. AES_ctr128_encrypt((const unsigned char *)input,
  281. (unsigned char *)output,
  282. len,
  283. &cipher->key.aes,
  284. cipher->ctr_buf.buf,
  285. cipher->buf,
  286. &cipher->pos);
  287. }
  288. return;
  289. }
  290. else
  291. #endif
  292. {
  293. int c = cipher->pos;
  294. if (PREDICT_UNLIKELY(!len)) return;
  295. while (1) {
  296. do {
  297. if (len-- == 0) { cipher->pos = c; return; }
  298. *(output++) = *(input++) ^ cipher->buf[c];
  299. } while (++c != 16);
  300. cipher->pos = c = 0;
  301. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
  302. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
  303. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
  304. ++COUNTER(cipher, 3);
  305. UPDATE_CTR_BUF(cipher, 3);
  306. }
  307. UPDATE_CTR_BUF(cipher, 2);
  308. }
  309. UPDATE_CTR_BUF(cipher, 1);
  310. }
  311. UPDATE_CTR_BUF(cipher, 0);
  312. _aes_fill_buf(cipher);
  313. }
  314. }
  315. }
  316. /** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
  317. * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
  318. * as it encrypts.
  319. */
  320. void
  321. aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
  322. {
  323. #ifdef CAN_USE_OPENSSL_CTR
  324. if (should_use_openssl_CTR) {
  325. aes_crypt(cipher, data, len, data);
  326. return;
  327. }
  328. else
  329. #endif
  330. {
  331. int c = cipher->pos;
  332. if (PREDICT_UNLIKELY(!len)) return;
  333. while (1) {
  334. do {
  335. if (len-- == 0) { cipher->pos = c; return; }
  336. *(data++) ^= cipher->buf[c];
  337. } while (++c != 16);
  338. cipher->pos = c = 0;
  339. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
  340. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
  341. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
  342. ++COUNTER(cipher, 3);
  343. UPDATE_CTR_BUF(cipher, 3);
  344. }
  345. UPDATE_CTR_BUF(cipher, 2);
  346. }
  347. UPDATE_CTR_BUF(cipher, 1);
  348. }
  349. UPDATE_CTR_BUF(cipher, 0);
  350. _aes_fill_buf(cipher);
  351. }
  352. }
  353. }
  354. /** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
  355. * in <b>iv</b>. */
  356. void
  357. aes_set_iv(aes_cnt_cipher_t *cipher, const char *iv)
  358. {
  359. #ifdef USING_COUNTER_VARS
  360. cipher->counter3 = ntohl(get_uint32(iv));
  361. cipher->counter2 = ntohl(get_uint32(iv+4));
  362. cipher->counter1 = ntohl(get_uint32(iv+8));
  363. cipher->counter0 = ntohl(get_uint32(iv+12));
  364. #endif
  365. cipher->pos = 0;
  366. memcpy(cipher->ctr_buf.buf, iv, 16);
  367. #ifdef CAN_USE_OPENSSL_CTR
  368. if (!should_use_openssl_CTR)
  369. #endif
  370. _aes_fill_buf(cipher);
  371. }