Sparewall — Design#
Oct 9, 2026 · @Steven Pritchard
Sparewall is an open-source, image-based Linux firewall: a single node or an HA pair, configured from one versioned document, built from systemd, nftables and a small Rust coordinator.
Overview#
Sparewall turns a Linux box or VM into a firewall appliance that is upgraded and rolled back as a whole image, configured from one document, and run either standalone or as an active/standby pair. It targets homelabs and small offices first, without anything in its defaults or schema that is specific to one site.
Goals#
- Image-based and rollback-safe. The OS is a signed, versioned image; an upgrade is a reboot into the new image, and a rollback is a reboot into the old one.
- One source of truth. A single JSON/YAML document describes the whole deployment. Every change is validated, applied with compensating recovery if a step fails, and reverted automatically unless confirmed.
- HA when wanted, not required. The same image and document shape run one node or an HA pair; growing from one to two nodes is invisible to clients.
- Portable. Runs on VMs and physical hardware, with one NIC or several, VLAN trunks, LACP or active-backup bonds.
- Built from standard parts. systemd (networkd, Varlink), nftables, keepalived, conntrackd, WireGuard, Podman; the only new code is the coordinator and its CLI.
- Entirely open source, including everything the project builds.
- Swappable services. DHCP, DNS, certificate issuance, log forwarding, metrics and backup are pluggable providers behind an implementation-neutral schema.
Scope of the first releases#
| In scope | Later |
|---|---|
| Standalone node or HA pair (active/standby) | More than two nodes, active-active |
| VLANs, LACP and active-backup bonds, VM or physical ports | |
| One WAN | Multiple WANs, WAN failover, load balancing |
| IPv4 routing, NAT and DHCP; IPv6 routing (0.6.0): DHCPv6, SLAAC or static on the WAN, delegated or static /64s with router advertisements inside | DHCPv6 on inside networks (#217), tunnels for sites without native IPv6 (#218); NAT66 and IPv6 forwards are not planned |
| Zone-based firewall with raw nftables rules | IPsec, captive portal, multi-tenancy |
| WireGuard remote-access VPN; site-to-site tunnels with static WireGuard peers; WireGuard clients for chosen networks' egress | Site-to-site beyond static WireGuard peers (dynamic routing, many sites) |
| Optional recursive DNS (Unbound), NTP, logging, metrics, health endpoints | DHCP-to-DNS updates (DDNS), IDS/IPS (Suricata), dynamic routing (BGP, OSPF) |
sparewall CLI and the Varlink API; a first web UI and HTTP API (0.3.0) |
A web UI and HTTP API covering every CLI operation (milestone 7, which 1.0 waits for) |
Design principles#
- The coordinator is the only writer of daemon configuration; people and tools change the document, never the files.
- Kernel-adjacent daemons on the host, applications in containers. nftables, keepalived, conntrackd and networkd run on the host; Kea, the resolver and other application services run as Podman Quadlet containers.
- Every change can be undone: configuration generations with confirm-or-revert, and image deployments with
bootc rollback. - Secure by default, debuggable with standard tools: one network namespace for the data plane, systemd sandboxing for management services, SELinux enforcing.
- Intent over implementation: the document says what a service must do; providers decide how a particular daemon does it.
Architecture#
Each node has four layers: a read-only bootc image, host services that touch kernel networking state, containers for application services, and one coordinator that is the only writer of their configuration.
[embedded content: node architecture · 4 layers, one coordinator]
Clients hand the coordinator a document; it renders, tests, applies and, if unconfirmed, reverts every layer together. In a pair, the second node is identical and is reached only through a WireGuard tunnel on the sync VLAN.
Platform: a bootc image#
Sparewall ships as a bootable container image built from a Containerfile on a Fedora bootc base. Nodes bootc upgrade to new images and bootc rollback to old ones; nothing is installed on a running node.
Base OS path#
- Now: Fedora bootc. It carries systemd 261+ (Fedora 45 is getting 262), whose Varlink interfaces the coordinator depends on, with
systemd-networkdas an ordinary subpackage. - Next: CentOS Stream 10 bootc with the CentOS Hyperscale SIG's systemd rebuilds (261.3 at the time of writing), tested in CI as a second image variant.
- Long term: CentOS Stream 11 or AlmaLinux 11 bootc once they are released, for a longer support window. Each move is a
FROMchange plus package-name fixes, thenbootc switchon each node in the normal rolling-upgrade order. - Stock Fedora CoreOS is not used: it ships NetworkManager and deliberately omits systemd-networkd.
Filesystem semantics#
| Path | Behaviour | Holds |
|---|---|---|
/usr |
Read-only, versioned with the image | OS, daemons, coordinator, Quadlet units, pinned container image references |
/etc |
Mutable with a 3-way merge on upgrade by default; Sparewall aims to make it transient once identity provisioning is proven | Nothing site-specific long term |
/var |
Persistent, shared across deployments | Configuration generations, secrets, leases, container storage, logs |
/run |
Volatile, rebuilt every boot | Daemon configs rendered by the coordinator |
Image contents#
systemd-networkd, nftables, keepalived, conntrack-tools, chrony, ulogd2, podman, wireguard-tools, restic, the coordinator (sparewalld) and CLI (sparewall), Quadlet units for the containerized services with their images pinned by digest, troubleshooting tools (tcpdump, conntrack, ethtool, nft, wg), and a built-in bootstrap configuration that keeps a management interface reachable before any config has been applied.
Deployment targets and the port model#
The same image and the same config document run on a VM fed a VLAN trunk, a single-NIC mini PC, or a multi-NIC box with bonds, including a mixed pair of one VM and one physical node. The document makes this possible by separating ports (physical, per node) from networks (logical, shared); zones, gateway addresses, DHCP and policy only ever reference networks.
- A port is a per-node role name (
uplink,wan,mgmt) bound to hardware: one NIC matched by permanent MAC or PCI path, or a bond of several NICs. - A network is one L2 segment: a port role, an optional VLAN ID, per-node addresses, and (in a pair) a gateway address (
vip) and VRRP ID.extra_vipsadds addresses that move with the gateway address, for services that need their own public address (forwards, SNAT). Management and sync are networks with a role. - Because networks reference port roles,
uplinkcan be a virtio trunk on one node and an LACP bond on the other.
ports:
fw1:
uplink: { nic: "52:54:00:aa:00:01" }
fw2:
uplink: { bond: { members: ["9c:6b:00:00:00:01", "9c:6b:00:00:00:02"], mode: 802.3ad } }
networks:
wan: { port: uplink, vlan: 10, role: wan,
addresses: { fw1: 10.0.10.2/24, fw2: 10.0.10.3/24 },
vip: 203.0.113.1/29, vrid: 10, gateway: 203.0.113.6 }
users: { port: uplink, vlan: 20,
addresses: { fw1: 192.0.2.2/24, fw2: 192.0.2.3/24 }, vip: 192.0.2.1/24, vrid: 20 }
sync: { port: uplink, vlan: 4000, role: sync,
addresses: { fw1: 10.255.0.1/30, fw2: 10.255.0.2/30 } }
Port shapes#
| Shape | Rendered as | Notes |
|---|---|---|
| Single NIC, untagged | .link (stable name) + .network |
One network per NIC |
| Single NIC, VLAN trunk | NIC .network with VLAN=, one VLAN .netdev and .network per network |
Typical for VMs and one-port mini PCs |
| Bond, LACP | Bond .netdev with Mode=802.3ad, LACPTransmitRate=, TransmitHashPolicy=, MIIMonitorSec=; members join with Bond= |
Switch needs a matching LAG; VLANs stack on the bond |
| Bond, active-backup | Same with Mode=active-backup, optional PrimarySlave= |
No switch configuration |
| Several independent NICs | One .link/.network per NIC, each its own port role |
For example wan on its own NIC |
MTU (parent and VLAN) and NIC offload overrides are per port.
On libvirt with Open vSwitch#
- Give each VM a fixed MAC in its domain XML so port matching stays stable.
- Pass VLANs as a trunk on one virtio interface (OVS
vlan_mode=trunkwith an explicittrunkslist), with virtio multiqueue enabled. - Do not apply libvirt's
clean-trafficnwfilter: it blocks the extra MACs and addresses that gateway addresses need. - VRRP adverts use link-local multicast, which OVS floods; switch instances to
unicast_peerif anything in the path filters it. - PCI passthrough or SR-IOV remain options where virtio becomes the bottleneck.
- The image ships the QEMU guest agent, which starts when the domain has its channel (libvirt adds one by default) and never on hardware. Snapshots can then quiesce (
virsh snapshot-create-as --quiesce), andvirsh domifaddr --source agentshows the node's addresses. The agent answers only freeze and thaw, fstrim, time, shutdown and read-only queries:guest-exec, file access, SSH keys, passwords and suspend are refused, by an allow list inqemu-guest-agent.service.d/50-sparewall.conf.
Mixed pairs#
Give the larger node the higher VRRP priority and keep nopreempt, so the pair does not bounce when that node flaps. Size connection tracking, Kea and nft sets for the smaller node, since it must carry the full load after a failover.
The configuration document#
One versioned document describes a whole deployment, one node or a pair, and the coordinator is the only thing that turns it into daemon configuration. It is JSON on the wire and accepted or emitted as JSON or YAML; a JSON Schema shipped in the image validates it.
Conventions#
- One document per deployment. Shared values appear once; per-node values are keyed by node name (
addresses: { fw1: …, fw2: … }). - Collections of named things are maps keyed by name, never arrays: zones, networks, policies, rules, raw entries, VPN peers, DHCP reservations. Adding one item is then a one-entry merge.
- Explicit order where order matters. Rules within a zone pair and raw entries at one hook carry an
ordernumber with gaps (100, 200, …), so a new entry can be inserted without renumbering. - Arrays only for value lists where replacing the whole list is expected: bond members, a network's addresses, DNS servers.
- No secrets in the document. Secrets are referenced by name (
secret:dns-tsig) and live in the coordinator's secret store. - Types come from the schema, never from YAML guessing; parsers are YAML 1.2.
- Canonical form. Exported documents use a fixed key order and formatting, so files in git diff cleanly and the content hash is stable.
Schema reference (top level)#
| Key | Holds | Per node? |
|---|---|---|
schema |
The oldest schema revision that reads the document, set by the coordinator | No |
cluster |
Node names (one or two), VRRP timing, which network carries sync | No |
management |
Which network is management; anti-lockout switch and who it admits (sources) |
No |
ports |
Per node: port role → NIC (MAC or PCI path) or bond (members, mode, LACP options); MTU; offload overrides | Yes |
networks |
Name → port role, VLAN, role (wan, management, sync, service), addresses, vip, extra_vips, vrid, MTU, WAN DHCP client |
Addresses per node |
zones |
Name → member networks; self is built in |
No |
objects |
Named address and port sets; dynamic sets filled by networkd | No |
policy |
"from->to" → default action, NAT mode, rules (named, ordered) |
No |
forwards |
Named inbound port forwards (DNAT) | No |
raw |
Named raw nft statements with a hook point and order | No |
dhcp |
Per network: pools, reservations, options, lease time; provider; HA mode | No |
dns |
Enabled flag, provider, listening networks, forwarders or recursion, local records | No |
ntp |
Upstream servers; networks to serve time on | No |
vpn |
Remote-access WireGuard instances and their peers | No |
tls |
Certificates: names, ACME settings, DNS-01 provider | No |
logging |
Rule-log defaults; remote forwarding target | No |
metrics |
Mode: external scrape, local Prometheus, or off; retention | No |
backup |
Enabled flag, restic repository, schedule, credentials reference | No |
updates |
Channel, mode (manual or windowed), maintenance window and its length, background check | No |
provider_options |
Per-provider passthrough settings | No |
Users, API tokens and secrets are coordinator state, not document content.
A minimal document#
schema: 1
cluster: { nodes: [fw1, fw2], sync_network: sync }
management: { network: mgmt }
zones:
wan: { networks: [wan] }
users: { networks: [users] }
policy:
users->wan: { action: accept, nat: masquerade }
wan->self:
action: drop
rules:
ssh-admin: { order: 100, proto: tcp, dport: 22, src: "@admin_nets", action: accept }
dhcp:
users: { pool: 192.0.2.100-192.0.2.199, reservations: {} }
dns: { enabled: true, provider: unbound }
(ports and networks as in the previous section.)
Configuration lifecycle#
Every change, whether a full document or a one-line set, becomes a numbered generation that is validated, rendered and applied, and automatically reverted unless confirmed. In a pair, the coordinator then pushes it to the peer and tracks whether both nodes hold and run the same configuration.
Apply, confirm, roll back#
- Validate: the JSON Schema, then semantic checks (overlapping subnets, reused VRIDs, rules naming missing zones, pools outside their subnet, capabilities the chosen providers lack).
- Render generation N: networkd files, the nft script, keepalived and conntrackd configs, provider configs, WireGuard configs.
- Dry-run every artifact with its own checker:
nft -c -f, the DHCP provider's config test,keepalived --config-test. A change that fails steps 1–3 changes nothing on the node. - Store N under
/var/lib/sparewall/generations/N/, then activate it: reload only what changed, in the order given in What is atomic. - Record N as the active generation in
state.json. Only now is N the node's configuration: see Durable intent and restarts. - Confirm window: unless
Confirm(N)arrives within the requested time, the coordinator re-activates the last confirmed generation. A change that cuts off management access therefore reverts itself. - Peer: once confirmed, the generation is pushed to the peer; see Pair ordering.
Generations are kept on disk with their author, timestamp and diff summary; sparewall history lists them and sparewall rollback N returns to one. A rollback is itself a new generation carrying generation N's document, so the generation it replaces stays in history and, in a pair, the rollback is pushed to the peer like any other change (a change still in its confirm window is simply discarded, since it was never pushed).
What is atomic#
Two guarantees differ in strength.
- The firewall is atomic. The nft ruleset is replaced in one kernel transaction: packets see either the whole old ruleset or the whole new one, never a mixture, and a load the kernel rejects leaves the old one in place.
- A configuration change is sequential, with compensating recovery. The other layers have no shared transaction, so activation changes them one after another. Each step is skipped if its part of the rendering is unchanged:
- the nft ruleset, so new interfaces are filtered as soon as they appear;
- sysctls;
- links (networkd), then the sysctls again for links that just appeared;
- provider configuration files;
- links whose networkd-filled nft sets were recreated, then service reloads and restarts (providers, keepalived, conntrackd).
Between steps, the node runs a mixture: for example, the new firewall with the old addresses. The firewall goes first so that interfaces a change adds are filtered from the moment they appear. Steps take from milliseconds (nft) to a few seconds (a provider restart).
If a step fails, the coordinator compensates: it activates the previous generation again, against what the failed attempt may have changed, and reports the failure (ApplyFailed, the applied health check). If that also fails, the node is left running a mixture it reports as apply failed. Health is then failed, so in a pair keepalived moves the gateway addresses to the peer. The outcome is therefore not binary: the old configuration, the new one, or a reported mixture.
What happens next depends on what failed:
- A failed new change is not retried. The admin applies a fix or rolls back.
- A failed revert of an expired pending change is retried every second until it succeeds. The pending change stays recorded, and health stays failed, until it does.
Recording the change (step 5) can fail too, after activation succeeded, if state.json cannot be written. The node must then run whatever the readable record names:
- The write failed before its rename. The previous record still stands, and no record ever named the change. The coordinator re-activates the previous generation and reports
ApplyFailed. A local change is set aside. A peer's generation is rejected, or pushed again on the next sync pass if the rejection cannot be recorded either. - The rename happened but syncing the directory failed. The new record is readable but may not survive a power loss. The coordinator writes the previous record back and runs what is then readable: the previous generation, or the change itself if the old record could not be written back. In that case the change's confirm window, or the peer's confirmation, still applies. The change is set aside or rejected only if the previous record was written back cleanly. Otherwise a record naming it may still reach the disk, so it is kept.
Durable intent and restarts#
state.json is the only record of what a node should run. It holds the active generation, the last confirmed one and any pending change with its revert target and deadline, and it is replaced atomically (written aside, then renamed). The order of steps 4 and 5 gives the rules below.
The rules hold across a power loss as well as a coordinator crash. Every file is written to a temporary name, fsynced and renamed, and then the directory is fsynced. A generation's directory and its entry in generations/ are fsynced before any state record may name it. That happens on every attempt, including a retried push of a generation already stored, because a file that exists may not have reached the disk. So the on-disk order is the order of the steps.
- A generation is stored before it runs and becomes active only after it runs. A coordinator crash at any point before step 5 leaves
state.jsonnaming the previous generation, and at start-up the coordinator activates that from scratch (every layer, not just the changed ones). The new generation stays on disk without ever having been active. - A pending change does not survive a restart. If
state.jsonholds a pending change at start-up, the coordinator reverts to its revert target before activating anything. That applies both to the node's own unconfirmed change and to a peer's generation awaiting the peer's confirmation. A crash during a revert (activation done,state.jsonnot yet updated) therefore ends the same way. - Start-up re-renders the active generation with the running image's renderers, so an upgraded image applies its own rendering of the same document.
- Early boot (before udev and networkd start) installs files, sets sysctls and loads the firewall; the coordinator applies links and services once it starts.
A generation stored but never active must never block later changes, from this node or the peer (#24).
Pair ordering#
A change is applied first on the node it was submitted to, whether that is the MASTER or the BACKUP. It is pushed to the peer only once it is confirmed there. So the confirm window, which protects the admin's own access, always covers the node the admin is talking to, and the peer never runs a change the admin has not confirmed.
- Submitted to the BACKUP, the change is proven on the node carrying no traffic before the MASTER gets it. This is the recommended way to make risky changes.
- Submitted to the MASTER, it affects traffic at once, including the mixture while it activates. If activation fails and so does the compensation, health fails and the BACKUP, still on the old configuration, takes over.
On the peer, a pushed generation goes through the same validation, dry-run and activation. If activation fails partway, the peer compensates as above, then rejects the generation. A rejected generation is not pushed into the same failure again; a newer generation or sparewall sync retries. Otherwise the peer runs it pending:
- The pushing node confirms it over a new connection through the tunnel, proving the change left the tunnel working.
- The peer accepts the confirmation only if the change made no further health check fail.
- Unconfirmed within two minutes, or across a restart of the peer's coordinator, it reverts.
Until it is confirmed the peer does not report it as applied, so the pair shows applying and an upgrade waits. Changes are serialized: neither node pushes while either has a change pending, and the peer refuses a push that does not extend its active generation.
Changes to the sync link reverse the order, because they alter the tunnel the push travels through. That covers the cluster's nodes and sync settings (sync_network, sync_port, sync_keys), the sync network, and each node's port carrying it, and a rollback across such a change too. Such a change must change nothing else, and it cannot be made while another change is pending. The accepting node decides; the peer only follows:
- The accepting node stores the change without running it.
- It pushes the change, gated, through the current tunnel, and the peer runs it pending.
- Only then does the accepting node run it, pending.
- Prepare: it confirms the change to the peer over the new tunnel. The peer checks that nothing new fails, as for any gated push. Instead of keeping the change, it holds it in doubt.
- Decide: the accepting node keeps the change once the peer has prepared it and, if a confirm window was asked for, the admin has confirmed it, in either order. Otherwise it reverts: at its deadline, which is 30 seconds after the peer's, at a restart, or on a rollback. The decision is recorded in its state, and that record stays until the peer is seen to have followed it.
- No other change is accepted while the decision is pending, on either node. On the peer,
sparewall sync --fromis the explicit way out. - A kept decision is shown to the peer only once it is on disk. If writing it fails, the node shows the change as still pending until the write is durable. That includes after a restart: the node syncs its state record at boot first.
- Follow: the in-doubt peer reads the decision record from the accepting node's status and does the same. History may have been pruned since, so the peer never takes a missing generation as a revert.
- In doubt, the peer never reverts on its own deadline or at a restart.
- While the accepting node cannot be reached, the peer switches between the old and the new link every 30 seconds to find it. Only the sync link differs between the two, and health stays degraded, not failed, so the gateway addresses do not move.
A peer that never prepared the change cannot have been counted on, so it reverts at its own deadline as usual.
If the peer cannot take the change first (it is unreachable or an older release), nothing changes on either node. With the peer unreachable, --allow-diverge applies the change locally as before, and the other node needs the same change.
OS upgrades are a separate order: the BACKUP is upgraded first, then the MASTER after it fails over (see Releases, upgrades and versioning).
What a generation carries#
id: a number that increases across the pair, assigned by the node that accepted the change.hash: SHA-256 of the canonical document, so equal content always hashes equal.base: the generation it was derived from. Every change, and every push to the peer, is rejected ifbaseis no longer current, so nobody overwrites a change they have not seen.schema: the oldest schema revision that reads it: the newest revision among the fields it uses.
Pair sync states#
Each node reports a desired hash (the confirmed generation it holds) and an applied hash (what its daemons are verified to be running).
| State | Condition | Meaning |
|---|---|---|
| In sync | All four hashes equal, and neither node's history is missing the other's generations | Both nodes hold and run the same config |
| Applying | Desired equal, an applied hash differs, apply in progress | Normal for seconds after a change |
| Apply failed | Desired ≠ applied on a node after the apply finished | That node runs older config; alert |
| Behind | The peer's generation is an ancestor of the local one (even with equal content: after a change and its rollback, the peer still lacks both) | Push pending; retried automatically. Generations before the last are stored without being run |
| Diverged | Desired hashes differ and neither descends from the other | Changes were made on both sides; needs a decision |
Divergence policy#
- With the peer reachable, a change on either node is accepted and pushed at once.
- With the peer unreachable, a change requires
--allow-divergeand marks the pair diverged. - Nothing merges automatically. An admin resolves divergence with
sparewall sync --from <node>; the other side's generation stays in history.
Lease replication, connection-state sync and the OS image version are reported separately and never count toward config sync; differing images are expected midway through a rolling upgrade.
The coordinator and its Varlink API#
sparewalld is a Rust daemon that owns the configuration document, renders and applies it, coordinates with the peer, and exposes everything over Varlink. It talks Varlink to systemd where systemd offers it, and uses small adapters for daemons that do not.
What systemd exposes over Varlink#
| Interface | Used for | Since |
|---|---|---|
io.systemd.Network |
Describe links; reconfigure, renew or force-renew one link | Describe 257; link methods 261 |
io.systemd.Unit, io.systemd.Manager |
Unit status, transient units, reboot and soft-reboot | 261 |
io.systemd.Job |
List and cancel queued jobs | 261 |
io.systemd.Resolve, io.systemd.Resolve.Monitor |
Host-side lookups, DNS configuration events | Earlier releases |
Adapters for everything else#
| Component | Native control surface | The adapter |
|---|---|---|
| nftables | nft -f scripts, nft -j JSON |
Loads generated scripts; reads counters and set contents |
| keepalived | notify_fifo, D-Bus, signals |
Turns FIFO lines into events; triggers reloads |
| conntrackd | Its control socket via the conntrackd CLI |
Runs the failover sequence; reads statistics |
| Providers (Kea, Unbound, …) | Each daemon's own control interface | Implemented per provider (see Service providers) |
| WireGuard | Netlink | Reads per-peer handshake and traffic |
Adapters shell out to nft and conntrackd rather than reimplementing their netlink protocols, keeping low-level code in well-tested tools.
Implementation#
- Rust, using zlink (MIT) for Varlink services and clients, with bindings generated from
.varlinkIDL, including for systemd's interfaces. - One Cargo workspace for
sparewalld,sparewall, the schema, the renderers and the providers. - Socket-activated from a
.socketunit at/run/sparewall/org.sparewall.Firewall, mode 0600, root only. A second, restricted socket serves unprivileged clients such assparewall-httpd, with every call checked against the caller's role (Web UI and HTTP API). The peer never uses either socket; it talks through the sync tunnel. - Interface names follow the project domain in reverse:
org.sparewall.*.
Interface sketch#
interface org.sparewall.Firewall
type Generation (id: int, hash: string, base: ?int, schema: int, author: string, applied: string, confirmed: bool)
method Validate(config: object) -> (warnings: []string)
method Apply(config: object, base: int, confirm_seconds: ?int) -> (generation: Generation, changed: []string)
method Merge(patch: object, base: int, confirm_seconds: ?int) -> (generation: Generation, changed: []string)
method Patch(ops: []object, base: int, confirm_seconds: ?int) -> (generation: Generation, changed: []string)
method Confirm(id: int) -> ()
method Rollback(id: ?int, allow_diverge: ?bool) -> (generation: Generation)
method GetConfig(id: ?int) -> (config: object, generation: Generation)
method Export(id: ?int) -> (config: object)
method History(limit: ?int) -> (generations: []Generation)
method Sync(from_node: string) -> (generation: Generation)
method Health(verbose: ?bool) -> (level: string, role: string, checks: ?[]object)
method AckHealth(name: string) -> () # a check that stays degraded until acknowledged
method Status() -> (role: string, sync: object, links: object, vrrp: object, conntrack: object, services: object)
method Backup() -> (path: string, digest: string)
method Subscribe() -> (event: object) # called with "more": streams events
error ValidationFailed (errors: []string)
error Conflict (current: int)
error ConfirmTimeout (rolled_back_to: int)
error PeerUnreachable (peer: string)
error PermissionDenied (role: string)
Related interfaces follow the same pattern: org.sparewall.Auth (users, tokens, roles), org.sparewall.Secrets (write-only secret store), org.sparewall.Upgrade (rolling upgrades and channels).
The sparewall CLI#
sparewall is a thin Varlink client with kubectl-style ergonomics: whole documents or small fragments in JSON or YAML, individual values by path, and the same validate, diff and confirm-or-revert safety on every change.
Design goals#
- Thin client. All validation, rendering and state live in the coordinator, so any future front end can do everything the CLI can.
- JSON and YAML, in and out. Input format detected from extension or content (
-f site.yaml,-f -); output chosen with-o json|yaml|table. YAML is converted in the client; Varlink carries JSON. - Small pieces merge in without restating the whole document.
- Get and set by path from the command line, no file needed.
- Every change is safe: validated, diffable, and applied with a confirm window.
- Scriptable: stable
-o json, meaningful exit codes,--quiet, generated shell completion.
Commands#
| Command | What it does | kubectl analogue |
|---|---|---|
sparewall get [path] [-o yaml] |
Print the document or a subtree | get -o yaml |
sparewall set path=value … |
Set values in one transaction | set, patch |
sparewall unset path … |
Remove keys or map entries | patch with null |
sparewall merge -f fragment.yaml |
Merge a partial document | apply |
sparewall apply -f site.yaml |
Apply a whole document, replacing the current one | replace |
sparewall patch --type json -f ops.json |
Apply RFC 6902 operations | patch --type json |
sparewall diff -f fragment.yaml |
Show what a merge or replace would change | diff |
sparewall edit [path] |
Edit in $EDITOR, validate and apply on save |
edit |
sparewall explain path |
Describe a field from the schema | explain |
sparewall status, history, confirm, rollback N |
Operational state and generations | rollout |
sparewall sync --from <node> |
Resolve a diverged pair | none |
sparewall backup, export |
Backup bundle; canonical document export | none |
sparewall upgrade [--channel stable] |
Rolling, health-gated OS upgrade | none |
sparewall schema upgrade / downgrade |
Migrate the document between schema versions | none |
sparewall token …, secret …, vpn client-config <peer> |
Tokens, write-only secrets, VPN client configs | none |
sparewall get networks.users -o yaml
sparewall set networks.users.vip=192.0.2.1/24 dhcp.users.pool=192.0.2.100-192.0.2.199
sparewall unset vpn.roadwarrior.peers.old-laptop
sparewall merge -f add-guest-vlan.yaml --confirm 120
sparewall get policy.'wan->self'.rules -o json | jq .
Semantics#
mergeuses JSON Merge Patch (RFC 7386): objects merge,nulldeletes, other values replace. Because collections are maps keyed by name, adding a peer or a rule is a one-entry fragment.setandunsetcompile to merge patches client-side;patch --type jsoncovers anything a merge cannot express.- Paths are dot-separated; keys containing dots or
->are quoted (policy.'wan->self'). Values are typed by the schema, sovlan=20is a number and string fields stay strings. - Several
set/unsetpairs in one invocation are one generation and one confirm window. - Every mutation sends its
basegeneration; if the document changed in between, the coordinator returns a conflict instead of overwriting. --dry-runvalidates and prints the diff.--confirm Nsets the revert window; over SSH the default is non-zero.
Implementation notes#
- Rust, in the same workspace as the coordinator, sharing the zlink-generated types;
clapfor arguments and completions. - An actively maintained YAML 1.2 crate (
serde_yamlwas archived upstream in 2024). - Remote use runs over SSH to a node; named contexts for each deployment live in the user's config directory.
Networking with systemd-networkd#
systemd-networkd owns every link and address except the VRRP gateway addresses. The coordinator renders its files into /run/systemd/network/, so the document, not hand-edited files, is the source of truth; /etc/systemd/network/ stays empty and is reserved for emergency overrides, which take precedence over /run.
| Need | networkd mechanism | Note |
|---|---|---|
| Stable names | .link files, Name= matched on PermanentMACAddress= or Path= |
Interfaces are named after port roles and networks |
| VLANs, bonds, WireGuard | .netdev plus VLAN= and Bond= in .network |
Remote-access VPN and the sync tunnel are WireGuard netdevs |
| WAN addressing | DHCP= or static Address=/Gateway= |
[DHCPv4] NFTSet= puts the leased address into an nft set |
| Forwarding | IPv4Forwarding= in networkd.conf |
Global |
| Addresses in firewall sets | NFTSet=source:family:table:set with sources address, prefix, ifindex |
networkd only adds and removes elements; the sets must already exist |
| Reverse-path filtering | IPv4ReversePathFilter= per network |
Strict on single-homed LANs |
| LLDP | LLDP=, EmitLLDP= |
Shows which switch port each NIC is on |
| WAN queue management | [CAKE] qdisc |
Bandwidth set per WAN in the document |
| DHCP relay | DHCPRelay= (261+) |
For segments served by another DHCP server |
| NAT | Not IPMasquerade= |
nft owns NAT, so there is one rule source |
networkd's built-in DHCP server is available as a provider for a simple standalone node, but it has no failover protocol, so pairs use Kea.
Coexisting with keepalived#
networkd treats addresses it did not configure as foreign and drops foreign configuration when it starts, which can remove VRRP gateway addresses. The design guards against this:
KeepConfiguration=on links that carry gateway addresses, andManageForeignRoutes=no/ManageForeignRoutingPolicyRules=noinnetworkd.conf.- Changes are applied with a per-link reconfigure over Varlink, never by restarting networkd.
- keepalived 2.x re-adds addresses it sees removed, so a mistake costs a blip rather than an outage.
IPv6#
IPv6 is in the schema from revision 5 (#211), and rendered by 0.6.0 (#212 to #216). A network without ipv6 has link-local IPv6 addresses only, as before.
networks:
wan:
role: wan
dhcp_client: true
ipv6: { mode: dhcpv6, prefix_length: 56 } # an address, and a /56 for the inside
users:
ipv6: { mode: delegated, subnet_id: 1 } # the /56's second /64
servers:
ipv6: { mode: static, prefix: "2001:db8:0:10::/64" }
objects:
nas:
type: ipv6
suffixes: { users: ["::20"] } # 2001:db8:…:1::20, whatever the /56 is
policy:
wan->users:
action: drop
rules:
nas-https: { order: 100, proto: tcp, dport: 443, dst: "@nas", action: accept }
- On a WAN,
modeisdhcpv6,raorstatic: dhcpv6: the node's address from DHCPv6 (IA_NA) or SLAAC, as the upstream's router advertisements say, and a delegated prefix (IA_PD) for the inside networks;prefix_lengthasks for a size (48 to 64, default 56), which the ISP may not grant. The DHCPv6 client's DUID is the WAN's MAC (DUID-LL), so a reboot keeps the address and the prefix. The default route comes from the router advertisements. An upstream that advertises the M flag and no prefix gives the address by DHCPv6 only.ra: an address by SLAAC only, and no delegated prefix.static: the link'sprefix, each node's address in it, and the upstream router (gateway, in the prefix or link-local).- On an inside network,
modeisdelegated(thesubnet_idth /64 of the WAN's delegated prefix, by networkd'sDHCPPrefixDelegation=andSubnetId=) orstatic(a /64 of its own). The node is::1in the /64 (a delegated network'sToken=static:::1); hosts take addresses by SLAAC from the node's router advertisements (IPv6SendRA=), which name the node as the resolver where DHCPv4 does (so IPv6 never sends clients past serversdhcp.<network>.options.dnsnames): by its address on a static network, by its link-local address on a delegated one, which renumbering does not change;ipv6.dnsnames other resolvers in its place (#230). On renumbering, networkd stops announcing the old /64 but does not announce it as deprecated (systemd #29651), so the coordinator adds it to the advertisements with a preferred lifetime of 0, through a runtime drop-in beside the.networkfile that sends them, while it is valid and for at most 2 hours (RFC 4862 §5.5.3(e)'s floor for cutting a host's valid lifetime). It keeps the /64s in use in its state, so a reboot onto another prefix deprecates the old one too (#232). Unbound then listens on every address (::0), as a delegated network's change with the prefix, and the firewall drops IPv6 to its port from every interface but the served networks', ahead of the policies (service:dns-served-only), since a delegated prefix cannot be named in its access control. DHCPv6 on inside networks follows 1.0 (#217). - The sync network stays IPv4.
- Policies cover both families. A policy's default action applies to IPv4 and IPv6. A rule applies to the families that its
src, itsdstand itsprotoall allow: one whose addresses are all IPv4 (literals, oripv4objects) is IPv4 only,proto: icmpis IPv4's andicmpv6IPv6's, and a rule with neither addresses nor such a protocol is both. A rule whose parts allow no family in common (an IPv4 source and an IPv6 destination) is refused. The family is implicit rather than written out (afamily:on the rule) because the addresses already say it, as nft'sip saddrmatches only IPv4: a second statement of it could only disagree with them. The consequence to keep in mind is a drop rule listing one family's addresses of a host that has both; its other addresses reach the policy's default. - Objects:
ipv6objects hold IPv6 addresses, prefixes and ranges; a dynamic one is filled with the node's own IPv6 addresses on a network, or the network's prefix.suffixesnames hosts in a network's prefix by the address's last 64 bits, and follows the prefix when a delegated one changes. - Forwards and
natstay IPv4. Opening a port to an inside IPv6 host is a policy from the WAN's zone to that host, with no NAT; NAT66 is not planned. - Validation refuses a delegated network with no WAN on
dhcpv6, two networks with one subnet ID or overlapping static prefixes, a subnet ID beyond whatprefix_lengthholds, an inside static prefix that is not a /64, and fields for another mode. - A pair (#215) keeps the gateway on the master, as for IPv4:
- The WAN: DHCPv6 and router advertisements need the pair's one DHCP lease. The DHCPv6 client runs on its lease link (
swwan), which is up on the master only, with a DUID from the virtual MAC and a fixed IAID, so the lease and the delegated prefix move with the gateway. A static block's link is up on both nodes, so its IPv6 is static, withipv6.vip: the address the ISP routes the site to, which moves with the gateway, while the nodes take no IPv6 address of their own there. A WAN on the nodes' own MACs (vmac: false) is IPv4 only. - Inside networks: only the master advertises, from a shared gateway address (
fe80::1) on a macvlan with the network's IPv6 VRRP virtual MAC (00:00:5e:00:02:<vrid>), which is up on the master only. Hosts keep the same router across a failover. The nodes take no global address there. Where the RAs name the node as the resolver (as on a standalone node), they namefe80::1;ipv6.dnsreplaces it as it does there. - Across the pair: the backup learns the master's delegated prefixes and their lifetimes in the peer hello, and keeps the last it heard. At a failover, until its own DHCPv6 reply arrives, the new master routes the delegated networks' /64s of that prefix to their gateway links, at a metric below networkd's and expiring with the prefix, so hosts' addresses keep working; with the expected same prefix (one DUID and IAID), networkd's routes take over and those go; a prefix the new lease does not repeat stays routed until it expires, for hosts' addresses in it. Its RAs carry no prefix meanwhile, which leaves hosts' addresses as they were, so nothing has to advertise a prefix networkd did not learn.
- ipv6 objects: networkd fills a dynamic object from the node's address in a network, and a pair's nodes take none on an inside network, so an address object there is refused (
source: prefixnames the network's /64), and the coordinator fills a delegated network's prefix object with the /64s of the prefixes in use: the node's own, and the peer's last while valid. A static WAN's address object holds itsvip. - Following the master: the coordinator brings the gateway links up and down with the lease link, and only the master runs the
ipv6health check; the backup's says IPv6 runs on the master, and a node in FAULT (or whose role is not known yet) is degraded. - How it is rendered:
- The lease link runs networkd's DHCPv6 client (
DUIDRawData=from the virtual MAC,IAID=thevrid,SendRelease=no), or holds a staticvipand route itself, since keepalived could not route on a link that is down. - A static block's
vipand IPv6 default route ride in the WAN's keepalived instance (virtual_ipaddress_excluded, as adverts carry one family). Its link is up on the backup too, so there it joins no multicast group the kernel would report from the virtual MAC: no link-local address, and not a router on that link (IPv6Forwarding=no). Writing the global forwarding key resets every interface's, so the coordinator writes no sysctl whose value is unchanged. - Each inside network's gateway is a macvlan named
swgw<vrid>(a network's name may already take the 15 bytes), withActivationPolicy=manual. It holds onlyfe80::1and sends the RAs. The /64 is routed there: a delegated one byDHCPPrefixDelegation=withAssign=no, a static one by a route. Hosts' IPv6 arrives on it, so it is in the network's zone. - conntrackd syncs forwarded IPv6 flows and ICMPv6, and ignores the nodes' own link-local addresses.
- The lease link runs networkd's DHCPv6 client (
- Older releases: an IPv6 address in a rule's
srcordstneeds revision 5 as the new fields do (x-since-ipv6on the match types), so 0.5.x refuses such a document as too new, not as invalid. Hosts by suffix on a delegated network (#245) and IPv6 inmanagement.sources(#246), which 0.6 parses but refuses as not built, need revision 6: combinationsschema::revisionnames itself, as no one field's revision can say them.
Firewall: zones plus raw rules#
The coordinator renders the nftables ruleset from the document: a zone-based policy for the common case, with raw nft statements allowed at defined hook points for anything the zone model cannot express.
Zone model#
- Zones are named groups of networks, plus a built-in
selfzone for traffic to and from the firewall. - Policies are per zone pair (
users->wan): a default action (accept, drop, reject) and named, ordered rules (protocol, ports, source and destination objects, log, rate limit). - Objects are named address and port sets rendered as nft named sets, of type
ipv4,ipv6orport. Sets that networkd fills viaNFTSet=(the WAN address, for example) appear as dynamic objects, so rules never hold literal addresses that DHCP can change. Anipv6object can also name hosts by their suffix in a network's prefix (suffixes), so a rule follows a delegated prefix the ISP renumbers. - Both families: a policy applies to IPv4 and IPv6 alike. A rule applies to the families its addresses and protocol allow (see IPv6).
- NAT attaches to zone pairs (masquerade or SNAT outbound); forwards define inbound DNAT. A forward's
hairpinzones may also use it by its outside address (NAT reflection); clients on the server's own network are then source-NATed to the firewall's address there, so replies return through it.
Raw rules#
Raw entries are literal nft statements placed at named hook points, so the zone model never has to grow a feature for every edge case.
| Hook point | Typical use |
|---|---|
| Before or after one zone pair's generated rules | An exception the policy language lacks, a catch-all log |
| Prerouting at raw priority | notrack for VRRP or sync traffic, early drops |
| Forward, before zone dispatch | Global blocks, MSS clamping |
| Postrouting | Custom SNAT, marks for policy routing |
The coordinator does not parse raw rules: it places them, tags each with a comment naming its entry, and validates the whole script with nft -c. They ride in the same atomic transaction and the same confirm-or-revert window as everything else, and their counters are reported by name.
policy:
users->wan: { action: accept, nat: masquerade }
wan->self:
action: drop
rules:
ssh-admin: { order: 100, proto: tcp, dport: 22, src: "@admin_nets", action: accept }
raw:
block-scanner:
at: { pair: wan->users, position: before }
order: 100
nft: ip saddr 198.51.100.0/24 counter drop
notrack-vrrp:
at: { hook: prerouting-raw }
order: 100
nft: ip protocol vrrp notrack
Rendering#
- Base chains accept
ct state established,relatedand dropinvalidfirst, then dispatch by interface pair through verdict maps, for exampleiifname . oifname vmap { "users" . "wan" : jump users_to_wan }, so rule count stays flat as networks are added. - Each zone-pair chain runs: raw before entries, generated rules, raw after entries, default action.
- An anti-lockout rule for SSH and HTTPS from the management network to
selfis always rendered first, unless anadminexplicitly disables it. - Protocols that need conntrack helpers (FTP, SIP) get explicit
ct helperobjects; nftables does not assign helpers automatically. - Rule logging uses
log group N, collected by ulogd2 (see Observability). - IPv6 (#212). Without a network that has
ipv6, IPv6 is dropped but link-local neighbour discovery and MLD, as before. With one: - First, before the state rule: neighbour discovery and MLD on every link, then IPv6 to, from or through any interface without IPv6 is dropped (
ipv6-off), so not even a flow conntrack already knows carries on there. Neighbour discovery must come from the link (hop limit 255) with code 0 and not from a multicast address, and an advertisement not from::(RFC 4861); the kernel checks the rest of each message. - Router solicitations are accepted from the inside networks with IPv6; router advertisements only on a WAN in
dhcpv6orramode, from a link-local address; DHCPv6 replies (547 to 546) only on adhcpv6WAN, to the node. - ICMPv6 errors (Packet Too Big, which path MTU discovery needs, and the others RFC 4890 asks for) pass as conntrack's
related; echo is the policies', with a flood limit to the node as for IPv4. - A rule with addresses renders one line per family it applies to, with that family's addresses (
ip saddr,ip6 saddr); one without addresses is one line, for both. Within a family, nft can't put an object's named set inside an anonymous set, so the literals together are one match and each object is one of its own, and the rule renders a line for each pairing of its source and destination matches (#259); forwards andmanagement.sourcessplit the same way. Every line has the rule's verdict, so this changes nothing about what matches. Alimitwould apply to each line separately, so a rule with one must match each family with a single line: validation refuses it otherwise, and the addresses belong in one object.ipv6objects areipv6_addrsets; their hosts by suffix in a static prefix are elements. In a delegated one the coordinator adds them (#245): each suffix in each /64 a rule should still reach, which are the node's prefix, the peer's last while valid (a takeover), and a withdrawn /64 while it is announced as deprecated (#232). The set is preserved across a reload, as a set networkd fills is, and refilled in one transaction when what it should hold changes. - NAT and the extra-port redirects say
meta nfproto ipv4, sincemasqueradealone would translate IPv6 too. The anti-lockout rule takes both families (#246): withmanagement.sources, a line per family it names (ip saddr,ip6 saddr); IPv6 sources only where the management network has IPv6, as elsewhere they match nothing; without sources, one line for both families, which IPv6 reaches where the management network has it and, on a node with no IPv6 at all, by link-local address, as before IPv6 (elsewhereipv6-offdrops it first). A pair's nodes are managed over IPv6 at their own link-local addresses, as they take no global one on an inside network.
Sharing nftables with other software#
The coordinator owns one table (inet sparewall) and loads each generation as one nft -f transaction. It never runs flush ruleset, because others write nft too:
- networkd inserts set elements only when addresses change, so those sets are declared idempotently (
add table,add set) and never flushed; only coordinator-owned chains are flushed and rebuilt. - keepalived may install its own rules.
- Podman's Netavark manages container networking in nftables; Sparewall's containers run with host networking or none, which keeps it out of the way.
Every script is validated with nft -c -f before loading, and the previous generation's script is kept for rollback. Flowtables (a fast path for established flows) stay off until they are proven compatible with conntrackd failover.
High availability and standalone mode#
A pair is active/standby: keepalived moves the gateway addresses, conntrackd moves connection state with them, and the DHCP provider runs its own HA protocol. All replication runs inside a WireGuard tunnel between the nodes, over the sync network: by default the LAN itself, on two-NIC nodes behind a plain switch (#177), or a dedicated sync VLAN on a trunk. No dedicated sync cable is required.
Sync over the LAN#
On the usual hardware, two-NIC nodes behind plain switches, cluster.sync_network names the LAN, which is also the management network: the tunnel's endpoints are the nodes' LAN addresses, and nft accepts the tunnel's UDP port on the LAN link only from the peer's address.
- Confidentiality and integrity do not rest on a separate segment. Replication, DHCP HA and configuration pushes all travel inside WireGuard, which drops anything not authenticated by the peer's key, and the tunnel's addresses are unreachable from the LAN, so a LAN client cannot read, alter or inject sync traffic or reach the services behind the tunnel.
- What a hostile LAN host can still do. nft admits the tunnel's UDP port only from the peer's address, but a host on the same segment can spoof that address. WireGuard then rejects what it sends, yet the handshake path still processes it: a flood can cost the nodes CPU and packets, and delay replication. That is the case for a dedicated sync VLAN on sites whose LAN clients are untrusted (a guest network on the same segment, for instance); on a LAN whose hosts are the site's own, the shared segment is the practical default.
- Failures. Sync then fails only together with the LAN link, which is the "master loses its whole trunk" case: health fails and VRRP moves the gateway, as it does today. It never fails alone while VRRP stays up, so the split-brain argument for a separate VLAN does not apply.
- The trade-off is the management plane's: management and sync share the clients' broadcast domain. A dedicated sync and management VLAN (below) isolates both, at the cost of a VLAN-aware switch.
Sync over a shared trunk#
- Isolation.
syncis its own VLAN, never routed or bridged anywhere. nft on it accepts only WireGuard from the peer's sync address, and drops everything else that arrives on it. Every switch port between the nodes must carry it. - Authentication and encryption. conntrackd's protocol has neither, so it runs inside a WireGuard tunnel between the nodes' sync addresses, configured by networkd. DHCP HA and the coordinator's config push use the same tunnel. Each node generates its sync key at first boot; only public keys appear in the document.
- Split-brain behaviour. VRRP adverts stay on the service VLANs, never on
sync. Losing only the sync VLAN degrades state and lease replication but cannot move or duplicate gateway addresses; losing a whole trunk takes VRRP and sync down together, which is what VRRP is built to handle. Sync loss raises its own alert. - Contention (optional). The sync VLAN can carry an 802.1p priority (networkd
EgressQOSMaps=), honoured by switches and OVS.
keepalived#
- One
vrrp_sync_groupholds every VRRP instance, so all gateway addresses move together; a split would break stateful filtering. - VRRPv3;
track_interfaceon every member link;nopreempt; optionaluse_vmac(not on a WAN with private node addresses, which has its own virtual-MAC link, below). nopreemptstays the default. A larger node that returns would otherwise take the gateway addresses back as soon as it could, and a node that flaps would move them each time. Failback is an operator's decision instead (sparewall failover: the master yields through a track script that fails while the coordinator asks it to, andnopreemptthen keeps it the backup). A site that wants automatic failback setscluster.vrrp.preempt_delay_s, which replacesnopreemptwith keepalived'spreempt_delay, the delay being its only flap protection.- A
track_scriptcalls the coordinator'sHealth()over Varlink. Only a failed result lowers priority, with a hold-down so a briefly failing check cannot flap the pair. - State changes reach the coordinator through
notify_fifo, so transitions are serialized and logged in one place.
The WAN of a pair#
A pair does not need a public address per node. With a static block, each node has a private address on the WAN link (VRRP and node-to-node traffic), and the public addresses (vip, extra_vips) and the ISP's gateway lie in a subnet of their own:
- The public addresses are VRRP addresses held by the master, and the public default route is a keepalived
virtual_routesentry (on-link, metric 100) in the WAN instance, so it moves with them. - Both nodes have a default route via the peer's private address, metric 200 (below a management network's 1024): only the backup uses it, so its own traffic (upgrades, ACME, NTP, backups) leaves through the master. The master's forward chain accepts its peer's traffic from the WAN link to
swwan(infra:peer-egress). - In postrouting, traffic from the private subnet leaving by
swwanis SNATed to the gateway address (infra:wan-egress). That is the master's own traffic and the backup's it forwards; the backup sends nothing byswwan, so nothing matches there. VRRP adverts are never tracked (infra:vrrp-notrack, at raw priority in prerouting and output), so this SNAT never rewrites a node's own adverts, whose checksum covers their source address. - The public addresses and that route are on
swwan, a macvlan on the WAN link with the VRRP virtual MAC of the network'svrid(00:00:5e:00:01:<vrid>), so the ISP sees them behind one MAC whichever node is the master (#176). An ISP gateway that ignores gratuitous ARP, at least from a MAC it has not heard from in a while (a standby's own MAC always is), would otherwise drop the site's traffic at a handover until its ARP cache expired. The link is up on both nodes, since the kernel refuses a route on a link that is down and keepalived adds it the moment it becomes master; the backup's has no address and IPv6 disabled, so it never sends a frame from the virtual MAC. Both links answer ARP only for their own addresses (arp_ignore=1), so the WAN link never answers for the public ones with the node's own MAC. VRRP adverts stay on the WAN link, from the private addresses. vmac: falseon the network (#194, for an upstream that limits the MACs it learns on a port) leaves outswwan: the public addresses and the route go on the WAN link itself, peer egress is from the WAN link back out of it, and the SNAT skips the private subnet and traffic routed via the peer (ip daddr != <private> rt ip nexthop != <peer>). A handover then changes the MAC behind the public addresses.- Reach probes (#41) use the private subnet: the ISP's gateway cannot answer the backup, so a WAN cut on one side is found only through other hosts on the private subnet, and otherwise only degrades health.
With a single DHCP lease (one public address, leased to one MAC), the WAN has dhcp_client: true, private addresses and a vrid, and no vip:
- Both nodes render a macvlan
swwanon the WAN link with the VRRP virtual MAC of thatvrid(00:00:5e:00:01:<vrid>), running the DHCP client (ClientIdentifier=mac,SendRelease=no) and filling the dynamic objects. networkd leaves it down (ActivationPolicy=manual); the coordinator brings it up on the master and down otherwise, on every keepalived transition and every few seconds. The ISP sees one MAC and one client ID, and the new master asks for the lease the old one held. keepalived's ownuse_vmacis not used: it keeps the virtual MAC up on both nodes, where the backup's IPv6 link-local traffic could pull the ISP's frames toward it. - The WAN zone includes
swwan, so outbound NAT masquerades to the leased address and forwards and remote access are reached there. - The backup's own traffic takes the route via the peer as above; the master accepts it (
infra:peer-egress, from the WAN toswwan) and masquerades whatever leaves byswwanfrom the private subnet (infra:wan-egress).
Standalone nodes keep their own public address, static or leased.
conntrackd#
FTFW mode, active/backup, bound to the tunnel addresses. Connection tracking is shared by iptables and nftables, so it works unchanged with an nft ruleset. On becoming master the coordinator runs the standard sequence: commit the external cache (-c), flush the internal cache (-f), resync (-R), request a bulk send (-B).
DHCP HA#
With the Kea provider: hot-standby mode, with the HA hook and lease_cmds, both open source since Kea 3.0. Each Kea binds to its node's own addresses, not the gateway address; clients receive the gateway address as their router, so it does not matter if the VRRP master and the active Kea briefly differ. HA traffic uses the peer's tunnel address.
Failover sequence#
- The standby's keepalived stops seeing adverts and becomes MASTER, adding every gateway address and announcing it with gratuitous ARP.
- The coordinator receives the FIFO event and runs the conntrackd sequence, so established flows keep passing the new master's stateful rules.
- Independently, the DHCP provider detects its partner down after its own timeouts and starts answering.
- The old master returns as BACKUP, bulk-syncs connection state and leases, and stays standby until the next failure.
Standalone mode#
A document listing one node in cluster.nodes runs the same image as a single firewall; the mode comes from the document alone.
| Concern | Pair | Standalone |
|---|---|---|
Gateway addresses (vip) |
Moved by keepalived | Plain static addresses |
| keepalived, conntrackd | Running | Not started |
sync network and tunnel |
Required | Rejected by validation |
| DHCP provider | HA mode | No HA |
| Config apply | On the node it was submitted to, then pushed to the peer once confirmed | Local, same confirm and rollback |
| OS upgrade | Rolling, no outage | One reboot of downtime |
Status role |
MASTER / BACKUP | standalone |
The gateway address stays separate from the node's own address even when standalone. Growing to a pair is therefore additive: install the second node, add it and a sync network to the document, and apply; clients notice nothing.
Service providers#
The document says what a service must do; a provider turns that intent into one implementation's configuration and controls it. Every application-level service is a provider, so any of them can be replaced, or moved to a new major version, without changing the schema.
Roles and providers#
| Role | Neutral config | Default provider | Alternatives |
|---|---|---|---|
| DHCPv4 | Pools, reservations (MAC, address, name), options (router, DNS, NTP, domain), lease time, HA | Kea | networkd's built-in server (standalone only), dnsmasq: not built yet |
| DNS resolver | Enabled flag, listening networks, forwarders or full recursion, local records from reservations | Unbound | Disabled; Knot Resolver, dnsmasq: not built yet |
| ACME DNS-01 | Names, CA directory, provider name, secret reference | Built-in RFC 2136 | lego (Google Cloud DNS, Cloudflare, Route 53 and many more) |
| Log forwarding | Destination, protocol, TLS | systemd-journal-upload |
Off; rsyslog remote (syslog over UDP, TCP or RELP, with TLS) |
| Metrics storage | Mode, retention (time and size) | External scrape | Local Prometheus container, queried through the API; off |
| Backup | Repository, schedule, credentials | restic | Any restic backend; off |
What a provider is#
- A Rust module in the coordinator implementing one interface: render the intent, validate with the daemon's own checker, apply and reload, report status and metrics, declare capabilities, and export/import state.
- For containerized services, a Quadlet unit and pinned image. The image may bundle more than one provider version (Kea 3.0 and 3.2), so switching is a config change and a reload, not a rebuild.
Rules that keep providers swappable#
- Neutral schema first. Anything most implementations can express belongs in the shared schema.
- Escape hatch.
provider_options.<provider>passes settings straight into that provider's config; it is validated by the daemon's checker, shown in diffs, and ignored with a warning if the provider changes. - Capabilities are checked. Each provider declares what it supports (HA, DDNS, DNSSEC, VLAN redetection); validation rejects a document needing something the chosen provider lacks.
- State moves or is declared lost. Switching runs the provider's export and import (Kea's lease file, for example) where possible, and otherwise warns that state will be lost.
- One conformance suite per role, run against every provider and version: a lease on every VLAN, reservations honoured, lease continuity across failover, local names resolve.
In the first releases#
Each role has one built provider, so the contract is narrower than the full interface above:
- One table. Every provider is listed per role with its capabilities (HA) and the state it keeps (Kea's lease database, with where it lives and which providers can import it). Validation, the renderers, backups and
applyall go by that table. - Not built means rejected. A provider the table lists as not built is rejected at its path, like other settings not built yet, so a document never names a provider that silently does nothing.
- State on a switch. A change that switches a role's provider warns when the old provider's state cannot move to the new one.
- Status and state export/import stay provider-specific until a second provider of a role exists.
- Conformance. The VM conformance suite runs against the built providers.
Container conventions#
- Quadlet files ship in the image under
/usr/share/containers/systemd/; images are pinned by digest, so a service and the OS move and roll back together. Nodes never runpodman auto-update. - bootc logically bound images make
bootc upgradepull new container images before the reboot. - Containers use host networking where they serve the LAN (Kea needs raw broadcast handling) or no network at all; Netavark stays out of the firewall's nft table.
- All capabilities dropped, then added back per service (Kea:
NET_RAW,NET_BIND_SERVICE); read-only root filesystems; no privileged containers. - State in named volumes under
/var/lib/containers; control sockets in a shared/run/<service>/the coordinator can reach.
Defaults in detail#
- Kea: ISC's official open-source images for
kea-dhcp4. Start on 3.0 LTS; move to 3.2 if 3.0's interface handling falls short on VLAN-heavy hosts, since 3.2 addsinterface-redetectand refactored interface code. Since 3.0 the DHCP daemons serve their control API directly, and 3.2 removed the Control Agent. The coordinator drives Kea over its control socket (config-test,config-set, lease and HA status). As built: Kea 3.2 from Fedora's packages, in Sparewall's own provider image (image/providers/kea), since ISC publishes no 3.2 images; see implementation notes. The milestone and risk tables below keep the original plan. - Unbound: a recursive resolver bound to the gateway addresses of the networks it serves; the whole service can be turned off for sites with their own DNS. systemd-resolved remains the host's own stub resolver and never serves the LAN.
- Time: chrony runs on the host as both client and LAN time server; systemd-timesyncd cannot serve time.
Remote-access VPN (WireGuard)#
Remote-access WireGuard is built in: networkd runs the tunnel, the VPN is a zone in the policy, and peers are entries in the document. Nothing extra is installed.
vpn:
roadwarrior:
listen_port: 51820
endpoint: vpn.example.org
addresses: [10.99.0.1/24]
zone: vpn
dns: [10.99.0.1]
peers:
alice-laptop: { public_key: "<base64>", addresses: [10.99.0.10/32] }
The coordinator renders a WireGuard .netdev (ListenPort=, PrivateKeyFile=, one [WireGuardPeer] per peer with PublicKey= and AllowedIPs=) and a .network with the tunnel addresses. It adds the WAN-to-self rule for the listen port and MSS clamping for the tunnel's smaller MTU; policy from vpn to other zones is written like any other zone pair.
Keys#
- Client keys are generated on the client. Only public keys enter the document, so git never holds a VPN secret.
- The server key is a cluster secret: clients know one public key and one endpoint, so both nodes must hold the same private key. The coordinator generates it once, sends it to the peer through the sync tunnel, and keeps it in the secret store.
- Rotation generates a new server key and lists the clients needing a new config; WireGuard has no in-place key rollover.
sparewall vpn client-config <peer>prints a client config and QR code with the server's public key, endpoint and DNS; the client supplies its own private key.
With HA#
- Clients connect to the WAN gateway address. Both nodes run the same interface, key and peer list, but only the gateway holder receives traffic.
- The nodes share the server's static identity (its private key, synced as a cluster secret), not its sessions. A WireGuard session (ephemeral keys, receiver indices, the client's current endpoint) exists only on the node that made the handshake, and none of it is synced. After a failover the new master drops the client's packets, since it does not know their session, until the client makes a new handshake. It learns the client's endpoint from that handshake.
- Recovery is driven by the client's own timers. A client whose session is older than 2 minutes rekeys at its next send, so it recovers at once. Otherwise, a client sending data that gets no reply starts a handshake after about 15 seconds (keepalive timeout plus rekey timeout), whether it was busy or idle before.
PersistentKeepalivekeeps a NAT mapping open while idle. Keepalives are not data, so they do not arm that 15-second timer and do not make failover faster. They are still sent on the session, though, so a client sending only keepalives rekeys once its session is 2 minutes old (or has no usable key), and recovers within about 2½ minutes without sending anything.- The pair test measures these cases on every run, with Linux WireGuard clients: about 16 seconds for clients sending data on a session under 2 minutes old; a few seconds for older sessions (one 5-second handshake retry if the first is sent before the new master holds the address); and from seconds to about 2½ minutes for a client sending only keepalives, depending on its session's age. Other implementations follow the same protocol timers but are not tested.
- A node sends remote-access packets only from the gateway address. When a node hands the address over (an upgrade, a manual failover) it still holds its clients' sessions for a moment; a reply from its own address would make a client roam there, since WireGuard follows the source of any authenticated packet, and the client would lose the tunnel when that node rebooted. The output chain drops them.
- The new master cannot start the handshake itself: it knows client endpoints only from handshakes it received. Clients behind NAT therefore have to recover on their own, as above.
- Flows inside the tunnel are tracked and synced by conntrackd like any other traffic, so an inner TCP connection survives the outage as long as its retransmissions (and the application's own timeouts) outlast it, and inner UDP resumes once the tunnel does.
- The remote-access interface and the sync tunnel are separate WireGuard interfaces with separate ports and keys.
Standalone nodes run the same configuration. Static-endpoint peers are site-to-site tunnels with the same mechanism: their networks are routed through the tunnel, and in a pair the master starts the tunnel from the gateway address.
Observability and health#
Logs land in the journal and can be forwarded off the box; metrics are exposed in Prometheus format; one health model answers every "is this node OK?" question. Dashboards, long-term storage and alert delivery live elsewhere, so a firewall never depends on its own monitoring.
Logging#
| Source | Captured by |
|---|---|
| Host services (networkd, keepalived, conntrackd, coordinator) | journald |
| Containers (Kea, resolver) | Podman's journald log driver, tagged with the unit name |
| Firewall rule hits | nft log group N → ulogd2 → structured JSON entries in the journal, avoiding kernel-log rate limits |
| Connection and NAT records (optional, off by default) | ulogd2's conntrack plugin: flow start and end with NAT mappings |
| Configuration changes | The coordinator: generation, hash, author and diff summary as structured journal fields |
Forwarding is configured in logging.remote: systemd-journal-upload to a systemd-journal-remote collector, an rsyslog remote (plain syslog or RELP), or off. Journal size caps on /var keep a log flood from filling the disk.
Metrics#
- Host: Prometheus node_exporter (CPU, memory, NIC counters and errors, conntrack table use).
- Appliance: the coordinator serves
/metricsfor everything else: nft rule and raw-entry counters by name, set sizes, VRRP state and failover count, conntrackd sync statistics, DHCP pool use and HA state, WireGuard per-peer handshakes and traffic, config sync state and generation, last apply duration, backup age. - Where they go is configured in
metrics.mode: exposed for an external Prometheus, collected by an optional local Prometheus container with bounded retention, or off. - The project ships starter alert rules: failover occurred, pair diverged or apply failed, sync tunnel down, WAN down, DHCP pool above 90%, conntrack table above 80%, backup older than its interval, certificate or key near expiry.
Health endpoints#
One health model lives in the coordinator as Health(); HTTP endpoints, sparewall status and the keepalived check are all views of it.
| Endpoint | Means |
|---|---|
/livez |
The coordinator responds; no dependency checks. Locally, systemd's WatchdogSec= restarts a hung coordinator |
/readyz |
This node could carry traffic now: required links up, nft holds the current generation, providers and conntrackd running, applied hash equals desired hash |
/readyz?verbose, /readyz/<check> |
Each named check and its result, or one check |
/healthz |
Alias of /readyz for tools that expect it |
Results have three levels: ok (HTTP 200), degraded (HTTP 200 with the reason: sync tunnel down, pair diverged, backup stale), and failed (HTTP 503). A check that records an event rather than a state, such as an SELinux denial for the coordinator, stays degraded, across restarts and reboots, until an admin acknowledges it (AckHealth); its /metrics counter only ever rises, for alerting. Only failed lowers VRRP priority; degraded never triggers failover, because a sync fault affects both nodes equally. The node's VRRP role appears only in the response body, never as a status code. Endpoints share the /metrics listener on the management network; unauthenticated requests get only the level, and verbose detail requires authentication.
Security#
The coordinator is the single authority: it holds users and tokens, checks every call against a role, stores secrets, and manages certificates. Management services are confined to the management network by systemd, nftables backs that up, and SELinux stays enforcing.
Authentication#
| Who | How |
|---|---|
| Admin at a shell | SSH keys; sparewall talks to the root-only local socket. An optional console password for admin (sparewall passwd, or seeded with the identity) is the break-glass path; over SSH only if the document opts in (management.ssh.password); root stays locked |
| Scripts and CI | API tokens, over HTTPS or the restricted socket |
| A browser (the web UI) | A password login, then a session cookie (see Web UI and HTTP API) |
| Prometheus and health checks | A monitor-role token or a TLS client certificate |
| Peer node | WireGuard keys on the sync tunnel |
- A built-in
adminaccount may have a password (sparewall passwd, or seeded with the node identity); its crypt(3) hash is a cluster secret, which console logins and web UI logins check. Password logins are rate-limited. - API tokens are random opaque strings, not JWTs, so revocation is immediate.
sparewall token create --role operator --expires 90dshows a token once; the coordinator stores only its hash with name, role, expiry and last use. - Single sign-on (OpenID Connect) can be added later and mapped onto the same roles; the local
adminaccount always keeps working, so an identity provider reached through the firewall can never lock anyone out of it.
Roles#
| Role | May |
|---|---|
admin |
Everything, including users, tokens, secrets and certificates |
operator |
Change, confirm, roll back and sync configuration; read status |
viewer |
Read configuration and status |
monitor |
Verbose health and metrics only |
Every authenticated mutation is logged with its principal. Because every setting has a path, path-scoped grants (a token that may only edit vpn.roadwarrior.peers) are a natural later extension.
TLS and ACME#
- Each node generates a self-signed certificate at first boot;
sparewall statusshows its fingerprint. Without ACME configured, or if issuance fails, nodes keep serving it and raise an alert. - ACME is built into the coordinator with a configurable directory URL (Let's Encrypt, a private CA such as step-ca) and External Account Binding.
- DNS-01 is the primary challenge, because management interfaces should not be reachable from the internet. RFC 2136 dynamic updates with TSIG are built in; lego (MIT) in a container covers hosted DNS APIs such as Google Cloud DNS, Cloudflare and Route 53. HTTP-01 remains available for public names.
- In a pair, a certificate for a shared name is requested only by the active node and synced to the peer, so CA rate limits are not consumed twice.
- Renewal happens at two-thirds of the lifetime, or earlier when the CA publishes ACME Renewal Information; certificates reload without restarting listeners.
tls:
certificates:
mgmt:
names: [fw.example.org]
acme:
directory: https://acme-v02.api.letsencrypt.org/directory
challenge: dns-01
dns: { provider: gcloud, credentials: secret:gcloud-dns }
Secret storage#
Secrets never appear in the document or in git; the document refers to them by name.
| Class | Examples | Leaves the node? |
|---|---|---|
| Node secrets | SSH host keys, sync-tunnel WireGuard key, self-signed TLS key | Never |
| Cluster secrets | VPN server key, admin password hash, issued TLS keys, ACME account key, DNS and log-forwarding credentials | Synced to the peer through the sync tunnel; included in the encrypted backup |
- At rest: each secret is encrypted with
systemd-creds, bound to the TPM2 where present (libvirt VMs can be given a virtual TPM), otherwise to the host credential key. - In use: services receive secrets through
LoadCredentialEncrypted=, so plaintext exists only in that service's private credentials directory. - Between nodes: TPM-bound ciphertext cannot move, so the coordinator decrypts, sends through the tunnel, and the peer re-encrypts with its own key.
- Interface:
sparewall secret set NAMEreads from stdin or a prompt;sparewall secret listshows names and versions. Secrets are write-only. - The backup repository password is the one secret kept outside Sparewall, in an operator's password manager.
Management-plane isolation#
The data plane (networkd, nft, keepalived, conntrackd, WireGuard) stays in the root network namespace. Management services are confined per service rather than by separate namespaces, which would require a second networkd, ruleset and resolver and make every debugging command harder. A management VRF is available for sites whose management network has its own upstream gateway.
| Service | Listens on | Restriction |
|---|---|---|
| sshd | All addresses | nft: the anti-lockout rule admits it from the management network only (narrowed by management.sources), or a zone's ->self policy; keys only; no root login over SSH |
| Coordinator HTTPS (health, metrics, web UI) | All addresses | nft, as sshd; the web UI and API need a login or token |
| DHCP provider | Service networks | Host network; minimal capabilities; nft limits it to DHCP |
| DNS resolver | Gateway addresses of served networks | Host network; may only query out through the WAN |
| chrony | Served networks (NTP) | Host network |
| Remote-access WireGuard | WAN, one UDP port | Kernel; silent to packets without a valid key |
Nothing else listens on the WAN. ICMP is rate-limited and invalid packets are dropped. The anti-lockout rule keeps SSH and HTTPS reachable from the management network unless an admin disables it.
The management network may be a network of its own, in no zone, which no client reaches, or, on two-NIC hardware with no VLANs, the LAN itself (#177): in a zone like any other, served DHCP and DNS, with its zone policy applying to everything but SSH and HTTPS to the node. Those the anti-lockout rule admits first, so lan->self: drop cannot lock the admin out; management.sources narrows it to the admin's addresses, and without it validation warns that every host on the LAN reaches them. The shared LAN is the default layout; a separate management VLAN is the stronger one, for sites with a VLAN-aware switch.
The design once planned RestrictNetworkInterfaces= and IPAddressAllow= on sshd and the coordinator as well; they are not rendered, so nftables is the one gate, and the rows above say so.
Host hardening#
- SELinux enforcing. Distribution policy confines networkd, chronyd, keepalived and containers; the coordinator runs in its own enforcing domain,
sparewalld_t, from its own policy module. The VM suites fail on any denial it logs, with dontaudit rules off. - Coordinator sandboxing: bounded capabilities (network administration, raw sockets),
NoNewPrivileges=,RestrictAddressFamilies=(UNIX, netlink, IPv4, IPv6),ProtectHome=, a@system-servicesyscall filter, writes limited to its own state and rendered configs; tracked withsystemd-analyze securityin CI. - Packet captures run outside the coordinator:
sparewall-capture@.service, a dynamic user withCAP_NET_RAWalone, in its own domain,sparewall_capture_t, runs tcpdump for each connection the coordinator makes tosparewall-capture.socket, and the pcap streams back on that connection with nothing written to disk (#265). - Secure Boot and measured boot are optional and recommended on physical nodes; binding TPM-sealed secrets to the boot state stops a moved disk from unsealing them.
Bootstrap#
A fresh node boots into a safe built-in default that is reachable only on its management port, and receives its real configuration through the same sparewall apply path as every later change. Install time carries only a tiny identity, and optionally a first configuration that the node applies itself through that same path, confirming it once healthy (no secrets, no pairing).
1. Install with a minimal identity#
Installer ISOs and raw disk images are built from the bootc image with bootc-image-builder. Three values are supplied at install:
| Value | Why it is needed before any config exists |
|---|---|
Node name (fw1, fw2) |
Selects this node's values in the shared document |
| Admin SSH public key | Lets an operator or CI reach the node |
| Management port, matched by MAC | The only interface bootstrap mode brings up |
On VMs they arrive as systemd credentials (SMBIOS or kernel command line), read by the coordinator with ImportCredential=. On physical machines they come from a kickstart for the ISO install, or a small seed file on a USB stick read once at first boot and recorded under /var/lib/sparewall.
2. First boot: bootstrap mode#
With no applied generation, the coordinator renders the default shipped in the image: only the management port up (static address or DHCP client, per the identity), SSH accepted on that port only, all forwarding dropped, and keepalived, conntrackd and providers stopped. It also generates the SSH host keys and the sync-tunnel WireGuard key under /var/lib, so private keys never leave the node. A serial console with a local sparewall is the fallback.
3. First configuration#
An operator or CI runs sparewall apply -f site.yaml --confirm 120 over SSH to the management port and confirms once a post-apply check passes. If the configuration cuts off management access, the confirm timer returns the node to bootstrap mode (generation 0). The coordinator also runs the bootstrap configuration when it cannot read the active generation's document at boot (a newer release's, after an image rollback, or a damaged file), and reports health failed until a rollback or a new apply: a node that cannot read its configuration stays reachable.
4. Pairing#
- Install and bootstrap both nodes.
- Read each node's sync-tunnel WireGuard public key with
sparewall status. - Add both keys to the document's
clustersection and apply on each node. - The tunnel comes up and the nodes authenticate each other; from then on, an apply on one node is pushed to the other.
Only public keys appear in the document.
Backup and restore#
Little on a node needs backing up: the OS is an image in a registry, the document lives in git, and in a pair the peer holds a live copy of everything else. The backup exists for losing both nodes, losing git, or running standalone, and it is one small encrypted bundle per node.
State and where it is protected#
| State | Lives in | Protected by | If every copy is lost |
|---|---|---|---|
| OS, daemons, coordinator | Registry | Retention of every deployed digest; sparewall status records the running digest |
Rebuild from the Containerfile at that commit |
| Configuration document | Git (source of truth); generations in /var/lib/sparewall |
Git, plus the bundle | Export from either node |
| Node identity (SSH host keys, sync key) | /var/lib on each node |
Not backed up by design | Regenerate on reinstall and re-pair |
| Cluster secrets | Secret store on both nodes | The peer, plus the encrypted bundle | Re-enter or regenerate; a new VPN key means new client configs |
| DHCP leases | Provider state (Kea's memfile) | Provider HA, plus the bundle | Clients re-request; Kea's open-source ping_check hook avoids handing out addresses still in use |
| Connection tracking | Kernel, synced to the peer | Never backed up | Connections reconnect |
| Logs and metrics | Journal and exporters | Forwarded off-box when configured | Not a backup concern |
Regenerating node identity instead of backing it up keeps node private keys from ever existing outside their node, at the cost of one pairing step after a rebuild.
The bundle#
sparewall backup writes one archive with the active document, the last N generations, the encrypted cluster secrets, a lease export, the running image digest and the node's public keys. A systemd timer runs it on a configurable schedule (hourly by default) and sends it with restic, which encrypts the repository itself, to a configurable repository: a local path, SFTP, S3-compatible storage or a restic REST server. Backups can be turned off. Standalone nodes have no peer copy, so a shorter schedule is recommended where lease continuity matters.
Restore by scenario#
| Failure | Restore |
|---|---|
| Bad configuration change | Confirm timeout reverts it; otherwise sparewall rollback |
| Bad OS or container update | bootc rollback and reboot that node |
| One node destroyed | Reinstall with the same node name, add its new sync key to the document and apply; the peer pushes configuration and secrets, DHCP HA resyncs leases, conntrackd bulk-syncs |
| Both nodes destroyed | Reinstall both, restore the bundle (document, secrets, leases) before services first start |
| Git lost | sparewall export from either node, or the latest bundle |
| Registry lost | Rebuild images from the Containerfile; re-pin container digests if upstream images moved |
CI runs a restore drill on every release candidate: destroy one node, then both, and restore from the latest bundle.
Releases, upgrades and versioning#
Every image a node runs is built in CI, signed, and verified on the node; upgrades are orchestrated by the coordinator, never by a timer; and three independently versioned interfaces have rules that keep a rolling upgrade or a rollback from stranding a node.
Build, sign, publish#
- CI builds the OS image from the Containerfile with the base image pinned by digest and records the exact package list as the image manifest. Renovate (or a scheduled job) bumps the base digest so security fixes flow in automatically.
- An SBOM (syft) is generated for each image; images are signed with cosign, using a key held in CI secrets.
- Everything is published on GitHub. The OS image goes to GitHub Container Registry as
ghcr.io/sparewall/sparewallwithstableandtestingchannel tags, signatures and SBOMs attached. CLI binaries, checksums, SBOMs and installer disk images go on GitHub Releases (2 GiB per asset, so a larger installer ships compressed or split). - License allow-lists (RPM
License:tags andcargo-deny) gate the build.
Verify on the node#
The image ships a containers signature policy requiring the project's signature; bootc enforces it on switch and upgrade, and Podman enforces it for Quadlet images. Unsigned or wrongly signed images are refused.
Upgrade policy#
- bootc's own automatic update timer is disabled.
sparewall upgradestages the new image on the BACKUP node, pre-pulls bound container images, reboots it, waits for ok health and matching config hashes, fails over, then repeats on the other node. A failed gate stops the upgrade;bootc rollbackreturns that node. - Channels: every passing build reaches
testing; it is promoted tostableafter the two-node test suite passes. Nodes follow one channel:updates.channel, else the channel tag they track, elsestable(a node installed from release media tracks a build tag, which is no channel). - Rebuilds: between releases, the newest release is rebuilt from its tag on newer base images when they bring security advisories, and at least monthly, as
X.Y.Z+rN; it passes every suite before its release's tag andstablemove to it (#187, docs/releasing.md). - Versions: a release's image carries its version (
org.sparewall.version); a build between releases is the next patch's prerelease (0.3.2-dev.5+g<commit>), so builds sort as semver says. A node offers only a newer version, or the same one rebuilt, and refuses an older one unless asked (--allow-downgrade). - Modes: manual by default; optionally automatic within a maintenance window (
updates.mode: windowed,updates.window, #84). The master (or a standalone node) tries each window once, only with health ok, nothing pending, the pair in sync and not held, and no unacknowledged failure of an earlier scheduled upgrade, then runs the same sequence assparewall upgrade. A failure degrades theupgradecheck and blocks scheduled upgrades until acknowledged. - Checking: each node checks its channel every few hours and logs, once, when an update appears or goes away (a fixed journal
MESSAGE_ID, an event, a metric). An available update never affects health, so it never moves a pair's addresses.updates.check: falseturns the check off. - Standalone nodes use the same command and accept one reboot of downtime.
- The registry keeps every digest ever deployed, so rollbacks and disaster recovery can always fetch it.
Versioning and compatibility#
| Version | Changes when | Rule |
|---|---|---|
| Release (image, semver) | Every release | The image carries the coordinator with the daemons and providers it renders for, so they never skew within a node |
| Config schema (integer revision) | A field is added, or the format changes | Each field names the revision that added it, and a document records the newest revision among the fields it uses, so a release reads every document that needs nothing newer. A format change that is not just an added field needs a migration, which is an explicit step |
| Peer protocol (Varlink interface) | Node-to-node calls change | Only additive changes within an interface; breaking changes get a new interface name; nodes negotiate the highest common version |
An added field needs no migration: a document that does not use it keeps its revision, and every release that reads that revision still reads it. New fields are gated on the oldest release in the pair: each node reports the newest revision it reads in its hello (a node that does not say reads revision 1), and the coordinator refuses a change, rollback included, that needs a newer one. A format change that is more than an added field goes: upgrade the BACKUP node, fail over, upgrade the other node, then run sparewall schema upgrade, which migrates the document as an ordinary generation.
Rollback rules:
- Rolling the image back is safe while the active generation needs no newer revision than the older release reads.
- Otherwise the older coordinator cannot read it. At boot it runs the newest generation in its history that it reads, or the bootstrap configuration if there is none, and reports
generationfailed, naming the generation it skipped and why. Releases before 0.3.2 lack this fallback: roll the configuration back to a generation they read first. - Migrations ship with a down-migration where possible, so
sparewall schema downgradecan precede an intentional image rollback. - Backup bundles record their schema version; restores follow the same rules.
Performance and sizing#
Small-office loads (a 1 to 2.5 Gb/s WAN with NAT and a few thousand connections) are expected to fit software forwarding on a modern mini PC or a virtio VM; this is measured, not promised. In a pair the standby must carry the full load, so everything is sized for the smaller node.
Connection tracking#
- The conntrack table maximum and hash size are set explicitly in the document as one value both nodes can hold; the kernel default scales with RAM and would otherwise differ between nodes.
- The established-TCP timeout is lowered from the kernel's 5-day default (to about a day) so dead entries do not fill the table.
nf_conntrack_tcp_loosestays enabled (the default) so a new master picks up mid-stream connections.
Kernel and NIC settings#
- Reverse-path filtering is strict on single-homed LANs.
- ARP behaviour (
arp_ignore,arp_announce) is set on interfaces carrying gateway addresses so replies always match the interface asked. - GRO, TSO and GSO stay on; the kernel disables LRO automatically when forwarding. Overrides are per port for misbehaving drivers.
- VMs use virtio multiqueue with one queue per vCPU; physical nodes use irqbalance, or RPS where a NIC has one queue.
- nftables flowtables are the largest available forwarding gain and are enabled only once proven compatible with conntrackd failover.
Benchmarks#
- iperf3 through NAT, single and multi-stream, both directions, on each node.
- New-connection rate, and filling the conntrack table to its maximum.
- Failover under load: interruption length and which flows survive.
- Repeated with high-rate rule logging and with CAKE on the WAN, both CPU-heavy.
- Results are kept per hardware profile in the repository and compared on every release, on real hardware rather than shared CI runners.
Testing and CI#
Each layer is tested where it is cheapest, and promotion to the stable channel is gated on a two-node VM suite that exercises failure, upgrade and restore end to end. Everything except performance benchmarks runs on GitHub Actions' hosted runners.
| Layer | Tests | When |
|---|---|---|
| Schema and CLI | Valid and invalid document fixtures; property tests for merge, patch and set (set-then-get round-trips, idempotent merges, canonical hash stable across key order and JSON vs YAML); fuzzing of the parsers | Every commit |
| Renderers | Snapshot tests from document to networkd, nft, keepalived, conntrackd, provider and WireGuard files; every rendered file also passes its own checker | Every commit |
| Coordinator logic | Unit tests with fake adapters: apply, confirm, rollback, divergence, health levels, role checks | Every commit |
| Providers | The role's conformance suite against every provider and version | Every merge |
| Single-node VM | Boot the image, bootstrap, first apply, standalone mode, backup and restore | Every merge |
| Two-node VM suite | Failover (kill the master, cut one VLAN, cut only the sync VLAN, flap a bond member); flow survival; lease continuity; VPN client reconnect; rolling upgrade from the previous release; schema upgrade and downgrade; divergence and sync --from; full restore drill |
Before promotion to stable |
| Policy conformance | Generate the expected reachability matrix (zone pairs by service) from the document and probe it from test clients in each zone | In the two-node suite |
| Performance | Benchmarks compared with the previous release | Each release, on real hardware |
On GitHub Actions#
Standard Linux runners for public repositories (4 vCPUs, 16 GB RAM, 14 GB SSD, with /dev/kvm) run everything above except benchmarks.
- Only the firewalls are VMs. Two at 1.5 to 2 GB each fit easily; LAN clients, the WAN upstream and VPN clients are network namespaces or containers on the runner, attached to the same bridges.
- Switching: Open vSwitch on the runner provides VLAN trunks and an LACP bond, so every port shape is exercised. A VLAN-filtering Linux bridge is the fallback.
- One scenario per job: a matrix of failover, upgrade, restore, VPN and policy conformance, each booting its own pair.
- Disk is the tight resource: preinstalled toolchains are removed at job start, and the upgrade test uses a throwaway local registry.
- Outcomes, not timings. Nested virtualization makes timing variable, so tests assert that gateway addresses moved and flows survived, with generous timeouts; failover timing is measured on real hardware.
Self-hosted runners, if added for benchmarks or capacity, never run workflows triggered by pull requests from forks; they are limited to protected-branch pushes, releases and manual runs.
Web UI and HTTP API#
The web UI and the HTTP API are milestone 7. Work on them began while milestone 6's 0.x releases were still proving themselves at real sites, and 1.0 waits for both. A first version shipped in 0.3.0: status, history and rollback, the configuration editor, the zone policy matrix, and users and tokens. The UI is the Varlink API's first client not built alongside it, and the gaps it finds (live events for status pages, errors that name the field at fault, schema metadata for forms, concurrent edits) should be closed before 1.0 freezes the schema, the Varlink API and the HTTP API together.
Off until enabled#
A node serves no web UI and no HTTP API until the document enables them (management.web). Enabling it is an ordinary change, validated, applied, confirmed and recorded in the history, and so is turning it off again. It listens only on the management network, enforced by systemd and nftables like the health and metrics listener, with the mgmt certificate from tls.certificates or the node's self-signed one. SSH, the console and the anti-lockout rule never depend on it, so a broken UI cannot lock anyone out.
Three pieces#
| Piece | Where | Role |
|---|---|---|
| The coordinator | This repository | Serves a restricted socket next to the root-only one. A client binds its connection to a principal with a token before anything else, and the coordinator checks every call against that principal's role and logs every mutation with it (#11). The root-only socket is unchanged |
sparewall-httpd |
This repository | An unprivileged, sandboxed Rust service with its own SELinux domain and no network: it serves plain HTTP on a Unix socket. It authenticates browsers and API clients, calls the restricted socket on their behalf, and serves the UI's files. The coordinator keeps the HTTPS port and its certificate, answers the health endpoints itself, and passes every other request to this socket, so the UI, the API and health checks share one port and one certificate, and the service never holds a private key |
| The UI | This repository (ui/) |
Angular with Angular Material, built into a static bundle that the image includes. No container, since sparewall-httpd serves the files. CI runs the Rust jobs and the UI's jobs only for changes that touch them |
The HTTP API follows the conventions of systemd's varlink-http-bridge: POST /call/<interface.Method> with the parameters as JSON, and streamed replies (more) as application/json-seq. Generic Varlink-over-HTTP clients then work with a token, and an OpenAPI description generated from the same interfaces serves the UI and scripts. The bridge itself is not used: it authenticates callers but does not authorize them, runs as root, and connects to each socket as itself, so the coordinator could not tell an admin from a viewer, and it has no login or session model for browsers.
Browser authentication#
- People log in as named local users. Each user has one role (
admin,operator,viewerormonitor), and an admin manages them (sparewall user add alice --role operator). The built-inadminaccount is one of these users. Password hashes (crypt(3), as shadow keeps them) are cluster secrets, like theadminhash, and logins are rate-limited. - The coordinator checks the password (
org.sparewall.Auth.Login) and issues a short-lived, opaque session token for that user from its token store, so ending a session, revoking it or removing the user takes effect at once. sparewall-httpdholds no authority of its own. It binds each call's connection with the caller's session or API token, and the coordinator derives the principal and role from that token alone, sosparewall-httpdcannot act as anyone other than the caller or with more than the caller's role. Without a token, the restricted socket allows onlyBindandLogin.- The session travels in an
HttpOnly,Secure,SameSite=Strictcookie, and every request must also carry a custom header, which a cross-site form cannot send. - Scripts use API tokens in an
Authorization: Bearerheader instead. - Single sign-on (OpenID Connect) can follow later; it maps an identity provider's users or groups onto the same roles, and local users keep working.
The UI#
Much of the configuration editor is generated from the document's JSON Schema (sparewall schema show), with JSON Forms' Angular Material renderers, so a schema change reaches the UI without a hand-built form. Hand-built screens cover what needs real design: the zone policy matrix, status and health, apply with its confirm countdown, history and rollback, and the pair's sync state. In a pair the UI is reached through either node or the management gateway address; changes go through the coordinator, which pushes them to the peer as it does for the CLI.
Project#
Sparewall lives at github.com/sparewall; sparewall.org is the project domain and the source of the org.sparewall interface namespace. Everything the project builds is open source, and every artifact is published on GitHub.
Repositories#
| Repository | Contents |
|---|---|
sparewall/sparewall |
Cargo workspace (sparewalld, sparewall, sparewall-httpd, schema, renderers, providers), the web UI (ui/), Containerfile and Quadlet units, VM test suites, example documents, and the documentation under docs/ |
sparewall/.github |
Organization profile, shared workflows, security policy, contributing guide |
The schema, coordinator, providers, web UI and image live in one repository because they change in lockstep (the UI is a client of the HTTP API that the same release freezes): the image pins the daemon versions the providers render for, and one release tag means one tested image. Documentation lives beside the code so it changes in the same pull request. Rust crates stay unpublished on crates.io until there is a reason to publish them, since crate names cannot be reclaimed.
Licensing#
| Component | License |
|---|---|
Coordinator, CLI, sparewall-httpd, providers, schema (built here) |
GPL-3.0 |
| Web UI (built here, milestone 7) | AGPL-3.0, as a network service |
| Kea | MPL-2.0. All hooks are open source since 3.0 except RBAC and the Configuration Backend, which Sparewall does not use |
| systemd | LGPL-2.1+ (some tools GPL-2.0) |
| nftables, conntrack-tools, keepalived, chrony, ulogd2 | GPL-2.0 family |
| Podman, bootc, cosign, syft, node_exporter, Prometheus | Apache-2.0 (bootc also MIT) |
| zlink | MIT |
| Unbound | BSD-3-Clause |
| lego | MIT |
| restic | BSD-2-Clause |
| Fedora base image | Free licences, except redistributable binary NIC firmware in linux-firmware |
MIT and Apache-2.0 dependencies are compatible with GPL-3.0 and AGPL-3.0. CI enforces license allow-lists for RPMs (License: tags) and crates (cargo-deny), so a non-free or incompatible dependency fails the build. Licenses in this table should be confirmed by that check rather than taken from this document.
Development milestones#
Build bottom-up: a bootable image, then a standalone firewall, then services, then HA, then everything around it. Each milestone ends with tests that run in CI.
| # | Milestone | Delivers | Exit criteria |
|---|---|---|---|
| 0 | Foundations | Repositories, CI skeleton, Fedora bootc Containerfile with networkd, nftables and Podman; signed image published to ghcr.io/sparewall/sparewall:testing; license gates |
The image boots in a CI VM; its signature verifies; the license checks pass |
| 1 | Standalone core | sparewalld and sparewall; schema v1 for ports, networks, zones, objects, policy, raw, forwards; networkd and nft renderers; generations with confirm and rollback; bootstrap mode; anti-lockout; /livez and /readyz |
Single-node VM suite: bootstrap, first apply, rollback on missed confirm, policy conformance across VLANs |
| 2 | Services | Provider interface; Kea 3.0 and Unbound providers with conformance suites; chrony; log forwarding; /metrics; backup bundle and restore |
DHCP leases and reservations on every VLAN; local DNS; standalone backup-and-restore drill |
| 3 | High availability | Sync VLAN and WireGuard tunnel; keepalived and conntrackd; Kea HA; peer push, hashes and divergence handling; health-driven VRRP priority | Two-node suite: failover scenarios, flow survival, lease continuity, sync --from |
| 4 | Access and secrets | Secret store; users, tokens and roles; ACME (RFC 2136 and lego) with self-signed fallback; remote-access WireGuard | Token and role tests; certificate issuance against a test CA; VPN client survives failover |
| 5 | Releases and upgrades | sparewall upgrade with channels and health gates; signature enforcement on nodes; schema versioning and migrations; installer images on GitHub Releases |
Rolling upgrade from the previous release; schema upgrade and downgrade; unsigned image refused |
| 6 | First production deployments | 0.x releases: hardening pass (SELinux module, sandboxing score), benchmarks on real hardware, documentation | Runs in production at two sites; restore drill passes on real hardware |
| 7 | Web UI and HTTP API | Role checks on a restricted socket (#11); sparewall-httpd; the UI; opt-in through the document |
The UI and the HTTP API drive every operation the CLI does, under each role's limits; 1.0 released, freezing the schema, the Varlink API and the HTTP API |
Later features (multiple WANs and WAN failover, DDNS, IDS/IPS, dynamic routing) follow 1.0 and slot in as providers or schema additions.
To prove in the lab#
Every component here is mature, but some combinations are unproven. Each item below has a concrete test and a fallback; the milestone column says when it must be settled.
| Unknown | Test | Fallback | By milestone |
|---|---|---|---|
| networkd drops keepalived gateway addresses on reload or restart | Hold MASTER; run a link reconfigure, networkctl reload, then a networkd restart; watch for address loss and ARP gaps |
KeepConfiguration=, ManageForeign*=no, never restart networkd in production paths |
3 |
| conntrackd failover loses flows | Long-lived TCP and UDP flows through the pair while the master is killed | Tune FTFW timers; test nf_conntrack_tcp_be_liberal |
3 |
| Flowtables hide state from conntrackd | The same test with a flowtable enabled | Leave flowtables off | 6 |
networkd's NFTSet= elements vanish on ruleset reload |
Reload the nft script; check the sets still hold WAN and LAN addresses | Never recreate tables; trigger a link reconfigure after reloads | 1 |
| Kea 3.0 misses VLANs that appear late | Boot with a VLAN whose parent comes up slowly | Kea 3.2 with interface-redetect; or start Kea after systemd-networkd-wait-online |
2 |
| Kea 3.2 container images are not published | Check ISC's registry | Kea 3.0, or build images from distribution RPMs | 2 |
| Container images are absent after an offline install | Install from the ISO with no network; check bound images | Embed images in the installer | 5 |
machine-id persistence with a transient /etc |
Reboot and upgrade with transient /etc enabled |
Keep the 3-way-merged /etc |
6 |
| bootc's signature-enforcement option and flag name | Switch to an unsigned image | Enforce through the containers policy alone | 5 |
| OVS with an LACP bond on GitHub's hosted runners | Run the two-node suite there | VLAN-filtering Linux bridge with a bond in a namespace | 3 |
| No TPM on a node | Give libvirt VMs a virtual TPM; check physical hardware | Host-key encryption of secrets, documented as weaker | 4 |
| A leaked DNS-01 credential can issue certificates for the zone | Scope the TSIG key or cloud role to _acme-challenge records only |
Delegate a dedicated challenge subdomain | 4 |
| Remote-access reconnect time after failover | VPN client VM during failover | Tune the recommended client keepalive | 4 |
| The smaller node cannot carry full load after failover | Benchmarks | Flowtables, lighter logging, or larger hardware | 6 |
| Mixed coordinator versions during an upgrade | Rolling upgrade across a schema change | The versioning rules: schema bump only after both nodes upgrade | 5 |
Version baseline and sources#
Versions current in October 2026; recheck when the Containerfile is written.
| Component | Version | Note |
|---|---|---|
| systemd | 262, released 22 September 2026 | 261 added networkd link Varlink methods and DHCP relay |
| Fedora | 45 being prepared with systemd 262 | Fedora CoreOS and bootc are being unified for Fedora 46 |
| CentOS Stream 10 Hyperscale SIG | systemd 261.3 rebuilds | Stock Stream 10 ships 257 |
| Podman | 6.0 | Netavark with nftables only; Quadlet improvements |
| Kea | 3.0 LTS; 3.2 stable since 24 June 2026 | Control Agent removed in 3.2 |
| keepalived | 2.3.x | |
| zlink | Releases through 2026 | MIT |
Other components (chrony, ulogd2, restic, lego, step-ca, node_exporter, cosign, syft) are used at their current distribution or upstream releases.
Sources#
- systemd.network(5), systemd 262
- systemd 261 release notes (LFS mirror) · Linuxiac on systemd 261
- systemd v257: sd-varlink made public
- Fedora CoreOS: why networkd is absent · CoreOS and bootc unification
- Fedora bootc filesystem layout
- Kea 3.2 announcement · Kea hooks feature matrix · Kea 3.2.0 release mail · ISC container images
- conntrack-tools manual · keepalived news
- networkd restart removing keepalived addresses (Ubuntu bug 1815101)
- Podman 6.0.0 release notes
- zlink
- GitHub-hosted runner specifications