router.c 122 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-2016, The Tor Project, Inc. */
5
6
/* See LICENSE for licensing information */

7
8
#define ROUTER_PRIVATE

9
#include "or.h"
10
#include "circuitbuild.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
11
#include "circuitlist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
12
#include "circuituse.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
13
#include "config.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
14
#include "connection.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
15
#include "control.h"
16
#include "crypto_curve25519.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
17
#include "directory.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
18
#include "dirserv.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
19
#include "dns.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
20
#include "geoip.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
21
#include "hibernate.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
22
#include "main.h"
23
#include "networkstatus.h"
24
#include "nodelist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
25
#include "policies.h"
26
#include "protover.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
27
#include "relay.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
28
#include "rephist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
29
#include "router.h"
30
#include "routerkeys.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
31
#include "routerlist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
32
#include "routerparse.h"
33
#include "statefile.h"
34
#include "torcert.h"
George Kadianakis's avatar
George Kadianakis committed
35
#include "transports.h"
36
#include "routerset.h"
37

Roger Dingledine's avatar
Roger Dingledine committed
38
39
/**
 * \file router.c
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 * \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
57
 **/
Nick Mathewson's avatar
Nick Mathewson committed
58

59
60
/************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
61
62
63
64
/*****
 * Key management: ORs only.
 *****/

Roger Dingledine's avatar
Roger Dingledine committed
65
/** Private keys for this OR.  There is also an SSL key managed by tortls.c.
Nick Mathewson's avatar
Nick Mathewson committed
66
 */
67
static tor_mutex_t *key_lock=NULL;
68
static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
69
/** Current private onionskin decryption key: used to decode CREATE cells. */
70
static crypto_pk_t *onionkey=NULL;
Nick Mathewson's avatar
Nick Mathewson committed
71
/** Previous private onionskin decryption key: used to decode CREATE cells
Roger Dingledine's avatar
Roger Dingledine committed
72
 * generated by clients that have an older version of our descriptor. */
73
static crypto_pk_t *lastonionkey=NULL;
74
/** Current private ntor secret key: used to perform the ntor handshake. */
75
static curve25519_keypair_t curve25519_onion_key;
76
77
/** Previous private ntor secret key: used to perform the ntor handshake
 * with clients that have an older version of our descriptor. */
78
static curve25519_keypair_t last_curve25519_onion_key;
79
/** Private server "identity key": used to sign directory info and TLS
80
 * certificates. Never changes. */
81
static crypto_pk_t *server_identitykey=NULL;
82
83
84
85
86
/** 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. */
87
static crypto_pk_t *client_identitykey=NULL;
88
/** Signing key used for v3 directory material; only set for authorities. */
89
static crypto_pk_t *authority_signing_key = NULL;
90
91
92
/** Key certificate to authenticate v3 directory material; only set for
 * authorities. */
static authority_cert_t *authority_key_certificate = NULL;
93

94
95
/** For emergency V3 authority key migration: An extra signing key that we use
 * with our old (obsolete) identity key for a while. */
96
static crypto_pk_t *legacy_signing_key = NULL;
97
98
/** For emergency V3 authority key migration: An extra certificate to
 * authenticate legacy_signing_key with our obsolete identity key.*/
99
100
static authority_cert_t *legacy_key_certificate = NULL;

101
102
103
104
105
/* (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. */

106
107
/** 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
108
 */
109
static void
110
set_onion_key(crypto_pk_t *k)
111
{
112
  if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
113
    /* k is already our onion key; free it and return */
114
    crypto_pk_free(k);
115
116
    return;
  }
117
  tor_mutex_acquire(key_lock);
118
  crypto_pk_free(onionkey);
119
  onionkey = k;
120
  tor_mutex_release(key_lock);
121
  mark_my_descriptor_dirty("set onion key");
122
123
}

Roger Dingledine's avatar
Roger Dingledine committed
124
/** Return the current onion key.  Requires that the onion key has been
Nick Mathewson's avatar
Nick Mathewson committed
125
 * loaded or generated. */
