Merge branch 'maint-0.4.8'
[tor.git] / src / feature / hs / hs_common.c
blobe16ec89ccb51a5fb4d64fb4e1bc556c08ac2e9fe
1 /* Copyright (c) 2016-2021, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file hs_common.c
6 * \brief Contains code shared between different HS protocol version as well
7 * as useful data structures and accessors used by other subsystems.
8 **/
10 #define HS_COMMON_PRIVATE
12 #include "core/or/or.h"
14 #include "app/config/config.h"
15 #include "core/or/circuitbuild.h"
16 #include "core/or/policies.h"
17 #include "core/or/extendinfo.h"
18 #include "feature/dirauth/shared_random_state.h"
19 #include "feature/hs/hs_cache.h"
20 #include "feature/hs/hs_circuitmap.h"
21 #include "feature/hs/hs_client.h"
22 #include "feature/hs/hs_common.h"
23 #include "feature/hs/hs_dos.h"
24 #include "feature/hs/hs_ob.h"
25 #include "feature/hs/hs_ident.h"
26 #include "feature/hs/hs_service.h"
27 #include "feature/hs_common/shared_random_client.h"
28 #include "feature/nodelist/describe.h"
29 #include "feature/nodelist/microdesc.h"
30 #include "feature/nodelist/networkstatus.h"
31 #include "feature/nodelist/nodelist.h"
32 #include "feature/nodelist/routerset.h"
33 #include "feature/rend/rendcommon.h"
34 #include "feature/relay/routermode.h"
35 #include "lib/crypt_ops/crypto_rand.h"
36 #include "lib/crypt_ops/crypto_util.h"
37 #include "lib/net/resolve.h"
39 #include "core/or/edge_connection_st.h"
40 #include "feature/nodelist/networkstatus_st.h"
41 #include "feature/nodelist/node_st.h"
42 #include "core/or/origin_circuit_st.h"
43 #include "feature/nodelist/routerstatus_st.h"
45 /* Trunnel */
46 #include "trunnel/ed25519_cert.h"
48 /** Ed25519 Basepoint value. Taken from section 5 of
49 * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03 */
50 static const char *str_ed25519_basepoint =
51 "(15112221349535400772501151409588531511"
52 "454012693041857206046113283949847762202, "
53 "463168356949264781694283940034751631413"
54 "07993866256225615783033603165251855960)";
56 #ifdef HAVE_SYS_UN_H
58 /** Given <b>ports</b>, a smartlist containing hs_port_config_t,
59 * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
60 * else return -ENOSYS if AF_UNIX is not supported (see function in the
61 * #else statement below). */
62 static int
63 add_unix_port(smartlist_t *ports, hs_port_config_t *p)
65 tor_assert(ports);
66 tor_assert(p);
67 tor_assert(p->is_unix_addr);
69 smartlist_add(ports, p);
70 return 0;
73 /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
74 * on success else return -ENOSYS if AF_UNIX is not supported (see function
75 * in the #else statement below). */
76 static int
77 set_unix_port(edge_connection_t *conn, hs_port_config_t *p)
79 tor_assert(conn);
80 tor_assert(p);
81 tor_assert(p->is_unix_addr);
83 conn->base_.socket_family = AF_UNIX;
84 tor_addr_make_unspec(&conn->base_.addr);
85 conn->base_.port = 1;
86 conn->base_.address = tor_strdup(p->unix_addr);
87 return 0;
90 #else /* !defined(HAVE_SYS_UN_H) */
92 static int
93 set_unix_port(edge_connection_t *conn, hs_port_config_t *p)
95 (void) conn;
96 (void) p;
97 return -ENOSYS;
100 static int
101 add_unix_port(smartlist_t *ports, hs_port_config_t *p)
103 (void) ports;
104 (void) p;
105 return -ENOSYS;
108 #endif /* defined(HAVE_SYS_UN_H) */
110 /** Helper function: The key is a digest that we compare to a node_t object
111 * current hsdir_index. */
112 static int
113 compare_digest_to_fetch_hsdir_index(const void *_key, const void **_member)
115 const char *key = _key;
116 const node_t *node = *_member;
117 return tor_memcmp(key, node->hsdir_index.fetch, DIGEST256_LEN);
120 /** Helper function: The key is a digest that we compare to a node_t object
121 * next hsdir_index. */
122 static int
123 compare_digest_to_store_first_hsdir_index(const void *_key,
124 const void **_member)
126 const char *key = _key;
127 const node_t *node = *_member;
128 return tor_memcmp(key, node->hsdir_index.store_first, DIGEST256_LEN);
131 /** Helper function: The key is a digest that we compare to a node_t object
132 * next hsdir_index. */
133 static int
134 compare_digest_to_store_second_hsdir_index(const void *_key,
135 const void **_member)
137 const char *key = _key;
138 const node_t *node = *_member;
139 return tor_memcmp(key, node->hsdir_index.store_second, DIGEST256_LEN);
142 /** Helper function: Compare two node_t objects current hsdir_index. */
143 static int
144 compare_node_fetch_hsdir_index(const void **a, const void **b)
146 const node_t *node1= *a;
147 const node_t *node2 = *b;
148 return tor_memcmp(node1->hsdir_index.fetch,
149 node2->hsdir_index.fetch,
150 DIGEST256_LEN);
153 /** Helper function: Compare two node_t objects next hsdir_index. */
154 static int
155 compare_node_store_first_hsdir_index(const void **a, const void **b)
157 const node_t *node1= *a;
158 const node_t *node2 = *b;
159 return tor_memcmp(node1->hsdir_index.store_first,
160 node2->hsdir_index.store_first,
161 DIGEST256_LEN);
164 /** Helper function: Compare two node_t objects next hsdir_index. */
165 static int
166 compare_node_store_second_hsdir_index(const void **a, const void **b)
168 const node_t *node1= *a;
169 const node_t *node2 = *b;
170 return tor_memcmp(node1->hsdir_index.store_second,
171 node2->hsdir_index.store_second,
172 DIGEST256_LEN);
175 /** Allocate and return a string containing the path to filename in directory.
176 * This function will never return NULL. The caller must free this path. */
177 char *
178 hs_path_from_filename(const char *directory, const char *filename)
180 char *file_path = NULL;
182 tor_assert(directory);
183 tor_assert(filename);
185 tor_asprintf(&file_path, "%s%s%s", directory, PATH_SEPARATOR, filename);
186 return file_path;
189 /** Make sure that the directory for <b>service</b> is private, using the
190 * config <b>username</b>.
192 * If <b>create</b> is true:
193 * - if the directory exists, change permissions if needed,
194 * - if the directory does not exist, create it with the correct permissions.
195 * If <b>create</b> is false:
196 * - if the directory exists, check permissions,
197 * - if the directory does not exist, check if we think we can create it.
198 * Return 0 on success, -1 on failure. */
200 hs_check_service_private_dir(const char *username, const char *path,
201 unsigned int dir_group_readable,
202 unsigned int create)
204 cpd_check_t check_opts = CPD_NONE;
206 tor_assert(path);
208 if (create) {
209 check_opts |= CPD_CREATE;
210 } else {
211 check_opts |= CPD_CHECK_MODE_ONLY;
212 check_opts |= CPD_CHECK;
214 if (dir_group_readable) {
215 check_opts |= CPD_GROUP_READ;
217 /* Check/create directory */
218 if (check_private_dir(path, check_opts, username) < 0) {
219 return -1;
221 return 0;
224 /* Default, minimum, and maximum values for the maximum rendezvous failures
225 * consensus parameter. */
226 #define MAX_REND_FAILURES_DEFAULT 2
227 #define MAX_REND_FAILURES_MIN 1
228 #define MAX_REND_FAILURES_MAX 10
230 /** How many times will a hidden service operator attempt to connect to
231 * a requested rendezvous point before giving up? */
233 hs_get_service_max_rend_failures(void)
235 return networkstatus_get_param(NULL, "hs_service_max_rdv_failures",
236 MAX_REND_FAILURES_DEFAULT,
237 MAX_REND_FAILURES_MIN,
238 MAX_REND_FAILURES_MAX);
241 /** Get the default HS time period length in minutes from the consensus. */
242 STATIC uint64_t
243 get_time_period_length(void)
245 /* If we are on a test network, make the time period smaller than normal so
246 that we actually see it rotate. Specifically, make it the same length as
247 an SRV protocol run. */
248 if (get_options()->TestingTorNetwork) {
249 unsigned run_duration = sr_state_get_protocol_run_duration();
250 /* An SRV run should take more than a minute (it's 24 rounds) */
251 tor_assert_nonfatal(run_duration > 60);
252 /* Turn it from seconds to minutes before returning: */
253 return sr_state_get_protocol_run_duration() / 60;
256 int32_t time_period_length = networkstatus_get_param(NULL, "hsdir_interval",
257 HS_TIME_PERIOD_LENGTH_DEFAULT,
258 HS_TIME_PERIOD_LENGTH_MIN,
259 HS_TIME_PERIOD_LENGTH_MAX);
260 /* Make sure it's a positive value. */
261 tor_assert(time_period_length > 0);
262 /* uint64_t will always be able to contain a positive int32_t */
263 return (uint64_t) time_period_length;
266 /** Get the HS time period number at time <b>now</b>. If <b>now</b> is not set,
267 * we try to get the time ourselves from a live consensus. */
268 uint64_t
269 hs_get_time_period_num(time_t now)
271 uint64_t time_period_num;
272 time_t current_time;
274 /* If no time is specified, set current time based on consensus time, and
275 * only fall back to system time if that fails. */
276 if (now != 0) {
277 current_time = now;
278 } else {
279 networkstatus_t *ns =
280 networkstatus_get_reasonably_live_consensus(approx_time(),
281 usable_consensus_flavor());
282 current_time = ns ? ns->valid_after : approx_time();
285 /* Start by calculating minutes since the epoch */
286 uint64_t time_period_length = get_time_period_length();
287 uint64_t minutes_since_epoch = current_time / 60;
289 /* Apply the rotation offset as specified by prop224 (section
290 * [TIME-PERIODS]), so that new time periods synchronize nicely with SRV
291 * publication */
292 unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
293 time_period_rotation_offset /= 60; /* go from seconds to minutes */
294 tor_assert(minutes_since_epoch > time_period_rotation_offset);
295 minutes_since_epoch -= time_period_rotation_offset;
297 /* Calculate the time period */
298 time_period_num = minutes_since_epoch / time_period_length;
299 return time_period_num;
302 /** Get the number of the _upcoming_ HS time period, given that the current
303 * time is <b>now</b>. If <b>now</b> is not set, we try to get the time from a
304 * live consensus. */
305 uint64_t
306 hs_get_next_time_period_num(time_t now)
308 return hs_get_time_period_num(now) + 1;
311 /** Get the number of the _previous_ HS time period, given that the current
312 * time is <b>now</b>. If <b>now</b> is not set, we try to get the time from a
313 * live consensus. */
314 uint64_t
315 hs_get_previous_time_period_num(time_t now)
317 return hs_get_time_period_num(now) - 1;
320 /** Return the start time of the upcoming time period based on <b>now</b>. If
321 * <b>now</b> is not set, we try to get the time ourselves from a live
322 * consensus. */
323 time_t
324 hs_get_start_time_of_next_time_period(time_t now)
326 uint64_t time_period_length = get_time_period_length();
328 /* Get start time of next time period */
329 uint64_t next_time_period_num = hs_get_next_time_period_num(now);
330 uint64_t start_of_next_tp_in_mins = next_time_period_num *time_period_length;
332 /* Apply rotation offset as specified by prop224 section [TIME-PERIODS] */
333 unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
334 return (time_t)(start_of_next_tp_in_mins * 60 + time_period_rotation_offset);
337 /** Using the given time period number, compute the disaster shared random
338 * value and put it in srv_out. It MUST be at least DIGEST256_LEN bytes. */
339 static void
340 compute_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
342 crypto_digest_t *digest;
344 tor_assert(srv_out);
346 digest = crypto_digest256_new(DIGEST_SHA3_256);
348 /* Start setting up payload:
349 * H("shared-random-disaster" | INT_8(period_length) | INT_8(period_num)) */
350 crypto_digest_add_bytes(digest, HS_SRV_DISASTER_PREFIX,
351 HS_SRV_DISASTER_PREFIX_LEN);
353 /* Setup INT_8(period_length) | INT_8(period_num) */
355 uint64_t time_period_length = get_time_period_length();
356 char period_stuff[sizeof(uint64_t)*2];
357 size_t offset = 0;
358 set_uint64(period_stuff, tor_htonll(time_period_length));
359 offset += sizeof(uint64_t);
360 set_uint64(period_stuff+offset, tor_htonll(time_period_num));
361 offset += sizeof(uint64_t);
362 tor_assert(offset == sizeof(period_stuff));
364 crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
367 crypto_digest_get_digest(digest, (char *) srv_out, DIGEST256_LEN);
368 crypto_digest_free(digest);
371 /** Due to the high cost of computing the disaster SRV and that potentially we
372 * would have to do it thousands of times in a row, we always cache the
373 * computer disaster SRV (and its corresponding time period num) in case we
374 * want to reuse it soon after. We need to cache two SRVs, one for each active
375 * time period.
377 static uint8_t cached_disaster_srv[2][DIGEST256_LEN];
378 static uint64_t cached_time_period_nums[2] = {0};
380 /** Compute the disaster SRV value for this <b>time_period_num</b> and put it
381 * in <b>srv_out</b> (of size at least DIGEST256_LEN). First check our caches
382 * to see if we have already computed it. */
383 STATIC void
384 get_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
386 if (time_period_num == cached_time_period_nums[0]) {
387 memcpy(srv_out, cached_disaster_srv[0], DIGEST256_LEN);
388 return;
389 } else if (time_period_num == cached_time_period_nums[1]) {
390 memcpy(srv_out, cached_disaster_srv[1], DIGEST256_LEN);
391 return;
392 } else {
393 int replace_idx;
394 // Replace the lower period number.
395 if (cached_time_period_nums[0] <= cached_time_period_nums[1]) {
396 replace_idx = 0;
397 } else {
398 replace_idx = 1;
400 cached_time_period_nums[replace_idx] = time_period_num;
401 compute_disaster_srv(time_period_num, cached_disaster_srv[replace_idx]);
402 memcpy(srv_out, cached_disaster_srv[replace_idx], DIGEST256_LEN);
403 return;
407 #ifdef TOR_UNIT_TESTS
409 /** Get the first cached disaster SRV. Only used by unittests. */
410 STATIC uint8_t *
411 get_first_cached_disaster_srv(void)
413 return cached_disaster_srv[0];
416 /** Get the second cached disaster SRV. Only used by unittests. */
417 STATIC uint8_t *
418 get_second_cached_disaster_srv(void)
420 return cached_disaster_srv[1];
423 #endif /* defined(TOR_UNIT_TESTS) */
425 /** When creating a blinded key, we need a parameter which construction is as
426 * follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
428 * The nonce has a pre-defined format which uses the time period number
429 * period_num and the start of the period in second start_time_period.
431 * The secret of size secret_len is optional meaning that it can be NULL and
432 * thus will be ignored for the param construction.
434 * The result is put in param_out. */
435 STATIC void
436 build_blinded_key_param(const ed25519_public_key_t *pubkey,
437 const uint8_t *secret, size_t secret_len,
438 uint64_t period_num, uint64_t period_length,
439 uint8_t *param_out)
441 size_t offset = 0;
442 const char blind_str[] = "Derive temporary signing key";
443 uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
444 crypto_digest_t *digest;
446 tor_assert(pubkey);
447 tor_assert(param_out);
449 /* Create the nonce N. The construction is as follow:
450 * N = "key-blind" || INT_8(period_num) || INT_8(period_length) */
451 memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
452 offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
453 set_uint64(nonce + offset, tor_htonll(period_num));
454 offset += sizeof(uint64_t);
455 set_uint64(nonce + offset, tor_htonll(period_length));
456 offset += sizeof(uint64_t);
457 tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
459 /* Generate the parameter h and the construction is as follow:
460 * h = H(BLIND_STRING | pubkey | [secret] | ed25519-basepoint | N) */
461 digest = crypto_digest256_new(DIGEST_SHA3_256);
462 crypto_digest_add_bytes(digest, blind_str, sizeof(blind_str));
463 crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
464 /* Optional secret. */
465 if (secret) {
466 crypto_digest_add_bytes(digest, (char *) secret, secret_len);
468 crypto_digest_add_bytes(digest, str_ed25519_basepoint,
469 strlen(str_ed25519_basepoint));
470 crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
472 /* Extract digest and put it in the param. */
473 crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
474 crypto_digest_free(digest);
476 memwipe(nonce, 0, sizeof(nonce));
479 /** Using an ed25519 public key and version to build the checksum of an
480 * address. Put in checksum_out. Format is:
481 * SHA3-256(".onion checksum" || PUBKEY || VERSION)
483 * checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
484 static void
485 build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
486 uint8_t *checksum_out)
488 size_t offset = 0;
489 char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
491 /* Build checksum data. */
492 memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
493 HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
494 offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
495 memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
496 offset += ED25519_PUBKEY_LEN;
497 set_uint8(data + offset, version);
498 offset += sizeof(version);
499 tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
501 /* Hash the data payload to create the checksum. */
502 crypto_digest256((char *) checksum_out, data, sizeof(data),
503 DIGEST_SHA3_256);
506 /** Using an ed25519 public key, checksum and version to build the binary
507 * representation of a service address. Put in addr_out. Format is:
508 * addr_out = PUBKEY || CHECKSUM || VERSION
510 * addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
511 static void
512 build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
513 uint8_t version, char *addr_out)
515 size_t offset = 0;
517 tor_assert(key);
518 tor_assert(checksum);
520 memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
521 offset += ED25519_PUBKEY_LEN;
522 memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
523 offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
524 set_uint8(addr_out + offset, version);
525 offset += sizeof(uint8_t);
526 tor_assert(offset == HS_SERVICE_ADDR_LEN);
529 /** Helper for hs_parse_address(): Using a binary representation of a service
530 * address, parse its content into the key_out, checksum_out and version_out.
531 * Any out variable can be NULL in case the caller would want only one field.
532 * checksum_out MUST at least be 2 bytes long. address must be at least
533 * HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
534 static void
535 hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
536 uint8_t *checksum_out, uint8_t *version_out)
538 size_t offset = 0;
540 tor_assert(address);
542 if (key_out) {
543 /* First is the key. */
544 memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
546 offset += ED25519_PUBKEY_LEN;
547 if (checksum_out) {
548 /* Followed by a 2 bytes checksum. */
549 memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
551 offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
552 if (version_out) {
553 /* Finally, version value is 1 byte. */
554 *version_out = get_uint8(address + offset);
556 offset += sizeof(uint8_t);
557 /* Extra safety. */
558 tor_assert(offset == HS_SERVICE_ADDR_LEN);
561 /** Using the given identity public key and a blinded public key, compute the
562 * subcredential and put it in subcred_out.
563 * This can't fail. */
564 void
565 hs_get_subcredential(const ed25519_public_key_t *identity_pk,
566 const ed25519_public_key_t *blinded_pk,
567 hs_subcredential_t *subcred_out)
569 uint8_t credential[DIGEST256_LEN];
570 crypto_digest_t *digest;
572 tor_assert(identity_pk);
573 tor_assert(blinded_pk);
574 tor_assert(subcred_out);
576 /* First, build the credential. Construction is as follow:
577 * credential = H("credential" | public-identity-key) */
578 digest = crypto_digest256_new(DIGEST_SHA3_256);
579 crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
580 HS_CREDENTIAL_PREFIX_LEN);
581 crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
582 ED25519_PUBKEY_LEN);
583 crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
584 crypto_digest_free(digest);
586 /* Now, compute the subcredential. Construction is as follow:
587 * subcredential = H("subcredential" | credential | blinded-public-key). */
588 digest = crypto_digest256_new(DIGEST_SHA3_256);
589 crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
590 HS_SUBCREDENTIAL_PREFIX_LEN);
591 crypto_digest_add_bytes(digest, (const char *) credential,
592 sizeof(credential));
593 crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
594 ED25519_PUBKEY_LEN);
595 crypto_digest_get_digest(digest, (char *) subcred_out->subcred,
596 SUBCRED_LEN);
597 crypto_digest_free(digest);
599 memwipe(credential, 0, sizeof(credential));
602 /** From the given list of hidden service ports, find the ones that match the
603 * given edge connection conn, pick one at random and use it to set the
604 * connection address. Return 0 on success or -1 if none. */
606 hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
608 hs_port_config_t *chosen_port;
609 unsigned int warn_once = 0;
610 smartlist_t *matching_ports;
612 tor_assert(ports);
613 tor_assert(conn);
615 matching_ports = smartlist_new();
616 SMARTLIST_FOREACH_BEGIN(ports, hs_port_config_t *, p) {
617 if (TO_CONN(conn)->port != p->virtual_port) {
618 continue;
620 if (!(p->is_unix_addr)) {
621 smartlist_add(matching_ports, p);
622 } else {
623 if (add_unix_port(matching_ports, p)) {
624 if (!warn_once) {
625 /* Unix port not supported so warn only once. */
626 log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d "
627 "which is unsupported on this platform. "
628 "Ignoring it.",
629 TO_CONN(conn)->port);
631 warn_once++;
634 } SMARTLIST_FOREACH_END(p);
636 chosen_port = smartlist_choose(matching_ports);
637 smartlist_free(matching_ports);
638 if (chosen_port) {
639 if (conn->hs_ident) {
640 /* There is always a connection identifier at this point. Regardless of a
641 * Unix or TCP port, note the virtual port. */
642 conn->hs_ident->orig_virtual_port = chosen_port->virtual_port;
645 if (!(chosen_port->is_unix_addr)) {
646 /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
647 tor_addr_copy(&TO_CONN(conn)->addr, &chosen_port->real_addr);
648 TO_CONN(conn)->port = chosen_port->real_port;
649 } else {
650 if (set_unix_port(conn, chosen_port)) {
651 /* Simply impossible to end up here else we were able to add a Unix
652 * port without AF_UNIX support... ? */
653 tor_assert(0);
657 return (chosen_port) ? 0 : -1;
660 /** Return a new hs_port_config_t with its path set to
661 * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
662 static hs_port_config_t *
663 hs_port_config_new(const char *socket_path)
665 if (!socket_path)
666 return tor_malloc_zero(sizeof(hs_port_config_t) + 1);
668 const size_t pathlen = strlen(socket_path) + 1;
669 hs_port_config_t *conf =
670 tor_malloc_zero(sizeof(hs_port_config_t) + pathlen);
671 memcpy(conf->unix_addr, socket_path, pathlen);
672 conf->is_unix_addr = 1;
673 return conf;
676 /** Parses a virtual-port to real-port/socket mapping separated by
677 * the provided separator and returns a new hs_port_config_t,
678 * or NULL and an optional error string on failure.
680 * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
682 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
684 hs_port_config_t *
685 hs_parse_port_config(const char *string, const char *sep,
686 char **err_msg_out)
688 smartlist_t *sl;
689 int virtport;
690 int realport = 0;
691 uint16_t p;
692 tor_addr_t addr;
693 hs_port_config_t *result = NULL;
694 unsigned int is_unix_addr = 0;
695 const char *socket_path = NULL;
696 char *err_msg = NULL;
697 char *addrport = NULL;
699 sl = smartlist_new();
700 smartlist_split_string(sl, string, sep,
701 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
702 if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
703 err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
704 goto err;
706 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
707 if (!virtport) {
708 tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
709 "port configuration", escaped(smartlist_get(sl,0)));
711 goto err;
713 if (smartlist_len(sl) == 1) {
714 /* No addr:port part; use default. */
715 realport = virtport;
716 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
717 } else {
718 int ret;
720 const char *addrport_element = smartlist_get(sl,1);
721 const char *rest = NULL;
722 int is_unix;
723 ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
724 &is_unix, &rest);
726 if (ret < 0) {
727 tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
728 "service configuration", addrport_element);
729 goto err;
732 if (rest && strlen(rest)) {
733 err_msg = tor_strdup("HiddenServicePort parse error: invalid port "
734 "mapping");
735 goto err;
738 if (is_unix) {
739 socket_path = addrport;
740 is_unix_addr = 1;
741 } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
742 /* else try it as an IP:port pair if it has a : or . in it */
743 if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
744 err_msg = tor_strdup("Unparseable address in hidden service port "
745 "configuration.");
746 goto err;
748 realport = p?p:virtport;
749 } else {
750 /* No addr:port, no addr -- must be port. */
751 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
752 if (!realport) {
753 tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
754 "hidden service port configuration.",
755 escaped(addrport));
756 goto err;
758 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
762 /* Allow room for unix_addr */
763 result = hs_port_config_new(socket_path);
764 result->virtual_port = virtport;
765 result->is_unix_addr = is_unix_addr;
766 if (!is_unix_addr) {
767 result->real_port = realport;
768 tor_addr_copy(&result->real_addr, &addr);
769 result->unix_addr[0] = '\0';
772 err:
773 tor_free(addrport);
774 if (err_msg_out != NULL) {
775 *err_msg_out = err_msg;
776 } else {
777 tor_free(err_msg);
779 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
780 smartlist_free(sl);
782 return result;
785 /** Release all storage held in a hs_port_config_t. */
786 void
787 hs_port_config_free_(hs_port_config_t *p)
789 tor_free(p);
792 /** Using a base32 representation of a service address, parse its content into
793 * the key_out, checksum_out and version_out. Any out variable can be NULL in
794 * case the caller would want only one field. checksum_out MUST at least be 2
795 * bytes long.
797 * Return 0 if parsing went well; return -1 in case of error and if errmsg is
798 * non NULL, a human readable string message is set. */
800 hs_parse_address_no_log(const char *address, ed25519_public_key_t *key_out,
801 uint8_t *checksum_out, uint8_t *version_out,
802 const char **errmsg)
804 char decoded[HS_SERVICE_ADDR_LEN];
806 tor_assert(address);
808 if (errmsg) {
809 *errmsg = NULL;
812 /* Obvious length check. */
813 if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
814 if (errmsg) {
815 *errmsg = "Invalid length";
817 goto invalid;
820 /* Decode address so we can extract needed fields. */
821 if (base32_decode(decoded, sizeof(decoded), address, strlen(address))
822 != sizeof(decoded)) {
823 if (errmsg) {
824 *errmsg = "Unable to base32 decode";
826 goto invalid;
829 /* Parse the decoded address into the fields we need. */
830 hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
832 return 0;
833 invalid:
834 return -1;
837 /** Same has hs_parse_address_no_log() but emits a log warning on parsing
838 * failure. */
840 hs_parse_address(const char *address, ed25519_public_key_t *key_out,
841 uint8_t *checksum_out, uint8_t *version_out)
843 const char *errmsg = NULL;
844 int ret = hs_parse_address_no_log(address, key_out, checksum_out,
845 version_out, &errmsg);
846 if (ret < 0) {
847 log_warn(LD_REND, "Service address %s failed to be parsed: %s",
848 escaped_safe_str(address), errmsg);
850 return ret;
853 /** Validate a given onion address. The length, the base32 decoding, and
854 * checksum are validated. Return 1 if valid else 0. */
856 hs_address_is_valid(const char *address)
858 uint8_t version;
859 uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
860 uint8_t target_checksum[DIGEST256_LEN];
861 ed25519_public_key_t service_pubkey;
863 /* Parse the decoded address into the fields we need. */
864 if (hs_parse_address(address, &service_pubkey, checksum, &version) < 0) {
865 goto invalid;
868 /* Get the checksum it's supposed to be and compare it with what we have
869 * encoded in the address. */
870 build_hs_checksum(&service_pubkey, version, target_checksum);
871 if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
872 log_warn(LD_REND, "Service address %s invalid checksum.",
873 escaped_safe_str(address));
874 goto invalid;
877 /* Validate that this pubkey does not have a torsion component. We need to do
878 * this on the prop224 client-side so that attackers can't give equivalent
879 * forms of an onion address to users. */
880 if (ed25519_validate_pubkey(&service_pubkey) < 0) {
881 log_warn(LD_REND, "Service address %s has bad pubkey .",
882 escaped_safe_str(address));
883 goto invalid;
886 /* Valid address. */
887 return 1;
888 invalid:
889 return 0;
892 /** Build a service address using an ed25519 public key and a given version.
893 * The returned address is base32 encoded and put in addr_out. The caller MUST
894 * make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
896 * Format is as follows:
897 * base32(PUBKEY || CHECKSUM || VERSION)
898 * CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
899 * */
900 void
901 hs_build_address(const ed25519_public_key_t *key, uint8_t version,
902 char *addr_out)
904 uint8_t checksum[DIGEST256_LEN];
905 char address[HS_SERVICE_ADDR_LEN];
907 tor_assert(key);
908 tor_assert(addr_out);
910 /* Get the checksum of the address. */
911 build_hs_checksum(key, version, checksum);
912 /* Get the binary address representation. */
913 build_hs_address(key, checksum, version, address);
915 /* Encode the address. addr_out will be NUL terminated after this. */
916 base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
917 sizeof(address));
918 /* Validate what we just built. */
919 tor_assert(hs_address_is_valid(addr_out));
922 /** From a given ed25519 public key pk and an optional secret, compute a
923 * blinded public key and put it in blinded_pk_out. This is only useful to
924 * the client side because the client only has access to the identity public
925 * key of the service. */
926 void
927 hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
928 const uint8_t *secret, size_t secret_len,
929 uint64_t time_period_num,
930 ed25519_public_key_t *blinded_pk_out)
932 /* Our blinding key API requires a 32 bytes parameter. */
933 uint8_t param[DIGEST256_LEN];
935 tor_assert(pk);
936 tor_assert(blinded_pk_out);
937 tor_assert(!fast_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
939 build_blinded_key_param(pk, secret, secret_len,
940 time_period_num, get_time_period_length(), param);
941 ed25519_public_blind(blinded_pk_out, pk, param);
943 memwipe(param, 0, sizeof(param));
946 /** From a given ed25519 keypair kp and an optional secret, compute a blinded
947 * keypair for the current time period and put it in blinded_kp_out. This is
948 * only useful by the service side because the client doesn't have access to
949 * the identity secret key. */
950 void
951 hs_build_blinded_keypair(const ed25519_keypair_t *kp,
952 const uint8_t *secret, size_t secret_len,
953 uint64_t time_period_num,
954 ed25519_keypair_t *blinded_kp_out)
956 /* Our blinding key API requires a 32 bytes parameter. */
957 uint8_t param[DIGEST256_LEN];
959 tor_assert(kp);
960 tor_assert(blinded_kp_out);
961 /* Extra safety. A zeroed key is bad. */
962 tor_assert(!fast_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
963 tor_assert(!fast_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
965 build_blinded_key_param(&kp->pubkey, secret, secret_len,
966 time_period_num, get_time_period_length(), param);
967 ed25519_keypair_blind(blinded_kp_out, kp, param);
969 memwipe(param, 0, sizeof(param));
972 /** Return true if we are currently in the time segment between a new time
973 * period and a new SRV (in the real network that happens between 12:00 and
974 * 00:00 UTC). Here is a diagram showing exactly when this returns true:
976 * +------------------------------------------------------------------+
977 * | |
978 * | 00:00 12:00 00:00 12:00 00:00 12:00 |
979 * | SRV#1 TP#1 SRV#2 TP#2 SRV#3 TP#3 |
980 * | |
981 * | $==========|-----------$===========|-----------$===========| |
982 * | ^^^^^^^^^^^^ ^^^^^^^^^^^^ |
983 * | |
984 * +------------------------------------------------------------------+
986 MOCK_IMPL(int,
987 hs_in_period_between_tp_and_srv,(const networkstatus_t *consensus, time_t now))
989 time_t valid_after;
990 time_t srv_start_time, tp_start_time;
992 if (!consensus) {
993 consensus = networkstatus_get_reasonably_live_consensus(now,
994 usable_consensus_flavor());
995 if (!consensus) {
996 return 0;
1000 /* Get start time of next TP and of current SRV protocol run, and check if we
1001 * are between them. */
1002 valid_after = consensus->valid_after;
1003 srv_start_time = sr_state_get_start_time_of_current_protocol_run();
1004 tp_start_time = hs_get_start_time_of_next_time_period(srv_start_time);
1006 if (valid_after >= srv_start_time && valid_after < tp_start_time) {
1007 return 0;
1010 return 1;
1013 /** Return 1 if any virtual port in ports needs a circuit with good uptime.
1014 * Else return 0. */
1016 hs_service_requires_uptime_circ(const smartlist_t *ports)
1018 tor_assert(ports);
1020 SMARTLIST_FOREACH_BEGIN(ports, hs_port_config_t *, p) {
1021 if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
1022 p->virtual_port)) {
1023 return 1;
1025 } SMARTLIST_FOREACH_END(p);
1026 return 0;
1029 /** Build hs_index which is used to find the responsible hsdirs. This index
1030 * value is used to select the responsible HSDir where their hsdir_index is
1031 * closest to this value.
1032 * SHA3-256("store-at-idx" | blinded_public_key |
1033 * INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) )
1035 * hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
1036 void
1037 hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
1038 uint64_t period_num, uint8_t *hs_index_out)
1040 crypto_digest_t *digest;
1042 tor_assert(blinded_pk);
1043 tor_assert(hs_index_out);
1045 /* Build hs_index. See construction at top of function comment. */
1046 digest = crypto_digest256_new(DIGEST_SHA3_256);
1047 crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
1048 crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
1049 ED25519_PUBKEY_LEN);
1051 /* Now setup INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) */
1053 uint64_t period_length = get_time_period_length();
1054 char buf[sizeof(uint64_t)*3];
1055 size_t offset = 0;
1056 set_uint64(buf, tor_htonll(replica));
1057 offset += sizeof(uint64_t);
1058 set_uint64(buf+offset, tor_htonll(period_length));
1059 offset += sizeof(uint64_t);
1060 set_uint64(buf+offset, tor_htonll(period_num));
1061 offset += sizeof(uint64_t);
1062 tor_assert(offset == sizeof(buf));
1064 crypto_digest_add_bytes(digest, buf, sizeof(buf));
1067 crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
1068 crypto_digest_free(digest);
1071 /** Build hsdir_index which is used to find the responsible hsdirs. This is the
1072 * index value that is compare to the hs_index when selecting an HSDir.
1073 * SHA3-256("node-idx" | node_identity |
1074 * shared_random_value | INT_8(period_length) | INT_8(period_num) )
1076 * hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
1077 void
1078 hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
1079 const uint8_t *srv_value, uint64_t period_num,
1080 uint8_t *hsdir_index_out)
1082 crypto_digest_t *digest;
1084 tor_assert(identity_pk);
1085 tor_assert(srv_value);
1086 tor_assert(hsdir_index_out);
1088 /* Build hsdir_index. See construction at top of function comment. */
1089 digest = crypto_digest256_new(DIGEST_SHA3_256);
1090 crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
1091 crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
1092 ED25519_PUBKEY_LEN);
1093 crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
1096 uint64_t time_period_length = get_time_period_length();
1097 char period_stuff[sizeof(uint64_t)*2];
1098 size_t offset = 0;
1099 set_uint64(period_stuff, tor_htonll(period_num));
1100 offset += sizeof(uint64_t);
1101 set_uint64(period_stuff+offset, tor_htonll(time_period_length));
1102 offset += sizeof(uint64_t);
1103 tor_assert(offset == sizeof(period_stuff));
1105 crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
1108 crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
1109 crypto_digest_free(digest);
1112 /** Return a newly allocated buffer containing the current shared random value
1113 * or if not present, a disaster value is computed using the given time period
1114 * number. If a consensus is provided in <b>ns</b>, use it to get the SRV
1115 * value. This function can't fail. */
1116 uint8_t *
1117 hs_get_current_srv(uint64_t time_period_num, const networkstatus_t *ns)
1119 uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
1120 const sr_srv_t *current_srv = sr_get_current(ns);
1122 if (current_srv) {
1123 memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
1124 } else {
1125 /* Disaster mode. */
1126 get_disaster_srv(time_period_num, sr_value);
1128 return sr_value;
1131 /** Return a newly allocated buffer containing the previous shared random
1132 * value or if not present, a disaster value is computed using the given time
1133 * period number. This function can't fail. */
1134 uint8_t *
1135 hs_get_previous_srv(uint64_t time_period_num, const networkstatus_t *ns)
1137 uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
1138 const sr_srv_t *previous_srv = sr_get_previous(ns);
1140 if (previous_srv) {
1141 memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
1142 } else {
1143 /* Disaster mode. */
1144 get_disaster_srv(time_period_num, sr_value);
1146 return sr_value;
1149 /** Return the number of replicas defined by a consensus parameter or the
1150 * default value. */
1151 int32_t
1152 hs_get_hsdir_n_replicas(void)
1154 /* The [1,16] range is a specification requirement. */
1155 return networkstatus_get_param(NULL, "hsdir_n_replicas",
1156 HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
1159 /** Return the spread fetch value defined by a consensus parameter or the
1160 * default value. */
1161 int32_t
1162 hs_get_hsdir_spread_fetch(void)
1164 /* The [1,128] range is a specification requirement. */
1165 return networkstatus_get_param(NULL, "hsdir_spread_fetch",
1166 HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
1169 /** Return the spread store value defined by a consensus parameter or the
1170 * default value. */
1171 int32_t
1172 hs_get_hsdir_spread_store(void)
1174 /* The [1,128] range is a specification requirement. */
1175 return networkstatus_get_param(NULL, "hsdir_spread_store",
1176 HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
1179 /** <b>node</b> is an HSDir so make sure that we have assigned an hsdir index.
1180 * Return 0 if everything is as expected, else return -1. */
1181 static int
1182 node_has_hsdir_index(const node_t *node)
1184 tor_assert(node_supports_v3_hsdir(node));
1186 /* A node can't have an HSDir index without a descriptor since we need desc
1187 * to get its ed25519 key. for_direct_connect should be zero, since we
1188 * always use the consensus-indexed node's keys to build the hash ring, even
1189 * if some of the consensus-indexed nodes are also bridges. */
1190 if (!node_has_preferred_descriptor(node, 0)) {
1191 return 0;
1194 /* At this point, since the node has a desc, this node must also have an
1195 * hsdir index. If not, something went wrong, so BUG out. */
1196 if (BUG(fast_mem_is_zero((const char*)node->hsdir_index.fetch,
1197 DIGEST256_LEN))) {
1198 return 0;
1200 if (BUG(fast_mem_is_zero((const char*)node->hsdir_index.store_first,
1201 DIGEST256_LEN))) {
1202 return 0;
1204 if (BUG(fast_mem_is_zero((const char*)node->hsdir_index.store_second,
1205 DIGEST256_LEN))) {
1206 return 0;
1209 return 1;
1212 /** For a given blinded key and time period number, get the responsible HSDir
1213 * and put their routerstatus_t object in the responsible_dirs list. If
1214 * 'use_second_hsdir_index' is true, use the second hsdir_index of the node_t
1215 * is used. If 'for_fetching' is true, the spread fetch consensus parameter is
1216 * used else the spread store is used which is only for upload. This function
1217 * can't fail but it is possible that the responsible_dirs list contains fewer
1218 * nodes than expected.
1220 * This function goes over the latest consensus routerstatus list and sorts it
1221 * by their node_t hsdir_index then does a binary search to find the closest
1222 * node. All of this makes it a bit CPU intensive so use it wisely. */
1223 void
1224 hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
1225 uint64_t time_period_num, int use_second_hsdir_index,
1226 int for_fetching, smartlist_t *responsible_dirs)
1228 smartlist_t *sorted_nodes;
1229 /* The compare function used for the smartlist bsearch. We have two
1230 * different depending on is_next_period. */
1231 int (*cmp_fct)(const void *, const void **);
1233 tor_assert(blinded_pk);
1234 tor_assert(responsible_dirs);
1236 sorted_nodes = smartlist_new();
1238 /* Make sure we actually have a live consensus */
1239 networkstatus_t *c =
1240 networkstatus_get_reasonably_live_consensus(approx_time(),
1241 usable_consensus_flavor());
1242 if (!c || smartlist_len(c->routerstatus_list) == 0) {
1243 log_warn(LD_REND, "No live consensus so we can't get the responsible "
1244 "hidden service directories.");
1245 goto done;
1248 /* Ensure the nodelist is fresh, since it contains the HSDir indices. */
1249 nodelist_ensure_freshness(c);
1251 /* Add every node_t that support HSDir v3 for which we do have a valid
1252 * hsdir_index already computed for them for this consensus. */
1254 SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
1255 /* Even though this node_t object won't be modified and should be const,
1256 * we can't add const object in a smartlist_t. */
1257 node_t *n = node_get_mutable_by_id(rs->identity_digest);
1258 tor_assert(n);
1259 if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
1260 if (!node_has_hsdir_index(n)) {
1261 log_info(LD_GENERAL, "Node %s was found without hsdir index.",
1262 node_describe(n));
1263 continue;
1265 smartlist_add(sorted_nodes, n);
1267 } SMARTLIST_FOREACH_END(rs);
1269 if (smartlist_len(sorted_nodes) == 0) {
1270 log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
1271 goto done;
1274 /* First thing we have to do is sort all node_t by hsdir_index. The
1275 * is_next_period tells us if we want the current or the next one. Set the
1276 * bsearch compare function also while we are at it. */
1277 if (for_fetching) {
1278 smartlist_sort(sorted_nodes, compare_node_fetch_hsdir_index);
1279 cmp_fct = compare_digest_to_fetch_hsdir_index;
1280 } else if (use_second_hsdir_index) {
1281 smartlist_sort(sorted_nodes, compare_node_store_second_hsdir_index);
1282 cmp_fct = compare_digest_to_store_second_hsdir_index;
1283 } else {
1284 smartlist_sort(sorted_nodes, compare_node_store_first_hsdir_index);
1285 cmp_fct = compare_digest_to_store_first_hsdir_index;
1288 /* For all replicas, we'll select a set of HSDirs using the consensus
1289 * parameters and the sorted list. The replica starting at value 1 is
1290 * defined by the specification. */
1291 for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
1292 int idx, start, found, n_added = 0;
1293 uint8_t hs_index[DIGEST256_LEN] = {0};
1294 /* Number of node to add to the responsible dirs list depends on if we are
1295 * trying to fetch or store. A client always fetches. */
1296 int n_to_add = (for_fetching) ? hs_get_hsdir_spread_fetch() :
1297 hs_get_hsdir_spread_store();
1299 /* Get the index that we should use to select the node. */
1300 hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
1301 /* The compare function pointer has been set correctly earlier. */
1302 start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
1303 &found);
1304 /* Getting the length of the list if no member is greater than the key we
1305 * are looking for so start at the first element. */
1306 if (idx == smartlist_len(sorted_nodes)) {
1307 start = idx = 0;
1309 while (n_added < n_to_add) {
1310 const node_t *node = smartlist_get(sorted_nodes, idx);
1311 /* If the node has already been selected which is possible between
1312 * replicas, the specification says to skip over. */
1313 if (!smartlist_contains(responsible_dirs, node->rs)) {
1314 smartlist_add(responsible_dirs, node->rs);
1315 ++n_added;
1317 if (++idx == smartlist_len(sorted_nodes)) {
1318 /* Wrap if we've reached the end of the list. */
1319 idx = 0;
1321 if (idx == start) {
1322 /* We've gone over the whole list, stop and avoid infinite loop. */
1323 break;
1328 done:
1329 smartlist_free(sorted_nodes);
1332 /*********************** HSDir request tracking ***************************/
1334 /** Return the period for which a hidden service directory cannot be queried
1335 * for the same descriptor ID again, taking TestingTorNetwork into account. */
1336 time_t
1337 hs_hsdir_requery_period(const or_options_t *options)
1339 tor_assert(options);
1341 if (options->TestingTorNetwork) {
1342 return REND_HID_SERV_DIR_REQUERY_PERIOD_TESTING;
1343 } else {
1344 return REND_HID_SERV_DIR_REQUERY_PERIOD;
1348 /** Tracks requests for fetching hidden service descriptors. It's used by
1349 * hidden service clients, to avoid querying HSDirs that have already failed
1350 * giving back a descriptor. The same data structure is used to track v3 HS
1351 * descriptor requests.
1353 * The string map is a key/value store that contains the last request times to
1354 * hidden service directories for certain queries. Specifically:
1356 * key = base32(hsdir_identity) + base32(hs_identity)
1357 * value = time_t of last request for that hs_identity to that HSDir
1359 * where 'hsdir_identity' is the identity digest of the HSDir node, and
1360 * 'hs_identity' is the ed25519 blinded public key of the HS for v3. */
1361 static strmap_t *last_hid_serv_requests_ = NULL;
1363 /** Returns last_hid_serv_requests_, initializing it to a new strmap if
1364 * necessary. */
1365 STATIC strmap_t *
1366 get_last_hid_serv_requests(void)
1368 if (!last_hid_serv_requests_)
1369 last_hid_serv_requests_ = strmap_new();
1370 return last_hid_serv_requests_;
1373 /** Look up the last request time to hidden service directory <b>hs_dir</b>
1374 * for descriptor request key <b>req_key_str</b> which is the blinded key for
1375 * v3. If <b>set</b> is non-zero, assign the current time <b>now</b> and
1376 * return that. Otherwise, return the most recent request time, or 0 if no
1377 * such request has been sent before. */
1378 time_t
1379 hs_lookup_last_hid_serv_request(routerstatus_t *hs_dir,
1380 const char *req_key_str,
1381 time_t now, int set)
1383 char hsdir_id_base32[BASE32_DIGEST_LEN + 1];
1384 char *hsdir_desc_comb_id = NULL;
1385 time_t *last_request_ptr;
1386 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
1388 /* Create the key */
1389 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
1390 hs_dir->identity_digest, DIGEST_LEN);
1391 tor_asprintf(&hsdir_desc_comb_id, "%s%s", hsdir_id_base32, req_key_str);
1393 if (set) {
1394 time_t *oldptr;
1395 last_request_ptr = tor_malloc_zero(sizeof(time_t));
1396 *last_request_ptr = now;
1397 oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
1398 last_request_ptr);
1399 tor_free(oldptr);
1400 } else {
1401 last_request_ptr = strmap_get(last_hid_serv_requests,
1402 hsdir_desc_comb_id);
1405 tor_free(hsdir_desc_comb_id);
1406 return (last_request_ptr) ? *last_request_ptr : 0;
1409 /** Clean the history of request times to hidden service directories, so that
1410 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
1411 * seconds any more. */
1412 void
1413 hs_clean_last_hid_serv_requests(time_t now)
1415 strmap_iter_t *iter;
1416 time_t cutoff = now - hs_hsdir_requery_period(get_options());
1417 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
1418 for (iter = strmap_iter_init(last_hid_serv_requests);
1419 !strmap_iter_done(iter); ) {
1420 const char *key;
1421 void *val;
1422 time_t *ent;
1423 strmap_iter_get(iter, &key, &val);
1424 ent = (time_t *) val;
1425 if (*ent < cutoff) {
1426 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
1427 tor_free(ent);
1428 } else {
1429 iter = strmap_iter_next(last_hid_serv_requests, iter);
1434 /** Remove all requests related to the descriptor request key string
1435 * <b>req_key_str</b> from the history of times of requests to hidden service
1436 * directories.
1438 * This is called from purge_hid_serv_request(), which must be idempotent, so
1439 * any future changes to this function must leave it idempotent too. */
1440 void
1441 hs_purge_hid_serv_from_last_hid_serv_requests(const char *req_key_str)
1443 strmap_iter_t *iter;
1444 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
1446 for (iter = strmap_iter_init(last_hid_serv_requests);
1447 !strmap_iter_done(iter); ) {
1448 const char *key;
1449 void *val;
1450 strmap_iter_get(iter, &key, &val);
1452 /* XXX: The use of REND_DESC_ID_V2_LEN_BASE32 is very wrong in terms of
1453 * semantic, see #23305. */
1455 /* This strmap contains variable-sized elements so this is a basic length
1456 * check on the strings we are about to compare. The key is variable sized
1457 * since it's composed as follows:
1458 * key = base32(hsdir_identity) + base32(req_key_str)
1459 * where 'req_key_str' is the ed25519 blinded public key of the HS v3. */
1460 if (strlen(key) < REND_DESC_ID_V2_LEN_BASE32 + strlen(req_key_str)) {
1461 iter = strmap_iter_next(last_hid_serv_requests, iter);
1462 continue;
1465 /* Check if the tracked request matches our request key */
1466 if (tor_memeq(key + REND_DESC_ID_V2_LEN_BASE32, req_key_str,
1467 strlen(req_key_str))) {
1468 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
1469 tor_free(val);
1470 } else {
1471 iter = strmap_iter_next(last_hid_serv_requests, iter);
1476 /** Purge the history of request times to hidden service directories,
1477 * so that future lookups of an HS descriptor will not fail because we
1478 * accessed all of the HSDir relays responsible for the descriptor
1479 * recently. */
1480 void
1481 hs_purge_last_hid_serv_requests(void)
1483 /* Don't create the table if it doesn't exist yet (and it may very
1484 * well not exist if the user hasn't accessed any HSes)... */
1485 strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
1486 /* ... and let get_last_hid_serv_requests re-create it for us if
1487 * necessary. */
1488 last_hid_serv_requests_ = NULL;
1490 if (old_last_hid_serv_requests != NULL) {
1491 log_info(LD_REND, "Purging client last-HS-desc-request-time table");
1492 strmap_free(old_last_hid_serv_requests, tor_free_);
1496 /***********************************************************************/
1498 /** Given the list of responsible HSDirs in <b>responsible_dirs</b>, pick the
1499 * one that we should use to fetch a descriptor right now. Take into account
1500 * previous failed attempts at fetching this descriptor from HSDirs using the
1501 * string identifier <b>req_key_str</b>. We return whether we are rate limited
1502 * into *<b>is_rate_limited_out</b> if it is not NULL.
1504 * Steals ownership of <b>responsible_dirs</b>.
1506 * Return the routerstatus of the chosen HSDir if successful, otherwise return
1507 * NULL if no HSDirs are worth trying right now. */
1508 routerstatus_t *
1509 hs_pick_hsdir(smartlist_t *responsible_dirs, const char *req_key_str,
1510 bool *is_rate_limited_out)
1512 smartlist_t *usable_responsible_dirs = smartlist_new();
1513 const or_options_t *options = get_options();
1514 routerstatus_t *hs_dir;
1515 time_t now = time(NULL);
1516 int excluded_some;
1517 bool rate_limited = false;
1518 int rate_limited_count = 0;
1519 int responsible_dirs_count = smartlist_len(responsible_dirs);
1521 tor_assert(req_key_str);
1523 /* Clean outdated request history first. */
1524 hs_clean_last_hid_serv_requests(now);
1526 /* Only select those hidden service directories to which we did not send a
1527 * request recently and for which we have a router descriptor here.
1529 * Use for_direct_connect==0 even if we will be connecting to the node
1530 * directly, since we always use the key information in the
1531 * consensus-indexed node descriptors for building the index.
1533 SMARTLIST_FOREACH_BEGIN(responsible_dirs, routerstatus_t *, dir) {
1534 time_t last = hs_lookup_last_hid_serv_request(dir, req_key_str, 0, 0);
1535 const node_t *node = node_get_by_id(dir->identity_digest);
1536 if (last + hs_hsdir_requery_period(options) >= now ||
1537 !node || !node_has_preferred_descriptor(node, 0)) {
1538 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
1539 rate_limited_count++;
1540 continue;
1542 if (!routerset_contains_node(options->ExcludeNodes, node)) {
1543 smartlist_add(usable_responsible_dirs, dir);
1545 } SMARTLIST_FOREACH_END(dir);
1547 if (rate_limited_count > 0 || responsible_dirs_count > 0) {
1548 rate_limited = rate_limited_count == responsible_dirs_count;
1551 excluded_some =
1552 smartlist_len(usable_responsible_dirs) < smartlist_len(responsible_dirs);
1554 hs_dir = smartlist_choose(usable_responsible_dirs);
1555 if (!hs_dir && !options->StrictNodes) {
1556 hs_dir = smartlist_choose(responsible_dirs);
1559 smartlist_free(responsible_dirs);
1560 smartlist_free(usable_responsible_dirs);
1561 if (!hs_dir) {
1562 const char *warn_str = (rate_limited) ? "we are rate limited." :
1563 "we requested them all recently without success";
1564 log_info(LD_REND, "Could not pick one of the responsible hidden "
1565 "service directories, because %s.", warn_str);
1566 if (options->StrictNodes && excluded_some) {
1567 log_warn(LD_REND, "Could not pick a hidden service directory for the "
1568 "requested hidden service: they are all either down or "
1569 "excluded, and StrictNodes is set.");
1571 } else {
1572 /* Remember that we are requesting a descriptor from this hidden service
1573 * directory now. */
1574 hs_lookup_last_hid_serv_request(hs_dir, req_key_str, now, 1);
1577 if (is_rate_limited_out != NULL) {
1578 *is_rate_limited_out = rate_limited;
1581 return hs_dir;
1584 /** Given a list of link specifiers lspecs, a curve 25519 onion_key, and
1585 * a direct connection boolean direct_conn (true for single onion services),
1586 * return a newly allocated extend_info_t object.
1588 * This function always returns an extend info with a valid IP address and
1589 * ORPort, or NULL. If direct_conn is false, the IP address is always IPv4.
1591 * It performs the following checks:
1592 * if there is no usable IP address, or legacy ID is missing, return NULL.
1593 * if direct_conn, and we can't reach any IP address, return NULL.
1595 extend_info_t *
1596 hs_get_extend_info_from_lspecs(const smartlist_t *lspecs,
1597 const curve25519_public_key_t *onion_key,
1598 int direct_conn)
1600 int have_v4 = 0, have_legacy_id = 0, have_ed25519_id = 0;
1601 char legacy_id[DIGEST_LEN] = {0};
1602 ed25519_public_key_t ed25519_pk;
1603 extend_info_t *info = NULL;
1604 tor_addr_port_t ap;
1606 tor_addr_make_null(&ap.addr, AF_UNSPEC);
1607 ap.port = 0;
1609 if (lspecs == NULL) {
1610 log_warn(LD_BUG, "Specified link specifiers is null");
1611 goto done;
1614 if (onion_key == NULL) {
1615 log_warn(LD_BUG, "Specified onion key is null");
1616 goto done;
1619 if (smartlist_len(lspecs) == 0) {
1620 log_fn(LOG_PROTOCOL_WARN, LD_REND, "Empty link specifier list.");
1621 /* Return NULL. */
1622 goto done;
1625 SMARTLIST_FOREACH_BEGIN(lspecs, const link_specifier_t *, ls) {
1626 switch (link_specifier_get_ls_type(ls)) {
1627 case LS_IPV4:
1628 /* Skip if we already seen a v4. If direct_conn is true, we skip this
1629 * block because reachable_addr_choose_from_ls() will set ap. If
1630 * direct_conn is false, set ap to the first IPv4 address and port in
1631 * the link specifiers.*/
1632 if (have_v4 || direct_conn) continue;
1633 tor_addr_from_ipv4h(&ap.addr,
1634 link_specifier_get_un_ipv4_addr(ls));
1635 ap.port = link_specifier_get_un_ipv4_port(ls);
1636 have_v4 = 1;
1637 break;
1638 case LS_LEGACY_ID:
1639 /* Make sure we do have enough bytes for the legacy ID. */
1640 if (link_specifier_getlen_un_legacy_id(ls) < sizeof(legacy_id)) {
1641 break;
1643 memcpy(legacy_id, link_specifier_getconstarray_un_legacy_id(ls),
1644 sizeof(legacy_id));
1645 have_legacy_id = 1;
1646 break;
1647 case LS_ED25519_ID:
1648 memcpy(ed25519_pk.pubkey,
1649 link_specifier_getconstarray_un_ed25519_id(ls),
1650 ED25519_PUBKEY_LEN);
1651 have_ed25519_id = 1;
1652 break;
1653 default:
1654 /* Ignore unknown. */
1655 break;
1657 } SMARTLIST_FOREACH_END(ls);
1659 /* Choose a preferred address first, but fall back to an allowed address. */
1660 if (direct_conn)
1661 reachable_addr_choose_from_ls(lspecs, 0, &ap);
1663 /* Legacy ID is mandatory, and we require an IP address. */
1664 if (!tor_addr_port_is_valid_ap(&ap, 0)) {
1665 /* If we're missing the IP address, log a warning and return NULL. */
1666 log_info(LD_NET, "Unreachable or invalid IP address in link state");
1667 goto done;
1669 if (!have_legacy_id) {
1670 /* If we're missing the legacy ID, log a warning and return NULL. */
1671 log_warn(LD_PROTOCOL, "Missing Legacy ID in link state");
1672 goto done;
1675 /* We will add support for falling back to a 3-hop path in a later
1676 * release. */
1678 /* We'll validate now that the address we've picked isn't a private one. If
1679 * it is, are we allowed to extend to private addresses? */
1680 if (!extend_info_addr_is_allowed(&ap.addr)) {
1681 log_fn(LOG_PROTOCOL_WARN, LD_REND,
1682 "Requested address is private and we are not allowed to extend to "
1683 "it: %s:%u", safe_str(fmt_addr(&ap.addr)), ap.port);
1684 goto done;
1687 /* We do have everything for which we think we can connect successfully. */
1688 info = extend_info_new(NULL, legacy_id,
1689 (have_ed25519_id) ? &ed25519_pk : NULL,
1690 onion_key, &ap.addr, ap.port, NULL, false);
1691 done:
1692 return info;
1695 /***********************************************************************/
1697 /** Initialize the entire HS subsystem. This is called in tor_init() before any
1698 * torrc options are loaded. Only for >= v3. */
1699 void
1700 hs_init(void)
1702 hs_circuitmap_init();
1703 hs_service_init();
1704 hs_cache_init();
1707 /** Release and cleanup all memory of the HS subsystem (all version). This is
1708 * called by tor_free_all(). */
1709 void
1710 hs_free_all(void)
1712 hs_circuitmap_free_all();
1713 hs_service_free_all();
1714 hs_cache_free_all();
1715 hs_client_free_all();
1716 hs_ob_free_all();
1719 /** For the given origin circuit circ, decrement the number of rendezvous
1720 * stream counter. This handles every hidden service version. */
1721 void
1722 hs_dec_rdv_stream_counter(origin_circuit_t *circ)
1724 tor_assert(circ);
1726 if (circ->hs_ident) {
1727 circ->hs_ident->num_rdv_streams--;
1728 } else {
1729 /* Should not be called if this circuit is not for hidden service. */
1730 tor_assert_nonfatal_unreached();
1734 /** For the given origin circuit circ, increment the number of rendezvous
1735 * stream counter. This handles every hidden service version. */
1736 void
1737 hs_inc_rdv_stream_counter(origin_circuit_t *circ)
1739 tor_assert(circ);
1741 if (circ->hs_ident) {
1742 circ->hs_ident->num_rdv_streams++;
1743 } else {
1744 /* Should not be called if this circuit is not for hidden service. */
1745 tor_assert_nonfatal_unreached();
1749 /** Return a newly allocated link specifier object that is a copy of dst. */
1750 link_specifier_t *
1751 link_specifier_dup(const link_specifier_t *src)
1753 link_specifier_t *dup = NULL;
1754 uint8_t *buf = NULL;
1756 if (BUG(!src)) {
1757 goto err;
1760 ssize_t encoded_len_alloc = link_specifier_encoded_len(src);
1761 if (BUG(encoded_len_alloc < 0)) {
1762 goto err;
1765 buf = tor_malloc_zero(encoded_len_alloc);
1766 ssize_t encoded_len_data = link_specifier_encode(buf,
1767 encoded_len_alloc,
1768 src);
1769 if (BUG(encoded_len_data < 0)) {
1770 goto err;
1773 ssize_t parsed_len = link_specifier_parse(&dup, buf, encoded_len_alloc);
1774 if (BUG(parsed_len < 0)) {
1775 goto err;
1778 goto done;
1780 err:
1781 dup = NULL;
1783 done:
1784 tor_free(buf);
1785 return dup;