rust nfnetlink management suite
  • Rust 98.8%
  • Shell 0.6%
  • Nix 0.6%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
goeranh 9a2e8372b1
Some checks failed
ci / test (push) Successful in 44s
ci / package-debian (push) Has been skipped
ci / package-alpine (push) Has been skipped
ci / fuzz-smoke (push) Successful in 34s
ci / netlink-live (push) Has been cancelled
ci / gui (push) Failing after 27s
perf(fwui): decouple flow telemetry and incrementalize topology placement
2026-11-08 15:04:34 +01:00
.cargo fwguard: nftables management daemon (fwd) + egui GUI (fwui), kernel 7.3 verified 2026-10-26 17:16:32 +01:00
.github/workflows netlink hardening 2026-11-05 15:32:41 +01:00
apps perf(fwui): decouple flow telemetry and incrementalize topology placement 2026-11-08 15:04:34 +01:00
crates fix: canonicalize reconcile inputs and scale snapshots 2026-11-05 19:46:02 +01:00
deploy feat(telemetry): add Filebeat ECS pipeline and exact drop verdicts 2026-11-04 18:24:02 +01:00
docs fix: canonicalize reconcile inputs and scale snapshots 2026-11-05 19:46:02 +01:00
scripts ui topology optimizations for large networks 2026-11-07 10:35:29 +01:00
vendor feat(flow): add live eBPF flow telemetry overlay 2026-11-02 14:36:01 +01:00
.gitignore build: repair NixOS module, drop result symlinks, prune deps 2026-10-27 10:17:43 +01:00
Cargo.lock fix: canonicalize reconcile inputs and scale snapshots 2026-11-05 19:46:02 +01:00
Cargo.toml fix: canonicalize reconcile inputs and scale snapshots 2026-11-05 19:46:02 +01:00
DEBUGGING_NOTES.md fwguard: nftables management daemon (fwd) + egui GUI (fwui), kernel 7.3 verified 2026-10-26 17:16:32 +01:00
flake.lock nix static builds for armv7l 2026-11-01 12:58:25 +01:00
flake.nix refactor: harden data structures, remove duplication and optimize hot paths 2026-11-05 00:34:13 +01:00
README.md ui topology optimizations for large networks 2026-11-07 10:35:29 +01:00

fwguard — nftables firewall management (Rust)

A GUI + daemon pair for viewing and managing nftables rulesets across multiple machines (and/or netns). Complete as-implemented architecture documentation: ../ARCHITECTURE.md (research folder) — components, thread models, wire formats, kernel-7.3 ABI notes, security model.

Layout

apps/fwd      daemon: owns CAP_NET_ADMIN, nft netlink service thread + read-only rtnetlink task + framed-protocol listeners
apps/fwui     GUI: egui/eframe, connects to local daemons over UDS and remote daemons over SSH, snapshot-driven UI
crates/fw-core    domain model (tables/chains/rules/sets) — plain data, serde, no I/O
crates/fw-fabric  fabric model + compiler/solver/reconciler (no egui/daemon state)
crates/fw-netlink hand-rolled NETLINK_NETFILTER client: dumps, atomic batches, NEWGEN events
crates/fw-route   read-only NETLINK_ROUTE snapshots via rtnetlink (interfaces/addresses/routes/rules/neighbours/bridge FDB/VRF/tunnel)
crates/fw-proto   wire protocol v12: [u32 BE len][flags][JSON, optional deflate], Hello/Welcome auth, request/batch/response + pushes
crates/fw-client  async multi-daemon connection pool with reconnect/backoff (used by the GUI)

Key invariants:

  • One nft netlink thread owns the nftables socket + cache + commits ("single writer" is structural). A separate async task reads routes via NETLINK_ROUTE.
  • The daemon pushes a full RulesetDoc snapshot after every kernel change it observes (NEWGEN), so the GUI never holds stale state and needs no polling.
  • Batches carry the snapshot genid (CommitAt); stale writes are rejected by the kernel with -ERESTART and surfaced as a conflict error. Callers without a snapshot can still pass None, which sends genid 0 (wildcard).
  • The GUI has no privileges; tokens are compared constant-time; read-only tokens exist for shared dashboards.