126
crypto_pk_t *
127
128
get_onion_key(void)
{
Roger Dingledine's avatar
Roger Dingledine committed
129
  tor_assert(onionkey);
130
131
132
  return onionkey;
}

133
134
/** Store a full copy of the current onion key into *<b>key</b>, and a full
 * copy of the most recent onion key into *<b>last</b>.
135
 */
136
void
137
dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
138
{
139
140
  tor_assert(key);
  tor_assert(last);
141
  tor_mutex_acquire(key_lock);
142
  tor_assert(onionkey);
143
  *key = crypto_pk_copy_full(onionkey);
144
  if (lastonionkey)
145
    *last = crypto_pk_copy_full(lastonionkey);
146
147
148
149
150
  else
    *last = NULL;
  tor_mutex_release(key_lock);
}

151
152
/** Return the current secret onion key for the ntor handshake. Must only
 * be called from the main thread. */
153
154
155
156
157
static const curve25519_keypair_t *
get_current_curve25519_keypair(void)
{
  return &curve25519_onion_key;
}
158
159
/** Return a map from KEYID (the key itself) to keypairs for use in the ntor
 * handshake. Must only be called from the main thread. */
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
di_digest256_map_t *
construct_ntor_key_map(void)
{
  di_digest256_map_t *m = NULL;

  dimap_add_entry(&m,
                  curve25519_onion_key.pubkey.public_key,
                  tor_memdup(&curve25519_onion_key,
                             sizeof(curve25519_keypair_t)));
  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;
}
180
181
/** Helper used to deallocate a di_digest256_map_t returned by
 * construct_ntor_key_map. */
182
183
184
185
186
187
188
static void
ntor_key_map_free_helper(void *arg)
{
  curve25519_keypair_t *k = arg;
  memwipe(k, 0, sizeof(*k));
  tor_free(k);
}
189
/** Release all storage from a keymap returned by construct_ntor_key_map. */
190
191
192
void
ntor_key_map_free(di_digest256_map_t *map)
{
193
194
  if (!map)
    return;
195
196
197
  dimap_free(map, ntor_key_map_free_helper);
}

Roger Dingledine's avatar
Roger Dingledine committed
198
/** Return the time when the onion key was last set.  This is either the time
Nick Mathewson's avatar
Nick Mathewson committed
199
200
201
 * when the process launched, or the time of the most recent key rotation since
 * the process launched.
 */
202
203
204
time_t
get_onion_key_set_at(void)
{
205
  return onionkey_set_at;
206
207
}

208
/** Set the current server identity key to <b>k</b>.
Nick Mathewson's avatar
Nick Mathewson committed
209
 */
210
void
211
set_server_identity_key(crypto_pk_t *k)
212
{
213
  crypto_pk_free(server_identitykey);
214
215
  server_identitykey = k;
  crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
216
217
}

218
219
220
221
222
/** 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)
{
223
224
  if (1)
    return;
225
226
227
228
  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);
229
    tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
230
231
232
  } else {
    /* assert that we have set the client and server keys to be unequal */
    if (server_identitykey)
233
      tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
234
235
236
  }
}

237
/** Returns the current server identity key; requires that the key has
238
 * been set, and that we are running as a Tor server.
Nick Mathewson's avatar
Nick Mathewson committed
239
 */
240
crypto_pk_t *
241
get_server_identity_key(void)
242
{
243
  tor_assert(server_identitykey);
244
245
  tor_assert(server_mode(get_options()));
  assert_identity_keys_ok();
246
  return server_identitykey;
247
248
}

Nick Mathewson's avatar
Nick Mathewson committed
249
250
/** Return true iff we are a server and the server identity key
 * has been set. */
251
int
252
server_identity_key_is_set(void)
253
{
254
  return server_mode(get_options()) && server_identitykey != NULL;
255
256
257
258
259
}

