crypto_curve25519.c 12.1 KB
Newer Older
1
/* Copyright (c) 2012-2015, The Tor Project, Inc. */
2
3
4
5
6
7
/* See LICENSE for licensing information */

/* Wrapper code for a curve25519 implementation. */

#define CRYPTO_CURVE25519_PRIVATE
#include "orconfig.h"
8
9
10
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
11
#include "container.h"
12
13
14
#include "crypto.h"
#include "crypto_curve25519.h"
#include "util.h"
15
#include "torlog.h"
16

17
18
#include "ed25519/donna/ed25519_donna_tor.h"

19
20
21
22
23
24
25
26
27
/* ==============================
   Part 1: wrap a suitable curve25519 implementation as curve25519_impl
   ============================== */

#ifdef USE_CURVE25519_DONNA
int curve25519_donna(uint8_t *mypublic,
                     const uint8_t *secret, const uint8_t *basepoint);
#endif
#ifdef USE_CURVE25519_NACL
28
#ifdef HAVE_CRYPTO_SCALARMULT_CURVE25519_H
29
#include <crypto_scalarmult_curve25519.h>
30
31
32
#elif defined(HAVE_NACL_CRYPTO_SCALARMULT_CURVE25519_H)
#include <nacl/crypto_scalarmult_curve25519.h>
#endif
33
34
#endif

35
36
37
38
static void pick_curve25519_basepoint_impl(void);

static int curve25519_use_ed = -1;

39
STATIC int
40
41
42
curve25519_impl(uint8_t *output, const uint8_t *secret,
                const uint8_t *basepoint)
{
43
44
45
46
47
  uint8_t bp[CURVE25519_PUBKEY_LEN];
  int r;
  memcpy(bp, basepoint, CURVE25519_PUBKEY_LEN);
  /* Clear the high bit, in case our backend foolishly looks at it. */
  bp[31] &= 0x7f;
48
#ifdef USE_CURVE25519_DONNA
49
  r = curve25519_donna(output, secret, bp);
50
#elif defined(USE_CURVE25519_NACL)
51
  r = crypto_scalarmult_curve25519(output, secret, bp);
52
53
54
#else
#error "No implementation of curve25519 is available."
#endif
55
56
  memwipe(bp, 0, sizeof(bp));
  return r;
57
58
}

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
STATIC int
curve25519_basepoint_impl(uint8_t *output, const uint8_t *secret)
{
  int r = 0;
  if (PREDICT_UNLIKELY(curve25519_use_ed == -1)) {
    pick_curve25519_basepoint_impl();
  }

  /* TODO: Someone should benchmark curved25519_scalarmult_basepoint versus
   * an optimized NaCl build to see which should be used when compiled with
   * NaCl available.  I suspected that the ed25519 optimization always wins.
   */
  if (PREDICT_LIKELY(curve25519_use_ed == 1)) {
    curved25519_scalarmult_basepoint_donna(output, secret);
    r = 0;
  } else {
    static const uint8_t basepoint[32] = {9};
    r = curve25519_impl(output, secret, basepoint);
  }
  return r;
}

void
curve25519_set_impl_params(int use_ed)
{
  curve25519_use_ed = use_ed;
}

87
88
89
90
91
92
93
94
95
96
97
/* ==============================
   Part 2: Wrap curve25519_impl with some convenience types and functions.
   ============================== */

/**
 * Return true iff a curve25519_public_key_t seems valid. (It's not necessary
 * to see if the point is on the curve, since the twist is also secure, but we
 * do need to make sure that it isn't the point at infinity.) */
int
curve25519_public_key_is_ok(const curve25519_public_key_t *key)
{
98
  return !safe_mem_is_zero(key->public_key, CURVE25519_PUBKEY_LEN);
99
100
}

