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 */
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"
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.)
86 /************************************************************/
89 * Key management: ORs only.
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
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
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
133 /** Return a readonly string with human readable description
137 routerinfo_err_to_string(int 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().
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 */
185 tor_mutex_acquire(key_lock
);
186 crypto_pk_free(onionkey
);
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. */
197 tor_assert(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.
206 dup_onion_keys(crypto_pk_t
**key
, crypto_pk_t
**last
)
210 tor_mutex_acquire(key_lock
);
212 *key
= crypto_pk_copy_full(onionkey
);
216 *last
= crypto_pk_copy_full(lastonionkey
);
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
226 * This function does not perform any grace period checks for the old onion
230 expire_old_onion_keys(void)
234 tor_mutex_acquire(key_lock
);
236 /* Free lastonionkey and set it to NULL. */
238 crypto_pk_free(lastonionkey
);
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
));
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
));
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. */
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
)) {
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
)) {
293 last_curve25519_onion_key
.pubkey
.public_key
,
294 tor_memdup(&last_curve25519_onion_key
,
295 sizeof(curve25519_keypair_t
)));
300 /** Helper used to deallocate a di_digest256_map_t returned by
301 * construct_ntor_key_map. */
303 ntor_key_map_free_helper(void *arg
)
305 curve25519_keypair_t
*k
= arg
;
306 memwipe(k
, 0, sizeof(*k
));
309 /** Release all storage from a keymap returned by construct_ntor_key_map. */
311 ntor_key_map_free_(di_digest256_map_t
*map
)
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.
323 get_onion_key_set_at(void)
325 return onionkey_set_at
;
328 /** Set the current server identity key to <b>k</b>.
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.");
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. */
345 assert_identity_keys_ok(void)
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
));
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.
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
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>.
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.
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. */
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
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. */
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,
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.
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
;
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
))
463 if (!(prkey
= crypto_pk_new())) {
464 log_err(LD_GENERAL
,"Error constructing rotated onion key");
467 if (crypto_pk_generate_key(prkey
)) {
468 log_err(LD_BUG
,"Error generating onion key");
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
);
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)
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
))
486 if (curve25519_keypair_write_to_file(&new_curve25519_keypair
, fname
,
488 log_err(LD_FS
,"Couldn't write curve25519 onion key to \"%s\".",fname
);
491 log_info(LD_GENERAL
, "Rotating onion key");
492 tor_mutex_acquire(key_lock
);
493 crypto_pk_free(lastonionkey
);
494 lastonionkey
= onionkey
;
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
));
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);
507 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
509 crypto_pk_free(prkey
);
511 memwipe(&new_curve25519_keypair
, 0, sizeof(new_curve25519_keypair
));
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.
520 log_new_relay_greeting(void)
522 static int already_logged
= 0;
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"
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. */
542 init_curve25519_keypair_from_file(curve25519_keypair_t
*keys_out
,
548 switch (file_status(fname
)) {
551 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
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() */
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. */
569 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
571 if (curve25519_keypair_generate(keys_out
, 1) < 0)
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
));
580 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
586 if (curve25519_keypair_read_from_file(keys_out
, &tag_in
, fname
) < 0) {
587 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
591 if (!tag_in
|| strcmp(tag_in
, tag
)) {
592 tor_log(severity
, LD_GENERAL
,"Unexpected tag %s on private key.",
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. */
614 load_authority_keyset(int legacy
, crypto_pk_t
**key_out
,
615 authority_cert_t
**cert_out
)
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
);
627 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
631 fname
= get_keydir_fname(
632 legacy
? "legacy_certificate" : "authority_certificate");
633 cert
= read_file_to_str(fname
, 0, NULL
);
635 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
639 parsed
= authority_cert_parse_from_string(cert
, &eos
);
641 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
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 "
650 crypto_pk_free(*key_out
);
651 authority_cert_free(*cert_out
);
653 *key_out
= signing_key
;
662 crypto_pk_free(signing_key
);
663 authority_cert_free(parsed
);
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. */
671 init_v3_authority_keys(void)
673 if (load_authority_keyset(0, &authority_signing_key
,
674 &authority_key_certificate
)<0)
677 if (get_options()->V3AuthUseLegacyKey
&&
678 load_authority_keyset(1, &legacy_signing_key
,
679 &legacy_key_certificate
)<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. */
688 v3_authority_check_key_expiry(void)
691 static time_t last_warned
= 0;
692 int badness
, time_left
, warn_interval
;
693 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
697 expires
= authority_key_certificate
->expires
;
698 time_left
= (int)( expires
- now
);
699 if (time_left
<= 0) {
701 warn_interval
= 60*60;
702 } else if (time_left
<= 24*60*60) {
704 warn_interval
= 60*60;
705 } else if (time_left
<= 24*60*60*7) {
707 warn_interval
= 24*60*60;
708 } else if (time_left
<= 24*60*60*30) {
710 warn_interval
= 24*60*60*5;
715 if (last_warned
+ warn_interval
> now
)
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));
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));
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>.
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)
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.) */
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,
813 router_write_fingerprint(int hashed
)
815 char *keydir
= NULL
, *cp
= NULL
;
816 const char *fname
= hashed
? "hashed-fingerprint" :
818 char fingerprint
[FINGERPRINT_LEN
+1];
819 const or_options_t
*options
= get_options();
820 char *fingerprint_line
= NULL
;
823 keydir
= get_datadir_fname(fname
);
824 log_info(LD_GENERAL
,"Dumping %sfingerprint to \"%s\"...",
825 hashed
? "hashed " : "", keydir
);
827 if (crypto_pk_get_fingerprint(get_server_identity_key(),
828 fingerprint
, 0) < 0) {
829 log_err(LD_GENERAL
,"Error computing fingerprint");
833 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
835 log_err(LD_GENERAL
,"Error computing hashed fingerprint");
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 " : "");
853 log_notice(LD_GENERAL
, "Your Tor %s identity key fingerprint is '%s %s'",
854 hashed
? "bridge's hashed" : "server's", options
->Nickname
,
861 tor_free(fingerprint_line
);
866 init_keys_common(void)
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.");
884 init_keys_client(void)
887 if (init_keys_common() < 0)
890 if (!(prkey
= crypto_pk_new()))
892 if (crypto_pk_generate_key(prkey
)) {
893 crypto_pk_free(prkey
);
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.");
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.
915 char digest
[DIGEST_LEN
];
916 char v3_digest
[DIGEST_LEN
];
917 const or_options_t
*options
= get_options();
919 time_t now
= time(NULL
);
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)
932 if (create_keys_directory(options
) < 0)
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.");
944 cert
= get_my_v3_authority_cert();
946 if (crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
948 log_err(LD_BUG
, "Couldn't compute my v3 authority identity key "
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
);
962 if (!prkey
) return -1;
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
970 if (public_server_mode(options
)) {
971 set_client_identity_key(crypto_pk_dup_key(prkey
)); /* set above */
973 if (!(prkey
= crypto_pk_new()))
975 if (crypto_pk_generate_key(prkey
)) {
976 crypto_pk_free(prkey
);
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)
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
);
992 log_new_relay_greeting();
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
1003 onionkey_set_at
= state
->LastRotatedOnionKey
;
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);
1021 lastonionkey
= prkey
;
1026 /* 2b. Load curve25519 onion keys. */
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");
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");
1048 /* 3. Initialize link key and TLS context. */
1049 if (router_initialize_tls_context() < 0) {
1050 log_err(LD_GENERAL
,"Error initializing TLS context");
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");
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
;
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");
1073 was_router_added_t added
;
1074 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
, NULL
);
1076 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
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>");
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");
1103 if (!public_server_mode(options
) && router_write_fingerprint(1)) {
1104 log_err(LD_FS
, "Error writing hashed fingerprint to file");
1108 if (!authdir_mode(options
))
1110 /* 6. [authdirserver only] load approved-routers file */
1111 if (dirserv_load_fingerprint_file() < 0) {
1112 log_err(LD_GENERAL
,"Error loading fingerprints");
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
);
1123 ds
= trusted_dir_server_new(options
->Nickname
, NULL
,
1124 router_get_advertised_dir_port(options
, 0),
1125 router_get_advertised_or_port(options
),
1131 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
1132 "couldn't add ourselves to the authority list. Failing.");
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)",
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,
1156 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
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
1173 router_has_bandwidth_to_be_dirserver(const or_options_t
*options
)
1175 if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRSERVER
) {
1178 if (options
->RelayBandwidthRate
> 0 &&
1179 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRSERVER
) {
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.
1193 router_should_be_dirserver(const or_options_t
*options
, int dir_port
)
1195 static int advertising
=1; /* start out assuming we will advertise */
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
);
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
),
1221 acc_bytes
= options
->AccountingMax
;
1222 if (get_options()->AccountingRule
== ACCT_SUM
)
1225 acc_bytes
/ interval_length
) {
1227 reason
= "AccountingMax enabled";
1229 } else if (! router_has_bandwidth_to_be_dirserver(options
)) {
1230 /* if we're advertising a small amount */
1232 reason
= "BandwidthRate under 50KB";
1235 if (advertising
!= new_choice
) {
1236 if (new_choice
== 1) {
1238 log_notice(LD_DIR
, "Advertising DirPort as %d", dir_port
);
1240 log_notice(LD_DIR
, "Advertising directory service support");
1243 log_notice(LD_DIR
, "Not advertising Dir%s (Reason: %s)",
1244 dir_port
? "Port" : "ectory Service support", reason
);
1246 advertising
= new_choice
;
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
1256 * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1259 * Log a helpful message if we change our mind about whether to publish.
1262 decide_to_advertise_dir_impl(const or_options_t
*options
,
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
)
1273 if (authdir_mode(options
)) /* always publish */
1275 if (net_is_disabled())
1277 if (dir_port
&& !router_get_advertised_dir_port(options
, dir_port
))
1279 if (supports_tunnelled_dir_requests
&&
1280 !router_get_advertised_or_port(options
))
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.
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
;
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
1327 * - We have the PublishServerDescriptor option set to non-empty
1329 * - We have ORPort set
1331 * - We believe our ORPort and DirPort (if present) are reachable from
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.
1338 decide_if_publishable_server(void)
1340 const or_options_t
*options
= get_options();
1342 if (options
->ClientOnly
)
1344 if (options
->PublishServerDescriptor_
== NO_DIRINFO
)
1346 if (!server_mode(options
))
1348 if (authdir_mode(options
))
1350 if (!router_get_advertised_or_port(options
))
1352 if (!check_whether_orport_reachable(options
))
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. */
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.
1371 consider_publishable_server(int force
)
1375 if (!server_mode(get_options()))
1378 rebuilt
= router_rebuild_descriptor(0);
1379 if (decide_if_publishable_server()) {
1380 set_server_advertised(1);
1382 router_upload_dir_desc_to_dirservers(force
);
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. */
1393 router_get_active_listener_port_by_type_af(int listener_type
,
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
) {
1404 } SMARTLIST_FOREACH_END(conn
);
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".
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.
1422 router_get_advertised_or_port_by_af(const or_options_t
*options
,
1425 int port
= get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER
,
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
,
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". */
1444 router_get_advertised_dir_port(const or_options_t
*options
, uint16_t dirport
)
1446 int dirport_configured
= get_primary_dir_port();
1449 if (!dirport_configured
)
1452 if (dirport_configured
== CFG_AUTO_PORT
)
1453 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER
,
1456 return dirport_configured
;
1460 * OR descriptor generation.
1463 /** My routerinfo. */
1464 static routerinfo_t
*desc_routerinfo
= NULL
;
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
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.
1483 router_upload_dir_desc_to_dirservers(int force
)
1485 const routerinfo_t
*ri
;
1488 size_t desc_len
, extra_len
= 0, total_len
;
1489 dirinfo_type_t auth
= get_options()->PublishServerDescriptor_
;
1491 ri
= router_get_my_routerinfo();
1493 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1496 ei
= router_get_my_extrainfo();
1497 if (auth
== NO_DIRINFO
)
1499 if (!force
&& !desc_needs_upload
)
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
);
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
);
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 */
1535 /* make sure it's resolved to something. this way we can't get a
1537 if (tor_addr_is_null(addr
))
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
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
;
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
;
1561 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1562 * have a descriptor */
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 */
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. */
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();
1598 return tor_memeq(digest
,
1599 ei
->cache_info
.signed_descriptor_digest
,
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())) {
1627 *err
= TOR_ROUTERINFO_ERROR_NOT_A_SERVER
;
1632 if (!desc_clean_since
) {
1633 int rebuild_err
= router_rebuild_descriptor(0);
1634 if (rebuild_err
< 0) {
1642 if (!desc_routerinfo
) {
1644 *err
= TOR_ROUTERINFO_ERROR_DESC_REBUILDING
;
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.
1659 router_get_my_descriptor(void)
1662 const routerinfo_t
*me
= router_get_my_routerinfo();
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
);
1673 /** Return the extrainfo document for this OR, or NULL if we have none.
1674 * Rebuilt it (and the server descriptor) if necessary. */
1676 router_get_my_extrainfo(void)
1678 if (!server_mode(get_options()))
1680 if (router_rebuild_descriptor(0))
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. */
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.
1708 router_pick_published_address
,(const or_options_t
*options
, uint32_t *addr
,
1711 /* First, check the cached output from resolve_my_address(). */
1712 *addr
= get_last_resolved_addr();
1716 /* Second, consider doing a resolve attempt right here. */
1718 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
, NULL
) >= 0) {
1719 log_info(LD_CONFIG
,"Success: chose address '%s'.", fmt_addr32(*addr
));
1724 /* Third, check the cached output from router_new_address_suggestion(). */
1725 if (router_guess_address_from_dir_headers(addr
) >= 0)
1728 /* We have no useful cached answers. Return failure. */
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. */
1736 router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr
,
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
,
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(
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
?
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> "
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
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
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
1797 * The message tells operators to configure an ORPort and DirPort that match
1798 * the Address (using NoListen if needed).
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
1817 router_build_fresh_descriptor(routerinfo_t
**r
, extrainfo_t
**e
)
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
);
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
) {
1867 char addrbuf
[TOR_ADDR_BUF_LEN
];
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
);
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
);
1909 policies_parse_exit_policy_from_options(options
,ri
->addr
,&ri
->ipv6_addr
,
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
);
1919 ri
->ipv6_exit_policy
= parse_short_policy(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 */
1934 member
= node_get_by_nickname(name
, 0);
1936 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1937 if (!smartlist_contains_string(warned_nonexistent_family
, name
) &&
1938 !is_legal_hexdigest(name
)) {
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
);
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
);
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 */
1957 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
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
,
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.");
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
,
2000 /* Now finish the router descriptor. */
2002 memcpy(ri
->cache_info
.extra_info_digest
,
2003 ei
->cache_info
.signed_descriptor_digest
,
2005 memcpy(ri
->cache_info
.extra_info_digest256
,
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(),
2015 get_current_curve25519_keypair(),
2016 get_master_signing_keypair())) ) {
2017 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
2018 routerinfo_free(ri
);
2020 return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE
;
2022 ri
->cache_info
.signed_descriptor_len
=
2023 strlen(ri
->cache_info
.signed_descriptor_body
);
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;
2034 ei
->cache_info
.send_unencrypted
= 0;
2036 ri
->cache_info
.send_unencrypted
= 1;
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
);
2047 routerinfo_incompatible_with_extrainfo(ri
->identity_pkey
, ei
,
2048 &ri
->cache_info
, NULL
));
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
)
2067 const or_options_t
*options
= get_options();
2069 if (desc_clean_since
&& !force
)
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
);
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();
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
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
)
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");
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
);
2139 rs
= networkstatus_vote_find_entry(ns
, server_identitykey_digest
);
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. */
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. */
2181 check_descriptor_bandwidth_changed(time_t now
)
2183 static time_t last_changed
= 0;
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
)
2192 const routerinfo_t
*my_ri
= router_get_my_routerinfo();
2197 prev
= my_ri
->bandwidthcapacity
;
2199 /* Consider ourselves to have zero bandwidth if we're hibernating or
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");
2215 /** Note at log level severity that our best guess of address has changed from
2216 * <b>prev</b> to <b>cur</b>. */
2218 log_addr_has_changed(int severity
,
2219 const tor_addr_t
*prev
,
2220 const tor_addr_t
*cur
,
2223 char addrbuf_prev
[TOR_ADDR_BUF_LEN
];
2224 char addrbuf_cur
[TOR_ADDR_BUF_LEN
];
2226 if (BUG(!server_mode(get_options())))
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
);
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. */
2249 check_descriptor_ipaddress_changed(time_t now
)
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();
2259 if (my_ri
== NULL
) /* make sure routerinfo exists */
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.");
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
);
2283 ip_address_changed(0);
2289 /** The most recently guessed value of our IP address, based on directory
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. */
2298 router_new_address_suggestion(const char *suggestion
,
2299 const dir_connection_t
*d_conn
)
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
));
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
);
2320 cur
= get_last_resolved_addr();
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
2328 if (tor_addr_is_internal(&addr
, 0)) {
2329 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
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.",
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
2343 if (!tor_addr_eq(&last_guessed_ip
, &addr
)) {
2344 control_event_server_status(LOG_NOTICE
,
2345 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
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()
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. */
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
);
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.
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.
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!");
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
);
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");
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!");
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");
2457 tor_asprintf(&ed_cert_line
, "identity-ed25519\n"
2458 "-----BEGIN ED25519 CERT-----\n"
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!");
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!");
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
) {
2487 make_tap_onion_key_crosscert(tap_key
,
2488 &router
->cache_info
.signing_key_cert
->signing_key
,
2489 router
->identity_pkey
,
2492 log_warn(LD_BUG
,"make_tap_onion_key_crosscert failed!");
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!");
2504 tor_asprintf(&rsa_tap_cc_line
,
2505 "onion-key-crosscert\n"
2506 "-----BEGIN CROSSCERT-----\n"
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
) {
2516 /* XXXX Base the expiration date on the actual onion key expiration time?*/
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
);
2523 log_warn(LD_BUG
,"make_ntor_onion_key_crosscert failed!");
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
);
2535 tor_cert_free(cert
);
2537 tor_asprintf(&ntor_cc_line
,
2538 "ntor-onion-key-crosscert %d\n"
2539 "-----BEGIN ED25519 CERT-----\n"
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
,
2550 tor_asprintf(&family_line
, "family %s\n", family
);
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
);
2566 tor_asprintf(&extra_info_line
, "extra-info-digest %s\n",
2571 if (router
->ipv6_orport
&&
2572 tor_addr_family(&router
->ipv6_addr
) == AF_INET6
) {
2573 char addr
[TOR_ADDR_BUF_LEN
];
2575 a
= tor_addr_to_str(addr
, &router
->ipv6_addr
, sizeof(addr
), 1);
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
);
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"
2602 "bandwidth %d %d %d\n"
2611 router_should_advertise_dirport(options
, router
->dir_port
),
2612 ed_cert_line
? ed_cert_line
: "",
2613 extra_or_address
? extra_or_address
: "",
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
: "",
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'))
2636 smartlist_add_asprintf(chunks
, "contact %s\n", ci
);
2639 if (options
->BridgeRelay
) {
2641 if (options
->BridgeDistribution
&& strlen(options
->BridgeDistribution
)) {
2642 bd
= options
->BridgeDistribution
;
2646 if (strchr(bd
, '\n') || strchr(bd
, '\r'))
2648 smartlist_add_asprintf(chunks
, "bridge-distribution-request %s\n", bd
);
2651 if (router
->onion_curve25519_pkey
) {
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
);
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");
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);
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
);
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 */
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)
2701 if (ed25519_signature_to_base64(buf
, &sig
) < 0)
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
);
2714 if (!(sig
= router_get_dirobj_signature(digest
, DIGEST_LEN
, ident_key
))) {
2715 log_warn(LD_BUG
, "Couldn't sign router descriptor");
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
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
);
2735 "We just generated a router descriptor we can't parse.");
2736 log_err(LD_BUG
, "Descriptor was: <<%s>>", output
);
2740 routerinfo_free(ri_tmp
);
2742 #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
2747 tor_free(output
); /* sets output to NULL */
2750 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2751 smartlist_free(chunks
);
2753 crypto_pk_free(rsa_pubkey
);
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
);
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.
2774 router_dump_exit_policy_to_string(const routerinfo_t
*router
,
2778 if ((!router
->exit_policy
) || (router
->policy_is_reject_star
)) {
2779 return tor_strdup("reject *:*");
2782 return policy_dump_to_string(router
->exit_policy
,
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
2795 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
2799 char *fname
= get_datadir_fname(filename
);
2800 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
2802 switch (file_status(fname
)) {
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 */
2810 tmp
= strstr(tmp
+ 1, end_line
);
2814 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
2816 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
2817 if (parse_iso_time(timestr
, &written
) < 0)
2819 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
2821 *out
= tor_strdup(start
);
2827 /* treat empty stats files as if the file doesn't exist */
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
;
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();
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
);
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!");
2886 tor_asprintf(&ed_cert_line
, "identity-ed25519\n"
2887 "-----BEGIN ED25519 CERT-----\n"
2889 "-----END ED25519 CERT-----\n", ed_cert_base64
);
2891 ed_cert_line
= tor_strdup("");
2894 tor_asprintf(&pre
, "extra-info %s %s\n%spublished %s\n%s",
2895 extrainfo
->nickname
, identity
,
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();
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
);
2957 smartlist_add_strdup(chunks
, bridge_stats
);
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)
2972 if (ed25519_signature_to_base64(buf
, &ed_sig
) < 0)
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
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 "
2997 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2999 log_warn(LD_BUG
, "We just generated an extra-info descriptors that "
3000 "exceeds the 50 KB upload limit.");
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
,
3009 log_warn(LD_BUG
, "Could not append signature to extra-info "
3013 smartlist_add_strdup(chunks
, sig
);
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
);
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
,
3030 log_warn(LD_BUG
, "We just generated an extrainfo descriptor we "
3037 s
= NULL
; /* prevent free */
3046 SMARTLIST_FOREACH(chunks
, char *, chunk
, tor_free(chunk
));
3047 smartlist_free(chunks
);
3049 tor_free(ed_cert_line
);
3050 extrainfo_free(ei_tmp
);
3051 tor_free(bandwidth_usage
);
3056 /** Forget that we have issued any router-related warnings, so that we'll
3057 * warn again if we see the same errors. */
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 */
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. */
3096 router_set_rsa_onion_pkey(const crypto_pk_t
*pk
, char **onion_pkey_out
,
3097 size_t *onion_pkey_len_out
)
3103 tor_assert(onion_pkey_out
);
3104 tor_assert(onion_pkey_len_out
);
3106 len
= crypto_pk_asn1_encode(pk
, buf
, sizeof(buf
));
3111 *onion_pkey_out
= tor_memdup(buf
, len
);
3112 *onion_pkey_len_out
= len
;
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. */
3123 router_get_rsa_onion_pkey(const char *pkey
, size_t pkey_len
)
3125 if (!pkey
|| pkey_len
== 0) {
3128 return crypto_pk_asn1_decode(pkey
, pkey_len
);