router.c 117 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
#include "feature/dircommon/directory.h"
#include "feature/dirclient/dirclient.h"
21
#include "feature/dircache/dirserv.h"
22
#include "feature/dirauth/process_descs.h"
23
24
25
#include "feature/relay/dns.h"
#include "feature/stats/geoip.h"
#include "feature/hibernate/hibernate.h"
26
27
#include "app/main/main.h"
#include "core/mainloop/mainloop.h"
28
29
30
#include "feature/nodelist/networkstatus.h"
#include "feature/nodelist/nodelist.h"
#include "core/or/policies.h"
31
#include "core/or/protover.h"
32
#include "core/or/relay.h"
33
#include "feature/keymgt/loadkey.h"
34
35
36
#include "feature/stats/rephist.h"
#include "feature/relay/router.h"
#include "feature/relay/routerkeys.h"
37
#include "feature/relay/selftest.h"
38
39
#include "feature/nodelist/authcert.h"
#include "feature/nodelist/dirlist.h"
40
41
42
43
44
45
#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"
46

47
#include "feature/dirauth/authmode.h"
48

49
50
51
52
53
54
55
56
57
58
59
#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"
60

61
#include "lib/osinfo/uname.h"
62
63
#include "lib/tls/tortls.h"
#include "lib/encoding/confline.h"
64
#include "lib/crypt_ops/crypto_format.h"
65
#include "lib/crypt_ops/crypto_init.h"
66

Roger Dingledine's avatar
Roger Dingledine committed
67
68
/**
 * \file router.c
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 * \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
86
 **/
Nick Mathewson's avatar
Nick Mathewson committed
87

88
89
/************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
90
91
92
93
/*****
 * Key management: ORs only.
 *****/

Roger Dingledine's avatar
Roger Dingledine committed
94
/** Private keys for this OR.  There is also an SSL key managed by tortls.c.
Nick Mathewson's avatar
Nick Mathewson committed
95
 */
96
static tor_mutex_t *key_lock=NULL;
97
static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
98
/** Current private onionskin decryption key: used to decode CREATE cells. */
99
static crypto_pk_t *onionkey=NULL;
Nick Mathewson's avatar
Nick Mathewson committed
100
/** Previous private onionskin decryption key: used to decode CREATE cells
Roger Dingledine's avatar
Roger Dingledine committed
101
 * generated by clients that have an older version of our descriptor. */
102
static crypto_pk_t *lastonionkey=NULL;
103
/** Current private ntor secret key: used to perform the ntor handshake. */
104
static curve25519_keypair_t curve25519_onion_key;
105
106
/** Previous private ntor secret key: used to perform the ntor handshake
 * with clients that have an older version of our descriptor. */
107
static curve25519_keypair_t last_curve25519_onion_key;
108
/** Private server "identity key": used to sign directory info and TLS
109
 * certificates. Never changes. */
110
static crypto_pk_t *server_identitykey=NULL;
111
112
113
114
115
/** 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. */
116
static crypto_pk_t *client_identitykey=NULL;
117
/** Signing key used for v3 directory material; only set for authorities. */
118
static crypto_pk_t *authority_signing_key = NULL;
119
120
121
/** Key certificate to authenticate v3 directory material; only set for
 * authorities. */
static authority_cert_t *authority_key_certificate = NULL;
122

123
124
/** For emergency V3 authority key migration: An extra signing key that we use
 * with our old (obsolete) identity key for a while. */
125
static crypto_pk_t *legacy_signing_key = NULL;
126
127
/** For emergency V3 authority key migration: An extra certificate to
 * authenticate legacy_signing_key with our obsolete identity key.*/
128
129
static authority_cert_t *legacy_key_certificate = NULL;

130
131
132
133
134
/* (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. */

135
136
137
138
139
140
141
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);

142
143
144
145
/** Return a readonly string with human readable description
 * of <b>err</b>.
 */
const char *
rl1987's avatar
rl1987 committed
146
routerinfo_err_to_string(int err)
147
148
149
150
151
152
153
154
155
156
157
158
{
  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
159
160
    case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
      return "Descriptor still rebuilding - not ready yet";
161
162
  }