/** Set the current client identity key to <b>k</b>.
 */
void
260
set_client_identity_key(crypto_pk_t *k)
261
{
262
  crypto_pk_free(client_identitykey);
263
264
265
  client_identitykey = k;
}

266
267
/** Returns the current client identity key for use on outgoing TLS
 * connections; requires that the key has been set.
268
 */
269
crypto_pk_t *
270
get_tlsclient_identity_key(void)
271
272
{
  tor_assert(client_identitykey);
273
  assert_identity_keys_ok();
274
275
276
277
278
279
280
281
  return client_identitykey;
}

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

284
285
/** Return the key certificate for this v3 (voting) authority, or NULL
 * if we have no such certificate. */
286
287
MOCK_IMPL(authority_cert_t *,
get_my_v3_authority_cert, (void))
288
289
290
291
{
  return authority_key_certificate;
}

292
293
/** Return the v3 signing key for this v3 (voting) authority, or NULL
 * if we have no such key. */
294
crypto_pk_t *
295
296
297
298
299
get_my_v3_authority_signing_key(void)
{
  return authority_signing_key;
}

300
301
302
/** 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. */
303
304
305
306
307
308
authority_cert_t *
get_my_v3_legacy_cert(void)
{
  return legacy_key_certificate;
}

309
310
/** If we're an authority, and we're using a legacy authority identity key for
 * emergency migration purposes, return that key. */
311
crypto_pk_t *
312
313
314
315
316
get_my_v3_legacy_signing_key(void)
{
  return legacy_signing_key;
}

Roger Dingledine's avatar
Roger Dingledine committed
317
/** Replace the previous onion key with the current onion key, and generate
318
319
 * a new previous onion key.  Immediately after calling this function,
 * the OR should:
Roger Dingledine's avatar
Roger Dingledine committed
320
321
322
 *   - 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.
323
 */
324
325
void
rotate_onion_key(void)
326
{
327
  char *fname, *fname_prev;
328
  crypto_pk_t *prkey = NULL;
329
  or_state_t *state = get_or_state();
330
  curve25519_keypair_t new_curve25519_keypair;
331
  time_t now;
332
333
  fname = get_datadir_fname2("keys", "secret_onion_key");
  fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
334
  /* There isn't much point replacing an old key with an empty file */
335
336
337
338
  if (file_status(fname) == FN_FILE) {
    if (replace_file(fname, fname_prev))
      goto error;
  }
339
  if (!(prkey = crypto_pk_new())) {
340
    log_err(LD_GENERAL,"Error constructing rotated onion key");
341
342
    goto error;
  }
343
  if (crypto_pk_generate_key(prkey)) {
344
    log_err(LD_BUG,"Error generating onion key");
345
346
    goto error;
  }
347
348
349
350
351
352
353
354
  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);
  fname = get_datadir_fname2("keys", "secret_onion_key_ntor");
  fname_prev = get_datadir_fname2("keys", "secret_onion_key_ntor.old");
355
356
  if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
    goto error;
357
  /* There isn't much point replacing an old key with an empty file */
358
359
360
361
  if (file_status(fname) == FN_FILE) {
    if (replace_file(fname, fname_prev))
      goto error;
  }
362
363
364
  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);
365
366
    goto error;
  }
367
  log_info(LD_GENERAL, "Rotating onion key");
368
  tor_mutex_acquire(key_lock);
369
  crypto_pk_free(lastonionkey);
370
  lastonionkey = onionkey;
371
  onionkey = prkey;
372
373
374
375
  memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
         sizeof(curve25519_keypair_t));
  memcpy(&curve25519_onion_key, &new_curve25519_keypair,
         sizeof(curve25519_keypair_t));
376
377
  now = time(NULL);
  state->LastRotatedOnionKey = onionkey_set_at = now;
378
  tor_mutex_release(key_lock);
379
  mark_my_descriptor_dirty("rotated onion key");
380
  or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
381
  goto done;
