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
- Client generates a random 32-byte nonce
- Client sends
AUTHCHALLENGE SAFECOOKIE <client_nonce> - Server responds with
SERVERHASHandSERVERNONCE - Client verifies
SERVERHASHusing HMAC-SHA256 - 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 socketpath- Path to the authentication cookie file
§Errors
Returns Error::Authentication with:
AuthError::CookieUnreadable: Cannot read the cookie fileAuthError::IncorrectCookieSize: Cookie file is not 32 bytesAuthError::ChallengeUnsupported: Tor doesn’t support AUTHCHALLENGEAuthError::ChallengeFailed: Server hash verification failed or auth rejected
§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"