Update new relay blogpost URL
[tor.git] / src / feature / relay / router.c
blobc4170cd720b566616057f804574ac25fdce2579f
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 #define ROUTER_PRIVATE
9 #include "core/or/or.h"
10 #include "app/config/config.h"
11 #include "app/config/statefile.h"
12 #include "app/main/main.h"
13 #include "core/mainloop/connection.h"
14 #include "core/mainloop/mainloop.h"
15 #include "core/mainloop/netstatus.h"
16 #include "core/or/policies.h"
17 #include "core/or/protover.h"
18 #include "feature/client/transports.h"
19 #include "feature/control/control.h"
20 #include "feature/dirauth/process_descs.h"
21 #include "feature/dircache/dirserv.h"
22 #include "feature/dirclient/dirclient.h"
23 #include "feature/dircommon/directory.h"
24 #include "feature/dirparse/authcert_parse.h"
25 #include "feature/dirparse/routerparse.h"
26 #include "feature/dirparse/signing.h"
27 #include "feature/hibernate/hibernate.h"
28 #include "feature/keymgt/loadkey.h"
29 #include "feature/nodelist/authcert.h"
30 #include "feature/nodelist/dirlist.h"
31 #include "feature/nodelist/networkstatus.h"
32 #include "feature/nodelist/nickname.h"
33 #include "feature/nodelist/nodelist.h"
34 #include "feature/nodelist/routerlist.h"
35 #include "feature/nodelist/torcert.h"
36 #include "feature/relay/dns.h"
37 #include "feature/relay/router.h"
38 #include "feature/relay/routerkeys.h"
39 #include "feature/relay/routermode.h"
40 #include "feature/relay/selftest.h"
41 #include "lib/geoip/geoip.h"
42 #include "feature/stats/geoip_stats.h"
43 #include "feature/stats/rephist.h"
44 #include "lib/crypt_ops/crypto_ed25519.h"
45 #include "lib/crypt_ops/crypto_format.h"
46 #include "lib/crypt_ops/crypto_init.h"
47 #include "lib/crypt_ops/crypto_rand.h"
48 #include "lib/crypt_ops/crypto_util.h"
49 #include "lib/encoding/confline.h"
50 #include "lib/osinfo/uname.h"
51 #include "lib/tls/tortls.h"
53 #include "feature/dirauth/authmode.h"
55 #include "app/config/or_state_st.h"
56 #include "core/or/port_cfg_st.h"
57 #include "feature/dirclient/dir_server_st.h"
58 #include "feature/dircommon/dir_connection_st.h"
59 #include "feature/nodelist/authority_cert_st.h"
60 #include "feature/nodelist/extrainfo_st.h"
61 #include "feature/nodelist/node_st.h"
62 #include "feature/nodelist/routerinfo_st.h"
63 #include "feature/nodelist/routerstatus_st.h"
65 /**
66 * \file router.c
67 * \brief Miscellaneous relay functionality, including RSA key maintenance,
68 * generating and uploading server descriptors, picking an address to
69 * advertise, and so on.
71 * This module handles the job of deciding whether we are a Tor relay, and if
72 * so what kind. (Mostly through functions like server_mode() that inspect an
73 * or_options_t, but in some cases based on our own capabilities, such as when
74 * we are deciding whether to be a directory cache in
75 * router_has_bandwidth_to_be_dirserver().)
77 * Also in this module are the functions to generate our own routerinfo_t and
78 * extrainfo_t, and to encode those to signed strings for upload to the
79 * directory authorities.
81 * This module also handles key maintenance for RSA and Curve25519-ntor keys,
82 * and for our TLS context. (These functions should eventually move to
83 * routerkeys.c along with the code that handles Ed25519 keys now.)
84 **/
86 /************************************************************/
88 /*****
89 * Key management: ORs only.
90 *****/
92 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
94 static tor_mutex_t *key_lock=NULL;
95 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
96 /** Current private onionskin decryption key: used to decode CREATE cells. */
97 static crypto_pk_t *onionkey=NULL;
98 /** Previous private onionskin decryption key: used to decode CREATE cells
99 * generated by clients that have an older version of our descriptor. */
100 static crypto_pk_t *lastonionkey=NULL;
101 /** Current private ntor secret key: used to perform the ntor handshake. */
102 static curve25519_keypair_t curve25519_onion_key;
103 /** Previous private ntor secret key: used to perform the ntor handshake
104 * with clients that have an older version of our descriptor. */
105 static curve25519_keypair_t last_curve25519_onion_key;
106 /** Private server "identity key": used to sign directory info and TLS
107 * certificates. Never changes. */
108 static crypto_pk_t *server_identitykey=NULL;
109 /** Digest of server_identitykey. */
110 static char server_identitykey_digest[DIGEST_LEN];
111 /** Private client "identity key": used to sign bridges' and clients'
112 * outbound TLS certificates. Regenerated on startup and on IP address
113 * change. */
114 static crypto_pk_t *client_identitykey=NULL;
115 /** Signing key used for v3 directory material; only set for authorities. */
116 static crypto_pk_t *authority_signing_key = NULL;
117 /** Key certificate to authenticate v3 directory material; only set for
118 * authorities. */
119 static authority_cert_t *authority_key_certificate = NULL;
121 /** For emergency V3 authority key migration: An extra signing key that we use
122 * with our old (obsolete) identity key for a while. */
123 static crypto_pk_t *legacy_signing_key = NULL;
124 /** For emergency V3 authority key migration: An extra certificate to
125 * authenticate legacy_signing_key with our obsolete identity key.*/
126 static authority_cert_t *legacy_key_certificate = NULL;
128 /* (Note that v3 authorities also have a separate "authority identity key",
129 * but this key is never actually loaded by the Tor process. Instead, it's
130 * used by tor-gencert to sign new signing keys and make new key
131 * certificates. */
133 /** Return a readonly string with human readable description
134 * of <b>err</b>.
136 const char *
137 routerinfo_err_to_string(int err)
139 switch (err) {
140 case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
141 return "No known exit address yet";
142 case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
143 return "Cannot parse descriptor";
144 case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
145 return "Not running in server mode";
146 case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
147 return "Key digest failed";
148 case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
149 return "Cannot generate descriptor";
150 case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
151 return "Descriptor still rebuilding - not ready yet";
154 log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
155 tor_assert_unreached();
157 return "Unknown error";
160 /** Return true if we expect given error to be transient.
161 * Return false otherwise.
164 routerinfo_err_is_transient(int err)
167 * For simplicity, we consider all errors other than
168 * "not a server" transient - see discussion on
169 * https://trac.torproject.org/projects/tor/ticket/27034
171 return err != TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
174 /** Replace the current onion key with <b>k</b>. Does not affect
175 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
177 static void
178 set_onion_key(crypto_pk_t *k)
180 if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
181 /* k is already our onion key; free it and return */
182 crypto_pk_free(k);
183 return;
185 tor_mutex_acquire(key_lock);
186 crypto_pk_free(onionkey);
187 onionkey = k;
188 tor_mutex_release(key_lock);
189 mark_my_descriptor_dirty("set onion key");
192 /** Return the current onion key. Requires that the onion key has been
193 * loaded or generated. */
194 crypto_pk_t *
195 get_onion_key(void)
197 tor_assert(onionkey);
198 return onionkey;
201 /** Store a full copy of the current onion key into *<b>key</b>, and a full
202 * copy of the most recent onion key into *<b>last</b>. Store NULL into
203 * a pointer if the corresponding key does not exist.
205 void
206 dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
208 tor_assert(key);
209 tor_assert(last);
210 tor_mutex_acquire(key_lock);
211 if (onionkey)
212 *key = crypto_pk_copy_full(onionkey);
213 else
214 *key = NULL;
215 if (lastonionkey)
216 *last = crypto_pk_copy_full(lastonionkey);
217 else
218 *last = NULL;
219 tor_mutex_release(key_lock);
222 /** Expire our old set of onion keys. This is done by setting
223 * last_curve25519_onion_key and lastonionkey to all zero's and NULL
224 * respectively.
226 * This function does not perform any grace period checks for the old onion
227 * keys.
229 void
230 expire_old_onion_keys(void)
232 char *fname = NULL;
234 tor_mutex_acquire(key_lock);
236 /* Free lastonionkey and set it to NULL. */
237 if (lastonionkey) {
238 crypto_pk_free(lastonionkey);
239 lastonionkey = NULL;
242 /* We zero out the keypair. See the tor_mem_is_zero() check made in
243 * construct_ntor_key_map() below. */
244 memset(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
246 tor_mutex_release(key_lock);
248 fname = get_keydir_fname("secret_onion_key.old");
249 if (file_status(fname) == FN_FILE) {
250 if (tor_unlink(fname) != 0) {
251 log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
252 fname, strerror(errno));
255 tor_free(fname);
257 fname = get_keydir_fname("secret_onion_key_ntor.old");
258 if (file_status(fname) == FN_FILE) {
259 if (tor_unlink(fname) != 0) {
260 log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
261 fname, strerror(errno));
264 tor_free(fname);
267 /** Return the current secret onion key for the ntor handshake. Must only
268 * be called from the main thread. */
269 static const curve25519_keypair_t *
270 get_current_curve25519_keypair(void)
272 return &curve25519_onion_key;
274 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
275 * handshake. Must only be called from the main thread. */
276 di_digest256_map_t *
277 construct_ntor_key_map(void)
279 di_digest256_map_t *m = NULL;
281 const uint8_t *cur_pk = curve25519_onion_key.pubkey.public_key;
282 const uint8_t *last_pk = last_curve25519_onion_key.pubkey.public_key;
284 if (!tor_mem_is_zero((const char *)cur_pk, CURVE25519_PUBKEY_LEN)) {
285 dimap_add_entry(&m, cur_pk,
286 tor_memdup(&curve25519_onion_key,
287 sizeof(curve25519_keypair_t)));
289 if (!tor_mem_is_zero((const char*)last_pk, CURVE25519_PUBKEY_LEN) &&
290 tor_memneq(cur_pk, last_pk, CURVE25519_PUBKEY_LEN)) {
291 dimap_add_entry(&m, last_pk,
292 tor_memdup(&last_curve25519_onion_key,
293 sizeof(curve25519_keypair_t)));
296 return m;
298 /** Helper used to deallocate a di_digest256_map_t returned by
299 * construct_ntor_key_map. */
300 static void
301 ntor_key_map_free_helper(void *arg)
303 curve25519_keypair_t *k = arg;
304 memwipe(k, 0, sizeof(*k));
305 tor_free(k);
307 /** Release all storage from a keymap returned by construct_ntor_key_map. */
308 void
309 ntor_key_map_free_(di_digest256_map_t *map)
311 if (!map)
312 return;
313 dimap_free(map, ntor_key_map_free_helper);
316 /** Return the time when the onion key was last set. This is either the time
317 * when the process launched, or the time of the most recent key rotation since
318 * the process launched.
320 time_t
321 get_onion_key_set_at(void)
323 return onionkey_set_at;
326 /** Set the current server identity key to <b>k</b>.
328 void
329 set_server_identity_key(crypto_pk_t *k)
331 crypto_pk_free(server_identitykey);
332 server_identitykey = k;
333 if (crypto_pk_get_digest(server_identitykey,
334 server_identitykey_digest) < 0) {
335 log_err(LD_BUG, "Couldn't compute our own identity key digest.");
336 tor_assert(0);
340 /** Make sure that we have set up our identity keys to match or not match as
341 * appropriate, and die with an assertion if we have not. */
342 static void
343 assert_identity_keys_ok(void)
345 if (1)
346 return;
347 tor_assert(client_identitykey);
348 if (public_server_mode(get_options())) {
349 /* assert that we have set the client and server keys to be equal */
350 tor_assert(server_identitykey);
351 tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
352 } else {
353 /* assert that we have set the client and server keys to be unequal */
354 if (server_identitykey)
355 tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
359 /** Returns the current server identity key; requires that the key has
360 * been set, and that we are running as a Tor server.
362 crypto_pk_t *
363 get_server_identity_key(void)
365 tor_assert(server_identitykey);
366 tor_assert(server_mode(get_options()));
367 assert_identity_keys_ok();
368 return server_identitykey;
371 /** Return true iff we are a server and the server identity key
372 * has been set. */
374 server_identity_key_is_set(void)
376 return server_mode(get_options()) && server_identitykey != NULL;
379 /** Set the current client identity key to <b>k</b>.
381 void
382 set_client_identity_key(crypto_pk_t *k)
384 crypto_pk_free(client_identitykey);
385 client_identitykey = k;
388 /** Returns the current client identity key for use on outgoing TLS
389 * connections; requires that the key has been set.
391 crypto_pk_t *
392 get_tlsclient_identity_key(void)
394 tor_assert(client_identitykey);
395 assert_identity_keys_ok();
396 return client_identitykey;
399 /** Return true iff the client identity key has been set. */
401 client_identity_key_is_set(void)
403 return client_identitykey != NULL;
406 /** Return the key certificate for this v3 (voting) authority, or NULL
407 * if we have no such certificate. */
408 MOCK_IMPL(authority_cert_t *,
409 get_my_v3_authority_cert, (void))
411 return authority_key_certificate;
414 /** Return the v3 signing key for this v3 (voting) authority, or NULL
415 * if we have no such key. */
416 crypto_pk_t *
417 get_my_v3_authority_signing_key(void)
419 return authority_signing_key;
422 /** If we're an authority, and we're using a legacy authority identity key for
423 * emergency migration purposes, return the certificate associated with that
424 * key. */
425 authority_cert_t *
426 get_my_v3_legacy_cert(void)
428 return legacy_key_certificate;
431 /** If we're an authority, and we're using a legacy authority identity key for
432 * emergency migration purposes, return that key. */
433 crypto_pk_t *
434 get_my_v3_legacy_signing_key(void)
436 return legacy_signing_key;
439 /** Replace the previous onion key with the current onion key, and generate
440 * a new previous onion key. Immediately after calling this function,
441 * the OR should:
442 * - schedule all previous cpuworkers to shut down _after_ processing
443 * pending work. (This will cause fresh cpuworkers to be generated.)
444 * - generate and upload a fresh routerinfo.
446 void
447 rotate_onion_key(void)
449 char *fname, *fname_prev;
450 crypto_pk_t *prkey = NULL;
451 or_state_t *state = get_or_state();
452 curve25519_keypair_t new_curve25519_keypair;
453 time_t now;
454 fname = get_keydir_fname("secret_onion_key");
455 fname_prev = get_keydir_fname("secret_onion_key.old");
456 /* There isn't much point replacing an old key with an empty file */
457 if (file_status(fname) == FN_FILE) {
458 if (replace_file(fname, fname_prev))
459 goto error;
461 if (!(prkey = crypto_pk_new())) {
462 log_err(LD_GENERAL,"Error constructing rotated onion key");
463 goto error;
465 if (crypto_pk_generate_key(prkey)) {
466 log_err(LD_BUG,"Error generating onion key");
467 goto error;
469 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
470 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
471 goto error;
473 tor_free(fname);
474 tor_free(fname_prev);
475 fname = get_keydir_fname("secret_onion_key_ntor");
476 fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
477 if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
478 goto error;
479 /* There isn't much point replacing an old key with an empty file */
480 if (file_status(fname) == FN_FILE) {
481 if (replace_file(fname, fname_prev))
482 goto error;
484 if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
485 "onion") < 0) {
486 log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
487 goto error;
489 log_info(LD_GENERAL, "Rotating onion key");
490 tor_mutex_acquire(key_lock);
491 crypto_pk_free(lastonionkey);
492 lastonionkey = onionkey;
493 onionkey = prkey;
494 memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
495 sizeof(curve25519_keypair_t));
496 memcpy(&curve25519_onion_key, &new_curve25519_keypair,
497 sizeof(curve25519_keypair_t));
498 now = time(NULL);
499 state->LastRotatedOnionKey = onionkey_set_at = now;
500 tor_mutex_release(key_lock);
501 mark_my_descriptor_dirty("rotated onion key");
502 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
503 goto done;
504 error:
505 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
506 if (prkey)
507 crypto_pk_free(prkey);
508 done:
509 memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
510 tor_free(fname);
511 tor_free(fname_prev);
514 /** Log greeting message that points to new relay lifecycle document the
515 * first time this function has been called.
517 static void
518 log_new_relay_greeting(void)
520 static int already_logged = 0;
522 if (already_logged)
523 return;
525 tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
526 "Thanks for helping the Tor network! If you wish to know "
527 "what will happen in the upcoming weeks regarding its usage, "
528 "have a look at https://blog.torproject.org/lifecycle-of-a"
529 "-new-relay");
531 already_logged = 1;
534 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
535 * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
536 * is true, create a new keypair and write it into the file. If there are
537 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
538 * in their ASCII wrapper. */
539 static int
540 init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
541 const char *fname,
542 int generate,
543 int severity,
544 const char *tag)
546 switch (file_status(fname)) {
547 case FN_DIR:
548 case FN_ERROR:
549 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
550 goto error;
551 /* treat empty key files as if the file doesn't exist, and, if generate
552 * is set, replace the empty file in curve25519_keypair_write_to_file() */
553 case FN_NOENT:
554 case FN_EMPTY:
555 if (generate) {
556 if (!have_lockfile()) {
557 if (try_locking(get_options(), 0)<0) {
558 /* Make sure that --list-fingerprint only creates new keys
559 * if there is no possibility for a deadlock. */
560 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
561 "Not writing any new keys.", fname);
562 /*XXXX The 'other process' might make a key in a second or two;
563 * maybe we should wait for it. */
564 goto error;
567 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
568 fname);
569 if (curve25519_keypair_generate(keys_out, 1) < 0)
570 goto error;
571 if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
572 tor_log(severity, LD_FS,
573 "Couldn't write generated key to \"%s\".", fname);
574 memwipe(keys_out, 0, sizeof(*keys_out));
575 goto error;
577 } else {
578 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
580 return 0;
581 case FN_FILE:
583 char *tag_in=NULL;
584 if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
585 tor_log(severity, LD_GENERAL,"Error loading private key.");
586 tor_free(tag_in);
587 goto error;
589 if (!tag_in || strcmp(tag_in, tag)) {
590 tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
591 escaped(tag_in));
592 tor_free(tag_in);
593 goto error;
595 tor_free(tag_in);
596 return 0;
598 default:
599 tor_assert(0);
602 error:
603 return -1;
606 /** Try to load the vote-signing private key and certificate for being a v3
607 * directory authority, and make sure they match. If <b>legacy</b>, load a
608 * legacy key/cert set for emergency key migration; otherwise load the regular
609 * key/cert set. On success, store them into *<b>key_out</b> and
610 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
611 static int
612 load_authority_keyset(int legacy, crypto_pk_t **key_out,
613 authority_cert_t **cert_out)
615 int r = -1;
616 char *fname = NULL, *cert = NULL;
617 const char *eos = NULL;
618 crypto_pk_t *signing_key = NULL;
619 authority_cert_t *parsed = NULL;
621 fname = get_keydir_fname(
622 legacy ? "legacy_signing_key" : "authority_signing_key");
623 signing_key = init_key_from_file(fname, 0, LOG_ERR, NULL);
624 if (!signing_key) {
625 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
626 goto done;
628 tor_free(fname);
629 fname = get_keydir_fname(
630 legacy ? "legacy_certificate" : "authority_certificate");
631 cert = read_file_to_str(fname, 0, NULL);
632 if (!cert) {
633 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
634 fname);
635 goto done;
637 parsed = authority_cert_parse_from_string(cert, &eos);
638 if (!parsed) {
639 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
640 goto done;
642 if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
643 log_warn(LD_DIR, "Stored signing key does not match signing key in "
644 "certificate");
645 goto done;
648 crypto_pk_free(*key_out);
649 authority_cert_free(*cert_out);
651 *key_out = signing_key;
652 *cert_out = parsed;
653 r = 0;
654 signing_key = NULL;
655 parsed = NULL;
657 done:
658 tor_free(fname);
659 tor_free(cert);
660 crypto_pk_free(signing_key);
661 authority_cert_free(parsed);
662 return r;
665 /** Load the v3 (voting) authority signing key and certificate, if they are
666 * present. Return -1 if anything is missing, mismatched, or unloadable;
667 * return 0 on success. */
668 static int
669 init_v3_authority_keys(void)
671 if (load_authority_keyset(0, &authority_signing_key,
672 &authority_key_certificate)<0)
673 return -1;
675 if (get_options()->V3AuthUseLegacyKey &&
676 load_authority_keyset(1, &legacy_signing_key,
677 &legacy_key_certificate)<0)
678 return -1;
680 return 0;
683 /** If we're a v3 authority, check whether we have a certificate that's
684 * likely to expire soon. Warn if we do, but not too often. */
685 void
686 v3_authority_check_key_expiry(void)
688 time_t now, expires;
689 static time_t last_warned = 0;
690 int badness, time_left, warn_interval;
691 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
692 return;
694 now = time(NULL);
695 expires = authority_key_certificate->expires;
696 time_left = (int)( expires - now );
697 if (time_left <= 0) {
698 badness = LOG_ERR;
699 warn_interval = 60*60;
700 } else if (time_left <= 24*60*60) {
701 badness = LOG_WARN;
702 warn_interval = 60*60;
703 } else if (time_left <= 24*60*60*7) {
704 badness = LOG_WARN;
705 warn_interval = 24*60*60;
706 } else if (time_left <= 24*60*60*30) {
707 badness = LOG_WARN;
708 warn_interval = 24*60*60*5;
709 } else {
710 return;
713 if (last_warned + warn_interval > now)
714 return;
716 if (time_left <= 0) {
717 tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
718 " Generate a new one NOW.");
719 } else if (time_left <= 24*60*60) {
720 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
721 "hours; Generate a new one NOW.", time_left/(60*60));
722 } else {
723 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
724 "days; Generate a new one soon.", time_left/(24*60*60));
726 last_warned = now;
729 /** Get the lifetime of an onion key in days. This value is defined by the
730 * network consesus parameter "onion-key-rotation-days". Always returns a value
731 * between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
732 * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
734 static int
735 get_onion_key_rotation_days_(void)
737 return networkstatus_get_param(NULL,
738 "onion-key-rotation-days",
739 DEFAULT_ONION_KEY_LIFETIME_DAYS,
740 MIN_ONION_KEY_LIFETIME_DAYS,
741 MAX_ONION_KEY_LIFETIME_DAYS);
744 /** Get the current lifetime of an onion key in seconds. This value is defined
745 * by the network consesus parameter "onion-key-rotation-days", but the value
746 * is converted to seconds.
749 get_onion_key_lifetime(void)
751 return get_onion_key_rotation_days_()*24*60*60;
754 /** Get the grace period of an onion key in seconds. This value is defined by
755 * the network consesus parameter "onion-key-grace-period-days", but the value
756 * is converted to seconds.
759 get_onion_key_grace_period(void)
761 int grace_period;
762 grace_period = networkstatus_get_param(NULL,
763 "onion-key-grace-period-days",
764 DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS,
765 MIN_ONION_KEY_GRACE_PERIOD_DAYS,
766 get_onion_key_rotation_days_());
767 return grace_period*24*60*60;
770 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
771 * on success, and -1 on failure. */
773 router_initialize_tls_context(void)
775 unsigned int flags = 0;
776 const or_options_t *options = get_options();
777 int lifetime = options->SSLKeyLifetime;
778 if (public_server_mode(options))
779 flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
780 if (!lifetime) { /* we should guess a good ssl cert lifetime */
782 /* choose between 5 and 365 days, and round to the day */
783 unsigned int five_days = 5*24*3600;
784 unsigned int one_year = 365*24*3600;
785 lifetime = crypto_rand_int_range(five_days, one_year);
786 lifetime -= lifetime % (24*3600);
788 if (crypto_rand_int(2)) {
789 /* Half the time we expire at midnight, and half the time we expire
790 * one second before midnight. (Some CAs wobble their expiry times a
791 * bit in practice, perhaps to reduce collision attacks; see ticket
792 * 8443 for details about observed certs in the wild.) */
793 lifetime--;
797 /* It's ok to pass lifetime in as an unsigned int, since
798 * config_parse_interval() checked it. */
799 return tor_tls_context_init(flags,
800 get_tlsclient_identity_key(),
801 server_mode(options) ?
802 get_server_identity_key() : NULL,
803 (unsigned int)lifetime);
806 /** Announce URL to bridge status page. */
807 STATIC void
808 router_announce_bridge_status_page(void)
810 char fingerprint[FINGERPRINT_LEN + 1];
812 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
813 fingerprint) < 0) {
814 // LCOV_EXCL_START
815 log_err(LD_GENERAL, "Unable to compute bridge fingerprint");
816 return;
817 // LCOV_EXCL_STOP
820 log_notice(LD_GENERAL, "You can check the status of your bridge relay at "
821 "https://bridges.torproject.org/status?id=%s",
822 fingerprint);
825 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
826 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
827 * -1 if Tor should die,
829 STATIC int
830 router_write_fingerprint(int hashed)
832 char *keydir = NULL, *cp = NULL;
833 const char *fname = hashed ? "hashed-fingerprint" :
834 "fingerprint";
835 char fingerprint[FINGERPRINT_LEN+1];
836 const or_options_t *options = get_options();
837 char *fingerprint_line = NULL;
838 int result = -1;
840 keydir = get_datadir_fname(fname);
841 log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
842 hashed ? "hashed " : "", keydir);
843 if (!hashed) {
844 if (crypto_pk_get_fingerprint(get_server_identity_key(),
845 fingerprint, 0) < 0) {
846 log_err(LD_GENERAL,"Error computing fingerprint");
847 goto done;
849 } else {
850 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
851 fingerprint) < 0) {
852 log_err(LD_GENERAL,"Error computing hashed fingerprint");
853 goto done;
857 tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
859 /* Check whether we need to write the (hashed-)fingerprint file. */
861 cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
862 if (!cp || strcmp(cp, fingerprint_line)) {
863 if (write_str_to_file(keydir, fingerprint_line, 0)) {
864 log_err(LD_FS, "Error writing %sfingerprint line to file",
865 hashed ? "hashed " : "");
866 goto done;
870 log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
871 hashed ? "bridge's hashed" : "server's", options->Nickname,
872 fingerprint);
874 result = 0;
875 done:
876 tor_free(cp);
877 tor_free(keydir);
878 tor_free(fingerprint_line);
879 return result;
882 static int
883 init_keys_common(void)
885 if (!key_lock)
886 key_lock = tor_mutex_new();
888 /* There are a couple of paths that put us here before we've asked
889 * openssl to initialize itself. */
890 if (crypto_global_init(get_options()->HardwareAccel,
891 get_options()->AccelName,
892 get_options()->AccelDir)) {
893 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
894 return -1;
897 return 0;
901 init_keys_client(void)
903 crypto_pk_t *prkey;
904 if (init_keys_common() < 0)
905 return -1;
907 if (!(prkey = crypto_pk_new()))
908 return -1;
909 if (crypto_pk_generate_key(prkey)) {
910 crypto_pk_free(prkey);
911 return -1;
913 set_client_identity_key(prkey);
914 /* Create a TLS context. */
915 if (router_initialize_tls_context() < 0) {
916 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
917 return -1;
919 return 0;
922 /** Initialize all OR private keys, and the TLS context, as necessary.
923 * On OPs, this only initializes the tls context. Return 0 on success,
924 * or -1 if Tor should die.
927 init_keys(void)
929 char *keydir;
930 const char *mydesc;
931 crypto_pk_t *prkey;
932 char digest[DIGEST_LEN];
933 char v3_digest[DIGEST_LEN];
934 const or_options_t *options = get_options();
935 dirinfo_type_t type;
936 time_t now = time(NULL);
937 dir_server_t *ds;
938 int v3_digest_set = 0;
939 authority_cert_t *cert = NULL;
941 /* OP's don't need persistent keys; just make up an identity and
942 * initialize the TLS context. */
943 if (!server_mode(options)) {
944 return init_keys_client();
946 if (init_keys_common() < 0)
947 return -1;
949 if (create_keys_directory(options) < 0)
950 return -1;
952 /* 1a. Read v3 directory authority key/cert information. */
953 memset(v3_digest, 0, sizeof(v3_digest));
954 if (authdir_mode_v3(options)) {
955 if (init_v3_authority_keys()<0) {
956 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
957 "were unable to load our v3 authority keys and certificate! "
958 "Use tor-gencert to generate them. Dying.");
959 return -1;
961 cert = get_my_v3_authority_cert();
962 if (cert) {
963 if (crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
964 v3_digest) < 0) {
965 log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
966 "digest.");
967 return -1;
969 v3_digest_set = 1;
973 /* 1b. Read identity key. Make it if none is found. */
974 keydir = get_keydir_fname("secret_id_key");
975 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
976 bool created = false;
977 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
978 tor_free(keydir);
979 if (!prkey) return -1;
980 if (created)
981 log_new_relay_greeting();
982 set_server_identity_key(prkey);
984 /* 1c. If we are configured as a bridge, generate a client key;
985 * otherwise, set the server identity key as our client identity
986 * key. */
987 if (public_server_mode(options)) {
988 set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
989 } else {
990 if (!(prkey = crypto_pk_new()))
991 return -1;
992 if (crypto_pk_generate_key(prkey)) {
993 crypto_pk_free(prkey);
994 return -1;
996 set_client_identity_key(prkey);
999 /* 1d. Load all ed25519 keys */
1000 const int new_signing_key = load_ed_keys(options,now);
1001 if (new_signing_key < 0)
1002 return -1;
1004 /* 2. Read onion key. Make it if none is found. */
1005 keydir = get_keydir_fname("secret_onion_key");
1006 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
1007 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
1008 if (created)
1009 log_new_relay_greeting();
1010 tor_free(keydir);
1011 if (!prkey) return -1;
1012 set_onion_key(prkey);
1013 if (options->command == CMD_RUN_TOR) {
1014 /* only mess with the state file if we're actually running Tor */
1015 or_state_t *state = get_or_state();
1016 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
1017 /* We allow for some parsing slop, but we don't want to risk accepting
1018 * values in the distant future. If we did, we might never rotate the
1019 * onion key. */
1020 onionkey_set_at = state->LastRotatedOnionKey;
1021 } else {
1022 /* We have no LastRotatedOnionKey set; either we just created the key
1023 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
1024 * start the clock ticking now so that we will eventually rotate it even
1025 * if we don't stay up for the full lifetime of an onion key. */
1026 state->LastRotatedOnionKey = onionkey_set_at = now;
1027 or_state_mark_dirty(state, options->AvoidDiskWrites ?
1028 time(NULL)+3600 : 0);
1032 keydir = get_keydir_fname("secret_onion_key.old");
1033 if (!lastonionkey && file_status(keydir) == FN_FILE) {
1034 /* Load keys from non-empty files only.
1035 * Missing old keys won't be replaced with freshly generated keys. */
1036 prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
1037 if (prkey)
1038 lastonionkey = prkey;
1040 tor_free(keydir);
1043 /* 2b. Load curve25519 onion keys. */
1044 int r;
1045 keydir = get_keydir_fname("secret_onion_key_ntor");
1046 r = init_curve25519_keypair_from_file(&curve25519_onion_key,
1047 keydir, 1, LOG_ERR, "onion");
1048 tor_free(keydir);
1049 if (r<0)
1050 return -1;
1052 keydir = get_keydir_fname("secret_onion_key_ntor.old");
1053 if (tor_mem_is_zero((const char *)
1054 last_curve25519_onion_key.pubkey.public_key,
1055 CURVE25519_PUBKEY_LEN) &&
1056 file_status(keydir) == FN_FILE) {
1057 /* Load keys from non-empty files only.
1058 * Missing old keys won't be replaced with freshly generated keys. */
1059 init_curve25519_keypair_from_file(&last_curve25519_onion_key,
1060 keydir, 0, LOG_ERR, "onion");
1062 tor_free(keydir);
1065 /* 3. Initialize link key and TLS context. */
1066 if (router_initialize_tls_context() < 0) {
1067 log_err(LD_GENERAL,"Error initializing TLS context");
1068 return -1;
1071 /* 3b. Get an ed25519 link certificate. Note that we need to do this
1072 * after we set up the TLS context */
1073 if (generate_ed_link_cert(options, now, new_signing_key > 0) < 0) {
1074 log_err(LD_GENERAL,"Couldn't make link cert");
1075 return -1;
1078 /* 4. Build our router descriptor. */
1079 /* Must be called after keys are initialized. */
1080 mydesc = router_get_my_descriptor();
1081 if (authdir_mode_v3(options)) {
1082 const char *m = NULL;
1083 routerinfo_t *ri;
1084 /* We need to add our own fingerprint so it gets recognized. */
1085 if (dirserv_add_own_fingerprint(get_server_identity_key())) {
1086 log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
1087 return -1;
1089 if (mydesc) {
1090 was_router_added_t added;
1091 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
1092 if (!ri) {
1093 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
1094 return -1;
1096 added = dirserv_add_descriptor(ri, &m, "self");
1097 if (!WRA_WAS_ADDED(added)) {
1098 if (!WRA_WAS_OUTDATED(added)) {
1099 log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
1100 m?m:"<unknown error>");
1101 return -1;
1102 } else {
1103 /* If the descriptor was outdated, that's ok. This can happen
1104 * when some config options are toggled that affect workers, but
1105 * we don't really need new keys yet so the descriptor doesn't
1106 * change and the old one is still fresh. */
1107 log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
1108 "after key init: %s This is usually not a problem.",
1109 m?m:"<unknown error>");
1115 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
1116 if (router_write_fingerprint(0)) {
1117 log_err(LD_FS, "Error writing fingerprint to file");
1118 return -1;
1120 if (!public_server_mode(options) && router_write_fingerprint(1)) {
1121 log_err(LD_FS, "Error writing hashed fingerprint to file");
1122 return -1;
1125 /* Display URL to bridge status page. */
1126 if (! public_server_mode(options))
1127 router_announce_bridge_status_page();
1129 if (!authdir_mode(options))
1130 return 0;
1131 /* 6. [authdirserver only] load approved-routers file */
1132 if (dirserv_load_fingerprint_file() < 0) {
1133 log_err(LD_GENERAL,"Error loading fingerprints");
1134 return -1;
1136 /* 6b. [authdirserver only] add own key to approved directories. */
1137 crypto_pk_get_digest(get_server_identity_key(), digest);
1138 type = ((options->V3AuthoritativeDir ?
1139 (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
1140 (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
1142 ds = router_get_trusteddirserver_by_digest(digest);
1143 if (!ds) {
1144 ds = trusted_dir_server_new(options->Nickname, NULL,
1145 router_get_advertised_dir_port(options, 0),
1146 router_get_advertised_or_port(options),
1147 NULL,
1148 digest,
1149 v3_digest,
1150 type, 0.0);
1151 if (!ds) {
1152 log_err(LD_GENERAL,"We want to be a directory authority, but we "
1153 "couldn't add ourselves to the authority list. Failing.");
1154 return -1;
1156 dir_server_add(ds);
1158 if (ds->type != type) {
1159 log_warn(LD_DIR, "Configured authority type does not match authority "
1160 "type in DirAuthority list. Adjusting. (%d v %d)",
1161 type, ds->type);
1162 ds->type = type;
1164 if (v3_digest_set && (ds->type & V3_DIRINFO) &&
1165 tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
1166 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
1167 "DirAuthority line. Adjusting.");
1168 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
1171 if (cert) { /* add my own cert to the list of known certs */
1172 log_info(LD_DIR, "adding my own v3 cert");
1173 if (trusted_dirs_load_certs_from_string(
1174 cert->cache_info.signed_descriptor_body,
1175 TRUSTED_DIRS_CERTS_SRC_SELF, 0,
1176 NULL)<0) {
1177 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1178 return -1;
1182 return 0; /* success */
1185 /** The lower threshold of remaining bandwidth required to advertise (or
1186 * automatically provide) directory services */
1187 /* XXX Should this be increased? */
1188 #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
1190 /** Return true iff we have enough configured bandwidth to advertise or
1191 * automatically provide directory services from cache directory
1192 * information. */
1194 router_has_bandwidth_to_be_dirserver(const or_options_t *options)
1196 if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
1197 return 0;
1199 if (options->RelayBandwidthRate > 0 &&
1200 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
1201 return 0;
1203 return 1;
1206 /** Helper: Return 1 if we have sufficient resources for serving directory
1207 * requests, return 0 otherwise.
1208 * dir_port is either 0 or the configured DirPort number.
1209 * If AccountingMax is set less than our advertised bandwidth, then don't
1210 * serve requests. Likewise, if our advertised bandwidth is less than
1211 * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
1213 static int
1214 router_should_be_dirserver(const or_options_t *options, int dir_port)
1216 static int advertising=1; /* start out assuming we will advertise */
1217 int new_choice=1;
1218 const char *reason = NULL;
1220 if (accounting_is_enabled(options) &&
1221 get_options()->AccountingRule != ACCT_IN) {
1222 /* Don't spend bytes for directory traffic if we could end up hibernating,
1223 * but allow DirPort otherwise. Some relay operators set AccountingMax
1224 * because they're confused or to get statistics. Directory traffic has a
1225 * much larger effect on output than input so there is no reason to turn it
1226 * off if using AccountingRule in. */
1227 int interval_length = accounting_get_interval_length();
1228 uint32_t effective_bw = get_effective_bwrate(options);
1229 uint64_t acc_bytes;
1230 if (!interval_length) {
1231 log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1232 "seconds long. Raising to 1.");
1233 interval_length = 1;
1235 log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
1236 "bwrate: %u, AccountingMax: %"PRIu64", "
1237 "accounting interval length %d",
1238 dir_port ? "dirport" : "begindir",
1239 effective_bw, (options->AccountingMax),
1240 interval_length);
1242 acc_bytes = options->AccountingMax;
1243 if (get_options()->AccountingRule == ACCT_SUM)
1244 acc_bytes /= 2;
1245 if (effective_bw >=
1246 acc_bytes / interval_length) {
1247 new_choice = 0;
1248 reason = "AccountingMax enabled";
1250 } else if (! router_has_bandwidth_to_be_dirserver(options)) {
1251 /* if we're advertising a small amount */
1252 new_choice = 0;
1253 reason = "BandwidthRate under 50KB";
1256 if (advertising != new_choice) {
1257 if (new_choice == 1) {
1258 if (dir_port > 0)
1259 log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1260 else
1261 log_notice(LD_DIR, "Advertising directory service support");
1262 } else {
1263 tor_assert(reason);
1264 log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
1265 dir_port ? "Port" : "ectory Service support", reason);
1267 advertising = new_choice;
1270 return advertising;
1273 /** Look at a variety of factors, and return 0 if we don't want to
1274 * advertise the fact that we have a DirPort open or begindir support, else
1275 * return 1.
1277 * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1278 * must be 0.
1280 * Log a helpful message if we change our mind about whether to publish.
1282 static int
1283 decide_to_advertise_dir_impl(const or_options_t *options,
1284 uint16_t dir_port,
1285 int supports_tunnelled_dir_requests)
1287 /* Part one: reasons to publish or not publish that aren't
1288 * worth mentioning to the user, either because they're obvious
1289 * or because they're normal behavior. */
1291 /* short circuit the rest of the function */
1292 if (!dir_port && !supports_tunnelled_dir_requests)
1293 return 0;
1294 if (authdir_mode(options)) /* always publish */
1295 return 1;
1296 if (net_is_disabled())
1297 return 0;
1298 if (dir_port && !router_get_advertised_dir_port(options, dir_port))
1299 return 0;
1300 if (supports_tunnelled_dir_requests &&
1301 !router_get_advertised_or_port(options))
1302 return 0;
1304 /* Part two: consider config options that could make us choose to
1305 * publish or not publish that the user might find surprising. */
1306 return router_should_be_dirserver(options, dir_port);
1309 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1310 * advertise the fact that we have a DirPort open, else return the
1311 * DirPort we want to advertise.
1314 router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1316 /* supports_tunnelled_dir_requests is not relevant, pass 0 */
1317 return decide_to_advertise_dir_impl(options, dir_port, 0) ? dir_port : 0;
1320 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1321 * advertise the fact that we support begindir requests, else return 1.
1323 static int
1324 router_should_advertise_begindir(const or_options_t *options,
1325 int supports_tunnelled_dir_requests)
1327 /* dir_port is not relevant, pass 0 */
1328 return decide_to_advertise_dir_impl(options, 0,
1329 supports_tunnelled_dir_requests);
1332 /** Return true iff the combination of options in <b>options</b> and parameters
1333 * in the consensus mean that we don't want to allow exits from circuits
1334 * we got from addresses not known to be servers. */
1336 should_refuse_unknown_exits(const or_options_t *options)
1338 if (options->RefuseUnknownExits != -1) {
1339 return options->RefuseUnknownExits;
1340 } else {
1341 return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1345 /** Decide if we're a publishable server. We are a publishable server if:
1346 * - We don't have the ClientOnly option set
1347 * and
1348 * - We have the PublishServerDescriptor option set to non-empty
1349 * and
1350 * - We have ORPort set
1351 * and
1352 * - We believe our ORPort and DirPort (if present) are reachable from
1353 * the outside; or
1354 * - We believe our ORPort is reachable from the outside, and we can't
1355 * check our DirPort because the consensus has no exits; or
1356 * - We are an authoritative directory server.
1358 static int
1359 decide_if_publishable_server(void)
1361 const or_options_t *options = get_options();
1363 if (options->ClientOnly)
1364 return 0;
1365 if (options->PublishServerDescriptor_ == NO_DIRINFO)
1366 return 0;
1367 if (!server_mode(options))
1368 return 0;
1369 if (authdir_mode(options))
1370 return 1;
1371 if (!router_get_advertised_or_port(options))
1372 return 0;
1373 if (!check_whether_orport_reachable(options))
1374 return 0;
1375 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
1376 /* All set: there are no exits in the consensus (maybe this is a tiny
1377 * test network), so we can't check our DirPort reachability. */
1378 return 1;
1379 } else {
1380 return check_whether_dirport_reachable(options);
1384 /** Initiate server descriptor upload as reasonable (if server is publishable,
1385 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1387 * We need to rebuild the descriptor if it's dirty even if we're not
1388 * uploading, because our reachability testing *uses* our descriptor to
1389 * determine what IP address and ports to test.
1391 void
1392 consider_publishable_server(int force)
1394 int rebuilt;
1396 if (!server_mode(get_options()))
1397 return;
1399 rebuilt = router_rebuild_descriptor(0);
1400 if (decide_if_publishable_server()) {
1401 set_server_advertised(1);
1402 if (rebuilt == 0)
1403 router_upload_dir_desc_to_dirservers(force);
1404 } else {
1405 set_server_advertised(0);
1409 /** Return the port of the first active listener of type
1410 * <b>listener_type</b>. */
1411 /** XXX not a very good interface. it's not reliable when there are
1412 multiple listeners. */
1413 uint16_t
1414 router_get_active_listener_port_by_type_af(int listener_type,
1415 sa_family_t family)
1417 /* Iterate all connections, find one of the right kind and return
1418 the port. Not very sophisticated or fast, but effective. */
1419 smartlist_t *conns = get_connection_array();
1420 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1421 if (conn->type == listener_type && !conn->marked_for_close &&
1422 conn->socket_family == family) {
1423 return conn->port;
1425 } SMARTLIST_FOREACH_END(conn);
1427 return 0;
1430 /** Return the port that we should advertise as our ORPort; this is either
1431 * the one configured in the ORPort option, or the one we actually bound to
1432 * if ORPort is "auto".
1434 uint16_t
1435 router_get_advertised_or_port(const or_options_t *options)
1437 return router_get_advertised_or_port_by_af(options, AF_INET);
1440 /** As router_get_advertised_or_port(), but allows an address family argument.
1442 uint16_t
1443 router_get_advertised_or_port_by_af(const or_options_t *options,
1444 sa_family_t family)
1446 int port = get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER,
1447 family);
1448 (void)options;
1450 /* If the port is in 'auto' mode, we have to use
1451 router_get_listener_port_by_type(). */
1452 if (port == CFG_AUTO_PORT)
1453 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER,
1454 family);
1456 return port;
1459 /** As router_get_advertised_or_port(), but returns the IPv6 address and
1460 * port in ipv6_ap_out, which must not be NULL. Returns a null address and
1461 * zero port, if no ORPort is found. */
1462 void
1463 router_get_advertised_ipv6_or_ap(const or_options_t *options,
1464 tor_addr_port_t *ipv6_ap_out)
1466 /* Bug in calling function, we can't return a sensible result, and it
1467 * shouldn't use the NULL pointer once we return. */
1468 tor_assert(ipv6_ap_out);
1470 /* If there is no valid IPv6 ORPort, return a null address and port. */
1471 tor_addr_make_null(&ipv6_ap_out->addr, AF_INET6);
1472 ipv6_ap_out->port = 0;
1474 const tor_addr_t *addr = get_first_advertised_addr_by_type_af(
1475 CONN_TYPE_OR_LISTENER,
1476 AF_INET6);
1477 const uint16_t port = router_get_advertised_or_port_by_af(
1478 options,
1479 AF_INET6);
1481 if (!addr || port == 0) {
1482 log_info(LD_CONFIG, "There is no advertised IPv6 ORPort.");
1483 return;
1486 /* If the relay is configured using the default authorities, disallow
1487 * internal IPs. Otherwise, allow them. For IPv4 ORPorts and DirPorts,
1488 * this check is done in resolve_my_address(). See #33681. */
1489 const int default_auth = using_default_dir_authorities(options);
1490 if (tor_addr_is_internal(addr, 0) && default_auth) {
1491 log_warn(LD_CONFIG,
1492 "Unable to use configured IPv6 ORPort \"%s\" in a "
1493 "descriptor. Skipping it. "
1494 "Try specifying a globally reachable address explicitly.",
1495 fmt_addrport(addr, port));
1496 return;
1499 tor_addr_copy(&ipv6_ap_out->addr, addr);
1500 ipv6_ap_out->port = port;
1503 /** Return the port that we should advertise as our DirPort;
1504 * this is one of three possibilities:
1505 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1506 * the one configured in the DirPort option,
1507 * or the one we actually bound to if DirPort is "auto". */
1508 uint16_t
1509 router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
1511 int dirport_configured = get_primary_dir_port();
1512 (void)options;
1514 if (!dirport_configured)
1515 return dirport;
1517 if (dirport_configured == CFG_AUTO_PORT)
1518 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER,
1519 AF_INET);
1521 return dirport_configured;
1525 * OR descriptor generation.
1528 /** My routerinfo. */
1529 static routerinfo_t *desc_routerinfo = NULL;
1530 /** My extrainfo */
1531 static extrainfo_t *desc_extrainfo = NULL;
1532 /** Why did we most recently decide to regenerate our descriptor? Used to
1533 * tell the authorities why we're sending it to them. */
1534 static const char *desc_gen_reason = "uninitialized reason";
1535 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1536 * now. */
1537 static time_t desc_clean_since = 0;
1538 /** Why did we mark the descriptor dirty? */
1539 static const char *desc_dirty_reason = "Tor just started";
1540 /** Boolean: do we need to regenerate the above? */
1541 static int desc_needs_upload = 0;
1543 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1544 * descriptor successfully yet, try to upload our signed descriptor to
1545 * all the directory servers we know about.
1547 void
1548 router_upload_dir_desc_to_dirservers(int force)
1550 const routerinfo_t *ri;
1551 extrainfo_t *ei;
1552 char *msg;
1553 size_t desc_len, extra_len = 0, total_len;
1554 dirinfo_type_t auth = get_options()->PublishServerDescriptor_;
1556 ri = router_get_my_routerinfo();
1557 if (!ri) {
1558 log_info(LD_GENERAL, "No descriptor; skipping upload");
1559 return;
1561 ei = router_get_my_extrainfo();
1562 if (auth == NO_DIRINFO)
1563 return;
1564 if (!force && !desc_needs_upload)
1565 return;
1567 log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1568 force ? " (forced)" : "");
1570 desc_needs_upload = 0;
1572 desc_len = ri->cache_info.signed_descriptor_len;
1573 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1574 total_len = desc_len + extra_len + 1;
1575 msg = tor_malloc(total_len);
1576 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1577 if (ei) {
1578 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1580 msg[desc_len+extra_len] = 0;
1582 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1583 (auth & BRIDGE_DIRINFO) ?
1584 ROUTER_PURPOSE_BRIDGE :
1585 ROUTER_PURPOSE_GENERAL,
1586 auth, msg, desc_len, extra_len);
1587 tor_free(msg);
1590 /** OR only: Check whether my exit policy says to allow connection to
1591 * conn. Return 0 if we accept; non-0 if we reject.
1594 router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
1596 const routerinfo_t *me = router_get_my_routerinfo();
1597 if (!me) /* make sure routerinfo exists */
1598 return -1;
1600 /* make sure it's resolved to something. this way we can't get a
1601 'maybe' below. */
1602 if (tor_addr_is_null(addr))
1603 return -1;
1605 /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
1606 * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
1607 * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
1608 * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
1609 * summary. */
1610 if ((tor_addr_family(addr) == AF_INET ||
1611 tor_addr_family(addr) == AF_INET6)) {
1612 return compare_tor_addr_to_addr_policy(addr, port,
1613 me->exit_policy) != ADDR_POLICY_ACCEPTED;
1614 #if 0
1615 } else if (tor_addr_family(addr) == AF_INET6) {
1616 return get_options()->IPv6Exit &&
1617 desc_routerinfo->ipv6_exit_policy &&
1618 compare_tor_addr_to_short_policy(addr, port,
1619 me->ipv6_exit_policy) != ADDR_POLICY_ACCEPTED;
1620 #endif /* 0 */
1621 } else {
1622 return -1;
1626 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1627 * have a descriptor */
1628 MOCK_IMPL(int,
1629 router_my_exit_policy_is_reject_star,(void))
1631 const routerinfo_t *me = router_get_my_routerinfo();
1632 if (!me) /* make sure routerinfo exists */
1633 return -1;
1635 return me->policy_is_reject_star;
1638 /** Return true iff I'm a server and <b>digest</b> is equal to
1639 * my server identity key digest. */
1641 router_digest_is_me(const char *digest)
1643 return (server_identitykey &&
1644 tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
1647 /** Return my identity digest. */
1648 const uint8_t *
1649 router_get_my_id_digest(void)
1651 return (const uint8_t *)server_identitykey_digest;
1654 /** Return true iff I'm a server and <b>digest</b> is equal to
1655 * my identity digest. */
1657 router_extrainfo_digest_is_me(const char *digest)
1659 extrainfo_t *ei = router_get_my_extrainfo();
1660 if (!ei)
1661 return 0;
1663 return tor_memeq(digest,
1664 ei->cache_info.signed_descriptor_digest,
1665 DIGEST_LEN);
1668 /** A wrapper around router_digest_is_me(). */
1670 router_is_me(const routerinfo_t *router)
1672 return router_digest_is_me(router->cache_info.identity_digest);
1675 /** Return a routerinfo for this OR, rebuilding a fresh one if
1676 * necessary. Return NULL on error, or if called on an OP. */
1677 MOCK_IMPL(const routerinfo_t *,
1678 router_get_my_routerinfo,(void))
1680 return router_get_my_routerinfo_with_err(NULL);
1683 /** Return routerinfo of this OR. Rebuild it from
1684 * scratch if needed. Set <b>*err</b> to 0 on success or to
1685 * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
1687 MOCK_IMPL(const routerinfo_t *,
1688 router_get_my_routerinfo_with_err,(int *err))
1690 if (!server_mode(get_options())) {
1691 if (err)
1692 *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
1694 return NULL;
1697 if (!desc_clean_since) {
1698 int rebuild_err = router_rebuild_descriptor(0);
1699 if (rebuild_err < 0) {
1700 if (err)
1701 *err = rebuild_err;
1703 return NULL;
1707 if (!desc_routerinfo) {
1708 if (err)
1709 *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
1711 return NULL;
1714 if (err)
1715 *err = 0;
1717 return desc_routerinfo;
1720 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1721 * one if necessary. Return NULL on error.
1723 const char *
1724 router_get_my_descriptor(void)
1726 const char *body;
1727 const routerinfo_t *me = router_get_my_routerinfo();
1728 if (! me)
1729 return NULL;
1730 tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
1731 body = signed_descriptor_get_body(&me->cache_info);
1732 /* Make sure this is nul-terminated. */
1733 tor_assert(!body[me->cache_info.signed_descriptor_len]);
1734 log_debug(LD_GENERAL,"my desc is '%s'", body);
1735 return body;
1738 /** Return the extrainfo document for this OR, or NULL if we have none.
1739 * Rebuilt it (and the server descriptor) if necessary. */
1740 extrainfo_t *
1741 router_get_my_extrainfo(void)
1743 if (!server_mode(get_options()))
1744 return NULL;
1745 if (router_rebuild_descriptor(0))
1746 return NULL;
1747 return desc_extrainfo;
1750 /** Return a human-readable string describing what triggered us to generate
1751 * our current descriptor, or NULL if we don't know. */
1752 const char *
1753 router_get_descriptor_gen_reason(void)
1755 return desc_gen_reason;
1758 /** A list of nicknames that we've warned about including in our family
1759 * declaration verbatim rather than as digests. */
1760 static smartlist_t *warned_nonexistent_family = NULL;
1762 static int router_guess_address_from_dir_headers(uint32_t *guess);
1764 /** Make a current best guess at our address, either because
1765 * it's configured in torrc, or because we've learned it from
1766 * dirserver headers. Place the answer in *<b>addr</b> and return
1767 * 0 on success, else return -1 if we have no guess.
1769 * If <b>cache_only</b> is true, just return any cached answers, and
1770 * don't try to get any new answers.
1772 MOCK_IMPL(int,
1773 router_pick_published_address,(const or_options_t *options, uint32_t *addr,
1774 int cache_only))
1776 /* First, check the cached output from resolve_my_address(). */
1777 *addr = get_last_resolved_addr();
1778 if (*addr)
1779 return 0;
1781 /* Second, consider doing a resolve attempt right here. */
1782 if (!cache_only) {
1783 if (resolve_my_address(LOG_INFO, options, addr, NULL, NULL) >= 0) {
1784 log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
1785 return 0;
1789 /* Third, check the cached output from router_new_address_suggestion(). */
1790 if (router_guess_address_from_dir_headers(addr) >= 0)
1791 return 0;
1793 /* We have no useful cached answers. Return failure. */
1794 return -1;
1797 /* Like router_check_descriptor_address_consistency, but specifically for the
1798 * ORPort or DirPort.
1799 * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
1800 static void
1801 router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr,
1802 int listener_type)
1804 tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
1805 listener_type == CONN_TYPE_DIR_LISTENER);
1807 /* The first advertised Port may be the magic constant CFG_AUTO_PORT.
1809 int port_v4_cfg = get_first_advertised_port_by_type_af(listener_type,
1810 AF_INET);
1811 if (port_v4_cfg != 0 &&
1812 !port_exists_by_type_addr32h_port(listener_type,
1813 ipv4h_desc_addr, port_v4_cfg, 1)) {
1814 const tor_addr_t *port_addr = get_first_advertised_addr_by_type_af(
1815 listener_type,
1816 AF_INET);
1817 /* If we're building a descriptor with no advertised address,
1818 * something is terribly wrong. */
1819 tor_assert(port_addr);
1821 tor_addr_t desc_addr;
1822 char port_addr_str[TOR_ADDR_BUF_LEN];
1823 char desc_addr_str[TOR_ADDR_BUF_LEN];
1825 tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
1827 tor_addr_from_ipv4h(&desc_addr, ipv4h_desc_addr);
1828 tor_addr_to_str(desc_addr_str, &desc_addr, TOR_ADDR_BUF_LEN, 0);
1830 const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
1831 "OR" : "Dir");
1832 log_warn(LD_CONFIG, "The IPv4 %sPort address %s does not match the "
1833 "descriptor address %s. If you have a static public IPv4 "
1834 "address, use 'Address <IPv4>' and 'OutboundBindAddress "
1835 "<IPv4>'. If you are behind a NAT, use two %sPort lines: "
1836 "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
1837 "NoAdvertise'.",
1838 listener_str, port_addr_str, desc_addr_str, listener_str,
1839 listener_str, listener_str);
1843 /* Tor relays only have one IPv4 address in the descriptor, which is derived
1844 * from the Address torrc option, or guessed using various methods in
1845 * router_pick_published_address().
1846 * Warn the operator if there is no ORPort on the descriptor address
1847 * ipv4h_desc_addr.
1848 * Warn the operator if there is no DirPort on the descriptor address.
1849 * This catches a few common config errors:
1850 * - operators who expect ORPorts and DirPorts to be advertised on the
1851 * ports' listen addresses, rather than the torrc Address (or guessed
1852 * addresses in the absence of an Address config). This includes
1853 * operators who attempt to put their ORPort and DirPort on different
1854 * addresses;
1855 * - discrepancies between guessed addresses and configured listen
1856 * addresses (when the Address option isn't set).
1857 * If a listener is listening on all IPv4 addresses, it is assumed that it
1858 * is listening on the configured Address, and no messages are logged.
1859 * If an operators has specified NoAdvertise ORPorts in a NAT setting,
1860 * no messages are logged, unless they have specified other advertised
1861 * addresses.
1862 * The message tells operators to configure an ORPort and DirPort that match
1863 * the Address (using NoListen if needed).
1865 static void
1866 router_check_descriptor_address_consistency(uint32_t ipv4h_desc_addr)
1868 router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1869 CONN_TYPE_OR_LISTENER);
1870 router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1871 CONN_TYPE_DIR_LISTENER);
1874 /** Build a fresh routerinfo, signed server descriptor, and extra-info document
1875 * for this OR. Set r to the generated routerinfo, e to the generated
1876 * extra-info document. Return 0 on success, -1 on temporary error. Failure to
1877 * generate an extra-info document is not an error and is indicated by setting
1878 * e to NULL. Caller is responsible for freeing generated documents if 0 is
1879 * returned.
1882 router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
1884 routerinfo_t *ri;
1885 extrainfo_t *ei;
1886 uint32_t addr;
1887 char platform[256];
1888 int hibernating = we_are_hibernating();
1889 const or_options_t *options = get_options();
1891 if (router_pick_published_address(options, &addr, 0) < 0) {
1892 log_warn(LD_CONFIG, "Don't know my address while generating descriptor");
1893 return TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
1896 /* Log a message if the address in the descriptor doesn't match the ORPort
1897 * and DirPort addresses configured by the operator. */
1898 router_check_descriptor_address_consistency(addr);
1900 ri = tor_malloc_zero(sizeof(routerinfo_t));
1901 ri->cache_info.routerlist_index = -1;
1902 ri->nickname = tor_strdup(options->Nickname);
1903 ri->addr = addr;
1904 ri->or_port = router_get_advertised_or_port(options);
1905 ri->dir_port = router_get_advertised_dir_port(options, 0);
1906 ri->supports_tunnelled_dir_requests =
1907 directory_permits_begindir_requests(options);
1908 ri->cache_info.published_on = time(NULL);
1909 /* get_onion_key() must invoke from main thread */
1910 router_set_rsa_onion_pkey(get_onion_key(), &ri->onion_pkey,
1911 &ri->onion_pkey_len);
1913 ri->onion_curve25519_pkey =
1914 tor_memdup(&get_current_curve25519_keypair()->pubkey,
1915 sizeof(curve25519_public_key_t));
1917 /* For now, at most one IPv6 or-address is being advertised. */
1918 tor_addr_port_t ipv6_orport;
1919 router_get_advertised_ipv6_or_ap(options, &ipv6_orport);
1920 /* If there is no valud IPv6 ORPort, the address and port are null. */
1921 tor_addr_copy(&ri->ipv6_addr, &ipv6_orport.addr);
1922 ri->ipv6_orport = ipv6_orport.port;
1924 ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
1925 if (BUG(crypto_pk_get_digest(ri->identity_pkey,
1926 ri->cache_info.identity_digest) < 0)) {
1927 routerinfo_free(ri);
1928 return TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
1930 ri->cache_info.signing_key_cert =
1931 tor_cert_dup(get_master_signing_key_cert());
1933 get_platform_str(platform, sizeof(platform));
1934 ri->platform = tor_strdup(platform);
1936 ri->protocol_list = tor_strdup(protover_get_supported_protocols());
1938 /* compute ri->bandwidthrate as the min of various options */
1939 ri->bandwidthrate = get_effective_bwrate(options);
1941 /* and compute ri->bandwidthburst similarly */
1942 ri->bandwidthburst = get_effective_bwburst(options);
1944 /* Report bandwidth, unless we're hibernating or shutting down */
1945 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1947 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1948 /* DNS is screwed up; don't claim to be an exit. */
1949 policies_exit_policy_append_reject_star(&ri->exit_policy);
1950 } else {
1951 policies_parse_exit_policy_from_options(options,ri->addr,&ri->ipv6_addr,
1952 &ri->exit_policy);
1954 ri->policy_is_reject_star =
1955 policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
1956 policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
1958 if (options->IPv6Exit) {
1959 char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
1960 if (p_tmp)
1961 ri->ipv6_exit_policy = parse_short_policy(p_tmp);
1962 tor_free(p_tmp);
1965 if (options->MyFamily && ! options->BridgeRelay) {
1966 if (!warned_nonexistent_family)
1967 warned_nonexistent_family = smartlist_new();
1968 ri->declared_family = smartlist_new();
1969 config_line_t *family;
1970 for (family = options->MyFamily; family; family = family->next) {
1971 char *name = family->value;
1972 const node_t *member;
1973 if (!strcasecmp(name, options->Nickname))
1974 continue; /* Don't list ourself, that's redundant */
1975 else
1976 member = node_get_by_nickname(name, 0);
1977 if (!member) {
1978 int is_legal = is_legal_nickname_or_hexdigest(name);
1979 if (!smartlist_contains_string(warned_nonexistent_family, name) &&
1980 !is_legal_hexdigest(name)) {
1981 if (is_legal)
1982 log_warn(LD_CONFIG,
1983 "I have no descriptor for the router named \"%s\" in my "
1984 "declared family; I'll use the nickname as is, but "
1985 "this may confuse clients.", name);
1986 else
1987 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1988 "declared family, but that isn't a legal nickname. "
1989 "Skipping it.", escaped(name));
1990 smartlist_add_strdup(warned_nonexistent_family, name);
1992 if (is_legal) {
1993 smartlist_add_strdup(ri->declared_family, name);
1995 } else if (router_digest_is_me(member->identity)) {
1996 /* Don't list ourself in our own family; that's redundant */
1997 /* XXX shouldn't be possible */
1998 } else {
1999 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
2000 fp[0] = '$';
2001 base16_encode(fp+1,HEX_DIGEST_LEN+1,
2002 member->identity, DIGEST_LEN);
2003 smartlist_add(ri->declared_family, fp);
2004 if (smartlist_contains_string(warned_nonexistent_family, name))
2005 smartlist_string_remove(warned_nonexistent_family, name);
2009 /* remove duplicates from the list */
2010 smartlist_sort_strings(ri->declared_family);
2011 smartlist_uniq_strings(ri->declared_family);
2014 /* Now generate the extrainfo. */
2015 ei = tor_malloc_zero(sizeof(extrainfo_t));
2016 ei->cache_info.is_extrainfo = 1;
2017 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
2018 ei->cache_info.published_on = ri->cache_info.published_on;
2019 ei->cache_info.signing_key_cert =
2020 tor_cert_dup(get_master_signing_key_cert());
2022 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
2023 DIGEST_LEN);
2024 if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
2025 ei, get_server_identity_key(),
2026 get_master_signing_keypair()) < 0) {
2027 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
2028 extrainfo_free(ei);
2029 ei = NULL;
2030 } else {
2031 ei->cache_info.signed_descriptor_len =
2032 strlen(ei->cache_info.signed_descriptor_body);
2033 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
2034 ei->cache_info.signed_descriptor_len,
2035 ei->cache_info.signed_descriptor_digest);
2036 crypto_digest256((char*) ei->digest256,
2037 ei->cache_info.signed_descriptor_body,
2038 ei->cache_info.signed_descriptor_len,
2039 DIGEST_SHA256);
2042 /* Now finish the router descriptor. */
2043 if (ei) {
2044 memcpy(ri->cache_info.extra_info_digest,
2045 ei->cache_info.signed_descriptor_digest,
2046 DIGEST_LEN);
2047 memcpy(ri->cache_info.extra_info_digest256,
2048 ei->digest256,
2049 DIGEST256_LEN);
2050 } else {
2051 /* ri was allocated with tor_malloc_zero, so there is no need to
2052 * zero ri->cache_info.extra_info_digest here. */
2054 if (! (ri->cache_info.signed_descriptor_body =
2055 router_dump_router_to_string(ri, get_server_identity_key(),
2056 get_onion_key(),
2057 get_current_curve25519_keypair(),
2058 get_master_signing_keypair())) ) {
2059 log_warn(LD_BUG, "Couldn't generate router descriptor.");
2060 routerinfo_free(ri);
2061 extrainfo_free(ei);
2062 return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
2064 ri->cache_info.signed_descriptor_len =
2065 strlen(ri->cache_info.signed_descriptor_body);
2067 ri->purpose =
2068 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
2069 if (options->BridgeRelay) {
2070 /* Bridges shouldn't be able to send their descriptors unencrypted,
2071 anyway, since they don't have a DirPort, and always connect to the
2072 bridge authority anonymously. But just in case they somehow think of
2073 sending them on an unencrypted connection, don't allow them to try. */
2074 ri->cache_info.send_unencrypted = 0;
2075 if (ei)
2076 ei->cache_info.send_unencrypted = 0;
2077 } else {
2078 ri->cache_info.send_unencrypted = 1;
2079 if (ei)
2080 ei->cache_info.send_unencrypted = 1;
2083 router_get_router_hash(ri->cache_info.signed_descriptor_body,
2084 strlen(ri->cache_info.signed_descriptor_body),
2085 ri->cache_info.signed_descriptor_digest);
2087 if (ei) {
2088 tor_assert(!
2089 routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
2090 &ri->cache_info, NULL));
2093 *r = ri;
2094 *e = ei;
2095 return 0;
2098 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2099 * routerinfo, signed server descriptor, and extra-info document for this OR.
2100 * Return 0 on success, -1 on temporary error.
2103 router_rebuild_descriptor(int force)
2105 int err = 0;
2106 routerinfo_t *ri;
2107 extrainfo_t *ei;
2108 uint32_t addr;
2109 const or_options_t *options = get_options();
2111 if (desc_clean_since && !force)
2112 return 0;
2114 if (router_pick_published_address(options, &addr, 0) < 0 ||
2115 router_get_advertised_or_port(options) == 0) {
2116 /* Stop trying to rebuild our descriptor every second. We'll
2117 * learn that it's time to try again when ip_address_changed()
2118 * marks it dirty. */
2119 desc_clean_since = time(NULL);
2120 return TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
2123 log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
2125 err = router_build_fresh_descriptor(&ri, &ei);
2126 if (err < 0) {
2127 return err;
2130 routerinfo_free(desc_routerinfo);
2131 desc_routerinfo = ri;
2132 extrainfo_free(desc_extrainfo);
2133 desc_extrainfo = ei;
2135 desc_clean_since = time(NULL);
2136 desc_needs_upload = 1;
2137 desc_gen_reason = desc_dirty_reason;
2138 if (BUG(desc_gen_reason == NULL)) {
2139 desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
2141 desc_dirty_reason = NULL;
2142 control_event_my_descriptor_changed();
2143 return 0;
2146 /** If our router descriptor ever goes this long without being regenerated
2147 * because something changed, we force an immediate regenerate-and-upload. */
2148 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2150 /** If our router descriptor seems to be missing or unacceptable according
2151 * to the authorities, regenerate and reupload it _this_ often. */
2152 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2154 /** Mark descriptor out of date if it's been "too long" since we last tried
2155 * to upload one. */
2156 void
2157 mark_my_descriptor_dirty_if_too_old(time_t now)
2159 networkstatus_t *ns;
2160 const routerstatus_t *rs;
2161 const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2162 const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2163 const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2165 /* If it's already dirty, don't mark it. */
2166 if (! desc_clean_since)
2167 return;
2169 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2170 * time to rebuild it. */
2171 if (desc_clean_since < slow_cutoff) {
2172 mark_my_descriptor_dirty("time for new descriptor");
2173 return;
2175 /* Now we see whether we want to be retrying frequently or no. The
2176 * rule here is that we'll retry frequently if we aren't listed in the
2177 * live consensus we have, or if the publication time of the
2178 * descriptor listed for us in the consensus is very old. */
2179 ns = networkstatus_get_live_consensus(now);
2180 if (ns) {
2181 rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
2182 if (rs == NULL)
2183 retry_fast_reason = "not listed in consensus";
2184 else if (rs->published_on < slow_cutoff)
2185 retry_fast_reason = "version listed in consensus is quite old";
2188 if (retry_fast_reason && desc_clean_since < fast_cutoff)
2189 mark_my_descriptor_dirty(retry_fast_reason);
2192 /** Call when the current descriptor is out of date. */
2193 void
2194 mark_my_descriptor_dirty(const char *reason)
2196 const or_options_t *options = get_options();
2197 if (BUG(reason == NULL)) {
2198 reason = "marked descriptor dirty for unspecified reason";
2200 if (server_mode(options) && options->PublishServerDescriptor_)
2201 log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2202 desc_clean_since = 0;
2203 if (!desc_dirty_reason)
2204 desc_dirty_reason = reason;
2207 /** How frequently will we republish our descriptor because of large (factor
2208 * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2209 * if our previous bandwidth estimate was exactly 0. */
2210 #define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
2212 /** Maximum uptime to republish our descriptor because of large shifts in
2213 * estimated bandwidth. */
2214 #define MAX_UPTIME_BANDWIDTH_CHANGE (24*60*60)
2216 /** By which factor bandwidth shifts have to change to be considered large. */
2217 #define BANDWIDTH_CHANGE_FACTOR 2
2219 /** Check whether bandwidth has changed a lot since the last time we announced
2220 * bandwidth while the uptime is smaller than MAX_UPTIME_BANDWIDTH_CHANGE.
2221 * If so, mark our descriptor dirty. */
2222 void
2223 check_descriptor_bandwidth_changed(time_t now)
2225 static time_t last_changed = 0;
2226 uint64_t prev, cur;
2227 const int hibernating = we_are_hibernating();
2229 /* If the relay uptime is bigger than MAX_UPTIME_BANDWIDTH_CHANGE,
2230 * the next regularly scheduled descriptor update (18h) will be enough */
2231 if (get_uptime() > MAX_UPTIME_BANDWIDTH_CHANGE && !hibernating)
2232 return;
2234 const routerinfo_t *my_ri = router_get_my_routerinfo();
2236 if (!my_ri)
2237 return;
2239 prev = my_ri->bandwidthcapacity;
2241 /* Consider ourselves to have zero bandwidth if we're hibernating or
2242 * shutting down. */
2243 cur = hibernating ? 0 : rep_hist_bandwidth_assess();
2245 if ((prev != cur && (!prev || !cur)) ||
2246 cur > (prev * BANDWIDTH_CHANGE_FACTOR) ||
2247 cur < (prev / BANDWIDTH_CHANGE_FACTOR) ) {
2248 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
2249 log_info(LD_GENERAL,
2250 "Measured bandwidth has changed; rebuilding descriptor.");
2251 mark_my_descriptor_dirty("bandwidth has changed");
2252 last_changed = now;
2257 /** Note at log level severity that our best guess of address has changed from
2258 * <b>prev</b> to <b>cur</b>. */
2259 static void
2260 log_addr_has_changed(int severity,
2261 const tor_addr_t *prev,
2262 const tor_addr_t *cur,
2263 const char *source)
2265 char addrbuf_prev[TOR_ADDR_BUF_LEN];
2266 char addrbuf_cur[TOR_ADDR_BUF_LEN];
2268 if (BUG(!server_mode(get_options())))
2269 return;
2271 if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2272 strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2273 if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2274 strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2276 if (!tor_addr_is_null(prev))
2277 log_fn(severity, LD_GENERAL,
2278 "Our IP Address has changed from %s to %s; "
2279 "rebuilding descriptor (source: %s).",
2280 addrbuf_prev, addrbuf_cur, source);
2281 else
2282 log_notice(LD_GENERAL,
2283 "Guessed our IP address as %s (source: %s).",
2284 addrbuf_cur, source);
2287 /** Check whether our own address as defined by the Address configuration
2288 * has changed. This is for routers that get their address from a service
2289 * like dyndns. If our address has changed, mark our descriptor dirty. */
2290 void
2291 check_descriptor_ipaddress_changed(time_t now)
2293 uint32_t prev, cur;
2294 const or_options_t *options = get_options();
2295 const char *method = NULL;
2296 char *hostname = NULL;
2297 const routerinfo_t *my_ri = router_get_my_routerinfo();
2299 (void) now;
2301 if (my_ri == NULL) /* make sure routerinfo exists */
2302 return;
2304 /* XXXX ipv6 */
2305 prev = my_ri->addr;
2306 if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
2307 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
2308 return;
2311 if (prev != cur) {
2312 char *source;
2313 tor_addr_t tmp_prev, tmp_cur;
2315 tor_addr_from_ipv4h(&tmp_prev, prev);
2316 tor_addr_from_ipv4h(&tmp_cur, cur);
2318 tor_asprintf(&source, "METHOD=%s%s%s", method,
2319 hostname ? " HOSTNAME=" : "",
2320 hostname ? hostname : "");
2322 log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
2323 tor_free(source);
2325 ip_address_changed(0);
2328 tor_free(hostname);
2331 /** The most recently guessed value of our IP address, based on directory
2332 * headers. */
2333 static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
2335 /** A directory server <b>d_conn</b> told us our IP address is
2336 * <b>suggestion</b>.
2337 * If this address is different from the one we think we are now, and
2338 * if our computer doesn't actually know its IP address, then switch. */
2339 void
2340 router_new_address_suggestion(const char *suggestion,
2341 const dir_connection_t *d_conn)
2343 tor_addr_t addr;
2344 uint32_t cur = 0; /* Current IPv4 address. */
2345 const or_options_t *options = get_options();
2347 /* first, learn what the IP address actually is */
2348 if (tor_addr_parse(&addr, suggestion) == -1) {
2349 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
2350 escaped(suggestion));
2351 return;
2354 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
2356 if (!server_mode(options)) {
2357 tor_addr_copy(&last_guessed_ip, &addr);
2358 return;
2361 /* XXXX ipv6 */
2362 cur = get_last_resolved_addr();
2363 if (cur ||
2364 resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
2365 /* We're all set -- we already know our address. Great. */
2366 tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
2367 need it later */
2368 return;
2370 if (tor_addr_is_internal(&addr, 0)) {
2371 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2372 return;
2374 if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
2375 /* Don't believe anybody who says our IP is their IP. */
2376 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
2377 "but they are just reporting their own IP address. Ignoring.",
2378 suggestion);
2379 return;
2382 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2383 * us an answer different from what we had the last time we managed to
2384 * resolve it. */
2385 if (!tor_addr_eq(&last_guessed_ip, &addr)) {
2386 control_event_server_status(LOG_NOTICE,
2387 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2388 suggestion);
2389 log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
2390 d_conn->base_.address);
2391 ip_address_changed(0);
2392 tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
2393 will fetch it */
2397 /** We failed to resolve our address locally, but we'd like to build
2398 * a descriptor and publish / test reachability. If we have a guess
2399 * about our address based on directory headers, answer it and return
2400 * 0; else return -1. */
2401 static int
2402 router_guess_address_from_dir_headers(uint32_t *guess)
2404 if (!tor_addr_is_null(&last_guessed_ip)) {
2405 *guess = tor_addr_to_ipv4h(&last_guessed_ip);
2406 return 0;
2408 return -1;
2411 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2412 * string describing the version of Tor and the operating system we're
2413 * currently running on.
2415 STATIC void
2416 get_platform_str(char *platform, size_t len)
2418 tor_snprintf(platform, len, "Tor %s on %s",
2419 get_short_version(), get_uname());
2422 /* XXX need to audit this thing and count fenceposts. maybe
2423 * refactor so we don't have to keep asking if we're
2424 * near the end of maxlen?
2426 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2428 /** OR only: Given a routerinfo for this router, and an identity key to sign
2429 * with, encode the routerinfo as a signed server descriptor and return a new
2430 * string encoding the result, or NULL on failure.
2432 char *
2433 router_dump_router_to_string(routerinfo_t *router,
2434 const crypto_pk_t *ident_key,
2435 const crypto_pk_t *tap_key,
2436 const curve25519_keypair_t *ntor_keypair,
2437 const ed25519_keypair_t *signing_keypair)
2439 char *address = NULL;
2440 char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2441 crypto_pk_t *rsa_pubkey = NULL;
2442 char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2443 char digest[DIGEST256_LEN];
2444 char published[ISO_TIME_LEN+1];
2445 char fingerprint[FINGERPRINT_LEN+1];
2446 char *extra_info_line = NULL;
2447 size_t onion_pkeylen, identity_pkeylen;
2448 char *family_line = NULL;
2449 char *extra_or_address = NULL;
2450 const or_options_t *options = get_options();
2451 smartlist_t *chunks = NULL;
2452 char *output = NULL;
2453 const int emit_ed_sigs = signing_keypair &&
2454 router->cache_info.signing_key_cert;
2455 char *ed_cert_line = NULL;
2456 char *rsa_tap_cc_line = NULL;
2457 char *ntor_cc_line = NULL;
2458 char *proto_line = NULL;
2460 /* Make sure the identity key matches the one in the routerinfo. */
2461 if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2462 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2463 "match router's public key!");
2464 goto err;
2466 if (emit_ed_sigs) {
2467 if (!router->cache_info.signing_key_cert->signing_key_included ||
2468 !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
2469 &signing_keypair->pubkey)) {
2470 log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
2471 "ed25519 key chain %d",
2472 router->cache_info.signing_key_cert->signing_key_included);
2473 goto err;
2477 /* record our fingerprint, so we can include it in the descriptor */
2478 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2479 log_err(LD_BUG,"Error computing fingerprint");
2480 goto err;
2483 if (emit_ed_sigs) {
2484 /* Encode ed25519 signing cert */
2485 char ed_cert_base64[256];
2486 char ed_fp_base64[ED25519_BASE64_LEN+1];
2487 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2488 (const char*)router->cache_info.signing_key_cert->encoded,
2489 router->cache_info.signing_key_cert->encoded_len,
2490 BASE64_ENCODE_MULTILINE) < 0) {
2491 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2492 goto err;
2494 if (ed25519_public_to_base64(ed_fp_base64,
2495 &router->cache_info.signing_key_cert->signing_key)<0) {
2496 log_err(LD_BUG,"Couldn't base64-encode identity key\n");
2497 goto err;
2499 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2500 "-----BEGIN ED25519 CERT-----\n"
2501 "%s"
2502 "-----END ED25519 CERT-----\n"
2503 "master-key-ed25519 %s\n",
2504 ed_cert_base64, ed_fp_base64);
2507 /* PEM-encode the onion key */
2508 rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
2509 router->onion_pkey_len);
2510 if (crypto_pk_write_public_key_to_string(rsa_pubkey,
2511 &onion_pkey,&onion_pkeylen)<0) {
2512 log_warn(LD_BUG,"write onion_pkey to string failed!");
2513 goto err;
2516 /* PEM-encode the identity key */
2517 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
2518 &identity_pkey,&identity_pkeylen)<0) {
2519 log_warn(LD_BUG,"write identity_pkey to string failed!");
2520 goto err;
2523 /* Cross-certify with RSA key */
2524 if (tap_key && router->cache_info.signing_key_cert &&
2525 router->cache_info.signing_key_cert->signing_key_included) {
2526 char buf[256];
2527 int tap_cc_len = 0;
2528 uint8_t *tap_cc =
2529 make_tap_onion_key_crosscert(tap_key,
2530 &router->cache_info.signing_key_cert->signing_key,
2531 router->identity_pkey,
2532 &tap_cc_len);
2533 if (!tap_cc) {
2534 log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
2535 goto err;
2538 if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
2539 BASE64_ENCODE_MULTILINE) < 0) {
2540 log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
2541 tor_free(tap_cc);
2542 goto err;
2544 tor_free(tap_cc);
2546 tor_asprintf(&rsa_tap_cc_line,
2547 "onion-key-crosscert\n"
2548 "-----BEGIN CROSSCERT-----\n"
2549 "%s"
2550 "-----END CROSSCERT-----\n", buf);
2553 /* Cross-certify with onion keys */
2554 if (ntor_keypair && router->cache_info.signing_key_cert &&
2555 router->cache_info.signing_key_cert->signing_key_included) {
2556 int sign = 0;
2557 char buf[256];
2558 /* XXXX Base the expiration date on the actual onion key expiration time?*/
2559 tor_cert_t *cert =
2560 make_ntor_onion_key_crosscert(ntor_keypair,
2561 &router->cache_info.signing_key_cert->signing_key,
2562 router->cache_info.published_on,
2563 get_onion_key_lifetime(), &sign);
2564 if (!cert) {
2565 log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
2566 goto err;
2568 tor_assert(sign == 0 || sign == 1);
2570 if (base64_encode(buf, sizeof(buf),
2571 (const char*)cert->encoded, cert->encoded_len,
2572 BASE64_ENCODE_MULTILINE)<0) {
2573 log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
2574 tor_cert_free(cert);
2575 goto err;
2577 tor_cert_free(cert);
2579 tor_asprintf(&ntor_cc_line,
2580 "ntor-onion-key-crosscert %d\n"
2581 "-----BEGIN ED25519 CERT-----\n"
2582 "%s"
2583 "-----END ED25519 CERT-----\n", sign, buf);
2586 /* Encode the publication time. */
2587 format_iso_time(published, router->cache_info.published_on);
2589 if (router->declared_family && smartlist_len(router->declared_family)) {
2590 char *family = smartlist_join_strings(router->declared_family,
2591 " ", 0, NULL);
2592 tor_asprintf(&family_line, "family %s\n", family);
2593 tor_free(family);
2594 } else {
2595 family_line = tor_strdup("");
2598 if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
2599 char extra_info_digest[HEX_DIGEST_LEN+1];
2600 base16_encode(extra_info_digest, sizeof(extra_info_digest),
2601 router->cache_info.extra_info_digest, DIGEST_LEN);
2602 if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
2603 char d256_64[BASE64_DIGEST256_LEN+1];
2604 digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
2605 tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
2606 extra_info_digest, d256_64);
2607 } else {
2608 tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
2609 extra_info_digest);
2613 if (router->ipv6_orport &&
2614 tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2615 char addr[TOR_ADDR_BUF_LEN];
2616 const char *a;
2617 a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2618 if (a) {
2619 tor_asprintf(&extra_or_address,
2620 "or-address %s:%d\n", a, router->ipv6_orport);
2621 log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2625 if (router->protocol_list) {
2626 tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
2627 } else {
2628 proto_line = tor_strdup("");
2631 address = tor_dup_ip(router->addr);
2632 chunks = smartlist_new();
2634 /* Generate the easy portion of the router descriptor. */
2635 smartlist_add_asprintf(chunks,
2636 "router %s %s %d 0 %d\n"
2637 "%s"
2638 "%s"
2639 "platform %s\n"
2640 "%s"
2641 "published %s\n"
2642 "fingerprint %s\n"
2643 "uptime %ld\n"
2644 "bandwidth %d %d %d\n"
2645 "%s%s"
2646 "onion-key\n%s"
2647 "signing-key\n%s"
2648 "%s%s"
2649 "%s%s%s",
2650 router->nickname,
2651 address,
2652 router->or_port,
2653 router_should_advertise_dirport(options, router->dir_port),
2654 ed_cert_line ? ed_cert_line : "",
2655 extra_or_address ? extra_or_address : "",
2656 router->platform,
2657 proto_line,
2658 published,
2659 fingerprint,
2660 get_uptime(),
2661 (int) router->bandwidthrate,
2662 (int) router->bandwidthburst,
2663 (int) router->bandwidthcapacity,
2664 extra_info_line ? extra_info_line : "",
2665 (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
2666 "caches-extra-info\n" : "",
2667 onion_pkey, identity_pkey,
2668 rsa_tap_cc_line ? rsa_tap_cc_line : "",
2669 ntor_cc_line ? ntor_cc_line : "",
2670 family_line,
2671 we_are_hibernating() ? "hibernating 1\n" : "",
2672 "hidden-service-dir\n");
2674 if (options->ContactInfo && strlen(options->ContactInfo)) {
2675 const char *ci = options->ContactInfo;
2676 if (strchr(ci, '\n') || strchr(ci, '\r'))
2677 ci = escaped(ci);
2678 smartlist_add_asprintf(chunks, "contact %s\n", ci);
2681 if (options->BridgeRelay) {
2682 char *bd = NULL;
2684 if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
2685 bd = tor_strdup(options->BridgeDistribution);
2686 } else {
2687 bd = tor_strdup("any");
2690 // Make sure our value is lowercased in the descriptor instead of just
2691 // forwarding what the user wrote in their torrc directly.
2692 tor_strlower(bd);
2694 smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
2695 tor_free(bd);
2698 if (router->onion_curve25519_pkey) {
2699 char kbuf[128];
2700 base64_encode(kbuf, sizeof(kbuf),
2701 (const char *)router->onion_curve25519_pkey->public_key,
2702 CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
2703 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
2704 } else {
2705 /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
2706 log_err(LD_BUG, "A relay must have an ntor onion key");
2707 goto err;
2710 /* Write the exit policy to the end of 's'. */
2711 if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
2712 smartlist_add_strdup(chunks, "reject *:*\n");
2713 } else if (router->exit_policy) {
2714 char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
2716 if (!exit_policy)
2717 goto err;
2719 smartlist_add_asprintf(chunks, "%s\n", exit_policy);
2720 tor_free(exit_policy);
2723 if (router->ipv6_exit_policy) {
2724 char *p6 = write_short_policy(router->ipv6_exit_policy);
2725 if (p6 && strcmp(p6, "reject 1-65535")) {
2726 smartlist_add_asprintf(chunks,
2727 "ipv6-policy %s\n", p6);
2729 tor_free(p6);
2732 if (router_should_advertise_begindir(options,
2733 router->supports_tunnelled_dir_requests)) {
2734 smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
2737 /* Sign the descriptor with Ed25519 */
2738 if (emit_ed_sigs) {
2739 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
2740 crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
2741 ED_DESC_SIGNATURE_PREFIX,
2742 chunks, "", DIGEST_SHA256);
2743 ed25519_signature_t sig;
2744 char buf[ED25519_SIG_BASE64_LEN+1];
2745 if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
2746 signing_keypair) < 0)
2747 goto err;
2748 if (ed25519_signature_to_base64(buf, &sig) < 0)
2749 goto err;
2751 smartlist_add_asprintf(chunks, "%s\n", buf);
2754 /* Sign the descriptor with RSA */
2755 smartlist_add_strdup(chunks, "router-signature\n");
2757 crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
2760 char *sig;
2761 if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
2762 log_warn(LD_BUG, "Couldn't sign router descriptor");
2763 goto err;
2765 smartlist_add(chunks, sig);
2768 /* include a last '\n' */
2769 smartlist_add_strdup(chunks, "\n");
2771 output = smartlist_join_strings(chunks, "", 0, NULL);
2773 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2775 char *s_dup;
2776 const char *cp;
2777 routerinfo_t *ri_tmp;
2778 cp = s_dup = tor_strdup(output);
2779 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
2780 if (!ri_tmp) {
2781 log_err(LD_BUG,
2782 "We just generated a router descriptor we can't parse.");
2783 log_err(LD_BUG, "Descriptor was: <<%s>>", output);
2784 goto err;
2786 tor_free(s_dup);
2787 routerinfo_free(ri_tmp);
2789 #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
2791 goto done;
2793 err:
2794 tor_free(output); /* sets output to NULL */
2795 done:
2796 if (chunks) {
2797 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2798 smartlist_free(chunks);
2800 crypto_pk_free(rsa_pubkey);
2801 tor_free(address);
2802 tor_free(family_line);
2803 tor_free(onion_pkey);
2804 tor_free(identity_pkey);
2805 tor_free(extra_or_address);
2806 tor_free(ed_cert_line);
2807 tor_free(rsa_tap_cc_line);
2808 tor_free(ntor_cc_line);
2809 tor_free(extra_info_line);
2810 tor_free(proto_line);
2812 return output;
2816 * OR only: Given <b>router</b>, produce a string with its exit policy.
2817 * If <b>include_ipv4</b> is true, include IPv4 entries.
2818 * If <b>include_ipv6</b> is true, include IPv6 entries.
2820 char *
2821 router_dump_exit_policy_to_string(const routerinfo_t *router,
2822 int include_ipv4,
2823 int include_ipv6)
2825 if ((!router->exit_policy) || (router->policy_is_reject_star)) {
2826 return tor_strdup("reject *:*");
2829 return policy_dump_to_string(router->exit_policy,
2830 include_ipv4,
2831 include_ipv6);
2834 /** Load the contents of <b>filename</b>, find the last line starting with
2835 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2836 * the past or more than 1 hour in the future with respect to <b>now</b>,
2837 * and write the file contents starting with that line to *<b>out</b>.
2838 * Return 1 for success, 0 if the file does not exist or is empty, or -1
2839 * if the file does not contain a line matching these criteria or other
2840 * failure. */
2841 static int
2842 load_stats_file(const char *filename, const char *end_line, time_t now,
2843 char **out)
2845 int r = -1;
2846 char *fname = get_datadir_fname(filename);
2847 char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
2848 time_t written;
2849 switch (file_status(fname)) {
2850 case FN_FILE:
2851 /* X022 Find an alternative to reading the whole file to memory. */
2852 if ((contents = read_file_to_str(fname, 0, NULL))) {
2853 tmp = strstr(contents, end_line);
2854 /* Find last block starting with end_line */
2855 while (tmp) {
2856 start = tmp;
2857 tmp = strstr(tmp + 1, end_line);
2859 if (!start)
2860 goto notfound;
2861 if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
2862 goto notfound;
2863 strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
2864 if (parse_iso_time(timestr, &written) < 0)
2865 goto notfound;
2866 if (written < now - (25*60*60) || written > now + (1*60*60))
2867 goto notfound;
2868 *out = tor_strdup(start);
2869 r = 1;
2871 notfound:
2872 tor_free(contents);
2873 break;
2874 /* treat empty stats files as if the file doesn't exist */
2875 case FN_NOENT:
2876 case FN_EMPTY:
2877 r = 0;
2878 break;
2879 case FN_ERROR:
2880 case FN_DIR:
2881 default:
2882 break;
2884 tor_free(fname);
2885 return r;
2888 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2889 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2890 * success, negative on failure. */
2892 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
2893 crypto_pk_t *ident_key,
2894 const ed25519_keypair_t *signing_keypair)
2896 const or_options_t *options = get_options();
2897 char identity[HEX_DIGEST_LEN+1];
2898 char published[ISO_TIME_LEN+1];
2899 char digest[DIGEST_LEN];
2900 char *bandwidth_usage;
2901 int result;
2902 static int write_stats_to_extrainfo = 1;
2903 char sig[DIROBJ_MAX_SIG_LEN+1];
2904 char *s = NULL, *pre, *contents, *cp, *s_dup = NULL;
2905 time_t now = time(NULL);
2906 smartlist_t *chunks = smartlist_new();
2907 extrainfo_t *ei_tmp = NULL;
2908 const int emit_ed_sigs = signing_keypair &&
2909 extrainfo->cache_info.signing_key_cert;
2910 char *ed_cert_line = NULL;
2912 base16_encode(identity, sizeof(identity),
2913 extrainfo->cache_info.identity_digest, DIGEST_LEN);
2914 format_iso_time(published, extrainfo->cache_info.published_on);
2915 bandwidth_usage = rep_hist_get_bandwidth_lines();
2916 if (emit_ed_sigs) {
2917 if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
2918 !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
2919 &signing_keypair->pubkey)) {
2920 log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
2921 "mismatched ed25519 key chain %d",
2922 extrainfo->cache_info.signing_key_cert->signing_key_included);
2923 goto err;
2925 char ed_cert_base64[256];
2926 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2927 (const char*)extrainfo->cache_info.signing_key_cert->encoded,
2928 extrainfo->cache_info.signing_key_cert->encoded_len,
2929 BASE64_ENCODE_MULTILINE) < 0) {
2930 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2931 goto err;
2933 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2934 "-----BEGIN ED25519 CERT-----\n"
2935 "%s"
2936 "-----END ED25519 CERT-----\n", ed_cert_base64);
2937 } else {
2938 ed_cert_line = tor_strdup("");
2941 tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n%s",
2942 extrainfo->nickname, identity,
2943 ed_cert_line,
2944 published, bandwidth_usage);
2945 smartlist_add(chunks, pre);
2947 if (geoip_is_loaded(AF_INET))
2948 smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
2949 geoip_db_digest(AF_INET));
2950 if (geoip_is_loaded(AF_INET6))
2951 smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
2952 geoip_db_digest(AF_INET6));
2954 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
2955 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
2956 if (options->DirReqStatistics &&
2957 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
2958 "dirreq-stats-end", now, &contents) > 0) {
2959 smartlist_add(chunks, contents);
2961 if (options->HiddenServiceStatistics &&
2962 load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
2963 "hidserv-stats-end", now, &contents) > 0) {
2964 smartlist_add(chunks, contents);
2966 if (options->EntryStatistics &&
2967 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
2968 "entry-stats-end", now, &contents) > 0) {
2969 smartlist_add(chunks, contents);
2971 if (options->CellStatistics &&
2972 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
2973 "cell-stats-end", now, &contents) > 0) {
2974 smartlist_add(chunks, contents);
2976 if (options->ExitPortStatistics &&
2977 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
2978 "exit-stats-end", now, &contents) > 0) {
2979 smartlist_add(chunks, contents);
2981 if (options->ConnDirectionStatistics &&
2982 load_stats_file("stats"PATH_SEPARATOR"conn-stats",
2983 "conn-bi-direct", now, &contents) > 0) {
2984 smartlist_add(chunks, contents);
2986 if (options->PaddingStatistics) {
2987 contents = rep_hist_get_padding_count_lines();
2988 if (contents)
2989 smartlist_add(chunks, contents);
2993 /* Add information about the pluggable transports we support. */
2994 if (options->ServerTransportPlugin) {
2995 char *pluggable_transports = pt_get_extra_info_descriptor_string();
2996 if (pluggable_transports)
2997 smartlist_add(chunks, pluggable_transports);
3000 if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
3001 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
3002 if (bridge_stats) {
3003 smartlist_add_strdup(chunks, bridge_stats);
3007 if (emit_ed_sigs) {
3008 char sha256_digest[DIGEST256_LEN];
3009 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
3010 crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
3011 ED_DESC_SIGNATURE_PREFIX,
3012 chunks, "", DIGEST_SHA256);
3013 ed25519_signature_t ed_sig;
3014 char buf[ED25519_SIG_BASE64_LEN+1];
3015 if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
3016 signing_keypair) < 0)
3017 goto err;
3018 if (ed25519_signature_to_base64(buf, &ed_sig) < 0)
3019 goto err;
3021 smartlist_add_asprintf(chunks, "%s\n", buf);
3024 smartlist_add_strdup(chunks, "router-signature\n");
3025 s = smartlist_join_strings(chunks, "", 0, NULL);
3027 while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
3028 /* So long as there are at least two chunks (one for the initial
3029 * extra-info line and one for the router-signature), we can keep removing
3030 * things. */
3031 if (smartlist_len(chunks) > 2) {
3032 /* We remove the next-to-last element (remember, len-1 is the last
3033 element), since we need to keep the router-signature element. */
3034 int idx = smartlist_len(chunks) - 2;
3035 char *e = smartlist_get(chunks, idx);
3036 smartlist_del_keeporder(chunks, idx);
3037 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3038 "with statistics that exceeds the 50 KB "
3039 "upload limit. Removing last added "
3040 "statistics.");
3041 tor_free(e);
3042 tor_free(s);
3043 s = smartlist_join_strings(chunks, "", 0, NULL);
3044 } else {
3045 log_warn(LD_BUG, "We just generated an extra-info descriptors that "
3046 "exceeds the 50 KB upload limit.");
3047 goto err;
3051 memset(sig, 0, sizeof(sig));
3052 if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
3053 router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
3054 ident_key) < 0) {
3055 log_warn(LD_BUG, "Could not append signature to extra-info "
3056 "descriptor.");
3057 goto err;
3059 smartlist_add_strdup(chunks, sig);
3060 tor_free(s);
3061 s = smartlist_join_strings(chunks, "", 0, NULL);
3063 cp = s_dup = tor_strdup(s);
3064 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
3065 if (!ei_tmp) {
3066 if (write_stats_to_extrainfo) {
3067 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3068 "with statistics that we can't parse. Not "
3069 "adding statistics to this or any future "
3070 "extra-info descriptors.");
3071 write_stats_to_extrainfo = 0;
3072 result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
3073 signing_keypair);
3074 goto done;
3075 } else {
3076 log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
3077 "can't parse.");
3078 goto err;
3082 *s_out = s;
3083 s = NULL; /* prevent free */
3084 result = 0;
3085 goto done;
3087 err:
3088 result = -1;
3090 done:
3091 tor_free(s);
3092 SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
3093 smartlist_free(chunks);
3094 tor_free(s_dup);
3095 tor_free(ed_cert_line);
3096 extrainfo_free(ei_tmp);
3097 tor_free(bandwidth_usage);
3099 return result;
3102 /** Forget that we have issued any router-related warnings, so that we'll
3103 * warn again if we see the same errors. */
3104 void
3105 router_reset_warnings(void)
3107 if (warned_nonexistent_family) {
3108 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3109 smartlist_clear(warned_nonexistent_family);
3113 /** Release all static resources held in router.c */
3114 void
3115 router_free_all(void)
3117 crypto_pk_free(onionkey);
3118 crypto_pk_free(lastonionkey);
3119 crypto_pk_free(server_identitykey);
3120 crypto_pk_free(client_identitykey);
3122 tor_mutex_free(key_lock);
3123 routerinfo_free(desc_routerinfo);
3124 extrainfo_free(desc_extrainfo);
3125 crypto_pk_free(authority_signing_key);
3126 authority_cert_free(authority_key_certificate);
3127 crypto_pk_free(legacy_signing_key);
3128 authority_cert_free(legacy_key_certificate);
3130 memwipe(&curve25519_onion_key, 0, sizeof(curve25519_onion_key));
3131 memwipe(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
3133 if (warned_nonexistent_family) {
3134 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3135 smartlist_free(warned_nonexistent_family);
3138 /* From the given RSA key object, convert it to ASN-1 encoded format and set
3139 * the newly allocated object in onion_pkey_out. The length of the key is set
3140 * in onion_pkey_len_out. */
3141 void
3142 router_set_rsa_onion_pkey(const crypto_pk_t *pk, char **onion_pkey_out,
3143 size_t *onion_pkey_len_out)
3145 int len;
3146 char buf[1024];
3148 tor_assert(pk);
3149 tor_assert(onion_pkey_out);
3150 tor_assert(onion_pkey_len_out);
3152 len = crypto_pk_asn1_encode(pk, buf, sizeof(buf));
3153 if (BUG(len < 0)) {
3154 goto done;
3157 *onion_pkey_out = tor_memdup(buf, len);
3158 *onion_pkey_len_out = len;
3160 done:
3161 return;
3164 /* From an ASN-1 encoded onion pkey, return a newly allocated RSA key object.
3165 * It is the caller responsability to free the returned object.
3167 * Return NULL if the pkey is NULL, malformed or if the length is 0. */
3168 crypto_pk_t *
3169 router_get_rsa_onion_pkey(const char *pkey, size_t pkey_len)
3171 if (!pkey || pkey_len == 0) {
3172 return NULL;
3174 return crypto_pk_asn1_decode(pkey, pkey_len);