authenticate_safecookie

Function authenticate_safecookie 

Source
pub async fn authenticate_safecookie(
    socket: &mut ControlSocket,
    path: &Path,
) -> Result<(), Error>
Expand description

Authenticates using the SAFECOOKIE challenge-response protocol.

This is the most secure cookie-based authentication method, available in Tor 0.2.3+. It uses HMAC-SHA256 challenge-response to prevent replay attacks where an attacker captures and reuses the cookie value.

§Protocol Steps

  1. Client generates a random 32-byte nonce
  2. Client sends AUTHCHALLENGE SAFECOOKIE <client_nonce>
  3. Server responds with SERVERHASH and SERVERNONCE
  4. Client verifies SERVERHASH using HMAC-SHA256
  5. Client computes its own hash and sends AUTHENTICATE <client_hash>

§Preconditions

  • The socket must be connected
  • Tor must support SAFECOOKIE (version 0.2.3+)
  • The cookie file must exist and be readable
  • The cookie file must be exactly 32 bytes

§Postconditions

  • On success: The socket is authenticated
  • On failure: Tor may disconnect the socket

§Arguments

  • socket - A connected control socket
  • path - Path to the authentication cookie file

§Errors

Returns Error::Authentication with:

§Security Advantages

Unlike plain cookie authentication, SAFECOOKIE:

  • Prevents replay attacks (nonces are unique per session)
  • Provides mutual authentication (client verifies server)
  • Uses constant-time comparison for cryptographic values

§Example

use stem_rs::auth::authenticate_safecookie;
use stem_rs::ControlSocket;
use std::path::Path;

let mut socket = ControlSocket::connect_port("127.0.0.1:9051".parse()?).await?;
let cookie_path = Path::new("/var/run/tor/control.authcookie");
authenticate_safecookie(&mut socket, cookie_path).await?;

§HMAC Details

The HMAC keys are fixed strings defined by the Tor specification:

  • Server hash: "Tor safe cookie authentication server-to-controller hash"
  • Client hash: "Tor safe cookie authentication controller-to-server hash"