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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
9 * \brief The actual details of building circuits.
14 #include "circuitbuild.h"
15 #include "circuitlist.h"
16 #include "circuitstats.h"
17 #include "circuituse.h"
20 #include "confparse.h"
21 #include "connection.h"
22 #include "connection_edge.h"
23 #include "connection_or.h"
25 #include "directory.h"
26 #include "entrynodes.h"
28 #include "networkstatus.h"
31 #include "onion_tap.h"
32 #include "onion_fast.h"
34 #include "transports.h"
38 #include "routerlist.h"
39 #include "routerparse.h"
40 #include "routerset.h"
42 #include "connection_edge.h"
45 #define MIN(a,b) ((a)<(b)?(a):(b))
48 /********* START VARIABLES **********/
50 /** A global list of all circuits at this hop. */
51 extern circuit_t
*global_circuitlist
;
53 /********* END VARIABLES ************/
55 static channel_t
* channel_connect_for_circuit(const tor_addr_t
*addr
,
57 const char *id_digest
);
58 static int circuit_deliver_create_cell(circuit_t
*circ
,
59 const create_cell_t
*create_cell
,
61 static int onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
);
62 static crypt_path_t
*onion_next_hop_in_cpath(crypt_path_t
*cpath
);
63 static int onion_extend_cpath(origin_circuit_t
*circ
);
64 static int count_acceptable_nodes(smartlist_t
*routers
);
65 static int onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
);
66 static int entry_guard_inc_circ_attempt_count(entry_guard_t
*guard
);
67 static void pathbias_count_build_success(origin_circuit_t
*circ
);
68 static void pathbias_count_successful_close(origin_circuit_t
*circ
);
69 static void pathbias_count_collapse(origin_circuit_t
*circ
);
70 static void pathbias_count_unusable(origin_circuit_t
*circ
);
72 /** This function tries to get a channel to the specified endpoint,
73 * and then calls command_setup_channel() to give it the right
77 channel_connect_for_circuit(const tor_addr_t
*addr
, uint16_t port
,
78 const char *id_digest
)
82 chan
= channel_connect(addr
, port
, id_digest
);
83 if (chan
) command_setup_channel(chan
);
88 /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
89 * and with the high bit specified by conn-\>circ_id_type, until we get
90 * a circ_id that is not in use by any other circuit on that conn.
92 * Return it, or 0 if can't get a unique circ_id.
95 get_unique_circ_id_by_chan(channel_t
*chan
)
97 circid_t test_circ_id
;
103 if (chan
->circ_id_type
== CIRC_ID_TYPE_NEITHER
) {
105 "Trying to pick a circuit ID for a connection from "
106 "a client with no identity.");
110 (chan
->circ_id_type
== CIRC_ID_TYPE_HIGHER
) ? 1<<15 : 0;
112 /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
113 * circID such that (high_bit|test_circ_id) is not already used. */
114 test_circ_id
= chan
->next_circ_id
++;
115 if (test_circ_id
== 0 || test_circ_id
>= 1<<15) {
117 chan
->next_circ_id
= 2;
119 if (++attempts
> 1<<15) {
120 /* Make sure we don't loop forever if all circ_id's are used. This
121 * matters because it's an external DoS opportunity.
123 log_warn(LD_CIRC
,"No unused circ IDs. Failing.");
126 test_circ_id
|= high_bit
;
127 } while (circuit_id_in_use_on_channel(test_circ_id
, chan
));
131 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
132 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
133 * list information about link status in a more verbose format using spaces.
134 * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
135 * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
139 circuit_list_path_impl(origin_circuit_t
*circ
, int verbose
, int verbose_names
)
142 smartlist_t
*elements
;
143 const char *states
[] = {"closed", "waiting for keys", "open"};
146 elements
= smartlist_new();
149 const char *nickname
= build_state_get_exit_nickname(circ
->build_state
);
150 smartlist_add_asprintf(elements
, "%s%s circ (length %d%s%s):",
151 circ
->build_state
->is_internal
? "internal" : "exit",
152 circ
->build_state
->need_uptime
? " (high-uptime)" : "",
153 circ
->build_state
->desired_path_len
,
154 circ
->base_
.state
== CIRCUIT_STATE_OPEN
? "" : ", last hop ",
155 circ
->base_
.state
== CIRCUIT_STATE_OPEN
? "" :
156 (nickname
?nickname
:"*unnamed*"));
166 if (!verbose
&& hop
->state
!= CPATH_STATE_OPEN
)
168 if (!hop
->extend_info
)
170 id
= hop
->extend_info
->identity_digest
;
172 elt
= tor_malloc(MAX_VERBOSE_NICKNAME_LEN
+1);
173 if ((node
= node_get_by_id(id
))) {
174 node_get_verbose_nickname(node
, elt
);
175 } else if (is_legal_nickname(hop
->extend_info
->nickname
)) {
177 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
178 elt
[HEX_DIGEST_LEN
+1]= '~';
179 strlcpy(elt
+HEX_DIGEST_LEN
+2,
180 hop
->extend_info
->nickname
, MAX_NICKNAME_LEN
+1);
183 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
185 } else { /* ! verbose_names */
186 node
= node_get_by_id(id
);
187 if (node
&& node_is_named(node
)) {
188 elt
= tor_strdup(node_get_nickname(node
));
190 elt
= tor_malloc(HEX_DIGEST_LEN
+2);
192 base16_encode(elt
+1, HEX_DIGEST_LEN
+1, id
, DIGEST_LEN
);
197 tor_assert(hop
->state
<= 2);
198 smartlist_add_asprintf(elements
,"%s(%s)",elt
,states
[hop
->state
]);
201 smartlist_add(elements
, elt
);
204 } while (hop
!= circ
->cpath
);
206 s
= smartlist_join_strings(elements
, verbose
?" ":",", 0, NULL
);
207 SMARTLIST_FOREACH(elements
, char*, cp
, tor_free(cp
));
208 smartlist_free(elements
);
212 /** If <b>verbose</b> is false, allocate and return a comma-separated
213 * list of the currently built elements of <b>circ</b>. If
214 * <b>verbose</b> is true, also list information about link status in
215 * a more verbose format using spaces.
218 circuit_list_path(origin_circuit_t
*circ
, int verbose
)
220 return circuit_list_path_impl(circ
, verbose
, 0);
223 /** Allocate and return a comma-separated list of the currently built elements
224 * of <b>circ</b>, giving each as a verbose nickname.
227 circuit_list_path_for_controller(origin_circuit_t
*circ
)
229 return circuit_list_path_impl(circ
, 0, 1);
232 /** Log, at severity <b>severity</b>, the nicknames of each router in
233 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
237 circuit_log_path(int severity
, unsigned int domain
, origin_circuit_t
*circ
)
239 char *s
= circuit_list_path(circ
,1);
240 tor_log(severity
,domain
,"%s",s
);
244 /** Tell the rep(utation)hist(ory) module about the status of the links
245 * in <b>circ</b>. Hops that have become OPEN are marked as successfully
246 * extended; the _first_ hop that isn't open (if any) is marked as
249 /* XXXX Someday we should learn from OR circuits too. */
251 circuit_rep_hist_note_result(origin_circuit_t
*circ
)
254 const char *prev_digest
= NULL
;
256 if (!hop
) /* circuit hasn't started building yet. */
258 if (server_mode(get_options())) {
259 const routerinfo_t
*me
= router_get_my_routerinfo();
262 prev_digest
= me
->cache_info
.identity_digest
;
265 const node_t
*node
= node_get_by_id(hop
->extend_info
->identity_digest
);
266 if (node
) { /* Why do we check this? We know the identity. -NM XXXX */
268 if (hop
->state
== CPATH_STATE_OPEN
)
269 rep_hist_note_extend_succeeded(prev_digest
, node
->identity
);
271 rep_hist_note_extend_failed(prev_digest
, node
->identity
);
275 prev_digest
= node
->identity
;
280 } while (hop
!=circ
->cpath
);
283 /** Pick all the entries in our cpath. Stop and return 0 when we're
284 * happy, or return -1 if an error occurs. */
286 onion_populate_cpath(origin_circuit_t
*circ
)
290 r
= onion_extend_cpath(circ
);
292 log_info(LD_CIRC
,"Generating cpath hop failed.");
297 return 0; /* if r == 1 */
300 /** Create and return a new origin circuit. Initialize its purpose and
301 * build-state based on our arguments. The <b>flags</b> argument is a
302 * bitfield of CIRCLAUNCH_* flags. */
304 origin_circuit_init(uint8_t purpose
, int flags
)
306 /* sets circ->p_circ_id and circ->p_chan */
307 origin_circuit_t
*circ
= origin_circuit_new();
308 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_CHAN_WAIT
);
309 circ
->build_state
= tor_malloc_zero(sizeof(cpath_build_state_t
));
310 circ
->build_state
->onehop_tunnel
=
311 ((flags
& CIRCLAUNCH_ONEHOP_TUNNEL
) ? 1 : 0);
312 circ
->build_state
->need_uptime
=
313 ((flags
& CIRCLAUNCH_NEED_UPTIME
) ? 1 : 0);
314 circ
->build_state
->need_capacity
=
315 ((flags
& CIRCLAUNCH_NEED_CAPACITY
) ? 1 : 0);
316 circ
->build_state
->is_internal
=
317 ((flags
& CIRCLAUNCH_IS_INTERNAL
) ? 1 : 0);
318 circ
->base_
.purpose
= purpose
;
322 /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
323 * is defined, then use that as your exit router, else choose a suitable
326 * Also launch a connection to the first OR in the chosen path, if
327 * it's not open already.
330 circuit_establish_circuit(uint8_t purpose
, extend_info_t
*exit
, int flags
)
332 origin_circuit_t
*circ
;
335 circ
= origin_circuit_init(purpose
, flags
);
337 if (onion_pick_cpath_exit(circ
, exit
) < 0 ||
338 onion_populate_cpath(circ
) < 0) {
339 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_NOPATH
);
343 control_event_circuit_status(circ
, CIRC_EVENT_LAUNCHED
, 0);
345 if ((err_reason
= circuit_handle_first_hop(circ
)) < 0) {
346 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
352 /** Start establishing the first hop of our circuit. Figure out what
353 * OR we should connect to, and if necessary start the connection to
354 * it. If we're already connected, then send the 'create' cell.
355 * Return 0 for ok, -reason if circ should be marked-for-close. */
357 circuit_handle_first_hop(origin_circuit_t
*circ
)
359 crypt_path_t
*firsthop
;
362 const char *msg
= NULL
;
363 int should_launch
= 0;
365 firsthop
= onion_next_hop_in_cpath(circ
->cpath
);
366 tor_assert(firsthop
);
367 tor_assert(firsthop
->extend_info
);
369 /* now see if we're already connected to the first OR in 'route' */
370 log_debug(LD_CIRC
,"Looking for firsthop '%s'",
371 fmt_addrport(&firsthop
->extend_info
->addr
,
372 firsthop
->extend_info
->port
));
374 n_chan
= channel_get_for_extend(firsthop
->extend_info
->identity_digest
,
375 &firsthop
->extend_info
->addr
,
380 /* not currently connected in a useful way. */
381 log_info(LD_CIRC
, "Next router is %s: %s",
382 safe_str_client(extend_info_describe(firsthop
->extend_info
)),
384 circ
->base_
.n_hop
= extend_info_dup(firsthop
->extend_info
);
387 if (circ
->build_state
->onehop_tunnel
)
388 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR
, 0);
389 n_chan
= channel_connect_for_circuit(
390 &firsthop
->extend_info
->addr
,
391 firsthop
->extend_info
->port
,
392 firsthop
->extend_info
->identity_digest
);
393 if (!n_chan
) { /* connect failed, forget the whole thing */
394 log_info(LD_CIRC
,"connect to firsthop failed. Closing.");
395 return -END_CIRC_REASON_CONNECTFAILED
;
399 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
400 /* return success. The onion/circuit/etc will be taken care of
401 * automatically (may already have been) whenever n_chan reaches
402 * OR_CONN_STATE_OPEN.
405 } else { /* it's already open. use it. */
406 tor_assert(!circ
->base_
.n_hop
);
407 circ
->base_
.n_chan
= n_chan
;
408 log_debug(LD_CIRC
,"Conn open. Delivering first onion skin.");
409 if ((err_reason
= circuit_send_next_onion_skin(circ
)) < 0) {
410 log_info(LD_CIRC
,"circuit_send_next_onion_skin failed.");
417 /** Find any circuits that are waiting on <b>or_conn</b> to become
418 * open and get them to send their create cells forward.
420 * Status is 1 if connect succeeded, or 0 if connect failed.
423 circuit_n_chan_done(channel_t
*chan
, int status
)
425 smartlist_t
*pending_circs
;
430 log_debug(LD_CIRC
,"chan to %s/%s, status=%d",
431 chan
->nickname
? chan
->nickname
: "NULL",
432 channel_get_canonical_remote_descr(chan
), status
);
434 pending_circs
= smartlist_new();
435 circuit_get_all_pending_on_channel(pending_circs
, chan
);
437 SMARTLIST_FOREACH_BEGIN(pending_circs
, circuit_t
*, circ
)
439 /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
440 * leaving them in in case it's possible for the status of a circuit to
441 * change as we're going down the list. */
442 if (circ
->marked_for_close
|| circ
->n_chan
|| !circ
->n_hop
||
443 circ
->state
!= CIRCUIT_STATE_CHAN_WAIT
)
446 if (tor_digest_is_zero(circ
->n_hop
->identity_digest
)) {
447 /* Look at addr/port. This is an unkeyed connection. */
448 if (!channel_matches_extend_info(chan
, circ
->n_hop
))
451 /* We expected a key. See if it's the right one. */
452 if (tor_memneq(chan
->identity_digest
,
453 circ
->n_hop
->identity_digest
, DIGEST_LEN
))
456 if (!status
) { /* chan failed; close circ */
457 log_info(LD_CIRC
,"Channel failed; closing circ.");
458 circuit_mark_for_close(circ
, END_CIRC_REASON_CHANNEL_CLOSED
);
461 log_debug(LD_CIRC
, "Found circ, sending create cell.");
462 /* circuit_deliver_create_cell will set n_circ_id and add us to
463 * chan_circuid_circuit_map, so we don't need to call
464 * set_circid_chan here. */
466 extend_info_free(circ
->n_hop
);
469 if (CIRCUIT_IS_ORIGIN(circ
)) {
471 circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ
))) < 0) {
473 "send_next_onion_skin failed; circuit marked for closing.");
474 circuit_mark_for_close(circ
, -err_reason
);
476 /* XXX could this be bad, eg if next_onion_skin failed because conn
480 /* pull the create cell out of circ->n_chan_create_cell, and send it */
481 tor_assert(circ
->n_chan_create_cell
);
482 if (circuit_deliver_create_cell(circ
, circ
->n_chan_create_cell
, 1)<0) {
483 circuit_mark_for_close(circ
, END_CIRC_REASON_RESOURCELIMIT
);
486 tor_free(circ
->n_chan_create_cell
);
487 circuit_set_state(circ
, CIRCUIT_STATE_OPEN
);
490 SMARTLIST_FOREACH_END(circ
);
492 smartlist_free(pending_circs
);
495 /** Find a new circid that isn't currently in use on the circ->n_chan
497 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
498 * circuit. If <b>relayed</b> is true, this is a create cell somebody
499 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
500 * it. Return -1 if we failed to find a suitable circid, else return 0.
503 circuit_deliver_create_cell(circuit_t
*circ
, const create_cell_t
*create_cell
,
511 tor_assert(circ
->n_chan
);
512 tor_assert(create_cell
);
513 tor_assert(create_cell
->cell_type
== CELL_CREATE
||
514 create_cell
->cell_type
== CELL_CREATE_FAST
||
515 create_cell
->cell_type
== CELL_CREATE2
);
517 id
= get_unique_circ_id_by_chan(circ
->n_chan
);
519 log_warn(LD_CIRC
,"failed to get unique circID.");
522 log_debug(LD_CIRC
,"Chosen circID %u.", id
);
523 circuit_set_n_circid_chan(circ
, id
, circ
->n_chan
);
525 memset(&cell
, 0, sizeof(cell_t
));
526 r
= relayed
? create_cell_format_relayed(&cell
, create_cell
)
527 : create_cell_format(&cell
, create_cell
);
529 log_warn(LD_CIRC
,"Couldn't format create cell");
532 cell
.circ_id
= circ
->n_circ_id
;
534 append_cell_to_circuit_queue(circ
, circ
->n_chan
, &cell
,
535 CELL_DIRECTION_OUT
, 0);
537 if (CIRCUIT_IS_ORIGIN(circ
)) {
538 /* Update began timestamp for circuits starting their first hop */
539 if (TO_ORIGIN_CIRCUIT(circ
)->cpath
->state
== CPATH_STATE_CLOSED
) {
540 if (circ
->n_chan
->state
!= CHANNEL_STATE_OPEN
) {
542 "Got first hop for a circuit without an opened channel. "
543 "State: %s.", channel_state_to_string(circ
->n_chan
->state
));
544 tor_fragile_assert();
547 tor_gettimeofday(&circ
->timestamp_began
);
550 /* mark it so it gets better rate limiting treatment. */
551 channel_timestamp_client(circ
->n_chan
);
557 /** We've decided to start our reachability testing. If all
558 * is set, log this to the user. Return 1 if we did, or 0 if
559 * we chose not to log anything. */
561 inform_testing_reachability(void)
564 const routerinfo_t
*me
= router_get_my_routerinfo();
567 control_event_server_status(LOG_NOTICE
,
568 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
569 me
->address
, me
->or_port
);
571 tor_snprintf(dirbuf
, sizeof(dirbuf
), " and DirPort %s:%d",
572 me
->address
, me
->dir_port
);
573 control_event_server_status(LOG_NOTICE
,
574 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
575 me
->address
, me
->dir_port
);
577 log_notice(LD_OR
, "Now checking whether ORPort %s:%d%s %s reachable... "
578 "(this may take up to %d minutes -- look for log "
579 "messages indicating success)",
580 me
->address
, me
->or_port
,
581 me
->dir_port
? dirbuf
: "",
582 me
->dir_port
? "are" : "is",
583 TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT
/60);
588 /** Return true iff we should send a create_fast cell to start building a given
591 should_use_create_fast_for_circuit(origin_circuit_t
*circ
)
593 const or_options_t
*options
= get_options();
594 tor_assert(circ
->cpath
);
595 tor_assert(circ
->cpath
->extend_info
);
597 if (!circ
->cpath
->extend_info
->onion_key
)
598 return 1; /* our hand is forced: only a create_fast will work. */
599 if (!options
->FastFirstHopPK
)
600 return 0; /* we prefer to avoid create_fast */
601 if (public_server_mode(options
)) {
602 /* We're a server, and we know an onion key. We can choose.
603 * Prefer to blend our circuit into the other circuits we are
604 * creating on behalf of others. */
611 /** Return true if <b>circ</b> is the type of circuit we want to count
612 * timeouts from. In particular, we want it to have not completed yet
613 * (already completing indicates we cannibalized it), and we want it to
614 * have exactly three hops.
617 circuit_timeout_want_to_count_circ(origin_circuit_t
*circ
)
619 return !circ
->has_opened
620 && circ
->build_state
->desired_path_len
== DEFAULT_ROUTE_LEN
;
623 #ifdef CURVE25519_ENABLED
624 /** Return true if the ntor handshake is enabled in the configuration, or if
625 * it's been set to "auto" in the configuration and it's enabled in the
628 circuits_can_use_ntor(void)
630 const or_options_t
*options
= get_options();
631 if (options
->UseNTorHandshake
!= -1)
632 return options
->UseNTorHandshake
;
633 return networkstatus_get_param(NULL
, "UseNTorHandshake", 0, 0, 1);
637 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
638 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
641 circuit_pick_create_handshake(uint8_t *cell_type_out
,
642 uint16_t *handshake_type_out
,
643 const extend_info_t
*ei
)
645 #ifdef CURVE25519_ENABLED
646 if (!tor_mem_is_zero((const char*)ei
->curve25519_onion_key
.public_key
,
647 CURVE25519_PUBKEY_LEN
) &&
648 circuits_can_use_ntor()) {
649 *cell_type_out
= CELL_CREATE2
;
650 *handshake_type_out
= ONION_HANDSHAKE_TYPE_NTOR
;
657 *cell_type_out
= CELL_CREATE
;
658 *handshake_type_out
= ONION_HANDSHAKE_TYPE_TAP
;
661 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
662 * directly, and set *<b>handshake_type_out</b> accordingly. Decide whether,
663 * in extending through <b>node</b> to do so, we should use an EXTEND2 or an
664 * EXTEND cell to do so, and set *<b>cell_type_out</b> and
665 * *<b>create_cell_type_out</b> accordingly. */
667 circuit_pick_extend_handshake(uint8_t *cell_type_out
,
668 uint8_t *create_cell_type_out
,
669 uint16_t *handshake_type_out
,
670 const node_t
*node_prev
,
671 const extend_info_t
*ei
)
674 circuit_pick_create_handshake(&t
, handshake_type_out
, ei
);
675 /* XXXX024 The check for whether the node has a curve25519 key is a bad
676 * proxy for whether it can do extend2 cells; once a version that
677 * handles extend2 cells is out, remove it. */
679 *handshake_type_out
!= ONION_HANDSHAKE_TYPE_TAP
&&
680 (node_has_curve25519_onion_key(node_prev
) ||
681 (node_prev
->rs
&& node_prev
->rs
->version_supports_extend2_cells
))) {
682 *cell_type_out
= RELAY_COMMAND_EXTEND2
;
683 *create_cell_type_out
= CELL_CREATE2
;
685 *cell_type_out
= RELAY_COMMAND_EXTEND
;
686 *create_cell_type_out
= CELL_CREATE
;
690 /** This is the backbone function for building circuits.
692 * If circ's first hop is closed, then we need to build a create
693 * cell and send it forward.
695 * Otherwise, we need to build a relay extend cell and send it
698 * Return -reason if we want to tear down circ, else return 0.
701 circuit_send_next_onion_skin(origin_circuit_t
*circ
)
708 if (circ
->cpath
->state
== CPATH_STATE_CLOSED
) {
709 /* This is the first hop. */
713 log_debug(LD_CIRC
,"First skin; sending create cell.");
714 memset(&cc
, 0, sizeof(cc
));
715 if (circ
->build_state
->onehop_tunnel
)
716 control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE
, 0);
718 control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE
, 0);
720 node
= node_get_by_id(circ
->base_
.n_chan
->identity_digest
);
721 fast
= should_use_create_fast_for_circuit(circ
);
723 /* We are an OR and we know the right onion key: we should
724 * send a create cell.
726 circuit_pick_create_handshake(&cc
.cell_type
, &cc
.handshake_type
,
727 circ
->cpath
->extend_info
);
728 note_request("cell: create", 1);
730 /* We are not an OR, and we're building the first hop of a circuit to a
731 * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
732 * and a DH operation. */
733 cc
.cell_type
= CELL_CREATE_FAST
;
734 cc
.handshake_type
= ONION_HANDSHAKE_TYPE_FAST
;
735 note_request("cell: create fast", 1);
738 len
= onion_skin_create(cc
.handshake_type
,
739 circ
->cpath
->extend_info
,
740 &circ
->cpath
->handshake_state
,
743 log_warn(LD_CIRC
,"onion_skin_create (first hop) failed.");
744 return - END_CIRC_REASON_INTERNAL
;
746 cc
.handshake_len
= len
;
748 if (circuit_deliver_create_cell(TO_CIRCUIT(circ
), &cc
, 0) < 0)
749 return - END_CIRC_REASON_RESOURCELIMIT
;
751 circ
->cpath
->state
= CPATH_STATE_AWAITING_KEYS
;
752 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
753 log_info(LD_CIRC
,"First hop: finished sending %s cell to '%s'",
754 fast
? "CREATE_FAST" : "CREATE",
755 node
? node_describe(node
) : "<unnamed>");
759 tor_assert(circ
->cpath
->state
== CPATH_STATE_OPEN
);
760 tor_assert(circ
->base_
.state
== CIRCUIT_STATE_BUILDING
);
761 log_debug(LD_CIRC
,"starting to send subsequent skin.");
762 hop
= onion_next_hop_in_cpath(circ
->cpath
);
763 memset(&ec
, 0, sizeof(ec
));
765 /* done building the circuit. whew. */
766 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
767 if (circuit_timeout_want_to_count_circ(circ
)) {
770 tor_gettimeofday(&end
);
771 timediff
= tv_mdiff(&circ
->base_
.timestamp_began
, &end
);
774 * If the circuit build time is much greater than we would have cut
775 * it off at, we probably had a suspend event along this codepath,
776 * and we should discard the value.
778 if (timediff
< 0 || timediff
> 2*circ_times
.close_ms
+1000) {
779 log_notice(LD_CIRC
, "Strange value for circuit build time: %ldmsec. "
780 "Assuming clock jump. Purpose %d (%s)", timediff
,
782 circuit_purpose_to_string(circ
->base_
.purpose
));
783 } else if (!circuit_build_times_disabled()) {
784 /* Only count circuit times if the network is live */
785 if (circuit_build_times_network_check_live(&circ_times
)) {
786 circuit_build_times_add_time(&circ_times
, (build_time_t
)timediff
);
787 circuit_build_times_set_timeout(&circ_times
);
790 if (circ
->base_
.purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
791 circuit_build_times_network_circ_success(&circ_times
);
795 log_info(LD_CIRC
,"circuit built!");
796 circuit_reset_failure_count(0);
798 if (circ
->build_state
->onehop_tunnel
|| circ
->has_opened
) {
799 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS
, 0);
802 if (!can_complete_circuit
&& !circ
->build_state
->onehop_tunnel
) {
803 const or_options_t
*options
= get_options();
804 can_complete_circuit
=1;
805 /* FFFF Log a count of known routers here */
806 log_notice(LD_GENERAL
,
807 "Tor has successfully opened a circuit. "
808 "Looks like client functionality is working.");
809 control_event_bootstrap(BOOTSTRAP_STATUS_DONE
, 0);
810 control_event_client_status(LOG_NOTICE
, "CIRCUIT_ESTABLISHED");
811 clear_broken_connection_map(1);
812 if (server_mode(options
) && !check_whether_orport_reachable()) {
813 inform_testing_reachability();
814 consider_testing_reachability(1, 1);
818 pathbias_count_build_success(circ
);
819 circuit_rep_hist_note_result(circ
);
820 circuit_has_opened(circ
); /* do other actions as necessary */
822 /* We're done with measurement circuits here. Just close them */
823 if (circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
824 /* If a measurement circ ever gets back to us, consider it
825 * succeeded for path bias */
826 circ
->path_state
= PATH_STATE_USE_SUCCEEDED
;
827 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_FINISHED
);
832 if (tor_addr_family(&hop
->extend_info
->addr
) != AF_INET
) {
833 log_warn(LD_BUG
, "Trying to extend to a non-IPv4 address.");
834 return - END_CIRC_REASON_INTERNAL
;
838 const node_t
*prev_node
;
839 prev_node
= node_get_by_id(hop
->prev
->extend_info
->identity_digest
);
840 circuit_pick_extend_handshake(&ec
.cell_type
,
841 &ec
.create_cell
.cell_type
,
842 &ec
.create_cell
.handshake_type
,
847 tor_addr_copy(&ec
.orport_ipv4
.addr
, &hop
->extend_info
->addr
);
848 ec
.orport_ipv4
.port
= hop
->extend_info
->port
;
849 tor_addr_make_unspec(&ec
.orport_ipv6
.addr
);
850 memcpy(ec
.node_id
, hop
->extend_info
->identity_digest
, DIGEST_LEN
);
852 len
= onion_skin_create(ec
.create_cell
.handshake_type
,
854 &hop
->handshake_state
,
855 ec
.create_cell
.onionskin
);
857 log_warn(LD_CIRC
,"onion_skin_create failed.");
858 return - END_CIRC_REASON_INTERNAL
;
860 ec
.create_cell
.handshake_len
= len
;
862 log_info(LD_CIRC
,"Sending extend relay cell.");
863 note_request("cell: extend", 1);
866 uint16_t payload_len
=0;
867 uint8_t payload
[RELAY_PAYLOAD_SIZE
];
868 if (extend_cell_format(&command
, &payload_len
, payload
, &ec
)<0) {
869 log_warn(LD_CIRC
,"Couldn't format extend cell");
870 return -END_CIRC_REASON_INTERNAL
;
873 /* send it to hop->prev, because it will transfer
874 * it to a create cell and then send to hop */
875 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
877 (char*)payload
, payload_len
,
879 return 0; /* circuit is closed */
881 hop
->state
= CPATH_STATE_AWAITING_KEYS
;
886 /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
887 * something has also gone wrong with our network: notify the user,
888 * and abandon all not-yet-used circuits. */
890 circuit_note_clock_jumped(int seconds_elapsed
)
892 int severity
= server_mode(get_options()) ? LOG_WARN
: LOG_NOTICE
;
893 tor_log(severity
, LD_GENERAL
, "Your system clock just jumped %d seconds %s; "
894 "assuming established circuits no longer work.",
895 seconds_elapsed
>=0 ? seconds_elapsed
: -seconds_elapsed
,
896 seconds_elapsed
>=0 ? "forward" : "backward");
897 control_event_general_status(LOG_WARN
, "CLOCK_JUMPED TIME=%d",
899 can_complete_circuit
=0; /* so it'll log when it works again */
900 control_event_client_status(severity
, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
902 circuit_mark_all_unused_circs();
903 circuit_expire_all_dirty_circs();
906 /** Take the 'extend' <b>cell</b>, pull out addr/port plus the onion
907 * skin and identity digest for the next hop. If we're already connected,
908 * pass the onion skin to the next hop using a create cell; otherwise
909 * launch a new OR connection, and <b>circ</b> will notice when the
910 * connection succeeds or fails.
912 * Return -1 if we want to warn and tear down the circuit, else return 0.
915 circuit_extend(cell_t
*cell
, circuit_t
*circ
)
920 const char *msg
= NULL
;
921 int should_launch
= 0;
924 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
925 "n_chan already set. Bug/attack. Closing.");
929 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
930 "conn to next hop already launched. Bug/attack. Closing.");
934 if (!server_mode(get_options())) {
935 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
936 "Got an extend cell, but running as a client. Closing.");
940 relay_header_unpack(&rh
, cell
->payload
);
942 if (extend_cell_parse(&ec
, rh
.command
,
943 cell
->payload
+RELAY_HEADER_SIZE
,
945 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
946 "Can't parse extend cell. Closing circuit.");
950 if (!ec
.orport_ipv4
.port
|| tor_addr_is_null(&ec
.orport_ipv4
.addr
)) {
951 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
952 "Client asked me to extend to zero destination port or addr.");
956 if (tor_addr_is_internal(&ec
.orport_ipv4
.addr
, 0) &&
957 !get_options()->ExtendAllowPrivateAddresses
) {
958 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
959 "Client asked me to extend to a private address");
963 /* Check if they asked us for 0000..0000. We support using
964 * an empty fingerprint for the first hop (e.g. for a bridge relay),
965 * but we don't want to let people send us extend cells for empty
966 * fingerprints -- a) because it opens the user up to a mitm attack,
967 * and b) because it lets an attacker force the relay to hold open a
968 * new TLS connection for each extend request. */
969 if (tor_digest_is_zero((const char*)ec
.node_id
)) {
970 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
971 "Client asked me to extend without specifying an id_digest.");
975 /* Next, check if we're being asked to connect to the hop that the
976 * extend cell came from. There isn't any reason for that, and it can
977 * assist circular-path attacks. */
978 if (tor_memeq(ec
.node_id
,
979 TO_OR_CIRCUIT(circ
)->p_chan
->identity_digest
,
981 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
982 "Client asked me to extend back to the previous hop.");
986 n_chan
= channel_get_for_extend((const char*)ec
.node_id
,
987 &ec
.orport_ipv4
.addr
,
992 log_debug(LD_CIRC
|LD_OR
,"Next router (%s): %s",
993 fmt_addrport(&ec
.orport_ipv4
.addr
,ec
.orport_ipv4
.port
),
996 circ
->n_hop
= extend_info_new(NULL
/*nickname*/,
997 (const char*)ec
.node_id
,
999 NULL
/*curve25519_key*/,
1000 &ec
.orport_ipv4
.addr
,
1001 ec
.orport_ipv4
.port
);
1003 circ
->n_chan_create_cell
= tor_memdup(&ec
.create_cell
,
1004 sizeof(ec
.create_cell
));
1006 circuit_set_state(circ
, CIRCUIT_STATE_CHAN_WAIT
);
1008 if (should_launch
) {
1009 /* we should try to open a connection */
1010 n_chan
= channel_connect_for_circuit(&ec
.orport_ipv4
.addr
,
1011 ec
.orport_ipv4
.port
,
1012 (const char*)ec
.node_id
);
1014 log_info(LD_CIRC
,"Launching n_chan failed. Closing circuit.");
1015 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
1018 log_debug(LD_CIRC
,"connecting in progress (or finished). Good.");
1020 /* return success. The onion/circuit/etc will be taken care of
1021 * automatically (may already have been) whenever n_chan reaches
1022 * OR_CONN_STATE_OPEN.
1027 tor_assert(!circ
->n_hop
); /* Connection is already established. */
1028 circ
->n_chan
= n_chan
;
1031 channel_get_canonical_remote_descr(n_chan
));
1033 if (circuit_deliver_create_cell(circ
, &ec
.create_cell
, 1) < 0)
1039 /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
1040 * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
1042 * - 20 to initialize f_digest
1043 * - 20 to initialize b_digest
1044 * - 16 to key f_crypto
1045 * - 16 to key b_crypto
1047 * (If 'reverse' is true, then f_XX and b_XX are swapped.)
1050 circuit_init_cpath_crypto(crypt_path_t
*cpath
, const char *key_data
,
1053 crypto_digest_t
*tmp_digest
;
1054 crypto_cipher_t
*tmp_crypto
;
1057 tor_assert(key_data
);
1058 tor_assert(!(cpath
->f_crypto
|| cpath
->b_crypto
||
1059 cpath
->f_digest
|| cpath
->b_digest
));
1061 cpath
->f_digest
= crypto_digest_new();
1062 crypto_digest_add_bytes(cpath
->f_digest
, key_data
, DIGEST_LEN
);
1063 cpath
->b_digest
= crypto_digest_new();
1064 crypto_digest_add_bytes(cpath
->b_digest
, key_data
+DIGEST_LEN
, DIGEST_LEN
);
1066 if (!(cpath
->f_crypto
=
1067 crypto_cipher_new(key_data
+(2*DIGEST_LEN
)))) {
1068 log_warn(LD_BUG
,"Forward cipher initialization failed.");
1071 if (!(cpath
->b_crypto
=
1072 crypto_cipher_new(key_data
+(2*DIGEST_LEN
)+CIPHER_KEY_LEN
))) {
1073 log_warn(LD_BUG
,"Backward cipher initialization failed.");
1078 tmp_digest
= cpath
->f_digest
;
1079 cpath
->f_digest
= cpath
->b_digest
;
1080 cpath
->b_digest
= tmp_digest
;
1081 tmp_crypto
= cpath
->f_crypto
;
1082 cpath
->f_crypto
= cpath
->b_crypto
;
1083 cpath
->b_crypto
= tmp_crypto
;
1089 /** The minimum number of circuit attempts before we start
1090 * thinking about warning about path bias and dropping guards */
1092 pathbias_get_min_circs(const or_options_t
*options
)
1094 #define DFLT_PATH_BIAS_MIN_CIRC 150
1095 if (options
->PathBiasCircThreshold
>= 5)
1096 return options
->PathBiasCircThreshold
;
1098 return networkstatus_get_param(NULL
, "pb_mincircs",
1099 DFLT_PATH_BIAS_MIN_CIRC
,
1103 /** The circuit success rate below which we issue a notice */
1105 pathbias_get_notice_rate(const or_options_t
*options
)
1107 #define DFLT_PATH_BIAS_NOTICE_PCT 70
1108 if (options
->PathBiasNoticeRate
>= 0.0)
1109 return options
->PathBiasNoticeRate
;
1111 return networkstatus_get_param(NULL
, "pb_noticepct",
1112 DFLT_PATH_BIAS_NOTICE_PCT
, 0, 100)/100.0;
1115 /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
1116 /** The circuit success rate below which we issue a warn */
1118 pathbias_get_warn_rate(const or_options_t
*options
)
1120 #define DFLT_PATH_BIAS_WARN_PCT 50
1121 if (options
->PathBiasWarnRate
>= 0.0)
1122 return options
->PathBiasWarnRate
;
1124 return networkstatus_get_param(NULL
, "pb_warnpct",
1125 DFLT_PATH_BIAS_WARN_PCT
, 0, 100)/100.0;
1128 /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
1130 * The extreme rate is the rate at which we would drop the guard,
1131 * if pb_dropguard is also set. Otherwise we just warn.
1134 pathbias_get_extreme_rate(const or_options_t
*options
)
1136 #define DFLT_PATH_BIAS_EXTREME_PCT 30
1137 if (options
->PathBiasExtremeRate
>= 0.0)
1138 return options
->PathBiasExtremeRate
;
1140 return networkstatus_get_param(NULL
, "pb_extremepct",
1141 DFLT_PATH_BIAS_EXTREME_PCT
, 0, 100)/100.0;
1144 /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
1146 * If 1, we actually disable use of guards that fall below
1150 pathbias_get_dropguards(const or_options_t
*options
)
1152 #define DFLT_PATH_BIAS_DROP_GUARDS 0
1153 if (options
->PathBiasDropGuards
>= 0)
1154 return options
->PathBiasDropGuards
;
1156 return networkstatus_get_param(NULL
, "pb_dropguards",
1157 DFLT_PATH_BIAS_DROP_GUARDS
, 0, 1);
1161 * This is the number of circuits at which we scale our
1162 * counts by mult_factor/scale_factor. Note, this count is
1163 * not exact, as we only perform the scaling in the event
1164 * of no integer truncation.
1167 pathbias_get_scale_threshold(const or_options_t
*options
)
1169 #define DFLT_PATH_BIAS_SCALE_THRESHOLD 300
1170 if (options
->PathBiasScaleThreshold
>= 10)
1171 return options
->PathBiasScaleThreshold
;
1173 return networkstatus_get_param(NULL
, "pb_scalecircs",
1174 DFLT_PATH_BIAS_SCALE_THRESHOLD
, 10,
1179 * The scale factor is the denominator for our scaling
1180 * of circuit counts for our path bias window.
1182 * Note that our use of doubles for the path bias state
1183 * file means that powers of 2 work best here.
1186 pathbias_get_scale_factor(const or_options_t
*options
)
1188 #define DFLT_PATH_BIAS_SCALE_FACTOR 2
1189 if (options
->PathBiasScaleFactor
>= 1)
1190 return options
->PathBiasScaleFactor
;
1192 return networkstatus_get_param(NULL
, "pb_scalefactor",
1193 DFLT_PATH_BIAS_SCALE_FACTOR
, 1, INT32_MAX
);
1197 * The mult factor is the numerator for our scaling
1198 * of circuit counts for our path bias window. It
1199 * allows us to scale by fractions.
1202 pathbias_get_mult_factor(const or_options_t
*options
)
1204 #define DFLT_PATH_BIAS_MULT_FACTOR 1
1205 if (options
->PathBiasMultFactor
>= 1)
1206 return options
->PathBiasMultFactor
;
1208 return networkstatus_get_param(NULL
, "pb_multfactor",
1209 DFLT_PATH_BIAS_MULT_FACTOR
, 1,
1210 pathbias_get_scale_factor(options
));
1214 * If this parameter is set to a true value (default), we use the
1215 * successful_circuits_closed. Otherwise, we use the success_count.
1218 pathbias_use_close_counts(const or_options_t
*options
)
1220 #define DFLT_PATH_BIAS_USE_CLOSE_COUNTS 1
1221 if (options
->PathBiasUseCloseCounts
>= 0)
1222 return options
->PathBiasUseCloseCounts
;
1224 return networkstatus_get_param(NULL
, "pb_useclosecounts",
1225 DFLT_PATH_BIAS_USE_CLOSE_COUNTS
, 0, 1);
1229 * Convert a Guard's path state to string.
1232 pathbias_state_to_string(path_state_t state
)
1235 case PATH_STATE_NEW_CIRC
:
1237 case PATH_STATE_BUILD_ATTEMPTED
:
1238 return "build attempted";
1239 case PATH_STATE_BUILD_SUCCEEDED
:
1240 return "build succeeded";
1241 case PATH_STATE_USE_SUCCEEDED
:
1242 return "use succeeded";
1243 case PATH_STATE_USE_FAILED
:
1244 return "use failed";
1251 * This function decides if a circuit has progressed far enough to count
1252 * as a circuit "attempt". As long as end-to-end tagging is possible,
1253 * we assume the adversary will use it over hop-to-hop failure. Therefore,
1254 * we only need to account bias for the last hop. This should make us
1255 * much more resilient to ambient circuit failure, and also make that
1256 * failure easier to measure (we only need to measure Exit failure rates).
1259 pathbias_is_new_circ_attempt(origin_circuit_t
*circ
)
1261 #define N2N_TAGGING_IS_POSSIBLE
1262 #ifdef N2N_TAGGING_IS_POSSIBLE
1263 /* cpath is a circular list. We want circs with more than one hop,
1264 * and the second hop must be waiting for keys still (it's just
1265 * about to get them). */
1266 return circ
->cpath
->next
!= circ
->cpath
&&
1267 circ
->cpath
->next
->state
== CPATH_STATE_AWAITING_KEYS
;
1269 /* If tagging attacks are no longer possible, we probably want to
1270 * count bias from the first hop. However, one could argue that
1271 * timing-based tagging is still more useful than per-hop failure.
1272 * In which case, we'd never want to use this.
1274 return circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
;
1279 * Decide if the path bias code should count a circuit.
1281 * @returns 1 if we should count it, 0 otherwise.
1284 pathbias_should_count(origin_circuit_t
*circ
)
1286 #define PATHBIAS_COUNT_INTERVAL (600)
1287 static ratelim_t count_limit
=
1288 RATELIM_INIT(PATHBIAS_COUNT_INTERVAL
);
1289 char *rate_msg
= NULL
;
1291 /* We can't do path bias accounting without entry guards.
1292 * Testing and controller circuits also have no guards.
1294 * We also don't count server-side rends, because their
1295 * endpoint could be chosen maliciously.
1296 * Similarly, we can't count client-side intro attempts,
1297 * because clients can be manipulated into connecting to
1298 * malicious intro points. */
1299 if (get_options()->UseEntryGuards
== 0 ||
1300 circ
->base_
.purpose
== CIRCUIT_PURPOSE_TESTING
||
1301 circ
->base_
.purpose
== CIRCUIT_PURPOSE_CONTROLLER
||
1302 circ
->base_
.purpose
== CIRCUIT_PURPOSE_S_CONNECT_REND
||
1303 circ
->base_
.purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
||
1304 (circ
->base_
.purpose
>= CIRCUIT_PURPOSE_C_INTRODUCING
&&
1305 circ
->base_
.purpose
<= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
)) {
1309 /* Completely ignore one hop circuits */
1310 if (circ
->build_state
->onehop_tunnel
||
1311 circ
->build_state
->desired_path_len
== 1) {
1312 /* Check for inconsistency */
1313 if (circ
->build_state
->desired_path_len
!= 1 ||
1314 !circ
->build_state
->onehop_tunnel
) {
1315 if ((rate_msg
= rate_limit_log(&count_limit
, approx_time()))) {
1317 "One-hop circuit has length %d. Path state is %s. "
1318 "Circuit is a %s currently %s.%s",
1319 circ
->build_state
->desired_path_len
,
1320 pathbias_state_to_string(circ
->path_state
),
1321 circuit_purpose_to_string(circ
->base_
.purpose
),
1322 circuit_state_to_string(circ
->base_
.state
),
1326 tor_fragile_assert();
1335 * Check our circuit state to see if this is a successful circuit attempt.
1336 * If so, record it in the current guard's path bias circ_attempt count.
1338 * Also check for several potential error cases for bug #6475.
1341 pathbias_count_circ_attempt(origin_circuit_t
*circ
)
1343 #define CIRC_ATTEMPT_NOTICE_INTERVAL (600)
1344 static ratelim_t circ_attempt_notice_limit
=
1345 RATELIM_INIT(CIRC_ATTEMPT_NOTICE_INTERVAL
);
1346 char *rate_msg
= NULL
;
1348 if (!pathbias_should_count(circ
)) {
1352 if (pathbias_is_new_circ_attempt(circ
)) {
1353 /* Help track down the real cause of bug #6475: */
1354 if (circ
->has_opened
&& circ
->path_state
!= PATH_STATE_BUILD_ATTEMPTED
) {
1355 if ((rate_msg
= rate_limit_log(&circ_attempt_notice_limit
,
1358 "Opened circuit is in strange path state %s. "
1359 "Circuit is a %s currently %s.%s",
1360 pathbias_state_to_string(circ
->path_state
),
1361 circuit_purpose_to_string(circ
->base_
.purpose
),
1362 circuit_state_to_string(circ
->base_
.state
),
1368 /* Don't re-count cannibalized circs.. */
1369 if (!circ
->has_opened
) {
1370 entry_guard_t
*guard
= NULL
;
1372 if (circ
->cpath
&& circ
->cpath
->extend_info
) {
1373 guard
= entry_guard_get_by_id_digest(
1374 circ
->cpath
->extend_info
->identity_digest
);
1375 } else if (circ
->base_
.n_chan
) {
1377 entry_guard_get_by_id_digest(circ
->base_
.n_chan
->identity_digest
);
1381 if (circ
->path_state
== PATH_STATE_NEW_CIRC
) {
1382 circ
->path_state
= PATH_STATE_BUILD_ATTEMPTED
;
1384 if (entry_guard_inc_circ_attempt_count(guard
) < 0) {
1385 /* Bogus guard; we already warned. */
1386 return -END_CIRC_REASON_TORPROTOCOL
;
1389 if ((rate_msg
= rate_limit_log(&circ_attempt_notice_limit
,
1392 "Unopened circuit has strange path state %s. "
1393 "Circuit is a %s currently %s.%s",
1394 pathbias_state_to_string(circ
->path_state
),
1395 circuit_purpose_to_string(circ
->base_
.purpose
),
1396 circuit_state_to_string(circ
->base_
.state
),
1402 if ((rate_msg
= rate_limit_log(&circ_attempt_notice_limit
,
1405 "Unopened circuit has no known guard. "
1406 "Circuit is a %s currently %s.%s",
1407 circuit_purpose_to_string(circ
->base_
.purpose
),
1408 circuit_state_to_string(circ
->base_
.state
),
1420 * Check our circuit state to see if this is a successful circuit
1421 * completion. If so, record it in the current guard's path bias
1424 * Also check for several potential error cases for bug #6475.
1427 pathbias_count_build_success(origin_circuit_t
*circ
)
1429 #define SUCCESS_NOTICE_INTERVAL (600)
1430 static ratelim_t success_notice_limit
=
1431 RATELIM_INIT(SUCCESS_NOTICE_INTERVAL
);
1432 char *rate_msg
= NULL
;
1433 entry_guard_t
*guard
= NULL
;
1435 if (!pathbias_should_count(circ
)) {
1439 /* Don't count cannibalized/reused circs for path bias
1440 * "build" success, since they get counted under "use" success. */
1441 if (!circ
->has_opened
) {
1442 if (circ
->cpath
&& circ
->cpath
->extend_info
) {
1443 guard
= entry_guard_get_by_id_digest(
1444 circ
->cpath
->extend_info
->identity_digest
);
1448 if (circ
->path_state
== PATH_STATE_BUILD_ATTEMPTED
) {
1449 circ
->path_state
= PATH_STATE_BUILD_SUCCEEDED
;
1450 guard
->circ_successes
++;
1452 log_info(LD_CIRC
, "Got success count %f/%f for guard %s=%s",
1453 guard
->circ_successes
, guard
->circ_attempts
,
1454 guard
->nickname
, hex_str(guard
->identity
, DIGEST_LEN
));
1456 if ((rate_msg
= rate_limit_log(&success_notice_limit
,
1459 "Succeeded circuit is in strange path state %s. "
1460 "Circuit is a %s currently %s.%s",
1461 pathbias_state_to_string(circ
->path_state
),
1462 circuit_purpose_to_string(circ
->base_
.purpose
),
1463 circuit_state_to_string(circ
->base_
.state
),
1469 if (guard
->circ_attempts
< guard
->circ_successes
) {
1470 log_notice(LD_BUG
, "Unexpectedly high successes counts (%f/%f) "
1472 guard
->circ_successes
, guard
->circ_attempts
,
1473 guard
->nickname
, hex_str(guard
->identity
, DIGEST_LEN
));
1475 /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
1476 * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
1477 * No need to log that case. */
1478 } else if (circ
->base_
.purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
1479 if ((rate_msg
= rate_limit_log(&success_notice_limit
,
1482 "Completed circuit has no known guard. "
1483 "Circuit is a %s currently %s.%s",
1484 circuit_purpose_to_string(circ
->base_
.purpose
),
1485 circuit_state_to_string(circ
->base_
.state
),
1491 if (circ
->path_state
< PATH_STATE_BUILD_SUCCEEDED
) {
1492 if ((rate_msg
= rate_limit_log(&success_notice_limit
,
1495 "Opened circuit is in strange path state %s. "
1496 "Circuit is a %s currently %s.%s",
1497 pathbias_state_to_string(circ
->path_state
),
1498 circuit_purpose_to_string(circ
->base_
.purpose
),
1499 circuit_state_to_string(circ
->base_
.state
),
1508 * Send a probe down a circuit that the client attempted to use,
1509 * but for which the stream timed out/failed. The probe is a
1510 * RELAY_BEGIN cell with a 0.a.b.c destination address, which
1511 * the exit will reject and reply back, echoing that address.
1513 * The reason for such probes is because it is possible to bias
1514 * a user's paths simply by causing timeouts, and these timeouts
1515 * are not possible to differentiate from unresponsive servers.
1517 * The probe is sent at the end of the circuit lifetime for two
1518 * reasons: to prevent cryptographic taggers from being able to
1519 * drop cells to cause timeouts, and to prevent easy recognition
1520 * of probes before any real client traffic happens.
1522 * Returns -1 if we couldn't probe, 0 otherwise.
1525 pathbias_send_usable_probe(circuit_t
*circ
)
1527 /* Based on connection_ap_handshake_send_begin() */
1528 char payload
[CELL_PAYLOAD_SIZE
];
1530 origin_circuit_t
*ocirc
= TO_ORIGIN_CIRCUIT(circ
);
1531 crypt_path_t
*cpath_layer
= NULL
;
1532 char *probe_nonce
= NULL
;
1536 cpath_layer
= ocirc
->cpath
->prev
;
1538 if (cpath_layer
->state
!= CPATH_STATE_OPEN
) {
1539 /* This can happen for cannibalized circuits. Their
1540 * last hop isn't yet open */
1542 "Got pathbias probe request for unopened circuit %d. "
1543 "Opened %d, len %d", ocirc
->global_identifier
,
1544 ocirc
->has_opened
, ocirc
->build_state
->desired_path_len
);
1548 /* We already went down this road. */
1549 if (circ
->purpose
== CIRCUIT_PURPOSE_PATH_BIAS_TESTING
&&
1550 ocirc
->pathbias_probe_id
) {
1552 "Got pathbias probe request for circuit %d with "
1553 "outstanding probe", ocirc
->global_identifier
);
1557 circuit_change_purpose(circ
, CIRCUIT_PURPOSE_PATH_BIAS_TESTING
);
1559 /* Update timestamp for when circuit_expire_building() should kill us */
1560 tor_gettimeofday(&circ
->timestamp_began
);
1562 /* Generate a random address for the nonce */
1563 crypto_rand((char*)ô
->pathbias_probe_nonce
,
1564 sizeof(ocirc
->pathbias_probe_nonce
));
1565 ocirc
->pathbias_probe_nonce
&= 0x00ffffff;
1566 probe_nonce
= tor_dup_ip(ocirc
->pathbias_probe_nonce
);
1568 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:25", probe_nonce
);
1569 payload_len
= (int)strlen(payload
)+1;
1571 // XXX: need this? Can we assume ipv4 will always be supported?
1572 // If not, how do we tell?
1573 //if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
1574 // set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
1575 // payload_len += 4;
1578 /* Generate+Store stream id, make sure it's non-zero */
1579 ocirc
->pathbias_probe_id
= get_unique_stream_id_by_circ(ocirc
);
1581 if (ocirc
->pathbias_probe_id
==0) {
1583 "Ran out of stream IDs on circuit %u during "
1584 "pathbias probe attempt.", ocirc
->global_identifier
);
1585 tor_free(probe_nonce
);
1590 "Sending pathbias testing cell to %s:25 on stream %d for circ %d.",
1591 probe_nonce
, ocirc
->pathbias_probe_id
, ocirc
->global_identifier
);
1592 tor_free(probe_nonce
);
1594 /* Send a test relay cell */
1595 if (relay_send_command_from_edge(ocirc
->pathbias_probe_id
, circ
,
1596 RELAY_COMMAND_BEGIN
, payload
,
1597 payload_len
, cpath_layer
) < 0) {
1599 "Failed to send pathbias probe cell on circuit %d.",
1600 ocirc
->global_identifier
);
1604 /* Mark it freshly dirty so it doesn't get expired in the meantime */
1605 circ
->timestamp_dirty
= time(NULL
);
1611 * Check the response to a pathbias probe, to ensure the
1612 * cell is recognized and the nonce and other probe
1613 * characteristics are as expected.
1615 * If the response is valid, return 0. Otherwise return < 0.
1618 pathbias_check_probe_response(circuit_t
*circ
, const cell_t
*cell
)
1620 /* Based on connection_edge_process_relay_cell() */
1624 origin_circuit_t
*ocirc
= TO_ORIGIN_CIRCUIT(circ
);
1628 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_PATH_BIAS_TESTING
);
1630 relay_header_unpack(&rh
, cell
->payload
);
1632 reason
= rh
.length
> 0 ?
1633 get_uint8(cell
->payload
+RELAY_HEADER_SIZE
) : END_STREAM_REASON_MISC
;
1635 if (rh
.command
== RELAY_COMMAND_END
&&
1636 reason
== END_STREAM_REASON_EXITPOLICY
&&
1637 ocirc
->pathbias_probe_id
== rh
.stream_id
) {
1639 /* Check length+extract host: It is in network order after the reason code.
1640 * See connection_edge_end(). */
1641 if (rh
.length
< 9) { /* reason+ipv4+dns_ttl */
1642 log_notice(LD_PROTOCOL
,
1643 "Short path bias probe response length field (%d).", rh
.length
);
1644 return - END_CIRC_REASON_TORPROTOCOL
;
1647 ipv4_host
= ntohl(get_uint32(cell
->payload
+RELAY_HEADER_SIZE
+1));
1650 if (ipv4_host
== ocirc
->pathbias_probe_nonce
) {
1651 ocirc
->path_state
= PATH_STATE_USE_SUCCEEDED
;
1652 circuit_mark_for_close(circ
, END_CIRC_REASON_FINISHED
);
1654 "Got valid path bias probe back for circ %d, stream %d.",
1655 ocirc
->global_identifier
, ocirc
->pathbias_probe_id
);
1659 "Got strange probe value 0x%x vs 0x%x back for circ %d, "
1660 "stream %d.", ipv4_host
, ocirc
->pathbias_probe_nonce
,
1661 ocirc
->global_identifier
, ocirc
->pathbias_probe_id
);
1666 "Got another cell back back on pathbias probe circuit %d: "
1667 "Command: %d, Reason: %d, Stream-id: %d",
1668 ocirc
->global_identifier
, rh
.command
, reason
, rh
.stream_id
);
1673 * Check if a circuit was used and/or closed successfully.
1675 * If we attempted to use the circuit to carry a stream but failed
1676 * for whatever reason, or if the circuit mysteriously died before
1677 * we could attach any streams, record these two cases.
1679 * If we *have* successfully used the circuit, or it appears to
1680 * have been closed by us locally, count it as a success.
1682 * Returns 0 if we're done making decisions with the circ,
1683 * or -1 if we want to probe it first.
1686 pathbias_check_close(origin_circuit_t
*ocirc
, int reason
)
1688 circuit_t
*circ
= ô
->base_
;
1690 if (!pathbias_should_count(ocirc
)) {
1694 if (ocirc
->path_state
== PATH_STATE_BUILD_SUCCEEDED
) {
1695 if (circ
->timestamp_dirty
) {
1696 if (pathbias_send_usable_probe(circ
) == 0)
1699 pathbias_count_unusable(ocirc
);
1701 /* Any circuit where there were attempted streams but no successful
1702 * streams could be bias */
1704 "Circuit %d closed without successful use for reason %d. "
1705 "Circuit purpose %d currently %d,%s. Len %d.",
1706 ocirc
->global_identifier
,
1707 reason
, circ
->purpose
, ocirc
->has_opened
,
1708 circuit_state_to_string(circ
->state
),
1709 ocirc
->build_state
->desired_path_len
);
1712 if (reason
& END_CIRC_REASON_FLAG_REMOTE
) {
1713 /* Remote circ close reasons on an unused circuit all could be bias */
1715 "Circuit %d remote-closed without successful use for reason %d. "
1716 "Circuit purpose %d currently %d,%s. Len %d.",
1717 ocirc
->global_identifier
,
1718 reason
, circ
->purpose
, ocirc
->has_opened
,
1719 circuit_state_to_string(circ
->state
),
1720 ocirc
->build_state
->desired_path_len
);
1721 pathbias_count_collapse(ocirc
);
1722 } else if ((reason
& ~END_CIRC_REASON_FLAG_REMOTE
)
1723 == END_CIRC_REASON_CHANNEL_CLOSED
&&
1725 circ
->n_chan
->reason_for_closing
1726 != CHANNEL_CLOSE_REQUESTED
) {
1727 /* If we didn't close the channel ourselves, it could be bias */
1728 /* XXX: Only count bias if the network is live?
1729 * What about clock jumps/suspends? */
1731 "Circuit %d's channel closed without successful use for reason "
1732 "%d, channel reason %d. Circuit purpose %d currently %d,%s. Len "
1733 "%d.", ocirc
->global_identifier
,
1734 reason
, circ
->n_chan
->reason_for_closing
,
1735 circ
->purpose
, ocirc
->has_opened
,
1736 circuit_state_to_string(circ
->state
),
1737 ocirc
->build_state
->desired_path_len
);
1738 pathbias_count_collapse(ocirc
);
1740 pathbias_count_successful_close(ocirc
);
1743 } else if (ocirc
->path_state
== PATH_STATE_USE_SUCCEEDED
) {
1744 pathbias_count_successful_close(ocirc
);
1751 * Count a successfully closed circuit.
1754 pathbias_count_successful_close(origin_circuit_t
*circ
)
1756 entry_guard_t
*guard
= NULL
;
1757 if (!pathbias_should_count(circ
)) {
1761 if (circ
->cpath
&& circ
->cpath
->extend_info
) {
1762 guard
= entry_guard_get_by_id_digest(
1763 circ
->cpath
->extend_info
->identity_digest
);
1767 /* In the long run: circuit_success ~= successful_circuit_close +
1768 * circ_failure + stream_failure */
1769 guard
->successful_circuits_closed
++;
1770 entry_guards_changed();
1771 } else if (circ
->base_
.purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
1772 /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
1773 * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
1774 * No need to log that case. */
1776 "Successfully closed circuit has no known guard. "
1777 "Circuit is a %s currently %s",
1778 circuit_purpose_to_string(circ
->base_
.purpose
),
1779 circuit_state_to_string(circ
->base_
.state
));
1784 * Count a circuit that fails after it is built, but before it can
1785 * carry any traffic.
1787 * This is needed because there are ways to destroy a
1788 * circuit after it has successfully completed. Right now, this is
1789 * used for purely informational/debugging purposes.
1792 pathbias_count_collapse(origin_circuit_t
*circ
)
1794 entry_guard_t
*guard
= NULL
;
1795 if (!pathbias_should_count(circ
)) {
1799 if (circ
->cpath
&& circ
->cpath
->extend_info
) {
1800 guard
= entry_guard_get_by_id_digest(
1801 circ
->cpath
->extend_info
->identity_digest
);
1805 guard
->collapsed_circuits
++;
1806 entry_guards_changed();
1807 } else if (circ
->base_
.purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
1808 /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
1809 * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
1810 * No need to log that case. */
1812 "Destroyed circuit has no known guard. "
1813 "Circuit is a %s currently %s",
1814 circuit_purpose_to_string(circ
->base_
.purpose
),
1815 circuit_state_to_string(circ
->base_
.state
));
1820 pathbias_count_unusable(origin_circuit_t
*circ
)
1822 entry_guard_t
*guard
= NULL
;
1823 if (!pathbias_should_count(circ
)) {
1827 if (circ
->cpath
&& circ
->cpath
->extend_info
) {
1828 guard
= entry_guard_get_by_id_digest(
1829 circ
->cpath
->extend_info
->identity_digest
);
1833 guard
->unusable_circuits
++;
1834 entry_guards_changed();
1835 } else if (circ
->base_
.purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
) {
1836 /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
1837 * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
1838 * No need to log that case. */
1839 /* XXX note cut-and-paste code in this function compared to nearby
1840 * functions. Would be nice to refactor. -RD */
1842 "Stream-failing circuit has no known guard. "
1843 "Circuit is a %s currently %s",
1844 circuit_purpose_to_string(circ
->base_
.purpose
),
1845 circuit_state_to_string(circ
->base_
.state
));
1850 * Count timeouts for path bias log messages.
1852 * These counts are purely informational.
1855 pathbias_count_timeout(origin_circuit_t
*circ
)
1857 entry_guard_t
*guard
= NULL
;
1859 if (!pathbias_should_count(circ
)) {
1863 /* For hidden service circs, they can actually be used
1864 * successfully and then time out later (because
1865 * the other side declines to use them). */
1866 if (circ
->path_state
== PATH_STATE_USE_SUCCEEDED
) {
1870 if (circ
->cpath
&& circ
->cpath
->extend_info
) {
1871 guard
= entry_guard_get_by_id_digest(
1872 circ
->cpath
->extend_info
->identity_digest
);
1877 entry_guards_changed();
1882 * Return the number of circuits counted as successfully closed for
1885 * Also add in the currently open circuits to give them the benefit
1889 pathbias_get_closed_count(entry_guard_t
*guard
)
1892 int open_circuits
= 0;
1894 /* Count currently open circuits. Give them the benefit of the doubt. */
1895 for (circ
= global_circuitlist
; circ
; circ
= circ
->next
) {
1896 origin_circuit_t
*ocirc
= NULL
;
1897 if (!CIRCUIT_IS_ORIGIN(circ
) || /* didn't originate here */
1898 circ
->marked_for_close
) /* already counted */
1901 ocirc
= TO_ORIGIN_CIRCUIT(circ
);
1903 if (!ocirc
->cpath
|| !ocirc
->cpath
->extend_info
)
1906 if (ocirc
->path_state
>= PATH_STATE_BUILD_SUCCEEDED
&&
1907 fast_memeq(guard
->identity
,
1908 ocirc
->cpath
->extend_info
->identity_digest
,
1914 return guard
->successful_circuits_closed
+ open_circuits
;
1918 * This function checks the consensus parameters to decide
1919 * if it should return guard->circ_successes or
1920 * guard->successful_circuits_closed.
1923 pathbias_get_success_count(entry_guard_t
*guard
)
1925 if (pathbias_use_close_counts(get_options())) {
1926 return pathbias_get_closed_count(guard
);
1928 return guard
->circ_successes
;
1932 /** Increment the number of times we successfully extended a circuit to
1933 * <b>guard</b>, first checking if the failure rate is high enough that
1934 * we should eliminate the guard. Return -1 if the guard looks no good;
1935 * return 0 if the guard looks fine.
1938 entry_guard_inc_circ_attempt_count(entry_guard_t
*guard
)
1940 const or_options_t
*options
= get_options();
1942 entry_guards_changed();
1944 if (guard
->circ_attempts
> pathbias_get_min_circs(options
)) {
1945 /* Note: We rely on the < comparison here to allow us to set a 0
1946 * rate and disable the feature entirely. If refactoring, don't
1948 if (pathbias_get_success_count(guard
)/guard
->circ_attempts
1949 < pathbias_get_extreme_rate(options
)) {
1950 /* Dropping is currently disabled by default. */
1951 if (pathbias_get_dropguards(options
)) {
1952 if (!guard
->path_bias_disabled
) {
1954 "Your Guard %s=%s is failing an extremely large amount of "
1955 "circuits. To avoid potential route manipulation attacks, "
1956 "Tor has disabled use of this guard. "
1957 "Success counts are %ld/%ld. %ld circuits completed, %ld "
1958 "were unusable, %ld collapsed, and %ld timed out. For "
1959 "reference, your timeout cutoff is %ld seconds.",
1960 guard
->nickname
, hex_str(guard
->identity
, DIGEST_LEN
),
1961 tor_lround(pathbias_get_closed_count(guard
)),
1962 tor_lround(guard
->circ_attempts
),
1963 tor_lround(guard
->circ_successes
),
1964 tor_lround(guard
->unusable_circuits
),
1965 tor_lround(guard
->collapsed_circuits
),
1966 tor_lround(guard
->timeouts
),
1967 tor_lround(circ_times
.close_ms
/1000));
1968 guard
->path_bias_disabled
= 1;
1969 guard
->bad_since
= approx_time();
1972 } else if (!guard
->path_bias_extreme
) {
1973 guard
->path_bias_extreme
= 1;
1975 "Your Guard %s=%s is failing an extremely large amount of "
1976 "circuits. This could indicate a route manipulation attack, "
1977 "extreme network overload, or a bug. "
1978 "Success counts are %ld/%ld. %ld circuits completed, %ld "
1979 "were unusable, %ld collapsed, and %ld timed out. For "
1980 "reference, your timeout cutoff is %ld seconds.",
1981 guard
->nickname
, hex_str(guard
->identity
, DIGEST_LEN
),
1982 tor_lround(pathbias_get_closed_count(guard
)),
1983 tor_lround(guard
->circ_attempts
),
1984 tor_lround(guard
->circ_successes
),
1985 tor_lround(guard
->unusable_circuits
),
1986 tor_lround(guard
->collapsed_circuits
),
1987 tor_lround(guard
->timeouts
),
1988 tor_lround(circ_times
.close_ms
/1000));
1990 } else if (pathbias_get_success_count(guard
)/((double)guard
->circ_attempts
)
1991 < pathbias_get_warn_rate(options
)) {
1992 if (!guard
->path_bias_warned
) {
1993 guard
->path_bias_warned
= 1;
1995 "Your Guard %s=%s is failing a very large amount of "
1996 "circuits. Most likely this means the Tor network is "
1997 "overloaded, but it could also mean an attack against "
1998 "you or potentially the guard itself. "
1999 "Success counts are %ld/%ld. %ld circuits completed, %ld "
2000 "were unusable, %ld collapsed, and %ld timed out. For "
2001 "reference, your timeout cutoff is %ld seconds.",
2002 guard
->nickname
, hex_str(guard
->identity
, DIGEST_LEN
),
2003 tor_lround(pathbias_get_closed_count(guard
)),
2004 tor_lround(guard
->circ_attempts
),
2005 tor_lround(guard
->circ_successes
),
2006 tor_lround(guard
->unusable_circuits
),
2007 tor_lround(guard
->collapsed_circuits
),
2008 tor_lround(guard
->timeouts
),
2009 tor_lround(circ_times
.close_ms
/1000));
2011 } else if (pathbias_get_success_count(guard
)/((double)guard
->circ_attempts
)
2012 < pathbias_get_notice_rate(options
)) {
2013 if (!guard
->path_bias_noticed
) {
2014 guard
->path_bias_noticed
= 1;
2016 "Your Guard %s=%s is failing more circuits than usual. "
2017 "Most likely this means the Tor network is overloaded. "
2018 "Success counts are %ld/%ld. %ld circuits completed, %ld "
2019 "were unusable, %ld collapsed, and %ld timed out. For "
2020 "reference, your timeout cutoff is %ld seconds.",
2021 guard
->nickname
, hex_str(guard
->identity
, DIGEST_LEN
),
2022 tor_lround(pathbias_get_closed_count(guard
)),
2023 tor_lround(guard
->circ_attempts
),
2024 tor_lround(guard
->circ_successes
),
2025 tor_lround(guard
->unusable_circuits
),
2026 tor_lround(guard
->collapsed_circuits
),
2027 tor_lround(guard
->timeouts
),
2028 tor_lround(circ_times
.close_ms
/1000));
2033 /* If we get a ton of circuits, just scale everything down */
2034 if (guard
->circ_attempts
> pathbias_get_scale_threshold(options
)) {
2035 const int scale_factor
= pathbias_get_scale_factor(options
);
2036 const int mult_factor
= pathbias_get_mult_factor(options
);
2038 "Scaling pathbias counts to (%f/%f)*(%d/%d) for guard %s=%s",
2039 guard
->circ_successes
, guard
->circ_attempts
,
2040 mult_factor
, scale_factor
, guard
->nickname
,
2041 hex_str(guard
->identity
, DIGEST_LEN
));
2043 guard
->circ_attempts
*= mult_factor
;
2044 guard
->circ_successes
*= mult_factor
;
2045 guard
->timeouts
*= mult_factor
;
2046 guard
->successful_circuits_closed
*= mult_factor
;
2047 guard
->collapsed_circuits
*= mult_factor
;
2048 guard
->unusable_circuits
*= mult_factor
;
2050 guard
->circ_attempts
/= scale_factor
;
2051 guard
->circ_successes
/= scale_factor
;
2052 guard
->timeouts
/= scale_factor
;
2053 guard
->successful_circuits_closed
/= scale_factor
;
2054 guard
->collapsed_circuits
/= scale_factor
;
2055 guard
->unusable_circuits
/= scale_factor
;
2057 guard
->circ_attempts
++;
2058 log_info(LD_CIRC
, "Got success count %f/%f for guard %s=%s",
2059 guard
->circ_successes
, guard
->circ_attempts
, guard
->nickname
,
2060 hex_str(guard
->identity
, DIGEST_LEN
));
2064 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
2065 * (The body of <b>reply</b> varies depending on what sort of handshake
2068 * Calculate the appropriate keys and digests, make sure KH is
2069 * correct, and initialize this hop of the cpath.
2071 * Return - reason if we want to mark circ for close, else return 0.
2074 circuit_finish_handshake(origin_circuit_t
*circ
,
2075 const created_cell_t
*reply
)
2077 char keys
[CPATH_KEY_MATERIAL_LEN
];
2081 if ((rv
= pathbias_count_circ_attempt(circ
)) < 0)
2084 if (circ
->cpath
->state
== CPATH_STATE_AWAITING_KEYS
) {
2087 hop
= onion_next_hop_in_cpath(circ
->cpath
);
2088 if (!hop
) { /* got an extended when we're all done? */
2089 log_warn(LD_PROTOCOL
,"got extended when circ already built? Closing.");
2090 return - END_CIRC_REASON_TORPROTOCOL
;
2093 tor_assert(hop
->state
== CPATH_STATE_AWAITING_KEYS
);
2096 if (onion_skin_client_handshake(hop
->handshake_state
.tag
,
2097 &hop
->handshake_state
,
2098 reply
->reply
, reply
->handshake_len
,
2099 (uint8_t*)keys
, sizeof(keys
),
2100 (uint8_t*)hop
->rend_circ_nonce
) < 0) {
2101 log_warn(LD_CIRC
,"onion_skin_client_handshake failed.");
2102 return -END_CIRC_REASON_TORPROTOCOL
;
2106 onion_handshake_state_release(&hop
->handshake_state
);
2108 if (circuit_init_cpath_crypto(hop
, keys
, 0)<0) {
2109 return -END_CIRC_REASON_TORPROTOCOL
;
2112 hop
->state
= CPATH_STATE_OPEN
;
2113 log_info(LD_CIRC
,"Finished building circuit hop:");
2114 circuit_log_path(LOG_INFO
,LD_CIRC
,circ
);
2115 control_event_circuit_status(circ
, CIRC_EVENT_EXTENDED
, 0);
2120 /** We received a relay truncated cell on circ.
2122 * Since we don't send truncates currently, getting a truncated
2123 * means that a connection broke or an extend failed. For now,
2124 * just give up: force circ to close, and return 0.
2127 circuit_truncated(origin_circuit_t
*circ
, crypt_path_t
*layer
, int reason
)
2129 // crypt_path_t *victim;
2130 // connection_t *stream;
2135 /* XXX Since we don't send truncates currently, getting a truncated
2136 * means that a connection broke or an extend failed. For now,
2139 circuit_mark_for_close(TO_CIRCUIT(circ
),
2140 END_CIRC_REASON_FLAG_REMOTE
|reason
);
2144 while (layer
->next
!= circ
->cpath
) {
2145 /* we need to clear out layer->next */
2146 victim
= layer
->next
;
2147 log_debug(LD_CIRC
, "Killing a layer of the cpath.");
2149 for (stream
= circ
->p_streams
; stream
; stream
=stream
->next_stream
) {
2150 if (stream
->cpath_layer
== victim
) {
2151 log_info(LD_APP
, "Marking stream %d for close because of truncate.",
2153 /* no need to send 'end' relay cells,
2154 * because the other side's already dead
2156 connection_mark_unattached_ap(stream
, END_STREAM_REASON_DESTROY
);
2160 layer
->next
= victim
->next
;
2161 circuit_free_cpath_node(victim
);
2164 log_info(LD_CIRC
, "finished");
2169 /** Given a response payload and keys, initialize, then send a created
2173 onionskin_answer(or_circuit_t
*circ
,
2174 const created_cell_t
*created_cell
,
2176 const uint8_t *rend_circ_nonce
)
2179 crypt_path_t
*tmp_cpath
;
2181 if (created_cell_format(&cell
, created_cell
) < 0) {
2182 log_warn(LD_BUG
,"couldn't format created cell (type=%d, len=%d)",
2183 (int)created_cell
->cell_type
, (int)created_cell
->handshake_len
);
2186 cell
.circ_id
= circ
->p_circ_id
;
2188 tmp_cpath
= tor_malloc_zero(sizeof(crypt_path_t
));
2189 tmp_cpath
->magic
= CRYPT_PATH_MAGIC
;
2191 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_OPEN
);
2193 log_debug(LD_CIRC
,"init digest forward 0x%.8x, backward 0x%.8x.",
2194 (unsigned int)get_uint32(keys
),
2195 (unsigned int)get_uint32(keys
+20));
2196 if (circuit_init_cpath_crypto(tmp_cpath
, keys
, 0)<0) {
2197 log_warn(LD_BUG
,"Circuit initialization failed");
2198 tor_free(tmp_cpath
);
2201 circ
->n_digest
= tmp_cpath
->f_digest
;
2202 circ
->n_crypto
= tmp_cpath
->f_crypto
;
2203 circ
->p_digest
= tmp_cpath
->b_digest
;
2204 circ
->p_crypto
= tmp_cpath
->b_crypto
;
2205 tmp_cpath
->magic
= 0;
2206 tor_free(tmp_cpath
);
2208 memcpy(circ
->rend_circ_nonce
, rend_circ_nonce
, DIGEST_LEN
);
2210 circ
->is_first_hop
= (created_cell
->cell_type
== CELL_CREATED_FAST
);
2212 append_cell_to_circuit_queue(TO_CIRCUIT(circ
),
2213 circ
->p_chan
, &cell
, CELL_DIRECTION_IN
, 0);
2214 log_debug(LD_CIRC
,"Finished sending '%s' cell.",
2215 circ
->is_first_hop
? "created_fast" : "created");
2217 if (!channel_is_local(circ
->p_chan
) &&
2218 !channel_is_outgoing(circ
->p_chan
)) {
2219 /* record that we could process create cells from a non-local conn
2220 * that we didn't initiate; presumably this means that create cells
2221 * can reach us too. */
2222 router_orport_found_reachable();
2228 /** Choose a length for a circuit of purpose <b>purpose</b>: three + the
2229 * number of endpoints that would give something away about our destination.
2231 * If the routerlist <b>nodes</b> doesn't have enough routers
2232 * to handle the desired path length, return as large a path length as
2233 * is feasible, except if it's less than 2, in which case return -1.
2234 * XXX ^^ I think this behavior is a hold-over from back when we had only a
2235 * few relays in the network, and certainly back before guards existed.
2236 * We should very likely get rid of it. -RD
2239 new_route_len(uint8_t purpose
, extend_info_t
*exit
, smartlist_t
*nodes
)
2241 int num_acceptable_routers
;
2246 routelen
= DEFAULT_ROUTE_LEN
;
2248 purpose
!= CIRCUIT_PURPOSE_TESTING
&&
2249 purpose
!= CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
)
2252 num_acceptable_routers
= count_acceptable_nodes(nodes
);
2254 log_debug(LD_CIRC
,"Chosen route length %d (%d/%d routers suitable).",
2255 routelen
, num_acceptable_routers
, smartlist_len(nodes
));
2257 if (num_acceptable_routers
< 2) {
2259 "Not enough acceptable routers (%d). Discarding this circuit.",
2260 num_acceptable_routers
);
2264 if (num_acceptable_routers
< routelen
) {
2265 log_info(LD_CIRC
,"Not enough routers: cutting routelen from %d to %d.",
2266 routelen
, num_acceptable_routers
);
2267 routelen
= num_acceptable_routers
;
2273 /** Return a newly allocated list of uint16_t * for each predicted port not
2274 * handled by a current circuit. */
2275 static smartlist_t
*
2276 circuit_get_unhandled_ports(time_t now
)
2278 smartlist_t
*dest
= rep_hist_get_predicted_ports(now
);
2279 circuit_remove_handled_ports(dest
);
2283 /** Return 1 if we already have circuits present or on the way for
2284 * all anticipated ports. Return 0 if we should make more.
2286 * If we're returning 0, set need_uptime and need_capacity to
2287 * indicate any requirements that the unhandled ports have.
2290 circuit_all_predicted_ports_handled(time_t now
, int *need_uptime
,
2295 smartlist_t
*sl
= circuit_get_unhandled_ports(now
);
2296 smartlist_t
*LongLivedServices
= get_options()->LongLivedPorts
;
2297 tor_assert(need_uptime
);
2298 tor_assert(need_capacity
);
2299 // Always predict need_capacity
2301 enough
= (smartlist_len(sl
) == 0);
2302 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
2303 port
= smartlist_get(sl
, i
);
2304 if (smartlist_contains_int_as_string(LongLivedServices
, *port
))
2312 /** Return 1 if <b>node</b> can handle one or more of the ports in
2313 * <b>needed_ports</b>, else return 0.
2316 node_handles_some_port(const node_t
*node
, smartlist_t
*needed_ports
)
2321 for (i
= 0; i
< smartlist_len(needed_ports
); ++i
) {
2322 addr_policy_result_t r
;
2323 /* alignment issues aren't a worry for this dereference, since
2324 needed_ports is explicitly a smartlist of uint16_t's */
2325 port
= *(uint16_t *)smartlist_get(needed_ports
, i
);
2328 r
= compare_tor_addr_to_node_policy(NULL
, port
, node
);
2331 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
2337 /** Return true iff <b>conn</b> needs another general circuit to be
2340 ap_stream_wants_exit_attention(connection_t
*conn
)
2342 entry_connection_t
*entry
;
2343 if (conn
->type
!= CONN_TYPE_AP
)
2345 entry
= TO_ENTRY_CONN(conn
);
2347 if (conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
&&
2348 !conn
->marked_for_close
&&
2349 !(entry
->want_onehop
) && /* ignore one-hop streams */
2350 !(entry
->use_begindir
) && /* ignore targeted dir fetches */
2351 !(entry
->chosen_exit_name
) && /* ignore defined streams */
2352 !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn
)) &&
2353 !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn
), 0,
2354 MIN_CIRCUITS_HANDLING_STREAM
))
2359 /** Return a pointer to a suitable router to be the exit node for the
2360 * general-purpose circuit we're about to build.
2362 * Look through the connection array, and choose a router that maximizes
2363 * the number of pending streams that can exit from this router.
2365 * Return NULL if we can't find any suitable routers.
2367 static const node_t
*
2368 choose_good_exit_server_general(int need_uptime
, int need_capacity
)
2371 int n_pending_connections
= 0;
2372 smartlist_t
*connections
;
2373 int best_support
= -1;
2374 int n_best_support
=0;
2375 const or_options_t
*options
= get_options();
2376 const smartlist_t
*the_nodes
;
2377 const node_t
*node
=NULL
;
2379 connections
= get_connection_array();
2381 /* Count how many connections are waiting for a circuit to be built.
2382 * We use this for log messages now, but in the future we may depend on it.
2384 SMARTLIST_FOREACH(connections
, connection_t
*, conn
,
2386 if (ap_stream_wants_exit_attention(conn
))
2387 ++n_pending_connections
;
2389 // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
2390 // n_pending_connections);
2391 /* Now we count, for each of the routers in the directory, how many
2392 * of the pending connections could possibly exit from that
2393 * router (n_supported[i]). (We can't be sure about cases where we
2394 * don't know the IP address of the pending connection.)
2396 * -1 means "Don't use this router at all."
2398 the_nodes
= nodelist_get_list();
2399 n_supported
= tor_malloc(sizeof(int)*smartlist_len(the_nodes
));
2400 SMARTLIST_FOREACH_BEGIN(the_nodes
, const node_t
*, node
) {
2401 const int i
= node_sl_idx
;
2402 if (router_digest_is_me(node
->identity
)) {
2403 n_supported
[i
] = -1;
2404 // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
2405 /* XXX there's probably a reverse predecessor attack here, but
2406 * it's slow. should we take this out? -RD
2410 if (!node_has_descriptor(node
)) {
2411 n_supported
[i
] = -1;
2414 if (!node
->is_running
|| node
->is_bad_exit
) {
2415 n_supported
[i
] = -1;
2416 continue; /* skip routers that are known to be down or bad exits */
2418 if (node_get_purpose(node
) != ROUTER_PURPOSE_GENERAL
) {
2419 /* never pick a non-general node as a random exit. */
2420 n_supported
[i
] = -1;
2423 if (routerset_contains_node(options
->ExcludeExitNodesUnion_
, node
)) {
2424 n_supported
[i
] = -1;
2425 continue; /* user asked us not to use it, no matter what */
2427 if (options
->ExitNodes
&&
2428 !routerset_contains_node(options
->ExitNodes
, node
)) {
2429 n_supported
[i
] = -1;
2430 continue; /* not one of our chosen exit nodes */
2433 if (node_is_unreliable(node
, need_uptime
, need_capacity
, 0)) {
2434 n_supported
[i
] = -1;
2435 continue; /* skip routers that are not suitable. Don't worry if
2436 * this makes us reject all the possible routers: if so,
2437 * we'll retry later in this function with need_update and
2438 * need_capacity set to 0. */
2440 if (!(node
->is_valid
|| options
->AllowInvalid_
& ALLOW_INVALID_EXIT
)) {
2441 /* if it's invalid and we don't want it */
2442 n_supported
[i
] = -1;
2443 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
2444 // router->nickname, i);
2445 continue; /* skip invalid routers */
2447 if (options
->ExcludeSingleHopRelays
&&
2448 node_allows_single_hop_exits(node
)) {
2449 n_supported
[i
] = -1;
2452 if (node_exit_policy_rejects_all(node
)) {
2453 n_supported
[i
] = -1;
2454 // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
2455 // router->nickname, i);
2456 continue; /* skip routers that reject all */
2459 /* iterate over connections */
2460 SMARTLIST_FOREACH_BEGIN(connections
, connection_t
*, conn
) {
2461 if (!ap_stream_wants_exit_attention(conn
))
2462 continue; /* Skip everything but APs in CIRCUIT_WAIT */
2463 if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn
), node
)) {
2465 // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
2466 // router->nickname, i, n_supported[i]);
2468 // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
2469 // router->nickname, i);
2471 } SMARTLIST_FOREACH_END(conn
);
2472 if (n_pending_connections
> 0 && n_supported
[i
] == 0) {
2473 /* Leave best_support at -1 if that's where it is, so we can
2474 * distinguish it later. */
2477 if (n_supported
[i
] > best_support
) {
2478 /* If this router is better than previous ones, remember its index
2479 * and goodness, and start counting how many routers are this good. */
2480 best_support
= n_supported
[i
]; n_best_support
=1;
2481 // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
2482 // router->nickname);
2483 } else if (n_supported
[i
] == best_support
) {
2484 /* If this router is _as good_ as the best one, just increment the
2485 * count of equally good routers.*/
2488 } SMARTLIST_FOREACH_END(node
);
2490 "Found %d servers that might support %d/%d pending connections.",
2491 n_best_support
, best_support
>= 0 ? best_support
: 0,
2492 n_pending_connections
);
2494 /* If any routers definitely support any pending connections, choose one
2496 if (best_support
> 0) {
2497 smartlist_t
*supporting
= smartlist_new();
2499 SMARTLIST_FOREACH(the_nodes
, const node_t
*, node
, {
2500 if (n_supported
[node_sl_idx
] == best_support
)
2501 smartlist_add(supporting
, (void*)node
);
2504 node
= node_sl_choose_by_bandwidth(supporting
, WEIGHT_FOR_EXIT
);
2505 smartlist_free(supporting
);
2507 /* Either there are no pending connections, or no routers even seem to
2508 * possibly support any of them. Choose a router at random that satisfies
2509 * at least one predicted exit port. */
2512 smartlist_t
*needed_ports
, *supporting
;
2514 if (best_support
== -1) {
2515 if (need_uptime
|| need_capacity
) {
2517 "We couldn't find any live%s%s routers; falling back "
2518 "to list of all routers.",
2519 need_capacity
?", fast":"",
2520 need_uptime
?", stable":"");
2521 tor_free(n_supported
);
2522 return choose_good_exit_server_general(0, 0);
2524 log_notice(LD_CIRC
, "All routers are down or won't exit%s -- "
2525 "choosing a doomed exit at random.",
2526 options
->ExcludeExitNodesUnion_
? " or are Excluded" : "");
2528 supporting
= smartlist_new();
2529 needed_ports
= circuit_get_unhandled_ports(time(NULL
));
2530 for (attempt
= 0; attempt
< 2; attempt
++) {
2531 /* try once to pick only from routers that satisfy a needed port,
2532 * then if there are none, pick from any that support exiting. */
2533 SMARTLIST_FOREACH_BEGIN(the_nodes
, const node_t
*, node
) {
2534 if (n_supported
[node_sl_idx
] != -1 &&
2535 (attempt
|| node_handles_some_port(node
, needed_ports
))) {
2536 // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
2537 // try, router->nickname);
2538 smartlist_add(supporting
, (void*)node
);
2540 } SMARTLIST_FOREACH_END(node
);
2542 node
= node_sl_choose_by_bandwidth(supporting
, WEIGHT_FOR_EXIT
);
2545 smartlist_clear(supporting
);
2546 /* If we reach this point, we can't actually support any unhandled
2547 * predicted ports, so clear all the remaining ones. */
2548 if (smartlist_len(needed_ports
))
2549 rep_hist_remove_predicted_ports(needed_ports
);
2551 SMARTLIST_FOREACH(needed_ports
, uint16_t *, cp
, tor_free(cp
));
2552 smartlist_free(needed_ports
);
2553 smartlist_free(supporting
);
2556 tor_free(n_supported
);
2558 log_info(LD_CIRC
, "Chose exit server '%s'", node_describe(node
));
2561 if (options
->ExitNodes
) {
2563 "No specified %sexit routers seem to be running: "
2564 "can't choose an exit.",
2565 options
->ExcludeExitNodesUnion_
? "non-excluded " : "");
2570 /** Return a pointer to a suitable router to be the exit node for the
2571 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
2572 * if no router is suitable).
2574 * For general-purpose circuits, pass it off to
2575 * choose_good_exit_server_general()
2577 * For client-side rendezvous circuits, choose a random node, weighted
2578 * toward the preferences in 'options'.
2580 static const node_t
*
2581 choose_good_exit_server(uint8_t purpose
,
2582 int need_uptime
, int need_capacity
, int is_internal
)
2584 const or_options_t
*options
= get_options();
2585 router_crn_flags_t flags
= CRN_NEED_DESC
;
2587 flags
|= CRN_NEED_UPTIME
;
2589 flags
|= CRN_NEED_CAPACITY
;
2592 case CIRCUIT_PURPOSE_C_GENERAL
:
2593 if (options
->AllowInvalid_
& ALLOW_INVALID_MIDDLE
)
2594 flags
|= CRN_ALLOW_INVALID
;
2595 if (is_internal
) /* pick it like a middle hop */
2596 return router_choose_random_node(NULL
, options
->ExcludeNodes
, flags
);
2598 return choose_good_exit_server_general(need_uptime
,need_capacity
);
2599 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
2600 if (options
->AllowInvalid_
& ALLOW_INVALID_RENDEZVOUS
)
2601 flags
|= CRN_ALLOW_INVALID
;
2602 return router_choose_random_node(NULL
, options
->ExcludeNodes
, flags
);
2604 log_warn(LD_BUG
,"Unhandled purpose %d", purpose
);
2605 tor_fragile_assert();
2609 /** Log a warning if the user specified an exit for the circuit that
2610 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
2612 warn_if_last_router_excluded(origin_circuit_t
*circ
, const extend_info_t
*exit
)
2614 const or_options_t
*options
= get_options();
2615 routerset_t
*rs
= options
->ExcludeNodes
;
2616 const char *description
;
2617 uint8_t purpose
= circ
->base_
.purpose
;
2619 if (circ
->build_state
->onehop_tunnel
)
2625 case CIRCUIT_PURPOSE_OR
:
2626 case CIRCUIT_PURPOSE_INTRO_POINT
:
2627 case CIRCUIT_PURPOSE_REND_POINT_WAITING
:
2628 case CIRCUIT_PURPOSE_REND_ESTABLISHED
:
2629 log_warn(LD_BUG
, "Called on non-origin circuit (purpose %d, %s)",
2631 circuit_purpose_to_string(purpose
));
2633 case CIRCUIT_PURPOSE_C_GENERAL
:
2634 if (circ
->build_state
->is_internal
)
2636 description
= "requested exit node";
2637 rs
= options
->ExcludeExitNodesUnion_
;
2639 case CIRCUIT_PURPOSE_C_INTRODUCING
:
2640 case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
:
2641 case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED
:
2642 case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO
:
2643 case CIRCUIT_PURPOSE_S_CONNECT_REND
:
2644 case CIRCUIT_PURPOSE_S_REND_JOINED
:
2645 case CIRCUIT_PURPOSE_TESTING
:
2647 case CIRCUIT_PURPOSE_C_ESTABLISH_REND
:
2648 case CIRCUIT_PURPOSE_C_REND_READY
:
2649 case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED
:
2650 case CIRCUIT_PURPOSE_C_REND_JOINED
:
2651 description
= "chosen rendezvous point";
2653 case CIRCUIT_PURPOSE_CONTROLLER
:
2654 rs
= options
->ExcludeExitNodesUnion_
;
2655 description
= "controller-selected circuit target";
2659 if (routerset_contains_extendinfo(rs
, exit
)) {
2660 /* We should never get here if StrictNodes is set to 1. */
2661 if (options
->StrictNodes
) {
2662 log_warn(LD_BUG
, "Using %s '%s' which is listed in ExcludeNodes%s, "
2663 "even though StrictNodes is set. Please report. "
2664 "(Circuit purpose: %s)",
2665 description
, extend_info_describe(exit
),
2666 rs
==options
->ExcludeNodes
?"":" or ExcludeExitNodes",
2667 circuit_purpose_to_string(purpose
));
2669 log_warn(LD_CIRC
, "Using %s '%s' which is listed in "
2670 "ExcludeNodes%s, because no better options were available. To "
2671 "prevent this (and possibly break your Tor functionality), "
2672 "set the StrictNodes configuration option. "
2673 "(Circuit purpose: %s)",
2674 description
, extend_info_describe(exit
),
2675 rs
==options
->ExcludeNodes
?"":" or ExcludeExitNodes",
2676 circuit_purpose_to_string(purpose
));
2678 circuit_log_path(LOG_WARN
, LD_CIRC
, circ
);
2684 /** Decide a suitable length for circ's cpath, and pick an exit
2685 * router (or use <b>exit</b> if provided). Store these in the
2686 * cpath. Return 0 if ok, -1 if circuit should be closed. */
2688 onion_pick_cpath_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
2690 cpath_build_state_t
*state
= circ
->build_state
;
2692 if (state
->onehop_tunnel
) {
2693 log_debug(LD_CIRC
, "Launching a one-hop circuit for dir tunnel.");
2694 state
->desired_path_len
= 1;
2696 int r
= new_route_len(circ
->base_
.purpose
, exit
, nodelist_get_list());
2697 if (r
< 1) /* must be at least 1 */
2699 state
->desired_path_len
= r
;
2702 if (exit
) { /* the circuit-builder pre-requested one */
2703 warn_if_last_router_excluded(circ
, exit
);
2704 log_info(LD_CIRC
,"Using requested exit node '%s'",
2705 extend_info_describe(exit
));
2706 exit
= extend_info_dup(exit
);
2707 } else { /* we have to decide one */
2708 const node_t
*node
=
2709 choose_good_exit_server(circ
->base_
.purpose
, state
->need_uptime
,
2710 state
->need_capacity
, state
->is_internal
);
2712 log_warn(LD_CIRC
,"failed to choose an exit server");
2715 exit
= extend_info_from_node(node
, 0);
2718 state
->chosen_exit
= exit
;
2722 /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
2723 * hop to the cpath reflecting this. Don't send the next extend cell --
2724 * the caller will do this if it wants to.
2727 circuit_append_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
2729 cpath_build_state_t
*state
;
2733 state
= circ
->build_state
;
2735 extend_info_free(state
->chosen_exit
);
2736 state
->chosen_exit
= extend_info_dup(exit
);
2738 ++circ
->build_state
->desired_path_len
;
2739 onion_append_hop(&circ
->cpath
, exit
);
2743 /** Take an open <b>circ</b>, and add a new hop at the end, based on
2744 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
2745 * send the next extend cell to begin connecting to that hop.
2748 circuit_extend_to_new_exit(origin_circuit_t
*circ
, extend_info_t
*exit
)
2751 warn_if_last_router_excluded(circ
, exit
);
2753 tor_gettimeofday(&circ
->base_
.timestamp_began
);
2755 circuit_append_new_exit(circ
, exit
);
2756 circuit_set_state(TO_CIRCUIT(circ
), CIRCUIT_STATE_BUILDING
);
2757 if ((err_reason
= circuit_send_next_onion_skin(circ
))<0) {
2758 log_warn(LD_CIRC
, "Couldn't extend circuit to new point %s.",
2759 extend_info_describe(exit
));
2760 circuit_mark_for_close(TO_CIRCUIT(circ
), -err_reason
);
2764 /* Set timestamp_dirty, so we can check it for path use bias */
2765 if (!circ
->base_
.timestamp_dirty
)
2766 circ
->base_
.timestamp_dirty
= time(NULL
);
2771 /** Return the number of routers in <b>routers</b> that are currently up
2772 * and available for building circuits through.
2775 count_acceptable_nodes(smartlist_t
*nodes
)
2779 SMARTLIST_FOREACH_BEGIN(nodes
, const node_t
*, node
) {
2780 // log_debug(LD_CIRC,
2781 // "Contemplating whether router %d (%s) is a new option.",
2783 if (! node
->is_running
)
2784 // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
2786 if (! node
->is_valid
)
2787 // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
2789 if (! node_has_descriptor(node
))
2791 /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
2792 * allows this node in some places, then we're getting an inaccurate
2793 * count. For now, be conservative and don't count it. But later we
2794 * should try to be smarter. */
2796 } SMARTLIST_FOREACH_END(node
);
2798 // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
2803 /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
2804 * This function is used to extend cpath by another hop.
2807 onion_append_to_cpath(crypt_path_t
**head_ptr
, crypt_path_t
*new_hop
)
2810 new_hop
->next
= (*head_ptr
);
2811 new_hop
->prev
= (*head_ptr
)->prev
;
2812 (*head_ptr
)->prev
->next
= new_hop
;
2813 (*head_ptr
)->prev
= new_hop
;
2815 *head_ptr
= new_hop
;
2816 new_hop
->prev
= new_hop
->next
= new_hop
;
2820 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
2821 * and <b>state</b> and the cpath <b>head</b> (currently populated only
2822 * to length <b>cur_len</b> to decide a suitable middle hop for a
2823 * circuit. In particular, make sure we don't pick the exit node or its
2824 * family, and make sure we don't duplicate any previous nodes or their
2826 static const node_t
*
2827 choose_good_middle_server(uint8_t purpose
,
2828 cpath_build_state_t
*state
,
2833 const node_t
*r
, *choice
;
2834 crypt_path_t
*cpath
;
2835 smartlist_t
*excluded
;
2836 const or_options_t
*options
= get_options();
2837 router_crn_flags_t flags
= CRN_NEED_DESC
;
2838 tor_assert(CIRCUIT_PURPOSE_MIN_
<= purpose
&&
2839 purpose
<= CIRCUIT_PURPOSE_MAX_
);
2841 log_debug(LD_CIRC
, "Contemplating intermediate hop: random choice.");
2842 excluded
= smartlist_new();
2843 if ((r
= build_state_get_exit_node(state
))) {
2844 nodelist_add_node_and_family(excluded
, r
);
2846 for (i
= 0, cpath
= head
; i
< cur_len
; ++i
, cpath
=cpath
->next
) {
2847 if ((r
= node_get_by_id(cpath
->extend_info
->identity_digest
))) {
2848 nodelist_add_node_and_family(excluded
, r
);
2852 if (state
->need_uptime
)
2853 flags
|= CRN_NEED_UPTIME
;
2854 if (state
->need_capacity
)
2855 flags
|= CRN_NEED_CAPACITY
;
2856 if (options
->AllowInvalid_
& ALLOW_INVALID_MIDDLE
)
2857 flags
|= CRN_ALLOW_INVALID
;
2858 choice
= router_choose_random_node(excluded
, options
->ExcludeNodes
, flags
);
2859 smartlist_free(excluded
);
2863 /** Pick a good entry server for the circuit to be built according to
2864 * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
2865 * router (if we're an OR), and respect firewall settings; if we're
2866 * configured to use entry guards, return one.
2868 * If <b>state</b> is NULL, we're choosing a router to serve as an entry
2869 * guard, not for any particular circuit.
2871 /* XXXX024 I'd like to have this be static again, but entrynodes.c needs it. */
2873 choose_good_entry_server(uint8_t purpose
, cpath_build_state_t
*state
)
2875 const node_t
*choice
;
2876 smartlist_t
*excluded
;
2877 const or_options_t
*options
= get_options();
2878 router_crn_flags_t flags
= CRN_NEED_GUARD
|CRN_NEED_DESC
;
2881 if (state
&& options
->UseEntryGuards
&&
2882 (purpose
!= CIRCUIT_PURPOSE_TESTING
|| options
->BridgeRelay
)) {
2883 /* This request is for an entry server to use for a regular circuit,
2884 * and we use entry guard nodes. Just return one of the guard nodes. */
2885 return choose_random_entry(state
);
2888 excluded
= smartlist_new();
2890 if (state
&& (node
= build_state_get_exit_node(state
))) {
2891 /* Exclude the exit node from the state, if we have one. Also exclude its
2893 nodelist_add_node_and_family(excluded
, node
);
2895 if (firewall_is_fascist_or()) {
2896 /* Exclude all ORs that we can't reach through our firewall */
2897 smartlist_t
*nodes
= nodelist_get_list();
2898 SMARTLIST_FOREACH(nodes
, const node_t
*, node
, {
2899 if (!fascist_firewall_allows_node(node
))
2900 smartlist_add(excluded
, (void*)node
);
2903 /* and exclude current entry guards and their families, if applicable */
2904 if (options
->UseEntryGuards
) {
2905 SMARTLIST_FOREACH(get_entry_guards(), const entry_guard_t
*, entry
,
2907 if ((node
= node_get_by_id(entry
->identity
))) {
2908 nodelist_add_node_and_family(excluded
, node
);
2914 if (state
->need_uptime
)
2915 flags
|= CRN_NEED_UPTIME
;
2916 if (state
->need_capacity
)
2917 flags
|= CRN_NEED_CAPACITY
;
2919 if (options
->AllowInvalid_
& ALLOW_INVALID_ENTRY
)
2920 flags
|= CRN_ALLOW_INVALID
;
2922 choice
= router_choose_random_node(excluded
, options
->ExcludeNodes
, flags
);
2923 smartlist_free(excluded
);
2927 /** Return the first non-open hop in cpath, or return NULL if all
2929 static crypt_path_t
*
2930 onion_next_hop_in_cpath(crypt_path_t
*cpath
)
2932 crypt_path_t
*hop
= cpath
;
2934 if (hop
->state
!= CPATH_STATE_OPEN
)
2937 } while (hop
!= cpath
);
2941 /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
2942 * based on <b>state</b>. Append the hop info to head_ptr.
2945 onion_extend_cpath(origin_circuit_t
*circ
)
2947 uint8_t purpose
= circ
->base_
.purpose
;
2948 cpath_build_state_t
*state
= circ
->build_state
;
2949 int cur_len
= circuit_get_cpath_len(circ
);
2950 extend_info_t
*info
= NULL
;
2952 if (cur_len
>= state
->desired_path_len
) {
2953 log_debug(LD_CIRC
, "Path is complete: %d steps long",
2954 state
->desired_path_len
);
2958 log_debug(LD_CIRC
, "Path is %d long; we want %d", cur_len
,
2959 state
->desired_path_len
);
2961 if (cur_len
== state
->desired_path_len
- 1) { /* Picking last node */
2962 info
= extend_info_dup(state
->chosen_exit
);
2963 } else if (cur_len
== 0) { /* picking first node */
2964 const node_t
*r
= choose_good_entry_server(purpose
, state
);
2966 /* If we're a client, use the preferred address rather than the
2967 primary address, for potentially connecting to an IPv6 OR
2969 info
= extend_info_from_node(r
, server_mode(get_options()) == 0);
2974 choose_good_middle_server(purpose
, state
, circ
->cpath
, cur_len
);
2976 info
= extend_info_from_node(r
, 0);
2982 log_warn(LD_CIRC
,"Failed to find node for hop %d of our path. Discarding "
2983 "this circuit.", cur_len
);
2987 log_debug(LD_CIRC
,"Chose router %s for hop %d (exit is %s)",
2988 extend_info_describe(info
),
2989 cur_len
+1, build_state_get_exit_nickname(state
));
2991 onion_append_hop(&circ
->cpath
, info
);
2992 extend_info_free(info
);
2996 /** Create a new hop, annotate it with information about its
2997 * corresponding router <b>choice</b>, and append it to the
2998 * end of the cpath <b>head_ptr</b>. */
3000 onion_append_hop(crypt_path_t
**head_ptr
, extend_info_t
*choice
)
3002 crypt_path_t
*hop
= tor_malloc_zero(sizeof(crypt_path_t
));
3004 /* link hop into the cpath, at the end. */
3005 onion_append_to_cpath(head_ptr
, hop
);
3007 hop
->magic
= CRYPT_PATH_MAGIC
;
3008 hop
->state
= CPATH_STATE_CLOSED
;
3010 hop
->extend_info
= extend_info_dup(choice
);
3012 hop
->package_window
= circuit_initial_package_window();
3013 hop
->deliver_window
= CIRCWINDOW_START
;
3018 /** Allocate a new extend_info object based on the various arguments. */
3020 extend_info_new(const char *nickname
, const char *digest
,
3021 crypto_pk_t
*onion_key
,
3022 const curve25519_public_key_t
*curve25519_key
,
3023 const tor_addr_t
*addr
, uint16_t port
)
3025 extend_info_t
*info
= tor_malloc_zero(sizeof(extend_info_t
));
3026 memcpy(info
->identity_digest
, digest
, DIGEST_LEN
);
3028 strlcpy(info
->nickname
, nickname
, sizeof(info
->nickname
));
3030 info
->onion_key
= crypto_pk_dup_key(onion_key
);
3031 #ifdef CURVE25519_ENABLED
3033 memcpy(&info
->curve25519_onion_key
, curve25519_key
,
3034 sizeof(curve25519_public_key_t
));
3036 (void)curve25519_key
;
3038 tor_addr_copy(&info
->addr
, addr
);
3043 /** Allocate and return a new extend_info that can be used to build a
3044 * circuit to or through the node <b>node</b>. Use the primary address
3045 * of the node (i.e. its IPv4 address) unless
3046 * <b>for_direct_connect</b> is true, in which case the preferred
3047 * address is used instead. May return NULL if there is not enough
3048 * info about <b>node</b> to extend to it--for example, if there is no
3049 * routerinfo_t or microdesc_t.
3052 extend_info_from_node(const node_t
*node
, int for_direct_connect
)
3056 if (node
->ri
== NULL
&& (node
->rs
== NULL
|| node
->md
== NULL
))
3059 if (for_direct_connect
)
3060 node_get_pref_orport(node
, &ap
);
3062 node_get_prim_orport(node
, &ap
);
3064 log_debug(LD_CIRC
, "using %s for %s",
3065 fmt_addrport(&ap
.addr
, ap
.port
),
3066 node
->ri
? node
->ri
->nickname
: node
->rs
->nickname
);
3069 return extend_info_new(node
->ri
->nickname
,
3071 node
->ri
->onion_pkey
,
3072 node
->ri
->onion_curve25519_pkey
,
3075 else if (node
->rs
&& node
->md
)
3076 return extend_info_new(node
->rs
->nickname
,
3078 node
->md
->onion_pkey
,
3079 node
->md
->onion_curve25519_pkey
,
3086 /** Release storage held by an extend_info_t struct. */
3088 extend_info_free(extend_info_t
*info
)
3092 crypto_pk_free(info
->onion_key
);
3096 /** Allocate and return a new extend_info_t with the same contents as
3099 extend_info_dup(extend_info_t
*info
)
3101 extend_info_t
*newinfo
;
3103 newinfo
= tor_malloc(sizeof(extend_info_t
));
3104 memcpy(newinfo
, info
, sizeof(extend_info_t
));
3105 if (info
->onion_key
)
3106 newinfo
->onion_key
= crypto_pk_dup_key(info
->onion_key
);
3108 newinfo
->onion_key
= NULL
;
3112 /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
3113 * If there is no chosen exit, or if we don't know the routerinfo_t for
3114 * the chosen exit, return NULL.
3117 build_state_get_exit_node(cpath_build_state_t
*state
)
3119 if (!state
|| !state
->chosen_exit
)
3121 return node_get_by_id(state
->chosen_exit
->identity_digest
);
3124 /** Return the nickname for the chosen exit router in <b>state</b>. If
3125 * there is no chosen exit, or if we don't know the routerinfo_t for the
3126 * chosen exit, return NULL.
3129 build_state_get_exit_nickname(cpath_build_state_t
*state
)
3131 if (!state
|| !state
->chosen_exit
)
3133 return state
->chosen_exit
->nickname
;