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>
This commit is contained in:
1 parent
82fe4d8e65
commit
40221e7981
12 files changed
+282
-14
No files matched your search
@@ -115,7 +115,7 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
|
||||
for (on, path, what) in [
|
||||
(cfg.amnezia_wg.enable, "amneziaWg.enable", "AmneziaWG"),
|
||||
(cfg.warp.enable, "warp.enable", "WARP"),
|
||||
(cfg.tor.enable, "tor.enable", "Tor"),
|
||||
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
|
||||
(cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"),
|
||||
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
|
||||
(cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"),
|
||||
|
||||
@@ -24,6 +24,8 @@ tracing-subscriber.workspace = true
|
||||
rand.workspace = true
|
||||
sha2.workspace = true
|
||||
zip.workspace = true
|
||||
flate2 = "1"
|
||||
tar = { version = "0.4", default-features = false }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-service.workspace = true
|
||||
|
||||
@@ -48,8 +48,10 @@ impl Components {
|
||||
if cfg!(windows) {
|
||||
return None;
|
||||
}
|
||||
// Development: the system's program of that name (a bundle's "tor/tor" is "tor").
|
||||
let bare = std::path::Path::new(&file).file_name()?.to_owned();
|
||||
let path = std::env::var_os("PATH")?;
|
||||
std::env::split_paths(&path).map(|dir| dir.join(&file)).find(|p| p.is_file())
|
||||
std::env::split_paths(&path).map(|dir| dir.join(&bare)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
pub fn sing_box(&self) -> anyhow::Result<PathBuf> {
|
||||
|
||||
@@ -44,19 +44,15 @@ pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Res
|
||||
Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")).context(format!("fetching {}", src.url)))
|
||||
}
|
||||
|
||||
/// Extracts what `src` takes from `data` into `dest`, verifying each file it pins.
|
||||
/// Extracts what `src` takes from `data`, a zip or a gzipped tar, into `dest`, verifying each
|
||||
/// file it pins. Only plain files are taken from a tar: a link could point anywhere.
|
||||
pub fn extract(src: &Source, data: &[u8], dest: &Path) -> Result<usize> {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(data)).context("not a zip archive")?;
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut n = 0;
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i)?;
|
||||
let name = entry.name().to_owned();
|
||||
let Some(rel) = src.place(&name) else { continue };
|
||||
let mut body = Vec::with_capacity(entry.size() as usize);
|
||||
entry.read_to_end(&mut body)?;
|
||||
let mut take = |name: &str, body: Vec<u8>| -> Result<()> {
|
||||
let Some(rel) = src.place(name) else { return Ok(()) };
|
||||
if let Some(files) = &src.files {
|
||||
let in_archive = name.strip_prefix(src.strip.as_str()).unwrap_or(&name);
|
||||
let in_archive = name.strip_prefix(src.strip.as_str()).unwrap_or(name);
|
||||
let want = &files[in_archive];
|
||||
let got = hex(&body);
|
||||
if got != *want {
|
||||
@@ -70,6 +66,29 @@ pub fn extract(src: &Source, data: &[u8], dest: &Path) -> Result<usize> {
|
||||
}
|
||||
std::fs::write(&out, &body).with_context(|| format!("writing {}", out.display()))?;
|
||||
n += 1;
|
||||
Ok(())
|
||||
};
|
||||
if data.starts_with(&[0x1f, 0x8b]) {
|
||||
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(data));
|
||||
for entry in tar.entries().context("not a gzipped tar archive")? {
|
||||
let mut entry = entry?;
|
||||
if !entry.header().entry_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.path()?.to_string_lossy().trim_start_matches("./").to_owned();
|
||||
let mut body = Vec::with_capacity(entry.size() as usize);
|
||||
entry.read_to_end(&mut body)?;
|
||||
take(&name, body)?;
|
||||
}
|
||||
} else {
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(data)).context("not a zip archive")?;
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i)?;
|
||||
let name = entry.name().to_owned();
|
||||
let mut body = Vec::with_capacity(entry.size() as usize);
|
||||
entry.read_to_end(&mut body)?;
|
||||
take(&name, body)?;
|
||||
}
|
||||
}
|
||||
if let Some(files) = &src.files {
|
||||
let missing: Vec<&String> = files.keys().filter(|f| !seen.contains(*f)).collect();
|
||||
|
||||
@@ -15,6 +15,7 @@ mod service;
|
||||
mod ssh;
|
||||
mod store;
|
||||
mod tg;
|
||||
mod tor;
|
||||
mod units;
|
||||
#[cfg(windows)]
|
||||
mod winsvc;
|
||||
|
||||
@@ -93,6 +93,13 @@ impl Service {
|
||||
{
|
||||
direct.push(p.to_string_lossy().into_owned());
|
||||
}
|
||||
// Tor's own connections, unless it is to go through the proxy (upstream = "proxy").
|
||||
if cfg.tor.enable
|
||||
&& cfg.tor.upstream == ps_core::config::Upstream::Direct
|
||||
&& let Some(p) = self.comps.find("tor", "tor/tor")
|
||||
{
|
||||
direct.push(p.to_string_lossy().into_owned());
|
||||
}
|
||||
let (zd, zi) = crate::zapret::direct_sync(cfg, &paths.bin());
|
||||
Env {
|
||||
zapret_direct: ps_core::config::RouteMatch { domains: zd, ips: zi, ..Default::default() },
|
||||
@@ -141,8 +148,27 @@ impl Service {
|
||||
if let Err(e) = &ssh {
|
||||
self.sup.note(crate::ssh::UNIT, format!("proxy-suite: the SSH tunnel: {e:#}"));
|
||||
}
|
||||
let tor = self.apply_tor().await;
|
||||
if let Err(e) = &tor {
|
||||
self.sup.note(crate::tor::UNIT, format!("proxy-suite: Tor: {e:#}"));
|
||||
}
|
||||
let proxy = self.apply_proxy().await;
|
||||
zapret.and(tg).and(ssh).and(proxy)
|
||||
zapret.and(tg).and(ssh).and(tor).and(proxy)
|
||||
}
|
||||
|
||||
async fn apply_tor(&mut self) -> Result<()> {
|
||||
let cfg = self.cfg().clone();
|
||||
if !cfg.enable || !cfg.tor.enable {
|
||||
self.sup.stop(crate::tor::UNIT).await;
|
||||
return Ok(());
|
||||
}
|
||||
// The Expert Bundle's tor.exe, checked; on Linux (development) the system's tor.
|
||||
let program = self.comps.program("tor", "tor/tor")?;
|
||||
let bundle = self.paths().bin().join("tor");
|
||||
let bundle = program.starts_with(&bundle).then_some(bundle);
|
||||
let spec = crate::tor::unit(&cfg, self.paths(), program, bundle.as_deref())?;
|
||||
self.sup.ensure(spec);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn apply_ssh(&mut self) -> Result<()> {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
//! 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")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user