#!/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 < 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 < "$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