router.c 127 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
2
/* Copyright (c) 2001 Matej Pfajfar.
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
Nick Mathewson's avatar
Nick Mathewson committed
4
 * Copyright (c) 2007-2018, The Tor Project, Inc. */
5
6
/* See LICENSE for licensing information */

7
8
#define ROUTER_PRIVATE

9
10
11
12
13
14
15
#include "core/or/or.h"
#include "core/or/circuitbuild.h"
#include "core/or/circuitlist.h"
#include "core/or/circuituse.h"
#include "app/config/config.h"
#include "core/mainloop/connection.h"
#include "feature/control/control.h"
16
17
18
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_util.h"
#include "lib/crypt_ops/crypto_curve25519.h"
19
20
21
22
23
24
25
26
27
#include "feature/dircache/directory.h"
#include "feature/dircache/dirserv.h"
#include "feature/relay/dns.h"
#include "feature/stats/geoip.h"
#include "feature/hibernate/hibernate.h"
#include "core/mainloop/main.h"
#include "feature/nodelist/networkstatus.h"
#include "feature/nodelist/nodelist.h"
#include "core/or/policies.h"
28
#include "core/or/protover.h"
29
30
31
32
33
34
35
36
37
38
#include "core/or/relay.h"
#include "feature/stats/rephist.h"
#include "feature/relay/router.h"
#include "feature/relay/routerkeys.h"
#include "feature/nodelist/routerlist.h"
#include "feature/nodelist/routerparse.h"
#include "app/config/statefile.h"
#include "feature/nodelist/torcert.h"
#include "feature/client/transports.h"
#include "feature/nodelist/routerset.h"
39

40
#include "feature/dirauth/mode.h"
41

42
43
44
45
46
47
48
49
50
51
52
#include "feature/nodelist/authority_cert_st.h"
#include "core/or/crypt_path_st.h"
#include "feature/dircommon/dir_connection_st.h"
#include "feature/dirclient/dir_server_st.h"
#include "core/or/extend_info_st.h"
#include "feature/nodelist/extrainfo_st.h"
#include "feature/nodelist/node_st.h"
#include "core/or/origin_circuit_st.h"
#include "app/config/or_state_st.h"
#include "core/or/port_cfg_st.h"
#include "feature/nodelist/routerinfo_st.h"
53

54
#include "lib/osinfo/uname.h"
55
56
#include "lib/tls/tortls.h"
#include "lib/encoding/confline.h"
57
#include "lib/crypt_ops/crypto_format.h"
58

Roger Dingledine's avatar
Roger Dingledine committed
59
60
/**
 * \file router.c
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
 * \brief Miscellaneous relay functionality, including RSA key maintenance,
 * generating and uploading server descriptors, picking an address to
 * advertise, and so on.
 *
 * This module handles the job of deciding whether we are a Tor relay, and if
 * so what kind. (Mostly through functions like server_mode() that inspect an
 * or_options_t, but in some cases based on our own capabilities, such as when
 * we are deciding whether to be a directory cache in
 * router_has_bandwidth_to_be_dirserver().)
 *
 * Also in this module are the functions to generate our own routerinfo_t and
 * extrainfo_t, and to encode those to signed strings for upload to the
 * directory authorities.
 *
 * This module also handles key maintenance for RSA and Curve25519-ntor keys,
 * and for our TLS context. (These functions should eventually move to
 * routerkeys.c along with the code that handles Ed25519 keys now.)
Roger Dingledine's avatar
Roger Dingledine committed
78
 **/
Nick Mathewson's avatar
Nick Mathewson committed
79

80
81
/************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
82
83
84
85
/*****
 * Key management: ORs only.
 *****/

Roger Dingledine's avatar
Roger Dingledine committed
86
/** Private keys for this OR.  There is also an SSL key managed by tortls.c.
Nick Mathewson's avatar
Nick Mathewson committed
87
 */
88
static tor_mutex_t *key_lock=NULL;
89
static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
90
/** Current private onionskin decryption key: used to decode CREATE cells. */
91
static crypto_pk_t *onionkey=NULL;
Nick Mathewson's avatar
Nick Mathewson committed
92
/** Previous private onionskin decryption key: used to decode CREATE cells
Roger Dingledine's avatar
Roger Dingledine committed
93
 * generated by clients that have an older version of our descriptor. */
