windows: raw backend JSON is always admin-only; WireGuard profiles

Telling path-shaped values from addresses on Windows (drive letters,
UNC, device paths, sockets) is too easy to get wrong, so raw sing-box
and XRay JSON now needs an administrator outright. ps-core::wg parses
WireGuard/AmneziaWG profiles into sing-box endpoints, as upstream's
warp_outbound.py does. Routing rules gain name, priority and disabled
for proxy-ctl proxy rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-26 22:44:31 +03:00
1 parent 96958c4e61
commit c01538fec9
4 files changed
+195 -40

No files matched your search

+7 -36
View File
@@ -14,14 +14,12 @@ use super::Config;
const RAW_KEYS: [&str; 4] = ["extraArgs", "extraConfig", "nfqwsArgs", "allowConfigHooks"];
/// Option paths (`.`-separated, `*` for any key or index) privileged as a whole.
const PRIVILEGED_PATHS: [&str; 6] = [
const PRIVILEGED_PATHS: [&str; 5] = [
"userControl",
"proxy.dns.singBox",
"zapret.zapret2.profiles",
"zapret.zapret2.blobs",
"inbounds.manager.api",
// XRay inbound JSON can listen on a socket path or serve a directory: no subset of it is safe.
"inbounds.listeners.*.xrayJson",
];
/// Where a value of `new` that differs from `old` needs an administrator, as option paths.
@@ -99,39 +97,15 @@ fn privileged_here(path: &[String], new: Option<&Value>) -> Option<bool> {
if RAW_KEYS.contains(&key) {
return Some(true);
}
// Raw backend JSON is fine as long as it names no local file or program, as upstream
// takes it at runtime from its userControl group.
// Raw backend JSON reaches sing-box or XRay as it stands. Upstream takes it from its
// userControl group after a check for file keys, but on Windows a value can name a file
// in too many ways (drive letters, UNC and device paths, sockets) to sort out safely.
if key.ends_with("Json") {
return Some(new.is_some_and(raw_json_is_unsafe));
return Some(true);
}
None
}
/// Raw backend JSON a non-administrator may not set: it names a local file or program by key
/// (`local_file_keys`), runs Tor, or holds a value shaped like a path (a Unix socket for a
/// server address, a file to write).
fn raw_json_is_unsafe(value: &Value) -> bool {
fn path_like(s: &str) -> bool {
let b = s.as_bytes();
s.starts_with('/')
|| s.starts_with('@')
|| s.starts_with('\\')
|| s.starts_with('~')
|| (b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'\\' | b'/'))
}
fn any_string(v: &Value, f: &dyn Fn(&str) -> bool) -> bool {
match v {
Value::String(s) => f(s),
Value::Array(a) => a.iter().any(|v| any_string(v, f)),
Value::Object(o) => o.values().any(|v| any_string(v, f)),
_ => false,
}
}
!crate::links::local_file_keys(value).is_empty()
|| value.get("type").and_then(Value::as_str) == Some("tor")
|| any_string(value, &|s| path_like(s) && !s.starts_with("//"))
}
fn matches_path(pattern: &str, path: &[String]) -> bool {
let parts: Vec<&str> = pattern.split('.').collect();
path.len() >= parts.len() && parts.iter().zip(path).all(|(p, s)| *p == "*" || *p == s)
@@ -183,15 +157,12 @@ mod tests {
}
#[test]
fn raw_json_is_privileged_only_when_it_names_files() {
fn raw_json_always_needs_one() {
let old = Config::default();
let mut new = old.clone();
let mut json = serde_json::Map::new();
json.insert("type".into(), "vless".into());
new.proxy.outbounds.push(Outbound { tag: "a".into(), sing_box_json: Some(json.clone()), ..Default::default() });
assert_eq!(privileged_changes(&old, &new), Vec::<String>::new());
json.insert("tls".into(), serde_json::json!({ "certificate_path": "C:\\x" }));
new.proxy.outbounds[0].sing_box_json = Some(json);
new.proxy.outbounds.push(Outbound { tag: "a".into(), sing_box_json: Some(json), ..Default::default() });
assert_eq!(privileged_changes(&old, &new), ["proxy.outbounds.0.singBoxJson"]);
}
+12 -4
View File
@@ -218,10 +218,6 @@ pub struct Outbound {
pub xray_json: Option<Map<String, Value>>,
pub backend: OutboundBackend,
pub routing: RouteMatch,
/// Windows only, and what upstream's `proxy-ctl proxy outbounds disable` keeps in its
/// state: left out of selection and autoProxy, still usable by name.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub disabled: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
@@ -443,6 +439,18 @@ impl Default for Routing {
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct RoutingRule {
/// Windows only: what `proxy-ctl proxy rules` calls the rule. Upstream's runtime rules
/// have names; its declared ones do not, and neither need one here.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Windows only: where the rule sorts among the configuration's sections, lower first
/// (`proxy.routing.rules` sit at 100, the proxy, block, direct and geo lists at 200 to
/// 500). `null`: 100, in list order.
#[serde(skip_serializing_if = "Option::is_none")]
pub priority: Option<i64>,
/// Windows only: kept, but not applied.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub disabled: bool,
pub outbound: String,
#[serde(flatten)]
pub matches: RouteMatch,
+1
View File
@@ -7,3 +7,4 @@
pub mod config;
pub mod derived;
pub mod links;
pub mod wg;
+175
View File
@@ -0,0 +1,175 @@
//! WireGuard and AmneziaWG `.conf` files: their sections, and a profile as a sing-box
//! WireGuard endpoint (upstream's `warp_outbound.py`).
use serde_json::{Value, json};
/// The AmneziaWG `[Interface]` keys, lowercased, with their spelling. sing-box speaks plain
/// WireGuard and has no use for them.
pub const AWG_INTERFACE_FIELDS: [(&str, &str); 25] = [
("jc", "Jc"),
("jmin", "Jmin"),
("jmax", "Jmax"),
("s1", "S1"),
("s2", "S2"),
("s3", "S3"),
("s4", "S4"),
("h1", "H1"),
("h2", "H2"),
("h3", "H3"),
("h4", "H4"),
("i1", "I1"),
("i2", "I2"),
("i3", "I3"),
("i4", "I4"),
("i5", "I5"),
("headerprotectionkey", "HeaderProtectionKey"),
("contentpaddingaddition", "ContentPaddingAddition"),
("rekeyaftertime", "RekeyAfterTime"),
("rekeytimeout", "RekeyTimeout"),
("rejectaftertime", "RejectAfterTime"),
("keepalivetimeout", "KeepaliveTimeout"),
("maxhandshakeattempts", "MaxHandshakeAttempts"),
("randomtrailers", "RandomTrailers"),
("disablecookies", "DisableCookies"),
];
/// wg-quick keys that run commands or rewrite the file: refused in imported configs unless
/// `allowConfigHooks`.
pub const FORBIDDEN_WG_QUICK_KEYS: [&str; 5] = ["preup", "postup", "predown", "postdown", "saveconfig"];
pub type Section = (String, Vec<(String, String)>);
/// Each `[Section]`, lowercased, with its `key = value` lines in order; keys lowercased,
/// comments (`#`, `;`) and lines outside a section dropped.
pub fn conf_sections(config: &str) -> Vec<Section> {
let mut sections: Vec<Section> = Vec::new();
for line in crate::links::py::splitlines(config) {
let stripped = line.split('#').next().unwrap_or("").split(';').next().unwrap_or("").trim();
if stripped.starts_with('[') && stripped.ends_with(']') && stripped.len() >= 2 {
sections.push((stripped[1..stripped.len() - 1].trim().to_lowercase(), Vec::new()));
} else if let Some((key, value)) = stripped.split_once('=') {
if let Some(last) = sections.last_mut() {
last.1.push((key.trim().to_lowercase(), value.trim().to_owned()));
}
}
}
sections
}
fn section<'a>(sections: &'a [Section], name: &str) -> Option<&'a [(String, String)]> {
sections.iter().find(|(n, _)| n == name).map(|(_, pairs)| pairs.as_slice())
}
fn get<'a>(pairs: &'a [(String, String)], key: &str) -> Option<&'a str> {
// dict(pairs): the last value of a repeated key wins.
pairs.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v.as_str()).filter(|v| !v.is_empty())
}
fn split_list(value: &str) -> Vec<String> {
value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
}
/// `host:port`, IPv6 in brackets.
pub fn split_endpoint(endpoint: &str) -> Result<(String, u16), String> {
let bad = || format!("endpoint '{endpoint}' is not host:port");
let (host, port) = endpoint.rsplit_once(':').ok_or_else(bad)?;
if host.is_empty() || port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) {
return Err(bad());
}
let port: u16 = port.parse().map_err(|_| bad())?;
Ok((host.trim_matches(|c| c == '[' || c == ']').to_owned(), port))
}
/// A WireGuard profile as a sing-box `wireguard` endpoint tagged `tag`, the profile's
/// endpoint replaced by `endpoint` when given. Also the AmneziaWG keys it had to drop.
pub fn sing_box_endpoint(text: &str, tag: &str, endpoint: Option<&str>) -> Result<(Value, Vec<&'static str>), String> {
let sections = conf_sections(text);
let (Some(interface), Some(peer)) = (section(&sections, "interface"), section(&sections, "peer")) else {
return Err("configuration requires [Interface] and [Peer] sections".into());
};
for (pairs, key) in [(interface, "privatekey"), (interface, "address"), (peer, "publickey"), (peer, "endpoint")] {
if get(pairs, key).is_none() {
return Err(format!("configuration has no {key}"));
}
}
let (host, port) = split_endpoint(endpoint.unwrap_or_else(|| get(peer, "endpoint").unwrap()))?;
let allowed = get(peer, "allowedips").map(split_list).filter(|l| !l.is_empty());
let mut sb_peer = json!({
"address": host,
"port": port,
"public_key": get(peer, "publickey").unwrap(),
"allowed_ips": allowed.unwrap_or_else(|| vec!["0.0.0.0/0".into(), "::/0".into()]),
});
if let Some(ka) = get(peer, "persistentkeepalive") {
// AWG 3 profiles give a range ("25-35"); sing-box takes one value.
let first = ka.split('-').next().unwrap_or("");
let interval: u32 = first.trim().parse().map_err(|_| format!("persistentkeepalive '{ka}' is not a number"))?;
sb_peer["persistent_keepalive_interval"] = interval.into();
}
if let Some(psk) = get(peer, "presharedkey") {
sb_peer["pre_shared_key"] = psk.into();
}
let mtu: u32 = match get(interface, "mtu") {
Some(m) => m.parse().map_err(|_| format!("mtu '{m}' is not a number"))?,
None => 1280,
};
let endpoint = json!({
"type": "wireguard",
"tag": tag,
"address": split_list(get(interface, "address").unwrap()),
"private_key": get(interface, "privatekey").unwrap(),
"mtu": mtu,
"peers": [sb_peer],
});
let mut dropped: Vec<&'static str> = AWG_INTERFACE_FIELDS
.iter()
.filter(|(k, _)| interface.iter().any(|(key, _)| key == k))
.map(|(_, name)| *name)
.collect();
dropped.sort_unstable();
Ok((endpoint, dropped))
}
/// The wg-quick hooks a config would run.
pub fn forbidden_keys(text: &str) -> Vec<String> {
let mut found: Vec<String> = conf_sections(text)
.into_iter()
.flat_map(|(_, pairs)| pairs.into_iter().map(|(k, _)| k))
.filter(|k| FORBIDDEN_WG_QUICK_KEYS.contains(&k.as_str()))
.collect();
found.sort();
found.dedup();
found
}
#[cfg(test)]
mod tests {
use super::*;
const WGCF: &str = "[Interface]\nPrivateKey = cHJpdmF0ZQ==\nAddress = 172.16.0.2/32, 2606:4700:110::2/128\nDNS = 1.1.1.1\nMTU = 1280\nJc = 4\n\n[Peer]\nPublicKey = cHVibGlj\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = engage.cloudflareclient.com:2408 # comment\nPersistentKeepalive = 25-35\n";
#[test]
fn a_wgcf_profile_becomes_an_endpoint() {
let (ep, dropped) = sing_box_endpoint(WGCF, "warp", None).unwrap();
assert_eq!(ep["address"], json!(["172.16.0.2/32", "2606:4700:110::2/128"]));
assert_eq!(ep["peers"][0]["address"], "engage.cloudflareclient.com");
assert_eq!(ep["peers"][0]["port"], 2408);
assert_eq!(ep["peers"][0]["persistent_keepalive_interval"], 25);
assert_eq!(dropped, ["Jc"]);
let (ep, _) = sing_box_endpoint(WGCF, "warp", Some("[2606:4700:d0::a29f:c001]:500")).unwrap();
assert_eq!(ep["peers"][0]["address"], "2606:4700:d0::a29f:c001");
assert_eq!(ep["peers"][0]["port"], 500);
}
#[test]
fn missing_pieces_are_named() {
assert!(sing_box_endpoint("[Interface]\nPrivateKey = x\n", "w", None).unwrap_err().contains("[Peer]"));
let no_ep = WGCF.replace("Endpoint", "#Endpoint");
assert_eq!(sing_box_endpoint(&no_ep, "w", None).unwrap_err(), "configuration has no endpoint");
}
#[test]
fn hooks_are_found() {
assert_eq!(forbidden_keys("[Interface]\nPostUp = calc.exe\nSaveConfig = true\n"), ["postup", "saveconfig"]);
}
}