rl1987's avatar
rl1987 committed
163
164
  log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
  tor_assert_unreached();
165
166
167
168
169
170
171
172
173
174

  return "Unknown error";
}

/** Return true if we expect given error to be transient.
 * Return false otherwise.
 */
int
routerinfo_err_is_transient(int err)
{
175
176
177
178
179
180
  /**
   * For simplicity, we consider all errors other than
   * "not a server" transient - see discussion on
   * https://trac.torproject.org/projects/tor/ticket/27034
   */
  return err != TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
181
182
}

183
184
/** 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
185
 */
186
static void
187
set_onion_key(crypto_pk_t *k)
188
{
189
  if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
190
    /* k is already our onion key; free it and return */
191
    crypto_pk_free(k);
192
193
    return;
  }
194
  tor_mutex_acquire(key_lock);
195
  crypto_pk_free(onionkey);
196
  onionkey = k;
197
  tor_mutex_release(key_lock);
198
  mark_my_descriptor_dirty("set onion key");
199
200
}

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

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

231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/** 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);

257
  fname = get_keydir_fname("secret_onion_key.old");
258
259
260
261
262
263
264
265
  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);

266
  fname = get_keydir_fname("secret_onion_key_ntor.old");
267
268
269
270
271
272
273
274
275
  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);
}

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

290
291
292
293
294
295
296
297
  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)));
  }
298
299
300
301
302
303
304
305
306
307
308
  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;
}
309
310
/** Helper used to deallocate a di_digest256_map_t returned by
 * construct_ntor_key_map. */
311
312
313
314
315
316
317
static void
ntor_key_map_free_helper(void *arg)
{
  curve25519_keypair_t *k = arg;
  memwipe(k, 0, sizeof(*k));
  tor_free(k);
}
318
/** Release all storage from a keymap returned by construct_ntor_key_map. */
319
void
320
ntor_key_map_free_(di_digest256_map_t *map)
321
{
322
323
  if (!map)
    return;
324
325
326
  dimap_free(map, ntor_key_map_free_helper);
}

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

337
/** Set the current server identity key to <b>k</b>.
Nick Mathewson's avatar
Nick Mathewson committed
338
 */
339
void
340
set_server_identity_key(crypto_pk_t *k)
341
{
342
  crypto_pk_free(server_identitykey);
343
  server_identitykey = k;
344
345
346
347
348
  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);
  }
349
350
}

351
352
353
354
355
/** 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)
{
356
357
  if (1)
    return;
358
359
360
361
  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);
362
    tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
363
364
365
  } else {
    /* assert that we have set the client and server keys to be unequal */
    if (server_identitykey)
366
      tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
367
368
369
  }
}

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

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

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

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

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

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

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

433
434
435
/** 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. */
436
437
438
439
440
441
authority_cert_t *
get_my_v3_legacy_cert(void)
{
  return legacy_key_certificate;
}

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

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

525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/** 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;
}

545
/** Load a curve25519 keypair from the file <b>fname</b>, writing it into
546
547
548
549
 * <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. */
550
551
552
553
554
555
556
557
558
559
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:
560
      tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
561
      goto error;
562
563
    /* 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() */
564
    case FN_NOENT:
565
    case FN_EMPTY:
566
567
568
569
570
      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. */
571
572
            tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
                    "Not writing any new keys.", fname);
573
574
575
576
577
578
579
            /*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);
580
581
        if (curve25519_keypair_generate(keys_out, 1) < 0)
          goto error;
582
        if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
583
          tor_log(severity, LD_FS,
584
              "Couldn't write generated key to \"%s\".", fname);
585
          memwipe(keys_out, 0, sizeof(*keys_out));
586
587
588
589
590
591
592
593
594
595
          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) {
596
          tor_log(severity, LD_GENERAL,"Error loading private key.");
597
598
599
600
          tor_free(tag_in);
          goto error;
        }
        if (!tag_in || strcmp(tag_in, tag)) {
601
          tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
              escaped(tag_in));
          tor_free(tag_in);
          goto error;
        }
        tor_free(tag_in);
        return 0;
      }
    default:
      tor_assert(0);
  }

 error:
  return -1;
}

617
618
619
620
/** 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
621
 * *<b>cert_out</b> respectively, and return 0.  On failure, return -1. */
