router.c 90.4 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.
4
 * Copyright (c) 2007-2012, 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"
Sebastian Hahn's avatar
Sebastian Hahn committed
16
#include "directory.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
17
#include "dirserv.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
18
#include "dns.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
19
#include "geoip.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
20
#include "hibernate.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
21
#include "main.h"
22
#include "networkstatus.h"
23
#include "nodelist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
24
#include "policies.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
25
#include "relay.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
26
#include "rephist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
27
#include "router.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
28
#include "routerlist.h"
Sebastian Hahn's avatar
Sebastian Hahn committed
29
#include "routerparse.h"
30
#include "statefile.h"
George Kadianakis's avatar
George Kadianakis committed
31
#include "transports.h"
32
#include "routerset.h"
33

Roger Dingledine's avatar
Roger Dingledine committed
34
35
36
/**
 * \file router.c
 * \brief OR functionality, including key maintenance, generating
Nick Mathewson's avatar
Nick Mathewson committed
37
 * and uploading server descriptors, retrying OR connections.
Roger Dingledine's avatar
Roger Dingledine committed
38
 **/
Nick Mathewson's avatar
Nick Mathewson committed
39

40
extern long stats_n_seconds_working;
41
42
43

/************************************************************/

Nick Mathewson's avatar
Nick Mathewson committed
44
45
46
47
/*****
 * Key management: ORs only.
 *****/

Roger Dingledine's avatar
Roger Dingledine committed
48
/** Private keys for this OR.  There is also an SSL key managed by tortls.c.
Nick Mathewson's avatar
Nick Mathewson committed
49
 */
50
static tor_mutex_t *key_lock=NULL;
51
static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
52
/** Current private onionskin decryption key: used to decode CREATE cells. */
53
static crypto_pk_t *onionkey=NULL;
Nick Mathewson's avatar
Nick Mathewson committed
54
/** Previous private onionskin decryption key: used to decode CREATE cells
Roger Dingledine's avatar
Roger Dingledine committed
55
 * generated by clients that have an older version of our descriptor. */
56
static crypto_pk_t *lastonionkey=NULL;
57
/** Private server "identity key": used to sign directory info and TLS
58
 * certificates. Never changes. */
59
static crypto_pk_t *server_identitykey=NULL;
60
61
62
63
64
/** 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. */
65
static crypto_pk_t *client_identitykey=NULL;
66
/** Signing key used for v3 directory material; only set for authorities. */
67
static crypto_pk_t *authority_signing_key = NULL;
68
69
70
/** Key certificate to authenticate v3 directory material; only set for
 * authorities. */
static authority_cert_t *authority_key_certificate = NULL;
71

72
73
/** For emergency V3 authority key migration: An extra signing key that we use
 * with our old (obsolete) identity key for a while. */
74
static crypto_pk_t *legacy_signing_key = NULL;
75
76
/** For emergency V3 authority key migration: An extra certificate to
 * authenticate legacy_signing_key with our obsolete identity key.*/
77
78
static authority_cert_t *legacy_key_certificate = NULL;

79
80
81
82
83
/* (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. */

84
85
/** 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
86
 */
87
static void
88
set_onion_key(crypto_pk_t *k)
89
{
90
  if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
91
    /* k is already our onion key; free it and return */
92
    crypto_pk_free(k);
93
94
    return;
  }
95
  tor_mutex_acquire(key_lock);
96
  crypto_pk_free(onionkey);
97
  onionkey = k;
98
  tor_mutex_release(key_lock);
99
  mark_my_descriptor_dirty("set onion key");
100
101
}

Roger Dingledine's avatar
Roger Dingledine committed
102
/** Return the current onion key.  Requires that the onion key has been
Nick Mathewson's avatar
Nick Mathewson committed
103
 * loaded or generated. */
104
crypto_pk_t *
105
106
get_onion_key(void)
{
Roger Dingledine's avatar
Roger Dingledine committed
107
  tor_assert(onionkey);
108
109
110
  return onionkey;
}

111
112
/** 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>.
113
 */
114
void
115
dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
116
{
117
118
  tor_assert(key);
  tor_assert(last);
119
  tor_mutex_acquire(key_lock);
120
  tor_assert(onionkey);
121
  *key = crypto_pk_copy_full(onionkey);
122
  if (lastonionkey)
123
    *last = crypto_pk_copy_full(lastonionkey);
124
125
126
127
128
  else
    *last = NULL;
  tor_mutex_release(key_lock);
}

