aes.c 12 KB
Newer Older
1
/* Copyright (c) 2001, Matej Pfajfar.
Roger Dingledine's avatar
Roger Dingledine committed
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
6
/* See LICENSE for licensing information */

Nick Mathewson's avatar
Nick Mathewson committed
7
8
/**
 * \file aes.c
9
 * \brief Implements a counter-mode stream cipher on top of AES.
Nick Mathewson's avatar
Nick Mathewson committed
10
 **/
11

12
#include "orconfig.h"
13
#include <openssl/opensslv.h>
14
15
16
#include <assert.h>
#include <stdlib.h>
#include <string.h>
17
18
19
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/engine.h>
20
#include "crypto.h"
21
#if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,0)
22
23
/* See comments about which counter mode implementation to use below. */
#include <openssl/modes.h>
24
#define CAN_USE_OPENSSL_CTR
25
#endif
26
#include "compat.h"
27
#include "aes.h"
28
#include "util.h"
Nick Mathewson's avatar
Nick Mathewson committed
29
#include "torlog.h"
30

31
32
33
#ifdef ANDROID
/* Android's OpenSSL seems to have removed all of its Engine support. */
#define DISABLE_ENGINES
34
#endif
35

36
37
38
39
40
41
42
43
/* We have 2 strategies for getting AES: Via OpenSSL's AES_encrypt function,
 * via OpenSSL's EVP_EncryptUpdate function.
 *
 * If there's any hardware acceleration in play, we want to be using EVP_* so
 * we can get it.  Otherwise, we'll want AES_*, which seems to be about 5%
 * faster than indirecting through the EVP layer.
 */

44
45
46
47
48
/* We have 2 strategies for counter mode: use our own, or use OpenSSL's.
 *
 * Here we have a counter mode that's faster than the one shipping with
 * OpenSSL pre-1.0 (by about 10%!).  But OpenSSL 1.0.0 added a counter mode
 * implementation faster than the one here (by about 7%).  So we pick which
49
 * one to used based on the Openssl version above.  (OpenSSL 1.0.0a fixed a
50
51
 * critical bug in that counter mode implementation, so we need to test to
 * make sure that we have a fixed version.)
52
 */
53

54
55
56
/*======================================================================*/
/* Interface to AES code, and counter implementation */

57
/** Implements an AES counter-mode cipher. */
58
struct aes_cnt_cipher {
59
/** This next element (however it's defined) is the AES key. */
60
61
62
63
  union {
    EVP_CIPHER_CTX evp;
    AES_KEY aes;
  } key;
64

65
#if !defined(WORDS_BIGENDIAN)
66
#define USING_COUNTER_VARS
67
68
  /** These four values, together, implement a 128-bit counter, with
   * counter0 as the low-order word and counter3 as the high-order word. */
69
70
71
72
  uint32_t counter3;
  uint32_t counter2;
  uint32_t counter1;
  uint32_t counter0;
73
74
75
76
#endif

  union {
    /** The counter, in big-endian order, as bytes. */
77
    uint8_t buf[16];
78
79
80
    /** The counter, in big-endian order, as big-endian words.  Note that
     * on big-endian platforms, this is redundant with counter3...0,
     * so we just use these values instead. */
81
    uint32_t buf32[4];
82
  } ctr_buf;
83

84
  /** The encrypted value of ctr_buf. */
85
  uint8_t buf[16];
86
  /** Our current stream position within buf. */
87
  unsigned int pos;
88
89
90

  /** True iff we're using the evp implementation of this cipher. */
  uint8_t using_evp;
91
92
};

93
/** True iff we should prefer the EVP implementation for AES, either because
94
95
96
 * we're testing it or because we have hardware acceleration configured */
static int should_use_EVP = 0;

97
#ifdef CAN_USE_OPENSSL_CTR
98
99
/** True iff we have tested the counter-mode implementation and found that it
 * doesn't have the counter-mode bug from OpenSSL 1.0.0. */
100
101
102
static int should_use_openssl_CTR = 0;
#endif