94
static crypto_pk_t *lastonionkey=NULL;
95
/** Current private ntor secret key: used to perform the ntor handshake. */
96
static curve25519_keypair_t curve25519_onion_key;
97
98
/** Previous private ntor secret key: used to perform the ntor handshake
 * with clients that have an older version of our descriptor. */
99
static curve25519_keypair_t last_curve25519_onion_key;
100
/** Private server "identity key": used to sign directory info and TLS
101
 * certificates. Never changes. */
102
static crypto_pk_t *server_identitykey=NULL;
103
104
105
106
107
/** Digest of server_identitykey. */
static char server_identitykey_digest[DIGEST_LEN];
/** Private client "identity key": used to sign bridges' and clients'
 * outbound TLS certificates. Regenerated on startup and on IP address
 * change. */
108
static crypto_pk_t *client_identitykey=NULL;
109
/** Signing key used for v3 directory material; only set for authorities. */
110
static crypto_pk_t *authority_signing_key = NULL;
111
112
113
/** Key certificate to authenticate v3 directory material; only set for
 * authorities. */
static authority_cert_t *authority_key_certificate = NULL;
114

115
116
/** For emergency V3 authority key migration: An extra signing key that we use
 * with our old (obsolete) identity key for a while. */
117
static crypto_pk_t *legacy_signing_key = NULL;
118
119
/** For emergency V3 authority key migration: An extra certificate to
 * authenticate legacy_signing_key with our obsolete identity key.*/
120
121
static authority_cert_t *legacy_key_certificate = NULL;

122
123
124
125
126
/* (Note that v3 authorities also have a separate "authority identity key",
 * but this key is never actually loaded by the Tor process.  Instead, it's
 * used by tor-gencert to sign new signing keys and make new key
 * certificates. */

127
128
129
130
131
132
133
const char *format_node_description(char *buf,
                                    const char *id_digest,
                                    int is_named,
                                    const char *nickname,
                                    const tor_addr_t *addr,
                                    uint32_t addr32h);

134
135
136
137
/** Return a readonly string with human readable description
 * of <b>err</b>.
 */
const char *
rl1987's avatar
rl1987 committed
138
routerinfo_err_to_string(int err)
139
140
141
142
143
144
145
146
147
148
149
150
{
  switch (err) {
    case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
      return "No known exit address yet";
    case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
      return "Cannot parse descriptor";
    case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
      return "Not running in server mode";
    case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
      return "Key digest failed";
    case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
      return "Cannot generate descriptor";
rl1987's avatar
rl1987 committed
151
152
    case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
      return "Descriptor still rebuilding - not ready yet";
153
154
  }

rl1987's avatar
rl1987 committed
155
156
  log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
  tor_assert_unreached();
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

  return "Unknown error";
}

/** Return true if we expect given error to be transient.
 * Return false otherwise.
 */
int
routerinfo_err_is_transient(int err)
{
  switch (err) {
    case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
      return 1;
    case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
      return 1;
    case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
      return 0;
    case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
      return 0; // XXX: bug?
    case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
      return 1;
rl1987's avatar
rl1987 committed
178
    case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
179
180
181
182
183
184
      return 1;
  }

  return 0;
}

185
186
/** Replace the current onion key with <b>k</b>.  Does not affect
 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
Nick Mathewson's avatar
Nick Mathewson committed
187
 */
188
static void
189
set_onion_key(crypto_pk_t *k)
190
{
191
  if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
192
    /* k is already our onion key; free it and return */
193
    crypto_pk_free(k);
194
195
    return;
  }
196
  tor_mutex_acquire(key_lock);
197
  crypto_pk_free(onionkey);
198
  onionkey = k;
199
  tor_mutex_release(key_lock);
200
  mark_my_descriptor_dirty("set onion key");
201
202
}

Roger Dingledine's avatar
Roger Dingledine committed
203
/** Return the current onion key.  Requires that the onion key has been
Nick Mathewson's avatar
Nick Mathewson committed
204
 * loaded or generated. */
205
crypto_pk_t *
206
207
get_onion_key(void)
{
Roger Dingledine's avatar
Roger Dingledine committed
208
  tor_assert(onionkey);
209
210
211
  return onionkey;
}

212
/** Store a full copy of the current onion key into *<b>key</b>, and a full
213
214
 * copy of the most recent onion key into *<b>last</b>.  Store NULL into
 * a pointer if the corresponding key does not exist.
215
 */
