Merge remote-tracking branch 'public/bug23985_029' into maint-0.2.9
[tor.git] / src / or / rendservice.c
bloba8c383444da171141d2438bbaccf5aba58460c44
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2016, 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 "or.h"
13 #include "circpathbias.h"
14 #include "circuitbuild.h"
15 #include "circuitlist.h"
16 #include "circuituse.h"
17 #include "config.h"
18 #include "control.h"
19 #include "directory.h"
20 #include "main.h"
21 #include "networkstatus.h"
22 #include "nodelist.h"
23 #include "policies.h"
24 #include "rendclient.h"
25 #include "rendcommon.h"
26 #include "rendservice.h"
27 #include "router.h"
28 #include "relay.h"
29 #include "rephist.h"
30 #include "replaycache.h"
31 #include "routerlist.h"
32 #include "routerparse.h"
33 #include "routerset.h"
35 struct rend_service_t;
36 static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
37 const char *pk_digest);
38 static rend_intro_point_t *find_intro_point(origin_circuit_t *circ);
39 static rend_intro_point_t *find_expiring_intro_point(
40 struct rend_service_t *service, origin_circuit_t *circ);
42 static extend_info_t *find_rp_for_intro(
43 const rend_intro_cell_t *intro,
44 char **err_msg_out);
46 static int intro_point_accepted_intro_count(rend_intro_point_t *intro);
47 static int intro_point_should_expire_now(rend_intro_point_t *intro,
48 time_t now);
49 static int rend_service_derive_key_digests(struct rend_service_t *s);
50 static int rend_service_load_keys(struct rend_service_t *s);
51 static int rend_service_load_auth_keys(struct rend_service_t *s,
52 const char *hfname);
53 static struct rend_service_t *rend_service_get_by_pk_digest(
54 const char* digest);
55 static struct rend_service_t *rend_service_get_by_service_id(const char *id);
56 static const char *rend_service_escaped_dir(
57 const struct rend_service_t *s);
59 static ssize_t rend_service_parse_intro_for_v0_or_v1(
60 rend_intro_cell_t *intro,
61 const uint8_t *buf,
62 size_t plaintext_len,
63 char **err_msg_out);
64 static ssize_t rend_service_parse_intro_for_v2(
65 rend_intro_cell_t *intro,
66 const uint8_t *buf,
67 size_t plaintext_len,
68 char **err_msg_out);
69 static ssize_t rend_service_parse_intro_for_v3(
70 rend_intro_cell_t *intro,
71 const uint8_t *buf,
72 size_t plaintext_len,
73 char **err_msg_out);
75 static int rend_service_check_private_dir(const or_options_t *options,
76 const rend_service_t *s,
77 int create);
78 static int rend_service_check_private_dir_impl(const or_options_t *options,
79 const rend_service_t *s,
80 int create);
82 /** Represents the mapping from a virtual port of a rendezvous service to
83 * a real port on some IP.
85 struct rend_service_port_config_s {
86 /* The incoming HS virtual port we're mapping */
87 uint16_t virtual_port;
88 /* Is this an AF_UNIX port? */
89 unsigned int is_unix_addr:1;
90 /* The outgoing TCP port to use, if !is_unix_addr */
91 uint16_t real_port;
92 /* The outgoing IPv4 or IPv6 address to use, if !is_unix_addr */
93 tor_addr_t real_addr;
94 /* The socket path to connect to, if is_unix_addr */
95 char unix_addr[FLEXIBLE_ARRAY_MEMBER];
98 /** Try to maintain this many intro points per service by default. */
99 #define NUM_INTRO_POINTS_DEFAULT 3
100 /** Maximum number of intro points per service. */
101 #define NUM_INTRO_POINTS_MAX 10
102 /** Number of extra intro points we launch if our set of intro nodes is
103 * empty. See proposal 155, section 4. */
104 #define NUM_INTRO_POINTS_EXTRA 2
106 /** If we can't build our intro circuits, don't retry for this long. */
107 #define INTRO_CIRC_RETRY_PERIOD (60*5)
108 /** Don't try to build more than this many circuits before giving up
109 * for a while.*/
110 #define MAX_INTRO_CIRCS_PER_PERIOD 10
111 /** How many times will a hidden service operator attempt to connect to
112 * a requested rendezvous point before giving up? */
113 #define MAX_REND_FAILURES 1
114 /** How many seconds should we spend trying to connect to a requested
115 * rendezvous point before giving up? */
116 #define MAX_REND_TIMEOUT 30
118 /* Hidden service directory file names:
119 * new file names should be added to rend_service_add_filenames_to_list()
120 * for sandboxing purposes. */
121 static const char *private_key_fname = "private_key";
122 static const char *hostname_fname = "hostname";
123 static const char *client_keys_fname = "client_keys";
124 static const char *sos_poison_fname = "onion_service_non_anonymous";
126 /** Returns a escaped string representation of the service, <b>s</b>.
128 static const char *
129 rend_service_escaped_dir(const struct rend_service_t *s)
131 return (s->directory) ? escaped(s->directory) : "[EPHEMERAL]";
134 /** A list of rend_service_t's for services run on this OP.
136 static smartlist_t *rend_service_list = NULL;
138 /** Return the number of rendezvous services we have configured. */
140 num_rend_services(void)
142 if (!rend_service_list)
143 return 0;
144 return smartlist_len(rend_service_list);
147 /** Helper: free storage held by a single service authorized client entry. */
148 void
149 rend_authorized_client_free(rend_authorized_client_t *client)
151 if (!client)
152 return;
153 if (client->client_key)
154 crypto_pk_free(client->client_key);
155 if (client->client_name)
156 memwipe(client->client_name, 0, strlen(client->client_name));
157 tor_free(client->client_name);
158 memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
159 tor_free(client);
162 /** Helper for strmap_free. */
163 static void
164 rend_authorized_client_strmap_item_free(void *authorized_client)
166 rend_authorized_client_free(authorized_client);
169 /** Release the storage held by <b>service</b>.
171 STATIC void
172 rend_service_free(rend_service_t *service)
174 if (!service)
175 return;
177 tor_free(service->directory);
178 if (service->ports) {
179 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
180 rend_service_port_config_free(p));
181 smartlist_free(service->ports);
183 if (service->private_key)
184 crypto_pk_free(service->private_key);
185 if (service->intro_nodes) {
186 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
187 rend_intro_point_free(intro););
188 smartlist_free(service->intro_nodes);
190 if (service->expiring_nodes) {
191 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
192 rend_intro_point_free(intro););
193 smartlist_free(service->expiring_nodes);
196 rend_service_descriptor_free(service->desc);
197 if (service->clients) {
198 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
199 rend_authorized_client_free(c););
200 smartlist_free(service->clients);
202 if (service->accepted_intro_dh_parts) {
203 replaycache_free(service->accepted_intro_dh_parts);
205 tor_free(service);
208 /** Release all the storage held in rend_service_list.
210 void
211 rend_service_free_all(void)
213 if (!rend_service_list)
214 return;
216 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
217 rend_service_free(ptr));
218 smartlist_free(rend_service_list);
219 rend_service_list = NULL;
222 /** Validate <b>service</b> and add it to <b>service_list</b>, or to
223 * the global rend_service_list if <b>service_list</b> is NULL.
224 * Return 0 on success. On failure, free <b>service</b> and return -1.
225 * Takes ownership of <b>service</b>.
227 static int
228 rend_add_service(smartlist_t *service_list, rend_service_t *service)
230 int i;
231 rend_service_port_config_t *p;
233 smartlist_t *s_list;
234 /* If no special service list is provided, then just use the global one. */
235 if (!service_list) {
236 if (BUG(!rend_service_list)) {
237 /* No global HS list, which is a failure. */
238 return -1;
241 s_list = rend_service_list;
242 } else {
243 s_list = service_list;
246 service->intro_nodes = smartlist_new();
247 service->expiring_nodes = smartlist_new();
249 if (service->max_streams_per_circuit < 0) {
250 log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
251 "streams per circuit; ignoring.",
252 rend_service_escaped_dir(service));
253 rend_service_free(service);
254 return -1;
257 if (service->max_streams_close_circuit < 0 ||
258 service->max_streams_close_circuit > 1) {
259 log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
260 "max streams handling; ignoring.",
261 rend_service_escaped_dir(service));
262 rend_service_free(service);
263 return -1;
266 if (service->auth_type != REND_NO_AUTH &&
267 (!service->clients ||
268 smartlist_len(service->clients) == 0)) {
269 log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but no "
270 "clients; ignoring.",
271 rend_service_escaped_dir(service));
272 rend_service_free(service);
273 return -1;
276 if (!service->ports || !smartlist_len(service->ports)) {
277 log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured; "
278 "ignoring.",
279 rend_service_escaped_dir(service));
280 rend_service_free(service);
281 return -1;
282 } else {
283 int dupe = 0;
284 /* XXX This duplicate check has two problems:
286 * a) It's O(n^2), but the same comment from the bottom of
287 * rend_config_services() should apply.
289 * b) We only compare directory paths as strings, so we can't
290 * detect two distinct paths that specify the same directory
291 * (which can arise from symlinks, case-insensitivity, bind
292 * mounts, etc.).
294 * It also can't detect that two separate Tor instances are trying
295 * to use the same HiddenServiceDir; for that, we would need a
296 * lock file. But this is enough to detect a simple mistake that
297 * at least one person has actually made.
299 if (service->directory != NULL) {
300 /* Skip dupe for ephemeral services. */
301 SMARTLIST_FOREACH(s_list, rend_service_t*, ptr,
302 dupe = dupe ||
303 !strcmp(ptr->directory, service->directory));
304 if (dupe) {
305 log_warn(LD_REND, "Another hidden service is already configured for "
306 "directory %s, ignoring.",
307 rend_service_escaped_dir(service));
308 rend_service_free(service);
309 return -1;
312 smartlist_add(s_list, service);
313 log_debug(LD_REND,"Configuring service with directory \"%s\"",
314 service->directory);
315 for (i = 0; i < smartlist_len(service->ports); ++i) {
316 p = smartlist_get(service->ports, i);
317 if (!(p->is_unix_addr)) {
318 log_debug(LD_REND,
319 "Service maps port %d to %s",
320 p->virtual_port,
321 fmt_addrport(&p->real_addr, p->real_port));
322 } else {
323 #ifdef HAVE_SYS_UN_H
324 log_debug(LD_REND,
325 "Service maps port %d to socket at \"%s\"",
326 p->virtual_port, p->unix_addr);
327 #else
328 log_debug(LD_REND,
329 "Service maps port %d to an AF_UNIX socket, but we "
330 "have no AF_UNIX support on this platform. This is "
331 "probably a bug.",
332 p->virtual_port);
333 #endif /* defined(HAVE_SYS_UN_H) */
336 return 0;
338 /* NOTREACHED */
341 /** Return a new rend_service_port_config_t with its path set to
342 * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
343 static rend_service_port_config_t *
344 rend_service_port_config_new(const char *socket_path)
346 if (!socket_path)
347 return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
349 const size_t pathlen = strlen(socket_path) + 1;
350 rend_service_port_config_t *conf =
351 tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
352 memcpy(conf->unix_addr, socket_path, pathlen);
353 conf->is_unix_addr = 1;
354 return conf;
357 /** Parses a real-port to virtual-port mapping separated by the provided
358 * separator and returns a new rend_service_port_config_t, or NULL and an
359 * optional error string on failure.
361 * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
363 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
365 rend_service_port_config_t *
366 rend_service_parse_port_config(const char *string, const char *sep,
367 char **err_msg_out)
369 smartlist_t *sl;
370 int virtport;
371 int realport = 0;
372 uint16_t p;
373 tor_addr_t addr;
374 rend_service_port_config_t *result = NULL;
375 unsigned int is_unix_addr = 0;
376 const char *socket_path = NULL;
377 char *err_msg = NULL;
378 char *addrport = NULL;
380 sl = smartlist_new();
381 smartlist_split_string(sl, string, sep,
382 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
383 if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
384 if (err_msg_out)
385 err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
386 goto err;
388 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
389 if (!virtport) {
390 if (err_msg_out)
391 tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
392 "port configuration", escaped(smartlist_get(sl,0)));
394 goto err;
396 if (smartlist_len(sl) == 1) {
397 /* No addr:port part; use default. */
398 realport = virtport;
399 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
400 } else {
401 int ret;
403 const char *addrport_element = smartlist_get(sl,1);
404 const char *rest = NULL;
405 int is_unix;
406 ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
407 &is_unix, &rest);
408 if (ret < 0) {
409 tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
410 "service configuration", addrport_element);
411 goto err;
413 if (is_unix) {
414 socket_path = addrport;
415 is_unix_addr = 1;
416 } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
417 /* else try it as an IP:port pair if it has a : or . in it */
418 if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
419 if (err_msg_out)
420 err_msg = tor_strdup("Unparseable address in hidden service port "
421 "configuration.");
423 goto err;
425 realport = p?p:virtport;
426 } else {
427 /* No addr:port, no addr -- must be port. */
428 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
429 if (!realport) {
430 if (err_msg_out)
431 tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
432 "hidden service port configuration.",
433 escaped(addrport));
435 goto err;
437 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
441 /* Allow room for unix_addr */
442 result = rend_service_port_config_new(socket_path);
443 result->virtual_port = virtport;
444 result->is_unix_addr = is_unix_addr;
445 if (!is_unix_addr) {
446 result->real_port = realport;
447 tor_addr_copy(&result->real_addr, &addr);
448 result->unix_addr[0] = '\0';
451 err:
452 tor_free(addrport);
453 if (err_msg_out) *err_msg_out = err_msg;
454 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
455 smartlist_free(sl);
457 return result;
460 /** Release all storage held in a rend_service_port_config_t. */
461 void
462 rend_service_port_config_free(rend_service_port_config_t *p)
464 tor_free(p);
467 /* Check the directory for <b>service</b>, and add the service to
468 * <b>service_list</b>, or to the global list if <b>service_list</b> is NULL.
469 * Only add the service to the list if <b>validate_only</b> is false.
470 * If <b>validate_only</b> is true, free the service.
471 * If <b>service</b> is NULL, ignore it, and return 0.
472 * Returns 0 on success, and -1 on failure.
473 * Takes ownership of <b>service</b>, either freeing it, or adding it to the
474 * global service list.
476 STATIC int
477 rend_service_check_dir_and_add(smartlist_t *service_list,
478 const or_options_t *options,
479 rend_service_t *service,
480 int validate_only)
482 if (!service) {
483 /* It is ok for a service to be NULL, this means there are no services */
484 return 0;
487 if (rend_service_check_private_dir(options, service, !validate_only)
488 < 0) {
489 rend_service_free(service);
490 return -1;
493 if (validate_only) {
494 rend_service_free(service);
495 return 0;
496 } else {
497 /* Use service_list for unit tests */
498 smartlist_t *s_list = NULL;
499 /* If no special service list is provided, then just use the global one. */
500 if (!service_list) {
501 if (BUG(!rend_service_list)) {
502 /* No global HS list, which is a failure, because we plan on adding to
503 * it */
504 return -1;
506 s_list = rend_service_list;
507 } else {
508 s_list = service_list;
510 /* s_list can not be NULL here - if both service_list and rend_service_list
511 * are NULL, and validate_only is false, we exit earlier in the function
513 if (BUG(!s_list)) {
514 return -1;
516 /* Ignore service failures until 030 */
517 rend_add_service(s_list, service);
518 return 0;
522 /** Set up rend_service_list, based on the values of HiddenServiceDir and
523 * HiddenServicePort in <b>options</b>. Return 0 on success and -1 on
524 * failure. (If <b>validate_only</b> is set, parse, warn and return as
525 * normal, but don't actually change the configured services.)
528 rend_config_services(const or_options_t *options, int validate_only)
530 config_line_t *line;
531 rend_service_t *service = NULL;
532 rend_service_port_config_t *portcfg;
533 smartlist_t *old_service_list = NULL;
534 int ok = 0;
536 if (!validate_only) {
537 old_service_list = rend_service_list;
538 rend_service_list = smartlist_new();
541 for (line = options->RendConfigLines; line; line = line->next) {
542 if (!strcasecmp(line->key, "HiddenServiceDir")) {
543 /* register the service we just finished parsing
544 * this code registers every service except the last one parsed,
545 * which is registered below the loop */
546 if (rend_service_check_dir_and_add(NULL, options, service,
547 validate_only) < 0) {
548 return -1;
550 service = tor_malloc_zero(sizeof(rend_service_t));
551 service->directory = tor_strdup(line->value);
552 service->ports = smartlist_new();
553 service->intro_period_started = time(NULL);
554 service->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
555 continue;
557 if (!service) {
558 log_warn(LD_CONFIG, "%s with no preceding HiddenServiceDir directive",
559 line->key);
560 rend_service_free(service);
561 return -1;
563 if (!strcasecmp(line->key, "HiddenServicePort")) {
564 char *err_msg = NULL;
565 portcfg = rend_service_parse_port_config(line->value, " ", &err_msg);
566 if (!portcfg) {
567 if (err_msg)
568 log_warn(LD_CONFIG, "%s", err_msg);
569 tor_free(err_msg);
570 rend_service_free(service);
571 return -1;
573 tor_assert(!err_msg);
574 smartlist_add(service->ports, portcfg);
575 } else if (!strcasecmp(line->key, "HiddenServiceAllowUnknownPorts")) {
576 service->allow_unknown_ports = (int)tor_parse_long(line->value,
577 10, 0, 1, &ok, NULL);
578 if (!ok) {
579 log_warn(LD_CONFIG,
580 "HiddenServiceAllowUnknownPorts should be 0 or 1, not %s",
581 line->value);
582 rend_service_free(service);
583 return -1;
585 log_info(LD_CONFIG,
586 "HiddenServiceAllowUnknownPorts=%d for %s",
587 (int)service->allow_unknown_ports, service->directory);
588 } else if (!strcasecmp(line->key,
589 "HiddenServiceDirGroupReadable")) {
590 service->dir_group_readable = (int)tor_parse_long(line->value,
591 10, 0, 1, &ok, NULL);
592 if (!ok) {
593 log_warn(LD_CONFIG,
594 "HiddenServiceDirGroupReadable should be 0 or 1, not %s",
595 line->value);
596 rend_service_free(service);
597 return -1;
599 log_info(LD_CONFIG,
600 "HiddenServiceDirGroupReadable=%d for %s",
601 service->dir_group_readable, service->directory);
602 } else if (!strcasecmp(line->key, "HiddenServiceMaxStreams")) {
603 service->max_streams_per_circuit = (int)tor_parse_long(line->value,
604 10, 0, 65535, &ok, NULL);
605 if (!ok) {
606 log_warn(LD_CONFIG,
607 "HiddenServiceMaxStreams should be between 0 and %d, not %s",
608 65535, line->value);
609 rend_service_free(service);
610 return -1;
612 log_info(LD_CONFIG,
613 "HiddenServiceMaxStreams=%d for %s",
614 service->max_streams_per_circuit, service->directory);
615 } else if (!strcasecmp(line->key, "HiddenServiceMaxStreamsCloseCircuit")) {
616 service->max_streams_close_circuit = (int)tor_parse_long(line->value,
617 10, 0, 1, &ok, NULL);
618 if (!ok) {
619 log_warn(LD_CONFIG,
620 "HiddenServiceMaxStreamsCloseCircuit should be 0 or 1, "
621 "not %s",
622 line->value);
623 rend_service_free(service);
624 return -1;
626 log_info(LD_CONFIG,
627 "HiddenServiceMaxStreamsCloseCircuit=%d for %s",
628 (int)service->max_streams_close_circuit, service->directory);
629 } else if (!strcasecmp(line->key, "HiddenServiceNumIntroductionPoints")) {
630 service->n_intro_points_wanted =
631 (unsigned int) tor_parse_long(line->value, 10,
632 NUM_INTRO_POINTS_DEFAULT,
633 NUM_INTRO_POINTS_MAX, &ok, NULL);
634 if (!ok) {
635 log_warn(LD_CONFIG,
636 "HiddenServiceNumIntroductionPoints "
637 "should be between %d and %d, not %s",
638 NUM_INTRO_POINTS_DEFAULT, NUM_INTRO_POINTS_MAX,
639 line->value);
640 rend_service_free(service);
641 return -1;
643 log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
644 service->n_intro_points_wanted, service->directory);
645 } else if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
646 /* Parse auth type and comma-separated list of client names and add a
647 * rend_authorized_client_t for each client to the service's list
648 * of authorized clients. */
649 smartlist_t *type_names_split, *clients;
650 const char *authname;
651 int num_clients;
652 if (service->auth_type != REND_NO_AUTH) {
653 log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
654 "lines for a single service.");
655 rend_service_free(service);
656 return -1;
658 type_names_split = smartlist_new();
659 smartlist_split_string(type_names_split, line->value, " ", 0, 2);
660 if (smartlist_len(type_names_split) < 1) {
661 log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
662 "should have been prevented when parsing the "
663 "configuration.");
664 smartlist_free(type_names_split);
665 rend_service_free(service);
666 return -1;
668 authname = smartlist_get(type_names_split, 0);
669 if (!strcasecmp(authname, "basic")) {
670 service->auth_type = REND_BASIC_AUTH;
671 } else if (!strcasecmp(authname, "stealth")) {
672 service->auth_type = REND_STEALTH_AUTH;
673 } else {
674 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
675 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
676 "are recognized.",
677 (char *) smartlist_get(type_names_split, 0));
678 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
679 smartlist_free(type_names_split);
680 rend_service_free(service);
681 return -1;
683 service->clients = smartlist_new();
684 if (smartlist_len(type_names_split) < 2) {
685 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
686 "auth-type '%s', but no client names.",
687 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
688 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
689 smartlist_free(type_names_split);
690 continue;
692 clients = smartlist_new();
693 smartlist_split_string(clients, smartlist_get(type_names_split, 1),
694 ",", SPLIT_SKIP_SPACE, 0);
695 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
696 smartlist_free(type_names_split);
697 /* Remove duplicate client names. */
698 num_clients = smartlist_len(clients);
699 smartlist_sort_strings(clients);
700 smartlist_uniq_strings(clients);
701 if (smartlist_len(clients) < num_clients) {
702 log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
703 "duplicate client name(s); removing.",
704 num_clients - smartlist_len(clients));
705 num_clients = smartlist_len(clients);
707 SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
709 rend_authorized_client_t *client;
710 if (!rend_valid_client_name(client_name)) {
711 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
712 "illegal client name: '%s'. Names must be "
713 "between 1 and %d characters and contain "
714 "only [A-Za-z0-9+_-].",
715 client_name, REND_CLIENTNAME_MAX_LEN);
716 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
717 smartlist_free(clients);
718 rend_service_free(service);
719 return -1;
721 client = tor_malloc_zero(sizeof(rend_authorized_client_t));
722 client->client_name = tor_strdup(client_name);
723 smartlist_add(service->clients, client);
724 log_debug(LD_REND, "Adding client name '%s'", client_name);
726 SMARTLIST_FOREACH_END(client_name);
727 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
728 smartlist_free(clients);
729 /* Ensure maximum number of clients. */
730 if ((service->auth_type == REND_BASIC_AUTH &&
731 smartlist_len(service->clients) > 512) ||
732 (service->auth_type == REND_STEALTH_AUTH &&
733 smartlist_len(service->clients) > 16)) {
734 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
735 "client authorization entries, but only a "
736 "maximum of %d entries is allowed for "
737 "authorization type '%s'.",
738 smartlist_len(service->clients),
739 service->auth_type == REND_BASIC_AUTH ? 512 : 16,
740 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
741 rend_service_free(service);
742 return -1;
744 } else {
745 tor_assert(!strcasecmp(line->key, "HiddenServiceVersion"));
746 if (strcmp(line->value, "2")) {
747 log_warn(LD_CONFIG,
748 "The only supported HiddenServiceVersion is 2.");
749 rend_service_free(service);
750 return -1;
754 /* register the final service after we have finished parsing all services
755 * this code only registers the last service, other services are registered
756 * within the loop. It is ok for this service to be NULL, it is ignored. */
757 if (rend_service_check_dir_and_add(NULL, options, service,
758 validate_only) < 0) {
759 return -1;
762 /* If this is a reload and there were hidden services configured before,
763 * keep the introduction points that are still needed and close the
764 * other ones. */
765 if (old_service_list && !validate_only) {
766 smartlist_t *surviving_services = smartlist_new();
768 /* Preserve the existing ephemeral services.
770 * This is the ephemeral service equivalent of the "Copy introduction
771 * points to new services" block, except there's no copy required since
772 * the service structure isn't regenerated.
774 * After this is done, all ephemeral services will be:
775 * * Removed from old_service_list, so the equivalent non-ephemeral code
776 * will not attempt to preserve them.
777 * * Added to the new rend_service_list (that previously only had the
778 * services listed in the configuration).
779 * * Added to surviving_services, which is the list of services that
780 * will NOT have their intro point closed.
782 SMARTLIST_FOREACH(old_service_list, rend_service_t *, old, {
783 if (!old->directory) {
784 SMARTLIST_DEL_CURRENT(old_service_list, old);
785 smartlist_add(surviving_services, old);
786 smartlist_add(rend_service_list, old);
790 /* Copy introduction points to new services. */
791 /* XXXX This is O(n^2), but it's only called on reconfigure, so it's
792 * probably ok? */
793 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, new) {
794 SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
795 if (new->directory && old->directory &&
796 !strcmp(old->directory, new->directory)) {
797 smartlist_add_all(new->intro_nodes, old->intro_nodes);
798 smartlist_clear(old->intro_nodes);
799 smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
800 smartlist_clear(old->expiring_nodes);
801 smartlist_add(surviving_services, old);
802 break;
804 } SMARTLIST_FOREACH_END(old);
805 } SMARTLIST_FOREACH_END(new);
807 /* Close introduction circuits of services we don't serve anymore. */
808 /* XXXX it would be nicer if we had a nicer abstraction to use here,
809 * so we could just iterate over the list of services to close, but
810 * once again, this isn't critical-path code. */
811 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
812 if (!circ->marked_for_close &&
813 circ->state == CIRCUIT_STATE_OPEN &&
814 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
815 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
816 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
817 int keep_it = 0;
818 tor_assert(oc->rend_data);
819 SMARTLIST_FOREACH(surviving_services, rend_service_t *, ptr, {
820 if (tor_memeq(ptr->pk_digest, oc->rend_data->rend_pk_digest,
821 DIGEST_LEN)) {
822 keep_it = 1;
823 break;
826 if (keep_it)
827 continue;
828 log_info(LD_REND, "Closing intro point %s for service %s.",
829 safe_str_client(extend_info_describe(
830 oc->build_state->chosen_exit)),
831 oc->rend_data->onion_address);
832 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
833 /* XXXX Is there another reason we should use here? */
836 SMARTLIST_FOREACH_END(circ);
837 smartlist_free(surviving_services);
838 SMARTLIST_FOREACH(old_service_list, rend_service_t *, ptr,
839 rend_service_free(ptr));
840 smartlist_free(old_service_list);
843 return 0;
846 /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
847 * client authorization <b>auth_type</b> and an optional list of
848 * rend_authorized_client_t in <b>auth_clients</b>, with
849 * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
850 * and circuit closure on max streams being exceeded set by
851 * <b>max_streams_close_circuit</b>.
853 * Ownership of pk, ports, and auth_clients is passed to this routine.
854 * Regardless of success/failure, callers should not touch these values
855 * after calling this routine, and may assume that correct cleanup has
856 * been done on failure.
858 * Return an appropriate rend_service_add_ephemeral_status_t.
860 rend_service_add_ephemeral_status_t
861 rend_service_add_ephemeral(crypto_pk_t *pk,
862 smartlist_t *ports,
863 int max_streams_per_circuit,
864 int max_streams_close_circuit,
865 rend_auth_type_t auth_type,
866 smartlist_t *auth_clients,
867 char **service_id_out)
869 *service_id_out = NULL;
870 /* Allocate the service structure, and initialize the key, and key derived
871 * parameters.
873 rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
874 s->directory = NULL; /* This indicates the service is ephemeral. */
875 s->private_key = pk;
876 s->auth_type = auth_type;
877 s->clients = auth_clients;
878 s->ports = ports;
879 s->intro_period_started = time(NULL);
880 s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
881 s->max_streams_per_circuit = max_streams_per_circuit;
882 s->max_streams_close_circuit = max_streams_close_circuit;
883 if (rend_service_derive_key_digests(s) < 0) {
884 rend_service_free(s);
885 return RSAE_BADPRIVKEY;
888 if (!s->ports || smartlist_len(s->ports) == 0) {
889 log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
890 rend_service_free(s);
891 return RSAE_BADVIRTPORT;
893 if (s->auth_type != REND_NO_AUTH &&
894 (!s->clients || smartlist_len(s->clients) == 0)) {
895 log_warn(LD_CONFIG, "At least one authorized client must be specified.");
896 rend_service_free(s);
897 return RSAE_BADAUTH;
900 /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
901 * it's not, see #14828.
903 if (rend_service_get_by_pk_digest(s->pk_digest)) {
904 log_warn(LD_CONFIG, "Onion Service private key collides with an "
905 "existing service.");
906 rend_service_free(s);
907 return RSAE_ADDREXISTS;
909 if (rend_service_get_by_service_id(s->service_id)) {
910 log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
911 rend_service_free(s);
912 return RSAE_ADDREXISTS;
915 /* Initialize the service. */
916 if (rend_add_service(NULL, s)) {
917 return RSAE_INTERNAL;
919 *service_id_out = tor_strdup(s->service_id);
921 log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
922 return RSAE_OKAY;
925 /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
926 * success, and -1 on failure.
929 rend_service_del_ephemeral(const char *service_id)
931 rend_service_t *s;
932 if (!rend_valid_service_id(service_id)) {
933 log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
934 return -1;
936 if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
937 log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
938 "removal.");
939 return -1;
941 if (s->directory) {
942 log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
943 return -1;
946 /* Kill the intro point circuit for the Onion Service, and remove it from
947 * the list. Closing existing connections is the application's problem.
949 * XXX: As with the comment in rend_config_services(), a nice abstraction
950 * would be ideal here, but for now just duplicate the code.
952 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
953 if (!circ->marked_for_close &&
954 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
955 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
956 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
957 tor_assert(oc->rend_data);
958 if (!tor_memeq(s->pk_digest, oc->rend_data->rend_pk_digest, DIGEST_LEN))
959 continue;
960 log_debug(LD_REND, "Closing intro point %s for service %s.",
961 safe_str_client(extend_info_describe(
962 oc->build_state->chosen_exit)),
963 oc->rend_data->onion_address);
964 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
966 } SMARTLIST_FOREACH_END(circ);
967 smartlist_remove(rend_service_list, s);
968 rend_service_free(s);
970 log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
972 return 0;
975 /** Replace the old value of <b>service</b>-\>desc with one that reflects
976 * the other fields in service.
978 static void
979 rend_service_update_descriptor(rend_service_t *service)
981 rend_service_descriptor_t *d;
982 origin_circuit_t *circ;
983 int i;
985 rend_service_descriptor_free(service->desc);
986 service->desc = NULL;
988 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
989 d->pk = crypto_pk_dup_key(service->private_key);
990 d->timestamp = time(NULL);
991 d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */
992 d->intro_nodes = smartlist_new();
993 /* Support intro protocols 2 and 3. */
994 d->protocols = (1 << 2) + (1 << 3);
996 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
997 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
998 rend_intro_point_t *intro_desc;
1000 /* This intro point won't be listed in the descriptor... */
1001 intro_svc->listed_in_last_desc = 0;
1003 circ = find_intro_circuit(intro_svc, service->pk_digest);
1004 if (!circ || circ->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
1005 /* This intro point's circuit isn't finished yet. Don't list it. */
1006 continue;
1009 /* ...unless this intro point is listed in the descriptor. */
1010 intro_svc->listed_in_last_desc = 1;
1012 /* We have an entirely established intro circuit. Publish it in
1013 * our descriptor. */
1014 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
1015 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
1016 if (intro_svc->intro_key)
1017 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
1018 smartlist_add(d->intro_nodes, intro_desc);
1020 if (intro_svc->time_published == -1) {
1021 /* We are publishing this intro point in a descriptor for the
1022 * first time -- note the current time in the service's copy of
1023 * the intro point. */
1024 intro_svc->time_published = time(NULL);
1029 /* Allocate and return a string containing the path to file_name in
1030 * service->directory. Asserts that service has a directory.
1031 * This function will never return NULL.
1032 * The caller must free this path. */
1033 static char *
1034 rend_service_path(const rend_service_t *service, const char *file_name)
1036 char *file_path = NULL;
1038 tor_assert(service->directory);
1040 /* Can never fail: asserts rather than leaving file_path NULL. */
1041 tor_asprintf(&file_path, "%s%s%s",
1042 service->directory, PATH_SEPARATOR, file_name);
1044 return file_path;
1047 /* Allocate and return a string containing the path to the single onion
1048 * service poison file in service->directory. Asserts that service has a
1049 * directory.
1050 * The caller must free this path. */
1051 STATIC char *
1052 rend_service_sos_poison_path(const rend_service_t *service)
1054 return rend_service_path(service, sos_poison_fname);
1057 /** Return True if hidden services <b>service> has been poisoned by single
1058 * onion mode. */
1059 static int
1060 service_is_single_onion_poisoned(const rend_service_t *service)
1062 char *poison_fname = NULL;
1063 file_status_t fstatus;
1065 /* Passing a NULL service is a bug */
1066 if (BUG(!service)) {
1067 return 0;
1070 if (!service->directory) {
1071 return 0;
1074 poison_fname = rend_service_sos_poison_path(service);
1076 fstatus = file_status(poison_fname);
1077 tor_free(poison_fname);
1079 /* If this fname is occupied, the hidden service has been poisoned.
1080 * fstatus can be FN_ERROR if the service directory does not exist, in that
1081 * case, there is obviously no private key. */
1082 if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
1083 return 1;
1086 return 0;
1089 /* Return 1 if the private key file for service exists and has a non-zero size,
1090 * and 0 otherwise. */
1091 static int
1092 rend_service_private_key_exists(const rend_service_t *service)
1094 char *private_key_path = rend_service_path(service, private_key_fname);
1095 const file_status_t private_key_status = file_status(private_key_path);
1096 tor_free(private_key_path);
1097 /* Only non-empty regular private key files could have been used before.
1098 * fstatus can be FN_ERROR if the service directory does not exist, in that
1099 * case, there is obviously no private key. */
1100 return private_key_status == FN_FILE;
1103 /** Check the single onion service poison state of the directory for s:
1104 * - If the service is poisoned, and we are in Single Onion Mode,
1105 * return 0,
1106 * - If the service is not poisoned, and we are not in Single Onion Mode,
1107 * return 0,
1108 * - Otherwise, the poison state is invalid: the service was created in one
1109 * mode, and is being used in the other, return -1.
1110 * Hidden service directories without keys are always considered consistent.
1111 * They will be poisoned after their directory is created (if needed). */
1112 STATIC int
1113 rend_service_verify_single_onion_poison(const rend_service_t* s,
1114 const or_options_t* options)
1116 /* Passing a NULL service is a bug */
1117 if (BUG(!s)) {
1118 return -1;
1121 /* Ephemeral services are checked at ADD_ONION time */
1122 if (!s->directory) {
1123 return 0;
1126 /* Services without keys are always ok - their keys will only ever be used
1127 * in the current mode */
1128 if (!rend_service_private_key_exists(s)) {
1129 return 0;
1132 /* The key has been used before in a different mode */
1133 if (service_is_single_onion_poisoned(s) !=
1134 rend_service_non_anonymous_mode_enabled(options)) {
1135 return -1;
1138 /* The key exists and is consistent with the current mode */
1139 return 0;
1142 /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
1143 * the hidden service directory for s that marks it as a single onion service.
1144 * Tor must be in single onion mode before calling this function, and the
1145 * service directory must already have been created.
1146 * Returns 0 when a directory is successfully poisoned, or if it is already
1147 * poisoned. Returns -1 on a failure to read the directory or write the poison
1148 * file, or if there is an existing private key file in the directory. (The
1149 * service should have been poisoned when the key was created.) */
1150 static int
1151 poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
1152 const or_options_t* options)
1154 /* Passing a NULL service is a bug */
1155 if (BUG(!service)) {
1156 return -1;
1159 /* We must only poison directories if we're in Single Onion mode */
1160 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1162 int fd;
1163 int retval = -1;
1164 char *poison_fname = NULL;
1166 if (!service->directory) {
1167 log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
1168 return 0;
1171 /* Make sure we're only poisoning new hidden service directories */
1172 if (rend_service_private_key_exists(service)) {
1173 log_warn(LD_BUG, "Tried to single onion poison a service directory after "
1174 "the private key was created.");
1175 return -1;
1178 /* Make sure the directory was created before calling this function. */
1179 if (BUG(rend_service_check_private_dir_impl(options, service, 0) < 0))
1180 return -1;
1182 poison_fname = rend_service_sos_poison_path(service);
1184 switch (file_status(poison_fname)) {
1185 case FN_DIR:
1186 case FN_ERROR:
1187 log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
1188 poison_fname);
1189 goto done;
1190 case FN_FILE: /* single onion poison file already exists. NOP. */
1191 case FN_EMPTY: /* single onion poison file already exists. NOP. */
1192 log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
1193 poison_fname);
1194 break;
1195 case FN_NOENT:
1196 fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
1197 if (fd < 0) {
1198 log_warn(LD_FS, "Could not create single onion poison file %s",
1199 poison_fname);
1200 goto done;
1202 close(fd);
1203 break;
1204 default:
1205 tor_assert(0);
1208 retval = 0;
1210 done:
1211 tor_free(poison_fname);
1213 return retval;
1216 /** We just got launched in Single Onion Mode. That's a non-anoymous mode for
1217 * hidden services. If s is new, we should mark its hidden service
1218 * directory appropriately so that it is never launched as a location-private
1219 * hidden service. (New directories don't have private key files.)
1220 * Return 0 on success, -1 on fail. */
1221 STATIC int
1222 rend_service_poison_new_single_onion_dir(const rend_service_t *s,
1223 const or_options_t* options)
1225 /* Passing a NULL service is a bug */
1226 if (BUG(!s)) {
1227 return -1;
1230 /* We must only poison directories if we're in Single Onion mode */
1231 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1233 if (!rend_service_private_key_exists(s)) {
1234 if (poison_new_single_onion_hidden_service_dir_impl(s, options)
1235 < 0) {
1236 return -1;
1240 return 0;
1243 /** Load and/or generate private keys for all hidden services, possibly
1244 * including keys for client authorization.
1245 * If a <b>service_list</b> is provided, treat it as the list of hidden
1246 * services (used in unittests). Otherwise, require that rend_service_list is
1247 * not NULL.
1248 * Return 0 on success, -1 on failure. */
1250 rend_service_load_all_keys(const smartlist_t *service_list)
1252 const smartlist_t *s_list = NULL;
1253 /* If no special service list is provided, then just use the global one. */
1254 if (!service_list) {
1255 if (BUG(!rend_service_list)) {
1256 return -1;
1258 s_list = rend_service_list;
1259 } else {
1260 s_list = service_list;
1263 SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
1264 if (s->private_key)
1265 continue;
1266 log_info(LD_REND, "Loading hidden-service keys from \"%s\"",
1267 s->directory);
1269 if (rend_service_load_keys(s) < 0)
1270 return -1;
1271 } SMARTLIST_FOREACH_END(s);
1273 return 0;
1276 /** Add to <b>lst</b> every filename used by <b>s</b>. */
1277 static void
1278 rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
1280 tor_assert(lst);
1281 tor_assert(s);
1282 tor_assert(s->directory);
1283 smartlist_add(lst, rend_service_path(s, private_key_fname));
1284 smartlist_add(lst, rend_service_path(s, hostname_fname));
1285 smartlist_add(lst, rend_service_path(s, client_keys_fname));
1286 smartlist_add(lst, rend_service_sos_poison_path(s));
1289 /** Add to <b>open_lst</b> every filename used by a configured hidden service,
1290 * and to <b>stat_lst</b> every directory used by a configured hidden
1291 * service */
1292 void
1293 rend_services_add_filenames_to_lists(smartlist_t *open_lst,
1294 smartlist_t *stat_lst)
1296 if (!rend_service_list)
1297 return;
1298 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
1299 if (s->directory) {
1300 rend_service_add_filenames_to_list(open_lst, s);
1301 smartlist_add(stat_lst, tor_strdup(s->directory));
1303 } SMARTLIST_FOREACH_END(s);
1306 /** Derive all rend_service_t internal material based on the service's key.
1307 * Returns 0 on sucess, -1 on failure.
1309 static int
1310 rend_service_derive_key_digests(struct rend_service_t *s)
1312 if (rend_get_service_id(s->private_key, s->service_id)<0) {
1313 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1314 return -1;
1316 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
1317 log_warn(LD_BUG, "Couldn't compute hash of public key.");
1318 return -1;
1321 return 0;
1324 /* Implements the directory check from rend_service_check_private_dir,
1325 * without doing the single onion poison checks. */
1326 static int
1327 rend_service_check_private_dir_impl(const or_options_t *options,
1328 const rend_service_t *s,
1329 int create)
1331 cpd_check_t check_opts = CPD_NONE;
1332 if (create) {
1333 check_opts |= CPD_CREATE;
1334 } else {
1335 check_opts |= CPD_CHECK_MODE_ONLY;
1336 check_opts |= CPD_CHECK;
1338 if (s->dir_group_readable) {
1339 check_opts |= CPD_GROUP_READ;
1341 /* Check/create directory */
1342 if (check_private_dir(s->directory, check_opts, options->User) < 0) {
1343 log_warn(LD_REND, "Checking service directory %s failed.", s->directory);
1344 return -1;
1347 return 0;
1350 /** Make sure that the directory for <b>s</b> is private, using the config in
1351 * <b>options</b>.
1352 * If <b>create</b> is true:
1353 * - if the directory exists, change permissions if needed,
1354 * - if the directory does not exist, create it with the correct permissions.
1355 * If <b>create</b> is false:
1356 * - if the directory exists, check permissions,
1357 * - if the directory does not exist, check if we think we can create it.
1358 * Return 0 on success, -1 on failure. */
1359 static int
1360 rend_service_check_private_dir(const or_options_t *options,
1361 const rend_service_t *s,
1362 int create)
1364 /* Passing a NULL service is a bug */
1365 if (BUG(!s)) {
1366 return -1;
1369 /* Check/create directory */
1370 if (rend_service_check_private_dir_impl(options, s, create) < 0) {
1371 return -1;
1374 /* Check if the hidden service key exists, and was created in a different
1375 * single onion service mode, and refuse to launch if it has.
1376 * This is safe to call even when create is false, as it ignores missing
1377 * keys and directories: they are always valid.
1379 if (rend_service_verify_single_onion_poison(s, options) < 0) {
1380 /* We can't use s->service_id here, as the key may not have been loaded */
1381 log_warn(LD_GENERAL, "We are configured with "
1382 "HiddenServiceNonAnonymousMode %d, but the hidden "
1383 "service key in directory %s was created in %s mode. "
1384 "This is not allowed.",
1385 rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
1386 rend_service_escaped_dir(s),
1387 rend_service_non_anonymous_mode_enabled(options) ?
1388 "an anonymous" : "a non-anonymous"
1390 return -1;
1393 /* Poison new single onion directories immediately after they are created,
1394 * so that we never accidentally launch non-anonymous hidden services
1395 * thinking they are anonymous. Any keys created later will end up with the
1396 * correct poisoning state.
1398 if (create && rend_service_non_anonymous_mode_enabled(options)) {
1399 static int logged_warning = 0;
1401 if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
1402 log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
1403 ".");
1404 return -1;
1407 if (!logged_warning) {
1408 /* The keys for these services are linked to the server IP address */
1409 log_notice(LD_REND, "The configured onion service directories have been "
1410 "used in single onion mode. They can not be used for "
1411 "anonymous hidden services.");
1412 logged_warning = 1;
1416 return 0;
1419 /** Load and/or generate private keys for the hidden service <b>s</b>,
1420 * possibly including keys for client authorization. Return 0 on success, -1
1421 * on failure. */
1422 static int
1423 rend_service_load_keys(rend_service_t *s)
1425 char *fname = NULL;
1426 char buf[128];
1428 /* Make sure the directory was created and single onion poisoning was
1429 * checked before calling this function */
1430 if (BUG(rend_service_check_private_dir(get_options(), s, 0) < 0))
1431 goto err;
1433 /* Load key */
1434 fname = rend_service_path(s, private_key_fname);
1435 s->private_key = init_key_from_file(fname, 1, LOG_ERR, 0);
1437 if (!s->private_key)
1438 goto err;
1440 if (rend_service_derive_key_digests(s) < 0)
1441 goto err;
1443 tor_free(fname);
1444 /* Create service file */
1445 fname = rend_service_path(s, hostname_fname);
1447 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
1448 if (write_str_to_file(fname,buf,0)<0) {
1449 log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
1450 goto err;
1452 #ifndef _WIN32
1453 if (s->dir_group_readable) {
1454 /* Also verify hostname file created with group read. */
1455 if (chmod(fname, 0640))
1456 log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
1457 fname);
1459 #endif
1461 /* If client authorization is configured, load or generate keys. */
1462 if (s->auth_type != REND_NO_AUTH) {
1463 if (rend_service_load_auth_keys(s, fname) < 0) {
1464 goto err;
1468 int r = 0;
1469 goto done;
1470 err:
1471 r = -1;
1472 done:
1473 memwipe(buf, 0, sizeof(buf));
1474 tor_free(fname);
1475 return r;
1478 /** Load and/or generate client authorization keys for the hidden service
1479 * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
1480 * -1 on failure. */
1481 static int
1482 rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
1484 int r = 0;
1485 char *cfname = NULL;
1486 char *client_keys_str = NULL;
1487 strmap_t *parsed_clients = strmap_new();
1488 FILE *cfile, *hfile;
1489 open_file_t *open_cfile = NULL, *open_hfile = NULL;
1490 char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
1491 char service_id[16+1];
1492 char buf[1500];
1494 /* Load client keys and descriptor cookies, if available. */
1495 cfname = rend_service_path(s, client_keys_fname);
1496 client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
1497 if (client_keys_str) {
1498 if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
1499 log_warn(LD_CONFIG, "Previously stored client_keys file could not "
1500 "be parsed.");
1501 goto err;
1502 } else {
1503 log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
1504 strmap_size(parsed_clients));
1508 /* Prepare client_keys and hostname files. */
1509 if (!(cfile = start_writing_to_stdio_file(cfname,
1510 OPEN_FLAGS_REPLACE | O_TEXT,
1511 0600, &open_cfile))) {
1512 log_warn(LD_CONFIG, "Could not open client_keys file %s",
1513 escaped(cfname));
1514 goto err;
1517 if (!(hfile = start_writing_to_stdio_file(hfname,
1518 OPEN_FLAGS_REPLACE | O_TEXT,
1519 0600, &open_hfile))) {
1520 log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
1521 goto err;
1524 /* Either use loaded keys for configured clients or generate new
1525 * ones if a client is new. */
1526 SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
1527 rend_authorized_client_t *parsed =
1528 strmap_get(parsed_clients, client->client_name);
1529 int written;
1530 size_t len;
1531 /* Copy descriptor cookie from parsed entry or create new one. */
1532 if (parsed) {
1533 memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
1534 REND_DESC_COOKIE_LEN);
1535 } else {
1536 crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
1538 /* For compatibility with older tor clients, this does not
1539 * truncate the padding characters, unlike rend_auth_encode_cookie. */
1540 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
1541 (char *) client->descriptor_cookie,
1542 REND_DESC_COOKIE_LEN, 0) < 0) {
1543 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1544 goto err;
1546 /* Copy client key from parsed entry or create new one if required. */
1547 if (parsed && parsed->client_key) {
1548 client->client_key = crypto_pk_dup_key(parsed->client_key);
1549 } else if (s->auth_type == REND_STEALTH_AUTH) {
1550 /* Create private key for client. */
1551 crypto_pk_t *prkey = NULL;
1552 if (!(prkey = crypto_pk_new())) {
1553 log_warn(LD_BUG,"Error constructing client key");
1554 goto err;
1556 if (crypto_pk_generate_key(prkey)) {
1557 log_warn(LD_BUG,"Error generating client key");
1558 crypto_pk_free(prkey);
1559 goto err;
1561 if (crypto_pk_check_key(prkey) <= 0) {
1562 log_warn(LD_BUG,"Generated client key seems invalid");
1563 crypto_pk_free(prkey);
1564 goto err;
1566 client->client_key = prkey;
1568 /* Add entry to client_keys file. */
1569 written = tor_snprintf(buf, sizeof(buf),
1570 "client-name %s\ndescriptor-cookie %s\n",
1571 client->client_name, desc_cook_out);
1572 if (written < 0) {
1573 log_warn(LD_BUG, "Could not write client entry.");
1574 goto err;
1576 if (client->client_key) {
1577 char *client_key_out = NULL;
1578 if (crypto_pk_write_private_key_to_string(client->client_key,
1579 &client_key_out, &len) != 0) {
1580 log_warn(LD_BUG, "Internal error: "
1581 "crypto_pk_write_private_key_to_string() failed.");
1582 goto err;
1584 if (rend_get_service_id(client->client_key, service_id)<0) {
1585 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1587 * len is string length, not buffer length, but last byte is NUL
1588 * anyway.
1590 memwipe(client_key_out, 0, len);
1591 tor_free(client_key_out);
1592 goto err;
1594 written = tor_snprintf(buf + written, sizeof(buf) - written,
1595 "client-key\n%s", client_key_out);
1596 memwipe(client_key_out, 0, len);
1597 tor_free(client_key_out);
1598 if (written < 0) {
1599 log_warn(LD_BUG, "Could not write client entry.");
1600 goto err;
1602 } else {
1603 strlcpy(service_id, s->service_id, sizeof(service_id));
1606 if (fputs(buf, cfile) < 0) {
1607 log_warn(LD_FS, "Could not append client entry to file: %s",
1608 strerror(errno));
1609 goto err;
1612 /* Add line to hostname file. This is not the same encoding as in
1613 * client_keys. */
1614 char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
1615 s->auth_type);
1616 if (!encoded_cookie) {
1617 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1618 goto err;
1620 tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
1621 service_id, encoded_cookie, client->client_name);
1622 memwipe(encoded_cookie, 0, strlen(encoded_cookie));
1623 tor_free(encoded_cookie);
1625 if (fputs(buf, hfile)<0) {
1626 log_warn(LD_FS, "Could not append host entry to file: %s",
1627 strerror(errno));
1628 goto err;
1630 } SMARTLIST_FOREACH_END(client);
1632 finish_writing_to_file(open_cfile);
1633 finish_writing_to_file(open_hfile);
1635 goto done;
1636 err:
1637 r = -1;
1638 if (open_cfile)
1639 abort_writing_to_file(open_cfile);
1640 if (open_hfile)
1641 abort_writing_to_file(open_hfile);
1642 done:
1643 if (client_keys_str) {
1644 memwipe(client_keys_str, 0, strlen(client_keys_str));
1645 tor_free(client_keys_str);
1647 strmap_free(parsed_clients, rend_authorized_client_strmap_item_free);
1649 if (cfname) {
1650 memwipe(cfname, 0, strlen(cfname));
1651 tor_free(cfname);
1654 /* Clear stack buffers that held key-derived material. */
1655 memwipe(buf, 0, sizeof(buf));
1656 memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
1657 memwipe(service_id, 0, sizeof(service_id));
1659 return r;
1662 /** Return the service whose public key has a digest of <b>digest</b>, or
1663 * NULL if no such service exists.
1665 static rend_service_t *
1666 rend_service_get_by_pk_digest(const char* digest)
1668 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
1669 if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
1670 return s);
1671 return NULL;
1674 /** Return the service whose service id is <b>id</b>, or NULL if no such
1675 * service exists.
1677 static struct rend_service_t *
1678 rend_service_get_by_service_id(const char *id)
1680 tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
1681 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
1682 if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
1683 return s;
1685 return NULL;
1688 /** Return 1 if any virtual port in <b>service</b> wants a circuit
1689 * to have good uptime. Else return 0.
1691 static int
1692 rend_service_requires_uptime(rend_service_t *service)
1694 int i;
1695 rend_service_port_config_t *p;
1697 for (i=0; i < smartlist_len(service->ports); ++i) {
1698 p = smartlist_get(service->ports, i);
1699 if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
1700 p->virtual_port))
1701 return 1;
1703 return 0;
1706 /** Check client authorization of a given <b>descriptor_cookie</b> of
1707 * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
1708 * and 0 for failure. */
1709 static int
1710 rend_check_authorization(rend_service_t *service,
1711 const char *descriptor_cookie,
1712 size_t cookie_len)
1714 rend_authorized_client_t *auth_client = NULL;
1715 tor_assert(service);
1716 tor_assert(descriptor_cookie);
1717 if (!service->clients) {
1718 log_warn(LD_BUG, "Can't check authorization for a service that has no "
1719 "authorized clients configured.");
1720 return 0;
1723 if (cookie_len != REND_DESC_COOKIE_LEN) {
1724 log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
1725 "%lu bytes. Dropping cell.",
1726 (unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
1727 return 0;
1730 /* Look up client authorization by descriptor cookie. */
1731 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
1732 if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
1733 REND_DESC_COOKIE_LEN)) {
1734 auth_client = client;
1735 break;
1738 if (!auth_client) {
1739 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
1740 base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
1741 descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
1742 log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
1743 "Dropping cell!",
1744 descriptor_cookie_base64);
1745 return 0;
1748 /* Allow the request. */
1749 log_info(LD_REND, "Client %s authorized for service %s.",
1750 auth_client->client_name, service->service_id);
1751 return 1;
1754 /* Can this service make a direct connection to ei?
1755 * It must be a single onion service, and the firewall rules must allow ei. */
1756 static int
1757 rend_service_use_direct_connection(const or_options_t* options,
1758 const extend_info_t* ei)
1760 /* We'll connect directly all reachable addresses, whether preferred or not.
1761 * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
1762 * ignored, because pref_only is 0. */
1763 return (rend_service_allow_non_anonymous_connection(options) &&
1764 fascist_firewall_allows_address_addr(&ei->addr, ei->port,
1765 FIREWALL_OR_CONNECTION, 0, 0));
1768 /* Like rend_service_use_direct_connection, but to a node. */
1769 static int
1770 rend_service_use_direct_connection_node(const or_options_t* options,
1771 const node_t* node)
1773 /* We'll connect directly all reachable addresses, whether preferred or not.
1775 return (rend_service_allow_non_anonymous_connection(options) &&
1776 fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0));
1779 /******
1780 * Handle cells
1781 ******/
1783 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
1784 * rendezvous point.
1787 rend_service_receive_introduction(origin_circuit_t *circuit,
1788 const uint8_t *request,
1789 size_t request_len)
1791 /* Global status stuff */
1792 int status = 0, result;
1793 const or_options_t *options = get_options();
1794 char *err_msg = NULL;
1795 int err_msg_severity = LOG_WARN;
1796 const char *stage_descr = NULL;
1797 int reason = END_CIRC_REASON_TORPROTOCOL;
1798 /* Service/circuit/key stuff we can learn before parsing */
1799 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1800 rend_service_t *service = NULL;
1801 rend_intro_point_t *intro_point = NULL;
1802 crypto_pk_t *intro_key = NULL;
1803 /* Parsed cell */
1804 rend_intro_cell_t *parsed_req = NULL;
1805 /* Rendezvous point */
1806 extend_info_t *rp = NULL;
1807 /* XXX not handled yet */
1808 char buf[RELAY_PAYLOAD_SIZE];
1809 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
1810 int i;
1811 crypto_dh_t *dh = NULL;
1812 origin_circuit_t *launched = NULL;
1813 crypt_path_t *cpath = NULL;
1814 char hexcookie[9];
1815 int circ_needs_uptime;
1816 time_t now = time(NULL);
1817 time_t elapsed;
1818 int replay;
1819 ssize_t keylen;
1821 /* Do some initial validation and logging before we parse the cell */
1822 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
1823 log_warn(LD_PROTOCOL,
1824 "Got an INTRODUCE2 over a non-introduction circuit %u.",
1825 (unsigned) circuit->base_.n_circ_id);
1826 goto err;
1829 assert_circ_anonymity_ok(circuit, options);
1830 tor_assert(circuit->rend_data);
1832 /* We'll use this in a bazillion log messages */
1833 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1834 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
1836 /* look up service depending on circuit. */
1837 service =
1838 rend_service_get_by_pk_digest(circuit->rend_data->rend_pk_digest);
1839 if (!service) {
1840 log_warn(LD_BUG,
1841 "Internal error: Got an INTRODUCE2 cell on an intro "
1842 "circ for an unrecognized service %s.",
1843 escaped(serviceid));
1844 goto err;
1847 intro_point = find_intro_point(circuit);
1848 if (intro_point == NULL) {
1849 intro_point = find_expiring_intro_point(service, circuit);
1850 if (intro_point == NULL) {
1851 log_warn(LD_BUG,
1852 "Internal error: Got an INTRODUCE2 cell on an "
1853 "intro circ (for service %s) with no corresponding "
1854 "rend_intro_point_t.",
1855 escaped(serviceid));
1856 goto err;
1860 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
1861 escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
1863 /* use intro key instead of service key. */
1864 intro_key = circuit->intro_key;
1866 tor_free(err_msg);
1867 stage_descr = NULL;
1869 stage_descr = "early parsing";
1870 /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
1871 parsed_req =
1872 rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
1873 if (!parsed_req) {
1874 goto log_error;
1875 } else if (err_msg) {
1876 log_info(LD_REND, "%s on circ %u.", err_msg,
1877 (unsigned)circuit->base_.n_circ_id);
1878 tor_free(err_msg);
1881 /* make sure service replay caches are present */
1882 if (!service->accepted_intro_dh_parts) {
1883 service->accepted_intro_dh_parts =
1884 replaycache_new(REND_REPLAY_TIME_INTERVAL,
1885 REND_REPLAY_TIME_INTERVAL);
1888 if (!intro_point->accepted_intro_rsa_parts) {
1889 intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
1892 /* check for replay of PK-encrypted portion. */
1893 keylen = crypto_pk_keysize(intro_key);
1894 replay = replaycache_add_test_and_elapsed(
1895 intro_point->accepted_intro_rsa_parts,
1896 parsed_req->ciphertext, MIN(parsed_req->ciphertext_len, keylen),
1897 &elapsed);
1899 if (replay) {
1900 log_warn(LD_REND,
1901 "Possible replay detected! We received an "
1902 "INTRODUCE2 cell with same PK-encrypted part %d "
1903 "seconds ago. Dropping cell.",
1904 (int)elapsed);
1905 goto err;
1908 stage_descr = "decryption";
1909 /* Now try to decrypt it */
1910 result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
1911 if (result < 0) {
1912 goto log_error;
1913 } else if (err_msg) {
1914 log_info(LD_REND, "%s on circ %u.", err_msg,
1915 (unsigned)circuit->base_.n_circ_id);
1916 tor_free(err_msg);
1919 stage_descr = "late parsing";
1920 /* Parse the plaintext */
1921 result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
1922 if (result < 0) {
1923 goto log_error;
1924 } else if (err_msg) {
1925 log_info(LD_REND, "%s on circ %u.", err_msg,
1926 (unsigned)circuit->base_.n_circ_id);
1927 tor_free(err_msg);
1930 stage_descr = "late validation";
1931 /* Validate the parsed plaintext parts */
1932 result = rend_service_validate_intro_late(parsed_req, &err_msg);
1933 if (result < 0) {
1934 goto log_error;
1935 } else if (err_msg) {
1936 log_info(LD_REND, "%s on circ %u.", err_msg,
1937 (unsigned)circuit->base_.n_circ_id);
1938 tor_free(err_msg);
1940 stage_descr = NULL;
1942 /* Increment INTRODUCE2 counter */
1943 ++(intro_point->accepted_introduce2_count);
1945 /* Find the rendezvous point */
1946 rp = find_rp_for_intro(parsed_req, &err_msg);
1947 if (!rp) {
1948 err_msg_severity = LOG_PROTOCOL_WARN;
1949 goto log_error;
1952 /* Check if we'd refuse to talk to this router */
1953 if (options->StrictNodes &&
1954 routerset_contains_extendinfo(options->ExcludeNodes, rp)) {
1955 log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
1956 "exclude, and StrictNodes is set. Refusing service.");
1957 reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
1958 goto err;
1961 base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
1963 /* Check whether there is a past request with the same Diffie-Hellman,
1964 * part 1. */
1965 replay = replaycache_add_test_and_elapsed(
1966 service->accepted_intro_dh_parts,
1967 parsed_req->dh, DH_KEY_LEN,
1968 &elapsed);
1970 if (replay) {
1971 /* A Tor client will send a new INTRODUCE1 cell with the same rend
1972 * cookie and DH public key as its previous one if its intro circ
1973 * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
1974 * If we received the first INTRODUCE1 cell (the intro-point relay
1975 * converts it into an INTRODUCE2 cell), we are already trying to
1976 * connect to that rend point (and may have already succeeded);
1977 * drop this cell. */
1978 log_info(LD_REND, "We received an "
1979 "INTRODUCE2 cell with same first part of "
1980 "Diffie-Hellman handshake %d seconds ago. Dropping "
1981 "cell.",
1982 (int) elapsed);
1983 goto err;
1986 /* If the service performs client authorization, check included auth data. */
1987 if (service->clients) {
1988 if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
1989 if (rend_check_authorization(service,
1990 (const char*)parsed_req->u.v3.auth_data,
1991 parsed_req->u.v3.auth_len)) {
1992 log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
1993 } else {
1994 log_info(LD_REND, "The authorization data that are contained in "
1995 "the INTRODUCE2 cell are invalid. Dropping cell.");
1996 reason = END_CIRC_REASON_CONNECTFAILED;
1997 goto err;
1999 } else {
2000 log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
2001 "data, but we require client authorization. Dropping cell.");
2002 reason = END_CIRC_REASON_CONNECTFAILED;
2003 goto err;
2007 /* Try DH handshake... */
2008 dh = crypto_dh_new(DH_TYPE_REND);
2009 if (!dh || crypto_dh_generate_public(dh)<0) {
2010 log_warn(LD_BUG,"Internal error: couldn't build DH state "
2011 "or generate public key.");
2012 reason = END_CIRC_REASON_INTERNAL;
2013 goto err;
2015 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
2016 (char *)(parsed_req->dh),
2017 DH_KEY_LEN, keys,
2018 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
2019 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
2020 reason = END_CIRC_REASON_INTERNAL;
2021 goto err;
2024 circ_needs_uptime = rend_service_requires_uptime(service);
2026 /* help predict this next time */
2027 rep_hist_note_used_internal(now, circ_needs_uptime, 1);
2029 /* Launch a circuit to the client's chosen rendezvous point.
2031 for (i=0;i<MAX_REND_FAILURES;i++) {
2032 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
2033 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2034 /* A Single Onion Service only uses a direct connection if its
2035 * firewall rules permit direct connections to the address. */
2036 if (rend_service_use_direct_connection(options, rp)) {
2037 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
2039 launched = circuit_launch_by_extend_info(
2040 CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
2042 if (launched)
2043 break;
2045 if (!launched) { /* give up */
2046 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
2047 "point %s for service %s.",
2048 safe_str_client(extend_info_describe(rp)),
2049 serviceid);
2050 reason = END_CIRC_REASON_CONNECTFAILED;
2051 goto err;
2053 log_info(LD_REND,
2054 "Accepted intro; launching circuit to %s "
2055 "(cookie %s) for service %s.",
2056 safe_str_client(extend_info_describe(rp)),
2057 hexcookie, serviceid);
2058 tor_assert(launched->build_state);
2059 /* Fill in the circuit's state. */
2061 launched->rend_data =
2062 rend_data_service_create(service->service_id,
2063 circuit->rend_data->rend_pk_digest,
2064 parsed_req->rc, service->auth_type);
2066 launched->build_state->service_pending_final_cpath_ref =
2067 tor_malloc_zero(sizeof(crypt_path_reference_t));
2068 launched->build_state->service_pending_final_cpath_ref->refcount = 1;
2070 launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
2071 tor_malloc_zero(sizeof(crypt_path_t));
2072 cpath->magic = CRYPT_PATH_MAGIC;
2073 launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
2075 cpath->rend_dh_handshake_state = dh;
2076 dh = NULL;
2077 if (circuit_init_cpath_crypto(cpath,keys+DIGEST_LEN,1)<0)
2078 goto err;
2079 memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
2081 goto done;
2083 log_error:
2084 if (!err_msg) {
2085 if (stage_descr) {
2086 tor_asprintf(&err_msg,
2087 "unknown %s error for INTRODUCE2", stage_descr);
2088 } else {
2089 err_msg = tor_strdup("unknown error for INTRODUCE2");
2093 log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
2094 (unsigned)circuit->base_.n_circ_id);
2095 err:
2096 status = -1;
2097 if (dh) crypto_dh_free(dh);
2098 if (launched) {
2099 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
2101 tor_free(err_msg);
2103 done:
2104 memwipe(keys, 0, sizeof(keys));
2105 memwipe(buf, 0, sizeof(buf));
2106 memwipe(serviceid, 0, sizeof(serviceid));
2107 memwipe(hexcookie, 0, sizeof(hexcookie));
2109 /* Free the parsed cell */
2110 rend_service_free_intro(parsed_req);
2112 /* Free rp */
2113 extend_info_free(rp);
2115 return status;
2118 /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
2119 * return NULL and an error string if we can't. Return a newly allocated
2120 * extend_info_t* for the rendezvous point. */
2121 static extend_info_t *
2122 find_rp_for_intro(const rend_intro_cell_t *intro,
2123 char **err_msg_out)
2125 extend_info_t *rp = NULL;
2126 char *err_msg = NULL;
2127 const char *rp_nickname = NULL;
2128 const node_t *node = NULL;
2130 if (!intro) {
2131 if (err_msg_out)
2132 err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
2134 goto err;
2137 if (intro->version == 0 || intro->version == 1) {
2138 rp_nickname = (const char *)(intro->u.v0_v1.rp);
2140 node = node_get_by_nickname(rp_nickname, 0);
2141 if (!node) {
2142 if (err_msg_out) {
2143 tor_asprintf(&err_msg,
2144 "Couldn't find router %s named in INTRODUCE2 cell",
2145 escaped_safe_str_client(rp_nickname));
2148 goto err;
2151 /* Are we in single onion mode? */
2152 const int allow_direct = rend_service_allow_non_anonymous_connection(
2153 get_options());
2154 rp = extend_info_from_node(node, allow_direct);
2155 if (!rp) {
2156 if (err_msg_out) {
2157 tor_asprintf(&err_msg,
2158 "Couldn't build extend_info_t for router %s named "
2159 "in INTRODUCE2 cell",
2160 escaped_safe_str_client(rp_nickname));
2163 goto err;
2165 } else if (intro->version == 2) {
2166 rp = extend_info_dup(intro->u.v2.extend_info);
2167 } else if (intro->version == 3) {
2168 rp = extend_info_dup(intro->u.v3.extend_info);
2169 } else {
2170 if (err_msg_out) {
2171 tor_asprintf(&err_msg,
2172 "Unknown version %d in INTRODUCE2 cell",
2173 (int)(intro->version));
2176 goto err;
2179 /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2180 * the other cases goto err. */
2181 tor_assert(rp);
2183 /* Make sure the RP we are being asked to connect to is _not_ a private
2184 * address unless it's allowed. Let's avoid to build a circuit to our
2185 * second middle node and fail right after when extending to the RP. */
2186 if (!extend_info_addr_is_allowed(&rp->addr)) {
2187 if (err_msg_out) {
2188 tor_asprintf(&err_msg,
2189 "Relay IP in INTRODUCE2 cell is private address.");
2191 extend_info_free(rp);
2192 rp = NULL;
2193 goto err;
2195 goto done;
2197 err:
2198 if (err_msg_out)
2199 *err_msg_out = err_msg;
2200 else
2201 tor_free(err_msg);
2203 done:
2204 return rp;
2207 /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
2208 * rend_service_parse_intro().
2210 void
2211 rend_service_free_intro(rend_intro_cell_t *request)
2213 if (!request) {
2214 return;
2217 /* Free ciphertext */
2218 tor_free(request->ciphertext);
2219 request->ciphertext_len = 0;
2221 /* Have plaintext? */
2222 if (request->plaintext) {
2223 /* Zero it out just to be safe */
2224 memwipe(request->plaintext, 0, request->plaintext_len);
2225 tor_free(request->plaintext);
2226 request->plaintext_len = 0;
2229 /* Have parsed plaintext? */
2230 if (request->parsed) {
2231 switch (request->version) {
2232 case 0:
2233 case 1:
2235 * Nothing more to do; these formats have no further pointers
2236 * in them.
2238 break;
2239 case 2:
2240 extend_info_free(request->u.v2.extend_info);
2241 request->u.v2.extend_info = NULL;
2242 break;
2243 case 3:
2244 if (request->u.v3.auth_data) {
2245 memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
2246 tor_free(request->u.v3.auth_data);
2249 extend_info_free(request->u.v3.extend_info);
2250 request->u.v3.extend_info = NULL;
2251 break;
2252 default:
2253 log_info(LD_BUG,
2254 "rend_service_free_intro() saw unknown protocol "
2255 "version %d.",
2256 request->version);
2260 /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2261 memwipe(request, 0, sizeof(*request));
2263 tor_free(request);
2266 /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
2267 * rend_intro_cell_t structure. Free it with rend_service_free_intro()
2268 * when finished. The type parameter should be 1 or 2 to indicate whether
2269 * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
2270 * parts; after this, call rend_service_decrypt_intro() with a key, then
2271 * rend_service_parse_intro_plaintext() to finish parsing. The optional
2272 * err_msg_out parameter is set to a string suitable for log output
2273 * if parsing fails. This function does some validation, but only
2274 * that which depends solely on the contents of the cell and the
2275 * key; it can be unit-tested. Further validation is done in
2276 * rend_service_validate_intro().
2279 rend_intro_cell_t *
2280 rend_service_begin_parse_intro(const uint8_t *request,
2281 size_t request_len,
2282 uint8_t type,
2283 char **err_msg_out)
2285 rend_intro_cell_t *rv = NULL;
2286 char *err_msg = NULL;
2288 if (!request || request_len <= 0) goto err;
2289 if (!(type == 1 || type == 2)) goto err;
2291 /* First, check that the cell is long enough to be a sensible INTRODUCE */
2293 /* min key length plus digest length plus nickname length */
2294 if (request_len <
2295 (DIGEST_LEN + REND_COOKIE_LEN + (MAX_NICKNAME_LEN + 1) +
2296 DH_KEY_LEN + 42)) {
2297 if (err_msg_out) {
2298 tor_asprintf(&err_msg,
2299 "got a truncated INTRODUCE%d cell",
2300 (int)type);
2302 goto err;
2305 /* Allocate a new parsed cell structure */
2306 rv = tor_malloc_zero(sizeof(*rv));
2308 /* Set the type */
2309 rv->type = type;
2311 /* Copy in the ID */
2312 memcpy(rv->pk, request, DIGEST_LEN);
2314 /* Copy in the ciphertext */
2315 rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
2316 memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
2317 rv->ciphertext_len = request_len - DIGEST_LEN;
2319 goto done;
2321 err:
2322 rend_service_free_intro(rv);
2323 rv = NULL;
2325 if (err_msg_out && !err_msg) {
2326 tor_asprintf(&err_msg,
2327 "unknown INTRODUCE%d error",
2328 (int)type);
2331 done:
2332 if (err_msg_out) *err_msg_out = err_msg;
2333 else tor_free(err_msg);
2335 return rv;
2338 /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
2339 * cell
2342 static ssize_t
2343 rend_service_parse_intro_for_v0_or_v1(
2344 rend_intro_cell_t *intro,
2345 const uint8_t *buf,
2346 size_t plaintext_len,
2347 char **err_msg_out)
2349 const char *rp_nickname, *endptr;
2350 size_t nickname_field_len, ver_specific_len;
2352 if (intro->version == 1) {
2353 ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
2354 rp_nickname = ((const char *)buf) + 1;
2355 nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
2356 } else if (intro->version == 0) {
2357 ver_specific_len = MAX_NICKNAME_LEN + 1;
2358 rp_nickname = (const char *)buf;
2359 nickname_field_len = MAX_NICKNAME_LEN + 1;
2360 } else {
2361 if (err_msg_out)
2362 tor_asprintf(err_msg_out,
2363 "rend_service_parse_intro_for_v0_or_v1() called with "
2364 "bad version %d on INTRODUCE%d cell (this is a bug)",
2365 intro->version,
2366 (int)(intro->type));
2367 goto err;
2370 if (plaintext_len < ver_specific_len) {
2371 if (err_msg_out)
2372 tor_asprintf(err_msg_out,
2373 "short plaintext of encrypted part in v1 INTRODUCE%d "
2374 "cell (%lu bytes, needed %lu)",
2375 (int)(intro->type),
2376 (unsigned long)plaintext_len,
2377 (unsigned long)ver_specific_len);
2378 goto err;
2381 endptr = memchr(rp_nickname, 0, nickname_field_len);
2382 if (!endptr || endptr == rp_nickname) {
2383 if (err_msg_out) {
2384 tor_asprintf(err_msg_out,
2385 "couldn't find a nul-padded nickname in "
2386 "INTRODUCE%d cell",
2387 (int)(intro->type));
2389 goto err;
2392 if ((intro->version == 0 &&
2393 !is_legal_nickname(rp_nickname)) ||
2394 (intro->version == 1 &&
2395 !is_legal_nickname_or_hexdigest(rp_nickname))) {
2396 if (err_msg_out) {
2397 tor_asprintf(err_msg_out,
2398 "bad nickname in INTRODUCE%d cell",
2399 (int)(intro->type));
2401 goto err;
2404 memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
2406 return ver_specific_len;
2408 err:
2409 return -1;
2412 /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
2415 static ssize_t
2416 rend_service_parse_intro_for_v2(
2417 rend_intro_cell_t *intro,
2418 const uint8_t *buf,
2419 size_t plaintext_len,
2420 char **err_msg_out)
2422 unsigned int klen;
2423 extend_info_t *extend_info = NULL;
2424 ssize_t ver_specific_len;
2427 * We accept version 3 too so that the v3 parser can call this with
2428 * an adjusted buffer for the latter part of a v3 cell, which is
2429 * identical to a v2 cell.
2431 if (!(intro->version == 2 ||
2432 intro->version == 3)) {
2433 if (err_msg_out)
2434 tor_asprintf(err_msg_out,
2435 "rend_service_parse_intro_for_v2() called with "
2436 "bad version %d on INTRODUCE%d cell (this is a bug)",
2437 intro->version,
2438 (int)(intro->type));
2439 goto err;
2442 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2443 if (plaintext_len < 7 + DIGEST_LEN + 2) {
2444 if (err_msg_out) {
2445 tor_asprintf(err_msg_out,
2446 "truncated plaintext of encrypted parted of "
2447 "version %d INTRODUCE%d cell",
2448 intro->version,
2449 (int)(intro->type));
2452 goto err;
2455 extend_info = tor_malloc_zero(sizeof(extend_info_t));
2456 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
2457 extend_info->port = ntohs(get_uint16(buf + 5));
2458 memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
2459 extend_info->nickname[0] = '$';
2460 base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
2461 extend_info->identity_digest, DIGEST_LEN);
2462 klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
2464 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2465 if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
2466 if (err_msg_out) {
2467 tor_asprintf(err_msg_out,
2468 "truncated plaintext of encrypted parted of "
2469 "version %d INTRODUCE%d cell",
2470 intro->version,
2471 (int)(intro->type));
2474 goto err;
2477 extend_info->onion_key =
2478 crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
2479 if (!extend_info->onion_key) {
2480 if (err_msg_out) {
2481 tor_asprintf(err_msg_out,
2482 "error decoding onion key in version %d "
2483 "INTRODUCE%d cell",
2484 intro->version,
2485 (intro->type));
2488 goto err;
2490 if (128 != crypto_pk_keysize(extend_info->onion_key)) {
2491 if (err_msg_out) {
2492 tor_asprintf(err_msg_out,
2493 "invalid onion key size in version %d INTRODUCE%d cell",
2494 intro->version,
2495 (intro->type));
2498 goto err;
2501 ver_specific_len = 7+DIGEST_LEN+2+klen;
2503 if (intro->version == 2) intro->u.v2.extend_info = extend_info;
2504 else intro->u.v3.extend_info = extend_info;
2506 return ver_specific_len;
2508 err:
2509 extend_info_free(extend_info);
2511 return -1;
2514 /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
2517 static ssize_t
2518 rend_service_parse_intro_for_v3(
2519 rend_intro_cell_t *intro,
2520 const uint8_t *buf,
2521 size_t plaintext_len,
2522 char **err_msg_out)
2524 ssize_t adjust, v2_ver_specific_len, ts_offset;
2526 /* This should only be called on v3 cells */
2527 if (intro->version != 3) {
2528 if (err_msg_out)
2529 tor_asprintf(err_msg_out,
2530 "rend_service_parse_intro_for_v3() called with "
2531 "bad version %d on INTRODUCE%d cell (this is a bug)",
2532 intro->version,
2533 (int)(intro->type));
2534 goto err;
2538 * Check that we have at least enough to get auth_len:
2540 * 1 octet for version, 1 for auth_type, 2 for auth_len
2542 if (plaintext_len < 4) {
2543 if (err_msg_out) {
2544 tor_asprintf(err_msg_out,
2545 "truncated plaintext of encrypted parted of "
2546 "version %d INTRODUCE%d cell",
2547 intro->version,
2548 (int)(intro->type));
2551 goto err;
2555 * The rend_client_send_introduction() function over in rendclient.c is
2556 * broken (i.e., fails to match the spec) in such a way that we can't
2557 * change it without breaking the protocol. Specifically, it doesn't
2558 * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2559 * by two bytes after that. Calculate ts_offset and do everything from
2560 * the timestamp on relative to that to handle this dain bramage.
2563 intro->u.v3.auth_type = buf[1];
2564 if (intro->u.v3.auth_type != REND_NO_AUTH) {
2565 intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
2566 ts_offset = 4 + intro->u.v3.auth_len;
2567 } else {
2568 intro->u.v3.auth_len = 0;
2569 ts_offset = 2;
2572 /* Check that auth len makes sense for this auth type */
2573 if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
2574 intro->u.v3.auth_type == REND_STEALTH_AUTH) {
2575 if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
2576 if (err_msg_out) {
2577 tor_asprintf(err_msg_out,
2578 "wrong auth data size %d for INTRODUCE%d cell, "
2579 "should be %d",
2580 (int)(intro->u.v3.auth_len),
2581 (int)(intro->type),
2582 REND_DESC_COOKIE_LEN);
2585 goto err;
2589 /* Check that we actually have everything up through the timestamp */
2590 if (plaintext_len < (size_t)(ts_offset)+4) {
2591 if (err_msg_out) {
2592 tor_asprintf(err_msg_out,
2593 "truncated plaintext of encrypted parted of "
2594 "version %d INTRODUCE%d cell",
2595 intro->version,
2596 (int)(intro->type));
2599 goto err;
2602 if (intro->u.v3.auth_type != REND_NO_AUTH &&
2603 intro->u.v3.auth_len > 0) {
2604 /* Okay, we can go ahead and copy auth_data */
2605 intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
2607 * We know we had an auth_len field in this case, so 4 is
2608 * always right.
2610 memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
2614 * From here on, the format is as in v2, so we call the v2 parser with
2615 * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2616 * v2 parser expects to skip over a version byte at the start, so we
2617 * adjust by 3 + ts_offset.
2619 adjust = 3 + ts_offset;
2621 v2_ver_specific_len =
2622 rend_service_parse_intro_for_v2(intro,
2623 buf + adjust, plaintext_len - adjust,
2624 err_msg_out);
2626 /* Success in v2 parser */
2627 if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
2628 /* Failure in v2 parser; it will have provided an err_msg */
2629 else return v2_ver_specific_len;
2631 err:
2632 return -1;
2635 /** Table of parser functions for version-specific parts of an INTRODUCE2
2636 * cell.
2639 static ssize_t
2640 (*intro_version_handlers[])(
2641 rend_intro_cell_t *,
2642 const uint8_t *,
2643 size_t,
2644 char **) =
2645 { rend_service_parse_intro_for_v0_or_v1,
2646 rend_service_parse_intro_for_v0_or_v1,
2647 rend_service_parse_intro_for_v2,
2648 rend_service_parse_intro_for_v3 };
2650 /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
2651 * return 0 if successful, or < 0 and write an error message to
2652 * *err_msg_out if provided.
2656 rend_service_decrypt_intro(
2657 rend_intro_cell_t *intro,
2658 crypto_pk_t *key,
2659 char **err_msg_out)
2661 char *err_msg = NULL;
2662 uint8_t key_digest[DIGEST_LEN];
2663 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
2664 ssize_t key_len;
2665 uint8_t buf[RELAY_PAYLOAD_SIZE];
2666 int result, status = -1;
2668 if (!intro || !key) {
2669 if (err_msg_out) {
2670 err_msg =
2671 tor_strdup("rend_service_decrypt_intro() called with bad "
2672 "parameters");
2675 status = -2;
2676 goto err;
2679 /* Make sure we have ciphertext */
2680 if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
2681 if (err_msg_out) {
2682 tor_asprintf(&err_msg,
2683 "rend_intro_cell_t was missing ciphertext for "
2684 "INTRODUCE%d cell",
2685 (int)(intro->type));
2687 status = -3;
2688 goto err;
2691 /* Check that this cell actually matches this service key */
2693 /* first DIGEST_LEN bytes of request is intro or service pk digest */
2694 crypto_pk_get_digest(key, (char *)key_digest);
2695 if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
2696 if (err_msg_out) {
2697 base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
2698 (char*)(intro->pk), REND_SERVICE_ID_LEN);
2699 tor_asprintf(&err_msg,
2700 "got an INTRODUCE%d cell for the wrong service (%s)",
2701 (int)(intro->type),
2702 escaped(service_id));
2705 status = -4;
2706 goto err;
2709 /* Make sure the encrypted part is long enough to decrypt */
2711 key_len = crypto_pk_keysize(key);
2712 if (intro->ciphertext_len < key_len) {
2713 if (err_msg_out) {
2714 tor_asprintf(&err_msg,
2715 "got an INTRODUCE%d cell with a truncated PK-encrypted "
2716 "part",
2717 (int)(intro->type));
2720 status = -5;
2721 goto err;
2724 /* Decrypt the encrypted part */
2726 note_crypto_pk_op(REND_SERVER);
2727 result =
2728 crypto_pk_private_hybrid_decrypt(
2729 key, (char *)buf, sizeof(buf),
2730 (const char *)(intro->ciphertext), intro->ciphertext_len,
2731 PK_PKCS1_OAEP_PADDING, 1);
2732 if (result < 0) {
2733 if (err_msg_out) {
2734 tor_asprintf(&err_msg,
2735 "couldn't decrypt INTRODUCE%d cell",
2736 (int)(intro->type));
2738 status = -6;
2739 goto err;
2741 intro->plaintext_len = result;
2742 intro->plaintext = tor_malloc(intro->plaintext_len);
2743 memcpy(intro->plaintext, buf, intro->plaintext_len);
2745 status = 0;
2747 goto done;
2749 err:
2750 if (err_msg_out && !err_msg) {
2751 tor_asprintf(&err_msg,
2752 "unknown INTRODUCE%d error decrypting encrypted part",
2753 intro ? (int)(intro->type) : -1);
2756 done:
2757 if (err_msg_out) *err_msg_out = err_msg;
2758 else tor_free(err_msg);
2760 /* clean up potentially sensitive material */
2761 memwipe(buf, 0, sizeof(buf));
2762 memwipe(key_digest, 0, sizeof(key_digest));
2763 memwipe(service_id, 0, sizeof(service_id));
2765 return status;
2768 /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
2769 * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
2770 * message to *err_msg_out if provided.
2774 rend_service_parse_intro_plaintext(
2775 rend_intro_cell_t *intro,
2776 char **err_msg_out)
2778 char *err_msg = NULL;
2779 ssize_t ver_specific_len, ver_invariant_len;
2780 uint8_t version;
2781 int status = -1;
2783 if (!intro) {
2784 if (err_msg_out) {
2785 err_msg =
2786 tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2787 "rend_intro_cell_t");
2790 status = -2;
2791 goto err;
2794 /* Check that we have plaintext */
2795 if (!(intro->plaintext) || intro->plaintext_len <= 0) {
2796 if (err_msg_out) {
2797 err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
2799 status = -3;
2800 goto err;
2803 /* In all formats except v0, the first byte is a version number */
2804 version = intro->plaintext[0];
2806 /* v0 has no version byte (stupid...), so handle it as a fallback */
2807 if (version > 3) version = 0;
2809 /* Copy the version into the parsed cell structure */
2810 intro->version = version;
2812 /* Call the version-specific parser from the table */
2813 ver_specific_len =
2814 intro_version_handlers[version](intro,
2815 intro->plaintext, intro->plaintext_len,
2816 &err_msg);
2817 if (ver_specific_len < 0) {
2818 status = -4;
2819 goto err;
2822 /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
2823 * and at the end of the plaintext of the encrypted part of the cell.
2826 ver_invariant_len = intro->plaintext_len - ver_specific_len;
2827 if (ver_invariant_len < REND_COOKIE_LEN + DH_KEY_LEN) {
2828 tor_asprintf(&err_msg,
2829 "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2830 (int)(intro->type),
2831 (long)(intro->plaintext_len));
2832 status = -5;
2833 goto err;
2834 } else if (ver_invariant_len > REND_COOKIE_LEN + DH_KEY_LEN) {
2835 tor_asprintf(&err_msg,
2836 "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2837 (int)(intro->type),
2838 (long)(intro->plaintext_len));
2839 status = -6;
2840 goto err;
2841 } else {
2842 memcpy(intro->rc,
2843 intro->plaintext + ver_specific_len,
2844 REND_COOKIE_LEN);
2845 memcpy(intro->dh,
2846 intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
2847 DH_KEY_LEN);
2850 /* Flag it as being fully parsed */
2851 intro->parsed = 1;
2853 status = 0;
2854 goto done;
2856 err:
2857 if (err_msg_out && !err_msg) {
2858 tor_asprintf(&err_msg,
2859 "unknown INTRODUCE%d error parsing encrypted part",
2860 intro ? (int)(intro->type) : -1);
2863 done:
2864 if (err_msg_out) *err_msg_out = err_msg;
2865 else tor_free(err_msg);
2867 return status;
2870 /** Do validity checks on a parsed intro cell after decryption; some of
2871 * these are not done in rend_service_parse_intro_plaintext() itself because
2872 * they depend on a lot of other state and would make it hard to unit test.
2873 * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
2874 * optionally writes out an error message for logging. If an err_msg
2875 * pointer is provided, it is the caller's responsibility to free any
2876 * provided message.
2880 rend_service_validate_intro_late(const rend_intro_cell_t *intro,
2881 char **err_msg_out)
2883 int status = 0;
2885 if (!intro) {
2886 if (err_msg_out)
2887 *err_msg_out =
2888 tor_strdup("NULL intro cell passed to "
2889 "rend_service_validate_intro_late()");
2891 status = -1;
2892 goto err;
2895 if (intro->version == 3 && intro->parsed) {
2896 if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
2897 intro->u.v3.auth_type == REND_BASIC_AUTH ||
2898 intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
2899 /* This is an informative message, not an error, as in the old code */
2900 if (err_msg_out)
2901 tor_asprintf(err_msg_out,
2902 "unknown authorization type %d",
2903 intro->u.v3.auth_type);
2907 err:
2908 return status;
2911 /** Called when we fail building a rendezvous circuit at some point other
2912 * than the last hop: launches a new circuit to the same rendezvous point.
2914 void
2915 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
2917 origin_circuit_t *newcirc;
2918 cpath_build_state_t *newstate, *oldstate;
2920 tor_assert(oldcirc->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
2922 /* Don't relaunch the same rend circ twice. */
2923 if (oldcirc->hs_service_side_rend_circ_has_been_relaunched) {
2924 log_info(LD_REND, "Rendezvous circuit to %s has already been relaunched; "
2925 "not relaunching it again.",
2926 oldcirc->build_state ?
2927 safe_str(extend_info_describe(oldcirc->build_state->chosen_exit))
2928 : "*unknown*");
2929 return;
2931 oldcirc->hs_service_side_rend_circ_has_been_relaunched = 1;
2933 if (!oldcirc->build_state ||
2934 oldcirc->build_state->failure_count > MAX_REND_FAILURES ||
2935 oldcirc->build_state->expiry_time < time(NULL)) {
2936 log_info(LD_REND,
2937 "Attempt to build circuit to %s for rendezvous has failed "
2938 "too many times or expired; giving up.",
2939 oldcirc->build_state ?
2940 safe_str(extend_info_describe(oldcirc->build_state->chosen_exit))
2941 : "*unknown*");
2942 return;
2945 oldstate = oldcirc->build_state;
2946 tor_assert(oldstate);
2948 if (oldstate->service_pending_final_cpath_ref == NULL) {
2949 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
2950 "Initiator will retry.");
2951 return;
2954 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
2955 safe_str(extend_info_describe(oldstate->chosen_exit)));
2957 /* You'd think Single Onion Services would want to retry the rendezvous
2958 * using a direct connection. But if it's blocked by a firewall, or the
2959 * service is IPv6-only, or the rend point avoiding becoming a one-hop
2960 * proxy, we need a 3-hop connection. */
2961 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
2962 oldstate->chosen_exit,
2963 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
2965 if (!newcirc) {
2966 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
2967 safe_str(extend_info_describe(oldstate->chosen_exit)));
2968 return;
2970 newstate = newcirc->build_state;
2971 tor_assert(newstate);
2972 newstate->failure_count = oldstate->failure_count+1;
2973 newstate->expiry_time = oldstate->expiry_time;
2974 newstate->service_pending_final_cpath_ref =
2975 oldstate->service_pending_final_cpath_ref;
2976 ++(newstate->service_pending_final_cpath_ref->refcount);
2978 newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
2981 /** Launch a circuit to serve as an introduction point for the service
2982 * <b>service</b> at the introduction point <b>nickname</b>
2984 static int
2985 rend_service_launch_establish_intro(rend_service_t *service,
2986 rend_intro_point_t *intro)
2988 origin_circuit_t *launched;
2989 int flags = CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL;
2990 const or_options_t *options = get_options();
2991 extend_info_t *launch_ei = intro->extend_info;
2992 extend_info_t *direct_ei = NULL;
2994 /* Are we in single onion mode? */
2995 if (rend_service_allow_non_anonymous_connection(options)) {
2996 /* Do we have a descriptor for the node?
2997 * We've either just chosen it from the consensus, or we've just reviewed
2998 * our intro points to see which ones are still valid, and deleted the ones
2999 * that aren't in the consensus any more. */
3000 const node_t *node = node_get_by_id(launch_ei->identity_digest);
3001 if (BUG(!node)) {
3002 /* The service has kept an intro point after it went missing from the
3003 * consensus. If we did anything else here, it would be a consensus
3004 * distinguisher. Which are less of an issue for single onion services,
3005 * but still a bug. */
3006 return -1;
3008 /* Can we connect to the node directly? If so, replace launch_ei
3009 * (a multi-hop extend_info) with one suitable for direct connection. */
3010 if (rend_service_use_direct_connection_node(options, node)) {
3011 direct_ei = extend_info_from_node(node, 1);
3012 if (BUG(!direct_ei)) {
3013 /* rend_service_use_direct_connection_node and extend_info_from_node
3014 * disagree about which addresses on this node are permitted. This
3015 * should never happen. Avoiding the connection is a safe response. */
3016 return -1;
3018 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
3019 launch_ei = direct_ei;
3022 /* launch_ei is either intro->extend_info, or has been replaced with a valid
3023 * extend_info for single onion service direct connection. */
3024 tor_assert(launch_ei);
3025 /* We must have the same intro when making a direct connection. */
3026 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3027 launch_ei->identity_digest,
3028 DIGEST_LEN));
3030 log_info(LD_REND,
3031 "Launching circuit to introduction point %s%s%s for service %s",
3032 safe_str_client(extend_info_describe(intro->extend_info)),
3033 direct_ei ? " via direct address " : "",
3034 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
3035 service->service_id);
3037 rep_hist_note_used_internal(time(NULL), 1, 0);
3039 ++service->n_intro_circuits_launched;
3040 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
3041 launch_ei, flags);
3043 if (!launched) {
3044 log_info(LD_REND,
3045 "Can't launch circuit to establish introduction at %s%s%s.",
3046 safe_str_client(extend_info_describe(intro->extend_info)),
3047 direct_ei ? " via direct address " : "",
3048 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
3050 extend_info_free(direct_ei);
3051 return -1;
3053 /* We must have the same exit node even if cannibalized or direct connection.
3055 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3056 launched->build_state->chosen_exit->identity_digest,
3057 DIGEST_LEN));
3059 launched->rend_data = rend_data_service_create(service->service_id,
3060 service->pk_digest, NULL,
3061 service->auth_type);
3062 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
3063 if (launched->base_.state == CIRCUIT_STATE_OPEN)
3064 rend_service_intro_has_opened(launched);
3065 extend_info_free(direct_ei);
3066 return 0;
3069 /** Return the number of introduction points that are established for the
3070 * given service. */
3071 static unsigned int
3072 count_established_intro_points(const rend_service_t *service)
3074 unsigned int num = 0;
3076 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
3077 num += intro->circuit_established
3079 return num;
3082 /** Return the number of introduction points that are or are being
3083 * established for the given service. This function iterates over all
3084 * circuit and count those that are linked to the service and are waiting
3085 * for the intro point to respond. */
3086 static unsigned int
3087 count_intro_point_circuits(const rend_service_t *service)
3089 unsigned int num_ipos = 0;
3090 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
3091 if (!circ->marked_for_close &&
3092 circ->state == CIRCUIT_STATE_OPEN &&
3093 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3094 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
3095 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
3096 if (oc->rend_data &&
3097 !rend_cmp_service_ids(service->service_id,
3098 oc->rend_data->onion_address))
3099 num_ipos++;
3102 SMARTLIST_FOREACH_END(circ);
3103 return num_ipos;
3106 /** Called when we're done building a circuit to an introduction point:
3107 * sends a RELAY_ESTABLISH_INTRO cell.
3109 void
3110 rend_service_intro_has_opened(origin_circuit_t *circuit)
3112 rend_service_t *service;
3113 size_t len;
3114 int r;
3115 char buf[RELAY_PAYLOAD_SIZE];
3116 char auth[DIGEST_LEN + 9];
3117 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3118 int reason = END_CIRC_REASON_TORPROTOCOL;
3120 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
3121 assert_circ_anonymity_ok(circuit, get_options());
3122 tor_assert(circuit->cpath);
3123 tor_assert(circuit->rend_data);
3125 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3126 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
3128 service = rend_service_get_by_pk_digest(
3129 circuit->rend_data->rend_pk_digest);
3130 if (!service) {
3131 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
3132 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3133 reason = END_CIRC_REASON_NOSUCHSERVICE;
3134 goto err;
3137 /* If we already have enough introduction circuits for this service,
3138 * redefine this one as a general circuit or close it, depending.
3139 * Substract the amount of expiring nodes here since the circuits are
3140 * still opened. */
3141 if ((count_intro_point_circuits(service) -
3142 smartlist_len(service->expiring_nodes)) >
3143 service->n_intro_points_wanted) {
3144 const or_options_t *options = get_options();
3145 /* Remove the intro point associated with this circuit, it's being
3146 * repurposed or closed thus cleanup memory. */
3147 rend_intro_point_t *intro = find_intro_point(circuit);
3148 if (intro != NULL) {
3149 smartlist_remove(service->intro_nodes, intro);
3150 rend_intro_point_free(intro);
3153 if (options->ExcludeNodes) {
3154 /* XXXX in some future version, we can test whether the transition is
3155 allowed or not given the actual nodes in the circuit. But for now,
3156 this case, we might as well close the thing. */
3157 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3158 "circuit, but we already have enough. Closing it.");
3159 reason = END_CIRC_REASON_NONE;
3160 goto err;
3161 } else {
3162 tor_assert(circuit->build_state->is_internal);
3163 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3164 "circuit, but we already have enough. Redefining purpose to "
3165 "general; leaving as internal.");
3167 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
3170 rend_data_t *rend_data = circuit->rend_data;
3171 circuit->rend_data = NULL;
3172 rend_data_free(rend_data);
3175 crypto_pk_t *intro_key = circuit->intro_key;
3176 circuit->intro_key = NULL;
3177 crypto_pk_free(intro_key);
3180 circuit_has_opened(circuit);
3181 goto done;
3185 log_info(LD_REND,
3186 "Established circuit %u as introduction point for service %s",
3187 (unsigned)circuit->base_.n_circ_id, serviceid);
3188 circuit_log_path(LOG_INFO, LD_REND, circuit);
3190 /* Use the intro key instead of the service key in ESTABLISH_INTRO. */
3191 crypto_pk_t *intro_key = circuit->intro_key;
3192 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3193 r = crypto_pk_asn1_encode(intro_key, buf+2,
3194 RELAY_PAYLOAD_SIZE-2);
3195 if (r < 0) {
3196 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
3197 reason = END_CIRC_REASON_INTERNAL;
3198 goto err;
3200 len = r;
3201 set_uint16(buf, htons((uint16_t)len));
3202 len += 2;
3203 memcpy(auth, circuit->cpath->prev->rend_circ_nonce, DIGEST_LEN);
3204 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
3205 if (crypto_digest(buf+len, auth, DIGEST_LEN+9))
3206 goto err;
3207 len += 20;
3208 note_crypto_pk_op(REND_SERVER);
3209 r = crypto_pk_private_sign_digest(intro_key, buf+len, sizeof(buf)-len,
3210 buf, len);
3211 if (r<0) {
3212 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
3213 reason = END_CIRC_REASON_INTERNAL;
3214 goto err;
3216 len += r;
3218 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3219 RELAY_COMMAND_ESTABLISH_INTRO,
3220 buf, len, circuit->cpath->prev)<0) {
3221 log_info(LD_GENERAL,
3222 "Couldn't send introduction request for service %s on circuit %u",
3223 serviceid, (unsigned)circuit->base_.n_circ_id);
3224 reason = END_CIRC_REASON_INTERNAL;
3225 goto err;
3228 /* We've attempted to use this circuit */
3229 pathbias_count_use_attempt(circuit);
3231 goto done;
3233 err:
3234 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3235 done:
3236 memwipe(buf, 0, sizeof(buf));
3237 memwipe(auth, 0, sizeof(auth));
3238 memwipe(serviceid, 0, sizeof(serviceid));
3240 return;
3243 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
3244 * live introduction point, and note that the service descriptor is
3245 * now out-of-date. */
3247 rend_service_intro_established(origin_circuit_t *circuit,
3248 const uint8_t *request,
3249 size_t request_len)
3251 rend_service_t *service;
3252 rend_intro_point_t *intro;
3253 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3254 (void) request;
3255 (void) request_len;
3257 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
3258 log_warn(LD_PROTOCOL,
3259 "received INTRO_ESTABLISHED cell on non-intro circuit.");
3260 goto err;
3262 tor_assert(circuit->rend_data);
3263 service = rend_service_get_by_pk_digest(
3264 circuit->rend_data->rend_pk_digest);
3265 if (!service) {
3266 log_warn(LD_REND, "Unknown service on introduction circuit %u.",
3267 (unsigned)circuit->base_.n_circ_id);
3268 goto err;
3270 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
3271 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
3272 /* We've just successfully established a intro circuit to one of our
3273 * introduction point, account for it. */
3274 intro = find_intro_point(circuit);
3275 if (intro == NULL) {
3276 log_warn(LD_REND,
3277 "Introduction circuit established without a rend_intro_point_t "
3278 "object for service %s on circuit %u",
3279 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3280 goto err;
3282 intro->circuit_established = 1;
3283 /* We might not have every introduction point ready but at this point we
3284 * know that the descriptor needs to be uploaded. */
3285 service->desc_is_dirty = time(NULL);
3286 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
3288 log_info(LD_REND,
3289 "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3290 (unsigned)circuit->base_.n_circ_id, serviceid);
3292 /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3293 * used the circ */
3294 pathbias_mark_use_success(circuit);
3296 return 0;
3297 err:
3298 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
3299 return -1;
3302 /** Called once a circuit to a rendezvous point is established: sends a
3303 * RELAY_COMMAND_RENDEZVOUS1 cell.
3305 void
3306 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
3308 rend_service_t *service;
3309 char buf[RELAY_PAYLOAD_SIZE];
3310 crypt_path_t *hop;
3311 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3312 char hexcookie[9];
3313 int reason;
3315 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
3316 tor_assert(circuit->cpath);
3317 tor_assert(circuit->build_state);
3318 assert_circ_anonymity_ok(circuit, get_options());
3319 tor_assert(circuit->rend_data);
3321 /* Declare the circuit dirty to avoid reuse, and for path-bias */
3322 if (!circuit->base_.timestamp_dirty)
3323 circuit->base_.timestamp_dirty = time(NULL);
3325 /* This may be redundant */
3326 pathbias_count_use_attempt(circuit);
3328 hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
3330 base16_encode(hexcookie,9,circuit->rend_data->rend_cookie,4);
3331 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3332 circuit->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
3334 log_info(LD_REND,
3335 "Done building circuit %u to rendezvous with "
3336 "cookie %s for service %s",
3337 (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
3338 circuit_log_path(LOG_INFO, LD_REND, circuit);
3340 /* Clear the 'in-progress HS circ has timed out' flag for
3341 * consistency with what happens on the client side; this line has
3342 * no effect on Tor's behaviour. */
3343 circuit->hs_circ_has_timed_out = 0;
3345 /* If hop is NULL, another rend circ has already connected to this
3346 * rend point. Close this circ. */
3347 if (hop == NULL) {
3348 log_info(LD_REND, "Another rend circ has already reached this rend point; "
3349 "closing this rend circ.");
3350 reason = END_CIRC_REASON_NONE;
3351 goto err;
3354 /* Remove our final cpath element from the reference, so that no
3355 * other circuit will try to use it. Store it in
3356 * pending_final_cpath for now to ensure that it will be freed if
3357 * our rendezvous attempt fails. */
3358 circuit->build_state->pending_final_cpath = hop;
3359 circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
3361 service = rend_service_get_by_pk_digest(
3362 circuit->rend_data->rend_pk_digest);
3363 if (!service) {
3364 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
3365 "rendezvous circuit.");
3366 reason = END_CIRC_REASON_INTERNAL;
3367 goto err;
3370 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3371 memcpy(buf, circuit->rend_data->rend_cookie, REND_COOKIE_LEN);
3372 if (crypto_dh_get_public(hop->rend_dh_handshake_state,
3373 buf+REND_COOKIE_LEN, DH_KEY_LEN)<0) {
3374 log_warn(LD_GENERAL,"Couldn't get DH public key.");
3375 reason = END_CIRC_REASON_INTERNAL;
3376 goto err;
3378 memcpy(buf+REND_COOKIE_LEN+DH_KEY_LEN, hop->rend_circ_nonce,
3379 DIGEST_LEN);
3381 /* Send the cell */
3382 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3383 RELAY_COMMAND_RENDEZVOUS1,
3384 buf, REND_COOKIE_LEN+DH_KEY_LEN+DIGEST_LEN,
3385 circuit->cpath->prev)<0) {
3386 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
3387 reason = END_CIRC_REASON_INTERNAL;
3388 goto err;
3391 crypto_dh_free(hop->rend_dh_handshake_state);
3392 hop->rend_dh_handshake_state = NULL;
3394 /* Append the cpath entry. */
3395 hop->state = CPATH_STATE_OPEN;
3396 /* set the windows to default. these are the windows
3397 * that the service thinks the client has.
3399 hop->package_window = circuit_initial_package_window();
3400 hop->deliver_window = CIRCWINDOW_START;
3402 onion_append_to_cpath(&circuit->cpath, hop);
3403 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
3405 /* Change the circuit purpose. */
3406 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
3408 goto done;
3410 err:
3411 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3412 done:
3413 memwipe(buf, 0, sizeof(buf));
3414 memwipe(serviceid, 0, sizeof(serviceid));
3415 memwipe(hexcookie, 0, sizeof(hexcookie));
3417 return;
3421 * Manage introduction points
3424 /** Return the (possibly non-open) introduction circuit ending at
3425 * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
3426 * (<b>desc_version</b> is ignored). Return NULL if no such service is
3427 * found.
3429 static origin_circuit_t *
3430 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
3432 origin_circuit_t *circ = NULL;
3434 tor_assert(intro);
3435 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
3436 CIRCUIT_PURPOSE_S_INTRO))) {
3437 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3438 intro->extend_info->identity_digest, DIGEST_LEN) &&
3439 circ->rend_data) {
3440 return circ;
3444 circ = NULL;
3445 while ((circ = circuit_get_next_by_pk_and_purpose(circ,pk_digest,
3446 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
3447 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3448 intro->extend_info->identity_digest, DIGEST_LEN) &&
3449 circ->rend_data) {
3450 return circ;
3453 return NULL;
3456 /** Return the corresponding introdution point using the circuit <b>circ</b>
3457 * found in the <b>service</b>. NULL is returned if not found. */
3458 static rend_intro_point_t *
3459 find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
3461 tor_assert(service);
3462 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3463 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3465 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
3466 intro_point,
3467 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3468 return intro_point;
3471 return NULL;
3474 /** Return a pointer to the rend_intro_point_t corresponding to the
3475 * service-side introduction circuit <b>circ</b>. */
3476 static rend_intro_point_t *
3477 find_intro_point(origin_circuit_t *circ)
3479 const char *serviceid;
3480 rend_service_t *service = NULL;
3482 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3483 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3484 tor_assert(circ->rend_data);
3485 serviceid = circ->rend_data->onion_address;
3487 SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
3488 if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
3489 service = s;
3490 break;
3493 if (service == NULL) return NULL;
3495 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
3496 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3497 return intro_point;
3500 return NULL;
3503 /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
3504 * associated with the rend_service_descriptor_t <b>renddesc</b> to
3505 * the responsible hidden service directories OR the hidden service
3506 * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
3507 * <b>seconds_valid</b> are only passed for logging purposes.
3509 void
3510 directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
3511 smartlist_t *descs, smartlist_t *hs_dirs,
3512 const char *service_id, int seconds_valid)
3514 int i, j, failed_upload = 0;
3515 smartlist_t *responsible_dirs = smartlist_new();
3516 smartlist_t *successful_uploads = smartlist_new();
3517 routerstatus_t *hs_dir;
3518 for (i = 0; i < smartlist_len(descs); i++) {
3519 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
3520 /** If any HSDirs are specified, they should be used instead of
3521 * the responsible directories */
3522 if (hs_dirs && smartlist_len(hs_dirs) > 0) {
3523 smartlist_add_all(responsible_dirs, hs_dirs);
3524 } else {
3525 /* Determine responsible dirs. */
3526 if (hid_serv_get_responsible_directories(responsible_dirs,
3527 desc->desc_id) < 0) {
3528 log_warn(LD_REND, "Could not determine the responsible hidden service "
3529 "directories to post descriptors to.");
3530 control_event_hs_descriptor_upload(service_id,
3531 "UNKNOWN",
3532 "UNKNOWN");
3533 goto done;
3536 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
3537 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
3538 char *hs_dir_ip;
3539 const node_t *node;
3540 rend_data_t *rend_data;
3541 hs_dir = smartlist_get(responsible_dirs, j);
3542 if (smartlist_contains_digest(renddesc->successful_uploads,
3543 hs_dir->identity_digest))
3544 /* Don't upload descriptor if we succeeded in doing so last time. */
3545 continue;
3546 node = node_get_by_id(hs_dir->identity_digest);
3547 if (!node || !node_has_descriptor(node)) {
3548 log_info(LD_REND, "Not launching upload for for v2 descriptor to "
3549 "hidden service directory %s; we don't have its "
3550 "router descriptor. Queuing for later upload.",
3551 safe_str_client(routerstatus_describe(hs_dir)));
3552 failed_upload = -1;
3553 continue;
3555 /* Send publish request. */
3557 /* We need the service ID to identify which service did the upload
3558 * request. Lookup is made in rend_service_desc_has_uploaded(). */
3559 rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
3560 REND_NO_AUTH);
3561 directory_initiate_command_routerstatus_rend(hs_dir,
3562 DIR_PURPOSE_UPLOAD_RENDDESC_V2,
3563 ROUTER_PURPOSE_GENERAL,
3564 DIRIND_ANONYMOUS, NULL,
3565 desc->desc_str,
3566 strlen(desc->desc_str),
3567 0, rend_data);
3568 rend_data_free(rend_data);
3569 base32_encode(desc_id_base32, sizeof(desc_id_base32),
3570 desc->desc_id, DIGEST_LEN);
3571 hs_dir_ip = tor_dup_ip(hs_dir->addr);
3572 log_info(LD_REND, "Launching upload for v2 descriptor for "
3573 "service '%s' with descriptor ID '%s' with validity "
3574 "of %d seconds to hidden service directory '%s' on "
3575 "%s:%d.",
3576 safe_str_client(service_id),
3577 safe_str_client(desc_id_base32),
3578 seconds_valid,
3579 hs_dir->nickname,
3580 hs_dir_ip,
3581 hs_dir->or_port);
3582 control_event_hs_descriptor_upload(service_id,
3583 hs_dir->identity_digest,
3584 desc_id_base32);
3585 tor_free(hs_dir_ip);
3586 /* Remember successful upload to this router for next time. */
3587 if (!smartlist_contains_digest(successful_uploads,
3588 hs_dir->identity_digest))
3589 smartlist_add(successful_uploads, hs_dir->identity_digest);
3591 smartlist_clear(responsible_dirs);
3593 if (!failed_upload) {
3594 if (renddesc->successful_uploads) {
3595 SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
3596 smartlist_free(renddesc->successful_uploads);
3597 renddesc->successful_uploads = NULL;
3599 renddesc->all_uploads_performed = 1;
3600 } else {
3601 /* Remember which routers worked this time, so that we don't upload the
3602 * descriptor to them again. */
3603 if (!renddesc->successful_uploads)
3604 renddesc->successful_uploads = smartlist_new();
3605 SMARTLIST_FOREACH(successful_uploads, const char *, c, {
3606 if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
3607 char *hsdir_id = tor_memdup(c, DIGEST_LEN);
3608 smartlist_add(renddesc->successful_uploads, hsdir_id);
3612 done:
3613 smartlist_free(responsible_dirs);
3614 smartlist_free(successful_uploads);
3617 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
3618 * and upload it/them to the responsible hidden service directories.
3620 static void
3621 upload_service_descriptor(rend_service_t *service)
3623 time_t now = time(NULL);
3624 int rendpostperiod;
3625 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3626 int uploaded = 0;
3628 rendpostperiod = get_options()->RendPostPeriod;
3630 networkstatus_t *c = networkstatus_get_latest_consensus();
3631 if (c && smartlist_len(c->routerstatus_list) > 0) {
3632 int seconds_valid, i, j, num_descs;
3633 smartlist_t *descs = smartlist_new();
3634 smartlist_t *client_cookies = smartlist_new();
3635 /* Either upload a single descriptor (including replicas) or one
3636 * descriptor for each authorized client in case of authorization
3637 * type 'stealth'. */
3638 num_descs = service->auth_type == REND_STEALTH_AUTH ?
3639 smartlist_len(service->clients) : 1;
3640 for (j = 0; j < num_descs; j++) {
3641 crypto_pk_t *client_key = NULL;
3642 rend_authorized_client_t *client = NULL;
3643 smartlist_clear(client_cookies);
3644 switch (service->auth_type) {
3645 case REND_NO_AUTH:
3646 /* Do nothing here. */
3647 break;
3648 case REND_BASIC_AUTH:
3649 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
3650 cl, smartlist_add(client_cookies, cl->descriptor_cookie));
3651 break;
3652 case REND_STEALTH_AUTH:
3653 client = smartlist_get(service->clients, j);
3654 client_key = client->client_key;
3655 smartlist_add(client_cookies, client->descriptor_cookie);
3656 break;
3658 /* Encode the current descriptor. */
3659 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3660 now, 0,
3661 service->auth_type,
3662 client_key,
3663 client_cookies);
3664 if (seconds_valid < 0) {
3665 log_warn(LD_BUG, "Internal error: couldn't encode service "
3666 "descriptor; not uploading.");
3667 smartlist_free(descs);
3668 smartlist_free(client_cookies);
3669 return;
3671 rend_get_service_id(service->desc->pk, serviceid);
3672 if (get_options()->PublishHidServDescriptors) {
3673 /* Post the current descriptors to the hidden service directories. */
3674 log_info(LD_REND, "Launching upload for hidden service %s",
3675 serviceid);
3676 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3677 seconds_valid);
3679 /* Free memory for descriptors. */
3680 for (i = 0; i < smartlist_len(descs); i++)
3681 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
3682 smartlist_clear(descs);
3683 /* Update next upload time. */
3684 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3685 > rendpostperiod)
3686 service->next_upload_time = now + rendpostperiod;
3687 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
3688 service->next_upload_time = now + seconds_valid + 1;
3689 else
3690 service->next_upload_time = now + seconds_valid -
3691 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
3692 /* Post also the next descriptors, if necessary. */
3693 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
3694 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3695 now, 1,
3696 service->auth_type,
3697 client_key,
3698 client_cookies);
3699 if (seconds_valid < 0) {
3700 log_warn(LD_BUG, "Internal error: couldn't encode service "
3701 "descriptor; not uploading.");
3702 smartlist_free(descs);
3703 smartlist_free(client_cookies);
3704 return;
3706 if (get_options()->PublishHidServDescriptors) {
3707 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3708 seconds_valid);
3710 /* Free memory for descriptors. */
3711 for (i = 0; i < smartlist_len(descs); i++)
3712 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
3713 smartlist_clear(descs);
3716 smartlist_free(descs);
3717 smartlist_free(client_cookies);
3718 uploaded = 1;
3719 if (get_options()->PublishHidServDescriptors) {
3720 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
3721 } else {
3722 log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
3726 /* If not uploaded, try again in one minute. */
3727 if (!uploaded)
3728 service->next_upload_time = now + 60;
3730 /* Unmark dirty flag of this service. */
3731 service->desc_is_dirty = 0;
3734 /** Return the number of INTRODUCE2 cells this hidden service has received
3735 * from this intro point. */
3736 static int
3737 intro_point_accepted_intro_count(rend_intro_point_t *intro)
3739 return intro->accepted_introduce2_count;
3742 /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
3743 * should stop publishing it in new descriptors and eventually close
3744 * it). */
3745 static int
3746 intro_point_should_expire_now(rend_intro_point_t *intro,
3747 time_t now)
3749 tor_assert(intro != NULL);
3751 if (intro->time_published == -1) {
3752 /* Don't expire an intro point if we haven't even published it yet. */
3753 return 0;
3756 if (intro_point_accepted_intro_count(intro) >=
3757 intro->max_introductions) {
3758 /* This intro point has been used too many times. Expire it now. */
3759 return 1;
3762 if (intro->time_to_expire == -1) {
3763 /* This intro point has been published, but we haven't picked an
3764 * expiration time for it. Pick one now. */
3765 int intro_point_lifetime_seconds =
3766 crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
3767 INTRO_POINT_LIFETIME_MAX_SECONDS);
3769 /* Start the expiration timer now, rather than when the intro
3770 * point was first published. There shouldn't be much of a time
3771 * difference. */
3772 intro->time_to_expire = now + intro_point_lifetime_seconds;
3774 return 0;
3777 /* This intro point has a time to expire set already. Use it. */
3778 return (now >= intro->time_to_expire);
3781 /** Iterate over intro points in the given service and remove the invalid
3782 * ones. For an intro point object to be considered invalid, the circuit
3783 * _and_ node need to have disappeared.
3785 * If the intro point should expire, it's placed into the expiring_nodes
3786 * list of the service and removed from the active intro nodes list.
3788 * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
3790 * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
3791 * circuit disappeared but the node is still in the consensus. */
3792 static void
3793 remove_invalid_intro_points(rend_service_t *service,
3794 smartlist_t *exclude_nodes,
3795 smartlist_t *retry_nodes, time_t now)
3797 tor_assert(service);
3799 SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
3800 intro) {
3801 /* Find the introduction point node object. */
3802 const node_t *node =
3803 node_get_by_id(intro->extend_info->identity_digest);
3804 /* Find the intro circuit, this might be NULL. */
3805 origin_circuit_t *intro_circ =
3806 find_intro_circuit(intro, service->pk_digest);
3808 /* Add the valid node to the exclusion list so we don't try to establish
3809 * an introduction point to it again. */
3810 if (node && exclude_nodes) {
3811 smartlist_add(exclude_nodes, (void*) node);
3814 /* First, make sure we still have a valid circuit for this intro point.
3815 * If we dont, we'll give up on it and make a new one. */
3816 if (intro_circ == NULL) {
3817 log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
3818 " (circuit disappeared).",
3819 safe_str_client(extend_info_describe(intro->extend_info)),
3820 safe_str_client(service->service_id));
3821 /* We've lost the circuit for this intro point, flag it so it can be
3822 * accounted for when considiring uploading a descriptor. */
3823 intro->circuit_established = 0;
3825 /* Node is gone or we've reached our maximum circuit creationg retry
3826 * count, clean up everything, we'll find a new one. */
3827 if (node == NULL ||
3828 intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
3829 rend_intro_point_free(intro);
3830 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
3831 /* We've just killed the intro point, nothing left to do. */
3832 continue;
3835 /* The intro point is still alive so let's try to use it again because
3836 * we have a published descriptor containing it. Keep the intro point
3837 * in the intro_nodes list because it's still valid, we are rebuilding
3838 * a circuit to it. */
3839 if (retry_nodes) {
3840 smartlist_add(retry_nodes, intro);
3843 /* else, the circuit is valid so in both cases, node being alive or not,
3844 * we leave the circuit and intro point object as is. Closing the
3845 * circuit here would leak new consensus timing and freeing the intro
3846 * point object would make the intro circuit unusable. */
3848 /* Now, check if intro point should expire. If it does, queue it so
3849 * it can be cleaned up once it has been replaced properly. */
3850 if (intro_point_should_expire_now(intro, now)) {
3851 log_info(LD_REND, "Expiring %s as intro point for %s.",
3852 safe_str_client(extend_info_describe(intro->extend_info)),
3853 safe_str_client(service->service_id));
3854 /* We might have put it in the retry list if so, undo. */
3855 if (retry_nodes) {
3856 smartlist_remove(retry_nodes, intro);
3858 smartlist_add(service->expiring_nodes, intro);
3859 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
3860 /* Intro point is expired, we need a new one thus don't consider it
3861 * anymore has a valid established intro point. */
3862 intro->circuit_established = 0;
3864 } SMARTLIST_FOREACH_END(intro);
3867 /** A new descriptor has been successfully uploaded for the given
3868 * <b>rend_data</b>. Remove and free the expiring nodes from the associated
3869 * service. */
3870 void
3871 rend_service_desc_has_uploaded(const rend_data_t *rend_data)
3873 rend_service_t *service;
3875 tor_assert(rend_data);
3877 service = rend_service_get_by_service_id(rend_data->onion_address);
3878 if (service == NULL) {
3879 return;
3882 SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
3883 intro) {
3884 origin_circuit_t *intro_circ =
3885 find_intro_circuit(intro, service->pk_digest);
3886 if (intro_circ != NULL) {
3887 circuit_mark_for_close(TO_CIRCUIT(intro_circ),
3888 END_CIRC_REASON_FINISHED);
3890 SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
3891 rend_intro_point_free(intro);
3892 } SMARTLIST_FOREACH_END(intro);
3895 /** For every service, check how many intro points it currently has, and:
3896 * - Invalidate introdution points based on specific criteria, see
3897 * remove_invalid_intro_points comments.
3898 * - Pick new intro points as necessary.
3899 * - Launch circuits to any new intro points.
3901 * This is called once a second by the main loop.
3903 void
3904 rend_consider_services_intro_points(void)
3906 int i;
3907 time_t now;
3908 const or_options_t *options = get_options();
3909 /* Are we in single onion mode? */
3910 const int allow_direct = rend_service_allow_non_anonymous_connection(
3911 get_options());
3912 /* List of nodes we need to _exclude_ when choosing a new node to
3913 * establish an intro point to. */
3914 smartlist_t *exclude_nodes;
3915 /* List of nodes we need to retry to build a circuit on them because the
3916 * node is valid but circuit died. */
3917 smartlist_t *retry_nodes;
3919 if (!have_completed_a_circuit())
3920 return;
3922 exclude_nodes = smartlist_new();
3923 retry_nodes = smartlist_new();
3924 now = time(NULL);
3926 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
3927 int r;
3928 /* Number of intro points we want to open and add to the intro nodes
3929 * list of the service. */
3930 unsigned int n_intro_points_to_open;
3931 /* Have an unsigned len so we can use it to compare values else gcc is
3932 * not happy with unmatching signed comparaison. */
3933 unsigned int intro_nodes_len;
3934 /* Different service are allowed to have the same introduction point as
3935 * long as they are on different circuit thus why we clear this list. */
3936 smartlist_clear(exclude_nodes);
3937 smartlist_clear(retry_nodes);
3939 /* This retry period is important here so we don't stress circuit
3940 * creation. */
3941 if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
3942 /* One period has elapsed; we can try building circuits again. */
3943 service->intro_period_started = now;
3944 service->n_intro_circuits_launched = 0;
3945 } else if (service->n_intro_circuits_launched >=
3946 MAX_INTRO_CIRCS_PER_PERIOD) {
3947 /* We have failed too many times in this period; wait for the next
3948 * one before we try again. */
3949 continue;
3952 /* Cleanup the invalid intro points and save the node objects, if apply,
3953 * in the exclude_nodes and retry_nodes list. */
3954 remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
3956 /* Let's try to rebuild circuit on the nodes we want to retry on. */
3957 SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
3958 r = rend_service_launch_establish_intro(service, intro);
3959 if (r < 0) {
3960 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
3961 safe_str_client(extend_info_describe(intro->extend_info)),
3962 safe_str_client(service->service_id));
3963 /* Unable to launch a circuit to that intro point, remove it from
3964 * the valid list so we can create a new one. */
3965 smartlist_remove(service->intro_nodes, intro);
3966 rend_intro_point_free(intro);
3967 continue;
3969 intro->circuit_retries++;
3970 } SMARTLIST_FOREACH_END(intro);
3972 /* Avoid mismatched signed comparaison below. */
3973 intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
3975 /* Quiescent state, no node expiring and we have more or the amount of
3976 * wanted node for this service. Proceed to the next service. Could be
3977 * more because we launch two preemptive circuits if our intro nodes
3978 * list is empty. */
3979 if (smartlist_len(service->expiring_nodes) == 0 &&
3980 intro_nodes_len >= service->n_intro_points_wanted) {
3981 continue;
3984 /* Number of intro points we want to open which is the wanted amount
3985 * minus the current amount of valid nodes. */
3986 n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
3987 if (intro_nodes_len == 0) {
3988 /* We want to end up with n_intro_points_wanted intro points, but if
3989 * we have no intro points at all (chances are they all cycled or we
3990 * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
3991 * and use the first n_intro_points_wanted that complete. See proposal
3992 * #155, section 4 for the rationale of this which is purely for
3993 * performance.
3995 * The ones after the first n_intro_points_to_open will be converted
3996 * to 'general' internal circuits in rend_service_intro_has_opened(),
3997 * and then we'll drop them from the list of intro points. */
3998 n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
4001 for (i = 0; i < (int) n_intro_points_to_open; i++) {
4002 const node_t *node;
4003 rend_intro_point_t *intro;
4004 router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
4005 if (get_options()->AllowInvalid_ & ALLOW_INVALID_INTRODUCTION)
4006 flags |= CRN_ALLOW_INVALID;
4007 router_crn_flags_t direct_flags = flags;
4008 direct_flags |= CRN_PREF_ADDR;
4009 direct_flags |= CRN_DIRECT_CONN;
4011 node = router_choose_random_node(exclude_nodes,
4012 options->ExcludeNodes,
4013 allow_direct ? direct_flags : flags);
4014 /* If we are in single onion mode, retry node selection for a 3-hop
4015 * path */
4016 if (allow_direct && !node) {
4017 log_info(LD_REND,
4018 "Unable to find an intro point that we can connect to "
4019 "directly for %s, falling back to a 3-hop path.",
4020 safe_str_client(service->service_id));
4021 node = router_choose_random_node(exclude_nodes,
4022 options->ExcludeNodes, flags);
4025 if (!node) {
4026 log_warn(LD_REND,
4027 "We only have %d introduction points established for %s; "
4028 "wanted %u.",
4029 smartlist_len(service->intro_nodes),
4030 safe_str_client(service->service_id),
4031 n_intro_points_to_open);
4032 break;
4034 /* Add the choosen node to the exclusion list in order to avoid picking
4035 * it again in the next iteration. */
4036 smartlist_add(exclude_nodes, (void*)node);
4037 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4038 /* extend_info is for clients, so we want the multi-hop primary ORPort,
4039 * even if we are a single onion service and intend to connect to it
4040 * directly ourselves. */
4041 intro->extend_info = extend_info_from_node(node, 0);
4042 intro->intro_key = crypto_pk_new();
4043 const int fail = crypto_pk_generate_key(intro->intro_key);
4044 tor_assert(!fail);
4045 intro->time_published = -1;
4046 intro->time_to_expire = -1;
4047 intro->max_introductions =
4048 crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
4049 INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
4050 smartlist_add(service->intro_nodes, intro);
4051 log_info(LD_REND, "Picked router %s as an intro point for %s.",
4052 safe_str_client(node_describe(node)),
4053 safe_str_client(service->service_id));
4054 /* Establish new introduction circuit to our chosen intro point. */
4055 r = rend_service_launch_establish_intro(service, intro);
4056 if (r < 0) {
4057 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4058 safe_str_client(extend_info_describe(intro->extend_info)),
4059 safe_str_client(service->service_id));
4060 /* This funcion will be called again by the main loop so this intro
4061 * point without a intro circuit will be retried on or removed after
4062 * a maximum number of attempts. */
4065 } SMARTLIST_FOREACH_END(service);
4066 smartlist_free(exclude_nodes);
4067 smartlist_free(retry_nodes);
4070 #define MIN_REND_INITIAL_POST_DELAY (30)
4071 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4073 /** Regenerate and upload rendezvous service descriptors for all
4074 * services, if necessary. If the descriptor has been dirty enough
4075 * for long enough, definitely upload; else only upload when the
4076 * periodic timeout has expired.
4078 * For the first upload, pick a random time between now and two periods
4079 * from now, and pick it independently for each service.
4081 void
4082 rend_consider_services_upload(time_t now)
4084 int i;
4085 rend_service_t *service;
4086 const or_options_t *options = get_options();
4087 int rendpostperiod = options->RendPostPeriod;
4088 int rendinitialpostdelay = (options->TestingTorNetwork ?
4089 MIN_REND_INITIAL_POST_DELAY_TESTING :
4090 MIN_REND_INITIAL_POST_DELAY);
4092 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4093 service = smartlist_get(rend_service_list, i);
4094 if (!service->next_upload_time) { /* never been uploaded yet */
4095 /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4096 * the descriptor is stable before being published. See comment below. */
4097 service->next_upload_time =
4098 now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
4099 /* Single Onion Services prioritise availability over hiding their
4100 * startup time, as their IP address is publicly discoverable anyway.
4102 if (rend_service_reveal_startup_time(options)) {
4103 service->next_upload_time = now + rendinitialpostdelay;
4106 /* Does every introduction points have been established? */
4107 unsigned int intro_points_ready =
4108 count_established_intro_points(service) >=
4109 service->n_intro_points_wanted;
4110 if (intro_points_ready &&
4111 (service->next_upload_time < now ||
4112 (service->desc_is_dirty &&
4113 service->desc_is_dirty < now-rendinitialpostdelay))) {
4114 /* if it's time, or if the directory servers have a wrong service
4115 * descriptor and ours has been stable for rendinitialpostdelay seconds,
4116 * upload a new one of each format. */
4117 rend_service_update_descriptor(service);
4118 upload_service_descriptor(service);
4123 /** True if the list of available router descriptors might have changed so
4124 * that we should have a look whether we can republish previously failed
4125 * rendezvous service descriptors. */
4126 static int consider_republishing_rend_descriptors = 1;
4128 /** Called when our internal view of the directory has changed, so that we
4129 * might have router descriptors of hidden service directories available that
4130 * we did not have before. */
4131 void
4132 rend_hsdir_routers_changed(void)
4134 consider_republishing_rend_descriptors = 1;
4137 /** Consider republication of v2 rendezvous service descriptors that failed
4138 * previously, but without regenerating descriptor contents.
4140 void
4141 rend_consider_descriptor_republication(void)
4143 int i;
4144 rend_service_t *service;
4146 if (!consider_republishing_rend_descriptors)
4147 return;
4148 consider_republishing_rend_descriptors = 0;
4150 if (!get_options()->PublishHidServDescriptors)
4151 return;
4153 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4154 service = smartlist_get(rend_service_list, i);
4155 if (service->desc && !service->desc->all_uploads_performed) {
4156 /* If we failed in uploading a descriptor last time, try again *without*
4157 * updating the descriptor's contents. */
4158 upload_service_descriptor(service);
4163 /** Log the status of introduction points for all rendezvous services
4164 * at log severity <b>severity</b>.
4166 void
4167 rend_service_dump_stats(int severity)
4169 int i,j;
4170 rend_service_t *service;
4171 rend_intro_point_t *intro;
4172 const char *safe_name;
4173 origin_circuit_t *circ;
4175 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4176 service = smartlist_get(rend_service_list, i);
4177 tor_log(severity, LD_GENERAL, "Service configured in \"%s\":",
4178 service->directory);
4179 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
4180 intro = smartlist_get(service->intro_nodes, j);
4181 safe_name = safe_str_client(intro->extend_info->nickname);
4183 circ = find_intro_circuit(intro, service->pk_digest);
4184 if (!circ) {
4185 tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
4186 j, safe_name);
4187 continue;
4189 tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
4190 j, safe_name, circuit_state_to_string(circ->base_.state));
4195 #ifdef HAVE_SYS_UN_H
4197 /** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
4198 * add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
4199 * else return -ENOSYS if AF_UNIX is not supported (see function in the
4200 * #else statement below). */
4201 static int
4202 add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
4204 tor_assert(ports);
4205 tor_assert(p);
4206 tor_assert(p->is_unix_addr);
4208 smartlist_add(ports, p);
4209 return 0;
4212 /** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
4213 * on success else return -ENOSYS if AF_UNIX is not supported (see function
4214 * in the #else statement below). */
4215 static int
4216 set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
4218 tor_assert(conn);
4219 tor_assert(p);
4220 tor_assert(p->is_unix_addr);
4222 conn->base_.socket_family = AF_UNIX;
4223 tor_addr_make_unspec(&conn->base_.addr);
4224 conn->base_.port = 1;
4225 conn->base_.address = tor_strdup(p->unix_addr);
4226 return 0;
4229 #else /* defined(HAVE_SYS_UN_H) */
4231 static int
4232 set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
4234 (void) conn;
4235 (void) p;
4236 return -ENOSYS;
4239 static int
4240 add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
4242 (void) ports;
4243 (void) p;
4244 return -ENOSYS;
4247 #endif /* HAVE_SYS_UN_H */
4249 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
4250 * 'circ', and look up the port and address based on conn-\>port.
4251 * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
4252 * for which the circuit should be closed, -1 on other failure,
4253 * or 0 for success.
4256 rend_service_set_connection_addr_port(edge_connection_t *conn,
4257 origin_circuit_t *circ)
4259 rend_service_t *service;
4260 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4261 smartlist_t *matching_ports;
4262 rend_service_port_config_t *chosen_port;
4263 unsigned int warn_once = 0;
4265 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
4266 tor_assert(circ->rend_data);
4267 log_debug(LD_REND,"beginning to hunt for addr/port");
4268 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
4269 circ->rend_data->rend_pk_digest, REND_SERVICE_ID_LEN);
4270 service = rend_service_get_by_pk_digest(
4271 circ->rend_data->rend_pk_digest);
4272 if (!service) {
4273 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
4274 "rendezvous circuit %u; closing.",
4275 serviceid, (unsigned)circ->base_.n_circ_id);
4276 return -2;
4278 if (service->max_streams_per_circuit > 0) {
4279 /* Enforce the streams-per-circuit limit, and refuse to provide a
4280 * mapping if this circuit will exceed the limit. */
4281 #define MAX_STREAM_WARN_INTERVAL 600
4282 static struct ratelim_t stream_ratelim =
4283 RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
4284 if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
4285 log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
4286 "Maximum streams per circuit limit reached on rendezvous "
4287 "circuit %u; %s. Circuit has %d out of %d streams.",
4288 (unsigned)circ->base_.n_circ_id,
4289 service->max_streams_close_circuit ?
4290 "closing circuit" :
4291 "ignoring open stream request",
4292 circ->rend_data->nr_streams,
4293 service->max_streams_per_circuit);
4294 return service->max_streams_close_circuit ? -2 : -1;
4297 matching_ports = smartlist_new();
4298 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t *, p,
4300 if (conn->base_.port != p->virtual_port) {
4301 continue;
4303 if (!(p->is_unix_addr)) {
4304 smartlist_add(matching_ports, p);
4305 } else {
4306 if (add_unix_port(matching_ports, p)) {
4307 if (!warn_once) {
4308 /* Unix port not supported so warn only once. */
4309 log_warn(LD_REND,
4310 "Saw AF_UNIX virtual port mapping for port %d on service "
4311 "%s, which is unsupported on this platform. Ignoring it.",
4312 conn->base_.port, serviceid);
4314 warn_once++;
4318 chosen_port = smartlist_choose(matching_ports);
4319 smartlist_free(matching_ports);
4320 if (chosen_port) {
4321 if (!(chosen_port->is_unix_addr)) {
4322 /* Get a non-AF_UNIX connection ready for connection_exit_connect() */
4323 tor_addr_copy(&conn->base_.addr, &chosen_port->real_addr);
4324 conn->base_.port = chosen_port->real_port;
4325 } else {
4326 if (set_unix_port(conn, chosen_port)) {
4327 /* Simply impossible to end up here else we were able to add a Unix
4328 * port without AF_UNIX support... ? */
4329 tor_assert(0);
4332 return 0;
4335 log_info(LD_REND,
4336 "No virtual port mapping exists for port %d on service %s",
4337 conn->base_.port, serviceid);
4339 if (service->allow_unknown_ports)
4340 return -1;
4341 else
4342 return -2;
4345 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4347 static int
4348 rend_service_non_anonymous_mode_consistent(const or_options_t *options)
4350 /* !! is used to make these options boolean */
4351 return (!! options->HiddenServiceSingleHopMode ==
4352 !! options->HiddenServiceNonAnonymousMode);
4355 /* Do the options allow onion services to make direct (non-anonymous)
4356 * connections to introduction or rendezvous points?
4357 * Must only be called after options_validate_single_onion() has successfully
4358 * checked onion service option consistency.
4359 * Returns true if tor is in HiddenServiceSingleHopMode. */
4361 rend_service_allow_non_anonymous_connection(const or_options_t *options)
4363 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4364 return options->HiddenServiceSingleHopMode ? 1 : 0;
4367 /* Do the options allow us to reveal the exact startup time of the onion
4368 * service?
4369 * Single Onion Services prioritise availability over hiding their
4370 * startup time, as their IP address is publicly discoverable anyway.
4371 * Must only be called after options_validate_single_onion() has successfully
4372 * checked onion service option consistency.
4373 * Returns true if tor is in non-anonymous hidden service mode. */
4375 rend_service_reveal_startup_time(const or_options_t *options)
4377 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4378 return rend_service_non_anonymous_mode_enabled(options);
4381 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4382 * config option?
4383 * Must only be called after options_validate_single_onion() has successfully
4384 * checked onion service option consistency.
4387 rend_service_non_anonymous_mode_enabled(const or_options_t *options)
4389 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4390 return options->HiddenServiceNonAnonymousMode ? 1 : 0;