103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/** Check whether we should use the EVP interface for AES. If <b>force_val</b>
 * is nonnegative, we use use EVP iff it is true.  Otherwise, we use EVP
 * if there is an engine enabled for aes-ecb. */
int
evaluate_evp_for_aes(int force_val)
{
  ENGINE *e;

  if (force_val >= 0) {
    should_use_EVP = force_val;
    return 0;
  }
#ifdef DISABLE_ENGINES
  should_use_EVP = 0;
#else
  e = ENGINE_get_cipher_engine(NID_aes_128_ecb);

  if (e) {
    log_notice(LD_CRYPTO, "AES engine \"%s\" found; using EVP_* functions.",
               ENGINE_get_name(e));
    should_use_EVP = 1;
  } else {
    log_notice(LD_CRYPTO, "No AES engine found; using AES_* functions.");
    should_use_EVP = 0;
  }
#endif

  return 0;
}

133
134
135
136
137
138
139
/** Test the OpenSSL counter mode implementation to see whether it has the
 * counter-mode bug from OpenSSL 1.0.0. If the implementation works, then
 * we will use it for future encryption/decryption operations.
 *
 * We can't just look at the OpenSSL version, since some distributions update
 * their OpenSSL packages without changing the version number.
 **/
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
int
evaluate_ctr_for_aes(void)
{
#ifdef CAN_USE_OPENSSL_CTR
  /* Result of encrypting an all-zero block with an all-zero 128-bit AES key.
   * This should be the same as encrypting an all-zero block with an all-zero
   * 128-bit AES key in counter mode, starting at position 0 of the stream.
   */
  static const unsigned char encrypt_zero[] =
    "\x66\xe9\x4b\xd4\xef\x8a\x2c\x3b\x88\x4c\xfa\x59\xca\x34\x2b\x2e";
  unsigned char zero[16];
  unsigned char output[16];
  unsigned char ivec[16];
  unsigned char ivec_tmp[16];
  unsigned int pos, i;
  AES_KEY key;
  memset(zero, 0, sizeof(zero));
  memset(ivec, 0, sizeof(ivec));
  AES_set_encrypt_key(zero, 128, &key);

  pos = 0;
  /* Encrypting a block one byte at a time should make the error manifest
   * itself for known bogus openssl versions. */
  for (i=0; i<16; ++i)
    AES_ctr128_encrypt(&zero[i], &output[i], 1, &key, ivec, ivec_tmp, &pos);

  if (memcmp(output, encrypt_zero, 16)) {
    /* Counter mode is buggy */
    log_notice(LD_CRYPTO, "This OpenSSL has a buggy version of counter mode; "
               "not using it.");
  } else {
    /* Counter mode is okay */
    log_notice(LD_CRYPTO, "This OpenSSL has a good implementation of counter "
               "mode; using it.");
    should_use_openssl_CTR = 1;
  }
#else
  log_notice(LD_CRYPTO, "This version of OpenSSL has a slow implementation of "
             "counter mode; not using it.");
#endif
  return 0;
}

183
#if !defined(USING_COUNTER_VARS)
184
185
186
187
188
#define COUNTER(c, n) ((c)->ctr_buf.buf32[3-(n)])
#else
#define COUNTER(c, n) ((c)->counter ## n)
#endif

Nick Mathewson's avatar
Nick Mathewson committed
189
190
191
192
/**
 * Helper function: set <b>cipher</b>'s internal buffer to the encrypted
 * value of the current counter.
 */
193
static INLINE void
194
195
_aes_fill_buf(aes_cnt_cipher_t *cipher)
{
196
197
198
199
200
201
  /* We don't currently use OpenSSL's counter mode implementation because:
   *  1) some versions have known bugs
   *  2) its attitude towards IVs is not our own
   *  3) changing the counter position was not trivial, last time I looked.
   * None of these issues are insurmountable in principle.
   */
202

203
  if (cipher->using_evp) {
204
    int outl=16, inl=16;
205
    EVP_EncryptUpdate(&cipher->key.evp, cipher->buf, &outl,
206
                      cipher->ctr_buf.buf, inl);
207
208
  } else {
    AES_encrypt(cipher->ctr_buf.buf, cipher->buf, &cipher->key.aes);
209
  }
210
211
}

