windows: zapret's hostlistRules, and the SSH tunnel
- hostlistRules (zapret-discord-youtube): a group of sites with its own strategy, as upstream's patch-zapret-config.py makes them: the preset's profiles for the rule's family (or another preset's, with configName; Discord's voice profile with it), pointed at the rule's own list with the standard excludes, or the rule's nfqwsArgs; ahead of the preset's own. WinDivert's filter takes the ports they add. Rules with enableDirectSync join the direct list. Names of zapret's own lists, and the instagram/soundcloud/twitter families (not in Flowseal's Windows release), are refused. Every preset with sample rules checked by winws.exe --dry-run (tools/winws-dry-run.sh); one without the profile a rule copies is refused, as upstream refuses it. - The SSH tunnel (sshProxy): Windows' own OpenSSH (System32) as ssh -N -D, with upstream's options and only the configured key offered (IdentitiesOnly: an agent's keys used up the server's tries); the key copied below the protected state root, as Windows' OpenSSH wants it and sing-box's SSH outbound reads it; the server's keys from hostKey, hostKeyFile or knownHostsFile. End to end on Linux against an sshd of the test's own: a page through each, two logins with the copied key. - The dev shell has OpenSSH, for that test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
88c8b88a49
commit
fb6c5962d0
14 files changed
+776
-24
No files matched your search
@@ -0,0 +1,179 @@
|
||||
//! The SSH tunnel: OpenSSH's dynamic SOCKS listener (`ssh -N -D`), run as upstream's
|
||||
//! ssh-proxy.nix runs it, with Windows' own client (System32\OpenSSH, there since Windows 10
|
||||
//! 1803). With the sing-box backend the proxy's `ssh-proxy` outbound is sing-box's own SSH
|
||||
//! client; this listener is for other programs, and the outbound of the other backends.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use ps_core::config::Config;
|
||||
|
||||
use crate::paths::{Paths, write_atomic};
|
||||
use crate::units::UnitSpec;
|
||||
|
||||
pub const UNIT: &str = "proxy-suite-ssh-proxy";
|
||||
|
||||
/// The OpenSSH client.
|
||||
pub fn program() -> Result<PathBuf> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let root = std::env::var_os("SystemRoot").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows"));
|
||||
let ssh = root.join(r"System32\OpenSSH\ssh.exe");
|
||||
if !ssh.is_file() {
|
||||
anyhow::bail!("Windows' OpenSSH client is not installed (Settings → System → Optional features → OpenSSH Client)");
|
||||
}
|
||||
Ok(ssh)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
Ok(PathBuf::from("ssh"))
|
||||
}
|
||||
|
||||
/// Where the key is copied: below the state root, which only SYSTEM and administrators reach.
|
||||
/// Windows' OpenSSH refuses a key others can read, and to a service running as SYSTEM the
|
||||
/// user's own copy is someone else's; upstream copies it for its service too (systemd's
|
||||
/// credentials).
|
||||
pub fn identity_path(paths: &Paths) -> PathBuf {
|
||||
paths.root.join("ssh").join("identity")
|
||||
}
|
||||
|
||||
fn copy_identity(cfg: &Config, paths: &Paths) -> Result<Option<PathBuf>> {
|
||||
let Some(src) = &cfg.ssh_proxy.identity_file else { return Ok(None) };
|
||||
let data = std::fs::read(src).with_context(|| format!("reading sshProxy.identityFile {src}"))?;
|
||||
let dst = identity_path(paths);
|
||||
std::fs::create_dir_all(dst.parent().unwrap())?;
|
||||
write_atomic(&dst, &data)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
Ok(Some(dst))
|
||||
}
|
||||
|
||||
/// The server's keys as sing-box takes them (`ssh-ed25519 AAAA…`): `hostKey`, else the lines
|
||||
/// of `hostKeyFile` or `knownHostsFile`, a known-hosts line's host names left off.
|
||||
pub fn host_keys(cfg: &Config, read: impl Fn(&str) -> Option<String>) -> Vec<String> {
|
||||
let s = &cfg.ssh_proxy;
|
||||
if !s.host_key.is_empty() {
|
||||
return s.host_key.clone();
|
||||
}
|
||||
let Some(text) = s.host_key_file.as_deref().or(s.known_hosts_file.as_deref()).and_then(read) else {
|
||||
return Vec::new();
|
||||
};
|
||||
text.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.map(|l| {
|
||||
let fields: Vec<&str> = l.split_whitespace().collect();
|
||||
// A key type comes first in a key line; in a known-hosts line, the hosts do.
|
||||
let is_type = |f: &str| f.starts_with("ssh-") || f.starts_with("ecdsa-") || f.starts_with("sk-");
|
||||
match fields.iter().position(|f| is_type(f)) {
|
||||
Some(at) => fields[at..].iter().take(2).copied().collect::<Vec<_>>().join(" "),
|
||||
None => l.to_owned(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The known-hosts file ssh is given: `knownHostsFile`, or one written from the server's keys,
|
||||
/// or one of the service's own, where `accept-new` keeps what it accepts.
|
||||
fn known_hosts(cfg: &Config, paths: &Paths, keys: &[String]) -> Result<PathBuf> {
|
||||
let s = &cfg.ssh_proxy;
|
||||
if let Some(f) = &s.known_hosts_file {
|
||||
return Ok(PathBuf::from(f));
|
||||
}
|
||||
let dir = paths.root.join("ssh");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
if keys.is_empty() {
|
||||
return Ok(dir.join("known_hosts"));
|
||||
}
|
||||
let host = s.server.host.as_deref().unwrap_or("");
|
||||
let name = if s.server.port == 22 { host.to_owned() } else { format!("[{host}]:{}", s.server.port) };
|
||||
let text: String = keys.iter().map(|k| format!("{name} {k}\n")).collect();
|
||||
let file = dir.join("known_hosts.given");
|
||||
write_atomic(&file, text.as_bytes())?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
pub fn args(cfg: &Config, known_hosts: &Path, identity: Option<&Path>) -> Vec<String> {
|
||||
let s = &cfg.ssh_proxy;
|
||||
// ssh reads "::1:1091" as a bad forwarding: an IPv6 address goes in brackets.
|
||||
let listen = if s.listener.address.contains(':') { format!("[{}]", s.listener.address) } else { s.listener.address.clone() };
|
||||
let mut a: Vec<String> = [
|
||||
"-N",
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"ExitOnForwardFailure=yes",
|
||||
"-o",
|
||||
"ServerAliveInterval=15",
|
||||
"-o",
|
||||
"ServerAliveCountMax=3",
|
||||
"-o",
|
||||
"ConnectTimeout=10",
|
||||
]
|
||||
.map(String::from)
|
||||
.to_vec();
|
||||
a.extend(["-o".into(), format!("StrictHostKeyChecking={}", s.strict_host_key_checking.as_str())]);
|
||||
a.extend(["-o".into(), format!("UserKnownHostsFile={}", known_hosts.display())]);
|
||||
a.extend(["-D".into(), format!("{listen}:{}", s.listener.port)]);
|
||||
if s.server.port != 22 {
|
||||
a.extend(["-p".into(), s.server.port.to_string()]);
|
||||
}
|
||||
if let Some(identity) = identity {
|
||||
// That key alone: not an agent's or ~/.ssh's first, which can use up the server's
|
||||
// MaxAuthTries before it.
|
||||
a.extend(["-i".into(), identity.display().to_string(), "-o".into(), "IdentitiesOnly=yes".into()]);
|
||||
}
|
||||
a.extend(s.extra_args.iter().cloned());
|
||||
let host = s.server.host.clone().unwrap_or_default();
|
||||
a.push(match &s.server.user {
|
||||
Some(u) => format!("{u}@{host}"),
|
||||
None => host,
|
||||
});
|
||||
a
|
||||
}
|
||||
|
||||
pub fn unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
|
||||
let keys = host_keys(cfg, |f| std::fs::read_to_string(f).ok());
|
||||
let known = known_hosts(cfg, paths, &keys)?;
|
||||
let identity = copy_identity(cfg, paths)?;
|
||||
let args = args(cfg, &known, identity.as_deref());
|
||||
Ok(UnitSpec { name: UNIT.into(), program, generation: args.join("\n"), args, env: Vec::new(), cwd: None })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cfg() -> Config {
|
||||
let mut c = Config::default();
|
||||
c.ssh_proxy.enable = true;
|
||||
c.ssh_proxy.server.host = Some("vps.example".into());
|
||||
c.ssh_proxy.server.user = Some("me".into());
|
||||
c
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upstreams_flags() {
|
||||
let mut c = cfg();
|
||||
c.ssh_proxy.server.port = 2222;
|
||||
let a = args(&c, Path::new("kh"), Some(Path::new(r"C:\keys\id_ed25519")));
|
||||
assert_eq!(&a[..2], ["-N", "-o"]);
|
||||
assert!(a.windows(2).any(|w| w == ["-D", "127.0.0.1:1091"]), "{a:?}");
|
||||
assert!(a.windows(2).any(|w| w == ["-p", "2222"]));
|
||||
assert!(a.windows(2).any(|w| w == ["-i", r"C:\keys\id_ed25519"]));
|
||||
assert!(a.contains(&"UserKnownHostsFile=kh".to_owned()));
|
||||
assert_eq!(a.last().unwrap(), "me@vps.example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_keys_from_lines_of_either_kind() {
|
||||
let mut c = cfg();
|
||||
c.ssh_proxy.host_key_file = Some("f".into());
|
||||
let keys = host_keys(&c, |_| Some("# c\nvps.example ssh-ed25519 AAAA1\nssh-rsa BBBB2 comment\n".into()));
|
||||
assert_eq!(keys, ["ssh-ed25519 AAAA1", "ssh-rsa BBBB2"]);
|
||||
c.ssh_proxy.host_key = vec!["ssh-ed25519 CCCC".into()];
|
||||
assert_eq!(host_keys(&c, |_| None), ["ssh-ed25519 CCCC"]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user