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