382
 error:
383
  log_warn(LD_GENERAL, "Couldn't rotate onion key.");
384
  if (prkey)
385
    crypto_pk_free(prkey);
386
 done:
387
  memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
388
389
  tor_free(fname);
  tor_free(fname_prev);
390
391
}

392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/** 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;
}

412
413
414
/** 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
415
416
 * 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.
417
 */
418
crypto_pk_t *
419
420
init_key_from_file(const char *fname, int generate, int severity,
                   int log_greeting)
421
{
422
  crypto_pk_t *prkey = NULL;
423

424
  if (!(prkey = crypto_pk_new())) {
425
    tor_log(severity, LD_GENERAL,"Error constructing key");
426
427
428
    goto error;
  }

429
  switch (file_status(fname)) {
430
431
    case FN_DIR:
    case FN_ERROR:
432
      tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
433
      goto error;
434
435
436
    /* 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() */
437
    case FN_NOENT:
438
    case FN_EMPTY:
439
      if (generate) {
440
441
442
443
        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. */
444
445
            tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
                    "Not writing any new keys.", fname);
446
447
448
449
450
            /*XXXX The 'other process' might make a key in a second or two;
             * maybe we should wait for it. */
            goto error;
          }
        }
451
452
453
        log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
                 fname);
        if (crypto_pk_generate_key(prkey)) {
454
          tor_log(severity, LD_GENERAL,"Error generating onion key");
455
456
457
          goto error;
        }
        if (crypto_pk_check_key(prkey) <= 0) {
458
          tor_log(severity, LD_GENERAL,"Generated key seems invalid");
459
460
461
          goto error;
        }
        log_info(LD_GENERAL, "Generated key seems valid");
462
463
464
        if (log_greeting) {
            log_new_relay_greeting();
        }
465
        if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
466
          tor_log(severity, LD_FS,
467
468
469
470
              "Couldn't write generated key to \"%s\".", fname);
          goto error;
        }
      } else {
471
472
        tor_log(severity, LD_GENERAL, "No key found in \"%s\"", fname);
        goto error;
473
474
475
476
      }
      return prkey;
    case FN_FILE:
      if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
477
        tor_log(severity, LD_GENERAL,"Error loading private key.");
478
479
480
481
482
        goto error;
      }
      return prkey;
    default:
      tor_assert(0);
483
484
485
486
  }

 error:
  if (prkey)
487
    crypto_pk_free(prkey);
488
489
490
  return NULL;
}

491
/** Load a curve25519 keypair from the file <b>fname</b>, writing it into
492
493
494
495
 * <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. */
496
497
498
499
500
501
502
503
504
505
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:
506
      tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
507
      goto error;
508
509
    /* 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() */
510
    case FN_NOENT:
511
    case FN_EMPTY:
512
513
514
515
516
      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. */
517
518
            tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
                    "Not writing any new keys.", fname);
519
520
521
522
523
524
525
            /*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);
526
527
        if (curve25519_keypair_generate(keys_out, 1) < 0)
          goto error;
528
        if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
529
          tor_log(severity, LD_FS,
530
              "Couldn't write generated key to \"%s\".", fname);
531
          memwipe(keys_out, 0, sizeof(*keys_out));
532
533
534
535
536
537
538
539
540
541
          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) {
542
          tor_log(severity, LD_GENERAL,"Error loading private key.");
543
544
545
546
          tor_free(tag_in);
          goto error;
        }
        if (!tag_in || strcmp(tag_in, tag)) {
547
          tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
              escaped(tag_in));
          tor_free(tag_in);
          goto error;
        }
        tor_free(tag_in);
        return 0;
      }
    default:
      tor_assert(0);
  }

 error:
  return -1;
}

563
564
565
566
/** 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
567
 * *<b>cert_out</b> respectively, and return 0.  On failure, return -1. */
568
static int
569
load_authority_keyset(int legacy, crypto_pk_t **key_out,
570
                      authority_cert_t **cert_out)
