73426592e4
The least-privilege oracle works in u32, so P-1 never saw an IPv6 address. P-6v6 (1,000 cases) writes the same generated world with every IPv4 address a as fd00::a and every /L as /(L+96) (the default route as ::/0), compiles both, and requires the IPv6 plans to equal the IPv4 plans mapped the same way, with the same problems. So every IPv6 path behaves like the IPv4 one P-1 checks against the oracle. Mutation-checked: IPv6 hosts as /127 fails it at once.
871 lines
33 KiB
Rust
871 lines
33 KiB
Rust
//! Mandatory test 3: least privilege, as a property test (proptest), designed after QA's plan
|
||
//! (`Via/qa/02_roads_attacks.md` §10).
|
||
//!
|
||
//! - **Generators** draw small worlds so that collisions are frequent: 1–4 people, up to 2 groups, 2–7 devices,
|
||
//! routes inside `10.0.0.0/22`, road subnets of /22 to /32 inside the same /22 (so nesting, adjacency and
|
||
//! overlap are the normal case), `until` on the boundary (`now − 1 s`, `now`, `now + 1 s`), five port sets,
|
||
//! 10% custom roads carrying `AllowedIPs = 0.0.0.0/0`, and 5% deliberately invalid roads.
|
||
//! - The world comes from a byte string, so proptest's shrinking makes counterexamples smaller.
|
||
//! - The **oracle** below shares no code with `roads`: it reads the generated world (not the parsed store),
|
||
//! resolves people and groups itself, and compares networks with `u32` arithmetic.
|
||
//!
|
||
//! Properties: P-1 every receiving-side firewall rule, sampled at both ends and the middle of its network and
|
||
//! of its ports, is allowed by an active road for the device whose address is the rule's source (so a client
|
||
//! that widens its own allowed IPs gains nothing: only the receiving side is checked); every allowed IP on the
|
||
//! sending side is exactly what a road names (no supernet, QA R-02); every firewall source sits on its own
|
||
//! peer as a /32 (no spoofing, QA R-10); invalid and expired roads change no byte; removing a road or moving
|
||
//! `now` forward never adds a rule (P-3, P-4); `explain` agrees with the firewall (P-7).
|
||
//!
|
||
//! IPv6 (QA F-10): the oracle works in `u32`, so IPv6 is checked by embedding instead. P-6v6 writes the same
|
||
//! world with every IPv4 address `a` replaced by `fd00::a` and every prefix `/L` by `/(L+96)` (the default
|
||
//! route by `::/0`), compiles both, maps the IPv4 plans through the same embedding and requires them to be
|
||
//! equal to the IPv6 plans: so every IPv6 path (`/128` hosts, nesting, overlap, `except`, exits, the kill
|
||
//! switch) behaves exactly like the IPv4 one that P-1 checks against the oracle, plus the same problems.
|
||
|
||
use jiff::{SignedDuration, Timestamp as Instant};
|
||
use proptest::prelude::*;
|
||
use roads::plan::{Direction, Dst};
|
||
use roads::{DeviceKey, Store, compile};
|
||
use std::collections::BTreeSet;
|
||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||
|
||
const NOW: &str = "2026-11-25T12:00:00Z";
|
||
const BASE: u32 = 0x0A00_0000; // 10.0.0.0
|
||
|
||
static CASES: AtomicUsize = AtomicUsize::new(0);
|
||
static P1_CASES: AtomicUsize = AtomicUsize::new(0);
|
||
static P1_WITH_RULES: AtomicUsize = AtomicUsize::new(0);
|
||
static P1_RULES: AtomicUsize = AtomicUsize::new(0);
|
||
static P1_ALLOWED: AtomicUsize = AtomicUsize::new(0);
|
||
|
||
fn now() -> Instant {
|
||
NOW.parse().unwrap()
|
||
}
|
||
|
||
/// Draws choices from bytes; an exhausted source gives 0, the simplest choice.
|
||
struct Src<'a> {
|
||
b: &'a [u8],
|
||
i: usize,
|
||
}
|
||
|
||
impl Src<'_> {
|
||
fn n(&mut self, n: usize) -> usize {
|
||
let v = self.b.get(self.i).copied().unwrap_or(0) as usize;
|
||
self.i += 1;
|
||
v % n
|
||
}
|
||
fn pct(&mut self, p: usize) -> bool {
|
||
self.n(100) < p
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
struct Dev {
|
||
owner: Option<usize>,
|
||
classic: bool,
|
||
exit: bool,
|
||
relay: bool,
|
||
route: Option<(u32, u8)>,
|
||
service: Option<Vec<(&'static str, u16, u16)>>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
enum Subj {
|
||
Person(usize),
|
||
Group(usize),
|
||
Device(usize),
|
||
/// An app on a person's devices (QA B-3).
|
||
App(usize),
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
enum Obj {
|
||
Device(usize),
|
||
Subnet(u32, u8),
|
||
Service(usize),
|
||
Exit(usize),
|
||
}
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
enum Verb {
|
||
Reach,
|
||
Exits,
|
||
Direct,
|
||
Kill,
|
||
Custom,
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
struct R {
|
||
subject: Subj,
|
||
verb: Verb,
|
||
object: Option<Obj>,
|
||
/// Seconds from now.
|
||
until: Option<i64>,
|
||
ports: Option<Vec<(&'static str, u16, u16)>>,
|
||
classic: Option<bool>,
|
||
invalid: bool,
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
struct World {
|
||
people: usize,
|
||
groups: Vec<Vec<usize>>,
|
||
devs: Vec<Dev>,
|
||
roads: Vec<R>,
|
||
}
|
||
|
||
const PORT_SETS: [&[(&str, u16, u16)]; 4] = [
|
||
&[("tcp", 443, 443)],
|
||
&[("tcp", 22, 22), ("tcp", 443, 443)],
|
||
&[("tcp", 1, 1024)],
|
||
&[("tcp", 1, 65535)],
|
||
];
|
||
|
||
fn world(bytes: &[u8]) -> World {
|
||
let mut s = Src { b: bytes, i: 0 };
|
||
let people = 1 + s.n(4);
|
||
let groups = (0..s.n(3))
|
||
.map(|_| (0..people).filter(|_| s.pct(50)).collect())
|
||
.collect();
|
||
let n_dev = 2 + s.n(6);
|
||
let devs = (0..n_dev)
|
||
.map(|i| Dev {
|
||
owner: if s.pct(80) { Some(s.n(people)) } else { None },
|
||
classic: s.pct(10),
|
||
exit: s.pct(30),
|
||
relay: s.pct(20),
|
||
route: (i < 4 && s.pct(70)).then(|| (BASE + ((i as u32) << 8), 24)),
|
||
service: s.pct(35).then(|| PORT_SETS[s.n(2)].to_vec()),
|
||
})
|
||
.collect::<Vec<_>>();
|
||
let n_roads = 1 + s.n(12);
|
||
let roads = (0..n_roads)
|
||
.map(|_| {
|
||
let verb = match s.n(20) {
|
||
0..=10 => Verb::Reach,
|
||
11..=13 => Verb::Exits,
|
||
14 | 15 => Verb::Direct,
|
||
16 | 17 => Verb::Kill,
|
||
_ => Verb::Custom,
|
||
};
|
||
// Indices one past the end name things that do not exist.
|
||
let subject = match (s.n(4), &verb) {
|
||
(_, Verb::Custom) => Subj::Device(s.n(n_dev + 1)),
|
||
(3, Verb::Direct) => Subj::App(s.n(people + 1)),
|
||
(0, _) | (3, _) => Subj::Person(s.n(people + 1)),
|
||
(1, _) => Subj::Group(s.n(3)),
|
||
_ => Subj::Device(s.n(n_dev + 1)),
|
||
};
|
||
let object = match verb {
|
||
Verb::Custom => None,
|
||
Verb::Exits | Verb::Kill => Some(Obj::Exit(s.n(n_dev + 1))),
|
||
Verb::Direct => Some(Obj::Subnet(
|
||
if s.pct(50) { 0 } else { BASE },
|
||
if s.pct(50) { 0 } else { 22 },
|
||
)),
|
||
Verb::Reach => Some(match s.n(3) {
|
||
0 => Obj::Device(s.n(n_dev + 1)),
|
||
1 => Obj::Service(s.n(n_dev + 1)),
|
||
_ => {
|
||
if s.pct(10) {
|
||
Obj::Subnet(0x0A09_0000, 24) // routed by nobody
|
||
} else {
|
||
let len = 22 + s.n(11) as u8;
|
||
let off = (s.n(256) as u32) << 2 | s.n(4) as u32;
|
||
Obj::Subnet(BASE | (off & mask(len) & 0x3FF), len)
|
||
}
|
||
}
|
||
}),
|
||
};
|
||
R {
|
||
until: match s.n(6) {
|
||
0 | 1 => None,
|
||
2 => Some(-1),
|
||
3 => Some(0),
|
||
4 => Some(1),
|
||
_ => Some(86_400),
|
||
},
|
||
ports: (verb == Verb::Reach && s.pct(50)).then(|| PORT_SETS[s.n(4)].to_vec()),
|
||
classic: match s.n(3) {
|
||
0 => None,
|
||
1 => Some(true),
|
||
_ => Some(false),
|
||
},
|
||
invalid: s.pct(5),
|
||
subject,
|
||
verb,
|
||
object,
|
||
}
|
||
})
|
||
.collect();
|
||
World {
|
||
people,
|
||
groups,
|
||
devs,
|
||
roads,
|
||
}
|
||
}
|
||
|
||
fn mask(len: u8) -> u32 {
|
||
if len == 0 {
|
||
0
|
||
} else {
|
||
u32::MAX << (32 - len as u32)
|
||
}
|
||
}
|
||
|
||
fn ip(v: u32) -> String {
|
||
format!(
|
||
"{}.{}.{}.{}",
|
||
v >> 24,
|
||
(v >> 16) & 255,
|
||
(v >> 8) & 255,
|
||
v & 255
|
||
)
|
||
}
|
||
|
||
fn dev_addr(i: usize) -> u32 {
|
||
0x6460_0000 + 1 + i as u32 // 100.96.0.(i+1)
|
||
}
|
||
|
||
fn dev_key(i: usize) -> String {
|
||
DeviceKey::from_bytes(&[i as u8 + 1; 32])
|
||
.as_str()
|
||
.to_string()
|
||
}
|
||
|
||
fn id_of(i: usize) -> String {
|
||
format!("t{i:05}")
|
||
}
|
||
|
||
fn ports_text(p: &[(&str, u16, u16)]) -> String {
|
||
let items: Vec<String> = p
|
||
.iter()
|
||
.map(|(pr, lo, hi)| {
|
||
if lo == hi {
|
||
format!("{pr}/{lo}")
|
||
} else {
|
||
format!("{pr}/{lo}-{hi}")
|
||
}
|
||
})
|
||
.collect();
|
||
format!("[{}]", items.join(", "))
|
||
}
|
||
|
||
/// The world as store bytes, written here without the library's writer.
|
||
fn to_store(w: &World, roads: &[(usize, &R)], when: Instant) -> Store {
|
||
let (files, directory, devices) = store_parts(w, roads, when);
|
||
Store::from_parts(&files, Some(directory.as_bytes()), Some(devices.as_bytes()))
|
||
}
|
||
|
||
type Parts = (Vec<(String, Vec<u8>)>, String, String);
|
||
|
||
fn store_parts(w: &World, roads: &[(usize, &R)], when: Instant) -> Parts {
|
||
let people: Vec<String> = (0..w.people)
|
||
.map(|p| format!(r#"{{"id":"p{p}","name":"P{p}"}}"#))
|
||
.collect();
|
||
let groups: Vec<String> = w
|
||
.groups
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(g, m)| {
|
||
let m: Vec<String> = m.iter().map(|p| format!("\"p{p}\"")).collect();
|
||
format!(
|
||
r#"{{"id":"g{g}","name":"G{g}","members":[{}]}}"#,
|
||
m.join(",")
|
||
)
|
||
})
|
||
.collect();
|
||
let directory = format!(
|
||
r#"{{"format":1,"people":[{}],"groups":[{}]}}"#,
|
||
people.join(","),
|
||
groups.join(",")
|
||
);
|
||
let devices: Vec<String> = w
|
||
.devs
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(i, d)| {
|
||
let owner = d.owner.map(|o| format!(r#","owner":"p{o}""#)).unwrap_or_default();
|
||
let routes = d.route.map(|(n, l)| format!(r#","routes":["{}/{l}"]"#, ip(n))).unwrap_or_default();
|
||
let services = d
|
||
.service
|
||
.as_ref()
|
||
.map(|p| {
|
||
let ports: Vec<String> = ports_text(p).trim_matches(['[', ']']).split(", ").map(|x| format!("\"{x}\"")).collect();
|
||
format!(r#","services":[{{"host":"s{i}.test","ports":[{}]}}]"#, ports.join(","))
|
||
})
|
||
.unwrap_or_default();
|
||
format!(
|
||
r#"{{"key":"{}","name":"d{i}","address":"{}","classic":{},"exit":{},"relay":{}{owner}{routes}{services}}}"#,
|
||
dev_key(i),
|
||
ip(dev_addr(i)),
|
||
d.classic,
|
||
d.exit,
|
||
d.relay
|
||
)
|
||
})
|
||
.collect();
|
||
let devices = format!(r#"{{"format":1,"devices":[{}]}}"#, devices.join(","));
|
||
let files: Vec<(String, Vec<u8>)> = roads
|
||
.iter()
|
||
.map(|(i, r)| {
|
||
let mut t = format!("---\nid: {}\n", id_of(*i));
|
||
t += &match &r.subject {
|
||
Subj::Person(p) => format!("subject: person:p{p}\n"),
|
||
Subj::Group(g) => format!("subject: group:g{g}\n"),
|
||
Subj::Device(d) => format!("subject: device:{}\n", dev_key(*d)),
|
||
Subj::App(p) => format!("subject: app:games\non: person:p{p}\n"),
|
||
};
|
||
t += match r.verb {
|
||
Verb::Reach => "verb: can-reach\n",
|
||
Verb::Exits => "verb: exits-through\n",
|
||
Verb::Direct => "verb: goes-direct\n",
|
||
Verb::Kill => "verb: never-online-without\n",
|
||
Verb::Custom => "verb: custom\n",
|
||
};
|
||
if let Some(o) = &r.object {
|
||
t += &match o {
|
||
Obj::Device(d) => format!("object: device:{}\n", dev_key(*d)),
|
||
Obj::Exit(d) => format!("object: exit:{}\n", dev_key(*d)),
|
||
Obj::Service(d) => format!("object: service:s{d}.test\n"),
|
||
Obj::Subnet(n, l) => format!("object: subnet:{}/{l}\n", ip(*n)),
|
||
};
|
||
}
|
||
if let Some(u) = r.until {
|
||
let key = if r.invalid { "untill" } else { "until" };
|
||
t += &format!("{key}: {}\n", (now() + SignedDuration::from_secs(u)));
|
||
} else if r.invalid {
|
||
t += "allowedIPs: [0.0.0.0/0]\n";
|
||
}
|
||
if let Some(p) = &r.ports {
|
||
t += &format!("ports: {}\n", ports_text(p));
|
||
}
|
||
if let Some(c) = r.classic
|
||
&& matches!(r.verb, Verb::Reach | Verb::Exits | Verb::Custom)
|
||
{
|
||
t += &format!("classic: {c}\n");
|
||
}
|
||
t += "created: 2026-11-01T00:00:00Z\n---\n";
|
||
if r.verb == Verb::Custom {
|
||
t += "```raw\n[Peer]\nPublicKey = AAAA\nAllowedIPs = 0.0.0.0/0, ::/0\n```\n";
|
||
}
|
||
(format!("{}-r.md", id_of(*i)), t.into_bytes())
|
||
})
|
||
.collect();
|
||
let _ = when;
|
||
(files, directory, devices)
|
||
}
|
||
|
||
// ------------------------------------------------------------------ IPv6 by embedding (QA F-10)
|
||
|
||
fn v6_of(a: std::net::Ipv4Addr) -> std::net::Ipv6Addr {
|
||
std::net::Ipv6Addr::from(0xfd00_u128 << 112 | u32::from(a) as u128)
|
||
}
|
||
|
||
/// One IPv4 address or network, embedded; anything else unchanged.
|
||
fn embed_token(t: &str) -> Option<String> {
|
||
let (a, len) = match t.split_once('/') {
|
||
Some((a, l)) => (a, Some(l.parse::<u8>().ok().filter(|l| *l <= 32)?)),
|
||
None => (t, None),
|
||
};
|
||
let a: std::net::Ipv4Addr = a.parse().ok()?;
|
||
if a.to_string() != t.split('/').next().unwrap() {
|
||
return None;
|
||
}
|
||
Some(match len {
|
||
None => v6_of(a).to_string(),
|
||
Some(0) if a.is_unspecified() => "::/0".to_string(),
|
||
Some(l) => format!("{}/{}", v6_of(a), l + 96),
|
||
})
|
||
}
|
||
|
||
/// Replaces every IPv4 address or network in `text` (a maximal run of digits, dots and one slash).
|
||
fn embed_text(text: &str) -> String {
|
||
let mut out = String::new();
|
||
let mut run = String::new();
|
||
let flush = |run: &mut String, out: &mut String| {
|
||
out.push_str(&embed_token(run).unwrap_or_else(|| run.clone()));
|
||
run.clear();
|
||
};
|
||
for c in text.chars() {
|
||
if c.is_ascii_digit() || c == '.' || (c == '/' && !run.is_empty() && !run.contains('/')) {
|
||
run.push(c);
|
||
} else {
|
||
flush(&mut run, &mut out);
|
||
out.push(c);
|
||
}
|
||
}
|
||
flush(&mut run, &mut out);
|
||
out
|
||
}
|
||
|
||
fn embed_parts((files, dir, devs): Parts) -> Parts {
|
||
(
|
||
files
|
||
.into_iter()
|
||
.map(|(n, b)| (n, embed_text(&String::from_utf8(b).unwrap()).into_bytes()))
|
||
.collect(),
|
||
dir,
|
||
embed_text(&devs),
|
||
)
|
||
}
|
||
|
||
/// A plan as JSON with IPv4 embedded (when `embed`), the two default routes made one spelling, and every
|
||
/// list sorted, so plans of the two families compare.
|
||
fn normal(plan: &roads::Plan, embed: bool) -> serde_json::Value {
|
||
fn walk(v: &mut serde_json::Value, embed: bool) {
|
||
match v {
|
||
serde_json::Value::String(s) => {
|
||
// Raw blocks are free text: embed inside them too, as the store's text was.
|
||
if embed {
|
||
*s = embed_text(s);
|
||
} else if s == "0.0.0.0/0" {
|
||
*s = "::/0".into();
|
||
}
|
||
}
|
||
serde_json::Value::Array(a) => {
|
||
a.iter_mut().for_each(|x| walk(x, embed));
|
||
a.sort_by_key(|x| x.to_string());
|
||
}
|
||
serde_json::Value::Object(m) => m.values_mut().for_each(|x| walk(x, embed)),
|
||
_ => {}
|
||
}
|
||
}
|
||
let mut v = serde_json::to_value(plan).unwrap();
|
||
walk(&mut v, embed);
|
||
v
|
||
}
|
||
|
||
// ------------------------------------------------------------------ the oracle (no roads code)
|
||
|
||
fn subj_devs(w: &World, s: &Subj) -> BTreeSet<usize> {
|
||
(0..w.devs.len())
|
||
.filter(|&d| match s {
|
||
Subj::Person(p) => w.devs[d].owner == Some(*p),
|
||
Subj::Group(g) => w
|
||
.groups
|
||
.get(*g)
|
||
.is_some_and(|m| w.devs[d].owner.is_some_and(|o| m.contains(&o))),
|
||
Subj::Device(x) => *x == d,
|
||
Subj::App(p) => w.devs[d].owner == Some(*p),
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// An upper bound on the roads that can grant: not deliberately invalid, not expired at `at` (seconds from
|
||
/// NOW). The compiler may refuse more (classic, unknown references); it may never grant more.
|
||
fn live(r: &R, at: i64) -> bool {
|
||
!r.invalid && r.until.is_none_or(|u| at < u)
|
||
}
|
||
|
||
fn in_prefix(addr: u32, net: u32, len: u8) -> bool {
|
||
addr & mask(len) == net & mask(len)
|
||
}
|
||
|
||
fn ports_allow(p: &Option<Vec<(&str, u16, u16)>>, proto: &str, port: u16) -> bool {
|
||
p.as_ref().is_none_or(|ps| {
|
||
ps.iter()
|
||
.any(|(pr, lo, hi)| *pr == proto && *lo <= port && port <= *hi)
|
||
})
|
||
}
|
||
|
||
/// May device `d` open a connection to `addr` on `proto/port`, by some live can-reach road?
|
||
fn may_reach(w: &World, at: i64, d: usize, addr: u32, proto: &str, port: u16) -> bool {
|
||
w.roads
|
||
.iter()
|
||
.filter(|r| live(r, at) && r.verb == Verb::Reach && subj_devs(w, &r.subject).contains(&d))
|
||
.any(|r| match r.object.as_ref().unwrap() {
|
||
Obj::Device(x) => {
|
||
*x < w.devs.len() && addr == dev_addr(*x) && ports_allow(&r.ports, proto, port)
|
||
}
|
||
Obj::Service(x) => {
|
||
*x < w.devs.len()
|
||
&& w.devs[*x].service.is_some()
|
||
&& addr == dev_addr(*x)
|
||
&& ports_allow(&r.ports.clone().or(w.devs[*x].service.clone()), proto, port)
|
||
}
|
||
Obj::Subnet(n, l) => in_prefix(addr, *n, *l) && ports_allow(&r.ports, proto, port),
|
||
Obj::Exit(_) => false,
|
||
})
|
||
}
|
||
|
||
fn may_exit(w: &World, at: i64, d: usize, exit: usize) -> bool {
|
||
w.roads.iter().any(|r| {
|
||
live(r, at)
|
||
&& r.verb == Verb::Exits
|
||
&& r.object == Some(Obj::Exit(exit))
|
||
&& subj_devs(w, &r.subject).contains(&d)
|
||
})
|
||
}
|
||
|
||
fn parse_net(s: &str) -> Option<(u32, u8)> {
|
||
let (a, l) = s.split_once('/')?;
|
||
let o: Vec<u32> = a
|
||
.split('.')
|
||
.map(|x| x.parse().ok())
|
||
.collect::<Option<_>>()?;
|
||
(o.len() == 4).then(|| {
|
||
(
|
||
o[0] << 24 | o[1] << 16 | o[2] << 8 | o[3],
|
||
l.parse().unwrap(),
|
||
)
|
||
})
|
||
}
|
||
|
||
fn dev_of_addr(w: &World, a: u32) -> Option<usize> {
|
||
(0..w.devs.len()).find(|&i| dev_addr(i) == a)
|
||
}
|
||
|
||
fn dev_of_key(w: &World, k: &DeviceKey) -> usize {
|
||
(0..w.devs.len())
|
||
.find(|&i| dev_key(i) == k.as_str())
|
||
.expect("a plan for a known device")
|
||
}
|
||
|
||
/// Every rule of every plan, without its road list: what P-3 and P-4 compare.
|
||
fn rule_set(c: &roads::Compiled) -> BTreeSet<String> {
|
||
c.plans
|
||
.values()
|
||
.flat_map(|p| {
|
||
p.firewall
|
||
.rules
|
||
.iter()
|
||
.filter(|r| r.dst != Dst::Internet)
|
||
.map(move |r| {
|
||
format!(
|
||
"{} {:?} {} {:?} {:?} {:?}",
|
||
p.name, r.direction, r.src, r.dst, r.proto, r.ports
|
||
)
|
||
})
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
fn check_p1(w: &World, c: &roads::Compiled) -> Result<(), TestCaseError> {
|
||
for plan in c.plans.values() {
|
||
let h = dev_of_key(w, &plan.device);
|
||
for rule in &plan.firewall.rules {
|
||
let (src, slen) = parse_net(&rule.src.to_string()).unwrap();
|
||
prop_assert_eq!(
|
||
slen,
|
||
32,
|
||
"a firewall source wider than one device: {:?}",
|
||
rule
|
||
);
|
||
let d = dev_of_addr(w, src);
|
||
prop_assert!(
|
||
d.is_some(),
|
||
"a firewall source that is no device: {:?}",
|
||
rule
|
||
);
|
||
let d = d.unwrap();
|
||
// R-10: that source is on its own peer, as exactly its /32, so no other peer can send from it.
|
||
let own = plan.peers.iter().find(|p| p.address.to_string() == ip(src));
|
||
prop_assert!(
|
||
own.is_some_and(|p| p
|
||
.allowed_ips
|
||
.iter()
|
||
.any(|n| n.to_string() == format!("{}/32", ip(src)))),
|
||
"{}: source {} has no peer of its own",
|
||
plan.name,
|
||
ip(src)
|
||
);
|
||
match rule.dst {
|
||
Dst::Internet => {
|
||
prop_assert!(
|
||
w.devs[h].exit,
|
||
"{} forwards to the internet but is no exit",
|
||
plan.name
|
||
);
|
||
prop_assert!(
|
||
may_exit(w, 0, d, h),
|
||
"{}: d{d} exits through it without a road",
|
||
plan.name
|
||
);
|
||
}
|
||
Dst::Net(n) => {
|
||
let (net, len) = parse_net(&n.to_string()).unwrap();
|
||
match rule.direction {
|
||
Direction::In => prop_assert!(
|
||
net == dev_addr(h) && len == 32,
|
||
"an in rule not to the device itself"
|
||
),
|
||
Direction::Forward => {
|
||
let routed = w.devs[h]
|
||
.route
|
||
.is_some_and(|(rn, rl)| len >= rl && in_prefix(net, rn, rl));
|
||
prop_assert!(
|
||
routed,
|
||
"{} forwards to {n}, which it does not route",
|
||
plan.name
|
||
);
|
||
}
|
||
}
|
||
let last = net | !mask(len);
|
||
let samples = [net, last, net + (last - net) / 2];
|
||
let ports: Vec<(&str, u16)> = match (rule.proto, rule.ports) {
|
||
(roads::ports::Proto::Any, _) => vec![
|
||
("tcp", 1),
|
||
("tcp", 443),
|
||
("tcp", 65535),
|
||
("udp", 53),
|
||
("icmp", 0),
|
||
],
|
||
(p, Some([lo, hi])) => {
|
||
let p = if p == roads::ports::Proto::Udp {
|
||
"udp"
|
||
} else {
|
||
"tcp"
|
||
};
|
||
vec![(p, lo), (p, hi), (p, lo + (hi - lo) / 2)]
|
||
}
|
||
(p, None) => {
|
||
let p = match p {
|
||
roads::ports::Proto::Udp => "udp",
|
||
roads::ports::Proto::Icmp => "icmp",
|
||
_ => "tcp",
|
||
};
|
||
vec![(p, 1), (p, 65535)]
|
||
}
|
||
};
|
||
for a in samples {
|
||
for (proto, port) in &ports {
|
||
prop_assert!(
|
||
may_reach(w, 0, d, a, proto, *port),
|
||
"{}: rule {:?} lets d{d} reach {}:{proto}/{port}, which no live road allows",
|
||
plan.name,
|
||
rule,
|
||
ip(a)
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// Sending side: every allowed IP is exactly what a live road names (no supernet, QA R-02).
|
||
let me = h;
|
||
for peer in &plan.peers {
|
||
let p = dev_of_key(w, &peer.key);
|
||
for n in &peer.allowed_ips {
|
||
let text = n.to_string();
|
||
if text == "0.0.0.0/0" || text == "::/0" {
|
||
prop_assert!(
|
||
w.devs[p].exit && may_exit(w, 0, me, p),
|
||
"{}: a default route to d{p} without a road",
|
||
plan.name
|
||
);
|
||
continue;
|
||
}
|
||
let (net, len) = parse_net(&text).unwrap();
|
||
if len == 32 && net == dev_addr(p) {
|
||
let related = w.roads.iter().any(|r| {
|
||
live(r, 0) && {
|
||
let s = subj_devs(w, &r.subject);
|
||
let host = match &r.object {
|
||
Some(Obj::Device(x))
|
||
| Some(Obj::Service(x))
|
||
| Some(Obj::Exit(x)) => Some(*x),
|
||
Some(Obj::Subnet(sn, sl)) => (0..w.devs.len()).find(|&i| {
|
||
w.devs[i]
|
||
.route
|
||
.is_some_and(|(rn, rl)| *sl >= rl && in_prefix(*sn, rn, rl))
|
||
}),
|
||
None => None,
|
||
};
|
||
(s.contains(&me) && host == Some(p))
|
||
|| (s.contains(&p) && host == Some(me))
|
||
}
|
||
});
|
||
prop_assert!(
|
||
related,
|
||
"{}: peer d{p} with no road between them",
|
||
plan.name
|
||
);
|
||
continue;
|
||
}
|
||
let named = w.roads.iter().any(|r| {
|
||
live(r, 0)
|
||
&& r.verb == Verb::Reach
|
||
&& r.object == Some(Obj::Subnet(net, len))
|
||
&& subj_devs(w, &r.subject).contains(&me)
|
||
});
|
||
prop_assert!(
|
||
named,
|
||
"{}: allowed IP {text} on d{p} that no road names exactly",
|
||
plan.name
|
||
);
|
||
prop_assert!(
|
||
w.devs[p]
|
||
.route
|
||
.is_some_and(|(rn, rl)| len >= rl && in_prefix(net, rn, rl)),
|
||
"{text} on a peer that does not route it"
|
||
);
|
||
}
|
||
}
|
||
// Custom raw blocks never become peers (QA R-40): checked above, since no road names 0.0.0.0/0 for them.
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
proptest! {
|
||
#![proptest_config(ProptestConfig { cases: 5_000, max_shrink_iters: 10_000, failure_persistence: None, .. ProptestConfig::default() })]
|
||
|
||
#[test]
|
||
fn p1_no_plan_grants_what_no_road_grants(bytes in proptest::collection::vec(any::<u8>(), 64..400)) {
|
||
CASES.fetch_add(1, Ordering::Relaxed);
|
||
let w = world(&bytes);
|
||
let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect();
|
||
let store = to_store(&w, &all, now());
|
||
let c = compile(&store, now());
|
||
prop_assert!(c.has_plans(), "the generated snapshots are valid: {:?}", c.problems.iter().filter(|p| !p.path.starts_with("roads/")).collect::<Vec<_>>());
|
||
check_p1(&w, &c)?;
|
||
let rules: usize = c.plans.values().map(|p| p.firewall.rules.len()).sum();
|
||
let allowed: usize = c.plans.values().map(|p| p.allowed_ips().count()).sum();
|
||
P1_RULES.fetch_add(rules, Ordering::Relaxed);
|
||
P1_ALLOWED.fetch_add(allowed, Ordering::Relaxed);
|
||
if rules > 0 { P1_WITH_RULES.fetch_add(1, Ordering::Relaxed); }
|
||
let n = P1_CASES.fetch_add(1, Ordering::Relaxed) + 1;
|
||
if n.is_multiple_of(5_000) {
|
||
eprintln!("p1: {n} cases, {} with at least one firewall rule, {} rules and {} allowed IPs checked against the oracle",
|
||
P1_WITH_RULES.load(Ordering::Relaxed), P1_RULES.load(Ordering::Relaxed), P1_ALLOWED.load(Ordering::Relaxed));
|
||
}
|
||
|
||
// P-7: explain agrees with the receiving side's firewall, device by device.
|
||
let devs = store.devices.as_ref().unwrap();
|
||
for a in 0..w.devs.len() {
|
||
for b in 0..w.devs.len() {
|
||
if a == b { continue; }
|
||
let ka = DeviceKey::new(&dev_key(a)).unwrap();
|
||
let kb = DeviceKey::new(&dev_key(b)).unwrap();
|
||
let why = roads::explain(&c, devs, &ka, &roads::Place::Device(kb.clone()));
|
||
let fw = c.plans[&kb].firewall.rules.iter().any(|r| r.direction == Direction::In && r.src.to_string() == format!("{}/32", ip(dev_addr(a))));
|
||
prop_assert_eq!(!why.is_empty(), fw, "explain d{} -> d{} says {:?}", a, b, why);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
proptest! {
|
||
#![proptest_config(ProptestConfig { cases: 1_000, failure_persistence: None, .. ProptestConfig::default() })]
|
||
|
||
#[test]
|
||
fn p6v6_ipv6_compiles_like_ipv4(bytes in proptest::collection::vec(any::<u8>(), 64..400)) {
|
||
CASES.fetch_add(1, Ordering::Relaxed);
|
||
let w = world(&bytes);
|
||
let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect();
|
||
let v4 = store_parts(&w, &all, now());
|
||
let v6 = embed_parts(v4.clone());
|
||
prop_assert!(!v6.2.contains("\"100.96."), "the device list was not embedded");
|
||
let s4 = Store::from_parts(&v4.0, Some(v4.1.as_bytes()), Some(v4.2.as_bytes()));
|
||
let s6 = Store::from_parts(&v6.0, Some(v6.1.as_bytes()), Some(v6.2.as_bytes()));
|
||
let (c4, c6) = (compile(&s4, now()), compile(&s6, now()));
|
||
prop_assert!(c6.has_plans(), "the IPv6 snapshots are valid: {:?}", c6.problems.iter().filter(|p| !p.path.starts_with("roads/")).collect::<Vec<_>>());
|
||
let key = |p: &roads::Problem| (p.path.clone(), p.field.clone(), p.code, p.severity);
|
||
let k4: BTreeSet<_> = c4.problems.iter().map(key).collect();
|
||
let k6: BTreeSet<_> = c6.problems.iter().map(key).collect();
|
||
prop_assert_eq!(k4, k6, "IPv4 and IPv6 report different problems");
|
||
for (k, p4) in &c4.plans {
|
||
prop_assert_eq!(normal(p4, true), normal(&c6.plans[k], false), "{} compiles differently in IPv6", p4.name);
|
||
}
|
||
}
|
||
}
|
||
|
||
proptest! {
|
||
#![proptest_config(ProptestConfig { cases: 500, failure_persistence: None, .. ProptestConfig::default() })]
|
||
|
||
#[test]
|
||
fn invalid_and_expired_roads_change_no_byte(bytes in proptest::collection::vec(any::<u8>(), 64..400), pick in any::<prop::sample::Index>(), expired in any::<bool>()) {
|
||
CASES.fetch_add(1, Ordering::Relaxed);
|
||
let w = world(&bytes);
|
||
let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect();
|
||
let base = compile(&to_store(&w, &all, now()), now());
|
||
// Copy one road, then make the copy invalid or expired, under a fresh id.
|
||
let mut extra = w.roads.get(pick.index(w.roads.len().max(1))).cloned().unwrap_or(R {
|
||
subject: Subj::Person(0), verb: Verb::Reach, object: Some(Obj::Subnet(BASE, 22)), until: None, ports: None, classic: None, invalid: false,
|
||
});
|
||
if expired { extra.until = Some(if extra.until == Some(0) { -5 } else { 0 }); extra.invalid = false; } else { extra.invalid = true; }
|
||
let mut with: Vec<(usize, &R)> = all.clone();
|
||
with.push((99_999, &extra));
|
||
let c = compile(&to_store(&w, &with, now()), now());
|
||
for (k, p) in &base.plans {
|
||
prop_assert_eq!(p.to_json(), c.plans[k].to_json(), "an {} road changed {}", if expired { "expired" } else { "invalid" }, p.name);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn removing_a_road_or_waiting_never_adds_a_rule(bytes in proptest::collection::vec(any::<u8>(), 64..400), pick in any::<prop::sample::Index>()) {
|
||
CASES.fetch_add(1, Ordering::Relaxed);
|
||
let w = world(&bytes);
|
||
let all: Vec<(usize, &R)> = w.roads.iter().enumerate().collect();
|
||
let store = to_store(&w, &all, now());
|
||
let full = rule_set(&compile(&store, now()));
|
||
// P-4: later is never wider (exit rules excluded: resolving an exit conflict is allowed to add one).
|
||
for later in [1, 2, 86_401] {
|
||
let l = rule_set(&compile(&store, now() + SignedDuration::from_secs(later)));
|
||
prop_assert!(l.is_subset(&full), "waiting {}s added {:?}", later, l.difference(&full).collect::<Vec<_>>());
|
||
}
|
||
// P-3: one road fewer is never wider.
|
||
if !w.roads.is_empty() {
|
||
let drop = pick.index(w.roads.len());
|
||
let fewer: Vec<(usize, &R)> = all.iter().copied().filter(|(i, _)| *i != drop).collect();
|
||
let f = rule_set(&compile(&to_store(&w, &fewer, now()), now()));
|
||
prop_assert!(f.is_subset(&full), "removing road {} added {:?}", drop, f.difference(&full).collect::<Vec<_>>());
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn zz_report_case_count() {
|
||
// Runs in the same binary; the count is only complete when the properties ran first, so it is printed,
|
||
// not asserted.
|
||
eprintln!(
|
||
"least_privilege: {} property cases so far in this process",
|
||
CASES.load(Ordering::Relaxed)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn the_oracle_catches_a_wider_rule() {
|
||
// The property would fail if the compiler emitted a supernet: check the oracle on a hand-made world
|
||
// whose only road grants 10.0.0.0/24, against a rule for 10.0.0.0/23 (QA R-02).
|
||
let w = World {
|
||
people: 1,
|
||
groups: vec![],
|
||
devs: vec![
|
||
Dev {
|
||
owner: Some(0),
|
||
classic: false,
|
||
exit: false,
|
||
relay: false,
|
||
route: None,
|
||
service: None,
|
||
},
|
||
Dev {
|
||
owner: None,
|
||
classic: false,
|
||
exit: false,
|
||
relay: false,
|
||
route: Some((BASE, 22)),
|
||
service: None,
|
||
},
|
||
],
|
||
roads: vec![R {
|
||
subject: Subj::Person(0),
|
||
verb: Verb::Reach,
|
||
object: Some(Obj::Subnet(BASE, 24)),
|
||
until: None,
|
||
ports: None,
|
||
classic: None,
|
||
invalid: false,
|
||
}],
|
||
};
|
||
assert!(may_reach(&w, 0, 0, BASE + 255, "tcp", 443));
|
||
assert!(
|
||
!may_reach(&w, 0, 0, BASE + 256, "tcp", 443),
|
||
"10.0.1.0 is outside the /24"
|
||
);
|
||
assert!(!may_reach(&w, 1, 0, BASE, "tcp", 443) || w.roads[0].until.is_none());
|
||
}
|