Split the authority-cert and signature/hash code from routerparse
[tor.git] / src / feature / relay / router.c
blob4afcddc6751a632734af51caf18789d936f35ee3
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/dirparse/authcert_parse.h"
25 #include "feature/dirparse/routerparse.h"
26 #include "feature/dirparse/signing.h"
27 #include "feature/hibernate/hibernate.h"
28 #include "feature/keymgt/loadkey.h"
29 #include "feature/nodelist/authcert.h"
30 #include "feature/nodelist/dirlist.h"
31 #include "feature/nodelist/networkstatus.h"
32 #include "feature/nodelist/nickname.h"
33 #include "feature/nodelist/nodelist.h"
34 #include "feature/nodelist/routerlist.h"
35 #include "feature/nodelist/torcert.h"
36 #include "feature/relay/dns.h"
37 #include "feature/relay/router.h"
38 #include "feature/relay/routerkeys.h"
39 #include "feature/relay/routermode.h"
40 #include "feature/relay/selftest.h"
41 #include "lib/geoip/geoip.h"
42 #include "feature/stats/geoip_stats.h"
43 #include "feature/stats/rephist.h"
44 #include "lib/crypt_ops/crypto_ed25519.h"
45 #include "lib/crypt_ops/crypto_format.h"
46 #include "lib/crypt_ops/crypto_init.h"
47 #include "lib/crypt_ops/crypto_rand.h"
48 #include "lib/crypt_ops/crypto_util.h"
49 #include "lib/encoding/confline.h"
50 #include "lib/osinfo/uname.h"
51 #include "lib/tls/tortls.h"
53 #include "feature/dirauth/authmode.h"
55 #include "app/config/or_state_st.h"
56 #include "core/or/port_cfg_st.h"
57 #include "feature/dirclient/dir_server_st.h"
58 #include "feature/dircommon/dir_connection_st.h"
59 #include "feature/nodelist/authority_cert_st.h"
60 #include "feature/nodelist/extrainfo_st.h"
61 #include "feature/nodelist/node_st.h"
62 #include "feature/nodelist/routerinfo_st.h"
63 #include "feature/nodelist/routerstatus_st.h"
65 /**
66 * \file router.c
67 * \brief Miscellaneous relay functionality, including RSA key maintenance,
68 * generating and uploading server descriptors, picking an address to
69 * advertise, and so on.
71 * This module handles the job of deciding whether we are a Tor relay, and if
72 * so what kind. (Mostly through functions like server_mode() that inspect an
73 * or_options_t, but in some cases based on our own capabilities, such as when
74 * we are deciding whether to be a directory cache in
75 * router_has_bandwidth_to_be_dirserver().)
77 * Also in this module are the functions to generate our own routerinfo_t and
78 * extrainfo_t, and to encode those to signed strings for upload to the
79 * directory authorities.
81 * This module also handles key maintenance for RSA and Curve25519-ntor keys,
82 * and for our TLS context. (These functions should eventually move to
83 * routerkeys.c along with the code that handles Ed25519 keys now.)
84 **/
86 /************************************************************/
88 /*****
89 * Key management: ORs only.
90 *****/
92 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
94 static tor_mutex_t *key_lock=NULL;
95 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
96 /** Current private onionskin decryption key: used to decode CREATE cells. */
97 static crypto_pk_t *onionkey=NULL;
98 /** Previous private onionskin decryption key: used to decode CREATE cells
99 * generated by clients that have an older version of our descriptor. */
100 static crypto_pk_t *lastonionkey=NULL;
101 /** Current private ntor secret key: used to perform the ntor handshake. */
102 static curve25519_keypair_t curve25519_onion_key;
103 /** Previous private ntor secret key: used to perform the ntor handshake
104 * with clients that have an older version of our descriptor. */
105 static curve25519_keypair_t last_curve25519_onion_key;
106 /** Private server "identity key": used to sign directory info and TLS
107 * certificates. Never changes. */
108 static crypto_pk_t *server_identitykey=NULL;
109 /** Digest of server_identitykey. */
110 static char server_identitykey_digest[DIGEST_LEN];
111 /** Private client "identity key": used to sign bridges' and clients'
112 * outbound TLS certificates. Regenerated on startup and on IP address
113 * change. */
114 static crypto_pk_t *client_identitykey=NULL;
115 /** Signing key used for v3 directory material; only set for authorities. */
116 static crypto_pk_t *authority_signing_key = NULL;
117 /** Key certificate to authenticate v3 directory material; only set for
118 * authorities. */
119 static authority_cert_t *authority_key_certificate = NULL;
121 /** For emergency V3 authority key migration: An extra signing key that we use
122 * with our old (obsolete) identity key for a while. */
123 static crypto_pk_t *legacy_signing_key = NULL;
124 /** For emergency V3 authority key migration: An extra certificate to
125 * authenticate legacy_signing_key with our obsolete identity key.*/
126 static authority_cert_t *legacy_key_certificate = NULL;
128 /* (Note that v3 authorities also have a separate "authority identity key",
129 * but this key is never actually loaded by the Tor process. Instead, it's
130 * used by tor-gencert to sign new signing keys and make new key
131 * certificates. */
133 /** Return a readonly string with human readable description
134 * of <b>err</b>.
136 const char *
137 routerinfo_err_to_string(int err)
139 switch (err) {
140 case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
141 return "No known exit address yet";
142 case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
143 return "Cannot parse descriptor";
144 case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
145 return "Not running in server mode";
146 case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
147 return "Key digest failed";
148 case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
149 return "Cannot generate descriptor";
150 case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
151 return "Descriptor still rebuilding - not ready yet";
154 log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
155 tor_assert_unreached();
157 return "Unknown error";
160 /** Return true if we expect given error to be transient.
161 * Return false otherwise.
164 routerinfo_err_is_transient(int err)
167 * For simplicity, we consider all errors other than
168 * "not a server" transient - see discussion on
169 * https://trac.torproject.org/projects/tor/ticket/27034
171 return err != TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
174 /** Replace the current onion key with <b>k</b>. Does not affect
175 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
177 static void
178 set_onion_key(crypto_pk_t *k)
180 if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
181 /* k is already our onion key; free it and return */
182 crypto_pk_free(k);
183 return;
185 tor_mutex_acquire(key_lock);
186 crypto_pk_free(onionkey);
187 onionkey = k;
188 tor_mutex_release(key_lock);
189 mark_my_descriptor_dirty("set onion key");
192 /** Return the current onion key. Requires that the onion key has been
193 * loaded or generated. */
194 crypto_pk_t *
195 get_onion_key(void)
197 tor_assert(onionkey);
198 return onionkey;
201 /** Store a full copy of the current onion key into *<b>key</b>, and a full
202 * copy of the most recent onion key into *<b>last</b>. Store NULL into
203 * a pointer if the corresponding key does not exist.
205 void
206 dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
208 tor_assert(key);
209 tor_assert(last);
210 tor_mutex_acquire(key_lock);
211 if (onionkey)
212 *key = crypto_pk_copy_full(onionkey);
213 else
214 *key = NULL;
215 if (lastonionkey)
216 *last = crypto_pk_copy_full(lastonionkey);
217 else
218 *last = NULL;
219 tor_mutex_release(key_lock);
222 /** Expire our old set of onion keys. This is done by setting
223 * last_curve25519_onion_key and lastonionkey to all zero's and NULL
224 * respectively.
226 * This function does not perform any grace period checks for the old onion
227 * keys.
229 void
230 expire_old_onion_keys(void)
232 char *fname = NULL;
234 tor_mutex_acquire(key_lock);
236 /* Free lastonionkey and set it to NULL. */
237 if (lastonionkey) {
238 crypto_pk_free(lastonionkey);
239 lastonionkey = NULL;
242 /* We zero out the keypair. See the tor_mem_is_zero() check made in
243 * construct_ntor_key_map() below. */
244 memset(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
246 tor_mutex_release(key_lock);
248 fname = get_keydir_fname("secret_onion_key.old");
249 if (file_status(fname) == FN_FILE) {
250 if (tor_unlink(fname) != 0) {
251 log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
252 fname, strerror(errno));
255 tor_free(fname);
257 fname = get_keydir_fname("secret_onion_key_ntor.old");
258 if (file_status(fname) == FN_FILE) {
259 if (tor_unlink(fname) != 0) {
260 log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
261 fname, strerror(errno));
264 tor_free(fname);
267 /** Return the current secret onion key for the ntor handshake. Must only
268 * be called from the main thread. */
269 static const curve25519_keypair_t *
270 get_current_curve25519_keypair(void)
272 return &curve25519_onion_key;
274 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
275 * handshake. Must only be called from the main thread. */
276 di_digest256_map_t *
277 construct_ntor_key_map(void)
279 di_digest256_map_t *m = NULL;
281 if (!tor_mem_is_zero((const char*)
282 curve25519_onion_key.pubkey.public_key,
283 CURVE25519_PUBKEY_LEN)) {
284 dimap_add_entry(&m,
285 curve25519_onion_key.pubkey.public_key,
286 tor_memdup(&curve25519_onion_key,
287 sizeof(curve25519_keypair_t)));
289 if (!tor_mem_is_zero((const char*)
290 last_curve25519_onion_key.pubkey.public_key,
291 CURVE25519_PUBKEY_LEN)) {
292 dimap_add_entry(&m,
293 last_curve25519_onion_key.pubkey.public_key,
294 tor_memdup(&last_curve25519_onion_key,
295 sizeof(curve25519_keypair_t)));
298 return m;
300 /** Helper used to deallocate a di_digest256_map_t returned by
301 * construct_ntor_key_map. */
302 static void
303 ntor_key_map_free_helper(void *arg)
305 curve25519_keypair_t *k = arg;
306 memwipe(k, 0, sizeof(*k));
307 tor_free(k);
309 /** Release all storage from a keymap returned by construct_ntor_key_map. */
310 void
311 ntor_key_map_free_(di_digest256_map_t *map)
313 if (!map)
314 return;
315 dimap_free(map, ntor_key_map_free_helper);
318 /** Return the time when the onion key was last set. This is either the time
319 * when the process launched, or the time of the most recent key rotation since
320 * the process launched.
322 time_t
323 get_onion_key_set_at(void)
325 return onionkey_set_at;
328 /** Set the current server identity key to <b>k</b>.
330 void
331 set_server_identity_key(crypto_pk_t *k)
333 crypto_pk_free(server_identitykey);
334 server_identitykey = k;
335 if (crypto_pk_get_digest(server_identitykey,
336 server_identitykey_digest) < 0) {
337 log_err(LD_BUG, "Couldn't compute our own identity key digest.");
338 tor_assert(0);
342 /** Make sure that we have set up our identity keys to match or not match as
343 * appropriate, and die with an assertion if we have not. */
344 static void
345 assert_identity_keys_ok(void)
347 if (1)
348 return;
349 tor_assert(client_identitykey);
350 if (public_server_mode(get_options())) {
351 /* assert that we have set the client and server keys to be equal */
352 tor_assert(server_identitykey);
353 tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
354 } else {
355 /* assert that we have set the client and server keys to be unequal */
356 if (server_identitykey)
357 tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
361 /** Returns the current server identity key; requires that the key has
362 * been set, and that we are running as a Tor server.
364 crypto_pk_t *
365 get_server_identity_key(void)
367 tor_assert(server_identitykey);
368 tor_assert(server_mode(get_options()));
369 assert_identity_keys_ok();
370 return server_identitykey;
373 /** Return true iff we are a server and the server identity key
374 * has been set. */
376 server_identity_key_is_set(void)
378 return server_mode(get_options()) && server_identitykey != NULL;
381 /** Set the current client identity key to <b>k</b>.
383 void
384 set_client_identity_key(crypto_pk_t *k)
386 crypto_pk_free(client_identitykey);
387 client_identitykey = k;
390 /** Returns the current client identity key for use on outgoing TLS
391 * connections; requires that the key has been set.
393 crypto_pk_t *
394 get_tlsclient_identity_key(void)
396 tor_assert(client_identitykey);
397 assert_identity_keys_ok();
398 return client_identitykey;
401 /** Return true iff the client identity key has been set. */
403 client_identity_key_is_set(void)
405 return client_identitykey != NULL;
408 /** Return the key certificate for this v3 (voting) authority, or NULL
409 * if we have no such certificate. */
410 MOCK_IMPL(authority_cert_t *,
411 get_my_v3_authority_cert, (void))
413 return authority_key_certificate;
416 /** Return the v3 signing key for this v3 (voting) authority, or NULL
417 * if we have no such key. */
418 crypto_pk_t *
419 get_my_v3_authority_signing_key(void)
421 return authority_signing_key;
424 /** If we're an authority, and we're using a legacy authority identity key for
425 * emergency migration purposes, return the certificate associated with that
426 * key. */
427 authority_cert_t *
428 get_my_v3_legacy_cert(void)
430 return legacy_key_certificate;
433 /** If we're an authority, and we're using a legacy authority identity key for
434 * emergency migration purposes, return that key. */
435 crypto_pk_t *
436 get_my_v3_legacy_signing_key(void)
438 return legacy_signing_key;
441 /** Replace the previous onion key with the current onion key, and generate
442 * a new previous onion key. Immediately after calling this function,
443 * the OR should:
444 * - schedule all previous cpuworkers to shut down _after_ processing
445 * pending work. (This will cause fresh cpuworkers to be generated.)
446 * - generate and upload a fresh routerinfo.
448 void
449 rotate_onion_key(void)
451 char *fname, *fname_prev;
452 crypto_pk_t *prkey = NULL;
453 or_state_t *state = get_or_state();
454 curve25519_keypair_t new_curve25519_keypair;
455 time_t now;
456 fname = get_keydir_fname("secret_onion_key");
457 fname_prev = get_keydir_fname("secret_onion_key.old");
458 /* There isn't much point replacing an old key with an empty file */
459 if (file_status(fname) == FN_FILE) {
460 if (replace_file(fname, fname_prev))
461 goto error;
463 if (!(prkey = crypto_pk_new())) {
464 log_err(LD_GENERAL,"Error constructing rotated onion key");
465 goto error;
467 if (crypto_pk_generate_key(prkey)) {
468 log_err(LD_BUG,"Error generating onion key");
469 goto error;
471 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
472 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
473 goto error;
475 tor_free(fname);
476 tor_free(fname_prev);
477 fname = get_keydir_fname("secret_onion_key_ntor");
478 fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
479 if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
480 goto error;
481 /* There isn't much point replacing an old key with an empty file */
482 if (file_status(fname) == FN_FILE) {
483 if (replace_file(fname, fname_prev))
484 goto error;
486 if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
487 "onion") < 0) {
488 log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
489 goto error;
491 log_info(LD_GENERAL, "Rotating onion key");
492 tor_mutex_acquire(key_lock);
493 crypto_pk_free(lastonionkey);
494 lastonionkey = onionkey;
495 onionkey = prkey;
496 memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
497 sizeof(curve25519_keypair_t));
498 memcpy(&curve25519_onion_key, &new_curve25519_keypair,
499 sizeof(curve25519_keypair_t));
500 now = time(NULL);
501 state->LastRotatedOnionKey = onionkey_set_at = now;
502 tor_mutex_release(key_lock);
503 mark_my_descriptor_dirty("rotated onion key");
504 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
505 goto done;
506 error:
507 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
508 if (prkey)
509 crypto_pk_free(prkey);
510 done:
511 memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
512 tor_free(fname);
513 tor_free(fname_prev);
516 /** Log greeting message that points to new relay lifecycle document the
517 * first time this function has been called.
519 static void
520 log_new_relay_greeting(void)
522 static int already_logged = 0;
524 if (already_logged)
525 return;
527 tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
528 "Thanks for helping the Tor network! If you wish to know "
529 "what will happen in the upcoming weeks regarding its usage, "
530 "have a look at https://blog.torproject.org/blog/lifecycle-of"
531 "-a-new-relay");
533 already_logged = 1;
536 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
537 * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
538 * is true, create a new keypair and write it into the file. If there are
539 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
540 * in their ASCII wrapper. */
541 static int
542 init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
543 const char *fname,
544 int generate,
545 int severity,
546 const char *tag)
548 switch (file_status(fname)) {
549 case FN_DIR:
550 case FN_ERROR:
551 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
552 goto error;
553 /* treat empty key files as if the file doesn't exist, and, if generate
554 * is set, replace the empty file in curve25519_keypair_write_to_file() */
555 case FN_NOENT:
556 case FN_EMPTY:
557 if (generate) {
558 if (!have_lockfile()) {
559 if (try_locking(get_options(), 0)<0) {
560 /* Make sure that --list-fingerprint only creates new keys
561 * if there is no possibility for a deadlock. */
562 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
563 "Not writing any new keys.", fname);
564 /*XXXX The 'other process' might make a key in a second or two;
565 * maybe we should wait for it. */
566 goto error;
569 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
570 fname);
571 if (curve25519_keypair_generate(keys_out, 1) < 0)
572 goto error;
573 if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
574 tor_log(severity, LD_FS,
575 "Couldn't write generated key to \"%s\".", fname);
576 memwipe(keys_out, 0, sizeof(*keys_out));
577 goto error;
579 } else {
580 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
582 return 0;
583 case FN_FILE:
585 char *tag_in=NULL;
586 if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
587 tor_log(severity, LD_GENERAL,"Error loading private key.");
588 tor_free(tag_in);
589 goto error;
591 if (!tag_in || strcmp(tag_in, tag)) {
592 tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
593 escaped(tag_in));
594 tor_free(tag_in);
595 goto error;
597 tor_free(tag_in);
598 return 0;
600 default:
601 tor_assert(0);
604 error:
605 return -1;
608 /** Try to load the vote-signing private key and certificate for being a v3
609 * directory authority, and make sure they match. If <b>legacy</b>, load a
610 * legacy key/cert set for emergency key migration; otherwise load the regular
611 * key/cert set. On success, store them into *<b>key_out</b> and
612 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
613 static int
614 load_authority_keyset(int legacy, crypto_pk_t **key_out,
615 authority_cert_t **cert_out)
617 int r = -1;
618 char *fname = NULL, *cert = NULL;
619 const char *eos = NULL;
620 crypto_pk_t *signing_key = NULL;
621 authority_cert_t *parsed = NULL;
623 fname = get_keydir_fname(
624 legacy ? "legacy_signing_key" : "authority_signing_key");
625 signing_key = init_key_from_file(fname, 0, LOG_ERR, NULL);
626 if (!signing_key) {
627 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
628 goto done;
630 tor_free(fname);
631 fname = get_keydir_fname(
632 legacy ? "legacy_certificate" : "authority_certificate");
633 cert = read_file_to_str(fname, 0, NULL);
634 if (!cert) {
635 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
636 fname);
637 goto done;
639 parsed = authority_cert_parse_from_string(cert, &eos);
640 if (!parsed) {
641 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
642 goto done;
644 if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
645 log_warn(LD_DIR, "Stored signing key does not match signing key in "
646 "certificate");
647 goto done;
650 crypto_pk_free(*key_out);
651 authority_cert_free(*cert_out);
653 *key_out = signing_key;
654 *cert_out = parsed;
655 r = 0;
656 signing_key = NULL;
657 parsed = NULL;
659 done:
660 tor_free(fname);
661 tor_free(cert);
662 crypto_pk_free(signing_key);
663 authority_cert_free(parsed);
664 return r;
667 /** Load the v3 (voting) authority signing key and certificate, if they are
668 * present. Return -1 if anything is missing, mismatched, or unloadable;
669 * return 0 on success. */
670 static int
671 init_v3_authority_keys(void)
673 if (load_authority_keyset(0, &authority_signing_key,
674 &authority_key_certificate)<0)
675 return -1;
677 if (get_options()->V3AuthUseLegacyKey &&
678 load_authority_keyset(1, &legacy_signing_key,
679 &legacy_key_certificate)<0)
680 return -1;
682 return 0;
685 /** If we're a v3 authority, check whether we have a certificate that's
686 * likely to expire soon. Warn if we do, but not too often. */
687 void
688 v3_authority_check_key_expiry(void)
690 time_t now, expires;
691 static time_t last_warned = 0;
692 int badness, time_left, warn_interval;
693 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
694 return;
696 now = time(NULL);
697 expires = authority_key_certificate->expires;
698 time_left = (int)( expires - now );
699 if (time_left <= 0) {
700 badness = LOG_ERR;
701 warn_interval = 60*60;
702 } else if (time_left <= 24*60*60) {
703 badness = LOG_WARN;
704 warn_interval = 60*60;
705 } else if (time_left <= 24*60*60*7) {
706 badness = LOG_WARN;
707 warn_interval = 24*60*60;
708 } else if (time_left <= 24*60*60*30) {
709 badness = LOG_WARN;
710 warn_interval = 24*60*60*5;
711 } else {
712 return;
715 if (last_warned + warn_interval > now)
716 return;
718 if (time_left <= 0) {
719 tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
720 " Generate a new one NOW.");
721 } else if (time_left <= 24*60*60) {
722 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
723 "hours; Generate a new one NOW.", time_left/(60*60));
724 } else {
725 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
726 "days; Generate a new one soon.", time_left/(24*60*60));
728 last_warned = now;
731 /** Get the lifetime of an onion key in days. This value is defined by the
732 * network consesus parameter "onion-key-rotation-days". Always returns a value
733 * between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
734 * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
736 static int
737 get_onion_key_rotation_days_(void)
739 return networkstatus_get_param(NULL,
740 "onion-key-rotation-days",
741 DEFAULT_ONION_KEY_LIFETIME_DAYS,
742 MIN_ONION_KEY_LIFETIME_DAYS,
743 MAX_ONION_KEY_LIFETIME_DAYS);
746 /** Get the current lifetime of an onion key in seconds. This value is defined
747 * by the network consesus parameter "onion-key-rotation-days", but the value
748 * is converted to seconds.
751 get_onion_key_lifetime(void)
753 return get_onion_key_rotation_days_()*24*60*60;
756 /** Get the grace period of an onion key in seconds. This value is defined by
757 * the network consesus parameter "onion-key-grace-period-days", but the value
758 * is converted to seconds.
761 get_onion_key_grace_period(void)
763 int grace_period;
764 grace_period = networkstatus_get_param(NULL,
765 "onion-key-grace-period-days",
766 DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS,
767 MIN_ONION_KEY_GRACE_PERIOD_DAYS,
768 get_onion_key_rotation_days_());
769 return grace_period*24*60*60;
772 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
773 * on success, and -1 on failure. */
775 router_initialize_tls_context(void)
777 unsigned int flags = 0;
778 const or_options_t *options = get_options();
779 int lifetime = options->SSLKeyLifetime;
780 if (public_server_mode(options))
781 flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
782 if (!lifetime) { /* we should guess a good ssl cert lifetime */
784 /* choose between 5 and 365 days, and round to the day */
785 unsigned int five_days = 5*24*3600;
786 unsigned int one_year = 365*24*3600;
787 lifetime = crypto_rand_int_range(five_days, one_year);
788 lifetime -= lifetime % (24*3600);
790 if (crypto_rand_int(2)) {
791 /* Half the time we expire at midnight, and half the time we expire
792 * one second before midnight. (Some CAs wobble their expiry times a
793 * bit in practice, perhaps to reduce collision attacks; see ticket
794 * 8443 for details about observed certs in the wild.) */
795 lifetime--;
799 /* It's ok to pass lifetime in as an unsigned int, since
800 * config_parse_interval() checked it. */
801 return tor_tls_context_init(flags,
802 get_tlsclient_identity_key(),
803 server_mode(options) ?
804 get_server_identity_key() : NULL,
805 (unsigned int)lifetime);
808 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
809 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
810 * -1 if Tor should die,
812 STATIC int
813 router_write_fingerprint(int hashed)
815 char *keydir = NULL, *cp = NULL;
816 const char *fname = hashed ? "hashed-fingerprint" :
817 "fingerprint";
818 char fingerprint[FINGERPRINT_LEN+1];
819 const or_options_t *options = get_options();
820 char *fingerprint_line = NULL;
821 int result = -1;
823 keydir = get_datadir_fname(fname);
824 log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
825 hashed ? "hashed " : "", keydir);
826 if (!hashed) {
827 if (crypto_pk_get_fingerprint(get_server_identity_key(),
828 fingerprint, 0) < 0) {
829 log_err(LD_GENERAL,"Error computing fingerprint");
830 goto done;
832 } else {
833 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
834 fingerprint) < 0) {
835 log_err(LD_GENERAL,"Error computing hashed fingerprint");
836 goto done;
840 tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
842 /* Check whether we need to write the (hashed-)fingerprint file. */
844 cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
845 if (!cp || strcmp(cp, fingerprint_line)) {
846 if (write_str_to_file(keydir, fingerprint_line, 0)) {
847 log_err(LD_FS, "Error writing %sfingerprint line to file",
848 hashed ? "hashed " : "");
849 goto done;
853 log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
854 hashed ? "bridge's hashed" : "server's", options->Nickname,
855 fingerprint);
857 result = 0;
858 done:
859 tor_free(cp);
860 tor_free(keydir);
861 tor_free(fingerprint_line);
862 return result;
865 static int
866 init_keys_common(void)
868 if (!key_lock)
869 key_lock = tor_mutex_new();
871 /* There are a couple of paths that put us here before we've asked
872 * openssl to initialize itself. */
873 if (crypto_global_init(get_options()->HardwareAccel,
874 get_options()->AccelName,
875 get_options()->AccelDir)) {
876 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
877 return -1;
880 return 0;
884 init_keys_client(void)
886 crypto_pk_t *prkey;
887 if (init_keys_common() < 0)
888 return -1;
890 if (!(prkey = crypto_pk_new()))
891 return -1;
892 if (crypto_pk_generate_key(prkey)) {
893 crypto_pk_free(prkey);
894 return -1;
896 set_client_identity_key(prkey);
897 /* Create a TLS context. */
898 if (router_initialize_tls_context() < 0) {
899 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
900 return -1;
902 return 0;
905 /** Initialize all OR private keys, and the TLS context, as necessary.
906 * On OPs, this only initializes the tls context. Return 0 on success,
907 * or -1 if Tor should die.
910 init_keys(void)
912 char *keydir;
913 const char *mydesc;
914 crypto_pk_t *prkey;
915 char digest[DIGEST_LEN];
916 char v3_digest[DIGEST_LEN];
917 const or_options_t *options = get_options();
918 dirinfo_type_t type;
919 time_t now = time(NULL);
920 dir_server_t *ds;
921 int v3_digest_set = 0;
922 authority_cert_t *cert = NULL;
924 /* OP's don't need persistent keys; just make up an identity and
925 * initialize the TLS context. */
926 if (!server_mode(options)) {
927 return init_keys_client();
929 if (init_keys_common() < 0)
930 return -1;
932 if (create_keys_directory(options) < 0)
933 return -1;
935 /* 1a. Read v3 directory authority key/cert information. */
936 memset(v3_digest, 0, sizeof(v3_digest));
937 if (authdir_mode_v3(options)) {
938 if (init_v3_authority_keys()<0) {
939 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
940 "were unable to load our v3 authority keys and certificate! "
941 "Use tor-gencert to generate them. Dying.");
942 return -1;
944 cert = get_my_v3_authority_cert();
945 if (cert) {
946 if (crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
947 v3_digest) < 0) {
948 log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
949 "digest.");
950 return -1;
952 v3_digest_set = 1;
956 /* 1b. Read identity key. Make it if none is found. */
957 keydir = get_keydir_fname("secret_id_key");
958 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
959 bool created = false;
960 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
961 tor_free(keydir);
962 if (!prkey) return -1;
963 if (created)
964 log_new_relay_greeting();
965 set_server_identity_key(prkey);
967 /* 1c. If we are configured as a bridge, generate a client key;
968 * otherwise, set the server identity key as our client identity
969 * key. */
970 if (public_server_mode(options)) {
971 set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
972 } else {
973 if (!(prkey = crypto_pk_new()))
974 return -1;
975 if (crypto_pk_generate_key(prkey)) {
976 crypto_pk_free(prkey);
977 return -1;
979 set_client_identity_key(prkey);
982 /* 1d. Load all ed25519 keys */
983 const int new_signing_key = load_ed_keys(options,now);
984 if (new_signing_key < 0)
985 return -1;
987 /* 2. Read onion key. Make it if none is found. */
988 keydir = get_keydir_fname("secret_onion_key");
989 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
990 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
991 if (created)
992 log_new_relay_greeting();
993 tor_free(keydir);
994 if (!prkey) return -1;
995 set_onion_key(prkey);
996 if (options->command == CMD_RUN_TOR) {
997 /* only mess with the state file if we're actually running Tor */
998 or_state_t *state = get_or_state();
999 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
1000 /* We allow for some parsing slop, but we don't want to risk accepting
1001 * values in the distant future. If we did, we might never rotate the
1002 * onion key. */
1003 onionkey_set_at = state->LastRotatedOnionKey;
1004 } else {
1005 /* We have no LastRotatedOnionKey set; either we just created the key
1006 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
1007 * start the clock ticking now so that we will eventually rotate it even
1008 * if we don't stay up for the full lifetime of an onion key. */
1009 state->LastRotatedOnionKey = onionkey_set_at = now;
1010 or_state_mark_dirty(state, options->AvoidDiskWrites ?
1011 time(NULL)+3600 : 0);
1015 keydir = get_keydir_fname("secret_onion_key.old");
1016 if (!lastonionkey && file_status(keydir) == FN_FILE) {
1017 /* Load keys from non-empty files only.
1018 * Missing old keys won't be replaced with freshly generated keys. */
1019 prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
1020 if (prkey)
1021 lastonionkey = prkey;
1023 tor_free(keydir);
1026 /* 2b. Load curve25519 onion keys. */
1027 int r;
1028 keydir = get_keydir_fname("secret_onion_key_ntor");
1029 r = init_curve25519_keypair_from_file(&curve25519_onion_key,
1030 keydir, 1, LOG_ERR, "onion");
1031 tor_free(keydir);
1032 if (r<0)
1033 return -1;
1035 keydir = get_keydir_fname("secret_onion_key_ntor.old");
1036 if (tor_mem_is_zero((const char *)
1037 last_curve25519_onion_key.pubkey.public_key,
1038 CURVE25519_PUBKEY_LEN) &&
1039 file_status(keydir) == FN_FILE) {
1040 /* Load keys from non-empty files only.
1041 * Missing old keys won't be replaced with freshly generated keys. */
1042 init_curve25519_keypair_from_file(&last_curve25519_onion_key,
1043 keydir, 0, LOG_ERR, "onion");
1045 tor_free(keydir);
1048 /* 3. Initialize link key and TLS context. */
1049 if (router_initialize_tls_context() < 0) {
1050 log_err(LD_GENERAL,"Error initializing TLS context");
1051 return -1;
1054 /* 3b. Get an ed25519 link certificate. Note that we need to do this
1055 * after we set up the TLS context */
1056 if (generate_ed_link_cert(options, now, new_signing_key > 0) < 0) {
1057 log_err(LD_GENERAL,"Couldn't make link cert");
1058 return -1;
1061 /* 4. Build our router descriptor. */
1062 /* Must be called after keys are initialized. */
1063 mydesc = router_get_my_descriptor();
1064 if (authdir_mode_v3(options)) {
1065 const char *m = NULL;
1066 routerinfo_t *ri;
1067 /* We need to add our own fingerprint so it gets recognized. */
1068 if (dirserv_add_own_fingerprint(get_server_identity_key())) {
1069 log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
1070 return -1;
1072 if (mydesc) {
1073 was_router_added_t added;
1074 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
1075 if (!ri) {
1076 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
1077 return -1;
1079 added = dirserv_add_descriptor(ri, &m, "self");
1080 if (!WRA_WAS_ADDED(added)) {
1081 if (!WRA_WAS_OUTDATED(added)) {
1082 log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
1083 m?m:"<unknown error>");
1084 return -1;
1085 } else {
1086 /* If the descriptor was outdated, that's ok. This can happen
1087 * when some config options are toggled that affect workers, but
1088 * we don't really need new keys yet so the descriptor doesn't
1089 * change and the old one is still fresh. */
1090 log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
1091 "after key init: %s This is usually not a problem.",
1092 m?m:"<unknown error>");
1098 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
1099 if (router_write_fingerprint(0)) {
1100 log_err(LD_FS, "Error writing fingerprint to file");
1101 return -1;
1103 if (!public_server_mode(options) && router_write_fingerprint(1)) {
1104 log_err(LD_FS, "Error writing hashed fingerprint to file");
1105 return -1;
1108 if (!authdir_mode(options))
1109 return 0;
1110 /* 6. [authdirserver only] load approved-routers file */
1111 if (dirserv_load_fingerprint_file() < 0) {
1112 log_err(LD_GENERAL,"Error loading fingerprints");
1113 return -1;
1115 /* 6b. [authdirserver only] add own key to approved directories. */
1116 crypto_pk_get_digest(get_server_identity_key(), digest);
1117 type = ((options->V3AuthoritativeDir ?
1118 (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
1119 (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
1121 ds = router_get_trusteddirserver_by_digest(digest);
1122 if (!ds) {
1123 ds = trusted_dir_server_new(options->Nickname, NULL,
1124 router_get_advertised_dir_port(options, 0),
1125 router_get_advertised_or_port(options),
1126 NULL,
1127 digest,
1128 v3_digest,
1129 type, 0.0);
1130 if (!ds) {
1131 log_err(LD_GENERAL,"We want to be a directory authority, but we "
1132 "couldn't add ourselves to the authority list. Failing.");
1133 return -1;
1135 dir_server_add(ds);
1137 if (ds->type != type) {
1138 log_warn(LD_DIR, "Configured authority type does not match authority "
1139 "type in DirAuthority list. Adjusting. (%d v %d)",
1140 type, ds->type);
1141 ds->type = type;
1143 if (v3_digest_set && (ds->type & V3_DIRINFO) &&
1144 tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
1145 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
1146 "DirAuthority line. Adjusting.");
1147 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
1150 if (cert) { /* add my own cert to the list of known certs */
1151 log_info(LD_DIR, "adding my own v3 cert");
1152 if (trusted_dirs_load_certs_from_string(
1153 cert->cache_info.signed_descriptor_body,
1154 TRUSTED_DIRS_CERTS_SRC_SELF, 0,
1155 NULL)<0) {
1156 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1157 return -1;
1161 return 0; /* success */
1164 /** The lower threshold of remaining bandwidth required to advertise (or
1165 * automatically provide) directory services */
1166 /* XXX Should this be increased? */
1167 #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
1169 /** Return true iff we have enough configured bandwidth to advertise or
1170 * automatically provide directory services from cache directory
1171 * information. */
1173 router_has_bandwidth_to_be_dirserver(const or_options_t *options)
1175 if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
1176 return 0;
1178 if (options->RelayBandwidthRate > 0 &&
1179 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRSERVER) {
1180 return 0;
1182 return 1;
1185 /** Helper: Return 1 if we have sufficient resources for serving directory
1186 * requests, return 0 otherwise.
1187 * dir_port is either 0 or the configured DirPort number.
1188 * If AccountingMax is set less than our advertised bandwidth, then don't
1189 * serve requests. Likewise, if our advertised bandwidth is less than
1190 * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
1192 static int
1193 router_should_be_dirserver(const or_options_t *options, int dir_port)
1195 static int advertising=1; /* start out assuming we will advertise */
1196 int new_choice=1;
1197 const char *reason = NULL;
1199 if (accounting_is_enabled(options) &&
1200 get_options()->AccountingRule != ACCT_IN) {
1201 /* Don't spend bytes for directory traffic if we could end up hibernating,
1202 * but allow DirPort otherwise. Some relay operators set AccountingMax
1203 * because they're confused or to get statistics. Directory traffic has a
1204 * much larger effect on output than input so there is no reason to turn it
1205 * off if using AccountingRule in. */
1206 int interval_length = accounting_get_interval_length();
1207 uint32_t effective_bw = get_effective_bwrate(options);
1208 uint64_t acc_bytes;
1209 if (!interval_length) {
1210 log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1211 "seconds long. Raising to 1.");
1212 interval_length = 1;
1214 log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
1215 "bwrate: %u, AccountingMax: %"PRIu64", "
1216 "accounting interval length %d",
1217 dir_port ? "dirport" : "begindir",
1218 effective_bw, (options->AccountingMax),
1219 interval_length);
1221 acc_bytes = options->AccountingMax;
1222 if (get_options()->AccountingRule == ACCT_SUM)
1223 acc_bytes /= 2;
1224 if (effective_bw >=
1225 acc_bytes / interval_length) {
1226 new_choice = 0;
1227 reason = "AccountingMax enabled";
1229 } else if (! router_has_bandwidth_to_be_dirserver(options)) {
1230 /* if we're advertising a small amount */
1231 new_choice = 0;
1232 reason = "BandwidthRate under 50KB";
1235 if (advertising != new_choice) {
1236 if (new_choice == 1) {
1237 if (dir_port > 0)
1238 log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1239 else
1240 log_notice(LD_DIR, "Advertising directory service support");
1241 } else {
1242 tor_assert(reason);
1243 log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
1244 dir_port ? "Port" : "ectory Service support", reason);
1246 advertising = new_choice;
1249 return advertising;
1252 /** Look at a variety of factors, and return 0 if we don't want to
1253 * advertise the fact that we have a DirPort open or begindir support, else
1254 * return 1.
1256 * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1257 * must be 0.
1259 * Log a helpful message if we change our mind about whether to publish.
1261 static int
1262 decide_to_advertise_dir_impl(const or_options_t *options,
1263 uint16_t dir_port,
1264 int supports_tunnelled_dir_requests)
1266 /* Part one: reasons to publish or not publish that aren't
1267 * worth mentioning to the user, either because they're obvious
1268 * or because they're normal behavior. */
1270 /* short circuit the rest of the function */
1271 if (!dir_port && !supports_tunnelled_dir_requests)
1272 return 0;
1273 if (authdir_mode(options)) /* always publish */
1274 return 1;
1275 if (net_is_disabled())
1276 return 0;
1277 if (dir_port && !router_get_advertised_dir_port(options, dir_port))
1278 return 0;
1279 if (supports_tunnelled_dir_requests &&
1280 !router_get_advertised_or_port(options))
1281 return 0;
1283 /* Part two: consider config options that could make us choose to
1284 * publish or not publish that the user might find surprising. */
1285 return router_should_be_dirserver(options, dir_port);
1288 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1289 * advertise the fact that we have a DirPort open, else return the
1290 * DirPort we want to advertise.
1293 router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1295 /* supports_tunnelled_dir_requests is not relevant, pass 0 */
1296 return decide_to_advertise_dir_impl(options, dir_port, 0) ? dir_port : 0;
1299 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1300 * advertise the fact that we support begindir requests, else return 1.
1302 static int
1303 router_should_advertise_begindir(const or_options_t *options,
1304 int supports_tunnelled_dir_requests)
1306 /* dir_port is not relevant, pass 0 */
1307 return decide_to_advertise_dir_impl(options, 0,
1308 supports_tunnelled_dir_requests);
1311 /** Return true iff the combination of options in <b>options</b> and parameters
1312 * in the consensus mean that we don't want to allow exits from circuits
1313 * we got from addresses not known to be servers. */
1315 should_refuse_unknown_exits(const or_options_t *options)
1317 if (options->RefuseUnknownExits != -1) {
1318 return options->RefuseUnknownExits;
1319 } else {
1320 return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1324 /** Decide if we're a publishable server. We are a publishable server if:
1325 * - We don't have the ClientOnly option set
1326 * and
1327 * - We have the PublishServerDescriptor option set to non-empty
1328 * and
1329 * - We have ORPort set
1330 * and
1331 * - We believe our ORPort and DirPort (if present) are reachable from
1332 * the outside; or
1333 * - We believe our ORPort is reachable from the outside, and we can't
1334 * check our DirPort because the consensus has no exits; or
1335 * - We are an authoritative directory server.
1337 static int
1338 decide_if_publishable_server(void)
1340 const or_options_t *options = get_options();
1342 if (options->ClientOnly)
1343 return 0;
1344 if (options->PublishServerDescriptor_ == NO_DIRINFO)
1345 return 0;
1346 if (!server_mode(options))
1347 return 0;
1348 if (authdir_mode(options))
1349 return 1;
1350 if (!router_get_advertised_or_port(options))
1351 return 0;
1352 if (!check_whether_orport_reachable(options))
1353 return 0;
1354 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
1355 /* All set: there are no exits in the consensus (maybe this is a tiny
1356 * test network), so we can't check our DirPort reachability. */
1357 return 1;
1358 } else {
1359 return check_whether_dirport_reachable(options);
1363 /** Initiate server descriptor upload as reasonable (if server is publishable,
1364 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1366 * We need to rebuild the descriptor if it's dirty even if we're not
1367 * uploading, because our reachability testing *uses* our descriptor to
1368 * determine what IP address and ports to test.
1370 void
1371 consider_publishable_server(int force)
1373 int rebuilt;
1375 if (!server_mode(get_options()))
1376 return;
1378 rebuilt = router_rebuild_descriptor(0);
1379 if (decide_if_publishable_server()) {
1380 set_server_advertised(1);
1381 if (rebuilt == 0)
1382 router_upload_dir_desc_to_dirservers(force);
1383 } else {
1384 set_server_advertised(0);
1388 /** Return the port of the first active listener of type
1389 * <b>listener_type</b>. */
1390 /** XXX not a very good interface. it's not reliable when there are
1391 multiple listeners. */
1392 uint16_t
1393 router_get_active_listener_port_by_type_af(int listener_type,
1394 sa_family_t family)
1396 /* Iterate all connections, find one of the right kind and return
1397 the port. Not very sophisticated or fast, but effective. */
1398 smartlist_t *conns = get_connection_array();
1399 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1400 if (conn->type == listener_type && !conn->marked_for_close &&
1401 conn->socket_family == family) {
1402 return conn->port;
1404 } SMARTLIST_FOREACH_END(conn);
1406 return 0;
1409 /** Return the port that we should advertise as our ORPort; this is either
1410 * the one configured in the ORPort option, or the one we actually bound to
1411 * if ORPort is "auto".
1413 uint16_t
1414 router_get_advertised_or_port(const or_options_t *options)
1416 return router_get_advertised_or_port_by_af(options, AF_INET);
1419 /** As router_get_advertised_or_port(), but allows an address family argument.
1421 uint16_t
1422 router_get_advertised_or_port_by_af(const or_options_t *options,
1423 sa_family_t family)
1425 int port = get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER,
1426 family);
1427 (void)options;
1429 /* If the port is in 'auto' mode, we have to use
1430 router_get_listener_port_by_type(). */
1431 if (port == CFG_AUTO_PORT)
1432 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER,
1433 family);
1435 return port;
1438 /** Return the port that we should advertise as our DirPort;
1439 * this is one of three possibilities:
1440 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1441 * the one configured in the DirPort option,
1442 * or the one we actually bound to if DirPort is "auto". */
1443 uint16_t
1444 router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
1446 int dirport_configured = get_primary_dir_port();
1447 (void)options;
1449 if (!dirport_configured)
1450 return dirport;
1452 if (dirport_configured == CFG_AUTO_PORT)
1453 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER,
1454 AF_INET);
1456 return dirport_configured;
1460 * OR descriptor generation.
1463 /** My routerinfo. */
1464 static routerinfo_t *desc_routerinfo = NULL;
1465 /** My extrainfo */
1466 static extrainfo_t *desc_extrainfo = NULL;
1467 /** Why did we most recently decide to regenerate our descriptor? Used to
1468 * tell the authorities why we're sending it to them. */
1469 static const char *desc_gen_reason = "uninitialized reason";
1470 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1471 * now. */
1472 static time_t desc_clean_since = 0;
1473 /** Why did we mark the descriptor dirty? */
1474 static const char *desc_dirty_reason = "Tor just started";
1475 /** Boolean: do we need to regenerate the above? */
1476 static int desc_needs_upload = 0;
1478 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1479 * descriptor successfully yet, try to upload our signed descriptor to
1480 * all the directory servers we know about.
1482 void
1483 router_upload_dir_desc_to_dirservers(int force)
1485 const routerinfo_t *ri;
1486 extrainfo_t *ei;
1487 char *msg;
1488 size_t desc_len, extra_len = 0, total_len;
1489 dirinfo_type_t auth = get_options()->PublishServerDescriptor_;
1491 ri = router_get_my_routerinfo();
1492 if (!ri) {
1493 log_info(LD_GENERAL, "No descriptor; skipping upload");
1494 return;
1496 ei = router_get_my_extrainfo();
1497 if (auth == NO_DIRINFO)
1498 return;
1499 if (!force && !desc_needs_upload)
1500 return;
1502 log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1503 force ? " (forced)" : "");
1505 desc_needs_upload = 0;
1507 desc_len = ri->cache_info.signed_descriptor_len;
1508 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1509 total_len = desc_len + extra_len + 1;
1510 msg = tor_malloc(total_len);
1511 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1512 if (ei) {
1513 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1515 msg[desc_len+extra_len] = 0;
1517 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1518 (auth & BRIDGE_DIRINFO) ?
1519 ROUTER_PURPOSE_BRIDGE :
1520 ROUTER_PURPOSE_GENERAL,
1521 auth, msg, desc_len, extra_len);
1522 tor_free(msg);
1525 /** OR only: Check whether my exit policy says to allow connection to
1526 * conn. Return 0 if we accept; non-0 if we reject.
1529 router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
1531 const routerinfo_t *me = router_get_my_routerinfo();
1532 if (!me) /* make sure routerinfo exists */
1533 return -1;
1535 /* make sure it's resolved to something. this way we can't get a
1536 'maybe' below. */
1537 if (tor_addr_is_null(addr))
1538 return -1;
1540 /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
1541 * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
1542 * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
1543 * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
1544 * summary. */
1545 if ((tor_addr_family(addr) == AF_INET ||
1546 tor_addr_family(addr) == AF_INET6)) {
1547 return compare_tor_addr_to_addr_policy(addr, port,
1548 me->exit_policy) != ADDR_POLICY_ACCEPTED;
1549 #if 0
1550 } else if (tor_addr_family(addr) == AF_INET6) {
1551 return get_options()->IPv6Exit &&
1552 desc_routerinfo->ipv6_exit_policy &&
1553 compare_tor_addr_to_short_policy(addr, port,
1554 me->ipv6_exit_policy) != ADDR_POLICY_ACCEPTED;
1555 #endif /* 0 */
1556 } else {
1557 return -1;
1561 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1562 * have a descriptor */
1563 MOCK_IMPL(int,
1564 router_my_exit_policy_is_reject_star,(void))
1566 const routerinfo_t *me = router_get_my_routerinfo();
1567 if (!me) /* make sure routerinfo exists */
1568 return -1;
1570 return me->policy_is_reject_star;
1573 /** Return true iff I'm a server and <b>digest</b> is equal to
1574 * my server identity key digest. */
1576 router_digest_is_me(const char *digest)
1578 return (server_identitykey &&
1579 tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
1582 /** Return my identity digest. */
1583 const uint8_t *
1584 router_get_my_id_digest(void)
1586 return (const uint8_t *)server_identitykey_digest;
1589 /** Return true iff I'm a server and <b>digest</b> is equal to
1590 * my identity digest. */
1592 router_extrainfo_digest_is_me(const char *digest)
1594 extrainfo_t *ei = router_get_my_extrainfo();
1595 if (!ei)
1596 return 0;
1598 return tor_memeq(digest,
1599 ei->cache_info.signed_descriptor_digest,
1600 DIGEST_LEN);
1603 /** A wrapper around router_digest_is_me(). */
1605 router_is_me(const routerinfo_t *router)
1607 return router_digest_is_me(router->cache_info.identity_digest);
1610 /** Return a routerinfo for this OR, rebuilding a fresh one if
1611 * necessary. Return NULL on error, or if called on an OP. */
1612 MOCK_IMPL(const routerinfo_t *,
1613 router_get_my_routerinfo,(void))
1615 return router_get_my_routerinfo_with_err(NULL);
1618 /** Return routerinfo of this OR. Rebuild it from
1619 * scratch if needed. Set <b>*err</b> to 0 on success or to
1620 * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
1622 MOCK_IMPL(const routerinfo_t *,
1623 router_get_my_routerinfo_with_err,(int *err))
1625 if (!server_mode(get_options())) {
1626 if (err)
1627 *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
1629 return NULL;
1632 if (!desc_clean_since) {
1633 int rebuild_err = router_rebuild_descriptor(0);
1634 if (rebuild_err < 0) {
1635 if (err)
1636 *err = rebuild_err;
1638 return NULL;
1642 if (!desc_routerinfo) {
1643 if (err)
1644 *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
1646 return NULL;
1649 if (err)
1650 *err = 0;
1652 return desc_routerinfo;
1655 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1656 * one if necessary. Return NULL on error.
1658 const char *
1659 router_get_my_descriptor(void)
1661 const char *body;
1662 const routerinfo_t *me = router_get_my_routerinfo();
1663 if (! me)
1664 return NULL;
1665 tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
1666 body = signed_descriptor_get_body(&me->cache_info);
1667 /* Make sure this is nul-terminated. */
1668 tor_assert(!body[me->cache_info.signed_descriptor_len]);
1669 log_debug(LD_GENERAL,"my desc is '%s'", body);
1670 return body;
1673 /** Return the extrainfo document for this OR, or NULL if we have none.
1674 * Rebuilt it (and the server descriptor) if necessary. */
1675 extrainfo_t *
1676 router_get_my_extrainfo(void)
1678 if (!server_mode(get_options()))
1679 return NULL;
1680 if (router_rebuild_descriptor(0))
1681 return NULL;
1682 return desc_extrainfo;
1685 /** Return a human-readable string describing what triggered us to generate
1686 * our current descriptor, or NULL if we don't know. */
1687 const char *
1688 router_get_descriptor_gen_reason(void)
1690 return desc_gen_reason;
1693 /** A list of nicknames that we've warned about including in our family
1694 * declaration verbatim rather than as digests. */
1695 static smartlist_t *warned_nonexistent_family = NULL;
1697 static int router_guess_address_from_dir_headers(uint32_t *guess);
1699 /** Make a current best guess at our address, either because
1700 * it's configured in torrc, or because we've learned it from
1701 * dirserver headers. Place the answer in *<b>addr</b> and return
1702 * 0 on success, else return -1 if we have no guess.
1704 * If <b>cache_only</b> is true, just return any cached answers, and
1705 * don't try to get any new answers.
1707 MOCK_IMPL(int,
1708 router_pick_published_address,(const or_options_t *options, uint32_t *addr,
1709 int cache_only))
1711 /* First, check the cached output from resolve_my_address(). */
1712 *addr = get_last_resolved_addr();
1713 if (*addr)
1714 return 0;
1716 /* Second, consider doing a resolve attempt right here. */
1717 if (!cache_only) {
1718 if (resolve_my_address(LOG_INFO, options, addr, NULL, NULL) >= 0) {
1719 log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
1720 return 0;
1724 /* Third, check the cached output from router_new_address_suggestion(). */
1725 if (router_guess_address_from_dir_headers(addr) >= 0)
1726 return 0;
1728 /* We have no useful cached answers. Return failure. */
1729 return -1;
1732 /* Like router_check_descriptor_address_consistency, but specifically for the
1733 * ORPort or DirPort.
1734 * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
1735 static void
1736 router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr,
1737 int listener_type)
1739 tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
1740 listener_type == CONN_TYPE_DIR_LISTENER);
1742 /* The first advertised Port may be the magic constant CFG_AUTO_PORT.
1744 int port_v4_cfg = get_first_advertised_port_by_type_af(listener_type,
1745 AF_INET);
1746 if (port_v4_cfg != 0 &&
1747 !port_exists_by_type_addr32h_port(listener_type,
1748 ipv4h_desc_addr, port_v4_cfg, 1)) {
1749 const tor_addr_t *port_addr = get_first_advertised_addr_by_type_af(
1750 listener_type,
1751 AF_INET);
1752 /* If we're building a descriptor with no advertised address,
1753 * something is terribly wrong. */
1754 tor_assert(port_addr);
1756 tor_addr_t desc_addr;
1757 char port_addr_str[TOR_ADDR_BUF_LEN];
1758 char desc_addr_str[TOR_ADDR_BUF_LEN];
1760 tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
1762 tor_addr_from_ipv4h(&desc_addr, ipv4h_desc_addr);
1763 tor_addr_to_str(desc_addr_str, &desc_addr, TOR_ADDR_BUF_LEN, 0);
1765 const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
1766 "OR" : "Dir");
1767 log_warn(LD_CONFIG, "The IPv4 %sPort address %s does not match the "
1768 "descriptor address %s. If you have a static public IPv4 "
1769 "address, use 'Address <IPv4>' and 'OutboundBindAddress "
1770 "<IPv4>'. If you are behind a NAT, use two %sPort lines: "
1771 "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
1772 "NoAdvertise'.",
1773 listener_str, port_addr_str, desc_addr_str, listener_str,
1774 listener_str, listener_str);
1778 /* Tor relays only have one IPv4 address in the descriptor, which is derived
1779 * from the Address torrc option, or guessed using various methods in
1780 * router_pick_published_address().
1781 * Warn the operator if there is no ORPort on the descriptor address
1782 * ipv4h_desc_addr.
1783 * Warn the operator if there is no DirPort on the descriptor address.
1784 * This catches a few common config errors:
1785 * - operators who expect ORPorts and DirPorts to be advertised on the
1786 * ports' listen addresses, rather than the torrc Address (or guessed
1787 * addresses in the absence of an Address config). This includes
1788 * operators who attempt to put their ORPort and DirPort on different
1789 * addresses;
1790 * - discrepancies between guessed addresses and configured listen
1791 * addresses (when the Address option isn't set).
1792 * If a listener is listening on all IPv4 addresses, it is assumed that it
1793 * is listening on the configured Address, and no messages are logged.
1794 * If an operators has specified NoAdvertise ORPorts in a NAT setting,
1795 * no messages are logged, unless they have specified other advertised
1796 * addresses.
1797 * The message tells operators to configure an ORPort and DirPort that match
1798 * the Address (using NoListen if needed).
1800 static void
1801 router_check_descriptor_address_consistency(uint32_t ipv4h_desc_addr)
1803 router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1804 CONN_TYPE_OR_LISTENER);
1805 router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1806 CONN_TYPE_DIR_LISTENER);
1809 /** Build a fresh routerinfo, signed server descriptor, and extra-info document
1810 * for this OR. Set r to the generated routerinfo, e to the generated
1811 * extra-info document. Return 0 on success, -1 on temporary error. Failure to
1812 * generate an extra-info document is not an error and is indicated by setting
1813 * e to NULL. Caller is responsible for freeing generated documents if 0 is
1814 * returned.
1817 router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
1819 routerinfo_t *ri;
1820 extrainfo_t *ei;
1821 uint32_t addr;
1822 char platform[256];
1823 int hibernating = we_are_hibernating();
1824 const or_options_t *options = get_options();
1826 if (router_pick_published_address(options, &addr, 0) < 0) {
1827 log_warn(LD_CONFIG, "Don't know my address while generating descriptor");
1828 return TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
1831 /* Log a message if the address in the descriptor doesn't match the ORPort
1832 * and DirPort addresses configured by the operator. */
1833 router_check_descriptor_address_consistency(addr);
1835 ri = tor_malloc_zero(sizeof(routerinfo_t));
1836 ri->cache_info.routerlist_index = -1;
1837 ri->nickname = tor_strdup(options->Nickname);
1838 ri->addr = addr;
1839 ri->or_port = router_get_advertised_or_port(options);
1840 ri->dir_port = router_get_advertised_dir_port(options, 0);
1841 ri->supports_tunnelled_dir_requests =
1842 directory_permits_begindir_requests(options);
1843 ri->cache_info.published_on = time(NULL);
1844 /* get_onion_key() must invoke from main thread */
1845 router_set_rsa_onion_pkey(get_onion_key(), &ri->onion_pkey,
1846 &ri->onion_pkey_len);
1848 ri->onion_curve25519_pkey =
1849 tor_memdup(&get_current_curve25519_keypair()->pubkey,
1850 sizeof(curve25519_public_key_t));
1852 /* For now, at most one IPv6 or-address is being advertised. */
1854 const port_cfg_t *ipv6_orport = NULL;
1855 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
1856 if (p->type == CONN_TYPE_OR_LISTENER &&
1857 ! p->server_cfg.no_advertise &&
1858 ! p->server_cfg.bind_ipv4_only &&
1859 tor_addr_family(&p->addr) == AF_INET6) {
1860 /* Like IPv4, if the relay is configured using the default
1861 * authorities, disallow internal IPs. Otherwise, allow them. */
1862 const int default_auth = using_default_dir_authorities(options);
1863 if (! tor_addr_is_internal(&p->addr, 0) || ! default_auth) {
1864 ipv6_orport = p;
1865 break;
1866 } else {
1867 char addrbuf[TOR_ADDR_BUF_LEN];
1868 log_warn(LD_CONFIG,
1869 "Unable to use configured IPv6 address \"%s\" in a "
1870 "descriptor. Skipping it. "
1871 "Try specifying a globally reachable address explicitly.",
1872 tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
1875 } SMARTLIST_FOREACH_END(p);
1876 if (ipv6_orport) {
1877 tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
1878 ri->ipv6_orport = ipv6_orport->port;
1882 ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
1883 if (BUG(crypto_pk_get_digest(ri->identity_pkey,
1884 ri->cache_info.identity_digest) < 0)) {
1885 routerinfo_free(ri);
1886 return TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
1888 ri->cache_info.signing_key_cert =
1889 tor_cert_dup(get_master_signing_key_cert());
1891 get_platform_str(platform, sizeof(platform));
1892 ri->platform = tor_strdup(platform);
1894 ri->protocol_list = tor_strdup(protover_get_supported_protocols());
1896 /* compute ri->bandwidthrate as the min of various options */
1897 ri->bandwidthrate = get_effective_bwrate(options);
1899 /* and compute ri->bandwidthburst similarly */
1900 ri->bandwidthburst = get_effective_bwburst(options);
1902 /* Report bandwidth, unless we're hibernating or shutting down */
1903 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1905 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1906 /* DNS is screwed up; don't claim to be an exit. */
1907 policies_exit_policy_append_reject_star(&ri->exit_policy);
1908 } else {
1909 policies_parse_exit_policy_from_options(options,ri->addr,&ri->ipv6_addr,
1910 &ri->exit_policy);
1912 ri->policy_is_reject_star =
1913 policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
1914 policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
1916 if (options->IPv6Exit) {
1917 char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
1918 if (p_tmp)
1919 ri->ipv6_exit_policy = parse_short_policy(p_tmp);
1920 tor_free(p_tmp);
1923 if (options->MyFamily && ! options->BridgeRelay) {
1924 if (!warned_nonexistent_family)
1925 warned_nonexistent_family = smartlist_new();
1926 ri->declared_family = smartlist_new();
1927 config_line_t *family;
1928 for (family = options->MyFamily; family; family = family->next) {
1929 char *name = family->value;
1930 const node_t *member;
1931 if (!strcasecmp(name, options->Nickname))
1932 continue; /* Don't list ourself, that's redundant */
1933 else
1934 member = node_get_by_nickname(name, 0);
1935 if (!member) {
1936 int is_legal = is_legal_nickname_or_hexdigest(name);
1937 if (!smartlist_contains_string(warned_nonexistent_family, name) &&
1938 !is_legal_hexdigest(name)) {
1939 if (is_legal)
1940 log_warn(LD_CONFIG,
1941 "I have no descriptor for the router named \"%s\" in my "
1942 "declared family; I'll use the nickname as is, but "
1943 "this may confuse clients.", name);
1944 else
1945 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1946 "declared family, but that isn't a legal nickname. "
1947 "Skipping it.", escaped(name));
1948 smartlist_add_strdup(warned_nonexistent_family, name);
1950 if (is_legal) {
1951 smartlist_add_strdup(ri->declared_family, name);
1953 } else if (router_digest_is_me(member->identity)) {
1954 /* Don't list ourself in our own family; that's redundant */
1955 /* XXX shouldn't be possible */
1956 } else {
1957 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1958 fp[0] = '$';
1959 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1960 member->identity, DIGEST_LEN);
1961 smartlist_add(ri->declared_family, fp);
1962 if (smartlist_contains_string(warned_nonexistent_family, name))
1963 smartlist_string_remove(warned_nonexistent_family, name);
1967 /* remove duplicates from the list */
1968 smartlist_sort_strings(ri->declared_family);
1969 smartlist_uniq_strings(ri->declared_family);
1972 /* Now generate the extrainfo. */
1973 ei = tor_malloc_zero(sizeof(extrainfo_t));
1974 ei->cache_info.is_extrainfo = 1;
1975 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1976 ei->cache_info.published_on = ri->cache_info.published_on;
1977 ei->cache_info.signing_key_cert =
1978 tor_cert_dup(get_master_signing_key_cert());
1980 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1981 DIGEST_LEN);
1982 if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
1983 ei, get_server_identity_key(),
1984 get_master_signing_keypair()) < 0) {
1985 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1986 extrainfo_free(ei);
1987 ei = NULL;
1988 } else {
1989 ei->cache_info.signed_descriptor_len =
1990 strlen(ei->cache_info.signed_descriptor_body);
1991 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1992 ei->cache_info.signed_descriptor_len,
1993 ei->cache_info.signed_descriptor_digest);
1994 crypto_digest256((char*) ei->digest256,
1995 ei->cache_info.signed_descriptor_body,
1996 ei->cache_info.signed_descriptor_len,
1997 DIGEST_SHA256);
2000 /* Now finish the router descriptor. */
2001 if (ei) {
2002 memcpy(ri->cache_info.extra_info_digest,
2003 ei->cache_info.signed_descriptor_digest,
2004 DIGEST_LEN);
2005 memcpy(ri->cache_info.extra_info_digest256,
2006 ei->digest256,
2007 DIGEST256_LEN);
2008 } else {
2009 /* ri was allocated with tor_malloc_zero, so there is no need to
2010 * zero ri->cache_info.extra_info_digest here. */
2012 if (! (ri->cache_info.signed_descriptor_body =
2013 router_dump_router_to_string(ri, get_server_identity_key(),
2014 get_onion_key(),
2015 get_current_curve25519_keypair(),
2016 get_master_signing_keypair())) ) {
2017 log_warn(LD_BUG, "Couldn't generate router descriptor.");
2018 routerinfo_free(ri);
2019 extrainfo_free(ei);
2020 return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
2022 ri->cache_info.signed_descriptor_len =
2023 strlen(ri->cache_info.signed_descriptor_body);
2025 ri->purpose =
2026 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
2027 if (options->BridgeRelay) {
2028 /* Bridges shouldn't be able to send their descriptors unencrypted,
2029 anyway, since they don't have a DirPort, and always connect to the
2030 bridge authority anonymously. But just in case they somehow think of
2031 sending them on an unencrypted connection, don't allow them to try. */
2032 ri->cache_info.send_unencrypted = 0;
2033 if (ei)
2034 ei->cache_info.send_unencrypted = 0;
2035 } else {
2036 ri->cache_info.send_unencrypted = 1;
2037 if (ei)
2038 ei->cache_info.send_unencrypted = 1;
2041 router_get_router_hash(ri->cache_info.signed_descriptor_body,
2042 strlen(ri->cache_info.signed_descriptor_body),
2043 ri->cache_info.signed_descriptor_digest);
2045 if (ei) {
2046 tor_assert(!
2047 routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
2048 &ri->cache_info, NULL));
2051 *r = ri;
2052 *e = ei;
2053 return 0;
2056 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2057 * routerinfo, signed server descriptor, and extra-info document for this OR.
2058 * Return 0 on success, -1 on temporary error.
2061 router_rebuild_descriptor(int force)
2063 int err = 0;
2064 routerinfo_t *ri;
2065 extrainfo_t *ei;
2066 uint32_t addr;
2067 const or_options_t *options = get_options();
2069 if (desc_clean_since && !force)
2070 return 0;
2072 if (router_pick_published_address(options, &addr, 0) < 0 ||
2073 router_get_advertised_or_port(options) == 0) {
2074 /* Stop trying to rebuild our descriptor every second. We'll
2075 * learn that it's time to try again when ip_address_changed()
2076 * marks it dirty. */
2077 desc_clean_since = time(NULL);
2078 return TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
2081 log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
2083 err = router_build_fresh_descriptor(&ri, &ei);
2084 if (err < 0) {
2085 return err;
2088 routerinfo_free(desc_routerinfo);
2089 desc_routerinfo = ri;
2090 extrainfo_free(desc_extrainfo);
2091 desc_extrainfo = ei;
2093 desc_clean_since = time(NULL);
2094 desc_needs_upload = 1;
2095 desc_gen_reason = desc_dirty_reason;
2096 if (BUG(desc_gen_reason == NULL)) {
2097 desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
2099 desc_dirty_reason = NULL;
2100 control_event_my_descriptor_changed();
2101 return 0;
2104 /** If our router descriptor ever goes this long without being regenerated
2105 * because something changed, we force an immediate regenerate-and-upload. */
2106 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2108 /** If our router descriptor seems to be missing or unacceptable according
2109 * to the authorities, regenerate and reupload it _this_ often. */
2110 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2112 /** Mark descriptor out of date if it's been "too long" since we last tried
2113 * to upload one. */
2114 void
2115 mark_my_descriptor_dirty_if_too_old(time_t now)
2117 networkstatus_t *ns;
2118 const routerstatus_t *rs;
2119 const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2120 const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2121 const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2123 /* If it's already dirty, don't mark it. */
2124 if (! desc_clean_since)
2125 return;
2127 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2128 * time to rebuild it. */
2129 if (desc_clean_since < slow_cutoff) {
2130 mark_my_descriptor_dirty("time for new descriptor");
2131 return;
2133 /* Now we see whether we want to be retrying frequently or no. The
2134 * rule here is that we'll retry frequently if we aren't listed in the
2135 * live consensus we have, or if the publication time of the
2136 * descriptor listed for us in the consensus is very old. */
2137 ns = networkstatus_get_live_consensus(now);
2138 if (ns) {
2139 rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
2140 if (rs == NULL)
2141 retry_fast_reason = "not listed in consensus";
2142 else if (rs->published_on < slow_cutoff)
2143 retry_fast_reason = "version listed in consensus is quite old";
2146 if (retry_fast_reason && desc_clean_since < fast_cutoff)
2147 mark_my_descriptor_dirty(retry_fast_reason);
2150 /** Call when the current descriptor is out of date. */
2151 void
2152 mark_my_descriptor_dirty(const char *reason)
2154 const or_options_t *options = get_options();
2155 if (BUG(reason == NULL)) {
2156 reason = "marked descriptor dirty for unspecified reason";
2158 if (server_mode(options) && options->PublishServerDescriptor_)
2159 log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2160 desc_clean_since = 0;
2161 if (!desc_dirty_reason)
2162 desc_dirty_reason = reason;
2165 /** How frequently will we republish our descriptor because of large (factor
2166 * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2167 * if our previous bandwidth estimate was exactly 0. */
2168 #define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
2170 /** Maximum uptime to republish our descriptor because of large shifts in
2171 * estimated bandwidth. */
2172 #define MAX_UPTIME_BANDWIDTH_CHANGE (24*60*60)
2174 /** By which factor bandwidth shifts have to change to be considered large. */
2175 #define BANDWIDTH_CHANGE_FACTOR 2
2177 /** Check whether bandwidth has changed a lot since the last time we announced
2178 * bandwidth while the uptime is smaller than MAX_UPTIME_BANDWIDTH_CHANGE.
2179 * If so, mark our descriptor dirty. */
2180 void
2181 check_descriptor_bandwidth_changed(time_t now)
2183 static time_t last_changed = 0;
2184 uint64_t prev, cur;
2185 const int hibernating = we_are_hibernating();
2187 /* If the relay uptime is bigger than MAX_UPTIME_BANDWIDTH_CHANGE,
2188 * the next regularly scheduled descriptor update (18h) will be enough */
2189 if (get_uptime() > MAX_UPTIME_BANDWIDTH_CHANGE && !hibernating)
2190 return;
2192 const routerinfo_t *my_ri = router_get_my_routerinfo();
2194 if (!my_ri)
2195 return;
2197 prev = my_ri->bandwidthcapacity;
2199 /* Consider ourselves to have zero bandwidth if we're hibernating or
2200 * shutting down. */
2201 cur = hibernating ? 0 : rep_hist_bandwidth_assess();
2203 if ((prev != cur && (!prev || !cur)) ||
2204 cur > (prev * BANDWIDTH_CHANGE_FACTOR) ||
2205 cur < (prev / BANDWIDTH_CHANGE_FACTOR) ) {
2206 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
2207 log_info(LD_GENERAL,
2208 "Measured bandwidth has changed; rebuilding descriptor.");
2209 mark_my_descriptor_dirty("bandwidth has changed");
2210 last_changed = now;
2215 /** Note at log level severity that our best guess of address has changed from
2216 * <b>prev</b> to <b>cur</b>. */
2217 static void
2218 log_addr_has_changed(int severity,
2219 const tor_addr_t *prev,
2220 const tor_addr_t *cur,
2221 const char *source)
2223 char addrbuf_prev[TOR_ADDR_BUF_LEN];
2224 char addrbuf_cur[TOR_ADDR_BUF_LEN];
2226 if (BUG(!server_mode(get_options())))
2227 return;
2229 if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2230 strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2231 if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2232 strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2234 if (!tor_addr_is_null(prev))
2235 log_fn(severity, LD_GENERAL,
2236 "Our IP Address has changed from %s to %s; "
2237 "rebuilding descriptor (source: %s).",
2238 addrbuf_prev, addrbuf_cur, source);
2239 else
2240 log_notice(LD_GENERAL,
2241 "Guessed our IP address as %s (source: %s).",
2242 addrbuf_cur, source);
2245 /** Check whether our own address as defined by the Address configuration
2246 * has changed. This is for routers that get their address from a service
2247 * like dyndns. If our address has changed, mark our descriptor dirty. */
2248 void
2249 check_descriptor_ipaddress_changed(time_t now)
2251 uint32_t prev, cur;
2252 const or_options_t *options = get_options();
2253 const char *method = NULL;
2254 char *hostname = NULL;
2255 const routerinfo_t *my_ri = router_get_my_routerinfo();
2257 (void) now;
2259 if (my_ri == NULL) /* make sure routerinfo exists */
2260 return;
2262 /* XXXX ipv6 */
2263 prev = my_ri->addr;
2264 if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
2265 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
2266 return;
2269 if (prev != cur) {
2270 char *source;
2271 tor_addr_t tmp_prev, tmp_cur;
2273 tor_addr_from_ipv4h(&tmp_prev, prev);
2274 tor_addr_from_ipv4h(&tmp_cur, cur);
2276 tor_asprintf(&source, "METHOD=%s%s%s", method,
2277 hostname ? " HOSTNAME=" : "",
2278 hostname ? hostname : "");
2280 log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
2281 tor_free(source);
2283 ip_address_changed(0);
2286 tor_free(hostname);
2289 /** The most recently guessed value of our IP address, based on directory
2290 * headers. */
2291 static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
2293 /** A directory server <b>d_conn</b> told us our IP address is
2294 * <b>suggestion</b>.
2295 * If this address is different from the one we think we are now, and
2296 * if our computer doesn't actually know its IP address, then switch. */
2297 void
2298 router_new_address_suggestion(const char *suggestion,
2299 const dir_connection_t *d_conn)
2301 tor_addr_t addr;
2302 uint32_t cur = 0; /* Current IPv4 address. */
2303 const or_options_t *options = get_options();
2305 /* first, learn what the IP address actually is */
2306 if (tor_addr_parse(&addr, suggestion) == -1) {
2307 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
2308 escaped(suggestion));
2309 return;
2312 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
2314 if (!server_mode(options)) {
2315 tor_addr_copy(&last_guessed_ip, &addr);
2316 return;
2319 /* XXXX ipv6 */
2320 cur = get_last_resolved_addr();
2321 if (cur ||
2322 resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
2323 /* We're all set -- we already know our address. Great. */
2324 tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
2325 need it later */
2326 return;
2328 if (tor_addr_is_internal(&addr, 0)) {
2329 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2330 return;
2332 if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
2333 /* Don't believe anybody who says our IP is their IP. */
2334 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
2335 "but they are just reporting their own IP address. Ignoring.",
2336 suggestion);
2337 return;
2340 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2341 * us an answer different from what we had the last time we managed to
2342 * resolve it. */
2343 if (!tor_addr_eq(&last_guessed_ip, &addr)) {
2344 control_event_server_status(LOG_NOTICE,
2345 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2346 suggestion);
2347 log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
2348 d_conn->base_.address);
2349 ip_address_changed(0);
2350 tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
2351 will fetch it */
2355 /** We failed to resolve our address locally, but we'd like to build
2356 * a descriptor and publish / test reachability. If we have a guess
2357 * about our address based on directory headers, answer it and return
2358 * 0; else return -1. */
2359 static int
2360 router_guess_address_from_dir_headers(uint32_t *guess)
2362 if (!tor_addr_is_null(&last_guessed_ip)) {
2363 *guess = tor_addr_to_ipv4h(&last_guessed_ip);
2364 return 0;
2366 return -1;
2369 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2370 * string describing the version of Tor and the operating system we're
2371 * currently running on.
2373 STATIC void
2374 get_platform_str(char *platform, size_t len)
2376 tor_snprintf(platform, len, "Tor %s on %s",
2377 get_short_version(), get_uname());
2380 /* XXX need to audit this thing and count fenceposts. maybe
2381 * refactor so we don't have to keep asking if we're
2382 * near the end of maxlen?
2384 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2386 /** OR only: Given a routerinfo for this router, and an identity key to sign
2387 * with, encode the routerinfo as a signed server descriptor and return a new
2388 * string encoding the result, or NULL on failure.
2390 char *
2391 router_dump_router_to_string(routerinfo_t *router,
2392 const crypto_pk_t *ident_key,
2393 const crypto_pk_t *tap_key,
2394 const curve25519_keypair_t *ntor_keypair,
2395 const ed25519_keypair_t *signing_keypair)
2397 char *address = NULL;
2398 char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2399 crypto_pk_t *rsa_pubkey = NULL;
2400 char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2401 char digest[DIGEST256_LEN];
2402 char published[ISO_TIME_LEN+1];
2403 char fingerprint[FINGERPRINT_LEN+1];
2404 char *extra_info_line = NULL;
2405 size_t onion_pkeylen, identity_pkeylen;
2406 char *family_line = NULL;
2407 char *extra_or_address = NULL;
2408 const or_options_t *options = get_options();
2409 smartlist_t *chunks = NULL;
2410 char *output = NULL;
2411 const int emit_ed_sigs = signing_keypair &&
2412 router->cache_info.signing_key_cert;
2413 char *ed_cert_line = NULL;
2414 char *rsa_tap_cc_line = NULL;
2415 char *ntor_cc_line = NULL;
2416 char *proto_line = NULL;
2418 /* Make sure the identity key matches the one in the routerinfo. */
2419 if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2420 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2421 "match router's public key!");
2422 goto err;
2424 if (emit_ed_sigs) {
2425 if (!router->cache_info.signing_key_cert->signing_key_included ||
2426 !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
2427 &signing_keypair->pubkey)) {
2428 log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
2429 "ed25519 key chain %d",
2430 router->cache_info.signing_key_cert->signing_key_included);
2431 goto err;
2435 /* record our fingerprint, so we can include it in the descriptor */
2436 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2437 log_err(LD_BUG,"Error computing fingerprint");
2438 goto err;
2441 if (emit_ed_sigs) {
2442 /* Encode ed25519 signing cert */
2443 char ed_cert_base64[256];
2444 char ed_fp_base64[ED25519_BASE64_LEN+1];
2445 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2446 (const char*)router->cache_info.signing_key_cert->encoded,
2447 router->cache_info.signing_key_cert->encoded_len,
2448 BASE64_ENCODE_MULTILINE) < 0) {
2449 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2450 goto err;
2452 if (ed25519_public_to_base64(ed_fp_base64,
2453 &router->cache_info.signing_key_cert->signing_key)<0) {
2454 log_err(LD_BUG,"Couldn't base64-encode identity key\n");
2455 goto err;
2457 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2458 "-----BEGIN ED25519 CERT-----\n"
2459 "%s"
2460 "-----END ED25519 CERT-----\n"
2461 "master-key-ed25519 %s\n",
2462 ed_cert_base64, ed_fp_base64);
2465 /* PEM-encode the onion key */
2466 rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
2467 router->onion_pkey_len);
2468 if (crypto_pk_write_public_key_to_string(rsa_pubkey,
2469 &onion_pkey,&onion_pkeylen)<0) {
2470 log_warn(LD_BUG,"write onion_pkey to string failed!");
2471 goto err;
2474 /* PEM-encode the identity key */
2475 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
2476 &identity_pkey,&identity_pkeylen)<0) {
2477 log_warn(LD_BUG,"write identity_pkey to string failed!");
2478 goto err;
2481 /* Cross-certify with RSA key */
2482 if (tap_key && router->cache_info.signing_key_cert &&
2483 router->cache_info.signing_key_cert->signing_key_included) {
2484 char buf[256];
2485 int tap_cc_len = 0;
2486 uint8_t *tap_cc =
2487 make_tap_onion_key_crosscert(tap_key,
2488 &router->cache_info.signing_key_cert->signing_key,
2489 router->identity_pkey,
2490 &tap_cc_len);
2491 if (!tap_cc) {
2492 log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
2493 goto err;
2496 if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
2497 BASE64_ENCODE_MULTILINE) < 0) {
2498 log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
2499 tor_free(tap_cc);
2500 goto err;
2502 tor_free(tap_cc);
2504 tor_asprintf(&rsa_tap_cc_line,
2505 "onion-key-crosscert\n"
2506 "-----BEGIN CROSSCERT-----\n"
2507 "%s"
2508 "-----END CROSSCERT-----\n", buf);
2511 /* Cross-certify with onion keys */
2512 if (ntor_keypair && router->cache_info.signing_key_cert &&
2513 router->cache_info.signing_key_cert->signing_key_included) {
2514 int sign = 0;
2515 char buf[256];
2516 /* XXXX Base the expiration date on the actual onion key expiration time?*/
2517 tor_cert_t *cert =
2518 make_ntor_onion_key_crosscert(ntor_keypair,
2519 &router->cache_info.signing_key_cert->signing_key,
2520 router->cache_info.published_on,
2521 get_onion_key_lifetime(), &sign);
2522 if (!cert) {
2523 log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
2524 goto err;
2526 tor_assert(sign == 0 || sign == 1);
2528 if (base64_encode(buf, sizeof(buf),
2529 (const char*)cert->encoded, cert->encoded_len,
2530 BASE64_ENCODE_MULTILINE)<0) {
2531 log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
2532 tor_cert_free(cert);
2533 goto err;
2535 tor_cert_free(cert);
2537 tor_asprintf(&ntor_cc_line,
2538 "ntor-onion-key-crosscert %d\n"
2539 "-----BEGIN ED25519 CERT-----\n"
2540 "%s"
2541 "-----END ED25519 CERT-----\n", sign, buf);
2544 /* Encode the publication time. */
2545 format_iso_time(published, router->cache_info.published_on);
2547 if (router->declared_family && smartlist_len(router->declared_family)) {
2548 char *family = smartlist_join_strings(router->declared_family,
2549 " ", 0, NULL);
2550 tor_asprintf(&family_line, "family %s\n", family);
2551 tor_free(family);
2552 } else {
2553 family_line = tor_strdup("");
2556 if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
2557 char extra_info_digest[HEX_DIGEST_LEN+1];
2558 base16_encode(extra_info_digest, sizeof(extra_info_digest),
2559 router->cache_info.extra_info_digest, DIGEST_LEN);
2560 if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
2561 char d256_64[BASE64_DIGEST256_LEN+1];
2562 digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
2563 tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
2564 extra_info_digest, d256_64);
2565 } else {
2566 tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
2567 extra_info_digest);
2571 if (router->ipv6_orport &&
2572 tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2573 char addr[TOR_ADDR_BUF_LEN];
2574 const char *a;
2575 a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2576 if (a) {
2577 tor_asprintf(&extra_or_address,
2578 "or-address %s:%d\n", a, router->ipv6_orport);
2579 log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2583 if (router->protocol_list) {
2584 tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
2585 } else {
2586 proto_line = tor_strdup("");
2589 address = tor_dup_ip(router->addr);
2590 chunks = smartlist_new();
2592 /* Generate the easy portion of the router descriptor. */
2593 smartlist_add_asprintf(chunks,
2594 "router %s %s %d 0 %d\n"
2595 "%s"
2596 "%s"
2597 "platform %s\n"
2598 "%s"
2599 "published %s\n"
2600 "fingerprint %s\n"
2601 "uptime %ld\n"
2602 "bandwidth %d %d %d\n"
2603 "%s%s"
2604 "onion-key\n%s"
2605 "signing-key\n%s"
2606 "%s%s"
2607 "%s%s%s",
2608 router->nickname,
2609 address,
2610 router->or_port,
2611 router_should_advertise_dirport(options, router->dir_port),
2612 ed_cert_line ? ed_cert_line : "",
2613 extra_or_address ? extra_or_address : "",
2614 router->platform,
2615 proto_line,
2616 published,
2617 fingerprint,
2618 get_uptime(),
2619 (int) router->bandwidthrate,
2620 (int) router->bandwidthburst,
2621 (int) router->bandwidthcapacity,
2622 extra_info_line ? extra_info_line : "",
2623 (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
2624 "caches-extra-info\n" : "",
2625 onion_pkey, identity_pkey,
2626 rsa_tap_cc_line ? rsa_tap_cc_line : "",
2627 ntor_cc_line ? ntor_cc_line : "",
2628 family_line,
2629 we_are_hibernating() ? "hibernating 1\n" : "",
2630 "hidden-service-dir\n");
2632 if (options->ContactInfo && strlen(options->ContactInfo)) {
2633 const char *ci = options->ContactInfo;
2634 if (strchr(ci, '\n') || strchr(ci, '\r'))
2635 ci = escaped(ci);
2636 smartlist_add_asprintf(chunks, "contact %s\n", ci);
2639 if (options->BridgeRelay) {
2640 const char *bd;
2641 if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
2642 bd = options->BridgeDistribution;
2643 } else {
2644 bd = "any";
2646 if (strchr(bd, '\n') || strchr(bd, '\r'))
2647 bd = escaped(bd);
2648 smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
2651 if (router->onion_curve25519_pkey) {
2652 char kbuf[128];
2653 base64_encode(kbuf, sizeof(kbuf),
2654 (const char *)router->onion_curve25519_pkey->public_key,
2655 CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
2656 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
2657 } else {
2658 /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
2659 log_err(LD_BUG, "A relay must have an ntor onion key");
2660 goto err;
2663 /* Write the exit policy to the end of 's'. */
2664 if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
2665 smartlist_add_strdup(chunks, "reject *:*\n");
2666 } else if (router->exit_policy) {
2667 char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
2669 if (!exit_policy)
2670 goto err;
2672 smartlist_add_asprintf(chunks, "%s\n", exit_policy);
2673 tor_free(exit_policy);
2676 if (router->ipv6_exit_policy) {
2677 char *p6 = write_short_policy(router->ipv6_exit_policy);
2678 if (p6 && strcmp(p6, "reject 1-65535")) {
2679 smartlist_add_asprintf(chunks,
2680 "ipv6-policy %s\n", p6);
2682 tor_free(p6);
2685 if (router_should_advertise_begindir(options,
2686 router->supports_tunnelled_dir_requests)) {
2687 smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
2690 /* Sign the descriptor with Ed25519 */
2691 if (emit_ed_sigs) {
2692 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
2693 crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
2694 ED_DESC_SIGNATURE_PREFIX,
2695 chunks, "", DIGEST_SHA256);
2696 ed25519_signature_t sig;
2697 char buf[ED25519_SIG_BASE64_LEN+1];
2698 if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
2699 signing_keypair) < 0)
2700 goto err;
2701 if (ed25519_signature_to_base64(buf, &sig) < 0)
2702 goto err;
2704 smartlist_add_asprintf(chunks, "%s\n", buf);
2707 /* Sign the descriptor with RSA */
2708 smartlist_add_strdup(chunks, "router-signature\n");
2710 crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
2713 char *sig;
2714 if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
2715 log_warn(LD_BUG, "Couldn't sign router descriptor");
2716 goto err;
2718 smartlist_add(chunks, sig);
2721 /* include a last '\n' */
2722 smartlist_add_strdup(chunks, "\n");
2724 output = smartlist_join_strings(chunks, "", 0, NULL);
2726 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2728 char *s_dup;
2729 const char *cp;
2730 routerinfo_t *ri_tmp;
2731 cp = s_dup = tor_strdup(output);
2732 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
2733 if (!ri_tmp) {
2734 log_err(LD_BUG,
2735 "We just generated a router descriptor we can't parse.");
2736 log_err(LD_BUG, "Descriptor was: <<%s>>", output);
2737 goto err;
2739 tor_free(s_dup);
2740 routerinfo_free(ri_tmp);
2742 #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
2744 goto done;
2746 err:
2747 tor_free(output); /* sets output to NULL */
2748 done:
2749 if (chunks) {
2750 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2751 smartlist_free(chunks);
2753 crypto_pk_free(rsa_pubkey);
2754 tor_free(address);
2755 tor_free(family_line);
2756 tor_free(onion_pkey);
2757 tor_free(identity_pkey);
2758 tor_free(extra_or_address);
2759 tor_free(ed_cert_line);
2760 tor_free(rsa_tap_cc_line);
2761 tor_free(ntor_cc_line);
2762 tor_free(extra_info_line);
2763 tor_free(proto_line);
2765 return output;
2769 * OR only: Given <b>router</b>, produce a string with its exit policy.
2770 * If <b>include_ipv4</b> is true, include IPv4 entries.
2771 * If <b>include_ipv6</b> is true, include IPv6 entries.
2773 char *
2774 router_dump_exit_policy_to_string(const routerinfo_t *router,
2775 int include_ipv4,
2776 int include_ipv6)
2778 if ((!router->exit_policy) || (router->policy_is_reject_star)) {
2779 return tor_strdup("reject *:*");
2782 return policy_dump_to_string(router->exit_policy,
2783 include_ipv4,
2784 include_ipv6);
2787 /** Load the contents of <b>filename</b>, find the last line starting with
2788 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2789 * the past or more than 1 hour in the future with respect to <b>now</b>,
2790 * and write the file contents starting with that line to *<b>out</b>.
2791 * Return 1 for success, 0 if the file does not exist or is empty, or -1
2792 * if the file does not contain a line matching these criteria or other
2793 * failure. */
2794 static int
2795 load_stats_file(const char *filename, const char *end_line, time_t now,
2796 char **out)
2798 int r = -1;
2799 char *fname = get_datadir_fname(filename);
2800 char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
2801 time_t written;
2802 switch (file_status(fname)) {
2803 case FN_FILE:
2804 /* X022 Find an alternative to reading the whole file to memory. */
2805 if ((contents = read_file_to_str(fname, 0, NULL))) {
2806 tmp = strstr(contents, end_line);
2807 /* Find last block starting with end_line */
2808 while (tmp) {
2809 start = tmp;
2810 tmp = strstr(tmp + 1, end_line);
2812 if (!start)
2813 goto notfound;
2814 if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
2815 goto notfound;
2816 strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
2817 if (parse_iso_time(timestr, &written) < 0)
2818 goto notfound;
2819 if (written < now - (25*60*60) || written > now + (1*60*60))
2820 goto notfound;
2821 *out = tor_strdup(start);
2822 r = 1;
2824 notfound:
2825 tor_free(contents);
2826 break;
2827 /* treat empty stats files as if the file doesn't exist */
2828 case FN_NOENT:
2829 case FN_EMPTY:
2830 r = 0;
2831 break;
2832 case FN_ERROR:
2833 case FN_DIR:
2834 default:
2835 break;
2837 tor_free(fname);
2838 return r;
2841 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2842 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2843 * success, negative on failure. */
2845 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
2846 crypto_pk_t *ident_key,
2847 const ed25519_keypair_t *signing_keypair)
2849 const or_options_t *options = get_options();
2850 char identity[HEX_DIGEST_LEN+1];
2851 char published[ISO_TIME_LEN+1];
2852 char digest[DIGEST_LEN];
2853 char *bandwidth_usage;
2854 int result;
2855 static int write_stats_to_extrainfo = 1;
2856 char sig[DIROBJ_MAX_SIG_LEN+1];
2857 char *s = NULL, *pre, *contents, *cp, *s_dup = NULL;
2858 time_t now = time(NULL);
2859 smartlist_t *chunks = smartlist_new();
2860 extrainfo_t *ei_tmp = NULL;
2861 const int emit_ed_sigs = signing_keypair &&
2862 extrainfo->cache_info.signing_key_cert;
2863 char *ed_cert_line = NULL;
2865 base16_encode(identity, sizeof(identity),
2866 extrainfo->cache_info.identity_digest, DIGEST_LEN);
2867 format_iso_time(published, extrainfo->cache_info.published_on);
2868 bandwidth_usage = rep_hist_get_bandwidth_lines();
2869 if (emit_ed_sigs) {
2870 if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
2871 !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
2872 &signing_keypair->pubkey)) {
2873 log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
2874 "mismatched ed25519 key chain %d",
2875 extrainfo->cache_info.signing_key_cert->signing_key_included);
2876 goto err;
2878 char ed_cert_base64[256];
2879 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2880 (const char*)extrainfo->cache_info.signing_key_cert->encoded,
2881 extrainfo->cache_info.signing_key_cert->encoded_len,
2882 BASE64_ENCODE_MULTILINE) < 0) {
2883 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2884 goto err;
2886 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2887 "-----BEGIN ED25519 CERT-----\n"
2888 "%s"
2889 "-----END ED25519 CERT-----\n", ed_cert_base64);
2890 } else {
2891 ed_cert_line = tor_strdup("");
2894 tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n%s",
2895 extrainfo->nickname, identity,
2896 ed_cert_line,
2897 published, bandwidth_usage);
2898 smartlist_add(chunks, pre);
2900 if (geoip_is_loaded(AF_INET))
2901 smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
2902 geoip_db_digest(AF_INET));
2903 if (geoip_is_loaded(AF_INET6))
2904 smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
2905 geoip_db_digest(AF_INET6));
2907 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
2908 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
2909 if (options->DirReqStatistics &&
2910 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
2911 "dirreq-stats-end", now, &contents) > 0) {
2912 smartlist_add(chunks, contents);
2914 if (options->HiddenServiceStatistics &&
2915 load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
2916 "hidserv-stats-end", now, &contents) > 0) {
2917 smartlist_add(chunks, contents);
2919 if (options->EntryStatistics &&
2920 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
2921 "entry-stats-end", now, &contents) > 0) {
2922 smartlist_add(chunks, contents);
2924 if (options->CellStatistics &&
2925 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
2926 "cell-stats-end", now, &contents) > 0) {
2927 smartlist_add(chunks, contents);
2929 if (options->ExitPortStatistics &&
2930 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
2931 "exit-stats-end", now, &contents) > 0) {
2932 smartlist_add(chunks, contents);
2934 if (options->ConnDirectionStatistics &&
2935 load_stats_file("stats"PATH_SEPARATOR"conn-stats",
2936 "conn-bi-direct", now, &contents) > 0) {
2937 smartlist_add(chunks, contents);
2941 if (options->PaddingStatistics) {
2942 contents = rep_hist_get_padding_count_lines();
2943 if (contents)
2944 smartlist_add(chunks, contents);
2947 /* Add information about the pluggable transports we support. */
2948 if (options->ServerTransportPlugin) {
2949 char *pluggable_transports = pt_get_extra_info_descriptor_string();
2950 if (pluggable_transports)
2951 smartlist_add(chunks, pluggable_transports);
2954 if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
2955 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
2956 if (bridge_stats) {
2957 smartlist_add_strdup(chunks, bridge_stats);
2961 if (emit_ed_sigs) {
2962 char sha256_digest[DIGEST256_LEN];
2963 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
2964 crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
2965 ED_DESC_SIGNATURE_PREFIX,
2966 chunks, "", DIGEST_SHA256);
2967 ed25519_signature_t ed_sig;
2968 char buf[ED25519_SIG_BASE64_LEN+1];
2969 if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
2970 signing_keypair) < 0)
2971 goto err;
2972 if (ed25519_signature_to_base64(buf, &ed_sig) < 0)
2973 goto err;
2975 smartlist_add_asprintf(chunks, "%s\n", buf);
2978 smartlist_add_strdup(chunks, "router-signature\n");
2979 s = smartlist_join_strings(chunks, "", 0, NULL);
2981 while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
2982 /* So long as there are at least two chunks (one for the initial
2983 * extra-info line and one for the router-signature), we can keep removing
2984 * things. */
2985 if (smartlist_len(chunks) > 2) {
2986 /* We remove the next-to-last element (remember, len-1 is the last
2987 element), since we need to keep the router-signature element. */
2988 int idx = smartlist_len(chunks) - 2;
2989 char *e = smartlist_get(chunks, idx);
2990 smartlist_del_keeporder(chunks, idx);
2991 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
2992 "with statistics that exceeds the 50 KB "
2993 "upload limit. Removing last added "
2994 "statistics.");
2995 tor_free(e);
2996 tor_free(s);
2997 s = smartlist_join_strings(chunks, "", 0, NULL);
2998 } else {
2999 log_warn(LD_BUG, "We just generated an extra-info descriptors that "
3000 "exceeds the 50 KB upload limit.");
3001 goto err;
3005 memset(sig, 0, sizeof(sig));
3006 if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
3007 router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
3008 ident_key) < 0) {
3009 log_warn(LD_BUG, "Could not append signature to extra-info "
3010 "descriptor.");
3011 goto err;
3013 smartlist_add_strdup(chunks, sig);
3014 tor_free(s);
3015 s = smartlist_join_strings(chunks, "", 0, NULL);
3017 cp = s_dup = tor_strdup(s);
3018 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
3019 if (!ei_tmp) {
3020 if (write_stats_to_extrainfo) {
3021 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3022 "with statistics that we can't parse. Not "
3023 "adding statistics to this or any future "
3024 "extra-info descriptors.");
3025 write_stats_to_extrainfo = 0;
3026 result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
3027 signing_keypair);
3028 goto done;
3029 } else {
3030 log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
3031 "can't parse.");
3032 goto err;
3036 *s_out = s;
3037 s = NULL; /* prevent free */
3038 result = 0;
3039 goto done;
3041 err:
3042 result = -1;
3044 done:
3045 tor_free(s);
3046 SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
3047 smartlist_free(chunks);
3048 tor_free(s_dup);
3049 tor_free(ed_cert_line);
3050 extrainfo_free(ei_tmp);
3051 tor_free(bandwidth_usage);
3053 return result;
3056 /** Forget that we have issued any router-related warnings, so that we'll
3057 * warn again if we see the same errors. */
3058 void
3059 router_reset_warnings(void)
3061 if (warned_nonexistent_family) {
3062 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3063 smartlist_clear(warned_nonexistent_family);
3067 /** Release all static resources held in router.c */
3068 void
3069 router_free_all(void)
3071 crypto_pk_free(onionkey);
3072 crypto_pk_free(lastonionkey);
3073 crypto_pk_free(server_identitykey);
3074 crypto_pk_free(client_identitykey);
3076 tor_mutex_free(key_lock);
3077 routerinfo_free(desc_routerinfo);
3078 extrainfo_free(desc_extrainfo);
3079 crypto_pk_free(authority_signing_key);
3080 authority_cert_free(authority_key_certificate);
3081 crypto_pk_free(legacy_signing_key);
3082 authority_cert_free(legacy_key_certificate);
3084 memwipe(&curve25519_onion_key, 0, sizeof(curve25519_onion_key));
3085 memwipe(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
3087 if (warned_nonexistent_family) {
3088 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3089 smartlist_free(warned_nonexistent_family);
3092 /* From the given RSA key object, convert it to ASN-1 encoded format and set
3093 * the newly allocated object in onion_pkey_out. The length of the key is set
3094 * in onion_pkey_len_out. */
3095 void
3096 router_set_rsa_onion_pkey(const crypto_pk_t *pk, char **onion_pkey_out,
3097 size_t *onion_pkey_len_out)
3099 int len;
3100 char buf[1024];
3102 tor_assert(pk);
3103 tor_assert(onion_pkey_out);
3104 tor_assert(onion_pkey_len_out);
3106 len = crypto_pk_asn1_encode(pk, buf, sizeof(buf));
3107 if (BUG(len < 0)) {
3108 goto done;
3111 *onion_pkey_out = tor_memdup(buf, len);
3112 *onion_pkey_len_out = len;
3114 done:
3115 return;
3118 /* From an ASN-1 encoded onion pkey, return a newly allocated RSA key object.
3119 * It is the caller responsability to free the returned object.
3121 * Return NULL if the pkey is NULL, malformed or if the length is 0. */
3122 crypto_pk_t *
3123 router_get_rsa_onion_pkey(const char *pkey, size_t pkey_len)
3125 if (!pkey || pkey_len == 0) {
3126 return NULL;
3128 return crypto_pk_asn1_decode(pkey, pkey_len);