571
{
572
  int r = -1;
573
574
  char *fname = NULL, *cert = NULL;
  const char *eos = NULL;
575
  crypto_pk_t *signing_key = NULL;
576
577
  authority_cert_t *parsed = NULL;

578
579
  fname = get_datadir_fname2("keys",
                 legacy ? "legacy_signing_key" : "authority_signing_key");
580
  signing_key = init_key_from_file(fname, 0, LOG_ERR, 0);
581
582
583
584
  if (!signing_key) {
    log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
    goto done;
  }
585
  tor_free(fname);
586
587
  fname = get_datadir_fname2("keys",
               legacy ? "legacy_certificate" : "authority_certificate");
588
589
590
591
592
593
594
595
596
597
598
  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;
  }
599
  if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
600
601
602
603
604
    log_warn(LD_DIR, "Stored signing key does not match signing key in "
             "certificate");
    goto done;
  }

605
  crypto_pk_free(*key_out);
606
607
  authority_cert_free(*cert_out);

608
609
610
  *key_out = signing_key;
  *cert_out = parsed;
  r = 0;
611
  signing_key = NULL;
612
  parsed = NULL;
613
614
615
616

 done:
  tor_free(fname);
  tor_free(cert);
617
  crypto_pk_free(signing_key);
618
  authority_cert_free(parsed);
619
  return r;
620
621
}

622
623
624
625
626
627
628
629
630
631
632
/** 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 &&
633
      load_authority_keyset(1, &legacy_signing_key,
634
635
636
637
638
639
                            &legacy_key_certificate)<0)
    return -1;

  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
640
/** If we're a v3 authority, check whether we have a certificate that's
641
 * likely to expire soon.  Warn if we do, but not too often. */
642
643
644
645
646
647
648
649
650
651
652
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;
653
  time_left = (int)( expires - now );
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
  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) {
674
    tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
675
            " Generate a new one NOW.");
676
  } else if (time_left <= 24*60*60) {
677
678
    tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
            "hours; Generate a new one NOW.", time_left/(60*60));
679
  } else {
680
681
    tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
            "days; Generate a new one soon.", time_left/(24*60*60));
682
683
684
685
  }
  last_warned = now;
}

Nick Mathewson's avatar
Nick Mathewson committed
686
687
/** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
 * on success, and -1 on failure. */
688
689
690
int
router_initialize_tls_context(void)
{
691
692
  unsigned int flags = 0;
  const or_options_t *options = get_options();
Roger Dingledine's avatar
Roger Dingledine committed
693
  int lifetime = options->SSLKeyLifetime;
694
695
696
697
698
699
700
701
  if (public_server_mode(options))
    flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
  if (options->TLSECGroup) {
    if (!strcasecmp(options->TLSECGroup, "P256"))
      flags |= TOR_TLS_CTX_USE_ECDHE_P256;
    else if (!strcasecmp(options->TLSECGroup, "P224"))
      flags |= TOR_TLS_CTX_USE_ECDHE_P224;
  }
702
  if (!lifetime) { /* we should guess a good ssl cert lifetime */
703
704

    /* choose between 5 and 365 days, and round to the day */
705
706
707
    unsigned int five_days = 5*24*3600;
    unsigned int one_year = 365*24*3600;
    lifetime = crypto_rand_int_range(five_days, one_year);
708
709
710
711
712
713
714
715
716
    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--;
    }
717
  }
718

Roger Dingledine's avatar
Roger Dingledine committed
719
720
  /* It's ok to pass lifetime in as an unsigned int, since
   * config_parse_interval() checked it. */
721
  return tor_tls_context_init(flags,
722
                              get_tlsclient_identity_key(),
Roger Dingledine's avatar
Roger Dingledine committed
723
                              server_mode(options) ?
724
                              get_server_identity_key() : NULL,
Roger Dingledine's avatar
Roger Dingledine committed
725
                              (unsigned int)lifetime);
