Remove extra includes from router.c
[tor.git] / src / feature / relay / router.c
blob8629ad95619b2bc11112f3caa9ba87804f8b7b6f
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-2018, 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/hibernate/hibernate.h"
25 #include "feature/keymgt/loadkey.h"
26 #include "feature/nodelist/authcert.h"
27 #include "feature/nodelist/dirlist.h"
28 #include "feature/nodelist/networkstatus.h"
29 #include "feature/nodelist/nickname.h"
30 #include "feature/nodelist/nodelist.h"
31 #include "feature/nodelist/routerlist.h"
32 #include "feature/nodelist/routerparse.h"
33 #include "feature/nodelist/torcert.h"
34 #include "feature/relay/dns.h"
35 #include "feature/relay/router.h"
36 #include "feature/relay/routerkeys.h"
37 #include "feature/relay/routermode.h"
38 #include "feature/relay/selftest.h"
39 #include "feature/stats/geoip.h"
40 #include "feature/stats/rephist.h"
41 #include "lib/crypt_ops/crypto_ed25519.h"
42 #include "lib/crypt_ops/crypto_format.h"
43 #include "lib/crypt_ops/crypto_init.h"
44 #include "lib/crypt_ops/crypto_rand.h"
45 #include "lib/crypt_ops/crypto_util.h"
46 #include "lib/encoding/confline.h"
47 #include "lib/osinfo/uname.h"
48 #include "lib/tls/tortls.h"
50 #include "feature/dirauth/authmode.h"
52 #include "app/config/or_state_st.h"
53 #include "core/or/port_cfg_st.h"
54 #include "feature/dirclient/dir_server_st.h"
55 #include "feature/dircommon/dir_connection_st.h"
56 #include "feature/nodelist/authority_cert_st.h"
57 #include "feature/nodelist/extrainfo_st.h"
58 #include "feature/nodelist/node_st.h"
59 #include "feature/nodelist/routerinfo_st.h"
60 #include "feature/nodelist/routerstatus_st.h"
62 /**
63 * \file router.c
64 * \brief Miscellaneous relay functionality, including RSA key maintenance,
65 * generating and uploading server descriptors, picking an address to
66 * advertise, and so on.
68 * This module handles the job of deciding whether we are a Tor relay, and if
69 * so what kind. (Mostly through functions like server_mode() that inspect an
70 * or_options_t, but in some cases based on our own capabilities, such as when
71 * we are deciding whether to be a directory cache in
72 * router_has_bandwidth_to_be_dirserver().)
74 * Also in this module are the functions to generate our own routerinfo_t and
75 * extrainfo_t, and to encode those to signed strings for upload to the
76 * directory authorities.
78 * This module also handles key maintenance for RSA and Curve25519-ntor keys,
79 * and for our TLS context. (These functions should eventually move to
80 * routerkeys.c along with the code that handles Ed25519 keys now.)
81 **/
83 /************************************************************/
85 /*****
86 * Key management: ORs only.
87 *****/
89 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
91 static tor_mutex_t *key_lock=NULL;
92 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
93 /** Current private onionskin decryption key: used to decode CREATE cells. */
94 static crypto_pk_t *onionkey=NULL;
95 /** Previous private onionskin decryption key: used to decode CREATE cells
96 * generated by clients that have an older version of our descriptor. */
97 static crypto_pk_t *lastonionkey=NULL;
98 /** Current private ntor secret key: used to perform the ntor handshake. */
99 static curve25519_keypair_t curve25519_onion_key;
100 /** Previous private ntor secret key: used to perform the ntor handshake
101 * with clients that have an older version of our descriptor. */
102 static curve25519_keypair_t last_curve25519_onion_key;
103 /** Private server "identity key": used to sign directory info and TLS
104 * certificates. Never changes. */
105 static crypto_pk_t *server_identitykey=NULL;
106 /** Digest of server_identitykey. */
107 static char server_identitykey_digest[DIGEST_LEN];
108 /** Private client "identity key": used to sign bridges' and clients'
109 * outbound TLS certificates. Regenerated on startup and on IP address
110 * change. */
111 static crypto_pk_t *client_identitykey=NULL;
112 /** Signing key used for v3 directory material; only set for authorities. */
113 static crypto_pk_t *authority_signing_key = NULL;
114 /** Key certificate to authenticate v3 directory material; only set for
115 * authorities. */
116 static authority_cert_t *authority_key_certificate = NULL;
118 /** For emergency V3 authority key migration: An extra signing key that we use
119 * with our old (obsolete) identity key for a while. */
120 static crypto_pk_t *legacy_signing_key = NULL;
121 /** For emergency V3 authority key migration: An extra certificate to
122 * authenticate legacy_signing_key with our obsolete identity key.*/
123 static authority_cert_t *legacy_key_certificate = NULL;
125 /* (Note that v3 authorities also have a separate "authority identity key",
126 * but this key is never actually loaded by the Tor process. Instead, it's
127 * used by tor-gencert to sign new signing keys and make new key
128 * certificates. */
130 /** Return a readonly string with human readable description
131 * of <b>err</b>.
133 const char *
134 routerinfo_err_to_string(int err)
136 switch (err) {
137 case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
138 return "No known exit address yet";
139 case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
140 return "Cannot parse descriptor";
141 case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
142 return "Not running in server mode";
143 case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
144 return "Key digest failed";
145 case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
146 return "Cannot generate descriptor";
147 case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
148 return "Descriptor still rebuilding - not ready yet";
151 log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
152 tor_assert_unreached();
154 return "Unknown error";
157 /** Return true if we expect given error to be transient.
158 * Return false otherwise.
161 routerinfo_err_is_transient(int err)
164 * For simplicity, we consider all errors other than
165 * "not a server" transient - see discussion on
166 * https://trac.torproject.org/projects/tor/ticket/27034
168 return err != TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
171 /** Replace the current onion key with <b>k</b>. Does not affect
172 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
174 static void
175 set_onion_key(crypto_pk_t *k)
177 if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
178 /* k is already our onion key; free it and return */
179 crypto_pk_free(k);
180 return;
182 tor_mutex_acquire(key_lock);
183 crypto_pk_free(onionkey);
184 onionkey = k;
185 tor_mutex_release(key_lock);
186 mark_my_descriptor_dirty("set onion key");
189 /** Return the current onion key. Requires that the onion key has been
190 * loaded or generated. */
191 crypto_pk_t *
192 get_onion_key(void)
194 tor_assert(onionkey);
195 return onionkey;
198 /** Store a full copy of the current onion key into *<b>key</b>, and a full
199 * copy of the most recent onion key into *<b>last</b>. Store NULL into
200 * a pointer if the corresponding key does not exist.
202 void
203 dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
205 tor_assert(key);
206 tor_assert(last);
207 tor_mutex_acquire(key_lock);
208 if (onionkey)
209 *key = crypto_pk_copy_full(onionkey);
210 else
211 *key = NULL;
212 if (lastonionkey)
213 *last = crypto_pk_copy_full(lastonionkey);
214 else
215 *last = NULL;
216 tor_mutex_release(key_lock);
219 /** Expire our old set of onion keys. This is done by setting
220 * last_curve25519_onion_key and lastonionkey to all zero's and NULL
221 * respectively.
223 * This function does not perform any grace period checks for the old onion
224 * keys.
226 void
227 expire_old_onion_keys(void)
229 char *fname = NULL;
231 tor_mutex_acquire(key_lock);
233 /* Free lastonionkey and set it to NULL. */
234 if (lastonionkey) {
235 crypto_pk_free(lastonionkey);
236 lastonionkey = NULL;
239 /* We zero out the keypair. See the tor_mem_is_zero() check made in
240 * construct_ntor_key_map() below. */
241 memset(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
243 tor_mutex_release(key_lock);
245 fname = get_keydir_fname("secret_onion_key.old");
246 if (file_status(fname) == FN_FILE) {
247 if (tor_unlink(fname) != 0) {
248 log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
249 fname, strerror(errno));
252 tor_free(fname);
254 fname = get_keydir_fname("secret_onion_key_ntor.old");
255 if (file_status(fname) == FN_FILE) {
256 if (tor_unlink(fname) != 0) {
257 log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
258 fname, strerror(errno));
261 tor_free(fname);
264 /** Return the current secret onion key for the ntor handshake. Must only
265 * be called from the main thread. */
266 static const curve25519_keypair_t *
267 get_current_curve25519_keypair(void)
269 return &curve25519_onion_key;
271 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
272 * handshake. Must only be called from the main thread. */
273 di_digest256_map_t *
274 construct_ntor_key_map(void)
276 di_digest256_map_t *m = NULL;
278 if (!tor_mem_is_zero((const char*)
279 curve25519_onion_key.pubkey.public_key,
280 CURVE25519_PUBKEY_LEN)) {
281 dimap_add_entry(&m,
282 curve25519_onion_key.pubkey.public_key,
283 tor_memdup(&curve25519_onion_key,
284 sizeof(curve25519_keypair_t)));
286 if (!tor_mem_is_zero((const char*)
287 last_curve25519_onion_key.pubkey.public_key,
288 CURVE25519_PUBKEY_LEN)) {
289 dimap_add_entry(&m,
290 last_curve25519_onion_key.pubkey.public_key,
291 tor_memdup(&last_curve25519_onion_key,
292 sizeof(curve25519_keypair_t)));
295 return m;
297 /** Helper used to deallocate a di_digest256_map_t returned by
298 * construct_ntor_key_map. */
299 static void
300 ntor_key_map_free_helper(void *arg)
302 curve25519_keypair_t *k = arg;
303 memwipe(k, 0, sizeof(*k));
304 tor_free(k);
306 /** Release all storage from a keymap returned by construct_ntor_key_map. */
307 void
308 ntor_key_map_free_(di_digest256_map_t *map)
310 if (!map)
311 return;
312 dimap_free(map, ntor_key_map_free_helper);
315 /** Return the time when the onion key was last set. This is either the time
316 * when the process launched, or the time of the most recent key rotation since
317 * the process launched.
319 time_t
320 get_onion_key_set_at(void)
322 return onionkey_set_at;
325 /** Set the current server identity key to <b>k</b>.
327 void
328 set_server_identity_key(crypto_pk_t *k)
330 crypto_pk_free(server_identitykey);
331 server_identitykey = k;
332 if (crypto_pk_get_digest(server_identitykey,
333 server_identitykey_digest) < 0) {
334 log_err(LD_BUG, "Couldn't compute our own identity key digest.");
335 tor_assert(0);
339 /** Make sure that we have set up our identity keys to match or not match as
340 * appropriate, and die with an assertion if we have not. */
341 static void
342 assert_identity_keys_ok(void)
344 if (1)
345 return;
346 tor_assert(client_identitykey);
347 if (public_server_mode(get_options())) {
348 /* assert that we have set the client and server keys to be equal */
349 tor_assert(server_identitykey);
350 tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
351 } else {
352 /* assert that we have set the client and server keys to be unequal */
353 if (server_identitykey)
354 tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
358 /** Returns the current server identity key; requires that the key has
359 * been set, and that we are running as a Tor server.
361 crypto_pk_t *
362 get_server_identity_key(void)
364 tor_assert(server_identitykey);
365 tor_assert(server_mode(get_options()));
366 assert_identity_keys_ok();
367 return server_identitykey;
370 /** Return true iff we are a server and the server identity key
371 * has been set. */
373 server_identity_key_is_set(void)
375 return server_mode(get_options()) && server_identitykey != NULL;
378 /** Set the current client identity key to <b>k</b>.
380 void
381 set_client_identity_key(crypto_pk_t *k)
383 crypto_pk_free(client_identitykey);
384 client_identitykey = k;
387 /** Returns the current client identity key for use on outgoing TLS
388 * connections; requires that the key has been set.
390 crypto_pk_t *
391 get_tlsclient_identity_key(void)
393 tor_assert(client_identitykey);
394 assert_identity_keys_ok();
395 return client_identitykey;
398 /** Return true iff the client identity key has been set. */
400 client_identity_key_is_set(void)
402 return client_identitykey != NULL;
405 /** Return the key certificate for this v3 (voting) authority, or NULL
406 * if we have no such certificate. */
407 MOCK_IMPL(authority_cert_t *,
408 get_my_v3_authority_cert, (void))
410 return authority_key_certificate;
413 /** Return the v3 signing key for this v3 (voting) authority, or NULL
414 * if we have no such key. */
415 crypto_pk_t *
416 get_my_v3_authority_signing_key(void)
418 return authority_signing_key;
421 /** If we're an authority, and we're using a legacy authority identity key for
422 * emergency migration purposes, return the certificate associated with that
423 * key. */
424 authority_cert_t *
425 get_my_v3_legacy_cert(void)
427 return legacy_key_certificate;
430 /** If we're an authority, and we're using a legacy authority identity key for
431 * emergency migration purposes, return that key. */
432 crypto_pk_t *
433 get_my_v3_legacy_signing_key(void)
435 return legacy_signing_key;
438 /** Replace the previous onion key with the current onion key, and generate
439 * a new previous onion key. Immediately after calling this function,
440 * the OR should:
441 * - schedule all previous cpuworkers to shut down _after_ processing
442 * pending work. (This will cause fresh cpuworkers to be generated.)
443 * - generate and upload a fresh routerinfo.
445 void
446 rotate_onion_key(void)
448 char *fname, *fname_prev;
449 crypto_pk_t *prkey = NULL;
450 or_state_t *state = get_or_state();
451 curve25519_keypair_t new_curve25519_keypair;
452 time_t now;
453 fname = get_keydir_fname("secret_onion_key");
454 fname_prev = get_keydir_fname("secret_onion_key.old");
455 /* There isn't much point replacing an old key with an empty file */
456 if (file_status(fname) == FN_FILE) {
457 if (replace_file(fname, fname_prev))
458 goto error;
460 if (!(prkey = crypto_pk_new())) {
461 log_err(LD_GENERAL,"Error constructing rotated onion key");
462 goto error;
464 if (crypto_pk_generate_key(prkey)) {
465 log_err(LD_BUG,"Error generating onion key");
466 goto error;
468 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
469 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
470 goto error;
472 tor_free(fname);
473 tor_free(fname_prev);
474 fname = get_keydir_fname("secret_onion_key_ntor");
475 fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
476 if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
477 goto error;
478 /* There isn't much point replacing an old key with an empty file */
479 if (file_status(fname) == FN_FILE) {
480 if (replace_file(fname, fname_prev))
481 goto error;
483 if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
484 "onion") < 0) {
485 log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
486 goto error;
488 log_info(LD_GENERAL, "Rotating onion key");
489 tor_mutex_acquire(key_lock);
490 crypto_pk_free(lastonionkey);
491 lastonionkey = onionkey;
492 onionkey = prkey;
493 memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
494 sizeof(curve25519_keypair_t));
495 memcpy(&curve25519_onion_key, &new_curve25519_keypair,
496 sizeof(curve25519_keypair_t));
497 now = time(NULL);
498 state->LastRotatedOnionKey = onionkey_set_at = now;
499 tor_mutex_release(key_lock);
500 mark_my_descriptor_dirty("rotated onion key");
501 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
502 goto done;
503 error:
504 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
505 if (prkey)
506 crypto_pk_free(prkey);
507 done:
508 memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
509 tor_free(fname);
510 tor_free(fname_prev);
513 /** Log greeting message that points to new relay lifecycle document the
514 * first time this function has been called.
516 static void
517 log_new_relay_greeting(void)
519 static int already_logged = 0;
521 if (already_logged)
522 return;
524 tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
525 "Thanks for helping the Tor network! If you wish to know "
526 "what will happen in the upcoming weeks regarding its usage, "
527 "have a look at https://blog.torproject.org/blog/lifecycle-of"
528 "-a-new-relay");
530 already_logged = 1;
533 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
534 * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
535 * is true, create a new keypair and write it into the file. If there are
536 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
537 * in their ASCII wrapper. */
538 static int
539 init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
540 const char *fname,
541 int generate,
542 int severity,
543 const char *tag)
545 switch (file_status(fname)) {
546 case FN_DIR:
547 case FN_ERROR:
548 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
549 goto error;
550 /* treat empty key files as if the file doesn't exist, and, if generate
551 * is set, replace the empty file in curve25519_keypair_write_to_file() */
552 case FN_NOENT:
553 case FN_EMPTY:
554 if (generate) {
555 if (!have_lockfile()) {
556 if (try_locking(get_options(), 0)<0) {
557 /* Make sure that --list-fingerprint only creates new keys
558 * if there is no possibility for a deadlock. */
559 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
560 "Not writing any new keys.", fname);
561 /*XXXX The 'other process' might make a key in a second or two;
562 * maybe we should wait for it. */
563 goto error;
566 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
567 fname);
568 if (curve25519_keypair_generate(keys_out, 1) < 0)
569 goto error;
570 if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
571 tor_log(severity, LD_FS,
572 "Couldn't write generated key to \"%s\".", fname);
573 memwipe(keys_out, 0, sizeof(*keys_out));
574 goto error;
576 } else {
577 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
579 return 0;
580 case FN_FILE:
582 char *tag_in=NULL;
583 if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
584 tor_log(severity, LD_GENERAL,"Error loading private key.");
585 tor_free(tag_in);
586 goto error;
588 if (!tag_in || strcmp(tag_in, tag)) {
589 tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
590 escaped(tag_in));
591 tor_free(tag_in);
592 goto error;
594 tor_free(tag_in);
595 return 0;
597 default:
598 tor_assert(0);
601 error:
602 return -1;
605 /** Try to load the vote-signing private key and certificate for being a v3
606 * directory authority, and make sure they match. If <b>legacy</b>, load a
607 * legacy key/cert set for emergency key migration; otherwise load the regular
608 * key/cert set. On success, store them into *<b>key_out</b> and
609 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
610 static int
611 load_authority_keyset(int legacy, crypto_pk_t **key_out,
612 authority_cert_t **cert_out)
614 int r = -1;
615 char *fname = NULL, *cert = NULL;
616 const char *eos = NULL;
617 crypto_pk_t *signing_key = NULL;
618 authority_cert_t *parsed = NULL;
620 fname = get_keydir_fname(
621 legacy ? "legacy_signing_key" : "authority_signing_key");
622 signing_key = init_key_from_file(fname, 0, LOG_ERR, NULL);
623 if (!signing_key) {
624 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
625 goto done;
627 tor_free(fname);
628 fname = get_keydir_fname(
629 legacy ? "legacy_certificate" : "authority_certificate");
630 cert = read_file_to_str(fname, 0, NULL);
631 if (!cert) {
632 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
633 fname);
634 goto done;
636 parsed = authority_cert_parse_from_string(cert, &eos);
637 if (!parsed) {
638 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
639 goto done;
641 if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
642 log_warn(LD_DIR, "Stored signing key does not match signing key in "
643 "certificate");
644 goto done;
647 crypto_pk_free(*key_out);
648 authority_cert_free(*cert_out);
650 *key_out = signing_key;
651 *cert_out = parsed;
652 r = 0;
653 signing_key = NULL;
654 parsed = NULL;
656 done:
657 tor_free(fname);
658 tor_free(cert);
659 crypto_pk_free(signing_key);
660 authority_cert_free(parsed);
661 return r;
664 /** Load the v3 (voting) authority signing key and certificate, if they are
665 * present. Return -1 if anything is missing, mismatched, or unloadable;
666 * return 0 on success. */
667 static int
668 init_v3_authority_keys(void)
670 if (load_authority_keyset(0, &authority_signing_key,
671 &authority_key_certificate)<0)
672 return -1;
674 if (get_options()->V3AuthUseLegacyKey &&
675 load_authority_keyset(1, &legacy_signing_key,
676 &legacy_key_certificate)<0)
677 return -1;
679 return 0;
682 /** If we're a v3 authority, check whether we have a certificate that's
683 * likely to expire soon. Warn if we do, but not too often. */
684 void
685 v3_authority_check_key_expiry(void)
687 time_t now, expires;
688 static time_t last_warned = 0;
689 int badness, time_left, warn_interval;
690 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
691 return;
693 now = time(NULL);
694 expires = authority_key_certificate->expires;
695 time_left = (int)( expires - now );
696 if (time_left <= 0) {
697 badness = LOG_ERR;
698 warn_interval = 60*60;
699 } else if (time_left <= 24*60*60) {
700 badness = LOG_WARN;
701 warn_interval = 60*60;
702 } else if (time_left <= 24*60*60*7) {
703 badness = LOG_WARN;
704 warn_interval = 24*60*60;
705 } else if (time_left <= 24*60*60*30) {
706 badness = LOG_WARN;
707 warn_interval = 24*60*60*5;
708 } else {
709 return;
712 if (last_warned + warn_interval > now)
713 return;
715 if (time_left <= 0) {
716 tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
717 " Generate a new one NOW.");
718 } else if (time_left <= 24*60*60) {
719 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
720 "hours; Generate a new one NOW.", time_left/(60*60));
721 } else {
722 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
723 "days; Generate a new one soon.", time_left/(24*60*60));
725 last_warned = now;
728 /** Get the lifetime of an onion key in days. This value is defined by the
729 * network consesus parameter "onion-key-rotation-days". Always returns a value
730 * between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
731 * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
733 static int
734 get_onion_key_rotation_days_(void)
736 return networkstatus_get_param(NULL,
737 "onion-key-rotation-days",
738 DEFAULT_ONION_KEY_LIFETIME_DAYS,
739 MIN_ONION_KEY_LIFETIME_DAYS,
740 MAX_ONION_KEY_LIFETIME_DAYS);
743 /** Get the current lifetime of an onion key in seconds. This value is defined
744 * by the network consesus parameter "onion-key-rotation-days", but the value
745 * is converted to seconds.
748 get_onion_key_lifetime(void)
750 return get_onion_key_rotation_days_()*24*60*60;
753 /** Get the grace period of an onion key in seconds. This value is defined by
754 * the network consesus parameter "onion-key-grace-period-days", but the value
755 * is converted to seconds.
758 get_onion_key_grace_period(void)
760 int grace_period;
761 grace_period = networkstatus_get_param(NULL,
762 "onion-key-grace-period-days",
763 DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS,
764 MIN_ONION_KEY_GRACE_PERIOD_DAYS,
765 get_onion_key_rotation_days_());
766 return grace_period*24*60*60;
769 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
770 * on success, and -1 on failure. */
772 router_initialize_tls_context(void)
774 unsigned int flags = 0;
775 const or_options_t *options = get_options();
776 int lifetime = options->SSLKeyLifetime;
777 if (public_server_mode(options))
778 flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
779 if (!lifetime) { /* we should guess a good ssl cert lifetime */
781 /* choose between 5 and 365 days, and round to the day */
782 unsigned int five_days = 5*24*3600;
783 unsigned int one_year = 365*24*3600;
784 lifetime = crypto_rand_int_range(five_days, one_year);
785 lifetime -= lifetime % (24*3600);
787 if (crypto_rand_int(2)) {
788 /* Half the time we expire at midnight, and half the time we expire
789 * one second before midnight. (Some CAs wobble their expiry times a
790 * bit in practice, perhaps to reduce collision attacks; see ticket
791 * 8443 for details about observed certs in the wild.) */
792 lifetime--;
796 /* It's ok to pass lifetime in as an unsigned int, since
797 * config_parse_interval() checked it. */
798 return tor_tls_context_init(flags,
799 get_tlsclient_identity_key(),
800 server_mode(options) ?
801 get_server_identity_key() : NULL,
802 (unsigned int)lifetime);
805 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
806 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
807 * -1 if Tor should die,
809 STATIC int
810 router_write_fingerprint(int hashed)
812 char *keydir = NULL, *cp = NULL;
813 const char *fname = hashed ? "hashed-fingerprint" :
814 "fingerprint";
815 char fingerprint[FINGERPRINT_LEN+1];
816 const or_options_t *options = get_options();
817 char *fingerprint_line = NULL;
818 int result = -1;
820 keydir = get_datadir_fname(fname);
821 log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
822 hashed ? "hashed " : "", keydir);
823 if (!hashed) {
824 if (crypto_pk_get_fingerprint(get_server_identity_key(),
825 fingerprint, 0) < 0) {
826 log_err(LD_GENERAL,"Error computing fingerprint");
827 goto done;
829 } else {
830 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
831 fingerprint) < 0) {
832 log_err(LD_GENERAL,"Error computing hashed fingerprint");
833 goto done;
837 tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
839 /* Check whether we need to write the (hashed-)fingerprint file. */
841 cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
842 if (!cp || strcmp(cp, fingerprint_line)) {
843 if (write_str_to_file(keydir, fingerprint_line, 0)) {
844 log_err(LD_FS, "Error writing %sfingerprint line to file",
845 hashed ? "hashed " : "");
846 goto done;
850 log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
851 hashed ? "bridge's hashed" : "server's", options->Nickname,
852 fingerprint);
854 result = 0;
855 done:
856 tor_free(cp);
857 tor_free(keydir);
858 tor_free(fingerprint_line);
859 return result;
862 static int
863 init_keys_common(void)
865 if (!key_lock)
866 key_lock = tor_mutex_new();
868 /* There are a couple of paths that put us here before we've asked
869 * openssl to initialize itself. */
870 if (crypto_global_init(get_options()->HardwareAccel,
871 get_options()->AccelName,
872 get_options()->AccelDir)) {
873 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
874 return -1;
877 return 0;
881 init_keys_client(void)
883 crypto_pk_t *prkey;
884 if (init_keys_common() < 0)
885 return -1;
887 if (!(prkey = crypto_pk_new()))
888 return -1;
889 if (crypto_pk_generate_key(prkey)) {
890 crypto_pk_free(prkey);
891 return -1;
893 set_client_identity_key(prkey);
894 /* Create a TLS context. */
895 if (router_initialize_tls_context() < 0) {
896 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
897 return -1;
899 return 0;
902 /** Initialize all OR private keys, and the TLS context, as necessary.
903 * On OPs, this only initializes the tls context. Return 0 on success,
904 * or -1 if Tor should die.
907 init_keys(void)
909 char *keydir;
910 const char *mydesc;
911 crypto_pk_t *prkey;
912 char digest[DIGEST_LEN];
913 char v3_digest[DIGEST_LEN];
914 const or_options_t *options = get_options();
915 dirinfo_type_t type;
916 time_t now = time(NULL);
917 dir_server_t *ds;
918 int v3_digest_set = 0;
919 authority_cert_t *cert = NULL;
921 /* OP's don't need persistent keys; just make up an identity and
922 * initialize the TLS context. */
923 if (!server_mode(options)) {
924 return init_keys_client();
926 if (init_keys_common() < 0)
927 return -1;
929 if (create_keys_directory(options) < 0)
930 return -1;
932 /* 1a. Read v3 directory authority key/cert information. */
933 memset(v3_digest, 0, sizeof(v3_digest));
934 if (authdir_mode_v3(options)) {
935 if (init_v3_authority_keys()<0) {
936 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
937 "were unable to load our v3 authority keys and certificate! "
938 "Use tor-gencert to generate them. Dying.");
939 return -1;
941 cert = get_my_v3_authority_cert();
942 if (cert) {
943 if (crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
944 v3_digest) < 0) {
945 log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
946 "digest.");
947 return -1;
949 v3_digest_set = 1;
953 /* 1b. Read identity key. Make it if none is found. */
954 keydir = get_keydir_fname("secret_id_key");
955 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
956 bool created = false;
957 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
958 tor_free(keydir);
959 if (!prkey) return -1;
960 if (created)
961 log_new_relay_greeting();
962 set_server_identity_key(prkey);
964 /* 1c. If we are configured as a bridge, generate a client key;
965 * otherwise, set the server identity key as our client identity
966 * key. */
967 if (public_server_mode(options)) {
968 set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
969 } else {
970 if (!(prkey = crypto_pk_new()))
971 return -1;
972 if (crypto_pk_generate_key(prkey)) {
973 crypto_pk_free(prkey);
974 return -1;
976 set_client_identity_key(prkey);
979 /* 1d. Load all ed25519 keys */
980 const int new_signing_key = load_ed_keys(options,now);
981 if (new_signing_key < 0)
982 return -1;
984 /* 2. Read onion key. Make it if none is found. */
985 keydir = get_keydir_fname("secret_onion_key");
986 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
987 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
988 if (created)
989 log_new_relay_greeting();
990 tor_free(keydir);
991 if (!prkey) return -1;
992 set_onion_key(prkey);
993 if (options->command == CMD_RUN_TOR) {
994 /* only mess with the state file if we're actually running Tor */
995 or_state_t *state = get_or_state();
996 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
997 /* We allow for some parsing slop, but we don't want to risk accepting
998 * values in the distant future. If we did, we might never rotate the
999 * onion key. */
1000 onionkey_set_at = state->LastRotatedOnionKey;
1001 } else {
1002 /* We have no LastRotatedOnionKey set; either we just created the key
1003 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
1004 * start the clock ticking now so that we will eventually rotate it even
1005 * if we don't stay up for the full lifetime of an onion key. */
1006 state->LastRotatedOnionKey = onionkey_set_at = now;
1007 or_state_mark_dirty(state, options->AvoidDiskWrites ?
1008 time(NULL)+3600 : 0);
1012 keydir = get_keydir_fname("secret_onion_key.old");
1013 if (!lastonionkey && file_status(keydir) == FN_FILE) {
1014 /* Load keys from non-empty files only.
1015 * Missing old keys won't be replaced with freshly generated keys. */
1016 prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
1017 if (prkey)
1018 lastonionkey = prkey;
1020 tor_free(keydir);
1023 /* 2b. Load curve25519 onion keys. */
1024 int r;
1025 keydir = get_keydir_fname("secret_onion_key_ntor");
1026 r = init_curve25519_keypair_from_file(&curve25519_onion_key,
1027 keydir, 1, LOG_ERR, "onion");
1028 tor_free(keydir);
1029 if (r<0)
1030 return -1;
1032 keydir = get_keydir_fname("secret_onion_key_ntor.old");
1033 if (tor_mem_is_zero((const char *)
1034 last_curve25519_onion_key.pubkey.public_key,
1035 CURVE25519_PUBKEY_LEN) &&
1036 file_status(keydir) == FN_FILE) {
1037 /* Load keys from non-empty files only.
1038 * Missing old keys won't be replaced with freshly generated keys. */
1039 init_curve25519_keypair_from_file(&last_curve25519_onion_key,
1040 keydir, 0, LOG_ERR, "onion");
1042 tor_free(keydir);
1045 /* 3. Initialize link key and TLS context. */
1046 if (router_initialize_tls_context() < 0) {
1047 log_err(LD_GENERAL,"Error initializing TLS context");
1048 return -1;
1051 /* 3b. Get an ed25519 link certificate. Note that we need to do this
1052 * after we set up the TLS context */
1053 if (generate_ed_link_cert(options, now, new_signing_key > 0) < 0) {
1054 log_err(LD_GENERAL,"Couldn't make link cert");
1055 return -1;
1058 /* 4. Build our router descriptor. */
1059 /* Must be called after keys are initialized. */
1060 mydesc = router_get_my_descriptor();
1061 if (authdir_mode_v3(options)) {
1062 const char *m = NULL;
1063 routerinfo_t *ri;
1064 /* We need to add our own fingerprint so it gets recognized. */
1065 if (dirserv_add_own_fingerprint(get_server_identity_key())) {
1066 log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
1067 return -1;
1069 if (mydesc) {
1070 was_router_added_t added;
1071 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
1072 if (!ri) {
1073 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
1074 return -1;
1076 added = dirserv_add_descriptor(ri, &m, "self");
1077 if (!WRA_WAS_ADDED(added)) {
1078 if (!WRA_WAS_OUTDATED(added)) {
1079 log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
1080 m?m:"<unknown error>");
1081 return -1;
1082 } else {
1083 /* If the descriptor was outdated, that's ok. This can happen
1084 * when some config options are toggled that affect workers, but
1085 * we don't really need new keys yet so the descriptor doesn't
1086 * change and the old one is still fresh. */
1087 log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
1088 "after key init: %s This is usually not a problem.",
1089 m?m:"<unknown error>");
1095 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
1096 if (router_write_fingerprint(0)) {
1097 log_err(LD_FS, "Error writing fingerprint to file");
1098 return -1;
1100 if (!public_server_mode(options) && router_write_fingerprint(1)) {
1101 log_err(LD_FS, "Error writing hashed fingerprint to file");
1102 return -1;
1105 if (!authdir_mode(options))
1106 return 0;
1107 /* 6. [authdirserver only] load approved-routers file */
1108 if (dirserv_load_fingerprint_file() < 0) {
1109 log_err(LD_GENERAL,"Error loading fingerprints");
1110 return -1;
1112 /* 6b. [authdirserver only] add own key to approved directories. */
1113 crypto_pk_get_digest(get_server_identity_key(), digest);
1114 type = ((options->V3AuthoritativeDir ?
1115 (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
1116 (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
1118 ds = router_get_trusteddirserver_by_digest(digest);
1119 if (!ds) {
1120 ds = trusted_dir_server_new(options->Nickname, NULL,
1121 router_get_advertised_dir_port(options, 0),
1122 router_get_advertised_or_port(options),
1123 NULL,
1124 digest,
1125 v3_digest,
1126 type, 0.0);
1127 if (!ds) {
1128 log_err(LD_GENERAL,"We want to be a directory authority, but we "
1129 "couldn't add ourselves to the authority list. Failing.");
1130 return -1;
1132 dir_server_add(ds);
1134 if (ds->type != type) {
1135 log_warn(LD_DIR, "Configured authority type does not match authority "
1136 "type in DirAuthority list. Adjusting. (%d v %d)",
1137 type, ds->type);
1138 ds->type = type;
1140 if (v3_digest_set && (ds->type & V3_DIRINFO) &&
1141 tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
1142 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
1143 "DirAuthority line. Adjusting.");
1144 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
1147 if (cert) { /* add my own cert to the list of known certs */
1148 log_info(LD_DIR, "adding my own v3 cert");
1149 if (trusted_dirs_load_certs_from_string(
1150 cert->cache_info.signed_descriptor_body,
1151 TRUSTED_DIRS_CERTS_SRC_SELF, 0,
1152 NULL)<0) {
1153 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1154 return -1;
1158 return 0; /* success */
1161 /** The lower threshold of remaining bandwidth required to advertise (or
1162 * automatically provide) directory services */
1163 /* XXX Should this be increased? */
1164 #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
1166 /** Return true iff we have enough configured bandwidth to advertise or
1167 * automatically provide directory services from cache directory
1168 * information. */
1170 router_has_bandwidth_to_be_dirserver(const or_options_t *options)
1172 if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
1173 return 0;
1175 if (options->RelayBandwidthRate > 0 &&
1176 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
1177 return 0;
1179 return 1;
1182 /** Helper: Return 1 if we have sufficient resources for serving directory
1183 * requests, return 0 otherwise.
1184 * dir_port is either 0 or the configured DirPort number.
1185 * If AccountingMax is set less than our advertised bandwidth, then don't
1186 * serve requests. Likewise, if our advertised bandwidth is less than
1187 * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
1189 static int
1190 router_should_be_dirserver(const or_options_t *options, int dir_port)
1192 static int advertising=1; /* start out assuming we will advertise */
1193 int new_choice=1;
1194 const char *reason = NULL;
1196 if (accounting_is_enabled(options) &&
1197 get_options()->AccountingRule != ACCT_IN) {
1198 /* Don't spend bytes for directory traffic if we could end up hibernating,
1199 * but allow DirPort otherwise. Some relay operators set AccountingMax
1200 * because they're confused or to get statistics. Directory traffic has a
1201 * much larger effect on output than input so there is no reason to turn it
1202 * off if using AccountingRule in. */
1203 int interval_length = accounting_get_interval_length();
1204 uint32_t effective_bw = get_effective_bwrate(options);
1205 uint64_t acc_bytes;
1206 if (!interval_length) {
1207 log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1208 "seconds long. Raising to 1.");
1209 interval_length = 1;
1211 log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
1212 "bwrate: %u, AccountingMax: %"PRIu64", "
1213 "accounting interval length %d",
1214 dir_port ? "dirport" : "begindir",
1215 effective_bw, (options->AccountingMax),
1216 interval_length);
1218 acc_bytes = options->AccountingMax;
1219 if (get_options()->AccountingRule == ACCT_SUM)
1220 acc_bytes /= 2;
1221 if (effective_bw >=
1222 acc_bytes / interval_length) {
1223 new_choice = 0;
1224 reason = "AccountingMax enabled";
1226 } else if (! router_has_bandwidth_to_be_dirserver(options)) {
1227 /* if we're advertising a small amount */
1228 new_choice = 0;
1229 reason = "BandwidthRate under 50KB";
1232 if (advertising != new_choice) {
1233 if (new_choice == 1) {
1234 if (dir_port > 0)
1235 log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1236 else
1237 log_notice(LD_DIR, "Advertising directory service support");
1238 } else {
1239 tor_assert(reason);
1240 log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
1241 dir_port ? "Port" : "ectory Service support", reason);
1243 advertising = new_choice;
1246 return advertising;
1249 /** Look at a variety of factors, and return 0 if we don't want to
1250 * advertise the fact that we have a DirPort open or begindir support, else
1251 * return 1.
1253 * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1254 * must be 0.
1256 * Log a helpful message if we change our mind about whether to publish.
1258 static int
1259 decide_to_advertise_dir_impl(const or_options_t *options,
1260 uint16_t dir_port,
1261 int supports_tunnelled_dir_requests)
1263 /* Part one: reasons to publish or not publish that aren't
1264 * worth mentioning to the user, either because they're obvious
1265 * or because they're normal behavior. */
1267 /* short circuit the rest of the function */
1268 if (!dir_port && !supports_tunnelled_dir_requests)
1269 return 0;
1270 if (authdir_mode(options)) /* always publish */
1271 return 1;
1272 if (net_is_disabled())
1273 return 0;
1274 if (dir_port && !router_get_advertised_dir_port(options, dir_port))
1275 return 0;
1276 if (supports_tunnelled_dir_requests &&
1277 !router_get_advertised_or_port(options))
1278 return 0;
1280 /* Part two: consider config options that could make us choose to
1281 * publish or not publish that the user might find surprising. */
1282 return router_should_be_dirserver(options, dir_port);
1285 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1286 * advertise the fact that we have a DirPort open, else return the
1287 * DirPort we want to advertise.
1290 router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1292 /* supports_tunnelled_dir_requests is not relevant, pass 0 */
1293 return decide_to_advertise_dir_impl(options, dir_port, 0) ? dir_port : 0;
1296 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1297 * advertise the fact that we support begindir requests, else return 1.
1299 static int
1300 router_should_advertise_begindir(const or_options_t *options,
1301 int supports_tunnelled_dir_requests)
1303 /* dir_port is not relevant, pass 0 */
1304 return decide_to_advertise_dir_impl(options, 0,
1305 supports_tunnelled_dir_requests);
1308 /** Return true iff the combination of options in <b>options</b> and parameters
1309 * in the consensus mean that we don't want to allow exits from circuits
1310 * we got from addresses not known to be servers. */
1312 should_refuse_unknown_exits(const or_options_t *options)
1314 if (options->RefuseUnknownExits != -1) {
1315 return options->RefuseUnknownExits;
1316 } else {
1317 return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1321 /** Decide if we're a publishable server. We are a publishable server if:
1322 * - We don't have the ClientOnly option set
1323 * and
1324 * - We have the PublishServerDescriptor option set to non-empty
1325 * and
1326 * - We have ORPort set
1327 * and
1328 * - We believe our ORPort and DirPort (if present) are reachable from
1329 * the outside; or
1330 * - We believe our ORPort is reachable from the outside, and we can't
1331 * check our DirPort because the consensus has no exits; or
1332 * - We are an authoritative directory server.
1334 static int
1335 decide_if_publishable_server(void)
1337 const or_options_t *options = get_options();
1339 if (options->ClientOnly)
1340 return 0;
1341 if (options->PublishServerDescriptor_ == NO_DIRINFO)
1342 return 0;
1343 if (!server_mode(options))
1344 return 0;
1345 if (authdir_mode(options))
1346 return 1;
1347 if (!router_get_advertised_or_port(options))
1348 return 0;
1349 if (!check_whether_orport_reachable(options))
1350 return 0;
1351 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
1352 /* All set: there are no exits in the consensus (maybe this is a tiny
1353 * test network), so we can't check our DirPort reachability. */
1354 return 1;
1355 } else {
1356 return check_whether_dirport_reachable(options);
1360 /** Initiate server descriptor upload as reasonable (if server is publishable,
1361 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1363 * We need to rebuild the descriptor if it's dirty even if we're not
1364 * uploading, because our reachability testing *uses* our descriptor to
1365 * determine what IP address and ports to test.
1367 void
1368 consider_publishable_server(int force)
1370 int rebuilt;
1372 if (!server_mode(get_options()))
1373 return;
1375 rebuilt = router_rebuild_descriptor(0);
1376 if (decide_if_publishable_server()) {
1377 set_server_advertised(1);
1378 if (rebuilt == 0)
1379 router_upload_dir_desc_to_dirservers(force);
1380 } else {
1381 set_server_advertised(0);
1385 /** Return the port of the first active listener of type
1386 * <b>listener_type</b>. */
1387 /** XXX not a very good interface. it's not reliable when there are
1388 multiple listeners. */
1389 uint16_t
1390 router_get_active_listener_port_by_type_af(int listener_type,
1391 sa_family_t family)
1393 /* Iterate all connections, find one of the right kind and return
1394 the port. Not very sophisticated or fast, but effective. */
1395 smartlist_t *conns = get_connection_array();
1396 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1397 if (conn->type == listener_type && !conn->marked_for_close &&
1398 conn->socket_family == family) {
1399 return conn->port;
1401 } SMARTLIST_FOREACH_END(conn);
1403 return 0;
1406 /** Return the port that we should advertise as our ORPort; this is either
1407 * the one configured in the ORPort option, or the one we actually bound to
1408 * if ORPort is "auto".
1410 uint16_t
1411 router_get_advertised_or_port(const or_options_t *options)
1413 return router_get_advertised_or_port_by_af(options, AF_INET);
1416 /** As router_get_advertised_or_port(), but allows an address family argument.
1418 uint16_t
1419 router_get_advertised_or_port_by_af(const or_options_t *options,
1420 sa_family_t family)
1422 int port = get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER,
1423 family);
1424 (void)options;
1426 /* If the port is in 'auto' mode, we have to use
1427 router_get_listener_port_by_type(). */
1428 if (port == CFG_AUTO_PORT)
1429 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER,
1430 family);
1432 return port;
1435 /** Return the port that we should advertise as our DirPort;
1436 * this is one of three possibilities:
1437 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1438 * the one configured in the DirPort option,
1439 * or the one we actually bound to if DirPort is "auto". */
1440 uint16_t
1441 router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
1443 int dirport_configured = get_primary_dir_port();
1444 (void)options;
1446 if (!dirport_configured)
1447 return dirport;
1449 if (dirport_configured == CFG_AUTO_PORT)
1450 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER,
1451 AF_INET);
1453 return dirport_configured;
1457 * OR descriptor generation.
1460 /** My routerinfo. */
1461 static routerinfo_t *desc_routerinfo = NULL;
1462 /** My extrainfo */
1463 static extrainfo_t *desc_extrainfo = NULL;
1464 /** Why did we most recently decide to regenerate our descriptor? Used to
1465 * tell the authorities why we're sending it to them. */
1466 static const char *desc_gen_reason = "uninitialized reason";
1467 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1468 * now. */
1469 static time_t desc_clean_since = 0;
1470 /** Why did we mark the descriptor dirty? */
1471 static const char *desc_dirty_reason = "Tor just started";
1472 /** Boolean: do we need to regenerate the above? */
1473 static int desc_needs_upload = 0;
1475 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1476 * descriptor successfully yet, try to upload our signed descriptor to
1477 * all the directory servers we know about.
1479 void
1480 router_upload_dir_desc_to_dirservers(int force)
1482 const routerinfo_t *ri;
1483 extrainfo_t *ei;
1484 char *msg;
1485 size_t desc_len, extra_len = 0, total_len;
1486 dirinfo_type_t auth = get_options()->PublishServerDescriptor_;
1488 ri = router_get_my_routerinfo();
1489 if (!ri) {
1490 log_info(LD_GENERAL, "No descriptor; skipping upload");
1491 return;
1493 ei = router_get_my_extrainfo();
1494 if (auth == NO_DIRINFO)
1495 return;
1496 if (!force && !desc_needs_upload)
1497 return;
1499 log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1500 force ? " (forced)" : "");
1502 desc_needs_upload = 0;
1504 desc_len = ri->cache_info.signed_descriptor_len;
1505 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1506 total_len = desc_len + extra_len + 1;
1507 msg = tor_malloc(total_len);
1508 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1509 if (ei) {
1510 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1512 msg[desc_len+extra_len] = 0;
1514 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1515 (auth & BRIDGE_DIRINFO) ?
1516 ROUTER_PURPOSE_BRIDGE :
1517 ROUTER_PURPOSE_GENERAL,
1518 auth, msg, desc_len, extra_len);
1519 tor_free(msg);
1522 /** OR only: Check whether my exit policy says to allow connection to
1523 * conn. Return 0 if we accept; non-0 if we reject.
1526 router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
1528 const routerinfo_t *me = router_get_my_routerinfo();
1529 if (!me) /* make sure routerinfo exists */
1530 return -1;
1532 /* make sure it's resolved to something. this way we can't get a
1533 'maybe' below. */
1534 if (tor_addr_is_null(addr))
1535 return -1;
1537 /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
1538 * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
1539 * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
1540 * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
1541 * summary. */
1542 if ((tor_addr_family(addr) == AF_INET ||
1543 tor_addr_family(addr) == AF_INET6)) {
1544 return compare_tor_addr_to_addr_policy(addr, port,
1545 me->exit_policy) != ADDR_POLICY_ACCEPTED;
1546 #if 0
1547 } else if (tor_addr_family(addr) == AF_INET6) {
1548 return get_options()->IPv6Exit &&
1549 desc_routerinfo->ipv6_exit_policy &&
1550 compare_tor_addr_to_short_policy(addr, port,
1551 me->ipv6_exit_policy) != ADDR_POLICY_ACCEPTED;
1552 #endif /* 0 */
1553 } else {
1554 return -1;
1558 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1559 * have a descriptor */
1560 MOCK_IMPL(int,
1561 router_my_exit_policy_is_reject_star,(void))
1563 const routerinfo_t *me = router_get_my_routerinfo();
1564 if (!me) /* make sure routerinfo exists */
1565 return -1;
1567 return me->policy_is_reject_star;
1570 /** Return true iff I'm a server and <b>digest</b> is equal to
1571 * my server identity key digest. */
1573 router_digest_is_me(const char *digest)
1575 return (server_identitykey &&
1576 tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
1579 /** Return my identity digest. */
1580 const uint8_t *
1581 router_get_my_id_digest(void)
1583 return (const uint8_t *)server_identitykey_digest;
1586 /** Return true iff I'm a server and <b>digest</b> is equal to
1587 * my identity digest. */
1589 router_extrainfo_digest_is_me(const char *digest)
1591 extrainfo_t *ei = router_get_my_extrainfo();
1592 if (!ei)
1593 return 0;
1595 return tor_memeq(digest,
1596 ei->cache_info.signed_descriptor_digest,
1597 DIGEST_LEN);
1600 /** A wrapper around router_digest_is_me(). */
1602 router_is_me(const routerinfo_t *router)
1604 return router_digest_is_me(router->cache_info.identity_digest);
1607 /** Return a routerinfo for this OR, rebuilding a fresh one if
1608 * necessary. Return NULL on error, or if called on an OP. */
1609 MOCK_IMPL(const routerinfo_t *,
1610 router_get_my_routerinfo,(void))
1612 return router_get_my_routerinfo_with_err(NULL);
1615 /** Return routerinfo of this OR. Rebuild it from
1616 * scratch if needed. Set <b>*err</b> to 0 on success or to
1617 * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
1619 MOCK_IMPL(const routerinfo_t *,
1620 router_get_my_routerinfo_with_err,(int *err))
1622 if (!server_mode(get_options())) {
1623 if (err)
1624 *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
1626 return NULL;
1629 if (!desc_clean_since) {
1630 int rebuild_err = router_rebuild_descriptor(0);
1631 if (rebuild_err < 0) {
1632 if (err)
1633 *err = rebuild_err;
1635 return NULL;
1639 if (!desc_routerinfo) {
1640 if (err)
1641 *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
1643 return NULL;
1646 if (err)
1647 *err = 0;
1649 return desc_routerinfo;
1652 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1653 * one if necessary. Return NULL on error.
1655 const char *
1656 router_get_my_descriptor(void)
1658 const char *body;
1659 const routerinfo_t *me = router_get_my_routerinfo();
1660 if (! me)
1661 return NULL;
1662 tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
1663 body = signed_descriptor_get_body(&me->cache_info);
1664 /* Make sure this is nul-terminated. */
1665 tor_assert(!body[me->cache_info.signed_descriptor_len]);
1666 log_debug(LD_GENERAL,"my desc is '%s'", body);
1667 return body;
1670 /** Return the extrainfo document for this OR, or NULL if we have none.
1671 * Rebuilt it (and the server descriptor) if necessary. */
1672 extrainfo_t *
1673 router_get_my_extrainfo(void)
1675 if (!server_mode(get_options()))
1676 return NULL;
1677 if (router_rebuild_descriptor(0))
1678 return NULL;
1679 return desc_extrainfo;
1682 /** Return a human-readable string describing what triggered us to generate
1683 * our current descriptor, or NULL if we don't know. */
1684 const char *
1685 router_get_descriptor_gen_reason(void)
1687 return desc_gen_reason;
1690 /** A list of nicknames that we've warned about including in our family
1691 * declaration verbatim rather than as digests. */
1692 static smartlist_t *warned_nonexistent_family = NULL;
1694 static int router_guess_address_from_dir_headers(uint32_t *guess);
1696 /** Make a current best guess at our address, either because
1697 * it's configured in torrc, or because we've learned it from
1698 * dirserver headers. Place the answer in *<b>addr</b> and return
1699 * 0 on success, else return -1 if we have no guess.
1701 * If <b>cache_only</b> is true, just return any cached answers, and
1702 * don't try to get any new answers.
1704 MOCK_IMPL(int,
1705 router_pick_published_address,(const or_options_t *options, uint32_t *addr,
1706 int cache_only))
1708 /* First, check the cached output from resolve_my_address(). */
1709 *addr = get_last_resolved_addr();
1710 if (*addr)
1711 return 0;
1713 /* Second, consider doing a resolve attempt right here. */
1714 if (!cache_only) {
1715 if (resolve_my_address(LOG_INFO, options, addr, NULL, NULL) >= 0) {
1716 log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
1717 return 0;
1721 /* Third, check the cached output from router_new_address_suggestion(). */
1722 if (router_guess_address_from_dir_headers(addr) >= 0)
1723 return 0;
1725 /* We have no useful cached answers. Return failure. */
1726 return -1;
1729 /* Like router_check_descriptor_address_consistency, but specifically for the
1730 * ORPort or DirPort.
1731 * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
1732 static void
1733 router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr,
1734 int listener_type)
1736 tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
1737 listener_type == CONN_TYPE_DIR_LISTENER);
1739 /* The first advertised Port may be the magic constant CFG_AUTO_PORT.
1741 int port_v4_cfg = get_first_advertised_port_by_type_af(listener_type,
1742 AF_INET);
1743 if (port_v4_cfg != 0 &&
1744 !port_exists_by_type_addr32h_port(listener_type,
1745 ipv4h_desc_addr, port_v4_cfg, 1)) {
1746 const tor_addr_t *port_addr = get_first_advertised_addr_by_type_af(
1747 listener_type,
1748 AF_INET);
1749 /* If we're building a descriptor with no advertised address,
1750 * something is terribly wrong. */
1751 tor_assert(port_addr);
1753 tor_addr_t desc_addr;
1754 char port_addr_str[TOR_ADDR_BUF_LEN];
1755 char desc_addr_str[TOR_ADDR_BUF_LEN];
1757 tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
1759 tor_addr_from_ipv4h(&desc_addr, ipv4h_desc_addr);
1760 tor_addr_to_str(desc_addr_str, &desc_addr, TOR_ADDR_BUF_LEN, 0);
1762 const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
1763 "OR" : "Dir");
1764 log_warn(LD_CONFIG, "The IPv4 %sPort address %s does not match the "
1765 "descriptor address %s. If you have a static public IPv4 "
1766 "address, use 'Address <IPv4>' and 'OutboundBindAddress "
1767 "<IPv4>'. If you are behind a NAT, use two %sPort lines: "
1768 "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
1769 "NoAdvertise'.",
1770 listener_str, port_addr_str, desc_addr_str, listener_str,
1771 listener_str, listener_str);
1775 /* Tor relays only have one IPv4 address in the descriptor, which is derived
1776 * from the Address torrc option, or guessed using various methods in
1777 * router_pick_published_address().
1778 * Warn the operator if there is no ORPort on the descriptor address
1779 * ipv4h_desc_addr.
1780 * Warn the operator if there is no DirPort on the descriptor address.
1781 * This catches a few common config errors:
1782 * - operators who expect ORPorts and DirPorts to be advertised on the
1783 * ports' listen addresses, rather than the torrc Address (or guessed
1784 * addresses in the absence of an Address config). This includes
1785 * operators who attempt to put their ORPort and DirPort on different
1786 * addresses;
1787 * - discrepancies between guessed addresses and configured listen
1788 * addresses (when the Address option isn't set).
1789 * If a listener is listening on all IPv4 addresses, it is assumed that it
1790 * is listening on the configured Address, and no messages are logged.
1791 * If an operators has specified NoAdvertise ORPorts in a NAT setting,
1792 * no messages are logged, unless they have specified other advertised
1793 * addresses.
1794 * The message tells operators to configure an ORPort and DirPort that match
1795 * the Address (using NoListen if needed).
1797 static void
1798 router_check_descriptor_address_consistency(uint32_t ipv4h_desc_addr)
1800 router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1801 CONN_TYPE_OR_LISTENER);
1802 router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1803 CONN_TYPE_DIR_LISTENER);
1806 /** Build a fresh routerinfo, signed server descriptor, and extra-info document
1807 * for this OR. Set r to the generated routerinfo, e to the generated
1808 * extra-info document. Return 0 on success, -1 on temporary error. Failure to
1809 * generate an extra-info document is not an error and is indicated by setting
1810 * e to NULL. Caller is responsible for freeing generated documents if 0 is
1811 * returned.
1814 router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
1816 routerinfo_t *ri;
1817 extrainfo_t *ei;
1818 uint32_t addr;
1819 char platform[256];
1820 int hibernating = we_are_hibernating();
1821 const or_options_t *options = get_options();
1823 if (router_pick_published_address(options, &addr, 0) < 0) {
1824 log_warn(LD_CONFIG, "Don't know my address while generating descriptor");
1825 return TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
1828 /* Log a message if the address in the descriptor doesn't match the ORPort
1829 * and DirPort addresses configured by the operator. */
1830 router_check_descriptor_address_consistency(addr);
1832 ri = tor_malloc_zero(sizeof(routerinfo_t));
1833 ri->cache_info.routerlist_index = -1;
1834 ri->nickname = tor_strdup(options->Nickname);
1835 ri->addr = addr;
1836 ri->or_port = router_get_advertised_or_port(options);
1837 ri->dir_port = router_get_advertised_dir_port(options, 0);
1838 ri->supports_tunnelled_dir_requests =
1839 directory_permits_begindir_requests(options);
1840 ri->cache_info.published_on = time(NULL);
1841 /* get_onion_key() must invoke from main thread */
1842 router_set_rsa_onion_pkey(get_onion_key(), &ri->onion_pkey,
1843 &ri->onion_pkey_len);
1845 ri->onion_curve25519_pkey =
1846 tor_memdup(&get_current_curve25519_keypair()->pubkey,
1847 sizeof(curve25519_public_key_t));
1849 /* For now, at most one IPv6 or-address is being advertised. */
1851 const port_cfg_t *ipv6_orport = NULL;
1852 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
1853 if (p->type == CONN_TYPE_OR_LISTENER &&
1854 ! p->server_cfg.no_advertise &&
1855 ! p->server_cfg.bind_ipv4_only &&
1856 tor_addr_family(&p->addr) == AF_INET6) {
1857 /* Like IPv4, if the relay is configured using the default
1858 * authorities, disallow internal IPs. Otherwise, allow them. */
1859 const int default_auth = using_default_dir_authorities(options);
1860 if (! tor_addr_is_internal(&p->addr, 0) || ! default_auth) {
1861 ipv6_orport = p;
1862 break;
1863 } else {
1864 char addrbuf[TOR_ADDR_BUF_LEN];
1865 log_warn(LD_CONFIG,
1866 "Unable to use configured IPv6 address \"%s\" in a "
1867 "descriptor. Skipping it. "
1868 "Try specifying a globally reachable address explicitly.",
1869 tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
1872 } SMARTLIST_FOREACH_END(p);
1873 if (ipv6_orport) {
1874 tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
1875 ri->ipv6_orport = ipv6_orport->port;
1879 ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
1880 if (BUG(crypto_pk_get_digest(ri->identity_pkey,
1881 ri->cache_info.identity_digest) < 0)) {
1882 routerinfo_free(ri);
1883 return TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
1885 ri->cache_info.signing_key_cert =
1886 tor_cert_dup(get_master_signing_key_cert());
1888 get_platform_str(platform, sizeof(platform));
1889 ri->platform = tor_strdup(platform);
1891 ri->protocol_list = tor_strdup(protover_get_supported_protocols());
1893 /* compute ri->bandwidthrate as the min of various options */
1894 ri->bandwidthrate = get_effective_bwrate(options);
1896 /* and compute ri->bandwidthburst similarly */
1897 ri->bandwidthburst = get_effective_bwburst(options);
1899 /* Report bandwidth, unless we're hibernating or shutting down */
1900 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1902 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1903 /* DNS is screwed up; don't claim to be an exit. */
1904 policies_exit_policy_append_reject_star(&ri->exit_policy);
1905 } else {
1906 policies_parse_exit_policy_from_options(options,ri->addr,&ri->ipv6_addr,
1907 &ri->exit_policy);
1909 ri->policy_is_reject_star =
1910 policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
1911 policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
1913 if (options->IPv6Exit) {
1914 char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
1915 if (p_tmp)
1916 ri->ipv6_exit_policy = parse_short_policy(p_tmp);
1917 tor_free(p_tmp);
1920 if (options->MyFamily && ! options->BridgeRelay) {
1921 if (!warned_nonexistent_family)
1922 warned_nonexistent_family = smartlist_new();
1923 ri->declared_family = smartlist_new();
1924 config_line_t *family;
1925 for (family = options->MyFamily; family; family = family->next) {
1926 char *name = family->value;
1927 const node_t *member;
1928 if (!strcasecmp(name, options->Nickname))
1929 continue; /* Don't list ourself, that's redundant */
1930 else
1931 member = node_get_by_nickname(name, 0);
1932 if (!member) {
1933 int is_legal = is_legal_nickname_or_hexdigest(name);
1934 if (!smartlist_contains_string(warned_nonexistent_family, name) &&
1935 !is_legal_hexdigest(name)) {
1936 if (is_legal)
1937 log_warn(LD_CONFIG,
1938 "I have no descriptor for the router named \"%s\" in my "
1939 "declared family; I'll use the nickname as is, but "
1940 "this may confuse clients.", name);
1941 else
1942 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1943 "declared family, but that isn't a legal nickname. "
1944 "Skipping it.", escaped(name));
1945 smartlist_add_strdup(warned_nonexistent_family, name);
1947 if (is_legal) {
1948 smartlist_add_strdup(ri->declared_family, name);
1950 } else if (router_digest_is_me(member->identity)) {
1951 /* Don't list ourself in our own family; that's redundant */
1952 /* XXX shouldn't be possible */
1953 } else {
1954 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1955 fp[0] = '$';
1956 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1957 member->identity, DIGEST_LEN);
1958 smartlist_add(ri->declared_family, fp);
1959 if (smartlist_contains_string(warned_nonexistent_family, name))
1960 smartlist_string_remove(warned_nonexistent_family, name);
1964 /* remove duplicates from the list */
1965 smartlist_sort_strings(ri->declared_family);
1966 smartlist_uniq_strings(ri->declared_family);
1969 /* Now generate the extrainfo. */
1970 ei = tor_malloc_zero(sizeof(extrainfo_t));
1971 ei->cache_info.is_extrainfo = 1;
1972 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1973 ei->cache_info.published_on = ri->cache_info.published_on;
1974 ei->cache_info.signing_key_cert =
1975 tor_cert_dup(get_master_signing_key_cert());
1977 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1978 DIGEST_LEN);
1979 if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
1980 ei, get_server_identity_key(),
1981 get_master_signing_keypair()) < 0) {
1982 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1983 extrainfo_free(ei);
1984 ei = NULL;
1985 } else {
1986 ei->cache_info.signed_descriptor_len =
1987 strlen(ei->cache_info.signed_descriptor_body);
1988 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1989 ei->cache_info.signed_descriptor_len,
1990 ei->cache_info.signed_descriptor_digest);
1991 crypto_digest256((char*) ei->digest256,
1992 ei->cache_info.signed_descriptor_body,
1993 ei->cache_info.signed_descriptor_len,
1994 DIGEST_SHA256);
1997 /* Now finish the router descriptor. */
1998 if (ei) {
1999 memcpy(ri->cache_info.extra_info_digest,
2000 ei->cache_info.signed_descriptor_digest,
2001 DIGEST_LEN);
2002 memcpy(ri->cache_info.extra_info_digest256,
2003 ei->digest256,
2004 DIGEST256_LEN);
2005 } else {
2006 /* ri was allocated with tor_malloc_zero, so there is no need to
2007 * zero ri->cache_info.extra_info_digest here. */
2009 if (! (ri->cache_info.signed_descriptor_body =
2010 router_dump_router_to_string(ri, get_server_identity_key(),
2011 get_onion_key(),
2012 get_current_curve25519_keypair(),
2013 get_master_signing_keypair())) ) {
2014 log_warn(LD_BUG, "Couldn't generate router descriptor.");
2015 routerinfo_free(ri);
2016 extrainfo_free(ei);
2017 return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
2019 ri->cache_info.signed_descriptor_len =
2020 strlen(ri->cache_info.signed_descriptor_body);
2022 ri->purpose =
2023 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
2024 if (options->BridgeRelay) {
2025 /* Bridges shouldn't be able to send their descriptors unencrypted,
2026 anyway, since they don't have a DirPort, and always connect to the
2027 bridge authority anonymously. But just in case they somehow think of
2028 sending them on an unencrypted connection, don't allow them to try. */
2029 ri->cache_info.send_unencrypted = 0;
2030 if (ei)
2031 ei->cache_info.send_unencrypted = 0;
2032 } else {
2033 ri->cache_info.send_unencrypted = 1;
2034 if (ei)
2035 ei->cache_info.send_unencrypted = 1;
2038 router_get_router_hash(ri->cache_info.signed_descriptor_body,
2039 strlen(ri->cache_info.signed_descriptor_body),
2040 ri->cache_info.signed_descriptor_digest);
2042 if (ei) {
2043 tor_assert(!
2044 routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
2045 &ri->cache_info, NULL));
2048 *r = ri;
2049 *e = ei;
2050 return 0;
2053 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2054 * routerinfo, signed server descriptor, and extra-info document for this OR.
2055 * Return 0 on success, -1 on temporary error.
2058 router_rebuild_descriptor(int force)
2060 int err = 0;
2061 routerinfo_t *ri;
2062 extrainfo_t *ei;
2063 uint32_t addr;
2064 const or_options_t *options = get_options();
2066 if (desc_clean_since && !force)
2067 return 0;
2069 if (router_pick_published_address(options, &addr, 0) < 0 ||
2070 router_get_advertised_or_port(options) == 0) {
2071 /* Stop trying to rebuild our descriptor every second. We'll
2072 * learn that it's time to try again when ip_address_changed()
2073 * marks it dirty. */
2074 desc_clean_since = time(NULL);
2075 return TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
2078 log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
2080 err = router_build_fresh_descriptor(&ri, &ei);
2081 if (err < 0) {
2082 return err;
2085 routerinfo_free(desc_routerinfo);
2086 desc_routerinfo = ri;
2087 extrainfo_free(desc_extrainfo);
2088 desc_extrainfo = ei;
2090 desc_clean_since = time(NULL);
2091 desc_needs_upload = 1;
2092 desc_gen_reason = desc_dirty_reason;
2093 if (BUG(desc_gen_reason == NULL)) {
2094 desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
2096 desc_dirty_reason = NULL;
2097 control_event_my_descriptor_changed();
2098 return 0;
2101 /** If our router descriptor ever goes this long without being regenerated
2102 * because something changed, we force an immediate regenerate-and-upload. */
2103 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2105 /** If our router descriptor seems to be missing or unacceptable according
2106 * to the authorities, regenerate and reupload it _this_ often. */
2107 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2109 /** Mark descriptor out of date if it's been "too long" since we last tried
2110 * to upload one. */
2111 void
2112 mark_my_descriptor_dirty_if_too_old(time_t now)
2114 networkstatus_t *ns;
2115 const routerstatus_t *rs;
2116 const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2117 const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2118 const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2120 /* If it's already dirty, don't mark it. */
2121 if (! desc_clean_since)
2122 return;
2124 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2125 * time to rebuild it. */
2126 if (desc_clean_since < slow_cutoff) {
2127 mark_my_descriptor_dirty("time for new descriptor");
2128 return;
2130 /* Now we see whether we want to be retrying frequently or no. The
2131 * rule here is that we'll retry frequently if we aren't listed in the
2132 * live consensus we have, or if the publication time of the
2133 * descriptor listed for us in the consensus is very old. */
2134 ns = networkstatus_get_live_consensus(now);
2135 if (ns) {
2136 rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
2137 if (rs == NULL)
2138 retry_fast_reason = "not listed in consensus";
2139 else if (rs->published_on < slow_cutoff)
2140 retry_fast_reason = "version listed in consensus is quite old";
2143 if (retry_fast_reason && desc_clean_since < fast_cutoff)
2144 mark_my_descriptor_dirty(retry_fast_reason);
2147 /** Call when the current descriptor is out of date. */
2148 void
2149 mark_my_descriptor_dirty(const char *reason)
2151 const or_options_t *options = get_options();
2152 if (BUG(reason == NULL)) {
2153 reason = "marked descriptor dirty for unspecified reason";
2155 if (server_mode(options) && options->PublishServerDescriptor_)
2156 log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2157 desc_clean_since = 0;
2158 if (!desc_dirty_reason)
2159 desc_dirty_reason = reason;
2162 /** How frequently will we republish our descriptor because of large (factor
2163 * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2164 * if our previous bandwidth estimate was exactly 0. */
2165 #define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
2167 /** Maximum uptime to republish our descriptor because of large shifts in
2168 * estimated bandwidth. */
2169 #define MAX_UPTIME_BANDWIDTH_CHANGE (24*60*60)
2171 /** By which factor bandwidth shifts have to change to be considered large. */
2172 #define BANDWIDTH_CHANGE_FACTOR 2
2174 /** Check whether bandwidth has changed a lot since the last time we announced
2175 * bandwidth while the uptime is smaller than MAX_UPTIME_BANDWIDTH_CHANGE.
2176 * If so, mark our descriptor dirty. */
2177 void
2178 check_descriptor_bandwidth_changed(time_t now)
2180 static time_t last_changed = 0;
2181 uint64_t prev, cur;
2182 const int hibernating = we_are_hibernating();
2184 /* If the relay uptime is bigger than MAX_UPTIME_BANDWIDTH_CHANGE,
2185 * the next regularly scheduled descriptor update (18h) will be enough */
2186 if (get_uptime() > MAX_UPTIME_BANDWIDTH_CHANGE && !hibernating)
2187 return;
2189 const routerinfo_t *my_ri = router_get_my_routerinfo();
2191 if (!my_ri)
2192 return;
2194 prev = my_ri->bandwidthcapacity;
2196 /* Consider ourselves to have zero bandwidth if we're hibernating or
2197 * shutting down. */
2198 cur = hibernating ? 0 : rep_hist_bandwidth_assess();
2200 if ((prev != cur && (!prev || !cur)) ||
2201 cur > (prev * BANDWIDTH_CHANGE_FACTOR) ||
2202 cur < (prev / BANDWIDTH_CHANGE_FACTOR) ) {
2203 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
2204 log_info(LD_GENERAL,
2205 "Measured bandwidth has changed; rebuilding descriptor.");
2206 mark_my_descriptor_dirty("bandwidth has changed");
2207 last_changed = now;
2212 /** Note at log level severity that our best guess of address has changed from
2213 * <b>prev</b> to <b>cur</b>. */
2214 static void
2215 log_addr_has_changed(int severity,
2216 const tor_addr_t *prev,
2217 const tor_addr_t *cur,
2218 const char *source)
2220 char addrbuf_prev[TOR_ADDR_BUF_LEN];
2221 char addrbuf_cur[TOR_ADDR_BUF_LEN];
2223 if (BUG(!server_mode(get_options())))
2224 return;
2226 if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2227 strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2228 if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2229 strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2231 if (!tor_addr_is_null(prev))
2232 log_fn(severity, LD_GENERAL,
2233 "Our IP Address has changed from %s to %s; "
2234 "rebuilding descriptor (source: %s).",
2235 addrbuf_prev, addrbuf_cur, source);
2236 else
2237 log_notice(LD_GENERAL,
2238 "Guessed our IP address as %s (source: %s).",
2239 addrbuf_cur, source);
2242 /** Check whether our own address as defined by the Address configuration
2243 * has changed. This is for routers that get their address from a service
2244 * like dyndns. If our address has changed, mark our descriptor dirty. */
2245 void
2246 check_descriptor_ipaddress_changed(time_t now)
2248 uint32_t prev, cur;
2249 const or_options_t *options = get_options();
2250 const char *method = NULL;
2251 char *hostname = NULL;
2252 const routerinfo_t *my_ri = router_get_my_routerinfo();
2254 (void) now;
2256 if (my_ri == NULL) /* make sure routerinfo exists */
2257 return;
2259 /* XXXX ipv6 */
2260 prev = my_ri->addr;
2261 if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
2262 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
2263 return;
2266 if (prev != cur) {
2267 char *source;
2268 tor_addr_t tmp_prev, tmp_cur;
2270 tor_addr_from_ipv4h(&tmp_prev, prev);
2271 tor_addr_from_ipv4h(&tmp_cur, cur);
2273 tor_asprintf(&source, "METHOD=%s%s%s", method,
2274 hostname ? " HOSTNAME=" : "",
2275 hostname ? hostname : "");
2277 log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
2278 tor_free(source);
2280 ip_address_changed(0);
2283 tor_free(hostname);
2286 /** The most recently guessed value of our IP address, based on directory
2287 * headers. */
2288 static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
2290 /** A directory server <b>d_conn</b> told us our IP address is
2291 * <b>suggestion</b>.
2292 * If this address is different from the one we think we are now, and
2293 * if our computer doesn't actually know its IP address, then switch. */
2294 void
2295 router_new_address_suggestion(const char *suggestion,
2296 const dir_connection_t *d_conn)
2298 tor_addr_t addr;
2299 uint32_t cur = 0; /* Current IPv4 address. */
2300 const or_options_t *options = get_options();
2302 /* first, learn what the IP address actually is */
2303 if (tor_addr_parse(&addr, suggestion) == -1) {
2304 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
2305 escaped(suggestion));
2306 return;
2309 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
2311 if (!server_mode(options)) {
2312 tor_addr_copy(&last_guessed_ip, &addr);
2313 return;
2316 /* XXXX ipv6 */
2317 cur = get_last_resolved_addr();
2318 if (cur ||
2319 resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
2320 /* We're all set -- we already know our address. Great. */
2321 tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
2322 need it later */
2323 return;
2325 if (tor_addr_is_internal(&addr, 0)) {
2326 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2327 return;
2329 if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
2330 /* Don't believe anybody who says our IP is their IP. */
2331 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
2332 "but they are just reporting their own IP address. Ignoring.",
2333 suggestion);
2334 return;
2337 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2338 * us an answer different from what we had the last time we managed to
2339 * resolve it. */
2340 if (!tor_addr_eq(&last_guessed_ip, &addr)) {
2341 control_event_server_status(LOG_NOTICE,
2342 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2343 suggestion);
2344 log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
2345 d_conn->base_.address);
2346 ip_address_changed(0);
2347 tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
2348 will fetch it */
2352 /** We failed to resolve our address locally, but we'd like to build
2353 * a descriptor and publish / test reachability. If we have a guess
2354 * about our address based on directory headers, answer it and return
2355 * 0; else return -1. */
2356 static int
2357 router_guess_address_from_dir_headers(uint32_t *guess)
2359 if (!tor_addr_is_null(&last_guessed_ip)) {
2360 *guess = tor_addr_to_ipv4h(&last_guessed_ip);
2361 return 0;
2363 return -1;
2366 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2367 * string describing the version of Tor and the operating system we're
2368 * currently running on.
2370 STATIC void
2371 get_platform_str(char *platform, size_t len)
2373 tor_snprintf(platform, len, "Tor %s on %s",
2374 get_short_version(), get_uname());
2377 /* XXX need to audit this thing and count fenceposts. maybe
2378 * refactor so we don't have to keep asking if we're
2379 * near the end of maxlen?
2381 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2383 /** OR only: Given a routerinfo for this router, and an identity key to sign
2384 * with, encode the routerinfo as a signed server descriptor and return a new
2385 * string encoding the result, or NULL on failure.
2387 char *
2388 router_dump_router_to_string(routerinfo_t *router,
2389 const crypto_pk_t *ident_key,
2390 const crypto_pk_t *tap_key,
2391 const curve25519_keypair_t *ntor_keypair,
2392 const ed25519_keypair_t *signing_keypair)
2394 char *address = NULL;
2395 char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2396 crypto_pk_t *rsa_pubkey = NULL;
2397 char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2398 char digest[DIGEST256_LEN];
2399 char published[ISO_TIME_LEN+1];
2400 char fingerprint[FINGERPRINT_LEN+1];
2401 char *extra_info_line = NULL;
2402 size_t onion_pkeylen, identity_pkeylen;
2403 char *family_line = NULL;
2404 char *extra_or_address = NULL;
2405 const or_options_t *options = get_options();
2406 smartlist_t *chunks = NULL;
2407 char *output = NULL;
2408 const int emit_ed_sigs = signing_keypair &&
2409 router->cache_info.signing_key_cert;
2410 char *ed_cert_line = NULL;
2411 char *rsa_tap_cc_line = NULL;
2412 char *ntor_cc_line = NULL;
2413 char *proto_line = NULL;
2415 /* Make sure the identity key matches the one in the routerinfo. */
2416 if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2417 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2418 "match router's public key!");
2419 goto err;
2421 if (emit_ed_sigs) {
2422 if (!router->cache_info.signing_key_cert->signing_key_included ||
2423 !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
2424 &signing_keypair->pubkey)) {
2425 log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
2426 "ed25519 key chain %d",
2427 router->cache_info.signing_key_cert->signing_key_included);
2428 goto err;
2432 /* record our fingerprint, so we can include it in the descriptor */
2433 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2434 log_err(LD_BUG,"Error computing fingerprint");
2435 goto err;
2438 if (emit_ed_sigs) {
2439 /* Encode ed25519 signing cert */
2440 char ed_cert_base64[256];
2441 char ed_fp_base64[ED25519_BASE64_LEN+1];
2442 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2443 (const char*)router->cache_info.signing_key_cert->encoded,
2444 router->cache_info.signing_key_cert->encoded_len,
2445 BASE64_ENCODE_MULTILINE) < 0) {
2446 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2447 goto err;
2449 if (ed25519_public_to_base64(ed_fp_base64,
2450 &router->cache_info.signing_key_cert->signing_key)<0) {
2451 log_err(LD_BUG,"Couldn't base64-encode identity key\n");
2452 goto err;
2454 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2455 "-----BEGIN ED25519 CERT-----\n"
2456 "%s"
2457 "-----END ED25519 CERT-----\n"
2458 "master-key-ed25519 %s\n",
2459 ed_cert_base64, ed_fp_base64);
2462 /* PEM-encode the onion key */
2463 rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
2464 router->onion_pkey_len);
2465 if (crypto_pk_write_public_key_to_string(rsa_pubkey,
2466 &onion_pkey,&onion_pkeylen)<0) {
2467 log_warn(LD_BUG,"write onion_pkey to string failed!");
2468 goto err;
2471 /* PEM-encode the identity key */
2472 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
2473 &identity_pkey,&identity_pkeylen)<0) {
2474 log_warn(LD_BUG,"write identity_pkey to string failed!");
2475 goto err;
2478 /* Cross-certify with RSA key */
2479 if (tap_key && router->cache_info.signing_key_cert &&
2480 router->cache_info.signing_key_cert->signing_key_included) {
2481 char buf[256];
2482 int tap_cc_len = 0;
2483 uint8_t *tap_cc =
2484 make_tap_onion_key_crosscert(tap_key,
2485 &router->cache_info.signing_key_cert->signing_key,
2486 router->identity_pkey,
2487 &tap_cc_len);
2488 if (!tap_cc) {
2489 log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
2490 goto err;
2493 if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
2494 BASE64_ENCODE_MULTILINE) < 0) {
2495 log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
2496 tor_free(tap_cc);
2497 goto err;
2499 tor_free(tap_cc);
2501 tor_asprintf(&rsa_tap_cc_line,
2502 "onion-key-crosscert\n"
2503 "-----BEGIN CROSSCERT-----\n"
2504 "%s"
2505 "-----END CROSSCERT-----\n", buf);
2508 /* Cross-certify with onion keys */
2509 if (ntor_keypair && router->cache_info.signing_key_cert &&
2510 router->cache_info.signing_key_cert->signing_key_included) {
2511 int sign = 0;
2512 char buf[256];
2513 /* XXXX Base the expiration date on the actual onion key expiration time?*/
2514 tor_cert_t *cert =
2515 make_ntor_onion_key_crosscert(ntor_keypair,
2516 &router->cache_info.signing_key_cert->signing_key,
2517 router->cache_info.published_on,
2518 get_onion_key_lifetime(), &sign);
2519 if (!cert) {
2520 log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
2521 goto err;
2523 tor_assert(sign == 0 || sign == 1);
2525 if (base64_encode(buf, sizeof(buf),
2526 (const char*)cert->encoded, cert->encoded_len,
2527 BASE64_ENCODE_MULTILINE)<0) {
2528 log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
2529 tor_cert_free(cert);
2530 goto err;
2532 tor_cert_free(cert);
2534 tor_asprintf(&ntor_cc_line,
2535 "ntor-onion-key-crosscert %d\n"
2536 "-----BEGIN ED25519 CERT-----\n"
2537 "%s"
2538 "-----END ED25519 CERT-----\n", sign, buf);
2541 /* Encode the publication time. */
2542 format_iso_time(published, router->cache_info.published_on);
2544 if (router->declared_family && smartlist_len(router->declared_family)) {
2545 char *family = smartlist_join_strings(router->declared_family,
2546 " ", 0, NULL);
2547 tor_asprintf(&family_line, "family %s\n", family);
2548 tor_free(family);
2549 } else {
2550 family_line = tor_strdup("");
2553 if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
2554 char extra_info_digest[HEX_DIGEST_LEN+1];
2555 base16_encode(extra_info_digest, sizeof(extra_info_digest),
2556 router->cache_info.extra_info_digest, DIGEST_LEN);
2557 if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
2558 char d256_64[BASE64_DIGEST256_LEN+1];
2559 digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
2560 tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
2561 extra_info_digest, d256_64);
2562 } else {
2563 tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
2564 extra_info_digest);
2568 if (router->ipv6_orport &&
2569 tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2570 char addr[TOR_ADDR_BUF_LEN];
2571 const char *a;
2572 a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2573 if (a) {
2574 tor_asprintf(&extra_or_address,
2575 "or-address %s:%d\n", a, router->ipv6_orport);
2576 log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2580 if (router->protocol_list) {
2581 tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
2582 } else {
2583 proto_line = tor_strdup("");
2586 address = tor_dup_ip(router->addr);
2587 chunks = smartlist_new();
2589 /* Generate the easy portion of the router descriptor. */
2590 smartlist_add_asprintf(chunks,
2591 "router %s %s %d 0 %d\n"
2592 "%s"
2593 "%s"
2594 "platform %s\n"
2595 "%s"
2596 "published %s\n"
2597 "fingerprint %s\n"
2598 "uptime %ld\n"
2599 "bandwidth %d %d %d\n"
2600 "%s%s"
2601 "onion-key\n%s"
2602 "signing-key\n%s"
2603 "%s%s"
2604 "%s%s%s",
2605 router->nickname,
2606 address,
2607 router->or_port,
2608 router_should_advertise_dirport(options, router->dir_port),
2609 ed_cert_line ? ed_cert_line : "",
2610 extra_or_address ? extra_or_address : "",
2611 router->platform,
2612 proto_line,
2613 published,
2614 fingerprint,
2615 get_uptime(),
2616 (int) router->bandwidthrate,
2617 (int) router->bandwidthburst,
2618 (int) router->bandwidthcapacity,
2619 extra_info_line ? extra_info_line : "",
2620 (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
2621 "caches-extra-info\n" : "",
2622 onion_pkey, identity_pkey,
2623 rsa_tap_cc_line ? rsa_tap_cc_line : "",
2624 ntor_cc_line ? ntor_cc_line : "",
2625 family_line,
2626 we_are_hibernating() ? "hibernating 1\n" : "",
2627 "hidden-service-dir\n");
2629 if (options->ContactInfo && strlen(options->ContactInfo)) {
2630 const char *ci = options->ContactInfo;
2631 if (strchr(ci, '\n') || strchr(ci, '\r'))
2632 ci = escaped(ci);
2633 smartlist_add_asprintf(chunks, "contact %s\n", ci);
2636 if (options->BridgeRelay) {
2637 const char *bd;
2638 if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
2639 bd = options->BridgeDistribution;
2640 } else {
2641 bd = "any";
2643 if (strchr(bd, '\n') || strchr(bd, '\r'))
2644 bd = escaped(bd);
2645 smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
2648 if (router->onion_curve25519_pkey) {
2649 char kbuf[128];
2650 base64_encode(kbuf, sizeof(kbuf),
2651 (const char *)router->onion_curve25519_pkey->public_key,
2652 CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
2653 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
2654 } else {
2655 /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
2656 log_err(LD_BUG, "A relay must have an ntor onion key");
2657 goto err;
2660 /* Write the exit policy to the end of 's'. */
2661 if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
2662 smartlist_add_strdup(chunks, "reject *:*\n");
2663 } else if (router->exit_policy) {
2664 char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
2666 if (!exit_policy)
2667 goto err;
2669 smartlist_add_asprintf(chunks, "%s\n", exit_policy);
2670 tor_free(exit_policy);
2673 if (router->ipv6_exit_policy) {
2674 char *p6 = write_short_policy(router->ipv6_exit_policy);
2675 if (p6 && strcmp(p6, "reject 1-65535")) {
2676 smartlist_add_asprintf(chunks,
2677 "ipv6-policy %s\n", p6);
2679 tor_free(p6);
2682 if (router_should_advertise_begindir(options,
2683 router->supports_tunnelled_dir_requests)) {
2684 smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
2687 /* Sign the descriptor with Ed25519 */
2688 if (emit_ed_sigs) {
2689 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
2690 crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
2691 ED_DESC_SIGNATURE_PREFIX,
2692 chunks, "", DIGEST_SHA256);
2693 ed25519_signature_t sig;
2694 char buf[ED25519_SIG_BASE64_LEN+1];
2695 if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
2696 signing_keypair) < 0)
2697 goto err;
2698 if (ed25519_signature_to_base64(buf, &sig) < 0)
2699 goto err;
2701 smartlist_add_asprintf(chunks, "%s\n", buf);
2704 /* Sign the descriptor with RSA */
2705 smartlist_add_strdup(chunks, "router-signature\n");
2707 crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
2710 char *sig;
2711 if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
2712 log_warn(LD_BUG, "Couldn't sign router descriptor");
2713 goto err;
2715 smartlist_add(chunks, sig);
2718 /* include a last '\n' */
2719 smartlist_add_strdup(chunks, "\n");
2721 output = smartlist_join_strings(chunks, "", 0, NULL);
2723 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2725 char *s_dup;
2726 const char *cp;
2727 routerinfo_t *ri_tmp;
2728 cp = s_dup = tor_strdup(output);
2729 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
2730 if (!ri_tmp) {
2731 log_err(LD_BUG,
2732 "We just generated a router descriptor we can't parse.");
2733 log_err(LD_BUG, "Descriptor was: <<%s>>", output);
2734 goto err;
2736 tor_free(s_dup);
2737 routerinfo_free(ri_tmp);
2739 #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
2741 goto done;
2743 err:
2744 tor_free(output); /* sets output to NULL */
2745 done:
2746 if (chunks) {
2747 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2748 smartlist_free(chunks);
2750 crypto_pk_free(rsa_pubkey);
2751 tor_free(address);
2752 tor_free(family_line);
2753 tor_free(onion_pkey);
2754 tor_free(identity_pkey);
2755 tor_free(extra_or_address);
2756 tor_free(ed_cert_line);
2757 tor_free(rsa_tap_cc_line);
2758 tor_free(ntor_cc_line);
2759 tor_free(extra_info_line);
2760 tor_free(proto_line);
2762 return output;
2766 * OR only: Given <b>router</b>, produce a string with its exit policy.
2767 * If <b>include_ipv4</b> is true, include IPv4 entries.
2768 * If <b>include_ipv6</b> is true, include IPv6 entries.
2770 char *
2771 router_dump_exit_policy_to_string(const routerinfo_t *router,
2772 int include_ipv4,
2773 int include_ipv6)
2775 if ((!router->exit_policy) || (router->policy_is_reject_star)) {
2776 return tor_strdup("reject *:*");
2779 return policy_dump_to_string(router->exit_policy,
2780 include_ipv4,
2781 include_ipv6);
2784 /** Load the contents of <b>filename</b>, find the last line starting with
2785 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2786 * the past or more than 1 hour in the future with respect to <b>now</b>,
2787 * and write the file contents starting with that line to *<b>out</b>.
2788 * Return 1 for success, 0 if the file does not exist or is empty, or -1
2789 * if the file does not contain a line matching these criteria or other
2790 * failure. */
2791 static int
2792 load_stats_file(const char *filename, const char *end_line, time_t now,
2793 char **out)
2795 int r = -1;
2796 char *fname = get_datadir_fname(filename);
2797 char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
2798 time_t written;
2799 switch (file_status(fname)) {
2800 case FN_FILE:
2801 /* X022 Find an alternative to reading the whole file to memory. */
2802 if ((contents = read_file_to_str(fname, 0, NULL))) {
2803 tmp = strstr(contents, end_line);
2804 /* Find last block starting with end_line */
2805 while (tmp) {
2806 start = tmp;
2807 tmp = strstr(tmp + 1, end_line);
2809 if (!start)
2810 goto notfound;
2811 if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
2812 goto notfound;
2813 strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
2814 if (parse_iso_time(timestr, &written) < 0)
2815 goto notfound;
2816 if (written < now - (25*60*60) || written > now + (1*60*60))
2817 goto notfound;
2818 *out = tor_strdup(start);
2819 r = 1;
2821 notfound:
2822 tor_free(contents);
2823 break;
2824 /* treat empty stats files as if the file doesn't exist */
2825 case FN_NOENT:
2826 case FN_EMPTY:
2827 r = 0;
2828 break;
2829 case FN_ERROR:
2830 case FN_DIR:
2831 default:
2832 break;
2834 tor_free(fname);
2835 return r;
2838 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2839 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2840 * success, negative on failure. */
2842 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
2843 crypto_pk_t *ident_key,
2844 const ed25519_keypair_t *signing_keypair)
2846 const or_options_t *options = get_options();
2847 char identity[HEX_DIGEST_LEN+1];
2848 char published[ISO_TIME_LEN+1];
2849 char digest[DIGEST_LEN];
2850 char *bandwidth_usage;
2851 int result;
2852 static int write_stats_to_extrainfo = 1;
2853 char sig[DIROBJ_MAX_SIG_LEN+1];
2854 char *s = NULL, *pre, *contents, *cp, *s_dup = NULL;
2855 time_t now = time(NULL);
2856 smartlist_t *chunks = smartlist_new();
2857 extrainfo_t *ei_tmp = NULL;
2858 const int emit_ed_sigs = signing_keypair &&
2859 extrainfo->cache_info.signing_key_cert;
2860 char *ed_cert_line = NULL;
2862 base16_encode(identity, sizeof(identity),
2863 extrainfo->cache_info.identity_digest, DIGEST_LEN);
2864 format_iso_time(published, extrainfo->cache_info.published_on);
2865 bandwidth_usage = rep_hist_get_bandwidth_lines();
2866 if (emit_ed_sigs) {
2867 if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
2868 !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
2869 &signing_keypair->pubkey)) {
2870 log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
2871 "mismatched ed25519 key chain %d",
2872 extrainfo->cache_info.signing_key_cert->signing_key_included);
2873 goto err;
2875 char ed_cert_base64[256];
2876 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2877 (const char*)extrainfo->cache_info.signing_key_cert->encoded,
2878 extrainfo->cache_info.signing_key_cert->encoded_len,
2879 BASE64_ENCODE_MULTILINE) < 0) {
2880 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2881 goto err;
2883 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2884 "-----BEGIN ED25519 CERT-----\n"
2885 "%s"
2886 "-----END ED25519 CERT-----\n", ed_cert_base64);
2887 } else {
2888 ed_cert_line = tor_strdup("");
2891 tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n%s",
2892 extrainfo->nickname, identity,
2893 ed_cert_line,
2894 published, bandwidth_usage);
2895 smartlist_add(chunks, pre);
2897 if (geoip_is_loaded(AF_INET))
2898 smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
2899 geoip_db_digest(AF_INET));
2900 if (geoip_is_loaded(AF_INET6))
2901 smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
2902 geoip_db_digest(AF_INET6));
2904 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
2905 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
2906 if (options->DirReqStatistics &&
2907 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
2908 "dirreq-stats-end", now, &contents) > 0) {
2909 smartlist_add(chunks, contents);
2911 if (options->HiddenServiceStatistics &&
2912 load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
2913 "hidserv-stats-end", now, &contents) > 0) {
2914 smartlist_add(chunks, contents);
2916 if (options->EntryStatistics &&
2917 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
2918 "entry-stats-end", now, &contents) > 0) {
2919 smartlist_add(chunks, contents);
2921 if (options->CellStatistics &&
2922 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
2923 "cell-stats-end", now, &contents) > 0) {
2924 smartlist_add(chunks, contents);
2926 if (options->ExitPortStatistics &&
2927 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
2928 "exit-stats-end", now, &contents) > 0) {
2929 smartlist_add(chunks, contents);
2931 if (options->ConnDirectionStatistics &&
2932 load_stats_file("stats"PATH_SEPARATOR"conn-stats",
2933 "conn-bi-direct", now, &contents) > 0) {
2934 smartlist_add(chunks, contents);
2938 if (options->PaddingStatistics) {
2939 contents = rep_hist_get_padding_count_lines();
2940 if (contents)
2941 smartlist_add(chunks, contents);
2944 /* Add information about the pluggable transports we support. */
2945 if (options->ServerTransportPlugin) {
2946 char *pluggable_transports = pt_get_extra_info_descriptor_string();
2947 if (pluggable_transports)
2948 smartlist_add(chunks, pluggable_transports);
2951 if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
2952 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
2953 if (bridge_stats) {
2954 smartlist_add_strdup(chunks, bridge_stats);
2958 if (emit_ed_sigs) {
2959 char sha256_digest[DIGEST256_LEN];
2960 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
2961 crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
2962 ED_DESC_SIGNATURE_PREFIX,
2963 chunks, "", DIGEST_SHA256);
2964 ed25519_signature_t ed_sig;
2965 char buf[ED25519_SIG_BASE64_LEN+1];
2966 if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
2967 signing_keypair) < 0)
2968 goto err;
2969 if (ed25519_signature_to_base64(buf, &ed_sig) < 0)
2970 goto err;
2972 smartlist_add_asprintf(chunks, "%s\n", buf);
2975 smartlist_add_strdup(chunks, "router-signature\n");
2976 s = smartlist_join_strings(chunks, "", 0, NULL);
2978 while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
2979 /* So long as there are at least two chunks (one for the initial
2980 * extra-info line and one for the router-signature), we can keep removing
2981 * things. */
2982 if (smartlist_len(chunks) > 2) {
2983 /* We remove the next-to-last element (remember, len-1 is the last
2984 element), since we need to keep the router-signature element. */
2985 int idx = smartlist_len(chunks) - 2;
2986 char *e = smartlist_get(chunks, idx);
2987 smartlist_del_keeporder(chunks, idx);
2988 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
2989 "with statistics that exceeds the 50 KB "
2990 "upload limit. Removing last added "
2991 "statistics.");
2992 tor_free(e);
2993 tor_free(s);
2994 s = smartlist_join_strings(chunks, "", 0, NULL);
2995 } else {
2996 log_warn(LD_BUG, "We just generated an extra-info descriptors that "
2997 "exceeds the 50 KB upload limit.");
2998 goto err;
3002 memset(sig, 0, sizeof(sig));
3003 if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
3004 router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
3005 ident_key) < 0) {
3006 log_warn(LD_BUG, "Could not append signature to extra-info "
3007 "descriptor.");
3008 goto err;
3010 smartlist_add_strdup(chunks, sig);
3011 tor_free(s);
3012 s = smartlist_join_strings(chunks, "", 0, NULL);
3014 cp = s_dup = tor_strdup(s);
3015 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
3016 if (!ei_tmp) {
3017 if (write_stats_to_extrainfo) {
3018 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3019 "with statistics that we can't parse. Not "
3020 "adding statistics to this or any future "
3021 "extra-info descriptors.");
3022 write_stats_to_extrainfo = 0;
3023 result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
3024 signing_keypair);
3025 goto done;
3026 } else {
3027 log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
3028 "can't parse.");
3029 goto err;
3033 *s_out = s;
3034 s = NULL; /* prevent free */
3035 result = 0;
3036 goto done;
3038 err:
3039 result = -1;
3041 done:
3042 tor_free(s);
3043 SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
3044 smartlist_free(chunks);
3045 tor_free(s_dup);
3046 tor_free(ed_cert_line);
3047 extrainfo_free(ei_tmp);
3048 tor_free(bandwidth_usage);
3050 return result;
3053 /** Forget that we have issued any router-related warnings, so that we'll
3054 * warn again if we see the same errors. */
3055 void
3056 router_reset_warnings(void)
3058 if (warned_nonexistent_family) {
3059 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3060 smartlist_clear(warned_nonexistent_family);
3064 /** Release all static resources held in router.c */
3065 void
3066 router_free_all(void)
3068 crypto_pk_free(onionkey);
3069 crypto_pk_free(lastonionkey);
3070 crypto_pk_free(server_identitykey);
3071 crypto_pk_free(client_identitykey);
3073 tor_mutex_free(key_lock);
3074 routerinfo_free(desc_routerinfo);
3075 extrainfo_free(desc_extrainfo);
3076 crypto_pk_free(authority_signing_key);
3077 authority_cert_free(authority_key_certificate);
3078 crypto_pk_free(legacy_signing_key);
3079 authority_cert_free(legacy_key_certificate);
3081 memwipe(&curve25519_onion_key, 0, sizeof(curve25519_onion_key));
3082 memwipe(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
3084 if (warned_nonexistent_family) {
3085 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3086 smartlist_free(warned_nonexistent_family);
3089 /* From the given RSA key object, convert it to ASN-1 encoded format and set
3090 * the newly allocated object in onion_pkey_out. The length of the key is set
3091 * in onion_pkey_len_out. */
3092 void
3093 router_set_rsa_onion_pkey(const crypto_pk_t *pk, char **onion_pkey_out,
3094 size_t *onion_pkey_len_out)
3096 int len;
3097 char buf[1024];
3099 tor_assert(pk);
3100 tor_assert(onion_pkey_out);
3101 tor_assert(onion_pkey_len_out);
3103 len = crypto_pk_asn1_encode(pk, buf, sizeof(buf));
3104 if (BUG(len < 0)) {
3105 goto done;
3108 *onion_pkey_out = tor_memdup(buf, len);
3109 *onion_pkey_len_out = len;
3111 done:
3112 return;
3115 /* From an ASN-1 encoded onion pkey, return a newly allocated RSA key object.
3116 * It is the caller responsability to free the returned object.
3118 * Return NULL if the pkey is NULL, malformed or if the length is 0. */
3119 crypto_pk_t *
3120 router_get_rsa_onion_pkey(const char *pkey, size_t pkey_len)
3122 if (!pkey || pkey_len == 0) {
3123 return NULL;
3125 return crypto_pk_asn1_decode(pkey, pkey_len);