pub async fn authenticate(
socket: &mut ControlSocket,
password: Option<&str>,
) -> Result<(), Error>Expand description
Authenticates to Tor using the best available method.
This function queries Tor for supported authentication methods via
get_protocol_info, then attempts authentication using the most secure
available method in this order:
- NONE - If no authentication is required
- SAFECOOKIE - HMAC challenge-response (most secure)
- COOKIE - Cookie file contents
- PASSWORD - If a password is provided
§Preconditions
- The socket must be connected but not yet authenticated
- For password authentication,
passwordmust beSome
§Postconditions
- On success: The socket is authenticated and ready for commands
- On failure: The socket state is undefined; reconnection is recommended
§Arguments
socket- A connected control socketpassword- Optional password for PASSWORD authentication
§Errors
Returns Error::Authentication with specific AuthError variants:
AuthError::NoMethods: No compatible auth methods availableAuthError::MissingPassword: PASSWORD auth required but no password providedAuthError::IncorrectPassword: PASSWORD auth failedAuthError::CookieUnreadable: Cannot read cookie fileAuthError::IncorrectCookie: COOKIE auth failedAuthError::ChallengeFailed: SAFECOOKIE challenge failed
§Example
use stem_rs::auth::authenticate;
use stem_rs::ControlSocket;
let mut socket = ControlSocket::connect_port("127.0.0.1:9051".parse()?).await?;
// Auto-detect authentication method (no password)
authenticate(&mut socket, None).await?;
// Or with a password
// authenticate(&mut socket, Some("my_password")).await?;§Security
- Passwords are hex-encoded before transmission but not encrypted
- Cookie comparison uses constant-time algorithm to prevent timing attacks
- SAFECOOKIE nonces are cryptographically random (32 bytes)