Roger Dingledine's avatar
Roger Dingledine committed
129
/** Return the time when the onion key was last set.  This is either the time
Nick Mathewson's avatar
Nick Mathewson committed
130
131
132
 * when the process launched, or the time of the most recent key rotation since
 * the process launched.
 */
133
134
135
time_t
get_onion_key_set_at(void)
{
136
  return onionkey_set_at;
137
138
}

139
/** Set the current server identity key to <b>k</b>.
Nick Mathewson's avatar
Nick Mathewson committed
140
 */
141
void
142
set_server_identity_key(crypto_pk_t *k)
143
{
144
  crypto_pk_free(server_identitykey);
145
146
  server_identitykey = k;
  crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
147
148
}

149
150
151
152
153
154
155
156
157
/** 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)
{
  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);
158
    tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
159
160
161
  } else {
    /* assert that we have set the client and server keys to be unequal */
    if (server_identitykey)
162
      tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
163
164
165
  }
}

166
/** Returns the current server identity key; requires that the key has
167
 * been set, and that we are running as a Tor server.
Nick Mathewson's avatar
Nick Mathewson committed
168
 */
169
crypto_pk_t *
170
get_server_identity_key(void)
171
{
172
  tor_assert(server_identitykey);
173
174
  tor_assert(server_mode(get_options()));
  assert_identity_keys_ok();
175
  return server_identitykey;
176
177
}

178
/** Return true iff the server identity key has been set. */
179
int
180
server_identity_key_is_set(void)
181
{
182
183
184
185
186
187
  return server_identitykey != NULL;
}

/** Set the current client identity key to <b>k</b>.
 */
void
188
set_client_identity_key(crypto_pk_t *k)
189
{
190
  crypto_pk_free(client_identitykey);
191
192
193
  client_identitykey = k;
}

194
195
/** Returns the current client identity key for use on outgoing TLS
 * connections; requires that the key has been set.
196
 */
197
crypto_pk_t *
198
get_tlsclient_identity_key(void)
199
200
{
  tor_assert(client_identitykey);
201
  assert_identity_keys_ok();
202
203
204
205
206
207
208
209
  return client_identitykey;
}

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

212
213
/** Return the key certificate for this v3 (voting) authority, or NULL
 * if we have no such certificate. */
214
215
216
217
218
219
authority_cert_t *
get_my_v3_authority_cert(void)
{
  return authority_key_certificate;
}

220
221
/** Return the v3 signing key for this v3 (voting) authority, or NULL
 * if we have no such key. */
222
crypto_pk_t *
223
224
225
226
227
get_my_v3_authority_signing_key(void)
{
  return authority_signing_key;
}

228
229
230
/** 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. */
231
232
233
234
235
236
authority_cert_t *
get_my_v3_legacy_cert(void)
{
  return legacy_key_certificate;
}

237
238
/** If we're an authority, and we're using a legacy authority identity key for
 * emergency migration purposes, return that key. */
239
crypto_pk_t *
240
241
242
243
244
get_my_v3_legacy_signing_key(void)
{
  return legacy_signing_key;
}

Roger Dingledine's avatar
Roger Dingledine committed
245
/** Replace the previous onion key with the current onion key, and generate
246
247
 * a new previous onion key.  Immediately after calling this function,
 * the OR should:
Roger Dingledine's avatar
Roger Dingledine committed
248
249
250
 *   - 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.
251
 */
252
253
void
rotate_onion_key(void)
254
{
255
  char *fname, *fname_prev;
256
  crypto_pk_t *prkey;
257
258
  or_state_t *state = get_or_state();
  time_t now;
259
260
  fname = get_datadir_fname2("keys", "secret_onion_key");
  fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
261
  if (!(prkey = crypto_pk_new())) {
262
    log_err(LD_GENERAL,"Error constructing rotated onion key");
263
264
    goto error;
  }
265
  if (crypto_pk_generate_key(prkey)) {
266
    log_err(LD_BUG,"Error generating onion key");
267
268
    goto error;
  }
269
270
271
272
  if (file_status(fname) == FN_FILE) {
    if (replace_file(fname, fname_prev))
      goto error;
  }
273
  if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
274
    log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
275
276
    goto error;
  }
