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