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