726
727
}

728
729
730
731
/** 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,
 */
732
STATIC int
733
734
router_write_fingerprint(int hashed)
{
735
  char *keydir = NULL, *cp = NULL;
736
737
738
739
  const char *fname = hashed ? "hashed-fingerprint" :
                               "fingerprint";
  char fingerprint[FINGERPRINT_LEN+1];
  const or_options_t *options = get_options();
740
741
742
  char *fingerprint_line = NULL;
  int result = -1;

743
744
745
746
747
748
749
  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");
750
      goto done;
751
752
753
754
755
    }
  } else {
    if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
                                         fingerprint) < 0) {
      log_err(LD_GENERAL,"Error computing hashed fingerprint");
756
      goto done;
757
758
    }
  }
759
760
761

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

762
  /* Check whether we need to write the (hashed-)fingerprint file. */
763
764

  cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
765
766
767
768
  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 " : "");
769
      goto done;
770
771
772
773
774
775
    }
  }

  log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
             hashed ? "bridge's hashed" : "server's", options->Nickname,
             fingerprint);
776
777
778
779
780
781
782

  result = 0;
 done:
  tor_free(cp);
  tor_free(keydir);
  tor_free(fingerprint_line);
  return result;
783
784
}

785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
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
825
/** Initialize all OR private keys, and the TLS context, as necessary.
826
827
 * 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
828
 */
829
830
831
int
init_keys(void)
{
832
833
  char *keydir;
  const char *mydesc;
834
  crypto_pk_t *prkey;
Roger Dingledine's avatar
Roger Dingledine committed
835
836
  char digest[DIGEST_LEN];
  char v3_digest[DIGEST_LEN];
837
  const or_options_t *options = get_options();
838
  dirinfo_type_t type;
839
  time_t now = time(NULL);
840
  dir_server_t *ds;
841
  int v3_digest_set = 0;
842
  authority_cert_t *cert = NULL;
843

844
  /* OP's don't need persistent keys; just make up an identity and
845
   * initialize the TLS context. */
846
  if (!server_mode(options)) {
847
    return init_keys_client();
848
  }
849
850
  if (init_keys_common() < 0)
    return -1;
Nick Mathewson's avatar
Nick Mathewson committed
851
  /* Make sure DataDirectory exists, and is private. */
852
  if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
853
854
    return -1;
  }
Nick Mathewson's avatar
Nick Mathewson committed
855
  /* Check the key directory. */
856
  keydir = get_datadir_fname("keys");
857
  if (check_private_dir(keydir, CPD_CREATE, options->User)) {
858
    tor_free(keydir);
859
860
    return -1;
  }
861
  tor_free(keydir);
862

863
  /* 1a. Read v3 directory authority key/cert information. */
864
  memset(v3_digest, 0, sizeof(v3_digest));
865
  if (authdir_mode_v3(options)) {
866
867
868
869
870
871
    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;
    }
872
873
    cert = get_my_v3_authority_cert();
    if (cert) {
874
875
      crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
                           v3_digest);
876
      v3_digest_set = 1;
877
878
    }
  }
879

880
  /* 1b. Read identity key. Make it if none is found. */
881
  keydir = get_datadir_fname2("keys", "secret_id_key");
882
  log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
883
  prkey = init_key_from_file(keydir, 1, LOG_ERR, 1);
884
  tor_free(keydir);
885
  if (!prkey) return -1;
886
887
888
889
890
891
  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)) {
892
    set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
893
  } else {
894
    if (!(prkey = crypto_pk_new()))
895
896
      return -1;
    if (crypto_pk_generate_key(prkey)) {
897
      crypto_pk_free(prkey);
898
899
900
901
      return -1;
    }
    set_client_identity_key(prkey);
  }
902

903
  /* 1d. Load all ed25519 keys */
904
  if (load_ed_keys(options,now) < 0)
905
906
    return -1;

907
  /* 2. Read onion key.  Make it if none is found. */
