hs-v2: Add deprecation warning for service
[tor.git] / src / feature / rend / rendservice.c
blobeaf0432a7da15f0e0fcab98e9405b6618b4db6fa
1 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
2 * Copyright (c) 2007-2019, 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/routerset.h"
35 #include "feature/rend/rendclient.h"
36 #include "feature/rend/rendcommon.h"
37 #include "feature/rend/rendparse.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 /** Helper: log the deprecation warning for version 2 only once. */
134 static void
135 log_once_deprecation_warning(void)
137 static bool logged_once = false;
138 if (!logged_once) {
139 log_warn(LD_REND, "DEPRECATED: Onion service version 2 are deprecated. "
140 "Please use version 3 which is the default now. "
141 "Currently, version 2 is planned to be obsolete in "
142 "the Tor version 0.4.6 stable series.");
143 logged_once = true;
146 /** Macro to make it very explicit that we are warning about deprecation. */
147 #define WARN_ONCE_DEPRECATION() log_once_deprecation_warning()
149 /* Like rend_get_service_list_mutable, but returns a read-only list. */
150 static const smartlist_t*
151 rend_get_service_list(const smartlist_t* substitute_service_list)
153 /* It is safe to cast away the const here, because
154 * rend_get_service_list_mutable does not actually modify the list */
155 return rend_get_service_list_mutable((smartlist_t*)substitute_service_list);
158 /* Return a mutable list of hidden services.
159 * If substitute_service_list is not NULL, return it.
160 * Otherwise, check if the global rend_service_list is non-NULL, and if so,
161 * return it.
162 * Otherwise, log a BUG message and return NULL.
163 * */
164 static smartlist_t*
165 rend_get_service_list_mutable(smartlist_t* substitute_service_list)
167 if (substitute_service_list) {
168 return substitute_service_list;
171 /* If no special service list is provided, then just use the global one. */
173 if (BUG(!rend_service_list)) {
174 /* No global HS list, which is a programmer error. */
175 return NULL;
178 return rend_service_list;
181 /** Tells if onion service <b>s</b> is ephemeral.
183 static unsigned int
184 rend_service_is_ephemeral(const struct rend_service_t *s)
186 return (s->directory == NULL);
189 /** Returns a escaped string representation of the service, <b>s</b>.
191 static const char *
192 rend_service_escaped_dir(const struct rend_service_t *s)
194 return rend_service_is_ephemeral(s) ? "[EPHEMERAL]" : escaped(s->directory);
197 /** Return the number of rendezvous services we have configured. */
199 rend_num_services(void)
201 if (!rend_service_list)
202 return 0;
203 return smartlist_len(rend_service_list);
206 /** Helper: free storage held by a single service authorized client entry. */
207 void
208 rend_authorized_client_free_(rend_authorized_client_t *client)
210 if (!client)
211 return;
212 if (client->client_key)
213 crypto_pk_free(client->client_key);
214 if (client->client_name)
215 memwipe(client->client_name, 0, strlen(client->client_name));
216 tor_free(client->client_name);
217 memwipe(client->descriptor_cookie, 0, sizeof(client->descriptor_cookie));
218 tor_free(client);
221 /** Helper for strmap_free. */
222 static void
223 rend_authorized_client_free_void(void *authorized_client)
225 rend_authorized_client_free_(authorized_client);
228 /** Release the storage held by <b>service</b>.
230 STATIC void
231 rend_service_free_(rend_service_t *service)
233 if (!service)
234 return;
236 tor_free(service->directory);
237 if (service->ports) {
238 SMARTLIST_FOREACH(service->ports, rend_service_port_config_t*, p,
239 rend_service_port_config_free(p));
240 smartlist_free(service->ports);
242 if (service->private_key)
243 crypto_pk_free(service->private_key);
244 if (service->intro_nodes) {
245 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
246 rend_intro_point_free(intro););
247 smartlist_free(service->intro_nodes);
249 if (service->expiring_nodes) {
250 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *, intro,
251 rend_intro_point_free(intro););
252 smartlist_free(service->expiring_nodes);
255 rend_service_descriptor_free(service->desc);
256 if (service->clients) {
257 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, c,
258 rend_authorized_client_free(c););
259 smartlist_free(service->clients);
261 if (service->accepted_intro_dh_parts) {
262 replaycache_free(service->accepted_intro_dh_parts);
264 tor_free(service);
267 /* Release all the storage held in rend_service_staging_list. */
268 void
269 rend_service_free_staging_list(void)
271 if (rend_service_staging_list) {
272 SMARTLIST_FOREACH(rend_service_staging_list, rend_service_t*, ptr,
273 rend_service_free(ptr));
274 smartlist_free(rend_service_staging_list);
275 rend_service_staging_list = NULL;
279 /** Release all the storage held in both rend_service_list and
280 * rend_service_staging_list. */
281 void
282 rend_service_free_all(void)
284 if (rend_service_list) {
285 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, ptr,
286 rend_service_free(ptr));
287 smartlist_free(rend_service_list);
288 rend_service_list = NULL;
290 rend_service_free_staging_list();
293 /* Initialize the subsystem. */
294 void
295 rend_service_init(void)
297 tor_assert(!rend_service_list);
298 tor_assert(!rend_service_staging_list);
300 rend_service_list = smartlist_new();
301 rend_service_staging_list = smartlist_new();
304 /* Validate a <b>service</b>. Use the <b>service_list</b> to make sure there
305 * is no duplicate entry for the given service object. Return 0 if valid else
306 * -1 if not.*/
307 static int
308 rend_validate_service(const smartlist_t *service_list,
309 const rend_service_t *service)
311 tor_assert(service_list);
312 tor_assert(service);
314 if (service->max_streams_per_circuit < 0) {
315 log_warn(LD_CONFIG, "Hidden service (%s) configured with negative max "
316 "streams per circuit.",
317 rend_service_escaped_dir(service));
318 goto invalid;
321 if (service->max_streams_close_circuit < 0 ||
322 service->max_streams_close_circuit > 1) {
323 log_warn(LD_CONFIG, "Hidden service (%s) configured with invalid "
324 "max streams handling.",
325 rend_service_escaped_dir(service));
326 goto invalid;
329 if (service->auth_type != REND_NO_AUTH &&
330 (!service->clients || smartlist_len(service->clients) == 0)) {
331 log_warn(LD_CONFIG, "Hidden service (%s) with client authorization but "
332 "no clients.",
333 rend_service_escaped_dir(service));
334 goto invalid;
337 if (!service->ports || !smartlist_len(service->ports)) {
338 log_warn(LD_CONFIG, "Hidden service (%s) with no ports configured.",
339 rend_service_escaped_dir(service));
340 goto invalid;
343 /* Valid. */
344 return 0;
345 invalid:
346 return -1;
349 /** Add it to <b>service_list</b>, or to the global rend_service_list if
350 * <b>service_list</b> is NULL. Return 0 on success. On failure, free
351 * <b>service</b> and return -1. Takes ownership of <b>service</b>. */
352 static int
353 rend_add_service(smartlist_t *service_list, rend_service_t *service)
355 int i;
356 rend_service_port_config_t *p;
358 tor_assert(service);
360 smartlist_t *s_list = rend_get_service_list_mutable(service_list);
361 /* We must have a service list, even if it's a temporary one, so we can
362 * check for duplicate services */
363 if (BUG(!s_list)) {
364 rend_service_free(service);
365 return -1;
368 service->intro_nodes = smartlist_new();
369 service->expiring_nodes = smartlist_new();
371 log_debug(LD_REND,"Configuring service with directory %s",
372 rend_service_escaped_dir(service));
373 for (i = 0; i < smartlist_len(service->ports); ++i) {
374 p = smartlist_get(service->ports, i);
375 if (!(p->is_unix_addr)) {
376 log_debug(LD_REND,
377 "Service maps port %d to %s",
378 p->virtual_port,
379 fmt_addrport(&p->real_addr, p->real_port));
380 } else {
381 #ifdef HAVE_SYS_UN_H
382 log_debug(LD_REND,
383 "Service maps port %d to socket at \"%s\"",
384 p->virtual_port, p->unix_addr);
385 #else
386 log_warn(LD_BUG,
387 "Service maps port %d to an AF_UNIX socket, but we "
388 "have no AF_UNIX support on this platform. This is "
389 "probably a bug.",
390 p->virtual_port);
391 rend_service_free(service);
392 return -1;
393 #endif /* defined(HAVE_SYS_UN_H) */
396 /* The service passed all the checks */
397 tor_assert(s_list);
398 smartlist_add(s_list, service);
400 /* Notify that our global service list has changed only if this new service
401 * went into our global list. If not, when we move service from the staging
402 * list to the new list, a notify is triggered. */
403 if (s_list == rend_service_list) {
404 hs_service_map_has_changed();
406 return 0;
409 /** Return a new rend_service_port_config_t with its path set to
410 * <b>socket_path</b> or empty if <b>socket_path</b> is NULL */
411 static rend_service_port_config_t *
412 rend_service_port_config_new(const char *socket_path)
414 if (!socket_path)
415 return tor_malloc_zero(sizeof(rend_service_port_config_t) + 1);
417 const size_t pathlen = strlen(socket_path) + 1;
418 rend_service_port_config_t *conf =
419 tor_malloc_zero(sizeof(rend_service_port_config_t) + pathlen);
420 memcpy(conf->unix_addr, socket_path, pathlen);
421 conf->is_unix_addr = 1;
422 return conf;
425 /** Parses a virtual-port to real-port/socket mapping separated by
426 * the provided separator and returns a new rend_service_port_config_t,
427 * or NULL and an optional error string on failure.
429 * The format is: VirtualPort SEP (IP|RealPort|IP:RealPort|'socket':path)?
431 * IP defaults to 127.0.0.1; RealPort defaults to VirtualPort.
433 rend_service_port_config_t *
434 rend_service_parse_port_config(const char *string, const char *sep,
435 char **err_msg_out)
437 smartlist_t *sl;
438 int virtport;
439 int realport = 0;
440 uint16_t p;
441 tor_addr_t addr;
442 rend_service_port_config_t *result = NULL;
443 unsigned int is_unix_addr = 0;
444 const char *socket_path = NULL;
445 char *err_msg = NULL;
446 char *addrport = NULL;
448 sl = smartlist_new();
449 smartlist_split_string(sl, string, sep,
450 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
451 if (smartlist_len(sl) < 1 || BUG(smartlist_len(sl) > 2)) {
452 err_msg = tor_strdup("Bad syntax in hidden service port configuration.");
453 goto err;
455 virtport = (int)tor_parse_long(smartlist_get(sl,0), 10, 1, 65535, NULL,NULL);
456 if (!virtport) {
457 tor_asprintf(&err_msg, "Missing or invalid port %s in hidden service "
458 "port configuration", escaped(smartlist_get(sl,0)));
460 goto err;
462 if (smartlist_len(sl) == 1) {
463 /* No addr:port part; use default. */
464 realport = virtport;
465 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* 127.0.0.1 */
466 } else {
467 int ret;
469 const char *addrport_element = smartlist_get(sl,1);
470 const char *rest = NULL;
471 int is_unix;
472 ret = port_cfg_line_extract_addrport(addrport_element, &addrport,
473 &is_unix, &rest);
475 if (ret < 0) {
476 tor_asprintf(&err_msg, "Couldn't process address <%s> from hidden "
477 "service configuration", addrport_element);
478 goto err;
481 if (rest && strlen(rest)) {
482 err_msg = tor_strdup("HiddenServicePort parse error: invalid port "
483 "mapping");
484 goto err;
487 if (is_unix) {
488 socket_path = addrport;
489 is_unix_addr = 1;
490 } else if (strchr(addrport, ':') || strchr(addrport, '.')) {
491 /* else try it as an IP:port pair if it has a : or . in it */
492 if (tor_addr_port_lookup(addrport, &addr, &p)<0) {
493 err_msg = tor_strdup("Unparseable address in hidden service port "
494 "configuration.");
495 goto err;
497 realport = p?p:virtport;
498 } else {
499 /* No addr:port, no addr -- must be port. */
500 realport = (int)tor_parse_long(addrport, 10, 1, 65535, NULL, NULL);
501 if (!realport) {
502 tor_asprintf(&err_msg, "Unparseable or out-of-range port %s in "
503 "hidden service port configuration.",
504 escaped(addrport));
505 goto err;
507 tor_addr_from_ipv4h(&addr, 0x7F000001u); /* Default to 127.0.0.1 */
511 /* Allow room for unix_addr */
512 result = rend_service_port_config_new(socket_path);
513 result->virtual_port = virtport;
514 result->is_unix_addr = is_unix_addr;
515 if (!is_unix_addr) {
516 result->real_port = realport;
517 tor_addr_copy(&result->real_addr, &addr);
518 result->unix_addr[0] = '\0';
521 err:
522 tor_free(addrport);
523 if (err_msg_out != NULL) {
524 *err_msg_out = err_msg;
525 } else {
526 tor_free(err_msg);
528 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
529 smartlist_free(sl);
531 return result;
534 /** Release all storage held in a rend_service_port_config_t. */
535 void
536 rend_service_port_config_free_(rend_service_port_config_t *p)
538 tor_free(p);
541 /* Copy relevant data from service src to dst while pruning the service lists.
542 * This should only be called during the pruning process which takes existing
543 * services and copy their data to the newly configured services. The src
544 * service replaycache will be set to NULL after this call. */
545 static void
546 copy_service_on_prunning(rend_service_t *dst, rend_service_t *src)
548 tor_assert(dst);
549 tor_assert(src);
551 /* Keep the timestamps for when the content changed and the next upload
552 * time so we can properly upload the descriptor if needed for the new
553 * service object. */
554 dst->desc_is_dirty = src->desc_is_dirty;
555 dst->next_upload_time = src->next_upload_time;
556 /* Move the replaycache to the new object. */
557 dst->accepted_intro_dh_parts = src->accepted_intro_dh_parts;
558 src->accepted_intro_dh_parts = NULL;
559 /* Copy intro point information to destination service. */
560 dst->intro_period_started = src->intro_period_started;
561 dst->n_intro_circuits_launched = src->n_intro_circuits_launched;
562 dst->n_intro_points_wanted = src->n_intro_points_wanted;
565 /* Helper: Actual implementation of the pruning on reload which we've
566 * decoupled in order to make the unit test workeable without ugly hacks.
567 * Furthermore, this function does NOT free any memory but will nullify the
568 * temporary list pointer whatever happens. */
569 STATIC void
570 rend_service_prune_list_impl_(void)
572 origin_circuit_t *ocirc = NULL;
573 smartlist_t *surviving_services, *old_service_list, *new_service_list;
575 /* When pruning our current service list, we must have a staging list that
576 * contains what we want to check else it's a code flow error. */
577 tor_assert(rend_service_staging_list);
579 /* We are about to prune the current list of its dead service so set the
580 * semantic for that list to be the "old" one. */
581 old_service_list = rend_service_list;
582 /* The staging list is now the "new" list so set this semantic. */
583 new_service_list = rend_service_staging_list;
584 /* After this, whatever happens, we'll use our new list. */
585 rend_service_list = new_service_list;
586 /* Finally, nullify the staging list pointer as we don't need it anymore
587 * and it needs to be NULL before the next reload. */
588 rend_service_staging_list = NULL;
589 /* Nothing to prune if we have no service list so stop right away. */
590 if (!old_service_list) {
591 return;
594 /* This contains all _existing_ services that survives the relaod that is
595 * that haven't been removed from the configuration. The difference between
596 * this list and the new service list is that the new list can possibly
597 * contain newly configured service that have no introduction points opened
598 * yet nor key material loaded or generated. */
599 surviving_services = smartlist_new();
601 /* Preserve the existing ephemeral services.
603 * This is the ephemeral service equivalent of the "Copy introduction
604 * points to new services" block, except there's no copy required since
605 * the service structure isn't regenerated.
607 * After this is done, all ephemeral services will be:
608 * * Removed from old_service_list, so the equivalent non-ephemeral code
609 * will not attempt to preserve them.
610 * * Added to the new_service_list (that previously only had the
611 * services listed in the configuration).
612 * * Added to surviving_services, which is the list of services that
613 * will NOT have their intro point closed.
615 SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
616 if (rend_service_is_ephemeral(old)) {
617 SMARTLIST_DEL_CURRENT(old_service_list, old);
618 smartlist_add(surviving_services, old);
619 smartlist_add(new_service_list, old);
621 } SMARTLIST_FOREACH_END(old);
623 /* Copy introduction points to new services. This is O(n^2), but it's only
624 * called on reconfigure, so it's ok performance wise. */
625 SMARTLIST_FOREACH_BEGIN(new_service_list, rend_service_t *, new) {
626 SMARTLIST_FOREACH_BEGIN(old_service_list, rend_service_t *, old) {
627 /* Skip ephemeral services as we only want to copy introduction points
628 * from current services to newly configured one that already exists.
629 * The same directory means it's the same service. */
630 if (rend_service_is_ephemeral(new) || rend_service_is_ephemeral(old) ||
631 strcmp(old->directory, new->directory)) {
632 continue;
634 smartlist_add_all(new->intro_nodes, old->intro_nodes);
635 smartlist_clear(old->intro_nodes);
636 smartlist_add_all(new->expiring_nodes, old->expiring_nodes);
637 smartlist_clear(old->expiring_nodes);
639 /* Copy needed information from old to new. */
640 copy_service_on_prunning(new, old);
642 /* This regular service will survive the closing IPs step after. */
643 smartlist_add(surviving_services, old);
644 break;
645 } SMARTLIST_FOREACH_END(old);
646 } SMARTLIST_FOREACH_END(new);
648 /* For every service introduction circuit we can find, see if we have a
649 * matching surviving configured service. If not, close the circuit. */
650 while ((ocirc = circuit_get_next_intro_circ(ocirc, false))) {
651 int keep_it = 0;
652 if (ocirc->rend_data == NULL) {
653 /* This is a v3 circuit, ignore it. */
654 continue;
656 SMARTLIST_FOREACH_BEGIN(surviving_services, const rend_service_t *, s) {
657 if (rend_circuit_pk_digest_eq(ocirc, (uint8_t *) s->pk_digest)) {
658 /* Keep this circuit as we have a matching configured service. */
659 keep_it = 1;
660 break;
662 } SMARTLIST_FOREACH_END(s);
663 if (keep_it) {
664 continue;
666 log_info(LD_REND, "Closing intro point %s for service %s.",
667 safe_str_client(extend_info_describe(
668 ocirc->build_state->chosen_exit)),
669 safe_str_client(rend_data_get_address(ocirc->rend_data)));
670 /* Reason is FINISHED because service has been removed and thus the
671 * circuit is considered old/uneeded. */
672 circuit_mark_for_close(TO_CIRCUIT(ocirc), END_CIRC_REASON_FINISHED);
674 smartlist_free(surviving_services);
675 /* Notify that our global service list has changed. */
676 hs_service_map_has_changed();
679 /* Try to prune our main service list using the temporary one that we just
680 * loaded and parsed successfully. The pruning process decides which onion
681 * services to keep and which to discard after a reload. */
682 void
683 rend_service_prune_list(void)
685 smartlist_t *old_service_list = rend_service_list;
687 if (!rend_service_staging_list) {
688 rend_service_staging_list = smartlist_new();
691 rend_service_prune_list_impl_();
692 if (old_service_list) {
693 /* Every remaining service in the old list have been removed from the
694 * configuration so clean them up safely. */
695 SMARTLIST_FOREACH(old_service_list, rend_service_t *, s,
696 rend_service_free(s));
697 smartlist_free(old_service_list);
701 /* Copy all the relevant data that the hs_service object contains over to the
702 * rend_service_t object. The reason to do so is because when configuring a
703 * service, we go through a generic handler that creates an hs_service_t
704 * object which so we have to copy the parsed values to a rend service object
705 * which is version 2 specific. */
706 static void
707 service_config_shadow_copy(rend_service_t *service,
708 hs_service_config_t *config)
710 tor_assert(service);
711 tor_assert(config);
713 service->directory = tor_strdup(config->directory_path);
714 service->dir_group_readable = config->dir_group_readable;
715 service->allow_unknown_ports = config->allow_unknown_ports;
716 /* This value can't go above HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT (65535)
717 * if the code flow is right so this cast is safe. But just in case, we'll
718 * check it. */
719 service->max_streams_per_circuit = (int) config->max_streams_per_rdv_circuit;
720 if (BUG(config->max_streams_per_rdv_circuit >
721 HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT)) {
722 service->max_streams_per_circuit = HS_CONFIG_MAX_STREAMS_PER_RDV_CIRCUIT;
724 service->max_streams_close_circuit = config->max_streams_close_circuit;
725 service->n_intro_points_wanted = config->num_intro_points;
726 /* Switching ownership of the ports to the rend service object. */
727 smartlist_add_all(service->ports, config->ports);
728 smartlist_free(config->ports);
729 config->ports = NULL;
732 /* Parse the hidden service configuration starting at <b>line_</b> using the
733 * already configured generic service configuration in <b>config</b>. This
734 * function will translate the config object to a rend_service_t and add it to
735 * the temporary list if valid. If <b>validate_only</b> is set, parse, warn
736 * and return as normal but don't actually add the service to the list. */
738 rend_config_service(const config_line_t *line_,
739 const or_options_t *options,
740 hs_service_config_t *config)
742 const config_line_t *line;
743 rend_service_t *service = NULL;
745 /* line_ can be NULL which would mean that the service configuration only
746 * have one line that is the directory directive. */
747 tor_assert(options);
748 tor_assert(config);
750 /* We are about to configure a version 2 service. Warn of deprecation. */
751 WARN_ONCE_DEPRECATION();
753 /* Use the staging service list so that we can check then do the pruning
754 * process using the main list at the end. */
755 if (rend_service_staging_list == NULL) {
756 rend_service_staging_list = smartlist_new();
759 /* Initialize service. */
760 service = tor_malloc_zero(sizeof(rend_service_t));
761 service->intro_period_started = time(NULL);
762 service->ports = smartlist_new();
763 /* From the hs_service object which has been used to load the generic
764 * options, we'll copy over the useful data to the rend_service_t object. */
765 service_config_shadow_copy(service, config);
767 for (line = line_; line; line = line->next) {
768 if (!strcasecmp(line->key, "HiddenServiceDir")) {
769 /* We just hit the next hidden service, stop right now. */
770 break;
772 /* Number of introduction points. */
773 if (!strcasecmp(line->key, "HiddenServiceNumIntroductionPoints")) {
774 int ok = 0;
775 /* Those are specific defaults for version 2. */
776 service->n_intro_points_wanted =
777 (unsigned int) tor_parse_long(line->value, 10,
778 0, NUM_INTRO_POINTS_MAX, &ok, NULL);
779 if (!ok) {
780 log_warn(LD_CONFIG,
781 "HiddenServiceNumIntroductionPoints "
782 "should be between %d and %d, not %s",
783 0, NUM_INTRO_POINTS_MAX, line->value);
784 goto err;
786 log_info(LD_CONFIG, "HiddenServiceNumIntroductionPoints=%d for %s",
787 service->n_intro_points_wanted, escaped(service->directory));
788 continue;
790 if (!strcasecmp(line->key, "HiddenServiceAuthorizeClient")) {
791 /* Parse auth type and comma-separated list of client names and add a
792 * rend_authorized_client_t for each client to the service's list
793 * of authorized clients. */
794 smartlist_t *type_names_split, *clients;
795 const char *authname;
796 if (service->auth_type != REND_NO_AUTH) {
797 log_warn(LD_CONFIG, "Got multiple HiddenServiceAuthorizeClient "
798 "lines for a single service.");
799 goto err;
801 type_names_split = smartlist_new();
802 smartlist_split_string(type_names_split, line->value, " ", 0, 2);
803 if (smartlist_len(type_names_split) < 1) {
804 log_warn(LD_BUG, "HiddenServiceAuthorizeClient has no value. This "
805 "should have been prevented when parsing the "
806 "configuration.");
807 smartlist_free(type_names_split);
808 goto err;
810 authname = smartlist_get(type_names_split, 0);
811 if (!strcasecmp(authname, "basic")) {
812 service->auth_type = REND_BASIC_AUTH;
813 } else if (!strcasecmp(authname, "stealth")) {
814 service->auth_type = REND_STEALTH_AUTH;
815 } else {
816 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
817 "unrecognized auth-type '%s'. Only 'basic' or 'stealth' "
818 "are recognized.",
819 (char *) smartlist_get(type_names_split, 0));
820 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
821 smartlist_free(type_names_split);
822 goto err;
824 service->clients = smartlist_new();
825 if (smartlist_len(type_names_split) < 2) {
826 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains "
827 "auth-type '%s', but no client names.",
828 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
829 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
830 smartlist_free(type_names_split);
831 continue;
833 clients = smartlist_new();
834 smartlist_split_string(clients, smartlist_get(type_names_split, 1),
835 ",", SPLIT_SKIP_SPACE, 0);
836 SMARTLIST_FOREACH(type_names_split, char *, cp, tor_free(cp));
837 smartlist_free(type_names_split);
838 /* Remove duplicate client names. */
840 int num_clients = smartlist_len(clients);
841 smartlist_sort_strings(clients);
842 smartlist_uniq_strings(clients);
843 if (smartlist_len(clients) < num_clients) {
844 log_info(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
845 "duplicate client name(s); removing.",
846 num_clients - smartlist_len(clients));
849 SMARTLIST_FOREACH_BEGIN(clients, const char *, client_name)
851 rend_authorized_client_t *client;
852 if (!rend_valid_client_name(client_name)) {
853 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains an "
854 "illegal client name: '%s'. Names must be "
855 "between 1 and %d characters and contain "
856 "only [A-Za-z0-9+_-].",
857 client_name, REND_CLIENTNAME_MAX_LEN);
858 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
859 smartlist_free(clients);
860 goto err;
862 client = tor_malloc_zero(sizeof(rend_authorized_client_t));
863 client->client_name = tor_strdup(client_name);
864 smartlist_add(service->clients, client);
865 log_debug(LD_REND, "Adding client name '%s'", client_name);
867 SMARTLIST_FOREACH_END(client_name);
868 SMARTLIST_FOREACH(clients, char *, cp, tor_free(cp));
869 smartlist_free(clients);
870 /* Ensure maximum number of clients. */
871 if ((service->auth_type == REND_BASIC_AUTH &&
872 smartlist_len(service->clients) > 512) ||
873 (service->auth_type == REND_STEALTH_AUTH &&
874 smartlist_len(service->clients) > 16)) {
875 log_warn(LD_CONFIG, "HiddenServiceAuthorizeClient contains %d "
876 "client authorization entries, but only a "
877 "maximum of %d entries is allowed for "
878 "authorization type '%s'.",
879 smartlist_len(service->clients),
880 service->auth_type == REND_BASIC_AUTH ? 512 : 16,
881 service->auth_type == REND_BASIC_AUTH ? "basic" : "stealth");
882 goto err;
884 continue;
887 /* Validate the service just parsed. */
888 if (rend_validate_service(rend_service_staging_list, service) < 0) {
889 /* Service is in the staging list so don't try to free it. */
890 goto err;
893 /* Add it to the temporary list which we will use to prune our current
894 * list if any after configuring all services. */
895 if (rend_add_service(rend_service_staging_list, service) < 0) {
896 /* The object has been freed on error already. */
897 service = NULL;
898 goto err;
901 return 0;
902 err:
903 rend_service_free(service);
904 return -1;
907 /** Add the ephemeral service <b>pk</b>/<b>ports</b> if possible, using
908 * client authorization <b>auth_type</b> and an optional list of
909 * rend_authorized_client_t in <b>auth_clients</b>, with
910 * <b>max_streams_per_circuit</b> streams allowed per rendezvous circuit,
911 * and circuit closure on max streams being exceeded set by
912 * <b>max_streams_close_circuit</b>.
914 * Ownership of pk, ports, and auth_clients is passed to this routine.
915 * Regardless of success/failure, callers should not touch these values
916 * after calling this routine, and may assume that correct cleanup has
917 * been done on failure.
919 * Return an appropriate hs_service_add_ephemeral_status_t.
921 hs_service_add_ephemeral_status_t
922 rend_service_add_ephemeral(crypto_pk_t *pk,
923 smartlist_t *ports,
924 int max_streams_per_circuit,
925 int max_streams_close_circuit,
926 rend_auth_type_t auth_type,
927 smartlist_t *auth_clients,
928 char **service_id_out)
930 *service_id_out = NULL;
931 /* Allocate the service structure, and initialize the key, and key derived
932 * parameters.
934 rend_service_t *s = tor_malloc_zero(sizeof(rend_service_t));
935 s->directory = NULL; /* This indicates the service is ephemeral. */
936 s->private_key = pk;
937 s->auth_type = auth_type;
938 s->clients = auth_clients;
939 s->ports = ports;
940 s->intro_period_started = time(NULL);
941 s->n_intro_points_wanted = NUM_INTRO_POINTS_DEFAULT;
942 s->max_streams_per_circuit = max_streams_per_circuit;
943 s->max_streams_close_circuit = max_streams_close_circuit;
944 if (rend_service_derive_key_digests(s) < 0) {
945 rend_service_free(s);
946 return RSAE_BADPRIVKEY;
949 if (!s->ports || smartlist_len(s->ports) == 0) {
950 log_warn(LD_CONFIG, "At least one VIRTPORT/TARGET must be specified.");
951 rend_service_free(s);
952 return RSAE_BADVIRTPORT;
954 if (s->auth_type != REND_NO_AUTH &&
955 (!s->clients || smartlist_len(s->clients) == 0)) {
956 log_warn(LD_CONFIG, "At least one authorized client must be specified.");
957 rend_service_free(s);
958 return RSAE_BADAUTH;
961 /* Enforcing pk/id uniqueness should be done by rend_service_load_keys(), but
962 * it's not, see #14828.
964 if (rend_service_get_by_pk_digest(s->pk_digest)) {
965 log_warn(LD_CONFIG, "Onion Service private key collides with an "
966 "existing service.");
967 rend_service_free(s);
968 return RSAE_ADDREXISTS;
970 if (rend_service_get_by_service_id(s->service_id)) {
971 log_warn(LD_CONFIG, "Onion Service id collides with an existing service.");
972 rend_service_free(s);
973 return RSAE_ADDREXISTS;
976 /* Initialize the service. */
977 if (rend_add_service(NULL, s)) {
978 return RSAE_INTERNAL;
980 *service_id_out = tor_strdup(s->service_id);
982 log_debug(LD_CONFIG, "Added ephemeral Onion Service: %s", s->service_id);
983 return RSAE_OKAY;
986 /** Remove the ephemeral service <b>service_id</b> if possible. Returns 0 on
987 * success, and -1 on failure.
990 rend_service_del_ephemeral(const char *service_id)
992 rend_service_t *s;
993 if (!rend_valid_v2_service_id(service_id)) {
994 log_warn(LD_CONFIG, "Requested malformed Onion Service id for removal.");
995 return -1;
997 if ((s = rend_service_get_by_service_id(service_id)) == NULL) {
998 log_warn(LD_CONFIG, "Requested non-existent Onion Service id for "
999 "removal.");
1000 return -1;
1002 if (!rend_service_is_ephemeral(s)) {
1003 log_warn(LD_CONFIG, "Requested non-ephemeral Onion Service for removal.");
1004 return -1;
1007 /* Kill the intro point circuit for the Onion Service, and remove it from
1008 * the list. Closing existing connections is the application's problem.
1010 * XXX: As with the comment in rend_config_services(), a nice abstraction
1011 * would be ideal here, but for now just duplicate the code.
1013 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
1014 if (!circ->marked_for_close &&
1015 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
1016 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
1017 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
1018 if (oc->rend_data == NULL ||
1019 !rend_circuit_pk_digest_eq(oc, (uint8_t *) s->pk_digest)) {
1020 continue;
1022 log_debug(LD_REND, "Closing intro point %s for service %s.",
1023 safe_str_client(extend_info_describe(
1024 oc->build_state->chosen_exit)),
1025 rend_data_get_address(oc->rend_data));
1026 circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
1028 } SMARTLIST_FOREACH_END(circ);
1029 smartlist_remove(rend_service_list, s);
1030 /* Notify that we just removed a service from our global list. */
1031 hs_service_map_has_changed();
1032 rend_service_free(s);
1034 log_debug(LD_CONFIG, "Removed ephemeral Onion Service: %s", service_id);
1036 return 0;
1039 /* There can be 1 second's delay due to second_elapsed_callback, and perhaps
1040 * another few seconds due to blocking calls. */
1041 #define INTRO_CIRC_RETRY_PERIOD_SLOP 10
1043 /** Log information about the intro point creation rate and current intro
1044 * points for service, upgrading the log level from min_severity to warn if
1045 * we have stopped launching new intro point circuits. */
1046 static void
1047 rend_log_intro_limit(const rend_service_t *service, int min_severity)
1049 int exceeded_limit = (service->n_intro_circuits_launched >=
1050 rend_max_intro_circs_per_period(
1051 service->n_intro_points_wanted));
1052 int severity = min_severity;
1053 /* We stopped creating circuits */
1054 if (exceeded_limit) {
1055 severity = LOG_WARN;
1057 time_t intro_period_elapsed = time(NULL) - service->intro_period_started;
1058 tor_assert_nonfatal(intro_period_elapsed >= 0);
1060 char *msg;
1061 static ratelim_t rlimit = RATELIM_INIT(INTRO_CIRC_RETRY_PERIOD);
1062 if ((msg = rate_limit_log(&rlimit, approx_time()))) {
1063 log_fn(severity, LD_REND,
1064 "Hidden service %s %s %d intro points in the last %d seconds. "
1065 "Intro circuit launches are limited to %d per %d seconds.%s",
1066 service->service_id,
1067 exceeded_limit ? "exceeded launch limit with" : "launched",
1068 service->n_intro_circuits_launched,
1069 (int)intro_period_elapsed,
1070 rend_max_intro_circs_per_period(service->n_intro_points_wanted),
1071 INTRO_CIRC_RETRY_PERIOD, msg);
1072 rend_service_dump_stats(severity);
1073 tor_free(msg);
1078 /** Replace the old value of <b>service</b>-\>desc with one that reflects
1079 * the other fields in service.
1081 static void
1082 rend_service_update_descriptor(rend_service_t *service)
1084 rend_service_descriptor_t *d;
1085 int i;
1087 rend_service_descriptor_free(service->desc);
1088 service->desc = NULL;
1090 d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t));
1091 d->pk = crypto_pk_dup_key(service->private_key);
1092 d->timestamp = time(NULL);
1093 d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */
1094 d->intro_nodes = smartlist_new();
1095 /* Support intro protocols 2 and 3. */
1096 d->protocols = (1 << 2) + (1 << 3);
1098 for (i = 0; i < smartlist_len(service->intro_nodes); ++i) {
1099 rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i);
1100 rend_intro_point_t *intro_desc;
1102 /* This intro point won't be listed in the descriptor... */
1103 intro_svc->listed_in_last_desc = 0;
1105 /* circuit_established is set in rend_service_intro_established(), and
1106 * checked every second in rend_consider_services_intro_points(), so it's
1107 * safe to use it here */
1108 if (!intro_svc->circuit_established) {
1109 continue;
1112 /* ...unless this intro point is listed in the descriptor. */
1113 intro_svc->listed_in_last_desc = 1;
1115 /* We have an entirely established intro circuit. Publish it in
1116 * our descriptor. */
1117 intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t));
1118 intro_desc->extend_info = extend_info_dup(intro_svc->extend_info);
1119 if (intro_svc->intro_key)
1120 intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key);
1121 smartlist_add(d->intro_nodes, intro_desc);
1123 if (intro_svc->time_published == -1) {
1124 /* We are publishing this intro point in a descriptor for the
1125 * first time -- note the current time in the service's copy of
1126 * the intro point. */
1127 intro_svc->time_published = time(NULL);
1131 /* Check that we have the right number of intro points */
1132 unsigned int have_intro = (unsigned int)smartlist_len(d->intro_nodes);
1133 if (have_intro != service->n_intro_points_wanted) {
1134 int severity;
1135 /* Getting less than we wanted or more than we're allowed is serious */
1136 if (have_intro < service->n_intro_points_wanted ||
1137 have_intro > NUM_INTRO_POINTS_MAX) {
1138 severity = LOG_WARN;
1139 } else {
1140 /* Getting more than we wanted is weird, but less of a problem */
1141 severity = LOG_NOTICE;
1143 log_fn(severity, LD_REND, "Hidden service %s wanted %d intro points, but "
1144 "descriptor was updated with %d instead.",
1145 service->service_id,
1146 service->n_intro_points_wanted, have_intro);
1147 /* Now log an informative message about how we might have got here. */
1148 rend_log_intro_limit(service, severity);
1152 /* Allocate and return a string containing the path to file_name in
1153 * service->directory. Asserts that service has a directory.
1154 * This function will never return NULL.
1155 * The caller must free this path. */
1156 static char *
1157 rend_service_path(const rend_service_t *service, const char *file_name)
1159 tor_assert(service->directory);
1160 return hs_path_from_filename(service->directory, file_name);
1163 /* Allocate and return a string containing the path to the single onion
1164 * service poison file in service->directory. Asserts that service has a
1165 * directory.
1166 * The caller must free this path. */
1167 STATIC char *
1168 rend_service_sos_poison_path(const rend_service_t *service)
1170 return rend_service_path(service, sos_poison_fname);
1173 /** Return True if hidden services <b>service</b> has been poisoned by single
1174 * onion mode. */
1175 static int
1176 service_is_single_onion_poisoned(const rend_service_t *service)
1178 char *poison_fname = NULL;
1179 file_status_t fstatus;
1181 /* Passing a NULL service is a bug */
1182 if (BUG(!service)) {
1183 return 0;
1186 if (rend_service_is_ephemeral(service)) {
1187 return 0;
1190 poison_fname = rend_service_sos_poison_path(service);
1192 fstatus = file_status(poison_fname);
1193 tor_free(poison_fname);
1195 /* If this fname is occupied, the hidden service has been poisoned.
1196 * fstatus can be FN_ERROR if the service directory does not exist, in that
1197 * case, there is obviously no private key. */
1198 if (fstatus == FN_FILE || fstatus == FN_EMPTY) {
1199 return 1;
1202 return 0;
1205 /* Return 1 if the private key file for service exists and has a non-zero size,
1206 * and 0 otherwise. */
1207 static int
1208 rend_service_private_key_exists(const rend_service_t *service)
1210 char *private_key_path = rend_service_path(service, private_key_fname);
1211 const file_status_t private_key_status = file_status(private_key_path);
1212 tor_free(private_key_path);
1213 /* Only non-empty regular private key files could have been used before.
1214 * fstatus can be FN_ERROR if the service directory does not exist, in that
1215 * case, there is obviously no private key. */
1216 return private_key_status == FN_FILE;
1219 /** Check the single onion service poison state of the directory for s:
1220 * - If the service is poisoned, and we are in Single Onion Mode,
1221 * return 0,
1222 * - If the service is not poisoned, and we are not in Single Onion Mode,
1223 * return 0,
1224 * - Otherwise, the poison state is invalid: the service was created in one
1225 * mode, and is being used in the other, return -1.
1226 * Hidden service directories without keys are always considered consistent.
1227 * They will be poisoned after their directory is created (if needed). */
1228 STATIC int
1229 rend_service_verify_single_onion_poison(const rend_service_t* s,
1230 const or_options_t* options)
1232 /* Passing a NULL service is a bug */
1233 if (BUG(!s)) {
1234 return -1;
1237 /* Ephemeral services are checked at ADD_ONION time */
1238 if (BUG(rend_service_is_ephemeral(s))) {
1239 return -1;
1242 /* Service is expected to have a directory */
1243 if (BUG(!s->directory)) {
1244 return -1;
1247 /* Services without keys are always ok - their keys will only ever be used
1248 * in the current mode */
1249 if (!rend_service_private_key_exists(s)) {
1250 return 0;
1253 /* The key has been used before in a different mode */
1254 if (service_is_single_onion_poisoned(s) !=
1255 rend_service_non_anonymous_mode_enabled(options)) {
1256 return -1;
1259 /* The key exists and is consistent with the current mode */
1260 return 0;
1263 /*** Helper for rend_service_poison_new_single_onion_dir(). Add a file to
1264 * the hidden service directory for s that marks it as a single onion service.
1265 * Tor must be in single onion mode before calling this function, and the
1266 * service directory must already have been created.
1267 * Returns 0 when a directory is successfully poisoned, or if it is already
1268 * poisoned. Returns -1 on a failure to read the directory or write the poison
1269 * file, or if there is an existing private key file in the directory. (The
1270 * service should have been poisoned when the key was created.) */
1271 static int
1272 poison_new_single_onion_hidden_service_dir_impl(const rend_service_t *service,
1273 const or_options_t* options)
1275 /* Passing a NULL service is a bug */
1276 if (BUG(!service)) {
1277 return -1;
1280 /* We must only poison directories if we're in Single Onion mode */
1281 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1283 int fd;
1284 int retval = -1;
1285 char *poison_fname = NULL;
1287 if (rend_service_is_ephemeral(service)) {
1288 log_info(LD_REND, "Ephemeral HS started in non-anonymous mode.");
1289 return 0;
1292 /* Make sure we're only poisoning new hidden service directories */
1293 if (rend_service_private_key_exists(service)) {
1294 log_warn(LD_BUG, "Tried to single onion poison a service directory after "
1295 "the private key was created.");
1296 return -1;
1299 /* Make sure the directory was created before calling this function. */
1300 if (BUG(hs_check_service_private_dir(options->User, service->directory,
1301 service->dir_group_readable, 0) < 0))
1302 return -1;
1304 poison_fname = rend_service_sos_poison_path(service);
1306 switch (file_status(poison_fname)) {
1307 case FN_DIR:
1308 case FN_ERROR:
1309 log_warn(LD_FS, "Can't read single onion poison file \"%s\"",
1310 poison_fname);
1311 goto done;
1312 case FN_FILE: /* single onion poison file already exists. NOP. */
1313 case FN_EMPTY: /* single onion poison file already exists. NOP. */
1314 log_debug(LD_FS, "Tried to re-poison a single onion poisoned file \"%s\"",
1315 poison_fname);
1316 break;
1317 case FN_NOENT:
1318 fd = tor_open_cloexec(poison_fname, O_RDWR|O_CREAT|O_TRUNC, 0600);
1319 if (fd < 0) {
1320 log_warn(LD_FS, "Could not create single onion poison file %s",
1321 poison_fname);
1322 goto done;
1324 close(fd);
1325 break;
1326 default:
1327 tor_assert(0);
1330 retval = 0;
1332 done:
1333 tor_free(poison_fname);
1335 return retval;
1338 /** We just got launched in Single Onion Mode. That's a non-anonymous mode for
1339 * hidden services. If s is new, we should mark its hidden service
1340 * directory appropriately so that it is never launched as a location-private
1341 * hidden service. (New directories don't have private key files.)
1342 * Return 0 on success, -1 on fail. */
1343 STATIC int
1344 rend_service_poison_new_single_onion_dir(const rend_service_t *s,
1345 const or_options_t* options)
1347 /* Passing a NULL service is a bug */
1348 if (BUG(!s)) {
1349 return -1;
1352 /* We must only poison directories if we're in Single Onion mode */
1353 tor_assert(rend_service_non_anonymous_mode_enabled(options));
1355 /* Ephemeral services aren't allowed in non-anonymous mode */
1356 if (BUG(rend_service_is_ephemeral(s))) {
1357 return -1;
1360 /* Service is expected to have a directory */
1361 if (BUG(!s->directory)) {
1362 return -1;
1365 if (!rend_service_private_key_exists(s)) {
1366 if (poison_new_single_onion_hidden_service_dir_impl(s, options)
1367 < 0) {
1368 return -1;
1372 return 0;
1375 /* Return true iff the given service identity key is present on disk. This is
1376 * used to try to learn the service version during configuration time. */
1378 rend_service_key_on_disk(const char *directory_path)
1380 int ret = 0;
1381 char *fname;
1382 crypto_pk_t *pk = NULL;
1384 tor_assert(directory_path);
1386 /* Load key */
1387 fname = hs_path_from_filename(directory_path, private_key_fname);
1388 pk = init_key_from_file(fname, 0, LOG_DEBUG, NULL);
1389 if (pk) {
1390 ret = 1;
1393 crypto_pk_free(pk);
1394 tor_free(fname);
1395 return ret;
1398 /** Load and/or generate private keys for all hidden services, possibly
1399 * including keys for client authorization.
1400 * If a <b>service_list</b> is provided, treat it as the list of hidden
1401 * services (used in unittests). Otherwise, require that rend_service_list is
1402 * not NULL.
1403 * Return 0 on success, -1 on failure. */
1405 rend_service_load_all_keys(const smartlist_t *service_list)
1407 /* Use service_list for unit tests */
1408 const smartlist_t *s_list = rend_get_service_list(service_list);
1409 if (BUG(!s_list)) {
1410 return -1;
1413 SMARTLIST_FOREACH_BEGIN(s_list, rend_service_t *, s) {
1414 if (s->private_key)
1415 continue;
1416 log_info(LD_REND, "Loading hidden-service keys from %s",
1417 rend_service_escaped_dir(s));
1419 if (rend_service_load_keys(s) < 0)
1420 return -1;
1421 } SMARTLIST_FOREACH_END(s);
1423 return 0;
1426 /** Add to <b>lst</b> every filename used by <b>s</b>. */
1427 static void
1428 rend_service_add_filenames_to_list(smartlist_t *lst, const rend_service_t *s)
1430 tor_assert(lst);
1431 tor_assert(s);
1432 tor_assert(s->directory);
1433 smartlist_add(lst, rend_service_path(s, private_key_fname));
1434 smartlist_add(lst, rend_service_path(s, hostname_fname));
1435 smartlist_add(lst, rend_service_path(s, client_keys_fname));
1436 smartlist_add(lst, rend_service_sos_poison_path(s));
1439 /** Add to <b>open_lst</b> every filename used by a configured hidden service,
1440 * and to <b>stat_lst</b> every directory used by a configured hidden
1441 * service */
1442 void
1443 rend_services_add_filenames_to_lists(smartlist_t *open_lst,
1444 smartlist_t *stat_lst)
1446 if (!rend_service_list)
1447 return;
1448 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, s) {
1449 if (!rend_service_is_ephemeral(s)) {
1450 rend_service_add_filenames_to_list(open_lst, s);
1451 smartlist_add_strdup(stat_lst, s->directory);
1453 } SMARTLIST_FOREACH_END(s);
1456 /** Derive all rend_service_t internal material based on the service's key.
1457 * Returns 0 on success, -1 on failure.
1459 static int
1460 rend_service_derive_key_digests(struct rend_service_t *s)
1462 if (rend_get_service_id(s->private_key, s->service_id)<0) {
1463 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1464 return -1;
1466 if (crypto_pk_get_digest(s->private_key, s->pk_digest)<0) {
1467 log_warn(LD_BUG, "Couldn't compute hash of public key.");
1468 return -1;
1471 return 0;
1474 /** Make sure that the directory for <b>s</b> is private, using the config in
1475 * <b>options</b>.
1476 * If <b>create</b> is true:
1477 * - if the directory exists, change permissions if needed,
1478 * - if the directory does not exist, create it with the correct permissions.
1479 * If <b>create</b> is false:
1480 * - if the directory exists, check permissions,
1481 * - if the directory does not exist, check if we think we can create it.
1482 * Return 0 on success, -1 on failure. */
1483 static int
1484 rend_service_check_private_dir(const or_options_t *options,
1485 const rend_service_t *s,
1486 int create)
1488 /* Passing a NULL service is a bug */
1489 if (BUG(!s)) {
1490 return -1;
1493 /* Check/create directory */
1494 if (hs_check_service_private_dir(options->User, s->directory,
1495 s->dir_group_readable, create) < 0) {
1496 return -1;
1499 /* Check if the hidden service key exists, and was created in a different
1500 * single onion service mode, and refuse to launch if it has.
1501 * This is safe to call even when create is false, as it ignores missing
1502 * keys and directories: they are always valid.
1504 if (rend_service_verify_single_onion_poison(s, options) < 0) {
1505 /* We can't use s->service_id here, as the key may not have been loaded */
1506 log_warn(LD_GENERAL, "We are configured with "
1507 "HiddenServiceNonAnonymousMode %d, but the hidden "
1508 "service key in directory %s was created in %s mode. "
1509 "This is not allowed.",
1510 rend_service_non_anonymous_mode_enabled(options) ? 1 : 0,
1511 rend_service_escaped_dir(s),
1512 rend_service_non_anonymous_mode_enabled(options) ?
1513 "an anonymous" : "a non-anonymous"
1515 return -1;
1518 /* Poison new single onion directories immediately after they are created,
1519 * so that we never accidentally launch non-anonymous hidden services
1520 * thinking they are anonymous. Any keys created later will end up with the
1521 * correct poisoning state.
1523 if (create && rend_service_non_anonymous_mode_enabled(options)) {
1524 static int logged_warning = 0;
1526 if (rend_service_poison_new_single_onion_dir(s, options) < 0) {
1527 log_warn(LD_GENERAL,"Failed to mark new hidden services as non-anonymous"
1528 ".");
1529 return -1;
1532 if (!logged_warning) {
1533 /* The keys for these services are linked to the server IP address */
1534 log_notice(LD_REND, "The configured onion service directories have been "
1535 "used in single onion mode. They can not be used for "
1536 "anonymous hidden services.");
1537 logged_warning = 1;
1541 return 0;
1544 /** Load and/or generate private keys for the hidden service <b>s</b>,
1545 * possibly including keys for client authorization. Return 0 on success, -1
1546 * on failure. */
1547 static int
1548 rend_service_load_keys(rend_service_t *s)
1550 char *fname = NULL;
1551 char buf[128];
1553 /* Create the directory if needed which will also poison it in case of
1554 * single onion service. */
1555 if (rend_service_check_private_dir(get_options(), s, 1) < 0)
1556 goto err;
1558 /* Load key */
1559 fname = rend_service_path(s, private_key_fname);
1560 s->private_key = init_key_from_file(fname, 1, LOG_ERR, NULL);
1562 if (!s->private_key)
1563 goto err;
1565 if (rend_service_derive_key_digests(s) < 0)
1566 goto err;
1568 tor_free(fname);
1569 /* Create service file */
1570 fname = rend_service_path(s, hostname_fname);
1572 tor_snprintf(buf, sizeof(buf),"%s.onion\n", s->service_id);
1573 if (write_str_to_file(fname,buf,0)<0) {
1574 log_warn(LD_CONFIG, "Could not write onion address to hostname file.");
1575 goto err;
1577 #ifndef _WIN32
1578 if (s->dir_group_readable) {
1579 /* Also verify hostname file created with group read. */
1580 if (chmod(fname, 0640))
1581 log_warn(LD_FS,"Unable to make hidden hostname file %s group-readable.",
1582 fname);
1584 #endif /* !defined(_WIN32) */
1586 /* If client authorization is configured, load or generate keys. */
1587 if (s->auth_type != REND_NO_AUTH) {
1588 if (rend_service_load_auth_keys(s, fname) < 0) {
1589 goto err;
1593 int r = 0;
1594 goto done;
1595 err:
1596 r = -1;
1597 done:
1598 memwipe(buf, 0, sizeof(buf));
1599 tor_free(fname);
1600 return r;
1603 /** Load and/or generate client authorization keys for the hidden service
1604 * <b>s</b>, which stores its hostname in <b>hfname</b>. Return 0 on success,
1605 * -1 on failure. */
1606 static int
1607 rend_service_load_auth_keys(rend_service_t *s, const char *hfname)
1609 int r = 0;
1610 char *cfname = NULL;
1611 char *client_keys_str = NULL;
1612 strmap_t *parsed_clients = strmap_new();
1613 FILE *cfile, *hfile;
1614 open_file_t *open_cfile = NULL, *open_hfile = NULL;
1615 char desc_cook_out[3*REND_DESC_COOKIE_LEN_BASE64+1];
1616 char service_id[16+1];
1617 char buf[1500];
1619 /* Load client keys and descriptor cookies, if available. */
1620 cfname = rend_service_path(s, client_keys_fname);
1621 client_keys_str = read_file_to_str(cfname, RFTS_IGNORE_MISSING, NULL);
1622 if (client_keys_str) {
1623 if (rend_parse_client_keys(parsed_clients, client_keys_str) < 0) {
1624 log_warn(LD_CONFIG, "Previously stored client_keys file could not "
1625 "be parsed.");
1626 goto err;
1627 } else {
1628 log_info(LD_CONFIG, "Parsed %d previously stored client entries.",
1629 strmap_size(parsed_clients));
1633 /* Prepare client_keys and hostname files. */
1634 if (!(cfile = start_writing_to_stdio_file(cfname,
1635 OPEN_FLAGS_REPLACE | O_TEXT,
1636 0600, &open_cfile))) {
1637 log_warn(LD_CONFIG, "Could not open client_keys file %s",
1638 escaped(cfname));
1639 goto err;
1642 if (!(hfile = start_writing_to_stdio_file(hfname,
1643 OPEN_FLAGS_REPLACE | O_TEXT,
1644 0600, &open_hfile))) {
1645 log_warn(LD_CONFIG, "Could not open hostname file %s", escaped(hfname));
1646 goto err;
1649 /* Either use loaded keys for configured clients or generate new
1650 * ones if a client is new. */
1651 SMARTLIST_FOREACH_BEGIN(s->clients, rend_authorized_client_t *, client) {
1652 rend_authorized_client_t *parsed =
1653 strmap_get(parsed_clients, client->client_name);
1654 int written;
1655 size_t len;
1656 /* Copy descriptor cookie from parsed entry or create new one. */
1657 if (parsed) {
1658 memcpy(client->descriptor_cookie, parsed->descriptor_cookie,
1659 REND_DESC_COOKIE_LEN);
1660 } else {
1661 crypto_rand((char *) client->descriptor_cookie, REND_DESC_COOKIE_LEN);
1663 /* For compatibility with older tor clients, this does not
1664 * truncate the padding characters, unlike rend_auth_encode_cookie. */
1665 if (base64_encode(desc_cook_out, 3*REND_DESC_COOKIE_LEN_BASE64+1,
1666 (char *) client->descriptor_cookie,
1667 REND_DESC_COOKIE_LEN, 0) < 0) {
1668 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1669 goto err;
1671 /* Copy client key from parsed entry or create new one if required. */
1672 if (parsed && parsed->client_key) {
1673 client->client_key = crypto_pk_dup_key(parsed->client_key);
1674 } else if (s->auth_type == REND_STEALTH_AUTH) {
1675 /* Create private key for client. */
1676 crypto_pk_t *prkey = NULL;
1677 if (!(prkey = crypto_pk_new())) {
1678 log_warn(LD_BUG,"Error constructing client key");
1679 goto err;
1681 if (crypto_pk_generate_key(prkey)) {
1682 log_warn(LD_BUG,"Error generating client key");
1683 crypto_pk_free(prkey);
1684 goto err;
1686 if (! crypto_pk_is_valid_private_key(prkey)) {
1687 log_warn(LD_BUG,"Generated client key seems invalid");
1688 crypto_pk_free(prkey);
1689 goto err;
1691 client->client_key = prkey;
1693 /* Add entry to client_keys file. */
1694 written = tor_snprintf(buf, sizeof(buf),
1695 "client-name %s\ndescriptor-cookie %s\n",
1696 client->client_name, desc_cook_out);
1697 if (written < 0) {
1698 log_warn(LD_BUG, "Could not write client entry.");
1699 goto err;
1701 if (client->client_key) {
1702 char *client_key_out = NULL;
1703 if (crypto_pk_write_private_key_to_string(client->client_key,
1704 &client_key_out, &len) != 0) {
1705 log_warn(LD_BUG, "Internal error: "
1706 "crypto_pk_write_private_key_to_string() failed.");
1707 goto err;
1709 if (rend_get_service_id(client->client_key, service_id)<0) {
1710 log_warn(LD_BUG, "Internal error: couldn't encode service ID.");
1712 * len is string length, not buffer length, but last byte is NUL
1713 * anyway.
1715 memwipe(client_key_out, 0, len);
1716 tor_free(client_key_out);
1717 goto err;
1719 written = tor_snprintf(buf + written, sizeof(buf) - written,
1720 "client-key\n%s", client_key_out);
1721 memwipe(client_key_out, 0, len);
1722 tor_free(client_key_out);
1723 if (written < 0) {
1724 log_warn(LD_BUG, "Could not write client entry.");
1725 goto err;
1727 } else {
1728 strlcpy(service_id, s->service_id, sizeof(service_id));
1731 if (fputs(buf, cfile) < 0) {
1732 log_warn(LD_FS, "Could not append client entry to file: %s",
1733 strerror(errno));
1734 goto err;
1737 /* Add line to hostname file. This is not the same encoding as in
1738 * client_keys. */
1739 char *encoded_cookie = rend_auth_encode_cookie(client->descriptor_cookie,
1740 s->auth_type);
1741 if (!encoded_cookie) {
1742 log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
1743 goto err;
1745 tor_snprintf(buf, sizeof(buf), "%s.onion %s # client: %s\n",
1746 service_id, encoded_cookie, client->client_name);
1747 memwipe(encoded_cookie, 0, strlen(encoded_cookie));
1748 tor_free(encoded_cookie);
1750 if (fputs(buf, hfile)<0) {
1751 log_warn(LD_FS, "Could not append host entry to file: %s",
1752 strerror(errno));
1753 goto err;
1755 } SMARTLIST_FOREACH_END(client);
1757 finish_writing_to_file(open_cfile);
1758 finish_writing_to_file(open_hfile);
1760 goto done;
1761 err:
1762 r = -1;
1763 if (open_cfile)
1764 abort_writing_to_file(open_cfile);
1765 if (open_hfile)
1766 abort_writing_to_file(open_hfile);
1767 done:
1768 if (client_keys_str) {
1769 memwipe(client_keys_str, 0, strlen(client_keys_str));
1770 tor_free(client_keys_str);
1772 strmap_free(parsed_clients, rend_authorized_client_free_void);
1774 if (cfname) {
1775 memwipe(cfname, 0, strlen(cfname));
1776 tor_free(cfname);
1779 /* Clear stack buffers that held key-derived material. */
1780 memwipe(buf, 0, sizeof(buf));
1781 memwipe(desc_cook_out, 0, sizeof(desc_cook_out));
1782 memwipe(service_id, 0, sizeof(service_id));
1784 return r;
1787 /** Return the service whose public key has a digest of <b>digest</b>, or
1788 * NULL if no such service exists.
1790 static rend_service_t *
1791 rend_service_get_by_pk_digest(const char* digest)
1793 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s,
1794 if (tor_memeq(s->pk_digest,digest,DIGEST_LEN))
1795 return s);
1796 return NULL;
1799 /** Return the service whose service id is <b>id</b>, or NULL if no such
1800 * service exists.
1802 static struct rend_service_t *
1803 rend_service_get_by_service_id(const char *id)
1805 tor_assert(strlen(id) == REND_SERVICE_ID_LEN_BASE32);
1806 SMARTLIST_FOREACH(rend_service_list, rend_service_t*, s, {
1807 if (tor_memeq(s->service_id, id, REND_SERVICE_ID_LEN_BASE32))
1808 return s;
1810 return NULL;
1813 /** Check client authorization of a given <b>descriptor_cookie</b> of
1814 * length <b>cookie_len</b> for <b>service</b>. Return 1 for success
1815 * and 0 for failure. */
1816 static int
1817 rend_check_authorization(rend_service_t *service,
1818 const char *descriptor_cookie,
1819 size_t cookie_len)
1821 rend_authorized_client_t *auth_client = NULL;
1822 tor_assert(service);
1823 tor_assert(descriptor_cookie);
1824 if (!service->clients) {
1825 log_warn(LD_BUG, "Can't check authorization for a service that has no "
1826 "authorized clients configured.");
1827 return 0;
1830 if (cookie_len != REND_DESC_COOKIE_LEN) {
1831 log_info(LD_REND, "Descriptor cookie is %lu bytes, but we expected "
1832 "%lu bytes. Dropping cell.",
1833 (unsigned long)cookie_len, (unsigned long)REND_DESC_COOKIE_LEN);
1834 return 0;
1837 /* Look up client authorization by descriptor cookie. */
1838 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *, client, {
1839 if (tor_memeq(client->descriptor_cookie, descriptor_cookie,
1840 REND_DESC_COOKIE_LEN)) {
1841 auth_client = client;
1842 break;
1845 if (!auth_client) {
1846 char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
1847 base64_encode(descriptor_cookie_base64, sizeof(descriptor_cookie_base64),
1848 descriptor_cookie, REND_DESC_COOKIE_LEN, 0);
1849 log_info(LD_REND, "No authorization found for descriptor cookie '%s'! "
1850 "Dropping cell!",
1851 descriptor_cookie_base64);
1852 return 0;
1855 /* Allow the request. */
1856 log_info(LD_REND, "Client %s authorized for service %s.",
1857 auth_client->client_name, service->service_id);
1858 return 1;
1861 /* Can this service make a direct connection to ei?
1862 * It must be a single onion service, and the firewall rules must allow ei. */
1863 static int
1864 rend_service_use_direct_connection(const or_options_t* options,
1865 const extend_info_t* ei)
1867 /* We'll connect directly all reachable addresses, whether preferred or not.
1868 * The prefer_ipv6 argument to fascist_firewall_allows_address_addr is
1869 * ignored, because pref_only is 0. */
1870 return (rend_service_allow_non_anonymous_connection(options) &&
1871 fascist_firewall_allows_address_addr(&ei->addr, ei->port,
1872 FIREWALL_OR_CONNECTION, 0, 0));
1875 /* Like rend_service_use_direct_connection, but to a node. */
1876 static int
1877 rend_service_use_direct_connection_node(const or_options_t* options,
1878 const node_t* node)
1880 /* We'll connect directly all reachable addresses, whether preferred or not.
1882 return (rend_service_allow_non_anonymous_connection(options) &&
1883 fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0));
1886 /******
1887 * Handle cells
1888 ******/
1890 /** Respond to an INTRODUCE2 cell by launching a circuit to the chosen
1891 * rendezvous point.
1894 rend_service_receive_introduction(origin_circuit_t *circuit,
1895 const uint8_t *request,
1896 size_t request_len)
1898 /* Global status stuff */
1899 int status = 0, result;
1900 const or_options_t *options = get_options();
1901 char *err_msg = NULL;
1902 int err_msg_severity = LOG_WARN;
1903 const char *stage_descr = NULL, *rend_pk_digest;
1904 int reason = END_CIRC_REASON_TORPROTOCOL;
1905 /* Service/circuit/key stuff we can learn before parsing */
1906 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
1907 rend_service_t *service = NULL;
1908 rend_intro_point_t *intro_point = NULL;
1909 crypto_pk_t *intro_key = NULL;
1910 /* Parsed cell */
1911 rend_intro_cell_t *parsed_req = NULL;
1912 /* Rendezvous point */
1913 extend_info_t *rp = NULL;
1914 /* XXX not handled yet */
1915 char buf[RELAY_PAYLOAD_SIZE];
1916 char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN]; /* Holds KH, Df, Db, Kf, Kb */
1917 int i;
1918 crypto_dh_t *dh = NULL;
1919 origin_circuit_t *launched = NULL;
1920 crypt_path_t *cpath = NULL;
1921 char hexcookie[9];
1922 int circ_needs_uptime;
1923 time_t now = time(NULL);
1924 time_t elapsed;
1925 int replay;
1926 ssize_t keylen;
1928 /* Do some initial validation and logging before we parse the cell */
1929 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) {
1930 log_warn(LD_PROTOCOL,
1931 "Got an INTRODUCE2 over a non-introduction circuit %u.",
1932 (unsigned) circuit->base_.n_circ_id);
1933 goto err;
1936 assert_circ_anonymity_ok(circuit, options);
1937 tor_assert(circuit->rend_data);
1938 /* XXX: This is version 2 specific (only one supported). */
1939 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
1941 /* We'll use this in a bazillion log messages */
1942 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
1943 rend_pk_digest, REND_SERVICE_ID_LEN);
1945 /* look up service depending on circuit. */
1946 service = rend_service_get_by_pk_digest(rend_pk_digest);
1947 if (!service) {
1948 log_warn(LD_BUG,
1949 "Internal error: Got an INTRODUCE2 cell on an intro "
1950 "circ for an unrecognized service %s.",
1951 escaped(serviceid));
1952 goto err;
1955 intro_point = find_intro_point(circuit);
1956 if (intro_point == NULL) {
1957 intro_point = find_expiring_intro_point(service, circuit);
1958 if (intro_point == NULL) {
1959 log_warn(LD_BUG,
1960 "Internal error: Got an INTRODUCE2 cell on an "
1961 "intro circ (for service %s) with no corresponding "
1962 "rend_intro_point_t.",
1963 escaped(serviceid));
1964 goto err;
1968 log_info(LD_REND, "Received INTRODUCE2 cell for service %s on circ %u.",
1969 escaped(serviceid), (unsigned)circuit->base_.n_circ_id);
1971 /* use intro key instead of service key. */
1972 intro_key = circuit->intro_key;
1974 tor_free(err_msg);
1975 stage_descr = NULL;
1977 stage_descr = "early parsing";
1978 /* Early parsing pass (get pk, ciphertext); type 2 is INTRODUCE2 */
1979 parsed_req =
1980 rend_service_begin_parse_intro(request, request_len, 2, &err_msg);
1981 if (!parsed_req) {
1982 goto log_error;
1983 } else if (err_msg) {
1984 log_info(LD_REND, "%s on circ %u.", err_msg,
1985 (unsigned)circuit->base_.n_circ_id);
1986 tor_free(err_msg);
1989 /* make sure service replay caches are present */
1990 if (!service->accepted_intro_dh_parts) {
1991 service->accepted_intro_dh_parts =
1992 replaycache_new(REND_REPLAY_TIME_INTERVAL,
1993 REND_REPLAY_TIME_INTERVAL);
1996 if (!intro_point->accepted_intro_rsa_parts) {
1997 intro_point->accepted_intro_rsa_parts = replaycache_new(0, 0);
2000 /* check for replay of PK-encrypted portion. */
2001 keylen = crypto_pk_keysize(intro_key);
2002 replay = replaycache_add_test_and_elapsed(
2003 intro_point->accepted_intro_rsa_parts,
2004 parsed_req->ciphertext, MIN(parsed_req->ciphertext_len, keylen),
2005 &elapsed);
2007 if (replay) {
2008 log_warn(LD_REND,
2009 "Possible replay detected! We received an "
2010 "INTRODUCE2 cell with same PK-encrypted part %d "
2011 "seconds ago. Dropping cell.",
2012 (int)elapsed);
2013 goto err;
2016 stage_descr = "decryption";
2017 /* Now try to decrypt it */
2018 result = rend_service_decrypt_intro(parsed_req, intro_key, &err_msg);
2019 if (result < 0) {
2020 goto log_error;
2021 } else if (err_msg) {
2022 log_info(LD_REND, "%s on circ %u.", err_msg,
2023 (unsigned)circuit->base_.n_circ_id);
2024 tor_free(err_msg);
2027 stage_descr = "late parsing";
2028 /* Parse the plaintext */
2029 result = rend_service_parse_intro_plaintext(parsed_req, &err_msg);
2030 if (result < 0) {
2031 goto log_error;
2032 } else if (err_msg) {
2033 log_info(LD_REND, "%s on circ %u.", err_msg,
2034 (unsigned)circuit->base_.n_circ_id);
2035 tor_free(err_msg);
2038 stage_descr = "late validation";
2039 /* Validate the parsed plaintext parts */
2040 result = rend_service_validate_intro_late(parsed_req, &err_msg);
2041 if (result < 0) {
2042 goto log_error;
2043 } else if (err_msg) {
2044 log_info(LD_REND, "%s on circ %u.", err_msg,
2045 (unsigned)circuit->base_.n_circ_id);
2046 tor_free(err_msg);
2048 stage_descr = NULL;
2050 /* Increment INTRODUCE2 counter */
2051 ++(intro_point->accepted_introduce2_count);
2053 /* Find the rendezvous point */
2054 rp = find_rp_for_intro(parsed_req, &err_msg);
2055 if (!rp) {
2056 err_msg_severity = LOG_PROTOCOL_WARN;
2057 goto log_error;
2060 /* Check if we'd refuse to talk to this router */
2061 if (options->StrictNodes &&
2062 routerset_contains_extendinfo(options->ExcludeNodes, rp)) {
2063 log_warn(LD_REND, "Client asked to rendezvous at a relay that we "
2064 "exclude, and StrictNodes is set. Refusing service.");
2065 reason = END_CIRC_REASON_INTERNAL; /* XXX might leak why we refused */
2066 goto err;
2069 base16_encode(hexcookie, 9, (const char *)(parsed_req->rc), 4);
2071 /* Check whether there is a past request with the same Diffie-Hellman,
2072 * part 1. */
2073 replay = replaycache_add_test_and_elapsed(
2074 service->accepted_intro_dh_parts,
2075 parsed_req->dh, DH1024_KEY_LEN,
2076 &elapsed);
2078 if (replay) {
2079 /* A Tor client will send a new INTRODUCE1 cell with the same rend
2080 * cookie and DH public key as its previous one if its intro circ
2081 * times out while in state CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT .
2082 * If we received the first INTRODUCE1 cell (the intro-point relay
2083 * converts it into an INTRODUCE2 cell), we are already trying to
2084 * connect to that rend point (and may have already succeeded);
2085 * drop this cell. */
2086 log_info(LD_REND, "We received an "
2087 "INTRODUCE2 cell with same first part of "
2088 "Diffie-Hellman handshake %d seconds ago. Dropping "
2089 "cell.",
2090 (int) elapsed);
2091 goto err;
2094 /* If the service performs client authorization, check included auth data. */
2095 if (service->clients) {
2096 if (parsed_req->version == 3 && parsed_req->u.v3.auth_len > 0) {
2097 if (rend_check_authorization(service,
2098 (const char*)parsed_req->u.v3.auth_data,
2099 parsed_req->u.v3.auth_len)) {
2100 log_info(LD_REND, "Authorization data in INTRODUCE2 cell are valid.");
2101 } else {
2102 log_info(LD_REND, "The authorization data that are contained in "
2103 "the INTRODUCE2 cell are invalid. Dropping cell.");
2104 reason = END_CIRC_REASON_CONNECTFAILED;
2105 goto err;
2107 } else {
2108 log_info(LD_REND, "INTRODUCE2 cell does not contain authentication "
2109 "data, but we require client authorization. Dropping cell.");
2110 reason = END_CIRC_REASON_CONNECTFAILED;
2111 goto err;
2115 /* Try DH handshake... */
2116 dh = crypto_dh_new(DH_TYPE_REND);
2117 if (!dh || crypto_dh_generate_public(dh)<0) {
2118 log_warn(LD_BUG,"Internal error: couldn't build DH state "
2119 "or generate public key.");
2120 reason = END_CIRC_REASON_INTERNAL;
2121 goto err;
2123 if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN, dh,
2124 (char *)(parsed_req->dh),
2125 DH1024_KEY_LEN, keys,
2126 DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
2127 log_warn(LD_BUG, "Internal error: couldn't complete DH handshake");
2128 reason = END_CIRC_REASON_INTERNAL;
2129 goto err;
2132 circ_needs_uptime = hs_service_requires_uptime_circ(service->ports);
2134 /* help predict this next time */
2135 rep_hist_note_used_internal(now, circ_needs_uptime, 1);
2137 /* Launch a circuit to the client's chosen rendezvous point.
2139 int max_rend_failures=hs_get_service_max_rend_failures();
2140 for (i=0;i<max_rend_failures;i++) {
2141 int flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
2142 if (circ_needs_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
2143 /* A Single Onion Service only uses a direct connection if its
2144 * firewall rules permit direct connections to the address.
2146 * We only use a one-hop path on the first attempt. If the first attempt
2147 * fails, we use a 3-hop path for reachability / reliability.
2148 * See the comment in rend_service_relauch_rendezvous() for details. */
2149 if (rend_service_use_direct_connection(options, rp) && i == 0) {
2150 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
2152 launched = circuit_launch_by_extend_info(
2153 CIRCUIT_PURPOSE_S_CONNECT_REND, rp, flags);
2155 if (launched)
2156 break;
2158 if (!launched) { /* give up */
2159 log_warn(LD_REND, "Giving up launching first hop of circuit to rendezvous "
2160 "point %s for service %s.",
2161 safe_str_client(extend_info_describe(rp)),
2162 serviceid);
2163 reason = END_CIRC_REASON_CONNECTFAILED;
2164 goto err;
2166 log_info(LD_REND,
2167 "Accepted intro; launching circuit to %s "
2168 "(cookie %s) for service %s.",
2169 safe_str_client(extend_info_describe(rp)),
2170 hexcookie, serviceid);
2171 tor_assert(launched->build_state);
2172 /* Fill in the circuit's state. */
2174 launched->rend_data =
2175 rend_data_service_create(service->service_id, rend_pk_digest,
2176 parsed_req->rc, service->auth_type);
2178 launched->build_state->service_pending_final_cpath_ref =
2179 tor_malloc_zero(sizeof(crypt_path_reference_t));
2180 launched->build_state->service_pending_final_cpath_ref->refcount = 1;
2182 launched->build_state->service_pending_final_cpath_ref->cpath = cpath =
2183 tor_malloc_zero(sizeof(crypt_path_t));
2184 cpath->magic = CRYPT_PATH_MAGIC;
2185 launched->build_state->expiry_time = now + MAX_REND_TIMEOUT;
2187 cpath->rend_dh_handshake_state = dh;
2188 dh = NULL;
2189 if (circuit_init_cpath_crypto(cpath,
2190 keys+DIGEST_LEN, sizeof(keys)-DIGEST_LEN,
2191 1, 0)<0)
2192 goto err;
2193 memcpy(cpath->rend_circ_nonce, keys, DIGEST_LEN);
2195 goto done;
2197 log_error:
2198 if (!err_msg) {
2199 if (stage_descr) {
2200 tor_asprintf(&err_msg,
2201 "unknown %s error for INTRODUCE2", stage_descr);
2202 } else {
2203 err_msg = tor_strdup("unknown error for INTRODUCE2");
2207 log_fn(err_msg_severity, LD_REND, "%s on circ %u", err_msg,
2208 (unsigned)circuit->base_.n_circ_id);
2209 err:
2210 status = -1;
2211 if (dh) crypto_dh_free(dh);
2212 if (launched) {
2213 circuit_mark_for_close(TO_CIRCUIT(launched), reason);
2215 tor_free(err_msg);
2217 done:
2218 memwipe(keys, 0, sizeof(keys));
2219 memwipe(buf, 0, sizeof(buf));
2220 memwipe(serviceid, 0, sizeof(serviceid));
2221 memwipe(hexcookie, 0, sizeof(hexcookie));
2223 /* Free the parsed cell */
2224 rend_service_free_intro(parsed_req);
2226 /* Free rp */
2227 extend_info_free(rp);
2229 return status;
2232 /** Given a parsed and decrypted INTRODUCE2, find the rendezvous point or
2233 * return NULL and an error string if we can't. Return a newly allocated
2234 * extend_info_t* for the rendezvous point. */
2235 static extend_info_t *
2236 find_rp_for_intro(const rend_intro_cell_t *intro,
2237 char **err_msg_out)
2239 extend_info_t *rp = NULL;
2240 char *err_msg = NULL;
2241 const char *rp_nickname = NULL;
2242 const node_t *node = NULL;
2244 if (!intro) {
2245 if (err_msg_out)
2246 err_msg = tor_strdup("Bad parameters to find_rp_for_intro()");
2248 goto err;
2251 if (intro->version == 0 || intro->version == 1) {
2252 rp_nickname = (const char *)(intro->u.v0_v1.rp);
2254 node = node_get_by_nickname(rp_nickname, NNF_NO_WARN_UNNAMED);
2255 if (!node) {
2256 if (err_msg_out) {
2257 tor_asprintf(&err_msg,
2258 "Couldn't find router %s named in INTRODUCE2 cell",
2259 escaped_safe_str_client(rp_nickname));
2262 goto err;
2265 /* Are we in single onion mode? */
2266 const int allow_direct = rend_service_allow_non_anonymous_connection(
2267 get_options());
2268 rp = extend_info_from_node(node, allow_direct);
2269 if (!rp) {
2270 if (err_msg_out) {
2271 tor_asprintf(&err_msg,
2272 "Couldn't build extend_info_t for router %s named "
2273 "in INTRODUCE2 cell",
2274 escaped_safe_str_client(rp_nickname));
2277 goto err;
2279 } else if (intro->version == 2) {
2280 rp = extend_info_dup(intro->u.v2.extend_info);
2281 } else if (intro->version == 3) {
2282 rp = extend_info_dup(intro->u.v3.extend_info);
2283 } else {
2284 if (err_msg_out) {
2285 tor_asprintf(&err_msg,
2286 "Unknown version %d in INTRODUCE2 cell",
2287 (int)(intro->version));
2290 goto err;
2293 /* rp is always set here: extend_info_dup guarantees a non-NULL result, and
2294 * the other cases goto err. */
2295 tor_assert(rp);
2297 /* Make sure the RP we are being asked to connect to is _not_ a private
2298 * address unless it's allowed. Let's avoid to build a circuit to our
2299 * second middle node and fail right after when extending to the RP. */
2300 if (!extend_info_addr_is_allowed(&rp->addr)) {
2301 if (err_msg_out) {
2302 tor_asprintf(&err_msg,
2303 "Relay IP in INTRODUCE2 cell is private address.");
2305 extend_info_free(rp);
2306 rp = NULL;
2307 goto err;
2309 goto done;
2311 err:
2312 if (err_msg_out)
2313 *err_msg_out = err_msg;
2314 else
2315 tor_free(err_msg);
2317 done:
2318 return rp;
2321 /** Free a parsed INTRODUCE1 or INTRODUCE2 cell that was allocated by
2322 * rend_service_parse_intro().
2324 void
2325 rend_service_free_intro_(rend_intro_cell_t *request)
2327 if (!request) {
2328 return;
2331 /* Free ciphertext */
2332 tor_free(request->ciphertext);
2333 request->ciphertext_len = 0;
2335 /* Have plaintext? */
2336 if (request->plaintext) {
2337 /* Zero it out just to be safe */
2338 memwipe(request->plaintext, 0, request->plaintext_len);
2339 tor_free(request->plaintext);
2340 request->plaintext_len = 0;
2343 /* Have parsed plaintext? */
2344 if (request->parsed) {
2345 switch (request->version) {
2346 case 0:
2347 case 1:
2349 * Nothing more to do; these formats have no further pointers
2350 * in them.
2352 break;
2353 case 2:
2354 extend_info_free(request->u.v2.extend_info);
2355 request->u.v2.extend_info = NULL;
2356 break;
2357 case 3:
2358 if (request->u.v3.auth_data) {
2359 memwipe(request->u.v3.auth_data, 0, request->u.v3.auth_len);
2360 tor_free(request->u.v3.auth_data);
2363 extend_info_free(request->u.v3.extend_info);
2364 request->u.v3.extend_info = NULL;
2365 break;
2366 default:
2367 log_info(LD_BUG,
2368 "rend_service_free_intro() saw unknown protocol "
2369 "version %d.",
2370 request->version);
2374 /* Zero it out to make sure sensitive stuff doesn't hang around in memory */
2375 memwipe(request, 0, sizeof(*request));
2377 tor_free(request);
2380 /** Parse an INTRODUCE1 or INTRODUCE2 cell into a newly allocated
2381 * rend_intro_cell_t structure. Free it with rend_service_free_intro()
2382 * when finished. The type parameter should be 1 or 2 to indicate whether
2383 * this is INTRODUCE1 or INTRODUCE2. This parses only the non-encrypted
2384 * parts; after this, call rend_service_decrypt_intro() with a key, then
2385 * rend_service_parse_intro_plaintext() to finish parsing. The optional
2386 * err_msg_out parameter is set to a string suitable for log output
2387 * if parsing fails. This function does some validation, but only
2388 * that which depends solely on the contents of the cell and the
2389 * key; it can be unit-tested. Further validation is done in
2390 * rend_service_validate_intro().
2393 rend_intro_cell_t *
2394 rend_service_begin_parse_intro(const uint8_t *request,
2395 size_t request_len,
2396 uint8_t type,
2397 char **err_msg_out)
2399 rend_intro_cell_t *rv = NULL;
2400 char *err_msg = NULL;
2402 if (!request || request_len <= 0) goto err;
2403 if (!(type == 1 || type == 2)) goto err;
2405 /* First, check that the cell is long enough to be a sensible INTRODUCE */
2407 /* min key length plus digest length plus nickname length */
2408 if (request_len <
2409 (DIGEST_LEN + REND_COOKIE_LEN + (MAX_NICKNAME_LEN + 1) +
2410 DH1024_KEY_LEN + 42)) {
2411 if (err_msg_out) {
2412 tor_asprintf(&err_msg,
2413 "got a truncated INTRODUCE%d cell",
2414 (int)type);
2416 goto err;
2419 /* Allocate a new parsed cell structure */
2420 rv = tor_malloc_zero(sizeof(*rv));
2422 /* Set the type */
2423 rv->type = type;
2425 /* Copy in the ID */
2426 memcpy(rv->pk, request, DIGEST_LEN);
2428 /* Copy in the ciphertext */
2429 rv->ciphertext = tor_malloc(request_len - DIGEST_LEN);
2430 memcpy(rv->ciphertext, request + DIGEST_LEN, request_len - DIGEST_LEN);
2431 rv->ciphertext_len = request_len - DIGEST_LEN;
2433 goto done;
2435 err:
2436 rend_service_free_intro(rv);
2437 rv = NULL;
2439 if (err_msg_out && !err_msg) {
2440 tor_asprintf(&err_msg,
2441 "unknown INTRODUCE%d error",
2442 (int)type);
2445 done:
2446 if (err_msg_out) *err_msg_out = err_msg;
2447 else tor_free(err_msg);
2449 return rv;
2452 /** Parse the version-specific parts of a v0 or v1 INTRODUCE1 or INTRODUCE2
2453 * cell
2456 static ssize_t
2457 rend_service_parse_intro_for_v0_or_v1(
2458 rend_intro_cell_t *intro,
2459 const uint8_t *buf,
2460 size_t plaintext_len,
2461 char **err_msg_out)
2463 const char *rp_nickname, *endptr;
2464 size_t nickname_field_len, ver_specific_len;
2466 if (intro->version == 1) {
2467 ver_specific_len = MAX_HEX_NICKNAME_LEN + 2;
2468 rp_nickname = ((const char *)buf) + 1;
2469 nickname_field_len = MAX_HEX_NICKNAME_LEN + 1;
2470 } else if (intro->version == 0) {
2471 ver_specific_len = MAX_NICKNAME_LEN + 1;
2472 rp_nickname = (const char *)buf;
2473 nickname_field_len = MAX_NICKNAME_LEN + 1;
2474 } else {
2475 if (err_msg_out)
2476 tor_asprintf(err_msg_out,
2477 "rend_service_parse_intro_for_v0_or_v1() called with "
2478 "bad version %d on INTRODUCE%d cell (this is a bug)",
2479 intro->version,
2480 (int)(intro->type));
2481 goto err;
2484 if (plaintext_len < ver_specific_len) {
2485 if (err_msg_out)
2486 tor_asprintf(err_msg_out,
2487 "short plaintext of encrypted part in v1 INTRODUCE%d "
2488 "cell (%lu bytes, needed %lu)",
2489 (int)(intro->type),
2490 (unsigned long)plaintext_len,
2491 (unsigned long)ver_specific_len);
2492 goto err;
2495 endptr = memchr(rp_nickname, 0, nickname_field_len);
2496 if (!endptr || endptr == rp_nickname) {
2497 if (err_msg_out) {
2498 tor_asprintf(err_msg_out,
2499 "couldn't find a nul-padded nickname in "
2500 "INTRODUCE%d cell",
2501 (int)(intro->type));
2503 goto err;
2506 if ((intro->version == 0 &&
2507 !is_legal_nickname(rp_nickname)) ||
2508 (intro->version == 1 &&
2509 !is_legal_nickname_or_hexdigest(rp_nickname))) {
2510 if (err_msg_out) {
2511 tor_asprintf(err_msg_out,
2512 "bad nickname in INTRODUCE%d cell",
2513 (int)(intro->type));
2515 goto err;
2518 memcpy(intro->u.v0_v1.rp, rp_nickname, endptr - rp_nickname + 1);
2520 return ver_specific_len;
2522 err:
2523 return -1;
2526 /** Parse the version-specific parts of a v2 INTRODUCE1 or INTRODUCE2 cell
2529 static ssize_t
2530 rend_service_parse_intro_for_v2(
2531 rend_intro_cell_t *intro,
2532 const uint8_t *buf,
2533 size_t plaintext_len,
2534 char **err_msg_out)
2536 unsigned int klen;
2537 extend_info_t *extend_info = NULL;
2538 ssize_t ver_specific_len;
2541 * We accept version 3 too so that the v3 parser can call this with
2542 * an adjusted buffer for the latter part of a v3 cell, which is
2543 * identical to a v2 cell.
2545 if (!(intro->version == 2 ||
2546 intro->version == 3)) {
2547 if (err_msg_out)
2548 tor_asprintf(err_msg_out,
2549 "rend_service_parse_intro_for_v2() called with "
2550 "bad version %d on INTRODUCE%d cell (this is a bug)",
2551 intro->version,
2552 (int)(intro->type));
2553 goto err;
2556 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2557 if (plaintext_len < 7 + DIGEST_LEN + 2) {
2558 if (err_msg_out) {
2559 tor_asprintf(err_msg_out,
2560 "truncated plaintext of encrypted parted of "
2561 "version %d INTRODUCE%d cell",
2562 intro->version,
2563 (int)(intro->type));
2566 goto err;
2569 extend_info = tor_malloc_zero(sizeof(extend_info_t));
2570 tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
2571 extend_info->port = ntohs(get_uint16(buf + 5));
2572 memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
2573 extend_info->nickname[0] = '$';
2574 base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
2575 extend_info->identity_digest, DIGEST_LEN);
2576 klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
2578 /* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
2579 if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
2580 if (err_msg_out) {
2581 tor_asprintf(err_msg_out,
2582 "truncated plaintext of encrypted parted of "
2583 "version %d INTRODUCE%d cell",
2584 intro->version,
2585 (int)(intro->type));
2588 goto err;
2591 extend_info->onion_key =
2592 crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
2593 if (!extend_info->onion_key) {
2594 if (err_msg_out) {
2595 tor_asprintf(err_msg_out,
2596 "error decoding onion key in version %d "
2597 "INTRODUCE%d cell",
2598 intro->version,
2599 (intro->type));
2602 goto err;
2604 if (128 != crypto_pk_keysize(extend_info->onion_key)) {
2605 if (err_msg_out) {
2606 tor_asprintf(err_msg_out,
2607 "invalid onion key size in version %d INTRODUCE%d cell",
2608 intro->version,
2609 (intro->type));
2612 goto err;
2615 ver_specific_len = 7+DIGEST_LEN+2+klen;
2617 if (intro->version == 2) intro->u.v2.extend_info = extend_info;
2618 else intro->u.v3.extend_info = extend_info;
2620 return ver_specific_len;
2622 err:
2623 extend_info_free(extend_info);
2625 return -1;
2628 /** Parse the version-specific parts of a v3 INTRODUCE1 or INTRODUCE2 cell
2631 static ssize_t
2632 rend_service_parse_intro_for_v3(
2633 rend_intro_cell_t *intro,
2634 const uint8_t *buf,
2635 size_t plaintext_len,
2636 char **err_msg_out)
2638 ssize_t adjust, v2_ver_specific_len, ts_offset;
2640 /* This should only be called on v3 cells */
2641 if (intro->version != 3) {
2642 if (err_msg_out)
2643 tor_asprintf(err_msg_out,
2644 "rend_service_parse_intro_for_v3() called with "
2645 "bad version %d on INTRODUCE%d cell (this is a bug)",
2646 intro->version,
2647 (int)(intro->type));
2648 goto err;
2652 * Check that we have at least enough to get auth_len:
2654 * 1 octet for version, 1 for auth_type, 2 for auth_len
2656 if (plaintext_len < 4) {
2657 if (err_msg_out) {
2658 tor_asprintf(err_msg_out,
2659 "truncated plaintext of encrypted parted of "
2660 "version %d INTRODUCE%d cell",
2661 intro->version,
2662 (int)(intro->type));
2665 goto err;
2669 * The rend_client_send_introduction() function over in rendclient.c is
2670 * broken (i.e., fails to match the spec) in such a way that we can't
2671 * change it without breaking the protocol. Specifically, it doesn't
2672 * emit auth_len when auth-type is REND_NO_AUTH, so everything is off
2673 * by two bytes after that. Calculate ts_offset and do everything from
2674 * the timestamp on relative to that to handle this dain bramage.
2677 intro->u.v3.auth_type = buf[1];
2678 if (intro->u.v3.auth_type != REND_NO_AUTH) {
2679 intro->u.v3.auth_len = ntohs(get_uint16(buf + 2));
2680 ts_offset = 4 + intro->u.v3.auth_len;
2681 } else {
2682 intro->u.v3.auth_len = 0;
2683 ts_offset = 2;
2686 /* Check that auth len makes sense for this auth type */
2687 if (intro->u.v3.auth_type == REND_BASIC_AUTH ||
2688 intro->u.v3.auth_type == REND_STEALTH_AUTH) {
2689 if (intro->u.v3.auth_len != REND_DESC_COOKIE_LEN) {
2690 if (err_msg_out) {
2691 tor_asprintf(err_msg_out,
2692 "wrong auth data size %d for INTRODUCE%d cell, "
2693 "should be %d",
2694 (int)(intro->u.v3.auth_len),
2695 (int)(intro->type),
2696 REND_DESC_COOKIE_LEN);
2699 goto err;
2703 /* Check that we actually have everything up through the timestamp */
2704 if (plaintext_len < (size_t)(ts_offset)+4) {
2705 if (err_msg_out) {
2706 tor_asprintf(err_msg_out,
2707 "truncated plaintext of encrypted parted of "
2708 "version %d INTRODUCE%d cell",
2709 intro->version,
2710 (int)(intro->type));
2713 goto err;
2716 if (intro->u.v3.auth_type != REND_NO_AUTH &&
2717 intro->u.v3.auth_len > 0) {
2718 /* Okay, we can go ahead and copy auth_data */
2719 intro->u.v3.auth_data = tor_malloc(intro->u.v3.auth_len);
2721 * We know we had an auth_len field in this case, so 4 is
2722 * always right.
2724 memcpy(intro->u.v3.auth_data, buf + 4, intro->u.v3.auth_len);
2728 * From here on, the format is as in v2, so we call the v2 parser with
2729 * adjusted buffer and length. We are 4 + ts_offset octets in, but the
2730 * v2 parser expects to skip over a version byte at the start, so we
2731 * adjust by 3 + ts_offset.
2733 adjust = 3 + ts_offset;
2735 v2_ver_specific_len =
2736 rend_service_parse_intro_for_v2(intro,
2737 buf + adjust, plaintext_len - adjust,
2738 err_msg_out);
2740 /* Success in v2 parser */
2741 if (v2_ver_specific_len >= 0) return v2_ver_specific_len + adjust;
2742 /* Failure in v2 parser; it will have provided an err_msg */
2743 else return v2_ver_specific_len;
2745 err:
2746 return -1;
2749 /** Table of parser functions for version-specific parts of an INTRODUCE2
2750 * cell.
2753 static ssize_t
2754 (*intro_version_handlers[])(
2755 rend_intro_cell_t *,
2756 const uint8_t *,
2757 size_t,
2758 char **) =
2759 { rend_service_parse_intro_for_v0_or_v1,
2760 rend_service_parse_intro_for_v0_or_v1,
2761 rend_service_parse_intro_for_v2,
2762 rend_service_parse_intro_for_v3 };
2764 /** Decrypt the encrypted part of an INTRODUCE1 or INTRODUCE2 cell,
2765 * return 0 if successful, or < 0 and write an error message to
2766 * *err_msg_out if provided.
2770 rend_service_decrypt_intro(
2771 rend_intro_cell_t *intro,
2772 crypto_pk_t *key,
2773 char **err_msg_out)
2775 char *err_msg = NULL;
2776 uint8_t key_digest[DIGEST_LEN];
2777 char service_id[REND_SERVICE_ID_LEN_BASE32+1];
2778 ssize_t key_len;
2779 uint8_t buf[RELAY_PAYLOAD_SIZE];
2780 int result, status = -1;
2782 if (!intro || !key) {
2783 if (err_msg_out) {
2784 err_msg =
2785 tor_strdup("rend_service_decrypt_intro() called with bad "
2786 "parameters");
2789 status = -2;
2790 goto err;
2793 /* Make sure we have ciphertext */
2794 if (!(intro->ciphertext) || intro->ciphertext_len <= 0) {
2795 if (err_msg_out) {
2796 tor_asprintf(&err_msg,
2797 "rend_intro_cell_t was missing ciphertext for "
2798 "INTRODUCE%d cell",
2799 (int)(intro->type));
2801 status = -3;
2802 goto err;
2805 /* Check that this cell actually matches this service key */
2807 /* first DIGEST_LEN bytes of request is intro or service pk digest */
2808 if (crypto_pk_get_digest(key, (char *)key_digest) < 0) {
2809 if (err_msg_out)
2810 *err_msg_out = tor_strdup("Couldn't compute RSA digest.");
2811 log_warn(LD_BUG, "Couldn't compute key digest.");
2812 status = -7;
2813 goto err;
2816 if (tor_memneq(key_digest, intro->pk, DIGEST_LEN)) {
2817 if (err_msg_out) {
2818 base32_encode(service_id, REND_SERVICE_ID_LEN_BASE32 + 1,
2819 (char*)(intro->pk), REND_SERVICE_ID_LEN);
2820 tor_asprintf(&err_msg,
2821 "got an INTRODUCE%d cell for the wrong service (%s)",
2822 (int)(intro->type),
2823 escaped(service_id));
2826 status = -4;
2827 goto err;
2830 /* Make sure the encrypted part is long enough to decrypt */
2832 key_len = crypto_pk_keysize(key);
2833 if (intro->ciphertext_len < key_len) {
2834 if (err_msg_out) {
2835 tor_asprintf(&err_msg,
2836 "got an INTRODUCE%d cell with a truncated PK-encrypted "
2837 "part",
2838 (int)(intro->type));
2841 status = -5;
2842 goto err;
2845 /* Decrypt the encrypted part */
2846 result =
2847 crypto_pk_obsolete_private_hybrid_decrypt(
2848 key, (char *)buf, sizeof(buf),
2849 (const char *)(intro->ciphertext), intro->ciphertext_len,
2850 PK_PKCS1_OAEP_PADDING, 1);
2851 if (result < 0) {
2852 if (err_msg_out) {
2853 tor_asprintf(&err_msg,
2854 "couldn't decrypt INTRODUCE%d cell",
2855 (int)(intro->type));
2857 status = -6;
2858 goto err;
2860 intro->plaintext_len = result;
2861 intro->plaintext = tor_malloc(intro->plaintext_len);
2862 memcpy(intro->plaintext, buf, intro->plaintext_len);
2864 status = 0;
2866 goto done;
2868 err:
2869 if (err_msg_out && !err_msg) {
2870 tor_asprintf(&err_msg,
2871 "unknown INTRODUCE%d error decrypting encrypted part",
2872 intro ? (int)(intro->type) : -1);
2875 done:
2876 if (err_msg_out) *err_msg_out = err_msg;
2877 else tor_free(err_msg);
2879 /* clean up potentially sensitive material */
2880 memwipe(buf, 0, sizeof(buf));
2881 memwipe(key_digest, 0, sizeof(key_digest));
2882 memwipe(service_id, 0, sizeof(service_id));
2884 return status;
2887 /** Parse the plaintext of the encrypted part of an INTRODUCE1 or
2888 * INTRODUCE2 cell, return 0 if successful, or < 0 and write an error
2889 * message to *err_msg_out if provided.
2893 rend_service_parse_intro_plaintext(
2894 rend_intro_cell_t *intro,
2895 char **err_msg_out)
2897 char *err_msg = NULL;
2898 ssize_t ver_specific_len, ver_invariant_len;
2899 uint8_t version;
2900 int status = -1;
2902 if (!intro) {
2903 if (err_msg_out) {
2904 err_msg =
2905 tor_strdup("rend_service_parse_intro_plaintext() called with NULL "
2906 "rend_intro_cell_t");
2909 status = -2;
2910 goto err;
2913 /* Check that we have plaintext */
2914 if (!(intro->plaintext) || intro->plaintext_len <= 0) {
2915 if (err_msg_out) {
2916 err_msg = tor_strdup("rend_intro_cell_t was missing plaintext");
2918 status = -3;
2919 goto err;
2922 /* In all formats except v0, the first byte is a version number */
2923 version = intro->plaintext[0];
2925 /* v0 has no version byte (stupid...), so handle it as a fallback */
2926 if (version > 3) version = 0;
2928 /* Copy the version into the parsed cell structure */
2929 intro->version = version;
2931 /* Call the version-specific parser from the table */
2932 ver_specific_len =
2933 intro_version_handlers[version](intro,
2934 intro->plaintext, intro->plaintext_len,
2935 &err_msg);
2936 if (ver_specific_len < 0) {
2937 status = -4;
2938 goto err;
2941 /** The rendezvous cookie and Diffie-Hellman stuff are version-invariant
2942 * and at the end of the plaintext of the encrypted part of the cell.
2945 ver_invariant_len = intro->plaintext_len - ver_specific_len;
2946 if (ver_invariant_len < REND_COOKIE_LEN + DH1024_KEY_LEN) {
2947 tor_asprintf(&err_msg,
2948 "decrypted plaintext of INTRODUCE%d cell was truncated (%ld bytes)",
2949 (int)(intro->type),
2950 (long)(intro->plaintext_len));
2951 status = -5;
2952 goto err;
2953 } else if (ver_invariant_len > REND_COOKIE_LEN + DH1024_KEY_LEN) {
2954 tor_asprintf(&err_msg,
2955 "decrypted plaintext of INTRODUCE%d cell was too long (%ld bytes)",
2956 (int)(intro->type),
2957 (long)(intro->plaintext_len));
2958 status = -6;
2959 goto err;
2960 } else {
2961 memcpy(intro->rc,
2962 intro->plaintext + ver_specific_len,
2963 REND_COOKIE_LEN);
2964 memcpy(intro->dh,
2965 intro->plaintext + ver_specific_len + REND_COOKIE_LEN,
2966 DH1024_KEY_LEN);
2969 /* Flag it as being fully parsed */
2970 intro->parsed = 1;
2972 status = 0;
2973 goto done;
2975 err:
2976 if (err_msg_out && !err_msg) {
2977 tor_asprintf(&err_msg,
2978 "unknown INTRODUCE%d error parsing encrypted part",
2979 intro ? (int)(intro->type) : -1);
2982 done:
2983 if (err_msg_out) *err_msg_out = err_msg;
2984 else tor_free(err_msg);
2986 return status;
2989 /** Do validity checks on a parsed intro cell after decryption; some of
2990 * these are not done in rend_service_parse_intro_plaintext() itself because
2991 * they depend on a lot of other state and would make it hard to unit test.
2992 * Returns >= 0 if successful or < 0 if the intro cell is invalid, and
2993 * optionally writes out an error message for logging. If an err_msg
2994 * pointer is provided, it is the caller's responsibility to free any
2995 * provided message.
2999 rend_service_validate_intro_late(const rend_intro_cell_t *intro,
3000 char **err_msg_out)
3002 int status = 0;
3004 if (!intro) {
3005 if (err_msg_out)
3006 *err_msg_out =
3007 tor_strdup("NULL intro cell passed to "
3008 "rend_service_validate_intro_late()");
3010 status = -1;
3011 goto err;
3014 if (intro->version == 3 && intro->parsed) {
3015 if (!(intro->u.v3.auth_type == REND_NO_AUTH ||
3016 intro->u.v3.auth_type == REND_BASIC_AUTH ||
3017 intro->u.v3.auth_type == REND_STEALTH_AUTH)) {
3018 /* This is an informative message, not an error, as in the old code */
3019 if (err_msg_out)
3020 tor_asprintf(err_msg_out,
3021 "unknown authorization type %d",
3022 intro->u.v3.auth_type);
3026 err:
3027 return status;
3030 /** Called when we fail building a rendezvous circuit at some point other
3031 * than the last hop: launches a new circuit to the same rendezvous point.
3033 void
3034 rend_service_relaunch_rendezvous(origin_circuit_t *oldcirc)
3036 origin_circuit_t *newcirc;
3037 cpath_build_state_t *newstate, *oldstate;
3039 tor_assert(oldcirc->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
3040 oldstate = oldcirc->build_state;
3041 tor_assert(oldstate);
3043 if (oldstate->service_pending_final_cpath_ref == NULL) {
3044 log_info(LD_REND,"Skipping relaunch of circ that failed on its first hop. "
3045 "Initiator will retry.");
3046 return;
3049 log_info(LD_REND,"Reattempting rendezvous circuit to '%s'",
3050 safe_str(extend_info_describe(oldstate->chosen_exit)));
3052 /* You'd think Single Onion Services would want to retry the rendezvous
3053 * using a direct connection. But if it's blocked by a firewall, or the
3054 * service is IPv6-only, or the rend point avoiding becoming a one-hop
3055 * proxy, we need a 3-hop connection. */
3056 newcirc = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND,
3057 oldstate->chosen_exit,
3058 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
3060 if (!newcirc) {
3061 log_warn(LD_REND,"Couldn't relaunch rendezvous circuit to '%s'.",
3062 safe_str(extend_info_describe(oldstate->chosen_exit)));
3063 return;
3065 newstate = newcirc->build_state;
3066 tor_assert(newstate);
3067 newstate->failure_count = oldstate->failure_count+1;
3068 newstate->expiry_time = oldstate->expiry_time;
3069 newstate->service_pending_final_cpath_ref =
3070 oldstate->service_pending_final_cpath_ref;
3071 ++(newstate->service_pending_final_cpath_ref->refcount);
3073 newcirc->rend_data = rend_data_dup(oldcirc->rend_data);
3076 /** Launch a circuit to serve as an introduction point for the service
3077 * <b>service</b> at the introduction point <b>nickname</b>
3079 static int
3080 rend_service_launch_establish_intro(rend_service_t *service,
3081 rend_intro_point_t *intro)
3083 origin_circuit_t *launched;
3084 int flags = CIRCLAUNCH_NEED_UPTIME|CIRCLAUNCH_IS_INTERNAL;
3085 const or_options_t *options = get_options();
3086 extend_info_t *launch_ei = intro->extend_info;
3087 extend_info_t *direct_ei = NULL;
3089 /* Are we in single onion mode?
3091 * We only use a one-hop path on the first attempt. If the first attempt
3092 * fails, we use a 3-hop path for reachability / reliability.
3093 * (Unlike v3, retries is incremented by the caller after it calls this
3094 * function.)
3096 if (rend_service_allow_non_anonymous_connection(options) &&
3097 intro->circuit_retries == 0) {
3098 /* Do we have a descriptor for the node?
3099 * We've either just chosen it from the consensus, or we've just reviewed
3100 * our intro points to see which ones are still valid, and deleted the ones
3101 * that aren't in the consensus any more. */
3102 const node_t *node = node_get_by_id(launch_ei->identity_digest);
3103 if (BUG(!node)) {
3104 /* The service has kept an intro point after it went missing from the
3105 * consensus. If we did anything else here, it would be a consensus
3106 * distinguisher. Which are less of an issue for single onion services,
3107 * but still a bug. */
3108 return -1;
3110 /* Can we connect to the node directly? If so, replace launch_ei
3111 * (a multi-hop extend_info) with one suitable for direct connection. */
3112 if (rend_service_use_direct_connection_node(options, node)) {
3113 direct_ei = extend_info_from_node(node, 1);
3114 if (BUG(!direct_ei)) {
3115 /* rend_service_use_direct_connection_node and extend_info_from_node
3116 * disagree about which addresses on this node are permitted. This
3117 * should never happen. Avoiding the connection is a safe response. */
3118 return -1;
3120 flags = flags | CIRCLAUNCH_ONEHOP_TUNNEL;
3121 launch_ei = direct_ei;
3124 /* launch_ei is either intro->extend_info, or has been replaced with a valid
3125 * extend_info for single onion service direct connection. */
3126 tor_assert(launch_ei);
3127 /* We must have the same intro when making a direct connection. */
3128 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3129 launch_ei->identity_digest,
3130 DIGEST_LEN));
3132 log_info(LD_REND,
3133 "Launching circuit to introduction point %s%s%s for service %s",
3134 safe_str_client(extend_info_describe(intro->extend_info)),
3135 direct_ei ? " via direct address " : "",
3136 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : "",
3137 service->service_id);
3139 rep_hist_note_used_internal(time(NULL), 1, 0);
3141 ++service->n_intro_circuits_launched;
3142 launched = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_ESTABLISH_INTRO,
3143 launch_ei, flags);
3145 if (!launched) {
3146 log_info(LD_REND,
3147 "Can't launch circuit to establish introduction at %s%s%s.",
3148 safe_str_client(extend_info_describe(intro->extend_info)),
3149 direct_ei ? " via direct address " : "",
3150 direct_ei ? safe_str_client(extend_info_describe(direct_ei)) : ""
3152 extend_info_free(direct_ei);
3153 return -1;
3155 /* We must have the same exit node even if cannibalized or direct connection.
3157 tor_assert(tor_memeq(intro->extend_info->identity_digest,
3158 launched->build_state->chosen_exit->identity_digest,
3159 DIGEST_LEN));
3161 launched->rend_data = rend_data_service_create(service->service_id,
3162 service->pk_digest, NULL,
3163 service->auth_type);
3164 launched->intro_key = crypto_pk_dup_key(intro->intro_key);
3165 if (launched->base_.state == CIRCUIT_STATE_OPEN)
3166 rend_service_intro_has_opened(launched);
3167 extend_info_free(direct_ei);
3168 return 0;
3171 /** Return the number of introduction points that are established for the
3172 * given service. */
3173 static unsigned int
3174 count_established_intro_points(const rend_service_t *service)
3176 unsigned int num = 0;
3178 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro,
3179 num += intro->circuit_established
3181 return num;
3184 /** Return the number of introduction points that are or are being
3185 * established for the given service. This function iterates over all
3186 * circuit and count those that are linked to the service and are waiting
3187 * for the intro point to respond. */
3188 static unsigned int
3189 count_intro_point_circuits(const rend_service_t *service)
3191 unsigned int num_ipos = 0;
3192 SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
3193 if (!circ->marked_for_close &&
3194 circ->state == CIRCUIT_STATE_OPEN &&
3195 (circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3196 circ->purpose == CIRCUIT_PURPOSE_S_INTRO)) {
3197 origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
3198 if (oc->rend_data &&
3199 rend_circuit_pk_digest_eq(oc, (uint8_t *) service->pk_digest)) {
3200 num_ipos++;
3204 SMARTLIST_FOREACH_END(circ);
3205 return num_ipos;
3208 /* Given a buffer of at least RELAY_PAYLOAD_SIZE bytes in <b>cell_body_out</b>,
3209 write the body of a legacy ESTABLISH_INTRO cell in it. Use <b>intro_key</b>
3210 as the intro point auth key, and <b>rend_circ_nonce</b> as the circuit
3211 crypto material. On success, fill <b>cell_body_out</b> and return the number
3212 of bytes written. On fail, return -1.
3214 ssize_t
3215 rend_service_encode_establish_intro_cell(char *cell_body_out,
3216 size_t cell_body_out_len,
3217 crypto_pk_t *intro_key,
3218 const char *rend_circ_nonce)
3220 int retval = -1;
3221 int r;
3222 int len = 0;
3223 char auth[DIGEST_LEN + 9];
3225 tor_assert(intro_key);
3226 tor_assert(rend_circ_nonce);
3228 /* Build the payload for a RELAY_ESTABLISH_INTRO cell. */
3229 r = crypto_pk_asn1_encode(intro_key, cell_body_out+2,
3230 RELAY_PAYLOAD_SIZE-2);
3231 if (r < 0) {
3232 log_warn(LD_BUG, "Internal error; failed to establish intro point.");
3233 goto err;
3235 len = r;
3236 set_uint16(cell_body_out, htons((uint16_t)len));
3237 len += 2;
3238 memcpy(auth, rend_circ_nonce, DIGEST_LEN);
3239 memcpy(auth+DIGEST_LEN, "INTRODUCE", 9);
3240 if (crypto_digest(cell_body_out+len, auth, DIGEST_LEN+9))
3241 goto err;
3242 len += 20;
3243 r = crypto_pk_private_sign_digest(intro_key, cell_body_out+len,
3244 cell_body_out_len - len,
3245 cell_body_out, len);
3246 if (r<0) {
3247 log_warn(LD_BUG, "Internal error: couldn't sign introduction request.");
3248 goto err;
3250 len += r;
3252 retval = len;
3254 err:
3255 memwipe(auth, 0, sizeof(auth));
3257 return retval;
3260 /** Called when we're done building a circuit to an introduction point:
3261 * sends a RELAY_ESTABLISH_INTRO cell.
3263 void
3264 rend_service_intro_has_opened(origin_circuit_t *circuit)
3266 rend_service_t *service;
3267 char buf[RELAY_PAYLOAD_SIZE];
3268 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3269 unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0;
3270 int reason = END_CIRC_REASON_TORPROTOCOL;
3271 const char *rend_pk_digest;
3273 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO);
3274 assert_circ_anonymity_ok(circuit, get_options());
3275 tor_assert(circuit->cpath);
3276 tor_assert(circuit->rend_data);
3277 /* XXX: This is version 2 specific (only on supported). */
3278 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3280 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3281 rend_pk_digest, REND_SERVICE_ID_LEN);
3283 service = rend_service_get_by_pk_digest(rend_pk_digest);
3284 if (!service) {
3285 log_warn(LD_REND, "Unrecognized service ID %s on introduction circuit %u.",
3286 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3287 reason = END_CIRC_REASON_NOSUCHSERVICE;
3288 goto err;
3291 /* Take the current amount of expiring nodes and the current amount of IP
3292 * circuits and compute how many valid IP circuits we have. */
3293 expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes);
3294 num_ip_circuits = count_intro_point_circuits(service);
3295 /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in
3296 * case this condition turns out false because it means that all circuits
3297 * are expiring so we need to keep this circuit. */
3298 if (num_ip_circuits > expiring_nodes_len) {
3299 valid_ip_circuits = num_ip_circuits - expiring_nodes_len;
3302 /* If we already have enough introduction circuits for this service,
3303 * redefine this one as a general circuit or close it, depending.
3304 * Subtract the amount of expiring nodes here because the circuits are
3305 * still opened. */
3306 if (valid_ip_circuits > service->n_intro_points_wanted) {
3307 const or_options_t *options = get_options();
3308 /* Remove the intro point associated with this circuit, it's being
3309 * repurposed or closed thus cleanup memory. */
3310 rend_intro_point_t *intro = find_intro_point(circuit);
3311 if (intro != NULL) {
3312 smartlist_remove(service->intro_nodes, intro);
3313 rend_intro_point_free(intro);
3316 if (options->ExcludeNodes) {
3317 /* XXXX in some future version, we can test whether the transition is
3318 allowed or not given the actual nodes in the circuit. But for now,
3319 this case, we might as well close the thing. */
3320 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3321 "circuit, but we already have enough. Closing it.");
3322 reason = END_CIRC_REASON_NONE;
3323 goto err;
3324 } else {
3325 tor_assert(circuit->build_state->is_internal);
3326 log_info(LD_CIRC|LD_REND, "We have just finished an introduction "
3327 "circuit, but we already have enough. Redefining purpose to "
3328 "general; leaving as internal.");
3330 if (circuit_should_use_vanguards(TO_CIRCUIT(circuit)->purpose)) {
3331 circuit_change_purpose(TO_CIRCUIT(circuit),
3332 CIRCUIT_PURPOSE_HS_VANGUARDS);
3333 } else {
3334 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL);
3338 rend_data_free(circuit->rend_data);
3339 circuit->rend_data = NULL;
3342 crypto_pk_t *intro_key = circuit->intro_key;
3343 circuit->intro_key = NULL;
3344 crypto_pk_free(intro_key);
3347 circuit_has_opened(circuit);
3348 goto done;
3352 log_info(LD_REND,
3353 "Established circuit %u as introduction point for service %s",
3354 (unsigned)circuit->base_.n_circ_id, serviceid);
3355 circuit_log_path(LOG_INFO, LD_REND, circuit);
3357 /* Send the ESTABLISH_INTRO cell */
3359 ssize_t len;
3360 len = rend_service_encode_establish_intro_cell(buf, sizeof(buf),
3361 circuit->intro_key,
3362 circuit->cpath->prev->rend_circ_nonce);
3363 if (len < 0) {
3364 reason = END_CIRC_REASON_INTERNAL;
3365 goto err;
3368 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3369 RELAY_COMMAND_ESTABLISH_INTRO,
3370 buf, len, circuit->cpath->prev)<0) {
3371 log_info(LD_GENERAL,
3372 "Couldn't send introduction request for service %s on circuit %u",
3373 serviceid, (unsigned)circuit->base_.n_circ_id);
3374 goto done;
3378 /* We've attempted to use this circuit */
3379 pathbias_count_use_attempt(circuit);
3381 goto done;
3383 err:
3384 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3385 done:
3386 memwipe(buf, 0, sizeof(buf));
3387 memwipe(serviceid, 0, sizeof(serviceid));
3389 return;
3392 /** Called when we get an INTRO_ESTABLISHED cell; mark the circuit as a
3393 * live introduction point, and note that the service descriptor is
3394 * now out-of-date. */
3396 rend_service_intro_established(origin_circuit_t *circuit,
3397 const uint8_t *request,
3398 size_t request_len)
3400 rend_service_t *service;
3401 rend_intro_point_t *intro;
3402 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3403 (void) request;
3404 (void) request_len;
3405 tor_assert(circuit->rend_data);
3406 /* XXX: This is version 2 specific (only supported one for now). */
3407 const char *rend_pk_digest =
3408 (char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
3410 if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
3411 log_warn(LD_PROTOCOL,
3412 "received INTRO_ESTABLISHED cell on non-intro circuit.");
3413 goto err;
3415 service = rend_service_get_by_pk_digest(rend_pk_digest);
3416 if (!service) {
3417 log_warn(LD_REND, "Unknown service on introduction circuit %u.",
3418 (unsigned)circuit->base_.n_circ_id);
3419 goto err;
3421 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
3422 rend_pk_digest, REND_SERVICE_ID_LEN);
3423 /* We've just successfully established a intro circuit to one of our
3424 * introduction point, account for it. */
3425 intro = find_intro_point(circuit);
3426 if (intro == NULL) {
3427 log_warn(LD_REND,
3428 "Introduction circuit established without a rend_intro_point_t "
3429 "object for service %s on circuit %u",
3430 safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
3431 goto err;
3433 intro->circuit_established = 1;
3434 /* We might not have every introduction point ready but at this point we
3435 * know that the descriptor needs to be uploaded. */
3436 service->desc_is_dirty = time(NULL);
3437 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
3439 log_info(LD_REND,
3440 "Received INTRO_ESTABLISHED cell on circuit %u for service %s",
3441 (unsigned)circuit->base_.n_circ_id, serviceid);
3443 /* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
3444 * used the circ */
3445 pathbias_mark_use_success(circuit);
3447 return 0;
3448 err:
3449 circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
3450 return -1;
3453 /** Called once a circuit to a rendezvous point is established: sends a
3454 * RELAY_COMMAND_RENDEZVOUS1 cell.
3456 void
3457 rend_service_rendezvous_has_opened(origin_circuit_t *circuit)
3459 rend_service_t *service;
3460 char buf[RELAY_PAYLOAD_SIZE];
3461 crypt_path_t *hop;
3462 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3463 char hexcookie[9];
3464 int reason;
3465 const char *rend_cookie, *rend_pk_digest;
3467 tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND);
3468 tor_assert(circuit->cpath);
3469 tor_assert(circuit->build_state);
3470 assert_circ_anonymity_ok(circuit, get_options());
3471 tor_assert(circuit->rend_data);
3473 /* XXX: This is version 2 specific (only one supported). */
3474 rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data,
3475 NULL);
3476 rend_cookie = circuit->rend_data->rend_cookie;
3478 /* Declare the circuit dirty to avoid reuse, and for path-bias. We set the
3479 * timestamp regardless of its content because that circuit could have been
3480 * cannibalized so in any cases, we are about to use that circuit more. */
3481 circuit->base_.timestamp_dirty = time(NULL);
3483 /* This may be redundant */
3484 pathbias_count_use_attempt(circuit);
3486 hop = circuit->build_state->service_pending_final_cpath_ref->cpath;
3488 base16_encode(hexcookie,9, rend_cookie,4);
3489 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
3490 rend_pk_digest, REND_SERVICE_ID_LEN);
3492 log_info(LD_REND,
3493 "Done building circuit %u to rendezvous with "
3494 "cookie %s for service %s",
3495 (unsigned)circuit->base_.n_circ_id, hexcookie, serviceid);
3496 circuit_log_path(LOG_INFO, LD_REND, circuit);
3498 /* Clear the 'in-progress HS circ has timed out' flag for
3499 * consistency with what happens on the client side; this line has
3500 * no effect on Tor's behaviour. */
3501 circuit->hs_circ_has_timed_out = 0;
3503 /* If hop is NULL, another rend circ has already connected to this
3504 * rend point. Close this circ. */
3505 if (hop == NULL) {
3506 log_info(LD_REND, "Another rend circ has already reached this rend point; "
3507 "closing this rend circ.");
3508 reason = END_CIRC_REASON_NONE;
3509 goto err;
3512 /* Remove our final cpath element from the reference, so that no
3513 * other circuit will try to use it. Store it in
3514 * pending_final_cpath for now to ensure that it will be freed if
3515 * our rendezvous attempt fails. */
3516 circuit->build_state->pending_final_cpath = hop;
3517 circuit->build_state->service_pending_final_cpath_ref->cpath = NULL;
3519 service = rend_service_get_by_pk_digest(rend_pk_digest);
3520 if (!service) {
3521 log_warn(LD_GENERAL, "Internal error: unrecognized service ID on "
3522 "rendezvous circuit.");
3523 reason = END_CIRC_REASON_INTERNAL;
3524 goto err;
3527 /* All we need to do is send a RELAY_RENDEZVOUS1 cell... */
3528 memcpy(buf, rend_cookie, REND_COOKIE_LEN);
3529 if (crypto_dh_get_public(hop->rend_dh_handshake_state,
3530 buf+REND_COOKIE_LEN, DH1024_KEY_LEN)<0) {
3531 log_warn(LD_GENERAL,"Couldn't get DH public key.");
3532 reason = END_CIRC_REASON_INTERNAL;
3533 goto err;
3535 memcpy(buf+REND_COOKIE_LEN+DH1024_KEY_LEN, hop->rend_circ_nonce,
3536 DIGEST_LEN);
3538 /* Send the cell */
3539 if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit),
3540 RELAY_COMMAND_RENDEZVOUS1,
3541 buf, HS_LEGACY_RENDEZVOUS_CELL_SIZE,
3542 circuit->cpath->prev)<0) {
3543 log_warn(LD_GENERAL, "Couldn't send RENDEZVOUS1 cell.");
3544 goto done;
3547 crypto_dh_free(hop->rend_dh_handshake_state);
3548 hop->rend_dh_handshake_state = NULL;
3550 /* Append the cpath entry. */
3551 hop->state = CPATH_STATE_OPEN;
3552 /* set the windows to default. these are the windows
3553 * that the service thinks the client has.
3555 hop->package_window = circuit_initial_package_window();
3556 hop->deliver_window = CIRCWINDOW_START;
3558 onion_append_to_cpath(&circuit->cpath, hop);
3559 circuit->build_state->pending_final_cpath = NULL; /* prevent double-free */
3561 /* Change the circuit purpose. */
3562 circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_REND_JOINED);
3564 goto done;
3566 err:
3567 circuit_mark_for_close(TO_CIRCUIT(circuit), reason);
3568 done:
3569 memwipe(buf, 0, sizeof(buf));
3570 memwipe(serviceid, 0, sizeof(serviceid));
3571 memwipe(hexcookie, 0, sizeof(hexcookie));
3573 return;
3577 * Manage introduction points
3580 /** Return the (possibly non-open) introduction circuit ending at
3581 * <b>intro</b> for the service whose public key is <b>pk_digest</b>.
3582 * (<b>desc_version</b> is ignored). Return NULL if no such service is
3583 * found.
3585 static origin_circuit_t *
3586 find_intro_circuit(rend_intro_point_t *intro, const char *pk_digest)
3588 origin_circuit_t *circ = NULL;
3590 tor_assert(intro);
3591 while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3592 (uint8_t *) pk_digest, CIRCUIT_PURPOSE_S_INTRO))) {
3593 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3594 intro->extend_info->identity_digest, DIGEST_LEN) &&
3595 circ->rend_data) {
3596 return circ;
3600 circ = NULL;
3601 while ((circ = circuit_get_next_by_pk_and_purpose(circ,
3602 (uint8_t *) pk_digest,
3603 CIRCUIT_PURPOSE_S_ESTABLISH_INTRO))) {
3604 if (tor_memeq(circ->build_state->chosen_exit->identity_digest,
3605 intro->extend_info->identity_digest, DIGEST_LEN) &&
3606 circ->rend_data) {
3607 return circ;
3610 return NULL;
3613 /** Return the corresponding introdution point using the circuit <b>circ</b>
3614 * found in the <b>service</b>. NULL is returned if not found. */
3615 static rend_intro_point_t *
3616 find_expiring_intro_point(rend_service_t *service, origin_circuit_t *circ)
3618 tor_assert(service);
3619 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3620 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3622 SMARTLIST_FOREACH(service->expiring_nodes, rend_intro_point_t *,
3623 intro_point,
3624 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3625 return intro_point;
3628 return NULL;
3631 /** Return a pointer to the rend_intro_point_t corresponding to the
3632 * service-side introduction circuit <b>circ</b>. */
3633 static rend_intro_point_t *
3634 find_intro_point(origin_circuit_t *circ)
3636 const char *serviceid;
3637 rend_service_t *service = NULL;
3639 tor_assert(TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
3640 TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_INTRO);
3641 tor_assert(circ->rend_data);
3642 serviceid = rend_data_get_address(circ->rend_data);
3644 SMARTLIST_FOREACH(rend_service_list, rend_service_t *, s,
3645 if (tor_memeq(s->service_id, serviceid, REND_SERVICE_ID_LEN_BASE32)) {
3646 service = s;
3647 break;
3650 if (service == NULL) return NULL;
3652 SMARTLIST_FOREACH(service->intro_nodes, rend_intro_point_t *, intro_point,
3653 if (crypto_pk_eq_keys(intro_point->intro_key, circ->intro_key)) {
3654 return intro_point;
3657 return NULL;
3660 /** Upload the rend_encoded_v2_service_descriptor_t's in <b>descs</b>
3661 * associated with the rend_service_descriptor_t <b>renddesc</b> to
3662 * the responsible hidden service directories OR the hidden service
3663 * directories specified by <b>hs_dirs</b>; <b>service_id</b> and
3664 * <b>seconds_valid</b> are only passed for logging purposes.
3666 void
3667 directory_post_to_hs_dir(rend_service_descriptor_t *renddesc,
3668 smartlist_t *descs, smartlist_t *hs_dirs,
3669 const char *service_id, int seconds_valid)
3671 int i, j, failed_upload = 0;
3672 smartlist_t *responsible_dirs = smartlist_new();
3673 smartlist_t *successful_uploads = smartlist_new();
3674 routerstatus_t *hs_dir;
3675 for (i = 0; i < smartlist_len(descs); i++) {
3676 rend_encoded_v2_service_descriptor_t *desc = smartlist_get(descs, i);
3677 /** If any HSDirs are specified, they should be used instead of
3678 * the responsible directories */
3679 if (hs_dirs && smartlist_len(hs_dirs) > 0) {
3680 smartlist_add_all(responsible_dirs, hs_dirs);
3681 } else {
3682 /* Determine responsible dirs. */
3683 if (hid_serv_get_responsible_directories(responsible_dirs,
3684 desc->desc_id) < 0) {
3685 log_warn(LD_REND, "Could not determine the responsible hidden service "
3686 "directories to post descriptors to.");
3687 control_event_hs_descriptor_upload(service_id,
3688 "UNKNOWN",
3689 "UNKNOWN", NULL);
3690 goto done;
3693 for (j = 0; j < smartlist_len(responsible_dirs); j++) {
3694 char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
3695 char *hs_dir_ip;
3696 const node_t *node;
3697 rend_data_t *rend_data;
3698 hs_dir = smartlist_get(responsible_dirs, j);
3699 if (smartlist_contains_digest(renddesc->successful_uploads,
3700 hs_dir->identity_digest))
3701 /* Don't upload descriptor if we succeeded in doing so last time. */
3702 continue;
3703 node = node_get_by_id(hs_dir->identity_digest);
3704 if (!node || !node_has_preferred_descriptor(node,0)) {
3705 log_info(LD_REND, "Not launching upload for for v2 descriptor to "
3706 "hidden service directory %s; we don't have its "
3707 "router descriptor. Queuing for later upload.",
3708 safe_str_client(routerstatus_describe(hs_dir)));
3709 failed_upload = -1;
3710 continue;
3712 /* Send publish request. */
3714 /* We need the service ID to identify which service did the upload
3715 * request. Lookup is made in rend_service_desc_has_uploaded(). */
3716 rend_data = rend_data_client_create(service_id, desc->desc_id, NULL,
3717 REND_NO_AUTH);
3718 directory_request_t *req =
3719 directory_request_new(DIR_PURPOSE_UPLOAD_RENDDESC_V2);
3720 directory_request_set_routerstatus(req, hs_dir);
3721 directory_request_set_indirection(req, DIRIND_ANONYMOUS);
3722 directory_request_set_payload(req,
3723 desc->desc_str, strlen(desc->desc_str));
3724 directory_request_set_rend_query(req, rend_data);
3725 directory_initiate_request(req);
3726 directory_request_free(req);
3728 rend_data_free(rend_data);
3729 base32_encode(desc_id_base32, sizeof(desc_id_base32),
3730 desc->desc_id, DIGEST_LEN);
3731 hs_dir_ip = tor_dup_ip(hs_dir->addr);
3732 log_info(LD_REND, "Launching upload for v2 descriptor for "
3733 "service '%s' with descriptor ID '%s' with validity "
3734 "of %d seconds to hidden service directory '%s' on "
3735 "%s:%d.",
3736 safe_str_client(service_id),
3737 safe_str_client(desc_id_base32),
3738 seconds_valid,
3739 hs_dir->nickname,
3740 hs_dir_ip,
3741 hs_dir->or_port);
3742 control_event_hs_descriptor_upload(service_id,
3743 hs_dir->identity_digest,
3744 desc_id_base32, NULL);
3745 tor_free(hs_dir_ip);
3746 /* Remember successful upload to this router for next time. */
3747 if (!smartlist_contains_digest(successful_uploads,
3748 hs_dir->identity_digest))
3749 smartlist_add(successful_uploads, hs_dir->identity_digest);
3751 smartlist_clear(responsible_dirs);
3753 if (!failed_upload) {
3754 if (renddesc->successful_uploads) {
3755 SMARTLIST_FOREACH(renddesc->successful_uploads, char *, c, tor_free(c););
3756 smartlist_free(renddesc->successful_uploads);
3757 renddesc->successful_uploads = NULL;
3759 renddesc->all_uploads_performed = 1;
3760 } else {
3761 /* Remember which routers worked this time, so that we don't upload the
3762 * descriptor to them again. */
3763 if (!renddesc->successful_uploads)
3764 renddesc->successful_uploads = smartlist_new();
3765 SMARTLIST_FOREACH(successful_uploads, const char *, c, {
3766 if (!smartlist_contains_digest(renddesc->successful_uploads, c)) {
3767 char *hsdir_id = tor_memdup(c, DIGEST_LEN);
3768 smartlist_add(renddesc->successful_uploads, hsdir_id);
3772 done:
3773 smartlist_free(responsible_dirs);
3774 smartlist_free(successful_uploads);
3777 /** Encode and sign an up-to-date service descriptor for <b>service</b>,
3778 * and upload it/them to the responsible hidden service directories.
3780 static void
3781 upload_service_descriptor(rend_service_t *service)
3783 time_t now = time(NULL);
3784 int rendpostperiod;
3785 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
3786 int uploaded = 0;
3788 rendpostperiod = get_options()->RendPostPeriod;
3790 networkstatus_t *c = networkstatus_get_latest_consensus();
3791 if (c && smartlist_len(c->routerstatus_list) > 0) {
3792 int seconds_valid, i, j, num_descs;
3793 smartlist_t *descs = smartlist_new();
3794 smartlist_t *client_cookies = smartlist_new();
3795 /* Either upload a single descriptor (including replicas) or one
3796 * descriptor for each authorized client in case of authorization
3797 * type 'stealth'. */
3798 num_descs = service->auth_type == REND_STEALTH_AUTH ?
3799 smartlist_len(service->clients) : 1;
3800 for (j = 0; j < num_descs; j++) {
3801 crypto_pk_t *client_key = NULL;
3802 rend_authorized_client_t *client = NULL;
3803 smartlist_clear(client_cookies);
3804 switch (service->auth_type) {
3805 case REND_NO_AUTH:
3806 /* Do nothing here. */
3807 break;
3808 case REND_BASIC_AUTH:
3809 SMARTLIST_FOREACH(service->clients, rend_authorized_client_t *,
3810 cl, smartlist_add(client_cookies, cl->descriptor_cookie));
3811 break;
3812 case REND_STEALTH_AUTH:
3813 client = smartlist_get(service->clients, j);
3814 client_key = client->client_key;
3815 smartlist_add(client_cookies, client->descriptor_cookie);
3816 break;
3818 /* Encode the current descriptor. */
3819 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3820 now, 0,
3821 service->auth_type,
3822 client_key,
3823 client_cookies);
3824 if (seconds_valid < 0) {
3825 log_warn(LD_BUG, "Internal error: couldn't encode service "
3826 "descriptor; not uploading.");
3827 smartlist_free(descs);
3828 smartlist_free(client_cookies);
3829 return;
3831 rend_get_service_id(service->desc->pk, serviceid);
3832 if (get_options()->PublishHidServDescriptors) {
3833 /* Post the current descriptors to the hidden service directories. */
3834 log_info(LD_REND, "Launching upload for hidden service %s",
3835 serviceid);
3836 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3837 seconds_valid);
3839 /* Free memory for descriptors. */
3840 for (i = 0; i < smartlist_len(descs); i++)
3841 rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3842 smartlist_clear(descs);
3843 /* Update next upload time. */
3844 if (seconds_valid - REND_TIME_PERIOD_OVERLAPPING_V2_DESCS
3845 > rendpostperiod)
3846 service->next_upload_time = now + rendpostperiod;
3847 else if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS)
3848 service->next_upload_time = now + seconds_valid + 1;
3849 else
3850 service->next_upload_time = now + seconds_valid -
3851 REND_TIME_PERIOD_OVERLAPPING_V2_DESCS + 1;
3852 /* Post also the next descriptors, if necessary. */
3853 if (seconds_valid < REND_TIME_PERIOD_OVERLAPPING_V2_DESCS) {
3854 seconds_valid = rend_encode_v2_descriptors(descs, service->desc,
3855 now, 1,
3856 service->auth_type,
3857 client_key,
3858 client_cookies);
3859 if (seconds_valid < 0) {
3860 log_warn(LD_BUG, "Internal error: couldn't encode service "
3861 "descriptor; not uploading.");
3862 smartlist_free(descs);
3863 smartlist_free(client_cookies);
3864 return;
3866 if (get_options()->PublishHidServDescriptors) {
3867 directory_post_to_hs_dir(service->desc, descs, NULL, serviceid,
3868 seconds_valid);
3870 /* Free memory for descriptors. */
3871 for (i = 0; i < smartlist_len(descs); i++)
3872 rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
3873 smartlist_clear(descs);
3876 smartlist_free(descs);
3877 smartlist_free(client_cookies);
3878 uploaded = 1;
3879 if (get_options()->PublishHidServDescriptors) {
3880 log_info(LD_REND, "Successfully uploaded v2 rend descriptors!");
3881 } else {
3882 log_info(LD_REND, "Successfully stored created v2 rend descriptors!");
3886 /* If not uploaded, try again in one minute. */
3887 if (!uploaded)
3888 service->next_upload_time = now + 60;
3890 /* Unmark dirty flag of this service. */
3891 service->desc_is_dirty = 0;
3894 /** Return the number of INTRODUCE2 cells this hidden service has received
3895 * from this intro point. */
3896 static int
3897 intro_point_accepted_intro_count(rend_intro_point_t *intro)
3899 return intro->accepted_introduce2_count;
3902 /** Return non-zero iff <b>intro</b> should 'expire' now (i.e. we
3903 * should stop publishing it in new descriptors and eventually close
3904 * it). */
3905 static int
3906 intro_point_should_expire_now(rend_intro_point_t *intro,
3907 time_t now)
3909 tor_assert(intro != NULL);
3911 if (intro->time_published == -1) {
3912 /* Don't expire an intro point if we haven't even published it yet. */
3913 return 0;
3916 if (intro_point_accepted_intro_count(intro) >=
3917 intro->max_introductions) {
3918 /* This intro point has been used too many times. Expire it now. */
3919 return 1;
3922 if (intro->time_to_expire == -1) {
3923 /* This intro point has been published, but we haven't picked an
3924 * expiration time for it. Pick one now. */
3925 int intro_point_lifetime_seconds =
3926 crypto_rand_int_range(INTRO_POINT_LIFETIME_MIN_SECONDS,
3927 INTRO_POINT_LIFETIME_MAX_SECONDS);
3929 /* Start the expiration timer now, rather than when the intro
3930 * point was first published. There shouldn't be much of a time
3931 * difference. */
3932 intro->time_to_expire = now + intro_point_lifetime_seconds;
3934 return 0;
3937 /* This intro point has a time to expire set already. Use it. */
3938 return (now >= intro->time_to_expire);
3941 /** Iterate over intro points in the given service and remove the invalid
3942 * ones. For an intro point object to be considered invalid, the circuit
3943 * _and_ node need to have disappeared.
3945 * If the intro point should expire, it's placed into the expiring_nodes
3946 * list of the service and removed from the active intro nodes list.
3948 * If <b>exclude_nodes</b> is not NULL, add the valid nodes to it.
3950 * If <b>retry_nodes</b> is not NULL, add the valid node to it if the
3951 * circuit disappeared but the node is still in the consensus. */
3952 static void
3953 remove_invalid_intro_points(rend_service_t *service,
3954 smartlist_t *exclude_nodes,
3955 smartlist_t *retry_nodes, time_t now)
3957 tor_assert(service);
3959 /* Remove any expired nodes that doesn't have a circuit. */
3960 SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
3961 intro) {
3962 origin_circuit_t *intro_circ =
3963 find_intro_circuit(intro, service->pk_digest);
3964 if (intro_circ) {
3965 continue;
3967 /* No more circuit, cleanup the into point object. */
3968 SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
3969 rend_intro_point_free(intro);
3970 } SMARTLIST_FOREACH_END(intro);
3972 SMARTLIST_FOREACH_BEGIN(service->intro_nodes, rend_intro_point_t *,
3973 intro) {
3974 /* Find the introduction point node object. */
3975 const node_t *node =
3976 node_get_by_id(intro->extend_info->identity_digest);
3977 /* Find the intro circuit, this might be NULL. */
3978 origin_circuit_t *intro_circ =
3979 find_intro_circuit(intro, service->pk_digest);
3981 /* Add the valid node to the exclusion list so we don't try to establish
3982 * an introduction point to it again. */
3983 if (node && exclude_nodes) {
3984 smartlist_add(exclude_nodes, (void*) node);
3987 /* First, make sure we still have a valid circuit for this intro point.
3988 * If we dont, we'll give up on it and make a new one. */
3989 if (intro_circ == NULL) {
3990 log_info(LD_REND, "Attempting to retry on %s as intro point for %s"
3991 " (circuit disappeared).",
3992 safe_str_client(extend_info_describe(intro->extend_info)),
3993 safe_str_client(service->service_id));
3994 /* We've lost the circuit for this intro point, flag it so it can be
3995 * accounted for when considiring uploading a descriptor. */
3996 intro->circuit_established = 0;
3998 /* Node is gone or we've reached our maximum circuit creationg retry
3999 * count, clean up everything, we'll find a new one. */
4000 if (node == NULL ||
4001 intro->circuit_retries >= MAX_INTRO_POINT_CIRCUIT_RETRIES) {
4002 rend_intro_point_free(intro);
4003 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
4004 /* We've just killed the intro point, nothing left to do. */
4005 continue;
4008 /* The intro point is still alive so let's try to use it again because
4009 * we have a published descriptor containing it. Keep the intro point
4010 * in the intro_nodes list because it's still valid, we are rebuilding
4011 * a circuit to it. */
4012 if (retry_nodes) {
4013 smartlist_add(retry_nodes, intro);
4016 /* else, the circuit is valid so in both cases, node being alive or not,
4017 * we leave the circuit and intro point object as is. Closing the
4018 * circuit here would leak new consensus timing and freeing the intro
4019 * point object would make the intro circuit unusable. */
4021 /* Now, check if intro point should expire. If it does, queue it so
4022 * it can be cleaned up once it has been replaced properly. */
4023 if (intro_point_should_expire_now(intro, now)) {
4024 log_info(LD_REND, "Expiring %s as intro point for %s.",
4025 safe_str_client(extend_info_describe(intro->extend_info)),
4026 safe_str_client(service->service_id));
4027 /* We might have put it in the retry list if so, undo. */
4028 if (retry_nodes) {
4029 smartlist_remove(retry_nodes, intro);
4031 smartlist_add(service->expiring_nodes, intro);
4032 SMARTLIST_DEL_CURRENT(service->intro_nodes, intro);
4033 /* Intro point is expired, we need a new one thus don't consider it
4034 * anymore has a valid established intro point. */
4035 intro->circuit_established = 0;
4037 } SMARTLIST_FOREACH_END(intro);
4040 /** A new descriptor has been successfully uploaded for the given
4041 * <b>rend_data</b>. Remove and free the expiring nodes from the associated
4042 * service. */
4043 void
4044 rend_service_desc_has_uploaded(const rend_data_t *rend_data)
4046 rend_service_t *service;
4047 const char *onion_address;
4049 tor_assert(rend_data);
4051 onion_address = rend_data_get_address(rend_data);
4053 service = rend_service_get_by_service_id(onion_address);
4054 if (service == NULL) {
4055 return;
4058 SMARTLIST_FOREACH_BEGIN(service->expiring_nodes, rend_intro_point_t *,
4059 intro) {
4060 origin_circuit_t *intro_circ =
4061 find_intro_circuit(intro, service->pk_digest);
4062 if (intro_circ != NULL) {
4063 circuit_mark_for_close(TO_CIRCUIT(intro_circ),
4064 END_CIRC_REASON_FINISHED);
4066 SMARTLIST_DEL_CURRENT(service->expiring_nodes, intro);
4067 rend_intro_point_free(intro);
4068 } SMARTLIST_FOREACH_END(intro);
4071 /** Don't try to build more than this many circuits before giving up
4072 * for a while. Dynamically calculated based on the configured number of
4073 * introduction points for the service, n_intro_points_wanted. */
4074 static int
4075 rend_max_intro_circs_per_period(unsigned int n_intro_points_wanted)
4077 /* Allow all but one of the initial connections to fail and be
4078 * retried. (If all fail, we *want* to wait, because something is broken.) */
4079 tor_assert(n_intro_points_wanted <= NUM_INTRO_POINTS_MAX);
4081 /* For the normal use case, 3 intro points plus 2 extra for performance and
4082 * allow that twice because once every 24h or so, we can do it twice for two
4083 * descriptors that is the current one and the next one. So (3 + 2) * 2 ==
4084 * 12 allowed attempts for one period. */
4085 return ((n_intro_points_wanted + NUM_INTRO_POINTS_EXTRA) * 2);
4088 /** For every service, check how many intro points it currently has, and:
4089 * - Invalidate introdution points based on specific criteria, see
4090 * remove_invalid_intro_points comments.
4091 * - Pick new intro points as necessary.
4092 * - Launch circuits to any new intro points.
4094 * This is called once a second by the main loop.
4096 void
4097 rend_consider_services_intro_points(time_t now)
4099 int i;
4100 const or_options_t *options = get_options();
4101 /* Are we in single onion mode? */
4102 const int allow_direct = rend_service_allow_non_anonymous_connection(
4103 get_options());
4104 /* List of nodes we need to _exclude_ when choosing a new node to
4105 * establish an intro point to. */
4106 smartlist_t *exclude_nodes;
4107 /* List of nodes we need to retry to build a circuit on them because the
4108 * node is valid but circuit died. */
4109 smartlist_t *retry_nodes;
4111 if (!have_completed_a_circuit())
4112 return;
4114 exclude_nodes = smartlist_new();
4115 retry_nodes = smartlist_new();
4117 SMARTLIST_FOREACH_BEGIN(rend_service_list, rend_service_t *, service) {
4118 int r;
4119 /* Number of intro points we want to open and add to the intro nodes
4120 * list of the service. */
4121 unsigned int n_intro_points_to_open;
4122 /* Have an unsigned len so we can use it to compare values else gcc is
4123 * not happy with unmatching signed comparaison. */
4124 unsigned int intro_nodes_len;
4125 /* Different service are allowed to have the same introduction point as
4126 * long as they are on different circuit thus why we clear this list. */
4127 smartlist_clear(exclude_nodes);
4128 smartlist_clear(retry_nodes);
4130 /* Cleanup the invalid intro points and save the node objects, if any,
4131 * in the exclude_nodes and retry_nodes lists. */
4132 remove_invalid_intro_points(service, exclude_nodes, retry_nodes, now);
4134 /* This retry period is important here so we don't stress circuit
4135 * creation. */
4137 if (now > service->intro_period_started + INTRO_CIRC_RETRY_PERIOD) {
4138 /* One period has elapsed:
4139 * - if we stopped, we can try building circuits again,
4140 * - if we haven't, we reset the circuit creation counts. */
4141 rend_log_intro_limit(service, LOG_INFO);
4142 service->intro_period_started = now;
4143 service->n_intro_circuits_launched = 0;
4144 } else if (service->n_intro_circuits_launched >=
4145 rend_max_intro_circs_per_period(
4146 service->n_intro_points_wanted)) {
4147 /* We have failed too many times in this period; wait for the next
4148 * one before we try to initiate any more connections. */
4149 rend_log_intro_limit(service, LOG_WARN);
4150 continue;
4153 /* Let's try to rebuild circuit on the nodes we want to retry on. */
4154 SMARTLIST_FOREACH_BEGIN(retry_nodes, rend_intro_point_t *, intro) {
4155 r = rend_service_launch_establish_intro(service, intro);
4156 if (r < 0) {
4157 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4158 safe_str_client(extend_info_describe(intro->extend_info)),
4159 safe_str_client(service->service_id));
4160 /* Unable to launch a circuit to that intro point, remove it from
4161 * the valid list so we can create a new one. */
4162 smartlist_remove(service->intro_nodes, intro);
4163 rend_intro_point_free(intro);
4164 continue;
4166 intro->circuit_retries++;
4167 } SMARTLIST_FOREACH_END(intro);
4169 /* Avoid mismatched signed comparaison below. */
4170 intro_nodes_len = (unsigned int) smartlist_len(service->intro_nodes);
4172 /* Quiescent state, we have more or the equal amount of wanted node for
4173 * this service. Proceed to the next service. We can have more nodes
4174 * because we launch extra preemptive circuits if our intro nodes list was
4175 * originally empty for performance reasons. */
4176 if (intro_nodes_len >= service->n_intro_points_wanted) {
4177 continue;
4180 /* Number of intro points we want to open which is the wanted amount minus
4181 * the current amount of valid nodes. We know that this won't underflow
4182 * because of the check above. */
4183 n_intro_points_to_open = service->n_intro_points_wanted - intro_nodes_len;
4184 if (intro_nodes_len == 0) {
4185 /* We want to end up with n_intro_points_wanted intro points, but if
4186 * we have no intro points at all (chances are they all cycled or we
4187 * are starting up), we launch NUM_INTRO_POINTS_EXTRA extra circuits
4188 * and use the first n_intro_points_wanted that complete. See proposal
4189 * #155, section 4 for the rationale of this which is purely for
4190 * performance.
4192 * The ones after the first n_intro_points_to_open will be converted
4193 * to 'general' internal circuits in rend_service_intro_has_opened(),
4194 * and then we'll drop them from the list of intro points. */
4195 n_intro_points_to_open += NUM_INTRO_POINTS_EXTRA;
4198 for (i = 0; i < (int) n_intro_points_to_open; i++) {
4199 const node_t *node;
4200 rend_intro_point_t *intro;
4201 router_crn_flags_t flags = CRN_NEED_UPTIME|CRN_NEED_DESC;
4202 router_crn_flags_t direct_flags = flags;
4203 direct_flags |= CRN_PREF_ADDR;
4204 direct_flags |= CRN_DIRECT_CONN;
4206 node = router_choose_random_node(exclude_nodes,
4207 options->ExcludeNodes,
4208 allow_direct ? direct_flags : flags);
4209 /* If we are in single onion mode, retry node selection for a 3-hop
4210 * path */
4211 if (allow_direct && !node) {
4212 log_info(LD_REND,
4213 "Unable to find an intro point that we can connect to "
4214 "directly for %s, falling back to a 3-hop path.",
4215 safe_str_client(service->service_id));
4216 node = router_choose_random_node(exclude_nodes,
4217 options->ExcludeNodes, flags);
4220 if (!node) {
4221 log_warn(LD_REND,
4222 "We only have %d introduction points established for %s; "
4223 "wanted %u.",
4224 smartlist_len(service->intro_nodes),
4225 safe_str_client(service->service_id),
4226 n_intro_points_to_open);
4227 break;
4229 /* Add the chosen node to the exclusion list in order to avoid picking
4230 * it again in the next iteration. */
4231 smartlist_add(exclude_nodes, (void*)node);
4232 intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4233 /* extend_info is for clients, so we want the multi-hop primary ORPort,
4234 * even if we are a single onion service and intend to connect to it
4235 * directly ourselves. */
4236 intro->extend_info = extend_info_from_node(node, 0);
4237 if (BUG(intro->extend_info == NULL)) {
4238 break;
4240 intro->intro_key = crypto_pk_new();
4241 const int fail = crypto_pk_generate_key(intro->intro_key);
4242 tor_assert(!fail);
4243 intro->time_published = -1;
4244 intro->time_to_expire = -1;
4245 intro->max_introductions =
4246 crypto_rand_int_range(INTRO_POINT_MIN_LIFETIME_INTRODUCTIONS,
4247 INTRO_POINT_MAX_LIFETIME_INTRODUCTIONS);
4248 smartlist_add(service->intro_nodes, intro);
4249 log_info(LD_REND, "Picked router %s as an intro point for %s.",
4250 safe_str_client(node_describe(node)),
4251 safe_str_client(service->service_id));
4252 /* Establish new introduction circuit to our chosen intro point. */
4253 r = rend_service_launch_establish_intro(service, intro);
4254 if (r < 0) {
4255 log_warn(LD_REND, "Error launching circuit to node %s for service %s.",
4256 safe_str_client(extend_info_describe(intro->extend_info)),
4257 safe_str_client(service->service_id));
4258 /* This funcion will be called again by the main loop so this intro
4259 * point without a intro circuit will be retried on or removed after
4260 * a maximum number of attempts. */
4263 } SMARTLIST_FOREACH_END(service);
4264 smartlist_free(exclude_nodes);
4265 smartlist_free(retry_nodes);
4268 #define MIN_REND_INITIAL_POST_DELAY (30)
4269 #define MIN_REND_INITIAL_POST_DELAY_TESTING (5)
4271 /** Regenerate and upload rendezvous service descriptors for all
4272 * services, if necessary. If the descriptor has been dirty enough
4273 * for long enough, definitely upload; else only upload when the
4274 * periodic timeout has expired.
4276 * For the first upload, pick a random time between now and two periods
4277 * from now, and pick it independently for each service.
4279 void
4280 rend_consider_services_upload(time_t now)
4282 int i;
4283 rend_service_t *service;
4284 const or_options_t *options = get_options();
4285 int rendpostperiod = options->RendPostPeriod;
4286 int rendinitialpostdelay = (options->TestingTorNetwork ?
4287 MIN_REND_INITIAL_POST_DELAY_TESTING :
4288 MIN_REND_INITIAL_POST_DELAY);
4290 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4291 service = smartlist_get(rend_service_list, i);
4292 if (!service->next_upload_time) { /* never been uploaded yet */
4293 /* The fixed lower bound of rendinitialpostdelay seconds ensures that
4294 * the descriptor is stable before being published. See comment below. */
4295 service->next_upload_time =
4296 now + rendinitialpostdelay + crypto_rand_int(2*rendpostperiod);
4297 /* Single Onion Services prioritise availability over hiding their
4298 * startup time, as their IP address is publicly discoverable anyway.
4300 if (rend_service_reveal_startup_time(options)) {
4301 service->next_upload_time = now + rendinitialpostdelay;
4304 /* Does every introduction points have been established? */
4305 unsigned int intro_points_ready =
4306 count_established_intro_points(service) >=
4307 service->n_intro_points_wanted;
4308 if (intro_points_ready &&
4309 (service->next_upload_time < now ||
4310 (service->desc_is_dirty &&
4311 service->desc_is_dirty < now-rendinitialpostdelay))) {
4312 /* if it's time, or if the directory servers have a wrong service
4313 * descriptor and ours has been stable for rendinitialpostdelay seconds,
4314 * upload a new one of each format. */
4315 rend_service_update_descriptor(service);
4316 upload_service_descriptor(service);
4321 /** True if the list of available router descriptors might have changed so
4322 * that we should have a look whether we can republish previously failed
4323 * rendezvous service descriptors. */
4324 static int consider_republishing_rend_descriptors = 1;
4326 /** Called when our internal view of the directory has changed, so that we
4327 * might have router descriptors of hidden service directories available that
4328 * we did not have before. */
4329 void
4330 rend_hsdir_routers_changed(void)
4332 consider_republishing_rend_descriptors = 1;
4335 /** Consider republication of v2 rendezvous service descriptors that failed
4336 * previously, but without regenerating descriptor contents.
4338 void
4339 rend_consider_descriptor_republication(void)
4341 int i;
4342 rend_service_t *service;
4344 if (!consider_republishing_rend_descriptors)
4345 return;
4346 consider_republishing_rend_descriptors = 0;
4348 if (!get_options()->PublishHidServDescriptors)
4349 return;
4351 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4352 service = smartlist_get(rend_service_list, i);
4353 if (service->desc && !service->desc->all_uploads_performed) {
4354 /* If we failed in uploading a descriptor last time, try again *without*
4355 * updating the descriptor's contents. */
4356 upload_service_descriptor(service);
4361 /** Log the status of introduction points for all rendezvous services
4362 * at log severity <b>severity</b>.
4364 void
4365 rend_service_dump_stats(int severity)
4367 int i,j;
4368 rend_service_t *service;
4369 rend_intro_point_t *intro;
4370 const char *safe_name;
4371 origin_circuit_t *circ;
4373 for (i=0; i < smartlist_len(rend_service_list); ++i) {
4374 service = smartlist_get(rend_service_list, i);
4375 tor_log(severity, LD_GENERAL, "Service configured in %s:",
4376 rend_service_escaped_dir(service));
4377 for (j=0; j < smartlist_len(service->intro_nodes); ++j) {
4378 intro = smartlist_get(service->intro_nodes, j);
4379 safe_name = safe_str_client(intro->extend_info->nickname);
4381 circ = find_intro_circuit(intro, service->pk_digest);
4382 if (!circ) {
4383 tor_log(severity, LD_GENERAL, " Intro point %d at %s: no circuit",
4384 j, safe_name);
4385 continue;
4387 tor_log(severity, LD_GENERAL, " Intro point %d at %s: circuit is %s",
4388 j, safe_name, circuit_state_to_string(circ->base_.state));
4393 /** Given <b>conn</b>, a rendezvous exit stream, look up the hidden service for
4394 * <b>circ</b>, and look up the port and address based on conn-\>port.
4395 * Assign the actual conn-\>addr and conn-\>port. Return -2 on failure
4396 * for which the circuit should be closed, -1 on other failure,
4397 * or 0 for success.
4400 rend_service_set_connection_addr_port(edge_connection_t *conn,
4401 origin_circuit_t *circ)
4403 rend_service_t *service;
4404 char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
4405 const char *rend_pk_digest;
4407 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
4408 tor_assert(circ->rend_data);
4409 log_debug(LD_REND,"beginning to hunt for addr/port");
4410 rend_pk_digest = (char *) rend_data_get_pk_digest(circ->rend_data, NULL);
4411 base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1,
4412 rend_pk_digest, REND_SERVICE_ID_LEN);
4413 service = rend_service_get_by_pk_digest(rend_pk_digest);
4414 if (!service) {
4415 log_warn(LD_REND, "Couldn't find any service associated with pk %s on "
4416 "rendezvous circuit %u; closing.",
4417 serviceid, (unsigned)circ->base_.n_circ_id);
4418 return -2;
4420 if (service->max_streams_per_circuit > 0) {
4421 /* Enforce the streams-per-circuit limit, and refuse to provide a
4422 * mapping if this circuit will exceed the limit. */
4423 #define MAX_STREAM_WARN_INTERVAL 600
4424 static struct ratelim_t stream_ratelim =
4425 RATELIM_INIT(MAX_STREAM_WARN_INTERVAL);
4426 if (circ->rend_data->nr_streams >= service->max_streams_per_circuit) {
4427 log_fn_ratelim(&stream_ratelim, LOG_WARN, LD_REND,
4428 "Maximum streams per circuit limit reached on rendezvous "
4429 "circuit %u; %s. Circuit has %d out of %d streams.",
4430 (unsigned)circ->base_.n_circ_id,
4431 service->max_streams_close_circuit ?
4432 "closing circuit" :
4433 "ignoring open stream request",
4434 circ->rend_data->nr_streams,
4435 service->max_streams_per_circuit);
4436 return service->max_streams_close_circuit ? -2 : -1;
4440 if (hs_set_conn_addr_port(service->ports, conn) == 0) {
4441 /* Successfully set the port to the connection. We are done. */
4442 return 0;
4445 log_info(LD_REND,
4446 "No virtual port mapping exists for port %d on service %s",
4447 conn->base_.port, serviceid);
4449 if (service->allow_unknown_ports)
4450 return -1;
4451 else
4452 return -2;
4455 /* Are HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode consistent?
4457 static int
4458 rend_service_non_anonymous_mode_consistent(const or_options_t *options)
4460 /* !! is used to make these options boolean */
4461 return (!! options->HiddenServiceSingleHopMode ==
4462 !! options->HiddenServiceNonAnonymousMode);
4465 /* Do the options allow onion services to make direct (non-anonymous)
4466 * connections to introduction or rendezvous points?
4467 * Must only be called after options_validate_single_onion() has successfully
4468 * checked onion service option consistency.
4469 * Returns true if tor is in HiddenServiceSingleHopMode. */
4471 rend_service_allow_non_anonymous_connection(const or_options_t *options)
4473 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4474 return options->HiddenServiceSingleHopMode ? 1 : 0;
4477 /* Do the options allow us to reveal the exact startup time of the onion
4478 * service?
4479 * Single Onion Services prioritise availability over hiding their
4480 * startup time, as their IP address is publicly discoverable anyway.
4481 * Must only be called after options_validate_single_onion() has successfully
4482 * checked onion service option consistency.
4483 * Returns true if tor is in non-anonymous hidden service mode. */
4485 rend_service_reveal_startup_time(const or_options_t *options)
4487 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4488 return rend_service_non_anonymous_mode_enabled(options);
4491 /* Is non-anonymous mode enabled using the HiddenServiceNonAnonymousMode
4492 * config option?
4493 * Must only be called after options_validate_single_onion() has successfully
4494 * checked onion service option consistency.
4497 rend_service_non_anonymous_mode_enabled(const or_options_t *options)
4499 tor_assert(rend_service_non_anonymous_mode_consistent(options));
4500 return options->HiddenServiceNonAnonymousMode ? 1 : 0;
4503 #ifdef TOR_UNIT_TESTS
4505 STATIC void
4506 set_rend_service_list(smartlist_t *new_list)
4508 rend_service_list = new_list;
4511 STATIC void
4512 set_rend_rend_service_staging_list(smartlist_t *new_list)
4514 rend_service_staging_list = new_list;
4517 #endif /* defined(TOR_UNIT_TESTS) */