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.
+38 -2
View File
@@ -199,6 +199,7 @@ Create the `ovpmon` user and the directories, copy the code, build both virtuale
| Helper configuration | `/etc/ovpmon/helper.conf` | `root:root` 644 |
| TLS certificate and key | `/etc/ovpmon/tls/ovpmon.crt`, `ovpmon.key` | `root:root` (key 600) |
| Deployment state | `/etc/ovpmon/deploy.state` | `root:root` 644 |
| nftables ruleset of the VPN clients (only after `firewall.sh`) | `/etc/ovpmon/nftables.nft`, service `ovpmon-nft` | `root:root` 644 |
| Root helper | `/usr/local/sbin/ovpmon-helper` | `root:root` 755 |
| doas rules | Alpine: `/etc/doas.d/ovpmon.conf`; Debian/Ubuntu: block in `/etc/doas.conf` | `root:root` |
| OpenVPN configuration | `/etc/openvpn/server.conf` (Alpine) or `/etc/openvpn/server/server.conf`, `/etc/openvpn/crl.pem`, `/etc/openvpn/scripts/` | `root:root` |
@@ -243,9 +244,44 @@ With the unprivileged profiler the API only stages `server.conf`; **the helper c
OpenRC runs `/sbin/rc-service <unit> <action>`, systemd runs `systemctl <action> <unit>` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse.
## Firewall, NAT and forwarding (manual)
## Firewall, NAT and forwarding
The scripts **never touch the firewall**. `net.ipv4.ip_forward=1` is set persistently in `/etc/sysctl.d/98-ovpmon-forward.conf`. You open the ports and give the VPN clients access yourself. Replace `eth0` with the uplink interface and `172.20.1.0/24` with the VPN subnet of the server settings.
`install.sh` and `update.sh` **never touch the firewall**. `net.ipv4.ip_forward=1` is set persistently in `/etc/sysctl.d/98-ovpmon-forward.conf`. Opening the ports (UI, VPN) is yours. NAT and packet tuning for the VPN clients are done by a separate opt-in script.
### `deploy/native/firewall.sh` (nftables)
Reads the interfaces of this server and applies, for traffic **from the VPN network to every other network**: masquerade, TCP MSS clamping (path MTU tuning) and TTL tuning. Run it as root after the VPN server configuration exists (the VPN network is read from the `server` line of `server.conf`).
```sh
deploy/native/firewall.sh --dry-run # show what was detected and the ruleset; change nothing
deploy/native/firewall.sh # apply, ask for confirmation, load at boot
deploy/native/firewall.sh status # loaded rules with counters, boot service, detected parameters
deploy/native/firewall.sh remove # delete the rules, the ruleset file and the boot service
```
| Option | Meaning |
|---|---|
| `--vpn-net CIDR` | VPN network. Default: `server` line of the OpenVPN config, else the address of the VPN interface |
| `--vpn-if NAME` | VPN interface. Default: the interface with an address in the VPN network, else the `dev` line, else `tun*` |
| `--out-if A,B` | Only these interfaces (exact names) are "other networks". Default: every interface except `lo` and the VPN interface, so new uplinks (VLAN, `hytun`, a second ISP) need no rerun |
| `--ttl N` / `--no-ttl` | TTL of packets leaving towards the other networks (default 64, set after the forwarding decrement) |
| `--mss pmtu\|N` / `--no-mss` | TCP MSS of SYN and SYN-ACK in both directions: `pmtu` = MTU of the route of each connection (default), or a fixed value |
| `--no-persist` | Running kernel only: no ruleset file, no boot service |
| `--yes`, `--force` | No questions; continue on an untested OS version |
What it creates: only the table `ip ovpmon` (replaced atomically with `nft -f`; other tables and the distribution's `nftables.service` are not touched), the ruleset file `/etc/ovpmon/nftables.nft` and the boot service `ovpmon-nft` (systemd oneshot / OpenRC). The `nftables` package is installed on request only (it is not part of the install packages). IPv4 only.
Notes:
- "Every other network" includes container bridges and tunnels on the host; use `--out-if` to limit it.
- The VPN network must not overlap with the network of another interface (the script stops).
- The options are not remembered: after a change of the VPN subnet in the UI run the script again with the same options.
- The MSS clamp complements `tun-mtu` / `mssfix` of the server settings, it does not replace them. If another nftables table has a `policy drop`, allow the VPN traffic and ICMP "fragmentation needed" (type 3, code 4) there, otherwise path MTU discovery fails.
- Old manual rules (`iptables -t nat ... MASQUERADE` for the same network) are reported: remove them when this script is the one to keep.
- The filtering policy (INPUT/FORWARD allow/drop, ports, anti-leak) is not part of the script.
### Manual rules (iptables / nftables)
Replace `eth0` with the uplink interface and `172.20.1.0/24` with the VPN subnet of the server settings.
```sh
# iptables: services
+29
View File
@@ -0,0 +1,29 @@
#!/sbin/openrc-run
# managed by ovpmon deploy/native (firewall.sh replaces this file only while this marker line is present)
#
# Loads the nftables rules of the VPN clients (masquerade, TCP MSS clamp, TTL) at boot, OpenRC (Alpine).
# Install: `deploy/native/firewall.sh` renders this script into /etc/init.d/ovpmon-nft, adds it to the default
# runlevel and starts it. Independent of the distribution's nftables service: only the table `ip ovpmon`
# is loaded and removed. Guide: DOCS/Deployment/Scenario2_System_Services.md
name="ovpmon-nft"
description="NAT, MSS and TTL rules for the VPN clients (nftables)"
rules="/etc/ovpmon/nftables.nft"
depend() {
need localmount
before net
}
start() {
ebegin "Loading $rules"
nft -f "$rules"
eend $?
}
stop() {
ebegin "Removing the table ip ovpmon"
nft delete table ip ovpmon 2>/dev/null
eend 0
}
+20
View File
@@ -0,0 +1,20 @@
# managed by ovpmon deploy/native (firewall.sh replaces this file only while this marker line is present)
#
# Loads the nftables rules of the VPN clients (masquerade, TCP MSS clamp, TTL) at boot.
# Install: `deploy/native/firewall.sh` renders and enables this unit together with /etc/ovpmon/nftables.nft.
# Independent of the distribution's nftables.service: only the table `ip ovpmon` is loaded and removed.
# Guide: DOCS/Deployment/Scenario2_System_Services.md
[Unit]
Description=OpenVPN Monitor: NAT, MSS and TTL rules for the VPN clients (nftables)
Wants=network-pre.target
Before=network-pre.target
ConditionPathExists=/etc/ovpmon/nftables.nft
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/sbin/nft -f /etc/ovpmon/nftables.nft
ExecStop=-/usr/sbin/nft delete table ip ovpmon
[Install]
WantedBy=multi-user.target
+2
View File
@@ -15,6 +15,7 @@ Nginx is the only public entry point: `/` UI, `/api/` Monitoring API, `/profiles
- **Containers:** `deploy/docker/install.sh --variant a|b`, open `http://<host>`. Details: [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) (update, backup, rollback included).
- **System services** (Alpine/OpenRC, Debian and Ubuntu/systemd, no containers): `deploy/native/install.sh --prefix DIR` (the install directory is always asked for; the checkout is only the source; the web UI is installed from `deploy/ui-dist` of the repository); details, update and rollback: [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md).
- **NAT, MSS and TTL for the VPN clients** (nftables, optional): `deploy/native/firewall.sh [--dry-run]` reads the interfaces of the server and sets masquerade, TCP MSS clamping and TTL for traffic from the VPN network to all other networks; see [Firewall, NAT and forwarding](DOCS/Deployment/Scenario2_System_Services.md#firewall-nat-and-forwarding).
After the first start: sign in, open **PKI Configuration** → **Initialize PKI**, generate the server config, start OpenVPN, create profiles.
@@ -68,6 +69,7 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US
| 2026-10-05 | Database migrations with backup, integrity checks and downgrade protection; standalone `migrate.py` (phase 1 of install/update scenarios) | [Database migrations](DOCS/Changes/2026-10-05_DB_Migrations.md) |
| 2026-10-05 | Scenario 1: container install and update, variant A (one container) and B (per component); backup, restore, automatic rollback | [Scenario 1: containers](DOCS/Deployment/Scenario1_Containers.md) · [change](DOCS/Changes/2026-10-05_Scenario1_Containers.md) |
| 2026-10-05 | Scenario 2: install and update as system services on Alpine, Debian, Ubuntu; helper config for systemd; backup, restore, automatic rollback | [Scenario 2: system services](DOCS/Deployment/Scenario2_System_Services.md) · [change](DOCS/Changes/2026-10-05_Scenario2_System_Services.md) |
| 2026-10-05 | nftables script for system-service installs: masquerade, TCP MSS clamping (path MTU) and TTL for traffic from the VPN network to all other networks; boot service | [Firewall, NAT and forwarding](DOCS/Deployment/Scenario2_System_Services.md#firewall-nat-and-forwarding) · [plan](DOCS/Changes/2026-10-05_NFT_Firewall_PLAN.md) · [change](DOCS/Changes/2026-10-05_NFT_Firewall.md) |
## Notes
+513
View File
@@ -0,0 +1,513 @@
#!/bin/sh
# nftables rules for the VPN clients (system-service installs: Alpine, Debian, Ubuntu): masquerade, TCP MSS
# clamping (path MTU tuning) and TTL tuning for traffic going from the VPN network to every other network.
#
# deploy/native/firewall.sh [apply] [options] detect, show, apply and make the rules persistent (default)
# deploy/native/firewall.sh status loaded rules with counters, boot service, detected parameters
# deploy/native/firewall.sh remove delete the rules, the ruleset file and the boot service
#
# --dry-run print the detected parameters and the ruleset, check its syntax, change nothing
# --vpn-net CIDR VPN network, e.g. 172.20.1.0/24 (default: the `server` line of the OpenVPN config, else the
# address of the VPN interface)
# --vpn-if NAME VPN interface (default: the interface with an address in the VPN network, else the `dev`
# line of the OpenVPN config, else the pattern tun*)
# --out-if A,B only these interfaces count as "other networks" (exact names). Default: every interface
# except lo and the VPN interface, so new uplinks (VLAN, hytun, ...) need no rerun
# --ttl N TTL of packets leaving towards the other networks, 1-255 (default 64)
# --no-ttl leave the TTL alone
# --mss pmtu|N TCP MSS clamp: pmtu = MTU of the route of each connection (default), or a fixed value
# --no-mss do not touch the TCP MSS
# --no-persist load the rules into the running kernel only (no ruleset file, no boot service)
# --yes do not ask for confirmation
# --force continue on an untested OS version / Debian derivative
#
# Run as root. Only the table `ip ovpmon` is created or replaced (atomically); other nftables tables and the
# distribution's nftables service are never touched. IPv4 only. The options are not remembered: give them on
# every run (e.g. after the VPN subnet was changed in the UI). Persistence: /etc/ovpmon/nftables.nft loaded at
# boot by the service ovpmon-nft. install.sh and update.sh do not call this script.
# See DOCS/Deployment/Scenario2_System_Services.md
set -eu
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
. "$SCRIPT_DIR/lib.sh"
RULES_FILE="$ETC_DIR/nftables.nft"
NFT_TABLE=ovpmon
NFT_SERVICE=ovpmon-nft
usage() {
sed -n '2,/^[^#]/{/^#/p}' "$0" | sed 's/^# \{0,1\}//'
}
CMD=apply
DRY_RUN=0
ASSUME_YES=0
FORCE=0
PERSIST=1
VPN_NET=""
VPN_IF=""
OUT_IF=""
TTL=64
MSS=pmtu
while [ $# -gt 0 ]; do
case "$1" in
apply|status|remove) CMD="$1"; shift ;;
--dry-run) DRY_RUN=1; shift ;;
--vpn-net) [ $# -ge 2 ] || die "--vpn-net needs a value"; VPN_NET="$2"; shift 2 ;;
--vpn-if) [ $# -ge 2 ] || die "--vpn-if needs a value"; VPN_IF="$2"; shift 2 ;;
--out-if) [ $# -ge 2 ] || die "--out-if needs a value"; OUT_IF="$2"; shift 2 ;;
--ttl) [ $# -ge 2 ] || die "--ttl needs a value"; TTL="$2"; shift 2 ;;
--no-ttl) TTL=""; shift ;;
--mss) [ $# -ge 2 ] || die "--mss needs a value"; MSS="$2"; shift 2 ;;
--no-mss) MSS=""; shift ;;
--no-persist) PERSIST=0; shift ;;
--yes|-y) ASSUME_YES=1; shift ;;
--force) FORCE=1; shift ;;
-h|--help) usage; exit 0 ;;
*) usage >&2; die "unknown argument: $1" ;;
esac
done
# ---------------------------------------------------------------------------------------------
# IPv4 arithmetic (POSIX shell integers, 64 bit)
# ---------------------------------------------------------------------------------------------
valid_ipv4() {
printf '%s' "$1" | grep -Eq '^(0|[1-9][0-9]{0,2})(\.(0|[1-9][0-9]{0,2})){3}$' || return 1
( IFS=.; for o in $1; do [ "$o" -le 255 ] || exit 1; done )
}
ip2int() { ( IFS=.; set -- $1; echo $(( ($1 << 24) + ($2 << 16) + ($3 << 8) + $4 )) ); }
int2ip() { echo "$(( ($1 >> 24) & 255 )).$(( ($1 >> 16) & 255 )).$(( ($1 >> 8) & 255 )).$(( $1 & 255 ))"; }
prefix2mask() {
if [ "$1" -eq 0 ]; then echo 0; else echo $(( (0xFFFFFFFF << (32 - $1)) & 0xFFFFFFFF )); fi
}
# mask_to_prefix 255.255.255.0 -> 24 (fails for a non-contiguous mask)
mask_to_prefix() {
local m inv n
valid_ipv4 "$1" || return 1
m=$(ip2int "$1")
inv=$(( ~m & 0xFFFFFFFF ))
[ $(( inv & (inv + 1) )) -eq 0 ] || return 1
n=0
while [ "$inv" -gt 0 ]; do inv=$(( inv >> 1 )); n=$(( n + 1 )); done
echo $(( 32 - n ))
}
# parse_cidr A.B.C.D/P: sets NET_ADDR (network address) and NET_PREFIX; prefix 8..30
parse_cidr() {
local addr p
case "$1" in */*) ;; *) return 1 ;; esac
addr=${1%/*}; p=${1#*/}
valid_ipv4 "$addr" || return 1
case "$p" in ''|*[!0-9]*) return 1 ;; esac
[ "$p" -ge 8 ] && [ "$p" -le 30 ] || return 1
NET_PREFIX=$p
NET_ADDR=$(int2ip $(( $(ip2int "$addr") & $(prefix2mask "$p") )))
}
# in_net ADDR NET PREFIX
in_net() {
local m
m=$(prefix2mask "$3")
[ $(( $(ip2int "$1") & m )) -eq $(( $(ip2int "$2") & m )) ]
}
# nets_overlap A PA B PB: one network contains the other
nets_overlap() {
local p m
p=$2; [ "$4" -lt "$p" ] && p=$4
m=$(prefix2mask "$p")
[ $(( $(ip2int "$1") & m )) -eq $(( $(ip2int "$3") & m )) ]
}
valid_ifname() { printf '%s' "$1" | grep -Eq '^[A-Za-z0-9_.:-]{1,15}$'; }
# ---------------------------------------------------------------------------------------------
# Reading the local configuration
# ---------------------------------------------------------------------------------------------
# collect_interfaces: $TMP_DIR/addrs ("name addr/prefix"), $TMP_DIR/links ("name mtu state")
collect_interfaces() {
command -v ip >/dev/null 2>&1 || die "the 'ip' command was not found (package iproute2)"
ip -o -4 addr show 2>/dev/null | awk '{ n = $2; sub(/:$/, "", n); print n, $4 }' > "$TMP_DIR/addrs"
ip -o link show 2>/dev/null | awk '{
n = $2; sub(/:$/, "", n); sub(/@.*/, "", n)
m = "?"; s = "?"
for (i = 3; i < NF; i++) { if ($i == "mtu") m = $(i + 1); if ($i == "state") s = $(i + 1) }
print n, m, s }' > "$TMP_DIR/links"
[ -s "$TMP_DIR/links" ] || die "no network interfaces could be read with 'ip link'"
}
# conf_get KEY: value of the first KEY line of the OpenVPN config (comments stripped); empty when unknown
conf_get() {
[ -r "$OVPN_CONFIG" ] || return 0
sed -e 's/[#;].*$//' "$OVPN_CONFIG" | awk -v k="$1" '$1 == k { $1 = ""; sub(/^[ \t]+/, ""); print; exit }'
}
# iface_cidr NAME|tun: first IPv4 address (addr/prefix) of an interface; "tun" = first tunN interface
iface_cidr() {
if [ "$1" = tun ]; then
awk '$1 ~ /^tun[0-9]*$/ { print $2; exit }' "$TMP_DIR/addrs"
else
awk -v i="$1" '$1 == i { print $2; exit }' "$TMP_DIR/addrs"
fi
}
# resolve_vpn_net: NET_ADDR, NET_PREFIX, VPN_NET_SRC
resolve_vpn_net() {
local v mask p cidr
if [ -n "$VPN_NET" ]; then
parse_cidr "$VPN_NET" || die "--vpn-net '$VPN_NET': expected A.B.C.D/P with a prefix from 8 to 30"
VPN_NET_SRC="--vpn-net"
return 0
fi
v=$(conf_get server)
if [ -n "$v" ]; then
set -- $v
mask=${2:-}
p=$(mask_to_prefix "$mask") || die "$OVPN_CONFIG: cannot read the netmask of the line 'server $v'"
parse_cidr "$1/$p" || die "$OVPN_CONFIG: the VPN network of the line 'server $v' is not usable (prefix 8..30 expected): use --vpn-net"
VPN_NET_SRC="$OVPN_CONFIG"
return 0
fi
cidr=$(iface_cidr "${VPN_IF:-tun}")
[ -n "$cidr" ] || die "the VPN network is unknown: no 'server' line in $OVPN_CONFIG (generate the server configuration in the UI first) and no VPN interface with an address. Use --vpn-net"
case "$cidr" in */*) ;; *) cidr="$cidr/32" ;; esac
parse_cidr "$cidr" || die "address $cidr of the VPN interface is not a usable network (prefix 8..30 expected): use --vpn-net"
VPN_NET_SRC="address of the VPN interface"
}
# resolve_vpn_if: VPN_IF (a name or a pattern such as tun*), VPN_IF_SRC
resolve_vpn_if() {
local name cidr addr d
if [ -n "$VPN_IF" ]; then
valid_ifname "${VPN_IF%\*}" || die "--vpn-if '$VPN_IF' is not a valid interface name (a trailing * is allowed)"
VPN_IF_SRC="--vpn-if"
return 0
fi
while read -r name cidr; do
[ "$name" = lo ] && continue
addr=${cidr%/*}
valid_ipv4 "$addr" || continue
if in_net "$addr" "$NET_ADDR" "$NET_PREFIX"; then
VPN_IF=$name
VPN_IF_SRC="address in the VPN network"
return 0
fi
done < "$TMP_DIR/addrs"
d=$(conf_get dev)
d=${d%% *}
case "$d" in
'') ;;
tun|tap) VPN_IF="$d*"; VPN_IF_SRC="dev line of $OVPN_CONFIG"; return 0 ;;
*) if valid_ifname "$d"; then VPN_IF=$d; VPN_IF_SRC="dev line of $OVPN_CONFIG"; return 0; fi ;;
esac
VPN_IF="tun*"
VPN_IF_SRC="default (the VPN is not running yet)"
}
# check_overlap: the VPN network must not coincide with a network of another interface
check_overlap() {
local name cidr addr p
while read -r name cidr; do
case "$name" in lo|$VPN_IF) continue ;; esac
addr=${cidr%/*}
case "$cidr" in */*) p=${cidr#*/} ;; *) p=32 ;; esac
valid_ipv4 "$addr" || continue
if nets_overlap "$addr" "$p" "$NET_ADDR" "$NET_PREFIX"; then
die "the VPN network $NET_ADDR/$NET_PREFIX overlaps with $cidr of the interface $name: NAT cannot tell them apart. Change the VPN subnet or the interface address"
fi
done < "$TMP_DIR/addrs"
}
# validate_out_if: the exact names of --out-if
validate_out_if() {
local n
[ -n "$OUT_IF" ] || return 0
for n in $(printf '%s' "$OUT_IF" | tr ',' ' '); do
valid_ifname "$n" || die "--out-if: '$n' is not a valid interface name (wildcards are not supported here)"
case "$n" in lo|$VPN_IF) die "--out-if: '$n' is the loopback or the VPN interface itself" ;; esac
awk -v i="$n" '$1 == i { f = 1 } END { exit !f }' "$TMP_DIR/links" || warn "--out-if: interface $n does not exist now (the rule is still created)"
done
}
# report_interfaces: the networks the rules apply to
report_interfaces() {
local name mtu state addrs
while read -r name mtu state; do
case "$name" in lo|$VPN_IF) continue ;; esac
if [ -n "$OUT_IF" ]; then
case ",$OUT_IF," in *",$name,"*) ;; *) continue ;; esac
fi
addrs=$(awk -v n="$name" '$1 == n { printf "%s ", $2 }' "$TMP_DIR/addrs")
log " $name mtu $mtu state $state ${addrs:-no IPv4 address}"
done < "$TMP_DIR/links"
}
resolve_all() {
collect_interfaces
resolve_vpn_net
resolve_vpn_if
check_overlap
validate_out_if
}
validate_options() {
if [ -n "$TTL" ]; then
case "$TTL" in *[!0-9]*) die "--ttl '$TTL': a number from 1 to 255 is expected" ;; esac
[ "$TTL" -ge 1 ] && [ "$TTL" -le 255 ] || die "--ttl '$TTL': a number from 1 to 255 is expected"
fi
if [ -n "$MSS" ] && [ "$MSS" != pmtu ]; then
case "$MSS" in *[!0-9]*) die "--mss '$MSS': 'pmtu' or a number from 536 to 65535 is expected" ;; esac
[ "$MSS" -ge 536 ] && [ "$MSS" -le 65535 ] || die "--mss '$MSS': 'pmtu' or a number from 536 to 65535 is expected"
fi
}
# ---------------------------------------------------------------------------------------------
# Ruleset
# ---------------------------------------------------------------------------------------------
# build_ruleset OUT: the nftables file; one transaction (add + delete + define) replaces the table atomically
build_ruleset() {
local oo oi list mss_val net
net="$NET_ADDR/$NET_PREFIX"
if [ -n "$OUT_IF" ]; then
list=$(printf '%s' "$OUT_IF" | sed -e 's/[^,][^,]*/"&"/g' -e 's/,/, /g')
oo="oifname { $list }"
oi="iifname { $list }"
else
oo="oifname != \"$VPN_IF\""
oi="iifname != \"$VPN_IF\""
fi
{
cat <<EOF
# $MARKER (firewall.sh): regenerated by 'deploy/native/firewall.sh apply', do not edit
# VPN network $net, VPN interface $VPN_IF, other networks: ${OUT_IF:-all interfaces except the VPN one}
add table ip $NFT_TABLE
delete table ip $NFT_TABLE
table ip $NFT_TABLE {
# VPN network -> other networks: source address rewriting
chain nat_postrouting {
type nat hook postrouting priority srcnat; policy accept;
ip saddr $net $oo counter masquerade
}
EOF
if [ -n "$TTL" ]; then
cat <<EOF
# TTL at egress (after the forwarding decrement): every packet leaves with exactly $TTL
chain ttl_postrouting {
type filter hook postrouting priority mangle; policy accept;
ip saddr $net $oo counter ip ttl set $TTL
}
EOF
fi
if [ -n "$MSS" ]; then
if [ "$MSS" = pmtu ]; then mss_val="rt mtu"; else mss_val="$MSS"; fi
cat <<EOF
# TCP MSS of SYN and SYN-ACK in both directions (path MTU tuning)
chain mss_forward {
type filter hook forward priority mangle; policy accept;
iifname "$VPN_IF" ip saddr $net $oo tcp flags & (syn | rst) == syn counter tcp option maxseg size set $mss_val
oifname "$VPN_IF" ip daddr $net $oi tcp flags & (syn | rst) == syn counter tcp option maxseg size set $mss_val
}
EOF
fi
echo "}"
} > "$1"
}
# ---------------------------------------------------------------------------------------------
# Preflight
# ---------------------------------------------------------------------------------------------
ensure_nft() {
command -v nft >/dev/null 2>&1 && return 0
if [ "$DRY_RUN" = 1 ] || [ "$CMD" != apply ]; then
return 1
fi
confirm "nftables is not installed. Install the package 'nftables'?" || die "nft is required"
pkg_install nftables
command -v nft >/dev/null 2>&1 || die "nft is still not available after the installation"
}
# preflight_notes: warnings only; nothing here stops the script
preflight_notes() {
local fwd rpf rules
fwd=$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo "?")
if [ "$fwd" != 1 ]; then
warn "net.ipv4.ip_forward is $fwd: the server does not forward packets (install.sh sets it persistently in $SYSCTL_FILE)"
if [ "$CMD" = apply ] && [ "$DRY_RUN" != 1 ] && confirm "Enable forwarding in the running kernel now (sysctl -w net.ipv4.ip_forward=1)?"; then
sysctl -qw net.ipv4.ip_forward=1
[ -f "$SYSCTL_FILE" ] || warn "$SYSCTL_FILE does not exist: forwarding will not survive a reboot"
fi
fi
if command -v iptables >/dev/null 2>&1 \
&& iptables -t nat -S POSTROUTING 2>/dev/null | grep -q -e "-s $NET_ADDR/$NET_PREFIX .*MASQUERADE"; then
warn "iptables already has a MASQUERADE rule for $NET_ADDR/$NET_PREFIX (the manual rules): the traffic is matched by both. Remove the old rule when this script is the one to keep"
fi
rpf=$(cat /proc/sys/net/ipv4/conf/all/rp_filter 2>/dev/null || echo 0)
rules=$(ip rule show 2>/dev/null | wc -l)
if [ "$rpf" = 1 ] && [ "$rules" -gt 3 ]; then
warn "rp_filter=1 (strict) with policy routing rules present: replies arriving through another interface are dropped. Use 2 (loose) when the VPN traffic is routed through a tunnel such as hytun"
fi
if command -v nft >/dev/null 2>&1 && nft list ruleset 2>/dev/null | grep -q 'policy drop'; then
warn "another nftables table has a 'policy drop' chain: allow the VPN traffic there (forward tun* -> uplink, replies back) and ICMP 'fragmentation needed' (type 3 code 4), otherwise path MTU discovery fails"
fi
}
show_plan() {
log "VPN network: $NET_ADDR/$NET_PREFIX ($VPN_NET_SRC)"
log "VPN interface: $VPN_IF ($VPN_IF_SRC)"
log "Other networks: ${OUT_IF:-every interface except lo and the VPN interface}"
report_interfaces
log "Masquerade: VPN network -> other networks"
if [ -n "$TTL" ]; then log "TTL: set to $TTL at egress"; else log "TTL: not changed"; fi
if [ -z "$MSS" ]; then log "TCP MSS: not changed"
elif [ "$MSS" = pmtu ]; then log "TCP MSS: clamped to the MTU of the route (both directions)"
else log "TCP MSS: set to $MSS (both directions)"; fi
}
# ---------------------------------------------------------------------------------------------
# Persistence
# ---------------------------------------------------------------------------------------------
install_service() {
local mode rc
rc=0
require_init
render_unit "$ROOT_DIR" "$NFT_SERVICE" "$DEFAULT_PREFIX" "$TMP_DIR/unit"
if [ "$INIT" = systemd ]; then mode=644; else mode=755; fi
install_managed "$TMP_DIR/unit" "$(unit_file "$NFT_SERVICE")" "$mode" "$(unit_src "$ROOT_DIR" "$NFT_SERVICE")" || rc=$?
case "$rc" in
0) log "service definition installed: $(unit_file "$NFT_SERVICE")" ;;
1) ;;
*) die "$(unit_file "$NFT_SERVICE") exists and was not created by these scripts: not replaced, the rules would not be loaded at boot" ;;
esac
svc_defs_reload
svc_enable "$NFT_SERVICE" || warn "could not enable $NFT_SERVICE at boot"
if ! svc_active "$NFT_SERVICE"; then svc_start "$NFT_SERVICE" || warn "$NFT_SERVICE did not start (the rules are loaded anyway)"; fi
}
state_clear() {
[ -f "$STATE_FILE" ] || return 0
sed -i '/^FIREWALL_/d' "$STATE_FILE"
}
# ---------------------------------------------------------------------------------------------
# Commands
# ---------------------------------------------------------------------------------------------
do_apply() {
local rc
validate_options
ensure_nft || HAVE_NFT=0
resolve_all
build_ruleset "$TMP_DIR/ovpmon.nft"
phase 1 "detected configuration"
show_plan
preflight_notes
phase 2 "ruleset"
if [ "$HAVE_NFT" = 1 ]; then
nft -c -f "$TMP_DIR/ovpmon.nft" || die "the generated ruleset was rejected by 'nft -c' (see the message above); nothing was changed"
log "syntax check: ok"
else
warn "nft is not installed: the syntax of the ruleset was not checked"
fi
if [ "$DRY_RUN" = 1 ]; then
indent "$(cat "$TMP_DIR/ovpmon.nft")"
log "dry run: nothing was changed"
return 0
fi
confirm "Apply these rules to the running system$([ "$PERSIST" = 1 ] && echo ' and load them at boot')?" || die "cancelled"
acquire_lock
phase 3 "apply"
if [ "$PERSIST" = 1 ]; then
mkdir -p "$ETC_DIR"
rc=0
install_managed "$TMP_DIR/ovpmon.nft" "$RULES_FILE" 644 "the generated ruleset" || rc=$?
case "$rc" in
0) log "ruleset file written: $RULES_FILE" ;;
1) log "ruleset file unchanged: $RULES_FILE" ;;
*) die "$RULES_FILE exists and was not created by this script: left untouched, nothing was applied" ;;
esac
nft -f "$RULES_FILE" || die "loading $RULES_FILE failed"
log "rules loaded: table ip $NFT_TABLE"
install_service
state_set FIREWALL_VPN_NET "$NET_ADDR/$NET_PREFIX"
state_set FIREWALL_VPN_IF "$VPN_IF"
state_set FIREWALL_OUT_IF "${OUT_IF:-all}"
state_set FIREWALL_TTL "${TTL:-off}"
state_set FIREWALL_MSS "${MSS:-off}"
state_set FIREWALL_APPLIED "$(now_iso)"
else
nft -f "$TMP_DIR/ovpmon.nft" || die "loading the ruleset failed"
log "rules loaded: table ip $NFT_TABLE (running kernel only: they are lost at reboot)"
fi
printf '\n'
log "Done. View: deploy/native/firewall.sh status (or: nft list table ip $NFT_TABLE)"
log "After a change of the VPN subnet run this script again (the options are not remembered)."
}
do_status() {
local k v
phase 1 "kernel"
if command -v nft >/dev/null 2>&1 && nft list table ip "$NFT_TABLE" >/dev/null 2>&1; then
indent "$(nft list table ip "$NFT_TABLE")"
else
log "table ip $NFT_TABLE: not loaded"
fi
log "net.ipv4.ip_forward = $(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo '?')"
phase 2 "persistence"
if [ -f "$RULES_FILE" ]; then log "ruleset file: $RULES_FILE"; else log "ruleset file: none"; fi
if svc_known "$NFT_SERVICE"; then log "service $NFT_SERVICE: $(svc_state_word "$NFT_SERVICE")"; else log "service $NFT_SERVICE: not installed"; fi
for k in VPN_NET VPN_IF OUT_IF TTL MSS APPLIED; do
v=$(state_get "FIREWALL_$k")
[ -z "$v" ] || log "recorded $k: $v"
done
phase 3 "detected now"
( validate_options; resolve_all; show_plan ) || warn "the current configuration could not be read (see above)"
}
do_remove() {
local f
confirm "Remove the nftables rules of the VPN clients (table ip $NFT_TABLE), the ruleset file and the boot service?" || die "cancelled"
acquire_lock
if svc_known "$NFT_SERVICE"; then
if svc_active "$NFT_SERVICE"; then svc_stop "$NFT_SERVICE" || warn "$NFT_SERVICE did not stop"; fi
if [ "$INIT" = systemd ]; then
systemctl disable "$NFT_SERVICE" >/dev/null 2>&1 || true
else
rc-update del "$NFT_SERVICE" default >/dev/null 2>&1 || true
fi
f=$(unit_file "$NFT_SERVICE")
if [ -f "$f" ] && grep -q "$MARKER" "$f"; then
rm -f "$f"
log "removed $f"
elif [ -f "$f" ]; then
warn "$f was not created by these scripts: left in place"
fi
svc_defs_reload
fi
if command -v nft >/dev/null 2>&1 && nft list table ip "$NFT_TABLE" >/dev/null 2>&1; then
nft delete table ip "$NFT_TABLE"
log "table ip $NFT_TABLE deleted"
fi
if [ -f "$RULES_FILE" ] && grep -q "$MARKER" "$RULES_FILE"; then
rm -f "$RULES_FILE"
log "removed $RULES_FILE"
elif [ -f "$RULES_FILE" ]; then
warn "$RULES_FILE was not created by this script: left in place"
fi
state_clear
log "Done."
}
# ---------------------------------------------------------------------------------------------
TMP_DIR=$(mktemp -d)
on_exit() { release_lock; rm -rf "$TMP_DIR"; }
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
HAVE_NFT=1
need_root
check_os
case "$CMD" in
apply) do_apply ;;
status) do_status ;;
remove) do_remove ;;
esac
+2
View File
@@ -525,6 +525,8 @@ Next steps:
iptables -A FORWARD -i tun+ -o $UPLINK -j ACCEPT
iptables -A FORWARD -i $UPLINK -o tun+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
net.ipv4.ip_forward is enabled ($SYSCTL_FILE). Persistence and nftables variants: see the guide.
With nftables: $SCRIPT_DIR/firewall.sh sets masquerade, TCP MSS clamping and TTL for the VPN clients
(read the interfaces, --dry-run first; after the VPN server configuration exists).
5. Replace the self-signed certificate ($TLS_DIR/ovpmon.crt and .key) with a real one when a domain is available.
Update later with: $SCRIPT_DIR/update.sh Backup: $SCRIPT_DIR/backup.sh
Log of this run: $DEPLOY_LOG
+2 -1
View File
@@ -8,7 +8,8 @@
# POSIX sh (dash, busybox ash, bash); `local` is used in functions (supported by all of them).
# Contains the OS adapter: Alpine (OpenRC), Debian and Ubuntu (systemd).
# Nothing here ever deletes a database, the PKI (APP_PROFILER/easy-rsa) or client configs
# (APP_PROFILER/client-config), and nothing touches the firewall.
# (APP_PROFILER/client-config), and nothing touches the firewall except the separate opt-in script
# firewall.sh (its own nftables table `ip ovpmon`).
ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)