101
102
103
104
105
106
107
108
109
/**
 * Generate CURVE25519_SECKEY_LEN random bytes in <b>out</b>. If
 * <b>extra_strong</b> is true, this key is possibly going to get used more
 * than once, so use a better-than-usual RNG. Return 0 on success, -1 on
 * failure.
 *
 * This function does not adjust the output of the RNG at all; the will caller
 * will need to clear or set the appropriate bits to make curve25519 work.
 */
110
int
111
curve25519_rand_seckey_bytes(uint8_t *out, int extra_strong)
112
{
113
  uint8_t k_tmp[CURVE25519_SECKEY_LEN];
114

115
  if (crypto_rand((char*)out, CURVE25519_SECKEY_LEN) < 0)
116
    return -1;
117
118
  if (extra_strong && !crypto_strongest_rand(k_tmp, CURVE25519_SECKEY_LEN)) {
    /* If they asked for extra-strong entropy and we have some, use it as an
119
     * HMAC key to improve not-so-good entropy rather than using it directly,
120
     * just in case the extra-strong entropy is less amazing than we hoped. */
121
122
123
    crypto_hmac_sha256((char*) out,
                       (const char *)k_tmp, sizeof(k_tmp),
                       (const char *)out, CURVE25519_SECKEY_LEN);
124
125
  }
  memwipe(k_tmp, 0, sizeof(k_tmp));
126
127
128
129
130
131
132
133
134
135
136
137
138
  return 0;
}

/** Generate a new keypair and return the secret key.  If <b>extra_strong</b>
 * is true, this key is possibly going to get used more than once, so
 * use a better-than-usual RNG. Return 0 on success, -1 on failure. */
int
curve25519_secret_key_generate(curve25519_secret_key_t *key_out,
                               int extra_strong)
{
  if (curve25519_rand_seckey_bytes(key_out->secret_key, extra_strong) < 0)
    return -1;

139
140
141
  key_out->secret_key[0] &= 248;
  key_out->secret_key[31] &= 127;
  key_out->secret_key[31] |= 64;
142
143

  return 0;
144
145
146
147
148
149
}

void
curve25519_public_key_generate(curve25519_public_key_t *key_out,
                               const curve25519_secret_key_t *seckey)
{
150
  curve25519_basepoint_impl(key_out->public_key, seckey->secret_key);
151
152
}

153
int
154
155
156
curve25519_keypair_generate(curve25519_keypair_t *keypair_out,
                            int extra_strong)
{
157
158
  if (curve25519_secret_key_generate(&keypair_out->seckey, extra_strong) < 0)
    return -1;
159
  curve25519_public_key_generate(&keypair_out->pubkey, &keypair_out->seckey);
160
  return 0;
161
162
}

163
164
165
166
167
168
169
/** Write the <b>datalen</b> bytes from <b>data</b> to the file named
 * <b>fname</b> in the tagged-data format.  This format contains a
 * 32-byte header, followed by the data itself.  The header is the
 * NUL-padded string "== <b>typestring</b>: <b>tag</b> ==".  The length
 * of <b>typestring</b> and <b>tag</b> must therefore be no more than
 * 24.
 **/
170
int
171
172
173
174
175
crypto_write_tagged_contents_to_file(const char *fname,
                                     const char *typestring,
                                     const char *tag,
                                     const uint8_t *data,
                                     size_t datalen)
176
{
177
178
179
180
  char header[32];
  smartlist_t *chunks = smartlist_new();
  sized_chunk_t ch0, ch1;
  int r = -1;
181

182
183
184
185
186
187
188
189
190
191
  memset(header, 0, sizeof(header));
  if (tor_snprintf(header, sizeof(header),
                   "== %s: %s ==", typestring, tag) < 0)
    goto end;
  ch0.bytes = header;
  ch0.len = 32;
  ch1.bytes = (const char*) data;
  ch1.len = datalen;
  smartlist_add(chunks, &ch0);
  smartlist_add(chunks, &ch1);
192

193
  r = write_chunks_to_file(fname, chunks, 1, 0);
194

195
196
 end:
  smartlist_free(chunks);
197
198
199
  return r;
}