216
void
217
dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
218
{
219
220
  tor_assert(key);
  tor_assert(last);
221
  tor_mutex_acquire(key_lock);
222
223
224
  if (onionkey)
    *key = crypto_pk_copy_full(onionkey);
  else
225
    *key = NULL;
226
  if (lastonionkey)
227
    *last = crypto_pk_copy_full(lastonionkey);
228
229
230
231
232
  else
    *last = NULL;
  tor_mutex_release(key_lock);
}

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/** Expire our old set of onion keys. This is done by setting
 * last_curve25519_onion_key and lastonionkey to all zero's and NULL
 * respectively.
 *
 * This function does not perform any grace period checks for the old onion
 * keys.
 */
void
expire_old_onion_keys(void)
{
  char *fname = NULL;

  tor_mutex_acquire(key_lock);

  /* Free lastonionkey and set it to NULL. */
  if (lastonionkey) {
    crypto_pk_free(lastonionkey);
    lastonionkey = NULL;
  }

  /* We zero out the keypair. See the tor_mem_is_zero() check made in
   * construct_ntor_key_map() below. */
  memset(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));

  tor_mutex_release(key_lock);

259
  fname = get_keydir_fname("secret_onion_key.old");
260
261
262
263
264
265
266
267
  if (file_status(fname) == FN_FILE) {
    if (tor_unlink(fname) != 0) {
      log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
               fname, strerror(errno));
    }
  }
  tor_free(fname);

268
  fname = get_keydir_fname("secret_onion_key_ntor.old");
269
270
271
272
273
274
275
276
277
  if (file_status(fname) == FN_FILE) {
    if (tor_unlink(fname) != 0) {
      log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
               fname, strerror(errno));
    }
  }
  tor_free(fname);
}

278
279
/** Return the current secret onion key for the ntor handshake. Must only
 * be called from the main thread. */
280
281
282
283
284
static const curve25519_keypair_t *
get_current_curve25519_keypair(void)
{
  return &curve25519_onion_key;
}
285
286
/** Return a map from KEYID (the key itself) to keypairs for use in the ntor
 * handshake. Must only be called from the main thread. */
287
288
289
290
291
di_digest256_map_t *
construct_ntor_key_map(void)
{
  di_digest256_map_t *m = NULL;

292
293
294
295
296
297
298
299
  if (!tor_mem_is_zero((const char*)
                       curve25519_onion_key.pubkey.public_key,
                       CURVE25519_PUBKEY_LEN)) {
    dimap_add_entry(&m,
                    curve25519_onion_key.pubkey.public_key,
                    tor_memdup(&curve25519_onion_key,
                               sizeof(curve25519_keypair_t)));
  }
300
301
302
303
304
305
306
307
308
309
310
  if (!tor_mem_is_zero((const char*)
                          last_curve25519_onion_key.pubkey.public_key,
                       CURVE25519_PUBKEY_LEN)) {
    dimap_add_entry(&m,
                    last_curve25519_onion_key.pubkey.public_key,
                    tor_memdup(&last_curve25519_onion_key,
                               sizeof(curve25519_keypair_t)));
  }

  return m;
}
311
312
/** Helper used to deallocate a di_digest256_map_t returned by
 * construct_ntor_key_map. */
313
314
315
316
317
318
319
static void
ntor_key_map_free_helper(void *arg)
{
  curve25519_keypair_t *k = arg;
  memwipe(k, 0, sizeof(*k));
  tor_free(k);
}
320
/** Release all storage from a keymap returned by construct_ntor_key_map. */
321
void
322
ntor_key_map_free_(di_digest256_map_t *map)
323
{
324
325
  if (!map)
    return;
326
327
328
  dimap_free(map, ntor_key_map_free_helper);
}

Roger Dingledine's avatar
Roger Dingledine committed
329
/** Return the time when the onion key was last set.  This is either the time
Nick Mathewson's avatar
Nick Mathewson committed
330
331
332
 * when the process launched, or the time of the most recent key rotation since
 * the process launched.
 */
333
334
335
time_t
get_onion_key_set_at(void)
{
336
  return onionkey_set_at;
337
338
}

339
/** Set the current server identity key to <b>k</b>.
Nick Mathewson's avatar
Nick Mathewson committed
340
 */
