Wind ACL Intermediate Representation (acl-ir)¶
- Document: Wind ACL Intermediate Representation (
acl-ir) - Category: Informational
- Chinese edition: 简体中文
Status of This Memo¶
This document specifies the internal ACL intermediate representation used by wind-acl in the Wind workspace. It is not an Internet Standard and does not define a wire protocol. The normative implementation resides in wind-acl, wind-rule, wind-geodata, and wind-core.
Abstract¶
acl-ir is the internal routing program representation of wind-acl. It lowers apernet (Hysteria 2) ACL entries, externally lowered wind_rule::Rule values (such as tuic-server's legacy ACL dialect), and Clash/Mihomo rule lines into a single Ruleset, preserving first-match-wins semantics and default-outbound fallback while enabling Verus-verified order-preserving folding into sets and port verdict maps.
1. Introduction¶
An ACL router answers one question: given a connection context, which outbound should handle it, or should it be rejected? Flat Vec<wind_rule::Rule> scanning is simple and compatible with Clash/Mihomo syntax, but hard to optimize and lacks a structured target for multiple surface dialects.
acl-ir provides that structured target with three goals:
- Preserve exact first-match-wins routing decisions for all rules supported by the flat engine;
- Expose typed structure that permits verified folding into
NamedSets andVerdictMaps; - Provide explicit extension points for multi-chain control flow, non-terminal statements, and additional dialects without requiring v1 to implement everything at once.
While modeled on nftables concepts (sets, maps, chains, statements, verdicts), acl-ir runs inside Wind over wind_rule::MatchContext and retains L7 proxy concepts such as domains, inbound metadata, and GeoIP/GeoSite lookups.
2. Conventions and Terminology¶
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.
- Match: A boolean expression evaluated against a
MatchContext. - Predicate: An opaque
Arc<wind_rule::Rule>embedded in IR. - Statement: A non-terminal action attached to a matching rule.
- Verdict: A routing or control-flow outcome (
Forward,Reject,Drop,Return,Jump,Goto, orMap). - Rule: A
Match, zero or moreStatements, and oneVerdict. - Chain: An ordered list of rules; the entry chain also carries a fallback
policy. - Set: An unordered lookup table queried by
Match::InSet. - Verdict map: An unordered lookup table mapping key ranges to verdicts.
- Degenerate embedding: The single-chain IR equivalent to the legacy flat rule engine.
- First-match-wins: The first rule in declaration order whose match evaluates to true determines the route.
Rust snippets are illustrative and mirror public types in crates/wind-acl/src/model.rs.
3. Compilation Pipeline¶
AclEngineBuilder constructs the engine in the following fixed order:
- Parse Hysteria 2 (apernet) ACL entries via
syntax::apernetand lower them withapernet::acl_to_rules. - Collect raw
wind_rule::Rulevalues passed viaAclEngineBuilder::rules(for example,tuic-server's legacy rules lowered viatuic_server::legacy::acl_to_rules). - Parse Clash/Mihomo rule lines via
syntax::metacubex. - Concatenate all rules in the normative order
apernet→ rawrules→clash. - Construct the degenerate
RulesetviaRuleset::from_rules. - Run the Verus-verified order-preserving optimizer
compile. - At route time, enforce any configured
GuardConfigbefore populatingMatchContextviaFlowContext::apply_to_match_contextand evaluating theRuleset.
The apernet → raw rules → clash precedence is normative for AclEngine: when multiple sources match a flow, the earlier source wins.
AclEngine automatically populates MatchContext with destination domain/IP, destination port, source IP/port, network protocol, inbound port, inbound name, inbound type, and UTF-8 IN-USER, and binds geoip_lookup and geosite_lookup when AclEngineBuilder::geodata(Arc<GeoData>) is configured. IP-ASN/SRC-IP-ASN callbacks and process metadata (PROCESS-*, UID, DSCP) are not populated automatically unless a caller evaluates a Ruleset with a fuller MatchContext.
4. Data Model¶
4.1. Match Expressions¶
enum Side {
Dst,
Src,
}
enum Match {
All(Vec<Match>),
Any(Vec<Match>),
Not(Box<Match>),
Always,
Ip { side: Side, net: IpNet },
Port { side: Side, range: RangeInclusive<u16> },
Proto (NetworkType),
Domain (DomainTest),
InSet { side: Side, set: usize },
Predicate(Arc<wind_rule::Rule>),
}
enum DomainTest {
Exact(String),
Suffix(String),
Keyword(String),
}
By standard boolean convention, All([]) is true and Any([]) is false, though lowering SHOULD avoid emitting empty combinators. Always represents MATCH.
DomainTest::Suffix matches both the suffix apex and subdomains on ASCII dot boundaries. Exact, Suffix, and Keyword comparisons are ASCII case-insensitive.
DOMAIN, DOMAIN-SUFFIX, and DOMAIN-KEYWORD values MUST be non-empty. An empty keyword degenerates into a universal match and an empty suffix virtually never matches, silently defeating subsequent rules including REJECT. wind_rule::Rule::parse therefore rejects empty values at parse time.
Predicate is the compatibility escape hatch and MUST be evaluated by delegating to Rule::matches(ctx), preserving wind_rule semantics verbatim (including RULE-SET evaluating to false and SUB-RULE retaining legacy nested-rule semantics).
4.2. Sets¶
struct NamedSet {
data: SetData,
}
enum SetData {
Domains(DomainSet),
Ips(Vec<IpNet>),
Ports(Vec<RangeInclusive<u16>>),
}
struct DomainSet {
exact: Vec<String>,
suffix: Vec<String>,
keyword: Vec<String>,
}
Sets live in Ruleset::sets and are referenced by index. Membership queries read fields by set kind:
Domainsreadsctx.domain(ignoringside);Ipsreadsctx.dst_iporctx.src_ipaccording toside;Portsreadsctx.dst_portorctx.src_portaccording toside.
4.3. Statements and Verdicts¶
enum Statement {
Counter,
Log(String),
Mark(u32),
Dnat(String),
}
enum Verdict {
Forward(String),
Reject(String),
Drop,
Return,
Jump(String),
Goto(String),
Map(usize),
}
Statements are non-terminal actions. Implementations exposing statement side effects MUST execute stmts in order before applying verdict. Because RouteAction currently observes only routing outcomes, the built-in evaluator ignores statement side effects and degenerate embedding emits no statements.
Forward selects a named outbound; Reject denies the connection with a reason string. Drop exists in the IR and currently maps to a rejection with reason "dropped" in wind_core::RouteAction.
4.4. Verdict Maps, Chains, and Rulesets¶
enum MapField {
Port,
}
struct VerdictMap {
side: Side,
field: MapField,
entries: Vec<(RangeInclusive<u16>, Verdict)>,
default: Option<Verdict>,
}
struct IrRule {
matches: Match,
stmts: Vec<Statement>,
verdict: Verdict,
}
struct Chain {
name: String,
policy: Verdict,
rules: Vec<IrRule>,
}
struct Ruleset {
sets: Vec<NamedSet>,
maps: Vec<VerdictMap>,
chains: Vec<Chain>,
entry: usize,
}
In v1, VerdictMap keys are limited to source or destination port ranges, and the optimizer only constructs maps with pairwise-disjoint ranges. entry indexes the starting chain in chains.
5. Evaluation Semantics¶
Evaluation begins at Ruleset::entry and scans rules top-to-bottom:
- Evaluate
rule.matchesagainstMatchContext. - If false, proceed to the next rule.
- If true, process
rule.stmts, then applyrule.verdict.
Terminal verdicts:
Forward(outbound)terminates withRouteAction::Forward(outbound).Reject(reason)terminates withRouteAction::Reject(reason).Dropterminates with a rejection ("dropped") in the current public API.
Control-flow verdicts:
Returnyields fallthrough to the caller.Jump(name)evaluates the named chain; a terminal verdict ends evaluation, whereas fallthrough resumes at the rule followingJump.Goto(name)evaluates the named chain without establishing a return point; in the current evaluator, a non-terminal outcome still falls through at the call site, so configurations SHOULD terminateGototarget chains explicitly.Map(index)looks up the current key inRuleset::maps[index], applying the matched verdict,defaulton miss if present, or falling through otherwise.
If the entry chain falls through, Ruleset::route applies the entry chain's policy. Non-entry chain policies are reserved for future multi-base-chain semantics; v1 sub-chains SHOULD end with an explicit terminal fallback rule.
Implementations MUST prevent infinite recursion and map cycles: the evaluator enforces a maximum chain depth of 64 (exceeding it yields fallthrough) and bounds map traversal by maps.len(), rejecting invalid indices and cycles.
6. Degenerate Embedding¶
Ruleset::from_rules(rules, default_outbound) embeds flat wind_rule::Rule values into a single-chain Ruleset:
Ruleset {
sets: vec![],
maps: vec![],
entry: 0,
chains: vec![Chain {
name: "main".to_string(),
policy: Verdict::Forward(default_outbound),
rules: rules.into_iter().map(rule_to_ir).collect(),
}],
}
This embedding is normative: both before and after optimization, routing decisions for any MatchContext MUST match the flat first-match-wins engine.
The following wind_rule::RuleType variants lower to typed IR leaves:
wind_rule::RuleType |
IR Match |
|---|---|
Domain |
Domain(Exact) |
DomainSuffix |
Domain(Suffix) |
DomainKeyword |
Domain(Keyword) |
IpCidr, IpSuffix |
Ip { side: Dst } |
IpCidr6 |
Ip { side: Dst } |
SrcIpCidr, SrcIpSuffix |
Ip { side: Src } |
DstPort, DstPortRange |
Port { side: Dst } |
SrcPort, SrcPortRange |
Port { side: Src } |
Network |
Proto |
Match |
Always |
All other rule types embed as Match::Predicate(Arc<Rule>).
Target strings map to verdicts as follows:
reject,block, anddeny(case-insensitive) map toVerdict::Rejectwith a normalized reason string;- All other targets map to
Verdict::Forward(target)preserving exact spelling.
7. Surface Dialect Lowering¶
7.1. Clash / Mihomo¶
Parsed by wind_rule::Rule::parse (skipping blank lines and # comments), covering domain, destination/source IP, port, inbound metadata, process/UID, protocol/DSCP, and composite rules. Leaves in Section 6 become typed IR nodes; all others preserve semantics via Predicate.
7.2. tuic-server Legacy ACL¶
tuic-server's whitespace-delimited legacy dialect (distinct from Hysteria 2's function-call syntax) is parsed and lowered in tuic-server's legacy module:
Address lowering:
| Legacy address | Lowered rule type |
|---|---|
omitted or * |
MATCH |
| IPv4 literal | IP-CIDR host route /32 |
| IPv6 literal | IP-CIDR host route /128 |
| CIDR | IP-CIDR |
| exact domain | DOMAIN |
*.example.com / suffix:example.com |
DOMAIN-SUFFIX,example.com |
localhost |
127.0.0.0/8 and ::1/128 |
private |
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8, 169.254.0.0/16, ::1/128, fc00::/7, fe80::/10 |
Port lowering: omitted adds no port condition; 80 → DST-PORT,80; 1000-2000 → DST-PORT,1000-2000; tcp/443 or udp/53 → AND(NETWORK, DST-PORT). When both address and port conditions are present, lowering emits AND(address, port) for each pair.
Outbound lowering: allow and default normalize to default; all others pass through to Section 6 mapping. hijack is parsed and retained but not executed (Statement::Dnat is its intended IR target).
7.3. apernet ACL (Hysteria 2)¶
Hysteria 2's function-call dialect outbound(address[, proto/port[, hijack]]) is parsed by wind-acl's syntax::apernet module and dispatched in order (after lowercasing and stripping trailing .):
| apernet address | Lowered rule type |
|---|---|
all or * |
MATCH |
| IPv4 / IPv6 literal | IP-CIDR /32 or /128 |
| CIDR (v4/v6) | IP-CIDR |
geoip:<cc> |
GEOIP,<cc> |
geosite:<name>[@attr...] |
GEOSITE,<name> (attributes dropped with warning) |
suffix:<domain> |
DOMAIN-SUFFIX,<domain> |
domain containing * (e.g. *.example.com) |
DOMAIN-WILDCARD,<pattern> |
| exact domain | DOMAIN,<domain> |
suffix: matches apex and subdomains; *.example.com matches subdomains only, not the bare apex. Port lowering (<proto> ∈ {tcp, udp, *}, <port> ∈ {*, single, lo-hi}): omitted/*/*/* adds no constraint; tcp/tcp/* (and udp) → NETWORK; */<port> → DST-PORT; tcp/<port> (and udp) → AND(NETWORK, DST-PORT); start port 0 is an any-port sentinel.
Outbound names pass verbatim to Section 6 mapping. Both @attr filters on geosite: and the optional third hijack parameter are parsed but dropped with a warning during v1 lowering. Degenerate inputs (empty address, whitespace-only arguments, literal ) inside arguments) are rejected strictly; ? inside * patterns acts as a single-character wildcard, matching performs no IDNA ToUnicode, and case folding is ASCII-only.
8. Order-Preserving Optimization¶
Ordered chains are the source of truth. Because sets and verdict maps are unordered, the optimizer MAY introduce them only when first-match-wins decisions and observable callback order are provably unchanged. Both passes are formally verified in Verus and currently run on the entry chain.
8.1. Pass 1: Adjacent Same-Verdict Bucketing¶
Starting at the current rule, scan the longest contiguous run where every rule satisfies:
- Its match is a side-effect-free bucketable typed leaf (
Match::Domain,Match::Ip, orMatch::Portonly); (stmts, verdict)is identical across the run andverdictis a terminal verdict (Forward,Reject,Drop, orReturn).
The run is replaced by a single rule whose match groups:
- Domain exact/suffix/keyword leaves into one
SetData::Domainsset; - Destination IP and source IP leaves into separate
SetData::Ipssets; - Destination port and source port leaves into separate
SetData::Portssets; - Producing a single
Match::InSetorMatch::Any(alts).
Proto, Predicate, Always, composite expressions, and control-flow verdicts (Jump, Goto, Map) are excluded from bucketing so short-circuit order and legacy callback effects remain unchanged.
8.2. Pass 2: Port Verdict Maps¶
If Pass 1 did not consume the current position, scan the longest contiguous run of single Match::Port leaves on the same Side with empty stmts.
The run folds into a VerdictMap if and only if all closed port ranges are pairwise disjoint. Overlapping ranges MUST remain ordered; for example:
Port 1500 MUST still route to proxy.
8.3. No Other Reordering¶
v1 performs no non-adjacent hoisting, IP/domain verdict maps, or cross-chain optimization. Any future pass MUST obey the same order-invariance guarantee.
9. Scope and Extensions¶
RULE-SETremains aPredicateevaluating tofalse;SUB-RULEretains legacy nested-rule semantics.GEOIP,SRC-GEOIP, andGEOSITEare wired automatically viaAclEngineBuilder::geodatabacked bywind-geodata(omitting geodata emits a build-time warning and rules never match).IP-ASN/SRC-IP-ASNhave no built-in lookup provider yet (build-time warning; never match).- Process metadata (
PROCESS-*,UID,DSCP) requires caller-populatedMatchContextfields. Statement::DnatandVerdict::Dropare modeled in the IR for future redirect and distinct-drop support.
10. Security Considerations¶
- Fail-closed optimizer: Any transformation whose order-invariance cannot be proved MUST leave rule order intact so blocks cannot be silently bypassed.
- Missing context: Rules reading absent
MatchContextfields or callbacks evaluate to false; deployments relying on GeoIP/GeoSite, ASN, or process identity MUST supply the required data sources. - Loopback and private guards (
GuardConfig): Execute before IR evaluation and require aResolverat build time when enabled.drop_loopbackcanonicalizes IPv4-mapped IPv6 addresses and rejects127.0.0.0/8,::1, and unspecified0.0.0.0/::.drop_privateuses Verus-verifiedwind_core::is_private_ipcovering RFC 1918, link-local, CGNAT, and IPv6 unique-local ranges.AclEnginepins the validated resolved IP viaroute_with_targetto defeat DNS rebinding, and re-validates every subsequent UDP datagram viaprepare_udp_target. - Redirect behavior:
hijackis parsed but not executed; futureDnatexecution SHOULD be explicitly opt-in and logged. - Cycle limits: Chain recursion caps at depth 64, and map lookups are bounded by table length.
- Reserved reject keywords:
reject,block, anddeny(case-insensitive) always produce a reject verdict.
11. References¶
- [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997.
- [RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words", BCP 14, RFC 8174, May 2017.
crates/wind-acl/src/{model,embed,eval,optimize,bucket,port_map,matches,routing,route_equivalence,engine}.rsandsyntax/{apernet,metacubex}.rscrates/wind-rule/src/lib.rscrates/wind-geodata/src/lib.rs- MetaCubeX / Mihomo rule syntax and apernet / Hysteria 2 ACL syntax
tuic-servercratelegacymodule- nftables concepts: set, map, chain, statement, and verdict