1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
10 * \brief Implements the details of building circuits (by choosing paths,
11 * constructing/sending create/extend cells, and so on).
13 * On the client side, this module handles launching circuits. Circuit
14 * launches are srtarted from circuit_establish_circuit(), called from
15 * circuit_launch_by_extend_info()). To choose the path the circuit will
16 * take, onion_extend_cpath() calls into a maze of node selection functions.
18 * Once the circuit is ready to be launched, the first hop is treated as a
19 * special case with circuit_handle_first_hop(), since it might need to open a
20 * channel. As the channel opens, and later as CREATED and RELAY_EXTENDED
21 * cells arrive, the client will invoke circuit_send_next_onion_skin() to send
22 * CREATE or RELAY_EXTEND cells.
24 * The server side is handled in feature/relay/circuitbuild_relay.c.
27 #define CIRCUITBUILD_PRIVATE
28 #define OCIRC_EVENT_PRIVATE
30 #include "core/or/or.h"
31 #include "app/config/config.h"
32 #include "lib/confmgt/confmgt.h"
33 #include "core/crypto/hs_ntor.h"
34 #include "core/crypto/onion_crypto.h"
35 #include "core/crypto/onion_fast.h"
36 #include "core/crypto/onion_tap.h"
37 #include "core/mainloop/connection.h"
38 #include "core/mainloop/mainloop.h"
39 #include "core/or/channel.h"
40 #include "core/or/circuitbuild.h"
41 #include "core/or/circuitlist.h"
42 #include "core/or/circuitstats.h"
43 #include "core/or/circuituse.h"
44 #include "core/or/circuitpadding.h"
45 #include "core/or/command.h"
46 #include "core/or/connection_edge.h"
47 #include "core/or/connection_or.h"
48 #include "core/or/extendinfo.h"
49 #include "core/or/onion.h"
50 #include "core/or/ocirc_event.h"
51 #include "core/or/policies.h"
52 #include "core/or/relay.h"
53 #include "core/or/trace_probes_circuit.h"
54 #include "core/or/crypt_path.h"
55 #include "feature/client/bridges.h"
56 #include "feature/client/circpathbias.h"
57 #include "feature/client/entrynodes.h"
58 #include "feature/client/transports.h"
59 #include "feature/control/control_events.h"
60 #include "feature/dircommon/directory.h"
61 #include "feature/nodelist/describe.h"
62 #include "feature/nodelist/microdesc.h"
63 #include "feature/nodelist/networkstatus.h"
64 #include "feature/nodelist/nickname.h"
65 #include "feature/nodelist/node_select.h"
66 #include "feature/nodelist/nodelist.h"
67 #include "feature/nodelist/routerlist.h"
68 #include "feature/nodelist/routerset.h"
69 #include "feature/relay/router.h"
70 #include "feature/relay/routermode.h"
71 #include "feature/relay/selftest.h"
72 #include "feature/stats/predict_ports.h"
73 #include "lib/crypt_ops/crypto_rand.h"
74 #include "lib/trace/events.h"
76 #include "core/or/cell_st.h"
77 #include "core/or/cpath_build_state_st.h"
78 #include "core/or/entry_connection_st.h"
79 #include "core/or/extend_info_st.h"
80 #include "feature/nodelist/node_st.h"
81 #include "core/or/or_circuit_st.h"
82 #include "core/or/origin_circuit_st.h"
84 static int circuit_send_first_onion_skin(origin_circuit_t
*circ
);
85 static int circuit_build_no_more_hops(origin_circuit_t
*circ
);
86 static int circuit_send_intermediate_onion_skin(origin_circuit_t
*circ
,
88 static const node_t
*choose_good_middle_server(uint8_t purpose
,
89 cpath_build_state_t
*state
,
93 /** This function tries to get a channel to the specified endpoint,
94 * and then calls command_setup_channel() to give it the right
97 MOCK_IMPL(channel_t
*,
98 channel_connect_for_circuit
,(const extend_info_t
*ei
))
102 const tor_addr_port_t
*orport
= extend_info_pick_orport(ei
);
105 const char *id_digest
= ei
->identity_digest
;
106 const ed25519_public_key_t
*ed_id
= &ei
->ed_identity
;
108 chan
= channel_connect(&orport
->addr
, orport
->port
, id_digest
, ed_id
);
109 if (chan
) command_setup_channel(chan
);
114 /** Search for a value for circ_id that we can use on <b>chan</b> for an
115 * outbound circuit, until we get a circ_id that is not in use by any other
116 * circuit on that conn.
118 * Return it, or 0 if can't get a unique circ_id.
121 get_unique_circ_id_by_chan(channel_t
*chan
)
123 /* This number is chosen somewhat arbitrarily; see comment below for more
124 * info. When the space is 80% full, it gives a one-in-a-million failure
125 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
126 * the space is 95% full, it gives a one-in-26 failure chance. That seems
127 * okay, though you could make a case IMO for anything between N=32 and
129 #define MAX_CIRCID_ATTEMPTS 64
131 unsigned n_with_circ
= 0, n_pending_destroy
= 0, n_weird_pending_destroy
= 0;
132 circid_t test_circ_id
;
134 circid_t high_bit
, max_range
, mask
;
135 int64_t pending_destroy_time_total
= 0;
136 int64_t pending_destroy_time_max
= 0;
140 if (chan
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
142 "Trying to pick a circuit ID for a connection from "
143 "a client with no identity.");
146 max_range
= (chan
->wide_circ_ids
) ? (1u<<31) : (1u<<15);
147 mask
= max_range
- 1;
148 high_bit
= (chan
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? max_range
: 0;
150 if (++attempts
> MAX_CIRCID_ATTEMPTS
) {
151 /* Make sure we don't loop forever because all circuit IDs are used.
153 * Once, we would try until we had tried every possible circuit ID. But
154 * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
155 * circuit IDs, and then give up.
157 * This potentially causes us to give up early if our circuit ID space
158 * is nearly full. If we have N circuit IDs in use, then we will reject
159 * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
160 * This means that in practice, a few percent of our circuit ID capacity
163 * The alternative here, though, is to do a linear search over the
164 * whole circuit ID space every time we extend a circuit, which is
165 * not so great either.
167 int64_t queued_destroys
;
168 char *m
= rate_limit_log(&chan
->last_warned_circ_ids_exhausted
,
171 return 0; /* This message has been rate-limited away. */
172 if (n_pending_destroy
)
173 pending_destroy_time_total
/= n_pending_destroy
;
174 log_warn(LD_CIRC
,"No unused circIDs found on channel %s wide "
175 "circID support, with %u inbound and %u outbound circuits. "
176 "Found %u circuit IDs in use by circuits, and %u with "
177 "pending destroy cells. (%u of those were marked bogusly.) "
178 "The ones with pending destroy cells "
179 "have been marked unusable for an average of %ld seconds "
180 "and a maximum of %ld seconds. This channel is %ld seconds "
181 "old. Failing a circuit.%s",
182 chan
->wide_circ_ids
? "with" : "without",
183 chan
->num_p_circuits
, chan
->num_n_circuits
,
184 n_with_circ
, n_pending_destroy
, n_weird_pending_destroy
,
185 (long)pending_destroy_time_total
,
186 (long)pending_destroy_time_max
,
187 (long)(approx_time() - chan
->timestamp_created
),
192 /* This warning should be impossible. */
193 log_warn(LD_BUG
, " This channel somehow has no cmux on it!");
197 /* analysis so far on 12184 suggests that we're running out of circuit
198 IDs because it looks like we have too many pending destroy
199 cells. Let's see how many we really have pending.
201 queued_destroys
= circuitmux_count_queued_destroy_cells(chan
,
204 log_warn(LD_CIRC
, " Circuitmux on this channel has %u circuits, "
205 "of which %u are active. It says it has %"PRId64
206 " destroy cells queued.",
207 circuitmux_num_circuits(chan
->cmux
),
208 circuitmux_num_active_circuits(chan
->cmux
),
211 /* Change this into "if (1)" in order to get more information about
212 * possible failure modes here. You'll need to know how to use gdb with
213 * Tor: this will make Tor exit with an assertion failure if the cmux is
216 circuitmux_assert_okay(chan
->cmux
);
218 channel_dump_statistics(chan
, LOG_WARN
);
224 crypto_rand((char*) &test_circ_id
, sizeof(test_circ_id
));
225 test_circ_id
&= mask
;
226 } while (test_circ_id
== 0);
228 test_circ_id
|= high_bit
;
230 in_use
= circuit_id_in_use_on_channel(test_circ_id
, chan
);
233 else if (in_use
== 2) {
237 circuit_id_when_marked_unusable_on_channel(test_circ_id
, chan
);
239 time_t waiting
= approx_time() - since_when
;
240 pending_destroy_time_total
+= waiting
;
241 if (waiting
> pending_destroy_time_max
)
242 pending_destroy_time_max
= waiting
;
244 ++n_weird_pending_destroy
;
251 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
252 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
253 * list information about link status in a more verbose format using spaces.
254 * If <b>verbose_names</b> is false, give hex digests; if <b>verbose_names</b>
255 * is true, use $DIGEST=Name style names.
258 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
261 smartlist_t
*elements
;
262 const char *states
[] = {"closed", "waiting for keys", "open"};
265 elements
= smartlist_new();
268 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
269 smartlist_add_asprintf(elements
, "%s%s circ (length %d%s%s):",
270 circ
->build_state
->is_internal
? "internal" : "exit",
271 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
272 circ
->build_state
->desired_path_len
,
273 circ
->base_
.state
== CIRCUIT_STATE_OPEN
? "" : ", last hop ",
274 circ
->base_
.state
== CIRCUIT_STATE_OPEN
? "" :
275 (nickname
?nickname
:"*unnamed*"));
285 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
287 if (!hop
->extend_info
)
289 id
= hop
->extend_info
->identity_digest
;
291 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
292 if ((node
= node_get_by_id(id
))) {
293 node_get_verbose_nickname(node
, elt
);
294 } else if (is_legal_nickname(hop
->extend_info
->nickname
)) {
296 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
297 elt
[HEX_DIGEST_LEN
+1]= '~';
298 strlcpy(elt
+HEX_DIGEST_LEN
+2,
299 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
302 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
304 } else { /* ! verbose_names */
305 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
307 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
311 tor_assert(hop
->state
<= 2);
312 smartlist_add_asprintf(elements
,"%s(%s)",elt
,states
[hop
->state
]);
315 smartlist_add(elements
, elt
);
318 } while (hop
!= circ
->cpath
);
320 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
321 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
322 smartlist_free(elements
);
326 /** If <b>verbose</b> is false, allocate and return a comma-separated
327 * list of the currently built elements of <b>circ</b>. If
328 * <b>verbose</b> is true, also list information about link status in
329 * a more verbose format using spaces.
332 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
334 return circuit_list_path_impl(circ
, verbose
, 0);
337 /** Allocate and return a comma-separated list of the currently built elements
338 * of <b>circ</b>, giving each as a verbose nickname.
341 circuit_list_path_for_controller(origin_circuit_t
*circ
)
343 return circuit_list_path_impl(circ
, 0, 1);
346 /** Log, at severity <b>severity</b>, the nicknames of each router in
347 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
351 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
353 char *s
= circuit_list_path(circ
,1);
354 tor_log(severity
,domain
,"%s",s
);
358 /** Return 1 iff every node in circ's cpath definitely supports ntor. */
360 circuit_cpath_supports_ntor(const origin_circuit_t
*circ
)
362 crypt_path_t
*head
, *cpath
;
364 cpath
= head
= circ
->cpath
;
366 /* if the extend_info is missing, we can't tell if it supports ntor */
367 if (!cpath
->extend_info
) {
371 /* if the key is blank, it definitely doesn't support ntor */
372 if (!extend_info_supports_ntor(cpath
->extend_info
)) {
376 } while (cpath
!= head
);
381 /** Pick all the entries in our cpath. Stop and return 0 when we're
382 * happy, or return -1 if an error occurs. */
384 onion_populate_cpath(origin_circuit_t
*circ
)
388 /* onion_extend_cpath assumes these are non-NULL */
390 tor_assert(circ
->build_state
);
393 r
= onion_extend_cpath(circ
);
395 log_info(LD_CIRC
,"Generating cpath hop failed.");
400 /* The path is complete */
403 /* Does every node in this path support ntor? */
404 int path_supports_ntor
= circuit_cpath_supports_ntor(circ
);
406 /* We would like every path to support ntor, but we have to allow for some
408 tor_assert(circuit_get_cpath_len(circ
));
409 if (circuit_can_use_tap(circ
)) {
410 /* Circuits from clients to intro points, and hidden services to rend
411 * points do not support ntor, because the hidden service protocol does
412 * not include ntor onion keys. This is also true for Single Onion
417 if (circuit_get_cpath_len(circ
) == 1) {
418 /* Allow for bootstrapping: when we're fetching directly from a fallback,
419 * authority, or bridge, we have no way of knowing its ntor onion key
420 * before we connect to it. So instead, we try connecting, and end up using
422 tor_assert(circ
->cpath
);
423 tor_assert(circ
->cpath
->extend_info
);
424 const node_t
*node
= node_get_by_id(
425 circ
->cpath
->extend_info
->identity_digest
);
426 /* If we don't know the node and its descriptor, we must be bootstrapping.
428 if (!node
|| !node_has_preferred_descriptor(node
, 1)) {
433 if (BUG(!path_supports_ntor
)) {
434 /* If we're building a multi-hop path, and it's not one of the HS or
435 * bootstrapping exceptions, and it doesn't support ntor, something has
443 /** Create and return a new origin circuit. Initialize its purpose and
444 * build-state based on our arguments. The <b>flags</b> argument is a
445 * bitfield of CIRCLAUNCH_* flags, see circuit_launch_by_extend_info() for
448 origin_circuit_init(uint8_t purpose
, int flags
)
450 /* sets circ->p_circ_id and circ->p_chan */
451 origin_circuit_t
*circ
= origin_circuit_new();
452 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_CHAN_WAIT
);
453 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
454 circ
->build_state
->onehop_tunnel
=
455 ((flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) ? 1 : 0);
456 circ
->build_state
->need_uptime
=
457 ((flags
& CIRCLAUNCH_NEED_UPTIME
) ? 1 : 0);
458 circ
->build_state
->need_capacity
=
459 ((flags
& CIRCLAUNCH_NEED_CAPACITY
) ? 1 : 0);
460 circ
->build_state
->is_internal
=
461 ((flags
& CIRCLAUNCH_IS_INTERNAL
) ? 1 : 0);
462 circ
->build_state
->is_ipv6_selftest
=
463 ((flags
& CIRCLAUNCH_IS_IPV6_SELFTEST
) ? 1 : 0);
464 circ
->base_
.purpose
= purpose
;
468 /** Build a new circuit for <b>purpose</b>. If <b>exit</b> is defined, then use
469 * that as your exit router, else choose a suitable exit node. The <b>flags</b>
470 * argument is a bitfield of CIRCLAUNCH_* flags, see
471 * circuit_launch_by_extend_info() for more details.
473 * Also launch a connection to the first OR in the chosen path, if
474 * it's not open already.
477 circuit_establish_circuit(uint8_t purpose
, extend_info_t
*exit_ei
, int flags
)
479 origin_circuit_t
*circ
;
481 int is_hs_v3_rp_circuit
= 0;
483 if (flags
& CIRCLAUNCH_IS_V3_RP
) {
484 is_hs_v3_rp_circuit
= 1;
487 circ
= origin_circuit_init(purpose
, flags
);
489 if (onion_pick_cpath_exit(circ
, exit_ei
, is_hs_v3_rp_circuit
) < 0 ||
490 onion_populate_cpath(circ
) < 0) {
491 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
495 circuit_event_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
497 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
498 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
502 tor_trace(TR_SUBSYS(circuit
), TR_EV(establish
), circ
);
506 /** Return the guard state associated with <b>circ</b>, which may be NULL. */
507 circuit_guard_state_t
*
508 origin_circuit_get_guard_state(origin_circuit_t
*circ
)
510 return circ
->guard_state
;
514 * Helper function to publish a channel association message
516 * circuit_handle_first_hop() calls this to notify subscribers about a
517 * channel launch event, which associates a circuit with a channel.
518 * This doesn't always correspond to an assignment of the circuit's
519 * n_chan field, because that seems to be only for fully-open
523 circuit_chan_publish(const origin_circuit_t
*circ
, const channel_t
*chan
)
525 ocirc_chan_msg_t
*msg
= tor_malloc(sizeof(*msg
));
527 msg
->gid
= circ
->global_identifier
;
528 msg
->chan
= chan
->global_identifier
;
529 msg
->onehop
= circ
->build_state
->onehop_tunnel
;
531 ocirc_chan_publish(msg
);
534 /** Start establishing the first hop of our circuit. Figure out what
535 * OR we should connect to, and if necessary start the connection to
536 * it. If we're already connected, then send the 'create' cell.
537 * Return 0 for ok, -reason if circ should be marked-for-close. */
539 circuit_handle_first_hop(origin_circuit_t
*circ
)
541 crypt_path_t
*firsthop
;
544 const char *msg
= NULL
;
545 int should_launch
= 0;
546 const or_options_t
*options
= get_options();
548 firsthop
= cpath_get_next_non_open_hop(circ
->cpath
);
549 tor_assert(firsthop
);
550 tor_assert(firsthop
->extend_info
);
552 /* Some bridges are on private addresses. Others pass a dummy private
553 * address to the pluggable transport, which ignores it.
554 * Deny the connection if:
555 * - the address is internal, and
556 * - we're not connecting to a configured bridge, and
557 * - we're not configured to allow extends to private addresses. */
558 if (extend_info_any_orport_addr_is_internal(firsthop
->extend_info
) &&
559 !extend_info_is_a_configured_bridge(firsthop
->extend_info
) &&
560 !options
->ExtendAllowPrivateAddresses
) {
561 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
562 "Client asked me to connect directly to a private address");
563 return -END_CIRC_REASON_TORPROTOCOL
;
566 /* now see if we're already connected to the first OR in 'route' */
567 const tor_addr_port_t
*orport4
=
568 extend_info_get_orport(firsthop
->extend_info
, AF_INET
);
569 const tor_addr_port_t
*orport6
=
570 extend_info_get_orport(firsthop
->extend_info
, AF_INET6
);
571 n_chan
= channel_get_for_extend(
572 firsthop
->extend_info
->identity_digest
,
573 &firsthop
->extend_info
->ed_identity
,
574 orport4
? &orport4
->addr
: NULL
,
575 orport6
? &orport6
->addr
: NULL
,
581 /* not currently connected in a useful way. */
582 log_info(LD_CIRC
, "Next router is %s: %s",
583 safe_str_client(extend_info_describe(firsthop
->extend_info
)),
585 circ
->base_
.n_hop
= extend_info_dup(firsthop
->extend_info
);
588 n_chan
= channel_connect_for_circuit(firsthop
->extend_info
);
589 if (!n_chan
) { /* connect failed, forget the whole thing */
590 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
591 return -END_CIRC_REASON_CONNECTFAILED
;
593 /* We didn't find a channel, but we're launching one for an origin
594 * circuit. (If we decided not to launch a channel, then we found at
595 * least one once good in-progress channel use for this circuit, and
596 * marked it in channel_get_for_extend().) */
597 channel_mark_as_used_for_origin_circuit(n_chan
);
598 circuit_chan_publish(circ
, n_chan
);
601 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
602 /* return success. The onion/circuit/etc will be taken care of
603 * automatically (may already have been) whenever n_chan reaches
604 * OR_CONN_STATE_OPEN.
607 } else { /* it's already open. use it. */
608 tor_assert(!circ
->base_
.n_hop
);
609 circ
->base_
.n_chan
= n_chan
;
610 /* We found a channel, and we're using it for an origin circuit. */
611 channel_mark_as_used_for_origin_circuit(n_chan
);
612 circuit_chan_publish(circ
, n_chan
);
613 log_debug(LD_CIRC
,"Conn open for %s. Delivering first onion skin.",
614 safe_str_client(extend_info_describe(firsthop
->extend_info
)));
615 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
616 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
617 circ
->base_
.n_chan
= NULL
;
624 /** Find any circuits that are waiting on <b>or_conn</b> to become
625 * open and get them to send their create cells forward.
627 * Status is 1 if connect succeeded, or 0 if connect failed.
629 * Close_origin_circuits is 1 if we should close all the origin circuits
630 * through this channel, or 0 otherwise. (This happens when we want to retry
634 circuit_n_chan_done(channel_t
*chan
, int status
, int close_origin_circuits
)
636 smartlist_t
*pending_circs
;
641 log_debug(LD_CIRC
,"chan to %s, status=%d",
642 channel_describe_peer(chan
), status
);
644 pending_circs
= smartlist_new();
645 circuit_get_all_pending_on_channel(pending_circs
, chan
);
647 SMARTLIST_FOREACH_BEGIN(pending_circs
, circuit_t
*, circ
)
649 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
650 * leaving them in in case it's possible for the status of a circuit to
651 * change as we're going down the list. */
652 if (circ
->marked_for_close
|| circ
->n_chan
|| !circ
->n_hop
||
653 circ
->state
!= CIRCUIT_STATE_CHAN_WAIT
)
656 const char *rsa_ident
= NULL
;
657 const ed25519_public_key_t
*ed_ident
= NULL
;
658 if (! tor_digest_is_zero(circ
->n_hop
->identity_digest
)) {
659 rsa_ident
= circ
->n_hop
->identity_digest
;
661 if (! ed25519_public_key_is_zero(&circ
->n_hop
->ed_identity
)) {
662 ed_ident
= &circ
->n_hop
->ed_identity
;
665 if (rsa_ident
== NULL
&& ed_ident
== NULL
) {
666 /* Look at addr/port. This is an unkeyed connection. */
667 if (!channel_matches_extend_info(chan
, circ
->n_hop
))
670 /* We expected a key or keys. See if they matched. */
671 if (!channel_remote_identity_matches(chan
, rsa_ident
, ed_ident
))
674 /* If the channel is canonical, great. If not, it needs to match
675 * the requested address exactly. */
676 if (! chan
->is_canonical
&&
677 ! channel_matches_extend_info(chan
, circ
->n_hop
)) {
681 if (!status
) { /* chan failed; close circ */
682 log_info(LD_CIRC
,"Channel failed; closing circ.");
683 circuit_mark_for_close(circ
, END_CIRC_REASON_CHANNEL_CLOSED
);
687 if (close_origin_circuits
&& CIRCUIT_IS_ORIGIN(circ
)) {
688 log_info(LD_CIRC
,"Channel deprecated for origin circs; closing circ.");
689 circuit_mark_for_close(circ
, END_CIRC_REASON_CHANNEL_CLOSED
);
692 log_debug(LD_CIRC
, "Found circ, sending create cell.");
693 /* circuit_deliver_create_cell will set n_circ_id and add us to
694 * chan_circuid_circuit_map, so we don't need to call
695 * set_circid_chan here. */
697 extend_info_free(circ
->n_hop
);
700 if (CIRCUIT_IS_ORIGIN(circ
)) {
702 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
704 "send_next_onion_skin failed; circuit marked for closing.");
705 circuit_mark_for_close(circ
, -err_reason
);
707 /* XXX could this be bad, eg if next_onion_skin failed because conn
711 /* pull the create cell out of circ->n_chan_create_cell, and send it */
712 tor_assert(circ
->n_chan_create_cell
);
713 if (circuit_deliver_create_cell(circ
, circ
->n_chan_create_cell
, 1)<0) {
714 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
717 tor_free(circ
->n_chan_create_cell
);
718 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
721 SMARTLIST_FOREACH_END(circ
);
723 smartlist_free(pending_circs
);
726 /** Find a new circid that isn't currently in use on the circ->n_chan
728 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
729 * circuit. If <b>relayed</b> is true, this is a create cell somebody
730 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
731 * it. Return -1 if we failed to find a suitable circid, else return 0.
734 circuit_deliver_create_cell
,(circuit_t
*circ
,
735 const struct create_cell_t
*create_cell
,
743 tor_assert(circ
->n_chan
);
744 tor_assert(create_cell
);
745 tor_assert(create_cell
->cell_type
== CELL_CREATE
||
746 create_cell
->cell_type
== CELL_CREATE_FAST
||
747 create_cell
->cell_type
== CELL_CREATE2
);
749 id
= get_unique_circ_id_by_chan(circ
->n_chan
);
751 static ratelim_t circid_warning_limit
= RATELIM_INIT(9600);
752 log_fn_ratelim(&circid_warning_limit
, LOG_WARN
, LD_CIRC
,
753 "failed to get unique circID.");
757 tor_assert_nonfatal_once(circ
->n_chan
->is_canonical
);
759 memset(&cell
, 0, sizeof(cell_t
));
760 r
= relayed
? create_cell_format_relayed(&cell
, create_cell
)
761 : create_cell_format(&cell
, create_cell
);
763 log_warn(LD_CIRC
,"Couldn't format create cell");
766 log_debug(LD_CIRC
,"Chosen circID %u.", (unsigned)id
);
767 circuit_set_n_circid_chan(circ
, id
, circ
->n_chan
);
768 cell
.circ_id
= circ
->n_circ_id
;
770 append_cell_to_circuit_queue(circ
, circ
->n_chan
, &cell
,
771 CELL_DIRECTION_OUT
, 0);
773 if (CIRCUIT_IS_ORIGIN(circ
)) {
774 /* Update began timestamp for circuits starting their first hop */
775 if (TO_ORIGIN_CIRCUIT(circ
)->cpath
->state
== CPATH_STATE_CLOSED
) {
776 if (!CHANNEL_IS_OPEN(circ
->n_chan
)) {
778 "Got first hop for a circuit without an opened channel. "
779 "State: %s.", channel_state_to_string(circ
->n_chan
->state
));
780 tor_fragile_assert();
783 tor_gettimeofday(&circ
->timestamp_began
);
786 /* mark it so it gets better rate limiting treatment. */
787 channel_timestamp_client(circ
->n_chan
);
796 /** Return true iff we should send a create_fast cell to start building a
799 should_use_create_fast_for_circuit(origin_circuit_t
*circ
)
801 tor_assert(circ
->cpath
);
802 tor_assert(circ
->cpath
->extend_info
);
804 return ! circuit_has_usable_onion_key(circ
);
808 * Return true if <b>circ</b> is the type of circuit we want to count
811 * In particular, we want to consider any circuit that plans to build
812 * at least 3 hops (but maybe more), but has 3 or fewer hops built
815 * We still want to consider circuits before 3 hops, because we need
816 * to decide if we should convert them to a measurement circuit in
817 * circuit_build_times_handle_completed_hop(), rather than letting
818 * slow circuits get killed right away.
821 circuit_timeout_want_to_count_circ(const origin_circuit_t
*circ
)
823 return !circ
->has_opened
824 && circ
->build_state
->desired_path_len
>= DEFAULT_ROUTE_LEN
825 && circuit_get_cpath_opened_len(circ
) <= DEFAULT_ROUTE_LEN
;
828 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
829 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
831 * Note that TAP handshakes in CREATE cells are only used for direct
833 * - from Single Onions to rend points not in the service's consensus.
834 * This is checked in onion_populate_cpath. */
836 circuit_pick_create_handshake(uint8_t *cell_type_out
,
837 uint16_t *handshake_type_out
,
838 const extend_info_t
*ei
)
840 /* torspec says: In general, clients SHOULD use CREATE whenever they are
841 * using the TAP handshake, and CREATE2 otherwise. */
842 if (extend_info_supports_ntor(ei
)) {
843 *cell_type_out
= CELL_CREATE2
;
844 *handshake_type_out
= ONION_HANDSHAKE_TYPE_NTOR
;
846 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
847 *cell_type_out
= CELL_CREATE
;
848 *handshake_type_out
= ONION_HANDSHAKE_TYPE_TAP
;
852 /** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
853 * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
854 * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
855 * and *<b>create_cell_type_out</b> accordingly.
856 * Note that TAP handshakes in EXTEND cells are only used:
857 * - from clients to intro points, and
858 * - from hidden services to rend points.
859 * This is checked in onion_populate_cpath.
862 circuit_pick_extend_handshake(uint8_t *cell_type_out
,
863 uint8_t *create_cell_type_out
,
864 uint16_t *handshake_type_out
,
865 const extend_info_t
*ei
)
868 circuit_pick_create_handshake(&t
, handshake_type_out
, ei
);
870 /* torspec says: Clients SHOULD use the EXTEND format whenever sending a TAP
871 * handshake... In other cases, clients SHOULD use EXTEND2. */
872 if (*handshake_type_out
!= ONION_HANDSHAKE_TYPE_TAP
) {
873 *cell_type_out
= RELAY_COMMAND_EXTEND2
;
874 *create_cell_type_out
= CELL_CREATE2
;
876 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
877 *cell_type_out
= RELAY_COMMAND_EXTEND
;
878 *create_cell_type_out
= CELL_CREATE
;
883 * Return true iff <b>purpose</b> is a purpose for a circuit which is
884 * allowed to have no guard configured, even if the circuit is multihop
885 * and guards are enabled.
888 circuit_purpose_may_omit_guard(int purpose
)
891 case CIRCUIT_PURPOSE_TESTING
:
892 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
:
893 /* Testing circuits may omit guards because they're measuring
894 * liveness or performance, and don't want guards to interfere. */
897 /* All other multihop circuits should use guards if guards are
903 /** This is the backbone function for building circuits.
905 * If circ's first hop is closed, then we need to build a create
906 * cell and send it forward.
908 * Otherwise, if circ's cpath still has any non-open hops, we need to
909 * build a relay extend cell and send it forward to the next non-open hop.
911 * If all hops on the cpath are open, we're done building the circuit
912 * and we should do housekeeping for the newly opened circuit.
914 * Return -reason if we want to tear down circ, else return 0.
917 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
921 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
922 /* Case one: we're on the first hop. */
923 return circuit_send_first_onion_skin(circ
);
926 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
927 tor_assert(circ
->base_
.state
== CIRCUIT_STATE_BUILDING
);
929 crypt_path_t
*hop
= cpath_get_next_non_open_hop(circ
->cpath
);
930 circuit_build_times_handle_completed_hop(circ
);
932 circpad_machine_event_circ_added_hop(circ
);
935 /* Case two: we're on a hop after the first. */
936 return circuit_send_intermediate_onion_skin(circ
, hop
);
939 /* Case three: the circuit is finished. Do housekeeping tasks on it. */
940 circpad_machine_event_circ_built(circ
);
941 return circuit_build_no_more_hops(circ
);
945 * Called from circuit_send_next_onion_skin() when we find ourselves connected
946 * to the first hop in <b>circ</b>: Send a CREATE or CREATE2 or CREATE_FAST
947 * cell to that hop. Return 0 on success; -reason on failure (if the circuit
948 * should be torn down).
951 circuit_send_first_onion_skin(origin_circuit_t
*circ
)
957 memset(&cc
, 0, sizeof(cc
));
959 log_debug(LD_CIRC
,"First skin; sending create cell.");
961 if (circ
->build_state
->onehop_tunnel
) {
962 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE
, 0);
964 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE
, 0);
966 /* If this is not a one-hop tunnel, the channel is being used
967 * for traffic that wants anonymity and protection from traffic
968 * analysis (such as netflow record retention). That means we want
971 if (circ
->base_
.n_chan
->channel_usage
< CHANNEL_USED_FOR_FULL_CIRCS
)
972 circ
->base_
.n_chan
->channel_usage
= CHANNEL_USED_FOR_FULL_CIRCS
;
975 node
= node_get_by_id(circ
->base_
.n_chan
->identity_digest
);
976 fast
= should_use_create_fast_for_circuit(circ
);
978 /* We know the right onion key: we should send a create cell. */
979 circuit_pick_create_handshake(&cc
.cell_type
, &cc
.handshake_type
,
980 circ
->cpath
->extend_info
);
982 /* We don't know an onion key, so we need to fall back to CREATE_FAST. */
983 cc
.cell_type
= CELL_CREATE_FAST
;
984 cc
.handshake_type
= ONION_HANDSHAKE_TYPE_FAST
;
987 len
= onion_skin_create(cc
.handshake_type
,
988 circ
->cpath
->extend_info
,
989 &circ
->cpath
->handshake_state
,
992 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
993 return - END_CIRC_REASON_INTERNAL
;
995 cc
.handshake_len
= len
;
997 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), &cc
, 0) < 0)
998 return - END_CIRC_REASON_RESOURCELIMIT
;
999 tor_trace(TR_SUBSYS(circuit
), TR_EV(first_onion_skin
), circ
, circ
->cpath
);
1001 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
1002 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
1003 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
1004 fast
? "CREATE_FAST" : "CREATE",
1005 node
? node_describe(node
) : "<unnamed>");
1010 * Called from circuit_send_next_onion_skin() when we find that we have no
1011 * more hops: mark the circuit as finished, and perform the necessary
1012 * bookkeeping. Return 0 on success; -reason on failure (if the circuit
1013 * should be torn down).
1016 circuit_build_no_more_hops(origin_circuit_t
*circ
)
1019 if (! circ
->guard_state
) {
1020 if (circuit_get_cpath_len(circ
) != 1 &&
1021 ! circuit_purpose_may_omit_guard(circ
->base_
.purpose
) &&
1022 get_options()->UseEntryGuards
) {
1023 log_warn(LD_BUG
, "%d-hop circuit %p with purpose %d has no "
1025 circuit_get_cpath_len(circ
), circ
, circ
->base_
.purpose
);
1027 r
= GUARD_USABLE_NOW
;
1029 r
= entry_guard_succeeded(&circ
->guard_state
);
1031 const int is_usable_for_streams
= (r
== GUARD_USABLE_NOW
);
1032 if (r
== GUARD_USABLE_NOW
) {
1033 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
1034 } else if (r
== GUARD_MAYBE_USABLE_LATER
) {
1035 // Wait till either a better guard succeeds, or till
1036 // all better guards fail.
1037 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_GUARD_WAIT
);
1039 tor_assert_nonfatal(r
== GUARD_USABLE_NEVER
);
1040 return - END_CIRC_REASON_INTERNAL
;
1043 /* XXXX #21422 -- the rest of this branch needs careful thought!
1044 * Some of the things here need to happen when a circuit becomes
1045 * mechanically open; some need to happen when it is actually usable.
1046 * I think I got them right, but more checking would be wise. -NM
1049 log_info(LD_CIRC
,"circuit built!");
1050 circuit_reset_failure_count(0);
1052 if (circ
->build_state
->onehop_tunnel
|| circ
->has_opened
) {
1053 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS
, 0);
1056 pathbias_count_build_success(circ
);
1057 if (is_usable_for_streams
)
1058 circuit_has_opened(circ
); /* do other actions as necessary */
1060 if (!have_completed_a_circuit() && !circ
->build_state
->onehop_tunnel
) {
1061 const or_options_t
*options
= get_options();
1062 note_that_we_completed_a_circuit();
1063 /* FFFF Log a count of known routers here */
1064 log_info(LD_GENERAL
,
1065 "Tor has successfully opened a circuit. "
1066 "Looks like client functionality is working.");
1067 control_event_bootstrap(BOOTSTRAP_STATUS_DONE
, 0);
1068 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
1069 clear_broken_connection_map(1);
1070 if (server_mode(options
) &&
1071 !router_all_orports_seem_reachable(options
)) {
1072 router_do_reachability_checks();
1076 /* We're done with measurement circuits here. Just close them */
1077 if (circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
1078 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_FINISHED
);
1084 * Called from circuit_send_next_onion_skin() when we find that we have a hop
1085 * other than the first that we need to extend to: use <b>hop</b>'s
1086 * information to extend the circuit another step. Return 0 on success;
1087 * -reason on failure (if the circuit should be torn down).
1090 circuit_send_intermediate_onion_skin(origin_circuit_t
*circ
,
1095 /* Relays and bridges can send IPv6 extends. But for clients, it's an
1096 * obvious version distinguisher. */
1097 const bool include_ipv6
= server_mode(get_options());
1098 memset(&ec
, 0, sizeof(ec
));
1099 tor_addr_make_unspec(&ec
.orport_ipv4
.addr
);
1100 tor_addr_make_unspec(&ec
.orport_ipv6
.addr
);
1102 log_debug(LD_CIRC
,"starting to send subsequent skin.");
1104 circuit_pick_extend_handshake(&ec
.cell_type
,
1105 &ec
.create_cell
.cell_type
,
1106 &ec
.create_cell
.handshake_type
,
1109 const tor_addr_port_t
*orport4
=
1110 extend_info_get_orport(hop
->extend_info
, AF_INET
);
1111 const tor_addr_port_t
*orport6
=
1112 extend_info_get_orport(hop
->extend_info
, AF_INET6
);
1113 int n_addrs_set
= 0;
1115 tor_addr_copy(&ec
.orport_ipv4
.addr
, &orport4
->addr
);
1116 ec
.orport_ipv4
.port
= orport4
->port
;
1119 if (orport6
&& include_ipv6
) {
1120 tor_addr_copy(&ec
.orport_ipv6
.addr
, &orport6
->addr
);
1121 ec
.orport_ipv6
.port
= orport6
->port
;
1125 if (n_addrs_set
== 0) {
1126 log_warn(LD_BUG
, "No supported address family found in extend_info.");
1127 return - END_CIRC_REASON_INTERNAL
;
1129 memcpy(ec
.node_id
, hop
->extend_info
->identity_digest
, DIGEST_LEN
);
1130 /* Set the ED25519 identity too -- it will only get included
1131 * in the extend2 cell if we're configured to use it, though. */
1132 ed25519_pubkey_copy(&ec
.ed_pubkey
, &hop
->extend_info
->ed_identity
);
1134 len
= onion_skin_create(ec
.create_cell
.handshake_type
,
1136 &hop
->handshake_state
,
1137 ec
.create_cell
.onionskin
);
1139 log_warn(LD_CIRC
,"onion_skin_create failed.");
1140 return - END_CIRC_REASON_INTERNAL
;
1142 ec
.create_cell
.handshake_len
= len
;
1144 log_info(LD_CIRC
,"Sending extend relay cell.");
1146 uint8_t command
= 0;
1147 uint16_t payload_len
=0;
1148 uint8_t payload
[RELAY_PAYLOAD_SIZE
];
1149 if (extend_cell_format(&command
, &payload_len
, payload
, &ec
)<0) {
1150 log_warn(LD_CIRC
,"Couldn't format extend cell");
1151 return -END_CIRC_REASON_INTERNAL
;
1154 /* send it to hop->prev, because that relay will transfer
1155 * it to a create cell and then send to hop */
1156 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
1158 (char*)payload
, payload_len
,
1160 return 0; /* circuit is closed */
1162 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
1163 tor_trace(TR_SUBSYS(circuit
), TR_EV(intermediate_onion_skin
), circ
, hop
);
1167 /** Our clock just jumped by <b>seconds_elapsed</b>. If <b>was_idle</b> is
1168 * true, then the monotonic time matches; otherwise it doesn't. Assume
1169 * something has also gone wrong with our network: notify the user, and
1170 * abandon all not-yet-used circuits. */
1172 circuit_note_clock_jumped(int64_t seconds_elapsed
, bool was_idle
)
1174 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
1176 tor_log(severity
, LD_GENERAL
, "Tor has been idle for %"PRId64
1177 " seconds; assuming established circuits no longer work.",
1180 tor_log(severity
, LD_GENERAL
,
1181 "Your system clock just jumped %"PRId64
" seconds %s; "
1182 "assuming established circuits no longer work.",
1184 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
),
1185 seconds_elapsed
>=0 ? "forward" : "backward");
1187 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%"PRId64
1189 (seconds_elapsed
), was_idle
?1:0);
1190 /* so we log when it works again */
1191 note_that_we_maybe_cant_complete_circuits();
1192 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1194 circuit_mark_all_unused_circs();
1195 circuit_mark_all_dirty_circs_as_unusable();
1196 if (seconds_elapsed
< 0) {
1197 /* Restart all the timers in case we jumped a long way into the past. */
1198 reset_all_main_loop_timers();
1202 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
1203 * (The body of <b>reply</b> varies depending on what sort of handshake
1206 * Calculate the appropriate keys and digests, make sure KH is
1207 * correct, and initialize this hop of the cpath.
1209 * Return - reason if we want to mark circ for close, else return 0.
1212 circuit_finish_handshake(origin_circuit_t
*circ
,
1213 const created_cell_t
*reply
)
1215 char keys
[CPATH_KEY_MATERIAL_LEN
];
1219 if ((rv
= pathbias_count_build_attempt(circ
)) < 0) {
1220 log_warn(LD_CIRC
, "pathbias_count_build_attempt failed: %d", rv
);
1224 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
) {
1227 hop
= cpath_get_next_non_open_hop(circ
->cpath
);
1228 if (!hop
) { /* got an extended when we're all done? */
1229 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
1230 return - END_CIRC_REASON_TORPROTOCOL
;
1233 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
1236 const char *msg
= NULL
;
1237 if (onion_skin_client_handshake(hop
->handshake_state
.tag
,
1238 &hop
->handshake_state
,
1239 reply
->reply
, reply
->handshake_len
,
1240 (uint8_t*)keys
, sizeof(keys
),
1241 (uint8_t*)hop
->rend_circ_nonce
,
1244 log_warn(LD_CIRC
,"onion_skin_client_handshake failed: %s", msg
);
1245 return -END_CIRC_REASON_TORPROTOCOL
;
1249 onion_handshake_state_release(&hop
->handshake_state
);
1251 if (cpath_init_circuit_crypto(hop
, keys
, sizeof(keys
), 0, 0)<0) {
1252 return -END_CIRC_REASON_TORPROTOCOL
;
1255 hop
->state
= CPATH_STATE_OPEN
;
1256 log_info(LD_CIRC
,"Finished building circuit hop:");
1257 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
1258 circuit_event_status(circ
, CIRC_EVENT_EXTENDED
, 0);
1263 /** We received a relay truncated cell on circ.
1265 * Since we don't send truncates currently, getting a truncated
1266 * means that a connection broke or an extend failed. For now,
1267 * just give up: force circ to close, and return 0.
1270 circuit_truncated(origin_circuit_t
*circ
, int reason
)
1272 // crypt_path_t *victim;
1273 // connection_t *stream;
1277 /* XXX Since we don't send truncates currently, getting a truncated
1278 * means that a connection broke or an extend failed. For now,
1281 circuit_mark_for_close(TO_CIRCUIT(circ
),
1282 END_CIRC_REASON_FLAG_REMOTE
|reason
);
1286 while (layer
->next
!= circ
->cpath
) {
1287 /* we need to clear out layer->next */
1288 victim
= layer
->next
;
1289 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
1291 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
1292 if (stream
->cpath_layer
== victim
) {
1293 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
1295 /* no need to send 'end' relay cells,
1296 * because the other side's already dead
1298 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
1302 layer
->next
= victim
->next
;
1306 log_info(LD_CIRC
, "finished");
1311 /** Helper for new_route_len(). Choose a circuit length for purpose
1312 * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
1313 * exit). If someone else chose the exit, they could be colluding
1314 * with the exit, so add a randomly selected node to preserve
1317 * Here, "exit node" sometimes means an OR acting as an internal
1318 * endpoint, rather than as a relay to an external endpoint. This
1319 * means there need to be at least DEFAULT_ROUTE_LEN routers between
1320 * us and the internal endpoint to preserve the same anonymity
1321 * properties that we would get when connecting to an external
1322 * endpoint. These internal endpoints can include:
1324 * - Connections to a directory of hidden services
1325 * (CIRCUIT_PURPOSE_C_GENERAL)
1327 * - A client connecting to an introduction point, which the hidden
1328 * service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
1329 * circuit_get_open_circ_or_launch() which rewrites it from
1330 * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1332 * - A hidden service connecting to a rendezvous point, which the
1333 * client picked (CIRCUIT_PURPOSE_S_CONNECT_REND.
1335 * There are currently two situations where we picked the exit node
1336 * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
1338 * - We are a hidden service connecting to an introduction point
1339 * (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO).
1341 * - We are a router testing its own reachabiity
1342 * (CIRCUIT_PURPOSE_TESTING, via router_do_reachability_checks())
1344 * onion_pick_cpath_exit() bypasses us (by not calling
1345 * new_route_len()) in the one-hop tunnel case, so we don't need to
1349 route_len_for_purpose(uint8_t purpose
, extend_info_t
*exit_ei
)
1351 int routelen
= DEFAULT_ROUTE_LEN
;
1352 int known_purpose
= 0;
1354 if (circuit_should_use_vanguards(purpose
)) {
1355 /* Clients want an extra hop for rends to avoid linkability.
1356 * Services want it for intro points to avoid publishing their
1357 * layer3 guards. They want it for hsdir posts to use
1358 * their full layer3 guard set for those connections.
1359 * Ex: C - G - L2 - L3 - R
1360 * S - G - L2 - L3 - HSDIR
1361 * S - G - L2 - L3 - I
1363 if (purpose
== CIRCUIT_PURPOSE_C_ESTABLISH_REND
||
1364 purpose
== CIRCUIT_PURPOSE_S_HSDIR_POST
||
1365 purpose
== CIRCUIT_PURPOSE_HS_VANGUARDS
||
1366 purpose
== CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
1369 /* If we only have Layer2 vanguards, then we do not need
1370 * the extra hop for linkabilty reasons (see below).
1371 * This means all hops can be of the form:
1372 * S/C - G - L2 - M - R/HSDir/I
1374 if (get_options()->HSLayer2Nodes
&& !get_options()->HSLayer3Nodes
)
1377 /* For connections to hsdirs, clients want two extra hops
1378 * when using layer3 guards, to avoid linkability.
1379 * Same goes for intro points. Note that the route len
1380 * includes the intro point or hsdir, hence the +2.
1381 * Ex: C - G - L2 - L3 - M - I
1382 * C - G - L2 - L3 - M - HSDIR
1383 * S - G - L2 - L3 - M - R
1385 if (purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
||
1386 purpose
== CIRCUIT_PURPOSE_C_HSDIR_GET
||
1387 purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
)
1395 /* These two purposes connect to a router that we chose, so
1396 * DEFAULT_ROUTE_LEN is safe. */
1397 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1398 /* hidden service connecting to introduction point */
1399 case CIRCUIT_PURPOSE_TESTING
:
1400 /* router reachability testing */
1404 /* These three purposes connect to a router that someone else
1405 * might have chosen, so add an extra hop to protect anonymity. */
1406 case CIRCUIT_PURPOSE_C_GENERAL
:
1407 case CIRCUIT_PURPOSE_C_HSDIR_GET
:
1408 case CIRCUIT_PURPOSE_S_HSDIR_POST
:
1409 /* connecting to hidden service directory */
1410 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1411 /* client connecting to introduction point */
1412 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1413 /* hidden service connecting to rendezvous point */
1419 /* Got a purpose not listed above along with a chosen exit.
1420 * Increase the circuit length by one anyway for safety. */
1425 if (BUG(exit_ei
&& !known_purpose
)) {
1426 log_warn(LD_BUG
, "Unhandled purpose %d with a chosen exit; "
1427 "assuming routelen %d.", purpose
, routelen
);
1432 /** Choose a length for a circuit of purpose <b>purpose</b> and check
1433 * if enough routers are available.
1435 * If the routerlist <b>nodes</b> doesn't have enough routers
1436 * to handle the desired path length, return -1.
1439 new_route_len(uint8_t purpose
, extend_info_t
*exit_ei
,
1440 const smartlist_t
*nodes
)
1446 routelen
= route_len_for_purpose(purpose
, exit_ei
);
1448 int num_acceptable_direct
= count_acceptable_nodes(nodes
, 1);
1449 int num_acceptable_indirect
= count_acceptable_nodes(nodes
, 0);
1451 log_debug(LD_CIRC
,"Chosen route length %d (%d direct and %d indirect "
1452 "routers suitable).", routelen
, num_acceptable_direct
,
1453 num_acceptable_indirect
);
1455 if (num_acceptable_direct
< 1 || num_acceptable_indirect
< routelen
- 1) {
1457 "Not enough acceptable routers (%d/%d direct and %d/%d "
1458 "indirect routers suitable). Discarding this circuit.",
1459 num_acceptable_direct
, routelen
,
1460 num_acceptable_indirect
, routelen
);
1467 /** Return a newly allocated list of uint16_t * for each predicted port not
1468 * handled by a current circuit. */
1469 static smartlist_t
*
1470 circuit_get_unhandled_ports(time_t now
)
1472 smartlist_t
*dest
= rep_hist_get_predicted_ports(now
);
1473 circuit_remove_handled_ports(dest
);
1477 /** Return 1 if we already have circuits present or on the way for
1478 * all anticipated ports. Return 0 if we should make more.
1480 * If we're returning 0, set need_uptime and need_capacity to
1481 * indicate any requirements that the unhandled ports have.
1484 circuit_all_predicted_ports_handled
, (time_t now
, int *need_uptime
,
1485 int *need_capacity
))
1489 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
1490 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
1491 tor_assert(need_uptime
);
1492 tor_assert(need_capacity
);
1493 // Always predict need_capacity
1495 enough
= (smartlist_len(sl
) == 0);
1496 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
1497 port
= smartlist_get(sl
, i
);
1498 if (smartlist_contains_int_as_string(LongLivedServices
, *port
))
1506 /** Return 1 if <b>node</b> can handle one or more of the ports in
1507 * <b>needed_ports</b>, else return 0.
1510 node_handles_some_port(const node_t
*node
, smartlist_t
*needed_ports
)
1515 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
1516 addr_policy_result_t r
;
1517 /* alignment issues aren't a worry for this dereference, since
1518 needed_ports is explicitly a smartlist of uint16_t's */
1519 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
1522 r
= compare_tor_addr_to_node_policy(NULL
, port
, node
);
1525 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
1531 /** Return true iff <b>conn</b> needs another general circuit to be
1534 ap_stream_wants_exit_attention(connection_t
*conn
)
1536 entry_connection_t
*entry
;
1537 if (conn
->type
!= CONN_TYPE_AP
)
1539 entry
= TO_ENTRY_CONN(conn
);
1541 if (conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
1542 !conn
->marked_for_close
&&
1543 !(entry
->want_onehop
) && /* ignore one-hop streams */
1544 !(entry
->use_begindir
) && /* ignore targeted dir fetches */
1545 !(entry
->chosen_exit_name
) && /* ignore defined streams */
1546 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
1547 !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn
), 0,
1548 MIN_CIRCUITS_HANDLING_STREAM
))
1553 /** Return a pointer to a suitable router to be the exit node for the
1554 * general-purpose circuit we're about to build.
1556 * Look through the connection array, and choose a router that maximizes
1557 * the number of pending streams that can exit from this router.
1559 * Return NULL if we can't find any suitable routers.
1561 static const node_t
*
1562 choose_good_exit_server_general(router_crn_flags_t flags
)
1565 int n_pending_connections
= 0;
1566 smartlist_t
*connections
;
1567 int best_support
= -1;
1568 int n_best_support
=0;
1569 const or_options_t
*options
= get_options();
1570 const smartlist_t
*the_nodes
;
1571 const node_t
*selected_node
=NULL
;
1572 const int need_uptime
= (flags
& CRN_NEED_UPTIME
) != 0;
1573 const int need_capacity
= (flags
& CRN_NEED_CAPACITY
) != 0;
1575 /* We should not require guard flags on exits. */
1576 IF_BUG_ONCE(flags
& CRN_NEED_GUARD
)
1579 /* We reject single-hop exits for all node positions. */
1580 IF_BUG_ONCE(flags
& CRN_DIRECT_CONN
)
1583 /* This isn't the function for picking rendezvous nodes. */
1584 IF_BUG_ONCE(flags
& CRN_RENDEZVOUS_V3
)
1587 /* We only want exits to extend if we cannibalize the circuit.
1588 * But we don't require IPv6 extends yet. */
1589 IF_BUG_ONCE(flags
& CRN_INITIATE_IPV6_EXTEND
)
1592 connections
= get_connection_array();
1594 /* Count how many connections are waiting for a circuit to be built.
1595 * We use this for log messages now, but in the future we may depend on it.
1597 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
1599 if (ap_stream_wants_exit_attention(conn
))
1600 ++n_pending_connections
;
1602 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1603 // n_pending_connections);
1604 /* Now we count, for each of the routers in the directory, how many
1605 * of the pending connections could possibly exit from that
1606 * router (n_supported[i]). (We can't be sure about cases where we
1607 * don't know the IP address of the pending connection.)
1609 * -1 means "Don't use this router at all."
1611 the_nodes
= nodelist_get_list();
1612 n_supported
= tor_calloc(smartlist_len(the_nodes
), sizeof(int));
1613 SMARTLIST_FOREACH_BEGIN(the_nodes
, const node_t
*, node
) {
1614 const int i
= node_sl_idx
;
1615 if (router_digest_is_me(node
->identity
)) {
1616 n_supported
[i
] = -1;
1617 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1618 /* XXX there's probably a reverse predecessor attack here, but
1619 * it's slow. should we take this out? -RD
1623 if (!router_can_choose_node(node
, flags
)) {
1624 n_supported
[i
] = -1;
1627 if (node
->is_bad_exit
) {
1628 n_supported
[i
] = -1;
1629 continue; /* skip routers that are known to be down or bad exits */
1631 if (routerset_contains_node(options
->ExcludeExitNodesUnion_
, node
)) {
1632 n_supported
[i
] = -1;
1633 continue; /* user asked us not to use it, no matter what */
1635 if (options
->ExitNodes
&&
1636 !routerset_contains_node(options
->ExitNodes
, node
)) {
1637 n_supported
[i
] = -1;
1638 continue; /* not one of our chosen exit nodes */
1640 if (node_exit_policy_rejects_all(node
)) {
1641 n_supported
[i
] = -1;
1642 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1643 // router->nickname, i);
1644 continue; /* skip routers that reject all */
1647 /* iterate over connections */
1648 SMARTLIST_FOREACH_BEGIN(connections
, connection_t
*, conn
) {
1649 if (!ap_stream_wants_exit_attention(conn
))
1650 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1651 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn
), node
)) {
1653 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1654 // router->nickname, i, n_supported[i]);
1656 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1657 // router->nickname, i);
1659 } SMARTLIST_FOREACH_END(conn
);
1660 if (n_pending_connections
> 0 && n_supported
[i
] == 0) {
1661 /* Leave best_support at -1 if that's where it is, so we can
1662 * distinguish it later. */
1665 if (n_supported
[i
] > best_support
) {
1666 /* If this router is better than previous ones, remember its index
1667 * and goodness, and start counting how many routers are this good. */
1668 best_support
= n_supported
[i
]; n_best_support
=1;
1669 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1670 // router->nickname);
1671 } else if (n_supported
[i
] == best_support
) {
1672 /* If this router is _as good_ as the best one, just increment the
1673 * count of equally good routers.*/
1676 } SMARTLIST_FOREACH_END(node
);
1678 "Found %d servers that might support %d/%d pending connections.",
1679 n_best_support
, best_support
>= 0 ? best_support
: 0,
1680 n_pending_connections
);
1682 /* If any routers definitely support any pending connections, choose one
1684 if (best_support
> 0) {
1685 smartlist_t
*supporting
= smartlist_new();
1687 SMARTLIST_FOREACH(the_nodes
, const node_t
*, node
, {
1688 if (n_supported
[node_sl_idx
] == best_support
)
1689 smartlist_add(supporting
, (void*)node
);
1692 selected_node
= node_sl_choose_by_bandwidth(supporting
, WEIGHT_FOR_EXIT
);
1693 smartlist_free(supporting
);
1695 /* Either there are no pending connections, or no routers even seem to
1696 * possibly support any of them. Choose a router at random that satisfies
1697 * at least one predicted exit port. */
1700 smartlist_t
*needed_ports
, *supporting
;
1702 if (best_support
== -1) {
1703 if (need_uptime
|| need_capacity
) {
1705 "We couldn't find any live%s%s routers; falling back "
1706 "to list of all routers.",
1707 need_capacity
?", fast":"",
1708 need_uptime
?", stable":"");
1709 tor_free(n_supported
);
1710 flags
&= ~(CRN_NEED_UPTIME
|CRN_NEED_CAPACITY
);
1711 return choose_good_exit_server_general(flags
);
1713 log_notice(LD_CIRC
, "All routers are down or won't exit%s -- "
1714 "choosing a doomed exit at random.",
1715 options
->ExcludeExitNodesUnion_
? " or are Excluded" : "");
1717 supporting
= smartlist_new();
1718 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
1719 for (attempt
= 0; attempt
< 2; attempt
++) {
1720 /* try once to pick only from routers that satisfy a needed port,
1721 * then if there are none, pick from any that support exiting. */
1722 SMARTLIST_FOREACH_BEGIN(the_nodes
, const node_t
*, node
) {
1723 if (n_supported
[node_sl_idx
] != -1 &&
1724 (attempt
|| node_handles_some_port(node
, needed_ports
))) {
1725 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1726 // try, router->nickname);
1727 smartlist_add(supporting
, (void*)node
);
1729 } SMARTLIST_FOREACH_END(node
);
1731 selected_node
= node_sl_choose_by_bandwidth(supporting
, WEIGHT_FOR_EXIT
);
1734 smartlist_clear(supporting
);
1735 /* If we reach this point, we can't actually support any unhandled
1736 * predicted ports, so clear all the remaining ones. */
1737 if (smartlist_len(needed_ports
))
1738 rep_hist_remove_predicted_ports(needed_ports
);
1740 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
1741 smartlist_free(needed_ports
);
1742 smartlist_free(supporting
);
1745 tor_free(n_supported
);
1746 if (selected_node
) {
1747 log_info(LD_CIRC
, "Chose exit server '%s'", node_describe(selected_node
));
1748 return selected_node
;
1750 if (options
->ExitNodes
) {
1752 "No exits in ExitNodes%s seem to be running: "
1753 "can't choose an exit.",
1754 options
->ExcludeExitNodesUnion_
?
1755 ", except possibly those excluded by your configuration, " : "");
1760 /* Pick a Rendezvous Point for our HS circuits according to <b>flags</b>. */
1761 static const node_t
*
1762 pick_rendezvous_node(router_crn_flags_t flags
)
1764 const or_options_t
*options
= get_options();
1765 return router_choose_random_node(NULL
, options
->ExcludeNodes
, flags
);
1769 * Helper function to pick a configured restricted middle node
1770 * (either HSLayer2Nodes or HSLayer3Nodes).
1772 * Make sure that the node we chose is alive, and not excluded,
1775 * The exclude_set is a routerset of nodes that the selected node
1776 * must not match, and the exclude_list is a simple list of nodes
1777 * that the selected node must not be in. Either or both may be
1780 * Return NULL if no usable nodes could be found. */
1781 static const node_t
*
1782 pick_restricted_middle_node(router_crn_flags_t flags
,
1783 const routerset_t
*pick_from
,
1784 const routerset_t
*exclude_set
,
1785 const smartlist_t
*exclude_list
,
1788 const node_t
*middle_node
= NULL
;
1790 smartlist_t
*allowlisted_live_middles
= smartlist_new();
1791 smartlist_t
*all_live_nodes
= smartlist_new();
1793 tor_assert(pick_from
);
1795 /* Add all running nodes to all_live_nodes */
1796 router_add_running_nodes_to_smartlist(all_live_nodes
, flags
);
1798 /* Filter all_live_nodes to only add live *and* allowlisted middles
1799 * to the list allowlisted_live_middles. */
1800 SMARTLIST_FOREACH_BEGIN(all_live_nodes
, node_t
*, live_node
) {
1801 if (routerset_contains_node(pick_from
, live_node
)) {
1802 smartlist_add(allowlisted_live_middles
, live_node
);
1804 } SMARTLIST_FOREACH_END(live_node
);
1806 /* Honor ExcludeNodes */
1808 routerset_subtract_nodes(allowlisted_live_middles
, exclude_set
);
1812 smartlist_subtract(allowlisted_live_middles
, exclude_list
);
1816 * Max number of restricted nodes before we alert the user and try
1817 * to load balance for them.
1819 * The most aggressive vanguard design had 16 nodes at layer3.
1820 * Let's give a small ceiling above that. */
1821 #define MAX_SANE_RESTRICTED_NODES 20
1822 /* If the user (or associated tor controller) selected only a few nodes,
1823 * assume they took load balancing into account and don't do it for them.
1825 * If there are a lot of nodes in here, assume they did not load balance
1826 * and do it for them, but also warn them that they may be Doing It Wrong.
1828 if (smartlist_len(allowlisted_live_middles
) <=
1829 MAX_SANE_RESTRICTED_NODES
) {
1830 middle_node
= smartlist_choose(allowlisted_live_middles
);
1832 static ratelim_t pinned_notice_limit
= RATELIM_INIT(24*3600);
1833 log_fn_ratelim(&pinned_notice_limit
, LOG_NOTICE
, LD_CIRC
,
1834 "Your _HSLayer%dNodes setting has resulted "
1835 "in %d total nodes. This is a lot of nodes. "
1836 "You may want to consider using a Tor controller "
1837 "to select and update a smaller set of nodes instead.",
1838 position_hint
, smartlist_len(allowlisted_live_middles
));
1840 /* NO_WEIGHTING here just means don't take node flags into account
1841 * (ie: use consensus measurement only). This is done so that
1842 * we don't further surprise the user by not using Exits that they
1843 * specified at all */
1844 middle_node
= node_sl_choose_by_bandwidth(allowlisted_live_middles
,
1848 smartlist_free(allowlisted_live_middles
);
1849 smartlist_free(all_live_nodes
);
1854 /** Return a pointer to a suitable router to be the exit node for the
1855 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
1856 * if no router is suitable).
1858 * For general-purpose circuits, pass it off to
1859 * choose_good_exit_server_general()
1861 * For client-side rendezvous circuits, choose a random node, weighted
1862 * toward the preferences in 'options'.
1864 static const node_t
*
1865 choose_good_exit_server(origin_circuit_t
*circ
,
1866 router_crn_flags_t flags
, int is_internal
)
1868 const or_options_t
*options
= get_options();
1869 flags
|= CRN_NEED_DESC
;
1871 switch (TO_CIRCUIT(circ
)->purpose
) {
1872 case CIRCUIT_PURPOSE_C_HSDIR_GET
:
1873 case CIRCUIT_PURPOSE_S_HSDIR_POST
:
1874 case CIRCUIT_PURPOSE_HS_VANGUARDS
:
1875 /* For these three, we want to pick the exit like a middle hop,
1876 * since it should be random. */
1877 tor_assert_nonfatal(is_internal
);
1879 case CIRCUIT_PURPOSE_C_GENERAL
:
1880 if (is_internal
) /* pick it like a middle hop */
1881 return router_choose_random_node(NULL
, options
->ExcludeNodes
, flags
);
1883 return choose_good_exit_server_general(flags
);
1884 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1887 const node_t
*rendezvous_node
= pick_rendezvous_node(flags
);
1888 log_info(LD_REND
, "Picked new RP: %s",
1889 safe_str_client(node_describe(rendezvous_node
)));
1890 return rendezvous_node
;
1893 log_warn(LD_BUG
,"Unhandled purpose %d", TO_CIRCUIT(circ
)->purpose
);
1894 tor_fragile_assert();
1898 /** Log a warning if the user specified an exit for the circuit that
1899 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
1901 warn_if_last_router_excluded(origin_circuit_t
*circ
,
1902 const extend_info_t
*exit_ei
)
1904 const or_options_t
*options
= get_options();
1905 routerset_t
*rs
= options
->ExcludeNodes
;
1906 const char *description
;
1907 uint8_t purpose
= circ
->base_
.purpose
;
1909 if (circ
->build_state
->onehop_tunnel
)
1915 case CIRCUIT_PURPOSE_OR
:
1916 case CIRCUIT_PURPOSE_INTRO_POINT
:
1917 case CIRCUIT_PURPOSE_REND_POINT_WAITING
:
1918 case CIRCUIT_PURPOSE_REND_ESTABLISHED
:
1919 log_warn(LD_BUG
, "Called on non-origin circuit (purpose %d, %s)",
1921 circuit_purpose_to_string(purpose
));
1923 case CIRCUIT_PURPOSE_S_HSDIR_POST
:
1924 case CIRCUIT_PURPOSE_C_HSDIR_GET
:
1925 case CIRCUIT_PURPOSE_C_GENERAL
:
1926 if (circ
->build_state
->is_internal
)
1928 description
= "requested exit node";
1929 rs
= options
->ExcludeExitNodesUnion_
;
1931 case CIRCUIT_PURPOSE_C_INTRODUCING
:
1932 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
1933 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
:
1934 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
1935 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
1936 case CIRCUIT_PURPOSE_S_REND_JOINED
:
1937 case CIRCUIT_PURPOSE_TESTING
:
1939 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
1940 case CIRCUIT_PURPOSE_C_REND_READY
:
1941 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
1942 case CIRCUIT_PURPOSE_C_REND_JOINED
:
1943 description
= "chosen rendezvous point";
1945 case CIRCUIT_PURPOSE_CONTROLLER
:
1946 rs
= options
->ExcludeExitNodesUnion_
;
1947 description
= "controller-selected circuit target";
1951 if (routerset_contains_extendinfo(rs
, exit_ei
)) {
1952 /* We should never get here if StrictNodes is set to 1. */
1953 if (options
->StrictNodes
) {
1954 log_warn(LD_BUG
, "Using %s '%s' which is listed in ExcludeNodes%s, "
1955 "even though StrictNodes is set. Please report. "
1956 "(Circuit purpose: %s)",
1957 description
, extend_info_describe(exit_ei
),
1958 rs
==options
->ExcludeNodes
?"":" or ExcludeExitNodes",
1959 circuit_purpose_to_string(purpose
));
1961 log_warn(LD_CIRC
, "Using %s '%s' which is listed in "
1962 "ExcludeNodes%s, because no better options were available. To "
1963 "prevent this (and possibly break your Tor functionality), "
1964 "set the StrictNodes configuration option. "
1965 "(Circuit purpose: %s)",
1966 description
, extend_info_describe(exit_ei
),
1967 rs
==options
->ExcludeNodes
?"":" or ExcludeExitNodes",
1968 circuit_purpose_to_string(purpose
));
1970 circuit_log_path(LOG_WARN
, LD_CIRC
, circ
);
1976 /* Return a set of generic CRN_* flags based on <b>state</b>.
1978 * Called for every position in the circuit. */
1980 cpath_build_state_to_crn_flags(const cpath_build_state_t
*state
)
1982 router_crn_flags_t flags
= 0;
1983 /* These flags apply to entry, middle, and exit nodes.
1984 * If a flag only applies to a specific position, it should be checked in
1986 if (state
->need_uptime
)
1987 flags
|= CRN_NEED_UPTIME
;
1988 if (state
->need_capacity
)
1989 flags
|= CRN_NEED_CAPACITY
;
1993 /* Return the CRN_INITIATE_IPV6_EXTEND flag, based on <b>state</b> and
1996 * Only called for middle nodes (for now). Must not be called on single-hop
1999 cpath_build_state_to_crn_ipv6_extend_flag(const cpath_build_state_t
*state
,
2002 IF_BUG_ONCE(state
->desired_path_len
< 2)
2005 /* The last node is the relay doing the self-test. So we want to extend over
2006 * IPv6 from the second-last node. */
2007 if (state
->is_ipv6_selftest
&& cur_len
== state
->desired_path_len
- 2)
2008 return CRN_INITIATE_IPV6_EXTEND
;
2013 /** Decide a suitable length for circ's cpath, and pick an exit
2014 * router (or use <b>exit</b> if provided). Store these in the
2017 * If <b>is_hs_v3_rp_circuit</b> is set, then this exit should be suitable to
2018 * be used as an HS v3 rendezvous point.
2020 * Return 0 if ok, -1 if circuit should be closed. */
2022 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit_ei
,
2023 int is_hs_v3_rp_circuit
)
2025 cpath_build_state_t
*state
= circ
->build_state
;
2027 if (state
->onehop_tunnel
) {
2028 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel%s.",
2029 (hs_service_allow_non_anonymous_connection(get_options()) ?
2030 ", or intro or rendezvous connection" : ""));
2031 state
->desired_path_len
= 1;
2033 int r
= new_route_len(circ
->base_
.purpose
, exit_ei
, nodelist_get_list());
2034 if (r
< 1) /* must be at least 1 */
2036 state
->desired_path_len
= r
;
2039 if (exit_ei
) { /* the circuit-builder pre-requested one */
2040 warn_if_last_router_excluded(circ
, exit_ei
);
2041 log_info(LD_CIRC
,"Using requested exit node '%s'",
2042 extend_info_describe(exit_ei
));
2043 exit_ei
= extend_info_dup(exit_ei
);
2044 } else { /* we have to decide one */
2045 router_crn_flags_t flags
= CRN_NEED_DESC
;
2046 flags
|= cpath_build_state_to_crn_flags(state
);
2047 /* Some internal exits are one hop, for example directory connections.
2048 * (Guards are always direct, middles are never direct.) */
2049 if (state
->onehop_tunnel
)
2050 flags
|= CRN_DIRECT_CONN
;
2051 if (is_hs_v3_rp_circuit
)
2052 flags
|= CRN_RENDEZVOUS_V3
;
2053 const node_t
*node
=
2054 choose_good_exit_server(circ
, flags
, state
->is_internal
);
2056 log_warn(LD_CIRC
,"Failed to choose an exit server");
2059 exit_ei
= extend_info_from_node(node
, state
->onehop_tunnel
);
2060 if (BUG(exit_ei
== NULL
))
2063 state
->chosen_exit
= exit_ei
;
2067 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
2068 * hop to the cpath reflecting this. Don't send the next extend cell --
2069 * the caller will do this if it wants to.
2072 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit_ei
)
2074 cpath_build_state_t
*state
;
2075 tor_assert(exit_ei
);
2078 state
= circ
->build_state
;
2080 extend_info_free(state
->chosen_exit
);
2081 state
->chosen_exit
= extend_info_dup(exit_ei
);
2083 ++circ
->build_state
->desired_path_len
;
2084 cpath_append_hop(&circ
->cpath
, exit_ei
);
2088 /** Take an open <b>circ</b>, and add a new hop at the end, based on
2089 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
2090 * send the next extend cell to begin connecting to that hop.
2093 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit_ei
)
2096 warn_if_last_router_excluded(circ
, exit_ei
);
2098 tor_gettimeofday(&circ
->base_
.timestamp_began
);
2100 circuit_append_new_exit(circ
, exit_ei
);
2101 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2102 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
2103 log_warn(LD_CIRC
, "Couldn't extend circuit to new point %s.",
2104 extend_info_describe(exit_ei
));
2105 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2109 // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
2114 /** Return the number of routers in <b>nodes</b> that are currently up and
2115 * available for building circuits through.
2117 * If <b>direct</b> is true, only count nodes that are suitable for direct
2118 * connections. Counts nodes regardless of whether their addresses are
2121 MOCK_IMPL(STATIC
int,
2122 count_acceptable_nodes
, (const smartlist_t
*nodes
, int direct
))
2125 int flags
= CRN_NEED_DESC
;
2128 flags
|= CRN_DIRECT_CONN
;
2130 SMARTLIST_FOREACH_BEGIN(nodes
, const node_t
*, node
) {
2131 // log_debug(LD_CIRC,
2132 // "Contemplating whether router %d (%s) is a new option.",
2134 if (!router_can_choose_node(node
, flags
))
2137 } SMARTLIST_FOREACH_END(node
);
2139 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2145 * Build the exclude list for vanguard circuits.
2147 * For vanguard circuits we exclude all the already chosen nodes (including the
2148 * exit) from being middle hops to prevent the creation of A - B - A subpaths.
2149 * We also allow the 4th hop to be the same as the guard node so as to not leak
2150 * guard information to RP/IP/HSDirs.
2152 * For vanguard circuits, we don't apply any subnet or family restrictions.
2153 * This is to avoid impossible-to-build circuit paths, or just situations where
2154 * our earlier guards prevent us from using most of our later ones.
2156 * The alternative is building the circuit in reverse. Reverse calls to
2157 * onion_extend_cpath() (ie: select outer hops first) would then have the
2158 * property that you don't gain information about inner hops by observing
2159 * outer ones. See https://bugs.torproject.org/tpo/core/tor/24487
2162 * (Note further that we still exclude the exit to prevent A - B - A
2163 * at the end of the path. */
2164 static smartlist_t
*
2165 build_vanguard_middle_exclude_list(uint8_t purpose
,
2166 cpath_build_state_t
*state
,
2170 smartlist_t
*excluded
;
2172 crypt_path_t
*cpath
;
2177 excluded
= smartlist_new();
2179 /* Add the exit to the exclude list (note that the exit/last hop is always
2180 * chosen first in circuit_establish_circuit()). */
2181 if ((r
= build_state_get_exit_node(state
))) {
2182 smartlist_add(excluded
, (node_t
*)r
);
2185 /* If we are picking the 4th hop, allow that node to be the guard too.
2186 * This prevents us from avoiding the Guard for those hops, which
2187 * gives the adversary information about our guard if they control
2188 * the RP, IP, or HSDIR. We don't do this check based on purpose
2189 * because we also want to allow HS_VANGUARDS pre-build circuits
2190 * to use the guard for that last hop.
2192 if (cur_len
== DEFAULT_ROUTE_LEN
+1) {
2193 /* Skip the first hop for the exclude list below */
2198 for (i
= 0, cpath
= head
; cpath
&& i
< cur_len
; ++i
, cpath
=cpath
->next
) {
2199 if ((r
= node_get_by_id(cpath
->extend_info
->identity_digest
))) {
2200 smartlist_add(excluded
, (node_t
*)r
);
2208 * Build a list of nodes to exclude from the choice of this middle
2209 * hop, based on already chosen nodes.
2211 static smartlist_t
*
2212 build_middle_exclude_list(uint8_t purpose
,
2213 cpath_build_state_t
*state
,
2217 smartlist_t
*excluded
;
2219 crypt_path_t
*cpath
;
2222 /** Vanguard circuits have their own path selection rules */
2223 if (circuit_should_use_vanguards(purpose
)) {
2224 return build_vanguard_middle_exclude_list(purpose
, state
, head
, cur_len
);
2227 excluded
= smartlist_new();
2229 /* For non-vanguard circuits, add the exit and its family to the exclude list
2230 * (note that the exit/last hop is always chosen first in
2231 * circuit_establish_circuit()). */
2232 if ((r
= build_state_get_exit_node(state
))) {
2233 nodelist_add_node_and_family(excluded
, r
);
2236 /* also exclude all other already chosen nodes and their family */
2237 for (i
= 0, cpath
= head
; cpath
&& i
< cur_len
; ++i
, cpath
=cpath
->next
) {
2238 if ((r
= node_get_by_id(cpath
->extend_info
->identity_digest
))) {
2239 nodelist_add_node_and_family(excluded
, r
);
2246 /** Return true if we MUST use vanguards for picking this middle node. */
2248 middle_node_must_be_vanguard(const or_options_t
*options
,
2249 uint8_t purpose
, int cur_len
)
2251 /* If this is not a hidden service circuit, don't use vanguards */
2252 if (!circuit_purpose_is_hidden_service(purpose
)) {
2256 /* If we have sticky L2 nodes, and this is an L2 pick, use vanguards */
2257 if (options
->HSLayer2Nodes
&& cur_len
== 1) {
2261 /* If we have sticky L3 nodes, and this is an L3 pick, use vanguards */
2262 if (options
->HSLayer3Nodes
&& cur_len
== 2) {
2269 /** Pick a sticky vanguard middle node or return NULL if not found.
2270 * See doc of pick_restricted_middle_node() for argument details. */
2271 static const node_t
*
2272 pick_vanguard_middle_node(const or_options_t
*options
,
2273 router_crn_flags_t flags
, int cur_len
,
2274 const smartlist_t
*excluded
)
2276 const routerset_t
*vanguard_routerset
= NULL
;
2277 const node_t
*node
= NULL
;
2279 /* Pick the right routerset based on the current hop */
2281 vanguard_routerset
= options
->HSLayer2Nodes
;
2282 } else if (cur_len
== 2) {
2283 vanguard_routerset
= options
->HSLayer3Nodes
;
2285 /* guaranteed by middle_node_should_be_vanguard() */
2286 tor_assert_nonfatal_unreached();
2290 node
= pick_restricted_middle_node(flags
, vanguard_routerset
,
2291 options
->ExcludeNodes
, excluded
,
2295 static ratelim_t pinned_warning_limit
= RATELIM_INIT(300);
2296 log_fn_ratelim(&pinned_warning_limit
, LOG_WARN
, LD_CIRC
,
2297 "Could not find a node that matches the configured "
2298 "_HSLayer%dNodes set", cur_len
+1);
2304 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
2305 * and <b>state</b> and the cpath <b>head</b> (currently populated only
2306 * to length <b>cur_len</b> to decide a suitable middle hop for a
2307 * circuit. In particular, make sure we don't pick the exit node or its
2308 * family, and make sure we don't duplicate any previous nodes or their
2310 static const node_t
*
2311 choose_good_middle_server(uint8_t purpose
,
2312 cpath_build_state_t
*state
,
2316 const node_t
*choice
;
2317 smartlist_t
*excluded
;
2318 const or_options_t
*options
= get_options();
2319 router_crn_flags_t flags
= CRN_NEED_DESC
;
2320 tor_assert(CIRCUIT_PURPOSE_MIN_
<= purpose
&&
2321 purpose
<= CIRCUIT_PURPOSE_MAX_
);
2323 log_debug(LD_CIRC
, "Contemplating intermediate hop #%d: random choice.",
2326 excluded
= build_middle_exclude_list(purpose
, state
, head
, cur_len
);
2328 flags
|= cpath_build_state_to_crn_flags(state
);
2329 flags
|= cpath_build_state_to_crn_ipv6_extend_flag(state
, cur_len
);
2331 /** If a hidden service circuit wants a specific middle node, pin it. */
2332 if (middle_node_must_be_vanguard(options
, purpose
, cur_len
)) {
2333 log_debug(LD_GENERAL
, "Picking a sticky node (cur_len = %d)", cur_len
);
2334 choice
= pick_vanguard_middle_node(options
, flags
, cur_len
, excluded
);
2335 smartlist_free(excluded
);
2339 if (options
->MiddleNodes
) {
2340 smartlist_t
*sl
= smartlist_new();
2341 routerset_get_all_nodes(sl
, options
->MiddleNodes
,
2342 options
->ExcludeNodes
, 1);
2344 smartlist_subtract(sl
, excluded
);
2346 choice
= node_sl_choose_by_bandwidth(sl
, WEIGHT_FOR_MID
);
2349 log_fn(LOG_INFO
, LD_CIRC
, "Chose fixed middle node: %s",
2350 hex_str(choice
->identity
, DIGEST_LEN
));
2352 log_fn(LOG_NOTICE
, LD_CIRC
, "Restricted middle not available");
2355 choice
= router_choose_random_node(excluded
, options
->ExcludeNodes
, flags
);
2357 smartlist_free(excluded
);
2361 /** Pick a good entry server for the circuit to be built according to
2362 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2363 * router (if we're an OR), and respect firewall settings; if we're
2364 * configured to use entry guards, return one.
2366 * Set *<b>guard_state_out</b> to information about the guard that
2367 * we're selecting, which we'll use later to remember whether the
2368 * guard worked or not.
2371 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
,
2372 circuit_guard_state_t
**guard_state_out
)
2374 const node_t
*choice
;
2375 smartlist_t
*excluded
;
2376 const or_options_t
*options
= get_options();
2377 /* If possible, choose an entry server with a preferred address,
2378 * otherwise, choose one with an allowed address */
2379 router_crn_flags_t flags
= (CRN_NEED_GUARD
|CRN_NEED_DESC
|CRN_PREF_ADDR
|
2383 /* Once we used this function to select a node to be a guard. We had
2384 * 'state == NULL' be the signal for that. But we don't do that any more.
2386 tor_assert_nonfatal(state
);
2388 if (state
&& options
->UseEntryGuards
&&
2389 (purpose
!= CIRCUIT_PURPOSE_TESTING
|| options
->BridgeRelay
)) {
2390 /* This request is for an entry server to use for a regular circuit,
2391 * and we use entry guard nodes. Just return one of the guard nodes. */
2392 tor_assert(guard_state_out
);
2393 return guards_choose_guard(state
, purpose
, guard_state_out
);
2396 excluded
= smartlist_new();
2398 if (state
&& (node
= build_state_get_exit_node(state
))) {
2399 /* Exclude the exit node from the state, if we have one. Also exclude its
2401 nodelist_add_node_and_family(excluded
, node
);
2405 flags
|= cpath_build_state_to_crn_flags(state
);
2408 choice
= router_choose_random_node(excluded
, options
->ExcludeNodes
, flags
);
2409 smartlist_free(excluded
);
2413 /** Choose a suitable next hop for the circuit <b>circ</b>.
2414 * Append the hop info to circ->cpath.
2416 * Return 1 if the path is complete, 0 if we successfully added a hop,
2420 onion_extend_cpath(origin_circuit_t
*circ
)
2422 uint8_t purpose
= circ
->base_
.purpose
;
2423 cpath_build_state_t
*state
= circ
->build_state
;
2424 int cur_len
= circuit_get_cpath_len(circ
);
2425 extend_info_t
*info
= NULL
;
2427 if (cur_len
>= state
->desired_path_len
) {
2428 log_debug(LD_CIRC
, "Path is complete: %d steps long",
2429 state
->desired_path_len
);
2433 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
2434 state
->desired_path_len
);
2436 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
2437 info
= extend_info_dup(state
->chosen_exit
);
2438 } else if (cur_len
== 0) { /* picking first node */
2439 const node_t
*r
= choose_good_entry_server(purpose
, state
,
2440 &circ
->guard_state
);
2442 /* If we're a client, use the preferred address rather than the
2443 primary address, for potentially connecting to an IPv6 OR
2444 port. Servers always want the primary (IPv4) address. */
2445 int client
= (server_mode(get_options()) == 0);
2446 info
= extend_info_from_node(r
, client
);
2447 /* Clients can fail to find an allowed address */
2448 tor_assert_nonfatal(info
|| client
);
2452 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
2454 info
= extend_info_from_node(r
, 0);
2459 log_warn(LD_CIRC
,"Failed to find node for hop #%d of our path. Discarding "
2460 "this circuit.", cur_len
+1);
2464 log_debug(LD_CIRC
,"Chose router %s for hop #%d (exit is %s)",
2465 extend_info_describe(info
),
2466 cur_len
+1, build_state_get_exit_nickname(state
));
2468 cpath_append_hop(&circ
->cpath
, info
);
2469 extend_info_free(info
);
2473 /** Return the node_t for the chosen exit router in <b>state</b>.
2474 * If there is no chosen exit, or if we don't know the node_t for
2475 * the chosen exit, return NULL.
2477 MOCK_IMPL(const node_t
*,
2478 build_state_get_exit_node
,(cpath_build_state_t
*state
))
2480 if (!state
|| !state
->chosen_exit
)
2482 return node_get_by_id(state
->chosen_exit
->identity_digest
);
2485 /** Return the RSA ID digest for the chosen exit router in <b>state</b>.
2486 * If there is no chosen exit, return NULL.
2489 build_state_get_exit_rsa_id(cpath_build_state_t
*state
)
2491 if (!state
|| !state
->chosen_exit
)
2493 return (const uint8_t *) state
->chosen_exit
->identity_digest
;
2496 /** Return the nickname for the chosen exit router in <b>state</b>. If
2497 * there is no chosen exit, or if we don't know the routerinfo_t for the
2498 * chosen exit, return NULL.
2501 build_state_get_exit_nickname(cpath_build_state_t
*state
)
2503 if (!state
|| !state
->chosen_exit
)
2505 return state
->chosen_exit
->nickname
;
2508 /* Is circuit purpose allowed to use the deprecated TAP encryption protocol?
2509 * The hidden service protocol still uses TAP for some connections, because
2510 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2512 circuit_purpose_can_use_tap_impl(uint8_t purpose
)
2514 return (purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
||
2515 purpose
== CIRCUIT_PURPOSE_C_INTRODUCING
);
2518 /* Is circ allowed to use the deprecated TAP encryption protocol?
2519 * The hidden service protocol still uses TAP for some connections, because
2520 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2522 circuit_can_use_tap(const origin_circuit_t
*circ
)
2525 tor_assert(circ
->cpath
);
2526 tor_assert(circ
->cpath
->extend_info
);
2527 return (circuit_purpose_can_use_tap_impl(circ
->base_
.purpose
) &&
2528 extend_info_supports_tap(circ
->cpath
->extend_info
));
2531 /* Does circ have an onion key which it's allowed to use? */
2533 circuit_has_usable_onion_key(const origin_circuit_t
*circ
)
2536 tor_assert(circ
->cpath
);
2537 tor_assert(circ
->cpath
->extend_info
);
2538 return (extend_info_supports_ntor(circ
->cpath
->extend_info
) ||
2539 circuit_can_use_tap(circ
));
2542 /** Find the circuits that are waiting to find out whether their guards are
2543 * usable, and if any are ready to become usable, mark them open and try
2544 * attaching streams as appropriate. */
2546 circuit_upgrade_circuits_from_guard_wait(void)
2548 smartlist_t
*to_upgrade
=
2549 circuit_find_circuits_to_upgrade_from_guard_wait();
2551 if (to_upgrade
== NULL
)
2554 log_info(LD_GUARD
, "Upgrading %d circuits from 'waiting for better guard' "
2555 "to 'open'.", smartlist_len(to_upgrade
));
2557 SMARTLIST_FOREACH_BEGIN(to_upgrade
, origin_circuit_t
*, circ
) {
2558 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
2559 circuit_has_opened(circ
);
2560 } SMARTLIST_FOREACH_END(circ
);
2562 smartlist_free(to_upgrade
);