Security

  • Transport. The daemon only listens on a Unix socket: it is created 0660 (owner + group) and still requires token authentication. Remote GUIs use OpenSSH stream-local forwarding to that socket; fwui spawns ssh -N -L <local.sock>:<remote.sock> <host> and speaks the normal framed protocol over the local socket. SSH authentication is public-key only, password/keyboard-interactive prompts are disabled, and host keys must already be trusted in known_hosts. There is no remote TCP listener and no TLS layer to configure.
  • SSH local sockets. Each forwarded socket is created inside a 0700 directory under $XDG_RUNTIME_DIR/fwguard/ssh (fallback: /tmp/fwguard-<uid>/ssh), with a 0600 socket. Its filename starts with the daemon profile label, sanitized to a filesystem-safe name, plus a process id and random suffix so concurrent profiles/instances never collide. The socket is removed when the connection closes.
  • Local peer identity. fwui validates the uid of the process on the other end of a local socket instead of trusting the socket-path owner (which a local attacker can pre-create/symlink). Only root, the current euid, or an explicitly configured FWGUARD_TRUSTED_UID is accepted; a daemon running as a dedicated service user must set that variable in the GUI environment.
  • Tokens. Admin and read-only tokens are compared in constant time. Prefer --token-file/--readonly-token-file over --token (which exposes the secret in process arguments). Token files must be regular files owned by the daemon uid, not group/world-writable, and at most 8 KiB. The generated admin token is stored at ~/.config/fwguard/token with mode 0600 and replaced atomically; if no private config directory exists, fwd refuses to start rather than logging an ephemeral secret. An empty/blank token file is an error, never a silent fallback to a previously stored token.
  • Untrusted input. Client-supplied names are stripped of control/escape characters and length-capped before logging, and empty --dns-allow entries are rejected (they never become wildcards). Open connections, authenticated clients, and concurrent handshakes are bounded; excess connections are rejected and failed logins are slowed.

Developing (Nix)

nix develop                     # rustc/cargo + rustfmt/clippy + nftables/iproute2/unshare + GUI link deps
nix develop .#nightly           # Rust nightly + rust-src + bpf-linker/bpftool for eBPF probes
cargo build                     # everything (deps come from ./vendor — offline, see .cargo/config.toml)
cargo test --workspace          # unit + parse tests (no privileges needed)
scripts/check.sh                # fwui + fw-fabric guardrails: rustfmt, clippy, tests

Inside the default devshell the nightly toolchain is available without replacing stable Cargo for normal builds:

cargo build -p fwd --features flow-telemetry
FW_EBPF_BUILD=1 scripts/build-ebpf.sh   # rebuild the checked-in probe object

The checked-in crates/fw-ebpf/fw-flow-probes object keeps normal and Nix builds offline; the nightly shell is only needed when changing the probe source.

scripts/check.sh is the required pre-refactor check for the GUI and Fabric planning modules. It is scoped to apps/fwui + crates/fw-fabric while the rest of the workspace is not yet rustfmt-clean; CI runs the same script in the gui job.

Live netlink integration runs in a throwaway user+net namespace — no root or sudo needed:

unshare -Urn cargo test -p fw-netlink --test live -- --nocapture
# or: unshare -Urn bash && cd <repo> && ./target/debug/deps/live-*  (after cargo build --tests)

Run the daemon and GUI:

# terminal 1 (needs root or CAP_NET_ADMIN):
sudo -E cargo run -p fwd        # -E keeps XDG_RUNTIME_DIR/SUDO_GID; token is
                                # written to ~/.config/fwguard/token (0600)
# The UDS is 0660. When run via sudo, its group is changed to $SUDO_GID so the
# invoking user's GUI can connect. For a system service use the NixOS module
# (services.fwguard.socketGroup, default "fwguard").

# terminal 2 — inside `nix develop` (no privileges needed):
./target/debug/fwui             # “Add daemon”: uds:/run/user/<uid>/fwd.sock + token

GUI: why you must run it from the devshell (or use the nix build)

winit/wgpu do not link their GUI libraries; they dlopen them at runtime (libwayland-client.so, libX11.so.6, libvulkan.so.1, ...). Inside nix develop the devshell exports those store paths in LD_LIBRARY_PATH (modern nixpkgs mkShell no longer does this automatically — see flake.nix); outside, the loader finds nothing and you get:

Error: WinitEventLoop(Os(... WaylandError(Connection(NoWaylandLib))))

