Each profile without asOutbound is a tunnel service of its own, AmneziaWGTunnel$<interface>, as amneziawg-windows's client installs one: amneziawg-go on Wintun, its routes and DNS, and for one peer that takes everything its firewall blocking what would leave outside the tunnel. It runs awg-tunnel.exe, amneziawg-windows built from its pinned commit with a main of ours (its Run(), its log in a file) instead of its tunnel.dll, beside Wintun's signed DLL (tools/build-amneziawg.sh). The service writes each profile's .conf below its state root, registers the tunnel (unrestricted service SID, which its firewall exempts it by), starts the autostart ones with itself, and removes the tunnels of profiles gone, and all of them on uninstall. proxy-ctl awg list|on|off|log, and the app's AmneziaWG page: profiles (a system-wide one switched on and off, its log), one added from a vpn:// link or a .conf, or removed. tools/lib.sh: clone_commit, and fetch_pinned, which fetches in pieces a download that stalls (some networks cut TLS after about 16 KB, as wintun.net's here). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
420 lines
17 KiB
Rust
420 lines
17 KiB
Rust
//! The configuration edits proxy-ctl and the app make, on the configuration as JSON (what
|
|
//! `config-get` returns). Each can be made again on a newer configuration, which
|
|
//! [`Client::edit`](crate::Client::edit) does when another change came first.
|
|
|
|
use anyhow::{Result, anyhow, bail};
|
|
use serde_json::{Value, json};
|
|
|
|
/// The list at `path`, made (with the objects above it) when missing.
|
|
pub fn arr<'a>(v: &'a mut Value, path: &[&str]) -> &'a mut Vec<Value> {
|
|
let mut cur = v;
|
|
for p in path {
|
|
if cur.get(*p).is_none_or(Value::is_null) {
|
|
cur[*p] = if *p == path[path.len() - 1] { json!([]) } else { json!({}) };
|
|
}
|
|
cur = cur.get_mut(*p).unwrap();
|
|
}
|
|
cur.as_array_mut().expect("a list")
|
|
}
|
|
|
|
/// A tag for a link without one: its remark, else its host.
|
|
pub fn link_tag(link: &str) -> String {
|
|
if let Some((_, remark)) = link.split_once('#') {
|
|
let t = ps_core::links::subscription::slugify_tag(&ps_core::links::py::unquote(remark));
|
|
if t != "proxy" {
|
|
return t;
|
|
}
|
|
}
|
|
let host = link.split("://").nth(1).unwrap_or("").split(['@']).next_back().unwrap_or("").split([':', '/', '?', '#']).next().unwrap_or("");
|
|
let t = ps_core::links::subscription::slugify_tag(host);
|
|
if t.is_empty() { "outbound".into() } else { t }
|
|
}
|
|
|
|
/// A tag for a subscription without one: its host.
|
|
pub fn subscription_tag(url: &str) -> String {
|
|
let host = ps_core::links::subscription::url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_else(|| "sub".into());
|
|
ps_core::links::subscription::slugify_tag(&host)
|
|
}
|
|
|
|
/// What an outbound is made from: a share link, or a backend's own JSON for one.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum OutboundSource {
|
|
Link(String),
|
|
SingBoxJson(Value),
|
|
XrayJson(Value),
|
|
}
|
|
|
|
impl OutboundSource {
|
|
/// A link, or JSON (XRay's has a `protocol`, sing-box's a `type`). A link is checked
|
|
/// here: the service would only say it left the outbound out.
|
|
pub fn parse(text: &str) -> Result<Self> {
|
|
let text = text.trim();
|
|
if text.starts_with('{') {
|
|
let json: Value = serde_json::from_str(text).map_err(|e| anyhow!("not JSON: {e}"))?;
|
|
return Ok(if json.get("protocol").is_some() { Self::XrayJson(json) } else { Self::SingBoxJson(json) });
|
|
}
|
|
ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::SingBox)
|
|
.or_else(|_| ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::Xray))
|
|
.map_err(|e| anyhow!("{e}"))?;
|
|
Ok(Self::Link(text.to_owned()))
|
|
}
|
|
}
|
|
|
|
pub fn add_outbound(c: &mut Value, tag: &str, source: &OutboundSource, detour: Option<&str>) -> Result<()> {
|
|
let list = arr(c, &["proxy", "outbounds"]);
|
|
if list.iter().any(|o| o["tag"] == tag) {
|
|
bail!("an outbound '{tag}' exists");
|
|
}
|
|
let mut ob = match source {
|
|
OutboundSource::Link(link) => json!({ "tag": tag, "url": link }),
|
|
OutboundSource::SingBoxJson(j) => json!({ "tag": tag, "singBoxJson": j }),
|
|
OutboundSource::XrayJson(j) => json!({ "tag": tag, "xrayJson": j }),
|
|
};
|
|
if let Some(d) = detour {
|
|
ob["detour"] = d.into();
|
|
}
|
|
list.push(ob);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_outbound(c: &mut Value, tag: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "outbounds"]);
|
|
let before = list.len();
|
|
list.retain(|o| o["tag"] != tag);
|
|
if list.len() == before {
|
|
bail!("no outbound '{tag}' in the configuration");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn add_subscription(c: &mut Value, tag: &str, url: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "subscriptions"]);
|
|
if list.iter().any(|s| s["tag"] == tag) {
|
|
bail!("a subscription '{tag}' exists");
|
|
}
|
|
list.push(json!({ "tag": tag, "url": url }));
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_subscription(c: &mut Value, tag: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "subscriptions"]);
|
|
let before = list.len();
|
|
list.retain(|s| s["tag"] != tag);
|
|
if list.len() == before {
|
|
bail!("no subscription '{tag}'");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// A rule's matches, sorted into their kinds: domains, addresses, `geosite:`, `geoip:`,
|
|
/// `ruleset:` and `process:` ones.
|
|
pub fn sort_matches(matches: &[String]) -> Value {
|
|
let mut m = json!({ "domains": [], "ips": [], "geosites": [], "geoips": [], "ruleSets": [], "processNames": [] });
|
|
for x in matches {
|
|
let (key, value) = if let Some(v) = x.strip_prefix("geosite:") {
|
|
("geosites", v.to_owned())
|
|
} else if let Some(v) = x.strip_prefix("geoip:") {
|
|
("geoips", v.to_owned())
|
|
} else if let Some(v) = x.strip_prefix("ruleset:") {
|
|
("ruleSets", v.to_owned())
|
|
} else if let Some(v) = x.strip_prefix("process:") {
|
|
("processNames", v.to_owned())
|
|
} else if x.parse::<std::net::IpAddr>().is_ok() || x.split_once('/').is_some_and(|(a, _)| a.parse::<std::net::IpAddr>().is_ok()) {
|
|
("ips", x.clone())
|
|
} else {
|
|
("domains", x.trim_start_matches('.').to_lowercase())
|
|
};
|
|
m[key].as_array_mut().unwrap().push(value.into());
|
|
}
|
|
m
|
|
}
|
|
|
|
/// Sends `matches` to `target`: into the rule called `name` (the target's name without
|
|
/// one), extended if it exists, made with priority 50 if not.
|
|
pub fn add_rule(c: &mut Value, target: &str, matches: &[String], name: Option<&str>, priority: Option<i64>) -> Result<()> {
|
|
if matches.is_empty() {
|
|
bail!("a rule needs something to match");
|
|
}
|
|
let m = sort_matches(matches);
|
|
let name = name.unwrap_or(target);
|
|
let list = arr(c, &["proxy", "routing", "rules"]);
|
|
if let Some(rule) = list.iter_mut().find(|r| r["name"] == name) {
|
|
for (k, v) in m.as_object().unwrap() {
|
|
let mut merged = rule[k.as_str()].as_array().cloned().unwrap_or_default();
|
|
for x in v.as_array().unwrap() {
|
|
if !merged.contains(x) {
|
|
merged.push(x.clone());
|
|
}
|
|
}
|
|
rule[k.as_str()] = Value::Array(merged);
|
|
}
|
|
rule["outbound"] = target.into();
|
|
if let Some(p) = priority {
|
|
rule["priority"] = p.into();
|
|
}
|
|
} else {
|
|
let mut rule = m;
|
|
rule["name"] = name.into();
|
|
rule["outbound"] = target.into();
|
|
rule["priority"] = priority.unwrap_or(50).into();
|
|
list.push(rule);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_rule(c: &mut Value, name: &str) -> Result<()> {
|
|
let list = arr(c, &["proxy", "routing", "rules"]);
|
|
let before = list.len();
|
|
list.retain(|r| r["name"] != name);
|
|
if list.len() == before {
|
|
bail!("no rule named '{name}'");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn set_rule_disabled(c: &mut Value, name: &str, disabled: bool) -> Result<()> {
|
|
if name.is_empty() {
|
|
bail!("a rule name");
|
|
}
|
|
let list = arr(c, &["proxy", "routing", "rules"]);
|
|
let rule = list.iter_mut().find(|r| r["name"] == name).ok_or_else(|| anyhow!("no rule named '{name}'"))?;
|
|
rule["disabled"] = disabled.into();
|
|
Ok(())
|
|
}
|
|
|
|
pub fn set_proxy_enabled(c: &mut Value, on: bool) {
|
|
c["proxy"]["enable"] = on.into();
|
|
}
|
|
|
|
pub fn set_tun_enabled(c: &mut Value, on: bool) {
|
|
c["proxy"]["tun"]["enable"] = on.into();
|
|
}
|
|
|
|
pub fn set_zapret_enabled(c: &mut Value, on: bool) {
|
|
c["zapret"]["enable"] = on.into();
|
|
}
|
|
|
|
/// The DPI bypass's engine, by upstream's names: `zapret-discord-youtube` (Flowseal's
|
|
/// presets) or `zapret2`.
|
|
pub fn set_zapret_engine(c: &mut Value, engine: &str) -> Result<()> {
|
|
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
|
|
bail!("the engine is zapret-discord-youtube or zapret2");
|
|
}
|
|
c["zapret"]["engine"] = engine.into();
|
|
Ok(())
|
|
}
|
|
|
|
/// The zapret-discord-youtube preset, e.g. "general (ALT9)".
|
|
pub fn set_zapret_preset(c: &mut Value, name: &str) {
|
|
c["zapret"]["zapret-discord-youtube"]["configName"] = name.into();
|
|
}
|
|
|
|
/// Which game traffic zapret handles: all, tcp, udp or null.
|
|
pub fn set_game_filter(c: &mut Value, filter: &str) -> Result<()> {
|
|
if !matches!(filter, "all" | "tcp" | "udp" | "null") {
|
|
bail!("the game filter is all, tcp, udp or null");
|
|
}
|
|
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.into();
|
|
Ok(())
|
|
}
|
|
|
|
pub fn set_tg_ws_proxy_enabled(c: &mut Value, on: bool) {
|
|
c["tgWsProxy"]["enable"] = on.into();
|
|
}
|
|
|
|
/// Any option by its path, e.g. `["zapret", "zapret2", "ipv6"]`; the objects above it are
|
|
/// made when missing.
|
|
pub fn set_path(c: &mut Value, path: &[&str], value: Value) {
|
|
let mut cur = c;
|
|
for p in path {
|
|
if !cur.is_object() {
|
|
*cur = json!({});
|
|
}
|
|
cur = &mut cur[*p];
|
|
}
|
|
*cur = value;
|
|
}
|
|
|
|
/// whitelist-bypass's platforms, as its options name them.
|
|
pub const WL_PLATFORMS: [&str; 5] = ["wbstream", "telemost", "dion", "bitrix", "vk"];
|
|
|
|
/// A whitelist-bypass joiner or creator (`role`: "joiners" or "creators") on `platform`. A name
|
|
/// is one of either: `proxy-ctl wl` takes them by name alone.
|
|
pub fn add_wl(c: &mut Value, role: &str, name: &str, platform: &str) -> Result<()> {
|
|
if !matches!(role, "joiners" | "creators") {
|
|
bail!("a whitelist-bypass role is joiners or creators");
|
|
}
|
|
if !ps_core::config::path_name_ok(name) {
|
|
bail!("a name takes letters, digits, '.', '_' and '-', and no leading dot");
|
|
}
|
|
if !WL_PLATFORMS.contains(&platform) {
|
|
bail!("no platform '{platform}': {}", WL_PLATFORMS.join(", "));
|
|
}
|
|
if role == "joiners" && platform == "vk" {
|
|
bail!("VK has no joiner, only creators");
|
|
}
|
|
let wl = &c["whitelistBypass"];
|
|
if wl["joiners"].get(name).is_some() || wl["creators"].get(name).is_some() {
|
|
bail!("'{name}' is taken");
|
|
}
|
|
set_path(c, &["whitelistBypass", role, name], json!({ "platform": platform }));
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_wl(c: &mut Value, role: &str, name: &str) -> Result<()> {
|
|
match c.get_mut("whitelistBypass").and_then(|w| w.get_mut(role)).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
|
|
Some(_) => Ok(()),
|
|
None => bail!("no whitelist-bypass {} '{name}'", role.trim_end_matches('s')),
|
|
}
|
|
}
|
|
|
|
/// 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<()> {
|
|
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
|
|
bail!("the engine is zapret-discord-youtube or zapret2");
|
|
}
|
|
let clean = |list: &[String]| -> Vec<Value> {
|
|
let mut out: Vec<Value> = Vec::new();
|
|
for d in list.iter().map(|d| d.trim().trim_start_matches('.').to_lowercase()).filter(|d| !d.is_empty()) {
|
|
if !out.contains(&Value::from(d.as_str())) {
|
|
out.push(d.into());
|
|
}
|
|
}
|
|
out
|
|
};
|
|
c["zapret"][engine]["domains"] = Value::Array(clean(domains));
|
|
c["zapret"][engine]["excludeDomains"] = Value::Array(clean(exclude));
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
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!({});
|
|
add_wl(&mut c, "joiners", "wl", "wbstream").unwrap();
|
|
add_wl(&mut c, "creators", "laptop", "vk").unwrap();
|
|
assert_eq!(c["whitelistBypass"]["joiners"]["wl"], json!({ "platform": "wbstream" }));
|
|
assert!(add_wl(&mut c, "creators", "wl", "dion").is_err(), "a name is one of either");
|
|
assert!(add_wl(&mut c, "joiners", "phone", "vk").is_err(), "VK has no joiner");
|
|
assert!(add_wl(&mut c, "joiners", "phone", "zoom").is_err());
|
|
assert!(add_wl(&mut c, "joiners", "../x", "wbstream").is_err());
|
|
assert!(add_wl(&mut c, "joiners", "CON", "wbstream").is_err());
|
|
remove_wl(&mut c, "joiners", "wl").unwrap();
|
|
assert!(remove_wl(&mut c, "joiners", "wl").is_err());
|
|
assert_eq!(c["whitelistBypass"]["creators"]["laptop"]["platform"], "vk");
|
|
}
|
|
|
|
#[test]
|
|
fn outbounds_are_added_once_and_removed() {
|
|
let mut c = json!({});
|
|
let src = OutboundSource::parse("ss://YWVzLTEyOC1nY206cGFzcw@1.2.3.4:8388#My%20Server").unwrap();
|
|
add_outbound(&mut c, "nl", &src, Some("hop")).unwrap();
|
|
assert_eq!(c["proxy"]["outbounds"][0]["detour"], "hop");
|
|
assert!(add_outbound(&mut c, "nl", &src, None).is_err());
|
|
remove_outbound(&mut c, "nl").unwrap();
|
|
assert!(remove_outbound(&mut c, "nl").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn sources_are_links_or_either_json() {
|
|
assert!(matches!(OutboundSource::parse(r#"{"protocol":"vless"}"#).unwrap(), OutboundSource::XrayJson(_)));
|
|
assert!(matches!(OutboundSource::parse(r#" {"type":"vless"}"#).unwrap(), OutboundSource::SingBoxJson(_)));
|
|
assert!(OutboundSource::parse("not a link").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn tags_come_from_the_remark_or_the_host() {
|
|
assert_eq!(link_tag("ss://x@1.2.3.4:8388#My%20Server"), "My-Server");
|
|
assert_eq!(link_tag("vless://id@example.com:443?security=tls"), "example-com");
|
|
}
|
|
|
|
#[test]
|
|
fn rules_are_extended_by_name() {
|
|
let mut c = json!({});
|
|
add_rule(&mut c, "direct", &["Example.com".into(), "10.0.0.0/8".into(), "process:steam.exe".into()], None, None).unwrap();
|
|
add_rule(&mut c, "direct", &["example.com".into(), "geosite:cn".into()], None, Some(10)).unwrap();
|
|
let r = &c["proxy"]["routing"]["rules"][0];
|
|
assert_eq!(r["domains"], json!(["example.com"]));
|
|
assert_eq!(r["ips"], json!(["10.0.0.0/8"]));
|
|
assert_eq!(r["processNames"], json!(["steam.exe"]));
|
|
assert_eq!(r["geosites"], json!(["cn"]));
|
|
assert_eq!(r["priority"], 10);
|
|
set_rule_disabled(&mut c, "direct", true).unwrap();
|
|
assert_eq!(c["proxy"]["routing"]["rules"][0]["disabled"], true);
|
|
}
|
|
|
|
#[test]
|
|
fn paths_and_site_lists() {
|
|
let mut c = json!({ "zapret": null });
|
|
set_path(&mut c, &["zapret", "zapret2", "ipv6"], true.into());
|
|
assert_eq!(c["zapret"]["zapret2"]["ipv6"], true);
|
|
set_zapret_sites(&mut c, "zapret2", &[" .Example.com".into(), "".into(), "example.com".into()], &["bank.example".into()]).unwrap();
|
|
assert_eq!(c["zapret"]["zapret2"]["domains"], json!(["example.com"]));
|
|
assert_eq!(c["zapret"]["zapret2"]["excludeDomains"], json!(["bank.example"]));
|
|
assert!(set_zapret_sites(&mut c, "goodbyedpi", &[], &[]).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn zapret_settings_are_checked() {
|
|
let mut c = json!({});
|
|
assert!(set_game_filter(&mut c, "everything").is_err());
|
|
set_game_filter(&mut c, "udp").unwrap();
|
|
assert!(set_zapret_engine(&mut c, "goodbyedpi").is_err());
|
|
set_zapret_engine(&mut c, "zapret2").unwrap();
|
|
assert_eq!(c["zapret"], json!({ "engine": "zapret2", "zapret-discord-youtube": { "gameFilter": "udp" } }));
|
|
}
|
|
}
|