200
201
202
203
/** Read a tagged-data file from <b>fname</b> into the
 * <b>data_out_len</b>-byte buffer in <b>data_out</b>. Check that the
 * typestring matches <b>typestring</b>; store the tag into a newly allocated
 * string in <b>tag_out</b>. Return -1 on failure, and the number of bytes of
204
 * data on success.  Preserves the errno from reading the file. */
205
206
207
208
209
210
ssize_t
crypto_read_tagged_contents_from_file(const char *fname,
                                      const char *typestring,
                                      char **tag_out,
                                      uint8_t *data_out,
                                      ssize_t data_out_len)
211
212
{
  char prefix[33];
213
  char *content = NULL;
214
  struct stat st;
215
  ssize_t r = -1;
Nick Mathewson's avatar
Nick Mathewson committed
216
  size_t st_size = 0;
217
  int saved_errno = 0;
218
219
220
221

  *tag_out = NULL;
  st.st_size = 0;
  content = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
222
223
  if (! content) {
    saved_errno = errno;
224
    goto end;
225
226
227
  }
  if (st.st_size < 32 || st.st_size > 32 + data_out_len) {
    saved_errno = EINVAL;
228
    goto end;
229
  }
230
  st_size = (size_t)st.st_size;
231
232

  memcpy(prefix, content, 32);
233
234
235
  prefix[32] = 0;
  /* Check type, extract tag. */
  if (strcmpstart(prefix, "== ") || strcmpend(prefix, " ==") ||
236
237
      ! tor_mem_is_zero(prefix+strlen(prefix), 32-strlen(prefix))) {
    saved_errno = EINVAL;
238
    goto end;
239
  }
240

241
242
  if (strcmpstart(prefix+3, typestring) ||
      3+strlen(typestring) >= 32 ||
243
244
      strcmpstart(prefix+3+strlen(typestring), ": ")) {
    saved_errno = EINVAL;
245
    goto end;
246
  }
247
248
249
250

  *tag_out = tor_strndup(prefix+5+strlen(typestring),
                         strlen(prefix)-8-strlen(typestring));

251
252
  memcpy(data_out, content+32, st_size-32);
  r = st_size - 32;
253
254
255

 end:
  if (content)
256
    memwipe(content, 0, st_size);
257
  tor_free(content);
258
259
  if (saved_errno)
    errno = saved_errno;
260
261
262
263
264
265
266
267
268
269
270
  return r;
}

/** DOCDOC */
int
curve25519_keypair_write_to_file(const curve25519_keypair_t *keypair,
                                 const char *fname,
                                 const char *tag)
{
  uint8_t contents[CURVE25519_SECKEY_LEN + CURVE25519_PUBKEY_LEN];
  int r;
271

272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
  memcpy(contents, keypair->seckey.secret_key, CURVE25519_SECKEY_LEN);
  memcpy(contents+CURVE25519_SECKEY_LEN,
         keypair->pubkey.public_key, CURVE25519_PUBKEY_LEN);

  r = crypto_write_tagged_contents_to_file(fname,
                                           "c25519v1",
                                           tag,
                                           contents,
                                           sizeof(contents));

  memwipe(contents, 0, sizeof(contents));
  return r;
}

/** DOCDOC */
int
curve25519_keypair_read_from_file(curve25519_keypair_t *keypair_out,
                                  char **tag_out,
                                  const char *fname)
{
  uint8_t content[CURVE25519_SECKEY_LEN + CURVE25519_PUBKEY_LEN];
  ssize_t len;
  int r = -1;

  len = crypto_read_tagged_contents_from_file(fname, "c25519v1", tag_out,
                                              content, sizeof(content));
  if (len != sizeof(content))
    goto end;

  memcpy(keypair_out->seckey.secret_key, content, CURVE25519_SECKEY_LEN);
302
303
  curve25519_public_key_generate(&keypair_out->pubkey, &keypair_out->seckey);
  if (tor_memneq(keypair_out->pubkey.public_key,
304
                 content + CURVE25519_SECKEY_LEN,
305
306
307
308
309
310
                 CURVE25519_PUBKEY_LEN))
    goto end;

  r = 0;

 end:
311
  memwipe(content, 0, sizeof(content));
312
313
314
315
316
317
318
  if (r != 0) {
    memset(keypair_out, 0, sizeof(*keypair_out));
    tor_free(*tag_out);
  }
  return r;
}