The nix-built binary embeds a RUNPATH with all store paths (patchelf in postFixup, applied after stdenv's fixupOutput resets it), so it runs anywhere on the same NixOS machine:

nix build .#fwguard-gui && ./result/bin/fwui    # works outside nix develop too

(Changing dependencies? cargo vendor again and commit — builds are hermetic.)

Remote GUI → daemon: add the host through Add daemon → SSH + remote socket. fwui opens an OpenSSH stream-local forward to the daemon's Unix socket, so there is no remote TCP listener and no plaintext token on the network.

Requirements:

  • ssh (OpenSSH) must be installed locally. The Nix fwguard-gui package wraps the binary with OpenSSH on PATH; the dev shell includes it too.
  • The SSH host key must already be in known_hosts. fwui uses StrictHostKeyChecking=yes and never accepts a key implicitly.
  • Public-key authentication only. Password and keyboard-interactive prompts are disabled; use an agent if the key has a passphrase.
  • The remote account must be able to open the daemon socket, for example root, or a user in the NixOS services.fwguard.socketGroup group.
  • sshd must permit stream-local forwarding (AllowStreamLocalForwarding yes, normally the default).

Example UI values:

SSH host:       root@target
Remote socket:  /run/fwguard/fwd.sock
Identity file:  (optional; otherwise ~/.ssh/config and the agent are used)

The generated local socket is named after the profile label, for example home-router-<pid>-<random>.sock, and is only accessible by your user. The daemon imports network inventory read-only from NETLINK_ROUTE; the GUI's Network tab shows it and allows labelling each object per host. Labels are stored in the active project, keyed by endpoint + stable object id. Network and interface rows have a Rule… action: pick any compatible table/chain, choose from/to direction, counter and verdict; prefix matches create/reuse a named interval set and insert the lookup rule.

The Ruleset view can create type nat base chains and SNAT/DNAT/masquerade rules. Explicit NAT targets may be a single address or an address range (203.0.113.5-203.0.113.10), with optional port ranges; existing NAT rules are editable in place with the structured rule editor. NAT chains must use prerouting/output for DNAT, postrouting for masquerade, and postrouting/input for SNAT. The structured rule editor also supports icmp type/icmp code, icmpv6 type/icmpv6 code and ip6 hoplimit, so neighbour-discovery and PMTUD rules can be inspected and edited after creation.

Projects

fwui keeps daemon sets and their desired state in projects. The project switcher sits at the top of the left sidebar. Projects opened in the current session stay connected as additional rows, so switching between them does not reconnect or discard transient editor state. On the next launch only the last active project is reopened; the rest remain available through Manage projects….

A project owns its daemon profiles, per-project tokens, Fabric rules, network labels, topology layout/manual placement/viewport, selected daemon and last main view. Storage is per project:

~/.config/fwguard/workspace.json
~/.config/fwguard/projects/<project-id>/project.json
~/.config/fwguard/projects/<project-id>/fabric.json
~/.config/fwguard/projects/<project-id>/usage.json
~/.config/fwguard/projects/<project-id>/tokens.json

Project directories use mode 0700; project, fabric, usage and token files use 0600 and atomic replacement. Tokens never enter project.json.

The old single-workspace ~/.config/fwguard/fabric.json, ~/.config/fwguard/tokens.json and eframe fwguard.prefs are ignored and left untouched after upgrading; fwui starts with a new empty project.

The Topology tab is the primary global multi-host view; the Fabric tab holds the desired-state rules and editors. Fabric stores its desired state in the project's fabric.json (schema version 11; older files load unchanged, v7 zones are folded into groups, v9 adds optional sites and v11 adds host services) and reconciles it onto each connected daemon:

  • Bind each host to an existing table and its input/output/forward base chains. Fabric creates managed user chains (fwg_in, fwg_out, fwg_fwd) and inserts marked jumps at the top of the selected base chains. Existing unmanaged rules are never modified. A binding may also select existing NAT base chains for source/destination translation; those chains must be type nat on the matching postrouting/prerouting hook. The bind dialog can initialize the table and all missing conventional filter/NAT base chains on that host before saving, so a freshly connected daemon can be bound without preparing its ruleset first. Bridge/bond hosts that only switch L2 (no second routed subnet) get an accepting forward base chain instead of a drop-policy one, so br_netfilter cannot blackhole bridged traffic; the chain stays available for manually authored bridge filter rules, and it switches back to the binding policy once the host has an L3 routing topology. Bind all unbound applies the same default binding to every connected daemon that is not bound yet and initializes every missing table/base chain. It retries briefly while newly connected daemons finish publishing their ruleset snapshots. Fabric records which conventional base chains and fwg_* objects it created; unbinding deletes or policy-restores only those objects, never pre-existing user chains. Cleanup for an offline host is kept as a tombstone and retried when it reconnects.
  • A host binding can also enable host-local services for the IPv6 edge: neighbour discovery for a client, a router, or both; optional SLAAC router solicitations/advertisements; ICMPv6 errors (including Packet Too Big); MLD; and DHCPv4/DHCPv6 as a client, server, relay or client+server. Strict ND matches hop limit 255 and uses link-local/unspecified source sets for RS/NS and link-local source for RA/Redirect; NA is type/hop-limit matched because its source may legitimately be a global target address. Rules are inserted into the managed fwg_in/fwg_out chains and removed again when the service is disabled. The Ruleset view has a standalone IPv6 baseline action for tables that are not Fabric-managed.
  • Mark an interface as a gateway uplink from the Topology view (right-click an interface lane -> Mark as gateway / NAT…). An uplink is host-bound and can masquerade IPv4 and/or IPv6 traffic leaving that interface. Uplinks are postrouting NAT egress rules only: the managed input/output/forward chains still decide what may pass, so normal Fabric connections and DNS policies remain the filter. Fabric creates/reuses the managed SNAT base chain and removes the rule when the uplink is disabled or deleted. The Fabric view lists all uplinks, their family flags, generated rules, and delete/edit actions.
  • Author a connection once (source host/network or FQDN -> destination host/network or FQDN, protocols and ports, per-endpoint roles). Source and destination selectors accept free-form IP/CIDR/interface text with live-filtered suggestions from the connected hosts' inventory. Protocols are TCP, UDP, ICMP (family-aware: ICMP on IPv4, ICMPv6/58 on IPv6), or any; ICMP needs no ports, and one connection may carry several protocols (e.g. DNS over both UDP and TCP 53). Roles are auto, local (traffic starts/terminates on this host: input/output), or gateway (the network is behind this host: forward). auto derives the role from the legacy path/selector, and connections whose endpoint selector is a non-local address in that host's connected network/neighbour table are promoted to gateway and re-solved. This is what allows a neighbour such as 192.168.99.1 behind test4 to use test4's forward chain and NAT. Existing unmanaged rule candidates are listed read-only. Rules in inet tables carry an explicit meta nfproto ipv4 / ipv6 guard, so IPv4/IPv6 header-offset matches cannot leak onto the other address family.
  • Groups are named collections of address selectors. Each member belongs to one host, so a group can describe addresses on a single host or span several hosts. Connection profiles are optional reusable service templates (protocols, ports, endpoint roles, statefulness, counters, NAT) that the connection editor can load into a policy. A connection now carries a list of source items and a list of destination items; each item is a host/socket plus any, an address/CIDR, interface, DNS domain, domain set, group, or tag. One item per side behaves like a direct connection. Additional items expand to every source/destination pair, and each pair gets its own sets/rules/counters and runs the full topology solver independently (including per-pair NAT-hop selection). This replaces the separate group-connection dialog: v9 group connections are migrated to multi-item connections on load, and their filter attachments keep working. Groups must be non-empty; deleting a group that is still referenced is blocked. A group selector used directly by one item must stay on that item's host; add one item per host to spread a policy.
  • A connection compiles its whole managed path. A source gateway -> transit router(s) -> local destination emits fwg_fwd on the source and transit hops and fwg_in on the destination, plus an fwg_out conntrack reply baseline on the local destination. Local-sourced flows use fwg_out with an fwg_in reply baseline. Example: a client network (gateway) -> fwd-managed router(s) -> a central DNS server (local), using UDP+TCP port 53 with roles gateway/local and auto-solve (or Solve now).
  • auto-solve path uses the topology solver over connected prefixes and bound transit hosts to build an ordered path with iif/oif per hop. It is prefix/topology based, not a full routing-table, VRF, or ECMP solver. Auto-solve takes precedence over cached hops and re-runs on every apply, so enabling it after Solve now still re-solves; with auto-solve disabled, explicit hops override via, and via networks remain a legacy/manual ordered-prefix constraint. When no NAT hop is pinned, the solver places SNAT on the source endpoint (or on a gateway destination, so the network behind it sees a routable source) and DNAT on the destination endpoint. Explicit NAT hops are validated against the hop's hook.
  • Fabric connections can apply source NAT (masquerade or explicit SNAT to an address/range, optional ports) and destination NAT (DNAT to an address/range, optional ports). The connection editor's resolved path table shows per-hop request/reply directions and the derived allow/baseline chains; S/D buttons pin SNAT/DNAT to a specific hop, and the NAT sections also offer path hop dropdowns. Multi-item connections pin source/destination NAT hops for every expanded pair. Compile creates managed fwg_nat_post/fwg_nat_pre base chains of type nat, emits marked NAT rules, and translates the address sets used by later hops. Destination NAT is applied before the destination allow rule; source NAT is applied after the source allow rule. Masquerade downstream source matches are omitted because the translated source address is not known statically. DNAT is emitted in prerouting without an output-interface match; SNAT in postrouting keeps both interface matches. SNAT is rejected on a local input destination and DNAT on a local output source. Dual-stack connections must be split when NAT is family-specific.
  • Filter chains are reusable Fabric-managed user chains. A host-bound chain belongs to one Fabric host; a floating chain has no host binding and is a host-agnostic template with a family/table compatibility constraint. Right- click a topology line to insert a new chain or attach a host-bound/floating one to a specific host/direction. Right-click an interface lane to create a new floating chain or attach an existing compatible chain directly to that interface for ingress (iif), egress (oif), forwarded ingress, or forwarded egress. Floating chains may be attached to several compatible hosts and are instantiated per host under the same stable fwg_flt_* name. Connection/line jumps still carry the edge's full traffic match, while interface jumps match only the selected interface/hook before entering the chain. Chain rules can narrow traffic further and accept, drop, return, or jump/goto another chain on the same host/table. Unattached chains are created too, so one chain can be reused as a jump target from several edges. Chain rules are edited with the same structured condition/action form as ordinary rules; floating-chain editing offers generic expressions and other floating chains as jump targets. Generated rules and the Ruleset view resolve fwg_flt_* names back to the friendly Fabric chain name inline.
  • Fleet is the inventory and lifecycle view: one row per daemon with connection state, agent build/OS/kernel/architecture/uptime (reported in the handshake), ruleset generation, interface/address/route/neighbour counts, Fabric binding/tags, health, site path and HA hints. It detects VRRP virtual MACs and addresses shared by more than one daemon, lists unmanaged neighbours discovered on managed prefixes, exports fleet-inventory.json, refreshes snapshots, reconnects profiles, and shows a build-mismatch upgrade plan. Agent upgrades stay operator-driven; the daemon has no remote-exec capability.
  • Sites / tenants are an optional hierarchy (sites in fabric.json) with parent sites, explicit host membership and prefixes. Topology gains a Site grouping that draws a labelled region per site and falls back to the longest matching prefix; the Fleet view shows each host's site path and prefix matching places multi-homed cards in the most specific site.
  • Topology renders each host/system as a compact card containing its networks, with neighbour hosts in a tray. The diagram is zoomable: use the mouse wheel or the Fit/−/+ toolbar controls, and pan with middle- or right-drag. It supports three selectable layouts: Cards (deterministic side-by-side system cards), Layered (source -> transit -> destination policy flow), and Force (deterministic edge-weighted clustering). Networks have fixed card width instead of spanning the screen. A separate group selector can cluster cards by Host (the default), Network, or Site; network grouping orders and attracts cards that share a connected prefix, assigns multi-homed cards to their dominant shared network, and draws labelled background regions around each group. Grouping works with every layout and resetting the layout clears manual placements. The view selector provides Physical (interfaces, bridges, neighbours, and detected links), Logical (one node per managed system, with collapsed policy paths plus VRF/tunnel sub-nodes), and Policy (the detailed per-interface policy map). Custom appears after changing the independent Layers toggles for physical links, policy edges, neighbours, DNS objects, tunnels, VRFs, filter chains, health, labels, and traffic. The traffic overlay uses counter deltas (or live flow rates when NetFlow collection is on) to draw a log-scaled, cool-to-hot halo whose width follows bytes/s or packets/s (selectable in Layers); system headers and site regions show rollups, and edge tooltips/details list per-hop rates, totals and observed idle age. The selected mode, layers and traffic metric are stored in the project; existing projects default to Policy. Enable NetFlow collection in the Layers menu to replace nft counter rates with live flow records from daemons built with flow-telemetry: connection badges show the current attributed rate averaged across path hops (not summed by hop), host cards show all observed traffic (including established/ct-accepted packets that bypass nft allow-rule counters), halos use the averaged flow rate, and tooltips list every hop's counter. The probe records ingress/egress direction, TCP flags, packet/byte totals, first/last seen, and a best-effort new/established state; egress observations are marked allow, while ingress packets that may still be dropped stay unknown. The toolbar reports when a daemon does not advertise flow telemetry or has not returned a report yet. Attribution for edge badges is conservative (protocol/ports plus both policy address sides), so overlapping policies may all be credited; host totals are deliberately broader. The toolbar's Trace action opens the read-only access query: enter source and destination addresses, protocol, and optional source/destination ports. It solves the path, evaluates the live nftables rules (falling back to the compiled desired policy for hosts without a snapshot), follows filter-chain jumps, reports NAT and route details, names the first accepting or blocking managed/unmanaged/base-policy rule, evaluates the established reply path, and highlights the path on the topology. Source ports are matched against both Fabric-compiled destination-port policy and any live source-port expressions. The Impact action compares the draft with the last published state (falling back to the newest snapshot), lists field, path, NAT, DNS and compiled-rule changes, highlights added/modified policy edges, draws removed policy paths as ghost edges, and shows affected hosts/sites for the selected change. The Findings action runs read-only policy analysis over the compiled per-host plans: it detects unreachable and duplicate rules, partial overlaps, allow/drop conflicts, CIDR/group containment, overly broad access, inactive filter attachments, and order-sensitive NAT overlaps. Findings are marked directly on affected graph edges and in the right-hand details panel. Each finding carries remediation links to edit or delete either rule involved, make the covering rule more granular, or inspect the compiled rule markers; destructive actions require confirmation and only change the draft until Apply all. Top-bar views can be torn off into native windows by dragging a tab out of the title bar (or via its right-click Move to new window action); the detached window has its own header and Dock button, and the main window switches to another docked view. Closing a detached view re-docks it. The last docked view cannot be detached, and switching projects re-docks all view windows. Dialogs, editors, findings, trace, explain, generated-rule and context-action windows also open as independent native child windows so they can be moved outside the main window and kept open while inspecting the topology. Context menus and dropdowns remain attached to their parent window. Neighbour hosts learned via ip neigh are promoted to their own system cards, linked back to the interface/network they were seen on instead of being drawn as a small box attached to that network. Neighbour entries that resolve to another connected daemon are drawn as neutral detected links labelled with the shared network CIDR. Bridges are rendered as switch cards; learned forwarding-database entries attach each host to the correct switch port, and hosts on the same switched L2 connect through the switch instead of as a direct full mesh. Click a link label for network actions; outbound/inbound connection actions create one connection for every connected daemon on that network, so a rule is not limited to a single selected daemon. Right-click a label to preselect the network prefix as an allow-rule source. Detect neighbours sends one UDP probe to every peer daemon address on a shared prefix, which populates the kernel's ARP/ND table even before any application traffic; the daemon then refreshes its network inventory. Connections are routed orthogonally between cards; compact edge badges show the name and state, while the right-hand details panel shows service, path, NAT, traffic totals/rates, per-hop observed usage, first/last observed hit, idle age, and edit actions. With nothing selected, the details panel lists current top talkers plus idle-30d/90d and burst counts. System headers/neighbour cards and edge badges can be dragged to custom positions; Reset layout clears those overrides. Click a lane to focus it, click a neighbour card for quick actions, click a badge to select an edge, or double-click a badge to edit. Right-click any system card, network/interface/DNS lane, or neighbour host to preselect it as an allow-rule source, then right-click the destination item and choose Create allow rule to open a prefilled connection editor. The selected layout mode is persisted.
  • Author DNS domain allowlists for specific source networks. FQDNs are resolved by each daemon's own system resolver (split-horizon safe) into per-host IPv4/IPv6 sets, refreshed on a timer while fwui runs. Exact names are reliable; *.example.com is best-effort (the suffix is resolved, not arbitrary subdomains). A policy may select an egress uplink: it is then compiled on the uplink's host (plus managed source/transit hosts found by the topology solver), resolves names on the uplink host, and matches traffic leaving that interface. This keeps the allow rule and the egress DNS result in one place; the uplink's IPv4/IPv6 NAT flags perform translation, while forward/input/output chains continue to filter. A domain policy uses the same per-protocol service rows as connections, so one rule can allow e.g. TCP 80/443, UDP 53 and ICMP together. When an egress uplink is selected the domain list is optional: leave it empty for an unrestricted outbound allow, or add domains/domain sets to restrict the destination. Policies without an egress still require at least one domain. Policies without an egress keep their previous per-host local/forwarded behavior. In Topology, select the client host card(s), right-click the uplink interface, and choose either Allow all outbound from … via this uplink… or Allow selected domains from … via this uplink… to open a prefilled policy.
  • Each host update is one atomic nfnetlink batch (RequestBatch). Fabric applies inbound/destination rules before outbound/source rules; the pair is not atomic across hosts, so partial states are surfaced and can be retried.
  • Change management lives in the Fabric view. Edits are a draft until an apply; a successful apply of every bound host publishes the baseline to published.json. Projects can require an approval for the exact draft hash (DNS refresh results do not invalidate it). Applies can be scheduled or run as an ordered canary rollout in batches with a settling interval between them. Every deployment records the pre-apply snapshot, so a recorded deployment can be rolled back and re-applied across the fleet. Approval, schedule/rollout state and the append-only audit.jsonl live beside fabric.json; the audit log records configuration edits, approvals, publishes, applies, schedules, rollout batches and rollbacks.

Packaging:

nix build .#fwguard-daemon      # or .#fwguard-gui
nix build .#fwguard-daemon-flows # fwd built with live flow telemetry
sudo nix run .#fwd -- --socket /run/user/$(id -u)/fwd.sock

NixOS module (see flake.nix):

services.fwguard = {
  enable = true;
  tokenFile = "/etc/fwguard/token";   # or let the daemon generate one in /run? no — file required on NixOS
  flowTelemetry.enable = true;        # CAP_BPF/CAP_PERFMON + live flow collector
};

Status

Done: workspace, full model + serde, netlink dumps/commits/events, protocol v12 (auth, roles, framing, network/flow inventory, daemon-side DNS resolution, atomic multi-op batches, rule userdata), client pool with reconnect, GUI browse tree with live counters (1 s counter-only poll; hover a rule for its packet/byte counters; double-click a rule to edit it), live snapshot updates, set-element add/remove, structured rule editor (create + in-place edit), counter objects, resolved rule/set detail view (clickable jump arrows, inline verdict maps and port ranges; address and interface fields are editable text with live-filtered inventory suggestions), read-only network inventory (interfaces, connected prefixes, routes, policy rules, neighbours, VRFs, tunnels) with persistent per-node labels, cross-node address/interface pickers in the rule editor, deletes (two-step confirm), prefs persistence, ruleset/network/event filters, human-readable counters and per-rule packet/byte rates, daemon health details, Fabric per-host dry-run previews, NAT chains/rules (masquerade, explicit/range SNAT and DNAT, editable in place), multi-host Fabric view (visual address/DNS policy map, paired connections, endpoint roles, multi-protocol services, topology auto-solver, managed chains/jumps, source/destination NAT, DNS domain sets, existing-rule match hints, live traffic overlays and observed usage history, optional live flow telemetry via the Aya TC collector), an access-query packet tracer with live/desired rule evaluation and topology path highlighting), change management (published baselines, approval-gated applies, scheduled applies, canary rollouts, cross-host rollback, append-only audit log), fleet inventory (agent identity, lifecycle/reconnect, HA hints, discovered neighbours, JSON export), site/tenant hierarchy and topology site grouping, packaging + NixOS module.