908
  keydir = get_datadir_fname2("keys", "secret_onion_key");
909
  log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
910
  prkey = init_key_from_file(keydir, 1, LOG_ERR, 1);
911
  tor_free(keydir);
912
913
  if (!prkey) return -1;
  set_onion_key(prkey);
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
  if (options->command == CMD_RUN_TOR) {
    /* only mess with the state file if we're actually running Tor */
    or_state_t *state = get_or_state();
    if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
      /* We allow for some parsing slop, but we don't want to risk accepting
       * values in the distant future.  If we did, we might never rotate the
       * onion key. */
      onionkey_set_at = state->LastRotatedOnionKey;
    } else {
      /* We have no LastRotatedOnionKey set; either we just created the key
       * or it's a holdover from 0.1.2.4-alpha-dev or earlier.  In either case,
       * start the clock ticking now so that we will eventually rotate it even
       * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
      state->LastRotatedOnionKey = onionkey_set_at = now;
      or_state_mark_dirty(state, options->AvoidDiskWrites ?
                                   time(NULL)+3600 : 0);
    }
931
932
  }

933
  keydir = get_datadir_fname2("keys", "secret_onion_key.old");
934
  if (!lastonionkey && file_status(keydir) == FN_FILE) {
935
936
    /* Load keys from non-empty files only.
     * Missing old keys won't be replaced with freshly generated keys. */
937
    prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
938
939
940
    if (prkey)
      lastonionkey = prkey;
  }
941
  tor_free(keydir);
942

943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
  {
    /* 2b. Load curve25519 onion keys. */
    int r;
    keydir = get_datadir_fname2("keys", "secret_onion_key_ntor");
    r = init_curve25519_keypair_from_file(&curve25519_onion_key,
                                          keydir, 1, LOG_ERR, "onion");
    tor_free(keydir);
    if (r<0)
      return -1;

    keydir = get_datadir_fname2("keys", "secret_onion_key_ntor.old");
    if (tor_mem_is_zero((const char *)
                           last_curve25519_onion_key.pubkey.public_key,
                        CURVE25519_PUBKEY_LEN) &&
        file_status(keydir) == FN_FILE) {
958
959
      /* Load keys from non-empty files only.
       * Missing old keys won't be replaced with freshly generated keys. */
960
961
962
963
964
965
      init_curve25519_keypair_from_file(&last_curve25519_onion_key,
                                        keydir, 0, LOG_ERR, "onion");
    }
    tor_free(keydir);
  }

966
  /* 3. Initialize link key and TLS context. */
967
  if (router_initialize_tls_context() < 0) {
968
    log_err(LD_GENERAL,"Error initializing TLS context");
969
970
    return -1;
  }
971

972
973
974
975
976
977
978
  /* 3b. Get an ed25519 link certificate.  Note that we need to do this
   * after we set up the TLS context */
  if (generate_ed_link_cert(options, now) < 0) {
    log_err(LD_GENERAL,"Couldn't make link cert");
    return -1;
  }

979
  /* 4. Build our router descriptor. */
980
  /* Must be called after keys are initialized. */
981
  mydesc = router_get_my_descriptor();
982
  if (authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)) {
983
    const char *m = NULL;
984
    routerinfo_t *ri;
Roger Dingledine's avatar
Roger Dingledine committed
985
    /* We need to add our own fingerprint so it gets recognized. */
986
987
    if (dirserv_add_own_fingerprint(get_server_identity_key())) {
      log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
Roger Dingledine's avatar
Roger Dingledine committed
988
989
      return -1;
    }
990
    if (mydesc) {
991
      was_router_added_t added;
992
      ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
993
994
995
996
      if (!ri) {
        log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
        return -1;
      }
997
998
      added = dirserv_add_descriptor(ri, &m, "self");
      if (!WRA_WAS_ADDED(added)) {
999
        if (!WRA_WAS_OUTDATED(added)) {
1000
          log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",