69e3a9377d
A firewall sees an address and a port, never a hostname, so a road to photos.home.arpa compiled to home-server:443 and also opened git.home.arpa there. Rules are now per service: - devices.json services may carry their own mesh address (same rules as a device address, unique among all of them). A road to such a service compiles to that address only; the hosting device's plan lists it in the new field services[] so it answers on it, and DNS points there. - A road to a service that shares its address and a port with another service is refused (service.shared), naming the others, instead of opening both. Narrowing ports: to a port nobody else serves on that address is allowed. - A device: road reaches the whole device: its own address and its services' own addresses. No Ianitor identity check is needed for this. The home fixture gives photos its own address (100.96.1.2); tests that encoded the old host:port model are updated, three new snapshot fixtures cover the address rules, and the golden plans and pinned digest are regenerated. Mutation-checked: dropping the refusal, or ignoring the service address, each fails an F-01 test.
598 lines
21 KiB
Rust
598 lines
21 KiB
Rust
//! The two snapshots the compiler reads besides the roads: `directory.json` and `devices.json`
|
|
//! (docs/FORMATS.md). Both are strict: unknown fields are errors, and a *structural* error (bad JSON, a wrong
|
|
//! format, a malformed or duplicate id, key or address) means no plan is produced.
|
|
//!
|
|
//! A *dangling reference* is different (QA F-04): a group member or a device owner that is a well-formed id
|
|
//! but no longer a person in the directory. That is what deleting a person upstream leaves behind. It is
|
|
//! still an error, and reported, but it only removes that reference: the member leaves the group, the device
|
|
//! becomes ownerless (reached only by `device:` roads). Everybody else keeps their plans.
|
|
|
|
use crate::ids::{
|
|
DeviceKey, GroupId, Hostname, PersonId, clip, is_device_key, is_hostname, is_opaque_id,
|
|
};
|
|
use crate::net::{Addr, Net};
|
|
use crate::ports::PortSpec;
|
|
use crate::problem::Problem;
|
|
use crate::rules as r;
|
|
use serde::Deserialize;
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
|
|
pub const DIRECTORY_FILE: &str = "directory.json";
|
|
pub const DEVICES_FILE: &str = "devices.json";
|
|
pub const MAX_SNAPSHOT: usize = 4 * 1024 * 1024;
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Person {
|
|
pub id: PersonId,
|
|
pub name: String,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Group {
|
|
pub id: GroupId,
|
|
pub name: String,
|
|
pub members: BTreeSet<PersonId>,
|
|
}
|
|
|
|
/// The people directory snapshot, validated.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
pub struct Directory {
|
|
pub people: BTreeMap<PersonId, Person>,
|
|
pub groups: BTreeMap<GroupId, Group>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Service {
|
|
pub host: Hostname,
|
|
pub ports: Vec<PortSpec>,
|
|
/// The service's own mesh address on its device, if it has one. A firewall sees addresses and ports, not
|
|
/// hostnames, so only a service with its own address (or alone on its ports) can be granted by itself
|
|
/// (QA F-01).
|
|
pub address: Option<Addr>,
|
|
}
|
|
|
|
impl Service {
|
|
/// Where a road to this service sends traffic: its own address, or its device's.
|
|
pub fn endpoint(&self, device: &Device) -> Addr {
|
|
self.address.unwrap_or(device.address)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Device {
|
|
pub key: DeviceKey,
|
|
pub name: String,
|
|
pub owner: Option<PersonId>,
|
|
pub address: Addr,
|
|
/// A classic WireGuard peer: **not post-quantum**.
|
|
pub classic: bool,
|
|
pub exit: bool,
|
|
pub relay: bool,
|
|
pub routes: Vec<Net>,
|
|
pub services: Vec<Service>,
|
|
}
|
|
|
|
/// The device list, validated.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
pub struct Devices {
|
|
pub devices: BTreeMap<DeviceKey, Device>,
|
|
}
|
|
|
|
impl Devices {
|
|
pub fn by_name(&self, name: &str) -> Option<&Device> {
|
|
self.devices.values().find(|d| d.name == name)
|
|
}
|
|
|
|
/// The device serving `host`.
|
|
pub fn service(&self, host: &Hostname) -> Option<(&Device, &Service)> {
|
|
self.devices
|
|
.values()
|
|
.find_map(|d| d.services.iter().find(|s| &s.host == host).map(|s| (d, s)))
|
|
}
|
|
|
|
/// Every mesh address: each device's own and its services' own. Never goes direct (QA F-02).
|
|
pub fn mesh_addresses(&self) -> impl Iterator<Item = (&Device, Addr)> {
|
|
self.devices.values().flat_map(|d| {
|
|
std::iter::once((d, d.address)).chain(
|
|
d.services
|
|
.iter()
|
|
.filter_map(move |s| s.address.map(|a| (d, a))),
|
|
)
|
|
})
|
|
}
|
|
|
|
/// The one device whose routes cover `net`.
|
|
pub fn router_of(&self, net: &Net) -> Option<&Device> {
|
|
self.devices
|
|
.values()
|
|
.find(|d| d.routes.iter().any(|r| r.contains(net)))
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawDirectory {
|
|
format: u32,
|
|
people: Vec<RawPerson>,
|
|
#[serde(default)]
|
|
groups: Vec<RawGroup>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawPerson {
|
|
id: String,
|
|
name: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawGroup {
|
|
id: String,
|
|
name: String,
|
|
members: Vec<String>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawDevices {
|
|
format: u32,
|
|
devices: Vec<RawDevice>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawDevice {
|
|
key: String,
|
|
name: String,
|
|
#[serde(default)]
|
|
owner: Option<String>,
|
|
address: String,
|
|
#[serde(default)]
|
|
classic: bool,
|
|
#[serde(default)]
|
|
exit: bool,
|
|
#[serde(default)]
|
|
relay: bool,
|
|
#[serde(default)]
|
|
routes: Vec<String>,
|
|
#[serde(default)]
|
|
services: Vec<RawService>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawService {
|
|
host: String,
|
|
ports: Vec<String>,
|
|
#[serde(default)]
|
|
address: Option<String>,
|
|
}
|
|
|
|
fn read_json<T: for<'de> Deserialize<'de>>(path: &str, bytes: &[u8]) -> Result<T, Vec<Problem>> {
|
|
if bytes.len() > MAX_SNAPSHOT {
|
|
return Err(vec![Problem::error(
|
|
path,
|
|
None,
|
|
r::SNAPSHOT_JSON,
|
|
"larger than 4 MiB",
|
|
)]);
|
|
}
|
|
serde_json::from_slice(bytes).map_err(|e| {
|
|
vec![
|
|
Problem::error(
|
|
path,
|
|
None,
|
|
r::SNAPSHOT_JSON,
|
|
format!("not a valid snapshot: {e}"),
|
|
)
|
|
.at(e.line()),
|
|
]
|
|
})
|
|
}
|
|
|
|
/// A mesh address: one canonical IP address, never loopback, link-local, multicast, IPv4-embedding IPv6 or an
|
|
/// internet address, so an exit's `internet` rule can never cover a device or service of the mesh (QA F-08).
|
|
fn mesh_address(text: &str) -> Option<Addr> {
|
|
let a = text.parse::<std::net::IpAddr>().ok()?;
|
|
let n = Net::host(a);
|
|
(a.to_string() == text && !n.is_special() && !n.embeds_ipv4() && !n.reaches_internet())
|
|
.then_some(Addr(a))
|
|
}
|
|
|
|
fn not_mesh(text: &str) -> String {
|
|
format!(
|
|
"`{}` is not one private IP address (a mesh address is never loopback, link-local, multicast, embedded IPv4 or on the internet; use 100.64.0.0/10 or a ULA)",
|
|
clip(text)
|
|
)
|
|
}
|
|
|
|
fn good_name(s: &str) -> bool {
|
|
let n = s.chars().count();
|
|
(1..=100).contains(&n) && !s.chars().any(is_hidden_char) && s.trim() == s
|
|
}
|
|
|
|
/// Characters a name may not hold: controls (newlines included, so a name can never inject a line into an
|
|
/// exported config, QA R-42), line and paragraph separators, zero-width and bidi controls (QA R-34).
|
|
pub fn is_hidden_char(c: char) -> bool {
|
|
c.is_control()
|
|
|| matches!(c, '\u{2028}' | '\u{2029}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}')
|
|
}
|
|
|
|
/// A parsed snapshot and the dangling references dropped from it (errors that do not stop plans).
|
|
pub type Parsed<T> = Result<(T, Vec<Problem>), Vec<Problem>>;
|
|
|
|
impl Directory {
|
|
/// `Err`: a structural error, no directory. `Ok((dir, dangling))`: `dangling` lists the members left
|
|
/// out because they are not people in the directory.
|
|
pub fn parse(bytes: &[u8]) -> Parsed<Directory> {
|
|
let path = DIRECTORY_FILE;
|
|
let raw: RawDirectory = read_json(path, bytes)?;
|
|
let mut problems = Vec::new();
|
|
let mut dangling = Vec::new();
|
|
let mut e = |field: String, code, msg: String| {
|
|
problems.push(Problem::error(path, Some(&field), code, msg))
|
|
};
|
|
if raw.format != 1 {
|
|
e(
|
|
"format".into(),
|
|
r::SNAPSHOT_FORMAT,
|
|
format!("format {} is not 1", raw.format),
|
|
);
|
|
}
|
|
let mut dir = Directory::default();
|
|
for (i, p) in raw.people.iter().enumerate() {
|
|
let Some(id) = PersonId::new(&p.id) else {
|
|
e(
|
|
format!("people[{i}].id"),
|
|
r::DIRECTORY_ID,
|
|
format!(
|
|
"`{}` is not a person id: 1-64 of A-Z a-z 0-9 _ -",
|
|
clip(&p.id)
|
|
),
|
|
);
|
|
continue;
|
|
};
|
|
if !good_name(&p.name) {
|
|
e(
|
|
format!("people[{i}].name"),
|
|
r::DIRECTORY_NAME,
|
|
"a name is 1-100 characters on one line".into(),
|
|
);
|
|
}
|
|
if dir
|
|
.people
|
|
.insert(
|
|
id.clone(),
|
|
Person {
|
|
id,
|
|
name: p.name.clone(),
|
|
},
|
|
)
|
|
.is_some()
|
|
{
|
|
e(
|
|
format!("people[{i}].id"),
|
|
r::DIRECTORY_DUPLICATE,
|
|
format!("person `{}` is listed twice", p.id),
|
|
);
|
|
}
|
|
}
|
|
for (i, g) in raw.groups.iter().enumerate() {
|
|
let Some(id) = GroupId::new(&g.id) else {
|
|
e(
|
|
format!("groups[{i}].id"),
|
|
r::DIRECTORY_ID,
|
|
format!(
|
|
"`{}` is not a group id: 1-64 of A-Z a-z 0-9 _ -",
|
|
clip(&g.id)
|
|
),
|
|
);
|
|
continue;
|
|
};
|
|
if !good_name(&g.name) {
|
|
e(
|
|
format!("groups[{i}].name"),
|
|
r::DIRECTORY_NAME,
|
|
"a name is 1-100 characters on one line".into(),
|
|
);
|
|
}
|
|
let mut members = BTreeSet::new();
|
|
for (j, m) in g.members.iter().enumerate() {
|
|
match PersonId::new(m) {
|
|
Some(m) if dir.people.contains_key(&m) => {
|
|
if !members.insert(m.clone()) {
|
|
e(
|
|
format!("groups[{i}].members[{j}]"),
|
|
r::DIRECTORY_MEMBER,
|
|
format!("`{m}` is listed twice"),
|
|
);
|
|
}
|
|
}
|
|
Some(m) => dangling.push(Problem::error(
|
|
path,
|
|
Some(&format!("groups[{i}].members[{j}]")),
|
|
r::DIRECTORY_MEMBER_UNKNOWN,
|
|
format!(
|
|
"`{m}` is not a person in the directory (groups are flat: members are people); left out of the group"
|
|
),
|
|
)),
|
|
None => e(
|
|
format!("groups[{i}].members[{j}]"),
|
|
r::DIRECTORY_MEMBER,
|
|
format!(
|
|
"`{}` is not a person id: 1-64 of A-Z a-z 0-9 _ -",
|
|
clip(m)
|
|
),
|
|
),
|
|
}
|
|
}
|
|
if dir
|
|
.groups
|
|
.insert(
|
|
id.clone(),
|
|
Group {
|
|
id,
|
|
name: g.name.clone(),
|
|
members,
|
|
},
|
|
)
|
|
.is_some()
|
|
{
|
|
e(
|
|
format!("groups[{i}].id"),
|
|
r::DIRECTORY_DUPLICATE,
|
|
format!("group `{}` is listed twice", g.id),
|
|
);
|
|
}
|
|
}
|
|
if problems.is_empty() {
|
|
Ok((dir, dangling))
|
|
} else {
|
|
Err(problems)
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Devices {
|
|
/// `Err`: a structural error, no device list. `Ok((devices, dangling))`: `dangling` lists the owners
|
|
/// dropped because they are not people in `directory`; those devices are ownerless.
|
|
pub fn parse(bytes: &[u8], directory: Option<&Directory>) -> Parsed<Devices> {
|
|
let path = DEVICES_FILE;
|
|
let raw: RawDevices = read_json(path, bytes)?;
|
|
let mut problems = Vec::new();
|
|
let mut dangling = Vec::new();
|
|
let mut e = |field: String, code, msg: String| {
|
|
problems.push(Problem::error(path, Some(&field), code, msg))
|
|
};
|
|
if raw.format != 1 {
|
|
e(
|
|
"format".into(),
|
|
r::SNAPSHOT_FORMAT,
|
|
format!("format {} is not 1", raw.format),
|
|
);
|
|
}
|
|
let mut out = Devices::default();
|
|
let mut names = BTreeSet::new();
|
|
let mut addresses = BTreeSet::new();
|
|
let mut hosts = BTreeSet::new();
|
|
for (i, d) in raw.devices.iter().enumerate() {
|
|
let f = |k: &str| format!("devices[{i}].{k}");
|
|
let Some(key) = DeviceKey::new(&d.key).filter(|_| is_device_key(&d.key)) else {
|
|
e(
|
|
f("key"),
|
|
r::DEVICES_KEY,
|
|
format!(
|
|
"`{}` is not a Tessera device key: 43 characters of base64url",
|
|
clip(&d.key)
|
|
),
|
|
);
|
|
continue;
|
|
};
|
|
let name_ok = (1..=64).contains(&d.name.len())
|
|
&& d.name
|
|
.bytes()
|
|
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
|
|
if !name_ok {
|
|
e(
|
|
f("name"),
|
|
r::DEVICES_NAME,
|
|
format!(
|
|
"`{}` is not a device name: 1-64 of a-z 0-9 -",
|
|
clip(&d.name)
|
|
),
|
|
);
|
|
} else if !names.insert(d.name.clone()) {
|
|
e(
|
|
f("name"),
|
|
r::DEVICES_NAME,
|
|
format!("the name `{}` is used twice", d.name),
|
|
);
|
|
}
|
|
let owner = match &d.owner {
|
|
None => None,
|
|
Some(o) => match PersonId::new(o).filter(|_| is_opaque_id(o)) {
|
|
Some(p) if directory.is_none_or(|dir| dir.people.contains_key(&p)) => Some(p),
|
|
Some(p) => {
|
|
dangling.push(Problem::error(
|
|
path,
|
|
Some(&f("owner")),
|
|
r::DEVICES_OWNER_UNKNOWN,
|
|
format!(
|
|
"`{p}` is not a person in the directory; the device is ownerless until it gets an owner, and only `device:` roads reach it"
|
|
),
|
|
));
|
|
None
|
|
}
|
|
None => {
|
|
e(
|
|
f("owner"),
|
|
r::DEVICES_OWNER,
|
|
format!("`{}` is not a person id: 1-64 of A-Z a-z 0-9 _ -", clip(o)),
|
|
);
|
|
None
|
|
}
|
|
},
|
|
};
|
|
let address = match mesh_address(&d.address) {
|
|
Some(a) => {
|
|
if !addresses.insert(a.0) {
|
|
e(
|
|
f("address"),
|
|
r::DEVICES_ADDRESS,
|
|
format!("{a} is used twice"),
|
|
);
|
|
}
|
|
Some(a)
|
|
}
|
|
None => {
|
|
e(f("address"), r::DEVICES_ADDRESS, not_mesh(&d.address));
|
|
None
|
|
}
|
|
};
|
|
let mut routes = Vec::new();
|
|
for (j, rt) in d.routes.iter().enumerate() {
|
|
match Net::parse_canonical(rt) {
|
|
Ok(n)
|
|
if n.prefix_len() > 0
|
|
&& !n.is_special()
|
|
&& !n.embeds_ipv4()
|
|
&& !n.reaches_internet() =>
|
|
{
|
|
routes.push(n)
|
|
}
|
|
Ok(n) if n.prefix_len() > 0 => e(
|
|
format!("devices[{i}].routes[{j}]"),
|
|
r::DEVICES_ROUTE,
|
|
format!(
|
|
"{n} is not a private subnet (loopback, link-local, multicast, embedded IPv4 or internet); the internet is reached through an exit"
|
|
),
|
|
),
|
|
Ok(_) => e(
|
|
format!("devices[{i}].routes[{j}]"),
|
|
r::DEVICES_ROUTE,
|
|
"a route of /0 is an exit; set `exit: true` instead".into(),
|
|
),
|
|
Err(_) => e(
|
|
format!("devices[{i}].routes[{j}]"),
|
|
r::DEVICES_ROUTE,
|
|
format!("`{}` is not a canonical subnet", clip(rt)),
|
|
),
|
|
}
|
|
}
|
|
routes.sort();
|
|
routes.dedup();
|
|
let mut services = Vec::new();
|
|
for (j, s) in d.services.iter().enumerate() {
|
|
let Some(host) = Hostname::new(&s.host).filter(|_| is_hostname(&s.host)) else {
|
|
e(
|
|
format!("devices[{i}].services[{j}].host"),
|
|
r::DEVICES_SERVICE,
|
|
format!("`{}` is not a hostname", clip(&s.host)),
|
|
);
|
|
continue;
|
|
};
|
|
if !hosts.insert(host.clone()) {
|
|
e(
|
|
format!("devices[{i}].services[{j}].host"),
|
|
r::DEVICES_SERVICE,
|
|
format!("{host} is served by two devices"),
|
|
);
|
|
}
|
|
let mut ports = Vec::new();
|
|
for p in &s.ports {
|
|
match PortSpec::parse(p) {
|
|
Ok(p) => ports.push(p),
|
|
Err(m) => e(
|
|
format!("devices[{i}].services[{j}].ports"),
|
|
r::DEVICES_PORTS,
|
|
m,
|
|
),
|
|
}
|
|
}
|
|
if s.ports.is_empty() {
|
|
e(
|
|
format!("devices[{i}].services[{j}].ports"),
|
|
r::DEVICES_PORTS,
|
|
"a service lists the ports it serves".into(),
|
|
);
|
|
}
|
|
let field = format!("devices[{i}].services[{j}].address");
|
|
let address = match s.address.as_deref().map(mesh_address) {
|
|
None => None,
|
|
Some(Some(a)) => {
|
|
if !addresses.insert(a.0) {
|
|
e(field, r::DEVICES_ADDRESS, format!("{a} is used twice"));
|
|
}
|
|
Some(a)
|
|
}
|
|
Some(None) => {
|
|
e(
|
|
field,
|
|
r::DEVICES_ADDRESS,
|
|
not_mesh(s.address.as_deref().unwrap_or_default()),
|
|
);
|
|
None
|
|
}
|
|
};
|
|
services.push(Service {
|
|
host,
|
|
ports,
|
|
address,
|
|
});
|
|
}
|
|
services.sort_by(|a, b| a.host.cmp(&b.host));
|
|
let Some(address) = address else { continue };
|
|
let dev = Device {
|
|
key: key.clone(),
|
|
name: d.name.clone(),
|
|
owner,
|
|
address,
|
|
classic: d.classic,
|
|
exit: d.exit,
|
|
relay: d.relay,
|
|
routes,
|
|
services,
|
|
};
|
|
if out.devices.insert(key.clone(), dev).is_some() {
|
|
e(
|
|
f("key"),
|
|
r::DEVICES_DUPLICATE,
|
|
format!("the key {} is listed twice", key.short()),
|
|
);
|
|
}
|
|
}
|
|
// Routes may not overlap between devices, and no device address may sit inside a route.
|
|
let all: Vec<(&Device, &Net)> = out
|
|
.devices
|
|
.values()
|
|
.flat_map(|d| d.routes.iter().map(move |n| (d, n)))
|
|
.collect();
|
|
for (a, (da, na)) in all.iter().enumerate() {
|
|
for (db, nb) in all.iter().skip(a + 1) {
|
|
if da.key != db.key && na.overlaps(nb) {
|
|
e(
|
|
format!("devices.{}.routes", db.name),
|
|
r::DEVICES_OVERLAP,
|
|
format!("{nb} on {} overlaps {na} on {}", db.name, da.name),
|
|
);
|
|
}
|
|
}
|
|
for (d, a) in out.mesh_addresses() {
|
|
if na.contains_addr(&a.0) {
|
|
e(
|
|
format!("devices.{}.address", d.name),
|
|
r::DEVICES_ADDRESS,
|
|
format!("{a} of {} is inside the route {na} of {}", d.name, da.name),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
if problems.is_empty() {
|
|
Ok((out, dangling))
|
|
} else {
|
|
Err(problems)
|
|
}
|
|
}
|
|
}
|