622
static int
623
load_authority_keyset(int legacy, crypto_pk_t **key_out,
624
                      authority_cert_t **cert_out)
625
{
626
  int r = -1;
627
628
  char *fname = NULL, *cert = NULL;
  const char *eos = NULL;
629
  crypto_pk_t *signing_key = NULL;
630
631
  authority_cert_t *parsed = NULL;

632
  fname = get_keydir_fname(
633
                 legacy ? "legacy_signing_key" : "authority_signing_key");
634
  signing_key = init_key_from_file(fname, 0, LOG_ERR, NULL);
635
636
637
638
  if (!signing_key) {
    log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
    goto done;
  }
639
  tor_free(fname);
640
  fname = get_keydir_fname(
641
               legacy ? "legacy_certificate" : "authority_certificate");
642
643
644
645
646
647
648
649
650
651
652
  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;
  }
653
  if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
654
655
656
657
658
    log_warn(LD_DIR, "Stored signing key does not match signing key in "
             "certificate");
    goto done;
  }

659
  crypto_pk_free(*key_out);
660
661
  authority_cert_free(*cert_out);

662
663
664
  *key_out = signing_key;
  *cert_out = parsed;
  r = 0;
665
  signing_key = NULL;
666
  parsed = NULL;
667
668
669
670

 done:
  tor_free(fname);
  tor_free(cert);
671
  crypto_pk_free(signing_key);
672
  authority_cert_free(parsed);
673
  return r;
674
675
}

676
677
678
679
680
681
682
683
684
685
686
/** 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 &&
687
      load_authority_keyset(1, &legacy_signing_key,
688
689
690
691
692
693
                            &legacy_key_certificate)<0)
    return -1;

  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
694
/** If we're a v3 authority, check whether we have a certificate that's
695
 * likely to expire soon.  Warn if we do, but not too often. */
696
697
698
699
700
701
702
703
704
705
706
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;
707
  time_left = (int)( expires - now );
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
  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) {
728
    tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
729
            " Generate a new one NOW.");
730
  } else if (time_left <= 24*60*60) {
731
732
    tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
            "hours; Generate a new one NOW.", time_left/(60*60));
733
  } else {
734
735
    tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
            "days; Generate a new one soon.", time_left/(24*60*60));
736
737
738
739
  }
  last_warned = now;
}

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
/** 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;
}

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
/** 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
781
782
/** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
 * on success, and -1 on failure. */
783
784
785
int
router_initialize_tls_context(void)
{
786
787
  unsigned int flags = 0;
  const or_options_t *options = get_options();
Roger Dingledine's avatar
Roger Dingledine committed
788
  int lifetime = options->SSLKeyLifetime;
789
790
  if (public_server_mode(options))
    flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
791
  if (!lifetime) { /* we should guess a good ssl cert lifetime */
792
793

    /* choose between 5 and 365 days, and round to the day */
794
795
796
    unsigned int five_days = 5*24*3600;
    unsigned int one_year = 365*24*3600;
    lifetime = crypto_rand_int_range(five_days, one_year);
797
798
799
800
801
802
803
804
805
    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--;
    }
806
  }
807

Roger Dingledine's avatar
Roger Dingledine committed
808
809
  /* It's ok to pass lifetime in as an unsigned int, since
   * config_parse_interval() checked it. */
810
  return tor_tls_context_init(flags,
811
                              get_tlsclient_identity_key(),
Roger Dingledine's avatar
Roger Dingledine committed
812
                              server_mode(options) ?
813
                              get_server_identity_key() : NULL,
Roger Dingledine's avatar
Roger Dingledine committed
814
                              (unsigned int)lifetime);
815
816
}

817
818
819
820
/** 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,
 */