319
320
321
322
323
324
325
326
327
328
/** Perform the curve25519 ECDH handshake with <b>skey</b> and <b>pkey</b>,
 * writing CURVE25519_OUTPUT_LEN bytes of output into <b>output</b>. */
void
curve25519_handshake(uint8_t *output,
                     const curve25519_secret_key_t *skey,
                     const curve25519_public_key_t *pkey)
{
  curve25519_impl(output, skey->secret_key, pkey->public_key);
}

329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/** Check whether the ed25519-based curve25519 basepoint optimization seems to
 * be working. If so, return 0; otherwise return -1. */
static int
curve25519_basepoint_spot_check(void)
{
  static const uint8_t alicesk[32] = {
    0x77,0x07,0x6d,0x0a,0x73,0x18,0xa5,0x7d,
    0x3c,0x16,0xc1,0x72,0x51,0xb2,0x66,0x45,
    0xdf,0x4c,0x2f,0x87,0xeb,0xc0,0x99,0x2a,
    0xb1,0x77,0xfb,0xa5,0x1d,0xb9,0x2c,0x2a
  };
  static const uint8_t alicepk[32] = {
    0x85,0x20,0xf0,0x09,0x89,0x30,0xa7,0x54,
    0x74,0x8b,0x7d,0xdc,0xb4,0x3e,0xf7,0x5a,
    0x0d,0xbf,0x3a,0x0d,0x26,0x38,0x1a,0xf4,
    0xeb,0xa4,0xa9,0x8e,0xaa,0x9b,0x4e,0x6a
  };
  const int loop_max=200;
  int save_use_ed = curve25519_use_ed;
  unsigned char e1[32] = { 5 };
  unsigned char e2[32] = { 5 };
  unsigned char x[32],y[32];
  int i;
  int r=0;

  /* Check the most basic possible sanity via the test secret/public key pair
   * used in "Cryptography in NaCl - 2. Secret keys and public keys".  This
Nick Mathewson's avatar
Nick Mathewson committed
356
   * may catch catastrophic failures on systems where Curve25519 is expensive,
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
   * without requiring a ton of key generation.
   */
  curve25519_use_ed = 1;
  r |= curve25519_basepoint_impl(x, alicesk);
  if (fast_memneq(x, alicepk, 32))
    goto fail;

  /* Ok, the optimization appears to produce passable results, try a few more
   * values, maybe there's something subtle wrong.
   */
  for (i = 0; i < loop_max; ++i) {
    curve25519_use_ed = 0;
    r |= curve25519_basepoint_impl(x, e1);
    curve25519_use_ed = 1;
    r |= curve25519_basepoint_impl(y, e2);
    if (fast_memneq(x,y,32))
      goto fail;
    memcpy(e1, x, 32);
    memcpy(e2, x, 32);
  }

  goto end;
 fail:
  r = -1;
 end:
  curve25519_use_ed = save_use_ed;
  return r;
}

/** Choose whether to use the ed25519-based curve25519-basepoint
 * implementation. */
static void
pick_curve25519_basepoint_impl(void)
{
  curve25519_use_ed = 1;

  if (curve25519_basepoint_spot_check() == 0)
    return;

  log_warn(LD_CRYPTO, "The ed25519-based curve25519 basepoint "
           "multiplication seems broken; using the curve25519 "
           "implementation.");
  curve25519_use_ed = 0;
}

/** Initialize the curve25519 implementations. This is necessary if you're
 * going to use them in a multithreaded setting, and not otherwise. */
void
curve25519_init(void)
{
  pick_curve25519_basepoint_impl();
}