Base-chain policies are editable in the inspector (accept/drop). The update is sent as NEWCHAIN keyed by name without NLM_F_REPLACE: this kernel rejects REPLACE for existing chains (-EOPNOTSUPP), while the keyed update applies the new policy in place. Hook, priority and type remain immutable. New base chains default to accept (nft's own default). The rules tree and inspector scroll independently of the event log.

Observed usage history records only what fwui saw while polling; kernel counters do not carry timestamps, and counter resets after an apply are ignored rather than counted as traffic. Not yet (per plan phases): daemon-side usage timestamps, route/rule writes into the network inventory, always-on daemon-owned DNS set refresh while the GUI is closed, exact per-rule flow attribution and full conntrack state (the TC collector reports observed directional 5-tuples and nf_hook_slow records exact drops; per-rule attribution and non-drop conntrack state remain inferred), full DNS-proxy wildcard enforcement, verdict maps/flowtables, automated agent upgrades, and active LLDP/CDP/SNMP/cloud topology discovery (neighbour/bridge/FDB discovery from daemons is available today). The Network tab is a read-only import of the daemon's rtnetlink data.

GUI credentials: tokens are not written to project.json; each project has its own tokens.json (0600, created atomically) and the token field is password-masked. The daemon's generated admin token is ~/.config/fwguard/token (0600).

UI coverage and expert mode

The Ruleset view now exposes the full modeled nftables surface:

  • tables/chains/sets/objects carry their flags, userdata, handles and other metadata in the inspector;
  • set elements show timeout, expiration, userdata, catch-all/object-reference state and attached expressions;
  • object creation covers counter, quota, limit, connlimit, ct helper/timeout/ expect and secmark payloads, plus raw type:hex data for anything newer;
  • rules expose userdata/compat metadata, an advanced element/expression JSON field and a lossless raw fallback when the guided form cannot represent an existing expression stream;
  • flowtables have tree/inspector/editor support and are enabled only when the daemon advertises the flowtables capability;
  • the toolbar's Advanced JSON editor accepts exact Op/Expr JSON and is the completeness backstop for new kernel features before a bespoke form exists. It is sent through the same atomic-batch generation/conflict path and preserves unknown expressions as Expr::Raw.

fw-netlink models the full transaction surface used by nftables: tables, chains, rules, sets/maps/elements, stateful objects, flowtables, generations, batches, traces and the destroy/reset message variants. Chain/table/set/object userdata, set policy/descriptor-size/GC interval/set expressions, element expressions/object references, typed object payloads (quota, limit, connlimit, ct helper/timeout/expect, secmark), all standard expression families, ARP tables and flowtable hooks are encoded and decoded. Unknown expressions and object payload attributes are preserved verbatim (Expr::Raw / data_hex) so they survive a snapshot/apply round trip.

The service probes the running kernel at startup (GETGEN) and refuses to serve a kernel whose nftables netlink ABI does not match this tree.

Kernel 7.3 compatibility notes (this tree ≠ upstream)

The kernel at /home/goeranh/projects/sys/linux-build-nix-shell/linux (v7.3.0, custom) diverges from upstream nftables ABI in several ways — all of these were verified empirically against the running kernel and are baked into fw-netlink:

  • Host-byte-order netlink headers: nlmsghdr and nlattr headers are native byte order (upstream: big-endian). NLA numeric payloads (u16/u32/u64) remain big-endian. Proven empirically: LE header → kernel replies, BE header → message dropped.
  • nfnetlink batches: NFNL_MSG_BATCH_BEGIN/END = bare nlmsg types 0x10/ 0x11 (no subsystem); the subsystem goes in the BEGIN message's nfgenmsg.res_id (host order).
  • NFTA_SET_ID is mandatory for NEWSET — missing → -EINVAL. The value is stored (nft_trans_set_id) but never read; we assign distinct per-batch ids.
  • Registers: in this tree NFT_REG_VERDICT = 0 (first enumerator), not upstream's 0xffff; nft_parse_register() accepts 0..4 and 8..23, else -ERANGE. Sending 0xffff makes NEWRULE fail with errno 34.
  • Verdicts are shifted: NF_DROP=0, NF_ACCEPT=1, NF_STOLEN=2, NF_QUEUE=3; nft verdicts CONTINUE=-1 … RETURN=-5 (matches upstream).
  • One in-flight dump per socket: starting a second netlink DUMP before the first completes makes it fail with -EBUSY (GETGEN: -EINVAL). The service therefore steps dumps strictly sequentially (send one, wait for its DONE, repeat) — see DumpState::inflight in service.rs.
  • Dumps answer with NEW* types: a GETSETELEM dump returns NEWSETELEM-typed messages; the parser matches both variants.
  • Set key type ids: this uapi only documents NFTA_DATA_VALUE = 0, but kernel + nft v1.1.6 use a wider numbering — verified: 2 = nf_proto, 7 = ipv4_addr (a set created with type 2 is listed by nft as type nf_proto). Use fw_core::set_data_type::*; do NOT pass NFPROTO values.
  • Per-set element dumps only: family-wide GETSETELEM is rejected (-EINVAL) — the service does a second, per-set element pass after each primary dump (which is why NFTA_SET_ELEM_LIST_TABLE/SET are always sent).
  • Event subscription works via setsockopt(SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, group 7); bind-time nl_groups did not deliver.
  • Host nft v1.1.6 quirk: add element inet <t> <s> { 9.9.9.9 } requires the braced list as one argument — separate {/} tokens fail with "Could not parse netfilter protocol".
  • NLA length is unaligned: nla_len is 4 + payload, padding follows the attribute and is not counted. Counting padding broke every 1/2/6-byte value (proto/port/MAC set keys and cmp data).
  • 32-bit BE attributes: NFTA_CMP_OP, NFTA_PAYLOAD_OFFSET and NFTA_PAYLOAD_LEN are NLA_U32/NLA_BE32 in this kernel, not u8/u16.
  • Meta loads use NFTA_META_DREG; SREG selects the meta-set expression and fails for l4proto/iifname/oifname.
  • ct state is a single-bit value in a native-endian u32 register. Testing established|related requires a bitwise mask followed by cmp neq 0 (as nft itself emits), not a direct equality; the cmp/mask bytes are native-endian.
  • Reject requires NFTA_REJECT_TYPE (we send ICMPX port-unreachable).
  • Set timeouts are milliseconds and require NFT_SET_TIMEOUT. Normal interval ranges are a start element plus a separate NFT_SET_ELEM_INTERVAL_END marker; NFTA_SET_ELEM_KEY_END is only valid for concatenated sets. The marker is exclusive, so an inclusive model end is encoded as end + 1; single points in an interval set must be encoded as the degenerate range [key, key + 1) — bare start keys fail with -EEXIST when several are added.
  • Batch acks: BEGIN is acked before processing; request NLM_F_ACK on BATCH_END too. A success then produces BEGIN-ack + END-ack, while a failure produces BEGIN-ack + per-op error. This is used instead of a timeout guess.
  • Extended ACKs need setsockopt(NETLINK_EXT_ACK) and, for a fixed TLV offset, NETLINK_CAP_ACK; the message attr is NLMSGERR_ATTR_MSG = 1.

Testing notes

  • crates/fw-netlink/tests/live.rs runs the full create→mutate→external-nft-change→teardown cycle inside a throwaway user+net namespace (unshare -Urn, no root needed) — never touches the host ruleset. It asserts: atomic 4-object batch, event-triggered re-dumps, set-element visibility via the per-set pass, detection of an external nft add element from a separate process, and full teardown. A second live test pins every wire encoding that used to be broken: 1/2/6-byte set keys, NEQ cmp, payload offsets, meta DREG, reject, plain set lookups, interval ranges and set timeouts.
  • apps/fwd/tests/protocol.rs exercises handshake/auth/roles without privileges (skips when netlink can't open).
  • scripts/netns-lab.sh up creates a 50-host Fabric lab (25 LAN clients, 25 DMZ servers) with three multi-port bridges (lan-switch, wan-switch, dmz-switch), two ordinary routers without bridges (edge-router, dmz-router), and the internet-gw uplink namespace. Set FWGUARD_LAB_HOSTS to change the host count (minimum 4). It starts one fwd per namespace under /tmp/fwguard-lab with --flow-telemetry by default, and prints the UDS endpoints/token for the GUI. Build the daemon with cargo build -p fwd --features flow-telemetry; use --no-flow for nft-counter-only runs. Use status, endpoints, logs NAME, shell NAME, and down; add --no-daemons for a connectivity-only topology. up --uplink adds a veth from the root netns to internet-gw, a default route in that namespace, and a temporary root NAT table so clients can reach the host's upstream network; down removes all of it. In the GUI, mark internet-gw:uplink (or edge-router:wan) as a gateway uplink, then add a DNS policy with that uplink as egress and the client LAN prefix as source. Needs root (the script re-runs itself with sudo).
  • Set FWD_NL_TRACE=1 for verbose per-netlink-message tracing in the daemon.