a7n-platform 0.29.0

Native desktop backends for the Apeirogon software KVM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
// SPDX-License-Identifier: GPL-3.0-or-later

//! Pure decision logic over firewall rules read from the OS.

use std::path::{Path, PathBuf};

use super::{Problem, Profiles};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Direction {
    Inbound,
    Outbound,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Action {
    Allow,
    Block,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Protocol {
    Udp,
    Tcp,
    Any,
    Other,
}

#[derive(Debug, Clone)]
pub(super) struct Rule {
    pub name: String,
    pub enabled: bool,
    pub direction: Direction,
    pub action: Action,
    pub protocol: Protocol,
    /// As Windows reports it: `*`, `42042`, `1000-2000,5353`, or a keyword.
    pub local_ports: String,
    /// None means every program.
    pub program: Option<PathBuf>,
    pub profiles: Profiles,
    pub local_users: String,
    pub package_id: String,
    pub remote_addresses: String,
}

impl Profiles {
    fn is_empty(self) -> bool {
        self.0 == 0
    }

    fn intersects(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }

    fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    fn without(self, other: Self) -> Self {
        Self(self.0 & !other.0)
    }
}

/// Problems for `program` on UDP `ports` while the firewall is on for the
/// `active` profiles; nothing when no profile is active.
pub(super) fn evaluate(
    rules: &[Rule],
    active: Profiles,
    program: &Path,
    ports: &[u16],
    user_sid: &str,
) -> Vec<Problem> {
    if active.is_empty() {
        return Vec::new();
    }
    let relevant: Vec<&Rule> = rules
        .iter()
        .filter(|rule| rule.reaches(active, program, user_sid))
        .collect();
    let mut problems = Vec::new();
    problems.extend(blocking(&relevant, ports));
    problems.extend(missing_allow(&relevant, active, program, ports));
    problems
}

impl Rule {
    /// An enabled inbound UDP rule for this program on one of the active profiles.
    fn reaches(&self, active: Profiles, program: &Path, user_sid: &str) -> bool {
        let inbound = self.direction == Direction::Inbound;
        let udp = matches!(self.protocol, Protocol::Udp | Protocol::Any);
        let active_profile = self.profiles.intersects(active);
        let unpackaged = self.package_id.trim().is_empty();
        let user_matches = self.applies_to_user(user_sid);
        let program_matches = self
            .program
            .as_deref()
            .is_none_or(|own| same_program(own, program));
        self.enabled
            && inbound
            && udp
            && active_profile
            && unpackaged
            && user_matches
            && program_matches
    }

    fn applies_to_user(&self, user_sid: &str) -> bool {
        if is_unrestricted(&self.local_users) {
            return true;
        }
        let mut allowed = false;
        for entry in self.local_users.split('(').skip(1) {
            let Some((ace, _)) = entry.split_once(')') else {
                continue;
            };
            let mut fields = ace.split(';');
            let kind = fields.next();
            let trustee = fields.nth(4);
            if !trustee.is_some_and(|sid| sid.eq_ignore_ascii_case(user_sid)) {
                continue;
            }
            match kind {
                Some("D") => return false,
                Some("A") => allowed = true,
                _ => {}
            }
        }
        allowed
    }

    fn covers(&self, port: u16) -> bool {
        covers_port(&self.local_ports, port)
    }
}

fn is_unrestricted(spec: &str) -> bool {
    matches!(spec.trim(), "" | "*")
}

fn blocking(relevant: &[&Rule], ports: &[u16]) -> Vec<Problem> {
    relevant
        .iter()
        .filter(|rule| rule.action == Action::Block)
        // A scoped block may leave other peers reachable, so it is not a blanket block.
        .filter(|rule| is_unrestricted(&rule.remote_addresses))
        .filter_map(|rule| {
            let blocked: Vec<u16> = ports
                .iter()
                .copied()
                .filter(|&port| rule.covers(port))
                .collect();
            (!blocked.is_empty()).then(|| Problem::Blocked {
                rule: rule.name.clone(),
                ports: blocked,
            })
        })
        .collect()
}

fn missing_allow(
    relevant: &[&Rule],
    active: Profiles,
    program: &Path,
    ports: &[u16],
) -> Option<Problem> {
    let mut missing_ports = Vec::new();
    let mut missing_profiles = Profiles::default();
    for &port in ports {
        let allowed = relevant
            .iter()
            .filter(|rule| rule.action == Action::Allow && rule.covers(port))
            .fold(Profiles::default(), |all, rule| all.union(rule.profiles));
        let uncovered = active.without(allowed);
        if !uncovered.is_empty() {
            missing_ports.push(port);
            missing_profiles = missing_profiles.union(uncovered);
        }
    }
    (!missing_ports.is_empty()).then(|| Problem::MissingAllow {
        program: program.to_path_buf(),
        ports: missing_ports,
        profiles: missing_profiles,
    })
}

/// Windows paths compare case-insensitively. Rule paths with environment
/// variables such as `%SystemRoot%` are not expanded and never match.
fn same_program(rule: &Path, program: &Path) -> bool {
    normalize(rule) == normalize(program)
}

fn normalize(path: &Path) -> String {
    path.to_string_lossy().replace('/', "\\").to_lowercase()
}

/// Accepts `*`, `Any`, an empty list, single ports and ranges, comma
/// separated. Anything else, such as the keyword `RPC`, matches nothing.
fn covers_port(spec: &str, port: u16) -> bool {
    let spec = spec.trim();
    if spec.is_empty() || spec == "*" || spec.eq_ignore_ascii_case("any") {
        return true;
    }
    spec.split(',')
        .any(|item| match item.trim().split_once('-') {
            Some((low, high)) => matches!(
                (low.trim().parse::<u16>(), high.trim().parse::<u16>()),
                (Ok(low), Ok(high)) if (low..=high).contains(&port)
            ),
            None => item.trim().parse() == Ok(port),
        })
}

#[cfg(test)]
mod tests {
    use super::*;

    const USER_SID: &str = "S-1-5-21-123-456-789-1001";
    const PORT: u16 = 42042;
    const MDNS: u16 = 5353;
    const PRIVATE: Profiles = Profiles(2);
    const PUBLIC: Profiles = Profiles(4);
    const ALL_PROFILES: Profiles = Profiles(0x7FFF_FFFF);

    fn program() -> PathBuf {
        PathBuf::from(r"C:\Apps\apeirogond.exe")
    }

    fn rule(action: Action, ports: &str, profiles: Profiles) -> Rule {
        Rule {
            name: "test rule".into(),
            enabled: true,
            direction: Direction::Inbound,
            action,
            protocol: Protocol::Udp,
            local_ports: ports.into(),
            program: Some(program()),
            profiles,
            local_users: String::new(),
            package_id: String::new(),
            remote_addresses: "*".into(),
        }
    }

    fn evaluate_private(rules: &[Rule]) -> Vec<Problem> {
        evaluate(rules, PRIVATE, &program(), &[PORT, MDNS], USER_SID)
    }

    #[test]
    fn covers_port_specs_match_windows_syntax() {
        // Arrange
        let cases = [
            ("*", PORT, true),
            ("Any", PORT, true),
            ("42042", PORT, true),
            ("1000-2000,5353", MDNS, true),
            ("1000-2000,5353", PORT, false),
            ("42000-42100", PORT, true),
            ("80, 443", PORT, false),
            ("RPC", PORT, false),
            ("9-x", PORT, false),
        ];

        for (spec, port, expected) in cases {
            // Act
            let result = covers_port(spec, port);

            // Assert
            assert_eq!(result, expected, "{spec} on {port}");
        }
    }

    fn assert_missing_allow(problems: &[Problem], what: &str) {
        assert!(matches!(problems, [Problem::MissingAllow { .. }]), "{what}");
    }

    #[test]
    fn evaluate_allow_rules_reach_program_and_profile_only_when_applicable() {
        // Arrange
        let reaching = |edit: fn(&mut Rule)| {
            let mut allow = rule(Action::Allow, "42042,5353", PRIVATE);
            edit(&mut allow);
            allow
        };
        let reaches: [(&str, Rule); 4] = [
            ("both ports", reaching(|_| {})),
            (
                "program path in other case",
                reaching(|r| r.program = Some(PathBuf::from(r"c:/apps/APEIROGOND.EXE"))),
            ),
            (
                "any program and protocol",
                reaching(|r| {
                    r.program = None;
                    r.protocol = Protocol::Any;
                    r.local_ports = "*".into();
                    r.profiles = ALL_PROFILES;
                }),
            ),
            (
                "local subnet only",
                reaching(|r| r.remote_addresses = "LocalSubnet".into()),
            ),
        ];
        let misses: [(&str, Rule); 8] = [
            ("other profile", reaching(|r| r.profiles = PUBLIC)),
            ("disabled", reaching(|r| r.enabled = false)),
            ("outbound", reaching(|r| r.direction = Direction::Outbound)),
            ("tcp", reaching(|r| r.protocol = Protocol::Tcp)),
            ("other protocol", reaching(|r| r.protocol = Protocol::Other)),
            (
                "other program",
                reaching(|r| r.program = Some(PathBuf::from(r"C:\Other\app.exe"))),
            ),
            (
                "other user",
                reaching(|r| r.local_users = "D:(A;;CC;;;S-1-5-18)".into()),
            ),
            (
                "package scoped",
                reaching(|r| r.package_id = "S-1-15-2-123".into()),
            ),
        ];

        for (what, allow) in reaches {
            // Act
            let problems = evaluate_private(&[allow]);

            // Assert
            assert_eq!(problems, Vec::new(), "{what}");
        }
        for (what, allow) in misses {
            // Act
            let problems = evaluate_private(&[allow]);

            // Assert
            assert_missing_allow(&problems, what);
        }
    }

    #[test]
    fn evaluate_no_rules_reports_missing_allow_for_both_ports() {
        // Arrange
        let expected = Problem::MissingAllow {
            program: program(),
            ports: vec![PORT, MDNS],
            profiles: PRIVATE,
        };

        // Act
        let problems = evaluate_private(&[]);

        // Assert
        assert_eq!(problems, vec![expected]);
    }

    #[test]
    fn evaluate_block_rule_wins_over_allow_rule() {
        // Arrange
        let allow = rule(Action::Allow, "*", ALL_PROFILES);
        let mut block = rule(Action::Block, "42000-42100", PRIVATE);
        block.name = "Dismissed prompt".into();
        let mut listing_user = rule(Action::Block, "*", PRIVATE);
        listing_user.local_users = format!("D:(A;;CC;;;S-1-5-18)(A;;CC;;;{USER_SID})");
        listing_user.remote_addresses = String::new();

        // Act
        let named = evaluate_private(&[allow.clone(), block]);
        let scoped = evaluate_private(&[allow, listing_user]);

        // Assert
        let expected = Problem::Blocked {
            rule: "Dismissed prompt".into(),
            ports: vec![PORT],
        };
        assert_eq!(named, vec![expected]);
        assert!(matches!(scoped.as_slice(), [Problem::Blocked { .. }]));
    }

    #[test]
    fn evaluate_block_not_reaching_this_user_or_peers_reports_nothing() {
        // Arrange
        let other_user = format!("D:(A;;CC;;;{USER_SID}0)");
        let deny_overrides = format!("D:(A;;CC;;;{USER_SID})(D;;CC;;;{USER_SID})");
        let deny_first = format!("D:(D;;CC;;;{USER_SID})(A;;CC;;;{USER_SID})");
        let scopes = [
            ("other user", other_user.as_str(), "*"),
            ("deny ace overrides allow", deny_overrides.as_str(), "*"),
            ("deny ace first", deny_first.as_str(), "*"),
            ("local subnet", "", "LocalSubnet"),
            ("single address", "", "192.0.2.1"),
            ("cidr", "", "10.0.0.0/8"),
        ];

        for (what, local_users, remote_addresses) in scopes {
            let allow = rule(Action::Allow, "*", PRIVATE);
            let mut block = rule(Action::Block, "*", PRIVATE);
            block.local_users = local_users.into();
            block.remote_addresses = remote_addresses.into();

            // Act
            let problems = evaluate_private(&[allow, block]);

            // Assert
            assert_eq!(problems, Vec::new(), "{what}");
        }
    }

    #[test]
    fn evaluate_firewall_off_for_current_profile_reports_nothing() {
        // Arrange
        let no_active_profile = Profiles::default();

        // Act
        let problems = evaluate(&[], no_active_profile, &program(), &[PORT, MDNS], USER_SID);

        // Assert
        assert_eq!(problems, Vec::new());
    }
}