Tor 0.4.9.2-alpha-dev
All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
aes_openssl.c
Go to the documentation of this file.
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-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file aes_openssl.c
9 * \brief Use OpenSSL to implement AES_CTR.
10 **/
11
12#include "orconfig.h"
13#include "lib/crypt_ops/aes.h"
15#include "lib/log/util_bug.h"
16#include "lib/arch/bytes.h"
17
18#ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
19 #include <winsock2.h>
20 #include <ws2tcpip.h>
21#endif
22
23#include "lib/crypt_ops/compat_openssl.h"
24#include <openssl/opensslv.h>
26
27DISABLE_GCC_WARNING("-Wredundant-decls")
28
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
36ENABLE_GCC_WARNING("-Wredundant-decls")
37
38#include "lib/log/log.h"
39#include "lib/ctime/di_ops.h"
40
41#ifdef OPENSSL_NO_ENGINE
42/* Android's OpenSSL seems to have removed all of its Engine support. */
43#define DISABLE_ENGINES
44#endif
45
46/* We have five strategies for implementing AES counter mode.
47 *
48 * Best with x86 and x86_64: Use EVP_aes_*_ctr() and EVP_EncryptUpdate().
49 * This is possible with OpenSSL 1.0.1, where the counter-mode implementation
50 * can use bit-sliced or vectorized AES or AESNI as appropriate.
51 *
52 * Otherwise: Pick the best possible AES block implementation that OpenSSL
53 * gives us, and the best possible counter-mode implementation, and combine
54 * them.
55 */
56#if OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,1,0)
57
58/* With newer OpenSSL versions, the older fallback modes don't compile. So
59 * don't use them, even if we lack specific acceleration. */
60
61#define USE_EVP_AES_CTR
62
63#elif OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,0,1) && \
64 (defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
65 defined(__x86_64) || defined(__x86_64__) || \
66 defined(_M_AMD64) || defined(_M_X64) || defined(__INTEL__))
67
68#define USE_EVP_AES_CTR
69
70#endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_NOPATCH(1,1,0) || ... */
71
72/* We have 2 strategies for getting the AES block cipher: Via OpenSSL's
73 * AES_encrypt function, or via OpenSSL's EVP_EncryptUpdate function.
74 *
75 * If there's any hardware acceleration in play, we want to be using EVP_* so
76 * we can get it. Otherwise, we'll want AES_*, which seems to be about 5%
77 * faster than indirecting through the EVP layer.
78 */
79
80/* We have 2 strategies for getting a plug-in counter mode: use our own, or
81 * use OpenSSL's.
82 *
83 * Here we have a counter mode that's faster than the one shipping with
84 * OpenSSL pre-1.0 (by about 10%!). But OpenSSL 1.0.0 added a counter mode
85 * implementation faster than the one here (by about 7%). So we pick which
86 * one to used based on the Openssl version above. (OpenSSL 1.0.0a fixed a
87 * critical bug in that counter mode implementation, so we need to test to
88 * make sure that we have a fixed version.)
89 */
90
91#ifdef USE_EVP_AES_CTR
92
93/* We don't actually define the struct here. */
94
95aes_cnt_cipher_t *
96aes_new_cipher(const uint8_t *key, const uint8_t *iv, int key_bits)
97{
98 EVP_CIPHER_CTX *cipher = EVP_CIPHER_CTX_new();
99 const EVP_CIPHER *c = NULL;
100 switch (key_bits) {
101 case 128: c = EVP_aes_128_ctr(); break;
102 case 192: c = EVP_aes_192_ctr(); break;
103 case 256: c = EVP_aes_256_ctr(); break;
104 default: tor_assert_unreached(); // LCOV_EXCL_LINE
105 }
106 EVP_EncryptInit(cipher, c, key, iv);
107 return (aes_cnt_cipher_t *) cipher;
108}
109void
110aes_cipher_free_(aes_cnt_cipher_t *cipher_)
111{
112 if (!cipher_)
113 return;
114 EVP_CIPHER_CTX *cipher = (EVP_CIPHER_CTX *) cipher_;
115 EVP_CIPHER_CTX_reset(cipher);
116 EVP_CIPHER_CTX_free(cipher);
117}
118void
119aes_crypt_inplace(aes_cnt_cipher_t *cipher_, char *data, size_t len)
120{
121 int outl;
122 EVP_CIPHER_CTX *cipher = (EVP_CIPHER_CTX *) cipher_;
123
124 tor_assert(len < INT_MAX);
125
126 EVP_EncryptUpdate(cipher, (unsigned char*)data,
127 &outl, (unsigned char*)data, (int)len);
128}
129int
130evaluate_evp_for_aes(int force_val)
131{
132 (void) force_val;
133 log_info(LD_CRYPTO, "This version of OpenSSL has a known-good EVP "
134 "counter-mode implementation. Using it.");
135 return 0;
136}
137int
138evaluate_ctr_for_aes(void)
139{
140 return 0;
141}
142#else /* !defined(USE_EVP_AES_CTR) */
143
144/*======================================================================*/
145/* Interface to AES code, and counter implementation */
146
147/** Implements an AES counter-mode cipher. */
148struct aes_cnt_cipher_t {
149/** This next element (however it's defined) is the AES key. */
150 union {
151 EVP_CIPHER_CTX evp;
152 AES_KEY aes;
153 } key;
154
155#if !defined(WORDS_BIGENDIAN)
156#define USING_COUNTER_VARS
157 /** These four values, together, implement a 128-bit counter, with
158 * counter0 as the low-order word and counter3 as the high-order word. */
159 uint32_t counter3;
160 uint32_t counter2;
161 uint32_t counter1;
162 uint32_t counter0;
163#endif /* !defined(WORDS_BIGENDIAN) */
164
165 union {
166 /** The counter, in big-endian order, as bytes. */
167 uint8_t buf[16];
168 /** The counter, in big-endian order, as big-endian words. Note that
169 * on big-endian platforms, this is redundant with counter3...0,
170 * so we just use these values instead. */
171 uint32_t buf32[4];
172 } ctr_buf;
173
174 /** The encrypted value of ctr_buf. */
175 uint8_t buf[16];
176 /** Our current stream position within buf. */
177 unsigned int pos;
178
179 /** True iff we're using the evp implementation of this cipher. */
180 uint8_t using_evp;
181};
182
183/** True iff we should prefer the EVP implementation for AES, either because
184 * we're testing it or because we have hardware acceleration configured */
185static int should_use_EVP = 0;
186
187/** Check whether we should use the EVP interface for AES. If <b>force_val</b>
188 * is nonnegative, we use use EVP iff it is true. Otherwise, we use EVP
189 * if there is an engine enabled for aes-ecb. */
190int
191evaluate_evp_for_aes(int force_val)
192{
193 ENGINE *e;
194
195 if (force_val >= 0) {
196 should_use_EVP = force_val;
197 return 0;
198 }
199#ifdef DISABLE_ENGINES
200 should_use_EVP = 0;
201#else
202 e = ENGINE_get_cipher_engine(NID_aes_128_ecb);
203
204 if (e) {
205 log_info(LD_CRYPTO, "AES engine \"%s\" found; using EVP_* functions.",
206 ENGINE_get_name(e));
207 should_use_EVP = 1;
208 } else {
209 log_info(LD_CRYPTO, "No AES engine found; using AES_* functions.");
210 should_use_EVP = 0;
211 }
212#endif /* defined(DISABLE_ENGINES) */
213
214 return 0;
215}
216
217/** Test the OpenSSL counter mode implementation to see whether it has the
218 * counter-mode bug from OpenSSL 1.0.0. If the implementation works, then
219 * we will use it for future encryption/decryption operations.
220 *
221 * We can't just look at the OpenSSL version, since some distributions update
222 * their OpenSSL packages without changing the version number.
223 **/
224int
225evaluate_ctr_for_aes(void)
226{
227 /* Result of encrypting an all-zero block with an all-zero 128-bit AES key.
228 * This should be the same as encrypting an all-zero block with an all-zero
229 * 128-bit AES key in counter mode, starting at position 0 of the stream.
230 */
231 static const unsigned char encrypt_zero[] =
232 "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e";
233 unsigned char zero[16];
234 unsigned char output[16];
235 unsigned char ivec[16];
236 unsigned char ivec_tmp[16];
237 unsigned int pos, i;
238 AES_KEY key;
239 memset(zero, 0, sizeof(zero));
240 memset(ivec, 0, sizeof(ivec));
241 AES_set_encrypt_key(zero, 128, &key);
242
243 pos = 0;
244 /* Encrypting a block one byte at a time should make the error manifest
245 * itself for known bogus openssl versions. */
246 for (i=0; i<16; ++i)
247 AES_ctr128_encrypt(&zero[i], &output[i], 1, &key, ivec, ivec_tmp, &pos);
248
249 if (fast_memneq(output, encrypt_zero, 16)) {
250 /* Counter mode is buggy */
251 /* LCOV_EXCL_START */
252 log_err(LD_CRYPTO, "This OpenSSL has a buggy version of counter mode; "
253 "quitting tor.");
254 exit(1); // exit ok: openssl is broken.
255 /* LCOV_EXCL_STOP */
256 }
257 return 0;
258}
259
260#if !defined(USING_COUNTER_VARS)
261#define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
262#else
263#define COUNTER(c, n) ((c)->counter ## n)
264#endif
265
266static void aes_set_key(aes_cnt_cipher_t *cipher, const uint8_t *key,
267 int key_bits);
268static void aes_set_iv(aes_cnt_cipher_t *cipher, const uint8_t *iv);
269
270/**
271 * Return a newly allocated counter-mode AES128 cipher implementation,
272 * using the 128-bit key <b>key</b> and the 128-bit IV <b>iv</b>.
273 */
274aes_cnt_cipher_t*
275aes_new_cipher(const uint8_t *key, const uint8_t *iv, int bits)
276{
277 aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
278
279 aes_set_key(result, key, bits);
280 aes_set_iv(result, iv);
281
282 return result;
283}
284
285/** Set the key of <b>cipher</b> to <b>key</b>, which is
286 * <b>key_bits</b> bits long (must be 128, 192, or 256). Also resets
287 * the counter to 0.
288 */
289static void
290aes_set_key(aes_cnt_cipher_t *cipher, const uint8_t *key, int key_bits)
291{
292 if (should_use_EVP) {
293 const EVP_CIPHER *c = 0;
294 switch (key_bits) {
295 case 128: c = EVP_aes_128_ecb(); break;
296 case 192: c = EVP_aes_192_ecb(); break;
297 case 256: c = EVP_aes_256_ecb(); break;
298 default: tor_assert(0); // LCOV_EXCL_LINE
299 }
300 EVP_EncryptInit(&cipher->key.evp, c, key, NULL);
301 cipher->using_evp = 1;
302 } else {
303 AES_set_encrypt_key(key, key_bits,&cipher->key.aes);
304 cipher->using_evp = 0;
305 }
306
307#ifdef USING_COUNTER_VARS
308 cipher->counter0 = 0;
309 cipher->counter1 = 0;
310 cipher->counter2 = 0;
311 cipher->counter3 = 0;
312#endif /* defined(USING_COUNTER_VARS) */
313
314 memset(cipher->ctr_buf.buf, 0, sizeof(cipher->ctr_buf.buf));
315
316 cipher->pos = 0;
317
318 memset(cipher->buf, 0, sizeof(cipher->buf));
319}
320
321/** Release storage held by <b>cipher</b>
322 */
323void
324aes_cipher_free_(aes_cnt_cipher_t *cipher)
325{
326 if (!cipher)
327 return;
328 if (cipher->using_evp) {
329 EVP_CIPHER_CTX_cleanup(&cipher->key.evp);
330 }
331 memwipe(cipher, 0, sizeof(aes_cnt_cipher_t));
332 tor_free(cipher);
333}
334
335#if defined(USING_COUNTER_VARS)
336#define UPDATE_CTR_BUF(c, n) STMT_BEGIN \
337 (c)->ctr_buf.buf32[3-(n)] = htonl((c)->counter ## n); \
338 STMT_END
339#else
340#define UPDATE_CTR_BUF(c, n)
341#endif /* defined(USING_COUNTER_VARS) */
342
343/* Helper function to use EVP with openssl's counter-mode wrapper. */
344static void
345evp_block128_fn(const uint8_t in[16],
346 uint8_t out[16],
347 const void *key)
348{
349 EVP_CIPHER_CTX *ctx = (void*)key;
350 int inl=16, outl=16;
351 EVP_EncryptUpdate(ctx, out, &outl, in, inl);
352}
353
354/** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
355 * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
356 * as it encrypts.
357 */
358void
359aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
360{
361 /* Note that the "128" below refers to the length of the counter,
362 * not the length of the AES key. */
363 if (cipher->using_evp) {
364 /* In openssl 1.0.0, there's an if'd out EVP_aes_128_ctr in evp.h. If
365 * it weren't disabled, it might be better just to use that.
366 */
367 CRYPTO_ctr128_encrypt((const unsigned char *)data,
368 (unsigned char *)data,
369 len,
370 &cipher->key.evp,
371 cipher->ctr_buf.buf,
372 cipher->buf,
373 &cipher->pos,
374 evp_block128_fn);
375 } else {
376 AES_ctr128_encrypt((const unsigned char *)data,
377 (unsigned char *)data,
378 len,
379 &cipher->key.aes,
380 cipher->ctr_buf.buf,
381 cipher->buf,
382 &cipher->pos);
383 }
384}
385
386/** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
387 * in <b>iv</b>. */
388static void
389aes_set_iv(aes_cnt_cipher_t *cipher, const uint8_t *iv)
390{
391#ifdef USING_COUNTER_VARS
392 cipher->counter3 = tor_ntohl(get_uint32(iv));
393 cipher->counter2 = tor_ntohl(get_uint32(iv+4));
394 cipher->counter1 = tor_ntohl(get_uint32(iv+8));
395 cipher->counter0 = tor_ntohl(get_uint32(iv+12));
396#endif /* defined(USING_COUNTER_VARS) */
397 cipher->pos = 0;
398 memcpy(cipher->ctr_buf.buf, iv, 16);
399}
400
401#endif /* defined(USE_EVP_AES_CTR) */
Headers for aes.c.
Inline functions for reading and writing multibyte values from the middle of strings,...
static uint32_t tor_ntohl(uint32_t a)
Definition: bytes.h:177
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:54
Headers for crypto_openssl_mgt.c.
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
Common functions for cryptographic routines.
Headers for di_ops.c.
#define fast_memneq(a, b, c)
Definition: di_ops.h:42
#define LD_CRYPTO
Definition: log.h:64
#define tor_free(p)
Definition: malloc.h:56
Macros to manage assertions, fatal and non-fatal.
#define tor_assert(expr)
Definition: util_bug.h:103