1use std::io::Read;
2use std::net::{IpAddr, Ipv4Addr};
3use std::path::{Component, Path, PathBuf};
4
5use hmac::{Hmac, KeyInit, Mac};
6use sha2::Sha256;
7use subtle::ConstantTimeEq;
8use zeroize::Zeroizing;
9
10use crate::controller::Controller;
11use crate::error::{Error, Result};
12use crate::response::{ControlMessage, SingleLineResponse, escape_quoted};
13use crate::socket::ControlSocket;
14use crate::validation::is_hex_digits;
15use crate::version::Version;
16
17const CLIENT_HASH_CONSTANT: &[u8] =
18 b"Tor safe cookie authentication controller-to-server hash";
19const SERVER_HASH_CONSTANT: &[u8] =
20 b"Tor safe cookie authentication server-to-controller hash";
21const COOKIE_LENGTH: usize = 32;
22const DEFAULT_CONTROL_PORTS: [u16; 2] = [9051, 9151];
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum AuthMethod {
26 None,
27 Password,
28 Cookie,
29 SafeCookie,
30 Unknown,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct CookieFailure {
35 pub message: String,
36 pub cookie_path: PathBuf,
37 pub is_safecookie: bool,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
41pub enum AuthenticationError {
42 #[error("{0}")]
43 Failure(String),
44 #[error("{message}")]
45 UnrecognizedMethods {
46 message: String,
47 unknown_methods: Vec<String>,
48 },
49 #[error("{0}")]
50 IncorrectSocketType(String),
51 #[error("{0}")]
52 OpenAuthRejected(String),
53 #[error("{0}")]
54 PasswordAuthRejected(String),
55 #[error("{0}")]
56 IncorrectPassword(String),
57 #[error("{0}")]
58 MissingPassword(String),
59 #[error("{}", .0.message)]
60 CookieAuthRejected(CookieFailure),
61 #[error("{}", .0.message)]
62 IncorrectCookieValue(CookieFailure),
63 #[error("{}", .0.message)]
64 IncorrectCookieSize(CookieFailure),
65 #[error("{}", .0.message)]
66 UnreadableCookieFile(CookieFailure),
67 #[error("{}", .0.message)]
68 AuthChallengeFailed(CookieFailure),
69 #[error("{}", .0.message)]
70 AuthChallengeUnsupported(CookieFailure),
71 #[error("{}", .0.message)]
72 UnrecognizedAuthChallengeMethod(CookieFailure),
73 #[error("{}", .0.message)]
74 AuthSecurityFailure(CookieFailure),
75 #[error("{}", .0.message)]
76 InvalidClientNonce(CookieFailure),
77 #[error("{0}")]
78 NoAuthMethods(String),
79 #[error("{message}")]
80 NoAuthCookie {
81 message: String,
82 is_safecookie: bool,
83 },
84}
85
86impl AuthenticationError {
87 fn priority(&self) -> usize {
88 match self {
89 Self::IncorrectSocketType(_) => 0,
90 Self::UnrecognizedMethods { .. } => 1,
91 Self::MissingPassword(_) => 2,
92 Self::IncorrectPassword(_) => 3,
93 Self::IncorrectCookieSize(_) => 4,
94 Self::UnreadableCookieFile(_) => 5,
95 Self::IncorrectCookieValue(_) => 6,
96 Self::AuthChallengeUnsupported(_) => 7,
97 Self::UnrecognizedAuthChallengeMethod(_) => 8,
98 Self::InvalidClientNonce(_) => 9,
99 Self::AuthSecurityFailure(_) => 10,
100 Self::OpenAuthRejected(_) => 11,
101 Self::NoAuthMethods(_) | Self::NoAuthCookie { .. } => 12,
102 _ => 13,
103 }
104 }
105}
106
107pub trait ControlChannel: Send + Sync {
108 fn request(
109 &self,
110 message: &str,
111 ) -> impl Future<Output = Result<ControlMessage>> + Send;
112
113 fn reconnect(&self) -> impl Future<Output = Result<()>> + Send;
114
115 fn post_authentication(&self) -> impl Future<Output = ()> + Send {
116 async {}
117 }
118}
119
120impl ControlChannel for ControlSocket {
121 async fn request(&self, message: &str) -> Result<ControlMessage> {
122 self.send(message).await?;
123 self.recv().await
124 }
125
126 async fn reconnect(&self) -> Result<()> {
127 self.connect().await
128 }
129}
130
131#[derive(Debug, Clone, Default)]
132pub struct ProtocolInfoResponse {
133 pub protocol_version: u32,
134 pub tor_version: Option<Version>,
135 pub auth_methods: Vec<AuthMethod>,
136 pub unknown_auth_methods: Vec<String>,
137 pub cookie_path: Option<String>,
138}
139
140impl ProtocolInfoResponse {
141 pub fn parse(message: &ControlMessage) -> Result<Self> {
142 let mut lines = message.lines();
143 if !message.is_ok() || lines.pop().is_none_or(|last| &*last != "OK") {
144 return Err(Error::protocol(format!(
145 "PROTOCOLINFO response didn't have an OK status:\n{message}"
146 )));
147 }
148 if !lines
149 .first()
150 .is_some_and(|line| line.starts_with("PROTOCOLINFO"))
151 {
152 return Err(Error::protocol(format!(
153 "Message is not a PROTOCOLINFO response:\n{message}"
154 )));
155 }
156 let mut response = Self::default();
157 for mut line in lines {
158 match line.pop(false, false)?.as_str() {
159 "PROTOCOLINFO" => response.parse_version(&mut line)?,
160 "AUTH" => response.parse_auth(&mut line)?,
161 "VERSION" => response.parse_tor_version(&mut line)?,
162 other => log::debug!(
163 "Unrecognized PROTOCOLINFO line type '{other}', ignoring it: {line}"
164 ),
165 }
166 }
167 Ok(response)
168 }
169
170 fn parse_version(&mut self, line: &mut crate::response::ControlLine) -> Result<()> {
171 if line.is_empty() {
172 return Err(Error::protocol(format!(
173 "PROTOCOLINFO response's initial line is missing the protocol version: \
174 {line}"
175 )));
176 }
177 let version = line.pop(false, false)?;
178 self.protocol_version = version.parse().map_err(|_| {
179 Error::protocol(format!(
180 "PROTOCOLINFO response version is non-numeric: {line}"
181 ))
182 })?;
183 if self.protocol_version != 1 {
184 log::info!(
185 "We made a PROTOCOLINFO version 1 query but got a version {} response \
186 instead.",
187 self.protocol_version
188 );
189 }
190 Ok(())
191 }
192
193 fn parse_auth(&mut self, line: &mut crate::response::ControlLine) -> Result<()> {
194 if !line.is_next_mapping(Some("METHODS"), false, false) {
195 return Err(Error::protocol(format!(
196 "PROTOCOLINFO response's AUTH line is missing its mandatory 'METHODS' \
197 mapping: {line}"
198 )));
199 }
200 let (_, methods) = line.pop_mapping(false, false)?;
201 for method in methods.split(',') {
202 let known = match method {
203 "NULL" => Some(AuthMethod::None),
204 "HASHEDPASSWORD" => Some(AuthMethod::Password),
205 "COOKIE" => Some(AuthMethod::Cookie),
206 "SAFECOOKIE" => Some(AuthMethod::SafeCookie),
207 _ => None,
208 };
209 match known {
210 Some(method) => self.auth_methods.push(method),
211 None => {
212 log::info!(
213 "PROTOCOLINFO response included a type of authentication that \
214 we don't recognize: {method}"
215 );
216 self.unknown_auth_methods.push(method.to_string());
217 if !self.auth_methods.contains(&AuthMethod::Unknown) {
218 self.auth_methods.push(AuthMethod::Unknown);
219 }
220 }
221 }
222 }
223 if line.is_next_mapping(Some("COOKIEFILE"), true, true) {
224 let (_, path) = line.pop_mapping_bytes(true, true)?;
225 self.cookie_path = Some(String::from_utf8_lossy(&path).into_owned());
226 }
227 Ok(())
228 }
229
230 fn parse_tor_version(
231 &mut self,
232 line: &mut crate::response::ControlLine,
233 ) -> Result<()> {
234 if !line.is_next_mapping(Some("Tor"), true, false) {
235 return Err(Error::protocol(format!(
236 "PROTOCOLINFO response's VERSION line is missing its mandatory tor \
237 version mapping: {line}"
238 )));
239 }
240 let (_, version) = line.pop_mapping(true, false)?;
241 self.tor_version = Some(
242 Version::new(&version).map_err(|error| Error::protocol(error.to_string()))?,
243 );
244 Ok(())
245 }
246}
247
248#[derive(Debug, Clone)]
249pub struct AuthChallengeResponse {
250 pub server_hash: Vec<u8>,
251 pub server_nonce: Vec<u8>,
252}
253
254impl AuthChallengeResponse {
255 pub fn parse(message: &ControlMessage) -> Result<Self> {
256 if !message.is_ok() {
257 return Err(Error::protocol(format!(
258 "AUTHCHALLENGE response didn't have an OK status:\n{message}"
259 )));
260 }
261 if message.len() > 1 {
262 return Err(Error::protocol(format!(
263 "Received multiline AUTHCHALLENGE response:\n{message}"
264 )));
265 }
266 let mut line = message.lines().remove(0);
267 if line.pop(false, false)? != "AUTHCHALLENGE" {
268 return Err(Error::protocol(format!(
269 "Message is not an AUTHCHALLENGE response ({message})"
270 )));
271 }
272 let server_hash = Self::pop_hex(&mut line, "SERVERHASH")?;
273 let server_nonce = Self::pop_hex(&mut line, "SERVERNONCE")?;
274 Ok(Self {
275 server_hash,
276 server_nonce,
277 })
278 }
279
280 fn pop_hex(line: &mut crate::response::ControlLine, key: &str) -> Result<Vec<u8>> {
281 if !line.is_next_mapping(Some(key), false, false) {
282 return Err(Error::protocol(format!("Missing {key} mapping: {line}")));
283 }
284 let (_, value) = line.pop_mapping(false, false)?;
285 match is_hex_digits(&value, 64) {
286 true => Ok(hex::decode(&value)
287 .map_err(|error| Error::protocol(error.to_string()))?),
288 false => Err(Error::protocol(format!(
289 "{key} has an invalid value: {value}"
290 ))),
291 }
292 }
293}
294
295pub async fn get_protocolinfo<C: ControlChannel>(
296 channel: &C,
297) -> Result<ProtocolInfoResponse> {
298 let first_attempt = channel.request("PROTOCOLINFO 1").await;
299 let message = match first_attempt {
300 Ok(message) if message.to_string() != "Authentication required." => message,
301 _ => {
302 channel.reconnect().await?;
303 channel
304 .request("PROTOCOLINFO 1")
305 .await
306 .map_err(|error| match error {
307 Error::SocketClosed => Error::Socket("socket closed".to_string()),
308 other => other,
309 })?
310 }
311 };
312 ProtocolInfoResponse::parse(&message)
313}
314
315fn fail(error: AuthenticationError) -> Error {
316 Error::Authentication(error)
317}
318
319fn cookie_failure(
320 message: impl Into<String>,
321 path: &Path,
322 is_safecookie: bool,
323) -> CookieFailure {
324 CookieFailure {
325 message: message.into(),
326 cookie_path: path.to_path_buf(),
327 is_safecookie,
328 }
329}
330
331fn resolve_cookie_path(cookie_path: &str, chroot_path: Option<&Path>) -> Result<PathBuf> {
332 let Some(chroot) = chroot_path else {
333 return Ok(PathBuf::from(cookie_path));
334 };
335 let relative = Path::new(cookie_path)
336 .strip_prefix("/")
337 .unwrap_or(Path::new(cookie_path));
338 if relative
339 .components()
340 .any(|part| matches!(part, Component::ParentDir))
341 {
342 return Err(fail(AuthenticationError::Failure(format!(
343 "Refusing to read a cookie path that escapes the chroot: {cookie_path}"
344 ))));
345 }
346 Ok(chroot.join(relative))
347}
348
349pub async fn authenticate<C: ControlChannel>(
350 channel: &C,
351 password: Option<&str>,
352 chroot_path: Option<&Path>,
353 protocolinfo: Option<ProtocolInfoResponse>,
354) -> Result<()> {
355 let protocolinfo = match protocolinfo {
356 Some(protocolinfo) => protocolinfo,
357 None => match get_protocolinfo(channel).await {
358 Ok(protocolinfo) => protocolinfo,
359 Err(Error::Protocol(_)) => {
360 return Err(fail(AuthenticationError::IncorrectSocketType(
361 "unable to use the control socket".to_string(),
362 )));
363 }
364 Err(Error::Socket(message)) => {
365 return Err(fail(AuthenticationError::Failure(format!(
366 "socket connection failed ({message})"
367 ))));
368 }
369 Err(Error::SocketClosed) => {
370 return Err(fail(AuthenticationError::Failure(
371 "socket connection failed (socket closed)".to_string(),
372 )));
373 }
374 Err(other) => return Err(other),
375 },
376 };
377
378 let (methods, mut failures) = plan_methods(&protocolinfo, password)?;
379 for method in [
380 AuthMethod::None,
381 AuthMethod::Password,
382 AuthMethod::SafeCookie,
383 AuthMethod::Cookie,
384 ] {
385 if !methods.contains(&method) {
386 continue;
387 }
388 let attempt =
389 attempt_method(channel, method, password, chroot_path, &protocolinfo).await;
390 match attempt {
391 Ok(()) => {
392 channel.post_authentication().await;
393 return Ok(());
394 }
395 Err(Error::Authentication(error)) => failures.push(error),
396 Err(error) => failures.push(AuthenticationError::Failure(error.to_string())),
397 }
398 }
399 let chosen = failures
400 .into_iter()
401 .min_by_key(AuthenticationError::priority)
402 .unwrap_or_else(|| {
403 AuthenticationError::Failure("Authentication failed".to_string())
404 });
405 Err(fail(chosen))
406}
407
408fn plan_methods(
409 protocolinfo: &ProtocolInfoResponse,
410 password: Option<&str>,
411) -> Result<(Vec<AuthMethod>, Vec<AuthenticationError>)> {
412 let mut methods = protocolinfo.auth_methods.clone();
413 let mut failures = Vec::new();
414 if methods.is_empty() {
415 return Err(fail(AuthenticationError::NoAuthMethods(
416 "our PROTOCOLINFO response did not have any methods for authenticating"
417 .to_string(),
418 )));
419 }
420 if methods.contains(&AuthMethod::Unknown) {
421 methods.retain(|method| *method != AuthMethod::Unknown);
422 let unknown = &protocolinfo.unknown_auth_methods;
423 let plural = if unknown.len() > 1 { "s" } else { "" };
424 if methods.is_empty() {
425 failures.push(AuthenticationError::UnrecognizedMethods {
426 message: format!(
427 "unrecognized authentication method{plural} ({})",
428 unknown.join(", ")
429 ),
430 unknown_methods: unknown.clone(),
431 });
432 } else {
433 log::debug!(
434 "Authenticating to a socket with unrecognized auth method{plural}, \
435 ignoring them: {}",
436 unknown.join(", ")
437 );
438 }
439 }
440 if protocolinfo.cookie_path.is_none() {
441 for cookie_method in [AuthMethod::Cookie, AuthMethod::SafeCookie] {
442 if methods.contains(&cookie_method) {
443 methods.retain(|method| *method != cookie_method);
444 failures.push(AuthenticationError::NoAuthCookie {
445 message: "our PROTOCOLINFO response did not have the location of \
446 our authentication cookie"
447 .to_string(),
448 is_safecookie: cookie_method == AuthMethod::SafeCookie,
449 });
450 }
451 }
452 }
453 if methods.contains(&AuthMethod::Password) && password.is_none() {
454 methods.retain(|method| *method != AuthMethod::Password);
455 failures.push(AuthenticationError::MissingPassword(
456 "no passphrase provided".to_string(),
457 ));
458 }
459 Ok((methods, failures))
460}
461
462async fn attempt_method<C: ControlChannel>(
463 channel: &C,
464 method: AuthMethod,
465 password: Option<&str>,
466 chroot_path: Option<&Path>,
467 protocolinfo: &ProtocolInfoResponse,
468) -> Result<()> {
469 match method {
470 AuthMethod::None => authenticate_none(channel, false).await,
471 AuthMethod::Password => {
472 authenticate_password(channel, password.unwrap_or_default(), false).await
473 }
474 AuthMethod::Cookie | AuthMethod::SafeCookie => {
475 let cookie_path = resolve_cookie_path(
476 protocolinfo.cookie_path.as_deref().unwrap_or_default(),
477 chroot_path,
478 )?;
479 match method {
480 AuthMethod::SafeCookie => {
481 authenticate_safecookie(channel, &cookie_path, false).await
482 }
483 _ => authenticate_cookie(channel, &cookie_path, false).await,
484 }
485 }
486 AuthMethod::Unknown => Ok(()),
487 }
488}
489
490async fn reset_after_failure<C: ControlChannel>(channel: &C) {
491 let _ = channel.reconnect().await;
492}
493
494async fn send_authenticate<C: ControlChannel>(
495 channel: &C,
496 message: &str,
497) -> Result<SingleLineResponse> {
498 let response = channel.request(message).await?;
499 Ok(SingleLineResponse {
500 code: response.status_code().to_string(),
501 message: response.to_string(),
502 raw: response,
503 })
504}
505
506pub async fn authenticate_none<C: ControlChannel>(
507 channel: &C,
508 suppress_controller_errors: bool,
509) -> Result<()> {
510 match send_authenticate(channel, "AUTHENTICATE").await {
511 Ok(response) if response.raw.to_string() == "OK" => Ok(()),
512 Ok(response) => {
513 reset_after_failure(channel).await;
514 Err(fail(AuthenticationError::OpenAuthRejected(
515 response.raw.to_string(),
516 )))
517 }
518 Err(error) => {
519 reset_after_failure(channel).await;
520 match suppress_controller_errors {
521 false => Err(error),
522 true => Err(fail(AuthenticationError::OpenAuthRejected(format!(
523 "Socket failed ({error})"
524 )))),
525 }
526 }
527 }
528}
529
530pub async fn authenticate_password<C: ControlChannel>(
531 channel: &C,
532 password: &str,
533 suppress_controller_errors: bool,
534) -> Result<()> {
535 let command = Zeroizing::new(format!("AUTHENTICATE {}", escape_quoted(password)));
536 match send_authenticate(channel, &command).await {
537 Ok(response) if response.raw.to_string() == "OK" => Ok(()),
538 Ok(response) => {
539 reset_after_failure(channel).await;
540 let text = response.raw.to_string();
541 Err(fail(
542 match text.contains("Password did not match HashedControlPassword") {
543 true => AuthenticationError::IncorrectPassword(text),
544 false => AuthenticationError::PasswordAuthRejected(text),
545 },
546 ))
547 }
548 Err(error) => {
549 reset_after_failure(channel).await;
550 match suppress_controller_errors {
551 false => Err(error),
552 true => Err(fail(AuthenticationError::PasswordAuthRejected(format!(
553 "Socket failed ({error})"
554 )))),
555 }
556 }
557 }
558}
559
560fn read_cookie(cookie_path: &Path, is_safecookie: bool) -> Result<Zeroizing<Vec<u8>>> {
561 let unreadable = |message: String| {
562 fail(AuthenticationError::UnreadableCookieFile(cookie_failure(
563 message,
564 cookie_path,
565 is_safecookie,
566 )))
567 };
568 let mut file =
569 std::fs::File::open(cookie_path).map_err(|error| match error.kind() {
570 std::io::ErrorKind::NotFound => unreadable(format!(
571 "Authentication failed: '{}' doesn't exist",
572 cookie_path.display()
573 )),
574 _ => unreadable(format!(
575 "Authentication failed: unable to read '{}' ({error})",
576 cookie_path.display()
577 )),
578 })?;
579 let metadata = file.metadata().map_err(|error| {
580 unreadable(format!(
581 "Authentication failed: unable to read '{}' ({error})",
582 cookie_path.display()
583 ))
584 })?;
585 if !metadata.is_file() || metadata.len() != COOKIE_LENGTH as u64 {
586 return Err(fail(AuthenticationError::IncorrectCookieSize(
587 cookie_failure(
588 format!(
589 "Authentication failed: authentication cookie '{}' is the wrong \
590 size ({} bytes instead of {COOKIE_LENGTH})",
591 cookie_path.display(),
592 metadata.len()
593 ),
594 cookie_path,
595 is_safecookie,
596 ),
597 )));
598 }
599 let mut cookie = Zeroizing::new(Vec::with_capacity(COOKIE_LENGTH + 1));
600 (&mut file)
601 .take(COOKIE_LENGTH as u64 + 1)
602 .read_to_end(&mut cookie)
603 .map_err(|error| {
604 unreadable(format!(
605 "Authentication failed: unable to read '{}' ({error})",
606 cookie_path.display()
607 ))
608 })?;
609 match cookie.len() == COOKIE_LENGTH {
610 true => Ok(cookie),
611 false => Err(fail(AuthenticationError::IncorrectCookieSize(
612 cookie_failure(
613 format!(
614 "Authentication failed: authentication cookie '{}' changed size \
615 while reading",
616 cookie_path.display()
617 ),
618 cookie_path,
619 is_safecookie,
620 ),
621 ))),
622 }
623}
624
625pub async fn authenticate_cookie<C: ControlChannel>(
626 channel: &C,
627 cookie_path: &Path,
628 suppress_controller_errors: bool,
629) -> Result<()> {
630 let cookie = read_cookie(cookie_path, false)?;
631 let command = Zeroizing::new(format!("AUTHENTICATE {}", hex::encode(&*cookie)));
632 let rejected = |message: String| {
633 fail(AuthenticationError::CookieAuthRejected(cookie_failure(
634 message,
635 cookie_path,
636 false,
637 )))
638 };
639 match send_authenticate(channel, &command).await {
640 Ok(response) if response.raw.to_string() == "OK" => Ok(()),
641 Ok(response) => {
642 reset_after_failure(channel).await;
643 let text = response.raw.to_string();
644 let mismatch = text.contains("*or* authentication cookie.")
645 || text.contains("Authentication cookie did not match expected value.");
646 Err(match mismatch {
647 true => fail(AuthenticationError::IncorrectCookieValue(cookie_failure(
648 text,
649 cookie_path,
650 false,
651 ))),
652 false => rejected(text),
653 })
654 }
655 Err(error) => {
656 reset_after_failure(channel).await;
657 match suppress_controller_errors {
658 false => Err(error),
659 true => Err(rejected(format!("Socket failed ({error})"))),
660 }
661 }
662 }
663}
664
665fn hmac_sha256(key: &[u8], parts: &[&[u8]]) -> Vec<u8> {
666 let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(key)
667 .expect("HMAC accepts any key length");
668 for part in parts {
669 mac.update(part);
670 }
671 mac.finalize().into_bytes().to_vec()
672}
673
674pub async fn authenticate_safecookie<C: ControlChannel>(
675 channel: &C,
676 cookie_path: &Path,
677 suppress_controller_errors: bool,
678) -> Result<()> {
679 let cookie = read_cookie(cookie_path, true)?;
680 let client_nonce: [u8; 32] = rand::random();
681 let failure = |message: String| cookie_failure(message, cookie_path, true);
682 let challenge = match channel
683 .request(&format!(
684 "AUTHCHALLENGE SAFECOOKIE {}",
685 hex::encode(client_nonce)
686 ))
687 .await
688 {
689 Ok(challenge) => challenge,
690 Err(error) => {
691 reset_after_failure(channel).await;
692 return match suppress_controller_errors {
693 false => Err(error),
694 true => Err(fail(AuthenticationError::AuthChallengeFailed(failure(
695 format!("Socket failed ({error})"),
696 )))),
697 };
698 }
699 };
700 if !challenge.is_ok() {
701 reset_after_failure(channel).await;
702 return Err(fail(challenge_failure(&challenge.to_string(), failure)));
703 }
704 let challenge = AuthChallengeResponse::parse(&challenge).map_err(|error| {
705 match suppress_controller_errors {
706 false => error,
707 true => fail(AuthenticationError::AuthChallengeFailed(failure(format!(
708 "Unable to parse AUTHCHALLENGE response: {error}"
709 )))),
710 }
711 })?;
712 let parts: [&[u8]; 3] = [&cookie, &client_nonce, &challenge.server_nonce];
713 let expected_server_hash = hmac_sha256(SERVER_HASH_CONSTANT, &parts);
714 if !bool::from(expected_server_hash.ct_eq(&challenge.server_hash)) {
715 return Err(fail(AuthenticationError::AuthSecurityFailure(failure(
716 "Tor provided the wrong server nonce".to_string(),
717 ))));
718 }
719 let client_hash = hmac_sha256(CLIENT_HASH_CONSTANT, &parts);
720 let command = format!("AUTHENTICATE {}", hex::encode(client_hash));
721 let rejected =
722 |message: String| fail(AuthenticationError::CookieAuthRejected(failure(message)));
723 match send_authenticate(channel, &command).await {
724 Ok(response) if response.raw.is_ok() => Ok(()),
725 Ok(response) => {
726 reset_after_failure(channel).await;
727 let text = response.raw.to_string();
728 let mismatch = text.contains("*or* authentication cookie.")
729 || text.contains("Safe cookie response did not match expected value");
730 Err(match mismatch {
731 true => fail(AuthenticationError::IncorrectCookieValue(failure(text))),
732 false => rejected(text),
733 })
734 }
735 Err(error) => {
736 reset_after_failure(channel).await;
737 match suppress_controller_errors {
738 false => Err(error),
739 true => Err(rejected(format!("Socket failed ({error})"))),
740 }
741 }
742 }
743}
744
745fn challenge_failure(
746 text: &str,
747 failure: impl Fn(String) -> CookieFailure,
748) -> AuthenticationError {
749 let details = failure(text.to_string());
750 if text.contains("Authentication required.") {
751 AuthenticationError::AuthChallengeUnsupported(failure(
752 "SAFECOOKIE authentication isn't supported".to_string(),
753 ))
754 } else if text.contains("AUTHCHALLENGE only supports") {
755 AuthenticationError::UnrecognizedAuthChallengeMethod(details)
756 } else if text.contains("Invalid base16 client nonce") {
757 AuthenticationError::InvalidClientNonce(details)
758 } else if text.contains("Cookie authentication is disabled") {
759 AuthenticationError::CookieAuthRejected(details)
760 } else {
761 AuthenticationError::AuthChallengeFailed(details)
762 }
763}
764
765#[derive(Debug, Clone)]
766pub struct ConnectOptions {
767 pub control_port: Option<(IpAddr, Option<u16>)>,
768 pub control_socket: Option<PathBuf>,
769 pub password: Option<String>,
770 pub password_prompt: bool,
771 pub chroot_path: Option<PathBuf>,
772}
773
774impl Default for ConnectOptions {
775 fn default() -> Self {
776 Self {
777 control_port: Some((IpAddr::V4(Ipv4Addr::LOCALHOST), None)),
778 control_socket: Some(PathBuf::from("/var/run/tor/control")),
779 password: None,
780 password_prompt: false,
781 chroot_path: None,
782 }
783 }
784}
785
786async fn control_port_connection(
787 address: IpAddr,
788 port: Option<u16>,
789) -> Result<ControlSocket> {
790 let ports: Vec<u16> = match port {
791 Some(port) => vec![port],
792 None => DEFAULT_CONTROL_PORTS.to_vec(),
793 };
794 let mut last_error = Error::Socket("no control port to try".to_string());
795 for port in ports {
796 let socket = ControlSocket::port(address, port);
797 match socket.connect().await {
798 Ok(()) => return Ok(socket),
799 Err(error) => last_error = error,
800 }
801 }
802 Err(last_error)
803}
804
805pub async fn connect(options: ConnectOptions) -> Result<Controller> {
806 if options.control_port.is_none() && options.control_socket.is_none() {
807 return Err(Error::invalid_input(
808 "Neither a control port nor control socket were provided. Nothing to \
809 connect to.",
810 ));
811 }
812 let mut error_message = String::new();
813 let mut socket = None;
814 if let Some(path) = &options.control_socket {
815 match path.exists() {
816 true => match ControlSocket::file(path).connect_and_return().await {
817 Ok(connected) => socket = Some(connected),
818 Err(error) => {
819 error_message =
820 format!("Unable to connect to '{}': {error}", path.display())
821 }
822 },
823 false => {
824 error_message = format!(
825 "The socket file you specified ({}) doesn't exist",
826 path.display()
827 )
828 }
829 }
830 }
831 if let (None, Some((address, port))) = (&socket, options.control_port) {
832 match control_port_connection(address, port).await {
833 Ok(connected) => socket = Some(connected),
834 Err(error) => {
835 error_message = format!(
836 "Unable to connect to {address}:{}: {error}",
837 port.map_or("default".to_string(), |port| port.to_string())
838 )
839 }
840 }
841 }
842 let Some(socket) = socket else {
843 if options.control_socket.is_some() && options.control_port.is_some() {
844 error_message =
845 "Unable to connect to tor. Are you sure it's running?".to_string();
846 }
847 return Err(Error::Socket(error_message));
848 };
849 authenticate_new_controller(
850 Controller::new(socket),
851 options.password,
852 options.password_prompt,
853 options.chroot_path,
854 )
855 .await
856}
857
858impl ControlSocket {
859 async fn connect_and_return(self) -> Result<Self> {
860 self.connect().await?;
861 Ok(self)
862 }
863}
864
865pub async fn connect_port(
866 address: IpAddr,
867 port: u16,
868 password: Option<String>,
869 chroot_path: Option<PathBuf>,
870) -> Result<Controller> {
871 let socket = ControlSocket::port(address, port)
872 .connect_and_return()
873 .await?;
874 authenticate_new_controller(Controller::new(socket), password, true, chroot_path)
875 .await
876}
877
878pub async fn connect_socket_file(
879 path: impl Into<PathBuf>,
880 password: Option<String>,
881 chroot_path: Option<PathBuf>,
882) -> Result<Controller> {
883 let socket = ControlSocket::file(path).connect_and_return().await?;
884 authenticate_new_controller(Controller::new(socket), password, true, chroot_path)
885 .await
886}
887
888fn prompt_password() -> Option<String> {
889 rpassword::prompt_password("Tor controller password: ").ok()
890}
891
892async fn authenticate_new_controller(
893 controller: Controller,
894 password: Option<String>,
895 password_prompt: bool,
896 chroot_path: Option<PathBuf>,
897) -> Result<Controller> {
898 let mut password = password.map(Zeroizing::new);
899 loop {
900 let outcome = authenticate(
901 &controller,
902 password.as_ref().map(|secret| secret.as_str()),
903 chroot_path.as_deref(),
904 None,
905 )
906 .await;
907 match outcome {
908 Ok(()) => return Ok(controller),
909 Err(Error::Authentication(AuthenticationError::MissingPassword(_)))
910 if password.is_none() && password_prompt =>
911 {
912 match prompt_password() {
913 Some(entered) => password = Some(Zeroizing::new(entered)),
914 None => {
915 controller.close().await;
916 return Err(Error::Authentication(
917 AuthenticationError::MissingPassword(
918 "Tor requires a password to authenticate".to_string(),
919 ),
920 ));
921 }
922 }
923 }
924 Err(error) => {
925 controller.close().await;
926 return Err(describe_connect_error(&controller, error));
927 }
928 }
929 }
930}
931
932fn describe_connect_error(controller: &Controller, error: Error) -> Error {
933 match error {
934 Error::Authentication(AuthenticationError::IncorrectSocketType(_)) => {
935 let hint = match controller.socket().control_port() {
936 Some(address) => format!(
937 "Please check in your torrc that {} is the ControlPort. Maybe you \
938 configured it to be the ORPort or SocksPort instead?",
939 address.port()
940 ),
941 None => "Unable to connect to tor. Are you sure the interface you \
942 specified belongs to tor?"
943 .to_string(),
944 };
945 Error::Authentication(AuthenticationError::IncorrectSocketType(hint))
946 }
947 Error::Authentication(AuthenticationError::MissingPassword(_)) => {
948 Error::Authentication(AuthenticationError::MissingPassword(
949 "Tor requires a password to authenticate".to_string(),
950 ))
951 }
952 other => other,
953 }
954}