tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

router.c (125480B)


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