341
void
342
set_server_identity_key(crypto_pk_t *k)
343
{
344
  crypto_pk_free(server_identitykey);
345
  server_identitykey = k;
346
347
348
349
350
  if (crypto_pk_get_digest(server_identitykey,
                           server_identitykey_digest) < 0) {
    log_err(LD_BUG, "Couldn't compute our own identity key digest.");
    tor_assert(0);
  }
351
352
}

353
354
355
356
357
/** Make sure that we have set up our identity keys to match or not match as
 * appropriate, and die with an assertion if we have not. */
static void
assert_identity_keys_ok(void)
{
358
359
  if (1)
    return;
360
361
362
363
  tor_assert(client_identitykey);
  if (public_server_mode(get_options())) {
    /* assert that we have set the client and server keys to be equal */
    tor_assert(server_identitykey);
364
    tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
365
366
367
  } else {
    /* assert that we have set the client and server keys to be unequal */
    if (server_identitykey)
368
      tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
369
370
371
  }
}

372
/** Returns the current server identity key; requires that the key has
373
 * been set, and that we are running as a Tor server.
Nick Mathewson's avatar
Nick Mathewson committed
374
 */
375
crypto_pk_t *
376
get_server_identity_key(void)
377
{
378
  tor_assert(server_identitykey);
379
380
  tor_assert(server_mode(get_options()));
  assert_identity_keys_ok();
381
  return server_identitykey;
382
383
}

Nick Mathewson's avatar
Nick Mathewson committed
384
385
/** Return true iff we are a server and the server identity key
 * has been set. */
386
int
387
server_identity_key_is_set(void)
388
{
389
  return server_mode(get_options()) && server_identitykey != NULL;
390
391
392
393
394
}

/** Set the current client identity key to <b>k</b>.
 */
void
395
set_client_identity_key(crypto_pk_t *k)
396
{
397
  crypto_pk_free(client_identitykey);
398
399
400
  client_identitykey = k;
}

401
402
/** Returns the current client identity key for use on outgoing TLS
 * connections; requires that the key has been set.
403
 */
404
crypto_pk_t *
405
get_tlsclient_identity_key(void)
406
407
{
  tor_assert(client_identitykey);
408
  assert_identity_keys_ok();
409
410
411
412
413
414
415
416
  return client_identitykey;
}

/** Return true iff the client identity key has been set. */
int
client_identity_key_is_set(void)
{
  return client_identitykey != NULL;
417
418
}

419
420
/** Return the key certificate for this v3 (voting) authority, or NULL
 * if we have no such certificate. */
421
422
MOCK_IMPL(authority_cert_t *,
get_my_v3_authority_cert, (void))
423
424
425
426
{
  return authority_key_certificate;
}

427
428
/** Return the v3 signing key for this v3 (voting) authority, or NULL
 * if we have no such key. */
429
crypto_pk_t *
430
431
432
433
434
get_my_v3_authority_signing_key(void)
{
  return authority_signing_key;
}

435
436
437
/** If we're an authority, and we're using a legacy authority identity key for
 * emergency migration purposes, return the certificate associated with that
 * key. */
438
439
440
441
442
443
authority_cert_t *
get_my_v3_legacy_cert(void)
{
  return legacy_key_certificate;
}

444
445
/** If we're an authority, and we're using a legacy authority identity key for
 * emergency migration purposes, return that key. */
446
crypto_pk_t *
447
448
449
450
451
get_my_v3_legacy_signing_key(void)
{
  return legacy_signing_key;
}

Roger Dingledine's avatar
Roger Dingledine committed
452
/** Replace the previous onion key with the current onion key, and generate
453
454
 * a new previous onion key.  Immediately after calling this function,
 * the OR should:
Roger Dingledine's avatar
Roger Dingledine committed
455
456
457
 *   - schedule all previous cpuworkers to shut down _after_ processing
 *     pending work.  (This will cause fresh cpuworkers to be generated.)
 *   - generate and upload a fresh routerinfo.
458
 */
459
460
void
rotate_onion_key(void)
461
{
462
  char *fname, *fname_prev;
463
  crypto_pk_t *prkey = NULL;
464
  or_state_t *state = get_or_state();
465
  curve25519_keypair_t new_curve25519_keypair;
466
  time_t now;
467
468
  fname = get_keydir_fname("secret_onion_key");
  fname_prev = get_keydir_fname("secret_onion_key.old");
469
  /* There isn't much point replacing an old key with an empty file */
470
471
472
473
  if (file_status(fname) == FN_FILE) {
    if (replace_file(fname, fname_prev))
      goto error;
  }
474
  if (!(prkey = crypto_pk_new())) {
475
    log_err(LD_GENERAL,"Error constructing rotated onion key");
476
477
    goto error;
  }
478
  if (crypto_pk_generate_key(prkey)) {
479
    log_err(LD_BUG,"Error generating onion key");
480
481
    goto error;
  }
482
483
484
485
486
487
  if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
    log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
    goto error;
  }
  tor_free(fname);
  tor_free(fname_prev);