Nick Mathewson's avatar
Nick Mathewson committed
212
213
214
/**
 * Return a newly allocated counter-mode AES128 cipher implementation.
 */
215
aes_cnt_cipher_t*
216
aes_new_cipher(void)
217
{
218
  aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));
219
220
221
222

  return result;
}

Nick Mathewson's avatar
Nick Mathewson committed
223
224
225
226
/** Set the key of <b>cipher</b> to <b>key</b>, which is
 * <b>key_bits</b> bits long (must be 128, 192, or 256).  Also resets
 * the counter to 0.
 */
227
void
228
aes_set_key(aes_cnt_cipher_t *cipher, const char *key, int key_bits)
229
{
230
231
232
233
234
235
236
237
238
239
240
241
242
  if (should_use_EVP) {
    const EVP_CIPHER *c;
    switch (key_bits) {
      case 128: c = EVP_aes_128_ecb(); break;
      case 192: c = EVP_aes_192_ecb(); break;
      case 256: c = EVP_aes_256_ecb(); break;
      default: tor_assert(0);
    }
    EVP_EncryptInit(&cipher->key.evp, c, (const unsigned char*)key, NULL);
    cipher->using_evp = 1;
  } else {
    AES_set_encrypt_key((const unsigned char *)key, key_bits, &cipher->key.aes);
    cipher->using_evp = 0;
243
  }
244

245
246
247
248
249
250
#ifdef USING_COUNTER_VARS
  cipher->counter0 = 0;
  cipher->counter1 = 0;
  cipher->counter2 = 0;
  cipher->counter3 = 0;
#endif
251

252
253
  memset(cipher->ctr_buf.buf, 0, sizeof(cipher->ctr_buf.buf));

254
  cipher->pos = 0;
255

256
257
258
259
#ifdef CAN_USE_OPENSSL_CTR
  if (should_use_openssl_CTR)
    memset(cipher->buf, 0, sizeof(cipher->buf));
  else
260
#endif
261
    _aes_fill_buf(cipher);
262
263
}

Nick Mathewson's avatar
Nick Mathewson committed
264
265
/** Release storage held by <b>cipher</b>
 */
266
void
267
aes_cipher_free(aes_cnt_cipher_t *cipher)
268
{
269
270
  if (!cipher)
    return;
271
272
273
  if (cipher->using_evp) {
    EVP_CIPHER_CTX_cleanup(&cipher->key.evp);
  }
274
  memset(cipher, 0, sizeof(aes_cnt_cipher_t));
275
  tor_free(cipher);
276
277
}

