Validate ed25519 keys and canonicity from circuit_n_conn_done()
[tor.git] / src / core / or / circuitbuild.c
blob67b47b38f10b62b4be76e42e5dfbedb9830aedf7
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-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file circuitbuild.c
10 * \brief Implements the details of building circuits (by chosing 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 * On the server side, this module also handles the logic of responding to
25 * RELAY_EXTEND requests, using circuit_extend().
26 **/
28 #define CIRCUITBUILD_PRIVATE
30 #include "core/or/or.h"
31 #include "app/config/config.h"
32 #include "app/config/confparse.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/crypto/relay_crypto.h"
38 #include "core/mainloop/connection.h"
39 #include "core/mainloop/mainloop.h"
40 #include "core/or/channel.h"
41 #include "core/or/circuitbuild.h"
42 #include "core/or/circuitlist.h"
43 #include "core/or/circuitstats.h"
44 #include "core/or/circuituse.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/onion.h"
49 #include "core/or/policies.h"
50 #include "core/or/relay.h"
51 #include "feature/client/bridges.h"
52 #include "feature/client/circpathbias.h"
53 #include "feature/client/entrynodes.h"
54 #include "feature/client/transports.h"
55 #include "feature/control/control.h"
56 #include "feature/dircommon/directory.h"
57 #include "feature/nodelist/describe.h"
58 #include "feature/nodelist/microdesc.h"
59 #include "feature/nodelist/networkstatus.h"
60 #include "feature/nodelist/nickname.h"
61 #include "feature/nodelist/node_select.h"
62 #include "feature/nodelist/nodelist.h"
63 #include "feature/nodelist/routerlist.h"
64 #include "feature/nodelist/routerset.h"
65 #include "feature/relay/router.h"
66 #include "feature/relay/routermode.h"
67 #include "feature/relay/selftest.h"
68 #include "feature/rend/rendcommon.h"
69 #include "feature/stats/predict_ports.h"
70 #include "lib/crypt_ops/crypto_rand.h"
72 #include "core/or/cell_st.h"
73 #include "core/or/cpath_build_state_st.h"
74 #include "core/or/entry_connection_st.h"
75 #include "core/or/extend_info_st.h"
76 #include "feature/nodelist/node_st.h"
77 #include "core/or/or_circuit_st.h"
78 #include "core/or/origin_circuit_st.h"
79 #include "feature/nodelist/microdesc_st.h"
80 #include "feature/nodelist/routerinfo_st.h"
81 #include "feature/nodelist/routerstatus_st.h"
83 static channel_t * channel_connect_for_circuit(const tor_addr_t *addr,
84 uint16_t port,
85 const char *id_digest,
86 const ed25519_public_key_t *ed_id);
87 static int circuit_deliver_create_cell(circuit_t *circ,
88 const create_cell_t *create_cell,
89 int relayed);
90 static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
91 STATIC int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
92 static int circuit_send_first_onion_skin(origin_circuit_t *circ);
93 static int circuit_build_no_more_hops(origin_circuit_t *circ);
94 static int circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
95 crypt_path_t *hop);
96 static const node_t *choose_good_middle_server(uint8_t purpose,
97 cpath_build_state_t *state,
98 crypt_path_t *head,
99 int cur_len);
101 /** This function tries to get a channel to the specified endpoint,
102 * and then calls command_setup_channel() to give it the right
103 * callbacks.
105 static channel_t *
106 channel_connect_for_circuit(const tor_addr_t *addr, uint16_t port,
107 const char *id_digest,
108 const ed25519_public_key_t *ed_id)
110 channel_t *chan;
112 chan = channel_connect(addr, port, id_digest, ed_id);
113 if (chan) command_setup_channel(chan);
115 return chan;
118 /** Search for a value for circ_id that we can use on <b>chan</b> for an
119 * outbound circuit, until we get a circ_id that is not in use by any other
120 * circuit on that conn.
122 * Return it, or 0 if can't get a unique circ_id.
124 STATIC circid_t
125 get_unique_circ_id_by_chan(channel_t *chan)
127 /* This number is chosen somewhat arbitrarily; see comment below for more
128 * info. When the space is 80% full, it gives a one-in-a-million failure
129 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
130 * the space is 95% full, it gives a one-in-26 failure chance. That seems
131 * okay, though you could make a case IMO for anything between N=32 and
132 * N=256. */
133 #define MAX_CIRCID_ATTEMPTS 64
134 int in_use;
135 unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
136 circid_t test_circ_id;
137 circid_t attempts=0;
138 circid_t high_bit, max_range, mask;
139 int64_t pending_destroy_time_total = 0;
140 int64_t pending_destroy_time_max = 0;
142 tor_assert(chan);
144 if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
145 log_warn(LD_BUG,
146 "Trying to pick a circuit ID for a connection from "
147 "a client with no identity.");
148 return 0;
150 max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
151 mask = max_range - 1;
152 high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
153 do {
154 if (++attempts > MAX_CIRCID_ATTEMPTS) {
155 /* Make sure we don't loop forever because all circuit IDs are used.
157 * Once, we would try until we had tried every possible circuit ID. But
158 * that's quite expensive. Instead, we try MAX_CIRCID_ATTEMPTS random
159 * circuit IDs, and then give up.
161 * This potentially causes us to give up early if our circuit ID space
162 * is nearly full. If we have N circuit IDs in use, then we will reject
163 * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
164 * This means that in practice, a few percent of our circuit ID capacity
165 * will go unused.
167 * The alternative here, though, is to do a linear search over the
168 * whole circuit ID space every time we extend a circuit, which is
169 * not so great either.
171 int64_t queued_destroys;
172 char *m = rate_limit_log(&chan->last_warned_circ_ids_exhausted,
173 approx_time());
174 if (m == NULL)
175 return 0; /* This message has been rate-limited away. */
176 if (n_pending_destroy)
177 pending_destroy_time_total /= n_pending_destroy;
178 log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
179 "circID support, with %u inbound and %u outbound circuits. "
180 "Found %u circuit IDs in use by circuits, and %u with "
181 "pending destroy cells. (%u of those were marked bogusly.) "
182 "The ones with pending destroy cells "
183 "have been marked unusable for an average of %ld seconds "
184 "and a maximum of %ld seconds. This channel is %ld seconds "
185 "old. Failing a circuit.%s",
186 chan->wide_circ_ids ? "with" : "without",
187 chan->num_p_circuits, chan->num_n_circuits,
188 n_with_circ, n_pending_destroy, n_weird_pending_destroy,
189 (long)pending_destroy_time_total,
190 (long)pending_destroy_time_max,
191 (long)(approx_time() - chan->timestamp_created),
193 tor_free(m);
195 if (!chan->cmux) {
196 /* This warning should be impossible. */
197 log_warn(LD_BUG, " This channel somehow has no cmux on it!");
198 return 0;
201 /* analysis so far on 12184 suggests that we're running out of circuit
202 IDs because it looks like we have too many pending destroy
203 cells. Let's see how many we really have pending.
205 queued_destroys = circuitmux_count_queued_destroy_cells(chan,
206 chan->cmux);
208 log_warn(LD_CIRC, " Circuitmux on this channel has %u circuits, "
209 "of which %u are active. It says it has %"PRId64
210 " destroy cells queued.",
211 circuitmux_num_circuits(chan->cmux),
212 circuitmux_num_active_circuits(chan->cmux),
213 (queued_destroys));
215 /* Change this into "if (1)" in order to get more information about
216 * possible failure modes here. You'll need to know how to use gdb with
217 * Tor: this will make Tor exit with an assertion failure if the cmux is
218 * corrupt. */
219 if (0)
220 circuitmux_assert_okay(chan->cmux);
222 channel_dump_statistics(chan, LOG_WARN);
224 return 0;
227 do {
228 crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
229 test_circ_id &= mask;
230 } while (test_circ_id == 0);
232 test_circ_id |= high_bit;
234 in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
235 if (in_use == 1)
236 ++n_with_circ;
237 else if (in_use == 2) {
238 time_t since_when;
239 ++n_pending_destroy;
240 since_when =
241 circuit_id_when_marked_unusable_on_channel(test_circ_id, chan);
242 if (since_when) {
243 time_t waiting = approx_time() - since_when;
244 pending_destroy_time_total += waiting;
245 if (waiting > pending_destroy_time_max)
246 pending_destroy_time_max = waiting;
247 } else {
248 ++n_weird_pending_destroy;
251 } while (in_use);
252 return test_circ_id;
255 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
256 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
257 * list information about link status in a more verbose format using spaces.
258 * If <b>verbose_names</b> is false, give hex digests; if <b>verbose_names</b>
259 * is true, use $DIGEST=Name style names.
261 static char *
262 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
264 crypt_path_t *hop;
265 smartlist_t *elements;
266 const char *states[] = {"closed", "waiting for keys", "open"};
267 char *s;
269 elements = smartlist_new();
271 if (verbose) {
272 const char *nickname = build_state_get_exit_nickname(circ->build_state);
273 smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
274 circ->build_state->is_internal ? "internal" : "exit",
275 circ->build_state->need_uptime ? " (high-uptime)" : "",
276 circ->build_state->desired_path_len,
277 circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
278 circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
279 (nickname?nickname:"*unnamed*"));
282 hop = circ->cpath;
283 do {
284 char *elt;
285 const char *id;
286 const node_t *node;
287 if (!hop)
288 break;
289 if (!verbose && hop->state != CPATH_STATE_OPEN)
290 break;
291 if (!hop->extend_info)
292 break;
293 id = hop->extend_info->identity_digest;
294 if (verbose_names) {
295 elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
296 if ((node = node_get_by_id(id))) {
297 node_get_verbose_nickname(node, elt);
298 } else if (is_legal_nickname(hop->extend_info->nickname)) {
299 elt[0] = '$';
300 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
301 elt[HEX_DIGEST_LEN+1]= '~';
302 strlcpy(elt+HEX_DIGEST_LEN+2,
303 hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
304 } else {
305 elt[0] = '$';
306 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
308 } else { /* ! verbose_names */
309 elt = tor_malloc(HEX_DIGEST_LEN+2);
310 elt[0] = '$';
311 base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
313 tor_assert(elt);
314 if (verbose) {
315 tor_assert(hop->state <= 2);
316 smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
317 tor_free(elt);
318 } else {
319 smartlist_add(elements, elt);
321 hop = hop->next;
322 } while (hop != circ->cpath);
324 s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
325 SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
326 smartlist_free(elements);
327 return s;
330 /** If <b>verbose</b> is false, allocate and return a comma-separated
331 * list of the currently built elements of <b>circ</b>. If
332 * <b>verbose</b> is true, also list information about link status in
333 * a more verbose format using spaces.
335 char *
336 circuit_list_path(origin_circuit_t *circ, int verbose)
338 return circuit_list_path_impl(circ, verbose, 0);
341 /** Allocate and return a comma-separated list of the currently built elements
342 * of <b>circ</b>, giving each as a verbose nickname.
344 char *
345 circuit_list_path_for_controller(origin_circuit_t *circ)
347 return circuit_list_path_impl(circ, 0, 1);
350 /** Log, at severity <b>severity</b>, the nicknames of each router in
351 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
352 * exit point.
354 void
355 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
357 char *s = circuit_list_path(circ,1);
358 tor_log(severity,domain,"%s",s);
359 tor_free(s);
362 /** Return 1 iff every node in circ's cpath definitely supports ntor. */
363 static int
364 circuit_cpath_supports_ntor(const origin_circuit_t *circ)
366 crypt_path_t *head, *cpath;
368 cpath = head = circ->cpath;
369 do {
370 /* if the extend_info is missing, we can't tell if it supports ntor */
371 if (!cpath->extend_info) {
372 return 0;
375 /* if the key is blank, it definitely doesn't support ntor */
376 if (!extend_info_supports_ntor(cpath->extend_info)) {
377 return 0;
379 cpath = cpath->next;
380 } while (cpath != head);
382 return 1;
385 /** Pick all the entries in our cpath. Stop and return 0 when we're
386 * happy, or return -1 if an error occurs. */
387 static int
388 onion_populate_cpath(origin_circuit_t *circ)
390 int r = 0;
392 /* onion_extend_cpath assumes these are non-NULL */
393 tor_assert(circ);
394 tor_assert(circ->build_state);
396 while (r == 0) {
397 r = onion_extend_cpath(circ);
398 if (r < 0) {
399 log_info(LD_CIRC,"Generating cpath hop failed.");
400 return -1;
404 /* The path is complete */
405 tor_assert(r == 1);
407 /* Does every node in this path support ntor? */
408 int path_supports_ntor = circuit_cpath_supports_ntor(circ);
410 /* We would like every path to support ntor, but we have to allow for some
411 * edge cases. */
412 tor_assert(circuit_get_cpath_len(circ));
413 if (circuit_can_use_tap(circ)) {
414 /* Circuits from clients to intro points, and hidden services to rend
415 * points do not support ntor, because the hidden service protocol does
416 * not include ntor onion keys. This is also true for Single Onion
417 * Services. */
418 return 0;
421 if (circuit_get_cpath_len(circ) == 1) {
422 /* Allow for bootstrapping: when we're fetching directly from a fallback,
423 * authority, or bridge, we have no way of knowing its ntor onion key
424 * before we connect to it. So instead, we try connecting, and end up using
425 * CREATE_FAST. */
426 tor_assert(circ->cpath);
427 tor_assert(circ->cpath->extend_info);
428 const node_t *node = node_get_by_id(
429 circ->cpath->extend_info->identity_digest);
430 /* If we don't know the node and its descriptor, we must be bootstrapping.
432 if (!node || !node_has_preferred_descriptor(node, 1)) {
433 return 0;
437 if (BUG(!path_supports_ntor)) {
438 /* If we're building a multi-hop path, and it's not one of the HS or
439 * bootstrapping exceptions, and it doesn't support ntor, something has
440 * gone wrong. */
441 return -1;
444 return 0;
447 /** Create and return a new origin circuit. Initialize its purpose and
448 * build-state based on our arguments. The <b>flags</b> argument is a
449 * bitfield of CIRCLAUNCH_* flags. */
450 origin_circuit_t *
451 origin_circuit_init(uint8_t purpose, int flags)
453 /* sets circ->p_circ_id and circ->p_chan */
454 origin_circuit_t *circ = origin_circuit_new();
455 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
456 circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
457 circ->build_state->onehop_tunnel =
458 ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
459 circ->build_state->need_uptime =
460 ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
461 circ->build_state->need_capacity =
462 ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
463 circ->build_state->is_internal =
464 ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
465 circ->base_.purpose = purpose;
466 return circ;
469 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
470 * is defined, then use that as your exit router, else choose a suitable
471 * exit node.
473 * Also launch a connection to the first OR in the chosen path, if
474 * it's not open already.
476 origin_circuit_t *
477 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
479 origin_circuit_t *circ;
480 int err_reason = 0;
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);
492 return NULL;
495 control_event_circuit_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);
499 return NULL;
501 return circ;
504 /** Return the guard state associated with <b>circ</b>, which may be NULL. */
505 circuit_guard_state_t *
506 origin_circuit_get_guard_state(origin_circuit_t *circ)
508 return circ->guard_state;
511 /** Start establishing the first hop of our circuit. Figure out what
512 * OR we should connect to, and if necessary start the connection to
513 * it. If we're already connected, then send the 'create' cell.
514 * Return 0 for ok, -reason if circ should be marked-for-close. */
516 circuit_handle_first_hop(origin_circuit_t *circ)
518 crypt_path_t *firsthop;
519 channel_t *n_chan;
520 int err_reason = 0;
521 const char *msg = NULL;
522 int should_launch = 0;
523 const or_options_t *options = get_options();
525 firsthop = onion_next_hop_in_cpath(circ->cpath);
526 tor_assert(firsthop);
527 tor_assert(firsthop->extend_info);
529 /* Some bridges are on private addresses. Others pass a dummy private
530 * address to the pluggable transport, which ignores it.
531 * Deny the connection if:
532 * - the address is internal, and
533 * - we're not connecting to a configured bridge, and
534 * - we're not configured to allow extends to private addresses. */
535 if (tor_addr_is_internal(&firsthop->extend_info->addr, 0) &&
536 !extend_info_is_a_configured_bridge(firsthop->extend_info) &&
537 !options->ExtendAllowPrivateAddresses) {
538 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
539 "Client asked me to connect directly to a private address");
540 return -END_CIRC_REASON_TORPROTOCOL;
543 /* now see if we're already connected to the first OR in 'route' */
544 log_debug(LD_CIRC,"Looking for firsthop '%s'",
545 fmt_addrport(&firsthop->extend_info->addr,
546 firsthop->extend_info->port));
548 n_chan = channel_get_for_extend(firsthop->extend_info->identity_digest,
549 &firsthop->extend_info->ed_identity,
550 &firsthop->extend_info->addr,
551 &msg,
552 &should_launch);
554 if (!n_chan) {
555 /* not currently connected in a useful way. */
556 log_info(LD_CIRC, "Next router is %s: %s",
557 safe_str_client(extend_info_describe(firsthop->extend_info)),
558 msg?msg:"???");
559 circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
561 if (should_launch) {
562 if (circ->build_state->onehop_tunnel)
563 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
564 n_chan = channel_connect_for_circuit(
565 &firsthop->extend_info->addr,
566 firsthop->extend_info->port,
567 firsthop->extend_info->identity_digest,
568 &firsthop->extend_info->ed_identity);
569 if (!n_chan) { /* connect failed, forget the whole thing */
570 log_info(LD_CIRC,"connect to firsthop failed. Closing.");
571 return -END_CIRC_REASON_CONNECTFAILED;
575 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
576 /* return success. The onion/circuit/etc will be taken care of
577 * automatically (may already have been) whenever n_chan reaches
578 * OR_CONN_STATE_OPEN.
580 return 0;
581 } else { /* it's already open. use it. */
582 tor_assert(!circ->base_.n_hop);
583 circ->base_.n_chan = n_chan;
584 log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
585 if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
586 log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
587 circ->base_.n_chan = NULL;
588 return err_reason;
591 return 0;
594 /** Find any circuits that are waiting on <b>or_conn</b> to become
595 * open and get them to send their create cells forward.
597 * Status is 1 if connect succeeded, or 0 if connect failed.
599 * Close_origin_circuits is 1 if we should close all the origin circuits
600 * through this channel, or 0 otherwise. (This happens when we want to retry
601 * an older guard.)
603 void
604 circuit_n_chan_done(channel_t *chan, int status, int close_origin_circuits)
606 smartlist_t *pending_circs;
607 int err_reason = 0;
609 tor_assert(chan);
611 log_debug(LD_CIRC,"chan to %s, status=%d",
612 channel_get_canonical_remote_descr(chan), status);
614 pending_circs = smartlist_new();
615 circuit_get_all_pending_on_channel(pending_circs, chan);
617 SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
619 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
620 * leaving them in in case it's possible for the status of a circuit to
621 * change as we're going down the list. */
622 if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
623 circ->state != CIRCUIT_STATE_CHAN_WAIT)
624 continue;
626 const char *rsa_ident = NULL;
627 const ed25519_public_key_t *ed_ident = NULL;
628 if (! tor_digest_is_zero(circ->n_hop->identity_digest)) {
629 rsa_ident = circ->n_hop->identity_digest;
631 if (! ed25519_public_key_is_zero(&circ->n_hop->ed_identity)) {
632 ed_ident = &circ->n_hop->ed_identity;
635 if (rsa_ident == NULL && ed_ident == NULL) {
636 /* Look at addr/port. This is an unkeyed connection. */
637 if (!channel_matches_extend_info(chan, circ->n_hop))
638 continue;
639 } else {
640 /* We expected a key or keys. See if they matched. */
641 if (!channel_remote_identity_matches(chan, rsa_ident, ed_ident))
642 continue;
644 /* If the channel is canonical, great. If not, it needs to match
645 * the requested address exactly. */
646 if (! chan->is_canonical &&
647 ! channel_matches_extend_info(chan, circ->n_hop)) {
648 continue;
651 if (!status) { /* chan failed; close circ */
652 log_info(LD_CIRC,"Channel failed; closing circ.");
653 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
654 continue;
657 if (close_origin_circuits && CIRCUIT_IS_ORIGIN(circ)) {
658 log_info(LD_CIRC,"Channel deprecated for origin circs; closing circ.");
659 circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
660 continue;
662 log_debug(LD_CIRC, "Found circ, sending create cell.");
663 /* circuit_deliver_create_cell will set n_circ_id and add us to
664 * chan_circuid_circuit_map, so we don't need to call
665 * set_circid_chan here. */
666 circ->n_chan = chan;
667 extend_info_free(circ->n_hop);
668 circ->n_hop = NULL;
670 if (CIRCUIT_IS_ORIGIN(circ)) {
671 if ((err_reason =
672 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
673 log_info(LD_CIRC,
674 "send_next_onion_skin failed; circuit marked for closing.");
675 circuit_mark_for_close(circ, -err_reason);
676 continue;
677 /* XXX could this be bad, eg if next_onion_skin failed because conn
678 * died? */
680 } else {
681 /* pull the create cell out of circ->n_chan_create_cell, and send it */
682 tor_assert(circ->n_chan_create_cell);
683 if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
684 circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
685 continue;
687 tor_free(circ->n_chan_create_cell);
688 circuit_set_state(circ, CIRCUIT_STATE_OPEN);
691 SMARTLIST_FOREACH_END(circ);
693 smartlist_free(pending_circs);
696 /** Find a new circid that isn't currently in use on the circ->n_chan
697 * for the outgoing
698 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
699 * circuit. If <b>relayed</b> is true, this is a create cell somebody
700 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
701 * it. Return -1 if we failed to find a suitable circid, else return 0.
703 static int
704 circuit_deliver_create_cell(circuit_t *circ, const create_cell_t *create_cell,
705 int relayed)
707 cell_t cell;
708 circid_t id;
709 int r;
711 tor_assert(circ);
712 tor_assert(circ->n_chan);
713 tor_assert(create_cell);
714 tor_assert(create_cell->cell_type == CELL_CREATE ||
715 create_cell->cell_type == CELL_CREATE_FAST ||
716 create_cell->cell_type == CELL_CREATE2);
718 id = get_unique_circ_id_by_chan(circ->n_chan);
719 if (!id) {
720 static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
721 log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
722 "failed to get unique circID.");
723 goto error;
726 memset(&cell, 0, sizeof(cell_t));
727 r = relayed ? create_cell_format_relayed(&cell, create_cell)
728 : create_cell_format(&cell, create_cell);
729 if (r < 0) {
730 log_warn(LD_CIRC,"Couldn't format create cell");
731 goto error;
733 log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
734 circuit_set_n_circid_chan(circ, id, circ->n_chan);
735 cell.circ_id = circ->n_circ_id;
737 append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
738 CELL_DIRECTION_OUT, 0);
740 if (CIRCUIT_IS_ORIGIN(circ)) {
741 /* Update began timestamp for circuits starting their first hop */
742 if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
743 if (!CHANNEL_IS_OPEN(circ->n_chan)) {
744 log_warn(LD_CIRC,
745 "Got first hop for a circuit without an opened channel. "
746 "State: %s.", channel_state_to_string(circ->n_chan->state));
747 tor_fragile_assert();
750 tor_gettimeofday(&circ->timestamp_began);
753 /* mark it so it gets better rate limiting treatment. */
754 channel_timestamp_client(circ->n_chan);
757 return 0;
758 error:
759 circ->n_chan = NULL;
760 return -1;
763 /** We've decided to start our reachability testing. If all
764 * is set, log this to the user. Return 1 if we did, or 0 if
765 * we chose not to log anything. */
767 inform_testing_reachability(void)
769 char dirbuf[128];
770 char *address;
771 const routerinfo_t *me = router_get_my_routerinfo();
772 if (!me)
773 return 0;
774 address = tor_dup_ip(me->addr);
775 control_event_server_status(LOG_NOTICE,
776 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
777 address, me->or_port);
778 if (me->dir_port) {
779 tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
780 address, me->dir_port);
781 control_event_server_status(LOG_NOTICE,
782 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
783 address, me->dir_port);
785 log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
786 "(this may take up to %d minutes -- look for log "
787 "messages indicating success)",
788 address, me->or_port,
789 me->dir_port ? dirbuf : "",
790 me->dir_port ? "are" : "is",
791 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
793 tor_free(address);
794 return 1;
797 /** Return true iff we should send a create_fast cell to start building a given
798 * circuit */
799 static inline int
800 should_use_create_fast_for_circuit(origin_circuit_t *circ)
802 const or_options_t *options = get_options();
803 tor_assert(circ->cpath);
804 tor_assert(circ->cpath->extend_info);
806 if (!circuit_has_usable_onion_key(circ)) {
807 /* We don't have ntor, and we don't have or can't use TAP,
808 * so our hand is forced: only a create_fast will work. */
809 return 1;
811 if (public_server_mode(options)) {
812 /* We're a server, and we have a usable onion key. We can choose.
813 * Prefer to blend our circuit into the other circuits we are
814 * creating on behalf of others. */
815 return 0;
817 return networkstatus_get_param(NULL, "usecreatefast", 0, 0, 1);
821 * Return true if <b>circ</b> is the type of circuit we want to count
822 * timeouts from.
824 * In particular, we want to consider any circuit that plans to build
825 * at least 3 hops (but maybe more), but has 3 or fewer hops built
826 * so far.
828 * We still want to consider circuits before 3 hops, because we need
829 * to decide if we should convert them to a measurement circuit in
830 * circuit_build_times_handle_completed_hop(), rather than letting
831 * slow circuits get killed right away.
834 circuit_timeout_want_to_count_circ(const origin_circuit_t *circ)
836 return !circ->has_opened
837 && circ->build_state->desired_path_len >= DEFAULT_ROUTE_LEN
838 && circuit_get_cpath_opened_len(circ) <= DEFAULT_ROUTE_LEN;
841 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
842 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
843 * accordingly.
844 * Note that TAP handshakes in CREATE cells are only used for direct
845 * connections:
846 * - from Single Onions to rend points not in the service's consensus.
847 * This is checked in onion_populate_cpath. */
848 static void
849 circuit_pick_create_handshake(uint8_t *cell_type_out,
850 uint16_t *handshake_type_out,
851 const extend_info_t *ei)
853 /* torspec says: In general, clients SHOULD use CREATE whenever they are
854 * using the TAP handshake, and CREATE2 otherwise. */
855 if (extend_info_supports_ntor(ei)) {
856 *cell_type_out = CELL_CREATE2;
857 *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
858 } else {
859 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
860 *cell_type_out = CELL_CREATE;
861 *handshake_type_out = ONION_HANDSHAKE_TYPE_TAP;
865 /** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
866 * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
867 * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
868 * and *<b>create_cell_type_out</b> accordingly.
869 * Note that TAP handshakes in EXTEND cells are only used:
870 * - from clients to intro points, and
871 * - from hidden services to rend points.
872 * This is checked in onion_populate_cpath.
874 static void
875 circuit_pick_extend_handshake(uint8_t *cell_type_out,
876 uint8_t *create_cell_type_out,
877 uint16_t *handshake_type_out,
878 const extend_info_t *ei)
880 uint8_t t;
881 circuit_pick_create_handshake(&t, handshake_type_out, ei);
883 /* torspec says: Clients SHOULD use the EXTEND format whenever sending a TAP
884 * handshake... In other cases, clients SHOULD use EXTEND2. */
885 if (*handshake_type_out != ONION_HANDSHAKE_TYPE_TAP) {
886 *cell_type_out = RELAY_COMMAND_EXTEND2;
887 *create_cell_type_out = CELL_CREATE2;
888 } else {
889 /* XXXX030 Remove support for deciding to use TAP and EXTEND. */
890 *cell_type_out = RELAY_COMMAND_EXTEND;
891 *create_cell_type_out = CELL_CREATE;
896 * Return true iff <b>purpose</b> is a purpose for a circuit which is
897 * allowed to have no guard configured, even if the circuit is multihop
898 * and guards are enabled.
900 static int
901 circuit_purpose_may_omit_guard(int purpose)
903 switch (purpose) {
904 case CIRCUIT_PURPOSE_TESTING:
905 case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
906 /* Testing circuits may omit guards because they're measuring
907 * liveness or performance, and don't want guards to interfere. */
908 return 1;
909 default:
910 /* All other multihop circuits should use guards if guards are
911 * enabled. */
912 return 0;
916 /** This is the backbone function for building circuits.
918 * If circ's first hop is closed, then we need to build a create
919 * cell and send it forward.
921 * Otherwise, if circ's cpath still has any non-open hops, we need to
922 * build a relay extend cell and send it forward to the next non-open hop.
924 * If all hops on the cpath are open, we're done building the circuit
925 * and we should do housekeeping for the newly opened circuit.
927 * Return -reason if we want to tear down circ, else return 0.
930 circuit_send_next_onion_skin(origin_circuit_t *circ)
932 tor_assert(circ);
934 if (circ->cpath->state == CPATH_STATE_CLOSED) {
935 /* Case one: we're on the first hop. */
936 return circuit_send_first_onion_skin(circ);
939 tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
940 tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
942 crypt_path_t *hop = onion_next_hop_in_cpath(circ->cpath);
943 circuit_build_times_handle_completed_hop(circ);
945 if (hop) {
946 /* Case two: we're on a hop after the first. */
947 return circuit_send_intermediate_onion_skin(circ, hop);
950 /* Case three: the circuit is finished. Do housekeeping tasks on it. */
951 return circuit_build_no_more_hops(circ);
955 * Called from circuit_send_next_onion_skin() when we find ourselves connected
956 * to the first hop in <b>circ</b>: Send a CREATE or CREATE2 or CREATE_FAST
957 * cell to that hop. Return 0 on success; -reason on failure (if the circuit
958 * should be torn down).
960 static int
961 circuit_send_first_onion_skin(origin_circuit_t *circ)
963 int fast;
964 int len;
965 const node_t *node;
966 create_cell_t cc;
967 memset(&cc, 0, sizeof(cc));
969 log_debug(LD_CIRC,"First skin; sending create cell.");
971 if (circ->build_state->onehop_tunnel) {
972 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
973 } else {
974 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
976 /* If this is not a one-hop tunnel, the channel is being used
977 * for traffic that wants anonymity and protection from traffic
978 * analysis (such as netflow record retention). That means we want
979 * to pad it.
981 if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
982 circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
985 node = node_get_by_id(circ->base_.n_chan->identity_digest);
986 fast = should_use_create_fast_for_circuit(circ);
987 if (!fast) {
988 /* We know the right onion key: we should send a create cell. */
989 circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
990 circ->cpath->extend_info);
991 } else {
992 /* We don't know an onion key, so we need to fall back to CREATE_FAST. */
993 cc.cell_type = CELL_CREATE_FAST;
994 cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
997 len = onion_skin_create(cc.handshake_type,
998 circ->cpath->extend_info,
999 &circ->cpath->handshake_state,
1000 cc.onionskin);
1001 if (len < 0) {
1002 log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
1003 return - END_CIRC_REASON_INTERNAL;
1005 cc.handshake_len = len;
1007 if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
1008 return - END_CIRC_REASON_RESOURCELIMIT;
1010 circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
1011 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
1012 log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
1013 fast ? "CREATE_FAST" : "CREATE",
1014 node ? node_describe(node) : "<unnamed>");
1015 return 0;
1019 * Called from circuit_send_next_onion_skin() when we find that we have no
1020 * more hops: mark the circuit as finished, and perform the necessary
1021 * bookkeeping. Return 0 on success; -reason on failure (if the circuit
1022 * should be torn down).
1024 static int
1025 circuit_build_no_more_hops(origin_circuit_t *circ)
1027 guard_usable_t r;
1028 if (! circ->guard_state) {
1029 if (circuit_get_cpath_len(circ) != 1 &&
1030 ! circuit_purpose_may_omit_guard(circ->base_.purpose) &&
1031 get_options()->UseEntryGuards) {
1032 log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
1033 "guard state",
1034 circuit_get_cpath_len(circ), circ, circ->base_.purpose);
1036 r = GUARD_USABLE_NOW;
1037 } else {
1038 r = entry_guard_succeeded(&circ->guard_state);
1040 const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
1041 if (r == GUARD_USABLE_NOW) {
1042 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1043 } else if (r == GUARD_MAYBE_USABLE_LATER) {
1044 // Wait till either a better guard succeeds, or till
1045 // all better guards fail.
1046 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_GUARD_WAIT);
1047 } else {
1048 tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
1049 return - END_CIRC_REASON_INTERNAL;
1052 /* XXXX #21422 -- the rest of this branch needs careful thought!
1053 * Some of the things here need to happen when a circuit becomes
1054 * mechanically open; some need to happen when it is actually usable.
1055 * I think I got them right, but more checking would be wise. -NM
1058 log_info(LD_CIRC,"circuit built!");
1059 circuit_reset_failure_count(0);
1061 if (circ->build_state->onehop_tunnel || circ->has_opened) {
1062 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
1065 pathbias_count_build_success(circ);
1066 if (is_usable_for_streams)
1067 circuit_has_opened(circ); /* do other actions as necessary */
1069 if (!have_completed_a_circuit() && !circ->build_state->onehop_tunnel) {
1070 const or_options_t *options = get_options();
1071 note_that_we_completed_a_circuit();
1072 /* FFFF Log a count of known routers here */
1073 log_info(LD_GENERAL,
1074 "Tor has successfully opened a circuit. "
1075 "Looks like client functionality is working.");
1076 control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
1077 control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
1078 clear_broken_connection_map(1);
1079 if (server_mode(options) && !check_whether_orport_reachable(options)) {
1080 inform_testing_reachability();
1081 router_do_reachability_checks(1, 1);
1085 /* We're done with measurement circuits here. Just close them */
1086 if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
1087 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
1089 return 0;
1093 * Called from circuit_send_next_onion_skin() when we find that we have a hop
1094 * other than the first that we need to extend to: use <b>hop</b>'s
1095 * information to extend the circuit another step. Return 0 on success;
1096 * -reason on failure (if the circuit should be torn down).
1098 static int
1099 circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
1100 crypt_path_t *hop)
1102 int len;
1103 extend_cell_t ec;
1104 memset(&ec, 0, sizeof(ec));
1106 log_debug(LD_CIRC,"starting to send subsequent skin.");
1108 if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
1109 log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
1110 return - END_CIRC_REASON_INTERNAL;
1113 circuit_pick_extend_handshake(&ec.cell_type,
1114 &ec.create_cell.cell_type,
1115 &ec.create_cell.handshake_type,
1116 hop->extend_info);
1118 tor_addr_copy(&ec.orport_ipv4.addr, &hop->extend_info->addr);
1119 ec.orport_ipv4.port = hop->extend_info->port;
1120 tor_addr_make_unspec(&ec.orport_ipv6.addr);
1121 memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
1122 /* Set the ED25519 identity too -- it will only get included
1123 * in the extend2 cell if we're configured to use it, though. */
1124 ed25519_pubkey_copy(&ec.ed_pubkey, &hop->extend_info->ed_identity);
1126 len = onion_skin_create(ec.create_cell.handshake_type,
1127 hop->extend_info,
1128 &hop->handshake_state,
1129 ec.create_cell.onionskin);
1130 if (len < 0) {
1131 log_warn(LD_CIRC,"onion_skin_create failed.");
1132 return - END_CIRC_REASON_INTERNAL;
1134 ec.create_cell.handshake_len = len;
1136 log_info(LD_CIRC,"Sending extend relay cell.");
1138 uint8_t command = 0;
1139 uint16_t payload_len=0;
1140 uint8_t payload[RELAY_PAYLOAD_SIZE];
1141 if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
1142 log_warn(LD_CIRC,"Couldn't format extend cell");
1143 return -END_CIRC_REASON_INTERNAL;
1146 /* send it to hop->prev, because that relay will transfer
1147 * it to a create cell and then send to hop */
1148 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1149 command,
1150 (char*)payload, payload_len,
1151 hop->prev) < 0)
1152 return 0; /* circuit is closed */
1154 hop->state = CPATH_STATE_AWAITING_KEYS;
1155 return 0;
1158 /** Our clock just jumped by <b>seconds_elapsed</b>. If <b>was_idle</b> is
1159 * true, then the monotonic time matches; otherwise it doesn't. Assume
1160 * something has also gone wrong with our network: notify the user, and
1161 * abandon all not-yet-used circuits. */
1162 void
1163 circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
1165 int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
1166 if (was_idle) {
1167 tor_log(severity, LD_GENERAL, "Tor has been idle for %"PRId64
1168 " seconds; assuming established circuits no longer work.",
1169 (seconds_elapsed));
1170 } else {
1171 tor_log(severity, LD_GENERAL,
1172 "Your system clock just jumped %"PRId64" seconds %s; "
1173 "assuming established circuits no longer work.",
1175 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed),
1176 seconds_elapsed >=0 ? "forward" : "backward");
1178 control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%"PRId64
1179 " IDLE=%d",
1180 (seconds_elapsed), was_idle?1:0);
1181 /* so we log when it works again */
1182 note_that_we_maybe_cant_complete_circuits();
1183 control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
1184 "CLOCK_JUMPED");
1185 circuit_mark_all_unused_circs();
1186 circuit_mark_all_dirty_circs_as_unusable();
1187 if (seconds_elapsed < 0) {
1188 /* Restart all the timers in case we jumped a long way into the past. */
1189 reset_all_main_loop_timers();
1193 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
1194 * skin and identity digest for the next hop. If we're already connected,
1195 * pass the onion skin to the next hop using a create cell; otherwise
1196 * launch a new OR connection, and <b>circ</b> will notice when the
1197 * connection succeeds or fails.
1199 * Return -1 if we want to warn and tear down the circuit, else return 0.
1202 circuit_extend(cell_t *cell, circuit_t *circ)
1204 channel_t *n_chan;
1205 relay_header_t rh;
1206 extend_cell_t ec;
1207 const char *msg = NULL;
1208 int should_launch = 0;
1210 if (circ->n_chan) {
1211 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1212 "n_chan already set. Bug/attack. Closing.");
1213 return -1;
1215 if (circ->n_hop) {
1216 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1217 "conn to next hop already launched. Bug/attack. Closing.");
1218 return -1;
1221 if (!server_mode(get_options())) {
1222 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1223 "Got an extend cell, but running as a client. Closing.");
1224 return -1;
1227 relay_header_unpack(&rh, cell->payload);
1229 if (extend_cell_parse(&ec, rh.command,
1230 cell->payload+RELAY_HEADER_SIZE,
1231 rh.length) < 0) {
1232 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1233 "Can't parse extend cell. Closing circuit.");
1234 return -1;
1237 if (!ec.orport_ipv4.port || tor_addr_is_null(&ec.orport_ipv4.addr)) {
1238 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1239 "Client asked me to extend to zero destination port or addr.");
1240 return -1;
1243 if (tor_addr_is_internal(&ec.orport_ipv4.addr, 0) &&
1244 !get_options()->ExtendAllowPrivateAddresses) {
1245 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1246 "Client asked me to extend to a private address");
1247 return -1;
1250 /* Check if they asked us for 0000..0000. We support using
1251 * an empty fingerprint for the first hop (e.g. for a bridge relay),
1252 * but we don't want to let clients send us extend cells for empty
1253 * fingerprints -- a) because it opens the user up to a mitm attack,
1254 * and b) because it lets an attacker force the relay to hold open a
1255 * new TLS connection for each extend request. */
1256 if (tor_digest_is_zero((const char*)ec.node_id)) {
1257 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1258 "Client asked me to extend without specifying an id_digest.");
1259 return -1;
1262 /* Fill in ed_pubkey if it was not provided and we can infer it from
1263 * our networkstatus */
1264 if (ed25519_public_key_is_zero(&ec.ed_pubkey)) {
1265 const node_t *node = node_get_by_id((const char*)ec.node_id);
1266 const ed25519_public_key_t *node_ed_id = NULL;
1267 if (node &&
1268 node_supports_ed25519_link_authentication(node, 1) &&
1269 (node_ed_id = node_get_ed25519_id(node))) {
1270 ed25519_pubkey_copy(&ec.ed_pubkey, node_ed_id);
1274 /* Next, check if we're being asked to connect to the hop that the
1275 * extend cell came from. There isn't any reason for that, and it can
1276 * assist circular-path attacks. */
1277 if (tor_memeq(ec.node_id,
1278 TO_OR_CIRCUIT(circ)->p_chan->identity_digest,
1279 DIGEST_LEN)) {
1280 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1281 "Client asked me to extend back to the previous hop.");
1282 return -1;
1285 /* Check the previous hop Ed25519 ID too */
1286 if (! ed25519_public_key_is_zero(&ec.ed_pubkey) &&
1287 ed25519_pubkey_eq(&ec.ed_pubkey,
1288 &TO_OR_CIRCUIT(circ)->p_chan->ed25519_identity)) {
1289 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1290 "Client asked me to extend back to the previous hop "
1291 "(by Ed25519 ID).");
1292 return -1;
1295 n_chan = channel_get_for_extend((const char*)ec.node_id,
1296 &ec.ed_pubkey,
1297 &ec.orport_ipv4.addr,
1298 &msg,
1299 &should_launch);
1301 if (!n_chan) {
1302 log_debug(LD_CIRC|LD_OR,"Next router (%s): %s",
1303 fmt_addrport(&ec.orport_ipv4.addr,ec.orport_ipv4.port),
1304 msg?msg:"????");
1306 circ->n_hop = extend_info_new(NULL /*nickname*/,
1307 (const char*)ec.node_id,
1308 &ec.ed_pubkey,
1309 NULL, /*onion_key*/
1310 NULL, /*curve25519_key*/
1311 &ec.orport_ipv4.addr,
1312 ec.orport_ipv4.port);
1314 circ->n_chan_create_cell = tor_memdup(&ec.create_cell,
1315 sizeof(ec.create_cell));
1317 circuit_set_state(circ, CIRCUIT_STATE_CHAN_WAIT);
1319 if (should_launch) {
1320 /* we should try to open a connection */
1321 n_chan = channel_connect_for_circuit(&ec.orport_ipv4.addr,
1322 ec.orport_ipv4.port,
1323 (const char*)ec.node_id,
1324 &ec.ed_pubkey);
1325 if (!n_chan) {
1326 log_info(LD_CIRC,"Launching n_chan failed. Closing circuit.");
1327 circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
1328 return 0;
1330 log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
1332 /* return success. The onion/circuit/etc will be taken care of
1333 * automatically (may already have been) whenever n_chan reaches
1334 * OR_CONN_STATE_OPEN.
1336 return 0;
1339 tor_assert(!circ->n_hop); /* Connection is already established. */
1340 circ->n_chan = n_chan;
1341 log_debug(LD_CIRC,
1342 "n_chan is %s",
1343 channel_get_canonical_remote_descr(n_chan));
1345 if (circuit_deliver_create_cell(circ, &ec.create_cell, 1) < 0)
1346 return -1;
1348 return 0;
1351 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in key_data.
1353 * If <b>is_hs_v3</b> is set, this cpath will be used for next gen hidden
1354 * service circuits and <b>key_data</b> must be at least
1355 * HS_NTOR_KEY_EXPANSION_KDF_OUT_LEN bytes in length.
1357 * If <b>is_hs_v3</b> is not set, key_data must contain CPATH_KEY_MATERIAL_LEN
1358 * bytes, which are used as follows:
1359 * - 20 to initialize f_digest
1360 * - 20 to initialize b_digest
1361 * - 16 to key f_crypto
1362 * - 16 to key b_crypto
1364 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
1366 * Return 0 if init was successful, else -1 if it failed.
1369 circuit_init_cpath_crypto(crypt_path_t *cpath,
1370 const char *key_data, size_t key_data_len,
1371 int reverse, int is_hs_v3)
1374 tor_assert(cpath);
1375 return relay_crypto_init(&cpath->crypto, key_data, key_data_len, reverse,
1376 is_hs_v3);
1379 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
1380 * (The body of <b>reply</b> varies depending on what sort of handshake
1381 * this is.)
1383 * Calculate the appropriate keys and digests, make sure KH is
1384 * correct, and initialize this hop of the cpath.
1386 * Return - reason if we want to mark circ for close, else return 0.
1389 circuit_finish_handshake(origin_circuit_t *circ,
1390 const created_cell_t *reply)
1392 char keys[CPATH_KEY_MATERIAL_LEN];
1393 crypt_path_t *hop;
1394 int rv;
1396 if ((rv = pathbias_count_build_attempt(circ)) < 0) {
1397 log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
1398 return rv;
1401 if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
1402 hop = circ->cpath;
1403 } else {
1404 hop = onion_next_hop_in_cpath(circ->cpath);
1405 if (!hop) { /* got an extended when we're all done? */
1406 log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
1407 return - END_CIRC_REASON_TORPROTOCOL;
1410 tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
1413 const char *msg = NULL;
1414 if (onion_skin_client_handshake(hop->handshake_state.tag,
1415 &hop->handshake_state,
1416 reply->reply, reply->handshake_len,
1417 (uint8_t*)keys, sizeof(keys),
1418 (uint8_t*)hop->rend_circ_nonce,
1419 &msg) < 0) {
1420 if (msg)
1421 log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
1422 return -END_CIRC_REASON_TORPROTOCOL;
1426 onion_handshake_state_release(&hop->handshake_state);
1428 if (circuit_init_cpath_crypto(hop, keys, sizeof(keys), 0, 0)<0) {
1429 return -END_CIRC_REASON_TORPROTOCOL;
1432 hop->state = CPATH_STATE_OPEN;
1433 log_info(LD_CIRC,"Finished building circuit hop:");
1434 circuit_log_path(LOG_INFO,LD_CIRC,circ);
1435 control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
1437 return 0;
1440 /** We received a relay truncated cell on circ.
1442 * Since we don't send truncates currently, getting a truncated
1443 * means that a connection broke or an extend failed. For now,
1444 * just give up: force circ to close, and return 0.
1447 circuit_truncated(origin_circuit_t *circ, int reason)
1449 // crypt_path_t *victim;
1450 // connection_t *stream;
1452 tor_assert(circ);
1454 /* XXX Since we don't send truncates currently, getting a truncated
1455 * means that a connection broke or an extend failed. For now,
1456 * just give up.
1458 circuit_mark_for_close(TO_CIRCUIT(circ),
1459 END_CIRC_REASON_FLAG_REMOTE|reason);
1460 return 0;
1462 #if 0
1463 while (layer->next != circ->cpath) {
1464 /* we need to clear out layer->next */
1465 victim = layer->next;
1466 log_debug(LD_CIRC, "Killing a layer of the cpath.");
1468 for (stream = circ->p_streams; stream; stream=stream->next_stream) {
1469 if (stream->cpath_layer == victim) {
1470 log_info(LD_APP, "Marking stream %d for close because of truncate.",
1471 stream->stream_id);
1472 /* no need to send 'end' relay cells,
1473 * because the other side's already dead
1475 connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
1479 layer->next = victim->next;
1480 circuit_free_cpath_node(victim);
1483 log_info(LD_CIRC, "finished");
1484 return 0;
1485 #endif /* 0 */
1488 /** Given a response payload and keys, initialize, then send a created
1489 * cell back.
1492 onionskin_answer(or_circuit_t *circ,
1493 const created_cell_t *created_cell,
1494 const char *keys, size_t keys_len,
1495 const uint8_t *rend_circ_nonce)
1497 cell_t cell;
1499 tor_assert(keys_len == CPATH_KEY_MATERIAL_LEN);
1501 if (created_cell_format(&cell, created_cell) < 0) {
1502 log_warn(LD_BUG,"couldn't format created cell (type=%d, len=%d)",
1503 (int)created_cell->cell_type, (int)created_cell->handshake_len);
1504 return -1;
1506 cell.circ_id = circ->p_circ_id;
1508 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
1510 log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
1511 (unsigned int)get_uint32(keys),
1512 (unsigned int)get_uint32(keys+20));
1513 if (relay_crypto_init(&circ->crypto, keys, keys_len, 0, 0)<0) {
1514 log_warn(LD_BUG,"Circuit initialization failed");
1515 return -1;
1518 memcpy(circ->rend_circ_nonce, rend_circ_nonce, DIGEST_LEN);
1520 int used_create_fast = (created_cell->cell_type == CELL_CREATED_FAST);
1522 append_cell_to_circuit_queue(TO_CIRCUIT(circ),
1523 circ->p_chan, &cell, CELL_DIRECTION_IN, 0);
1524 log_debug(LD_CIRC,"Finished sending '%s' cell.",
1525 used_create_fast ? "created_fast" : "created");
1527 /* Ignore the local bit when ExtendAllowPrivateAddresses is set:
1528 * it violates the assumption that private addresses are local.
1529 * Also, many test networks run on local addresses, and
1530 * TestingTorNetwork sets ExtendAllowPrivateAddresses. */
1531 if ((!channel_is_local(circ->p_chan)
1532 || get_options()->ExtendAllowPrivateAddresses)
1533 && !channel_is_outgoing(circ->p_chan)) {
1534 /* record that we could process create cells from a non-local conn
1535 * that we didn't initiate; presumably this means that create cells
1536 * can reach us too. */
1537 router_orport_found_reachable();
1540 return 0;
1543 /** Helper for new_route_len(). Choose a circuit length for purpose
1544 * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
1545 * exit). If someone else chose the exit, they could be colluding
1546 * with the exit, so add a randomly selected node to preserve
1547 * anonymity.
1549 * Here, "exit node" sometimes means an OR acting as an internal
1550 * endpoint, rather than as a relay to an external endpoint. This
1551 * means there need to be at least DEFAULT_ROUTE_LEN routers between
1552 * us and the internal endpoint to preserve the same anonymity
1553 * properties that we would get when connecting to an external
1554 * endpoint. These internal endpoints can include:
1556 * - Connections to a directory of hidden services
1557 * (CIRCUIT_PURPOSE_C_GENERAL)
1559 * - A client connecting to an introduction point, which the hidden
1560 * service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
1561 * circuit_get_open_circ_or_launch() which rewrites it from
1562 * CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
1564 * - A hidden service connecting to a rendezvous point, which the
1565 * client picked (CIRCUIT_PURPOSE_S_CONNECT_REND, via
1566 * rend_service_receive_introduction() and
1567 * rend_service_relaunch_rendezvous)
1569 * There are currently two situations where we picked the exit node
1570 * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
1572 * - We are a hidden service connecting to an introduction point
1573 * (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO, via
1574 * rend_service_launch_establish_intro())
1576 * - We are a router testing its own reachabiity
1577 * (CIRCUIT_PURPOSE_TESTING, via router_do_reachability_checks())
1579 * onion_pick_cpath_exit() bypasses us (by not calling
1580 * new_route_len()) in the one-hop tunnel case, so we don't need to
1581 * handle that.
1584 route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
1586 int routelen = DEFAULT_ROUTE_LEN;
1587 int known_purpose = 0;
1589 if (circuit_should_use_vanguards(purpose)) {
1590 /* Clients want an extra hop for rends to avoid linkability.
1591 * Services want it for intro points to avoid publishing their
1592 * layer3 guards. They want it for hsdir posts to use
1593 * their full layer3 guard set for those connections.
1594 * Ex: C - G - L2 - L3 - R
1595 * S - G - L2 - L3 - HSDIR
1596 * S - G - L2 - L3 - I
1598 if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
1599 purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
1600 purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
1601 purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
1602 return routelen+1;
1604 /* If we only have Layer2 vanguards, then we do not need
1605 * the extra hop for linkabilty reasons (see below).
1606 * This means all hops can be of the form:
1607 * S/C - G - L2 - M - R/HSDir/I
1609 if (get_options()->HSLayer2Nodes && !get_options()->HSLayer3Nodes)
1610 return routelen+1;
1612 /* For connections to hsdirs, clients want two extra hops
1613 * when using layer3 guards, to avoid linkability.
1614 * Same goes for intro points. Note that the route len
1615 * includes the intro point or hsdir, hence the +2.
1616 * Ex: C - G - L2 - L3 - M - I
1617 * C - G - L2 - L3 - M - HSDIR
1618 * S - G - L2 - L3 - M - R
1620 if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
1621 purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
1622 purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
1623 return routelen+2;
1626 if (!exit_ei)
1627 return routelen;
1629 switch (purpose) {
1630 /* These two purposes connect to a router that we chose, so
1631 * DEFAULT_ROUTE_LEN is safe. */
1632 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
1633 /* hidden service connecting to introduction point */
1634 case CIRCUIT_PURPOSE_TESTING:
1635 /* router reachability testing */
1636 known_purpose = 1;
1637 break;
1639 /* These three purposes connect to a router that someone else
1640 * might have chosen, so add an extra hop to protect anonymity. */
1641 case CIRCUIT_PURPOSE_C_GENERAL:
1642 case CIRCUIT_PURPOSE_C_HSDIR_GET:
1643 case CIRCUIT_PURPOSE_S_HSDIR_POST:
1644 /* connecting to hidden service directory */
1645 case CIRCUIT_PURPOSE_C_INTRODUCING:
1646 /* client connecting to introduction point */
1647 case CIRCUIT_PURPOSE_S_CONNECT_REND:
1648 /* hidden service connecting to rendezvous point */
1649 known_purpose = 1;
1650 routelen++;
1651 break;
1653 default:
1654 /* Got a purpose not listed above along with a chosen exit.
1655 * Increase the circuit length by one anyway for safety. */
1656 routelen++;
1657 break;
1660 if (BUG(exit_ei && !known_purpose)) {
1661 log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
1662 "assuming routelen %d.", purpose, routelen);
1664 return routelen;
1667 /** Choose a length for a circuit of purpose <b>purpose</b> and check
1668 * if enough routers are available.
1670 * If the routerlist <b>nodes</b> doesn't have enough routers
1671 * to handle the desired path length, return -1.
1673 STATIC int
1674 new_route_len(uint8_t purpose, extend_info_t *exit_ei, smartlist_t *nodes)
1676 int num_acceptable_routers;
1677 int routelen;
1679 tor_assert(nodes);
1681 routelen = route_len_for_purpose(purpose, exit_ei);
1683 num_acceptable_routers = count_acceptable_nodes(nodes);
1685 log_debug(LD_CIRC,"Chosen route length %d (%d/%d routers suitable).",
1686 routelen, num_acceptable_routers, smartlist_len(nodes));
1688 if (num_acceptable_routers < routelen) {
1689 log_info(LD_CIRC,
1690 "Not enough acceptable routers (%d/%d). Discarding this circuit.",
1691 num_acceptable_routers, routelen);
1692 return -1;
1695 return routelen;
1698 /** Return a newly allocated list of uint16_t * for each predicted port not
1699 * handled by a current circuit. */
1700 static smartlist_t *
1701 circuit_get_unhandled_ports(time_t now)
1703 smartlist_t *dest = rep_hist_get_predicted_ports(now);
1704 circuit_remove_handled_ports(dest);
1705 return dest;
1708 /** Return 1 if we already have circuits present or on the way for
1709 * all anticipated ports. Return 0 if we should make more.
1711 * If we're returning 0, set need_uptime and need_capacity to
1712 * indicate any requirements that the unhandled ports have.
1714 MOCK_IMPL(int,
1715 circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
1716 int *need_capacity))
1718 int i, enough;
1719 uint16_t *port;
1720 smartlist_t *sl = circuit_get_unhandled_ports(now);
1721 smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
1722 tor_assert(need_uptime);
1723 tor_assert(need_capacity);
1724 // Always predict need_capacity
1725 *need_capacity = 1;
1726 enough = (smartlist_len(sl) == 0);
1727 for (i = 0; i < smartlist_len(sl); ++i) {
1728 port = smartlist_get(sl, i);
1729 if (smartlist_contains_int_as_string(LongLivedServices, *port))
1730 *need_uptime = 1;
1731 tor_free(port);
1733 smartlist_free(sl);
1734 return enough;
1737 /** Return 1 if <b>node</b> can handle one or more of the ports in
1738 * <b>needed_ports</b>, else return 0.
1740 static int
1741 node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
1742 { /* XXXX MOVE */
1743 int i;
1744 uint16_t port;
1746 for (i = 0; i < smartlist_len(needed_ports); ++i) {
1747 addr_policy_result_t r;
1748 /* alignment issues aren't a worry for this dereference, since
1749 needed_ports is explicitly a smartlist of uint16_t's */
1750 port = *(uint16_t *)smartlist_get(needed_ports, i);
1751 tor_assert(port);
1752 if (node)
1753 r = compare_tor_addr_to_node_policy(NULL, port, node);
1754 else
1755 continue;
1756 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1757 return 1;
1759 return 0;
1762 /** Return true iff <b>conn</b> needs another general circuit to be
1763 * built. */
1764 static int
1765 ap_stream_wants_exit_attention(connection_t *conn)
1767 entry_connection_t *entry;
1768 if (conn->type != CONN_TYPE_AP)
1769 return 0;
1770 entry = TO_ENTRY_CONN(conn);
1772 if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
1773 !conn->marked_for_close &&
1774 !(entry->want_onehop) && /* ignore one-hop streams */
1775 !(entry->use_begindir) && /* ignore targeted dir fetches */
1776 !(entry->chosen_exit_name) && /* ignore defined streams */
1777 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
1778 !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
1779 MIN_CIRCUITS_HANDLING_STREAM))
1780 return 1;
1781 return 0;
1784 /** Return a pointer to a suitable router to be the exit node for the
1785 * general-purpose circuit we're about to build.
1787 * Look through the connection array, and choose a router that maximizes
1788 * the number of pending streams that can exit from this router.
1790 * Return NULL if we can't find any suitable routers.
1792 static const node_t *
1793 choose_good_exit_server_general(router_crn_flags_t flags)
1795 int *n_supported;
1796 int n_pending_connections = 0;
1797 smartlist_t *connections;
1798 int best_support = -1;
1799 int n_best_support=0;
1800 const or_options_t *options = get_options();
1801 const smartlist_t *the_nodes;
1802 const node_t *selected_node=NULL;
1803 const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
1804 const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
1805 const int direct_conn = (flags & CRN_DIRECT_CONN) != 0;
1807 connections = get_connection_array();
1809 /* Count how many connections are waiting for a circuit to be built.
1810 * We use this for log messages now, but in the future we may depend on it.
1812 SMARTLIST_FOREACH(connections, connection_t *, conn,
1814 if (ap_stream_wants_exit_attention(conn))
1815 ++n_pending_connections;
1817 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
1818 // n_pending_connections);
1819 /* Now we count, for each of the routers in the directory, how many
1820 * of the pending connections could possibly exit from that
1821 * router (n_supported[i]). (We can't be sure about cases where we
1822 * don't know the IP address of the pending connection.)
1824 * -1 means "Don't use this router at all."
1826 the_nodes = nodelist_get_list();
1827 n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
1828 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1829 const int i = node_sl_idx;
1830 if (router_digest_is_me(node->identity)) {
1831 n_supported[i] = -1;
1832 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
1833 /* XXX there's probably a reverse predecessor attack here, but
1834 * it's slow. should we take this out? -RD
1836 continue;
1838 if (!node_has_preferred_descriptor(node, direct_conn)) {
1839 n_supported[i] = -1;
1840 continue;
1842 if (!node->is_running || node->is_bad_exit) {
1843 n_supported[i] = -1;
1844 continue; /* skip routers that are known to be down or bad exits */
1846 if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
1847 /* never pick a non-general node as a random exit. */
1848 n_supported[i] = -1;
1849 continue;
1851 if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
1852 n_supported[i] = -1;
1853 continue; /* user asked us not to use it, no matter what */
1855 if (options->ExitNodes &&
1856 !routerset_contains_node(options->ExitNodes, node)) {
1857 n_supported[i] = -1;
1858 continue; /* not one of our chosen exit nodes */
1861 if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
1862 n_supported[i] = -1;
1863 continue; /* skip routers that are not suitable. Don't worry if
1864 * this makes us reject all the possible routers: if so,
1865 * we'll retry later in this function with need_update and
1866 * need_capacity set to 0. */
1868 if (!(node->is_valid)) {
1869 /* if it's invalid and we don't want it */
1870 n_supported[i] = -1;
1871 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
1872 // router->nickname, i);
1873 continue; /* skip invalid routers */
1875 /* We do not allow relays that allow single hop exits by default. Option
1876 * was deprecated in 0.2.9.2-alpha and removed in 0.3.1.0-alpha. */
1877 if (node_allows_single_hop_exits(node)) {
1878 n_supported[i] = -1;
1879 continue;
1881 if (node_exit_policy_rejects_all(node)) {
1882 n_supported[i] = -1;
1883 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
1884 // router->nickname, i);
1885 continue; /* skip routers that reject all */
1887 n_supported[i] = 0;
1888 /* iterate over connections */
1889 SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
1890 if (!ap_stream_wants_exit_attention(conn))
1891 continue; /* Skip everything but APs in CIRCUIT_WAIT */
1892 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
1893 ++n_supported[i];
1894 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
1895 // router->nickname, i, n_supported[i]);
1896 } else {
1897 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
1898 // router->nickname, i);
1900 } SMARTLIST_FOREACH_END(conn);
1901 if (n_pending_connections > 0 && n_supported[i] == 0) {
1902 /* Leave best_support at -1 if that's where it is, so we can
1903 * distinguish it later. */
1904 continue;
1906 if (n_supported[i] > best_support) {
1907 /* If this router is better than previous ones, remember its index
1908 * and goodness, and start counting how many routers are this good. */
1909 best_support = n_supported[i]; n_best_support=1;
1910 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
1911 // router->nickname);
1912 } else if (n_supported[i] == best_support) {
1913 /* If this router is _as good_ as the best one, just increment the
1914 * count of equally good routers.*/
1915 ++n_best_support;
1917 } SMARTLIST_FOREACH_END(node);
1918 log_info(LD_CIRC,
1919 "Found %d servers that might support %d/%d pending connections.",
1920 n_best_support, best_support >= 0 ? best_support : 0,
1921 n_pending_connections);
1923 /* If any routers definitely support any pending connections, choose one
1924 * at random. */
1925 if (best_support > 0) {
1926 smartlist_t *supporting = smartlist_new();
1928 SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
1929 if (n_supported[node_sl_idx] == best_support)
1930 smartlist_add(supporting, (void*)node);
1933 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1934 smartlist_free(supporting);
1935 } else {
1936 /* Either there are no pending connections, or no routers even seem to
1937 * possibly support any of them. Choose a router at random that satisfies
1938 * at least one predicted exit port. */
1940 int attempt;
1941 smartlist_t *needed_ports, *supporting;
1943 if (best_support == -1) {
1944 if (need_uptime || need_capacity) {
1945 log_info(LD_CIRC,
1946 "We couldn't find any live%s%s routers; falling back "
1947 "to list of all routers.",
1948 need_capacity?", fast":"",
1949 need_uptime?", stable":"");
1950 tor_free(n_supported);
1951 flags &= ~(CRN_NEED_UPTIME|CRN_NEED_CAPACITY);
1952 return choose_good_exit_server_general(flags);
1954 log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
1955 "choosing a doomed exit at random.",
1956 options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
1958 supporting = smartlist_new();
1959 needed_ports = circuit_get_unhandled_ports(time(NULL));
1960 for (attempt = 0; attempt < 2; attempt++) {
1961 /* try once to pick only from routers that satisfy a needed port,
1962 * then if there are none, pick from any that support exiting. */
1963 SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
1964 if (n_supported[node_sl_idx] != -1 &&
1965 (attempt || node_handles_some_port(node, needed_ports))) {
1966 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
1967 // try, router->nickname);
1968 smartlist_add(supporting, (void*)node);
1970 } SMARTLIST_FOREACH_END(node);
1972 selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
1973 if (selected_node)
1974 break;
1975 smartlist_clear(supporting);
1976 /* If we reach this point, we can't actually support any unhandled
1977 * predicted ports, so clear all the remaining ones. */
1978 if (smartlist_len(needed_ports))
1979 rep_hist_remove_predicted_ports(needed_ports);
1981 SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
1982 smartlist_free(needed_ports);
1983 smartlist_free(supporting);
1986 tor_free(n_supported);
1987 if (selected_node) {
1988 log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
1989 return selected_node;
1991 if (options->ExitNodes) {
1992 log_warn(LD_CIRC,
1993 "No exits in ExitNodes%s seem to be running: "
1994 "can't choose an exit.",
1995 options->ExcludeExitNodesUnion_ ?
1996 ", except possibly those excluded by your configuration, " : "");
1998 return NULL;
2001 /* Pick a Rendezvous Point for our HS circuits according to <b>flags</b>. */
2002 static const node_t *
2003 pick_rendezvous_node(router_crn_flags_t flags)
2005 const or_options_t *options = get_options();
2006 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
2010 * Helper function to pick a configured restricted middle node
2011 * (either HSLayer2Nodes or HSLayer3Nodes).
2013 * Make sure that the node we chose is alive, and not excluded,
2014 * and return it.
2016 * The exclude_set is a routerset of nodes that the selected node
2017 * must not match, and the exclude_list is a simple list of nodes
2018 * that the selected node must not be in. Either or both may be
2019 * NULL.
2021 * Return NULL if no usable nodes could be found. */
2022 static const node_t *
2023 pick_restricted_middle_node(router_crn_flags_t flags,
2024 const routerset_t *pick_from,
2025 const routerset_t *exclude_set,
2026 const smartlist_t *exclude_list,
2027 int position_hint)
2029 const node_t *middle_node = NULL;
2031 smartlist_t *whitelisted_live_middles = smartlist_new();
2032 smartlist_t *all_live_nodes = smartlist_new();
2034 tor_assert(pick_from);
2036 /* Add all running nodes to all_live_nodes */
2037 router_add_running_nodes_to_smartlist(all_live_nodes,
2038 (flags & CRN_NEED_UPTIME) != 0,
2039 (flags & CRN_NEED_CAPACITY) != 0,
2040 (flags & CRN_NEED_GUARD) != 0,
2041 (flags & CRN_NEED_DESC) != 0,
2042 (flags & CRN_PREF_ADDR) != 0,
2043 (flags & CRN_DIRECT_CONN) != 0);
2045 /* Filter all_live_nodes to only add live *and* whitelisted middles
2046 * to the list whitelisted_live_middles. */
2047 SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
2048 if (routerset_contains_node(pick_from, live_node)) {
2049 smartlist_add(whitelisted_live_middles, live_node);
2051 } SMARTLIST_FOREACH_END(live_node);
2053 /* Honor ExcludeNodes */
2054 if (exclude_set) {
2055 routerset_subtract_nodes(whitelisted_live_middles, exclude_set);
2058 if (exclude_list) {
2059 smartlist_subtract(whitelisted_live_middles, exclude_list);
2063 * Max number of restricted nodes before we alert the user and try
2064 * to load balance for them.
2066 * The most aggressive vanguard design had 16 nodes at layer3.
2067 * Let's give a small ceiling above that. */
2068 #define MAX_SANE_RESTRICTED_NODES 20
2069 /* If the user (or associated tor controller) selected only a few nodes,
2070 * assume they took load balancing into account and don't do it for them.
2072 * If there are a lot of nodes in here, assume they did not load balance
2073 * and do it for them, but also warn them that they may be Doing It Wrong.
2075 if (smartlist_len(whitelisted_live_middles) <=
2076 MAX_SANE_RESTRICTED_NODES) {
2077 middle_node = smartlist_choose(whitelisted_live_middles);
2078 } else {
2079 static ratelim_t pinned_notice_limit = RATELIM_INIT(24*3600);
2080 log_fn_ratelim(&pinned_notice_limit, LOG_NOTICE, LD_CIRC,
2081 "Your _HSLayer%dNodes setting has resulted "
2082 "in %d total nodes. This is a lot of nodes. "
2083 "You may want to consider using a Tor controller "
2084 "to select and update a smaller set of nodes instead.",
2085 position_hint, smartlist_len(whitelisted_live_middles));
2087 /* NO_WEIGHTING here just means don't take node flags into account
2088 * (ie: use consensus measurement only). This is done so that
2089 * we don't further surprise the user by not using Exits that they
2090 * specified at all */
2091 middle_node = node_sl_choose_by_bandwidth(whitelisted_live_middles,
2092 NO_WEIGHTING);
2095 smartlist_free(whitelisted_live_middles);
2096 smartlist_free(all_live_nodes);
2098 return middle_node;
2101 /** Return a pointer to a suitable router to be the exit node for the
2102 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
2103 * if no router is suitable).
2105 * For general-purpose circuits, pass it off to
2106 * choose_good_exit_server_general()
2108 * For client-side rendezvous circuits, choose a random node, weighted
2109 * toward the preferences in 'options'.
2111 static const node_t *
2112 choose_good_exit_server(origin_circuit_t *circ,
2113 router_crn_flags_t flags, int is_internal)
2115 const or_options_t *options = get_options();
2116 flags |= CRN_NEED_DESC;
2118 switch (TO_CIRCUIT(circ)->purpose) {
2119 case CIRCUIT_PURPOSE_C_HSDIR_GET:
2120 case CIRCUIT_PURPOSE_S_HSDIR_POST:
2121 case CIRCUIT_PURPOSE_HS_VANGUARDS:
2122 /* For these three, we want to pick the exit like a middle hop,
2123 * since it should be random. */
2124 tor_assert_nonfatal(is_internal);
2125 FALLTHROUGH;
2126 case CIRCUIT_PURPOSE_C_GENERAL:
2127 if (is_internal) /* pick it like a middle hop */
2128 return router_choose_random_node(NULL, options->ExcludeNodes, flags);
2129 else
2130 return choose_good_exit_server_general(flags);
2131 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
2133 /* Pick a new RP */
2134 const node_t *rendezvous_node = pick_rendezvous_node(flags);
2135 log_info(LD_REND, "Picked new RP: %s",
2136 safe_str_client(node_describe(rendezvous_node)));
2137 return rendezvous_node;
2140 log_warn(LD_BUG,"Unhandled purpose %d", TO_CIRCUIT(circ)->purpose);
2141 tor_fragile_assert();
2142 return NULL;
2145 /** Log a warning if the user specified an exit for the circuit that
2146 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
2147 static void
2148 warn_if_last_router_excluded(origin_circuit_t *circ,
2149 const extend_info_t *exit_ei)
2151 const or_options_t *options = get_options();
2152 routerset_t *rs = options->ExcludeNodes;
2153 const char *description;
2154 uint8_t purpose = circ->base_.purpose;
2156 if (circ->build_state->onehop_tunnel)
2157 return;
2159 switch (purpose)
2161 default:
2162 case CIRCUIT_PURPOSE_OR:
2163 case CIRCUIT_PURPOSE_INTRO_POINT:
2164 case CIRCUIT_PURPOSE_REND_POINT_WAITING:
2165 case CIRCUIT_PURPOSE_REND_ESTABLISHED:
2166 log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
2167 (int)purpose,
2168 circuit_purpose_to_string(purpose));
2169 return;
2170 case CIRCUIT_PURPOSE_S_HSDIR_POST:
2171 case CIRCUIT_PURPOSE_C_HSDIR_GET:
2172 case CIRCUIT_PURPOSE_C_GENERAL:
2173 if (circ->build_state->is_internal)
2174 return;
2175 description = "requested exit node";
2176 rs = options->ExcludeExitNodesUnion_;
2177 break;
2178 case CIRCUIT_PURPOSE_C_INTRODUCING:
2179 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
2180 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
2181 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
2182 case CIRCUIT_PURPOSE_S_CONNECT_REND:
2183 case CIRCUIT_PURPOSE_S_REND_JOINED:
2184 case CIRCUIT_PURPOSE_TESTING:
2185 return;
2186 case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
2187 case CIRCUIT_PURPOSE_C_REND_READY:
2188 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
2189 case CIRCUIT_PURPOSE_C_REND_JOINED:
2190 description = "chosen rendezvous point";
2191 break;
2192 case CIRCUIT_PURPOSE_CONTROLLER:
2193 rs = options->ExcludeExitNodesUnion_;
2194 description = "controller-selected circuit target";
2195 break;
2198 if (routerset_contains_extendinfo(rs, exit_ei)) {
2199 /* We should never get here if StrictNodes is set to 1. */
2200 if (options->StrictNodes) {
2201 log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
2202 "even though StrictNodes is set. Please report. "
2203 "(Circuit purpose: %s)",
2204 description, extend_info_describe(exit_ei),
2205 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2206 circuit_purpose_to_string(purpose));
2207 } else {
2208 log_warn(LD_CIRC, "Using %s '%s' which is listed in "
2209 "ExcludeNodes%s, because no better options were available. To "
2210 "prevent this (and possibly break your Tor functionality), "
2211 "set the StrictNodes configuration option. "
2212 "(Circuit purpose: %s)",
2213 description, extend_info_describe(exit_ei),
2214 rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
2215 circuit_purpose_to_string(purpose));
2217 circuit_log_path(LOG_WARN, LD_CIRC, circ);
2220 return;
2223 /** Decide a suitable length for circ's cpath, and pick an exit
2224 * router (or use <b>exit</b> if provided). Store these in the
2225 * cpath.
2227 * If <b>is_hs_v3_rp_circuit</b> is set, then this exit should be suitable to
2228 * be used as an HS v3 rendezvous point.
2230 * Return 0 if ok, -1 if circuit should be closed. */
2231 STATIC int
2232 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei,
2233 int is_hs_v3_rp_circuit)
2235 cpath_build_state_t *state = circ->build_state;
2237 if (state->onehop_tunnel) {
2238 log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
2239 (rend_allow_non_anonymous_connection(get_options()) ?
2240 ", or intro or rendezvous connection" : ""));
2241 state->desired_path_len = 1;
2242 } else {
2243 int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
2244 if (r < 1) /* must be at least 1 */
2245 return -1;
2246 state->desired_path_len = r;
2249 if (exit_ei) { /* the circuit-builder pre-requested one */
2250 warn_if_last_router_excluded(circ, exit_ei);
2251 log_info(LD_CIRC,"Using requested exit node '%s'",
2252 extend_info_describe(exit_ei));
2253 exit_ei = extend_info_dup(exit_ei);
2254 } else { /* we have to decide one */
2255 router_crn_flags_t flags = CRN_NEED_DESC;
2256 if (state->need_uptime)
2257 flags |= CRN_NEED_UPTIME;
2258 if (state->need_capacity)
2259 flags |= CRN_NEED_CAPACITY;
2260 if (is_hs_v3_rp_circuit)
2261 flags |= CRN_RENDEZVOUS_V3;
2262 if (state->onehop_tunnel)
2263 flags |= CRN_DIRECT_CONN;
2264 const node_t *node =
2265 choose_good_exit_server(circ, flags, state->is_internal);
2266 if (!node) {
2267 log_warn(LD_CIRC,"Failed to choose an exit server");
2268 return -1;
2270 exit_ei = extend_info_from_node(node, state->onehop_tunnel);
2271 if (BUG(exit_ei == NULL))
2272 return -1;
2274 state->chosen_exit = exit_ei;
2275 return 0;
2278 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
2279 * hop to the cpath reflecting this. Don't send the next extend cell --
2280 * the caller will do this if it wants to.
2283 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2285 cpath_build_state_t *state;
2286 tor_assert(exit_ei);
2287 tor_assert(circ);
2289 state = circ->build_state;
2290 tor_assert(state);
2291 extend_info_free(state->chosen_exit);
2292 state->chosen_exit = extend_info_dup(exit_ei);
2294 ++circ->build_state->desired_path_len;
2295 onion_append_hop(&circ->cpath, exit_ei);
2296 return 0;
2299 /** Take an open <b>circ</b>, and add a new hop at the end, based on
2300 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
2301 * send the next extend cell to begin connecting to that hop.
2304 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
2306 int err_reason = 0;
2307 warn_if_last_router_excluded(circ, exit_ei);
2309 tor_gettimeofday(&circ->base_.timestamp_began);
2311 circuit_append_new_exit(circ, exit_ei);
2312 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
2313 if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
2314 log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
2315 extend_info_describe(exit_ei));
2316 circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
2317 return -1;
2320 // XXX: Should cannibalized circuits be dirty or not? Not easy to say..
2322 return 0;
2325 /** Return the number of routers in <b>routers</b> that are currently up
2326 * and available for building circuits through.
2328 * (Note that this function may overcount or undercount, if we have
2329 * descriptors that are not the type we would prefer to use for some
2330 * particular router. See bug #25885.)
2332 MOCK_IMPL(STATIC int,
2333 count_acceptable_nodes, (smartlist_t *nodes))
2335 int num=0;
2337 SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
2338 // log_debug(LD_CIRC,
2339 // "Contemplating whether router %d (%s) is a new option.",
2340 // i, r->nickname);
2341 if (! node->is_running)
2342 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
2343 continue;
2344 if (! node->is_valid)
2345 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
2346 continue;
2347 if (! node_has_any_descriptor(node))
2348 continue;
2349 /* The node has a descriptor, so we can just check the ntor key directly */
2350 if (!node_has_curve25519_onion_key(node))
2351 continue;
2352 ++num;
2353 } SMARTLIST_FOREACH_END(node);
2355 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2357 return num;
2360 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
2361 * This function is used to extend cpath by another hop.
2363 void
2364 onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
2366 if (*head_ptr) {
2367 new_hop->next = (*head_ptr);
2368 new_hop->prev = (*head_ptr)->prev;
2369 (*head_ptr)->prev->next = new_hop;
2370 (*head_ptr)->prev = new_hop;
2371 } else {
2372 *head_ptr = new_hop;
2373 new_hop->prev = new_hop->next = new_hop;
2377 #ifdef TOR_UNIT_TESTS
2379 /** Unittest helper function: Count number of hops in cpath linked list. */
2380 unsigned int
2381 cpath_get_n_hops(crypt_path_t **head_ptr)
2383 unsigned int n_hops = 0;
2384 crypt_path_t *tmp;
2386 if (!*head_ptr) {
2387 return 0;
2390 tmp = *head_ptr;
2391 do {
2392 n_hops++;
2393 tmp = tmp->next;
2394 } while (tmp != *head_ptr);
2396 return n_hops;
2399 #endif /* defined(TOR_UNIT_TESTS) */
2402 * Build the exclude list for vanguard circuits.
2404 * For vanguard circuits we exclude all the already chosen nodes (including the
2405 * exit) from being middle hops to prevent the creation of A - B - A subpaths.
2406 * We also allow the 4th hop to be the same as the guard node so as to not leak
2407 * guard information to RP/IP/HSDirs.
2409 * For vanguard circuits, we don't apply any subnet or family restrictions.
2410 * This is to avoid impossible-to-build circuit paths, or just situations where
2411 * our earlier guards prevent us from using most of our later ones.
2413 * The alternative is building the circuit in reverse. Reverse calls to
2414 * onion_extend_cpath() (ie: select outer hops first) would then have the
2415 * property that you don't gain information about inner hops by observing
2416 * outer ones. See https://trac.torproject.org/projects/tor/ticket/24487
2417 * for this.
2419 * (Note further that we still exclude the exit to prevent A - B - A
2420 * at the end of the path. */
2421 static smartlist_t *
2422 build_vanguard_middle_exclude_list(uint8_t purpose,
2423 cpath_build_state_t *state,
2424 crypt_path_t *head,
2425 int cur_len)
2427 smartlist_t *excluded;
2428 const node_t *r;
2429 crypt_path_t *cpath;
2430 int i;
2432 (void) purpose;
2434 excluded = smartlist_new();
2436 /* Add the exit to the exclude list (note that the exit/last hop is always
2437 * chosen first in circuit_establish_circuit()). */
2438 if ((r = build_state_get_exit_node(state))) {
2439 smartlist_add(excluded, (node_t*)r);
2442 /* If we are picking the 4th hop, allow that node to be the guard too.
2443 * This prevents us from avoiding the Guard for those hops, which
2444 * gives the adversary information about our guard if they control
2445 * the RP, IP, or HSDIR. We don't do this check based on purpose
2446 * because we also want to allow HS_VANGUARDS pre-build circuits
2447 * to use the guard for that last hop.
2449 if (cur_len == DEFAULT_ROUTE_LEN+1) {
2450 /* Skip the first hop for the exclude list below */
2451 head = head->next;
2452 cur_len--;
2455 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2456 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2457 smartlist_add(excluded, (node_t*)r);
2461 return excluded;
2465 * Build a list of nodes to exclude from the choice of this middle
2466 * hop, based on already chosen nodes.
2468 static smartlist_t *
2469 build_middle_exclude_list(uint8_t purpose,
2470 cpath_build_state_t *state,
2471 crypt_path_t *head,
2472 int cur_len)
2474 smartlist_t *excluded;
2475 const node_t *r;
2476 crypt_path_t *cpath;
2477 int i;
2479 /** Vanguard circuits have their own path selection rules */
2480 if (circuit_should_use_vanguards(purpose)) {
2481 return build_vanguard_middle_exclude_list(purpose, state, head, cur_len);
2484 excluded = smartlist_new();
2486 /* For non-vanguard circuits, add the exit and its family to the exclude list
2487 * (note that the exit/last hop is always chosen first in
2488 * circuit_establish_circuit()). */
2489 if ((r = build_state_get_exit_node(state))) {
2490 nodelist_add_node_and_family(excluded, r);
2493 /* also exclude all other already chosen nodes and their family */
2494 for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
2495 if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
2496 nodelist_add_node_and_family(excluded, r);
2500 return excluded;
2503 /** Return true if we MUST use vanguards for picking this middle node. */
2504 static int
2505 middle_node_must_be_vanguard(const or_options_t *options,
2506 uint8_t purpose, int cur_len)
2508 /* If this is not a hidden service circuit, don't use vanguards */
2509 if (!circuit_purpose_is_hidden_service(purpose)) {
2510 return 0;
2513 /* If we have sticky L2 nodes, and this is an L2 pick, use vanguards */
2514 if (options->HSLayer2Nodes && cur_len == 1) {
2515 return 1;
2518 /* If we have sticky L3 nodes, and this is an L3 pick, use vanguards */
2519 if (options->HSLayer3Nodes && cur_len == 2) {
2520 return 1;
2523 return 0;
2526 /** Pick a sticky vanguard middle node or return NULL if not found.
2527 * See doc of pick_restricted_middle_node() for argument details. */
2528 static const node_t *
2529 pick_vanguard_middle_node(const or_options_t *options,
2530 router_crn_flags_t flags, int cur_len,
2531 const smartlist_t *excluded)
2533 const routerset_t *vanguard_routerset = NULL;
2534 const node_t *node = NULL;
2536 /* Pick the right routerset based on the current hop */
2537 if (cur_len == 1) {
2538 vanguard_routerset = options->HSLayer2Nodes;
2539 } else if (cur_len == 2) {
2540 vanguard_routerset = options->HSLayer3Nodes;
2541 } else {
2542 /* guaranteed by middle_node_should_be_vanguard() */
2543 tor_assert_nonfatal_unreached();
2544 return NULL;
2547 node = pick_restricted_middle_node(flags, vanguard_routerset,
2548 options->ExcludeNodes, excluded,
2549 cur_len+1);
2551 if (!node) {
2552 static ratelim_t pinned_warning_limit = RATELIM_INIT(300);
2553 log_fn_ratelim(&pinned_warning_limit, LOG_WARN, LD_CIRC,
2554 "Could not find a node that matches the configured "
2555 "_HSLayer%dNodes set", cur_len+1);
2558 return node;
2561 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
2562 * and <b>state</b> and the cpath <b>head</b> (currently populated only
2563 * to length <b>cur_len</b> to decide a suitable middle hop for a
2564 * circuit. In particular, make sure we don't pick the exit node or its
2565 * family, and make sure we don't duplicate any previous nodes or their
2566 * families. */
2567 static const node_t *
2568 choose_good_middle_server(uint8_t purpose,
2569 cpath_build_state_t *state,
2570 crypt_path_t *head,
2571 int cur_len)
2573 const node_t *choice;
2574 smartlist_t *excluded;
2575 const or_options_t *options = get_options();
2576 router_crn_flags_t flags = CRN_NEED_DESC;
2577 tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
2578 purpose <= CIRCUIT_PURPOSE_MAX_);
2580 log_debug(LD_CIRC, "Contemplating intermediate hop #%d: random choice.",
2581 cur_len+1);
2583 excluded = build_middle_exclude_list(purpose, state, head, cur_len);
2585 if (state->need_uptime)
2586 flags |= CRN_NEED_UPTIME;
2587 if (state->need_capacity)
2588 flags |= CRN_NEED_CAPACITY;
2590 /** If a hidden service circuit wants a specific middle node, pin it. */
2591 if (middle_node_must_be_vanguard(options, purpose, cur_len)) {
2592 log_debug(LD_GENERAL, "Picking a sticky node (cur_len = %d)", cur_len);
2593 choice = pick_vanguard_middle_node(options, flags, cur_len, excluded);
2594 smartlist_free(excluded);
2595 return choice;
2598 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2599 smartlist_free(excluded);
2600 return choice;
2603 /** Pick a good entry server for the circuit to be built according to
2604 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2605 * router (if we're an OR), and respect firewall settings; if we're
2606 * configured to use entry guards, return one.
2608 * Set *<b>guard_state_out</b> to information about the guard that
2609 * we're selecting, which we'll use later to remember whether the
2610 * guard worked or not.
2612 const node_t *
2613 choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state,
2614 circuit_guard_state_t **guard_state_out)
2616 const node_t *choice;
2617 smartlist_t *excluded;
2618 const or_options_t *options = get_options();
2619 /* If possible, choose an entry server with a preferred address,
2620 * otherwise, choose one with an allowed address */
2621 router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
2622 CRN_DIRECT_CONN);
2623 const node_t *node;
2625 /* Once we used this function to select a node to be a guard. We had
2626 * 'state == NULL' be the signal for that. But we don't do that any more.
2628 tor_assert_nonfatal(state);
2630 if (state && options->UseEntryGuards &&
2631 (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
2632 /* This request is for an entry server to use for a regular circuit,
2633 * and we use entry guard nodes. Just return one of the guard nodes. */
2634 tor_assert(guard_state_out);
2635 return guards_choose_guard(state, purpose, guard_state_out);
2638 excluded = smartlist_new();
2640 if (state && (node = build_state_get_exit_node(state))) {
2641 /* Exclude the exit node from the state, if we have one. Also exclude its
2642 * family. */
2643 nodelist_add_node_and_family(excluded, node);
2646 if (state) {
2647 if (state->need_uptime)
2648 flags |= CRN_NEED_UPTIME;
2649 if (state->need_capacity)
2650 flags |= CRN_NEED_CAPACITY;
2653 choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
2654 smartlist_free(excluded);
2655 return choice;
2658 /** Return the first non-open hop in cpath, or return NULL if all
2659 * hops are open. */
2660 static crypt_path_t *
2661 onion_next_hop_in_cpath(crypt_path_t *cpath)
2663 crypt_path_t *hop = cpath;
2664 do {
2665 if (hop->state != CPATH_STATE_OPEN)
2666 return hop;
2667 hop = hop->next;
2668 } while (hop != cpath);
2669 return NULL;
2672 /** Choose a suitable next hop for the circuit <b>circ</b>.
2673 * Append the hop info to circ->cpath.
2675 * Return 1 if the path is complete, 0 if we successfully added a hop,
2676 * and -1 on error.
2678 STATIC int
2679 onion_extend_cpath(origin_circuit_t *circ)
2681 uint8_t purpose = circ->base_.purpose;
2682 cpath_build_state_t *state = circ->build_state;
2683 int cur_len = circuit_get_cpath_len(circ);
2684 extend_info_t *info = NULL;
2686 if (cur_len >= state->desired_path_len) {
2687 log_debug(LD_CIRC, "Path is complete: %d steps long",
2688 state->desired_path_len);
2689 return 1;
2692 log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
2693 state->desired_path_len);
2695 if (cur_len == state->desired_path_len - 1) { /* Picking last node */
2696 info = extend_info_dup(state->chosen_exit);
2697 } else if (cur_len == 0) { /* picking first node */
2698 const node_t *r = choose_good_entry_server(purpose, state,
2699 &circ->guard_state);
2700 if (r) {
2701 /* If we're a client, use the preferred address rather than the
2702 primary address, for potentially connecting to an IPv6 OR
2703 port. Servers always want the primary (IPv4) address. */
2704 int client = (server_mode(get_options()) == 0);
2705 info = extend_info_from_node(r, client);
2706 /* Clients can fail to find an allowed address */
2707 tor_assert_nonfatal(info || client);
2709 } else {
2710 const node_t *r =
2711 choose_good_middle_server(purpose, state, circ->cpath, cur_len);
2712 if (r) {
2713 info = extend_info_from_node(r, 0);
2714 tor_assert_nonfatal(info);
2718 if (!info) {
2719 log_warn(LD_CIRC,"Failed to find node for hop #%d of our path. Discarding "
2720 "this circuit.", cur_len+1);
2721 return -1;
2724 log_debug(LD_CIRC,"Chose router %s for hop #%d (exit is %s)",
2725 extend_info_describe(info),
2726 cur_len+1, build_state_get_exit_nickname(state));
2728 onion_append_hop(&circ->cpath, info);
2729 extend_info_free(info);
2730 return 0;
2733 /** Create a new hop, annotate it with information about its
2734 * corresponding router <b>choice</b>, and append it to the
2735 * end of the cpath <b>head_ptr</b>. */
2736 STATIC int
2737 onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
2739 crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
2741 /* link hop into the cpath, at the end. */
2742 onion_append_to_cpath(head_ptr, hop);
2744 hop->magic = CRYPT_PATH_MAGIC;
2745 hop->state = CPATH_STATE_CLOSED;
2747 hop->extend_info = extend_info_dup(choice);
2749 hop->package_window = circuit_initial_package_window();
2750 hop->deliver_window = CIRCWINDOW_START;
2752 return 0;
2755 /** Allocate a new extend_info object based on the various arguments. */
2756 extend_info_t *
2757 extend_info_new(const char *nickname,
2758 const char *rsa_id_digest,
2759 const ed25519_public_key_t *ed_id,
2760 crypto_pk_t *onion_key,
2761 const curve25519_public_key_t *ntor_key,
2762 const tor_addr_t *addr, uint16_t port)
2764 extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
2765 memcpy(info->identity_digest, rsa_id_digest, DIGEST_LEN);
2766 if (ed_id && !ed25519_public_key_is_zero(ed_id))
2767 memcpy(&info->ed_identity, ed_id, sizeof(ed25519_public_key_t));
2768 if (nickname)
2769 strlcpy(info->nickname, nickname, sizeof(info->nickname));
2770 if (onion_key)
2771 info->onion_key = crypto_pk_dup_key(onion_key);
2772 if (ntor_key)
2773 memcpy(&info->curve25519_onion_key, ntor_key,
2774 sizeof(curve25519_public_key_t));
2775 tor_addr_copy(&info->addr, addr);
2776 info->port = port;
2777 return info;
2780 /** Allocate and return a new extend_info that can be used to build a
2781 * circuit to or through the node <b>node</b>. Use the primary address
2782 * of the node (i.e. its IPv4 address) unless
2783 * <b>for_direct_connect</b> is true, in which case the preferred
2784 * address is used instead. May return NULL if there is not enough
2785 * info about <b>node</b> to extend to it--for example, if the preferred
2786 * routerinfo_t or microdesc_t is missing, or if for_direct_connect is
2787 * true and none of the node's addresses is allowed by tor's firewall
2788 * and IP version config.
2790 extend_info_t *
2791 extend_info_from_node(const node_t *node, int for_direct_connect)
2793 crypto_pk_t *rsa_pubkey = NULL;
2794 extend_info_t *info = NULL;
2795 tor_addr_port_t ap;
2796 int valid_addr = 0;
2798 if (!node_has_preferred_descriptor(node, for_direct_connect)) {
2799 return NULL;
2802 /* Choose a preferred address first, but fall back to an allowed address. */
2803 if (for_direct_connect)
2804 fascist_firewall_choose_address_node(node, FIREWALL_OR_CONNECTION, 0, &ap);
2805 else {
2806 node_get_prim_orport(node, &ap);
2808 valid_addr = tor_addr_port_is_valid_ap(&ap, 0);
2810 if (valid_addr)
2811 log_debug(LD_CIRC, "using %s for %s",
2812 fmt_addrport(&ap.addr, ap.port),
2813 node->ri ? node->ri->nickname : node->rs->nickname);
2814 else
2815 log_warn(LD_CIRC, "Could not choose valid address for %s",
2816 node->ri ? node->ri->nickname : node->rs->nickname);
2818 /* Every node we connect or extend to must support ntor */
2819 if (!node_has_curve25519_onion_key(node)) {
2820 log_fn(LOG_PROTOCOL_WARN, LD_CIRC,
2821 "Attempted to create extend_info for a node that does not support "
2822 "ntor: %s", node_describe(node));
2823 return NULL;
2826 const ed25519_public_key_t *ed_pubkey = NULL;
2828 /* Don't send the ed25519 pubkey unless the target node actually supports
2829 * authenticating with it. */
2830 if (node_supports_ed25519_link_authentication(node, 0)) {
2831 log_info(LD_CIRC, "Including Ed25519 ID for %s", node_describe(node));
2832 ed_pubkey = node_get_ed25519_id(node);
2833 } else if (node_get_ed25519_id(node)) {
2834 log_info(LD_CIRC, "Not including the ed25519 ID for %s, since it won't "
2835 "be able to authenticate it.",
2836 node_describe(node));
2839 /* Retrieve the curve25519 pubkey. */
2840 const curve25519_public_key_t *curve_pubkey =
2841 node_get_curve25519_onion_key(node);
2842 rsa_pubkey = node_get_rsa_onion_key(node);
2844 if (valid_addr && node->ri) {
2845 info = extend_info_new(node->ri->nickname,
2846 node->identity,
2847 ed_pubkey,
2848 rsa_pubkey,
2849 curve_pubkey,
2850 &ap.addr,
2851 ap.port);
2852 } else if (valid_addr && node->rs && node->md) {
2853 info = extend_info_new(node->rs->nickname,
2854 node->identity,
2855 ed_pubkey,
2856 rsa_pubkey,
2857 curve_pubkey,
2858 &ap.addr,
2859 ap.port);
2862 crypto_pk_free(rsa_pubkey);
2863 return info;
2866 /** Release storage held by an extend_info_t struct. */
2867 void
2868 extend_info_free_(extend_info_t *info)
2870 if (!info)
2871 return;
2872 crypto_pk_free(info->onion_key);
2873 tor_free(info);
2876 /** Allocate and return a new extend_info_t with the same contents as
2877 * <b>info</b>. */
2878 extend_info_t *
2879 extend_info_dup(extend_info_t *info)
2881 extend_info_t *newinfo;
2882 tor_assert(info);
2883 newinfo = tor_malloc(sizeof(extend_info_t));
2884 memcpy(newinfo, info, sizeof(extend_info_t));
2885 if (info->onion_key)
2886 newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
2887 else
2888 newinfo->onion_key = NULL;
2889 return newinfo;
2892 /** Return the node_t for the chosen exit router in <b>state</b>.
2893 * If there is no chosen exit, or if we don't know the node_t for
2894 * the chosen exit, return NULL.
2896 const node_t *
2897 build_state_get_exit_node(cpath_build_state_t *state)
2899 if (!state || !state->chosen_exit)
2900 return NULL;
2901 return node_get_by_id(state->chosen_exit->identity_digest);
2904 /** Return the RSA ID digest for the chosen exit router in <b>state</b>.
2905 * If there is no chosen exit, return NULL.
2907 const uint8_t *
2908 build_state_get_exit_rsa_id(cpath_build_state_t *state)
2910 if (!state || !state->chosen_exit)
2911 return NULL;
2912 return (const uint8_t *) state->chosen_exit->identity_digest;
2915 /** Return the nickname for the chosen exit router in <b>state</b>. If
2916 * there is no chosen exit, or if we don't know the routerinfo_t for the
2917 * chosen exit, return NULL.
2919 const char *
2920 build_state_get_exit_nickname(cpath_build_state_t *state)
2922 if (!state || !state->chosen_exit)
2923 return NULL;
2924 return state->chosen_exit->nickname;
2927 /** Return true iff the given address can be used to extend to. */
2929 extend_info_addr_is_allowed(const tor_addr_t *addr)
2931 tor_assert(addr);
2933 /* Check if we have a private address and if we can extend to it. */
2934 if ((tor_addr_is_internal(addr, 0) || tor_addr_is_multicast(addr)) &&
2935 !get_options()->ExtendAllowPrivateAddresses) {
2936 goto disallow;
2938 /* Allowed! */
2939 return 1;
2940 disallow:
2941 return 0;
2944 /* Does ei have a valid TAP key? */
2946 extend_info_supports_tap(const extend_info_t* ei)
2948 tor_assert(ei);
2949 /* Valid TAP keys are not NULL */
2950 return ei->onion_key != NULL;
2953 /* Does ei have a valid ntor key? */
2955 extend_info_supports_ntor(const extend_info_t* ei)
2957 tor_assert(ei);
2958 /* Valid ntor keys have at least one non-zero byte */
2959 return !tor_mem_is_zero(
2960 (const char*)ei->curve25519_onion_key.public_key,
2961 CURVE25519_PUBKEY_LEN);
2964 /* Is circuit purpose allowed to use the deprecated TAP encryption protocol?
2965 * The hidden service protocol still uses TAP for some connections, because
2966 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2967 static int
2968 circuit_purpose_can_use_tap_impl(uint8_t purpose)
2970 return (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
2971 purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
2974 /* Is circ allowed to use the deprecated TAP encryption protocol?
2975 * The hidden service protocol still uses TAP for some connections, because
2976 * ntor onion keys aren't included in HS descriptors or INTRODUCE cells. */
2978 circuit_can_use_tap(const origin_circuit_t *circ)
2980 tor_assert(circ);
2981 tor_assert(circ->cpath);
2982 tor_assert(circ->cpath->extend_info);
2983 return (circuit_purpose_can_use_tap_impl(circ->base_.purpose) &&
2984 extend_info_supports_tap(circ->cpath->extend_info));
2987 /* Does circ have an onion key which it's allowed to use? */
2989 circuit_has_usable_onion_key(const origin_circuit_t *circ)
2991 tor_assert(circ);
2992 tor_assert(circ->cpath);
2993 tor_assert(circ->cpath->extend_info);
2994 return (extend_info_supports_ntor(circ->cpath->extend_info) ||
2995 circuit_can_use_tap(circ));
2998 /* Does ei have an onion key which it would prefer to use?
2999 * Currently, we prefer ntor keys*/
3001 extend_info_has_preferred_onion_key(const extend_info_t* ei)
3003 tor_assert(ei);
3004 return extend_info_supports_ntor(ei);
3007 /** Find the circuits that are waiting to find out whether their guards are
3008 * usable, and if any are ready to become usable, mark them open and try
3009 * attaching streams as appropriate. */
3010 void
3011 circuit_upgrade_circuits_from_guard_wait(void)
3013 smartlist_t *to_upgrade =
3014 circuit_find_circuits_to_upgrade_from_guard_wait();
3016 if (to_upgrade == NULL)
3017 return;
3019 log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
3020 "to 'open'.", smartlist_len(to_upgrade));
3022 SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
3023 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
3024 circuit_has_opened(circ);
3025 } SMARTLIST_FOREACH_END(circ);
3027 smartlist_free(to_upgrade);