488
489
  fname = get_keydir_fname("secret_onion_key_ntor");
  fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
490
491
  if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
    goto error;
492
  /* There isn't much point replacing an old key with an empty file */
493
494
495
496
  if (file_status(fname) == FN_FILE) {
    if (replace_file(fname, fname_prev))
      goto error;
  }
497
498
499
  if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
                                       "onion") < 0) {
    log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
500
501
    goto error;
  }
502
  log_info(LD_GENERAL, "Rotating onion key");
503
  tor_mutex_acquire(key_lock);
504
  crypto_pk_free(lastonionkey);
505
  lastonionkey = onionkey;
506
  onionkey = prkey;
507
508
509
510
  memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
         sizeof(curve25519_keypair_t));
  memcpy(&curve25519_onion_key, &new_curve25519_keypair,
         sizeof(curve25519_keypair_t));
511
512
  now = time(NULL);
  state->LastRotatedOnionKey = onionkey_set_at = now;
513
  tor_mutex_release(key_lock);
514
  mark_my_descriptor_dirty("rotated onion key");
515
  or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
516
  goto done;
517
 error:
518
  log_warn(LD_GENERAL, "Couldn't rotate onion key.");
519
  if (prkey)
520
    crypto_pk_free(prkey);
521
 done:
522
  memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
523
524
  tor_free(fname);
  tor_free(fname_prev);
525
526
}

527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/** Log greeting message that points to new relay lifecycle document the
 * first time this function has been called.
 */
static void
log_new_relay_greeting(void)
{
  static int already_logged = 0;

  if (already_logged)
    return;

  tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
         "Thanks for helping the Tor network! If you wish to know "
         "what will happen in the upcoming weeks regarding its usage, "
         "have a look at https://blog.torproject.org/blog/lifecycle-of"
         "-a-new-relay");

  already_logged = 1;
}

547
548
549
/** Try to read an RSA key from <b>fname</b>.  If <b>fname</b> doesn't exist
 * and <b>generate</b> is true, create a new RSA key and save it in
 * <b>fname</b>.  Return the read/created key, or NULL on error.  Log all
550
551
 * errors at level <b>severity</b>. If <b>log_greeting</b> is non-zero and a
 * new key was created, log_new_relay_greeting() is called.
552
 */
553
crypto_pk_t *
554
555
init_key_from_file(const char *fname, int generate, int severity,
                   int log_greeting)
556
{
557
  crypto_pk_t *prkey = NULL;
558

559
  if (!(prkey = crypto_pk_new())) {
560
    tor_log(severity, LD_GENERAL,"Error constructing key");
561
562
563
    goto error;
  }

564
  switch (file_status(fname)) {
565
566
    case FN_DIR:
    case FN_ERROR:
567
      tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
568
      goto error;
569
570
571
    /* treat empty key files as if the file doesn't exist, and,
     * if generate is set, replace the empty file in
     * crypto_pk_write_private_key_to_filename() */
572
    case FN_NOENT:
573
    case FN_EMPTY:
574
      if (generate) {
575
576
577
578
        if (!have_lockfile()) {
          if (try_locking(get_options(), 0)<0) {
            /* Make sure that --list-fingerprint only creates new keys
             * if there is no possibility for a deadlock. */
579
580
            tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
                    "Not writing any new keys.", fname);
581
582
583
584
585
            /*XXXX The 'other process' might make a key in a second or two;
             * maybe we should wait for it. */
            goto error;
          }
        }
586
587
588
        log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
                 fname);
        if (crypto_pk_generate_key(prkey)) {
589
          tor_log(severity, LD_GENERAL,"Error generating onion key");
590
591
592
          goto error;
        }
        if (crypto_pk_check_key(prkey) <= 0) {
593
          tor_log(severity, LD_GENERAL,"Generated key seems invalid");
594
595
596
          goto error;
        }
        log_info(LD_GENERAL, "Generated key seems valid");
597
598
599
        if (log_greeting) {
            log_new_relay_greeting();
        }
600
        if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
601
          tor_log(severity, LD_FS,
602
603
604
605
              "Couldn't write generated key to \"%s\".", fname);
          goto error;
        }
      } else {
606
607
        tor_log(severity, LD_GENERAL, "No key found in \"%s\"", fname);
        goto error;
608
609
610
611
      }
      return prkey;
    case FN_FILE:
      if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
