Files
proxy-suite-flake/windows/crates/ps-core/src/config/validate.rs
T
faumarayandClaude Opus 5.5 5cf3a237e6 windows: AmneziaWG as a system-wide VPN
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>
2026-10-27 17:23:11 +03:00

912 lines
43 KiB
Rust

//! Checks a configuration before the service takes it, as upstream's assertions do at
//! evaluation. Errors refuse the configuration; warnings go with it.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use super::{Backend, Config, GroupStrategy, Selection, StrategySource, ZapretDefaultDomains, ZapretEngine, ZapretPreset};
use crate::derived::{self, BUILTIN_TAGS};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Issue {
pub severity: Severity,
/// The option it is about, as `proxy.outbounds.2.tag`.
pub path: String,
pub message: String,
}
struct Issues(Vec<Issue>);
impl Issues {
fn error(&mut self, path: impl Into<String>, message: impl Into<String>) {
self.0.push(Issue { severity: Severity::Error, path: path.into(), message: message.into() });
}
fn warn(&mut self, path: impl Into<String>, message: impl Into<String>) {
self.0.push(Issue { severity: Severity::Warning, path: path.into(), message: message.into() });
}
/// `used` needs `dependency`: the shape of most of upstream's assertions.
fn requires(&mut self, used: bool, dependency: bool, path: &str, used_label: &str, dependency_label: &str) {
if used && !dependency {
self.error(path, format!("{used_label} requires {dependency_label}"));
}
}
}
fn tag_pattern_ok(tag: &str) -> bool {
let mut chars = tag.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
/// A name that becomes part of a file path, a Windows service name or an adapter name:
/// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters.
pub fn path_name_ok(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
&& !windows_device(name)
}
/// CON, NUL, COM1 and the rest: on Windows a file named so (whatever its extension) is the
/// device.
fn windows_device(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes()[3].is_ascii_digit())
}
/// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path
/// (upstream's routing-render.jq `geo`).
pub(crate) fn geo_name_ok(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '!' | '@' | '.' | '_' | '-'))
}
fn profile_name_ok(name: &str) -> bool {
let mut chars = name.chars();
matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// A host name, an IPv4 address or a bracketless IPv6 one.
fn ssh_host_ok(host: &str) -> bool {
if host.parse::<std::net::IpAddr>().is_ok() {
return true;
}
!host.is_empty()
&& host.len() <= 253
&& host.split('.').all(|l| !l.is_empty() && l.len() <= 63 && !l.starts_with('-') && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'))
}
fn ssh_user_ok(user: &str) -> bool {
!user.is_empty() && !user.starts_with('-') && user.chars().all(|c| c.is_alphanumeric() || matches!(c, '.' | '_' | '-' | '@' | '$'))
}
fn count_some(values: &[bool]) -> usize {
values.iter().filter(|v| **v).count()
}
/// Every problem with `cfg`, errors first.
pub fn validate(cfg: &Config) -> Vec<Issue> {
let mut v = Issues(Vec::new());
proxy(cfg, &mut v);
tunnels(cfg, &mut v);
zapret(cfg, &mut v);
per_app(cfg, &mut v);
inbounds(cfg, &mut v);
ports(cfg, &mut v);
not_ported(cfg, &mut v);
let mut issues = v.0;
issues.sort_by_key(|i| i.severity != Severity::Error);
issues
}
/// What upstream runs and this port does not yet: said, never taken silently. (The kill switch
/// above all: on, it would otherwise look like protection that is not there.)
fn not_ported(cfg: &Config, v: &mut Issues) {
const IGNORED: &str = "is not on Windows yet: this release ignores it";
if cfg.kill_switch.enable {
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.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"),
] {
if on {
v.warn(path, format!("{what} {IGNORED}"));
}
}
if cfg.proxy.enable && cfg.proxy.backend == Backend::Xray {
v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)");
}
let z = &cfg.zapret;
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 && 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");
}
}
fn proxy(cfg: &Config, v: &mut Issues) {
let p = &cfg.proxy;
let sing_box = p.backend.runs_sing_box();
// Listen addresses reach other programs' configs and command lines (Tor's torrc, ssh's -D,
// tg-ws-proxy's --host): an IP address, nothing else.
for (path, address) in [
("proxy.listener.address", &p.listener.address),
("sshProxy.listener.address", &cfg.ssh_proxy.listener.address),
("tgWsProxy.listener.address", &cfg.tg_ws_proxy.listener.address),
] {
if address.parse::<std::net::IpAddr>().is_err() {
v.error(path, format!("'{address}' is not an IP address"));
}
}
let mut seen = BTreeSet::new();
for (i, ob) in p.outbounds.iter().enumerate() {
let path = format!("proxy.outbounds.{i}");
if ob.tag.is_empty() {
v.error(format!("{path}.tag"), "an outbound needs a tag");
} else if BUILTIN_TAGS.contains(&ob.tag.as_str()) {
v.error(format!("{path}.tag"), format!("'{}' is a builtin target and cannot be an outbound's tag", ob.tag));
} else if !seen.insert(ob.tag.as_str()) {
v.error(format!("{path}.tag"), format!("outbound tag '{}' is used twice", ob.tag));
}
let sources = [ob.url.is_some(), ob.url_file.is_some(), ob.sing_box_json.is_some(), ob.xray_json.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("outbound '{}' sets {} of url, urlFile, singBoxJson and xrayJson; it needs exactly one", ob.tag, count_some(&sources)));
}
if ob.sing_box_json.is_some() && p.backend == Backend::Xray {
v.error(&path, format!("outbound '{}' is sing-box JSON, which the xray backend cannot run", ob.tag));
}
if ob.xray_json.is_some() && p.backend == Backend::SingBox {
v.error(&path, format!("outbound '{}' is XRay JSON, which the sing-box backend cannot run", ob.tag));
}
if !ob.routing.rule_sets.is_empty() && !sing_box {
v.error(format!("{path}.routing.ruleSets"), "rule sets need the sing-box or hybrid backend");
}
for name in &ob.routing.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("{path}.routing.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
let mut subs = BTreeSet::new();
for (i, sub) in p.subscriptions.iter().enumerate() {
let path = format!("proxy.subscriptions.{i}");
if !tag_pattern_ok(&sub.tag) {
v.error(format!("{path}.tag"), format!("subscription tag '{}' must start with a letter or digit and hold only letters, digits, '.', '_' and '-'", sub.tag));
} else if !subs.insert(sub.tag.as_str()) {
v.error(format!("{path}.tag"), format!("subscription tag '{}' is used twice", sub.tag));
}
if count_some(&[sub.url.is_some(), sub.url_file.is_some()]) != 1 {
v.error(&path, format!("subscription '{}' needs exactly one of url and urlFile", sub.tag));
}
}
let known = |t: &str| derived::is_known_target(cfg, t);
for (i, ob) in p.outbounds.iter().enumerate() {
if let Some(hop) = &ob.detour {
if hop == &ob.tag {
v.error(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' cannot chain through itself", ob.tag));
} else if !known(hop) {
// A subscription entry, perhaps: those only exist once fetched.
v.warn(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' chains through '{hop}', which names no outbound declared here; it must be a subscription entry", ob.tag));
}
}
}
for (i, rule) in p.routing.rules.iter().enumerate() {
let path = format!("proxy.routing.rules.{i}");
if !known(&rule.outbound) {
v.error(format!("{path}.outbound"), format!("routing rule target '{}' is not an outbound, a group, or proxy, direct or block", rule.outbound));
}
if rule.matches.is_empty() && rule.process_names.is_empty() && rule.process_paths.is_empty() {
v.warn(&path, "this rule matches nothing");
}
if !rule.matches.rule_sets.is_empty() && !sing_box {
v.error(format!("{path}.ruleSets"), "rule sets need the sing-box or hybrid backend");
}
if (!rule.process_names.is_empty() || !rule.process_paths.is_empty()) && !sing_box {
v.error(&path, "matching programs needs the sing-box or hybrid backend");
}
for name in &rule.matches.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("{path}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
for (bucket, m) in [("proxy", &p.routing.proxy), ("direct", &p.routing.direct), ("block", &p.routing.block)] {
for name in &m.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("proxy.routing.{bucket}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
let mut geo_lists: Vec<(String, &crate::config::RouteMatch)> = vec![
("proxy.routing.proxy".into(), &p.routing.proxy),
("proxy.routing.direct".into(), &p.routing.direct),
("proxy.routing.block".into(), &p.routing.block),
];
geo_lists.extend(p.routing.rules.iter().enumerate().map(|(i, r)| (format!("proxy.routing.rules.{i}"), &r.matches)));
geo_lists.extend(p.outbounds.iter().enumerate().map(|(i, o)| (format!("proxy.outbounds.{i}.routing"), &o.routing)));
for (path, m) in geo_lists {
for name in m.geosites.iter().chain(&m.geoips) {
if !geo_name_ok(name) {
v.error(&path, format!("'{name}' is not a geosite or geoip name: letters, digits, '!', '@', '.', '_' and '-'"));
}
}
}
for name in p.routing.rule_sets.keys() {
if !path_name_ok(name) {
v.error(format!("proxy.routing.ruleSets.{name}"), "a rule set name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if !p.routing.rule_sets.is_empty() && !sing_box {
v.error("proxy.routing.ruleSets", "rule sets need the sing-box or hybrid backend");
}
for (name, rs) in &p.routing.rule_sets {
if !rs.url.starts_with("https://") || rs.url.len() <= "https://".len() {
v.error(format!("proxy.routing.ruleSets.{name}.url"), "a rule set is fetched over https only");
}
}
if !p.groups.is_empty() && !sing_box {
v.error("proxy.groups", "outbound groups need the sing-box or hybrid backend");
}
for (name, group) in &p.groups {
let path = format!("proxy.groups.{name}");
if !path_name_ok(name) {
v.error(&path, format!("group name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
if BUILTIN_TAGS.contains(&name.as_str()) || p.outbounds.iter().any(|o| &o.tag == name) {
v.error(&path, format!("group '{name}' takes a tag an outbound or builtin already has"));
}
for member in &group.outbounds {
if member == name {
v.error(format!("{path}.outbounds"), format!("group '{name}' cannot contain itself"));
} else if !known(member) {
v.warn(format!("{path}.outbounds"), format!("member '{member}' names no outbound declared here; it is left out unless a subscription brings it"));
}
}
for sub in &group.subscriptions {
if !p.subscriptions.iter().any(|s| &s.tag == sub) {
v.error(format!("{path}.subscriptions"), format!("subscription '{sub}' does not exist"));
}
}
if group.outbounds.is_empty() && group.subscriptions.is_empty() && group.match_.is_empty() {
v.warn(&path, format!("group '{name}' has no members: it blocks"));
}
if group.strategy != GroupStrategy::Failover && !group.failback {
v.warn(format!("{path}.failback"), "failback only applies to the failover strategy");
}
}
if p.selection == Selection::Failover && !sing_box {
v.error("proxy.selection", "\"failover\" selection needs the sing-box or hybrid backend");
}
if p.auto_proxy.enable && !sing_box {
v.error("proxy.autoProxy.enable", "autoProxy needs the sing-box or hybrid backend");
}
// Upstream samples transfers through the Clash API, which "first" selection leaves off
// there; here it is always on, so slow sites are routed whatever the selection.
if p.dns.fake_ip.enable && !sing_box {
v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend");
}
if p.enable && !derived::has_available_outbounds(cfg) {
v.warn("proxy.outbounds", "the proxy has no outbound or subscription yet; it starts once one is added");
}
v.requires(p.autostart.is_some(), p.tun.enable, "proxy.autostart", "proxy.autostart = \"tun\"", "proxy.tun.enable = true");
v.requires(p.tun.enable, p.enable, "proxy.tun.enable", "proxy.tun.enable", "proxy.enable = true");
v.requires(p.system_proxy.enable, p.enable, "proxy.systemProxy.enable", "proxy.systemProxy.enable", "proxy.enable = true");
let auth = &p.listener.auth;
if auth.username.is_some() && auth.password.is_none() && auth.password_file.is_none() {
v.error("proxy.listener.auth", "a username needs password or passwordFile");
}
if auth.password.is_some() && auth.password_file.is_some() {
v.error("proxy.listener.auth", "set password or passwordFile, not both");
}
if auth.username.is_none() && (auth.password.is_some() || auth.password_file.is_some()) {
v.error("proxy.listener.auth", "a password needs a username");
}
for (label, value) in [("username", &auth.username), ("password", &auth.password)] {
if value.as_deref().is_some_and(|s| s.is_empty() || s.chars().any(char::is_whitespace)) {
v.error(format!("proxy.listener.auth.{label}"), "it must be a single word");
}
}
if p.system_proxy.enable && auth.enabled() {
v.warn("proxy.systemProxy.enable", "the system proxy cannot carry a login: apps that follow it will be asked for one");
}
}
fn tunnels(cfg: &Config, v: &mut Issues) {
let proxy_on = cfg.proxy.enable;
let w = &cfg.warp;
if w.enable {
if w.as_outbound.is_none() && !w.as_amnezia_wg {
v.warn("warp.enable", "WARP is on, but neither asOutbound nor asAmneziaWg uses it");
}
if w.as_outbound.is_some() && w.as_amnezia_wg {
v.error("warp.asAmneziaWg", "asAmneziaWg cannot be used with asOutbound");
}
v.requires(w.as_outbound.is_some(), proxy_on, "warp.asOutbound", "warp.asOutbound", "proxy.enable = true");
v.requires(w.as_amnezia_wg, cfg.amnezia_wg.enable, "warp.asAmneziaWg", "warp.asAmneziaWg", "amneziaWg.enable = true");
v.requires(w.autostart, w.as_amnezia_wg, "warp.autostart", "warp.autostart", "warp.asAmneziaWg = true");
if w.instances.is_some() && !w.devices.is_empty() {
v.error("warp.instances", "instances cannot be used with devices");
}
if w.devices.len() > 1 && w.devices.contains_key(derived::WARP_TAG) {
v.error("warp.devices", "with several devices, \"warp\" names their group and cannot be a device");
}
if w.config_file.is_some() && w.config.is_some() {
v.error("warp.config", "set configFile or config, not both");
}
for name in w.devices.keys() {
if !path_name_ok(name) {
v.error(format!("warp.devices.{name}"), "a device name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
}
let a = &cfg.amnezia_wg;
if a.enable {
let mut autostarts = Vec::new();
for (name, p) in &a.profiles {
let path = format!("amneziaWg.profiles.{name}");
let sources = [p.config_file.is_some(), p.config.is_some(), p.vpn_file.is_some(), p.vpn.is_some(), p.settings.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("profile '{name}' needs exactly one of configFile, config, vpnFile, vpn and settings"));
}
if p.autostart {
autostarts.push(name.clone());
}
if p.as_outbound.is_some() && p.autostart {
v.warn(format!("{path}.autostart"), "an outbound always runs: autostart only applies to a global profile");
}
v.requires(p.as_outbound.is_some(), proxy_on, &format!("{path}.asOutbound"), &format!("amneziaWg.profiles.{name}.asOutbound"), "proxy.enable = true");
if !path_name_ok(name) {
v.error(&path, format!("profile name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
if let Some(iface) = &p.interface_name
&& (!path_name_ok(iface) || iface.len() > 32)
{
v.error(format!("{path}.interfaceName"), "a tunnel name takes letters, digits, '.', '_' and '-' (at most 32, no leading dot)");
}
if let Some(settings) = &p.settings {
if settings.peers.is_empty() {
v.error(format!("{path}.settings.peers"), "a profile needs a peer");
}
if settings.private_key.is_some() == settings.private_key_file.is_some() {
v.error(format!("{path}.settings"), "set exactly one of privateKey and privateKeyFile");
}
}
if BUILTIN_TAGS.contains(&name.as_str()) {
v.error(&path, format!("'{name}' is a builtin target"));
}
}
if w.autostart {
autostarts.push(derived::WARP_TAG.into());
}
if autostarts.len() > 1 {
v.error("amneziaWg.profiles", format!("only one global profile can autostart, not {}", autostarts.join(", ")));
}
if !autostarts.is_empty() && cfg.proxy.autostart.is_some() {
v.error("proxy.autostart", "only one global mode can autostart: a TUN and an AmneziaWG profile both do");
}
}
let t = &cfg.tor;
if t.enable {
v.requires(t.as_outbound, proxy_on, "tor.asOutbound", "tor.asOutbound", "proxy.enable = true");
v.requires(t.onion_service.enable, cfg.inbounds.enable, "tor.onionService.enable", "tor.onionService.enable", "inbounds.enable = true");
if !t.as_outbound && !t.onion_service.enable {
v.warn("tor.enable", "Tor is on, but neither asOutbound nor onionService uses it");
}
if t.socks_port == t.control_port {
v.error("tor.controlPort", "Tor's SOCKS and control ports must differ");
}
}
let s = &cfg.ssh_proxy;
if s.enable {
if s.server.host.is_none() {
v.error("sshProxy.server.host", "the SSH tunnel needs a server");
}
if s.server.user.is_none() {
v.error("sshProxy.server.user", "the SSH tunnel needs a login user");
}
// They reach ssh's command line (as SYSTEM on Windows): a host name or address and a
// login name, nothing that could read as an option or carry another line.
if let Some(host) = &s.server.host
&& !ssh_host_ok(host)
{
v.error("sshProxy.server.host", "a host name or an IP address");
}
if let Some(user) = &s.server.user
&& !ssh_user_ok(user)
{
v.error("sshProxy.server.user", "a login name: letters, digits, '.', '_', '-' and '@', not starting with '-'");
}
for (i, key) in s.host_key.iter().enumerate() {
if key.chars().any(char::is_control) {
v.error(format!("sshProxy.hostKey.{i}"), "a host key is one line");
}
}
v.requires(s.as_outbound, proxy_on, "sshProxy.asOutbound", "sshProxy.asOutbound", "proxy.enable = true");
if s.strict_host_key_checking == crate::config::StrictHostKeyChecking::Yes
&& s.known_hosts_file.is_none()
&& s.host_key_file.is_none()
&& s.host_key.is_empty()
{
v.error("sshProxy.strictHostKeyChecking", "\"yes\" needs the server's keys: knownHostsFile, hostKeyFile or hostKey");
}
}
let g = &cfg.tg_ws_proxy;
if g.enable {
if g.secret.is_some() && g.secret_file.is_some() {
v.error("tgWsProxy.secret", "set secret or secretFile, not both");
}
if let Some(secret) = &g.secret
&& (secret.len() != 32 || !secret.chars().all(|c| c.is_ascii_hexdigit())) {
v.error("tgWsProxy.secret", "an MTProto secret is 32 hex digits");
}
if g.buffer_kib < 4 {
v.error("tgWsProxy.bufferKiB", "the buffer is at least 4 KiB");
}
}
let wl = &cfg.whitelist_bypass;
// Checked on or off: `proxy-ctl wl` names files after them either way.
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if wl.enable {
v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true");
for (name, j) in &wl.joiners {
if j.platform == crate::config::WlPlatform::Vk {
v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here");
}
}
if wl.joiners.is_empty() && wl.creators.is_empty() {
v.warn("whitelistBypass.enable", "whitelist-bypass is on without creators or joiners");
}
}
}
fn zapret(cfg: &Config, v: &mut Issues) {
let z = &cfg.zapret;
if !z.enable {
return;
}
if z.engine == ZapretEngine::DiscordYoutube {
let mut names = BTreeSet::new();
for (i, rule) in z.discord_youtube.hostlist_rules.iter().enumerate() {
let path = format!("zapret.zapret-discord-youtube.hostlistRules.{i}");
if !profile_name_ok(&rule.name) {
v.error(format!("{path}.name"), "a list name takes lowercase letters, digits and '-'");
} else if !names.insert(rule.name.as_str()) {
v.error(format!("{path}.name"), format!("list '{}' is defined twice", rule.name));
}
// Its lists are list-<name>.txt and ipset-<name>.txt beside the release's own.
const RELEASE_LISTS: [&str; 9] = ["general", "general-user", "google", "exclude", "exclude-user", "all", "instagram", "soundcloud", "twitter"];
if RELEASE_LISTS.contains(&rule.name.as_str()) {
v.error(format!("{path}.name"), format!("'{}' is the name of one of zapret's own lists", rule.name));
}
if rule.default_domains.iter().any(|d| matches!(d, ZapretDefaultDomains::Instagram | ZapretDefaultDomains::Soundcloud | ZapretDefaultDomains::Twitter)) {
v.error(format!("{path}.defaultDomains"), "Flowseal's Windows release has no instagram, soundcloud or twitter list");
}
if matches!(rule.preset, Some(ZapretPreset::Instagram | ZapretPreset::Soundcloud | ZapretPreset::Twitter)) {
v.error(format!("{path}.preset"), "Flowseal's Windows release has no instagram, soundcloud or twitter profiles");
}
if !rule.domains.is_empty() && rule.preset.is_none() && rule.default_domains.is_empty() && rule.nfqws_args.is_empty() {
v.error(&path, "a list with domains needs preset, defaultDomains or nfqwsArgs, for its strategy");
}
if rule.config_name.is_some() && !rule.nfqws_args.is_empty() {
v.error(&path, "configName cannot be used with nfqwsArgs");
}
if rule.preset.is_none() && rule.config_name.is_none() && rule.nfqws_args.is_empty() && rule.default_domains.len() != 1 {
v.error(&path, "without preset, configName or nfqwsArgs, use exactly one of defaultDomains, so its strategy can be inferred");
}
if rule.domains.is_empty() && rule.default_domains.is_empty() && rule.ips.is_empty() && rule.default_ips.is_empty() {
v.warn(&path, format!("list '{}' holds no sites", rule.name));
}
}
}
for (label, list) in [
("zapret.zapret2.domains", &z.zapret2.domains),
("zapret.zapret2.excludeDomains", &z.zapret2.exclude_domains),
("zapret.zapret-discord-youtube.domains", &z.discord_youtube.domains),
("zapret.zapret-discord-youtube.excludeDomains", &z.discord_youtube.exclude_domains),
] {
for d in list.iter().filter(|d| !crate::zapret2::host_entry_ok(d)) {
v.error(label, format!("'{d}' is not a site name: letters, digits, '.', '-', '_', '*', and '^' first for an exact match"));
}
}
for (label, list) in [
("zapret.zapret-discord-youtube.ips", &z.discord_youtube.ips),
("zapret.zapret-discord-youtube.excludeIps", &z.discord_youtube.exclude_ips),
("zapret.cidrExemption.cidrs", &z.cidr_exemption.cidrs),
] {
for ip in list.iter().filter(|ip| ip.parse::<ipnet::IpNet>().is_err() && ip.parse::<std::net::IpAddr>().is_err()) {
v.error(label, format!("'{ip}' is not an address or CIDR"));
}
}
if z.engine == ZapretEngine::Zapret2 {
let ah = &z.zapret2.auto_hostlist;
for (label, value) in [("failThreshold", ah.fail_threshold), ("failTime", ah.fail_time), ("retransThreshold", ah.retrans_threshold), ("udpOut", ah.udp_out)] {
if value == 0 {
v.error(format!("zapret.zapret2.autoHostlist.{label}"), "it must be greater than zero");
}
}
if z.zapret2.proxy_fallback && !derived::has_available_outbounds(cfg) {
v.warn("zapret.zapret2.proxyFallback", "proxyFallback needs an outbound to fall back to");
}
if z.zapret2.cutoff.enable && z.zapret2.cutoff.proxy_fallback && !derived::sing_box_enabled(cfg) {
v.warn("zapret.zapret2.cutoff.proxyFallback", "the cutoff fallback needs the sing-box backend");
}
}
if z.cidr_exemption.enable && z.cidr_exemption.cidrs.is_empty() {
v.warn("zapret.cidrExemption", "the exemption is on but lists no networks");
}
}
fn per_app(cfg: &Config, v: &mut Issues) {
let pa = &cfg.per_app_routing;
if !pa.enable {
return;
}
v.requires(true, cfg.proxy.enable, "perAppRouting.enable", "perAppRouting", "proxy.enable = true");
if !cfg.proxy.backend.runs_sing_box() {
v.error("perAppRouting.enable", "per-app routing needs the sing-box or hybrid backend");
}
let mut names = BTreeSet::new();
for (i, prof) in pa.profiles.iter().enumerate() {
let path = format!("perAppRouting.profiles.{i}");
if !profile_name_ok(&prof.name) {
v.error(format!("{path}.name"), "a profile name takes lowercase letters, digits and '-'");
} else if !names.insert(prof.name.as_str()) {
v.error(format!("{path}.name"), format!("profile '{}' is defined twice", prof.name));
}
if !derived::is_known_target(cfg, &prof.outbound) {
v.error(format!("{path}.outbound"), format!("'{}' is not an outbound, a group, or proxy, direct or block", prof.outbound));
}
}
if pa.profiles.len() > 200 {
v.error("perAppRouting.profiles", "at most 200 profiles");
}
}
fn inbounds(cfg: &Config, v: &mut Issues) {
let ib = &cfg.inbounds;
if !ib.enable {
return;
}
let via_ok = |via: &str| {
matches!(via, "proxy" | "direct" | "block") || cfg.proxy.outbounds.iter().any(|o| o.tag == via)
};
if !via_ok(&ib.routing.via) {
v.error("inbounds.routing.via", format!("'{}' is not proxy, direct, block or a proxy.outbounds tag", ib.routing.via));
}
v.requires(ib.routing.via == "proxy", cfg.proxy.enable, "inbounds.routing.via", "inbounds.routing.via = \"proxy\"", "proxy.enable = true");
v.requires(ib.subscriptions.enable, ib.share_links, "inbounds.subscriptions.enable", "inbounds.subscriptions", "inbounds.shareLinks = true");
let mut ports: BTreeMap<(u16, bool), &str> = BTreeMap::new();
for (tag, l) in &ib.listeners {
let path = format!("inbounds.listeners.{tag}");
if !path_name_ok(tag) {
v.error(&path, format!("listener tag '{tag}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
let sources = [l.kind.is_some(), l.xray_json.is_some(), l.json_file.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("listener '{tag}' needs exactly one of type, xrayJson and jsonFile"));
}
for user in &l.users {
if !ib.users.contains_key(user) {
v.error(format!("{path}.users"), format!("listener '{tag}' names user '{user}', which inbounds.users does not define"));
}
}
if let Some(via) = &l.via
&& !via_ok(via) {
v.error(format!("{path}.via"), format!("'{via}' is not proxy, direct, block or a proxy.outbounds tag"));
}
if l.tls.enable && l.reality.enable {
v.error(&path, "tls cannot be used with reality");
}
use crate::config::InboundType as T;
let udp = matches!(l.kind, Some(T::Hysteria2) | Some(T::Amneziawg));
if let Some(other) = ports.insert((l.port, udp), tag) {
v.error(format!("{path}.port"), format!("listeners '{other}' and '{tag}' share port {}", l.port));
}
match l.kind {
Some(T::Hysteria2) if !l.tls.enable => {
v.error(format!("{path}.tls"), "hysteria2 needs tls");
}
Some(T::Trojan) if !l.tls.enable && !l.reality.enable => {
v.error(format!("{path}.tls"), "trojan needs tls or reality");
}
_ => {}
}
if l.reality.enable {
if l.reality.server_names.is_empty() {
v.error(format!("{path}.reality.serverNames"), "REALITY needs at least one server name");
}
if l.reality.private_key.is_some() == l.reality.private_key_file.is_some() {
v.error(format!("{path}.reality"), "set exactly one of privateKey and privateKeyFile");
}
if ib.share_links && l.reality.public_key.is_none() {
v.warn(format!("{path}.reality.publicKey"), "share links need the public key");
}
}
if l.tls.enable && (l.tls.certificate_file.is_none() || l.tls.key_file.is_none()) {
v.error(format!("{path}.tls"), "TLS needs certificateFile and keyFile");
}
if l.flow.is_some() && l.transport.kind != "raw" {
v.error(format!("{path}.flow"), "the vision flow only works on the raw transport");
}
}
let mut orders = BTreeMap::new();
for (name, user) in &ib.users {
if !path_name_ok(name) {
v.error(format!("inbounds.users.{name}"), format!("user name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
if let Some(order) = user.order
&& let Some(other) = orders.insert(order, name) {
v.error(format!("inbounds.users.{name}.order"), format!("users '{other}' and '{name}' share order {order}"));
}
if user.uuid.is_some() && user.uuid_file.is_some() {
v.error(format!("inbounds.users.{name}"), "set uuid or uuidFile, not both");
}
if user.password.is_some() && user.password_file.is_some() {
v.error(format!("inbounds.users.{name}"), "set password or passwordFile, not both");
}
}
if ib.manager.enable && (ib.manager.interval < 5 || ib.manager.interval > 3600) {
v.error("inbounds.manager.interval", "between 5 and 3600 seconds");
}
if ib.manager.api.listen.is_some() && ib.manager.api.tokens_file.is_none() {
v.error("inbounds.manager.api.listen", "a TCP API needs tokensFile");
}
}
/// Loopback listeners must not collide: whichever starts second would die.
fn ports(cfg: &Config, v: &mut Issues) {
let mut taken: BTreeMap<u16, String> = BTreeMap::new();
let mut claim = |port: u16, who: String, v: &mut Issues| {
if let Some(other) = taken.get(&port) {
v.error(who.clone(), format!("port {port} is taken by {other} too"));
} else {
taken.insert(port, who);
}
};
let p = &cfg.proxy;
if p.enable {
claim(p.listener.port, "proxy.listener.port".into(), v);
if p.backend.runs_sing_box() {
claim(p.sing_box.clash_api_port, "proxy.singBox.clashApiPort".into(), v);
}
if p.backend.runs_sing_box() {
claim(p.sing_box.test_port, "proxy.singBox.testPort".into(), v);
}
}
if cfg.tor.enable {
claim(cfg.tor.socks_port, "tor.socksPort".into(), v);
claim(cfg.tor.control_port, "tor.controlPort".into(), v);
}
if cfg.ssh_proxy.enable {
claim(cfg.ssh_proxy.listener.port, "sshProxy.listener.port".into(), v);
}
if cfg.tg_ws_proxy.enable {
claim(cfg.tg_ws_proxy.listener.port, "tgWsProxy.listener.port".into(), v);
}
if cfg.per_app_routing.enable {
for (i, prof) in cfg.per_app_routing.profiles.iter().enumerate() {
claim(
cfg.per_app_routing.listener_base_port.saturating_add(i as u16),
format!("perAppRouting.profiles.{i} ({})", prof.name),
v,
);
}
}
for ob in derived::extra_outbounds(cfg) {
use derived::ExtraKind as K;
match ob.kind {
K::Awg { port, kind: crate::config::AwgOutboundKind::Userspace, .. } => {
claim(port, format!("AmneziaWG outbound '{}'", ob.tag), v)
}
K::WlJoiner { port, .. } => claim(port, format!("whitelist-bypass joiner '{}'", ob.tag), v),
K::Warp { device } if device.kind == crate::config::WarpOutboundKind::Userspace => {
claim(device.port, format!("WARP device '{}'", device.tag), v)
}
_ => {}
}
}
if p.enable && p.auto_proxy.enable {
let base = p.auto_proxy.probe_base_port;
for i in 0..p.auto_proxy.max_exits.min(64) as u16 {
claim(base.saturating_add(i), format!("proxy.autoProxy.probeBasePort (+{i})"), v);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Group, Outbound, RoutingRule};
#[test]
fn names_are_plain_file_names_and_never_devices() {
for ok in ["laptop", "wl", "a.b_c-1", "COM", "console", "lpt10", "nul-ish"] {
assert!(path_name_ok(ok), "{ok}");
}
for bad in ["", ".hidden", "a/b", r"a\b", "C:x", "..", "CON", "con.txt", "Nul", "PRN", "aux.json", "COM1", "lpt9.link"] {
assert!(!path_name_ok(bad), "{bad}");
}
}
#[test]
fn whitelist_bypass_names_are_checked_while_it_is_off() {
let mut cfg = Config::default();
cfg.whitelist_bypass.creators.insert(r"C:\Windows\x".into(), serde_json::from_value(serde_json::json!({ "platform": "wbstream" })).unwrap());
assert!(errors(&cfg).iter().any(|e| e.starts_with("whitelistBypass.")), "{:?}", errors(&cfg));
}
fn errors(cfg: &Config) -> Vec<String> {
validate(cfg)
.into_iter()
.filter(|i| i.severity == Severity::Error)
.map(|i| format!("{}: {}", i.path, i.message))
.collect()
}
fn outbound(tag: &str) -> Outbound {
Outbound { tag: tag.into(), url: Some("hy2://pw@example.com:443".into()), ..Default::default() }
}
#[test]
fn the_default_config_is_valid() {
assert_eq!(errors(&Config::default()), Vec::<String>::new());
}
#[test]
fn listen_addresses_are_ip_addresses() {
let mut cfg = Config::default();
assert!(!errors(&cfg).iter().any(|e| e.contains("listener.address")));
cfg.proxy.listener.address = "127.0.0.1\nClientTransportPlugin x exec calc.exe".into();
cfg.tg_ws_proxy.listener.address = "::".into();
let errs = errors(&cfg);
assert!(errs.iter().any(|e| e.starts_with("proxy.listener.address:")), "{errs:?}");
assert!(!errs.iter().any(|e| e.starts_with("tgWsProxy.listener.address:")), "{errs:?}");
}
#[test]
fn ssh_host_and_user_cannot_be_options() {
let mut cfg = Config::default();
cfg.ssh_proxy.enable = true;
cfg.ssh_proxy.strict_host_key_checking = crate::config::StrictHostKeyChecking::No;
for (host, user, bad) in [
("vps.example", "me", None),
("192.0.2.7", "me.you", None),
("2001:db8::1", "me", None),
("-oProxyCommand=calc.exe", "me", Some("sshProxy.server.host")),
("vps.example", "-oProxyCommand=calc.exe", Some("sshProxy.server.user")),
("vps.example x", "me", Some("sshProxy.server.host")),
("vps.example", "me\nx", Some("sshProxy.server.user")),
] {
cfg.ssh_proxy.server.host = Some(host.into());
cfg.ssh_proxy.server.user = Some(user.into());
let errs = errors(&cfg);
match bad {
None => assert!(!errs.iter().any(|e| e.starts_with("sshProxy.server")), "{host} {user}: {errs:?}"),
Some(p) => assert!(errs.iter().any(|e| e.starts_with(&format!("{p}:"))), "{host} {user}: {errs:?}"),
}
}
}
#[test]
fn what_is_not_ported_is_said() {
let quiet: Vec<String> = validate(&Config::default()).into_iter().filter(|i| i.message.contains("not on Windows yet")).map(|i| i.path).collect();
assert!(quiet.is_empty(), "{quiet:?}");
let mut cfg = Config::default();
cfg.kill_switch.enable = true;
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", "proxy.tun.enable"] {
assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}");
}
}
#[test]
fn outbound_tags_are_unique_and_not_builtin() {
let mut cfg = Config::default();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![outbound("de"), outbound("de"), outbound("direct")];
let errs = errors(&cfg);
assert!(errs.iter().any(|e| e.contains("'de' is used twice")), "{errs:?}");
assert!(errs.iter().any(|e| e.contains("'direct' is a builtin")), "{errs:?}");
}
#[test]
fn an_outbound_needs_exactly_one_source() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![Outbound { tag: "x".into(), ..Default::default() }];
assert!(errors(&cfg)[0].contains("needs exactly one"));
}
#[test]
fn rule_targets_must_exist() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![outbound("de")];
cfg.proxy.groups.insert("eu".into(), Group { outbounds: vec!["de".into()], ..Default::default() });
let rule = |target: &str| RoutingRule {
outbound: target.into(),
matches: crate::config::RouteMatch { domains: vec!["example.com".into()], ..Default::default() },
..Default::default()
};
cfg.proxy.routing.rules = vec![rule("de"), rule("eu"), rule("direct"), rule("nowhere")];
let errs = errors(&cfg);
assert_eq!(errs.len(), 1, "{errs:?}");
assert!(errs[0].contains("'nowhere'"));
}
#[test]
fn colliding_ports_are_refused() {
let mut cfg = Config::default();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![outbound("de")];
cfg.tor.enable = true;
cfg.tor.as_outbound = true;
cfg.tor.socks_port = 1080;
assert!(errors(&cfg).iter().any(|e| e.contains("port 1080")));
}
#[test]
fn names_that_become_paths_are_checked() {
let mut cfg = Config::default();
cfg.amnezia_wg.enable = true;
cfg.amnezia_wg.profiles.insert(
"..\\evil".into(),
crate::config::AwgProfile { config: Some("[Interface]".into()), ..Default::default() },
);
assert!(errors(&cfg).iter().any(|e| e.contains("profile name")), "{:?}", errors(&cfg));
}
#[test]
fn groups_need_sing_box() {
let mut cfg = Config::default();
cfg.proxy.backend = Backend::Xray;
cfg.proxy.groups.insert("g".into(), Group::default());
assert!(errors(&cfg).iter().any(|e| e.contains("groups need")));
}
}