Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe291fab2b | ||
|
|
7cdd33f05e | ||
|
|
36532bcf47 | ||
|
|
e71f6bf5aa | ||
|
|
514ffb97ca | ||
|
|
9eed225ccc | ||
|
|
0a7d8d99c0 | ||
|
|
5cf3a237e6 |
No files matched your search
@@ -1,2 +1,4 @@
|
||||
target/
|
||||
dist/
|
||||
# The app logs tools/gui-shot.sh writes beside each shot.
|
||||
docs/screenshots/*.log
|
||||
@@ -21,10 +21,10 @@ tray icon) or with `proxy-ctl`, as upstream's is.
|
||||
| Local proxy | SOCKS5/HTTP on `127.0.0.1:1080` through sing-box (or the hybrid sing-box + XRay backend) |
|
||||
| Outbounds | links (vless/REALITY/TLS, vmess, trojan, shadowsocks, hysteria2, tuic, anytls, naive, socks, http), raw JSON, subscriptions, groups (failover, urltest, selector), chains, pins, route modes, routing rules by site, address, geodata, rule set or **program** |
|
||||
| zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter, and `hostlistRules` (a strategy of its own for a group of sites, copied from a preset or given) |
|
||||
| zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies and nfqws2's own learning of blocked sites |
|
||||
| zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies or [z2k](https://github.com/necronicle/z2k)'s (made by z2k's own generator, per category: YouTube, Discord, QUIC, the RKN list), and upstream's Lua around them: each site's working strategy kept across restarts, strategies keyed by site (the public suffix list), and the extended detector, which also learns sites blocked only some of the time and requests that never get an answer. The server's TLS replies reach the detectors through a WinDivert filter part; a download stalling mid-way (the 16 KB cutoff) is not seen on Windows, as WinDivert cannot hand over a flow's first packets alone. By its detector's verdicts the proxy routes too: what zapret2 cannot fix goes through the proxy (`proxyFallback`), what it fixes goes direct so it sees it (`directSync`) |
|
||||
| tg-ws-proxy | Flowseal's [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy), the headless proxy, on a bundled Python |
|
||||
| Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy |
|
||||
| AmneziaWG | `amneziaWg` profiles as outbounds, from a `.conf`, an AmneziaVPN `vpn://` link or settings: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too |
|
||||
| AmneziaWG | `amneziaWg` profiles, from a `.conf`, an AmneziaVPN `vpn://` link or settings. Without `asOutbound`, a **system-wide VPN**: amneziawg-windows's tunnel (amneziawg-go on Wintun, built from its source) as a Windows service of its own, with its routes, DNS and, for one peer that takes everything, its firewall blocking what leaves outside the tunnel; on and off in the app or `proxy-ctl awg on|off`. As outbounds: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too |
|
||||
| WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` |
|
||||
| autoProxy | `proxy.autoProxy`: the sites apps reach directly are probed through each exit in turn (direct first); one blocked directly but reached through an exit is routed through it, as upstream's prober decides (block pages, one exit per network first, strikes against exits that refuse). Blocks zapret can fix stay direct. A site that crawls directly (`slowBelowKiBps`) moves to the first exit that carries it as well as direct does. Its page in the app, or `proxy-ctl proxy auto`, shows, probes, learns and forgets |
|
||||
| whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins |
|
||||
@@ -32,13 +32,24 @@ tray icon) or with `proxy-ctl`, as upstream's is.
|
||||
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** |
|
||||
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy |
|
||||
|
||||
Not in this release, still to come: AmneziaWG as a system-wide VPN (its driver), Tor's onion service,
|
||||
the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and z2k
|
||||
strategies. Their options are accepted (they are upstream's), but the
|
||||
Not in this release, still to come: Tor's onion service,
|
||||
the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe. Their options are accepted (they are upstream's), but the
|
||||
service says, in its status and in the app, that it does not run them yet.
|
||||
|
||||
Needs 64-bit Windows 10 (1903 or later) or 11.
|
||||
|
||||
## Screenshots
|
||||
|
||||
Taken on Linux against the service with a demo configuration (`tools/screenshots.sh`), so the
|
||||
DPI bypass, which runs on Windows only, shows as inactive.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
## What has been verified
|
||||
|
||||
| Part | How |
|
||||
@@ -55,6 +66,7 @@ Needs 64-bit Windows 10 (1903 or later) or 11.
|
||||
| AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) |
|
||||
| autoProxy | its judgement (upstream's verdicts, walk, exit order, strikes, state) by unit tests; the config with its probe listeners and learned rule-sets accepted by `sing-box check`; on Linux with a local exit: probes through direct and the exit, a learn request, a site an app reached directly queued from the Clash API and probed at the next run, the state and the rule-set files written; a download held to 40 KiB/s seen crawling and moved to the exit. A site blocked here and reached through an exit needs a remote exit, so none was routed that way |
|
||||
| whitelist-bypass | its Windows programs built from upstream's tag with upstream's patches (links and passwords from the environment, never the command line); on Linux the service runs a joiner and a creator with their flags, the link and the login reaching them (`proxy-ctl wl join`, `wl auth`, `wl new`, `wl link`); a real call needs an account on a platform, so none was made |
|
||||
| AmneziaWG system-wide | under Wine's service manager (`tools/wine-setup-test.sh`): a profile added registers its tunnel service (program, configuration, dependencies), `proxy-ctl awg on` starts it, and the tunnel runs as a service up to creating the Wintun adapter, which Wine cannot; its log is read back; the service goes with its profile. Traffic through it needs real Windows |
|
||||
| WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) |
|
||||
| zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) |
|
||||
| The app | every page against the service running on Linux, in a window on a virtual display (Xvfb, Mesa's software Vulkan), clicked and typed into by a script, screenshots looked at, and the service's configuration checked after each change (`tools/gui-shot.sh`) |
|
||||
@@ -134,6 +146,11 @@ proxy-ctl proxy pin wl
|
||||
proxy-ctl wl auth laptop cookies.json
|
||||
proxy-ctl wl link laptop
|
||||
|
||||
# AmneziaWG as a system-wide VPN (a profile without asOutbound):
|
||||
proxy-ctl awg # profiles and their state
|
||||
proxy-ctl awg on home # start it; off stops it
|
||||
proxy-ctl awg log home # its tunnel's log
|
||||
|
||||
# autoProxy (set "proxy": { "autoProxy": { "enable": true } }):
|
||||
proxy-ctl proxy auto # what it routed, and where
|
||||
proxy-ctl proxy auto probe example.com # how a site answers through each exit
|
||||
|
||||
@@ -126,6 +126,20 @@
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
},
|
||||
"zapret2-extras": {
|
||||
"version": "2026.10.27+z2k.7beb975",
|
||||
"license": "MIT (z2k, proxy-suite's Lua); MPL-2.0 (the public suffix list)",
|
||||
"homepage": "https://github.com/necronicle/z2k",
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
},
|
||||
"amneziawg": {
|
||||
"version": "0-unstable-2026-08-14+e90531d",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/amnezia-vpn/amneziawg-windows",
|
||||
"bundled": true,
|
||||
"sources": []
|
||||
},
|
||||
"whitelist-bypass": {
|
||||
"version": "0.4.4",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -268,6 +268,40 @@ pub fn remove_wl(c: &mut Value, role: &str, name: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An AmneziaWG profile from an AmneziaVPN `vpn://` link or a `.conf`'s text: `kind` "vpn"
|
||||
/// (system-wide), "userspace" or "singBox" (an outbound of the proxy).
|
||||
pub fn add_awg_profile(c: &mut Value, name: &str, text: &str, kind: &str) -> Result<()> {
|
||||
if !ps_core::config::path_name_ok(name) || name.len() > 32 {
|
||||
bail!("a profile name takes up to 32 letters, digits, '.', '_' and '-', and no leading dot");
|
||||
}
|
||||
let text = text.trim();
|
||||
let mut profile = if text.starts_with("vpn://") {
|
||||
json!({ "vpn": text })
|
||||
} else if text.contains("[Interface]") {
|
||||
json!({ "config": text })
|
||||
} else {
|
||||
bail!("paste an AmneziaVPN vpn:// link or a .conf (with its [Interface])");
|
||||
};
|
||||
match kind {
|
||||
"vpn" => {}
|
||||
"userspace" | "singBox" => profile["asOutbound"] = kind.into(),
|
||||
_ => bail!("a profile is a system-wide VPN or an outbound (userspace, singBox)"),
|
||||
}
|
||||
if c["amneziaWg"]["profiles"].get(name).is_some() {
|
||||
bail!("there is a profile '{name}' already");
|
||||
}
|
||||
set_path(c, &["amneziaWg", "profiles", name], profile);
|
||||
set_path(c, &["amneziaWg", "enable"], true.into());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_awg_profile(c: &mut Value, name: &str) -> Result<()> {
|
||||
match c.get_mut("amneziaWg").and_then(|w| w.get_mut("profiles")).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
|
||||
Some(_) => Ok(()),
|
||||
None => bail!("no AmneziaWG profile '{name}'"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube`
|
||||
/// beside its release's lists, for `zapret2` beside its strategies' own.
|
||||
pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> {
|
||||
@@ -292,6 +326,21 @@ pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn amneziawg_profiles_come_from_links_or_confs() {
|
||||
let mut c = json!({});
|
||||
add_awg_profile(&mut c, "home", "vpn://AAAA", "vpn").unwrap();
|
||||
add_awg_profile(&mut c, "exit", "[Interface]\nPrivateKey = x\n", "userspace").unwrap();
|
||||
assert_eq!(c["amneziaWg"]["profiles"]["home"], json!({ "vpn": "vpn://AAAA" }));
|
||||
assert_eq!(c["amneziaWg"]["profiles"]["exit"]["asOutbound"], "userspace");
|
||||
assert_eq!(c["amneziaWg"]["enable"], true);
|
||||
assert!(add_awg_profile(&mut c, "home", "vpn://B", "vpn").is_err());
|
||||
assert!(add_awg_profile(&mut c, "x", "hello", "vpn").is_err());
|
||||
assert!(add_awg_profile(&mut c, "a/b", "vpn://B", "vpn").is_err());
|
||||
remove_awg_profile(&mut c, "home").unwrap();
|
||||
assert!(remove_awg_profile(&mut c, "home").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_bypass_entries_are_added_once_and_removed() {
|
||||
let mut c = json!({});
|
||||
|
||||
@@ -1,21 +1,47 @@
|
||||
//! For tools/winws-dry-run.sh: winws2's arguments as the service builds them, one per line.
|
||||
//! `zapret2_args <component dir> <component dir as Windows sees it> <state dir as Windows sees it>`
|
||||
//! `zapret2_args <component dir> <component dir as Windows sees it> <state dir as Windows sees it>
|
||||
//! [<extras dir> <extras dir as Windows sees it> <extras dir as Cygwin sees it> keenetic|z2k]`
|
||||
|
||||
use ps_core::config::Zapret2;
|
||||
use ps_core::zapret2::{Paths, args, keenetic};
|
||||
use ps_core::config::{StrategySource, Zapret2};
|
||||
use ps_core::zapret2::{Extras, Paths, args, keenetic, z2k};
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().collect();
|
||||
let conf = std::fs::read_to_string(std::path::Path::new(&a[1]).join("keenetic").join("nfqws2.conf")).unwrap();
|
||||
let (comp, state) = (&a[2], &a[3]);
|
||||
let source = keenetic(&conf, &format!("{comp}keenetic\\")).unwrap();
|
||||
let mut z = Zapret2 { domains: vec!["rutracker.org".into()], ..Default::default() };
|
||||
let mut source = keenetic(&conf, &format!("{comp}keenetic\\")).unwrap();
|
||||
let mut extras = None;
|
||||
if let [_, _, _, _, dir, win, cyg, kind] = &a[..] {
|
||||
let read = |f: &str| std::fs::read_to_string(std::path::Path::new(dir).join("z2k").join(f)).unwrap();
|
||||
if kind == "z2k" {
|
||||
z.strategy_source = StrategySource::Z2k;
|
||||
source = z2k(
|
||||
&read("profiles.plain"),
|
||||
&read("profiles.learn"),
|
||||
&read("blobs"),
|
||||
&read("ports"),
|
||||
&format!("{cyg}z2k"),
|
||||
&format!("{cyg}z2k/root"),
|
||||
&format!("{cyg}z2k/files/lua/"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let state_cyg = format!("/cygdrive/{}", state.replace(':', "").replace('\\', "/").to_lowercase());
|
||||
extras = Some(Extras {
|
||||
lua: format!("{win}lua\\"),
|
||||
z2k_lua: format!("{win}z2k\\files\\lua\\"),
|
||||
auto_lua: format!("{state_cyg}learned/zapret-hosts-auto.txt"),
|
||||
exclude_lua: vec![format!("{state_cyg}zapret-hosts-user-exclude.txt")],
|
||||
});
|
||||
}
|
||||
let paths = Paths {
|
||||
lua: format!("{comp}lua\\"),
|
||||
user: format!("{state}zapret-hosts-user.txt"),
|
||||
exclude: format!("{state}zapret-hosts-user-exclude.txt"),
|
||||
auto: format!("{state}learned\\zapret-hosts-auto.txt"),
|
||||
extras,
|
||||
};
|
||||
let z = Zapret2 { domains: vec!["rutracker.org".into()], ..Default::default() };
|
||||
for arg in args(&z, &source, &paths, false).unwrap() {
|
||||
println!("{arg}");
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{Backend, Config, GroupStrategy, Selection, StrategySource, ZapretDefaultDomains, ZapretEngine, ZapretPreset};
|
||||
use super::{Backend, Config, GroupStrategy, Selection, ZapretDefaultDomains, ZapretEngine, ZapretPreset};
|
||||
use crate::derived::{self, BUILTIN_TAGS};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -122,7 +122,6 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
|
||||
v.warn("killSwitch.enable", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel");
|
||||
}
|
||||
for (on, path, what) in [
|
||||
(cfg.amnezia_wg.enable && cfg.amnezia_wg.profiles.values().any(|p| p.as_outbound.is_none()), "amneziaWg.profiles", "AmneziaWG as a system-wide VPN (its driver; as outbounds it is here)"),
|
||||
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
|
||||
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
|
||||
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
|
||||
@@ -138,13 +137,8 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
|
||||
if z.enable && z.engine == ZapretEngine::DiscordYoutube && z.discord_youtube.include_extra_upstream_lists {
|
||||
v.warn("zapret.zapret-discord-youtube.includeExtraUpstreamLists", "Flowseal's Windows release has no instagram, soundcloud or twitter list: ignored");
|
||||
}
|
||||
if z.enable && z.engine == ZapretEngine::Zapret2 {
|
||||
if z.zapret2.strategy_source == StrategySource::Z2k && z.zapret2.profiles.is_none() {
|
||||
v.warn("zapret.zapret2.strategySource", "z2k's strategies are not on Windows yet: zapret2 does not start with them (nfqws2-keenetic's, or your own profiles, do)");
|
||||
}
|
||||
if z.zapret2.auto_hostlist.extended_detection {
|
||||
v.warn("zapret.zapret2.autoHostlist.extendedDetection", "the extended detection is not on Windows yet: nfqws2's own learning is used");
|
||||
}
|
||||
if z.enable && z.engine == ZapretEngine::Zapret2 && z.zapret2.cutoff.enable {
|
||||
v.warn("zapret.zapret2.cutoff.enable", "the 16 KB cutoff probe is not on Windows yet");
|
||||
}
|
||||
if z.enable && cfg.proxy.tun.enable {
|
||||
v.warn("proxy.tun.enable", "TUN and zapret together: zapret's packets are not kept off the TUN on Windows yet; use one or the other");
|
||||
@@ -505,6 +499,26 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
|
||||
|
||||
fn zapret(cfg: &Config, v: &mut Issues) {
|
||||
let z = &cfg.zapret;
|
||||
// They join winws2's options as written.
|
||||
let p = &z.zapret2.ports;
|
||||
for (path, values) in [("zapret.zapret2.ports.extraTcp", &p.extra_tcp), ("zapret.zapret2.ports.extraUdp", &p.extra_udp)] {
|
||||
for value in values {
|
||||
let text = match value {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
if !crate::zapret2::port_spec_ok(text.trim()) {
|
||||
v.error(path, format!("'{text}' is not a port or a range (N, or N-M, within 1-65535)"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (path, list) in [("zapret.zapret2.ports.tcp", &p.tcp), ("zapret.zapret2.ports.udp", &p.udp)] {
|
||||
if let Some(list) = list
|
||||
&& !list.split(',').all(|x| crate::zapret2::port_spec_ok(x.trim().replace(':', "-").as_str()))
|
||||
{
|
||||
v.error(path, "ports and ranges, comma-separated (N, or N-M, within 1-65535)");
|
||||
}
|
||||
}
|
||||
if !z.enable {
|
||||
return;
|
||||
}
|
||||
@@ -774,6 +788,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zapret2_extra_ports_are_ports() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.zapret.zapret2.ports.extra_tcp = vec![serde_json::json!(8443), serde_json::json!("50000-50099"), serde_json::json!("443\n--lua-init=@x.lua")];
|
||||
cfg.zapret.zapret2.ports.udp = Some("443,590:600".into());
|
||||
let errs = errors(&cfg);
|
||||
assert_eq!(errs.iter().filter(|e| e.starts_with("zapret.zapret2.ports")).count(), 1, "{errs:?}");
|
||||
assert!(crate::zapret2::port_spec_ok("1-65535") && !crate::zapret2::port_spec_ok("0") && !crate::zapret2::port_spec_ok("9-1") && !crate::zapret2::port_spec_ok("443 x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_bypass_names_are_checked_while_it_is_off() {
|
||||
let mut cfg = Config::default();
|
||||
@@ -839,12 +863,10 @@ mod tests {
|
||||
assert!(quiet.is_empty(), "{quiet:?}");
|
||||
let mut cfg = Config::default();
|
||||
cfg.kill_switch.enable = true;
|
||||
cfg.amnezia_wg.enable = true;
|
||||
cfg.amnezia_wg.profiles.insert("vpn".into(), Default::default());
|
||||
cfg.zapret.enable = true;
|
||||
cfg.proxy.tun.enable = true;
|
||||
let paths: Vec<String> = validate(&cfg).into_iter().filter(|i| i.severity == Severity::Warning && i.message.contains("Windows yet")).map(|i| i.path).collect();
|
||||
for want in ["killSwitch.enable", "amneziaWg.profiles", "proxy.tun.enable"] {
|
||||
for want in ["killSwitch.enable", "proxy.tun.enable"] {
|
||||
assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +105,10 @@ pub struct Env {
|
||||
pub windows: bool,
|
||||
/// Where autoProxy's learned rule-sets are (one file per exit), when it runs.
|
||||
pub autoproxy_rules_dir: Option<String>,
|
||||
/// zapret2's rule-sets (ps_core::zapret2::routing): what it fixes, sent direct
|
||||
/// (`zapret.directSync`), and what it cannot, for the proxy (`zapret2.proxyFallback`).
|
||||
pub zapret2_direct_rule_set: Option<String>,
|
||||
pub zapret2_proxy_rule_set: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Input<'a> {
|
||||
|
||||
@@ -146,6 +146,21 @@ pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], w
|
||||
let mut rule_sets = route.rule_set;
|
||||
let mut dns_rules = route.dns_rules;
|
||||
autoproxy::apply(input, probe_exits, &mut inbounds, &mut rules, route.pin_at, &mut rule_sets, &mut dns_rules, route.mode);
|
||||
// zapret2's: what it cannot fix through the proxy, after the explicit rules and autoProxy's,
|
||||
// ahead of the hosts it does fix, which go direct so it sees them. all-bypass sends
|
||||
// everything direct, and all-proxy keeps no direct lists.
|
||||
if let Some(path) = &env.zapret2_proxy_rule_set
|
||||
&& route.mode != super::RouteMode::AllBypass
|
||||
{
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-unfixable", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
}
|
||||
if let Some(path) = &env.zapret2_direct_rule_set
|
||||
&& !matches!(route.mode, super::RouteMode::AllBypass | super::RouteMode::AllProxy)
|
||||
{
|
||||
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-hosts", "path": path }));
|
||||
rules.push(json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
|
||||
}
|
||||
let after_sniff = rules.iter().position(|r| r["action"] == "sniff").map_or(0, |i| i + 1);
|
||||
rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" }));
|
||||
if hybrid {
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
//! zapret2 on Windows: winws2 (WinDivert) with the strategies upstream's module gives nfqws2
|
||||
//! (NFQUEUE). The strategy source is nfqws2-keenetic, read and patched as upstream's
|
||||
//! `zapret2/sources.nix` does; the profiles, markers, circular defaults and ports follow
|
||||
//! upstream's `zapret2/runtime.nix` and zapret2's own `common/list.sh`.
|
||||
//! (NFQUEUE): nfqws2-keenetic's, read and patched as upstream's `zapret2/sources.nix` does, or
|
||||
//! z2k's, made by its own generator (tools/build-zapret2-extras.sh); the profiles, markers,
|
||||
//! circular defaults, ports and Lua layers follow upstream's `zapret2/runtime.nix`, and the
|
||||
//! routing by the detector's verdicts its `direct-sync.template.sh`.
|
||||
//!
|
||||
//! What differs on Windows: WinDivert's port filters (`--wf-tcp-out`, `--wf-udp-out`) take
|
||||
//! the place of the queue's rules, and there are no marks. winws2 drops to Low integrity once
|
||||
//! it runs, so the learned list lives in a directory the service labels Low for it (winws2's
|
||||
//! own `--writable` insists on making the directory, which must already hold the list).
|
||||
//! Learning is nfqws2's own autohostlist; upstream's detector (`detect.lua`,
|
||||
//! `extendedDetection`) and z2k come later.
|
||||
//! the place of the queue's rules, a filter part hands the detectors the server's TLS
|
||||
//! records in place of the queue's packet windows, and there are no marks. winws2 drops to
|
||||
//! Low integrity once it runs, so what it writes lives in a directory the service labels Low
|
||||
//! for it (winws2's own `--writable` insists on making the directory).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::config::{StrategySource, Zapret2};
|
||||
|
||||
@@ -34,14 +36,59 @@ fn patch(what: &str, from: &str, to: &str, text: &str) -> Result<String, String>
|
||||
}
|
||||
}
|
||||
|
||||
/// nfqws2-keenetic's strategies, as upstream's sources.nix takes them.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
/// A strategy source, as upstream's sources.nix takes it: nfqws2-keenetic's or z2k's.
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Source {
|
||||
/// In nfqws2's order: UDP, QUIC, TCP. Hostlist markers still in.
|
||||
/// In nfqws2's order. Hostlist markers (and z2k's tokens) still in.
|
||||
pub profiles: Vec<String>,
|
||||
/// z2k: its profiles with the extended detector learning in its last place.
|
||||
pub learn_profiles: Option<Vec<String>>,
|
||||
pub blob_args: Vec<String>,
|
||||
pub tcp_ports: String,
|
||||
pub udp_ports: String,
|
||||
/// Lua its strategies need, loaded after zapret2's own (z2k's detectors).
|
||||
pub lua_init: Vec<String>,
|
||||
/// winws2 options it runs with.
|
||||
pub daemon_args: Vec<String>,
|
||||
/// z2k's: its profiles carry @HSUF@, @ESUF@ and the learner's tokens.
|
||||
pub z2k: bool,
|
||||
}
|
||||
|
||||
/// z2k's Lua, in its S99zapret2 order (upstream's sources.nix): z2k-range-rand resolves the
|
||||
/// ranges its strategies write; without it each fake goes once.
|
||||
pub const Z2K_LUA: [&str; 6] = ["z2k-alert", "z2k-quic-silence", "z2k-tcp16", "z2k-fooling-ext", "z2k-range-rand", "z2k-modern-core"];
|
||||
|
||||
/// z2k's strategies, as its generator made them (tools/build-zapret2-extras.sh): `plain` and
|
||||
/// `learn` its two profile sets, `blobs` its fake payloads, `ports` its NFQWS2_PORTS_*;
|
||||
/// `z2k_dir` where its files are and `root_dir` the tree its generator wrote, as winws2 reads
|
||||
/// them, and `lua` its `files/lua/` likewise (with a trailing separator).
|
||||
pub fn z2k(plain: &str, learn: &str, blobs: &str, ports: &str, z2k_dir: &str, root_dir: &str, lua: &str) -> Result<Source, String> {
|
||||
let fill = |t: &str| t.replace("@ROOT@", root_dir).replace("@Z2K@", z2k_dir);
|
||||
let split = |t: &str| -> Vec<String> { fill(t).split(" --new ").map(|p| p.trim().to_owned()).filter(|p| !p.is_empty()).collect() };
|
||||
let (plain, learn) = (split(plain), split(learn));
|
||||
if plain.is_empty() || !plain.iter().any(|p| p.contains("--lua-desync=circular")) {
|
||||
return Err("z2k's generated profiles are empty: is the zapret2-extras component installed?".into());
|
||||
}
|
||||
let port = |name: &str| -> Result<String, String> {
|
||||
ports
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix(&format!("{name}=")))
|
||||
.map(|v| v.trim().to_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
.ok_or_else(|| format!("z2k's ports: no {name}"))
|
||||
};
|
||||
Ok(Source {
|
||||
profiles: plain,
|
||||
learn_profiles: Some(learn),
|
||||
blob_args: words(&fill(blobs)).into_iter().map(str::to_owned).collect(),
|
||||
tcp_ports: port("NFQWS2_PORTS_TCP")?,
|
||||
udp_ports: port("NFQWS2_PORTS_UDP")?.replace(':', "-"),
|
||||
lua_init: Z2K_LUA.iter().map(|n| format!("{lua}{n}.lua")).collect(),
|
||||
// As its S99zapret2 runs nfqws2: a connection without SNI takes the name last seen
|
||||
// on that address, so it still meets its site's profile and strategy.
|
||||
daemon_args: vec!["--ipcache-hostname=1".into()],
|
||||
z2k: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// `conf`: its `etc/nfqws2/nfqws2.conf`; `dir`: where its `etc/nfqws2/` is (as winws2 will
|
||||
@@ -94,6 +141,7 @@ pub fn keenetic(conf: &str, dir: &str) -> Result<Source, String> {
|
||||
blob_args,
|
||||
tcp_ports: bare("TCP_PORTS")?.trim().to_owned(),
|
||||
udp_ports: bare("UDP_PORTS")?.trim().replace(':', "-"),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -108,6 +156,22 @@ pub struct Paths {
|
||||
pub exclude: String,
|
||||
/// `zapret-hosts-auto.txt`, in a directory labelled Low integrity.
|
||||
pub auto: String,
|
||||
/// The zapret2-extras component, when installed: upstream's Lua layers and z2k's.
|
||||
pub extras: Option<Extras>,
|
||||
}
|
||||
|
||||
/// Where the zapret2-extras component's files are, as winws2 reads them.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Extras {
|
||||
/// proxy-suite's own Lua (detect.lua, …), with a trailing separator.
|
||||
pub lua: String,
|
||||
/// z2k's `files/lua/`, with a trailing separator: its state layer persists strategies
|
||||
/// whichever the source.
|
||||
pub z2k_lua: String,
|
||||
/// The auto list and the lists the learner never learns from, as Lua arguments take
|
||||
/// paths: without a colon, so Cygwin's `/cygdrive/c/…` on Windows.
|
||||
pub auto_lua: String,
|
||||
pub exclude_lua: Vec<String>,
|
||||
}
|
||||
|
||||
/// A hostlist entry as nfqws2 takes one: a name (`^` for an exact match), nothing that could
|
||||
@@ -119,8 +183,9 @@ pub fn host_entry_ok(entry: &str) -> bool {
|
||||
&& entry.chars().enumerate().all(|(i, c)| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '*') || (c == '^' && i == 0))
|
||||
}
|
||||
|
||||
/// What `<HOSTLIST>` and `<HOSTLIST_NOAUTO>` expand to (zapret2's filter_apply_hostlist_target).
|
||||
fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String) {
|
||||
/// What `<HOSTLIST>` and `<HOSTLIST_NOAUTO>` expand to (zapret2's filter_apply_hostlist_target),
|
||||
/// and the configuration's own sites and exclusions, which join every profile that takes a list.
|
||||
fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String, String) {
|
||||
let a = &z.auto_hostlist;
|
||||
let base = format!("--hostlist={} --hostlist-exclude={}", p.user, p.exclude);
|
||||
let (with_auto, no_auto) = if a.enable {
|
||||
@@ -156,7 +221,57 @@ fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String) {
|
||||
if !excluded.is_empty() {
|
||||
statics.push_str(&format!(" --hostlist-exclude-domains={}", excluded.join(",")));
|
||||
}
|
||||
(with_auto + &statics, no_auto + &statics)
|
||||
(with_auto, no_auto, statics)
|
||||
}
|
||||
|
||||
/// The extended detector's arguments (upstream's learnArgs and stallWatch), when it learns.
|
||||
fn detector(z: &Zapret2, x: &Extras) -> (String, String) {
|
||||
let a = &z.auto_hostlist;
|
||||
let mut learn = vec![
|
||||
format!("auto={}", x.auto_lua),
|
||||
format!("exclude={}", x.exclude_lua.join(",")),
|
||||
format!("fails={}", a.fail_threshold),
|
||||
format!("time={}", a.fail_time),
|
||||
format!("inseq={}", a.incoming_maxseq),
|
||||
format!("retrans={}", a.retrans_threshold),
|
||||
// How many of the server's packets it watches (upstream's NFQUEUE window).
|
||||
"win=32".into(),
|
||||
];
|
||||
let excluded: Vec<&str> = z.exclude_domains.iter().map(String::as_str).filter(|d| host_entry_ok(d)).collect();
|
||||
if !excluded.is_empty() {
|
||||
learn.push(format!("exclude_domains={}", excluded.join(",")));
|
||||
}
|
||||
if z.strategy_log {
|
||||
learn.push("log".into());
|
||||
}
|
||||
let mut watch = vec![format!("fails={}", a.fail_threshold), format!("time={}", a.fail_time), "win=32".into()];
|
||||
if z.strategy_log {
|
||||
watch.push("log".into());
|
||||
}
|
||||
(
|
||||
learn.join(":"),
|
||||
format!("--in-range=-s65536 --payload=all --lua-desync=ps_watch:{} --in-range=x --payload=all", watch.join(":")),
|
||||
)
|
||||
}
|
||||
|
||||
/// A WinDivert filter part for the server's packets that begin a TLS handshake or alert
|
||||
/// record, on `ports`: what the detectors judge a site by (its ServerHello, a refusal), where
|
||||
/// nfqws2 is handed a flow's first packets by a queue window WinDivert has no means for.
|
||||
fn tls_reply_filter(ports: &str) -> Option<String> {
|
||||
let conds: Vec<String> = ports
|
||||
.split(',')
|
||||
.filter_map(|p| match p.split_once('-') {
|
||||
Some((a, b)) => Some(format!("(tcp.SrcPort >= {} and tcp.SrcPort <= {})", a.trim().parse::<u16>().ok()?, b.trim().parse::<u16>().ok()?)),
|
||||
None => Some(format!("tcp.SrcPort == {}", p.trim().parse::<u16>().ok()?)),
|
||||
})
|
||||
.collect();
|
||||
if conds.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"inbound and tcp.PayloadLength >= 6 and (tcp.Payload[0] == 0x16 or tcp.Payload[0] == 0x15) and tcp.Payload[1] == 0x03 and ({})",
|
||||
conds.join(" or ")
|
||||
))
|
||||
}
|
||||
|
||||
/// Detector settings a circular instance leaves unset come from autoHostlist.
|
||||
@@ -184,13 +299,25 @@ fn circular_fill(z: &Zapret2, token: &str) -> String {
|
||||
t
|
||||
}
|
||||
|
||||
/// A port or a range as winws2 takes one: `N` or `N-M`, within 1-65535.
|
||||
pub fn port_spec_ok(spec: &str) -> bool {
|
||||
let num = |s: &str| !s.is_empty() && s.len() <= 5 && s.chars().all(|c| c.is_ascii_digit()) && s.parse::<u32>().is_ok_and(|n| (1..=65535).contains(&n));
|
||||
match spec.split_once('-') {
|
||||
Some((a, b)) => num(a) && num(b) && a.parse::<u32>().ok() <= b.parse::<u32>().ok(),
|
||||
None => num(spec),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ports.extraTcp`/`extraUdp` as winws2's list: numbers and ranges alone (validated already;
|
||||
/// anything else dropped here too, as it joins winws2's options).
|
||||
fn port_list(values: &[serde_json::Value]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
serde_json::Value::String(s) => s.trim().to_owned(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.filter(|s| port_spec_ok(s))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
@@ -230,29 +357,91 @@ pub(crate) fn merge_ports(lists: &[&str]) -> String {
|
||||
|
||||
/// winws2's whole command line.
|
||||
pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Result<Vec<String>, String> {
|
||||
if z.strategy_source != StrategySource::Nfqws2Keenetic && z.profiles.is_none() {
|
||||
return Err("only the nfqws2-keenetic strategies are there on Windows yet (zapret.zapret2.strategySource)".into());
|
||||
if z.strategy_source == StrategySource::Z2k && z.profiles.is_none() && !source.z2k {
|
||||
return Err("z2k's strategies need the zapret2-extras component (proxy-ctl components)".into());
|
||||
}
|
||||
let (with_auto, no_auto) = hostlist_args(z, p);
|
||||
let render = |profile: &str| {
|
||||
let (with_auto, no_auto, statics) = hostlist_args(z, p);
|
||||
// The extended detector learns in place of nfqws2's own learning: with the source's own
|
||||
// strategies only, and the component installed.
|
||||
let learning = p.extras.as_ref().filter(|_| z.auto_hostlist.enable && z.auto_hostlist.extended_detection && z.profiles.is_none());
|
||||
let (learn_args, stall_watch) = learning.map(|x| detector(z, x)).unwrap_or_default();
|
||||
let exclude_suffix = {
|
||||
let mut e = format!("--hostlist-exclude={}", p.exclude);
|
||||
let excluded: Vec<&str> = z.exclude_domains.iter().map(String::as_str).filter(|d| host_entry_ok(d)).collect();
|
||||
if !excluded.is_empty() {
|
||||
e.push_str(&format!(" --hostlist-exclude-domains={}", excluded.join(",")));
|
||||
}
|
||||
e
|
||||
};
|
||||
let render = |profile: &str| -> String {
|
||||
if source.z2k && z.profiles.is_none() {
|
||||
// z2k's profiles name the lists themselves; the markers take only ours, and the
|
||||
// configuration's sites go where its generator left @HSUF@.
|
||||
return profile
|
||||
.replace("<HOSTLIST_NOAUTO>", &no_auto)
|
||||
.replace("<HOSTLIST>", &with_auto)
|
||||
.replace("@HSUF@", statics.trim())
|
||||
.replace("@ESUF@", &exclude_suffix)
|
||||
.replace("@STALLWATCH@", &stall_watch)
|
||||
.replace(":win=32@LEARNEXTRA@", &learn_args.split(":win=32").nth(1).map(|rest| format!(":win=32{rest}")).unwrap_or_else(|| ":win=32".into()))
|
||||
.replace("@AUTO@", learning.map_or("", |x| x.auto_lua.as_str()))
|
||||
.replace("@EXCLUDE@", &learning.map(|x| x.exclude_lua.join(",")).unwrap_or_default())
|
||||
.replace("@FAILS@", &z.auto_hostlist.fail_threshold.to_string())
|
||||
.replace("@TIME@", &z.auto_hostlist.fail_time.to_string())
|
||||
.replace("@INSEQ@", &z.auto_hostlist.incoming_maxseq.to_string())
|
||||
.replace("@RETRANS@", &z.auto_hostlist.retrans_threshold.to_string());
|
||||
}
|
||||
// nfqws2-keenetic: with the extended detector, its learning profile only reads the
|
||||
// auto list (upstream's sourceProfiles).
|
||||
let profile = if learning.is_some() { profile.replace("<HOSTLIST>", "<HOSTLIST_NOAUTO>") } else { profile.to_owned() };
|
||||
profile
|
||||
.replace("<HOSTLIST_NOAUTO>", &no_auto)
|
||||
.replace("<HOSTLIST>", &with_auto)
|
||||
.replace("<STALLWATCH> ", "")
|
||||
.replace("<STALLWATCH>", "")
|
||||
.replace("<HOSTLIST_NOAUTO>", &(no_auto.clone() + &statics))
|
||||
.replace("<HOSTLIST>", &(with_auto.clone() + &statics))
|
||||
.replace("<STALLWATCH> ", &if stall_watch.is_empty() { String::new() } else { format!("{stall_watch} ") })
|
||||
.replace("<STALLWATCH>", &stall_watch)
|
||||
};
|
||||
let profiles: Vec<String> = match &z.profiles {
|
||||
Some(own) => own.iter().map(|x| render(x)).collect(),
|
||||
None => source.profiles.iter().map(|x| render(x)).collect(),
|
||||
let mut profiles: Vec<String> = match (&z.profiles, &source.learn_profiles) {
|
||||
(Some(own), _) => own.iter().map(|x| render(x)).collect(),
|
||||
(None, Some(learn)) if learning.is_some() => learn.iter().map(|x| render(x)).collect(),
|
||||
(None, _) => source.profiles.iter().map(|x| render(x)).collect(),
|
||||
};
|
||||
// After every source profile, so it only takes what none of them did: ps_learn, the TLS
|
||||
// sites in no list (z2k's places its own).
|
||||
if learning.is_some() && !source.z2k {
|
||||
profiles.push(format!(
|
||||
"--filter-tcp=443 --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:{learn_args}"
|
||||
));
|
||||
}
|
||||
|
||||
let mut opt: Vec<String> = Vec::new();
|
||||
if debug_packets {
|
||||
opt.push("--debug=1".into());
|
||||
}
|
||||
if z.profiles.is_none() {
|
||||
opt.extend(source.daemon_args.iter().cloned());
|
||||
}
|
||||
for lua in ["zapret-lib.lua", "zapret-antidpi.lua", "zapret-auto.lua"] {
|
||||
opt.push(format!("--lua-init=@{}{lua}", p.lua));
|
||||
}
|
||||
if z.profiles.is_none() {
|
||||
opt.extend(source.lua_init.iter().map(|f| format!("--lua-init=@{f}")));
|
||||
}
|
||||
// Upstream's layers, in its order: the per-site key, the fail stamp, z2k's state layer
|
||||
// (each site's strategy kept across restarts) and its every-change writes, the detector
|
||||
// (after z2k-alert.lua, whose detector it wraps), the strategy log.
|
||||
if let Some(x) = &p.extras {
|
||||
let mut layers = vec![
|
||||
format!("{}public-suffix-hostkey.lua", x.lua),
|
||||
format!("{}fail-stamp.lua", x.lua),
|
||||
format!("{}z2k-state-persist.lua", x.z2k_lua),
|
||||
format!("{}persist-every.lua", x.lua),
|
||||
format!("{}detect.lua", x.lua),
|
||||
];
|
||||
if z.strategy_log {
|
||||
layers.push(format!("{}strategy-log.lua", x.lua));
|
||||
}
|
||||
opt.extend(layers.into_iter().map(|f| format!("--lua-init=@{f}")));
|
||||
}
|
||||
for (name, file) in &z.blobs {
|
||||
opt.push(format!("--blob={name}:@{file}"));
|
||||
}
|
||||
@@ -313,6 +502,9 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
|
||||
let (wf_tcp, wf_udp) = (merge_ports(&tcp_all), merge_ports(&udp_all));
|
||||
if !wf_tcp.is_empty() {
|
||||
opt.push(format!("--wf-tcp-out={wf_tcp}"));
|
||||
if let Some(part) = tls_reply_filter(&wf_tcp) {
|
||||
opt.push(format!("--wf-raw-part={part}"));
|
||||
}
|
||||
}
|
||||
if !wf_udp.is_empty() {
|
||||
opt.push(format!("--wf-udp-out={wf_udp}"));
|
||||
@@ -326,6 +518,119 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
|
||||
Ok(opt)
|
||||
}
|
||||
|
||||
// --- what the proxy does with zapret2's verdicts (upstream's direct-sync.template.sh) -------
|
||||
|
||||
/// An entry a rule-set can take: an IPv4 or IPv6 address, or a name of two labels at least
|
||||
/// (a bare "com" would send the whole TLD past the proxy). The zapret scope writes the lists.
|
||||
fn host_valid(h: &str) -> bool {
|
||||
if let Ok(ip) = h.parse::<std::net::IpAddr>() {
|
||||
return ip.is_ipv4() || !h.contains('%');
|
||||
}
|
||||
let label_ok = |l: &str| {
|
||||
!l.is_empty()
|
||||
&& l.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
|
||||
&& !l.starts_with('-')
|
||||
&& !l.ends_with('-')
|
||||
};
|
||||
h.len() <= 253 && h.contains('.') && h.split('.').all(label_ok) && !h.chars().all(|c| c.is_ascii_digit() || c == '.')
|
||||
}
|
||||
|
||||
/// nfqws hostlists: one host a line, `#` comments, `^` for the name alone.
|
||||
fn hosts(text: &str) -> Vec<String> {
|
||||
text.lines()
|
||||
.map(|l| l.trim().to_ascii_lowercase())
|
||||
.map(|l| l.trim_start_matches('^').to_owned())
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#') && host_valid(l))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// detect.lua's verdicts ("kind<TAB>name<TAB>proto<TAB>..."), the last per name and proto:
|
||||
/// (name, proto) -> kind.
|
||||
fn verdicts(text: &str) -> BTreeMap<(String, String), String> {
|
||||
let mut out = BTreeMap::new();
|
||||
for line in text.lines() {
|
||||
let f: Vec<&str> = line.split('\t').collect();
|
||||
if f.len() < 3 || !host_valid(f[1]) {
|
||||
continue;
|
||||
}
|
||||
out.insert((f[1].to_owned(), f[2].to_owned()), f[0].to_owned());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn named(v: &BTreeMap<(String, String), String>, kind: &str, proto: &str) -> Vec<String> {
|
||||
v.iter().filter(|((_, p), k)| k.as_str() == kind && p == proto).map(|((n, _), _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
/// A name and a site key cover each other either way round: www.notion.so and notion.so.
|
||||
fn covers(a: &str, b: &str) -> bool {
|
||||
a == b || a.ends_with(&format!(".{b}")) || b.ends_with(&format!(".{a}"))
|
||||
}
|
||||
|
||||
fn is_ip(h: &str) -> bool {
|
||||
h.parse::<std::net::IpAddr>().is_ok()
|
||||
}
|
||||
|
||||
fn cidr(ips: &[String]) -> Vec<String> {
|
||||
ips.iter().map(|ip| if ip.contains(':') { format!("{ip}/128") } else { format!("{ip}/32") }).collect()
|
||||
}
|
||||
|
||||
/// The two rule-sets the proxy routes by, from zapret2's lists and its detector's verdicts:
|
||||
/// `direct`, the hosts zapret2 handles, sent direct so it sees them (the pinned ones, and the
|
||||
/// learned ones once a strategy got through for them, unless learned from transfers cut short);
|
||||
/// `proxy`, what it cannot fix, for the proxy to carry (sites every strategy failed for, all
|
||||
/// of a site's TCP or only its QUIC, and addresses that leave connections unanswered).
|
||||
/// `auto` is the learned list, none when learning is off.
|
||||
pub fn routing(user: &str, auto: Option<&str>, excluded: &str, verdicts_text: &str) -> (serde_json::Value, serde_json::Value) {
|
||||
use serde_json::json;
|
||||
let v = verdicts(verdicts_text);
|
||||
let works = named(&v, "works", "tcp");
|
||||
// Learned from a transfer cut short: success is judged on the first 4 KB, which the
|
||||
// cutoff lets through, so "works" proves nothing for it.
|
||||
let stalls = named(&v, "stalls", "cutoff");
|
||||
let excluded = hosts(excluded);
|
||||
let mut direct: Vec<String> = hosts(user);
|
||||
direct.extend(
|
||||
hosts(auto.unwrap_or(""))
|
||||
.into_iter()
|
||||
.filter(|h| works.iter().any(|w| covers(h, w)) && !stalls.iter().any(|s| covers(h, s))),
|
||||
);
|
||||
direct.sort();
|
||||
direct.dedup();
|
||||
direct.retain(|h| !excluded.contains(h));
|
||||
let (ips, names): (Vec<String>, Vec<String>) = direct.into_iter().partition(|h| is_ip(h));
|
||||
let mut rules = Vec::new();
|
||||
if !names.is_empty() {
|
||||
rules.push(json!({ "domain_suffix": names }));
|
||||
}
|
||||
if !ips.is_empty() {
|
||||
rules.push(json!({ "ip_cidr": cidr(&ips) }));
|
||||
}
|
||||
let direct = json!({ "version": 1, "rules": rules });
|
||||
|
||||
// A site keyed by its address (no name seen) goes by address.
|
||||
let tcp = named(&v, "unfixable", "tcp");
|
||||
let udp = named(&v, "unfixable", "udp");
|
||||
let (tcp_ips, tcp_names): (Vec<String>, Vec<String>) = tcp.into_iter().partition(|h| is_ip(h));
|
||||
let (udp_ips, udp_names): (Vec<String>, Vec<String>) = udp.into_iter().partition(|h| is_ip(h));
|
||||
let mut blocked = named(&v, "blocked", "ip");
|
||||
blocked.extend(tcp_ips);
|
||||
let mut rules = Vec::new();
|
||||
if !tcp_names.is_empty() {
|
||||
rules.push(json!({ "domain_suffix": tcp_names }));
|
||||
}
|
||||
if !udp_names.is_empty() {
|
||||
rules.push(json!({ "network": ["udp"], "port": [443], "domain_suffix": udp_names }));
|
||||
}
|
||||
if !udp_ips.is_empty() {
|
||||
rules.push(json!({ "network": ["udp"], "port": [443], "ip_cidr": cidr(&udp_ips) }));
|
||||
}
|
||||
if !blocked.is_empty() {
|
||||
rules.push(json!({ "ip_cidr": cidr(&blocked) }));
|
||||
}
|
||||
(direct, json!({ "version": 1, "rules": rules }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -364,9 +669,81 @@ UDP_PORTS=443,590:600
|
||||
user: r"C:\s\user.txt".into(),
|
||||
exclude: r"C:\s\exclude.txt".into(),
|
||||
auto: r"C:\s\learned\auto.txt".into(),
|
||||
extras: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn extras() -> Extras {
|
||||
Extras {
|
||||
lua: r"C:\x\lua\".into(),
|
||||
z2k_lua: r"C:\x\z2k\files\lua\".into(),
|
||||
auto_lua: "/cygdrive/c/s/learned/auto.txt".into(),
|
||||
exclude_lua: vec!["/cygdrive/c/s/exclude.txt".into()],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdicts_route_what_zapret2_fixes_direct_and_the_rest_by_the_proxy() {
|
||||
let user = "^pinned.example\n# a comment\ncom\n203.0.113.5\nbad entry\n";
|
||||
let auto = "learned.example\nnotyet.example\ncut.example\nleft.example\n";
|
||||
let verdicts = "works\tlearned.example\ttcp\t\t1\nworks\tcut.example\ttcp\t\t1\nstalls\tcut.example\tcutoff\t\t2\n\
|
||||
works\tleft.example\ttcp\t\t1\nunfixable\tdead.example\ttcp\t\t3\nunfixable\tquic.example\tudp\t\t3\n\
|
||||
blocked\t198.51.100.7\tip\t\t4\nunfixable\tgone.example\ttcp\t\t3\nretry\tgone.example\ttcp\t\t5\n";
|
||||
let (direct, proxy) = routing(user, Some(auto), "left.example\n", verdicts);
|
||||
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["learned.example", "pinned.example"]));
|
||||
assert_eq!(direct["rules"][1]["ip_cidr"], serde_json::json!(["203.0.113.5/32"]));
|
||||
assert_eq!(proxy["rules"][0]["domain_suffix"], serde_json::json!(["dead.example"]), "gone.example's last verdict clears it");
|
||||
assert_eq!(proxy["rules"][1], serde_json::json!({ "network": ["udp"], "port": [443], "domain_suffix": ["quic.example"] }));
|
||||
assert_eq!(proxy["rules"][2]["ip_cidr"], serde_json::json!(["198.51.100.7/32"]));
|
||||
// Learning off: the pinned ones alone.
|
||||
let (direct, _) = routing(user, None, "", verdicts);
|
||||
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["pinned.example"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extended_detector_learns_in_place_of_nfqws2() {
|
||||
let z = Zapret2 { strategy_log: true, ..Default::default() };
|
||||
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
|
||||
let p = Paths { extras: Some(extras()), ..paths() };
|
||||
let a = args(&z, &s, &p, false).unwrap();
|
||||
let inits: Vec<&String> = a.iter().filter(|x| x.starts_with("--lua-init=")).collect();
|
||||
assert_eq!(inits.len(), 3 + 6, "zapret's, then upstream's layers: {inits:?}");
|
||||
assert_eq!(inits[3], r"--lua-init=@C:\x\lua\public-suffix-hostkey.lua");
|
||||
assert_eq!(inits[5], r"--lua-init=@C:\x\z2k\files\lua\z2k-state-persist.lua");
|
||||
assert!(inits[7].ends_with("detect.lua") && inits[8].ends_with("strategy-log.lua"));
|
||||
let learn = a.iter().find(|x| x.starts_with("--lua-desync=ps_learn:")).expect("a learning profile");
|
||||
assert!(learn.starts_with("--lua-desync=ps_learn:auto=/cygdrive/c/s/learned/auto.txt:exclude=/cygdrive/c/s/exclude.txt:fails="), "{learn}");
|
||||
assert!(learn.ends_with(":win=32:log"));
|
||||
assert!(a.iter().any(|x| x.starts_with("--lua-desync=ps_watch:")), "the stall watch, where <STALLWATCH> was");
|
||||
assert!(!a.iter().any(|x| x.starts_with("--hostlist-auto=")), "nfqws2's own learning is off");
|
||||
let raw = a.iter().find(|x| x.starts_with("--wf-raw-part=")).expect("the TLS replies' filter");
|
||||
assert!(raw.contains("tcp.Payload[0] == 0x16") && raw.contains("tcp.SrcPort == 443"), "{raw}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn z2k_fills_its_tokens() {
|
||||
let plain = "--filter-tcp=443 --hostlist-exclude=@ROOT@/lists/whitelist.txt @ESUF@ --lua-desync=circular:fails=3 --new --filter-tcp=443 --filter-l7=tls <HOSTLIST> @HSUF@";
|
||||
let learn = "--filter-tcp=443 @STALLWATCH@ --lua-desync=circular:fails=3 --new --filter-tcp=443 --lua-desync=ps_learn:auto=@AUTO@:exclude=@ROOT@/lists/whitelist.txt,@EXCLUDE@:fails=@FAILS@:time=@TIME@:inseq=@INSEQ@:retrans=@RETRANS@:win=32@LEARNEXTRA@";
|
||||
let s = z2k(plain, learn, "--blob=a:@@Z2K@/files/fake/a.bin", "NFQWS2_PORTS_TCP=80,443\nNFQWS2_PORTS_UDP=443\n", "/cygdrive/c/x/z2k", "/cygdrive/c/x/z2k/root", "/cygdrive/c/x/z2k/files/lua/").unwrap();
|
||||
assert_eq!(s.blob_args, ["--blob=a:@/cygdrive/c/x/z2k/files/fake/a.bin"]);
|
||||
assert!(s.lua_init[0].ends_with("z2k-alert.lua") && s.daemon_args == ["--ipcache-hostname=1"]);
|
||||
let mut z = Zapret2 { strategy_source: StrategySource::Z2k, ..Default::default() };
|
||||
z.domains = vec!["mine.example".into()];
|
||||
// Without the detector: the plain set, our lists where the markers are.
|
||||
z.auto_hostlist.extended_detection = false;
|
||||
let a = args(&z, &s, &Paths { extras: Some(extras()), ..paths() }, false).unwrap().join(" ");
|
||||
assert!(a.contains("--hostlist-exclude=/cygdrive/c/x/z2k/root/lists/whitelist.txt --hostlist-exclude=C:\\s\\exclude.txt"), "{a}");
|
||||
assert!(a.contains("--hostlist-auto=C:\\s\\learned\\auto.txt") && a.contains("--hostlist-domains=mine.example"), "{a}");
|
||||
assert!(a.contains("--lua-init=@/cygdrive/c/x/z2k/files/lua/z2k-alert.lua"));
|
||||
// With it: the learning set, every token filled.
|
||||
z.auto_hostlist.extended_detection = true;
|
||||
let a = args(&z, &s, &Paths { extras: Some(extras()), ..paths() }, false).unwrap().join(" ");
|
||||
assert!(!a.contains('@') || !a.contains("@AUTO@"), "{a}");
|
||||
assert!(a.contains("ps_learn:auto=/cygdrive/c/s/learned/auto.txt:exclude=/cygdrive/c/x/z2k/root/lists/whitelist.txt,/cygdrive/c/s/exclude.txt:fails=3"), "{a}");
|
||||
assert!(a.contains("--lua-desync=ps_watch:"), "{a}");
|
||||
assert!(!a.contains("@STALLWATCH@") && !a.contains("@LEARNEXTRA@") && !a.contains("@HSUF@") && !a.contains("@ESUF@"), "{a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keenetic_is_read_and_patched_as_upstream_does() {
|
||||
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
|
||||
|
||||
@@ -289,3 +289,29 @@ fn auto_proxy_never_routes_what_it_excludes() {
|
||||
);
|
||||
check_sing_box(&sb, &dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zapret2s_rule_sets_follow_autoproxy_and_the_mode() {
|
||||
let dir = scratch("zapret2-sync");
|
||||
let (direct, proxy) = (dir.join("direct.json"), dir.join("proxy.json"));
|
||||
std::fs::write(&direct, r#"{"version":1,"rules":[{"domain_suffix":["fixed.example"]}]}"#).unwrap();
|
||||
std::fs::write(&proxy, r#"{"version":1,"rules":[{"domain_suffix":["unfixable.example"]}]}"#).unwrap();
|
||||
let cfg = base();
|
||||
let mut e = env(&dir);
|
||||
e.windows = false;
|
||||
e.zapret2_direct_rule_set = Some(direct.to_string_lossy().into());
|
||||
e.zapret2_proxy_rule_set = Some(proxy.to_string_lossy().into());
|
||||
let render_with = |state: &State| render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap().sing_box.unwrap();
|
||||
let sb = render_with(&State::default());
|
||||
let rules = sb["route"]["rules"].as_array().unwrap();
|
||||
let n = rules.len();
|
||||
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||
assert_eq!(rules[n - 1], json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
|
||||
check_sing_box(&sb, &dir);
|
||||
// all-proxy keeps no direct lists; all-bypass sends everything direct.
|
||||
let mut state = State { route_mode: Some(RouteMode::AllProxy), ..Default::default() };
|
||||
let tags = |sb: &Value| sb["route"]["rules"].as_array().unwrap().iter().filter_map(|r| r["rule_set"][0].as_str().map(str::to_owned)).collect::<Vec<_>>();
|
||||
assert_eq!(tags(&render_with(&state)), ["zapret-unfixable"]);
|
||||
state.route_mode = Some(RouteMode::AllBypass);
|
||||
assert!(tags(&render_with(&state)).is_empty());
|
||||
}
|
||||
@@ -54,6 +54,11 @@ enum Cmd {
|
||||
#[command(subcommand)]
|
||||
verb: TgVerb,
|
||||
},
|
||||
/// AmneziaWG profiles: the system-wide ones started and stopped.
|
||||
Awg {
|
||||
#[command(subcommand)]
|
||||
verb: Option<AwgVerb>,
|
||||
},
|
||||
/// whitelist-bypass creators and joiners.
|
||||
Wl {
|
||||
#[command(subcommand)]
|
||||
@@ -72,6 +77,22 @@ enum TgVerb {
|
||||
Link,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum AwgVerb {
|
||||
/// Profiles and their state.
|
||||
List,
|
||||
/// Start a system-wide profile's tunnel.
|
||||
On { profile: String },
|
||||
/// Stop it.
|
||||
Off { profile: String },
|
||||
/// Its tunnel's log.
|
||||
Log {
|
||||
profile: String,
|
||||
#[arg(short = 'n', long, default_value_t = 50)]
|
||||
lines: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum WlVerb {
|
||||
/// Creators and joiners, and their state.
|
||||
@@ -681,6 +702,51 @@ async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn awg(ctl: &Ctl, verb: Option<AwgVerb>) -> Result<()> {
|
||||
match verb.unwrap_or(AwgVerb::List) {
|
||||
AwgVerb::List => {
|
||||
let r = ctl.call(Request::AwgList).await?;
|
||||
if ctl.json {
|
||||
ctl.print(&r);
|
||||
return Ok(());
|
||||
}
|
||||
let profiles = r["profiles"].as_array().cloned().unwrap_or_default();
|
||||
if profiles.is_empty() {
|
||||
println!("No AmneziaWG profiles configured.");
|
||||
return Ok(());
|
||||
}
|
||||
if r["enabled"] != true {
|
||||
println!("AmneziaWG is off (amneziaWg.enable).");
|
||||
}
|
||||
println!(" {:<24} {:<12} {:<12} INTERFACE", "PROFILE", "KIND", "STATUS");
|
||||
for p in profiles {
|
||||
let kind = match p["kind"].as_str().unwrap_or("") {
|
||||
"vpn" => "system VPN",
|
||||
"userspace" => "outbound",
|
||||
"singBox" => "outbound (WG)",
|
||||
k => k,
|
||||
};
|
||||
println!(" {:<24} {:<12} {:<12} {}", p["name"].as_str().unwrap_or(""), kind, p["state"].as_str().unwrap_or(""), p["interface"].as_str().unwrap_or("-"));
|
||||
}
|
||||
}
|
||||
AwgVerb::On { profile } => {
|
||||
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: true }).await?;
|
||||
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
|
||||
}
|
||||
AwgVerb::Off { profile } => {
|
||||
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: false }).await?;
|
||||
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
|
||||
}
|
||||
AwgVerb::Log { profile, lines } => {
|
||||
let r = ctl.call(Request::AwgLog { name: profile, lines }).await?;
|
||||
for l in r["lines"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
println!("{l}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A login for the DION and Bitrix creators, which log in on their own from it.
|
||||
fn password_login(platform: &str, name: &str) -> Result<String> {
|
||||
let fields: &[&str] = match platform {
|
||||
@@ -834,6 +900,7 @@ async fn real_main() -> Result<()> {
|
||||
Cmd::Zapret { verb } => zapret(&ctl, verb).await?,
|
||||
Cmd::Components { verb } => components(&ctl, verb).await?,
|
||||
Cmd::Wl { verb } => wl(&ctl, verb).await?,
|
||||
Cmd::Awg { verb } => awg(&ctl, verb).await?,
|
||||
Cmd::Tg { verb: TgVerb::Link } => {
|
||||
let r = ctl.call(Request::TgLinks).await?;
|
||||
for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::*;
|
||||
|
||||
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route]);
|
||||
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route, Lock]);
|
||||
|
||||
pub struct AppAssets;
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! AmneziaWG: its profiles, system-wide VPNs (started and stopped here, their tunnel's log) or
|
||||
//! outbounds of the proxy; one added from an AmneziaVPN vpn:// link or a .conf, or removed.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gpui_kit::assets::IconName;
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
|
||||
use gpui_kit::component::notification::Notification;
|
||||
use gpui_kit::component::radio::RadioGroup;
|
||||
use gpui_kit::component::switch::Switch;
|
||||
use gpui_kit::component::tag::Tag;
|
||||
use gpui_kit::component::*;
|
||||
use gpui_kit::*;
|
||||
use ps_client::edits;
|
||||
use ps_ipc::Request;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::widgets::{card, hint, page, state_tag};
|
||||
use crate::model::Model;
|
||||
|
||||
const KINDS: [(&str, &str); 3] = [("vpn", "System-wide VPN"), ("userspace", "Outbound (AmneziaWG)"), ("singBox", "Outbound (plain WireGuard)")];
|
||||
|
||||
pub struct AmneziaWgPage {
|
||||
model: Entity<Model>,
|
||||
name: Entity<InputState>,
|
||||
text: Entity<TextareaState>,
|
||||
kind: usize,
|
||||
list: Result<Value, String>,
|
||||
loaded_at: Option<Instant>,
|
||||
/// A profile's tunnel log, while shown.
|
||||
logs: BTreeMap<String, Result<Vec<String>, String>>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl AmneziaWgPage {
|
||||
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let name = cx.new(|cx| InputState::new(window, cx).placeholder("home"));
|
||||
let text = cx.new(|cx| TextareaState::new(window, cx).rows(5).placeholder("vpn://… from AmneziaVPN, or a .conf: [Interface] …"));
|
||||
let subscriptions = vec![cx.observe(&model, |this, _, cx| {
|
||||
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(3)) {
|
||||
this.load(cx);
|
||||
}
|
||||
})];
|
||||
let mut this = Self { model, name, text, kind: 0, list: Ok(Value::Null), loaded_at: None, logs: BTreeMap::new(), _subscriptions: subscriptions };
|
||||
this.load(cx);
|
||||
this
|
||||
}
|
||||
|
||||
fn load(&mut self, cx: &mut Context<Self>) {
|
||||
self.loaded_at = Some(Instant::now());
|
||||
let job = self.model.read(cx).bridge().call(Request::AwgList);
|
||||
cx.spawn(async move |this, cx| {
|
||||
let r = job.await;
|
||||
this.update(cx, |this, cx| {
|
||||
this.list = r.map_err(|e| format!("{e:#}"));
|
||||
cx.notify();
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn set(&mut self, name: String, on: bool, cx: &mut Context<Self>) {
|
||||
let what = format!("{name}: {}", if on { "tunnel up" } else { "tunnel down" });
|
||||
let job = self.model.read(cx).bridge().call(Request::AwgSet { name, on });
|
||||
let model = self.model.clone();
|
||||
cx.spawn(async move |this, cx| {
|
||||
let r = job.await;
|
||||
model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx));
|
||||
this.update(cx, |this, cx| this.load(cx)).ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn toggle_log(&mut self, name: String, cx: &mut Context<Self>) {
|
||||
if self.logs.remove(&name).is_some() {
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
let job = self.model.read(cx).bridge().call(Request::AwgLog { name: name.clone(), lines: 30 });
|
||||
cx.spawn(async move |this, cx| {
|
||||
let r = job.await.map(|v| v["lines"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()).map_err(|e| format!("{e:#}"));
|
||||
this.update(cx, |this, cx| {
|
||||
this.logs.insert(name, r);
|
||||
cx.notify();
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn add(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let name = self.name.read(cx).value().trim().to_owned();
|
||||
let text = self.text.read(cx).value().to_string();
|
||||
let kind = KINDS[self.kind].0;
|
||||
// Checked here first, for a message at once.
|
||||
if let Err(e) = edits::add_awg_profile(&mut serde_json::json!({}), &name, &text, kind) {
|
||||
window.push_notification(Notification::error(format!("{e:#}")), cx);
|
||||
return;
|
||||
}
|
||||
self.name.update(cx, |s, cx| s.set_value("", window, cx));
|
||||
self.text.update(cx, |s, cx| s.set_value("", window, cx));
|
||||
let what = format!("AmneziaWG profile '{name}' added");
|
||||
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_awg_profile(c, &name, &text, kind), cx));
|
||||
}
|
||||
|
||||
fn remove(&mut self, name: String, cx: &mut Context<Self>) {
|
||||
self.model.update(cx, |m, cx| m.edit(format!("AmneziaWG profile '{name}' removed"), move |c| edits::remove_awg_profile(c, &name), cx));
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for AmneziaWgPage {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let m = self.model.read(cx);
|
||||
let body = page("AmneziaWG", cx);
|
||||
if m.config().is_null() {
|
||||
return body.child(hint("Waiting for the service…", cx));
|
||||
}
|
||||
let on = m.config()["amneziaWg"]["enable"] == true;
|
||||
let model = self.model.clone();
|
||||
let enable = Switch::new("awg-enable").checked(on).on_change(move |on, _, cx| {
|
||||
let on = *on;
|
||||
model.update(cx, |m, cx| {
|
||||
m.edit(
|
||||
if on { "AmneziaWG is on" } else { "AmneziaWG is off" },
|
||||
move |c| {
|
||||
edits::set_path(c, &["amneziaWg", "enable"], on.into());
|
||||
Ok(())
|
||||
},
|
||||
cx,
|
||||
)
|
||||
})
|
||||
});
|
||||
let about = card("AmneziaWG", Some(enable.into_any_element()), cx).child(hint(
|
||||
"WireGuard with AmneziaVPN's obfuscation. A system-wide profile is a VPN of its own (a network adapter, its routes and DNS); with one peer that takes everything, it also blocks what would leave outside the tunnel. An outbound profile is one more exit for the proxy, with nothing else changed.",
|
||||
cx,
|
||||
));
|
||||
|
||||
let mut profiles = card("Profiles", Some(Button::new("awg-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))).into_any_element()), cx);
|
||||
match &self.list {
|
||||
Err(e) => profiles = profiles.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
|
||||
Ok(l) => {
|
||||
let list = l["profiles"].as_array().cloned().unwrap_or_default();
|
||||
if list.is_empty() {
|
||||
profiles = profiles.child(hint("None yet: add one below.", cx));
|
||||
}
|
||||
for (i, p) in list.iter().enumerate() {
|
||||
let name = p["name"].as_str().unwrap_or("").to_owned();
|
||||
let vpn = p["kind"] == "vpn";
|
||||
let state = p["state"].as_str().unwrap_or("").to_owned();
|
||||
let kind = match p["kind"].as_str().unwrap_or("") {
|
||||
"vpn" => Tag::info().child("system VPN"),
|
||||
"userspace" => Tag::secondary().child("outbound"),
|
||||
_ => Tag::secondary().child("outbound (WireGuard)"),
|
||||
};
|
||||
let mut line = div()
|
||||
.h_flex()
|
||||
.gap_3()
|
||||
.items_center()
|
||||
.child(div().font_medium().child(name.clone()))
|
||||
.child(kind)
|
||||
.child(if state == "windows-only" { Tag::secondary().child("Windows only") } else { state_tag(&state) })
|
||||
.child(div().flex_1());
|
||||
if vpn {
|
||||
let (n1, n2) = (name.clone(), name.clone());
|
||||
let running = matches!(state.as_str(), "active" | "activating");
|
||||
line = line
|
||||
.child(Button::new(("awg-log", i)).small().ghost().label("Log").on_click(cx.listener(move |this, _, _, cx| this.toggle_log(n1.clone(), cx))))
|
||||
.child(
|
||||
Switch::new(("awg-on", i))
|
||||
.checked(running)
|
||||
.disabled(!on)
|
||||
.on_change(cx.listener(move |this, v: &bool, _, cx| this.set(n2.clone(), *v, cx))),
|
||||
);
|
||||
}
|
||||
let n3 = name.clone();
|
||||
line = line.child(Button::new(("awg-remove", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove(n3.clone(), cx))));
|
||||
let mut row = div().v_flex().gap_2().py_2().border_t_1().border_color(cx.theme().border).child(line);
|
||||
match self.logs.get(&name) {
|
||||
Some(Ok(lines)) => {
|
||||
let text = if lines.is_empty() { "(no log yet)".to_owned() } else { lines.join("\n") };
|
||||
row = row.child(div().text_xs().font_family("monospace").text_color(cx.theme().muted_foreground).child(text));
|
||||
}
|
||||
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
|
||||
None => {}
|
||||
}
|
||||
profiles = profiles.child(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| label)).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| {
|
||||
this.kind = *ix;
|
||||
cx.notify();
|
||||
}));
|
||||
let add = card("Add a profile", Some(Button::new("awg-add").small().primary().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx)
|
||||
.child(div().v_flex().gap_1().child(div().text_sm().child("Name (also the adapter's)")).child(Input::new(&self.name)))
|
||||
.child(kinds)
|
||||
.child(Textarea::new(&self.text))
|
||||
.child(hint("The link or .conf stays in the service's configuration, which only you and administrators read. Starting at sign-in (autostart), the endpoint and the rest are in Settings, under amneziaWg.profiles.", cx));
|
||||
|
||||
body.child(about).child(profiles).child(add)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ use super::widgets::{card, hint, page, state_tag};
|
||||
use crate::model::Model;
|
||||
|
||||
const ENGINES: [(&str, &str); 2] = [("zapret-discord-youtube", "Flowseal's presets (zapret)"), ("zapret2", "zapret2")];
|
||||
const SOURCES: [(&str, &str); 2] = [("nfqws2-keenetic", "nfqws2-keenetic"), ("z2k", "z2k (per category: YouTube, Discord, QUIC, the RKN list)")];
|
||||
const GAME_FILTERS: [(&str, &str); 4] = [("null", "Off"), ("all", "TCP and UDP"), ("tcp", "TCP only"), ("udp", "UDP only")];
|
||||
|
||||
/// Preset names as the service matches them: without spaces, any case.
|
||||
@@ -180,7 +181,7 @@ impl Render for DpiPage {
|
||||
.child(engines)
|
||||
.child(hint(
|
||||
if engine == "zapret2" {
|
||||
"zapret2 (winws2) with nfqws2-keenetic's strategies; it learns which sites are blocked as it goes."
|
||||
"zapret2 (winws2): it learns which sites are blocked as it goes, rotates each one's strategy until one works, and keeps it across restarts."
|
||||
} else {
|
||||
"Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists."
|
||||
},
|
||||
@@ -189,9 +190,35 @@ impl Render for DpiPage {
|
||||
);
|
||||
|
||||
if engine == "zapret2" {
|
||||
let model = self.model.clone();
|
||||
let source = config["zapret"]["zapret2"]["strategySource"].as_str().unwrap_or("nfqws2-keenetic");
|
||||
let sources = RadioGroup::horizontal("strategy-source")
|
||||
.children(SOURCES.map(|(_, label)| label))
|
||||
.selected_index(SOURCES.iter().position(|(v, _)| *v == source))
|
||||
.on_change(move |ix, _, cx| {
|
||||
let (value, label) = SOURCES[*ix];
|
||||
model.update(cx, |m, cx| {
|
||||
m.edit(
|
||||
format!("Strategies: {label}"),
|
||||
move |c| {
|
||||
edits::set_path(c, &["zapret", "zapret2", "strategySource"], value.into());
|
||||
Ok(())
|
||||
},
|
||||
cx,
|
||||
)
|
||||
})
|
||||
});
|
||||
body = body.child(
|
||||
card("zapret2", None, cx)
|
||||
.child(div().text_sm().child("Strategies"))
|
||||
.child(sources)
|
||||
.child(self.option_switch("autohostlist", "Learn which sites are blocked", &["zapret", "zapret2", "autoHostlist", "enable"], &config))
|
||||
.child(self.option_switch(
|
||||
"extended-detection",
|
||||
"Extended detection: also sites blocked only some of the time, and requests that never get an answer",
|
||||
&["zapret", "zapret2", "autoHostlist", "extendedDetection"],
|
||||
&config,
|
||||
))
|
||||
.child(self.option_switch("ipv6", "IPv6 too", &["zapret", "zapret2", "ipv6"], &config))
|
||||
.child(self.option_switch("strategy-log", "Log the strategy each site gets", &["zapret", "zapret2", "strategyLog"], &config)),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The window: a sidebar of pages, the page shown, and what came of each change as a
|
||||
//! notification.
|
||||
|
||||
mod amneziawg;
|
||||
mod autoproxy;
|
||||
mod components;
|
||||
mod dpi;
|
||||
@@ -28,14 +29,25 @@ pub enum Page {
|
||||
Whitelist,
|
||||
Outbounds,
|
||||
AutoProxy,
|
||||
AmneziaWg,
|
||||
Logs,
|
||||
Settings,
|
||||
Components,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
const ALL: [Page; 9] =
|
||||
[Page::Overview, Page::Dpi, Page::Telegram, Page::Whitelist, Page::Outbounds, Page::AutoProxy, Page::Logs, Page::Settings, Page::Components];
|
||||
const ALL: [Page; 10] = [
|
||||
Page::Overview,
|
||||
Page::Dpi,
|
||||
Page::Telegram,
|
||||
Page::Whitelist,
|
||||
Page::Outbounds,
|
||||
Page::AutoProxy,
|
||||
Page::AmneziaWg,
|
||||
Page::Logs,
|
||||
Page::Settings,
|
||||
Page::Components,
|
||||
];
|
||||
|
||||
fn title(self) -> &'static str {
|
||||
match self {
|
||||
@@ -45,6 +57,7 @@ impl Page {
|
||||
Page::Whitelist => "Whitelist bypass",
|
||||
Page::Outbounds => "Outbounds",
|
||||
Page::AutoProxy => "autoProxy",
|
||||
Page::AmneziaWg => "AmneziaWG",
|
||||
Page::Logs => "Logs",
|
||||
Page::Settings => "Settings",
|
||||
Page::Components => "Components",
|
||||
@@ -59,6 +72,7 @@ impl Page {
|
||||
Page::Whitelist => IconName::Video,
|
||||
Page::Outbounds => IconName::Globe,
|
||||
Page::AutoProxy => IconName::Route,
|
||||
Page::AmneziaWg => IconName::Lock,
|
||||
Page::Logs => IconName::SquareTerminal,
|
||||
Page::Settings => IconName::Settings,
|
||||
Page::Components => IconName::Package,
|
||||
@@ -75,6 +89,7 @@ pub struct AppView {
|
||||
/// Made when first shown.
|
||||
whitelist: Option<Entity<whitelist::WhitelistPage>>,
|
||||
autoproxy: Option<Entity<autoproxy::AutoProxyPage>>,
|
||||
amneziawg: Option<Entity<amneziawg::AmneziaWgPage>>,
|
||||
/// Made when first shown: following the logs starts then.
|
||||
logs: Option<Entity<logs::LogsPage>>,
|
||||
/// Made when first shown, as it loads the configuration into its editor then.
|
||||
@@ -98,7 +113,7 @@ impl AppView {
|
||||
let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx));
|
||||
let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx));
|
||||
let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx));
|
||||
Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, autoproxy: None, logs: None, settings: None, components: None, _subscriptions: subscriptions }
|
||||
Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, autoproxy: None, amneziawg: None, logs: None, settings: None, components: None, _subscriptions: subscriptions }
|
||||
}
|
||||
|
||||
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
@@ -131,6 +146,10 @@ impl Render for AppView {
|
||||
self.whitelist.get_or_insert_with(|| cx.new(|cx| whitelist::WhitelistPage::new(model, window, cx))).clone().into_any_element()
|
||||
}
|
||||
Page::Outbounds => self.outbounds.clone().into_any_element(),
|
||||
Page::AmneziaWg => {
|
||||
let model = self.model.clone();
|
||||
self.amneziawg.get_or_insert_with(|| cx.new(|cx| amneziawg::AmneziaWgPage::new(model, window, cx))).clone().into_any_element()
|
||||
}
|
||||
Page::AutoProxy => {
|
||||
let model = self.model.clone();
|
||||
self.autoproxy.get_or_insert_with(|| cx.new(|cx| autoproxy::AutoProxyPage::new(model, window, cx))).clone().into_any_element()
|
||||
|
||||
@@ -96,6 +96,12 @@ pub enum Request {
|
||||
#[serde(default)]
|
||||
domain: Option<String>,
|
||||
},
|
||||
/// AmneziaWG's profiles: system-wide ones with their tunnel's state, outbounds by kind.
|
||||
AwgList,
|
||||
/// Starts or stops a system-wide profile's tunnel.
|
||||
AwgSet { name: String, on: bool },
|
||||
/// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are.
|
||||
AwgLog { name: String, lines: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -137,6 +137,8 @@ fn scope_of(req: &Request) -> Option<Scope> {
|
||||
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
|
||||
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
|
||||
Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
|
||||
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
|
||||
Request::AwgLog { .. } => Some(Scope::Secrets),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -628,6 +630,49 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
||||
Err(e) => Response::err(format!("{e:#}")),
|
||||
},
|
||||
|
||||
Request::AwgList => {
|
||||
let s = shared.lock().await;
|
||||
let cfg = s.cfg();
|
||||
let vpns = crate::awgvpn::profiles(cfg);
|
||||
let list: Vec<Value> = cfg
|
||||
.amnezia_wg
|
||||
.profiles
|
||||
.iter()
|
||||
.map(|(name, p)| match vpns.iter().find(|v| &v.name == name) {
|
||||
Some(v) => json!({ "name": name, "kind": "vpn", "interface": v.iface, "autostart": v.autostart, "state": crate::awgvpn::state(&v.iface) }),
|
||||
None => json!({
|
||||
"name": name,
|
||||
"kind": match p.as_outbound { Some(ps_core::config::AwgOutboundKind::SingBox) => "singBox", Some(_) => "userspace", None => "vpn" },
|
||||
"state": if cfg.amnezia_wg.enable { "outbound" } else { "off" },
|
||||
}),
|
||||
})
|
||||
.collect();
|
||||
Response::ok(json!({ "enabled": cfg.amnezia_wg.enable, "profiles": list }))
|
||||
}
|
||||
|
||||
Request::AwgSet { name, on } => {
|
||||
let s = shared.lock().await;
|
||||
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
|
||||
return Response::err(format!("no system-wide AmneziaWG profile '{name}' (is amneziaWg.enable on, and the profile without asOutbound?)"));
|
||||
};
|
||||
// The SCM's calls wait for the tunnel: not in the async runtime's threads.
|
||||
let iface = vpn.iface.clone();
|
||||
let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await;
|
||||
match r {
|
||||
Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })),
|
||||
Ok(Err(e)) => Response::err(format!("{e:#}")),
|
||||
Err(e) => Response::err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
Request::AwgLog { name, lines } => {
|
||||
let s = shared.lock().await;
|
||||
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
|
||||
return Response::err(format!("no system-wide AmneziaWG profile '{name}'"));
|
||||
};
|
||||
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
|
||||
}
|
||||
|
||||
Request::ComponentsInstall { names } => {
|
||||
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
|
||||
if !peer.admin {
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
//! AmneziaWG as a system-wide VPN: each profile with no `asOutbound` is a tunnel service of
|
||||
//! its own, `AmneziaWGTunnel$<interface name>`, as amneziawg-windows's client installs one:
|
||||
//! amneziawg-go on Wintun, routes and DNS from the configuration, and, for a single peer that
|
||||
//! takes everything (0.0.0.0/0, ::/0), its firewall blocking what would leave outside the
|
||||
//! tunnel. It runs `awg-tunnel.exe` (tools/build-amneziawg.sh) with the profile's `.conf`,
|
||||
//! written below the protected state root, and logs beside it.
|
||||
//!
|
||||
//! The service writes the configuration and registers the tunnel; `proxy-ctl awg on|off` and
|
||||
//! the app start and stop it; `autostart` starts it with the service. Windows only: on Linux
|
||||
//! (development) the profiles are listed and say so.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use ps_core::config::Config;
|
||||
|
||||
use crate::paths::{Paths, write_atomic};
|
||||
|
||||
/// The tunnel services' names: amneziawg-windows's own.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub const SERVICE_PREFIX: &str = "AmneziaWGTunnel$";
|
||||
|
||||
/// Where the service's notes about the tunnels go: `proxy-ctl logs proxy-suite-awg-vpn`.
|
||||
pub const UNIT: &str = "proxy-suite-awg-vpn";
|
||||
|
||||
/// A system-wide profile.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Vpn {
|
||||
pub name: String,
|
||||
/// The adapter's and the service's name.
|
||||
pub iface: String,
|
||||
pub autostart: bool,
|
||||
}
|
||||
|
||||
/// The profiles that are system-wide VPNs, while AmneziaWG is on.
|
||||
pub fn profiles(cfg: &Config) -> Vec<Vpn> {
|
||||
if !cfg.enable || !cfg.amnezia_wg.enable {
|
||||
return Vec::new();
|
||||
}
|
||||
cfg.amnezia_wg
|
||||
.profiles
|
||||
.iter()
|
||||
.filter(|(_, p)| p.as_outbound.is_none())
|
||||
.map(|(name, p)| Vpn { name: name.clone(), iface: p.interface_name.clone().unwrap_or_else(|| name.clone()), autostart: p.autostart })
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub fn service_name(iface: &str) -> String {
|
||||
format!("{SERVICE_PREFIX}{iface}")
|
||||
}
|
||||
|
||||
/// The tunnels' configurations: each `<interface>.conf` there is a tunnel this suite
|
||||
/// registered, which is how it finds its own to remove.
|
||||
fn dir(paths: &Paths) -> PathBuf {
|
||||
paths.root.join("awg-vpn")
|
||||
}
|
||||
|
||||
/// The tunnels registered, by interface name.
|
||||
fn registered(paths: &Paths) -> Vec<String> {
|
||||
std::fs::read_dir(dir(paths))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().to_str()?.strip_suffix(".conf").map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A tunnel unregistered: its service, configuration and log gone.
|
||||
fn forget(paths: &Paths, iface: &str) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
scm::remove(iface, &paths.bin())?;
|
||||
let _ = std::fs::remove_file(conf_path(paths, iface));
|
||||
let _ = std::fs::remove_file(log_path(paths, iface));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn conf_path(paths: &Paths, iface: &str) -> PathBuf {
|
||||
dir(paths).join(format!("{iface}.conf"))
|
||||
}
|
||||
|
||||
/// The tunnel's log: awg-tunnel.exe writes it anew at each start.
|
||||
pub fn log_path(paths: &Paths, iface: &str) -> PathBuf {
|
||||
dir(paths).join(format!("{iface}.conf.log"))
|
||||
}
|
||||
|
||||
/// The profile's `.conf`, as the tunnel reads it: it holds the private key, so only below
|
||||
/// the protected state root.
|
||||
pub fn write_conf(cfg: &Config, paths: &Paths, vpn: &Vpn) -> Result<PathBuf> {
|
||||
let p = &cfg.amnezia_wg.profiles[&vpn.name];
|
||||
let read = |f: &str| std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"));
|
||||
let text = ps_core::awg::prepare(p, &read).map_err(|e| anyhow::anyhow!("AmneziaWG profile '{}': {e}", vpn.name))?;
|
||||
let file = conf_path(paths, &vpn.iface);
|
||||
std::fs::create_dir_all(dir(paths))?;
|
||||
if std::fs::read_to_string(&file).ok().as_deref() != Some(text.as_str()) {
|
||||
write_atomic(&file, text.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// The last lines of a tunnel's log.
|
||||
pub fn log_tail(paths: &Paths, iface: &str, lines: usize) -> Vec<String> {
|
||||
let text = std::fs::read_to_string(log_path(paths, iface)).unwrap_or_default();
|
||||
let all: Vec<&str> = text.lines().collect();
|
||||
all[all.len().saturating_sub(lines)..].iter().map(|l| (*l).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod scm {
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use windows_service::service::{
|
||||
ServiceAccess, ServiceDependency, ServiceErrorControl, ServiceInfo, ServiceSidType, ServiceStartType, ServiceState, ServiceType,
|
||||
};
|
||||
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
|
||||
|
||||
fn manager() -> Result<ServiceManager> {
|
||||
ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE | ServiceManagerAccess::ENUMERATE_SERVICE)
|
||||
.context("opening the Service Control Manager")
|
||||
}
|
||||
|
||||
const ACCESS: ServiceAccess = ServiceAccess::QUERY_STATUS
|
||||
.union(ServiceAccess::QUERY_CONFIG)
|
||||
.union(ServiceAccess::START)
|
||||
.union(ServiceAccess::STOP)
|
||||
.union(ServiceAccess::CHANGE_CONFIG)
|
||||
.union(ServiceAccess::DELETE);
|
||||
|
||||
/// The tunnel's service, created or brought in line with `program` and `conf`.
|
||||
pub fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> {
|
||||
let m = manager()?;
|
||||
let info = ServiceInfo {
|
||||
name: OsString::from(super::service_name(iface)),
|
||||
display_name: OsString::from(format!("AmneziaWG tunnel: {iface} (Proxy Suite)")),
|
||||
service_type: ServiceType::OWN_PROCESS,
|
||||
start_type: ServiceStartType::OnDemand,
|
||||
error_control: ServiceErrorControl::Normal,
|
||||
executable_path: program.to_path_buf(),
|
||||
launch_arguments: vec![conf.as_os_str().to_owned(), OsString::from(iface)],
|
||||
// As amneziawg-windows's client: the network stack first.
|
||||
dependencies: vec![ServiceDependency::Service(OsString::from("Nsi")), ServiceDependency::Service(OsString::from("TcpIp"))],
|
||||
account_name: None,
|
||||
account_password: None,
|
||||
};
|
||||
let service = match m.open_service(super::service_name(iface), ACCESS) {
|
||||
Ok(s) => {
|
||||
let current = s.query_config()?;
|
||||
let wanted_args = format!("\"{}\" \"{}\" \"{iface}\"", program.display(), conf.display());
|
||||
if current.executable_path.to_string_lossy() != wanted_args {
|
||||
s.change_config(&info)?;
|
||||
}
|
||||
s
|
||||
}
|
||||
Err(_) => m.create_service(&info, ACCESS).context("creating the tunnel service")?,
|
||||
};
|
||||
// Its firewall lets the tunnel's own traffic out by the service's SID, which a service
|
||||
// has in its token only with this.
|
||||
service.set_config_service_sid_info(ServiceSidType::Unrestricted)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn start(iface: &str) -> Result<()> {
|
||||
let s = manager()?.open_service(super::service_name(iface), ACCESS).context("the tunnel is not registered")?;
|
||||
if s.query_status()?.current_state == ServiceState::Stopped {
|
||||
s.start::<&str>(&[]).context("starting the tunnel")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop(iface: &str) -> Result<()> {
|
||||
let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) };
|
||||
if s.query_status()?.current_state != ServiceState::Stopped {
|
||||
let _ = s.stop();
|
||||
for _ in 0..40 {
|
||||
if s.query_status()?.current_state == ServiceState::Stopped {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn state(iface: &str) -> String {
|
||||
let Ok(m) = manager() else { return "unknown".into() };
|
||||
let Ok(s) = m.open_service(super::service_name(iface), ServiceAccess::QUERY_STATUS) else { return "inactive".into() };
|
||||
match s.query_status().map(|st| st.current_state) {
|
||||
Ok(ServiceState::Running) => "active",
|
||||
Ok(ServiceState::StartPending) => "activating",
|
||||
Ok(ServiceState::StopPending) => "deactivating",
|
||||
Ok(_) => "inactive",
|
||||
Err(_) => "unknown",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Stopped and deleted, if it runs this suite's program (under `bin`): a tunnel of
|
||||
/// amneziawg-windows's own client by the same name is left alone.
|
||||
pub fn remove(iface: &str, bin: &Path) -> Result<()> {
|
||||
let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) };
|
||||
let bin = bin.to_string_lossy().to_lowercase();
|
||||
if !s.query_config().is_ok_and(|c| c.executable_path.to_string_lossy().to_lowercase().contains(&bin)) {
|
||||
return Ok(());
|
||||
}
|
||||
stop(iface)?;
|
||||
s.delete()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers every system-wide profile's tunnel (its `.conf` written), removes the tunnels
|
||||
/// of profiles gone, and starts the `autostart` ones when `boot`. Errors per profile are
|
||||
/// returned as lines, the rest done.
|
||||
pub fn apply(cfg: &Config, paths: &Paths, program: Option<&Path>, boot: bool) -> Vec<String> {
|
||||
let wanted = profiles(cfg);
|
||||
let mut notes = Vec::new();
|
||||
let keep: Vec<&str> = wanted.iter().map(|v| v.iface.as_str()).collect();
|
||||
for iface in registered(paths) {
|
||||
if !keep.contains(&iface.as_str()) {
|
||||
match forget(paths, &iface) {
|
||||
Ok(()) => notes.push(format!("AmneziaWG tunnel {iface} removed: its profile is gone, or AmneziaWG is off")),
|
||||
Err(e) => notes.push(format!("AmneziaWG tunnel {iface}: {e:#}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
if wanted.is_empty() {
|
||||
return notes;
|
||||
}
|
||||
let Some(program) = program else {
|
||||
notes.push("AmneziaWG's tunnel (component amneziawg) is not installed: the system-wide profiles cannot start".into());
|
||||
return notes;
|
||||
};
|
||||
for vpn in &wanted {
|
||||
let r = write_conf(cfg, paths, vpn).and_then(|conf| register(&vpn.iface, program, &conf));
|
||||
match r {
|
||||
Ok(()) if boot && vpn.autostart => {
|
||||
if let Err(e) = start(&vpn.iface) {
|
||||
notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name));
|
||||
}
|
||||
}
|
||||
Ok(()) => {}
|
||||
Err(e) => notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name)),
|
||||
}
|
||||
}
|
||||
notes
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> {
|
||||
scm::register(iface, program, conf)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn register(_iface: &str, _program: &Path, _conf: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn start(iface: &str) -> Result<()> {
|
||||
scm::start(iface)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn start(_iface: &str) -> Result<()> {
|
||||
anyhow::bail!("AmneziaWG as a system-wide VPN runs on Windows only")
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn stop(iface: &str) -> Result<()> {
|
||||
scm::stop(iface)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn stop(_iface: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn state(iface: &str) -> String {
|
||||
scm::state(iface)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn state(_iface: &str) -> String {
|
||||
"windows-only".into()
|
||||
}
|
||||
|
||||
/// Every tunnel this suite registered, stopped and deleted: on uninstall.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub fn remove_all(paths: &Paths) {
|
||||
for iface in registered(paths) {
|
||||
let _ = forget(paths, &iface);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ps_core::config::{AwgOutboundKind, AwgProfile};
|
||||
|
||||
#[test]
|
||||
fn only_profiles_without_an_outbound_are_vpns() {
|
||||
let mut cfg = Config::default();
|
||||
cfg.amnezia_wg.enable = true;
|
||||
cfg.amnezia_wg.profiles.insert("home".into(), AwgProfile { autostart: true, ..Default::default() });
|
||||
cfg.amnezia_wg.profiles.insert("office".into(), AwgProfile { interface_name: Some("awg-office".into()), ..Default::default() });
|
||||
cfg.amnezia_wg.profiles.insert("exit".into(), AwgProfile { as_outbound: Some(AwgOutboundKind::Userspace), ..Default::default() });
|
||||
let v = profiles(&cfg);
|
||||
assert_eq!(v.iter().map(|v| (v.name.as_str(), v.iface.as_str(), v.autostart)).collect::<Vec<_>>(), [("home", "home", true), ("office", "awg-office", false)]);
|
||||
assert_eq!(service_name("home"), "AmneziaWGTunnel$home");
|
||||
cfg.amnezia_wg.enable = false;
|
||||
assert!(profiles(&cfg).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,12 @@ pub enum Route {
|
||||
}
|
||||
|
||||
fn client(route: &Route) -> Result<reqwest::Client> {
|
||||
client_with(route, Some(Duration::from_secs(60)))
|
||||
}
|
||||
|
||||
/// `total`: the whole transfer's limit; none for an archive, which a stall (a minute without a
|
||||
/// byte) ends instead.
|
||||
fn client_with(route: &Route, total: Option<Duration>) -> Result<reqwest::Client> {
|
||||
let policy = reqwest::redirect::Policy::custom(|attempt| {
|
||||
let from = attempt.previous().last().map(|u| u.as_str().to_owned()).unwrap_or_default();
|
||||
let to = attempt.url().as_str().to_owned();
|
||||
@@ -34,7 +40,10 @@ fn client(route: &Route) -> Result<reqwest::Client> {
|
||||
.user_agent(USER_AGENT)
|
||||
.redirect(policy)
|
||||
.connect_timeout(Duration::from_secs(15))
|
||||
.timeout(Duration::from_secs(60));
|
||||
.read_timeout(Duration::from_secs(60));
|
||||
if let Some(total) = total {
|
||||
b = b.timeout(total);
|
||||
}
|
||||
b = match route {
|
||||
Route::Direct => b.no_proxy(),
|
||||
Route::Proxy { port, login } => {
|
||||
@@ -69,6 +78,54 @@ pub async fn get(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// A large download (a component's archive), at most `limit` bytes: no limit on the whole
|
||||
/// transfer, which a slow line needs, but a minute without a byte fails it, and a transfer cut
|
||||
/// short is taken up where it stopped (an HTTP range), eight times at most.
|
||||
pub async fn get_large(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
|
||||
let scheme = url_parts::split(url).map(|u| u.scheme).unwrap_or_default();
|
||||
if scheme != "http" && scheme != "https" {
|
||||
bail!("the URL must be http:// or https://");
|
||||
}
|
||||
let http = client_with(route, None)?;
|
||||
let mut body: Vec<u8> = Vec::new();
|
||||
let mut last = String::new();
|
||||
for _ in 0..8 {
|
||||
let mut req = http.get(url);
|
||||
if !body.is_empty() {
|
||||
req = req.header(reqwest::header::RANGE, format!("bytes={}-", body.len()));
|
||||
}
|
||||
let mut resp = match req.send().await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
last = describe(&e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match resp.status().as_u16() {
|
||||
206 if !body.is_empty() => {}
|
||||
// The whole of it again: the server takes no range.
|
||||
200 => body.clear(),
|
||||
s => bail!("the server answered {s}"),
|
||||
}
|
||||
loop {
|
||||
match resp.chunk().await {
|
||||
Ok(Some(chunk)) => {
|
||||
body.extend_from_slice(&chunk);
|
||||
if body.len() > limit {
|
||||
bail!("the answer is larger than {limit} bytes");
|
||||
}
|
||||
}
|
||||
Ok(None) => return Ok(body),
|
||||
Err(e) => {
|
||||
last = describe(&e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
bail!("{last} (after eight tries)")
|
||||
}
|
||||
|
||||
/// `body` posted as JSON to `url` with `headers`, and the JSON answer.
|
||||
pub async fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)], route: &Route) -> Result<serde_json::Value> {
|
||||
let mut req = client(route)?.post(url).json(body);
|
||||
|
||||
@@ -27,7 +27,7 @@ pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Res
|
||||
}
|
||||
let mut last = None;
|
||||
for route in routes {
|
||||
match fetch::get(&src.url, route, 512 * 1024 * 1024).await {
|
||||
match fetch::get_large(&src.url, route, 512 * 1024 * 1024).await {
|
||||
Ok(data) => {
|
||||
if let Some(want) = &src.sha256 {
|
||||
let got = hex(&data);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
mod api;
|
||||
mod autoproxy;
|
||||
mod awg;
|
||||
mod awgvpn;
|
||||
mod clash;
|
||||
mod components;
|
||||
mod fetch;
|
||||
@@ -107,6 +108,7 @@ pub async fn run(
|
||||
tokio::spawn(autoproxy::runner(shared.clone()));
|
||||
tokio::spawn(autoproxy::sample(shared.clone()));
|
||||
tokio::spawn(autoproxy::sample_slow(shared.clone()));
|
||||
tokio::spawn(zapret::sync_loop(shared.clone()));
|
||||
// First fetches: what the configuration needs and has not got yet.
|
||||
{
|
||||
let shared = shared.clone();
|
||||
|
||||
@@ -41,6 +41,9 @@ pub struct Service {
|
||||
wl_waiting: BTreeSet<String>,
|
||||
/// autoProxy's requests and the hosts its prober learns from (crate::autoproxy).
|
||||
pub ap: Arc<crate::autoproxy::AutoProxy>,
|
||||
/// Whether the system-wide AmneziaWG tunnels were registered since the service started:
|
||||
/// the first time, the `autostart` ones start too.
|
||||
awg_vpn_started: bool,
|
||||
}
|
||||
|
||||
fn digest(data: &[u8]) -> String {
|
||||
@@ -65,6 +68,7 @@ impl Service {
|
||||
tcp_timestamps_on: false,
|
||||
wl_waiting: BTreeSet::new(),
|
||||
ap: Arc::default(),
|
||||
awg_vpn_started: false,
|
||||
store,
|
||||
})
|
||||
}
|
||||
@@ -140,6 +144,8 @@ impl Service {
|
||||
ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() },
|
||||
windows: cfg!(windows),
|
||||
autoproxy_rules_dir: cfg.proxy.auto_proxy.enable.then(|| crate::autoproxy::rules_dir(paths).to_string_lossy().into_owned()),
|
||||
zapret2_direct_rule_set: crate::zapret::rule_set_paths(cfg, paths).0,
|
||||
zapret2_proxy_rule_set: crate::zapret::rule_set_paths(cfg, paths).1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +187,7 @@ impl Service {
|
||||
if let Err(e) = &awg {
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}"));
|
||||
}
|
||||
self.apply_awg_vpn();
|
||||
let wl = self.apply_wl().await;
|
||||
if let Err(e) = &wl {
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
|
||||
@@ -189,6 +196,24 @@ impl Service {
|
||||
zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy)
|
||||
}
|
||||
|
||||
/// AmneziaWG's system-wide tunnels: registered (their `.conf` written) or removed with
|
||||
/// their profiles, the `autostart` ones started with the service.
|
||||
fn apply_awg_vpn(&mut self) {
|
||||
let cfg = self.cfg().clone();
|
||||
let boot = !self.awg_vpn_started;
|
||||
self.awg_vpn_started = true;
|
||||
if !cfg!(windows) {
|
||||
if !crate::awgvpn::profiles(&cfg).is_empty() {
|
||||
self.sup.note(crate::awgvpn::UNIT, "proxy-suite: AmneziaWG as a system-wide VPN runs on Windows only; not registered");
|
||||
}
|
||||
return;
|
||||
}
|
||||
let program = self.comps.program("amneziawg", "awg-tunnel").ok();
|
||||
for note in crate::awgvpn::apply(&cfg, self.paths(), program.as_deref(), boot) {
|
||||
self.sup.note(crate::awgvpn::UNIT, format!("proxy-suite: {note}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// whitelist-bypass: the joiners while the proxy they serve runs, the creators while it
|
||||
/// is on; the ones no longer wanted stopped, and what the rest wait for said once.
|
||||
pub async fn apply_wl(&mut self) -> Result<()> {
|
||||
@@ -361,10 +386,12 @@ impl Service {
|
||||
for w in &rendered.warnings {
|
||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
|
||||
}
|
||||
// sing-box refuses a local rule-set file that is not there: autoProxy's, written first.
|
||||
// sing-box refuses a local rule-set file that is not there: autoProxy's and zapret2's,
|
||||
// written first.
|
||||
if !rendered.probe_exits.is_empty() {
|
||||
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
|
||||
}
|
||||
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
|
||||
|
||||
let backend = self.cfg().proxy.backend;
|
||||
let main_program = match backend {
|
||||
|
||||
@@ -167,6 +167,7 @@ pub fn uninstall() -> Result<()> {
|
||||
println!("{DISPLAY} was not installed.");
|
||||
}
|
||||
remove_windivert(&manager);
|
||||
crate::awgvpn::remove_all(&crate::paths::Paths::platform_default());
|
||||
let dir = install_dir();
|
||||
desktop::remove();
|
||||
apps::remove();
|
||||
|
||||
@@ -146,19 +146,43 @@ pub async fn enable_tcp_timestamps() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The unit for zapret2: winws2 with nfqws2-keenetic's strategies (ps_core::zapret2), its
|
||||
/// lists in the service's `zapret2\\` directory, the learned one where winws2 can still write
|
||||
/// once it runs at Low integrity.
|
||||
/// The unit for zapret2: winws2 with nfqws2-keenetic's or z2k's strategies
|
||||
/// (ps_core::zapret2), upstream's Lua layers from the zapret2-extras component when it is
|
||||
/// installed, its lists in the service's `zapret2\\` directory, and what winws2 writes (the
|
||||
/// learned list, each site's strategy, the detector's verdicts) where it can still write once
|
||||
/// it runs at Low integrity.
|
||||
pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
|
||||
use ps_core::config::StrategySource;
|
||||
use ps_core::zapret2;
|
||||
let z = &cfg.zapret.zapret2;
|
||||
let component = paths.bin().join("zapret2");
|
||||
let conf = std::fs::read_to_string(component.join("keenetic").join("nfqws2.conf")).context("reading nfqws2-keenetic's nfqws2.conf")?;
|
||||
let source = zapret2::keenetic(&conf, &with_sep(&component.join("keenetic"))).map_err(anyhow::Error::msg)?;
|
||||
let extras_dir = paths.bin().join("zapret2-extras");
|
||||
let extras_there = extras_dir.join("lua").join("detect.lua").is_file();
|
||||
let keenetic_dir = component.join("keenetic");
|
||||
let source = if z.strategy_source == StrategySource::Z2k && extras_there {
|
||||
let z2k = extras_dir.join("z2k");
|
||||
let read = |name: &str| std::fs::read_to_string(z2k.join(name)).with_context(|| format!("reading z2k's {name}"));
|
||||
zapret2::z2k(
|
||||
&read("profiles.plain")?,
|
||||
&read("profiles.learn")?,
|
||||
&read("blobs")?,
|
||||
&read("ports")?,
|
||||
&lua_path(&z2k),
|
||||
&lua_path(&z2k.join("root")),
|
||||
&with_sep_lua(&z2k.join("files").join("lua")),
|
||||
)
|
||||
.map_err(anyhow::Error::msg)?
|
||||
} else {
|
||||
let conf = std::fs::read_to_string(keenetic_dir.join("nfqws2.conf")).context("reading nfqws2-keenetic's nfqws2.conf")?;
|
||||
zapret2::keenetic(&conf, &with_sep(&keenetic_dir)).map_err(anyhow::Error::msg)?
|
||||
};
|
||||
|
||||
let state = paths.root.join("zapret2");
|
||||
let learned = state.join("learned");
|
||||
std::fs::create_dir_all(&learned)?;
|
||||
let circular = learned.join("circular");
|
||||
let fallback = learned.join("run");
|
||||
std::fs::create_dir_all(&circular)?;
|
||||
std::fs::create_dir_all(&fallback)?;
|
||||
#[cfg(windows)]
|
||||
low_integrity(&learned)?;
|
||||
let user = state.join("zapret-hosts-user.txt");
|
||||
@@ -170,23 +194,151 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
|
||||
std::fs::write(f, b"")?;
|
||||
}
|
||||
}
|
||||
let extras = extras_there.then(|| {
|
||||
// Never learned by the detector, as the source's own learning never learned them.
|
||||
let mut exclude_lua = Vec::new();
|
||||
if !source.z2k {
|
||||
exclude_lua.push(lua_path(&keenetic_dir.join("lists").join("exclude.list")));
|
||||
}
|
||||
exclude_lua.push(lua_path(&exclude));
|
||||
zapret2::Extras {
|
||||
lua: with_sep(&extras_dir.join("lua")),
|
||||
z2k_lua: with_sep(&extras_dir.join("z2k").join("files").join("lua")),
|
||||
auto_lua: lua_path(&auto),
|
||||
exclude_lua,
|
||||
}
|
||||
});
|
||||
let p = zapret2::Paths {
|
||||
lua: with_sep(&component.join("lua")),
|
||||
user: user.to_string_lossy().into_owned(),
|
||||
exclude: exclude.to_string_lossy().into_owned(),
|
||||
auto: auto.to_string_lossy().into_owned(),
|
||||
extras,
|
||||
};
|
||||
let argv = zapret2::args(z, &source, &p, cfg.debug.zapret2.packets).map_err(anyhow::Error::msg)?;
|
||||
// Read inside winws2 by z2k's state layer, the detector and the per-site key.
|
||||
let mut env = Vec::new();
|
||||
if extras_there {
|
||||
env.push(("Z2K_STATE_DIR_OVERRIDE".to_owned(), lua_path(&circular)));
|
||||
env.push(("Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE".to_owned(), lua_path(&fallback)));
|
||||
env.push(("PROXY_SUITE_ZAPRET2_VERDICTS".to_owned(), lua_path(&learned.join("verdicts.tsv"))));
|
||||
env.push(("PROXY_SUITE_PUBLIC_SUFFIXES".to_owned(), lua_path(&extras_dir.join("public_suffixes.txt"))));
|
||||
}
|
||||
let generation = {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut h = Sha256::new();
|
||||
for a in &argv {
|
||||
for a in argv.iter().chain(env.iter().map(|(_, v)| v)) {
|
||||
h.update(a.as_bytes());
|
||||
h.update(b"\n");
|
||||
}
|
||||
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||
};
|
||||
Ok(UnitSpec { name: UNIT.into(), program, args: argv, env: Vec::new(), cwd: Some(component), generation })
|
||||
// In a file winws2 reads (`@file`, its only argument): z2k's strategies alone run past
|
||||
// the 32767 characters a Windows command line holds.
|
||||
let file = paths.run().join("winws2.conf");
|
||||
write_atomic(&file, options_file(&argv)?.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
|
||||
Ok(UnitSpec { name: UNIT.into(), program, args: vec![format!("@{}", file.display())], env, cwd: Some(component), generation })
|
||||
}
|
||||
|
||||
/// winws2's options as its `@file` takes them: one a line, quoted when it holds a space. One
|
||||
/// holding a line break would be read as more options than it is: refused.
|
||||
pub fn options_file(argv: &[String]) -> Result<String> {
|
||||
let mut out = String::new();
|
||||
for a in argv {
|
||||
if a.contains(char::is_control) {
|
||||
bail!("a winws2 option holds a control character: {:?}", a.chars().take(80).collect::<String>());
|
||||
}
|
||||
if a.contains(char::is_whitespace) || a.contains('"') {
|
||||
out.push('"');
|
||||
out.push_str(&a.replace('\\', "\\\\").replace('"', "\\\""));
|
||||
out.push('"');
|
||||
} else {
|
||||
out.push_str(a);
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// zapret2's rule-sets for the proxy (ps_core::zapret2::routing), when it runs: what it fixes,
|
||||
/// sent direct (`zapret.directSync`), and what it cannot, for the proxy
|
||||
/// (`zapret2.proxyFallback`).
|
||||
pub fn rule_set_paths(cfg: &Config, paths: &Paths) -> (Option<String>, Option<String>) {
|
||||
let on = cfg.enable && cfg.zapret.enable && cfg.zapret.engine == ZapretEngine::Zapret2;
|
||||
let dir = paths.root.join("zapret2-direct");
|
||||
let file = |name: &str| dir.join(name).to_string_lossy().into_owned();
|
||||
(
|
||||
(on && cfg.zapret.direct_sync.enable).then(|| file("direct.json")),
|
||||
(on && cfg.zapret.zapret2.proxy_fallback).then(|| file("proxy.json")),
|
||||
)
|
||||
}
|
||||
|
||||
/// The rule-sets rebuilt from zapret2's lists and its detector's verdicts, each written only
|
||||
/// when it changed (sing-box reloads a rule-set file replaced). Whether either did.
|
||||
pub fn sync_rule_sets(cfg: &Config, paths: &Paths) -> Result<bool> {
|
||||
let (direct, proxy) = rule_set_paths(cfg, paths);
|
||||
if direct.is_none() && proxy.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
let state = paths.root.join("zapret2");
|
||||
let read = |p: PathBuf| std::fs::read_to_string(p).unwrap_or_default();
|
||||
let auto = cfg.zapret.zapret2.auto_hostlist.enable.then(|| read(state.join("learned").join("zapret-hosts-auto.txt")));
|
||||
let (d, p) = ps_core::zapret2::routing(
|
||||
&read(state.join("zapret-hosts-user.txt")),
|
||||
auto.as_deref(),
|
||||
&read(state.join("zapret-hosts-user-exclude.txt")),
|
||||
&read(state.join("learned").join("verdicts.tsv")),
|
||||
);
|
||||
let mut changed = false;
|
||||
for (path, set) in [(direct, d), (proxy, p)] {
|
||||
let Some(path) = path else { continue };
|
||||
let path = PathBuf::from(path);
|
||||
let body = serde_json::to_vec(&set)?;
|
||||
if std::fs::read(&path).ok().as_deref() != Some(body.as_slice()) {
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
write_atomic(&path, &body)?;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// The rule-sets kept in step with what zapret2 learns, every ten seconds.
|
||||
pub async fn sync_loop(shared: crate::service::Shared) {
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
||||
let s = shared.lock().await;
|
||||
if let Err(e) = sync_rule_sets(s.cfg(), s.paths()) {
|
||||
tracing::warn!("zapret2's rule-sets: {e:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A path as winws2's Lua takes it in a colon-separated argument, or opens it from the
|
||||
/// environment: Cygwin's `/cygdrive/c/…` on Windows (winws2 is a Cygwin program), as it is
|
||||
/// elsewhere.
|
||||
fn lua_path(p: &Path) -> String {
|
||||
let s = p.to_string_lossy().into_owned();
|
||||
if cfg!(windows) { cygwin(&s) } else { s }
|
||||
}
|
||||
|
||||
fn with_sep_lua(p: &Path) -> String {
|
||||
let mut s = lua_path(p);
|
||||
if !s.ends_with('/') && !s.ends_with('\\') {
|
||||
s.push(if cfg!(windows) { '/' } else { std::path::MAIN_SEPARATOR });
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// `C:\\a\\b` as Cygwin names it: `/cygdrive/c/a/b`.
|
||||
fn cygwin(path: &str) -> String {
|
||||
let path = path.trim_start_matches(r"\\?\");
|
||||
match path.as_bytes() {
|
||||
[d, b':', rest @ ..] if d.is_ascii_alphabetic() => {
|
||||
format!("/cygdrive/{}{}", (*d as char).to_ascii_lowercase(), String::from_utf8_lossy(rest).replace('\\', "/"))
|
||||
}
|
||||
_ => path.replace('\\', "/"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Low mandatory label on `dir`, inherited below it: what a Low-integrity process (winws2,
|
||||
@@ -220,3 +372,21 @@ fn low_integrity(dir: &Path) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn options_go_one_a_line_quoted_when_spaced() {
|
||||
let argv: Vec<String> = ["--filter-tcp=443", "--wf-raw-part=inbound and tcp.Payload[0] == 0x16", r#"--x="a""#].map(String::from).into();
|
||||
assert_eq!(options_file(&argv).unwrap(), "--filter-tcp=443\n\"--wf-raw-part=inbound and tcp.Payload[0] == 0x16\"\n\"--x=\\\"a\\\"\"\n");
|
||||
assert!(options_file(&["--filter-tcp=443\n--lua-init=@x.lua".to_owned()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cygwin_names_drives_and_separators() {
|
||||
assert_eq!(cygwin(r"C:\ProgramData\ProxySuite\zapret2\learned"), "/cygdrive/c/ProgramData/ProxySuite/zapret2/learned");
|
||||
assert_eq!(cygwin(r"\\?\D:\x"), "/cygdrive/d/x");
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 130 KiB |
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 76 KiB After Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 79 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 85 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 77 KiB |
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 103 KiB |
@@ -1,44 +1,57 @@
|
||||
The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`; and a setup program.
|
||||
Proxy Suite for Windows, now with a desktop app and a setup program. Since 0.1.0-pre.2 it also gained zapret2 with z2k's strategies and upstream's extended detector, autoProxy, AmneziaWG as a system-wide VPN and as outbounds, WARP, Tor, the SSH tunnel and whitelist-bypass.
|
||||
|
||||
**Not yet run on real Windows.** It was built and tested on Linux, and under Wine where Wine can (it cannot draw the app's text: its DirectWrite does not match fonts). See "What has been verified" in the README, and please report what happens on yours.
|
||||
|
||||
### Downloads
|
||||
- **`ProxySuite-0.2.0-pre.1-windows-x64-setup.exe`**: the setup program (recommended). It installs everything into Program Files, starts the service and the app, and adds Proxy Suite to **Settings → Apps**, where its **Uninstall** is. Silent: `/S`.
|
||||
- **`ProxySuite-0.2.0-pre.1-windows-x64.zip`**: the same files, unpacked anywhere; `install.cmd` installs them (as an administrator), `uninstall.cmd` removes them.
|
||||
|
||||
Each has its SHA-256 in the `.sha256` file next to it. SmartScreen may warn of an unknown publisher, as the programs are not signed yet (**More info** → **Run anyway**). Nothing has to be installed first: the programs carry their C runtime. Needs 64-bit Windows 10 (1903 or later) or 11.
|
||||
|
||||
### zapret2
|
||||
- **z2k's strategies** (`strategySource = "z2k"`), made by z2k's own generator, per category (YouTube, Discord, QUIC, the RKN list), besides nfqws2-keenetic's.
|
||||
- **Upstream's Lua around either source**: each site's working strategy kept across restarts, strategies keyed by site (the public suffix list), and the **extended detector** (`autoHostlist.extendedDetection`), which also learns sites blocked only some of the time and requests that never get an answer.
|
||||
- **By the detector's verdicts the proxy routes too**: what zapret2 cannot fix goes through the proxy (`proxyFallback`), what it fixes goes direct so it sees it (`directSync`).
|
||||
- On Windows the detectors get the server's TLS replies through a WinDivert filter part; a download stalling mid-way (the 16 KB cutoff) is not seen, as WinDivert cannot hand over a flow's first packets alone.
|
||||
|
||||
### autoProxy
|
||||
Sites apps reach directly are probed through each exit, direct first; one blocked directly but reached through an exit is routed through it, as upstream decides (block pages, one exit per network first, strikes against exits that refuse). A site that crawls directly moves to an exit that carries it as well (`slowBelowKiBps`). Blocks zapret can fix stay direct. On its page in the app, or `proxy-ctl proxy auto` (list, probe, learn, forget, clear).
|
||||
|
||||
### AmneziaWG
|
||||
- **As a system-wide VPN**: a profile without `asOutbound` is a tunnel of its own (amneziawg-windows's, built from its source, on Wintun), with its routes, DNS and, for one peer that takes everything, a kill switch; on and off on the app's AmneziaWG page or with `proxy-ctl awg on|off`, at boot with `autostart`.
|
||||
- **As outbounds**: `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either.
|
||||
- Profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings, added in the app.
|
||||
|
||||
### The app
|
||||
- **Overview:** the local proxy, the DPI bypass and the Telegram proxy, their states and switches; what the service warns of.
|
||||
- **DPI bypass:** zapret with Flowseal's presets (the preset, game traffic) or zapret2 (learning, IPv6); your own sites to handle or leave alone.
|
||||
- **DPI bypass:** zapret with Flowseal's presets (the preset, game traffic) or zapret2 (its strategies, learning, the extended detection, IPv6, the strategy log); your own sites to handle or leave alone.
|
||||
- **Telegram proxy:** on or off, its tg:// links to open in Telegram or copy to a phone, other devices allowed or not, port and fake-TLS domain.
|
||||
- **autoProxy:** on or off; probe a site through each exit, or learn it now; the sites it routed (forget each, or all); the exits, bad ones marked; what it never touches and how slow is slow.
|
||||
- **Whitelist bypass:** joiners and creators, added or removed; a joiner's call link given, a creator's call link copied, its login given (a cookies file, or DION's and Bitrix's email and password).
|
||||
- **Outbounds:** add one from a link; pin, test delays, leave out, remove; the routing mode; subscriptions.
|
||||
- **autoProxy:** on or off; probe a site through each exit, or learn it now; the sites it routed (forget each, or all); the exits, bad ones marked; what it never touches and how slow is slow.
|
||||
- **AmneziaWG:** profiles, a system-wide one switched on and off with its tunnel's log, one added from a `vpn://` link or a `.conf`, or removed.
|
||||
- **Logs:** every service's, live.
|
||||
- **Settings:** every option, as JSON, checked by the service before it is saved.
|
||||
- **Components:** what is installed, at which version.
|
||||
- **Icon:** the app has one now (window, taskbar, Start Menu, Settings → Apps).
|
||||
- **Tray:** a shield, green while things work, amber when one failed, grey when all is off; its menu switches the proxy, the DPI bypass and the Telegram proxy.
|
||||
- **System proxy:** the app can point Windows' proxy setting (browsers, most programs) at the local proxy while it runs, and puts yours back after.
|
||||
- It has an icon (window, taskbar, Start Menu, Settings → Apps), starts at every sign-in in the tray, and is in the Start Menu.
|
||||
|
||||
`install.cmd` puts it in the Start Menu and starts it at every sign-in, in the tray.
|
||||
Screenshots are in the README.
|
||||
|
||||
### Also
|
||||
- zapret's `hostlistRules`: a group of sites with its own strategy, copied from a preset (or another one, `configName`) or given as `nfqwsArgs`, ahead of the preset's own; every preset with them checked by Flowseal's `winws.exe`.
|
||||
- The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809).
|
||||
- The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809; the setup program offers it).
|
||||
- Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy.
|
||||
- AmneziaWG as outbounds (`amneziaWg`): profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings; `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either.
|
||||
- autoProxy (`proxy.autoProxy`): sites apps reach directly are probed through each exit; one blocked directly but reached through an exit is routed through it, as upstream decides. A site that crawls directly moves to an exit that carries it as well (`slowBelowKiBps`). In the app, or `proxy-ctl proxy auto` (list, probe, learn, forget, clear).
|
||||
- whitelist-bypass (`whitelistBypass`): its creators and joiners, built from upstream's source; a joiner is an outbound of the proxy through a video call (WB Stream, Telemost, DION, Bitrix), a creator the call's other end. `proxy-ctl wl join|auth|link|new`.
|
||||
- WARP (`warp`, as a sing-box outbound): devices registered with Cloudflare as wgcf registers them (through the local proxy first, where its API is blocked), or profiles given; several grouped as `warp`.
|
||||
- What is not on Windows yet (the kill switch, AmneziaWG, WARP, Tor, the SSH tunnel, …) is no longer accepted silently: the service warns while it is configured, and the app shows it.
|
||||
- whitelist-bypass (`whitelistBypass`): its creators and joiners, built from upstream's source; a joiner is an outbound of the proxy through a video call (WB Stream, Telemost, DION, Bitrix), a creator the call's other end. `proxy-ctl wl join|auth|link|new`.
|
||||
- What is not on Windows yet is no longer accepted silently: the service warns while it is configured, and the app shows it.
|
||||
- The service names zapret's presets and gives tg-ws-proxy's links (`proxy-ctl zapret presets`, `proxy-ctl tg link`).
|
||||
- A setup program (`…-setup.exe`, English and Russian), with an uninstaller in Settings → Apps; `install.cmd` from the zip makes that entry too. Uninstalling removes WinDivert's driver service too, when it is the suite's.
|
||||
- The programs carry their C runtime: no Visual C++ Redistributable needed.
|
||||
- Uninstalling removes WinDivert's driver service and the AmneziaWG tunnels too, when they are the suite's.
|
||||
- Built and published by Gitea Actions.
|
||||
|
||||
### Install
|
||||
Download `ProxySuite-0.2.0-pre.1-windows-x64-setup.exe` and run it (its SHA-256 is in the `.sha256` file next to it); SmartScreen may warn of an unknown publisher, the programs are not signed yet (**More info** → **Run anyway**). It installs everything, starts the service and the app, and adds Proxy Suite to **Settings → Apps**, where its **Uninstall** is. Nothing has to be installed first: the programs carry their C runtime now. Needs 64-bit Windows 10 (1903 or later) or 11.
|
||||
|
||||
The zip is still there, the same files with `install.cmd`.
|
||||
|
||||
### Not yet
|
||||
AmneziaWG as a system-wide VPN, Tor's onion service, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies.
|
||||
Tor's onion service, the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe.
|
||||
|
||||
### Note
|
||||
Unlike upstream, the signed-in user may change every setting by default (`userControl`), except the ones that could run programs or read files as SYSTEM: those always need an administrator. On a shared computer, restrict `userControl.scopes`.
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
# AmneziaWG as a system-wide VPN: amneziawg-windows's tunnel (amneziawg-go on Wintun, its
|
||||
# firewall that blocks what leaves outside a full tunnel, its DNS and routes), built from its
|
||||
# pinned commit as awg-tunnel.exe rather than its tunnel.dll: the same Run() a tunnel service
|
||||
# makes, with a main that takes the config's path and the tunnel's name, and its log in a
|
||||
# file beside the config (not its ring log). Wintun's signed driver DLL from wintun.net,
|
||||
# pinned as amneziawg-windows's own build pins it.
|
||||
#
|
||||
# tools/build-amneziawg.sh OUT_DIR (needs git, go, curl, unzip)
|
||||
set -euo pipefail
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
OUT=$(realpath -m "${1:?output directory}")
|
||||
COMMIT=e90531d15802cb976773f3b63443bc281f738ca3
|
||||
VERSION=0-unstable-2026-08-14+e90531d
|
||||
WINTUN_URL=https://www.wintun.net/builds/wintun-0.14.1.zip
|
||||
WINTUN_SHA256=07c256185d6ee3652e09fa55c0b673e2624b565e02c4b9091c79ca7d2f24ef51
|
||||
WORK=$(mktemp -d)
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
clone_commit https://github.com/amnezia-vpn/amneziawg-windows "$COMMIT" "$WORK/src"
|
||||
cd "$WORK/src"
|
||||
# Its exports (tunnel.dll's, through cgo) out; a main of ours in.
|
||||
rm main.go
|
||||
grep -q 'err = ringlogger.InitGlobalLogger("TUN")' service.go || { echo "service.go changed: no ring logger to replace"; exit 1; }
|
||||
sed -i 's|err = ringlogger.InitGlobalLogger("TUN")|err = nil|' service.go
|
||||
sed -i '/"github.com\/amnezia-vpn\/amneziawg-windows\/v3\/ringlogger"/d' service.go
|
||||
cat > proxysuite_main.go <<'GO'
|
||||
/* SPDX-License-Identifier: MIT
|
||||
*
|
||||
* Proxy Suite's AmneziaWG tunnel service: run by the Service Control Manager as
|
||||
* `awg-tunnel <config path> <tunnel name>`, as amneziawg-windows's tunnel.dll is from its
|
||||
* client's service. Its log goes to <config path>.log, written anew at each start.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 3 {
|
||||
fmt.Fprintln(os.Stderr, "usage: awg-tunnel <config> <tunnel name> (as a Windows service)")
|
||||
os.Exit(2)
|
||||
}
|
||||
confPath, name := os.Args[1], os.Args[2]
|
||||
if f, err := os.OpenFile(confPath+".log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600); err == nil {
|
||||
log.SetOutput(f)
|
||||
}
|
||||
text, err := os.ReadFile(confPath)
|
||||
if err != nil {
|
||||
log.Printf("reading %s: %v", confPath, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := Run(string(text), name); err != nil {
|
||||
log.Printf("the tunnel service: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
GO
|
||||
export GOTOOLCHAIN=local GOFLAGS=-mod=mod CGO_ENABLED=0 GOOS=windows GOARCH=amd64
|
||||
go build -trimpath -ldflags "-s -w" -o "$WORK/awg-tunnel.exe" .
|
||||
|
||||
rm -rf "$OUT" && mkdir -p "$OUT"
|
||||
cp "$WORK/awg-tunnel.exe" "$OUT/"
|
||||
# Its license is the MIT text in its README.
|
||||
sed -n '/^```text/,/^```/p' README.md | sed '1d;$d' >"$OUT/LICENSE"
|
||||
grep -q 'Permission is hereby granted' "$OUT/LICENSE" || { echo "README.md: no license text"; exit 1; }
|
||||
fetch_pinned "$WINTUN_URL" "$WINTUN_SHA256" "$WORK/wintun.zip"
|
||||
unzip -q -o "$WORK/wintun.zip" -d "$WORK/wintun"
|
||||
cp "$WORK/wintun/wintun/bin/amd64/wintun.dll" "$OUT/"
|
||||
cp "$WORK/wintun/wintun/LICENSE.txt" "$OUT/wintun-LICENSE.txt"
|
||||
echo "$VERSION" >"$OUT/.version"
|
||||
echo "amneziawg $VERSION (windows) in $OUT"
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env bash
|
||||
# zapret2's layers beyond the strategies, as upstream's runtime.nix loads them into nfqws2
|
||||
# (winws2 here: the same engine, the same Lua): z2k's Lua (a site's working strategy kept
|
||||
# across restarts, and its own detectors) and its lists and fake payloads; proxy-suite's own
|
||||
# Lua (the extended detector, the per-site key by public suffix, the fail stamp, the
|
||||
# strategy log); and z2k's strategies, made by z2k's own generator, as upstream's
|
||||
# z2k-profiles.template.sh runs it at build time.
|
||||
#
|
||||
# What upstream fills in from the configuration at build time is left as a token here and
|
||||
# filled in by the service (ps_core::zapret2): @HSUF@ and @ESUF@ (the user's sites and
|
||||
# exclusions), @AUTO@ @EXCLUDE@ @FAILS@ @TIME@ @INSEQ@ @RETRANS@ @LEARNEXTRA@ (the
|
||||
# learner's arguments), @STALLWATCH@; and the paths, @Z2K@ (z2k's files) and @ROOT@ (the
|
||||
# tree its generator wrote), which winws2 reads where the component is installed.
|
||||
#
|
||||
# tools/build-zapret2-extras.sh OUT_DIR (needs git, bash, gawk, python3, nix)
|
||||
set -euo pipefail
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
OUT=$(realpath -m "${1:?output directory}")
|
||||
HERE=$(realpath "$(dirname "$0")")
|
||||
UPSTREAM=$(realpath "$HERE/../../modules/proxy-suite/zapret2")
|
||||
Z2K_COMMIT=7beb9754d65a2cafd9c1d26d382bcb61d453d5b3
|
||||
WORK=$(mktemp -d)
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
clone_commit https://github.com/necronicle/z2k "$Z2K_COMMIT" "$WORK/z2k"
|
||||
Z=$WORK/z2k
|
||||
rm -rf "$OUT" && mkdir -p "$OUT/z2k/files" "$OUT/lua"
|
||||
|
||||
# --- z2k's files the strategies and Lua read --------------------------------------------
|
||||
cp -r "$Z/files/lua" "$Z/files/lists" "$OUT/z2k/files/"
|
||||
[ -d "$Z/files/fake" ] && cp -r "$Z/files/fake" "$OUT/z2k/files/"
|
||||
cp "$Z/LICENSE" "$OUT/z2k/LICENSE"
|
||||
# Its QUIC silence detector, as upstream's sources.nix patches it: rkn_quic's flows too, and
|
||||
# a flow answered past udp_in replies only.
|
||||
q=$OUT/z2k/files/lua/z2k-quic-silence.lua
|
||||
grep -qF 'local Z2K_QUIC_POOLS = { yt_quic = true, gv_quic = true }' "$q" || { echo "z2k-quic-silence.lua changed"; exit 1; }
|
||||
sed -i 's/local Z2K_QUIC_POOLS = { yt_quic = true, gv_quic = true }/local Z2K_QUIC_POOLS = { yt_quic = true, gv_quic = true, rkn_quic = true }/' "$q"
|
||||
python3 -I - "$q" <<'PY'
|
||||
import sys
|
||||
p = sys.argv[1]
|
||||
s = open(p).read()
|
||||
old = " if not desync.outgoing then\n crec.z2k_quic_answered = true\n"
|
||||
new = " if not desync.outgoing then\n if (pos_get(desync, 'n') or 0) > (tonumber(desync.arg.udp_in) or 1) then crec.z2k_quic_answered = true end\n"
|
||||
if old not in s:
|
||||
sys.exit("z2k-quic-silence.lua: the answer check changed")
|
||||
open(p, "w").write(s.replace(old, new))
|
||||
PY
|
||||
|
||||
# --- proxy-suite's own Lua --------------------------------------------------------------
|
||||
cp "$UPSTREAM/detect.lua" "$UPSTREAM/persist-every.lua" "$UPSTREAM/strategy-log.lua" "$OUT/lua/"
|
||||
# The suffix list's path from the environment: it is where the component is installed.
|
||||
grep -q '"@suffixes@"' "$UPSTREAM/public-suffix-hostkey.lua" || { echo "public-suffix-hostkey.lua changed"; exit 1; }
|
||||
sed 's|"@suffixes@"|os.getenv("PROXY_SUITE_PUBLIC_SUFFIXES")|' "$UPSTREAM/public-suffix-hostkey.lua" >"$OUT/lua/public-suffix-hostkey.lua"
|
||||
cat >"$OUT/lua/fail-stamp.lua" <<'LUA'
|
||||
-- The state layer undoes a rotation when the host succeeded within 30 s, unless a failure
|
||||
-- came later; only z2k's own detector stamps that failure. Without the stamp any success on
|
||||
-- a busy host (all of googlevideo.com) undoes every rotation. (upstream's runtime.nix)
|
||||
local count = automate_failure_counter
|
||||
function automate_failure_counter(hrec, crec, fails, maxtime)
|
||||
if not (crec and crec.failure) then
|
||||
hrec.z2k_last_fail_ts = type(clock_getfloattime) == "function" and clock_getfloattime() or os.time()
|
||||
end
|
||||
return count(hrec, crec, fails, maxtime)
|
||||
end
|
||||
LUA
|
||||
psl=$(nix build --no-link --print-out-paths --inputs-from "$HERE/.." nixpkgs#publicsuffix-list | head -1)
|
||||
python3 -I "$UPSTREAM/public-suffixes.py" "$psl/share/publicsuffix/public_suffix_list.dat" >"$OUT/public_suffixes.txt"
|
||||
|
||||
# --- z2k's strategies, by its generator ---------------------------------------------------
|
||||
root=$WORK/root
|
||||
mkdir -p "$root/lists" "$root/lua" "$WORK/conf"
|
||||
cp -r "$Z/files/lists/extra_strats" "$root/"
|
||||
chmod -R u+w "$root"
|
||||
cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt"
|
||||
cp "$Z/files/lists/cf_extra_check_ips.txt" "$root/lists/"
|
||||
: >"$root/lists/discovered-domains.txt"
|
||||
mkdir -p "$root/state"
|
||||
echo 1 >"$root/state/tcp16.flag"
|
||||
ln -s "$Z"/files/lua/*.lua "$root/lua/"
|
||||
(
|
||||
export ZAPRET2_DIR="$root" CONFIG_DIR="$WORK/conf" LISTS_DIR="$root/lists"
|
||||
cd "$Z"
|
||||
bash -c '
|
||||
. lib/utils.sh && . lib/config.sh && . lib/strategies.sh && . lib/config_official.sh || exit 1
|
||||
print_info() { echo "$*" >&2; }
|
||||
print_success() { echo "$*" >&2; }
|
||||
print_warning() { echo "$*" >&2; }
|
||||
print_error() { echo "$*" >&2; }
|
||||
create_base_config >&2 &&
|
||||
generate_strategies_conf strats_new2.txt "$STRATEGIES_CONF" >&2 &&
|
||||
generate_quic_strategies_conf quic_strats.ini "$QUIC_STRATEGIES_CONF" >&2 &&
|
||||
create_default_strategy_files >&2 &&
|
||||
generate_nfqws2_opt_from_strategies
|
||||
'
|
||||
) >"$WORK/generated" 2>"$WORK/generator.log" || { tail -20 "$WORK/generator.log"; exit 1; }
|
||||
sed -n '/^NFQWS2_OPT="/,/^"$/p' "$WORK/generated" | sed '1s/^NFQWS2_OPT="//; $d' | tr '\n' ' ' >"$WORK/raw"
|
||||
grep -q -- '--lua-desync=circular' "$WORK/raw" || { echo "z2k generator produced no profiles"; exit 1; }
|
||||
|
||||
# As upstream's z2k-profiles.template.sh: its learned-host list becomes ours, its whitelist
|
||||
# takes our exclusions, circular's pinned detector args go (autoHostlist fills them), and
|
||||
# learning is a last profile of its own; with the extended detector, ps_learn's.
|
||||
profiles() {
|
||||
local learn=$1 watch=$2
|
||||
awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
|
||||
-v wl="--hostlist-exclude=$root/lists/whitelist.txt" \
|
||||
-v yt="--hostlist-exclude=$root/extra_strats/TCP/YT/List.txt --hostlist-exclude=$root/extra_strats/TCP/YT_GV/List.txt" \
|
||||
-v hsuf=" @HSUF@" -v esuf=" @ESUF@" \
|
||||
-v learn="$learn" -v wlfile="$root/lists/whitelist.txt" -v watch="$watch" '
|
||||
{
|
||||
for (i = 1; i <= NF; i++) {
|
||||
t = $i
|
||||
if (t == "--new") {
|
||||
prof++
|
||||
} else if (t ~ /^--filter-tcp=/ && !(prof in ports)) {
|
||||
ports[prof] = substr(t, 14)
|
||||
}
|
||||
pre = ""
|
||||
if (t ~ /^--(in-range|out-range|payload|lua-desync)=/) {
|
||||
if (watch != "" && seen && prof == learner && !watched++) pre = watch " "
|
||||
filtered[prof] = 1
|
||||
}
|
||||
if (t == disc) {
|
||||
t = "<HOSTLIST_NOAUTO>" hsuf
|
||||
if (!seen++) {
|
||||
t = t " " yt
|
||||
learner = prof
|
||||
if (prof in filtered) { print "z2k general TLS profile: hostlist after its instances" > "/dev/stderr"; exit 1 }
|
||||
}
|
||||
} else if (t == wl) {
|
||||
t = t esuf
|
||||
} else if (t ~ /^--lua-desync=circular:/) {
|
||||
n = split(substr(t, 23), p, ":")
|
||||
t = "--lua-desync=circular"
|
||||
for (j = 1; j <= n; j++)
|
||||
if (p[j] !~ /^(retrans|maxseq|inseq)=/ && p[j] != "reset") t = t ":" p[j]
|
||||
}
|
||||
printf "%s%s%s", (i > 1 ? " " : ""), pre, t
|
||||
}
|
||||
}
|
||||
END {
|
||||
if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 }
|
||||
if (watch != "" && !watched) { print "z2k general TLS profile has no instances" > "/dev/stderr"; exit 1 }
|
||||
if (learn == "")
|
||||
printf " --new --filter-tcp=%s --filter-l7=tls %s%s <HOSTLIST>%s", ports[learner], wl, esuf, hsuf
|
||||
else {
|
||||
sub(/:exclude=/, ":exclude=" wlfile ",", learn)
|
||||
printf " --new --filter-tcp=%s --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:%s", ports[learner], learn
|
||||
}
|
||||
}' "$WORK/raw" >"$WORK/body"
|
||||
# rkn_quic: z2k's YouTube QUIC profile over the sites rkn_tcp handles, right after it.
|
||||
awk -v yt="--hostlist=$root/extra_strats/UDP/YT/List.txt" \
|
||||
-v rkn="--hostlist=$root/extra_strats/TCP/RKN/List.txt --hostlist=$root/extra_strats/TCP_Discord.txt <HOSTLIST_NOAUTO> @HSUF@" '
|
||||
{
|
||||
n = split($0, p, / --new /)
|
||||
for (i = 1; i <= n; i++) {
|
||||
printf "%s%s", (i > 1 ? " --new " : ""), p[i]
|
||||
if (p[i] ~ /key=yt_quic:/ && (k = index(p[i], yt))) {
|
||||
q = substr(p[i], 1, k - 1) rkn substr(p[i], k + length(yt))
|
||||
gsub(/key=yt_quic:/, "key=rkn_quic:", q)
|
||||
if (!sub(/:udp_in=1:/, ":udp_in=4:", q)) { print "z2k YouTube QUIC udp_in=1 not found" > "/dev/stderr"; exit 1 }
|
||||
printf " --new %s", q
|
||||
found++
|
||||
}
|
||||
}
|
||||
}
|
||||
END { if (found != 1) { print "z2k YouTube QUIC profile not found" > "/dev/stderr"; exit 1 } }' "$WORK/body"
|
||||
}
|
||||
profiles "" "" >"$WORK/profiles.plain"
|
||||
profiles "auto=@AUTO@:exclude=@EXCLUDE@:fails=@FAILS@:time=@TIME@:inseq=@INSEQ@:retrans=@RETRANS@:win=32@LEARNEXTRA@" "@STALLWATCH@" >"$WORK/profiles.learn"
|
||||
awk -v z="$Z" '
|
||||
match($0, /^([A-Z0-9_]+_BLOB)="\$ZAPRET_BASE\/([^"]+)"/, m) { file[m[1]] = m[2] }
|
||||
match($0, /--blob=([a-z0-9_]+):@\$([A-Z0-9_]+_BLOB)/, m) { printf "--blob=%s:@%s/%s ", m[1], z, file[m[2]] }
|
||||
' "$Z/files/S99zapret2.new" >"$WORK/blobs"
|
||||
grep -q -- '--blob=' "$WORK/blobs" || { echo "z2k blob registrations not found"; exit 1; }
|
||||
|
||||
# The paths as tokens; the tree the generator wrote, shipped.
|
||||
for f in profiles.plain profiles.learn blobs; do
|
||||
sed -e "s|$root|@ROOT@|g" -e "s|$Z|@Z2K@|g" "$WORK/$f" >"$OUT/z2k/$f"
|
||||
if grep -q "$WORK" "$OUT/z2k/$f"; then echo "$f still names the build's directory"; exit 1; fi
|
||||
done
|
||||
# The blobs it names, from z2k's tree, wherever they are in it.
|
||||
for b in $(grep -o '@Z2K@/[^ ]*' "$OUT/z2k/blobs" | sed 's|@Z2K@/||'); do
|
||||
mkdir -p "$OUT/z2k/$(dirname "$b")" && cp "$Z/$b" "$OUT/z2k/$b"
|
||||
done
|
||||
cp -rL "$root" "$OUT/z2k/root"
|
||||
rm -rf "$OUT/z2k/root/lua"
|
||||
# Its ports, from its generator's configuration.
|
||||
gen=$(cat "$Z/lib/config_official.sh")
|
||||
for name in NFQWS2_PORTS_TCP NFQWS2_PORTS_UDP; do
|
||||
printf '%s=%s\n' "$name" "$(sed -n "s/^$name=\"\\(.*\\)\"/\\1/p" "$Z/lib/config_official.sh" | head -1)"
|
||||
done >"$OUT/z2k/ports"
|
||||
grep -q '^NFQWS2_PORTS_TCP=.\+' "$OUT/z2k/ports" || { echo "z2k's ports not found"; exit 1; }
|
||||
echo "$Z2K_COMMIT" >"$OUT/z2k/.commit"
|
||||
echo "2026.10.27+z2k.${Z2K_COMMIT:0:7}" >"$OUT/.version"
|
||||
echo "zapret2-extras $(cat "$OUT/.version") in $OUT"
|
||||
@@ -28,3 +28,63 @@ clone_tag() {
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# clone_commit URL COMMIT DIR: COMMIT alone, for a project without release tags; cached and
|
||||
# tried again as clone_tag is.
|
||||
clone_commit() {
|
||||
local url=$1 commit=$2 dir=$3 try cached=""
|
||||
if [ -n "${SRC_CACHE:-}" ]; then
|
||||
cached="$SRC_CACHE/$(basename "$url")@$commit"
|
||||
if [ -d "$cached/.git" ]; then
|
||||
rm -rf "$dir" && cp -a "$cached" "$dir" && git -C "$dir" reset -q --hard && git -C "$dir" clean -qfdx && return 0
|
||||
fi
|
||||
fi
|
||||
for try in 1 2 3; do
|
||||
rm -rf "$dir" && mkdir -p "$dir"
|
||||
if git -C "$dir" init -q && git -C "$dir" remote add origin "$url" &&
|
||||
git -C "$dir" -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=60 fetch -q --depth 1 origin "$commit" &&
|
||||
git -C "$dir" -c advice.detachedHead=false checkout -q FETCH_HEAD; then
|
||||
if [ -n "$cached" ]; then
|
||||
mkdir -p "$SRC_CACHE" && rm -rf "$cached.tmp" && cp -a "$dir" "$cached.tmp" && mv "$cached.tmp" "$cached"
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
echo "fetching $url ($commit) failed, try $try of 3" >&2
|
||||
sleep 5
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# fetch_pinned URL SHA256 FILE: a download, checked by its hash; kept in SRC_CACHE.
|
||||
fetch_pinned() {
|
||||
local url=$1 sha=$2 out=$3 cached=""
|
||||
if [ -n "${SRC_CACHE:-}" ]; then
|
||||
cached="$SRC_CACHE/$sha"
|
||||
if [ -f "$cached" ] && echo "$sha $cached" | sha256sum -c --quiet 2>/dev/null; then
|
||||
cp "$cached" "$out" && return 0
|
||||
fi
|
||||
fi
|
||||
# Whole, unless it stalls: some networks cut TLS to some hosts after about 16 KB (as
|
||||
# zapret2's cutoff option knows). Then in ranges below that, each on a connection of its own.
|
||||
if ! curl -fsSL --connect-timeout 30 --speed-limit 1 --speed-time 15 --max-time 900 --retry 2 -o "$out" "$url"; then
|
||||
echo "$url stalled; fetching it in pieces" >&2
|
||||
local size from=0 step=12000 tries=0
|
||||
size=$(curl -fsSIL --connect-timeout 30 --max-time 60 "$url" | tr -d '\r' | awk 'tolower($1) == "content-length:" { n = $2 } END { print n }')
|
||||
[[ "$size" =~ ^[0-9]+$ ]] && [ "$size" -gt 0 ] || { echo "$url: no size to fetch it in pieces by" >&2; return 1; }
|
||||
: >"$out"
|
||||
while [ "$from" -lt "$size" ]; do
|
||||
if curl -fsSL --connect-timeout 30 --max-time 60 -r "$from-$((from + step - 1))" "$url" >>"$out.piece" 2>/dev/null &&
|
||||
[ "$(stat -c %s "$out.piece")" -gt 0 ]; then
|
||||
cat "$out.piece" >>"$out"
|
||||
from=$(stat -c %s "$out")
|
||||
tries=0
|
||||
else
|
||||
tries=$((tries + 1))
|
||||
[ "$tries" -lt 5 ] || { rm -f "$out.piece"; echo "$url: a piece failed five times" >&2; return 1; }
|
||||
fi
|
||||
rm -f "$out.piece"
|
||||
done
|
||||
fi
|
||||
echo "$sha $out" | sha256sum -c --quiet || { echo "$url: not the pinned file" >&2; return 1; }
|
||||
if [ -n "$cached" ]; then mkdir -p "$SRC_CACHE" && cp "$out" "$cached"; fi
|
||||
}
|
||||
@@ -21,6 +21,8 @@ echo "== components"
|
||||
tools/build-tg-ws-proxy.sh "$DIST/components/tg-ws-proxy"
|
||||
tools/build-wireproxy-awg.sh "$DIST/components/wireproxy-awg" windows
|
||||
tools/build-whitelist-bypass.sh "$DIST/components/whitelist-bypass" windows
|
||||
tools/build-amneziawg.sh "$DIST/components/amneziawg"
|
||||
tools/build-zapret2-extras.sh "$DIST/components/zapret2-extras"
|
||||
cargo build -q --release -p ps-service
|
||||
target/release/proxy-suite-service stage-components --to "$DIST/components" --cache "$CACHE"
|
||||
rm -rf "$DIST"/components/*.old "$DIST"/components/*.staging
|
||||
@@ -57,7 +59,11 @@ echo "== THIRD-PARTY.md"
|
||||
echo "- **cygwin1.dll** (zapret, zapret2): LGPL-3.0, https://cygwin.com"
|
||||
echo "- **zapret2** (winws2.exe, its Lua) and **nfqws2-keenetic** (its strategies, lists, blobs): MIT, https://github.com/bol-van/zapret2, https://github.com/nfqws/nfqws2-keenetic"
|
||||
echo "- **wintun** (inside sing-box): WireGuard's prebuilt-binary license, https://www.wintun.net"
|
||||
echo "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch): MIT, https://github.com/amnezia-vpn/amneziawg-go"
|
||||
echo "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch, and inside amneziawg's awg-tunnel.exe): MIT, https://github.com/amnezia-vpn/amneziawg-go"
|
||||
echo "- **z2k** (zapret2-extras: its strategies, made by its own generator, its Lua and lists): MIT, https://github.com/necronicle/z2k"
|
||||
echo "- **The public suffix list** (zapret2-extras' public_suffixes.txt, derived): MPL-2.0, https://publicsuffix.org"
|
||||
echo "- **proxy-suite's zapret2 Lua** (zapret2-extras' lua/: the extended detector and the layers around z2k's state): MIT, this repository's modules/proxy-suite/zapret2"
|
||||
echo "- **Wintun** (amneziawg's wintun.dll, as WireGuard LLC builds and signs it): its prebuilt-binaries license, components/amneziawg/wintun-LICENSE.txt"
|
||||
echo "- **Go modules** (inside wireproxy-awg and whitelist-bypass, e.g. Pion's WebRTC): as each project's go.mod pins them, under their own licenses (MIT, BSD-3-Clause, Apache-2.0)"
|
||||
echo "- **lyrebird** and **conjure** (Tor's pluggable transports, in the Expert Bundle): their licenses are in components/tor/docs"
|
||||
echo "- **CPython $( sed 's/.*+py//' "$DIST/components/tg-ws-proxy/.version" )** (tg-ws-proxy): PSF License, https://www.python.org"
|
||||
|
||||
@@ -36,9 +36,13 @@ cat >"$STATE/config.json" <<JSON
|
||||
"outbounds": [{ "tag": "Netherlands", "url": "$SS_URL#Netherlands" },
|
||||
{ "tag": "Germany", "url": "$SS_URL#Germany" },
|
||||
{ "tag": "Finland", "url": "$SS_URL#Finland" }] },
|
||||
"zapret": { "enable": true, "engine": "zapret-discord-youtube",
|
||||
"zapret": { "enable": true, "engine": "zapret2",
|
||||
"zapret2": { "strategySource": "z2k", "strategyLog": true, "cutoff": { "enable": false } },
|
||||
"zapret-discord-youtube": { "configName": "general (ALT9)", "gameFilter": "all" } },
|
||||
"tgWsProxy": { "enable": false },
|
||||
"amneziaWg": { "enable": true, "profiles": {
|
||||
"home": { "autostart": true, "config": "[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 10.8.0.2/32\nDNS = 1.1.1.1\nJc = 4\nJmin = 40\nJmax = 70\nS1 = 12\nS2 = 34\nH1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.7:51820\n" },
|
||||
"office": { "asOutbound": "userspace", "config": "[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 10.8.0.2/32\nDNS = 1.1.1.1\nJc = 4\nJmin = 40\nJmax = 70\nS1 = 12\nS2 = 34\nH1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.7:51820\n" } } },
|
||||
"whitelistBypass": { "enable": true,
|
||||
"joiners": { "wl": { "platform": "wbstream" } },
|
||||
"creators": { "office": { "platform": "bitrix" } } } }
|
||||
@@ -57,6 +61,8 @@ target/debug/proxy-ctl --socket "$SOCK" proxy outbounds test >/dev/null 2>&1 ||
|
||||
shot() {
|
||||
local name=$1 y=$2 extra=${3:-}
|
||||
SHOT_STEPS="click:197,$y wait:2 $extra" tools/gui-shot.sh "$OUT/$name.png" 8 -- --socket "$SOCK" >/dev/null
|
||||
# gui-shot keeps the app's log beside the shot: not for the README.
|
||||
rm -f "$OUT/$name.log"
|
||||
echo "$OUT/$name.png"
|
||||
}
|
||||
shot overview 162
|
||||
@@ -65,6 +71,7 @@ shot telegram 234
|
||||
shot whitelist-bypass 270
|
||||
shot outbounds 306
|
||||
shot autoproxy 342
|
||||
shot logs 378
|
||||
shot settings 414
|
||||
shot components 450
|
||||
shot amneziawg 378
|
||||
shot logs 414
|
||||
shot settings 450
|
||||
shot components 486
|
||||
@@ -64,6 +64,26 @@ running || fail "the service is $(state)"
|
||||
for _ in $(seq 30); do wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 && break; sleep 1; done
|
||||
wine "$PF/proxy-ctl.exe" components | tr -d '\r' | sed 's/^/ /' || fail "no answer over the pipe"
|
||||
|
||||
echo "== an AmneziaWG system-wide profile: its tunnel service registered, then removed"
|
||||
CONF='[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 10.8.0.2/32\nDNS = 1.1.1.1\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.7:51820\n'
|
||||
printf '{ "amneziaWg": { "enable": true, "profiles": { "home": { "config": "%s" } } } }' "$CONF" >"$WORK/awg.json"
|
||||
wine "$PF/proxy-ctl.exe" config set "Z:$WORK/awg.json" | tr -d '\r' | sed 's/^/ /'
|
||||
sleep 3
|
||||
# Wine's sc has no qc: the service's registry key says the same.
|
||||
qc=$(wine reg query 'HKLM\System\CurrentControlSet\Services\AmneziaWGTunnel$home' 2>/dev/null | tr -d '\r' || true)
|
||||
grep -q 'awg-tunnel.exe' <<<"$qc" || fail "no tunnel service registered: $(wine "$PF/proxy-ctl.exe" logs proxy-suite-awg-vpn -n 20 | tr -d '\r')"
|
||||
grep -iE 'ImagePath|ServiceSidType|DependOnService' <<<"$qc" | sed 's/^ */ /'
|
||||
wine "$PF/proxy-ctl.exe" awg | tr -d '\r' | sed 's/^/ /'
|
||||
# Wine has no Wintun driver: the tunnel itself cannot come up here, only be asked to.
|
||||
wine "$PF/proxy-ctl.exe" awg on home 2>&1 | tr -d '\r' | sed 's/^/ on: /' || true
|
||||
sleep 3
|
||||
wine "$PF/proxy-ctl.exe" awg log home -n 5 2>&1 | tr -d '\r' | sed 's/^/ log: /' || true
|
||||
printf '{}' >"$WORK/none.json"
|
||||
wine "$PF/proxy-ctl.exe" config set "Z:$WORK/none.json" >/dev/null
|
||||
sleep 3
|
||||
wine reg query 'HKLM\System\CurrentControlSet\Services\AmneziaWGTunnel$home' >/dev/null 2>&1 && fail "the tunnel service outlived its profile"
|
||||
echo " registered, and removed with its profile"
|
||||
|
||||
echo "== setup /S again, over the running install"
|
||||
wine "$SETUP" /S && rc=0 || rc=$?
|
||||
[ "$rc" = 0 ] || fail "the upgrade exited with $rc"
|
||||
|
||||
@@ -59,4 +59,27 @@ if out=$(cd "$Z2" && wine ./winws2.exe --dry-run "${args[@]}" 2>&1) && grep -q "
|
||||
else
|
||||
fail=$((fail + 1)); echo "FAIL: zapret2"; grep -v -i cygwin <<<"$out" | tail -4
|
||||
fi
|
||||
# With the zapret2-extras component: upstream's Lua layers loaded and the extended detector
|
||||
# learning, for nfqws2-keenetic's strategies and for z2k's, with the environment the service
|
||||
# gives winws2.
|
||||
X="$STAGE/zapret2-extras"
|
||||
if [ -d "$X" ]; then
|
||||
cyg() { echo "/cygdrive/z$(realpath "$1")"; }
|
||||
mkdir -p "$WORK/z2/learned/circular" "$WORK/z2/learned/run"
|
||||
for kind in keenetic z2k; do
|
||||
# Through an options file (@file), as the service starts winws2: z2k's run past the
|
||||
# 32767 characters of a Windows command line. One a line, quoted when it holds a space.
|
||||
{ echo --dry-run; target/debug/examples/zapret2_args "$Z2" "$(win "$Z2")" "$(win "$WORK/z2")" "$X" "$(win "$X")" "$(cyg "$X")/" "$kind"; } |
|
||||
python3 -I -c 'import sys
|
||||
for a in sys.stdin.read().splitlines():
|
||||
print(("\"" + a.replace("\\", "\\\\").replace("\"", "\\\"") + "\"") if (" " in a or "\"" in a) else a)' >"$WORK/winws2.conf"
|
||||
if out=$(cd "$Z2" && Z2K_STATE_DIR_OVERRIDE="$(cyg "$WORK/z2/learned/circular")" Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE="$(cyg "$WORK/z2/learned/run")" \
|
||||
PROXY_SUITE_ZAPRET2_VERDICTS="$(cyg "$WORK/z2/learned")/verdicts.tsv" PROXY_SUITE_PUBLIC_SUFFIXES="$(cyg "$X")/public_suffixes.txt" \
|
||||
WINEDEBUG=-all wine ./winws2.exe "@$(win "$WORK")winws2.conf" 2>&1) && grep -q "parameters verified" <<<"$out"; then
|
||||
echo "zapret2 ($kind, extended detection, upstream's Lua layers): verified by winws2.exe, $(grep -c -- '--lua-init' "$WORK/winws2.conf") Lua files, $(wc -l <"$WORK/winws2.conf") options"
|
||||
else
|
||||
fail=$((fail + 1)); echo "FAIL: zapret2 ($kind with the extras)"; grep -v -i cygwin <<<"$out" | tail -6
|
||||
fi
|
||||
done
|
||||
fi
|
||||
[ "$fail" = 0 ]
|
||||