Tor  0.4.3.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-2019, 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 so it gets recognized. */
1078  if (dirserv_add_own_fingerprint(get_server_identity_key())) {
1079  log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
1080  return -1;
1081  }
1082  if (mydesc) {
1083  was_router_added_t added;
1084  ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
1085  if (!ri) {
1086  log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
1087  return -1;
1088  }
1089  added = dirserv_add_descriptor(ri, &m, "self");
1090  if (!WRA_WAS_ADDED(added)) {
1091  if (!WRA_WAS_OUTDATED(added)) {
1092  log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
1093  m?m:"<unknown error>");
1094  return -1;
1095  } else {
1096  /* If the descriptor was outdated, that's ok. This can happen
1097  * when some config options are toggled that affect workers, but
1098  * we don't really need new keys yet so the descriptor doesn't
1099  * change and the old one is still fresh. */
1100  log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
1101  "after key init: %s This is usually not a problem.",
1102  m?m:"<unknown error>");
1103  }
1104  }
1105  }
1106  }
1107 
1108  /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
1109  if (router_write_fingerprint(0)) {
1110  log_err(LD_FS, "Error writing fingerprint to file");
1111  return -1;
1112  }
1113  if (!public_server_mode(options) && router_write_fingerprint(1)) {
1114  log_err(LD_FS, "Error writing hashed fingerprint to file");
1115  return -1;
1116  }
1117 
1118  if (!authdir_mode(options))
1119  return 0;
1120  /* 6. [authdirserver only] load approved-routers file */
1121  if (dirserv_load_fingerprint_file() < 0) {
1122  log_err(LD_GENERAL,"Error loading fingerprints");
1123  return -1;
1124  }
1125  /* 6b. [authdirserver only] add own key to approved directories. */
1126  crypto_pk_get_digest(get_server_identity_key(), digest);
1127  type = ((options->V3AuthoritativeDir ?
1129  (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
1130 
1132  if (!ds) {
1133  ds = trusted_dir_server_new(options->Nickname, NULL,
1134  router_get_advertised_dir_port(options, 0),
1136  NULL,
1137  digest,
1138  v3_digest,
1139  type, 0.0);
1140  if (!ds) {
1141  log_err(LD_GENERAL,"We want to be a directory authority, but we "
1142  "couldn't add ourselves to the authority list. Failing.");
1143  return -1;
1144  }
1145  dir_server_add(ds);
1146  }
1147  if (ds->type != type) {
1148  log_warn(LD_DIR, "Configured authority type does not match authority "
1149  "type in DirAuthority list. Adjusting. (%d v %d)",
1150  type, ds->type);
1151  ds->type = type;
1152  }
1153  if (v3_digest_set && (ds->type & V3_DIRINFO) &&
1154  tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
1155  log_warn(LD_DIR, "V3 identity key does not match identity declared in "
1156  "DirAuthority line. Adjusting.");
1157  memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
1158  }
1159 
1160  if (cert) { /* add my own cert to the list of known certs */
1161  log_info(LD_DIR, "adding my own v3 cert");
1164  TRUSTED_DIRS_CERTS_SRC_SELF, 0,
1165  NULL)<0) {
1166  log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1167  return -1;
1168  }
1169  }
1170 
1171  return 0; /* success */
1172 }
1173 
1174 /** The lower threshold of remaining bandwidth required to advertise (or
1175  * automatically provide) directory services */
1176 /* XXX Should this be increased? */
1177 #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
1178 
1179 /** Return true iff we have enough configured bandwidth to advertise or
1180  * automatically provide directory services from cache directory
1181  * information. */
1182 int
1184 {
1186  return 0;
1187  }
1188  if (options->RelayBandwidthRate > 0 &&
1190  return 0;
1191  }
1192  return 1;
1193 }
1194 
1195 /** Helper: Return 1 if we have sufficient resources for serving directory
1196  * requests, return 0 otherwise.
1197  * dir_port is either 0 or the configured DirPort number.
1198  * If AccountingMax is set less than our advertised bandwidth, then don't
1199  * serve requests. Likewise, if our advertised bandwidth is less than
1200  * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
1201  */
1202 static int
1203 router_should_be_dirserver(const or_options_t *options, int dir_port)
1204 {
1205  static int advertising=1; /* start out assuming we will advertise */
1206  int new_choice=1;
1207  const char *reason = NULL;
1208 
1209  if (accounting_is_enabled(options) &&
1210  get_options()->AccountingRule != ACCT_IN) {
1211  /* Don't spend bytes for directory traffic if we could end up hibernating,
1212  * but allow DirPort otherwise. Some relay operators set AccountingMax
1213  * because they're confused or to get statistics. Directory traffic has a
1214  * much larger effect on output than input so there is no reason to turn it
1215  * off if using AccountingRule in. */
1216  int interval_length = accounting_get_interval_length();
1217  uint32_t effective_bw = relay_get_effective_bwrate(options);
1218  uint64_t acc_bytes;
1219  if (!interval_length) {
1220  log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1221  "seconds long. Raising to 1.");
1222  interval_length = 1;
1223  }
1224  log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
1225  "bwrate: %u, AccountingMax: %"PRIu64", "
1226  "accounting interval length %d",
1227  dir_port ? "dirport" : "begindir",
1228  effective_bw, (options->AccountingMax),
1229  interval_length);
1230 
1231  acc_bytes = options->AccountingMax;
1232  if (get_options()->AccountingRule == ACCT_SUM)
1233  acc_bytes /= 2;
1234  if (effective_bw >=
1235  acc_bytes / interval_length) {
1236  new_choice = 0;
1237  reason = "AccountingMax enabled";
1238  }
1239  } else if (! router_has_bandwidth_to_be_dirserver(options)) {
1240  /* if we're advertising a small amount */
1241  new_choice = 0;
1242  reason = "BandwidthRate under 50KB";
1243  }
1244 
1245  if (advertising != new_choice) {
1246  if (new_choice == 1) {
1247  if (dir_port > 0)
1248  log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1249  else
1250  log_notice(LD_DIR, "Advertising directory service support");
1251  } else {
1252  tor_assert(reason);
1253  log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
1254  dir_port ? "Port" : "ectory Service support", reason);
1255  }
1256  advertising = new_choice;
1257  }
1258 
1259  return advertising;
1260 }
1261 
1262 /** Look at a variety of factors, and return 0 if we don't want to
1263  * advertise the fact that we have a DirPort open or begindir support, else
1264  * return 1.
1265  *
1266  * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1267  * must be 0.
1268  *
1269  * Log a helpful message if we change our mind about whether to publish.
1270  */
1271 static int
1273  uint16_t dir_port,
1274  int supports_tunnelled_dir_requests)
1275 {
1276  /* Part one: reasons to publish or not publish that aren't
1277  * worth mentioning to the user, either because they're obvious
1278  * or because they're normal behavior. */
1279 
1280  /* short circuit the rest of the function */
1281  if (!dir_port && !supports_tunnelled_dir_requests)
1282  return 0;
1283  if (authdir_mode(options)) /* always publish */
1284  return 1;
1285  if (net_is_disabled())
1286  return 0;
1287  if (dir_port && !router_get_advertised_dir_port(options, dir_port))
1288  return 0;
1289  if (supports_tunnelled_dir_requests &&
1291  return 0;
1292 
1293  /* Part two: consider config options that could make us choose to
1294  * publish or not publish that the user might find surprising. */
1295  return router_should_be_dirserver(options, dir_port);
1296 }
1297 
1298 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1299  * advertise the fact that we have a DirPort open, else return the
1300  * DirPort we want to advertise.
1301  */
1302 int
1303 router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1304 {
1305  /* supports_tunnelled_dir_requests is not relevant, pass 0 */
1306  return decide_to_advertise_dir_impl(options, dir_port, 0) ? dir_port : 0;
1307 }
1308 
1309 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1310  * advertise the fact that we support begindir requests, else return 1.
1311  */
1312 static int
1314  int supports_tunnelled_dir_requests)
1315 {
1316  /* dir_port is not relevant, pass 0 */
1317  return decide_to_advertise_dir_impl(options, 0,
1318  supports_tunnelled_dir_requests);
1319 }
1320 
1321 /** Return true iff the combination of options in <b>options</b> and parameters
1322  * in the consensus mean that we don't want to allow exits from circuits
1323  * we got from addresses not known to be servers. */
1324 int
1326 {
1327  if (options->RefuseUnknownExits != -1) {
1328  return options->RefuseUnknownExits;
1329  } else {
1330  return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1331  }
1332 }
1333 
1334 /** Decide if we're a publishable server. We are a publishable server if:
1335  * - We don't have the ClientOnly option set
1336  * and
1337  * - We have the PublishServerDescriptor option set to non-empty
1338  * and
1339  * - We have ORPort set
1340  * and
1341  * - We believe our ORPort and DirPort (if present) are reachable from
1342  * the outside; or
1343  * - We believe our ORPort is reachable from the outside, and we can't
1344  * check our DirPort because the consensus has no exits; or
1345  * - We are an authoritative directory server.
1346  */
1347 static int
1349 {
1350  const or_options_t *options = get_options();
1351 
1352  if (options->ClientOnly)
1353  return 0;
1354  if (options->PublishServerDescriptor_ == NO_DIRINFO)
1355  return 0;
1356  if (!server_mode(options))
1357  return 0;
1358  if (authdir_mode(options))
1359  return 1;
1360  if (!router_get_advertised_or_port(options))
1361  return 0;
1362  if (!check_whether_orport_reachable(options))
1363  return 0;
1364  if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
1365  /* All set: there are no exits in the consensus (maybe this is a tiny
1366  * test network), so we can't check our DirPort reachability. */
1367  return 1;
1368  } else {
1369  return check_whether_dirport_reachable(options);
1370  }
1371 }
1372 
1373 /** Initiate server descriptor upload as reasonable (if server is publishable,
1374  * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1375  *
1376  * We need to rebuild the descriptor if it's dirty even if we're not
1377  * uploading, because our reachability testing *uses* our descriptor to
1378  * determine what IP address and ports to test.
1379  */
1380 void
1382 {
1383  int rebuilt;
1384 
1385  if (!server_mode(get_options()))
1386  return;
1387 
1388  rebuilt = router_rebuild_descriptor(0);
1391  if (rebuilt == 0)
1393  } else {
1395  }
1396 }
1397 
1398 /** Return the port of the first active listener of type
1399  * <b>listener_type</b>. */
1400 /** XXX not a very good interface. it's not reliable when there are
1401  multiple listeners. */
1402 uint16_t
1404  sa_family_t family)
1405 {
1406  /* Iterate all connections, find one of the right kind and return
1407  the port. Not very sophisticated or fast, but effective. */
1408  smartlist_t *conns = get_connection_array();
1409  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1410  if (conn->type == listener_type && !conn->marked_for_close &&
1411  conn->socket_family == family) {
1412  return conn->port;
1413  }
1414  } SMARTLIST_FOREACH_END(conn);
1415 
1416  return 0;
1417 }
1418 
1419 /** Return the port that we should advertise as our ORPort; this is either
1420  * the one configured in the ORPort option, or the one we actually bound to
1421  * if ORPort is "auto".
1422  */
1423 uint16_t
1425 {
1426  return router_get_advertised_or_port_by_af(options, AF_INET);
1427 }
1428 
1429 /** As router_get_advertised_or_port(), but allows an address family argument.
1430  */
1431 uint16_t
1433  sa_family_t family)
1434 {
1436  family);
1437  (void)options;
1438 
1439  /* If the port is in 'auto' mode, we have to use
1440  router_get_listener_port_by_type(). */
1441  if (port == CFG_AUTO_PORT)
1443  family);
1444 
1445  return port;
1446 }
1447 
1448 /** Return the port that we should advertise as our DirPort;
1449  * this is one of three possibilities:
1450  * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1451  * the one configured in the DirPort option,
1452  * or the one we actually bound to if DirPort is "auto". */
1453 uint16_t
1454 router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
1455 {
1456  int dirport_configured = get_primary_dir_port();
1457  (void)options;
1458 
1459  if (!dirport_configured)
1460  return dirport;
1461 
1462  if (dirport_configured == CFG_AUTO_PORT)
1464  AF_INET);
1465 
1466  return dirport_configured;
1467 }
1468 
1469 /*
1470  * OR descriptor generation.
1471  */
1472 
1473 /** My routerinfo. */
1475 /** My extrainfo */
1477 /** Why did we most recently decide to regenerate our descriptor? Used to
1478  * tell the authorities why we're sending it to them. */
1479 static const char *desc_gen_reason = "uninitialized reason";
1480 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1481  * now. */
1483 /** Why did we mark the descriptor dirty? */
1484 STATIC const char *desc_dirty_reason = "Tor just started";
1485 /** Boolean: do we need to regenerate the above? */
1486 static int desc_needs_upload = 0;
1487 
1488 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1489  * descriptor successfully yet, try to upload our signed descriptor to
1490  * all the directory servers we know about.
1491  */
1492 void
1494 {
1495  const routerinfo_t *ri;
1496  extrainfo_t *ei;
1497  char *msg;
1498  size_t desc_len, extra_len = 0, total_len;
1500 
1501  ri = router_get_my_routerinfo();
1502  if (!ri) {
1503  log_info(LD_GENERAL, "No descriptor; skipping upload");
1504  return;
1505  }
1506  ei = router_get_my_extrainfo();
1507  if (auth == NO_DIRINFO)
1508  return;
1509  if (!force && !desc_needs_upload)
1510  return;
1511 
1512  log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1513  force ? " (forced)" : "");
1514 
1515  desc_needs_upload = 0;
1516 
1517  desc_len = ri->cache_info.signed_descriptor_len;
1518  extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1519  total_len = desc_len + extra_len + 1;
1520  msg = tor_malloc(total_len);
1521  memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1522  if (ei) {
1523  memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1524  }
1525  msg[desc_len+extra_len] = 0;
1526 
1528  (auth & BRIDGE_DIRINFO) ?
1531  auth, msg, desc_len, extra_len);
1532  tor_free(msg);
1533 }
1534 
1535 /** OR only: Check whether my exit policy says to allow connection to
1536  * conn. Return 0 if we accept; non-0 if we reject.
1537  */
1538 int
1540 {
1541  const routerinfo_t *me = router_get_my_routerinfo();
1542  if (!me) /* make sure routerinfo exists */
1543  return -1;
1544 
1545  /* make sure it's resolved to something. this way we can't get a
1546  'maybe' below. */
1547  if (tor_addr_is_null(addr))
1548  return -1;
1549 
1550  /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
1551  * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
1552  * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
1553  * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
1554  * summary. */
1555  if ((tor_addr_family(addr) == AF_INET ||
1556  tor_addr_family(addr) == AF_INET6)) {
1557  return compare_tor_addr_to_addr_policy(addr, port,
1559 #if 0
1560  } else if (tor_addr_family(addr) == AF_INET6) {
1561  return get_options()->IPv6Exit &&
1565 #endif /* 0 */
1566  } else {
1567  return -1;
1568  }
1569 }
1570 
1571 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1572  * have a descriptor */
1573 MOCK_IMPL(int,
1575 {
1576  const routerinfo_t *me = router_get_my_routerinfo();
1577  if (!me) /* make sure routerinfo exists */
1578  return -1;
1579 
1580  return me->policy_is_reject_star;
1581 }
1582 
1583 /** Return true iff I'm a server and <b>digest</b> is equal to
1584  * my server identity key digest. */
1585 int
1586 router_digest_is_me(const char *digest)
1587 {
1588  return (server_identitykey &&
1590 }
1591 
1592 /** Return my identity digest. */
1593 const uint8_t *
1595 {
1596  return (const uint8_t *)server_identitykey_digest;
1597 }
1598 
1599 /** Return true iff I'm a server and <b>digest</b> is equal to
1600  * my identity digest. */
1601 int
1603 {
1605  if (!ei)
1606  return 0;
1607 
1608  return tor_memeq(digest,
1609  ei->cache_info.signed_descriptor_digest,
1610  DIGEST_LEN);
1611 }
1612 
1613 /** A wrapper around router_digest_is_me(). */
1614 int
1616 {
1617  return router_digest_is_me(router->cache_info.identity_digest);
1618 }
1619 
1620 /** Return a routerinfo for this OR, rebuilding a fresh one if
1621  * necessary. Return NULL on error, or if called on an OP. */
1622 MOCK_IMPL(const routerinfo_t *,
1624 {
1625  return router_get_my_routerinfo_with_err(NULL);
1626 }
1627 
1628 /** Return routerinfo of this OR. Rebuild it from
1629  * scratch if needed. Set <b>*err</b> to 0 on success or to
1630  * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
1631  */
1632 MOCK_IMPL(const routerinfo_t *,
1634 {
1635  if (!server_mode(get_options())) {
1636  if (err)
1637  *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
1638 
1639  return NULL;
1640  }
1641 
1642  if (!desc_clean_since) {
1643  int rebuild_err = router_rebuild_descriptor(0);
1644  if (rebuild_err < 0) {
1645  if (err)
1646  *err = rebuild_err;
1647 
1648  return NULL;
1649  }
1650  }
1651 
1652  if (!desc_routerinfo) {
1653  if (err)
1654  *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
1655 
1656  return NULL;
1657  }
1658 
1659  if (err)
1660  *err = 0;
1661 
1662  return desc_routerinfo;
1663 }
1664 
1665 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1666  * one if necessary. Return NULL on error.
1667  */
1668 const char *
1670 {
1671  const char *body;
1672  const routerinfo_t *me = router_get_my_routerinfo();
1673  if (! me)
1674  return NULL;
1675  tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
1676  body = signed_descriptor_get_body(&me->cache_info);
1677  /* Make sure this is nul-terminated. */
1678  tor_assert(!body[me->cache_info.signed_descriptor_len]);
1679  log_debug(LD_GENERAL,"my desc is '%s'", body);
1680  return body;
1681 }
1682 
1683 /** Return the extrainfo document for this OR, or NULL if we have none.
1684  * Rebuilt it (and the server descriptor) if necessary. */
1685 extrainfo_t *
1687 {
1688  if (!server_mode(get_options()))
1689  return NULL;
1691  return NULL;
1692  return desc_extrainfo;
1693 }
1694 
1695 /** Return a human-readable string describing what triggered us to generate
1696  * our current descriptor, or NULL if we don't know. */
1697 const char *
1699 {
1700  return desc_gen_reason;
1701 }
1702 
1703 static int router_guess_address_from_dir_headers(uint32_t *guess);
1704 
1705 /** Make a current best guess at our address, either because
1706  * it's configured in torrc, or because we've learned it from
1707  * dirserver headers. Place the answer in *<b>addr</b> and return
1708  * 0 on success, else return -1 if we have no guess.
1709  *
1710  * If <b>cache_only</b> is true, just return any cached answers, and
1711  * don't try to get any new answers.
1712  */
1713 MOCK_IMPL(int,
1714 router_pick_published_address,(const or_options_t *options, uint32_t *addr,
1715  int cache_only))
1716 {
1717  /* First, check the cached output from resolve_my_address(). */
1718  *addr = get_last_resolved_addr();
1719  if (*addr)
1720  return 0;
1721 
1722  /* Second, consider doing a resolve attempt right here. */
1723  if (!cache_only) {
1724  if (resolve_my_address(LOG_INFO, options, addr, NULL, NULL) >= 0) {
1725  log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
1726  return 0;
1727  }
1728  }
1729 
1730  /* Third, check the cached output from router_new_address_suggestion(). */
1732  return 0;
1733 
1734  /* We have no useful cached answers. Return failure. */
1735  return -1;
1736 }
1737 
1738 /* Like router_check_descriptor_address_consistency, but specifically for the
1739  * ORPort or DirPort.
1740  * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
1741 static void
1742 router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr,
1743  int listener_type)
1744 {
1745  tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
1746  listener_type == CONN_TYPE_DIR_LISTENER);
1747 
1748  /* The first advertised Port may be the magic constant CFG_AUTO_PORT.
1749  */
1750  int port_v4_cfg = get_first_advertised_port_by_type_af(listener_type,
1751  AF_INET);
1752  if (port_v4_cfg != 0 &&
1753  !port_exists_by_type_addr32h_port(listener_type,
1754  ipv4h_desc_addr, port_v4_cfg, 1)) {
1756  listener_type,
1757  AF_INET);
1758  /* If we're building a descriptor with no advertised address,
1759  * something is terribly wrong. */
1760  tor_assert(port_addr);
1761 
1762  tor_addr_t desc_addr;
1763  char port_addr_str[TOR_ADDR_BUF_LEN];
1764  char desc_addr_str[TOR_ADDR_BUF_LEN];
1765 
1766  tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
1767 
1768  tor_addr_from_ipv4h(&desc_addr, ipv4h_desc_addr);
1769  tor_addr_to_str(desc_addr_str, &desc_addr, TOR_ADDR_BUF_LEN, 0);
1770 
1771  const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
1772  "OR" : "Dir");
1773  log_warn(LD_CONFIG, "The IPv4 %sPort address %s does not match the "
1774  "descriptor address %s. If you have a static public IPv4 "
1775  "address, use 'Address <IPv4>' and 'OutboundBindAddress "
1776  "<IPv4>'. If you are behind a NAT, use two %sPort lines: "
1777  "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
1778  "NoAdvertise'.",
1779  listener_str, port_addr_str, desc_addr_str, listener_str,
1780  listener_str, listener_str);
1781  }
1782 }
1783 
1784 /* Tor relays only have one IPv4 address in the descriptor, which is derived
1785  * from the Address torrc option, or guessed using various methods in
1786  * router_pick_published_address().
1787  * Warn the operator if there is no ORPort on the descriptor address
1788  * ipv4h_desc_addr.
1789  * Warn the operator if there is no DirPort on the descriptor address.
1790  * This catches a few common config errors:
1791  * - operators who expect ORPorts and DirPorts to be advertised on the
1792  * ports' listen addresses, rather than the torrc Address (or guessed
1793  * addresses in the absence of an Address config). This includes
1794  * operators who attempt to put their ORPort and DirPort on different
1795  * addresses;
1796  * - discrepancies between guessed addresses and configured listen
1797  * addresses (when the Address option isn't set).
1798  * If a listener is listening on all IPv4 addresses, it is assumed that it
1799  * is listening on the configured Address, and no messages are logged.
1800  * If an operators has specified NoAdvertise ORPorts in a NAT setting,
1801  * no messages are logged, unless they have specified other advertised
1802  * addresses.
1803  * The message tells operators to configure an ORPort and DirPort that match
1804  * the Address (using NoListen if needed).
1805  */
1806 static void
1807 router_check_descriptor_address_consistency(uint32_t ipv4h_desc_addr)
1808 {
1809  router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1811  router_check_descriptor_address_port_consistency(ipv4h_desc_addr,
1813 }
1814 
1815 /** A list of nicknames that we've warned about including in our family,
1816  * for one reason or another. */
1818 
1819 /**
1820  * Return a new smartlist containing the family members configured in
1821  * <b>options</b>. Warn about invalid or missing entries. Return NULL
1822  * if this relay should not declare a family.
1823  **/
1826 {
1827  if (!options->MyFamily)
1828  return NULL;
1829 
1830  if (options->BridgeRelay)
1831  return NULL;
1832 
1833  if (!warned_family)
1835 
1836  smartlist_t *declared_family = smartlist_new();
1837  config_line_t *family;
1838 
1839  /* First we try to get the whole family in the form of hexdigests. */
1840  for (family = options->MyFamily; family; family = family->next) {
1841  char *name = family->value;
1842  const node_t *member;
1843  if (options->Nickname && !strcasecmp(name, options->Nickname))
1844  continue; /* Don't list ourself by nickname, that's redundant */
1845  else
1846  member = node_get_by_nickname(name, 0);
1847 
1848  if (!member) {
1849  /* This node doesn't seem to exist, so warn about it if it is not
1850  * a hexdigest. */
1851  int is_legal = is_legal_nickname_or_hexdigest(name);
1854  if (is_legal)
1855  log_warn(LD_CONFIG,
1856  "There is a router named %s in my declared family, but "
1857  "I have no descriptor for it. I'll use the nickname "
1858  "as is, but this may confuse clients. Please list it "
1859  "by identity digest instead.", escaped(name));
1860  else
1861  log_warn(LD_CONFIG, "There is a router named %s in my declared "
1862  "family, but that isn't a legal digest or nickname. "
1863  "Skipping it.", escaped(name));
1865  }
1866  if (is_legal) {
1867  smartlist_add_strdup(declared_family, name);
1868  }
1869  } else {
1870  /* List the node by digest. */
1871  char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1872  fp[0] = '$';
1874  member->identity, DIGEST_LEN);
1875  smartlist_add(declared_family, fp);
1876 
1877  if (! is_legal_hexdigest(name) &&
1879  /* Warn if this node was not specified by hexdigest. */
1880  log_warn(LD_CONFIG, "There is a router named %s in my declared "
1881  "family, but it wasn't listed by digest. Please consider "
1882  "saying %s instead, if that's what you meant.",
1883  escaped(name), fp);
1885  }
1886  }
1887  }
1888 
1889  /* Now declared_family should have the closest we can come to the
1890  * identities that the user wanted.
1891  *
1892  * Unlike older versions of Tor, we _do_ include our own identity: this
1893  * helps microdescriptor compression, and helps in-memory compression
1894  * on clients. */
1895  nodefamily_t *nf = nodefamily_from_members(declared_family,
1897  NF_WARN_MALFORMED,
1898  NULL);
1899  SMARTLIST_FOREACH(declared_family, char *, s, tor_free(s));
1900  smartlist_free(declared_family);
1901  if (!nf) {
1902  return NULL;
1903  }
1904 
1905  char *s = nodefamily_format(nf);
1906  nodefamily_free(nf);
1907 
1908  smartlist_t *result = smartlist_new();
1909  smartlist_split_string(result, s, NULL,
1910  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1911  tor_free(s);
1912 
1913  if (smartlist_len(result) == 1) {
1914  /* This is a one-element list containing only ourself; instead return
1915  * nothing */
1916  const char *singleton = smartlist_get(result, 0);
1917  bool is_me = false;
1918  if (singleton[0] == '$') {
1919  char d[DIGEST_LEN];
1920  int n = base16_decode(d, sizeof(d), singleton+1, strlen(singleton+1));
1921  if (n == DIGEST_LEN &&
1923  is_me = true;
1924  }
1925  }
1926  if (!is_me) {
1927  // LCOV_EXCL_START
1928  log_warn(LD_BUG, "Found a singleton family list with an element "
1929  "that wasn't us! Element was %s", escaped(singleton));
1930  // LCOV_EXCL_STOP
1931  } else {
1932  SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
1933  smartlist_free(result);
1934  return NULL;
1935  }
1936  }
1937 
1938  return result;
1939 }
1940 
1941 /** Allocate a fresh, unsigned routerinfo for this OR, without any of the
1942  * fields that depend on the corresponding extrainfo.
1943  *
1944  * On success, set ri_out to the new routerinfo, and return 0.
1945  * Caller is responsible for freeing the generated routerinfo.
1946  *
1947  * Returns a negative value and sets ri_out to NULL on temporary error.
1948  */
1949 MOCK_IMPL(STATIC int,
1951 {
1952  routerinfo_t *ri = NULL;
1953  uint32_t addr;
1954  char platform[256];
1955  int hibernating = we_are_hibernating();
1956  const or_options_t *options = get_options();
1957  int result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
1958 
1959  if (BUG(!ri_out)) {
1960  result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
1961  goto err;
1962  }
1963 
1964  if (router_pick_published_address(options, &addr, 0) < 0) {
1965  log_warn(LD_CONFIG, "Don't know my address while generating descriptor");
1966  result = TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
1967  goto err;
1968  }
1969 
1970  /* Log a message if the address in the descriptor doesn't match the ORPort
1971  * and DirPort addresses configured by the operator. */
1972  router_check_descriptor_address_consistency(addr);
1973 
1974  ri = tor_malloc_zero(sizeof(routerinfo_t));
1975  ri->cache_info.routerlist_index = -1;
1976  ri->nickname = tor_strdup(options->Nickname);
1977  ri->addr = addr;
1978  ri->or_port = router_get_advertised_or_port(options);
1979  ri->dir_port = router_get_advertised_dir_port(options, 0);
1982  ri->cache_info.published_on = time(NULL);
1983  /* get_onion_key() must invoke from main thread */
1984  router_set_rsa_onion_pkey(get_onion_key(), &ri->onion_pkey,
1985  &ri->onion_pkey_len);
1986 
1987  ri->onion_curve25519_pkey =
1988  tor_memdup(&get_current_curve25519_keypair()->pubkey,
1989  sizeof(curve25519_public_key_t));
1990 
1991  /* For now, at most one IPv6 or-address is being advertised. */
1992  {
1993  const port_cfg_t *ipv6_orport = NULL;
1995  if (p->type == CONN_TYPE_OR_LISTENER &&
1996  ! p->server_cfg.no_advertise &&
1997  ! p->server_cfg.bind_ipv4_only &&
1998  tor_addr_family(&p->addr) == AF_INET6) {
1999  /* Like IPv4, if the relay is configured using the default
2000  * authorities, disallow internal IPs. Otherwise, allow them. */
2001  const int default_auth = using_default_dir_authorities(options);
2002  if (! tor_addr_is_internal(&p->addr, 0) || ! default_auth) {
2003  ipv6_orport = p;
2004  break;
2005  } else {
2006  char addrbuf[TOR_ADDR_BUF_LEN];
2007  log_warn(LD_CONFIG,
2008  "Unable to use configured IPv6 address \"%s\" in a "
2009  "descriptor. Skipping it. "
2010  "Try specifying a globally reachable address explicitly.",
2011  tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
2012  }
2013  }
2014  } SMARTLIST_FOREACH_END(p);
2015  if (ipv6_orport) {
2016  tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
2017  ri->ipv6_orport = ipv6_orport->port;
2018  }
2019  }
2020 
2021  ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
2022  if (BUG(crypto_pk_get_digest(ri->identity_pkey,
2023  ri->cache_info.identity_digest) < 0)) {
2024  result = TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
2025  goto err;
2026  }
2027  ri->cache_info.signing_key_cert =
2028  tor_cert_dup(get_master_signing_key_cert());
2029 
2030  get_platform_str(platform, sizeof(platform));
2031  ri->platform = tor_strdup(platform);
2032 
2033  ri->protocol_list = tor_strdup(protover_get_supported_protocols());
2034 
2035  /* compute ri->bandwidthrate as the min of various options */
2037 
2038  /* and compute ri->bandwidthburst similarly */
2040 
2041  /* Report bandwidth, unless we're hibernating or shutting down */
2042  ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
2043 
2045  /* DNS is screwed up; don't claim to be an exit. */
2047  } else {
2049  &ri->exit_policy);
2050  }
2051  ri->policy_is_reject_star =
2052  policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
2053  policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
2054 
2055  if (options->IPv6Exit) {
2056  char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
2057  if (p_tmp)
2058  ri->ipv6_exit_policy = parse_short_policy(p_tmp);
2059  tor_free(p_tmp);
2060  }
2061 
2062  ri->declared_family = get_my_declared_family(options);
2063 
2064  if (options->BridgeRelay) {
2066  /* Bridges shouldn't be able to send their descriptors unencrypted,
2067  anyway, since they don't have a DirPort, and always connect to the
2068  bridge authority anonymously. But just in case they somehow think of
2069  sending them on an unencrypted connection, don't allow them to try. */
2070  ri->cache_info.send_unencrypted = 0;
2071  } else {
2073  ri->cache_info.send_unencrypted = 1;
2074  }
2075 
2076  goto done;
2077 
2078  err:
2079  routerinfo_free(ri);
2080  *ri_out = NULL;
2081  return result;
2082 
2083  done:
2084  *ri_out = ri;
2085  return 0;
2086 }
2087 
2088 /** Allocate and return a fresh, unsigned extrainfo for this OR, based on the
2089  * routerinfo ri.
2090  *
2091  * Uses options->Nickname to set the nickname, and options->BridgeRelay to set
2092  * ei->cache_info.send_unencrypted.
2093  *
2094  * If ri is NULL, logs a BUG() warning and returns NULL.
2095  * Caller is responsible for freeing the generated extrainfo.
2096  */
2097 static extrainfo_t *
2099 {
2100  extrainfo_t *ei = NULL;
2101  const or_options_t *options = get_options();
2102 
2103  if (BUG(!ri))
2104  return NULL;
2105 
2106  /* Now generate the extrainfo. */
2107  ei = tor_malloc_zero(sizeof(extrainfo_t));
2108  ei->cache_info.is_extrainfo = 1;
2109  strlcpy(ei->nickname, options->Nickname, sizeof(ei->nickname));
2110  ei->cache_info.published_on = ri->cache_info.published_on;
2111  ei->cache_info.signing_key_cert =
2112  tor_cert_dup(get_master_signing_key_cert());
2113 
2114  memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
2115  DIGEST_LEN);
2116 
2117  if (options->BridgeRelay) {
2118  /* See note in router_build_fresh_routerinfo(). */
2119  ei->cache_info.send_unencrypted = 0;
2120  } else {
2121  ei->cache_info.send_unencrypted = 1;
2122  }
2123 
2124  return ei;
2125 }
2126 
2127 /** Dump the extrainfo descriptor body for ei, sign it, and add the body and
2128  * signature to ei->cache_info. Note that the extrainfo body is determined by
2129  * ei, and some additional config and statistics state: see
2130  * extrainfo_dump_to_string() for details.
2131  *
2132  * Return 0 on success, -1 on temporary error.
2133  * If ei is NULL, logs a BUG() warning and returns -1.
2134  * On error, ei->cache_info is not modified.
2135  */
2136 static int
2138 {
2139  if (BUG(!ei))
2140  return -1;
2141 
2143  ei, get_server_identity_key(),
2144  get_master_signing_keypair()) < 0) {
2145  log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
2146  return -1;
2147  }
2148 
2149  ei->cache_info.signed_descriptor_len =
2150  strlen(ei->cache_info.signed_descriptor_body);
2151 
2153  ei->cache_info.signed_descriptor_len,
2154  ei->cache_info.signed_descriptor_digest);
2155  crypto_digest256((char*) ei->digest256,
2156  ei->cache_info.signed_descriptor_body,
2157  ei->cache_info.signed_descriptor_len,
2158  DIGEST_SHA256);
2159 
2160  return 0;
2161 }
2162 
2163 /** Allocate and return a fresh, signed extrainfo for this OR, based on the
2164  * routerinfo ri.
2165  *
2166  * If ri is NULL, logs a BUG() warning and returns NULL.
2167  * Caller is responsible for freeing the generated extrainfo.
2168  */
2171 {
2172  int result = -1;
2173  extrainfo_t *ei = NULL;
2174 
2175  if (BUG(!ri))
2176  return NULL;
2177 
2179  /* router_build_fresh_unsigned_extrainfo() should not fail. */
2180  if (BUG(!ei))
2181  goto err;
2182 
2184  if (result < 0)
2185  goto err;
2186 
2187  goto done;
2188 
2189  err:
2190  extrainfo_free(ei);
2191  return NULL;
2192 
2193  done:
2194  return ei;
2195 }
2196 
2197 /** Set the fields in ri that depend on ei.
2198  *
2199  * If ei is NULL, logs a BUG() warning and zeroes the relevant fields.
2200  */
2201 STATIC void
2203  const extrainfo_t *ei)
2204 {
2205  if (BUG(!ei)) {
2206  /* Just to be safe, zero ri->cache_info.extra_info_digest here. */
2207  memset(ri->cache_info.extra_info_digest, 0, DIGEST_LEN);
2208  memset(ri->cache_info.extra_info_digest256, 0, DIGEST256_LEN);
2209  return;
2210  }
2211 
2212  /* Now finish the router descriptor. */
2213  memcpy(ri->cache_info.extra_info_digest,
2214  ei->cache_info.signed_descriptor_digest,
2215  DIGEST_LEN);
2216  memcpy(ri->cache_info.extra_info_digest256,
2217  ei->digest256,
2218  DIGEST256_LEN);
2219 }
2220 
2221 /** Dump the descriptor body for ri, sign it, and add the body and signature to
2222  * ri->cache_info. Note that the descriptor body is determined by ri, and some
2223  * additional config and state: see router_dump_router_to_string() for details.
2224  *
2225  * Return 0 on success, and a negative value on temporary error.
2226  * If ri is NULL, logs a BUG() warning and returns a negative value.
2227  * On error, ri->cache_info is not modified.
2228  */
2229 STATIC int
2231 {
2232  if (BUG(!ri))
2233  return TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2234 
2235  if (! (ri->cache_info.signed_descriptor_body =
2236  router_dump_router_to_string(ri, get_server_identity_key(),
2237  get_onion_key(),
2239  get_master_signing_keypair())) ) {
2240  log_warn(LD_BUG, "Couldn't generate router descriptor.");
2241  return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
2242  }
2243 
2244  ri->cache_info.signed_descriptor_len =
2245  strlen(ri->cache_info.signed_descriptor_body);
2246 
2248  strlen(ri->cache_info.signed_descriptor_body),
2249  ri->cache_info.signed_descriptor_digest);
2250 
2251  return 0;
2252 }
2253 
2254 /** Build a fresh routerinfo, signed server descriptor, and signed extrainfo
2255  * document for this OR.
2256  *
2257  * Set r to the generated routerinfo, e to the generated extrainfo document.
2258  * Failure to generate an extra-info document is not an error and is indicated
2259  * by setting e to NULL.
2260  * Return 0 on success, and a negative value on temporary error.
2261  * Caller is responsible for freeing generated documents on success.
2262  */
2263 int
2265 {
2266  int result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2267  routerinfo_t *ri = NULL;
2268  extrainfo_t *ei = NULL;
2269 
2270  if (BUG(!r))
2271  goto err;
2272 
2273  if (BUG(!e))
2274  goto err;
2275 
2277  if (result < 0) {
2278  goto err;
2279  }
2280  /* If ri is NULL, then result should be negative. So this check should be
2281  * unreachable. */
2282  if (BUG(!ri)) {
2283  result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2284  goto err;
2285  }
2286 
2288 
2289  /* Failing to create an ei is not an error. */
2290  if (ei) {
2292  }
2293 
2295  if (result < 0)
2296  goto err;
2297 
2298  if (ei) {
2300  &ri->cache_info, NULL))) {
2301  result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2302  goto err;
2303  }
2304  }
2305 
2306  goto done;
2307 
2308  err:
2309  routerinfo_free(ri);
2310  extrainfo_free(ei);
2311  *r = NULL;
2312  *e = NULL;
2313  return result;
2314 
2315  done:
2316  *r = ri;
2317  *e = ei;
2318  return 0;
2319 }
2320 
2321 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2322  * routerinfo, signed server descriptor, and extra-info document for this OR.
2323  * Return 0 on success, -1 on temporary error.
2324  */
2325 int
2327 {
2328  int err = 0;
2329  routerinfo_t *ri;
2330  extrainfo_t *ei;
2331  uint32_t addr;
2332  const or_options_t *options = get_options();
2333 
2334  if (desc_clean_since && !force)
2335  return 0;
2336 
2337  if (router_pick_published_address(options, &addr, 0) < 0 ||
2338  router_get_advertised_or_port(options) == 0) {
2339  /* Stop trying to rebuild our descriptor every second. We'll
2340  * learn that it's time to try again when ip_address_changed()
2341  * marks it dirty. */
2342  desc_clean_since = time(NULL);
2343  return TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
2344  }
2345 
2346  log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
2347 
2348  err = router_build_fresh_descriptor(&ri, &ei);
2349  if (err < 0) {
2350  return err;
2351  }
2352 
2353  routerinfo_free(desc_routerinfo);
2354  desc_routerinfo = ri;
2355  extrainfo_free(desc_extrainfo);
2356  desc_extrainfo = ei;
2357 
2358  desc_clean_since = time(NULL);
2359  desc_needs_upload = 1;
2361  if (BUG(desc_gen_reason == NULL)) {
2362  desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
2363  }
2364  desc_dirty_reason = NULL;
2366  return 0;
2367 }
2368 
2369 /** If our router descriptor ever goes this long without being regenerated
2370  * because something changed, we force an immediate regenerate-and-upload. */
2371 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2372 
2373 /** If our router descriptor seems to be missing or unacceptable according
2374  * to the authorities, regenerate and reupload it _this_ often. */
2375 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2376 
2377 /** Mark descriptor out of date if it's been "too long" since we last tried
2378  * to upload one. */
2379 void
2381 {
2382  networkstatus_t *ns;
2383  const routerstatus_t *rs;
2384  const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2385  const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2386  const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2387 
2388  /* If it's already dirty, don't mark it. */
2389  if (! desc_clean_since)
2390  return;
2391 
2392  /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2393  * time to rebuild it. */
2394  if (desc_clean_since < slow_cutoff) {
2395  mark_my_descriptor_dirty("time for new descriptor");
2396  return;
2397  }
2398  /* Now we see whether we want to be retrying frequently or no. The
2399  * rule here is that we'll retry frequently if we aren't listed in the
2400  * live consensus we have, or if the publication time of the
2401  * descriptor listed for us in the consensus is very old, or if the
2402  * consensus lists us as "stale" and we haven't regenerated since the
2403  * consensus was published. */
2405  if (ns) {
2407  if (rs == NULL)
2408  retry_fast_reason = "not listed in consensus";
2409  else if (rs->published_on < slow_cutoff)
2410  retry_fast_reason = "version listed in consensus is quite old";
2411  else if (rs->is_staledesc && ns->valid_after > desc_clean_since)
2412  retry_fast_reason = "listed as stale in consensus";
2413  }
2414 
2415  if (retry_fast_reason && desc_clean_since < fast_cutoff)
2416  mark_my_descriptor_dirty(retry_fast_reason);
2417 }
2418 
2419 /** Call when the current descriptor is out of date. */
2420 void
2421 mark_my_descriptor_dirty(const char *reason)
2422 {
2423  const or_options_t *options = get_options();
2424  if (BUG(reason == NULL)) {
2425  reason = "marked descriptor dirty for unspecified reason";
2426  }
2427  if (server_mode(options) && options->PublishServerDescriptor_)
2428  log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2429  desc_clean_since = 0;
2430  if (!desc_dirty_reason)
2431  desc_dirty_reason = reason;
2432 }
2433 
2434 /** How frequently will we republish our descriptor because of large (factor
2435  * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2436  * if our previous bandwidth estimate was exactly 0. */
2437 #define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
2438 
2439 /** Maximum uptime to republish our descriptor because of large shifts in
2440  * estimated bandwidth. */
2441 #define MAX_UPTIME_BANDWIDTH_CHANGE (24*60*60)
2442 
2443 /** By which factor bandwidth shifts have to change to be considered large. */
2444 #define BANDWIDTH_CHANGE_FACTOR 2
2445 
2446 /** Check whether bandwidth has changed a lot since the last time we announced
2447  * bandwidth while the uptime is smaller than MAX_UPTIME_BANDWIDTH_CHANGE.
2448  * If so, mark our descriptor dirty. */
2449 void
2451 {
2452  static time_t last_changed = 0;
2453  uint64_t prev, cur;
2454  const int hibernating = we_are_hibernating();
2455 
2456  /* If the relay uptime is bigger than MAX_UPTIME_BANDWIDTH_CHANGE,
2457  * the next regularly scheduled descriptor update (18h) will be enough */
2458  if (get_uptime() > MAX_UPTIME_BANDWIDTH_CHANGE && !hibernating)
2459  return;
2460 
2461  const routerinfo_t *my_ri = router_get_my_routerinfo();
2462 
2463  if (!my_ri)
2464  return;
2465 
2466  prev = my_ri->bandwidthcapacity;
2467 
2468  /* Consider ourselves to have zero bandwidth if we're hibernating or
2469  * shutting down. */
2470  cur = hibernating ? 0 : rep_hist_bandwidth_assess();
2471 
2472  if ((prev != cur && (!prev || !cur)) ||
2473  cur > (prev * BANDWIDTH_CHANGE_FACTOR) ||
2474  cur < (prev / BANDWIDTH_CHANGE_FACTOR) ) {
2475  if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
2476  log_info(LD_GENERAL,
2477  "Measured bandwidth has changed; rebuilding descriptor.");
2478  mark_my_descriptor_dirty("bandwidth has changed");
2479  last_changed = now;
2480  }
2481  }
2482 }
2483 
2484 /** Note at log level severity that our best guess of address has changed from
2485  * <b>prev</b> to <b>cur</b>. */
2486 static void
2488  const tor_addr_t *prev,
2489  const tor_addr_t *cur,
2490  const char *source)
2491 {
2492  char addrbuf_prev[TOR_ADDR_BUF_LEN];
2493  char addrbuf_cur[TOR_ADDR_BUF_LEN];
2494 
2495  if (BUG(!server_mode(get_options())))
2496  return;
2497 
2498  if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2499  strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2500  if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2501  strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2502 
2503  if (!tor_addr_is_null(prev))
2504  log_fn(severity, LD_GENERAL,
2505  "Our IP Address has changed from %s to %s; "
2506  "rebuilding descriptor (source: %s).",
2507  addrbuf_prev, addrbuf_cur, source);
2508  else
2509  log_notice(LD_GENERAL,
2510  "Guessed our IP address as %s (source: %s).",
2511  addrbuf_cur, source);
2512 }
2513 
2514 /** Check whether our own address as defined by the Address configuration
2515  * has changed. This is for routers that get their address from a service
2516  * like dyndns. If our address has changed, mark our descriptor dirty. */
2517 void
2519 {
2520  uint32_t prev, cur;
2521  const or_options_t *options = get_options();
2522  const char *method = NULL;
2523  char *hostname = NULL;
2524  const routerinfo_t *my_ri = router_get_my_routerinfo();
2525 
2526  (void) now;
2527 
2528  if (my_ri == NULL) /* make sure routerinfo exists */
2529  return;
2530 
2531  /* XXXX ipv6 */
2532  prev = my_ri->addr;
2533  if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
2534  log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
2535  return;
2536  }
2537 
2538  if (prev != cur) {
2539  char *source;
2540  tor_addr_t tmp_prev, tmp_cur;
2541 
2542  tor_addr_from_ipv4h(&tmp_prev, prev);
2543  tor_addr_from_ipv4h(&tmp_cur, cur);
2544 
2545  tor_asprintf(&source, "METHOD=%s%s%s", method,
2546  hostname ? " HOSTNAME=" : "",
2547  hostname ? hostname : "");
2548 
2549  log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
2550  tor_free(source);
2551 
2552  ip_address_changed(0);
2553  }
2554 
2555  tor_free(hostname);
2556 }
2557 
2558 /** The most recently guessed value of our IP address, based on directory
2559  * headers. */
2560 static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
2561 
2562 /** A directory server <b>d_conn</b> told us our IP address is
2563  * <b>suggestion</b>.
2564  * If this address is different from the one we think we are now, and
2565  * if our computer doesn't actually know its IP address, then switch. */
2566 void
2567 router_new_address_suggestion(const char *suggestion,
2568  const dir_connection_t *d_conn)
2569 {
2570  tor_addr_t addr;
2571  uint32_t cur = 0; /* Current IPv4 address. */
2572  const or_options_t *options = get_options();
2573 
2574  /* first, learn what the IP address actually is */
2575  if (tor_addr_parse(&addr, suggestion) == -1) {
2576  log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
2577  escaped(suggestion));
2578  return;
2579  }
2580 
2581  log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
2582 
2583  if (!server_mode(options)) {
2584  tor_addr_copy(&last_guessed_ip, &addr);
2585  return;
2586  }
2587 
2588  /* XXXX ipv6 */
2589  cur = get_last_resolved_addr();
2590  if (cur ||
2591  resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
2592  /* We're all set -- we already know our address. Great. */
2593  tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
2594  need it later */
2595  return;
2596  }
2597  if (tor_addr_is_internal(&addr, 0)) {
2598  /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2599  return;
2600  }
2601  if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
2602  /* Don't believe anybody who says our IP is their IP. */
2603  log_debug(LD_DIR, "A directory server told us our IP address is %s, "
2604  "but they are just reporting their own IP address. Ignoring.",
2605  suggestion);
2606  return;
2607  }
2608 
2609  /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2610  * us an answer different from what we had the last time we managed to
2611  * resolve it. */
2612  if (!tor_addr_eq(&last_guessed_ip, &addr)) {
2614  "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2615  suggestion);
2617  d_conn->base_.address);
2618  ip_address_changed(0);
2619  tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
2620  will fetch it */
2621  }
2622 }
2623 
2624 /** We failed to resolve our address locally, but we'd like to build
2625  * a descriptor and publish / test reachability. If we have a guess
2626  * about our address based on directory headers, answer it and return
2627  * 0; else return -1. */
2628 static int
2630 {
2633  return 0;
2634  }
2635  return -1;
2636 }
2637 
2638 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2639  * string describing the version of Tor and the operating system we're
2640  * currently running on.
2641  */
2642 STATIC void
2643 get_platform_str(char *platform, size_t len)
2644 {
2645  tor_snprintf(platform, len, "Tor %s on %s",
2647 }
2648 
2649 /* XXX need to audit this thing and count fenceposts. maybe
2650  * refactor so we don't have to keep asking if we're
2651  * near the end of maxlen?
2652  */
2653 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2654 
2655 /** OR only: Given a routerinfo for this router, and an identity key to sign
2656  * with, encode the routerinfo as a signed server descriptor and return a new
2657  * string encoding the result, or NULL on failure.
2658  *
2659  * In addition to the fields in router, this function calls
2660  * onion_key_lifetime(), get_options(), and we_are_hibernating(), and uses the
2661  * results to populate some fields in the descriptor.
2662  */
2663 char *
2665  const crypto_pk_t *ident_key,
2666  const crypto_pk_t *tap_key,
2667  const curve25519_keypair_t *ntor_keypair,
2668  const ed25519_keypair_t *signing_keypair)
2669 {
2670  char *address = NULL;
2671  char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2672  crypto_pk_t *rsa_pubkey = NULL;
2673  char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2674  char digest[DIGEST256_LEN];
2675  char published[ISO_TIME_LEN+1];
2676  char fingerprint[FINGERPRINT_LEN+1];
2677  char *extra_info_line = NULL;
2678  size_t onion_pkeylen, identity_pkeylen;
2679  char *family_line = NULL;
2680  char *extra_or_address = NULL;
2681  const or_options_t *options = get_options();
2682  smartlist_t *chunks = NULL;
2683  char *output = NULL;
2684  const int emit_ed_sigs = signing_keypair &&
2685  router->cache_info.signing_key_cert;
2686  char *ed_cert_line = NULL;
2687  char *rsa_tap_cc_line = NULL;
2688  char *ntor_cc_line = NULL;
2689  char *proto_line = NULL;
2690 
2691  /* Make sure the identity key matches the one in the routerinfo. */
2692  if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2693  log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2694  "match router's public key!");
2695  goto err;
2696  }
2697  if (emit_ed_sigs) {
2698  if (!router->cache_info.signing_key_cert->signing_key_included ||
2699  !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
2700  &signing_keypair->pubkey)) {
2701  log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
2702  "ed25519 key chain %d",
2703  router->cache_info.signing_key_cert->signing_key_included);
2704  goto err;
2705  }
2706  }
2707 
2708  /* record our fingerprint, so we can include it in the descriptor */
2709  if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2710  log_err(LD_BUG,"Error computing fingerprint");
2711  goto err;
2712  }
2713 
2714  if (emit_ed_sigs) {
2715  /* Encode ed25519 signing cert */
2716  char ed_cert_base64[256];
2717  char ed_fp_base64[ED25519_BASE64_LEN+1];
2718  if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2719  (const char*)router->cache_info.signing_key_cert->encoded,
2720  router->cache_info.signing_key_cert->encoded_len,
2721  BASE64_ENCODE_MULTILINE) < 0) {
2722  log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2723  goto err;
2724  }
2725  ed25519_public_to_base64(ed_fp_base64,
2726  &router->cache_info.signing_key_cert->signing_key);
2727  tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2728  "-----BEGIN ED25519 CERT-----\n"
2729  "%s"
2730  "-----END ED25519 CERT-----\n"
2731  "master-key-ed25519 %s\n",
2732  ed_cert_base64, ed_fp_base64);
2733  }
2734 
2735  /* PEM-encode the onion key */
2736  rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
2737  router->onion_pkey_len);
2738  if (crypto_pk_write_public_key_to_string(rsa_pubkey,
2739  &onion_pkey,&onion_pkeylen)<0) {
2740  log_warn(LD_BUG,"write onion_pkey to string failed!");
2741  goto err;
2742  }
2743 
2744  /* PEM-encode the identity key */
2746  &identity_pkey,&identity_pkeylen)<0) {
2747  log_warn(LD_BUG,"write identity_pkey to string failed!");
2748  goto err;
2749  }
2750 
2751  /* Cross-certify with RSA key */
2752  if (tap_key && router->cache_info.signing_key_cert &&
2753  router->cache_info.signing_key_cert->signing_key_included) {
2754  char buf[256];
2755  int tap_cc_len = 0;
2756  uint8_t *tap_cc =
2758  &router->cache_info.signing_key_cert->signing_key,
2759  router->identity_pkey,
2760  &tap_cc_len);
2761  if (!tap_cc) {
2762  log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
2763  goto err;
2764  }
2765 
2766  if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
2767  BASE64_ENCODE_MULTILINE) < 0) {
2768  log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
2769  tor_free(tap_cc);
2770  goto err;
2771  }
2772  tor_free(tap_cc);
2773 
2774  tor_asprintf(&rsa_tap_cc_line,
2775  "onion-key-crosscert\n"
2776  "-----BEGIN CROSSCERT-----\n"
2777  "%s"
2778  "-----END CROSSCERT-----\n", buf);
2779  }
2780 
2781  /* Cross-certify with onion keys */
2782  if (ntor_keypair && router->cache_info.signing_key_cert &&
2783  router->cache_info.signing_key_cert->signing_key_included) {
2784  int sign = 0;
2785  char buf[256];
2786  /* XXXX Base the expiration date on the actual onion key expiration time?*/
2787  tor_cert_t *cert =
2788  make_ntor_onion_key_crosscert(ntor_keypair,
2789  &router->cache_info.signing_key_cert->signing_key,
2790  router->cache_info.published_on,
2791  get_onion_key_lifetime(), &sign);
2792  if (!cert) {
2793  log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
2794  goto err;
2795  }
2796  tor_assert(sign == 0 || sign == 1);
2797 
2798  if (base64_encode(buf, sizeof(buf),
2799  (const char*)cert->encoded, cert->encoded_len,
2800  BASE64_ENCODE_MULTILINE)<0) {
2801  log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
2802  tor_cert_free(cert);
2803  goto err;
2804  }
2805  tor_cert_free(cert);
2806 
2807  tor_asprintf(&ntor_cc_line,
2808  "ntor-onion-key-crosscert %d\n"
2809  "-----BEGIN ED25519 CERT-----\n"
2810  "%s"
2811  "-----END ED25519 CERT-----\n", sign, buf);
2812  }
2813 
2814  /* Encode the publication time. */
2815  format_iso_time(published, router->cache_info.published_on);
2816 
2817  if (router->declared_family && smartlist_len(router->declared_family)) {
2818  char *family = smartlist_join_strings(router->declared_family,
2819  " ", 0, NULL);
2820  tor_asprintf(&family_line, "family %s\n", family);
2821  tor_free(family);
2822  } else {
2823  family_line = tor_strdup("");
2824  }
2825 
2826  if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
2827  char extra_info_digest[HEX_DIGEST_LEN+1];
2828  base16_encode(extra_info_digest, sizeof(extra_info_digest),
2829  router->cache_info.extra_info_digest, DIGEST_LEN);
2830  if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
2831  char d256_64[BASE64_DIGEST256_LEN+1];
2832  digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
2833  tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
2834  extra_info_digest, d256_64);
2835  } else {
2836  tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
2837  extra_info_digest);
2838  }
2839  }
2840 
2841  if (router->ipv6_orport &&
2842  tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2843  char addr[TOR_ADDR_BUF_LEN];
2844  const char *a;
2845  a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2846  if (a) {
2847  tor_asprintf(&extra_or_address,
2848  "or-address %s:%d\n", a, router->ipv6_orport);
2849  log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2850  }
2851  }
2852 
2853  if (router->protocol_list) {
2854  tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
2855  } else {
2856  proto_line = tor_strdup("");
2857  }
2858 
2859  address = tor_dup_ip(router->addr);
2860  chunks = smartlist_new();
2861 
2862  /* Generate the easy portion of the router descriptor. */
2863  smartlist_add_asprintf(chunks,
2864  "router %s %s %d 0 %d\n"
2865  "%s"
2866  "%s"
2867  "platform %s\n"
2868  "%s"
2869  "published %s\n"
2870  "fingerprint %s\n"
2871  "uptime %ld\n"
2872  "bandwidth %d %d %d\n"
2873  "%s%s"
2874  "onion-key\n%s"
2875  "signing-key\n%s"
2876  "%s%s"
2877  "%s%s%s",
2878  router->nickname,
2879  address,
2880  router->or_port,
2881  router_should_advertise_dirport(options, router->dir_port),
2882  ed_cert_line ? ed_cert_line : "",
2883  extra_or_address ? extra_or_address : "",
2884  router->platform,
2885  proto_line,
2886  published,
2887  fingerprint,
2888  get_uptime(),
2889  (int) router->bandwidthrate,
2890  (int) router->bandwidthburst,
2891  (int) router->bandwidthcapacity,
2892  extra_info_line ? extra_info_line : "",
2893  (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
2894  "caches-extra-info\n" : "",
2895  onion_pkey, identity_pkey,
2896  rsa_tap_cc_line ? rsa_tap_cc_line : "",
2897  ntor_cc_line ? ntor_cc_line : "",
2898  family_line,
2899  we_are_hibernating() ? "hibernating 1\n" : "",
2900  "hidden-service-dir\n");
2901 
2902  if (options->ContactInfo && strlen(options->ContactInfo)) {
2903  const char *ci = options->ContactInfo;
2904  if (strchr(ci, '\n') || strchr(ci, '\r'))
2905  ci = escaped(ci);
2906  smartlist_add_asprintf(chunks, "contact %s\n", ci);
2907  }
2908 
2909  if (options->BridgeRelay) {
2910  const char *bd;
2911  if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
2912  bd = options->BridgeDistribution;
2913  } else {
2914  bd = "any";
2915  }
2916  if (strchr(bd, '\n') || strchr(bd, '\r'))
2917  bd = escaped(bd);
2918  smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
2919  }
2920 
2921  if (router->onion_curve25519_pkey) {
2922  char kbuf[128];
2923  base64_encode(kbuf, sizeof(kbuf),
2924  (const char *)router->onion_curve25519_pkey->public_key,
2925  CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
2926  smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
2927  } else {
2928  /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
2929  log_err(LD_BUG, "A relay must have an ntor onion key");
2930  goto err;
2931  }
2932 
2933  /* Write the exit policy to the end of 's'. */
2934  if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
2935  smartlist_add_strdup(chunks, "reject *:*\n");
2936  } else if (router->exit_policy) {
2937  char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
2938 
2939  if (!exit_policy)
2940  goto err;
2941 
2942  smartlist_add_asprintf(chunks, "%s\n", exit_policy);
2943  tor_free(exit_policy);
2944  }
2945 
2946  if (router->ipv6_exit_policy) {
2947  char *p6 = write_short_policy(router->ipv6_exit_policy);
2948  if (p6 && strcmp(p6, "reject 1-65535")) {
2949  smartlist_add_asprintf(chunks,
2950  "ipv6-policy %s\n", p6);
2951  }
2952  tor_free(p6);
2953  }
2954 
2957  smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
2958  }
2959 
2960  /* Sign the descriptor with Ed25519 */
2961  if (emit_ed_sigs) {
2962  smartlist_add_strdup(chunks, "router-sig-ed25519 ");
2963  crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
2964  ED_DESC_SIGNATURE_PREFIX,
2965  chunks, "", DIGEST_SHA256);
2966  ed25519_signature_t sig;
2967  char buf[ED25519_SIG_BASE64_LEN+1];
2968  if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
2969  signing_keypair) < 0)
2970  goto err;
2971  ed25519_signature_to_base64(buf, &sig);
2972 
2973  smartlist_add_asprintf(chunks, "%s\n", buf);
2974  }
2975 
2976  /* Sign the descriptor with RSA */
2977  smartlist_add_strdup(chunks, "router-signature\n");
2978 
2979  crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
2980 
2981  {
2982  char *sig;
2983  if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
2984  log_warn(LD_BUG, "Couldn't sign router descriptor");
2985  goto err;
2986  }
2987  smartlist_add(chunks, sig);
2988  }
2989 
2990  /* include a last '\n' */
2991  smartlist_add_strdup(chunks, "\n");
2992 
2993  output = smartlist_join_strings(chunks, "", 0, NULL);
2994 
2995 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2996  {
2997  char *s_dup;
2998  const char *cp;
2999  routerinfo_t *ri_tmp;
3000  cp = s_dup = tor_strdup(output);
3001  ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
3002  if (!ri_tmp) {
3003  log_err(LD_BUG,
3004  "We just generated a router descriptor we can't parse.");
3005  log_err(LD_BUG, "Descriptor was: <<%s>>", output);
3006  goto err;
3007  }
3008  tor_free(s_dup);
3009  routerinfo_free(ri_tmp);
3010  }
3011 #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
3012 
3013  goto done;
3014 
3015  err:
3016  tor_free(output); /* sets output to NULL */
3017  done:
3018  if (chunks) {
3019  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
3020  smartlist_free(chunks);
3021  }
3022  crypto_pk_free(rsa_pubkey);
3023  tor_free(address);
3024  tor_free(family_line);
3025  tor_free(onion_pkey);
3026  tor_free(identity_pkey);
3027  tor_free(extra_or_address);
3028  tor_free(ed_cert_line);
3029  tor_free(rsa_tap_cc_line);
3030  tor_free(ntor_cc_line);
3031  tor_free(extra_info_line);
3032  tor_free(proto_line);
3033 
3034  return output;
3035 }
3036 
3037 /**
3038  * OR only: Given <b>router</b>, produce a string with its exit policy.
3039  * If <b>include_ipv4</b> is true, include IPv4 entries.
3040  * If <b>include_ipv6</b> is true, include IPv6 entries.
3041  */
3042 char *
3044  int include_ipv4,
3045  int include_ipv6)
3046 {
3047  if ((!router->exit_policy) || (router->policy_is_reject_star)) {
3048  return tor_strdup("reject *:*");
3049  }
3050 
3051  return policy_dump_to_string(router->exit_policy,
3052  include_ipv4,
3053  include_ipv6);
3054 }
3055 
3056 /** Load the contents of <b>filename</b>, find the last line starting with
3057  * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
3058  * the past or more than 1 hour in the future with respect to <b>now</b>,
3059  * and write the file contents starting with that line to *<b>out</b>.
3060  * Return 1 for success, 0 if the file does not exist or is empty, or -1
3061  * if the file does not contain a line matching these criteria or other
3062  * failure. */
3063 static int
3064 load_stats_file(const char *filename, const char *end_line, time_t now,
3065  char **out)
3066 {
3067  int r = -1;
3068  char *fname = get_datadir_fname(filename);
3069  char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
3070  time_t written;
3071  switch (file_status(fname)) {
3072  case FN_FILE:
3073  /* X022 Find an alternative to reading the whole file to memory. */
3074  if ((contents = read_file_to_str(fname, 0, NULL))) {
3075  tmp = strstr(contents, end_line);
3076  /* Find last block starting with end_line */
3077  while (tmp) {
3078  start = tmp;
3079  tmp = strstr(tmp + 1, end_line);
3080  }
3081  if (!start)
3082  goto notfound;
3083  if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
3084  goto notfound;
3085  strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
3086  if (parse_iso_time(timestr, &written) < 0)
3087  goto notfound;
3088  if (written < now - (25*60*60) || written > now + (1*60*60))
3089  goto notfound;
3090  *out = tor_strdup(start);
3091  r = 1;
3092  }
3093  notfound:
3094  tor_free(contents);
3095  break;
3096  /* treat empty stats files as if the file doesn't exist */
3097  case FN_NOENT:
3098  case FN_EMPTY:
3099  r = 0;
3100  break;
3101  case FN_ERROR:
3102  case FN_DIR:
3103  default:
3104  break;
3105  }
3106  tor_free(fname);
3107  return r;
3108 }
3109 
3110 /** Add header strings to chunks, based on the extrainfo object extrainfo,
3111  * and ed25519 keypair signing_keypair, if emit_ed_sigs is true.
3112  * Helper for extrainfo_dump_to_string().
3113  * Returns 0 on success, negative on failure. */
3114 static int
3116  smartlist_t *chunks,
3117  const extrainfo_t *extrainfo,
3118  const ed25519_keypair_t *signing_keypair,
3119  int emit_ed_sigs)
3120 {
3121  char identity[HEX_DIGEST_LEN+1];
3122  char published[ISO_TIME_LEN+1];
3123  char *ed_cert_line = NULL;
3124  char *pre = NULL;
3125  int rv = -1;
3126 
3127  base16_encode(identity, sizeof(identity),
3128  extrainfo->cache_info.identity_digest, DIGEST_LEN);
3129  format_iso_time(published, extrainfo->cache_info.published_on);
3130  if (emit_ed_sigs) {
3131  if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
3132  !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
3133  &signing_keypair->pubkey)) {
3134  log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
3135  "mismatched ed25519 key chain %d",
3136  extrainfo->cache_info.signing_key_cert->signing_key_included);
3137  goto err;
3138  }
3139  char ed_cert_base64[256];
3140  if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
3141  (const char*)extrainfo->cache_info.signing_key_cert->encoded,
3142  extrainfo->cache_info.signing_key_cert->encoded_len,
3143  BASE64_ENCODE_MULTILINE) < 0) {
3144  log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
3145  goto err;
3146  }
3147  tor_asprintf(&ed_cert_line, "identity-ed25519\n"
3148  "-----BEGIN ED25519 CERT-----\n"
3149  "%s"
3150  "-----END ED25519 CERT-----\n", ed_cert_base64);
3151  } else {
3152  ed_cert_line = tor_strdup("");
3153  }
3154 
3155  /* This is the first chunk in the file. If the file is too big, other chunks
3156  * are removed. So we must only add one chunk here. */
3157  tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n",
3158  extrainfo->nickname, identity,
3159  ed_cert_line,
3160  published);
3161  smartlist_add(chunks, pre);
3162 
3163  rv = 0;
3164  goto done;
3165 
3166  err:
3167  rv = -1;
3168 
3169  done:
3170  tor_free(ed_cert_line);
3171  return rv;
3172 }
3173 
3174 /** Add pluggable transport and statistics strings to chunks, skipping
3175  * statistics if write_stats_to_extrainfo is false.
3176  * Helper for extrainfo_dump_to_string().
3177  * Can not fail. */
3178 static void
3180  int write_stats_to_extrainfo)
3181 {
3182  const or_options_t *options = get_options();
3183  char *contents = NULL;
3184  time_t now = time(NULL);
3185 
3186  /* If the file is too big, these chunks are removed, starting with the last
3187  * chunk. So each chunk must be a complete line, and the file must be valid
3188  * after each chunk. */
3189 
3190  /* Add information about the pluggable transports we support, even if we
3191  * are not publishing statistics. This information is needed by BridgeDB
3192  * to distribute bridges. */
3193  if (options->ServerTransportPlugin) {
3194  char *pluggable_transports = pt_get_extra_info_descriptor_string();
3195  if (pluggable_transports)
3196  smartlist_add(chunks, pluggable_transports);
3197  }
3198 
3199  if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
3200  log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
3201  /* Bandwidth usage stats don't have their own option */
3202  {
3203  contents = rep_hist_get_bandwidth_lines();
3204  smartlist_add(chunks, contents);
3205  }
3206  /* geoip hashes aren't useful unless we are publishing other stats */
3207  if (geoip_is_loaded(AF_INET))
3208  smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
3209  geoip_db_digest(AF_INET));
3210  if (geoip_is_loaded(AF_INET6))
3211  smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
3212  geoip_db_digest(AF_INET6));
3213  if (options->DirReqStatistics &&
3214  load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
3215  "dirreq-stats-end", now, &contents) > 0) {
3216  smartlist_add(chunks, contents);
3217  }
3218  if (options->HiddenServiceStatistics &&
3219  load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
3220  "hidserv-stats-end", now, &contents) > 0) {
3221  smartlist_add(chunks, contents);
3222  }
3223  if (options->EntryStatistics &&
3224  load_stats_file("stats"PATH_SEPARATOR"entry-stats",
3225  "entry-stats-end", now, &contents) > 0) {
3226  smartlist_add(chunks, contents);
3227  }
3228  if (options->CellStatistics &&
3229  load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
3230  "cell-stats-end", now, &contents) > 0) {
3231  smartlist_add(chunks, contents);
3232  }
3233  if (options->ExitPortStatistics &&
3234  load_stats_file("stats"PATH_SEPARATOR"exit-stats",
3235  "exit-stats-end", now, &contents) > 0) {
3236  smartlist_add(chunks, contents);
3237  }
3238  if (options->ConnDirectionStatistics &&
3239  load_stats_file("stats"PATH_SEPARATOR"conn-stats",
3240  "conn-bi-direct", now, &contents) > 0) {
3241  smartlist_add(chunks, contents);
3242  }
3243  if (options->PaddingStatistics) {
3244  contents = rep_hist_get_padding_count_lines();
3245  if (contents)
3246  smartlist_add(chunks, contents);
3247  }
3248  /* bridge statistics */
3249  if (should_record_bridge_info(options)) {
3250  const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
3251  if (bridge_stats) {
3252  smartlist_add_strdup(chunks, bridge_stats);
3253  }
3254  }
3255  }
3256 }
3257 
3258 /** Add an ed25519 signature of chunks to chunks, using the ed25519 keypair
3259  * signing_keypair.
3260  * Helper for extrainfo_dump_to_string().
3261  * Returns 0 on success, negative on failure. */
3262 static int
3264  smartlist_t *chunks,
3265  const ed25519_keypair_t *signing_keypair)
3266 {
3267  char sha256_digest[DIGEST256_LEN];
3268  ed25519_signature_t ed_sig;
3269  char buf[ED25519_SIG_BASE64_LEN+1];
3270  int rv = -1;
3271 
3272  /* These are two of the three final chunks in the file. If the file is too
3273  * big, other chunks are removed. So we must only add two chunks here. */
3274  smartlist_add_strdup(chunks, "router-sig-ed25519 ");
3275  crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
3276  ED_DESC_SIGNATURE_PREFIX,
3277  chunks, "", DIGEST_SHA256);
3278  if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
3279  signing_keypair) < 0)
3280  goto err;
3281  ed25519_signature_to_base64(buf, &ed_sig);
3282 
3283  smartlist_add_asprintf(chunks, "%s\n", buf);
3284 
3285  rv = 0;
3286  goto done;
3287 
3288  err:
3289  rv = -1;
3290 
3291  done:
3292  return rv;
3293 }
3294 
3295 /** Add an RSA signature of extrainfo_string to chunks, using the RSA key
3296  * ident_key.
3297  * Helper for extrainfo_dump_to_string().
3298  * Returns 0 on success, negative on failure. */
3299 static int
3301  crypto_pk_t *ident_key,
3302  const char *extrainfo_string)
3303 {
3304  char sig[DIROBJ_MAX_SIG_LEN+1];
3305  char digest[DIGEST_LEN];
3306  int rv = -1;
3307 
3308  memset(sig, 0, sizeof(sig));
3309  if (router_get_extrainfo_hash(extrainfo_string, strlen(extrainfo_string),
3310  digest) < 0 ||
3311  router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
3312  ident_key) < 0) {
3313  log_warn(LD_BUG, "Could not append signature to extra-info "
3314  "descriptor.");
3315  goto err;
3316  }
3317  smartlist_add_strdup(chunks, sig);
3318 
3319  rv = 0;
3320  goto done;
3321 
3322  err:
3323  rv = -1;
3324 
3325  done:
3326  return rv;
3327 }
3328 
3329 /** Write the contents of <b>extrainfo</b>, to * *<b>s_out</b>, signing them
3330  * with <b>ident_key</b>.
3331  *
3332  * If ExtraInfoStatistics is 1, also write aggregated statistics and related
3333  * configuration data before signing. Most statistics also have an option that
3334  * enables or disables that particular statistic.
3335  *
3336  * Always write pluggable transport lines.
3337  *
3338  * Return 0 on success, negative on failure. */
3339 int
3340 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
3341  crypto_pk_t *ident_key,
3342  const ed25519_keypair_t *signing_keypair)
3343 {
3344  int result;
3345  static int write_stats_to_extrainfo = 1;
3346  char *s = NULL, *cp, *s_dup = NULL;
3347  smartlist_t *chunks = smartlist_new();
3348  extrainfo_t *ei_tmp = NULL;
3349  const int emit_ed_sigs = signing_keypair &&
3350  extrainfo->cache_info.signing_key_cert;
3351  int rv = 0;
3352 
3353  rv = extrainfo_dump_to_string_header_helper(chunks, extrainfo,
3354  signing_keypair,
3355  emit_ed_sigs);
3356  if (rv < 0)
3357  goto err;
3358 
3359  extrainfo_dump_to_string_stats_helper(chunks, write_stats_to_extrainfo);
3360 
3361  if (emit_ed_sigs) {
3362  rv = extrainfo_dump_to_string_ed_sig_helper(chunks, signing_keypair);
3363  if (rv < 0)
3364  goto err;
3365  }
3366 
3367  /* This is one of the three final chunks in the file. If the file is too big,
3368  * other chunks are removed. So we must only add one chunk here. */
3369  smartlist_add_strdup(chunks, "router-signature\n");
3370  s = smartlist_join_strings(chunks, "", 0, NULL);
3371 
3372  while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
3373  /* So long as there are at least two chunks (one for the initial
3374  * extra-info line and one for the router-signature), we can keep removing
3375  * things. If emit_ed_sigs is true, we also keep 2 additional chunks at the
3376  * end for the ed25519 signature. */
3377  const int required_chunks = emit_ed_sigs ? 4 : 2;
3378  if (smartlist_len(chunks) > required_chunks) {
3379  /* We remove the next-to-last or 4th-last element (remember, len-1 is the
3380  * last element), since we need to keep the router-signature elements. */
3381  int idx = smartlist_len(chunks) - required_chunks;
3382  char *e = smartlist_get(chunks, idx);
3383  smartlist_del_keeporder(chunks, idx);
3384  log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3385  "with statistics that exceeds the 50 KB "
3386  "upload limit. Removing last added "
3387  "statistics.");
3388  tor_free(e);
3389  tor_free(s);
3390  s = smartlist_join_strings(chunks, "", 0, NULL);
3391  } else {
3392  log_warn(LD_BUG, "We just generated an extra-info descriptors that "
3393  "exceeds the 50 KB upload limit.");
3394  goto err;
3395  }
3396  }
3397 
3398  rv = extrainfo_dump_to_string_rsa_sig_helper(chunks, ident_key, s);
3399  if (rv < 0)
3400  goto err;
3401 
3402  tor_free(s);
3403  s = smartlist_join_strings(chunks, "", 0, NULL);
3404 
3405  cp = s_dup = tor_strdup(s);
3406  ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
3407  if (!ei_tmp) {
3408  if (write_stats_to_extrainfo) {
3409  log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3410  "with statistics that we can't parse. Not "
3411  "adding statistics to this or any future "
3412  "extra-info descriptors.");
3413  write_stats_to_extrainfo = 0;
3414  result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
3415  signing_keypair);
3416  goto done;
3417  } else {
3418  log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
3419  "can't parse.");
3420  goto err;
3421  }
3422  }
3423 
3424  *s_out = s;
3425  s = NULL; /* prevent free */
3426  result = 0;
3427  goto done;
3428 
3429  err:
3430  result = -1;
3431 
3432  done:
3433  tor_free(s);
3434  SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
3435  smartlist_free(chunks);
3436  tor_free(s_dup);
3437  extrainfo_free(ei_tmp);
3438 
3439  return result;
3440 }
3441 
3442 /** Forget that we have issued any router-related warnings, so that we'll
3443  * warn again if we see the same errors. */
3444 void
3446 {
3447  if (warned_family) {
3448  SMARTLIST_FOREACH(warned_family, char *, cp, tor_free(cp));
3450  }
3451 }
3452 
3453 /** Release all static resources held in router.c */
3454 void
3456 {
3457  crypto_pk_free(onionkey);
3458  crypto_pk_free(lastonionkey);
3459  crypto_pk_free(server_identitykey);
3460  crypto_pk_free(client_identitykey);
3461 
3462  /* Destroying a locked mutex is undefined behaviour. This mutex may be
3463  * locked, because multiple threads can access it. But we need to destroy
3464  * it, otherwise re-initialisation will trigger undefined behaviour.
3465  * See #31735 for details. */
3467  routerinfo_free(desc_routerinfo);
3468  extrainfo_free(desc_extrainfo);
3469  crypto_pk_free(authority_signing_key);
3470  authority_cert_free(authority_key_certificate);
3471  crypto_pk_free(legacy_signing_key);
3472  authority_cert_free(legacy_key_certificate);
3473 
3476 
3477  if (warned_family) {
3478  SMARTLIST_FOREACH(warned_family, char *, cp, tor_free(cp));
3479  smartlist_free(warned_family);
3480  }
3481 }
3482 
3483 /* From the given RSA key object, convert it to ASN-1 encoded format and set
3484  * the newly allocated object in onion_pkey_out. The length of the key is set
3485  * in onion_pkey_len_out. */
3486 void
3487 router_set_rsa_onion_pkey(const crypto_pk_t *pk, char **onion_pkey_out,
3488  size_t *onion_pkey_len_out)
3489 {
3490  int len;
3491  char buf[1024];
3492 
3493  tor_assert(pk);
3494  tor_assert(onion_pkey_out);
3495  tor_assert(onion_pkey_len_out);
3496 
3497  len = crypto_pk_asn1_encode(pk, buf, sizeof(buf));
3498  if (BUG(len < 0)) {
3499  goto done;
3500  }
3501 
3502  *onion_pkey_out = tor_memdup(buf, len);
3503  *onion_pkey_len_out = len;
3504 
3505  done:
3506  return;
3507 }
3508 
3509 /* From an ASN-1 encoded onion pkey, return a newly allocated RSA key object.
3510  * It is the caller responsability to free the returned object.
3511  *
3512  * Return NULL if the pkey is NULL, malformed or if the length is 0. */
3513 crypto_pk_t *
3514 router_get_rsa_onion_pkey(const char *pkey, size_t pkey_len)
3515 {
3516  if (!pkey || pkey_len == 0) {
3517  return NULL;
3518  }
3519  return crypto_pk_asn1_decode(pkey, pkey_len);
3520 }
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:33
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:366
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:1686
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:2326
Router descriptor structure.
static int router_should_be_dirserver(const or_options_t *options, int dir_port)
Definition: router.c:1203
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:2939
char * policy_summarize(smartlist_t *policy, sa_family_t family)
Definition: policies.c:2690
void tor_mutex_release(tor_mutex_t *m)
Header file for signing.c.
#define TOR_ADDR_BUF_LEN
Definition: address.h:205
char * protocol_list
Definition: routerinfo_st.h:52
Common functions for using (pseudo-)random number generators.
Definition: node_st.h:33
int have_lockfile(void)
Definition: main.c:669
static extrainfo_t * desc_extrainfo
Definition: router.c:1476
#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:1615
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:1479
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:1424
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:1432
char * ContactInfo
Header file for nodefamily.c.
static extrainfo_t * router_build_fresh_unsigned_extrainfo(const routerinfo_t *ri)
Definition: router.c:2098
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:1950
Header file for connection.c.
static int get_onion_key_rotation_days_(void)
Definition: router.c:756
long get_uptime(void)
Definition: mainloop.c:2522
const tor_addr_t * get_first_advertised_addr_by_type_af(int listener_type, int address_family)
Definition: config.c:6496
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
#define DEFAULT_ONION_KEY_LIFETIME_DAYS
Definition: or.h:140
static int extrainfo_dump_to_string_rsa_sig_helper(smartlist_t *chunks, crypto_pk_t *ident_key, const char *extrainfo_string)
Definition: router.c:3300
#define LD_GENERAL
Definition: log.h:62
int should_refuse_unknown_exits(const or_options_t *options)
Definition: router.c:1325
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:2629
char * pt_get_extra_info_descriptor_string(void)
Definition: transports.c:1621
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:2202
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:1817
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:794
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:21
int ExtraInfoStatistics
Header file for config.c.
Header file for authcert.c.
static routerinfo_t * desc_routerinfo
Definition: router.c:1474
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:941
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:1715
#define MIN_ONION_KEY_LIFETIME_DAYS
Definition: or.h:134
#define MAX_UPTIME_BANDWIDTH_CHANGE
Definition: router.c:2441
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:152
STATIC time_t desc_clean_since
Definition: router.c:1482
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
int dirserv_add_own_fingerprint(crypto_pk_t *pk)
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:2495
#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:2375
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:1617
static void assert_identity_keys_ok(void)
Definition: router.c:360
const char * name
Definition: config.c:2211
#define LOG_NOTICE
Definition: log.h:50
static int router_dump_and_sign_extrainfo_descriptor_body(extrainfo_t *ei)
Definition: router.c:2137
crypto_pk_t * get_tlsclient_identity_key(void)
Definition: router.c:413
static int desc_needs_upload
Definition: router.c:1486
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:57
const uint8_t * router_get_my_id_digest(void)
Definition: router.c:1594
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:3179
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:233
static crypto_pk_t * client_identitykey
Definition: router.c:118
dir_server_t * router_get_trusteddirserver_by_digest(const char *digest)
Definition: dirlist.c:112
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:2664
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:2802
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:2518
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:633
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:2643
#define DIGEST256_LEN
Definition: digest_sizes.h:23
#define FORCE_REGENERATE_DESCRIPTOR_INTERVAL
Definition: router.c:2371
void policies_exit_policy_append_reject_star(smartlist_t **dest)
Definition: policies.c:2283
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:6474
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:159
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:3445
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:2437
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:1602
static int decide_if_publishable_server(void)
Definition: router.c:1348
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:287
const smartlist_t * get_configured_ports(void)
Definition: config.c:6403
static tor_addr_t last_guessed_ip
Definition: router.c:2560
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:1633
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:3115
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:2567
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:2264
int router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
Definition: router.c:1303
static int extrainfo_dump_to_string_ed_sig_helper(smartlist_t *chunks, const ed25519_keypair_t *signing_keypair)
Definition: router.c:3263
#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:137
int net_is_disabled(void)
Definition: netstatus.c:25
void mark_my_descriptor_dirty_if_too_old(time_t now)
Definition: router.c:2380
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:308
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:1698
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:1272
void router_free_all(void)
Definition: router.c:3455
uint16_t router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
Definition: router.c:1454
char identity[DIGEST_LEN]
Definition: node_st.h:45
int routerinfo_err_is_transient(int err)
Definition: router.c:170
saved_location_t saved_location
Header file for rephist.c.
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:3064
char * policy_dump_to_string(const smartlist_t *policy_list, int include_ipv4, int include_ipv6)
Definition: policies.c:3042
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:148
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:2487
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2421
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:2361
#define RFTS_IGNORE_MISSING
Definition: files.h:97
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
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:1313
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:2066
#define MIN_ONION_KEY_GRACE_PERIOD_DAYS
Definition: or.h:145
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:2564
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:986
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:65
void router_upload_dir_desc_to_dirservers(int force)
Definition: router.c:1493
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:1403
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:1623
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:1539
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:131
Header file for router.c.
STATIC extrainfo_t * router_build_fresh_signed_extrainfo(const routerinfo_t *ri)
Definition: router.c:2170
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:1381
#define MIN_BW_TO_ADVERTISE_DIRSERVER
Definition: router.c:1177
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:1183
int router_digest_is_me(const char *digest)
Definition: router.c:1586
const char * router_get_my_descriptor(void)
Definition: router.c:1669
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:244
void tor_mutex_acquire(tor_mutex_t *m)
Definition: or.h:894
int router_my_exit_policy_is_reject_star(void)
Definition: router.c:1574
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:2903
char * router_dump_exit_policy_to_string(const routerinfo_t *router, int include_ipv4, int include_ipv6)
Definition: router.c:3043
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:3340
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:2444
int control_event_server_status(int severity, const char *format,...)
consensus_path_type_t router_have_consensus_path(void)
Definition: nodelist.c:2330
STATIC smartlist_t * get_my_declared_family(const or_options_t *options)
Definition: router.c:1825
int tor_digest256_is_zero(const char *digest)
Definition: util_string.c:103
int HiddenServiceStatistics
void ip_address_changed(int at_interface)
Definition: mainloop.c:2280
tor_cmdline_mode_t command
Definition: or_options_st.h:35
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:2230
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:1403
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:2957
Header file for control_events.c.
void smartlist_clear(smartlist_t *sl)
void check_descriptor_bandwidth_changed(time_t now)
Definition: router.c:2450
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:75
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:2220
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:179
int check_whether_dirport_reachable(const or_options_t *options)
Definition: selftest.c:92
Listener port configuration structure.
Networkstatus consensus/vote structure.
STATIC const char * desc_dirty_reason
Definition: router.c:1484
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