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