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