tor

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

hs_service.c (171222B)


      1 /* Copyright (c) 2016-2021, The Tor Project, Inc. */
      2 /* See LICENSE for licensing information */
      3 
      4 /**
      5 * \file hs_service.c
      6 * \brief Implement next generation hidden service functionality
      7 **/
      8 
      9 #define HS_SERVICE_PRIVATE
     10 
     11 #include "core/or/or.h"
     12 #include "app/config/config.h"
     13 #include "app/config/statefile.h"
     14 #include "core/mainloop/connection.h"
     15 #include "core/mainloop/mainloop.h"
     16 #include "core/or/circuitbuild.h"
     17 #include "core/or/circuitlist.h"
     18 #include "core/or/circuituse.h"
     19 #include "core/or/congestion_control_common.h"
     20 #include "core/or/extendinfo.h"
     21 #include "core/or/relay.h"
     22 #include "feature/client/circpathbias.h"
     23 #include "feature/dirclient/dirclient.h"
     24 #include "feature/dircommon/directory.h"
     25 #include "feature/hs_common/shared_random_client.h"
     26 #include "feature/keymgt/loadkey.h"
     27 #include "feature/nodelist/describe.h"
     28 #include "feature/nodelist/microdesc.h"
     29 #include "feature/nodelist/networkstatus.h"
     30 #include "feature/nodelist/nickname.h"
     31 #include "feature/nodelist/node_select.h"
     32 #include "feature/nodelist/nodelist.h"
     33 #include "lib/crypt_ops/crypto_ope.h"
     34 #include "lib/crypt_ops/crypto_rand.h"
     35 #include "lib/crypt_ops/crypto_util.h"
     36 #include "lib/time/tvdiff.h"
     37 #include "lib/time/compat_time.h"
     38 
     39 #include "feature/hs/hs_circuit.h"
     40 #include "feature/hs/hs_common.h"
     41 #include "feature/hs/hs_config.h"
     42 #include "feature/hs/hs_control.h"
     43 #include "feature/hs/hs_descriptor.h"
     44 #include "feature/hs/hs_ident.h"
     45 #include "feature/hs/hs_intropoint.h"
     46 #include "feature/hs/hs_metrics.h"
     47 #include "feature/hs/hs_metrics_entry.h"
     48 #include "feature/hs/hs_service.h"
     49 #include "feature/hs/hs_stats.h"
     50 #include "feature/hs/hs_ob.h"
     51 
     52 #include "feature/dircommon/dir_connection_st.h"
     53 #include "core/or/edge_connection_st.h"
     54 #include "core/or/extend_info_st.h"
     55 #include "feature/nodelist/networkstatus_st.h"
     56 #include "feature/nodelist/node_st.h"
     57 #include "core/or/origin_circuit_st.h"
     58 #include "app/config/or_state_st.h"
     59 #include "feature/nodelist/routerstatus_st.h"
     60 
     61 #include "lib/encoding/confline.h"
     62 #include "lib/crypt_ops/crypto_format.h"
     63 
     64 /* Trunnel */
     65 #include "trunnel/ed25519_cert.h"
     66 #include "trunnel/hs/cell_establish_intro.h"
     67 
     68 #ifdef HAVE_SYS_STAT_H
     69 #include <sys/stat.h>
     70 #endif
     71 #ifdef HAVE_UNISTD_H
     72 #include <unistd.h>
     73 #endif
     74 
     75 #ifndef COCCI
     76 /** Helper macro. Iterate over every service in the global map. The var is the
     77 * name of the service pointer. */
     78 #define FOR_EACH_SERVICE_BEGIN(var)                          \
     79    STMT_BEGIN                                               \
     80    hs_service_t **var##_iter, *var;                         \
     81    HT_FOREACH(var##_iter, hs_service_ht, hs_service_map) {  \
     82      var = *var##_iter;
     83 #define FOR_EACH_SERVICE_END } STMT_END ;
     84 
     85 /** Helper macro. Iterate over both current and previous descriptor of a
     86 * service. The var is the name of the descriptor pointer. This macro skips
     87 * any descriptor object of the service that is NULL. */
     88 #define FOR_EACH_DESCRIPTOR_BEGIN(service, var)                  \
     89  STMT_BEGIN                                                     \
     90    hs_service_descriptor_t *var;                                \
     91    for (int var ## _loop_idx = 0; var ## _loop_idx < 2;         \
     92         ++var ## _loop_idx) {                                   \
     93      (var ## _loop_idx == 0) ? (var = service->desc_current) :  \
     94                                (var = service->desc_next);      \
     95      if (var == NULL) continue;
     96 #define FOR_EACH_DESCRIPTOR_END } STMT_END ;
     97 #endif /* !defined(COCCI) */
     98 
     99 /* Onion service directory file names. */
    100 static const char fname_keyfile_prefix[] = "hs_ed25519";
    101 static const char dname_client_pubkeys[] = "authorized_clients";
    102 static const char fname_hostname[] = "hostname";
    103 static const char address_tld[] = "onion";
    104 
    105 /** Staging list of service object. When configuring service, we add them to
    106 * this list considered a staging area and they will get added to our global
    107 * map once the keys have been loaded. These two steps are separated because
    108 * loading keys requires that we are an actual running tor process. */
    109 static smartlist_t *hs_service_staging_list;
    110 
    111 /** True if the list of available router descriptors might have changed which
    112 *  might result in an altered hash ring. Check if the hash ring changed and
    113 *  reupload if needed */
    114 static int consider_republishing_hs_descriptors = 0;
    115 
    116 /* Static declaration. */
    117 static int load_client_keys(hs_service_t *service);
    118 static void set_descriptor_revision_counter(hs_service_descriptor_t *hs_desc,
    119                                            time_t now, bool is_current);
    120 static int build_service_desc_superencrypted(const hs_service_t *service,
    121                                             hs_service_descriptor_t *desc);
    122 static void move_descriptors(hs_service_t *src, hs_service_t *dst);
    123 static int service_encode_descriptor(const hs_service_t *service,
    124                                     const hs_service_descriptor_t *desc,
    125                                     const ed25519_keypair_t *signing_kp,
    126                                     char **encoded_out);
    127 
    128 /** Helper: Function to compare two objects in the service map. Return 1 if the
    129 * two service have the same master public identity key. */
    130 static inline int
    131 hs_service_ht_eq(const hs_service_t *first, const hs_service_t *second)
    132 {
    133  tor_assert(first);
    134  tor_assert(second);
    135  /* Simple key compare. */
    136  return ed25519_pubkey_eq(&first->keys.identity_pk,
    137                           &second->keys.identity_pk);
    138 }
    139 
    140 /** Helper: Function for the service hash table code below. The key used is the
    141 * master public identity key which is ultimately the onion address. */
    142 static inline unsigned int
    143 hs_service_ht_hash(const hs_service_t *service)
    144 {
    145  tor_assert(service);
    146  return (unsigned int) siphash24g(service->keys.identity_pk.pubkey,
    147                                   sizeof(service->keys.identity_pk.pubkey));
    148 }
    149 
    150 /** This is _the_ global hash map of hidden services which indexes the services
    151 * contained in it by master public identity key which is roughly the onion
    152 * address of the service. */
    153 static struct hs_service_ht *hs_service_map;
    154 
    155 /* Register the service hash table. */
    156 HT_PROTOTYPE(hs_service_ht,      /* Name of hashtable. */
    157             hs_service_t,       /* Object contained in the map. */
    158             hs_service_node,    /* The name of the HT_ENTRY member. */
    159             hs_service_ht_hash, /* Hashing function. */
    160             hs_service_ht_eq);  /* Compare function for objects. */
    161 
    162 HT_GENERATE2(hs_service_ht, hs_service_t, hs_service_node,
    163             hs_service_ht_hash, hs_service_ht_eq,
    164             0.6, tor_reallocarray, tor_free_);
    165 
    166 /** Return true iff the given service has client authorization configured that
    167 * is the client list is non empty. */
    168 static inline bool
    169 is_client_auth_enabled(const hs_service_t *service)
    170 {
    171  return (service->config.clients != NULL &&
    172          smartlist_len(service->config.clients) > 0);
    173 }
    174 
    175 /** Query the given service map with a public key and return a service object
    176 * if found else NULL. */
    177 STATIC hs_service_t *
    178 find_service(hs_service_ht *map, const ed25519_public_key_t *pk)
    179 {
    180  hs_service_t dummy_service;
    181  tor_assert(map);
    182  tor_assert(pk);
    183  memset(&dummy_service, 0, sizeof(dummy_service));
    184  ed25519_pubkey_copy(&dummy_service.keys.identity_pk, pk);
    185  return HT_FIND(hs_service_ht, map, &dummy_service);
    186 }
    187 
    188 /** Register the given service in the given map. If the service already exists
    189 * in the map, -1 is returned. On success, 0 is returned and the service
    190 * ownership has been transferred to the global map. */
    191 STATIC int
    192 register_service(hs_service_ht *map, hs_service_t *service)
    193 {
    194  tor_assert(map);
    195  tor_assert(service);
    196  tor_assert(!ed25519_public_key_is_zero(&service->keys.identity_pk));
    197 
    198  if (find_service(map, &service->keys.identity_pk)) {
    199    /* Existing service with the same key. Do not register it. */
    200    return -1;
    201  }
    202  /* Taking ownership of the object at this point. */
    203  HT_INSERT(hs_service_ht, map, service);
    204 
    205  /* If we just modified the global map, we notify. */
    206  if (map == hs_service_map) {
    207    hs_service_map_has_changed();
    208  }
    209  /* Setup metrics. This is done here because in order to initialize metrics,
    210   * we require tor to have fully initialized a service so the ports of the
    211   * service can be looked at for instance. */
    212  hs_metrics_service_init(service);
    213 
    214  return 0;
    215 }
    216 
    217 /** Remove a given service from the given map. If service is NULL or the
    218 * service key is unset, return gracefully. */
    219 STATIC void
    220 remove_service(hs_service_ht *map, hs_service_t *service)
    221 {
    222  hs_service_t *elm;
    223 
    224  tor_assert(map);
    225 
    226  /* Ignore if no service or key is zero. */
    227  if (BUG(service == NULL) ||
    228      BUG(ed25519_public_key_is_zero(&service->keys.identity_pk))) {
    229    return;
    230  }
    231 
    232  elm = HT_REMOVE(hs_service_ht, map, service);
    233  if (elm) {
    234    tor_assert(elm == service);
    235  } else {
    236    log_warn(LD_BUG, "Could not find service in the global map "
    237                     "while removing service %s",
    238             escaped(service->config.directory_path));
    239  }
    240 
    241  /* If we just modified the global map, we notify. */
    242  if (map == hs_service_map) {
    243    hs_service_map_has_changed();
    244  }
    245 }
    246 
    247 /** Set the default values for a service configuration object <b>c</b>. */
    248 static void
    249 set_service_default_config(hs_service_config_t *c,
    250                           const or_options_t *options)
    251 {
    252  (void) options;
    253  tor_assert(c);
    254  c->ports = smartlist_new();
    255  c->directory_path = NULL;
    256  c->max_streams_per_rdv_circuit = 0;
    257  c->max_streams_close_circuit = 0;
    258  c->num_intro_points = NUM_INTRO_POINTS_DEFAULT;
    259  c->allow_unknown_ports = 0;
    260  c->is_single_onion = 0;
    261  c->dir_group_readable = 0;
    262  c->is_ephemeral = 0;
    263  c->has_dos_defense_enabled = HS_CONFIG_V3_DOS_DEFENSE_DEFAULT;
    264  c->intro_dos_rate_per_sec = HS_CONFIG_V3_DOS_DEFENSE_RATE_PER_SEC_DEFAULT;
    265  c->intro_dos_burst_per_sec = HS_CONFIG_V3_DOS_DEFENSE_BURST_PER_SEC_DEFAULT;
    266  /* PoW default options. */
    267  c->has_pow_defenses_enabled = HS_CONFIG_V3_POW_DEFENSES_DEFAULT;
    268  c->pow_queue_rate = HS_CONFIG_V3_POW_QUEUE_RATE;
    269  c->pow_queue_burst = HS_CONFIG_V3_POW_QUEUE_BURST;
    270 }
    271 
    272 /** Initialize PoW defenses */
    273 static void
    274 initialize_pow_defenses(hs_service_t *service)
    275 {
    276  service->state.pow_state = tor_malloc_zero(sizeof(hs_pow_service_state_t));
    277 
    278  /* Make life easier */
    279  hs_pow_service_state_t *pow_state = service->state.pow_state;
    280 
    281  pow_state->rend_request_pqueue = smartlist_new();
    282  pow_state->pop_pqueue_ev = NULL;
    283 
    284  /* If we are using the pqueue rate limiter, calculate min and max queue
    285   * levels based on those programmed rates. If not, we have generic
    286   * defaults */
    287  pow_state->pqueue_low_level = 16;
    288  pow_state->pqueue_high_level = 16384;
    289 
    290  if (service->config.pow_queue_rate > 0 &&
    291      service->config.pow_queue_burst >= service->config.pow_queue_rate) {
    292    pow_state->using_pqueue_bucket = 1;
    293    token_bucket_ctr_init(&pow_state->pqueue_bucket,
    294                          service->config.pow_queue_rate,
    295                          service->config.pow_queue_burst,
    296                          (uint32_t) monotime_coarse_absolute_sec());
    297 
    298    pow_state->pqueue_low_level = MAX(8, service->config.pow_queue_rate / 4);
    299    pow_state->pqueue_high_level =
    300      service->config.pow_queue_burst +
    301      service->config.pow_queue_rate * MAX_REND_TIMEOUT * 2;
    302  }
    303 
    304  /* We recalculate and update the suggested effort every HS_UPDATE_PERIOD
    305   * seconds. */
    306  pow_state->suggested_effort = 0;
    307  pow_state->rend_handled = 0;
    308  pow_state->total_effort = 0;
    309  pow_state->next_effort_update = (time(NULL) + HS_UPDATE_PERIOD);
    310 
    311  /* Generate the random seeds. We generate both as we don't want the previous
    312   * seed to be predictable even if it doesn't really exist yet, and it needs
    313   * to be different to the current nonce for the replay cache scrubbing to
    314   * function correctly. */
    315  log_info(LD_REND, "Generating both PoW seeds...");
    316  crypto_rand((char *)&pow_state->seed_current, HS_POW_SEED_LEN);
    317  crypto_rand((char *)&pow_state->seed_previous, HS_POW_SEED_LEN);
    318 
    319  pow_state->expiration_time =
    320      (time(NULL) +
    321       crypto_rand_int_range(HS_SERVICE_POW_SEED_ROTATE_TIME_MIN,
    322                             HS_SERVICE_POW_SEED_ROTATE_TIME_MAX));
    323 }
    324 
    325 /** From a service configuration object config, clear everything from it
    326 * meaning free allocated pointers and reset the values. */
    327 STATIC void
    328 service_clear_config(hs_service_config_t *config)
    329 {
    330  if (config == NULL) {
    331    return;
    332  }
    333  tor_free(config->directory_path);
    334  if (config->ports) {
    335    SMARTLIST_FOREACH(config->ports, hs_port_config_t *, p,
    336                      hs_port_config_free(p););
    337    smartlist_free(config->ports);
    338  }
    339  if (config->clients) {
    340    SMARTLIST_FOREACH(config->clients, hs_service_authorized_client_t *, p,
    341                      service_authorized_client_free(p));
    342    smartlist_free(config->clients);
    343  }
    344  if (config->ob_master_pubkeys) {
    345    SMARTLIST_FOREACH(config->ob_master_pubkeys, ed25519_public_key_t *, k,
    346                      tor_free(k));
    347    smartlist_free(config->ob_master_pubkeys);
    348  }
    349  memset(config, 0, sizeof(*config));
    350 }
    351 
    352 /** Helper function to return a human readable description of the given intro
    353 * point object.
    354 *
    355 * This function is not thread-safe. Each call to this invalidates the
    356 * previous values returned by it. */
    357 static const char *
    358 describe_intro_point(const hs_service_intro_point_t *ip)
    359 {
    360  /* Hex identity digest of the IP prefixed by the $ sign and ends with NUL
    361   * byte hence the plus two. */
    362  static char buf[HEX_DIGEST_LEN + 2];
    363  const char *legacy_id = NULL;
    364 
    365  SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
    366                          const link_specifier_t *, lspec) {
    367    if (link_specifier_get_ls_type(lspec) == LS_LEGACY_ID) {
    368      legacy_id = (const char *)
    369        link_specifier_getconstarray_un_legacy_id(lspec);
    370      break;
    371    }
    372  } SMARTLIST_FOREACH_END(lspec);
    373 
    374  /* For now, we only print the identity digest but we could improve this with
    375   * much more information such as the ed25519 identity has well. */
    376  buf[0] = '$';
    377  if (legacy_id) {
    378    base16_encode(buf + 1, HEX_DIGEST_LEN + 1, legacy_id, DIGEST_LEN);
    379  }
    380 
    381  return buf;
    382 }
    383 
    384 /** Return the lower bound of maximum INTRODUCE2 cells per circuit before we
    385 * rotate intro point (defined by a consensus parameter or the default
    386 * value). */
    387 static int32_t
    388 get_intro_point_min_introduce2(void)
    389 {
    390  /* The [0, 2147483647] range is quite large to accommodate anything we decide
    391   * in the future. */
    392  return networkstatus_get_param(NULL, "hs_intro_min_introduce2",
    393                                 INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
    394                                 0, INT32_MAX);
    395 }
    396 
    397 /** Return the upper bound of maximum INTRODUCE2 cells per circuit before we
    398 * rotate intro point (defined by a consensus parameter or the default
    399 * value). */
    400 static int32_t
    401 get_intro_point_max_introduce2(void)
    402 {
    403  /* The [0, 2147483647] range is quite large to accommodate anything we decide
    404   * in the future. */
    405  return networkstatus_get_param(NULL, "hs_intro_max_introduce2",
    406                                 INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS,
    407                                 0, INT32_MAX);
    408 }
    409 
    410 /** Return the minimum lifetime in seconds of an introduction point defined by
    411 * a consensus parameter or the default value. */
    412 static int32_t
    413 get_intro_point_min_lifetime(void)
    414 {
    415  /* The [0, 2147483647] range is quite large to accommodate anything we decide
    416   * in the future. */
    417  return networkstatus_get_param(NULL, "hs_intro_min_lifetime",
    418                                 INTRO_POINT_LIFETIME_MIN_SECONDS,
    419                                 0, INT32_MAX);
    420 }
    421 
    422 /** Return the maximum lifetime in seconds of an introduction point defined by
    423 * a consensus parameter or the default value. */
    424 static int32_t
    425 get_intro_point_max_lifetime(void)
    426 {
    427  /* The [0, 2147483647] range is quite large to accommodate anything we decide
    428   * in the future. */
    429  return networkstatus_get_param(NULL, "hs_intro_max_lifetime",
    430                                 INTRO_POINT_LIFETIME_MAX_SECONDS,
    431                                 0, INT32_MAX);
    432 }
    433 
    434 /** Return the number of extra introduction point defined by a consensus
    435 * parameter or the default value. */
    436 static int32_t
    437 get_intro_point_num_extra(void)
    438 {
    439  /* The [0, 128] range bounds the number of extra introduction point allowed.
    440   * Above 128 intro points, it's getting a bit crazy. */
    441  return networkstatus_get_param(NULL, "hs_intro_num_extra",
    442                                 NUM_INTRO_POINTS_EXTRA, 0, 128);
    443 }
    444 
    445 /** Helper: Function that needs to return 1 for the HT for each loop which
    446 * frees every service in an hash map. */
    447 static int
    448 ht_free_service_(struct hs_service_t *service, void *data)
    449 {
    450  (void) data;
    451  hs_service_free(service);
    452  /* This function MUST return 1 so the given object is then removed from the
    453   * service map leading to this free of the object being safe. */
    454  return 1;
    455 }
    456 
    457 /** Free every service that can be found in the global map. Once done, clear
    458 * and free the global map. */
    459 static void
    460 service_free_all(void)
    461 {
    462  if (hs_service_map) {
    463    /* The free helper function returns 1 so this is safe. */
    464    hs_service_ht_HT_FOREACH_FN(hs_service_map, ht_free_service_, NULL);
    465    HT_CLEAR(hs_service_ht, hs_service_map);
    466    tor_free(hs_service_map);
    467    hs_service_map = NULL;
    468  }
    469 
    470  if (hs_service_staging_list) {
    471    /* Cleanup staging list. */
    472    SMARTLIST_FOREACH(hs_service_staging_list, hs_service_t *, s,
    473                      hs_service_free(s));
    474    smartlist_free(hs_service_staging_list);
    475    hs_service_staging_list = NULL;
    476  }
    477 }
    478 
    479 /** Free a given service intro point object. */
    480 STATIC void
    481 service_intro_point_free_(hs_service_intro_point_t *ip)
    482 {
    483  if (!ip) {
    484    return;
    485  }
    486  memwipe(&ip->auth_key_kp, 0, sizeof(ip->auth_key_kp));
    487  memwipe(&ip->enc_key_kp, 0, sizeof(ip->enc_key_kp));
    488  crypto_pk_free(ip->legacy_key);
    489  replaycache_free(ip->replay_cache);
    490  hs_intropoint_clear(&ip->base);
    491  tor_free(ip);
    492 }
    493 
    494 /** Helper: free an hs_service_intro_point_t object. This function is used by
    495 * digest256map_free() which requires a void * pointer. */
    496 static void
    497 service_intro_point_free_void(void *obj)
    498 {
    499  service_intro_point_free_(obj);
    500 }
    501 
    502 /** Return a newly allocated service intro point and fully initialized from the
    503 * given node_t node, if non NULL.
    504 *
    505 * If node is NULL, returns a hs_service_intro_point_t with an empty link
    506 * specifier list and no onion key. (This is used for testing.)
    507 * On any other error, NULL is returned.
    508 *
    509 * node must be an node_t with an IPv4 address. */
    510 STATIC hs_service_intro_point_t *
    511 service_intro_point_new(const node_t *node)
    512 {
    513  hs_service_intro_point_t *ip;
    514 
    515  ip = tor_malloc_zero(sizeof(*ip));
    516  /* We'll create the key material. No need for extra strong, those are short
    517   * term keys. */
    518  ed25519_keypair_generate(&ip->auth_key_kp, 0);
    519 
    520  { /* Set introduce2 max cells limit */
    521    int32_t min_introduce2_cells = get_intro_point_min_introduce2();
    522    int32_t max_introduce2_cells = get_intro_point_max_introduce2();
    523    if (BUG(max_introduce2_cells < min_introduce2_cells)) {
    524      goto err;
    525    }
    526    ip->introduce2_max = crypto_rand_int_range(min_introduce2_cells,
    527                                               max_introduce2_cells);
    528  }
    529  { /* Set intro point lifetime */
    530    int32_t intro_point_min_lifetime = get_intro_point_min_lifetime();
    531    int32_t intro_point_max_lifetime = get_intro_point_max_lifetime();
    532    if (BUG(intro_point_max_lifetime < intro_point_min_lifetime)) {
    533      goto err;
    534    }
    535    ip->time_to_expire = approx_time() +
    536      crypto_rand_int_range(intro_point_min_lifetime,intro_point_max_lifetime);
    537  }
    538 
    539  ip->replay_cache = replaycache_new(0, 0);
    540 
    541  /* Initialize the base object. We don't need the certificate object. */
    542  ip->base.link_specifiers = node_get_link_specifier_smartlist(node, 0);
    543 
    544  if (node == NULL) {
    545    goto done;
    546  }
    547 
    548  /* Generate the encryption key for this intro point. */
    549  curve25519_keypair_generate(&ip->enc_key_kp, 0);
    550  /* Figure out if this chosen node supports v3 or is legacy only.
    551   * NULL nodes are used in the unit tests. */
    552  if (!node_supports_ed25519_hs_intro(node)) {
    553    ip->base.is_only_legacy = 1;
    554    /* Legacy mode that is doesn't support v3+ with ed25519 auth key. */
    555    ip->legacy_key = crypto_pk_new();
    556    if (crypto_pk_generate_key(ip->legacy_key) < 0) {
    557      goto err;
    558    }
    559    if (crypto_pk_get_digest(ip->legacy_key,
    560                             (char *) ip->legacy_key_digest) < 0) {
    561      goto err;
    562    }
    563  }
    564 
    565  /* Flag if this intro point supports the INTRO2 dos defenses. */
    566  ip->support_intro2_dos_defense =
    567    node_supports_establish_intro_dos_extension(node);
    568 
    569  /* Finally, copy onion key from the node. */
    570  memcpy(&ip->onion_key, node_get_curve25519_onion_key(node),
    571         sizeof(ip->onion_key));
    572 
    573 done:
    574  return ip;
    575 err:
    576  service_intro_point_free(ip);
    577  return NULL;
    578 }
    579 
    580 /** Add the given intro point object to the given intro point map. The intro
    581 * point MUST have its RSA encryption key set if this is a legacy type or the
    582 * authentication key set otherwise. */
    583 STATIC void
    584 service_intro_point_add(digest256map_t *map, hs_service_intro_point_t *ip)
    585 {
    586  hs_service_intro_point_t *old_ip_entry;
    587 
    588  tor_assert(map);
    589  tor_assert(ip);
    590 
    591  old_ip_entry = digest256map_set(map, ip->auth_key_kp.pubkey.pubkey, ip);
    592  /* Make sure we didn't just try to double-add an intro point */
    593  tor_assert_nonfatal(!old_ip_entry);
    594 }
    595 
    596 /** For a given service, remove the intro point from that service's descriptors
    597 * (check both current and next descriptor) */
    598 STATIC void
    599 service_intro_point_remove(const hs_service_t *service,
    600                           const hs_service_intro_point_t *ip)
    601 {
    602  tor_assert(service);
    603  tor_assert(ip);
    604 
    605  /* Trying all descriptors. */
    606  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
    607    /* We'll try to remove the descriptor on both descriptors which is not
    608     * very expensive to do instead of doing lookup + remove. */
    609    digest256map_remove(desc->intro_points.map,
    610                        ip->auth_key_kp.pubkey.pubkey);
    611  } FOR_EACH_DESCRIPTOR_END;
    612 }
    613 
    614 /** For a given service and authentication key, return the intro point or NULL
    615 * if not found. This will check both descriptors in the service. */
    616 STATIC hs_service_intro_point_t *
    617 service_intro_point_find(const hs_service_t *service,
    618                         const ed25519_public_key_t *auth_key)
    619 {
    620  hs_service_intro_point_t *ip = NULL;
    621 
    622  tor_assert(service);
    623  tor_assert(auth_key);
    624 
    625  /* Trying all descriptors to find the right intro point.
    626   *
    627   * Even if we use the same node as intro point in both descriptors, the node
    628   * will have a different intro auth key for each descriptor since we generate
    629   * a new one every time we pick an intro point.
    630   *
    631   * After #22893 gets implemented, intro points will be moved to be
    632   * per-service instead of per-descriptor so this function will need to
    633   * change.
    634   */
    635  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
    636    if ((ip = digest256map_get(desc->intro_points.map,
    637                               auth_key->pubkey)) != NULL) {
    638      break;
    639    }
    640  } FOR_EACH_DESCRIPTOR_END;
    641 
    642  return ip;
    643 }
    644 
    645 /** For a given service and intro point, return the descriptor for which the
    646 * intro point is assigned to. NULL is returned if not found. */
    647 STATIC hs_service_descriptor_t *
    648 service_desc_find_by_intro(const hs_service_t *service,
    649                           const hs_service_intro_point_t *ip)
    650 {
    651  hs_service_descriptor_t *descp = NULL;
    652 
    653  tor_assert(service);
    654  tor_assert(ip);
    655 
    656  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
    657    if (digest256map_get(desc->intro_points.map,
    658                         ip->auth_key_kp.pubkey.pubkey)) {
    659      descp = desc;
    660      break;
    661    }
    662  } FOR_EACH_DESCRIPTOR_END;
    663 
    664  return descp;
    665 }
    666 
    667 /** From a circuit identifier, get all the possible objects associated with the
    668 * ident. If not NULL, service, ip or desc are set if the object can be found.
    669 * They are untouched if they can't be found.
    670 *
    671 * This is an helper function because we do those lookups often so it's more
    672 * convenient to simply call this functions to get all the things at once. */
    673 STATIC void
    674 get_objects_from_ident(const hs_ident_circuit_t *ident,
    675                       hs_service_t **service, hs_service_intro_point_t **ip,
    676                       hs_service_descriptor_t **desc)
    677 {
    678  hs_service_t *s;
    679 
    680  tor_assert(ident);
    681 
    682  /* Get service object from the circuit identifier. */
    683  s = find_service(hs_service_map, &ident->identity_pk);
    684  if (s && service) {
    685    *service = s;
    686  }
    687 
    688  /* From the service object, get the intro point object of that circuit. The
    689   * following will query both descriptors intro points list. */
    690  if (s && ip) {
    691    *ip = service_intro_point_find(s, &ident->intro_auth_pk);
    692  }
    693 
    694  /* Get the descriptor for this introduction point and service. */
    695  if (s && ip && *ip && desc) {
    696    *desc = service_desc_find_by_intro(s, *ip);
    697  }
    698 }
    699 
    700 /** From a given intro point, return the first link specifier of type
    701 * encountered in the link specifier list. Return NULL if it can't be found.
    702 *
    703 * The caller does NOT have ownership of the object, the intro point does. */
    704 static link_specifier_t *
    705 get_link_spec_by_type(const hs_service_intro_point_t *ip, uint8_t type)
    706 {
    707  link_specifier_t *lnk_spec = NULL;
    708 
    709  tor_assert(ip);
    710 
    711  SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
    712                          link_specifier_t *, ls) {
    713    if (link_specifier_get_ls_type(ls) == type) {
    714      lnk_spec = ls;
    715      goto end;
    716    }
    717  } SMARTLIST_FOREACH_END(ls);
    718 
    719 end:
    720  return lnk_spec;
    721 }
    722 
    723 /** Given a service intro point, return the node_t associated to it. This can
    724 * return NULL if the given intro point has no legacy ID or if the node can't
    725 * be found in the consensus. */
    726 STATIC const node_t *
    727 get_node_from_intro_point(const hs_service_intro_point_t *ip)
    728 {
    729  const link_specifier_t *ls;
    730 
    731  tor_assert(ip);
    732 
    733  ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
    734  if (BUG(!ls)) {
    735    return NULL;
    736  }
    737  /* XXX In the future, we want to only use the ed25519 ID (#22173). */
    738  return node_get_by_id(
    739    (const char *) link_specifier_getconstarray_un_legacy_id(ls));
    740 }
    741 
    742 /** Given a service intro point, return the extend_info_t for it. This can
    743 * return NULL if the node can't be found for the intro point or the extend
    744 * info can't be created for the found node. If direct_conn is set, the extend
    745 * info is validated on if we can connect directly. */
    746 static extend_info_t *
    747 get_extend_info_from_intro_point(const hs_service_intro_point_t *ip,
    748                                 unsigned int direct_conn)
    749 {
    750  extend_info_t *info = NULL;
    751  const node_t *node;
    752 
    753  tor_assert(ip);
    754 
    755  node = get_node_from_intro_point(ip);
    756  if (node == NULL) {
    757    /* This can happen if the relay serving as intro point has been removed
    758     * from the consensus. In that case, the intro point will be removed from
    759     * the descriptor during the scheduled events. */
    760    goto end;
    761  }
    762 
    763  /* In the case of a direct connection (single onion service), it is possible
    764   * our firewall policy won't allow it so this can return a NULL value. */
    765  info = extend_info_from_node(node, direct_conn, false);
    766 
    767 end:
    768  return info;
    769 }
    770 
    771 /** Return the number of introduction points that are established for the
    772 * given descriptor. */
    773 MOCK_IMPL(STATIC unsigned int,
    774 count_desc_circuit_established, (const hs_service_descriptor_t *desc))
    775 {
    776  unsigned int count = 0;
    777 
    778  tor_assert(desc);
    779 
    780  DIGEST256MAP_FOREACH(desc->intro_points.map, key,
    781                       const hs_service_intro_point_t *, ip) {
    782    count += !!hs_circ_service_get_established_intro_circ(ip);
    783  } DIGEST256MAP_FOREACH_END;
    784 
    785  return count;
    786 }
    787 
    788 /** For a given service and descriptor of that service, close all active
    789 * directory connections. */
    790 static void
    791 close_directory_connections(const hs_service_t *service,
    792                            const hs_service_descriptor_t *desc)
    793 {
    794  unsigned int count = 0;
    795  smartlist_t *dir_conns;
    796 
    797  tor_assert(service);
    798  tor_assert(desc);
    799 
    800  /* Close pending HS desc upload connections for the blinded key of 'desc'. */
    801  dir_conns = connection_list_by_type_purpose(CONN_TYPE_DIR,
    802                                              DIR_PURPOSE_UPLOAD_HSDESC);
    803  SMARTLIST_FOREACH_BEGIN(dir_conns, connection_t *, conn) {
    804    dir_connection_t *dir_conn = TO_DIR_CONN(conn);
    805    if (ed25519_pubkey_eq(&dir_conn->hs_ident->identity_pk,
    806                          &service->keys.identity_pk) &&
    807        ed25519_pubkey_eq(&dir_conn->hs_ident->blinded_pk,
    808                          &desc->blinded_kp.pubkey)) {
    809      connection_mark_for_close(conn);
    810      count++;
    811      continue;
    812    }
    813  } SMARTLIST_FOREACH_END(conn);
    814 
    815  log_info(LD_REND, "Closed %u active service directory connections for "
    816                    "descriptor %s of service %s",
    817           count, safe_str_client(ed25519_fmt(&desc->blinded_kp.pubkey)),
    818           safe_str_client(service->onion_address));
    819  /* We don't have ownership of the objects in this list. */
    820  smartlist_free(dir_conns);
    821 }
    822 
    823 /** Close all rendezvous circuits for the given service. */
    824 static void
    825 close_service_rp_circuits(hs_service_t *service)
    826 {
    827  origin_circuit_t *ocirc = NULL;
    828 
    829  tor_assert(service);
    830 
    831  /* The reason we go over all circuit instead of using the circuitmap API is
    832   * because most hidden service circuits are rendezvous circuits so there is
    833   * no real improvement at getting all rendezvous circuits from the
    834   * circuitmap and then going over them all to find the right ones.
    835   * Furthermore, another option would have been to keep a list of RP cookies
    836   * for a service but it creates an engineering complexity since we don't
    837   * have a "RP circuit closed" event to clean it up properly so we avoid a
    838   * memory DoS possibility. */
    839 
    840  while ((ocirc = circuit_get_next_service_rp_circ(ocirc))) {
    841    /* Only close circuits that are v3 and for this service. */
    842    if (ocirc->hs_ident != NULL &&
    843        ed25519_pubkey_eq(&ocirc->hs_ident->identity_pk,
    844                          &service->keys.identity_pk)) {
    845      /* Reason is FINISHED because service has been removed and thus the
    846       * circuit is considered old/unneeded. When freed, it is removed from the
    847       * hs circuitmap. */
    848      circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
    849    }
    850  }
    851 }
    852 
    853 /** Close the circuit(s) for the given map of introduction points. */
    854 static void
    855 close_intro_circuits(hs_service_intropoints_t *intro_points)
    856 {
    857  tor_assert(intro_points);
    858 
    859  DIGEST256MAP_FOREACH(intro_points->map, key,
    860                       const hs_service_intro_point_t *, ip) {
    861    origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
    862    if (ocirc) {
    863      /* Reason is FINISHED because service has been removed and thus the
    864       * circuit is considered old/unneeded. When freed, the circuit is removed
    865       * from the HS circuitmap. */
    866      circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
    867    }
    868  } DIGEST256MAP_FOREACH_END;
    869 }
    870 
    871 /** Close all introduction circuits for the given service. */
    872 static void
    873 close_service_intro_circuits(hs_service_t *service)
    874 {
    875  tor_assert(service);
    876 
    877  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
    878    close_intro_circuits(&desc->intro_points);
    879  } FOR_EACH_DESCRIPTOR_END;
    880 }
    881 
    882 /** Close any circuits related to the given service. */
    883 static void
    884 close_service_circuits(hs_service_t *service)
    885 {
    886  tor_assert(service);
    887 
    888  /* Only support for version >= 3. */
    889  if (BUG(service->config.version < HS_VERSION_THREE)) {
    890    return;
    891  }
    892  /* Close intro points. */
    893  close_service_intro_circuits(service);
    894  /* Close rendezvous points. */
    895  close_service_rp_circuits(service);
    896 }
    897 
    898 /** Move every ephemeral services from the src service map to the dst service
    899 * map. It is possible that a service can't be register to the dst map which
    900 * won't stop the process of moving them all but will trigger a log warn. */
    901 static void
    902 move_ephemeral_services(hs_service_ht *src, hs_service_ht *dst)
    903 {
    904  hs_service_t **iter, **next;
    905 
    906  tor_assert(src);
    907  tor_assert(dst);
    908 
    909  /* Iterate over the map to find ephemeral service and move them to the other
    910   * map. We loop using this method to have a safe removal process. */
    911  for (iter = HT_START(hs_service_ht, src); iter != NULL; iter = next) {
    912    hs_service_t *s = *iter;
    913    if (!s->config.is_ephemeral) {
    914      /* Yeah, we are in a very manual loop :). */
    915      next = HT_NEXT(hs_service_ht, src, iter);
    916      continue;
    917    }
    918    /* Remove service from map and then register to it to the other map.
    919     * Reminder that "*iter" and "s" are the same thing. */
    920    next = HT_NEXT_RMV(hs_service_ht, src, iter);
    921    if (register_service(dst, s) < 0) {
    922      log_warn(LD_BUG, "Ephemeral service key is already being used. "
    923                       "Skipping.");
    924    }
    925  }
    926 }
    927 
    928 /** Return a const string of the directory path escaped. If this is an
    929 * ephemeral service, it returns "[EPHEMERAL]". This can only be called from
    930 * the main thread because escaped() uses a static variable. */
    931 static const char *
    932 service_escaped_dir(const hs_service_t *s)
    933 {
    934  return (s->config.is_ephemeral) ? "[EPHEMERAL]" :
    935                                    escaped(s->config.directory_path);
    936 }
    937 
    938 /** Move the hidden service state from <b>src</b> to <b>dst</b>. We do this
    939 *  when we receive a SIGHUP: <b>dst</b> is the post-HUP service */
    940 static void
    941 move_hs_state(hs_service_t *src_service, hs_service_t *dst_service)
    942 {
    943  tor_assert(src_service);
    944  tor_assert(dst_service);
    945 
    946  hs_service_state_t *src = &src_service->state;
    947  hs_service_state_t *dst = &dst_service->state;
    948 
    949  /* Let's do a shallow copy */
    950  dst->intro_circ_retry_started_time = src->intro_circ_retry_started_time;
    951  dst->num_intro_circ_launched = src->num_intro_circ_launched;
    952  /* Freeing a NULL replaycache triggers an info LD_BUG. */
    953  if (dst->replay_cache_rend_cookie != NULL) {
    954    replaycache_free(dst->replay_cache_rend_cookie);
    955  }
    956 
    957  dst->replay_cache_rend_cookie = src->replay_cache_rend_cookie;
    958  src->replay_cache_rend_cookie = NULL; /* steal pointer reference */
    959 
    960  dst->next_rotation_time = src->next_rotation_time;
    961 
    962  if (src->ob_subcreds) {
    963    dst->ob_subcreds = src->ob_subcreds;
    964    dst->n_ob_subcreds =  src->n_ob_subcreds;
    965 
    966    src->ob_subcreds = NULL; /* steal pointer reference */
    967  }
    968 }
    969 
    970 /** Register services that are in the staging list. Once this function returns,
    971 * the global service map will be set with the right content and all non
    972 * surviving services will be cleaned up. */
    973 static void
    974 register_all_services(void)
    975 {
    976  struct hs_service_ht *new_service_map;
    977 
    978  tor_assert(hs_service_staging_list);
    979 
    980  /* Allocate a new map that will replace the current one. */
    981  new_service_map = tor_malloc_zero(sizeof(*new_service_map));
    982  HT_INIT(hs_service_ht, new_service_map);
    983 
    984  /* First step is to transfer all ephemeral services from the current global
    985   * map to the new one we are constructing. We do not prune ephemeral
    986   * services as the only way to kill them is by deleting it from the control
    987   * port or stopping the tor daemon. */
    988  move_ephemeral_services(hs_service_map, new_service_map);
    989 
    990  SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, snew) {
    991    hs_service_t *s;
    992 
    993    /* Check if that service is already in our global map and if so, we'll
    994     * transfer the intro points to it. */
    995    s = find_service(hs_service_map, &snew->keys.identity_pk);
    996    if (s) {
    997      /* Pass ownership of the descriptors from s (the current service) to
    998       * snew (the newly configured one). */
    999      move_descriptors(s, snew);
   1000      move_hs_state(s, snew);
   1001      /* Remove the service from the global map because after this, we need to
   1002       * go over the remaining service in that map that aren't surviving the
   1003       * reload to close their circuits. */
   1004      remove_service(hs_service_map, s);
   1005      hs_service_free(s);
   1006    }
   1007    /* Great, this service is now ready to be added to our new map. */
   1008    if (BUG(register_service(new_service_map, snew) < 0)) {
   1009      /* This should never happen because prior to registration, we validate
   1010       * every service against the entire set. Not being able to register a
   1011       * service means we failed to validate correctly. In that case, don't
   1012       * break tor and ignore the service but tell user. */
   1013      log_warn(LD_BUG, "Unable to register service with directory %s",
   1014               service_escaped_dir(snew));
   1015      SMARTLIST_DEL_CURRENT(hs_service_staging_list, snew);
   1016      hs_service_free(snew);
   1017    }
   1018  } SMARTLIST_FOREACH_END(snew);
   1019 
   1020  /* Close any circuits associated with the non surviving services. Every
   1021   * service in the current global map are roaming. */
   1022  FOR_EACH_SERVICE_BEGIN(service) {
   1023    close_service_circuits(service);
   1024  } FOR_EACH_SERVICE_END;
   1025 
   1026  /* Time to make the switch. We'll clear the staging list because its content
   1027   * has now changed ownership to the map. */
   1028  smartlist_clear(hs_service_staging_list);
   1029  service_free_all();
   1030  hs_service_map = new_service_map;
   1031  /* We've just register services into the new map and now we've replaced the
   1032   * global map with it so we have to notify that the change happened. When
   1033   * registering a service, the notify is only triggered if the destination
   1034   * map is the global map for which in here it was not. */
   1035  hs_service_map_has_changed();
   1036 }
   1037 
   1038 /** Write the onion address of a given service to the given filename fname_ in
   1039 * the service directory. Return 0 on success else -1 on error. */
   1040 STATIC int
   1041 write_address_to_file(const hs_service_t *service, const char *fname_)
   1042 {
   1043  int ret = -1;
   1044  char *fname = NULL;
   1045  char *addr_buf = NULL;
   1046 
   1047  tor_assert(service);
   1048  tor_assert(fname_);
   1049 
   1050  /* Construct the full address with the onion tld and write the hostname file
   1051   * to disk. */
   1052  tor_asprintf(&addr_buf, "%s.%s\n", service->onion_address, address_tld);
   1053  /* Notice here that we use the given "fname_". */
   1054  fname = hs_path_from_filename(service->config.directory_path, fname_);
   1055  if (write_str_to_file_if_not_equal(fname, addr_buf)) {
   1056    log_warn(LD_REND, "Could not write onion address to hostname file %s",
   1057             escaped(fname));
   1058    goto end;
   1059  }
   1060 
   1061 #ifndef _WIN32
   1062  if (service->config.dir_group_readable) {
   1063    /* Mode to 0640. */
   1064    if (chmod(fname, S_IRUSR | S_IWUSR | S_IRGRP) < 0) {
   1065      log_warn(LD_FS, "Unable to make onion service hostname file %s "
   1066                      "group-readable.", escaped(fname));
   1067    }
   1068  }
   1069 #endif /* !defined(_WIN32) */
   1070 
   1071  /* Success. */
   1072  ret = 0;
   1073 end:
   1074  tor_free(fname);
   1075  tor_free(addr_buf);
   1076  return ret;
   1077 }
   1078 
   1079 /** Load and/or generate private keys for the given service. On success, the
   1080 * hostname file will be written to disk along with the master private key iff
   1081 * the service is not configured for offline keys. Return 0 on success else -1
   1082 * on failure. */
   1083 static int
   1084 load_service_keys(hs_service_t *service)
   1085 {
   1086  int ret = -1;
   1087  char *fname = NULL;
   1088  ed25519_keypair_t *kp;
   1089  const hs_service_config_t *config;
   1090 
   1091  tor_assert(service);
   1092 
   1093  config = &service->config;
   1094 
   1095  /* Create and fix permission on service directory. We are about to write
   1096   * files to that directory so make sure it exists and has the right
   1097   * permissions. We do this here because at this stage we know that Tor is
   1098   * actually running and the service we have has been validated. */
   1099  if (hs_check_service_private_dir(get_options()->User,
   1100                                   config->directory_path,
   1101                                   config->dir_group_readable, 1) < 0) {
   1102    goto end;
   1103  }
   1104 
   1105  /* Try to load the keys from file or generate it if not found. */
   1106  fname = hs_path_from_filename(config->directory_path, fname_keyfile_prefix);
   1107  /* Don't ask for key creation, we want to know if we were able to load it or
   1108   * we had to generate it. Better logging! */
   1109  kp = ed_key_init_from_file(fname, INIT_ED_KEY_SPLIT, LOG_INFO, NULL, 0, 0,
   1110                             0, NULL, NULL);
   1111  if (!kp) {
   1112    log_info(LD_REND, "Unable to load keys from %s. Generating it...", fname);
   1113    /* We'll now try to generate the keys and for it we want the strongest
   1114     * randomness for it. The keypair will be written in different files. */
   1115    uint32_t key_flags = INIT_ED_KEY_CREATE | INIT_ED_KEY_EXTRA_STRONG |
   1116                         INIT_ED_KEY_SPLIT;
   1117    kp = ed_key_init_from_file(fname, key_flags, LOG_WARN, NULL, 0, 0, 0,
   1118                               NULL, NULL);
   1119    if (!kp) {
   1120      log_warn(LD_REND, "Unable to generate keys and save in %s.", fname);
   1121      goto end;
   1122    }
   1123  }
   1124 
   1125  /* Copy loaded or generated keys to service object. */
   1126  ed25519_pubkey_copy(&service->keys.identity_pk, &kp->pubkey);
   1127  memcpy(&service->keys.identity_sk, &kp->seckey,
   1128         sizeof(service->keys.identity_sk));
   1129  /* This does a proper memory wipe. */
   1130  ed25519_keypair_free(kp);
   1131 
   1132  /* Build onion address from the newly loaded keys. */
   1133  tor_assert(service->config.version <= UINT8_MAX);
   1134  hs_build_address(&service->keys.identity_pk,
   1135                   (uint8_t) service->config.version,
   1136                   service->onion_address);
   1137 
   1138  /* Write onion address to hostname file. */
   1139  if (write_address_to_file(service, fname_hostname) < 0) {
   1140    goto end;
   1141  }
   1142 
   1143  /* Load all client authorization keys in the service. */
   1144  if (load_client_keys(service) < 0) {
   1145    goto end;
   1146  }
   1147 
   1148  /* Success. */
   1149  ret = 0;
   1150 end:
   1151  tor_free(fname);
   1152  return ret;
   1153 }
   1154 
   1155 /** Check if the client file name is valid or not. Return 1 if valid,
   1156 * otherwise return 0. */
   1157 STATIC int
   1158 client_filename_is_valid(const char *filename)
   1159 {
   1160  int ret = 1;
   1161  const char *valid_extension = ".auth";
   1162 
   1163  tor_assert(filename);
   1164 
   1165  /* The file extension must match and the total filename length can't be the
   1166   * length of the extension else we do not have a filename. */
   1167  if (!strcmpend(filename, valid_extension) &&
   1168      strlen(filename) != strlen(valid_extension)) {
   1169    ret = 1;
   1170  } else {
   1171    ret = 0;
   1172  }
   1173 
   1174  return ret;
   1175 }
   1176 
   1177 /** Parse an base32-encoded authorized client from a string.
   1178 *
   1179 * Return the key on success, return NULL, otherwise. */
   1180 hs_service_authorized_client_t *
   1181 parse_authorized_client_key(const char *key_str, int severity)
   1182 {
   1183  hs_service_authorized_client_t *client = NULL;
   1184 
   1185  /* We expect a specific length of the base64 encoded key so make sure we
   1186   * have that so we don't successfully decode a value with a different length
   1187   * and end up in trouble when copying the decoded key into a fixed length
   1188   * buffer. */
   1189  if (strlen(key_str) != BASE32_NOPAD_LEN(CURVE25519_PUBKEY_LEN)) {
   1190    log_fn(severity, LD_REND, "Client authorization encoded base32 public key "
   1191                              "length is invalid: %s", key_str);
   1192    goto err;
   1193  }
   1194 
   1195  client = tor_malloc_zero(sizeof(hs_service_authorized_client_t));
   1196  if (base32_decode((char *) client->client_pk.public_key,
   1197                    sizeof(client->client_pk.public_key),
   1198                    key_str, strlen(key_str)) !=
   1199      sizeof(client->client_pk.public_key)) {
   1200    log_fn(severity, LD_REND, "Client authorization public key cannot be "
   1201             "decoded: %s", key_str);
   1202    goto err;
   1203  }
   1204 
   1205  return client;
   1206 
   1207 err:
   1208  if (client != NULL) {
   1209    service_authorized_client_free(client);
   1210  }
   1211  return NULL;
   1212 }
   1213 
   1214 /** Parse an authorized client from a string. The format of a client string
   1215 * looks like (see rend-spec-v3.txt):
   1216 *
   1217 *  <auth-type>:<key-type>:<base32-encoded-public-key>
   1218 *
   1219 * The <auth-type> can only be "descriptor".
   1220 * The <key-type> can only be "x25519".
   1221 *
   1222 * Return the key on success, return NULL, otherwise. */
   1223 STATIC hs_service_authorized_client_t *
   1224 parse_authorized_client(const char *client_key_str)
   1225 {
   1226  char *auth_type = NULL;
   1227  char *key_type = NULL;
   1228  char *pubkey_b32 = NULL;
   1229  hs_service_authorized_client_t *client = NULL;
   1230  smartlist_t *fields = smartlist_new();
   1231 
   1232  tor_assert(client_key_str);
   1233 
   1234  smartlist_split_string(fields, client_key_str, ":",
   1235                         SPLIT_SKIP_SPACE, 0);
   1236  /* Wrong number of fields. */
   1237  if (smartlist_len(fields) != 3) {
   1238    log_warn(LD_REND, "Unknown format of client authorization file.");
   1239    goto err;
   1240  }
   1241 
   1242  auth_type = smartlist_get(fields, 0);
   1243  key_type = smartlist_get(fields, 1);
   1244  pubkey_b32 = smartlist_get(fields, 2);
   1245 
   1246  /* Currently, the only supported auth type is "descriptor". */
   1247  if (strcmp(auth_type, "descriptor")) {
   1248    log_warn(LD_REND, "Client authorization auth type '%s' not supported.",
   1249             auth_type);
   1250    goto err;
   1251  }
   1252 
   1253  /* Currently, the only supported key type is "x25519". */
   1254  if (strcmp(key_type, "x25519")) {
   1255    log_warn(LD_REND, "Client authorization key type '%s' not supported.",
   1256             key_type);
   1257    goto err;
   1258  }
   1259 
   1260  if ((client = parse_authorized_client_key(pubkey_b32, LOG_WARN)) == NULL) {
   1261    goto err;
   1262  }
   1263 
   1264  /* Success. */
   1265  goto done;
   1266 
   1267 err:
   1268  service_authorized_client_free(client);
   1269 done:
   1270  /* It is also a good idea to wipe the public key. */
   1271  if (pubkey_b32) {
   1272    memwipe(pubkey_b32, 0, strlen(pubkey_b32));
   1273  }
   1274  tor_assert(fields);
   1275  SMARTLIST_FOREACH(fields, char *, s, tor_free(s));
   1276  smartlist_free(fields);
   1277  return client;
   1278 }
   1279 
   1280 /** Load all the client public keys for the given service. Return 0 on
   1281 * success else -1 on failure. */
   1282 static int
   1283 load_client_keys(hs_service_t *service)
   1284 {
   1285  int ret = -1;
   1286  char *client_key_str = NULL;
   1287  char *client_key_file_path = NULL;
   1288  char *client_keys_dir_path = NULL;
   1289  hs_service_config_t *config;
   1290  smartlist_t *file_list = NULL;
   1291 
   1292  tor_assert(service);
   1293 
   1294  config = &service->config;
   1295 
   1296  /* Before calling this function, we already call load_service_keys to make
   1297   * sure that the directory exists with the right permission. So, if we
   1298   * cannot create a client pubkey key directory, we consider it as a bug. */
   1299  client_keys_dir_path = hs_path_from_filename(config->directory_path,
   1300                                               dname_client_pubkeys);
   1301  if (BUG(hs_check_service_private_dir(get_options()->User,
   1302                                       client_keys_dir_path,
   1303                                       config->dir_group_readable, 1) < 0)) {
   1304    goto end;
   1305  }
   1306 
   1307  /* If the list of clients already exists, we must clear it first. */
   1308  if (config->clients) {
   1309    SMARTLIST_FOREACH(config->clients, hs_service_authorized_client_t *, p,
   1310                      service_authorized_client_free(p));
   1311    smartlist_free(config->clients);
   1312  }
   1313 
   1314  config->clients = smartlist_new();
   1315 
   1316  file_list = tor_listdir(client_keys_dir_path);
   1317  if (file_list == NULL) {
   1318    log_warn(LD_REND, "Client authorization directory %s can't be listed.",
   1319             client_keys_dir_path);
   1320    goto end;
   1321  }
   1322 
   1323  SMARTLIST_FOREACH_BEGIN(file_list, const char *, filename) {
   1324    hs_service_authorized_client_t *client = NULL;
   1325    log_info(LD_REND, "Loading a client authorization key file %s...",
   1326             filename);
   1327 
   1328    if (!client_filename_is_valid(filename)) {
   1329      log_warn(LD_REND, "Client authorization unrecognized filename %s. "
   1330                        "File must end in .auth. Ignoring.", filename);
   1331      continue;
   1332    }
   1333 
   1334    /* Create a full path for a file. */
   1335    client_key_file_path = hs_path_from_filename(client_keys_dir_path,
   1336                                                 filename);
   1337    client_key_str = read_file_to_str(client_key_file_path, 0, NULL);
   1338 
   1339    /* If we cannot read the file, continue with the next file. */
   1340    if (!client_key_str) {
   1341      log_warn(LD_REND, "Client authorization file %s can't be read. "
   1342                        "Corrupted or verify permission? Ignoring.",
   1343               client_key_file_path);
   1344      tor_free(client_key_file_path);
   1345      continue;
   1346    }
   1347    tor_free(client_key_file_path);
   1348 
   1349    client = parse_authorized_client(client_key_str);
   1350    /* Wipe and free immediately after using it. */
   1351    memwipe(client_key_str, 0, strlen(client_key_str));
   1352    tor_free(client_key_str);
   1353 
   1354    if (client) {
   1355      smartlist_add(config->clients, client);
   1356      log_info(LD_REND, "Loaded a client authorization key file %s.",
   1357               filename);
   1358    }
   1359 
   1360  } SMARTLIST_FOREACH_END(filename);
   1361 
   1362  /* Success. */
   1363  ret = 0;
   1364 end:
   1365  if (client_key_str) {
   1366    memwipe(client_key_str, 0, strlen(client_key_str));
   1367  }
   1368  if (file_list) {
   1369    SMARTLIST_FOREACH(file_list, char *, s, tor_free(s));
   1370    smartlist_free(file_list);
   1371  }
   1372  tor_free(client_key_str);
   1373  tor_free(client_key_file_path);
   1374  tor_free(client_keys_dir_path);
   1375  return ret;
   1376 }
   1377 
   1378 /** Release all storage held in <b>client</b>. */
   1379 void
   1380 service_authorized_client_free_(hs_service_authorized_client_t *client)
   1381 {
   1382  if (!client) {
   1383    return;
   1384  }
   1385  memwipe(&client->client_pk, 0, sizeof(client->client_pk));
   1386  tor_free(client);
   1387 }
   1388 
   1389 /** Free a given service descriptor object and all key material is wiped. */
   1390 STATIC void
   1391 service_descriptor_free_(hs_service_descriptor_t *desc)
   1392 {
   1393  if (!desc) {
   1394    return;
   1395  }
   1396  hs_descriptor_free(desc->desc);
   1397  memwipe(&desc->signing_kp, 0, sizeof(desc->signing_kp));
   1398  memwipe(&desc->blinded_kp, 0, sizeof(desc->blinded_kp));
   1399  /* Cleanup all intro points. */
   1400  digest256map_free(desc->intro_points.map, service_intro_point_free_void);
   1401  digestmap_free(desc->intro_points.failed_id, tor_free_);
   1402  if (desc->previous_hsdirs) {
   1403    SMARTLIST_FOREACH(desc->previous_hsdirs, char *, s, tor_free(s));
   1404    smartlist_free(desc->previous_hsdirs);
   1405  }
   1406  crypto_ope_free(desc->ope_cipher);
   1407  tor_free(desc);
   1408 }
   1409 
   1410 /** Return a newly allocated service descriptor object. */
   1411 STATIC hs_service_descriptor_t *
   1412 service_descriptor_new(void)
   1413 {
   1414  hs_service_descriptor_t *sdesc = tor_malloc_zero(sizeof(*sdesc));
   1415  sdesc->desc = tor_malloc_zero(sizeof(hs_descriptor_t));
   1416  /* Initialize the intro points map. */
   1417  sdesc->intro_points.map = digest256map_new();
   1418  sdesc->intro_points.failed_id = digestmap_new();
   1419  sdesc->previous_hsdirs = smartlist_new();
   1420  return sdesc;
   1421 }
   1422 
   1423 /** Allocate and return a deep copy of client. */
   1424 static hs_service_authorized_client_t *
   1425 service_authorized_client_dup(const hs_service_authorized_client_t *client)
   1426 {
   1427  hs_service_authorized_client_t *client_dup = NULL;
   1428 
   1429  tor_assert(client);
   1430 
   1431  client_dup = tor_malloc_zero(sizeof(hs_service_authorized_client_t));
   1432  /* Currently, the public key is the only component of
   1433   * hs_service_authorized_client_t. */
   1434  memcpy(client_dup->client_pk.public_key,
   1435         client->client_pk.public_key,
   1436         CURVE25519_PUBKEY_LEN);
   1437 
   1438  return client_dup;
   1439 }
   1440 
   1441 /** If two authorized clients are equal, return 0. If the first one should come
   1442 * before the second, return less than zero. If the first should come after
   1443 * the second, return greater than zero. */
   1444 static int
   1445 service_authorized_client_cmp(const hs_service_authorized_client_t *client1,
   1446                              const hs_service_authorized_client_t *client2)
   1447 {
   1448  tor_assert(client1);
   1449  tor_assert(client2);
   1450 
   1451  /* Currently, the public key is the only component of
   1452   * hs_service_authorized_client_t. */
   1453  return tor_memcmp(client1->client_pk.public_key,
   1454                    client2->client_pk.public_key,
   1455                    CURVE25519_PUBKEY_LEN);
   1456 }
   1457 
   1458 /** Helper for sorting authorized clients. */
   1459 static int
   1460 compare_service_authorzized_client_(const void **_a, const void **_b)
   1461 {
   1462  const hs_service_authorized_client_t *a = *_a, *b = *_b;
   1463  return service_authorized_client_cmp(a, b);
   1464 }
   1465 
   1466 /** If the list of hs_service_authorized_client_t's is different between
   1467 * src and dst, return 1. Otherwise, return 0. */
   1468 STATIC int
   1469 service_authorized_client_config_equal(const hs_service_config_t *config1,
   1470                                       const hs_service_config_t *config2)
   1471 {
   1472  int ret = 0;
   1473  int i;
   1474  smartlist_t *sl1 = smartlist_new();
   1475  smartlist_t *sl2 = smartlist_new();
   1476 
   1477  tor_assert(config1);
   1478  tor_assert(config2);
   1479  tor_assert(config1->clients);
   1480  tor_assert(config2->clients);
   1481 
   1482  /* If the number of clients is different, it is obvious that the list
   1483   * changes. */
   1484  if (smartlist_len(config1->clients) != smartlist_len(config2->clients)) {
   1485    goto done;
   1486  }
   1487 
   1488  /* We do not want to mutate config1 and config2, so we will duplicate both
   1489   * entire client lists here. */
   1490  SMARTLIST_FOREACH(config1->clients,
   1491              hs_service_authorized_client_t *, client,
   1492              smartlist_add(sl1, service_authorized_client_dup(client)));
   1493 
   1494  SMARTLIST_FOREACH(config2->clients,
   1495              hs_service_authorized_client_t *, client,
   1496              smartlist_add(sl2, service_authorized_client_dup(client)));
   1497 
   1498  smartlist_sort(sl1, compare_service_authorzized_client_);
   1499  smartlist_sort(sl2, compare_service_authorzized_client_);
   1500 
   1501  for (i = 0; i < smartlist_len(sl1); i++) {
   1502    /* If the clients at index i in both lists differ, the whole configs
   1503     * differ. */
   1504    if (service_authorized_client_cmp(smartlist_get(sl1, i),
   1505                                      smartlist_get(sl2, i))) {
   1506      goto done;
   1507    }
   1508  }
   1509 
   1510  /* Success. */
   1511  ret = 1;
   1512 
   1513 done:
   1514  if (sl1) {
   1515    SMARTLIST_FOREACH(sl1, hs_service_authorized_client_t *, p,
   1516                      service_authorized_client_free(p));
   1517    smartlist_free(sl1);
   1518  }
   1519  if (sl2) {
   1520    SMARTLIST_FOREACH(sl2, hs_service_authorized_client_t *, p,
   1521                      service_authorized_client_free(p));
   1522    smartlist_free(sl2);
   1523  }
   1524  return ret;
   1525 }
   1526 
   1527 /** Move descriptor(s) from the src service to the dst service and modify their
   1528 * content if necessary. We do this during SIGHUP when we re-create our
   1529 * hidden services. */
   1530 static void
   1531 move_descriptors(hs_service_t *src, hs_service_t *dst)
   1532 {
   1533  tor_assert(src);
   1534  tor_assert(dst);
   1535 
   1536  if (src->desc_current) {
   1537    /* Nothing should be there, but clean it up just in case */
   1538    if (BUG(dst->desc_current)) {
   1539      service_descriptor_free(dst->desc_current);
   1540    }
   1541    dst->desc_current = src->desc_current;
   1542    src->desc_current = NULL;
   1543  }
   1544 
   1545  if (src->desc_next) {
   1546    /* Nothing should be there, but clean it up just in case */
   1547    if (BUG(dst->desc_next)) {
   1548      service_descriptor_free(dst->desc_next);
   1549    }
   1550    dst->desc_next = src->desc_next;
   1551    src->desc_next = NULL;
   1552  }
   1553 
   1554  /* If the client authorization changes, we must rebuild the superencrypted
   1555   * section and republish the descriptors. */
   1556  int client_auth_changed =
   1557    !service_authorized_client_config_equal(&src->config, &dst->config);
   1558  if (client_auth_changed && dst->desc_current) {
   1559    /* We have to clear the superencrypted content first. */
   1560    hs_desc_superencrypted_data_free_contents(
   1561                                &dst->desc_current->desc->superencrypted_data);
   1562    if (build_service_desc_superencrypted(dst, dst->desc_current) < 0) {
   1563      goto err;
   1564    }
   1565    service_desc_schedule_upload(dst->desc_current, time(NULL), 1);
   1566  }
   1567  if (client_auth_changed && dst->desc_next) {
   1568    /* We have to clear the superencrypted content first. */
   1569    hs_desc_superencrypted_data_free_contents(
   1570                                &dst->desc_next->desc->superencrypted_data);
   1571    if (build_service_desc_superencrypted(dst, dst->desc_next) < 0) {
   1572      goto err;
   1573    }
   1574    service_desc_schedule_upload(dst->desc_next, time(NULL), 1);
   1575  }
   1576 
   1577  return;
   1578 
   1579 err:
   1580  /* If there is an error, free all descriptors to make it clean and generate
   1581   * them later. */
   1582  service_descriptor_free(dst->desc_current);
   1583  service_descriptor_free(dst->desc_next);
   1584 }
   1585 
   1586 /** From the given service, remove all expired failing intro points for each
   1587 * descriptor. */
   1588 static void
   1589 remove_expired_failing_intro(hs_service_t *service, time_t now)
   1590 {
   1591  tor_assert(service);
   1592 
   1593  /* For both descriptors, cleanup the failing intro points list. */
   1594  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   1595    DIGESTMAP_FOREACH_MODIFY(desc->intro_points.failed_id, key, time_t *, t) {
   1596      time_t failure_time = *t;
   1597      if ((failure_time + INTRO_CIRC_RETRY_PERIOD) <= now) {
   1598        MAP_DEL_CURRENT(key);
   1599        tor_free(t);
   1600      }
   1601    } DIGESTMAP_FOREACH_END;
   1602  } FOR_EACH_DESCRIPTOR_END;
   1603 }
   1604 
   1605 /** For the given descriptor desc, put all node_t object found from its failing
   1606 * intro point list and put them in the given node_list. */
   1607 static void
   1608 setup_intro_point_exclude_list(const hs_service_descriptor_t *desc,
   1609                               smartlist_t *node_list)
   1610 {
   1611  tor_assert(desc);
   1612  tor_assert(node_list);
   1613 
   1614  DIGESTMAP_FOREACH(desc->intro_points.failed_id, key, time_t *, t) {
   1615    (void) t; /* Make gcc happy. */
   1616    const node_t *node = node_get_by_id(key);
   1617    if (node) {
   1618      smartlist_add(node_list, (void *) node);
   1619    }
   1620  } DIGESTMAP_FOREACH_END;
   1621 }
   1622 
   1623 /** For the given failing intro point ip, we add its time of failure to the
   1624 * failed map and index it by identity digest (legacy ID) in the descriptor
   1625 * desc failed id map. */
   1626 static void
   1627 remember_failing_intro_point(const hs_service_intro_point_t *ip,
   1628                             hs_service_descriptor_t *desc, time_t now)
   1629 {
   1630  time_t *time_of_failure, *prev_ptr;
   1631  const link_specifier_t *legacy_ls;
   1632 
   1633  tor_assert(ip);
   1634  tor_assert(desc);
   1635 
   1636  time_of_failure = tor_malloc_zero(sizeof(time_t));
   1637  *time_of_failure = now;
   1638  legacy_ls = get_link_spec_by_type(ip, LS_LEGACY_ID);
   1639  tor_assert(legacy_ls);
   1640  prev_ptr = digestmap_set(
   1641    desc->intro_points.failed_id,
   1642    (const char *) link_specifier_getconstarray_un_legacy_id(legacy_ls),
   1643    time_of_failure);
   1644  tor_free(prev_ptr);
   1645 }
   1646 
   1647 /** Using a given descriptor signing keypair signing_kp, a service intro point
   1648 * object ip and the time now, setup the content of an already allocated
   1649 * descriptor intro desc_ip.
   1650 *
   1651 * Return 0 on success else a negative value. */
   1652 static int
   1653 setup_desc_intro_point(const ed25519_keypair_t *signing_kp,
   1654                       const hs_service_intro_point_t *ip,
   1655                       time_t now, hs_desc_intro_point_t *desc_ip)
   1656 {
   1657  int ret = -1;
   1658  time_t nearest_hour = now - (now % 3600);
   1659 
   1660  tor_assert(signing_kp);
   1661  tor_assert(ip);
   1662  tor_assert(desc_ip);
   1663 
   1664  /* Copy the onion key. */
   1665  memcpy(&desc_ip->onion_key, &ip->onion_key, sizeof(desc_ip->onion_key));
   1666 
   1667  /* Key and certificate material. */
   1668  desc_ip->auth_key_cert = tor_cert_create_ed25519(signing_kp,
   1669                                           CERT_TYPE_AUTH_HS_IP_KEY,
   1670                                           &ip->auth_key_kp.pubkey,
   1671                                           nearest_hour,
   1672                                           HS_DESC_CERT_LIFETIME,
   1673                                           CERT_FLAG_INCLUDE_SIGNING_KEY);
   1674  if (desc_ip->auth_key_cert == NULL) {
   1675    log_warn(LD_REND, "Unable to create intro point auth-key certificate");
   1676    goto done;
   1677  }
   1678 
   1679  /* Copy link specifier(s). */
   1680  SMARTLIST_FOREACH_BEGIN(ip->base.link_specifiers,
   1681                          const link_specifier_t *, ls) {
   1682    if (BUG(!ls)) {
   1683      goto done;
   1684    }
   1685    link_specifier_t *copy = link_specifier_dup(ls);
   1686    if (BUG(!copy)) {
   1687      goto done;
   1688    }
   1689    smartlist_add(desc_ip->link_specifiers, copy);
   1690  } SMARTLIST_FOREACH_END(ls);
   1691 
   1692  /* For a legacy intro point, we'll use an RSA/ed cross certificate. */
   1693  if (ip->base.is_only_legacy) {
   1694    desc_ip->legacy.key = crypto_pk_dup_key(ip->legacy_key);
   1695    /* Create cross certification cert. */
   1696    ssize_t cert_len = tor_make_rsa_ed25519_crosscert(
   1697                                    &signing_kp->pubkey,
   1698                                    desc_ip->legacy.key,
   1699                                    nearest_hour + HS_DESC_CERT_LIFETIME,
   1700                                    &desc_ip->legacy.cert.encoded);
   1701    if (cert_len < 0) {
   1702      log_warn(LD_REND, "Unable to create enc key legacy cross cert.");
   1703      goto done;
   1704    }
   1705    desc_ip->legacy.cert.len = cert_len;
   1706  }
   1707 
   1708  /* Encryption key and its cross certificate. */
   1709  {
   1710    ed25519_public_key_t ed25519_pubkey;
   1711 
   1712    /* Use the public curve25519 key. */
   1713    memcpy(&desc_ip->enc_key, &ip->enc_key_kp.pubkey,
   1714           sizeof(desc_ip->enc_key));
   1715    /* The following can't fail. */
   1716    ed25519_public_key_from_curve25519_public_key(&ed25519_pubkey,
   1717                                                  &ip->enc_key_kp.pubkey,
   1718                                                  0);
   1719    desc_ip->enc_key_cert = tor_cert_create_ed25519(signing_kp,
   1720                                            CERT_TYPE_CROSS_HS_IP_KEYS,
   1721                                            &ed25519_pubkey, nearest_hour,
   1722                                            HS_DESC_CERT_LIFETIME,
   1723                                            CERT_FLAG_INCLUDE_SIGNING_KEY);
   1724    if (desc_ip->enc_key_cert == NULL) {
   1725      log_warn(LD_REND, "Unable to create enc key curve25519 cross cert.");
   1726      goto done;
   1727    }
   1728  }
   1729  /* Success. */
   1730  ret = 0;
   1731 
   1732 done:
   1733  return ret;
   1734 }
   1735 
   1736 /** Using the given descriptor from the given service, build the descriptor
   1737 * intro point list so we can then encode the descriptor for publication. This
   1738 * function does not pick intro points, they have to be in the descriptor
   1739 * current map. Cryptographic material (keys) must be initialized in the
   1740 * descriptor for this function to make sense. */
   1741 static void
   1742 build_desc_intro_points(const hs_service_t *service,
   1743                        hs_service_descriptor_t *desc, time_t now)
   1744 {
   1745  hs_desc_encrypted_data_t *encrypted;
   1746 
   1747  tor_assert(service);
   1748  tor_assert(desc);
   1749 
   1750  /* Ease our life. */
   1751  encrypted = &desc->desc->encrypted_data;
   1752  /* Cleanup intro points, we are about to set them from scratch. */
   1753  hs_descriptor_clear_intro_points(desc->desc);
   1754 
   1755  DIGEST256MAP_FOREACH(desc->intro_points.map, key,
   1756                       const hs_service_intro_point_t *, ip) {
   1757    if (!hs_circ_service_get_established_intro_circ(ip)) {
   1758      /* Ignore un-established intro points. They can linger in that list
   1759       * because their circuit has not opened and they haven't been removed
   1760       * yet even though we have enough intro circuits.
   1761       *
   1762       * Due to #31561, it can stay in that list until rotation so this check
   1763       * prevents to publish an intro point without a circuit. */
   1764      continue;
   1765    }
   1766    hs_desc_intro_point_t *desc_ip = hs_desc_intro_point_new();
   1767    if (setup_desc_intro_point(&desc->signing_kp, ip, now, desc_ip) < 0) {
   1768      hs_desc_intro_point_free(desc_ip);
   1769      continue;
   1770    }
   1771    /* We have a valid descriptor intro point. Add it to the list. */
   1772    smartlist_add(encrypted->intro_points, desc_ip);
   1773  } DIGEST256MAP_FOREACH_END;
   1774 }
   1775 
   1776 /** Build the descriptor signing key certificate. */
   1777 static void
   1778 build_desc_signing_key_cert(hs_service_descriptor_t *desc, time_t now)
   1779 {
   1780  hs_desc_plaintext_data_t *plaintext;
   1781 
   1782  tor_assert(desc);
   1783  tor_assert(desc->desc);
   1784 
   1785  /* Ease our life a bit. */
   1786  plaintext = &desc->desc->plaintext_data;
   1787 
   1788  /* Get rid of what we have right now. */
   1789  tor_cert_free(plaintext->signing_key_cert);
   1790 
   1791  /* Fresh certificate for the signing key. */
   1792  plaintext->signing_key_cert =
   1793    tor_cert_create_ed25519(&desc->blinded_kp, CERT_TYPE_SIGNING_HS_DESC,
   1794                    &desc->signing_kp.pubkey, now, HS_DESC_CERT_LIFETIME,
   1795                    CERT_FLAG_INCLUDE_SIGNING_KEY);
   1796  /* If the cert creation fails, the descriptor encoding will fail and thus
   1797   * ultimately won't be uploaded. We'll get a stack trace to help us learn
   1798   * where the call came from and the tor_cert_create_ed25519() will log the
   1799   * error. */
   1800  tor_assert_nonfatal(plaintext->signing_key_cert);
   1801 }
   1802 
   1803 /** Populate the descriptor encrypted section from the given service object.
   1804 * This will generate a valid list of introduction points that can be used
   1805 * after for circuit creation. Return 0 on success else -1 on error. */
   1806 static int
   1807 build_service_desc_encrypted(const hs_service_t *service,
   1808                             hs_service_descriptor_t *desc)
   1809 {
   1810  hs_desc_encrypted_data_t *encrypted;
   1811 
   1812  tor_assert(service);
   1813  tor_assert(desc);
   1814 
   1815  encrypted = &desc->desc->encrypted_data;
   1816  encrypted->sendme_inc = congestion_control_sendme_inc();
   1817 
   1818  encrypted->create2_ntor = 1;
   1819  encrypted->single_onion_service = service->config.is_single_onion;
   1820 
   1821  /* Setup introduction points from what we have in the service. */
   1822  if (encrypted->intro_points == NULL) {
   1823    encrypted->intro_points = smartlist_new();
   1824  }
   1825  /* We do NOT build introduction point yet, we only do that once the circuit
   1826   * have been opened. Until we have the right number of introduction points,
   1827   * we do not encode anything in the descriptor. */
   1828 
   1829  /* XXX: Support client authorization (#20700). */
   1830  encrypted->intro_auth_types = NULL;
   1831  return 0;
   1832 }
   1833 
   1834 /** Populate the descriptor superencrypted section from the given service
   1835 * object. This will generate a valid list of hs_desc_authorized_client_t
   1836 * of clients that are authorized to use the service. Return 0 on success
   1837 * else -1 on error. */
   1838 static int
   1839 build_service_desc_superencrypted(const hs_service_t *service,
   1840                                  hs_service_descriptor_t *desc)
   1841 {
   1842  const hs_service_config_t *config;
   1843  int i;
   1844  hs_desc_superencrypted_data_t *superencrypted;
   1845 
   1846  tor_assert(service);
   1847  tor_assert(desc);
   1848 
   1849  superencrypted = &desc->desc->superencrypted_data;
   1850  config = &service->config;
   1851 
   1852  /* The ephemeral key pair is already generated, so this should not give
   1853   * an error. */
   1854  if (BUG(!curve25519_public_key_is_ok(&desc->auth_ephemeral_kp.pubkey))) {
   1855    return -1;
   1856  }
   1857  memcpy(&superencrypted->auth_ephemeral_pubkey,
   1858         &desc->auth_ephemeral_kp.pubkey,
   1859         sizeof(curve25519_public_key_t));
   1860 
   1861  /* Test that subcred is not zero because we might use it below */
   1862  if (BUG(fast_mem_is_zero((char*)desc->desc->subcredential.subcred,
   1863                           DIGEST256_LEN))) {
   1864    return -1;
   1865  }
   1866 
   1867  /* Create a smartlist to store clients */
   1868  superencrypted->clients = smartlist_new();
   1869 
   1870  /* We do not need to build the desc authorized client if the client
   1871   * authorization is disabled */
   1872  if (is_client_auth_enabled(service)) {
   1873    SMARTLIST_FOREACH_BEGIN(config->clients,
   1874                            hs_service_authorized_client_t *, client) {
   1875      hs_desc_authorized_client_t *desc_client;
   1876      desc_client = tor_malloc_zero(sizeof(hs_desc_authorized_client_t));
   1877 
   1878      /* Prepare the client for descriptor and then add to the list in the
   1879       * superencrypted part of the descriptor */
   1880      hs_desc_build_authorized_client(&desc->desc->subcredential,
   1881                                      &client->client_pk,
   1882                                      &desc->auth_ephemeral_kp.seckey,
   1883                                      desc->descriptor_cookie, desc_client);
   1884      smartlist_add(superencrypted->clients, desc_client);
   1885 
   1886    } SMARTLIST_FOREACH_END(client);
   1887  }
   1888 
   1889  /* We cannot let the number of auth-clients to be zero, so we need to
   1890   * make it be 16. If it is already a multiple of 16, we do not need to
   1891   * do anything. Otherwise, add the additional ones to make it a
   1892   * multiple of 16. */
   1893  int num_clients = smartlist_len(superencrypted->clients);
   1894  int num_clients_to_add;
   1895  if (num_clients == 0) {
   1896    num_clients_to_add = HS_DESC_AUTH_CLIENT_MULTIPLE;
   1897  } else if (num_clients % HS_DESC_AUTH_CLIENT_MULTIPLE == 0) {
   1898    num_clients_to_add = 0;
   1899  } else {
   1900    num_clients_to_add =
   1901      HS_DESC_AUTH_CLIENT_MULTIPLE
   1902      - (num_clients % HS_DESC_AUTH_CLIENT_MULTIPLE);
   1903  }
   1904 
   1905  for (i = 0; i < num_clients_to_add; i++) {
   1906    hs_desc_authorized_client_t *desc_client =
   1907      hs_desc_build_fake_authorized_client();
   1908    smartlist_add(superencrypted->clients, desc_client);
   1909  }
   1910 
   1911  /* Shuffle the list to prevent the client know the position in the
   1912   * config. */
   1913  smartlist_shuffle(superencrypted->clients);
   1914 
   1915  return 0;
   1916 }
   1917 
   1918 /** Populate the descriptor plaintext section from the given service object.
   1919 * The caller must make sure that the keys in the descriptors are valid that
   1920 * is are non-zero. This can't fail. */
   1921 static void
   1922 build_service_desc_plaintext(const hs_service_t *service,
   1923                             hs_service_descriptor_t *desc)
   1924 {
   1925  hs_desc_plaintext_data_t *plaintext;
   1926 
   1927  tor_assert(service);
   1928  tor_assert(desc);
   1929  tor_assert(!fast_mem_is_zero((char *) &desc->blinded_kp,
   1930                              sizeof(desc->blinded_kp)));
   1931  tor_assert(!fast_mem_is_zero((char *) &desc->signing_kp,
   1932                              sizeof(desc->signing_kp)));
   1933 
   1934  /* Set the subcredential. */
   1935  hs_get_subcredential(&service->keys.identity_pk, &desc->blinded_kp.pubkey,
   1936                       &desc->desc->subcredential);
   1937 
   1938  plaintext = &desc->desc->plaintext_data;
   1939 
   1940  plaintext->version = service->config.version;
   1941  plaintext->lifetime_sec = HS_DESC_DEFAULT_LIFETIME;
   1942  /* Copy public key material to go in the descriptor. */
   1943  ed25519_pubkey_copy(&plaintext->signing_pubkey, &desc->signing_kp.pubkey);
   1944  ed25519_pubkey_copy(&plaintext->blinded_pubkey, &desc->blinded_kp.pubkey);
   1945 
   1946  /* Create the signing key certificate. This will be updated before each
   1947   * upload but we create it here so we don't complexify our unit tests. */
   1948  build_desc_signing_key_cert(desc, approx_time());
   1949 }
   1950 
   1951 /** Compute the descriptor's OPE cipher for encrypting revision counters. */
   1952 static crypto_ope_t *
   1953 generate_ope_cipher_for_desc(const hs_service_descriptor_t *hs_desc)
   1954 {
   1955  /* Compute OPE key as H("rev-counter-generation" | blinded privkey) */
   1956  uint8_t key[DIGEST256_LEN];
   1957  crypto_digest_t *digest = crypto_digest256_new(DIGEST_SHA3_256);
   1958  const char ope_key_prefix[] = "rev-counter-generation";
   1959  const ed25519_secret_key_t *eph_privkey = &hs_desc->blinded_kp.seckey;
   1960  crypto_digest_add_bytes(digest, ope_key_prefix, sizeof(ope_key_prefix));
   1961  crypto_digest_add_bytes(digest, (char*)eph_privkey->seckey,
   1962                          sizeof(eph_privkey->seckey));
   1963  crypto_digest_get_digest(digest, (char *)key, sizeof(key));
   1964  crypto_digest_free(digest);
   1965 
   1966  return crypto_ope_new(key);
   1967 }
   1968 
   1969 /** For the given service and descriptor object, create the key material which
   1970 * is the blinded keypair, the descriptor signing keypair, the ephemeral
   1971 * keypair, and the descriptor cookie. Return 0 on success else -1 on error
   1972 * where the generated keys MUST be ignored. */
   1973 static int
   1974 build_service_desc_keys(const hs_service_t *service,
   1975                        hs_service_descriptor_t *desc)
   1976 {
   1977  int ret = -1;
   1978  ed25519_keypair_t kp;
   1979 
   1980  tor_assert(desc);
   1981  tor_assert(!fast_mem_is_zero((char *) &service->keys.identity_pk,
   1982             ED25519_PUBKEY_LEN));
   1983 
   1984  /* XXX: Support offline key feature (#18098). */
   1985 
   1986  /* Copy the identity keys to the keypair so we can use it to create the
   1987   * blinded key. */
   1988  memcpy(&kp.pubkey, &service->keys.identity_pk, sizeof(kp.pubkey));
   1989  memcpy(&kp.seckey, &service->keys.identity_sk, sizeof(kp.seckey));
   1990  /* Build blinded keypair for this time period. */
   1991  hs_build_blinded_keypair(&kp, NULL, 0, desc->time_period_num,
   1992                           &desc->blinded_kp);
   1993  /* Let's not keep too much traces of our keys in memory. */
   1994  memwipe(&kp, 0, sizeof(kp));
   1995 
   1996  /* Compute the OPE cipher struct (it's tied to the current blinded key) */
   1997  log_info(LD_GENERAL,
   1998           "Getting OPE for TP#%u", (unsigned) desc->time_period_num);
   1999  tor_assert_nonfatal(!desc->ope_cipher);
   2000  desc->ope_cipher = generate_ope_cipher_for_desc(desc);
   2001 
   2002  /* No need for extra strong, this is a temporary key only for this
   2003   * descriptor. Nothing long term. */
   2004  if (ed25519_keypair_generate(&desc->signing_kp, 0) < 0) {
   2005    log_warn(LD_REND, "Can't generate descriptor signing keypair for "
   2006                      "service %s",
   2007             safe_str_client(service->onion_address));
   2008    goto end;
   2009  }
   2010 
   2011  /* No need for extra strong, this is a temporary key only for this
   2012   * descriptor. Nothing long term. */
   2013  if (curve25519_keypair_generate(&desc->auth_ephemeral_kp, 0) < 0) {
   2014    log_warn(LD_REND, "Can't generate auth ephemeral keypair for "
   2015                      "service %s",
   2016             safe_str_client(service->onion_address));
   2017    goto end;
   2018  }
   2019 
   2020  /* Random descriptor cookie to be used as a part of a key to encrypt the
   2021   * descriptor, only if the client auth is enabled will it be used. */
   2022  crypto_strongest_rand(desc->descriptor_cookie,
   2023                        sizeof(desc->descriptor_cookie));
   2024 
   2025  /* Success. */
   2026  ret = 0;
   2027 end:
   2028  return ret;
   2029 }
   2030 
   2031 /** Given a service and the current time, build a descriptor for the service.
   2032 * This function does not pick introduction point, this needs to be done by
   2033 * the update function. On success, desc_out will point to the newly allocated
   2034 * descriptor object.
   2035 *
   2036 * This can error if we are unable to create keys or certificate. */
   2037 static void
   2038 build_service_descriptor(hs_service_t *service, uint64_t time_period_num,
   2039                         hs_service_descriptor_t **desc_out)
   2040 {
   2041  char *encoded_desc;
   2042  hs_service_descriptor_t *desc;
   2043 
   2044  tor_assert(service);
   2045  tor_assert(desc_out);
   2046 
   2047  desc = service_descriptor_new();
   2048 
   2049  /* Set current time period */
   2050  desc->time_period_num = time_period_num;
   2051 
   2052  /* Create the needed keys so we can setup the descriptor content. */
   2053  if (build_service_desc_keys(service, desc) < 0) {
   2054    goto err;
   2055  }
   2056  /* Setup plaintext descriptor content. */
   2057  build_service_desc_plaintext(service, desc);
   2058 
   2059  /* Setup superencrypted descriptor content. */
   2060  if (build_service_desc_superencrypted(service, desc) < 0) {
   2061    goto err;
   2062  }
   2063  /* Setup encrypted descriptor content. */
   2064  if (build_service_desc_encrypted(service, desc) < 0) {
   2065    goto err;
   2066  }
   2067 
   2068  /* Let's make sure that we've created a descriptor that can actually be
   2069   * encoded properly. This function also checks if the encoded output is
   2070   * decodable after. */
   2071  if (BUG(service_encode_descriptor(service, desc, &desc->signing_kp,
   2072                                    &encoded_desc) < 0)) {
   2073    goto err;
   2074  }
   2075  tor_free(encoded_desc);
   2076 
   2077  /* Assign newly built descriptor to the next slot. */
   2078  *desc_out = desc;
   2079 
   2080  /* Fire a CREATED control port event. */
   2081  hs_control_desc_event_created(service->onion_address,
   2082                                &desc->blinded_kp.pubkey);
   2083 
   2084  /* If we are an onionbalance instance, we refresh our keys when we rotate
   2085   * descriptors. */
   2086  hs_ob_refresh_keys(service);
   2087 
   2088  return;
   2089 
   2090 err:
   2091  service_descriptor_free(desc);
   2092 }
   2093 
   2094 /** Build both descriptors for the given service that has just booted up.
   2095 * Because it's a special case, it deserves its special function ;). */
   2096 static void
   2097 build_descriptors_for_new_service(hs_service_t *service, time_t now)
   2098 {
   2099  uint64_t current_desc_tp, next_desc_tp;
   2100 
   2101  tor_assert(service);
   2102  /* These are the conditions for a new service. */
   2103  tor_assert(!service->desc_current);
   2104  tor_assert(!service->desc_next);
   2105 
   2106  /*
   2107   * +------------------------------------------------------------------+
   2108   * |                                                                  |
   2109   * | 00:00      12:00       00:00       12:00       00:00       12:00 |
   2110   * | SRV#1      TP#1        SRV#2       TP#2        SRV#3       TP#3  |
   2111   * |                                                                  |
   2112   * |  $==========|-----------$===========|-----------$===========|    |
   2113   * |                             ^         ^                          |
   2114   * |                             A         B                          |
   2115   * +------------------------------------------------------------------+
   2116   *
   2117   * Case A: The service boots up before a new time period, the current time
   2118   * period is thus TP#1 and the next is TP#2 which for both we have access to
   2119   * their SRVs.
   2120   *
   2121   * Case B: The service boots up inside TP#2, we can't use the TP#3 for the
   2122   * next descriptor because we don't have the SRV#3 so the current should be
   2123   * TP#1 and next TP#2.
   2124   */
   2125 
   2126  if (hs_in_period_between_tp_and_srv(NULL, now)) {
   2127    /* Case B from the above, inside of the new time period. */
   2128    current_desc_tp = hs_get_previous_time_period_num(0); /* TP#1 */
   2129    next_desc_tp = hs_get_time_period_num(0);             /* TP#2 */
   2130  } else {
   2131    /* Case A from the above, outside of the new time period. */
   2132    current_desc_tp = hs_get_time_period_num(0);    /* TP#1 */
   2133    next_desc_tp = hs_get_next_time_period_num(0);  /* TP#2 */
   2134  }
   2135 
   2136  /* Build descriptors. */
   2137  build_service_descriptor(service, current_desc_tp, &service->desc_current);
   2138  build_service_descriptor(service, next_desc_tp, &service->desc_next);
   2139  log_info(LD_REND, "Hidden service %s has just started. Both descriptors "
   2140                    "built. Now scheduled for upload.",
   2141           safe_str_client(service->onion_address));
   2142 }
   2143 
   2144 /** Build descriptors for each service if needed. There are conditions to build
   2145 * a descriptor which are details in the function. */
   2146 STATIC void
   2147 build_all_descriptors(time_t now)
   2148 {
   2149  FOR_EACH_SERVICE_BEGIN(service) {
   2150 
   2151    /* A service booting up will have both descriptors to NULL. No other cases
   2152     * makes both descriptor non existent. */
   2153    if (service->desc_current == NULL && service->desc_next == NULL) {
   2154      build_descriptors_for_new_service(service, now);
   2155      continue;
   2156    }
   2157 
   2158    /* Reaching this point means we are past bootup so at runtime. We should
   2159     * *never* have an empty current descriptor. If the next descriptor is
   2160     * empty, we'll try to build it for the next time period. This only
   2161     * happens when we rotate meaning that we are guaranteed to have a new SRV
   2162     * at that point for the next time period. */
   2163    if (BUG(service->desc_current == NULL)) {
   2164      continue;
   2165    }
   2166 
   2167    if (service->desc_next == NULL) {
   2168      build_service_descriptor(service, hs_get_next_time_period_num(0),
   2169                               &service->desc_next);
   2170      log_info(LD_REND, "Hidden service %s next descriptor successfully "
   2171                        "built. Now scheduled for upload.",
   2172               safe_str_client(service->onion_address));
   2173    }
   2174  } FOR_EACH_DESCRIPTOR_END;
   2175 }
   2176 
   2177 /** Randomly pick a node to become an introduction point but not present in the
   2178 * given exclude_nodes list. The chosen node is put in the exclude list
   2179 * regardless of success or not because in case of failure, the node is simply
   2180 * unusable from that point on.
   2181 *
   2182 * If direct_conn is set, try to pick a node that our local firewall/policy
   2183 * allows us to connect to directly. If we can't find any, return NULL.
   2184 * This function supports selecting dual-stack nodes for direct single onion
   2185 * service IPv6 connections. But it does not send IPv6 addresses in link
   2186 * specifiers. (Current clients don't use IPv6 addresses to extend, and
   2187 * direct client connections to intro points are not supported.)
   2188 *
   2189 * Return a newly allocated service intro point ready to be used for encoding.
   2190 * Return NULL on error. */
   2191 static hs_service_intro_point_t *
   2192 pick_intro_point(unsigned int direct_conn, smartlist_t *exclude_nodes)
   2193 {
   2194  const or_options_t *options = get_options();
   2195  const node_t *node;
   2196  hs_service_intro_point_t *ip = NULL;
   2197  /* Normal 3-hop introduction point flags. */
   2198  router_crn_flags_t flags = CRN_NEED_UPTIME | CRN_NEED_DESC | CRN_FOR_HS;
   2199  /* Single onion flags. */
   2200  router_crn_flags_t direct_flags = flags | CRN_PREF_ADDR | CRN_DIRECT_CONN;
   2201 
   2202  node = router_choose_random_node(exclude_nodes, options->ExcludeNodes,
   2203                                   direct_conn ? direct_flags : flags);
   2204 
   2205  /* If we are in single onion mode, retry node selection for a 3-hop
   2206   * path */
   2207  if (direct_conn && !node) {
   2208    log_info(LD_REND,
   2209             "Unable to find an intro point that we can connect to "
   2210             "directly, falling back to a 3-hop path.");
   2211    node = router_choose_random_node(exclude_nodes, options->ExcludeNodes,
   2212                                     flags);
   2213  }
   2214 
   2215  if (!node) {
   2216    goto err;
   2217  }
   2218 
   2219  /* We have a suitable node, add it to the exclude list. We do this *before*
   2220   * we can validate the extend information because even in case of failure,
   2221   * we don't want to use that node anymore. */
   2222  smartlist_add(exclude_nodes, (void *) node);
   2223 
   2224  /* Create our objects and populate them with the node information. */
   2225  ip = service_intro_point_new(node);
   2226 
   2227  if (ip == NULL) {
   2228    goto err;
   2229  }
   2230 
   2231  log_info(LD_REND, "Picked intro point: %s", node_describe(node));
   2232  return ip;
   2233 err:
   2234  service_intro_point_free(ip);
   2235  return NULL;
   2236 }
   2237 
   2238 /** For a given descriptor from the given service, pick any needed intro points
   2239 * and update the current map with those newly picked intro points. Return the
   2240 * number node that might have been added to the descriptor current map. */
   2241 static unsigned int
   2242 pick_needed_intro_points(hs_service_t *service,
   2243                         hs_service_descriptor_t *desc)
   2244 {
   2245  int i = 0, num_needed_ip;
   2246  smartlist_t *exclude_nodes = smartlist_new();
   2247 
   2248  tor_assert(service);
   2249  tor_assert(desc);
   2250 
   2251  /* Compute how many intro points we actually need to open. */
   2252  num_needed_ip = service->config.num_intro_points -
   2253                  digest256map_size(desc->intro_points.map);
   2254  if (BUG(num_needed_ip < 0)) {
   2255    /* Let's not make tor freak out here and just skip this. */
   2256    goto done;
   2257  }
   2258 
   2259  /* We want to end up with config.num_intro_points intro points, but if we
   2260   * have no intro points at all (chances are they all cycled or we are
   2261   * starting up), we launch get_intro_point_num_extra() extra circuits and
   2262   * use the first config.num_intro_points that complete. See proposal #155,
   2263   * section 4 for the rationale of this which is purely for performance.
   2264   *
   2265   * The ones after the first config.num_intro_points will be converted to
   2266   * 'General' internal circuits and then we'll drop them from the list of
   2267   * intro points. */
   2268  if (digest256map_size(desc->intro_points.map) == 0) {
   2269    num_needed_ip += get_intro_point_num_extra();
   2270  }
   2271 
   2272  /* Build an exclude list of nodes of our intro point(s). The expiring intro
   2273   * points are OK to pick again because this is after all a concept of round
   2274   * robin so they are considered valid nodes to pick again. */
   2275  DIGEST256MAP_FOREACH(desc->intro_points.map, key,
   2276                       hs_service_intro_point_t *, ip) {
   2277    const node_t *intro_node = get_node_from_intro_point(ip);
   2278    if (intro_node) {
   2279      smartlist_add(exclude_nodes, (void*)intro_node);
   2280    }
   2281  } DIGEST256MAP_FOREACH_END;
   2282  /* Also, add the failing intro points that our descriptor encounteered in
   2283   * the exclude node list. */
   2284  setup_intro_point_exclude_list(desc, exclude_nodes);
   2285 
   2286  for (i = 0; i < num_needed_ip; i++) {
   2287    hs_service_intro_point_t *ip;
   2288 
   2289    /* This function will add the picked intro point node to the exclude nodes
   2290     * list so we don't pick the same one at the next iteration. */
   2291    ip = pick_intro_point(service->config.is_single_onion, exclude_nodes);
   2292    if (ip == NULL) {
   2293      /* If we end up unable to pick an introduction point it is because we
   2294       * can't find suitable node and calling this again is highly unlikely to
   2295       * give us a valid node all of the sudden. */
   2296      log_info(LD_REND, "Unable to find a suitable node to be an "
   2297                        "introduction point for service %s.",
   2298               safe_str_client(service->onion_address));
   2299      goto done;
   2300    }
   2301 
   2302    /* Save a copy of the specific version of the blinded ID that we
   2303     * use to reach this intro point. Needed to validate proof-of-work
   2304     * solutions that are bound to this specific service. */
   2305    tor_assert(desc->desc);
   2306    ed25519_pubkey_copy(&ip->blinded_id,
   2307                        &desc->desc->plaintext_data.blinded_pubkey);
   2308 
   2309    /* Valid intro point object, add it to the descriptor current map. */
   2310    service_intro_point_add(desc->intro_points.map, ip);
   2311  }
   2312  /* We've successfully picked all our needed intro points thus none are
   2313   * missing which will tell our upload process to expect the number of
   2314   * circuits to be the number of configured intro points circuits and not the
   2315   * number of intro points object that we have. */
   2316  desc->missing_intro_points = 0;
   2317 
   2318  /* Success. */
   2319 done:
   2320  /* We don't have ownership of the node_t object in this list. */
   2321  smartlist_free(exclude_nodes);
   2322  return i;
   2323 }
   2324 
   2325 /** Clear previous cached HSDirs in <b>desc</b>. */
   2326 static void
   2327 service_desc_clear_previous_hsdirs(hs_service_descriptor_t *desc)
   2328 {
   2329  if (BUG(!desc->previous_hsdirs)) {
   2330    return;
   2331  }
   2332 
   2333  SMARTLIST_FOREACH(desc->previous_hsdirs, char*, s, tor_free(s));
   2334  smartlist_clear(desc->previous_hsdirs);
   2335 }
   2336 
   2337 /** Note that we attempted to upload <b>desc</b> to <b>hsdir</b>. */
   2338 static void
   2339 service_desc_note_upload(hs_service_descriptor_t *desc, const node_t *hsdir)
   2340 {
   2341  char b64_digest[BASE64_DIGEST_LEN+1] = {0};
   2342  digest_to_base64(b64_digest, hsdir->identity);
   2343 
   2344  if (BUG(!desc->previous_hsdirs)) {
   2345    return;
   2346  }
   2347 
   2348  if (!smartlist_contains_string(desc->previous_hsdirs, b64_digest)) {
   2349    smartlist_add_strdup(desc->previous_hsdirs, b64_digest);
   2350  }
   2351 }
   2352 
   2353 /** Schedule an upload of <b>desc</b>. If <b>descriptor_changed</b> is set, it
   2354 *  means that this descriptor is dirty. */
   2355 STATIC void
   2356 service_desc_schedule_upload(hs_service_descriptor_t *desc,
   2357                             time_t now,
   2358                             int descriptor_changed)
   2359 
   2360 {
   2361  desc->next_upload_time = now;
   2362 
   2363  /* If the descriptor changed, clean up the old HSDirs list. We want to
   2364   * re-upload no matter what. */
   2365  if (descriptor_changed) {
   2366    service_desc_clear_previous_hsdirs(desc);
   2367  }
   2368 }
   2369 
   2370 /** Pick missing intro points for this descriptor if needed. */
   2371 static void
   2372 update_service_descriptor_intro_points(hs_service_t *service,
   2373                          hs_service_descriptor_t *desc, time_t now)
   2374 {
   2375  unsigned int num_intro_points;
   2376 
   2377  tor_assert(service);
   2378  tor_assert(desc);
   2379  tor_assert(desc->desc);
   2380 
   2381  num_intro_points = digest256map_size(desc->intro_points.map);
   2382 
   2383  /* Pick any missing introduction point(s). */
   2384  if (num_intro_points < service->config.num_intro_points) {
   2385    unsigned int num_new_intro_points = pick_needed_intro_points(service,
   2386                                                                 desc);
   2387    if (num_new_intro_points != 0) {
   2388      log_info(LD_REND, "Service %s just picked %u intro points and wanted "
   2389                        "%u for %s descriptor. It currently has %d intro "
   2390                        "points. Launching ESTABLISH_INTRO circuit shortly.",
   2391               safe_str_client(service->onion_address),
   2392               num_new_intro_points,
   2393               service->config.num_intro_points - num_intro_points,
   2394               (desc == service->desc_current) ? "current" : "next",
   2395               num_intro_points);
   2396      /* We'll build those introduction point into the descriptor once we have
   2397       * confirmation that the circuits are opened and ready. However,
   2398       * indicate that this descriptor should be uploaded from now on. */
   2399      service_desc_schedule_upload(desc, now, 1);
   2400    }
   2401    /* Were we able to pick all the intro points we needed? If not, we'll
   2402     * flag the descriptor that it's missing intro points because it
   2403     * couldn't pick enough which will trigger a descriptor upload. */
   2404    if ((num_new_intro_points + num_intro_points) <
   2405        service->config.num_intro_points) {
   2406      desc->missing_intro_points = 1;
   2407    }
   2408  }
   2409 }
   2410 
   2411 /** Update descriptor intro points for each service if needed. We do this as
   2412 * part of the periodic event because we need to establish intro point circuits
   2413 * before we publish descriptors. */
   2414 STATIC void
   2415 update_all_descriptors_intro_points(time_t now)
   2416 {
   2417  FOR_EACH_SERVICE_BEGIN(service) {
   2418    /* We'll try to update each descriptor that is if certain conditions apply
   2419     * in order for the descriptor to be updated. */
   2420    FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   2421      update_service_descriptor_intro_points(service, desc, now);
   2422    } FOR_EACH_DESCRIPTOR_END;
   2423  } FOR_EACH_SERVICE_END;
   2424 }
   2425 
   2426 /** Update or initialise PoW parameters in the descriptors if they do not
   2427 * reflect the current state of the PoW defenses. If the defenses have been
   2428 * disabled then remove the PoW parameters from the descriptors. */
   2429 static void
   2430 update_all_descriptors_pow_params(time_t now)
   2431 {
   2432  FOR_EACH_SERVICE_BEGIN(service) {
   2433    int descs_updated = 0;
   2434    hs_pow_service_state_t *pow_state = service->state.pow_state;
   2435    hs_desc_encrypted_data_t *encrypted;
   2436    uint32_t previous_effort;
   2437 
   2438    /* If PoW defenses have been disabled after previously being enabled, i.e
   2439     * via config change and SIGHUP, we need to remove the PoW parameters from
   2440     * the descriptors so clients stop attempting to solve the puzzle. */
   2441    FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   2442      if (!service->config.has_pow_defenses_enabled &&
   2443          desc->desc->encrypted_data.pow_params) {
   2444        log_info(LD_REND, "PoW defenses have been disabled, clearing "
   2445                         "pow_params from a descriptor.");
   2446        tor_free(desc->desc->encrypted_data.pow_params);
   2447        /* Schedule for upload here as we can skip the following checks as PoW
   2448         * defenses are disabled. */
   2449        service_desc_schedule_upload(desc, now, 1);
   2450      }
   2451    } FOR_EACH_DESCRIPTOR_END;
   2452 
   2453    /* Skip remaining checks if this service does not have PoW defenses
   2454     * enabled. */
   2455    if (!service->config.has_pow_defenses_enabled) {
   2456      continue;
   2457    }
   2458 
   2459    FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   2460      encrypted = &desc->desc->encrypted_data;
   2461      /* If this is a new service or PoW defenses were just enabled we need to
   2462       * initialise pow_params in the descriptors. If this runs the next if
   2463       * statement will run and set the correct values. */
   2464      if (!encrypted->pow_params) {
   2465        log_info(LD_REND, "Initializing pow_params in descriptor...");
   2466        encrypted->pow_params = tor_malloc_zero(sizeof(hs_pow_desc_params_t));
   2467      }
   2468 
   2469      /* Update the descriptor any time the seed rotates, using expiration
   2470       * time as a proxy for parameters not including the suggested_effort,
   2471       * which gets special treatment below. */
   2472      if (encrypted->pow_params->expiration_time !=
   2473          pow_state->expiration_time) {
   2474        encrypted->pow_params->type = 0; /* use first version in the list */
   2475        memcpy(encrypted->pow_params->seed, &pow_state->seed_current,
   2476               HS_POW_SEED_LEN);
   2477        encrypted->pow_params->suggested_effort = pow_state->suggested_effort;
   2478        encrypted->pow_params->expiration_time = pow_state->expiration_time;
   2479        descs_updated = 1;
   2480      }
   2481 
   2482      /* Services SHOULD NOT upload a new descriptor if the suggested
   2483       * effort value changes by less than 15 percent. */
   2484      previous_effort = encrypted->pow_params->suggested_effort;
   2485      if (pow_state->suggested_effort < previous_effort * 0.85 ||
   2486          previous_effort * 1.15 < pow_state->suggested_effort) {
   2487        log_info(LD_REND, "Suggested effort changed significantly, "
   2488                          "updating descriptors...");
   2489        encrypted->pow_params->suggested_effort = pow_state->suggested_effort;
   2490        descs_updated = 1;
   2491      } else if (previous_effort != pow_state->suggested_effort) {
   2492        /* The change in suggested effort was not significant enough to
   2493         * warrant updating the descriptors, return 0 to reflect they are
   2494         * unchanged. */
   2495        log_info(LD_REND, "Change in suggested effort didn't warrant "
   2496                          "updating descriptors.");
   2497      }
   2498    } FOR_EACH_DESCRIPTOR_END;
   2499 
   2500    if (descs_updated) {
   2501      FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   2502        service_desc_schedule_upload(desc, now, 1);
   2503      } FOR_EACH_DESCRIPTOR_END;
   2504    }
   2505  } FOR_EACH_SERVICE_END;
   2506 }
   2507 
   2508 /** Return true iff the given intro point has expired that is it has been used
   2509 * for too long or we've reached our max seen INTRODUCE2 cell. */
   2510 STATIC int
   2511 intro_point_should_expire(const hs_service_intro_point_t *ip,
   2512                          time_t now)
   2513 {
   2514  tor_assert(ip);
   2515 
   2516  if (ip->introduce2_count >= ip->introduce2_max) {
   2517    goto expired;
   2518  }
   2519 
   2520  if (ip->time_to_expire <= now) {
   2521    goto expired;
   2522  }
   2523 
   2524  /* Not expiring. */
   2525  return 0;
   2526 expired:
   2527  return 1;
   2528 }
   2529 
   2530 /** Return true iff we should remove the intro point ip from its service.
   2531 *
   2532 * We remove an intro point from the service descriptor list if one of
   2533 * these criteria is met:
   2534 *    - It has expired (either in INTRO2 count or in time).
   2535 *    - No node was found (fell off the consensus).
   2536 *    - We are over the maximum amount of retries.
   2537 *
   2538 * If an established or pending circuit is found for the given ip object, this
   2539 * return false indicating it should not be removed. */
   2540 static bool
   2541 should_remove_intro_point(hs_service_intro_point_t *ip, time_t now)
   2542 {
   2543  bool ret = false;
   2544 
   2545  tor_assert(ip);
   2546 
   2547  /* Any one of the following needs to be True to fulfill the criteria to
   2548   * remove an intro point. */
   2549  bool has_no_retries = (ip->circuit_retries >
   2550                         MAX_INTRO_POINT_CIRCUIT_RETRIES);
   2551  bool has_no_node = (get_node_from_intro_point(ip) == NULL);
   2552  bool has_expired = intro_point_should_expire(ip, now);
   2553 
   2554  /* If the node fell off the consensus or the IP has expired, we have to
   2555   * remove it now. */
   2556  if (has_no_node || has_expired) {
   2557    ret = true;
   2558    goto end;
   2559  }
   2560 
   2561  /* Past this point, even though we might be over the retry limit, we check
   2562   * if a circuit (established or pending) exists. In that case, we should not
   2563   * remove it because it might simply be valid and opened at the previous
   2564   * scheduled event for the last retry. */
   2565 
   2566  /* Do we simply have an existing circuit regardless of its state? */
   2567  if (hs_circ_service_get_intro_circ(ip)) {
   2568    goto end;
   2569  }
   2570 
   2571  /* Getting here means we have _no_ circuits so then return if we have any
   2572   * remaining retries. */
   2573  ret = has_no_retries;
   2574 
   2575 end:
   2576  /* Meaningful log in case we are about to remove the IP. */
   2577  if (ret) {
   2578    log_info(LD_REND, "Intro point %s%s (retried: %u times). "
   2579                      "Removing it.",
   2580             describe_intro_point(ip),
   2581             has_expired ? " has expired" :
   2582               (has_no_node) ?  " fell off the consensus" : "",
   2583             ip->circuit_retries);
   2584  }
   2585  return ret;
   2586 }
   2587 
   2588 /** Go over the given set of intro points for each service and remove any
   2589 * invalid ones.
   2590 *
   2591 * If an intro point is removed, the circuit (if any) is immediately close.
   2592 * If a circuit can't be found, the intro point is kept if it hasn't reached
   2593 * its maximum circuit retry value and thus should be retried.  */
   2594 static void
   2595 cleanup_intro_points(hs_service_t *service, time_t now)
   2596 {
   2597  /* List of intro points to close. We can't mark the intro circuits for close
   2598   * in the modify loop because doing so calls back into the HS subsystem and
   2599   * we need to keep that code path outside of the service/desc loop so those
   2600   * maps don't get modified during the close making us in a possible
   2601   * use-after-free situation. */
   2602  smartlist_t *ips_to_free = smartlist_new();
   2603 
   2604  tor_assert(service);
   2605 
   2606  /* For both descriptors, cleanup the intro points. */
   2607  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   2608    /* Go over the current intro points we have, make sure they are still
   2609     * valid and remove any of them that aren't. */
   2610    DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
   2611                                hs_service_intro_point_t *, ip) {
   2612      if (should_remove_intro_point(ip, now)) {
   2613        /* We've retried too many times, remember it as a failed intro point
   2614         * so we don't pick it up again for INTRO_CIRC_RETRY_PERIOD sec. */
   2615        if (ip->circuit_retries > MAX_INTRO_POINT_CIRCUIT_RETRIES) {
   2616          remember_failing_intro_point(ip, desc, approx_time());
   2617        }
   2618 
   2619        /* Remove intro point from descriptor map and add it to the list of
   2620         * ips to free for which we'll also try to close the intro circuit. */
   2621        MAP_DEL_CURRENT(key);
   2622        smartlist_add(ips_to_free, ip);
   2623      }
   2624    } DIGEST256MAP_FOREACH_END;
   2625  } FOR_EACH_DESCRIPTOR_END;
   2626 
   2627  /* Go over the intro points to free and close their circuit if any. */
   2628  SMARTLIST_FOREACH_BEGIN(ips_to_free, hs_service_intro_point_t *, ip) {
   2629    /* See if we need to close the intro point circuit as well */
   2630 
   2631    /* XXX: Legacy code does NOT close circuits like this: it keeps the circuit
   2632     * open until a new descriptor is uploaded and then closed all expiring
   2633     * intro point circuit. Here, we close immediately and because we just
   2634     * discarded the intro point, a new one will be selected, a new descriptor
   2635     * created and uploaded. There is no difference to an attacker between the
   2636     * timing of a new consensus and intro point rotation (possibly?). */
   2637    origin_circuit_t *ocirc = hs_circ_service_get_intro_circ(ip);
   2638    if (ocirc && !TO_CIRCUIT(ocirc)->marked_for_close) {
   2639      circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
   2640    }
   2641 
   2642    /* Cleanup the intro point */
   2643    service_intro_point_free(ip);
   2644  } SMARTLIST_FOREACH_END(ip);
   2645 
   2646  smartlist_free(ips_to_free);
   2647 }
   2648 
   2649 /** Rotate the seeds used in the proof-of-work defenses. */
   2650 static void
   2651 rotate_pow_seeds(hs_service_t *service, time_t now)
   2652 {
   2653  /* Make life easier */
   2654  hs_pow_service_state_t *pow_state = service->state.pow_state;
   2655 
   2656  log_info(LD_REND,
   2657          "Current seed expired. Scrubbing replay cache, rotating PoW "
   2658          "seeds, generating new seed and updating descriptors.");
   2659 
   2660  /* Before we overwrite the previous seed lets scrub entries corresponding
   2661   * to it in the nonce replay cache. */
   2662  hs_pow_remove_seed_from_cache(pow_state->seed_previous);
   2663 
   2664  /* Keep track of the current seed that we are now rotating. */
   2665  memcpy(pow_state->seed_previous, pow_state->seed_current, HS_POW_SEED_LEN);
   2666 
   2667  /* Generate a new random seed to use from now on. Make sure the seed head
   2668   * is different to that of the previous seed. The following while loop
   2669   * will run at least once as the seeds will initially be equal. */
   2670  while (fast_memeq(pow_state->seed_previous, pow_state->seed_current,
   2671                    HS_POW_SEED_HEAD_LEN)) {
   2672    crypto_rand((char *)pow_state->seed_current, HS_POW_SEED_LEN);
   2673  }
   2674 
   2675  /* Update the expiration time for the new seed. */
   2676  pow_state->expiration_time =
   2677      (now +
   2678       crypto_rand_int_range(HS_SERVICE_POW_SEED_ROTATE_TIME_MIN,
   2679                             HS_SERVICE_POW_SEED_ROTATE_TIME_MAX));
   2680 
   2681  {
   2682    char fmt_next_time[ISO_TIME_LEN + 1];
   2683    format_local_iso_time(fmt_next_time, pow_state->expiration_time);
   2684    log_debug(LD_REND, "PoW state expiration time set to: %s", fmt_next_time);
   2685  }
   2686 }
   2687 
   2688 /** Every HS_UPDATE_PERIOD seconds, and while PoW defenses are enabled, the
   2689 * service updates its suggested effort for PoW solutions as SUGGESTED_EFFORT =
   2690 * TOTAL_EFFORT / (SVC_BOTTOM_CAPACITY * HS_UPDATE_PERIOD) where TOTAL_EFFORT
   2691 * is the sum of the effort of all valid requests that have been received since
   2692 * the suggested_effort was last updated. */
   2693 static void
   2694 update_suggested_effort(hs_service_t *service, time_t now)
   2695 {
   2696  /* Make life easier */
   2697  hs_pow_service_state_t *pow_state = service->state.pow_state;
   2698 
   2699  /* Calculate the new suggested effort, using an additive-increase
   2700   * multiplicative-decrease estimation scheme. */
   2701  enum {
   2702    NONE,
   2703    INCREASE,
   2704    DECREASE
   2705  } aimd_event = NONE;
   2706 
   2707  if (pow_state->max_trimmed_effort > pow_state->suggested_effort) {
   2708    /* Increase when we notice that high-effort requests are trimmed */
   2709    aimd_event = INCREASE;
   2710  } else if (pow_state->had_queue) {
   2711    if (smartlist_len(pow_state->rend_request_pqueue) > 0 &&
   2712        top_of_rend_pqueue_is_worthwhile(pow_state)) {
   2713      /* Increase when the top of queue is high-effort */
   2714      aimd_event = INCREASE;
   2715    }
   2716  } else if (smartlist_len(pow_state->rend_request_pqueue) <
   2717             pow_state->pqueue_low_level) {
   2718    /* Dec when the queue is empty now and had_queue wasn't set this period */
   2719    aimd_event = DECREASE;
   2720  }
   2721 
   2722  switch (aimd_event) {
   2723    case INCREASE:
   2724      if (pow_state->suggested_effort < UINT32_MAX) {
   2725        pow_state->suggested_effort = MAX(pow_state->suggested_effort + 1,
   2726                                          (uint32_t)(pow_state->total_effort /
   2727                                                     pow_state->rend_handled));
   2728      }
   2729      break;
   2730    case DECREASE:
   2731      pow_state->suggested_effort = 2*pow_state->suggested_effort/3;
   2732      break;
   2733    case NONE:
   2734      break;
   2735  }
   2736 
   2737  hs_metrics_pow_suggested_effort(service, pow_state->suggested_effort);
   2738 
   2739  log_debug(LD_REND, "Recalculated suggested effort: %u",
   2740            pow_state->suggested_effort);
   2741 
   2742  /* Reset the total effort sum and number of rends for this update period. */
   2743  pow_state->total_effort = 0;
   2744  pow_state->rend_handled = 0;
   2745  pow_state->max_trimmed_effort = 0;
   2746  pow_state->had_queue = 0;
   2747  pow_state->next_effort_update = now + HS_UPDATE_PERIOD;
   2748 }
   2749 
   2750 /** Run PoW defenses housekeeping. This MUST be called if the defenses are
   2751 * actually enabled for the given service. */
   2752 static void
   2753 pow_housekeeping(hs_service_t *service, time_t now)
   2754 {
   2755  /* If the service is starting off or just been reset we need to
   2756   * initialize the state of the defenses. */
   2757  if (!service->state.pow_state) {
   2758    initialize_pow_defenses(service);
   2759  }
   2760 
   2761  /* If the current PoW seed has expired then generate a new current
   2762   * seed, storing the old one in seed_previous. */
   2763  if (now >= service->state.pow_state->expiration_time) {
   2764    rotate_pow_seeds(service, now);
   2765  }
   2766 
   2767  /* Update the suggested effort if HS_UPDATE_PERIOD seconds have passed
   2768   * since we last did so. */
   2769  if (now >= service->state.pow_state->next_effort_update) {
   2770    update_suggested_effort(service, now);
   2771  }
   2772 }
   2773 
   2774 /** Set the next rotation time of the descriptors for the given service for the
   2775 * time now. */
   2776 static void
   2777 set_rotation_time(hs_service_t *service)
   2778 {
   2779  tor_assert(service);
   2780 
   2781  service->state.next_rotation_time =
   2782    sr_state_get_start_time_of_current_protocol_run() +
   2783    sr_state_get_protocol_run_duration();
   2784 
   2785  {
   2786    char fmt_time[ISO_TIME_LEN + 1];
   2787    format_local_iso_time(fmt_time, service->state.next_rotation_time);
   2788    log_info(LD_REND, "Next descriptor rotation time set to %s for %s",
   2789             fmt_time, safe_str_client(service->onion_address));
   2790  }
   2791 }
   2792 
   2793 /** Return true iff the service should rotate its descriptor. The time now is
   2794 * only used to fetch the live consensus and if none can be found, this
   2795 * returns false. */
   2796 static unsigned int
   2797 should_rotate_descriptors(hs_service_t *service, time_t now)
   2798 {
   2799  const networkstatus_t *ns;
   2800 
   2801  tor_assert(service);
   2802 
   2803  ns = networkstatus_get_reasonably_live_consensus(now,
   2804                                                   usable_consensus_flavor());
   2805  if (ns == NULL) {
   2806    goto no_rotation;
   2807  }
   2808 
   2809  if (ns->valid_after >= service->state.next_rotation_time) {
   2810    /* In theory, we should never get here with no descriptors. We can never
   2811     * have a NULL current descriptor except when tor starts up. The next
   2812     * descriptor can be NULL after a rotation but we build a new one right
   2813     * after.
   2814     *
   2815     * So, when tor starts, the next rotation time is set to the start of the
   2816     * next SRV period using the consensus valid after time so it should
   2817     * always be set to a future time value. This means that we should never
   2818     * reach this point at bootup that is this check safeguards tor in never
   2819     * allowing a rotation if the valid after time is smaller than the next
   2820     * rotation time.
   2821     *
   2822     * This is all good in theory but we've had a NULL descriptor issue here
   2823     * so this is why we BUG() on both with extra logging to try to understand
   2824     * how this can possibly happens. We'll simply ignore and tor should
   2825     * recover from this by skipping rotation and building the missing
   2826     * descriptors just after this. */
   2827    if (BUG(service->desc_current == NULL || service->desc_next == NULL)) {
   2828      log_warn(LD_BUG, "Service descriptor is NULL (%p/%p). Next rotation "
   2829                       "time is %ld (now: %ld). Valid after time from "
   2830                       "consensus is %ld",
   2831               service->desc_current, service->desc_next,
   2832               (long)service->state.next_rotation_time,
   2833               (long)now,
   2834               (long)ns->valid_after);
   2835      goto no_rotation;
   2836    }
   2837    goto rotation;
   2838  }
   2839 
   2840 no_rotation:
   2841  return 0;
   2842 rotation:
   2843  return 1;
   2844 }
   2845 
   2846 /** Rotate the service descriptors of the given service. The current descriptor
   2847 * will be freed, the next one put in as the current and finally the next
   2848 * descriptor pointer is NULLified. */
   2849 static void
   2850 rotate_service_descriptors(hs_service_t *service)
   2851 {
   2852  if (service->desc_current) {
   2853    /* Close all IP circuits for the descriptor. */
   2854    close_intro_circuits(&service->desc_current->intro_points);
   2855    /* We don't need this one anymore, we won't serve any clients coming with
   2856     * this service descriptor. */
   2857    service_descriptor_free(service->desc_current);
   2858  }
   2859  /* The next one become the current one and emptying the next will trigger
   2860   * a descriptor creation for it. */
   2861  service->desc_current = service->desc_next;
   2862  service->desc_next = NULL;
   2863 
   2864  /* We've just rotated, set the next time for the rotation. */
   2865  set_rotation_time(service);
   2866 }
   2867 
   2868 /** Rotate descriptors for each service if needed. A non existing current
   2869 * descriptor will trigger a descriptor build for the next time period. */
   2870 STATIC void
   2871 rotate_all_descriptors(time_t now)
   2872 {
   2873  /* XXX We rotate all our service descriptors at once. In the future it might
   2874   *     be wise, to rotate service descriptors independently to hide that all
   2875   *     those descriptors are on the same tor instance */
   2876 
   2877  FOR_EACH_SERVICE_BEGIN(service) {
   2878 
   2879    /* Note for a service booting up: Both descriptors are NULL in that case
   2880     * so this function might return true if we are in the timeframe for a
   2881     * rotation leading to basically swapping two NULL pointers which is
   2882     * harmless. However, the side effect is that triggering a rotation will
   2883     * update the service state and avoid doing anymore rotations after the
   2884     * two descriptors have been built. */
   2885    if (!should_rotate_descriptors(service, now)) {
   2886      continue;
   2887    }
   2888 
   2889    log_info(LD_REND, "Time to rotate our descriptors (%p / %p) for %s",
   2890             service->desc_current, service->desc_next,
   2891             safe_str_client(service->onion_address));
   2892 
   2893    rotate_service_descriptors(service);
   2894  } FOR_EACH_SERVICE_END;
   2895 }
   2896 
   2897 /** Scheduled event run from the main loop. Make sure all our services are up
   2898 * to date and ready for the other scheduled events. This includes looking at
   2899 * the introduction points status and descriptor rotation time. */
   2900 STATIC void
   2901 run_housekeeping_event(time_t now)
   2902 {
   2903  /* Note that nothing here opens circuit(s) nor uploads descriptor(s). We are
   2904   * simply moving things around or removing unneeded elements. */
   2905 
   2906  FOR_EACH_SERVICE_BEGIN(service) {
   2907 
   2908    /* If the service is starting off, set the rotation time. We can't do that
   2909     * at configure time because the get_options() needs to be set for setting
   2910     * that time that uses the voting interval. */
   2911    if (service->state.next_rotation_time == 0) {
   2912      /* Set the next rotation time of the descriptors. If it's Oct 25th
   2913       * 23:47:00, the next rotation time is when the next SRV is computed
   2914       * which is at Oct 26th 00:00:00 that is in 13 minutes. */
   2915      set_rotation_time(service);
   2916    }
   2917 
   2918    /* Check if we need to initialize or update PoW parameters, if the
   2919     * defenses are enabled. */
   2920    if (have_module_pow() && service->config.has_pow_defenses_enabled) {
   2921      pow_housekeeping(service, now);
   2922    }
   2923 
   2924    /* Cleanup invalid intro points from the service descriptor. */
   2925    cleanup_intro_points(service, now);
   2926 
   2927    /* Remove expired failing intro point from the descriptor failed list. We
   2928     * reset them at each INTRO_CIRC_RETRY_PERIOD. */
   2929    remove_expired_failing_intro(service, now);
   2930 
   2931    /* At this point, the service is now ready to go through the scheduled
   2932     * events guaranteeing a valid state. Intro points might be missing from
   2933     * the descriptors after the cleanup but the update/build process will
   2934     * make sure we pick those missing ones. */
   2935  } FOR_EACH_SERVICE_END;
   2936 }
   2937 
   2938 /** Scheduled event run from the main loop. Make sure all descriptors are up to
   2939 * date. Once this returns, each service descriptor needs to be considered for
   2940 * new introduction circuits and then for upload. */
   2941 static void
   2942 run_build_descriptor_event(time_t now)
   2943 {
   2944  /* Run v3+ events. */
   2945  /* We start by rotating the descriptors only if needed. */
   2946  rotate_all_descriptors(now);
   2947 
   2948  /* Then, we'll try to build  new descriptors that we might need. The
   2949   * condition is that the next descriptor is non existing because it has
   2950   * been rotated or we just started up. */
   2951  build_all_descriptors(now);
   2952 
   2953  /* Finally, we'll check if we should update the descriptors' intro
   2954   * points. Missing introduction points will be picked in this function which
   2955   * is useful for newly built descriptors. */
   2956  update_all_descriptors_intro_points(now);
   2957 
   2958  if (have_module_pow()) {
   2959    /* Update the PoW params if needed. */
   2960    update_all_descriptors_pow_params(now);
   2961  }
   2962 }
   2963 
   2964 /** For the given service, launch any intro point circuits that could be
   2965 * needed. This considers every descriptor of the service. */
   2966 static void
   2967 launch_intro_point_circuits(hs_service_t *service)
   2968 {
   2969  tor_assert(service);
   2970 
   2971  /* For both descriptors, try to launch any missing introduction point
   2972   * circuits using the current map. */
   2973  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   2974    /* Keep a ref on if we need a direct connection. We use this often. */
   2975    bool direct_conn = service->config.is_single_onion;
   2976 
   2977    DIGEST256MAP_FOREACH_MODIFY(desc->intro_points.map, key,
   2978                                hs_service_intro_point_t *, ip) {
   2979      extend_info_t *ei;
   2980 
   2981      /* Skip the intro point that already has an existing circuit
   2982       * (established or not). */
   2983      if (hs_circ_service_get_intro_circ(ip)) {
   2984        continue;
   2985      }
   2986      ei = get_extend_info_from_intro_point(ip, direct_conn);
   2987 
   2988      /* If we can't connect directly to the intro point, get an extend_info
   2989       * for a multi-hop path instead. */
   2990      if (ei == NULL && direct_conn) {
   2991        direct_conn = false;
   2992        ei = get_extend_info_from_intro_point(ip, 0);
   2993      }
   2994 
   2995      if (ei == NULL) {
   2996        /* This is possible if we can get a node_t but not the extend info out
   2997         * of it. In this case, we remove the intro point and a new one will
   2998         * be picked at the next main loop callback. */
   2999        MAP_DEL_CURRENT(key);
   3000        service_intro_point_free(ip);
   3001        continue;
   3002      }
   3003 
   3004      /* Launch a circuit to the intro point. */
   3005      ip->circuit_retries++;
   3006      if (hs_circ_launch_intro_point(service, ip, ei, direct_conn) < 0) {
   3007        log_info(LD_REND, "Unable to launch intro circuit to node %s "
   3008                          "for service %s.",
   3009                 safe_str_client(extend_info_describe(ei)),
   3010                 safe_str_client(service->onion_address));
   3011        /* Intro point will be retried if possible after this. */
   3012      }
   3013      extend_info_free(ei);
   3014    } DIGEST256MAP_FOREACH_END;
   3015  } FOR_EACH_DESCRIPTOR_END;
   3016 }
   3017 
   3018 /** Don't try to build more than this many circuits before giving up for a
   3019 * while. Dynamically calculated based on the configured number of intro
   3020 * points for the given service and how many descriptor exists. The default
   3021 * use case of 3 introduction points and two descriptors will allow 28
   3022 * circuits for a retry period (((3 + 2) + (3 * 3)) * 2). */
   3023 static unsigned int
   3024 get_max_intro_circ_per_period(const hs_service_t *service)
   3025 {
   3026  unsigned int count = 0;
   3027  unsigned int multiplier = 0;
   3028  unsigned int num_wanted_ip;
   3029 
   3030  tor_assert(service);
   3031  tor_assert(service->config.num_intro_points <=
   3032             HS_CONFIG_V3_MAX_INTRO_POINTS);
   3033 
   3034  num_wanted_ip = service->config.num_intro_points;
   3035 
   3036  /* The calculation is as follow. We have a number of intro points that we
   3037   * want configured as a torrc option (num_intro_points). We then add an
   3038   * extra value so we can launch multiple circuits at once and pick the
   3039   * quickest ones. For instance, we want 3 intros, we add 2 extra so we'll
   3040   * pick 5 intros and launch 5 circuits. */
   3041  count += (num_wanted_ip + get_intro_point_num_extra());
   3042 
   3043  /* Then we add the number of retries that is possible to do for each intro
   3044   * point. If we want 3 intros, we'll allow 3 times the number of possible
   3045   * retry. */
   3046  count += (num_wanted_ip * MAX_INTRO_POINT_CIRCUIT_RETRIES);
   3047 
   3048  /* Then, we multiply by a factor of 2 if we have both descriptor or 0 if we
   3049   * have none.  */
   3050  multiplier += (service->desc_current) ? 1 : 0;
   3051  multiplier += (service->desc_next) ? 1 : 0;
   3052 
   3053  return (count * multiplier);
   3054 }
   3055 
   3056 /** For the given service, return 1 if the service is allowed to launch more
   3057 * introduction circuits else 0 if the maximum has been reached for the retry
   3058 * period of INTRO_CIRC_RETRY_PERIOD. */
   3059 STATIC int
   3060 can_service_launch_intro_circuit(hs_service_t *service, time_t now)
   3061 {
   3062  tor_assert(service);
   3063 
   3064  /* Consider the intro circuit retry period of the service. */
   3065  if (now > (service->state.intro_circ_retry_started_time +
   3066             INTRO_CIRC_RETRY_PERIOD)) {
   3067    service->state.intro_circ_retry_started_time = now;
   3068    service->state.num_intro_circ_launched = 0;
   3069    goto allow;
   3070  }
   3071  /* Check if we can still launch more circuits in this period. */
   3072  if (service->state.num_intro_circ_launched <=
   3073      get_max_intro_circ_per_period(service)) {
   3074    goto allow;
   3075  }
   3076 
   3077  /* Rate limit log that we've reached our circuit creation limit. */
   3078  {
   3079    char *msg;
   3080    time_t elapsed_time = now - service->state.intro_circ_retry_started_time;
   3081    static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
   3082    if ((msg = rate_limit_log(&rlimit, now))) {
   3083      log_info(LD_REND, "Hidden service %s exceeded its circuit launch limit "
   3084                        "of %u per %d seconds. It launched %u circuits in "
   3085                        "the last %ld seconds. Will retry in %ld seconds.",
   3086               safe_str_client(service->onion_address),
   3087               get_max_intro_circ_per_period(service),
   3088               INTRO_CIRC_RETRY_PERIOD,
   3089               service->state.num_intro_circ_launched,
   3090               (long int) elapsed_time,
   3091               (long int) (INTRO_CIRC_RETRY_PERIOD - elapsed_time));
   3092      tor_free(msg);
   3093    }
   3094  }
   3095 
   3096  /* Not allow. */
   3097  return 0;
   3098 allow:
   3099  return 1;
   3100 }
   3101 
   3102 /** Scheduled event run from the main loop. Make sure we have all the circuits
   3103 * we need for each service. */
   3104 static void
   3105 run_build_circuit_event(time_t now)
   3106 {
   3107  /* Make sure we can actually have enough information or able to build
   3108   * internal circuits as required by services. */
   3109  if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN ||
   3110      !have_completed_a_circuit()) {
   3111    return;
   3112  }
   3113 
   3114  /* Run v3+ check. */
   3115  FOR_EACH_SERVICE_BEGIN(service) {
   3116    /* For introduction circuit, we need to make sure we don't stress too much
   3117     * circuit creation so make sure this service is respecting that limit. */
   3118    if (can_service_launch_intro_circuit(service, now)) {
   3119      /* Launch intro point circuits if needed. */
   3120      launch_intro_point_circuits(service);
   3121      /* Once the circuits have opened, we'll make sure to update the
   3122       * descriptor intro point list and cleanup any extraneous. */
   3123    }
   3124  } FOR_EACH_SERVICE_END;
   3125 }
   3126 
   3127 /** Encode and sign the service descriptor desc and upload it to the given
   3128 * hidden service directory.  This does nothing if PublishHidServDescriptors
   3129 * is false. */
   3130 static void
   3131 upload_descriptor_to_hsdir(const hs_service_t *service,
   3132                           hs_service_descriptor_t *desc, const node_t *hsdir)
   3133 {
   3134  char *encoded_desc = NULL;
   3135 
   3136  tor_assert(service);
   3137  tor_assert(desc);
   3138  tor_assert(hsdir);
   3139 
   3140  /* Let's avoid doing that if tor is configured to not publish. */
   3141  if (!get_options()->PublishHidServDescriptors) {
   3142    log_info(LD_REND, "Service %s not publishing descriptor. "
   3143                      "PublishHidServDescriptors is set to 0.",
   3144             safe_str_client(service->onion_address));
   3145    goto end;
   3146  }
   3147 
   3148  /* First of all, we'll encode the descriptor. This should NEVER fail but
   3149   * just in case, let's make sure we have an actual usable descriptor. */
   3150  if (BUG(service_encode_descriptor(service, desc, &desc->signing_kp,
   3151                                    &encoded_desc) < 0)) {
   3152    goto end;
   3153  }
   3154 
   3155  /* Time to upload the descriptor to the directory. */
   3156  hs_service_upload_desc_to_dir(encoded_desc, service->config.version,
   3157                                &service->keys.identity_pk,
   3158                                &desc->blinded_kp.pubkey, hsdir->rs);
   3159 
   3160  /* Add this node to previous_hsdirs list */
   3161  service_desc_note_upload(desc, hsdir);
   3162 
   3163  /* Logging so we know where it was sent. */
   3164  {
   3165    int is_next_desc = (service->desc_next == desc);
   3166    const uint8_t *idx = (is_next_desc) ? hsdir->hsdir_index.store_second:
   3167                                          hsdir->hsdir_index.store_first;
   3168    char *blinded_pubkey_log_str =
   3169      tor_strdup(hex_str((char*)&desc->blinded_kp.pubkey.pubkey, 32));
   3170    /* This log message is used by Chutney as part of its bootstrap
   3171     * detection mechanism. Please don't change without first checking
   3172     * Chutney. */
   3173    log_info(LD_REND, "Service %s %s descriptor of revision %" PRIu64
   3174                      " initiated upload request to %s with index %s (%s)",
   3175             safe_str_client(service->onion_address),
   3176             (is_next_desc) ? "next" : "current",
   3177             desc->desc->plaintext_data.revision_counter,
   3178             safe_str_client(node_describe(hsdir)),
   3179             safe_str_client(hex_str((const char *) idx, 32)),
   3180             safe_str_client(blinded_pubkey_log_str));
   3181    tor_free(blinded_pubkey_log_str);
   3182 
   3183    /* Fire a UPLOAD control port event. */
   3184    hs_control_desc_event_upload(service->onion_address, hsdir->identity,
   3185                                 &desc->blinded_kp.pubkey, idx);
   3186  }
   3187 
   3188 end:
   3189  tor_free(encoded_desc);
   3190  return;
   3191 }
   3192 
   3193 /** Set the revision counter in <b>hs_desc</b>. We do this by encrypting a
   3194 *  timestamp using an OPE scheme and using the ciphertext as our revision
   3195 *  counter.
   3196 *
   3197 *  If <b>is_current</b> is true, then this is the current HS descriptor,
   3198 *  otherwise it's the next one. */
   3199 static void
   3200 set_descriptor_revision_counter(hs_service_descriptor_t *hs_desc, time_t now,
   3201                                bool is_current)
   3202 {
   3203  uint64_t rev_counter = 0;
   3204 
   3205  /* Get current time */
   3206  time_t srv_start = 0;
   3207 
   3208  /* As our revision counter plaintext value, we use the seconds since the
   3209   * start of the SR protocol run that is relevant to this descriptor. This is
   3210   * guaranteed to be a positive value since we need the SRV to start making a
   3211   * descriptor (so that we know where to upload it).
   3212   *
   3213   * Depending on whether we are building the current or the next descriptor,
   3214   * services use a different SRV value. See [SERVICEUPLOAD] in
   3215   * rend-spec-v3.txt:
   3216   *
   3217   * In particular, for the current descriptor (aka first descriptor), Tor
   3218   * always uses the previous SRV for uploading the descriptor, and hence we
   3219   * should use the start time of the previous protocol run here.
   3220   *
   3221   * Whereas for the next descriptor (aka second descriptor), Tor always uses
   3222   * the current SRV for uploading the descriptor.  and hence we use the start
   3223   * time of the current protocol run.
   3224   */
   3225  if (is_current) {
   3226    srv_start = sr_state_get_start_time_of_previous_protocol_run();
   3227  } else {
   3228    srv_start = sr_state_get_start_time_of_current_protocol_run();
   3229  }
   3230 
   3231  log_info(LD_REND, "Setting rev counter for TP #%u: "
   3232           "SRV started at %d, now %d (%s)",
   3233           (unsigned) hs_desc->time_period_num, (int)srv_start,
   3234           (int)now, is_current ? "current" : "next");
   3235 
   3236  tor_assert_nonfatal(now >= srv_start);
   3237 
   3238  /* Compute seconds elapsed since the start of the time period. That's the
   3239   * number of seconds of how long this blinded key has been active. */
   3240  time_t seconds_since_start_of_srv = now - srv_start;
   3241 
   3242  /* Increment by one so that we are definitely sure this is strictly
   3243   * positive and not zero. */
   3244  seconds_since_start_of_srv++;
   3245 
   3246  /* Check for too big inputs. */
   3247  if (BUG(seconds_since_start_of_srv > OPE_INPUT_MAX)) {
   3248    seconds_since_start_of_srv = OPE_INPUT_MAX;
   3249  }
   3250 
   3251  /* Now we compute the final revision counter value by encrypting the
   3252     plaintext using our OPE cipher: */
   3253  tor_assert(hs_desc->ope_cipher);
   3254  rev_counter = crypto_ope_encrypt(hs_desc->ope_cipher,
   3255                                   (int) seconds_since_start_of_srv);
   3256 
   3257  /* The OPE module returns CRYPTO_OPE_ERROR in case of errors. */
   3258  tor_assert_nonfatal(rev_counter < CRYPTO_OPE_ERROR);
   3259 
   3260  log_info(LD_REND, "Encrypted revision counter %d to %" PRIu64,
   3261           (int) seconds_since_start_of_srv, rev_counter);
   3262 
   3263  hs_desc->desc->plaintext_data.revision_counter = rev_counter;
   3264 }
   3265 
   3266 /** Encode and sign the service descriptor desc and upload it to the
   3267 * responsible hidden service directories.
   3268 * This does nothing if PublishHidServDescriptors is false. */
   3269 STATIC void
   3270 upload_descriptor_to_all(const hs_service_t *service,
   3271                         hs_service_descriptor_t *desc)
   3272 {
   3273  smartlist_t *responsible_dirs = NULL;
   3274 
   3275  tor_assert(service);
   3276  tor_assert(desc);
   3277 
   3278  /* We'll first cancel any directory request that are ongoing for this
   3279   * descriptor. It is possible that we can trigger multiple uploads in a
   3280   * short time frame which can lead to a race where the second upload arrives
   3281   * before the first one leading to a 400 malformed descriptor response from
   3282   * the directory. Closing all pending requests avoids that. */
   3283  close_directory_connections(service, desc);
   3284 
   3285  /* Get our list of responsible HSDir. */
   3286  responsible_dirs = smartlist_new();
   3287  /* The parameter 0 means that we aren't a client so tell the function to use
   3288   * the spread store consensus parameter. */
   3289  hs_get_responsible_hsdirs(&desc->blinded_kp.pubkey, desc->time_period_num,
   3290                            service->desc_next == desc, 0, responsible_dirs);
   3291 
   3292  /** Clear list of previous hsdirs since we are about to upload to a new
   3293   *  list. Let's keep it up to date. */
   3294  service_desc_clear_previous_hsdirs(desc);
   3295 
   3296  /* For each responsible HSDir we have, initiate an upload command. */
   3297  SMARTLIST_FOREACH_BEGIN(responsible_dirs, const routerstatus_t *,
   3298                          hsdir_rs) {
   3299    const node_t *hsdir_node = node_get_by_id(hsdir_rs->identity_digest);
   3300    /* Getting responsible hsdir implies that the node_t object exists for the
   3301     * routerstatus_t found in the consensus else we have a problem. */
   3302    tor_assert(hsdir_node);
   3303    /* Upload this descriptor to the chosen directory. */
   3304    upload_descriptor_to_hsdir(service, desc, hsdir_node);
   3305  } SMARTLIST_FOREACH_END(hsdir_rs);
   3306 
   3307  /* Set the next upload time for this descriptor. Even if we are configured
   3308   * to not upload, we still want to follow the right cycle of life for this
   3309   * descriptor. */
   3310  desc->next_upload_time =
   3311    (time(NULL) + crypto_rand_int_range(HS_SERVICE_NEXT_UPLOAD_TIME_MIN,
   3312                                        HS_SERVICE_NEXT_UPLOAD_TIME_MAX));
   3313  {
   3314    char fmt_next_time[ISO_TIME_LEN+1];
   3315    format_local_iso_time(fmt_next_time, desc->next_upload_time);
   3316    log_debug(LD_REND, "Service %s set to upload a descriptor at %s",
   3317              safe_str_client(service->onion_address), fmt_next_time);
   3318  }
   3319 
   3320  smartlist_free(responsible_dirs);
   3321  return;
   3322 }
   3323 
   3324 /** The set of HSDirs have changed: check if the change affects our descriptor
   3325 *  HSDir placement, and if it does, reupload the desc. */
   3326 STATIC int
   3327 service_desc_hsdirs_changed(const hs_service_t *service,
   3328                            const hs_service_descriptor_t *desc)
   3329 {
   3330  int should_reupload = 0;
   3331  smartlist_t *responsible_dirs = smartlist_new();
   3332 
   3333  /* No desc upload has happened yet: it will happen eventually */
   3334  if (!desc->previous_hsdirs || !smartlist_len(desc->previous_hsdirs)) {
   3335    goto done;
   3336  }
   3337 
   3338  /* Get list of responsible hsdirs */
   3339  hs_get_responsible_hsdirs(&desc->blinded_kp.pubkey, desc->time_period_num,
   3340                            service->desc_next == desc, 0, responsible_dirs);
   3341 
   3342  /* Check if any new hsdirs have been added to the responsible hsdirs set:
   3343   * Iterate over the list of new hsdirs, and reupload if any of them is not
   3344   * present in the list of previous hsdirs.
   3345   */
   3346  SMARTLIST_FOREACH_BEGIN(responsible_dirs, const routerstatus_t *, hsdir_rs) {
   3347    char b64_digest[BASE64_DIGEST_LEN+1] = {0};
   3348    digest_to_base64(b64_digest, hsdir_rs->identity_digest);
   3349 
   3350    if (!smartlist_contains_string(desc->previous_hsdirs, b64_digest)) {
   3351      should_reupload = 1;
   3352      break;
   3353    }
   3354  } SMARTLIST_FOREACH_END(hsdir_rs);
   3355 
   3356 done:
   3357  smartlist_free(responsible_dirs);
   3358 
   3359  return should_reupload;
   3360 }
   3361 
   3362 /** These are all the reasons why a descriptor upload can't occur. We use
   3363 * those to log the reason properly with the right rate limiting and for the
   3364 * right descriptor. */
   3365 typedef enum {
   3366  LOG_DESC_UPLOAD_REASON_MISSING_IPS = 0,
   3367  LOG_DESC_UPLOAD_REASON_IP_NOT_ESTABLISHED = 1,
   3368  LOG_DESC_UPLOAD_REASON_NOT_TIME = 2,
   3369  LOG_DESC_UPLOAD_REASON_NO_LIVE_CONSENSUS = 3,
   3370  LOG_DESC_UPLOAD_REASON_NO_DIRINFO = 4,
   3371 } log_desc_upload_reason_t;
   3372 
   3373 /** Maximum number of reasons. This is used to allocate the static array of
   3374 * all rate limiting objects. */
   3375 #define LOG_DESC_UPLOAD_REASON_MAX LOG_DESC_UPLOAD_REASON_NO_DIRINFO
   3376 
   3377 /** Log the reason why we can't upload the given descriptor for the given
   3378 * service. This takes a message string (allocated by the caller) and a
   3379 * reason.
   3380 *
   3381 * Depending on the reason and descriptor, different rate limit applies. This
   3382 * is done because this function will basically be called every second. Each
   3383 * descriptor for each reason uses its own log rate limit object in order to
   3384 * avoid message suppression for different reasons and descriptors. */
   3385 static void
   3386 log_cant_upload_desc(const hs_service_t *service,
   3387                     const hs_service_descriptor_t *desc, const char *msg,
   3388                     const log_desc_upload_reason_t reason)
   3389 {
   3390  /* Writing the log every minute shouldn't be too annoying for log rate limit
   3391   * since this can be emitted every second for each descriptor.
   3392   *
   3393   * However, for one specific case, we increase it to 10 minutes because it
   3394   * is hit constantly, as an expected behavior, which is the reason
   3395   * indicating that it is not the time to upload. */
   3396  static ratelim_t limits[2][LOG_DESC_UPLOAD_REASON_MAX + 1] =
   3397    { { RATELIM_INIT(60), RATELIM_INIT(60), RATELIM_INIT(60 * 10),
   3398        RATELIM_INIT(60), RATELIM_INIT(60) },
   3399      { RATELIM_INIT(60), RATELIM_INIT(60), RATELIM_INIT(60 * 10),
   3400        RATELIM_INIT(60), RATELIM_INIT(60) },
   3401    };
   3402  bool is_next_desc = false;
   3403  unsigned int rlim_pos = 0;
   3404  ratelim_t *rlim = NULL;
   3405 
   3406  tor_assert(service);
   3407  tor_assert(desc);
   3408  tor_assert(msg);
   3409 
   3410  /* Make sure the reason value is valid. It should never happen because we
   3411   * control that value in the code flow but will be apparent during
   3412   * development if a reason is added but LOG_DESC_UPLOAD_REASON_NUM_ is not
   3413   * updated. */
   3414  if (BUG(reason > LOG_DESC_UPLOAD_REASON_MAX)) {
   3415    return;
   3416  }
   3417 
   3418  /* Ease our life. Flag that tells us if the descriptor is the next one. */
   3419  is_next_desc = (service->desc_next == desc);
   3420 
   3421  /* Current descriptor is the first element in the ratelimit object array.
   3422   * The next descriptor is the second element. */
   3423  rlim_pos = (is_next_desc ? 1 : 0);
   3424  /* Get the ratelimit object for the reason _and_ right descriptor. */
   3425  rlim = &limits[rlim_pos][reason];
   3426 
   3427  log_fn_ratelim(rlim, LOG_INFO, LD_REND,
   3428                 "Service %s can't upload its %s descriptor: %s",
   3429                 safe_str_client(service->onion_address),
   3430                 (is_next_desc) ? "next" : "current", msg);
   3431 }
   3432 
   3433 /** Return 1 if the given descriptor from the given service can be uploaded
   3434 * else return 0 if it can not. */
   3435 static int
   3436 should_service_upload_descriptor(const hs_service_t *service,
   3437                              const hs_service_descriptor_t *desc, time_t now)
   3438 {
   3439  char *msg = NULL;
   3440  unsigned int num_intro_points, count_ip_established;
   3441 
   3442  tor_assert(service);
   3443  tor_assert(desc);
   3444 
   3445  /* If this descriptors has missing intro points that is that it couldn't get
   3446   * them all when it was time to pick them, it means that we should upload
   3447   * instead of waiting an arbitrary amount of time breaking the service.
   3448   * Else, if we have no missing intro points, we use the value taken from the
   3449   * service configuration. */
   3450  if (desc->missing_intro_points) {
   3451    num_intro_points = digest256map_size(desc->intro_points.map);
   3452  } else {
   3453    num_intro_points = service->config.num_intro_points;
   3454  }
   3455 
   3456  /* This means we tried to pick intro points but couldn't get any so do not
   3457   * upload descriptor in this case. We need at least one for the service to
   3458   * be reachable. */
   3459  if (desc->missing_intro_points && num_intro_points == 0) {
   3460    msg = tor_strdup("Missing intro points");
   3461    log_cant_upload_desc(service, desc, msg,
   3462                         LOG_DESC_UPLOAD_REASON_MISSING_IPS);
   3463    goto cannot;
   3464  }
   3465 
   3466  /* Check if all our introduction circuit have been established for all the
   3467   * intro points we have selected. */
   3468  count_ip_established = count_desc_circuit_established(desc);
   3469  if (count_ip_established != num_intro_points) {
   3470    tor_asprintf(&msg, "Intro circuits aren't yet all established (%d/%d).",
   3471                 count_ip_established, num_intro_points);
   3472    log_cant_upload_desc(service, desc, msg,
   3473                         LOG_DESC_UPLOAD_REASON_IP_NOT_ESTABLISHED);
   3474    goto cannot;
   3475  }
   3476 
   3477  /* Is it the right time to upload? */
   3478  if (desc->next_upload_time > now) {
   3479    tor_asprintf(&msg, "Next upload time is %ld, it is now %ld.",
   3480                 (long int) desc->next_upload_time, (long int) now);
   3481    log_cant_upload_desc(service, desc, msg,
   3482                         LOG_DESC_UPLOAD_REASON_NOT_TIME);
   3483    goto cannot;
   3484  }
   3485 
   3486  /* Don't upload desc if we don't have a live consensus */
   3487  if (!networkstatus_get_reasonably_live_consensus(now,
   3488                                            usable_consensus_flavor())) {
   3489    msg = tor_strdup("No reasonably live consensus");
   3490    log_cant_upload_desc(service, desc, msg,
   3491                         LOG_DESC_UPLOAD_REASON_NO_LIVE_CONSENSUS);
   3492    goto cannot;
   3493  }
   3494 
   3495  /* Do we know enough router descriptors to have adequate vision of the HSDir
   3496     hash ring? */
   3497  if (!router_have_minimum_dir_info()) {
   3498    msg = tor_strdup("Not enough directory information");
   3499    log_cant_upload_desc(service, desc, msg,
   3500                         LOG_DESC_UPLOAD_REASON_NO_DIRINFO);
   3501    goto cannot;
   3502  }
   3503 
   3504  /* Can upload! */
   3505  return 1;
   3506 
   3507 cannot:
   3508  tor_free(msg);
   3509  return 0;
   3510 }
   3511 
   3512 /** Refresh the given service descriptor meaning this will update every mutable
   3513 * field that needs to be updated before we upload.
   3514 *
   3515 * This should ONLY be called before uploading a descriptor. It assumes that
   3516 * the descriptor has been built (desc->desc) and that all intro point
   3517 * circuits have been established.  */
   3518 static void
   3519 refresh_service_descriptor(const hs_service_t *service,
   3520                           hs_service_descriptor_t *desc, time_t now)
   3521 {
   3522  /* There are few fields that we consider "mutable" in the descriptor meaning
   3523   * we need to update them regularly over the lifetime for the descriptor.
   3524   * The rest are set once and should not be modified.
   3525   *
   3526   *  - Signing key certificate.
   3527   *  - Revision counter.
   3528   *  - Introduction points which includes many thing. See
   3529   *    hs_desc_intro_point_t. and the setup_desc_intro_point() function.
   3530   */
   3531 
   3532  /* Create the signing key certificate. */
   3533  build_desc_signing_key_cert(desc, now);
   3534 
   3535  /* Build the intro points descriptor section. The refresh step is just
   3536   * before we upload so all circuits have been properly established. */
   3537  build_desc_intro_points(service, desc, now);
   3538 
   3539  /* Set the desc revision counter right before uploading */
   3540  set_descriptor_revision_counter(desc, now, service->desc_current == desc);
   3541 }
   3542 
   3543 /** Scheduled event run from the main loop. Try to upload the descriptor for
   3544 * each service. */
   3545 STATIC void
   3546 run_upload_descriptor_event(time_t now)
   3547 {
   3548  /* Run v3+ check. */
   3549  FOR_EACH_SERVICE_BEGIN(service) {
   3550    FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   3551      /* If we were asked to re-examine the hash ring, and it changed, then
   3552         schedule an upload */
   3553      if (consider_republishing_hs_descriptors &&
   3554          service_desc_hsdirs_changed(service, desc)) {
   3555        service_desc_schedule_upload(desc, now, 0);
   3556      }
   3557 
   3558      /* Can this descriptor be uploaded? */
   3559      if (!should_service_upload_descriptor(service, desc, now)) {
   3560        continue;
   3561      }
   3562 
   3563      log_info(LD_REND, "Initiating upload for hidden service %s descriptor "
   3564                        "for service %s with %u/%u introduction points%s.",
   3565               (desc == service->desc_current) ? "current" : "next",
   3566               safe_str_client(service->onion_address),
   3567               digest256map_size(desc->intro_points.map),
   3568               service->config.num_intro_points,
   3569               (desc->missing_intro_points) ? " (couldn't pick more)" : "");
   3570 
   3571      /* We are about to upload so we need to do one last step which is to
   3572       * update the service's descriptor mutable fields in order to upload a
   3573       * coherent descriptor. */
   3574      refresh_service_descriptor(service, desc, now);
   3575 
   3576      /* Proceed with the upload, the descriptor is ready to be encoded. */
   3577      upload_descriptor_to_all(service, desc);
   3578    } FOR_EACH_DESCRIPTOR_END;
   3579  } FOR_EACH_SERVICE_END;
   3580 
   3581  /* We are done considering whether to republish rend descriptors */
   3582  consider_republishing_hs_descriptors = 0;
   3583 }
   3584 
   3585 /** Called when the introduction point circuit is done building and ready to be
   3586 * used. */
   3587 static void
   3588 service_intro_circ_has_opened(origin_circuit_t *circ)
   3589 {
   3590  hs_service_t *service = NULL;
   3591  hs_service_intro_point_t *ip = NULL;
   3592  hs_service_descriptor_t *desc = NULL;
   3593 
   3594  tor_assert(circ);
   3595 
   3596  /* Let's do some basic sanity checking of the circ state */
   3597  if (BUG(!circ->cpath)) {
   3598    return;
   3599  }
   3600  if (BUG(TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)) {
   3601    return;
   3602  }
   3603  if (BUG(!circ->hs_ident)) {
   3604    return;
   3605  }
   3606 
   3607  /* Get the corresponding service and intro point. */
   3608  get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
   3609 
   3610  if (service == NULL) {
   3611    log_warn(LD_REND, "Unknown service identity key %s on the introduction "
   3612                      "circuit %u. Can't find onion service.",
   3613             safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
   3614             TO_CIRCUIT(circ)->n_circ_id);
   3615    goto err;
   3616  }
   3617  if (ip == NULL) {
   3618    log_warn(LD_REND, "Unknown introduction point auth key on circuit %u "
   3619                      "for service %s",
   3620             TO_CIRCUIT(circ)->n_circ_id,
   3621             safe_str_client(service->onion_address));
   3622    goto err;
   3623  }
   3624  /* We can't have an IP object without a descriptor. */
   3625  tor_assert(desc);
   3626 
   3627  if (hs_circ_service_intro_has_opened(service, ip, desc, circ)) {
   3628    /* Getting here means that the circuit has been re-purposed because we
   3629     * have enough intro circuit opened. Remove the IP from the service. */
   3630    service_intro_point_remove(service, ip);
   3631    service_intro_point_free(ip);
   3632  }
   3633 
   3634  goto done;
   3635 
   3636 err:
   3637  /* Close circuit, we can't use it. */
   3638  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOSUCHSERVICE);
   3639 done:
   3640  return;
   3641 }
   3642 
   3643 /** Called when a rendezvous circuit is done building and ready to be used. */
   3644 static void
   3645 service_rendezvous_circ_has_opened(origin_circuit_t *circ)
   3646 {
   3647  hs_service_t *service = NULL;
   3648 
   3649  tor_assert(circ);
   3650  tor_assert(circ->cpath);
   3651  /* Getting here means this is a v3 rendezvous circuit. */
   3652  tor_assert(circ->hs_ident);
   3653  tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
   3654 
   3655  /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
   3656   * timestamp regardless of its content because that circuit could have been
   3657   * cannibalized so in any cases, we are about to use that circuit more. */
   3658  TO_CIRCUIT(circ)->timestamp_dirty = time(NULL);
   3659  pathbias_count_use_attempt(circ);
   3660 
   3661  /* Get the corresponding service and intro point. */
   3662  get_objects_from_ident(circ->hs_ident, &service, NULL, NULL);
   3663  if (service == NULL) {
   3664    log_warn(LD_REND, "Unknown service identity key %s on the rendezvous "
   3665                      "circuit %u with cookie %s. Can't find onion service.",
   3666             safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
   3667             TO_CIRCUIT(circ)->n_circ_id,
   3668             hex_str((const char *) circ->hs_ident->rendezvous_cookie,
   3669                     REND_COOKIE_LEN));
   3670    goto err;
   3671  }
   3672 
   3673  /* If the cell can't be sent, the circuit will be closed within this
   3674   * function. */
   3675  hs_circ_service_rp_has_opened(service, circ);
   3676 
   3677  /* Update metrics that we have an established rendezvous circuit. It is not
   3678   * entirely true until the client receives the RENDEZVOUS2 cell and starts
   3679   * sending but if that circuit collapes, we'll decrement the counter thus it
   3680   * will even out the metric. */
   3681  if (TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
   3682    hs_metrics_new_established_rdv(service);
   3683 
   3684    struct timeval now;
   3685    tor_gettimeofday(&now);
   3686    int64_t duration = tv_mdiff(&TO_CIRCUIT(circ)->timestamp_began, &now);
   3687    hs_metrics_rdv_circ_build_time(service, duration);
   3688  }
   3689 
   3690  goto done;
   3691 
   3692 err:
   3693  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOSUCHSERVICE);
   3694 done:
   3695  return;
   3696 }
   3697 
   3698 /** We've been expecting an INTRO_ESTABLISHED cell on this circuit and it just
   3699 * arrived. Handle the INTRO_ESTABLISHED cell arriving on the given
   3700 * introduction circuit. Return 0 on success else a negative value. */
   3701 static int
   3702 service_handle_intro_established(origin_circuit_t *circ,
   3703                                 const uint8_t *payload,
   3704                                 size_t payload_len)
   3705 {
   3706  hs_service_t *service = NULL;
   3707  hs_service_intro_point_t *ip = NULL;
   3708 
   3709  tor_assert(circ);
   3710  tor_assert(payload);
   3711  tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
   3712 
   3713  /* We need the service and intro point for this cell. */
   3714  get_objects_from_ident(circ->hs_ident, &service, &ip, NULL);
   3715 
   3716  /* Get service object from the circuit identifier. */
   3717  if (service == NULL) {
   3718    log_warn(LD_REND, "Unknown service identity key %s on the introduction "
   3719                      "circuit %u. Can't find onion service.",
   3720             safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
   3721             TO_CIRCUIT(circ)->n_circ_id);
   3722    goto err;
   3723  }
   3724  if (ip == NULL) {
   3725    /* We don't recognize the key. */
   3726    log_warn(LD_REND, "Introduction circuit established without an intro "
   3727                      "point object on circuit %u for service %s",
   3728             TO_CIRCUIT(circ)->n_circ_id,
   3729             safe_str_client(service->onion_address));
   3730    goto err;
   3731  }
   3732 
   3733  /* Try to parse the payload into a cell making sure we do actually have a
   3734   * valid cell. On success, the ip object and circuit purpose is updated to
   3735   * reflect the fact that the introduction circuit is established. */
   3736  if (hs_circ_handle_intro_established(service, ip, circ, payload,
   3737                                       payload_len) < 0) {
   3738    goto err;
   3739  }
   3740 
   3741  struct timeval now;
   3742  tor_gettimeofday(&now);
   3743  int64_t duration = tv_mdiff(&TO_CIRCUIT(circ)->timestamp_began, &now);
   3744 
   3745  /* Update metrics. */
   3746  hs_metrics_new_established_intro(service);
   3747  hs_metrics_intro_circ_build_time(service, duration);
   3748 
   3749  log_info(LD_REND, "Successfully received an INTRO_ESTABLISHED cell "
   3750                    "on circuit %u for service %s",
   3751           TO_CIRCUIT(circ)->n_circ_id,
   3752           safe_str_client(service->onion_address));
   3753  return 0;
   3754 
   3755 err:
   3756  return -1;
   3757 }
   3758 
   3759 /** We just received an INTRODUCE2 cell on the established introduction circuit
   3760 * circ. Handle the cell and return 0 on success else a negative value. */
   3761 static int
   3762 service_handle_introduce2(origin_circuit_t *circ, const uint8_t *payload,
   3763                          size_t payload_len)
   3764 {
   3765  hs_service_t *service = NULL;
   3766  hs_service_intro_point_t *ip = NULL;
   3767  hs_service_descriptor_t *desc = NULL;
   3768 
   3769  tor_assert(circ);
   3770  tor_assert(payload);
   3771  tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
   3772 
   3773  /* We'll need every object associated with this circuit. */
   3774  get_objects_from_ident(circ->hs_ident, &service, &ip, &desc);
   3775 
   3776  /* Get service object from the circuit identifier. */
   3777  if (service == NULL) {
   3778    log_warn(LD_BUG, "Unknown service identity key %s when handling "
   3779                     "an INTRODUCE2 cell on circuit %u",
   3780             safe_str_client(ed25519_fmt(&circ->hs_ident->identity_pk)),
   3781             TO_CIRCUIT(circ)->n_circ_id);
   3782    goto err;
   3783  }
   3784  if (ip == NULL) {
   3785    /* We don't recognize the key. */
   3786    log_warn(LD_BUG, "Unknown introduction auth key when handling "
   3787                     "an INTRODUCE2 cell on circuit %u for service %s",
   3788             TO_CIRCUIT(circ)->n_circ_id,
   3789             safe_str_client(service->onion_address));
   3790 
   3791    hs_metrics_reject_intro_req(service,
   3792                                HS_METRICS_ERR_INTRO_REQ_BAD_AUTH_KEY);
   3793    goto err;
   3794  }
   3795  /* If we have an IP object, we MUST have a descriptor object. */
   3796  tor_assert(desc);
   3797 
   3798  /* The following will parse, decode and launch the rendezvous point circuit.
   3799   * Both current and legacy cells are handled. */
   3800  if (hs_circ_handle_introduce2(service, circ, ip, &desc->desc->subcredential,
   3801                                payload, payload_len) < 0) {
   3802    goto err;
   3803  }
   3804  /* Update metrics that a new introduction was successful. */
   3805  hs_metrics_new_introduction(service);
   3806 
   3807  return 0;
   3808 err:
   3809 
   3810  return -1;
   3811 }
   3812 
   3813 /** Add to list every filename used by service. This is used by the sandbox
   3814 * subsystem. */
   3815 static void
   3816 service_add_fnames_to_list(const hs_service_t *service, smartlist_t *list)
   3817 {
   3818  const char *s_dir;
   3819  char fname[128] = {0};
   3820 
   3821  tor_assert(service);
   3822  tor_assert(list);
   3823 
   3824  /* Ease our life. */
   3825  s_dir = service->config.directory_path;
   3826  /* The hostname file. */
   3827  smartlist_add(list, hs_path_from_filename(s_dir, fname_hostname));
   3828  /* The key files split in two. */
   3829  tor_snprintf(fname, sizeof(fname), "%s_secret_key", fname_keyfile_prefix);
   3830  smartlist_add(list, hs_path_from_filename(s_dir, fname));
   3831  tor_snprintf(fname, sizeof(fname), "%s_public_key", fname_keyfile_prefix);
   3832  smartlist_add(list, hs_path_from_filename(s_dir, fname));
   3833 }
   3834 
   3835 /** Return true iff the given service identity key is present on disk. */
   3836 static int
   3837 service_key_on_disk(const char *directory_path)
   3838 {
   3839  int ret = 0;
   3840  char *fname;
   3841  ed25519_keypair_t *kp = NULL;
   3842 
   3843  tor_assert(directory_path);
   3844 
   3845  /* Build the v3 key path name and then try to load it. */
   3846  fname = hs_path_from_filename(directory_path, fname_keyfile_prefix);
   3847  kp = ed_key_init_from_file(fname, INIT_ED_KEY_SPLIT,
   3848                             LOG_DEBUG, NULL, 0, 0, 0, NULL, NULL);
   3849  if (kp) {
   3850    ret = 1;
   3851  }
   3852 
   3853  ed25519_keypair_free(kp);
   3854  tor_free(fname);
   3855 
   3856  return ret;
   3857 }
   3858 
   3859 /** This is a proxy function before actually calling hs_desc_encode_descriptor
   3860 * because we need some preprocessing here */
   3861 static int
   3862 service_encode_descriptor(const hs_service_t *service,
   3863                          const hs_service_descriptor_t *desc,
   3864                          const ed25519_keypair_t *signing_kp,
   3865                          char **encoded_out)
   3866 {
   3867  int ret;
   3868  const uint8_t *descriptor_cookie = NULL;
   3869 
   3870  tor_assert(service);
   3871  tor_assert(desc);
   3872  tor_assert(encoded_out);
   3873 
   3874  /* If the client authorization is enabled, send the descriptor cookie to
   3875   * hs_desc_encode_descriptor. Otherwise, send NULL */
   3876  if (is_client_auth_enabled(service)) {
   3877    descriptor_cookie = desc->descriptor_cookie;
   3878  }
   3879 
   3880  ret = hs_desc_encode_descriptor(desc->desc, signing_kp,
   3881                                  descriptor_cookie, encoded_out);
   3882 
   3883  return ret;
   3884 }
   3885 
   3886 /* ========== */
   3887 /* Public API */
   3888 /* ========== */
   3889 
   3890 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
   3891 */
   3892 static int
   3893 hs_service_non_anonymous_mode_consistent(const or_options_t *options)
   3894 {
   3895  /* !! is used to make these options boolean */
   3896  return (!! options->HiddenServiceSingleHopMode ==
   3897          !! options->HiddenServiceNonAnonymousMode);
   3898 }
   3899 
   3900 /* Do the options allow onion services to make direct (non-anonymous)
   3901 * connections to introduction or rendezvous points?
   3902 * Must only be called after options_validate_single_onion() has successfully
   3903 * checked onion service option consistency.
   3904 * Returns true if tor is in HiddenServiceSingleHopMode. */
   3905 int
   3906 hs_service_allow_non_anonymous_connection(const or_options_t *options)
   3907 {
   3908  tor_assert(hs_service_non_anonymous_mode_consistent(options));
   3909  return options->HiddenServiceSingleHopMode ? 1 : 0;
   3910 }
   3911 
   3912 /* Do the options allow us to reveal the exact startup time of the onion
   3913 * service?
   3914 * Single Onion Services prioritise availability over hiding their
   3915 * startup time, as their IP address is publicly discoverable anyway.
   3916 * Must only be called after options_validate_single_onion() has successfully
   3917 * checked onion service option consistency.
   3918 * Returns true if tor is in non-anonymous hidden service mode. */
   3919 int
   3920 hs_service_reveal_startup_time(const or_options_t *options)
   3921 {
   3922  tor_assert(hs_service_non_anonymous_mode_consistent(options));
   3923  return hs_service_non_anonymous_mode_enabled(options);
   3924 }
   3925 
   3926 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
   3927 * config option?
   3928 * Must only be called after options_validate_single_onion() has successfully
   3929 * checked onion service option consistency.
   3930 */
   3931 int
   3932 hs_service_non_anonymous_mode_enabled(const or_options_t *options)
   3933 {
   3934  tor_assert(hs_service_non_anonymous_mode_consistent(options));
   3935  return options->HiddenServiceNonAnonymousMode ? 1 : 0;
   3936 }
   3937 
   3938 /** Called when a circuit was just cleaned up. This is done right before the
   3939 * circuit is marked for close. */
   3940 void
   3941 hs_service_circuit_cleanup_on_close(const circuit_t *circ)
   3942 {
   3943  tor_assert(circ);
   3944  tor_assert(CIRCUIT_IS_ORIGIN(circ));
   3945 
   3946  switch (circ->purpose) {
   3947  case CIRCUIT_PURPOSE_S_INTRO:
   3948    /* About to close an established introduction circuit. Update the metrics
   3949     * to reflect how many we have at the moment. */
   3950    hs_metrics_close_established_intro(
   3951      &CONST_TO_ORIGIN_CIRCUIT(circ)->hs_ident->identity_pk);
   3952    break;
   3953  case CIRCUIT_PURPOSE_S_REND_JOINED:
   3954    /* About to close an established rendezvous circuit. Update the metrics to
   3955     * reflect how many we have at the moment. */
   3956    hs_metrics_close_established_rdv(
   3957      &CONST_TO_ORIGIN_CIRCUIT(circ)->hs_ident->identity_pk);
   3958    break;
   3959  case CIRCUIT_PURPOSE_S_CONNECT_REND:
   3960    hs_circ_retry_service_rendezvous_point(CONST_TO_ORIGIN_CIRCUIT(circ));
   3961    break;
   3962  default:
   3963    break;
   3964  }
   3965 }
   3966 
   3967 /** This is called every time the service map changes that is if an
   3968 * element is added or removed. */
   3969 void
   3970 hs_service_map_has_changed(void)
   3971 {
   3972  /* If we now have services where previously we had not, we need to enable
   3973   * the HS service main loop event. If we changed to having no services, we
   3974   * need to disable the event. */
   3975  rescan_periodic_events(get_options());
   3976 }
   3977 
   3978 /** Called when a new consensus has arrived and has been set globally. The new
   3979 * consensus is pointed by ns. */
   3980 void
   3981 hs_service_new_consensus_params(const networkstatus_t *ns)
   3982 {
   3983  tor_assert(ns);
   3984 
   3985  /* This value is the new value from the consensus. */
   3986  uint8_t current_sendme_inc = congestion_control_sendme_inc();
   3987 
   3988  if (!hs_service_map)
   3989    return;
   3990 
   3991  /* Check each service and look if their descriptor contains a different
   3992   * sendme increment. If so, nuke all intro points by forcing an expiration
   3993   * which will lead to rebuild and reupload with the new value. */
   3994  FOR_EACH_SERVICE_BEGIN(service) {
   3995    FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   3996      if (desc->desc &&
   3997          desc->desc->encrypted_data.sendme_inc != current_sendme_inc) {
   3998        /* Passing the maximum time_t will force expiration of all intro points
   3999         * and thus will lead to a rebuild of the descriptor. */
   4000        cleanup_intro_points(service, LONG_MAX);
   4001      }
   4002    } FOR_EACH_DESCRIPTOR_END;
   4003  } FOR_EACH_SERVICE_END;
   4004 }
   4005 
   4006 /** Upload an encoded descriptor in encoded_desc of the given version. This
   4007 * descriptor is for the service identity_pk and blinded_pk used to setup the
   4008 * directory connection identifier. It is uploaded to the directory hsdir_rs
   4009 * routerstatus_t object.
   4010 *
   4011 * NOTE: This function does NOT check for PublishHidServDescriptors because it
   4012 * is only used by the control port command HSPOST outside of this subsystem.
   4013 * Inside this code, upload_descriptor_to_hsdir() should be used. */
   4014 void
   4015 hs_service_upload_desc_to_dir(const char *encoded_desc,
   4016                              const uint8_t version,
   4017                              const ed25519_public_key_t *identity_pk,
   4018                              const ed25519_public_key_t *blinded_pk,
   4019                              const routerstatus_t *hsdir_rs)
   4020 {
   4021  char version_str[4] = {0};
   4022  directory_request_t *dir_req;
   4023  hs_ident_dir_conn_t ident;
   4024 
   4025  tor_assert(encoded_desc);
   4026  tor_assert(identity_pk);
   4027  tor_assert(blinded_pk);
   4028  tor_assert(hsdir_rs);
   4029 
   4030  /* Setup the connection identifier. */
   4031  memset(&ident, 0, sizeof(ident));
   4032  hs_ident_dir_conn_init(identity_pk, blinded_pk, &ident);
   4033 
   4034  /* This is our resource when uploading which is used to construct the URL
   4035   * with the version number: "/tor/hs/<version>/publish". */
   4036  tor_snprintf(version_str, sizeof(version_str), "%u", version);
   4037 
   4038  /* Build the directory request for this HSDir. */
   4039  dir_req = directory_request_new(DIR_PURPOSE_UPLOAD_HSDESC);
   4040  directory_request_set_routerstatus(dir_req, hsdir_rs);
   4041  directory_request_set_indirection(dir_req, DIRIND_ANONYMOUS);
   4042  directory_request_set_resource(dir_req, version_str);
   4043  directory_request_set_payload(dir_req, encoded_desc,
   4044                                strlen(encoded_desc));
   4045  /* The ident object is copied over the directory connection object once
   4046   * the directory request is initiated. */
   4047  directory_request_upload_set_hs_ident(dir_req, &ident);
   4048 
   4049  /* Initiate the directory request to the hsdir.*/
   4050  directory_initiate_request(dir_req);
   4051  directory_request_free(dir_req);
   4052 }
   4053 
   4054 /** Add the ephemeral service using the secret key sk and ports. Both max
   4055 * streams parameter will be set in the newly created service.
   4056 *
   4057 * Ownership of sk, ports, and auth_clients_v3 is passed to this routine.
   4058 * Regardless of success/failure, callers should not touch these values
   4059 * after calling this routine, and may assume that correct cleanup has
   4060 * been done on failure.
   4061 *
   4062 * Return an appropriate hs_service_add_ephemeral_status_t. */
   4063 hs_service_add_ephemeral_status_t
   4064 hs_service_add_ephemeral(ed25519_secret_key_t *sk, smartlist_t *ports,
   4065                         int max_streams_per_rdv_circuit,
   4066                         int max_streams_close_circuit,
   4067                         int pow_defenses_enabled,
   4068                         uint32_t pow_queue_rate,
   4069                         uint32_t pow_queue_burst,
   4070                         smartlist_t *auth_clients_v3, char **address_out)
   4071 {
   4072  hs_service_add_ephemeral_status_t ret;
   4073  hs_service_t *service = NULL;
   4074 
   4075  tor_assert(sk);
   4076  tor_assert(ports);
   4077  tor_assert(address_out);
   4078 
   4079  service = hs_service_new(get_options());
   4080 
   4081  /* Setup the service configuration with specifics. A default service is
   4082   * HS_VERSION_TWO so explicitly set it. */
   4083  service->config.version = HS_VERSION_THREE;
   4084  service->config.max_streams_per_rdv_circuit = max_streams_per_rdv_circuit;
   4085  service->config.max_streams_close_circuit = !!max_streams_close_circuit;
   4086  service->config.is_ephemeral = 1;
   4087  smartlist_free(service->config.ports);
   4088  service->config.ports = ports;
   4089  service->config.has_pow_defenses_enabled = pow_defenses_enabled;
   4090  service->config.pow_queue_rate = pow_queue_rate;
   4091  service->config.pow_queue_burst = pow_queue_burst;
   4092 
   4093  /* Handle the keys. */
   4094  memcpy(&service->keys.identity_sk, sk, sizeof(service->keys.identity_sk));
   4095  if (ed25519_public_key_generate(&service->keys.identity_pk,
   4096                                  &service->keys.identity_sk) < 0) {
   4097    log_warn(LD_CONFIG, "Unable to generate ed25519 public key"
   4098                        "for v3 service.");
   4099    ret = RSAE_BADPRIVKEY;
   4100    goto err;
   4101  }
   4102 
   4103  if (ed25519_validate_pubkey(&service->keys.identity_pk) < 0) {
   4104    log_warn(LD_CONFIG, "Bad ed25519 private key was provided");
   4105    ret = RSAE_BADPRIVKEY;
   4106    goto err;
   4107  }
   4108 
   4109  /* Make sure we have at least one port. */
   4110  if (smartlist_len(service->config.ports) == 0) {
   4111    log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified "
   4112                        "for v3 service.");
   4113    ret = RSAE_BADVIRTPORT;
   4114    goto err;
   4115  }
   4116 
   4117  if (auth_clients_v3) {
   4118    service->config.clients = smartlist_new();
   4119    SMARTLIST_FOREACH(auth_clients_v3, hs_service_authorized_client_t *, c, {
   4120      if (c != NULL) {
   4121        smartlist_add(service->config.clients, c);
   4122      }
   4123    });
   4124    smartlist_free(auth_clients_v3);
   4125  }
   4126 
   4127  /* Build the onion address for logging purposes but also the control port
   4128   * uses it for the HS_DESC event. */
   4129  hs_build_address(&service->keys.identity_pk,
   4130                   (uint8_t) service->config.version,
   4131                   service->onion_address);
   4132 
   4133  /* The only way the registration can fail is if the service public key
   4134   * already exists. */
   4135  if (BUG(register_service(hs_service_map, service) < 0)) {
   4136    log_warn(LD_CONFIG, "Onion Service private key collides with an "
   4137                        "existing v3 service.");
   4138    ret = RSAE_ADDREXISTS;
   4139    goto err;
   4140  }
   4141 
   4142  log_info(LD_CONFIG, "Added ephemeral v3 onion service: %s",
   4143           safe_str_client(service->onion_address));
   4144 
   4145  *address_out = tor_strdup(service->onion_address);
   4146  ret = RSAE_OKAY;
   4147  goto end;
   4148 
   4149 err:
   4150  hs_service_free(service);
   4151 
   4152 end:
   4153  memwipe(sk, 0, sizeof(ed25519_secret_key_t));
   4154  tor_free(sk);
   4155  return ret;
   4156 }
   4157 
   4158 /** For the given onion address, delete the ephemeral service. Return 0 on
   4159 * success else -1 on error. */
   4160 int
   4161 hs_service_del_ephemeral(const char *address)
   4162 {
   4163  uint8_t version;
   4164  ed25519_public_key_t pk;
   4165  hs_service_t *service = NULL;
   4166 
   4167  tor_assert(address);
   4168 
   4169  if (hs_parse_address(address, &pk, NULL, &version) < 0) {
   4170    log_warn(LD_CONFIG, "Requested malformed v3 onion address for removal.");
   4171    goto err;
   4172  }
   4173 
   4174  if (version != HS_VERSION_THREE) {
   4175    log_warn(LD_CONFIG, "Requested version of onion address for removal "
   4176                        "is not supported.");
   4177    goto err;
   4178  }
   4179 
   4180  service = find_service(hs_service_map, &pk);
   4181  if (service == NULL) {
   4182    log_warn(LD_CONFIG, "Requested non-existent v3 hidden service for "
   4183                        "removal.");
   4184    goto err;
   4185  }
   4186 
   4187  if (!service->config.is_ephemeral) {
   4188    log_warn(LD_CONFIG, "Requested non-ephemeral v3 hidden service for "
   4189                        "removal.");
   4190    goto err;
   4191  }
   4192 
   4193  /* Close introduction circuits, remove from map and finally free. Notice
   4194   * that the rendezvous circuits aren't closed in order for any existing
   4195   * connections to finish. We let the application terminate them. */
   4196  close_service_intro_circuits(service);
   4197  remove_service(hs_service_map, service);
   4198  hs_service_free(service);
   4199 
   4200  log_info(LD_CONFIG, "Removed ephemeral v3 hidden service: %s",
   4201           safe_str_client(address));
   4202  return 0;
   4203 
   4204 err:
   4205  return -1;
   4206 }
   4207 
   4208 /** Using the ed25519 public key pk, find a service for that key and return the
   4209 * current encoded descriptor as a newly allocated string or NULL if not
   4210 * found. This is used by the control port subsystem. */
   4211 char *
   4212 hs_service_lookup_current_desc(const ed25519_public_key_t *pk)
   4213 {
   4214  const hs_service_t *service;
   4215 
   4216  tor_assert(pk);
   4217 
   4218  service = find_service(hs_service_map, pk);
   4219  if (service && service->desc_current) {
   4220    char *encoded_desc = NULL;
   4221    /* No matter what is the result (which should never be a failure), return
   4222     * the encoded variable, if success it will contain the right thing else
   4223     * it will be NULL. */
   4224    service_encode_descriptor(service,
   4225                              service->desc_current,
   4226                              &service->desc_current->signing_kp,
   4227                              &encoded_desc);
   4228    return encoded_desc;
   4229  }
   4230 
   4231  return NULL;
   4232 }
   4233 
   4234 /** Return the number of service we have configured and usable. */
   4235 MOCK_IMPL(unsigned int,
   4236 hs_service_get_num_services,(void))
   4237 {
   4238  if (hs_service_map == NULL) {
   4239    return 0;
   4240  }
   4241  return HT_SIZE(hs_service_map);
   4242 }
   4243 
   4244 /** Given conn, a rendezvous edge connection acting as an exit stream, look up
   4245 * the hidden service for the circuit circ, and look up the port and address
   4246 * based on the connection port. Assign the actual connection address.
   4247 *
   4248 * Return 0 on success. Return -1 on failure and the caller should NOT close
   4249 * the circuit. Return -2 on failure and the caller MUST close the circuit for
   4250 * security reasons. */
   4251 int
   4252 hs_service_set_conn_addr_port(const origin_circuit_t *circ,
   4253                              edge_connection_t *conn)
   4254 {
   4255  hs_service_t *service = NULL;
   4256 
   4257  tor_assert(circ);
   4258  tor_assert(conn);
   4259  tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
   4260  tor_assert(circ->hs_ident);
   4261 
   4262  get_objects_from_ident(circ->hs_ident, &service, NULL, NULL);
   4263 
   4264  if (service == NULL) {
   4265    log_warn(LD_REND, "Unable to find any hidden service associated "
   4266                      "identity key %s on rendezvous circuit %u.",
   4267             ed25519_fmt(&circ->hs_ident->identity_pk),
   4268             TO_CIRCUIT(circ)->n_circ_id);
   4269    /* We want the caller to close the circuit because it's not a valid
   4270     * service so no danger. Attempting to bruteforce the entire key space by
   4271     * opening circuits to learn which service is being hosted here is
   4272     * impractical. */
   4273    goto err_close;
   4274  }
   4275 
   4276  /* Enforce the streams-per-circuit limit, and refuse to provide a mapping if
   4277   * this circuit will exceed the limit. */
   4278  if (service->config.max_streams_per_rdv_circuit > 0 &&
   4279      (circ->hs_ident->num_rdv_streams >=
   4280       service->config.max_streams_per_rdv_circuit)) {
   4281 #define MAX_STREAM_WARN_INTERVAL 600
   4282    static struct ratelim_t stream_ratelim =
   4283      RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
   4284    log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
   4285                   "Maximum streams per circuit limit reached on "
   4286                   "rendezvous circuit %u for service %s. Circuit has "
   4287                   "%" PRIu64 " out of %" PRIu64 " streams. %s.",
   4288                   TO_CIRCUIT(circ)->n_circ_id,
   4289                   service->onion_address,
   4290                   circ->hs_ident->num_rdv_streams,
   4291                   service->config.max_streams_per_rdv_circuit,
   4292                   service->config.max_streams_close_circuit ?
   4293                    "Closing circuit" : "Ignoring open stream request");
   4294    if (service->config.max_streams_close_circuit) {
   4295      /* Service explicitly configured to close immediately. */
   4296      goto err_close;
   4297    }
   4298    /* Exceeding the limit makes tor silently ignore the stream creation
   4299     * request and keep the circuit open. */
   4300    goto err_no_close;
   4301  }
   4302 
   4303  /* Find a virtual port of that service matching the one in the connection if
   4304   * successful, set the address in the connection. */
   4305  if (hs_set_conn_addr_port(service->config.ports, conn) < 0) {
   4306    log_info(LD_REND, "No virtual port mapping exists for port %d for "
   4307                      "hidden service %s.",
   4308             TO_CONN(conn)->port, service->onion_address);
   4309    if (service->config.allow_unknown_ports) {
   4310      /* Service explicitly allow connection to unknown ports so close right
   4311       * away because we do not care about port mapping. */
   4312      goto err_close;
   4313    }
   4314    /* If the service didn't explicitly allow it, we do NOT close the circuit
   4315     * here to raise the bar in terms of performance for port mapping. */
   4316    goto err_no_close;
   4317  }
   4318 
   4319  /* Success. */
   4320  return 0;
   4321 err_close:
   4322  /* Indicate the caller that the circuit should be closed. */
   4323  return -2;
   4324 err_no_close:
   4325  /* Indicate the caller to NOT close the circuit. */
   4326  return -1;
   4327 }
   4328 
   4329 /** Does the service with identity pubkey <b>pk</b> export the circuit IDs of
   4330 *  its clients?  */
   4331 hs_circuit_id_protocol_t
   4332 hs_service_exports_circuit_id(const ed25519_public_key_t *pk)
   4333 {
   4334  hs_service_t *service = find_service(hs_service_map, pk);
   4335  if (!service) {
   4336    return HS_CIRCUIT_ID_PROTOCOL_NONE;
   4337  }
   4338 
   4339  return service->config.circuit_id_protocol;
   4340 }
   4341 
   4342 /** Add to file_list every filename used by a configured hidden service, and to
   4343 * dir_list every directory path used by a configured hidden service. This is
   4344 * used by the sandbox subsystem to allowlist those. */
   4345 void
   4346 hs_service_lists_fnames_for_sandbox(smartlist_t *file_list,
   4347                                    smartlist_t *dir_list)
   4348 {
   4349  tor_assert(file_list);
   4350  tor_assert(dir_list);
   4351 
   4352  /* Add files and dirs for v3+. */
   4353  FOR_EACH_SERVICE_BEGIN(service) {
   4354    /* Skip ephemeral service, they don't touch the disk. */
   4355    if (service->config.is_ephemeral) {
   4356      continue;
   4357    }
   4358    service_add_fnames_to_list(service, file_list);
   4359    smartlist_add_strdup(dir_list, service->config.directory_path);
   4360    smartlist_add_strdup(dir_list, dname_client_pubkeys);
   4361  } FOR_EACH_DESCRIPTOR_END;
   4362 }
   4363 
   4364 /** Called when our internal view of the directory has changed. We might have
   4365 * received a new batch of descriptors which might affect the shape of the
   4366 * HSDir hash ring. Signal that we should reexamine the hash ring and
   4367 * re-upload our HS descriptors if needed. */
   4368 void
   4369 hs_service_dir_info_changed(void)
   4370 {
   4371  if (hs_service_get_num_services() > 0) {
   4372    /* New directory information usually goes every consensus so rate limit
   4373     * every 30 minutes to not be too conservative. */
   4374    static struct ratelim_t dir_info_changed_ratelim = RATELIM_INIT(30 * 60);
   4375    log_fn_ratelim(&dir_info_changed_ratelim, LOG_INFO, LD_REND,
   4376                   "New dirinfo arrived: consider reuploading descriptor");
   4377    consider_republishing_hs_descriptors = 1;
   4378  }
   4379 }
   4380 
   4381 /** Called when we get an INTRODUCE2 cell on the circ. Respond to the cell and
   4382 * launch a circuit to the rendezvous point. */
   4383 int
   4384 hs_service_receive_introduce2(origin_circuit_t *circ, const uint8_t *payload,
   4385                              size_t payload_len)
   4386 {
   4387  int ret = -1;
   4388 
   4389  tor_assert(circ);
   4390  tor_assert(payload);
   4391 
   4392  /* Do some initial validation and logging before we parse the cell */
   4393  if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_INTRO) {
   4394    log_warn(LD_PROTOCOL, "Received an INTRODUCE2 cell on a "
   4395                          "non introduction circuit of purpose %d",
   4396             TO_CIRCUIT(circ)->purpose);
   4397    goto done;
   4398  }
   4399 
   4400  if (circ->hs_ident) {
   4401    ret = service_handle_introduce2(circ, payload, payload_len);
   4402    hs_stats_note_introduce2_cell();
   4403  }
   4404 
   4405 done:
   4406  return ret;
   4407 }
   4408 
   4409 /** Called when we get an INTRO_ESTABLISHED cell. Mark the circuit as an
   4410 * established introduction point. Return 0 on success else a negative value
   4411 * and the circuit is closed. */
   4412 int
   4413 hs_service_receive_intro_established(origin_circuit_t *circ,
   4414                                     const uint8_t *payload,
   4415                                     size_t payload_len)
   4416 {
   4417  int ret = -1;
   4418 
   4419  tor_assert(circ);
   4420  tor_assert(payload);
   4421 
   4422  if (TO_CIRCUIT(circ)->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
   4423    log_warn(LD_PROTOCOL, "Received an INTRO_ESTABLISHED cell on a "
   4424                          "non introduction circuit of purpose %d",
   4425             TO_CIRCUIT(circ)->purpose);
   4426    goto err;
   4427  }
   4428 
   4429  if (circ->hs_ident) {
   4430    ret = service_handle_intro_established(circ, payload, payload_len);
   4431  }
   4432 
   4433  if (ret < 0) {
   4434    goto err;
   4435  }
   4436  return 0;
   4437 err:
   4438  circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
   4439  return -1;
   4440 }
   4441 
   4442 /** Called when any kind of hidden service circuit is done building thus
   4443 * opened. This is the entry point from the circuit subsystem. */
   4444 void
   4445 hs_service_circuit_has_opened(origin_circuit_t *circ)
   4446 {
   4447  tor_assert(circ);
   4448 
   4449  switch (TO_CIRCUIT(circ)->purpose) {
   4450  case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
   4451    if (circ->hs_ident) {
   4452      service_intro_circ_has_opened(circ);
   4453    }
   4454    break;
   4455  case CIRCUIT_PURPOSE_S_CONNECT_REND:
   4456    if (circ->hs_ident) {
   4457      service_rendezvous_circ_has_opened(circ);
   4458    }
   4459    break;
   4460  default:
   4461    tor_assert(0);
   4462  }
   4463 }
   4464 
   4465 /** Return the service version by looking at the key in the service directory.
   4466 * If the key is not found or unrecognized, -1 is returned. Else, the service
   4467 * version is returned. */
   4468 int
   4469 hs_service_get_version_from_key(const hs_service_t *service)
   4470 {
   4471  int version = -1; /* Unknown version. */
   4472  const char *directory_path;
   4473 
   4474  tor_assert(service);
   4475 
   4476  /* We'll try to load the key for version 3. If not found, we'll try version
   4477   * 2 and if not found, we'll send back an unknown version (-1). */
   4478  directory_path = service->config.directory_path;
   4479 
   4480  /* Version 3 check. */
   4481  if (service_key_on_disk(directory_path)) {
   4482    version = HS_VERSION_THREE;
   4483    goto end;
   4484  }
   4485 
   4486 end:
   4487  return version;
   4488 }
   4489 
   4490 /** Load and/or generate keys for all onion services including the client
   4491 * authorization if any. Return 0 on success, -1 on failure. */
   4492 int
   4493 hs_service_load_all_keys(void)
   4494 {
   4495  /* Load or/and generate them for v3+. */
   4496  SMARTLIST_FOREACH_BEGIN(hs_service_staging_list, hs_service_t *, service) {
   4497    /* Ignore ephemeral service, they already have their keys set. */
   4498    if (service->config.is_ephemeral) {
   4499      continue;
   4500    }
   4501    log_info(LD_REND, "Loading v3 onion service keys from %s",
   4502             service_escaped_dir(service));
   4503    if (load_service_keys(service) < 0) {
   4504      goto err;
   4505    }
   4506  } SMARTLIST_FOREACH_END(service);
   4507 
   4508  /* Final step, the staging list contains service in a quiescent state that
   4509   * is ready to be used. Register them to the global map. Once this is over,
   4510   * the staging list will be cleaned up. */
   4511  register_all_services();
   4512 
   4513  /* All keys have been loaded successfully. */
   4514  return 0;
   4515 err:
   4516  return -1;
   4517 }
   4518 
   4519 /** Log the status of introduction points for all version 3 onion services
   4520 * at log severity <b>severity</b>.
   4521 */
   4522 void
   4523 hs_service_dump_stats(int severity)
   4524 {
   4525  origin_circuit_t *circ;
   4526 
   4527  FOR_EACH_SERVICE_BEGIN(hs) {
   4528 
   4529    tor_log(severity, LD_GENERAL, "Service configured in %s:",
   4530            service_escaped_dir(hs));
   4531    FOR_EACH_DESCRIPTOR_BEGIN(hs, desc) {
   4532 
   4533      DIGEST256MAP_FOREACH(desc->intro_points.map, key,
   4534                           hs_service_intro_point_t *, ip) {
   4535        const node_t *intro_node;
   4536        const char *nickname;
   4537 
   4538        intro_node = get_node_from_intro_point(ip);
   4539        if (!intro_node) {
   4540          tor_log(severity, LD_GENERAL, "  Couldn't find intro point, "
   4541                  "skipping");
   4542          continue;
   4543        }
   4544        nickname = node_get_nickname(intro_node);
   4545        if (!nickname) {
   4546          continue;
   4547        }
   4548 
   4549        circ = hs_circ_service_get_intro_circ(ip);
   4550        if (!circ) {
   4551          tor_log(severity, LD_GENERAL, "  Intro point at %s: no circuit",
   4552                  nickname);
   4553          continue;
   4554        }
   4555        tor_log(severity, LD_GENERAL, "  Intro point %s: circuit is %s",
   4556                nickname, circuit_state_to_string(circ->base_.state));
   4557      } DIGEST256MAP_FOREACH_END;
   4558 
   4559    } FOR_EACH_DESCRIPTOR_END;
   4560  } FOR_EACH_SERVICE_END;
   4561 }
   4562 
   4563 /** Put all service object in the given service list. After this, the caller
   4564 * looses ownership of every elements in the list and responsible to free the
   4565 * list pointer. */
   4566 void
   4567 hs_service_stage_services(const smartlist_t *service_list)
   4568 {
   4569  tor_assert(service_list);
   4570  /* This list is freed at registration time but this function can be called
   4571   * multiple time. */
   4572  if (hs_service_staging_list == NULL) {
   4573    hs_service_staging_list = smartlist_new();
   4574  }
   4575  /* Add all service object to our staging list. Caller is responsible for
   4576   * freeing the service_list. */
   4577  smartlist_add_all(hs_service_staging_list, service_list);
   4578 }
   4579 
   4580 /** Return a newly allocated list of all the service's metrics store. */
   4581 smartlist_t *
   4582 hs_service_get_metrics_stores(void)
   4583 {
   4584  smartlist_t *list = smartlist_new();
   4585 
   4586  if (hs_service_map) {
   4587    FOR_EACH_SERVICE_BEGIN(service) {
   4588      smartlist_add(list, service->metrics.store);
   4589    } FOR_EACH_SERVICE_END;
   4590  }
   4591 
   4592  return list;
   4593 }
   4594 
   4595 /** Lookup the global service map for the given identitiy public key and
   4596 * return the service object if found, NULL if not. */
   4597 hs_service_t *
   4598 hs_service_find(const ed25519_public_key_t *identity_pk)
   4599 {
   4600  tor_assert(identity_pk);
   4601 
   4602  if (!hs_service_map) {
   4603    return NULL;
   4604  }
   4605  return find_service(hs_service_map, identity_pk);
   4606 }
   4607 
   4608 /** Allocate and initialize a service object. The service configuration will
   4609 * contain the default values. Return the newly allocated object pointer. This
   4610 * function can't fail. */
   4611 hs_service_t *
   4612 hs_service_new(const or_options_t *options)
   4613 {
   4614  hs_service_t *service = tor_malloc_zero(sizeof(hs_service_t));
   4615  /* Set default configuration value. */
   4616  set_service_default_config(&service->config, options);
   4617  /* Set the default service version. */
   4618  service->config.version = HS_SERVICE_DEFAULT_VERSION;
   4619  /* Allocate the CLIENT_PK replay cache in service state. */
   4620  service->state.replay_cache_rend_cookie =
   4621    replaycache_new(REND_REPLAY_TIME_INTERVAL, REND_REPLAY_TIME_INTERVAL);
   4622 
   4623  return service;
   4624 }
   4625 
   4626 /** Free the given <b>service</b> object and all its content. This function
   4627 * also takes care of wiping service keys from memory. It is safe to pass a
   4628 * NULL pointer. */
   4629 void
   4630 hs_service_free_(hs_service_t *service)
   4631 {
   4632  if (service == NULL) {
   4633    return;
   4634  }
   4635 
   4636  /* Free descriptors. Go over both descriptor with this loop. */
   4637  FOR_EACH_DESCRIPTOR_BEGIN(service, desc) {
   4638    service_descriptor_free(desc);
   4639  } FOR_EACH_DESCRIPTOR_END;
   4640 
   4641  /* Free the state of the PoW defenses. */
   4642  hs_pow_free_service_state(service->state.pow_state);
   4643 
   4644  /* Free service configuration. */
   4645  service_clear_config(&service->config);
   4646 
   4647  /* Free replay cache from state. */
   4648  if (service->state.replay_cache_rend_cookie) {
   4649    replaycache_free(service->state.replay_cache_rend_cookie);
   4650  }
   4651 
   4652  /* Free onionbalance subcredentials (if any) */
   4653  if (service->state.ob_subcreds) {
   4654    tor_free(service->state.ob_subcreds);
   4655  }
   4656 
   4657  /* Free metrics object. */
   4658  hs_metrics_service_free(service);
   4659 
   4660  /* Wipe service keys. */
   4661  memwipe(&service->keys.identity_sk, 0, sizeof(service->keys.identity_sk));
   4662 
   4663  tor_free(service);
   4664 }
   4665 
   4666 /** Periodic callback. Entry point from the main loop to the HS service
   4667 * subsystem. This is call every second. This is skipped if tor can't build a
   4668 * circuit or the network is disabled. */
   4669 void
   4670 hs_service_run_scheduled_events(time_t now)
   4671 {
   4672  /* First thing we'll do here is to make sure our services are in a
   4673   * quiescent state for the scheduled events. */
   4674  run_housekeeping_event(now);
   4675 
   4676  /* Order matters here. We first make sure the descriptor object for each
   4677   * service contains the latest data. Once done, we check if we need to open
   4678   * new introduction circuit. Finally, we try to upload the descriptor for
   4679   * each service. */
   4680 
   4681  /* Make sure descriptors are up to date. */
   4682  run_build_descriptor_event(now);
   4683  /* Make sure services have enough circuits. */
   4684  run_build_circuit_event(now);
   4685  /* Upload the descriptors if needed/possible. */
   4686  run_upload_descriptor_event(now);
   4687 }
   4688 
   4689 /** Initialize the service HS subsystem. */
   4690 void
   4691 hs_service_init(void)
   4692 {
   4693  /* Should never be called twice. */
   4694  tor_assert(!hs_service_map);
   4695  tor_assert(!hs_service_staging_list);
   4696 
   4697  hs_service_map = tor_malloc_zero(sizeof(struct hs_service_ht));
   4698  HT_INIT(hs_service_ht, hs_service_map);
   4699 
   4700  hs_service_staging_list = smartlist_new();
   4701 }
   4702 
   4703 /** Release all global storage of the hidden service subsystem. */
   4704 void
   4705 hs_service_free_all(void)
   4706 {
   4707  service_free_all();
   4708  hs_config_free_all();
   4709 }
   4710 
   4711 #ifdef TOR_UNIT_TESTS
   4712 
   4713 /** Return the global service map size. Only used by unit test. */
   4714 STATIC unsigned int
   4715 get_hs_service_map_size(void)
   4716 {
   4717  return HT_SIZE(hs_service_map);
   4718 }
   4719 
   4720 /** Return the staging list size. Only used by unit test. */
   4721 STATIC int
   4722 get_hs_service_staging_list_size(void)
   4723 {
   4724  return smartlist_len(hs_service_staging_list);
   4725 }
   4726 
   4727 STATIC hs_service_ht *
   4728 get_hs_service_map(void)
   4729 {
   4730  return hs_service_map;
   4731 }
   4732 
   4733 STATIC hs_service_t *
   4734 get_first_service(void)
   4735 {
   4736  hs_service_t **obj = HT_START(hs_service_ht, hs_service_map);
   4737  if (obj == NULL) {
   4738    return NULL;
   4739  }
   4740  return *obj;
   4741 }
   4742 
   4743 #endif /* defined(TOR_UNIT_TESTS) */