278
#if defined(USING_COUNTER_VARS)
279
280
281
#define UPDATE_CTR_BUF(c, n) STMT_BEGIN                 \
  (c)->ctr_buf.buf32[3-(n)] = htonl((c)->counter ## n); \
  STMT_END
282
283
#else
#define UPDATE_CTR_BUF(c, n)
284
285
#endif

286
#ifdef CAN_USE_OPENSSL_CTR
287
288
289
290
291
292
293
294
295
296
297
/* Helper function to use EVP with openssl's counter-mode wrapper. */
static void evp_block128_fn(const uint8_t in[16],
                            uint8_t out[16],
                            const void *key)
{
  EVP_CIPHER_CTX *ctx = (void*)key;
  int inl=16, outl=16;
  EVP_EncryptUpdate(ctx, out, &outl, in, inl);
}
#endif

Nick Mathewson's avatar
Nick Mathewson committed
298
299
300
301
/** Encrypt <b>len</b> bytes from <b>input</b>, storing the result in
 * <b>output</b>.  Uses the key in <b>cipher</b>, and advances the counter
 * by <b>len</b> bytes as it encrypts.
 */
302
void
303
304
aes_crypt(aes_cnt_cipher_t *cipher, const char *input, size_t len,
          char *output)
305
{
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#ifdef CAN_USE_OPENSSL_CTR
  if (should_use_openssl_CTR) {
    if (cipher->using_evp) {
      /* In openssl 1.0.0, there's an if'd out EVP_aes_128_ctr in evp.h.  If
       * it weren't disabled, it might be better just to use that.
       */
      CRYPTO_ctr128_encrypt((const unsigned char *)input,
                            (unsigned char *)output,
                            len,
                            &cipher->key.evp,
                            cipher->ctr_buf.buf,
                            cipher->buf,
                            &cipher->pos,
                            evp_block128_fn);
    } else {
      AES_ctr128_encrypt((const unsigned char *)input,
                         (unsigned char *)output,
                         len,
                         &cipher->key.aes,
                         cipher->ctr_buf.buf,
                         cipher->buf,
                         &cipher->pos);
    }
    return;
330
  }
331
332
333
  else
#endif
  {
Nick Mathewson's avatar
Nick Mathewson committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
    int c = cipher->pos;
    if (PREDICT_UNLIKELY(!len)) return;

    while (1) {
      do {
        if (len-- == 0) { cipher->pos = c; return; }
        *(output++) = *(input++) ^ cipher->buf[c];
      } while (++c != 16);
      cipher->pos = c = 0;
      if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
        if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
          if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
            ++COUNTER(cipher, 3);
            UPDATE_CTR_BUF(cipher, 3);
          }
          UPDATE_CTR_BUF(cipher, 2);
350
        }
Nick Mathewson's avatar
Nick Mathewson committed
351
        UPDATE_CTR_BUF(cipher, 1);
352
      }
Nick Mathewson's avatar
Nick Mathewson committed
353
354
      UPDATE_CTR_BUF(cipher, 0);
      _aes_fill_buf(cipher);
355
    }
356
  }
357
358
}

359
360
361
362
363
364
365
/** Encrypt <b>len</b> bytes from <b>input</b>, storing the results in place.
 * Uses the key in <b>cipher</b>, and advances the counter by <b>len</b> bytes
 * as it encrypts.
 */
void
aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data, size_t len)
{
366
367
368
369
370
371
372
373
#ifdef CAN_USE_OPENSSL_CTR
  if (should_use_openssl_CTR) {
    aes_crypt(cipher, data, len, data);
    return;
  }
  else
#endif
  {
Nick Mathewson's avatar
Nick Mathewson committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
    int c = cipher->pos;
    if (PREDICT_UNLIKELY(!len)) return;

    while (1) {
      do {
        if (len-- == 0) { cipher->pos = c; return; }
        *(data++) ^= cipher->buf[c];
      } while (++c != 16);
      cipher->pos = c = 0;
      if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 0))) {
        if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 1))) {
          if (PREDICT_UNLIKELY(! ++COUNTER(cipher, 2))) {
            ++COUNTER(cipher, 3);
            UPDATE_CTR_BUF(cipher, 3);
          }
          UPDATE_CTR_BUF(cipher, 2);
390
        }
Nick Mathewson's avatar
Nick Mathewson committed
391
        UPDATE_CTR_BUF(cipher, 1);
392
      }
Nick Mathewson's avatar
Nick Mathewson committed
393
394
      UPDATE_CTR_BUF(cipher, 0);
      _aes_fill_buf(cipher);
395
    }
396
  }
397
398
}

399
400
/** Reset the 128-bit counter of <b>cipher</b> to the 16-bit big-endian value
 * in <b>iv</b>. */
401
402
403
void
aes_set_iv(aes_cnt_cipher_t *cipher, const char *iv)
{
404
#ifdef USING_COUNTER_VARS
405
406
407
408
  cipher->counter3 = ntohl(get_uint32(iv));
  cipher->counter2 = ntohl(get_uint32(iv+4));
  cipher->counter1 = ntohl(get_uint32(iv+8));
  cipher->counter0 = ntohl(get_uint32(iv+12));
409
#endif
410
  cipher->pos = 0;
411
  memcpy(cipher->ctr_buf.buf, iv, 16);
412

413
414
#ifdef CAN_USE_OPENSSL_CTR
  if (!should_use_openssl_CTR)
415
#endif
416
    _aes_fill_buf(cipher);
417
418
}