Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Firewall: settings section, privileged helper, and policy

oxydizer4a03900d1c88
diff --git a/AGENTS.md b/AGENTS.md
index 48e652c..d184f06 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,8 +5,8 @@ Tests: `TESTING.md`. Where code lives: [source map](docs/agent-notes/map.md).
Area notes are in an `AGENTS.md` beside the code; read
the one for the directory you work in: `src/files`, `src/editor`,
`src/desktop`, `src/input`, `src/control_center`, `src/ui`, `src/session`,
-`src/dm`, `src/accounts_helper`, `src/printing`, `src/player`, `scripts`,
-`src/wlr`, `src/platform`.
+`src/dm`, `src/accounts_helper`, `src/firewall`, `src/printing`, `src/player`,
+`scripts`, `src/wlr`, `src/platform`.
## Working rules
@@ -207,8 +207,8 @@ panel painting. The key rules:
starts. Lock-before-sleep holds a logind delay inhibitor until
`Lock.covered()`. Only `REDIWM_LOGIN_SESSION`'s logind `Lock` is followed;
`Unlock` is ignored on purpose. The lock never polls.
-* **Only rediwm-dm and the accounts helper run as root** (see their
- `AGENTS.md`); never the compositor.
+* **Only rediwm-dm, the accounts helper and the firewall helper run as
+ root** (see their `AGENTS.md`); never the compositor.
* **No test hooks in production:** `REDIWM_*_PREVIEW` only in `test` blocks,
`REDIWM_TEST_*` only in noninstalled fixtures; only `polkit_test_service`
reads `REDIWM_POLKIT_HELPER_SOCKET` (it decides where passwords go).
diff --git a/TESTING.md b/TESTING.md
index 0b7974b..c646c6d 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -56,6 +56,16 @@ agent. Requires OpenSSH, OpenSSL and `gio`; `GIO_USE_VFS=local` keeps Trash
within the fixture. `--helper-only` skips the compositor; `--bin-dir` selects
the helper and compositor builds together.
+Firewall: `zig build test-firewall` (parsers, validation, nftables/pf
+rendering), `python3 tests/firewall_helper.py` (the real helper as namespace
+root in `unshare -rmn`, against real nftables in an empty network namespace;
+config and run directories on tmpfs, nmcli/systemctl/ufw/firewall-cmd
+hidden) and `python3 tests/firewall_settings.py` (Settings with a fake pkexec
+and helper in a private mount namespace; needs a `/etc/subuid` range; repeat
+with `REDIWM_TEST_SCALE=1.5`, `FIREWALL_TEST_SHOTS=<dir>` keeps screenshots).
+Neither touches the host firewall. pf output is checked on FreeBSD with
+`pfctl -nf`.
+
Keyboard layouts and input methods: `python3 tests/input_sources.py` starts
its own `dbus-run-session` with a fake Fcitx5 controller; it never reaches the
host's Fcitx. Layout labels need libxkbregistry.
diff --git a/assets/icons/shield.svg b/assets/icons/shield.svg
new file mode 100644
index 0000000..4dcef13
--- /dev/null
+++ b/assets/icons/shield.svg
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="utf-8"?><svg fill="#000000" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 1.5 3.5 4.8v6.1c0 5.3 3.6 10.2 8.5 11.6 4.9-1.4 8.5-6.3 8.5-11.6V4.8L12 1.5zm4.6 7.6-5.6 6.1a1 1 0 0 1-1.45.03l-2.9-2.9 1.41-1.41 2.16 2.16 4.88-5.33 1.5 1.35z"/></svg>
diff --git a/build.zig b/build.zig
index 2134b94..24afba6 100644
--- a/build.zig
+++ b/build.zig
@@ -285,6 +285,7 @@ pub fn build(b: *std.Build) void {
const zig_tests = tests.addZig(ctx, session);
@import("build/keys.zig").add(ctx, zig_tests.test_step, &.{ compositor.root_module, zig_tests.ui_tests_module });
+ @import("build/firewall.zig").add(ctx, zig_tests.test_step, &.{ compositor.root_module, zig_tests.ui_tests_module });
const ui_tests_module = zig_tests.ui_tests_module;
const ipc_tests_module = zig_tests.ipc_tests_module;
const files_tests = zig_tests.files_tests;
diff --git a/build/firewall.zig b/build/firewall.zig
new file mode 100644
index 0000000..ddd3a05
--- /dev/null
+++ b/build/firewall.zig
@@ -0,0 +1,30 @@
+//! The firewall model shared by Settings and the root helper, the helper
+//! itself, its polkit policy and the standalone tests.
+const std = @import("std");
+const Context = @import("context.zig").Context;
+const support = @import("support.zig");
+
+pub fn add(ctx: Context, test_step: *std.Build.Step, hosts: []const *std.Build.Module) void {
+ const b = ctx.b;
+ const module = b.createModule(.{ .root_source_file = b.path("src/firewall/mod.zig"), .target = ctx.target, .optimize = ctx.optimize });
+ for (hosts) |host| host.addImport("firewall", module);
+ const helper = b.addExecutable(.{ .name = "rediwm-firewall-helper", .root_module = b.createModule(.{ .root_source_file = b.path("src/firewall_main.zig"), .target = ctx.target, .optimize = ctx.optimize, .link_libc = true }), .use_llvm = ctx.use_llvm, .use_lld = ctx.use_llvm });
+ helper.root_module.addImport("firewall", module);
+ helper.root_module.addImport("platform", ctx.platform_mod);
+ helper.root_module.addImport("c", ctx.c.libc);
+ helper.root_module.addImport("install_paths", ctx.layout.options);
+ b.installArtifact(helper);
+ b.step("firewall-helper", "Build the privileged firewall helper").dependOn(&helper.step);
+ b.getInstallStep().dependOn(&b.addInstallFileWithDir(support.localizedData(b, ctx.i18n_tool, ctx.layout.prefix, "data/org.rediwm.firewall.policy"), .prefix, "share/polkit-1/actions/org.rediwm.firewall.policy").step);
+ const tests = b.addTest(.{ .root_module = module });
+ const run = b.addRunArtifact(tests);
+ b.step("test-firewall", "Test firewall parsers, validation and rule rendering").dependOn(&run.step);
+ test_step.dependOn(&run.step);
+ // Integration suites (namespaces, never the host firewall); run on demand.
+ inline for (.{ .{ "test-firewall-helper", "tests/firewall_helper.py", "Test the firewall helper against nftables in a private namespace" }, .{ "test-firewall-settings", "tests/firewall_settings.py", "Test Settings' Firewall section against a fake helper" } }) |suite| {
+ const integration = b.addSystemCommand(&.{"python3"});
+ integration.addFileArg(b.path(suite[1]));
+ integration.step.dependOn(b.getInstallStep());
+ b.step(suite[0], suite[2]).dependOn(&integration.step);
+ }
+}
diff --git a/build/support.zig b/build/support.zig
index b8ba4dc..5af96a6 100644
--- a/build/support.zig
+++ b/build/support.zig
@@ -152,7 +152,7 @@ pub fn addShellUi(b: *std.Build, module: *std.Build.Module) void {
pub fn addShellIcons(b: *std.Build, module: *std.Build.Module) void {
module.addAnonymousImport("redi-logo", .{ .root_source_file = b.path("assets/redi-logo.svg") });
module.addAnonymousImport("rediwm-settings-icon", .{ .root_source_file = b.path("assets/icons/rediwm-settings.png") });
- inline for (.{ "git-branch", "home", "folder", "terminal", "settings", "keyboard", "edit", "mouse", "touchpad", "trackball", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "cpu", "ram", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares", "divide" }) |name| {
+ inline for (.{ "git-branch", "home", "folder", "terminal", "settings", "keyboard", "edit", "mouse", "touchpad", "trackball", "display", "music", "headphones", "wifi", "ethernet", "globe", "bluetooth", "battery", "notification-bell", "speaker", "speaker-xmark", "power-button", "clock", "cpu", "ram", "lock", "logout", "restart", "eye", "eye-off", "refresh", "cut", "copy", "paste", "trash-outline", "trash", "view-grid", "view-list", "sort", "filter", "zoom-in", "zoom-out", "rotate", "crop", "undo", "save", "fit", "print", "open", "usb-stick", "drive", "eject", "users", "squares", "divide", "shield" }) |name| {
module.addAnonymousImport("shell-icon-" ++ name, .{ .root_source_file = b.path("assets/icons/" ++ name ++ ".svg") });
}
}
diff --git a/data/org.rediwm.firewall.policy b/data/org.rediwm.firewall.policy
new file mode 100644
index 0000000..0e001d8
--- /dev/null
+++ b/data/org.rediwm.firewall.policy
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE policyconfig PUBLIC
+ "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
+ "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
+<policyconfig>
+ <!-- pkexec picks the action by the helper's first argument. -->
+ <action id="org.rediwm.firewall.read">
+ <description>Read the firewall settings</description>
+ <message>Authentication is required to read the firewall settings</message>
+ <defaults>
+ <allow_any>auth_admin</allow_any>
+ <allow_inactive>auth_admin</allow_inactive>
+ <allow_active>yes</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">@BINDIR@/rediwm-firewall-helper</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">read</annotate>
+ </action>
+ <action id="org.rediwm.firewall.manage">
+ <description>Change the firewall settings</description>
+ <message>Authentication is required to change the firewall settings</message>
+ <defaults>
+ <allow_any>auth_admin</allow_any>
+ <allow_inactive>auth_admin</allow_inactive>
+ <allow_active>auth_admin_keep</allow_active>
+ </defaults>
+ <annotate key="org.freedesktop.policykit.exec.path">@BINDIR@/rediwm-firewall-helper</annotate>
+ <annotate key="org.freedesktop.policykit.exec.argv1">manage</annotate>
+ </action>
+</policyconfig>
diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.md
index 1a0910b..cdfd531 100644
--- a/docs/agent-notes/map.md
+++ b/docs/agent-notes/map.md
@@ -30,6 +30,7 @@ or a lowercase directory named after a TitleCase host (`Dock.zig` → `dock/`).
| `rediwm-session` | `src/session_main.zig` | login supervisor (`session/supervisor.zig`, `publication.zig`) |
| `rediwm-dm` | `src/dm/main.zig` | display manager, runs as root (`dm/AGENTS.md`) |
| `rediwm-accounts-helper` | `src/accounts_helper/main.zig` | root account helper (`accounts_helper/AGENTS.md`) |
+| `rediwm-firewall-helper` | `src/firewall_main.zig` | root firewall helper (`firewall_helper/`, `firewall/AGENTS.md`); Settings uses `control_center/sections/firewall_client.zig` |
| `rediwm-theme` | `src/theme_main.zig` | theme archive helper (`theme_helper/`) |
| `rediwm-keys` | `src/keys_main.zig` | unprivileged SSH metadata and operations (`keys/`, `keys_helper.zig`); Settings uses `keys/client.zig` |
@@ -46,7 +47,9 @@ widgets, layout, text, theme, animation), `config` (`src/config/`: parsing and
saving `config.toml`), `dbus`, `i18n`, `memory` and `protocol`
(`src/ipc/protocol.zig`, the IPC wire format shared with `rediwm-msg`). Also
`keys` (`src/keys/mod.zig`: public identity model, bounded key metadata parsers,
-inventory and operation protocol; parsers run in `rediwm-keys`) and
+inventory and operation protocol; parsers run in `rediwm-keys`), `firewall`
+(`src/firewall/mod.zig`: the firewall model, helper protocol, validation, and
+the parsers and renderers for ufw, firewalld, nftables and pf) and
`platform` (`src/platform/`, std only): child-process handles, directory
watching, the program's own path, system helper lookup (`tool.zig`) and
syscall filters (`seccomp.zig`), the
@@ -96,7 +99,8 @@ and `effects/minimize_mesh.zig` (minimize snapshots and deformation),
* **Settings** (`control_center/`, `AGENTS.md` there): the window is
`ControlCenter.zig` (+ `tree`, `keys`, `relayout`, `paint.zig`); `panel.zig`
has shared helpers; one `sections/*.zig` per page, the big ones split into
- `appearance_*.zig` and `printers_*.zig`.
+ `appearance_*.zig`, `printers_*.zig` and `network_*.zig` (the Firewall card
+ and sub-view are `firewall*.zig`, shown from the Network page).
* **Session** (`session/`, `AGENTS.md` there): `lock.zig` (+ `lock_account`,
`lock_events`, `lock_input`, `lock_view.zig`), `greeter.zig`, `idle.zig`,
`power.zig` (+ `power_*.zig`), `login_manager.zig` (`login_manager/`: service
diff --git a/docs/plans/firewall.md b/docs/plans/firewall.md
new file mode 100644
index 0000000..298c681
--- /dev/null
+++ b/docs/plans/firewall.md
@@ -0,0 +1,362 @@
+# Plan: Firewall settings
+
+Status: 2026-11-17. D1–D8 decided (as recommended). Phases 1–5 are built on
+Linux and pass their tests; the FreeBSD half is written and cross-compiles but
+has not run on FreeBSD (see "Not done yet"). Phase 6 (editing through `redi`)
+is not started.
+
+Scope: a Firewall section in Settings → Network that shows the whole firewall
+on one screen and lets the user manage it: on/off, default policies, trust per
+network, allow/deny rules for services, ports and addresses, which programs are
+listening and whether the firewall lets anyone reach them, ping, logging, a
+recent-blocks view, and a read-only list of rules owned by other programs
+(Docker, libvirt, Tailscale, VPNs). It must work on Linux and on FreeBSD 15.x
+(`freebsd.md`).
+
+Out of scope: per-application outgoing filtering (OpenSnitch-style; needs a
+resident daemon and cgroup/eBPF matching), intrusion detection, authoring NAT
+or port forwarding (shown read-only), and installing firewall packages.
+
+## Where we are
+
+* Nothing in RediWM touches the firewall. Settings → Network is one scrolling
+ page of cards (`sections/network*.zig`: overview, Ethernet, Wi-Fi, editor,
+ VPN, proxy, airplane). On FreeBSD the NetworkManager and BlueZ cards are
+ hidden (freebsd D3), which leaves that page almost empty. Firewall would be
+ the first Network card that both systems show, so **it cannot depend on
+ NetworkManager**.
+* Root precedent: `rediwm-accounts-helper` runs under `pkexec`, reads stdin
+ JSON, validates every field and passes argv to absolute tools. AGENTS.md
+ currently says only rediwm-dm and that helper run as root (see D1).
+* Lifetime precedent: Keys and Printers own their worker only while the page
+ is on screen, allow one request in flight with an absolute deadline, cancel
+ it on hide, close or lock, and create no idle timers.
+
+### What we would talk to
+
+| Stack | Where | Interface | Reading needs root? |
+| --- | --- | --- | --- |
+| firewalld | Fedora, openSUSE, optional elsewhere | D-Bus `org.fedoraproject.FirewallD1`, gated by polkit; zones, services, rich rules, runtime vs permanent; NM's `connection.zone` | No (`firewall.info`, P0 confirms) |
+| ufw | Ubuntu, Mint, Arch (this machine: active, DROP/ACCEPT/DROP) | CLI only, `/etc/ufw`, `/etc/default/ufw`; Plasma ships its own KAuth helper (`org.kde.ufw`) | State and counters: yes |
+| plain nftables | Arch `/etc/nftables.conf`, Gentoo `/var/lib/nftables/rules-save` | `nft -j`, netlink | Yes (`CAP_NET_ADMIN`) |
+| RediOS `redi` | redi-iso installs | Renders `table inet redi` from the manifest's typed `Firewall::Nftables` (incoming/forwarding/outgoing, `allow_icmp`, `tcp_ports`, `udp_ports`), **starting with `flush ruleset`** | Yes |
+| pf | FreeBSD (default choice) | `pfctl`, `/dev/pf`; anchors loaded at runtime, made persistent with `load anchor` in `pf.conf`; `pf_enable` in rc.conf | Yes |
+| ipfw / ipf | FreeBSD alternatives | `ipfw list` | Yes |
+| Docker, podman, libvirt, Tailscale, WireGuard | both (Linux mostly) | Their own tables, chains or anchors | Yes |
+
+Two facts that shape the design:
+
+* **Two filters stack, they don't merge.** With nftables, every base chain on a
+ hook has to accept a packet: an `accept` in our table cannot override a
+ `drop` in ufw's or redi's. pf's anchors are evaluated inside the main
+ ruleset. A port can therefore only be opened by the program that manages
+ the firewall, so **one manager at a time**, and we edit through that manager.
+* **On FreeBSD, polkit answered `auth_admin` for session shells** in the VM
+ probe (freebsd.md). Until that is settled, every root call may show a
+ password prompt there, reads included. The page must not prompt without a
+ click.
+
+## Design
+
+### One model, several backends
+
+`src/firewall/` is std + `dbus` only, with no compositor imports, and holds a
+model that does not depend on any backend:
+
+* **Status:** backend, running, starts at boot, default incoming/outgoing/
+ forward policy, ping answered, logging level, lockdown active.
+* **Rules:** allow/deny/reject/limit, direction, a service *or*
+ protocol + port/range, source (anywhere / local network / address or CIDR),
+ scope (everywhere / a trust level / an interface), IP family, comment.
+ Each rule is either *ours*, which we can edit, or *foreign*, which is
+ read-only and grouped by a guessed owner: `docker`, `libvirt`, `tailscale`,
+ `ts-*`, `nm-*` and similar.
+* **Listeners:** proto, address, port, process name, pid, uid, plus a
+ *verdict* the model computes: loopback only / blocked / reachable on home
+ networks / reachable from everywhere.
+* **Capabilities** per backend. The UI hides or disables what a backend cannot
+ express. ufw has no zones, redi has no source restriction, and firewalld has
+ no "limit" outside rich rules.
+
+| Backend | OS | Reads | Writes |
+| --- | --- | --- | --- |
+| `firewalld` | Linux | helper: `firewall-cmd` (zones, active zones), service XML | helper: `firewall-cmd --permanent` + `--reload` |
+| `ufw` | Linux | helper: `ufw status verbose`, `ufw show added`, rule files | helper: `ufw` argv (`allow`, `delete`, `default`, `enable`, `logging`) |
+| `nft` (ours) | Linux | helper: `nft -j list ruleset` | helper: atomic `nft -f` of our table only |
+| `redi` | RediOS | helper: `nft -j` | `redi` CLI (D5) |
+| `pf` | FreeBSD | helper: `pfctl -s info/-sr/-a rediwm -sr` | helper: `pfctl -a rediwm -f` (anchor only) |
+| `foreign` | both | helper | none: a hand-written nftables.conf, ipfw or ipf is shown read-only |
+
+**Detection** looks at every stack that is present and active. Exactly one
+manager is editable. If two are active (ufw and firewalld, say), a conflict
+banner explains the situation and everything stays read-only until one is
+turned off. Each backend's parser is a pure function over captured output, so
+it can be tested without root.
+
+### Privileged helper: `rediwm-firewall-helper`
+
+Built like the accounts helper:
+
+* root under `pkexec`; stdin JSON; `PKEXEC_UID` is untrusted
+* argv only, to absolute tools found through `platform.tool`, never a shell
+* every field validated before anything is rendered: ports 1–65535, ranges,
+ CIDRs, interface names `[A-Za-z0-9._-]{1,15}`, comments of up to 64
+ printable characters with no quotes
+* operations: `status` (rules, listeners and counters in one reply), `apply`
+ (desired state for what we own), `enable`/`disable`, `set-defaults`,
+ `add-rule`/`remove-rule`, `set-trust`, `lockdown`
+
+**Unlock, like Users and Services (D1).** Editing sits behind an **Unlock**
+button in the overview card. It runs the helper's `authorize` operation, which
+changes nothing (as `rediwm-accounts-helper`'s does). pkexec asks for the
+password, and the page is unlocked for this Settings session; the button then
+reads **Lock**. Edit controls are disabled until then, with *Unlock to change
+firewall settings* beneath them. The action is `auth_admin_keep`, so polkit
+remembers the password for a few minutes and the edits that follow run without
+a prompt. After that, the next edit asks again; the page stays unlocked
+(Users behaves the same way). Lock, closing Settings, leaving the page or the
+screen lock drop the unlocked state and cancel a pending prompt.
+
+Polkit actions (`data/org.rediwm.firewall.policy`, with an `exec.path`
+annotation on the helper like the accounts policy):
+
+* `org.rediwm.firewall.read`: `allow_active=yes`, so on Linux the overview
+ shows with no password. Only `status` and `recent-blocks` use it.
+* `org.rediwm.firewall.manage`: `auth_admin` / `auth_admin` /
+ `auth_admin_keep`. This covers `authorize` and every change.
+
+pkexec picks the action by the helper's first argument
+(`org.freedesktop.policykit.exec.argv1`). Following network changes needs no
+action: NetworkManager's dispatcher runs `rediwm-firewall-helper sync` as root.
+
+Where `read` is denied without interaction (FreeBSD today, where polkit
+answered `auth_admin` in the VM probe), the overview shows *Unlock to view*
+in place of the status. Unlocking then reads, so one password covers both
+viewing and editing. A page never prompts without a click.
+
+Lifetime is the Keys pattern: one request in flight, an absolute deadline, a
+child process group, cancelled on hide, close or lock. A read runs when the
+section comes on screen, after each write, on the Refresh button and when an
+ActiveConnection change arrives that the page already receives. Nothing polls.
+Not in greeter mode; IPC returns `SessionLocked` while locked.
+
+firewalld also goes through the helper (`firewall-cmd`), not D-Bus from the
+compositor: one code path, one way to test it, and the listener list needs
+root anyway. Its output is read in the C locale.
+
+### Our own table or anchor (when nothing manages the firewall)
+
+* **nft:** we own only `table inet rediwm`. The helper renders the whole table
+ and loads it in one transaction (`destroy table` + `table …` in a single
+ `nft -f`), so a failed load changes nothing. It persists to
+ `${sysconfdir}/rediwm/firewall.nft` (`install_paths`, never a literal
+ `/etc`). At boot it is loaded by `rediwm-firewall.service`
+ (`Before=network-pre.target`, running `rediwm-firewall-helper sync`), which
+ the helper writes to `/etc/systemd/system` and enables when the firewall is
+ turned on. Without systemd (Artix's OpenRC) there is no boot unit yet, and
+ Start at boot is hidden. Other tables are never touched.
+* **pf:** we own only the anchor `rediwm`, persisted to
+ `${sysconfdir}/rediwm/pf.rediwm.conf` (`/usr/local/etc` on FreeBSD) and
+ rendered with `quick` rules so pf's last-match rule cannot surprise us.
+ * `pf.conf` already has `anchor "rediwm"` and `load anchor`: manage the
+ anchor.
+ * `pf.conf` exists without them: show its rules read-only and offer to add
+ the two lines, showing the diff first.
+ * No `pf.conf`, pf off: *Turn on* writes a minimal one after confirmation
+ (`set skip on lo0`, `block in`, `pass out keep state`, the anchor), then
+ runs `sysrc pf_enable=YES` and `service pf start`.
+* The seed matches RediOS's: block unsolicited incoming and forwarded
+ traffic, allow outgoing; accept loopback, established/related, ICMP/ICMPv6
+ and DHCP client replies; open no listening ports, SSH included.
+
+### Network trust (Public / Home)
+
+Trust lives on the *network*, not on the interface, because `wlan0` is the
+same device at home and in a café.
+
+* **firewalld:** `connection.zone` on the NM profile (`public`/`home`). This
+ is native.
+* **Our nft table with NM:** trust is also `connection.zone` (`home`,
+ `trusted`, `internal` and `work` count as Home), so it carries over if the
+ user switches to firewalld. The table's `home_ifaces` set holds the devices
+ of active Home connections. The NM dispatcher script we install
+ (`/etc/NetworkManager/dispatcher.d/90-rediwm-firewall`; it runs as root on
+ up/down, even before login) runs `sync`, which refills it. Unknown networks
+ are Public.
+* **FreeBSD (no NM) or no NM:** trust per interface, saved in our anchor file.
+* **ufw:** no trust levels (capability off): rules apply everywhere, and the
+ card says so.
+* The connection editor and the Wi-Fi details gain a *Firewall: Public / Home*
+ row where the backend supports it.
+
+### Service catalog
+
+`firewall/services.zig` (a table, translated in Settings): name, ports and a
+suggested scope.
+Examples: SSH, web server, mDNS/Avahi, KDE Connect/GSConnect, Syncthing, Steam
+Remote Play and LAN transfers, Samba, IPP/CUPS sharing, DLNA, Chromecast and
+Spotify Connect discovery, the Files transfers (torrent helper) listening
+port, VNC/RDP, WireGuard. When firewalld runs we also show its services, and
+ufw's application profiles when ufw runs (`/etc/ufw/applications.d`).
+
+### Listening and exposure
+
+The helper's `status` includes listeners.
+
+* **Linux:** `/proc/net/{tcp,tcp6,udp,udp6}` plus an inode → pid scan, which
+ only root can do for every user. This goes through
+ `system_monitor/proc.zig`; only its Linux backend reads `/proc`.
+* **FreeBSD:** `sockstat -46lq` (or `net.inet.*.pcblist`, decided in P0).
+
+The model gives each listener a verdict, and the overview names the ones that
+matter: *sshd :22 is reachable from every network* with **Block** and **Allow
+on home networks** next to it.
+
+### The page
+
+The overview card is always on the Network page. **Manage** opens a Firewall
+sub-view (D6).
+
+```
+Firewall [ On ]
+Protected by ufw · blocks incoming, allows outgoing
+This network (Home Wi-Fi) is trusted as [ Public | Home ]
+────────────────────────────────────────────────────────────
+Incoming Block Outgoing Allow Forwarding Block
+Ping Answer Logging Low Starts at boot Yes
+────────────────────────────────────────────────────────────
+! sshd :22 is reachable from every network [Block] [Home only]
+Rules 6 allow · 1 deny Also active: Docker (4), Tailscale (2)
+ [Refresh] [Unlock] [Manage…]
+```
+
+Sub-view cards:
+
+1. **Rules:** list, filter, add/edit/delete, *Add service* from the catalog,
+ *Add port*, source and scope pickers.
+2. **Listening services:** every listener with its verdict and a quick action.
+3. **Networks:** known NM profiles (or interfaces) and their trust.
+4. **Advanced:** default policies (outgoing Block is guarded, see Safety),
+ forwarding, ping, logging level, rate-limit SSH, IPv6 on/off for our
+ rules, starts at boot.
+5. **Other rules:** foreign tables, chains and anchors, grouped and
+ read-only, with a note that we cannot override them.
+6. **Recent blocks** (D7).
+
+Every control is a `ui/widgets/` control. Search index entries go into
+`search_index.zig` (firewall, ports, ssh, ufw, pf, block, allow, ping).
+
+### Safety
+
+* **Confirm, or revert automatically**, for changes that can cut the user off:
+ outgoing Block, Lockdown, and turning off a rule that allows SSH while SSH
+ connections are established. The helper applies the change, keeps a small
+ watchdog alive on a pipe, and restores the previous state after 20 s unless
+ Settings confirms (the same pattern as a display mode change).
+* **Lockdown** ("Block all connections"): drops everything except loopback,
+ in the runtime only, until it is turned off or the machine reboots.
+* The helper renders all text itself from validated fields. A user string is
+ never placed into a ruleset, a shell or a log.
+* Reports and logs contain no addresses or process command lines.
+* Never write the host's firewall from tests.
+
+### Recent blocks (D7)
+
+Our rules log drops with a prefix (`rediwm-drop`) and a rate limit (nft
+`limit rate 10/minute`; pf `log` on the anchor's block rules). On demand, the
+helper reads them: `journalctl -k` (or the kernel ring) on Linux, `tcpdump
+-r /var/log/pflog` on FreeBSD. The view shows time, direction, protocol, port
+and remote address, with *Allow this* where the backend can express it.
+There is no live stream and no idle wakeups.
+
+## Phases
+
+Status: 0 done on Linux (nft in `unshare -rn` works, ufw's tuple format read
+from its source, firewalld's API checked); its FreeBSD items wait for the VM.
+1–5 built. 6 not started.
+
+0. **Facts** (nothing shipped):
+ * firewalld `info` without a prompt
+ * NM `user` data key syntax and its dispatcher environment
+ * stability of ufw's output across 0.36
+ * `nft -j` inside `unshare -rn` (an unprivileged netns: real kernel
+ validation without touching the host)
+ * pf anchor load and persistence, and pkexec/polkit behaviour, on the
+ HyprBSD 15.1 VM, including whether `auth_admin_keep` carries across
+ separate pkexec runs there as it does on Linux
+ * `sockstat` format
+ * the real table and chain names of Docker, Tailscale and libvirt
+ * whether `redi` can edit its firewall policy from the CLI
+1. **Read-only overview, both systems:** model, the helper's `status`, parsers
+ for firewalld, ufw, nft (foreign) and pf, the overview card, listeners,
+ other rules.
+2. **Editing through the manager:** on/off, defaults, ping, logging, rule
+ CRUD within each backend's capabilities, the catalog. (No IPC
+ command: the tests read the page's widgets and the helper's replies.)
+3. **Our own firewall when there is none:** the nft table + boot unit, the pf
+ anchor + setup, *Turn on*.
+4. **Network trust:** firewalld zones, the dispatcher for nft, per-interface
+ trust on FreeBSD, rows in the connection editor.
+5. **Safety and insight:** confirm/revert, lockdown, SSH rate limit, recent
+ blocks.
+6. **RediOS:** editing through `redi` (cross-repo, D5).
+
+## Not done yet
+
+* **FreeBSD has not run.** `firewall_helper/freebsd.zig` (pf anchor, pf.conf
+ setup, sockstat, pflog, per-interface trust) cross-compiles; on the HyprBSD
+ VM still to do: `pfctl -nf` of the rendered anchor, the pf.conf insertion,
+ `pkexec` with argv1 actions and whether `auth_admin_keep` carries across
+ runs, sockstat's columns, and a `tests/firewall_helper.py` equivalent in a
+ vnet jail.
+* **firewalld is tested only by its parsers.** No firewalld runs here; try it
+ in a Fedora container or VM before calling it done.
+* ufw application rules whose names contain spaces cannot be removed from
+ the page; OpenRC boot unit; translations of the new strings; Phase 6.
+
+## Tests
+
+* **Unit (`zig build test-firewall`):** parsers over captured fixtures (ufw
+ status, `nft -j`, firewalld replies, `pfctl -sr`, `sockstat`,
+ `/proc/net/tcp`); nft and pf renderers against goldens; validation,
+ including hostile comments and interface names; the helper's operations
+ over a recording executor.
+* **Real kernel without root:** load the rendered table with `nft -c -f` and
+ `nft -f` inside `unshare -rn`, then check a packet verdict with `nft
+ monitor trace` or `conntrack`-free probes in that namespace.
+* **FreeBSD:** pf in a vnet jail on the HyprBSD VM (root there is fine; it is
+ a VM).
+* **Real helper:** `tests/firewall_helper.py` runs it as namespace root in
+ `unshare -rmn`, with config and run directories on tmpfs and nmcli,
+ systemctl, ufw and firewall-cmd hidden, against real nftables.
+* **Settings:** `tests/firewall_settings.py` re-runs itself in a user and
+ mount namespace (namespace root is a subordinate uid, used only to
+ bind-mount `tests/fixtures/firewall_pkexec.sh` over `/usr/bin/pkexec`) and
+ drives the page against `tests/firewall_fake_helper.py`. No production
+ override of the helper or pkexec path exists.
+
+## Decisions (all decided 2026-11-17, as recommended)
+
+* **D1 Root helper: decided 2026-11-17.** Add `rediwm-firewall-helper` as a
+ third root program and amend the AGENTS.md rule. Changes need an
+ **Unlock** button that asks for the password through pkexec (the Users
+ page pattern, `auth_admin_keep`). Without the helper, only firewalld could
+ be managed; ufw (this machine), plain nftables, RediOS and every FreeBSD
+ system would show nothing.
+* **D2 Which stacks to manage.** *Recommended:* firewalld, ufw, pf (through
+ our anchor), our own nft table. Read-only: a hand-written nftables ruleset,
+ ipfw, ipf.
+* **D3 No firewall running.** Offer *Turn on*, which sets up our own (nft
+ table + unit, or pf + anchor) with the RediOS defaults. *Recommended: yes.*
+* **D4 Trust levels.** *Recommended:* Public / Home only, stored on the NM
+ profile (per interface without NM), off for ufw. Alternative: firewalld's
+ full zone list.
+* **D5 RediOS.** Read-only ("Managed by RediOS") until `redi` gains a firewall
+ edit command that we call. *Recommended* over editing its manifest
+ ourselves.
+* **D6 Placement.** Overview card on Network plus a Firewall sub-view
+ (*recommended*), or a sidebar page of its own.
+* **D7 Logging.** Off by default, with an on-demand *Recent blocks* view
+ (*recommended*), or on with a low limit.
+* **D8 Confirm/revert.** Only for outgoing Block, Lockdown and SSH removal
+ (*recommended*), or for every change.
diff --git a/scripts/build-steamos-bundle.sh b/scripts/build-steamos-bundle.sh
index 6ca2644..688bb3a 100644
--- a/scripts/build-steamos-bundle.sh
+++ b/scripts/build-steamos-bundle.sh
@@ -13,7 +13,7 @@ bundle=/work/zig-out/rediwm-steamos
mkdir -p "$bundle"
cp -a zig-out/steamos/bin zig-out/steamos/lib zig-out/steamos/share "$bundle/"
# Portable nested testing has no privileged helpers or system integration.
-rm -f "$bundle/bin/rediwm-dm" "$bundle/bin/rediwm-accounts-helper" \
+rm -f "$bundle/bin/rediwm-dm" "$bundle/bin/rediwm-accounts-helper" "$bundle/bin/rediwm-firewall-helper" \
"$bundle/bin/rediwm-session" "$bundle/bin/rediwm-restart"
rm -rf "$bundle/share/wayland-sessions" "$bundle/share/polkit-1" "$bundle/share/xdg-desktop-portal"
# These entries are visible only inside the nested session through XDG_DATA_DIRS.
diff --git a/scripts/install-session-root.sh b/scripts/install-session-root.sh
index 3ec8604..8e67452 100755
--- a/scripts/install-session-root.sh
+++ b/scripts/install-session-root.sh
@@ -58,6 +58,7 @@ install -Dm644 "$repo_dir/data/rediwm-portals.conf" "${datadir}/xdg-desktop-port
# xdg-desktop-portal reads backend descriptors only from its own datadir.
install -Dm644 "$repo_dir/data/rediwm.portal" "${system_data}/xdg-desktop-portal/portals/rediwm.portal"
install -Dm644 "$release_dir/share/polkit-1/actions/org.rediwm.accounts.policy" "${system_data}/polkit-1/actions/org.rediwm.accounts.policy"
+install -Dm644 "$release_dir/share/polkit-1/actions/org.rediwm.firewall.policy" "${system_data}/polkit-1/actions/org.rediwm.firewall.policy"
install -Dm644 "$repo_dir/data/xdg-desktop-portal-wlr.ini" "${datadir}/xdg-desktop-portal-wlr/config"
install -Dm644 "$release_dir/share/wayland-sessions/rediwm-release-safe.desktop" "${system_data}/wayland-sessions/rediwm-release-safe.desktop"
# The bass boost's LADSPA plugin, and on Debian/Ubuntu builds the private
diff --git a/scripts/make-deb.sh b/scripts/make-deb.sh
index a24b636..a1c2612 100644
--- a/scripts/make-deb.sh
+++ b/scripts/make-deb.sh
@@ -35,6 +35,7 @@ cp -a "$rel/lib/rediwm" "$L/lib/rediwm"
# System-wide data: portal backend, polkit action, session entry.
install -d "$root/usr/share/polkit-1/actions" "$root/usr/share/wayland-sessions" "$root/usr/share/xdg-desktop-portal/portals"
cp "$rel/share/polkit-1/actions/org.rediwm.accounts.policy" "$root/usr/share/polkit-1/actions/"
+cp "$rel/share/polkit-1/actions/org.rediwm.firewall.policy" "$root/usr/share/polkit-1/actions/"
cp "$rel/share/wayland-sessions/rediwm-release-safe.desktop" "$root/usr/share/wayland-sessions/"
install -m644 "$repo/data/rediwm.portal" "$root/usr/share/xdg-desktop-portal/portals/rediwm.portal"
# Remaining data follows the configured prefix.
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
index ce024c9..cb94002 100644
--- a/src/control_center/AGENTS.md
+++ b/src/control_center/AGENTS.md
@@ -108,3 +108,30 @@ helpers (and `panel.ControlCenter`); `sections/` one file per page.
* **Tests never touch the host:** `tests/nm_fake.py` is a fake NetworkManager
and polkit on the session bus; the proxy test sets `GSETTINGS_BACKEND=keyfile`
with a scratch `XDG_CONFIG_HOME`; nothing may write `/dev/rfkill`.
+
+## Firewall (on the Network page)
+
+* **`sections/firewall*.zig`:** `firewall.zig` (state, overview card, the
+ Manage sub-view, actions), `firewall_rules.zig` (rules list and Add rule
+ form), `firewall_cards.zig` (listening programs, networks, advanced, other
+ programs' rules, recent blocks), `firewall_client.zig` (pkexec runs of
+ `rediwm-firewall-helper`; see `src/firewall/AGENTS.md`).
+* **The client lives while the Network page is shown**: `firewall.start` from
+ `network.build`; `hide` on page change, search, close and the screen lock
+ (`lock.zig`), which also forgets the unlock. One request at a time; the
+ only timers are its deadline and one wake at a pending revert's deadline.
+* **No pkexec unless polkit's actions name this build's helper**
+ (`firewall_client.policyInstalled`): otherwise pkexec's generic action asks
+ for a password even to read. Development and test compositors therefore
+ never reach the session's polkit agent; `tests/firewall_settings.py` stages
+ a policy in its namespace.
+* **Unlock is the helper's `authorize`** through the `manage` action (polkit
+ `auth_admin_keep`); reads use `read` (no password for an active session).
+ Where a read is refused (exit 126/127, FreeBSD's polkit today) the card says
+ "Unlock to view" and reads go through `manage` after unlocking; the page
+ never prompts by itself. Child exit values are raw wait statuses.
+* **Reply strings are freed by the next reply**: copy them into the tree's
+ arena (`a.dupe`) before a widget keeps them.
+* Changes that can cut the user off (blocking outgoing, lockdown, removing a
+ rule that allows SSH) send `revert_after = 20`; the overview then offers
+ Keep change.
diff --git a/src/control_center/ControlCenter.zig b/src/control_center/ControlCenter.zig
index f9fc2a5..ee821a9 100644
--- a/src/control_center/ControlCenter.zig
+++ b/src/control_center/ControlCenter.zig
@@ -151,6 +151,7 @@ input: input_section.Section = .{},
input_sources: @import("sections/input_sources.zig").Section = .{},
users: users_section.Section = .{},
network: network_section.Section = .{},
+firewall: @import("sections/firewall.zig").Section = .{},
bluetooth: bluetooth_section.Section = .{},
services: services_section.Section = .{},
printers: printers_section.Section = .{},
@@ -256,6 +257,7 @@ pub fn destroy(cc: *ControlCenter) void {
cc.key_settings.deinit();
if (cc.server.network) |m| m.cancelUnlock();
cc.network.deinit();
+ cc.firewall.deinit();
if (cc.page == .bluetooth) if (cc.server.bluetooth) |m| m.closed();
cc.bluetooth.deinit();
users_section.deinit(cc);
diff --git a/src/control_center/keys.zig b/src/control_center/keys.zig
index bd7c5c2..f51b294 100644
--- a/src/control_center/keys.zig
+++ b/src/control_center/keys.zig
@@ -29,6 +29,10 @@ pub fn selectSearchPage(cc: *ControlCenter, page: Page) void {
if (cc.page == .services and page != .services) if (cc.systemd_client) |client| client.hide();
if (cc.page == .printers and page != .printers) cc.printers.hide();
if (cc.page == .keys and page != .keys) cc.key_settings.hide();
+ if (cc.page == .network and page != .network) {
+ cc.firewall.hide();
+ cc.firewall.managing = false;
+ }
if (cc.page == .network and page != .network) cc.network.clearForm();
if (cc.page == .bluetooth and page != .bluetooth) {
if (cc.server.bluetooth) |m| m.closed();
diff --git a/src/control_center/search_index.zig b/src/control_center/search_index.zig
index e68ccac..ed4b667 100644
--- a/src/control_center/search_index.zig
+++ b/src/control_center/search_index.zig
@@ -86,6 +86,7 @@ const source_entries = [_]SourceEntry{
.{ .page = .network, .title = i18n.msg("IP address and DNS"), .target = "ethernet_edit", .keywords = i18n.msg("ipv4 ipv6 static dhcp gateway mtu metered forget saved network") },
.{ .page = .network, .title = i18n.msg("Proxy"), .target = "proxy_card", .keywords = i18n.msg("http https socks pac proxy server bypass") },
.{ .page = .network, .title = i18n.msg("VPN"), .target = "vpn_card", .keywords = i18n.msg("wireguard openvpn tunnel private network") },
+ .{ .page = .network, .title = i18n.msg("Firewall"), .target = "firewall_card", .keywords = i18n.msg("firewall ports block allow incoming outgoing ufw firewalld pf nftables ssh listening lockdown") },
.{ .page = .network, .title = i18n.msg("Airplane mode"), .target = "network_airplane_row", .keywords = i18n.msg("flight radios bluetooth wi-fi rfkill") },
.{ .page = .appearance, .title = i18n.msg("Wallpaper"), .target = "@Wallpaper", .heading = i18n.msg("Wallpaper"), .keywords = i18n.msg("background desktop image folder") },
.{ .page = .appearance, .title = i18n.msg("Theme"), .target = "@Theme", .heading = i18n.msg("Theme"), .keywords = i18n.msg("colors colours dark light preset") },
diff --git a/src/control_center/sections/firewall.zig b/src/control_center/sections/firewall.zig
new file mode 100644
index 0000000..f89b977
--- /dev/null
+++ b/src/control_center/sections/firewall.zig
@@ -0,0 +1,444 @@
+//! Settings → Network → Firewall: the overview card on the Network page and,
+//! behind Manage, the Firewall sub-view (rules, listening programs, networks,
+//! advanced settings, other programs' rules, recent blocks). Everything comes
+//! from `rediwm-firewall-helper` through `firewall_client.zig`; changes need
+//! Unlock (the helper's `authorize`, then polkit remembers the password for a
+//! few minutes). The helper's client lives only while the Network page is on
+//! screen. Strings from a reply are copied into the tree's arena: the next
+//! reply frees them.
+const std = @import("std");
+const i18n = @import("i18n");
+const ui = @import("ui");
+const fw = @import("firewall");
+const panel = @import("../panel.zig");
+const Client = @import("firewall_client.zig").Client;
+const widgets = @import("network_ui.zig");
+const fields = @import("network_fields.zig");
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const model = fw.model;
+const text = widgets.text;
+const group = widgets.group;
+const card = widgets.card;
+const action = widgets.action;
+
+pub const Field = enum { port, address, source, comment };
+
+pub const Form = struct {
+ kind: usize = 0,
+ service: usize = 0,
+ rule_action: usize = 0,
+ proto: usize = 0,
+ direction: usize = 0,
+ source: usize = 0,
+ scope: usize = 0,
+ fields: fields.Slots(Field) = .{},
+};
+
+pub const Section = struct {
+ client: ?*Client = null,
+ unlocked: bool = false,
+ managing: bool = false,
+ adding: bool = false,
+ /// Reading needs the password here (FreeBSD's polkit today).
+ read_denied: bool = false,
+ show_blocks: bool = false,
+ /// A rule whose Remove waits for a second click.
+ remove_armed: ?usize = null,
+ message: []const u8 = "",
+ form: Form = .{},
+ /// Whether polkit has our actions, checked once per visit to the page.
+ policy: ?bool = null,
+
+ pub fn capture(s: *Section) void {
+ s.form.fields.capture();
+ }
+
+ /// The page went away (another page, search, close, lock): stop the
+ /// helper and forget the unlock.
+ pub fn hide(s: *Section) void {
+ if (s.client) |client| client.destroy();
+ s.client = null;
+ s.unlocked = false;
+ s.adding = false;
+ s.show_blocks = false;
+ s.remove_armed = null;
+ s.message = "";
+ s.policy = null;
+ }
+
+ pub fn deinit(s: *Section) void {
+ s.hide();
+ s.form.fields.release();
+ }
+};
+
+pub fn owner(raw: ?*anyopaque) *panel.ControlCenter {
+ return @ptrCast(@alignCast(raw.?));
+}
+
+/// Starts the helper's client when the Network page is built.
+pub fn start(cc: *panel.ControlCenter) void {
+ const s = &cc.firewall;
+ if (s.client != null or cc.server.greeter_mode or cc.server.locker != null) return;
+ if (s.policy == null) s.policy = @import("firewall_client.zig").policyInstalled(cc.server.io);
+ if (!s.policy.?) {
+ s.message = i18n.tr("Firewall settings are not installed for this build: its polkit policy is missing.");
+ return;
+ }
+ s.client = Client.create(cc.server.io, cc.server.wl_server.getEventLoop(), cc, changed) catch return;
+ s.client.?.send(.{ .op = .status }, .read) catch {
+ s.message = i18n.tr("The firewall helper could not be started.");
+ };
+}
+
+fn changed(raw: *anyopaque) void {
+ const cc: *panel.ControlCenter = @ptrCast(@alignCast(raw));
+ const s = &cc.firewall;
+ const client = s.client orelse return;
+ s.message = "";
+ switch (client.outcome) {
+ .denied => {
+ if (client.op == .status or client.op == .blocks) {
+ if (client.mode == .read) s.read_denied = true;
+ } else {
+ s.unlocked = false;
+ s.message = i18n.tr("Authentication was cancelled or denied.");
+ }
+ },
+ .broken => s.message = i18n.tr("The firewall helper did not answer."),
+ .failed => s.message = client.failure(),
+ .ok => if (client.op == .authorize) {
+ s.unlocked = true;
+ if (s.read_denied or client.status() == null) client.send(.{ .op = .status }, readMode(s)) catch {};
+ } else if (client.op == .add_rule) {
+ s.adding = false;
+ s.form.fields.release();
+ },
+ .none => {},
+ }
+ client.flush();
+ cc.refresh();
+}
+
+pub fn readMode(s: *const Section) @import("firewall_client.zig").Mode {
+ return if (s.read_denied) .manage else .read;
+}
+
+/// Sends a change; the reply carries the new status.
+pub fn change(cc: *panel.ControlCenter, req: fw.protocol.Request) void {
+ const s = &cc.firewall;
+ const client = s.client orelse return;
+ if (!s.unlocked) return;
+ s.remove_armed = null;
+ client.send(req, .manage) catch {
+ s.message = i18n.tr("Another firewall change is still running.");
+ };
+ cc.refresh();
+}
+
+pub fn busy(cc: *const panel.ControlCenter) bool {
+ const client = cc.firewall.client orelse return true;
+ return client.busy;
+}
+
+/// Whether controls that change something are usable now.
+pub fn editable(cc: *const panel.ControlCenter) bool {
+ const client = cc.firewall.client orelse return false;
+ const status = client.status() orelse return false;
+ return cc.firewall.unlocked and !client.busy and status.capabilities.edit;
+}
+
+pub fn policyLabel(p: model.Policy) []const u8 {
+ return switch (p) {
+ .accept => i18n.tr("Allow"),
+ .drop => i18n.tr("Block"),
+ .reject => i18n.tr("Reject"),
+ };
+}
+
+pub fn backendName(b: model.Backend, system: model.System) []const u8 {
+ return switch (b) {
+ .none => i18n.tr("None"),
+ .own => if (system == .freebsd) i18n.tr("pf (RediWM rules)") else i18n.tr("RediWM (nftables)"),
+ .ufw => "ufw",
+ .firewalld => "firewalld",
+ .redi => "RediOS",
+ .foreign => i18n.tr("another firewall"),
+ };
+}
+
+fn loggingLabel(level: model.Logging) []const u8 {
+ return switch (level) {
+ .off => i18n.tr("Off"),
+ .low => i18n.tr("Low"),
+ .medium => i18n.tr("Medium"),
+ .high => i18n.tr("High"),
+ };
+}
+
+pub const Id = enum(usize) {
+ refresh = 1,
+ unlock,
+ manage,
+ back,
+ keep,
+ lockdown_off,
+ lockdown_on,
+ add_open,
+ add_cancel,
+ add_submit,
+ blocks,
+ _,
+};
+pub const remove_base: usize = 1000;
+pub const block_base: usize = 2000;
+pub const allow_base: usize = 3000;
+pub const trust_base: usize = 4000;
+
+pub fn clicked(raw: ?*anyopaque, id: usize) void {
+ const cc = owner(raw);
+ const s = &cc.firewall;
+ const client = s.client orelse return;
+ s.form.fields.capture();
+ switch (@as(Id, @fromBackingInt(@intCast(id)))) {
+ .refresh => client.send(.{ .op = .status }, readMode(s)) catch {},
+ .unlock => {
+ if (s.unlocked) {
+ s.unlocked = false;
+ s.adding = false;
+ } else client.send(.{ .op = .authorize }, .manage) catch {};
+ },
+ .manage => s.managing = true,
+ .back => {
+ s.managing = false;
+ s.adding = false;
+ s.show_blocks = false;
+ },
+ .keep => change(cc, .{ .op = .confirm }),
+ .lockdown_off => change(cc, .{ .op = .lockdown, .on = false }),
+ .lockdown_on => change(cc, .{ .op = .lockdown, .on = true, .revert_after = 20 }),
+ .add_open => {
+ s.form.fields.release();
+ s.form = .{};
+ s.form.fields.set(cc, .port, "", i18n.tr("8080 or 6000-6010"));
+ s.form.fields.set(cc, .address, "", i18n.tr("203.0.113.9 or 10.0.0.0/8"));
+ s.form.fields.set(cc, .source, "", i18n.tr("192.168.1.0/24"));
+ s.form.fields.set(cc, .comment, "", i18n.tr("Optional"));
+ s.adding = true;
+ },
+ .add_cancel => {
+ s.adding = false;
+ s.form.fields.release();
+ s.message = "";
+ },
+ .add_submit => @import("firewall_rules.zig").submit(cc),
+ .blocks => {
+ s.show_blocks = true;
+ client.send(.{ .op = .blocks }, readMode(s)) catch {};
+ },
+ _ => @import("firewall_cards.zig").rowClicked(cc, id),
+ }
+ cc.refresh();
+}
+
+fn toggled(raw: ?*anyopaque, id: usize, on: bool) void {
+ const cc = owner(raw);
+ const status = (cc.firewall.client orelse return).status() orelse return;
+ if (id == 0) {
+ if (on) change(cc, .{ .op = .enable, .backend = status.backend }) else change(cc, .{ .op = .disable });
+ }
+}
+
+fn fact(a: Allocator, label: []const u8, value: []const u8) !W {
+ var column = try group(a, .column, &.{ text(label, 12, true), text(value, 14, false) });
+ column.gap = 3;
+ column.width = .{ .flex = 1 };
+ return column;
+}
+
+fn headline(status: *const model.Status) []const u8 {
+ if (status.lockdown) return i18n.tr("Blocking all connections");
+ if (status.backend == .none) return i18n.tr("Not available");
+ if (status.running) return i18n.tr("On");
+ return i18n.tr("Off");
+}
+
+fn summary(a: Allocator, status: *const model.Status) ![]const u8 {
+ var buffer: [256]u8 = undefined;
+ if (status.backend == .none) return i18n.tr("No firewall tool is installed (nftables, ufw, firewalld or pf).");
+ if (!status.running) return a.dupe(u8, i18n.fmt(&buffer, i18n.tr("{name} is installed but not filtering. Unprotected."), .{ .name = backendName(status.backend, status.system) }) catch "");
+ const incoming: []const u8 = switch (status.incoming) {
+ .accept => i18n.tr("allows incoming"),
+ .drop, .reject => i18n.tr("blocks incoming"),
+ };
+ const outgoing: []const u8 = if (status.outgoing == .accept) i18n.tr("allows outgoing") else i18n.tr("blocks outgoing");
+ return a.dupe(u8, i18n.fmt(&buffer, i18n.tr("Protected by {name} · {incoming}, {outgoing}"), .{ .name = backendName(status.backend, status.system), .incoming = incoming, .outgoing = outgoing }) catch "");
+}
+
+/// The line under the facts: the most exposed listening program.
+fn exposure(cc: *panel.ControlCenter, a: Allocator, status: *const model.Status) !?W {
+ var reachable: usize = 0;
+ var first: ?usize = null;
+ for (status.listeners, 0..) |l, i| if (l.verdict == .everywhere) {
+ reachable += 1;
+ if (first == null) first = i;
+ };
+ var buffer: [256]u8 = undefined;
+ if (first) |i| {
+ const l = status.listeners[i];
+ const name = if (l.process.len != 0) l.process else i18n.tr("A program");
+ const line = try a.dupe(u8, i18n.fmt(&buffer, i18n.tr("{name} (port {port}) can be reached from any network."), .{ .name = name, .port = l.port }) catch "");
+ var label = text(line, 13, false);
+ label.width = .{ .flex = 1 };
+ label.kind.text.color = panel.palette().danger;
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, label);
+ if (status.capabilities.edit) {
+ var block = action(cc, "firewall_expose_block", i18n.tr("Block"), block_base + i, clicked, !editable(cc));
+ block.width = .auto;
+ block.kind.button.variant = .secondary;
+ try items.append(a, block);
+ }
+ var row = try group(a, .row, items.items);
+ row.name = "firewall_exposure";
+ return row;
+ }
+ if (!status.running) return null;
+ const line: []const u8 = if (status.listeners.len == 0) i18n.tr("No program is listening for connections.") else i18n.tr("No listening program can be reached from every network.");
+ return text(line, 13, true);
+}
+
+fn rulesLine(a: Allocator, status: *const model.Status) ![]const u8 {
+ var allow: usize = 0;
+ var block: usize = 0;
+ for (status.rules) |r| switch (r.action) {
+ .allow, .limit => allow += 1,
+ .deny, .reject => block += 1,
+ };
+ var out: std.Io.Writer.Allocating = .init(a);
+ var buffer: [128]u8 = undefined;
+ try out.writer.writeAll(i18n.fmt(&buffer, i18n.tr("{allow} allowed · {block} blocked"), .{ .allow = allow, .block = block }) catch "");
+ if (status.foreign.len != 0) {
+ try out.writer.print(" · {s} ", .{i18n.tr("Also active:")});
+ for (status.foreign, 0..) |f, i| {
+ const who = if (f.owner.len != 0) f.owner else f.name;
+ try out.writer.print("{s}{s} ({d})", .{ if (i == 0) "" else ", ", who, f.rules });
+ }
+ }
+ return out.written();
+}
+
+fn noticeRow(cc: *panel.ControlCenter, a: Allocator, message: []const u8, label: []const u8, id: Id, name: []const u8) !W {
+ var line = text(message, 13, false);
+ line.width = .{ .flex = 1 };
+ line.kind.text.color = panel.palette().danger;
+ var button = action(cc, name, label, @backingInt(id), clicked, busy(cc) or !cc.firewall.unlocked);
+ button.width = .auto;
+ return group(a, .row, &.{ line, button });
+}
+
+/// The overview card: always on the Network page and at the top of the
+/// sub-view.
+pub fn overview(cc: *panel.ControlCenter, a: Allocator) !W {
+ const s = &cc.firewall;
+ const client = s.client;
+ const status = if (client) |cl| cl.status() else null;
+ var items: std.ArrayList(W) = .empty;
+ const on = if (status) |st| st.running and !st.lockdown else false;
+ var labels = try group(a, .column, &.{
+ text(i18n.tr("Firewall"), 20, false),
+ try widgets.status(a, if (status) |st| headline(st) else if (s.read_denied) i18n.tr("Locked") else if (client == null) i18n.tr("Unavailable") else i18n.tr("Reading…"), on),
+ });
+ labels.width = .{ .flex = 1 };
+ labels.gap = 4;
+ var header: std.ArrayList(W) = .empty;
+ try header.appendSlice(a, &.{ widgets.icon(.shield, 30, on), labels });
+ if (status) |st| if (st.backend != .none and st.backend != .redi) {
+ const disabled = !editable(cc) and !(s.unlocked and !busy(cc) and st.conflicts.len == 0);
+ try header.append(a, .{ .name = "firewall_enabled", .kind = .{ .toggle = .{ .style = .settings, .on = st.running, .disabled = disabled or st.conflicts.len != 0, .owner = cc, .id = 0, .on_change = toggled } } });
+ };
+ try items.append(a, try group(a, .row, header.items));
+
+ if (status) |st| {
+ try items.append(a, text(try summary(a, st), 13, true));
+ if (st.backend == .redi) try items.append(a, text(i18n.tr("Managed by RediOS. Change it with redi; it is shown here read-only."), 13, true));
+ if (st.conflicts.len != 0) {
+ var line = text(i18n.tr("More than one firewall is active. Turn all but one off to make changes here."), 13, false);
+ line.kind.text.color = panel.palette().danger;
+ try items.append(a, line);
+ }
+ if (st.needs_anchor and !st.running) try items.append(a, text(i18n.tr("Turning on adds RediWM's anchor to pf.conf (a backup is kept)."), 12, true));
+ if (st.revert_in != 0) {
+ var buffer: [128]u8 = undefined;
+ const line = try a.dupe(u8, i18n.fmt(&buffer, i18n.tr("The last change is undone in about {seconds} s unless you keep it."), .{ .seconds = st.revert_in }) catch "");
+ try items.append(a, try noticeRow(cc, a, line, i18n.tr("Keep change"), .keep, "firewall_keep"));
+ }
+ if (st.lockdown) try items.append(a, try noticeRow(cc, a, i18n.tr("All network connections are blocked."), i18n.tr("Stop blocking"), .lockdown_off, "firewall_lockdown_off"));
+ if (st.backend != .none) {
+ try items.append(a, try group(a, .row, &.{
+ try fact(a, i18n.tr("Incoming"), policyLabel(st.incoming)),
+ try fact(a, i18n.tr("Outgoing"), policyLabel(st.outgoing)),
+ try fact(a, i18n.tr("Forwarding"), policyLabel(st.forward)),
+ }));
+ try items.append(a, try group(a, .row, &.{
+ try fact(a, i18n.tr("Ping"), if (st.ping) i18n.tr("Answered") else i18n.tr("Ignored")),
+ try fact(a, i18n.tr("Logging"), loggingLabel(st.logging)),
+ try fact(a, i18n.tr("Starts at boot"), if (st.boot) i18n.tr("Yes") else i18n.tr("No")),
+ }));
+ if (try exposure(cc, a, st)) |row| try items.append(a, row);
+ try items.append(a, text(try rulesLine(a, st), 12, true));
+ }
+ } else if (s.read_denied) {
+ try items.append(a, text(i18n.tr("Unlock to view the firewall."), 13, true));
+ }
+
+ const message: []const u8 = if (client != null and client.?.busy and client.?.mode == .manage) (if (client.?.op == .authorize) i18n.tr("Waiting for authentication…") else i18n.tr("Applying…")) else if (s.message.len != 0) s.message else if (!s.unlocked and status != null and status.?.capabilities.edit) i18n.tr("Unlock to change firewall settings.") else "";
+ if (message.len != 0) try items.append(a, text(try a.dupe(u8, message), 12, true));
+
+ var buttons: std.ArrayList(W) = .empty;
+ var refresh = action(cc, "firewall_refresh", i18n.tr("Refresh"), @backingInt(Id.refresh), clicked, busy(cc) or (s.read_denied and !s.unlocked));
+ refresh.kind.button.variant = .secondary;
+ refresh.kind.button.leading_icon = .refresh;
+ refresh.width = .auto;
+ try buttons.append(a, refresh);
+ var unlock = action(cc, "firewall_unlock", if (s.unlocked) i18n.tr("Lock") else i18n.tr("Unlock"), @backingInt(Id.unlock), clicked, busy(cc) or client == null);
+ unlock.kind.button.leading_icon = if (s.unlocked) .checkmark else .lock;
+ unlock.kind.button.variant = .secondary;
+ unlock.width = .auto;
+ try buttons.append(a, unlock);
+ if (!s.managing) {
+ var manage = action(cc, "firewall_manage", i18n.tr("Manage…"), @backingInt(Id.manage), clicked, status == null);
+ manage.width = .auto;
+ try buttons.append(a, manage);
+ }
+ var row = try group(a, .row, buttons.items);
+ row.@"align" = .center;
+ try items.append(a, row);
+ var result = try card(a, items.items);
+ result.name = "firewall_card";
+ return result;
+}
+
+/// The Firewall sub-view that replaces the Network page behind Manage.
+pub fn view(cc: *panel.ControlCenter, a: Allocator) !W {
+ const cards = @import("firewall_cards.zig");
+ const rules = @import("firewall_rules.zig");
+ var back = action(cc, "firewall_back", i18n.tr("Network"), @backingInt(Id.back), clicked, false);
+ back.kind.button.leading_icon = .chevron_left;
+ back.kind.button.variant = .secondary;
+ back.width = .auto;
+ var page: std.ArrayList(W) = .empty;
+ try page.append(a, try group(a, .row, &.{back}));
+ try page.append(a, try overview(cc, a));
+ const status = (cc.firewall.client orelse return group(a, .column, page.items)).status() orelse return group(a, .column, page.items);
+ if (status.backend == .none) return group(a, .column, page.items);
+ try page.append(a, try rules.rulesCard(cc, a, status));
+ if (cc.firewall.adding) try page.append(a, try rules.formCard(cc, a, status));
+ try page.append(a, try cards.listeners(cc, a, status));
+ if (status.networks.len != 0) try page.append(a, try cards.networks(cc, a, status));
+ try page.append(a, try cards.advanced(cc, a, status));
+ if (status.foreign.len != 0) try page.append(a, try cards.foreign(a, status));
+ try page.append(a, try cards.blocks(cc, a, status));
+ return group(a, .column, page.items);
+}
diff --git a/src/control_center/sections/firewall_cards.zig b/src/control_center/sections/firewall_cards.zig
new file mode 100644
index 0000000..cd892ed
--- /dev/null
+++ b/src/control_center/sections/firewall_cards.zig
@@ -0,0 +1,324 @@
+//! The Firewall sub-view's other cards: listening programs, networks and their
+//! trust, advanced settings, other programs' rules and recent blocks, plus the
+//! row buttons' actions.
+const std = @import("std");
+const i18n = @import("i18n");
+const ui = @import("ui");
+const fw = @import("firewall");
+const panel = @import("../panel.zig");
+const firewall = @import("firewall.zig");
+const widgets = @import("network_ui.zig");
+const fields = @import("network_fields.zig");
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const model = fw.model;
+const text = widgets.text;
+const group = widgets.group;
+const card = widgets.card;
+const action = widgets.action;
+
+fn heading(a: Allocator, title: []const u8, note: []const u8) !W {
+ var column = try group(a, .column, &.{ text(title, 16, false), text(note, 12, true) });
+ column.gap = 4;
+ return column;
+}
+
+fn verdictLabel(v: model.Verdict) []const u8 {
+ return switch (v) {
+ .local => i18n.tr("This computer only"),
+ .blocked => i18n.tr("Blocked"),
+ .home => i18n.tr("Home or local networks"),
+ .everywhere => i18n.tr("Any network"),
+ };
+}
+
+pub fn listeners(cc: *panel.ControlCenter, a: Allocator, status: *const model.Status) !W {
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, try heading(a, i18n.tr("Listening programs"), i18n.tr("Programs waiting for connections, and who can reach them through the firewall.")));
+ if (status.listeners.len == 0) try items.append(a, text(i18n.tr("No program is listening."), 13, true));
+ const edit = status.capabilities.edit;
+ for (status.listeners, 0..) |l, i| {
+ if (i >= 64) break;
+ const name = if (l.process.len != 0) try a.dupe(u8, l.process) else i18n.tr("Unknown program");
+ const where = try std.fmt.allocPrint(a, "{s} {d} · {s}", .{ if (l.proto == .tcp) "TCP" else "UDP", l.port, l.address });
+ var labels = try group(a, .column, &.{ text(name, 14, false), text(where, 12, true) });
+ labels.gap = 3;
+ labels.width = .{ .flex = 1 };
+ var verdict = text(verdictLabel(l.verdict), 12, l.verdict != .everywhere);
+ if (l.verdict == .everywhere) verdict.kind.text.color = panel.palette().danger;
+ // Measured text can come out a little narrower than drawn at
+ // fractional scales; a fixed column keeps the label whole.
+ verdict.width = .{ .fixed = @max(150, ui.measure.textNatural(verdictLabel(l.verdict), .sans, 400, 12).w + 12) };
+ var row: std.ArrayList(W) = .empty;
+ try row.appendSlice(a, &.{ labels, verdict });
+ if (edit and (l.verdict == .everywhere or l.verdict == .home)) {
+ var block = action(cc, "firewall_listener_block", i18n.tr("Block"), firewall.block_base + i, firewall.clicked, !firewall.editable(cc));
+ block.kind.button.variant = .ghost;
+ block.width = .auto;
+ try row.append(a, block);
+ }
+ if (edit and l.verdict == .blocked) {
+ var allow = action(cc, "firewall_listener_allow", i18n.tr("Allow on home networks"), firewall.allow_base + i, firewall.clicked, !firewall.editable(cc));
+ allow.kind.button.variant = .ghost;
+ allow.width = .auto;
+ try row.append(a, allow);
+ }
+ var line = try group(a, .row, row.items);
+ line.name = "firewall_listener";
+ try items.append(a, line);
+ }
+ var result = try card(a, items.items);
+ result.name = "firewall_listeners";
+ return result;
+}
+
+fn trustLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Public"), i18n.msg("Home") });
+}
+
+pub fn networks(cc: *panel.ControlCenter, a: Allocator, status: *const model.Status) !W {
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, try heading(a, i18n.tr("Networks"), if (status.capabilities.trust) i18n.tr("Home networks also get the rules marked \"home networks only\", such as sharing and device discovery. New networks are Public.") else i18n.tr("This firewall applies the same rules on every network.")));
+ for (status.networks, 0..) |n, i| {
+ if (i >= 32) break;
+ const subtitle = if (n.iface.len != 0 and !std.mem.eql(u8, n.iface, n.name)) try a.dupe(u8, n.iface) else "";
+ var labels = try group(a, .column, &.{ text(try a.dupe(u8, n.name), 14, false), text(subtitle, 12, true) });
+ labels.gap = 3;
+ labels.width = .{ .flex = 1 };
+ var row: std.ArrayList(W) = .empty;
+ try row.append(a, labels);
+ if (status.capabilities.trust) {
+ const trust: W = .{ .name = "firewall_trust", .kind = .{ .select = .{ .labels = trustLabels(), .selected = @backingInt(n.trust), .owner = cc, .id = firewall.trust_base + i, .on_change = selected, .disabled = !firewall.editable(cc) } }, .width = .{ .fixed = 140 }, .height = .{ .fixed = 34 } };
+ try row.append(a, trust);
+ }
+ try items.append(a, try group(a, .row, row.items));
+ }
+ var result = try card(a, items.items);
+ result.name = "firewall_networks";
+ return result;
+}
+
+fn incomingLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Block"), i18n.msg("Reject"), i18n.msg("Allow") });
+}
+fn outgoingLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Allow"), i18n.msg("Block"), i18n.msg("Reject") });
+}
+fn forwardLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Block"), i18n.msg("Allow") });
+}
+fn loggingLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Off"), i18n.msg("Low"), i18n.msg("Medium"), i18n.msg("High") });
+}
+
+const select_incoming = 1;
+const select_outgoing = 2;
+const select_forward = 3;
+const select_logging = 4;
+const toggle_ping = 1;
+const toggle_ssh = 2;
+const toggle_boot = 3;
+
+fn settingRow(a: Allocator, title: []const u8, note: []const u8, control: W) !W {
+ var labels = try group(a, .column, &.{ text(title, 14, false), text(note, 12, true) });
+ labels.gap = 3;
+ labels.width = .{ .flex = 1 };
+ return group(a, .row, &.{ labels, control });
+}
+
+fn selectWidget(cc: *panel.ControlCenter, name: []const u8, id: usize, labels: []const []const u8, index: usize) W {
+ return .{ .name = name, .kind = .{ .select = .{ .labels = labels, .selected = index, .owner = cc, .id = id, .on_change = selected, .disabled = !firewall.editable(cc) } }, .width = .{ .fixed = 160 }, .height = .{ .fixed = 34 } };
+}
+
+fn toggleWidget(cc: *panel.ControlCenter, name: []const u8, id: usize, on: bool) W {
+ return .{ .name = name, .kind = .{ .toggle = .{ .style = .settings, .on = on, .disabled = !firewall.editable(cc), .owner = cc, .id = id, .on_change = toggled } } };
+}
+
+pub fn advanced(cc: *panel.ControlCenter, a: Allocator, status: *const model.Status) !W {
+ const caps = status.capabilities;
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, text(i18n.tr("Advanced"), 16, false));
+ const incoming: usize = switch (status.incoming) {
+ .drop => 0,
+ .reject => 1,
+ .accept => 2,
+ };
+ try items.append(a, try settingRow(a, i18n.tr("Incoming connections"), i18n.tr("What happens to connections no rule allows. Block is the safe choice."), selectWidget(cc, "firewall_incoming", select_incoming, incomingLabels(), incoming)));
+ if (caps.outgoing_policy) {
+ const outgoing: usize = switch (status.outgoing) {
+ .accept => 0,
+ .drop => 1,
+ .reject => 2,
+ };
+ try items.append(a, try settingRow(a, i18n.tr("Outgoing connections"), i18n.tr("Blocking stops every program from connecting out unless a rule allows it. It is undone after 20 s unless you keep it."), selectWidget(cc, "firewall_outgoing", select_outgoing, outgoingLabels(), outgoing)));
+ }
+ if (caps.forward_policy) try items.append(a, try settingRow(a, i18n.tr("Forwarding"), i18n.tr("Traffic passing through this computer, for virtual machines or sharing a connection."), selectWidget(cc, "firewall_forward", select_forward, forwardLabels(), if (status.forward == .accept) 1 else 0)));
+ if (caps.ping) try items.append(a, try settingRow(a, i18n.tr("Answer ping"), i18n.tr("Let other computers check that this one is there."), toggleWidget(cc, "firewall_ping", toggle_ping, status.ping)));
+ if (caps.ssh_limit) try items.append(a, try settingRow(a, i18n.tr("Slow down SSH login attempts"), i18n.tr("Drops a source that opens more than 6 SSH connections a minute."), toggleWidget(cc, "firewall_ssh_limit", toggle_ssh, status.ssh_limit)));
+ if (caps.logging) try items.append(a, try settingRow(a, i18n.tr("Log blocked connections"), i18n.tr("Records blocked connections in the system log, at a limited rate."), selectWidget(cc, "firewall_logging", select_logging, loggingLabels(), @backingInt(status.logging))));
+ if (caps.boot) try items.append(a, try settingRow(a, i18n.tr("Start at boot"), i18n.tr("Load the firewall before the network comes up."), toggleWidget(cc, "firewall_boot", toggle_boot, status.boot)));
+ if (caps.lockdown and !status.lockdown) {
+ var button = action(cc, "firewall_lockdown", i18n.tr("Block all connections"), @backingInt(firewall.Id.lockdown_on), firewall.clicked, !(cc.firewall.unlocked and !firewall.busy(cc)));
+ button.kind.button.variant = .secondary;
+ button.width = .auto;
+ try items.append(a, try settingRow(a, i18n.tr("Lockdown"), i18n.tr("Cut this computer off from every network until you stop it or restart. Undone after 20 s unless you keep it."), button));
+ }
+ var result = try card(a, items.items);
+ result.name = "firewall_advanced";
+ return result;
+}
+
+pub fn foreign(a: Allocator, status: *const model.Status) !W {
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, try heading(a, i18n.tr("Other programs' rules"), i18n.tr("Loaded by other programs. RediWM never changes them, and they apply in addition to the rules above.")));
+ for (status.foreign) |f| {
+ const who = if (f.owner.len != 0) try a.dupe(u8, f.owner) else i18n.tr("Unknown");
+ var buffer: [64]u8 = undefined;
+ const count = try a.dupe(u8, i18n.fmt(&buffer, i18n.tr("{count} rules"), .{ .count = f.rules }) catch "");
+ var labels = try group(a, .column, &.{ text(who, 14, false), text(try a.dupe(u8, f.name), 12, true) });
+ labels.gap = 3;
+ labels.width = .{ .flex = 1 };
+ try items.append(a, try group(a, .row, &.{ labels, text(count, 12, true) }));
+ }
+ var result = try card(a, items.items);
+ result.name = "firewall_foreign";
+ return result;
+}
+
+pub fn blocks(cc: *panel.ControlCenter, a: Allocator, status: *const model.Status) !W {
+ var items: std.ArrayList(W) = .empty;
+ var title = try heading(a, i18n.tr("Recent blocks"), if (status.logging == .off and status.capabilities.logging) i18n.tr("Logging is off, so only blocks from before it was turned off can show.") else i18n.tr("Connections the firewall refused in the last day."));
+ title.width = .{ .flex = 1 };
+ var show = action(cc, "firewall_blocks", if (cc.firewall.show_blocks) i18n.tr("Refresh") else i18n.tr("Show"), @backingInt(firewall.Id.blocks), firewall.clicked, firewall.busy(cc) or (cc.firewall.read_denied and !cc.firewall.unlocked));
+ show.kind.button.variant = .secondary;
+ show.width = .auto;
+ try items.append(a, try group(a, .row, &.{ title, show }));
+ if (cc.firewall.show_blocks) {
+ if (status.blocks.len == 0) try items.append(a, text(if (firewall.busy(cc)) i18n.tr("Reading…") else i18n.tr("Nothing was blocked recently."), 13, true));
+ for (status.blocks, 0..) |b, i| {
+ if (i >= 40) break;
+ const line = try std.fmt.allocPrint(a, "{s} · {s} {s} {d} · {s} {s}{s}{s}", .{
+ b.time,
+ if (b.direction == .in) i18n.tr("in") else i18n.tr("out"),
+ b.proto,
+ b.port,
+ if (b.direction == .in) i18n.tr("from") else i18n.tr("to"),
+ b.source,
+ if (b.iface.len != 0) " · " else "",
+ b.iface,
+ });
+ try items.append(a, text(line, 12, true));
+ }
+ }
+ var result = try card(a, items.items);
+ result.name = "firewall_blocks_card";
+ return result;
+}
+
+fn selected(raw: ?*anyopaque, id: usize, index: usize) void {
+ const cc = firewall.owner(raw);
+ const status = (cc.firewall.client orelse return).status() orelse return;
+ if (id >= firewall.trust_base) {
+ const i = id - firewall.trust_base;
+ if (i >= status.networks.len) return;
+ const n = status.networks[i];
+ firewall.change(cc, .{ .op = .set_trust, .uuid = n.uuid, .iface = n.iface, .trust = if (index == 1) .home else .public });
+ return;
+ }
+ switch (id) {
+ select_incoming => firewall.change(cc, .{ .op = .set_defaults, .incoming = switch (index) {
+ 1 => .reject,
+ 2 => .accept,
+ else => .drop,
+ } }),
+ select_outgoing => {
+ const p: model.Policy = switch (index) {
+ 1 => .drop,
+ 2 => .reject,
+ else => .accept,
+ };
+ firewall.change(cc, .{ .op = .set_defaults, .outgoing = p, .revert_after = if (p == .accept) 0 else 20 });
+ },
+ select_forward => firewall.change(cc, .{ .op = .set_defaults, .forward = if (index == 1) .accept else .drop }),
+ select_logging => firewall.change(cc, .{ .op = .set_option, .option = .logging, .logging = @fromBackingInt(@intCast(@min(index, 3))) }),
+ else => {},
+ }
+}
+
+fn toggled(raw: ?*anyopaque, id: usize, on: bool) void {
+ const cc = firewall.owner(raw);
+ const option: fw.protocol.Option = switch (id) {
+ toggle_ping => .ping,
+ toggle_ssh => .ssh_limit,
+ toggle_boot => .boot,
+ else => return,
+ };
+ firewall.change(cc, .{ .op = .set_option, .option = option, .on = on });
+}
+
+fn plainComment(buffer: []u8, name: []const u8) []const u8 {
+ var n: usize = 0;
+ for (name) |ch| {
+ if (n == buffer.len) break;
+ if (std.ascii.isAlphanumeric(ch) or ch == ' ' or ch == '-' or ch == '_' or ch == '.') {
+ buffer[n] = ch;
+ n += 1;
+ }
+ }
+ return buffer[0..n];
+}
+
+/// Allows SSH in? Removing such a rule waits for confirmation (D8).
+fn allowsSsh(rule: model.Rule) bool {
+ if (rule.direction != .in or rule.action == .deny or rule.action == .reject) return false;
+ return std.mem.eql(u8, rule.service, "ssh") or (rule.proto != .udp and model.portCovers(rule.port, 22) and rule.port.len != 0);
+}
+
+/// Buttons in rows: Remove a rule, Block or Allow a listening program.
+pub fn rowClicked(cc: *panel.ControlCenter, id: usize) void {
+ const s = &cc.firewall;
+ const status = (s.client orelse return).status() orelse return;
+ if (id >= firewall.remove_base and id < firewall.block_base) {
+ const i = id - firewall.remove_base;
+ if (i >= status.rules.len) return;
+ if (s.remove_armed != i) {
+ s.remove_armed = i;
+ return;
+ }
+ const rule = status.rules[i];
+ firewall.change(cc, .{ .op = .remove_rule, .rule = rule, .revert_after = if (allowsSsh(rule)) 20 else 0 });
+ return;
+ }
+ if (id >= firewall.block_base and id < firewall.allow_base) {
+ const i = id - firewall.block_base;
+ if (i >= status.listeners.len) return;
+ const l = status.listeners[i];
+ if (status.incoming == .accept) {
+ var buffer: [32]u8 = undefined;
+ const port = std.fmt.bufPrint(&buffer, "{d}", .{l.port}) catch return;
+ firewall.change(cc, .{ .op = .add_rule, .rule = .{ .action = .deny, .port = port, .proto = l.proto } });
+ return;
+ }
+ // Blocked by default: take away the rule that lets it through.
+ for (status.rules) |rule| {
+ if (rule.action != .allow and rule.action != .limit) continue;
+ if (rule.port.len == 0 and rule.service.len == 0) continue;
+ if (!model.about(rule, l)) continue;
+ firewall.change(cc, .{ .op = .remove_rule, .rule = rule, .revert_after = if (allowsSsh(rule)) 20 else 0 });
+ return;
+ }
+ s.message = i18n.tr("No single rule opens this port; check the rules list.");
+ return;
+ }
+ if (id >= firewall.allow_base and id < firewall.trust_base) {
+ const i = id - firewall.allow_base;
+ if (i >= status.listeners.len) return;
+ const l = status.listeners[i];
+ var port_buffer: [32]u8 = undefined;
+ var comment_buffer: [32]u8 = undefined;
+ const port = std.fmt.bufPrint(&port_buffer, "{d}", .{l.port}) catch return;
+ var rule: model.Rule = .{ .port = port, .proto = l.proto, .comment = plainComment(&comment_buffer, l.process) };
+ if (status.capabilities.trust) rule.scope = .home else if (status.capabilities.sources) rule.source = "lan";
+ firewall.change(cc, .{ .op = .add_rule, .rule = rule });
+ }
+}
diff --git a/src/control_center/sections/firewall_client.zig b/src/control_center/sections/firewall_client.zig
new file mode 100644
index 0000000..50e381e
--- /dev/null
+++ b/src/control_center/sections/firewall_client.zig
@@ -0,0 +1,242 @@
+//! Runs `rediwm-firewall-helper` through pkexec, one request at a time, for
+//! the Firewall section while it is on screen. Event-driven: the reply pipe
+//! and the child's exit wake the loop; the only timers are the request's
+//! deadline and, while a change waits to revert, one at its deadline.
+const std = @import("std");
+const wl = @import("wayland").server.wl;
+const c = @import("c");
+const platform = @import("platform");
+const fw = @import("firewall");
+const Child = @import("../../session/child.zig");
+const a = std.heap.c_allocator;
+
+pub const Mode = enum { read, manage };
+
+const helper_path = @import("install_paths").bin ++ "/rediwm-firewall-helper";
+const policy_dirs = [_][]const u8{ "/usr/share/polkit-1/actions", "/usr/local/share/polkit-1/actions", "/etc/polkit-1/actions" };
+
+/// Whether polkit has our actions for this helper. Without them pkexec falls
+/// back to its generic action, which asks for an administrator password even
+/// to read, so nothing runs: a build whose policy is not installed (a
+/// development or test compositor) never reaches the session's polkit agent.
+pub fn policyInstalled(io: std.Io) bool {
+ const needle = "<annotate key=\"org.freedesktop.policykit.exec.path\">" ++ helper_path ++ "</annotate>";
+ for (policy_dirs) |dir| {
+ var buffer: [4096]u8 = undefined;
+ const path = std.fmt.bufPrint(&buffer, "{s}/org.rediwm.firewall.policy", .{dir}) catch continue;
+ const text = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(64 << 10)) catch continue;
+ defer a.free(text);
+ if (std.mem.indexOf(u8, text, needle) != null) return true;
+ }
+ return false;
+}
+
+/// What the last run ended as, for the page's message line.
+pub const Outcome = enum { none, ok, failed, denied, broken };
+
+pub const Client = struct {
+ io: std.Io,
+ loop: *wl.EventLoop,
+ owner: *anyopaque,
+ changed: *const fn (*anyopaque) void,
+ child: ?*Child = null,
+ source: ?*wl.EventSource = null,
+ timer: ?*wl.EventSource = null,
+ revert_timer: ?*wl.EventSource = null,
+ fd: c_int = -1,
+ bytes: std.ArrayList(u8) = .empty,
+ /// The latest status; kept while a newer request runs.
+ current: ?std.json.Parsed(fw.protocol.Reply) = null,
+ busy: bool = false,
+ op: fw.protocol.Op = .status,
+ mode: Mode = .read,
+ outcome: Outcome = .none,
+ failure_buf: [160]u8 = undefined,
+ failure_len: usize = 0,
+ /// A status read was asked for while busy; it runs when the request ends.
+ refresh_pending: bool = false,
+
+ pub fn create(io: std.Io, loop: *wl.EventLoop, owner: *anyopaque, changed: *const fn (*anyopaque) void) !*Client {
+ const self = try a.create(Client);
+ self.* = .{ .io = io, .loop = loop, .owner = owner, .changed = changed };
+ return self;
+ }
+
+ pub fn destroy(self: *Client) void {
+ self.cancel();
+ if (self.revert_timer) |timer| timer.remove();
+ if (self.current) |*value| value.deinit();
+ self.bytes.deinit(a);
+ a.destroy(self);
+ }
+
+ /// Stops a running request. A pkexec still asking for the password ends;
+ /// the helper itself runs as root and finishes on its own deadline.
+ pub fn cancel(self: *Client) void {
+ if (self.source) |source| source.remove();
+ self.source = null;
+ if (self.timer) |timer| timer.remove();
+ self.timer = null;
+ if (self.fd >= 0) _ = c.close(self.fd);
+ self.fd = -1;
+ if (self.child) |child| {
+ child.signal(.TERM);
+ child.detach();
+ }
+ self.child = null;
+ self.busy = false;
+ self.refresh_pending = false;
+ }
+
+ pub fn status(self: *const Client) ?*const fw.model.Status {
+ const value = &(self.current orelse return null);
+ return &value.value.status;
+ }
+
+ pub fn failure(self: *const Client) []const u8 {
+ return self.failure_buf[0..self.failure_len];
+ }
+
+ pub fn send(self: *Client, req: fw.protocol.Request, mode: Mode) !void {
+ if (self.busy) {
+ if (req.op == .status) {
+ self.refresh_pending = true;
+ return;
+ }
+ return error.Busy;
+ }
+ const bytes = try std.json.Stringify.valueAlloc(a, req, .{});
+ defer a.free(bytes);
+ if (bytes.len > fw.model.max_request) return error.RequestTooLarge;
+ var sockets: [2]c_int = undefined;
+ if (c.socketpair(c.AF_UNIX, c.SOCK_STREAM | c.SOCK_CLOEXEC, 0, &sockets) != 0) return error.PipeFailed;
+ defer {
+ _ = c.close(sockets[0]);
+ _ = c.close(sockets[1]);
+ }
+ const pkexec = platform.tool.system(self.io, "pkexec") orelse return error.NoPkexec;
+ var process = try std.process.spawn(self.io, .{
+ .argv = &.{ pkexec, "--disable-internal-agent", helper_path, @tagName(mode) },
+ .stdin = .{ .file = .{ .handle = sockets[0], .flags = .{ .nonblocking = false } } },
+ .stdout = .pipe,
+ .stderr = .ignore,
+ .pgid = 0,
+ });
+ errdefer process.kill(self.io);
+ errdefer self.cancel();
+ self.fd = process.stdout.?.handle;
+ process.stdout = null;
+ const flags = c.fcntl(self.fd, c.F_GETFL);
+ if (flags < 0 or c.fcntl(self.fd, c.F_SETFL, flags | c.O_NONBLOCK) < 0) return error.PipeFailed;
+ self.source = try self.loop.addFd(*Client, self.fd, .{ .readable = true }, readable, self);
+ self.timer = try self.loop.addTimer(*Client, timeout, self);
+ // The password prompt may wait for the user; a read never prompts on
+ // Linux but may on FreeBSD.
+ try self.timer.?.timerUpdate(if (mode == .manage) 180000 else 90000);
+ self.child = try Child.watch(a, self.loop, process.id.?, self, exited);
+ process.id = null;
+ const sent = c.send(sockets[1], bytes.ptr, bytes.len, c.MSG_DONTWAIT | c.MSG_NOSIGNAL);
+ if (sent != bytes.len or c.shutdown(sockets[1], c.SHUT_WR) != 0) return error.RequestWriteFailed;
+ self.bytes.clearRetainingCapacity();
+ self.busy = true;
+ self.op = req.op;
+ self.mode = mode;
+ self.outcome = .none;
+ }
+
+ fn drain(self: *Client) void {
+ var buffer: [16384]u8 = undefined;
+ while (self.fd >= 0) {
+ const n = c.read(self.fd, &buffer, buffer.len);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n < 0 and std.posix.errno(n) == .AGAIN) return;
+ if (n <= 0) {
+ if (self.source) |source| source.remove();
+ self.source = null;
+ return;
+ }
+ const count: usize = @intCast(n);
+ if (self.bytes.items.len + count > fw.model.max_reply) {
+ self.bytes.clearRetainingCapacity();
+ if (self.child) |child| child.signal(.TERM);
+ return;
+ }
+ self.bytes.appendSlice(a, buffer[0..count]) catch return;
+ }
+ }
+
+ fn readable(_: c_int, _: wl.EventMask, self: *Client) c_int {
+ self.drain();
+ return 0;
+ }
+
+ fn timeout(self: *Client) c_int {
+ if (self.child) |child| child.signal(.TERM);
+ return 0;
+ }
+
+ fn setFailure(self: *Client, text: []const u8) void {
+ const n = @min(text.len, self.failure_buf.len);
+ @memcpy(self.failure_buf[0..n], text[0..n]);
+ self.failure_len = n;
+ }
+
+ fn exited(raw: ?*anyopaque, _: *Child, exit: ?u32) void {
+ const self: *Client = @ptrCast(@alignCast(raw.?));
+ self.drain();
+ self.child = null;
+ const op = self.op;
+ const pending = self.refresh_pending;
+ self.cancel();
+ self.refresh_pending = pending;
+ // `exit` is the raw wait status.
+ const code: u32 = if (exit) |wait| (if (std.posix.W.IFEXITED(wait)) std.posix.W.EXITSTATUS(wait) else 255) else 255;
+ self.failure_len = 0;
+ // pkexec: 126 when the dialog was dismissed, 127 when not authorized.
+ if (code == 126 or code == 127) {
+ self.outcome = .denied;
+ } else if (self.bytes.items.len == 0) {
+ self.outcome = if (code == 0) .ok else .broken;
+ } else if (std.json.parseFromSlice(fw.protocol.Reply, a, self.bytes.items, .{ .allocate = .alloc_always, .ignore_unknown_fields = true, .max_value_len = fw.model.max_reply })) |reply| {
+ if (reply.value.failure) |text| self.setFailure(text);
+ self.outcome = if (reply.value.failure == null) .ok else .failed;
+ if (op == .authorize) {
+ var discard = reply;
+ discard.deinit();
+ } else {
+ if (self.current) |*previous| previous.deinit();
+ self.current = reply;
+ }
+ } else |_| self.outcome = .broken;
+ self.armRevert();
+ self.op = op;
+ self.changed(self.owner);
+ }
+
+ /// One wake at the revert deadline so the page shows what came back.
+ fn armRevert(self: *Client) void {
+ const left = if (self.status()) |s| s.revert_in else 0;
+ if (left == 0) {
+ if (self.revert_timer) |timer| timer.remove();
+ self.revert_timer = null;
+ return;
+ }
+ if (self.revert_timer == null) self.revert_timer = self.loop.addTimer(*Client, reverted, self) catch return;
+ self.revert_timer.?.timerUpdate(@intCast(@as(u32, @min(left + 2, 400)) * 1000)) catch {};
+ }
+
+ fn reverted(self: *Client) c_int {
+ if (self.revert_timer) |timer| timer.remove();
+ self.revert_timer = null;
+ self.send(.{ .op = .status }, self.mode) catch {};
+ return 0;
+ }
+
+ /// Runs a status read queued while busy.
+ pub fn flush(self: *Client) void {
+ if (!self.busy and self.refresh_pending) {
+ self.refresh_pending = false;
+ self.send(.{ .op = .status }, self.mode) catch {};
+ }
+ }
+};
diff --git a/src/control_center/sections/firewall_rules.zig b/src/control_center/sections/firewall_rules.zig
new file mode 100644
index 0000000..e98e2b8
--- /dev/null
+++ b/src/control_center/sections/firewall_rules.zig
@@ -0,0 +1,277 @@
+//! The Firewall sub-view's rules: the list (with a two-click Remove) and the
+//! Add rule form. A rule is a catalog service, a port, or an address; the
+//! form offers only what the active manager can express.
+const std = @import("std");
+const i18n = @import("i18n");
+const ui = @import("ui");
+const fw = @import("firewall");
+const panel = @import("../panel.zig");
+const firewall = @import("firewall.zig");
+const widgets = @import("network_ui.zig");
+const fields = @import("network_fields.zig");
+const W = ui.layout.Widget;
+const Allocator = std.mem.Allocator;
+const model = fw.model;
+const text = widgets.text;
+const group = widgets.group;
+const card = widgets.card;
+const action = widgets.action;
+
+/// A catalog service's name in the user's language.
+pub fn serviceName(index: usize) []const u8 {
+ inline for (fw.services.all, 0..) |svc, i| if (i == index) return i18n.tr(svc.name);
+ return "";
+}
+
+fn catalogIndex(id: []const u8) ?usize {
+ for (fw.services.all, 0..) |svc, i| if (std.mem.eql(u8, svc.id, id)) return i;
+ return null;
+}
+
+fn actionLabel(act: model.Action) []const u8 {
+ return switch (act) {
+ .allow => i18n.tr("Allow"),
+ .deny => i18n.tr("Block"),
+ .reject => i18n.tr("Reject"),
+ .limit => i18n.tr("Allow, rate-limited"),
+ };
+}
+
+fn protoLabel(p: model.Proto) []const u8 {
+ return switch (p) {
+ .tcp => "TCP",
+ .udp => "UDP",
+ .both => "TCP/UDP",
+ };
+}
+
+/// The rule's first line: its service's name, a port, or an address.
+pub fn title(a: Allocator, rule: model.Rule) ![]const u8 {
+ if (rule.raw.len != 0 and rule.port.len == 0 and rule.service.len == 0 and rule.source.len == 0) return a.dupe(u8, rule.raw);
+ if (catalogIndex(rule.service)) |i| return a.dupe(u8, serviceName(i));
+ if (rule.service.len != 0) return a.dupe(u8, rule.service);
+ if (rule.port.len != 0) return std.fmt.allocPrint(a, "{s} {s} {s}", .{ i18n.tr("Port"), rule.port, protoLabel(rule.proto) });
+ if (rule.source.len != 0) return std.fmt.allocPrint(a, "{s} {s}", .{ i18n.tr("Address"), rule.source });
+ return a.dupe(u8, i18n.tr("All traffic"));
+}
+
+/// The rule's second line: what it does and where.
+pub fn detail(a: Allocator, rule: model.Rule) ![]const u8 {
+ var out: std.Io.Writer.Allocating = .init(a);
+ const w = &out.writer;
+ try w.print("{s} · {s}", .{ actionLabel(rule.action), if (rule.direction == .in) i18n.tr("incoming") else i18n.tr("outgoing") });
+ if (rule.service.len != 0 and rule.port.len != 0) try w.print(" · {s} {s}", .{ rule.port, protoLabel(rule.proto) });
+ if (std.mem.eql(u8, rule.source, "lan")) {
+ try w.print(" · {s}", .{i18n.tr("local network only")});
+ } else if (rule.source.len != 0 and (rule.port.len != 0 or rule.service.len != 0)) try w.print(" · {s} {s}", .{ if (rule.direction == .in) i18n.tr("from") else i18n.tr("to"), rule.source });
+ if (rule.scope == .home) try w.print(" · {s}", .{i18n.tr("home networks only")});
+ if (rule.iface.len != 0) try w.print(" · {s} {s}", .{ i18n.tr("on"), rule.iface });
+ if (rule.family != .both) try w.print(" · {s}", .{if (rule.family == .v4) "IPv4" else "IPv6"});
+ if (rule.comment.len != 0) try w.print(" · {s}", .{rule.comment});
+ if (rule.raw.len != 0) try w.print(" · {s}", .{i18n.tr("can only be removed here")});
+ return out.written();
+}
+
+pub fn rulesCard(cc: *panel.ControlCenter, a: Allocator, status: *const model.Status) !W {
+ const s = &cc.firewall;
+ var items: std.ArrayList(W) = .empty;
+ var heading = text(i18n.tr("Rules"), 16, false);
+ heading.width = .{ .flex = 1 };
+ var header: std.ArrayList(W) = .empty;
+ try header.append(a, heading);
+ if (status.capabilities.edit) {
+ var add = action(cc, "firewall_add", i18n.tr("Add rule…"), @backingInt(firewall.Id.add_open), firewall.clicked, !firewall.editable(cc) or s.adding);
+ add.kind.button.leading_icon = .plus;
+ add.width = .auto;
+ try header.append(a, add);
+ }
+ try items.append(a, try group(a, .row, header.items));
+ if (status.rules.len == 0) {
+ var buffer: [160]u8 = undefined;
+ try items.append(a, text(try a.dupe(u8, i18n.fmt(&buffer, i18n.tr("No rules. Incoming connections follow the default: {policy}."), .{ .policy = firewall.policyLabel(status.incoming) }) catch ""), 13, true));
+ }
+ for (status.rules, 0..) |rule, i| {
+ var labels = try group(a, .column, &.{ text(try title(a, rule), 14, false), text(try detail(a, rule), 12, true) });
+ labels.gap = 3;
+ labels.width = .{ .flex = 1 };
+ var row: std.ArrayList(W) = .empty;
+ try row.append(a, widgets.icon(if (rule.action == .allow or rule.action == .limit) .checkmark else .close, 18, rule.action == .allow or rule.action == .limit));
+ try row.append(a, labels);
+ if (status.capabilities.edit) {
+ const armed = s.remove_armed == i;
+ var remove = action(cc, "firewall_rule_remove", if (armed) i18n.tr("Remove?") else i18n.tr("Remove"), firewall.remove_base + i, firewall.clicked, !firewall.editable(cc));
+ remove.kind.button.variant = if (armed) .primary else .ghost;
+ remove.width = .auto;
+ try row.append(a, remove);
+ }
+ var line = try group(a, .row, row.items);
+ line.name = "firewall_rule";
+ try items.append(a, line);
+ }
+ var result = try card(a, items.items);
+ result.name = "firewall_rules";
+ return result;
+}
+
+fn kindLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Service"), i18n.msg("Port"), i18n.msg("Address") });
+}
+fn actionLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Allow"), i18n.msg("Block"), i18n.msg("Reject"), i18n.msg("Allow, rate-limited") });
+}
+fn protoLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("TCP"), i18n.msg("UDP"), i18n.msg("TCP and UDP") });
+}
+fn directionLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Incoming"), i18n.msg("Outgoing") });
+}
+fn sourceLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("Anywhere"), i18n.msg("Local network"), i18n.msg("An address") });
+}
+fn scopeLabels() []const []const u8 {
+ return panel.translatedLabels(&.{ i18n.msg("All networks"), i18n.msg("Home networks only") });
+}
+
+fn serviceLabels(a: Allocator) ![]const []const u8 {
+ const labels = try a.alloc([]const u8, fw.services.all.len);
+ for (labels, 0..) |*label, i| label.* = serviceName(i);
+ return labels;
+}
+
+fn select(cc: *panel.ControlCenter, name: []const u8, id: usize, labels: []const []const u8, selected: usize, disabled_options: []const usize) W {
+ return .{ .name = name, .kind = .{ .select = .{ .labels = labels, .selected = selected, .owner = cc, .id = id, .on_change = selectChanged, .disabled_options = disabled_options } }, .width = .{ .percent = 1 }, .height = .{ .fixed = 34 } };
+}
+
+fn selectChanged(raw: ?*anyopaque, id: usize, index: usize) void {
+ const cc = firewall.owner(raw);
+ const f = &cc.firewall.form;
+ f.fields.capture();
+ switch (id) {
+ 0 => f.kind = index,
+ 1 => {
+ f.service = index;
+ if (index < fw.services.all.len) f.scope = if (fw.services.all[index].scope == .home) 1 else 0;
+ },
+ 2 => f.rule_action = index,
+ 3 => f.proto = index,
+ 4 => f.direction = index,
+ 5 => f.source = index,
+ 6 => f.scope = index,
+ else => {},
+ }
+ cc.refresh();
+}
+
+pub fn formCard(cc: *panel.ControlCenter, a: Allocator, status: *const model.Status) !W {
+ const f = &cc.firewall.form;
+ const caps = status.capabilities;
+ var items: std.ArrayList(W) = .empty;
+ try items.append(a, text(i18n.tr("Add rule"), 16, false));
+ var first: std.ArrayList(W) = .empty;
+ try first.append(a, try fields.labeled(a, i18n.tr("Kind"), select(cc, "firewall_form_kind", 0, kindLabels(), f.kind, &.{})));
+ switch (f.kind) {
+ 0 => try first.append(a, try fields.labeled(a, i18n.tr("Service"), select(cc, "firewall_form_service", 1, try serviceLabels(a), f.service, &.{}))),
+ 1 => {
+ try first.append(a, try f.fields.input(a, .port, "firewall_form_port", i18n.tr("Port or range")));
+ try first.append(a, try fields.labeled(a, i18n.tr("Protocol"), select(cc, "firewall_form_proto", 3, protoLabels(), f.proto, &.{})));
+ },
+ else => try first.append(a, try f.fields.input(a, .address, "firewall_form_address", i18n.tr("Address or network"))),
+ }
+ for (first.items) |*w| w.width = .{ .flex = 1 };
+ var row1 = try group(a, .row, first.items);
+ row1.@"align" = .start;
+ try items.append(a, row1);
+
+ var disabled_actions: std.ArrayList(usize) = .empty;
+ if (!caps.reject) try disabled_actions.append(a, 2);
+ if (!caps.limit or f.kind == 2) try disabled_actions.append(a, 3);
+ var second: std.ArrayList(W) = .empty;
+ try second.append(a, try fields.labeled(a, i18n.tr("Action"), select(cc, "firewall_form_action", 2, actionLabels(), f.rule_action, disabled_actions.items)));
+ if (caps.outgoing_rules) try second.append(a, try fields.labeled(a, i18n.tr("Direction"), select(cc, "firewall_form_direction", 4, directionLabels(), f.direction, &.{})));
+ if (caps.sources and f.kind != 2) try second.append(a, try fields.labeled(a, if (f.direction == 0) i18n.tr("From") else i18n.tr("To"), select(cc, "firewall_form_source", 5, sourceLabels(), f.source, &.{})));
+ if (caps.trust) try second.append(a, try fields.labeled(a, i18n.tr("Where"), select(cc, "firewall_form_scope", 6, scopeLabels(), f.scope, &.{})));
+ for (second.items) |*w| w.width = .{ .flex = 1 };
+ var row2 = try group(a, .row, second.items);
+ row2.@"align" = .start;
+ try items.append(a, row2);
+ if (caps.sources and f.kind != 2 and f.source == 2) try items.append(a, try f.fields.input(a, .source, "firewall_form_source_address", i18n.tr("Address or network")));
+ try items.append(a, try f.fields.input(a, .comment, "firewall_form_comment", i18n.tr("Note")));
+ if (cc.firewall.message.len != 0) try items.append(a, text(try a.dupe(u8, cc.firewall.message), 12, true));
+ var add = action(cc, "firewall_form_add", i18n.tr("Add"), @backingInt(firewall.Id.add_submit), firewall.clicked, !firewall.editable(cc));
+ add.width = .auto;
+ var cancel = action(cc, "firewall_form_cancel", i18n.tr("Cancel"), @backingInt(firewall.Id.add_cancel), firewall.clicked, false);
+ cancel.kind.button.variant = .secondary;
+ cancel.width = .auto;
+ try items.append(a, try group(a, .row, &.{ add, cancel }));
+ var result = try card(a, items.items);
+ result.name = "firewall_form";
+ return result;
+}
+
+/// The form as a rule, or null with the reason in the section's message.
+pub fn formRule(cc: *panel.ControlCenter, status: *const model.Status) ?model.Rule {
+ const s = &cc.firewall;
+ const f = &s.form;
+ var rule: model.Rule = .{
+ .action = switch (f.rule_action) {
+ 1 => .deny,
+ 2 => .reject,
+ 3 => .limit,
+ else => .allow,
+ },
+ .direction = if (f.direction == 1 and status.capabilities.outgoing_rules) .out else .in,
+ .scope = if (f.scope == 1 and status.capabilities.trust) .home else .everywhere,
+ .comment = std.mem.trim(u8, f.fields.value(.comment), " "),
+ };
+ switch (f.kind) {
+ 0 => rule.service = fw.services.all[@min(f.service, fw.services.all.len - 1)].id,
+ 1 => {
+ rule.port = std.mem.trim(u8, f.fields.value(.port), " ");
+ rule.proto = switch (f.proto) {
+ 0 => .tcp,
+ 1 => .udp,
+ else => .both,
+ };
+ if (!fw.validate.port(rule.port) or rule.port.len == 0) {
+ s.message = i18n.tr("Enter a port from 1 to 65535, or a range like 6000-6010.");
+ return null;
+ }
+ },
+ else => {
+ rule.source = std.mem.trim(u8, f.fields.value(.address), " ");
+ if (!fw.validate.cidr(rule.source)) {
+ s.message = i18n.tr("Enter an IP address, or a network like 10.0.0.0/8.");
+ return null;
+ }
+ },
+ }
+ if (f.kind != 2 and status.capabilities.sources) {
+ if (f.source == 1) rule.source = "lan";
+ if (f.source == 2) {
+ rule.source = std.mem.trim(u8, f.fields.value(.source), " ");
+ if (!fw.validate.cidr(rule.source)) {
+ s.message = i18n.tr("Enter an IP address, or a network like 10.0.0.0/8.");
+ return null;
+ }
+ }
+ }
+ if (rule.action == .limit and rule.proto == .both and rule.port.len != 0) rule.proto = .tcp;
+ if (!fw.validate.comment(rule.comment)) {
+ s.message = i18n.tr("The note may use up to 64 plain characters, without quotes.");
+ return null;
+ }
+ if (!fw.validate.rule(rule)) {
+ s.message = i18n.tr("This rule cannot be added.");
+ return null;
+ }
+ return rule;
+}
+
+pub fn submit(cc: *panel.ControlCenter) void {
+ const status = (cc.firewall.client orelse return).status() orelse return;
+ cc.firewall.message = "";
+ const rule = formRule(cc, status) orelse return;
+ // Copy the typed strings: the fields own them and the request is
+ // serialized now, but keep them stable until then.
+ firewall.change(cc, .{ .op = .add_rule, .rule = rule });
+}
diff --git a/src/control_center/sections/keys.zig b/src/control_center/sections/keys.zig
index 8a6981c..8dc1b28 100644
--- a/src/control_center/sections/keys.zig
+++ b/src/control_center/sections/keys.zig
@@ -120,7 +120,9 @@ pub fn build(self: *Section, cc: *panel.ControlCenter) void {
const width = @max(80, @as(f32, @floatFromInt(cc.panel_box.width)) - panel.sidebarWidth(cc) - 80);
wrap(self.arena.allocator(), &self.root, width) catch {};
}
-fn wrap(a: A, widget: *W, width: f32) !void {
+/// Turns text wider than `width` into wrapped paragraphs (also used by the
+/// Firewall section).
+pub fn wrap(a: A, widget: *W, width: f32) !void {
const inner = @max(40, width - widget.padding.left - widget.padding.right);
if (widget.kind == .text and ui.measure.textNatural(widget.kind.text.content, .sans, widget.kind.text.weight, widget.kind.text.font_size).w > inner) {
const style = widget.kind.text;
diff --git a/src/control_center/sections/network.zig b/src/control_center/sections/network.zig
index f29994a..05884bf 100644
--- a/src/control_center/sections/network.zig
+++ b/src/control_center/sections/network.zig
@@ -22,6 +22,7 @@ const details = @import("network_details.zig");
const editor = @import("network_editor.zig");
const proxy_card = @import("network_proxy.zig");
const vpn_card = @import("network_vpn.zig");
+const firewall = @import("firewall.zig");
const rfkill = @import("platform").rfkill;
pub const Section = struct {
@@ -93,6 +94,8 @@ pub fn build(s: *Section, cc: *panel.ControlCenter) void {
s.name_field = null;
s.edit.capture();
s.proxy.capture();
+ cc.firewall.capture();
+ firewall.start(cc);
s.list = null;
_ = s.arena.reset(.retain_capacity);
// A service/radio change closes the form and wipes any entered secret.
@@ -115,6 +118,7 @@ pub fn build(s: *Section, cc: *panel.ControlCenter) void {
if (s.list) |list| list.kind.scroll_container = saved_scroll;
}
fn tree(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
+ if (cc.firewall.managing) return wrapped(cc, a, try firewall.view(cc, a));
const m = cc.server.network;
const available = if (m) |n| n.available else false;
const eth = if (m) |n| details.chosenEthernet(s, n) else null;
@@ -166,12 +170,21 @@ fn tree(s: *Section, cc: *panel.ControlCenter, a: Allocator) !W {
if (try airplaneRow(cc, a)) |row| try page.append(a, row);
if (m) |n| if (try accessRow(cc, a, n)) |row| try page.append(a, row);
try page.append(a, columns);
+ try page.append(a, try wrapped(cc, a, try firewall.overview(cc, a)));
if (try editor.build(cc, a)) |edit_card| try page.append(a, edit_card);
try page.append(a, try vpn_card.build(cc, a));
try page.append(a, try proxy_card.build(cc, a));
return group(a, .column, page.items);
}
+/// Wraps the firewall's long lines to the page width.
+fn wrapped(cc: *panel.ControlCenter, a: Allocator, widget: W) !W {
+ var w = widget;
+ const width = @max(80, @as(f32, @floatFromInt(cc.panel_box.width)) - panel.sidebarWidth(cc) - 80);
+ try @import("keys.zig").wrap(a, &w, width);
+ return w;
+}
+
/// Airplane mode: every radio blocked by software (`/dev/rfkill`), which
/// NetworkManager and BlueZ both follow. Hidden where there is no rfkill.
fn airplaneRow(cc: *panel.ControlCenter, a: Allocator) !?W {
diff --git a/src/control_center/tree.zig b/src/control_center/tree.zig
index ba95fce..e1febbe 100644
--- a/src/control_center/tree.zig
+++ b/src/control_center/tree.zig
@@ -68,6 +68,7 @@ pub fn buildTree(cc: *ControlCenter) void {
if (cc.page == .services) if (cc.systemd_client) |client| client.hide();
if (cc.page == .printers) cc.printers.hide();
if (cc.page == .keys) cc.key_settings.hide();
+ if (cc.page == .network) cc.firewall.hide();
if (cc.page == .bluetooth) if (cc.server.bluetooth) |manager| manager.closed();
} else {
cc.search.restore_scroll = true;
diff --git a/src/firewall/AGENTS.md b/src/firewall/AGENTS.md
new file mode 100644
index 0000000..7f229c0
--- /dev/null
+++ b/src/firewall/AGENTS.md
@@ -0,0 +1,47 @@
+# Firewall (`firewall/`, `firewall_helper/`, `firewall_main.zig`)
+
+Plan and decisions: `docs/plans/firewall.md`. Settings side:
+`control_center/sections/firewall*.zig` (notes in `src/control_center/AGENTS.md`).
+
+* **`firewall/` is the shared module** (std only): the model Settings draws,
+ the request protocol, validation, and pure parsers/renderers per manager
+ (`ufw.zig`, `firewalld.zig`, `own.zig` for our nftables table and pf anchor,
+ `inventory.zig`, `sockets.zig`, `blocks.zig`). Test them with
+ `zig build test-firewall`; nothing here runs a tool.
+* **`rediwm-firewall-helper` runs as root under pkexec** and is the only code
+ that runs tools or writes system files. `read` (status, recent blocks) and
+ `manage` (everything) are separate polkit actions, chosen by argv1
+ (`data/org.rediwm.firewall.policy`); the helper refuses a change in `read`
+ mode. `sync` re-applies our saved rules (boot unit, NetworkManager
+ dispatcher). Requests are untrusted: every field passes `validate.zig`
+ before a renderer or argv sees it, which is why renderers never escape.
+ Removals use `validate.removal` (port lists, a manager's own `raw` text,
+ matched against its listing).
+* **Tools come from system directories only** (`run.tool`), run with a fixed
+ C-locale environment (`run.environment`), never a shell. Failures reach the
+ page as fixed words (`failure` in `firewall_main.zig`), never tool output.
+* **One manager at a time.** nftables base chains stack, so our table cannot
+ open what ufw or RediOS drops. `linux.zig` detects our table, firewalld,
+ ufw and RediOS; edits go through whichever manages, and nothing is editable
+ while two are active. Our own table (`inet rediwm`) and pf anchor
+ (`rediwm`) are written only by us; other tables, pf.conf rules and ipfw
+ are read-only. pf.conf is changed only to add the anchor (backup kept) or,
+ when missing, written from `own.pf_conf`.
+* **Trust** is a connection's NetworkManager zone (`networks.zig`): firewalld
+ follows it natively; our table's `home_ifaces` set is filled by `sync`
+ (dispatcher). Without NetworkManager (FreeBSD) trust is per interface in our
+ state.
+* **Revert**: a change with `revert_after` forks a detached watchdog
+ (`state.arm`) that applies the computed undo unless `confirm` stops it. It
+ closes stdio so Settings' pipe ends now. Lockdown is a separate
+ `inet rediwm_lockdown` table (priority -200), runtime only.
+* **State files** are root-only: `${sysconfdir}/rediwm/firewall.json` (ours;
+ re-validated on load), rendered `firewall.nft` / `pf.rediwm.conf`, run state
+ under `${rundir}/rediwm-firewall`. Use `install_paths`, never literals; the
+ systemd unit and dispatcher paths are third-party locations and literal.
+* **Tests never touch the host firewall**: `tests/firewall_helper.py` runs the
+ real helper as namespace root in `unshare -rmn` with config/run dirs on
+ tmpfs and nmcli/systemctl/ufw/firewall-cmd hidden;
+ `tests/firewall_settings.py` drives Settings with a fake pkexec
+ (`tests/fixtures/firewall_pkexec.sh`) and fake helper. pf is checked on the
+ FreeBSD VM (`pfctl -nf`).
diff --git a/src/firewall/blocks.zig b/src/firewall/blocks.zig
new file mode 100644
index 0000000..beec35f
--- /dev/null
+++ b/src/firewall/blocks.zig
@@ -0,0 +1,112 @@
+//! Recent blocked connections, from the kernel log lines our table, ufw and
+//! firewalld write (Linux, via `journalctl -k`) or from pflog (FreeBSD, via
+//! `tcpdump -r`). Shown on request only; nothing follows the log.
+const std = @import("std");
+const model = @import("model.zig");
+const Allocator = std.mem.Allocator;
+
+pub const max_blocks = 100;
+
+/// The `-g` pattern for journalctl: our prefix, ufw's and firewalld's.
+pub const journal_pattern = "rediwm-drop|UFW BLOCK|UFW LIMIT BLOCK|_REJECT: |_DROP: |FINAL_REJECT";
+
+fn field(line: []const u8, key: []const u8) []const u8 {
+ var start: usize = 0;
+ while (std.mem.indexOfPos(u8, line, start, key)) |i| {
+ if (i == 0 or line[i - 1] == ' ') {
+ const begin = i + key.len;
+ const end = std.mem.indexOfScalarPos(u8, line, begin, ' ') orelse line.len;
+ return line[begin..end];
+ }
+ start = i + key.len;
+ }
+ return "";
+}
+
+/// One `journalctl -k -o short-iso` line: "2026-11-17T10:00:00+0100 host
+/// kernel: rediwm-drop IN=wlan0 OUT= … SRC=… DST=… PROTO=TCP SPT=… DPT=22".
+pub fn parseKernel(line: []const u8) ?model.Block {
+ const time_end = std.mem.indexOfScalar(u8, line, ' ') orelse return null;
+ const in = field(line, "IN=");
+ const out = field(line, "OUT=");
+ const src = field(line, "SRC=");
+ if (src.len == 0) return null;
+ return .{
+ .time = line[0..time_end],
+ .direction = if (in.len == 0 and out.len != 0) .out else .in,
+ .proto = field(line, "PROTO="),
+ .source = if (in.len == 0 and out.len != 0) field(line, "DST=") else src,
+ .port = std.fmt.parseInt(u16, field(line, "DPT="), 10) catch 0,
+ .iface = if (in.len != 0) in else out,
+ };
+}
+
+fn splitHostPort(text: []const u8) struct { host: []const u8, port: u16 } {
+ const trimmed = std.mem.trimEnd(u8, text, ":,");
+ const dot = std.mem.lastIndexOfScalar(u8, trimmed, '.') orelse return .{ .host = trimmed, .port = 0 };
+ const port = std.fmt.parseInt(u16, trimmed[dot + 1 ..], 10) catch return .{ .host = trimmed, .port = 0 };
+ return .{ .host = trimmed[0..dot], .port = port };
+}
+
+/// One `tcpdump -n -e -tttt -r /var/log/pflog` line: "2026-11-17
+/// 10:00:00.123456 rule 3/0(match): block in on em0: 192.0.2.5.51234 >
+/// 192.0.2.10.22: Flags [S], …".
+pub fn parsePflog(line: []const u8) ?model.Block {
+ const marker = std.mem.indexOf(u8, line, "(match): block ") orelse return null;
+ const first_space = std.mem.indexOfScalar(u8, line, ' ') orelse return null;
+ const second_space = std.mem.indexOfScalarPos(u8, line, first_space + 1, ' ') orelse return null;
+ var rest = line[marker + "(match): block ".len ..];
+ const out = std.mem.startsWith(u8, rest, "out");
+ const on = std.mem.indexOf(u8, rest, " on ") orelse return null;
+ const iface_end = std.mem.indexOfScalarPos(u8, rest, on + 4, ':') orelse return null;
+ const iface = rest[on + 4 .. iface_end];
+ rest = std.mem.trimStart(u8, rest[iface_end + 1 ..], " ");
+ const gt = std.mem.indexOf(u8, rest, " > ") orelse return null;
+ const src = splitHostPort(rest[0..gt]);
+ const dst_end = std.mem.indexOfScalarPos(u8, rest, gt + 3, ' ') orelse rest.len;
+ const dst = splitHostPort(rest[gt + 3 .. dst_end]);
+ const tail = rest[dst_end..];
+ const proto: []const u8 = if (std.mem.indexOf(u8, tail, "Flags [") != null) "TCP" else if (std.mem.indexOf(u8, tail, "UDP") != null) "UDP" else if (std.mem.indexOf(u8, tail, "ICMP") != null) "ICMP" else "";
+ return .{
+ .time = line[0..second_space],
+ .direction = if (out) .out else .in,
+ .proto = proto,
+ .source = if (out) dst.host else src.host,
+ .port = dst.port,
+ .iface = iface,
+ };
+}
+
+/// The newest `max_blocks` blocks, newest first.
+pub fn parse(a: Allocator, text: []const u8, pflog: bool) ![]model.Block {
+ var list: std.ArrayList(model.Block) = .empty;
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |line| {
+ const block = (if (pflog) parsePflog(line) else parseKernel(line)) orelse continue;
+ try list.append(a, block);
+ }
+ std.mem.reverse(model.Block, list.items);
+ if (list.items.len > max_blocks) list.shrinkRetainingCapacity(max_blocks);
+ return list.toOwnedSlice(a);
+}
+
+test "kernel log" {
+ const b = parseKernel("2026-11-17T10:00:00+0100 laptop kernel: rediwm-drop IN=wlan0 OUT= MAC=aa:bb SRC=192.0.2.5 DST=192.0.2.10 LEN=60 TOS=0x00 PROTO=TCP SPT=51234 DPT=22 WINDOW=64240 SYN").?;
+ try std.testing.expectEqualStrings("192.0.2.5", b.source);
+ try std.testing.expectEqual(@as(u16, 22), b.port);
+ try std.testing.expectEqualStrings("wlan0", b.iface);
+ try std.testing.expectEqualStrings("TCP", b.proto);
+ try std.testing.expectEqual(model.Direction.in, b.direction);
+ const ufw = parseKernel("2026-11-17T10:00:01+0100 laptop kernel: [UFW BLOCK] IN=eth0 OUT= SRC=198.51.100.7 DST=192.0.2.10 PROTO=UDP SPT=5353 DPT=5353").?;
+ try std.testing.expectEqual(@as(u16, 5353), ufw.port);
+ try std.testing.expect(parseKernel("2026-11-17T10:00:01+0100 laptop kernel: usb 1-1: new device") == null);
+}
+
+test "pflog" {
+ const b = parsePflog("2026-11-17 10:00:00.123456 rule 3/0(match): block in on em0: 192.0.2.5.51234 > 192.0.2.10.22: Flags [S], seq 1, win 65535").?;
+ try std.testing.expectEqualStrings("192.0.2.5", b.source);
+ try std.testing.expectEqual(@as(u16, 22), b.port);
+ try std.testing.expectEqualStrings("em0", b.iface);
+ try std.testing.expectEqualStrings("TCP", b.proto);
+ try std.testing.expectEqualStrings("2026-11-17 10:00:00.123456", b.time);
+}
diff --git a/src/firewall/firewalld.zig b/src/firewall/firewalld.zig
new file mode 100644
index 0000000..518c65a
--- /dev/null
+++ b/src/firewall/firewalld.zig
@@ -0,0 +1,344 @@
+//! firewalld through `firewall-cmd`, which the helper runs as root: the zone
+//! listing (`--list-all`), the active zones and service definitions (their
+//! XML), and the rich rules we write for what plain services and ports cannot
+//! say (a source, a block, a rate limit). Our two trust levels map to two
+//! zones: the default zone (Public) and `home`. A rule "everywhere" is in
+//! both.
+const std = @import("std");
+const model = @import("model.zig");
+const services = @import("services.zig");
+const Allocator = std.mem.Allocator;
+
+pub const home_zone = "home";
+pub const service_dirs = [_][]const u8{ "/etc/firewalld/services", "/usr/lib/firewalld/services" };
+
+pub const Zone = struct {
+ name: []const u8 = "",
+ target: []const u8 = "default",
+ services: []const []const u8 = &.{},
+ ports: []const []const u8 = &.{},
+ interfaces: []const []const u8 = &.{},
+ icmp_blocks: []const []const u8 = &.{},
+ icmp_inversion: bool = false,
+ rich: []const []const u8 = &.{},
+};
+
+fn words(a: Allocator, text: []const u8) ![]const []const u8 {
+ var list: std.ArrayList([]const u8) = .empty;
+ var it = std.mem.tokenizeAny(u8, text, " \t");
+ while (it.next()) |word| try list.append(a, word);
+ return list.toOwnedSlice(a);
+}
+
+/// `firewall-cmd --zone=Z --list-all`.
+pub fn parseZone(a: Allocator, text: []const u8) !Zone {
+ var zone: Zone = .{};
+ var rich: std.ArrayList([]const u8) = .empty;
+ var in_rich = false;
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trimEnd(u8, raw, " \r");
+ if (line.len == 0) continue;
+ if (line[0] != ' ' and line[0] != '\t') {
+ zone.name = if (std.mem.indexOfScalar(u8, line, ' ')) |i| line[0..i] else line;
+ continue;
+ }
+ const trimmed = std.mem.trim(u8, line, " \t");
+ if (in_rich and std.mem.startsWith(u8, trimmed, "rule ")) {
+ try rich.append(a, trimmed);
+ continue;
+ }
+ in_rich = false;
+ const colon = std.mem.indexOfScalar(u8, trimmed, ':') orelse continue;
+ const key = trimmed[0..colon];
+ const rest = std.mem.trim(u8, trimmed[colon + 1 ..], " \t");
+ if (std.mem.eql(u8, key, "target")) zone.target = rest;
+ if (std.mem.eql(u8, key, "services")) zone.services = try words(a, rest);
+ if (std.mem.eql(u8, key, "ports")) zone.ports = try words(a, rest);
+ if (std.mem.eql(u8, key, "interfaces")) zone.interfaces = try words(a, rest);
+ if (std.mem.eql(u8, key, "icmp-blocks")) zone.icmp_blocks = try words(a, rest);
+ if (std.mem.eql(u8, key, "icmp-block-inversion")) zone.icmp_inversion = std.mem.eql(u8, rest, "yes");
+ if (std.mem.eql(u8, key, "rich rules")) {
+ in_rich = true;
+ if (rest.len != 0) try rich.append(a, rest);
+ }
+ }
+ zone.rich = try rich.toOwnedSlice(a);
+ return zone;
+}
+
+pub const Active = struct { zone: []const u8, iface: []const u8 };
+
+/// `firewall-cmd --get-active-zones`: zone lines, then indented
+/// "interfaces: a b" (a zone line may carry " (default)").
+pub fn parseActive(a: Allocator, text: []const u8) ![]Active {
+ var list: std.ArrayList(Active) = .empty;
+ var zone: []const u8 = "";
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trimEnd(u8, raw, " \r");
+ if (line.len == 0) continue;
+ if (line[0] != ' ' and line[0] != '\t') {
+ zone = if (std.mem.indexOfScalar(u8, line, ' ')) |i| line[0..i] else line;
+ continue;
+ }
+ const trimmed = std.mem.trim(u8, line, " \t");
+ if (!std.mem.startsWith(u8, trimmed, "interfaces:")) continue;
+ var it = std.mem.tokenizeAny(u8, trimmed["interfaces:".len..], " \t");
+ while (it.next()) |iface| try list.append(a, .{ .zone = zone, .iface = iface });
+ }
+ return list.toOwnedSlice(a);
+}
+
+/// Ports of a service definition: each `<port protocol="tcp" port="22"/>`.
+pub fn servicePorts(a: Allocator, xml: []const u8) ![]services.Port {
+ var list: std.ArrayList(services.Port) = .empty;
+ var rest = xml;
+ while (std.mem.indexOf(u8, rest, "<port ")) |start| {
+ const end = std.mem.indexOfScalarPos(u8, rest, start, '>') orelse break;
+ const tag = rest[start..end];
+ rest = rest[end..];
+ const port = attribute(tag, "port") orelse continue;
+ const proto = attribute(tag, "protocol") orelse continue;
+ try list.append(a, .{ .proto = if (std.mem.eql(u8, proto, "udp")) .udp else .tcp, .port = port });
+ }
+ return list.toOwnedSlice(a);
+}
+
+fn attribute(tag: []const u8, name: []const u8) ?[]const u8 {
+ var buffer: [32]u8 = undefined;
+ const needle = std.fmt.bufPrint(&buffer, " {s}=\"", .{name}) catch return null;
+ const i = std.mem.indexOf(u8, tag, needle) orelse return null;
+ const start = i + needle.len;
+ const end = std.mem.indexOfScalarPos(u8, tag, start, '"') orelse return null;
+ return tag[start..end];
+}
+
+fn portRule(entry: []const u8) ?model.Rule {
+ const slash = std.mem.indexOfScalar(u8, entry, '/') orelse return null;
+ const proto = entry[slash + 1 ..];
+ return .{ .port = entry[0..slash], .proto = if (std.mem.eql(u8, proto, "tcp")) .tcp else if (std.mem.eql(u8, proto, "udp")) .udp else return null };
+}
+
+/// A rich rule we can show as a plain rule; anything else stays `raw`.
+pub fn parseRich(a: Allocator, text: []const u8) model.Rule {
+ var rule: model.Rule = .{ .raw = text };
+ if (attribute(text, "family")) |family| rule.family = if (std.mem.eql(u8, family, "ipv6")) .v6 else .v4;
+ if (std.mem.indexOf(u8, text, "source address=\"")) |_| {
+ if (attribute(text, "address")) |address| rule.source = address;
+ }
+ if (std.mem.indexOf(u8, text, " service name=\"") != null) {
+ if (attribute(text, "name")) |name| rule.service = name;
+ } else if (std.mem.indexOf(u8, text, " port port=\"") != null) {
+ if (attribute(text, "port")) |port| rule.port = port;
+ if (attribute(text, "protocol")) |proto| rule.proto = if (std.mem.eql(u8, proto, "udp")) .udp else .tcp;
+ }
+ if (std.mem.endsWith(u8, text, " drop")) rule.action = .deny else if (std.mem.endsWith(u8, text, " reject")) rule.action = .reject else if (std.mem.indexOf(u8, text, " accept limit ") != null) rule.action = .limit;
+ if (std.mem.indexOf(u8, text, " not ") != null or std.mem.indexOf(u8, text, " log") != null or std.mem.indexOf(u8, text, " destination ") != null) return rule;
+ _ = a;
+ return rule;
+}
+
+/// The page's rules for the two zones: a service, port or rich rule in both
+/// is "everywhere", one only in `home` is home-only.
+pub fn rules(a: Allocator, public: Zone, home: ?Zone) ![]model.Rule {
+ var list: std.ArrayList(model.Rule) = .empty;
+ const zones = [_]?Zone{ public, home };
+ for (zones, 0..) |maybe, zi| {
+ const zone = maybe orelse continue;
+ const in_home = zi == 1;
+ for (zone.services) |name| {
+ if (in_home and contains(public.services, name)) continue;
+ var rule: model.Rule = .{ .service = name, .scope = if (in_home) .home else .everywhere };
+ if (services.find(name)) |s| if (s.ports.len == 1) {
+ rule.port = s.ports[0].port;
+ rule.proto = s.ports[0].proto;
+ };
+ try list.append(a, rule);
+ }
+ for (zone.ports) |entry| {
+ if (in_home and contains(public.ports, entry)) continue;
+ var rule = portRule(entry) orelse continue;
+ rule.scope = if (in_home) .home else .everywhere;
+ if (services.named(rule.proto, rule.port)) |s| rule.service = s.id;
+ try list.append(a, rule);
+ }
+ for (zone.rich) |text| {
+ if (in_home and contains(public.rich, text)) continue;
+ var rule = parseRich(a, text);
+ rule.scope = if (in_home) .home else .everywhere;
+ try list.append(a, rule);
+ }
+ }
+ for (list.items, 0..) |*rule, i| rule.id = @intCast(i);
+ return list.toOwnedSlice(a);
+}
+
+fn contains(list: []const []const u8, item: []const u8) bool {
+ for (list) |x| if (std.mem.eql(u8, x, item)) return true;
+ return false;
+}
+
+pub fn incoming(zone_target: []const u8) model.Policy {
+ if (std.mem.eql(u8, zone_target, "ACCEPT")) return .accept;
+ if (std.mem.eql(u8, zone_target, "DROP")) return .drop;
+ return .reject;
+}
+
+pub fn target(p: model.Policy) []const u8 {
+ return switch (p) {
+ .accept => "ACCEPT",
+ .drop => "DROP",
+ .reject => "default",
+ };
+}
+
+pub fn pingAllowed(zone: Zone) bool {
+ const blocked = contains(zone.icmp_blocks, "echo-request");
+ return if (zone.icmp_inversion) blocked else !blocked;
+}
+
+pub fn logging(word: []const u8) model.Logging {
+ const w = std.mem.trim(u8, word, " \n");
+ if (std.mem.eql(u8, w, "off") or w.len == 0) return .off;
+ if (std.mem.eql(u8, w, "all")) return .high;
+ if (std.mem.eql(u8, w, "unicast")) return .low;
+ return .medium;
+}
+
+pub fn logWord(level: model.Logging) []const u8 {
+ return switch (level) {
+ .off => "off",
+ .low => "unicast",
+ .medium => "broadcast",
+ .high => "all",
+ };
+}
+
+const lan4 = [_][]const u8{ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16" };
+const lan6 = [_][]const u8{ "fc00::/7", "fe80::/10" };
+
+/// The `firewall-cmd` arguments (without --zone/--permanent) that add `rule`
+/// (or remove it, `delete`). Plain services and ports where possible, rich
+/// rules for sources, blocks and limits.
+pub fn arguments(a: Allocator, rule: model.Rule, delete: bool) ![]const []const u8 {
+ var out: std.ArrayList([]const u8) = .empty;
+ const verb = if (delete) "remove" else "add";
+ if (rule.raw.len != 0) {
+ try out.append(a, try std.fmt.allocPrint(a, "--{s}-rich-rule={s}", .{ verb, rule.raw }));
+ return out.toOwnedSlice(a);
+ }
+ const plain = rule.source.len == 0 and rule.action == .allow and rule.family == .both and rule.direction == .in and rule.iface.len == 0;
+ const catalog = services.find(rule.service);
+ const fw_name: []const u8 = if (catalog) |s| s.firewalld orelse s.id else rule.service;
+ if (plain and rule.port.len == 0 and fw_name.len != 0) {
+ try out.append(a, try std.fmt.allocPrint(a, "--{s}-service={s}", .{ verb, fw_name }));
+ return out.toOwnedSlice(a);
+ }
+ var buffer: [8]services.Port = undefined;
+ const ports = @import("own.zig").expand(rule, &buffer);
+ if (plain) {
+ for (ports) |p| {
+ const protos: []const []const u8 = switch (p.proto) {
+ .tcp => &.{"tcp"},
+ .udp => &.{"udp"},
+ .both => &.{ "tcp", "udp" },
+ };
+ for (protos) |proto| try out.append(a, try std.fmt.allocPrint(a, "--{s}-port={s}/{s}", .{ verb, p.port, proto }));
+ }
+ return out.toOwnedSlice(a);
+ }
+ const sources: []const []const u8 = if (std.mem.eql(u8, rule.source, "lan")) &(lan4 ++ lan6) else &.{rule.source};
+ for (sources) |src| {
+ const v6 = std.mem.indexOfScalar(u8, src, ':') != null;
+ if (rule.family == .v4 and v6) continue;
+ if (rule.family == .v6 and src.len != 0 and !v6) continue;
+ for (ports) |p| {
+ const protos: []const []const u8 = switch (p.proto) {
+ .tcp => &.{"tcp"},
+ .udp => &.{"udp"},
+ .both => if (p.port.len != 0) &.{ "tcp", "udp" } else &.{""},
+ };
+ for (protos) |proto| {
+ var text: std.Io.Writer.Allocating = .init(a);
+ const w = &text.writer;
+ try w.writeAll("rule");
+ if (src.len != 0) {
+ try w.print(" family=\"{s}\" source address=\"{s}\"", .{ if (v6) "ipv6" else "ipv4", src });
+ } else if (rule.family != .both) try w.print(" family=\"{s}\"", .{if (rule.family == .v6) "ipv6" else "ipv4"});
+ if (p.port.len != 0) {
+ try w.print(" port port=\"{s}\" protocol=\"{s}\"", .{ p.port, proto });
+ } else if (proto.len != 0) try w.print(" protocol value=\"{s}\"", .{proto});
+ try w.writeAll(switch (rule.action) {
+ .allow => " accept",
+ .limit => " accept limit value=\"6/m\"",
+ .deny => " drop",
+ .reject => " reject",
+ });
+ try out.append(a, try std.fmt.allocPrint(a, "--{s}-rich-rule={s}", .{ verb, text.written() }));
+ }
+ }
+ }
+ return out.toOwnedSlice(a);
+}
+
+test "zone listing" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const text =
+ \\public (default, active)
+ \\ target: default
+ \\ icmp-block-inversion: no
+ \\ interfaces: wlan0
+ \\ sources:
+ \\ services: dhcpv6-client mdns ssh
+ \\ ports: 8080/tcp 1714-1764/udp
+ \\ protocols:
+ \\ forward: yes
+ \\ masquerade: no
+ \\ icmp-blocks: echo-request
+ \\ rich rules:
+ \\ rule family="ipv4" source address="203.0.113.9" drop
+ \\ rule family="ipv4" source address="10.0.0.0/8" port port="22" protocol="tcp" accept
+ \\
+ ;
+ const zone = try parseZone(a, text);
+ try std.testing.expectEqualStrings("public", zone.name);
+ try std.testing.expectEqual(@as(usize, 3), zone.services.len);
+ try std.testing.expectEqual(@as(usize, 2), zone.rich.len);
+ try std.testing.expect(!pingAllowed(zone));
+ try std.testing.expectEqual(model.Policy.reject, incoming(zone.target));
+ const home_text = "home\n target: default\n services: mdns ssh kdeconnect\n ports: \n";
+ const home = try parseZone(a, home_text);
+ const list = try rules(a, zone, home);
+ try std.testing.expectEqual(@as(usize, 8), list.len);
+ try std.testing.expectEqualStrings("kdeconnect", list[7].service);
+ try std.testing.expectEqual(model.Scope.home, list[7].scope);
+ try std.testing.expectEqual(model.Action.deny, list[5].action);
+ try std.testing.expectEqualStrings("203.0.113.9", list[5].source);
+ try std.testing.expectEqualStrings("22", list[6].port);
+}
+
+test "active zones and services" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const active = try parseActive(a, "home\n interfaces: eth0\npublic (default)\n interfaces: wlan0 wwan0\n");
+ try std.testing.expectEqual(@as(usize, 3), active.len);
+ try std.testing.expectEqualStrings("public", active[2].zone);
+ const ports = try servicePorts(a, "<service><short>SSH</short><port protocol=\"tcp\" port=\"22\"/></service>");
+ try std.testing.expectEqualStrings("22", ports[0].port);
+}
+
+test "arguments" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try std.testing.expectEqualStrings("--add-service=ssh", (try arguments(a, .{ .service = "ssh" }, false))[0]);
+ try std.testing.expectEqualStrings("--remove-port=8080/tcp", (try arguments(a, .{ .port = "8080", .proto = .tcp }, true))[0]);
+ const deny = try arguments(a, .{ .source = "203.0.113.9", .action = .deny }, false);
+ try std.testing.expectEqualStrings("--add-rich-rule=rule family=\"ipv4\" source address=\"203.0.113.9\" drop", deny[0]);
+ const lan = try arguments(a, .{ .port = "22", .proto = .tcp, .source = "lan" }, false);
+ try std.testing.expectEqual(@as(usize, 6), lan.len);
+}
diff --git a/src/firewall/inventory.zig b/src/firewall/inventory.zig
new file mode 100644
index 0000000..94b6702
--- /dev/null
+++ b/src/firewall/inventory.zig
@@ -0,0 +1,159 @@
+//! What else is loaded: the tables in `nft -j list ruleset` (Linux) and the
+//! pf and ipfw state (FreeBSD), named after the program that probably owns
+//! them, so the page can list rules it will not touch and detect which
+//! manager is active.
+const std = @import("std");
+const model = @import("model.zig");
+const own = @import("own.zig");
+const Allocator = std.mem.Allocator;
+
+pub const Table = struct {
+ family: []const u8,
+ name: []const u8,
+ rules: u32 = 0,
+ /// Chain names, for guessing the owner (iptables-nft keeps tables named
+ /// "filter" whose chains say who made them: ufw-*, DOCKER, ts-*).
+ chains: []const []const u8 = &.{},
+};
+
+/// Tables with their chains and rule counts, from `nft -j list ruleset`.
+pub fn parseNft(a: Allocator, json: []const u8) ![]Table {
+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, json, .{});
+ const items = switch (parsed) {
+ .object => |o| (o.get("nftables") orelse return &.{}).array.items,
+ else => return &.{},
+ };
+ var tables: std.ArrayList(Table) = .empty;
+ var chains: std.ArrayList(std.ArrayList([]const u8)) = .empty;
+ for (items) |item| {
+ if (item != .object) continue;
+ const obj = item.object;
+ if (obj.get("table")) |t| {
+ const family = stringField(t, "family") orelse continue;
+ const name = stringField(t, "name") orelse continue;
+ try tables.append(a, .{ .family = family, .name = name });
+ try chains.append(a, .empty);
+ } else if (obj.get("chain")) |c| {
+ const i = find(tables.items, stringField(c, "family"), stringField(c, "table")) orelse continue;
+ if (stringField(c, "name")) |name| try chains.items[i].append(a, name);
+ } else if (obj.get("rule")) |r| {
+ const i = find(tables.items, stringField(r, "family"), stringField(r, "table")) orelse continue;
+ tables.items[i].rules += 1;
+ }
+ }
+ for (tables.items, chains.items) |*t, *c| t.chains = try c.toOwnedSlice(a);
+ return tables.toOwnedSlice(a);
+}
+
+fn stringField(v: std.json.Value, key: []const u8) ?[]const u8 {
+ if (v != .object) return null;
+ const field = v.object.get(key) orelse return null;
+ return if (field == .string) field.string else null;
+}
+
+fn find(tables: []const Table, family: ?[]const u8, name: ?[]const u8) ?usize {
+ const f = family orelse return null;
+ const n = name orelse return null;
+ for (tables, 0..) |t, i| if (std.mem.eql(u8, t.family, f) and std.mem.eql(u8, t.name, n)) return i;
+ return null;
+}
+
+fn anyChain(t: Table, prefix: []const u8) bool {
+ for (t.chains) |c| if (std.mem.startsWith(u8, c, prefix)) return true;
+ return false;
+}
+
+/// Who probably owns a table, in words for the page ("Docker", "ufw").
+pub fn owner(t: Table) []const u8 {
+ if (std.mem.eql(u8, t.name, own.table) or std.mem.eql(u8, t.name, own.lockdown_table)) return "RediWM";
+ if (std.mem.eql(u8, t.name, "firewalld")) return "firewalld";
+ if (std.mem.eql(u8, t.name, "redi")) return "RediOS";
+ if (std.mem.startsWith(u8, t.name, "libvirt")) return "libvirt";
+ if (std.mem.startsWith(u8, t.name, "nm-shared") or std.mem.startsWith(u8, t.name, "nm-")) return "NetworkManager";
+ if (std.mem.eql(u8, t.name, "netavark") or std.mem.startsWith(u8, t.name, "podman")) return "Podman";
+ if (std.mem.startsWith(u8, t.name, "wg-quick")) return "WireGuard";
+ if (std.mem.eql(u8, t.name, "incus") or std.mem.eql(u8, t.name, "lxd")) return "Incus";
+ if (std.mem.eql(u8, t.name, "tailscale") or anyChain(t, "ts-")) return "Tailscale";
+ if (anyChain(t, "ufw")) return "ufw";
+ if (anyChain(t, "DOCKER")) return "Docker";
+ if (anyChain(t, "LIBVIRT")) return "libvirt";
+ if (anyChain(t, "f2b-")) return "fail2ban";
+ return "";
+}
+
+pub fn hasTable(tables: []const Table, name: []const u8) bool {
+ for (tables) |t| if (std.mem.eql(u8, t.name, name)) return true;
+ return false;
+}
+
+pub fn hasOwner(tables: []const Table, who: []const u8) bool {
+ for (tables) |t| if (std.mem.eql(u8, owner(t), who) and t.rules > 0) return true;
+ return false;
+}
+
+/// Tables the page lists as other programs' rules: everything except ours and
+/// the manager's own. Empty iptables-nft shells ("filter" with no rules) are
+/// left out.
+pub fn foreign(a: Allocator, tables: []const Table, manager: []const u8) ![]model.Foreign {
+ var list: std.ArrayList(model.Foreign) = .empty;
+ for (tables) |t| {
+ const who = owner(t);
+ if (std.mem.eql(u8, who, "RediWM")) continue;
+ if (manager.len != 0 and std.mem.eql(u8, who, manager)) continue;
+ if (t.rules == 0) continue;
+ try list.append(a, .{ .owner = if (who.len != 0) who else "", .name = try std.fmt.allocPrint(a, "{s} {s}", .{ t.family, t.name }), .rules = t.rules });
+ }
+ return list.toOwnedSlice(a);
+}
+
+/// `pfctl -s info`: "Status: Enabled for …" or "Status: Disabled".
+pub fn pfEnabled(info: []const u8) bool {
+ return std.mem.indexOf(u8, info, "Status: Enabled") != null;
+}
+
+/// Rule lines in `pfctl -sr` output, not counting our anchor's own line.
+pub fn pfRuleCount(rules: []const u8) u32 {
+ var count: u32 = 0;
+ var lines = std.mem.splitScalar(u8, rules, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0 or line[0] == '#') continue;
+ if (std.mem.startsWith(u8, line, "anchor \"rediwm\"")) continue;
+ if (std.mem.startsWith(u8, line, "@")) continue;
+ count += 1;
+ }
+ return count;
+}
+
+test "nft tables and owners" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const json =
+ \\{"nftables": [{"metainfo": {"version": "1.1.7"}},
+ \\ {"table": {"family": "ip", "name": "filter", "handle": 1}},
+ \\ {"chain": {"family": "ip", "table": "filter", "name": "ufw-user-input", "handle": 2}},
+ \\ {"rule": {"family": "ip", "table": "filter", "chain": "ufw-user-input", "handle": 3, "expr": []}},
+ \\ {"table": {"family": "ip", "name": "nat", "handle": 4}},
+ \\ {"chain": {"family": "ip", "table": "nat", "name": "DOCKER", "handle": 5}},
+ \\ {"rule": {"family": "ip", "table": "nat", "chain": "DOCKER", "handle": 6, "expr": []}},
+ \\ {"rule": {"family": "ip", "table": "nat", "chain": "DOCKER", "handle": 7, "expr": []}},
+ \\ {"table": {"family": "inet", "name": "rediwm", "handle": 8}}
+ \\]}
+ ;
+ const tables = try parseNft(a, json);
+ try std.testing.expectEqual(@as(usize, 3), tables.len);
+ try std.testing.expectEqualStrings("ufw", owner(tables[0]));
+ try std.testing.expectEqualStrings("Docker", owner(tables[1]));
+ try std.testing.expectEqual(@as(u32, 2), tables[1].rules);
+ try std.testing.expect(hasTable(tables, "rediwm"));
+ const others = try foreign(a, tables, "ufw");
+ try std.testing.expectEqual(@as(usize, 1), others.len);
+ try std.testing.expectEqualStrings("Docker", others[0].owner);
+}
+
+test "pf" {
+ try std.testing.expect(pfEnabled("Status: Enabled for 0 days 00:10:02 Debug: Urgent\n"));
+ try std.testing.expect(!pfEnabled("Status: Disabled for 0 days"));
+ try std.testing.expectEqual(@as(u32, 2), pfRuleCount("scrub in all fragment reassemble\nanchor \"rediwm\" all\nblock drop in all\n"));
+}
diff --git a/src/firewall/mod.zig b/src/firewall/mod.zig
new file mode 100644
index 0000000..3c5e70d
--- /dev/null
+++ b/src/firewall/mod.zig
@@ -0,0 +1,25 @@
+//! Firewall settings shared by Settings and `rediwm-firewall-helper`: the
+//! model, the request protocol, validation, and the parsers and renderers for
+//! each manager. Std only; no compositor imports. See docs/plans/firewall.md.
+pub const model = @import("model.zig");
+pub const protocol = @import("protocol.zig");
+pub const validate = @import("validate.zig");
+pub const services = @import("services.zig");
+pub const own = @import("own.zig");
+pub const ufw = @import("ufw.zig");
+pub const firewalld = @import("firewalld.zig");
+pub const inventory = @import("inventory.zig");
+pub const sockets = @import("sockets.zig");
+pub const blocks = @import("blocks.zig");
+
+test {
+ _ = model;
+ _ = validate;
+ _ = services;
+ _ = ufw;
+ _ = firewalld;
+ _ = inventory;
+ _ = sockets;
+ _ = blocks;
+ _ = @import("own_tests.zig");
+}
diff --git a/src/firewall/model.zig b/src/firewall/model.zig
new file mode 100644
index 0000000..3954122
--- /dev/null
+++ b/src/firewall/model.zig
@@ -0,0 +1,236 @@
+//! The firewall as Settings shows it, whatever program manages it. The helper
+//! fills it from ufw, firewalld, our own nftables table or our pf anchor and
+//! sends it as JSON; the page draws only from it. No compositor imports.
+const std = @import("std");
+
+pub const max_reply = 4 << 20;
+pub const max_request = 16 << 10;
+pub const max_rules = 512;
+
+/// Who manages the firewall. `own` is our nftables table (Linux) or pf anchor
+/// (FreeBSD); `redi` is RediOS's generated ruleset, read-only for now.
+pub const Backend = enum { none, own, ufw, firewalld, redi, foreign };
+pub const Policy = enum { accept, drop, reject };
+pub const Action = enum { allow, deny, reject, limit };
+pub const Direction = enum { in, out };
+pub const Proto = enum { tcp, udp, both };
+pub const Family = enum { both, v4, v6 };
+/// Where a rule applies: on every network, or only on trusted (home) ones.
+pub const Scope = enum { everywhere, home };
+pub const Trust = enum { public, home };
+pub const Logging = enum { off, low, medium, high };
+pub const System = enum { linux, freebsd };
+
+/// One rule. `port` is "22", "8000-8100" or "" (any); `service` is a catalog
+/// id or the manager's own service/application name, whose ports the helper
+/// resolves into `port` where it can. `source` is "" (anywhere), "lan" or an
+/// address/CIDR.
+pub const Rule = struct {
+ id: u32 = 0,
+ action: Action = .allow,
+ direction: Direction = .in,
+ proto: Proto = .both,
+ port: []const u8 = "",
+ service: []const u8 = "",
+ source: []const u8 = "",
+ scope: Scope = .everywhere,
+ family: Family = .both,
+ iface: []const u8 = "",
+ comment: []const u8 = "",
+ /// The manager can express this rule but we could not map all of it
+ /// (a firewalld rich rule, a ufw route rule): shown, deletable, not editable.
+ raw: []const u8 = "",
+};
+
+/// Rules some other program owns: a Docker or libvirt table, a pf.conf.
+pub const Foreign = struct {
+ owner: []const u8,
+ name: []const u8,
+ rules: u32 = 0,
+};
+
+pub const Verdict = enum { local, blocked, home, everywhere };
+
+/// A listening socket and whether the firewall lets anyone reach it.
+pub const Listener = struct {
+ proto: Proto = .tcp,
+ address: []const u8 = "",
+ port: u16 = 0,
+ process: []const u8 = "",
+ pid: i32 = 0,
+ uid: u32 = 0,
+ verdict: Verdict = .blocked,
+};
+
+/// A network's trust: an active NetworkManager connection (`uuid`), or an
+/// interface where there is no NetworkManager.
+pub const Network = struct {
+ name: []const u8 = "",
+ iface: []const u8 = "",
+ uuid: []const u8 = "",
+ trust: Trust = .public,
+ active: bool = false,
+};
+
+pub const Block = struct {
+ time: []const u8 = "",
+ direction: Direction = .in,
+ proto: []const u8 = "",
+ source: []const u8 = "",
+ port: u16 = 0,
+ iface: []const u8 = "",
+};
+
+/// What the manager can express; the page hides what it cannot.
+pub const Capabilities = struct {
+ edit: bool = false,
+ trust: bool = false,
+ sources: bool = false,
+ limit: bool = false,
+ reject: bool = false,
+ outgoing_rules: bool = false,
+ outgoing_policy: bool = false,
+ forward_policy: bool = false,
+ ping: bool = false,
+ logging: bool = false,
+ ssh_limit: bool = false,
+ boot: bool = false,
+ lockdown: bool = false,
+};
+
+pub const Status = struct {
+ system: System = .linux,
+ backend: Backend = .none,
+ /// The manager is installed and set up but not filtering now.
+ running: bool = false,
+ boot: bool = false,
+ /// Other managers that are active too; while any is, nothing is editable.
+ conflicts: []const Backend = &.{},
+ /// Managers that are installed but inactive (what Turn on may use).
+ installed: []const Backend = &.{},
+ incoming: Policy = .drop,
+ outgoing: Policy = .accept,
+ forward: Policy = .drop,
+ ping: bool = true,
+ logging: Logging = .off,
+ ssh_limit: bool = false,
+ lockdown: bool = false,
+ /// firewalld's zone for the default route; empty elsewhere.
+ zone: []const u8 = "",
+ rules: []const Rule = &.{},
+ foreign: []const Foreign = &.{},
+ listeners: []const Listener = &.{},
+ networks: []const Network = &.{},
+ blocks: []const Block = &.{},
+ capabilities: Capabilities = .{},
+ /// Seconds until a pending change reverts unless confirmed; 0 for none.
+ revert_in: u32 = 0,
+ /// The setup a Turn on would do needs a change to pf.conf first (FreeBSD).
+ needs_anchor: bool = false,
+};
+
+pub fn isAnywhere(source: []const u8) bool {
+ return source.len == 0 or std.mem.eql(u8, source, "0.0.0.0/0") or std.mem.eql(u8, source, "::/0") or std.mem.eql(u8, source, "any");
+}
+
+/// Whether `port` (as a rule writes it) covers `number`.
+pub fn portCovers(port: []const u8, number: u16) bool {
+ if (port.len == 0) return true;
+ var parts = std.mem.splitScalar(u8, port, ',');
+ while (parts.next()) |part| {
+ const trimmed = std.mem.trim(u8, part, " ");
+ const sep = std.mem.indexOfAny(u8, trimmed, "-:");
+ if (sep) |i| {
+ const lo = std.fmt.parseInt(u16, trimmed[0..i], 10) catch continue;
+ const hi = std.fmt.parseInt(u16, trimmed[i + 1 ..], 10) catch continue;
+ if (number >= lo and number <= hi) return true;
+ } else {
+ const one = std.fmt.parseInt(u16, trimmed, 10) catch continue;
+ if (one == number) return true;
+ }
+ }
+ return false;
+}
+
+/// Whether a rule is about this socket's port: a service whose ports the
+/// helper could not resolve matches nothing rather than everything.
+pub fn about(rule: Rule, listener: Listener) bool {
+ if (rule.direction != .in) return false;
+ if (rule.port.len == 0 and rule.service.len != 0) {
+ const s = @import("services.zig").find(rule.service) orelse return false;
+ for (s.ports) |p| if (protoMatches(p.proto, listener.proto) and portCovers(p.port, listener.port)) return true;
+ return false;
+ }
+ return protoMatches(rule.proto, listener.proto) and portCovers(rule.port, listener.port);
+}
+
+fn protoMatches(rule: Proto, sock: Proto) bool {
+ return rule == .both or rule == sock;
+}
+
+fn isLoopback(address: []const u8) bool {
+ return std.mem.startsWith(u8, address, "127.") or std.mem.eql(u8, address, "::1") or std.mem.eql(u8, address, "localhost");
+}
+
+/// How far a listener reaches through `status`'s rules. Approximate on
+/// purpose: it answers "can another machine connect", not every corner of
+/// the manager's semantics. Rules are matched first-wins as ufw, our table
+/// and our anchor (all `quick`) evaluate them.
+pub fn verdict(status: Status, listener: Listener) Verdict {
+ if (isLoopback(listener.address)) return .local;
+ if (status.lockdown) return .blocked;
+ if (!status.running or status.backend == .none) return .everywhere;
+ var best: Verdict = if (status.incoming == .accept) .everywhere else .blocked;
+ if (status.incoming == .accept) {
+ for (status.rules) |rule| {
+ if (!about(rule, listener)) continue;
+ if (rule.action == .deny or rule.action == .reject) {
+ if (isAnywhere(rule.source) and rule.scope == .everywhere) return .blocked;
+ }
+ }
+ return best;
+ }
+ for (status.rules) |rule| {
+ if (!about(rule, listener)) continue;
+ switch (rule.action) {
+ .deny, .reject => {
+ if (isAnywhere(rule.source) and rule.scope == .everywhere and best == .blocked) return .blocked;
+ },
+ .allow, .limit => {
+ const reach: Verdict = if (isAnywhere(rule.source) and rule.scope == .everywhere) .everywhere else .home;
+ if (@backingInt(reach) > @backingInt(best)) best = reach;
+ if (best == .everywhere) return best;
+ },
+ }
+ }
+ return best;
+}
+
+test "port ranges and lists" {
+ try std.testing.expect(portCovers("22", 22));
+ try std.testing.expect(!portCovers("22", 23));
+ try std.testing.expect(portCovers("1000-2000", 1500));
+ try std.testing.expect(portCovers("1714:1764", 1764));
+ try std.testing.expect(portCovers("80,443", 443));
+ try std.testing.expect(portCovers("", 9));
+}
+
+test "verdicts follow the rules" {
+ const rules = [_]Rule{
+ .{ .port = "22", .proto = .tcp },
+ .{ .port = "5353", .proto = .udp, .scope = .home },
+ .{ .port = "445", .proto = .tcp, .source = "192.168.0.0/16" },
+ };
+ const status: Status = .{ .backend = .own, .running = true, .rules = &rules };
+ try std.testing.expectEqual(Verdict.everywhere, verdict(status, .{ .proto = .tcp, .address = "0.0.0.0", .port = 22 }));
+ try std.testing.expectEqual(Verdict.blocked, verdict(status, .{ .proto = .udp, .address = "0.0.0.0", .port = 22 }));
+ try std.testing.expectEqual(Verdict.home, verdict(status, .{ .proto = .udp, .address = "::", .port = 5353 }));
+ try std.testing.expectEqual(Verdict.home, verdict(status, .{ .proto = .tcp, .address = "0.0.0.0", .port = 445 }));
+ try std.testing.expectEqual(Verdict.local, verdict(status, .{ .proto = .tcp, .address = "127.0.0.1", .port = 631 }));
+ try std.testing.expectEqual(Verdict.blocked, verdict(status, .{ .proto = .tcp, .address = "0.0.0.0", .port = 8080 }));
+ const by_service = [_]Rule{.{ .service = "ssh", .source = "lan" }};
+ try std.testing.expectEqual(Verdict.home, verdict(.{ .backend = .own, .running = true, .rules = &by_service }, .{ .proto = .tcp, .address = "::", .port = 22 }));
+ var off = status;
+ off.running = false;
+ try std.testing.expectEqual(Verdict.everywhere, verdict(off, .{ .proto = .tcp, .address = "0.0.0.0", .port = 8080 }));
+}
diff --git a/src/firewall/own.zig b/src/firewall/own.zig
new file mode 100644
index 0000000..feb268d
--- /dev/null
+++ b/src/firewall/own.zig
@@ -0,0 +1,343 @@
+//! Our own firewall, for systems where nothing else manages one: the state we
+//! keep in `${sysconfdir}/rediwm/firewall.json` and its rendering into an
+//! nftables table (`inet rediwm`, Linux) or a pf anchor (`rediwm`, FreeBSD).
+//! We never write outside that table or anchor. Every string reaching a
+//! renderer passed `validate.zig`, so nothing needs escaping here.
+const std = @import("std");
+const model = @import("model.zig");
+const services = @import("services.zig");
+const Writer = std.Io.Writer;
+
+pub const State = struct {
+ version: u32 = 1,
+ enabled: bool = false,
+ incoming: model.Policy = .drop,
+ outgoing: model.Policy = .accept,
+ forward: model.Policy = .drop,
+ ping: bool = true,
+ logging: model.Logging = .off,
+ ssh_limit: bool = false,
+ rules: []const model.Rule = &.{},
+ /// Interfaces trusted as home where trust is per interface (no
+ /// NetworkManager, or FreeBSD). With NetworkManager the dispatcher fills
+ /// the live set from each connection's zone instead.
+ home_ifaces: []const []const u8 = &.{},
+};
+
+pub const table = "rediwm";
+pub const lockdown_table = "rediwm_lockdown";
+pub const log_prefix = "rediwm-drop";
+
+const lan4 = "10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16";
+const lan6 = "fc00::/7, fe80::/10";
+
+fn logRate(level: model.Logging) []const u8 {
+ return switch (level) {
+ .off => "",
+ .low => "5/minute",
+ .medium => "30/minute",
+ .high => "120/minute",
+ };
+}
+
+fn policyWord(p: model.Policy) []const u8 {
+ return if (p == .accept) "accept" else "drop";
+}
+
+/// A rule's ports as concrete (proto, port) pairs: its own, or its service's.
+pub fn expand(rule: model.Rule, out: []services.Port) []const services.Port {
+ if (rule.port.len != 0 or rule.service.len == 0) {
+ out[0] = .{ .proto = rule.proto, .port = rule.port };
+ return out[0..1];
+ }
+ const s = services.find(rule.service) orelse {
+ out[0] = .{ .proto = rule.proto, .port = "" };
+ return out[0..1];
+ };
+ const n = @min(s.ports.len, out.len);
+ @memcpy(out[0..n], s.ports[0..n]);
+ return out[0..n];
+}
+
+fn nftPort(w: *Writer, port: []const u8) !void {
+ for (port) |ch| try w.writeByte(if (ch == ':') '-' else ch);
+}
+
+const LanFamily = enum { v4, v6 };
+
+fn nftMatch(w: *Writer, rule: model.Rule, p: services.Port, lan_family: ?LanFamily) !void {
+ const in = rule.direction == .in;
+ if (rule.family == .v4 and lan_family == null and rule.source.len == 0) try w.writeAll(" meta nfproto ipv4");
+ if (rule.family == .v6 and lan_family == null and rule.source.len == 0) try w.writeAll(" meta nfproto ipv6");
+ if (rule.iface.len != 0) try w.print(" {s} \"{s}\"", .{ if (in) "iifname" else "oifname", rule.iface });
+ if (rule.scope == .home) try w.print(" {s} @home_ifaces", .{if (in) "iifname" else "oifname"});
+ const field = if (in) "saddr" else "daddr";
+ if (lan_family) |fam| {
+ try w.print(" {s} {s} @lan{s}", .{ if (fam == .v4) "ip" else "ip6", field, if (fam == .v4) "4" else "6" });
+ } else if (rule.source.len != 0) {
+ const v6 = std.mem.indexOfScalar(u8, rule.source, ':') != null;
+ try w.print(" {s} {s} {s}", .{ if (v6) "ip6" else "ip", field, rule.source });
+ }
+ switch (p.proto) {
+ .tcp, .udp => {
+ const name = if (p.proto == .tcp) "tcp" else "udp";
+ if (p.port.len != 0) {
+ try w.print(" {s} dport ", .{name});
+ try nftPort(w, p.port);
+ } else try w.print(" meta l4proto {s}", .{name});
+ },
+ .both => if (p.port.len != 0) {
+ try w.writeAll(" meta l4proto { tcp, udp } th dport ");
+ try nftPort(w, p.port);
+ },
+ }
+}
+
+fn nftRule(w: *Writer, rule: model.Rule) !void {
+ var buffer: [8]services.Port = undefined;
+ const ports = expand(rule, &buffer);
+ const lan = std.mem.eql(u8, rule.source, "lan");
+ for (ports) |p| {
+ const passes: []const ?LanFamily = if (!lan) &.{null} else switch (rule.family) {
+ .both => &.{ .v4, .v6 },
+ .v4 => &.{.v4},
+ .v6 => &.{.v6},
+ };
+ for (passes) |fam| {
+ if (rule.action == .limit) {
+ try w.writeAll("\t\t");
+ try nftMatch(w, rule, p, fam);
+ try w.writeAll(" ct state new limit rate over 6/minute burst 6 packets drop\n");
+ }
+ try w.writeAll("\t\t");
+ try nftMatch(w, rule, p, fam);
+ try w.writeAll(switch (rule.action) {
+ .allow, .limit => " accept",
+ .deny => " drop",
+ .reject => " reject",
+ });
+ if (rule.comment.len != 0) try w.print(" comment \"{s}\"", .{rule.comment});
+ try w.writeByte('\n');
+ }
+ }
+}
+
+fn denyFirst(rules: []const model.Rule, direction: model.Direction, deny: bool, w: *Writer) !void {
+ for (rules) |rule| {
+ if (rule.direction != direction) continue;
+ const is_deny = rule.action == .deny or rule.action == .reject;
+ if (is_deny == deny) try nftRule(w, rule);
+ }
+}
+
+/// The whole table, replacing any previous one in a single transaction
+/// (`table` + `delete table` first, so the load works whether or not it
+/// exists, and a failed load changes nothing).
+pub fn renderNft(w: *Writer, state: State, live_home: []const []const u8) !void {
+ try w.writeAll("#!/usr/sbin/nft -f\n# Written by rediwm-firewall-helper from firewall.json; edit in Settings.\n");
+ try w.print("table inet {s}\ndelete table inet {s}\n", .{ table, table });
+ try w.print("table inet {s} {{\n", .{table});
+ const home = if (live_home.len != 0) live_home else state.home_ifaces;
+ try w.writeAll("\tset home_ifaces {\n\t\ttype ifname\n");
+ if (home.len != 0) {
+ try w.writeAll("\t\telements = { ");
+ for (home, 0..) |name, i| try w.print("{s}\"{s}\"", .{ if (i == 0) "" else ", ", name });
+ try w.writeAll(" }\n");
+ }
+ try w.writeAll("\t}\n");
+ try w.print("\tset lan4 {{\n\t\ttype ipv4_addr\n\t\tflags interval\n\t\telements = {{ {s} }}\n\t}}\n", .{lan4});
+ try w.print("\tset lan6 {{\n\t\ttype ipv6_addr\n\t\tflags interval\n\t\telements = {{ {s} }}\n\t}}\n", .{lan6});
+
+ try w.print("\tchain input {{\n\t\ttype filter hook input priority filter; policy {s};\n", .{policyWord(state.incoming)});
+ try w.writeAll("\t\tiif \"lo\" accept\n\t\tct state established,related accept\n\t\tct state invalid drop\n");
+ try denyFirst(state.rules, .in, true, w);
+ if (!state.ping) try w.writeAll("\t\ticmp type echo-request drop\n\t\ticmpv6 type echo-request drop\n");
+ try w.writeAll("\t\tmeta l4proto { icmp, ipv6-icmp } accept\n");
+ try w.writeAll("\t\tudp sport 67 udp dport 68 accept\n\t\tudp sport 547 udp dport 546 accept\n");
+ if (state.ssh_limit) try w.writeAll("\t\ttcp dport 22 ct state new limit rate over 6/minute burst 6 packets drop\n");
+ try denyFirst(state.rules, .in, false, w);
+ if (state.logging != .off and state.incoming != .accept) try w.print("\t\tlimit rate {s} log prefix \"{s} \" level info\n", .{ logRate(state.logging), log_prefix });
+ if (state.incoming == .reject) try w.writeAll("\t\treject with icmpx type admin-prohibited\n");
+ try w.writeAll("\t}\n");
+
+ try w.print("\tchain forward {{\n\t\ttype filter hook forward priority filter; policy {s};\n\t}}\n", .{policyWord(state.forward)});
+
+ try w.print("\tchain output {{\n\t\ttype filter hook output priority filter; policy {s};\n", .{policyWord(state.outgoing)});
+ try w.writeAll("\t\toif \"lo\" accept\n\t\tct state established,related accept\n");
+ try denyFirst(state.rules, .out, true, w);
+ if (state.outgoing != .accept) {
+ // Without these, blocking outgoing would also cut DHCP and DNS.
+ try w.writeAll("\t\tudp dport { 53, 67, 547 } accept\n\t\ttcp dport 53 accept\n\t\tmeta l4proto { icmp, ipv6-icmp } accept\n");
+ }
+ try denyFirst(state.rules, .out, false, w);
+ if (state.outgoing == .reject) try w.writeAll("\t\treject with icmpx type admin-prohibited\n");
+ try w.writeAll("\t}\n}\n");
+}
+
+/// Blocks everything but loopback, beside whatever else is loaded: a drop in
+/// any base chain drops the packet, so this works under every manager.
+pub fn renderLockdownNft(w: *Writer, on: bool) !void {
+ try w.print("table inet {s}\ndelete table inet {s}\n", .{ lockdown_table, lockdown_table });
+ if (!on) return;
+ try w.print("table inet {s} {{\n", .{lockdown_table});
+ inline for (.{ "input", "output", "forward" }) |hook| {
+ const lo = if (comptime std.mem.eql(u8, hook, "input")) "\t\tiif \"lo\" accept\n" else if (comptime std.mem.eql(u8, hook, "output")) "\t\toif \"lo\" accept\n" else "";
+ try w.print("\tchain {s} {{\n\t\ttype filter hook {s} priority -200; policy drop;\n{s}\t}}\n", .{ hook, hook, lo });
+ }
+ try w.writeAll("}\n");
+}
+
+fn pfPort(w: *Writer, port: []const u8) !void {
+ for (port) |ch| try w.writeByte(if (ch == '-') ':' else ch);
+}
+
+fn pfRule(w: *Writer, rule: model.Rule, home: []const []const u8) !void {
+ if (rule.scope == .home and home.len == 0 and rule.iface.len == 0) return;
+ var buffer: [8]services.Port = undefined;
+ for (expand(rule, &buffer)) |p| {
+ const verb = switch (rule.action) {
+ .allow, .limit => "pass",
+ .deny => "block drop",
+ .reject => "block return",
+ };
+ try w.print("{s} {s} quick", .{ verb, if (rule.direction == .in) "in" else "out" });
+ if (rule.iface.len != 0) {
+ try w.print(" on {s}", .{rule.iface});
+ } else if (rule.scope == .home) {
+ try w.writeAll(" on {");
+ for (home) |name| try w.print(" {s}", .{name});
+ try w.writeAll(" }");
+ }
+ const v6_source = rule.source.len != 0 and std.mem.indexOfScalar(u8, rule.source, ':') != null;
+ if (rule.family == .v4 or (rule.source.len != 0 and !v6_source and !std.mem.eql(u8, rule.source, "lan"))) try w.writeAll(" inet");
+ if (rule.family == .v6 or v6_source) try w.writeAll(" inet6");
+ switch (p.proto) {
+ .tcp => try w.writeAll(" proto tcp"),
+ .udp => try w.writeAll(" proto udp"),
+ .both => if (p.port.len != 0) try w.writeAll(" proto { tcp udp }"),
+ }
+ const remote = if (std.mem.eql(u8, rule.source, "lan")) "<rediwm_lan>" else if (rule.source.len != 0) rule.source else "any";
+ if (rule.direction == .in) try w.print(" from {s} to any", .{remote}) else try w.print(" from any to {s}", .{remote});
+ if (p.port.len != 0) {
+ try w.writeAll(" port ");
+ try pfPort(w, p.port);
+ }
+ if (rule.action == .allow or rule.action == .limit) {
+ try w.writeAll(" keep state");
+ if (rule.action == .limit) try w.writeAll(" (max-src-conn-rate 6/30, overload <rediwm_abuse> flush global)");
+ }
+ if (rule.comment.len != 0) try w.print(" label \"{s}\"", .{rule.comment});
+ try w.writeByte('\n');
+ }
+}
+
+/// The anchor's rules. Every rule is `quick`, so the anchor decides on its
+/// own and in order: loopback, blocks, then allows, then the default.
+pub fn renderPf(w: *Writer, state: State, lockdown: bool) !void {
+ try w.writeAll("# Written by rediwm-firewall-helper from firewall.json; edit in Settings.\n");
+ try w.print("table <rediwm_lan> const {{ {s}, {s} }}\ntable <rediwm_abuse> persist\n", .{ lan4, lan6 });
+ try w.writeAll("pass quick on lo0 all\n");
+ if (lockdown) {
+ try w.writeAll("block drop quick all\n");
+ return;
+ }
+ try w.writeAll("block drop in quick from <rediwm_abuse>\n");
+ for (state.rules) |rule| if (rule.action == .deny or rule.action == .reject) try pfRule(w, rule, state.home_ifaces);
+ if (state.ping) {
+ try w.writeAll("pass in quick inet proto icmp all icmp-type { echoreq, unreach } keep state\n");
+ } else try w.writeAll("pass in quick inet proto icmp all icmp-type unreach keep state\n");
+ // Neighbour discovery: IPv6 does not work without it.
+ try w.writeAll("pass in quick inet6 proto icmp6 all keep state\n");
+ try w.writeAll("pass in quick inet proto udp from any port 67 to any port 68\npass in quick inet6 proto udp from any port 547 to any port 546\n");
+ if (state.ssh_limit) try w.writeAll("pass in quick proto tcp from any to any port 22 keep state (max-src-conn-rate 6/30, overload <rediwm_abuse> flush global)\n");
+ for (state.rules) |rule| if ((rule.action == .allow or rule.action == .limit) and rule.direction == .in) try pfRule(w, rule, state.home_ifaces);
+ for (state.rules) |rule| if ((rule.action == .allow or rule.action == .limit) and rule.direction == .out) try pfRule(w, rule, state.home_ifaces);
+ const log = if (state.logging != .off) " log" else "";
+ try w.writeAll(switch (state.incoming) {
+ .accept => "pass in quick all keep state\n",
+ .drop => "",
+ .reject => "",
+ });
+ if (state.incoming == .drop) try w.print("block drop in{s} quick all\n", .{log});
+ if (state.incoming == .reject) try w.print("block return in{s} quick all\n", .{log});
+ if (state.outgoing == .accept) {
+ try w.writeAll("pass out quick all keep state\n");
+ } else {
+ try w.writeAll("pass out quick proto { tcp udp } from any to any port 53 keep state\npass out quick proto udp from any to any port { 67 547 } keep state\npass out quick inet proto icmp all keep state\npass out quick inet6 proto icmp6 all keep state\n");
+ try w.writeAll(if (state.outgoing == .reject) "block return out quick all\n" else "block drop out quick all\n");
+ }
+}
+
+/// The minimal pf.conf a Turn on writes when there is none.
+pub const pf_conf =
+ \\# Written by RediWM Settings. The rules live in the "rediwm" anchor;
+ \\# add your own below the anchor line.
+ \\set skip on lo0
+ \\scrub in all
+ \\anchor "rediwm"
+ \\load anchor "rediwm" from "@ANCHOR@"
+ \\block in all
+ \\pass out all keep state
+ \\
+;
+
+/// Whether a pf.conf evaluates our anchor (and loads it at boot).
+pub fn pfConfHasAnchor(conf: []const u8) struct { anchor: bool, load: bool } {
+ var anchor = false;
+ var load = false;
+ var lines = std.mem.splitScalar(u8, conf, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0 or line[0] == '#') continue;
+ if (std.mem.startsWith(u8, line, "anchor \"rediwm\"")) anchor = true;
+ if (std.mem.startsWith(u8, line, "load anchor \"rediwm\"")) load = true;
+ }
+ return .{ .anchor = anchor, .load = load };
+}
+
+/// The lines Turn on adds to an existing pf.conf. The anchor goes first so
+/// our blocks and allows come before the file's own rules.
+pub fn pfConfWithAnchor(a: std.mem.Allocator, conf: []const u8, anchor_path: []const u8) ![]u8 {
+ var out: Writer.Allocating = .init(a);
+ errdefer out.deinit();
+ var lines = std.mem.splitScalar(u8, conf, '\n');
+ var inserted = false;
+ const w = &out.writer;
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ // Options, tables, scrub and NAT must precede filter rules in pf.conf.
+ const filter = std.mem.startsWith(u8, line, "pass") or std.mem.startsWith(u8, line, "block") or std.mem.startsWith(u8, line, "anchor") or std.mem.startsWith(u8, line, "antispoof");
+ if (!inserted and filter) {
+ try w.print("anchor \"rediwm\"\nload anchor \"rediwm\" from \"{s}\"\n", .{anchor_path});
+ inserted = true;
+ }
+ try w.writeAll(raw);
+ if (lines.peek() != null) try w.writeByte('\n');
+ }
+ if (!inserted) try w.print("\nanchor \"rediwm\"\nload anchor \"rediwm\" from \"{s}\"\n", .{anchor_path});
+ return out.toOwnedSlice();
+}
+
+/// The status a saved state shows (rules carry their index as `id`).
+pub fn status(a: std.mem.Allocator, state: State) !model.Status {
+ const rules = try a.alloc(model.Rule, state.rules.len);
+ for (state.rules, rules, 0..) |rule, *out, i| {
+ out.* = rule;
+ out.id = @intCast(i);
+ }
+ return .{
+ .backend = .own,
+ .incoming = state.incoming,
+ .outgoing = state.outgoing,
+ .forward = state.forward,
+ .ping = state.ping,
+ .logging = state.logging,
+ .ssh_limit = state.ssh_limit,
+ .rules = rules,
+ };
+}
+
+pub fn sameRule(x: model.Rule, y: model.Rule) bool {
+ return x.action == y.action and x.direction == y.direction and x.proto == y.proto and x.scope == y.scope and x.family == y.family and
+ std.mem.eql(u8, x.port, y.port) and std.mem.eql(u8, x.service, y.service) and std.mem.eql(u8, x.source, y.source) and std.mem.eql(u8, x.iface, y.iface);
+}
diff --git a/src/firewall/own_tests.zig b/src/firewall/own_tests.zig
new file mode 100644
index 0000000..f60fc37
--- /dev/null
+++ b/src/firewall/own_tests.zig
@@ -0,0 +1,108 @@
+const std = @import("std");
+const own = @import("own.zig");
+const model = @import("model.zig");
+
+fn render(a: std.mem.Allocator, state: own.State, pf: bool) ![]const u8 {
+ var out: std.Io.Writer.Allocating = .init(a);
+ if (pf) try own.renderPf(&out.writer, state, false) else try own.renderNft(&out.writer, state, &.{});
+ return out.written();
+}
+
+const sample_rules = [_]model.Rule{
+ .{ .service = "ssh", .source = "lan", .comment = "ssh" },
+ .{ .port = "8000-8100", .proto = .both },
+ .{ .source = "203.0.113.9", .action = .deny },
+ .{ .service = "mdns", .scope = .home },
+ .{ .port = "25", .proto = .tcp, .direction = .out, .action = .reject },
+ .{ .port = "22", .proto = .tcp, .action = .limit, .family = .v6 },
+};
+
+test "nft table" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const text = try render(a, .{ .enabled = true, .rules = &sample_rules, .logging = .low, .ping = false, .home_ifaces = &.{"wlan0"} }, false);
+ const expect = [_][]const u8{
+ "table inet rediwm\ndelete table inet rediwm\ntable inet rediwm {",
+ "elements = { \"wlan0\" }",
+ "policy drop;",
+ "\t\t ip saddr @lan4 tcp dport 22 accept comment \"ssh\"\n",
+ "\t\t ip6 saddr @lan6 tcp dport 22 accept comment \"ssh\"\n",
+ "\t\t meta l4proto { tcp, udp } th dport 8000-8100 accept\n",
+ "\t\t ip saddr 203.0.113.9 drop\n",
+ "\t\t iifname @home_ifaces udp dport 5353 accept\n",
+ "\t\t tcp dport 25 reject\n",
+ "\t\t meta nfproto ipv6 tcp dport 22 ct state new limit rate over 6/minute burst 6 packets drop\n",
+ "icmp type echo-request drop",
+ "limit rate 5/minute log prefix \"rediwm-drop \" level info",
+ };
+ for (expect) |piece| {
+ if (std.mem.indexOf(u8, text, piece) == null) {
+ std.debug.print("missing {s}\nin\n{s}\n", .{ piece, text });
+ return error.TestUnexpectedResult;
+ }
+ }
+ // Blocks come before allows in the input chain.
+ try std.testing.expect(std.mem.indexOf(u8, text, "203.0.113.9 drop").? < std.mem.indexOf(u8, text, "@lan4 tcp dport 22").?);
+}
+
+test "pf anchor" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const text = try render(a, .{ .enabled = true, .rules = &sample_rules, .home_ifaces = &.{ "em0", "wlan0" } }, true);
+ const expect = [_][]const u8{
+ "pass quick on lo0 all\n",
+ "pass in quick proto tcp from <rediwm_lan> to any port 22 keep state label \"ssh\"\n",
+ "pass in quick proto { tcp udp } from any to any port 8000:8100 keep state\n",
+ "block drop in quick inet from 203.0.113.9 to any\n",
+ "pass in quick on { em0 wlan0 } proto udp from any to any port 5353 keep state\n",
+ "block return out quick proto tcp from any to any port 25\n",
+ "pass in quick inet6 proto tcp from any to any port 22 keep state (max-src-conn-rate 6/30, overload <rediwm_abuse> flush global)\n",
+ "block drop in quick all\n",
+ "pass out quick all keep state\n",
+ };
+ for (expect) |piece| {
+ if (std.mem.indexOf(u8, text, piece) == null) {
+ std.debug.print("missing {s}\nin\n{s}\n", .{ piece, text });
+ return error.TestUnexpectedResult;
+ }
+ }
+ var locked: std.Io.Writer.Allocating = .init(a);
+ try own.renderPf(&locked.writer, .{}, true);
+ try std.testing.expect(std.mem.endsWith(u8, locked.written(), "pass quick on lo0 all\nblock drop quick all\n"));
+}
+
+test "pf.conf anchor insertion" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const conf = "ext_if=\"em0\"\nset skip on lo0\nscrub in all\nblock in all\npass out all keep state\n";
+ try std.testing.expect(!own.pfConfHasAnchor(conf).anchor);
+ const updated = try own.pfConfWithAnchor(a, conf, "/usr/local/etc/rediwm/pf.rediwm.conf");
+ try std.testing.expect(std.mem.indexOf(u8, updated, "scrub in all\nanchor \"rediwm\"\nload anchor \"rediwm\" from \"/usr/local/etc/rediwm/pf.rediwm.conf\"\nblock in all") != null);
+ const has = own.pfConfHasAnchor(updated);
+ try std.testing.expect(has.anchor and has.load);
+}
+
+test "lockdown table" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ var out: std.Io.Writer.Allocating = .init(arena.allocator());
+ try own.renderLockdownNft(&out.writer, true);
+ try std.testing.expect(std.mem.indexOf(u8, out.written(), "type filter hook input priority -200; policy drop;\n\t\tiif \"lo\" accept") != null);
+ var off: std.Io.Writer.Allocating = .init(arena.allocator());
+ try own.renderLockdownNft(&off.writer, false);
+ try std.testing.expectEqualStrings("table inet rediwm_lockdown\ndelete table inet rediwm_lockdown\n", off.written());
+}
+
+test "state round trip" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const json = try std.json.Stringify.valueAlloc(a, own.State{ .enabled = true, .rules = &sample_rules }, .{});
+ const back = try std.json.parseFromSliceLeaky(own.State, a, json, .{ .ignore_unknown_fields = true });
+ try std.testing.expect(back.enabled);
+ try std.testing.expectEqual(sample_rules.len, back.rules.len);
+ try std.testing.expect(own.sameRule(sample_rules[0], back.rules[0]));
+}
diff --git a/src/firewall/protocol.zig b/src/firewall/protocol.zig
new file mode 100644
index 0000000..afdfb54
--- /dev/null
+++ b/src/firewall/protocol.zig
@@ -0,0 +1,57 @@
+//! Requests from Settings to `rediwm-firewall-helper`, one per run, on stdin.
+//! The helper answers with a `Reply` on stdout. Everything in a request is
+//! untrusted: the helper validates each field before it reaches a tool.
+const model = @import("model.zig");
+
+pub const Op = enum {
+ /// Read everything (the `read` polkit action).
+ status,
+ /// Recent blocked connections from the kernel log or pflog (`read`).
+ blocks,
+ /// Changes nothing; proves the password for the `manage` action.
+ authorize,
+ enable,
+ disable,
+ set_defaults,
+ add_rule,
+ remove_rule,
+ set_option,
+ set_trust,
+ lockdown,
+ /// Keep a change that is waiting to revert.
+ confirm,
+ /// Re-apply our saved table or anchor (NetworkManager dispatcher, boot).
+ sync,
+};
+
+pub const Option = enum { ping, logging, ssh_limit, boot };
+
+pub const Request = struct {
+ op: Op = .status,
+ rule: ?model.Rule = null,
+ incoming: ?model.Policy = null,
+ outgoing: ?model.Policy = null,
+ forward: ?model.Policy = null,
+ option: ?Option = null,
+ on: bool = false,
+ logging: ?model.Logging = null,
+ /// `set_trust`: a NetworkManager connection uuid, or an interface.
+ uuid: []const u8 = "",
+ iface: []const u8 = "",
+ trust: model.Trust = .public,
+ /// Undo the change after this many seconds unless `confirm` arrives.
+ revert_after: u32 = 0,
+ /// `enable` with no manager: which one to set up (`own` by default).
+ backend: model.Backend = .own,
+};
+
+pub const Reply = struct {
+ status: model.Status = .{},
+ /// Why the operation failed, in words for the page; null on success.
+ failure: ?[]const u8 = null,
+};
+
+/// Which operations the read-only polkit action may run.
+pub fn readOnly(op: Op) bool {
+ return op == .status or op == .blocks;
+}
diff --git a/src/firewall/services.zig b/src/firewall/services.zig
new file mode 100644
index 0000000..9d53c49
--- /dev/null
+++ b/src/firewall/services.zig
@@ -0,0 +1,66 @@
+//! Services the page offers by name. A service expands into port rules for
+//! managers without their own catalog (our table, our anchor, ufw); with
+//! firewalld the helper uses firewalld's service of the same name when it
+//! exists (`firewalld`).
+const std = @import("std");
+const model = @import("model.zig");
+
+pub const Port = struct { proto: model.Proto, port: []const u8 };
+
+pub const Service = struct {
+ id: []const u8,
+ /// English; the page translates it through `i18n.tr`.
+ name: []const u8,
+ ports: []const Port,
+ /// Suggested scope: discovery and sharing belong on home networks.
+ scope: model.Scope = .home,
+ /// firewalld's service name: null when it is `id`, "" when firewalld has
+ /// none (the helper then opens the ports).
+ firewalld: ?[]const u8 = null,
+};
+
+pub const all = [_]Service{
+ .{ .id = "ssh", .name = "SSH (remote login)", .ports = &.{.{ .proto = .tcp, .port = "22" }} },
+ .{ .id = "http", .name = "Web server (HTTP)", .ports = &.{.{ .proto = .tcp, .port = "80" }}, .scope = .everywhere },
+ .{ .id = "https", .name = "Web server (HTTPS)", .ports = &.{.{ .proto = .tcp, .port = "443" }}, .scope = .everywhere },
+ .{ .id = "mdns", .name = "Local network discovery (mDNS)", .ports = &.{.{ .proto = .udp, .port = "5353" }} },
+ .{ .id = "kdeconnect", .name = "KDE Connect / GSConnect", .ports = &.{ .{ .proto = .tcp, .port = "1714-1764" }, .{ .proto = .udp, .port = "1714-1764" } } },
+ .{ .id = "syncthing", .name = "Syncthing", .ports = &.{ .{ .proto = .tcp, .port = "22000" }, .{ .proto = .udp, .port = "22000" }, .{ .proto = .udp, .port = "21027" } } },
+ .{ .id = "steam-streaming", .name = "Steam Remote Play", .ports = &.{ .{ .proto = .udp, .port = "27031-27036" }, .{ .proto = .tcp, .port = "27036" }, .{ .proto = .tcp, .port = "27037" } } },
+ .{ .id = "samba", .name = "Windows file sharing (Samba)", .ports = &.{ .{ .proto = .udp, .port = "137-138" }, .{ .proto = .tcp, .port = "139" }, .{ .proto = .tcp, .port = "445" } } },
+ .{ .id = "ipp", .name = "Printer sharing (IPP)", .ports = &.{.{ .proto = .tcp, .port = "631" }} },
+ .{ .id = "dlna", .name = "Media sharing (DLNA)", .ports = &.{ .{ .proto = .udp, .port = "1900" }, .{ .proto = .tcp, .port = "8200" } }, .firewalld = "upnp-client" },
+ .{ .id = "spotify-sync", .name = "Spotify local discovery", .ports = &.{ .{ .proto = .tcp, .port = "57621" }, .{ .proto = .udp, .port = "57621" } } },
+ .{ .id = "torrent", .name = "Files transfers (BitTorrent)", .ports = &.{ .{ .proto = .tcp, .port = "6881-6889" }, .{ .proto = .udp, .port = "6881-6889" } }, .scope = .everywhere, .firewalld = "" },
+ .{ .id = "vnc-server", .name = "Screen sharing (VNC)", .ports = &.{.{ .proto = .tcp, .port = "5900-5903" }} },
+ .{ .id = "rdp", .name = "Remote desktop (RDP)", .ports = &.{.{ .proto = .tcp, .port = "3389" }} },
+ .{ .id = "wireguard", .name = "WireGuard server", .ports = &.{.{ .proto = .udp, .port = "51820" }}, .scope = .everywhere },
+ .{ .id = "nfs", .name = "NFS file sharing", .ports = &.{ .{ .proto = .tcp, .port = "2049" }, .{ .proto = .udp, .port = "2049" } } },
+ .{ .id = "minecraft", .name = "Minecraft server", .ports = &.{.{ .proto = .tcp, .port = "25565" }}, .scope = .everywhere },
+};
+
+pub fn find(id: []const u8) ?*const Service {
+ for (&all) |*s| if (std.mem.eql(u8, s.id, id)) return s;
+ return null;
+}
+
+/// The catalog service a rule's port and protocol match exactly, for naming
+/// rules that came in as bare ports.
+pub fn named(proto: model.Proto, port: []const u8) ?*const Service {
+ for (&all) |*s| {
+ if (s.ports.len != 1) continue;
+ if (s.ports[0].proto == proto and std.mem.eql(u8, s.ports[0].port, port)) return s;
+ }
+ return null;
+}
+
+test "catalog ids are unique and valid" {
+ const validate = @import("validate.zig");
+ for (all, 0..) |s, i| {
+ try std.testing.expect(validate.service(s.id));
+ for (s.ports) |p| try std.testing.expect(validate.port(p.port));
+ for (all[i + 1 ..]) |other| try std.testing.expect(!std.mem.eql(u8, s.id, other.id));
+ }
+ try std.testing.expect(find("ssh") != null);
+ try std.testing.expectEqualStrings("ssh", named(.tcp, "22").?.id);
+}
diff --git a/src/firewall/sockets.zig b/src/firewall/sockets.zig
new file mode 100644
index 0000000..8ab4a89
--- /dev/null
+++ b/src/firewall/sockets.zig
@@ -0,0 +1,198 @@
+//! Listening sockets in text form: Linux's `/proc/net/{tcp,udp}{,6}` tables
+//! (read by `system_monitor/proc_linux_sockets.zig`, parsed here) and
+//! FreeBSD's `sockstat -46lqn`. Pure parsers, tested on every system.
+const std = @import("std");
+const model = @import("model.zig");
+const Allocator = std.mem.Allocator;
+
+pub const Socket = struct {
+ proto: model.Proto,
+ address: []const u8,
+ port: u16,
+ inode: u64 = 0,
+ uid: u32 = 0,
+ process: []const u8 = "",
+ pid: i32 = 0,
+};
+
+fn hexAddress(a: Allocator, hex: []const u8) ![]const u8 {
+ if (hex.len == 8) {
+ const raw = try std.fmt.parseInt(u32, hex, 16);
+ // The kernel prints the address as a host-order integer of its
+ // network-order bytes.
+ const bytes: [4]u8 = @bitCast(std.mem.nativeToLittle(u32, raw));
+ return std.fmt.allocPrint(a, "{d}.{d}.{d}.{d}", .{ bytes[0], bytes[1], bytes[2], bytes[3] });
+ }
+ if (hex.len == 32) {
+ var bytes: [16]u8 = undefined;
+ for (0..4) |i| {
+ const word = try std.fmt.parseInt(u32, hex[i * 8 .. i * 8 + 8], 16);
+ const le: [4]u8 = @bitCast(std.mem.nativeToLittle(u32, word));
+ @memcpy(bytes[i * 4 .. i * 4 + 4], &le);
+ }
+ if (std.mem.allEqual(u8, &bytes, 0)) return "::";
+ if (std.mem.allEqual(u8, bytes[0..15], 0) and bytes[15] == 1) return "::1";
+ if (std.mem.allEqual(u8, bytes[0..10], 0) and bytes[10] == 0xff and bytes[11] == 0xff)
+ return std.fmt.allocPrint(a, "{d}.{d}.{d}.{d}", .{ bytes[12], bytes[13], bytes[14], bytes[15] });
+ var out: std.Io.Writer.Allocating = .init(a);
+ for (0..8) |i| {
+ const group = @as(u16, bytes[i * 2]) << 8 | bytes[i * 2 + 1];
+ try out.writer.print("{s}{x}", .{ if (i == 0) "" else ":", group });
+ }
+ return out.toOwnedSlice();
+ }
+ return error.BadAddress;
+}
+
+/// One `/proc/net/*` table. TCP rows in LISTEN (0A) count; UDP rows bound to
+/// a port with no remote end (state 07) count as listening.
+pub fn parseProcNet(a: Allocator, text: []const u8, proto: model.Proto, out: *std.ArrayList(Socket)) !void {
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ _ = lines.next();
+ while (lines.next()) |line| {
+ var it = std.mem.tokenizeAny(u8, line, " \t");
+ _ = it.next() orelse continue;
+ const local = it.next() orelse continue;
+ const remote = it.next() orelse continue;
+ const state = it.next() orelse continue;
+ _ = it.next();
+ _ = it.next();
+ _ = it.next();
+ const uid_text = it.next() orelse continue;
+ _ = it.next();
+ const inode_text = it.next() orelse continue;
+ const listening = if (proto == .tcp) std.mem.eql(u8, state, "0A") else std.mem.eql(u8, state, "07") and std.mem.endsWith(u8, remote, ":0000");
+ if (!listening) continue;
+ const colon = std.mem.indexOfScalar(u8, local, ':') orelse continue;
+ const port = std.fmt.parseInt(u16, local[colon + 1 ..], 16) catch continue;
+ if (port == 0) continue;
+ const address = hexAddress(a, local[0..colon]) catch continue;
+ try out.append(a, .{
+ .proto = proto,
+ .address = address,
+ .port = port,
+ .uid = std.fmt.parseInt(u32, uid_text, 10) catch 0,
+ .inode = std.fmt.parseInt(u64, inode_text, 10) catch 0,
+ });
+ }
+}
+
+/// `sockstat -46lqn` (FreeBSD): USER COMMAND PID FD PROTO LOCAL FOREIGN.
+/// With -n the user is numeric.
+pub fn parseSockstat(a: Allocator, text: []const u8) ![]Socket {
+ var list: std.ArrayList(Socket) = .empty;
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |line| {
+ var fields: [8][]const u8 = undefined;
+ var n: usize = 0;
+ var it = std.mem.tokenizeAny(u8, line, " \t");
+ while (it.next()) |field| {
+ if (n == fields.len) break;
+ fields[n] = field;
+ n += 1;
+ }
+ if (n < 7) continue;
+ if (std.mem.eql(u8, fields[0], "USER")) continue;
+ const proto_text = fields[4];
+ const proto: model.Proto = if (std.mem.startsWith(u8, proto_text, "tcp")) .tcp else if (std.mem.startsWith(u8, proto_text, "udp")) .udp else continue;
+ const local = fields[5];
+ const colon = std.mem.lastIndexOfScalar(u8, local, ':') orelse continue;
+ const port = std.fmt.parseInt(u16, local[colon + 1 ..], 10) catch continue;
+ var address = std.mem.trim(u8, local[0..colon], "[]");
+ if (std.mem.eql(u8, address, "*")) address = if (std.mem.endsWith(u8, proto_text, "6")) "::" else "0.0.0.0";
+ try list.append(a, .{
+ .proto = proto,
+ .address = try a.dupe(u8, address),
+ .port = port,
+ .uid = std.fmt.parseInt(u32, fields[0], 10) catch 0,
+ .process = try a.dupe(u8, fields[1]),
+ .pid = std.fmt.parseInt(i32, fields[2], 10) catch 0,
+ });
+ }
+ return list.toOwnedSlice(a);
+}
+
+/// One row per (proto, port, address family): a daemon bound to both
+/// 0.0.0.0 and :: shows once.
+pub fn listeners(a: Allocator, sockets: []const Socket, status: model.Status) ![]model.Listener {
+ var list: std.ArrayList(model.Listener) = .empty;
+ outer: for (sockets) |s| {
+ for (list.items) |existing| {
+ if (existing.proto == s.proto and existing.port == s.port and std.mem.eql(u8, existing.process, s.process) and
+ (std.mem.eql(u8, existing.address, s.address) or (wildcard(existing.address) and wildcard(s.address)))) continue :outer;
+ }
+ var l: model.Listener = .{ .proto = s.proto, .address = s.address, .port = s.port, .process = s.process, .pid = s.pid, .uid = s.uid };
+ l.verdict = model.verdict(status, l);
+ try list.append(a, l);
+ }
+ std.mem.sort(model.Listener, list.items, {}, struct {
+ fn less(_: void, x: model.Listener, y: model.Listener) bool {
+ if (x.verdict != y.verdict) return @backingInt(x.verdict) > @backingInt(y.verdict);
+ return x.port < y.port;
+ }
+ }.less);
+ return list.toOwnedSlice(a);
+}
+
+fn wildcard(address: []const u8) bool {
+ return std.mem.eql(u8, address, "0.0.0.0") or std.mem.eql(u8, address, "::");
+}
+
+test "proc net tables" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const tcp =
+ \\ sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
+ \\ 0: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 23456 1 0000000000000000 100 0 0 10 0
+ \\ 1: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 23457 1 0000000000000000 100 0 0 10 0
+ \\ 2: 0F02000A:D2A4 5E7C2B8E:01BB 01 00000000:00000000 02:000A7A0C 00000000 1000 0 99999 2 0000000000000000 20 4 30 10 -1
+ ;
+ var list: std.ArrayList(Socket) = .empty;
+ try parseProcNet(a, tcp, .tcp, &list);
+ try std.testing.expectEqual(@as(usize, 2), list.items.len);
+ try std.testing.expectEqualStrings("0.0.0.0", list.items[0].address);
+ try std.testing.expectEqual(@as(u16, 22), list.items[0].port);
+ try std.testing.expectEqualStrings("127.0.0.1", list.items[1].address);
+ try std.testing.expectEqual(@as(u16, 631), list.items[1].port);
+ const tcp6 =
+ \\ sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
+ \\ 0: 00000000000000000000000000000000:0016 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 23458 1 0000000000000000 100 0 0 10 0
+ \\ 1: 00000000000000000000000001000000:0277 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 23459 1 0000000000000000 100 0 0 10 0
+ ;
+ try parseProcNet(a, tcp6, .tcp, &list);
+ try std.testing.expectEqualStrings("::", list.items[2].address);
+ try std.testing.expectEqualStrings("::1", list.items[3].address);
+ const udp =
+ \\ sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode ref pointer drops
+ \\ 100: 00000000:14E9 00000000:0000 07 00000000:00000000 00:00000000 00000000 95 0 31337 2 0000000000000000 0
+ ;
+ try parseProcNet(a, udp, .udp, &list);
+ try std.testing.expectEqual(@as(u16, 5353), list.items[4].port);
+ try std.testing.expectEqual(@as(u32, 95), list.items[4].uid);
+}
+
+test "sockstat" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const text =
+ \\0 sshd 812 4 tcp6 *:22 *:*
+ \\0 sshd 812 5 tcp4 *:22 *:*
+ \\0 cupsd 700 6 tcp4 127.0.0.1:631 *:*
+ \\1001 syncthing 9001 12 udp46 *:21027 *:*
+ \\0 ntpd 600 20 udp6 [fe80::1%em0]:123 *:*
+ ;
+ const sockets = try parseSockstat(a, text);
+ try std.testing.expectEqual(@as(usize, 5), sockets.len);
+ try std.testing.expectEqualStrings("::", sockets[0].address);
+ try std.testing.expectEqualStrings("sshd", sockets[0].process);
+ try std.testing.expectEqual(@as(i32, 812), sockets[0].pid);
+ try std.testing.expectEqualStrings("127.0.0.1", sockets[2].address);
+ try std.testing.expectEqual(@as(u32, 1001), sockets[3].uid);
+ try std.testing.expectEqual(@as(u16, 123), sockets[4].port);
+ const rows = try listeners(a, sockets, .{ .backend = .own, .running = true, .rules = &.{.{ .port = "22", .proto = .tcp }} });
+ try std.testing.expectEqual(@as(usize, 4), rows.len);
+ try std.testing.expectEqual(model.Verdict.everywhere, rows[0].verdict);
+ try std.testing.expectEqual(@as(u16, 22), rows[0].port);
+}
diff --git a/src/firewall/ufw.zig b/src/firewall/ufw.zig
new file mode 100644
index 0000000..b99a596
--- /dev/null
+++ b/src/firewall/ufw.zig
@@ -0,0 +1,291 @@
+//! ufw: its rules come from the tuples ufw keeps in `/etc/ufw/user.rules` and
+//! `user6.rules` (the format `ufw/backend_iptables.py` reads back), its
+//! defaults from `/etc/default/ufw`, its logging and boot state from
+//! `/etc/ufw/ufw.conf`; only "is it filtering now" needs `ufw status`.
+//! Changes are `ufw` commands built here from validated rules.
+const std = @import("std");
+const model = @import("model.zig");
+const services = @import("services.zig");
+const own = @import("own.zig");
+const Allocator = std.mem.Allocator;
+
+pub const rules_v4 = "/etc/ufw/user.rules";
+pub const rules_v6 = "/etc/ufw/user6.rules";
+pub const defaults = "/etc/default/ufw";
+pub const conf = "/etc/ufw/ufw.conf";
+pub const applications = "/etc/ufw/applications.d";
+
+fn unhex(a: Allocator, hex: []const u8) []const u8 {
+ if (hex.len % 2 != 0) return "";
+ const out = a.alloc(u8, hex.len / 2) catch return "";
+ _ = std.fmt.hexToBytes(out, hex) catch return "";
+ for (out) |*ch| if (ch.* < 0x20 or ch.* > 0x7e) {
+ ch.* = '?';
+ };
+ return out;
+}
+
+fn parseAction(word: []const u8) ?model.Action {
+ const base = if (std.mem.indexOfScalar(u8, word, '_')) |i| word[0..i] else word;
+ if (std.mem.eql(u8, base, "allow")) return .allow;
+ if (std.mem.eql(u8, base, "deny")) return .deny;
+ if (std.mem.eql(u8, base, "reject")) return .reject;
+ if (std.mem.eql(u8, base, "limit")) return .limit;
+ return null;
+}
+
+/// One tuple line ("### tuple ### allow tcp 22 0.0.0.0/0 any 0.0.0.0/0 in").
+pub fn parseTuple(a: Allocator, line: []const u8, v6: bool) ?model.Rule {
+ const prefix = "### tuple ###";
+ if (!std.mem.startsWith(u8, line, prefix)) return null;
+ var body = std.mem.trim(u8, line[prefix.len..], " \t\r");
+ var comment: []const u8 = "";
+ if (std.mem.indexOf(u8, body, " comment=")) |i| {
+ comment = unhex(a, std.mem.trim(u8, body[i + 9 ..], " "));
+ body = body[0..i];
+ }
+ var fields: [9][]const u8 = undefined;
+ var n: usize = 0;
+ var it = std.mem.tokenizeAny(u8, body, " \t");
+ while (it.next()) |field| {
+ if (n == fields.len) return null;
+ fields[n] = field;
+ n += 1;
+ }
+ if (n < 6) return null;
+ var rule: model.Rule = .{ .family = if (v6) .v6 else .v4, .comment = comment };
+ const action_word = fields[0];
+ if (std.mem.indexOfScalar(u8, action_word, ':') != null) rule.raw = a.dupe(u8, body) catch "";
+ rule.action = parseAction(if (std.mem.indexOfScalar(u8, action_word, ':')) |i| action_word[i + 1 ..] else action_word) orelse return null;
+ rule.proto = if (std.mem.eql(u8, fields[1], "tcp")) .tcp else if (std.mem.eql(u8, fields[1], "udp")) .udp else .both;
+ rule.port = if (std.mem.eql(u8, fields[2], "any")) "" else a.dupe(u8, fields[2]) catch "";
+ const dst = fields[3];
+ const sport = fields[4];
+ const src = fields[5];
+ if (!model.isAnywhere(dst) or !std.mem.eql(u8, sport, "any")) {
+ if (rule.raw.len == 0) rule.raw = a.dupe(u8, body) catch "";
+ }
+ rule.source = if (model.isAnywhere(src)) "" else a.dupe(u8, src) catch "";
+ if (n == 7 or n == 9) {
+ const dir = fields[n - 1];
+ rule.direction = if (std.mem.startsWith(u8, dir, "out")) .out else .in;
+ if (std.mem.indexOfScalar(u8, dir, '_')) |i| {
+ if (std.mem.indexOfScalar(u8, dir, '!') != null) {
+ if (rule.raw.len == 0) rule.raw = a.dupe(u8, body) catch "";
+ } else rule.iface = a.dupe(u8, dir[i + 1 ..]) catch "";
+ }
+ }
+ if (n >= 8) {
+ if (!std.mem.eql(u8, fields[6], "-")) rule.service = std.mem.replaceOwned(u8, a, fields[6], "%20", " ") catch "";
+ if (!std.mem.eql(u8, fields[7], "-") and rule.raw.len == 0) rule.raw = a.dupe(u8, body) catch "";
+ }
+ if (rule.service.len == 0) {
+ if (services.named(rule.proto, rule.port)) |s| rule.service = s.id;
+ }
+ return rule;
+}
+
+fn sameButFamily(x: model.Rule, y: model.Rule) bool {
+ return x.action == y.action and x.direction == y.direction and x.proto == y.proto and
+ std.mem.eql(u8, x.port, y.port) and x.source.len == 0 and y.source.len == 0 and
+ std.mem.eql(u8, x.iface, y.iface) and std.mem.eql(u8, x.service, y.service) and std.mem.eql(u8, x.raw, y.raw);
+}
+
+/// Rules from both files; a rule ufw wrote to both (no address) becomes one
+/// rule for both families, as `ufw status` shows it.
+pub fn parseRules(a: Allocator, v4_text: []const u8, v6_text: []const u8) ![]model.Rule {
+ var list: std.ArrayList(model.Rule) = .empty;
+ var lines = std.mem.splitScalar(u8, v4_text, '\n');
+ while (lines.next()) |line| if (parseTuple(a, std.mem.trim(u8, line, " \r"), false)) |rule| try list.append(a, rule);
+ const v4_count = list.items.len;
+ lines = std.mem.splitScalar(u8, v6_text, '\n');
+ outer: while (lines.next()) |line| {
+ const rule = parseTuple(a, std.mem.trim(u8, line, " \r"), true) orelse continue;
+ for (list.items[0..v4_count]) |*existing| {
+ if (existing.family == .v4 and sameButFamily(existing.*, rule)) {
+ existing.family = .both;
+ continue :outer;
+ }
+ }
+ try list.append(a, rule);
+ }
+ for (list.items, 0..) |*rule, i| rule.id = @intCast(i);
+ return list.toOwnedSlice(a);
+}
+
+fn value(text: []const u8, key: []const u8) []const u8 {
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (!std.mem.startsWith(u8, line, key) or line.len <= key.len or line[key.len] != '=') continue;
+ return std.mem.trim(u8, line[key.len + 1 ..], "\" ");
+ }
+ return "";
+}
+
+fn policy(word: []const u8) model.Policy {
+ if (std.ascii.eqlIgnoreCase(word, "ACCEPT")) return .accept;
+ if (std.ascii.eqlIgnoreCase(word, "REJECT")) return .reject;
+ return .drop;
+}
+
+pub const Settings = struct {
+ incoming: model.Policy,
+ outgoing: model.Policy,
+ forward: model.Policy,
+ boot: bool,
+ logging: model.Logging,
+};
+
+pub fn parseSettings(defaults_text: []const u8, conf_text: []const u8) Settings {
+ const level = value(conf_text, "LOGLEVEL");
+ return .{
+ .incoming = policy(value(defaults_text, "DEFAULT_INPUT_POLICY")),
+ .outgoing = policy(value(defaults_text, "DEFAULT_OUTPUT_POLICY")),
+ .forward = policy(value(defaults_text, "DEFAULT_FORWARD_POLICY")),
+ .boot = std.ascii.eqlIgnoreCase(value(conf_text, "ENABLED"), "yes"),
+ .logging = if (std.mem.eql(u8, level, "off") or level.len == 0) .off else if (std.mem.eql(u8, level, "medium")) .medium else if (std.mem.eql(u8, level, "high") or std.mem.eql(u8, level, "full")) .high else .low,
+ };
+}
+
+/// `ufw status` output: whether it is filtering now.
+pub fn active(status_text: []const u8) bool {
+ return std.mem.indexOf(u8, status_text, "Status: active") != null;
+}
+
+fn actionWord(action: model.Action) []const u8 {
+ return switch (action) {
+ .allow => "allow",
+ .deny => "deny",
+ .reject => "reject",
+ .limit => "limit",
+ };
+}
+
+pub fn policyWord(p: model.Policy) []const u8 {
+ return switch (p) {
+ .accept => "allow",
+ .drop => "deny",
+ .reject => "reject",
+ };
+}
+
+pub fn loggingWord(level: model.Logging) []const u8 {
+ return @tagName(level);
+}
+
+const lan_sources = [_][]const u8{ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7", "fe80::/10" };
+
+/// The `ufw` argv lists (after the program and `--force`) that add `rule`, or
+/// with `delete` remove it. A service expands into one rule per port and a
+/// "lan" source into one per private range, since ufw has neither.
+pub fn commands(a: Allocator, rule: model.Rule, delete: bool) ![]const []const []const u8 {
+ var out: std.ArrayList([]const []const u8) = .empty;
+ var buffer: [8]services.Port = undefined;
+ const ports = own.expand(rule, &buffer);
+ const sources: []const []const u8 = if (std.mem.eql(u8, rule.source, "lan")) &lan_sources else &.{rule.source};
+ for (ports) |p| {
+ const protos: []const model.Proto = if (p.proto == .both and std.mem.indexOfAny(u8, p.port, "-:") != null) &.{ .tcp, .udp } else &.{p.proto};
+ for (protos) |proto| for (sources) |src| {
+ if (rule.family == .v4 and std.mem.indexOfScalar(u8, src, ':') != null) continue;
+ if (rule.family == .v6 and src.len != 0 and std.mem.indexOfScalar(u8, src, ':') == null) continue;
+ var argv: std.ArrayList([]const u8) = .empty;
+ if (delete) try argv.append(a, "delete");
+ try argv.append(a, actionWord(rule.action));
+ try argv.append(a, if (rule.direction == .in) "in" else "out");
+ if (rule.iface.len != 0) try argv.appendSlice(a, &.{ "on", rule.iface });
+ if (proto != .both) try argv.appendSlice(a, &.{ "proto", if (proto == .tcp) "tcp" else "udp" });
+ const any: []const u8 = switch (rule.family) {
+ .both => "any",
+ .v4 => "0.0.0.0/0",
+ .v6 => "::/0",
+ };
+ const remote = if (src.len == 0) any else src;
+ if (rule.direction == .in) try argv.appendSlice(a, &.{ "from", remote, "to", "any" }) else try argv.appendSlice(a, &.{ "from", "any", "to", remote });
+ if (p.port.len != 0) {
+ const port = try std.mem.replaceOwned(u8, a, p.port, "-", ":");
+ try argv.appendSlice(a, &.{ "port", port });
+ }
+ if (!delete and rule.comment.len != 0) try argv.appendSlice(a, &.{ "comment", rule.comment });
+ try out.append(a, try argv.toOwnedSlice(a));
+ };
+ }
+ return out.toOwnedSlice(a);
+}
+
+/// Ports of an application profile file (`ports=22/tcp|80,443/tcp`).
+pub fn profilePorts(text: []const u8, name: []const u8) []const u8 {
+ var section = false;
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len > 1 and line[0] == '[') {
+ section = std.mem.eql(u8, line[1 .. line.len - 1], name);
+ continue;
+ }
+ if (section and std.mem.startsWith(u8, line, "ports=")) return line[6..];
+ }
+ return "";
+}
+
+test "tuples" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const v4 =
+ \\### RULES ###
+ \\
+ \\### tuple ### allow tcp 22 0.0.0.0/0 any 0.0.0.0/0 in
+ \\-A ufw-user-input -p tcp --dport 22 -j ACCEPT
+ \\### tuple ### deny any any 0.0.0.0/0 any 203.0.113.9 in comment=6e6f697379
+ \\### tuple ### allow any 1714:1764 0.0.0.0/0 any 192.168.0.0/16 in_wlan0
+ \\### tuple ### allow any 80,443 0.0.0.0/0 any 0.0.0.0/0 Nginx%20Full - in
+ \\### tuple ### route:allow any any 0.0.0.0/0 any 10.0.0.0/8 in_eth0!out_eth1
+ \\### tuple ### limit tcp 22 0.0.0.0/0 any 0.0.0.0/0 out
+ \\### END RULES ###
+ ;
+ const v6 =
+ \\### tuple ### allow tcp 22 ::/0 any ::/0 in
+ \\### tuple ### allow udp 5353 ::/0 any fe80::/10 in
+ ;
+ const rules = try parseRules(a, v4, v6);
+ try std.testing.expectEqual(@as(usize, 7), rules.len);
+ try std.testing.expectEqual(model.Family.both, rules[0].family);
+ try std.testing.expectEqualStrings("22", rules[0].port);
+ try std.testing.expectEqualStrings("ssh", rules[0].service);
+ try std.testing.expectEqual(model.Action.deny, rules[1].action);
+ try std.testing.expectEqualStrings("203.0.113.9", rules[1].source);
+ try std.testing.expectEqualStrings("noisy", rules[1].comment);
+ try std.testing.expectEqualStrings("wlan0", rules[2].iface);
+ try std.testing.expectEqualStrings("Nginx Full", rules[3].service);
+ try std.testing.expect(rules[4].raw.len != 0);
+ try std.testing.expectEqual(model.Direction.out, rules[5].direction);
+ try std.testing.expectEqual(model.Action.limit, rules[5].action);
+ try std.testing.expectEqual(model.Family.v6, rules[6].family);
+}
+
+test "settings" {
+ const s = parseSettings("DEFAULT_INPUT_POLICY=\"DROP\"\nDEFAULT_OUTPUT_POLICY=\"ACCEPT\"\nDEFAULT_FORWARD_POLICY=\"REJECT\"\n", "ENABLED=yes\nLOGLEVEL=medium\n");
+ try std.testing.expectEqual(model.Policy.drop, s.incoming);
+ try std.testing.expectEqual(model.Policy.accept, s.outgoing);
+ try std.testing.expectEqual(model.Policy.reject, s.forward);
+ try std.testing.expect(s.boot);
+ try std.testing.expectEqual(model.Logging.medium, s.logging);
+ try std.testing.expect(active("Status: active\n\nTo Action From"));
+ try std.testing.expect(!active("Status: inactive"));
+}
+
+test "commands" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const ssh = try commands(a, .{ .service = "ssh", .source = "lan", .comment = "ssh" }, false);
+ try std.testing.expectEqual(@as(usize, 5), ssh.len);
+ const first = try std.mem.join(a, " ", ssh[0]);
+ try std.testing.expectEqualStrings("allow in proto tcp from 10.0.0.0/8 to any port 22 comment ssh", first);
+ const kde = try commands(a, .{ .service = "kdeconnect" }, true);
+ try std.testing.expectEqual(@as(usize, 2), kde.len);
+ try std.testing.expectEqualStrings("delete allow in proto tcp from any to any port 1714:1764", try std.mem.join(a, " ", kde[0]));
+ const v6only = try commands(a, .{ .port = "80", .proto = .tcp, .family = .v6 }, false);
+ try std.testing.expectEqualStrings("allow in proto tcp from ::/0 to any port 80", try std.mem.join(a, " ", v6only[0]));
+}
diff --git a/src/firewall/validate.zig b/src/firewall/validate.zig
new file mode 100644
index 0000000..3aef60c
--- /dev/null
+++ b/src/firewall/validate.zig
@@ -0,0 +1,186 @@
+//! Checks every value a request carries before the helper renders it into a
+//! ruleset or a tool's argv. A value that passes contains no quotes, spaces,
+//! braces, semicolons or newlines, so no renderer has to escape anything.
+const std = @import("std");
+const model = @import("model.zig");
+
+/// "22", "8000-8100" (or "8000:8100"), or "" for any port. Lists are not
+/// accepted from requests; the helper splits catalog services itself.
+pub fn port(text: []const u8) bool {
+ if (text.len == 0) return true;
+ if (text.len > 11) return false;
+ const sep = std.mem.indexOfAny(u8, text, "-:");
+ if (sep) |i| {
+ const lo = number(text[0..i]) orelse return false;
+ const hi = number(text[i + 1 ..]) orelse return false;
+ return lo < hi;
+ }
+ return number(text) != null;
+}
+
+fn number(text: []const u8) ?u16 {
+ if (text.len == 0 or text.len > 5) return null;
+ for (text) |ch| if (!std.ascii.isDigit(ch)) return null;
+ const value = std.fmt.parseInt(u16, text, 10) catch return null;
+ return if (value == 0) null else value;
+}
+
+/// An IPv4 or IPv6 address with an optional prefix length.
+pub fn cidr(text: []const u8) bool {
+ if (text.len == 0 or text.len > 43) return false;
+ const slash = std.mem.indexOfScalar(u8, text, '/');
+ const address = if (slash) |i| text[0..i] else text;
+ const v6 = std.mem.indexOfScalar(u8, address, ':') != null;
+ if (slash) |i| {
+ const bits = std.fmt.parseInt(u8, text[i + 1 ..], 10) catch return false;
+ if (text[i + 1 ..].len == 0 or text[i + 1 ..].len > 3) return false;
+ if (bits > @as(u8, if (v6) 128 else 32)) return false;
+ }
+ if (v6) {
+ _ = std.Io.net.Ip6Address.parse(address, 0) catch return false;
+ return true;
+ }
+ _ = std.Io.net.Ip4Address.parse(address, 0) catch return false;
+ return true;
+}
+
+pub fn isV6(text: []const u8) bool {
+ return std.mem.indexOfScalar(u8, text, ':') != null;
+}
+
+/// "" (anywhere), "lan", or an address.
+pub fn source(text: []const u8) bool {
+ return text.len == 0 or std.mem.eql(u8, text, "lan") or cidr(text);
+}
+
+/// A kernel interface name: 1–15 of [A-Za-z0-9._-], not starting with '-'.
+pub fn iface(text: []const u8) bool {
+ if (text.len == 0 or text.len > 15 or text[0] == '-' or text[0] == '.') return false;
+ for (text) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '.' or ch == '_' or ch == '-')) return false;
+ return true;
+}
+
+/// A service or application profile name: [A-Za-z0-9._+-], up to 48.
+pub fn service(text: []const u8) bool {
+ if (text.len == 0 or text.len > 48 or text[0] == '-') return false;
+ for (text) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '.' or ch == '_' or ch == '-' or ch == '+')) return false;
+ return true;
+}
+
+/// Comments are free text but plain: up to 64 printable ASCII characters
+/// without quotes, backslashes or anything a ruleset treats specially.
+pub fn comment(text: []const u8) bool {
+ if (text.len > 64) return false;
+ for (text) |ch| {
+ if (ch < 0x20 or ch > 0x7e) return false;
+ if (std.mem.indexOfScalar(u8, "\"'\\`$;{}#", ch) != null) return false;
+ }
+ return true;
+}
+
+/// A NetworkManager connection uuid.
+pub fn uuid(text: []const u8) bool {
+ if (text.len != 36) return false;
+ for (text, 0..) |ch, i| {
+ if (i == 8 or i == 13 or i == 18 or i == 23) {
+ if (ch != '-') return false;
+ } else if (!std.ascii.isHex(ch)) return false;
+ }
+ return true;
+}
+
+/// A whole rule from a request. A rule needs a port or a service, except an
+/// address rule (`source` set, any port) which allows or blocks a host.
+pub fn rule(r: model.Rule) bool {
+ if (!port(r.port) or !source(r.source) or !comment(r.comment)) return false;
+ if (r.service.len != 0 and !service(r.service)) return false;
+ if (r.iface.len != 0 and !iface(r.iface)) return false;
+ if (r.raw.len != 0) return false;
+ if (r.port.len == 0 and r.service.len == 0 and r.source.len == 0) return false;
+ if (r.port.len != 0 and r.proto == .both and r.action == .limit) return false;
+ if (r.source.len != 0 and !std.mem.eql(u8, r.source, "lan")) {
+ if (r.family == .v4 and isV6(r.source)) return false;
+ if (r.family == .v6 and !isV6(r.source)) return false;
+ }
+ return true;
+}
+
+/// A rule sent back for deletion, as the helper listed it: its port may be a
+/// list ("80,443", from a manager's service), and a rule we could not map
+/// carries the manager's own text in `raw` (matched against the manager's
+/// listing before use).
+pub fn removal(r: model.Rule) bool {
+ if (r.raw.len != 0) {
+ if (r.raw.len > 512) return false;
+ for (r.raw) |ch| if (ch < 0x20 or ch > 0x7e or std.mem.indexOfScalar(u8, "\\`$;", ch) != null) return false;
+ return true;
+ }
+ if (r.port.len > 128) return false;
+ var parts = std.mem.splitScalar(u8, r.port, ',');
+ while (parts.next()) |part| if (!port(part) or (part.len == 0 and r.port.len != 0)) return false;
+ var copy = r;
+ copy.port = "";
+ if (copy.service.len == 0 and copy.source.len == 0) copy.service = "x";
+ return rule(copy);
+}
+
+test "ports" {
+ try std.testing.expect(port("22"));
+ try std.testing.expect(port("8000-8100"));
+ try std.testing.expect(port("1714:1764"));
+ try std.testing.expect(port(""));
+ try std.testing.expect(!port("0"));
+ try std.testing.expect(!port("65536"));
+ try std.testing.expect(!port("100-50"));
+ try std.testing.expect(!port("22 ; drop"));
+ try std.testing.expect(!port("80,443"));
+ try std.testing.expect(!port("-1"));
+}
+
+test "addresses" {
+ try std.testing.expect(cidr("192.168.1.0/24"));
+ try std.testing.expect(cidr("10.0.0.1"));
+ try std.testing.expect(cidr("2001:db8::/32"));
+ try std.testing.expect(cidr("fe80::1"));
+ try std.testing.expect(!cidr("192.168.1.0/33"));
+ try std.testing.expect(!cidr("2001:db8::/129"));
+ try std.testing.expect(!cidr("300.1.1.1"));
+ try std.testing.expect(!cidr("1.2.3.4/"));
+ try std.testing.expect(!cidr("1.2.3.4 } accept"));
+ try std.testing.expect(source("lan"));
+ try std.testing.expect(source(""));
+}
+
+test "names and comments" {
+ try std.testing.expect(iface("wlan0"));
+ try std.testing.expect(iface("enp3s0f1.100"));
+ try std.testing.expect(!iface("eth0\"; flush"));
+ try std.testing.expect(!iface("-rf"));
+ try std.testing.expect(!iface("abcdefghijklmnop"));
+ try std.testing.expect(comment("Web server for the lab"));
+ try std.testing.expect(!comment("a\" accept"));
+ try std.testing.expect(!comment("x\ny"));
+ try std.testing.expect(!comment("rm $(x)"));
+ try std.testing.expect(service("OpenSSH"));
+ try std.testing.expect(service("kdeconnect"));
+ try std.testing.expect(!service("a b"));
+ try std.testing.expect(uuid("0b6f2c55-1a4e-4c68-9d1d-2a5c4cbe1f00"));
+ try std.testing.expect(!uuid("0b6f2c55-1a4e-4c68-9d1d-2a5c4cbe1f0z"));
+}
+
+test "removals" {
+ try std.testing.expect(removal(.{ .port = "80,443", .service = "Nginx Full" }) == false);
+ try std.testing.expect(removal(.{ .port = "80,443", .service = "nginx" }));
+ try std.testing.expect(removal(.{ .raw = "rule family=\"ipv4\" source address=\"10.0.0.0/8\" accept" }));
+ try std.testing.expect(!removal(.{ .raw = "x; rm" }));
+ try std.testing.expect(!removal(.{ .port = "80,,443" }));
+}
+
+test "rules" {
+ try std.testing.expect(rule(.{ .port = "22", .proto = .tcp }));
+ try std.testing.expect(rule(.{ .service = "ssh" }));
+ try std.testing.expect(rule(.{ .source = "203.0.113.9", .action = .deny }));
+ try std.testing.expect(!rule(.{}));
+ try std.testing.expect(!rule(.{ .port = "22", .raw = "x" }));
+ try std.testing.expect(!rule(.{ .port = "22", .family = .v4, .source = "::1" }));
+}
diff --git a/src/firewall_helper/freebsd.zig b/src/firewall_helper/freebsd.zig
new file mode 100644
index 0000000..33bbb48
--- /dev/null
+++ b/src/firewall_helper/freebsd.zig
@@ -0,0 +1,206 @@
+//! FreeBSD: pf with our rules in the anchor "rediwm" (`pfctl -a rediwm`),
+//! which pf.conf evaluates first and loads at boot. We write pf.conf only to
+//! add those two lines (after showing the change) or, when there is none, a
+//! minimal one; everything else in it is the user's and stays read-only. ipfw
+//! is detected and shown, never changed.
+const std = @import("std");
+const fw = @import("firewall");
+const model = fw.model;
+const run = @import("run.zig");
+const state = @import("state.zig");
+const nm = @import("networks.zig");
+const Ctx = run.Ctx;
+const Request = fw.protocol.Request;
+
+fn rc(ctx: Ctx, name: []const u8) []const u8 {
+ const result = run.tryTool(ctx, "sysrc", &.{ "-n", name }) orelse return "";
+ return if (result.ok) std.mem.trim(u8, result.out, " \n") else "";
+}
+
+fn yes(text: []const u8) bool {
+ return std.ascii.eqlIgnoreCase(text, "YES");
+}
+
+fn confPath(ctx: Ctx) []const u8 {
+ const path = rc(ctx, "pf_rules");
+ return if (path.len != 0 and path[0] == '/') path else "/etc/pf.conf";
+}
+
+const Pf = struct { loaded: bool, enabled: bool, main_rules: u32, anchor_rules: u32 };
+
+fn pf(ctx: Ctx) Pf {
+ const info = run.tryTool(ctx, "pfctl", &.{ "-s", "info" }) orelse return .{ .loaded = false, .enabled = false, .main_rules = 0, .anchor_rules = 0 };
+ if (!info.ok) return .{ .loaded = false, .enabled = false, .main_rules = 0, .anchor_rules = 0 };
+ const main = run.tryTool(ctx, "pfctl", &.{"-sr"});
+ const anchor = run.tryTool(ctx, "pfctl", &.{ "-a", fw.own.table, "-sr" });
+ return .{
+ .loaded = true,
+ .enabled = fw.inventory.pfEnabled(info.out),
+ .main_rules = if (main) |r| fw.inventory.pfRuleCount(r.out) else 0,
+ .anchor_rules = if (anchor) |r| fw.inventory.pfRuleCount(r.out) else 0,
+ };
+}
+
+fn ipfwActive(ctx: Ctx) ?u32 {
+ const result = run.tryTool(ctx, "sysctl", &.{ "-n", "net.inet.ip.fw.enable" }) orelse return null;
+ if (!result.ok or !std.mem.startsWith(u8, std.mem.trim(u8, result.out, " \n"), "1")) return null;
+ const rules = run.tryTool(ctx, "ipfw", &.{"list"}) orelse return 0;
+ return @intCast(std.mem.count(u8, rules.out, "\n"));
+}
+
+pub fn status(ctx: Ctx) !model.Status {
+ const saved = state.load(ctx);
+ const p = pf(ctx);
+ const conf = run.readFile(ctx, confPath(ctx), 1 << 20);
+ const has = if (conf) |text| fw.own.pfConfHasAnchor(text) else @TypeOf(fw.own.pfConfHasAnchor("")){ .anchor = false, .load = false };
+ const view = try fw.own.status(ctx.a, saved);
+ var s = view;
+ s.system = .freebsd;
+ s.backend = if (run.tool(ctx, "pfctl") != null) .own else .none;
+ s.running = saved.enabled and p.enabled and has.anchor;
+ s.boot = saved.enabled and yes(rc(ctx, "pf_enable")) and has.load;
+ s.needs_anchor = conf != null and !has.anchor;
+ s.lockdown = state.lockdown(ctx);
+ s.capabilities = .{ .edit = true, .trust = true, .sources = true, .limit = true, .reject = true, .outgoing_rules = true, .outgoing_policy = true, .ping = true, .logging = true, .ssh_limit = true, .boot = true, .lockdown = true };
+ var foreign: std.ArrayList(model.Foreign) = .empty;
+ if (p.loaded and p.main_rules > 0) try foreign.append(ctx.a, .{ .owner = "pf.conf", .name = confPath(ctx), .rules = p.main_rules });
+ if (ipfwActive(ctx)) |count| {
+ try foreign.append(ctx.a, .{ .owner = "ipfw", .name = "ipfw", .rules = count });
+ s.conflicts = try ctx.a.dupe(model.Backend, &.{.foreign});
+ s.capabilities.edit = false;
+ }
+ s.foreign = foreign.items;
+ s.networks = try nm.networks(ctx, saved.home_ifaces);
+ const listing = run.tryTool(ctx, "sockstat", &.{ "-46lqn", "-P", "tcp,udp" });
+ const sockets = if (listing) |r| try fw.sockets.parseSockstat(ctx.a, r.out) else &.{};
+ s.listeners = try fw.sockets.listeners(ctx.a, sockets, s);
+ s.revert_in = state.revertIn(ctx);
+ return s;
+}
+
+fn applyAnchor(ctx: Ctx, saved: fw.own.State, lockdown: bool) !void {
+ var out: std.Io.Writer.Allocating = .init(ctx.a);
+ try fw.own.renderPf(&out.writer, saved, lockdown);
+ // The persistent file never holds a lockdown: a reboot ends it.
+ const path = if (lockdown) state.run_dir ++ "/lockdown.pf" else state.pf_path;
+ try run.writeAtomic(ctx, path, out.written(), 0o600);
+ const check = run.tryTool(ctx, "pfctl", &.{ "-n", "-a", fw.own.table, "-f", path }) orelse return error.ToolMissing;
+ if (!check.ok) return error.RulesetRejected;
+ try run.must(ctx, "pfctl", &.{ "-a", fw.own.table, "-f", path });
+}
+
+fn ensureConf(ctx: Ctx) !void {
+ const path = confPath(ctx);
+ if (run.readFile(ctx, path, 1 << 20)) |text| {
+ const has = fw.own.pfConfHasAnchor(text);
+ if (has.anchor and has.load) return;
+ try run.writeAtomic(ctx, try std.fmt.allocPrint(ctx.a, "{s}.rediwm-backup", .{path}), text, 0o600);
+ const updated = try fw.own.pfConfWithAnchor(ctx.a, text, state.pf_path);
+ try run.writeAtomic(ctx, path, updated, 0o600);
+ } else {
+ const text = try std.mem.replaceOwned(u8, ctx.a, fw.own.pf_conf, "@ANCHOR@", state.pf_path);
+ try run.writeAtomic(ctx, path, text, 0o600);
+ }
+ const check = run.tryTool(ctx, "pfctl", &.{ "-n", "-f", path }) orelse return error.ToolMissing;
+ if (!check.ok) return error.RulesetRejected;
+}
+
+fn startPf(ctx: Ctx) !void {
+ try run.must(ctx, "sysrc", &.{"pf_enable=YES"});
+ _ = run.tryTool(ctx, "kldload", &.{ "-n", "pf" });
+ try run.must(ctx, "pfctl", &.{ "-f", confPath(ctx) });
+ // "pf already enabled" is an error exit; the state is what matters.
+ _ = run.tryTool(ctx, "pfctl", &.{"-e"});
+ if (!pf(ctx).enabled) return error.ToolFailed;
+}
+
+fn logging(ctx: Ctx, on: bool) void {
+ if (on) {
+ run.must(ctx, "sysrc", &.{"pflog_enable=YES"}) catch return;
+ _ = run.tryTool(ctx, "service", &.{ "pflog", "start" });
+ }
+}
+
+pub fn change(ctx: Ctx, req: Request) !void {
+ var saved = state.load(ctx);
+ if (ipfwActive(ctx) != null and req.op != .lockdown) return error.Conflict;
+ switch (req.op) {
+ .enable => {
+ saved.enabled = true;
+ try state.save(ctx, saved);
+ try applyAnchor(ctx, saved, false);
+ try ensureConf(ctx);
+ try startPf(ctx);
+ logging(ctx, saved.logging != .off);
+ return;
+ },
+ .disable => {
+ saved.enabled = false;
+ try state.save(ctx, saved);
+ _ = run.tryTool(ctx, "pfctl", &.{ "-a", fw.own.table, "-F", "rules" });
+ _ = run.tryTool(ctx, "pfctl", &.{"-d"});
+ _ = run.tryTool(ctx, "sysrc", &.{"pf_enable=NO"});
+ return;
+ },
+ .lockdown => {
+ try state.setLockdown(ctx, req.on);
+ return applyAnchor(ctx, saved, req.on);
+ },
+ .set_defaults => {
+ if (req.incoming) |p| saved.incoming = p;
+ if (req.outgoing) |p| saved.outgoing = p;
+ },
+ .add_rule => {
+ for (saved.rules) |r| if (fw.own.sameRule(r, req.rule.?)) return;
+ var list: std.ArrayList(model.Rule) = .empty;
+ try list.appendSlice(ctx.a, saved.rules);
+ try list.append(ctx.a, req.rule.?);
+ saved.rules = list.items;
+ },
+ .remove_rule => {
+ var list: std.ArrayList(model.Rule) = .empty;
+ var found = false;
+ for (saved.rules) |r| {
+ if (!found and fw.own.sameRule(r, req.rule.?)) {
+ found = true;
+ continue;
+ }
+ try list.append(ctx.a, r);
+ }
+ if (!found) return error.NoSuchRule;
+ saved.rules = list.items;
+ },
+ .set_option => switch (req.option.?) {
+ .ping => saved.ping = req.on,
+ .ssh_limit => saved.ssh_limit = req.on,
+ .logging => {
+ saved.logging = req.logging orelse .off;
+ logging(ctx, saved.logging != .off);
+ },
+ .boot => {
+ try run.must(ctx, "sysrc", &.{if (req.on) "pf_enable=YES" else "pf_enable=NO"});
+ return;
+ },
+ },
+ .set_trust => {
+ var list: std.ArrayList([]const u8) = .empty;
+ for (saved.home_ifaces) |name| if (!std.mem.eql(u8, name, req.iface)) try list.append(ctx.a, name);
+ if (req.trust == .home) try list.append(ctx.a, req.iface);
+ saved.home_ifaces = list.items;
+ },
+ else => return error.Unsupported,
+ }
+ try state.save(ctx, saved);
+ if (saved.enabled) try applyAnchor(ctx, saved, state.lockdown(ctx));
+}
+
+pub fn sync(ctx: Ctx) !void {
+ const saved = state.load(ctx);
+ if (saved.enabled) try applyAnchor(ctx, saved, state.lockdown(ctx));
+}
+
+pub fn blocks(ctx: Ctx) ![]const model.Block {
+ if (!run.exists(ctx, "/var/log/pflog")) return &.{};
+ const result = run.tryTool(ctx, "tcpdump", &.{ "-n", "-e", "-tttt", "-r", "/var/log/pflog" }) orelse return &.{};
+ return fw.blocks.parse(ctx.a, result.out, true);
+}
diff --git a/src/firewall_helper/linux.zig b/src/firewall_helper/linux.zig
new file mode 100644
index 0000000..ffebeee
--- /dev/null
+++ b/src/firewall_helper/linux.zig
@@ -0,0 +1,508 @@
+//! Linux: detects which manager runs (our nftables table, firewalld, ufw,
+//! RediOS's generated ruleset), reads it into the model and applies changes
+//! through it. Our own table is written only when nothing else manages the
+//! firewall.
+const std = @import("std");
+const fw = @import("firewall");
+const model = fw.model;
+const run = @import("run.zig");
+const state = @import("state.zig");
+const nm = @import("networks.zig");
+const Ctx = run.Ctx;
+const Request = fw.protocol.Request;
+
+const Detected = struct {
+ tables: []const fw.inventory.Table = &.{},
+ own: fw.own.State = .{},
+ own_live: bool = false,
+ ufw_installed: bool = false,
+ ufw_active: bool = false,
+ firewalld_installed: bool = false,
+ firewalld_running: bool = false,
+ redi: bool = false,
+ nft: bool = false,
+};
+
+fn detect(ctx: Ctx) Detected {
+ var d: Detected = .{ .own = state.load(ctx) };
+ if (run.tryTool(ctx, "nft", &.{ "-j", "list", "ruleset" })) |result| {
+ d.nft = true;
+ if (result.ok) d.tables = fw.inventory.parseNft(ctx.a, result.out) catch &.{};
+ }
+ d.own_live = fw.inventory.hasTable(d.tables, fw.own.table);
+ d.redi = fw.inventory.hasTable(d.tables, "redi");
+ if (run.tool(ctx, "ufw") != null) {
+ d.ufw_installed = true;
+ if (run.tryTool(ctx, "ufw", &.{"status"})) |result| d.ufw_active = fw.ufw.active(result.out);
+ }
+ if (run.tool(ctx, "firewall-cmd") != null) {
+ d.firewalld_installed = true;
+ if (run.tryTool(ctx, "firewall-cmd", &.{"--state"})) |result| d.firewalld_running = result.ok;
+ }
+ return d;
+}
+
+fn manager(d: Detected) model.Backend {
+ if (d.own.enabled) return .own;
+ if (d.firewalld_running) return .firewalld;
+ if (d.ufw_active) return .ufw;
+ if (d.redi) return .redi;
+ if (d.ufw_installed) return .ufw;
+ if (d.firewalld_installed) return .firewalld;
+ if (d.nft) return .own;
+ return .none;
+}
+
+fn ownerName(backend: model.Backend) []const u8 {
+ return switch (backend) {
+ .ufw => "ufw",
+ .firewalld => "firewalld",
+ .redi => "RediOS",
+ else => "",
+ };
+}
+
+pub fn status(ctx: Ctx) !model.Status {
+ const d = detect(ctx);
+ const backend = manager(d);
+ var s: model.Status = .{ .system = .linux, .backend = backend };
+ var conflicts: std.ArrayList(model.Backend) = .empty;
+ var installed: std.ArrayList(model.Backend) = .empty;
+ const actives = [_]struct { b: model.Backend, on: bool }{
+ .{ .b = .own, .on = d.own.enabled },
+ .{ .b = .firewalld, .on = d.firewalld_running },
+ .{ .b = .ufw, .on = d.ufw_active },
+ .{ .b = .redi, .on = d.redi },
+ };
+ for (actives) |entry| if (entry.on and entry.b != backend) try conflicts.append(ctx.a, entry.b);
+ if (d.ufw_installed and !d.ufw_active) try installed.append(ctx.a, .ufw);
+ if (d.firewalld_installed and !d.firewalld_running) try installed.append(ctx.a, .firewalld);
+ if (d.nft) try installed.append(ctx.a, .own);
+ s.conflicts = conflicts.items;
+ s.installed = installed.items;
+
+ switch (backend) {
+ .own => {
+ const view = try fw.own.status(ctx.a, d.own);
+ s.incoming = view.incoming;
+ s.outgoing = view.outgoing;
+ s.forward = view.forward;
+ s.ping = view.ping;
+ s.logging = view.logging;
+ s.ssh_limit = view.ssh_limit;
+ s.rules = view.rules;
+ s.running = d.own.enabled and d.own_live;
+ s.boot = d.own.enabled and systemdEnabled(ctx, "rediwm-firewall.service");
+ s.capabilities = .{ .edit = true, .trust = true, .sources = true, .limit = true, .reject = true, .outgoing_rules = true, .outgoing_policy = true, .forward_policy = true, .ping = true, .logging = true, .ssh_limit = true, .boot = run.tool(ctx, "systemctl") != null, .lockdown = true };
+ },
+ .ufw => try ufwStatus(ctx, &s, d),
+ .firewalld => try firewalldStatus(ctx, &s, d),
+ .redi => {
+ s.running = true;
+ s.boot = true;
+ },
+ .none, .foreign => {},
+ }
+ if (conflicts.items.len != 0) s.capabilities.edit = false;
+ s.foreign = try fw.inventory.foreign(ctx.a, d.tables, ownerName(backend));
+ if (backend != .firewalld) s.lockdown = fw.inventory.hasTable(d.tables, fw.own.lockdown_table);
+ s.networks = try nm.networks(ctx, if (backend == .own) d.own.home_ifaces else &.{});
+ s.listeners = try listeners(ctx, s);
+ s.revert_in = state.revertIn(ctx);
+ return s;
+}
+
+fn systemdEnabled(ctx: Ctx, name: []const u8) bool {
+ const result = run.tryTool(ctx, "systemctl", &.{ "is-enabled", name }) orelse return false;
+ return result.ok;
+}
+
+fn listeners(ctx: Ctx, s: model.Status) ![]const model.Listener {
+ const proc = @import("../system_monitor/proc.zig");
+ var sockets: std.ArrayList(fw.sockets.Socket) = .empty;
+ inline for (.{ .{ "tcp", model.Proto.tcp }, .{ "tcp6", model.Proto.tcp }, .{ "udp", model.Proto.udp }, .{ "udp6", model.Proto.udp } }) |entry| {
+ if (proc.sockets.netTable(ctx.a, @field(proc.sockets.NetTable, entry[0]))) |text| try fw.sockets.parseProcNet(ctx.a, text, entry[1], &sockets);
+ }
+ const owners = proc.sockets.socketOwners(ctx.a) catch &.{};
+ for (sockets.items) |*sock| {
+ for (owners) |o| if (o.inode == sock.inode and sock.inode != 0) {
+ sock.pid = o.pid;
+ sock.process = o.name;
+ break;
+ };
+ }
+ return fw.sockets.listeners(ctx.a, sockets.items, s);
+}
+
+// ---------------------------------------------------------------- ufw
+
+fn ufwStatus(ctx: Ctx, s: *model.Status, d: Detected) !void {
+ const settings = fw.ufw.parseSettings(run.readFile(ctx, fw.ufw.defaults, 64 << 10) orelse "", run.readFile(ctx, fw.ufw.conf, 64 << 10) orelse "");
+ s.running = d.ufw_active;
+ s.boot = settings.boot;
+ s.incoming = settings.incoming;
+ s.outgoing = settings.outgoing;
+ s.forward = settings.forward;
+ s.logging = settings.logging;
+ const rules = try fw.ufw.parseRules(ctx.a, run.readFile(ctx, fw.ufw.rules_v4, 4 << 20) orelse "", run.readFile(ctx, fw.ufw.rules_v6, 4 << 20) orelse "");
+ s.rules = rules;
+ for (s.rules) |rule| if (rule.action == .limit and std.mem.eql(u8, rule.port, "22")) {
+ s.ssh_limit = true;
+ };
+ s.capabilities = .{ .edit = true, .sources = true, .limit = true, .reject = true, .outgoing_rules = true, .outgoing_policy = true, .forward_policy = true, .logging = true, .lockdown = true };
+}
+
+fn ufw(ctx: Ctx, args: []const []const u8) !void {
+ try run.must(ctx, "ufw", args);
+}
+
+fn ufwAdd(ctx: Ctx, rule: model.Rule) !void {
+ const commands = try fw.ufw.commands(ctx.a, rule, false);
+ const existing = try fw.ufw.parseRules(ctx.a, run.readFile(ctx, fw.ufw.rules_v4, 4 << 20) orelse "", run.readFile(ctx, fw.ufw.rules_v6, 4 << 20) orelse "");
+ const first = rule.action == .deny or rule.action == .reject;
+ for (commands) |argv| {
+ var full: std.ArrayList([]const u8) = .empty;
+ try full.append(ctx.a, "--force");
+ // ufw matches in order: a block goes before the allows it overrides.
+ if (first and existing.len != 0) try full.appendSlice(ctx.a, &.{ "insert", "1" });
+ try full.appendSlice(ctx.a, argv);
+ try ufw(ctx, full.items);
+ }
+}
+
+fn ufwRemove(ctx: Ctx, rule: model.Rule) !void {
+ if (rule.raw.len != 0) {
+ // Rules we cannot spell are deleted by their number in `ufw status
+ // numbered`: the IPv4 file's rules, then the IPv6 file's.
+ const v4 = try fw.ufw.parseRules(ctx.a, run.readFile(ctx, fw.ufw.rules_v4, 4 << 20) orelse "", "");
+ const v6 = try fw.ufw.parseRules(ctx.a, "", run.readFile(ctx, fw.ufw.rules_v6, 4 << 20) orelse "");
+ for ([_][]model.Rule{ v4, v6 }, 0..) |list, part| for (list, 0..) |r, i| {
+ if (!std.mem.eql(u8, r.raw, rule.raw)) continue;
+ const number = try std.fmt.allocPrint(ctx.a, "{d}", .{i + 1 + (if (part == 1) v4.len else 0)});
+ return ufw(ctx, &.{ "--force", "delete", number });
+ };
+ return error.NoSuchRule;
+ }
+ var spelled = rule;
+ if (spelled.service.len != 0 and fw.services.find(spelled.service) == null) spelled.service = "";
+ for (try fw.ufw.commands(ctx.a, spelled, true)) |argv| {
+ var full: std.ArrayList([]const u8) = .empty;
+ try full.append(ctx.a, "--force");
+ try full.appendSlice(ctx.a, argv);
+ try ufw(ctx, full.items);
+ }
+}
+
+// ---------------------------------------------------------------- firewalld
+
+fn fwcmd(ctx: Ctx, args: []const []const u8) !run.Result {
+ return run.tryTool(ctx, "firewall-cmd", args) orelse error.ToolMissing;
+}
+
+fn defaultZone(ctx: Ctx) []const u8 {
+ const result = fwcmd(ctx, &.{"--get-default-zone"}) catch return "public";
+ const name = std.mem.trim(u8, result.out, " \n");
+ return if (result.ok and fw.validate.service(name)) name else "public";
+}
+
+fn zone(ctx: Ctx, name: []const u8) ?fw.firewalld.Zone {
+ const arg = std.fmt.allocPrint(ctx.a, "--zone={s}", .{name}) catch return null;
+ const result = fwcmd(ctx, &.{ arg, "--list-all" }) catch return null;
+ if (!result.ok) return null;
+ return fw.firewalld.parseZone(ctx.a, result.out) catch null;
+}
+
+fn firewalldStatus(ctx: Ctx, s: *model.Status, d: Detected) !void {
+ s.running = d.firewalld_running;
+ s.boot = systemdEnabled(ctx, "firewalld.service");
+ s.capabilities = .{ .edit = true, .trust = true, .sources = true, .limit = true, .reject = true, .ping = true, .logging = true, .boot = true, .lockdown = true };
+ if (!d.firewalld_running) return;
+ const public_name = defaultZone(ctx);
+ s.zone = public_name;
+ const public = zone(ctx, public_name) orelse return;
+ const home = if (std.mem.eql(u8, public_name, fw.firewalld.home_zone)) null else zone(ctx, fw.firewalld.home_zone);
+ s.incoming = fw.firewalld.incoming(public.target);
+ s.ping = fw.firewalld.pingAllowed(public);
+ if (fwcmd(ctx, &.{"--get-log-denied"})) |result| s.logging = fw.firewalld.logging(result.out) else |_| {}
+ if (fwcmd(ctx, &.{"--query-panic"})) |result| s.lockdown = result.ok else |_| {}
+ const rules = try fw.firewalld.rules(ctx.a, public, home);
+ for (rules) |*rule| if (rule.port.len == 0 and rule.service.len != 0) resolveService(ctx, rule);
+ s.rules = rules;
+}
+
+/// A firewalld service's ports from its definition, so listeners can be
+/// matched against it.
+fn resolveService(ctx: Ctx, rule: *model.Rule) void {
+ if (!fw.validate.service(rule.service)) return;
+ for (fw.firewalld.service_dirs) |dir| {
+ const path = std.fmt.allocPrint(ctx.a, "{s}/{s}.xml", .{ dir, rule.service }) catch return;
+ const xml = run.readFile(ctx, path, 256 << 10) orelse continue;
+ const ports = fw.firewalld.servicePorts(ctx.a, xml) catch return;
+ if (ports.len == 0) return;
+ var joined: std.ArrayList(u8) = .empty;
+ var proto = ports[0].proto;
+ for (ports, 0..) |p, i| {
+ if (i != 0) joined.append(ctx.a, ',') catch return;
+ joined.appendSlice(ctx.a, p.port) catch return;
+ if (p.proto != proto) proto = .both;
+ }
+ rule.port = joined.items;
+ rule.proto = proto;
+ return;
+ }
+}
+
+fn zonesFor(ctx: Ctx, scope: model.Scope) []const []const u8 {
+ const public = defaultZone(ctx);
+ if (scope == .home or std.mem.eql(u8, public, fw.firewalld.home_zone)) return ctx.a.dupe([]const u8, &.{fw.firewalld.home_zone}) catch &.{};
+ return ctx.a.dupe([]const u8, &.{ public, fw.firewalld.home_zone }) catch &.{};
+}
+
+fn firewalldRule(ctx: Ctx, rule: model.Rule, delete: bool) !void {
+ // Status rules carry resolved port lists; a service rule is spelled by name.
+ var spelled = rule;
+ if (rule.service.len != 0 and rule.raw.len == 0) spelled.port = "";
+ const args = try fw.firewalld.arguments(ctx.a, spelled, delete);
+ for (zonesFor(ctx, rule.scope)) |z| {
+ const zone_arg = try std.fmt.allocPrint(ctx.a, "--zone={s}", .{z});
+ for (args) |arg| {
+ const result = try fwcmd(ctx, &.{ "--permanent", zone_arg, arg });
+ // Removing from a zone that never had it is not a failure.
+ if (!result.ok and !delete) return error.ToolFailed;
+ }
+ }
+ _ = try fwcmd(ctx, &.{"--reload"});
+}
+
+fn firewalldBoth(ctx: Ctx, arg: []const u8) !void {
+ for (zonesFor(ctx, .everywhere)) |z| {
+ const zone_arg = try std.fmt.allocPrint(ctx.a, "--zone={s}", .{z});
+ _ = try fwcmd(ctx, &.{ "--permanent", zone_arg, arg });
+ }
+ _ = try fwcmd(ctx, &.{"--reload"});
+}
+
+// ---------------------------------------------------------------- own
+
+const unit =
+ \\[Unit]
+ \\Description=RediWM firewall (nftables table inet rediwm)
+ \\DefaultDependencies=no
+ \\Before=network-pre.target
+ \\Wants=network-pre.target
+ \\After=local-fs.target
+ \\
+ \\[Service]
+ \\Type=oneshot
+ \\RemainAfterExit=yes
+ \\ExecStart=@HELPER@ sync
+ \\
+ \\[Install]
+ \\WantedBy=multi-user.target
+ \\
+;
+const unit_path = "/etc/systemd/system/rediwm-firewall.service";
+
+const dispatcher =
+ \\#!/bin/sh
+ \\# Keeps RediWM's firewall in step with each connection's trust (its
+ \\# NetworkManager zone). Installed and removed by RediWM Settings.
+ \\case "$2" in
+ \\up|down|vpn-up|vpn-down|reapply) exec @HELPER@ sync ;;
+ \\esac
+ \\exit 0
+ \\
+;
+const dispatcher_path = "/etc/NetworkManager/dispatcher.d/90-rediwm-firewall";
+
+fn fill(ctx: Ctx, template: []const u8) ![]const u8 {
+ return std.mem.replaceOwned(u8, ctx.a, template, "@HELPER@", state.helper_path);
+}
+
+/// Loads our table from the saved state, with the live trust from
+/// NetworkManager when it runs.
+fn applyOwn(ctx: Ctx, s: fw.own.State) !void {
+ var out: std.Io.Writer.Allocating = .init(ctx.a);
+ if (s.enabled) {
+ const live = nm.homeIfaces(ctx);
+ try fw.own.renderNft(&out.writer, s, live orelse s.home_ifaces);
+ } else {
+ try out.writer.print("table inet {s}\ndelete table inet {s}\n", .{ fw.own.table, fw.own.table });
+ }
+ try run.writeAtomic(ctx, state.nft_path, out.written(), 0o600);
+ const check = run.tryTool(ctx, "nft", &.{ "-c", "-f", state.nft_path }) orelse return error.ToolMissing;
+ if (!check.ok) return error.RulesetRejected;
+ try run.must(ctx, "nft", &.{ "-f", state.nft_path });
+}
+
+fn installHooks(ctx: Ctx, on: bool) void {
+ if (run.tool(ctx, "systemctl") != null) {
+ if (on) {
+ const text = fill(ctx, unit) catch return;
+ run.writeAtomic(ctx, unit_path, text, 0o644) catch return;
+ run.must(ctx, "systemctl", &.{"daemon-reload"}) catch {};
+ run.must(ctx, "systemctl", &.{ "enable", "rediwm-firewall.service" }) catch {};
+ } else if (run.exists(ctx, unit_path)) {
+ run.must(ctx, "systemctl", &.{ "disable", "rediwm-firewall.service" }) catch {};
+ }
+ }
+ if (run.exists(ctx, "/etc/NetworkManager/dispatcher.d")) {
+ if (on) {
+ const text = fill(ctx, dispatcher) catch return;
+ run.writeAtomic(ctx, dispatcher_path, text, 0o755) catch {};
+ } else run.remove(ctx, dispatcher_path);
+ }
+}
+
+fn ownChange(ctx: Ctx, req: Request) !void {
+ var s = state.load(ctx);
+ switch (req.op) {
+ .enable => s.enabled = true,
+ .disable => s.enabled = false,
+ .set_defaults => {
+ if (req.incoming) |p| s.incoming = p;
+ if (req.outgoing) |p| s.outgoing = p;
+ if (req.forward) |p| s.forward = p;
+ },
+ .add_rule => {
+ const rule = req.rule.?;
+ for (s.rules) |r| if (fw.own.sameRule(r, rule)) return;
+ if (s.rules.len >= model.max_rules) return error.TooManyRules;
+ var list: std.ArrayList(model.Rule) = .empty;
+ try list.appendSlice(ctx.a, s.rules);
+ try list.append(ctx.a, rule);
+ s.rules = list.items;
+ },
+ .remove_rule => {
+ var list: std.ArrayList(model.Rule) = .empty;
+ var found = false;
+ for (s.rules) |r| {
+ if (!found and fw.own.sameRule(r, req.rule.?)) {
+ found = true;
+ continue;
+ }
+ try list.append(ctx.a, r);
+ }
+ if (!found) return error.NoSuchRule;
+ s.rules = list.items;
+ },
+ .set_option => switch (req.option.?) {
+ .ping => s.ping = req.on,
+ .ssh_limit => s.ssh_limit = req.on,
+ .logging => s.logging = req.logging orelse .off,
+ .boot => {
+ if (run.tool(ctx, "systemctl") == null) return error.Unsupported;
+ if (req.on) installHooks(ctx, true) else run.must(ctx, "systemctl", &.{ "disable", "rediwm-firewall.service" }) catch {};
+ return;
+ },
+ },
+ .set_trust => if (req.uuid.len == 0) {
+ var list: std.ArrayList([]const u8) = .empty;
+ for (s.home_ifaces) |name| if (!std.mem.eql(u8, name, req.iface)) try list.append(ctx.a, name);
+ if (req.trust == .home) try list.append(ctx.a, req.iface);
+ s.home_ifaces = list.items;
+ },
+ else => return error.Unsupported,
+ }
+ try state.save(ctx, s);
+ try applyOwn(ctx, s);
+ if (req.op == .enable or req.op == .disable) installHooks(ctx, s.enabled);
+}
+
+/// `sync`: reload our table (boot, NetworkManager changes).
+pub fn sync(ctx: Ctx) !void {
+ const s = state.load(ctx);
+ if (!s.enabled) return;
+ try applyOwn(ctx, s);
+ if (state.lockdown(ctx)) try lockdownNft(ctx, true);
+}
+
+fn lockdownNft(ctx: Ctx, on: bool) !void {
+ var out: std.Io.Writer.Allocating = .init(ctx.a);
+ try fw.own.renderLockdownNft(&out.writer, on);
+ const path = state.run_dir ++ "/lockdown.nft";
+ try run.writeAtomic(ctx, path, out.written(), 0o600);
+ try run.must(ctx, "nft", &.{ "-f", path });
+ try state.setLockdown(ctx, on);
+}
+
+// ---------------------------------------------------------------- changes
+
+pub fn change(ctx: Ctx, req: Request) !void {
+ const d = detect(ctx);
+ var backend = manager(d);
+ // Turn on with nothing set up: what the page asked for, if installed.
+ if (req.op == .enable and !d.own.enabled and !d.firewalld_running and !d.ufw_active and !d.redi) {
+ backend = switch (req.backend) {
+ .ufw => if (d.ufw_installed) .ufw else return error.Unsupported,
+ .firewalld => if (d.firewalld_installed) .firewalld else return error.Unsupported,
+ else => if (d.nft) .own else return error.ToolMissing,
+ };
+ }
+ if (req.op != .enable and req.op != .lockdown) {
+ for ([_]bool{ d.own.enabled and backend != .own, d.firewalld_running and backend != .firewalld, d.ufw_active and backend != .ufw }) |other| {
+ if (other) return error.Conflict;
+ }
+ }
+ if (req.op == .set_trust and req.uuid.len != 0) {
+ try nm.setTrust(ctx, req.uuid, req.trust);
+ if (backend == .own) try sync(ctx);
+ return;
+ }
+ if (req.op == .lockdown) {
+ if (backend == .firewalld and d.firewalld_running) {
+ _ = try fwcmd(ctx, &.{if (req.on) "--panic-on" else "--panic-off"});
+ return;
+ }
+ return lockdownNft(ctx, req.on);
+ }
+ switch (backend) {
+ .own => try ownChange(ctx, req),
+ .ufw => switch (req.op) {
+ .enable => try ufw(ctx, &.{ "--force", "enable" }),
+ .disable => try ufw(ctx, &.{"disable"}),
+ .set_defaults => {
+ if (req.incoming) |p| try ufw(ctx, &.{ "default", fw.ufw.policyWord(p), "incoming" });
+ if (req.outgoing) |p| try ufw(ctx, &.{ "default", fw.ufw.policyWord(p), "outgoing" });
+ if (req.forward) |p| try ufw(ctx, &.{ "default", fw.ufw.policyWord(p), "routed" });
+ },
+ .add_rule => try ufwAdd(ctx, req.rule.?),
+ .remove_rule => try ufwRemove(ctx, req.rule.?),
+ .set_option => switch (req.option.?) {
+ .logging => try ufw(ctx, &.{ "logging", fw.ufw.loggingWord(req.logging orelse .off) }),
+ else => return error.Unsupported,
+ },
+ else => return error.Unsupported,
+ },
+ .firewalld => switch (req.op) {
+ .enable => try run.must(ctx, "systemctl", &.{ "enable", "--now", "firewalld.service" }),
+ .disable => try run.must(ctx, "systemctl", &.{ "disable", "--now", "firewalld.service" }),
+ .set_defaults => if (req.incoming) |p| {
+ const arg = try std.fmt.allocPrint(ctx.a, "--set-target={s}", .{fw.firewalld.target(p)});
+ const zone_arg = try std.fmt.allocPrint(ctx.a, "--zone={s}", .{defaultZone(ctx)});
+ const result = try fwcmd(ctx, &.{ "--permanent", zone_arg, arg });
+ if (!result.ok) return error.ToolFailed;
+ _ = try fwcmd(ctx, &.{"--reload"});
+ },
+ .add_rule => try firewalldRule(ctx, req.rule.?, false),
+ .remove_rule => try firewalldRule(ctx, req.rule.?, true),
+ .set_option => switch (req.option.?) {
+ .ping => try firewalldBoth(ctx, if (req.on) "--remove-icmp-block=echo-request" else "--add-icmp-block=echo-request"),
+ .logging => {
+ const arg = try std.fmt.allocPrint(ctx.a, "--set-log-denied={s}", .{fw.firewalld.logWord(req.logging orelse .off)});
+ if (!(try fwcmd(ctx, &.{arg})).ok) return error.ToolFailed;
+ },
+ .boot => try run.must(ctx, "systemctl", &.{ if (req.on) "enable" else "disable", "firewalld.service" }),
+ else => return error.Unsupported,
+ },
+ else => return error.Unsupported,
+ },
+ .redi => return error.ManagedElsewhere,
+ .none, .foreign => return error.Unsupported,
+ }
+}
+
+pub fn blocks(ctx: Ctx) ![]const model.Block {
+ const result = run.tryTool(ctx, "journalctl", &.{ "-k", "-o", "short-iso", "--no-pager", "-n", "400", "-g", fw.blocks.journal_pattern, "--since", "-24h" }) orelse return &.{};
+ return fw.blocks.parse(ctx.a, result.out, false);
+}
diff --git a/src/firewall_helper/networks.zig b/src/firewall_helper/networks.zig
new file mode 100644
index 0000000..81dfcfa
--- /dev/null
+++ b/src/firewall_helper/networks.zig
@@ -0,0 +1,115 @@
+//! Networks and their trust. With NetworkManager a network is an active
+//! connection and its trust is the connection's zone (`connection.zone`,
+//! which firewalld follows natively and our dispatcher reads for our table).
+//! Without it, a network is an interface and its trust is in our state.
+const std = @import("std");
+const builtin = @import("builtin");
+const fw = @import("firewall");
+const model = fw.model;
+const run = @import("run.zig");
+const Ctx = run.Ctx;
+
+const Active = struct { name: []const u8, uuid: []const u8, device: []const u8, kind: []const u8 };
+
+/// Splits one `nmcli -t` line, honouring `\:` and `\\` escapes.
+fn terse(a: std.mem.Allocator, line: []const u8, out: [][]const u8) usize {
+ var n: usize = 0;
+ var field: std.ArrayList(u8) = .empty;
+ var i: usize = 0;
+ while (i < line.len) : (i += 1) {
+ const ch = line[i];
+ if (ch == '\\' and i + 1 < line.len) {
+ i += 1;
+ field.append(a, line[i]) catch return n;
+ } else if (ch == ':') {
+ if (n == out.len) return n;
+ out[n] = field.toOwnedSlice(a) catch "";
+ n += 1;
+ } else field.append(a, ch) catch return n;
+ }
+ if (n < out.len) {
+ out[n] = field.toOwnedSlice(a) catch "";
+ n += 1;
+ }
+ return n;
+}
+
+fn active(ctx: Ctx) ?[]Active {
+ const result = run.tryTool(ctx, "nmcli", &.{ "-t", "-f", "NAME,UUID,DEVICE,TYPE", "connection", "show", "--active" }) orelse return null;
+ if (!result.ok) return null;
+ var list: std.ArrayList(Active) = .empty;
+ var lines = std.mem.splitScalar(u8, result.out, '\n');
+ while (lines.next()) |line| {
+ var fields: [4][]const u8 = undefined;
+ if (terse(ctx.a, line, &fields) != 4) continue;
+ if (std.mem.eql(u8, fields[3], "loopback") or !fw.validate.uuid(fields[1])) continue;
+ list.append(ctx.a, .{ .name = fields[0], .uuid = fields[1], .device = fields[2], .kind = fields[3] }) catch continue;
+ }
+ return list.items;
+}
+
+fn zoneTrust(ctx: Ctx, uuid: []const u8) model.Trust {
+ const result = run.tryTool(ctx, "nmcli", &.{ "-g", "connection.zone", "connection", "show", "uuid", uuid }) orelse return .public;
+ const zone = std.mem.trim(u8, result.out, " \n");
+ return if (std.mem.eql(u8, zone, "home") or std.mem.eql(u8, zone, "trusted") or std.mem.eql(u8, zone, "internal") or std.mem.eql(u8, zone, "work")) .home else .public;
+}
+
+fn interfaces(ctx: Ctx) []const []const u8 {
+ if (builtin.os.tag == .freebsd) {
+ const result = run.tryTool(ctx, "ifconfig", &.{"-l"}) orelse return &.{};
+ var list: std.ArrayList([]const u8) = .empty;
+ var it = std.mem.tokenizeAny(u8, result.out, " \n");
+ while (it.next()) |name| {
+ if (std.mem.startsWith(u8, name, "lo") or std.mem.startsWith(u8, name, "pflog") or std.mem.startsWith(u8, name, "enc") or std.mem.startsWith(u8, name, "pfsync")) continue;
+ list.append(ctx.a, name) catch continue;
+ }
+ return list.items;
+ }
+ var list: std.ArrayList([]const u8) = .empty;
+ for (run.list(ctx, "/sys/class/net")) |name| {
+ if (std.mem.eql(u8, name, "lo") or !fw.validate.iface(name)) continue;
+ list.append(ctx.a, name) catch continue;
+ }
+ return list.items;
+}
+
+fn contains(names: []const []const u8, name: []const u8) bool {
+ for (names) |x| if (std.mem.eql(u8, x, name)) return true;
+ return false;
+}
+
+/// The networks the page lists. `home_ifaces` is our state's per-interface
+/// trust, used where there is no NetworkManager.
+pub fn networks(ctx: Ctx, home_ifaces: []const []const u8) ![]const model.Network {
+ var out: std.ArrayList(model.Network) = .empty;
+ if (active(ctx)) |connections| {
+ for (connections) |conn| try out.append(ctx.a, .{ .name = conn.name, .iface = conn.device, .uuid = conn.uuid, .trust = zoneTrust(ctx, conn.uuid), .active = true });
+ return out.items;
+ }
+ for (interfaces(ctx)) |name| try out.append(ctx.a, .{ .name = name, .iface = name, .trust = if (contains(home_ifaces, name)) .home else .public, .active = true });
+ return out.items;
+}
+
+/// Interfaces of the active connections trusted as home; null without
+/// NetworkManager (the caller then uses its saved per-interface trust).
+pub fn homeIfaces(ctx: Ctx) ?[]const []const u8 {
+ const connections = active(ctx) orelse return null;
+ var out: std.ArrayList([]const u8) = .empty;
+ for (connections) |conn| {
+ if (conn.device.len == 0 or !fw.validate.iface(conn.device)) continue;
+ if (zoneTrust(ctx, conn.uuid) == .home) out.append(ctx.a, conn.device) catch continue;
+ }
+ return out.items;
+}
+
+/// Sets a connection's zone and reapplies it, so firewalld (or our
+/// dispatcher) sees the change now rather than at the next connection.
+pub fn setTrust(ctx: Ctx, uuid: []const u8, trust: model.Trust) !void {
+ if (!fw.validate.uuid(uuid)) return error.InvalidRequest;
+ try run.must(ctx, "nmcli", &.{ "connection", "modify", "uuid", uuid, "connection.zone", if (trust == .home) "home" else "public" });
+ if (active(ctx)) |connections| for (connections) |conn| {
+ if (std.mem.eql(u8, conn.uuid, uuid) and conn.device.len != 0 and fw.validate.iface(conn.device)) {
+ run.must(ctx, "nmcli", &.{ "device", "reapply", conn.device }) catch {};
+ }
+ };
+}
diff --git a/src/firewall_helper/run.zig b/src/firewall_helper/run.zig
new file mode 100644
index 0000000..3fd90b7
--- /dev/null
+++ b/src/firewall_helper/run.zig
@@ -0,0 +1,140 @@
+//! Running system tools and touching root-owned files for the firewall
+//! helper. Tools are found only in root-owned system directories and run
+//! with a fixed environment (C locale, so their output parses), never a
+//! shell.
+const std = @import("std");
+const c = @import("c");
+const Allocator = std.mem.Allocator;
+
+pub const Ctx = struct {
+ a: Allocator,
+ io: std.Io,
+ env: *const std.process.Environ.Map,
+};
+
+const dirs = [_][]const u8{ "/usr/sbin", "/sbin", "/usr/bin", "/bin", "/usr/local/sbin", "/usr/local/bin" };
+
+/// `name` in the system directories, or null.
+pub fn tool(ctx: Ctx, comptime name: []const u8) ?[]const u8 {
+ inline for (dirs) |dir| {
+ const path = dir ++ "/" ++ name;
+ if (std.Io.Dir.accessAbsolute(ctx.io, path, .{ .execute = true })) |_| return path else |_| {}
+ }
+ return null;
+}
+
+pub const Result = struct {
+ ok: bool,
+ code: u8,
+ out: []const u8,
+ err: []const u8,
+};
+
+pub fn environment(a: Allocator) !std.process.Environ.Map {
+ var env: std.process.Environ.Map = .init(a);
+ try env.put("PATH", "/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/sbin:/usr/local/bin");
+ try env.put("LC_ALL", "C");
+ try env.put("LANG", "C");
+ return env;
+}
+
+/// Runs argv (argv[0] absolute) and collects its output. A tool that cannot
+/// start, times out or dies from a signal is `ok = false` with code 255.
+pub fn run(ctx: Ctx, argv: []const []const u8) Result {
+ const result = std.process.run(ctx.a, ctx.io, .{
+ .argv = argv,
+ .environ_map = ctx.env,
+ .stdout_limit = .limited(8 << 20),
+ .stderr_limit = .limited(64 << 10),
+ .timeout = .{ .duration = .{ .raw = .fromSeconds(40), .clock = .awake } },
+ }) catch |err| {
+ std.log.err("{s}: {s}", .{ argv[0], @errorName(err) });
+ return .{ .ok = false, .code = 255, .out = "", .err = "" };
+ };
+ const code: u8 = switch (result.term) {
+ .exited => |status| status,
+ else => 255,
+ };
+ if (code != 0) std.log.info("{s} exited {d}: {s}", .{ argv[0], code, std.mem.trim(u8, result.stderr, " \n") });
+ return .{ .ok = code == 0, .code = code, .out = result.stdout, .err = result.stderr };
+}
+
+/// Like `run` with a tool looked up by name; null when it is not installed.
+pub fn tryTool(ctx: Ctx, comptime name: []const u8, args: []const []const u8) ?Result {
+ const path = tool(ctx, name) orelse return null;
+ const argv = ctx.a.alloc([]const u8, args.len + 1) catch return null;
+ argv[0] = path;
+ @memcpy(argv[1..], args);
+ return run(ctx, argv);
+}
+
+/// Fails unless the tool exists and exits 0.
+pub fn must(ctx: Ctx, comptime name: []const u8, args: []const []const u8) !void {
+ const result = tryTool(ctx, name, args) orelse return error.ToolMissing;
+ if (!result.ok) return error.ToolFailed;
+}
+
+pub fn readFile(ctx: Ctx, path: []const u8, limit: usize) ?[]const u8 {
+ return std.Io.Dir.cwd().readFileAlloc(ctx.io, path, ctx.a, .limited(limit)) catch null;
+}
+
+pub fn exists(ctx: Ctx, path: []const u8) bool {
+ std.Io.Dir.accessAbsolute(ctx.io, path, .{}) catch return false;
+ return true;
+}
+
+/// Writes `data` to `path` through a temporary file in the same directory and
+/// a rename, so a reader sees the old or the new file, never half of one.
+pub fn writeAtomic(ctx: Ctx, path: []const u8, data: []const u8, mode: c.mode_t) !void {
+ const dir = std.fs.path.dirname(path) orelse return error.BadPath;
+ try makePath(ctx, dir);
+ const tmp = try std.fmt.allocPrintSentinel(ctx.a, "{s}.new", .{path}, 0);
+ const fd = c.open(tmp.ptr, c.O_WRONLY | c.O_CREAT | c.O_TRUNC | c.O_CLOEXEC | c.O_NOFOLLOW, @as(c_uint, mode));
+ if (fd < 0) return error.WriteFailed;
+ var done: usize = 0;
+ while (done < data.len) {
+ const n = c.write(fd, data.ptr + done, data.len - done);
+ if (n < 0 and std.posix.errno(n) == .INTR) continue;
+ if (n <= 0) {
+ _ = c.close(fd);
+ return error.WriteFailed;
+ }
+ done += @intCast(n);
+ }
+ _ = c.fchmod(fd, @intCast(mode));
+ if (c.fsync(fd) != 0) {
+ _ = c.close(fd);
+ return error.WriteFailed;
+ }
+ _ = c.close(fd);
+ const final = try ctx.a.dupeSentinel(u8, path, 0);
+ if (c.rename(tmp.ptr, final.ptr) != 0) return error.WriteFailed;
+}
+
+pub fn makePath(ctx: Ctx, dir: []const u8) !void {
+ std.Io.Dir.cwd().createDirPath(ctx.io, dir) catch return error.WriteFailed;
+}
+
+pub fn remove(ctx: Ctx, path: []const u8) void {
+ std.Io.Dir.cwd().deleteFile(ctx.io, path) catch {};
+}
+
+/// Entries of a directory (names only), or empty.
+pub fn list(ctx: Ctx, path: []const u8) []const []const u8 {
+ var names: std.ArrayList([]const u8) = .empty;
+ const z = ctx.a.dupeSentinel(u8, path, 0) catch return &.{};
+ const dir = c.opendir(z.ptr) orelse return &.{};
+ defer _ = c.closedir(dir);
+ while (c.readdir(dir)) |entry| {
+ const name = std.mem.sliceTo(entry.*.d_name[0..], 0);
+ if (name.len == 0 or name[0] == '.') continue;
+ names.append(ctx.a, ctx.a.dupe(u8, name) catch continue) catch continue;
+ }
+ return names.toOwnedSlice(ctx.a) catch &.{};
+}
+
+pub fn nowSeconds() i64 {
+ var ts: c.struct_timespec = undefined;
+ _ = c.clock_gettime(c.CLOCK_REALTIME, &ts);
+ return @intCast(ts.tv_sec);
+}
diff --git a/src/firewall_helper/state.zig b/src/firewall_helper/state.zig
new file mode 100644
index 0000000..47f9bcd
--- /dev/null
+++ b/src/firewall_helper/state.zig
@@ -0,0 +1,94 @@
+//! Files the helper owns: our firewall's saved state and rendered rules under
+//! `${sysconfdir}/rediwm`, and run state (a pending revert, lockdown) under
+//! `${rundir}/rediwm-firewall`. All root-only (0600 files, 0700 directories).
+const std = @import("std");
+const c = @import("c");
+const fw = @import("firewall");
+const paths = @import("install_paths");
+const run = @import("run.zig");
+
+pub const conf_dir = paths.sysconfdir ++ "/rediwm";
+pub const state_path = conf_dir ++ "/firewall.json";
+pub const nft_path = conf_dir ++ "/firewall.nft";
+pub const pf_path = conf_dir ++ "/pf.rediwm.conf";
+pub const run_dir = paths.rundir ++ "/rediwm-firewall";
+pub const revert_path = run_dir ++ "/revert.json";
+pub const lockdown_path = run_dir ++ "/lockdown";
+pub const helper_path = paths.bin ++ "/rediwm-firewall-helper";
+
+pub fn load(ctx: run.Ctx) fw.own.State {
+ const text = run.readFile(ctx, state_path, 1 << 20) orelse return .{};
+ const parsed = std.json.parseFromSliceLeaky(fw.own.State, ctx.a, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }) catch return .{};
+ // A file edited by hand must not smuggle text into a ruleset.
+ var rules: std.ArrayList(fw.model.Rule) = .empty;
+ for (parsed.rules) |rule| if (fw.validate.rule(rule)) rules.append(ctx.a, rule) catch {};
+ var home: std.ArrayList([]const u8) = .empty;
+ for (parsed.home_ifaces) |name| if (fw.validate.iface(name)) home.append(ctx.a, name) catch {};
+ var state = parsed;
+ state.rules = rules.items;
+ state.home_ifaces = home.items;
+ return state;
+}
+
+pub fn save(ctx: run.Ctx, state: fw.own.State) !void {
+ const json = try std.json.Stringify.valueAlloc(ctx.a, state, .{ .whitespace = .indent_2 });
+ _ = c.umask(0o077);
+ try run.writeAtomic(ctx, state_path, json, 0o600);
+}
+
+pub fn lockdown(ctx: run.Ctx) bool {
+ return run.exists(ctx, lockdown_path);
+}
+
+pub fn setLockdown(ctx: run.Ctx, on: bool) !void {
+ if (on) try run.writeAtomic(ctx, lockdown_path, "1\n", 0o600) else run.remove(ctx, lockdown_path);
+}
+
+const Revert = struct { pid: i32 = 0, deadline: i64 = 0, undo: fw.protocol.Request = .{} };
+
+fn readRevert(ctx: run.Ctx) ?Revert {
+ const text = run.readFile(ctx, revert_path, 64 << 10) orelse return null;
+ const value = std.json.parseFromSliceLeaky(Revert, ctx.a, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }) catch return null;
+ if (value.pid <= 1 or c.kill(value.pid, 0) != 0) return null;
+ return value;
+}
+
+/// Seconds until a pending change reverts, or 0.
+pub fn revertIn(ctx: run.Ctx) u32 {
+ const value = readRevert(ctx) orelse return 0;
+ const left = value.deadline - run.nowSeconds();
+ return if (left > 0) @intCast(left) else 0;
+}
+
+/// Keeps the change: stops the watchdog.
+pub fn confirm(ctx: run.Ctx) void {
+ if (readRevert(ctx)) |value| _ = c.kill(value.pid, c.SIGTERM);
+ run.remove(ctx, revert_path);
+}
+
+pub const Perform = *const fn (run.Ctx, fw.protocol.Request) anyerror!void;
+
+/// Forks a watchdog that applies `undo` after `seconds` unless `confirm`
+/// stops it first. It detaches from Settings' pipe so the page's request
+/// finishes now, and outlives the helper run that started it.
+pub fn arm(ctx: run.Ctx, undo: fw.protocol.Request, seconds: u32, perform: Perform) !void {
+ confirm(ctx);
+ const pid = c.fork();
+ if (pid < 0) return error.ForkFailed;
+ if (pid == 0) {
+ _ = c.setsid();
+ const null_fd = c.open("/dev/null", c.O_RDWR);
+ if (null_fd >= 0) {
+ _ = c.dup2(null_fd, 0);
+ _ = c.dup2(null_fd, 1);
+ _ = c.dup2(null_fd, 2);
+ }
+ var remaining: c.struct_timespec = .{ .tv_sec = @intCast(seconds), .tv_nsec = 0 };
+ while (c.nanosleep(&remaining, &remaining) != 0) {}
+ perform(ctx, undo) catch {};
+ run.remove(ctx, revert_path);
+ c._exit(0);
+ }
+ const json = try std.json.Stringify.valueAlloc(ctx.a, Revert{ .pid = pid, .deadline = run.nowSeconds() + seconds, .undo = undo }, .{});
+ try run.writeAtomic(ctx, revert_path, json, 0o600);
+}
diff --git a/src/firewall_main.zig b/src/firewall_main.zig
new file mode 100644
index 0000000..94c555d
--- /dev/null
+++ b/src/firewall_main.zig
@@ -0,0 +1,161 @@
+//! rediwm-firewall-helper: root-side firewall reads and changes for Settings.
+//! Run by pkexec as `read` (status and recent blocks; polkit lets an active
+//! session in without a password) or `manage` (everything; the Unlock
+//! password), with one JSON request on stdin and a JSON reply on stdout.
+//! `sync` (no request) re-applies our saved rules for boot and
+//! NetworkManager's dispatcher. Every request field is validated before use.
+const std = @import("std");
+const builtin = @import("builtin");
+const c = @import("c");
+const fw = @import("firewall");
+const platform = @import("platform");
+const run = @import("firewall_helper/run.zig");
+const state = @import("firewall_helper/state.zig");
+const backend = switch (builtin.os.tag) {
+ .linux => @import("firewall_helper/linux.zig"),
+ .freebsd => @import("firewall_helper/freebsd.zig"),
+ else => @compileError("the firewall helper is not ported to this OS"),
+};
+const Request = fw.protocol.Request;
+
+pub const std_options: std.Options = .{ .log_level = .info };
+
+pub fn main(init: std.process.Init) u8 {
+ if (c.geteuid() != 0) return fail("must be run through pkexec");
+ platform.process.denyDumps() catch {};
+ platform.process.ignoreBrokenPipes();
+ _ = c.umask(0o077);
+ // No run may hang Settings: the page has its own deadline, but a root
+ // process cannot be signalled by it.
+ _ = c.alarm(90);
+ const args = init.minimal.args.vector;
+ if (args.len != 2) return fail("usage: rediwm-firewall-helper read|manage|sync");
+ const mode = std.mem.span(args[1]);
+
+ var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var env = run.environment(a) catch return fail("out of memory");
+ const ctx: run.Ctx = .{ .a = a, .io = init.io, .env = &env };
+
+ if (std.mem.eql(u8, mode, "sync")) {
+ backend.sync(ctx) catch |err| {
+ std.log.err("sync failed: {s}", .{@errorName(err)});
+ return 1;
+ };
+ return 0;
+ }
+ const manage = std.mem.eql(u8, mode, "manage");
+ if (!manage and !std.mem.eql(u8, mode, "read")) return fail("unknown mode");
+
+ const input = readRequest(a) catch return fail("invalid request");
+ const parsed = std.json.parseFromSliceLeaky(Request, a, input, .{ .allocate = .alloc_always, .max_value_len = 4096 }) catch return fail("invalid request");
+ if (!manage and !fw.protocol.readOnly(parsed.op)) return fail("operation needs the manage action");
+ if (!valid(parsed)) return fail("invalid request");
+
+ var reply: fw.protocol.Reply = .{};
+ perform(ctx, parsed) catch |err| {
+ std.log.err("firewall {s} failed: {s}", .{ @tagName(parsed.op), @errorName(err) });
+ reply.failure = failure(err);
+ };
+ if (parsed.op != .authorize) {
+ reply.status = backend.status(ctx) catch |err| blk: {
+ std.log.err("firewall status failed: {s}", .{@errorName(err)});
+ if (reply.failure == null) reply.failure = "The firewall could not be read.";
+ break :blk .{};
+ };
+ if (parsed.op == .blocks and reply.failure == null) reply.status.blocks = backend.blocks(ctx) catch &.{};
+ }
+ const json = std.json.Stringify.valueAlloc(a, reply, .{}) catch return fail("out of memory");
+ var done: usize = 0;
+ while (done < json.len) {
+ const n = c.write(1, json.ptr + done, json.len - done);
+ if (n <= 0) return 1;
+ done += @intCast(n);
+ }
+ if (parsed.op != .status and parsed.op != .blocks and parsed.op != .authorize) {
+ std.log.info("firewall {s} by uid {s}: {s}", .{ @tagName(parsed.op), callerUid(), if (reply.failure == null) "done" else "failed" });
+ }
+ return if (reply.failure == null) 0 else 3;
+}
+
+fn callerUid() []const u8 {
+ const raw = c.getenv("PKEXEC_UID") orelse return "?";
+ return std.mem.span(raw);
+}
+
+fn readRequest(a: std.mem.Allocator) ![]u8 {
+ var input: std.ArrayList(u8) = .empty;
+ while (true) {
+ var chunk: [4096]u8 = undefined;
+ const got = c.read(0, &chunk, chunk.len);
+ if (got < 0 and std.posix.errno(got) == .INTR) continue;
+ if (got < 0) return error.ReadFailed;
+ if (got == 0) break;
+ const n: usize = @intCast(got);
+ if (input.items.len + n > fw.model.max_request) return error.TooLarge;
+ try input.appendSlice(a, chunk[0..n]);
+ }
+ return input.items;
+}
+
+fn valid(req: Request) bool {
+ if (req.rule) |rule| if (!(if (req.op == .remove_rule) fw.validate.removal(rule) else fw.validate.rule(rule))) return false;
+ if ((req.op == .add_rule or req.op == .remove_rule) and req.rule == null) return false;
+ if (req.op == .set_option and req.option == null) return false;
+ if (req.op == .set_trust) {
+ if (req.uuid.len != 0 and !fw.validate.uuid(req.uuid)) return false;
+ if (req.uuid.len == 0 and !fw.validate.iface(req.iface)) return false;
+ }
+ if (req.revert_after > 300) return false;
+ return true;
+}
+
+fn undo(ctx: run.Ctx, req: Request) ?Request {
+ return switch (req.op) {
+ .lockdown => if (req.on) Request{ .op = .lockdown, .on = false } else null,
+ .disable => Request{ .op = .enable },
+ .remove_rule => Request{ .op = .add_rule, .rule = req.rule },
+ .set_defaults => blk: {
+ const now = backend.status(ctx) catch break :blk null;
+ break :blk Request{ .op = .set_defaults, .incoming = if (req.incoming != null) now.incoming else null, .outgoing = if (req.outgoing != null) now.outgoing else null, .forward = if (req.forward != null) now.forward else null };
+ },
+ else => null,
+ };
+}
+
+fn perform(ctx: run.Ctx, req: Request) !void {
+ switch (req.op) {
+ .status, .blocks, .authorize => return,
+ .confirm => return state.confirm(ctx),
+ .sync => return backend.sync(ctx),
+ else => {},
+ }
+ const revert = if (req.revert_after != 0) undo(ctx, req) else null;
+ try backend.change(ctx, req);
+ if (revert) |back| try state.arm(ctx, back, req.revert_after, changeOnly);
+}
+
+fn changeOnly(ctx: run.Ctx, req: Request) anyerror!void {
+ return backend.change(ctx, req);
+}
+
+/// Fixed words for the page; tool output never reaches it.
+fn failure(err: anyerror) []const u8 {
+ return switch (err) {
+ error.Conflict => "Another firewall is active. Turn it off first.",
+ error.ManagedElsewhere => "This firewall is managed by RediOS.",
+ error.ToolMissing => "A firewall tool this needs is not installed.",
+ error.RulesetRejected => "The firewall rejected the new rules; nothing was changed.",
+ error.NoSuchRule => "That rule is no longer there.",
+ error.TooManyRules => "There are too many rules.",
+ error.Unsupported => "This firewall cannot do that.",
+ else => "The change could not be made.",
+ };
+}
+
+fn fail(message: []const u8) u8 {
+ _ = c.write(2, message.ptr, message.len);
+ _ = c.write(2, "\n", 1);
+ return 1;
+}
diff --git a/src/session/lock.zig b/src/session/lock.zig
index fcafc1b..870c58d 100644
--- a/src/session/lock.zig
+++ b/src/session/lock.zig
@@ -148,6 +148,7 @@ pub const Lock = struct {
cc.bluetooth.clearPin();
cc.key_settings.clearSecrets();
if (cc.key_settings.client) |client| client.cancel();
+ cc.firewall.hide();
cc.refresh();
}
@import("../extra_protocols.zig").rediwm_protocols_revoke(server.extra_protocols);
diff --git a/src/system_monitor/proc.zig b/src/system_monitor/proc.zig
index 86a97e8..43287a3 100644
--- a/src/system_monitor/proc.zig
+++ b/src/system_monitor/proc.zig
@@ -46,6 +46,9 @@ pub const cpuCores = backend.cpuCores;
pub const memoryTotals = backend.memoryTotals;
pub const systemStats = backend.systemStats;
pub const ticksPerSecond = backend.ticksPerSecond;
+/// Listening sockets for the firewall helper: Linux only. FreeBSD callers run
+/// `sockstat` instead (`firewall/sockets.zig` parses both).
+pub const sockets = if (builtin.os.tag == .linux) @import("proc_linux_sockets.zig") else struct {};
/// One process's stat, or null if it is gone or unreadable. `name` points into `buf`.
pub fn readStat(pid: i32, buf: []u8) ?Stat {
diff --git a/src/system_monitor/proc_linux_sockets.zig b/src/system_monitor/proc_linux_sockets.zig
new file mode 100644
index 0000000..dca89dc
--- /dev/null
+++ b/src/system_monitor/proc_linux_sockets.zig
@@ -0,0 +1,65 @@
+//! Listening sockets on Linux: the kernel's `/proc/net/{tcp,tcp6,udp,udp6}`
+//! tables (text; `firewall/sockets.zig` parses them) and which process holds
+//! each socket inode, from `/proc/<pid>/fd`. Only root sees every process's
+//! descriptors; the firewall helper calls this as root.
+const std = @import("std");
+const common = @import("proc_common.zig");
+const c = common.c;
+
+pub const NetTable = enum { tcp, tcp6, udp, udp6 };
+
+/// One table's text, or null when it cannot be read (no IPv6, say).
+pub fn netTable(a: std.mem.Allocator, which: NetTable) ?[]const u8 {
+ var path_buf: [32]u8 = undefined;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/net/{s}", .{@tagName(which)}, 0) catch return null;
+ var size: usize = 64 << 10;
+ while (size <= 16 << 20) : (size *= 4) {
+ const buf = a.alloc(u8, size) catch return null;
+ if (common.readAt(c.AT_FDCWD, path, buf)) |text| return text else |err| {
+ a.free(buf);
+ if (err != error.DataTooLarge) return null;
+ }
+ }
+ return null;
+}
+
+pub const Owner = struct { inode: u64, pid: i32, name: []const u8 };
+
+/// Socket inodes and the process holding each (the first one found).
+pub fn socketOwners(a: std.mem.Allocator) ![]Owner {
+ var list: std.ArrayList(Owner) = .empty;
+ const proc = c.opendir("/proc") orelse return list.toOwnedSlice(a);
+ defer _ = c.closedir(proc);
+ while (c.readdir(proc)) |entry| {
+ const pid_name = std.mem.sliceTo(entry.*.d_name[0..], 0);
+ const pid = std.fmt.parseInt(i32, pid_name, 10) catch continue;
+ var path_buf: [64]u8 = undefined;
+ const fd_path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/fd", .{pid}, 0) catch continue;
+ const fds = c.opendir(fd_path) orelse continue;
+ defer _ = c.closedir(fds);
+ var name: []const u8 = "";
+ while (c.readdir(fds)) |fd_entry| {
+ const fd_name = std.mem.sliceTo(fd_entry.*.d_name[0..], 0);
+ if (fd_name.len == 0 or fd_name[0] == '.') continue;
+ var link_buf: [64]u8 = undefined;
+ var target_buf: [64]u8 = undefined;
+ const link = std.fmt.bufPrintSentinel(&link_buf, "/proc/{d}/fd/{s}", .{ pid, fd_name }, 0) catch continue;
+ const n = c.readlink(link, &target_buf, target_buf.len);
+ if (n <= 0) continue;
+ const target = target_buf[0..@intCast(n)];
+ if (!std.mem.startsWith(u8, target, "socket:[") or target[target.len - 1] != ']') continue;
+ const inode = std.fmt.parseInt(u64, target[8 .. target.len - 1], 10) catch continue;
+ if (name.len == 0) name = comm(a, pid) catch "";
+ try list.append(a, .{ .inode = inode, .pid = pid, .name = name });
+ }
+ }
+ return list.toOwnedSlice(a);
+}
+
+fn comm(a: std.mem.Allocator, pid: i32) ![]const u8 {
+ var path_buf: [48]u8 = undefined;
+ const path = try std.fmt.bufPrintSentinel(&path_buf, "/proc/{d}/comm", .{pid}, 0);
+ var buf: [64]u8 = undefined;
+ const text = common.readAt(c.AT_FDCWD, path, &buf) catch return "";
+ return a.dupe(u8, std.mem.trimEnd(u8, text, "\n"));
+}
diff --git a/src/ui/layout.zig b/src/ui/layout.zig
index 45c6dc7..762ef2d 100644
--- a/src/ui/layout.zig
+++ b/src/ui/layout.zig
@@ -155,6 +155,8 @@ pub const IconId = enum {
trackball,
cpu,
ram,
+ /// Firewall: a shield with a check mark.
+ shield,
};
pub const ButtonState = enum { idle, hover, press, disabled };
diff --git a/src/ui/paint_icons.zig b/src/ui/paint_icons.zig
index b802af8..fa7f6f4 100644
--- a/src/ui/paint_icons.zig
+++ b/src/ui/paint_icons.zig
@@ -277,7 +277,7 @@ pub fn iconDistance(id: IconId, px: f32, py: f32, cx: f32, cy: f32, half: f32, t
const base = @min(ring_open, arrow);
break :blk if (id == .restart_shell) @min(base, sdCircle(px, py, cx, cy, half * 0.24)) else base;
},
- .git_branch, .home, .generic, .folder, .document, .terminal, .settings, .keyboard, .edit, .browser, .wifi, .ethernet, .globe, .mouse, .touchpad, .trackball, .display, .music, .headphones, .bluetooth, .battery, .notification, .eye, .eye_off, .refresh, .cut, .copy, .paste, .trash, .trash_can, .view_grid, .view_list, .sort, .filter, .zoom_in, .zoom_out, .rotate, .crop, .undo, .save, .fit, .print, .open, .usb_stick, .drive, .eject, .users, .squares => sdCircle(px, py, cx, cy, half * 0.6),
+ .git_branch, .home, .generic, .folder, .document, .terminal, .settings, .keyboard, .edit, .browser, .wifi, .ethernet, .globe, .mouse, .touchpad, .trackball, .display, .music, .headphones, .bluetooth, .battery, .notification, .eye, .eye_off, .refresh, .cut, .copy, .paste, .trash, .trash_can, .view_grid, .view_list, .sort, .filter, .zoom_in, .zoom_out, .rotate, .crop, .undo, .save, .fit, .print, .open, .usb_stick, .drive, .eject, .users, .squares, .shield => sdCircle(px, py, cx, cy, half * 0.6),
};
}
diff --git a/src/ui/shell_icons.zig b/src/ui/shell_icons.zig
index e1acfd1..f171305 100644
--- a/src/ui/shell_icons.zig
+++ b/src/ui/shell_icons.zig
@@ -107,6 +107,7 @@ pub fn configure(io: std.Io, root: []const u8) void {
.{ IconId.users, "users" },
.{ IconId.squares, "squares" },
.{ IconId.divide, "divide" },
+ .{ IconId.shield, "shield" },
}) |pair| {
loadOverride(io, root, pair[0], pair[1]);
}
@@ -203,6 +204,7 @@ fn builtinSource(id: IconId) ?[]const u8 {
.users => @embedFile("shell-icon-users"),
.squares => @embedFile("shell-icon-squares"),
.divide => @embedFile("shell-icon-divide"),
+ .shield => @embedFile("shell-icon-shield"),
else => null,
};
}
diff --git a/tests/firewall_fake_helper.py b/tests/firewall_fake_helper.py
new file mode 100644
index 0000000..7a0964f
--- /dev/null
+++ b/tests/firewall_fake_helper.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""A stand-in for rediwm-firewall-helper for tests/firewall_settings.py.
+
+Speaks the helper's JSON protocol (src/firewall/protocol.zig) over stdin and
+stdout, keeps its firewall in a JSON file and appends every request to a log,
+so the test can check what Settings asked for. It never touches a real
+firewall. The real helper is tested against nftables in tests/firewall_helper.py.
+"""
+import json
+import os
+import sys
+
+STATE = os.environ['FIREWALL_FAKE_STATE']
+LOG = os.environ['FIREWALL_FAKE_LOG']
+READ_ONLY = {'status', 'blocks'}
+
+
+def default_state():
+ return {
+ 'backend': 'own', 'running': False, 'boot': False, 'incoming': 'drop', 'outgoing': 'accept', 'forward': 'drop',
+ 'ping': True, 'logging': 'off', 'ssh_limit': False, 'lockdown': False, 'revert_in': 0,
+ 'rules': [{'service': 'ssh', 'action': 'allow', 'direction': 'in', 'proto': 'both', 'port': '', 'source': '', 'scope': 'everywhere', 'family': 'both', 'iface': '', 'comment': '', 'raw': ''}],
+ 'listeners': [
+ {'proto': 'tcp', 'address': '0.0.0.0', 'port': 22, 'process': 'sshd', 'pid': 700, 'uid': 0, 'verdict': 'everywhere'},
+ {'proto': 'tcp', 'address': '127.0.0.1', 'port': 631, 'process': 'cupsd', 'pid': 701, 'uid': 0, 'verdict': 'local'},
+ {'proto': 'udp', 'address': '0.0.0.0', 'port': 21027, 'process': 'syncthing', 'pid': 900, 'uid': 1000, 'verdict': 'blocked'},
+ ],
+ 'networks': [{'name': 'Home Wi-Fi', 'iface': 'wlan0', 'uuid': '0b6f2c55-1a4e-4c68-9d1d-2a5c4cbe1f00', 'trust': 'public', 'active': True}],
+ 'foreign': [{'owner': 'Docker', 'name': 'ip nat', 'rules': 4}],
+ }
+
+
+def load():
+ try:
+ with open(STATE) as f:
+ return json.load(f)
+ except FileNotFoundError:
+ return default_state()
+
+
+def status(state, blocks=False):
+ rules = [dict(r, id=i) for i, r in enumerate(state['rules'])]
+ caps = {k: True for k in ('edit', 'trust', 'sources', 'limit', 'reject', 'outgoing_rules', 'outgoing_policy', 'forward_policy', 'ping', 'logging', 'ssh_limit', 'boot', 'lockdown')}
+ out = {k: state[k] for k in ('backend', 'running', 'boot', 'incoming', 'outgoing', 'forward', 'ping', 'logging', 'ssh_limit', 'lockdown', 'revert_in', 'listeners', 'networks', 'foreign')}
+ out.update(system='linux', rules=rules, capabilities=caps, conflicts=[], installed=['own'], zone='', needs_anchor=False,
+ blocks=[{'time': '2026-11-17T10:00:00', 'direction': 'in', 'proto': 'TCP', 'source': '192.0.2.5', 'port': 23, 'iface': 'wlan0'}] if blocks else [])
+ return out
+
+
+def same(a, b):
+ keys = ('action', 'direction', 'proto', 'port', 'service', 'source', 'scope', 'family', 'iface')
+ return all(a.get(k, d) == b.get(k, d) for k, d in zip(keys, ('allow', 'in', 'both', '', '', '', 'everywhere', 'both', '')))
+
+
+def main():
+ mode = sys.argv[1]
+ request = json.loads(sys.stdin.read())
+ with open(LOG, 'a') as f:
+ f.write(json.dumps({'mode': mode, 'request': request}) + '\n')
+ op = request['op']
+ if mode != 'manage' and op not in READ_ONLY:
+ print('operation needs the manage action', file=sys.stderr)
+ return 1
+ state = load()
+ failure = None
+ state['revert_in'] = 0
+ if op == 'enable':
+ state['running'] = True
+ elif op == 'disable':
+ state['running'] = False
+ elif op == 'add_rule':
+ rule = request['rule']
+ if not any(same(r, rule) for r in state['rules']):
+ state['rules'].append(rule)
+ elif op == 'remove_rule':
+ before = len(state['rules'])
+ state['rules'] = [r for r in state['rules'] if not same(r, request['rule'])]
+ if len(state['rules']) == before:
+ failure = 'That rule is no longer there.'
+ elif op == 'set_defaults':
+ for key in ('incoming', 'outgoing', 'forward'):
+ if request.get(key):
+ state[key] = request[key]
+ elif op == 'set_option':
+ option = request['option']
+ if option == 'logging':
+ state['logging'] = request['logging']
+ else:
+ state[option] = request['on']
+ elif op == 'set_trust':
+ for n in state['networks']:
+ if n['uuid'] == request['uuid']:
+ n['trust'] = request['trust']
+ elif op == 'lockdown':
+ state['lockdown'] = request['on']
+ if request.get('revert_after'):
+ state['revert_in'] = request['revert_after']
+ with open(STATE, 'w') as f:
+ json.dump(state, f)
+ if op == 'authorize':
+ return 0
+ print(json.dumps({'status': status(state, blocks=op == 'blocks'), 'failure': failure}))
+ return 0 if failure is None else 3
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/tests/firewall_helper.py b/tests/firewall_helper.py
new file mode 100644
index 0000000..c04a8a8
--- /dev/null
+++ b/tests/firewall_helper.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python3
+"""rediwm-firewall-helper against real nftables, without touching the host.
+
+Re-runs itself in a private user, mount and network namespace (`unshare
+-rmn`): the helper is namespace root and its nftables table lands in the
+empty network namespace. ${sysconfdir}/rediwm and /run are scratch tmpfs;
+NetworkManager's and systemd's directories are masked and nmcli, systemctl,
+ufw and firewall-cmd are hidden, so nothing reaches host services. Checks our
+own backend end to end: enable, rules, validation, listener verdicts, trust,
+lockdown and policy changes that revert unless kept, and disable.
+Usage: python3 tests/firewall_helper.py [--bin-dir zig-out/bin]
+"""
+import json
+import os
+from pathlib import Path
+import shutil
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+
+HERE = Path(__file__).resolve().parent
+SETUP = r'''
+set -e
+scratch="$1"; shift
+if [ -d /etc/rediwm ]; then
+ mount -t tmpfs tmpfs /etc/rediwm
+else
+ mkdir -p "$scratch/etc"
+ mount --rbind /etc "$scratch/etc"
+ mount -t tmpfs tmpfs /etc
+ for entry in "$scratch"/etc/* "$scratch"/etc/.[!.]*; do [ -e "$entry" ] && ln -s "$entry" /etc/; done
+ mkdir /etc/rediwm
+fi
+mount -t tmpfs tmpfs /run
+for dir in /etc/NetworkManager /etc/systemd/system; do [ -d "$dir" ] && mount -t tmpfs tmpfs "$dir"; done
+for tool in ufw nmcli systemctl firewall-cmd; do
+ for dir in /usr/bin /usr/sbin /bin /sbin; do [ -e "$dir/$tool" ] && mount --bind /dev/null "$dir/$tool"; done
+done
+ip link set lo up 2>/dev/null || true
+exec "$@"
+'''
+
+
+def bin_dir():
+ if '--bin-dir' in sys.argv:
+ return Path(sys.argv[sys.argv.index('--bin-dir') + 1]).resolve()
+ return (HERE.parent / 'zig-out' / 'bin').resolve()
+
+
+def reexec():
+ if not shutil.which('nft') or not shutil.which('unshare'):
+ print('SKIP: firewall_helper needs nft and unshare')
+ sys.exit(0)
+ with tempfile.TemporaryDirectory(prefix='rediwm-firewall-helper-') as scratch:
+ command = ['unshare', '-rmn', 'sh', '-c', SETUP, 'setup', scratch, sys.executable, '-I', __file__, '--inside', '--bin-dir', str(bin_dir())]
+ sys.exit(subprocess.run(command).returncode)
+
+
+HELPER = str(bin_dir() / 'rediwm-firewall-helper')
+
+
+def call(mode, request):
+ result = subprocess.run([HELPER, mode], input=json.dumps(request).encode(), capture_output=True, timeout=60)
+ reply = json.loads(result.stdout) if result.stdout else None
+ return result.returncode, reply
+
+
+def manage(request):
+ code, reply = call('manage', request)
+ assert reply is not None, f'{request}: no reply (exit {code})'
+ assert reply['failure'] is None, f'{request}: {reply["failure"]}'
+ return reply['status']
+
+
+def status():
+ return call('read', {'op': 'status'})[1]['status']
+
+
+def nft(*args):
+ return subprocess.run(['nft', *args], capture_output=True, text=True).stdout
+
+
+def verdicts(s):
+ return {(l['proto'], l['port']): l['verdict'] for l in s['listeners']}
+
+
+def main():
+ s = status()
+ assert s['backend'] == 'own' and not s['running'], s
+ assert s['capabilities']['edit'] and s['capabilities']['lockdown']
+
+ # A read cannot change anything, and junk never reaches nft.
+ code, _ = call('read', {'op': 'enable'})
+ assert code != 0
+ for bad in ({'port': '22; flush ruleset', 'proto': 'tcp'}, {'source': '1.2.3.4 } accept', 'action': 'deny'}, {'service': 'ssh', 'comment': 'x" accept'}, {}):
+ code, reply = call('manage', {'op': 'add_rule', 'rule': bad})
+ assert code != 0 and reply is None, bad
+ assert 'rediwm' not in nft('list', 'tables')
+
+ s = manage({'op': 'enable'})
+ assert s['running'] and s['incoming'] == 'drop', s
+ assert 'table inet rediwm' in nft('list', 'tables')
+
+ listeners = []
+ for family, address, port, kind in ((socket.AF_INET, '0.0.0.0', 8080, socket.SOCK_STREAM), (socket.AF_INET, '127.0.0.1', 631, socket.SOCK_STREAM), (socket.AF_INET6, '::', 22, socket.SOCK_STREAM), (socket.AF_INET, '0.0.0.0', 5353, socket.SOCK_DGRAM)):
+ sock = socket.socket(family, kind)
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ sock.bind((address, port))
+ if kind == socket.SOCK_STREAM:
+ sock.listen()
+ listeners.append(sock)
+ v = verdicts(status())
+ assert v == {('tcp', 8080): 'blocked', ('tcp', 631): 'local', ('tcp', 22): 'blocked', ('udp', 5353): 'blocked'}, v
+
+ manage({'op': 'add_rule', 'rule': {'service': 'ssh', 'source': 'lan', 'comment': 'ssh'}})
+ manage({'op': 'add_rule', 'rule': {'port': '8080', 'proto': 'tcp'}})
+ manage({'op': 'add_rule', 'rule': {'service': 'mdns', 'scope': 'home'}})
+ s = manage({'op': 'add_rule', 'rule': {'source': '203.0.113.9', 'action': 'deny'}})
+ assert len(s['rules']) == 4, s['rules']
+ v = verdicts(s)
+ assert v[('tcp', 8080)] == 'everywhere' and v[('tcp', 22)] == 'home' and v[('udp', 5353)] == 'home', v
+ table = nft('list', 'table', 'inet', 'rediwm')
+ for piece in ('ip saddr 203.0.113.9 drop', 'ip saddr @lan4 tcp dport 22 accept comment "ssh"', 'tcp dport 8080 accept', 'iifname @home_ifaces udp dport 5353 accept'):
+ assert piece in table, (piece, table)
+ # Adding the same rule twice keeps one.
+ assert len(manage({'op': 'add_rule', 'rule': {'port': '8080', 'proto': 'tcp'}})['rules']) == 4
+
+ # Remove by the rule as the status listed it.
+ rule = next(r for r in s['rules'] if r['port'] == '8080')
+ s = manage({'op': 'remove_rule', 'rule': rule})
+ assert all(r['port'] != '8080' for r in s['rules']) and 'dport 8080' not in nft('list', 'table', 'inet', 'rediwm')
+ code, reply = call('manage', {'op': 'remove_rule', 'rule': rule})
+ assert code == 3 and reply['failure'] == 'That rule is no longer there.', reply
+
+ # Per-interface trust (no NetworkManager here) fills the home set.
+ iface = next((n['iface'] for n in s['networks']), None)
+ if iface:
+ s = manage({'op': 'set_trust', 'iface': iface, 'trust': 'home'})
+ assert any(n['iface'] == iface and n['trust'] == 'home' for n in s['networks'])
+ assert f'"{iface}"' in nft('list', 'set', 'inet', 'rediwm', 'home_ifaces')
+
+ # Lockdown and blocking outgoing undo themselves unless kept.
+ s = manage({'op': 'lockdown', 'on': True, 'revert_after': 2})
+ assert s['lockdown'] and s['revert_in'] > 0 and 'rediwm_lockdown' in nft('list', 'tables')
+ time.sleep(3.5)
+ s = status()
+ assert not s['lockdown'] and s['revert_in'] == 0, s
+ manage({'op': 'lockdown', 'on': True, 'revert_after': 2})
+ manage({'op': 'confirm'})
+ time.sleep(3)
+ assert status()['lockdown']
+ assert not manage({'op': 'lockdown', 'on': False})['lockdown']
+ s = manage({'op': 'set_defaults', 'outgoing': 'drop', 'revert_after': 2})
+ assert s['outgoing'] == 'drop' and 'policy drop' in nft('list', 'chain', 'inet', 'rediwm', 'output')
+ time.sleep(3.5)
+ assert status()['outgoing'] == 'accept'
+
+ s = manage({'op': 'set_option', 'option': 'ping', 'on': False})
+ assert not s['ping'] and 'icmp type echo-request drop' in nft('list', 'chain', 'inet', 'rediwm', 'input')
+ s = manage({'op': 'set_option', 'option': 'logging', 'logging': 'medium'})
+ assert s['logging'] == 'medium' and 'rediwm-drop' in nft('list', 'chain', 'inet', 'rediwm', 'input')
+ s = manage({'op': 'set_defaults', 'incoming': 'reject'})
+ assert s['incoming'] == 'reject'
+ code, reply = call('read', {'op': 'blocks'})
+ assert code == 0 and isinstance(reply['status']['blocks'], list)
+
+ # The saved state is root-only, and `sync` restores the table.
+ saved = Path('/etc/rediwm/firewall.json')
+ assert oct(saved.stat().st_mode & 0o777) == '0o600', oct(saved.stat().st_mode)
+ nft('delete', 'table', 'inet', 'rediwm')
+ assert subprocess.run([HELPER, 'sync']).returncode == 0
+ assert 'table inet rediwm' in nft('list', 'tables')
+
+ s = manage({'op': 'disable'})
+ assert not s['running'] and 'rediwm' not in nft('list', 'tables'), nft('list', 'tables')
+ for sock in listeners:
+ sock.close()
+ print('PASS firewall helper: own nftables backend, validation, verdicts, trust, revert, sync')
+
+
+if __name__ == '__main__':
+ if '--inside' in sys.argv:
+ main()
+ else:
+ reexec()
diff --git a/tests/firewall_settings.py b/tests/firewall_settings.py
new file mode 100644
index 0000000..fdacfb1
--- /dev/null
+++ b/tests/firewall_settings.py
@@ -0,0 +1,281 @@
+#!/usr/bin/env python3
+"""Settings → Network → Firewall against a fake helper; never touches a firewall.
+
+The compositor looks for pkexec only in the system directories, so the test
+re-runs itself in a private user and mount namespace (namespace root is a
+subordinate uid, used only to bind-mount a fake over /usr/bin/pkexec), then
+drops back to the user's own uid for the compositor. The fake pkexec runs
+tests/firewall_fake_helper.py instead of the real helper and can refuse, as a
+dismissed password dialog does (exit 126). Needs util-linux unshare/setpriv
+and a subuid range for newuidmap.
+"""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+
+HERE = Path(__file__).resolve().parent
+
+
+def reexec(no_policy=False):
+ uid, gid = os.getuid(), os.getgid()
+ sub = next((line.split(':') for line in Path('/etc/subuid').read_text().splitlines() if line.split(':')[0] in (os.environ.get('USER', ''), str(uid))), None)
+ if not sub:
+ print('SKIP: firewall_settings needs a /etc/subuid range for newuidmap')
+ sys.exit(0)
+ # Namespace root is a subordinate uid that cannot enter the user's home,
+ # so the fake is staged where it can be read.
+ with tempfile.TemporaryDirectory(prefix='rediwm-firewall-pkexec-') as stage:
+ os.chmod(stage, 0o755)
+ fake = Path(stage) / 'pkexec'
+ fake.write_bytes((HERE / 'fixtures' / 'firewall_pkexec.sh').read_bytes())
+ fake.chmod(0o755)
+ # Settings runs pkexec only when polkit's actions name its helper.
+ actions = Path(stage) / 'actions'
+ actions.mkdir(mode=0o755)
+ policy = actions / 'org.rediwm.firewall.policy'
+ text = (HERE.parent / 'zig-out' / 'share' / 'polkit-1' / 'actions' / 'org.rediwm.firewall.policy').read_text()
+ if no_policy:
+ text = text.replace('/rediwm-firewall-helper<', '/some-other-helper<')
+ policy.write_text(text)
+ policy.chmod(0o644)
+ inner = f'mount --bind {fake} /usr/bin/pkexec && mount --bind {actions} /usr/share/polkit-1/actions && exec setpriv --reuid={uid} --regid={gid} --keep-groups {sys.executable} -I {__file__} --inside' + (' --no-policy' if no_policy else '')
+ command = ['unshare', '--user', '--mount', f'--map-users=0:{sub[1]}:1', f'--map-users={uid}:{uid}:1', f'--map-groups=0:{sub[1]}:1', f'--map-groups={gid}:{gid}:1', '--setuid', '0', '--setgid', '0', 'sh', '-c', inner]
+ return subprocess.run(command).returncode
+
+
+if '--inside' not in sys.argv:
+ sys.exit(reexec() or reexec(no_policy=True))
+
+sys.path.insert(0, str(HERE))
+from ipc_client import IPCClient, spawn_compositor, stop_process # noqa: E402
+from power_profiles import wait_for as _wait_for # noqa: E402
+
+CURRENT = {}
+
+
+def wait_for(predicate, description, *args, **kwargs):
+ try:
+ return _wait_for(predicate, description, *args, **kwargs)
+ except AssertionError:
+ if CURRENT.get('page'):
+ print('page text:', CURRENT['page'].texts(), file=sys.stderr)
+ print('helper requests:', CURRENT['page'].requests(), file=sys.stderr)
+ raise
+from ui_driver import UIDriver # noqa: E402
+
+
+class Page:
+ def __init__(self, ipc, tmp):
+ self.ipc, self.ui, self.tmp = ipc, UIDriver(ipc), tmp
+
+ def widgets(self):
+ return self.ui.widgets()
+
+ def has(self, name):
+ return any(w.get('name') == name for w in self.widgets())
+
+ def find(self, name):
+ return self.ui.find(name, panel='control_center')
+
+ def label(self, name):
+ return self.find(name).get('label', '')
+
+ def texts(self):
+ return ' '.join(w.get('label') or w.get('text') or '' for w in self.widgets())
+
+ def click(self, name):
+ wait_for(lambda: self.has(name) and not self.find(name)['is_disabled'], name + ' enabled')
+ self.ui.click(self.ui.scroll_into_view(name, panel='control_center'), panel='control_center')
+ self.ui.wait_settled('control_center')
+
+ def key(self, code):
+ for pressed in (True, False):
+ self.ipc.action('key', {'keycode': code, 'pressed': pressed})
+ time.sleep(.12)
+
+ def choose(self, name, steps):
+ self.click(name)
+ for _ in range(abs(steps)):
+ self.key(108 if steps > 0 else 103)
+ self.key(28)
+ self.ui.wait_settled('control_center')
+
+ def type_into(self, name, text):
+ self.click(name)
+ self.ipc.type_text(text)
+ self.ui.wait_settled('control_center')
+
+ def shot(self, name):
+ """FIREWALL_TEST_SHOTS=<dir> keeps screenshots for a visual check."""
+ directory = os.environ.get('FIREWALL_TEST_SHOTS')
+ if directory:
+ self.ui.wait_settled('control_center')
+ self.ipc.screenshot(str(Path(directory) / f'{name}.png'))
+
+ def requests(self):
+ log = self.tmp / 'helper.log'
+ return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
+
+ def wait_request(self, op, count=1, **expect):
+ def found():
+ hits = [r for r in self.requests() if r['request']['op'] == op and all(r['request'].get(k) == v for k, v in expect.items())]
+ return hits[count - 1] if len(hits) >= count else None
+ wait_for(found, f'{op} request {expect}')
+ return found()
+
+ def open_network(self):
+ self.ipc.open_control_center()
+ self.ui.wait_settled('control_center')
+ self.ui.click('network', panel='control_center')
+ self.ui.wait_settled('control_center')
+ wait_for(lambda: self.has('firewall_card'), 'firewall card')
+
+
+def scenario_manage(page):
+ page.open_network()
+ page.wait_request('status')
+ wait_for(lambda: 'Unlock' in page.label('firewall_unlock'), 'unlock button')
+ assert page.find('firewall_enabled')['is_disabled'], 'toggle must wait for Unlock'
+ first = page.requests()[0]
+ assert first['mode'] == 'read', first
+
+ page.click('firewall_unlock')
+ page.wait_request('authorize')
+ wait_for(lambda: page.label('firewall_unlock') == 'Lock', 'unlocked')
+ page.click('firewall_enabled')
+ assert page.wait_request('enable')['mode'] == 'manage'
+ wait_for(lambda: 'Protected by' in page.texts(), 'protected summary')
+ page.ui.scroll_into_view('firewall_card', panel='control_center')
+ page.shot('overview')
+
+ page.click('firewall_manage')
+ wait_for(lambda: page.has('firewall_rules') and page.has('firewall_listeners') and page.has('firewall_advanced'), 'sub-view')
+ assert page.has('firewall_foreign') and 'Docker' in page.texts()
+ page.shot('manage-top')
+
+ # Add a port rule through the form.
+ page.click('firewall_add')
+ wait_for(lambda: page.has('firewall_form'), 'form')
+ page.choose('firewall_form_kind', 1)
+ wait_for(lambda: page.has('firewall_form_port'), 'port field')
+ page.type_into('firewall_form_port', '8080')
+ page.type_into('firewall_form_comment', 'dev server')
+ page.shot('form')
+ page.click('firewall_form_add')
+ rule = page.wait_request('add_rule')['request']['rule']
+ assert rule['port'] == '8080' and rule['proto'] == 'tcp' and rule['comment'] == 'dev server', rule
+ wait_for(lambda: not page.has('firewall_form'), 'form closes')
+ wait_for(lambda: 'Port 8080 TCP' in page.texts(), 'new rule listed')
+
+ # Bad input stays in the form with a reason and sends nothing.
+ page.click('firewall_add')
+ page.choose('firewall_form_kind', 2)
+ page.type_into('firewall_form_address', '300.1.1.1')
+ before = len(page.requests())
+ page.click('firewall_form_add')
+ wait_for(lambda: 'Enter an IP address' in page.texts(), 'address error')
+ assert len(page.requests()) == before
+ page.click('firewall_form_cancel')
+
+ # The exposed sshd: Block removes the rule that opens port 22, and since
+ # that rule allows SSH the change waits to be kept.
+ page.click('firewall_listener_block')
+ removal = page.wait_request('remove_rule')['request']
+ assert removal['rule']['service'] == 'ssh' and removal['revert_after'] == 20, removal
+ page.click('firewall_keep')
+ page.wait_request('confirm')
+
+ # Trust, outgoing policy (reverting), logging, recent blocks.
+ page.choose('firewall_trust', 1)
+ trust = page.wait_request('set_trust')['request']
+ assert trust['trust'] == 'home' and trust['uuid'].startswith('0b6f2c55'), trust
+ page.choose('firewall_outgoing', 1)
+ outgoing = page.wait_request('set_defaults')['request']
+ assert outgoing['outgoing'] == 'drop' and outgoing['revert_after'] == 20, outgoing
+ page.choose('firewall_logging', 1)
+ assert page.wait_request('set_option')['request']['logging'] == 'low'
+ page.click('firewall_blocks')
+ page.wait_request('blocks')
+ wait_for(lambda: '192.0.2.5' in page.texts(), 'block listed')
+ page.shot('blocks')
+ page.ui.scroll_into_view('firewall_listeners', panel='control_center')
+ page.shot('listeners')
+ page.ui.scroll_into_view('firewall_incoming', panel='control_center')
+ page.shot('advanced')
+
+ # Back to the Network page; leaving the page forgets the unlock.
+ page.click('firewall_back')
+ wait_for(lambda: page.has('firewall_card') and not page.has('firewall_rules'), 'network page')
+ page.ui.click('general', panel='control_center')
+ page.ui.wait_settled('control_center')
+ page.ui.click('network', panel='control_center')
+ page.ui.wait_settled('control_center')
+ wait_for(lambda: page.has('firewall_unlock') and page.label('firewall_unlock') == 'Unlock', 'locked again after leaving')
+
+
+def scenario_denied(page):
+ # Reads need the password here (FreeBSD's polkit today): the card asks for
+ # an unlock before showing anything, and never prompts by itself.
+ (page.tmp / 'deny-read').write_text('1')
+ page.open_network()
+ wait_for(lambda: 'Unlock to view the firewall.' in page.texts(), 'unlock to view')
+ assert [r['request']['op'] for r in page.requests()] == [], 'denied reads never reach the helper'
+ (page.tmp / 'deny-read').unlink()
+ page.click('firewall_unlock')
+ page.wait_request('authorize')
+ status = page.wait_request('status')
+ assert status['mode'] == 'manage', status
+ wait_for(lambda: page.has('firewall_manage') and not page.find('firewall_manage')['is_disabled'], 'status shown')
+ # A dismissed password dialog keeps the page locked.
+ page.click('firewall_unlock')
+ wait_for(lambda: page.label('firewall_unlock') == 'Unlock', 'locked by the user')
+ (page.tmp / 'deny-manage').write_text('1')
+ page.click('firewall_unlock')
+ wait_for(lambda: 'cancelled or denied' in page.texts(), 'denied message')
+ assert page.label('firewall_unlock') == 'Unlock'
+
+
+def scenario_no_policy(page):
+ # polkit's actions name another helper: pkexec would fall back to its
+ # generic action and ask for a password, so Settings runs nothing.
+ page.open_network()
+ wait_for(lambda: 'its polkit policy is missing' in page.texts(), 'missing policy message')
+ time.sleep(1)
+ assert page.requests() == [], page.requests()
+ assert page.find('firewall_unlock')['is_disabled']
+
+
+def run(scenario, scale='1'):
+ with tempfile.TemporaryDirectory(prefix='rediwm-firewall-') as directory:
+ tmp = Path(directory)
+ process, log = spawn_compositor(tmp, scale=scale, config_content='[compositor]\nxwayland = false\n', env_extra={
+ 'XDG_CACHE_HOME': str(tmp), 'PIPEWIRE_RUNTIME_DIR': str(tmp), 'PULSE_SERVER': 'unix:/nonexistent-rediwm-test-pulse',
+ 'FIREWALL_FAKE_STATE': str(tmp / 'state.json'), 'FIREWALL_FAKE_LOG': str(tmp / 'helper.log'),
+ 'FIREWALL_FAKE_DIR': str(tmp), 'FIREWALL_FAKE_HELPER': str(HERE / 'firewall_fake_helper.py'),
+ })
+ try:
+ with IPCClient(tmp, timeout=15) as ipc:
+ page = Page(ipc, tmp)
+ CURRENT['page'] = page
+ scenario(page)
+ except BaseException:
+ log.flush()
+ print(Path(log.name).read_text()[-6000:] if hasattr(log, 'name') else 'no log', file=sys.stderr)
+ raise
+ finally:
+ stop_process(process)
+
+
+if __name__ == '__main__':
+ scale = os.environ.get('REDIWM_TEST_SCALE', '1')
+ if '--no-policy' in sys.argv:
+ run(scenario_no_policy, scale)
+ print('PASS Firewall settings: no pkexec without the polkit policy')
+ else:
+ run(scenario_manage, scale)
+ run(scenario_denied, scale)
+ print('PASS Firewall settings: overview, unlock, rules, listeners, trust, revert, denied reads')
diff --git a/tests/fixtures/firewall_pkexec.sh b/tests/fixtures/firewall_pkexec.sh
new file mode 100755
index 0000000..3421653
--- /dev/null
+++ b/tests/fixtures/firewall_pkexec.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Fake pkexec for tests/firewall_settings.py, bind-mounted over /usr/bin/pkexec
+# in the test's private mount namespace only. Called as
+# pkexec --disable-internal-agent <helper> read|manage
+# it runs the fake helper instead, and exits 126 (a dismissed dialog) when the
+# test asks it to refuse that mode.
+[ "$1" = "--disable-internal-agent" ] && shift
+mode="$2"
+[ -e "$FIREWALL_FAKE_DIR/deny-$mode" ] && exit 126
+PKEXEC_UID=$(id -u) exec python3 -I "$FIREWALL_FAKE_HELPER" "$mode"