Files
proxy-suite-flake/windows/crates/ps-core/src/render/routing.rs
T
faumarayandClaude Opus 5.5 918cdc9a75 windows: rules and per-app profiles fail closed
A rule, an outbound's own routing or a per-app profile whose outbound is
not running blocks what it matches instead of letting it fall through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:58:28 +03:00

418 lines
16 KiB
Rust

//! sing-box's route and DNS rules: upstream's `rules/sing-box.nix`, composed by section
//! and priority as `routing-compose.jq` does, with the route mode applied.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use super::{Input, RouteMode};
use crate::config::{Config, RouteDefault, RouteMatch, RuleSetFormat};
use crate::derived;
/// Loopback, as a client of the local proxy could ask for it.
pub(super) const LOOPBACK: [&str; 4] = ["127.0.0.0/8", "::1/128", "0.0.0.0/32", "::/128"];
/// A rule set the service should keep downloaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WantedRuleSet {
/// The tag the config names it by.
pub tag: String,
pub url: String,
pub format: RuleSetFormat,
/// For a `ruleset-<name>-dns` copy: the rule set whose domain rules it holds. Its URL
/// is the original's.
pub dns_copy_of: Option<String>,
/// Fetch through the proxy rather than directly.
pub via_proxy: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Category {
Proxy,
Direct,
Block,
/// Private addresses and the Telegram relay's: direct, but kept in every mode.
Safety,
}
fn category(target: &str) -> Category {
match target {
"direct" => Category::Direct,
"block" => Category::Block,
_ => Category::Proxy,
}
}
struct Section {
priority: i64,
category: Category,
rules: Vec<Value>,
dns: Vec<Value>,
}
fn geosite(name: &str) -> String {
format!("geosite-{name}")
}
fn geoip(name: &str) -> String {
format!("geoip-{name}")
}
fn remote(name: &str) -> String {
format!("ruleset-{name}")
}
fn remote_dns(name: &str) -> String {
format!("ruleset-{name}-dns")
}
/// A rule sending what it matches to `outbound` ("block" is the block outbound, which groups
/// with nothing to pick fall back to as well).
fn target(rule: Value, outbound: &str) -> Value {
let mut rule = rule;
rule["outbound"] = outbound.into();
rule
}
/// One rule per kind of match, as upstream's `mkCustomRuleEntries`: a rule matches any of
/// them, not all.
fn match_rules(outbound: &str, m: &RouteMatch) -> Vec<Value> {
let mut rules = Vec::new();
if !m.domains.is_empty() {
rules.push(target(json!({ "domain_suffix": m.domains }), outbound));
}
if !m.ips.is_empty() {
rules.push(target(json!({ "ip_cidr": m.ips }), outbound));
}
if !m.geosites.is_empty() {
rules.push(target(json!({ "rule_set": m.geosites.iter().map(|s| geosite(s)).collect::<Vec<_>>() }), outbound));
}
if !m.geoips.is_empty() {
rules.push(target(json!({ "rule_set": m.geoips.iter().map(|s| geoip(s)).collect::<Vec<_>>() }), outbound));
}
if !m.rule_sets.is_empty() {
rules.push(target(json!({ "rule_set": m.rule_sets.iter().map(|s| remote(s)).collect::<Vec<_>>() }), outbound));
}
rules
}
/// The DNS mirror of a match: a name that goes through the proxy is looked up through it.
fn dns_rules(server: &str, domains: &[String], geosites: &[String], rule_sets: &[String]) -> Vec<Value> {
let mut rules = Vec::new();
if !domains.is_empty() {
rules.push(json!({ "domain_suffix": domains, "server": server }));
}
let tags: Vec<String> = geosites.iter().map(|s| geosite(s)).chain(rule_sets.iter().map(|s| remote_dns(s))).collect();
if !tags.is_empty() {
rules.push(json!({ "rule_set": tags, "server": server }));
}
rules
}
fn dns_server_for(c: Category) -> &'static str {
if c == Category::Direct { "local" } else { "remote" }
}
/// The direct lists: the configuration's, zapret's (`zapret.directSync`) and the Russian
/// ones (`routing.directRu`).
pub(super) fn direct_match(input: &Input) -> RouteMatch {
let r = &input.cfg.proxy.routing;
let z = &input.env.zapret_direct;
let uniq = |a: &[String], b: &[String], extra: Option<&str>| {
let mut out: Vec<String> = Vec::new();
for v in a.iter().chain(b).map(String::as_str).chain(extra) {
if !out.iter().any(|x| x == v) {
out.push(v.to_owned());
}
}
out
};
let ru = r.direct_ru;
RouteMatch {
domains: uniq(&r.direct.domains, &z.domains, None),
ips: uniq(&r.direct.ips, &z.ips, None),
geosites: uniq(&r.direct.geosites, &[], ru.then_some("category-ru")),
geoips: uniq(&r.direct.geoips, &[], ru.then_some("ru")),
rule_sets: r.direct.rule_sets.clone(),
}
}
/// The rules that pick an outbound by program, and the loopback hops' guard: kept in every
/// route mode, ahead of everything that picks by destination, as upstream's pin rules are.
fn always_rules(input: &Input, known: &dyn Fn(&str) -> bool, warnings: &mut Vec<String>) -> Vec<Value> {
let cfg = input.cfg;
let mut rules = Vec::new();
if !input.env.direct_processes.is_empty() {
rules.push(json!({ "process_path": input.env.direct_processes, "outbound": "direct" }));
}
if cfg.per_app_routing.enable {
for prof in &cfg.per_app_routing.profiles {
// An app held to an outbound that is not running is blocked, not let out another way.
let outbound = if derived::BUILTIN_TAGS.contains(&prof.outbound.as_str()) || known(&prof.outbound) {
prof.outbound.as_str()
} else {
warnings.push(format!(
"per-app profile '{}': no outbound or group named '{}' is running; its programs are blocked until it is",
prof.name, prof.outbound
));
"block"
};
let inbound = per_app_inbound(&prof.name);
rules.push(target(json!({ "inbound": [inbound] }), outbound));
if !prof.process_names.is_empty() {
rules.push(target(json!({ "process_name": prof.process_names }), outbound));
}
if !prof.process_paths.is_empty() {
rules.push(target(json!({ "process_path": prof.process_paths }), outbound));
}
}
}
rules
}
pub(super) fn per_app_inbound(name: &str) -> String {
format!("per-app-{name}")
}
/// Every route and DNS rule, in order, and the final outbound and resolver.
pub(super) struct Route {
pub rules: Vec<Value>,
pub dns_rules: Vec<Value>,
pub final_outbound: &'static str,
pub dns_final: &'static str,
pub rule_set: Vec<Value>,
}
pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bool, warnings: &mut Vec<String>) -> Route {
let cfg = input.cfg;
let r = &cfg.proxy.routing;
let direct = direct_match(input);
let mut common = vec![
json!({ "network": ["tcp", "udp"], "port": 53, "action": "hijack-dns" }),
json!({ "action": "sniff" }),
];
let onion = derived::tor_route_onion(cfg) && known(derived::TOR_OUTBOUND_TAG);
if onion {
common.push(json!({ "domain_suffix": ["onion"], "outbound": derived::TOR_OUTBOUND_TAG }));
}
// Nothing reaches this host's loopback through the proxy: the helpers' listeners, the
// Clash API and whatever else listens there would be a client's for the asking, a LAN
// client's too when the listener is exposed. Upstream guards only the hops (its firewall
// keeps the rest from other users); Windows has no such firewall here, so every port. A
// name that resolves to loopback on its own is not caught: keep the listener on loopback.
let _ = hop_ports;
common.push(json!({ "ip_cidr": LOOPBACK, "action": "reject" }));
common.push(json!({ "domain": ["localhost"], "domain_suffix": [".localhost"], "action": "reject" }));
common.extend(always_rules(input, known, warnings));
// The custom rules: each outbound's own routing, then routing.rules, at their priority.
let mut sections = Vec::new();
for ob in &cfg.proxy.outbounds {
if ob.routing.is_empty() {
continue;
}
let outbound = if known(&ob.tag) {
ob.tag.as_str()
} else {
warnings.push(format!("outbound '{}' is not running: what its routing sends to it is blocked until it is", ob.tag));
"block"
};
sections.push(custom_section(100, outbound, &ob.routing, &[], &[]));
}
for (i, rule) in r.rules.iter().enumerate() {
if rule.disabled {
continue;
}
let name = rule.name.clone().unwrap_or_else(|| format!("#{i}"));
// As a group with nothing to pick does: what the rule matches must not fall through to
// another rule, or to direct.
let outbound = if derived::BUILTIN_TAGS.contains(&rule.outbound.as_str()) || known(&rule.outbound) {
rule.outbound.as_str()
} else {
warnings.push(format!(
"routing rule {name}: no outbound or group named '{}' is running; what it matches is blocked until it is",
rule.outbound
));
"block"
};
sections.push(custom_section(
rule.priority.unwrap_or(100),
outbound,
&rule.matches,
&rule.process_names,
&rule.process_paths,
));
}
let proxy_primary = RouteMatch { domains: r.proxy.domains.clone(), ips: r.proxy.ips.clone(), ..Default::default() };
let proxy_geo = RouteMatch {
geosites: r.proxy.geosites.clone(),
geoips: r.proxy.geoips.clone(),
rule_sets: r.proxy.rule_sets.clone(),
..Default::default()
};
sections.push(Section {
priority: 200,
category: Category::Proxy,
rules: match_rules("proxy", &proxy_primary),
dns: dns_rules("remote", &r.proxy.domains, &[], &[]),
});
// Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too).
sections.push(Section { priority: 300, category: Category::Block, rules: match_rules("block", &r.block), dns: Vec::new() });
sections.push(Section {
priority: 400,
category: Category::Direct,
rules: match_rules("direct", &direct),
dns: dns_rules("local", &direct.domains, &direct.geosites, &r.direct.rule_sets),
});
let mut safety = vec![json!({ "ip_is_private": true, "outbound": "direct" })];
let tg = &cfg.tg_ws_proxy;
if tg.enable && tg.bypass_transparent_proxy && !tg.dc_ips.is_empty() {
let ips: BTreeSet<&String> = tg.dc_ips.values().collect();
safety.push(json!({ "ip_cidr": ips, "outbound": "direct" }));
}
sections.push(Section { priority: 400, category: Category::Safety, rules: safety, dns: Vec::new() });
sections.push(Section {
priority: 500,
category: Category::Proxy,
rules: match_rules("proxy", &proxy_geo),
dns: dns_rules("remote", &[], &r.proxy.geosites, &r.proxy.rule_sets),
});
// The mode: the configured default, or proxy-ctl's override.
let mode = input.state.route_mode.unwrap_or(match r.default {
RouteDefault::Proxy => RouteMode::Blacklist,
RouteDefault::Direct => RouteMode::Whitelist,
});
let (final_outbound, dns_final, clear_dns) = match mode {
RouteMode::Blacklist => ("proxy", "remote", false),
RouteMode::Whitelist => ("direct", "local", false),
RouteMode::AllProxy => ("proxy", "remote", true),
RouteMode::AllBypass => ("direct", "local", true),
};
let keep = |c: Category| match mode {
RouteMode::AllProxy => c != Category::Direct,
RouteMode::AllBypass => matches!(c, Category::Block | Category::Safety),
_ => true,
};
// A stable sort: among equals, the list's own order.
sections.sort_by_key(|s| s.priority);
let sections: Vec<Section> = sections.into_iter().filter(|s| keep(s.category)).collect();
let mut rules = common;
rules.extend(sections.iter().flat_map(|s| s.rules.iter().cloned()));
// DNS: the user's rules first (they stay in every mode), then .onion, which no resolver
// may see, then the mirror of the routing.
let mut dns_rules_out: Vec<Value> = cfg.proxy.dns.sing_box.rules.iter().map(|r| Value::Object(r.clone())).collect();
if derived::tor_route_onion(cfg) {
if input.tun && onion {
dns_rules_out.push(json!({
"inbound": ["tun-in"], "domain_suffix": ["onion"], "query_type": ["A", "AAAA"], "server": "fakeip",
}));
}
dns_rules_out.push(json!({ "domain_suffix": ["onion"], "action": "predefined", "rcode": "NXDOMAIN" }));
}
if !clear_dns {
dns_rules_out.extend(sections.iter().flat_map(|s| s.dns.iter().cloned()));
}
if input.tun && cfg.proxy.dns.fake_ip.enable {
dns_rules_out.push(json!({ "inbound": ["tun-in"], "query_type": ["A", "AAAA"], "server": "fakeip" }));
}
Route { rules, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) }
}
fn custom_section(priority: i64, outbound: &str, m: &RouteMatch, names: &[String], paths: &[String]) -> Section {
let c = category(outbound);
let mut rules = match_rules(outbound, m);
if !names.is_empty() {
rules.push(target(json!({ "process_name": names }), outbound));
}
if !paths.is_empty() {
rules.push(target(json!({ "process_path": paths }), outbound));
}
let dns = if c == Category::Block { Vec::new() } else { dns_rules(dns_server_for(c), &m.domains, &m.geosites, &m.rule_sets) };
Section { priority, category: c, rules, dns }
}
/// Every geosite, geoip and declared rule set the routing names.
fn referenced(cfg: &Config) -> (BTreeSet<String>, BTreeSet<String>) {
let r = &cfg.proxy.routing;
let mut sites = BTreeSet::new();
let mut ips = BTreeSet::new();
let mut add = |m: &RouteMatch| {
sites.extend(m.geosites.iter().cloned());
ips.extend(m.geoips.iter().cloned());
};
add(&r.proxy);
add(&r.direct);
add(&r.block);
r.rules.iter().filter(|x| !x.disabled).for_each(|x| add(&x.matches));
cfg.proxy.outbounds.iter().for_each(|o| add(&o.routing));
if r.direct_ru {
sites.insert("category-ru".into());
ips.insert("ru".into());
}
(sites, ips)
}
/// What the service should keep downloaded for this configuration.
pub fn wanted_rule_sets(cfg: &Config) -> Vec<WantedRuleSet> {
if !cfg.proxy.enable || !cfg.proxy.backend.runs_sing_box() {
return Vec::new();
}
let (sites, ips) = referenced(cfg);
let g = &cfg.geodata.sing_box;
let mut out: Vec<WantedRuleSet> = sites
.iter()
.map(|s| WantedRuleSet {
tag: geosite(s),
url: format!("{}/{}.srs", g.geosite.trim_end_matches('/'), geosite(s)),
format: RuleSetFormat::Binary,
dns_copy_of: None,
via_proxy: false,
})
.chain(ips.iter().map(|s| WantedRuleSet {
tag: geoip(s),
url: format!("{}/{}.srs", g.geoip.trim_end_matches('/'), geoip(s)),
format: RuleSetFormat::Binary,
dns_copy_of: None,
via_proxy: false,
}))
.collect();
for (name, rs) in &cfg.proxy.routing.rule_sets {
let via_proxy = rs.detour == crate::config::RuleSetDetour::Proxy;
out.push(WantedRuleSet { tag: remote(name), url: rs.url.clone(), format: rs.effective_format(), dns_copy_of: None, via_proxy });
out.push(WantedRuleSet {
tag: remote_dns(name),
url: rs.url.clone(),
format: RuleSetFormat::Source,
dns_copy_of: Some(remote(name)),
via_proxy,
});
}
out
}
fn rule_set_defs(input: &Input, warnings: &mut Vec<String>) -> Vec<Value> {
wanted_rule_sets(input.cfg)
.into_iter()
.map(|w| match input.env.rule_sets.get(&w.tag) {
Some(file) => json!({
"tag": w.tag,
"type": "local",
"format": if file.format == RuleSetFormat::Binary { "binary" } else { "source" },
"path": file.path,
}),
None => {
if w.dns_copy_of.is_none() {
warnings.push(format!("rule set '{}' is not downloaded yet; it matches nothing until it is", w.tag));
}
json!({ "tag": w.tag, "type": "local", "format": "source", "path": input.env.empty_rule_set })
}
})
.collect()
}