Add proposal 205: Remove global client-side DNS caching
[torspec/neena.git] / tor-spec.txt
blob86aa49f4d4eb7b2f336e1a288bbc07728674b778
2                          Tor Protocol Specification
4                               Roger Dingledine
5                                Nick Mathewson
7 Note: This document aims to specify Tor as implemented in 0.2.1.x.  Future
8 versions of Tor may implement improved protocols, and compatibility is not
9 guaranteed.  Compatibility notes are given for versions 0.1.1.15-rc and
10 later; earlier versions are not compatible with the Tor network as of this
11 writing.
13 This specification is not a design document; most design criteria
14 are not examined.  For more information on why Tor acts as it does,
15 see tor-design.pdf.
17 0. Preliminaries
19       The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL
20       NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED",  "MAY", and
21       "OPTIONAL" in this document are to be interpreted as described in
22       RFC 2119.
24 0.1.  Notation and encoding
26    PK -- a public key.
27    SK -- a private key.
28    K  -- a key for a symmetric cipher.
30    a|b -- concatenation of 'a' and 'b'.
32    [A0 B1 C2] -- a three-byte sequence, containing the bytes with
33    hexadecimal values A0, B1, and C2, in that order.
35    All numeric values are encoded in network (big-endian) order.
37    H(m) -- a cryptographic hash of m.
39 0.2. Security parameters
41    Tor uses a stream cipher, a public-key cipher, the Diffie-Hellman
42    protocol, and a hash function.
44    KEY_LEN -- the length of the stream cipher's key, in bytes.
46    PK_ENC_LEN -- the length of a public-key encrypted message, in bytes.
47    PK_PAD_LEN -- the number of bytes added in padding for public-key
48      encryption, in bytes. (The largest number of bytes that can be encrypted
49      in a single public-key operation is therefore PK_ENC_LEN-PK_PAD_LEN.)
51    DH_LEN -- the number of bytes used to represent a member of the
52      Diffie-Hellman group.
53    DH_SEC_LEN -- the number of bytes used in a Diffie-Hellman private key (x).
55    HASH_LEN -- the length of the hash function's output, in bytes.
57    PAYLOAD_LEN -- The longest allowable cell payload, in bytes. (509)
59    CELL_LEN -- The length of a Tor cell, in bytes.
61 0.3. Ciphers
63    For a stream cipher, we use 128-bit AES in counter mode, with an IV of all
64    0 bytes.
66    For a public-key cipher, we use RSA with 1024-bit keys and a fixed
67    exponent of 65537.  We use OAEP-MGF1 padding, with SHA-1 as its digest
68    function.  We leave the optional "Label" parameter unset. (For OAEP
69    padding, see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf)
71    For Diffie-Hellman, we use a generator (g) of 2.  For the modulus (p), we
72    use the 1024-bit safe prime from rfc2409 section 6.2 whose hex
73    representation is:
75      "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
76      "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
77      "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
78      "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
79      "49286651ECE65381FFFFFFFFFFFFFFFF"
81    As an optimization, implementations SHOULD choose DH private keys (x) of
82    320 bits.  Implementations that do this MUST never use any DH key more
83    than once.
84    [May other implementations reuse their DH keys?? -RD]
85    [Probably not. Conceivably, you could get away with changing DH keys once
86    per second, but there are too many oddball attacks for me to be
87    comfortable that this is safe. -NM]
89    For a hash function, we use SHA-1.
91    KEY_LEN=16.
92    DH_LEN=128; DH_SEC_LEN=40.
93    PK_ENC_LEN=128; PK_PAD_LEN=42.
94    HASH_LEN=20.
96    When we refer to "the hash of a public key", we mean the SHA-1 hash of the
97    DER encoding of an ASN.1 RSA public key (as specified in PKCS.1).
99    All "random" values MUST be generated with a cryptographically
100    strong pseudorandom number generator seeded from a strong entropy
101    source, unless otherwise noted.
103    The "hybrid encryption" of a byte sequence M with a public key PK is
104    computed as follows:
105       1. If M is less than PK_ENC_LEN-PK_PAD_LEN, pad and encrypt M with PK.
106       2. Otherwise, generate a KEY_LEN byte random key K.
107          Let M1 = the first PK_ENC_LEN-PK_PAD_LEN-KEY_LEN bytes of M,
108          and let M2 = the rest of M.
109          Pad and encrypt K|M1 with PK.  Encrypt M2 with our stream cipher,
110          using the key K.  Concatenate these encrypted values.
111    [XXX Note that this "hybrid encryption" approach does not prevent
112    an attacker from adding or removing bytes to the end of M. It also
113    allows attackers to modify the bytes not covered by the OAEP --
114    see Goldberg's PET2006 paper for details. We will add a MAC to this
115    scheme one day. -RD]
117 0.4. Other parameter values
119    CELL_LEN=512
121 1. System overview
123    Tor is a distributed overlay network designed to anonymize
124    low-latency TCP-based applications such as web browsing, secure shell,
125    and instant messaging. Clients choose a path through the network and
126    build a ``circuit'', in which each node (or ``onion router'' or ``OR'')
127    in the path knows its predecessor and successor, but no other nodes in
128    the circuit.  Traffic flowing down the circuit is sent in fixed-size
129    ``cells'', which are unwrapped by a symmetric key at each node (like
130    the layers of an onion) and relayed downstream.
132 1.1. Keys and names
134    Every Tor relay has multiple public/private keypairs:
136     - A long-term signing-only "Identity key" used to sign documents and
137       certificates, and used to establish relay identity.
138     - A medium-term "Onion key" used to decrypt onion skins when accepting
139       circuit extend attempts.  (See 5.1.)  Old keys MUST be accepted for at
140       least one week after they are no longer advertised.  Because of this,
141       relays MUST retain old keys for a while after they're rotated.
142     - A short-term "Connection key" used to negotiate TLS connections.
143       Tor implementations MAY rotate this key as often as they like, and
144       SHOULD rotate this key at least once a day.
146    Tor relays are also identified by "nicknames"; these are specified in
147    dir-spec.txt.
149 2. Connections
151    Connections between two Tor relays, or between a client and a relay,
152    use TLS/SSLv3 for link authentication and encryption.  All
153    implementations MUST support the SSLv3 ciphersuite
154    "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", and SHOULD support the TLS
155    ciphersuite "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" if it is available.
157    There are three ways to perform TLS handshakes with a Tor server.  In
158    the first way, "certificates-up-front", both the initiator and
159    responder send a two-certificate chain as part of their initial
160    handshake.  (This is supported in all Tor versions.)  In the second
161    way, "renegotiation", the responder provides a single certificate,
162    and the initiator immediately performs a TLS renegotiation.  (This is
163    supported in Tor 0.2.0.21 and later.)  And in the third way,
164    "in-protocol", the initial TLS renegotiation completes, and the
165    parties bootstrap themselves to mutual authentication via use of the
166    Tor protocol without further TLS handshaking.  (This is supported in
167    0.2.3.6-alpha and later.)
169    Each of these options provides a way for the parties to learn it is
170    available: a client does not need to know the version of the Tor
171    server in order to connect to it properly.
173    In "certificates up-front" (a.k.a "the v1 handshake"),
174    the connection initiator always sends a
175    two-certificate chain, consisting of an X.509 certificate using a
176    short-term connection public key and a second, self-signed X.509
177    certificate containing its identity key.  The other party sends a similar
178    certificate chain.  The initiator's ClientHello MUST NOT include any
179    ciphersuites other than:
180      TLS_DHE_RSA_WITH_AES_256_CBC_SHA
181      TLS_DHE_RSA_WITH_AES_128_CBC_SHA
182      SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA
183      SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA
185    In "renegotiation" (a.k.a. "the v2 handshake"),
186    the connection initiator sends no certificates, and
187    the responder sends a single connection certificate.  Once the TLS
188    handshake is complete, the initiator renegotiates the handshake, with each
189    party sending a two-certificate chain as in "certificates up-front".
190    The initiator's ClientHello MUST include at least one ciphersuite not in
191    the list above -- that's how the initiator indicates that it can
192    handle this handshake.  For other considerations on the initiator's
193    ClientHello, see section 2.1 below.
195    In "in-protocol" (a.k.a. "the v3 handshake"), the initiator sends no
196    certificates, and the
197    responder sends a single connection certificate.  The choice of
198    ciphersuites must be as in a "renegotiation" handshake.  There are
199    additionally a set of constraints on the connection certificate,
200    which the initiator can use to learn that the in-protocol handshake
201    is in use.  Specifically, at least one of these properties must be
202    true of the certificate:
203       * The certificate is self-signed
204       * Some component other than "commonName" is set in the subject or
205         issuer DN of the certificate.
206       * The commonName of the subject or issuer of the certificate ends
207         with a suffix other than ".net".
208       * The certificate's public key modulus is longer than 1024 bits.
209    The initiator then sends a VERSIONS cell to the responder, which then
210    replies with a VERSIONS cell; they have then negotiated a Tor
211    protocol version.  Assuming that the version they negotiate is 3 (the
212    only one specified for use with this handshake right now), the
213    responder sends a CERTS cell, an AUTH_CHALLENGE cell, and a NETINFO
214    cell to the initiator, which may send either CERTS, AUTHENTICATE,
215    NETINFO if it wants to authenticate, or just NETINFO if it does not.
217    For backward compatibility between later handshakes and "certificates
218    up-front", the ClientHello of an initiator that supports a later
219    handshake MUST include at least one ciphersuite other than those listed
220    above. The connection responder examines the initiator's ciphersuite list
221    to see whether it includes any ciphers other than those included in the
222    list above.  If extra ciphers are included, the responder proceeds as in
223    "renegotiation" and "in-protocol": it sends a single certificate and
224    does not request
225    client certificates.  Otherwise (in the case that no extra ciphersuites
226    are included in the ClientHello) the responder proceeds as in
227    "certificates up-front": it requests client certificates, and sends a
228    two-certificate chain.  In either case, once the responder has sent its
229    certificate or certificates, the initiator counts them.  If two
230    certificates have been sent, it proceeds as in "certificates up-front";
231    otherwise, it proceeds as in "renegotiation" or "in-protocol".
233    To decide whether to do "renegotiation" or "in-protocol", the
234    initiator checks whether the responder's initial certificate matches
235    the criteria listed above.
237    All new relay implementations of the Tor protocol MUST support
238    backwards-compatible renegotiation; clients SHOULD do this too.  If
239    this is not possible, new client implementations MUST support both
240    "renegotiation" and "in-protocol" and use the router's
241    published link protocols list (see dir-spec.txt on the "protocols" entry)
242    to decide which to use.
244    In all of the above handshake variants, certificates sent in the clear
245    SHOULD NOT include any strings to identify the host as a Tor relay. In
246    the "renegotiation" and "backwards-compatible renegotiation" steps, the
247    initiator SHOULD choose a list of ciphersuites and TLS extensions
248    to mimic one used by a popular web browser.
250    Even though the connection protocol is identical, we will think of the
251    initiator as either an onion router (OR) if it is willing to relay
252    traffic for other Tor users, or an onion proxy (OP) if it only handles
253    local requests. Onion proxies SHOULD NOT provide long-term-trackable
254    identifiers in their handshakes.
256    In all handshake variants, once all certificates are exchanged, all
257    parties receiving certificates must confirm that the identity key is as
258    expected.  (When initiating a connection, the expected identity key is
259    the one given in the directory; when creating a connection because of an
260    EXTEND cell, the expected identity key is the one given in the cell.)  If
261    the key is not as expected, the party must close the connection.
263    When connecting to an OR, all parties SHOULD reject the connection if that
264    OR has a malformed or missing certificate.  When accepting an incoming
265    connection, an OR SHOULD NOT reject incoming connections from parties with
266    malformed or missing certificates.  (However, an OR should not believe
267    that an incoming connection is from another OR unless the certificates
268    are present and well-formed.)
270    [Before version 0.1.2.8-rc, ORs rejected incoming connections from ORs and
271    OPs alike if their certificates were missing or malformed.]
273    Once a TLS connection is established, the two sides send cells
274    (specified below) to one another.  Cells are sent serially.  Standard
275    cells are CELL_LEN bytes long, but variable-length cells also exist; see
276    Section 3.  Cells may be sent embedded in TLS
277    records of any size or divided across TLS records, but the framing
278    of TLS records MUST NOT leak information about the type or contents
279    of the cells.
281    TLS connections are not permanent. Either side MAY close a connection
282    if there are no circuits running over it and an amount of time
283    (KeepalivePeriod, defaults to 5 minutes) has passed since the last time
284    any traffic was transmitted over the TLS connection.  Clients SHOULD
285    also hold a TLS connection with no circuits open, if it is likely that a
286    circuit will be built soon using that connection.
288    Client-only Tor instances are encouraged to avoid using handshake
289    variants that include certificates, if those certificates provide
290    any persistent tags to the relays they contact. If clients do use
291    certificates, they SHOULD NOT keep using the same certificates when
292    their IP address changes.  Clients MAY send certificates using any
293    of the above handshake variants.
295 2.1. Picking TLS ciphersuites
297    Clients SHOULD send a ciphersuite list chosen to emulate some popular
298    web browser or other program common on the internet. Clients may send
299    the "Fixed Cipheruite List" below.  If they do not, they MUST NOT
300    advertise any ciphersuite that they cannot actually support, unless that
301    cipher is one not supported by OpenSSL 1.0.1.
303    The fixed ciphersuite list is:
304      TLS1_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
305      TLS1_ECDHE_RSA_WITH_AES_256_CBC_SHA
306      TLS1_DHE_RSA_WITH_AES_256_SHA
307      TLS1_DHE_DSS_WITH_AES_256_SHA
308      TLS1_ECDH_RSA_WITH_AES_256_CBC_SHA
309      TLS1_ECDH_ECDSA_WITH_AES_256_CBC_SHA
310      TLS1_RSA_WITH_AES_256_SHA
311      TLS1_ECDHE_ECDSA_WITH_RC4_128_SHA
312      TLS1_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
313      TLS1_ECDHE_RSA_WITH_RC4_128_SHA
314      TLS1_ECDHE_RSA_WITH_AES_128_CBC_SHA
315      TLS1_DHE_RSA_WITH_AES_128_SHA
316      TLS1_DHE_DSS_WITH_AES_128_SHA
317      TLS1_ECDH_RSA_WITH_RC4_128_SHA
318      TLS1_ECDH_RSA_WITH_AES_128_CBC_SHA
319      TLS1_ECDH_ECDSA_WITH_RC4_128_SHA
320      TLS1_ECDH_ECDSA_WITH_AES_128_CBC_SHA
321      SSL3_RSA_RC4_128_MD5
322      SSL3_RSA_RC4_128_SHA
323      TLS1_RSA_WITH_AES_128_SHA
324      TLS1_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA
325      TLS1_ECDHE_RSA_WITH_DES_192_CBC3_SHA
326      SSL3_EDH_RSA_DES_192_CBC3_SHA
327      SSL3_EDH_DSS_DES_192_CBC3_SHA
328      TLS1_ECDH_RSA_WITH_DES_192_CBC3_SHA
329      TLS1_ECDH_ECDSA_WITH_DES_192_CBC3_SHA
330      SSL3_RSA_FIPS_WITH_3DES_EDE_CBC_SHA
331      SSL3_RSA_DES_192_CBC3_SHA
332      [*] The "extended renegotiation is supported" ciphersuite, 0x00ff, is
333          not counted when checking the list of ciphersuites.
335    If the client sends the Fixed Ciphersuite List, the responder MUST NOT
336    select any ciphersuite besides TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
337    TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, and
338    SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA: such ciphers might not actually be
339    supported by the client.
341    If the client sends a v2+ ClientHello with a list of ciphers other then
342    the Fixed Ciphersuite List, the responder can trust that the client
343    supports every cipher advertised in that list, so long as that ciphersuite
344    is also supported by OpenSSL 1.0.1.
346    Responders MUST NOT select any TLS ciphersuite that lacks ephemeral keys,
347    or whose symmetric keys are less then KEY_LEN bits, or whose digests are
348    less than HASH_LEN bits.  Responders SHOULD NOT select any SSLv3
349    ciphersuite other than the DHE+3DES suites listed above.
351 3. Cell Packet format
353    The basic unit of communication for onion routers and onion
354    proxies is a fixed-width "cell".
356    On a version 1 connection, each cell contains the following
357    fields:
359         CircID                                [2 bytes]
360         Command                               [1 byte]
361         Payload (padded with 0 bytes)         [PAYLOAD_LEN bytes]
363    On a version 2 or 3 connection, all cells are as in version 1 connections,
364    except for variable-length cells, whose format is:
366         CircID                                [2 octets]
367         Command                               [1 octet]
368         Length                                [2 octets; big-endian integer]
369         Payload                               [Length bytes]
371    On a version 2 connection, variable-length cells are indicated by a
372    command byte equal to 7 ("VERSIONS").  On a version 3 or
373    higher connection, variable-length cells are indicated by a command
374    byte equal to 7 ("VERSIONS"), or greater than or equal to 128.
376    The CircID field determines which circuit, if any, the cell is
377    associated with.
379    The 'Command' field of a fixed-length cell holds one of the following
380    values:
381          0 -- PADDING     (Padding)                 (See Sec 7.2)
382          1 -- CREATE      (Create a circuit)        (See Sec 5.1)
383          2 -- CREATED     (Acknowledge create)      (See Sec 5.1)
384          3 -- RELAY       (End-to-end data)         (See Sec 5.5 and 6)
385          4 -- DESTROY     (Stop using a circuit)    (See Sec 5.4)
386          5 -- CREATE_FAST (Create a circuit, no PK) (See Sec 5.1)
387          6 -- CREATED_FAST (Circuit created, no PK) (See Sec 5.1)
388          8 -- NETINFO     (Time and address info)   (See Sec 4.5)
389          9 -- RELAY_EARLY (End-to-end data; limited)(See Sec 5.6)
391     Variable-length command values are:
392          7 -- VERSIONS    (Negotiate proto version) (See Sec 4)
393          128 -- VPADDING  (Variable-length padding) (See Sec 7.2)
394          129 -- CERTS     (Certificates)            (See Sec 4.2)
395          130 -- AUTH_CHALLENGE (Challenge value)    (See Sec 4.3)
396          131 -- AUTHENTICATE (Client authentication)(See Sec 4.5)
397          132 -- AUTHORIZE (Client authorization)    (Not yet used)
399    The interpretation of 'Payload' depends on the type of the cell.
400       PADDING: Payload is unused.
401       CREATE:  Payload contains the handshake challenge.
402       CREATED: Payload contains the handshake response.
403       RELAY:   Payload contains the relay header and relay body.
404       DESTROY: Payload contains a reason for closing the circuit.
405                (see 5.4)
406    Upon receiving any other value for the command field, an OR must
407    drop the cell.  Since more cell types may be added in the future, ORs
408    should generally not warn when encountering unrecognized commands.
410    The payload is padded with 0 bytes.
412    PADDING cells are currently used to implement connection keepalive.
413    If there is no other traffic, ORs and OPs send one another a PADDING
414    cell every few minutes.
416    CREATE, CREATED, and DESTROY cells are used to manage circuits;
417    see section 5 below.
419    RELAY cells are used to send commands and data along a circuit; see
420    section 6 below.
422    VERSIONS and NETINFO cells are used to set up connections in link
423    protocols v2 and higher; in link protocol v3 and higher, CERTS,
424    AUTH_CHALLENGE, and AUTHENTICATE may also be used.  See section 4
425    below.
427 4. Negotiating and initializing connections
429    After Tor instances negotiate handshake with either the "renegotiation" or
430    "in-protocol" handshakes, they must exchange a set of cells to set up
431    the Tor connection and make it "open" and usable for circuits.
433    When the renegotiation handshake is used, both parties immediately
434    send a VERSIONS cell (4.1 below), and after negotiating a link
435    protocol version (which will be 2), each send a NETINFO cell (4.5
436    below) to confirm their addresses and timestamps.  No other intervening
437    cell types are allowed.
439    When the in-protocol handshake is used, the initiator sends a
440    VERSIONS cell to indicate that it will not be renegotiating.  The
441    responder sends a VERSIONS cell, a CERTS cell (4.2 below) to give the
442    initiator the certificates it needs to learn the responder's
443    identity, an AUTH_CHALLENGE cell (4.3) that the initiator must include
444    as part of its answer if it chooses to authenticate, and a NETINFO
445    cell (4.5).  As soon as it gets the CERTS cell, the initiator knows
446    whether the responder is correctly authenticated.  At this point the
447    initiator may send a NETINFO cell if it does not wish to
448    authenticate, or a CERTS cell, an AUTHENTICATE cell (4.4), and a NETINFO
449    cell if it does.  When this handshake is in use, the first cell must
450    be VERSIONS, VPADDING or AUTHORIZE, and no other cell type is allowed to
451    intervene besides those specified, except for PADDING and VPADDING cells.
453    The AUTHORIZE cell type is reserved for future use by scanning-resistance
454    designs.
456    [Tor versions before 0.2.3.11-alpha did not recognize the AUTHORIZE cell,
457    and did not permit any command other than VERSIONS as the first cell of
458    the in-protocol handshake.]
460 4.1. Negotiating versions with VERSIONS cells
462    There are multiple instances of the Tor link connection protocol.  Any
463    connection negotiated using the "certificates up front" handshake (see
464    section 2 above) is "version 1".  In any connection where both parties
465    have behaved as in the "renegotiation" handshake, the link protocol
466    version must be 2.  In any connection where both parties have behaved
467    as in the "in-protocol" handshake, the link protocol must be 3 or higher.
469    To determine the version, in any connection where the "renegotiation"
470    or "in-protocol" handshake was used (that is, where the responder
471    sent only one certificate at first and where the initiator did not
472    send any certificates in the first negotiation), both parties MUST
473    send a VERSIONS cell.  In "renegotiation", they send a VERSIONS cell
474    right after the renegotiation is finished, before any other cells are
475    sent.  In "in-protocol", the initiator sends a VERSIONS cell
476    immediately after the initial TLS handshake, and the responder
477    replies immediately with a VERSIONS cell.  Parties MUST NOT send any
478    other cells on a connection until they have received a VERSIONS cell.
480    The payload in a VERSIONS cell is a series of big-endian two-byte
481    integers.  Both parties MUST select as the link protocol version the
482    highest number contained both in the VERSIONS cell they sent and in the
483    versions cell they received.  If they have no such version in common,
484    they cannot communicate and MUST close the connection.
486    Since the version 1 link protocol does not use the "renegotiation"
487    handshake, implementations MUST NOT list version 1 in their VERSIONS
488    cell.  When the "renegotiation" handshake is used, implementations
489    MUST list only the version 2.  When the "in-protocol" handshake is
490    used, implementations MUST NOT list any version before 3, and SHOULD
491    list at least version 3.
493 4.2. CERTS cells
495    The CERTS cell describes the keys that a Tor instance is claiming
496    to have.  It is a variable-length cell.  Its payload format is:
498         N: Number of certs in cell            [1 octet]
499         N times:
500            CertType                           [1 octet]
501            CLEN                               [2 octets]
502            Certificate                        [CLEN octets]
504    Any extra octets at the end of a CERTS cell MUST be ignored.
506      CertType values are:
507         1: Link key certificate certified by RSA1024 identity
508         2: RSA1024 Identity certificate
509         3: RSA1024 AUTHENTICATE cell link certificate
511    The certificate format for the above certificate types is X509.
513    A CERTS cell may have no more than one certificate of each CertType.
515    To authenticate the responder, the initiator MUST check the following:
516      * The CERTS cell contains exactly one CertType 1 "Link" certificate.
517      * The CERTS cell contains exactly one CertType 2 "ID" certificate.
518      * Both certificates have validAfter and validUntil dates that
519        are not expired.
520      * The certified key in the Link certificate matches the
521        link key that was used to negotiate the TLS connection.
522      * The certified key in the ID certificate is a 1024-bit RSA key.
523      * The certified key in the ID certificate was used to sign both
524        certificates.
525      * The link certificate is correctly signed with the key in the
526        ID certificate
527      * The ID certificate is correctly self-signed.
528    Checking these conditions is sufficient to authenticate that the
529    initiator is talking to the Tor node with the expected identity,
530    as certified in the ID certificate.
532    To authenticate the initiator, the responder MUST check the
533    following:
534      * The CERTS cell contains exactly one CertType 3 "AUTH" certificate.
535      * The CERTS cell contains exactly one CertType 2 "ID" certificate.
536      * Both certificates have validAfter and validUntil dates that
537        are not expired.
538      * The certified key in the AUTH certificate is a 1024-bit RSA key.
539      * The certified key in the ID certificate is a 1024-bit RSA key.
540      * The certified key in the ID certificate was used to sign both
541        certificates.
542      * The auth certificate is correctly signed with the key in the
543        ID certificate.
544      * The ID certificate is correctly self-signed.
545    Checking these conditions is NOT sufficient to authenticate that the
546    initiator has the ID it claims; to do so, the cells in 4.3 and 4.4
547    below must be exchanged.
549 4.3. AUTH_CHALLENGE cells
551    An AUTH_CHALLENGE cell is a variable-length cell with the following
552    fields:
553        Challenge [32 octets]
554        N_Methods [2 octets]
555        Methods   [2 * N_Methods octets]
557    It is sent from the responder to the initiator. Initiators MUST
558    ignore unexpected bytes at the end of the cell.  Responders MUST
559    generate every challenge independently using a strong RNG or PRNG.
561    The Challenge field is a randomly generated string that the
562    initiator must sign (a hash of) as part of authenticating.  The
563    methods are the authentication methods that the responder will
564    accept.  Only one authentication method is defined right now:
565    see 4.4 below.
567 4.4. AUTHENTICATE cells
569    If an initiator wants to authenticate, it responds to the
570    AUTH_CHALLENGE cell with a CERTS cell and an AUTHENTICATE cell.
571    The CERTS cell is as a server would send, except that instead of
572    sending a CertType 1 cert for an arbitrary link certificate, the
573    client sends a CertType 3 cert for an RSA AUTHENTICATE key.
574    (This difference is because we allow any link key type on a TLS
575    link, but the protocol described here will only work for 1024-bit
576    RSA keys.  A later protocol version should extend the protocol
577    here to work with non-1024-bit, non-RSA keys.)
579    An AUTHENTICATE cell contains the following:
581         AuthType                              [2 octets]
582         AuthLen                               [2 octets]
583         Authentication                        [AuthLen octets]
585    Responders MUST ignore extra bytes at the end of an AUTHENTICATE
586    cell.  If AuthType is 1 (meaning "RSA-SHA256-TLSSecret"), then the
587    Authentication contains the following:
589        TYPE: The characters "AUTH0001" [8 octets]
590        CID: A SHA256 hash of the initiator's RSA1024 identity key [32 octets]
591        SID: A SHA256 hash of the responder's RSA1024 identity key [32 octets]
592        SLOG: A SHA256 hash of all bytes sent from the responder to the
593          initiator as part of the negotiation up to and including the
594          AUTH_CHALLENGE cell; that is, the VERSIONS cell, the CERTS cell,
595          the AUTH_CHALLENGE cell, and any padding cells.  [32 octets]
596        CLOG: A SHA256 hash of all bytes sent from the initiator to the
597          responder as part of the negotiation so far; that is, the
598          VERSIONS cell and the CERTS cell and any padding cells. [32
599          octets]
600        SCERT: A SHA256 hash of the responder's TLS link certificate. [32
601          octets]
602        TLSSECRETS: A SHA256 HMAC, using the TLS master secret as the
603          secret key, of the following:
604            - client_random, as sent in the TLS Client Hello
605            - server_random, as sent in the TLS Server Hello
606            - the NUL terminated ASCII string:
607              "Tor V3 handshake TLS cross-certification"
608           [32 octets]
609        TIME: The time of day in seconds since the POSIX epoch. [8 octets]
610        RAND: A 16 byte value, randomly chosen by the initiator [16 octets]
611        SIG: A signature of a SHA256 hash of all the previous fields
612          using the initiator's "Authenticate" key as presented.  (As
613          always in Tor, we use OAEP-MGF1 padding; see tor-spec.txt
614          section 0.3.)
615           [variable length]
617    To check the AUTHENTICATE cell, a responder checks that all fields
618    from TYPE through TLSSECRETS contain their unique
619    correct values as described above, and then verifies the signature.
620    signature.  The server MUST ignore any extra bytes in the signed
621    data after the SHA256 hash.
623 4.5. NETINFO cells
625    If version 2 or higher is negotiated, each party sends the other a
626    NETINFO cell.  The cell's payload is:
628          Timestamp              [4 bytes]
629          Other OR's address     [variable]
630          Number of addresses    [1 byte]
631          This OR's addresses    [variable]
633    The address format is a type/length/value sequence as given in section
634    6.4 below.  The timestamp is a big-endian unsigned integer number of
635    seconds since the Unix epoch.
637    Implementations MAY use the timestamp value to help decide if their
638    clocks are skewed.  Initiators MAY use "other OR's address" to help
639    learn which address their connections are originating from, if they do
640    not know it.  [As of 0.2.3.1-alpha, nodes use neither of these values.]
642    Initiators SHOULD use "this OR's address" to make sure
643    that they have connected to another OR at its canonical address.
644    (See 5.3.1 below.)
646 5. Circuit management
648 5.1. CREATE and CREATED cells
650    Users set up circuits incrementally, one hop at a time. To create a
651    new circuit, OPs send a CREATE cell to the first node, with the
652    first half of the DH handshake; that node responds with a CREATED
653    cell with the second half of the DH handshake plus the first 20 bytes
654    of derivative key data (see section 5.2). To extend a circuit past
655    the first hop, the OP sends an EXTEND relay cell (see section 5)
656    which instructs the last node in the circuit to send a CREATE cell
657    to extend the circuit.
659    The payload for a CREATE cell is an 'onion skin', which consists
660    of the first step of the DH handshake data (also known as g^x).
661    This value is hybrid-encrypted (see 0.3) to Bob's onion key, giving
662    an onion-skin of:
663        PK-encrypted:
664          Padding                       [PK_PAD_LEN bytes]
665          Symmetric key                 [KEY_LEN bytes]
666          First part of g^x             [PK_ENC_LEN-PK_PAD_LEN-KEY_LEN bytes]
667        Symmetrically encrypted:
668          Second part of g^x            [DH_LEN-(PK_ENC_LEN-PK_PAD_LEN-KEY_LEN)
669                                            bytes]
671    The relay payload for an EXTEND relay cell consists of:
672          Address                       [4 bytes]
673          Port                          [2 bytes]
674          Onion skin                    [DH_LEN+KEY_LEN+PK_PAD_LEN bytes]
675          Identity fingerprint          [HASH_LEN bytes]
677    The port and address field denote the IPv4 address and port of the next
678    onion router in the circuit; the public key hash is the hash of the PKCS#1
679    ASN1 encoding of the next onion router's identity (signing) key.  (See 0.3
680    above.)  Including this hash allows the extending OR verify that it is
681    indeed connected to the correct target OR, and prevents certain
682    man-in-the-middle attacks.
684    The payload for a CREATED cell, or the relay payload for an
685    EXTENDED cell, contains:
686          DH data (g^y)                 [DH_LEN bytes]
687          Derivative key data (KH)      [HASH_LEN bytes]   <see 5.2 below>
689    The CircID for a CREATE cell is an arbitrarily chosen 2-byte integer,
690    selected by the node (OP or OR) that sends the CREATE cell.  To prevent
691    CircID collisions, when one node sends a CREATE cell to another, it chooses
692    from only one half of the possible values based on the ORs' public
693    identity keys: if the sending node has a lower key, it chooses a CircID with
694    an MSB of 0; otherwise, it chooses a CircID with an MSB of 1.
696    (An OP with no public key MAY choose any CircID it wishes, since an OP
697    never needs to process a CREATE cell.)
699    Public keys are compared numerically by modulus.
701    As usual with DH, x and y MUST be generated randomly.
703 5.1.1. CREATE_FAST/CREATED_FAST cells
705    When initializing the first hop of a circuit, the OP has already
706    established the OR's identity and negotiated a secret key using TLS.
707    Because of this, it is not always necessary for the OP to perform the
708    public key operations to create a circuit.  In this case, the
709    OP MAY send a CREATE_FAST cell instead of a CREATE cell for the first
710    hop only.  The OR responds with a CREATED_FAST cell, and the circuit is
711    created.
713    A CREATE_FAST cell contains:
715        Key material (X)    [HASH_LEN bytes]
717    A CREATED_FAST cell contains:
719        Key material (Y)    [HASH_LEN bytes]
720        Derivative key data [HASH_LEN bytes] (See 5.2 below)
722    The values of X and Y must be generated randomly.
724    If an OR sees a circuit created with CREATE_FAST, the OR is sure to be the
725    first hop of a circuit.  ORs SHOULD reject attempts to create streams with
726    RELAY_BEGIN exiting the circuit at the first hop: letting Tor be used as a
727    single hop proxy makes exit nodes a more attractive target for compromise.
729 5.2. Setting circuit keys
731    Once the handshake between the OP and an OR is completed, both can
732    now calculate g^xy with ordinary DH.  Before computing g^xy, both parties
733    MUST verify that the received g^x or g^y value is not degenerate;
734    that is, it must be strictly greater than 1 and strictly less than p-1
735    where p is the DH modulus.  Implementations MUST NOT complete a handshake
736    with degenerate keys.  Implementations MUST NOT discard other "weak"
737    g^x values.
739    (Discarding degenerate keys is critical for security; if bad keys
740    are not discarded, an attacker can substitute the OR's CREATED
741    cell's g^y with 0 or 1, thus creating a known g^xy and impersonating
742    the OR. Discarding other keys may allow attacks to learn bits of
743    the private key.)
745    If CREATE or EXTEND is used to extend a circuit, both parties
746    base their key material on K0=g^xy, represented as a big-endian unsigned
747    integer.
749    If CREATE_FAST is used, both parties base their key material on
750    K0=X|Y.
752    From the base key material K0, they compute KEY_LEN*2+HASH_LEN*3 bytes of
753    derivative key data as
754        K = H(K0 | [00]) | H(K0 | [01]) | H(K0 | [02]) | ...
756    The first HASH_LEN bytes of K form KH; the next HASH_LEN form the forward
757    digest Df; the next HASH_LEN 41-60 form the backward digest Db; the next
758    KEY_LEN 61-76 form Kf, and the final KEY_LEN form Kb.  Excess bytes from K
759    are discarded.
761    KH is used in the handshake response to demonstrate knowledge of the
762    computed shared key. Df is used to seed the integrity-checking hash
763    for the stream of data going from the OP to the OR, and Db seeds the
764    integrity-checking hash for the data stream from the OR to the OP. Kf
765    is used to encrypt the stream of data going from the OP to the OR, and
766    Kb is used to encrypt the stream of data going from the OR to the OP.
768 5.3. Creating circuits
770    When creating a circuit through the network, the circuit creator
771    (OP) performs the following steps:
773       1. Choose an onion router as an exit node (R_N), such that the onion
774          router's exit policy includes at least one pending stream that
775          needs a circuit (if there are any).
777       2. Choose a chain of (N-1) onion routers
778          (R_1...R_N-1) to constitute the path, such that no router
779          appears in the path twice.
781       3. If not already connected to the first router in the chain,
782          open a new connection to that router.
784       4. Choose a circID not already in use on the connection with the
785          first router in the chain; send a CREATE cell along the
786          connection, to be received by the first onion router.
788       5. Wait until a CREATED cell is received; finish the handshake
789          and extract the forward key Kf_1 and the backward key Kb_1.
791       6. For each subsequent onion router R (R_2 through R_N), extend
792          the circuit to R.
794    To extend the circuit by a single onion router R_M, the OP performs
795    these steps:
797       1. Create an onion skin, encrypted to R_M's public onion key.
799       2. Send the onion skin in a relay EXTEND cell along
800          the circuit (see section 5).
802       3. When a relay EXTENDED cell is received, verify KH, and
803          calculate the shared keys.  The circuit is now extended.
805    When an onion router receives an EXTEND relay cell, it sends a CREATE
806    cell to the next onion router, with the enclosed onion skin as its
807    payload.  As special cases, if the extend cell includes a digest of
808    all zeroes, or asks to extend back to the relay that sent the extend
809    cell, the circuit will fail and be torn down. The initiating onion
810    router chooses some circID not yet used on the connection between the
811    two onion routers.  (But see section 5.1. above, concerning choosing
812    circIDs based on lexicographic order of nicknames.)
814    When an onion router receives a CREATE cell, if it already has a
815    circuit on the given connection with the given circID, it drops the
816    cell.  Otherwise, after receiving the CREATE cell, it completes the
817    DH handshake, and replies with a CREATED cell.  Upon receiving a
818    CREATED cell, an onion router packs it payload into an EXTENDED relay
819    cell (see section 5), and sends that cell up the circuit.  Upon
820    receiving the EXTENDED relay cell, the OP can retrieve g^y.
822    (As an optimization, OR implementations may delay processing onions
823    until a break in traffic allows time to do so without harming
824    network latency too greatly.)
826 5.3.1. Canonical connections
828    It is possible for an attacker to launch a man-in-the-middle attack
829    against a connection by telling OR Alice to extend to OR Bob at some
830    address X controlled by the attacker.  The attacker cannot read the
831    encrypted traffic, but the attacker is now in a position to count all
832    bytes sent between Alice and Bob (assuming Alice was not already
833    connected to Bob.)
835    To prevent this, when an OR we gets an extend request, it SHOULD use an
836    existing OR connection if the ID matches, and ANY of the following
837    conditions hold:
838        - The IP matches the requested IP.
839        - The OR knows that the IP of the connection it's using is canonical
840          because it was listed in the NETINFO cell.
841        - The OR knows that the IP of the connection it's using is canonical
842          because it was listed in the server descriptor.
844    [This is not implemented in Tor 0.2.0.23-rc.]
846 5.4. Tearing down circuits
848    Circuits are torn down when an unrecoverable error occurs along
849    the circuit, or when all streams on a circuit are closed and the
850    circuit's intended lifetime is over.  Circuits may be torn down
851    either completely or hop-by-hop.
853    To tear down a circuit completely, an OR or OP sends a DESTROY
854    cell to the adjacent nodes on that circuit, using the appropriate
855    direction's circID.
857    Upon receiving an outgoing DESTROY cell, an OR frees resources
858    associated with the corresponding circuit. If it's not the end of
859    the circuit, it sends a DESTROY cell for that circuit to the next OR
860    in the circuit. If the node is the end of the circuit, then it tears
861    down any associated edge connections (see section 6.1).
863    After a DESTROY cell has been processed, an OR ignores all data or
864    destroy cells for the corresponding circuit.
866    To tear down part of a circuit, the OP may send a RELAY_TRUNCATE cell
867    signaling a given OR (Stream ID zero).  That OR sends a DESTROY
868    cell to the next node in the circuit, and replies to the OP with a
869    RELAY_TRUNCATED cell.
871    [Note: If an OR receives a TRUNCATE cell and it has any RELAY cells
872    still queued on the circuit for the next node it will drop them
873    without sending them.  This is not considered conformant behavior,
874    but it probably won't get fixed until a later version of Tor.  Thus,
875    clients SHOULD NOT send a TRUNCATE cell to a node running any current
876    version of Tor if a) they have sent relay cells through that node,
877    and b) they aren't sure whether those cells have been sent on yes.]
879    When an unrecoverable error occurs along one connection in a
880    circuit, the nodes on either side of the connection should, if they
881    are able, act as follows:  the node closer to the OP should send a
882    RELAY_TRUNCATED cell towards the OP; the node farther from the OP
883    should send a DESTROY cell down the circuit.
885    The payload of a RELAY_TRUNCATED or DESTROY cell contains a single octet,
886    describing why the circuit is being closed or truncated.  When sending a
887    TRUNCATED or DESTROY cell because of another TRUNCATED or DESTROY cell,
888    the error code should be propagated.  The origin of a circuit always sets
889    this error code to 0, to avoid leaking its version.
891    The error codes are:
892      0 -- NONE            (No reason given.)
893      1 -- PROTOCOL        (Tor protocol violation.)
894      2 -- INTERNAL        (Internal error.)
895      3 -- REQUESTED       (A client sent a TRUNCATE command.)
896      4 -- HIBERNATING     (Not currently operating; trying to save bandwidth.)
897      5 -- RESOURCELIMIT   (Out of memory, sockets, or circuit IDs.)
898      6 -- CONNECTFAILED   (Unable to reach relay.)
899      7 -- OR_IDENTITY     (Connected to relay, but its OR identity was not
900                            as expected.)
901      8 -- OR_CONN_CLOSED  (The OR connection that was carrying this circuit
902                            died.)
903      9 -- FINISHED        (The circuit has expired for being dirty or old.)
904     10 -- TIMEOUT         (Circuit construction took too long)
905     11 -- DESTROYED       (The circuit was destroyed w/o client TRUNCATE)
906     12 -- NOSUCHSERVICE   (Request for unknown hidden service)
908 5.5. Routing relay cells
910    When an OR receives a RELAY or RELAY_EARLY cell, it checks the cell's
911    circID and determines whether it has a corresponding circuit along that
912    connection.  If not, the OR drops the cell.
914    Otherwise, if the OR is not at the OP edge of the circuit (that is,
915    either an 'exit node' or a non-edge node), it de/encrypts the payload
916    with the stream cipher, as follows:
917         'Forward' relay cell (same direction as CREATE):
918             Use Kf as key; decrypt.
919         'Back' relay cell (opposite direction from CREATE):
920             Use Kb as key; encrypt.
921    Note that in counter mode, decrypt and encrypt are the same operation.
923    The OR then decides whether it recognizes the relay cell, by
924    inspecting the payload as described in section 6.1 below.  If the OR
925    recognizes the cell, it processes the contents of the relay cell.
926    Otherwise, it passes the decrypted relay cell along the circuit if
927    the circuit continues.  If the OR at the end of the circuit
928    encounters an unrecognized relay cell, an error has occurred: the OR
929    sends a DESTROY cell to tear down the circuit.
931    When a relay cell arrives at an OP, the OP decrypts the payload
932    with the stream cipher as follows:
933          OP receives data cell:
934             For I=N...1,
935                 Decrypt with Kb_I.  If the payload is recognized (see
936                 section 6..1), then stop and process the payload.
938    For more information, see section 6 below.
940 5.6. Handling relay_early cells
942    A RELAY_EARLY cell is designed to limit the length any circuit can reach.
943    When an OR receives a RELAY_EARLY cell, and the next node in the circuit
944    is speaking v2 of the link protocol or later, the OR relays the cell as a
945    RELAY_EARLY cell.  Otherwise, older Tors will relay it as a RELAY cell.
947    If a node ever receives more than 8 RELAY_EARLY cells on a given
948    outbound circuit, it SHOULD close the circuit. (For historical reasons,
949    we don't limit the number of inbound RELAY_EARLY cells; they should
950    be harmless anyway because clients won't accept extend requests. See
951    bug 1038.)
953    When speaking v2 of the link protocol or later, clients MUST only send
954    EXTEND cells inside RELAY_EARLY cells.  Clients SHOULD send the first ~8
955    RELAY cells that are not targeted at the first hop of any circuit as
956    RELAY_EARLY cells too, in order to partially conceal the circuit length.
958    [Starting with Tor 0.2.3.11-alpha, future version of Tor, relays should
959    reject any EXTEND cell not received in a RELAY_EARLY cell.]
961 6. Application connections and stream management
963 6.1. Relay cells
965    Within a circuit, the OP and the exit node use the contents of
966    RELAY packets to tunnel end-to-end commands and TCP connections
967    ("Streams") across circuits.  End-to-end commands can be initiated
968    by either edge; streams are initiated by the OP.
970    The payload of each unencrypted RELAY cell consists of:
971          Relay command           [1 byte]
972          'Recognized'            [2 bytes]
973          StreamID                [2 bytes]
974          Digest                  [4 bytes]
975          Length                  [2 bytes]
976          Data                    [CELL_LEN-14 bytes]
978    The relay commands are:
979          1 -- RELAY_BEGIN     [forward]
980          2 -- RELAY_DATA      [forward or backward]
981          3 -- RELAY_END       [forward or backward]
982          4 -- RELAY_CONNECTED [backward]
983          5 -- RELAY_SENDME    [forward or backward] [sometimes control]
984          6 -- RELAY_EXTEND    [forward]             [control]
985          7 -- RELAY_EXTENDED  [backward]            [control]
986          8 -- RELAY_TRUNCATE  [forward]             [control]
987          9 -- RELAY_TRUNCATED [backward]            [control]
988         10 -- RELAY_DROP      [forward or backward] [control]
989         11 -- RELAY_RESOLVE   [forward]
990         12 -- RELAY_RESOLVED  [backward]
991         13 -- RELAY_BEGIN_DIR [forward]
993         32..40 -- Used for hidden services; see rend-spec.txt.
995    Commands labelled as "forward" must only be sent by the originator
996    of the circuit. Commands labelled as "backward" must only be sent by
997    other nodes in the circuit back to the originator. Commands marked
998    as either can be sent either by the originator or other nodes.
1000    The 'recognized' field in any unencrypted relay payload is always set
1001    to zero; the 'digest' field is computed as the first four bytes of
1002    the running digest of all the bytes that have been destined for
1003    this hop of the circuit or originated from this hop of the circuit,
1004    seeded from Df or Db respectively (obtained in section 5.2 above),
1005    and including this RELAY cell's entire payload (taken with the digest
1006    field set to zero).
1008    When the 'recognized' field of a RELAY cell is zero, and the digest
1009    is correct, the cell is considered "recognized" for the purposes of
1010    decryption (see section 5.5 above).
1012    (The digest does not include any bytes from relay cells that do
1013    not start or end at this hop of the circuit. That is, it does not
1014    include forwarded data. Therefore if 'recognized' is zero but the
1015    digest does not match, the running digest at that node should
1016    not be updated, and the cell should be forwarded on.)
1018    All RELAY cells pertaining to the same tunneled stream have the
1019    same stream ID.  StreamIDs are chosen arbitrarily by the OP.  RELAY
1020    cells that affect the entire circuit rather than a particular
1021    stream use a StreamID of zero -- they are marked in the table above
1022    as "[control]" style cells. (Sendme cells are marked as "sometimes
1023    control" because they can take include a StreamID or not depending
1024    on their purpose -- see Section 7.)
1026    The 'Length' field of a relay cell contains the number of bytes in
1027    the relay payload which contain real payload data. The remainder of
1028    the payload is padded with NUL bytes.
1030    If the RELAY cell is recognized but the relay command is not
1031    understood, the cell must be dropped and ignored. Its contents
1032    still count with respect to the digests, though.
1034 6.2. Opening streams and transferring data
1036    To open a new anonymized TCP connection, the OP chooses an open
1037    circuit to an exit that may be able to connect to the destination
1038    address, selects an arbitrary StreamID not yet used on that circuit,
1039    and constructs a RELAY_BEGIN cell with a payload encoding the address
1040    and port of the destination host.  The payload format is:
1042          ADDRESS | ':' | PORT | [00]
1044    where  ADDRESS can be a DNS hostname, or an IPv4 address in
1045    dotted-quad format, or an IPv6 address surrounded by square brackets;
1046    and where PORT is a decimal integer between 1 and 65535, inclusive.
1048    [What is the [00] for? -NM]
1049    [It's so the payload is easy to parse out with string funcs -RD]
1051    Upon receiving this cell, the exit node resolves the address as
1052    necessary, and opens a new TCP connection to the target port.  If the
1053    address cannot be resolved, or a connection can't be established, the
1054    exit node replies with a RELAY_END cell.  (See 6.4 below.)
1055    Otherwise, the exit node replies with a RELAY_CONNECTED cell, whose
1056    payload is in one of the following formats:
1057        The IPv4 address to which the connection was made [4 octets]
1058        A number of seconds (TTL) for which the address may be cached [4 octets]
1059     or
1060        Four zero-valued octets [4 octets]
1061        An address type (6)     [1 octet]
1062        The IPv6 address to which the connection was made [16 octets]
1063        A number of seconds (TTL) for which the address may be cached [4 octets]
1064    [XXXX No version of Tor currently generates the IPv6 format.]
1066    [Tor exit nodes before 0.1.2.0 set the TTL field to a fixed value.  Later
1067    versions set the TTL to the last value seen from a DNS server, and expire
1068    their own cached entries after a fixed interval.  This prevents certain
1069    attacks.]
1071    Once a connection has been established, the OP and exit node
1072    package stream data in RELAY_DATA cells, and upon receiving such
1073    cells, echo their contents to the corresponding TCP stream.
1075    If the exit node does not support optimistic data (i.e. its
1076    version number is before 0.2.3.1-alpha), then the OP MUST wait
1077    for a RELAY_CONNECTED cell before sending any data.  If the exit
1078    node supports optimistic data (i.e. its version number is
1079    0.2.3.1-alpha or later), then the OP MAY send RELAY_DATA cells
1080    immediately after sending the RELAY_BEGIN cell (and before
1081    receiving either a RELAY_CONNECTED or RELAY_END cell).
1083    RELAY_DATA cells sent to unrecognized streams are dropped.  If
1084    the exit node supports optimistic data, then RELAY_DATA cells it
1085    receives on streams which have seen RELAY_BEGIN but have not yet
1086    been replied to with a RELAY_CONNECTED or RELAY_END are queued.
1087    If the stream creation succeeds with a RELAY_CONNECTED, the queue
1088    is processed immediately afterwards; if the stream creation fails
1089    with a RELAY_END, the contents of the queue are deleted.
1091    Relay RELAY_DROP cells are long-range dummies; upon receiving such
1092    a cell, the OR or OP must drop it.
1094 6.2.1. Opening a directory stream
1096    If a Tor relay is a directory server, it should respond to a
1097    RELAY_BEGIN_DIR cell as if it had received a BEGIN cell requesting a
1098    connection to its directory port.  RELAY_BEGIN_DIR cells ignore exit
1099    policy, since the stream is local to the Tor process.
1101    If the Tor relay is not running a directory service, it should respond
1102    with a REASON_NOTDIRECTORY RELAY_END cell.
1104    Clients MUST generate an all-zero payload for RELAY_BEGIN_DIR cells,
1105    and relays MUST ignore the payload.
1107    [RELAY_BEGIN_DIR was not supported before Tor 0.1.2.2-alpha; clients
1108    SHOULD NOT send it to routers running earlier versions of Tor.]
1110 6.3. Closing streams
1112    When an anonymized TCP connection is closed, or an edge node
1113    encounters error on any stream, it sends a 'RELAY_END' cell along the
1114    circuit (if possible) and closes the TCP connection immediately.  If
1115    an edge node receives a 'RELAY_END' cell for any stream, it closes
1116    the TCP connection completely, and sends nothing more along the
1117    circuit for that stream.
1119    The payload of a RELAY_END cell begins with a single 'reason' byte to
1120    describe why the stream is closing, plus optional data (depending on
1121    the reason.)  The values are:
1123        1 -- REASON_MISC           (catch-all for unlisted reasons)
1124        2 -- REASON_RESOLVEFAILED  (couldn't look up hostname)
1125        3 -- REASON_CONNECTREFUSED (remote host refused connection) [*]
1126        4 -- REASON_EXITPOLICY     (OR refuses to connect to host or port)
1127        5 -- REASON_DESTROY        (Circuit is being destroyed)
1128        6 -- REASON_DONE           (Anonymized TCP connection was closed)
1129        7 -- REASON_TIMEOUT        (Connection timed out, or OR timed out
1130                                    while connecting)
1131        8 -- REASON_NOROUTE        (Routing error while attempting to
1132                                    contact destination)
1133        9 -- REASON_HIBERNATING    (OR is temporarily hibernating)
1134       10 -- REASON_INTERNAL       (Internal error at the OR)
1135       11 -- REASON_RESOURCELIMIT  (OR has no resources to fulfill request)
1136       12 -- REASON_CONNRESET      (Connection was unexpectedly reset)
1137       13 -- REASON_TORPROTOCOL    (Sent when closing connection because of
1138                                    Tor protocol violations.)
1139       14 -- REASON_NOTDIRECTORY   (Client sent RELAY_BEGIN_DIR to a
1140                                    non-directory relay.)
1142    (With REASON_EXITPOLICY, the 4-byte IPv4 address or 16-byte IPv6 address
1143    forms the optional data, along with a 4-byte TTL; no other reason
1144    currently has extra data.)
1146    OPs and ORs MUST accept reasons not on the above list, since future
1147    versions of Tor may provide more fine-grained reasons.
1149    Tors SHOULD NOT send any reason except REASON_MISC for a stream that they
1150    have originated.
1152    [*] Older versions of Tor also send this reason when connections are
1153        reset.
1155    --- [The rest of this section describes unimplemented functionality.]
1157    Because TCP connections can be half-open, we follow an equivalent
1158    to TCP's FIN/FIN-ACK/ACK protocol to close streams.
1160    An exit connection can have a TCP stream in one of three states:
1161    'OPEN', 'DONE_PACKAGING', and 'DONE_DELIVERING'.  For the purposes
1162    of modeling transitions, we treat 'CLOSED' as a fourth state,
1163    although connections in this state are not, in fact, tracked by the
1164    onion router.
1166    A stream begins in the 'OPEN' state.  Upon receiving a 'FIN' from
1167    the corresponding TCP connection, the edge node sends a 'RELAY_FIN'
1168    cell along the circuit and changes its state to 'DONE_PACKAGING'.
1169    Upon receiving a 'RELAY_FIN' cell, an edge node sends a 'FIN' to
1170    the corresponding TCP connection (e.g., by calling
1171    shutdown(SHUT_WR)) and changing its state to 'DONE_DELIVERING'.
1173    When a stream in already in 'DONE_DELIVERING' receives a 'FIN', it
1174    also sends a 'RELAY_FIN' along the circuit, and changes its state
1175    to 'CLOSED'.  When a stream already in 'DONE_PACKAGING' receives a
1176    'RELAY_FIN' cell, it sends a 'FIN' and changes its state to
1177    'CLOSED'.
1179    If an edge node encounters an error on any stream, it sends a
1180    'RELAY_END' cell (if possible) and closes the stream immediately.
1182 6.4. Remote hostname lookup
1184    To find the address associated with a hostname, the OP sends a
1185    RELAY_RESOLVE cell containing the hostname to be resolved with a NUL
1186    terminating byte. (For a reverse lookup, the OP sends a RELAY_RESOLVE
1187    cell containing an in-addr.arpa address.) The OR replies with a
1188    RELAY_RESOLVED cell containing a status byte, and any number of
1189    answers. Each answer is of the form:
1190        Type   (1 octet)
1191        Length (1 octet)
1192        Value  (variable-width)
1193        TTL    (4 octets)
1194    "Length" is the length of the Value field.
1195    "Type" is one of:
1196       0x00 -- Hostname
1197       0x04 -- IPv4 address
1198       0x06 -- IPv6 address
1199       0xF0 -- Error, transient
1200       0xF1 -- Error, nontransient
1202     If any answer has a type of 'Error', then no other answer may be given.
1204     The RELAY_RESOLVE cell must use a nonzero, distinct streamID; the
1205     corresponding RELAY_RESOLVED cell must use the same streamID.  No stream
1206     is actually created by the OR when resolving the name.
1208 7. Flow control
1210 7.1. Link throttling
1212    Each client or relay should do appropriate bandwidth throttling to
1213    keep its user happy.
1215    Communicants rely on TCP's default flow control to push back when they
1216    stop reading.
1218    The mainline Tor implementation uses token buckets (one for reads,
1219    one for writes) for the rate limiting.
1221    Since 0.2.0.x, Tor has let the user specify an additional pair of
1222    token buckets for "relayed" traffic, so people can deploy a Tor relay
1223    with strict rate limiting, but also use the same Tor as a client. To
1224    avoid partitioning concerns we combine both classes of traffic over a
1225    given OR connection, and keep track of the last time we read or wrote
1226    a high-priority (non-relayed) cell. If it's been less than N seconds
1227    (currently N=30), we give the whole connection high priority, else we
1228    give the whole connection low priority. We also give low priority
1229    to reads and writes for connections that are serving directory
1230    information. See proposal 111 for details.
1232 7.2. Link padding
1234    Link padding can be created by sending PADDING or VPADDING cells
1235    along the connection; relay cells of type "DROP" can be used for
1236    long-range padding.  The contents of a PADDING, VPADDING, or DROP
1237    cell SHOULD be chosen randomly, and MUST be ignored.
1239    Currently nodes are not required to do any sort of link padding or
1240    dummy traffic. Because strong attacks exist even with link padding,
1241    and because link padding greatly increases the bandwidth requirements
1242    for running a node, we plan to leave out link padding until this
1243    tradeoff is better understood.
1245 7.3. Circuit-level flow control
1247    To control a circuit's bandwidth usage, each OR keeps track of two
1248    'windows', consisting of how many RELAY_DATA cells it is allowed to
1249    originate (package for transmission), and how many RELAY_DATA cells
1250    it is willing to consume (receive for local streams).  These limits
1251    do not apply to cells that the OR receives from one host and relays
1252    to another.
1254    Each 'window' value is initially set based on the consensus parameter
1255    'circwindow' in the directory (see dir-spec.txt), or to 1000 data cells
1256    if no 'circwindow' value is given,
1257    in each direction (cells that are not data cells do not affect
1258    the window).  When an OR is willing to deliver more cells, it sends a
1259    RELAY_SENDME cell towards the OP, with Stream ID zero.  When an OR
1260    receives a RELAY_SENDME cell with stream ID zero, it increments its
1261    packaging window.
1263    Each of these cells increments the corresponding window by 100.
1265    The OP behaves identically, except that it must track a packaging
1266    window and a delivery window for every OR in the circuit.
1268    An OR or OP sends cells to increment its delivery window when the
1269    corresponding window value falls under some threshold (900).
1271    If a packaging window reaches 0, the OR or OP stops reading from
1272    TCP connections for all streams on the corresponding circuit, and
1273    sends no more RELAY_DATA cells until receiving a RELAY_SENDME cell.
1274 [this stuff is badly worded; copy in the tor-design section -RD]
1276 7.4. Stream-level flow control
1278    Edge nodes use RELAY_SENDME cells to implement end-to-end flow
1279    control for individual connections across circuits. Similarly to
1280    circuit-level flow control, edge nodes begin with a window of cells
1281    (500) per stream, and increment the window by a fixed value (50)
1282    upon receiving a RELAY_SENDME cell. Edge nodes initiate RELAY_SENDME
1283    cells when both a) the window is <= 450, and b) there are less than
1284    ten cell payloads remaining to be flushed at that edge.
1286 A.1. Differences between spec and implementation
1288 - The current specification requires all ORs to have IPv4 addresses, but
1289   allows relays to exit and resolve to IPv6 addresses, and to declare IPv6
1290   addresses in their exit policies.  The current codebase has no IPv6
1291   support at all.