Native install: nftables script for VPN clients (masquerade, MSS clamp, TTL)

deploy/native/firewall.sh reads the server interfaces and applies, for traffic
from the VPN network to all other networks: masquerade, TCP MSS clamping
(path MTU tuning) and TTL tuning, in its own table `ip ovpmon`. Rules are
persisted in /etc/ovpmon/nftables.nft and loaded at boot by the ovpmon-nft
service (systemd and OpenRC). Opt-in: install.sh and update.sh do not call it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-05 14:48:39 +03:00
1 parent 8371d889a4
commit f95a0b63e6
9 files changed
+713 -3

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
# nftables script for system-service installs: summary (2026-10-05)
Plan: [2026-10-05_NFT_Firewall_PLAN.md](2026-10-05_NFT_Firewall_PLAN.md). Guide: [Firewall, NAT and forwarding](../Deployment/Scenario2_System_Services.md#firewall-nat-and-forwarding).
## Done
| Item | Result |
|---|---|
| `deploy/native/firewall.sh` | Commands `apply` (default), `status`, `remove`; options `--dry-run`, `--vpn-net`, `--vpn-if`, `--out-if`, `--ttl`/`--no-ttl`, `--mss`/`--no-mss`, `--no-persist`, `--yes`, `--force` |
| Interface detection | VPN network: `--vpn-net` -> `server` line of the OpenVPN config -> address of the VPN interface. VPN interface: `--vpn-if` -> interface with an address in the VPN network -> `dev` line -> `tun*`. Other networks: every interface except `lo` and the VPN one (listed with MTU, state, addresses) |
| Rules (table `ip ovpmon`, one atomic transaction) | masquerade, `ip ttl set N` at egress (default 64), TCP MSS clamp of SYN/SYN-ACK in both directions (`rt mtu` or a fixed value); counters on every rule |
| Safety | other tables and the distribution's nftables service untouched; `nft -c` before applying; stops when the VPN network overlaps with an uplink network; warns about disabled forwarding, duplicate iptables MASQUERADE, strict `rp_filter` with policy routing, other `policy drop` chains (PMTUD/ICMP) |
| Persistence | `/etc/ovpmon/nftables.nft` (marker line, a foreign file is never overwritten) loaded by the service `ovpmon-nft`: `DOCS/General/systemd/ovpmon-nft.service`, `DOCS/General/openrc/ovpmon-nft`; applied parameters recorded as `FIREWALL_*` in `deploy.state` |
| `nftables` package | installed on request only; not added to the install package list |
| Documentation | Scenario 2 guide (new section, layout table), README (quick start, change table), hints of `install.sh`, header note of `lib.sh` |
## Differences from the plan
- Interfaces are read with `ip -o` (plain text) instead of `ip -j`: it works with the BusyBox `ip` of Alpine and needs no JSON parsing.
- The automated test (`test-firewall.sh`) was **not** written: the owner verifies the script by hand on a live system.
## Verification
Checked by the owner by hand on a live **Alpine** host (OpenRC): the script worked as intended. **Not verified:** Debian/Ubuntu (systemd unit `ovpmon-nft.service`) and the Hysteria2 host (specific environment, out of scope of this change).
## Out of scope
Filtering policy (INPUT/FORWARD, ports, anti-leak), IPv6, replacing the distribution's `nftables.service`, migration of the manual iptables rules of the Hysteria2 chain; options are not remembered between runs.
@@ -0,0 +1,79 @@
# nftables setup script for system-service installs: plan (2026-10-05)
Goal: a script in `deploy/native/` that reads the interface configuration of the local server and applies nftables rules for traffic going **from the VPN network to every other network**: masquerade, path MTU tuning (MSS clamping), TTL tuning.
Today the Scenario 2 scripts never touch the firewall; the guide only prints manual `iptables`/`nft` examples (`DOCS/Deployment/Scenario2_System_Services.md`, "Firewall, NAT and forwarding"). The new script is an explicit, separate opt-in step. `install.sh` and `update.sh` do not call it.
## Design
### Script: `deploy/native/firewall.sh`
POSIX sh, sources `lib.sh` (logging, `need_root`, OS detection, service helpers). Alpine (OpenRC), Debian, Ubuntu.
```
firewall.sh [apply] [--dry-run] [--vpn-net CIDR] [--vpn-if NAME] [--out-if NAME[,NAME]]
[--ttl N | --no-ttl] [--mss pmtu|N | --no-mss] [--no-persist] [--yes]
firewall.sh status # show the loaded ruleset, detected parameters, counters
firewall.sh remove # delete the table, the ruleset file and the boot service
```
### 1. Reading the local configuration (no hard-coded interface names)
| Parameter | Source, in priority order |
|---|---|
| VPN network | `--vpn-net` -> `server NET MASK` line of `$OVPN_CONFIG` (already known to `lib.sh`) -> IPv4 address of the `tun*` interface (`ip -j -4 addr`) |
| VPN interface | `--vpn-if` -> the interface whose address lies in the VPN network -> pattern `tun*` when the VPN is not up yet |
| Other networks | all interfaces from `ip -j link` except `lo` and the VPN interface (reported with their addresses, MTU and state); `--out-if` restricts the list |
The script prints what it found and stops with a clear message when the VPN network cannot be determined (e.g. no `server.conf` yet: generate it in the UI first) or the VPN network equals an uplink network.
Default scope "all other networks" is expressed as `oifname != <vpn if>` (not as a frozen list), so a new uplink (e.g. `hytun` of the Hysteria2 chain, a VLAN, a second ISP) is covered without a rerun. With `--out-if` an explicit `oifname { ... }` set is used instead.
### 2. Ruleset (one dedicated table, atomic load)
A single file loaded with `nft -f`; only the table `ip ovpmon` is created/replaced (`add table` + `delete table` + definition in one transaction). Other tables and `flush ruleset` are never used, so a user's own firewall is untouched. IPv4 only: the VPN server is IPv4-only (`topology subnet`, one `server` network).
```
table ip ovpmon {
chain postrouting_nat { type nat hook postrouting priority srcnat; policy accept;
ip saddr <VPN_NET> oifname != "<VPN_IF>" counter masquerade }
chain postrouting_mangle { type filter hook postrouting priority mangle; policy accept;
ip saddr <VPN_NET> oifname != "<VPN_IF>" counter ip ttl set <N> }
chain forward_mss { type filter hook forward priority mangle; policy accept;
iifname "<VPN_IF>" tcp flags syn tcp option maxseg size set rt mtu # client -> world SYN
oifname "<VPN_IF>" tcp flags syn tcp option maxseg size set rt mtu } # world -> client SYN-ACK
}
```
- **Masquerade**: only traffic whose source is the VPN network and which leaves through any interface except the VPN one.
- **Path MTU tuning**: MSS clamp to the MTU of the route of each connection (`rt mtu`), in both directions, so the smaller MTU of `hytun`, PPPoE or `tun-mtu` is respected per destination. `--mss N` sets a fixed value instead. This complements `tun-mtu`/`mssfix` of `server.conf` and does not replace them. ICMP "fragmentation needed" is not filtered by this table; if the user's own policy is `drop`, the script warns that it must be allowed (PMTUD).
- **TTL tuning**: `ip ttl set N` at egress, after the forwarding decrement, so every packet leaves with exactly N (default **64**). `--no-ttl` disables it. Purpose: remove the VPN hop and the NAT fingerprint visible to the upstream.
- Counters on every rule so `status` shows that traffic matches.
### 3. Checks before applying
- Root; `nft` present (otherwise offers `pkg_install nftables`, with confirmation; `nftables` is **not** added to `PKG_LIST`, so existing installs are unaffected).
- `nft -c -f` syntax check of the generated file first; `--dry-run` prints the ruleset and the detected parameters and stops here.
- `net.ipv4.ip_forward=1` (set persistently by `install.sh`): verified; if it is 0 the script says so and enables it only after confirmation.
- Warning when `iptables -t nat` already holds a MASQUERADE for the same network (the legacy manual rules of the Hysteria2 chain): both would work, but the rule would be duplicated; the user decides.
- `rp_filter` strict mode (1) on an uplink with asymmetric routes is reported as a hint (Hysteria2 notes require 2).
### 4. Persistence and idempotency
- The ruleset is written to `/etc/ovpmon/nftables.nft` (marker line `managed by ovpmon deploy/native`; a file without the marker is never overwritten) with a record of the detected parameters in `deploy.state`.
- Boot service `ovpmon-nft` (systemd oneshot / OpenRC), unit sources next to the existing ones in `DOCS/General/systemd/` and `DOCS/General/openrc/`, installed with the helpers of `lib.sh`. It only loads the ready file with `nft -f`; interface names are plain strings in the rules, so no ordering against `tun0` is needed. Independent of the distribution's own `nftables.service` and `/etc/nftables.conf`.
- Rerun = regenerate and replace atomically (use after changing the VPN subnet in the UI). `--no-persist` applies to the running kernel only.
- `remove` deletes only what the script created.
## Steps
1. `deploy/native/firewall.sh`: option parsing, detection (`ip -j`, JSON parsed with `ip -j` + `sed`/`awk`; python is not assumed on the host), ruleset generation, checks, `apply|status|remove`.
2. `lib.sh`: small helpers only where reuse is real (CIDR validation, network/interface helpers); the header note "nothing touches the firewall" is refined to name `firewall.sh` as the only exception.
3. Unit files `ovpmon-nft` for systemd and OpenRC.
4. Documentation: Scenario 2 guide (new section replaces the manual nft example; iptables example stays for users of that tool), `README.md` (quick start step), change summary `DOCS/Changes/2026-10-05_NFT_Firewall.md`.
## Verification
- One automated test (`deploy/native/test-firewall.sh`, minimal by project rule): generates the ruleset from a fixture (`--dry-run` with `--vpn-net`/`--vpn-if`), checks it with `nft -c`, and in a throw-away network namespace pair checks the three effects: source address is rewritten, egress TTL equals N, the MSS of a forwarded SYN is clamped. Skipped with a message when namespaces or `nft` are unavailable.
- Manual runs of `apply`, `status`, rerun, `remove` on Alpine (OpenRC) and Debian/Ubuntu (systemd) containers/VMs; reboot persistence check on a VM (containers have no real boot).
- Existing rules of other tables (a user's `inet filter`) are present before and after `apply` and `remove`.
## Decisions to confirm
1. Default TTL **64** with `set` (alternative: `inc N` / `dec`, i.e. relative change).
2. IPv4 only (IPv6 NAT/clamp can be added later together with IPv6 support of the VPN itself).
3. Name `firewall.sh`, not wired into `install.sh`/`update.sh` (explicit opt-in).
## Out of scope
Filtering policy (INPUT/FORWARD allow/drop rules, port opening, anti-leak drop), IPv6, replacing the distribution's `nftables.service`, migration of the manual `iptables` rules of the Hysteria2 chain.