aes.c 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 "compat.h"
  19. #include "aes.h"
  20. #include "util.h"
  21. #include "torlog.h"
  22. #ifdef ANDROID
  23. /* Android's OpenSSL seems to have removed all of its Engine support. */
  24. #define DISABLE_ENGINES
  25. #endif
  26. /* We have 2 strategies for getting AES: Via OpenSSL's AES_encrypt function,
  27. * via OpenSSL's EVP_EncryptUpdate function.
  28. *
  29. * If there's any hardware acceleration in play, we want to be using EVP_* so
  30. * we can get it. Otherwise, we'll want AES_*, which seems to be about 5%
  31. * faster than indirecting through the EVP layer.
  32. */
  33. /* Include OpenSSL headers as needed. */
  34. /*======================================================================*/
  35. /* Interface to AES code, and counter implementation */
  36. /** Implements an AES counter-mode cipher. */
  37. struct aes_cnt_cipher {
  38. /** This next element (however it's defined) is the AES key. */
  39. union {
  40. EVP_CIPHER_CTX evp;
  41. AES_KEY aes;
  42. } key;
  43. #if !defined(WORDS_BIGENDIAN)
  44. #define USING_COUNTER_VARS
  45. /** These four values, together, implement a 128-bit counter, with
  46. * counter0 as the low-order word and counter3 as the high-order word. */
  47. uint32_t counter3;
  48. uint32_t counter2;
  49. uint32_t counter1;
  50. uint32_t counter0;
  51. #endif
  52. union {
  53. /** The counter, in big-endian order, as bytes. */
  54. uint8_t buf[16];
  55. /** The counter, in big-endian order, as big-endian words. Note that
  56. * on big-endian platforms, this is redundant with counter3...0,
  57. * so we just use these values instead. */
  58. uint32_t buf32[4];
  59. } ctr_buf;
  60. /** The encrypted value of ctr_buf. */
  61. uint8_t buf[16];
  62. /** Our current stream position within buf. */
  63. uint8_t pos;
  64. /** True iff we're using the evp implementation of this cipher. */
  65. uint8_t using_evp;
  66. };
  67. /** True if we should prefer the EVP implementation for AES, either because
  68. * we're testing it or because we have hardware acceleration configured */
  69. static int should_use_EVP = 0;
  70. /** Check whether we should use the EVP interface for AES. If <b>force_val</b>
  71. * is nonnegative, we use use EVP iff it is true. Otherwise, we use EVP
  72. * if there is an engine enabled for aes-ecb. */
  73. int
  74. evaluate_evp_for_aes(int force_val)
  75. {
  76. ENGINE *e;
  77. if (force_val >= 0) {
  78. should_use_EVP = force_val;
  79. return 0;
  80. }
  81. #ifdef DISABLE_ENGINES
  82. should_use_EVP = 0;
  83. #else
  84. e = ENGINE_get_cipher_engine(NID_aes_128_ecb);
  85. if (e) {
  86. log_notice(LD_CRYPTO, "AES engine \"%s\" found; using EVP_* functions.",
  87. ENGINE_get_name(e));
  88. should_use_EVP = 1;
  89. } else {
  90. log_notice(LD_CRYPTO, "No AES engine found; using AES_* functions.");
  91. should_use_EVP = 0;
  92. }
  93. #endif
  94. return 0;
  95. }
  96. #if !defined(USING_COUNTER_VARS)
  97. #define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
  98. #else
  99. #define COUNTER(c, n) ((c)->counter ## n)
  100. #endif
  101. /**
  102. * Helper function: set <b>cipher</b>'s internal buffer to the encrypted
  103. * value of the current counter.
  104. */
  105. static INLINE void
  106. _aes_fill_buf(aes_cnt_cipher_t *cipher)
  107. {
  108. /* We don't currently use OpenSSL's counter mode implementation because:
  109. * 1) some versions have known bugs
  110. * 2) its attitude towards IVs is not our own
  111. * 3) changing the counter position was not trivial, last time I looked.
  112. * None of these issues are insurmountable in principle.
  113. */
  114. if (cipher->using_evp) {
  115. int outl=16, inl=16;
  116. EVP_EncryptUpdate(&cipher->key.evp, cipher->buf, &outl,
  117. cipher->ctr_buf.buf, inl);
  118. } else {
  119. AES_encrypt(cipher->ctr_buf.buf, cipher->buf, &cipher->key.aes);
  120. }
  121. }
  122. /**
  123. * Return a newly allocated counter-mode AES128 cipher implementation.
  124. */
  125. aes_cnt_cipher_t*
  126. aes_new_cipher(void)
  127. {
  128. aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
  129. return result;
  130. }
  131. /** Set the key of <b>cipher</b> to <b>key</b>, which is
  132. * <b>key_bits</b> bits long (must be 128, 192, or 256). Also resets
  133. * the counter to 0.
  134. */
  135. void
  136. aes_set_key(aes_cnt_cipher_t *cipher, const char *key, int key_bits)
  137. {
  138. if (should_use_EVP) {
  139. const EVP_CIPHER *c;
  140. switch (key_bits) {
  141. case 128: c = EVP_aes_128_ecb(); break;
  142. case 192: c = EVP_aes_192_ecb(); break;
  143. case 256: c = EVP_aes_256_ecb(); break;
  144. default: tor_assert(0);
  145. }
  146. EVP_EncryptInit(&cipher->key.evp, c, (const unsigned char*)key, NULL);
  147. cipher->using_evp = 1;
  148. } else {
  149. AES_set_encrypt_key((const unsigned char *)key, key_bits, &cipher->key.aes);
  150. cipher->using_evp = 0;
  151. }
  152. #ifdef USING_COUNTER_VARS
  153. cipher->counter0 = 0;
  154. cipher->counter1 = 0;
  155. cipher->counter2 = 0;
  156. cipher->counter3 = 0;
  157. #endif
  158. memset(cipher->ctr_buf.buf, 0, sizeof(cipher->ctr_buf.buf));
  159. cipher->pos = 0;
  160. _aes_fill_buf(cipher);
  161. }
  162. /** Release storage held by <b>cipher</b>
  163. */
  164. void
  165. aes_free_cipher(aes_cnt_cipher_t *cipher)
  166. {
  167. if (!cipher)
  168. return;
  169. if (cipher->using_evp) {
  170. EVP_CIPHER_CTX_cleanup(&cipher->key.evp);
  171. }
  172. memset(cipher, 0, sizeof(aes_cnt_cipher_t));
  173. tor_free(cipher);
  174. }
  175. #if defined(USING_COUNTER_VARS)
  176. #define UPDATE_CTR_BUF(c, n) STMT_BEGIN \
  177. (c)->ctr_buf.buf32[3-(n)] = htonl((c)->counter ## n); \
  178. STMT_END
  179. #else
  180. #define UPDATE_CTR_BUF(c, n)
  181. #endif
  182. /** Encrypt <b>len</b> bytes from <b>input</b>, storing the result in
  183. * <b>output</b>. Uses the key in <b>cipher</b>, and advances the counter
  184. * by <b>len</b> bytes as it encrypts.
  185. */
  186. void
  187. aes_crypt(aes_cnt_cipher_t *cipher, const char *input, size_t len,
  188. char *output)
  189. {
  190. /* This function alone is up to 5% of our runtime in some profiles; anything
  191. * we could do to make it faster would be great.
  192. *
  193. * Experimenting suggests that unrolling the inner loop into a switch
  194. * statement doesn't help. What does seem to help is making the input and
  195. * output buffers word aligned, and never crypting anything besides an
  196. * integer number of words at a time -- it shaves maybe 4-5% of the per-byte
  197. * encryption time measured by bench_aes. We can't do that with the current
  198. * Tor protocol, though: Tor really likes to crypt things in 509-byte
  199. * chunks.
  200. *
  201. * If we were really ambitous, we'd force len to be a multiple of the block
  202. * size, and shave maybe another 4-5% off.
  203. */
  204. int c = cipher->pos;
  205. if (PREDICT_UNLIKELY(!len)) return;
  206. while (1) {
  207. do {
  208. if (len-- == 0) { cipher->pos = c; return; }
  209. *(output++) = *(input++) ^ cipher->buf[c];
  210. } while (++c != 16);
  211. cipher->pos = c = 0;
  212. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
  213. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
  214. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
  215. ++COUNTER(cipher, 3);
  216. UPDATE_CTR_BUF(cipher, 3);
  217. }
  218. UPDATE_CTR_BUF(cipher, 2);
  219. }
  220. UPDATE_CTR_BUF(cipher, 1);
  221. }
  222. UPDATE_CTR_BUF(cipher, 0);
  223. _aes_fill_buf(cipher);
  224. }
  225. }
  226. /** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
  227. * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
  228. * as it encrypts.
  229. */
  230. void
  231. aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
  232. {
  233. /* XXXX This function is up to 5% of our runtime in some profiles;
  234. * we should look into unrolling some of the loops; taking advantage
  235. * of alignment, using a bigger buffer, and so on. Not till after 0.1.2.x,
  236. * though. */
  237. int c = cipher->pos;
  238. if (PREDICT_UNLIKELY(!len)) return;
  239. while (1) {
  240. do {
  241. if (len-- == 0) { cipher->pos = c; return; }
  242. *(data++) ^= cipher->buf[c];
  243. } while (++c != 16);
  244. cipher->pos = c = 0;
  245. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
  246. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
  247. if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
  248. ++COUNTER(cipher, 3);
  249. UPDATE_CTR_BUF(cipher, 3);
  250. }
  251. UPDATE_CTR_BUF(cipher, 2);
  252. }
  253. UPDATE_CTR_BUF(cipher, 1);
  254. }
  255. UPDATE_CTR_BUF(cipher, 0);
  256. _aes_fill_buf(cipher);
  257. }
  258. }
  259. /** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
  260. * in <b>iv</b>. */
  261. void
  262. aes_set_iv(aes_cnt_cipher_t *cipher, const char *iv)
  263. {
  264. #ifdef USING_COUNTER_VARS
  265. cipher->counter3 = ntohl(get_uint32(iv));
  266. cipher->counter2 = ntohl(get_uint32(iv+4));
  267. cipher->counter1 = ntohl(get_uint32(iv+8));
  268. cipher->counter0 = ntohl(get_uint32(iv+12));
  269. #endif
  270. cipher->pos = 0;
  271. memcpy(cipher->ctr_buf.buf, iv, 16);
  272. _aes_fill_buf(cipher);
  273. }