277
  log_info(LD_GENERAL, "Rotating onion key");
278
  tor_mutex_acquire(key_lock);
279
  crypto_pk_free(lastonionkey);
280
  lastonionkey = onionkey;
281
  onionkey = prkey;
282
283
  now = time(NULL);
  state->LastRotatedOnionKey = onionkey_set_at = now;
284
  tor_mutex_release(key_lock);
285
  mark_my_descriptor_dirty("rotated onion key");
286
  or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
287
  goto done;
288
 error:
289
  log_warn(LD_GENERAL, "Couldn't rotate onion key.");
290
  if (prkey)
291
    crypto_pk_free(prkey);
292
293
294
 done:
  tor_free(fname);
  tor_free(fname_prev);
295
296
}

297
298
299
300
301
/** 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
 * errors at level <b>severity</b>.
 */
302
crypto_pk_t *
303
init_key_from_file(const char *fname, int generate, int severity)
304
{
305
  crypto_pk_t *prkey = NULL;
306

307
  if (!(prkey = crypto_pk_new())) {
308
    log(severity, LD_GENERAL,"Error constructing key");
309
310
311
    goto error;
  }

312
  switch (file_status(fname)) {
313
314
    case FN_DIR:
    case FN_ERROR:
315
      log(severity, LD_FS,"Can't read key from \"%s\"", fname);
316
      goto error;
317
    case FN_NOENT:
318
      if (generate) {
319
320
321
322
323
324
325
326
327
328
329
        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. */
            log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
                "writing any new keys.", fname);
            /*XXXX The 'other process' might make a key in a second or two;
             * maybe we should wait for it. */
            goto error;
          }
        }
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
        log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
                 fname);
        if (crypto_pk_generate_key(prkey)) {
          log(severity, LD_GENERAL,"Error generating onion key");
          goto error;
        }
        if (crypto_pk_check_key(prkey) <= 0) {
          log(severity, LD_GENERAL,"Generated key seems invalid");
          goto error;
        }
        log_info(LD_GENERAL, "Generated key seems valid");
        if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
          log(severity, LD_FS,
              "Couldn't write generated key to \"%s\".", fname);
          goto error;
        }
      } else {
        log_info(LD_GENERAL, "No key found in \"%s\"", fname);
348
349
350
351
      }
      return prkey;
    case FN_FILE:
      if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
352
        log(severity, LD_GENERAL,"Error loading private key.");
353
354
355
356
357
        goto error;
      }
      return prkey;
    default:
      tor_assert(0);
358
359
360
361
  }

 error:
  if (prkey)
362
    crypto_pk_free(prkey);
363
364
365
  return NULL;
}

366
367
368
369
/** 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
370
 * *<b>cert_out</b> respectively, and return 0.  On failure, return -1. */
371
static int
372
load_authority_keyset(int legacy, crypto_pk_t **key_out,
373
                      authority_cert_t **cert_out)
374
{
375
  int r = -1;
376
377
  char *fname = NULL, *cert = NULL;
  const char *eos = NULL;
378
  crypto_pk_t *signing_key = NULL;
379
380
  authority_cert_t *parsed = NULL;

381
382
  fname = get_datadir_fname2("keys",
                 legacy ? "legacy_signing_key" : "authority_signing_key");
383
  signing_key = init_key_from_file(fname, 0, LOG_INFO);
384
385
386
387
  if (!signing_key) {
    log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
    goto done;
  }
388
  tor_free(fname);
389
390
  fname = get_datadir_fname2("keys",
               legacy ? "legacy_certificate" : "authority_certificate");
391
392
393
394
395
396
397
398
399
400
401
  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;
  }
402
  if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
403
404
405
406
407
    log_warn(LD_DIR, "Stored signing key does not match signing key in "
             "certificate");
    goto done;
  }

408
  crypto_pk_free(*key_out);
409
410
  authority_cert_free(*cert_out);

411
412
413
  *key_out = signing_key;
  *cert_out = parsed;
  r = 0;
414
  signing_key = NULL;
415
  parsed = NULL;
416
417
418
419

 done:
  tor_free(fname);
  tor_free(cert);
420
  crypto_pk_free(signing_key);
