<a id="tor-spec.txt-4"></a>

# Negotiating and initializing channels {#negotiating}

Here we describe the primary TLS behavior
used by Tor relays and clients to create a new channel.
There are older versions of these handshakes,
which we describe in [another section](./obsolete-channels.md).

In brief:
 - The initiator starts the handshake
   by [opening a TLS connection](#tls).
 - Both parties send a [VERSIONS](#VERSIONS-cells)
   to negotiate the protocol version to use.
 - The responder sends a
   [CERTS cell](#CERTS-cells) to give the
   initiator the certificates it needs to learn the responder's
   identity, an [AUTH_CHALLENGE cell](#AUTH-CHALLENGE-cells)
   that the initiator must include
   as part of its answer if it chooses to authenticate, and a
   [NETINFO cell](#NETINFO-cells)
   to establish clock skew and IP addresses.
 - The initiator checks whether the CERTS cell is correct,
   and decides whether to authenticate.
 - If the initiator
   [is not authenticating itself](./channels.md#does-initiator-authenticate),
   it sends a [NETINFO cell](#NETINFO-cells).
 - If the initiator
   [is authenticating itself](./channels.md#does-initiator-authenticate),
   it sends a [CERTS cell](#CERTS-cells),
   an [AUTHENTICATE cell](#AUTHENTICATE-cells),
   a [NETINFO cell](#NETINFO-cells).

When this handshake is in use,
the first cell must be VERSIONS, VPADDING, or AUTHORIZE,
and no other cell type is allowed to intervene besides those specified,
except for VPADDING cells.

(The AUTHORIZE cell type is reserved for future use
by scanning-resistance designs.
It is not specified here.)

```mermaid
sequenceDiagram
   Initiator --> Responder: TLS Handshake

   Note over Initiator,Responder: The rest is encrypted

   Initiator ->> Responder: VERSIONS
   Responder ->> Initiator: VERSIONS, CERTS, AUTH_CHALLENGE, NETINFO

   opt if the initiator is authenticating
      Initiator ->> Responder: CERTS, AUTHENTICATE
   end

   Initiator ->> Responder: NETINFO
```



## The TLS handshake {#tls}

<span id="in-protocol">The
initiator must send a ciphersuite list containing
at least one ciphersuite other than
[those listed in the obsolete v1 handshake](./obsolete-channels.md#v1-ciphersuite-list).
</span>

> This is trivially achieved
> by using any modern TLS implementation,
> and most implementations will not need to worry about it.
> 
> This requirement distinguishes the current protocol
> (sometimes called the "in-protocol" or "v3" handshake)
> from the obsolete v1 protocol.

<a id="tor-spec.txt-2.2"></a>

### TLS security considerations

(Standard TLS security guarantees apply;
this is not a comprehensive guide.)

Implementations SHOULD NOT allow TLS session resumption -- it can
exacerbate some attacks (e.g. the "Triple Handshake" attack from
Feb 2013), and it plays havoc with forward secrecy guarantees.

Implementations SHOULD NOT allow TLS compression -- although we don't
know a way to apply a CRIME-style attack to current Tor directly,
it's a waste of resources.

<a id="tor-spec.txt-4.1"></a>

## Negotiating versions with VERSIONS cells {#VERSIONS-cells}

There are multiple instances of the Tor channel protocol.

Once the TLS handshake is complete,
both parties send a VERSIONS cell
to negotiate which one they will use.

The body in a VERSIONS cell is a series of big-endian two-byte
integers.
Both parties MUST select as the link protocol version the
highest number contained both in the VERSIONS cell they sent and in the
VERSIONS cell they received.
If they have no such version in common,
they cannot communicate and MUST close the connection.
Either party MUST
close the connection if the VERSIONS cell is not well-formed (for example,
if the body contains an odd number of bytes).

Any VERSIONS cells sent after the first VERSIONS cell MUST be ignored.
(To be interpreted correctly, later VERSIONS cells MUST have a CIRCID_LEN
matching the version negotiated with the first VERSIONS cell.)

> (The
> [obsolete v1 channel protocol](./obsolete-channels.md#v1-handshake)
> does note VERSIONS cells.
> Implementations MUST NOT list version 1 in their VERSIONS cells.
> The
> [obsolete v2 channel protocol](./obsolete-channels.md#v2-handshake)
> can only be used after renegotiation;
> implementations MUST NOT list version 2 in their VERSIONS cells
> unless they have renegotiated the TLS session.)

The currently specified [Link](./subprotocol-versioning.md#link) protocols are:

| Version | Description
| ------- | -----------
| 1       | (Obsolete) The ["certs up front"](./obsolete-channels.md#v1-handshake) handshake.
| 2       | (Obsolete) Uses the [renegotiation-based handshake](./obsolete-channels.md#v2-handshake). Introduces variable-length cells.
| 3       | Uses the [current ("in-protocol") handshake](#in-protocol).  Must always be advertised.
| 4       | Increases circuit ID width to 4 bytes.
| 5       | Adds support for [link padding](../padding-spec) and negotiation.


<a id="tor-spec.txt-4.2"></a>

## CERTS cells {#CERTS-cells}

The CERTS cell describes the keys
that a Tor instance is claiming to have,
and provides certificates to authenticate that those keys
belong, ultimately, to one or more
[identity keys](./relay-keys.md#identity).

CERTS is a variable-length cell.  Its body format is:

| Field         | Size | Description                    |
| -----         | ---- | ------------------------------ |
| N             | 1    | Number of certificates in cell |
| N times:      |      |                                |
| - CertType    | 1    | Type of certificate            |
| - CertLen     | 2    | Length of "Certificate" field  |
| - Certificate | CertLen | Encoded certificate         |

Any extra octets at the end of a CERTS cell MUST be ignored.

The CertType field determines
the format of the certificate,
and the roles of its keys within the Tor protcol.
Recognized values are defined in
["Certificate types (CERT_TYPE field)"](../cert-spec.md#list-cert-types).

A CERTS cell MUST have no more than one certificate of any CertType.

### Authenticating the responder from its CERTS {#auth-responder}

The responder's CERTS cell is as follows:

- The CERTS cell contains exactly one CertType 4 Ed25519
  `IDENTITY_V_SIGNING_CERT`.
  - This cert must be self-signed;
    the signing key must be included in a
    ["signed-with-ed25519-key" extension](../cert-spec.md#signed-with-ed25519)
    extension.
    This signing key is `KP_relayid_ed`.
    The subject key is `KP_relaysign_ed`.
- The CERTS cell contains exactly one CertType 5 Ed25519
  `SIGNING_V_TLS_CERT` certificate.
  - This cert must be signed with `KP_relaysign_ed`.
    Its subject must be the SHA-256 digest
    of the TLS certificate
    that was presented curing the TLS handshake.
- All of the certs above must be correctly signed, and not expired.

The initiator must check all of the above.
If this is successful
the initiator knows that the responder
has the identity `KP_relayid_ed`.

> The responder's CERTS cell is meant to prove
> that the responder posses one or more
> [relay identities](./relay-keys.md#identity).
> It does this by containing certificate chains
> from each relay identity key
> to the TLS certificate presented during the TLS handshake.

> The responder's ownership of that TLS certificate
> was already proven during the TLS hadnshake itself.

### Validating an initiator's CERTS {#validate-initiator-certs}

When required
by [other parts of this specification](./channels.md#does-initiator-authenticate);
to prove its identity,
the initiator must provide a CERTS cell.

> Recall that
> [not all initiators authenticate themselves](./channels.md#does-initiator-authenticate);
> bridges and clients do not prove their identity.

The initiator's CERTS cell must conform to the rules
for the responder's CERTS cell (see above,
exchanging "initiator" and "responder")
except that:

**Instead** of containg a `SIGNING_V_TLS_CERT`,

- The CERTS cell contains exactly one CertType 6
  `SIGNING_V_LINK_AUTH` certificate.
  - This certificate must be signed with `KP_relayid_ed`.
    (Its subject key is deemed to be `KP_link_ed`.)
- All of the certs above must be correctly signed, and not expired.

The responder must check all of the CERTS cell's properties
(as stated here, and in the previous section).
If this is successful
**and**
the initiator later sends a valid
[AUTHENTICATE cell](#AUTHENTICATE-cells),
then the initiator has ownership of the presented `KP_relayid_ed`.

> Note that
> the CERTS cell is _not_ yet sufficent to authenticate the channel,
> until AUTHENTICATE is received:
> unlike the responder,
> the initiator is not required to present a TLS certificate
> during the TLS handshake.
> Therefore, the initiator has
> no meaningful `SIGNING_V_TLS_CERT` certificate.
>
> Therefore, instead, the initiator's CERTS cell
> proves a chain from the initiator's relay identities
> to a "link authentication" key.
> This key is later used to sign an "authentication challenge",
> and bind it to the channel.

### Authenticating an RSA identity (#auth-RSA)

After processing a CERTS cell
to find the other party's
`KP_relayid_ed` Ed25519 identity key,
a Tor instance MAY *additionally* check the CERTS cell
to find the other party's
`KP_relayid_rsa` legacy RSA identity key.

A party with a given `KP_relayid_ed` identity key
also has a given `KP_relayid_rsa` legacy identity key
when all of the following are true.
(A party MUST NOT conclude that an RSA identity key
is associated with a channel
without checking these properties.)

- The CERTS cell contains exactly one CertType 2
  `RSA_ID_X509` certificate.
  - This must be a self-signed certificate containing a 1024-bit RSA key;
    that key's exponent must be 65537.
    That key is `KP_relayid_rsa`.
- The CERTS cell contains exactly one CertType 7
  `RSA_ID_V_IDENTITY` certificate.
  - This certificate must be signed with `KP_relayid_rsa`.
  - This certificate's subject key must be the same
    as an already-authenticated `KP_relayid_ed`.
- All of the certs above must be correctly signed,
  not expired,
  and not before their `validAfter` dates.

If the above tests all pass,
then any relay which can prove it has the the identity `KP_relayid_ed`
also has the legacy identity `KP_relayid_rsa`.


<a id="tor-spec.txt-4.3"></a>

## AUTH_CHALLENGE cells{#AUTH-CHALLENGE-cells}

An AUTH_CHALLENGE cell is a variable-length cell with the following
fields:

| Field     | Size
| -----     | ----
| Challenge | 32 octets
| N_Methods | 2 octets
| Methods   | 2 * N_Methods octets

It is sent from the responder to the initiator.
Initiators MUST ignore unexpected bytes at the end of the cell.
Responders MUST generate every challenge independently.

The Challenge field is
a [randomly generated](./preliminaries.md#random-values)
binary string that the initiator must sign (a hash of)
as part of their [AUTHENTICATE cell](#AUTHENTICATE-cells).

The Methods are a list of authentication methods
that the responder will accept.
These methods are defined:

| Type      | Method |
| --------- | ------ |
| `[00 01]` | [RSA-SHA256-TLSSecret] (Obsolete) |
| `[00 02]` | (Historical, never implemented)   |
| `[00 03]` | [Ed25519-SHA256-RFC5705]          |


[RSA-SHA256-TLSSecret]: ./obsolete-channels.md#RSA-SHA256-TLSSecret
[Ed25519-SHA256-RFC5705]: #Ed25519-SHA256-RFC5705

<a id="tor-spec.txt-4.4"></a>

## AUTHENTICATE cells{#AUTHENTICATE-cells}

To authenticate, an initiator MUST
it respond to the AUTH_CHALLENGE cell
with a CERTS cell and an AUTHENTICATE cell.

> Recall that initiators are
> [not always required to authenticate](./channels.md#does-initiator-authenticate).
>
> ([As discussed above](#validate-initiator-certs),
> the initiator's CERTS cell differs slightly
> from what a responder would send.)

An AUTHENTICATE cell contains the following:

| Field           | Size
| -----           | ----
| AuthType        | 2
| AuthLen         | 2
| Authentication  | AuthLen

Responders MUST ignore extra bytes at the end of an AUTHENTICATE
cell.

The `AuthType` value corresponds to one of the
authentication methods.
The initiator MUST NOT send an AUTHENTICATE cell
whose AuthType was not contained
in the responder's AUTH_CHALLENGE.

An initiator MUST NOT send an AUTHENTICATE
cell before it has verified the certificates
presented in the responder's CERTS cell,
and authenticated the responder.

<a id="tor-spec.txt-4.4.2"></a>

### Link authentication type 3: Ed25519-SHA256-RFC5705 {#Ed25519-SHA256-RFC5705}

If AuthType is `[00 03]`,
meaning "Ed25519-SHA256-RFC5705",
the Authentication field of the AUTHENTICATE cell is as follows

Modified values and new fields below are marked with asterisks.

| Field      | Size | Summary |
| ---------  | ---- | ----------- |
| `TYPE`     | 8    | The nonterminated string `AUTH0003` |
| `CID`      | 32   | `SHA256(KP_relayid_rsa)` for initiator |
| `SID`      | 32   | `SHA256(KP_relayid_rsa)` for responder |
| `CID_ED`   | 32   | `KP_relayid_ed` for initiator |
| `SID_ED`   | 32   | `KP_relayid_ed` for responder |
| `SLOG`     | 32   | Responder log digest, SHA256 |
| `CLOG`     | 32   | Initiator log digest, SHA256 |
| `SCERT`    | 32   | SHA256 of responder's TLS certificate |
| `TLSSECRETS`|32   | RFC5705 information |
| `RAND`     | 24   | [Random bytes] |
| `SIG`      | 64   | Ed25519 signature |


- The `TYPE` string distinguishes this authentication document from others.
  It must be the nonterminated 8-byte string `AUTH0003`.
- For `CID` and `SID`, the SHA256 digest of an RSA key
  is computed as the SHA256 digest of its asn.1 encoding.
- The `SLOG`  field is computed
  as the SHA256 digest
  of all bytes sent within the TLS channel up to and including
  the AUTH_CHALLENGE cell.
  - This includes the VERSIONS cell,
    the CERTS cell,
    the AUTH_CHALLENGE cell,
    and any padding cells.
- The `CLOG` field is computed
  as the SHA256 digest
  of all bytes sent within the TLS channel up to but not including
  the AUTHENTICATE cell.
  - This includes the VERSIONS cell,
    the CERTS cell, and any padding cells.
- The `SCERT` field holds the SHA256 digest
  of the X.509 certificate presented by the responder
  as part of the TLS negotiation.
- The `TLSSECRETS` field is computed
  as the output of a Keying Material Exporter function
  on the TLS section.
  - The parameters for this exporter are:
    - Label string: "EXPORTER FOR TOR TLS CLIENT BINDING AUTH0003"
    - Context value: The initiator's `KP_relayid_ed`.
    - Length: 32.
  - For keying material exporters on TLS 1.3,
    see [RFC 8446 Section 7.5].
  - For keying material exporters on older TLS versions,
    see [RFC5705].
- The `RAND` field is a uniform squence of [Random bytes].
- The `SIG` field is an Ed25519 signature
  of all earlier members in the Authentication
  (from `TYPE` through `RAND`)
  using `KS_link_ed`.


[Random bytes]: ./preliminaries.md#random-values
[RFC 8446 Section 7.5]: https://datatracker.ietf.org/doc/html/rfc8446#section-7.5
[RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705.


To check an AUTHENTICATE cell,
a responder checks that all fields from TYPE through TLSSECRETS
contain their unique correct values as described above,
and then verifies the signature.
The responder MUST ignore any extra bytes in the signed data after
the RAND field.

<!-- TODO: We should consider removing that last sentence. -->

<a id="tor-spec.txt-4.5"></a>

## NETINFO cells {#NETINFO-cells}

To finish the handshake,
each party sends the other
a NETINFO cell.

A NETINFO cell's body is:

| Field            | Description                   | Size
| -----            | -----------                   | ----
| TIME             | Timestamp                     | 4 bytes
| OTHERADDR:       | Other party's address         |
| - ATYPE          | Address type                  | 1 byte
| - ALEN           | Address length                | 1 byte
| - AVAL           | Address value                 | ALEN bytes
| NMYADDR          | Number of this party's addresses | 1 byte
| NMYADDR times:   |                               |
| - ATYPE          | Address type                  | 1 byte
| - ALEN           | Address length                | 1 byte
| - AVAL           | Address value                 | ALEN bytes

Recognized address types (ATYPE) are:

| ATYPE | Description
| ----- | -----------
| 0x04  | IPv4
| 0x06  | IPv6

Implementations SHOULD ignore addresses with unrecognized types.

ALEN MUST be 4 when ATYPE is 0x04 (IPv4)
and 16 when ATYPE is 0x06 (IPv6).
If the ALEN value is wrong for the given ATYPE value, then
the provided address should be ignored.

The `OTHERADDR` field SHOULD be set to the actual IP address
observed for the other party.

> (This is typically the address passed to `connect()`
> when acting as the channel initiator,
> or the address received from `accept()`
> when acting as the channel responder.)

In the `ATYPE`/`ALEN`/`AVAL` fields,
relays SHOULD send the addresses that they have advertised
in their router descriptors.
Bridges and clients SHOULD send none of their own addresses.

For the `TIME` field,
relays send a (big-endian) integer
holding the number of seconds since the Unix epoch.
Clients SHOULD send `[00 00 00 00]` as their timestamp,
to avoid fingerprinting.

> See [proposal 338](../proposals/338-netinfo-y2038.md)
> for a proposal to extend the timestamp to 8 bytes.

Implementations MUST ignore unexpected bytes at the end of the NETINFO cell.

### Using information from NETINFO cells {#using-netinfo}

Implementations MAY use the timestamp value to help decide if their
clocks are skewed.

Initiators MAY use "other OR's address" field
to help learn which address their connections may be originating from,
if they do not know it;
and to learn whether the peer will treat the current connection as
canonical.
(See [Canonical connections](./creating-circuits.md#canonical-connections))

Implementations SHOULD NOT trust these values unconditionally,
especially when they come from non-authorities,
since the other party can lie about the time
or the IP addresses it sees.

Initiators SHOULD use "this OR's address" to make sure
that they have connected to another OR at its
[canonical address](./creating-circuits.md#canonical-connections).
