7 Note: This is an attempt to specify Tor as currently implemented. Future
8 versions of Tor will implement improved algorithms.
10 This document tries to cover how Tor chooses to build circuits and assign
11 streams to circuits. Other implementations MAY take other approaches, but
12 implementors should be aware of the anonymity and load-balancing implications
15 THIS SPEC ISN'T DONE YET.
17 The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL
18 NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
19 "OPTIONAL" in this document are to be interpreted as described in
24 Tor begins building circuits as soon as it has enough directory
25 information to do so (see section 5 of dir-spec.txt). Some circuits are
26 built preemptively because we expect to need them later (for user
27 traffic), and some are built because of immediate need (for user traffic
28 that no current circuit can handle, for testing the network or our
29 reachability, and so on).
31 When a client application creates a new stream (by opening a SOCKS
32 connection or launching a resolve request), we attach it to an appropriate
33 open circuit if one exists, or wait if an appropriate circuit is
34 in-progress. We launch a new circuit only
35 if no current circuit can handle the request. We rotate circuits over
36 time to avoid some profiling attacks.
38 To build a circuit, we choose all the nodes we want to use, and then
39 construct the circuit. Sometimes, when we want a circuit that ends at a
40 given hop, and we have an appropriate unused circuit, we "cannibalize" the
41 existing circuit and extend it to the new terminus.
43 These processes are described in more detail below.
45 This document describes Tor's automatic path selection logic only; path
46 selection can be overridden by a controller (with the EXTENDCIRCUIT and
47 ATTACHSTREAM commands). Paths constructed through these means may
48 violate some constraints given below.
52 A "path" is an ordered sequence of nodes, not yet built as a circuit.
54 A "clean" circuit is one that has not yet been used for any traffic.
56 A "fast" or "stable" or "valid" node is one that has the 'Fast' or
57 'Stable' or 'Valid' flag
58 set respectively, based on our current directory information. A "fast"
59 or "stable" circuit is one consisting only of "fast" or "stable" nodes.
61 In an "exit" circuit, the final node is chosen based on waiting stream
62 requests if any, and in any case it avoids nodes with exit policy of
63 "reject *:*". An "internal" circuit, on the other hand, is one where
64 the final node is chosen just like a middle node (ignoring its exit
67 A "request" is a client-side stream or DNS resolve that needs to be
70 A "pending" circuit is one that we have started to build, but which has
73 A circuit or path "supports" a request if it is okay to use the
74 circuit/path to fulfill the request, according to the rules given below.
75 A circuit or path "might support" a request if some aspect of the request
76 is unknown (usually its target IP), but we believe the path probably
77 supports the request according to the rules given below.
79 1.1. A relay's bandwidth
81 Old versions of Tor did not report bandwidths in network status
82 documents, so clients had to learn them from the routers' advertised
85 For versions of Tor prior to 0.2.1.17-rc, everywhere below where we
86 refer to a relay's "bandwidth", we mean its clipped advertised
87 bandwidth, computed by taking the smaller of the 'rate' and
88 'observed' arguments to the "bandwidth" element in the relay's
89 descriptor. If a router's advertised bandwidth is greater than
90 MAX_BELIEVABLE_BANDWIDTH (currently 10 MB/s), we clipped to that
93 For more recent versions of Tor, we take the bandwidth value declared
94 in the consensus, and fall back to the clipped advertised bandwidth
95 only if the consensus does not have bandwidths listed.
101 2.1.1. Clients build circuits preemptively
103 When running as a client, Tor tries to maintain at least a certain
104 number of clean circuits, so that new streams can be handled
105 quickly. To increase the likelihood of success, Tor tries to
106 predict what circuits will be useful by choosing from among nodes
107 that support the ports we have used in the recent past (by default
108 one hour). Specifically, on startup Tor tries to maintain one clean
109 fast exit circuit that allows connections to port 80, and at least
110 two fast clean stable internal circuits in case we get a resolve
111 request or hidden service request (at least three if we _run_ a
114 After that, Tor will adapt the circuits that it preemptively builds
115 based on the requests it sees from the user: it tries to have two fast
116 clean exit circuits available for every port seen within the past hour
117 (each circuit can be adequate for many predicted ports -- it doesn't
118 need two separate circuits for each port), and it tries to have the
119 above internal circuits available if we've seen resolves or hidden
120 service activity within the past hour. If there are 12 or more clean
121 circuits open, it doesn't open more even if it has more predictions.
123 Only stable circuits can "cover" a port that is listed in the
124 LongLivedPorts config option. Similarly, hidden service requests
125 to ports listed in LongLivedPorts make us create stable internal
128 Note that if there are no requests from the user for an hour, Tor
129 will predict no use and build no preemptive circuits.
131 The Tor client SHOULD NOT store its list of predicted requests to a
134 2.1.2. Clients build circuits on demand
136 Additionally, when a client request exists that no circuit (built or
137 pending) might support, we create a new circuit to support the request.
138 For exit connections, we pick an exit node that will handle the
139 most pending requests (choosing arbitrarily among ties), launch a
140 circuit to end there, and repeat until every unattached request
141 might be supported by a pending or built circuit. For internal
142 circuits, we pick an arbitrary acceptable path, repeating as needed.
144 In some cases we can reuse an already established circuit if it's
145 clean; see Section 2.3 (cannibalizing circuits) for details.
147 2.1.3. Relays build circuits for testing reachability and bandwidth
149 Tor relays test reachability of their ORPort once they have
150 successfully built a circuit (on startup and whenever their IP address
151 changes). They build an ordinary fast internal circuit with themselves
152 as the last hop. As soon as any testing circuit succeeds, the Tor
153 relay decides it's reachable and is willing to publish a descriptor.
155 We launch multiple testing circuits (one at a time), until we
156 have NUM_PARALLEL_TESTING_CIRC (4) such circuits open. Then we
157 do a "bandwidth test" by sending a certain number of relay drop
158 cells down each circuit: BandwidthRate * 10 / CELL_NETWORK_SIZE
159 total cells divided across the four circuits, but never more than
160 CIRCWINDOW_START (1000) cells total. This exercises both outgoing and
161 incoming bandwidth, and helps to jumpstart the observed bandwidth
164 Tor relays also test reachability of their DirPort once they have
165 established a circuit, but they use an ordinary exit circuit for
168 2.1.4. Hidden-service circuits
172 2.1.5. Rate limiting of failed circuits
174 If we fail to build a circuit N times in a X second period (see Section
175 2.3 for how this works), we stop building circuits until the X seconds
179 2.1.6. When to tear down circuits
184 2.2. Path selection and constraints
186 We choose the path for each new circuit before we build it. We choose the
187 exit node first, followed by the other nodes in the circuit. All paths
188 we generate obey the following constraints:
189 - We do not choose the same router twice for the same path.
190 - We do not choose any router in the same family as another in the same
192 - We do not choose more than one router in a given /16 subnet
193 (unless EnforceDistinctSubnets is 0).
194 - We don't choose any non-running or non-valid router unless we have
195 been configured to do so. By default, we are configured to allow
196 non-valid routers in "middle" and "rendezvous" positions.
197 - If we're using Guard nodes, the first node must be a Guard (see 5
199 - XXXX Choosing the length
201 For "fast" circuits, we only choose nodes with the Fast flag. For
202 non-"fast" circuits, all nodes are eligible.
204 For all circuits, we weight node selection according to router bandwidth.
206 We also weight the bandwidth of Exit and Guard flagged nodes depending on
207 the fraction of total bandwidth that they make up and depending upon the
208 position they are being selected for.
210 These weights are published in the consensus, and are computed as described
211 in Section 3.4.3 of dir-spec.txt. They are:
213 Wgg - Weight for Guard-flagged nodes in the guard position
214 Wgm - Weight for non-flagged nodes in the guard Position
215 Wgd - Weight for Guard+Exit-flagged nodes in the guard Position
217 Wmg - Weight for Guard-flagged nodes in the middle Position
218 Wmm - Weight for non-flagged nodes in the middle Position
219 Wme - Weight for Exit-flagged nodes in the middle Position
220 Wmd - Weight for Guard+Exit flagged nodes in the middle Position
222 Weg - Weight for Guard flagged nodes in the exit Position
223 Wem - Weight for non-flagged nodes in the exit Position
224 Wee - Weight for Exit-flagged nodes in the exit Position
225 Wed - Weight for Guard+Exit-flagged nodes in the exit Position
227 Wgb - Weight for BEGIN_DIR-supporting Guard-flagged nodes
228 Wmb - Weight for BEGIN_DIR-supporting non-flagged nodes
229 Web - Weight for BEGIN_DIR-supporting Exit-flagged nodes
230 Wdb - Weight for BEGIN_DIR-supporting Guard+Exit-flagged nodes
232 Wbg - Weight for Guard+Exit-flagged nodes for BEGIN_DIR requests
233 Wbm - Weight for Guard+Exit-flagged nodes for BEGIN_DIR requests
234 Wbe - Weight for Guard+Exit-flagged nodes for BEGIN_DIR requests
235 Wbd - Weight for Guard+Exit-flagged nodes for BEGIN_DIR requests
237 Additionally, we may be building circuits with one or more requests in
238 mind. Each kind of request puts certain constraints on paths:
240 - All service-side introduction circuits and all rendezvous paths
242 - All connection requests for connections that we think will need to
243 stay open a long time require Stable circuits. Currently, Tor decides
244 this by examining the request's target port, and comparing it to a
245 list of "long-lived" ports. (Default: 21, 22, 706, 1863, 5050,
246 5190, 5222, 5223, 6667, 6697, 8300.)
247 - DNS resolves require an exit node whose exit policy is not equivalent
249 - Reverse DNS resolves require a version of Tor with advertised eventdns
250 support (available in Tor 0.1.2.1-alpha-dev and later).
251 - All connection requests require an exit node whose exit policy
252 supports their target address and port (if known), or which "might
253 support it" (if the address isn't known). See 2.2.1.
254 - Rules for Fast? XXXXX
256 2.2.1. Choosing an exit
258 If we know what IP address we want to connect to or resolve, we can
259 trivially tell whether a given router will support it by simulating
260 its declared exit policy.
262 Because we often connect to addresses of the form hostname:port, we do not
263 always know the target IP address when we select an exit node. In these
264 cases, we need to pick an exit node that "might support" connections to a
265 given address port with an unknown address. An exit node "might support"
266 such a connection if any clause that accepts any connections to that port
267 precedes all clauses (if any) that reject all connections to that port.
269 Unless requested to do so by the user, we never choose an exit node
270 flagged as "BadExit" by more than half of the authorities who advertise
271 themselves as listing bad exits.
273 2.2.2. User configuration
275 Users can alter the default behavior for path selection with configuration
278 - If "ExitNodes" is provided, then every request requires an exit node on
279 the ExitNodes list. (If a request is supported by no nodes on that list,
280 and StrictExitNodes is false, then Tor treats that request as if
281 ExitNodes were not provided.)
283 - "EntryNodes" and "StrictEntryNodes" behave analogously.
285 - If a user tries to connect to or resolve a hostname of the form
286 <target>.<servername>.exit, the request is rewritten to a request for
287 <target>, and the request is only supported by the exit whose nickname
288 or fingerprint is <servername>.
290 2.3. Cannibalizing circuits
292 If we need a circuit and have a clean one already established, in
293 some cases we can adapt the clean circuit for our new
294 purpose. Specifically,
296 For hidden service interactions, we can "cannibalize" a clean internal
297 circuit if one is available, so we don't need to build those circuits
298 from scratch on demand.
300 We can also cannibalize clean circuits when the client asks to exit
301 at a given node -- either via the ".exit" notation or because the
302 destination is running at the same location as an exit node.
304 2.4. Learning when to give up ("timeout") on circuit construction
306 Since version 0.2.2.8-alpha, Tor attempts to learn when to give up on
307 circuits based on network conditions.
309 2.4.1 Distribution choice and parameter estimation
311 Based on studies of build times, we found that the distribution of
312 circuit build times appears to be a Frechet distribution. However,
313 estimators and quantile functions of the Frechet distribution are
314 difficult to work with and slow to converge. So instead, since we
315 are only interested in the accuracy of the tail, we approximate
316 the tail of the distribution with a Pareto curve.
318 We calculate the parameters for a Pareto distribution fitting the data
319 using the estimators in equation 4 from:
320 http://portal.acm.org/citation.cfm?id=1647962.1648139
324 alpha_m = s/(ln(U(X)/Xm^n))
326 where s is the total number of completed circuits we have seen, and
328 U(X) = x_max^u * Prod_s{x_i}
330 with x_i as our i-th completed circuit time, x_max as the longest
331 completed circuit build time we have yet observed, u as the
332 number of unobserved timeouts that have no exact value recorded,
333 and n as u+s, the total number of circuits that either timeout or
336 Using log laws, we compute this as the sum of logs to avoid
337 overflow and ln(1.0+epsilon) precision issues:
339 alpha_m = s/(u*ln(x_max) + Sum_s{ln(x_i)} - n*ln(Xm))
341 This estimator is closely related to the parameters present in:
342 http://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
343 except they are adjusted to handle the fact that our samples are
344 right-censored at the timeout cutoff.
346 Additionally, because this is not a true Pareto distribution, we alter
347 how Xm is computed. The Xm parameter is computed as the midpoint of the most
348 frequently occurring 50ms histogram bin, until the point where 1000
349 circuits are recorded. After this point, the weighted average of the top
350 'cbtnummodes' (default: 3) midpoint modes is used as Xm. All times below
351 this value are counted as having the midpoint value of this weighted average bin.
353 The timeout itself is calculated by using the Pareto Quantile function (the
354 inverted CDF) to give us the value on the CDF such that 80% of the mass
355 of the distribution is below the timeout value.
357 Thus, we expect that the Tor client will accept the fastest 80% of
358 the total number of paths on the network.
360 2.4.2. How much data to record
362 From our observations, the minimum number of circuit build times for a
363 reasonable fit appears to be on the order of 100. However, to keep a
364 good fit over the long term, we store 1000 most recent circuit build times
367 The Tor client should build test circuits at a rate of one per
368 minute up until 100 circuits are built. This allows a fresh Tor to have
369 a CircuitBuildTimeout estimated within 1.5 hours after install,
370 upgrade, or network change (see below).
372 Timeouts are stored on disk in a histogram of 50ms bin width, the same
373 width used to calculate the Xm value above. This histogram must be shuffled
374 after being read from disk, to preserve a proper expiration of old values
377 2.4.3. How to record timeouts
379 Circuits that pass the timeout threshold should be allowed to continue
380 building until a time corresponding to the point 'cbtclosequantile'
381 (default 95) on the Pareto curve, or 60 seconds, whichever is greater.
383 The actual completion times for these circuits should be recorded.
384 Implementations should completely abandon a circuit and record a value
385 as an 'unknown' timeout if the total build time exceeds this threshold.
387 The reason for this is that right-censored pareto estimators begin to lose
388 their accuracy if more than approximately 5% of the values are censored.
389 Since we wish to set the cutoff at 20%, we must allow circuits to continue
390 building past this cutoff point up to the 95th percentile.
392 2.4.4. Detecting Changing Network Conditions
394 We attempt to detect both network connectivity loss and drastic
395 changes in the timeout characteristics.
397 We assume that we've had network connectivity loss if 3 circuits
398 timeout and we've received no cells or TLS handshakes since those
399 circuits began. We then temporarily set the timeout to 60 seconds
400 and stop counting timeouts.
402 If 3 more circuits timeout and the network still has not been
403 live within this new 60 second timeout window, we then discard
404 the previous timeouts during this period from our history.
406 To detect changing network conditions, we keep a history of
407 the timeout or non-timeout status of the past 20 circuits that
408 successfully completed at least one hop. If more than 90% of
409 these circuits timeout, we discard all buildtimes history, reset
410 the timeout to 60, and then begin recomputing the timeout.
412 If the timeout was already 60 or higher, we double the timeout.
414 2.4.5. Consensus parameters governing behavior
416 Clients that implement circuit build timeout learning should obey the
417 following consensus parameters that govern behavior, in order to allow
418 us to handle bugs or other emergent behaviors due to client circuit
419 construction. If these parameters are not present in the consensus,
420 the listed default values should be used instead.
426 Effect: If 1, all CircuitBuildTime learning code should be
427 disabled and history should be discarded. For use in
428 emergency situations only.
434 Effect: This value governs how many modes to use in the weighted
435 average calculation of Pareto parameter Xm. A value of 3 introduces
436 some bias (2-5% of CDF) under ideal conditions, but allows for better
437 performance in the event that a client chooses guard nodes of radically
438 different performance characteristics.
444 Effect: This is the number of circuit build times to keep track of
445 for the following option.
451 Effect: When this many timeouts happen in the last 'cbtrecentcount'
452 circuit attempts, the client should discard all of its
453 history and begin learning a fresh timeout value.
459 Effect: This is the minimum number of circuits to build before
466 Effect: This is the position on the quantile curve to use to set the
467 timeout value. It is a percent (10-99).
471 Min: Value of cbtquantile parameter
473 Effect: This is the position on the quantile curve to use to set the
474 timeout value to use to actually close circuits. It is a percent
480 Max: 2147483647 (INT32_MAX)
481 Effect: Describes how often in seconds to build a test circuit to
482 gather timeout values. Only applies if less than 'cbtmincircs'
488 Max: 2147483647 (INT32_MAX)
489 Effect: This is the minimum allowed timeout value in milliseconds.
490 The minimum is to prevent rounding to 0 (we only check once
495 Min: Value of cbtmintimeout
496 Max: 2147483647 (INT32_MAX)
497 Effect: This is the timeout value to use before computing a timeout,
501 2.5. Handling failure
503 If an attempt to extend a circuit fails (either because the first create
504 failed or a subsequent extend failed) then the circuit is torn down and is
505 no longer pending. (XXXX really?) Requests that might have been
506 supported by the pending circuit thus become unsupported, and a new
507 circuit needs to be constructed.
509 If a stream "begin" attempt fails with an EXITPOLICY error, we
510 decide that the exit node's exit policy is not correctly advertised,
511 so we treat the exit node as if it were a non-exit until we retrieve
512 a fresh descriptor for it.
516 3. Attaching streams to circuits
518 When a circuit that might support a request is built, Tor tries to attach
519 the request's stream to the circuit and sends a BEGIN, BEGIN_DIR,
521 cell as appropriate. If the request completes unsuccessfully, Tor
522 considers the reason given in the CLOSE relay cell. [XXX yes, and?]
525 After a request has remained unattached for SocksTimeout (2 minutes
526 by default), Tor abandons the attempt and signals an error to the
527 client as appropriate (e.g., by closing the SOCKS connection).
529 XXX Timeouts and when Tor auto-retries.
530 * What stream-end-reasons are appropriate for retrying.
532 If no reply to BEGIN/RESOLVE, then the stream will timeout and fail.
534 4. Hidden-service related circuits
536 XXX Tracking expected hidden service use (client-side and hidserv-side)
540 We use Guard nodes (also called "helper nodes" in the literature) to
541 prevent certain profiling attacks. Here's the risk: if we choose entry and
542 exit nodes at random, and an attacker controls C out of N relays
543 (ignoring bandwidth), then the
544 attacker will control the entry and exit node of any given circuit with
545 probability (C/N)^2. But as we make many different circuits over time,
546 then the probability that the attacker will see a sample of about (C/N)^2
547 of our traffic goes to 1. Since statistical sampling works, the attacker
548 can be sure of learning a profile of our behavior.
550 If, on the other hand, we picked an entry node and held it fixed, we would
551 have probability C/N of choosing a bad entry and being profiled, and
552 probability (N-C)/N of choosing a good entry and not being profiled.
554 When guard nodes are enabled, Tor maintains an ordered list of entry nodes
555 as our chosen guards, and stores this list persistently to disk. If a Guard
556 node becomes unusable, rather than replacing it, Tor adds new guards to the
557 end of the list. When choosing the first hop of a circuit, Tor
559 random from among the first NumEntryGuards (default 3) usable guards on the
560 list. If there are not at least 2 usable guards on the list, Tor adds
561 routers until there are, or until there are no more usable routers to add.
563 A guard is unusable if any of the following hold:
564 - it is not marked as a Guard by the networkstatuses,
565 - it is not marked Valid (and the user hasn't set AllowInvalid entry)
566 - it is not marked Running
567 - Tor couldn't reach it the last time it tried to connect
569 A guard is unusable for a particular circuit if any of the rules for path
570 selection in 2.2 are not met. In particular, if the circuit is "fast"
571 and the guard is not Fast, or if the circuit is "stable" and the guard is
572 not Stable, or if the guard has already been chosen as the exit node in
573 that circuit, Tor can't use it as a guard node for that circuit.
575 If the guard is excluded because of its status in the networkstatuses for
576 over 30 days, Tor removes it from the list entirely, preserving order.
578 If Tor fails to connect to an otherwise usable guard, it retries
579 periodically: every hour for six hours, every 4 hours for 3 days, every
580 18 hours for a week, and every 36 hours thereafter. Additionally, Tor
581 retries unreachable guards the first time it adds a new guard to the list,
582 since it is possible that the old guards were only marked as unreachable
583 because the network was unreachable or down.
585 Tor does not add a guard persistently to the list until the first time we
586 have connected to it successfully.
588 6. Router descriptor purposes
590 There are currently three "purposes" supported for router descriptors:
591 general, controller, and bridge. Most descriptors are of type general
592 -- these are the ones listed in the consensus, and the ones fetched
593 and used in normal cases.
595 Controller-purpose descriptors are those delivered by the controller
596 and labelled as such: they will be kept around (and expire like
597 normal descriptors), and they can be used by the controller in its
598 CIRCUITEXTEND commands. Otherwise they are ignored by Tor when it
601 Bridge-purpose descriptors are for routers that are used as bridges. See
602 doc/design-paper/blocking.pdf for more design explanation, or proposal
603 125 for specific details. Currently bridge descriptors are used in place
604 of normal entry guards, for Tor clients that have UseBridges enabled.
609 X.1. Do we actually do this?
611 How to deal with network down.
612 - While all helpers are down/unreachable and there are no established
613 or on-the-way testing circuits, launch a testing circuit. (Do this
614 periodically in the same way we try to establish normal circuits
615 when things are working normally.)
616 (Testing circuits are a special type of circuit, that streams won't
617 attach to by accident.)
618 - When a testing circuit succeeds, mark all helpers up and hold
619 the testing circuit open.
620 - If a connection to a helper succeeds, close all testing circuits.
621 Else mark that helper down and try another.
622 - If the last helper is marked down and we already have a testing
623 circuit established, then add the first hop of that testing circuit
624 to the end of our helper node list, close that testing circuit,
625 and go back to square one. (Actually, rather than closing the
626 testing circuit, can we get away with converting it to a normal
627 circuit and beginning to use it immediately?)
629 [Do we actually do any of the above? If so, let's spec it. If not, let's
632 X.2. A thing we could do to deal with reachability.
634 And as a bonus, it leads to an answer to Nick's attack ("If I pick
635 my helper nodes all on 18.0.0.0:*, then I move, you'll know where I
636 bootstrapped") -- the answer is to pick your original three helper nodes
637 without regard for reachability. Then the above algorithm will add some
638 more that are reachable for you, and if you move somewhere, it's more
639 likely (though not certain) that some of the originals will become useful.
640 Is that smart or just complex?
642 X.3. Some stuff that worries me about entry guards. 2006 Jun, Nickm.
644 It is unlikely for two users to have the same set of entry guards.
645 Observing a user is sufficient to learn its entry guards. So, as we move
646 around, entry guards make us linkable. If we want to change guards when
647 our location (IP? subnet?) changes, we have two bad options. We could
648 - Drop the old guards. But if we go back to our old location,
649 we'll not use our old guards. For a laptop that sometimes gets used
650 from work and sometimes from home, this is pretty fatal.
651 - Remember the old guards as associated with the old location, and use
652 them again if we ever go back to the old location. This would be
653 nasty, since it would force us to record where we've been.
655 [Do we do any of this now? If not, this should move into 099-misc or