Tor 0.4.9.1-alpha-dev
router.c
Go to the documentation of this file.
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-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7#define ROUTER_PRIVATE
8
9#include "core/or/or.h"
10#include "app/config/config.h"
13#include "app/main/main.h"
17#include "core/or/policies.h"
18#include "core/or/protover.h"
38#include "feature/relay/dns.h"
46#include "lib/geoip/geoip.h"
56#include "lib/osinfo/uname.h"
57#include "lib/tls/tortls.h"
59
61
63#include "core/or/port_cfg_st.h"
72
73/**
74 * \file router.c
75 * \brief Miscellaneous relay functionality, including RSA key maintenance,
76 * generating and uploading server descriptors, picking an address to
77 * advertise, and so on.
78 *
79 * This module handles the job of deciding whether we are a Tor relay, and if
80 * so what kind. (Mostly through functions like server_mode() that inspect an
81 * or_options_t, but in some cases based on our own capabilities, such as when
82 * we are deciding whether to be a directory cache in
83 * router_has_bandwidth_to_be_dirserver().)
84 *
85 * Also in this module are the functions to generate our own routerinfo_t and
86 * extrainfo_t, and to encode those to signed strings for upload to the
87 * directory authorities.
88 *
89 * This module also handles key maintenance for RSA and Curve25519-ntor keys,
90 * and for our TLS context. (These functions should eventually move to
91 * routerkeys.c along with the code that handles Ed25519 keys now.)
92 **/
93
94/************************************************************/
95
96/*****
97 * Key management: ORs only.
98 *****/
99
100/** Private keys for this OR. There is also an SSL key managed by tortls.c.
101 */
103static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
104/** Current private onionskin decryption key: used to decode CREATE cells. */
106/** Previous private onionskin decryption key: used to decode CREATE cells
107 * generated by clients that have an older version of our descriptor. */
109/** Current private ntor secret key: used to perform the ntor handshake. */
111/** Previous private ntor secret key: used to perform the ntor handshake
112 * with clients that have an older version of our descriptor. */
114/** Private server "identity key": used to sign directory info and TLS
115 * certificates. Never changes. */
117/** Digest of server_identitykey. */
119/** Private client "identity key": used to sign bridges' and clients'
120 * outbound TLS certificates. Regenerated on startup and on IP address
121 * change. */
123/** Signing key used for v3 directory material; only set for authorities. */
125/** Key certificate to authenticate v3 directory material; only set for
126 * authorities. */
128
129/** For emergency V3 authority key migration: An extra signing key that we use
130 * with our old (obsolete) identity key for a while. */
132/** For emergency V3 authority key migration: An extra certificate to
133 * authenticate legacy_signing_key with our obsolete identity key.*/
135
136/* (Note that v3 authorities also have a separate "authority identity key",
137 * but this key is never actually loaded by the Tor process. Instead, it's
138 * used by tor-gencert to sign new signing keys and make new key
139 * certificates. */
140
141/** Indicate if the IPv6 address should be omitted from the descriptor when
142 * publishing it. This can happen if the IPv4 is reachable but the
143 * auto-discovered IPv6 is not. We still publish the descriptor.
144 *
145 * Only relays should look at this and only for their descriptor.
146 *
147 * XXX: The real harder fix is to never put in the routerinfo_t a non
148 * reachable address and instead use the last resolved address cache to do
149 * reachability test or anything that has to do with what address tor thinks
150 * it has. */
151static bool omit_ipv6_on_publish = false;
152
153/** Return a readonly string with human readable description
154 * of <b>err</b>.
155 */
156const char *
158{
159 switch (err) {
160 case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
161 return "No known exit address yet";
162 case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
163 return "Cannot parse descriptor";
164 case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
165 return "Not running in server mode";
166 case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
167 return "Key digest failed";
168 case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
169 return "Cannot generate descriptor";
170 case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
171 return "Descriptor still rebuilding - not ready yet";
172 case TOR_ROUTERINFO_ERROR_INTERNAL_BUG:
173 return "Internal bug, see logs for details";
174 }
175
176 log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
177 tor_assert_unreached();
178
179 return "Unknown error";
180}
181
182/** Return true if we expect given error to be transient.
183 * Return false otherwise.
184 */
185int
187{
188 /**
189 * For simplicity, we consider all errors other than
190 * "not a server" transient - see discussion on
191 * https://bugs.torproject.org/tpo/core/tor/27034.
192 */
193 return err != TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
194}
195
196/** Replace the current onion key with <b>k</b>. Does not affect
197 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
198 */
199static void
201{
203 /* k is already our onion key; free it and return */
204 crypto_pk_free(k);
205 return;
206 }
208 crypto_pk_free(onionkey);
209 onionkey = k;
211 mark_my_descriptor_dirty("set onion key");
212}
213
214/** Return the current TAP onion key. Requires that the onion key has been
215 * loaded or generated.
216 *
217 * Note that this key is no longer used for anything; we only keep it around
218 * because (as of June 2024) other Tor instances all expect to find it in
219 * our routerdescs.
220 **/
223{
225 return onionkey;
226}
227
228/**
229 * Return true iff we should include our TAP onion key in our router
230 * descriptor.
231 */
232static int
234{
235#define SHOULD_PUBLISH_TAP_MIN 0
236#define SHOULD_PUBLISH_TAP_MAX 1
237 /* Note that we err on the side of publishing. */
238#define SHOULD_PUBLISH_TAP_DFLT 1
239
240 return networkstatus_get_param(NULL,
241 "publish-dummy-tap-key",
242 SHOULD_PUBLISH_TAP_DFLT,
243 SHOULD_PUBLISH_TAP_MIN,
244 SHOULD_PUBLISH_TAP_MAX);
245}
246
247/** Store a full copy of the current onion key into *<b>key</b>, and a full
248 * copy of the most recent onion key into *<b>last</b>. Store NULL into
249 * a pointer if the corresponding key does not exist.
250 */
251void
253{
254 tor_assert(key);
255 tor_assert(last);
257 if (onionkey)
259 else
260 *key = NULL;
261 if (lastonionkey)
263 else
264 *last = NULL;
266}
267
268/** Expire our old set of onion keys. This is done by setting
269 * last_curve25519_onion_key and lastonionkey to all zero's and NULL
270 * respectively.
271 *
272 * This function does not perform any grace period checks for the old onion
273 * keys.
274 */
275void
277{
278 char *fname = NULL;
279
281
282 /* Free lastonionkey and set it to NULL. */
283 if (lastonionkey) {
284 crypto_pk_free(lastonionkey);
285 lastonionkey = NULL;
286 }
287
288 /* We zero out the keypair. See the fast_mem_is_zero() check made in
289 * construct_ntor_key_map() below. */
291
293
294 fname = get_keydir_fname("secret_onion_key.old");
295 if (file_status(fname) == FN_FILE) {
296 if (tor_unlink(fname) != 0) {
297 log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
298 fname, strerror(errno));
299 }
300 }
301 tor_free(fname);
302
303 fname = get_keydir_fname("secret_onion_key_ntor.old");
304 if (file_status(fname) == FN_FILE) {
305 if (tor_unlink(fname) != 0) {
306 log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
307 fname, strerror(errno));
308 }
309 }
310 tor_free(fname);
311}
312
313/** Return the current secret onion key for the ntor handshake. Must only
314 * be called from the main thread. */
317{
318 return &curve25519_onion_key;
319}
320
321/** Return a map from KEYID (the key itself) to keypairs for use in the ntor
322 * handshake. Must only be called from the main thread. */
325{
326 di_digest256_map_t *m = NULL;
327
328 const uint8_t *cur_pk = curve25519_onion_key.pubkey.public_key;
329 const uint8_t *last_pk = last_curve25519_onion_key.pubkey.public_key;
330
331 if (!fast_mem_is_zero((const char *)cur_pk, CURVE25519_PUBKEY_LEN)) {
332 dimap_add_entry(&m, cur_pk,
333 tor_memdup(&curve25519_onion_key,
334 sizeof(curve25519_keypair_t)));
335 }
336 if (!fast_mem_is_zero((const char*)last_pk, CURVE25519_PUBKEY_LEN) &&
337 tor_memneq(cur_pk, last_pk, CURVE25519_PUBKEY_LEN)) {
338 dimap_add_entry(&m, last_pk,
339 tor_memdup(&last_curve25519_onion_key,
340 sizeof(curve25519_keypair_t)));
341 }
342
343 return m;
344}
345/** Helper used to deallocate a di_digest256_map_t returned by
346 * construct_ntor_key_map. */
347static void
349{
350 curve25519_keypair_t *k = arg;
351 memwipe(k, 0, sizeof(*k));
352 tor_free(k);
353}
354/** Release all storage from a keymap returned by construct_ntor_key_map. */
355void
357{
358 if (!map)
359 return;
361}
362
363/** Return the time when the onion key was last set. This is either the time
364 * when the process launched, or the time of the most recent key rotation since
365 * the process launched.
366 */
367time_t
369{
370 return onionkey_set_at;
371}
372
373/** Set the current server identity key to <b>k</b>.
374 */
375void
377{
378 crypto_pk_free(server_identitykey);
382 log_err(LD_BUG, "Couldn't compute our own identity key digest.");
383 tor_assert(0);
384 }
385}
386
387#ifdef TOR_UNIT_TESTS
388/** Testing only -- set the server's RSA identity digest to
389 * be <b>digest</b> */
390void
391set_server_identity_key_digest_testing(const uint8_t *digest)
392{
393 memcpy(server_identitykey_digest, digest, DIGEST_LEN);
394}
395#endif /* defined(TOR_UNIT_TESTS) */
396
397/** Make sure that we have set up our identity keys to match or not match as
398 * appropriate, and die with an assertion if we have not. */
399static void
401{
402 if (1)
403 return;
406 /* assert that we have set the client and server keys to be equal */
409 } else {
410 /* assert that we have set the client and server keys to be unequal */
413 }
414}
415
416#ifdef HAVE_MODULE_RELAY
417
418/** Returns the current server identity key; requires that the key has
419 * been set, and that we are running as a Tor server.
420 */
422get_server_identity_key,(void))
423{
428 return server_identitykey;
429}
430
431#endif /* defined(HAVE_MODULE_RELAY) */
432
433/** Return true iff we are a server and the server identity key
434 * has been set. */
435int
437{
438 return (server_mode(get_options()) ||
440 server_identitykey != NULL;
441}
442
443/** Set the current client identity key to <b>k</b>.
444 */
445void
447{
448 crypto_pk_free(client_identitykey);
450}
451
452/** Returns the current client identity key for use on outgoing TLS
453 * connections; requires that the key has been set.
454 */
457{
460 return client_identitykey;
461}
462
463/** Return true iff the client identity key has been set. */
464int
466{
467 return client_identitykey != NULL;
468}
469
470/** Return the key certificate for this v3 (voting) authority, or NULL
471 * if we have no such certificate. */
474{
476}
477
478/** Return the v3 signing key for this v3 (voting) authority, or NULL
479 * if we have no such key. */
482{
484}
485
486/** If we're an authority, and we're using a legacy authority identity key for
487 * emergency migration purposes, return the certificate associated with that
488 * key. */
491{
493}
494
495/** If we're an authority, and we're using a legacy authority identity key for
496 * emergency migration purposes, return that key. */
499{
500 return legacy_signing_key;
501}
502
503/** Replace the previous onion key with the current onion key, and generate
504 * a new previous onion key. Immediately after calling this function,
505 * the OR should:
506 * - schedule all previous cpuworkers to shut down _after_ processing
507 * pending work. (This will cause fresh cpuworkers to be generated.)
508 * - generate and upload a fresh routerinfo.
509 *
510 * Return true on success, else false on error.
511 */
512bool
514{
515 char *fname, *fname_prev;
516 crypto_pk_t *prkey = NULL;
517 or_state_t *state = get_or_state();
518 curve25519_keypair_t new_curve25519_keypair;
519 time_t now;
520 bool result = false;
521 fname = get_keydir_fname("secret_onion_key");
522 fname_prev = get_keydir_fname("secret_onion_key.old");
523 /* There isn't much point replacing an old key with an empty file */
524 if (file_status(fname) == FN_FILE) {
525 if (replace_file(fname, fname_prev))
526 goto error;
527 }
528 if (!(prkey = crypto_pk_new())) {
529 log_err(LD_GENERAL,"Error constructing rotated onion key");
530 goto error;
531 }
532 if (crypto_pk_generate_key(prkey)) {
533 log_err(LD_BUG,"Error generating onion key");
534 goto error;
535 }
536 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
537 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
538 goto error;
539 }
540 tor_free(fname);
541 tor_free(fname_prev);
542 fname = get_keydir_fname("secret_onion_key_ntor");
543 fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
544 if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
545 goto error;
546 /* There isn't much point replacing an old key with an empty file */
547 if (file_status(fname) == FN_FILE) {
548 if (replace_file(fname, fname_prev))
549 goto error;
550 }
551 if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
552 "onion") < 0) {
553 log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
554 goto error;
555 }
556 log_info(LD_GENERAL, "Rotating onion key");
558 crypto_pk_free(lastonionkey);
560 onionkey = prkey;
562 sizeof(curve25519_keypair_t));
563 memcpy(&curve25519_onion_key, &new_curve25519_keypair,
564 sizeof(curve25519_keypair_t));
565 now = time(NULL);
568 mark_my_descriptor_dirty("rotated onion key");
569 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
570 result = true;
571 goto done;
572 error:
573 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
574 if (prkey)
575 crypto_pk_free(prkey);
576 done:
577 memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
578 tor_free(fname);
579 tor_free(fname_prev);
580 return result;
581}
582
583/** Log greeting message that points to new relay lifecycle document the
584 * first time this function has been called.
585 */
586static void
588{
589 static int already_logged = 0;
590
591 if (already_logged)
592 return;
593
594 tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
595 "Thanks for helping the Tor network! If you wish to know "
596 "what will happen in the upcoming weeks regarding its usage, "
597 "have a look at https://blog.torproject.org/lifecycle-of-a"
598 "-new-relay");
599
600 already_logged = 1;
601}
602
603/** Load a curve25519 keypair from the file <b>fname</b>, writing it into
604 * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
605 * is true, create a new keypair and write it into the file. If there are
606 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
607 * in their ASCII wrapper. */
608static int
610 const char *fname,
611 int generate,
612 int severity,
613 const char *tag)
614{
615 switch (file_status(fname)) {
616 case FN_DIR:
617 case FN_ERROR:
618 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
619 goto error;
620 /* treat empty key files as if the file doesn't exist, and, if generate
621 * is set, replace the empty file in curve25519_keypair_write_to_file() */
622 case FN_NOENT:
623 case FN_EMPTY:
624 if (generate) {
625 if (!have_lockfile()) {
626 if (try_locking(get_options(), 0)<0) {
627 /* Make sure that --list-fingerprint only creates new keys
628 * if there is no possibility for a deadlock. */
629 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
630 "Not writing any new keys.", fname);
631 /*XXXX The 'other process' might make a key in a second or two;
632 * maybe we should wait for it. */
633 goto error;
634 }
635 }
636 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
637 fname);
638 if (curve25519_keypair_generate(keys_out, 1) < 0)
639 goto error;
640 if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
641 tor_log(severity, LD_FS,
642 "Couldn't write generated key to \"%s\".", fname);
643 memwipe(keys_out, 0, sizeof(*keys_out));
644 goto error;
645 }
646 } else {
647 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
648 }
649 return 0;
650 case FN_FILE:
651 {
652 char *tag_in=NULL;
653 if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
654 tor_log(severity, LD_GENERAL,"Error loading private key.");
655 tor_free(tag_in);
656 goto error;
657 }
658 if (!tag_in || strcmp(tag_in, tag)) {
659 tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
660 escaped(tag_in));
661 tor_free(tag_in);
662 goto error;
663 }
664 tor_free(tag_in);
665 return 0;
666 }
667 default:
668 tor_assert(0);
669 }
670
671 error:
672 return -1;
673}
674
675/** Try to load the vote-signing private key and certificate for being a v3
676 * directory authority, and make sure they match. If <b>legacy</b>, load a
677 * legacy key/cert set for emergency key migration; otherwise load the regular
678 * key/cert set. On success, store them into *<b>key_out</b> and
679 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
680static int
681load_authority_keyset(int legacy, crypto_pk_t **key_out,
682 authority_cert_t **cert_out)
683{
684 int r = -1;
685 char *fname = NULL, *cert = NULL;
686 const char *eos = NULL;
687 crypto_pk_t *signing_key = NULL;
688 authority_cert_t *parsed = NULL;
689
690 fname = get_keydir_fname(
691 legacy ? "legacy_signing_key" : "authority_signing_key");
692 signing_key = init_key_from_file(fname, 0, LOG_ERR, NULL);
693 if (!signing_key) {
694 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
695 goto done;
696 }
697 tor_free(fname);
698 fname = get_keydir_fname(
699 legacy ? "legacy_certificate" : "authority_certificate");
700 cert = read_file_to_str(fname, 0, NULL);
701 if (!cert) {
702 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
703 fname);
704 goto done;
705 }
706 parsed = authority_cert_parse_from_string(cert, strlen(cert), &eos);
707 if (!parsed) {
708 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
709 goto done;
710 }
711 if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
712 log_warn(LD_DIR, "Stored signing key does not match signing key in "
713 "certificate");
714 goto done;
715 }
716
717 crypto_pk_free(*key_out);
718 authority_cert_free(*cert_out);
719
720 *key_out = signing_key;
721 *cert_out = parsed;
722 r = 0;
723 signing_key = NULL;
724 parsed = NULL;
725
726 done:
727 tor_free(fname);
728 tor_free(cert);
729 crypto_pk_free(signing_key);
730 authority_cert_free(parsed);
731 return r;
732}
733
734/** Load the v3 (voting) authority signing key and certificate, if they are
735 * present. Return -1 if anything is missing, mismatched, or unloadable;
736 * return 0 on success. */
737static int
739{
742 return -1;
743
744 if (get_options()->V3AuthUseLegacyKey &&
747 return -1;
748
749 return 0;
750}
751
752/** If we're a v3 authority, check whether we have a certificate that's
753 * likely to expire soon. Warn if we do, but not too often. */
754void
756{
757 time_t now, expires;
758 static time_t last_warned = 0;
759 int badness, time_left, warn_interval;
760 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
761 return;
762
763 now = time(NULL);
765 time_left = (int)( expires - now );
766 if (time_left <= 0) {
767 badness = LOG_ERR;
768 warn_interval = 60*60;
769 } else if (time_left <= 24*60*60) {
770 badness = LOG_WARN;
771 warn_interval = 60*60;
772 } else if (time_left <= 24*60*60*7) {
773 badness = LOG_WARN;
774 warn_interval = 24*60*60;
775 } else if (time_left <= 24*60*60*30) {
776 badness = LOG_WARN;
777 warn_interval = 24*60*60*5;
778 } else {
779 return;
780 }
781
782 if (last_warned + warn_interval > now)
783 return;
784
785 if (time_left <= 0) {
786 tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
787 " Generate a new one NOW.");
788 } else if (time_left <= 24*60*60) {
789 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
790 "hours; Generate a new one NOW.", time_left/(60*60));
791 } else {
792 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
793 "days; Generate a new one soon.", time_left/(24*60*60));
794 }
795 last_warned = now;
796}
797
798/** Get the lifetime of an onion key in days. This value is defined by the
799 * network consensus parameter "onion-key-rotation-days". Always returns a
800 * value between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
801 * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
802 */
803static int
805{
806 return networkstatus_get_param(NULL,
807 "onion-key-rotation-days",
811}
812
813/** Get the current lifetime of an onion key in seconds. This value is defined
814 * by the network consensus parameter "onion-key-rotation-days", but the value
815 * is converted to seconds.
816 */
817int
819{
820 return get_onion_key_rotation_days_()*24*60*60;
821}
822
823/** Get the grace period of an onion key in seconds. This value is defined by
824 * the network consensus parameter "onion-key-grace-period-days", but the value
825 * is converted to seconds.
826 */
827int
829{
830 int grace_period;
831 grace_period = networkstatus_get_param(NULL,
832 "onion-key-grace-period-days",
836 return grace_period*24*60*60;
837}
838
839/** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
840 * on success, and -1 on failure. */
841int
843{
844 unsigned int flags = 0;
845 const or_options_t *options = get_options();
846 int lifetime = options->SSLKeyLifetime;
847 if (public_server_mode(options))
848 flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
849 if (!lifetime) { /* we should guess a good ssl cert lifetime */
850
851 /* choose between 5 and 365 days, and round to the day */
852 unsigned int five_days = 5*24*3600;
853 unsigned int one_year = 365*24*3600;
854 lifetime = crypto_rand_int_range(five_days, one_year);
855 lifetime -= lifetime % (24*3600);
856
857 if (crypto_rand_int(2)) {
858 /* Half the time we expire at midnight, and half the time we expire
859 * one second before midnight. (Some CAs wobble their expiry times a
860 * bit in practice, perhaps to reduce collision attacks; see ticket
861 * 8443 for details about observed certs in the wild.) */
862 lifetime--;
863 }
864 }
865
866 /* It's ok to pass lifetime in as an unsigned int, since
867 * config_parse_interval() checked it. */
868 return tor_tls_context_init(flags,
870 server_mode(options) ?
871 get_server_identity_key() : NULL,
872 (unsigned int)lifetime);
873}
874
875/** Announce URL to bridge status page. */
876STATIC void
878{
879 char fingerprint[FINGERPRINT_LEN + 1];
880
881 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
882 fingerprint) < 0) {
883 // LCOV_EXCL_START
884 log_err(LD_GENERAL, "Unable to compute bridge fingerprint");
885 return;
886 // LCOV_EXCL_STOP
887 }
888
889 log_notice(LD_GENERAL, "You can check the status of your bridge relay at "
890 "https://bridges.torproject.org/status?id=%s",
891 fingerprint);
892}
893
894/** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
895 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
896 * -1 if Tor should die,
897 */
898STATIC int
899router_write_fingerprint(int hashed, int ed25519_identity)
900{
901 char *keydir = NULL;
902 const char *fname = hashed ? "hashed-fingerprint" :
903 (ed25519_identity ? "fingerprint-ed25519" :
904 "fingerprint");
905 char fingerprint[FINGERPRINT_LEN+1];
906 const or_options_t *options = get_options();
907 char *fingerprint_line = NULL;
908 int result = -1;
909
910 keydir = get_datadir_fname(fname);
911 log_info(LD_GENERAL,"Dumping %s%s to \"%s\"...", hashed ? "hashed " : "",
912 ed25519_identity ? "ed25519 identity" : "fingerprint", keydir);
913
914 if (ed25519_identity) { /* ed25519 identity */
915 digest256_to_base64(fingerprint, (const char *)
916 get_master_identity_key()->pubkey);
917 } else { /* RSA identity */
918 if (!hashed) {
919 if (crypto_pk_get_fingerprint(get_server_identity_key(),
920 fingerprint, 0) < 0) {
921 log_err(LD_GENERAL,"Error computing fingerprint");
922 goto done;
923 }
924 } else {
925 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
926 fingerprint) < 0) {
927 log_err(LD_GENERAL,"Error computing hashed fingerprint");
928 goto done;
929 }
930 }
931 }
932
933 tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
934
935 /* Check whether we need to write the (hashed-)fingerprint file. */
936 if (write_str_to_file_if_not_equal(keydir, fingerprint_line)) {
937 log_err(LD_FS, "Error writing %s%s line to file",
938 hashed ? "hashed " : "",
939 ed25519_identity ? "ed25519 identity" : "fingerprint");
940 goto done;
941 }
942
943 log_notice(LD_GENERAL, "Your Tor %s identity key %sfingerprint is '%s %s'",
944 hashed ? "bridge's hashed" : "server's",
945 ed25519_identity ? "ed25519 " : "",
946 options->Nickname, fingerprint);
947
948 result = 0;
949 done:
950 tor_free(keydir);
951 tor_free(fingerprint_line);
952 return result;
953}
954
955static int
956init_keys_common(void)
957{
958 if (!key_lock)
960
961 return 0;
962}
963
964int
965init_keys_client(void)
966{
967 crypto_pk_t *prkey;
968 if (init_keys_common() < 0)
969 return -1;
970
971 if (!(prkey = crypto_pk_new()))
972 return -1;
973 if (crypto_pk_generate_key(prkey)) {
974 crypto_pk_free(prkey);
975 return -1;
976 }
978 /* Create a TLS context. */
980 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
981 return -1;
982 }
983 return 0;
984}
985
986/** Initialize all OR private keys, and the TLS context, as necessary.
987 * On OPs, this only initializes the tls context. Return 0 on success,
988 * or -1 if Tor should die.
989 */
990int
992{
993 char *keydir;
994 const char *mydesc;
995 crypto_pk_t *prkey;
996 char digest[DIGEST_LEN];
997 char v3_digest[DIGEST_LEN];
998 const or_options_t *options = get_options();
999 dirinfo_type_t type;
1000 time_t now = time(NULL);
1001 dir_server_t *ds;
1002 int v3_digest_set = 0;
1003 authority_cert_t *cert = NULL;
1004
1005 /* OP's don't need persistent keys; just make up an identity and
1006 * initialize the TLS context. */
1007 if (!server_mode(options) && !(options->command == CMD_KEY_EXPIRATION)) {
1008 return init_keys_client();
1009 }
1010 if (init_keys_common() < 0)
1011 return -1;
1012
1013 if (create_keys_directory(options) < 0)
1014 return -1;
1015
1016 /* 1a. Read v3 directory authority key/cert information. */
1017 memset(v3_digest, 0, sizeof(v3_digest));
1018 if (authdir_mode_v3(options)) {
1019 if (init_v3_authority_keys()<0) {
1020 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
1021 "were unable to load our v3 authority keys and certificate! "
1022 "Use tor-gencert to generate them. Dying.");
1023 return -1;
1024 }
1025 cert = get_my_v3_authority_cert();
1026 if (cert) {
1028 v3_digest) < 0) {
1029 log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
1030 "digest.");
1031 return -1;
1032 }
1033 v3_digest_set = 1;
1034 }
1035 }
1036
1037 /* 1b. Read identity key. Make it if none is found. */
1038 keydir = get_keydir_fname("secret_id_key");
1039 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
1040 bool created = false;
1041 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
1042 tor_free(keydir);
1043 if (!prkey) return -1;
1044 if (created)
1047
1048 /* 1c. If we are configured as a bridge, generate a client key;
1049 * otherwise, set the server identity key as our client identity
1050 * key. */
1051 if (public_server_mode(options)) {
1052 set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
1053 } else {
1054 if (!(prkey = crypto_pk_new()))
1055 return -1;
1056 if (crypto_pk_generate_key(prkey)) {
1057 crypto_pk_free(prkey);
1058 return -1;
1059 }
1061 }
1062
1063 /* 1d. Load all ed25519 keys */
1064 const int new_signing_key = load_ed_keys(options,now);
1065 if (new_signing_key < 0)
1066 return -1;
1067
1068 /* 2. Read onion key. Make it if none is found. */
1069 keydir = get_keydir_fname("secret_onion_key");
1070 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
1071 prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
1072 if (created)
1074 tor_free(keydir);
1075 if (!prkey) return -1;
1076 set_onion_key(prkey);
1077 if (options->command == CMD_RUN_TOR) {
1078 /* only mess with the state file if we're actually running Tor */
1079 or_state_t *state = get_or_state();
1080 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
1081 /* We allow for some parsing slop, but we don't want to risk accepting
1082 * values in the distant future. If we did, we might never rotate the
1083 * onion key. */
1085 } else {
1086 /* We have no LastRotatedOnionKey set; either we just created the key
1087 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
1088 * start the clock ticking now so that we will eventually rotate it even
1089 * if we don't stay up for the full lifetime of an onion key. */
1090 state->LastRotatedOnionKey = onionkey_set_at = now;
1091 or_state_mark_dirty(state, options->AvoidDiskWrites ?
1092 time(NULL)+3600 : 0);
1093 }
1094 }
1095
1096 keydir = get_keydir_fname("secret_onion_key.old");
1097 if (!lastonionkey && file_status(keydir) == FN_FILE) {
1098 /* Load keys from non-empty files only.
1099 * Missing old keys won't be replaced with freshly generated keys. */
1100 prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
1101 if (prkey)
1102 lastonionkey = prkey;
1103 }
1104 tor_free(keydir);
1105
1106 {
1107 /* 2b. Load curve25519 onion keys. */
1108 int r;
1109 keydir = get_keydir_fname("secret_onion_key_ntor");
1111 keydir, 1, LOG_ERR, "onion");
1112 tor_free(keydir);
1113 if (r<0)
1114 return -1;
1115
1116 keydir = get_keydir_fname("secret_onion_key_ntor.old");
1117 if (fast_mem_is_zero((const char *)
1118 last_curve25519_onion_key.pubkey.public_key,
1120 file_status(keydir) == FN_FILE) {
1121 /* Load keys from non-empty files only.
1122 * Missing old keys won't be replaced with freshly generated keys. */
1124 keydir, 0, LOG_ERR, "onion");
1125 }
1126 tor_free(keydir);
1127 }
1128
1129 /* 3. Initialize link key and TLS context. */
1131 log_err(LD_GENERAL,"Error initializing TLS context");
1132 return -1;
1133 }
1134
1135 /* 3b. Get an ed25519 link certificate. Note that we need to do this
1136 * after we set up the TLS context */
1137 if (generate_ed_link_cert(options, now, new_signing_key > 0) < 0) {
1138 log_err(LD_GENERAL,"Couldn't make link cert");
1139 return -1;
1140 }
1141
1142 /* 4. Build our router descriptor. */
1143 /* Must be called after keys are initialized. */
1144 mydesc = router_get_my_descriptor();
1145 if (authdir_mode_v3(options)) {
1146 const char *m = NULL;
1147 routerinfo_t *ri;
1148 /* We need to add our own fingerprint and ed25519 key so it gets
1149 * recognized. */
1150 if (dirserv_add_own_fingerprint(get_server_identity_key(),
1151 get_master_identity_key())) {
1152 log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
1153 return -1;
1154 }
1155 if (mydesc) {
1156 was_router_added_t added;
1157 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
1158 if (!ri) {
1159 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
1160 return -1;
1161 }
1162 added = dirserv_add_descriptor(ri, &m, "self");
1163 if (!WRA_WAS_ADDED(added)) {
1164 if (!WRA_WAS_OUTDATED(added)) {
1165 log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
1166 m?m:"<unknown error>");
1167 return -1;
1168 } else {
1169 /* If the descriptor was outdated, that's ok. This can happen
1170 * when some config options are toggled that affect workers, but
1171 * we don't really need new keys yet so the descriptor doesn't
1172 * change and the old one is still fresh. */
1173 log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
1174 "after key init: %s This is usually not a problem.",
1175 m?m:"<unknown error>");
1176 }
1177 }
1178 }
1179 }
1180
1181 /* 5. Dump fingerprint, ed25519 identity and possibly hashed fingerprint
1182 * to files. */
1183 if (router_write_fingerprint(0, 0)) {
1184 log_err(LD_FS, "Error writing fingerprint to file");
1185 return -1;
1186 }
1187 if (!public_server_mode(options) && router_write_fingerprint(1, 0)) {
1188 log_err(LD_FS, "Error writing hashed fingerprint to file");
1189 return -1;
1190 }
1191 if (router_write_fingerprint(0, 1)) {
1192 log_err(LD_FS, "Error writing ed25519 identity to file");
1193 return -1;
1194 }
1195
1196 /* Display URL to bridge status page. */
1197 if (! public_server_mode(options))
1199
1200 if (!authdir_mode(options))
1201 return 0;
1202 /* 6. [authdirserver only] load approved-routers file */
1204 log_err(LD_GENERAL,"Error loading fingerprints");
1205 return -1;
1206 }
1207 /* 6b. [authdirserver only] add own key to approved directories. */
1208 crypto_pk_get_digest(get_server_identity_key(), digest);
1209 type = ((options->V3AuthoritativeDir ?
1211 (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
1212
1214 if (!ds) {
1215 tor_addr_port_t ipv6_orport;
1216 routerconf_find_ipv6_or_ap(options, &ipv6_orport);
1217 ds = trusted_dir_server_new(options->Nickname, NULL,
1218 routerconf_find_dir_port(options, 0),
1219 routerconf_find_or_port(options,AF_INET),
1220 &ipv6_orport,
1221 digest,
1222 v3_digest,
1223 type, 0.0);
1224 if (!ds) {
1225 log_err(LD_GENERAL,"We want to be a directory authority, but we "
1226 "couldn't add ourselves to the authority list. Failing.");
1227 return -1;
1228 }
1229 dir_server_add(ds);
1230 }
1231 if (ds->type != type) {
1232 log_warn(LD_DIR, "Configured authority type does not match authority "
1233 "type in DirAuthority list. Adjusting. (%d v %d)",
1234 type, ds->type);
1235 ds->type = type;
1236 }
1237 if (v3_digest_set && (ds->type & V3_DIRINFO) &&
1238 tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
1239 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
1240 "DirAuthority line. Adjusting.");
1241 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
1242 }
1243
1244 if (cert) { /* add my own cert to the list of known certs */
1245 log_info(LD_DIR, "adding my own v3 cert");
1248 TRUSTED_DIRS_CERTS_SRC_SELF, 0,
1249 NULL)<0) {
1250 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1251 return -1;
1252 }
1253 }
1254
1255 return 0; /* success */
1256}
1257
1258/** The lower threshold of remaining bandwidth required to advertise (or
1259 * automatically provide) directory services */
1260/* XXX Should this be increased? */
1261#define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
1262
1263/** Return true iff we have enough configured bandwidth to advertise or
1264 * automatically provide directory services from cache directory
1265 * information. */
1266int
1268{
1270 return 0;
1271 }
1272 if (options->RelayBandwidthRate > 0 &&
1274 return 0;
1275 }
1276 return 1;
1277}
1278
1279/** Helper: Return 1 if we have sufficient resources for serving directory
1280 * requests, return 0 otherwise.
1281 * dir_port is either 0 or the configured DirPort number.
1282 * If AccountingMax is set less than our advertised bandwidth, then don't
1283 * serve requests. Likewise, if our advertised bandwidth is less than
1284 * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
1285 */
1286static int
1287router_should_be_dirserver(const or_options_t *options, int dir_port)
1288{
1289 static int advertising=1; /* start out assuming we will advertise */
1290 int new_choice=1;
1291 const char *reason = NULL;
1292
1293 if (accounting_is_enabled(options) &&
1294 get_options()->AccountingRule != ACCT_IN) {
1295 /* Don't spend bytes for directory traffic if we could end up hibernating,
1296 * but allow DirPort otherwise. Some relay operators set AccountingMax
1297 * because they're confused or to get statistics. Directory traffic has a
1298 * much larger effect on output than input so there is no reason to turn it
1299 * off if using AccountingRule in. */
1300 int interval_length = accounting_get_interval_length();
1301 uint32_t effective_bw = relay_get_effective_bwrate(options);
1302 uint64_t acc_bytes;
1303 if (!interval_length) {
1304 log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1305 "seconds long. Raising to 1.");
1306 interval_length = 1;
1307 }
1308 log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
1309 "bwrate: %u, AccountingMax: %"PRIu64", "
1310 "accounting interval length %d",
1311 dir_port ? "dirport" : "begindir",
1312 effective_bw, (options->AccountingMax),
1313 interval_length);
1314
1315 acc_bytes = options->AccountingMax;
1316 if (get_options()->AccountingRule == ACCT_SUM)
1317 acc_bytes /= 2;
1318 if (effective_bw >=
1319 acc_bytes / interval_length) {
1320 new_choice = 0;
1321 reason = "AccountingMax enabled";
1322 }
1323 } else if (! router_has_bandwidth_to_be_dirserver(options)) {
1324 /* if we're advertising a small amount */
1325 new_choice = 0;
1326 reason = "BandwidthRate under 50KB";
1327 }
1328
1329 if (advertising != new_choice) {
1330 if (new_choice == 1) {
1331 if (dir_port > 0)
1332 log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1333 else
1334 log_notice(LD_DIR, "Advertising directory service support");
1335 } else {
1336 tor_assert(reason);
1337 log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
1338 dir_port ? "Port" : "ectory Service support", reason);
1339 }
1340 advertising = new_choice;
1341 }
1342
1343 return advertising;
1344}
1345
1346/** Look at a variety of factors, and return 0 if we don't want to
1347 * advertise the fact that we have a DirPort open or begindir support, else
1348 * return 1.
1349 *
1350 * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1351 * must be 0.
1352 *
1353 * Log a helpful message if we change our mind about whether to publish.
1354 */
1355static int
1357 uint16_t dir_port,
1358 int supports_tunnelled_dir_requests)
1359{
1360 /* Part one: reasons to publish or not publish that aren't
1361 * worth mentioning to the user, either because they're obvious
1362 * or because they're normal behavior. */
1363
1364 /* short circuit the rest of the function */
1365 if (!dir_port && !supports_tunnelled_dir_requests)
1366 return 0;
1367 if (authdir_mode(options)) /* always publish */
1368 return 1;
1369 if (net_is_disabled())
1370 return 0;
1371 if (dir_port && !routerconf_find_dir_port(options, dir_port))
1372 return 0;
1373 if (supports_tunnelled_dir_requests &&
1374 !routerconf_find_or_port(options, AF_INET))
1375 return 0;
1376
1377 /* Part two: consider config options that could make us choose to
1378 * publish or not publish that the user might find surprising. */
1379 return router_should_be_dirserver(options, dir_port);
1380}
1381
1382/** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1383 * advertise the fact that we have a DirPort open, else return the
1384 * DirPort we want to advertise.
1385 */
1386int
1387router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1388{
1389 /* Only authorities should advertise a DirPort now. */
1390 return authdir_mode(options) ? dir_port : 0;
1391}
1392
1393/** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1394 * advertise the fact that we support begindir requests, else return 1.
1395 */
1396static int
1398 int supports_tunnelled_dir_requests)
1399{
1400 /* dir_port is not relevant, pass 0 */
1401 return decide_to_advertise_dir_impl(options, 0,
1402 supports_tunnelled_dir_requests);
1403}
1404
1405/** Return true iff the combination of options in <b>options</b> and parameters
1406 * in the consensus mean that we don't want to allow exits from circuits
1407 * we got from addresses not known to be servers. */
1408int
1410{
1411 if (options->RefuseUnknownExits != -1) {
1412 return options->RefuseUnknownExits;
1413 } else {
1414 return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1415 }
1416}
1417
1418/**
1419 * If true, then we will publish our descriptor even if our own IPv4 ORPort
1420 * seems to be unreachable.
1421 **/
1423/**
1424 * If true, then we will publish our descriptor even if our own IPv6 ORPort
1425 * seems to be unreachable.
1426 **/
1428
1429/** Decide if we're a publishable server. We are a publishable server if:
1430 * - We don't have the ClientOnly option set
1431 * and
1432 * - We have the PublishServerDescriptor option set to non-empty
1433 * and
1434 * - We have ORPort set
1435 * and
1436 * - We believe our ORPort and DirPort (if present) are reachable from
1437 * the outside; or
1438 * - We believe our ORPort is reachable from the outside, and we can't
1439 * check our DirPort because the consensus has no exits; or
1440 * - We are an authoritative directory server.
1441 */
1442static int
1444{
1445 const or_options_t *options = get_options();
1446
1447 if (options->ClientOnly)
1448 return 0;
1449 if (options->PublishServerDescriptor_ == NO_DIRINFO)
1450 return 0;
1451 if (!server_mode(options))
1452 return 0;
1453 if (authdir_mode(options))
1454 return 1;
1455 if (!routerconf_find_or_port(options, AF_INET))
1456 return 0;
1457 if (!router_orport_seems_reachable(options, AF_INET)) {
1458 // We have an ipv4 orport, and it doesn't seem reachable.
1460 return 0;
1461 }
1462 }
1463 /* We could be flagged to omit the IPv6 and if so, don't check for
1464 * reachability on the IPv6. This can happen if the address was
1465 * auto-discovered but turns out to be non reachable. */
1466 if (!omit_ipv6_on_publish &&
1467 !router_orport_seems_reachable(options, AF_INET6)) {
1468 // We have an ipv6 orport, and it doesn't seem reachable.
1470 return 0;
1471 }
1472 }
1473 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
1474 /* All set: there are no exits in the consensus (maybe this is a tiny
1475 * test network), so we can't check our DirPort reachability. */
1476 return 1;
1477 } else {
1478 return router_dirport_seems_reachable(options);
1479 }
1480}
1481
1482/** Initiate server descriptor upload as reasonable (if server is publishable,
1483 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1484 *
1485 * We need to rebuild the descriptor if it's dirty even if we're not
1486 * uploading, because our reachability testing *uses* our descriptor to
1487 * determine what IP address and ports to test.
1488 */
1489void
1491{
1492 int rebuilt;
1493
1494 if (!server_mode(get_options()))
1495 return;
1496
1497 rebuilt = router_rebuild_descriptor(0);
1498 if (rebuilt && decide_if_publishable_server()) {
1501 } else {
1503 }
1504}
1505
1506/** Return the port of the first active listener of type
1507 * <b>listener_type</b>. Returns 0 if no port is found. */
1508/** XXX not a very good interface. it's not reliable when there are
1509 multiple listeners. */
1510uint16_t
1512 sa_family_t family)
1513{
1514 /* Iterate all connections, find one of the right kind and return
1515 the port. Not very sophisticated or fast, but effective. */
1517 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1518 if (conn->type == listener_type && !conn->marked_for_close &&
1519 conn->socket_family == family) {
1520 return conn->port;
1521 }
1522 } SMARTLIST_FOREACH_END(conn);
1523
1524 return 0;
1525}
1526
1527/** Return the port that we should advertise as our ORPort in a given address
1528 * family; this is either the one configured in the ORPort option, or the one
1529 * we actually bound to if ORPort is "auto". Returns 0 if no port is found. */
1530uint16_t
1532 sa_family_t family)
1533{
1535 family);
1536 (void)options;
1537
1538 /* If the port is in 'auto' mode, we have to use
1539 router_get_listener_port_by_type(). */
1540 if (port == CFG_AUTO_PORT)
1542 family);
1543
1544 return port;
1545}
1546
1547/** As routerconf_find_or_port(), but returns the IPv6 address and
1548 * port in ipv6_ap_out, which must not be NULL. Returns a null address and
1549 * zero port, if no ORPort is found. */
1550void
1552 tor_addr_port_t *ipv6_ap_out)
1553{
1554 /* Bug in calling function, we can't return a sensible result, and it
1555 * shouldn't use the NULL pointer once we return. */
1556 tor_assert(ipv6_ap_out);
1557
1558 /* If there is no valid IPv6 ORPort, return a null address and port. */
1559 tor_addr_make_null(&ipv6_ap_out->addr, AF_INET6);
1560 ipv6_ap_out->port = 0;
1561
1564 AF_INET6);
1565 const uint16_t port = routerconf_find_or_port(options,
1566 AF_INET6);
1567
1568 if (!addr || port == 0) {
1569 log_debug(LD_CONFIG, "There is no advertised IPv6 ORPort.");
1570 return;
1571 }
1572
1573 /* If the relay is configured using the default authorities, disallow
1574 * internal IPs. Otherwise, allow them. For IPv4 ORPorts and DirPorts,
1575 * this check is done in resolve_my_address(). See #33681. */
1576 const int default_auth = using_default_dir_authorities(options);
1577 if (tor_addr_is_internal(addr, 0) && default_auth) {
1578 log_warn(LD_CONFIG,
1579 "Unable to use configured IPv6 ORPort \"%s\" in a "
1580 "descriptor. Skipping it. "
1581 "Try specifying a globally reachable address explicitly.",
1582 fmt_addrport(addr, port));
1583 return;
1584 }
1585
1586 tor_addr_copy(&ipv6_ap_out->addr, addr);
1587 ipv6_ap_out->port = port;
1588}
1589
1590/** Returns true if this router has an advertised IPv6 ORPort. */
1591bool
1593{
1594 /* What we want here is to learn if we have configured an IPv6 ORPort.
1595 * Remember, ORPort can listen on [::] and thus consider internal by
1596 * router_get_advertised_ipv6_or_ap() since we do _not_ want to advertise
1597 * such address. */
1598 const tor_addr_t *addr =
1600 const uint16_t port =
1601 routerconf_find_or_port(options, AF_INET6);
1602
1603 return tor_addr_port_is_valid(addr, port, 1);
1604}
1605
1606/** Returns true if this router can extend over IPv6.
1607 *
1608 * This check should only be performed by relay extend code.
1609 *
1610 * Clients should check if relays can initiate and accept IPv6 extends using
1611 * node_supports_initiating_ipv6_extends() and
1612 * node_supports_accepting_ipv6_extends().
1613 *
1614 * As with other extends, relays should assume the client has already
1615 * performed the relevant checks for the next hop. (Otherwise, relays that
1616 * have just added IPv6 ORPorts won't be able to self-test those ORPorts.)
1617 *
1618 * Accepting relays don't need to perform any IPv6-specific checks before
1619 * accepting a connection, because having an IPv6 ORPort implies support for
1620 * the relevant protocol version.
1621 */
1622MOCK_IMPL(bool,
1624{
1625 /* We might add some extra checks here, such as ExtendAllowIPv6Addresses
1626 * from ticket 33818. */
1627 return routerconf_has_ipv6_orport(options);
1628}
1629
1630/** Return the port that we should advertise as our DirPort;
1631 * this is one of three possibilities:
1632 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1633 * the one configured in the DirPort option,
1634 * or the one we actually bound to if DirPort is "auto". */
1635uint16_t
1636routerconf_find_dir_port(const or_options_t *options, uint16_t dirport)
1637{
1638 int dirport_configured = portconf_get_primary_dir_port();
1639 (void)options;
1640
1641 if (!dirport_configured)
1642 return dirport;
1643
1644 if (dirport_configured == CFG_AUTO_PORT)
1646 AF_INET);
1647
1648 return dirport_configured;
1649}
1650
1651/*
1652 * OR descriptor generation.
1653 */
1654
1655/** My routerinfo. */
1657/** My extrainfo */
1659/** Why did we most recently decide to regenerate our descriptor? Used to
1660 * tell the authorities why we're sending it to them. */
1661static const char *desc_gen_reason = "uninitialized reason";
1662/** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1663 * now. */
1665/** Why did we mark the descriptor dirty? */
1666STATIC const char *desc_dirty_reason = "Tor just started";
1667/** Boolean: do we need to regenerate the above? */
1668static int desc_needs_upload = 0;
1669
1670/** OR only: If <b>force</b> is true, or we haven't uploaded this
1671 * descriptor successfully yet, try to upload our signed descriptor to
1672 * all the directory servers we know about.
1673 */
1674void
1676{
1677 const routerinfo_t *ri;
1678 extrainfo_t *ei;
1679 char *msg;
1680 size_t desc_len, extra_len = 0, total_len;
1682
1684 if (!ri) {
1685 log_info(LD_GENERAL, "No descriptor; skipping upload");
1686 return;
1687 }
1689 if (auth == NO_DIRINFO)
1690 return;
1691 if (!force && !desc_needs_upload)
1692 return;
1693
1694 log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1695 force ? " (forced)" : "");
1696
1698
1699 desc_len = ri->cache_info.signed_descriptor_len;
1700 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1701 total_len = desc_len + extra_len + 1;
1702 msg = tor_malloc(total_len);
1703 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1704 if (ei) {
1705 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1706 }
1707 msg[desc_len+extra_len] = 0;
1708
1710 (auth & BRIDGE_DIRINFO) ?
1713 auth, msg, desc_len, extra_len);
1714 tor_free(msg);
1715}
1716
1717/** OR only: Check whether my exit policy says to allow connection to
1718 * conn. Return 0 if we accept; non-0 if we reject.
1719 */
1720int
1722{
1724 if (!me) /* make sure routerinfo exists */
1725 return -1;
1726
1727 /* make sure it's resolved to something. this way we can't get a
1728 'maybe' below. */
1729 if (tor_addr_is_null(addr))
1730 return -1;
1731
1732 /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
1733 * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
1734 * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
1735 * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
1736 * summary. */
1737 if ((tor_addr_family(addr) == AF_INET ||
1738 tor_addr_family(addr) == AF_INET6)) {
1739 return compare_tor_addr_to_addr_policy(addr, port,
1741#if 0
1742 } else if (tor_addr_family(addr) == AF_INET6) {
1743 return get_options()->IPv6Exit &&
1747#endif /* 0 */
1748 } else {
1749 return -1;
1750 }
1751}
1752
1753/** Return true iff my exit policy is reject *:*. Return -1 if we don't
1754 * have a descriptor */
1755MOCK_IMPL(int,
1757{
1759 if (!me) /* make sure routerinfo exists */
1760 return -1;
1761
1762 return me->policy_is_reject_star;
1763}
1764
1765/** Return true iff I'm a server and <b>digest</b> is equal to
1766 * my server identity key digest. */
1767int
1768router_digest_is_me(const char *digest)
1769{
1770 return (server_identitykey &&
1772}
1773
1774/** Return my identity digest. */
1775const uint8_t *
1777{
1778 return (const uint8_t *)server_identitykey_digest;
1779}
1780
1781/** Return true iff I'm a server and <b>digest</b> is equal to
1782 * my identity digest. */
1783int
1785{
1787 if (!ei)
1788 return 0;
1789
1790 return tor_memeq(digest,
1791 ei->cache_info.signed_descriptor_digest,
1792 DIGEST_LEN);
1793}
1794
1795/** A wrapper around router_digest_is_me(). */
1796int
1798{
1799 return router_digest_is_me(router->cache_info.identity_digest);
1800}
1801
1802/**
1803 * Return true if we are a server, and if @a addr is an address we are
1804 * currently publishing (or trying to publish) in our descriptor.
1805 * Return false otherwise.
1806 **/
1807bool
1809{
1810 IF_BUG_ONCE(!addr)
1811 return false;
1812
1814 if (!me)
1815 return false;
1816
1817 switch (tor_addr_family(addr)) {
1818 case AF_INET:
1819 return tor_addr_eq(addr, &me->ipv4_addr);
1820 case AF_INET6:
1821 return tor_addr_eq(addr, &me->ipv6_addr);
1822 default:
1823 return false;
1824 }
1825}
1826
1827/** Return a routerinfo for this OR, rebuilding a fresh one if
1828 * necessary. Return NULL on error, or if called on an OP. */
1829MOCK_IMPL(const routerinfo_t *,
1831{
1833}
1834
1835/** Return routerinfo of this OR. Rebuild it from
1836 * scratch if needed. Set <b>*err</b> to 0 on success or to
1837 * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
1838 */
1839MOCK_IMPL(const routerinfo_t *,
1841{
1842 if (!server_mode(get_options())) {
1843 if (err)
1844 *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
1845
1846 return NULL;
1847 }
1848
1849 if (!desc_routerinfo) {
1850 if (err)
1851 *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
1852
1853 return NULL;
1854 }
1855
1856 if (err)
1857 *err = 0;
1858
1859 return desc_routerinfo;
1860}
1861
1862/** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1863 * one if necessary. Return NULL on error.
1864 */
1865const char *
1867{
1868 const char *body;
1870 if (! me)
1871 return NULL;
1872 tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
1873 body = signed_descriptor_get_body(&me->cache_info);
1874 /* Make sure this is nul-terminated. */
1875 tor_assert(!body[me->cache_info.signed_descriptor_len]);
1876 log_debug(LD_GENERAL,"my desc is '%s'", body);
1877 return body;
1878}
1879
1880/** Return the extrainfo document for this OR, or NULL if we have none.
1881 * Rebuilt it (and the server descriptor) if necessary. */
1884{
1885 if (!server_mode(get_options()))
1886 return NULL;
1888 return NULL;
1889 return desc_extrainfo;
1890}
1891
1892/** Return a human-readable string describing what triggered us to generate
1893 * our current descriptor, or NULL if we don't know. */
1894const char *
1896{
1897 return desc_gen_reason;
1898}
1899
1900/* Like router_check_descriptor_address_consistency, but specifically for the
1901 * ORPort or DirPort.
1902 * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
1903static void
1904router_check_descriptor_address_port_consistency(const tor_addr_t *addr,
1905 int listener_type)
1906{
1907 int family, port_cfg;
1908
1909 tor_assert(addr);
1910 tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
1911 listener_type == CONN_TYPE_DIR_LISTENER);
1912
1913 family = tor_addr_family(addr);
1914 /* The first advertised Port may be the magic constant CFG_AUTO_PORT. */
1915 port_cfg = portconf_get_first_advertised_port(listener_type, family);
1916 if (port_cfg != 0 &&
1917 !port_exists_by_type_addr_port(listener_type, addr, port_cfg, 1)) {
1918 const tor_addr_t *port_addr =
1919 portconf_get_first_advertised_addr(listener_type, family);
1920 /* If we're building a descriptor with no advertised address,
1921 * something is terribly wrong. */
1922 tor_assert(port_addr);
1923
1924 char port_addr_str[TOR_ADDR_BUF_LEN];
1925 char desc_addr_str[TOR_ADDR_BUF_LEN];
1926
1927 tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
1928 tor_addr_to_str(desc_addr_str, addr, TOR_ADDR_BUF_LEN, 0);
1929
1930 const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
1931 "OR" : "Dir");
1932 const char *af_str = fmt_af_family(family);
1933 log_warn(LD_CONFIG, "The %s %sPort address %s does not match the "
1934 "descriptor address %s. If you have a static public IPv4 "
1935 "address, use 'Address <%s>' and 'OutboundBindAddress "
1936 "<%s>'. If you are behind a NAT, use two %sPort lines: "
1937 "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
1938 "NoAdvertise'.",
1939 af_str, listener_str, port_addr_str, desc_addr_str, af_str,
1940 af_str, listener_str, listener_str, listener_str);
1941 }
1942}
1943
1944/** Tor relays only have one IPv4 or/and one IPv6 address in the descriptor,
1945 * which is derived from the Address torrc option, or guessed using various
1946 * methods in relay_find_addr_to_publish().
1947 *
1948 * Warn the operator if there is no ORPort associated with the given address
1949 * in addr.
1950 *
1951 * Warn the operator if there is no DirPort on the descriptor address.
1952 *
1953 * This catches a few common config errors:
1954 * - operators who expect ORPorts and DirPorts to be advertised on the
1955 * ports' listen addresses, rather than the torrc Address (or guessed
1956 * addresses in the absence of an Address config). This includes
1957 * operators who attempt to put their ORPort and DirPort on different
1958 * addresses;
1959 * - discrepancies between guessed addresses and configured listen
1960 * addresses (when the Address option isn't set).
1961 *
1962 * If a listener is listening on all IPv4 addresses, it is assumed that it
1963 * is listening on the configured Address, and no messages are logged.
1964 *
1965 * If an operators has specified NoAdvertise ORPorts in a NAT setting,
1966 * no messages are logged, unless they have specified other advertised
1967 * addresses.
1968 *
1969 * The message tells operators to configure an ORPort and DirPort that match
1970 * the Address (using NoListen if needed). */
1971static void
1973{
1974 router_check_descriptor_address_port_consistency(addr,
1976 router_check_descriptor_address_port_consistency(addr,
1978}
1979
1980/** A list of nicknames that we've warned about including in our family,
1981 * for one reason or another. */
1983
1984/**
1985 * Return a new smartlist containing the family members configured in
1986 * <b>options</b>. Warn about invalid or missing entries. Return NULL
1987 * if this relay should not declare a family.
1988 **/
1991{
1992 if (!options->MyFamily)
1993 return NULL;
1994
1995 if (options->BridgeRelay)
1996 return NULL;
1997
1998 if (!warned_family)
2000
2001 smartlist_t *declared_family = smartlist_new();
2002 config_line_t *family;
2003
2004 /* First we try to get the whole family in the form of hexdigests. */
2005 for (family = options->MyFamily; family; family = family->next) {
2006 char *name = family->value;
2007 const node_t *member;
2008 if (options->Nickname && !strcasecmp(name, options->Nickname))
2009 continue; /* Don't list ourself by nickname, that's redundant */
2010 else
2011 member = node_get_by_nickname(name, 0);
2012
2013 if (!member) {
2014 /* This node doesn't seem to exist, so warn about it if it is not
2015 * a hexdigest. */
2016 int is_legal = is_legal_nickname_or_hexdigest(name);
2019 if (is_legal)
2020 log_warn(LD_CONFIG,
2021 "There is a router named %s in my declared family, but "
2022 "I have no descriptor for it. I'll use the nickname "
2023 "as is, but this may confuse clients. Please list it "
2024 "by identity digest instead.", escaped(name));
2025 else
2026 log_warn(LD_CONFIG, "There is a router named %s in my declared "
2027 "family, but that isn't a legal digest or nickname. "
2028 "Skipping it.", escaped(name));
2030 }
2031 if (is_legal) {
2032 smartlist_add_strdup(declared_family, name);
2033 }
2034 } else {
2035 /* List the node by digest. */
2036 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
2037 fp[0] = '$';
2039 member->identity, DIGEST_LEN);
2040 smartlist_add(declared_family, fp);
2041
2042 if (! is_legal_hexdigest(name) &&
2044 /* Warn if this node was not specified by hexdigest. */
2045 log_warn(LD_CONFIG, "There is a router named %s in my declared "
2046 "family, but it wasn't listed by digest. Please consider "
2047 "saying %s instead, if that's what you meant.",
2048 escaped(name), fp);
2050 }
2051 }
2052 }
2053
2054 /* Now declared_family should have the closest we can come to the
2055 * identities that the user wanted.
2056 *
2057 * Unlike older versions of Tor, we _do_ include our own identity: this
2058 * helps microdescriptor compression, and helps in-memory compression
2059 * on clients. */
2060 nodefamily_t *nf = nodefamily_from_members(declared_family,
2062 NF_WARN_MALFORMED,
2063 NULL);
2064 SMARTLIST_FOREACH(declared_family, char *, s, tor_free(s));
2065 smartlist_free(declared_family);
2066 if (!nf) {
2067 return NULL;
2068 }
2069
2070 char *s = nodefamily_format(nf);
2071 nodefamily_free(nf);
2072
2073 smartlist_t *result = smartlist_new();
2074 smartlist_split_string(result, s, NULL,
2075 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2076 tor_free(s);
2077
2078 if (smartlist_len(result) == 1) {
2079 /* This is a one-element list containing only ourself; instead return
2080 * nothing */
2081 const char *singleton = smartlist_get(result, 0);
2082 bool is_me = false;
2083 if (singleton[0] == '$') {
2084 char d[DIGEST_LEN];
2085 int n = base16_decode(d, sizeof(d), singleton+1, strlen(singleton+1));
2086 if (n == DIGEST_LEN &&
2088 is_me = true;
2089 }
2090 }
2091 if (!is_me) {
2092 // LCOV_EXCL_START
2093 log_warn(LD_BUG, "Found a singleton family list with an element "
2094 "that wasn't us! Element was %s", escaped(singleton));
2095 // LCOV_EXCL_STOP
2096 } else {
2097 SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
2098 smartlist_free(result);
2099 return NULL;
2100 }
2101 }
2102
2103 return result;
2104}
2105
2106/** Allocate a fresh, unsigned routerinfo for this OR, without any of the
2107 * fields that depend on the corresponding extrainfo.
2108 *
2109 * On success, set ri_out to the new routerinfo, and return 0.
2110 * Caller is responsible for freeing the generated routerinfo.
2111 *
2112 * Returns a negative value and sets ri_out to NULL on temporary error.
2113 */
2114MOCK_IMPL(STATIC int,
2116{
2117 routerinfo_t *ri = NULL;
2118 tor_addr_t ipv4_addr;
2119 char platform[256];
2120 int hibernating = we_are_hibernating();
2121 const or_options_t *options = get_options();
2122 int result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2123
2124 if (BUG(!ri_out)) {
2125 result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2126 goto err;
2127 }
2128
2129 /* Find our resolved address both IPv4 and IPv6. In case the address is not
2130 * found, the object is set to an UNSPEC address. */
2131 bool have_v4 = relay_find_addr_to_publish(options, AF_INET,
2132 RELAY_FIND_ADDR_NO_FLAG,
2133 &ipv4_addr);
2134 /* Tor requires a relay to have an IPv4 so bail if we can't find it. */
2135 if (!have_v4) {
2136 log_info(LD_CONFIG, "Don't know my address while generating descriptor. "
2137 "Launching circuit to authority to learn it.");
2138 relay_addr_learn_from_dirauth();
2139 result = TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
2140 goto err;
2141 }
2142 /* Log a message if the address in the descriptor doesn't match the ORPort
2143 * and DirPort addresses configured by the operator. */
2145
2146 ri = tor_malloc_zero(sizeof(routerinfo_t));
2147 tor_addr_copy(&ri->ipv4_addr, &ipv4_addr);
2148 ri->cache_info.routerlist_index = -1;
2149 ri->nickname = tor_strdup(options->Nickname);
2150
2151 /* IPv4. */
2152 ri->ipv4_orport = routerconf_find_or_port(options, AF_INET);
2153 ri->ipv4_dirport = routerconf_find_dir_port(options, 0);
2154
2155 /* Optionally check for an IPv6. We still publish without one. */
2156 if (relay_find_addr_to_publish(options, AF_INET6, RELAY_FIND_ADDR_NO_FLAG,
2157 &ri->ipv6_addr)) {
2158 ri->ipv6_orport = routerconf_find_or_port(options, AF_INET6);
2160 }
2161
2164 ri->cache_info.published_on = time(NULL);
2165
2167 /* get_onion_key() must invoke from main thread */
2168 router_set_rsa_onion_pkey(get_onion_key(), &ri->tap_onion_pkey,
2169 &ri->tap_onion_pkey_len);
2170 }
2171
2173 tor_memdup(&get_current_curve25519_keypair()->pubkey,
2174 sizeof(curve25519_public_key_t));
2175
2176 ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
2178 ri->cache_info.identity_digest) < 0)) {
2179 result = TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
2180 goto err;
2181 }
2182 ri->cache_info.signing_key_cert =
2183 tor_cert_dup(get_master_signing_key_cert());
2184
2185 get_platform_str(platform, sizeof(platform));
2186 ri->platform = tor_strdup(platform);
2187
2189
2190 /* compute ri->bandwidthrate as the min of various options */
2192
2193 /* and compute ri->bandwidthburst similarly */
2195
2196 /* Report bandwidth, unless we're hibernating or shutting down */
2197 ri->bandwidthcapacity = hibernating ? 0 : bwhist_bandwidth_assess();
2198
2200 /* DNS is screwed up; don't claim to be an exit. */
2202 } else {
2204 &ri->ipv6_addr,
2205 &ri->exit_policy);
2206 }
2208 policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
2209 policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
2210
2211 if (options->IPv6Exit) {
2212 char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
2213 if (p_tmp)
2215 tor_free(p_tmp);
2216 }
2217
2219
2220 if (options->BridgeRelay) {
2222 /* Bridges shouldn't be able to send their descriptors unencrypted,
2223 anyway, since they don't have a DirPort, and always connect to the
2224 bridge authority anonymously. But just in case they somehow think of
2225 sending them on an unencrypted connection, don't allow them to try. */
2226 ri->cache_info.send_unencrypted = 0;
2227 } else {
2229 ri->cache_info.send_unencrypted = 1;
2230 }
2231
2232 goto done;
2233
2234 err:
2235 routerinfo_free(ri);
2236 *ri_out = NULL;
2237 return result;
2238
2239 done:
2240 *ri_out = ri;
2241 return 0;
2242}
2243
2244/** Allocate and return a fresh, unsigned extrainfo for this OR, based on the
2245 * routerinfo ri.
2246 *
2247 * Uses options->Nickname to set the nickname, and options->BridgeRelay to set
2248 * ei->cache_info.send_unencrypted.
2249 *
2250 * If ri is NULL, logs a BUG() warning and returns NULL.
2251 * Caller is responsible for freeing the generated extrainfo.
2252 */
2253static extrainfo_t *
2255{
2256 extrainfo_t *ei = NULL;
2257 const or_options_t *options = get_options();
2258
2259 if (BUG(!ri))
2260 return NULL;
2261
2262 /* Now generate the extrainfo. */
2263 ei = tor_malloc_zero(sizeof(extrainfo_t));
2264 ei->cache_info.is_extrainfo = 1;
2265 strlcpy(ei->nickname, options->Nickname, sizeof(ei->nickname));
2266 ei->cache_info.published_on = ri->cache_info.published_on;
2267 ei->cache_info.signing_key_cert =
2268 tor_cert_dup(get_master_signing_key_cert());
2269
2270 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
2271 DIGEST_LEN);
2272
2273 if (options->BridgeRelay) {
2274 /* See note in router_build_fresh_routerinfo(). */
2275 ei->cache_info.send_unencrypted = 0;
2276 } else {
2277 ei->cache_info.send_unencrypted = 1;
2278 }
2279
2280 return ei;
2281}
2282
2283/** Dump the extrainfo descriptor body for ei, sign it, and add the body and
2284 * signature to ei->cache_info. Note that the extrainfo body is determined by
2285 * ei, and some additional config and statistics state: see
2286 * extrainfo_dump_to_string() for details.
2287 *
2288 * Return 0 on success, -1 on temporary error.
2289 * If ei is NULL, logs a BUG() warning and returns -1.
2290 * On error, ei->cache_info is not modified.
2291 */
2292static int
2294{
2295 if (BUG(!ei))
2296 return -1;
2297
2299 ei, get_server_identity_key(),
2300 get_master_signing_keypair()) < 0) {
2301 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
2302 return -1;
2303 }
2304
2305 ei->cache_info.signed_descriptor_len =
2306 strlen(ei->cache_info.signed_descriptor_body);
2307
2309 ei->cache_info.signed_descriptor_len,
2310 ei->cache_info.signed_descriptor_digest);
2311 crypto_digest256((char*) ei->digest256,
2312 ei->cache_info.signed_descriptor_body,
2313 ei->cache_info.signed_descriptor_len,
2314 DIGEST_SHA256);
2315
2316 return 0;
2317}
2318
2319/** Allocate and return a fresh, signed extrainfo for this OR, based on the
2320 * routerinfo ri.
2321 *
2322 * If ri is NULL, logs a BUG() warning and returns NULL.
2323 * Caller is responsible for freeing the generated extrainfo.
2324 */
2327{
2328 int result = -1;
2329 extrainfo_t *ei = NULL;
2330
2331 if (BUG(!ri))
2332 return NULL;
2333
2335 /* router_build_fresh_unsigned_extrainfo() should not fail. */
2336 if (BUG(!ei))
2337 goto err;
2338
2340 if (result < 0)
2341 goto err;
2342
2343 goto done;
2344
2345 err:
2346 extrainfo_free(ei);
2347 return NULL;
2348
2349 done:
2350 return ei;
2351}
2352
2353/** Set the fields in ri that depend on ei.
2354 *
2355 * If ei is NULL, logs a BUG() warning and zeroes the relevant fields.
2356 */
2357STATIC void
2359 const extrainfo_t *ei)
2360{
2361 if (BUG(!ei)) {
2362 /* Just to be safe, zero ri->cache_info.extra_info_digest here. */
2363 memset(ri->cache_info.extra_info_digest, 0, DIGEST_LEN);
2364 memset(ri->cache_info.extra_info_digest256, 0, DIGEST256_LEN);
2365 return;
2366 }
2367
2368 /* Now finish the router descriptor. */
2369 memcpy(ri->cache_info.extra_info_digest,
2370 ei->cache_info.signed_descriptor_digest,
2371 DIGEST_LEN);
2372 memcpy(ri->cache_info.extra_info_digest256,
2373 ei->digest256,
2375}
2376
2377/** Dump the descriptor body for ri, sign it, and add the body and signature to
2378 * ri->cache_info. Note that the descriptor body is determined by ri, and some
2379 * additional config and state: see router_dump_router_to_string() for details.
2380 *
2381 * Return 0 on success, and a negative value on temporary error.
2382 * If ri is NULL, logs a BUG() warning and returns a negative value.
2383 * On error, ri->cache_info is not modified.
2384 */
2385STATIC int
2387{
2388 if (BUG(!ri))
2389 return TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2390
2391 if (! (ri->cache_info.signed_descriptor_body =
2392 router_dump_router_to_string(ri, get_server_identity_key(),
2393 get_onion_key(),
2395 get_master_signing_keypair())) ) {
2396 log_warn(LD_BUG, "Couldn't generate router descriptor.");
2397 return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
2398 }
2399
2400 ri->cache_info.signed_descriptor_len =
2401 strlen(ri->cache_info.signed_descriptor_body);
2402
2404 strlen(ri->cache_info.signed_descriptor_body),
2405 ri->cache_info.signed_descriptor_digest);
2406
2407 return 0;
2408}
2409
2410/** Build a fresh routerinfo, signed server descriptor, and signed extrainfo
2411 * document for this OR.
2412 *
2413 * Set r to the generated routerinfo, e to the generated extrainfo document.
2414 * Failure to generate an extra-info document is not an error and is indicated
2415 * by setting e to NULL.
2416 * Return 0 on success, and a negative value on temporary error.
2417 * Caller is responsible for freeing generated documents on success.
2418 */
2419int
2421{
2422 int result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2423 routerinfo_t *ri = NULL;
2424 extrainfo_t *ei = NULL;
2425
2426 if (BUG(!r))
2427 goto err;
2428
2429 if (BUG(!e))
2430 goto err;
2431
2433 if (result < 0) {
2434 goto err;
2435 }
2436 /* If ri is NULL, then result should be negative. So this check should be
2437 * unreachable. */
2438 if (BUG(!ri)) {
2439 result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2440 goto err;
2441 }
2442
2444
2445 /* Failing to create an ei is not an error. */
2446 if (ei) {
2448 }
2449
2451 if (result < 0)
2452 goto err;
2453
2454 if (ei) {
2456 &ri->cache_info, NULL))) {
2457 result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2458 goto err;
2459 }
2460 }
2461
2462 goto done;
2463
2464 err:
2465 routerinfo_free(ri);
2466 extrainfo_free(ei);
2467 *r = NULL;
2468 *e = NULL;
2469 return result;
2470
2471 done:
2472 *r = ri;
2473 *e = ei;
2474 return 0;
2475}
2476
2477/** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2478 * routerinfo, signed server descriptor, and extra-info document for this OR.
2479 *
2480 * Return true on success, else false on temporary error.
2481 */
2482bool
2484{
2485 int err = 0;
2486 routerinfo_t *ri;
2487 extrainfo_t *ei;
2488
2489 if (desc_clean_since && !force)
2490 return true;
2491
2492 log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
2493
2494 err = router_build_fresh_descriptor(&ri, &ei);
2495 if (err < 0) {
2496 return false;
2497 }
2498
2499 routerinfo_free(desc_routerinfo);
2500 desc_routerinfo = ri;
2501 extrainfo_free(desc_extrainfo);
2502 desc_extrainfo = ei;
2503
2504 desc_clean_since = time(NULL);
2507 if (BUG(desc_gen_reason == NULL)) {
2508 desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
2509 }
2510 desc_dirty_reason = NULL;
2512 return true;
2513}
2514
2515/** Called when we have a new set of consensus parameters. */
2516void
2518{
2519 const int32_t DEFAULT_ASSUME_REACHABLE = 0;
2520 const int32_t DEFAULT_ASSUME_REACHABLE_IPV6 = 0;
2521 int ar, ar6;
2523 "assume-reachable",
2524 DEFAULT_ASSUME_REACHABLE, 0, 1);
2525 ar6 = networkstatus_get_param(ns,
2526 "assume-reachable-ipv6",
2527 DEFAULT_ASSUME_REACHABLE_IPV6, 0, 1);
2528
2531}
2532
2533/** Mark our descriptor out of data iff the IPv6 omit status flag is flipped
2534 * it changes from its previous value.
2535 *
2536 * This is used when our IPv6 port is found reachable or not. */
2537void
2538mark_my_descriptor_if_omit_ipv6_changes(const char *reason, bool omit_ipv6)
2539{
2540 bool previous = omit_ipv6_on_publish;
2541 omit_ipv6_on_publish = omit_ipv6;
2542
2543 /* Only mark it dirty if the IPv6 omit flag was flipped. */
2544 if (previous != omit_ipv6) {
2546 }
2547}
2548
2549/** If our router descriptor ever goes this long without being regenerated
2550 * because something changed, we force an immediate regenerate-and-upload. */
2551#define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2552
2553/** If our router descriptor seems to be missing or unacceptable according
2554 * to the authorities, regenerate and reupload it _this_ often. */
2555#define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2556
2557/** Mark descriptor out of date if it's been "too long" since we last tried
2558 * to upload one. */
2559void
2561{
2562 networkstatus_t *ns;
2563 const routerstatus_t *rs;
2564 const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2565 const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2566 const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2567
2568 /* If it's already dirty, don't mark it. */
2569 if (! desc_clean_since)
2570 return;
2571
2572 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2573 * time to rebuild it. */
2574 if (desc_clean_since < slow_cutoff) {
2575 mark_my_descriptor_dirty("time for new descriptor");
2576 return;
2577 }
2578 /* Now we see whether we want to be retrying frequently or no. The
2579 * rule here is that we'll retry frequently if we aren't listed in the
2580 * live consensus we have, or if the publication time of the
2581 * descriptor listed for us in the consensus is very old, or if the
2582 * consensus lists us as "stale" and we haven't regenerated since the
2583 * consensus was published. */
2585 if (ns) {
2587 if (rs == NULL)
2588 retry_fast_reason = "not listed in consensus";
2589 else if (rs->is_staledesc && ns->valid_after > desc_clean_since)
2590 retry_fast_reason = "listed as stale in consensus";
2591 }
2592
2593 if (retry_fast_reason && desc_clean_since < fast_cutoff)
2594 mark_my_descriptor_dirty(retry_fast_reason);
2595}
2596
2597/** Call when the current descriptor is out of date. */
2598void
2599mark_my_descriptor_dirty(const char *reason)
2600{
2601 const or_options_t *options = get_options();
2602 if (BUG(reason == NULL)) {
2603 reason = "marked descriptor dirty for unspecified reason";
2604 }
2605 if (server_mode(options) && options->PublishServerDescriptor_) {
2606 log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2607 }
2608 desc_clean_since = 0;
2609 if (!desc_dirty_reason)
2610 desc_dirty_reason = reason;
2612}
2613
2614/** How frequently will we republish our descriptor because of large (factor
2615 * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2616 * if our previous bandwidth estimate was exactly 0. */
2617#define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
2618
2619/** Maximum uptime to republish our descriptor because of large shifts in
2620 * estimated bandwidth. */
2621#define MAX_UPTIME_BANDWIDTH_CHANGE (24*60*60)
2622
2623/** By which factor bandwidth shifts have to change to be considered large. */
2624#define BANDWIDTH_CHANGE_FACTOR 2
2625
2626/** Check whether bandwidth has changed a lot since the last time we announced
2627 * bandwidth while the uptime is smaller than MAX_UPTIME_BANDWIDTH_CHANGE.
2628 * If so, mark our descriptor dirty. */
2629void
2631{
2632 static time_t last_changed = 0;
2633 uint64_t prev, cur;
2634 const int hibernating = we_are_hibernating();
2635
2636 /* If the relay uptime is bigger than MAX_UPTIME_BANDWIDTH_CHANGE,
2637 * the next regularly scheduled descriptor update (18h) will be enough */
2638 if (get_uptime() > MAX_UPTIME_BANDWIDTH_CHANGE && !hibernating)
2639 return;
2640
2641 const routerinfo_t *my_ri = router_get_my_routerinfo();
2642
2643 if (!my_ri)
2644 return;
2645
2646 prev = my_ri->bandwidthcapacity;
2647
2648 /* Consider ourselves to have zero bandwidth if we're hibernating or
2649 * shutting down. */
2650 cur = hibernating ? 0 : bwhist_bandwidth_assess();
2651
2652 if ((prev != cur && (!prev || !cur)) ||
2653 cur > (prev * BANDWIDTH_CHANGE_FACTOR) ||
2654 cur < (prev / BANDWIDTH_CHANGE_FACTOR) ) {
2655 const bool change_recent_enough =
2656 last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now;
2657 const bool testing_network = get_options()->TestingTorNetwork;
2658 if (change_recent_enough || testing_network || !prev) {
2659 log_info(LD_GENERAL,
2660 "Measured bandwidth has changed; rebuilding descriptor.");
2661 mark_my_descriptor_dirty("bandwidth has changed");
2662 last_changed = now;
2663 }
2664 }
2665}
2666
2667// This function can be "noreturn" if relay mode is disabled and
2668// ALL_BUGS_ARE_FATAL is set.
2669DISABLE_GCC_WARNING("-Wmissing-noreturn")
2670
2671/** Note at log level severity that our best guess of address has changed from
2672 * <b>prev</b> to <b>cur</b>. */
2673void
2675 const tor_addr_t *prev,
2676 const tor_addr_t *cur,
2677 const char *source)
2678{
2679 char addrbuf_prev[TOR_ADDR_BUF_LEN];
2680 char addrbuf_cur[TOR_ADDR_BUF_LEN];
2681
2682 if (BUG(!server_mode(get_options())))
2683 return;
2684
2685 if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2686 strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2687 if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2688 strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2689
2690 if (!tor_addr_is_null(prev))
2691 log_fn(severity, LD_GENERAL,
2692 "Our IP Address has changed from %s to %s; "
2693 "rebuilding descriptor (source: %s).",
2694 addrbuf_prev, addrbuf_cur, source);
2695 else
2696 log_notice(LD_GENERAL,
2697 "Guessed our IP address as %s (source: %s).",
2698 addrbuf_cur, source);
2699}
2700ENABLE_GCC_WARNING("-Wmissing-noreturn")
2701
2702/** Check whether our own address has changed versus the one we have in our
2703 * current descriptor.
2704 *
2705 * If our address has changed, call ip_address_changed() which takes
2706 * appropriate actions. */
2707void
2709{
2710 const routerinfo_t *my_ri = router_get_my_routerinfo();
2711 resolved_addr_method_t method = RESOLVED_ADDR_NONE;
2712 char *hostname = NULL;
2713 int families[2] = { AF_INET, AF_INET6 };
2714 bool has_changed = false;
2715
2716 (void) now;
2717
2718 /* We can't learn our descriptor address without one. */
2719 if (my_ri == NULL) {
2720 return;
2721 }
2722
2723 for (size_t i = 0; i < ARRAY_LENGTH(families); i++) {
2724 tor_addr_t current;
2725 const tor_addr_t *previous;
2726 int family = families[i];
2727
2728 /* Get the descriptor address from the family we are looking up. */
2729 previous = &my_ri->ipv4_addr;
2730 if (family == AF_INET6) {
2731 previous = &my_ri->ipv6_addr;
2732 }
2733
2734 /* Attempt to discovery the publishable address for the family which will
2735 * actively attempt to discover the address if we are configured with a
2736 * port for the family.
2737 *
2738 * It is OK to ignore the returned value here since in the failure case,
2739 * that is the address was not found, the current value is set to UNSPEC.
2740 * Add this (void) so Coverity is happy. */
2741 (void) relay_find_addr_to_publish(get_options(), family,
2742 RELAY_FIND_ADDR_NO_FLAG, &current);
2743
2744 /* The "current" address might be UNSPEC meaning it was not discovered nor
2745 * found in our current cache. If we had an address before and we have
2746 * none now, we consider this an IP change since it appears the relay lost
2747 * its address. */
2748
2749 if (!tor_addr_eq(previous, &current)) {
2750 char *source;
2751 tor_asprintf(&source, "METHOD=%s%s%s",
2753 hostname ? " HOSTNAME=" : "",
2754 hostname ? hostname : "");
2755 log_addr_has_changed(LOG_NOTICE, previous, &current, source);
2756 tor_free(source);
2757 has_changed = true;
2758 }
2759 tor_free(hostname);
2760 }
2761
2762 if (has_changed) {
2764 }
2765}
2766
2767/** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2768 * string describing the version of Tor and the operating system we're
2769 * currently running on.
2770 */
2771STATIC void
2772get_platform_str(char *platform, size_t len)
2773{
2774 tor_snprintf(platform, len, "Tor %s on %s",
2776}
2777
2778/* XXX need to audit this thing and count fenceposts. maybe
2779 * refactor so we don't have to keep asking if we're
2780 * near the end of maxlen?
2781 */
2782#define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2783
2784/** OR only: Given a routerinfo for this router, and an identity key to sign
2785 * with, encode the routerinfo as a signed server descriptor and return a new
2786 * string encoding the result, or NULL on failure.
2787 *
2788 * In addition to the fields in router, this function calls
2789 * onion_key_lifetime(), get_options(), and we_are_hibernating(), and uses the
2790 * results to populate some fields in the descriptor.
2791 */
2792char *
2794 const crypto_pk_t *ident_key,
2795 const crypto_pk_t *tap_key,
2796 const curve25519_keypair_t *ntor_keypair,
2797 const ed25519_keypair_t *signing_keypair)
2798{
2799 char *address = NULL;
2800 char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2801 crypto_pk_t *rsa_pubkey = NULL;
2802 char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2803 char digest[DIGEST256_LEN];
2804 char published[ISO_TIME_LEN+1];
2805 char fingerprint[FINGERPRINT_LEN+1];
2806 char *extra_info_line = NULL;
2807 size_t onion_pkeylen=0, identity_pkeylen;
2808 char *family_line = NULL;
2809 char *extra_or_address = NULL;
2810 const or_options_t *options = get_options();
2811 smartlist_t *chunks = NULL;
2812 char *output = NULL;
2813 const int emit_ed_sigs = signing_keypair &&
2814 router->cache_info.signing_key_cert;
2815 char *ed_cert_line = NULL;
2816 char *rsa_tap_cc_line = NULL;
2817 char *ntor_cc_line = NULL;
2818 char *proto_line = NULL;
2819
2820 /* Make sure the identity key matches the one in the routerinfo. */
2821 if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2822 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2823 "match router's public key!");
2824 goto err;
2825 }
2826 if (emit_ed_sigs) {
2827 if (!router->cache_info.signing_key_cert->signing_key_included ||
2828 !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
2829 &signing_keypair->pubkey)) {
2830 log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
2831 "ed25519 key chain %d",
2832 router->cache_info.signing_key_cert->signing_key_included);
2833 goto err;
2834 }
2835 }
2836
2837 /* record our fingerprint, so we can include it in the descriptor */
2838 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2839 log_err(LD_BUG,"Error computing fingerprint");
2840 goto err;
2841 }
2842
2843 if (emit_ed_sigs) {
2844 /* Encode ed25519 signing cert */
2845 char ed_cert_base64[256];
2846 char ed_fp_base64[ED25519_BASE64_LEN+1];
2847 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2848 (const char*)router->cache_info.signing_key_cert->encoded,
2849 router->cache_info.signing_key_cert->encoded_len,
2850 BASE64_ENCODE_MULTILINE) < 0) {
2851 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2852 goto err;
2853 }
2854 ed25519_public_to_base64(ed_fp_base64,
2855 &router->cache_info.signing_key_cert->signing_key);
2856 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2857 "-----BEGIN ED25519 CERT-----\n"
2858 "%s"
2859 "-----END ED25519 CERT-----\n"
2860 "master-key-ed25519 %s\n",
2861 ed_cert_base64, ed_fp_base64);
2862 }
2863
2864 /* PEM-encode the onion key */
2865 rsa_pubkey = router_get_rsa_onion_pkey(router->tap_onion_pkey,
2866 router->tap_onion_pkey_len);
2867 if (rsa_pubkey) {
2869 &onion_pkey,&onion_pkeylen)<0) {
2870 log_warn(LD_BUG,"write onion_pkey to string failed!");
2871 goto err;
2872 }
2873 }
2874
2875 /* PEM-encode the identity key */
2877 &identity_pkey,&identity_pkeylen)<0) {
2878 log_warn(LD_BUG,"write identity_pkey to string failed!");
2879 goto err;
2880 }
2881
2882 /* Cross-certify with RSA key */
2883 if (tap_key && rsa_pubkey && router->cache_info.signing_key_cert &&
2884 router->cache_info.signing_key_cert->signing_key_included) {
2885 char buf[256];
2886 int tap_cc_len = 0;
2887 uint8_t *tap_cc =
2889 &router->cache_info.signing_key_cert->signing_key,
2890 router->identity_pkey,
2891 &tap_cc_len);
2892 if (!tap_cc) {
2893 log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
2894 goto err;
2895 }
2896
2897 if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
2898 BASE64_ENCODE_MULTILINE) < 0) {
2899 log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
2900 tor_free(tap_cc);
2901 goto err;
2902 }
2903 tor_free(tap_cc);
2904
2905 tor_asprintf(&rsa_tap_cc_line,
2906 "onion-key-crosscert\n"
2907 "-----BEGIN CROSSCERT-----\n"
2908 "%s"
2909 "-----END CROSSCERT-----\n", buf);
2910 }
2911
2912 /* Cross-certify with onion keys */
2913 if (ntor_keypair && router->cache_info.signing_key_cert &&
2914 router->cache_info.signing_key_cert->signing_key_included) {
2915 int sign = 0;
2916 char buf[256];
2917 /* XXXX Base the expiration date on the actual onion key expiration time?*/
2918 tor_cert_t *cert =
2919 make_ntor_onion_key_crosscert(ntor_keypair,
2920 &router->cache_info.signing_key_cert->signing_key,
2921 router->cache_info.published_on,
2922 get_onion_key_lifetime(), &sign);
2923 if (!cert) {
2924 log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
2925 goto err;
2926 }
2927 tor_assert(sign == 0 || sign == 1);
2928
2929 if (base64_encode(buf, sizeof(buf),
2930 (const char*)cert->encoded, cert->encoded_len,
2931 BASE64_ENCODE_MULTILINE)<0) {
2932 log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
2933 tor_cert_free(cert);
2934 goto err;
2935 }
2936 tor_cert_free(cert);
2937
2938 tor_asprintf(&ntor_cc_line,
2939 "ntor-onion-key-crosscert %d\n"
2940 "-----BEGIN ED25519 CERT-----\n"
2941 "%s"
2942 "-----END ED25519 CERT-----\n", sign, buf);
2943 }
2944
2945 /* Encode the publication time. */
2946 format_iso_time(published, router->cache_info.published_on);
2947
2948 if (router->declared_family && smartlist_len(router->declared_family)) {
2949 char *family = smartlist_join_strings(router->declared_family,
2950 " ", 0, NULL);
2951 tor_asprintf(&family_line, "family %s\n", family);
2952 tor_free(family);
2953 } else {
2954 family_line = tor_strdup("");
2955 }
2956
2957 if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
2958 char extra_info_digest[HEX_DIGEST_LEN+1];
2959 base16_encode(extra_info_digest, sizeof(extra_info_digest),
2960 router->cache_info.extra_info_digest, DIGEST_LEN);
2961 if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
2962 char d256_64[BASE64_DIGEST256_LEN+1];
2963 digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
2964 tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
2965 extra_info_digest, d256_64);
2966 } else {
2967 tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
2968 extra_info_digest);
2969 }
2970 }
2971
2972 if (!omit_ipv6_on_publish && router->ipv6_orport &&
2973 tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2974 char addr[TOR_ADDR_BUF_LEN];
2975 const char *a;
2976 a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2977 if (a) {
2978 tor_asprintf(&extra_or_address,
2979 "or-address %s:%d\n", a, router->ipv6_orport);
2980 log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2981 }
2982 }
2983
2984 if (router->protocol_list) {
2985 tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
2986 } else {
2987 proto_line = tor_strdup("");
2988 }
2989
2990 address = tor_addr_to_str_dup(&router->ipv4_addr);
2991 if (!address)
2992 goto err;
2993
2994 chunks = smartlist_new();
2995
2996 /* Generate the easy portion of the router descriptor. */
2998 "router %s %s %d 0 %d\n"
2999 "%s"
3000 "%s"
3001 "platform %s\n"
3002 "%s"
3003 "published %s\n"
3004 "fingerprint %s\n"
3005 "uptime %ld\n"
3006 "bandwidth %d %d %d\n"
3007 "%s%s"
3008 "%s%s"
3009 "signing-key\n%s"
3010 "%s%s"
3011 "%s%s%s",
3012 router->nickname,
3013 address,
3014 router->ipv4_orport,
3015 router_should_advertise_dirport(options, router->ipv4_dirport),
3016 ed_cert_line ? ed_cert_line : "",
3017 extra_or_address ? extra_or_address : "",
3018 router->platform,
3019 proto_line,
3020 published,
3021 fingerprint,
3022 get_uptime(),
3023 (int) router->bandwidthrate,
3024 (int) router->bandwidthburst,
3025 (int) router->bandwidthcapacity,
3026 extra_info_line ? extra_info_line : "",
3027 (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
3028 "caches-extra-info\n" : "",
3029 onion_pkey?"onion-key\n":"", onion_pkey?onion_pkey:"",
3030 identity_pkey,
3031 rsa_tap_cc_line ? rsa_tap_cc_line : "",
3032 ntor_cc_line ? ntor_cc_line : "",
3033 family_line,
3034 we_are_hibernating() ? "hibernating 1\n" : "",
3035 "hidden-service-dir\n");
3036
3037 if (options->ContactInfo && strlen(options->ContactInfo)) {
3038 const char *ci = options->ContactInfo;
3039 if (strchr(ci, '\n') || strchr(ci, '\r'))
3040 ci = escaped(ci);
3041 smartlist_add_asprintf(chunks, "contact %s\n", ci);
3042 }
3043
3044 if (options->BridgeRelay) {
3045 char *bd = NULL;
3046
3047 if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
3048 bd = tor_strdup(options->BridgeDistribution);
3049 } else {
3050 bd = tor_strdup("any");
3051 }
3052
3053 // Make sure our value is lowercased in the descriptor instead of just
3054 // forwarding what the user wrote in their torrc directly.
3055 tor_strlower(bd);
3056
3057 smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
3058 tor_free(bd);
3059 }
3060
3061 if (router->onion_curve25519_pkey) {
3062 char kbuf[CURVE25519_BASE64_PADDED_LEN + 1];
3064 smartlist_add_asprintf(chunks, "ntor-onion-key %s\n", kbuf);
3065 } else {
3066 /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
3067 log_err(LD_BUG, "A relay must have an ntor onion key");
3068 goto err;
3069 }
3070
3071 /* Write the exit policy to the end of 's'. */
3072 if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
3073 smartlist_add_strdup(chunks, "reject *:*\n");
3074 } else if (router->exit_policy) {
3075 char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
3076
3077 if (!exit_policy)
3078 goto err;
3079
3080 smartlist_add_asprintf(chunks, "%s\n", exit_policy);
3081 tor_free(exit_policy);
3082 }
3083
3084 if (router->ipv6_exit_policy) {
3085 char *p6 = write_short_policy(router->ipv6_exit_policy);
3086 if (p6 && strcmp(p6, "reject 1-65535")) {
3088 "ipv6-policy %s\n", p6);
3089 }
3090 tor_free(p6);
3091 }
3092
3095 smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
3096 }
3097
3098 /* Overload general information. */
3099 if (options->OverloadStatistics) {
3100 char *overload_general = rep_hist_get_overload_general_line();
3101
3102 if (overload_general) {
3103 smartlist_add(chunks, overload_general);
3104 }
3105 }
3106
3107 /* Sign the descriptor with Ed25519 */
3108 if (emit_ed_sigs) {
3109 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
3110 crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
3111 ED_DESC_SIGNATURE_PREFIX,
3112 chunks, "", DIGEST_SHA256);
3114 char buf[ED25519_SIG_BASE64_LEN+1];
3115 if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
3116 signing_keypair) < 0)
3117 goto err;
3118 ed25519_signature_to_base64(buf, &sig);
3119
3120 smartlist_add_asprintf(chunks, "%s\n", buf);
3121 }
3122
3123 /* Sign the descriptor with RSA */
3124 smartlist_add_strdup(chunks, "router-signature\n");
3125
3126 crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
3127
3128 {
3129 char *sig;
3130 if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
3131 log_warn(LD_BUG, "Couldn't sign router descriptor");
3132 goto err;
3133 }
3134 smartlist_add(chunks, sig);
3135 }
3136
3137 /* include a last '\n' */
3138 smartlist_add_strdup(chunks, "\n");
3139
3140 output = smartlist_join_strings(chunks, "", 0, NULL);
3141
3142#ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
3143 {
3144 char *s_dup;
3145 const char *cp;
3146 routerinfo_t *ri_tmp;
3147 cp = s_dup = tor_strdup(output);
3148 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
3149 if (!ri_tmp) {
3150 log_err(LD_BUG,
3151 "We just generated a router descriptor we can't parse.");
3152 log_err(LD_BUG, "Descriptor was: <<%s>>", output);
3153 goto err;
3154 }
3155 tor_free(s_dup);
3156 routerinfo_free(ri_tmp);
3157 }
3158#endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
3159
3160 goto done;
3161
3162 err:
3163 tor_free(output); /* sets output to NULL */
3164 done:
3165 if (chunks) {
3166 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
3167 smartlist_free(chunks);
3168 }
3169 crypto_pk_free(rsa_pubkey);
3170 tor_free(address);
3171 tor_free(family_line);
3172 tor_free(onion_pkey);
3173 tor_free(identity_pkey);
3174 tor_free(extra_or_address);
3175 tor_free(ed_cert_line);
3176 tor_free(rsa_tap_cc_line);
3177 tor_free(ntor_cc_line);
3178 tor_free(extra_info_line);
3179 tor_free(proto_line);
3180
3181 return output;
3182}
3183
3184/**
3185 * OR only: Given <b>router</b>, produce a string with its exit policy.
3186 * If <b>include_ipv4</b> is true, include IPv4 entries.
3187 * If <b>include_ipv6</b> is true, include IPv6 entries.
3188 */
3189char *
3191 int include_ipv4,
3192 int include_ipv6)
3193{
3194 if ((!router->exit_policy) || (router->policy_is_reject_star)) {
3195 return tor_strdup("reject *:*");
3196 }
3197
3198 return policy_dump_to_string(router->exit_policy,
3199 include_ipv4,
3200 include_ipv6);
3201}
3202
3203/** Load the contents of <b>filename</b>, find a line starting with
3204 * timestamp tag <b>ts_tag</b>, ensure that its timestamp is not more than 25
3205 * hours in the past or more than 1 hour in the future with respect to
3206 * <b>now</b>, and write the entire file contents into <b>out</b>.
3207 *
3208 * The timestamp expected should be an ISO-formatted UTC time value which is
3209 * parsed using our parse_iso_time() function.
3210 *
3211 * In case more than one tag are found in the file, the very first one is
3212 * used.
3213 *
3214 * Return 1 for success, 0 if the file does not exist or is empty, or -1 if
3215 * the file does not contain a line with the timestamp tag. */
3216STATIC int
3217load_stats_file(const char *filename, const char *ts_tag, time_t now,
3218 char **out)
3219{
3220 int r = -1;
3221 char *fname = get_datadir_fname(filename);
3222 char *contents = NULL, timestr[ISO_TIME_LEN+1];
3223 time_t written;
3224
3225 switch (file_status(fname)) {
3226 case FN_FILE:
3227 contents = read_file_to_str(fname, 0, NULL);
3228 if (contents == NULL) {
3229 log_debug(LD_BUG, "Unable to read content of %s", filename);
3230 goto end;
3231 }
3232 /* Find the timestamp tag to validate that the file is not too old or if
3233 * exists. */
3234 const char *ts_tok = find_str_at_start_of_line(contents, ts_tag);
3235 if (!ts_tok) {
3236 log_warn(LD_BUG, "Token %s not found in file %s", ts_tag, filename);
3237 goto end;
3238 }
3239 /* Do we have enough for parsing a timestamp? */
3240 if (strlen(ts_tok) < strlen(ts_tag) + 1 + sizeof(timestr)) {
3241 log_warn(LD_BUG, "Token %s malformed in file %s", ts_tag, filename);
3242 goto end;
3243 }
3244 /* Parse timestamp in order to validate it is not too old. */
3245 strlcpy(timestr, ts_tok + strlen(ts_tag) + 1, sizeof(timestr));
3246 if (parse_iso_time(timestr, &written) < 0) {
3247 log_warn(LD_BUG, "Token %s has a malformed timestamp in file %s",
3248 ts_tag, filename);
3249 goto end;
3250 }
3251 if (written < now - (25*60*60) || written > now + (1*60*60)) {
3252 /* This can happen normally so don't log. */
3253 goto end;
3254 }
3255 /* Success. Put in the entire content. */
3256 *out = contents;
3257 contents = NULL; /* Must not free it. */
3258 r = 1;
3259 break;
3260 /* treat empty stats files as if the file doesn't exist */
3261 case FN_NOENT:
3262 case FN_EMPTY:
3263 r = 0;
3264 break;
3265 case FN_ERROR:
3266 case FN_DIR:
3267 default:
3268 break;
3269 }
3270
3271 end:
3272 tor_free(fname);
3273 tor_free(contents);
3274 return r;
3275}
3276
3277/** Add header strings to chunks, based on the extrainfo object extrainfo,
3278 * and ed25519 keypair signing_keypair, if emit_ed_sigs is true.
3279 * Helper for extrainfo_dump_to_string().
3280 * Returns 0 on success, negative on failure. */
3281static int
3283 smartlist_t *chunks,
3284 const extrainfo_t *extrainfo,
3285 const ed25519_keypair_t *signing_keypair,
3286 int emit_ed_sigs)
3287{
3288 char identity[HEX_DIGEST_LEN+1];
3289 char published[ISO_TIME_LEN+1];
3290 char *ed_cert_line = NULL;
3291 char *pre = NULL;
3292 int rv = -1;
3293
3294 base16_encode(identity, sizeof(identity),
3295 extrainfo->cache_info.identity_digest, DIGEST_LEN);
3296 format_iso_time(published, extrainfo->cache_info.published_on);
3297 if (emit_ed_sigs) {
3298 if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
3299 !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
3300 &signing_keypair->pubkey)) {
3301 log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
3302 "mismatched ed25519 key chain %d",
3303 extrainfo->cache_info.signing_key_cert->signing_key_included);
3304 goto err;
3305 }
3306 char ed_cert_base64[256];
3307 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
3308 (const char*)extrainfo->cache_info.signing_key_cert->encoded,
3309 extrainfo->cache_info.signing_key_cert->encoded_len,
3310 BASE64_ENCODE_MULTILINE) < 0) {
3311 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
3312 goto err;
3313 }
3314 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
3315 "-----BEGIN ED25519 CERT-----\n"
3316 "%s"
3317 "-----END ED25519 CERT-----\n", ed_cert_base64);
3318 } else {
3319 ed_cert_line = tor_strdup("");
3320 }
3321
3322 /* This is the first chunk in the file. If the file is too big, other chunks
3323 * are removed. So we must only add one chunk here. */
3324 tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n",
3325 extrainfo->nickname, identity,
3326 ed_cert_line,
3327 published);
3328 smartlist_add(chunks, pre);
3329
3330 rv = 0;
3331 goto done;
3332
3333 err:
3334 rv = -1;
3335
3336 done:
3337 tor_free(ed_cert_line);
3338 return rv;
3339}
3340
3341/** Add pluggable transport and statistics strings to chunks, skipping
3342 * statistics if write_stats_to_extrainfo is false.
3343 * Helper for extrainfo_dump_to_string().
3344 * Can not fail. */
3345static void
3347 int write_stats_to_extrainfo)
3348{
3349 const or_options_t *options = get_options();
3350 char *contents = NULL;
3351 time_t now = time(NULL);
3352
3353 /* If the file is too big, these chunks are removed, starting with the last
3354 * chunk. So each chunk must be a complete line, and the file must be valid
3355 * after each chunk. */
3356
3357 /* Add information about the pluggable transports we support, even if we
3358 * are not publishing statistics. This information is needed by BridgeDB
3359 * to distribute bridges. */
3360 if (options->ServerTransportPlugin) {
3361 char *pluggable_transports = pt_get_extra_info_descriptor_string();
3362 if (pluggable_transports)
3363 smartlist_add(chunks, pluggable_transports);
3364 }
3365
3366 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
3367 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
3368 /* Bandwidth usage stats don't have their own option */
3369 {
3370 contents = bwhist_get_bandwidth_lines();
3371 smartlist_add(chunks, contents);
3372 }
3373 /* geoip hashes aren't useful unless we are publishing other stats */
3374 if (geoip_is_loaded(AF_INET))
3375 smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
3376 geoip_db_digest(AF_INET));
3377 if (geoip_is_loaded(AF_INET6))
3378 smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
3379 geoip_db_digest(AF_INET6));
3380 if (options->DirReqStatistics &&
3381 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
3382 "dirreq-stats-end", now, &contents) > 0) {
3383 smartlist_add(chunks, contents);
3384 }
3385 if (options->HiddenServiceStatistics &&
3386 load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
3387 "hidserv-stats-end", now, &contents) > 0) {
3388 smartlist_add(chunks, contents);
3389 }
3390 if (options->HiddenServiceStatistics &&
3391 load_stats_file("stats"PATH_SEPARATOR"hidserv-v3-stats",
3392 "hidserv-v3-stats-end", now, &contents) > 0) {
3393 smartlist_add(chunks, contents);
3394 }
3395 if (options->EntryStatistics &&
3396 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
3397 "entry-stats-end", now, &contents) > 0) {
3398 smartlist_add(chunks, contents);
3399 }
3400 if (options->CellStatistics &&
3401 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
3402 "cell-stats-end", now, &contents) > 0) {
3403 smartlist_add(chunks, contents);
3404 }
3405 if (options->ExitPortStatistics &&
3406 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
3407 "exit-stats-end", now, &contents) > 0) {
3408 smartlist_add(chunks, contents);
3409 }
3410 if (options->ConnDirectionStatistics &&
3411 load_stats_file("stats"PATH_SEPARATOR"conn-stats",
3412 "conn-bi-direct", now, &contents) > 0) {
3413 smartlist_add(chunks, contents);
3414 }
3415 if (options->PaddingStatistics) {
3417 if (contents)
3418 smartlist_add(chunks, contents);
3419 }
3420 if (options->OverloadStatistics) {
3422 if (contents) {
3423 smartlist_add(chunks, contents);
3424 }
3425 }
3426 /* bridge statistics */
3427 if (should_record_bridge_info(options)) {
3428 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
3429 if (bridge_stats) {
3430 smartlist_add_strdup(chunks, bridge_stats);
3431 }
3432 }
3433 }
3434}
3435
3436/** Add an ed25519 signature of chunks to chunks, using the ed25519 keypair
3437 * signing_keypair.
3438 * Helper for extrainfo_dump_to_string().
3439 * Returns 0 on success, negative on failure. */
3440static int
3442 smartlist_t *chunks,
3443 const ed25519_keypair_t *signing_keypair)
3444{
3445 char sha256_digest[DIGEST256_LEN];
3446 ed25519_signature_t ed_sig;
3447 char buf[ED25519_SIG_BASE64_LEN+1];
3448 int rv = -1;
3449
3450 /* These are two of the three final chunks in the file. If the file is too
3451 * big, other chunks are removed. So we must only add two chunks here. */
3452 smartlist_add_strdup(chunks, "router-sig-ed25519 ");
3453 crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
3454 ED_DESC_SIGNATURE_PREFIX,
3455 chunks, "", DIGEST_SHA256);
3456 if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
3457 signing_keypair) < 0)
3458 goto err;
3459 ed25519_signature_to_base64(buf, &ed_sig);
3460
3461 smartlist_add_asprintf(chunks, "%s\n", buf);
3462
3463 rv = 0;
3464 goto done;
3465
3466 err:
3467 rv = -1;
3468
3469 done:
3470 return rv;
3471}
3472
3473/** Add an RSA signature of extrainfo_string to chunks, using the RSA key
3474 * ident_key.
3475 * Helper for extrainfo_dump_to_string().
3476 * Returns 0 on success, negative on failure. */
3477static int
3479 crypto_pk_t *ident_key,
3480 const char *extrainfo_string)
3481{
3482 char sig[DIROBJ_MAX_SIG_LEN+1];
3483 char digest[DIGEST_LEN];
3484 int rv = -1;
3485
3486 memset(sig, 0, sizeof(sig));
3487 if (router_get_extrainfo_hash(extrainfo_string, strlen(extrainfo_string),
3488 digest) < 0 ||
3489 router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
3490 ident_key) < 0) {
3491 log_warn(LD_BUG, "Could not append signature to extra-info "
3492 "descriptor.");
3493 goto err;
3494 }
3495 smartlist_add_strdup(chunks, sig);
3496
3497 rv = 0;
3498 goto done;
3499
3500 err:
3501 rv = -1;
3502
3503 done:
3504 return rv;
3505}
3506
3507/** Write the contents of <b>extrainfo</b>, to * *<b>s_out</b>, signing them
3508 * with <b>ident_key</b>.
3509 *
3510 * If ExtraInfoStatistics is 1, also write aggregated statistics and related
3511 * configuration data before signing. Most statistics also have an option that
3512 * enables or disables that particular statistic.
3513 *
3514 * Always write pluggable transport lines.
3515 *
3516 * Return 0 on success, negative on failure. */
3517int
3518extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
3519 crypto_pk_t *ident_key,
3520 const ed25519_keypair_t *signing_keypair)
3521{
3522 int result;
3523 static int write_stats_to_extrainfo = 1;
3524 char *s = NULL, *cp, *s_dup = NULL;
3525 smartlist_t *chunks = smartlist_new();
3526 extrainfo_t *ei_tmp = NULL;
3527 const int emit_ed_sigs = signing_keypair &&
3528 extrainfo->cache_info.signing_key_cert;
3529 int rv = 0;
3530
3531 rv = extrainfo_dump_to_string_header_helper(chunks, extrainfo,
3532 signing_keypair,
3533 emit_ed_sigs);
3534 if (rv < 0)
3535 goto err;
3536
3537 extrainfo_dump_to_string_stats_helper(chunks, write_stats_to_extrainfo);
3538
3539 if (emit_ed_sigs) {
3540 rv = extrainfo_dump_to_string_ed_sig_helper(chunks, signing_keypair);
3541 if (rv < 0)
3542 goto err;
3543 }
3544
3545 /* This is one of the three final chunks in the file. If the file is too big,
3546 * other chunks are removed. So we must only add one chunk here. */
3547 smartlist_add_strdup(chunks, "router-signature\n");
3548 s = smartlist_join_strings(chunks, "", 0, NULL);
3549
3550 while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
3551 /* So long as there are at least two chunks (one for the initial
3552 * extra-info line and one for the router-signature), we can keep removing
3553 * things. If emit_ed_sigs is true, we also keep 2 additional chunks at the
3554 * end for the ed25519 signature. */
3555 const int required_chunks = emit_ed_sigs ? 4 : 2;
3556 if (smartlist_len(chunks) > required_chunks) {
3557 /* We remove the next-to-last or 4th-last element (remember, len-1 is the
3558 * last element), since we need to keep the router-signature elements. */
3559 int idx = smartlist_len(chunks) - required_chunks;
3560 char *e = smartlist_get(chunks, idx);
3561 smartlist_del_keeporder(chunks, idx);
3562 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3563 "with statistics that exceeds the 50 KB "
3564 "upload limit. Removing last added "
3565 "statistics.");
3566 tor_free(e);
3567 tor_free(s);
3568 s = smartlist_join_strings(chunks, "", 0, NULL);
3569 } else {
3570 log_warn(LD_BUG, "We just generated an extra-info descriptors that "
3571 "exceeds the 50 KB upload limit.");
3572 goto err;
3573 }
3574 }
3575
3576 rv = extrainfo_dump_to_string_rsa_sig_helper(chunks, ident_key, s);
3577 if (rv < 0)
3578 goto err;
3579
3580 tor_free(s);
3581 s = smartlist_join_strings(chunks, "", 0, NULL);
3582
3583 cp = s_dup = tor_strdup(s);
3584 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
3585 if (!ei_tmp) {
3586 if (write_stats_to_extrainfo) {
3587 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3588 "with statistics that we can't parse. Not "
3589 "adding statistics to this or any future "
3590 "extra-info descriptors.");
3591 write_stats_to_extrainfo = 0;
3592 result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
3593 signing_keypair);
3594 goto done;
3595 } else {
3596 log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
3597 "can't parse.");
3598 goto err;
3599 }
3600 }
3601
3602 *s_out = s;
3603 s = NULL; /* prevent free */
3604 result = 0;
3605 goto done;
3606
3607 err:
3608 result = -1;
3609
3610 done:
3611 tor_free(s);
3612 SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
3613 smartlist_free(chunks);
3614 tor_free(s_dup);
3615 extrainfo_free(ei_tmp);
3616
3617 return result;
3618}
3619
3620/** Forget that we have issued any router-related warnings, so that we'll
3621 * warn again if we see the same errors. */
3622void
3624{
3625 if (warned_family) {
3626 SMARTLIST_FOREACH(warned_family, char *, cp, tor_free(cp));
3628 }
3629}
3630
3631/** Release all static resources held in router.c */
3632void
3634{
3635 crypto_pk_free(onionkey);
3636 crypto_pk_free(lastonionkey);
3637 crypto_pk_free(server_identitykey);
3638 crypto_pk_free(client_identitykey);
3639
3640 /* Destroying a locked mutex is undefined behaviour. This mutex may be
3641 * locked, because multiple threads can access it. But we need to destroy
3642 * it, otherwise re-initialisation will trigger undefined behaviour.
3643 * See #31735 for details. */
3645 routerinfo_free(desc_routerinfo);
3646 extrainfo_free(desc_extrainfo);
3647 crypto_pk_free(authority_signing_key);
3648 authority_cert_free(authority_key_certificate);
3649 crypto_pk_free(legacy_signing_key);
3650 authority_cert_free(legacy_key_certificate);
3651
3654
3655 if (warned_family) {
3656 SMARTLIST_FOREACH(warned_family, char *, cp, tor_free(cp));
3657 smartlist_free(warned_family);
3658 }
3659}
3660
3661/* From the given RSA key object, convert it to ASN-1 encoded format and set
3662 * the newly allocated object in onion_pkey_out. The length of the key is set
3663 * in onion_pkey_len_out. */
3664void
3665router_set_rsa_onion_pkey(const crypto_pk_t *pk, char **onion_pkey_out,
3666 size_t *onion_pkey_len_out)
3667{
3668 int len;
3669 char buf[1024];
3670
3671 tor_assert(pk);
3672 tor_assert(onion_pkey_out);
3673 tor_assert(onion_pkey_len_out);
3674
3675 len = crypto_pk_asn1_encode(pk, buf, sizeof(buf));
3676 if (BUG(len < 0)) {
3677 goto done;
3678 }
3679
3680 *onion_pkey_out = tor_memdup(buf, len);
3681 *onion_pkey_len_out = len;
3682
3683 done:
3684 return;
3685}
3686
3687/* From an ASN-1 encoded onion pkey, return a newly allocated RSA key object.
3688 * It is the caller's responsibility to free the returned object.
3689 *
3690 * Return NULL if the pkey is NULL, malformed or if the length is 0. */
3692router_get_rsa_onion_pkey(const char *pkey, size_t pkey_len)
3693{
3694 if (!pkey || pkey_len == 0) {
3695 return NULL;
3696 }
3697 return crypto_pk_asn1_decode(pkey, pkey_len);
3698}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition: address.c:235
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:780
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1164
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1199
const char * fmt_af_family(sa_family_t family)
Definition: address.c:1246
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:187
#define TOR_ADDR_BUF_LEN
Definition: address.h:224
#define tor_addr_eq(a, b)
Definition: address.h:280
int trusted_dirs_load_certs_from_string(const char *contents, int source, int flush, const char *source_dir)
Definition: authcert.c:373
Header file for authcert.c.
authority_cert_t * authority_cert_parse_from_string(const char *s, size_t maxlen, const char **end_of_string)
Header file for authcert_parse.c.
int authdir_mode(const or_options_t *options)
Definition: authmode.c:25
Header file for directory authority mode.
Authority certificate structure.
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition: binascii.c:215
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:506
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
int bwhist_bandwidth_assess(void)
Definition: bwhist.c:241
char * bwhist_get_bandwidth_lines(void)
Definition: bwhist.c:332
Header for feature/stats/bwhist.c.
#define ARRAY_LENGTH(x)
tor_mutex_t * tor_mutex_new(void)
Definition: compat_mutex.c:17
void tor_mutex_release(tor_mutex_t *m)
void tor_mutex_acquire(tor_mutex_t *m)
#define tor_mutex_free(m)
Definition: compat_mutex.h:73
int portconf_get_first_advertised_port(int listener_type, int address_family)
Definition: config.c:6820
const char * name
Definition: config.c:2462
int create_keys_directory(const or_options_t *options)
Definition: config.c:1401
const or_options_t * get_options(void)
Definition: config.c:944
int port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr, int port, int check_wildcard)
Definition: config.c:6847
tor_cmdline_mode_t command
Definition: config.c:2468
const tor_addr_t * portconf_get_first_advertised_addr(int listener_type, int address_family)
Definition: config.c:6832
Header file for config.c.
Header for confline.c.
Header file for connection.c.
#define CONN_TYPE_DIR_LISTENER
Definition: connection.h:53
#define CONN_TYPE_OR_LISTENER
Definition: connection.h:41
int control_event_my_descriptor_changed(void)
Header file for control_events.c.
int curve25519_keypair_write_to_file(const curve25519_keypair_t *keypair, const char *fname, const char *tag)
int curve25519_keypair_read_from_file(curve25519_keypair_t *keypair_out, char **tag_out, const char *fname)
int curve25519_keypair_generate(curve25519_keypair_t *keypair_out, int extra_strong)
void curve25519_public_to_base64(char *output, const curve25519_public_key_t *pkey, bool pad)
#define BASE64_DIGEST256_LEN
Definition: crypto_digest.h:29
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
int crypto_digest256(char *digest, const char *m, size_t len, digest_algorithm_t algorithm)
int ed25519_sign(ed25519_signature_t *signature_out, const uint8_t *msg, size_t len, const ed25519_keypair_t *keypair)
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
Header for crypto_ed25519.c.
void digest256_to_base64(char *d64, const char *digest)
void ed25519_signature_to_base64(char *output, const ed25519_signature_t *sig)
void ed25519_public_to_base64(char *output, const ed25519_public_key_t *pkey)
Header for crypto_format.c.
Headers for crypto_init.c.
Common functions for using (pseudo-)random number generators.
int crypto_rand_int_range(unsigned int min, unsigned int max)
int crypto_rand_int(unsigned int max)
int crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
Definition: crypto_rsa.c:229
int crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
Definition: crypto_rsa.c:71
int crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest, size_t *len)
Definition: crypto_rsa.c:466
int crypto_pk_write_private_key_to_filename(crypto_pk_t *env, const char *fname)
Definition: crypto_rsa.c:610
int crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
Definition: crypto_rsa.c:254
int crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
Definition: crypto_rsa.c:356
crypto_pk_t * crypto_pk_new(void)
int crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
crypto_pk_t * crypto_pk_asn1_decode(const char *str, size_t len)
crypto_pk_t * crypto_pk_copy_full(crypto_pk_t *orig)
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
#define FINGERPRINT_LEN
Definition: crypto_rsa.h:34
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
Common functions for cryptographic routines.
void dimap_add_entry(di_digest256_map_t **map, const uint8_t *key, void *val)
Definition: di_ops.c:176
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
#define dimap_free(map, free_fn)
Definition: di_ops.h:63
#define fast_memeq(a, b, c)
Definition: di_ops.h:35
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
#define DIGEST_LEN
Definition: digest_sizes.h:20
#define DIGEST256_LEN
Definition: digest_sizes.h:23
Client/server directory connection structure.
Trusted/fallback directory server structure.
void directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose, dirinfo_type_t type, const char *payload, size_t payload_len, size_t extrainfo_len)
Definition: dirclient.c:229
Header file for dirclient.c.
Header file for directory.c.
#define DIR_PURPOSE_UPLOAD_DIR
Definition: directory.h:41
dir_server_t * router_get_trusteddirserver_by_digest(const char *digest)
Definition: dirlist.c:160
void dir_server_add(dir_server_t *ent)
Definition: dirlist.c:564
dir_server_t * trusted_dir_server_new(const char *nickname, const char *address, uint16_t ipv4_dirport, uint16_t ipv4_orport, const tor_addr_port_t *ipv6_addrport, const char *digest, const char *v3_auth_digest, dirinfo_type_t type, double weight)
Definition: dirlist.c:419
Header file for dirlist.c.
int directory_permits_begindir_requests(const or_options_t *options)
Definition: dirserv.c:110
Header file for dirserv.c.
int dns_seems_to_be_broken(void)
Definition: dns.c:2139
int has_dns_init_failed(void)
Definition: dns.c:274
Header file for dns.c.
const char * escaped(const char *s)
Definition: escape.c:126
A relay's extra-info structure.
int tor_unlink(const char *pathname)
Definition: files.c:155
file_status_t file_status(const char *filename)
Definition: files.c:213
int write_str_to_file_if_not_equal(const char *fname, const char *str)
Definition: files.c:745
int replace_file(const char *from, const char *to)
Definition: files.c:118
const char * geoip_db_digest(sa_family_t family)
Definition: geoip.c:473
int geoip_is_loaded(sa_family_t family)
Definition: geoip.c:458
Header file for geoip.c.
Header file for geoip_stats.c.
const char * geoip_get_bridge_stats_extrainfo(time_t)
Definition: geoip_stats.c:1301
int should_record_bridge_info(const or_options_t *options)
Definition: geoip_stats.c:112
int accounting_is_enabled(const or_options_t *options)
Definition: hibernate.c:305
int we_are_hibernating(void)
Definition: hibernate.c:937
int accounting_get_interval_length(void)
Definition: hibernate.c:315
Header file for hibernate.c.
uint16_t sa_family_t
Definition: inaddr_st.h:77
crypto_pk_t * init_key_from_file(const char *fname, int generate, int severity, bool *created_out)
Definition: loadkey.c:40
Header file for loadkey.c.
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:591
#define log_fn(severity, domain, args,...)
Definition: log.h:283
#define LD_OR
Definition: log.h:92
#define LOG_ERR
Definition: log.h:56
#define LD_FS
Definition: log.h:70
#define LD_BUG
Definition: log.h:86
#define LD_GENERAL
Definition: log.h:62
#define LD_DIR
Definition: log.h:88
#define LOG_NOTICE
Definition: log.h:50
#define LD_CONFIG
Definition: log.h:68
#define LOG_WARN
Definition: log.h:53
int try_locking(const or_options_t *options, int err_if_locked)
Definition: main.c:661
int have_lockfile(void)
Definition: main.c:697
Header file for main.c.
void ip_address_changed(int on_client_conn)
Definition: mainloop.c:2318
smartlist_t * get_connection_array(void)
Definition: mainloop.c:443
long get_uptime(void)
Definition: mainloop.c:2557
Header file for mainloop.c.
#define tor_free(p)
Definition: malloc.h:56
int net_is_disabled(void)
Definition: netstatus.c:25
Header for netstatus.c.
const routerstatus_t * networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
networkstatus_t * networkstatus_get_live_consensus(time_t now)
Header file for networkstatus.c.
Networkstatus consensus/vote structure.
int is_legal_nickname_or_hexdigest(const char *s)
Definition: nickname.c:31
int is_legal_hexdigest(const char *s)
Definition: nickname.c:45
Header file for nickname.c.
Node information structure.
char * nodefamily_format(const nodefamily_t *family)
Definition: nodefamily.c:374
nodefamily_t * nodefamily_from_members(const smartlist_t *members, const uint8_t *rsa_id_self, unsigned flags, smartlist_t *unrecognized_out)
Definition: nodefamily.c:159
Header file for nodefamily.c.
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1085
consensus_path_type_t router_have_consensus_path(void)
Definition: nodelist.c:2438
Header file for nodelist.c.
Master header file for Tor-specific functionality.
@ SAVED_NOWHERE
Definition: or.h:626
#define MAX_ONION_KEY_LIFETIME_DAYS
Definition: or.h:136
#define MAX_EXTRAINFO_UPLOAD_SIZE
Definition: or.h:130
#define CFG_AUTO_PORT
Definition: or.h:891
#define MIN_ONION_KEY_LIFETIME_DAYS
Definition: or.h:133
#define MIN_ONION_KEY_GRACE_PERIOD_DAYS
Definition: or.h:144
#define DEFAULT_ONION_KEY_LIFETIME_DAYS
Definition: or.h:139
dirinfo_type_t
Definition: or.h:787
@ V3_DIRINFO
Definition: or.h:790
@ BRIDGE_DIRINFO
Definition: or.h:792
@ EXTRAINFO_DIRINFO
Definition: or.h:794
@ MICRODESC_DIRINFO
Definition: or.h:796
#define DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS
Definition: or.h:147
The or_state_t structure, which represents Tor's state file.
int policies_parse_exit_policy_from_options(const or_options_t *or_options, const tor_addr_t *ipv4_local_address, const tor_addr_t *ipv6_local_address, smartlist_t **result)
Definition: policies.c:2123
char * policy_dump_to_string(const smartlist_t *policy_list, int include_ipv4, int include_ipv6)
Definition: policies.c:2945
addr_policy_result_t compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port, const smartlist_t *policy)
Definition: policies.c:1536
char * write_short_policy(const short_policy_t *policy)
Definition: policies.c:2806
addr_policy_result_t compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port, const short_policy_t *policy)
Definition: policies.c:2842
int policy_is_reject_star(const smartlist_t *policy, sa_family_t family, int default_reject)
Definition: policies.c:2264
char * policy_summarize(smartlist_t *policy, sa_family_t family)
Definition: policies.c:2593
short_policy_t * parse_short_policy(const char *summary)
Definition: policies.c:2705
void policies_exit_policy_append_reject_star(smartlist_t **dest)
Definition: policies.c:2186
Header file for policies.c.
@ ADDR_POLICY_ACCEPTED
Definition: policies.h:40
Listener port configuration structure.
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
int dirserv_load_fingerprint_file(void)
was_router_added_t dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
int dirserv_add_own_fingerprint(crypto_pk_t *pk, const ed25519_public_key_t *edkey)
Header file for process_descs.c.
const char * protover_get_supported_protocols(void)
C_RUST_COUPLED: src/rust/protover/protover.rs SUPPORTED_PROTOCOLS
Definition: protover.c:437
Headers and type declarations for protover.c.
uint32_t relay_get_effective_bwrate(const or_options_t *options)
Definition: relay_config.c:94
uint32_t relay_get_effective_bwburst(const or_options_t *options)
Definition: relay_config.c:108
Header for feature/relay/relay_config.c.
bool relay_find_addr_to_publish(const or_options_t *options, int family, int flags, tor_addr_t *addr_out)
Header file for relay_find_addr.c.
void reschedule_descriptor_update_check(void)
Header for feature/relay/relay_periodic.c.
char * rep_hist_get_overload_stats_lines(void)
Definition: rephist.c:494
char * rep_hist_get_overload_general_line(void)
Definition: rephist.c:476
char * rep_hist_get_padding_count_lines(void)
Definition: rephist.c:2916
Header file for rephist.c.
const char * resolved_addr_method_to_str(const resolved_addr_method_t method)
Definition: resolve_addr.c:81
Header file for resolve_addr.c.
resolved_addr_method_t
Definition: resolve_addr.h:19
int router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
Definition: router.c:1721
STATIC smartlist_t * get_my_declared_family(const or_options_t *options)
Definition: router.c:1990
void ntor_key_map_free_(di_digest256_map_t *map)
Definition: router.c:356
static int should_publish_tap_onion_key(void)
Definition: router.c:233
static crypto_pk_t * onionkey
Definition: router.c:105
static tor_mutex_t * key_lock
Definition: router.c:102
void router_reset_warnings(void)
Definition: router.c:3623
void consider_publishable_server(int force)
Definition: router.c:1490
#define FAST_RETRY_DESCRIPTOR_INTERVAL
Definition: router.c:2555
static void router_check_descriptor_address_consistency(const tor_addr_t *addr)
Definition: router.c:1972
int router_has_bandwidth_to_be_dirserver(const or_options_t *options)
Definition: router.c:1267
static int extrainfo_dump_to_string_ed_sig_helper(smartlist_t *chunks, const ed25519_keypair_t *signing_keypair)
Definition: router.c:3441
void v3_authority_check_key_expiry(void)
Definition: router.c:755
void router_new_consensus_params(const networkstatus_t *ns)
Definition: router.c:2517
static const char * desc_gen_reason
Definition: router.c:1661
STATIC extrainfo_t * router_build_fresh_signed_extrainfo(const routerinfo_t *ri)
Definition: router.c:2326
void router_free_all(void)
Definition: router.c:3633
static bool publish_even_when_ipv4_orport_unreachable
Definition: router.c:1422
crypto_pk_t * get_tlsclient_identity_key(void)
Definition: router.c:456
static curve25519_keypair_t last_curve25519_onion_key
Definition: router.c:113
static void assert_identity_keys_ok(void)
Definition: router.c:400
uint16_t routerconf_find_or_port(const or_options_t *options, sa_family_t family)
Definition: router.c:1531
static int extrainfo_dump_to_string_header_helper(smartlist_t *chunks, const extrainfo_t *extrainfo, const ed25519_keypair_t *signing_keypair, int emit_ed_sigs)
Definition: router.c:3282
static int desc_needs_upload
Definition: router.c:1668
const char * router_get_descriptor_gen_reason(void)
Definition: router.c:1895
static int init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out, const char *fname, int generate, int severity, const char *tag)
Definition: router.c:609
static authority_cert_t * authority_key_certificate
Definition: router.c:127
void router_upload_dir_desc_to_dirservers(int force)
Definition: router.c:1675
#define MAX_BANDWIDTH_CHANGE_FREQ
Definition: router.c:2617
STATIC int router_write_fingerprint(int hashed, int ed25519_identity)
Definition: router.c:899
static bool omit_ipv6_on_publish
Definition: router.c:151
STATIC void router_update_routerinfo_from_extrainfo(routerinfo_t *ri, const extrainfo_t *ei)
Definition: router.c:2358
void log_addr_has_changed(int severity, const tor_addr_t *prev, const tor_addr_t *cur, const char *source)
Definition: router.c:2674
int extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo, crypto_pk_t *ident_key, const ed25519_keypair_t *signing_keypair)
Definition: router.c:3518
static crypto_pk_t * server_identitykey
Definition: router.c:116
int init_keys(void)
Definition: router.c:991
int get_onion_key_grace_period(void)
Definition: router.c:828
static smartlist_t * warned_family
Definition: router.c:1982
void check_descriptor_ipaddress_changed(time_t now)
Definition: router.c:2708
#define FORCE_REGENERATE_DESCRIPTOR_INTERVAL
Definition: router.c:2551
STATIC int router_dump_and_sign_routerinfo_descriptor_body(routerinfo_t *ri)
Definition: router.c:2386
const uint8_t * router_get_my_id_digest(void)
Definition: router.c:1776
STATIC void router_announce_bridge_status_page(void)
Definition: router.c:877
bool router_addr_is_my_published_addr(const tor_addr_t *addr)
Definition: router.c:1808
static int decide_if_publishable_server(void)
Definition: router.c:1443
crypto_pk_t * get_my_v3_legacy_signing_key(void)
Definition: router.c:498
static curve25519_keypair_t curve25519_onion_key
Definition: router.c:110
int router_initialize_tls_context(void)
Definition: router.c:842
void set_client_identity_key(crypto_pk_t *k)
Definition: router.c:446
crypto_pk_t * get_my_v3_authority_signing_key(void)
Definition: router.c:481
static void extrainfo_dump_to_string_stats_helper(smartlist_t *chunks, int write_stats_to_extrainfo)
Definition: router.c:3346
void routerconf_find_ipv6_or_ap(const or_options_t *options, tor_addr_port_t *ipv6_ap_out)
Definition: router.c:1551
static crypto_pk_t * authority_signing_key
Definition: router.c:124
void dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
Definition: router.c:252
int router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
Definition: router.c:1387
static routerinfo_t * desc_routerinfo
Definition: router.c:1656
bool routerconf_has_ipv6_orport(const or_options_t *options)
Definition: router.c:1592
static char server_identitykey_digest[DIGEST_LEN]
Definition: router.c:118
void mark_my_descriptor_if_omit_ipv6_changes(const char *reason, bool omit_ipv6)
Definition: router.c:2538
STATIC int router_build_fresh_unsigned_routerinfo(routerinfo_t **ri_out)
Definition: router.c:2115
time_t get_onion_key_set_at(void)
Definition: router.c:368
static void set_onion_key(crypto_pk_t *k)
Definition: router.c:200
extrainfo_t * router_get_my_extrainfo(void)
Definition: router.c:1883
uint16_t router_get_active_listener_port_by_type_af(int listener_type, sa_family_t family)
Definition: router.c:1511
static int init_v3_authority_keys(void)
Definition: router.c:738
static int router_should_be_dirserver(const or_options_t *options, int dir_port)
Definition: router.c:1287
#define MIN_BW_TO_ADVERTISE_DIRSERVER
Definition: router.c:1261
const routerinfo_t * router_get_my_routerinfo_with_err(int *err)
Definition: router.c:1840
bool rotate_onion_key(void)
Definition: router.c:513
crypto_pk_t * get_onion_key(void)
Definition: router.c:222
static int router_should_advertise_begindir(const or_options_t *options, int supports_tunnelled_dir_requests)
Definition: router.c:1397
static crypto_pk_t * lastonionkey
Definition: router.c:108
void expire_old_onion_keys(void)
Definition: router.c:276
static int decide_to_advertise_dir_impl(const or_options_t *options, uint16_t dir_port, int supports_tunnelled_dir_requests)
Definition: router.c:1356
int client_identity_key_is_set(void)
Definition: router.c:465
int server_identity_key_is_set(void)
Definition: router.c:436
STATIC const char * desc_dirty_reason
Definition: router.c:1666
static bool publish_even_when_ipv6_orport_unreachable
Definition: router.c:1427
bool router_rebuild_descriptor(int force)
Definition: router.c:2483
static crypto_pk_t * legacy_signing_key
Definition: router.c:131
static authority_cert_t * legacy_key_certificate
Definition: router.c:134
int router_extrainfo_digest_is_me(const char *digest)
Definition: router.c:1784
void check_descriptor_bandwidth_changed(time_t now)
Definition: router.c:2630
int get_onion_key_lifetime(void)
Definition: router.c:818
#define MAX_UPTIME_BANDWIDTH_CHANGE
Definition: router.c:2621
static extrainfo_t * router_build_fresh_unsigned_extrainfo(const routerinfo_t *ri)
Definition: router.c:2254
int router_digest_is_me(const char *digest)
Definition: router.c:1768
static int router_dump_and_sign_extrainfo_descriptor_body(extrainfo_t *ei)
Definition: router.c:2293
const char * router_get_my_descriptor(void)
Definition: router.c:1866
bool router_can_extend_over_ipv6(const or_options_t *options)
Definition: router.c:1623
int router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
Definition: router.c:2420
STATIC const struct curve25519_keypair_t * get_current_curve25519_keypair(void)
Definition: router.c:316
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2599
static int get_onion_key_rotation_days_(void)
Definition: router.c:804
void mark_my_descriptor_dirty_if_too_old(time_t now)
Definition: router.c:2560
char * router_dump_exit_policy_to_string(const routerinfo_t *router, int include_ipv4, int include_ipv6)
Definition: router.c:3190
STATIC int load_stats_file(const char *filename, const char *ts_tag, time_t now, char **out)
Definition: router.c:3217
static time_t onionkey_set_at
Definition: router.c:103
void set_server_identity_key(crypto_pk_t *k)
Definition: router.c:376
int router_is_me(const routerinfo_t *router)
Definition: router.c:1797
static int extrainfo_dump_to_string_rsa_sig_helper(smartlist_t *chunks, crypto_pk_t *ident_key, const char *extrainfo_string)
Definition: router.c:3478
static void ntor_key_map_free_helper(void *arg)
Definition: router.c:348
static crypto_pk_t * client_identitykey
Definition: router.c:122
static void log_new_relay_greeting(void)
Definition: router.c:587
const routerinfo_t * router_get_my_routerinfo(void)
Definition: router.c:1830
static int load_authority_keyset(int legacy, crypto_pk_t **key_out, authority_cert_t **cert_out)
Definition: router.c:681
authority_cert_t * get_my_v3_authority_cert(void)
Definition: router.c:473
STATIC time_t desc_clean_since
Definition: router.c:1664
uint16_t routerconf_find_dir_port(const or_options_t *options, uint16_t dirport)
Definition: router.c:1636
int routerinfo_err_is_transient(int err)
Definition: router.c:186
#define BANDWIDTH_CHANGE_FACTOR
Definition: router.c:2624
char * router_dump_router_to_string(routerinfo_t *router, const crypto_pk_t *ident_key, const crypto_pk_t *tap_key, const curve25519_keypair_t *ntor_keypair, const ed25519_keypair_t *signing_keypair)
Definition: router.c:2793
const char * routerinfo_err_to_string(int err)
Definition: router.c:157
int router_my_exit_policy_is_reject_star(void)
Definition: router.c:1756
static extrainfo_t * desc_extrainfo
Definition: router.c:1658
STATIC void get_platform_str(char *platform, size_t len)
Definition: router.c:2772
int should_refuse_unknown_exits(const or_options_t *options)
Definition: router.c:1409
authority_cert_t * get_my_v3_legacy_cert(void)
Definition: router.c:490
di_digest256_map_t * construct_ntor_key_map(void)
Definition: router.c:324
Header file for router.c.
Router descriptor structure.
#define ROUTER_PURPOSE_GENERAL
#define ROUTER_PURPOSE_BRIDGE
int load_ed_keys(const or_options_t *options, time_t now)
Definition: routerkeys.c:55
uint8_t * make_tap_onion_key_crosscert(const crypto_pk_t *onion_key, const ed25519_public_key_t *master_id_key, const crypto_pk_t *rsa_id_key, int *len_out)
Definition: routerkeys.c:712
tor_cert_t * make_ntor_onion_key_crosscert(const curve25519_keypair_t *onion_key, const ed25519_public_key_t *master_id_key, time_t now, time_t lifetime, int *sign_out)
Definition: routerkeys.c:689
int generate_ed_link_cert(const or_options_t *options, time_t now, int force)
Definition: routerkeys.c:365
Header for routerkeys.c.
const char * signed_descriptor_get_body(const signed_descriptor_t *desc)
Definition: routerlist.c:883
int routerinfo_incompatible_with_extrainfo(const crypto_pk_t *identity_pkey, extrainfo_t *ei, signed_descriptor_t *sd, const char **msg)
Definition: routerlist.c:3077
Header file for routerlist.c.
static int WRA_WAS_ADDED(was_router_added_t s)
Definition: routerlist.h:106
static int WRA_WAS_OUTDATED(was_router_added_t s)
Definition: routerlist.h:116
was_router_added_t
Definition: routerlist.h:17
int public_server_mode(const or_options_t *options)
Definition: routermode.c:43
int server_mode(const or_options_t *options)
Definition: routermode.c:34
void set_server_advertised(int s)
Definition: routermode.c:65
Header file for routermode.c.
routerinfo_t * router_parse_entry_from_string(const char *s, const char *end, int cache_copy, int allow_annotations, const char *prepend_annotations, int *can_dl_again_out)
Definition: routerparse.c:394
int router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
Definition: routerparse.c:190
extrainfo_t * extrainfo_parse_entry_from_string(const char *s, const char *end, int cache_copy, struct digest_ri_map_t *routermap, int *can_dl_again_out)
Definition: routerparse.c:985
int router_get_router_hash(const char *s, size_t s_len, char *digest)
Definition: routerparse.c:180
Header file for routerparse.c.
Routerstatus (consensus entry) structure.
int router_orport_seems_reachable(const or_options_t *options, int family)
Definition: selftest.c:101
int router_dirport_seems_reachable(const or_options_t *options)
Definition: selftest.c:137
Header file for selftest.c.
int router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest, size_t digest_len, crypto_pk_t *private_key)
Definition: signing.c:79
char * router_get_dirobj_signature(const char *digest, size_t digest_len, const crypto_pk_t *private_key)
Definition: signing.c:22
Header file for signing.c.
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
int smartlist_contains_string(const smartlist_t *sl, const char *element)
Definition: smartlist.c:93
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
void smartlist_del_keeporder(smartlist_t *sl, int idx)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
void or_state_mark_dirty(or_state_t *state, time_t when)
Definition: statefile.c:784
or_state_t * get_or_state(void)
Definition: statefile.c:220
Header for statefile.c.
crypto_pk_t * signing_key
signed_descriptor_t cache_info
dirinfo_type_t type
Definition: dir_server_st.h:48
char v3_identity_digest[DIGEST_LEN]
Definition: dir_server_st.h:36
uint8_t digest256[DIGEST256_LEN]
Definition: extrainfo_st.h:21
char nickname[MAX_NICKNAME_LEN+1]
Definition: extrainfo_st.h:23
Definition: node_st.h:34
char identity[DIGEST_LEN]
Definition: node_st.h:46
int ExitPortStatistics
dirinfo_type_t PublishServerDescriptor_
struct config_line_t * MyFamily
int RefuseUnknownExits
char * ContactInfo
char * BridgeDistribution
uint64_t BandwidthRate
int ExtraInfoStatistics
uint64_t AccountingMax
int OverloadStatistics
char * Nickname
Definition: or_options_st.h:97
int HiddenServiceStatistics
struct config_line_t * ServerTransportPlugin
int V3AuthoritativeDir
uint64_t RelayBandwidthRate
int ConnDirectionStatistics
tor_cmdline_mode_t command
Definition: or_options_st.h:68
int BridgeAuthoritativeDir
time_t LastRotatedOnionKey
Definition: or_state_st.h:92
char * platform
Definition: routerinfo_st.h:51
tor_addr_t ipv6_addr
Definition: routerinfo_st.h:30
tor_addr_t ipv4_addr
Definition: routerinfo_st.h:25
smartlist_t * exit_policy
Definition: routerinfo_st.h:62
smartlist_t * declared_family
Definition: routerinfo_st.h:68
uint32_t bandwidthrate
Definition: routerinfo_st.h:57
crypto_pk_t * identity_pkey
Definition: routerinfo_st.h:44
size_t tap_onion_pkey_len
Definition: routerinfo_st.h:42
struct curve25519_public_key_t * onion_curve25519_pkey
Definition: routerinfo_st.h:46
unsigned int policy_is_reject_star
Definition: routerinfo_st.h:80
char * protocol_list
Definition: routerinfo_st.h:53
uint8_t purpose
unsigned int supports_tunnelled_dir_requests
Definition: routerinfo_st.h:89
uint32_t bandwidthcapacity
Definition: routerinfo_st.h:61
uint32_t bandwidthburst
Definition: routerinfo_st.h:59
char * tap_onion_pkey
Definition: routerinfo_st.h:40
char * nickname
Definition: routerinfo_st.h:22
struct short_policy_t * ipv6_exit_policy
Definition: routerinfo_st.h:66
unsigned int is_staledesc
char signed_descriptor_digest[DIGEST_LEN]
char extra_info_digest[DIGEST_LEN]
char identity_digest[DIGEST_LEN]
struct tor_cert_st * signing_key_cert
char extra_info_digest256[DIGEST256_LEN]
saved_location_t saved_location
size_t encoded_len
Definition: torcert.h:42
uint8_t * encoded
Definition: torcert.h:40
#define STATIC
Definition: testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
int parse_iso_time(const char *cp, time_t *t)
Definition: time_fmt.c:423
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:326
@ CMD_RUN_TOR
@ CMD_KEY_EXPIRATION
tor_cert_t * tor_cert_dup(const tor_cert_t *cert)
Definition: torcert.c:294
Header for torcert.c.
int tor_tls_context_init(unsigned flags, crypto_pk_t *client_identity, crypto_pk_t *server_identity, unsigned int key_lifetime)
Definition: tortls.c:182
Headers for tortls.c.
Header for version.c.
const char * get_short_version(void)
Definition: version.c:56
char * pt_get_extra_info_descriptor_string(void)
Definition: transports.c:1742
Headers for transports.c.
const char * get_uname(void)
Definition: uname.c:67
Header for uname.c.
#define tor_assert(expr)
Definition: util_bug.h:103
#define IF_BUG_ONCE(cond)
Definition: util_bug.h:254
void tor_strlower(char *s)
Definition: util_string.c:129
int tor_digest256_is_zero(const char *digest)
Definition: util_string.c:105
int fast_mem_is_zero(const char *mem, size_t len)
Definition: util_string.c:76
const char * find_str_at_start_of_line(const char *haystack, const char *needle)
Definition: util_string.c:402
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:98
#define CURVE25519_BASE64_PADDED_LEN
Definition: x25519_sizes.h:37
#define ED25519_BASE64_LEN
Definition: x25519_sizes.h:43
#define ED25519_SIG_BASE64_LEN
Definition: x25519_sizes.h:45
#define CURVE25519_PUBKEY_LEN
Definition: x25519_sizes.h:20