612
        tor_log(severity, LD_GENERAL,"Error loading private key.");
613
614
615
616
617
        goto error;
      }
      return prkey;
    default:
      tor_assert(0);
618
619
620
621
  }

 error:
  if (prkey)
622
    crypto_pk_free(prkey);
623
624
625
  return NULL;
}

626
/** Load a curve25519 keypair from the file <b>fname</b>, writing it into
627
628
629
630
 * <b>keys_out</b>.  If the file isn't found, or is empty, and <b>generate</b>
 * is true, create a new keypair and write it into the file.  If there are
 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
 * in their ASCII wrapper. */
631
632
633
634
635
636
637
638
639
640
static int
init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
                                  const char *fname,
                                  int generate,
                                  int severity,
                                  const char *tag)
{
  switch (file_status(fname)) {
    case FN_DIR:
    case FN_ERROR:
641
      tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
642
      goto error;
643
644
    /* treat empty key files as if the file doesn't exist, and, if generate
     * is set, replace the empty file in curve25519_keypair_write_to_file() */
645
    case FN_NOENT:
646
    case FN_EMPTY:
647
648
649
650
651
      if (generate) {
        if (!have_lockfile()) {
          if (try_locking(get_options(), 0)<0) {
            /* Make sure that --list-fingerprint only creates new keys
             * if there is no possibility for a deadlock. */
652
653
            tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
                    "Not writing any new keys.", fname);
654
655
656
657
658
659
660
            /*XXXX The 'other process' might make a key in a second or two;
             * maybe we should wait for it. */
            goto error;
          }
        }
        log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
                 fname);
661
662
        if (curve25519_keypair_generate(keys_out, 1) < 0)
          goto error;
663
        if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
664
          tor_log(severity, LD_FS,
665
              "Couldn't write generated key to \"%s\".", fname);
666
          memwipe(keys_out, 0, sizeof(*keys_out));
667
668
669
670
671
672
673
674
675
676
          goto error;
        }
      } else {
        log_info(LD_GENERAL, "No key found in \"%s\"", fname);
      }
      return 0;
    case FN_FILE:
      {
        char *tag_in=NULL;
        if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
677
          tor_log(severity, LD_GENERAL,"Error loading private key.");
678
679
680
681
          tor_free(tag_in);
          goto error;
        }
        if (!tag_in || strcmp(tag_in, tag)) {
682
          tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
              escaped(tag_in));
          tor_free(tag_in);
          goto error;
        }
        tor_free(tag_in);
        return 0;
      }
    default:
      tor_assert(0);
  }

 error:
  return -1;
}

698
699
700
701
/** Try to load the vote-signing private key and certificate for being a v3
 * directory authority, and make sure they match.  If <b>legacy</b>, load a
 * legacy key/cert set for emergency key migration; otherwise load the regular
 * key/cert set.  On success, store them into *<b>key_out</b> and
Nick Mathewson's avatar
Nick Mathewson committed
702
 * *<b>cert_out</b> respectively, and return 0.  On failure, return -1. */
703
static int
704
load_authority_keyset(int legacy, crypto_pk_t **key_out,
705
                      authority_cert_t **cert_out)
706
{
707
  int r = -1;
708
709
  char *fname = NULL, *cert = NULL;
  const char *eos = NULL;
710
  crypto_pk_t *signing_key = NULL;
711
712
  authority_cert_t *parsed = NULL;

713
  fname = get_keydir_fname(
714
                 legacy ? "legacy_signing_key" : "authority_signing_key");
715
  signing_key = init_key_from_file(fname, 0, LOG_ERR, 0);
716
717
718
719
  if (!signing_key) {
    log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
    goto done;
  }
720
  tor_free(fname);
721
  fname = get_keydir_fname(
722
               legacy ? "legacy_certificate" : "authority_certificate");
723
724
725
726
727
728
729
730
731
732
733
  cert = read_file_to_str(fname, 0, NULL);
  if (!cert) {
    log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
               fname);
    goto done;
  }
  parsed = authority_cert_parse_from_string(cert, &eos);
  if (!parsed) {
    log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
    goto done;
  }
