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