421
  authority_cert_free(parsed);
422
  return r;
423
424
}

425
426
427
428
429
430
431
432
433
434
435
/** 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 &&
436
      load_authority_keyset(1, &legacy_signing_key,
437
438
439
440
441
442
                            &legacy_key_certificate)<0)
    return -1;

  return 0;
}

Roger Dingledine's avatar
Roger Dingledine committed
443
/** If we're a v3 authority, check whether we have a certificate that's
444
 * likely to expire soon.  Warn if we do, but not too often. */
445
446
447
448
449
450
451
452
453
454
455
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;
456
  time_left = (int)( expires - now );
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  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) {
    log(badness, LD_DIR, "Your v3 authority certificate has expired."
        " Generate a new one NOW.");
  } else if (time_left <= 24*60*60) {
    log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
        " Generate a new one NOW.", time_left/(60*60));
  } else {
    log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
        " Generate a new one soon.", time_left/(24*60*60));
  }
  last_warned = now;
}

Nick Mathewson's avatar
Nick Mathewson committed
489
490
/** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
 * on success, and -1 on failure. */
491
492
493
494
495
496
497
498
499
500
int
router_initialize_tls_context(void)
{
  return tor_tls_context_init(public_server_mode(get_options()),
                              get_tlsclient_identity_key(),
                              server_mode(get_options()) ?
                              get_server_identity_key() : NULL,
                              MAX_SSL_KEY_LIFETIME_ADVERTISED);
}

Roger Dingledine's avatar
Roger Dingledine committed
501
/** Initialize all OR private keys, and the TLS context, as necessary.
502
503
 * 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
504
 */
505
506
507
int
init_keys(void)
{
508
  char *keydir;
509
  char fingerprint[FINGERPRINT_LEN+1];
Nick Mathewson's avatar
Nick Mathewson committed
510
511
  /*nickname<space>fp\n\0 */
  char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
512
  const char *mydesc;
513
  crypto_pk_t *prkey;
Roger Dingledine's avatar
Roger Dingledine committed
514
515
  char digest[DIGEST_LEN];
  char v3_digest[DIGEST_LEN];
516
  char *cp;
517
  const or_options_t *options = get_options();
518
  dirinfo_type_t type;
519
  time_t now = time(NULL);
520
521
  trusted_dir_server_t *ds;
  int v3_digest_set = 0;
522
  authority_cert_t *cert = NULL;
523

524
  if (!key_lock)
Nick Mathewson's avatar
Nick Mathewson committed
525
    key_lock = tor_mutex_new();
526

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

536
  /* OP's don't need persistent keys; just make up an identity and
537
   * initialize the TLS context. */
538
  if (!server_mode(options)) {
539
    if (!(prkey = crypto_pk_new()))
540
      return -1;
541
    if (crypto_pk_generate_key(prkey)) {
542
      crypto_pk_free(prkey);
543
      return -1;
544
    }
545
    set_client_identity_key(prkey);
546
    /* Create a TLS context. */
547
    if (router_initialize_tls_context() < 0) {
548
      log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
549
550
      return -1;
    }
551
552
    return 0;
  }
Nick Mathewson's avatar
Nick Mathewson committed
553
  /* Make sure DataDirectory exists, and is private. */
554
  if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
555
556
    return -1;
  }
Nick Mathewson's avatar
Nick Mathewson committed
557
  /* Check the key directory. */
558
  keydir = get_datadir_fname("keys");
559
  if (check_private_dir(keydir, CPD_CREATE, options->User)) {
560
    tor_free(keydir);
561
562
    return -1;
  }
563
  tor_free(keydir);
564

565
  /* 1a. Read v3 directory authority key/cert information. */
566
  memset(v3_digest, 0, sizeof(v3_digest));
567
  if (authdir_mode_v3(options)) {
568
569
570
571
572
573
    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;
    }
574
575
    cert = get_my_v3_authority_cert();
    if (cert) {
576
577
      crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
                           v3_digest);
578
      v3_digest_set = 1;
579
580
    }
  }
581

582
  /* 1b. Read identity key. Make it if none is found. */
583
  keydir = get_datadir_fname2("keys", "secret_id_key");
584
  log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
585
  prkey = init_key_from_file(keydir, 1, LOG_ERR);
