1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2017, 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"
21 #include "hs_config.h"
23 #include "networkstatus.h"
26 #include "rendclient.h"
27 #include "rendcommon.h"
28 #include "rendservice.h"
32 #include "replaycache.h"
33 #include "routerlist.h"
34 #include "routerparse.h"
35 #include "routerset.h"
37 struct rend_service_t
;
38 static origin_circuit_t
*find_intro_circuit(rend_intro_point_t
*intro
,
39 const char *pk_digest
);
40 static rend_intro_point_t
*find_intro_point(origin_circuit_t
*circ
);
41 static rend_intro_point_t
*find_expiring_intro_point(
42 struct rend_service_t
*service
, origin_circuit_t
*circ
);
44 static extend_info_t
*find_rp_for_intro(
45 const rend_intro_cell_t
*intro
,
48 static int intro_point_accepted_intro_count(rend_intro_point_t
*intro
);
49 static int intro_point_should_expire_now(rend_intro_point_t
*intro
,
51 static int rend_service_derive_key_digests(struct rend_service_t
*s
);
52 static int rend_service_load_keys(struct rend_service_t
*s
);
53 static int rend_service_load_auth_keys(struct rend_service_t
*s
,
55 static struct rend_service_t
*rend_service_get_by_pk_digest(
57 static struct rend_service_t
*rend_service_get_by_service_id(const char *id
);
58 static const char *rend_service_escaped_dir(
59 const struct rend_service_t
*s
);
61 static ssize_t
rend_service_parse_intro_for_v0_or_v1(
62 rend_intro_cell_t
*intro
,
66 static ssize_t
rend_service_parse_intro_for_v2(
67 rend_intro_cell_t
*intro
,
71 static ssize_t
rend_service_parse_intro_for_v3(
72 rend_intro_cell_t
*intro
,
77 static int rend_service_check_private_dir(const or_options_t
*options
,
78 const rend_service_t
*s
,
80 static const smartlist_t
* rend_get_service_list(
81 const smartlist_t
* substitute_service_list
);
82 static smartlist_t
* rend_get_service_list_mutable(
83 smartlist_t
* substitute_service_list
);
84 static int rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted
);
86 /* Hidden service directory file names:
87 * new file names should be added to rend_service_add_filenames_to_list()
88 * for sandboxing purposes. */
89 static const char *private_key_fname
= "private_key";
90 static const char *hostname_fname
= "hostname";
91 static const char *client_keys_fname
= "client_keys";
92 static const char *sos_poison_fname
= "onion_service_non_anonymous";
94 /** A list of rend_service_t's for services run on this OP. */
95 static smartlist_t
*rend_service_list
= NULL
;
96 /** A list of rend_service_t's for services run on this OP which is used as a
97 * staging area before they are put in the main list in order to prune dying
98 * service on config reload. */
99 static smartlist_t
*rend_service_staging_list
= NULL
;
101 /* Like rend_get_service_list_mutable, but returns a read-only list. */
102 static const smartlist_t
*
103 rend_get_service_list(const smartlist_t
* substitute_service_list
)
105 /* It is safe to cast away the const here, because
106 * rend_get_service_list_mutable does not actually modify the list */
107 return rend_get_service_list_mutable((smartlist_t
*)substitute_service_list
);
110 /* Return a mutable list of hidden services.
111 * If substitute_service_list is not NULL, return it.
112 * Otherwise, check if the global rend_service_list is non-NULL, and if so,
114 * Otherwise, log a BUG message and return NULL.
117 rend_get_service_list_mutable(smartlist_t
* substitute_service_list
)
119 if (substitute_service_list
) {
120 return substitute_service_list
;
123 /* If no special service list is provided, then just use the global one. */
125 if (BUG(!rend_service_list
)) {
126 /* No global HS list, which is a programmer error. */
130 return rend_service_list
;
133 /** Tells if onion service <b>s</b> is ephemeral.
136 rend_service_is_ephemeral(const struct rend_service_t
*s
)
138 return (s
->directory
== NULL
);
141 /** Returns a escaped string representation of the service, <b>s</b>.
144 rend_service_escaped_dir(const struct rend_service_t
*s
)
146 return rend_service_is_ephemeral(s
) ? "[EPHEMERAL]" : escaped(s
->directory
);
149 /** Return the number of rendezvous services we have configured. */
151 rend_num_services(void)
153 if (!rend_service_list
)
155 return smartlist_len(rend_service_list
);
158 /** Helper: free storage held by a single service authorized client entry. */
160 rend_authorized_client_free(rend_authorized_client_t
*client
)
164 if (client
->client_key
)
165 crypto_pk_free(client
->client_key
);
166 if (client
->client_name
)
167 memwipe(client
->client_name
, 0, strlen(client
->client_name
));
168 tor_free(client
->client_name
);
169 memwipe(client
->descriptor_cookie
, 0, sizeof(client
->descriptor_cookie
));
173 /** Helper for strmap_free. */
175 rend_authorized_client_strmap_item_free(void *authorized_client
)
177 rend_authorized_client_free(authorized_client
);
180 /** Release the storage held by <b>service</b>.
183 rend_service_free(rend_service_t
*service
)
188 tor_free(service
->directory
);
189 if (service
->ports
) {
190 SMARTLIST_FOREACH(service
->ports
, rend_service_port_config_t
*, p
,
191 rend_service_port_config_free(p
));
192 smartlist_free(service
->ports
);
194 if (service
->private_key
)
195 crypto_pk_free(service
->private_key
);
196 if (service
->intro_nodes
) {
197 SMARTLIST_FOREACH(service
->intro_nodes
, rend_intro_point_t
*, intro
,
198 rend_intro_point_free(intro
););
199 smartlist_free(service
->intro_nodes
);
201 if (service
->expiring_nodes
) {
202 SMARTLIST_FOREACH(service
->expiring_nodes
, rend_intro_point_t
*, intro
,
203 rend_intro_point_free(intro
););
204 smartlist_free(service
->expiring_nodes
);
207 rend_service_descriptor_free(service
->desc
);
208 if (service
->clients
) {
209 SMARTLIST_FOREACH(service
->clients
, rend_authorized_client_t
*, c
,
210 rend_authorized_client_free(c
););
211 smartlist_free(service
->clients
);
213 if (service
->accepted_intro_dh_parts
) {
214 replaycache_free(service
->accepted_intro_dh_parts
);
219 /* Release all the storage held in rend_service_staging_list. */
221 rend_service_free_staging_list(void)
223 if (rend_service_staging_list
) {
224 SMARTLIST_FOREACH(rend_service_staging_list
, rend_service_t
*, ptr
,
225 rend_service_free(ptr
));
226 smartlist_free(rend_service_staging_list
);
227 rend_service_staging_list
= NULL
;
231 /** Release all the storage held in both rend_service_list and
232 * rend_service_staging_list. */
234 rend_service_free_all(void)
236 if (rend_service_list
) {
237 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, ptr
,
238 rend_service_free(ptr
));
239 smartlist_free(rend_service_list
);
240 rend_service_list
= NULL
;
242 rend_service_free_staging_list();
245 /* Initialize the subsystem. */
247 rend_service_init(void)
249 tor_assert(!rend_service_list
);
250 tor_assert(!rend_service_staging_list
);
252 rend_service_list
= smartlist_new();
253 rend_service_staging_list
= smartlist_new();
256 /* Validate a <b>service</b>. Use the <b>service_list</b> to make sure there
257 * is no duplicate entry for the given service object. Return 0 if valid else
260 rend_validate_service(const smartlist_t
*service_list
,
261 const rend_service_t
*service
)
263 tor_assert(service_list
);
266 if (service
->max_streams_per_circuit
< 0) {
267 log_warn(LD_CONFIG
, "Hidden service (%s) configured with negative max "
268 "streams per circuit.",
269 rend_service_escaped_dir(service
));
273 if (service
->max_streams_close_circuit
< 0 ||
274 service
->max_streams_close_circuit
> 1) {
275 log_warn(LD_CONFIG
, "Hidden service (%s) configured with invalid "
276 "max streams handling.",
277 rend_service_escaped_dir(service
));
281 if (service
->auth_type
!= REND_NO_AUTH
&&
282 (!service
->clients
|| smartlist_len(service
->clients
) == 0)) {
283 log_warn(LD_CONFIG
, "Hidden service (%s) with client authorization but "
285 rend_service_escaped_dir(service
));
289 if (!service
->ports
|| !smartlist_len(service
->ports
)) {
290 log_warn(LD_CONFIG
, "Hidden service (%s) with no ports configured.",
291 rend_service_escaped_dir(service
));
301 /** Add it to <b>service_list</b>, or to the global rend_service_list if
302 * <b>service_list</b> is NULL. Return 0 on success. On failure, free
303 * <b>service</b> and return -1. Takes ownership of <b>service</b>. */
305 rend_add_service(smartlist_t
*service_list
, rend_service_t
*service
)
308 rend_service_port_config_t
*p
;
312 smartlist_t
*s_list
= rend_get_service_list_mutable(service_list
);
313 /* We must have a service list, even if it's a temporary one, so we can
314 * check for duplicate services */
316 rend_service_free(service
);
320 service
->intro_nodes
= smartlist_new();
321 service
->expiring_nodes
= smartlist_new();
323 log_debug(LD_REND
,"Configuring service with directory %s",
324 rend_service_escaped_dir(service
));
325 for (i
= 0; i
< smartlist_len(service
->ports
); ++i
) {
326 p
= smartlist_get(service
->ports
, i
);
327 if (!(p
->is_unix_addr
)) {
329 "Service maps port %d to %s",
331 fmt_addrport(&p
->real_addr
, p
->real_port
));
335 "Service maps port %d to socket at \"%s\"",
336 p
->virtual_port
, p
->unix_addr
);
339 "Service maps port %d to an AF_UNIX socket, but we "
340 "have no AF_UNIX support on this platform. This is "
343 rend_service_free(service
);
345 #endif /* defined(HAVE_SYS_UN_H) */
348 /* The service passed all the checks */
350 smartlist_add(s_list
, service
);
354 /** Return a new rend_service_port_config_t with its path set to
355 * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
356 static rend_service_port_config_t
*
357 rend_service_port_config_new(const char *socket_path
)
360 return tor_malloc_zero(sizeof(rend_service_port_config_t
) + 1);
362 const size_t pathlen
= strlen(socket_path
) + 1;
363 rend_service_port_config_t
*conf
=
364 tor_malloc_zero(sizeof(rend_service_port_config_t
) + pathlen
);
365 memcpy(conf
->unix_addr
, socket_path
, pathlen
);
366 conf
->is_unix_addr
= 1;
370 /** Parses a virtual-port to real-port/socket mapping separated by
371 * the provided separator and returns a new rend_service_port_config_t,
372 * or NULL and an optional error string on failure.
374 * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
376 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
378 rend_service_port_config_t
*
379 rend_service_parse_port_config(const char *string
, const char *sep
,
387 rend_service_port_config_t
*result
= NULL
;
388 unsigned int is_unix_addr
= 0;
389 const char *socket_path
= NULL
;
390 char *err_msg
= NULL
;
391 char *addrport
= NULL
;
393 sl
= smartlist_new();
394 smartlist_split_string(sl
, string
, sep
,
395 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
396 if (smartlist_len(sl
) < 1 || BUG(smartlist_len(sl
) > 2)) {
397 err_msg
= tor_strdup("Bad syntax in hidden service port configuration.");
400 virtport
= (int)tor_parse_long(smartlist_get(sl
,0), 10, 1, 65535, NULL
,NULL
);
402 tor_asprintf(&err_msg
, "Missing or invalid port %s in hidden service "
403 "port configuration", escaped(smartlist_get(sl
,0)));
407 if (smartlist_len(sl
) == 1) {
408 /* No addr:port part; use default. */
410 tor_addr_from_ipv4h(&addr
, 0x7F000001u
); /* 127.0.0.1 */
414 const char *addrport_element
= smartlist_get(sl
,1);
415 const char *rest
= NULL
;
417 ret
= port_cfg_line_extract_addrport(addrport_element
, &addrport
,
420 tor_asprintf(&err_msg
, "Couldn't process address <%s> from hidden "
421 "service configuration", addrport_element
);
425 socket_path
= addrport
;
427 } else if (strchr(addrport
, ':') || strchr(addrport
, '.')) {
428 /* else try it as an IP:port pair if it has a : or . in it */
429 if (tor_addr_port_lookup(addrport
, &addr
, &p
)<0) {
430 err_msg
= tor_strdup("Unparseable address in hidden service port "
434 realport
= p
?p
:virtport
;
436 /* No addr:port, no addr -- must be port. */
437 realport
= (int)tor_parse_long(addrport
, 10, 1, 65535, NULL
, NULL
);
439 tor_asprintf(&err_msg
, "Unparseable or out-of-range port %s in "
440 "hidden service port configuration.",
444 tor_addr_from_ipv4h(&addr
, 0x7F000001u
); /* Default to 127.0.0.1 */
448 /* Allow room for unix_addr */
449 result
= rend_service_port_config_new(socket_path
);
450 result
->virtual_port
= virtport
;
451 result
->is_unix_addr
= is_unix_addr
;
453 result
->real_port
= realport
;
454 tor_addr_copy(&result
->real_addr
, &addr
);
455 result
->unix_addr
[0] = '\0';
460 if (err_msg_out
!= NULL
) {
461 *err_msg_out
= err_msg
;
465 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
471 /** Release all storage held in a rend_service_port_config_t. */
473 rend_service_port_config_free(rend_service_port_config_t
*p
)
478 /* Copy relevant data from service src to dst while pruning the service lists.
479 * This should only be called during the pruning process which takes existing
480 * services and copy their data to the newly configured services. The src
481 * service replaycache will be set to NULL after this call. */
483 copy_service_on_prunning(rend_service_t
*dst
, rend_service_t
*src
)
488 /* Keep the timestamps for when the content changed and the next upload
489 * time so we can properly upload the descriptor if needed for the new
491 dst
->desc_is_dirty
= src
->desc_is_dirty
;
492 dst
->next_upload_time
= src
->next_upload_time
;
493 /* Move the replaycache to the new object. */
494 dst
->accepted_intro_dh_parts
= src
->accepted_intro_dh_parts
;
495 src
->accepted_intro_dh_parts
= NULL
;
496 /* Copy intro point information to destination service. */
497 dst
->intro_period_started
= src
->intro_period_started
;
498 dst
->n_intro_circuits_launched
= src
->n_intro_circuits_launched
;
499 dst
->n_intro_points_wanted
= src
->n_intro_points_wanted
;
502 /* Helper: Actual implementation of the pruning on reload which we've
503 * decoupled in order to make the unit test workeable without ugly hacks.
504 * Furthermore, this function does NOT free any memory but will nullify the
505 * temporary list pointer whatever happens. */
507 rend_service_prune_list_impl_(void)
509 origin_circuit_t
*ocirc
= NULL
;
510 smartlist_t
*surviving_services
, *old_service_list
, *new_service_list
;
512 /* When pruning our current service list, we must have a staging list that
513 * contains what we want to check else it's a code flow error. */
514 tor_assert(rend_service_staging_list
);
516 /* We are about to prune the current list of its dead service so set the
517 * semantic for that list to be the "old" one. */
518 old_service_list
= rend_service_list
;
519 /* The staging list is now the "new" list so set this semantic. */
520 new_service_list
= rend_service_staging_list
;
521 /* After this, whatever happens, we'll use our new list. */
522 rend_service_list
= new_service_list
;
523 /* Finally, nullify the staging list pointer as we don't need it anymore
524 * and it needs to be NULL before the next reload. */
525 rend_service_staging_list
= NULL
;
526 /* Nothing to prune if we have no service list so stop right away. */
527 if (!old_service_list
) {
531 /* This contains all _existing_ services that survives the relaod that is
532 * that haven't been removed from the configuration. The difference between
533 * this list and the new service list is that the new list can possibly
534 * contain newly configured service that have no introduction points opened
535 * yet nor key material loaded or generated. */
536 surviving_services
= smartlist_new();
538 /* Preserve the existing ephemeral services.
540 * This is the ephemeral service equivalent of the "Copy introduction
541 * points to new services" block, except there's no copy required since
542 * the service structure isn't regenerated.
544 * After this is done, all ephemeral services will be:
545 * * Removed from old_service_list, so the equivalent non-ephemeral code
546 * will not attempt to preserve them.
547 * * Added to the new_service_list (that previously only had the
548 * services listed in the configuration).
549 * * Added to surviving_services, which is the list of services that
550 * will NOT have their intro point closed.
552 SMARTLIST_FOREACH_BEGIN(old_service_list
, rend_service_t
*, old
) {
553 if (rend_service_is_ephemeral(old
)) {
554 SMARTLIST_DEL_CURRENT(old_service_list
, old
);
555 smartlist_add(surviving_services
, old
);
556 smartlist_add(new_service_list
, old
);
558 } SMARTLIST_FOREACH_END(old
);
560 /* Copy introduction points to new services. This is O(n^2), but it's only
561 * called on reconfigure, so it's ok performance wise. */
562 SMARTLIST_FOREACH_BEGIN(new_service_list
, rend_service_t
*, new) {
563 SMARTLIST_FOREACH_BEGIN(old_service_list
, rend_service_t
*, old
) {
564 /* Skip ephemeral services as we only want to copy introduction points
565 * from current services to newly configured one that already exists.
566 * The same directory means it's the same service. */
567 if (rend_service_is_ephemeral(new) || rend_service_is_ephemeral(old
) ||
568 strcmp(old
->directory
, new->directory
)) {
571 smartlist_add_all(new->intro_nodes
, old
->intro_nodes
);
572 smartlist_clear(old
->intro_nodes
);
573 smartlist_add_all(new->expiring_nodes
, old
->expiring_nodes
);
574 smartlist_clear(old
->expiring_nodes
);
576 /* Copy needed information from old to new. */
577 copy_service_on_prunning(new, old
);
579 /* This regular service will survive the closing IPs step after. */
580 smartlist_add(surviving_services
, old
);
582 } SMARTLIST_FOREACH_END(old
);
583 } SMARTLIST_FOREACH_END(new);
585 /* For every service introduction circuit we can find, see if we have a
586 * matching surviving configured service. If not, close the circuit. */
587 while ((ocirc
= circuit_get_next_service_intro_circ(ocirc
))) {
589 if (ocirc
->rend_data
== NULL
) {
590 /* This is a v3 circuit, ignore it. */
593 SMARTLIST_FOREACH_BEGIN(surviving_services
, const rend_service_t
*, s
) {
594 if (rend_circuit_pk_digest_eq(ocirc
, (uint8_t *) s
->pk_digest
)) {
595 /* Keep this circuit as we have a matching configured service. */
599 } SMARTLIST_FOREACH_END(s
);
603 log_info(LD_REND
, "Closing intro point %s for service %s.",
604 safe_str_client(extend_info_describe(
605 ocirc
->build_state
->chosen_exit
)),
606 safe_str_client(rend_data_get_address(ocirc
->rend_data
)));
607 /* Reason is FINISHED because service has been removed and thus the
608 * circuit is considered old/uneeded. */
609 circuit_mark_for_close(TO_CIRCUIT(ocirc
), END_CIRC_REASON_FINISHED
);
611 smartlist_free(surviving_services
);
614 /* Try to prune our main service list using the temporary one that we just
615 * loaded and parsed successfully. The pruning process decides which onion
616 * services to keep and which to discard after a reload. */
618 rend_service_prune_list(void)
620 smartlist_t
*old_service_list
= rend_service_list
;
621 /* Don't try to prune anything if we have no staging list. */
622 if (!rend_service_staging_list
) {
625 rend_service_prune_list_impl_();
626 if (old_service_list
) {
627 /* Every remaining service in the old list have been removed from the
628 * configuration so clean them up safely. */
629 SMARTLIST_FOREACH(old_service_list
, rend_service_t
*, s
,
630 rend_service_free(s
));
631 smartlist_free(old_service_list
);
635 /* Copy all the relevant data that the hs_service object contains over to the
636 * rend_service_t object. The reason to do so is because when configuring a
637 * service, we go through a generic handler that creates an hs_service_t
638 * object which so we have to copy the parsed values to a rend service object
639 * which is version 2 specific. */
641 service_config_shadow_copy(rend_service_t
*service
,
642 hs_service_config_t
*config
)
647 service
->directory
= tor_strdup(config
->directory_path
);
648 service
->dir_group_readable
= config
->dir_group_readable
;
649 service
->allow_unknown_ports
= config
->allow_unknown_ports
;
650 /* This value can't go above HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT (65535)
651 * if the code flow is right so this cast is safe. But just in case, we'll
653 service
->max_streams_per_circuit
= (int) config
->max_streams_per_rdv_circuit
;
654 if (BUG(config
->max_streams_per_rdv_circuit
>
655 HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT
)) {
656 service
->max_streams_per_circuit
= HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT
;
658 service
->max_streams_close_circuit
= config
->max_streams_close_circuit
;
659 service
->n_intro_points_wanted
= config
->num_intro_points
;
660 /* Switching ownership of the ports to the rend service object. */
661 smartlist_add_all(service
->ports
, config
->ports
);
662 smartlist_free(config
->ports
);
663 config
->ports
= NULL
;
666 /* Parse the hidden service configuration starting at <b>line_</b> using the
667 * already configured generic service configuration in <b>config</b>. This
668 * function will translate the config object to a rend_service_t and add it to
669 * the temporary list if valid. If <b>validate_only</b> is set, parse, warn
670 * and return as normal but don't actually add the service to the list. */
672 rend_config_service(const config_line_t
*line_
,
673 const or_options_t
*options
,
674 hs_service_config_t
*config
)
676 const config_line_t
*line
;
677 rend_service_t
*service
= NULL
;
679 /* line_ can be NULL which would mean that the service configuration only
680 * have one line that is the directory directive. */
684 /* Use the staging service list so that we can check then do the pruning
685 * process using the main list at the end. */
686 if (rend_service_staging_list
== NULL
) {
687 rend_service_staging_list
= smartlist_new();
690 /* Initialize service. */
691 service
= tor_malloc_zero(sizeof(rend_service_t
));
692 service
->intro_period_started
= time(NULL
);
693 service
->ports
= smartlist_new();
694 /* From the hs_service object which has been used to load the generic
695 * options, we'll copy over the useful data to the rend_service_t object. */
696 service_config_shadow_copy(service
, config
);
698 for (line
= line_
; line
; line
= line
->next
) {
699 if (!strcasecmp(line
->key
, "HiddenServiceDir")) {
700 /* We just hit the next hidden service, stop right now. */
703 /* Number of introduction points. */
704 if (!strcasecmp(line
->key
, "HiddenServiceNumIntroductionPoints")) {
706 /* Those are specific defaults for version 2. */
707 service
->n_intro_points_wanted
=
708 (unsigned int) tor_parse_long(line
->value
, 10,
709 0, NUM_INTRO_POINTS_MAX
, &ok
, NULL
);
712 "HiddenServiceNumIntroductionPoints "
713 "should be between %d and %d, not %s",
714 0, NUM_INTRO_POINTS_MAX
, line
->value
);
717 log_info(LD_CONFIG
, "HiddenServiceNumIntroductionPoints=%d for %s",
718 service
->n_intro_points_wanted
, escaped(service
->directory
));
721 if (!strcasecmp(line
->key
, "HiddenServiceAuthorizeClient")) {
722 /* Parse auth type and comma-separated list of client names and add a
723 * rend_authorized_client_t for each client to the service's list
724 * of authorized clients. */
725 smartlist_t
*type_names_split
, *clients
;
726 const char *authname
;
727 if (service
->auth_type
!= REND_NO_AUTH
) {
728 log_warn(LD_CONFIG
, "Got multiple HiddenServiceAuthorizeClient "
729 "lines for a single service.");
732 type_names_split
= smartlist_new();
733 smartlist_split_string(type_names_split
, line
->value
, " ", 0, 2);
734 if (smartlist_len(type_names_split
) < 1) {
735 log_warn(LD_BUG
, "HiddenServiceAuthorizeClient has no value. This "
736 "should have been prevented when parsing the "
738 smartlist_free(type_names_split
);
741 authname
= smartlist_get(type_names_split
, 0);
742 if (!strcasecmp(authname
, "basic")) {
743 service
->auth_type
= REND_BASIC_AUTH
;
744 } else if (!strcasecmp(authname
, "stealth")) {
745 service
->auth_type
= REND_STEALTH_AUTH
;
747 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains "
748 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
750 (char *) smartlist_get(type_names_split
, 0));
751 SMARTLIST_FOREACH(type_names_split
, char *, cp
, tor_free(cp
));
752 smartlist_free(type_names_split
);
755 service
->clients
= smartlist_new();
756 if (smartlist_len(type_names_split
) < 2) {
757 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains "
758 "auth-type '%s', but no client names.",
759 service
->auth_type
== REND_BASIC_AUTH
? "basic" : "stealth");
760 SMARTLIST_FOREACH(type_names_split
, char *, cp
, tor_free(cp
));
761 smartlist_free(type_names_split
);
764 clients
= smartlist_new();
765 smartlist_split_string(clients
, smartlist_get(type_names_split
, 1),
766 ",", SPLIT_SKIP_SPACE
, 0);
767 SMARTLIST_FOREACH(type_names_split
, char *, cp
, tor_free(cp
));
768 smartlist_free(type_names_split
);
769 /* Remove duplicate client names. */
771 int num_clients
= smartlist_len(clients
);
772 smartlist_sort_strings(clients
);
773 smartlist_uniq_strings(clients
);
774 if (smartlist_len(clients
) < num_clients
) {
775 log_info(LD_CONFIG
, "HiddenServiceAuthorizeClient contains %d "
776 "duplicate client name(s); removing.",
777 num_clients
- smartlist_len(clients
));
780 SMARTLIST_FOREACH_BEGIN(clients
, const char *, client_name
)
782 rend_authorized_client_t
*client
;
783 if (!rend_valid_client_name(client_name
)) {
784 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains an "
785 "illegal client name: '%s'. Names must be "
786 "between 1 and %d characters and contain "
787 "only [A-Za-z0-9+_-].",
788 client_name
, REND_CLIENTNAME_MAX_LEN
);
789 SMARTLIST_FOREACH(clients
, char *, cp
, tor_free(cp
));
790 smartlist_free(clients
);
793 client
= tor_malloc_zero(sizeof(rend_authorized_client_t
));
794 client
->client_name
= tor_strdup(client_name
);
795 smartlist_add(service
->clients
, client
);
796 log_debug(LD_REND
, "Adding client name '%s'", client_name
);
798 SMARTLIST_FOREACH_END(client_name
);
799 SMARTLIST_FOREACH(clients
, char *, cp
, tor_free(cp
));
800 smartlist_free(clients
);
801 /* Ensure maximum number of clients. */
802 if ((service
->auth_type
== REND_BASIC_AUTH
&&
803 smartlist_len(service
->clients
) > 512) ||
804 (service
->auth_type
== REND_STEALTH_AUTH
&&
805 smartlist_len(service
->clients
) > 16)) {
806 log_warn(LD_CONFIG
, "HiddenServiceAuthorizeClient contains %d "
807 "client authorization entries, but only a "
808 "maximum of %d entries is allowed for "
809 "authorization type '%s'.",
810 smartlist_len(service
->clients
),
811 service
->auth_type
== REND_BASIC_AUTH
? 512 : 16,
812 service
->auth_type
== REND_BASIC_AUTH
? "basic" : "stealth");
818 /* Validate the service just parsed. */
819 if (rend_validate_service(rend_service_staging_list
, service
) < 0) {
820 /* Service is in the staging list so don't try to free it. */
824 /* Add it to the temporary list which we will use to prune our current
825 * list if any after configuring all services. */
826 if (rend_add_service(rend_service_staging_list
, service
) < 0) {
827 /* The object has been freed on error already. */
834 rend_service_free(service
);
838 /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
839 * client authorization <b>auth_type</b> and an optional list of
840 * rend_authorized_client_t in <b>auth_clients</b>, with
841 * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
842 * and circuit closure on max streams being exceeded set by
843 * <b>max_streams_close_circuit</b>.
845 * Ownership of pk, ports, and auth_clients is passed to this routine.
846 * Regardless of success/failure, callers should not touch these values
847 * after calling this routine, and may assume that correct cleanup has
848 * been done on failure.
850 * Return an appropriate rend_service_add_ephemeral_status_t.
852 rend_service_add_ephemeral_status_t
853 rend_service_add_ephemeral(crypto_pk_t
*pk
,
855 int max_streams_per_circuit
,
856 int max_streams_close_circuit
,
857 rend_auth_type_t auth_type
,
858 smartlist_t
*auth_clients
,
859 char **service_id_out
)
861 *service_id_out
= NULL
;
862 /* Allocate the service structure, and initialize the key, and key derived
865 rend_service_t
*s
= tor_malloc_zero(sizeof(rend_service_t
));
866 s
->directory
= NULL
; /* This indicates the service is ephemeral. */
868 s
->auth_type
= auth_type
;
869 s
->clients
= auth_clients
;
871 s
->intro_period_started
= time(NULL
);
872 s
->n_intro_points_wanted
= NUM_INTRO_POINTS_DEFAULT
;
873 s
->max_streams_per_circuit
= max_streams_per_circuit
;
874 s
->max_streams_close_circuit
= max_streams_close_circuit
;
875 if (rend_service_derive_key_digests(s
) < 0) {
876 rend_service_free(s
);
877 return RSAE_BADPRIVKEY
;
880 if (!s
->ports
|| smartlist_len(s
->ports
) == 0) {
881 log_warn(LD_CONFIG
, "At least one VIRTPORT/TARGET must be specified.");
882 rend_service_free(s
);
883 return RSAE_BADVIRTPORT
;
885 if (s
->auth_type
!= REND_NO_AUTH
&&
886 (!s
->clients
|| smartlist_len(s
->clients
) == 0)) {
887 log_warn(LD_CONFIG
, "At least one authorized client must be specified.");
888 rend_service_free(s
);
892 /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
893 * it's not, see #14828.
895 if (rend_service_get_by_pk_digest(s
->pk_digest
)) {
896 log_warn(LD_CONFIG
, "Onion Service private key collides with an "
897 "existing service.");
898 rend_service_free(s
);
899 return RSAE_ADDREXISTS
;
901 if (rend_service_get_by_service_id(s
->service_id
)) {
902 log_warn(LD_CONFIG
, "Onion Service id collides with an existing service.");
903 rend_service_free(s
);
904 return RSAE_ADDREXISTS
;
907 /* Initialize the service. */
908 if (rend_add_service(NULL
, s
)) {
909 return RSAE_INTERNAL
;
911 *service_id_out
= tor_strdup(s
->service_id
);
913 log_debug(LD_CONFIG
, "Added ephemeral Onion Service: %s", s
->service_id
);
917 /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
918 * success, and -1 on failure.
921 rend_service_del_ephemeral(const char *service_id
)
924 if (!rend_valid_v2_service_id(service_id
)) {
925 log_warn(LD_CONFIG
, "Requested malformed Onion Service id for removal.");
928 if ((s
= rend_service_get_by_service_id(service_id
)) == NULL
) {
929 log_warn(LD_CONFIG
, "Requested non-existent Onion Service id for "
933 if (!rend_service_is_ephemeral(s
)) {
934 log_warn(LD_CONFIG
, "Requested non-ephemeral Onion Service for removal.");
938 /* Kill the intro point circuit for the Onion Service, and remove it from
939 * the list. Closing existing connections is the application's problem.
941 * XXX: As with the comment in rend_config_services(), a nice abstraction
942 * would be ideal here, but for now just duplicate the code.
944 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
945 if (!circ
->marked_for_close
&&
946 (circ
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
947 circ
->purpose
== CIRCUIT_PURPOSE_S_INTRO
)) {
948 origin_circuit_t
*oc
= TO_ORIGIN_CIRCUIT(circ
);
949 if (oc
->rend_data
== NULL
||
950 !rend_circuit_pk_digest_eq(oc
, (uint8_t *) s
->pk_digest
)) {
953 log_debug(LD_REND
, "Closing intro point %s for service %s.",
954 safe_str_client(extend_info_describe(
955 oc
->build_state
->chosen_exit
)),
956 rend_data_get_address(oc
->rend_data
));
957 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
959 } SMARTLIST_FOREACH_END(circ
);
960 smartlist_remove(rend_service_list
, s
);
961 rend_service_free(s
);
963 log_debug(LD_CONFIG
, "Removed ephemeral Onion Service: %s", service_id
);
968 /* There can be 1 second's delay due to second_elapsed_callback, and perhaps
969 * another few seconds due to blocking calls. */
970 #define INTRO_CIRC_RETRY_PERIOD_SLOP 10
972 /** Log information about the intro point creation rate and current intro
973 * points for service, upgrading the log level from min_severity to warn if
974 * we have stopped launching new intro point circuits. */
976 rend_log_intro_limit(const rend_service_t
*service
, int min_severity
)
978 int exceeded_limit
= (service
->n_intro_circuits_launched
>=
979 rend_max_intro_circs_per_period(
980 service
->n_intro_points_wanted
));
981 int severity
= min_severity
;
982 /* We stopped creating circuits */
983 if (exceeded_limit
) {
986 time_t intro_period_elapsed
= time(NULL
) - service
->intro_period_started
;
987 tor_assert_nonfatal(intro_period_elapsed
>= 0);
990 static ratelim_t rlimit
= RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD
);
991 if ((msg
= rate_limit_log(&rlimit
, approx_time()))) {
992 log_fn(severity
, LD_REND
,
993 "Hidden service %s %s %d intro points in the last %d seconds. "
994 "Intro circuit launches are limited to %d per %d seconds.%s",
996 exceeded_limit
? "exceeded launch limit with" : "launched",
997 service
->n_intro_circuits_launched
,
998 (int)intro_period_elapsed
,
999 rend_max_intro_circs_per_period(service
->n_intro_points_wanted
),
1000 INTRO_CIRC_RETRY_PERIOD
, msg
);
1001 rend_service_dump_stats(severity
);
1007 /** Replace the old value of <b>service</b>-\>desc with one that reflects
1008 * the other fields in service.
1011 rend_service_update_descriptor(rend_service_t
*service
)
1013 rend_service_descriptor_t
*d
;
1016 rend_service_descriptor_free(service
->desc
);
1017 service
->desc
= NULL
;
1019 d
= service
->desc
= tor_malloc_zero(sizeof(rend_service_descriptor_t
));
1020 d
->pk
= crypto_pk_dup_key(service
->private_key
);
1021 d
->timestamp
= time(NULL
);
1022 d
->timestamp
-= d
->timestamp
% 3600; /* Round down to nearest hour */
1023 d
->intro_nodes
= smartlist_new();
1024 /* Support intro protocols 2 and 3. */
1025 d
->protocols
= (1 << 2) + (1 << 3);
1027 for (i
= 0; i
< smartlist_len(service
->intro_nodes
); ++i
) {
1028 rend_intro_point_t
*intro_svc
= smartlist_get(service
->intro_nodes
, i
);
1029 rend_intro_point_t
*intro_desc
;
1031 /* This intro point won't be listed in the descriptor... */
1032 intro_svc
->listed_in_last_desc
= 0;
1034 /* circuit_established is set in rend_service_intro_established(), and
1035 * checked every second in rend_consider_services_intro_points(), so it's
1036 * safe to use it here */
1037 if (!intro_svc
->circuit_established
) {
1041 /* ...unless this intro point is listed in the descriptor. */
1042 intro_svc
->listed_in_last_desc
= 1;
1044 /* We have an entirely established intro circuit. Publish it in
1045 * our descriptor. */
1046 intro_desc
= tor_malloc_zero(sizeof(rend_intro_point_t
));
1047 intro_desc
->extend_info
= extend_info_dup(intro_svc
->extend_info
);
1048 if (intro_svc
->intro_key
)
1049 intro_desc
->intro_key
= crypto_pk_dup_key(intro_svc
->intro_key
);
1050 smartlist_add(d
->intro_nodes
, intro_desc
);
1052 if (intro_svc
->time_published
== -1) {
1053 /* We are publishing this intro point in a descriptor for the
1054 * first time -- note the current time in the service's copy of
1055 * the intro point. */
1056 intro_svc
->time_published
= time(NULL
);
1060 /* Check that we have the right number of intro points */
1061 unsigned int have_intro
= (unsigned int)smartlist_len(d
->intro_nodes
);
1062 if (have_intro
!= service
->n_intro_points_wanted
) {
1064 /* Getting less than we wanted or more than we're allowed is serious */
1065 if (have_intro
< service
->n_intro_points_wanted
||
1066 have_intro
> NUM_INTRO_POINTS_MAX
) {
1067 severity
= LOG_WARN
;
1069 /* Getting more than we wanted is weird, but less of a problem */
1070 severity
= LOG_NOTICE
;
1072 log_fn(severity
, LD_REND
, "Hidden service %s wanted %d intro points, but "
1073 "descriptor was updated with %d instead.",
1074 service
->service_id
,
1075 service
->n_intro_points_wanted
, have_intro
);
1076 /* Now log an informative message about how we might have got here. */
1077 rend_log_intro_limit(service
, severity
);
1081 /* Allocate and return a string containing the path to file_name in
1082 * service->directory. Asserts that service has a directory.
1083 * This function will never return NULL.
1084 * The caller must free this path. */
1086 rend_service_path(const rend_service_t
*service
, const char *file_name
)
1088 tor_assert(service
->directory
);
1089 return hs_path_from_filename(service
->directory
, file_name
);
1092 /* Allocate and return a string containing the path to the single onion
1093 * service poison file in service->directory. Asserts that service has a
1095 * The caller must free this path. */
1097 rend_service_sos_poison_path(const rend_service_t
*service
)
1099 return rend_service_path(service
, sos_poison_fname
);
1102 /** Return True if hidden services <b>service</b> has been poisoned by single
1105 service_is_single_onion_poisoned(const rend_service_t
*service
)
1107 char *poison_fname
= NULL
;
1108 file_status_t fstatus
;
1110 /* Passing a NULL service is a bug */
1111 if (BUG(!service
)) {
1115 if (rend_service_is_ephemeral(service
)) {
1119 poison_fname
= rend_service_sos_poison_path(service
);
1121 fstatus
= file_status(poison_fname
);
1122 tor_free(poison_fname
);
1124 /* If this fname is occupied, the hidden service has been poisoned.
1125 * fstatus can be FN_ERROR if the service directory does not exist, in that
1126 * case, there is obviously no private key. */
1127 if (fstatus
== FN_FILE
|| fstatus
== FN_EMPTY
) {
1134 /* Return 1 if the private key file for service exists and has a non-zero size,
1135 * and 0 otherwise. */
1137 rend_service_private_key_exists(const rend_service_t
*service
)
1139 char *private_key_path
= rend_service_path(service
, private_key_fname
);
1140 const file_status_t private_key_status
= file_status(private_key_path
);
1141 tor_free(private_key_path
);
1142 /* Only non-empty regular private key files could have been used before.
1143 * fstatus can be FN_ERROR if the service directory does not exist, in that
1144 * case, there is obviously no private key. */
1145 return private_key_status
== FN_FILE
;
1148 /** Check the single onion service poison state of the directory for s:
1149 * - If the service is poisoned, and we are in Single Onion Mode,
1151 * - If the service is not poisoned, and we are not in Single Onion Mode,
1153 * - Otherwise, the poison state is invalid: the service was created in one
1154 * mode, and is being used in the other, return -1.
1155 * Hidden service directories without keys are always considered consistent.
1156 * They will be poisoned after their directory is created (if needed). */
1158 rend_service_verify_single_onion_poison(const rend_service_t
* s
,
1159 const or_options_t
* options
)
1161 /* Passing a NULL service is a bug */
1166 /* Ephemeral services are checked at ADD_ONION time */
1167 if (BUG(rend_service_is_ephemeral(s
))) {
1171 /* Service is expected to have a directory */
1172 if (BUG(!s
->directory
)) {
1176 /* Services without keys are always ok - their keys will only ever be used
1177 * in the current mode */
1178 if (!rend_service_private_key_exists(s
)) {
1182 /* The key has been used before in a different mode */
1183 if (service_is_single_onion_poisoned(s
) !=
1184 rend_service_non_anonymous_mode_enabled(options
)) {
1188 /* The key exists and is consistent with the current mode */
1192 /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
1193 * the hidden service directory for s that marks it as a single onion service.
1194 * Tor must be in single onion mode before calling this function, and the
1195 * service directory must already have been created.
1196 * Returns 0 when a directory is successfully poisoned, or if it is already
1197 * poisoned. Returns -1 on a failure to read the directory or write the poison
1198 * file, or if there is an existing private key file in the directory. (The
1199 * service should have been poisoned when the key was created.) */
1201 poison_new_single_onion_hidden_service_dir_impl(const rend_service_t
*service
,
1202 const or_options_t
* options
)
1204 /* Passing a NULL service is a bug */
1205 if (BUG(!service
)) {
1209 /* We must only poison directories if we're in Single Onion mode */
1210 tor_assert(rend_service_non_anonymous_mode_enabled(options
));
1214 char *poison_fname
= NULL
;
1216 if (rend_service_is_ephemeral(service
)) {
1217 log_info(LD_REND
, "Ephemeral HS started in non-anonymous mode.");
1221 /* Make sure we're only poisoning new hidden service directories */
1222 if (rend_service_private_key_exists(service
)) {
1223 log_warn(LD_BUG
, "Tried to single onion poison a service directory after "
1224 "the private key was created.");
1228 /* Make sure the directory was created before calling this function. */
1229 if (BUG(hs_check_service_private_dir(options
->User
, service
->directory
,
1230 service
->dir_group_readable
, 0) < 0))
1233 poison_fname
= rend_service_sos_poison_path(service
);
1235 switch (file_status(poison_fname
)) {
1238 log_warn(LD_FS
, "Can't read single onion poison file \"%s\"",
1241 case FN_FILE
: /* single onion poison file already exists. NOP. */
1242 case FN_EMPTY
: /* single onion poison file already exists. NOP. */
1243 log_debug(LD_FS
, "Tried to re-poison a single onion poisoned file \"%s\"",
1247 fd
= tor_open_cloexec(poison_fname
, O_RDWR
|O_CREAT
|O_TRUNC
, 0600);
1249 log_warn(LD_FS
, "Could not create single onion poison file %s",
1262 tor_free(poison_fname
);
1267 /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
1268 * hidden services. If s is new, we should mark its hidden service
1269 * directory appropriately so that it is never launched as a location-private
1270 * hidden service. (New directories don't have private key files.)
1271 * Return 0 on success, -1 on fail. */
1273 rend_service_poison_new_single_onion_dir(const rend_service_t
*s
,
1274 const or_options_t
* options
)
1276 /* Passing a NULL service is a bug */
1281 /* We must only poison directories if we're in Single Onion mode */
1282 tor_assert(rend_service_non_anonymous_mode_enabled(options
));
1284 /* Ephemeral services aren't allowed in non-anonymous mode */
1285 if (BUG(rend_service_is_ephemeral(s
))) {
1289 /* Service is expected to have a directory */
1290 if (BUG(!s
->directory
)) {
1294 if (!rend_service_private_key_exists(s
)) {
1295 if (poison_new_single_onion_hidden_service_dir_impl(s
, options
)
1304 /** Load and/or generate private keys for all hidden services, possibly
1305 * including keys for client authorization.
1306 * If a <b>service_list</b> is provided, treat it as the list of hidden
1307 * services (used in unittests). Otherwise, require that rend_service_list is
1309 * Return 0 on success, -1 on failure. */
1311 rend_service_load_all_keys(const smartlist_t
*service_list
)
1313 /* Use service_list for unit tests */
1314 const smartlist_t
*s_list
= rend_get_service_list(service_list
);
1319 SMARTLIST_FOREACH_BEGIN(s_list
, rend_service_t
*, s
) {
1322 log_info(LD_REND
, "Loading hidden-service keys from %s",
1323 rend_service_escaped_dir(s
));
1325 if (rend_service_load_keys(s
) < 0)
1327 } SMARTLIST_FOREACH_END(s
);
1332 /** Add to <b>lst</b> every filename used by <b>s</b>. */
1334 rend_service_add_filenames_to_list(smartlist_t
*lst
, const rend_service_t
*s
)
1338 tor_assert(s
->directory
);
1339 smartlist_add(lst
, rend_service_path(s
, private_key_fname
));
1340 smartlist_add(lst
, rend_service_path(s
, hostname_fname
));
1341 smartlist_add(lst
, rend_service_path(s
, client_keys_fname
));
1342 smartlist_add(lst
, rend_service_sos_poison_path(s
));
1345 /** Add to <b>open_lst</b> every filename used by a configured hidden service,
1346 * and to <b>stat_lst</b> every directory used by a configured hidden
1349 rend_services_add_filenames_to_lists(smartlist_t
*open_lst
,
1350 smartlist_t
*stat_lst
)
1352 if (!rend_service_list
)
1354 SMARTLIST_FOREACH_BEGIN(rend_service_list
, rend_service_t
*, s
) {
1355 if (!rend_service_is_ephemeral(s
)) {
1356 rend_service_add_filenames_to_list(open_lst
, s
);
1357 smartlist_add_strdup(stat_lst
, s
->directory
);
1359 } SMARTLIST_FOREACH_END(s
);
1362 /** Derive all rend_service_t internal material based on the service's key.
1363 * Returns 0 on sucess, -1 on failure.
1366 rend_service_derive_key_digests(struct rend_service_t
*s
)
1368 if (rend_get_service_id(s
->private_key
, s
->service_id
)<0) {
1369 log_warn(LD_BUG
, "Internal error: couldn't encode service ID.");
1372 if (crypto_pk_get_digest(s
->private_key
, s
->pk_digest
)<0) {
1373 log_warn(LD_BUG
, "Couldn't compute hash of public key.");
1380 /** Make sure that the directory for <b>s</b> is private, using the config in
1382 * If <b>create</b> is true:
1383 * - if the directory exists, change permissions if needed,
1384 * - if the directory does not exist, create it with the correct permissions.
1385 * If <b>create</b> is false:
1386 * - if the directory exists, check permissions,
1387 * - if the directory does not exist, check if we think we can create it.
1388 * Return 0 on success, -1 on failure. */
1390 rend_service_check_private_dir(const or_options_t
*options
,
1391 const rend_service_t
*s
,
1394 /* Passing a NULL service is a bug */
1399 /* Check/create directory */
1400 if (hs_check_service_private_dir(options
->User
, s
->directory
,
1401 s
->dir_group_readable
, create
) < 0) {
1405 /* Check if the hidden service key exists, and was created in a different
1406 * single onion service mode, and refuse to launch if it has.
1407 * This is safe to call even when create is false, as it ignores missing
1408 * keys and directories: they are always valid.
1410 if (rend_service_verify_single_onion_poison(s
, options
) < 0) {
1411 /* We can't use s->service_id here, as the key may not have been loaded */
1412 log_warn(LD_GENERAL
, "We are configured with "
1413 "HiddenServiceNonAnonymousMode %d, but the hidden "
1414 "service key in directory %s was created in %s mode. "
1415 "This is not allowed.",
1416 rend_service_non_anonymous_mode_enabled(options
) ? 1 : 0,
1417 rend_service_escaped_dir(s
),
1418 rend_service_non_anonymous_mode_enabled(options
) ?
1419 "an anonymous" : "a non-anonymous"
1424 /* Poison new single onion directories immediately after they are created,
1425 * so that we never accidentally launch non-anonymous hidden services
1426 * thinking they are anonymous. Any keys created later will end up with the
1427 * correct poisoning state.
1429 if (create
&& rend_service_non_anonymous_mode_enabled(options
)) {
1430 static int logged_warning
= 0;
1432 if (rend_service_poison_new_single_onion_dir(s
, options
) < 0) {
1433 log_warn(LD_GENERAL
,"Failed to mark new hidden services as non-anonymous"
1438 if (!logged_warning
) {
1439 /* The keys for these services are linked to the server IP address */
1440 log_notice(LD_REND
, "The configured onion service directories have been "
1441 "used in single onion mode. They can not be used for "
1442 "anonymous hidden services.");
1450 /** Load and/or generate private keys for the hidden service <b>s</b>,
1451 * possibly including keys for client authorization. Return 0 on success, -1
1454 rend_service_load_keys(rend_service_t
*s
)
1459 /* Create the directory if needed which will also poison it in case of
1460 * single onion service. */
1461 if (rend_service_check_private_dir(get_options(), s
, 1) < 0)
1465 fname
= rend_service_path(s
, private_key_fname
);
1466 s
->private_key
= init_key_from_file(fname
, 1, LOG_ERR
, 0);
1468 if (!s
->private_key
)
1471 if (rend_service_derive_key_digests(s
) < 0)
1475 /* Create service file */
1476 fname
= rend_service_path(s
, hostname_fname
);
1478 tor_snprintf(buf
, sizeof(buf
),"%s.onion\n", s
->service_id
);
1479 if (write_str_to_file(fname
,buf
,0)<0) {
1480 log_warn(LD_CONFIG
, "Could not write onion address to hostname file.");
1484 if (s
->dir_group_readable
) {
1485 /* Also verify hostname file created with group read. */
1486 if (chmod(fname
, 0640))
1487 log_warn(LD_FS
,"Unable to make hidden hostname file %s group-readable.",
1490 #endif /* !defined(_WIN32) */
1492 /* If client authorization is configured, load or generate keys. */
1493 if (s
->auth_type
!= REND_NO_AUTH
) {
1494 if (rend_service_load_auth_keys(s
, fname
) < 0) {
1504 memwipe(buf
, 0, sizeof(buf
));
1509 /** Load and/or generate client authorization keys for the hidden service
1510 * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
1513 rend_service_load_auth_keys(rend_service_t
*s
, const char *hfname
)
1516 char *cfname
= NULL
;
1517 char *client_keys_str
= NULL
;
1518 strmap_t
*parsed_clients
= strmap_new();
1519 FILE *cfile
, *hfile
;
1520 open_file_t
*open_cfile
= NULL
, *open_hfile
= NULL
;
1521 char desc_cook_out
[3*REND_DESC_COOKIE_LEN_BASE64
+1];
1522 char service_id
[16+1];
1525 /* Load client keys and descriptor cookies, if available. */
1526 cfname
= rend_service_path(s
, client_keys_fname
);
1527 client_keys_str
= read_file_to_str(cfname
, RFTS_IGNORE_MISSING
, NULL
);
1528 if (client_keys_str
) {
1529 if (rend_parse_client_keys(parsed_clients
, client_keys_str
) < 0) {
1530 log_warn(LD_CONFIG
, "Previously stored client_keys file could not "
1534 log_info(LD_CONFIG
, "Parsed %d previously stored client entries.",
1535 strmap_size(parsed_clients
));
1539 /* Prepare client_keys and hostname files. */
1540 if (!(cfile
= start_writing_to_stdio_file(cfname
,
1541 OPEN_FLAGS_REPLACE
| O_TEXT
,
1542 0600, &open_cfile
))) {
1543 log_warn(LD_CONFIG
, "Could not open client_keys file %s",
1548 if (!(hfile
= start_writing_to_stdio_file(hfname
,
1549 OPEN_FLAGS_REPLACE
| O_TEXT
,
1550 0600, &open_hfile
))) {
1551 log_warn(LD_CONFIG
, "Could not open hostname file %s", escaped(hfname
));
1555 /* Either use loaded keys for configured clients or generate new
1556 * ones if a client is new. */
1557 SMARTLIST_FOREACH_BEGIN(s
->clients
, rend_authorized_client_t
*, client
) {
1558 rend_authorized_client_t
*parsed
=
1559 strmap_get(parsed_clients
, client
->client_name
);
1562 /* Copy descriptor cookie from parsed entry or create new one. */
1564 memcpy(client
->descriptor_cookie
, parsed
->descriptor_cookie
,
1565 REND_DESC_COOKIE_LEN
);
1567 crypto_rand((char *) client
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
1569 /* For compatibility with older tor clients, this does not
1570 * truncate the padding characters, unlike rend_auth_encode_cookie. */
1571 if (base64_encode(desc_cook_out
, 3*REND_DESC_COOKIE_LEN_BASE64
+1,
1572 (char *) client
->descriptor_cookie
,
1573 REND_DESC_COOKIE_LEN
, 0) < 0) {
1574 log_warn(LD_BUG
, "Could not base64-encode descriptor cookie.");
1577 /* Copy client key from parsed entry or create new one if required. */
1578 if (parsed
&& parsed
->client_key
) {
1579 client
->client_key
= crypto_pk_dup_key(parsed
->client_key
);
1580 } else if (s
->auth_type
== REND_STEALTH_AUTH
) {
1581 /* Create private key for client. */
1582 crypto_pk_t
*prkey
= NULL
;
1583 if (!(prkey
= crypto_pk_new())) {
1584 log_warn(LD_BUG
,"Error constructing client key");
1587 if (crypto_pk_generate_key(prkey
)) {
1588 log_warn(LD_BUG
,"Error generating client key");
1589 crypto_pk_free(prkey
);
1592 if (crypto_pk_check_key(prkey
) <= 0) {
1593 log_warn(LD_BUG
,"Generated client key seems invalid");
1594 crypto_pk_free(prkey
);
1597 client
->client_key
= prkey
;
1599 /* Add entry to client_keys file. */
1600 written
= tor_snprintf(buf
, sizeof(buf
),
1601 "client-name %s\ndescriptor-cookie %s\n",
1602 client
->client_name
, desc_cook_out
);
1604 log_warn(LD_BUG
, "Could not write client entry.");
1607 if (client
->client_key
) {
1608 char *client_key_out
= NULL
;
1609 if (crypto_pk_write_private_key_to_string(client
->client_key
,
1610 &client_key_out
, &len
) != 0) {
1611 log_warn(LD_BUG
, "Internal error: "
1612 "crypto_pk_write_private_key_to_string() failed.");
1615 if (rend_get_service_id(client
->client_key
, service_id
)<0) {
1616 log_warn(LD_BUG
, "Internal error: couldn't encode service ID.");
1618 * len is string length, not buffer length, but last byte is NUL
1621 memwipe(client_key_out
, 0, len
);
1622 tor_free(client_key_out
);
1625 written
= tor_snprintf(buf
+ written
, sizeof(buf
) - written
,
1626 "client-key\n%s", client_key_out
);
1627 memwipe(client_key_out
, 0, len
);
1628 tor_free(client_key_out
);
1630 log_warn(LD_BUG
, "Could not write client entry.");
1634 strlcpy(service_id
, s
->service_id
, sizeof(service_id
));
1637 if (fputs(buf
, cfile
) < 0) {
1638 log_warn(LD_FS
, "Could not append client entry to file: %s",
1643 /* Add line to hostname file. This is not the same encoding as in
1645 char *encoded_cookie
= rend_auth_encode_cookie(client
->descriptor_cookie
,
1647 if (!encoded_cookie
) {
1648 log_warn(LD_BUG
, "Could not base64-encode descriptor cookie.");
1651 tor_snprintf(buf
, sizeof(buf
), "%s.onion %s # client: %s\n",
1652 service_id
, encoded_cookie
, client
->client_name
);
1653 memwipe(encoded_cookie
, 0, strlen(encoded_cookie
));
1654 tor_free(encoded_cookie
);
1656 if (fputs(buf
, hfile
)<0) {
1657 log_warn(LD_FS
, "Could not append host entry to file: %s",
1661 } SMARTLIST_FOREACH_END(client
);
1663 finish_writing_to_file(open_cfile
);
1664 finish_writing_to_file(open_hfile
);
1670 abort_writing_to_file(open_cfile
);
1672 abort_writing_to_file(open_hfile
);
1674 if (client_keys_str
) {
1675 memwipe(client_keys_str
, 0, strlen(client_keys_str
));
1676 tor_free(client_keys_str
);
1678 strmap_free(parsed_clients
, rend_authorized_client_strmap_item_free
);
1681 memwipe(cfname
, 0, strlen(cfname
));
1685 /* Clear stack buffers that held key-derived material. */
1686 memwipe(buf
, 0, sizeof(buf
));
1687 memwipe(desc_cook_out
, 0, sizeof(desc_cook_out
));
1688 memwipe(service_id
, 0, sizeof(service_id
));
1693 /** Return the service whose public key has a digest of <b>digest</b>, or
1694 * NULL if no such service exists.
1696 static rend_service_t
*
1697 rend_service_get_by_pk_digest(const char* digest
)
1699 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, s
,
1700 if (tor_memeq(s
->pk_digest
,digest
,DIGEST_LEN
))
1705 /** Return the service whose service id is <b>id</b>, or NULL if no such
1708 static struct rend_service_t
*
1709 rend_service_get_by_service_id(const char *id
)
1711 tor_assert(strlen(id
) == REND_SERVICE_ID_LEN_BASE32
);
1712 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, s
, {
1713 if (tor_memeq(s
->service_id
, id
, REND_SERVICE_ID_LEN_BASE32
))
1719 /** Check client authorization of a given <b>descriptor_cookie</b> of
1720 * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
1721 * and 0 for failure. */
1723 rend_check_authorization(rend_service_t
*service
,
1724 const char *descriptor_cookie
,
1727 rend_authorized_client_t
*auth_client
= NULL
;
1728 tor_assert(service
);
1729 tor_assert(descriptor_cookie
);
1730 if (!service
->clients
) {
1731 log_warn(LD_BUG
, "Can't check authorization for a service that has no "
1732 "authorized clients configured.");
1736 if (cookie_len
!= REND_DESC_COOKIE_LEN
) {
1737 log_info(LD_REND
, "Descriptor cookie is %lu bytes, but we expected "
1738 "%lu bytes. Dropping cell.",
1739 (unsigned long)cookie_len
, (unsigned long)REND_DESC_COOKIE_LEN
);
1743 /* Look up client authorization by descriptor cookie. */
1744 SMARTLIST_FOREACH(service
->clients
, rend_authorized_client_t
*, client
, {
1745 if (tor_memeq(client
->descriptor_cookie
, descriptor_cookie
,
1746 REND_DESC_COOKIE_LEN
)) {
1747 auth_client
= client
;
1752 char descriptor_cookie_base64
[3*REND_DESC_COOKIE_LEN_BASE64
];
1753 base64_encode(descriptor_cookie_base64
, sizeof(descriptor_cookie_base64
),
1754 descriptor_cookie
, REND_DESC_COOKIE_LEN
, 0);
1755 log_info(LD_REND
, "No authorization found for descriptor cookie '%s'! "
1757 descriptor_cookie_base64
);
1761 /* Allow the request. */
1762 log_info(LD_REND
, "Client %s authorized for service %s.",
1763 auth_client
->client_name
, service
->service_id
);
1767 /* Can this service make a direct connection to ei?
1768 * It must be a single onion service, and the firewall rules must allow ei. */
1770 rend_service_use_direct_connection(const or_options_t
* options
,
1771 const extend_info_t
* ei
)
1773 /* We'll connect directly all reachable addresses, whether preferred or not.
1774 * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
1775 * ignored, because pref_only is 0. */
1776 return (rend_service_allow_non_anonymous_connection(options
) &&
1777 fascist_firewall_allows_address_addr(&ei
->addr
, ei
->port
,
1778 FIREWALL_OR_CONNECTION
, 0, 0));
1781 /* Like rend_service_use_direct_connection, but to a node. */
1783 rend_service_use_direct_connection_node(const or_options_t
* options
,
1786 /* We'll connect directly all reachable addresses, whether preferred or not.
1788 return (rend_service_allow_non_anonymous_connection(options
) &&
1789 fascist_firewall_allows_node(node
, FIREWALL_OR_CONNECTION
, 0));
1796 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
1800 rend_service_receive_introduction(origin_circuit_t
*circuit
,
1801 const uint8_t *request
,
1804 /* Global status stuff */
1805 int status
= 0, result
;
1806 const or_options_t
*options
= get_options();
1807 char *err_msg
= NULL
;
1808 int err_msg_severity
= LOG_WARN
;
1809 const char *stage_descr
= NULL
, *rend_pk_digest
;
1810 int reason
= END_CIRC_REASON_TORPROTOCOL
;
1811 /* Service/circuit/key stuff we can learn before parsing */
1812 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
1813 rend_service_t
*service
= NULL
;
1814 rend_intro_point_t
*intro_point
= NULL
;
1815 crypto_pk_t
*intro_key
= NULL
;
1817 rend_intro_cell_t
*parsed_req
= NULL
;
1818 /* Rendezvous point */
1819 extend_info_t
*rp
= NULL
;
1820 /* XXX not handled yet */
1821 char buf
[RELAY_PAYLOAD_SIZE
];
1822 char keys
[DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
]; /* Holds KH, Df, Db, Kf, Kb */
1824 crypto_dh_t
*dh
= NULL
;
1825 origin_circuit_t
*launched
= NULL
;
1826 crypt_path_t
*cpath
= NULL
;
1828 int circ_needs_uptime
;
1829 time_t now
= time(NULL
);
1833 /* Do some initial validation and logging before we parse the cell */
1834 if (circuit
->base_
.purpose
!= CIRCUIT_PURPOSE_S_INTRO
) {
1835 log_warn(LD_PROTOCOL
,
1836 "Got an INTRODUCE2 over a non-introduction circuit %u.",
1837 (unsigned) circuit
->base_
.n_circ_id
);
1841 assert_circ_anonymity_ok(circuit
, options
);
1842 tor_assert(circuit
->rend_data
);
1843 /* XXX: This is version 2 specific (only one supported). */
1844 rend_pk_digest
= (char *) rend_data_get_pk_digest(circuit
->rend_data
, NULL
);
1846 /* We'll use this in a bazillion log messages */
1847 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
1848 rend_pk_digest
, REND_SERVICE_ID_LEN
);
1850 /* look up service depending on circuit. */
1851 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
1854 "Internal error: Got an INTRODUCE2 cell on an intro "
1855 "circ for an unrecognized service %s.",
1856 escaped(serviceid
));
1860 intro_point
= find_intro_point(circuit
);
1861 if (intro_point
== NULL
) {
1862 intro_point
= find_expiring_intro_point(service
, circuit
);
1863 if (intro_point
== NULL
) {
1865 "Internal error: Got an INTRODUCE2 cell on an "
1866 "intro circ (for service %s) with no corresponding "
1867 "rend_intro_point_t.",
1868 escaped(serviceid
));
1873 log_info(LD_REND
, "Received INTRODUCE2 cell for service %s on circ %u.",
1874 escaped(serviceid
), (unsigned)circuit
->base_
.n_circ_id
);
1876 /* use intro key instead of service key. */
1877 intro_key
= circuit
->intro_key
;
1882 stage_descr
= "early parsing";
1883 /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
1885 rend_service_begin_parse_intro(request
, request_len
, 2, &err_msg
);
1888 } else if (err_msg
) {
1889 log_info(LD_REND
, "%s on circ %u.", err_msg
,
1890 (unsigned)circuit
->base_
.n_circ_id
);
1894 /* make sure service replay caches are present */
1895 if (!service
->accepted_intro_dh_parts
) {
1896 service
->accepted_intro_dh_parts
=
1897 replaycache_new(REND_REPLAY_TIME_INTERVAL
,
1898 REND_REPLAY_TIME_INTERVAL
);
1901 if (!intro_point
->accepted_intro_rsa_parts
) {
1902 intro_point
->accepted_intro_rsa_parts
= replaycache_new(0, 0);
1905 /* check for replay of PK-encrypted portion. */
1906 replay
= replaycache_add_test_and_elapsed(
1907 intro_point
->accepted_intro_rsa_parts
,
1908 parsed_req
->ciphertext
, parsed_req
->ciphertext_len
,
1913 "Possible replay detected! We received an "
1914 "INTRODUCE2 cell with same PK-encrypted part %d "
1915 "seconds ago. Dropping cell.",
1920 stage_descr
= "decryption";
1921 /* Now try to decrypt it */
1922 result
= rend_service_decrypt_intro(parsed_req
, intro_key
, &err_msg
);
1925 } else if (err_msg
) {
1926 log_info(LD_REND
, "%s on circ %u.", err_msg
,
1927 (unsigned)circuit
->base_
.n_circ_id
);
1931 stage_descr
= "late parsing";
1932 /* Parse the plaintext */
1933 result
= rend_service_parse_intro_plaintext(parsed_req
, &err_msg
);
1936 } else if (err_msg
) {
1937 log_info(LD_REND
, "%s on circ %u.", err_msg
,
1938 (unsigned)circuit
->base_
.n_circ_id
);
1942 stage_descr
= "late validation";
1943 /* Validate the parsed plaintext parts */
1944 result
= rend_service_validate_intro_late(parsed_req
, &err_msg
);
1947 } else if (err_msg
) {
1948 log_info(LD_REND
, "%s on circ %u.", err_msg
,
1949 (unsigned)circuit
->base_
.n_circ_id
);
1954 /* Increment INTRODUCE2 counter */
1955 ++(intro_point
->accepted_introduce2_count
);
1957 /* Find the rendezvous point */
1958 rp
= find_rp_for_intro(parsed_req
, &err_msg
);
1960 err_msg_severity
= LOG_PROTOCOL_WARN
;
1964 /* Check if we'd refuse to talk to this router */
1965 if (options
->StrictNodes
&&
1966 routerset_contains_extendinfo(options
->ExcludeNodes
, rp
)) {
1967 log_warn(LD_REND
, "Client asked to rendezvous at a relay that we "
1968 "exclude, and StrictNodes is set. Refusing service.");
1969 reason
= END_CIRC_REASON_INTERNAL
; /* XXX might leak why we refused */
1973 base16_encode(hexcookie
, 9, (const char *)(parsed_req
->rc
), 4);
1975 /* Check whether there is a past request with the same Diffie-Hellman,
1977 replay
= replaycache_add_test_and_elapsed(
1978 service
->accepted_intro_dh_parts
,
1979 parsed_req
->dh
, DH_KEY_LEN
,
1983 /* A Tor client will send a new INTRODUCE1 cell with the same rend
1984 * cookie and DH public key as its previous one if its intro circ
1985 * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
1986 * If we received the first INTRODUCE1 cell (the intro-point relay
1987 * converts it into an INTRODUCE2 cell), we are already trying to
1988 * connect to that rend point (and may have already succeeded);
1989 * drop this cell. */
1990 log_info(LD_REND
, "We received an "
1991 "INTRODUCE2 cell with same first part of "
1992 "Diffie-Hellman handshake %d seconds ago. Dropping "
1998 /* If the service performs client authorization, check included auth data. */
1999 if (service
->clients
) {
2000 if (parsed_req
->version
== 3 && parsed_req
->u
.v3
.auth_len
> 0) {
2001 if (rend_check_authorization(service
,
2002 (const char*)parsed_req
->u
.v3
.auth_data
,
2003 parsed_req
->u
.v3
.auth_len
)) {
2004 log_info(LD_REND
, "Authorization data in INTRODUCE2 cell are valid.");
2006 log_info(LD_REND
, "The authorization data that are contained in "
2007 "the INTRODUCE2 cell are invalid. Dropping cell.");
2008 reason
= END_CIRC_REASON_CONNECTFAILED
;
2012 log_info(LD_REND
, "INTRODUCE2 cell does not contain authentication "
2013 "data, but we require client authorization. Dropping cell.");
2014 reason
= END_CIRC_REASON_CONNECTFAILED
;
2019 /* Try DH handshake... */
2020 dh
= crypto_dh_new(DH_TYPE_REND
);
2021 if (!dh
|| crypto_dh_generate_public(dh
)<0) {
2022 log_warn(LD_BUG
,"Internal error: couldn't build DH state "
2023 "or generate public key.");
2024 reason
= END_CIRC_REASON_INTERNAL
;
2027 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN
, dh
,
2028 (char *)(parsed_req
->dh
),
2030 DIGEST_LEN
+CPATH_KEY_MATERIAL_LEN
)<0) {
2031 log_warn(LD_BUG
, "Internal error: couldn't complete DH handshake");
2032 reason
= END_CIRC_REASON_INTERNAL
;
2036 circ_needs_uptime
= hs_service_requires_uptime_circ(service
->ports
);
2038 /* help predict this next time */
2039 rep_hist_note_used_internal(now
, circ_needs_uptime
, 1);
2041 /* Launch a circuit to the client's chosen rendezvous point.
2043 for (i
=0;i
<MAX_REND_FAILURES
;i
++) {
2044 int flags
= CIRCLAUNCH_NEED_CAPACITY
| CIRCLAUNCH_IS_INTERNAL
;
2045 if (circ_needs_uptime
) flags
|= CIRCLAUNCH_NEED_UPTIME
;
2046 /* A Single Onion Service only uses a direct connection if its
2047 * firewall rules permit direct connections to the address. */
2048 if (rend_service_use_direct_connection(options
, rp
)) {
2049 flags
= flags
| CIRCLAUNCH_ONEHOP_TUNNEL
;
2051 launched
= circuit_launch_by_extend_info(
2052 CIRCUIT_PURPOSE_S_CONNECT_REND
, rp
, flags
);
2057 if (!launched
) { /* give up */
2058 log_warn(LD_REND
, "Giving up launching first hop of circuit to rendezvous "
2059 "point %s for service %s.",
2060 safe_str_client(extend_info_describe(rp
)),
2062 reason
= END_CIRC_REASON_CONNECTFAILED
;
2066 "Accepted intro; launching circuit to %s "
2067 "(cookie %s) for service %s.",
2068 safe_str_client(extend_info_describe(rp
)),
2069 hexcookie
, serviceid
);
2070 tor_assert(launched
->build_state
);
2071 /* Fill in the circuit's state. */
2073 launched
->rend_data
=
2074 rend_data_service_create(service
->service_id
, rend_pk_digest
,
2075 parsed_req
->rc
, service
->auth_type
);
2077 launched
->build_state
->service_pending_final_cpath_ref
=
2078 tor_malloc_zero(sizeof(crypt_path_reference_t
));
2079 launched
->build_state
->service_pending_final_cpath_ref
->refcount
= 1;
2081 launched
->build_state
->service_pending_final_cpath_ref
->cpath
= cpath
=
2082 tor_malloc_zero(sizeof(crypt_path_t
));
2083 cpath
->magic
= CRYPT_PATH_MAGIC
;
2084 launched
->build_state
->expiry_time
= now
+ MAX_REND_TIMEOUT
;
2086 cpath
->rend_dh_handshake_state
= dh
;
2088 if (circuit_init_cpath_crypto(cpath
,
2089 keys
+DIGEST_LEN
, sizeof(keys
)-DIGEST_LEN
,
2092 memcpy(cpath
->rend_circ_nonce
, keys
, DIGEST_LEN
);
2099 tor_asprintf(&err_msg
,
2100 "unknown %s error for INTRODUCE2", stage_descr
);
2102 err_msg
= tor_strdup("unknown error for INTRODUCE2");
2106 log_fn(err_msg_severity
, LD_REND
, "%s on circ %u", err_msg
,
2107 (unsigned)circuit
->base_
.n_circ_id
);
2110 if (dh
) crypto_dh_free(dh
);
2112 circuit_mark_for_close(TO_CIRCUIT(launched
), reason
);
2117 memwipe(keys
, 0, sizeof(keys
));
2118 memwipe(buf
, 0, sizeof(buf
));
2119 memwipe(serviceid
, 0, sizeof(serviceid
));
2120 memwipe(hexcookie
, 0, sizeof(hexcookie
));
2122 /* Free the parsed cell */
2123 rend_service_free_intro(parsed_req
);
2126 extend_info_free(rp
);
2131 /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
2132 * return NULL and an error string if we can't. Return a newly allocated
2133 * extend_info_t* for the rendezvous point. */
2134 static extend_info_t
*
2135 find_rp_for_intro(const rend_intro_cell_t
*intro
,
2138 extend_info_t
*rp
= NULL
;
2139 char *err_msg
= NULL
;
2140 const char *rp_nickname
= NULL
;
2141 const node_t
*node
= NULL
;
2145 err_msg
= tor_strdup("Bad parameters to find_rp_for_intro()");
2150 if (intro
->version
== 0 || intro
->version
== 1) {
2151 rp_nickname
= (const char *)(intro
->u
.v0_v1
.rp
);
2153 node
= node_get_by_nickname(rp_nickname
, NNF_NO_WARN_UNNAMED
);
2156 tor_asprintf(&err_msg
,
2157 "Couldn't find router %s named in INTRODUCE2 cell",
2158 escaped_safe_str_client(rp_nickname
));
2164 /* Are we in single onion mode? */
2165 const int allow_direct
= rend_service_allow_non_anonymous_connection(
2167 rp
= extend_info_from_node(node
, allow_direct
);
2170 tor_asprintf(&err_msg
,
2171 "Couldn't build extend_info_t for router %s named "
2172 "in INTRODUCE2 cell",
2173 escaped_safe_str_client(rp_nickname
));
2178 } else if (intro
->version
== 2) {
2179 rp
= extend_info_dup(intro
->u
.v2
.extend_info
);
2180 } else if (intro
->version
== 3) {
2181 rp
= extend_info_dup(intro
->u
.v3
.extend_info
);
2184 tor_asprintf(&err_msg
,
2185 "Unknown version %d in INTRODUCE2 cell",
2186 (int)(intro
->version
));
2192 /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2193 * the other cases goto err. */
2196 /* Make sure the RP we are being asked to connect to is _not_ a private
2197 * address unless it's allowed. Let's avoid to build a circuit to our
2198 * second middle node and fail right after when extending to the RP. */
2199 if (!extend_info_addr_is_allowed(&rp
->addr
)) {
2201 tor_asprintf(&err_msg
,
2202 "Relay IP in INTRODUCE2 cell is private address.");
2204 extend_info_free(rp
);
2212 *err_msg_out
= err_msg
;
2220 /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
2221 * rend_service_parse_intro().
2224 rend_service_free_intro(rend_intro_cell_t
*request
)
2230 /* Free ciphertext */
2231 tor_free(request
->ciphertext
);
2232 request
->ciphertext_len
= 0;
2234 /* Have plaintext? */
2235 if (request
->plaintext
) {
2236 /* Zero it out just to be safe */
2237 memwipe(request
->plaintext
, 0, request
->plaintext_len
);
2238 tor_free(request
->plaintext
);
2239 request
->plaintext_len
= 0;
2242 /* Have parsed plaintext? */
2243 if (request
->parsed
) {
2244 switch (request
->version
) {
2248 * Nothing more to do; these formats have no further pointers
2253 extend_info_free(request
->u
.v2
.extend_info
);
2254 request
->u
.v2
.extend_info
= NULL
;
2257 if (request
->u
.v3
.auth_data
) {
2258 memwipe(request
->u
.v3
.auth_data
, 0, request
->u
.v3
.auth_len
);
2259 tor_free(request
->u
.v3
.auth_data
);
2262 extend_info_free(request
->u
.v3
.extend_info
);
2263 request
->u
.v3
.extend_info
= NULL
;
2267 "rend_service_free_intro() saw unknown protocol "
2273 /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2274 memwipe(request
, 0, sizeof(*request
));
2279 /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
2280 * rend_intro_cell_t structure. Free it with rend_service_free_intro()
2281 * when finished. The type parameter should be 1 or 2 to indicate whether
2282 * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
2283 * parts; after this, call rend_service_decrypt_intro() with a key, then
2284 * rend_service_parse_intro_plaintext() to finish parsing. The optional
2285 * err_msg_out parameter is set to a string suitable for log output
2286 * if parsing fails. This function does some validation, but only
2287 * that which depends solely on the contents of the cell and the
2288 * key; it can be unit-tested. Further validation is done in
2289 * rend_service_validate_intro().
2293 rend_service_begin_parse_intro(const uint8_t *request
,
2298 rend_intro_cell_t
*rv
= NULL
;
2299 char *err_msg
= NULL
;
2301 if (!request
|| request_len
<= 0) goto err
;
2302 if (!(type
== 1 || type
== 2)) goto err
;
2304 /* First, check that the cell is long enough to be a sensible INTRODUCE */
2306 /* min key length plus digest length plus nickname length */
2308 (DIGEST_LEN
+ REND_COOKIE_LEN
+ (MAX_NICKNAME_LEN
+ 1) +
2311 tor_asprintf(&err_msg
,
2312 "got a truncated INTRODUCE%d cell",
2318 /* Allocate a new parsed cell structure */
2319 rv
= tor_malloc_zero(sizeof(*rv
));
2324 /* Copy in the ID */
2325 memcpy(rv
->pk
, request
, DIGEST_LEN
);
2327 /* Copy in the ciphertext */
2328 rv
->ciphertext
= tor_malloc(request_len
- DIGEST_LEN
);
2329 memcpy(rv
->ciphertext
, request
+ DIGEST_LEN
, request_len
- DIGEST_LEN
);
2330 rv
->ciphertext_len
= request_len
- DIGEST_LEN
;
2335 rend_service_free_intro(rv
);
2338 if (err_msg_out
&& !err_msg
) {
2339 tor_asprintf(&err_msg
,
2340 "unknown INTRODUCE%d error",
2345 if (err_msg_out
) *err_msg_out
= err_msg
;
2346 else tor_free(err_msg
);
2351 /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
2356 rend_service_parse_intro_for_v0_or_v1(
2357 rend_intro_cell_t
*intro
,
2359 size_t plaintext_len
,
2362 const char *rp_nickname
, *endptr
;
2363 size_t nickname_field_len
, ver_specific_len
;
2365 if (intro
->version
== 1) {
2366 ver_specific_len
= MAX_HEX_NICKNAME_LEN
+ 2;
2367 rp_nickname
= ((const char *)buf
) + 1;
2368 nickname_field_len
= MAX_HEX_NICKNAME_LEN
+ 1;
2369 } else if (intro
->version
== 0) {
2370 ver_specific_len
= MAX_NICKNAME_LEN
+ 1;
2371 rp_nickname
= (const char *)buf
;
2372 nickname_field_len
= MAX_NICKNAME_LEN
+ 1;
2375 tor_asprintf(err_msg_out
,
2376 "rend_service_parse_intro_for_v0_or_v1() called with "
2377 "bad version %d on INTRODUCE%d cell (this is a bug)",
2379 (int)(intro
->type
));
2383 if (plaintext_len
< ver_specific_len
) {
2385 tor_asprintf(err_msg_out
,
2386 "short plaintext of encrypted part in v1 INTRODUCE%d "
2387 "cell (%lu bytes, needed %lu)",
2389 (unsigned long)plaintext_len
,
2390 (unsigned long)ver_specific_len
);
2394 endptr
= memchr(rp_nickname
, 0, nickname_field_len
);
2395 if (!endptr
|| endptr
== rp_nickname
) {
2397 tor_asprintf(err_msg_out
,
2398 "couldn't find a nul-padded nickname in "
2400 (int)(intro
->type
));
2405 if ((intro
->version
== 0 &&
2406 !is_legal_nickname(rp_nickname
)) ||
2407 (intro
->version
== 1 &&
2408 !is_legal_nickname_or_hexdigest(rp_nickname
))) {
2410 tor_asprintf(err_msg_out
,
2411 "bad nickname in INTRODUCE%d cell",
2412 (int)(intro
->type
));
2417 memcpy(intro
->u
.v0_v1
.rp
, rp_nickname
, endptr
- rp_nickname
+ 1);
2419 return ver_specific_len
;
2425 /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
2429 rend_service_parse_intro_for_v2(
2430 rend_intro_cell_t
*intro
,
2432 size_t plaintext_len
,
2436 extend_info_t
*extend_info
= NULL
;
2437 ssize_t ver_specific_len
;
2440 * We accept version 3 too so that the v3 parser can call this with
2441 * an adjusted buffer for the latter part of a v3 cell, which is
2442 * identical to a v2 cell.
2444 if (!(intro
->version
== 2 ||
2445 intro
->version
== 3)) {
2447 tor_asprintf(err_msg_out
,
2448 "rend_service_parse_intro_for_v2() called with "
2449 "bad version %d on INTRODUCE%d cell (this is a bug)",
2451 (int)(intro
->type
));
2455 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2456 if (plaintext_len
< 7 + DIGEST_LEN
+ 2) {
2458 tor_asprintf(err_msg_out
,
2459 "truncated plaintext of encrypted parted of "
2460 "version %d INTRODUCE%d cell",
2462 (int)(intro
->type
));
2468 extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
2469 tor_addr_from_ipv4n(&extend_info
->addr
, get_uint32(buf
+ 1));
2470 extend_info
->port
= ntohs(get_uint16(buf
+ 5));
2471 memcpy(extend_info
->identity_digest
, buf
+ 7, DIGEST_LEN
);
2472 extend_info
->nickname
[0] = '$';
2473 base16_encode(extend_info
->nickname
+ 1, sizeof(extend_info
->nickname
) - 1,
2474 extend_info
->identity_digest
, DIGEST_LEN
);
2475 klen
= ntohs(get_uint16(buf
+ 7 + DIGEST_LEN
));
2477 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2478 if (plaintext_len
< 7 + DIGEST_LEN
+ 2 + klen
) {
2480 tor_asprintf(err_msg_out
,
2481 "truncated plaintext of encrypted parted of "
2482 "version %d INTRODUCE%d cell",
2484 (int)(intro
->type
));
2490 extend_info
->onion_key
=
2491 crypto_pk_asn1_decode((const char *)(buf
+ 7 + DIGEST_LEN
+ 2), klen
);
2492 if (!extend_info
->onion_key
) {
2494 tor_asprintf(err_msg_out
,
2495 "error decoding onion key in version %d "
2503 if (128 != crypto_pk_keysize(extend_info
->onion_key
)) {
2505 tor_asprintf(err_msg_out
,
2506 "invalid onion key size in version %d INTRODUCE%d cell",
2514 ver_specific_len
= 7+DIGEST_LEN
+2+klen
;
2516 if (intro
->version
== 2) intro
->u
.v2
.extend_info
= extend_info
;
2517 else intro
->u
.v3
.extend_info
= extend_info
;
2519 return ver_specific_len
;
2522 extend_info_free(extend_info
);
2527 /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
2531 rend_service_parse_intro_for_v3(
2532 rend_intro_cell_t
*intro
,
2534 size_t plaintext_len
,
2537 ssize_t adjust
, v2_ver_specific_len
, ts_offset
;
2539 /* This should only be called on v3 cells */
2540 if (intro
->version
!= 3) {
2542 tor_asprintf(err_msg_out
,
2543 "rend_service_parse_intro_for_v3() called with "
2544 "bad version %d on INTRODUCE%d cell (this is a bug)",
2546 (int)(intro
->type
));
2551 * Check that we have at least enough to get auth_len:
2553 * 1 octet for version, 1 for auth_type, 2 for auth_len
2555 if (plaintext_len
< 4) {
2557 tor_asprintf(err_msg_out
,
2558 "truncated plaintext of encrypted parted of "
2559 "version %d INTRODUCE%d cell",
2561 (int)(intro
->type
));
2568 * The rend_client_send_introduction() function over in rendclient.c is
2569 * broken (i.e., fails to match the spec) in such a way that we can't
2570 * change it without breaking the protocol. Specifically, it doesn't
2571 * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2572 * by two bytes after that. Calculate ts_offset and do everything from
2573 * the timestamp on relative to that to handle this dain bramage.
2576 intro
->u
.v3
.auth_type
= buf
[1];
2577 if (intro
->u
.v3
.auth_type
!= REND_NO_AUTH
) {
2578 intro
->u
.v3
.auth_len
= ntohs(get_uint16(buf
+ 2));
2579 ts_offset
= 4 + intro
->u
.v3
.auth_len
;
2581 intro
->u
.v3
.auth_len
= 0;
2585 /* Check that auth len makes sense for this auth type */
2586 if (intro
->u
.v3
.auth_type
== REND_BASIC_AUTH
||
2587 intro
->u
.v3
.auth_type
== REND_STEALTH_AUTH
) {
2588 if (intro
->u
.v3
.auth_len
!= REND_DESC_COOKIE_LEN
) {
2590 tor_asprintf(err_msg_out
,
2591 "wrong auth data size %d for INTRODUCE%d cell, "
2593 (int)(intro
->u
.v3
.auth_len
),
2595 REND_DESC_COOKIE_LEN
);
2602 /* Check that we actually have everything up through the timestamp */
2603 if (plaintext_len
< (size_t)(ts_offset
)+4) {
2605 tor_asprintf(err_msg_out
,
2606 "truncated plaintext of encrypted parted of "
2607 "version %d INTRODUCE%d cell",
2609 (int)(intro
->type
));
2615 if (intro
->u
.v3
.auth_type
!= REND_NO_AUTH
&&
2616 intro
->u
.v3
.auth_len
> 0) {
2617 /* Okay, we can go ahead and copy auth_data */
2618 intro
->u
.v3
.auth_data
= tor_malloc(intro
->u
.v3
.auth_len
);
2620 * We know we had an auth_len field in this case, so 4 is
2623 memcpy(intro
->u
.v3
.auth_data
, buf
+ 4, intro
->u
.v3
.auth_len
);
2627 * From here on, the format is as in v2, so we call the v2 parser with
2628 * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2629 * v2 parser expects to skip over a version byte at the start, so we
2630 * adjust by 3 + ts_offset.
2632 adjust
= 3 + ts_offset
;
2634 v2_ver_specific_len
=
2635 rend_service_parse_intro_for_v2(intro
,
2636 buf
+ adjust
, plaintext_len
- adjust
,
2639 /* Success in v2 parser */
2640 if (v2_ver_specific_len
>= 0) return v2_ver_specific_len
+ adjust
;
2641 /* Failure in v2 parser; it will have provided an err_msg */
2642 else return v2_ver_specific_len
;
2648 /** Table of parser functions for version-specific parts of an INTRODUCE2
2653 (*intro_version_handlers
[])(
2654 rend_intro_cell_t
*,
2658 { rend_service_parse_intro_for_v0_or_v1
,
2659 rend_service_parse_intro_for_v0_or_v1
,
2660 rend_service_parse_intro_for_v2
,
2661 rend_service_parse_intro_for_v3
};
2663 /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
2664 * return 0 if successful, or < 0 and write an error message to
2665 * *err_msg_out if provided.
2669 rend_service_decrypt_intro(
2670 rend_intro_cell_t
*intro
,
2674 char *err_msg
= NULL
;
2675 uint8_t key_digest
[DIGEST_LEN
];
2676 char service_id
[REND_SERVICE_ID_LEN_BASE32
+1];
2678 uint8_t buf
[RELAY_PAYLOAD_SIZE
];
2679 int result
, status
= -1;
2681 if (!intro
|| !key
) {
2684 tor_strdup("rend_service_decrypt_intro() called with bad "
2692 /* Make sure we have ciphertext */
2693 if (!(intro
->ciphertext
) || intro
->ciphertext_len
<= 0) {
2695 tor_asprintf(&err_msg
,
2696 "rend_intro_cell_t was missing ciphertext for "
2698 (int)(intro
->type
));
2704 /* Check that this cell actually matches this service key */
2706 /* first DIGEST_LEN bytes of request is intro or service pk digest */
2707 if (crypto_pk_get_digest(key
, (char *)key_digest
) < 0) {
2709 *err_msg_out
= tor_strdup("Couldn't compute RSA digest.");
2710 log_warn(LD_BUG
, "Couldn't compute key digest.");
2715 if (tor_memneq(key_digest
, intro
->pk
, DIGEST_LEN
)) {
2717 base32_encode(service_id
, REND_SERVICE_ID_LEN_BASE32
+ 1,
2718 (char*)(intro
->pk
), REND_SERVICE_ID_LEN
);
2719 tor_asprintf(&err_msg
,
2720 "got an INTRODUCE%d cell for the wrong service (%s)",
2722 escaped(service_id
));
2729 /* Make sure the encrypted part is long enough to decrypt */
2731 key_len
= crypto_pk_keysize(key
);
2732 if (intro
->ciphertext_len
< key_len
) {
2734 tor_asprintf(&err_msg
,
2735 "got an INTRODUCE%d cell with a truncated PK-encrypted "
2737 (int)(intro
->type
));
2744 /* Decrypt the encrypted part */
2746 crypto_pk_obsolete_private_hybrid_decrypt(
2747 key
, (char *)buf
, sizeof(buf
),
2748 (const char *)(intro
->ciphertext
), intro
->ciphertext_len
,
2749 PK_PKCS1_OAEP_PADDING
, 1);
2752 tor_asprintf(&err_msg
,
2753 "couldn't decrypt INTRODUCE%d cell",
2754 (int)(intro
->type
));
2759 intro
->plaintext_len
= result
;
2760 intro
->plaintext
= tor_malloc(intro
->plaintext_len
);
2761 memcpy(intro
->plaintext
, buf
, intro
->plaintext_len
);
2768 if (err_msg_out
&& !err_msg
) {
2769 tor_asprintf(&err_msg
,
2770 "unknown INTRODUCE%d error decrypting encrypted part",
2771 intro
? (int)(intro
->type
) : -1);
2775 if (err_msg_out
) *err_msg_out
= err_msg
;
2776 else tor_free(err_msg
);
2778 /* clean up potentially sensitive material */
2779 memwipe(buf
, 0, sizeof(buf
));
2780 memwipe(key_digest
, 0, sizeof(key_digest
));
2781 memwipe(service_id
, 0, sizeof(service_id
));
2786 /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
2787 * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
2788 * message to *err_msg_out if provided.
2792 rend_service_parse_intro_plaintext(
2793 rend_intro_cell_t
*intro
,
2796 char *err_msg
= NULL
;
2797 ssize_t ver_specific_len
, ver_invariant_len
;
2804 tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2805 "rend_intro_cell_t");
2812 /* Check that we have plaintext */
2813 if (!(intro
->plaintext
) || intro
->plaintext_len
<= 0) {
2815 err_msg
= tor_strdup("rend_intro_cell_t was missing plaintext");
2821 /* In all formats except v0, the first byte is a version number */
2822 version
= intro
->plaintext
[0];
2824 /* v0 has no version byte (stupid...), so handle it as a fallback */
2825 if (version
> 3) version
= 0;
2827 /* Copy the version into the parsed cell structure */
2828 intro
->version
= version
;
2830 /* Call the version-specific parser from the table */
2832 intro_version_handlers
[version
](intro
,
2833 intro
->plaintext
, intro
->plaintext_len
,
2835 if (ver_specific_len
< 0) {
2840 /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
2841 * and at the end of the plaintext of the encrypted part of the cell.
2844 ver_invariant_len
= intro
->plaintext_len
- ver_specific_len
;
2845 if (ver_invariant_len
< REND_COOKIE_LEN
+ DH_KEY_LEN
) {
2846 tor_asprintf(&err_msg
,
2847 "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2849 (long)(intro
->plaintext_len
));
2852 } else if (ver_invariant_len
> REND_COOKIE_LEN
+ DH_KEY_LEN
) {
2853 tor_asprintf(&err_msg
,
2854 "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2856 (long)(intro
->plaintext_len
));
2861 intro
->plaintext
+ ver_specific_len
,
2864 intro
->plaintext
+ ver_specific_len
+ REND_COOKIE_LEN
,
2868 /* Flag it as being fully parsed */
2875 if (err_msg_out
&& !err_msg
) {
2876 tor_asprintf(&err_msg
,
2877 "unknown INTRODUCE%d error parsing encrypted part",
2878 intro
? (int)(intro
->type
) : -1);
2882 if (err_msg_out
) *err_msg_out
= err_msg
;
2883 else tor_free(err_msg
);
2888 /** Do validity checks on a parsed intro cell after decryption; some of
2889 * these are not done in rend_service_parse_intro_plaintext() itself because
2890 * they depend on a lot of other state and would make it hard to unit test.
2891 * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
2892 * optionally writes out an error message for logging. If an err_msg
2893 * pointer is provided, it is the caller's responsibility to free any
2898 rend_service_validate_intro_late(const rend_intro_cell_t
*intro
,
2906 tor_strdup("NULL intro cell passed to "
2907 "rend_service_validate_intro_late()");
2913 if (intro
->version
== 3 && intro
->parsed
) {
2914 if (!(intro
->u
.v3
.auth_type
== REND_NO_AUTH
||
2915 intro
->u
.v3
.auth_type
== REND_BASIC_AUTH
||
2916 intro
->u
.v3
.auth_type
== REND_STEALTH_AUTH
)) {
2917 /* This is an informative message, not an error, as in the old code */
2919 tor_asprintf(err_msg_out
,
2920 "unknown authorization type %d",
2921 intro
->u
.v3
.auth_type
);
2929 /** Called when we fail building a rendezvous circuit at some point other
2930 * than the last hop: launches a new circuit to the same rendezvous point.
2933 rend_service_relaunch_rendezvous(origin_circuit_t
*oldcirc
)
2935 origin_circuit_t
*newcirc
;
2936 cpath_build_state_t
*newstate
, *oldstate
;
2938 tor_assert(oldcirc
->base_
.purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
);
2940 oldstate
= oldcirc
->build_state
;
2941 tor_assert(oldstate
);
2943 if (oldstate
->service_pending_final_cpath_ref
== NULL
) {
2944 log_info(LD_REND
,"Skipping relaunch of circ that failed on its first hop. "
2945 "Initiator will retry.");
2949 log_info(LD_REND
,"Reattempting rendezvous circuit to '%s'",
2950 safe_str(extend_info_describe(oldstate
->chosen_exit
)));
2952 /* You'd think Single Onion Services would want to retry the rendezvous
2953 * using a direct connection. But if it's blocked by a firewall, or the
2954 * service is IPv6-only, or the rend point avoiding becoming a one-hop
2955 * proxy, we need a 3-hop connection. */
2956 newcirc
= circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND
,
2957 oldstate
->chosen_exit
,
2958 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
2961 log_warn(LD_REND
,"Couldn't relaunch rendezvous circuit to '%s'.",
2962 safe_str(extend_info_describe(oldstate
->chosen_exit
)));
2965 newstate
= newcirc
->build_state
;
2966 tor_assert(newstate
);
2967 newstate
->failure_count
= oldstate
->failure_count
+1;
2968 newstate
->expiry_time
= oldstate
->expiry_time
;
2969 newstate
->service_pending_final_cpath_ref
=
2970 oldstate
->service_pending_final_cpath_ref
;
2971 ++(newstate
->service_pending_final_cpath_ref
->refcount
);
2973 newcirc
->rend_data
= rend_data_dup(oldcirc
->rend_data
);
2976 /** Launch a circuit to serve as an introduction point for the service
2977 * <b>service</b> at the introduction point <b>nickname</b>
2980 rend_service_launch_establish_intro(rend_service_t
*service
,
2981 rend_intro_point_t
*intro
)
2983 origin_circuit_t
*launched
;
2984 int flags
= CIRCLAUNCH_NEED_UPTIME
|CIRCLAUNCH_IS_INTERNAL
;
2985 const or_options_t
*options
= get_options();
2986 extend_info_t
*launch_ei
= intro
->extend_info
;
2987 extend_info_t
*direct_ei
= NULL
;
2989 /* Are we in single onion mode? */
2990 if (rend_service_allow_non_anonymous_connection(options
)) {
2991 /* Do we have a descriptor for the node?
2992 * We've either just chosen it from the consensus, or we've just reviewed
2993 * our intro points to see which ones are still valid, and deleted the ones
2994 * that aren't in the consensus any more. */
2995 const node_t
*node
= node_get_by_id(launch_ei
->identity_digest
);
2997 /* The service has kept an intro point after it went missing from the
2998 * consensus. If we did anything else here, it would be a consensus
2999 * distinguisher. Which are less of an issue for single onion services,
3000 * but still a bug. */
3003 /* Can we connect to the node directly? If so, replace launch_ei
3004 * (a multi-hop extend_info) with one suitable for direct connection. */
3005 if (rend_service_use_direct_connection_node(options
, node
)) {
3006 direct_ei
= extend_info_from_node(node
, 1);
3007 if (BUG(!direct_ei
)) {
3008 /* rend_service_use_direct_connection_node and extend_info_from_node
3009 * disagree about which addresses on this node are permitted. This
3010 * should never happen. Avoiding the connection is a safe response. */
3013 flags
= flags
| CIRCLAUNCH_ONEHOP_TUNNEL
;
3014 launch_ei
= direct_ei
;
3017 /* launch_ei is either intro->extend_info, or has been replaced with a valid
3018 * extend_info for single onion service direct connection. */
3019 tor_assert(launch_ei
);
3020 /* We must have the same intro when making a direct connection. */
3021 tor_assert(tor_memeq(intro
->extend_info
->identity_digest
,
3022 launch_ei
->identity_digest
,
3026 "Launching circuit to introduction point %s%s%s for service %s",
3027 safe_str_client(extend_info_describe(intro
->extend_info
)),
3028 direct_ei
? " via direct address " : "",
3029 direct_ei
? safe_str_client(extend_info_describe(direct_ei
)) : "",
3030 service
->service_id
);
3032 rep_hist_note_used_internal(time(NULL
), 1, 0);
3034 ++service
->n_intro_circuits_launched
;
3035 launched
= circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
,
3040 "Can't launch circuit to establish introduction at %s%s%s.",
3041 safe_str_client(extend_info_describe(intro
->extend_info
)),
3042 direct_ei
? " via direct address " : "",
3043 direct_ei
? safe_str_client(extend_info_describe(direct_ei
)) : ""
3045 extend_info_free(direct_ei
);
3048 /* We must have the same exit node even if cannibalized or direct connection.
3050 tor_assert(tor_memeq(intro
->extend_info
->identity_digest
,
3051 launched
->build_state
->chosen_exit
->identity_digest
,
3054 launched
->rend_data
= rend_data_service_create(service
->service_id
,
3055 service
->pk_digest
, NULL
,
3056 service
->auth_type
);
3057 launched
->intro_key
= crypto_pk_dup_key(intro
->intro_key
);
3058 if (launched
->base_
.state
== CIRCUIT_STATE_OPEN
)
3059 rend_service_intro_has_opened(launched
);
3060 extend_info_free(direct_ei
);
3064 /** Return the number of introduction points that are established for the
3067 count_established_intro_points(const rend_service_t
*service
)
3069 unsigned int num
= 0;
3071 SMARTLIST_FOREACH(service
->intro_nodes
, rend_intro_point_t
*, intro
,
3072 num
+= intro
->circuit_established
3077 /** Return the number of introduction points that are or are being
3078 * established for the given service. This function iterates over all
3079 * circuit and count those that are linked to the service and are waiting
3080 * for the intro point to respond. */
3082 count_intro_point_circuits(const rend_service_t
*service
)
3084 unsigned int num_ipos
= 0;
3085 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t
*, circ
) {
3086 if (!circ
->marked_for_close
&&
3087 circ
->state
== CIRCUIT_STATE_OPEN
&&
3088 (circ
->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
3089 circ
->purpose
== CIRCUIT_PURPOSE_S_INTRO
)) {
3090 origin_circuit_t
*oc
= TO_ORIGIN_CIRCUIT(circ
);
3091 if (oc
->rend_data
&&
3092 rend_circuit_pk_digest_eq(oc
, (uint8_t *) service
->pk_digest
)) {
3097 SMARTLIST_FOREACH_END(circ
);
3101 /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
3102 write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
3103 as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
3104 crypto material. On success, fill <b>cell_body_out</b> and return the number
3105 of bytes written. On fail, return -1.
3108 rend_service_encode_establish_intro_cell(char *cell_body_out
,
3109 size_t cell_body_out_len
,
3110 crypto_pk_t
*intro_key
,
3111 const char *rend_circ_nonce
)
3116 char auth
[DIGEST_LEN
+ 9];
3118 tor_assert(intro_key
);
3119 tor_assert(rend_circ_nonce
);
3121 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3122 r
= crypto_pk_asn1_encode(intro_key
, cell_body_out
+2,
3123 RELAY_PAYLOAD_SIZE
-2);
3125 log_warn(LD_BUG
, "Internal error; failed to establish intro point.");
3129 set_uint16(cell_body_out
, htons((uint16_t)len
));
3131 memcpy(auth
, rend_circ_nonce
, DIGEST_LEN
);
3132 memcpy(auth
+DIGEST_LEN
, "INTRODUCE", 9);
3133 if (crypto_digest(cell_body_out
+len
, auth
, DIGEST_LEN
+9))
3136 r
= crypto_pk_private_sign_digest(intro_key
, cell_body_out
+len
,
3137 cell_body_out_len
- len
,
3138 cell_body_out
, len
);
3140 log_warn(LD_BUG
, "Internal error: couldn't sign introduction request.");
3148 memwipe(auth
, 0, sizeof(auth
));
3153 /** Called when we're done building a circuit to an introduction point:
3154 * sends a RELAY_ESTABLISH_INTRO cell.
3157 rend_service_intro_has_opened(origin_circuit_t
*circuit
)
3159 rend_service_t
*service
;
3160 char buf
[RELAY_PAYLOAD_SIZE
];
3161 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3162 unsigned int expiring_nodes_len
, num_ip_circuits
, valid_ip_circuits
= 0;
3163 int reason
= END_CIRC_REASON_TORPROTOCOL
;
3164 const char *rend_pk_digest
;
3166 tor_assert(circuit
->base_
.purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
);
3167 assert_circ_anonymity_ok(circuit
, get_options());
3168 tor_assert(circuit
->cpath
);
3169 tor_assert(circuit
->rend_data
);
3170 /* XXX: This is version 2 specific (only on supported). */
3171 rend_pk_digest
= (char *) rend_data_get_pk_digest(circuit
->rend_data
, NULL
);
3173 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
3174 rend_pk_digest
, REND_SERVICE_ID_LEN
);
3176 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
3178 log_warn(LD_REND
, "Unrecognized service ID %s on introduction circuit %u.",
3179 safe_str_client(serviceid
), (unsigned)circuit
->base_
.n_circ_id
);
3180 reason
= END_CIRC_REASON_NOSUCHSERVICE
;
3184 /* Take the current amount of expiring nodes and the current amount of IP
3185 * circuits and compute how many valid IP circuits we have. */
3186 expiring_nodes_len
= (unsigned int) smartlist_len(service
->expiring_nodes
);
3187 num_ip_circuits
= count_intro_point_circuits(service
);
3188 /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
3189 * case this condition turns out false because it means that all circuits
3190 * are expiring so we need to keep this circuit. */
3191 if (num_ip_circuits
> expiring_nodes_len
) {
3192 valid_ip_circuits
= num_ip_circuits
- expiring_nodes_len
;
3195 /* If we already have enough introduction circuits for this service,
3196 * redefine this one as a general circuit or close it, depending.
3197 * Substract the amount of expiring nodes here because the circuits are
3199 if (valid_ip_circuits
> service
->n_intro_points_wanted
) {
3200 const or_options_t
*options
= get_options();
3201 /* Remove the intro point associated with this circuit, it's being
3202 * repurposed or closed thus cleanup memory. */
3203 rend_intro_point_t
*intro
= find_intro_point(circuit
);
3204 if (intro
!= NULL
) {
3205 smartlist_remove(service
->intro_nodes
, intro
);
3206 rend_intro_point_free(intro
);
3209 if (options
->ExcludeNodes
) {
3210 /* XXXX in some future version, we can test whether the transition is
3211 allowed or not given the actual nodes in the circuit. But for now,
3212 this case, we might as well close the thing. */
3213 log_info(LD_CIRC
|LD_REND
, "We have just finished an introduction "
3214 "circuit, but we already have enough. Closing it.");
3215 reason
= END_CIRC_REASON_NONE
;
3218 tor_assert(circuit
->build_state
->is_internal
);
3219 log_info(LD_CIRC
|LD_REND
, "We have just finished an introduction "
3220 "circuit, but we already have enough. Redefining purpose to "
3221 "general; leaving as internal.");
3223 circuit_change_purpose(TO_CIRCUIT(circuit
), CIRCUIT_PURPOSE_C_GENERAL
);
3226 rend_data_free(circuit
->rend_data
);
3227 circuit
->rend_data
= NULL
;
3230 crypto_pk_t
*intro_key
= circuit
->intro_key
;
3231 circuit
->intro_key
= NULL
;
3232 crypto_pk_free(intro_key
);
3235 circuit_has_opened(circuit
);
3241 "Established circuit %u as introduction point for service %s",
3242 (unsigned)circuit
->base_
.n_circ_id
, serviceid
);
3243 circuit_log_path(LOG_INFO
, LD_REND
, circuit
);
3245 /* Send the ESTABLISH_INTRO cell */
3248 len
= rend_service_encode_establish_intro_cell(buf
, sizeof(buf
),
3250 circuit
->cpath
->prev
->rend_circ_nonce
);
3252 reason
= END_CIRC_REASON_INTERNAL
;
3256 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit
),
3257 RELAY_COMMAND_ESTABLISH_INTRO
,
3258 buf
, len
, circuit
->cpath
->prev
)<0) {
3259 log_info(LD_GENERAL
,
3260 "Couldn't send introduction request for service %s on circuit %u",
3261 serviceid
, (unsigned)circuit
->base_
.n_circ_id
);
3266 /* We've attempted to use this circuit */
3267 pathbias_count_use_attempt(circuit
);
3272 circuit_mark_for_close(TO_CIRCUIT(circuit
), reason
);
3274 memwipe(buf
, 0, sizeof(buf
));
3275 memwipe(serviceid
, 0, sizeof(serviceid
));
3280 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
3281 * live introduction point, and note that the service descriptor is
3282 * now out-of-date. */
3284 rend_service_intro_established(origin_circuit_t
*circuit
,
3285 const uint8_t *request
,
3288 rend_service_t
*service
;
3289 rend_intro_point_t
*intro
;
3290 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3293 tor_assert(circuit
->rend_data
);
3294 /* XXX: This is version 2 specific (only supported one for now). */
3295 const char *rend_pk_digest
=
3296 (char *) rend_data_get_pk_digest(circuit
->rend_data
, NULL
);
3298 if (circuit
->base_
.purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
) {
3299 log_warn(LD_PROTOCOL
,
3300 "received INTRO_ESTABLISHED cell on non-intro circuit.");
3303 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
3305 log_warn(LD_REND
, "Unknown service on introduction circuit %u.",
3306 (unsigned)circuit
->base_
.n_circ_id
);
3309 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+ 1,
3310 rend_pk_digest
, REND_SERVICE_ID_LEN
);
3311 /* We've just successfully established a intro circuit to one of our
3312 * introduction point, account for it. */
3313 intro
= find_intro_point(circuit
);
3314 if (intro
== NULL
) {
3316 "Introduction circuit established without a rend_intro_point_t "
3317 "object for service %s on circuit %u",
3318 safe_str_client(serviceid
), (unsigned)circuit
->base_
.n_circ_id
);
3321 intro
->circuit_established
= 1;
3322 /* We might not have every introduction point ready but at this point we
3323 * know that the descriptor needs to be uploaded. */
3324 service
->desc_is_dirty
= time(NULL
);
3325 circuit_change_purpose(TO_CIRCUIT(circuit
), CIRCUIT_PURPOSE_S_INTRO
);
3328 "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3329 (unsigned)circuit
->base_
.n_circ_id
, serviceid
);
3331 /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3333 pathbias_mark_use_success(circuit
);
3337 circuit_mark_for_close(TO_CIRCUIT(circuit
), END_CIRC_REASON_TORPROTOCOL
);
3341 /** Called once a circuit to a rendezvous point is established: sends a
3342 * RELAY_COMMAND_RENDEZVOUS1 cell.
3345 rend_service_rendezvous_has_opened(origin_circuit_t
*circuit
)
3347 rend_service_t
*service
;
3348 char buf
[RELAY_PAYLOAD_SIZE
];
3350 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3353 const char *rend_cookie
, *rend_pk_digest
;
3355 tor_assert(circuit
->base_
.purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
);
3356 tor_assert(circuit
->cpath
);
3357 tor_assert(circuit
->build_state
);
3358 assert_circ_anonymity_ok(circuit
, get_options());
3359 tor_assert(circuit
->rend_data
);
3361 /* XXX: This is version 2 specific (only one supported). */
3362 rend_pk_digest
= (char *) rend_data_get_pk_digest(circuit
->rend_data
,
3364 rend_cookie
= circuit
->rend_data
->rend_cookie
;
3366 /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
3367 * timestamp regardless of its content because that circuit could have been
3368 * cannibalized so in any cases, we are about to use that circuit more. */
3369 circuit
->base_
.timestamp_dirty
= time(NULL
);
3371 /* This may be redundant */
3372 pathbias_count_use_attempt(circuit
);
3374 hop
= circuit
->build_state
->service_pending_final_cpath_ref
->cpath
;
3376 base16_encode(hexcookie
,9, rend_cookie
,4);
3377 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
3378 rend_pk_digest
, REND_SERVICE_ID_LEN
);
3381 "Done building circuit %u to rendezvous with "
3382 "cookie %s for service %s",
3383 (unsigned)circuit
->base_
.n_circ_id
, hexcookie
, serviceid
);
3384 circuit_log_path(LOG_INFO
, LD_REND
, circuit
);
3386 /* Clear the 'in-progress HS circ has timed out' flag for
3387 * consistency with what happens on the client side; this line has
3388 * no effect on Tor's behaviour. */
3389 circuit
->hs_circ_has_timed_out
= 0;
3391 /* If hop is NULL, another rend circ has already connected to this
3392 * rend point. Close this circ. */
3394 log_info(LD_REND
, "Another rend circ has already reached this rend point; "
3395 "closing this rend circ.");
3396 reason
= END_CIRC_REASON_NONE
;
3400 /* Remove our final cpath element from the reference, so that no
3401 * other circuit will try to use it. Store it in
3402 * pending_final_cpath for now to ensure that it will be freed if
3403 * our rendezvous attempt fails. */
3404 circuit
->build_state
->pending_final_cpath
= hop
;
3405 circuit
->build_state
->service_pending_final_cpath_ref
->cpath
= NULL
;
3407 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
3409 log_warn(LD_GENERAL
, "Internal error: unrecognized service ID on "
3410 "rendezvous circuit.");
3411 reason
= END_CIRC_REASON_INTERNAL
;
3415 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3416 memcpy(buf
, rend_cookie
, REND_COOKIE_LEN
);
3417 if (crypto_dh_get_public(hop
->rend_dh_handshake_state
,
3418 buf
+REND_COOKIE_LEN
, DH_KEY_LEN
)<0) {
3419 log_warn(LD_GENERAL
,"Couldn't get DH public key.");
3420 reason
= END_CIRC_REASON_INTERNAL
;
3423 memcpy(buf
+REND_COOKIE_LEN
+DH_KEY_LEN
, hop
->rend_circ_nonce
,
3427 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit
),
3428 RELAY_COMMAND_RENDEZVOUS1
,
3429 buf
, HS_LEGACY_RENDEZVOUS_CELL_SIZE
,
3430 circuit
->cpath
->prev
)<0) {
3431 log_warn(LD_GENERAL
, "Couldn't send RENDEZVOUS1 cell.");
3435 crypto_dh_free(hop
->rend_dh_handshake_state
);
3436 hop
->rend_dh_handshake_state
= NULL
;
3438 /* Append the cpath entry. */
3439 hop
->state
= CPATH_STATE_OPEN
;
3440 /* set the windows to default. these are the windows
3441 * that the service thinks the client has.
3443 hop
->package_window
= circuit_initial_package_window();
3444 hop
->deliver_window
= CIRCWINDOW_START
;
3446 onion_append_to_cpath(&circuit
->cpath
, hop
);
3447 circuit
->build_state
->pending_final_cpath
= NULL
; /* prevent double-free */
3449 /* Change the circuit purpose. */
3450 circuit_change_purpose(TO_CIRCUIT(circuit
), CIRCUIT_PURPOSE_S_REND_JOINED
);
3455 circuit_mark_for_close(TO_CIRCUIT(circuit
), reason
);
3457 memwipe(buf
, 0, sizeof(buf
));
3458 memwipe(serviceid
, 0, sizeof(serviceid
));
3459 memwipe(hexcookie
, 0, sizeof(hexcookie
));
3465 * Manage introduction points
3468 /** Return the (possibly non-open) introduction circuit ending at
3469 * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
3470 * (<b>desc_version</b> is ignored). Return NULL if no such service is
3473 static origin_circuit_t
*
3474 find_intro_circuit(rend_intro_point_t
*intro
, const char *pk_digest
)
3476 origin_circuit_t
*circ
= NULL
;
3479 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
,
3480 (uint8_t *) pk_digest
, CIRCUIT_PURPOSE_S_INTRO
))) {
3481 if (tor_memeq(circ
->build_state
->chosen_exit
->identity_digest
,
3482 intro
->extend_info
->identity_digest
, DIGEST_LEN
) &&
3489 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
,
3490 (uint8_t *) pk_digest
,
3491 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
))) {
3492 if (tor_memeq(circ
->build_state
->chosen_exit
->identity_digest
,
3493 intro
->extend_info
->identity_digest
, DIGEST_LEN
) &&
3501 /** Return the corresponding introdution point using the circuit <b>circ</b>
3502 * found in the <b>service</b>. NULL is returned if not found. */
3503 static rend_intro_point_t
*
3504 find_expiring_intro_point(rend_service_t
*service
, origin_circuit_t
*circ
)
3506 tor_assert(service
);
3507 tor_assert(TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
3508 TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_INTRO
);
3510 SMARTLIST_FOREACH(service
->expiring_nodes
, rend_intro_point_t
*,
3512 if (crypto_pk_eq_keys(intro_point
->intro_key
, circ
->intro_key
)) {
3519 /** Return a pointer to the rend_intro_point_t corresponding to the
3520 * service-side introduction circuit <b>circ</b>. */
3521 static rend_intro_point_t
*
3522 find_intro_point(origin_circuit_t
*circ
)
3524 const char *serviceid
;
3525 rend_service_t
*service
= NULL
;
3527 tor_assert(TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
||
3528 TO_CIRCUIT(circ
)->purpose
== CIRCUIT_PURPOSE_S_INTRO
);
3529 tor_assert(circ
->rend_data
);
3530 serviceid
= rend_data_get_address(circ
->rend_data
);
3532 SMARTLIST_FOREACH(rend_service_list
, rend_service_t
*, s
,
3533 if (tor_memeq(s
->service_id
, serviceid
, REND_SERVICE_ID_LEN_BASE32
)) {
3538 if (service
== NULL
) return NULL
;
3540 SMARTLIST_FOREACH(service
->intro_nodes
, rend_intro_point_t
*, intro_point
,
3541 if (crypto_pk_eq_keys(intro_point
->intro_key
, circ
->intro_key
)) {
3548 /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
3549 * associated with the rend_service_descriptor_t <b>renddesc</b> to
3550 * the responsible hidden service directories OR the hidden service
3551 * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
3552 * <b>seconds_valid</b> are only passed for logging purposes.
3555 directory_post_to_hs_dir(rend_service_descriptor_t
*renddesc
,
3556 smartlist_t
*descs
, smartlist_t
*hs_dirs
,
3557 const char *service_id
, int seconds_valid
)
3559 int i
, j
, failed_upload
= 0;
3560 smartlist_t
*responsible_dirs
= smartlist_new();
3561 smartlist_t
*successful_uploads
= smartlist_new();
3562 routerstatus_t
*hs_dir
;
3563 for (i
= 0; i
< smartlist_len(descs
); i
++) {
3564 rend_encoded_v2_service_descriptor_t
*desc
= smartlist_get(descs
, i
);
3565 /** If any HSDirs are specified, they should be used instead of
3566 * the responsible directories */
3567 if (hs_dirs
&& smartlist_len(hs_dirs
) > 0) {
3568 smartlist_add_all(responsible_dirs
, hs_dirs
);
3570 /* Determine responsible dirs. */
3571 if (hid_serv_get_responsible_directories(responsible_dirs
,
3572 desc
->desc_id
) < 0) {
3573 log_warn(LD_REND
, "Could not determine the responsible hidden service "
3574 "directories to post descriptors to.");
3575 control_event_hs_descriptor_upload(service_id
,
3581 for (j
= 0; j
< smartlist_len(responsible_dirs
); j
++) {
3582 char desc_id_base32
[REND_DESC_ID_V2_LEN_BASE32
+ 1];
3585 rend_data_t
*rend_data
;
3586 hs_dir
= smartlist_get(responsible_dirs
, j
);
3587 if (smartlist_contains_digest(renddesc
->successful_uploads
,
3588 hs_dir
->identity_digest
))
3589 /* Don't upload descriptor if we succeeded in doing so last time. */
3591 node
= node_get_by_id(hs_dir
->identity_digest
);
3592 if (!node
|| !node_has_descriptor(node
)) {
3593 log_info(LD_REND
, "Not launching upload for for v2 descriptor to "
3594 "hidden service directory %s; we don't have its "
3595 "router descriptor. Queuing for later upload.",
3596 safe_str_client(routerstatus_describe(hs_dir
)));
3600 /* Send publish request. */
3602 /* We need the service ID to identify which service did the upload
3603 * request. Lookup is made in rend_service_desc_has_uploaded(). */
3604 rend_data
= rend_data_client_create(service_id
, desc
->desc_id
, NULL
,
3606 directory_request_t
*req
=
3607 directory_request_new(DIR_PURPOSE_UPLOAD_RENDDESC_V2
);
3608 directory_request_set_routerstatus(req
, hs_dir
);
3609 directory_request_set_indirection(req
, DIRIND_ANONYMOUS
);
3610 directory_request_set_payload(req
,
3611 desc
->desc_str
, strlen(desc
->desc_str
));
3612 directory_request_set_rend_query(req
, rend_data
);
3613 directory_initiate_request(req
);
3614 directory_request_free(req
);
3616 rend_data_free(rend_data
);
3617 base32_encode(desc_id_base32
, sizeof(desc_id_base32
),
3618 desc
->desc_id
, DIGEST_LEN
);
3619 hs_dir_ip
= tor_dup_ip(hs_dir
->addr
);
3620 log_info(LD_REND
, "Launching upload for v2 descriptor for "
3621 "service '%s' with descriptor ID '%s' with validity "
3622 "of %d seconds to hidden service directory '%s' on "
3624 safe_str_client(service_id
),
3625 safe_str_client(desc_id_base32
),
3630 control_event_hs_descriptor_upload(service_id
,
3631 hs_dir
->identity_digest
,
3633 tor_free(hs_dir_ip
);
3634 /* Remember successful upload to this router for next time. */
3635 if (!smartlist_contains_digest(successful_uploads
,
3636 hs_dir
->identity_digest
))
3637 smartlist_add(successful_uploads
, hs_dir
->identity_digest
);
3639 smartlist_clear(responsible_dirs
);
3641 if (!failed_upload
) {
3642 if (renddesc
->successful_uploads
) {
3643 SMARTLIST_FOREACH(renddesc
->successful_uploads
, char *, c
, tor_free(c
););
3644 smartlist_free(renddesc
->successful_uploads
);
3645 renddesc
->successful_uploads
= NULL
;
3647 renddesc
->all_uploads_performed
= 1;
3649 /* Remember which routers worked this time, so that we don't upload the
3650 * descriptor to them again. */
3651 if (!renddesc
->successful_uploads
)
3652 renddesc
->successful_uploads
= smartlist_new();
3653 SMARTLIST_FOREACH(successful_uploads
, const char *, c
, {
3654 if (!smartlist_contains_digest(renddesc
->successful_uploads
, c
)) {
3655 char *hsdir_id
= tor_memdup(c
, DIGEST_LEN
);
3656 smartlist_add(renddesc
->successful_uploads
, hsdir_id
);
3661 smartlist_free(responsible_dirs
);
3662 smartlist_free(successful_uploads
);
3665 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
3666 * and upload it/them to the responsible hidden service directories.
3669 upload_service_descriptor(rend_service_t
*service
)
3671 time_t now
= time(NULL
);
3673 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
3676 rendpostperiod
= get_options()->RendPostPeriod
;
3678 networkstatus_t
*c
= networkstatus_get_latest_consensus();
3679 if (c
&& smartlist_len(c
->routerstatus_list
) > 0) {
3680 int seconds_valid
, i
, j
, num_descs
;
3681 smartlist_t
*descs
= smartlist_new();
3682 smartlist_t
*client_cookies
= smartlist_new();
3683 /* Either upload a single descriptor (including replicas) or one
3684 * descriptor for each authorized client in case of authorization
3685 * type 'stealth'. */
3686 num_descs
= service
->auth_type
== REND_STEALTH_AUTH
?
3687 smartlist_len(service
->clients
) : 1;
3688 for (j
= 0; j
< num_descs
; j
++) {
3689 crypto_pk_t
*client_key
= NULL
;
3690 rend_authorized_client_t
*client
= NULL
;
3691 smartlist_clear(client_cookies
);
3692 switch (service
->auth_type
) {
3694 /* Do nothing here. */
3696 case REND_BASIC_AUTH
:
3697 SMARTLIST_FOREACH(service
->clients
, rend_authorized_client_t
*,
3698 cl
, smartlist_add(client_cookies
, cl
->descriptor_cookie
));
3700 case REND_STEALTH_AUTH
:
3701 client
= smartlist_get(service
->clients
, j
);
3702 client_key
= client
->client_key
;
3703 smartlist_add(client_cookies
, client
->descriptor_cookie
);
3706 /* Encode the current descriptor. */
3707 seconds_valid
= rend_encode_v2_descriptors(descs
, service
->desc
,
3712 if (seconds_valid
< 0) {
3713 log_warn(LD_BUG
, "Internal error: couldn't encode service "
3714 "descriptor; not uploading.");
3715 smartlist_free(descs
);
3716 smartlist_free(client_cookies
);
3719 rend_get_service_id(service
->desc
->pk
, serviceid
);
3720 if (get_options()->PublishHidServDescriptors
) {
3721 /* Post the current descriptors to the hidden service directories. */
3722 log_info(LD_REND
, "Launching upload for hidden service %s",
3724 directory_post_to_hs_dir(service
->desc
, descs
, NULL
, serviceid
,
3727 /* Free memory for descriptors. */
3728 for (i
= 0; i
< smartlist_len(descs
); i
++)
3729 rend_encoded_v2_service_descriptor_free(smartlist_get(descs
, i
));
3730 smartlist_clear(descs
);
3731 /* Update next upload time. */
3732 if (seconds_valid
- REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3734 service
->next_upload_time
= now
+ rendpostperiod
;
3735 else if (seconds_valid
< REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
)
3736 service
->next_upload_time
= now
+ seconds_valid
+ 1;
3738 service
->next_upload_time
= now
+ seconds_valid
-
3739 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
+ 1;
3740 /* Post also the next descriptors, if necessary. */
3741 if (seconds_valid
< REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
) {
3742 seconds_valid
= rend_encode_v2_descriptors(descs
, service
->desc
,
3747 if (seconds_valid
< 0) {
3748 log_warn(LD_BUG
, "Internal error: couldn't encode service "
3749 "descriptor; not uploading.");
3750 smartlist_free(descs
);
3751 smartlist_free(client_cookies
);
3754 if (get_options()->PublishHidServDescriptors
) {
3755 directory_post_to_hs_dir(service
->desc
, descs
, NULL
, serviceid
,
3758 /* Free memory for descriptors. */
3759 for (i
= 0; i
< smartlist_len(descs
); i
++)
3760 rend_encoded_v2_service_descriptor_free(smartlist_get(descs
, i
));
3761 smartlist_clear(descs
);
3764 smartlist_free(descs
);
3765 smartlist_free(client_cookies
);
3767 if (get_options()->PublishHidServDescriptors
) {
3768 log_info(LD_REND
, "Successfully uploaded v2 rend descriptors!");
3770 log_info(LD_REND
, "Successfully stored created v2 rend descriptors!");
3774 /* If not uploaded, try again in one minute. */
3776 service
->next_upload_time
= now
+ 60;
3778 /* Unmark dirty flag of this service. */
3779 service
->desc_is_dirty
= 0;
3782 /** Return the number of INTRODUCE2 cells this hidden service has received
3783 * from this intro point. */
3785 intro_point_accepted_intro_count(rend_intro_point_t
*intro
)
3787 return intro
->accepted_introduce2_count
;
3790 /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
3791 * should stop publishing it in new descriptors and eventually close
3794 intro_point_should_expire_now(rend_intro_point_t
*intro
,
3797 tor_assert(intro
!= NULL
);
3799 if (intro
->time_published
== -1) {
3800 /* Don't expire an intro point if we haven't even published it yet. */
3804 if (intro_point_accepted_intro_count(intro
) >=
3805 intro
->max_introductions
) {
3806 /* This intro point has been used too many times. Expire it now. */
3810 if (intro
->time_to_expire
== -1) {
3811 /* This intro point has been published, but we haven't picked an
3812 * expiration time for it. Pick one now. */
3813 int intro_point_lifetime_seconds
=
3814 crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS
,
3815 INTRO_POINT_LIFETIME_MAX_SECONDS
);
3817 /* Start the expiration timer now, rather than when the intro
3818 * point was first published. There shouldn't be much of a time
3820 intro
->time_to_expire
= now
+ intro_point_lifetime_seconds
;
3825 /* This intro point has a time to expire set already. Use it. */
3826 return (now
>= intro
->time_to_expire
);
3829 /** Iterate over intro points in the given service and remove the invalid
3830 * ones. For an intro point object to be considered invalid, the circuit
3831 * _and_ node need to have disappeared.
3833 * If the intro point should expire, it's placed into the expiring_nodes
3834 * list of the service and removed from the active intro nodes list.
3836 * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
3838 * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
3839 * circuit disappeared but the node is still in the consensus. */
3841 remove_invalid_intro_points(rend_service_t
*service
,
3842 smartlist_t
*exclude_nodes
,
3843 smartlist_t
*retry_nodes
, time_t now
)
3845 tor_assert(service
);
3847 /* Remove any expired nodes that doesn't have a circuit. */
3848 SMARTLIST_FOREACH_BEGIN(service
->expiring_nodes
, rend_intro_point_t
*,
3850 origin_circuit_t
*intro_circ
=
3851 find_intro_circuit(intro
, service
->pk_digest
);
3855 /* No more circuit, cleanup the into point object. */
3856 SMARTLIST_DEL_CURRENT(service
->expiring_nodes
, intro
);
3857 rend_intro_point_free(intro
);
3858 } SMARTLIST_FOREACH_END(intro
);
3860 SMARTLIST_FOREACH_BEGIN(service
->intro_nodes
, rend_intro_point_t
*,
3862 /* Find the introduction point node object. */
3863 const node_t
*node
=
3864 node_get_by_id(intro
->extend_info
->identity_digest
);
3865 /* Find the intro circuit, this might be NULL. */
3866 origin_circuit_t
*intro_circ
=
3867 find_intro_circuit(intro
, service
->pk_digest
);
3869 /* Add the valid node to the exclusion list so we don't try to establish
3870 * an introduction point to it again. */
3871 if (node
&& exclude_nodes
) {
3872 smartlist_add(exclude_nodes
, (void*) node
);
3875 /* First, make sure we still have a valid circuit for this intro point.
3876 * If we dont, we'll give up on it and make a new one. */
3877 if (intro_circ
== NULL
) {
3878 log_info(LD_REND
, "Attempting to retry on %s as intro point for %s"
3879 " (circuit disappeared).",
3880 safe_str_client(extend_info_describe(intro
->extend_info
)),
3881 safe_str_client(service
->service_id
));
3882 /* We've lost the circuit for this intro point, flag it so it can be
3883 * accounted for when considiring uploading a descriptor. */
3884 intro
->circuit_established
= 0;
3886 /* Node is gone or we've reached our maximum circuit creationg retry
3887 * count, clean up everything, we'll find a new one. */
3889 intro
->circuit_retries
>= MAX_INTRO_POINT_CIRCUIT_RETRIES
) {
3890 rend_intro_point_free(intro
);
3891 SMARTLIST_DEL_CURRENT(service
->intro_nodes
, intro
);
3892 /* We've just killed the intro point, nothing left to do. */
3896 /* The intro point is still alive so let's try to use it again because
3897 * we have a published descriptor containing it. Keep the intro point
3898 * in the intro_nodes list because it's still valid, we are rebuilding
3899 * a circuit to it. */
3901 smartlist_add(retry_nodes
, intro
);
3904 /* else, the circuit is valid so in both cases, node being alive or not,
3905 * we leave the circuit and intro point object as is. Closing the
3906 * circuit here would leak new consensus timing and freeing the intro
3907 * point object would make the intro circuit unusable. */
3909 /* Now, check if intro point should expire. If it does, queue it so
3910 * it can be cleaned up once it has been replaced properly. */
3911 if (intro_point_should_expire_now(intro
, now
)) {
3912 log_info(LD_REND
, "Expiring %s as intro point for %s.",
3913 safe_str_client(extend_info_describe(intro
->extend_info
)),
3914 safe_str_client(service
->service_id
));
3915 smartlist_add(service
->expiring_nodes
, intro
);
3916 SMARTLIST_DEL_CURRENT(service
->intro_nodes
, intro
);
3917 /* Intro point is expired, we need a new one thus don't consider it
3918 * anymore has a valid established intro point. */
3919 intro
->circuit_established
= 0;
3921 } SMARTLIST_FOREACH_END(intro
);
3924 /** A new descriptor has been successfully uploaded for the given
3925 * <b>rend_data</b>. Remove and free the expiring nodes from the associated
3928 rend_service_desc_has_uploaded(const rend_data_t
*rend_data
)
3930 rend_service_t
*service
;
3931 const char *onion_address
;
3933 tor_assert(rend_data
);
3935 onion_address
= rend_data_get_address(rend_data
);
3937 service
= rend_service_get_by_service_id(onion_address
);
3938 if (service
== NULL
) {
3942 SMARTLIST_FOREACH_BEGIN(service
->expiring_nodes
, rend_intro_point_t
*,
3944 origin_circuit_t
*intro_circ
=
3945 find_intro_circuit(intro
, service
->pk_digest
);
3946 if (intro_circ
!= NULL
) {
3947 circuit_mark_for_close(TO_CIRCUIT(intro_circ
),
3948 END_CIRC_REASON_FINISHED
);
3950 SMARTLIST_DEL_CURRENT(service
->expiring_nodes
, intro
);
3951 rend_intro_point_free(intro
);
3952 } SMARTLIST_FOREACH_END(intro
);
3955 /** Don't try to build more than this many circuits before giving up
3956 * for a while. Dynamically calculated based on the configured number of
3957 * introduction points for the service, n_intro_points_wanted. */
3959 rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted
)
3961 /* Allow all but one of the initial connections to fail and be
3962 * retried. (If all fail, we *want* to wait, because something is broken.) */
3963 tor_assert(n_intro_points_wanted
<= NUM_INTRO_POINTS_MAX
);
3965 /* For the normal use case, 3 intro points plus 2 extra for performance and
3966 * allow that twice because once every 24h or so, we can do it twice for two
3967 * descriptors that is the current one and the next one. So (3 + 2) * 2 ==
3968 * 12 allowed attempts for one period. */
3969 return ((n_intro_points_wanted
+ NUM_INTRO_POINTS_EXTRA
) * 2);
3972 /** For every service, check how many intro points it currently has, and:
3973 * - Invalidate introdution points based on specific criteria, see
3974 * remove_invalid_intro_points comments.
3975 * - Pick new intro points as necessary.
3976 * - Launch circuits to any new intro points.
3978 * This is called once a second by the main loop.
3981 rend_consider_services_intro_points(time_t now
)
3984 const or_options_t
*options
= get_options();
3985 /* Are we in single onion mode? */
3986 const int allow_direct
= rend_service_allow_non_anonymous_connection(
3988 /* List of nodes we need to _exclude_ when choosing a new node to
3989 * establish an intro point to. */
3990 smartlist_t
*exclude_nodes
;
3991 /* List of nodes we need to retry to build a circuit on them because the
3992 * node is valid but circuit died. */
3993 smartlist_t
*retry_nodes
;
3995 if (!have_completed_a_circuit())
3998 exclude_nodes
= smartlist_new();
3999 retry_nodes
= smartlist_new();
4001 SMARTLIST_FOREACH_BEGIN(rend_service_list
, rend_service_t
*, service
) {
4003 /* Number of intro points we want to open and add to the intro nodes
4004 * list of the service. */
4005 unsigned int n_intro_points_to_open
;
4006 /* Have an unsigned len so we can use it to compare values else gcc is
4007 * not happy with unmatching signed comparaison. */
4008 unsigned int intro_nodes_len
;
4009 /* Different service are allowed to have the same introduction point as
4010 * long as they are on different circuit thus why we clear this list. */
4011 smartlist_clear(exclude_nodes
);
4012 smartlist_clear(retry_nodes
);
4014 /* Cleanup the invalid intro points and save the node objects, if any,
4015 * in the exclude_nodes and retry_nodes lists. */
4016 remove_invalid_intro_points(service
, exclude_nodes
, retry_nodes
, now
);
4018 /* This retry period is important here so we don't stress circuit
4021 if (now
> service
->intro_period_started
+ INTRO_CIRC_RETRY_PERIOD
) {
4022 /* One period has elapsed:
4023 * - if we stopped, we can try building circuits again,
4024 * - if we haven't, we reset the circuit creation counts. */
4025 rend_log_intro_limit(service
, LOG_INFO
);
4026 service
->intro_period_started
= now
;
4027 service
->n_intro_circuits_launched
= 0;
4028 } else if (service
->n_intro_circuits_launched
>=
4029 rend_max_intro_circs_per_period(
4030 service
->n_intro_points_wanted
)) {
4031 /* We have failed too many times in this period; wait for the next
4032 * one before we try to initiate any more connections. */
4033 rend_log_intro_limit(service
, LOG_WARN
);
4037 /* Let's try to rebuild circuit on the nodes we want to retry on. */
4038 SMARTLIST_FOREACH_BEGIN(retry_nodes
, rend_intro_point_t
*, intro
) {
4039 r
= rend_service_launch_establish_intro(service
, intro
);
4041 log_warn(LD_REND
, "Error launching circuit to node %s for service %s.",
4042 safe_str_client(extend_info_describe(intro
->extend_info
)),
4043 safe_str_client(service
->service_id
));
4044 /* Unable to launch a circuit to that intro point, remove it from
4045 * the valid list so we can create a new one. */
4046 smartlist_remove(service
->intro_nodes
, intro
);
4047 rend_intro_point_free(intro
);
4050 intro
->circuit_retries
++;
4051 } SMARTLIST_FOREACH_END(intro
);
4053 /* Avoid mismatched signed comparaison below. */
4054 intro_nodes_len
= (unsigned int) smartlist_len(service
->intro_nodes
);
4056 /* Quiescent state, we have more or the equal amount of wanted node for
4057 * this service. Proceed to the next service. We can have more nodes
4058 * because we launch extra preemptive circuits if our intro nodes list was
4059 * originally empty for performance reasons. */
4060 if (intro_nodes_len
>= service
->n_intro_points_wanted
) {
4064 /* Number of intro points we want to open which is the wanted amount minus
4065 * the current amount of valid nodes. We know that this won't underflow
4066 * because of the check above. */
4067 n_intro_points_to_open
= service
->n_intro_points_wanted
- intro_nodes_len
;
4068 if (intro_nodes_len
== 0) {
4069 /* We want to end up with n_intro_points_wanted intro points, but if
4070 * we have no intro points at all (chances are they all cycled or we
4071 * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
4072 * and use the first n_intro_points_wanted that complete. See proposal
4073 * #155, section 4 for the rationale of this which is purely for
4076 * The ones after the first n_intro_points_to_open will be converted
4077 * to 'general' internal circuits in rend_service_intro_has_opened(),
4078 * and then we'll drop them from the list of intro points. */
4079 n_intro_points_to_open
+= NUM_INTRO_POINTS_EXTRA
;
4082 for (i
= 0; i
< (int) n_intro_points_to_open
; i
++) {
4084 rend_intro_point_t
*intro
;
4085 router_crn_flags_t flags
= CRN_NEED_UPTIME
|CRN_NEED_DESC
;
4086 router_crn_flags_t direct_flags
= flags
;
4087 direct_flags
|= CRN_PREF_ADDR
;
4088 direct_flags
|= CRN_DIRECT_CONN
;
4090 node
= router_choose_random_node(exclude_nodes
,
4091 options
->ExcludeNodes
,
4092 allow_direct
? direct_flags
: flags
);
4093 /* If we are in single onion mode, retry node selection for a 3-hop
4095 if (allow_direct
&& !node
) {
4097 "Unable to find an intro point that we can connect to "
4098 "directly for %s, falling back to a 3-hop path.",
4099 safe_str_client(service
->service_id
));
4100 node
= router_choose_random_node(exclude_nodes
,
4101 options
->ExcludeNodes
, flags
);
4106 "We only have %d introduction points established for %s; "
4108 smartlist_len(service
->intro_nodes
),
4109 safe_str_client(service
->service_id
),
4110 n_intro_points_to_open
);
4113 /* Add the choosen node to the exclusion list in order to avoid picking
4114 * it again in the next iteration. */
4115 smartlist_add(exclude_nodes
, (void*)node
);
4116 intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
4117 /* extend_info is for clients, so we want the multi-hop primary ORPort,
4118 * even if we are a single onion service and intend to connect to it
4119 * directly ourselves. */
4120 intro
->extend_info
= extend_info_from_node(node
, 0);
4121 if (BUG(intro
->extend_info
== NULL
)) {
4124 intro
->intro_key
= crypto_pk_new();
4125 const int fail
= crypto_pk_generate_key(intro
->intro_key
);
4127 intro
->time_published
= -1;
4128 intro
->time_to_expire
= -1;
4129 intro
->max_introductions
=
4130 crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS
,
4131 INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS
);
4132 smartlist_add(service
->intro_nodes
, intro
);
4133 log_info(LD_REND
, "Picked router %s as an intro point for %s.",
4134 safe_str_client(node_describe(node
)),
4135 safe_str_client(service
->service_id
));
4136 /* Establish new introduction circuit to our chosen intro point. */
4137 r
= rend_service_launch_establish_intro(service
, intro
);
4139 log_warn(LD_REND
, "Error launching circuit to node %s for service %s.",
4140 safe_str_client(extend_info_describe(intro
->extend_info
)),
4141 safe_str_client(service
->service_id
));
4142 /* This funcion will be called again by the main loop so this intro
4143 * point without a intro circuit will be retried on or removed after
4144 * a maximum number of attempts. */
4147 } SMARTLIST_FOREACH_END(service
);
4148 smartlist_free(exclude_nodes
);
4149 smartlist_free(retry_nodes
);
4152 #define MIN_REND_INITIAL_POST_DELAY (30)
4153 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4155 /** Regenerate and upload rendezvous service descriptors for all
4156 * services, if necessary. If the descriptor has been dirty enough
4157 * for long enough, definitely upload; else only upload when the
4158 * periodic timeout has expired.
4160 * For the first upload, pick a random time between now and two periods
4161 * from now, and pick it independently for each service.
4164 rend_consider_services_upload(time_t now
)
4167 rend_service_t
*service
;
4168 const or_options_t
*options
= get_options();
4169 int rendpostperiod
= options
->RendPostPeriod
;
4170 int rendinitialpostdelay
= (options
->TestingTorNetwork
?
4171 MIN_REND_INITIAL_POST_DELAY_TESTING
:
4172 MIN_REND_INITIAL_POST_DELAY
);
4174 for (i
=0; i
< smartlist_len(rend_service_list
); ++i
) {
4175 service
= smartlist_get(rend_service_list
, i
);
4176 if (!service
->next_upload_time
) { /* never been uploaded yet */
4177 /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4178 * the descriptor is stable before being published. See comment below. */
4179 service
->next_upload_time
=
4180 now
+ rendinitialpostdelay
+ crypto_rand_int(2*rendpostperiod
);
4181 /* Single Onion Services prioritise availability over hiding their
4182 * startup time, as their IP address is publicly discoverable anyway.
4184 if (rend_service_reveal_startup_time(options
)) {
4185 service
->next_upload_time
= now
+ rendinitialpostdelay
;
4188 /* Does every introduction points have been established? */
4189 unsigned int intro_points_ready
=
4190 count_established_intro_points(service
) >=
4191 service
->n_intro_points_wanted
;
4192 if (intro_points_ready
&&
4193 (service
->next_upload_time
< now
||
4194 (service
->desc_is_dirty
&&
4195 service
->desc_is_dirty
< now
-rendinitialpostdelay
))) {
4196 /* if it's time, or if the directory servers have a wrong service
4197 * descriptor and ours has been stable for rendinitialpostdelay seconds,
4198 * upload a new one of each format. */
4199 rend_service_update_descriptor(service
);
4200 upload_service_descriptor(service
);
4205 /** True if the list of available router descriptors might have changed so
4206 * that we should have a look whether we can republish previously failed
4207 * rendezvous service descriptors. */
4208 static int consider_republishing_rend_descriptors
= 1;
4210 /** Called when our internal view of the directory has changed, so that we
4211 * might have router descriptors of hidden service directories available that
4212 * we did not have before. */
4214 rend_hsdir_routers_changed(void)
4216 consider_republishing_rend_descriptors
= 1;
4219 /** Consider republication of v2 rendezvous service descriptors that failed
4220 * previously, but without regenerating descriptor contents.
4223 rend_consider_descriptor_republication(void)
4226 rend_service_t
*service
;
4228 if (!consider_republishing_rend_descriptors
)
4230 consider_republishing_rend_descriptors
= 0;
4232 if (!get_options()->PublishHidServDescriptors
)
4235 for (i
=0; i
< smartlist_len(rend_service_list
); ++i
) {
4236 service
= smartlist_get(rend_service_list
, i
);
4237 if (service
->desc
&& !service
->desc
->all_uploads_performed
) {
4238 /* If we failed in uploading a descriptor last time, try again *without*
4239 * updating the descriptor's contents. */
4240 upload_service_descriptor(service
);
4245 /** Log the status of introduction points for all rendezvous services
4246 * at log severity <b>severity</b>.
4249 rend_service_dump_stats(int severity
)
4252 rend_service_t
*service
;
4253 rend_intro_point_t
*intro
;
4254 const char *safe_name
;
4255 origin_circuit_t
*circ
;
4257 for (i
=0; i
< smartlist_len(rend_service_list
); ++i
) {
4258 service
= smartlist_get(rend_service_list
, i
);
4259 tor_log(severity
, LD_GENERAL
, "Service configured in %s:",
4260 rend_service_escaped_dir(service
));
4261 for (j
=0; j
< smartlist_len(service
->intro_nodes
); ++j
) {
4262 intro
= smartlist_get(service
->intro_nodes
, j
);
4263 safe_name
= safe_str_client(intro
->extend_info
->nickname
);
4265 circ
= find_intro_circuit(intro
, service
->pk_digest
);
4267 tor_log(severity
, LD_GENERAL
, " Intro point %d at %s: no circuit",
4271 tor_log(severity
, LD_GENERAL
, " Intro point %d at %s: circuit is %s",
4272 j
, safe_name
, circuit_state_to_string(circ
->base_
.state
));
4277 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
4278 * 'circ', and look up the port and address based on conn-\>port.
4279 * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
4280 * for which the circuit should be closed, -1 on other failure,
4284 rend_service_set_connection_addr_port(edge_connection_t
*conn
,
4285 origin_circuit_t
*circ
)
4287 rend_service_t
*service
;
4288 char serviceid
[REND_SERVICE_ID_LEN_BASE32
+1];
4289 const char *rend_pk_digest
;
4291 tor_assert(circ
->base_
.purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
);
4292 tor_assert(circ
->rend_data
);
4293 log_debug(LD_REND
,"beginning to hunt for addr/port");
4294 rend_pk_digest
= (char *) rend_data_get_pk_digest(circ
->rend_data
, NULL
);
4295 base32_encode(serviceid
, REND_SERVICE_ID_LEN_BASE32
+1,
4296 rend_pk_digest
, REND_SERVICE_ID_LEN
);
4297 service
= rend_service_get_by_pk_digest(rend_pk_digest
);
4299 log_warn(LD_REND
, "Couldn't find any service associated with pk %s on "
4300 "rendezvous circuit %u; closing.",
4301 serviceid
, (unsigned)circ
->base_
.n_circ_id
);
4304 if (service
->max_streams_per_circuit
> 0) {
4305 /* Enforce the streams-per-circuit limit, and refuse to provide a
4306 * mapping if this circuit will exceed the limit. */
4307 #define MAX_STREAM_WARN_INTERVAL 600
4308 static struct ratelim_t stream_ratelim
=
4309 RATELIM_INIT(MAX_STREAM_WARN_INTERVAL
);
4310 if (circ
->rend_data
->nr_streams
>= service
->max_streams_per_circuit
) {
4311 log_fn_ratelim(&stream_ratelim
, LOG_WARN
, LD_REND
,
4312 "Maximum streams per circuit limit reached on rendezvous "
4313 "circuit %u; %s. Circuit has %d out of %d streams.",
4314 (unsigned)circ
->base_
.n_circ_id
,
4315 service
->max_streams_close_circuit
?
4317 "ignoring open stream request",
4318 circ
->rend_data
->nr_streams
,
4319 service
->max_streams_per_circuit
);
4320 return service
->max_streams_close_circuit
? -2 : -1;
4324 if (hs_set_conn_addr_port(service
->ports
, conn
) == 0) {
4325 /* Successfully set the port to the connection. We are done. */
4330 "No virtual port mapping exists for port %d on service %s",
4331 conn
->base_
.port
, serviceid
);
4333 if (service
->allow_unknown_ports
)
4339 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4342 rend_service_non_anonymous_mode_consistent(const or_options_t
*options
)
4344 /* !! is used to make these options boolean */
4345 return (!! options
->HiddenServiceSingleHopMode
==
4346 !! options
->HiddenServiceNonAnonymousMode
);
4349 /* Do the options allow onion services to make direct (non-anonymous)
4350 * connections to introduction or rendezvous points?
4351 * Must only be called after options_validate_single_onion() has successfully
4352 * checked onion service option consistency.
4353 * Returns true if tor is in HiddenServiceSingleHopMode. */
4355 rend_service_allow_non_anonymous_connection(const or_options_t
*options
)
4357 tor_assert(rend_service_non_anonymous_mode_consistent(options
));
4358 return options
->HiddenServiceSingleHopMode
? 1 : 0;
4361 /* Do the options allow us to reveal the exact startup time of the onion
4363 * Single Onion Services prioritise availability over hiding their
4364 * startup time, as their IP address is publicly discoverable anyway.
4365 * Must only be called after options_validate_single_onion() has successfully
4366 * checked onion service option consistency.
4367 * Returns true if tor is in non-anonymous hidden service mode. */
4369 rend_service_reveal_startup_time(const or_options_t
*options
)
4371 tor_assert(rend_service_non_anonymous_mode_consistent(options
));
4372 return rend_service_non_anonymous_mode_enabled(options
);
4375 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4377 * Must only be called after options_validate_single_onion() has successfully
4378 * checked onion service option consistency.
4381 rend_service_non_anonymous_mode_enabled(const or_options_t
*options
)
4383 tor_assert(rend_service_non_anonymous_mode_consistent(options
));
4384 return options
->HiddenServiceNonAnonymousMode
? 1 : 0;
4387 #ifdef TOR_UNIT_TESTS
4390 set_rend_service_list(smartlist_t
*new_list
)
4392 rend_service_list
= new_list
;
4396 set_rend_rend_service_staging_list(smartlist_t
*new_list
)
4398 rend_service_staging_list
= new_list
;
4401 #endif /* defined(TOR_UNIT_TESTS) */