prop250: Initialize the SR subsystem and us it!
[tor.git] / src / common / aes.c
blob2b8a68c4a22422bfcf5e87c3ad05c88d855fdd3a
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-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file aes.c
9 * \brief Implements a counter-mode stream cipher on top of AES.
10 **/
12 #include "orconfig.h"
14 #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
15 #include <winsock2.h>
16 #include <ws2tcpip.h>
17 #endif
19 #include <openssl/opensslv.h>
20 #include "crypto.h"
22 #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,0,0)
23 #error "We require OpenSSL >= 1.0.0"
24 #endif
26 DISABLE_GCC_WARNING(redundant-decls)
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>
36 ENABLE_GCC_WARNING(redundant-decls)
38 #include "compat.h"
39 #include "aes.h"
40 #include "util.h"
41 #include "torlog.h"
42 #include "di_ops.h"
44 #ifdef ANDROID
45 /* Android's OpenSSL seems to have removed all of its Engine support. */
46 #define DISABLE_ENGINES
47 #endif
49 /* We have five strategies for implementing AES counter mode.
51 * Best with x86 and x86_64: Use EVP_aes_ctr128() and EVP_EncryptUpdate().
52 * This is possible with OpenSSL 1.0.1, where the counter-mode implementation
53 * can use bit-sliced or vectorized AES or AESNI as appropriate.
55 * Otherwise: Pick the best possible AES block implementation that OpenSSL
56 * gives us, and the best possible counter-mode implementation, and combine
57 * them.
59 #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,0,1) && \
60 (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
61 defined(__x86_64) || defined(__x86_64__) || \
62 defined(_M_AMD64) || defined(_M_X64) || defined(__INTEL__)) \
64 #define USE_EVP_AES_CTR
66 #endif
68 /* We have 2 strategies for getting the AES block cipher: Via OpenSSL's
69 * AES_encrypt function, or via OpenSSL's EVP_EncryptUpdate function.
71 * If there's any hardware acceleration in play, we want to be using EVP_* so
72 * we can get it. Otherwise, we'll want AES_*, which seems to be about 5%
73 * faster than indirecting through the EVP layer.
76 /* We have 2 strategies for getting a plug-in counter mode: use our own, or
77 * use OpenSSL's.
79 * Here we have a counter mode that's faster than the one shipping with
80 * OpenSSL pre-1.0 (by about 10%!). But OpenSSL 1.0.0 added a counter mode
81 * implementation faster than the one here (by about 7%). So we pick which
82 * one to used based on the Openssl version above. (OpenSSL 1.0.0a fixed a
83 * critical bug in that counter mode implementation, so we need to test to
84 * make sure that we have a fixed version.)
87 #ifdef USE_EVP_AES_CTR
89 /* We don't actually define the struct here. */
91 aes_cnt_cipher_t *
92 aes_new_cipher(const char *key, const char *iv)
94 EVP_CIPHER_CTX *cipher = EVP_CIPHER_CTX_new();
95 EVP_EncryptInit(cipher, EVP_aes_128_ctr(),
96 (const unsigned char*)key, (const unsigned char *)iv);
97 return (aes_cnt_cipher_t *) cipher;
99 void
100 aes_cipher_free(aes_cnt_cipher_t *cipher_)
102 if (!cipher_)
103 return;
104 EVP_CIPHER_CTX *cipher = (EVP_CIPHER_CTX *) cipher_;
105 EVP_CIPHER_CTX_cleanup(cipher);
106 EVP_CIPHER_CTX_free(cipher);
108 void
109 aes_crypt_inplace(aes_cnt_cipher_t *cipher_, char *data, size_t len)
111 int outl;
112 EVP_CIPHER_CTX *cipher = (EVP_CIPHER_CTX *) cipher_;
114 tor_assert(len < INT_MAX);
116 EVP_EncryptUpdate(cipher, (unsigned char*)data,
117 &outl, (unsigned char*)data, (int)len);
120 evaluate_evp_for_aes(int force_val)
122 (void) force_val;
123 log_info(LD_CRYPTO, "This version of OpenSSL has a known-good EVP "
124 "counter-mode implementation. Using it.");
125 return 0;
128 evaluate_ctr_for_aes(void)
130 return 0;
132 #else
134 /*======================================================================*/
135 /* Interface to AES code, and counter implementation */
137 /** Implements an AES counter-mode cipher. */
138 struct aes_cnt_cipher {
139 /** This next element (however it's defined) is the AES key. */
140 union {
141 EVP_CIPHER_CTX evp;
142 AES_KEY aes;
143 } key;
145 #if !defined(WORDS_BIGENDIAN)
146 #define USING_COUNTER_VARS
147 /** These four values, together, implement a 128-bit counter, with
148 * counter0 as the low-order word and counter3 as the high-order word. */
149 uint32_t counter3;
150 uint32_t counter2;
151 uint32_t counter1;
152 uint32_t counter0;
153 #endif
155 union {
156 /** The counter, in big-endian order, as bytes. */
157 uint8_t buf[16];
158 /** The counter, in big-endian order, as big-endian words. Note that
159 * on big-endian platforms, this is redundant with counter3...0,
160 * so we just use these values instead. */
161 uint32_t buf32[4];
162 } ctr_buf;
164 /** The encrypted value of ctr_buf. */
165 uint8_t buf[16];
166 /** Our current stream position within buf. */
167 unsigned int pos;
169 /** True iff we're using the evp implementation of this cipher. */
170 uint8_t using_evp;
173 /** True iff we should prefer the EVP implementation for AES, either because
174 * we're testing it or because we have hardware acceleration configured */
175 static int should_use_EVP = 0;
177 /** Check whether we should use the EVP interface for AES. If <b>force_val</b>
178 * is nonnegative, we use use EVP iff it is true. Otherwise, we use EVP
179 * if there is an engine enabled for aes-ecb. */
181 evaluate_evp_for_aes(int force_val)
183 ENGINE *e;
185 if (force_val >= 0) {
186 should_use_EVP = force_val;
187 return 0;
189 #ifdef DISABLE_ENGINES
190 should_use_EVP = 0;
191 #else
192 e = ENGINE_get_cipher_engine(NID_aes_128_ecb);
194 if (e) {
195 log_info(LD_CRYPTO, "AES engine \"%s\" found; using EVP_* functions.",
196 ENGINE_get_name(e));
197 should_use_EVP = 1;
198 } else {
199 log_info(LD_CRYPTO, "No AES engine found; using AES_* functions.");
200 should_use_EVP = 0;
202 #endif
204 return 0;
207 /** Test the OpenSSL counter mode implementation to see whether it has the
208 * counter-mode bug from OpenSSL 1.0.0. If the implementation works, then
209 * we will use it for future encryption/decryption operations.
211 * We can't just look at the OpenSSL version, since some distributions update
212 * their OpenSSL packages without changing the version number.
215 evaluate_ctr_for_aes(void)
217 /* Result of encrypting an all-zero block with an all-zero 128-bit AES key.
218 * This should be the same as encrypting an all-zero block with an all-zero
219 * 128-bit AES key in counter mode, starting at position 0 of the stream.
221 static const unsigned char encrypt_zero[] =
222 "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e";
223 unsigned char zero[16];
224 unsigned char output[16];
225 unsigned char ivec[16];
226 unsigned char ivec_tmp[16];
227 unsigned int pos, i;
228 AES_KEY key;
229 memset(zero, 0, sizeof(zero));
230 memset(ivec, 0, sizeof(ivec));
231 AES_set_encrypt_key(zero, 128, &key);
233 pos = 0;
234 /* Encrypting a block one byte at a time should make the error manifest
235 * itself for known bogus openssl versions. */
236 for (i=0; i<16; ++i)
237 AES_ctr128_encrypt(&zero[i], &output[i], 1, &key, ivec, ivec_tmp, &pos);
239 if (fast_memneq(output, encrypt_zero, 16)) {
240 /* Counter mode is buggy */
241 /* LCOV_EXCL_START */
242 log_err(LD_CRYPTO, "This OpenSSL has a buggy version of counter mode; "
243 "quitting tor.");
244 exit(1);
245 /* LCOV_EXCL_STOP */
247 return 0;
250 #if !defined(USING_COUNTER_VARS)
251 #define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
252 #else
253 #define COUNTER(c, n) ((c)->counter ## n)
254 #endif
256 static void aes_set_key(aes_cnt_cipher_t *cipher, const char *key,
257 int key_bits);
258 static void aes_set_iv(aes_cnt_cipher_t *cipher, const char *iv);
261 * Return a newly allocated counter-mode AES128 cipher implementation,
262 * using the 128-bit key <b>key</b> and the 128-bit IV <b>iv</b>.
264 aes_cnt_cipher_t*
265 aes_new_cipher(const char *key, const char *iv)
267 aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
269 aes_set_key(result, key, 128);
270 aes_set_iv(result, iv);
272 return result;
275 /** Set the key of <b>cipher</b> to <b>key</b>, which is
276 * <b>key_bits</b> bits long (must be 128, 192, or 256). Also resets
277 * the counter to 0.
279 static void
280 aes_set_key(aes_cnt_cipher_t *cipher, const char *key, int key_bits)
282 if (should_use_EVP) {
283 const EVP_CIPHER *c = 0;
284 switch (key_bits) {
285 case 128: c = EVP_aes_128_ecb(); break;
286 case 192: c = EVP_aes_192_ecb(); break;
287 case 256: c = EVP_aes_256_ecb(); break;
288 default: tor_assert(0); // LCOV_EXCL_LINE
290 EVP_EncryptInit(&cipher->key.evp, c, (const unsigned char*)key, NULL);
291 cipher->using_evp = 1;
292 } else {
293 AES_set_encrypt_key((const unsigned char *)key, key_bits,&cipher->key.aes);
294 cipher->using_evp = 0;
297 #ifdef USING_COUNTER_VARS
298 cipher->counter0 = 0;
299 cipher->counter1 = 0;
300 cipher->counter2 = 0;
301 cipher->counter3 = 0;
302 #endif
304 memset(cipher->ctr_buf.buf, 0, sizeof(cipher->ctr_buf.buf));
306 cipher->pos = 0;
308 memset(cipher->buf, 0, sizeof(cipher->buf));
311 /** Release storage held by <b>cipher</b>
313 void
314 aes_cipher_free(aes_cnt_cipher_t *cipher)
316 if (!cipher)
317 return;
318 if (cipher->using_evp) {
319 EVP_CIPHER_CTX_cleanup(&cipher->key.evp);
321 memwipe(cipher, 0, sizeof(aes_cnt_cipher_t));
322 tor_free(cipher);
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
333 /* Helper function to use EVP with openssl's counter-mode wrapper. */
334 static void
335 evp_block128_fn(const uint8_t in[16],
336 uint8_t out[16],
337 const void *key)
339 EVP_CIPHER_CTX *ctx = (void*)key;
340 int inl=16, outl=16;
341 EVP_EncryptUpdate(ctx, out, &outl, in, inl);
344 /** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
345 * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
346 * as it encrypts.
348 void
349 aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
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.
355 CRYPTO_ctr128_encrypt((const unsigned char *)data,
356 (unsigned char *)data,
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 *)data,
365 (unsigned char *)data,
366 len,
367 &cipher->key.aes,
368 cipher->ctr_buf.buf,
369 cipher->buf,
370 &cipher->pos);
374 /** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
375 * in <b>iv</b>. */
376 static void
377 aes_set_iv(aes_cnt_cipher_t *cipher, const char *iv)
379 #ifdef USING_COUNTER_VARS
380 cipher->counter3 = ntohl(get_uint32(iv));
381 cipher->counter2 = ntohl(get_uint32(iv+4));
382 cipher->counter1 = ntohl(get_uint32(iv+8));
383 cipher->counter0 = ntohl(get_uint32(iv+12));
384 #endif
385 cipher->pos = 0;
386 memcpy(cipher->ctr_buf.buf, iv, 16);
389 #endif