Bump copyright date to 2019
[tor.git] / src / feature / hs / hs_common.c
blobebe49f09a518cc9a75502d812afb0ee59412d16c
1 /* Copyright (c) 2016-2019, 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 * The rendcommon.c should only contains code relating to the v2
9 * protocol.
10 **/
12 #define HS_COMMON_PRIVATE
14 #include "core/or/or.h"
16 #include "app/config/config.h"
17 #include "core/or/circuitbuild.h"
18 #include "core/or/policies.h"
19 #include "feature/dirauth/shared_random_state.h"
20 #include "feature/hs/hs_cache.h"
21 #include "feature/hs/hs_circuitmap.h"
22 #include "feature/hs/hs_client.h"
23 #include "feature/hs/hs_common.h"
24 #include "feature/hs/hs_ident.h"
25 #include "feature/hs/hs_service.h"
26 #include "feature/hs_common/shared_random_client.h"
27 #include "feature/nodelist/describe.h"
28 #include "feature/nodelist/networkstatus.h"
29 #include "feature/nodelist/nodelist.h"
30 #include "feature/nodelist/routerset.h"
31 #include "feature/rend/rendcommon.h"
32 #include "feature/rend/rendservice.h"
33 #include "lib/crypt_ops/crypto_rand.h"
34 #include "lib/crypt_ops/crypto_util.h"
36 #include "core/or/edge_connection_st.h"
37 #include "feature/nodelist/networkstatus_st.h"
38 #include "feature/nodelist/node_st.h"
39 #include "core/or/origin_circuit_st.h"
40 #include "feature/nodelist/routerstatus_st.h"
42 /* Trunnel */
43 #include "trunnel/ed25519_cert.h"
45 /* Ed25519 Basepoint value. Taken from section 5 of
46 * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03 */
47 static const char *str_ed25519_basepoint =
48 "(15112221349535400772501151409588531511"
49 "454012693041857206046113283949847762202, "
50 "463168356949264781694283940034751631413"
51 "07993866256225615783033603165251855960)";
53 #ifdef HAVE_SYS_UN_H
55 /** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
56 * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
57 * else return -ENOSYS if AF_UNIX is not supported (see function in the
58 * #else statement below). */
59 static int
60 add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
62 tor_assert(ports);
63 tor_assert(p);
64 tor_assert(p->is_unix_addr);
66 smartlist_add(ports, p);
67 return 0;
70 /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
71 * on success else return -ENOSYS if AF_UNIX is not supported (see function
72 * in the #else statement below). */
73 static int
74 set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
76 tor_assert(conn);
77 tor_assert(p);
78 tor_assert(p->is_unix_addr);
80 conn->base_.socket_family = AF_UNIX;
81 tor_addr_make_unspec(&conn->base_.addr);
82 conn->base_.port = 1;
83 conn->base_.address = tor_strdup(p->unix_addr);
84 return 0;
87 #else /* !(defined(HAVE_SYS_UN_H)) */
89 static int
90 set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
92 (void) conn;
93 (void) p;
94 return -ENOSYS;
97 static int
98 add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
100 (void) ports;
101 (void) p;
102 return -ENOSYS;
105 #endif /* defined(HAVE_SYS_UN_H) */
107 /* Helper function: The key is a digest that we compare to a node_t object
108 * current hsdir_index. */
109 static int
110 compare_digest_to_fetch_hsdir_index(const void *_key, const void **_member)
112 const char *key = _key;
113 const node_t *node = *_member;
114 return tor_memcmp(key, node->hsdir_index.fetch, DIGEST256_LEN);
117 /* Helper function: The key is a digest that we compare to a node_t object
118 * next hsdir_index. */
119 static int
120 compare_digest_to_store_first_hsdir_index(const void *_key,
121 const void **_member)
123 const char *key = _key;
124 const node_t *node = *_member;
125 return tor_memcmp(key, node->hsdir_index.store_first, DIGEST256_LEN);
128 /* Helper function: The key is a digest that we compare to a node_t object
129 * next hsdir_index. */
130 static int
131 compare_digest_to_store_second_hsdir_index(const void *_key,
132 const void **_member)
134 const char *key = _key;
135 const node_t *node = *_member;
136 return tor_memcmp(key, node->hsdir_index.store_second, DIGEST256_LEN);
139 /* Helper function: Compare two node_t objects current hsdir_index. */
140 static int
141 compare_node_fetch_hsdir_index(const void **a, const void **b)
143 const node_t *node1= *a;
144 const node_t *node2 = *b;
145 return tor_memcmp(node1->hsdir_index.fetch,
146 node2->hsdir_index.fetch,
147 DIGEST256_LEN);
150 /* Helper function: Compare two node_t objects next hsdir_index. */
151 static int
152 compare_node_store_first_hsdir_index(const void **a, const void **b)
154 const node_t *node1= *a;
155 const node_t *node2 = *b;
156 return tor_memcmp(node1->hsdir_index.store_first,
157 node2->hsdir_index.store_first,
158 DIGEST256_LEN);
161 /* Helper function: Compare two node_t objects next hsdir_index. */
162 static int
163 compare_node_store_second_hsdir_index(const void **a, const void **b)
165 const node_t *node1= *a;
166 const node_t *node2 = *b;
167 return tor_memcmp(node1->hsdir_index.store_second,
168 node2->hsdir_index.store_second,
169 DIGEST256_LEN);
172 /* Allocate and return a string containing the path to filename in directory.
173 * This function will never return NULL. The caller must free this path. */
174 char *
175 hs_path_from_filename(const char *directory, const char *filename)
177 char *file_path = NULL;
179 tor_assert(directory);
180 tor_assert(filename);
182 tor_asprintf(&file_path, "%s%s%s", directory, PATH_SEPARATOR, filename);
183 return file_path;
186 /* Make sure that the directory for <b>service</b> is private, using the config
187 * <b>username</b>.
188 * If <b>create</b> is true:
189 * - if the directory exists, change permissions if needed,
190 * - if the directory does not exist, create it with the correct permissions.
191 * If <b>create</b> is false:
192 * - if the directory exists, check permissions,
193 * - if the directory does not exist, check if we think we can create it.
194 * Return 0 on success, -1 on failure. */
196 hs_check_service_private_dir(const char *username, const char *path,
197 unsigned int dir_group_readable,
198 unsigned int create)
200 cpd_check_t check_opts = CPD_NONE;
202 tor_assert(path);
204 if (create) {
205 check_opts |= CPD_CREATE;
206 } else {
207 check_opts |= CPD_CHECK_MODE_ONLY;
208 check_opts |= CPD_CHECK;
210 if (dir_group_readable) {
211 check_opts |= CPD_GROUP_READ;
213 /* Check/create directory */
214 if (check_private_dir(path, check_opts, username) < 0) {
215 return -1;
217 return 0;
220 /* Default, minimum, and maximum values for the maximum rendezvous failures
221 * consensus parameter. */
222 #define MAX_REND_FAILURES_DEFAULT 2
223 #define MAX_REND_FAILURES_MIN 1
224 #define MAX_REND_FAILURES_MAX 10
226 /** How many times will a hidden service operator attempt to connect to
227 * a requested rendezvous point before giving up? */
229 hs_get_service_max_rend_failures(void)
231 return networkstatus_get_param(NULL, "hs_service_max_rdv_failures",
232 MAX_REND_FAILURES_DEFAULT,
233 MAX_REND_FAILURES_MIN,
234 MAX_REND_FAILURES_MAX);
237 /** Get the default HS time period length in minutes from the consensus. */
238 STATIC uint64_t
239 get_time_period_length(void)
241 /* If we are on a test network, make the time period smaller than normal so
242 that we actually see it rotate. Specifically, make it the same length as
243 an SRV protocol run. */
244 if (get_options()->TestingTorNetwork) {
245 unsigned run_duration = sr_state_get_protocol_run_duration();
246 /* An SRV run should take more than a minute (it's 24 rounds) */
247 tor_assert_nonfatal(run_duration > 60);
248 /* Turn it from seconds to minutes before returning: */
249 return sr_state_get_protocol_run_duration() / 60;
252 int32_t time_period_length = networkstatus_get_param(NULL, "hsdir_interval",
253 HS_TIME_PERIOD_LENGTH_DEFAULT,
254 HS_TIME_PERIOD_LENGTH_MIN,
255 HS_TIME_PERIOD_LENGTH_MAX);
256 /* Make sure it's a positive value. */
257 tor_assert(time_period_length > 0);
258 /* uint64_t will always be able to contain a positive int32_t */
259 return (uint64_t) time_period_length;
262 /** Get the HS time period number at time <b>now</b>. If <b>now</b> is not set,
263 * we try to get the time ourselves from a live consensus. */
264 uint64_t
265 hs_get_time_period_num(time_t now)
267 uint64_t time_period_num;
268 time_t current_time;
270 /* If no time is specified, set current time based on consensus time, and
271 * only fall back to system time if that fails. */
272 if (now != 0) {
273 current_time = now;
274 } else {
275 networkstatus_t *ns = networkstatus_get_live_consensus(approx_time());
276 current_time = ns ? ns->valid_after : approx_time();
279 /* Start by calculating minutes since the epoch */
280 uint64_t time_period_length = get_time_period_length();
281 uint64_t minutes_since_epoch = current_time / 60;
283 /* Apply the rotation offset as specified by prop224 (section
284 * [TIME-PERIODS]), so that new time periods synchronize nicely with SRV
285 * publication */
286 unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
287 time_period_rotation_offset /= 60; /* go from seconds to minutes */
288 tor_assert(minutes_since_epoch > time_period_rotation_offset);
289 minutes_since_epoch -= time_period_rotation_offset;
291 /* Calculate the time period */
292 time_period_num = minutes_since_epoch / time_period_length;
293 return time_period_num;
296 /** Get the number of the _upcoming_ HS time period, given that the current
297 * time is <b>now</b>. If <b>now</b> is not set, we try to get the time from a
298 * live consensus. */
299 uint64_t
300 hs_get_next_time_period_num(time_t now)
302 return hs_get_time_period_num(now) + 1;
305 /* Get the number of the _previous_ HS time period, given that the current time
306 * is <b>now</b>. If <b>now</b> is not set, we try to get the time from a live
307 * consensus. */
308 uint64_t
309 hs_get_previous_time_period_num(time_t now)
311 return hs_get_time_period_num(now) - 1;
314 /* Return the start time of the upcoming time period based on <b>now</b>. If
315 <b>now</b> is not set, we try to get the time ourselves from a live
316 consensus. */
317 time_t
318 hs_get_start_time_of_next_time_period(time_t now)
320 uint64_t time_period_length = get_time_period_length();
322 /* Get start time of next time period */
323 uint64_t next_time_period_num = hs_get_next_time_period_num(now);
324 uint64_t start_of_next_tp_in_mins = next_time_period_num *time_period_length;
326 /* Apply rotation offset as specified by prop224 section [TIME-PERIODS] */
327 unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
328 return (time_t)(start_of_next_tp_in_mins * 60 + time_period_rotation_offset);
331 /* Create a new rend_data_t for a specific given <b>version</b>.
332 * Return a pointer to the newly allocated data structure. */
333 static rend_data_t *
334 rend_data_alloc(uint32_t version)
336 rend_data_t *rend_data = NULL;
338 switch (version) {
339 case HS_VERSION_TWO:
341 rend_data_v2_t *v2 = tor_malloc_zero(sizeof(*v2));
342 v2->base_.version = HS_VERSION_TWO;
343 v2->base_.hsdirs_fp = smartlist_new();
344 rend_data = &v2->base_;
345 break;
347 default:
348 tor_assert(0);
349 break;
352 return rend_data;
355 /** Free all storage associated with <b>data</b> */
356 void
357 rend_data_free_(rend_data_t *data)
359 if (!data) {
360 return;
362 /* By using our allocation function, this should always be set. */
363 tor_assert(data->hsdirs_fp);
364 /* Cleanup the HSDir identity digest. */
365 SMARTLIST_FOREACH(data->hsdirs_fp, char *, d, tor_free(d));
366 smartlist_free(data->hsdirs_fp);
367 /* Depending on the version, cleanup. */
368 switch (data->version) {
369 case HS_VERSION_TWO:
371 rend_data_v2_t *v2_data = TO_REND_DATA_V2(data);
372 tor_free(v2_data);
373 break;
375 default:
376 tor_assert(0);
380 /* Allocate and return a deep copy of <b>data</b>. */
381 rend_data_t *
382 rend_data_dup(const rend_data_t *data)
384 rend_data_t *data_dup = NULL;
385 smartlist_t *hsdirs_fp = smartlist_new();
387 tor_assert(data);
388 tor_assert(data->hsdirs_fp);
390 SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
391 smartlist_add(hsdirs_fp, tor_memdup(fp, DIGEST_LEN)));
393 switch (data->version) {
394 case HS_VERSION_TWO:
396 rend_data_v2_t *v2_data = tor_memdup(TO_REND_DATA_V2(data),
397 sizeof(*v2_data));
398 data_dup = &v2_data->base_;
399 data_dup->hsdirs_fp = hsdirs_fp;
400 break;
402 default:
403 tor_assert(0);
404 break;
407 return data_dup;
410 /* Compute the descriptor ID for each HS descriptor replica and save them. A
411 * valid onion address must be present in the <b>rend_data</b>.
413 * Return 0 on success else -1. */
414 static int
415 compute_desc_id(rend_data_t *rend_data)
417 int ret = 0;
418 unsigned replica;
419 time_t now = time(NULL);
421 tor_assert(rend_data);
423 switch (rend_data->version) {
424 case HS_VERSION_TWO:
426 rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
427 /* Compute descriptor ID for each replicas. */
428 for (replica = 0; replica < ARRAY_LENGTH(v2_data->descriptor_id);
429 replica++) {
430 ret = rend_compute_v2_desc_id(v2_data->descriptor_id[replica],
431 v2_data->onion_address,
432 v2_data->descriptor_cookie,
433 now, replica);
434 if (ret < 0) {
435 goto end;
438 break;
440 default:
441 tor_assert(0);
444 end:
445 return ret;
448 /* Allocate and initialize a rend_data_t object for a service using the
449 * provided arguments. All arguments are optional (can be NULL), except from
450 * <b>onion_address</b> which MUST be set. The <b>pk_digest</b> is the hash of
451 * the service private key. The <b>cookie</b> is the rendezvous cookie and
452 * <b>auth_type</b> is which authentiation this service is configured with.
454 * Return a valid rend_data_t pointer. This only returns a version 2 object of
455 * rend_data_t. */
456 rend_data_t *
457 rend_data_service_create(const char *onion_address, const char *pk_digest,
458 const uint8_t *cookie, rend_auth_type_t auth_type)
460 /* Create a rend_data_t object for version 2. */
461 rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
462 rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
464 /* We need at least one else the call is wrong. */
465 tor_assert(onion_address != NULL);
467 if (pk_digest) {
468 memcpy(v2->rend_pk_digest, pk_digest, sizeof(v2->rend_pk_digest));
470 if (cookie) {
471 memcpy(rend_data->rend_cookie, cookie, sizeof(rend_data->rend_cookie));
474 strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
475 v2->auth_type = auth_type;
477 return rend_data;
480 /* Allocate and initialize a rend_data_t object for a client request using the
481 * given arguments. Either an onion address or a descriptor ID is needed. Both
482 * can be given but in this case only the onion address will be used to make
483 * the descriptor fetch. The <b>cookie</b> is the rendezvous cookie and
484 * <b>auth_type</b> is which authentiation the service is configured with.
486 * Return a valid rend_data_t pointer or NULL on error meaning the
487 * descriptor IDs couldn't be computed from the given data. */
488 rend_data_t *
489 rend_data_client_create(const char *onion_address, const char *desc_id,
490 const char *cookie, rend_auth_type_t auth_type)
492 /* Create a rend_data_t object for version 2. */
493 rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
494 rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
496 /* We need at least one else the call is wrong. */
497 tor_assert(onion_address != NULL || desc_id != NULL);
499 if (cookie) {
500 memcpy(v2->descriptor_cookie, cookie, sizeof(v2->descriptor_cookie));
502 if (desc_id) {
503 memcpy(v2->desc_id_fetch, desc_id, sizeof(v2->desc_id_fetch));
505 if (onion_address) {
506 strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
507 if (compute_desc_id(rend_data) < 0) {
508 goto error;
512 v2->auth_type = auth_type;
514 return rend_data;
516 error:
517 rend_data_free(rend_data);
518 return NULL;
521 /* Return the onion address from the rend data. Depending on the version,
522 * the size of the address can vary but it's always NUL terminated. */
523 const char *
524 rend_data_get_address(const rend_data_t *rend_data)
526 tor_assert(rend_data);
528 switch (rend_data->version) {
529 case HS_VERSION_TWO:
530 return TO_REND_DATA_V2(rend_data)->onion_address;
531 default:
532 /* We should always have a supported version. */
533 tor_assert_unreached();
537 /* Return the descriptor ID for a specific replica number from the rend
538 * data. The returned data is a binary digest and depending on the version its
539 * size can vary. The size of the descriptor ID is put in <b>len_out</b> if
540 * non NULL. */
541 const char *
542 rend_data_get_desc_id(const rend_data_t *rend_data, uint8_t replica,
543 size_t *len_out)
545 tor_assert(rend_data);
547 switch (rend_data->version) {
548 case HS_VERSION_TWO:
549 tor_assert(replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS);
550 if (len_out) {
551 *len_out = DIGEST_LEN;
553 return TO_REND_DATA_V2(rend_data)->descriptor_id[replica];
554 default:
555 /* We should always have a supported version. */
556 tor_assert_unreached();
560 /* Return the public key digest using the given <b>rend_data</b>. The size of
561 * the digest is put in <b>len_out</b> (if set) which can differ depending on
562 * the version. */
563 const uint8_t *
564 rend_data_get_pk_digest(const rend_data_t *rend_data, size_t *len_out)
566 tor_assert(rend_data);
568 switch (rend_data->version) {
569 case HS_VERSION_TWO:
571 const rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
572 if (len_out) {
573 *len_out = sizeof(v2_data->rend_pk_digest);
575 return (const uint8_t *) v2_data->rend_pk_digest;
577 default:
578 /* We should always have a supported version. */
579 tor_assert_unreached();
583 /* Using the given time period number, compute the disaster shared random
584 * value and put it in srv_out. It MUST be at least DIGEST256_LEN bytes. */
585 static void
586 compute_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
588 crypto_digest_t *digest;
590 tor_assert(srv_out);
592 digest = crypto_digest256_new(DIGEST_SHA3_256);
594 /* Start setting up payload:
595 * H("shared-random-disaster" | INT_8(period_length) | INT_8(period_num)) */
596 crypto_digest_add_bytes(digest, HS_SRV_DISASTER_PREFIX,
597 HS_SRV_DISASTER_PREFIX_LEN);
599 /* Setup INT_8(period_length) | INT_8(period_num) */
601 uint64_t time_period_length = get_time_period_length();
602 char period_stuff[sizeof(uint64_t)*2];
603 size_t offset = 0;
604 set_uint64(period_stuff, tor_htonll(time_period_length));
605 offset += sizeof(uint64_t);
606 set_uint64(period_stuff+offset, tor_htonll(time_period_num));
607 offset += sizeof(uint64_t);
608 tor_assert(offset == sizeof(period_stuff));
610 crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
613 crypto_digest_get_digest(digest, (char *) srv_out, DIGEST256_LEN);
614 crypto_digest_free(digest);
617 /** Due to the high cost of computing the disaster SRV and that potentially we
618 * would have to do it thousands of times in a row, we always cache the
619 * computer disaster SRV (and its corresponding time period num) in case we
620 * want to reuse it soon after. We need to cache two SRVs, one for each active
621 * time period.
623 static uint8_t cached_disaster_srv[2][DIGEST256_LEN];
624 static uint64_t cached_time_period_nums[2] = {0};
626 /** Compute the disaster SRV value for this <b>time_period_num</b> and put it
627 * in <b>srv_out</b> (of size at least DIGEST256_LEN). First check our caches
628 * to see if we have already computed it. */
629 STATIC void
630 get_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
632 if (time_period_num == cached_time_period_nums[0]) {
633 memcpy(srv_out, cached_disaster_srv[0], DIGEST256_LEN);
634 return;
635 } else if (time_period_num == cached_time_period_nums[1]) {
636 memcpy(srv_out, cached_disaster_srv[1], DIGEST256_LEN);
637 return;
638 } else {
639 int replace_idx;
640 // Replace the lower period number.
641 if (cached_time_period_nums[0] <= cached_time_period_nums[1]) {
642 replace_idx = 0;
643 } else {
644 replace_idx = 1;
646 cached_time_period_nums[replace_idx] = time_period_num;
647 compute_disaster_srv(time_period_num, cached_disaster_srv[replace_idx]);
648 memcpy(srv_out, cached_disaster_srv[replace_idx], DIGEST256_LEN);
649 return;
653 #ifdef TOR_UNIT_TESTS
655 /** Get the first cached disaster SRV. Only used by unittests. */
656 STATIC uint8_t *
657 get_first_cached_disaster_srv(void)
659 return cached_disaster_srv[0];
662 /** Get the second cached disaster SRV. Only used by unittests. */
663 STATIC uint8_t *
664 get_second_cached_disaster_srv(void)
666 return cached_disaster_srv[1];
669 #endif /* defined(TOR_UNIT_TESTS) */
671 /* When creating a blinded key, we need a parameter which construction is as
672 * follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
674 * The nonce has a pre-defined format which uses the time period number
675 * period_num and the start of the period in second start_time_period.
677 * The secret of size secret_len is optional meaning that it can be NULL and
678 * thus will be ignored for the param construction.
680 * The result is put in param_out. */
681 static void
682 build_blinded_key_param(const ed25519_public_key_t *pubkey,
683 const uint8_t *secret, size_t secret_len,
684 uint64_t period_num, uint64_t period_length,
685 uint8_t *param_out)
687 size_t offset = 0;
688 const char blind_str[] = "Derive temporary signing key";
689 uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
690 crypto_digest_t *digest;
692 tor_assert(pubkey);
693 tor_assert(param_out);
695 /* Create the nonce N. The construction is as follow:
696 * N = "key-blind" || INT_8(period_num) || INT_8(period_length) */
697 memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
698 offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
699 set_uint64(nonce + offset, tor_htonll(period_num));
700 offset += sizeof(uint64_t);
701 set_uint64(nonce + offset, tor_htonll(period_length));
702 offset += sizeof(uint64_t);
703 tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
705 /* Generate the parameter h and the construction is as follow:
706 * h = H(BLIND_STRING | pubkey | [secret] | ed25519-basepoint | N) */
707 digest = crypto_digest256_new(DIGEST_SHA3_256);
708 crypto_digest_add_bytes(digest, blind_str, sizeof(blind_str));
709 crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
710 /* Optional secret. */
711 if (secret) {
712 crypto_digest_add_bytes(digest, (char *) secret, secret_len);
714 crypto_digest_add_bytes(digest, str_ed25519_basepoint,
715 strlen(str_ed25519_basepoint));
716 crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
718 /* Extract digest and put it in the param. */
719 crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
720 crypto_digest_free(digest);
722 memwipe(nonce, 0, sizeof(nonce));
725 /* Using an ed25519 public key and version to build the checksum of an
726 * address. Put in checksum_out. Format is:
727 * SHA3-256(".onion checksum" || PUBKEY || VERSION)
729 * checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
730 static void
731 build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
732 uint8_t *checksum_out)
734 size_t offset = 0;
735 char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
737 /* Build checksum data. */
738 memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
739 HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
740 offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
741 memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
742 offset += ED25519_PUBKEY_LEN;
743 set_uint8(data + offset, version);
744 offset += sizeof(version);
745 tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
747 /* Hash the data payload to create the checksum. */
748 crypto_digest256((char *) checksum_out, data, sizeof(data),
749 DIGEST_SHA3_256);
752 /* Using an ed25519 public key, checksum and version to build the binary
753 * representation of a service address. Put in addr_out. Format is:
754 * addr_out = PUBKEY || CHECKSUM || VERSION
756 * addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
757 static void
758 build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
759 uint8_t version, char *addr_out)
761 size_t offset = 0;
763 tor_assert(key);
764 tor_assert(checksum);
766 memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
767 offset += ED25519_PUBKEY_LEN;
768 memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
769 offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
770 set_uint8(addr_out + offset, version);
771 offset += sizeof(uint8_t);
772 tor_assert(offset == HS_SERVICE_ADDR_LEN);
775 /* Helper for hs_parse_address(): Using a binary representation of a service
776 * address, parse its content into the key_out, checksum_out and version_out.
777 * Any out variable can be NULL in case the caller would want only one field.
778 * checksum_out MUST at least be 2 bytes long. address must be at least
779 * HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
780 static void
781 hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
782 uint8_t *checksum_out, uint8_t *version_out)
784 size_t offset = 0;
786 tor_assert(address);
788 if (key_out) {
789 /* First is the key. */
790 memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
792 offset += ED25519_PUBKEY_LEN;
793 if (checksum_out) {
794 /* Followed by a 2 bytes checksum. */
795 memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
797 offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
798 if (version_out) {
799 /* Finally, version value is 1 byte. */
800 *version_out = get_uint8(address + offset);
802 offset += sizeof(uint8_t);
803 /* Extra safety. */
804 tor_assert(offset == HS_SERVICE_ADDR_LEN);
807 /* Using the given identity public key and a blinded public key, compute the
808 * subcredential and put it in subcred_out (must be of size DIGEST256_LEN).
809 * This can't fail. */
810 void
811 hs_get_subcredential(const ed25519_public_key_t *identity_pk,
812 const ed25519_public_key_t *blinded_pk,
813 uint8_t *subcred_out)
815 uint8_t credential[DIGEST256_LEN];
816 crypto_digest_t *digest;
818 tor_assert(identity_pk);
819 tor_assert(blinded_pk);
820 tor_assert(subcred_out);
822 /* First, build the credential. Construction is as follow:
823 * credential = H("credential" | public-identity-key) */
824 digest = crypto_digest256_new(DIGEST_SHA3_256);
825 crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
826 HS_CREDENTIAL_PREFIX_LEN);
827 crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
828 ED25519_PUBKEY_LEN);
829 crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
830 crypto_digest_free(digest);
832 /* Now, compute the subcredential. Construction is as follow:
833 * subcredential = H("subcredential" | credential | blinded-public-key). */
834 digest = crypto_digest256_new(DIGEST_SHA3_256);
835 crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
836 HS_SUBCREDENTIAL_PREFIX_LEN);
837 crypto_digest_add_bytes(digest, (const char *) credential,
838 sizeof(credential));
839 crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
840 ED25519_PUBKEY_LEN);
841 crypto_digest_get_digest(digest, (char *) subcred_out, DIGEST256_LEN);
842 crypto_digest_free(digest);
844 memwipe(credential, 0, sizeof(credential));
847 /* From the given list of hidden service ports, find the ones that match the
848 * given edge connection conn, pick one at random and use it to set the
849 * connection address. Return 0 on success or -1 if none. */
851 hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
853 rend_service_port_config_t *chosen_port;
854 unsigned int warn_once = 0;
855 smartlist_t *matching_ports;
857 tor_assert(ports);
858 tor_assert(conn);
860 matching_ports = smartlist_new();
861 SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
862 if (TO_CONN(conn)->port != p->virtual_port) {
863 continue;
865 if (!(p->is_unix_addr)) {
866 smartlist_add(matching_ports, p);
867 } else {
868 if (add_unix_port(matching_ports, p)) {
869 if (!warn_once) {
870 /* Unix port not supported so warn only once. */
871 log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d "
872 "which is unsupported on this platform. "
873 "Ignoring it.",
874 TO_CONN(conn)->port);
876 warn_once++;
879 } SMARTLIST_FOREACH_END(p);
881 chosen_port = smartlist_choose(matching_ports);
882 smartlist_free(matching_ports);
883 if (chosen_port) {
884 if (!(chosen_port->is_unix_addr)) {
885 /* save the original destination before we overwrite it */
886 if (conn->hs_ident) {
887 conn->hs_ident->orig_virtual_port = TO_CONN(conn)->port;
890 /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
891 tor_addr_copy(&TO_CONN(conn)->addr, &chosen_port->real_addr);
892 TO_CONN(conn)->port = chosen_port->real_port;
893 } else {
894 if (set_unix_port(conn, chosen_port)) {
895 /* Simply impossible to end up here else we were able to add a Unix
896 * port without AF_UNIX support... ? */
897 tor_assert(0);
901 return (chosen_port) ? 0 : -1;
904 /* Using a base32 representation of a service address, parse its content into
905 * the key_out, checksum_out and version_out. Any out variable can be NULL in
906 * case the caller would want only one field. checksum_out MUST at least be 2
907 * bytes long.
909 * Return 0 if parsing went well; return -1 in case of error. */
911 hs_parse_address(const char *address, ed25519_public_key_t *key_out,
912 uint8_t *checksum_out, uint8_t *version_out)
914 char decoded[HS_SERVICE_ADDR_LEN];
916 tor_assert(address);
918 /* Obvious length check. */
919 if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
920 log_warn(LD_REND, "Service address %s has an invalid length. "
921 "Expected %lu but got %lu.",
922 escaped_safe_str(address),
923 (unsigned long) HS_SERVICE_ADDR_LEN_BASE32,
924 (unsigned long) strlen(address));
925 goto invalid;
928 /* Decode address so we can extract needed fields. */
929 if (base32_decode(decoded, sizeof(decoded), address, strlen(address)) < 0) {
930 log_warn(LD_REND, "Service address %s can't be decoded.",
931 escaped_safe_str(address));
932 goto invalid;
935 /* Parse the decoded address into the fields we need. */
936 hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
938 return 0;
939 invalid:
940 return -1;
943 /* Validate a given onion address. The length, the base32 decoding and
944 * checksum are validated. Return 1 if valid else 0. */
946 hs_address_is_valid(const char *address)
948 uint8_t version;
949 uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
950 uint8_t target_checksum[DIGEST256_LEN];
951 ed25519_public_key_t service_pubkey;
953 /* Parse the decoded address into the fields we need. */
954 if (hs_parse_address(address, &service_pubkey, checksum, &version) < 0) {
955 goto invalid;
958 /* Get the checksum it's suppose to be and compare it with what we have
959 * encoded in the address. */
960 build_hs_checksum(&service_pubkey, version, target_checksum);
961 if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
962 log_warn(LD_REND, "Service address %s invalid checksum.",
963 escaped_safe_str(address));
964 goto invalid;
967 /* Validate that this pubkey does not have a torsion component. We need to do
968 * this on the prop224 client-side so that attackers can't give equivalent
969 * forms of an onion address to users. */
970 if (ed25519_validate_pubkey(&service_pubkey) < 0) {
971 log_warn(LD_REND, "Service address %s has bad pubkey .",
972 escaped_safe_str(address));
973 goto invalid;
976 /* Valid address. */
977 return 1;
978 invalid:
979 return 0;
982 /* Build a service address using an ed25519 public key and a given version.
983 * The returned address is base32 encoded and put in addr_out. The caller MUST
984 * make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
986 * Format is as follow:
987 * base32(PUBKEY || CHECKSUM || VERSION)
988 * CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
989 * */
990 void
991 hs_build_address(const ed25519_public_key_t *key, uint8_t version,
992 char *addr_out)
994 uint8_t checksum[DIGEST256_LEN];
995 char address[HS_SERVICE_ADDR_LEN];
997 tor_assert(key);
998 tor_assert(addr_out);
1000 /* Get the checksum of the address. */
1001 build_hs_checksum(key, version, checksum);
1002 /* Get the binary address representation. */
1003 build_hs_address(key, checksum, version, address);
1005 /* Encode the address. addr_out will be NUL terminated after this. */
1006 base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
1007 sizeof(address));
1008 /* Validate what we just built. */
1009 tor_assert(hs_address_is_valid(addr_out));
1012 /* Return a newly allocated copy of lspec. */
1013 link_specifier_t *
1014 hs_link_specifier_dup(const link_specifier_t *lspec)
1016 link_specifier_t *result = link_specifier_new();
1017 memcpy(result, lspec, sizeof(*result));
1018 /* The unrecognized field is a dynamic array so make sure to copy its
1019 * content and not the pointer. */
1020 link_specifier_setlen_un_unrecognized(
1021 result, link_specifier_getlen_un_unrecognized(lspec));
1022 if (link_specifier_getlen_un_unrecognized(result)) {
1023 memcpy(link_specifier_getarray_un_unrecognized(result),
1024 link_specifier_getconstarray_un_unrecognized(lspec),
1025 link_specifier_getlen_un_unrecognized(result));
1027 return result;
1030 /* From a given ed25519 public key pk and an optional secret, compute a
1031 * blinded public key and put it in blinded_pk_out. This is only useful to
1032 * the client side because the client only has access to the identity public
1033 * key of the service. */
1034 void
1035 hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
1036 const uint8_t *secret, size_t secret_len,
1037 uint64_t time_period_num,
1038 ed25519_public_key_t *blinded_pk_out)
1040 /* Our blinding key API requires a 32 bytes parameter. */
1041 uint8_t param[DIGEST256_LEN];
1043 tor_assert(pk);
1044 tor_assert(blinded_pk_out);
1045 tor_assert(!tor_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
1047 build_blinded_key_param(pk, secret, secret_len,
1048 time_period_num, get_time_period_length(), param);
1049 ed25519_public_blind(blinded_pk_out, pk, param);
1051 memwipe(param, 0, sizeof(param));
1054 /* From a given ed25519 keypair kp and an optional secret, compute a blinded
1055 * keypair for the current time period and put it in blinded_kp_out. This is
1056 * only useful by the service side because the client doesn't have access to
1057 * the identity secret key. */
1058 void
1059 hs_build_blinded_keypair(const ed25519_keypair_t *kp,
1060 const uint8_t *secret, size_t secret_len,
1061 uint64_t time_period_num,
1062 ed25519_keypair_t *blinded_kp_out)
1064 /* Our blinding key API requires a 32 bytes parameter. */
1065 uint8_t param[DIGEST256_LEN];
1067 tor_assert(kp);
1068 tor_assert(blinded_kp_out);
1069 /* Extra safety. A zeroed key is bad. */
1070 tor_assert(!tor_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
1071 tor_assert(!tor_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
1073 build_blinded_key_param(&kp->pubkey, secret, secret_len,
1074 time_period_num, get_time_period_length(), param);
1075 ed25519_keypair_blind(blinded_kp_out, kp, param);
1077 memwipe(param, 0, sizeof(param));
1080 /* Return true if we are currently in the time segment between a new time
1081 * period and a new SRV (in the real network that happens between 12:00 and
1082 * 00:00 UTC). Here is a diagram showing exactly when this returns true:
1084 * +------------------------------------------------------------------+
1085 * | |
1086 * | 00:00 12:00 00:00 12:00 00:00 12:00 |
1087 * | SRV#1 TP#1 SRV#2 TP#2 SRV#3 TP#3 |
1088 * | |
1089 * | $==========|-----------$===========|-----------$===========| |
1090 * | ^^^^^^^^^^^^ ^^^^^^^^^^^^ |
1091 * | |
1092 * +------------------------------------------------------------------+
1094 MOCK_IMPL(int,
1095 hs_in_period_between_tp_and_srv,(const networkstatus_t *consensus, time_t now))
1097 time_t valid_after;
1098 time_t srv_start_time, tp_start_time;
1100 if (!consensus) {
1101 consensus = networkstatus_get_live_consensus(now);
1102 if (!consensus) {
1103 return 0;
1107 /* Get start time of next TP and of current SRV protocol run, and check if we
1108 * are between them. */
1109 valid_after = consensus->valid_after;
1110 srv_start_time = sr_state_get_start_time_of_current_protocol_run();
1111 tp_start_time = hs_get_start_time_of_next_time_period(srv_start_time);
1113 if (valid_after >= srv_start_time && valid_after < tp_start_time) {
1114 return 0;
1117 return 1;
1120 /* Return 1 if any virtual port in ports needs a circuit with good uptime.
1121 * Else return 0. */
1123 hs_service_requires_uptime_circ(const smartlist_t *ports)
1125 tor_assert(ports);
1127 SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
1128 if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
1129 p->virtual_port)) {
1130 return 1;
1132 } SMARTLIST_FOREACH_END(p);
1133 return 0;
1136 /* Build hs_index which is used to find the responsible hsdirs. This index
1137 * value is used to select the responsible HSDir where their hsdir_index is
1138 * closest to this value.
1139 * SHA3-256("store-at-idx" | blinded_public_key |
1140 * INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) )
1142 * hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
1143 void
1144 hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
1145 uint64_t period_num, uint8_t *hs_index_out)
1147 crypto_digest_t *digest;
1149 tor_assert(blinded_pk);
1150 tor_assert(hs_index_out);
1152 /* Build hs_index. See construction at top of function comment. */
1153 digest = crypto_digest256_new(DIGEST_SHA3_256);
1154 crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
1155 crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
1156 ED25519_PUBKEY_LEN);
1158 /* Now setup INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) */
1160 uint64_t period_length = get_time_period_length();
1161 char buf[sizeof(uint64_t)*3];
1162 size_t offset = 0;
1163 set_uint64(buf, tor_htonll(replica));
1164 offset += sizeof(uint64_t);
1165 set_uint64(buf+offset, tor_htonll(period_length));
1166 offset += sizeof(uint64_t);
1167 set_uint64(buf+offset, tor_htonll(period_num));
1168 offset += sizeof(uint64_t);
1169 tor_assert(offset == sizeof(buf));
1171 crypto_digest_add_bytes(digest, buf, sizeof(buf));
1174 crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
1175 crypto_digest_free(digest);
1178 /* Build hsdir_index which is used to find the responsible hsdirs. This is the
1179 * index value that is compare to the hs_index when selecting an HSDir.
1180 * SHA3-256("node-idx" | node_identity |
1181 * shared_random_value | INT_8(period_length) | INT_8(period_num) )
1183 * hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
1184 void
1185 hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
1186 const uint8_t *srv_value, uint64_t period_num,
1187 uint8_t *hsdir_index_out)
1189 crypto_digest_t *digest;
1191 tor_assert(identity_pk);
1192 tor_assert(srv_value);
1193 tor_assert(hsdir_index_out);
1195 /* Build hsdir_index. See construction at top of function comment. */
1196 digest = crypto_digest256_new(DIGEST_SHA3_256);
1197 crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
1198 crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
1199 ED25519_PUBKEY_LEN);
1200 crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
1203 uint64_t time_period_length = get_time_period_length();
1204 char period_stuff[sizeof(uint64_t)*2];
1205 size_t offset = 0;
1206 set_uint64(period_stuff, tor_htonll(period_num));
1207 offset += sizeof(uint64_t);
1208 set_uint64(period_stuff+offset, tor_htonll(time_period_length));
1209 offset += sizeof(uint64_t);
1210 tor_assert(offset == sizeof(period_stuff));
1212 crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
1215 crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
1216 crypto_digest_free(digest);
1219 /* Return a newly allocated buffer containing the current shared random value
1220 * or if not present, a disaster value is computed using the given time period
1221 * number. If a consensus is provided in <b>ns</b>, use it to get the SRV
1222 * value. This function can't fail. */
1223 uint8_t *
1224 hs_get_current_srv(uint64_t time_period_num, const networkstatus_t *ns)
1226 uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
1227 const sr_srv_t *current_srv = sr_get_current(ns);
1229 if (current_srv) {
1230 memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
1231 } else {
1232 /* Disaster mode. */
1233 get_disaster_srv(time_period_num, sr_value);
1235 return sr_value;
1238 /* Return a newly allocated buffer containing the previous shared random
1239 * value or if not present, a disaster value is computed using the given time
1240 * period number. This function can't fail. */
1241 uint8_t *
1242 hs_get_previous_srv(uint64_t time_period_num, const networkstatus_t *ns)
1244 uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
1245 const sr_srv_t *previous_srv = sr_get_previous(ns);
1247 if (previous_srv) {
1248 memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
1249 } else {
1250 /* Disaster mode. */
1251 get_disaster_srv(time_period_num, sr_value);
1253 return sr_value;
1256 /* Return the number of replicas defined by a consensus parameter or the
1257 * default value. */
1258 int32_t
1259 hs_get_hsdir_n_replicas(void)
1261 /* The [1,16] range is a specification requirement. */
1262 return networkstatus_get_param(NULL, "hsdir_n_replicas",
1263 HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
1266 /* Return the spread fetch value defined by a consensus parameter or the
1267 * default value. */
1268 int32_t
1269 hs_get_hsdir_spread_fetch(void)
1271 /* The [1,128] range is a specification requirement. */
1272 return networkstatus_get_param(NULL, "hsdir_spread_fetch",
1273 HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
1276 /* Return the spread store value defined by a consensus parameter or the
1277 * default value. */
1278 int32_t
1279 hs_get_hsdir_spread_store(void)
1281 /* The [1,128] range is a specification requirement. */
1282 return networkstatus_get_param(NULL, "hsdir_spread_store",
1283 HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
1286 /** <b>node</b> is an HSDir so make sure that we have assigned an hsdir index.
1287 * Return 0 if everything is as expected, else return -1. */
1288 static int
1289 node_has_hsdir_index(const node_t *node)
1291 tor_assert(node_supports_v3_hsdir(node));
1293 /* A node can't have an HSDir index without a descriptor since we need desc
1294 * to get its ed25519 key. for_direct_connect should be zero, since we
1295 * always use the consensus-indexed node's keys to build the hash ring, even
1296 * if some of the consensus-indexed nodes are also bridges. */
1297 if (!node_has_preferred_descriptor(node, 0)) {
1298 return 0;
1301 /* At this point, since the node has a desc, this node must also have an
1302 * hsdir index. If not, something went wrong, so BUG out. */
1303 if (BUG(tor_mem_is_zero((const char*)node->hsdir_index.fetch,
1304 DIGEST256_LEN))) {
1305 return 0;
1307 if (BUG(tor_mem_is_zero((const char*)node->hsdir_index.store_first,
1308 DIGEST256_LEN))) {
1309 return 0;
1311 if (BUG(tor_mem_is_zero((const char*)node->hsdir_index.store_second,
1312 DIGEST256_LEN))) {
1313 return 0;
1316 return 1;
1319 /* For a given blinded key and time period number, get the responsible HSDir
1320 * and put their routerstatus_t object in the responsible_dirs list. If
1321 * 'use_second_hsdir_index' is true, use the second hsdir_index of the node_t
1322 * is used. If 'for_fetching' is true, the spread fetch consensus parameter is
1323 * used else the spread store is used which is only for upload. This function
1324 * can't fail but it is possible that the responsible_dirs list contains fewer
1325 * nodes than expected.
1327 * This function goes over the latest consensus routerstatus list and sorts it
1328 * by their node_t hsdir_index then does a binary search to find the closest
1329 * node. All of this makes it a bit CPU intensive so use it wisely. */
1330 void
1331 hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
1332 uint64_t time_period_num, int use_second_hsdir_index,
1333 int for_fetching, smartlist_t *responsible_dirs)
1335 smartlist_t *sorted_nodes;
1336 /* The compare function used for the smartlist bsearch. We have two
1337 * different depending on is_next_period. */
1338 int (*cmp_fct)(const void *, const void **);
1340 tor_assert(blinded_pk);
1341 tor_assert(responsible_dirs);
1343 sorted_nodes = smartlist_new();
1345 /* Make sure we actually have a live consensus */
1346 networkstatus_t *c = networkstatus_get_live_consensus(approx_time());
1347 if (!c || smartlist_len(c->routerstatus_list) == 0) {
1348 log_warn(LD_REND, "No live consensus so we can't get the responsible "
1349 "hidden service directories.");
1350 goto done;
1353 /* Ensure the nodelist is fresh, since it contains the HSDir indices. */
1354 nodelist_ensure_freshness(c);
1356 /* Add every node_t that support HSDir v3 for which we do have a valid
1357 * hsdir_index already computed for them for this consensus. */
1359 SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
1360 /* Even though this node_t object won't be modified and should be const,
1361 * we can't add const object in a smartlist_t. */
1362 node_t *n = node_get_mutable_by_id(rs->identity_digest);
1363 tor_assert(n);
1364 if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
1365 if (!node_has_hsdir_index(n)) {
1366 log_info(LD_GENERAL, "Node %s was found without hsdir index.",
1367 node_describe(n));
1368 continue;
1370 smartlist_add(sorted_nodes, n);
1372 } SMARTLIST_FOREACH_END(rs);
1374 if (smartlist_len(sorted_nodes) == 0) {
1375 log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
1376 goto done;
1379 /* First thing we have to do is sort all node_t by hsdir_index. The
1380 * is_next_period tells us if we want the current or the next one. Set the
1381 * bsearch compare function also while we are at it. */
1382 if (for_fetching) {
1383 smartlist_sort(sorted_nodes, compare_node_fetch_hsdir_index);
1384 cmp_fct = compare_digest_to_fetch_hsdir_index;
1385 } else if (use_second_hsdir_index) {
1386 smartlist_sort(sorted_nodes, compare_node_store_second_hsdir_index);
1387 cmp_fct = compare_digest_to_store_second_hsdir_index;
1388 } else {
1389 smartlist_sort(sorted_nodes, compare_node_store_first_hsdir_index);
1390 cmp_fct = compare_digest_to_store_first_hsdir_index;
1393 /* For all replicas, we'll select a set of HSDirs using the consensus
1394 * parameters and the sorted list. The replica starting at value 1 is
1395 * defined by the specification. */
1396 for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
1397 int idx, start, found, n_added = 0;
1398 uint8_t hs_index[DIGEST256_LEN] = {0};
1399 /* Number of node to add to the responsible dirs list depends on if we are
1400 * trying to fetch or store. A client always fetches. */
1401 int n_to_add = (for_fetching) ? hs_get_hsdir_spread_fetch() :
1402 hs_get_hsdir_spread_store();
1404 /* Get the index that we should use to select the node. */
1405 hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
1406 /* The compare function pointer has been set correctly earlier. */
1407 start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
1408 &found);
1409 /* Getting the length of the list if no member is greater than the key we
1410 * are looking for so start at the first element. */
1411 if (idx == smartlist_len(sorted_nodes)) {
1412 start = idx = 0;
1414 while (n_added < n_to_add) {
1415 const node_t *node = smartlist_get(sorted_nodes, idx);
1416 /* If the node has already been selected which is possible between
1417 * replicas, the specification says to skip over. */
1418 if (!smartlist_contains(responsible_dirs, node->rs)) {
1419 smartlist_add(responsible_dirs, node->rs);
1420 ++n_added;
1422 if (++idx == smartlist_len(sorted_nodes)) {
1423 /* Wrap if we've reached the end of the list. */
1424 idx = 0;
1426 if (idx == start) {
1427 /* We've gone over the whole list, stop and avoid infinite loop. */
1428 break;
1433 done:
1434 smartlist_free(sorted_nodes);
1437 /*********************** HSDir request tracking ***************************/
1439 /** Return the period for which a hidden service directory cannot be queried
1440 * for the same descriptor ID again, taking TestingTorNetwork into account. */
1441 time_t
1442 hs_hsdir_requery_period(const or_options_t *options)
1444 tor_assert(options);
1446 if (options->TestingTorNetwork) {
1447 return REND_HID_SERV_DIR_REQUERY_PERIOD_TESTING;
1448 } else {
1449 return REND_HID_SERV_DIR_REQUERY_PERIOD;
1453 /** Tracks requests for fetching hidden service descriptors. It's used by
1454 * hidden service clients, to avoid querying HSDirs that have already failed
1455 * giving back a descriptor. The same data structure is used to track both v2
1456 * and v3 HS descriptor requests.
1458 * The string map is a key/value store that contains the last request times to
1459 * hidden service directories for certain queries. Specifically:
1461 * key = base32(hsdir_identity) + base32(hs_identity)
1462 * value = time_t of last request for that hs_identity to that HSDir
1464 * where 'hsdir_identity' is the identity digest of the HSDir node, and
1465 * 'hs_identity' is the descriptor ID of the HS in the v2 case, or the ed25519
1466 * blinded public key of the HS in the v3 case. */
1467 static strmap_t *last_hid_serv_requests_ = NULL;
1469 /** Returns last_hid_serv_requests_, initializing it to a new strmap if
1470 * necessary. */
1471 STATIC strmap_t *
1472 get_last_hid_serv_requests(void)
1474 if (!last_hid_serv_requests_)
1475 last_hid_serv_requests_ = strmap_new();
1476 return last_hid_serv_requests_;
1479 /** Look up the last request time to hidden service directory <b>hs_dir</b>
1480 * for descriptor request key <b>req_key_str</b> which is the descriptor ID
1481 * for a v2 service or the blinded key for v3. If <b>set</b> is non-zero,
1482 * assign the current time <b>now</b> and return that. Otherwise, return the
1483 * most recent request time, or 0 if no such request has been sent before. */
1484 time_t
1485 hs_lookup_last_hid_serv_request(routerstatus_t *hs_dir,
1486 const char *req_key_str,
1487 time_t now, int set)
1489 char hsdir_id_base32[BASE32_DIGEST_LEN + 1];
1490 char *hsdir_desc_comb_id = NULL;
1491 time_t *last_request_ptr;
1492 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
1494 /* Create the key */
1495 base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
1496 hs_dir->identity_digest, DIGEST_LEN);
1497 tor_asprintf(&hsdir_desc_comb_id, "%s%s", hsdir_id_base32, req_key_str);
1499 if (set) {
1500 time_t *oldptr;
1501 last_request_ptr = tor_malloc_zero(sizeof(time_t));
1502 *last_request_ptr = now;
1503 oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
1504 last_request_ptr);
1505 tor_free(oldptr);
1506 } else {
1507 last_request_ptr = strmap_get(last_hid_serv_requests,
1508 hsdir_desc_comb_id);
1511 tor_free(hsdir_desc_comb_id);
1512 return (last_request_ptr) ? *last_request_ptr : 0;
1515 /** Clean the history of request times to hidden service directories, so that
1516 * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
1517 * seconds any more. */
1518 void
1519 hs_clean_last_hid_serv_requests(time_t now)
1521 strmap_iter_t *iter;
1522 time_t cutoff = now - hs_hsdir_requery_period(get_options());
1523 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
1524 for (iter = strmap_iter_init(last_hid_serv_requests);
1525 !strmap_iter_done(iter); ) {
1526 const char *key;
1527 void *val;
1528 time_t *ent;
1529 strmap_iter_get(iter, &key, &val);
1530 ent = (time_t *) val;
1531 if (*ent < cutoff) {
1532 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
1533 tor_free(ent);
1534 } else {
1535 iter = strmap_iter_next(last_hid_serv_requests, iter);
1540 /** Remove all requests related to the descriptor request key string
1541 * <b>req_key_str</b> from the history of times of requests to hidden service
1542 * directories.
1544 * This is called from rend_client_note_connection_attempt_ended(), which
1545 * must be idempotent, so any future changes to this function must leave it
1546 * idempotent too. */
1547 void
1548 hs_purge_hid_serv_from_last_hid_serv_requests(const char *req_key_str)
1550 strmap_iter_t *iter;
1551 strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
1553 for (iter = strmap_iter_init(last_hid_serv_requests);
1554 !strmap_iter_done(iter); ) {
1555 const char *key;
1556 void *val;
1557 strmap_iter_get(iter, &key, &val);
1559 /* XXX: The use of REND_DESC_ID_V2_LEN_BASE32 is very wrong in terms of
1560 * semantic, see #23305. */
1562 /* This strmap contains variable-sized elements so this is a basic length
1563 * check on the strings we are about to compare. The key is variable sized
1564 * since it's composed as follows:
1565 * key = base32(hsdir_identity) + base32(req_key_str)
1566 * where 'req_key_str' is the descriptor ID of the HS in the v2 case, or
1567 * the ed25519 blinded public key of the HS in the v3 case. */
1568 if (strlen(key) < REND_DESC_ID_V2_LEN_BASE32 + strlen(req_key_str)) {
1569 iter = strmap_iter_next(last_hid_serv_requests, iter);
1570 continue;
1573 /* Check if the tracked request matches our request key */
1574 if (tor_memeq(key + REND_DESC_ID_V2_LEN_BASE32, req_key_str,
1575 strlen(req_key_str))) {
1576 iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
1577 tor_free(val);
1578 } else {
1579 iter = strmap_iter_next(last_hid_serv_requests, iter);
1584 /** Purge the history of request times to hidden service directories,
1585 * so that future lookups of an HS descriptor will not fail because we
1586 * accessed all of the HSDir relays responsible for the descriptor
1587 * recently. */
1588 void
1589 hs_purge_last_hid_serv_requests(void)
1591 /* Don't create the table if it doesn't exist yet (and it may very
1592 * well not exist if the user hasn't accessed any HSes)... */
1593 strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
1594 /* ... and let get_last_hid_serv_requests re-create it for us if
1595 * necessary. */
1596 last_hid_serv_requests_ = NULL;
1598 if (old_last_hid_serv_requests != NULL) {
1599 log_info(LD_REND, "Purging client last-HS-desc-request-time table");
1600 strmap_free(old_last_hid_serv_requests, tor_free_);
1604 /***********************************************************************/
1606 /** Given the list of responsible HSDirs in <b>responsible_dirs</b>, pick the
1607 * one that we should use to fetch a descriptor right now. Take into account
1608 * previous failed attempts at fetching this descriptor from HSDirs using the
1609 * string identifier <b>req_key_str</b>.
1611 * Steals ownership of <b>responsible_dirs</b>.
1613 * Return the routerstatus of the chosen HSDir if successful, otherwise return
1614 * NULL if no HSDirs are worth trying right now. */
1615 routerstatus_t *
1616 hs_pick_hsdir(smartlist_t *responsible_dirs, const char *req_key_str)
1618 smartlist_t *usable_responsible_dirs = smartlist_new();
1619 const or_options_t *options = get_options();
1620 routerstatus_t *hs_dir;
1621 time_t now = time(NULL);
1622 int excluded_some;
1624 tor_assert(req_key_str);
1626 /* Clean outdated request history first. */
1627 hs_clean_last_hid_serv_requests(now);
1629 /* Only select those hidden service directories to which we did not send a
1630 * request recently and for which we have a router descriptor here.
1632 * Use for_direct_connect==0 even if we will be connecting to the node
1633 * directly, since we always use the key information in the
1634 * consensus-indexed node descriptors for building the index.
1636 SMARTLIST_FOREACH_BEGIN(responsible_dirs, routerstatus_t *, dir) {
1637 time_t last = hs_lookup_last_hid_serv_request(dir, req_key_str, 0, 0);
1638 const node_t *node = node_get_by_id(dir->identity_digest);
1639 if (last + hs_hsdir_requery_period(options) >= now ||
1640 !node || !node_has_preferred_descriptor(node, 0)) {
1641 SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
1642 continue;
1644 if (!routerset_contains_node(options->ExcludeNodes, node)) {
1645 smartlist_add(usable_responsible_dirs, dir);
1647 } SMARTLIST_FOREACH_END(dir);
1649 excluded_some =
1650 smartlist_len(usable_responsible_dirs) < smartlist_len(responsible_dirs);
1652 hs_dir = smartlist_choose(usable_responsible_dirs);
1653 if (!hs_dir && !options->StrictNodes) {
1654 hs_dir = smartlist_choose(responsible_dirs);
1657 smartlist_free(responsible_dirs);
1658 smartlist_free(usable_responsible_dirs);
1659 if (!hs_dir) {
1660 log_info(LD_REND, "Could not pick one of the responsible hidden "
1661 "service directories, because we requested them all "
1662 "recently without success.");
1663 if (options->StrictNodes && excluded_some) {
1664 log_warn(LD_REND, "Could not pick a hidden service directory for the "
1665 "requested hidden service: they are all either down or "
1666 "excluded, and StrictNodes is set.");
1668 } else {
1669 /* Remember that we are requesting a descriptor from this hidden service
1670 * directory now. */
1671 hs_lookup_last_hid_serv_request(hs_dir, req_key_str, now, 1);
1674 return hs_dir;
1677 /* From a list of link specifier, an onion key and if we are requesting a
1678 * direct connection (ex: single onion service), return a newly allocated
1679 * extend_info_t object. This function always returns an extend info with
1680 * an IPv4 address, or NULL.
1682 * It performs the following checks:
1683 * if either IPv4 or legacy ID is missing, return NULL.
1684 * if direct_conn, and we can't reach the IPv4 address, return NULL.
1686 extend_info_t *
1687 hs_get_extend_info_from_lspecs(const smartlist_t *lspecs,
1688 const curve25519_public_key_t *onion_key,
1689 int direct_conn)
1691 int have_v4 = 0, have_legacy_id = 0, have_ed25519_id = 0;
1692 char legacy_id[DIGEST_LEN] = {0};
1693 uint16_t port_v4 = 0;
1694 tor_addr_t addr_v4;
1695 ed25519_public_key_t ed25519_pk;
1696 extend_info_t *info = NULL;
1698 tor_assert(lspecs);
1700 SMARTLIST_FOREACH_BEGIN(lspecs, const link_specifier_t *, ls) {
1701 switch (link_specifier_get_ls_type(ls)) {
1702 case LS_IPV4:
1703 /* Skip if we already seen a v4. */
1704 if (have_v4) continue;
1705 tor_addr_from_ipv4h(&addr_v4,
1706 link_specifier_get_un_ipv4_addr(ls));
1707 port_v4 = link_specifier_get_un_ipv4_port(ls);
1708 have_v4 = 1;
1709 break;
1710 case LS_LEGACY_ID:
1711 /* Make sure we do have enough bytes for the legacy ID. */
1712 if (link_specifier_getlen_un_legacy_id(ls) < sizeof(legacy_id)) {
1713 break;
1715 memcpy(legacy_id, link_specifier_getconstarray_un_legacy_id(ls),
1716 sizeof(legacy_id));
1717 have_legacy_id = 1;
1718 break;
1719 case LS_ED25519_ID:
1720 memcpy(ed25519_pk.pubkey,
1721 link_specifier_getconstarray_un_ed25519_id(ls),
1722 ED25519_PUBKEY_LEN);
1723 have_ed25519_id = 1;
1724 break;
1725 default:
1726 /* Ignore unknown. */
1727 break;
1729 } SMARTLIST_FOREACH_END(ls);
1731 /* Legacy ID is mandatory, and we require IPv4. */
1732 if (!have_v4 || !have_legacy_id) {
1733 goto done;
1736 /* We know we have IPv4, because we just checked. */
1737 if (!direct_conn) {
1738 /* All clients can extend to any IPv4 via a 3-hop path. */
1739 goto validate;
1740 } else if (direct_conn &&
1741 fascist_firewall_allows_address_addr(&addr_v4, port_v4,
1742 FIREWALL_OR_CONNECTION,
1743 0, 0)) {
1744 /* Direct connection and we can reach it in IPv4 so go for it. */
1745 goto validate;
1747 /* We will add support for falling back to a 3-hop path in a later
1748 * release. */
1749 } else {
1750 /* If we can't reach IPv4, return NULL. */
1751 goto done;
1754 /* We will add support for IPv6 in a later release. */
1756 validate:
1757 /* We'll validate now that the address we've picked isn't a private one. If
1758 * it is, are we allowing to extend to private address? */
1759 if (!extend_info_addr_is_allowed(&addr_v4)) {
1760 log_fn(LOG_PROTOCOL_WARN, LD_REND,
1761 "Requested address is private and we are not allowed to extend to "
1762 "it: %s:%u", fmt_addr(&addr_v4), port_v4);
1763 goto done;
1766 /* We do have everything for which we think we can connect successfully. */
1767 info = extend_info_new(NULL, legacy_id,
1768 (have_ed25519_id) ? &ed25519_pk : NULL, NULL,
1769 onion_key, &addr_v4, port_v4);
1770 done:
1771 return info;
1774 /***********************************************************************/
1776 /* Initialize the entire HS subsytem. This is called in tor_init() before any
1777 * torrc options are loaded. Only for >= v3. */
1778 void
1779 hs_init(void)
1781 hs_circuitmap_init();
1782 hs_service_init();
1783 hs_cache_init();
1786 /* Release and cleanup all memory of the HS subsystem (all version). This is
1787 * called by tor_free_all(). */
1788 void
1789 hs_free_all(void)
1791 hs_circuitmap_free_all();
1792 hs_service_free_all();
1793 hs_cache_free_all();
1794 hs_client_free_all();
1797 /* For the given origin circuit circ, decrement the number of rendezvous
1798 * stream counter. This handles every hidden service version. */
1799 void
1800 hs_dec_rdv_stream_counter(origin_circuit_t *circ)
1802 tor_assert(circ);
1804 if (circ->rend_data) {
1805 circ->rend_data->nr_streams--;
1806 } else if (circ->hs_ident) {
1807 circ->hs_ident->num_rdv_streams--;
1808 } else {
1809 /* Should not be called if this circuit is not for hidden service. */
1810 tor_assert_nonfatal_unreached();
1814 /* For the given origin circuit circ, increment the number of rendezvous
1815 * stream counter. This handles every hidden service version. */
1816 void
1817 hs_inc_rdv_stream_counter(origin_circuit_t *circ)
1819 tor_assert(circ);
1821 if (circ->rend_data) {
1822 circ->rend_data->nr_streams++;
1823 } else if (circ->hs_ident) {
1824 circ->hs_ident->num_rdv_streams++;
1825 } else {
1826 /* Should not be called if this circuit is not for hidden service. */
1827 tor_assert_nonfatal_unreached();