1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2016, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
7 * \brief The hidden-service side of rendezvous functionality.
10 #define RENDSERVICE_PRIVATE
13 #include "circpathbias.h"
14 #include "circuitbuild.h"
15 #include "circuitlist.h"
16 #include "circuituse.h"
19 #include "directory.h"
20 #include "hs_common.h"
22 #include "networkstatus.h"
25 #include "rendclient.h"
26 #include "rendcommon.h"
27 #include "rendservice.h"
31 #include "replaycache.h"
32 #include "routerlist.h"
33 #include "routerparse.h"
34 #include "routerset.h"
36 struct rend_service_t
;
37 static origin_circuit_t
*find_intro_circuit(rend_intro_point_t
*intro
,
38 const char *pk_digest
);
39 static rend_intro_point_t
*find_intro_point(origin_circuit_t
*circ
);
40 static rend_intro_point_t
*find_expiring_intro_point(
41 struct rend_service_t
*service
, origin_circuit_t
*circ
);
43 static extend_info_t
*find_rp_for_intro(
44 const rend_intro_cell_t
*intro
,
47 static int intro_point_accepted_intro_count(rend_intro_point_t
*intro
);
48 static int intro_point_should_expire_now(rend_intro_point_t
*intro
,
50 static int rend_service_derive_key_digests(struct rend_service_t
*s
);
51 static int rend_service_load_keys(struct rend_service_t
*s
);
52 static int rend_service_load_auth_keys(struct rend_service_t
*s
,
54 static struct rend_service_t
*rend_service_get_by_pk_digest(
56 static struct rend_service_t
*rend_service_get_by_service_id(const char *id
);
57 static const char *rend_service_escaped_dir(
58 const struct rend_service_t
*s
);
60 static ssize_t
rend_service_parse_intro_for_v0_or_v1(
61 rend_intro_cell_t
*intro
,
65 static ssize_t
rend_service_parse_intro_for_v2(
66 rend_intro_cell_t
*intro
,
70 static ssize_t
rend_service_parse_intro_for_v3(
71 rend_intro_cell_t
*intro
,
76 static int rend_service_check_private_dir(const or_options_t
*options
,
77 const rend_service_t
*s
,
79 static int rend_service_check_private_dir_impl(const or_options_t
*options
,
80 const rend_service_t
*s
,
82 static const smartlist_t
* rend_get_service_list(
83 const smartlist_t
* substitute_service_list
);
84 static smartlist_t
* rend_get_service_list_mutable(
85 smartlist_t
* substitute_service_list
);
87 /** Represents the mapping from a virtual port of a rendezvous service to
88 * a real port on some IP.
90 struct rend_service_port_config_s
{
91 /* The incoming HS virtual port we're mapping */
92 uint16_t virtual_port
;
93 /* Is this an AF_UNIX port? */
94 unsigned int is_unix_addr
:1;
95 /* The outgoing TCP port to use, if !is_unix_addr */
97 /* The outgoing IPv4 or IPv6 address to use, if !is_unix_addr */
99 /* The socket path to connect to, if is_unix_addr */
100 char unix_addr
[FLEXIBLE_ARRAY_MEMBER
];
103 /** Try to maintain this many intro points per service by default. */
104 #define NUM_INTRO_POINTS_DEFAULT 3
105 /** Maximum number of intro points per service. */
106 #define NUM_INTRO_POINTS_MAX 10
107 /** Number of extra intro points we launch if our set of intro nodes is
108 * empty. See proposal 155, section 4. */
109 #define NUM_INTRO_POINTS_EXTRA 2
111 /** If we can't build our intro circuits, don't retry for this long. */
112 #define INTRO_CIRC_RETRY_PERIOD (60*5)
113 /** Don't try to build more than this many circuits before giving up
115 #define MAX_INTRO_CIRCS_PER_PERIOD 10
116 /** How many times will a hidden service operator attempt to connect to
117 * a requested rendezvous point before giving up? */
118 #define MAX_REND_FAILURES 1
119 /** How many seconds should we spend trying to connect to a requested
120 * rendezvous point before giving up? */
121 #define MAX_REND_TIMEOUT 30
123 /* Hidden service directory file names:
124 * new file names should be added to rend_service_add_filenames_to_list()
125 * for sandboxing purposes. */
126 static const char *private_key_fname
= "private_key";
127 static const char *hostname_fname
= "hostname";
128 static const char *client_keys_fname
= "client_keys";
129 static const char *sos_poison_fname
= "onion_service_non_anonymous";
131 /** A list of rend_service_t's for services run on this OP.
133 static smartlist_t
*rend_service_list
= NULL
;
135 /* Like rend_get_service_list_mutable, but returns a read-only list. */
136 static const smartlist_t
*
137 rend_get_service_list(const smartlist_t
* substitute_service_list
)
139 /* It is safe to cast away the const here, because
140 * rend_get_service_list_mutable does not actually modify the list */
141 return rend_get_service_list_mutable((smartlist_t
*)substitute_service_list
);
144 /* Return a mutable list of hidden services.
145 * If substitute_service_list is not NULL, return it.
146 * Otherwise, check if the global rend_service_list is non-NULL, and if so,
148 * Otherwise, log a BUG message and return NULL.
151 rend_get_service_list_mutable(smartlist_t
* substitute_service_list
)
153 if (substitute_service_list
) {
154 return substitute_service_list
;
157 /* If no special service list is provided, then just use the global one. */
159 if (BUG(!rend_service_list
)) {
160 /* No global HS list, which is a programmer error. */
164 return rend_service_list
;
167 /** Tells if onion service <b>s</b> is ephemeral.
170 rend_service_is_ephemeral(const struct rend_service_t
*s
)
172 return (s
->directory
== NULL
);
175 /** Returns a escaped string representation of the service, <b>s</b>.
178 rend_service_escaped_dir(const struct rend_service_t
*s
)
180 return rend_service_is_ephemeral(s
) ? "[EPHEMERAL]" : escaped(s
->directory
);
183 /** Return the number of rendezvous services we have configured. */
185 num_rend_services(void)
187 if (!rend_service_list
)
189 return smartlist_len(rend_service_list
);
192 /** Helper: free storage held by a single service authorized client entry. */
194 rend_authorized_client_free(rend_authorized_client_t
*client
)
198 if (client
->client_key
)
199 crypto_pk_free(client
->client_key
);
200 if (client
->client_name
)
201 memwipe(client
->client_name
, 0, strlen(client
->client_name
));
202 tor_free(client
->client_name
);
203 memwipe(client
->descriptor_cookie
, 0, sizeof(client
->descriptor_cookie
));
207 /** Helper for strmap_free. */
209 rend_authorized_client_strmap_item_free(void *authorized_client
)
211 rend_authorized_client_free(authorized_client
);
214 /** Release the storage held by <b>service</b>.
217 rend_service_free(rend_service_t
*service
)
222 tor_free(service
->directory
);
223 if (service
->ports
) {
224 SMARTLIST_FOREACH(service
->ports
, rend_service_port_config_t
*, p
,
225 rend_service_port_config_free(p
));
226 smartlist_free(service
->ports
);
228 if (service
->private_key
)
229 crypto_pk_free(service
->private_key
);
230 if (service
->intro_nodes
) {
231 SMARTLIST_FOREACH(service
->intro_nodes
, rend_intro_point_t
*, intro
,
232 rend_intro_point_free(intro
););
233 smartlist_free(service
->intro_nodes
);
235 if (service
->expiring_nodes
) {
236 SMARTLIST_FOREACH(service
->expiring_nodes
, rend_intro_point_t
*, intro
,
237 rend_intro_point_free(intro
););
238 smartlist_free(service
->expiring_nodes
);
241 rend_service_descriptor_free(service
->desc
);
242 if (service
->clients
) {
243 SMARTLIST_FOREACH(service
->clients
, rend_authorized_client_t
*, c
,
244 rend_authorized_client_free(c
););
245 smartlist_free(service
->clients
);
247 if (service
->accepted_intro_dh_parts
) {
248 replaycache_free(service
->accepted_intro_dh_parts
);
253 /** Release all the storage held in rend_service_list.
256 rend_service_free_all(void)
258 if (!rend_service_list
)
261 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, ptr
,
262 rend_service_free(ptr
));
263 smartlist_free(rend_service_list
);
264 rend_service_list
= NULL
;
267 /** Validate <b>service</b> and add it to <b>service_list</b>, or to
268 * the global rend_service_list if <b>service_list</b> is NULL.
269 * Return 0 on success. On failure, free <b>service</b> and return -1.
270 * Takes ownership of <b>service</b>.
273 rend_add_service(smartlist_t
*service_list
, rend_service_t
*service
)
276 rend_service_port_config_t
*p
;
280 smartlist_t
*s_list
= rend_get_service_list_mutable(service_list
);
281 /* We must have a service list, even if it's a temporary one, so we can
282 * check for duplicate services */
287 service
->intro_nodes
= smartlist_new();
288 service
->expiring_nodes
= smartlist_new();
290 if (service
->max_streams_per_circuit
< 0) {
291 log_warn(LD_CONFIG
, "Hidden service (%s) configured with negative max "
292 "streams per circuit.",
293 rend_service_escaped_dir(service
));
294 rend_service_free(service
);
298 if (service
->max_streams_close_circuit
< 0 ||
299 service
->max_streams_close_circuit
> 1) {
300 log_warn(LD_CONFIG
, "Hidden service (%s) configured with invalid "
301 "max streams handling.",
302 rend_service_escaped_dir(service
));
303 rend_service_free(service
);
307 if (service
->auth_type
!= REND_NO_AUTH
&&
308 (!service
->clients
||
309 smartlist_len(service
->clients
) == 0)) {
310 log_warn(LD_CONFIG
, "Hidden service (%s) with client authorization but no "
312 rend_service_escaped_dir(service
));
313 rend_service_free(service
);
317 if (!service
->ports
|| !smartlist_len(service
->ports
)) {
318 log_warn(LD_CONFIG
, "Hidden service (%s) with no ports configured.",
319 rend_service_escaped_dir(service
));
320 rend_service_free(service
);
324 /* XXX This duplicate check has two problems:
326 * a) It's O(n^2), but the same comment from the bottom of
327 * rend_config_services() should apply.
329 * b) We only compare directory paths as strings, so we can't
330 * detect two distinct paths that specify the same directory
331 * (which can arise from symlinks, case-insensitivity, bind
334 * It also can't detect that two separate Tor instances are trying
335 * to use the same HiddenServiceDir; for that, we would need a
336 * lock file. But this is enough to detect a simple mistake that
337 * at least one person has actually made.
340 if (!rend_service_is_ephemeral(service
)) {
341 /* Skip dupe for ephemeral services. */
342 SMARTLIST_FOREACH(s_list
, rend_service_t
*, ptr
,
344 !strcmp(ptr
->directory
, service
->directory
));
346 log_warn(LD_REND
, "Another hidden service is already configured for "
348 rend_service_escaped_dir(service
));
349 rend_service_free(service
);
353 log_debug(LD_REND
,"Configuring service with directory %s",
354 rend_service_escaped_dir(service
));
355 for (i
= 0; i
< smartlist_len(service
->ports
); ++i
) {
356 p
= smartlist_get(service
->ports
, i
);
357 if (!(p
->is_unix_addr
)) {
359 "Service maps port %d to %s",
361 fmt_addrport(&p
->real_addr
, p
->real_port
));
365 "Service maps port %d to socket at \"%s\"",
366 p
->virtual_port
, p
->unix_addr
);
369 "Service maps port %d to an AF_UNIX socket, but we "
370 "have no AF_UNIX support on this platform. This is "
373 rend_service_free(service
);
375 #endif /* defined(HAVE_SYS_UN_H) */
378 /* The service passed all the checks */
380 smartlist_add(s_list
, service
);
386 /** Return a new rend_service_port_config_t with its path set to
387 * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
388 static rend_service_port_config_t
*
389 rend_service_port_config_new(const char *socket_path
)
392 return tor_malloc_zero(sizeof(rend_service_port_config_t
) + 1);
394 const size_t pathlen
= strlen(socket_path
) + 1;
395 rend_service_port_config_t
*conf
=
396 tor_malloc_zero(sizeof(rend_service_port_config_t
) + pathlen
);
397 memcpy(conf
->unix_addr
, socket_path
, pathlen
);
398 conf
->is_unix_addr
= 1;
402 /** Parses a virtual-port to real-port/socket mapping separated by
403 * the provided separator and returns a new rend_service_port_config_t,
404 * or NULL and an optional error string on failure.
406 * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
408 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
410 rend_service_port_config_t
*
411 rend_service_parse_port_config(const char *string
, const char *sep
,
419 rend_service_port_config_t
*result
= NULL
;
420 unsigned int is_unix_addr
= 0;
421 const char *socket_path
= NULL
;
422 char *err_msg
= NULL
;
423 char *addrport
= NULL
;
425 sl
= smartlist_new();
426 smartlist_split_string(sl
, string
, sep
,
427 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
428 if (smartlist_len(sl
) < 1 || BUG(smartlist_len(sl
) > 2)) {
429 err_msg
= tor_strdup("Bad syntax in hidden service port configuration.");
432 virtport
= (int)tor_parse_long(smartlist_get(sl
,0), 10, 1, 65535, NULL
,NULL
);
434 tor_asprintf(&err_msg
, "Missing or invalid port %s in hidden service "
435 "port configuration", escaped(smartlist_get(sl
,0)));
439 if (smartlist_len(sl
) == 1) {
440 /* No addr:port part; use default. */
442 tor_addr_from_ipv4h(&addr
, 0x7F000001u
); /* 127.0.0.1 */
446 const char *addrport_element
= smartlist_get(sl
,1);
447 const char *rest
= NULL
;
449 ret
= port_cfg_line_extract_addrport(addrport_element
, &addrport
,
452 tor_asprintf(&err_msg
, "Couldn't process address <%s> from hidden "
453 "service configuration", addrport_element
);
457 socket_path
= addrport
;
459 } else if (strchr(addrport
, ':') || strchr(addrport
, '.')) {
460 /* else try it as an IP:port pair if it has a : or . in it */
461 if (tor_addr_port_lookup(addrport
, &addr
, &p
)<0) {
462 err_msg
= tor_strdup("Unparseable address in hidden service port "
466 realport
= p
?p
:virtport
;
468 /* No addr:port, no addr -- must be port. */
469 realport
= (int)tor_parse_long(addrport
, 10, 1, 65535, NULL
, NULL
);
471 tor_asprintf(&err_msg
, "Unparseable or out-of-range port %s in "
472 "hidden service port configuration.",
476 tor_addr_from_ipv4h(&addr
, 0x7F000001u
); /* Default to 127.0.0.1 */
480 /* Allow room for unix_addr */
481 result
= rend_service_port_config_new(socket_path
);
482 result
->virtual_port
= virtport
;
483 result
->is_unix_addr
= is_unix_addr
;
485 result
->real_port
= realport
;
486 tor_addr_copy(&result
->real_addr
, &addr
);
487 result
->unix_addr
[0] = '\0';
492 if (err_msg_out
!= NULL
) {
493 *err_msg_out
= err_msg
;
497 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
503 /** Release all storage held in a rend_service_port_config_t. */
505 rend_service_port_config_free(rend_service_port_config_t
*p
)
510 /* Check the directory for <b>service</b>, and add the service to
511 * <b>service_list</b>, or to the global list if <b>service_list</b> is NULL.
512 * Only add the service to the list if <b>validate_only</b> is false.
513 * If <b>validate_only</b> is true, free the service.
514 * If <b>service</b> is NULL, ignore it, and return 0.
515 * Returns 0 on success, and -1 on failure.
516 * Takes ownership of <b>service</b>, either freeing it, or adding it to the
517 * global service list.
520 rend_service_check_dir_and_add(smartlist_t
*service_list
,
521 const or_options_t
*options
,
522 rend_service_t
*service
,
526 /* It is ok for a service to be NULL, this means there are no services */
530 if (rend_service_check_private_dir(options
, service
, !validate_only
)
532 rend_service_free(service
);
536 smartlist_t
*s_list
= rend_get_service_list_mutable(service_list
);
537 /* We must have a service list, even if it's a temporary one, so we can
538 * check for duplicate services */
542 return rend_add_service(s_list
, service
);
545 /* If this is a reload and there were hidden services configured before,
546 * keep the introduction points that are still needed and close the
549 prune_services_on_reload(smartlist_t
*old_service_list
,
550 smartlist_t
*new_service_list
)
552 origin_circuit_t
*ocirc
= NULL
;
553 smartlist_t
*surviving_services
= NULL
;
555 tor_assert(old_service_list
);
556 tor_assert(new_service_list
);
558 /* This contains all _existing_ services that survives the relaod that is
559 * that haven't been removed from the configuration. The difference between
560 * this list and the new service list is that the new list can possibly
561 * contain newly configured service that have no introduction points opened
562 * yet nor key material loaded or generated. */
563 surviving_services
= smartlist_new();
565 /* Preserve the existing ephemeral services.
567 * This is the ephemeral service equivalent of the "Copy introduction
568 * points to new services" block, except there's no copy required since
569 * the service structure isn't regenerated.
571 * After this is done, all ephemeral services will be:
572 * * Removed from old_service_list, so the equivalent non-ephemeral code
573 * will not attempt to preserve them.
574 * * Added to the new_service_list (that previously only had the
575 * services listed in the configuration).
576 * * Added to surviving_services, which is the list of services that
577 * will NOT have their intro point closed.
579 SMARTLIST_FOREACH_BEGIN(old_service_list
, rend_service_t
*, old
) {
580 if (rend_service_is_ephemeral(old
)) {
581 SMARTLIST_DEL_CURRENT(old_service_list
, old
);
582 smartlist_add(surviving_services
, old
);
583 smartlist_add(new_service_list
, old
);
585 } SMARTLIST_FOREACH_END(old
);
587 /* Copy introduction points to new services. This is O(n^2), but it's only
588 * called on reconfigure, so it's ok performance wise. */
589 SMARTLIST_FOREACH_BEGIN(new_service_list
, rend_service_t
*, new) {
590 SMARTLIST_FOREACH_BEGIN(old_service_list
, rend_service_t
*, old
) {
591 /* Skip ephemeral services as we only want to copy introduction points
592 * from current services to newly configured one that already exists.
593 * The same directory means it's the same service. */
594 if (rend_service_is_ephemeral(new) || rend_service_is_ephemeral(old
) ||
595 strcmp(old
->directory
, new->directory
)) {
598 smartlist_add_all(new->intro_nodes
, old
->intro_nodes
);
599 smartlist_clear(old
->intro_nodes
);
600 smartlist_add_all(new->expiring_nodes
, old
->expiring_nodes
);
601 smartlist_clear(old
->expiring_nodes
);
602 /* This regular service will survive the closing IPs step after. */
603 smartlist_add(surviving_services
, old
);
605 } SMARTLIST_FOREACH_END(old
);
606 } SMARTLIST_FOREACH_END(new);
608 /* For every service introduction circuit we can find, see if we have a
609 * matching surviving configured service. If not, close the circuit. */
610 while ((ocirc
= circuit_get_next_service_intro_circ(ocirc
))) {
612 tor_assert(ocirc
->rend_data
);
613 SMARTLIST_FOREACH_BEGIN(surviving_services
, const rend_service_t
*, s
) {
614 if (rend_circuit_pk_digest_eq(ocirc
, (uint8_t *) s
->pk_digest
)) {
615 /* Keep this circuit as we have a matching configured service. */
619 } SMARTLIST_FOREACH_END(s
);
623 log_info(LD_REND
, "Closing intro point %s for service %s.",
624 safe_str_client(extend_info_describe(
625 ocirc
->build_state
->chosen_exit
)),
626 safe_str_client(rend_data_get_address(ocirc
->rend_data
)));
627 /* Reason is FINISHED because service has been removed and thus the
628 * circuit is considered old/uneeded. */
629 circuit_mark_for_close(TO_CIRCUIT(ocirc
), END_CIRC_REASON_FINISHED
);
631 smartlist_free(surviving_services
);
634 /** Set up rend_service_list, based on the values of HiddenServiceDir and
635 * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
636 * failure. (If <b>validate_only</b> is set, parse, warn and return as
637 * normal, but don't actually change the configured services.)
640 rend_config_services(const or_options_t
*options
, int validate_only
)
643 rend_service_t
*service
= NULL
;
644 rend_service_port_config_t
*portcfg
;
645 smartlist_t
*old_service_list
= NULL
;
646 smartlist_t
*temp_service_list
= NULL
;
650 /* Use a temporary service list, so that we can check the new services'
651 * consistency with each other */
652 temp_service_list
= smartlist_new();
654 for (line
= options
->RendConfigLines
; line
; line
= line
->next
) {
655 if (!strcasecmp(line
->key
, "HiddenServiceDir")) {
656 /* register the service we just finished parsing
657 * this code registers every service except the last one parsed,
658 * which is registered below the loop */
659 if (rend_service_check_dir_and_add(temp_service_list
, options
, service
,
660 validate_only
) < 0) {
662 goto free_and_return
;
664 service
= tor_malloc_zero(sizeof(rend_service_t
));
665 service
->directory
= tor_strdup(line
->value
);
666 service
->ports
= smartlist_new();
667 service
->intro_period_started
= time(NULL
);
668 service
->n_intro_points_wanted
= NUM_INTRO_POINTS_DEFAULT
;
672 log_warn(LD_CONFIG
, "%s with no preceding HiddenServiceDir directive",
674 goto free_and_return
;
676 if (!strcasecmp(line
->key
, "HiddenServicePort")) {
677 char *err_msg
= NULL
;
678 portcfg
= rend_service_parse_port_config(line
->value
, " ", &err_msg
);
681 log_warn(LD_CONFIG
, "%s", err_msg
);
683 goto free_and_return
;
685 tor_assert(!err_msg
);
686 smartlist_add(service
->ports
, portcfg
);
687 } else if (!strcasecmp(line
->key
, "HiddenServiceAllowUnknownPorts")) {
688 service
->allow_unknown_ports
= (int)tor_parse_long(line
->value
,
689 10, 0, 1, &ok
, NULL
);
692 "HiddenServiceAllowUnknownPorts should be 0 or 1, not %s",
694 goto free_and_return
;
697 "HiddenServiceAllowUnknownPorts=%d for %s",
698 (int)service
->allow_unknown_ports
,
699 rend_service_escaped_dir(service
));
700 } else if (!strcasecmp(line
->key
,
701 "HiddenServiceDirGroupReadable")) {
702 service
->dir_group_readable
= (int)tor_parse_long(line
->value
,
703 10, 0, 1, &ok
, NULL
);
706 "HiddenServiceDirGroupReadable should be 0 or 1, not %s",
708 goto free_and_return
;
711 "HiddenServiceDirGroupReadable=%d for %s",
712 service
->dir_group_readable
,
713 rend_service_escaped_dir(service
));
714 } else if (!strcasecmp(line
->key
, "HiddenServiceMaxStreams")) {
715 service
->max_streams_per_circuit
= (int)tor_parse_long(line
->value
,
716 10, 0, 65535, &ok
, NULL
);
719 "HiddenServiceMaxStreams should be between 0 and %d, not %s",
721 goto free_and_return
;
724 "HiddenServiceMaxStreams=%d for %s",
725 service
->max_streams_per_circuit
,
726 rend_service_escaped_dir(service
));
727 } else if (!strcasecmp(line
->key
, "HiddenServiceMaxStreamsCloseCircuit")) {
728 service
->max_streams_close_circuit
= (int)tor_parse_long(line
->value
,
729 10, 0, 1, &ok
, NULL
);
732 "HiddenServiceMaxStreamsCloseCircuit should be 0 or 1, "
735 goto free_and_return
;
738 "HiddenServiceMaxStreamsCloseCircuit=%d for %s",
739 (int)service
->max_streams_close_circuit
,
740 rend_service_escaped_dir(service
));
741 } else if (!strcasecmp(line
->key
, "HiddenServiceNumIntroductionPoints")) {
742 service
->n_intro_points_wanted
=
743 (unsigned int) tor_parse_long(line
->value
, 10,
744 0, NUM_INTRO_POINTS_MAX
, &ok
, NULL
);
747 "HiddenServiceNumIntroductionPoints "
748 "should be between %d and %d, not %s",
749 0, NUM_INTRO_POINTS_MAX
, line
->value
);
750 goto free_and_return
;
752 log_info(LD_CONFIG
, "HiddenServiceNumIntroductionPoints=%d for %s",
753 service
->n_intro_points_wanted
,
754 rend_service_escaped_dir(service
));
755 } else if (!strcasecmp(line
->key
, "HiddenServiceAuthorizeClient")) {
756 /* Parse auth type and comma-separated list of client names and add a
757 * rend_authorized_client_t for each client to the service's list
758 * of authorized clients. */
759 smartlist_t
*type_names_split
, *clients
;
760 const char *authname
;
762 if (service
->auth_type
!= REND_NO_AUTH
) {
763 log_warn(LD_CONFIG
, "Got multiple HiddenServiceAuthorizeClient "
764 "lines for a single service.");
765 goto free_and_return
;
767 type_names_split
= smartlist_new();
768 smartlist_split_string(type_names_split
, line
->value
, " ", 0, 2);
769 if (smartlist_len(type_names_split
) < 1) {
770 log_warn(LD_BUG
, "HiddenServiceAuthorizeClient has no value. This "
771 "should have been prevented when parsing the "
773 goto free_and_return
;
775 authname
= smartlist_get(type_names_split
, 0);
776 if (!strcasecmp(authname
, "basic")) {
777 service
->auth_type
= REND_BASIC_AUTH
;
778 } else if (!strcasecmp(authname
, "stealth")) {
779 service
->auth_type
= REND_STEALTH_AUTH
;
781 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains "
782 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
784 (char *) smartlist_get(type_names_split
, 0));
785 SMARTLIST_FOREACH(type_names_split
, char *, cp
, tor_free(cp
));
786 smartlist_free(type_names_split
);
787 goto free_and_return
;
789 service
->clients
= smartlist_new();
790 if (smartlist_len(type_names_split
) < 2) {
791 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains "
792 "auth-type '%s', but no client names.",
793 service
->auth_type
== REND_BASIC_AUTH
? "basic" : "stealth");
794 SMARTLIST_FOREACH(type_names_split
, char *, cp
, tor_free(cp
));
795 smartlist_free(type_names_split
);
798 clients
= smartlist_new();
799 smartlist_split_string(clients
, smartlist_get(type_names_split
, 1),
800 ",", SPLIT_SKIP_SPACE
, 0);
801 SMARTLIST_FOREACH(type_names_split
, char *, cp
, tor_free(cp
));
802 smartlist_free(type_names_split
);
803 /* Remove duplicate client names. */
804 num_clients
= smartlist_len(clients
);
805 smartlist_sort_strings(clients
);
806 smartlist_uniq_strings(clients
);
807 if (smartlist_len(clients
) < num_clients
) {
808 log_info(LD_CONFIG
, "HiddenServiceAuthorizeClient contains %d "
809 "duplicate client name(s); removing.",
810 num_clients
- smartlist_len(clients
));
811 num_clients
= smartlist_len(clients
);
813 SMARTLIST_FOREACH_BEGIN(clients
, const char *, client_name
)
815 rend_authorized_client_t
*client
;
816 if (!rend_valid_client_name(client_name
)) {
817 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains an "
818 "illegal client name: '%s'. Names must be "
819 "between 1 and %d characters and contain "
820 "only [A-Za-z0-9+_-].",
821 client_name
, REND_CLIENTNAME_MAX_LEN
);
822 SMARTLIST_FOREACH(clients
, char *, cp
, tor_free(cp
));
823 smartlist_free(clients
);
824 goto free_and_return
;
826 client
= tor_malloc_zero(sizeof(rend_authorized_client_t
));
827 client
->client_name
= tor_strdup(client_name
);
828 smartlist_add(service
->clients
, client
);
829 log_debug(LD_REND
, "Adding client name '%s'", client_name
);
831 SMARTLIST_FOREACH_END(client_name
);
832 SMARTLIST_FOREACH(clients
, char *, cp
, tor_free(cp
));
833 smartlist_free(clients
);
834 /* Ensure maximum number of clients. */
835 if ((service
->auth_type
== REND_BASIC_AUTH
&&
836 smartlist_len(service
->clients
) > 512) ||
837 (service
->auth_type
== REND_STEALTH_AUTH
&&
838 smartlist_len(service
->clients
) > 16)) {
839 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains %d "
840 "client authorization entries, but only a "
841 "maximum of %d entries is allowed for "
842 "authorization type '%s'.",
843 smartlist_len(service
->clients
),
844 service
->auth_type
== REND_BASIC_AUTH
? 512 : 16,
845 service
->auth_type
== REND_BASIC_AUTH
? "basic" : "stealth");
846 goto free_and_return
;
849 tor_assert(!strcasecmp(line
->key
, "HiddenServiceVersion"));
850 if (strcmp(line
->value
, "2")) {
852 "The only supported HiddenServiceVersion is 2.");
853 goto free_and_return
;
857 /* register the final service after we have finished parsing all services
858 * this code only registers the last service, other services are registered
859 * within the loop. It is ok for this service to be NULL, it is ignored. */
860 if (rend_service_check_dir_and_add(temp_service_list
, options
, service
,
861 validate_only
) < 0) {
863 goto free_and_return
;
867 /* Free the newly added services if validating */
870 goto free_and_return
;
873 /* Otherwise, use the newly added services as the new service list
874 * Since we have now replaced the global service list, from this point on we
875 * must succeed, or die trying. */
876 old_service_list
= rend_service_list
;
877 rend_service_list
= temp_service_list
;
878 temp_service_list
= NULL
;
880 /* If this is a reload and there were hidden services configured before,
881 * keep the introduction points that are still needed and close the
883 if (old_service_list
&& !validate_only
) {
884 prune_services_on_reload(old_service_list
, rend_service_list
);
885 /* Every remaining service in the old list have been removed from the
886 * configuration so clean them up safely. */
887 SMARTLIST_FOREACH(old_service_list
, rend_service_t
*, s
,
888 rend_service_free(s
));
889 smartlist_free(old_service_list
);
894 rend_service_free(service
);
895 SMARTLIST_FOREACH(temp_service_list
, rend_service_t
*, ptr
,
896 rend_service_free(ptr
));
897 smartlist_free(temp_service_list
);
901 /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
902 * client authorization <b>auth_type</b> and an optional list of
903 * rend_authorized_client_t in <b>auth_clients</b>, with
904 * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
905 * and circuit closure on max streams being exceeded set by
906 * <b>max_streams_close_circuit</b>.
908 * Ownership of pk, ports, and auth_clients is passed to this routine.
909 * Regardless of success/failure, callers should not touch these values
910 * after calling this routine, and may assume that correct cleanup has
911 * been done on failure.
913 * Return an appropriate rend_service_add_ephemeral_status_t.
915 rend_service_add_ephemeral_status_t
916 rend_service_add_ephemeral(crypto_pk_t
*pk
,
918 int max_streams_per_circuit
,
919 int max_streams_close_circuit
,
920 rend_auth_type_t auth_type
,
921 smartlist_t
*auth_clients
,
922 char **service_id_out
)
924 *service_id_out
= NULL
;
925 /* Allocate the service structure, and initialize the key, and key derived
928 rend_service_t
*s
= tor_malloc_zero(sizeof(rend_service_t
));
929 s
->directory
= NULL
; /* This indicates the service is ephemeral. */
931 s
->auth_type
= auth_type
;
932 s
->clients
= auth_clients
;
934 s
->intro_period_started
= time(NULL
);
935 s
->n_intro_points_wanted
= NUM_INTRO_POINTS_DEFAULT
;
936 s
->max_streams_per_circuit
= max_streams_per_circuit
;
937 s
->max_streams_close_circuit
= max_streams_close_circuit
;
938 if (rend_service_derive_key_digests(s
) < 0) {
939 rend_service_free(s
);
940 return RSAE_BADPRIVKEY
;
943 if (!s
->ports
|| smartlist_len(s
->ports
) == 0) {
944 log_warn(LD_CONFIG
, "At least one VIRTPORT/TARGET must be specified.");
945 rend_service_free(s
);
946 return RSAE_BADVIRTPORT
;
948 if (s
->auth_type
!= REND_NO_AUTH
&&
949 (!s
->clients
|| smartlist_len(s
->clients
) == 0)) {
950 log_warn(LD_CONFIG
, "At least one authorized client must be specified.");
951 rend_service_free(s
);
955 /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
956 * it's not, see #14828.
958 if (rend_service_get_by_pk_digest(s
->pk_digest
)) {
959 log_warn(LD_CONFIG
, "Onion Service private key collides with an "
960 "existing service.");
961 rend_service_free(s
);
962 return RSAE_ADDREXISTS
;
964 if (rend_service_get_by_service_id(s
->service_id
)) {
965 log_warn(LD_CONFIG
, "Onion Service id collides with an existing service.");
966 rend_service_free(s
);
967 return RSAE_ADDREXISTS
;
970 /* Initialize the service. */
971 if (rend_add_service(NULL
, s
)) {
972 return RSAE_INTERNAL
;
974 *service_id_out
= tor_strdup(s
->service_id
);
976 log_debug(LD_CONFIG
, "Added ephemeral Onion Service: %s", s
->service_id
);
980 /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
981 * success, and -1 on failure.
984 rend_service_del_ephemeral(const char *service_id
)
987 if (!rend_valid_service_id(service_id
)) {
988 log_warn(LD_CONFIG
, "Requested malformed Onion Service id for removal.");
991 if ((s
= rend_service_get_by_service_id(service_id
)) == NULL
) {
992 log_warn(LD_CONFIG
, "Requested non-existent Onion Service id for "
996 if (!rend_service_is_ephemeral(s
)) {
997 log_warn(LD_CONFIG
, "Requested non-ephemeral Onion Service for removal.");
1001 /* Kill the intro point circuit for the Onion Service, and remove it from
1002 * the list. Closing existing connections is the application's problem.
1004 * XXX: As with the comment in rend_config_services(), a nice abstraction
1005 * would be ideal here, but for now just duplicate the code.
1007 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
1008 if (!circ
->marked_for_close
&&
1009 (circ
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
1010 circ
->purpose
== CIRCUIT_PURPOSE_S_INTRO
)) {
1011 origin_circuit_t
*oc
= TO_ORIGIN_CIRCUIT(circ
);
1012 tor_assert(oc
->rend_data
);
1013 if (!rend_circuit_pk_digest_eq(oc
, (uint8_t *) s
->pk_digest
)) {
1016 log_debug(LD_REND
, "Closing intro point %s for service %s.",
1017 safe_str_client(extend_info_describe(
1018 oc
->build_state
->chosen_exit
)),
1019 rend_data_get_address(oc
->rend_data
));
1020 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
1022 } SMARTLIST_FOREACH_END(circ
);
1023 smartlist_remove(rend_service_list
, s
);
1024 rend_service_free(s
);
1026 log_debug(LD_CONFIG
, "Removed ephemeral Onion Service: %s", service_id
);
1031 /** Replace the old value of <b>service</b>-\>desc with one that reflects
1032 * the other fields in service.
1035 rend_service_update_descriptor(rend_service_t
*service
)
1037 rend_service_descriptor_t
*d
;
1040 rend_service_descriptor_free(service
->desc
);
1041 service
->desc
= NULL
;
1043 d
= service
->desc
= tor_malloc_zero(sizeof(rend_service_descriptor_t
));
1044 d
->pk
= crypto_pk_dup_key(service
->private_key
);
1045 d
->timestamp
= time(NULL
);
1046 d
->timestamp
-= d
->timestamp
% 3600; /* Round down to nearest hour */
1047 d
->intro_nodes
= smartlist_new();
1048 /* Support intro protocols 2 and 3. */
1049 d
->protocols
= (1 << 2) + (1 << 3);
1051 for (i
= 0; i
< smartlist_len(service
->intro_nodes
); ++i
) {
1052 rend_intro_point_t
*intro_svc
= smartlist_get(service
->intro_nodes
, i
);
1053 rend_intro_point_t
*intro_desc
;
1055 /* This intro point won't be listed in the descriptor... */
1056 intro_svc
->listed_in_last_desc
= 0;
1058 /* circuit_established is set in rend_service_intro_established(), and
1059 * checked every second in rend_consider_services_intro_points(), so it's
1060 * safe to use it here */
1061 if (!intro_svc
->circuit_established
) {
1065 /* ...unless this intro point is listed in the descriptor. */
1066 intro_svc
->listed_in_last_desc
= 1;
1068 /* We have an entirely established intro circuit. Publish it in
1069 * our descriptor. */
1070 intro_desc
= tor_malloc_zero(sizeof(rend_intro_point_t
));
1071 intro_desc
->extend_info
= extend_info_dup(intro_svc
->extend_info
);
1072 if (intro_svc
->intro_key
)
1073 intro_desc
->intro_key
= crypto_pk_dup_key(intro_svc
->intro_key
);
1074 smartlist_add(d
->intro_nodes
, intro_desc
);
1076 if (intro_svc
->time_published
== -1) {
1077 /* We are publishing this intro point in a descriptor for the
1078 * first time -- note the current time in the service's copy of
1079 * the intro point. */
1080 intro_svc
->time_published
= time(NULL
);
1085 /* Allocate and return a string containing the path to file_name in
1086 * service->directory. Asserts that service has a directory.
1087 * This function will never return NULL.
1088 * The caller must free this path. */
1090 rend_service_path(const rend_service_t
*service
, const char *file_name
)
1092 char *file_path
= NULL
;
1094 tor_assert(service
->directory
);
1096 /* Can never fail: asserts rather than leaving file_path NULL. */
1097 tor_asprintf(&file_path
, "%s%s%s",
1098 service
->directory
, PATH_SEPARATOR
, file_name
);
1103 /* Allocate and return a string containing the path to the single onion
1104 * service poison file in service->directory. Asserts that service has a
1106 * The caller must free this path. */
1108 rend_service_sos_poison_path(const rend_service_t
*service
)
1110 return rend_service_path(service
, sos_poison_fname
);
1113 /** Return True if hidden services <b>service</b> has been poisoned by single
1116 service_is_single_onion_poisoned(const rend_service_t
*service
)
1118 char *poison_fname
= NULL
;
1119 file_status_t fstatus
;
1121 /* Passing a NULL service is a bug */
1122 if (BUG(!service
)) {
1126 if (rend_service_is_ephemeral(service
)) {
1130 poison_fname
= rend_service_sos_poison_path(service
);
1132 fstatus
= file_status(poison_fname
);
1133 tor_free(poison_fname
);
1135 /* If this fname is occupied, the hidden service has been poisoned.
1136 * fstatus can be FN_ERROR if the service directory does not exist, in that
1137 * case, there is obviously no private key. */
1138 if (fstatus
== FN_FILE
|| fstatus
== FN_EMPTY
) {
1145 /* Return 1 if the private key file for service exists and has a non-zero size,
1146 * and 0 otherwise. */
1148 rend_service_private_key_exists(const rend_service_t
*service
)
1150 char *private_key_path
= rend_service_path(service
, private_key_fname
);
1151 const file_status_t private_key_status
= file_status(private_key_path
);
1152 tor_free(private_key_path
);
1153 /* Only non-empty regular private key files could have been used before.
1154 * fstatus can be FN_ERROR if the service directory does not exist, in that
1155 * case, there is obviously no private key. */
1156 return private_key_status
== FN_FILE
;
1159 /** Check the single onion service poison state of the directory for s:
1160 * - If the service is poisoned, and we are in Single Onion Mode,
1162 * - If the service is not poisoned, and we are not in Single Onion Mode,
1164 * - Otherwise, the poison state is invalid: the service was created in one
1165 * mode, and is being used in the other, return -1.
1166 * Hidden service directories without keys are always considered consistent.
1167 * They will be poisoned after their directory is created (if needed). */
1169 rend_service_verify_single_onion_poison(const rend_service_t
* s
,
1170 const or_options_t
* options
)
1172 /* Passing a NULL service is a bug */
1177 /* Ephemeral services are checked at ADD_ONION time */
1178 if (BUG(rend_service_is_ephemeral(s
))) {
1182 /* Service is expected to have a directory */
1183 if (BUG(!s
->directory
)) {
1187 /* Services without keys are always ok - their keys will only ever be used
1188 * in the current mode */
1189 if (!rend_service_private_key_exists(s
)) {
1193 /* The key has been used before in a different mode */
1194 if (service_is_single_onion_poisoned(s
) !=
1195 rend_service_non_anonymous_mode_enabled(options
)) {
1199 /* The key exists and is consistent with the current mode */
1203 /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
1204 * the hidden service directory for s that marks it as a single onion service.
1205 * Tor must be in single onion mode before calling this function, and the
1206 * service directory must already have been created.
1207 * Returns 0 when a directory is successfully poisoned, or if it is already
1208 * poisoned. Returns -1 on a failure to read the directory or write the poison
1209 * file, or if there is an existing private key file in the directory. (The
1210 * service should have been poisoned when the key was created.) */
1212 poison_new_single_onion_hidden_service_dir_impl(const rend_service_t
*service
,
1213 const or_options_t
* options
)
1215 /* Passing a NULL service is a bug */
1216 if (BUG(!service
)) {
1220 /* We must only poison directories if we're in Single Onion mode */
1221 tor_assert(rend_service_non_anonymous_mode_enabled(options
));
1225 char *poison_fname
= NULL
;
1227 if (rend_service_is_ephemeral(service
)) {
1228 log_info(LD_REND
, "Ephemeral HS started in non-anonymous mode.");
1232 /* Make sure we're only poisoning new hidden service directories */
1233 if (rend_service_private_key_exists(service
)) {
1234 log_warn(LD_BUG
, "Tried to single onion poison a service directory after "
1235 "the private key was created.");
1239 /* Make sure the directory was created before calling this function. */
1240 if (BUG(rend_service_check_private_dir_impl(options
, service
, 0) < 0))
1243 poison_fname
= rend_service_sos_poison_path(service
);
1245 switch (file_status(poison_fname
)) {
1248 log_warn(LD_FS
, "Can't read single onion poison file \"%s\"",
1251 case FN_FILE
: /* single onion poison file already exists. NOP. */
1252 case FN_EMPTY
: /* single onion poison file already exists. NOP. */
1253 log_debug(LD_FS
, "Tried to re-poison a single onion poisoned file \"%s\"",
1257 fd
= tor_open_cloexec(poison_fname
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
1259 log_warn(LD_FS
, "Could not create single onion poison file %s",
1272 tor_free(poison_fname
);
1277 /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
1278 * hidden services. If s is new, we should mark its hidden service
1279 * directory appropriately so that it is never launched as a location-private
1280 * hidden service. (New directories don't have private key files.)
1281 * Return 0 on success, -1 on fail. */
1283 rend_service_poison_new_single_onion_dir(const rend_service_t
*s
,
1284 const or_options_t
* options
)
1286 /* Passing a NULL service is a bug */
1291 /* We must only poison directories if we're in Single Onion mode */
1292 tor_assert(rend_service_non_anonymous_mode_enabled(options
));
1294 /* Ephemeral services aren't allowed in non-anonymous mode */
1295 if (BUG(rend_service_is_ephemeral(s
))) {
1299 /* Service is expected to have a directory */
1300 if (BUG(!s
->directory
)) {
1304 if (!rend_service_private_key_exists(s
)) {
1305 if (poison_new_single_onion_hidden_service_dir_impl(s
, options
)
1314 /** Load and/or generate private keys for all hidden services, possibly
1315 * including keys for client authorization.
1316 * If a <b>service_list</b> is provided, treat it as the list of hidden
1317 * services (used in unittests). Otherwise, require that rend_service_list is
1319 * Return 0 on success, -1 on failure. */
1321 rend_service_load_all_keys(const smartlist_t
*service_list
)
1323 /* Use service_list for unit tests */
1324 const smartlist_t
*s_list
= rend_get_service_list(service_list
);
1329 SMARTLIST_FOREACH_BEGIN(s_list
, rend_service_t
*, s
) {
1332 log_info(LD_REND
, "Loading hidden-service keys from %s",
1333 rend_service_escaped_dir(s
));
1335 if (rend_service_load_keys(s
) < 0)
1337 } SMARTLIST_FOREACH_END(s
);
1342 /** Add to <b>lst</b> every filename used by <b>s</b>. */
1344 rend_service_add_filenames_to_list(smartlist_t
*lst
, const rend_service_t
*s
)
1348 tor_assert(s
->directory
);
1349 smartlist_add(lst
, rend_service_path(s
, private_key_fname
));
1350 smartlist_add(lst
, rend_service_path(s
, hostname_fname
));
1351 smartlist_add(lst
, rend_service_path(s
, client_keys_fname
));
1352 smartlist_add(lst
, rend_service_sos_poison_path(s
));
1355 /** Add to <b>open_lst</b> every filename used by a configured hidden service,
1356 * and to <b>stat_lst</b> every directory used by a configured hidden
1359 rend_services_add_filenames_to_lists(smartlist_t
*open_lst
,
1360 smartlist_t
*stat_lst
)
1362 if (!rend_service_list
)
1364 SMARTLIST_FOREACH_BEGIN(rend_service_list
, rend_service_t
*, s
) {
1365 if (!rend_service_is_ephemeral(s
)) {
1366 rend_service_add_filenames_to_list(open_lst
, s
);
1367 smartlist_add_strdup(stat_lst
, s
->directory
);
1369 } SMARTLIST_FOREACH_END(s
);
1372 /** Derive all rend_service_t internal material based on the service's key.
1373 * Returns 0 on sucess, -1 on failure.
1376 rend_service_derive_key_digests(struct rend_service_t
*s
)
1378 if (rend_get_service_id(s
->private_key
, s
->service_id
)<0) {
1379 log_warn(LD_BUG
, "Internal error: couldn't encode service ID.");
1382 if (crypto_pk_get_digest(s
->private_key
, s
->pk_digest
)<0) {
1383 log_warn(LD_BUG
, "Couldn't compute hash of public key.");
1390 /* Implements the directory check from rend_service_check_private_dir,
1391 * without doing the single onion poison checks. */
1393 rend_service_check_private_dir_impl(const or_options_t
*options
,
1394 const rend_service_t
*s
,
1397 cpd_check_t check_opts
= CPD_NONE
;
1399 check_opts
|= CPD_CREATE
;
1401 check_opts
|= CPD_CHECK_MODE_ONLY
;
1402 check_opts
|= CPD_CHECK
;
1404 if (s
->dir_group_readable
) {
1405 check_opts
|= CPD_GROUP_READ
;
1407 /* Check/create directory */
1408 if (check_private_dir(s
->directory
, check_opts
, options
->User
) < 0) {
1409 log_warn(LD_REND
, "Checking service directory %s failed.", s
->directory
);
1416 /** Make sure that the directory for <b>s</b> is private, using the config in
1418 * If <b>create</b> is true:
1419 * - if the directory exists, change permissions if needed,
1420 * - if the directory does not exist, create it with the correct permissions.
1421 * If <b>create</b> is false:
1422 * - if the directory exists, check permissions,
1423 * - if the directory does not exist, check if we think we can create it.
1424 * Return 0 on success, -1 on failure. */
1426 rend_service_check_private_dir(const or_options_t
*options
,
1427 const rend_service_t
*s
,
1430 /* Passing a NULL service is a bug */
1435 /* Check/create directory */
1436 if (rend_service_check_private_dir_impl(options
, s
, create
) < 0) {
1440 /* Check if the hidden service key exists, and was created in a different
1441 * single onion service mode, and refuse to launch if it has.
1442 * This is safe to call even when create is false, as it ignores missing
1443 * keys and directories: they are always valid.
1445 if (rend_service_verify_single_onion_poison(s
, options
) < 0) {
1446 /* We can't use s->service_id here, as the key may not have been loaded */
1447 log_warn(LD_GENERAL
, "We are configured with "
1448 "HiddenServiceNonAnonymousMode %d, but the hidden "
1449 "service key in directory %s was created in %s mode. "
1450 "This is not allowed.",
1451 rend_service_non_anonymous_mode_enabled(options
) ? 1 : 0,
1452 rend_service_escaped_dir(s
),
1453 rend_service_non_anonymous_mode_enabled(options
) ?
1454 "an anonymous" : "a non-anonymous"
1459 /* Poison new single onion directories immediately after they are created,
1460 * so that we never accidentally launch non-anonymous hidden services
1461 * thinking they are anonymous. Any keys created later will end up with the
1462 * correct poisoning state.
1464 if (create
&& rend_service_non_anonymous_mode_enabled(options
)) {
1465 static int logged_warning
= 0;
1467 if (rend_service_poison_new_single_onion_dir(s
, options
) < 0) {
1468 log_warn(LD_GENERAL
,"Failed to mark new hidden services as non-anonymous"
1473 if (!logged_warning
) {
1474 /* The keys for these services are linked to the server IP address */
1475 log_notice(LD_REND
, "The configured onion service directories have been "
1476 "used in single onion mode. They can not be used for "
1477 "anonymous hidden services.");
1485 /** Load and/or generate private keys for the hidden service <b>s</b>,
1486 * possibly including keys for client authorization. Return 0 on success, -1
1489 rend_service_load_keys(rend_service_t
*s
)
1494 /* Make sure the directory was created and single onion poisoning was
1495 * checked before calling this function */
1496 if (BUG(rend_service_check_private_dir(get_options(), s
, 0) < 0))
1500 fname
= rend_service_path(s
, private_key_fname
);
1501 s
->private_key
= init_key_from_file(fname
, 1, LOG_ERR
, 0);
1503 if (!s
->private_key
)
1506 if (rend_service_derive_key_digests(s
) < 0)
1510 /* Create service file */
1511 fname
= rend_service_path(s
, hostname_fname
);
1513 tor_snprintf(buf
, sizeof(buf
),"%s.onion\n", s
->service_id
);
1514 if (write_str_to_file(fname
,buf
,0)<0) {
1515 log_warn(LD_CONFIG
, "Could not write onion address to hostname file.");
1519 if (s
->dir_group_readable
) {
1520 /* Also verify hostname file created with group read. */
1521 if (chmod(fname
, 0640))
1522 log_warn(LD_FS
,"Unable to make hidden hostname file %s group-readable.",
1527 /* If client authorization is configured, load or generate keys. */
1528 if (s
->auth_type
!= REND_NO_AUTH
) {
1529 if (rend_service_load_auth_keys(s
, fname
) < 0) {
1539 memwipe(buf
, 0, sizeof(buf
));
1544 /** Load and/or generate client authorization keys for the hidden service
1545 * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
1548 rend_service_load_auth_keys(rend_service_t
*s
, const char *hfname
)
1551 char *cfname
= NULL
;
1552 char *client_keys_str
= NULL
;
1553 strmap_t
*parsed_clients
= strmap_new();
1554 FILE *cfile
, *hfile
;
1555 open_file_t
*open_cfile
= NULL
, *open_hfile
= NULL
;
1556 char desc_cook_out
[3*REND_DESC_COOKIE_LEN_BASE64
+1];
1557 char service_id
[16+1];
1560 /* Load client keys and descriptor cookies, if available. */
1561 cfname
= rend_service_path(s
, client_keys_fname
);
1562 client_keys_str
= read_file_to_str(cfname
, RFTS_IGNORE_MISSING
, NULL
);
1563 if (client_keys_str
) {
1564 if (rend_parse_client_keys(parsed_clients
, client_keys_str
) < 0) {
1565 log_warn(LD_CONFIG
, "Previously stored client_keys file could not "
1569 log_info(LD_CONFIG
, "Parsed %d previously stored client entries.",
1570 strmap_size(parsed_clients
));
1574 /* Prepare client_keys and hostname files. */
1575 if (!(cfile
= start_writing_to_stdio_file(cfname
,
1576 OPEN_FLAGS_REPLACE
| O_TEXT
,
1577 0600, &open_cfile
))) {
1578 log_warn(LD_CONFIG
, "Could not open client_keys file %s",
1583 if (!(hfile
= start_writing_to_stdio_file(hfname
,
1584 OPEN_FLAGS_REPLACE
| O_TEXT
,
1585 0600, &open_hfile
))) {
1586 log_warn(LD_CONFIG
, "Could not open hostname file %s", escaped(hfname
));
1590 /* Either use loaded keys for configured clients or generate new
1591 * ones if a client is new. */
1592 SMARTLIST_FOREACH_BEGIN(s
->clients
, rend_authorized_client_t
*, client
) {
1593 rend_authorized_client_t
*parsed
=
1594 strmap_get(parsed_clients
, client
->client_name
);
1597 /* Copy descriptor cookie from parsed entry or create new one. */
1599 memcpy(client
->descriptor_cookie
, parsed
->descriptor_cookie
,
1600 REND_DESC_COOKIE_LEN
);
1602 crypto_rand((char *) client
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
1604 /* For compatibility with older tor clients, this does not
1605 * truncate the padding characters, unlike rend_auth_encode_cookie. */
1606 if (base64_encode(desc_cook_out
, 3*REND_DESC_COOKIE_LEN_BASE64
+1,
1607 (char *) client
->descriptor_cookie
,
1608 REND_DESC_COOKIE_LEN
, 0) < 0) {
1609 log_warn(LD_BUG
, "Could not base64-encode descriptor cookie.");
1612 /* Copy client key from parsed entry or create new one if required. */
1613 if (parsed
&& parsed
->client_key
) {
1614 client
->client_key
= crypto_pk_dup_key(parsed
->client_key
);
1615 } else if (s
->auth_type
== REND_STEALTH_AUTH
) {
1616 /* Create private key for client. */
1617 crypto_pk_t
*prkey
= NULL
;
1618 if (!(prkey
= crypto_pk_new())) {
1619 log_warn(LD_BUG
,"Error constructing client key");
1622 if (crypto_pk_generate_key(prkey
)) {
1623 log_warn(LD_BUG
,"Error generating client key");
1624 crypto_pk_free(prkey
);
1627 if (crypto_pk_check_key(prkey
) <= 0) {
1628 log_warn(LD_BUG
,"Generated client key seems invalid");
1629 crypto_pk_free(prkey
);
1632 client
->client_key
= prkey
;
1634 /* Add entry to client_keys file. */
1635 written
= tor_snprintf(buf
, sizeof(buf
),
1636 "client-name %s\ndescriptor-cookie %s\n",
1637 client
->client_name
, desc_cook_out
);
1639 log_warn(LD_BUG
, "Could not write client entry.");
1642 if (client
->client_key
) {
1643 char *client_key_out
= NULL
;
1644 if (crypto_pk_write_private_key_to_string(client
->client_key
,
1645 &client_key_out
, &len
) != 0) {
1646 log_warn(LD_BUG
, "Internal error: "
1647 "crypto_pk_write_private_key_to_string() failed.");
1650 if (rend_get_service_id(client
->client_key
, service_id
)<0) {
1651 log_warn(LD_BUG
, "Internal error: couldn't encode service ID.");
1653 * len is string length, not buffer length, but last byte is NUL
1656 memwipe(client_key_out
, 0, len
);
1657 tor_free(client_key_out
);
1660 written
= tor_snprintf(buf
+ written
, sizeof(buf
) - written
,
1661 "client-key\n%s", client_key_out
);
1662 memwipe(client_key_out
, 0, len
);
1663 tor_free(client_key_out
);
1665 log_warn(LD_BUG
, "Could not write client entry.");
1669 strlcpy(service_id
, s
->service_id
, sizeof(service_id
));
1672 if (fputs(buf
, cfile
) < 0) {
1673 log_warn(LD_FS
, "Could not append client entry to file: %s",
1678 /* Add line to hostname file. This is not the same encoding as in
1680 char *encoded_cookie
= rend_auth_encode_cookie(client
->descriptor_cookie
,
1682 if (!encoded_cookie
) {
1683 log_warn(LD_BUG
, "Could not base64-encode descriptor cookie.");
1686 tor_snprintf(buf
, sizeof(buf
), "%s.onion %s # client: %s\n",
1687 service_id
, encoded_cookie
, client
->client_name
);
1688 memwipe(encoded_cookie
, 0, strlen(encoded_cookie
));
1689 tor_free(encoded_cookie
);
1691 if (fputs(buf
, hfile
)<0) {
1692 log_warn(LD_FS
, "Could not append host entry to file: %s",
1696 } SMARTLIST_FOREACH_END(client
);
1698 finish_writing_to_file(open_cfile
);
1699 finish_writing_to_file(open_hfile
);
1705 abort_writing_to_file(open_cfile
);
1707 abort_writing_to_file(open_hfile
);
1709 if (client_keys_str
) {
1710 memwipe(client_keys_str
, 0, strlen(client_keys_str
));
1711 tor_free(client_keys_str
);
1713 strmap_free(parsed_clients
, rend_authorized_client_strmap_item_free
);
1716 memwipe(cfname
, 0, strlen(cfname
));
1720 /* Clear stack buffers that held key-derived material. */
1721 memwipe(buf
, 0, sizeof(buf
));
1722 memwipe(desc_cook_out
, 0, sizeof(desc_cook_out
));
1723 memwipe(service_id
, 0, sizeof(service_id
));
1728 /** Return the service whose public key has a digest of <b>digest</b>, or
1729 * NULL if no such service exists.
1731 static rend_service_t
*
1732 rend_service_get_by_pk_digest(const char* digest
)
1734 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, s
,
1735 if (tor_memeq(s
->pk_digest
,digest
,DIGEST_LEN
))
1740 /** Return the service whose service id is <b>id</b>, or NULL if no such
1743 static struct rend_service_t
*
1744 rend_service_get_by_service_id(const char *id
)
1746 tor_assert(strlen(id
) == REND_SERVICE_ID_LEN_BASE32
);
1747 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, s
, {
1748 if (tor_memeq(s
->service_id
, id
, REND_SERVICE_ID_LEN_BASE32
))
1754 /** Return 1 if any virtual port in <b>service</b> wants a circuit
1755 * to have good uptime. Else return 0.
1758 rend_service_requires_uptime(rend_service_t
*service
)
1761 rend_service_port_config_t
*p
;
1763 for (i
=0; i
< smartlist_len(service
->ports
); ++i
) {
1764 p
= smartlist_get(service
->ports
, i
);
1765 if (smartlist_contains_int_as_string(get_options()->LongLivedPorts
,
1772 /** Check client authorization of a given <b>descriptor_cookie</b> of
1773 * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
1774 * and 0 for failure. */
1776 rend_check_authorization(rend_service_t
*service
,
1777 const char *descriptor_cookie
,
1780 rend_authorized_client_t
*auth_client
= NULL
;
1781 tor_assert(service
);
1782 tor_assert(descriptor_cookie
);
1783 if (!service
->clients
) {
1784 log_warn(LD_BUG
, "Can't check authorization for a service that has no "
1785 "authorized clients configured.");
1789 if (cookie_len
!= REND_DESC_COOKIE_LEN
) {
1790 log_info(LD_REND
, "Descriptor cookie is %lu bytes, but we expected "
1791 "%lu bytes. Dropping cell.",
1792 (unsigned long)cookie_len
, (unsigned long)REND_DESC_COOKIE_LEN
);
1796 /* Look up client authorization by descriptor cookie. */
1797 SMARTLIST_FOREACH(service
->clients
, rend_authorized_client_t
*, client
, {
1798 if (tor_memeq(client
->descriptor_cookie
, descriptor_cookie
,
1799 REND_DESC_COOKIE_LEN
)) {
1800 auth_client
= client
;
1805 char descriptor_cookie_base64
[3*REND_DESC_COOKIE_LEN_BASE64
];
1806 base64_encode(descriptor_cookie_base64
, sizeof(descriptor_cookie_base64
),
1807 descriptor_cookie
, REND_DESC_COOKIE_LEN
, 0);
1808 log_info(LD_REND
, "No authorization found for descriptor cookie '%s'! "
1810 descriptor_cookie_base64
);
1814 /* Allow the request. */
1815 log_info(LD_REND
, "Client %s authorized for service %s.",
1816 auth_client
->client_name
, service
->service_id
);
1820 /* Can this service make a direct connection to ei?
1821 * It must be a single onion service, and the firewall rules must allow ei. */
1823 rend_service_use_direct_connection(const or_options_t
* options
,
1824 const extend_info_t
* ei
)
1826 /* We'll connect directly all reachable addresses, whether preferred or not.
1827 * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
1828 * ignored, because pref_only is 0. */
1829 return (rend_service_allow_non_anonymous_connection(options
) &&
1830 fascist_firewall_allows_address_addr(&ei
->addr
, ei
->port
,
1831 FIREWALL_OR_CONNECTION
, 0, 0));
1834 /* Like rend_service_use_direct_connection, but to a node. */
1836 rend_service_use_direct_connection_node(const or_options_t
* options
,
1839 /* We'll connect directly all reachable addresses, whether preferred or not.
1841 return (rend_service_allow_non_anonymous_connection(options
) &&
1842 fascist_firewall_allows_node(node
, FIREWALL_OR_CONNECTION
, 0));
1849 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
1853 rend_service_receive_introduction(origin_circuit_t
*circuit
,
1854 const uint8_t *request
,
1857 /* Global status stuff */
1858 int status
= 0, result
;
1859 const or_options_t
*options
= get_options();
1860 char *err_msg
= NULL
;
1861 int err_msg_severity
= LOG_WARN
;
1862 const char *stage_descr
= NULL
, *rend_pk_digest
;
1863 int reason
= END_CIRC_REASON_TORPROTOCOL
;
1864 /* Service/circuit/key stuff we can learn before parsing */
1865 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
1866 rend_service_t
*service
= NULL
;
1867 rend_intro_point_t
*intro_point
= NULL
;
1868 crypto_pk_t
*intro_key
= NULL
;
1870 rend_intro_cell_t
*parsed_req
= NULL
;
1871 /* Rendezvous point */
1872 extend_info_t
*rp
= NULL
;
1873 /* XXX not handled yet */
1874 char buf
[RELAY_PAYLOAD_SIZE
];
1875 char keys
[DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
]; /* Holds KH, Df, Db, Kf, Kb */
1877 crypto_dh_t
*dh
= NULL
;
1878 origin_circuit_t
*launched
= NULL
;
1879 crypt_path_t
*cpath
= NULL
;
1881 int circ_needs_uptime
;
1882 time_t now
= time(NULL
);
1886 /* Do some initial validation and logging before we parse the cell */
1887 if (circuit
->base_
.purpose
!= CIRCUIT_PURPOSE_S_INTRO
) {
1888 log_warn(LD_PROTOCOL
,
1889 "Got an INTRODUCE2 over a non-introduction circuit %u.",
1890 (unsigned) circuit
->base_
.n_circ_id
);
1894 assert_circ_anonymity_ok(circuit
, options
);
1895 tor_assert(circuit
->rend_data
);
1896 /* XXX: This is version 2 specific (only one supported). */
1897 rend_pk_digest
= (char *) rend_data_get_pk_digest(circuit
->rend_data
, NULL
);
1899 /* We'll use this in a bazillion log messages */
1900 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
1901 rend_pk_digest
, REND_SERVICE_ID_LEN
);
1903 /* look up service depending on circuit. */
1904 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
1907 "Internal error: Got an INTRODUCE2 cell on an intro "
1908 "circ for an unrecognized service %s.",
1909 escaped(serviceid
));
1913 intro_point
= find_intro_point(circuit
);
1914 if (intro_point
== NULL
) {
1915 intro_point
= find_expiring_intro_point(service
, circuit
);
1916 if (intro_point
== NULL
) {
1918 "Internal error: Got an INTRODUCE2 cell on an "
1919 "intro circ (for service %s) with no corresponding "
1920 "rend_intro_point_t.",
1921 escaped(serviceid
));
1926 log_info(LD_REND
, "Received INTRODUCE2 cell for service %s on circ %u.",
1927 escaped(serviceid
), (unsigned)circuit
->base_
.n_circ_id
);
1929 /* use intro key instead of service key. */
1930 intro_key
= circuit
->intro_key
;
1935 stage_descr
= "early parsing";
1936 /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
1938 rend_service_begin_parse_intro(request
, request_len
, 2, &err_msg
);
1941 } else if (err_msg
) {
1942 log_info(LD_REND
, "%s on circ %u.", err_msg
,
1943 (unsigned)circuit
->base_
.n_circ_id
);
1947 /* make sure service replay caches are present */
1948 if (!service
->accepted_intro_dh_parts
) {
1949 service
->accepted_intro_dh_parts
=
1950 replaycache_new(REND_REPLAY_TIME_INTERVAL
,
1951 REND_REPLAY_TIME_INTERVAL
);
1954 if (!intro_point
->accepted_intro_rsa_parts
) {
1955 intro_point
->accepted_intro_rsa_parts
= replaycache_new(0, 0);
1958 /* check for replay of PK-encrypted portion. */
1959 replay
= replaycache_add_test_and_elapsed(
1960 intro_point
->accepted_intro_rsa_parts
,
1961 parsed_req
->ciphertext
, parsed_req
->ciphertext_len
,
1966 "Possible replay detected! We received an "
1967 "INTRODUCE2 cell with same PK-encrypted part %d "
1968 "seconds ago. Dropping cell.",
1973 stage_descr
= "decryption";
1974 /* Now try to decrypt it */
1975 result
= rend_service_decrypt_intro(parsed_req
, intro_key
, &err_msg
);
1978 } else if (err_msg
) {
1979 log_info(LD_REND
, "%s on circ %u.", err_msg
,
1980 (unsigned)circuit
->base_
.n_circ_id
);
1984 stage_descr
= "late parsing";
1985 /* Parse the plaintext */
1986 result
= rend_service_parse_intro_plaintext(parsed_req
, &err_msg
);
1989 } else if (err_msg
) {
1990 log_info(LD_REND
, "%s on circ %u.", err_msg
,
1991 (unsigned)circuit
->base_
.n_circ_id
);
1995 stage_descr
= "late validation";
1996 /* Validate the parsed plaintext parts */
1997 result
= rend_service_validate_intro_late(parsed_req
, &err_msg
);
2000 } else if (err_msg
) {
2001 log_info(LD_REND
, "%s on circ %u.", err_msg
,
2002 (unsigned)circuit
->base_
.n_circ_id
);
2007 /* Increment INTRODUCE2 counter */
2008 ++(intro_point
->accepted_introduce2_count
);
2010 /* Find the rendezvous point */
2011 rp
= find_rp_for_intro(parsed_req
, &err_msg
);
2013 err_msg_severity
= LOG_PROTOCOL_WARN
;
2017 /* Check if we'd refuse to talk to this router */
2018 if (options
->StrictNodes
&&
2019 routerset_contains_extendinfo(options
->ExcludeNodes
, rp
)) {
2020 log_warn(LD_REND
, "Client asked to rendezvous at a relay that we "
2021 "exclude, and StrictNodes is set. Refusing service.");
2022 reason
= END_CIRC_REASON_INTERNAL
; /* XXX might leak why we refused */
2026 base16_encode(hexcookie
, 9, (const char *)(parsed_req
->rc
), 4);
2028 /* Check whether there is a past request with the same Diffie-Hellman,
2030 replay
= replaycache_add_test_and_elapsed(
2031 service
->accepted_intro_dh_parts
,
2032 parsed_req
->dh
, DH_KEY_LEN
,
2036 /* A Tor client will send a new INTRODUCE1 cell with the same rend
2037 * cookie and DH public key as its previous one if its intro circ
2038 * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
2039 * If we received the first INTRODUCE1 cell (the intro-point relay
2040 * converts it into an INTRODUCE2 cell), we are already trying to
2041 * connect to that rend point (and may have already succeeded);
2042 * drop this cell. */
2043 log_info(LD_REND
, "We received an "
2044 "INTRODUCE2 cell with same first part of "
2045 "Diffie-Hellman handshake %d seconds ago. Dropping "
2051 /* If the service performs client authorization, check included auth data. */
2052 if (service
->clients
) {
2053 if (parsed_req
->version
== 3 && parsed_req
->u
.v3
.auth_len
> 0) {
2054 if (rend_check_authorization(service
,
2055 (const char*)parsed_req
->u
.v3
.auth_data
,
2056 parsed_req
->u
.v3
.auth_len
)) {
2057 log_info(LD_REND
, "Authorization data in INTRODUCE2 cell are valid.");
2059 log_info(LD_REND
, "The authorization data that are contained in "
2060 "the INTRODUCE2 cell are invalid. Dropping cell.");
2061 reason
= END_CIRC_REASON_CONNECTFAILED
;
2065 log_info(LD_REND
, "INTRODUCE2 cell does not contain authentication "
2066 "data, but we require client authorization. Dropping cell.");
2067 reason
= END_CIRC_REASON_CONNECTFAILED
;
2072 /* Try DH handshake... */
2073 dh
= crypto_dh_new(DH_TYPE_REND
);
2074 if (!dh
|| crypto_dh_generate_public(dh
)<0) {
2075 log_warn(LD_BUG
,"Internal error: couldn't build DH state "
2076 "or generate public key.");
2077 reason
= END_CIRC_REASON_INTERNAL
;
2080 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN
, dh
,
2081 (char *)(parsed_req
->dh
),
2083 DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
)<0) {
2084 log_warn(LD_BUG
, "Internal error: couldn't complete DH handshake");
2085 reason
= END_CIRC_REASON_INTERNAL
;
2089 circ_needs_uptime
= rend_service_requires_uptime(service
);
2091 /* help predict this next time */
2092 rep_hist_note_used_internal(now
, circ_needs_uptime
, 1);
2094 /* Launch a circuit to the client's chosen rendezvous point.
2096 for (i
=0;i
<MAX_REND_FAILURES
;i
++) {
2097 int flags
= CIRCLAUNCH_NEED_CAPACITY
| CIRCLAUNCH_IS_INTERNAL
;
2098 if (circ_needs_uptime
) flags
|= CIRCLAUNCH_NEED_UPTIME
;
2099 /* A Single Onion Service only uses a direct connection if its
2100 * firewall rules permit direct connections to the address. */
2101 if (rend_service_use_direct_connection(options
, rp
)) {
2102 flags
= flags
| CIRCLAUNCH_ONEHOP_TUNNEL
;
2104 launched
= circuit_launch_by_extend_info(
2105 CIRCUIT_PURPOSE_S_CONNECT_REND
, rp
, flags
);
2110 if (!launched
) { /* give up */
2111 log_warn(LD_REND
, "Giving up launching first hop of circuit to rendezvous "
2112 "point %s for service %s.",
2113 safe_str_client(extend_info_describe(rp
)),
2115 reason
= END_CIRC_REASON_CONNECTFAILED
;
2119 "Accepted intro; launching circuit to %s "
2120 "(cookie %s) for service %s.",
2121 safe_str_client(extend_info_describe(rp
)),
2122 hexcookie
, serviceid
);
2123 tor_assert(launched
->build_state
);
2124 /* Fill in the circuit's state. */
2126 launched
->rend_data
=
2127 rend_data_service_create(service
->service_id
, rend_pk_digest
,
2128 parsed_req
->rc
, service
->auth_type
);
2130 launched
->build_state
->service_pending_final_cpath_ref
=
2131 tor_malloc_zero(sizeof(crypt_path_reference_t
));
2132 launched
->build_state
->service_pending_final_cpath_ref
->refcount
= 1;
2134 launched
->build_state
->service_pending_final_cpath_ref
->cpath
= cpath
=
2135 tor_malloc_zero(sizeof(crypt_path_t
));
2136 cpath
->magic
= CRYPT_PATH_MAGIC
;
2137 launched
->build_state
->expiry_time
= now
+ MAX_REND_TIMEOUT
;
2139 cpath
->rend_dh_handshake_state
= dh
;
2141 if (circuit_init_cpath_crypto(cpath
,keys
+DIGEST_LEN
,1)<0)
2143 memcpy(cpath
->rend_circ_nonce
, keys
, DIGEST_LEN
);
2150 tor_asprintf(&err_msg
,
2151 "unknown %s error for INTRODUCE2", stage_descr
);
2153 err_msg
= tor_strdup("unknown error for INTRODUCE2");
2157 log_fn(err_msg_severity
, LD_REND
, "%s on circ %u", err_msg
,
2158 (unsigned)circuit
->base_
.n_circ_id
);
2161 if (dh
) crypto_dh_free(dh
);
2163 circuit_mark_for_close(TO_CIRCUIT(launched
), reason
);
2168 memwipe(keys
, 0, sizeof(keys
));
2169 memwipe(buf
, 0, sizeof(buf
));
2170 memwipe(serviceid
, 0, sizeof(serviceid
));
2171 memwipe(hexcookie
, 0, sizeof(hexcookie
));
2173 /* Free the parsed cell */
2174 rend_service_free_intro(parsed_req
);
2177 extend_info_free(rp
);
2182 /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
2183 * return NULL and an error string if we can't. Return a newly allocated
2184 * extend_info_t* for the rendezvous point. */
2185 static extend_info_t
*
2186 find_rp_for_intro(const rend_intro_cell_t
*intro
,
2189 extend_info_t
*rp
= NULL
;
2190 char *err_msg
= NULL
;
2191 const char *rp_nickname
= NULL
;
2192 const node_t
*node
= NULL
;
2196 err_msg
= tor_strdup("Bad parameters to find_rp_for_intro()");
2201 if (intro
->version
== 0 || intro
->version
== 1) {
2202 rp_nickname
= (const char *)(intro
->u
.v0_v1
.rp
);
2204 node
= node_get_by_nickname(rp_nickname
, 0);
2207 tor_asprintf(&err_msg
,
2208 "Couldn't find router %s named in INTRODUCE2 cell",
2209 escaped_safe_str_client(rp_nickname
));
2215 /* Are we in single onion mode? */
2216 const int allow_direct
= rend_service_allow_non_anonymous_connection(
2218 rp
= extend_info_from_node(node
, allow_direct
);
2221 tor_asprintf(&err_msg
,
2222 "Couldn't build extend_info_t for router %s named "
2223 "in INTRODUCE2 cell",
2224 escaped_safe_str_client(rp_nickname
));
2229 } else if (intro
->version
== 2) {
2230 rp
= extend_info_dup(intro
->u
.v2
.extend_info
);
2231 } else if (intro
->version
== 3) {
2232 rp
= extend_info_dup(intro
->u
.v3
.extend_info
);
2235 tor_asprintf(&err_msg
,
2236 "Unknown version %d in INTRODUCE2 cell",
2237 (int)(intro
->version
));
2243 /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2244 * the other cases goto err. */
2247 /* Make sure the RP we are being asked to connect to is _not_ a private
2248 * address unless it's allowed. Let's avoid to build a circuit to our
2249 * second middle node and fail right after when extending to the RP. */
2250 if (!extend_info_addr_is_allowed(&rp
->addr
)) {
2252 tor_asprintf(&err_msg
,
2253 "Relay IP in INTRODUCE2 cell is private address.");
2255 extend_info_free(rp
);
2263 *err_msg_out
= err_msg
;
2271 /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
2272 * rend_service_parse_intro().
2275 rend_service_free_intro(rend_intro_cell_t
*request
)
2281 /* Free ciphertext */
2282 tor_free(request
->ciphertext
);
2283 request
->ciphertext_len
= 0;
2285 /* Have plaintext? */
2286 if (request
->plaintext
) {
2287 /* Zero it out just to be safe */
2288 memwipe(request
->plaintext
, 0, request
->plaintext_len
);
2289 tor_free(request
->plaintext
);
2290 request
->plaintext_len
= 0;
2293 /* Have parsed plaintext? */
2294 if (request
->parsed
) {
2295 switch (request
->version
) {
2299 * Nothing more to do; these formats have no further pointers
2304 extend_info_free(request
->u
.v2
.extend_info
);
2305 request
->u
.v2
.extend_info
= NULL
;
2308 if (request
->u
.v3
.auth_data
) {
2309 memwipe(request
->u
.v3
.auth_data
, 0, request
->u
.v3
.auth_len
);
2310 tor_free(request
->u
.v3
.auth_data
);
2313 extend_info_free(request
->u
.v3
.extend_info
);
2314 request
->u
.v3
.extend_info
= NULL
;
2318 "rend_service_free_intro() saw unknown protocol "
2324 /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2325 memwipe(request
, 0, sizeof(*request
));
2330 /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
2331 * rend_intro_cell_t structure. Free it with rend_service_free_intro()
2332 * when finished. The type parameter should be 1 or 2 to indicate whether
2333 * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
2334 * parts; after this, call rend_service_decrypt_intro() with a key, then
2335 * rend_service_parse_intro_plaintext() to finish parsing. The optional
2336 * err_msg_out parameter is set to a string suitable for log output
2337 * if parsing fails. This function does some validation, but only
2338 * that which depends solely on the contents of the cell and the
2339 * key; it can be unit-tested. Further validation is done in
2340 * rend_service_validate_intro().
2344 rend_service_begin_parse_intro(const uint8_t *request
,
2349 rend_intro_cell_t
*rv
= NULL
;
2350 char *err_msg
= NULL
;
2352 if (!request
|| request_len
<= 0) goto err
;
2353 if (!(type
== 1 || type
== 2)) goto err
;
2355 /* First, check that the cell is long enough to be a sensible INTRODUCE */
2357 /* min key length plus digest length plus nickname length */
2359 (DIGEST_LEN
+ REND_COOKIE_LEN
+ (MAX_NICKNAME_LEN
+ 1) +
2362 tor_asprintf(&err_msg
,
2363 "got a truncated INTRODUCE%d cell",
2369 /* Allocate a new parsed cell structure */
2370 rv
= tor_malloc_zero(sizeof(*rv
));
2375 /* Copy in the ID */
2376 memcpy(rv
->pk
, request
, DIGEST_LEN
);
2378 /* Copy in the ciphertext */
2379 rv
->ciphertext
= tor_malloc(request_len
- DIGEST_LEN
);
2380 memcpy(rv
->ciphertext
, request
+ DIGEST_LEN
, request_len
- DIGEST_LEN
);
2381 rv
->ciphertext_len
= request_len
- DIGEST_LEN
;
2386 rend_service_free_intro(rv
);
2389 if (err_msg_out
&& !err_msg
) {
2390 tor_asprintf(&err_msg
,
2391 "unknown INTRODUCE%d error",
2396 if (err_msg_out
) *err_msg_out
= err_msg
;
2397 else tor_free(err_msg
);
2402 /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
2407 rend_service_parse_intro_for_v0_or_v1(
2408 rend_intro_cell_t
*intro
,
2410 size_t plaintext_len
,
2413 const char *rp_nickname
, *endptr
;
2414 size_t nickname_field_len
, ver_specific_len
;
2416 if (intro
->version
== 1) {
2417 ver_specific_len
= MAX_HEX_NICKNAME_LEN
+ 2;
2418 rp_nickname
= ((const char *)buf
) + 1;
2419 nickname_field_len
= MAX_HEX_NICKNAME_LEN
+ 1;
2420 } else if (intro
->version
== 0) {
2421 ver_specific_len
= MAX_NICKNAME_LEN
+ 1;
2422 rp_nickname
= (const char *)buf
;
2423 nickname_field_len
= MAX_NICKNAME_LEN
+ 1;
2426 tor_asprintf(err_msg_out
,
2427 "rend_service_parse_intro_for_v0_or_v1() called with "
2428 "bad version %d on INTRODUCE%d cell (this is a bug)",
2430 (int)(intro
->type
));
2434 if (plaintext_len
< ver_specific_len
) {
2436 tor_asprintf(err_msg_out
,
2437 "short plaintext of encrypted part in v1 INTRODUCE%d "
2438 "cell (%lu bytes, needed %lu)",
2440 (unsigned long)plaintext_len
,
2441 (unsigned long)ver_specific_len
);
2445 endptr
= memchr(rp_nickname
, 0, nickname_field_len
);
2446 if (!endptr
|| endptr
== rp_nickname
) {
2448 tor_asprintf(err_msg_out
,
2449 "couldn't find a nul-padded nickname in "
2451 (int)(intro
->type
));
2456 if ((intro
->version
== 0 &&
2457 !is_legal_nickname(rp_nickname
)) ||
2458 (intro
->version
== 1 &&
2459 !is_legal_nickname_or_hexdigest(rp_nickname
))) {
2461 tor_asprintf(err_msg_out
,
2462 "bad nickname in INTRODUCE%d cell",
2463 (int)(intro
->type
));
2468 memcpy(intro
->u
.v0_v1
.rp
, rp_nickname
, endptr
- rp_nickname
+ 1);
2470 return ver_specific_len
;
2476 /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
2480 rend_service_parse_intro_for_v2(
2481 rend_intro_cell_t
*intro
,
2483 size_t plaintext_len
,
2487 extend_info_t
*extend_info
= NULL
;
2488 ssize_t ver_specific_len
;
2491 * We accept version 3 too so that the v3 parser can call this with
2492 * an adjusted buffer for the latter part of a v3 cell, which is
2493 * identical to a v2 cell.
2495 if (!(intro
->version
== 2 ||
2496 intro
->version
== 3)) {
2498 tor_asprintf(err_msg_out
,
2499 "rend_service_parse_intro_for_v2() called with "
2500 "bad version %d on INTRODUCE%d cell (this is a bug)",
2502 (int)(intro
->type
));
2506 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2507 if (plaintext_len
< 7 + DIGEST_LEN
+ 2) {
2509 tor_asprintf(err_msg_out
,
2510 "truncated plaintext of encrypted parted of "
2511 "version %d INTRODUCE%d cell",
2513 (int)(intro
->type
));
2519 extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
2520 tor_addr_from_ipv4n(&extend_info
->addr
, get_uint32(buf
+ 1));
2521 extend_info
->port
= ntohs(get_uint16(buf
+ 5));
2522 memcpy(extend_info
->identity_digest
, buf
+ 7, DIGEST_LEN
);
2523 extend_info
->nickname
[0] = '$';
2524 base16_encode(extend_info
->nickname
+ 1, sizeof(extend_info
->nickname
) - 1,
2525 extend_info
->identity_digest
, DIGEST_LEN
);
2526 klen
= ntohs(get_uint16(buf
+ 7 + DIGEST_LEN
));
2528 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2529 if (plaintext_len
< 7 + DIGEST_LEN
+ 2 + klen
) {
2531 tor_asprintf(err_msg_out
,
2532 "truncated plaintext of encrypted parted of "
2533 "version %d INTRODUCE%d cell",
2535 (int)(intro
->type
));
2541 extend_info
->onion_key
=
2542 crypto_pk_asn1_decode((const char *)(buf
+ 7 + DIGEST_LEN
+ 2), klen
);
2543 if (!extend_info
->onion_key
) {
2545 tor_asprintf(err_msg_out
,
2546 "error decoding onion key in version %d "
2554 if (128 != crypto_pk_keysize(extend_info
->onion_key
)) {
2556 tor_asprintf(err_msg_out
,
2557 "invalid onion key size in version %d INTRODUCE%d cell",
2565 ver_specific_len
= 7+DIGEST_LEN
+2+klen
;
2567 if (intro
->version
== 2) intro
->u
.v2
.extend_info
= extend_info
;
2568 else intro
->u
.v3
.extend_info
= extend_info
;
2570 return ver_specific_len
;
2573 extend_info_free(extend_info
);
2578 /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
2582 rend_service_parse_intro_for_v3(
2583 rend_intro_cell_t
*intro
,
2585 size_t plaintext_len
,
2588 ssize_t adjust
, v2_ver_specific_len
, ts_offset
;
2590 /* This should only be called on v3 cells */
2591 if (intro
->version
!= 3) {
2593 tor_asprintf(err_msg_out
,
2594 "rend_service_parse_intro_for_v3() called with "
2595 "bad version %d on INTRODUCE%d cell (this is a bug)",
2597 (int)(intro
->type
));
2602 * Check that we have at least enough to get auth_len:
2604 * 1 octet for version, 1 for auth_type, 2 for auth_len
2606 if (plaintext_len
< 4) {
2608 tor_asprintf(err_msg_out
,
2609 "truncated plaintext of encrypted parted of "
2610 "version %d INTRODUCE%d cell",
2612 (int)(intro
->type
));
2619 * The rend_client_send_introduction() function over in rendclient.c is
2620 * broken (i.e., fails to match the spec) in such a way that we can't
2621 * change it without breaking the protocol. Specifically, it doesn't
2622 * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2623 * by two bytes after that. Calculate ts_offset and do everything from
2624 * the timestamp on relative to that to handle this dain bramage.
2627 intro
->u
.v3
.auth_type
= buf
[1];
2628 if (intro
->u
.v3
.auth_type
!= REND_NO_AUTH
) {
2629 intro
->u
.v3
.auth_len
= ntohs(get_uint16(buf
+ 2));
2630 ts_offset
= 4 + intro
->u
.v3
.auth_len
;
2632 intro
->u
.v3
.auth_len
= 0;
2636 /* Check that auth len makes sense for this auth type */
2637 if (intro
->u
.v3
.auth_type
== REND_BASIC_AUTH
||
2638 intro
->u
.v3
.auth_type
== REND_STEALTH_AUTH
) {
2639 if (intro
->u
.v3
.auth_len
!= REND_DESC_COOKIE_LEN
) {
2641 tor_asprintf(err_msg_out
,
2642 "wrong auth data size %d for INTRODUCE%d cell, "
2644 (int)(intro
->u
.v3
.auth_len
),
2646 REND_DESC_COOKIE_LEN
);
2653 /* Check that we actually have everything up through the timestamp */
2654 if (plaintext_len
< (size_t)(ts_offset
)+4) {
2656 tor_asprintf(err_msg_out
,
2657 "truncated plaintext of encrypted parted of "
2658 "version %d INTRODUCE%d cell",
2660 (int)(intro
->type
));
2666 if (intro
->u
.v3
.auth_type
!= REND_NO_AUTH
&&
2667 intro
->u
.v3
.auth_len
> 0) {
2668 /* Okay, we can go ahead and copy auth_data */
2669 intro
->u
.v3
.auth_data
= tor_malloc(intro
->u
.v3
.auth_len
);
2671 * We know we had an auth_len field in this case, so 4 is
2674 memcpy(intro
->u
.v3
.auth_data
, buf
+ 4, intro
->u
.v3
.auth_len
);
2678 * From here on, the format is as in v2, so we call the v2 parser with
2679 * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2680 * v2 parser expects to skip over a version byte at the start, so we
2681 * adjust by 3 + ts_offset.
2683 adjust
= 3 + ts_offset
;
2685 v2_ver_specific_len
=
2686 rend_service_parse_intro_for_v2(intro
,
2687 buf
+ adjust
, plaintext_len
- adjust
,
2690 /* Success in v2 parser */
2691 if (v2_ver_specific_len
>= 0) return v2_ver_specific_len
+ adjust
;
2692 /* Failure in v2 parser; it will have provided an err_msg */
2693 else return v2_ver_specific_len
;
2699 /** Table of parser functions for version-specific parts of an INTRODUCE2
2704 (*intro_version_handlers
[])(
2705 rend_intro_cell_t
*,
2709 { rend_service_parse_intro_for_v0_or_v1
,
2710 rend_service_parse_intro_for_v0_or_v1
,
2711 rend_service_parse_intro_for_v2
,
2712 rend_service_parse_intro_for_v3
};
2714 /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
2715 * return 0 if successful, or < 0 and write an error message to
2716 * *err_msg_out if provided.
2720 rend_service_decrypt_intro(
2721 rend_intro_cell_t
*intro
,
2725 char *err_msg
= NULL
;
2726 uint8_t key_digest
[DIGEST_LEN
];
2727 char service_id
[REND_SERVICE_ID_LEN_BASE32
+1];
2729 uint8_t buf
[RELAY_PAYLOAD_SIZE
];
2730 int result
, status
= -1;
2732 if (!intro
|| !key
) {
2735 tor_strdup("rend_service_decrypt_intro() called with bad "
2743 /* Make sure we have ciphertext */
2744 if (!(intro
->ciphertext
) || intro
->ciphertext_len
<= 0) {
2746 tor_asprintf(&err_msg
,
2747 "rend_intro_cell_t was missing ciphertext for "
2749 (int)(intro
->type
));
2755 /* Check that this cell actually matches this service key */
2757 /* first DIGEST_LEN bytes of request is intro or service pk digest */
2758 crypto_pk_get_digest(key
, (char *)key_digest
);
2759 if (tor_memneq(key_digest
, intro
->pk
, DIGEST_LEN
)) {
2761 base32_encode(service_id
, REND_SERVICE_ID_LEN_BASE32
+ 1,
2762 (char*)(intro
->pk
), REND_SERVICE_ID_LEN
);
2763 tor_asprintf(&err_msg
,
2764 "got an INTRODUCE%d cell for the wrong service (%s)",
2766 escaped(service_id
));
2773 /* Make sure the encrypted part is long enough to decrypt */
2775 key_len
= crypto_pk_keysize(key
);
2776 if (intro
->ciphertext_len
< key_len
) {
2778 tor_asprintf(&err_msg
,
2779 "got an INTRODUCE%d cell with a truncated PK-encrypted "
2781 (int)(intro
->type
));
2788 /* Decrypt the encrypted part */
2790 note_crypto_pk_op(REND_SERVER
);
2792 crypto_pk_private_hybrid_decrypt(
2793 key
, (char *)buf
, sizeof(buf
),
2794 (const char *)(intro
->ciphertext
), intro
->ciphertext_len
,
2795 PK_PKCS1_OAEP_PADDING
, 1);
2798 tor_asprintf(&err_msg
,
2799 "couldn't decrypt INTRODUCE%d cell",
2800 (int)(intro
->type
));
2805 intro
->plaintext_len
= result
;
2806 intro
->plaintext
= tor_malloc(intro
->plaintext_len
);
2807 memcpy(intro
->plaintext
, buf
, intro
->plaintext_len
);
2814 if (err_msg_out
&& !err_msg
) {
2815 tor_asprintf(&err_msg
,
2816 "unknown INTRODUCE%d error decrypting encrypted part",
2817 intro
? (int)(intro
->type
) : -1);
2821 if (err_msg_out
) *err_msg_out
= err_msg
;
2822 else tor_free(err_msg
);
2824 /* clean up potentially sensitive material */
2825 memwipe(buf
, 0, sizeof(buf
));
2826 memwipe(key_digest
, 0, sizeof(key_digest
));
2827 memwipe(service_id
, 0, sizeof(service_id
));
2832 /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
2833 * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
2834 * message to *err_msg_out if provided.
2838 rend_service_parse_intro_plaintext(
2839 rend_intro_cell_t
*intro
,
2842 char *err_msg
= NULL
;
2843 ssize_t ver_specific_len
, ver_invariant_len
;
2850 tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2851 "rend_intro_cell_t");
2858 /* Check that we have plaintext */
2859 if (!(intro
->plaintext
) || intro
->plaintext_len
<= 0) {
2861 err_msg
= tor_strdup("rend_intro_cell_t was missing plaintext");
2867 /* In all formats except v0, the first byte is a version number */
2868 version
= intro
->plaintext
[0];
2870 /* v0 has no version byte (stupid...), so handle it as a fallback */
2871 if (version
> 3) version
= 0;
2873 /* Copy the version into the parsed cell structure */
2874 intro
->version
= version
;
2876 /* Call the version-specific parser from the table */
2878 intro_version_handlers
[version
](intro
,
2879 intro
->plaintext
, intro
->plaintext_len
,
2881 if (ver_specific_len
< 0) {
2886 /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
2887 * and at the end of the plaintext of the encrypted part of the cell.
2890 ver_invariant_len
= intro
->plaintext_len
- ver_specific_len
;
2891 if (ver_invariant_len
< REND_COOKIE_LEN
+ DH_KEY_LEN
) {
2892 tor_asprintf(&err_msg
,
2893 "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2895 (long)(intro
->plaintext_len
));
2898 } else if (ver_invariant_len
> REND_COOKIE_LEN
+ DH_KEY_LEN
) {
2899 tor_asprintf(&err_msg
,
2900 "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2902 (long)(intro
->plaintext_len
));
2907 intro
->plaintext
+ ver_specific_len
,
2910 intro
->plaintext
+ ver_specific_len
+ REND_COOKIE_LEN
,
2914 /* Flag it as being fully parsed */
2921 if (err_msg_out
&& !err_msg
) {
2922 tor_asprintf(&err_msg
,
2923 "unknown INTRODUCE%d error parsing encrypted part",
2924 intro
? (int)(intro
->type
) : -1);
2928 if (err_msg_out
) *err_msg_out
= err_msg
;
2929 else tor_free(err_msg
);
2934 /** Do validity checks on a parsed intro cell after decryption; some of
2935 * these are not done in rend_service_parse_intro_plaintext() itself because
2936 * they depend on a lot of other state and would make it hard to unit test.
2937 * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
2938 * optionally writes out an error message for logging. If an err_msg
2939 * pointer is provided, it is the caller's responsibility to free any
2944 rend_service_validate_intro_late(const rend_intro_cell_t
*intro
,
2952 tor_strdup("NULL intro cell passed to "
2953 "rend_service_validate_intro_late()");
2959 if (intro
->version
== 3 && intro
->parsed
) {
2960 if (!(intro
->u
.v3
.auth_type
== REND_NO_AUTH
||
2961 intro
->u
.v3
.auth_type
== REND_BASIC_AUTH
||
2962 intro
->u
.v3
.auth_type
== REND_STEALTH_AUTH
)) {
2963 /* This is an informative message, not an error, as in the old code */
2965 tor_asprintf(err_msg_out
,
2966 "unknown authorization type %d",
2967 intro
->u
.v3
.auth_type
);
2975 /** Called when we fail building a rendezvous circuit at some point other
2976 * than the last hop: launches a new circuit to the same rendezvous point.
2979 rend_service_relaunch_rendezvous(origin_circuit_t
*oldcirc
)
2981 origin_circuit_t
*newcirc
;
2982 cpath_build_state_t
*newstate
, *oldstate
;
2984 tor_assert(oldcirc
->base_
.purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
);
2986 /* Don't relaunch the same rend circ twice. */
2987 if (oldcirc
->hs_service_side_rend_circ_has_been_relaunched
) {
2988 log_info(LD_REND
, "Rendezvous circuit to %s has already been relaunched; "
2989 "not relaunching it again.",
2990 oldcirc
->build_state
?
2991 safe_str(extend_info_describe(oldcirc
->build_state
->chosen_exit
))
2995 oldcirc
->hs_service_side_rend_circ_has_been_relaunched
= 1;
2997 if (!oldcirc
->build_state
||
2998 oldcirc
->build_state
->failure_count
> MAX_REND_FAILURES
||
2999 oldcirc
->build_state
->expiry_time
< time(NULL
)) {
3001 "Attempt to build circuit to %s for rendezvous has failed "
3002 "too many times or expired; giving up.",
3003 oldcirc
->build_state
?
3004 safe_str(extend_info_describe(oldcirc
->build_state
->chosen_exit
))
3009 oldstate
= oldcirc
->build_state
;
3010 tor_assert(oldstate
);
3012 if (oldstate
->service_pending_final_cpath_ref
== NULL
) {
3013 log_info(LD_REND
,"Skipping relaunch of circ that failed on its first hop. "
3014 "Initiator will retry.");
3018 log_info(LD_REND
,"Reattempting rendezvous circuit to '%s'",
3019 safe_str(extend_info_describe(oldstate
->chosen_exit
)));
3021 /* You'd think Single Onion Services would want to retry the rendezvous
3022 * using a direct connection. But if it's blocked by a firewall, or the
3023 * service is IPv6-only, or the rend point avoiding becoming a one-hop
3024 * proxy, we need a 3-hop connection. */
3025 newcirc
= circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND
,
3026 oldstate
->chosen_exit
,
3027 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
3030 log_warn(LD_REND
,"Couldn't relaunch rendezvous circuit to '%s'.",
3031 safe_str(extend_info_describe(oldstate
->chosen_exit
)));
3034 newstate
= newcirc
->build_state
;
3035 tor_assert(newstate
);
3036 newstate
->failure_count
= oldstate
->failure_count
+1;
3037 newstate
->expiry_time
= oldstate
->expiry_time
;
3038 newstate
->service_pending_final_cpath_ref
=
3039 oldstate
->service_pending_final_cpath_ref
;
3040 ++(newstate
->service_pending_final_cpath_ref
->refcount
);
3042 newcirc
->rend_data
= rend_data_dup(oldcirc
->rend_data
);
3045 /** Launch a circuit to serve as an introduction point for the service
3046 * <b>service</b> at the introduction point <b>nickname</b>
3049 rend_service_launch_establish_intro(rend_service_t
*service
,
3050 rend_intro_point_t
*intro
)
3052 origin_circuit_t
*launched
;
3053 int flags
= CIRCLAUNCH_NEED_UPTIME
|CIRCLAUNCH_IS_INTERNAL
;
3054 const or_options_t
*options
= get_options();
3055 extend_info_t
*launch_ei
= intro
->extend_info
;
3056 extend_info_t
*direct_ei
= NULL
;
3058 /* Are we in single onion mode? */
3059 if (rend_service_allow_non_anonymous_connection(options
)) {
3060 /* Do we have a descriptor for the node?
3061 * We've either just chosen it from the consensus, or we've just reviewed
3062 * our intro points to see which ones are still valid, and deleted the ones
3063 * that aren't in the consensus any more. */
3064 const node_t
*node
= node_get_by_id(launch_ei
->identity_digest
);
3066 /* The service has kept an intro point after it went missing from the
3067 * consensus. If we did anything else here, it would be a consensus
3068 * distinguisher. Which are less of an issue for single onion services,
3069 * but still a bug. */
3072 /* Can we connect to the node directly? If so, replace launch_ei
3073 * (a multi-hop extend_info) with one suitable for direct connection. */
3074 if (rend_service_use_direct_connection_node(options
, node
)) {
3075 direct_ei
= extend_info_from_node(node
, 1);
3076 if (BUG(!direct_ei
)) {
3077 /* rend_service_use_direct_connection_node and extend_info_from_node
3078 * disagree about which addresses on this node are permitted. This
3079 * should never happen. Avoiding the connection is a safe response. */
3082 flags
= flags
| CIRCLAUNCH_ONEHOP_TUNNEL
;
3083 launch_ei
= direct_ei
;
3086 /* launch_ei is either intro->extend_info, or has been replaced with a valid
3087 * extend_info for single onion service direct connection. */
3088 tor_assert(launch_ei
);
3089 /* We must have the same intro when making a direct connection. */
3090 tor_assert(tor_memeq(intro
->extend_info
->identity_digest
,
3091 launch_ei
->identity_digest
,
3095 "Launching circuit to introduction point %s%s%s for service %s",
3096 safe_str_client(extend_info_describe(intro
->extend_info
)),
3097 direct_ei
? " via direct address " : "",
3098 direct_ei
? safe_str_client(extend_info_describe(direct_ei
)) : "",
3099 service
->service_id
);
3101 rep_hist_note_used_internal(time(NULL
), 1, 0);
3103 ++service
->n_intro_circuits_launched
;
3104 launched
= circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
,
3109 "Can't launch circuit to establish introduction at %s%s%s.",
3110 safe_str_client(extend_info_describe(intro
->extend_info
)),
3111 direct_ei
? " via direct address " : "",
3112 direct_ei
? safe_str_client(extend_info_describe(direct_ei
)) : ""
3114 extend_info_free(direct_ei
);
3117 /* We must have the same exit node even if cannibalized or direct connection.
3119 tor_assert(tor_memeq(intro
->extend_info
->identity_digest
,
3120 launched
->build_state
->chosen_exit
->identity_digest
,
3123 launched
->rend_data
= rend_data_service_create(service
->service_id
,
3124 service
->pk_digest
, NULL
,
3125 service
->auth_type
);
3126 launched
->intro_key
= crypto_pk_dup_key(intro
->intro_key
);
3127 if (launched
->base_
.state
== CIRCUIT_STATE_OPEN
)
3128 rend_service_intro_has_opened(launched
);
3129 extend_info_free(direct_ei
);
3133 /** Return the number of introduction points that are established for the
3136 count_established_intro_points(const rend_service_t
*service
)
3138 unsigned int num
= 0;
3140 SMARTLIST_FOREACH(service
->intro_nodes
, rend_intro_point_t
*, intro
,
3141 num
+= intro
->circuit_established
3146 /** Return the number of introduction points that are or are being
3147 * established for the given service. This function iterates over all
3148 * circuit and count those that are linked to the service and are waiting
3149 * for the intro point to respond. */
3151 count_intro_point_circuits(const rend_service_t
*service
)
3153 unsigned int num_ipos
= 0;
3154 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
3155 if (!circ
->marked_for_close
&&
3156 circ
->state
== CIRCUIT_STATE_OPEN
&&
3157 (circ
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
3158 circ
->purpose
== CIRCUIT_PURPOSE_S_INTRO
)) {
3159 origin_circuit_t
*oc
= TO_ORIGIN_CIRCUIT(circ
);
3160 if (oc
->rend_data
&&
3161 rend_circuit_pk_digest_eq(oc
, (uint8_t *) service
->pk_digest
)) {
3166 SMARTLIST_FOREACH_END(circ
);
3170 /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
3171 write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
3172 as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
3173 crypto material. On success, fill <b>cell_body_out</b> and return the number
3174 of bytes written. On fail, return -1.
3177 encode_establish_intro_cell_legacy(char *cell_body_out
,
3178 size_t cell_body_out_len
,
3179 crypto_pk_t
*intro_key
, char *rend_circ_nonce
)
3184 char auth
[DIGEST_LEN
+ 9];
3186 tor_assert(intro_key
);
3187 tor_assert(rend_circ_nonce
);
3189 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3190 r
= crypto_pk_asn1_encode(intro_key
, cell_body_out
+2,
3191 RELAY_PAYLOAD_SIZE
-2);
3193 log_warn(LD_BUG
, "Internal error; failed to establish intro point.");
3197 set_uint16(cell_body_out
, htons((uint16_t)len
));
3199 memcpy(auth
, rend_circ_nonce
, DIGEST_LEN
);
3200 memcpy(auth
+DIGEST_LEN
, "INTRODUCE", 9);
3201 if (crypto_digest(cell_body_out
+len
, auth
, DIGEST_LEN
+9))
3204 note_crypto_pk_op(REND_SERVER
);
3205 r
= crypto_pk_private_sign_digest(intro_key
, cell_body_out
+len
,
3206 cell_body_out_len
- len
,
3207 cell_body_out
, len
);
3209 log_warn(LD_BUG
, "Internal error: couldn't sign introduction request.");
3217 memwipe(auth
, 0, sizeof(auth
));
3222 /** Called when we're done building a circuit to an introduction point:
3223 * sends a RELAY_ESTABLISH_INTRO cell.
3226 rend_service_intro_has_opened(origin_circuit_t
*circuit
)
3228 rend_service_t
*service
;
3229 char buf
[RELAY_PAYLOAD_SIZE
];
3230 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3231 unsigned int expiring_nodes_len
, num_ip_circuits
, valid_ip_circuits
= 0;
3232 int reason
= END_CIRC_REASON_TORPROTOCOL
;
3233 const char *rend_pk_digest
;
3235 tor_assert(circuit
->base_
.purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
);
3236 assert_circ_anonymity_ok(circuit
, get_options());
3237 tor_assert(circuit
->cpath
);
3238 tor_assert(circuit
->rend_data
);
3239 /* XXX: This is version 2 specific (only on supported). */
3240 rend_pk_digest
= (char *) rend_data_get_pk_digest(circuit
->rend_data
, NULL
);
3242 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
3243 rend_pk_digest
, REND_SERVICE_ID_LEN
);
3245 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
3247 log_warn(LD_REND
, "Unrecognized service ID %s on introduction circuit %u.",
3248 safe_str_client(serviceid
), (unsigned)circuit
->base_
.n_circ_id
);
3249 reason
= END_CIRC_REASON_NOSUCHSERVICE
;
3253 /* Take the current amount of expiring nodes and the current amount of IP
3254 * circuits and compute how many valid IP circuits we have. */
3255 expiring_nodes_len
= (unsigned int) smartlist_len(service
->expiring_nodes
);
3256 num_ip_circuits
= count_intro_point_circuits(service
);
3257 /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
3258 * case this condition turns out false because it means that all circuits
3259 * are expiring so we need to keep this circuit. */
3260 if (num_ip_circuits
> expiring_nodes_len
) {
3261 valid_ip_circuits
= num_ip_circuits
- expiring_nodes_len
;
3264 /* If we already have enough introduction circuits for this service,
3265 * redefine this one as a general circuit or close it, depending.
3266 * Substract the amount of expiring nodes here because the circuits are
3268 if (valid_ip_circuits
> service
->n_intro_points_wanted
) {
3269 const or_options_t
*options
= get_options();
3270 /* Remove the intro point associated with this circuit, it's being
3271 * repurposed or closed thus cleanup memory. */
3272 rend_intro_point_t
*intro
= find_intro_point(circuit
);
3273 if (intro
!= NULL
) {
3274 smartlist_remove(service
->intro_nodes
, intro
);
3275 rend_intro_point_free(intro
);
3278 if (options
->ExcludeNodes
) {
3279 /* XXXX in some future version, we can test whether the transition is
3280 allowed or not given the actual nodes in the circuit. But for now,
3281 this case, we might as well close the thing. */
3282 log_info(LD_CIRC
|LD_REND
, "We have just finished an introduction "
3283 "circuit, but we already have enough. Closing it.");
3284 reason
= END_CIRC_REASON_NONE
;
3287 tor_assert(circuit
->build_state
->is_internal
);
3288 log_info(LD_CIRC
|LD_REND
, "We have just finished an introduction "
3289 "circuit, but we already have enough. Redefining purpose to "
3290 "general; leaving as internal.");
3292 circuit_change_purpose(TO_CIRCUIT(circuit
), CIRCUIT_PURPOSE_C_GENERAL
);
3295 rend_data_free(circuit
->rend_data
);
3296 circuit
->rend_data
= NULL
;
3299 crypto_pk_t
*intro_key
= circuit
->intro_key
;
3300 circuit
->intro_key
= NULL
;
3301 crypto_pk_free(intro_key
);
3304 circuit_has_opened(circuit
);
3310 "Established circuit %u as introduction point for service %s",
3311 (unsigned)circuit
->base_
.n_circ_id
, serviceid
);
3312 circuit_log_path(LOG_INFO
, LD_REND
, circuit
);
3314 /* Send the ESTABLISH_INTRO cell */
3317 len
= encode_establish_intro_cell_legacy(buf
, sizeof(buf
),
3319 circuit
->cpath
->prev
->rend_circ_nonce
);
3321 reason
= END_CIRC_REASON_INTERNAL
;
3325 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit
),
3326 RELAY_COMMAND_ESTABLISH_INTRO
,
3327 buf
, len
, circuit
->cpath
->prev
)<0) {
3328 log_info(LD_GENERAL
,
3329 "Couldn't send introduction request for service %s on circuit %u",
3330 serviceid
, (unsigned)circuit
->base_
.n_circ_id
);
3335 /* We've attempted to use this circuit */
3336 pathbias_count_use_attempt(circuit
);
3341 circuit_mark_for_close(TO_CIRCUIT(circuit
), reason
);
3343 memwipe(buf
, 0, sizeof(buf
));
3344 memwipe(serviceid
, 0, sizeof(serviceid
));
3349 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
3350 * live introduction point, and note that the service descriptor is
3351 * now out-of-date. */
3353 rend_service_intro_established(origin_circuit_t
*circuit
,
3354 const uint8_t *request
,
3357 rend_service_t
*service
;
3358 rend_intro_point_t
*intro
;
3359 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3362 tor_assert(circuit
->rend_data
);
3363 /* XXX: This is version 2 specific (only supported one for now). */
3364 const char *rend_pk_digest
=
3365 (char *) rend_data_get_pk_digest(circuit
->rend_data
, NULL
);
3367 if (circuit
->base_
.purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
) {
3368 log_warn(LD_PROTOCOL
,
3369 "received INTRO_ESTABLISHED cell on non-intro circuit.");
3372 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
3374 log_warn(LD_REND
, "Unknown service on introduction circuit %u.",
3375 (unsigned)circuit
->base_
.n_circ_id
);
3378 /* We've just successfully established a intro circuit to one of our
3379 * introduction point, account for it. */
3380 intro
= find_intro_point(circuit
);
3381 if (intro
== NULL
) {
3383 "Introduction circuit established without a rend_intro_point_t "
3384 "object for service %s on circuit %u",
3385 safe_str_client(serviceid
), (unsigned)circuit
->base_
.n_circ_id
);
3388 intro
->circuit_established
= 1;
3389 /* We might not have every introduction point ready but at this point we
3390 * know that the descriptor needs to be uploaded. */
3391 service
->desc_is_dirty
= time(NULL
);
3392 circuit_change_purpose(TO_CIRCUIT(circuit
), CIRCUIT_PURPOSE_S_INTRO
);
3394 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+ 1,
3395 rend_pk_digest
, REND_SERVICE_ID_LEN
);
3397 "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3398 (unsigned)circuit
->base_
.n_circ_id
, serviceid
);
3400 /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3402 pathbias_mark_use_success(circuit
);
3406 circuit_mark_for_close(TO_CIRCUIT(circuit
), END_CIRC_REASON_TORPROTOCOL
);
3410 /** Called once a circuit to a rendezvous point is established: sends a
3411 * RELAY_COMMAND_RENDEZVOUS1 cell.
3414 rend_service_rendezvous_has_opened(origin_circuit_t
*circuit
)
3416 rend_service_t
*service
;
3417 char buf
[RELAY_PAYLOAD_SIZE
];
3419 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3422 const char *rend_cookie
, *rend_pk_digest
;
3424 tor_assert(circuit
->base_
.purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
);
3425 tor_assert(circuit
->cpath
);
3426 tor_assert(circuit
->build_state
);
3427 assert_circ_anonymity_ok(circuit
, get_options());
3428 tor_assert(circuit
->rend_data
);
3430 /* XXX: This is version 2 specific (only one supported). */
3431 rend_pk_digest
= (char *) rend_data_get_pk_digest(circuit
->rend_data
,
3433 rend_cookie
= circuit
->rend_data
->rend_cookie
;
3435 /* Declare the circuit dirty to avoid reuse, and for path-bias */
3436 if (!circuit
->base_
.timestamp_dirty
)
3437 circuit
->base_
.timestamp_dirty
= time(NULL
);
3439 /* This may be redundant */
3440 pathbias_count_use_attempt(circuit
);
3442 hop
= circuit
->build_state
->service_pending_final_cpath_ref
->cpath
;
3444 base16_encode(hexcookie
,9, rend_cookie
,4);
3445 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
3446 rend_pk_digest
, REND_SERVICE_ID_LEN
);
3449 "Done building circuit %u to rendezvous with "
3450 "cookie %s for service %s",
3451 (unsigned)circuit
->base_
.n_circ_id
, hexcookie
, serviceid
);
3452 circuit_log_path(LOG_INFO
, LD_REND
, circuit
);
3454 /* Clear the 'in-progress HS circ has timed out' flag for
3455 * consistency with what happens on the client side; this line has
3456 * no effect on Tor's behaviour. */
3457 circuit
->hs_circ_has_timed_out
= 0;
3459 /* If hop is NULL, another rend circ has already connected to this
3460 * rend point. Close this circ. */
3462 log_info(LD_REND
, "Another rend circ has already reached this rend point; "
3463 "closing this rend circ.");
3464 reason
= END_CIRC_REASON_NONE
;
3468 /* Remove our final cpath element from the reference, so that no
3469 * other circuit will try to use it. Store it in
3470 * pending_final_cpath for now to ensure that it will be freed if
3471 * our rendezvous attempt fails. */
3472 circuit
->build_state
->pending_final_cpath
= hop
;
3473 circuit
->build_state
->service_pending_final_cpath_ref
->cpath
= NULL
;
3475 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
3477 log_warn(LD_GENERAL
, "Internal error: unrecognized service ID on "
3478 "rendezvous circuit.");
3479 reason
= END_CIRC_REASON_INTERNAL
;
3483 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3484 memcpy(buf
, rend_cookie
, REND_COOKIE_LEN
);
3485 if (crypto_dh_get_public(hop
->rend_dh_handshake_state
,
3486 buf
+REND_COOKIE_LEN
, DH_KEY_LEN
)<0) {
3487 log_warn(LD_GENERAL
,"Couldn't get DH public key.");
3488 reason
= END_CIRC_REASON_INTERNAL
;
3491 memcpy(buf
+REND_COOKIE_LEN
+DH_KEY_LEN
, hop
->rend_circ_nonce
,
3495 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit
),
3496 RELAY_COMMAND_RENDEZVOUS1
,
3497 buf
, REND_COOKIE_LEN
+DH_KEY_LEN
+DIGEST_LEN
,
3498 circuit
->cpath
->prev
)<0) {
3499 log_warn(LD_GENERAL
, "Couldn't send RENDEZVOUS1 cell.");
3503 crypto_dh_free(hop
->rend_dh_handshake_state
);
3504 hop
->rend_dh_handshake_state
= NULL
;
3506 /* Append the cpath entry. */
3507 hop
->state
= CPATH_STATE_OPEN
;
3508 /* set the windows to default. these are the windows
3509 * that the service thinks the client has.
3511 hop
->package_window
= circuit_initial_package_window();
3512 hop
->deliver_window
= CIRCWINDOW_START
;
3514 onion_append_to_cpath(&circuit
->cpath
, hop
);
3515 circuit
->build_state
->pending_final_cpath
= NULL
; /* prevent double-free */
3517 /* Change the circuit purpose. */
3518 circuit_change_purpose(TO_CIRCUIT(circuit
), CIRCUIT_PURPOSE_S_REND_JOINED
);
3523 circuit_mark_for_close(TO_CIRCUIT(circuit
), reason
);
3525 memwipe(buf
, 0, sizeof(buf
));
3526 memwipe(serviceid
, 0, sizeof(serviceid
));
3527 memwipe(hexcookie
, 0, sizeof(hexcookie
));
3533 * Manage introduction points
3536 /** Return the (possibly non-open) introduction circuit ending at
3537 * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
3538 * (<b>desc_version</b> is ignored). Return NULL if no such service is
3541 static origin_circuit_t
*
3542 find_intro_circuit(rend_intro_point_t
*intro
, const char *pk_digest
)
3544 origin_circuit_t
*circ
= NULL
;
3547 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
,
3548 (uint8_t *) pk_digest
, CIRCUIT_PURPOSE_S_INTRO
))) {
3549 if (tor_memeq(circ
->build_state
->chosen_exit
->identity_digest
,
3550 intro
->extend_info
->identity_digest
, DIGEST_LEN
) &&
3557 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
,
3558 (uint8_t *) pk_digest
,
3559 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
))) {
3560 if (tor_memeq(circ
->build_state
->chosen_exit
->identity_digest
,
3561 intro
->extend_info
->identity_digest
, DIGEST_LEN
) &&
3569 /** Return the corresponding introdution point using the circuit <b>circ</b>
3570 * found in the <b>service</b>. NULL is returned if not found. */
3571 static rend_intro_point_t
*
3572 find_expiring_intro_point(rend_service_t
*service
, origin_circuit_t
*circ
)
3574 tor_assert(service
);
3575 tor_assert(TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
3576 TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_INTRO
);
3578 SMARTLIST_FOREACH(service
->expiring_nodes
, rend_intro_point_t
*,
3580 if (crypto_pk_eq_keys(intro_point
->intro_key
, circ
->intro_key
)) {
3587 /** Return a pointer to the rend_intro_point_t corresponding to the
3588 * service-side introduction circuit <b>circ</b>. */
3589 static rend_intro_point_t
*
3590 find_intro_point(origin_circuit_t
*circ
)
3592 const char *serviceid
;
3593 rend_service_t
*service
= NULL
;
3595 tor_assert(TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
3596 TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_INTRO
);
3597 tor_assert(circ
->rend_data
);
3598 serviceid
= rend_data_get_address(circ
->rend_data
);
3600 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, s
,
3601 if (tor_memeq(s
->service_id
, serviceid
, REND_SERVICE_ID_LEN_BASE32
)) {
3606 if (service
== NULL
) return NULL
;
3608 SMARTLIST_FOREACH(service
->intro_nodes
, rend_intro_point_t
*, intro_point
,
3609 if (crypto_pk_eq_keys(intro_point
->intro_key
, circ
->intro_key
)) {
3616 /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
3617 * associated with the rend_service_descriptor_t <b>renddesc</b> to
3618 * the responsible hidden service directories OR the hidden service
3619 * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
3620 * <b>seconds_valid</b> are only passed for logging purposes.
3623 directory_post_to_hs_dir(rend_service_descriptor_t
*renddesc
,
3624 smartlist_t
*descs
, smartlist_t
*hs_dirs
,
3625 const char *service_id
, int seconds_valid
)
3627 int i
, j
, failed_upload
= 0;
3628 smartlist_t
*responsible_dirs
= smartlist_new();
3629 smartlist_t
*successful_uploads
= smartlist_new();
3630 routerstatus_t
*hs_dir
;
3631 for (i
= 0; i
< smartlist_len(descs
); i
++) {
3632 rend_encoded_v2_service_descriptor_t
*desc
= smartlist_get(descs
, i
);
3633 /** If any HSDirs are specified, they should be used instead of
3634 * the responsible directories */
3635 if (hs_dirs
&& smartlist_len(hs_dirs
) > 0) {
3636 smartlist_add_all(responsible_dirs
, hs_dirs
);
3638 /* Determine responsible dirs. */
3639 if (hid_serv_get_responsible_directories(responsible_dirs
,
3640 desc
->desc_id
) < 0) {
3641 log_warn(LD_REND
, "Could not determine the responsible hidden service "
3642 "directories to post descriptors to.");
3643 control_event_hs_descriptor_upload(service_id
,
3649 for (j
= 0; j
< smartlist_len(responsible_dirs
); j
++) {
3650 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
3653 rend_data_t
*rend_data
;
3654 hs_dir
= smartlist_get(responsible_dirs
, j
);
3655 if (smartlist_contains_digest(renddesc
->successful_uploads
,
3656 hs_dir
->identity_digest
))
3657 /* Don't upload descriptor if we succeeded in doing so last time. */
3659 node
= node_get_by_id(hs_dir
->identity_digest
);
3660 if (!node
|| !node_has_descriptor(node
)) {
3661 log_info(LD_REND
, "Not launching upload for for v2 descriptor to "
3662 "hidden service directory %s; we don't have its "
3663 "router descriptor. Queuing for later upload.",
3664 safe_str_client(routerstatus_describe(hs_dir
)));
3668 /* Send publish request. */
3670 /* We need the service ID to identify which service did the upload
3671 * request. Lookup is made in rend_service_desc_has_uploaded(). */
3672 rend_data
= rend_data_client_create(service_id
, desc
->desc_id
, NULL
,
3674 directory_initiate_command_routerstatus_rend(hs_dir
,
3675 DIR_PURPOSE_UPLOAD_RENDDESC_V2
,
3676 ROUTER_PURPOSE_GENERAL
,
3677 DIRIND_ANONYMOUS
, NULL
,
3679 strlen(desc
->desc_str
),
3680 0, rend_data
, NULL
);
3681 rend_data_free(rend_data
);
3682 base32_encode(desc_id_base32
, sizeof(desc_id_base32
),
3683 desc
->desc_id
, DIGEST_LEN
);
3684 hs_dir_ip
= tor_dup_ip(hs_dir
->addr
);
3685 log_info(LD_REND
, "Launching upload for v2 descriptor for "
3686 "service '%s' with descriptor ID '%s' with validity "
3687 "of %d seconds to hidden service directory '%s' on "
3689 safe_str_client(service_id
),
3690 safe_str_client(desc_id_base32
),
3695 control_event_hs_descriptor_upload(service_id
,
3696 hs_dir
->identity_digest
,
3698 tor_free(hs_dir_ip
);
3699 /* Remember successful upload to this router for next time. */
3700 if (!smartlist_contains_digest(successful_uploads
,
3701 hs_dir
->identity_digest
))
3702 smartlist_add(successful_uploads
, hs_dir
->identity_digest
);
3704 smartlist_clear(responsible_dirs
);
3706 if (!failed_upload
) {
3707 if (renddesc
->successful_uploads
) {
3708 SMARTLIST_FOREACH(renddesc
->successful_uploads
, char *, c
, tor_free(c
););
3709 smartlist_free(renddesc
->successful_uploads
);
3710 renddesc
->successful_uploads
= NULL
;
3712 renddesc
->all_uploads_performed
= 1;
3714 /* Remember which routers worked this time, so that we don't upload the
3715 * descriptor to them again. */
3716 if (!renddesc
->successful_uploads
)
3717 renddesc
->successful_uploads
= smartlist_new();
3718 SMARTLIST_FOREACH(successful_uploads
, const char *, c
, {
3719 if (!smartlist_contains_digest(renddesc
->successful_uploads
, c
)) {
3720 char *hsdir_id
= tor_memdup(c
, DIGEST_LEN
);
3721 smartlist_add(renddesc
->successful_uploads
, hsdir_id
);
3726 smartlist_free(responsible_dirs
);
3727 smartlist_free(successful_uploads
);
3730 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
3731 * and upload it/them to the responsible hidden service directories.
3734 upload_service_descriptor(rend_service_t
*service
)
3736 time_t now
= time(NULL
);
3738 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3741 rendpostperiod
= get_options()->RendPostPeriod
;
3743 networkstatus_t
*c
= networkstatus_get_latest_consensus();
3744 if (c
&& smartlist_len(c
->routerstatus_list
) > 0) {
3745 int seconds_valid
, i
, j
, num_descs
;
3746 smartlist_t
*descs
= smartlist_new();
3747 smartlist_t
*client_cookies
= smartlist_new();
3748 /* Either upload a single descriptor (including replicas) or one
3749 * descriptor for each authorized client in case of authorization
3750 * type 'stealth'. */
3751 num_descs
= service
->auth_type
== REND_STEALTH_AUTH
?
3752 smartlist_len(service
->clients
) : 1;
3753 for (j
= 0; j
< num_descs
; j
++) {
3754 crypto_pk_t
*client_key
= NULL
;
3755 rend_authorized_client_t
*client
= NULL
;
3756 smartlist_clear(client_cookies
);
3757 switch (service
->auth_type
) {
3759 /* Do nothing here. */
3761 case REND_BASIC_AUTH
:
3762 SMARTLIST_FOREACH(service
->clients
, rend_authorized_client_t
*,
3763 cl
, smartlist_add(client_cookies
, cl
->descriptor_cookie
));
3765 case REND_STEALTH_AUTH
:
3766 client
= smartlist_get(service
->clients
, j
);
3767 client_key
= client
->client_key
;
3768 smartlist_add(client_cookies
, client
->descriptor_cookie
);
3771 /* Encode the current descriptor. */
3772 seconds_valid
= rend_encode_v2_descriptors(descs
, service
->desc
,
3777 if (seconds_valid
< 0) {
3778 log_warn(LD_BUG
, "Internal error: couldn't encode service "
3779 "descriptor; not uploading.");
3780 smartlist_free(descs
);
3781 smartlist_free(client_cookies
);
3784 rend_get_service_id(service
->desc
->pk
, serviceid
);
3785 if (get_options()->PublishHidServDescriptors
) {
3786 /* Post the current descriptors to the hidden service directories. */
3787 log_info(LD_REND
, "Launching upload for hidden service %s",
3789 directory_post_to_hs_dir(service
->desc
, descs
, NULL
, serviceid
,
3792 /* Free memory for descriptors. */
3793 for (i
= 0; i
< smartlist_len(descs
); i
++)
3794 rend_encoded_v2_service_descriptor_free(smartlist_get(descs
, i
));
3795 smartlist_clear(descs
);
3796 /* Update next upload time. */
3797 if (seconds_valid
- REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3799 service
->next_upload_time
= now
+ rendpostperiod
;
3800 else if (seconds_valid
< REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
)
3801 service
->next_upload_time
= now
+ seconds_valid
+ 1;
3803 service
->next_upload_time
= now
+ seconds_valid
-
3804 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
+ 1;
3805 /* Post also the next descriptors, if necessary. */
3806 if (seconds_valid
< REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
) {
3807 seconds_valid
= rend_encode_v2_descriptors(descs
, service
->desc
,
3812 if (seconds_valid
< 0) {
3813 log_warn(LD_BUG
, "Internal error: couldn't encode service "
3814 "descriptor; not uploading.");
3815 smartlist_free(descs
);
3816 smartlist_free(client_cookies
);
3819 if (get_options()->PublishHidServDescriptors
) {
3820 directory_post_to_hs_dir(service
->desc
, descs
, NULL
, serviceid
,
3823 /* Free memory for descriptors. */
3824 for (i
= 0; i
< smartlist_len(descs
); i
++)
3825 rend_encoded_v2_service_descriptor_free(smartlist_get(descs
, i
));
3826 smartlist_clear(descs
);
3829 smartlist_free(descs
);
3830 smartlist_free(client_cookies
);
3832 if (get_options()->PublishHidServDescriptors
) {
3833 log_info(LD_REND
, "Successfully uploaded v2 rend descriptors!");
3835 log_info(LD_REND
, "Successfully stored created v2 rend descriptors!");
3839 /* If not uploaded, try again in one minute. */
3841 service
->next_upload_time
= now
+ 60;
3843 /* Unmark dirty flag of this service. */
3844 service
->desc_is_dirty
= 0;
3847 /** Return the number of INTRODUCE2 cells this hidden service has received
3848 * from this intro point. */
3850 intro_point_accepted_intro_count(rend_intro_point_t
*intro
)
3852 return intro
->accepted_introduce2_count
;
3855 /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
3856 * should stop publishing it in new descriptors and eventually close
3859 intro_point_should_expire_now(rend_intro_point_t
*intro
,
3862 tor_assert(intro
!= NULL
);
3864 if (intro
->time_published
== -1) {
3865 /* Don't expire an intro point if we haven't even published it yet. */
3869 if (intro_point_accepted_intro_count(intro
) >=
3870 intro
->max_introductions
) {
3871 /* This intro point has been used too many times. Expire it now. */
3875 if (intro
->time_to_expire
== -1) {
3876 /* This intro point has been published, but we haven't picked an
3877 * expiration time for it. Pick one now. */
3878 int intro_point_lifetime_seconds
=
3879 crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS
,
3880 INTRO_POINT_LIFETIME_MAX_SECONDS
);
3882 /* Start the expiration timer now, rather than when the intro
3883 * point was first published. There shouldn't be much of a time
3885 intro
->time_to_expire
= now
+ intro_point_lifetime_seconds
;
3890 /* This intro point has a time to expire set already. Use it. */
3891 return (now
>= intro
->time_to_expire
);
3894 /** Iterate over intro points in the given service and remove the invalid
3895 * ones. For an intro point object to be considered invalid, the circuit
3896 * _and_ node need to have disappeared.
3898 * If the intro point should expire, it's placed into the expiring_nodes
3899 * list of the service and removed from the active intro nodes list.
3901 * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
3903 * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
3904 * circuit disappeared but the node is still in the consensus. */
3906 remove_invalid_intro_points(rend_service_t
*service
,
3907 smartlist_t
*exclude_nodes
,
3908 smartlist_t
*retry_nodes
, time_t now
)
3910 tor_assert(service
);
3912 /* Remove any expired nodes that doesn't have a circuit. */
3913 SMARTLIST_FOREACH_BEGIN(service
->expiring_nodes
, rend_intro_point_t
*,
3915 origin_circuit_t
*intro_circ
=
3916 find_intro_circuit(intro
, service
->pk_digest
);
3920 /* No more circuit, cleanup the into point object. */
3921 SMARTLIST_DEL_CURRENT(service
->expiring_nodes
, intro
);
3922 rend_intro_point_free(intro
);
3923 } SMARTLIST_FOREACH_END(intro
);
3925 SMARTLIST_FOREACH_BEGIN(service
->intro_nodes
, rend_intro_point_t
*,
3927 /* Find the introduction point node object. */
3928 const node_t
*node
=
3929 node_get_by_id(intro
->extend_info
->identity_digest
);
3930 /* Find the intro circuit, this might be NULL. */
3931 origin_circuit_t
*intro_circ
=
3932 find_intro_circuit(intro
, service
->pk_digest
);
3934 /* Add the valid node to the exclusion list so we don't try to establish
3935 * an introduction point to it again. */
3936 if (node
&& exclude_nodes
) {
3937 smartlist_add(exclude_nodes
, (void*) node
);
3940 /* First, make sure we still have a valid circuit for this intro point.
3941 * If we dont, we'll give up on it and make a new one. */
3942 if (intro_circ
== NULL
) {
3943 log_info(LD_REND
, "Attempting to retry on %s as intro point for %s"
3944 " (circuit disappeared).",
3945 safe_str_client(extend_info_describe(intro
->extend_info
)),
3946 safe_str_client(service
->service_id
));
3947 /* We've lost the circuit for this intro point, flag it so it can be
3948 * accounted for when considiring uploading a descriptor. */
3949 intro
->circuit_established
= 0;
3951 /* Node is gone or we've reached our maximum circuit creationg retry
3952 * count, clean up everything, we'll find a new one. */
3954 intro
->circuit_retries
>= MAX_INTRO_POINT_CIRCUIT_RETRIES
) {
3955 rend_intro_point_free(intro
);
3956 SMARTLIST_DEL_CURRENT(service
->intro_nodes
, intro
);
3957 /* We've just killed the intro point, nothing left to do. */
3961 /* The intro point is still alive so let's try to use it again because
3962 * we have a published descriptor containing it. Keep the intro point
3963 * in the intro_nodes list because it's still valid, we are rebuilding
3964 * a circuit to it. */
3966 smartlist_add(retry_nodes
, intro
);
3969 /* else, the circuit is valid so in both cases, node being alive or not,
3970 * we leave the circuit and intro point object as is. Closing the
3971 * circuit here would leak new consensus timing and freeing the intro
3972 * point object would make the intro circuit unusable. */
3974 /* Now, check if intro point should expire. If it does, queue it so
3975 * it can be cleaned up once it has been replaced properly. */
3976 if (intro_point_should_expire_now(intro
, now
)) {
3977 log_info(LD_REND
, "Expiring %s as intro point for %s.",
3978 safe_str_client(extend_info_describe(intro
->extend_info
)),
3979 safe_str_client(service
->service_id
));
3980 smartlist_add(service
->expiring_nodes
, intro
);
3981 SMARTLIST_DEL_CURRENT(service
->intro_nodes
, intro
);
3982 /* Intro point is expired, we need a new one thus don't consider it
3983 * anymore has a valid established intro point. */
3984 intro
->circuit_established
= 0;
3986 } SMARTLIST_FOREACH_END(intro
);
3989 /** A new descriptor has been successfully uploaded for the given
3990 * <b>rend_data</b>. Remove and free the expiring nodes from the associated
3993 rend_service_desc_has_uploaded(const rend_data_t
*rend_data
)
3995 rend_service_t
*service
;
3996 const char *onion_address
;
3998 tor_assert(rend_data
);
4000 onion_address
= rend_data_get_address(rend_data
);
4002 service
= rend_service_get_by_service_id(onion_address
);
4003 if (service
== NULL
) {
4007 SMARTLIST_FOREACH_BEGIN(service
->expiring_nodes
, rend_intro_point_t
*,
4009 origin_circuit_t
*intro_circ
=
4010 find_intro_circuit(intro
, service
->pk_digest
);
4011 if (intro_circ
!= NULL
) {
4012 circuit_mark_for_close(TO_CIRCUIT(intro_circ
),
4013 END_CIRC_REASON_FINISHED
);
4015 SMARTLIST_DEL_CURRENT(service
->expiring_nodes
, intro
);
4016 rend_intro_point_free(intro
);
4017 } SMARTLIST_FOREACH_END(intro
);
4020 /** For every service, check how many intro points it currently has, and:
4021 * - Invalidate introdution points based on specific criteria, see
4022 * remove_invalid_intro_points comments.
4023 * - Pick new intro points as necessary.
4024 * - Launch circuits to any new intro points.
4026 * This is called once a second by the main loop.
4029 rend_consider_services_intro_points(void)
4033 const or_options_t
*options
= get_options();
4034 /* Are we in single onion mode? */
4035 const int allow_direct
= rend_service_allow_non_anonymous_connection(
4037 /* List of nodes we need to _exclude_ when choosing a new node to
4038 * establish an intro point to. */
4039 smartlist_t
*exclude_nodes
;
4040 /* List of nodes we need to retry to build a circuit on them because the
4041 * node is valid but circuit died. */
4042 smartlist_t
*retry_nodes
;
4044 if (!have_completed_a_circuit())
4047 exclude_nodes
= smartlist_new();
4048 retry_nodes
= smartlist_new();
4051 SMARTLIST_FOREACH_BEGIN(rend_service_list
, rend_service_t
*, service
) {
4053 /* Number of intro points we want to open and add to the intro nodes
4054 * list of the service. */
4055 unsigned int n_intro_points_to_open
;
4056 /* Have an unsigned len so we can use it to compare values else gcc is
4057 * not happy with unmatching signed comparaison. */
4058 unsigned int intro_nodes_len
;
4059 /* Different service are allowed to have the same introduction point as
4060 * long as they are on different circuit thus why we clear this list. */
4061 smartlist_clear(exclude_nodes
);
4062 smartlist_clear(retry_nodes
);
4064 /* Cleanup the invalid intro points and save the node objects, if any,
4065 * in the exclude_nodes and retry_nodes lists. */
4066 remove_invalid_intro_points(service
, exclude_nodes
, retry_nodes
, now
);
4068 /* This retry period is important here so we don't stress circuit
4070 if (now
> service
->intro_period_started
+ INTRO_CIRC_RETRY_PERIOD
) {
4071 /* One period has elapsed; we can try building circuits again. */
4072 service
->intro_period_started
= now
;
4073 service
->n_intro_circuits_launched
= 0;
4074 } else if (service
->n_intro_circuits_launched
>=
4075 MAX_INTRO_CIRCS_PER_PERIOD
) {
4076 /* We have failed too many times in this period; wait for the next
4077 * one before we try to initiate any more connections. */
4081 /* Let's try to rebuild circuit on the nodes we want to retry on. */
4082 SMARTLIST_FOREACH_BEGIN(retry_nodes
, rend_intro_point_t
*, intro
) {
4083 r
= rend_service_launch_establish_intro(service
, intro
);
4085 log_warn(LD_REND
, "Error launching circuit to node %s for service %s.",
4086 safe_str_client(extend_info_describe(intro
->extend_info
)),
4087 safe_str_client(service
->service_id
));
4088 /* Unable to launch a circuit to that intro point, remove it from
4089 * the valid list so we can create a new one. */
4090 smartlist_remove(service
->intro_nodes
, intro
);
4091 rend_intro_point_free(intro
);
4094 intro
->circuit_retries
++;
4095 } SMARTLIST_FOREACH_END(intro
);
4097 /* Avoid mismatched signed comparaison below. */
4098 intro_nodes_len
= (unsigned int) smartlist_len(service
->intro_nodes
);
4100 /* Quiescent state, we have more or the equal amount of wanted node for
4101 * this service. Proceed to the next service. We can have more nodes
4102 * because we launch extra preemptive circuits if our intro nodes list was
4103 * originally empty for performance reasons. */
4104 if (intro_nodes_len
>= service
->n_intro_points_wanted
) {
4108 /* Number of intro points we want to open which is the wanted amount minus
4109 * the current amount of valid nodes. We know that this won't underflow
4110 * because of the check above. */
4111 n_intro_points_to_open
= service
->n_intro_points_wanted
- intro_nodes_len
;
4112 if (intro_nodes_len
== 0) {
4113 /* We want to end up with n_intro_points_wanted intro points, but if
4114 * we have no intro points at all (chances are they all cycled or we
4115 * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
4116 * and use the first n_intro_points_wanted that complete. See proposal
4117 * #155, section 4 for the rationale of this which is purely for
4120 * The ones after the first n_intro_points_to_open will be converted
4121 * to 'general' internal circuits in rend_service_intro_has_opened(),
4122 * and then we'll drop them from the list of intro points. */
4123 n_intro_points_to_open
+= NUM_INTRO_POINTS_EXTRA
;
4126 for (i
= 0; i
< (int) n_intro_points_to_open
; i
++) {
4128 rend_intro_point_t
*intro
;
4129 router_crn_flags_t flags
= CRN_NEED_UPTIME
|CRN_NEED_DESC
;
4130 if (get_options()->AllowInvalid_
& ALLOW_INVALID_INTRODUCTION
)
4131 flags
|= CRN_ALLOW_INVALID
;
4132 router_crn_flags_t direct_flags
= flags
;
4133 direct_flags
|= CRN_PREF_ADDR
;
4134 direct_flags
|= CRN_DIRECT_CONN
;
4136 node
= router_choose_random_node(exclude_nodes
,
4137 options
->ExcludeNodes
,
4138 allow_direct
? direct_flags
: flags
);
4139 /* If we are in single onion mode, retry node selection for a 3-hop
4141 if (allow_direct
&& !node
) {
4143 "Unable to find an intro point that we can connect to "
4144 "directly for %s, falling back to a 3-hop path.",
4145 safe_str_client(service
->service_id
));
4146 node
= router_choose_random_node(exclude_nodes
,
4147 options
->ExcludeNodes
, flags
);
4152 "We only have %d introduction points established for %s; "
4154 smartlist_len(service
->intro_nodes
),
4155 safe_str_client(service
->service_id
),
4156 n_intro_points_to_open
);
4159 /* Add the choosen node to the exclusion list in order to avoid picking
4160 * it again in the next iteration. */
4161 smartlist_add(exclude_nodes
, (void*)node
);
4162 intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
4163 /* extend_info is for clients, so we want the multi-hop primary ORPort,
4164 * even if we are a single onion service and intend to connect to it
4165 * directly ourselves. */
4166 intro
->extend_info
= extend_info_from_node(node
, 0);
4167 if (BUG(intro
->extend_info
== NULL
)) {
4170 intro
->intro_key
= crypto_pk_new();
4171 const int fail
= crypto_pk_generate_key(intro
->intro_key
);
4173 intro
->time_published
= -1;
4174 intro
->time_to_expire
= -1;
4175 intro
->max_introductions
=
4176 crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS
,
4177 INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS
);
4178 smartlist_add(service
->intro_nodes
, intro
);
4179 log_info(LD_REND
, "Picked router %s as an intro point for %s.",
4180 safe_str_client(node_describe(node
)),
4181 safe_str_client(service
->service_id
));
4182 /* Establish new introduction circuit to our chosen intro point. */
4183 r
= rend_service_launch_establish_intro(service
, intro
);
4185 log_warn(LD_REND
, "Error launching circuit to node %s for service %s.",
4186 safe_str_client(extend_info_describe(intro
->extend_info
)),
4187 safe_str_client(service
->service_id
));
4188 /* This funcion will be called again by the main loop so this intro
4189 * point without a intro circuit will be retried on or removed after
4190 * a maximum number of attempts. */
4193 } SMARTLIST_FOREACH_END(service
);
4194 smartlist_free(exclude_nodes
);
4195 smartlist_free(retry_nodes
);
4198 #define MIN_REND_INITIAL_POST_DELAY (30)
4199 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4201 /** Regenerate and upload rendezvous service descriptors for all
4202 * services, if necessary. If the descriptor has been dirty enough
4203 * for long enough, definitely upload; else only upload when the
4204 * periodic timeout has expired.
4206 * For the first upload, pick a random time between now and two periods
4207 * from now, and pick it independently for each service.
4210 rend_consider_services_upload(time_t now
)
4213 rend_service_t
*service
;
4214 const or_options_t
*options
= get_options();
4215 int rendpostperiod
= options
->RendPostPeriod
;
4216 int rendinitialpostdelay
= (options
->TestingTorNetwork
?
4217 MIN_REND_INITIAL_POST_DELAY_TESTING
:
4218 MIN_REND_INITIAL_POST_DELAY
);
4220 for (i
=0; i
< smartlist_len(rend_service_list
); ++i
) {
4221 service
= smartlist_get(rend_service_list
, i
);
4222 if (!service
->next_upload_time
) { /* never been uploaded yet */
4223 /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4224 * the descriptor is stable before being published. See comment below. */
4225 service
->next_upload_time
=
4226 now
+ rendinitialpostdelay
+ crypto_rand_int(2*rendpostperiod
);
4227 /* Single Onion Services prioritise availability over hiding their
4228 * startup time, as their IP address is publicly discoverable anyway.
4230 if (rend_service_reveal_startup_time(options
)) {
4231 service
->next_upload_time
= now
+ rendinitialpostdelay
;
4234 /* Does every introduction points have been established? */
4235 unsigned int intro_points_ready
=
4236 count_established_intro_points(service
) >=
4237 service
->n_intro_points_wanted
;
4238 if (intro_points_ready
&&
4239 (service
->next_upload_time
< now
||
4240 (service
->desc_is_dirty
&&
4241 service
->desc_is_dirty
< now
-rendinitialpostdelay
))) {
4242 /* if it's time, or if the directory servers have a wrong service
4243 * descriptor and ours has been stable for rendinitialpostdelay seconds,
4244 * upload a new one of each format. */
4245 rend_service_update_descriptor(service
);
4246 upload_service_descriptor(service
);
4251 /** True if the list of available router descriptors might have changed so
4252 * that we should have a look whether we can republish previously failed
4253 * rendezvous service descriptors. */
4254 static int consider_republishing_rend_descriptors
= 1;
4256 /** Called when our internal view of the directory has changed, so that we
4257 * might have router descriptors of hidden service directories available that
4258 * we did not have before. */
4260 rend_hsdir_routers_changed(void)
4262 consider_republishing_rend_descriptors
= 1;
4265 /** Consider republication of v2 rendezvous service descriptors that failed
4266 * previously, but without regenerating descriptor contents.
4269 rend_consider_descriptor_republication(void)
4272 rend_service_t
*service
;
4274 if (!consider_republishing_rend_descriptors
)
4276 consider_republishing_rend_descriptors
= 0;
4278 if (!get_options()->PublishHidServDescriptors
)
4281 for (i
=0; i
< smartlist_len(rend_service_list
); ++i
) {
4282 service
= smartlist_get(rend_service_list
, i
);
4283 if (service
->desc
&& !service
->desc
->all_uploads_performed
) {
4284 /* If we failed in uploading a descriptor last time, try again *without*
4285 * updating the descriptor's contents. */
4286 upload_service_descriptor(service
);
4291 /** Log the status of introduction points for all rendezvous services
4292 * at log severity <b>severity</b>.
4295 rend_service_dump_stats(int severity
)
4298 rend_service_t
*service
;
4299 rend_intro_point_t
*intro
;
4300 const char *safe_name
;
4301 origin_circuit_t
*circ
;
4303 for (i
=0; i
< smartlist_len(rend_service_list
); ++i
) {
4304 service
= smartlist_get(rend_service_list
, i
);
4305 tor_log(severity
, LD_GENERAL
, "Service configured in %s:",
4306 rend_service_escaped_dir(service
));
4307 for (j
=0; j
< smartlist_len(service
->intro_nodes
); ++j
) {
4308 intro
= smartlist_get(service
->intro_nodes
, j
);
4309 safe_name
= safe_str_client(intro
->extend_info
->nickname
);
4311 circ
= find_intro_circuit(intro
, service
->pk_digest
);
4313 tor_log(severity
, LD_GENERAL
, " Intro point %d at %s: no circuit",
4317 tor_log(severity
, LD_GENERAL
, " Intro point %d at %s: circuit is %s",
4318 j
, safe_name
, circuit_state_to_string(circ
->base_
.state
));
4323 #ifdef HAVE_SYS_UN_H
4325 /** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
4326 * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
4327 * else return -ENOSYS if AF_UNIX is not supported (see function in the
4328 * #else statement below). */
4330 add_unix_port(smartlist_t
*ports
, rend_service_port_config_t
*p
)
4334 tor_assert(p
->is_unix_addr
);
4336 smartlist_add(ports
, p
);
4340 /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
4341 * on success else return -ENOSYS if AF_UNIX is not supported (see function
4342 * in the #else statement below). */
4344 set_unix_port(edge_connection_t
*conn
, rend_service_port_config_t
*p
)
4348 tor_assert(p
->is_unix_addr
);
4350 conn
->base_
.socket_family
= AF_UNIX
;
4351 tor_addr_make_unspec(&conn
->base_
.addr
);
4352 conn
->base_
.port
= 1;
4353 conn
->base_
.address
= tor_strdup(p
->unix_addr
);
4357 #else /* defined(HAVE_SYS_UN_H) */
4360 set_unix_port(edge_connection_t
*conn
, rend_service_port_config_t
*p
)
4368 add_unix_port(smartlist_t
*ports
, rend_service_port_config_t
*p
)
4375 #endif /* HAVE_SYS_UN_H */
4377 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
4378 * 'circ', and look up the port and address based on conn-\>port.
4379 * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
4380 * for which the circuit should be closed, -1 on other failure,
4384 rend_service_set_connection_addr_port(edge_connection_t
*conn
,
4385 origin_circuit_t
*circ
)
4387 rend_service_t
*service
;
4388 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
4389 smartlist_t
*matching_ports
;
4390 rend_service_port_config_t
*chosen_port
;
4391 unsigned int warn_once
= 0;
4392 const char *rend_pk_digest
;
4394 tor_assert(circ
->base_
.purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
);
4395 tor_assert(circ
->rend_data
);
4396 log_debug(LD_REND
,"beginning to hunt for addr/port");
4397 /* XXX: This is version 2 specific (only one supported). */
4398 rend_pk_digest
= (char *) rend_data_get_pk_digest(circ
->rend_data
, NULL
);
4399 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
4400 rend_pk_digest
, REND_SERVICE_ID_LEN
);
4401 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
4403 log_warn(LD_REND
, "Couldn't find any service associated with pk %s on "
4404 "rendezvous circuit %u; closing.",
4405 serviceid
, (unsigned)circ
->base_
.n_circ_id
);
4408 if (service
->max_streams_per_circuit
> 0) {
4409 /* Enforce the streams-per-circuit limit, and refuse to provide a
4410 * mapping if this circuit will exceed the limit. */
4411 #define MAX_STREAM_WARN_INTERVAL 600
4412 static struct ratelim_t stream_ratelim
=
4413 RATELIM_INIT(MAX_STREAM_WARN_INTERVAL
);
4414 if (circ
->rend_data
->nr_streams
>= service
->max_streams_per_circuit
) {
4415 log_fn_ratelim(&stream_ratelim
, LOG_WARN
, LD_REND
,
4416 "Maximum streams per circuit limit reached on rendezvous "
4417 "circuit %u; %s. Circuit has %d out of %d streams.",
4418 (unsigned)circ
->base_
.n_circ_id
,
4419 service
->max_streams_close_circuit
?
4421 "ignoring open stream request",
4422 circ
->rend_data
->nr_streams
,
4423 service
->max_streams_per_circuit
);
4424 return service
->max_streams_close_circuit
? -2 : -1;
4427 matching_ports
= smartlist_new();
4428 SMARTLIST_FOREACH(service
->ports
, rend_service_port_config_t
*, p
,
4430 if (conn
->base_
.port
!= p
->virtual_port
) {
4433 if (!(p
->is_unix_addr
)) {
4434 smartlist_add(matching_ports
, p
);
4436 if (add_unix_port(matching_ports
, p
)) {
4438 /* Unix port not supported so warn only once. */
4440 "Saw AF_UNIX virtual port mapping for port %d on service "
4441 "%s, which is unsupported on this platform. Ignoring it.",
4442 conn
->base_
.port
, serviceid
);
4448 chosen_port
= smartlist_choose(matching_ports
);
4449 smartlist_free(matching_ports
);
4451 if (!(chosen_port
->is_unix_addr
)) {
4452 /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
4453 tor_addr_copy(&conn
->base_
.addr
, &chosen_port
->real_addr
);
4454 conn
->base_
.port
= chosen_port
->real_port
;
4456 if (set_unix_port(conn
, chosen_port
)) {
4457 /* Simply impossible to end up here else we were able to add a Unix
4458 * port without AF_UNIX support... ? */
4466 "No virtual port mapping exists for port %d on service %s",
4467 conn
->base_
.port
, serviceid
);
4469 if (service
->allow_unknown_ports
)
4475 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4478 rend_service_non_anonymous_mode_consistent(const or_options_t
*options
)
4480 /* !! is used to make these options boolean */
4481 return (!! options
->HiddenServiceSingleHopMode
==
4482 !! options
->HiddenServiceNonAnonymousMode
);
4485 /* Do the options allow onion services to make direct (non-anonymous)
4486 * connections to introduction or rendezvous points?
4487 * Must only be called after options_validate_single_onion() has successfully
4488 * checked onion service option consistency.
4489 * Returns true if tor is in HiddenServiceSingleHopMode. */
4491 rend_service_allow_non_anonymous_connection(const or_options_t
*options
)
4493 tor_assert(rend_service_non_anonymous_mode_consistent(options
));
4494 return options
->HiddenServiceSingleHopMode
? 1 : 0;
4497 /* Do the options allow us to reveal the exact startup time of the onion
4499 * Single Onion Services prioritise availability over hiding their
4500 * startup time, as their IP address is publicly discoverable anyway.
4501 * Must only be called after options_validate_single_onion() has successfully
4502 * checked onion service option consistency.
4503 * Returns true if tor is in non-anonymous hidden service mode. */
4505 rend_service_reveal_startup_time(const or_options_t
*options
)
4507 tor_assert(rend_service_non_anonymous_mode_consistent(options
));
4508 return rend_service_non_anonymous_mode_enabled(options
);
4511 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4513 * Must only be called after options_validate_single_onion() has successfully
4514 * checked onion service option consistency.
4517 rend_service_non_anonymous_mode_enabled(const or_options_t
*options
)
4519 tor_assert(rend_service_non_anonymous_mode_consistent(options
));
4520 return options
->HiddenServiceNonAnonymousMode
? 1 : 0;