586
  tor_free(keydir);
587
  if (!prkey) return -1;
588
589
590
591
592
593
  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)) {
594
    set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
595
  } else {
596
    if (!(prkey = crypto_pk_new()))
597
598
      return -1;
    if (crypto_pk_generate_key(prkey)) {
599
      crypto_pk_free(prkey);
600
601
602
603
      return -1;
    }
    set_client_identity_key(prkey);
  }
604

605
  /* 2. Read onion key.  Make it if none is found. */
606
  keydir = get_datadir_fname2("keys", "secret_onion_key");
607
  log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
608
  prkey = init_key_from_file(keydir, 1, LOG_ERR);
609
  tor_free(keydir);
610
611
  if (!prkey) return -1;
  set_onion_key(prkey);
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
  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);
    }
629
630
  }

631
  keydir = get_datadir_fname2("keys", "secret_onion_key.old");
632
  if (!lastonionkey && file_status(keydir) == FN_FILE) {
633
    prkey = init_key_from_file(keydir, 1, LOG_ERR);
634
635
636
    if (prkey)
      lastonionkey = prkey;
  }
637
  tor_free(keydir);
638
639

  /* 3. Initialize link key and TLS context. */
640
  if (router_initialize_tls_context() < 0) {
641
    log_err(LD_GENERAL,"Error initializing TLS context");
642
643
    return -1;
  }
644

645
  /* 4. Build our router descriptor. */
646
  /* Must be called after keys are initialized. */
647
  mydesc = router_get_my_descriptor();
648
  if (authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)) {
649
    const char *m = NULL;
650
    routerinfo_t *ri;
Roger Dingledine's avatar
Roger Dingledine committed
651
    /* We need to add our own fingerprint so it gets recognized. */
652
653
    if (dirserv_add_own_fingerprint(options->Nickname,
                                    get_server_identity_key())) {
654
      log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
Roger Dingledine's avatar
Roger Dingledine committed
655
656
      return -1;
    }
657
    if (mydesc) {
658
      was_router_added_t added;
659
      ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
660
661
662
663
      if (!ri) {
        log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
        return -1;
      }
664
665
      added = dirserv_add_descriptor(ri, &m, "self");
      if (!WRA_WAS_ADDED(added)) {
666
        if (!WRA_WAS_OUTDATED(added)) {
667
668
669
670
          log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
                  m?m:"<unknown error>");
          return -1;
        } else {
671
          /* If the descriptor was outdated, that's ok. This can happen
672
673
674
           * when some config options are toggled that affect workers, but
           * we don't really need new keys yet so the descriptor doesn't
           * change and the old one is still fresh. */
675
          log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
Roger Dingledine's avatar
Roger Dingledine committed
676
                   "after key init: %s This is usually not a problem.",
677
                   m?m:"<unknown error>");
678
        }
679
      }
Roger Dingledine's avatar
Roger Dingledine committed
680
    }
681
  }
Roger Dingledine's avatar
Roger Dingledine committed
682

683
  /* 5. Dump fingerprint to 'fingerprint' */
684
  keydir = get_datadir_fname("fingerprint");
685
  log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
686
687
  if (crypto_pk_get_fingerprint(get_server_identity_key(),
                                fingerprint, 0) < 0) {
688
    log_err(LD_GENERAL,"Error computing fingerprint");
689
    tor_free(keydir);
690
691
    return -1;
  }
692
693
694
  tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
                   "%s %s\n",options->Nickname, fingerprint) < 0) {
695
    log_err(LD_GENERAL,"Error writing fingerprint line");
696
    tor_free(keydir);
697
698
    return -1;
  }
699
700
701
  /* Check whether we need to write the fingerprint file. */
  cp = NULL;
  if (file_status(keydir) == FN_FILE)
702
    cp = read_file_to_str(keydir, 0, NULL);
703
  if (!cp || strcmp(cp, fingerprint_line)) {
704
705
    if (write_str_to_file(keydir, fingerprint_line, 0)) {
      log_err(LD_FS, "Error writing fingerprint line to file");
706
      tor_free(keydir);
707
      tor_free(cp);
708
709
      return -1;
    }
710
  }
711
  tor_free(cp);
712
  tor_free(keydir);