734
  if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
735
736
737
738
739
    log_warn(LD_DIR, "Stored signing key does not match signing key in "
             "certificate");
    goto done;
  }

740
  crypto_pk_free(*key_out);
741
742
  authority_cert_free(*cert_out);

743
744
745
  *key_out = signing_key;
  *cert_out = parsed;
  r = 0;
746
  signing_key = NULL;
747
  parsed = NULL;
748
749
750
751

 done:
  tor_free(fname);
  tor_free(cert);
752
  crypto_pk_free(signing_key);
753
  authority_cert_free(parsed);
754
  return r;
755
756
}

757
758
759
760
761
762
763
764
765
766
767
/** Load the v3 (voting) authority signing key and certificate, if they are
 * present.  Return -1 if anything is missing, mismatched, or unloadable;
 * return 0 on success. */
static int
init_v3_authority_keys(void)
{
  if (load_authority_keyset(0, &authority_signing_key,
                            &authority_key_certificate)<0)
    return -1;

  if (get_options()->V3AuthUseLegacyKey &&
768
      load_authority_keyset(1, &legacy_signing_key,
769
770
771
772
773
774
                            &legacy_key_certificate)<0)
    return -1;

  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
775
/** If we're a v3 authority, check whether we have a certificate that's
776
 * likely to expire soon.  Warn if we do, but not too often. */
777
778
779
780
781
782
783
784
785
786
787
void
v3_authority_check_key_expiry(void)
{
  time_t now, expires;
  static time_t last_warned = 0;
  int badness, time_left, warn_interval;
  if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
    return;

  now = time(NULL);
  expires = authority_key_certificate->expires;
788
  time_left = (int)( expires - now );
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
  if (time_left <= 0) {
    badness = LOG_ERR;
    warn_interval = 60*60;
  } else if (time_left <= 24*60*60) {
    badness = LOG_WARN;
    warn_interval = 60*60;
  } else if (time_left <= 24*60*60*7) {
    badness = LOG_WARN;
    warn_interval = 24*60*60;
  } else if (time_left <= 24*60*60*30) {
    badness = LOG_WARN;
    warn_interval = 24*60*60*5;
  } else {
    return;
  }

  if (last_warned + warn_interval > now)
    return;

  if (time_left <= 0) {
809
    tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
810
            " Generate a new one NOW.");
811
  } else if (time_left <= 24*60*60) {
812
813
    tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
            "hours; Generate a new one NOW.", time_left/(60*60));
814
  } else {
815
816
    tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
            "days; Generate a new one soon.", time_left/(24*60*60));
817
818
819
820
  }
  last_warned = now;
}

821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
/** Get the lifetime of an onion key in days. This value is defined by the
 * network consesus parameter "onion-key-rotation-days". Always returns a value
 * between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
 * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
 */
static int
get_onion_key_rotation_days_(void)
{
  return networkstatus_get_param(NULL,
                                 "onion-key-rotation-days",
                                 DEFAULT_ONION_KEY_LIFETIME_DAYS,
                                 MIN_ONION_KEY_LIFETIME_DAYS,
                                 MAX_ONION_KEY_LIFETIME_DAYS);
}

/** Get the current lifetime of an onion key in seconds. This value is defined
 * by the network consesus parameter "onion-key-rotation-days", but the value
 * is converted to seconds.
 */
int
get_onion_key_lifetime(void)
{
  return get_onion_key_rotation_days_()*24*60*60;
}

846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
/** Get the grace period of an onion key in seconds. This value is defined by
 * the network consesus parameter "onion-key-grace-period-days", but the value
 * is converted to seconds.
 */
int
get_onion_key_grace_period(void)
{
  int grace_period;
  grace_period = networkstatus_get_param(NULL,
                                         "onion-key-grace-period-days",
                                         DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS,
                                         MIN_ONION_KEY_GRACE_PERIOD_DAYS,
                                         get_onion_key_rotation_days_());
  return grace_period*24*60*60;
}

Nick Mathewson's avatar
Nick Mathewson committed
862
863
/** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
 * on success, and -1 on failure. */