821
STATIC int
822
823
router_write_fingerprint(int hashed)
{
824
  char *keydir = NULL, *cp = NULL;
825
826
827
828
  const char *fname = hashed ? "hashed-fingerprint" :
                               "fingerprint";
  char fingerprint[FINGERPRINT_LEN+1];
  const or_options_t *options = get_options();
829
830
831
  char *fingerprint_line = NULL;
  int result = -1;

832
833
834
835
836
837
838
  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");
839
      goto done;
840
841
842
843
844
    }
  } else {
    if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
                                         fingerprint) < 0) {
      log_err(LD_GENERAL,"Error computing hashed fingerprint");
845
      goto done;
846
847
    }
  }
848
849
850

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

851
  /* Check whether we need to write the (hashed-)fingerprint file. */
852
853

  cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
854
855
856
857
  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 " : "");
858
      goto done;
859
860
861
862
863
864
    }
  }

  log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
             hashed ? "bridge's hashed" : "server's", options->Nickname,
             fingerprint);
865
866
867
868
869
870
871

  result = 0;
 done:
  tor_free(cp);
  tor_free(keydir);
  tor_free(fingerprint_line);
  return result;
872
873
}

874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
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
914
/** Initialize all OR private keys, and the TLS context, as necessary.
915
916
 * 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
917
 */
918
919
920
int
init_keys(void)
{
921
922
  char *keydir;
  const char *mydesc;
923
  crypto_pk_t *prkey;
Roger Dingledine's avatar
Roger Dingledine committed
924
925
  char digest[DIGEST_LEN];
  char v3_digest[DIGEST_LEN];
926
  const or_options_t *options = get_options();
927
  dirinfo_type_t type;
928
  time_t now = time(NULL);
929
  dir_server_t *ds;
930
  int v3_digest_set = 0;
931
  authority_cert_t *cert = NULL;
932

933
  /* OP's don't need persistent keys; just make up an identity and
934
   * initialize the TLS context. */
935
  if (!server_mode(options)) {
936
    return init_keys_client();
937
  }
938
939
  if (init_keys_common() < 0)
    return -1;
940
941

  if (create_keys_directory(options) < 0)
942
943
    return -1;

944
  /* 1a. Read v3 directory authority key/cert information. */
945
  memset(v3_digest, 0, sizeof(v3_digest));
946
  if (authdir_mode_v3(options)) {
947
948
949
950
951
952
    if (init_v3_authority_keys()<0) {
      log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
              "were unable to load our v3 authority keys and certificate! "
              "Use tor-gencert to generate them. Dying.");
      return -1;
    }
953
954
    cert = get_my_v3_authority_cert();
    if (cert) {
955
956
957
958
959
960
      if (crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
                               v3_digest) < 0) {
        log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
                "digest.");
        return -1;
      }
961
      v3_digest_set = 1;
962
963
    }
  }
964

965
  /* 1b. Read identity key. Make it if none is found. */
966
  keydir = get_keydir_fname("secret_id_key");
967
  log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
968
969
  bool created = false;
  prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
970
  tor_free(keydir);
971
  if (!prkey) return -1;
972
973
  if (created)
    log_new_relay_greeting();
974
975
976
977
978
979
  set_server_identity_key(prkey);

  /* 1c. If we are configured as a bridge, generate a client key;
   * otherwise, set the server identity key as our client identity
   * key. */
  if (public_server_mode(options)) {
980
    set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
981
  } else {
982
    if (!(prkey = crypto_pk_new()))
983
984
      return -1;
    if (crypto_pk_generate_key(prkey)) {
985
      crypto_pk_free(prkey);
986
987
988
989
      return -1;
    }
    set_client_identity_key(prkey);
  }
990

991
  /* 1d. Load all ed25519 keys */
992
993
  const int new_signing_key = load_ed_keys(options,now);
  if (new_signing_key < 0)
994
995
    return -1;

996
  /* 2. Read onion key.  Make it if none is found. */
997
  keydir = get_keydir_fname("secret_onion_key");
998
  log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
999
1000
  prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
  if (created)
For faster browsing, not all history is shown. View entire blame