713
714

  log(LOG_NOTICE, LD_GENERAL,
715
      "Your Tor server's identity key fingerprint is '%s %s'",
716
      options->Nickname, fingerprint);
717
  if (!authdir_mode(options))
718
    return 0;
Roger Dingledine's avatar
Roger Dingledine committed
719
  /* 6. [authdirserver only] load approved-routers file */
720
  if (dirserv_load_fingerprint_file() < 0) {
721
    log_err(LD_GENERAL,"Error loading fingerprints");
722
723
    return -1;
  }
724
  /* 6b. [authdirserver only] add own key to approved directories. */
725
  crypto_pk_get_digest(get_server_identity_key(), digest);
726
727
  type = ((options->V1AuthoritativeDir ? V1_DIRINFO : NO_DIRINFO) |
          (options->V2AuthoritativeDir ? V2_DIRINFO : NO_DIRINFO) |
728
729
          (options->V3AuthoritativeDir ?
               (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
730
731
          (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO) |
          (options->HSAuthoritativeDir ? HIDSERV_DIRINFO : NO_DIRINFO));
732

733
  ds = router_get_trusteddirserver_by_digest(digest);
734
735
  if (!ds) {
    ds = add_trusted_dir_server(options->Nickname, NULL,
736
                                router_get_advertised_dir_port(options, 0),
737
                                router_get_advertised_or_port(options),
738
739
740
741
742
743
744
745
746
                                digest,
                                v3_digest,
                                type);
    if (!ds) {
      log_err(LD_GENERAL,"We want to be a directory authority, but we "
              "couldn't add ourselves to the authority list. Failing.");
      return -1;
    }
  }
747
748
749
750
751
752
  if (ds->type != type) {
    log_warn(LD_DIR,  "Configured authority type does not match authority "
             "type in DirServer list.  Adjusting. (%d v %d)",
             type, ds->type);
    ds->type = type;
  }
753
  if (v3_digest_set && (ds->type & V3_DIRINFO) &&
754
      tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
755
756
757
    log_warn(LD_DIR, "V3 identity key does not match identity declared in "
             "DirServer line.  Adjusting.");
    memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
758
759
  }

760
761
762
  if (cert) { /* add my own cert to the list of known certs */
    log_info(LD_DIR, "adding my own v3 cert");
    if (trusted_dirs_load_certs_from_string(
763
                      cert->cache_info.signed_descriptor_body, 0, 0)<0) {
764
765
766
767
768
      log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
      return -1;
    }
  }

769
  return 0; /* success */
770
771
}

772
773
774
775
776
/* Keep track of whether we should upload our server descriptor,
 * and what type of server we are.
 */

/** Whether we can reach our ORPort from the outside. */
777
static int can_reach_or_port = 0;
778
/** Whether we can reach our DirPort from the outside. */
779
static int can_reach_dir_port = 0;
780

781
/** Forget what we have learned about our reachability status. */
782
783
784
785
786
787
void
router_reset_reachability(void)
{
  can_reach_or_port = can_reach_dir_port = 0;
}

788
/** Return 1 if ORPort is known reachable; else return 0. */
789
790
791
int
check_whether_orport_reachable(void)
{
792
  const or_options_t *options = get_options();
793
  return options->AssumeReachable ||
794
         can_reach_or_port;
795
}
796

797
/** Return 1 if we don't have a dirport configured, or if it's reachable. */
798
799
800
int
check_whether_dirport_reachable(void)
{
801
  const or_options_t *options = get_options();
802
  return !options->DirPort_set ||
803
         options->AssumeReachable ||
804
         net_is_disabled() ||
805
         can_reach_dir_port;
806
807
}

808
809
/** Look at a variety of factors, and return 0 if we don't want to
 * advertise the fact that we have a DirPort open. Else return the
810
811
812
813
814
 * DirPort we want to advertise.
 *
 * Log a helpful message if we change our mind about whether to publish
 * a DirPort.
 */
815
static int
816
decide_to_advertise_dirport(const or_options_t *options, uint16_t dir_port)
817
{
818
819
820
821
822
823
824
825
  static int advertising=1; /* start out assuming we will advertise */
  int new_choice=1;
  const char *reason = NULL;

  /* Section one: reasons to publish or not publish that aren't
   * worth mentioning to the user, either because they're obvious
   * or because they're normal behavior. */

826
  if (!dir_port) /* short circuit the rest of the function */
827
828
    return 0;
  if (authdir_mode(options)) /* always publish */
829
    return dir_port;
830
  if (net_is_disabled())
831
832
833
    return 0;
  if (!check_whether_dirport_reachable())
    return 0;
834
  if (!router_get_advertised_dir_port(options, dir_port))
835
    return 0;
836

837
838
839
840
841
  /* Section two: reasons to publish or not publish that the user
   * might find surprising. These are generally config options that
   * make us choose not to publish. */

  if (accounting_is_enabled(options)) {
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
    /* Don't spend bytes for directory traffic if we could end up hibernating,
     * but allow DirPort otherwise. Some people set AccountingMax because
     * they're confused or to get statistics. */
    int interval_length = accounting_get_interval_length();
    uint32_t effective_bw = get_effective_bwrate(options);
    if (!interval_length) {
      log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
                       "seconds long. Raising to 1.");
      interval_length = 1;
    }
    log_info(LD_GENERAL, "Calculating whether to disable dirport: effective "
                         "bwrate: %u, AccountingMax: "U64_FORMAT", "
                         "accounting interval length %d", effective_bw,
                         U64_PRINTF_ARG(options->AccountingMax),
                         interval_length);
    if (effective_bw >=
        options->AccountingMax / interval_length) {
      new_choice = 0;
      reason = "AccountingMax enabled";
    }
862
863
864
865
#define MIN_BW_TO_ADVERTISE_DIRPORT 51200
  } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
             (options->RelayBandwidthRate > 0 &&
              options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
866
867
868
869
870
871
872
    /* if we're advertising a small amount */
    new_choice = 0;
    reason = "BandwidthRate under 50KB";
  }

  if (advertising != new_choice) {
    if (new_choice == 1) {
873
      log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
874
875
876
877
878
879
880
    } else {
      tor_assert(reason);
      log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
    }
    advertising = new_choice;
  }

881
  return advertising ? dir_port : 0;
882
883
}