864
865
866
int
router_initialize_tls_context(void)
{
867
868
  unsigned int flags = 0;
  const or_options_t *options = get_options();
Roger Dingledine's avatar
Roger Dingledine committed
869
  int lifetime = options->SSLKeyLifetime;
870
871
  if (public_server_mode(options))
    flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
872
  if (!lifetime) { /* we should guess a good ssl cert lifetime */
873
874

    /* choose between 5 and 365 days, and round to the day */
875
876
877
    unsigned int five_days = 5*24*3600;
    unsigned int one_year = 365*24*3600;
    lifetime = crypto_rand_int_range(five_days, one_year);
878
879
880
881
882
883
884
885
886
    lifetime -= lifetime % (24*3600);

    if (crypto_rand_int(2)) {
      /* Half the time we expire at midnight, and half the time we expire
       * one second before midnight. (Some CAs wobble their expiry times a
       * bit in practice, perhaps to reduce collision attacks; see ticket
       * 8443 for details about observed certs in the wild.) */
      lifetime--;
    }
887
  }
888

Roger Dingledine's avatar
Roger Dingledine committed
889
890
  /* It's ok to pass lifetime in as an unsigned int, since
   * config_parse_interval() checked it. */
891
  return tor_tls_context_init(flags,
892
                              get_tlsclient_identity_key(),
Roger Dingledine's avatar
Roger Dingledine committed
893
                              server_mode(options) ?
894
                              get_server_identity_key() : NULL,
Roger Dingledine's avatar
Roger Dingledine committed
895
                              (unsigned int)lifetime);
896
897
}

898
899
900
901
/** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
 * -1 if Tor should die,
 */
902
STATIC int
903
904
router_write_fingerprint(int hashed)
{
905
  char *keydir = NULL, *cp = NULL;
906
907
908
909
  const char *fname = hashed ? "hashed-fingerprint" :
                               "fingerprint";
  char fingerprint[FINGERPRINT_LEN+1];
  const or_options_t *options = get_options();
910
911
912
  char *fingerprint_line = NULL;
  int result = -1;

913
914
915
916
917
918
919
  keydir = get_datadir_fname(fname);
  log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
           hashed ? "hashed " : "", keydir);
  if (!hashed) {
    if (crypto_pk_get_fingerprint(get_server_identity_key(),
                                  fingerprint, 0) < 0) {
      log_err(LD_GENERAL,"Error computing fingerprint");
920
      goto done;
921
922
923
924
925
    }
  } else {
    if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
                                         fingerprint) < 0) {
      log_err(LD_GENERAL,"Error computing hashed fingerprint");
926
      goto done;
927
928
    }
  }
929
930
931

  tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);

932
  /* Check whether we need to write the (hashed-)fingerprint file. */
933
934

  cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
935
936
937
938
  if (!cp || strcmp(cp, fingerprint_line)) {
    if (write_str_to_file(keydir, fingerprint_line, 0)) {
      log_err(LD_FS, "Error writing %sfingerprint line to file",
              hashed ? "hashed " : "");
939
      goto done;
940
941
942
943
944
945
    }
  }

  log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
             hashed ? "bridge's hashed" : "server's", options->Nickname,
             fingerprint);
946
947
948
949
950
951
952

  result = 0;
 done:
  tor_free(cp);
  tor_free(keydir);
  tor_free(fingerprint_line);
  return result;
953
954
}

955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
static int
init_keys_common(void)
{
  if (!key_lock)
    key_lock = tor_mutex_new();

  /* There are a couple of paths that put us here before we've asked
   * openssl to initialize itself. */
  if (crypto_global_init(get_options()->HardwareAccel,
                         get_options()->AccelName,
                         get_options()->AccelDir)) {
    log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
    return -1;
  }

  return 0;
}

int
init_keys_client(void)
{
  crypto_pk_t *prkey;
  if (init_keys_common() < 0)
    return -1;

  if (!(prkey = crypto_pk_new()))
    return -1;
  if (crypto_pk_generate_key(prkey)) {
    crypto_pk_free(prkey);
    return -1;
  }
  set_client_identity_key(prkey);
  /* Create a TLS context. */
  if (router_initialize_tls_context() < 0) {
    log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
    return -1;
  }
  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
995
/** Initialize all OR private keys, and the TLS context, as necessary.
996
997
 * On OPs, this only initializes the tls context. Return 0 on success,
 * or -1 if Tor should die.
Nick Mathewson's avatar
Nick Mathewson committed
998
 */
999
1000
int
init_keys(void)