Move the predicted ports code out of rephist.c
[tor.git] / src / feature / rend / rendservice.c
blob057ca2d0c7555bd218af64ee9e452e597d9f00a5
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2018, The Tor Project, Inc. */
3 /* See LICENSE for licensing information */
5 /**
6 * \file rendservice.c
7 * \brief The hidden-service side of rendezvous functionality.
8 **/
10 #define RENDSERVICE_PRIVATE
12 #include "core/or/or.h"
14 #include "app/config/config.h"
15 #include "core/mainloop/mainloop.h"
16 #include "core/or/circuitbuild.h"
17 #include "core/or/circuitlist.h"
18 #include "core/or/circuituse.h"
19 #include "core/or/policies.h"
20 #include "core/or/relay.h"
21 #include "feature/client/circpathbias.h"
22 #include "feature/control/control.h"
23 #include "feature/dirclient/dirclient.h"
24 #include "feature/dircommon/directory.h"
25 #include "feature/hs/hs_common.h"
26 #include "feature/hs/hs_config.h"
27 #include "feature/hs_common/replaycache.h"
28 #include "feature/keymgt/loadkey.h"
29 #include "feature/nodelist/describe.h"
30 #include "feature/nodelist/networkstatus.h"
31 #include "feature/nodelist/nickname.h"
32 #include "feature/nodelist/node_select.h"
33 #include "feature/nodelist/nodelist.h"
34 #include "feature/nodelist/routerparse.h"
35 #include "feature/nodelist/routerset.h"
36 #include "feature/rend/rendclient.h"
37 #include "feature/rend/rendcommon.h"
38 #include "feature/rend/rendservice.h"
39 #include "feature/stats/predict_ports.h"
40 #include "lib/crypt_ops/crypto_dh.h"
41 #include "lib/crypt_ops/crypto_rand.h"
42 #include "lib/crypt_ops/crypto_util.h"
43 #include "lib/encoding/confline.h"
44 #include "lib/net/resolve.h"
46 #include "core/or/cpath_build_state_st.h"
47 #include "core/or/crypt_path_st.h"
48 #include "core/or/crypt_path_reference_st.h"
49 #include "core/or/edge_connection_st.h"
50 #include "core/or/extend_info_st.h"
51 #include "feature/nodelist/networkstatus_st.h"
52 #include "core/or/origin_circuit_st.h"
53 #include "feature/rend/rend_authorized_client_st.h"
54 #include "feature/rend/rend_encoded_v2_service_descriptor_st.h"
55 #include "feature/rend/rend_intro_point_st.h"
56 #include "feature/rend/rend_service_descriptor_st.h"
57 #include "feature/nodelist/routerstatus_st.h"
59 #ifdef HAVE_FCNTL_H
60 #include <fcntl.h>
61 #endif
62 #ifdef HAVE_UNISTD_H
63 #include <unistd.h>
64 #endif
65 #ifdef HAVE_SYS_STAT_H
66 #include <sys/stat.h>
67 #endif
69 struct rend_service_t;
70 static origin_circuit_t *find_intro_circuit(rend_intro_point_t *intro,
71 const char *pk_digest);
72 static rend_intro_point_t *find_intro_point(origin_circuit_t *circ);
73 static rend_intro_point_t *find_expiring_intro_point(
74 struct rend_service_t *service, origin_circuit_t *circ);
76 static extend_info_t *find_rp_for_intro(
77 const rend_intro_cell_t *intro,
78 char **err_msg_out);
80 static int intro_point_accepted_intro_count(rend_intro_point_t *intro);
81 static int intro_point_should_expire_now(rend_intro_point_t *intro,
82 time_t now);
83 static int rend_service_derive_key_digests(struct rend_service_t *s);
84 static int rend_service_load_keys(struct rend_service_t *s);
85 static int rend_service_load_auth_keys(struct rend_service_t *s,
86 const char *hfname);
87 static struct rend_service_t *rend_service_get_by_pk_digest(
88 const char* digest);
89 static struct rend_service_t *rend_service_get_by_service_id(const char *id);
90 static const char *rend_service_escaped_dir(
91 const struct rend_service_t *s);
93 static ssize_t rend_service_parse_intro_for_v0_or_v1(
94 rend_intro_cell_t *intro,
95 const uint8_t *buf,
96 size_t plaintext_len,
97 char **err_msg_out);
98 static ssize_t rend_service_parse_intro_for_v2(
99 rend_intro_cell_t *intro,
100 const uint8_t *buf,
101 size_t plaintext_len,
102 char **err_msg_out);
103 static ssize_t rend_service_parse_intro_for_v3(
104 rend_intro_cell_t *intro,
105 const uint8_t *buf,
106 size_t plaintext_len,
107 char **err_msg_out);
109 static int rend_service_check_private_dir(const or_options_t *options,
110 const rend_service_t *s,
111 int create);
112 static const smartlist_t* rend_get_service_list(
113 const smartlist_t* substitute_service_list);
114 static smartlist_t* rend_get_service_list_mutable(
115 smartlist_t* substitute_service_list);
116 static int rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted);
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 /** A list of rend_service_t's for services run on this OP. */
127 static smartlist_t *rend_service_list = NULL;
128 /** A list of rend_service_t's for services run on this OP which is used as a
129 * staging area before they are put in the main list in order to prune dying
130 * service on config reload. */
131 static smartlist_t *rend_service_staging_list = NULL;
133 /* Like rend_get_service_list_mutable, but returns a read-only list. */
134 static const smartlist_t*
135 rend_get_service_list(const smartlist_t* substitute_service_list)
137 /* It is safe to cast away the const here, because
138 * rend_get_service_list_mutable does not actually modify the list */
139 return rend_get_service_list_mutable((smartlist_t*)substitute_service_list);
142 /* Return a mutable list of hidden services.
143 * If substitute_service_list is not NULL, return it.
144 * Otherwise, check if the global rend_service_list is non-NULL, and if so,
145 * return it.
146 * Otherwise, log a BUG message and return NULL.
147 * */
148 static smartlist_t*
149 rend_get_service_list_mutable(smartlist_t* substitute_service_list)
151 if (substitute_service_list) {
152 return substitute_service_list;
155 /* If no special service list is provided, then just use the global one. */
157 if (BUG(!rend_service_list)) {
158 /* No global HS list, which is a programmer error. */
159 return NULL;
162 return rend_service_list;
165 /** Tells if onion service <b>s</b> is ephemeral.
167 static unsigned int
168 rend_service_is_ephemeral(const struct rend_service_t *s)
170 return (s->directory == NULL);
173 /** Returns a escaped string representation of the service, <b>s</b>.
175 static const char *
176 rend_service_escaped_dir(const struct rend_service_t *s)
178 return rend_service_is_ephemeral(s) ? "[EPHEMERAL]" : escaped(s->directory);
181 /** Return the number of rendezvous services we have configured. */
183 rend_num_services(void)
185 if (!rend_service_list)
186 return 0;
187 return smartlist_len(rend_service_list);
190 /** Helper: free storage held by a single service authorized client entry. */
191 void
192 rend_authorized_client_free_(rend_authorized_client_t *client)
194 if (!client)
195 return;
196 if (client->client_key)
197 crypto_pk_free(client->client_key);
198 if (client->client_name)
199 memwipe(client->client_name, 0, strlen(client->client_name));
200 tor_free(client->client_name);
201 memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
202 tor_free(client);
205 /** Helper for strmap_free. */
206 static void
207 rend_authorized_client_free_void(void *authorized_client)
209 rend_authorized_client_free_(authorized_client);
212 /** Release the storage held by <b>service</b>.
214 STATIC void
215 rend_service_free_(rend_service_t *service)
217 if (!service)
218 return;
220 tor_free(service->directory);
221 if (service->ports) {
222 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
223 rend_service_port_config_free(p));
224 smartlist_free(service->ports);
226 if (service->private_key)
227 crypto_pk_free(service->private_key);
228 if (service->intro_nodes) {
229 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
230 rend_intro_point_free(intro););
231 smartlist_free(service->intro_nodes);
233 if (service->expiring_nodes) {
234 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
235 rend_intro_point_free(intro););
236 smartlist_free(service->expiring_nodes);
239 rend_service_descriptor_free(service->desc);
240 if (service->clients) {
241 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
242 rend_authorized_client_free(c););
243 smartlist_free(service->clients);
245 if (service->accepted_intro_dh_parts) {
246 replaycache_free(service->accepted_intro_dh_parts);
248 tor_free(service);
251 /* Release all the storage held in rend_service_staging_list. */
252 void
253 rend_service_free_staging_list(void)
255 if (rend_service_staging_list) {
256 SMARTLIST_FOREACH(rend_service_staging_list, rend_service_t*, ptr,
257 rend_service_free(ptr));
258 smartlist_free(rend_service_staging_list);
259 rend_service_staging_list = NULL;
263 /** Release all the storage held in both rend_service_list and
264 * rend_service_staging_list. */
265 void
266 rend_service_free_all(void)
268 if (rend_service_list) {
269 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
270 rend_service_free(ptr));
271 smartlist_free(rend_service_list);
272 rend_service_list = NULL;
274 rend_service_free_staging_list();
277 /* Initialize the subsystem. */
278 void
279 rend_service_init(void)
281 tor_assert(!rend_service_list);
282 tor_assert(!rend_service_staging_list);
284 rend_service_list = smartlist_new();
285 rend_service_staging_list = smartlist_new();
288 /* Validate a <b>service</b>. Use the <b>service_list</b> to make sure there
289 * is no duplicate entry for the given service object. Return 0 if valid else
290 * -1 if not.*/
291 static int
292 rend_validate_service(const smartlist_t *service_list,
293 const rend_service_t *service)
295 tor_assert(service_list);
296 tor_assert(service);
298 if (service->max_streams_per_circuit < 0) {
299 log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
300 "streams per circuit.",
301 rend_service_escaped_dir(service));
302 goto invalid;
305 if (service->max_streams_close_circuit < 0 ||
306 service->max_streams_close_circuit > 1) {
307 log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
308 "max streams handling.",
309 rend_service_escaped_dir(service));
310 goto invalid;
313 if (service->auth_type != REND_NO_AUTH &&
314 (!service->clients || smartlist_len(service->clients) == 0)) {
315 log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but "
316 "no clients.",
317 rend_service_escaped_dir(service));
318 goto invalid;
321 if (!service->ports || !smartlist_len(service->ports)) {
322 log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured.",
323 rend_service_escaped_dir(service));
324 goto invalid;
327 /* Valid. */
328 return 0;
329 invalid:
330 return -1;
333 /** Add it to <b>service_list</b>, or to the global rend_service_list if
334 * <b>service_list</b> is NULL. Return 0 on success. On failure, free
335 * <b>service</b> and return -1. Takes ownership of <b>service</b>. */
336 static int
337 rend_add_service(smartlist_t *service_list, rend_service_t *service)
339 int i;
340 rend_service_port_config_t *p;
342 tor_assert(service);
344 smartlist_t *s_list = rend_get_service_list_mutable(service_list);
345 /* We must have a service list, even if it's a temporary one, so we can
346 * check for duplicate services */
347 if (BUG(!s_list)) {
348 rend_service_free(service);
349 return -1;
352 service->intro_nodes = smartlist_new();
353 service->expiring_nodes = smartlist_new();
355 log_debug(LD_REND,"Configuring service with directory %s",
356 rend_service_escaped_dir(service));
357 for (i = 0; i < smartlist_len(service->ports); ++i) {
358 p = smartlist_get(service->ports, i);
359 if (!(p->is_unix_addr)) {
360 log_debug(LD_REND,
361 "Service maps port %d to %s",
362 p->virtual_port,
363 fmt_addrport(&p->real_addr, p->real_port));
364 } else {
365 #ifdef HAVE_SYS_UN_H
366 log_debug(LD_REND,
367 "Service maps port %d to socket at \"%s\"",
368 p->virtual_port, p->unix_addr);
369 #else
370 log_warn(LD_BUG,
371 "Service maps port %d to an AF_UNIX socket, but we "
372 "have no AF_UNIX support on this platform. This is "
373 "probably a bug.",
374 p->virtual_port);
375 rend_service_free(service);
376 return -1;
377 #endif /* defined(HAVE_SYS_UN_H) */
380 /* The service passed all the checks */
381 tor_assert(s_list);
382 smartlist_add(s_list, service);
384 /* Notify that our global service list has changed only if this new service
385 * went into our global list. If not, when we move service from the staging
386 * list to the new list, a notify is triggered. */
387 if (s_list == rend_service_list) {
388 hs_service_map_has_changed();
390 return 0;
393 /** Return a new rend_service_port_config_t with its path set to
394 * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
395 static rend_service_port_config_t *
396 rend_service_port_config_new(const char *socket_path)
398 if (!socket_path)
399 return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
401 const size_t pathlen = strlen(socket_path) + 1;
402 rend_service_port_config_t *conf =
403 tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
404 memcpy(conf->unix_addr, socket_path, pathlen);
405 conf->is_unix_addr = 1;
406 return conf;
409 /** Parses a virtual-port to real-port/socket mapping separated by
410 * the provided separator and returns a new rend_service_port_config_t,
411 * or NULL and an optional error string on failure.
413 * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
415 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
417 rend_service_port_config_t *
418 rend_service_parse_port_config(const char *string, const char *sep,
419 char **err_msg_out)
421 smartlist_t *sl;
422 int virtport;
423 int realport = 0;
424 uint16_t p;
425 tor_addr_t addr;
426 rend_service_port_config_t *result = NULL;
427 unsigned int is_unix_addr = 0;
428 const char *socket_path = NULL;
429 char *err_msg = NULL;
430 char *addrport = NULL;
432 sl = smartlist_new();
433 smartlist_split_string(sl, string, sep,
434 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
435 if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
436 err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
437 goto err;
439 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
440 if (!virtport) {
441 tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
442 "port configuration", escaped(smartlist_get(sl,0)));
444 goto err;
446 if (smartlist_len(sl) == 1) {
447 /* No addr:port part; use default. */
448 realport = virtport;
449 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
450 } else {
451 int ret;
453 const char *addrport_element = smartlist_get(sl,1);
454 const char *rest = NULL;
455 int is_unix;
456 ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
457 &is_unix, &rest);
459 if (ret < 0) {
460 tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
461 "service configuration", addrport_element);
462 goto err;
465 if (rest && strlen(rest)) {
466 err_msg = tor_strdup("HiddenServicePort parse error: invalid port "
467 "mapping");
468 goto err;
471 if (is_unix) {
472 socket_path = addrport;
473 is_unix_addr = 1;
474 } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
475 /* else try it as an IP:port pair if it has a : or . in it */
476 if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
477 err_msg = tor_strdup("Unparseable address in hidden service port "
478 "configuration.");
479 goto err;
481 realport = p?p:virtport;
482 } else {
483 /* No addr:port, no addr -- must be port. */
484 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
485 if (!realport) {
486 tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
487 "hidden service port configuration.",
488 escaped(addrport));
489 goto err;
491 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
495 /* Allow room for unix_addr */
496 result = rend_service_port_config_new(socket_path);
497 result->virtual_port = virtport;
498 result->is_unix_addr = is_unix_addr;
499 if (!is_unix_addr) {
500 result->real_port = realport;
501 tor_addr_copy(&result->real_addr, &addr);
502 result->unix_addr[0] = '\0';
505 err:
506 tor_free(addrport);
507 if (err_msg_out != NULL) {
508 *err_msg_out = err_msg;
509 } else {
510 tor_free(err_msg);
512 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
513 smartlist_free(sl);
515 return result;
518 /** Release all storage held in a rend_service_port_config_t. */
519 void
520 rend_service_port_config_free_(rend_service_port_config_t *p)
522 tor_free(p);
525 /* Copy relevant data from service src to dst while pruning the service lists.
526 * This should only be called during the pruning process which takes existing
527 * services and copy their data to the newly configured services. The src
528 * service replaycache will be set to NULL after this call. */
529 static void
530 copy_service_on_prunning(rend_service_t *dst, rend_service_t *src)
532 tor_assert(dst);
533 tor_assert(src);
535 /* Keep the timestamps for when the content changed and the next upload
536 * time so we can properly upload the descriptor if needed for the new
537 * service object. */
538 dst->desc_is_dirty = src->desc_is_dirty;
539 dst->next_upload_time = src->next_upload_time;
540 /* Move the replaycache to the new object. */
541 dst->accepted_intro_dh_parts = src->accepted_intro_dh_parts;
542 src->accepted_intro_dh_parts = NULL;
543 /* Copy intro point information to destination service. */
544 dst->intro_period_started = src->intro_period_started;
545 dst->n_intro_circuits_launched = src->n_intro_circuits_launched;
546 dst->n_intro_points_wanted = src->n_intro_points_wanted;
549 /* Helper: Actual implementation of the pruning on reload which we've
550 * decoupled in order to make the unit test workeable without ugly hacks.
551 * Furthermore, this function does NOT free any memory but will nullify the
552 * temporary list pointer whatever happens. */
553 STATIC void
554 rend_service_prune_list_impl_(void)
556 origin_circuit_t *ocirc = NULL;
557 smartlist_t *surviving_services, *old_service_list, *new_service_list;
559 /* When pruning our current service list, we must have a staging list that
560 * contains what we want to check else it's a code flow error. */
561 tor_assert(rend_service_staging_list);
563 /* We are about to prune the current list of its dead service so set the
564 * semantic for that list to be the "old" one. */
565 old_service_list = rend_service_list;
566 /* The staging list is now the "new" list so set this semantic. */
567 new_service_list = rend_service_staging_list;
568 /* After this, whatever happens, we'll use our new list. */
569 rend_service_list = new_service_list;
570 /* Finally, nullify the staging list pointer as we don't need it anymore
571 * and it needs to be NULL before the next reload. */
572 rend_service_staging_list = NULL;
573 /* Nothing to prune if we have no service list so stop right away. */
574 if (!old_service_list) {
575 return;
578 /* This contains all _existing_ services that survives the relaod that is
579 * that haven't been removed from the configuration. The difference between
580 * this list and the new service list is that the new list can possibly
581 * contain newly configured service that have no introduction points opened
582 * yet nor key material loaded or generated. */
583 surviving_services = smartlist_new();
585 /* Preserve the existing ephemeral services.
587 * This is the ephemeral service equivalent of the "Copy introduction
588 * points to new services" block, except there's no copy required since
589 * the service structure isn't regenerated.
591 * After this is done, all ephemeral services will be:
592 * * Removed from old_service_list, so the equivalent non-ephemeral code
593 * will not attempt to preserve them.
594 * * Added to the new_service_list (that previously only had the
595 * services listed in the configuration).
596 * * Added to surviving_services, which is the list of services that
597 * will NOT have their intro point closed.
599 SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
600 if (rend_service_is_ephemeral(old)) {
601 SMARTLIST_DEL_CURRENT(old_service_list, old);
602 smartlist_add(surviving_services, old);
603 smartlist_add(new_service_list, old);
605 } SMARTLIST_FOREACH_END(old);
607 /* Copy introduction points to new services. This is O(n^2), but it's only
608 * called on reconfigure, so it's ok performance wise. */
609 SMARTLIST_FOREACH_BEGIN(new_service_list, rend_service_t *, new) {
610 SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
611 /* Skip ephemeral services as we only want to copy introduction points
612 * from current services to newly configured one that already exists.
613 * The same directory means it's the same service. */
614 if (rend_service_is_ephemeral(new) || rend_service_is_ephemeral(old) ||
615 strcmp(old->directory, new->directory)) {
616 continue;
618 smartlist_add_all(new->intro_nodes, old->intro_nodes);
619 smartlist_clear(old->intro_nodes);
620 smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
621 smartlist_clear(old->expiring_nodes);
623 /* Copy needed information from old to new. */
624 copy_service_on_prunning(new, old);
626 /* This regular service will survive the closing IPs step after. */
627 smartlist_add(surviving_services, old);
628 break;
629 } SMARTLIST_FOREACH_END(old);
630 } SMARTLIST_FOREACH_END(new);
632 /* For every service introduction circuit we can find, see if we have a
633 * matching surviving configured service. If not, close the circuit. */
634 while ((ocirc = circuit_get_next_service_intro_circ(ocirc))) {
635 int keep_it = 0;
636 if (ocirc->rend_data == NULL) {
637 /* This is a v3 circuit, ignore it. */
638 continue;
640 SMARTLIST_FOREACH_BEGIN(surviving_services, const rend_service_t *, s) {
641 if (rend_circuit_pk_digest_eq(ocirc, (uint8_t *) s->pk_digest)) {
642 /* Keep this circuit as we have a matching configured service. */
643 keep_it = 1;
644 break;
646 } SMARTLIST_FOREACH_END(s);
647 if (keep_it) {
648 continue;
650 log_info(LD_REND, "Closing intro point %s for service %s.",
651 safe_str_client(extend_info_describe(
652 ocirc->build_state->chosen_exit)),
653 safe_str_client(rend_data_get_address(ocirc->rend_data)));
654 /* Reason is FINISHED because service has been removed and thus the
655 * circuit is considered old/uneeded. */
656 circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
658 smartlist_free(surviving_services);
659 /* Notify that our global service list has changed. */
660 hs_service_map_has_changed();
663 /* Try to prune our main service list using the temporary one that we just
664 * loaded and parsed successfully. The pruning process decides which onion
665 * services to keep and which to discard after a reload. */
666 void
667 rend_service_prune_list(void)
669 smartlist_t *old_service_list = rend_service_list;
671 if (!rend_service_staging_list) {
672 rend_service_staging_list = smartlist_new();
675 rend_service_prune_list_impl_();
676 if (old_service_list) {
677 /* Every remaining service in the old list have been removed from the
678 * configuration so clean them up safely. */
679 SMARTLIST_FOREACH(old_service_list, rend_service_t *, s,
680 rend_service_free(s));
681 smartlist_free(old_service_list);
685 /* Copy all the relevant data that the hs_service object contains over to the
686 * rend_service_t object. The reason to do so is because when configuring a
687 * service, we go through a generic handler that creates an hs_service_t
688 * object which so we have to copy the parsed values to a rend service object
689 * which is version 2 specific. */
690 static void
691 service_config_shadow_copy(rend_service_t *service,
692 hs_service_config_t *config)
694 tor_assert(service);
695 tor_assert(config);
697 service->directory = tor_strdup(config->directory_path);
698 service->dir_group_readable = config->dir_group_readable;
699 service->allow_unknown_ports = config->allow_unknown_ports;
700 /* This value can't go above HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT (65535)
701 * if the code flow is right so this cast is safe. But just in case, we'll
702 * check it. */
703 service->max_streams_per_circuit = (int) config->max_streams_per_rdv_circuit;
704 if (BUG(config->max_streams_per_rdv_circuit >
705 HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT)) {
706 service->max_streams_per_circuit = HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT;
708 service->max_streams_close_circuit = config->max_streams_close_circuit;
709 service->n_intro_points_wanted = config->num_intro_points;
710 /* Switching ownership of the ports to the rend service object. */
711 smartlist_add_all(service->ports, config->ports);
712 smartlist_free(config->ports);
713 config->ports = NULL;
716 /* Parse the hidden service configuration starting at <b>line_</b> using the
717 * already configured generic service configuration in <b>config</b>. This
718 * function will translate the config object to a rend_service_t and add it to
719 * the temporary list if valid. If <b>validate_only</b> is set, parse, warn
720 * and return as normal but don't actually add the service to the list. */
722 rend_config_service(const config_line_t *line_,
723 const or_options_t *options,
724 hs_service_config_t *config)
726 const config_line_t *line;
727 rend_service_t *service = NULL;
729 /* line_ can be NULL which would mean that the service configuration only
730 * have one line that is the directory directive. */
731 tor_assert(options);
732 tor_assert(config);
734 /* Use the staging service list so that we can check then do the pruning
735 * process using the main list at the end. */
736 if (rend_service_staging_list == NULL) {
737 rend_service_staging_list = smartlist_new();
740 /* Initialize service. */
741 service = tor_malloc_zero(sizeof(rend_service_t));
742 service->intro_period_started = time(NULL);
743 service->ports = smartlist_new();
744 /* From the hs_service object which has been used to load the generic
745 * options, we'll copy over the useful data to the rend_service_t object. */
746 service_config_shadow_copy(service, config);
748 for (line = line_; line; line = line->next) {
749 if (!strcasecmp(line->key, "HiddenServiceDir")) {
750 /* We just hit the next hidden service, stop right now. */
751 break;
753 /* Number of introduction points. */
754 if (!strcasecmp(line->key, "HiddenServiceNumIntroductionPoints")) {
755 int ok = 0;
756 /* Those are specific defaults for version 2. */
757 service->n_intro_points_wanted =
758 (unsigned int) tor_parse_long(line->value, 10,
759 0, NUM_INTRO_POINTS_MAX, &ok, NULL);
760 if (!ok) {
761 log_warn(LD_CONFIG,
762 "HiddenServiceNumIntroductionPoints "
763 "should be between %d and %d, not %s",
764 0, NUM_INTRO_POINTS_MAX, line->value);
765 goto err;
767 log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
768 service->n_intro_points_wanted, escaped(service->directory));
769 continue;
771 if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
772 /* Parse auth type and comma-separated list of client names and add a
773 * rend_authorized_client_t for each client to the service's list
774 * of authorized clients. */
775 smartlist_t *type_names_split, *clients;
776 const char *authname;
777 if (service->auth_type != REND_NO_AUTH) {
778 log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
779 "lines for a single service.");
780 goto err;
782 type_names_split = smartlist_new();
783 smartlist_split_string(type_names_split, line->value, " ", 0, 2);
784 if (smartlist_len(type_names_split) < 1) {
785 log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
786 "should have been prevented when parsing the "
787 "configuration.");
788 smartlist_free(type_names_split);
789 goto err;
791 authname = smartlist_get(type_names_split, 0);
792 if (!strcasecmp(authname, "basic")) {
793 service->auth_type = REND_BASIC_AUTH;
794 } else if (!strcasecmp(authname, "stealth")) {
795 service->auth_type = REND_STEALTH_AUTH;
796 } else {
797 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
798 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
799 "are recognized.",
800 (char *) smartlist_get(type_names_split, 0));
801 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
802 smartlist_free(type_names_split);
803 goto err;
805 service->clients = smartlist_new();
806 if (smartlist_len(type_names_split) < 2) {
807 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
808 "auth-type '%s', but no client names.",
809 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
810 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
811 smartlist_free(type_names_split);
812 continue;
814 clients = smartlist_new();
815 smartlist_split_string(clients, smartlist_get(type_names_split, 1),
816 ",", SPLIT_SKIP_SPACE, 0);
817 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
818 smartlist_free(type_names_split);
819 /* Remove duplicate client names. */
821 int num_clients = smartlist_len(clients);
822 smartlist_sort_strings(clients);
823 smartlist_uniq_strings(clients);
824 if (smartlist_len(clients) < num_clients) {
825 log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
826 "duplicate client name(s); removing.",
827 num_clients - smartlist_len(clients));
830 SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
832 rend_authorized_client_t *client;
833 if (!rend_valid_client_name(client_name)) {
834 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
835 "illegal client name: '%s'. Names must be "
836 "between 1 and %d characters and contain "
837 "only [A-Za-z0-9+_-].",
838 client_name, REND_CLIENTNAME_MAX_LEN);
839 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
840 smartlist_free(clients);
841 goto err;
843 client = tor_malloc_zero(sizeof(rend_authorized_client_t));
844 client->client_name = tor_strdup(client_name);
845 smartlist_add(service->clients, client);
846 log_debug(LD_REND, "Adding client name '%s'", client_name);
848 SMARTLIST_FOREACH_END(client_name);
849 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
850 smartlist_free(clients);
851 /* Ensure maximum number of clients. */
852 if ((service->auth_type == REND_BASIC_AUTH &&
853 smartlist_len(service->clients) > 512) ||
854 (service->auth_type == REND_STEALTH_AUTH &&
855 smartlist_len(service->clients) > 16)) {
856 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
857 "client authorization entries, but only a "
858 "maximum of %d entries is allowed for "
859 "authorization type '%s'.",
860 smartlist_len(service->clients),
861 service->auth_type == REND_BASIC_AUTH ? 512 : 16,
862 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
863 goto err;
865 continue;
868 /* Validate the service just parsed. */
869 if (rend_validate_service(rend_service_staging_list, service) < 0) {
870 /* Service is in the staging list so don't try to free it. */
871 goto err;
874 /* Add it to the temporary list which we will use to prune our current
875 * list if any after configuring all services. */
876 if (rend_add_service(rend_service_staging_list, service) < 0) {
877 /* The object has been freed on error already. */
878 service = NULL;
879 goto err;
882 return 0;
883 err:
884 rend_service_free(service);
885 return -1;
888 /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
889 * client authorization <b>auth_type</b> and an optional list of
890 * rend_authorized_client_t in <b>auth_clients</b>, with
891 * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
892 * and circuit closure on max streams being exceeded set by
893 * <b>max_streams_close_circuit</b>.
895 * Ownership of pk, ports, and auth_clients is passed to this routine.
896 * Regardless of success/failure, callers should not touch these values
897 * after calling this routine, and may assume that correct cleanup has
898 * been done on failure.
900 * Return an appropriate hs_service_add_ephemeral_status_t.
902 hs_service_add_ephemeral_status_t
903 rend_service_add_ephemeral(crypto_pk_t *pk,
904 smartlist_t *ports,
905 int max_streams_per_circuit,
906 int max_streams_close_circuit,
907 rend_auth_type_t auth_type,
908 smartlist_t *auth_clients,
909 char **service_id_out)
911 *service_id_out = NULL;
912 /* Allocate the service structure, and initialize the key, and key derived
913 * parameters.
915 rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
916 s->directory = NULL; /* This indicates the service is ephemeral. */
917 s->private_key = pk;
918 s->auth_type = auth_type;
919 s->clients = auth_clients;
920 s->ports = ports;
921 s->intro_period_started = time(NULL);
922 s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
923 s->max_streams_per_circuit = max_streams_per_circuit;
924 s->max_streams_close_circuit = max_streams_close_circuit;
925 if (rend_service_derive_key_digests(s) < 0) {
926 rend_service_free(s);
927 return RSAE_BADPRIVKEY;
930 if (!s->ports || smartlist_len(s->ports) == 0) {
931 log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
932 rend_service_free(s);
933 return RSAE_BADVIRTPORT;
935 if (s->auth_type != REND_NO_AUTH &&
936 (!s->clients || smartlist_len(s->clients) == 0)) {
937 log_warn(LD_CONFIG, "At least one authorized client must be specified.");
938 rend_service_free(s);
939 return RSAE_BADAUTH;
942 /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
943 * it's not, see #14828.
945 if (rend_service_get_by_pk_digest(s->pk_digest)) {
946 log_warn(LD_CONFIG, "Onion Service private key collides with an "
947 "existing service.");
948 rend_service_free(s);
949 return RSAE_ADDREXISTS;
951 if (rend_service_get_by_service_id(s->service_id)) {
952 log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
953 rend_service_free(s);
954 return RSAE_ADDREXISTS;
957 /* Initialize the service. */
958 if (rend_add_service(NULL, s)) {
959 return RSAE_INTERNAL;
961 *service_id_out = tor_strdup(s->service_id);
963 log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
964 return RSAE_OKAY;
967 /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
968 * success, and -1 on failure.
971 rend_service_del_ephemeral(const char *service_id)
973 rend_service_t *s;
974 if (!rend_valid_v2_service_id(service_id)) {
975 log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
976 return -1;
978 if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
979 log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
980 "removal.");
981 return -1;
983 if (!rend_service_is_ephemeral(s)) {
984 log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
985 return -1;
988 /* Kill the intro point circuit for the Onion Service, and remove it from
989 * the list. Closing existing connections is the application's problem.
991 * XXX: As with the comment in rend_config_services(), a nice abstraction
992 * would be ideal here, but for now just duplicate the code.
994 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
995 if (!circ->marked_for_close &&
996 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
997 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
998 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
999 if (oc->rend_data == NULL ||
1000 !rend_circuit_pk_digest_eq(oc, (uint8_t *) s->pk_digest)) {
1001 continue;
1003 log_debug(LD_REND, "Closing intro point %s for service %s.",
1004 safe_str_client(extend_info_describe(
1005 oc->build_state->chosen_exit)),
1006 rend_data_get_address(oc->rend_data));
1007 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1009 } SMARTLIST_FOREACH_END(circ);
1010 smartlist_remove(rend_service_list, s);
1011 /* Notify that we just removed a service from our global list. */
1012 hs_service_map_has_changed();
1013 rend_service_free(s);
1015 log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
1017 return 0;
1020 /* There can be 1 second's delay due to second_elapsed_callback, and perhaps
1021 * another few seconds due to blocking calls. */
1022 #define INTRO_CIRC_RETRY_PERIOD_SLOP 10
1024 /** Log information about the intro point creation rate and current intro
1025 * points for service, upgrading the log level from min_severity to warn if
1026 * we have stopped launching new intro point circuits. */
1027 static void
1028 rend_log_intro_limit(const rend_service_t *service, int min_severity)
1030 int exceeded_limit = (service->n_intro_circuits_launched >=
1031 rend_max_intro_circs_per_period(
1032 service->n_intro_points_wanted));
1033 int severity = min_severity;
1034 /* We stopped creating circuits */
1035 if (exceeded_limit) {
1036 severity = LOG_WARN;
1038 time_t intro_period_elapsed = time(NULL) - service->intro_period_started;
1039 tor_assert_nonfatal(intro_period_elapsed >= 0);
1041 char *msg;
1042 static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
1043 if ((msg = rate_limit_log(&rlimit, approx_time()))) {
1044 log_fn(severity, LD_REND,
1045 "Hidden service %s %s %d intro points in the last %d seconds. "
1046 "Intro circuit launches are limited to %d per %d seconds.%s",
1047 service->service_id,
1048 exceeded_limit ? "exceeded launch limit with" : "launched",
1049 service->n_intro_circuits_launched,
1050 (int)intro_period_elapsed,
1051 rend_max_intro_circs_per_period(service->n_intro_points_wanted),
1052 INTRO_CIRC_RETRY_PERIOD, msg);
1053 rend_service_dump_stats(severity);
1054 tor_free(msg);
1059 /** Replace the old value of <b>service</b>-\>desc with one that reflects
1060 * the other fields in service.
1062 static void
1063 rend_service_update_descriptor(rend_service_t *service)
1065 rend_service_descriptor_t *d;
1066 int i;
1068 rend_service_descriptor_free(service->desc);
1069 service->desc = NULL;
1071 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
1072 d->pk = crypto_pk_dup_key(service->private_key);
1073 d->timestamp = time(NULL);
1074 d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */
1075 d->intro_nodes = smartlist_new();
1076 /* Support intro protocols 2 and 3. */
1077 d->protocols = (1 << 2) + (1 << 3);
1079 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
1080 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
1081 rend_intro_point_t *intro_desc;
1083 /* This intro point won't be listed in the descriptor... */
1084 intro_svc->listed_in_last_desc = 0;
1086 /* circuit_established is set in rend_service_intro_established(), and
1087 * checked every second in rend_consider_services_intro_points(), so it's
1088 * safe to use it here */
1089 if (!intro_svc->circuit_established) {
1090 continue;
1093 /* ...unless this intro point is listed in the descriptor. */
1094 intro_svc->listed_in_last_desc = 1;
1096 /* We have an entirely established intro circuit. Publish it in
1097 * our descriptor. */
1098 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
1099 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
1100 if (intro_svc->intro_key)
1101 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
1102 smartlist_add(d->intro_nodes, intro_desc);
1104 if (intro_svc->time_published == -1) {
1105 /* We are publishing this intro point in a descriptor for the
1106 * first time -- note the current time in the service's copy of
1107 * the intro point. */
1108 intro_svc->time_published = time(NULL);
1112 /* Check that we have the right number of intro points */
1113 unsigned int have_intro = (unsigned int)smartlist_len(d->intro_nodes);
1114 if (have_intro != service->n_intro_points_wanted) {
1115 int severity;
1116 /* Getting less than we wanted or more than we're allowed is serious */
1117 if (have_intro < service->n_intro_points_wanted ||
1118 have_intro > NUM_INTRO_POINTS_MAX) {
1119 severity = LOG_WARN;
1120 } else {
1121 /* Getting more than we wanted is weird, but less of a problem */
1122 severity = LOG_NOTICE;
1124 log_fn(severity, LD_REND, "Hidden service %s wanted %d intro points, but "
1125 "descriptor was updated with %d instead.",
1126 service->service_id,
1127 service->n_intro_points_wanted, have_intro);
1128 /* Now log an informative message about how we might have got here. */
1129 rend_log_intro_limit(service, severity);
1133 /* Allocate and return a string containing the path to file_name in
1134 * service->directory. Asserts that service has a directory.
1135 * This function will never return NULL.
1136 * The caller must free this path. */
1137 static char *
1138 rend_service_path(const rend_service_t *service, const char *file_name)
1140 tor_assert(service->directory);
1141 return hs_path_from_filename(service->directory, file_name);
1144 /* Allocate and return a string containing the path to the single onion
1145 * service poison file in service->directory. Asserts that service has a
1146 * directory.
1147 * The caller must free this path. */
1148 STATIC char *
1149 rend_service_sos_poison_path(const rend_service_t *service)
1151 return rend_service_path(service, sos_poison_fname);
1154 /** Return True if hidden services <b>service</b> has been poisoned by single
1155 * onion mode. */
1156 static int
1157 service_is_single_onion_poisoned(const rend_service_t *service)
1159 char *poison_fname = NULL;
1160 file_status_t fstatus;
1162 /* Passing a NULL service is a bug */
1163 if (BUG(!service)) {
1164 return 0;
1167 if (rend_service_is_ephemeral(service)) {
1168 return 0;
1171 poison_fname = rend_service_sos_poison_path(service);
1173 fstatus = file_status(poison_fname);
1174 tor_free(poison_fname);
1176 /* If this fname is occupied, the hidden service has been poisoned.
1177 * fstatus can be FN_ERROR if the service directory does not exist, in that
1178 * case, there is obviously no private key. */
1179 if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
1180 return 1;
1183 return 0;
1186 /* Return 1 if the private key file for service exists and has a non-zero size,
1187 * and 0 otherwise. */
1188 static int
1189 rend_service_private_key_exists(const rend_service_t *service)
1191 char *private_key_path = rend_service_path(service, private_key_fname);
1192 const file_status_t private_key_status = file_status(private_key_path);
1193 tor_free(private_key_path);
1194 /* Only non-empty regular private key files could have been used before.
1195 * fstatus can be FN_ERROR if the service directory does not exist, in that
1196 * case, there is obviously no private key. */
1197 return private_key_status == FN_FILE;
1200 /** Check the single onion service poison state of the directory for s:
1201 * - If the service is poisoned, and we are in Single Onion Mode,
1202 * return 0,
1203 * - If the service is not poisoned, and we are not in Single Onion Mode,
1204 * return 0,
1205 * - Otherwise, the poison state is invalid: the service was created in one
1206 * mode, and is being used in the other, return -1.
1207 * Hidden service directories without keys are always considered consistent.
1208 * They will be poisoned after their directory is created (if needed). */
1209 STATIC int
1210 rend_service_verify_single_onion_poison(const rend_service_t* s,
1211 const or_options_t* options)
1213 /* Passing a NULL service is a bug */
1214 if (BUG(!s)) {
1215 return -1;
1218 /* Ephemeral services are checked at ADD_ONION time */
1219 if (BUG(rend_service_is_ephemeral(s))) {
1220 return -1;
1223 /* Service is expected to have a directory */
1224 if (BUG(!s->directory)) {
1225 return -1;
1228 /* Services without keys are always ok - their keys will only ever be used
1229 * in the current mode */
1230 if (!rend_service_private_key_exists(s)) {
1231 return 0;
1234 /* The key has been used before in a different mode */
1235 if (service_is_single_onion_poisoned(s) !=
1236 rend_service_non_anonymous_mode_enabled(options)) {
1237 return -1;
1240 /* The key exists and is consistent with the current mode */
1241 return 0;
1244 /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
1245 * the hidden service directory for s that marks it as a single onion service.
1246 * Tor must be in single onion mode before calling this function, and the
1247 * service directory must already have been created.
1248 * Returns 0 when a directory is successfully poisoned, or if it is already
1249 * poisoned. Returns -1 on a failure to read the directory or write the poison
1250 * file, or if there is an existing private key file in the directory. (The
1251 * service should have been poisoned when the key was created.) */
1252 static int
1253 poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
1254 const or_options_t* options)
1256 /* Passing a NULL service is a bug */
1257 if (BUG(!service)) {
1258 return -1;
1261 /* We must only poison directories if we're in Single Onion mode */
1262 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1264 int fd;
1265 int retval = -1;
1266 char *poison_fname = NULL;
1268 if (rend_service_is_ephemeral(service)) {
1269 log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
1270 return 0;
1273 /* Make sure we're only poisoning new hidden service directories */
1274 if (rend_service_private_key_exists(service)) {
1275 log_warn(LD_BUG, "Tried to single onion poison a service directory after "
1276 "the private key was created.");
1277 return -1;
1280 /* Make sure the directory was created before calling this function. */
1281 if (BUG(hs_check_service_private_dir(options->User, service->directory,
1282 service->dir_group_readable, 0) < 0))
1283 return -1;
1285 poison_fname = rend_service_sos_poison_path(service);
1287 switch (file_status(poison_fname)) {
1288 case FN_DIR:
1289 case FN_ERROR:
1290 log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
1291 poison_fname);
1292 goto done;
1293 case FN_FILE: /* single onion poison file already exists. NOP. */
1294 case FN_EMPTY: /* single onion poison file already exists. NOP. */
1295 log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
1296 poison_fname);
1297 break;
1298 case FN_NOENT:
1299 fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
1300 if (fd < 0) {
1301 log_warn(LD_FS, "Could not create single onion poison file %s",
1302 poison_fname);
1303 goto done;
1305 close(fd);
1306 break;
1307 default:
1308 tor_assert(0);
1311 retval = 0;
1313 done:
1314 tor_free(poison_fname);
1316 return retval;
1319 /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
1320 * hidden services. If s is new, we should mark its hidden service
1321 * directory appropriately so that it is never launched as a location-private
1322 * hidden service. (New directories don't have private key files.)
1323 * Return 0 on success, -1 on fail. */
1324 STATIC int
1325 rend_service_poison_new_single_onion_dir(const rend_service_t *s,
1326 const or_options_t* options)
1328 /* Passing a NULL service is a bug */
1329 if (BUG(!s)) {
1330 return -1;
1333 /* We must only poison directories if we're in Single Onion mode */
1334 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1336 /* Ephemeral services aren't allowed in non-anonymous mode */
1337 if (BUG(rend_service_is_ephemeral(s))) {
1338 return -1;
1341 /* Service is expected to have a directory */
1342 if (BUG(!s->directory)) {
1343 return -1;
1346 if (!rend_service_private_key_exists(s)) {
1347 if (poison_new_single_onion_hidden_service_dir_impl(s, options)
1348 < 0) {
1349 return -1;
1353 return 0;
1356 /* Return true iff the given service identity key is present on disk. This is
1357 * used to try to learn the service version during configuration time. */
1359 rend_service_key_on_disk(const char *directory_path)
1361 int ret = 0;
1362 char *fname;
1363 crypto_pk_t *pk = NULL;
1365 tor_assert(directory_path);
1367 /* Load key */
1368 fname = hs_path_from_filename(directory_path, private_key_fname);
1369 pk = init_key_from_file(fname, 0, LOG_DEBUG, NULL);
1370 if (pk) {
1371 ret = 1;
1374 crypto_pk_free(pk);
1375 tor_free(fname);
1376 return ret;
1379 /** Load and/or generate private keys for all hidden services, possibly
1380 * including keys for client authorization.
1381 * If a <b>service_list</b> is provided, treat it as the list of hidden
1382 * services (used in unittests). Otherwise, require that rend_service_list is
1383 * not NULL.
1384 * Return 0 on success, -1 on failure. */
1386 rend_service_load_all_keys(const smartlist_t *service_list)
1388 /* Use service_list for unit tests */
1389 const smartlist_t *s_list = rend_get_service_list(service_list);
1390 if (BUG(!s_list)) {
1391 return -1;
1394 SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
1395 if (s->private_key)
1396 continue;
1397 log_info(LD_REND, "Loading hidden-service keys from %s",
1398 rend_service_escaped_dir(s));
1400 if (rend_service_load_keys(s) < 0)
1401 return -1;
1402 } SMARTLIST_FOREACH_END(s);
1404 return 0;
1407 /** Add to <b>lst</b> every filename used by <b>s</b>. */
1408 static void
1409 rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
1411 tor_assert(lst);
1412 tor_assert(s);
1413 tor_assert(s->directory);
1414 smartlist_add(lst, rend_service_path(s, private_key_fname));
1415 smartlist_add(lst, rend_service_path(s, hostname_fname));
1416 smartlist_add(lst, rend_service_path(s, client_keys_fname));
1417 smartlist_add(lst, rend_service_sos_poison_path(s));
1420 /** Add to <b>open_lst</b> every filename used by a configured hidden service,
1421 * and to <b>stat_lst</b> every directory used by a configured hidden
1422 * service */
1423 void
1424 rend_services_add_filenames_to_lists(smartlist_t *open_lst,
1425 smartlist_t *stat_lst)
1427 if (!rend_service_list)
1428 return;
1429 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
1430 if (!rend_service_is_ephemeral(s)) {
1431 rend_service_add_filenames_to_list(open_lst, s);
1432 smartlist_add_strdup(stat_lst, s->directory);
1434 } SMARTLIST_FOREACH_END(s);
1437 /** Derive all rend_service_t internal material based on the service's key.
1438 * Returns 0 on success, -1 on failure.
1440 static int
1441 rend_service_derive_key_digests(struct rend_service_t *s)
1443 if (rend_get_service_id(s->private_key, s->service_id)<0) {
1444 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1445 return -1;
1447 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
1448 log_warn(LD_BUG, "Couldn't compute hash of public key.");
1449 return -1;
1452 return 0;
1455 /** Make sure that the directory for <b>s</b> is private, using the config in
1456 * <b>options</b>.
1457 * If <b>create</b> is true:
1458 * - if the directory exists, change permissions if needed,
1459 * - if the directory does not exist, create it with the correct permissions.
1460 * If <b>create</b> is false:
1461 * - if the directory exists, check permissions,
1462 * - if the directory does not exist, check if we think we can create it.
1463 * Return 0 on success, -1 on failure. */
1464 static int
1465 rend_service_check_private_dir(const or_options_t *options,
1466 const rend_service_t *s,
1467 int create)
1469 /* Passing a NULL service is a bug */
1470 if (BUG(!s)) {
1471 return -1;
1474 /* Check/create directory */
1475 if (hs_check_service_private_dir(options->User, s->directory,
1476 s->dir_group_readable, create) < 0) {
1477 return -1;
1480 /* Check if the hidden service key exists, and was created in a different
1481 * single onion service mode, and refuse to launch if it has.
1482 * This is safe to call even when create is false, as it ignores missing
1483 * keys and directories: they are always valid.
1485 if (rend_service_verify_single_onion_poison(s, options) < 0) {
1486 /* We can't use s->service_id here, as the key may not have been loaded */
1487 log_warn(LD_GENERAL, "We are configured with "
1488 "HiddenServiceNonAnonymousMode %d, but the hidden "
1489 "service key in directory %s was created in %s mode. "
1490 "This is not allowed.",
1491 rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
1492 rend_service_escaped_dir(s),
1493 rend_service_non_anonymous_mode_enabled(options) ?
1494 "an anonymous" : "a non-anonymous"
1496 return -1;
1499 /* Poison new single onion directories immediately after they are created,
1500 * so that we never accidentally launch non-anonymous hidden services
1501 * thinking they are anonymous. Any keys created later will end up with the
1502 * correct poisoning state.
1504 if (create && rend_service_non_anonymous_mode_enabled(options)) {
1505 static int logged_warning = 0;
1507 if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
1508 log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
1509 ".");
1510 return -1;
1513 if (!logged_warning) {
1514 /* The keys for these services are linked to the server IP address */
1515 log_notice(LD_REND, "The configured onion service directories have been "
1516 "used in single onion mode. They can not be used for "
1517 "anonymous hidden services.");
1518 logged_warning = 1;
1522 return 0;
1525 /** Load and/or generate private keys for the hidden service <b>s</b>,
1526 * possibly including keys for client authorization. Return 0 on success, -1
1527 * on failure. */
1528 static int
1529 rend_service_load_keys(rend_service_t *s)
1531 char *fname = NULL;
1532 char buf[128];
1534 /* Create the directory if needed which will also poison it in case of
1535 * single onion service. */
1536 if (rend_service_check_private_dir(get_options(), s, 1) < 0)
1537 goto err;
1539 /* Load key */
1540 fname = rend_service_path(s, private_key_fname);
1541 s->private_key = init_key_from_file(fname, 1, LOG_ERR, NULL);
1543 if (!s->private_key)
1544 goto err;
1546 if (rend_service_derive_key_digests(s) < 0)
1547 goto err;
1549 tor_free(fname);
1550 /* Create service file */
1551 fname = rend_service_path(s, hostname_fname);
1553 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
1554 if (write_str_to_file(fname,buf,0)<0) {
1555 log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
1556 goto err;
1558 #ifndef _WIN32
1559 if (s->dir_group_readable) {
1560 /* Also verify hostname file created with group read. */
1561 if (chmod(fname, 0640))
1562 log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
1563 fname);
1565 #endif /* !defined(_WIN32) */
1567 /* If client authorization is configured, load or generate keys. */
1568 if (s->auth_type != REND_NO_AUTH) {
1569 if (rend_service_load_auth_keys(s, fname) < 0) {
1570 goto err;
1574 int r = 0;
1575 goto done;
1576 err:
1577 r = -1;
1578 done:
1579 memwipe(buf, 0, sizeof(buf));
1580 tor_free(fname);
1581 return r;
1584 /** Load and/or generate client authorization keys for the hidden service
1585 * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
1586 * -1 on failure. */
1587 static int
1588 rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
1590 int r = 0;
1591 char *cfname = NULL;
1592 char *client_keys_str = NULL;
1593 strmap_t *parsed_clients = strmap_new();
1594 FILE *cfile, *hfile;
1595 open_file_t *open_cfile = NULL, *open_hfile = NULL;
1596 char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
1597 char service_id[16+1];
1598 char buf[1500];
1600 /* Load client keys and descriptor cookies, if available. */
1601 cfname = rend_service_path(s, client_keys_fname);
1602 client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
1603 if (client_keys_str) {
1604 if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
1605 log_warn(LD_CONFIG, "Previously stored client_keys file could not "
1606 "be parsed.");
1607 goto err;
1608 } else {
1609 log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
1610 strmap_size(parsed_clients));
1614 /* Prepare client_keys and hostname files. */
1615 if (!(cfile = start_writing_to_stdio_file(cfname,
1616 OPEN_FLAGS_REPLACE | O_TEXT,
1617 0600, &open_cfile))) {
1618 log_warn(LD_CONFIG, "Could not open client_keys file %s",
1619 escaped(cfname));
1620 goto err;
1623 if (!(hfile = start_writing_to_stdio_file(hfname,
1624 OPEN_FLAGS_REPLACE | O_TEXT,
1625 0600, &open_hfile))) {
1626 log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
1627 goto err;
1630 /* Either use loaded keys for configured clients or generate new
1631 * ones if a client is new. */
1632 SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
1633 rend_authorized_client_t *parsed =
1634 strmap_get(parsed_clients, client->client_name);
1635 int written;
1636 size_t len;
1637 /* Copy descriptor cookie from parsed entry or create new one. */
1638 if (parsed) {
1639 memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
1640 REND_DESC_COOKIE_LEN);
1641 } else {
1642 crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
1644 /* For compatibility with older tor clients, this does not
1645 * truncate the padding characters, unlike rend_auth_encode_cookie. */
1646 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
1647 (char *) client->descriptor_cookie,
1648 REND_DESC_COOKIE_LEN, 0) < 0) {
1649 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1650 goto err;
1652 /* Copy client key from parsed entry or create new one if required. */
1653 if (parsed && parsed->client_key) {
1654 client->client_key = crypto_pk_dup_key(parsed->client_key);
1655 } else if (s->auth_type == REND_STEALTH_AUTH) {
1656 /* Create private key for client. */
1657 crypto_pk_t *prkey = NULL;
1658 if (!(prkey = crypto_pk_new())) {
1659 log_warn(LD_BUG,"Error constructing client key");
1660 goto err;
1662 if (crypto_pk_generate_key(prkey)) {
1663 log_warn(LD_BUG,"Error generating client key");
1664 crypto_pk_free(prkey);
1665 goto err;
1667 if (! crypto_pk_is_valid_private_key(prkey)) {
1668 log_warn(LD_BUG,"Generated client key seems invalid");
1669 crypto_pk_free(prkey);
1670 goto err;
1672 client->client_key = prkey;
1674 /* Add entry to client_keys file. */
1675 written = tor_snprintf(buf, sizeof(buf),
1676 "client-name %s\ndescriptor-cookie %s\n",
1677 client->client_name, desc_cook_out);
1678 if (written < 0) {
1679 log_warn(LD_BUG, "Could not write client entry.");
1680 goto err;
1682 if (client->client_key) {
1683 char *client_key_out = NULL;
1684 if (crypto_pk_write_private_key_to_string(client->client_key,
1685 &client_key_out, &len) != 0) {
1686 log_warn(LD_BUG, "Internal error: "
1687 "crypto_pk_write_private_key_to_string() failed.");
1688 goto err;
1690 if (rend_get_service_id(client->client_key, service_id)<0) {
1691 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1693 * len is string length, not buffer length, but last byte is NUL
1694 * anyway.
1696 memwipe(client_key_out, 0, len);
1697 tor_free(client_key_out);
1698 goto err;
1700 written = tor_snprintf(buf + written, sizeof(buf) - written,
1701 "client-key\n%s", client_key_out);
1702 memwipe(client_key_out, 0, len);
1703 tor_free(client_key_out);
1704 if (written < 0) {
1705 log_warn(LD_BUG, "Could not write client entry.");
1706 goto err;
1708 } else {
1709 strlcpy(service_id, s->service_id, sizeof(service_id));
1712 if (fputs(buf, cfile) < 0) {
1713 log_warn(LD_FS, "Could not append client entry to file: %s",
1714 strerror(errno));
1715 goto err;
1718 /* Add line to hostname file. This is not the same encoding as in
1719 * client_keys. */
1720 char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
1721 s->auth_type);
1722 if (!encoded_cookie) {
1723 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1724 goto err;
1726 tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
1727 service_id, encoded_cookie, client->client_name);
1728 memwipe(encoded_cookie, 0, strlen(encoded_cookie));
1729 tor_free(encoded_cookie);
1731 if (fputs(buf, hfile)<0) {
1732 log_warn(LD_FS, "Could not append host entry to file: %s",
1733 strerror(errno));
1734 goto err;
1736 } SMARTLIST_FOREACH_END(client);
1738 finish_writing_to_file(open_cfile);
1739 finish_writing_to_file(open_hfile);
1741 goto done;
1742 err:
1743 r = -1;
1744 if (open_cfile)
1745 abort_writing_to_file(open_cfile);
1746 if (open_hfile)
1747 abort_writing_to_file(open_hfile);
1748 done:
1749 if (client_keys_str) {
1750 memwipe(client_keys_str, 0, strlen(client_keys_str));
1751 tor_free(client_keys_str);
1753 strmap_free(parsed_clients, rend_authorized_client_free_void);
1755 if (cfname) {
1756 memwipe(cfname, 0, strlen(cfname));
1757 tor_free(cfname);
1760 /* Clear stack buffers that held key-derived material. */
1761 memwipe(buf, 0, sizeof(buf));
1762 memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
1763 memwipe(service_id, 0, sizeof(service_id));
1765 return r;
1768 /** Return the service whose public key has a digest of <b>digest</b>, or
1769 * NULL if no such service exists.
1771 static rend_service_t *
1772 rend_service_get_by_pk_digest(const char* digest)
1774 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
1775 if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
1776 return s);
1777 return NULL;
1780 /** Return the service whose service id is <b>id</b>, or NULL if no such
1781 * service exists.
1783 static struct rend_service_t *
1784 rend_service_get_by_service_id(const char *id)
1786 tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
1787 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
1788 if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
1789 return s;
1791 return NULL;
1794 /** Check client authorization of a given <b>descriptor_cookie</b> of
1795 * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
1796 * and 0 for failure. */
1797 static int
1798 rend_check_authorization(rend_service_t *service,
1799 const char *descriptor_cookie,
1800 size_t cookie_len)
1802 rend_authorized_client_t *auth_client = NULL;
1803 tor_assert(service);
1804 tor_assert(descriptor_cookie);
1805 if (!service->clients) {
1806 log_warn(LD_BUG, "Can't check authorization for a service that has no "
1807 "authorized clients configured.");
1808 return 0;
1811 if (cookie_len != REND_DESC_COOKIE_LEN) {
1812 log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
1813 "%lu bytes. Dropping cell.",
1814 (unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
1815 return 0;
1818 /* Look up client authorization by descriptor cookie. */
1819 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
1820 if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
1821 REND_DESC_COOKIE_LEN)) {
1822 auth_client = client;
1823 break;
1826 if (!auth_client) {
1827 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
1828 base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
1829 descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
1830 log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
1831 "Dropping cell!",
1832 descriptor_cookie_base64);
1833 return 0;
1836 /* Allow the request. */
1837 log_info(LD_REND, "Client %s authorized for service %s.",
1838 auth_client->client_name, service->service_id);
1839 return 1;
1842 /* Can this service make a direct connection to ei?
1843 * It must be a single onion service, and the firewall rules must allow ei. */
1844 static int
1845 rend_service_use_direct_connection(const or_options_t* options,
1846 const extend_info_t* ei)
1848 /* We'll connect directly all reachable addresses, whether preferred or not.
1849 * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
1850 * ignored, because pref_only is 0. */
1851 return (rend_service_allow_non_anonymous_connection(options) &&
1852 fascist_firewall_allows_address_addr(&ei->addr, ei->port,
1853 FIREWALL_OR_CONNECTION, 0, 0));
1856 /* Like rend_service_use_direct_connection, but to a node. */
1857 static int
1858 rend_service_use_direct_connection_node(const or_options_t* options,
1859 const node_t* node)
1861 /* We'll connect directly all reachable addresses, whether preferred or not.
1863 return (rend_service_allow_non_anonymous_connection(options) &&
1864 fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0));
1867 /******
1868 * Handle cells
1869 ******/
1871 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
1872 * rendezvous point.
1875 rend_service_receive_introduction(origin_circuit_t *circuit,
1876 const uint8_t *request,
1877 size_t request_len)
1879 /* Global status stuff */
1880 int status = 0, result;
1881 const or_options_t *options = get_options();
1882 char *err_msg = NULL;
1883 int err_msg_severity = LOG_WARN;
1884 const char *stage_descr = NULL, *rend_pk_digest;
1885 int reason = END_CIRC_REASON_TORPROTOCOL;
1886 /* Service/circuit/key stuff we can learn before parsing */
1887 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1888 rend_service_t *service = NULL;
1889 rend_intro_point_t *intro_point = NULL;
1890 crypto_pk_t *intro_key = NULL;
1891 /* Parsed cell */
1892 rend_intro_cell_t *parsed_req = NULL;
1893 /* Rendezvous point */
1894 extend_info_t *rp = NULL;
1895 /* XXX not handled yet */
1896 char buf[RELAY_PAYLOAD_SIZE];
1897 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
1898 int i;
1899 crypto_dh_t *dh = NULL;
1900 origin_circuit_t *launched = NULL;
1901 crypt_path_t *cpath = NULL;
1902 char hexcookie[9];
1903 int circ_needs_uptime;
1904 time_t now = time(NULL);
1905 time_t elapsed;
1906 int replay;
1907 ssize_t keylen;
1909 /* Do some initial validation and logging before we parse the cell */
1910 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
1911 log_warn(LD_PROTOCOL,
1912 "Got an INTRODUCE2 over a non-introduction circuit %u.",
1913 (unsigned) circuit->base_.n_circ_id);
1914 goto err;
1917 assert_circ_anonymity_ok(circuit, options);
1918 tor_assert(circuit->rend_data);
1919 /* XXX: This is version 2 specific (only one supported). */
1920 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
1922 /* We'll use this in a bazillion log messages */
1923 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1924 rend_pk_digest, REND_SERVICE_ID_LEN);
1926 /* look up service depending on circuit. */
1927 service = rend_service_get_by_pk_digest(rend_pk_digest);
1928 if (!service) {
1929 log_warn(LD_BUG,
1930 "Internal error: Got an INTRODUCE2 cell on an intro "
1931 "circ for an unrecognized service %s.",
1932 escaped(serviceid));
1933 goto err;
1936 intro_point = find_intro_point(circuit);
1937 if (intro_point == NULL) {
1938 intro_point = find_expiring_intro_point(service, circuit);
1939 if (intro_point == NULL) {
1940 log_warn(LD_BUG,
1941 "Internal error: Got an INTRODUCE2 cell on an "
1942 "intro circ (for service %s) with no corresponding "
1943 "rend_intro_point_t.",
1944 escaped(serviceid));
1945 goto err;
1949 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
1950 escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
1952 /* use intro key instead of service key. */
1953 intro_key = circuit->intro_key;
1955 tor_free(err_msg);
1956 stage_descr = NULL;
1958 stage_descr = "early parsing";
1959 /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
1960 parsed_req =
1961 rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
1962 if (!parsed_req) {
1963 goto log_error;
1964 } else if (err_msg) {
1965 log_info(LD_REND, "%s on circ %u.", err_msg,
1966 (unsigned)circuit->base_.n_circ_id);
1967 tor_free(err_msg);
1970 /* make sure service replay caches are present */
1971 if (!service->accepted_intro_dh_parts) {
1972 service->accepted_intro_dh_parts =
1973 replaycache_new(REND_REPLAY_TIME_INTERVAL,
1974 REND_REPLAY_TIME_INTERVAL);
1977 if (!intro_point->accepted_intro_rsa_parts) {
1978 intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
1981 /* check for replay of PK-encrypted portion. */
1982 keylen = crypto_pk_keysize(intro_key);
1983 replay = replaycache_add_test_and_elapsed(
1984 intro_point->accepted_intro_rsa_parts,
1985 parsed_req->ciphertext, MIN(parsed_req->ciphertext_len, keylen),
1986 &elapsed);
1988 if (replay) {
1989 log_warn(LD_REND,
1990 "Possible replay detected! We received an "
1991 "INTRODUCE2 cell with same PK-encrypted part %d "
1992 "seconds ago. Dropping cell.",
1993 (int)elapsed);
1994 goto err;
1997 stage_descr = "decryption";
1998 /* Now try to decrypt it */
1999 result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
2000 if (result < 0) {
2001 goto log_error;
2002 } else if (err_msg) {
2003 log_info(LD_REND, "%s on circ %u.", err_msg,
2004 (unsigned)circuit->base_.n_circ_id);
2005 tor_free(err_msg);
2008 stage_descr = "late parsing";
2009 /* Parse the plaintext */
2010 result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
2011 if (result < 0) {
2012 goto log_error;
2013 } else if (err_msg) {
2014 log_info(LD_REND, "%s on circ %u.", err_msg,
2015 (unsigned)circuit->base_.n_circ_id);
2016 tor_free(err_msg);
2019 stage_descr = "late validation";
2020 /* Validate the parsed plaintext parts */
2021 result = rend_service_validate_intro_late(parsed_req, &err_msg);
2022 if (result < 0) {
2023 goto log_error;
2024 } else if (err_msg) {
2025 log_info(LD_REND, "%s on circ %u.", err_msg,
2026 (unsigned)circuit->base_.n_circ_id);
2027 tor_free(err_msg);
2029 stage_descr = NULL;
2031 /* Increment INTRODUCE2 counter */
2032 ++(intro_point->accepted_introduce2_count);
2034 /* Find the rendezvous point */
2035 rp = find_rp_for_intro(parsed_req, &err_msg);
2036 if (!rp) {
2037 err_msg_severity = LOG_PROTOCOL_WARN;
2038 goto log_error;
2041 /* Check if we'd refuse to talk to this router */
2042 if (options->StrictNodes &&
2043 routerset_contains_extendinfo(options->ExcludeNodes, rp)) {
2044 log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
2045 "exclude, and StrictNodes is set. Refusing service.");
2046 reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
2047 goto err;
2050 base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
2052 /* Check whether there is a past request with the same Diffie-Hellman,
2053 * part 1. */
2054 replay = replaycache_add_test_and_elapsed(
2055 service->accepted_intro_dh_parts,
2056 parsed_req->dh, DH1024_KEY_LEN,
2057 &elapsed);
2059 if (replay) {
2060 /* A Tor client will send a new INTRODUCE1 cell with the same rend
2061 * cookie and DH public key as its previous one if its intro circ
2062 * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
2063 * If we received the first INTRODUCE1 cell (the intro-point relay
2064 * converts it into an INTRODUCE2 cell), we are already trying to
2065 * connect to that rend point (and may have already succeeded);
2066 * drop this cell. */
2067 log_info(LD_REND, "We received an "
2068 "INTRODUCE2 cell with same first part of "
2069 "Diffie-Hellman handshake %d seconds ago. Dropping "
2070 "cell.",
2071 (int) elapsed);
2072 goto err;
2075 /* If the service performs client authorization, check included auth data. */
2076 if (service->clients) {
2077 if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
2078 if (rend_check_authorization(service,
2079 (const char*)parsed_req->u.v3.auth_data,
2080 parsed_req->u.v3.auth_len)) {
2081 log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
2082 } else {
2083 log_info(LD_REND, "The authorization data that are contained in "
2084 "the INTRODUCE2 cell are invalid. Dropping cell.");
2085 reason = END_CIRC_REASON_CONNECTFAILED;
2086 goto err;
2088 } else {
2089 log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
2090 "data, but we require client authorization. Dropping cell.");
2091 reason = END_CIRC_REASON_CONNECTFAILED;
2092 goto err;
2096 /* Try DH handshake... */
2097 dh = crypto_dh_new(DH_TYPE_REND);
2098 if (!dh || crypto_dh_generate_public(dh)<0) {
2099 log_warn(LD_BUG,"Internal error: couldn't build DH state "
2100 "or generate public key.");
2101 reason = END_CIRC_REASON_INTERNAL;
2102 goto err;
2104 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
2105 (char *)(parsed_req->dh),
2106 DH1024_KEY_LEN, keys,
2107 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
2108 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
2109 reason = END_CIRC_REASON_INTERNAL;
2110 goto err;
2113 circ_needs_uptime = hs_service_requires_uptime_circ(service->ports);
2115 /* help predict this next time */
2116 rep_hist_note_used_internal(now, circ_needs_uptime, 1);
2118 /* Launch a circuit to the client's chosen rendezvous point.
2120 int max_rend_failures=hs_get_service_max_rend_failures();
2121 for (i=0;i<max_rend_failures;i++) {
2122 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
2123 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2124 /* A Single Onion Service only uses a direct connection if its
2125 * firewall rules permit direct connections to the address. */
2126 if (rend_service_use_direct_connection(options, rp)) {
2127 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
2129 launched = circuit_launch_by_extend_info(
2130 CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
2132 if (launched)
2133 break;
2135 if (!launched) { /* give up */
2136 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
2137 "point %s for service %s.",
2138 safe_str_client(extend_info_describe(rp)),
2139 serviceid);
2140 reason = END_CIRC_REASON_CONNECTFAILED;
2141 goto err;
2143 log_info(LD_REND,
2144 "Accepted intro; launching circuit to %s "
2145 "(cookie %s) for service %s.",
2146 safe_str_client(extend_info_describe(rp)),
2147 hexcookie, serviceid);
2148 tor_assert(launched->build_state);
2149 /* Fill in the circuit's state. */
2151 launched->rend_data =
2152 rend_data_service_create(service->service_id, rend_pk_digest,
2153 parsed_req->rc, service->auth_type);
2155 launched->build_state->service_pending_final_cpath_ref =
2156 tor_malloc_zero(sizeof(crypt_path_reference_t));
2157 launched->build_state->service_pending_final_cpath_ref->refcount = 1;
2159 launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
2160 tor_malloc_zero(sizeof(crypt_path_t));
2161 cpath->magic = CRYPT_PATH_MAGIC;
2162 launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
2164 cpath->rend_dh_handshake_state = dh;
2165 dh = NULL;
2166 if (circuit_init_cpath_crypto(cpath,
2167 keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
2168 1, 0)<0)
2169 goto err;
2170 memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
2172 goto done;
2174 log_error:
2175 if (!err_msg) {
2176 if (stage_descr) {
2177 tor_asprintf(&err_msg,
2178 "unknown %s error for INTRODUCE2", stage_descr);
2179 } else {
2180 err_msg = tor_strdup("unknown error for INTRODUCE2");
2184 log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
2185 (unsigned)circuit->base_.n_circ_id);
2186 err:
2187 status = -1;
2188 if (dh) crypto_dh_free(dh);
2189 if (launched) {
2190 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
2192 tor_free(err_msg);
2194 done:
2195 memwipe(keys, 0, sizeof(keys));
2196 memwipe(buf, 0, sizeof(buf));
2197 memwipe(serviceid, 0, sizeof(serviceid));
2198 memwipe(hexcookie, 0, sizeof(hexcookie));
2200 /* Free the parsed cell */
2201 rend_service_free_intro(parsed_req);
2203 /* Free rp */
2204 extend_info_free(rp);
2206 return status;
2209 /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
2210 * return NULL and an error string if we can't. Return a newly allocated
2211 * extend_info_t* for the rendezvous point. */
2212 static extend_info_t *
2213 find_rp_for_intro(const rend_intro_cell_t *intro,
2214 char **err_msg_out)
2216 extend_info_t *rp = NULL;
2217 char *err_msg = NULL;
2218 const char *rp_nickname = NULL;
2219 const node_t *node = NULL;
2221 if (!intro) {
2222 if (err_msg_out)
2223 err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
2225 goto err;
2228 if (intro->version == 0 || intro->version == 1) {
2229 rp_nickname = (const char *)(intro->u.v0_v1.rp);
2231 node = node_get_by_nickname(rp_nickname, NNF_NO_WARN_UNNAMED);
2232 if (!node) {
2233 if (err_msg_out) {
2234 tor_asprintf(&err_msg,
2235 "Couldn't find router %s named in INTRODUCE2 cell",
2236 escaped_safe_str_client(rp_nickname));
2239 goto err;
2242 /* Are we in single onion mode? */
2243 const int allow_direct = rend_service_allow_non_anonymous_connection(
2244 get_options());
2245 rp = extend_info_from_node(node, allow_direct);
2246 if (!rp) {
2247 if (err_msg_out) {
2248 tor_asprintf(&err_msg,
2249 "Couldn't build extend_info_t for router %s named "
2250 "in INTRODUCE2 cell",
2251 escaped_safe_str_client(rp_nickname));
2254 goto err;
2256 } else if (intro->version == 2) {
2257 rp = extend_info_dup(intro->u.v2.extend_info);
2258 } else if (intro->version == 3) {
2259 rp = extend_info_dup(intro->u.v3.extend_info);
2260 } else {
2261 if (err_msg_out) {
2262 tor_asprintf(&err_msg,
2263 "Unknown version %d in INTRODUCE2 cell",
2264 (int)(intro->version));
2267 goto err;
2270 /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2271 * the other cases goto err. */
2272 tor_assert(rp);
2274 /* Make sure the RP we are being asked to connect to is _not_ a private
2275 * address unless it's allowed. Let's avoid to build a circuit to our
2276 * second middle node and fail right after when extending to the RP. */
2277 if (!extend_info_addr_is_allowed(&rp->addr)) {
2278 if (err_msg_out) {
2279 tor_asprintf(&err_msg,
2280 "Relay IP in INTRODUCE2 cell is private address.");
2282 extend_info_free(rp);
2283 rp = NULL;
2284 goto err;
2286 goto done;
2288 err:
2289 if (err_msg_out)
2290 *err_msg_out = err_msg;
2291 else
2292 tor_free(err_msg);
2294 done:
2295 return rp;
2298 /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
2299 * rend_service_parse_intro().
2301 void
2302 rend_service_free_intro_(rend_intro_cell_t *request)
2304 if (!request) {
2305 return;
2308 /* Free ciphertext */
2309 tor_free(request->ciphertext);
2310 request->ciphertext_len = 0;
2312 /* Have plaintext? */
2313 if (request->plaintext) {
2314 /* Zero it out just to be safe */
2315 memwipe(request->plaintext, 0, request->plaintext_len);
2316 tor_free(request->plaintext);
2317 request->plaintext_len = 0;
2320 /* Have parsed plaintext? */
2321 if (request->parsed) {
2322 switch (request->version) {
2323 case 0:
2324 case 1:
2326 * Nothing more to do; these formats have no further pointers
2327 * in them.
2329 break;
2330 case 2:
2331 extend_info_free(request->u.v2.extend_info);
2332 request->u.v2.extend_info = NULL;
2333 break;
2334 case 3:
2335 if (request->u.v3.auth_data) {
2336 memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
2337 tor_free(request->u.v3.auth_data);
2340 extend_info_free(request->u.v3.extend_info);
2341 request->u.v3.extend_info = NULL;
2342 break;
2343 default:
2344 log_info(LD_BUG,
2345 "rend_service_free_intro() saw unknown protocol "
2346 "version %d.",
2347 request->version);
2351 /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2352 memwipe(request, 0, sizeof(*request));
2354 tor_free(request);
2357 /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
2358 * rend_intro_cell_t structure. Free it with rend_service_free_intro()
2359 * when finished. The type parameter should be 1 or 2 to indicate whether
2360 * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
2361 * parts; after this, call rend_service_decrypt_intro() with a key, then
2362 * rend_service_parse_intro_plaintext() to finish parsing. The optional
2363 * err_msg_out parameter is set to a string suitable for log output
2364 * if parsing fails. This function does some validation, but only
2365 * that which depends solely on the contents of the cell and the
2366 * key; it can be unit-tested. Further validation is done in
2367 * rend_service_validate_intro().
2370 rend_intro_cell_t *
2371 rend_service_begin_parse_intro(const uint8_t *request,
2372 size_t request_len,
2373 uint8_t type,
2374 char **err_msg_out)
2376 rend_intro_cell_t *rv = NULL;
2377 char *err_msg = NULL;
2379 if (!request || request_len <= 0) goto err;
2380 if (!(type == 1 || type == 2)) goto err;
2382 /* First, check that the cell is long enough to be a sensible INTRODUCE */
2384 /* min key length plus digest length plus nickname length */
2385 if (request_len <
2386 (DIGEST_LEN + REND_COOKIE_LEN + (MAX_NICKNAME_LEN + 1) +
2387 DH1024_KEY_LEN + 42)) {
2388 if (err_msg_out) {
2389 tor_asprintf(&err_msg,
2390 "got a truncated INTRODUCE%d cell",
2391 (int)type);
2393 goto err;
2396 /* Allocate a new parsed cell structure */
2397 rv = tor_malloc_zero(sizeof(*rv));
2399 /* Set the type */
2400 rv->type = type;
2402 /* Copy in the ID */
2403 memcpy(rv->pk, request, DIGEST_LEN);
2405 /* Copy in the ciphertext */
2406 rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
2407 memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
2408 rv->ciphertext_len = request_len - DIGEST_LEN;
2410 goto done;
2412 err:
2413 rend_service_free_intro(rv);
2414 rv = NULL;
2416 if (err_msg_out && !err_msg) {
2417 tor_asprintf(&err_msg,
2418 "unknown INTRODUCE%d error",
2419 (int)type);
2422 done:
2423 if (err_msg_out) *err_msg_out = err_msg;
2424 else tor_free(err_msg);
2426 return rv;
2429 /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
2430 * cell
2433 static ssize_t
2434 rend_service_parse_intro_for_v0_or_v1(
2435 rend_intro_cell_t *intro,
2436 const uint8_t *buf,
2437 size_t plaintext_len,
2438 char **err_msg_out)
2440 const char *rp_nickname, *endptr;
2441 size_t nickname_field_len, ver_specific_len;
2443 if (intro->version == 1) {
2444 ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
2445 rp_nickname = ((const char *)buf) + 1;
2446 nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
2447 } else if (intro->version == 0) {
2448 ver_specific_len = MAX_NICKNAME_LEN + 1;
2449 rp_nickname = (const char *)buf;
2450 nickname_field_len = MAX_NICKNAME_LEN + 1;
2451 } else {
2452 if (err_msg_out)
2453 tor_asprintf(err_msg_out,
2454 "rend_service_parse_intro_for_v0_or_v1() called with "
2455 "bad version %d on INTRODUCE%d cell (this is a bug)",
2456 intro->version,
2457 (int)(intro->type));
2458 goto err;
2461 if (plaintext_len < ver_specific_len) {
2462 if (err_msg_out)
2463 tor_asprintf(err_msg_out,
2464 "short plaintext of encrypted part in v1 INTRODUCE%d "
2465 "cell (%lu bytes, needed %lu)",
2466 (int)(intro->type),
2467 (unsigned long)plaintext_len,
2468 (unsigned long)ver_specific_len);
2469 goto err;
2472 endptr = memchr(rp_nickname, 0, nickname_field_len);
2473 if (!endptr || endptr == rp_nickname) {
2474 if (err_msg_out) {
2475 tor_asprintf(err_msg_out,
2476 "couldn't find a nul-padded nickname in "
2477 "INTRODUCE%d cell",
2478 (int)(intro->type));
2480 goto err;
2483 if ((intro->version == 0 &&
2484 !is_legal_nickname(rp_nickname)) ||
2485 (intro->version == 1 &&
2486 !is_legal_nickname_or_hexdigest(rp_nickname))) {
2487 if (err_msg_out) {
2488 tor_asprintf(err_msg_out,
2489 "bad nickname in INTRODUCE%d cell",
2490 (int)(intro->type));
2492 goto err;
2495 memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
2497 return ver_specific_len;
2499 err:
2500 return -1;
2503 /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
2506 static ssize_t
2507 rend_service_parse_intro_for_v2(
2508 rend_intro_cell_t *intro,
2509 const uint8_t *buf,
2510 size_t plaintext_len,
2511 char **err_msg_out)
2513 unsigned int klen;
2514 extend_info_t *extend_info = NULL;
2515 ssize_t ver_specific_len;
2518 * We accept version 3 too so that the v3 parser can call this with
2519 * an adjusted buffer for the latter part of a v3 cell, which is
2520 * identical to a v2 cell.
2522 if (!(intro->version == 2 ||
2523 intro->version == 3)) {
2524 if (err_msg_out)
2525 tor_asprintf(err_msg_out,
2526 "rend_service_parse_intro_for_v2() called with "
2527 "bad version %d on INTRODUCE%d cell (this is a bug)",
2528 intro->version,
2529 (int)(intro->type));
2530 goto err;
2533 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2534 if (plaintext_len < 7 + DIGEST_LEN + 2) {
2535 if (err_msg_out) {
2536 tor_asprintf(err_msg_out,
2537 "truncated plaintext of encrypted parted of "
2538 "version %d INTRODUCE%d cell",
2539 intro->version,
2540 (int)(intro->type));
2543 goto err;
2546 extend_info = tor_malloc_zero(sizeof(extend_info_t));
2547 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
2548 extend_info->port = ntohs(get_uint16(buf + 5));
2549 memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
2550 extend_info->nickname[0] = '$';
2551 base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
2552 extend_info->identity_digest, DIGEST_LEN);
2553 klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
2555 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2556 if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
2557 if (err_msg_out) {
2558 tor_asprintf(err_msg_out,
2559 "truncated plaintext of encrypted parted of "
2560 "version %d INTRODUCE%d cell",
2561 intro->version,
2562 (int)(intro->type));
2565 goto err;
2568 extend_info->onion_key =
2569 crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
2570 if (!extend_info->onion_key) {
2571 if (err_msg_out) {
2572 tor_asprintf(err_msg_out,
2573 "error decoding onion key in version %d "
2574 "INTRODUCE%d cell",
2575 intro->version,
2576 (intro->type));
2579 goto err;
2581 if (128 != crypto_pk_keysize(extend_info->onion_key)) {
2582 if (err_msg_out) {
2583 tor_asprintf(err_msg_out,
2584 "invalid onion key size in version %d INTRODUCE%d cell",
2585 intro->version,
2586 (intro->type));
2589 goto err;
2592 ver_specific_len = 7+DIGEST_LEN+2+klen;
2594 if (intro->version == 2) intro->u.v2.extend_info = extend_info;
2595 else intro->u.v3.extend_info = extend_info;
2597 return ver_specific_len;
2599 err:
2600 extend_info_free(extend_info);
2602 return -1;
2605 /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
2608 static ssize_t
2609 rend_service_parse_intro_for_v3(
2610 rend_intro_cell_t *intro,
2611 const uint8_t *buf,
2612 size_t plaintext_len,
2613 char **err_msg_out)
2615 ssize_t adjust, v2_ver_specific_len, ts_offset;
2617 /* This should only be called on v3 cells */
2618 if (intro->version != 3) {
2619 if (err_msg_out)
2620 tor_asprintf(err_msg_out,
2621 "rend_service_parse_intro_for_v3() called with "
2622 "bad version %d on INTRODUCE%d cell (this is a bug)",
2623 intro->version,
2624 (int)(intro->type));
2625 goto err;
2629 * Check that we have at least enough to get auth_len:
2631 * 1 octet for version, 1 for auth_type, 2 for auth_len
2633 if (plaintext_len < 4) {
2634 if (err_msg_out) {
2635 tor_asprintf(err_msg_out,
2636 "truncated plaintext of encrypted parted of "
2637 "version %d INTRODUCE%d cell",
2638 intro->version,
2639 (int)(intro->type));
2642 goto err;
2646 * The rend_client_send_introduction() function over in rendclient.c is
2647 * broken (i.e., fails to match the spec) in such a way that we can't
2648 * change it without breaking the protocol. Specifically, it doesn't
2649 * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2650 * by two bytes after that. Calculate ts_offset and do everything from
2651 * the timestamp on relative to that to handle this dain bramage.
2654 intro->u.v3.auth_type = buf[1];
2655 if (intro->u.v3.auth_type != REND_NO_AUTH) {
2656 intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
2657 ts_offset = 4 + intro->u.v3.auth_len;
2658 } else {
2659 intro->u.v3.auth_len = 0;
2660 ts_offset = 2;
2663 /* Check that auth len makes sense for this auth type */
2664 if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
2665 intro->u.v3.auth_type == REND_STEALTH_AUTH) {
2666 if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
2667 if (err_msg_out) {
2668 tor_asprintf(err_msg_out,
2669 "wrong auth data size %d for INTRODUCE%d cell, "
2670 "should be %d",
2671 (int)(intro->u.v3.auth_len),
2672 (int)(intro->type),
2673 REND_DESC_COOKIE_LEN);
2676 goto err;
2680 /* Check that we actually have everything up through the timestamp */
2681 if (plaintext_len < (size_t)(ts_offset)+4) {
2682 if (err_msg_out) {
2683 tor_asprintf(err_msg_out,
2684 "truncated plaintext of encrypted parted of "
2685 "version %d INTRODUCE%d cell",
2686 intro->version,
2687 (int)(intro->type));
2690 goto err;
2693 if (intro->u.v3.auth_type != REND_NO_AUTH &&
2694 intro->u.v3.auth_len > 0) {
2695 /* Okay, we can go ahead and copy auth_data */
2696 intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
2698 * We know we had an auth_len field in this case, so 4 is
2699 * always right.
2701 memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
2705 * From here on, the format is as in v2, so we call the v2 parser with
2706 * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2707 * v2 parser expects to skip over a version byte at the start, so we
2708 * adjust by 3 + ts_offset.
2710 adjust = 3 + ts_offset;
2712 v2_ver_specific_len =
2713 rend_service_parse_intro_for_v2(intro,
2714 buf + adjust, plaintext_len - adjust,
2715 err_msg_out);
2717 /* Success in v2 parser */
2718 if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
2719 /* Failure in v2 parser; it will have provided an err_msg */
2720 else return v2_ver_specific_len;
2722 err:
2723 return -1;
2726 /** Table of parser functions for version-specific parts of an INTRODUCE2
2727 * cell.
2730 static ssize_t
2731 (*intro_version_handlers[])(
2732 rend_intro_cell_t *,
2733 const uint8_t *,
2734 size_t,
2735 char **) =
2736 { rend_service_parse_intro_for_v0_or_v1,
2737 rend_service_parse_intro_for_v0_or_v1,
2738 rend_service_parse_intro_for_v2,
2739 rend_service_parse_intro_for_v3 };
2741 /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
2742 * return 0 if successful, or < 0 and write an error message to
2743 * *err_msg_out if provided.
2747 rend_service_decrypt_intro(
2748 rend_intro_cell_t *intro,
2749 crypto_pk_t *key,
2750 char **err_msg_out)
2752 char *err_msg = NULL;
2753 uint8_t key_digest[DIGEST_LEN];
2754 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
2755 ssize_t key_len;
2756 uint8_t buf[RELAY_PAYLOAD_SIZE];
2757 int result, status = -1;
2759 if (!intro || !key) {
2760 if (err_msg_out) {
2761 err_msg =
2762 tor_strdup("rend_service_decrypt_intro() called with bad "
2763 "parameters");
2766 status = -2;
2767 goto err;
2770 /* Make sure we have ciphertext */
2771 if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
2772 if (err_msg_out) {
2773 tor_asprintf(&err_msg,
2774 "rend_intro_cell_t was missing ciphertext for "
2775 "INTRODUCE%d cell",
2776 (int)(intro->type));
2778 status = -3;
2779 goto err;
2782 /* Check that this cell actually matches this service key */
2784 /* first DIGEST_LEN bytes of request is intro or service pk digest */
2785 if (crypto_pk_get_digest(key, (char *)key_digest) < 0) {
2786 if (err_msg_out)
2787 *err_msg_out = tor_strdup("Couldn't compute RSA digest.");
2788 log_warn(LD_BUG, "Couldn't compute key digest.");
2789 status = -7;
2790 goto err;
2793 if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
2794 if (err_msg_out) {
2795 base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
2796 (char*)(intro->pk), REND_SERVICE_ID_LEN);
2797 tor_asprintf(&err_msg,
2798 "got an INTRODUCE%d cell for the wrong service (%s)",
2799 (int)(intro->type),
2800 escaped(service_id));
2803 status = -4;
2804 goto err;
2807 /* Make sure the encrypted part is long enough to decrypt */
2809 key_len = crypto_pk_keysize(key);
2810 if (intro->ciphertext_len < key_len) {
2811 if (err_msg_out) {
2812 tor_asprintf(&err_msg,
2813 "got an INTRODUCE%d cell with a truncated PK-encrypted "
2814 "part",
2815 (int)(intro->type));
2818 status = -5;
2819 goto err;
2822 /* Decrypt the encrypted part */
2823 result =
2824 crypto_pk_obsolete_private_hybrid_decrypt(
2825 key, (char *)buf, sizeof(buf),
2826 (const char *)(intro->ciphertext), intro->ciphertext_len,
2827 PK_PKCS1_OAEP_PADDING, 1);
2828 if (result < 0) {
2829 if (err_msg_out) {
2830 tor_asprintf(&err_msg,
2831 "couldn't decrypt INTRODUCE%d cell",
2832 (int)(intro->type));
2834 status = -6;
2835 goto err;
2837 intro->plaintext_len = result;
2838 intro->plaintext = tor_malloc(intro->plaintext_len);
2839 memcpy(intro->plaintext, buf, intro->plaintext_len);
2841 status = 0;
2843 goto done;
2845 err:
2846 if (err_msg_out && !err_msg) {
2847 tor_asprintf(&err_msg,
2848 "unknown INTRODUCE%d error decrypting encrypted part",
2849 intro ? (int)(intro->type) : -1);
2852 done:
2853 if (err_msg_out) *err_msg_out = err_msg;
2854 else tor_free(err_msg);
2856 /* clean up potentially sensitive material */
2857 memwipe(buf, 0, sizeof(buf));
2858 memwipe(key_digest, 0, sizeof(key_digest));
2859 memwipe(service_id, 0, sizeof(service_id));
2861 return status;
2864 /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
2865 * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
2866 * message to *err_msg_out if provided.
2870 rend_service_parse_intro_plaintext(
2871 rend_intro_cell_t *intro,
2872 char **err_msg_out)
2874 char *err_msg = NULL;
2875 ssize_t ver_specific_len, ver_invariant_len;
2876 uint8_t version;
2877 int status = -1;
2879 if (!intro) {
2880 if (err_msg_out) {
2881 err_msg =
2882 tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2883 "rend_intro_cell_t");
2886 status = -2;
2887 goto err;
2890 /* Check that we have plaintext */
2891 if (!(intro->plaintext) || intro->plaintext_len <= 0) {
2892 if (err_msg_out) {
2893 err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
2895 status = -3;
2896 goto err;
2899 /* In all formats except v0, the first byte is a version number */
2900 version = intro->plaintext[0];
2902 /* v0 has no version byte (stupid...), so handle it as a fallback */
2903 if (version > 3) version = 0;
2905 /* Copy the version into the parsed cell structure */
2906 intro->version = version;
2908 /* Call the version-specific parser from the table */
2909 ver_specific_len =
2910 intro_version_handlers[version](intro,
2911 intro->plaintext, intro->plaintext_len,
2912 &err_msg);
2913 if (ver_specific_len < 0) {
2914 status = -4;
2915 goto err;
2918 /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
2919 * and at the end of the plaintext of the encrypted part of the cell.
2922 ver_invariant_len = intro->plaintext_len - ver_specific_len;
2923 if (ver_invariant_len < REND_COOKIE_LEN + DH1024_KEY_LEN) {
2924 tor_asprintf(&err_msg,
2925 "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2926 (int)(intro->type),
2927 (long)(intro->plaintext_len));
2928 status = -5;
2929 goto err;
2930 } else if (ver_invariant_len > REND_COOKIE_LEN + DH1024_KEY_LEN) {
2931 tor_asprintf(&err_msg,
2932 "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2933 (int)(intro->type),
2934 (long)(intro->plaintext_len));
2935 status = -6;
2936 goto err;
2937 } else {
2938 memcpy(intro->rc,
2939 intro->plaintext + ver_specific_len,
2940 REND_COOKIE_LEN);
2941 memcpy(intro->dh,
2942 intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
2943 DH1024_KEY_LEN);
2946 /* Flag it as being fully parsed */
2947 intro->parsed = 1;
2949 status = 0;
2950 goto done;
2952 err:
2953 if (err_msg_out && !err_msg) {
2954 tor_asprintf(&err_msg,
2955 "unknown INTRODUCE%d error parsing encrypted part",
2956 intro ? (int)(intro->type) : -1);
2959 done:
2960 if (err_msg_out) *err_msg_out = err_msg;
2961 else tor_free(err_msg);
2963 return status;
2966 /** Do validity checks on a parsed intro cell after decryption; some of
2967 * these are not done in rend_service_parse_intro_plaintext() itself because
2968 * they depend on a lot of other state and would make it hard to unit test.
2969 * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
2970 * optionally writes out an error message for logging. If an err_msg
2971 * pointer is provided, it is the caller's responsibility to free any
2972 * provided message.
2976 rend_service_validate_intro_late(const rend_intro_cell_t *intro,
2977 char **err_msg_out)
2979 int status = 0;
2981 if (!intro) {
2982 if (err_msg_out)
2983 *err_msg_out =
2984 tor_strdup("NULL intro cell passed to "
2985 "rend_service_validate_intro_late()");
2987 status = -1;
2988 goto err;
2991 if (intro->version == 3 && intro->parsed) {
2992 if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
2993 intro->u.v3.auth_type == REND_BASIC_AUTH ||
2994 intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
2995 /* This is an informative message, not an error, as in the old code */
2996 if (err_msg_out)
2997 tor_asprintf(err_msg_out,
2998 "unknown authorization type %d",
2999 intro->u.v3.auth_type);
3003 err:
3004 return status;
3007 /** Called when we fail building a rendezvous circuit at some point other
3008 * than the last hop: launches a new circuit to the same rendezvous point.
3010 void
3011 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
3013 origin_circuit_t *newcirc;
3014 cpath_build_state_t *newstate, *oldstate;
3016 tor_assert(oldcirc->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
3017 oldstate = oldcirc->build_state;
3018 tor_assert(oldstate);
3020 if (oldstate->service_pending_final_cpath_ref == NULL) {
3021 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
3022 "Initiator will retry.");
3023 return;
3026 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
3027 safe_str(extend_info_describe(oldstate->chosen_exit)));
3029 /* You'd think Single Onion Services would want to retry the rendezvous
3030 * using a direct connection. But if it's blocked by a firewall, or the
3031 * service is IPv6-only, or the rend point avoiding becoming a one-hop
3032 * proxy, we need a 3-hop connection. */
3033 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
3034 oldstate->chosen_exit,
3035 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
3037 if (!newcirc) {
3038 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
3039 safe_str(extend_info_describe(oldstate->chosen_exit)));
3040 return;
3042 newstate = newcirc->build_state;
3043 tor_assert(newstate);
3044 newstate->failure_count = oldstate->failure_count+1;
3045 newstate->expiry_time = oldstate->expiry_time;
3046 newstate->service_pending_final_cpath_ref =
3047 oldstate->service_pending_final_cpath_ref;
3048 ++(newstate->service_pending_final_cpath_ref->refcount);
3050 newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
3053 /** Launch a circuit to serve as an introduction point for the service
3054 * <b>service</b> at the introduction point <b>nickname</b>
3056 static int
3057 rend_service_launch_establish_intro(rend_service_t *service,
3058 rend_intro_point_t *intro)
3060 origin_circuit_t *launched;
3061 int flags = CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL;
3062 const or_options_t *options = get_options();
3063 extend_info_t *launch_ei = intro->extend_info;
3064 extend_info_t *direct_ei = NULL;
3066 /* Are we in single onion mode? */
3067 if (rend_service_allow_non_anonymous_connection(options)) {
3068 /* Do we have a descriptor for the node?
3069 * We've either just chosen it from the consensus, or we've just reviewed
3070 * our intro points to see which ones are still valid, and deleted the ones
3071 * that aren't in the consensus any more. */
3072 const node_t *node = node_get_by_id(launch_ei->identity_digest);
3073 if (BUG(!node)) {
3074 /* The service has kept an intro point after it went missing from the
3075 * consensus. If we did anything else here, it would be a consensus
3076 * distinguisher. Which are less of an issue for single onion services,
3077 * but still a bug. */
3078 return -1;
3080 /* Can we connect to the node directly? If so, replace launch_ei
3081 * (a multi-hop extend_info) with one suitable for direct connection. */
3082 if (rend_service_use_direct_connection_node(options, node)) {
3083 direct_ei = extend_info_from_node(node, 1);
3084 if (BUG(!direct_ei)) {
3085 /* rend_service_use_direct_connection_node and extend_info_from_node
3086 * disagree about which addresses on this node are permitted. This
3087 * should never happen. Avoiding the connection is a safe response. */
3088 return -1;
3090 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
3091 launch_ei = direct_ei;
3094 /* launch_ei is either intro->extend_info, or has been replaced with a valid
3095 * extend_info for single onion service direct connection. */
3096 tor_assert(launch_ei);
3097 /* We must have the same intro when making a direct connection. */
3098 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3099 launch_ei->identity_digest,
3100 DIGEST_LEN));
3102 log_info(LD_REND,
3103 "Launching circuit to introduction point %s%s%s for service %s",
3104 safe_str_client(extend_info_describe(intro->extend_info)),
3105 direct_ei ? " via direct address " : "",
3106 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
3107 service->service_id);
3109 rep_hist_note_used_internal(time(NULL), 1, 0);
3111 ++service->n_intro_circuits_launched;
3112 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
3113 launch_ei, flags);
3115 if (!launched) {
3116 log_info(LD_REND,
3117 "Can't launch circuit to establish introduction at %s%s%s.",
3118 safe_str_client(extend_info_describe(intro->extend_info)),
3119 direct_ei ? " via direct address " : "",
3120 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
3122 extend_info_free(direct_ei);
3123 return -1;
3125 /* We must have the same exit node even if cannibalized or direct connection.
3127 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3128 launched->build_state->chosen_exit->identity_digest,
3129 DIGEST_LEN));
3131 launched->rend_data = rend_data_service_create(service->service_id,
3132 service->pk_digest, NULL,
3133 service->auth_type);
3134 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
3135 if (launched->base_.state == CIRCUIT_STATE_OPEN)
3136 rend_service_intro_has_opened(launched);
3137 extend_info_free(direct_ei);
3138 return 0;
3141 /** Return the number of introduction points that are established for the
3142 * given service. */
3143 static unsigned int
3144 count_established_intro_points(const rend_service_t *service)
3146 unsigned int num = 0;
3148 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
3149 num += intro->circuit_established
3151 return num;
3154 /** Return the number of introduction points that are or are being
3155 * established for the given service. This function iterates over all
3156 * circuit and count those that are linked to the service and are waiting
3157 * for the intro point to respond. */
3158 static unsigned int
3159 count_intro_point_circuits(const rend_service_t *service)
3161 unsigned int num_ipos = 0;
3162 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
3163 if (!circ->marked_for_close &&
3164 circ->state == CIRCUIT_STATE_OPEN &&
3165 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3166 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
3167 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
3168 if (oc->rend_data &&
3169 rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
3170 num_ipos++;
3174 SMARTLIST_FOREACH_END(circ);
3175 return num_ipos;
3178 /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
3179 write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
3180 as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
3181 crypto material. On success, fill <b>cell_body_out</b> and return the number
3182 of bytes written. On fail, return -1.
3184 ssize_t
3185 rend_service_encode_establish_intro_cell(char *cell_body_out,
3186 size_t cell_body_out_len,
3187 crypto_pk_t *intro_key,
3188 const char *rend_circ_nonce)
3190 int retval = -1;
3191 int r;
3192 int len = 0;
3193 char auth[DIGEST_LEN + 9];
3195 tor_assert(intro_key);
3196 tor_assert(rend_circ_nonce);
3198 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3199 r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
3200 RELAY_PAYLOAD_SIZE-2);
3201 if (r < 0) {
3202 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
3203 goto err;
3205 len = r;
3206 set_uint16(cell_body_out, htons((uint16_t)len));
3207 len += 2;
3208 memcpy(auth, rend_circ_nonce, DIGEST_LEN);
3209 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
3210 if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
3211 goto err;
3212 len += 20;
3213 r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
3214 cell_body_out_len - len,
3215 cell_body_out, len);
3216 if (r<0) {
3217 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
3218 goto err;
3220 len += r;
3222 retval = len;
3224 err:
3225 memwipe(auth, 0, sizeof(auth));
3227 return retval;
3230 /** Called when we're done building a circuit to an introduction point:
3231 * sends a RELAY_ESTABLISH_INTRO cell.
3233 void
3234 rend_service_intro_has_opened(origin_circuit_t *circuit)
3236 rend_service_t *service;
3237 char buf[RELAY_PAYLOAD_SIZE];
3238 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3239 unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0;
3240 int reason = END_CIRC_REASON_TORPROTOCOL;
3241 const char *rend_pk_digest;
3243 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
3244 assert_circ_anonymity_ok(circuit, get_options());
3245 tor_assert(circuit->cpath);
3246 tor_assert(circuit->rend_data);
3247 /* XXX: This is version 2 specific (only on supported). */
3248 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3250 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3251 rend_pk_digest, REND_SERVICE_ID_LEN);
3253 service = rend_service_get_by_pk_digest(rend_pk_digest);
3254 if (!service) {
3255 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
3256 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3257 reason = END_CIRC_REASON_NOSUCHSERVICE;
3258 goto err;
3261 /* Take the current amount of expiring nodes and the current amount of IP
3262 * circuits and compute how many valid IP circuits we have. */
3263 expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes);
3264 num_ip_circuits = count_intro_point_circuits(service);
3265 /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
3266 * case this condition turns out false because it means that all circuits
3267 * are expiring so we need to keep this circuit. */
3268 if (num_ip_circuits > expiring_nodes_len) {
3269 valid_ip_circuits = num_ip_circuits - expiring_nodes_len;
3272 /* If we already have enough introduction circuits for this service,
3273 * redefine this one as a general circuit or close it, depending.
3274 * Subtract the amount of expiring nodes here because the circuits are
3275 * still opened. */
3276 if (valid_ip_circuits > service->n_intro_points_wanted) {
3277 const or_options_t *options = get_options();
3278 /* Remove the intro point associated with this circuit, it's being
3279 * repurposed or closed thus cleanup memory. */
3280 rend_intro_point_t *intro = find_intro_point(circuit);
3281 if (intro != NULL) {
3282 smartlist_remove(service->intro_nodes, intro);
3283 rend_intro_point_free(intro);
3286 if (options->ExcludeNodes) {
3287 /* XXXX in some future version, we can test whether the transition is
3288 allowed or not given the actual nodes in the circuit. But for now,
3289 this case, we might as well close the thing. */
3290 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3291 "circuit, but we already have enough. Closing it.");
3292 reason = END_CIRC_REASON_NONE;
3293 goto err;
3294 } else {
3295 tor_assert(circuit->build_state->is_internal);
3296 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3297 "circuit, but we already have enough. Redefining purpose to "
3298 "general; leaving as internal.");
3300 if (circuit_should_use_vanguards(TO_CIRCUIT(circuit)->purpose)) {
3301 circuit_change_purpose(TO_CIRCUIT(circuit),
3302 CIRCUIT_PURPOSE_HS_VANGUARDS);
3303 } else {
3304 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
3308 rend_data_free(circuit->rend_data);
3309 circuit->rend_data = NULL;
3312 crypto_pk_t *intro_key = circuit->intro_key;
3313 circuit->intro_key = NULL;
3314 crypto_pk_free(intro_key);
3317 circuit_has_opened(circuit);
3318 goto done;
3322 log_info(LD_REND,
3323 "Established circuit %u as introduction point for service %s",
3324 (unsigned)circuit->base_.n_circ_id, serviceid);
3325 circuit_log_path(LOG_INFO, LD_REND, circuit);
3327 /* Send the ESTABLISH_INTRO cell */
3329 ssize_t len;
3330 len = rend_service_encode_establish_intro_cell(buf, sizeof(buf),
3331 circuit->intro_key,
3332 circuit->cpath->prev->rend_circ_nonce);
3333 if (len < 0) {
3334 reason = END_CIRC_REASON_INTERNAL;
3335 goto err;
3338 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3339 RELAY_COMMAND_ESTABLISH_INTRO,
3340 buf, len, circuit->cpath->prev)<0) {
3341 log_info(LD_GENERAL,
3342 "Couldn't send introduction request for service %s on circuit %u",
3343 serviceid, (unsigned)circuit->base_.n_circ_id);
3344 goto done;
3348 /* We've attempted to use this circuit */
3349 pathbias_count_use_attempt(circuit);
3351 goto done;
3353 err:
3354 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3355 done:
3356 memwipe(buf, 0, sizeof(buf));
3357 memwipe(serviceid, 0, sizeof(serviceid));
3359 return;
3362 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
3363 * live introduction point, and note that the service descriptor is
3364 * now out-of-date. */
3366 rend_service_intro_established(origin_circuit_t *circuit,
3367 const uint8_t *request,
3368 size_t request_len)
3370 rend_service_t *service;
3371 rend_intro_point_t *intro;
3372 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3373 (void) request;
3374 (void) request_len;
3375 tor_assert(circuit->rend_data);
3376 /* XXX: This is version 2 specific (only supported one for now). */
3377 const char *rend_pk_digest =
3378 (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3380 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
3381 log_warn(LD_PROTOCOL,
3382 "received INTRO_ESTABLISHED cell on non-intro circuit.");
3383 goto err;
3385 service = rend_service_get_by_pk_digest(rend_pk_digest);
3386 if (!service) {
3387 log_warn(LD_REND, "Unknown service on introduction circuit %u.",
3388 (unsigned)circuit->base_.n_circ_id);
3389 goto err;
3391 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
3392 rend_pk_digest, REND_SERVICE_ID_LEN);
3393 /* We've just successfully established a intro circuit to one of our
3394 * introduction point, account for it. */
3395 intro = find_intro_point(circuit);
3396 if (intro == NULL) {
3397 log_warn(LD_REND,
3398 "Introduction circuit established without a rend_intro_point_t "
3399 "object for service %s on circuit %u",
3400 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3401 goto err;
3403 intro->circuit_established = 1;
3404 /* We might not have every introduction point ready but at this point we
3405 * know that the descriptor needs to be uploaded. */
3406 service->desc_is_dirty = time(NULL);
3407 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
3409 log_info(LD_REND,
3410 "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3411 (unsigned)circuit->base_.n_circ_id, serviceid);
3413 /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3414 * used the circ */
3415 pathbias_mark_use_success(circuit);
3417 return 0;
3418 err:
3419 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
3420 return -1;
3423 /** Called once a circuit to a rendezvous point is established: sends a
3424 * RELAY_COMMAND_RENDEZVOUS1 cell.
3426 void
3427 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
3429 rend_service_t *service;
3430 char buf[RELAY_PAYLOAD_SIZE];
3431 crypt_path_t *hop;
3432 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3433 char hexcookie[9];
3434 int reason;
3435 const char *rend_cookie, *rend_pk_digest;
3437 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
3438 tor_assert(circuit->cpath);
3439 tor_assert(circuit->build_state);
3440 assert_circ_anonymity_ok(circuit, get_options());
3441 tor_assert(circuit->rend_data);
3443 /* XXX: This is version 2 specific (only one supported). */
3444 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
3445 NULL);
3446 rend_cookie = circuit->rend_data->rend_cookie;
3448 /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
3449 * timestamp regardless of its content because that circuit could have been
3450 * cannibalized so in any cases, we are about to use that circuit more. */
3451 circuit->base_.timestamp_dirty = time(NULL);
3453 /* This may be redundant */
3454 pathbias_count_use_attempt(circuit);
3456 hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
3458 base16_encode(hexcookie,9, rend_cookie,4);
3459 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3460 rend_pk_digest, REND_SERVICE_ID_LEN);
3462 log_info(LD_REND,
3463 "Done building circuit %u to rendezvous with "
3464 "cookie %s for service %s",
3465 (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
3466 circuit_log_path(LOG_INFO, LD_REND, circuit);
3468 /* Clear the 'in-progress HS circ has timed out' flag for
3469 * consistency with what happens on the client side; this line has
3470 * no effect on Tor's behaviour. */
3471 circuit->hs_circ_has_timed_out = 0;
3473 /* If hop is NULL, another rend circ has already connected to this
3474 * rend point. Close this circ. */
3475 if (hop == NULL) {
3476 log_info(LD_REND, "Another rend circ has already reached this rend point; "
3477 "closing this rend circ.");
3478 reason = END_CIRC_REASON_NONE;
3479 goto err;
3482 /* Remove our final cpath element from the reference, so that no
3483 * other circuit will try to use it. Store it in
3484 * pending_final_cpath for now to ensure that it will be freed if
3485 * our rendezvous attempt fails. */
3486 circuit->build_state->pending_final_cpath = hop;
3487 circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
3489 service = rend_service_get_by_pk_digest(rend_pk_digest);
3490 if (!service) {
3491 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
3492 "rendezvous circuit.");
3493 reason = END_CIRC_REASON_INTERNAL;
3494 goto err;
3497 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3498 memcpy(buf, rend_cookie, REND_COOKIE_LEN);
3499 if (crypto_dh_get_public(hop->rend_dh_handshake_state,
3500 buf+REND_COOKIE_LEN, DH1024_KEY_LEN)<0) {
3501 log_warn(LD_GENERAL,"Couldn't get DH public key.");
3502 reason = END_CIRC_REASON_INTERNAL;
3503 goto err;
3505 memcpy(buf+REND_COOKIE_LEN+DH1024_KEY_LEN, hop->rend_circ_nonce,
3506 DIGEST_LEN);
3508 /* Send the cell */
3509 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3510 RELAY_COMMAND_RENDEZVOUS1,
3511 buf, HS_LEGACY_RENDEZVOUS_CELL_SIZE,
3512 circuit->cpath->prev)<0) {
3513 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
3514 goto done;
3517 crypto_dh_free(hop->rend_dh_handshake_state);
3518 hop->rend_dh_handshake_state = NULL;
3520 /* Append the cpath entry. */
3521 hop->state = CPATH_STATE_OPEN;
3522 /* set the windows to default. these are the windows
3523 * that the service thinks the client has.
3525 hop->package_window = circuit_initial_package_window();
3526 hop->deliver_window = CIRCWINDOW_START;
3528 onion_append_to_cpath(&circuit->cpath, hop);
3529 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
3531 /* Change the circuit purpose. */
3532 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
3534 goto done;
3536 err:
3537 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3538 done:
3539 memwipe(buf, 0, sizeof(buf));
3540 memwipe(serviceid, 0, sizeof(serviceid));
3541 memwipe(hexcookie, 0, sizeof(hexcookie));
3543 return;
3547 * Manage introduction points
3550 /** Return the (possibly non-open) introduction circuit ending at
3551 * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
3552 * (<b>desc_version</b> is ignored). Return NULL if no such service is
3553 * found.
3555 static origin_circuit_t *
3556 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
3558 origin_circuit_t *circ = NULL;
3560 tor_assert(intro);
3561 while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3562 (uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
3563 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3564 intro->extend_info->identity_digest, DIGEST_LEN) &&
3565 circ->rend_data) {
3566 return circ;
3570 circ = NULL;
3571 while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3572 (uint8_t *) pk_digest,
3573 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
3574 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3575 intro->extend_info->identity_digest, DIGEST_LEN) &&
3576 circ->rend_data) {
3577 return circ;
3580 return NULL;
3583 /** Return the corresponding introdution point using the circuit <b>circ</b>
3584 * found in the <b>service</b>. NULL is returned if not found. */
3585 static rend_intro_point_t *
3586 find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
3588 tor_assert(service);
3589 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3590 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3592 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
3593 intro_point,
3594 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3595 return intro_point;
3598 return NULL;
3601 /** Return a pointer to the rend_intro_point_t corresponding to the
3602 * service-side introduction circuit <b>circ</b>. */
3603 static rend_intro_point_t *
3604 find_intro_point(origin_circuit_t *circ)
3606 const char *serviceid;
3607 rend_service_t *service = NULL;
3609 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3610 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3611 tor_assert(circ->rend_data);
3612 serviceid = rend_data_get_address(circ->rend_data);
3614 SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
3615 if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
3616 service = s;
3617 break;
3620 if (service == NULL) return NULL;
3622 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
3623 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3624 return intro_point;
3627 return NULL;
3630 /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
3631 * associated with the rend_service_descriptor_t <b>renddesc</b> to
3632 * the responsible hidden service directories OR the hidden service
3633 * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
3634 * <b>seconds_valid</b> are only passed for logging purposes.
3636 void
3637 directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
3638 smartlist_t *descs, smartlist_t *hs_dirs,
3639 const char *service_id, int seconds_valid)
3641 int i, j, failed_upload = 0;
3642 smartlist_t *responsible_dirs = smartlist_new();
3643 smartlist_t *successful_uploads = smartlist_new();
3644 routerstatus_t *hs_dir;
3645 for (i = 0; i < smartlist_len(descs); i++) {
3646 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
3647 /** If any HSDirs are specified, they should be used instead of
3648 * the responsible directories */
3649 if (hs_dirs && smartlist_len(hs_dirs) > 0) {
3650 smartlist_add_all(responsible_dirs, hs_dirs);
3651 } else {
3652 /* Determine responsible dirs. */
3653 if (hid_serv_get_responsible_directories(responsible_dirs,
3654 desc->desc_id) < 0) {
3655 log_warn(LD_REND, "Could not determine the responsible hidden service "
3656 "directories to post descriptors to.");
3657 control_event_hs_descriptor_upload(service_id,
3658 "UNKNOWN",
3659 "UNKNOWN", NULL);
3660 goto done;
3663 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
3664 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
3665 char *hs_dir_ip;
3666 const node_t *node;
3667 rend_data_t *rend_data;
3668 hs_dir = smartlist_get(responsible_dirs, j);
3669 if (smartlist_contains_digest(renddesc->successful_uploads,
3670 hs_dir->identity_digest))
3671 /* Don't upload descriptor if we succeeded in doing so last time. */
3672 continue;
3673 node = node_get_by_id(hs_dir->identity_digest);
3674 if (!node || !node_has_preferred_descriptor(node,0)) {
3675 log_info(LD_REND, "Not launching upload for for v2 descriptor to "
3676 "hidden service directory %s; we don't have its "
3677 "router descriptor. Queuing for later upload.",
3678 safe_str_client(routerstatus_describe(hs_dir)));
3679 failed_upload = -1;
3680 continue;
3682 /* Send publish request. */
3684 /* We need the service ID to identify which service did the upload
3685 * request. Lookup is made in rend_service_desc_has_uploaded(). */
3686 rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
3687 REND_NO_AUTH);
3688 directory_request_t *req =
3689 directory_request_new(DIR_PURPOSE_UPLOAD_RENDDESC_V2);
3690 directory_request_set_routerstatus(req, hs_dir);
3691 directory_request_set_indirection(req, DIRIND_ANONYMOUS);
3692 directory_request_set_payload(req,
3693 desc->desc_str, strlen(desc->desc_str));
3694 directory_request_set_rend_query(req, rend_data);
3695 directory_initiate_request(req);
3696 directory_request_free(req);
3698 rend_data_free(rend_data);
3699 base32_encode(desc_id_base32, sizeof(desc_id_base32),
3700 desc->desc_id, DIGEST_LEN);
3701 hs_dir_ip = tor_dup_ip(hs_dir->addr);
3702 log_info(LD_REND, "Launching upload for v2 descriptor for "
3703 "service '%s' with descriptor ID '%s' with validity "
3704 "of %d seconds to hidden service directory '%s' on "
3705 "%s:%d.",
3706 safe_str_client(service_id),
3707 safe_str_client(desc_id_base32),
3708 seconds_valid,
3709 hs_dir->nickname,
3710 hs_dir_ip,
3711 hs_dir->or_port);
3712 control_event_hs_descriptor_upload(service_id,
3713 hs_dir->identity_digest,
3714 desc_id_base32, NULL);
3715 tor_free(hs_dir_ip);
3716 /* Remember successful upload to this router for next time. */
3717 if (!smartlist_contains_digest(successful_uploads,
3718 hs_dir->identity_digest))
3719 smartlist_add(successful_uploads, hs_dir->identity_digest);
3721 smartlist_clear(responsible_dirs);
3723 if (!failed_upload) {
3724 if (renddesc->successful_uploads) {
3725 SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
3726 smartlist_free(renddesc->successful_uploads);
3727 renddesc->successful_uploads = NULL;
3729 renddesc->all_uploads_performed = 1;
3730 } else {
3731 /* Remember which routers worked this time, so that we don't upload the
3732 * descriptor to them again. */
3733 if (!renddesc->successful_uploads)
3734 renddesc->successful_uploads = smartlist_new();
3735 SMARTLIST_FOREACH(successful_uploads, const char *, c, {
3736 if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
3737 char *hsdir_id = tor_memdup(c, DIGEST_LEN);
3738 smartlist_add(renddesc->successful_uploads, hsdir_id);
3742 done:
3743 smartlist_free(responsible_dirs);
3744 smartlist_free(successful_uploads);
3747 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
3748 * and upload it/them to the responsible hidden service directories.
3750 static void
3751 upload_service_descriptor(rend_service_t *service)
3753 time_t now = time(NULL);
3754 int rendpostperiod;
3755 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3756 int uploaded = 0;
3758 rendpostperiod = get_options()->RendPostPeriod;
3760 networkstatus_t *c = networkstatus_get_latest_consensus();
3761 if (c && smartlist_len(c->routerstatus_list) > 0) {
3762 int seconds_valid, i, j, num_descs;
3763 smartlist_t *descs = smartlist_new();
3764 smartlist_t *client_cookies = smartlist_new();
3765 /* Either upload a single descriptor (including replicas) or one
3766 * descriptor for each authorized client in case of authorization
3767 * type 'stealth'. */
3768 num_descs = service->auth_type == REND_STEALTH_AUTH ?
3769 smartlist_len(service->clients) : 1;
3770 for (j = 0; j < num_descs; j++) {
3771 crypto_pk_t *client_key = NULL;
3772 rend_authorized_client_t *client = NULL;
3773 smartlist_clear(client_cookies);
3774 switch (service->auth_type) {
3775 case REND_NO_AUTH:
3776 /* Do nothing here. */
3777 break;
3778 case REND_BASIC_AUTH:
3779 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
3780 cl, smartlist_add(client_cookies, cl->descriptor_cookie));
3781 break;
3782 case REND_STEALTH_AUTH:
3783 client = smartlist_get(service->clients, j);
3784 client_key = client->client_key;
3785 smartlist_add(client_cookies, client->descriptor_cookie);
3786 break;
3788 /* Encode the current descriptor. */
3789 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3790 now, 0,
3791 service->auth_type,
3792 client_key,
3793 client_cookies);
3794 if (seconds_valid < 0) {
3795 log_warn(LD_BUG, "Internal error: couldn't encode service "
3796 "descriptor; not uploading.");
3797 smartlist_free(descs);
3798 smartlist_free(client_cookies);
3799 return;
3801 rend_get_service_id(service->desc->pk, serviceid);
3802 if (get_options()->PublishHidServDescriptors) {
3803 /* Post the current descriptors to the hidden service directories. */
3804 log_info(LD_REND, "Launching upload for hidden service %s",
3805 serviceid);
3806 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3807 seconds_valid);
3809 /* Free memory for descriptors. */
3810 for (i = 0; i < smartlist_len(descs); i++)
3811 rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3812 smartlist_clear(descs);
3813 /* Update next upload time. */
3814 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3815 > rendpostperiod)
3816 service->next_upload_time = now + rendpostperiod;
3817 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
3818 service->next_upload_time = now + seconds_valid + 1;
3819 else
3820 service->next_upload_time = now + seconds_valid -
3821 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
3822 /* Post also the next descriptors, if necessary. */
3823 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
3824 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3825 now, 1,
3826 service->auth_type,
3827 client_key,
3828 client_cookies);
3829 if (seconds_valid < 0) {
3830 log_warn(LD_BUG, "Internal error: couldn't encode service "
3831 "descriptor; not uploading.");
3832 smartlist_free(descs);
3833 smartlist_free(client_cookies);
3834 return;
3836 if (get_options()->PublishHidServDescriptors) {
3837 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3838 seconds_valid);
3840 /* Free memory for descriptors. */
3841 for (i = 0; i < smartlist_len(descs); i++)
3842 rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3843 smartlist_clear(descs);
3846 smartlist_free(descs);
3847 smartlist_free(client_cookies);
3848 uploaded = 1;
3849 if (get_options()->PublishHidServDescriptors) {
3850 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
3851 } else {
3852 log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
3856 /* If not uploaded, try again in one minute. */
3857 if (!uploaded)
3858 service->next_upload_time = now + 60;
3860 /* Unmark dirty flag of this service. */
3861 service->desc_is_dirty = 0;
3864 /** Return the number of INTRODUCE2 cells this hidden service has received
3865 * from this intro point. */
3866 static int
3867 intro_point_accepted_intro_count(rend_intro_point_t *intro)
3869 return intro->accepted_introduce2_count;
3872 /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
3873 * should stop publishing it in new descriptors and eventually close
3874 * it). */
3875 static int
3876 intro_point_should_expire_now(rend_intro_point_t *intro,
3877 time_t now)
3879 tor_assert(intro != NULL);
3881 if (intro->time_published == -1) {
3882 /* Don't expire an intro point if we haven't even published it yet. */
3883 return 0;
3886 if (intro_point_accepted_intro_count(intro) >=
3887 intro->max_introductions) {
3888 /* This intro point has been used too many times. Expire it now. */
3889 return 1;
3892 if (intro->time_to_expire == -1) {
3893 /* This intro point has been published, but we haven't picked an
3894 * expiration time for it. Pick one now. */
3895 int intro_point_lifetime_seconds =
3896 crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
3897 INTRO_POINT_LIFETIME_MAX_SECONDS);
3899 /* Start the expiration timer now, rather than when the intro
3900 * point was first published. There shouldn't be much of a time
3901 * difference. */
3902 intro->time_to_expire = now + intro_point_lifetime_seconds;
3904 return 0;
3907 /* This intro point has a time to expire set already. Use it. */
3908 return (now >= intro->time_to_expire);
3911 /** Iterate over intro points in the given service and remove the invalid
3912 * ones. For an intro point object to be considered invalid, the circuit
3913 * _and_ node need to have disappeared.
3915 * If the intro point should expire, it's placed into the expiring_nodes
3916 * list of the service and removed from the active intro nodes list.
3918 * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
3920 * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
3921 * circuit disappeared but the node is still in the consensus. */
3922 static void
3923 remove_invalid_intro_points(rend_service_t *service,
3924 smartlist_t *exclude_nodes,
3925 smartlist_t *retry_nodes, time_t now)
3927 tor_assert(service);
3929 /* Remove any expired nodes that doesn't have a circuit. */
3930 SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
3931 intro) {
3932 origin_circuit_t *intro_circ =
3933 find_intro_circuit(intro, service->pk_digest);
3934 if (intro_circ) {
3935 continue;
3937 /* No more circuit, cleanup the into point object. */
3938 SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
3939 rend_intro_point_free(intro);
3940 } SMARTLIST_FOREACH_END(intro);
3942 SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
3943 intro) {
3944 /* Find the introduction point node object. */
3945 const node_t *node =
3946 node_get_by_id(intro->extend_info->identity_digest);
3947 /* Find the intro circuit, this might be NULL. */
3948 origin_circuit_t *intro_circ =
3949 find_intro_circuit(intro, service->pk_digest);
3951 /* Add the valid node to the exclusion list so we don't try to establish
3952 * an introduction point to it again. */
3953 if (node && exclude_nodes) {
3954 smartlist_add(exclude_nodes, (void*) node);
3957 /* First, make sure we still have a valid circuit for this intro point.
3958 * If we dont, we'll give up on it and make a new one. */
3959 if (intro_circ == NULL) {
3960 log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
3961 " (circuit disappeared).",
3962 safe_str_client(extend_info_describe(intro->extend_info)),
3963 safe_str_client(service->service_id));
3964 /* We've lost the circuit for this intro point, flag it so it can be
3965 * accounted for when considiring uploading a descriptor. */
3966 intro->circuit_established = 0;
3968 /* Node is gone or we've reached our maximum circuit creationg retry
3969 * count, clean up everything, we'll find a new one. */
3970 if (node == NULL ||
3971 intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
3972 rend_intro_point_free(intro);
3973 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
3974 /* We've just killed the intro point, nothing left to do. */
3975 continue;
3978 /* The intro point is still alive so let's try to use it again because
3979 * we have a published descriptor containing it. Keep the intro point
3980 * in the intro_nodes list because it's still valid, we are rebuilding
3981 * a circuit to it. */
3982 if (retry_nodes) {
3983 smartlist_add(retry_nodes, intro);
3986 /* else, the circuit is valid so in both cases, node being alive or not,
3987 * we leave the circuit and intro point object as is. Closing the
3988 * circuit here would leak new consensus timing and freeing the intro
3989 * point object would make the intro circuit unusable. */
3991 /* Now, check if intro point should expire. If it does, queue it so
3992 * it can be cleaned up once it has been replaced properly. */
3993 if (intro_point_should_expire_now(intro, now)) {
3994 log_info(LD_REND, "Expiring %s as intro point for %s.",
3995 safe_str_client(extend_info_describe(intro->extend_info)),
3996 safe_str_client(service->service_id));
3997 /* We might have put it in the retry list if so, undo. */
3998 if (retry_nodes) {
3999 smartlist_remove(retry_nodes, intro);
4001 smartlist_add(service->expiring_nodes, intro);
4002 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
4003 /* Intro point is expired, we need a new one thus don't consider it
4004 * anymore has a valid established intro point. */
4005 intro->circuit_established = 0;
4007 } SMARTLIST_FOREACH_END(intro);
4010 /** A new descriptor has been successfully uploaded for the given
4011 * <b>rend_data</b>. Remove and free the expiring nodes from the associated
4012 * service. */
4013 void
4014 rend_service_desc_has_uploaded(const rend_data_t *rend_data)
4016 rend_service_t *service;
4017 const char *onion_address;
4019 tor_assert(rend_data);
4021 onion_address = rend_data_get_address(rend_data);
4023 service = rend_service_get_by_service_id(onion_address);
4024 if (service == NULL) {
4025 return;
4028 SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
4029 intro) {
4030 origin_circuit_t *intro_circ =
4031 find_intro_circuit(intro, service->pk_digest);
4032 if (intro_circ != NULL) {
4033 circuit_mark_for_close(TO_CIRCUIT(intro_circ),
4034 END_CIRC_REASON_FINISHED);
4036 SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
4037 rend_intro_point_free(intro);
4038 } SMARTLIST_FOREACH_END(intro);
4041 /** Don't try to build more than this many circuits before giving up
4042 * for a while. Dynamically calculated based on the configured number of
4043 * introduction points for the service, n_intro_points_wanted. */
4044 static int
4045 rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
4047 /* Allow all but one of the initial connections to fail and be
4048 * retried. (If all fail, we *want* to wait, because something is broken.) */
4049 tor_assert(n_intro_points_wanted <= NUM_INTRO_POINTS_MAX);
4051 /* For the normal use case, 3 intro points plus 2 extra for performance and
4052 * allow that twice because once every 24h or so, we can do it twice for two
4053 * descriptors that is the current one and the next one. So (3 + 2) * 2 ==
4054 * 12 allowed attempts for one period. */
4055 return ((n_intro_points_wanted + NUM_INTRO_POINTS_EXTRA) * 2);
4058 /** For every service, check how many intro points it currently has, and:
4059 * - Invalidate introdution points based on specific criteria, see
4060 * remove_invalid_intro_points comments.
4061 * - Pick new intro points as necessary.
4062 * - Launch circuits to any new intro points.
4064 * This is called once a second by the main loop.
4066 void
4067 rend_consider_services_intro_points(time_t now)
4069 int i;
4070 const or_options_t *options = get_options();
4071 /* Are we in single onion mode? */
4072 const int allow_direct = rend_service_allow_non_anonymous_connection(
4073 get_options());
4074 /* List of nodes we need to _exclude_ when choosing a new node to
4075 * establish an intro point to. */
4076 smartlist_t *exclude_nodes;
4077 /* List of nodes we need to retry to build a circuit on them because the
4078 * node is valid but circuit died. */
4079 smartlist_t *retry_nodes;
4081 if (!have_completed_a_circuit())
4082 return;
4084 exclude_nodes = smartlist_new();
4085 retry_nodes = smartlist_new();
4087 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
4088 int r;
4089 /* Number of intro points we want to open and add to the intro nodes
4090 * list of the service. */
4091 unsigned int n_intro_points_to_open;
4092 /* Have an unsigned len so we can use it to compare values else gcc is
4093 * not happy with unmatching signed comparaison. */
4094 unsigned int intro_nodes_len;
4095 /* Different service are allowed to have the same introduction point as
4096 * long as they are on different circuit thus why we clear this list. */
4097 smartlist_clear(exclude_nodes);
4098 smartlist_clear(retry_nodes);
4100 /* Cleanup the invalid intro points and save the node objects, if any,
4101 * in the exclude_nodes and retry_nodes lists. */
4102 remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
4104 /* This retry period is important here so we don't stress circuit
4105 * creation. */
4107 if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
4108 /* One period has elapsed:
4109 * - if we stopped, we can try building circuits again,
4110 * - if we haven't, we reset the circuit creation counts. */
4111 rend_log_intro_limit(service, LOG_INFO);
4112 service->intro_period_started = now;
4113 service->n_intro_circuits_launched = 0;
4114 } else if (service->n_intro_circuits_launched >=
4115 rend_max_intro_circs_per_period(
4116 service->n_intro_points_wanted)) {
4117 /* We have failed too many times in this period; wait for the next
4118 * one before we try to initiate any more connections. */
4119 rend_log_intro_limit(service, LOG_WARN);
4120 continue;
4123 /* Let's try to rebuild circuit on the nodes we want to retry on. */
4124 SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
4125 r = rend_service_launch_establish_intro(service, intro);
4126 if (r < 0) {
4127 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4128 safe_str_client(extend_info_describe(intro->extend_info)),
4129 safe_str_client(service->service_id));
4130 /* Unable to launch a circuit to that intro point, remove it from
4131 * the valid list so we can create a new one. */
4132 smartlist_remove(service->intro_nodes, intro);
4133 rend_intro_point_free(intro);
4134 continue;
4136 intro->circuit_retries++;
4137 } SMARTLIST_FOREACH_END(intro);
4139 /* Avoid mismatched signed comparaison below. */
4140 intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
4142 /* Quiescent state, we have more or the equal amount of wanted node for
4143 * this service. Proceed to the next service. We can have more nodes
4144 * because we launch extra preemptive circuits if our intro nodes list was
4145 * originally empty for performance reasons. */
4146 if (intro_nodes_len >= service->n_intro_points_wanted) {
4147 continue;
4150 /* Number of intro points we want to open which is the wanted amount minus
4151 * the current amount of valid nodes. We know that this won't underflow
4152 * because of the check above. */
4153 n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
4154 if (intro_nodes_len == 0) {
4155 /* We want to end up with n_intro_points_wanted intro points, but if
4156 * we have no intro points at all (chances are they all cycled or we
4157 * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
4158 * and use the first n_intro_points_wanted that complete. See proposal
4159 * #155, section 4 for the rationale of this which is purely for
4160 * performance.
4162 * The ones after the first n_intro_points_to_open will be converted
4163 * to 'general' internal circuits in rend_service_intro_has_opened(),
4164 * and then we'll drop them from the list of intro points. */
4165 n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
4168 for (i = 0; i < (int) n_intro_points_to_open; i++) {
4169 const node_t *node;
4170 rend_intro_point_t *intro;
4171 router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
4172 router_crn_flags_t direct_flags = flags;
4173 direct_flags |= CRN_PREF_ADDR;
4174 direct_flags |= CRN_DIRECT_CONN;
4176 node = router_choose_random_node(exclude_nodes,
4177 options->ExcludeNodes,
4178 allow_direct ? direct_flags : flags);
4179 /* If we are in single onion mode, retry node selection for a 3-hop
4180 * path */
4181 if (allow_direct && !node) {
4182 log_info(LD_REND,
4183 "Unable to find an intro point that we can connect to "
4184 "directly for %s, falling back to a 3-hop path.",
4185 safe_str_client(service->service_id));
4186 node = router_choose_random_node(exclude_nodes,
4187 options->ExcludeNodes, flags);
4190 if (!node) {
4191 log_warn(LD_REND,
4192 "We only have %d introduction points established for %s; "
4193 "wanted %u.",
4194 smartlist_len(service->intro_nodes),
4195 safe_str_client(service->service_id),
4196 n_intro_points_to_open);
4197 break;
4199 /* Add the chosen node to the exclusion list in order to avoid picking
4200 * it again in the next iteration. */
4201 smartlist_add(exclude_nodes, (void*)node);
4202 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4203 /* extend_info is for clients, so we want the multi-hop primary ORPort,
4204 * even if we are a single onion service and intend to connect to it
4205 * directly ourselves. */
4206 intro->extend_info = extend_info_from_node(node, 0);
4207 if (BUG(intro->extend_info == NULL)) {
4208 break;
4210 intro->intro_key = crypto_pk_new();
4211 const int fail = crypto_pk_generate_key(intro->intro_key);
4212 tor_assert(!fail);
4213 intro->time_published = -1;
4214 intro->time_to_expire = -1;
4215 intro->max_introductions =
4216 crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
4217 INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
4218 smartlist_add(service->intro_nodes, intro);
4219 log_info(LD_REND, "Picked router %s as an intro point for %s.",
4220 safe_str_client(node_describe(node)),
4221 safe_str_client(service->service_id));
4222 /* Establish new introduction circuit to our chosen intro point. */
4223 r = rend_service_launch_establish_intro(service, intro);
4224 if (r < 0) {
4225 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4226 safe_str_client(extend_info_describe(intro->extend_info)),
4227 safe_str_client(service->service_id));
4228 /* This funcion will be called again by the main loop so this intro
4229 * point without a intro circuit will be retried on or removed after
4230 * a maximum number of attempts. */
4233 } SMARTLIST_FOREACH_END(service);
4234 smartlist_free(exclude_nodes);
4235 smartlist_free(retry_nodes);
4238 #define MIN_REND_INITIAL_POST_DELAY (30)
4239 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4241 /** Regenerate and upload rendezvous service descriptors for all
4242 * services, if necessary. If the descriptor has been dirty enough
4243 * for long enough, definitely upload; else only upload when the
4244 * periodic timeout has expired.
4246 * For the first upload, pick a random time between now and two periods
4247 * from now, and pick it independently for each service.
4249 void
4250 rend_consider_services_upload(time_t now)
4252 int i;
4253 rend_service_t *service;
4254 const or_options_t *options = get_options();
4255 int rendpostperiod = options->RendPostPeriod;
4256 int rendinitialpostdelay = (options->TestingTorNetwork ?
4257 MIN_REND_INITIAL_POST_DELAY_TESTING :
4258 MIN_REND_INITIAL_POST_DELAY);
4260 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4261 service = smartlist_get(rend_service_list, i);
4262 if (!service->next_upload_time) { /* never been uploaded yet */
4263 /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4264 * the descriptor is stable before being published. See comment below. */
4265 service->next_upload_time =
4266 now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
4267 /* Single Onion Services prioritise availability over hiding their
4268 * startup time, as their IP address is publicly discoverable anyway.
4270 if (rend_service_reveal_startup_time(options)) {
4271 service->next_upload_time = now + rendinitialpostdelay;
4274 /* Does every introduction points have been established? */
4275 unsigned int intro_points_ready =
4276 count_established_intro_points(service) >=
4277 service->n_intro_points_wanted;
4278 if (intro_points_ready &&
4279 (service->next_upload_time < now ||
4280 (service->desc_is_dirty &&
4281 service->desc_is_dirty < now-rendinitialpostdelay))) {
4282 /* if it's time, or if the directory servers have a wrong service
4283 * descriptor and ours has been stable for rendinitialpostdelay seconds,
4284 * upload a new one of each format. */
4285 rend_service_update_descriptor(service);
4286 upload_service_descriptor(service);
4291 /** True if the list of available router descriptors might have changed so
4292 * that we should have a look whether we can republish previously failed
4293 * rendezvous service descriptors. */
4294 static int consider_republishing_rend_descriptors = 1;
4296 /** Called when our internal view of the directory has changed, so that we
4297 * might have router descriptors of hidden service directories available that
4298 * we did not have before. */
4299 void
4300 rend_hsdir_routers_changed(void)
4302 consider_republishing_rend_descriptors = 1;
4305 /** Consider republication of v2 rendezvous service descriptors that failed
4306 * previously, but without regenerating descriptor contents.
4308 void
4309 rend_consider_descriptor_republication(void)
4311 int i;
4312 rend_service_t *service;
4314 if (!consider_republishing_rend_descriptors)
4315 return;
4316 consider_republishing_rend_descriptors = 0;
4318 if (!get_options()->PublishHidServDescriptors)
4319 return;
4321 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4322 service = smartlist_get(rend_service_list, i);
4323 if (service->desc && !service->desc->all_uploads_performed) {
4324 /* If we failed in uploading a descriptor last time, try again *without*
4325 * updating the descriptor's contents. */
4326 upload_service_descriptor(service);
4331 /** Log the status of introduction points for all rendezvous services
4332 * at log severity <b>severity</b>.
4334 void
4335 rend_service_dump_stats(int severity)
4337 int i,j;
4338 rend_service_t *service;
4339 rend_intro_point_t *intro;
4340 const char *safe_name;
4341 origin_circuit_t *circ;
4343 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4344 service = smartlist_get(rend_service_list, i);
4345 tor_log(severity, LD_GENERAL, "Service configured in %s:",
4346 rend_service_escaped_dir(service));
4347 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
4348 intro = smartlist_get(service->intro_nodes, j);
4349 safe_name = safe_str_client(intro->extend_info->nickname);
4351 circ = find_intro_circuit(intro, service->pk_digest);
4352 if (!circ) {
4353 tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
4354 j, safe_name);
4355 continue;
4357 tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
4358 j, safe_name, circuit_state_to_string(circ->base_.state));
4363 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
4364 * <b>circ</b>, and look up the port and address based on conn-\>port.
4365 * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
4366 * for which the circuit should be closed, -1 on other failure,
4367 * or 0 for success.
4370 rend_service_set_connection_addr_port(edge_connection_t *conn,
4371 origin_circuit_t *circ)
4373 rend_service_t *service;
4374 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4375 const char *rend_pk_digest;
4377 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
4378 tor_assert(circ->rend_data);
4379 log_debug(LD_REND,"beginning to hunt for addr/port");
4380 rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
4381 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
4382 rend_pk_digest, REND_SERVICE_ID_LEN);
4383 service = rend_service_get_by_pk_digest(rend_pk_digest);
4384 if (!service) {
4385 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
4386 "rendezvous circuit %u; closing.",
4387 serviceid, (unsigned)circ->base_.n_circ_id);
4388 return -2;
4390 if (service->max_streams_per_circuit > 0) {
4391 /* Enforce the streams-per-circuit limit, and refuse to provide a
4392 * mapping if this circuit will exceed the limit. */
4393 #define MAX_STREAM_WARN_INTERVAL 600
4394 static struct ratelim_t stream_ratelim =
4395 RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
4396 if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
4397 log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
4398 "Maximum streams per circuit limit reached on rendezvous "
4399 "circuit %u; %s. Circuit has %d out of %d streams.",
4400 (unsigned)circ->base_.n_circ_id,
4401 service->max_streams_close_circuit ?
4402 "closing circuit" :
4403 "ignoring open stream request",
4404 circ->rend_data->nr_streams,
4405 service->max_streams_per_circuit);
4406 return service->max_streams_close_circuit ? -2 : -1;
4410 if (hs_set_conn_addr_port(service->ports, conn) == 0) {
4411 /* Successfully set the port to the connection. We are done. */
4412 return 0;
4415 log_info(LD_REND,
4416 "No virtual port mapping exists for port %d on service %s",
4417 conn->base_.port, serviceid);
4419 if (service->allow_unknown_ports)
4420 return -1;
4421 else
4422 return -2;
4425 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4427 static int
4428 rend_service_non_anonymous_mode_consistent(const or_options_t *options)
4430 /* !! is used to make these options boolean */
4431 return (!! options->HiddenServiceSingleHopMode ==
4432 !! options->HiddenServiceNonAnonymousMode);
4435 /* Do the options allow onion services to make direct (non-anonymous)
4436 * connections to introduction or rendezvous points?
4437 * Must only be called after options_validate_single_onion() has successfully
4438 * checked onion service option consistency.
4439 * Returns true if tor is in HiddenServiceSingleHopMode. */
4441 rend_service_allow_non_anonymous_connection(const or_options_t *options)
4443 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4444 return options->HiddenServiceSingleHopMode ? 1 : 0;
4447 /* Do the options allow us to reveal the exact startup time of the onion
4448 * service?
4449 * Single Onion Services prioritise availability over hiding their
4450 * startup time, as their IP address is publicly discoverable anyway.
4451 * Must only be called after options_validate_single_onion() has successfully
4452 * checked onion service option consistency.
4453 * Returns true if tor is in non-anonymous hidden service mode. */
4455 rend_service_reveal_startup_time(const or_options_t *options)
4457 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4458 return rend_service_non_anonymous_mode_enabled(options);
4461 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4462 * config option?
4463 * Must only be called after options_validate_single_onion() has successfully
4464 * checked onion service option consistency.
4467 rend_service_non_anonymous_mode_enabled(const or_options_t *options)
4469 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4470 return options->HiddenServiceNonAnonymousMode ? 1 : 0;
4473 #ifdef TOR_UNIT_TESTS
4475 STATIC void
4476 set_rend_service_list(smartlist_t *new_list)
4478 rend_service_list = new_list;
4481 STATIC void
4482 set_rend_rend_service_staging_list(smartlist_t *new_list)
4484 rend_service_staging_list = new_list;
4487 #endif /* defined(TOR_UNIT_TESTS) */