884
885
886
887
888
889
890
891
892
893
894
/** Allocate and return a new extend_info_t that can be used to build
 * a circuit to or through the router <b>r</b>. Use the primary
 * address of the router unless <b>for_direct_connect</b> is true, in
 * which case the preferred address is used instead. */
static extend_info_t *
extend_info_from_router(const routerinfo_t *r)
{
  tor_addr_port_t ap;
  tor_assert(r);

  router_get_prim_orport(r, &ap);
895
  return extend_info_new(r->nickname, r->cache_info.identity_digest,
896
897
898
                           r->onion_pkey, &ap.addr, ap.port);
}

Roger Dingledine's avatar
Roger Dingledine committed
899
900
901
902
903
904
905
906
907
908
909
/** Some time has passed, or we just got new directory information.
 * See if we currently believe our ORPort or DirPort to be
 * unreachable. If so, launch a new test for it.
 *
 * For ORPort, we simply try making a circuit that ends at ourselves.
 * Success is noticed in onionskin_answer().
 *
 * For DirPort, we make a connection via Tor to our DirPort and ask
 * for our own server descriptor.
 * Success is noticed in connection_dir_client_reached_eof().
 */
910
void
911
consider_testing_reachability(int test_or, int test_dir)
912
{
913
  const routerinfo_t *me = router_get_my_routerinfo();
914
  int orport_reachable = check_whether_orport_reachable();
915
  tor_addr_t addr;
916
  const or_options_t *options = get_options();
917
  if (!me)
918
    return;
919

920
  if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
921
922
923
924
925
926
927
928
929
930
      options->StrictNodes) {
    /* If we've excluded ourself, and StrictNodes is set, we can't test
     * ourself. */
    if (test_or || test_dir) {
#define SELF_EXCLUDED_WARN_INTERVAL 3600
      static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
      char *msg;
      if ((msg = rate_limit_log(&warning_limit, approx_time()))) {
        log_warn(LD_CIRC, "Can't peform self-tests for this relay: we have "
                 "listed ourself in ExcludeNodes, and StrictNodes is set. "
Sebastian Hahn's avatar
Sebastian Hahn committed
931
                 "We cannot learn whether we are usable, and will not "
932
933
934
935
936
937
938
                 "be able to advertise ourself.%s", msg);