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