Skip to main content

agentmux_common/
lan_firewall_rules.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Windows Firewall rules that let LAN peers reach AgentMux, and what to change to get from the rules a machine
5//! has to those rules (`docs/specs/SPEC_LAN_FIREWALL_SETUP_2026_10_01.md` 4.1). Pure: it reads and writes nothing.
6//! The elevated helper in the launcher reads the machine's rules into [`Existing`], asks [`plan`] what to do and
7//! applies the answer; running it twice changes nothing the second time.
8
9/// The inbound TCP rule: the fixed block LAN listeners and the viewer take their ports from.
10pub const TCP_RULE_NAME: &str = "AgentMux LAN (TCP)";
11/// The inbound UDP rule: mDNS, the desktop peer discovery and the mobile broadcast responder.
12pub const UDP_RULE_NAME: &str = "AgentMux LAN (UDP)";
13/// `lan::ports::LAN_PORT_RANGE` as the firewall spells a range.
14pub const TCP_PORTS: &str = "29700-29799";
15/// mDNS (5353), the desktop discovery port (29700) and the mobile responder (47891).
16pub const UDP_PORTS: &str = "5353,29700,47891";
17/// `NET_FW_PROFILE2_DOMAIN | NET_FW_PROFILE2_PRIVATE`. Public is never in these rules: a Public network is the
18/// person's decision, one network at a time (spec 4.4).
19pub const PROFILES_PRIVATE_DOMAIN: i32 = 1 | 2;
20/// What the firewall calls "my own subnet".
21pub const REMOTE_LOCAL_SUBNET: &str = "LocalSubnet";
22/// IANA protocol numbers, which is how the firewall stores them.
23pub const PROTO_TCP: i32 = 6;
24pub const PROTO_UDP: i32 = 17;
25
26/// The flag that starts the helper (`agentmux.exe --configure-lan-firewall`): the launcher answers it, and the server runs
27/// it when the person asks for the setup.
28pub const CONFIGURE_FLAG: &str = "--configure-lan-firewall";
29/// The helper's exit codes, which is how it says how it went. The rules are as asked, or were already.
30pub const EXIT_OK: i32 = 0;
31/// The administrator answered no to Windows' prompt (`ERROR_CANCELLED`).
32pub const EXIT_CANCELLED: i32 = 1223;
33/// A policy decides the firewall's rules: local rules are ignored, so nothing the helper does can help.
34pub const EXIT_MANAGED: i32 = 2;
35/// Anything else; the reason is on stderr.
36pub const EXIT_FAILED: i32 = 3;
37/// The rules are as asked, but some of the firewall's rules could not be read, so it cannot be said that none of them
38/// blocks AgentMux (or, when removing, is one of ours). Not a success: the count is on stderr.
39pub const EXIT_UNVERIFIED: i32 = 4;
40
41/// One rule to create.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Spec {
44    pub name: &'static str,
45    pub protocol: i32,
46    pub local_ports: &'static str,
47}
48
49/// The two port rules, in the order they are created.
50pub const SPECS: [Spec; 2] = [
51    Spec { name: TCP_RULE_NAME, protocol: PROTO_TCP, local_ports: TCP_PORTS },
52    Spec { name: UDP_RULE_NAME, protocol: PROTO_UDP, local_ports: UDP_PORTS },
53];
54
55/// A rule the machine already has, as far as the plan needs to know it.
56#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct Existing {
58    pub name: String,
59    pub enabled: bool,
60    pub inbound: bool,
61    pub allow: bool,
62    /// `NET_FW_PROFILE2_*` bits.
63    pub profiles: i32,
64    /// The program the rule is bound to; empty for any program.
65    pub program: String,
66    pub protocol: i32,
67    pub local_ports: String,
68    pub remote: String,
69    /// The rule's local addresses; empty or `*` for any.
70    pub local_addresses: String,
71    /// The rule names adapters (`Interfaces`).
72    pub interfaces_named: bool,
73    /// The rule's interface types: empty or `All` for every kind of adapter.
74    pub interface_types: String,
75    /// The rule is bound to something besides a port and a program: a service, a Store app, particular users or machines,
76    /// or secure traffic only. A restriction that could not be read counts as one.
77    pub bound: bool,
78    /// The program file is still on disk. Meaningless when `program` is empty.
79    pub program_exists: bool,
80}
81
82/// What the helper is asked to do.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum Mode {
85    /// Make the machine's rules the ones above, remove the blocks a cancelled prompt left, and the rules of programs
86    /// that are gone.
87    Configure,
88    /// Remove the two port rules and nothing else (uninstall).
89    Remove,
90}
91
92/// One change, in the order to make it.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Op {
95    /// Remove every rule of this name, whatever else is wrong with it.
96    RemoveNamed(&'static str),
97    /// Remove the rule at this position of the list given to [`plan`]. A name another rule shares cannot say which
98    /// one, so the rule is switched off instead and its block stops counting.
99    Delete(usize),
100    /// Create this rule.
101    Add(Spec),
102}
103
104/// Whether a rule path is one of our own binaries: `agentmux.exe`, `agentmux-srv-<version>-....exe`, and so on.
105pub fn is_agentmux_program(path: &str) -> bool {
106    let base = path.rsplit(['\\', '/']).next().unwrap_or("").to_ascii_lowercase();
107    base.starts_with("agentmux") && base.ends_with(".exe")
108}
109
110fn same_ports(a: &str, b: &str) -> bool {
111    let norm = |s: &str| s.split_whitespace().collect::<String>().to_ascii_lowercase();
112    !a.trim().is_empty() && norm(a) == norm(b)
113}
114
115/// A local address list that names no address: empty or `*`.
116fn any_address(s: &str) -> bool {
117    matches!(s.trim(), "" | "*")
118}
119
120/// An interface-type list that names no kind: empty or `All`.
121fn any_interface_type(s: &str) -> bool {
122    s.trim().is_empty() || s.trim().eq_ignore_ascii_case("all")
123}
124
125/// Whether `rules` already hold `spec`, once and exactly: enabled, inbound, Allow, Private and Domain only, any
126/// program, our ports, the local subnet, and no narrowing to an address, an adapter, a kind of adapter, a service, an app
127/// package or a user. One that differs in any way (a widened profile, another port list, one address) is not it.
128fn satisfied(spec: &Spec, rules: &[&Existing]) -> bool {
129    match rules {
130        [r] => {
131            any_address(&r.local_addresses)
132                && !r.interfaces_named
133                && any_interface_type(&r.interface_types)
134                && !r.bound
135                && r.enabled
136                && r.inbound
137                && r.allow
138                && r.profiles == PROFILES_PRIVATE_DOMAIN
139                && r.program.trim().is_empty()
140                && r.protocol == spec.protocol
141                && same_ports(&r.local_ports, spec.local_ports)
142                && r.remote.trim().eq_ignore_ascii_case(REMOTE_LOCAL_SUBNET)
143        }
144        _ => false,
145    }
146}
147
148/// How a run ended, once it has looked at the machine again.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum Settled {
151    /// Nothing is left to change and every rule could be read.
152    Done,
153    /// Nothing is left to change, but `unreadable` rules could not be read, so it cannot be said that none of them blocks
154    /// AgentMux (or, when removing, is one of ours). Never an unqualified success.
155    Unverifiable { unreadable: u32 },
156    /// The plan still has work after the change was made: it did not take.
157    Differs,
158}
159
160/// What a run came to: `left` is the plan made from the machine as it is now, `unreadable` the rules that could not be read.
161pub fn settled(left: &[Op], unreadable: u32) -> Settled {
162    if !left.is_empty() {
163        Settled::Differs
164    } else if unreadable > 0 {
165        Settled::Unverifiable { unreadable }
166    } else {
167        Settled::Done
168    }
169}
170
171/// What to change so that `existing` is what `mode` asks for. Empty when nothing needs changing, which is how the
172/// helper knows to ask for no elevation.
173pub fn plan(mode: Mode, existing: &[Existing]) -> Vec<Op> {
174    let mut removals = Vec::new();
175    let mut additions = Vec::new();
176    for spec in &SPECS {
177        let ours: Vec<&Existing> = existing.iter().filter(|e| e.name == spec.name).collect();
178        match mode {
179            Mode::Remove if !ours.is_empty() => removals.push(Op::RemoveNamed(spec.name)),
180            Mode::Configure if !satisfied(spec, &ours) => {
181                if !ours.is_empty() {
182                    removals.push(Op::RemoveNamed(spec.name));
183                }
184                additions.push(Op::Add(spec.clone()));
185            }
186            _ => {}
187        }
188    }
189    if mode == Mode::Configure {
190        let is_ours = |e: &Existing| SPECS.iter().any(|s| s.name == e.name);
191        for (i, e) in existing.iter().enumerate() {
192            // A rule already switched off is as good as gone: the helper switches off what it cannot remove by name.
193            if is_ours(e) || !e.enabled || !e.inbound || !is_agentmux_program(&e.program) {
194                continue;
195            }
196            // A Block a cancelled Windows prompt left overrides every Allow, ours included. An Allow of a program
197            // that is gone matches nothing, and the 600 of them on a machine that built a lot are noise.
198            if !e.allow || !e.program_exists {
199                removals.push(Op::Delete(i));
200            }
201        }
202    }
203    removals.extend(additions);
204    removals
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    const SRV: &str = r"C:\Users\user\AppData\Local\AgentMux\runtime\agentmux-srv-0.60.49-windows.x64.exe";
212
213    fn ours(spec: &Spec) -> Existing {
214        Existing {
215            name: spec.name.into(),
216            enabled: true,
217            inbound: true,
218            allow: true,
219            profiles: PROFILES_PRIVATE_DOMAIN,
220            program: String::new(),
221            protocol: spec.protocol,
222            local_ports: spec.local_ports.into(),
223            remote: REMOTE_LOCAL_SUBNET.into(),
224            local_addresses: "*".into(),
225            interfaces_named: false,
226            interface_types: "All".into(),
227            bound: false,
228            program_exists: false,
229        }
230    }
231
232    fn both() -> Vec<Existing> {
233        SPECS.iter().map(ours).collect()
234    }
235
236    fn prompt_rule(allow: bool, exists: bool) -> Existing {
237        Existing {
238            name: "agentmux-srv-0.60.49-windows.x64.exe".into(),
239            enabled: true,
240            inbound: true,
241            allow,
242            profiles: 4,
243            program: SRV.into(),
244            protocol: 256,
245            local_ports: "*".into(),
246            remote: "*".into(),
247            local_addresses: "*".into(),
248            interfaces_named: false,
249            interface_types: "All".into(),
250            bound: false,
251            program_exists: exists,
252        }
253    }
254
255    /// Apply a plan to a model of the machine's rules, as the helper does: positions are those of the list the plan
256    /// was made from, so they are taken before anything is removed by name; a rule whose name another rule shares is
257    /// switched off, since a name cannot say which one to remove.
258    fn apply(rules: Vec<Existing>, ops: &[Op]) -> Vec<Existing> {
259        let before = rules.clone();
260        let mut rules = rules;
261        let mut gone = Vec::new();
262        for op in ops {
263            if let Op::Delete(i) = op {
264                if before.iter().filter(|r| r.name == before[*i].name).count() == 1 {
265                    gone.push(*i);
266                } else {
267                    rules[*i].enabled = false;
268                }
269            }
270        }
271        let mut rules: Vec<Existing> = rules.into_iter().enumerate().filter(|(i, _)| !gone.contains(i)).map(|(_, r)| r).collect();
272        for op in ops {
273            match op {
274                Op::RemoveNamed(n) => rules.retain(|r| r.name != *n),
275                Op::Add(s) => rules.push(ours(s)),
276                Op::Delete(_) => {}
277            }
278        }
279        rules
280    }
281
282    #[test]
283    fn a_machine_with_no_rules_gets_both_and_a_second_run_changes_nothing() {
284        let first = plan(Mode::Configure, &[]);
285        assert_eq!(first, vec![Op::Add(SPECS[0].clone()), Op::Add(SPECS[1].clone())]);
286        let after = apply(Vec::new(), &first);
287        assert_eq!(plan(Mode::Configure, &after), Vec::new(), "idempotent");
288    }
289
290    #[test]
291    fn the_rules_already_right_ask_for_nothing_so_no_elevation_is_asked() {
292        assert_eq!(plan(Mode::Configure, &both()), Vec::new());
293    }
294
295    #[test]
296    fn a_rule_that_differs_in_any_way_is_replaced_not_kept() {
297        let wrong: Vec<(&str, Box<dyn Fn(&mut Existing)>)> = vec![
298            ("public added", Box::new(|e| e.profiles = 7)),
299            ("private only", Box::new(|e| e.profiles = 2)),
300            ("disabled", Box::new(|e| e.enabled = false)),
301            ("outbound", Box::new(|e| e.inbound = false)),
302            ("block", Box::new(|e| e.allow = false)),
303            ("one program", Box::new(|e| e.program = SRV.into())),
304            ("other ports", Box::new(|e| e.local_ports = "29700-29710".into())),
305            ("any remote", Box::new(|e| e.remote = "*".into())),
306            ("other protocol", Box::new(|e| e.protocol = 256)),
307            ("one local address", Box::new(|e| e.local_addresses = "198.51.100.7".into())),
308            ("a named adapter", Box::new(|e| e.interfaces_named = true)),
309            ("one kind of adapter", Box::new(|e| e.interface_types = "Wireless".into())),
310            ("a service, package or user", Box::new(|e| e.bound = true)),
311        ];
312        for (what, change) in wrong {
313            let mut rules = both();
314            change(&mut rules[0]);
315            let ops = plan(Mode::Configure, &rules);
316            assert!(ops.contains(&Op::RemoveNamed(TCP_RULE_NAME)) && ops.contains(&Op::Add(SPECS[0].clone())), "{what}: {ops:?}");
317            assert!(!ops.iter().any(|o| matches!(o, Op::Add(s) if s.name == UDP_RULE_NAME)), "{what}: the other rule is right");
318            assert_eq!(plan(Mode::Configure, &apply(rules, &ops)), Vec::new(), "{what}: not idempotent");
319        }
320    }
321
322    #[test]
323    fn the_spellings_of_any_are_any() {
324        for (address, kind) in [("", ""), ("*", "All"), (" * ", "all"), ("", "ALL")] {
325            let mut rules = both();
326            rules[0].local_addresses = address.into();
327            rules[0].interface_types = kind.into();
328            assert_eq!(plan(Mode::Configure, &rules), Vec::new(), "{address:?} {kind:?}");
329        }
330    }
331
332    #[test]
333    fn a_run_is_done_only_when_nothing_is_left_and_nothing_was_unreadable() {
334        assert_eq!(settled(&[], 0), Settled::Done);
335        assert_eq!(settled(&[], 3), Settled::Unverifiable { unreadable: 3 });
336        let left = vec![Op::RemoveNamed(TCP_RULE_NAME)];
337        assert_eq!(settled(&left, 0), Settled::Differs);
338        assert_eq!(settled(&left, 3), Settled::Differs, "a change that did not take is the worse news");
339    }
340
341    #[test]
342    fn two_rules_of_our_name_are_one_after_a_run() {
343        let mut rules = both();
344        rules.push(rules[0].clone());
345        let ops = plan(Mode::Configure, &rules);
346        assert_eq!(apply(rules, &ops).iter().filter(|r| r.name == TCP_RULE_NAME).count(), 1);
347    }
348
349    #[test]
350    fn a_block_a_cancelled_prompt_left_is_removed_and_a_live_allow_is_kept() {
351        let mut rules = both();
352        rules.push(prompt_rule(false, true));
353        rules.push(prompt_rule(true, true));
354        let ops = plan(Mode::Configure, &rules);
355        assert_eq!(ops, vec![Op::Delete(2)], "{ops:?}");
356    }
357
358    #[test]
359    fn rules_that_share_a_name_are_switched_off_and_the_next_plan_asks_for_nothing() {
360        // What a cancelled Windows prompt leaves: a TCP and a UDP rule under the file's name, one name for both.
361        let mut rules = both();
362        rules.push(prompt_rule(false, true));
363        rules.push(prompt_rule(false, true));
364        rules.push(prompt_rule(true, false));
365        let ops = plan(Mode::Configure, &rules);
366        assert_eq!(ops, vec![Op::Delete(2), Op::Delete(3), Op::Delete(4)]);
367        let after = apply(rules, &ops);
368        assert_eq!(after.len(), 5, "a shared name cannot be removed one rule at a time, so none was");
369        assert!(after[2..].iter().all(|r| !r.enabled));
370        assert_eq!(plan(Mode::Configure, &after), Vec::new(), "idempotent: a rule that is off is not planned again");
371    }
372
373    #[test]
374    fn an_allow_for_a_program_that_is_gone_is_removed() {
375        let mut rules = both();
376        rules.push(prompt_rule(true, false));
377        assert_eq!(plan(Mode::Configure, &rules), vec![Op::Delete(2)]);
378    }
379
380    #[test]
381    fn rules_of_other_programs_are_never_touched() {
382        let mut rules = both();
383        for program in [r"C:\Program Files\Google\Chrome\Application\chrome.exe", r"C:\tools\agentmuxish.dll", r"C:\x\my-agentmux.exe", ""] {
384            rules.push(Existing { program: program.into(), allow: false, program_exists: false, ..prompt_rule(false, false) });
385        }
386        assert_eq!(plan(Mode::Configure, &rules), Vec::new());
387        // An outbound block of ours is not an inbound problem.
388        rules.push(Existing { inbound: false, ..prompt_rule(false, true) });
389        assert_eq!(plan(Mode::Configure, &rules), Vec::new());
390    }
391
392    #[test]
393    fn a_program_name_is_ours_by_its_file_name_whatever_the_slash() {
394        assert!(is_agentmux_program(SRV));
395        assert!(is_agentmux_program("C:/x/AgentMux.EXE"));
396        assert!(!is_agentmux_program(r"C:\agentmux\tools\other.exe"));
397        assert!(!is_agentmux_program(""));
398    }
399
400    #[test]
401    fn remove_takes_our_two_rules_and_nothing_else() {
402        let mut rules = both();
403        rules.push(prompt_rule(false, false));
404        let ops = plan(Mode::Remove, &rules);
405        assert_eq!(ops, vec![Op::RemoveNamed(TCP_RULE_NAME), Op::RemoveNamed(UDP_RULE_NAME)]);
406        assert_eq!(plan(Mode::Remove, &apply(rules, &ops)), Vec::new());
407        assert_eq!(plan(Mode::Remove, &[]), Vec::new(), "nothing to remove asks for no elevation");
408    }
409
410    #[test]
411    fn the_port_lists_are_the_ones_the_listeners_use() {
412        // The range the listeners take their ports from, and the ports the firewall check needs, are in the rules:
413        // see `srv-core` `lan::firewall` for the test that pins them to `LAN_PORT_RANGE` and the discovery ports.
414        assert_eq!(TCP_PORTS, "29700-29799");
415        assert_eq!(UDP_PORTS, "5353,29700,47891");
416    }
417}