//! Tor: the SOCKS listener behind the `tor` outbound, run with the torrc upstream's tor.nix //! writes, from the Tor Expert Bundle (the Tor Project's, signed; components.json). On Windows //! the control port is on loopback with cookie authentication, the cookie below the protected //! state root; upstream uses a Unix socket only Tor's user may open. Onion services serve the //! inbounds, which are not on Windows yet. use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use ps_core::config::{Config, Upstream}; use crate::paths::{Paths, write_atomic}; use crate::units::UnitSpec; pub const UNIT: &str = "proxy-suite-tor"; /// A torrc string, which Tor unescapes C's way inside the quotes. Control characters are /// escaped too: a bare newline would end the line and start a directive of the value's /// choosing (one that runs a program, as SYSTEM). fn quote(s: &str) -> String { let mut out = String::from("\""); for c in s.chars() { match c { '\\' => out.push_str("\\\\"), '"' => out.push_str("\\\""), c if (c as u32) < 0x20 || c as u32 == 0x7f => out.push_str(&format!("\\x{:02x}", c as u32)), c => out.push(c), } } out.push('"'); out } /// Bridge lines as upstream takes them: trimmed, blanks and comments gone, "Bridge " in front. /// One with a control character left in it (a lone carriage return) is refused: it could end /// the line in Tor's reading and start a directive. fn bridge_lines(text: &str) -> Result> { text.lines() .map(str::trim) .filter(|l| !l.is_empty() && !l.starts_with('#')) .map(|l| { if l.chars().any(char::is_control) { anyhow::bail!("a bridge line has a control character in it"); } let bare = l.strip_prefix("Bridge").filter(|r| r.starts_with(char::is_whitespace)).map(str::trim_start).unwrap_or(l); Ok(format!("Bridge {bare}")) }) .collect() } /// The torrc. `bundle` is the Expert Bundle's directory (its GeoIP files and transports), or /// `None` for a Tor of the system's own (Linux, for development); `data` is Tor's state. pub fn torrc(cfg: &Config, bundle: Option<&Path>, data: &Path, read: impl Fn(&str) -> Result) -> Result { let t = &cfg.tor; let mut c: Vec = Vec::new(); if let Some(b) = bundle { c.push(format!("GeoIPFile {}", b.join("data").join("geoip").display())); c.push(format!("GeoIPv6File {}", b.join("data").join("geoip6").display())); } c.extend( ["ClientUseIPv6 1", "AvoidDiskWrites 1", "Log notice stdout", "AutomapHostsOnResolve 0", "DNSPort 0", "TransPort 0", "NATDPort 0"] .map(String::from), ); if t.client_only { c.push("ClientOnly 1".into()); } if t.keep_awake { c.extend(["DormantTimeoutEnabled 0".into(), "DormantCanceledByStartup 1".into()]); } c.push(if t.as_outbound { format!("SocksPort 127.0.0.1:{}", t.socks_port) } else { "SocksPort 0".into() }); let mut bridges: Vec = Vec::new(); for l in &t.bridges.lines { bridges.extend(bridge_lines(l)?); } if let Some(f) = &t.bridges.file { bridges.extend(bridge_lines(&read(f).with_context(|| format!("reading tor.bridges.file {f}"))?)?); } if !bridges.is_empty() { c.push("UseBridges 1".into()); let pt = |exe: &str| bundle.map(|b| b.join("tor").join("pluggable_transports").join(exe).display().to_string()).unwrap_or_else(|| exe.trim_end_matches(".exe").into()); // The bundle's own pt_config.json: lyrebird carries snowflake too. c.push(format!("ClientTransportPlugin meek_lite,obfs2,obfs3,obfs4,scramblesuit,webtunnel exec {}", pt("lyrebird.exe"))); c.push(format!("ClientTransportPlugin snowflake exec {}", pt("lyrebird.exe"))); if bundle.is_some() { c.push(format!("ClientTransportPlugin conjure exec {} -registerURL https://registration.refraction.network/api", pt("conjure-client.exe"))); } c.extend(bridges); } if t.upstream == Upstream::Proxy { let l = &cfg.proxy.listener; // Written from the parsed address, never the text: it is not quoted in the torrc. let ip: std::net::IpAddr = l.address.parse().context("proxy.listener.address is not an IP address")?; let host = match ip { ip if ip.is_unspecified() => "127.0.0.1".to_owned(), std::net::IpAddr::V6(v6) => format!("[{v6}]"), v4 => v4.to_string(), }; c.push(format!("Socks5Proxy {host}:{}", l.port)); if let Some(user) = &l.auth.username { let password = match (&l.auth.password, &l.auth.password_file) { (Some(p), _) => p.clone(), (None, Some(f)) => read(f)?.lines().next().unwrap_or("").to_owned(), (None, None) => String::new(), }; c.push(format!("Socks5ProxyUsername {}", quote(user))); c.push(format!("Socks5ProxyPassword {}", quote(&password))); } } c.push(format!("DataDirectory {}", data.display())); c.push(format!("ControlPort 127.0.0.1:{}", t.control_port)); c.push("CookieAuthentication 1".into()); c.push(format!("CookieAuthFile {}", data.join("control_auth_cookie").display())); let mut out = c.join("\n"); out.push('\n'); if !t.extra_config.is_empty() { out.push_str(&t.extra_config); if !t.extra_config.ends_with('\n') { out.push('\n'); } } Ok(out) } /// The program: the bundle's tor.exe (checked against its hashes by the caller), or on Linux /// the system's `tor`. pub fn unit(cfg: &Config, paths: &Paths, program: PathBuf, bundle: Option<&Path>) -> Result { let data = paths.root.join("tor"); std::fs::create_dir_all(&data)?; let text = torrc(cfg, bundle, &data, |f| std::fs::read_to_string(f).with_context(|| format!("reading {f}")))?; let file = paths.run().join("torrc"); write_atomic(&file, text.as_bytes())?; Ok(UnitSpec { name: UNIT.into(), program, args: vec!["-f".into(), file.display().to_string()], env: Vec::new(), cwd: Some(data), generation: text, }) } #[cfg(test)] mod tests { use super::*; fn cfg() -> Config { let mut c = Config::default(); c.tor.enable = true; c.tor.as_outbound = true; c } #[test] fn upstreams_torrc() { let t = torrc(&cfg(), Some(Path::new("B")), Path::new("D"), |_| Ok(String::new())).unwrap(); for want in ["GeoIPFile B", "ClientOnly 1", "SocksPort 127.0.0.1:18530", "DNSPort 0", "DataDirectory D", "AutomapHostsOnResolve 0"] { assert!(t.lines().any(|l| l.starts_with(want)), "{want} in\n{t}"); } assert!(!t.contains("UseBridges")); } #[test] fn bridges_and_the_proxy_upstream() { let mut c = cfg(); c.tor.bridges.lines = vec!["obfs4 192.0.2.1:443 FP cert=x iat-mode=0".into(), "Bridge webtunnel 192.0.2.2:443 FP url=https://e.example/x".into()]; c.tor.bridges.file = Some("f".into()); c.tor.upstream = Upstream::Proxy; c.proxy.listener.auth.username = Some("u".into()); c.proxy.listener.auth.password = Some("p\"#\\".into()); let t = torrc(&c, Some(Path::new("B")), Path::new("D"), |_| Ok("# c\n snowflake 192.0.2.3:80 FP\n".into())).unwrap(); assert!(t.contains("UseBridges 1")); assert!(t.contains("Bridge obfs4 192.0.2.1:443 FP cert=x iat-mode=0\n")); assert!(t.contains("Bridge webtunnel 192.0.2.2:443")); assert!(t.contains("Bridge snowflake 192.0.2.3:80 FP\n")); assert!(t.contains("lyrebird.exe")); assert!(t.contains("Socks5Proxy 127.0.0.1:1080\n")); assert!(t.contains("Socks5ProxyPassword \"p\\\"#\\\\\"\n"), "{t}"); // A newline in a value stays in its line. c.proxy.listener.auth.username = Some("u\nClientTransportPlugin x exec calc.exe".into()); let t = torrc(&c, None, Path::new("D"), |_| Ok(String::new())).unwrap(); assert!(t.contains("Socks5ProxyUsername \"u\\x0aClientTransportPlugin x exec calc.exe\"\n"), "{t}"); assert!(!t.lines().any(|l| l.starts_with("ClientTransportPlugin x"))); // Nor through the address, which is not quoted, or a bridge line. c.proxy.listener.auth.username = None; c.proxy.listener.address = "127.0.0.1\nClientTransportPlugin x exec calc.exe".into(); assert!(torrc(&c, None, Path::new("D"), |_| Ok(String::new())).is_err()); c.proxy.listener.address = "127.0.0.1".into(); c.tor.bridges.lines = vec!["obfs4 192.0.2.1:443 FP\rClientTransportPlugin x exec calc.exe".into()]; assert!(torrc(&c, None, Path::new("D"), |_| Ok(String::new())).is_err()); } }