Split main.c into main.c and mainloop.c
[tor.git] / src / feature / rend / rendservice.c
blobceb4d958d79a07269ea4d17dc299f58242871db7
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2018, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rendservice.c
7 * \brief The hidden-service side of rendezvous functionality.
8 **/
10 #define RENDSERVICE_PRIVATE
12 #include "core/or/or.h"
13 #include "feature/client/circpathbias.h"
14 #include "core/or/circuitbuild.h"
15 #include "core/or/circuitlist.h"
16 #include "core/or/circuituse.h"
17 #include "app/config/config.h"
18 #include "feature/control/control.h"
19 #include "lib/crypt_ops/crypto_dh.h"
20 #include "lib/crypt_ops/crypto_rand.h"
21 #include "lib/crypt_ops/crypto_util.h"
22 #include "feature/dircache/directory.h"
23 #include "feature/hs/hs_common.h"
24 #include "feature/hs/hs_config.h"
25 #include "core/mainloop/mainloop.h"
26 #include "feature/nodelist/networkstatus.h"
27 #include "feature/nodelist/nodelist.h"
28 #include "core/or/policies.h"
29 #include "feature/rend/rendclient.h"
30 #include "feature/rend/rendcommon.h"
31 #include "feature/rend/rendservice.h"
32 #include "feature/relay/router.h"
33 #include "core/or/relay.h"
34 #include "feature/stats/rephist.h"
35 #include "feature/hs_common/replaycache.h"
36 #include "feature/nodelist/node_select.h"
37 #include "feature/nodelist/routerparse.h"
38 #include "feature/nodelist/routerset.h"
39 #include "lib/encoding/confline.h"
40 #include "lib/net/resolve.h"
42 #include "core/or/cpath_build_state_st.h"
43 #include "core/or/crypt_path_st.h"
44 #include "core/or/crypt_path_reference_st.h"
45 #include "core/or/edge_connection_st.h"
46 #include "core/or/extend_info_st.h"
47 #include "feature/nodelist/networkstatus_st.h"
48 #include "core/or/origin_circuit_st.h"
49 #include "feature/rend/rend_authorized_client_st.h"
50 #include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
51 #include "feature/rend/rend_intro_point_st.h"
52 #include "feature/rend/rend_service_descriptor_st.h"
53 #include "feature/nodelist/routerstatus_st.h"
55 #ifdef HAVE_FCNTL_H
56 #include <fcntl.h>
57 #endif
58 #ifdef HAVE_UNISTD_H
59 #include <unistd.h>
60 #endif
61 #ifdef HAVE_SYS_STAT_H
62 #include <sys/stat.h>
63 #endif
65 struct rend_service_t;
66 static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
67 const char *pk_digest);
68 static rend_intro_point_t *find_intro_point(origin_circuit_t *circ);
69 static rend_intro_point_t *find_expiring_intro_point(
70 struct rend_service_t *service, origin_circuit_t *circ);
72 static extend_info_t *find_rp_for_intro(
73 const rend_intro_cell_t *intro,
74 char **err_msg_out);
76 static int intro_point_accepted_intro_count(rend_intro_point_t *intro);
77 static int intro_point_should_expire_now(rend_intro_point_t *intro,
78 time_t now);
79 static int rend_service_derive_key_digests(struct rend_service_t *s);
80 static int rend_service_load_keys(struct rend_service_t *s);
81 static int rend_service_load_auth_keys(struct rend_service_t *s,
82 const char *hfname);
83 static struct rend_service_t *rend_service_get_by_pk_digest(
84 const char* digest);
85 static struct rend_service_t *rend_service_get_by_service_id(const char *id);
86 static const char *rend_service_escaped_dir(
87 const struct rend_service_t *s);
89 static ssize_t rend_service_parse_intro_for_v0_or_v1(
90 rend_intro_cell_t *intro,
91 const uint8_t *buf,
92 size_t plaintext_len,
93 char **err_msg_out);
94 static ssize_t rend_service_parse_intro_for_v2(
95 rend_intro_cell_t *intro,
96 const uint8_t *buf,
97 size_t plaintext_len,
98 char **err_msg_out);
99 static ssize_t rend_service_parse_intro_for_v3(
100 rend_intro_cell_t *intro,
101 const uint8_t *buf,
102 size_t plaintext_len,
103 char **err_msg_out);
105 static int rend_service_check_private_dir(const or_options_t *options,
106 const rend_service_t *s,
107 int create);
108 static const smartlist_t* rend_get_service_list(
109 const smartlist_t* substitute_service_list);
110 static smartlist_t* rend_get_service_list_mutable(
111 smartlist_t* substitute_service_list);
112 static int rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted);
114 /* Hidden service directory file names:
115 * new file names should be added to rend_service_add_filenames_to_list()
116 * for sandboxing purposes. */
117 static const char *private_key_fname = "private_key";
118 static const char *hostname_fname = "hostname";
119 static const char *client_keys_fname = "client_keys";
120 static const char *sos_poison_fname = "onion_service_non_anonymous";
122 /** A list of rend_service_t's for services run on this OP. */
123 static smartlist_t *rend_service_list = NULL;
124 /** A list of rend_service_t's for services run on this OP which is used as a
125 * staging area before they are put in the main list in order to prune dying
126 * service on config reload. */
127 static smartlist_t *rend_service_staging_list = NULL;
129 /* Like rend_get_service_list_mutable, but returns a read-only list. */
130 static const smartlist_t*
131 rend_get_service_list(const smartlist_t* substitute_service_list)
133 /* It is safe to cast away the const here, because
134 * rend_get_service_list_mutable does not actually modify the list */
135 return rend_get_service_list_mutable((smartlist_t*)substitute_service_list);
138 /* Return a mutable list of hidden services.
139 * If substitute_service_list is not NULL, return it.
140 * Otherwise, check if the global rend_service_list is non-NULL, and if so,
141 * return it.
142 * Otherwise, log a BUG message and return NULL.
143 * */
144 static smartlist_t*
145 rend_get_service_list_mutable(smartlist_t* substitute_service_list)
147 if (substitute_service_list) {
148 return substitute_service_list;
151 /* If no special service list is provided, then just use the global one. */
153 if (BUG(!rend_service_list)) {
154 /* No global HS list, which is a programmer error. */
155 return NULL;
158 return rend_service_list;
161 /** Tells if onion service <b>s</b> is ephemeral.
163 static unsigned int
164 rend_service_is_ephemeral(const struct rend_service_t *s)
166 return (s->directory == NULL);
169 /** Returns a escaped string representation of the service, <b>s</b>.
171 static const char *
172 rend_service_escaped_dir(const struct rend_service_t *s)
174 return rend_service_is_ephemeral(s) ? "[EPHEMERAL]" : escaped(s->directory);
177 /** Return the number of rendezvous services we have configured. */
179 rend_num_services(void)
181 if (!rend_service_list)
182 return 0;
183 return smartlist_len(rend_service_list);
186 /** Helper: free storage held by a single service authorized client entry. */
187 void
188 rend_authorized_client_free_(rend_authorized_client_t *client)
190 if (!client)
191 return;
192 if (client->client_key)
193 crypto_pk_free(client->client_key);
194 if (client->client_name)
195 memwipe(client->client_name, 0, strlen(client->client_name));
196 tor_free(client->client_name);
197 memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
198 tor_free(client);
201 /** Helper for strmap_free. */
202 static void
203 rend_authorized_client_free_void(void *authorized_client)
205 rend_authorized_client_free_(authorized_client);
208 /** Release the storage held by <b>service</b>.
210 STATIC void
211 rend_service_free_(rend_service_t *service)
213 if (!service)
214 return;
216 tor_free(service->directory);
217 if (service->ports) {
218 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
219 rend_service_port_config_free(p));
220 smartlist_free(service->ports);
222 if (service->private_key)
223 crypto_pk_free(service->private_key);
224 if (service->intro_nodes) {
225 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
226 rend_intro_point_free(intro););
227 smartlist_free(service->intro_nodes);
229 if (service->expiring_nodes) {
230 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
231 rend_intro_point_free(intro););
232 smartlist_free(service->expiring_nodes);
235 rend_service_descriptor_free(service->desc);
236 if (service->clients) {
237 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
238 rend_authorized_client_free(c););
239 smartlist_free(service->clients);
241 if (service->accepted_intro_dh_parts) {
242 replaycache_free(service->accepted_intro_dh_parts);
244 tor_free(service);
247 /* Release all the storage held in rend_service_staging_list. */
248 void
249 rend_service_free_staging_list(void)
251 if (rend_service_staging_list) {
252 SMARTLIST_FOREACH(rend_service_staging_list, rend_service_t*, ptr,
253 rend_service_free(ptr));
254 smartlist_free(rend_service_staging_list);
255 rend_service_staging_list = NULL;
259 /** Release all the storage held in both rend_service_list and
260 * rend_service_staging_list. */
261 void
262 rend_service_free_all(void)
264 if (rend_service_list) {
265 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
266 rend_service_free(ptr));
267 smartlist_free(rend_service_list);
268 rend_service_list = NULL;
270 rend_service_free_staging_list();
273 /* Initialize the subsystem. */
274 void
275 rend_service_init(void)
277 tor_assert(!rend_service_list);
278 tor_assert(!rend_service_staging_list);
280 rend_service_list = smartlist_new();
281 rend_service_staging_list = smartlist_new();
284 /* Validate a <b>service</b>. Use the <b>service_list</b> to make sure there
285 * is no duplicate entry for the given service object. Return 0 if valid else
286 * -1 if not.*/
287 static int
288 rend_validate_service(const smartlist_t *service_list,
289 const rend_service_t *service)
291 tor_assert(service_list);
292 tor_assert(service);
294 if (service->max_streams_per_circuit < 0) {
295 log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
296 "streams per circuit.",
297 rend_service_escaped_dir(service));
298 goto invalid;
301 if (service->max_streams_close_circuit < 0 ||
302 service->max_streams_close_circuit > 1) {
303 log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
304 "max streams handling.",
305 rend_service_escaped_dir(service));
306 goto invalid;
309 if (service->auth_type != REND_NO_AUTH &&
310 (!service->clients || smartlist_len(service->clients) == 0)) {
311 log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but "
312 "no clients.",
313 rend_service_escaped_dir(service));
314 goto invalid;
317 if (!service->ports || !smartlist_len(service->ports)) {
318 log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured.",
319 rend_service_escaped_dir(service));
320 goto invalid;
323 /* Valid. */
324 return 0;
325 invalid:
326 return -1;
329 /** Add it to <b>service_list</b>, or to the global rend_service_list if
330 * <b>service_list</b> is NULL. Return 0 on success. On failure, free
331 * <b>service</b> and return -1. Takes ownership of <b>service</b>. */
332 static int
333 rend_add_service(smartlist_t *service_list, rend_service_t *service)
335 int i;
336 rend_service_port_config_t *p;
338 tor_assert(service);
340 smartlist_t *s_list = rend_get_service_list_mutable(service_list);
341 /* We must have a service list, even if it's a temporary one, so we can
342 * check for duplicate services */
343 if (BUG(!s_list)) {
344 rend_service_free(service);
345 return -1;
348 service->intro_nodes = smartlist_new();
349 service->expiring_nodes = smartlist_new();
351 log_debug(LD_REND,"Configuring service with directory %s",
352 rend_service_escaped_dir(service));
353 for (i = 0; i < smartlist_len(service->ports); ++i) {
354 p = smartlist_get(service->ports, i);
355 if (!(p->is_unix_addr)) {
356 log_debug(LD_REND,
357 "Service maps port %d to %s",
358 p->virtual_port,
359 fmt_addrport(&p->real_addr, p->real_port));
360 } else {
361 #ifdef HAVE_SYS_UN_H
362 log_debug(LD_REND,
363 "Service maps port %d to socket at \"%s\"",
364 p->virtual_port, p->unix_addr);
365 #else
366 log_warn(LD_BUG,
367 "Service maps port %d to an AF_UNIX socket, but we "
368 "have no AF_UNIX support on this platform. This is "
369 "probably a bug.",
370 p->virtual_port);
371 rend_service_free(service);
372 return -1;
373 #endif /* defined(HAVE_SYS_UN_H) */
376 /* The service passed all the checks */
377 tor_assert(s_list);
378 smartlist_add(s_list, service);
380 /* Notify that our global service list has changed only if this new service
381 * went into our global list. If not, when we move service from the staging
382 * list to the new list, a notify is triggered. */
383 if (s_list == rend_service_list) {
384 hs_service_map_has_changed();
386 return 0;
389 /** Return a new rend_service_port_config_t with its path set to
390 * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
391 static rend_service_port_config_t *
392 rend_service_port_config_new(const char *socket_path)
394 if (!socket_path)
395 return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
397 const size_t pathlen = strlen(socket_path) + 1;
398 rend_service_port_config_t *conf =
399 tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
400 memcpy(conf->unix_addr, socket_path, pathlen);
401 conf->is_unix_addr = 1;
402 return conf;
405 /** Parses a virtual-port to real-port/socket mapping separated by
406 * the provided separator and returns a new rend_service_port_config_t,
407 * or NULL and an optional error string on failure.
409 * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
411 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
413 rend_service_port_config_t *
414 rend_service_parse_port_config(const char *string, const char *sep,
415 char **err_msg_out)
417 smartlist_t *sl;
418 int virtport;
419 int realport = 0;
420 uint16_t p;
421 tor_addr_t addr;
422 rend_service_port_config_t *result = NULL;
423 unsigned int is_unix_addr = 0;
424 const char *socket_path = NULL;
425 char *err_msg = NULL;
426 char *addrport = NULL;
428 sl = smartlist_new();
429 smartlist_split_string(sl, string, sep,
430 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
431 if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
432 err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
433 goto err;
435 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
436 if (!virtport) {
437 tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
438 "port configuration", escaped(smartlist_get(sl,0)));
440 goto err;
442 if (smartlist_len(sl) == 1) {
443 /* No addr:port part; use default. */
444 realport = virtport;
445 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
446 } else {
447 int ret;
449 const char *addrport_element = smartlist_get(sl,1);
450 const char *rest = NULL;
451 int is_unix;
452 ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
453 &is_unix, &rest);
455 if (ret < 0) {
456 tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
457 "service configuration", addrport_element);
458 goto err;
461 if (rest && strlen(rest)) {
462 err_msg = tor_strdup("HiddenServicePort parse error: invalid port "
463 "mapping");
464 goto err;
467 if (is_unix) {
468 socket_path = addrport;
469 is_unix_addr = 1;
470 } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
471 /* else try it as an IP:port pair if it has a : or . in it */
472 if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
473 err_msg = tor_strdup("Unparseable address in hidden service port "
474 "configuration.");
475 goto err;
477 realport = p?p:virtport;
478 } else {
479 /* No addr:port, no addr -- must be port. */
480 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
481 if (!realport) {
482 tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
483 "hidden service port configuration.",
484 escaped(addrport));
485 goto err;
487 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
491 /* Allow room for unix_addr */
492 result = rend_service_port_config_new(socket_path);
493 result->virtual_port = virtport;
494 result->is_unix_addr = is_unix_addr;
495 if (!is_unix_addr) {
496 result->real_port = realport;
497 tor_addr_copy(&result->real_addr, &addr);
498 result->unix_addr[0] = '\0';
501 err:
502 tor_free(addrport);
503 if (err_msg_out != NULL) {
504 *err_msg_out = err_msg;
505 } else {
506 tor_free(err_msg);
508 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
509 smartlist_free(sl);
511 return result;
514 /** Release all storage held in a rend_service_port_config_t. */
515 void
516 rend_service_port_config_free_(rend_service_port_config_t *p)
518 tor_free(p);
521 /* Copy relevant data from service src to dst while pruning the service lists.
522 * This should only be called during the pruning process which takes existing
523 * services and copy their data to the newly configured services. The src
524 * service replaycache will be set to NULL after this call. */
525 static void
526 copy_service_on_prunning(rend_service_t *dst, rend_service_t *src)
528 tor_assert(dst);
529 tor_assert(src);
531 /* Keep the timestamps for when the content changed and the next upload
532 * time so we can properly upload the descriptor if needed for the new
533 * service object. */
534 dst->desc_is_dirty = src->desc_is_dirty;
535 dst->next_upload_time = src->next_upload_time;
536 /* Move the replaycache to the new object. */
537 dst->accepted_intro_dh_parts = src->accepted_intro_dh_parts;
538 src->accepted_intro_dh_parts = NULL;
539 /* Copy intro point information to destination service. */
540 dst->intro_period_started = src->intro_period_started;
541 dst->n_intro_circuits_launched = src->n_intro_circuits_launched;
542 dst->n_intro_points_wanted = src->n_intro_points_wanted;
545 /* Helper: Actual implementation of the pruning on reload which we've
546 * decoupled in order to make the unit test workeable without ugly hacks.
547 * Furthermore, this function does NOT free any memory but will nullify the
548 * temporary list pointer whatever happens. */
549 STATIC void
550 rend_service_prune_list_impl_(void)
552 origin_circuit_t *ocirc = NULL;
553 smartlist_t *surviving_services, *old_service_list, *new_service_list;
555 /* When pruning our current service list, we must have a staging list that
556 * contains what we want to check else it's a code flow error. */
557 tor_assert(rend_service_staging_list);
559 /* We are about to prune the current list of its dead service so set the
560 * semantic for that list to be the "old" one. */
561 old_service_list = rend_service_list;
562 /* The staging list is now the "new" list so set this semantic. */
563 new_service_list = rend_service_staging_list;
564 /* After this, whatever happens, we'll use our new list. */
565 rend_service_list = new_service_list;
566 /* Finally, nullify the staging list pointer as we don't need it anymore
567 * and it needs to be NULL before the next reload. */
568 rend_service_staging_list = NULL;
569 /* Nothing to prune if we have no service list so stop right away. */
570 if (!old_service_list) {
571 return;
574 /* This contains all _existing_ services that survives the relaod that is
575 * that haven't been removed from the configuration. The difference between
576 * this list and the new service list is that the new list can possibly
577 * contain newly configured service that have no introduction points opened
578 * yet nor key material loaded or generated. */
579 surviving_services = smartlist_new();
581 /* Preserve the existing ephemeral services.
583 * This is the ephemeral service equivalent of the "Copy introduction
584 * points to new services" block, except there's no copy required since
585 * the service structure isn't regenerated.
587 * After this is done, all ephemeral services will be:
588 * * Removed from old_service_list, so the equivalent non-ephemeral code
589 * will not attempt to preserve them.
590 * * Added to the new_service_list (that previously only had the
591 * services listed in the configuration).
592 * * Added to surviving_services, which is the list of services that
593 * will NOT have their intro point closed.
595 SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
596 if (rend_service_is_ephemeral(old)) {
597 SMARTLIST_DEL_CURRENT(old_service_list, old);
598 smartlist_add(surviving_services, old);
599 smartlist_add(new_service_list, old);
601 } SMARTLIST_FOREACH_END(old);
603 /* Copy introduction points to new services. This is O(n^2), but it's only
604 * called on reconfigure, so it's ok performance wise. */
605 SMARTLIST_FOREACH_BEGIN(new_service_list, rend_service_t *, new) {
606 SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
607 /* Skip ephemeral services as we only want to copy introduction points
608 * from current services to newly configured one that already exists.
609 * The same directory means it's the same service. */
610 if (rend_service_is_ephemeral(new) || rend_service_is_ephemeral(old) ||
611 strcmp(old->directory, new->directory)) {
612 continue;
614 smartlist_add_all(new->intro_nodes, old->intro_nodes);
615 smartlist_clear(old->intro_nodes);
616 smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
617 smartlist_clear(old->expiring_nodes);
619 /* Copy needed information from old to new. */
620 copy_service_on_prunning(new, old);
622 /* This regular service will survive the closing IPs step after. */
623 smartlist_add(surviving_services, old);
624 break;
625 } SMARTLIST_FOREACH_END(old);
626 } SMARTLIST_FOREACH_END(new);
628 /* For every service introduction circuit we can find, see if we have a
629 * matching surviving configured service. If not, close the circuit. */
630 while ((ocirc = circuit_get_next_service_intro_circ(ocirc))) {
631 int keep_it = 0;
632 if (ocirc->rend_data == NULL) {
633 /* This is a v3 circuit, ignore it. */
634 continue;
636 SMARTLIST_FOREACH_BEGIN(surviving_services, const rend_service_t *, s) {
637 if (rend_circuit_pk_digest_eq(ocirc, (uint8_t *) s->pk_digest)) {
638 /* Keep this circuit as we have a matching configured service. */
639 keep_it = 1;
640 break;
642 } SMARTLIST_FOREACH_END(s);
643 if (keep_it) {
644 continue;
646 log_info(LD_REND, "Closing intro point %s for service %s.",
647 safe_str_client(extend_info_describe(
648 ocirc->build_state->chosen_exit)),
649 safe_str_client(rend_data_get_address(ocirc->rend_data)));
650 /* Reason is FINISHED because service has been removed and thus the
651 * circuit is considered old/uneeded. */
652 circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
654 smartlist_free(surviving_services);
655 /* Notify that our global service list has changed. */
656 hs_service_map_has_changed();
659 /* Try to prune our main service list using the temporary one that we just
660 * loaded and parsed successfully. The pruning process decides which onion
661 * services to keep and which to discard after a reload. */
662 void
663 rend_service_prune_list(void)
665 smartlist_t *old_service_list = rend_service_list;
667 if (!rend_service_staging_list) {
668 rend_service_staging_list = smartlist_new();
671 rend_service_prune_list_impl_();
672 if (old_service_list) {
673 /* Every remaining service in the old list have been removed from the
674 * configuration so clean them up safely. */
675 SMARTLIST_FOREACH(old_service_list, rend_service_t *, s,
676 rend_service_free(s));
677 smartlist_free(old_service_list);
681 /* Copy all the relevant data that the hs_service object contains over to the
682 * rend_service_t object. The reason to do so is because when configuring a
683 * service, we go through a generic handler that creates an hs_service_t
684 * object which so we have to copy the parsed values to a rend service object
685 * which is version 2 specific. */
686 static void
687 service_config_shadow_copy(rend_service_t *service,
688 hs_service_config_t *config)
690 tor_assert(service);
691 tor_assert(config);
693 service->directory = tor_strdup(config->directory_path);
694 service->dir_group_readable = config->dir_group_readable;
695 service->allow_unknown_ports = config->allow_unknown_ports;
696 /* This value can't go above HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT (65535)
697 * if the code flow is right so this cast is safe. But just in case, we'll
698 * check it. */
699 service->max_streams_per_circuit = (int) config->max_streams_per_rdv_circuit;
700 if (BUG(config->max_streams_per_rdv_circuit >
701 HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT)) {
702 service->max_streams_per_circuit = HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT;
704 service->max_streams_close_circuit = config->max_streams_close_circuit;
705 service->n_intro_points_wanted = config->num_intro_points;
706 /* Switching ownership of the ports to the rend service object. */
707 smartlist_add_all(service->ports, config->ports);
708 smartlist_free(config->ports);
709 config->ports = NULL;
712 /* Parse the hidden service configuration starting at <b>line_</b> using the
713 * already configured generic service configuration in <b>config</b>. This
714 * function will translate the config object to a rend_service_t and add it to
715 * the temporary list if valid. If <b>validate_only</b> is set, parse, warn
716 * and return as normal but don't actually add the service to the list. */
718 rend_config_service(const config_line_t *line_,
719 const or_options_t *options,
720 hs_service_config_t *config)
722 const config_line_t *line;
723 rend_service_t *service = NULL;
725 /* line_ can be NULL which would mean that the service configuration only
726 * have one line that is the directory directive. */
727 tor_assert(options);
728 tor_assert(config);
730 /* Use the staging service list so that we can check then do the pruning
731 * process using the main list at the end. */
732 if (rend_service_staging_list == NULL) {
733 rend_service_staging_list = smartlist_new();
736 /* Initialize service. */
737 service = tor_malloc_zero(sizeof(rend_service_t));
738 service->intro_period_started = time(NULL);
739 service->ports = smartlist_new();
740 /* From the hs_service object which has been used to load the generic
741 * options, we'll copy over the useful data to the rend_service_t object. */
742 service_config_shadow_copy(service, config);
744 for (line = line_; line; line = line->next) {
745 if (!strcasecmp(line->key, "HiddenServiceDir")) {
746 /* We just hit the next hidden service, stop right now. */
747 break;
749 /* Number of introduction points. */
750 if (!strcasecmp(line->key, "HiddenServiceNumIntroductionPoints")) {
751 int ok = 0;
752 /* Those are specific defaults for version 2. */
753 service->n_intro_points_wanted =
754 (unsigned int) tor_parse_long(line->value, 10,
755 0, NUM_INTRO_POINTS_MAX, &ok, NULL);
756 if (!ok) {
757 log_warn(LD_CONFIG,
758 "HiddenServiceNumIntroductionPoints "
759 "should be between %d and %d, not %s",
760 0, NUM_INTRO_POINTS_MAX, line->value);
761 goto err;
763 log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
764 service->n_intro_points_wanted, escaped(service->directory));
765 continue;
767 if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
768 /* Parse auth type and comma-separated list of client names and add a
769 * rend_authorized_client_t for each client to the service's list
770 * of authorized clients. */
771 smartlist_t *type_names_split, *clients;
772 const char *authname;
773 if (service->auth_type != REND_NO_AUTH) {
774 log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
775 "lines for a single service.");
776 goto err;
778 type_names_split = smartlist_new();
779 smartlist_split_string(type_names_split, line->value, " ", 0, 2);
780 if (smartlist_len(type_names_split) < 1) {
781 log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
782 "should have been prevented when parsing the "
783 "configuration.");
784 smartlist_free(type_names_split);
785 goto err;
787 authname = smartlist_get(type_names_split, 0);
788 if (!strcasecmp(authname, "basic")) {
789 service->auth_type = REND_BASIC_AUTH;
790 } else if (!strcasecmp(authname, "stealth")) {
791 service->auth_type = REND_STEALTH_AUTH;
792 } else {
793 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
794 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
795 "are recognized.",
796 (char *) smartlist_get(type_names_split, 0));
797 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
798 smartlist_free(type_names_split);
799 goto err;
801 service->clients = smartlist_new();
802 if (smartlist_len(type_names_split) < 2) {
803 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
804 "auth-type '%s', but no client names.",
805 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
806 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
807 smartlist_free(type_names_split);
808 continue;
810 clients = smartlist_new();
811 smartlist_split_string(clients, smartlist_get(type_names_split, 1),
812 ",", SPLIT_SKIP_SPACE, 0);
813 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
814 smartlist_free(type_names_split);
815 /* Remove duplicate client names. */
817 int num_clients = smartlist_len(clients);
818 smartlist_sort_strings(clients);
819 smartlist_uniq_strings(clients);
820 if (smartlist_len(clients) < num_clients) {
821 log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
822 "duplicate client name(s); removing.",
823 num_clients - smartlist_len(clients));
826 SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
828 rend_authorized_client_t *client;
829 if (!rend_valid_client_name(client_name)) {
830 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
831 "illegal client name: '%s'. Names must be "
832 "between 1 and %d characters and contain "
833 "only [A-Za-z0-9+_-].",
834 client_name, REND_CLIENTNAME_MAX_LEN);
835 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
836 smartlist_free(clients);
837 goto err;
839 client = tor_malloc_zero(sizeof(rend_authorized_client_t));
840 client->client_name = tor_strdup(client_name);
841 smartlist_add(service->clients, client);
842 log_debug(LD_REND, "Adding client name '%s'", client_name);
844 SMARTLIST_FOREACH_END(client_name);
845 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
846 smartlist_free(clients);
847 /* Ensure maximum number of clients. */
848 if ((service->auth_type == REND_BASIC_AUTH &&
849 smartlist_len(service->clients) > 512) ||
850 (service->auth_type == REND_STEALTH_AUTH &&
851 smartlist_len(service->clients) > 16)) {
852 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
853 "client authorization entries, but only a "
854 "maximum of %d entries is allowed for "
855 "authorization type '%s'.",
856 smartlist_len(service->clients),
857 service->auth_type == REND_BASIC_AUTH ? 512 : 16,
858 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
859 goto err;
861 continue;
864 /* Validate the service just parsed. */
865 if (rend_validate_service(rend_service_staging_list, service) < 0) {
866 /* Service is in the staging list so don't try to free it. */
867 goto err;
870 /* Add it to the temporary list which we will use to prune our current
871 * list if any after configuring all services. */
872 if (rend_add_service(rend_service_staging_list, service) < 0) {
873 /* The object has been freed on error already. */
874 service = NULL;
875 goto err;
878 return 0;
879 err:
880 rend_service_free(service);
881 return -1;
884 /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
885 * client authorization <b>auth_type</b> and an optional list of
886 * rend_authorized_client_t in <b>auth_clients</b>, with
887 * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
888 * and circuit closure on max streams being exceeded set by
889 * <b>max_streams_close_circuit</b>.
891 * Ownership of pk, ports, and auth_clients is passed to this routine.
892 * Regardless of success/failure, callers should not touch these values
893 * after calling this routine, and may assume that correct cleanup has
894 * been done on failure.
896 * Return an appropriate hs_service_add_ephemeral_status_t.
898 hs_service_add_ephemeral_status_t
899 rend_service_add_ephemeral(crypto_pk_t *pk,
900 smartlist_t *ports,
901 int max_streams_per_circuit,
902 int max_streams_close_circuit,
903 rend_auth_type_t auth_type,
904 smartlist_t *auth_clients,
905 char **service_id_out)
907 *service_id_out = NULL;
908 /* Allocate the service structure, and initialize the key, and key derived
909 * parameters.
911 rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
912 s->directory = NULL; /* This indicates the service is ephemeral. */
913 s->private_key = pk;
914 s->auth_type = auth_type;
915 s->clients = auth_clients;
916 s->ports = ports;
917 s->intro_period_started = time(NULL);
918 s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
919 s->max_streams_per_circuit = max_streams_per_circuit;
920 s->max_streams_close_circuit = max_streams_close_circuit;
921 if (rend_service_derive_key_digests(s) < 0) {
922 rend_service_free(s);
923 return RSAE_BADPRIVKEY;
926 if (!s->ports || smartlist_len(s->ports) == 0) {
927 log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
928 rend_service_free(s);
929 return RSAE_BADVIRTPORT;
931 if (s->auth_type != REND_NO_AUTH &&
932 (!s->clients || smartlist_len(s->clients) == 0)) {
933 log_warn(LD_CONFIG, "At least one authorized client must be specified.");
934 rend_service_free(s);
935 return RSAE_BADAUTH;
938 /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
939 * it's not, see #14828.
941 if (rend_service_get_by_pk_digest(s->pk_digest)) {
942 log_warn(LD_CONFIG, "Onion Service private key collides with an "
943 "existing service.");
944 rend_service_free(s);
945 return RSAE_ADDREXISTS;
947 if (rend_service_get_by_service_id(s->service_id)) {
948 log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
949 rend_service_free(s);
950 return RSAE_ADDREXISTS;
953 /* Initialize the service. */
954 if (rend_add_service(NULL, s)) {
955 return RSAE_INTERNAL;
957 *service_id_out = tor_strdup(s->service_id);
959 log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
960 return RSAE_OKAY;
963 /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
964 * success, and -1 on failure.
967 rend_service_del_ephemeral(const char *service_id)
969 rend_service_t *s;
970 if (!rend_valid_v2_service_id(service_id)) {
971 log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
972 return -1;
974 if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
975 log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
976 "removal.");
977 return -1;
979 if (!rend_service_is_ephemeral(s)) {
980 log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
981 return -1;
984 /* Kill the intro point circuit for the Onion Service, and remove it from
985 * the list. Closing existing connections is the application's problem.
987 * XXX: As with the comment in rend_config_services(), a nice abstraction
988 * would be ideal here, but for now just duplicate the code.
990 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
991 if (!circ->marked_for_close &&
992 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
993 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
994 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
995 if (oc->rend_data == NULL ||
996 !rend_circuit_pk_digest_eq(oc, (uint8_t *) s->pk_digest)) {
997 continue;
999 log_debug(LD_REND, "Closing intro point %s for service %s.",
1000 safe_str_client(extend_info_describe(
1001 oc->build_state->chosen_exit)),
1002 rend_data_get_address(oc->rend_data));
1003 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1005 } SMARTLIST_FOREACH_END(circ);
1006 smartlist_remove(rend_service_list, s);
1007 /* Notify that we just removed a service from our global list. */
1008 hs_service_map_has_changed();
1009 rend_service_free(s);
1011 log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
1013 return 0;
1016 /* There can be 1 second's delay due to second_elapsed_callback, and perhaps
1017 * another few seconds due to blocking calls. */
1018 #define INTRO_CIRC_RETRY_PERIOD_SLOP 10
1020 /** Log information about the intro point creation rate and current intro
1021 * points for service, upgrading the log level from min_severity to warn if
1022 * we have stopped launching new intro point circuits. */
1023 static void
1024 rend_log_intro_limit(const rend_service_t *service, int min_severity)
1026 int exceeded_limit = (service->n_intro_circuits_launched >=
1027 rend_max_intro_circs_per_period(
1028 service->n_intro_points_wanted));
1029 int severity = min_severity;
1030 /* We stopped creating circuits */
1031 if (exceeded_limit) {
1032 severity = LOG_WARN;
1034 time_t intro_period_elapsed = time(NULL) - service->intro_period_started;
1035 tor_assert_nonfatal(intro_period_elapsed >= 0);
1037 char *msg;
1038 static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
1039 if ((msg = rate_limit_log(&rlimit, approx_time()))) {
1040 log_fn(severity, LD_REND,
1041 "Hidden service %s %s %d intro points in the last %d seconds. "
1042 "Intro circuit launches are limited to %d per %d seconds.%s",
1043 service->service_id,
1044 exceeded_limit ? "exceeded launch limit with" : "launched",
1045 service->n_intro_circuits_launched,
1046 (int)intro_period_elapsed,
1047 rend_max_intro_circs_per_period(service->n_intro_points_wanted),
1048 INTRO_CIRC_RETRY_PERIOD, msg);
1049 rend_service_dump_stats(severity);
1050 tor_free(msg);
1055 /** Replace the old value of <b>service</b>-\>desc with one that reflects
1056 * the other fields in service.
1058 static void
1059 rend_service_update_descriptor(rend_service_t *service)
1061 rend_service_descriptor_t *d;
1062 int i;
1064 rend_service_descriptor_free(service->desc);
1065 service->desc = NULL;
1067 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
1068 d->pk = crypto_pk_dup_key(service->private_key);
1069 d->timestamp = time(NULL);
1070 d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */
1071 d->intro_nodes = smartlist_new();
1072 /* Support intro protocols 2 and 3. */
1073 d->protocols = (1 << 2) + (1 << 3);
1075 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
1076 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
1077 rend_intro_point_t *intro_desc;
1079 /* This intro point won't be listed in the descriptor... */
1080 intro_svc->listed_in_last_desc = 0;
1082 /* circuit_established is set in rend_service_intro_established(), and
1083 * checked every second in rend_consider_services_intro_points(), so it's
1084 * safe to use it here */
1085 if (!intro_svc->circuit_established) {
1086 continue;
1089 /* ...unless this intro point is listed in the descriptor. */
1090 intro_svc->listed_in_last_desc = 1;
1092 /* We have an entirely established intro circuit. Publish it in
1093 * our descriptor. */
1094 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
1095 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
1096 if (intro_svc->intro_key)
1097 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
1098 smartlist_add(d->intro_nodes, intro_desc);
1100 if (intro_svc->time_published == -1) {
1101 /* We are publishing this intro point in a descriptor for the
1102 * first time -- note the current time in the service's copy of
1103 * the intro point. */
1104 intro_svc->time_published = time(NULL);
1108 /* Check that we have the right number of intro points */
1109 unsigned int have_intro = (unsigned int)smartlist_len(d->intro_nodes);
1110 if (have_intro != service->n_intro_points_wanted) {
1111 int severity;
1112 /* Getting less than we wanted or more than we're allowed is serious */
1113 if (have_intro < service->n_intro_points_wanted ||
1114 have_intro > NUM_INTRO_POINTS_MAX) {
1115 severity = LOG_WARN;
1116 } else {
1117 /* Getting more than we wanted is weird, but less of a problem */
1118 severity = LOG_NOTICE;
1120 log_fn(severity, LD_REND, "Hidden service %s wanted %d intro points, but "
1121 "descriptor was updated with %d instead.",
1122 service->service_id,
1123 service->n_intro_points_wanted, have_intro);
1124 /* Now log an informative message about how we might have got here. */
1125 rend_log_intro_limit(service, severity);
1129 /* Allocate and return a string containing the path to file_name in
1130 * service->directory. Asserts that service has a directory.
1131 * This function will never return NULL.
1132 * The caller must free this path. */
1133 static char *
1134 rend_service_path(const rend_service_t *service, const char *file_name)
1136 tor_assert(service->directory);
1137 return hs_path_from_filename(service->directory, file_name);
1140 /* Allocate and return a string containing the path to the single onion
1141 * service poison file in service->directory. Asserts that service has a
1142 * directory.
1143 * The caller must free this path. */
1144 STATIC char *
1145 rend_service_sos_poison_path(const rend_service_t *service)
1147 return rend_service_path(service, sos_poison_fname);
1150 /** Return True if hidden services <b>service</b> has been poisoned by single
1151 * onion mode. */
1152 static int
1153 service_is_single_onion_poisoned(const rend_service_t *service)
1155 char *poison_fname = NULL;
1156 file_status_t fstatus;
1158 /* Passing a NULL service is a bug */
1159 if (BUG(!service)) {
1160 return 0;
1163 if (rend_service_is_ephemeral(service)) {
1164 return 0;
1167 poison_fname = rend_service_sos_poison_path(service);
1169 fstatus = file_status(poison_fname);
1170 tor_free(poison_fname);
1172 /* If this fname is occupied, the hidden service has been poisoned.
1173 * fstatus can be FN_ERROR if the service directory does not exist, in that
1174 * case, there is obviously no private key. */
1175 if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
1176 return 1;
1179 return 0;
1182 /* Return 1 if the private key file for service exists and has a non-zero size,
1183 * and 0 otherwise. */
1184 static int
1185 rend_service_private_key_exists(const rend_service_t *service)
1187 char *private_key_path = rend_service_path(service, private_key_fname);
1188 const file_status_t private_key_status = file_status(private_key_path);
1189 tor_free(private_key_path);
1190 /* Only non-empty regular private key files could have been used before.
1191 * fstatus can be FN_ERROR if the service directory does not exist, in that
1192 * case, there is obviously no private key. */
1193 return private_key_status == FN_FILE;
1196 /** Check the single onion service poison state of the directory for s:
1197 * - If the service is poisoned, and we are in Single Onion Mode,
1198 * return 0,
1199 * - If the service is not poisoned, and we are not in Single Onion Mode,
1200 * return 0,
1201 * - Otherwise, the poison state is invalid: the service was created in one
1202 * mode, and is being used in the other, return -1.
1203 * Hidden service directories without keys are always considered consistent.
1204 * They will be poisoned after their directory is created (if needed). */
1205 STATIC int
1206 rend_service_verify_single_onion_poison(const rend_service_t* s,
1207 const or_options_t* options)
1209 /* Passing a NULL service is a bug */
1210 if (BUG(!s)) {
1211 return -1;
1214 /* Ephemeral services are checked at ADD_ONION time */
1215 if (BUG(rend_service_is_ephemeral(s))) {
1216 return -1;
1219 /* Service is expected to have a directory */
1220 if (BUG(!s->directory)) {
1221 return -1;
1224 /* Services without keys are always ok - their keys will only ever be used
1225 * in the current mode */
1226 if (!rend_service_private_key_exists(s)) {
1227 return 0;
1230 /* The key has been used before in a different mode */
1231 if (service_is_single_onion_poisoned(s) !=
1232 rend_service_non_anonymous_mode_enabled(options)) {
1233 return -1;
1236 /* The key exists and is consistent with the current mode */
1237 return 0;
1240 /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
1241 * the hidden service directory for s that marks it as a single onion service.
1242 * Tor must be in single onion mode before calling this function, and the
1243 * service directory must already have been created.
1244 * Returns 0 when a directory is successfully poisoned, or if it is already
1245 * poisoned. Returns -1 on a failure to read the directory or write the poison
1246 * file, or if there is an existing private key file in the directory. (The
1247 * service should have been poisoned when the key was created.) */
1248 static int
1249 poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
1250 const or_options_t* options)
1252 /* Passing a NULL service is a bug */
1253 if (BUG(!service)) {
1254 return -1;
1257 /* We must only poison directories if we're in Single Onion mode */
1258 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1260 int fd;
1261 int retval = -1;
1262 char *poison_fname = NULL;
1264 if (rend_service_is_ephemeral(service)) {
1265 log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
1266 return 0;
1269 /* Make sure we're only poisoning new hidden service directories */
1270 if (rend_service_private_key_exists(service)) {
1271 log_warn(LD_BUG, "Tried to single onion poison a service directory after "
1272 "the private key was created.");
1273 return -1;
1276 /* Make sure the directory was created before calling this function. */
1277 if (BUG(hs_check_service_private_dir(options->User, service->directory,
1278 service->dir_group_readable, 0) < 0))
1279 return -1;
1281 poison_fname = rend_service_sos_poison_path(service);
1283 switch (file_status(poison_fname)) {
1284 case FN_DIR:
1285 case FN_ERROR:
1286 log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
1287 poison_fname);
1288 goto done;
1289 case FN_FILE: /* single onion poison file already exists. NOP. */
1290 case FN_EMPTY: /* single onion poison file already exists. NOP. */
1291 log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
1292 poison_fname);
1293 break;
1294 case FN_NOENT:
1295 fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
1296 if (fd < 0) {
1297 log_warn(LD_FS, "Could not create single onion poison file %s",
1298 poison_fname);
1299 goto done;
1301 close(fd);
1302 break;
1303 default:
1304 tor_assert(0);
1307 retval = 0;
1309 done:
1310 tor_free(poison_fname);
1312 return retval;
1315 /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
1316 * hidden services. If s is new, we should mark its hidden service
1317 * directory appropriately so that it is never launched as a location-private
1318 * hidden service. (New directories don't have private key files.)
1319 * Return 0 on success, -1 on fail. */
1320 STATIC int
1321 rend_service_poison_new_single_onion_dir(const rend_service_t *s,
1322 const or_options_t* options)
1324 /* Passing a NULL service is a bug */
1325 if (BUG(!s)) {
1326 return -1;
1329 /* We must only poison directories if we're in Single Onion mode */
1330 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1332 /* Ephemeral services aren't allowed in non-anonymous mode */
1333 if (BUG(rend_service_is_ephemeral(s))) {
1334 return -1;
1337 /* Service is expected to have a directory */
1338 if (BUG(!s->directory)) {
1339 return -1;
1342 if (!rend_service_private_key_exists(s)) {
1343 if (poison_new_single_onion_hidden_service_dir_impl(s, options)
1344 < 0) {
1345 return -1;
1349 return 0;
1352 /* Return true iff the given service identity key is present on disk. This is
1353 * used to try to learn the service version during configuration time. */
1355 rend_service_key_on_disk(const char *directory_path)
1357 int ret = 0;
1358 char *fname;
1359 crypto_pk_t *pk = NULL;
1361 tor_assert(directory_path);
1363 /* Load key */
1364 fname = hs_path_from_filename(directory_path, private_key_fname);
1365 pk = init_key_from_file(fname, 0, LOG_DEBUG, 0);
1366 if (pk) {
1367 ret = 1;
1370 crypto_pk_free(pk);
1371 tor_free(fname);
1372 return ret;
1375 /** Load and/or generate private keys for all hidden services, possibly
1376 * including keys for client authorization.
1377 * If a <b>service_list</b> is provided, treat it as the list of hidden
1378 * services (used in unittests). Otherwise, require that rend_service_list is
1379 * not NULL.
1380 * Return 0 on success, -1 on failure. */
1382 rend_service_load_all_keys(const smartlist_t *service_list)
1384 /* Use service_list for unit tests */
1385 const smartlist_t *s_list = rend_get_service_list(service_list);
1386 if (BUG(!s_list)) {
1387 return -1;
1390 SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
1391 if (s->private_key)
1392 continue;
1393 log_info(LD_REND, "Loading hidden-service keys from %s",
1394 rend_service_escaped_dir(s));
1396 if (rend_service_load_keys(s) < 0)
1397 return -1;
1398 } SMARTLIST_FOREACH_END(s);
1400 return 0;
1403 /** Add to <b>lst</b> every filename used by <b>s</b>. */
1404 static void
1405 rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
1407 tor_assert(lst);
1408 tor_assert(s);
1409 tor_assert(s->directory);
1410 smartlist_add(lst, rend_service_path(s, private_key_fname));
1411 smartlist_add(lst, rend_service_path(s, hostname_fname));
1412 smartlist_add(lst, rend_service_path(s, client_keys_fname));
1413 smartlist_add(lst, rend_service_sos_poison_path(s));
1416 /** Add to <b>open_lst</b> every filename used by a configured hidden service,
1417 * and to <b>stat_lst</b> every directory used by a configured hidden
1418 * service */
1419 void
1420 rend_services_add_filenames_to_lists(smartlist_t *open_lst,
1421 smartlist_t *stat_lst)
1423 if (!rend_service_list)
1424 return;
1425 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
1426 if (!rend_service_is_ephemeral(s)) {
1427 rend_service_add_filenames_to_list(open_lst, s);
1428 smartlist_add_strdup(stat_lst, s->directory);
1430 } SMARTLIST_FOREACH_END(s);
1433 /** Derive all rend_service_t internal material based on the service's key.
1434 * Returns 0 on success, -1 on failure.
1436 static int
1437 rend_service_derive_key_digests(struct rend_service_t *s)
1439 if (rend_get_service_id(s->private_key, s->service_id)<0) {
1440 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1441 return -1;
1443 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
1444 log_warn(LD_BUG, "Couldn't compute hash of public key.");
1445 return -1;
1448 return 0;
1451 /** Make sure that the directory for <b>s</b> is private, using the config in
1452 * <b>options</b>.
1453 * If <b>create</b> is true:
1454 * - if the directory exists, change permissions if needed,
1455 * - if the directory does not exist, create it with the correct permissions.
1456 * If <b>create</b> is false:
1457 * - if the directory exists, check permissions,
1458 * - if the directory does not exist, check if we think we can create it.
1459 * Return 0 on success, -1 on failure. */
1460 static int
1461 rend_service_check_private_dir(const or_options_t *options,
1462 const rend_service_t *s,
1463 int create)
1465 /* Passing a NULL service is a bug */
1466 if (BUG(!s)) {
1467 return -1;
1470 /* Check/create directory */
1471 if (hs_check_service_private_dir(options->User, s->directory,
1472 s->dir_group_readable, create) < 0) {
1473 return -1;
1476 /* Check if the hidden service key exists, and was created in a different
1477 * single onion service mode, and refuse to launch if it has.
1478 * This is safe to call even when create is false, as it ignores missing
1479 * keys and directories: they are always valid.
1481 if (rend_service_verify_single_onion_poison(s, options) < 0) {
1482 /* We can't use s->service_id here, as the key may not have been loaded */
1483 log_warn(LD_GENERAL, "We are configured with "
1484 "HiddenServiceNonAnonymousMode %d, but the hidden "
1485 "service key in directory %s was created in %s mode. "
1486 "This is not allowed.",
1487 rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
1488 rend_service_escaped_dir(s),
1489 rend_service_non_anonymous_mode_enabled(options) ?
1490 "an anonymous" : "a non-anonymous"
1492 return -1;
1495 /* Poison new single onion directories immediately after they are created,
1496 * so that we never accidentally launch non-anonymous hidden services
1497 * thinking they are anonymous. Any keys created later will end up with the
1498 * correct poisoning state.
1500 if (create && rend_service_non_anonymous_mode_enabled(options)) {
1501 static int logged_warning = 0;
1503 if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
1504 log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
1505 ".");
1506 return -1;
1509 if (!logged_warning) {
1510 /* The keys for these services are linked to the server IP address */
1511 log_notice(LD_REND, "The configured onion service directories have been "
1512 "used in single onion mode. They can not be used for "
1513 "anonymous hidden services.");
1514 logged_warning = 1;
1518 return 0;
1521 /** Load and/or generate private keys for the hidden service <b>s</b>,
1522 * possibly including keys for client authorization. Return 0 on success, -1
1523 * on failure. */
1524 static int
1525 rend_service_load_keys(rend_service_t *s)
1527 char *fname = NULL;
1528 char buf[128];
1530 /* Create the directory if needed which will also poison it in case of
1531 * single onion service. */
1532 if (rend_service_check_private_dir(get_options(), s, 1) < 0)
1533 goto err;
1535 /* Load key */
1536 fname = rend_service_path(s, private_key_fname);
1537 s->private_key = init_key_from_file(fname, 1, LOG_ERR, 0);
1539 if (!s->private_key)
1540 goto err;
1542 if (rend_service_derive_key_digests(s) < 0)
1543 goto err;
1545 tor_free(fname);
1546 /* Create service file */
1547 fname = rend_service_path(s, hostname_fname);
1549 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
1550 if (write_str_to_file(fname,buf,0)<0) {
1551 log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
1552 goto err;
1554 #ifndef _WIN32
1555 if (s->dir_group_readable) {
1556 /* Also verify hostname file created with group read. */
1557 if (chmod(fname, 0640))
1558 log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
1559 fname);
1561 #endif /* !defined(_WIN32) */
1563 /* If client authorization is configured, load or generate keys. */
1564 if (s->auth_type != REND_NO_AUTH) {
1565 if (rend_service_load_auth_keys(s, fname) < 0) {
1566 goto err;
1570 int r = 0;
1571 goto done;
1572 err:
1573 r = -1;
1574 done:
1575 memwipe(buf, 0, sizeof(buf));
1576 tor_free(fname);
1577 return r;
1580 /** Load and/or generate client authorization keys for the hidden service
1581 * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
1582 * -1 on failure. */
1583 static int
1584 rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
1586 int r = 0;
1587 char *cfname = NULL;
1588 char *client_keys_str = NULL;
1589 strmap_t *parsed_clients = strmap_new();
1590 FILE *cfile, *hfile;
1591 open_file_t *open_cfile = NULL, *open_hfile = NULL;
1592 char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
1593 char service_id[16+1];
1594 char buf[1500];
1596 /* Load client keys and descriptor cookies, if available. */
1597 cfname = rend_service_path(s, client_keys_fname);
1598 client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
1599 if (client_keys_str) {
1600 if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
1601 log_warn(LD_CONFIG, "Previously stored client_keys file could not "
1602 "be parsed.");
1603 goto err;
1604 } else {
1605 log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
1606 strmap_size(parsed_clients));
1610 /* Prepare client_keys and hostname files. */
1611 if (!(cfile = start_writing_to_stdio_file(cfname,
1612 OPEN_FLAGS_REPLACE | O_TEXT,
1613 0600, &open_cfile))) {
1614 log_warn(LD_CONFIG, "Could not open client_keys file %s",
1615 escaped(cfname));
1616 goto err;
1619 if (!(hfile = start_writing_to_stdio_file(hfname,
1620 OPEN_FLAGS_REPLACE | O_TEXT,
1621 0600, &open_hfile))) {
1622 log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
1623 goto err;
1626 /* Either use loaded keys for configured clients or generate new
1627 * ones if a client is new. */
1628 SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
1629 rend_authorized_client_t *parsed =
1630 strmap_get(parsed_clients, client->client_name);
1631 int written;
1632 size_t len;
1633 /* Copy descriptor cookie from parsed entry or create new one. */
1634 if (parsed) {
1635 memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
1636 REND_DESC_COOKIE_LEN);
1637 } else {
1638 crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
1640 /* For compatibility with older tor clients, this does not
1641 * truncate the padding characters, unlike rend_auth_encode_cookie. */
1642 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
1643 (char *) client->descriptor_cookie,
1644 REND_DESC_COOKIE_LEN, 0) < 0) {
1645 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1646 goto err;
1648 /* Copy client key from parsed entry or create new one if required. */
1649 if (parsed && parsed->client_key) {
1650 client->client_key = crypto_pk_dup_key(parsed->client_key);
1651 } else if (s->auth_type == REND_STEALTH_AUTH) {
1652 /* Create private key for client. */
1653 crypto_pk_t *prkey = NULL;
1654 if (!(prkey = crypto_pk_new())) {
1655 log_warn(LD_BUG,"Error constructing client key");
1656 goto err;
1658 if (crypto_pk_generate_key(prkey)) {
1659 log_warn(LD_BUG,"Error generating client key");
1660 crypto_pk_free(prkey);
1661 goto err;
1663 if (! crypto_pk_is_valid_private_key(prkey)) {
1664 log_warn(LD_BUG,"Generated client key seems invalid");
1665 crypto_pk_free(prkey);
1666 goto err;
1668 client->client_key = prkey;
1670 /* Add entry to client_keys file. */
1671 written = tor_snprintf(buf, sizeof(buf),
1672 "client-name %s\ndescriptor-cookie %s\n",
1673 client->client_name, desc_cook_out);
1674 if (written < 0) {
1675 log_warn(LD_BUG, "Could not write client entry.");
1676 goto err;
1678 if (client->client_key) {
1679 char *client_key_out = NULL;
1680 if (crypto_pk_write_private_key_to_string(client->client_key,
1681 &client_key_out, &len) != 0) {
1682 log_warn(LD_BUG, "Internal error: "
1683 "crypto_pk_write_private_key_to_string() failed.");
1684 goto err;
1686 if (rend_get_service_id(client->client_key, service_id)<0) {
1687 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1689 * len is string length, not buffer length, but last byte is NUL
1690 * anyway.
1692 memwipe(client_key_out, 0, len);
1693 tor_free(client_key_out);
1694 goto err;
1696 written = tor_snprintf(buf + written, sizeof(buf) - written,
1697 "client-key\n%s", client_key_out);
1698 memwipe(client_key_out, 0, len);
1699 tor_free(client_key_out);
1700 if (written < 0) {
1701 log_warn(LD_BUG, "Could not write client entry.");
1702 goto err;
1704 } else {
1705 strlcpy(service_id, s->service_id, sizeof(service_id));
1708 if (fputs(buf, cfile) < 0) {
1709 log_warn(LD_FS, "Could not append client entry to file: %s",
1710 strerror(errno));
1711 goto err;
1714 /* Add line to hostname file. This is not the same encoding as in
1715 * client_keys. */
1716 char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
1717 s->auth_type);
1718 if (!encoded_cookie) {
1719 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1720 goto err;
1722 tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
1723 service_id, encoded_cookie, client->client_name);
1724 memwipe(encoded_cookie, 0, strlen(encoded_cookie));
1725 tor_free(encoded_cookie);
1727 if (fputs(buf, hfile)<0) {
1728 log_warn(LD_FS, "Could not append host entry to file: %s",
1729 strerror(errno));
1730 goto err;
1732 } SMARTLIST_FOREACH_END(client);
1734 finish_writing_to_file(open_cfile);
1735 finish_writing_to_file(open_hfile);
1737 goto done;
1738 err:
1739 r = -1;
1740 if (open_cfile)
1741 abort_writing_to_file(open_cfile);
1742 if (open_hfile)
1743 abort_writing_to_file(open_hfile);
1744 done:
1745 if (client_keys_str) {
1746 memwipe(client_keys_str, 0, strlen(client_keys_str));
1747 tor_free(client_keys_str);
1749 strmap_free(parsed_clients, rend_authorized_client_free_void);
1751 if (cfname) {
1752 memwipe(cfname, 0, strlen(cfname));
1753 tor_free(cfname);
1756 /* Clear stack buffers that held key-derived material. */
1757 memwipe(buf, 0, sizeof(buf));
1758 memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
1759 memwipe(service_id, 0, sizeof(service_id));
1761 return r;
1764 /** Return the service whose public key has a digest of <b>digest</b>, or
1765 * NULL if no such service exists.
1767 static rend_service_t *
1768 rend_service_get_by_pk_digest(const char* digest)
1770 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
1771 if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
1772 return s);
1773 return NULL;
1776 /** Return the service whose service id is <b>id</b>, or NULL if no such
1777 * service exists.
1779 static struct rend_service_t *
1780 rend_service_get_by_service_id(const char *id)
1782 tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
1783 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
1784 if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
1785 return s;
1787 return NULL;
1790 /** Check client authorization of a given <b>descriptor_cookie</b> of
1791 * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
1792 * and 0 for failure. */
1793 static int
1794 rend_check_authorization(rend_service_t *service,
1795 const char *descriptor_cookie,
1796 size_t cookie_len)
1798 rend_authorized_client_t *auth_client = NULL;
1799 tor_assert(service);
1800 tor_assert(descriptor_cookie);
1801 if (!service->clients) {
1802 log_warn(LD_BUG, "Can't check authorization for a service that has no "
1803 "authorized clients configured.");
1804 return 0;
1807 if (cookie_len != REND_DESC_COOKIE_LEN) {
1808 log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
1809 "%lu bytes. Dropping cell.",
1810 (unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
1811 return 0;
1814 /* Look up client authorization by descriptor cookie. */
1815 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
1816 if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
1817 REND_DESC_COOKIE_LEN)) {
1818 auth_client = client;
1819 break;
1822 if (!auth_client) {
1823 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
1824 base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
1825 descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
1826 log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
1827 "Dropping cell!",
1828 descriptor_cookie_base64);
1829 return 0;
1832 /* Allow the request. */
1833 log_info(LD_REND, "Client %s authorized for service %s.",
1834 auth_client->client_name, service->service_id);
1835 return 1;
1838 /* Can this service make a direct connection to ei?
1839 * It must be a single onion service, and the firewall rules must allow ei. */
1840 static int
1841 rend_service_use_direct_connection(const or_options_t* options,
1842 const extend_info_t* ei)
1844 /* We'll connect directly all reachable addresses, whether preferred or not.
1845 * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
1846 * ignored, because pref_only is 0. */
1847 return (rend_service_allow_non_anonymous_connection(options) &&
1848 fascist_firewall_allows_address_addr(&ei->addr, ei->port,
1849 FIREWALL_OR_CONNECTION, 0, 0));
1852 /* Like rend_service_use_direct_connection, but to a node. */
1853 static int
1854 rend_service_use_direct_connection_node(const or_options_t* options,
1855 const node_t* node)
1857 /* We'll connect directly all reachable addresses, whether preferred or not.
1859 return (rend_service_allow_non_anonymous_connection(options) &&
1860 fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0));
1863 /******
1864 * Handle cells
1865 ******/
1867 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
1868 * rendezvous point.
1871 rend_service_receive_introduction(origin_circuit_t *circuit,
1872 const uint8_t *request,
1873 size_t request_len)
1875 /* Global status stuff */
1876 int status = 0, result;
1877 const or_options_t *options = get_options();
1878 char *err_msg = NULL;
1879 int err_msg_severity = LOG_WARN;
1880 const char *stage_descr = NULL, *rend_pk_digest;
1881 int reason = END_CIRC_REASON_TORPROTOCOL;
1882 /* Service/circuit/key stuff we can learn before parsing */
1883 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1884 rend_service_t *service = NULL;
1885 rend_intro_point_t *intro_point = NULL;
1886 crypto_pk_t *intro_key = NULL;
1887 /* Parsed cell */
1888 rend_intro_cell_t *parsed_req = NULL;
1889 /* Rendezvous point */
1890 extend_info_t *rp = NULL;
1891 /* XXX not handled yet */
1892 char buf[RELAY_PAYLOAD_SIZE];
1893 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
1894 int i;
1895 crypto_dh_t *dh = NULL;
1896 origin_circuit_t *launched = NULL;
1897 crypt_path_t *cpath = NULL;
1898 char hexcookie[9];
1899 int circ_needs_uptime;
1900 time_t now = time(NULL);
1901 time_t elapsed;
1902 int replay;
1903 ssize_t keylen;
1905 /* Do some initial validation and logging before we parse the cell */
1906 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
1907 log_warn(LD_PROTOCOL,
1908 "Got an INTRODUCE2 over a non-introduction circuit %u.",
1909 (unsigned) circuit->base_.n_circ_id);
1910 goto err;
1913 assert_circ_anonymity_ok(circuit, options);
1914 tor_assert(circuit->rend_data);
1915 /* XXX: This is version 2 specific (only one supported). */
1916 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
1918 /* We'll use this in a bazillion log messages */
1919 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1920 rend_pk_digest, REND_SERVICE_ID_LEN);
1922 /* look up service depending on circuit. */
1923 service = rend_service_get_by_pk_digest(rend_pk_digest);
1924 if (!service) {
1925 log_warn(LD_BUG,
1926 "Internal error: Got an INTRODUCE2 cell on an intro "
1927 "circ for an unrecognized service %s.",
1928 escaped(serviceid));
1929 goto err;
1932 intro_point = find_intro_point(circuit);
1933 if (intro_point == NULL) {
1934 intro_point = find_expiring_intro_point(service, circuit);
1935 if (intro_point == NULL) {
1936 log_warn(LD_BUG,
1937 "Internal error: Got an INTRODUCE2 cell on an "
1938 "intro circ (for service %s) with no corresponding "
1939 "rend_intro_point_t.",
1940 escaped(serviceid));
1941 goto err;
1945 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
1946 escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
1948 /* use intro key instead of service key. */
1949 intro_key = circuit->intro_key;
1951 tor_free(err_msg);
1952 stage_descr = NULL;
1954 stage_descr = "early parsing";
1955 /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
1956 parsed_req =
1957 rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
1958 if (!parsed_req) {
1959 goto log_error;
1960 } else if (err_msg) {
1961 log_info(LD_REND, "%s on circ %u.", err_msg,
1962 (unsigned)circuit->base_.n_circ_id);
1963 tor_free(err_msg);
1966 /* make sure service replay caches are present */
1967 if (!service->accepted_intro_dh_parts) {
1968 service->accepted_intro_dh_parts =
1969 replaycache_new(REND_REPLAY_TIME_INTERVAL,
1970 REND_REPLAY_TIME_INTERVAL);
1973 if (!intro_point->accepted_intro_rsa_parts) {
1974 intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
1977 /* check for replay of PK-encrypted portion. */
1978 keylen = crypto_pk_keysize(intro_key);
1979 replay = replaycache_add_test_and_elapsed(
1980 intro_point->accepted_intro_rsa_parts,
1981 parsed_req->ciphertext, MIN(parsed_req->ciphertext_len, keylen),
1982 &elapsed);
1984 if (replay) {
1985 log_warn(LD_REND,
1986 "Possible replay detected! We received an "
1987 "INTRODUCE2 cell with same PK-encrypted part %d "
1988 "seconds ago. Dropping cell.",
1989 (int)elapsed);
1990 goto err;
1993 stage_descr = "decryption";
1994 /* Now try to decrypt it */
1995 result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
1996 if (result < 0) {
1997 goto log_error;
1998 } else if (err_msg) {
1999 log_info(LD_REND, "%s on circ %u.", err_msg,
2000 (unsigned)circuit->base_.n_circ_id);
2001 tor_free(err_msg);
2004 stage_descr = "late parsing";
2005 /* Parse the plaintext */
2006 result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
2007 if (result < 0) {
2008 goto log_error;
2009 } else if (err_msg) {
2010 log_info(LD_REND, "%s on circ %u.", err_msg,
2011 (unsigned)circuit->base_.n_circ_id);
2012 tor_free(err_msg);
2015 stage_descr = "late validation";
2016 /* Validate the parsed plaintext parts */
2017 result = rend_service_validate_intro_late(parsed_req, &err_msg);
2018 if (result < 0) {
2019 goto log_error;
2020 } else if (err_msg) {
2021 log_info(LD_REND, "%s on circ %u.", err_msg,
2022 (unsigned)circuit->base_.n_circ_id);
2023 tor_free(err_msg);
2025 stage_descr = NULL;
2027 /* Increment INTRODUCE2 counter */
2028 ++(intro_point->accepted_introduce2_count);
2030 /* Find the rendezvous point */
2031 rp = find_rp_for_intro(parsed_req, &err_msg);
2032 if (!rp) {
2033 err_msg_severity = LOG_PROTOCOL_WARN;
2034 goto log_error;
2037 /* Check if we'd refuse to talk to this router */
2038 if (options->StrictNodes &&
2039 routerset_contains_extendinfo(options->ExcludeNodes, rp)) {
2040 log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
2041 "exclude, and StrictNodes is set. Refusing service.");
2042 reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
2043 goto err;
2046 base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
2048 /* Check whether there is a past request with the same Diffie-Hellman,
2049 * part 1. */
2050 replay = replaycache_add_test_and_elapsed(
2051 service->accepted_intro_dh_parts,
2052 parsed_req->dh, DH1024_KEY_LEN,
2053 &elapsed);
2055 if (replay) {
2056 /* A Tor client will send a new INTRODUCE1 cell with the same rend
2057 * cookie and DH public key as its previous one if its intro circ
2058 * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
2059 * If we received the first INTRODUCE1 cell (the intro-point relay
2060 * converts it into an INTRODUCE2 cell), we are already trying to
2061 * connect to that rend point (and may have already succeeded);
2062 * drop this cell. */
2063 log_info(LD_REND, "We received an "
2064 "INTRODUCE2 cell with same first part of "
2065 "Diffie-Hellman handshake %d seconds ago. Dropping "
2066 "cell.",
2067 (int) elapsed);
2068 goto err;
2071 /* If the service performs client authorization, check included auth data. */
2072 if (service->clients) {
2073 if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
2074 if (rend_check_authorization(service,
2075 (const char*)parsed_req->u.v3.auth_data,
2076 parsed_req->u.v3.auth_len)) {
2077 log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
2078 } else {
2079 log_info(LD_REND, "The authorization data that are contained in "
2080 "the INTRODUCE2 cell are invalid. Dropping cell.");
2081 reason = END_CIRC_REASON_CONNECTFAILED;
2082 goto err;
2084 } else {
2085 log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
2086 "data, but we require client authorization. Dropping cell.");
2087 reason = END_CIRC_REASON_CONNECTFAILED;
2088 goto err;
2092 /* Try DH handshake... */
2093 dh = crypto_dh_new(DH_TYPE_REND);
2094 if (!dh || crypto_dh_generate_public(dh)<0) {
2095 log_warn(LD_BUG,"Internal error: couldn't build DH state "
2096 "or generate public key.");
2097 reason = END_CIRC_REASON_INTERNAL;
2098 goto err;
2100 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
2101 (char *)(parsed_req->dh),
2102 DH1024_KEY_LEN, keys,
2103 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
2104 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
2105 reason = END_CIRC_REASON_INTERNAL;
2106 goto err;
2109 circ_needs_uptime = hs_service_requires_uptime_circ(service->ports);
2111 /* help predict this next time */
2112 rep_hist_note_used_internal(now, circ_needs_uptime, 1);
2114 /* Launch a circuit to the client's chosen rendezvous point.
2116 int max_rend_failures=hs_get_service_max_rend_failures();
2117 for (i=0;i<max_rend_failures;i++) {
2118 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
2119 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2120 /* A Single Onion Service only uses a direct connection if its
2121 * firewall rules permit direct connections to the address. */
2122 if (rend_service_use_direct_connection(options, rp)) {
2123 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
2125 launched = circuit_launch_by_extend_info(
2126 CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
2128 if (launched)
2129 break;
2131 if (!launched) { /* give up */
2132 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
2133 "point %s for service %s.",
2134 safe_str_client(extend_info_describe(rp)),
2135 serviceid);
2136 reason = END_CIRC_REASON_CONNECTFAILED;
2137 goto err;
2139 log_info(LD_REND,
2140 "Accepted intro; launching circuit to %s "
2141 "(cookie %s) for service %s.",
2142 safe_str_client(extend_info_describe(rp)),
2143 hexcookie, serviceid);
2144 tor_assert(launched->build_state);
2145 /* Fill in the circuit's state. */
2147 launched->rend_data =
2148 rend_data_service_create(service->service_id, rend_pk_digest,
2149 parsed_req->rc, service->auth_type);
2151 launched->build_state->service_pending_final_cpath_ref =
2152 tor_malloc_zero(sizeof(crypt_path_reference_t));
2153 launched->build_state->service_pending_final_cpath_ref->refcount = 1;
2155 launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
2156 tor_malloc_zero(sizeof(crypt_path_t));
2157 cpath->magic = CRYPT_PATH_MAGIC;
2158 launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
2160 cpath->rend_dh_handshake_state = dh;
2161 dh = NULL;
2162 if (circuit_init_cpath_crypto(cpath,
2163 keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
2164 1, 0)<0)
2165 goto err;
2166 memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
2168 goto done;
2170 log_error:
2171 if (!err_msg) {
2172 if (stage_descr) {
2173 tor_asprintf(&err_msg,
2174 "unknown %s error for INTRODUCE2", stage_descr);
2175 } else {
2176 err_msg = tor_strdup("unknown error for INTRODUCE2");
2180 log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
2181 (unsigned)circuit->base_.n_circ_id);
2182 err:
2183 status = -1;
2184 if (dh) crypto_dh_free(dh);
2185 if (launched) {
2186 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
2188 tor_free(err_msg);
2190 done:
2191 memwipe(keys, 0, sizeof(keys));
2192 memwipe(buf, 0, sizeof(buf));
2193 memwipe(serviceid, 0, sizeof(serviceid));
2194 memwipe(hexcookie, 0, sizeof(hexcookie));
2196 /* Free the parsed cell */
2197 rend_service_free_intro(parsed_req);
2199 /* Free rp */
2200 extend_info_free(rp);
2202 return status;
2205 /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
2206 * return NULL and an error string if we can't. Return a newly allocated
2207 * extend_info_t* for the rendezvous point. */
2208 static extend_info_t *
2209 find_rp_for_intro(const rend_intro_cell_t *intro,
2210 char **err_msg_out)
2212 extend_info_t *rp = NULL;
2213 char *err_msg = NULL;
2214 const char *rp_nickname = NULL;
2215 const node_t *node = NULL;
2217 if (!intro) {
2218 if (err_msg_out)
2219 err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
2221 goto err;
2224 if (intro->version == 0 || intro->version == 1) {
2225 rp_nickname = (const char *)(intro->u.v0_v1.rp);
2227 node = node_get_by_nickname(rp_nickname, NNF_NO_WARN_UNNAMED);
2228 if (!node) {
2229 if (err_msg_out) {
2230 tor_asprintf(&err_msg,
2231 "Couldn't find router %s named in INTRODUCE2 cell",
2232 escaped_safe_str_client(rp_nickname));
2235 goto err;
2238 /* Are we in single onion mode? */
2239 const int allow_direct = rend_service_allow_non_anonymous_connection(
2240 get_options());
2241 rp = extend_info_from_node(node, allow_direct);
2242 if (!rp) {
2243 if (err_msg_out) {
2244 tor_asprintf(&err_msg,
2245 "Couldn't build extend_info_t for router %s named "
2246 "in INTRODUCE2 cell",
2247 escaped_safe_str_client(rp_nickname));
2250 goto err;
2252 } else if (intro->version == 2) {
2253 rp = extend_info_dup(intro->u.v2.extend_info);
2254 } else if (intro->version == 3) {
2255 rp = extend_info_dup(intro->u.v3.extend_info);
2256 } else {
2257 if (err_msg_out) {
2258 tor_asprintf(&err_msg,
2259 "Unknown version %d in INTRODUCE2 cell",
2260 (int)(intro->version));
2263 goto err;
2266 /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2267 * the other cases goto err. */
2268 tor_assert(rp);
2270 /* Make sure the RP we are being asked to connect to is _not_ a private
2271 * address unless it's allowed. Let's avoid to build a circuit to our
2272 * second middle node and fail right after when extending to the RP. */
2273 if (!extend_info_addr_is_allowed(&rp->addr)) {
2274 if (err_msg_out) {
2275 tor_asprintf(&err_msg,
2276 "Relay IP in INTRODUCE2 cell is private address.");
2278 extend_info_free(rp);
2279 rp = NULL;
2280 goto err;
2282 goto done;
2284 err:
2285 if (err_msg_out)
2286 *err_msg_out = err_msg;
2287 else
2288 tor_free(err_msg);
2290 done:
2291 return rp;
2294 /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
2295 * rend_service_parse_intro().
2297 void
2298 rend_service_free_intro_(rend_intro_cell_t *request)
2300 if (!request) {
2301 return;
2304 /* Free ciphertext */
2305 tor_free(request->ciphertext);
2306 request->ciphertext_len = 0;
2308 /* Have plaintext? */
2309 if (request->plaintext) {
2310 /* Zero it out just to be safe */
2311 memwipe(request->plaintext, 0, request->plaintext_len);
2312 tor_free(request->plaintext);
2313 request->plaintext_len = 0;
2316 /* Have parsed plaintext? */
2317 if (request->parsed) {
2318 switch (request->version) {
2319 case 0:
2320 case 1:
2322 * Nothing more to do; these formats have no further pointers
2323 * in them.
2325 break;
2326 case 2:
2327 extend_info_free(request->u.v2.extend_info);
2328 request->u.v2.extend_info = NULL;
2329 break;
2330 case 3:
2331 if (request->u.v3.auth_data) {
2332 memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
2333 tor_free(request->u.v3.auth_data);
2336 extend_info_free(request->u.v3.extend_info);
2337 request->u.v3.extend_info = NULL;
2338 break;
2339 default:
2340 log_info(LD_BUG,
2341 "rend_service_free_intro() saw unknown protocol "
2342 "version %d.",
2343 request->version);
2347 /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2348 memwipe(request, 0, sizeof(*request));
2350 tor_free(request);
2353 /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
2354 * rend_intro_cell_t structure. Free it with rend_service_free_intro()
2355 * when finished. The type parameter should be 1 or 2 to indicate whether
2356 * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
2357 * parts; after this, call rend_service_decrypt_intro() with a key, then
2358 * rend_service_parse_intro_plaintext() to finish parsing. The optional
2359 * err_msg_out parameter is set to a string suitable for log output
2360 * if parsing fails. This function does some validation, but only
2361 * that which depends solely on the contents of the cell and the
2362 * key; it can be unit-tested. Further validation is done in
2363 * rend_service_validate_intro().
2366 rend_intro_cell_t *
2367 rend_service_begin_parse_intro(const uint8_t *request,
2368 size_t request_len,
2369 uint8_t type,
2370 char **err_msg_out)
2372 rend_intro_cell_t *rv = NULL;
2373 char *err_msg = NULL;
2375 if (!request || request_len <= 0) goto err;
2376 if (!(type == 1 || type == 2)) goto err;
2378 /* First, check that the cell is long enough to be a sensible INTRODUCE */
2380 /* min key length plus digest length plus nickname length */
2381 if (request_len <
2382 (DIGEST_LEN + REND_COOKIE_LEN + (MAX_NICKNAME_LEN + 1) +
2383 DH1024_KEY_LEN + 42)) {
2384 if (err_msg_out) {
2385 tor_asprintf(&err_msg,
2386 "got a truncated INTRODUCE%d cell",
2387 (int)type);
2389 goto err;
2392 /* Allocate a new parsed cell structure */
2393 rv = tor_malloc_zero(sizeof(*rv));
2395 /* Set the type */
2396 rv->type = type;
2398 /* Copy in the ID */
2399 memcpy(rv->pk, request, DIGEST_LEN);
2401 /* Copy in the ciphertext */
2402 rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
2403 memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
2404 rv->ciphertext_len = request_len - DIGEST_LEN;
2406 goto done;
2408 err:
2409 rend_service_free_intro(rv);
2410 rv = NULL;
2412 if (err_msg_out && !err_msg) {
2413 tor_asprintf(&err_msg,
2414 "unknown INTRODUCE%d error",
2415 (int)type);
2418 done:
2419 if (err_msg_out) *err_msg_out = err_msg;
2420 else tor_free(err_msg);
2422 return rv;
2425 /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
2426 * cell
2429 static ssize_t
2430 rend_service_parse_intro_for_v0_or_v1(
2431 rend_intro_cell_t *intro,
2432 const uint8_t *buf,
2433 size_t plaintext_len,
2434 char **err_msg_out)
2436 const char *rp_nickname, *endptr;
2437 size_t nickname_field_len, ver_specific_len;
2439 if (intro->version == 1) {
2440 ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
2441 rp_nickname = ((const char *)buf) + 1;
2442 nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
2443 } else if (intro->version == 0) {
2444 ver_specific_len = MAX_NICKNAME_LEN + 1;
2445 rp_nickname = (const char *)buf;
2446 nickname_field_len = MAX_NICKNAME_LEN + 1;
2447 } else {
2448 if (err_msg_out)
2449 tor_asprintf(err_msg_out,
2450 "rend_service_parse_intro_for_v0_or_v1() called with "
2451 "bad version %d on INTRODUCE%d cell (this is a bug)",
2452 intro->version,
2453 (int)(intro->type));
2454 goto err;
2457 if (plaintext_len < ver_specific_len) {
2458 if (err_msg_out)
2459 tor_asprintf(err_msg_out,
2460 "short plaintext of encrypted part in v1 INTRODUCE%d "
2461 "cell (%lu bytes, needed %lu)",
2462 (int)(intro->type),
2463 (unsigned long)plaintext_len,
2464 (unsigned long)ver_specific_len);
2465 goto err;
2468 endptr = memchr(rp_nickname, 0, nickname_field_len);
2469 if (!endptr || endptr == rp_nickname) {
2470 if (err_msg_out) {
2471 tor_asprintf(err_msg_out,
2472 "couldn't find a nul-padded nickname in "
2473 "INTRODUCE%d cell",
2474 (int)(intro->type));
2476 goto err;
2479 if ((intro->version == 0 &&
2480 !is_legal_nickname(rp_nickname)) ||
2481 (intro->version == 1 &&
2482 !is_legal_nickname_or_hexdigest(rp_nickname))) {
2483 if (err_msg_out) {
2484 tor_asprintf(err_msg_out,
2485 "bad nickname in INTRODUCE%d cell",
2486 (int)(intro->type));
2488 goto err;
2491 memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
2493 return ver_specific_len;
2495 err:
2496 return -1;
2499 /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
2502 static ssize_t
2503 rend_service_parse_intro_for_v2(
2504 rend_intro_cell_t *intro,
2505 const uint8_t *buf,
2506 size_t plaintext_len,
2507 char **err_msg_out)
2509 unsigned int klen;
2510 extend_info_t *extend_info = NULL;
2511 ssize_t ver_specific_len;
2514 * We accept version 3 too so that the v3 parser can call this with
2515 * an adjusted buffer for the latter part of a v3 cell, which is
2516 * identical to a v2 cell.
2518 if (!(intro->version == 2 ||
2519 intro->version == 3)) {
2520 if (err_msg_out)
2521 tor_asprintf(err_msg_out,
2522 "rend_service_parse_intro_for_v2() called with "
2523 "bad version %d on INTRODUCE%d cell (this is a bug)",
2524 intro->version,
2525 (int)(intro->type));
2526 goto err;
2529 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2530 if (plaintext_len < 7 + DIGEST_LEN + 2) {
2531 if (err_msg_out) {
2532 tor_asprintf(err_msg_out,
2533 "truncated plaintext of encrypted parted of "
2534 "version %d INTRODUCE%d cell",
2535 intro->version,
2536 (int)(intro->type));
2539 goto err;
2542 extend_info = tor_malloc_zero(sizeof(extend_info_t));
2543 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
2544 extend_info->port = ntohs(get_uint16(buf + 5));
2545 memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
2546 extend_info->nickname[0] = '$';
2547 base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
2548 extend_info->identity_digest, DIGEST_LEN);
2549 klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
2551 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2552 if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
2553 if (err_msg_out) {
2554 tor_asprintf(err_msg_out,
2555 "truncated plaintext of encrypted parted of "
2556 "version %d INTRODUCE%d cell",
2557 intro->version,
2558 (int)(intro->type));
2561 goto err;
2564 extend_info->onion_key =
2565 crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
2566 if (!extend_info->onion_key) {
2567 if (err_msg_out) {
2568 tor_asprintf(err_msg_out,
2569 "error decoding onion key in version %d "
2570 "INTRODUCE%d cell",
2571 intro->version,
2572 (intro->type));
2575 goto err;
2577 if (128 != crypto_pk_keysize(extend_info->onion_key)) {
2578 if (err_msg_out) {
2579 tor_asprintf(err_msg_out,
2580 "invalid onion key size in version %d INTRODUCE%d cell",
2581 intro->version,
2582 (intro->type));
2585 goto err;
2588 ver_specific_len = 7+DIGEST_LEN+2+klen;
2590 if (intro->version == 2) intro->u.v2.extend_info = extend_info;
2591 else intro->u.v3.extend_info = extend_info;
2593 return ver_specific_len;
2595 err:
2596 extend_info_free(extend_info);
2598 return -1;
2601 /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
2604 static ssize_t
2605 rend_service_parse_intro_for_v3(
2606 rend_intro_cell_t *intro,
2607 const uint8_t *buf,
2608 size_t plaintext_len,
2609 char **err_msg_out)
2611 ssize_t adjust, v2_ver_specific_len, ts_offset;
2613 /* This should only be called on v3 cells */
2614 if (intro->version != 3) {
2615 if (err_msg_out)
2616 tor_asprintf(err_msg_out,
2617 "rend_service_parse_intro_for_v3() called with "
2618 "bad version %d on INTRODUCE%d cell (this is a bug)",
2619 intro->version,
2620 (int)(intro->type));
2621 goto err;
2625 * Check that we have at least enough to get auth_len:
2627 * 1 octet for version, 1 for auth_type, 2 for auth_len
2629 if (plaintext_len < 4) {
2630 if (err_msg_out) {
2631 tor_asprintf(err_msg_out,
2632 "truncated plaintext of encrypted parted of "
2633 "version %d INTRODUCE%d cell",
2634 intro->version,
2635 (int)(intro->type));
2638 goto err;
2642 * The rend_client_send_introduction() function over in rendclient.c is
2643 * broken (i.e., fails to match the spec) in such a way that we can't
2644 * change it without breaking the protocol. Specifically, it doesn't
2645 * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2646 * by two bytes after that. Calculate ts_offset and do everything from
2647 * the timestamp on relative to that to handle this dain bramage.
2650 intro->u.v3.auth_type = buf[1];
2651 if (intro->u.v3.auth_type != REND_NO_AUTH) {
2652 intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
2653 ts_offset = 4 + intro->u.v3.auth_len;
2654 } else {
2655 intro->u.v3.auth_len = 0;
2656 ts_offset = 2;
2659 /* Check that auth len makes sense for this auth type */
2660 if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
2661 intro->u.v3.auth_type == REND_STEALTH_AUTH) {
2662 if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
2663 if (err_msg_out) {
2664 tor_asprintf(err_msg_out,
2665 "wrong auth data size %d for INTRODUCE%d cell, "
2666 "should be %d",
2667 (int)(intro->u.v3.auth_len),
2668 (int)(intro->type),
2669 REND_DESC_COOKIE_LEN);
2672 goto err;
2676 /* Check that we actually have everything up through the timestamp */
2677 if (plaintext_len < (size_t)(ts_offset)+4) {
2678 if (err_msg_out) {
2679 tor_asprintf(err_msg_out,
2680 "truncated plaintext of encrypted parted of "
2681 "version %d INTRODUCE%d cell",
2682 intro->version,
2683 (int)(intro->type));
2686 goto err;
2689 if (intro->u.v3.auth_type != REND_NO_AUTH &&
2690 intro->u.v3.auth_len > 0) {
2691 /* Okay, we can go ahead and copy auth_data */
2692 intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
2694 * We know we had an auth_len field in this case, so 4 is
2695 * always right.
2697 memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
2701 * From here on, the format is as in v2, so we call the v2 parser with
2702 * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2703 * v2 parser expects to skip over a version byte at the start, so we
2704 * adjust by 3 + ts_offset.
2706 adjust = 3 + ts_offset;
2708 v2_ver_specific_len =
2709 rend_service_parse_intro_for_v2(intro,
2710 buf + adjust, plaintext_len - adjust,
2711 err_msg_out);
2713 /* Success in v2 parser */
2714 if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
2715 /* Failure in v2 parser; it will have provided an err_msg */
2716 else return v2_ver_specific_len;
2718 err:
2719 return -1;
2722 /** Table of parser functions for version-specific parts of an INTRODUCE2
2723 * cell.
2726 static ssize_t
2727 (*intro_version_handlers[])(
2728 rend_intro_cell_t *,
2729 const uint8_t *,
2730 size_t,
2731 char **) =
2732 { rend_service_parse_intro_for_v0_or_v1,
2733 rend_service_parse_intro_for_v0_or_v1,
2734 rend_service_parse_intro_for_v2,
2735 rend_service_parse_intro_for_v3 };
2737 /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
2738 * return 0 if successful, or < 0 and write an error message to
2739 * *err_msg_out if provided.
2743 rend_service_decrypt_intro(
2744 rend_intro_cell_t *intro,
2745 crypto_pk_t *key,
2746 char **err_msg_out)
2748 char *err_msg = NULL;
2749 uint8_t key_digest[DIGEST_LEN];
2750 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
2751 ssize_t key_len;
2752 uint8_t buf[RELAY_PAYLOAD_SIZE];
2753 int result, status = -1;
2755 if (!intro || !key) {
2756 if (err_msg_out) {
2757 err_msg =
2758 tor_strdup("rend_service_decrypt_intro() called with bad "
2759 "parameters");
2762 status = -2;
2763 goto err;
2766 /* Make sure we have ciphertext */
2767 if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
2768 if (err_msg_out) {
2769 tor_asprintf(&err_msg,
2770 "rend_intro_cell_t was missing ciphertext for "
2771 "INTRODUCE%d cell",
2772 (int)(intro->type));
2774 status = -3;
2775 goto err;
2778 /* Check that this cell actually matches this service key */
2780 /* first DIGEST_LEN bytes of request is intro or service pk digest */
2781 if (crypto_pk_get_digest(key, (char *)key_digest) < 0) {
2782 if (err_msg_out)
2783 *err_msg_out = tor_strdup("Couldn't compute RSA digest.");
2784 log_warn(LD_BUG, "Couldn't compute key digest.");
2785 status = -7;
2786 goto err;
2789 if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
2790 if (err_msg_out) {
2791 base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
2792 (char*)(intro->pk), REND_SERVICE_ID_LEN);
2793 tor_asprintf(&err_msg,
2794 "got an INTRODUCE%d cell for the wrong service (%s)",
2795 (int)(intro->type),
2796 escaped(service_id));
2799 status = -4;
2800 goto err;
2803 /* Make sure the encrypted part is long enough to decrypt */
2805 key_len = crypto_pk_keysize(key);
2806 if (intro->ciphertext_len < key_len) {
2807 if (err_msg_out) {
2808 tor_asprintf(&err_msg,
2809 "got an INTRODUCE%d cell with a truncated PK-encrypted "
2810 "part",
2811 (int)(intro->type));
2814 status = -5;
2815 goto err;
2818 /* Decrypt the encrypted part */
2819 result =
2820 crypto_pk_obsolete_private_hybrid_decrypt(
2821 key, (char *)buf, sizeof(buf),
2822 (const char *)(intro->ciphertext), intro->ciphertext_len,
2823 PK_PKCS1_OAEP_PADDING, 1);
2824 if (result < 0) {
2825 if (err_msg_out) {
2826 tor_asprintf(&err_msg,
2827 "couldn't decrypt INTRODUCE%d cell",
2828 (int)(intro->type));
2830 status = -6;
2831 goto err;
2833 intro->plaintext_len = result;
2834 intro->plaintext = tor_malloc(intro->plaintext_len);
2835 memcpy(intro->plaintext, buf, intro->plaintext_len);
2837 status = 0;
2839 goto done;
2841 err:
2842 if (err_msg_out && !err_msg) {
2843 tor_asprintf(&err_msg,
2844 "unknown INTRODUCE%d error decrypting encrypted part",
2845 intro ? (int)(intro->type) : -1);
2848 done:
2849 if (err_msg_out) *err_msg_out = err_msg;
2850 else tor_free(err_msg);
2852 /* clean up potentially sensitive material */
2853 memwipe(buf, 0, sizeof(buf));
2854 memwipe(key_digest, 0, sizeof(key_digest));
2855 memwipe(service_id, 0, sizeof(service_id));
2857 return status;
2860 /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
2861 * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
2862 * message to *err_msg_out if provided.
2866 rend_service_parse_intro_plaintext(
2867 rend_intro_cell_t *intro,
2868 char **err_msg_out)
2870 char *err_msg = NULL;
2871 ssize_t ver_specific_len, ver_invariant_len;
2872 uint8_t version;
2873 int status = -1;
2875 if (!intro) {
2876 if (err_msg_out) {
2877 err_msg =
2878 tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2879 "rend_intro_cell_t");
2882 status = -2;
2883 goto err;
2886 /* Check that we have plaintext */
2887 if (!(intro->plaintext) || intro->plaintext_len <= 0) {
2888 if (err_msg_out) {
2889 err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
2891 status = -3;
2892 goto err;
2895 /* In all formats except v0, the first byte is a version number */
2896 version = intro->plaintext[0];
2898 /* v0 has no version byte (stupid...), so handle it as a fallback */
2899 if (version > 3) version = 0;
2901 /* Copy the version into the parsed cell structure */
2902 intro->version = version;
2904 /* Call the version-specific parser from the table */
2905 ver_specific_len =
2906 intro_version_handlers[version](intro,
2907 intro->plaintext, intro->plaintext_len,
2908 &err_msg);
2909 if (ver_specific_len < 0) {
2910 status = -4;
2911 goto err;
2914 /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
2915 * and at the end of the plaintext of the encrypted part of the cell.
2918 ver_invariant_len = intro->plaintext_len - ver_specific_len;
2919 if (ver_invariant_len < REND_COOKIE_LEN + DH1024_KEY_LEN) {
2920 tor_asprintf(&err_msg,
2921 "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2922 (int)(intro->type),
2923 (long)(intro->plaintext_len));
2924 status = -5;
2925 goto err;
2926 } else if (ver_invariant_len > REND_COOKIE_LEN + DH1024_KEY_LEN) {
2927 tor_asprintf(&err_msg,
2928 "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2929 (int)(intro->type),
2930 (long)(intro->plaintext_len));
2931 status = -6;
2932 goto err;
2933 } else {
2934 memcpy(intro->rc,
2935 intro->plaintext + ver_specific_len,
2936 REND_COOKIE_LEN);
2937 memcpy(intro->dh,
2938 intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
2939 DH1024_KEY_LEN);
2942 /* Flag it as being fully parsed */
2943 intro->parsed = 1;
2945 status = 0;
2946 goto done;
2948 err:
2949 if (err_msg_out && !err_msg) {
2950 tor_asprintf(&err_msg,
2951 "unknown INTRODUCE%d error parsing encrypted part",
2952 intro ? (int)(intro->type) : -1);
2955 done:
2956 if (err_msg_out) *err_msg_out = err_msg;
2957 else tor_free(err_msg);
2959 return status;
2962 /** Do validity checks on a parsed intro cell after decryption; some of
2963 * these are not done in rend_service_parse_intro_plaintext() itself because
2964 * they depend on a lot of other state and would make it hard to unit test.
2965 * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
2966 * optionally writes out an error message for logging. If an err_msg
2967 * pointer is provided, it is the caller's responsibility to free any
2968 * provided message.
2972 rend_service_validate_intro_late(const rend_intro_cell_t *intro,
2973 char **err_msg_out)
2975 int status = 0;
2977 if (!intro) {
2978 if (err_msg_out)
2979 *err_msg_out =
2980 tor_strdup("NULL intro cell passed to "
2981 "rend_service_validate_intro_late()");
2983 status = -1;
2984 goto err;
2987 if (intro->version == 3 && intro->parsed) {
2988 if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
2989 intro->u.v3.auth_type == REND_BASIC_AUTH ||
2990 intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
2991 /* This is an informative message, not an error, as in the old code */
2992 if (err_msg_out)
2993 tor_asprintf(err_msg_out,
2994 "unknown authorization type %d",
2995 intro->u.v3.auth_type);
2999 err:
3000 return status;
3003 /** Called when we fail building a rendezvous circuit at some point other
3004 * than the last hop: launches a new circuit to the same rendezvous point.
3006 void
3007 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
3009 origin_circuit_t *newcirc;
3010 cpath_build_state_t *newstate, *oldstate;
3012 tor_assert(oldcirc->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
3013 oldstate = oldcirc->build_state;
3014 tor_assert(oldstate);
3016 if (oldstate->service_pending_final_cpath_ref == NULL) {
3017 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
3018 "Initiator will retry.");
3019 return;
3022 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
3023 safe_str(extend_info_describe(oldstate->chosen_exit)));
3025 /* You'd think Single Onion Services would want to retry the rendezvous
3026 * using a direct connection. But if it's blocked by a firewall, or the
3027 * service is IPv6-only, or the rend point avoiding becoming a one-hop
3028 * proxy, we need a 3-hop connection. */
3029 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
3030 oldstate->chosen_exit,
3031 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
3033 if (!newcirc) {
3034 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
3035 safe_str(extend_info_describe(oldstate->chosen_exit)));
3036 return;
3038 newstate = newcirc->build_state;
3039 tor_assert(newstate);
3040 newstate->failure_count = oldstate->failure_count+1;
3041 newstate->expiry_time = oldstate->expiry_time;
3042 newstate->service_pending_final_cpath_ref =
3043 oldstate->service_pending_final_cpath_ref;
3044 ++(newstate->service_pending_final_cpath_ref->refcount);
3046 newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
3049 /** Launch a circuit to serve as an introduction point for the service
3050 * <b>service</b> at the introduction point <b>nickname</b>
3052 static int
3053 rend_service_launch_establish_intro(rend_service_t *service,
3054 rend_intro_point_t *intro)
3056 origin_circuit_t *launched;
3057 int flags = CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL;
3058 const or_options_t *options = get_options();
3059 extend_info_t *launch_ei = intro->extend_info;
3060 extend_info_t *direct_ei = NULL;
3062 /* Are we in single onion mode? */
3063 if (rend_service_allow_non_anonymous_connection(options)) {
3064 /* Do we have a descriptor for the node?
3065 * We've either just chosen it from the consensus, or we've just reviewed
3066 * our intro points to see which ones are still valid, and deleted the ones
3067 * that aren't in the consensus any more. */
3068 const node_t *node = node_get_by_id(launch_ei->identity_digest);
3069 if (BUG(!node)) {
3070 /* The service has kept an intro point after it went missing from the
3071 * consensus. If we did anything else here, it would be a consensus
3072 * distinguisher. Which are less of an issue for single onion services,
3073 * but still a bug. */
3074 return -1;
3076 /* Can we connect to the node directly? If so, replace launch_ei
3077 * (a multi-hop extend_info) with one suitable for direct connection. */
3078 if (rend_service_use_direct_connection_node(options, node)) {
3079 direct_ei = extend_info_from_node(node, 1);
3080 if (BUG(!direct_ei)) {
3081 /* rend_service_use_direct_connection_node and extend_info_from_node
3082 * disagree about which addresses on this node are permitted. This
3083 * should never happen. Avoiding the connection is a safe response. */
3084 return -1;
3086 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
3087 launch_ei = direct_ei;
3090 /* launch_ei is either intro->extend_info, or has been replaced with a valid
3091 * extend_info for single onion service direct connection. */
3092 tor_assert(launch_ei);
3093 /* We must have the same intro when making a direct connection. */
3094 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3095 launch_ei->identity_digest,
3096 DIGEST_LEN));
3098 log_info(LD_REND,
3099 "Launching circuit to introduction point %s%s%s for service %s",
3100 safe_str_client(extend_info_describe(intro->extend_info)),
3101 direct_ei ? " via direct address " : "",
3102 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
3103 service->service_id);
3105 rep_hist_note_used_internal(time(NULL), 1, 0);
3107 ++service->n_intro_circuits_launched;
3108 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
3109 launch_ei, flags);
3111 if (!launched) {
3112 log_info(LD_REND,
3113 "Can't launch circuit to establish introduction at %s%s%s.",
3114 safe_str_client(extend_info_describe(intro->extend_info)),
3115 direct_ei ? " via direct address " : "",
3116 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
3118 extend_info_free(direct_ei);
3119 return -1;
3121 /* We must have the same exit node even if cannibalized or direct connection.
3123 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3124 launched->build_state->chosen_exit->identity_digest,
3125 DIGEST_LEN));
3127 launched->rend_data = rend_data_service_create(service->service_id,
3128 service->pk_digest, NULL,
3129 service->auth_type);
3130 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
3131 if (launched->base_.state == CIRCUIT_STATE_OPEN)
3132 rend_service_intro_has_opened(launched);
3133 extend_info_free(direct_ei);
3134 return 0;
3137 /** Return the number of introduction points that are established for the
3138 * given service. */
3139 static unsigned int
3140 count_established_intro_points(const rend_service_t *service)
3142 unsigned int num = 0;
3144 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
3145 num += intro->circuit_established
3147 return num;
3150 /** Return the number of introduction points that are or are being
3151 * established for the given service. This function iterates over all
3152 * circuit and count those that are linked to the service and are waiting
3153 * for the intro point to respond. */
3154 static unsigned int
3155 count_intro_point_circuits(const rend_service_t *service)
3157 unsigned int num_ipos = 0;
3158 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
3159 if (!circ->marked_for_close &&
3160 circ->state == CIRCUIT_STATE_OPEN &&
3161 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3162 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
3163 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
3164 if (oc->rend_data &&
3165 rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
3166 num_ipos++;
3170 SMARTLIST_FOREACH_END(circ);
3171 return num_ipos;
3174 /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
3175 write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
3176 as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
3177 crypto material. On success, fill <b>cell_body_out</b> and return the number
3178 of bytes written. On fail, return -1.
3180 ssize_t
3181 rend_service_encode_establish_intro_cell(char *cell_body_out,
3182 size_t cell_body_out_len,
3183 crypto_pk_t *intro_key,
3184 const char *rend_circ_nonce)
3186 int retval = -1;
3187 int r;
3188 int len = 0;
3189 char auth[DIGEST_LEN + 9];
3191 tor_assert(intro_key);
3192 tor_assert(rend_circ_nonce);
3194 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3195 r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
3196 RELAY_PAYLOAD_SIZE-2);
3197 if (r < 0) {
3198 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
3199 goto err;
3201 len = r;
3202 set_uint16(cell_body_out, htons((uint16_t)len));
3203 len += 2;
3204 memcpy(auth, rend_circ_nonce, DIGEST_LEN);
3205 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
3206 if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
3207 goto err;
3208 len += 20;
3209 r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
3210 cell_body_out_len - len,
3211 cell_body_out, len);
3212 if (r<0) {
3213 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
3214 goto err;
3216 len += r;
3218 retval = len;
3220 err:
3221 memwipe(auth, 0, sizeof(auth));
3223 return retval;
3226 /** Called when we're done building a circuit to an introduction point:
3227 * sends a RELAY_ESTABLISH_INTRO cell.
3229 void
3230 rend_service_intro_has_opened(origin_circuit_t *circuit)
3232 rend_service_t *service;
3233 char buf[RELAY_PAYLOAD_SIZE];
3234 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3235 unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0;
3236 int reason = END_CIRC_REASON_TORPROTOCOL;
3237 const char *rend_pk_digest;
3239 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
3240 assert_circ_anonymity_ok(circuit, get_options());
3241 tor_assert(circuit->cpath);
3242 tor_assert(circuit->rend_data);
3243 /* XXX: This is version 2 specific (only on supported). */
3244 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3246 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3247 rend_pk_digest, REND_SERVICE_ID_LEN);
3249 service = rend_service_get_by_pk_digest(rend_pk_digest);
3250 if (!service) {
3251 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
3252 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3253 reason = END_CIRC_REASON_NOSUCHSERVICE;
3254 goto err;
3257 /* Take the current amount of expiring nodes and the current amount of IP
3258 * circuits and compute how many valid IP circuits we have. */
3259 expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes);
3260 num_ip_circuits = count_intro_point_circuits(service);
3261 /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
3262 * case this condition turns out false because it means that all circuits
3263 * are expiring so we need to keep this circuit. */
3264 if (num_ip_circuits > expiring_nodes_len) {
3265 valid_ip_circuits = num_ip_circuits - expiring_nodes_len;
3268 /* If we already have enough introduction circuits for this service,
3269 * redefine this one as a general circuit or close it, depending.
3270 * Subtract the amount of expiring nodes here because the circuits are
3271 * still opened. */
3272 if (valid_ip_circuits > service->n_intro_points_wanted) {
3273 const or_options_t *options = get_options();
3274 /* Remove the intro point associated with this circuit, it's being
3275 * repurposed or closed thus cleanup memory. */
3276 rend_intro_point_t *intro = find_intro_point(circuit);
3277 if (intro != NULL) {
3278 smartlist_remove(service->intro_nodes, intro);
3279 rend_intro_point_free(intro);
3282 if (options->ExcludeNodes) {
3283 /* XXXX in some future version, we can test whether the transition is
3284 allowed or not given the actual nodes in the circuit. But for now,
3285 this case, we might as well close the thing. */
3286 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3287 "circuit, but we already have enough. Closing it.");
3288 reason = END_CIRC_REASON_NONE;
3289 goto err;
3290 } else {
3291 tor_assert(circuit->build_state->is_internal);
3292 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3293 "circuit, but we already have enough. Redefining purpose to "
3294 "general; leaving as internal.");
3296 if (circuit_should_use_vanguards(TO_CIRCUIT(circuit)->purpose)) {
3297 circuit_change_purpose(TO_CIRCUIT(circuit),
3298 CIRCUIT_PURPOSE_HS_VANGUARDS);
3299 } else {
3300 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
3304 rend_data_free(circuit->rend_data);
3305 circuit->rend_data = NULL;
3308 crypto_pk_t *intro_key = circuit->intro_key;
3309 circuit->intro_key = NULL;
3310 crypto_pk_free(intro_key);
3313 circuit_has_opened(circuit);
3314 goto done;
3318 log_info(LD_REND,
3319 "Established circuit %u as introduction point for service %s",
3320 (unsigned)circuit->base_.n_circ_id, serviceid);
3321 circuit_log_path(LOG_INFO, LD_REND, circuit);
3323 /* Send the ESTABLISH_INTRO cell */
3325 ssize_t len;
3326 len = rend_service_encode_establish_intro_cell(buf, sizeof(buf),
3327 circuit->intro_key,
3328 circuit->cpath->prev->rend_circ_nonce);
3329 if (len < 0) {
3330 reason = END_CIRC_REASON_INTERNAL;
3331 goto err;
3334 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3335 RELAY_COMMAND_ESTABLISH_INTRO,
3336 buf, len, circuit->cpath->prev)<0) {
3337 log_info(LD_GENERAL,
3338 "Couldn't send introduction request for service %s on circuit %u",
3339 serviceid, (unsigned)circuit->base_.n_circ_id);
3340 goto done;
3344 /* We've attempted to use this circuit */
3345 pathbias_count_use_attempt(circuit);
3347 goto done;
3349 err:
3350 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3351 done:
3352 memwipe(buf, 0, sizeof(buf));
3353 memwipe(serviceid, 0, sizeof(serviceid));
3355 return;
3358 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
3359 * live introduction point, and note that the service descriptor is
3360 * now out-of-date. */
3362 rend_service_intro_established(origin_circuit_t *circuit,
3363 const uint8_t *request,
3364 size_t request_len)
3366 rend_service_t *service;
3367 rend_intro_point_t *intro;
3368 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3369 (void) request;
3370 (void) request_len;
3371 tor_assert(circuit->rend_data);
3372 /* XXX: This is version 2 specific (only supported one for now). */
3373 const char *rend_pk_digest =
3374 (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3376 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
3377 log_warn(LD_PROTOCOL,
3378 "received INTRO_ESTABLISHED cell on non-intro circuit.");
3379 goto err;
3381 service = rend_service_get_by_pk_digest(rend_pk_digest);
3382 if (!service) {
3383 log_warn(LD_REND, "Unknown service on introduction circuit %u.",
3384 (unsigned)circuit->base_.n_circ_id);
3385 goto err;
3387 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
3388 rend_pk_digest, REND_SERVICE_ID_LEN);
3389 /* We've just successfully established a intro circuit to one of our
3390 * introduction point, account for it. */
3391 intro = find_intro_point(circuit);
3392 if (intro == NULL) {
3393 log_warn(LD_REND,
3394 "Introduction circuit established without a rend_intro_point_t "
3395 "object for service %s on circuit %u",
3396 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3397 goto err;
3399 intro->circuit_established = 1;
3400 /* We might not have every introduction point ready but at this point we
3401 * know that the descriptor needs to be uploaded. */
3402 service->desc_is_dirty = time(NULL);
3403 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
3405 log_info(LD_REND,
3406 "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3407 (unsigned)circuit->base_.n_circ_id, serviceid);
3409 /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3410 * used the circ */
3411 pathbias_mark_use_success(circuit);
3413 return 0;
3414 err:
3415 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
3416 return -1;
3419 /** Called once a circuit to a rendezvous point is established: sends a
3420 * RELAY_COMMAND_RENDEZVOUS1 cell.
3422 void
3423 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
3425 rend_service_t *service;
3426 char buf[RELAY_PAYLOAD_SIZE];
3427 crypt_path_t *hop;
3428 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3429 char hexcookie[9];
3430 int reason;
3431 const char *rend_cookie, *rend_pk_digest;
3433 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
3434 tor_assert(circuit->cpath);
3435 tor_assert(circuit->build_state);
3436 assert_circ_anonymity_ok(circuit, get_options());
3437 tor_assert(circuit->rend_data);
3439 /* XXX: This is version 2 specific (only one supported). */
3440 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
3441 NULL);
3442 rend_cookie = circuit->rend_data->rend_cookie;
3444 /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
3445 * timestamp regardless of its content because that circuit could have been
3446 * cannibalized so in any cases, we are about to use that circuit more. */
3447 circuit->base_.timestamp_dirty = time(NULL);
3449 /* This may be redundant */
3450 pathbias_count_use_attempt(circuit);
3452 hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
3454 base16_encode(hexcookie,9, rend_cookie,4);
3455 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3456 rend_pk_digest, REND_SERVICE_ID_LEN);
3458 log_info(LD_REND,
3459 "Done building circuit %u to rendezvous with "
3460 "cookie %s for service %s",
3461 (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
3462 circuit_log_path(LOG_INFO, LD_REND, circuit);
3464 /* Clear the 'in-progress HS circ has timed out' flag for
3465 * consistency with what happens on the client side; this line has
3466 * no effect on Tor's behaviour. */
3467 circuit->hs_circ_has_timed_out = 0;
3469 /* If hop is NULL, another rend circ has already connected to this
3470 * rend point. Close this circ. */
3471 if (hop == NULL) {
3472 log_info(LD_REND, "Another rend circ has already reached this rend point; "
3473 "closing this rend circ.");
3474 reason = END_CIRC_REASON_NONE;
3475 goto err;
3478 /* Remove our final cpath element from the reference, so that no
3479 * other circuit will try to use it. Store it in
3480 * pending_final_cpath for now to ensure that it will be freed if
3481 * our rendezvous attempt fails. */
3482 circuit->build_state->pending_final_cpath = hop;
3483 circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
3485 service = rend_service_get_by_pk_digest(rend_pk_digest);
3486 if (!service) {
3487 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
3488 "rendezvous circuit.");
3489 reason = END_CIRC_REASON_INTERNAL;
3490 goto err;
3493 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3494 memcpy(buf, rend_cookie, REND_COOKIE_LEN);
3495 if (crypto_dh_get_public(hop->rend_dh_handshake_state,
3496 buf+REND_COOKIE_LEN, DH1024_KEY_LEN)<0) {
3497 log_warn(LD_GENERAL,"Couldn't get DH public key.");
3498 reason = END_CIRC_REASON_INTERNAL;
3499 goto err;
3501 memcpy(buf+REND_COOKIE_LEN+DH1024_KEY_LEN, hop->rend_circ_nonce,
3502 DIGEST_LEN);
3504 /* Send the cell */
3505 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3506 RELAY_COMMAND_RENDEZVOUS1,
3507 buf, HS_LEGACY_RENDEZVOUS_CELL_SIZE,
3508 circuit->cpath->prev)<0) {
3509 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
3510 goto done;
3513 crypto_dh_free(hop->rend_dh_handshake_state);
3514 hop->rend_dh_handshake_state = NULL;
3516 /* Append the cpath entry. */
3517 hop->state = CPATH_STATE_OPEN;
3518 /* set the windows to default. these are the windows
3519 * that the service thinks the client has.
3521 hop->package_window = circuit_initial_package_window();
3522 hop->deliver_window = CIRCWINDOW_START;
3524 onion_append_to_cpath(&circuit->cpath, hop);
3525 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
3527 /* Change the circuit purpose. */
3528 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
3530 goto done;
3532 err:
3533 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3534 done:
3535 memwipe(buf, 0, sizeof(buf));
3536 memwipe(serviceid, 0, sizeof(serviceid));
3537 memwipe(hexcookie, 0, sizeof(hexcookie));
3539 return;
3543 * Manage introduction points
3546 /** Return the (possibly non-open) introduction circuit ending at
3547 * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
3548 * (<b>desc_version</b> is ignored). Return NULL if no such service is
3549 * found.
3551 static origin_circuit_t *
3552 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
3554 origin_circuit_t *circ = NULL;
3556 tor_assert(intro);
3557 while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3558 (uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
3559 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3560 intro->extend_info->identity_digest, DIGEST_LEN) &&
3561 circ->rend_data) {
3562 return circ;
3566 circ = NULL;
3567 while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3568 (uint8_t *) pk_digest,
3569 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
3570 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3571 intro->extend_info->identity_digest, DIGEST_LEN) &&
3572 circ->rend_data) {
3573 return circ;
3576 return NULL;
3579 /** Return the corresponding introdution point using the circuit <b>circ</b>
3580 * found in the <b>service</b>. NULL is returned if not found. */
3581 static rend_intro_point_t *
3582 find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
3584 tor_assert(service);
3585 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3586 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3588 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
3589 intro_point,
3590 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3591 return intro_point;
3594 return NULL;
3597 /** Return a pointer to the rend_intro_point_t corresponding to the
3598 * service-side introduction circuit <b>circ</b>. */
3599 static rend_intro_point_t *
3600 find_intro_point(origin_circuit_t *circ)
3602 const char *serviceid;
3603 rend_service_t *service = NULL;
3605 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3606 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3607 tor_assert(circ->rend_data);
3608 serviceid = rend_data_get_address(circ->rend_data);
3610 SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
3611 if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
3612 service = s;
3613 break;
3616 if (service == NULL) return NULL;
3618 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
3619 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3620 return intro_point;
3623 return NULL;
3626 /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
3627 * associated with the rend_service_descriptor_t <b>renddesc</b> to
3628 * the responsible hidden service directories OR the hidden service
3629 * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
3630 * <b>seconds_valid</b> are only passed for logging purposes.
3632 void
3633 directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
3634 smartlist_t *descs, smartlist_t *hs_dirs,
3635 const char *service_id, int seconds_valid)
3637 int i, j, failed_upload = 0;
3638 smartlist_t *responsible_dirs = smartlist_new();
3639 smartlist_t *successful_uploads = smartlist_new();
3640 routerstatus_t *hs_dir;
3641 for (i = 0; i < smartlist_len(descs); i++) {
3642 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
3643 /** If any HSDirs are specified, they should be used instead of
3644 * the responsible directories */
3645 if (hs_dirs && smartlist_len(hs_dirs) > 0) {
3646 smartlist_add_all(responsible_dirs, hs_dirs);
3647 } else {
3648 /* Determine responsible dirs. */
3649 if (hid_serv_get_responsible_directories(responsible_dirs,
3650 desc->desc_id) < 0) {
3651 log_warn(LD_REND, "Could not determine the responsible hidden service "
3652 "directories to post descriptors to.");
3653 control_event_hs_descriptor_upload(service_id,
3654 "UNKNOWN",
3655 "UNKNOWN", NULL);
3656 goto done;
3659 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
3660 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
3661 char *hs_dir_ip;
3662 const node_t *node;
3663 rend_data_t *rend_data;
3664 hs_dir = smartlist_get(responsible_dirs, j);
3665 if (smartlist_contains_digest(renddesc->successful_uploads,
3666 hs_dir->identity_digest))
3667 /* Don't upload descriptor if we succeeded in doing so last time. */
3668 continue;
3669 node = node_get_by_id(hs_dir->identity_digest);
3670 if (!node || !node_has_preferred_descriptor(node,0)) {
3671 log_info(LD_REND, "Not launching upload for for v2 descriptor to "
3672 "hidden service directory %s; we don't have its "
3673 "router descriptor. Queuing for later upload.",
3674 safe_str_client(routerstatus_describe(hs_dir)));
3675 failed_upload = -1;
3676 continue;
3678 /* Send publish request. */
3680 /* We need the service ID to identify which service did the upload
3681 * request. Lookup is made in rend_service_desc_has_uploaded(). */
3682 rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
3683 REND_NO_AUTH);
3684 directory_request_t *req =
3685 directory_request_new(DIR_PURPOSE_UPLOAD_RENDDESC_V2);
3686 directory_request_set_routerstatus(req, hs_dir);
3687 directory_request_set_indirection(req, DIRIND_ANONYMOUS);
3688 directory_request_set_payload(req,
3689 desc->desc_str, strlen(desc->desc_str));
3690 directory_request_set_rend_query(req, rend_data);
3691 directory_initiate_request(req);
3692 directory_request_free(req);
3694 rend_data_free(rend_data);
3695 base32_encode(desc_id_base32, sizeof(desc_id_base32),
3696 desc->desc_id, DIGEST_LEN);
3697 hs_dir_ip = tor_dup_ip(hs_dir->addr);
3698 log_info(LD_REND, "Launching upload for v2 descriptor for "
3699 "service '%s' with descriptor ID '%s' with validity "
3700 "of %d seconds to hidden service directory '%s' on "
3701 "%s:%d.",
3702 safe_str_client(service_id),
3703 safe_str_client(desc_id_base32),
3704 seconds_valid,
3705 hs_dir->nickname,
3706 hs_dir_ip,
3707 hs_dir->or_port);
3708 control_event_hs_descriptor_upload(service_id,
3709 hs_dir->identity_digest,
3710 desc_id_base32, NULL);
3711 tor_free(hs_dir_ip);
3712 /* Remember successful upload to this router for next time. */
3713 if (!smartlist_contains_digest(successful_uploads,
3714 hs_dir->identity_digest))
3715 smartlist_add(successful_uploads, hs_dir->identity_digest);
3717 smartlist_clear(responsible_dirs);
3719 if (!failed_upload) {
3720 if (renddesc->successful_uploads) {
3721 SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
3722 smartlist_free(renddesc->successful_uploads);
3723 renddesc->successful_uploads = NULL;
3725 renddesc->all_uploads_performed = 1;
3726 } else {
3727 /* Remember which routers worked this time, so that we don't upload the
3728 * descriptor to them again. */
3729 if (!renddesc->successful_uploads)
3730 renddesc->successful_uploads = smartlist_new();
3731 SMARTLIST_FOREACH(successful_uploads, const char *, c, {
3732 if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
3733 char *hsdir_id = tor_memdup(c, DIGEST_LEN);
3734 smartlist_add(renddesc->successful_uploads, hsdir_id);
3738 done:
3739 smartlist_free(responsible_dirs);
3740 smartlist_free(successful_uploads);
3743 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
3744 * and upload it/them to the responsible hidden service directories.
3746 static void
3747 upload_service_descriptor(rend_service_t *service)
3749 time_t now = time(NULL);
3750 int rendpostperiod;
3751 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3752 int uploaded = 0;
3754 rendpostperiod = get_options()->RendPostPeriod;
3756 networkstatus_t *c = networkstatus_get_latest_consensus();
3757 if (c && smartlist_len(c->routerstatus_list) > 0) {
3758 int seconds_valid, i, j, num_descs;
3759 smartlist_t *descs = smartlist_new();
3760 smartlist_t *client_cookies = smartlist_new();
3761 /* Either upload a single descriptor (including replicas) or one
3762 * descriptor for each authorized client in case of authorization
3763 * type 'stealth'. */
3764 num_descs = service->auth_type == REND_STEALTH_AUTH ?
3765 smartlist_len(service->clients) : 1;
3766 for (j = 0; j < num_descs; j++) {
3767 crypto_pk_t *client_key = NULL;
3768 rend_authorized_client_t *client = NULL;
3769 smartlist_clear(client_cookies);
3770 switch (service->auth_type) {
3771 case REND_NO_AUTH:
3772 /* Do nothing here. */
3773 break;
3774 case REND_BASIC_AUTH:
3775 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
3776 cl, smartlist_add(client_cookies, cl->descriptor_cookie));
3777 break;
3778 case REND_STEALTH_AUTH:
3779 client = smartlist_get(service->clients, j);
3780 client_key = client->client_key;
3781 smartlist_add(client_cookies, client->descriptor_cookie);
3782 break;
3784 /* Encode the current descriptor. */
3785 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3786 now, 0,
3787 service->auth_type,
3788 client_key,
3789 client_cookies);
3790 if (seconds_valid < 0) {
3791 log_warn(LD_BUG, "Internal error: couldn't encode service "
3792 "descriptor; not uploading.");
3793 smartlist_free(descs);
3794 smartlist_free(client_cookies);
3795 return;
3797 rend_get_service_id(service->desc->pk, serviceid);
3798 if (get_options()->PublishHidServDescriptors) {
3799 /* Post the current descriptors to the hidden service directories. */
3800 log_info(LD_REND, "Launching upload for hidden service %s",
3801 serviceid);
3802 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3803 seconds_valid);
3805 /* Free memory for descriptors. */
3806 for (i = 0; i < smartlist_len(descs); i++)
3807 rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3808 smartlist_clear(descs);
3809 /* Update next upload time. */
3810 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3811 > rendpostperiod)
3812 service->next_upload_time = now + rendpostperiod;
3813 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
3814 service->next_upload_time = now + seconds_valid + 1;
3815 else
3816 service->next_upload_time = now + seconds_valid -
3817 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
3818 /* Post also the next descriptors, if necessary. */
3819 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
3820 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3821 now, 1,
3822 service->auth_type,
3823 client_key,
3824 client_cookies);
3825 if (seconds_valid < 0) {
3826 log_warn(LD_BUG, "Internal error: couldn't encode service "
3827 "descriptor; not uploading.");
3828 smartlist_free(descs);
3829 smartlist_free(client_cookies);
3830 return;
3832 if (get_options()->PublishHidServDescriptors) {
3833 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3834 seconds_valid);
3836 /* Free memory for descriptors. */
3837 for (i = 0; i < smartlist_len(descs); i++)
3838 rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3839 smartlist_clear(descs);
3842 smartlist_free(descs);
3843 smartlist_free(client_cookies);
3844 uploaded = 1;
3845 if (get_options()->PublishHidServDescriptors) {
3846 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
3847 } else {
3848 log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
3852 /* If not uploaded, try again in one minute. */
3853 if (!uploaded)
3854 service->next_upload_time = now + 60;
3856 /* Unmark dirty flag of this service. */
3857 service->desc_is_dirty = 0;
3860 /** Return the number of INTRODUCE2 cells this hidden service has received
3861 * from this intro point. */
3862 static int
3863 intro_point_accepted_intro_count(rend_intro_point_t *intro)
3865 return intro->accepted_introduce2_count;
3868 /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
3869 * should stop publishing it in new descriptors and eventually close
3870 * it). */
3871 static int
3872 intro_point_should_expire_now(rend_intro_point_t *intro,
3873 time_t now)
3875 tor_assert(intro != NULL);
3877 if (intro->time_published == -1) {
3878 /* Don't expire an intro point if we haven't even published it yet. */
3879 return 0;
3882 if (intro_point_accepted_intro_count(intro) >=
3883 intro->max_introductions) {
3884 /* This intro point has been used too many times. Expire it now. */
3885 return 1;
3888 if (intro->time_to_expire == -1) {
3889 /* This intro point has been published, but we haven't picked an
3890 * expiration time for it. Pick one now. */
3891 int intro_point_lifetime_seconds =
3892 crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
3893 INTRO_POINT_LIFETIME_MAX_SECONDS);
3895 /* Start the expiration timer now, rather than when the intro
3896 * point was first published. There shouldn't be much of a time
3897 * difference. */
3898 intro->time_to_expire = now + intro_point_lifetime_seconds;
3900 return 0;
3903 /* This intro point has a time to expire set already. Use it. */
3904 return (now >= intro->time_to_expire);
3907 /** Iterate over intro points in the given service and remove the invalid
3908 * ones. For an intro point object to be considered invalid, the circuit
3909 * _and_ node need to have disappeared.
3911 * If the intro point should expire, it's placed into the expiring_nodes
3912 * list of the service and removed from the active intro nodes list.
3914 * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
3916 * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
3917 * circuit disappeared but the node is still in the consensus. */
3918 static void
3919 remove_invalid_intro_points(rend_service_t *service,
3920 smartlist_t *exclude_nodes,
3921 smartlist_t *retry_nodes, time_t now)
3923 tor_assert(service);
3925 /* Remove any expired nodes that doesn't have a circuit. */
3926 SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
3927 intro) {
3928 origin_circuit_t *intro_circ =
3929 find_intro_circuit(intro, service->pk_digest);
3930 if (intro_circ) {
3931 continue;
3933 /* No more circuit, cleanup the into point object. */
3934 SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
3935 rend_intro_point_free(intro);
3936 } SMARTLIST_FOREACH_END(intro);
3938 SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
3939 intro) {
3940 /* Find the introduction point node object. */
3941 const node_t *node =
3942 node_get_by_id(intro->extend_info->identity_digest);
3943 /* Find the intro circuit, this might be NULL. */
3944 origin_circuit_t *intro_circ =
3945 find_intro_circuit(intro, service->pk_digest);
3947 /* Add the valid node to the exclusion list so we don't try to establish
3948 * an introduction point to it again. */
3949 if (node && exclude_nodes) {
3950 smartlist_add(exclude_nodes, (void*) node);
3953 /* First, make sure we still have a valid circuit for this intro point.
3954 * If we dont, we'll give up on it and make a new one. */
3955 if (intro_circ == NULL) {
3956 log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
3957 " (circuit disappeared).",
3958 safe_str_client(extend_info_describe(intro->extend_info)),
3959 safe_str_client(service->service_id));
3960 /* We've lost the circuit for this intro point, flag it so it can be
3961 * accounted for when considiring uploading a descriptor. */
3962 intro->circuit_established = 0;
3964 /* Node is gone or we've reached our maximum circuit creationg retry
3965 * count, clean up everything, we'll find a new one. */
3966 if (node == NULL ||
3967 intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
3968 rend_intro_point_free(intro);
3969 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
3970 /* We've just killed the intro point, nothing left to do. */
3971 continue;
3974 /* The intro point is still alive so let's try to use it again because
3975 * we have a published descriptor containing it. Keep the intro point
3976 * in the intro_nodes list because it's still valid, we are rebuilding
3977 * a circuit to it. */
3978 if (retry_nodes) {
3979 smartlist_add(retry_nodes, intro);
3982 /* else, the circuit is valid so in both cases, node being alive or not,
3983 * we leave the circuit and intro point object as is. Closing the
3984 * circuit here would leak new consensus timing and freeing the intro
3985 * point object would make the intro circuit unusable. */
3987 /* Now, check if intro point should expire. If it does, queue it so
3988 * it can be cleaned up once it has been replaced properly. */
3989 if (intro_point_should_expire_now(intro, now)) {
3990 log_info(LD_REND, "Expiring %s as intro point for %s.",
3991 safe_str_client(extend_info_describe(intro->extend_info)),
3992 safe_str_client(service->service_id));
3993 /* We might have put it in the retry list if so, undo. */
3994 if (retry_nodes) {
3995 smartlist_remove(retry_nodes, intro);
3997 smartlist_add(service->expiring_nodes, intro);
3998 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
3999 /* Intro point is expired, we need a new one thus don't consider it
4000 * anymore has a valid established intro point. */
4001 intro->circuit_established = 0;
4003 } SMARTLIST_FOREACH_END(intro);
4006 /** A new descriptor has been successfully uploaded for the given
4007 * <b>rend_data</b>. Remove and free the expiring nodes from the associated
4008 * service. */
4009 void
4010 rend_service_desc_has_uploaded(const rend_data_t *rend_data)
4012 rend_service_t *service;
4013 const char *onion_address;
4015 tor_assert(rend_data);
4017 onion_address = rend_data_get_address(rend_data);
4019 service = rend_service_get_by_service_id(onion_address);
4020 if (service == NULL) {
4021 return;
4024 SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
4025 intro) {
4026 origin_circuit_t *intro_circ =
4027 find_intro_circuit(intro, service->pk_digest);
4028 if (intro_circ != NULL) {
4029 circuit_mark_for_close(TO_CIRCUIT(intro_circ),
4030 END_CIRC_REASON_FINISHED);
4032 SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
4033 rend_intro_point_free(intro);
4034 } SMARTLIST_FOREACH_END(intro);
4037 /** Don't try to build more than this many circuits before giving up
4038 * for a while. Dynamically calculated based on the configured number of
4039 * introduction points for the service, n_intro_points_wanted. */
4040 static int
4041 rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
4043 /* Allow all but one of the initial connections to fail and be
4044 * retried. (If all fail, we *want* to wait, because something is broken.) */
4045 tor_assert(n_intro_points_wanted <= NUM_INTRO_POINTS_MAX);
4047 /* For the normal use case, 3 intro points plus 2 extra for performance and
4048 * allow that twice because once every 24h or so, we can do it twice for two
4049 * descriptors that is the current one and the next one. So (3 + 2) * 2 ==
4050 * 12 allowed attempts for one period. */
4051 return ((n_intro_points_wanted + NUM_INTRO_POINTS_EXTRA) * 2);
4054 /** For every service, check how many intro points it currently has, and:
4055 * - Invalidate introdution points based on specific criteria, see
4056 * remove_invalid_intro_points comments.
4057 * - Pick new intro points as necessary.
4058 * - Launch circuits to any new intro points.
4060 * This is called once a second by the main loop.
4062 void
4063 rend_consider_services_intro_points(time_t now)
4065 int i;
4066 const or_options_t *options = get_options();
4067 /* Are we in single onion mode? */
4068 const int allow_direct = rend_service_allow_non_anonymous_connection(
4069 get_options());
4070 /* List of nodes we need to _exclude_ when choosing a new node to
4071 * establish an intro point to. */
4072 smartlist_t *exclude_nodes;
4073 /* List of nodes we need to retry to build a circuit on them because the
4074 * node is valid but circuit died. */
4075 smartlist_t *retry_nodes;
4077 if (!have_completed_a_circuit())
4078 return;
4080 exclude_nodes = smartlist_new();
4081 retry_nodes = smartlist_new();
4083 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
4084 int r;
4085 /* Number of intro points we want to open and add to the intro nodes
4086 * list of the service. */
4087 unsigned int n_intro_points_to_open;
4088 /* Have an unsigned len so we can use it to compare values else gcc is
4089 * not happy with unmatching signed comparaison. */
4090 unsigned int intro_nodes_len;
4091 /* Different service are allowed to have the same introduction point as
4092 * long as they are on different circuit thus why we clear this list. */
4093 smartlist_clear(exclude_nodes);
4094 smartlist_clear(retry_nodes);
4096 /* Cleanup the invalid intro points and save the node objects, if any,
4097 * in the exclude_nodes and retry_nodes lists. */
4098 remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
4100 /* This retry period is important here so we don't stress circuit
4101 * creation. */
4103 if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
4104 /* One period has elapsed:
4105 * - if we stopped, we can try building circuits again,
4106 * - if we haven't, we reset the circuit creation counts. */
4107 rend_log_intro_limit(service, LOG_INFO);
4108 service->intro_period_started = now;
4109 service->n_intro_circuits_launched = 0;
4110 } else if (service->n_intro_circuits_launched >=
4111 rend_max_intro_circs_per_period(
4112 service->n_intro_points_wanted)) {
4113 /* We have failed too many times in this period; wait for the next
4114 * one before we try to initiate any more connections. */
4115 rend_log_intro_limit(service, LOG_WARN);
4116 continue;
4119 /* Let's try to rebuild circuit on the nodes we want to retry on. */
4120 SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
4121 r = rend_service_launch_establish_intro(service, intro);
4122 if (r < 0) {
4123 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4124 safe_str_client(extend_info_describe(intro->extend_info)),
4125 safe_str_client(service->service_id));
4126 /* Unable to launch a circuit to that intro point, remove it from
4127 * the valid list so we can create a new one. */
4128 smartlist_remove(service->intro_nodes, intro);
4129 rend_intro_point_free(intro);
4130 continue;
4132 intro->circuit_retries++;
4133 } SMARTLIST_FOREACH_END(intro);
4135 /* Avoid mismatched signed comparaison below. */
4136 intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
4138 /* Quiescent state, we have more or the equal amount of wanted node for
4139 * this service. Proceed to the next service. We can have more nodes
4140 * because we launch extra preemptive circuits if our intro nodes list was
4141 * originally empty for performance reasons. */
4142 if (intro_nodes_len >= service->n_intro_points_wanted) {
4143 continue;
4146 /* Number of intro points we want to open which is the wanted amount minus
4147 * the current amount of valid nodes. We know that this won't underflow
4148 * because of the check above. */
4149 n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
4150 if (intro_nodes_len == 0) {
4151 /* We want to end up with n_intro_points_wanted intro points, but if
4152 * we have no intro points at all (chances are they all cycled or we
4153 * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
4154 * and use the first n_intro_points_wanted that complete. See proposal
4155 * #155, section 4 for the rationale of this which is purely for
4156 * performance.
4158 * The ones after the first n_intro_points_to_open will be converted
4159 * to 'general' internal circuits in rend_service_intro_has_opened(),
4160 * and then we'll drop them from the list of intro points. */
4161 n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
4164 for (i = 0; i < (int) n_intro_points_to_open; i++) {
4165 const node_t *node;
4166 rend_intro_point_t *intro;
4167 router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
4168 router_crn_flags_t direct_flags = flags;
4169 direct_flags |= CRN_PREF_ADDR;
4170 direct_flags |= CRN_DIRECT_CONN;
4172 node = router_choose_random_node(exclude_nodes,
4173 options->ExcludeNodes,
4174 allow_direct ? direct_flags : flags);
4175 /* If we are in single onion mode, retry node selection for a 3-hop
4176 * path */
4177 if (allow_direct && !node) {
4178 log_info(LD_REND,
4179 "Unable to find an intro point that we can connect to "
4180 "directly for %s, falling back to a 3-hop path.",
4181 safe_str_client(service->service_id));
4182 node = router_choose_random_node(exclude_nodes,
4183 options->ExcludeNodes, flags);
4186 if (!node) {
4187 log_warn(LD_REND,
4188 "We only have %d introduction points established for %s; "
4189 "wanted %u.",
4190 smartlist_len(service->intro_nodes),
4191 safe_str_client(service->service_id),
4192 n_intro_points_to_open);
4193 break;
4195 /* Add the chosen node to the exclusion list in order to avoid picking
4196 * it again in the next iteration. */
4197 smartlist_add(exclude_nodes, (void*)node);
4198 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4199 /* extend_info is for clients, so we want the multi-hop primary ORPort,
4200 * even if we are a single onion service and intend to connect to it
4201 * directly ourselves. */
4202 intro->extend_info = extend_info_from_node(node, 0);
4203 if (BUG(intro->extend_info == NULL)) {
4204 break;
4206 intro->intro_key = crypto_pk_new();
4207 const int fail = crypto_pk_generate_key(intro->intro_key);
4208 tor_assert(!fail);
4209 intro->time_published = -1;
4210 intro->time_to_expire = -1;
4211 intro->max_introductions =
4212 crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
4213 INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
4214 smartlist_add(service->intro_nodes, intro);
4215 log_info(LD_REND, "Picked router %s as an intro point for %s.",
4216 safe_str_client(node_describe(node)),
4217 safe_str_client(service->service_id));
4218 /* Establish new introduction circuit to our chosen intro point. */
4219 r = rend_service_launch_establish_intro(service, intro);
4220 if (r < 0) {
4221 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4222 safe_str_client(extend_info_describe(intro->extend_info)),
4223 safe_str_client(service->service_id));
4224 /* This funcion will be called again by the main loop so this intro
4225 * point without a intro circuit will be retried on or removed after
4226 * a maximum number of attempts. */
4229 } SMARTLIST_FOREACH_END(service);
4230 smartlist_free(exclude_nodes);
4231 smartlist_free(retry_nodes);
4234 #define MIN_REND_INITIAL_POST_DELAY (30)
4235 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4237 /** Regenerate and upload rendezvous service descriptors for all
4238 * services, if necessary. If the descriptor has been dirty enough
4239 * for long enough, definitely upload; else only upload when the
4240 * periodic timeout has expired.
4242 * For the first upload, pick a random time between now and two periods
4243 * from now, and pick it independently for each service.
4245 void
4246 rend_consider_services_upload(time_t now)
4248 int i;
4249 rend_service_t *service;
4250 const or_options_t *options = get_options();
4251 int rendpostperiod = options->RendPostPeriod;
4252 int rendinitialpostdelay = (options->TestingTorNetwork ?
4253 MIN_REND_INITIAL_POST_DELAY_TESTING :
4254 MIN_REND_INITIAL_POST_DELAY);
4256 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4257 service = smartlist_get(rend_service_list, i);
4258 if (!service->next_upload_time) { /* never been uploaded yet */
4259 /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4260 * the descriptor is stable before being published. See comment below. */
4261 service->next_upload_time =
4262 now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
4263 /* Single Onion Services prioritise availability over hiding their
4264 * startup time, as their IP address is publicly discoverable anyway.
4266 if (rend_service_reveal_startup_time(options)) {
4267 service->next_upload_time = now + rendinitialpostdelay;
4270 /* Does every introduction points have been established? */
4271 unsigned int intro_points_ready =
4272 count_established_intro_points(service) >=
4273 service->n_intro_points_wanted;
4274 if (intro_points_ready &&
4275 (service->next_upload_time < now ||
4276 (service->desc_is_dirty &&
4277 service->desc_is_dirty < now-rendinitialpostdelay))) {
4278 /* if it's time, or if the directory servers have a wrong service
4279 * descriptor and ours has been stable for rendinitialpostdelay seconds,
4280 * upload a new one of each format. */
4281 rend_service_update_descriptor(service);
4282 upload_service_descriptor(service);
4287 /** True if the list of available router descriptors might have changed so
4288 * that we should have a look whether we can republish previously failed
4289 * rendezvous service descriptors. */
4290 static int consider_republishing_rend_descriptors = 1;
4292 /** Called when our internal view of the directory has changed, so that we
4293 * might have router descriptors of hidden service directories available that
4294 * we did not have before. */
4295 void
4296 rend_hsdir_routers_changed(void)
4298 consider_republishing_rend_descriptors = 1;
4301 /** Consider republication of v2 rendezvous service descriptors that failed
4302 * previously, but without regenerating descriptor contents.
4304 void
4305 rend_consider_descriptor_republication(void)
4307 int i;
4308 rend_service_t *service;
4310 if (!consider_republishing_rend_descriptors)
4311 return;
4312 consider_republishing_rend_descriptors = 0;
4314 if (!get_options()->PublishHidServDescriptors)
4315 return;
4317 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4318 service = smartlist_get(rend_service_list, i);
4319 if (service->desc && !service->desc->all_uploads_performed) {
4320 /* If we failed in uploading a descriptor last time, try again *without*
4321 * updating the descriptor's contents. */
4322 upload_service_descriptor(service);
4327 /** Log the status of introduction points for all rendezvous services
4328 * at log severity <b>severity</b>.
4330 void
4331 rend_service_dump_stats(int severity)
4333 int i,j;
4334 rend_service_t *service;
4335 rend_intro_point_t *intro;
4336 const char *safe_name;
4337 origin_circuit_t *circ;
4339 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4340 service = smartlist_get(rend_service_list, i);
4341 tor_log(severity, LD_GENERAL, "Service configured in %s:",
4342 rend_service_escaped_dir(service));
4343 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
4344 intro = smartlist_get(service->intro_nodes, j);
4345 safe_name = safe_str_client(intro->extend_info->nickname);
4347 circ = find_intro_circuit(intro, service->pk_digest);
4348 if (!circ) {
4349 tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
4350 j, safe_name);
4351 continue;
4353 tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
4354 j, safe_name, circuit_state_to_string(circ->base_.state));
4359 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
4360 * <b>circ</b>, and look up the port and address based on conn-\>port.
4361 * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
4362 * for which the circuit should be closed, -1 on other failure,
4363 * or 0 for success.
4366 rend_service_set_connection_addr_port(edge_connection_t *conn,
4367 origin_circuit_t *circ)
4369 rend_service_t *service;
4370 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4371 const char *rend_pk_digest;
4373 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
4374 tor_assert(circ->rend_data);
4375 log_debug(LD_REND,"beginning to hunt for addr/port");
4376 rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
4377 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
4378 rend_pk_digest, REND_SERVICE_ID_LEN);
4379 service = rend_service_get_by_pk_digest(rend_pk_digest);
4380 if (!service) {
4381 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
4382 "rendezvous circuit %u; closing.",
4383 serviceid, (unsigned)circ->base_.n_circ_id);
4384 return -2;
4386 if (service->max_streams_per_circuit > 0) {
4387 /* Enforce the streams-per-circuit limit, and refuse to provide a
4388 * mapping if this circuit will exceed the limit. */
4389 #define MAX_STREAM_WARN_INTERVAL 600
4390 static struct ratelim_t stream_ratelim =
4391 RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
4392 if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
4393 log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
4394 "Maximum streams per circuit limit reached on rendezvous "
4395 "circuit %u; %s. Circuit has %d out of %d streams.",
4396 (unsigned)circ->base_.n_circ_id,
4397 service->max_streams_close_circuit ?
4398 "closing circuit" :
4399 "ignoring open stream request",
4400 circ->rend_data->nr_streams,
4401 service->max_streams_per_circuit);
4402 return service->max_streams_close_circuit ? -2 : -1;
4406 if (hs_set_conn_addr_port(service->ports, conn) == 0) {
4407 /* Successfully set the port to the connection. We are done. */
4408 return 0;
4411 log_info(LD_REND,
4412 "No virtual port mapping exists for port %d on service %s",
4413 conn->base_.port, serviceid);
4415 if (service->allow_unknown_ports)
4416 return -1;
4417 else
4418 return -2;
4421 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4423 static int
4424 rend_service_non_anonymous_mode_consistent(const or_options_t *options)
4426 /* !! is used to make these options boolean */
4427 return (!! options->HiddenServiceSingleHopMode ==
4428 !! options->HiddenServiceNonAnonymousMode);
4431 /* Do the options allow onion services to make direct (non-anonymous)
4432 * connections to introduction or rendezvous points?
4433 * Must only be called after options_validate_single_onion() has successfully
4434 * checked onion service option consistency.
4435 * Returns true if tor is in HiddenServiceSingleHopMode. */
4437 rend_service_allow_non_anonymous_connection(const or_options_t *options)
4439 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4440 return options->HiddenServiceSingleHopMode ? 1 : 0;
4443 /* Do the options allow us to reveal the exact startup time of the onion
4444 * service?
4445 * Single Onion Services prioritise availability over hiding their
4446 * startup time, as their IP address is publicly discoverable anyway.
4447 * Must only be called after options_validate_single_onion() has successfully
4448 * checked onion service option consistency.
4449 * Returns true if tor is in non-anonymous hidden service mode. */
4451 rend_service_reveal_startup_time(const or_options_t *options)
4453 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4454 return rend_service_non_anonymous_mode_enabled(options);
4457 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4458 * config option?
4459 * Must only be called after options_validate_single_onion() has successfully
4460 * checked onion service option consistency.
4463 rend_service_non_anonymous_mode_enabled(const or_options_t *options)
4465 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4466 return options->HiddenServiceNonAnonymousMode ? 1 : 0;
4469 #ifdef TOR_UNIT_TESTS
4471 STATIC void
4472 set_rend_service_list(smartlist_t *new_list)
4474 rend_service_list = new_list;
4477 STATIC void
4478 set_rend_rend_service_staging_list(smartlist_t *new_list)
4480 rend_service_staging_list = new_list;
4483 #endif /* defined(TOR_UNIT_TESTS) */