Files
proxy-suite-flake/windows/crates/ps-service/src/tor.rs
T
faumarayandClaude Opus 5.5 40221e7981 windows: Tor
- tor: the Tor Project's Expert Bundle for Windows (15.0.26) as a
  component, pinned by the hash of the release whose signature was
  checked against the Tor Browser Developers' key; the installer takes
  gzipped tars now (plain files only: a link could point anywhere).
- The torrc upstream's tor.nix writes: SOCKS for the tor outbound,
  bridges with the bundle's lyrebird (obfs4, webtunnel, meek, snowflake)
  and conjure, the local proxy as upstream (upstream = "proxy") with its
  login, extraConfig. The control port is on loopback with cookie
  authentication (upstream's is a Unix socket only Tor's user opens).
  Values are quoted with control characters escaped: a newline in, say,
  the proxy's login would otherwise start a directive (one that runs a
  program, as SYSTEM).
- Tor's own connections go direct under the TUN unless upstream =
  "proxy". The onion service (for the inbounds) is still to come and is
  said to be.
- Checked: Windows' tor.exe, under Wine, takes a torrc of this shape,
  bridges and escaped values included; on Linux the service runs Tor and
  it bootstraps as far as this network lets it without bridges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:02:24 +03:00

173 lines
7.6 KiB
Rust

//! 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.
fn bridge_lines(text: &str) -> Vec<String> {
text.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|l| {
let bare = l.strip_prefix("Bridge").filter(|r| r.starts_with(char::is_whitespace)).map(str::trim_start).unwrap_or(l);
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<String>) -> Result<String> {
let t = &cfg.tor;
let mut c: Vec<String> = 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<String> = t.bridges.lines.iter().flat_map(|l| bridge_lines(l)).collect();
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;
let host = if l.address == "0.0.0.0" || l.address == "::" { "127.0.0.1".to_owned() } else { l.address.clone() };
let host = if host.contains(':') { format!("[{host}]") } else { host };
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<UnitSpec> {
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")));
}
}