#!/bin/bash
# plinius-forward-set: whether the phone forwards between its networks, as a router does. Off
# by default (GNOME Settings › Security › Forward Between Networks runs this through pkexec).
#
# The kernel forwards IPv4 once something switches it on (the hotspot, the USB network to a
# computer, Android in its container all do), and the firewall then let everything through:
# a device in the same Wi-Fi could reach the mobile network, the USB network or a VPN through
# the phone. Off, FORWARD drops what nothing allowed; the hotspot (NetworkManager's
# nm-sh-fw-* chains), the USB network (plinius-usb) and Android (waydroid-net.sh) let their own
# traffic through with rules of their own and keep working. On, FORWARD accepts everything and
# IPv4 forwarding is switched on.
#
# Those rules of their own accept by incoming interface only (NetworkManager: "-i ap0 -s NET",
# plinius-usb: "-i usb0"), whatever the way out, and both insert them at the top of FORWARD when
# the hotspot or the USB network comes up. So off also keeps the chain "plinius-forward" in the
# mangle table, jumped to first from its FORWARD: it drops what crosses from the hotspot or the
# USB network into a tunnel (a VPN, which would carry a guest into a company network as the
# phone), between the hotspot and the USB network, and new connections from either into Android.
# The mangle table sees every forwarded packet before the filter table does, whatever order the
# ACCEPT rules there come in, and nothing else on the phone puts rules into its FORWARD; what the
# chain does not drop (the way to the internet over Wi-Fi or mobile data) goes on to the rules
# above. On removes the chain.
#
# IPv6 forwarding stays as it is either way: switched on, the kernel would ignore the router
# advertisements of Wi-Fi and mobile data and leave the phone without its IPv6 addresses.
#
#   plinius-forward-set allow|deny   change the choice and apply it
#   plinius-forward-set apply        apply /etc/plinius-forward.conf (at boot, plinius-forward.service)
#   plinius-forward-set status       print the choice
#
# polkit (org.plinius.forward.policy): "allow" asks for an administrator's PIN, "deny" does not.
#
# SPDX-License-Identifier: MIT
set -euo pipefail

conf=/etc/plinius-forward.conf
ip_forward=/proc/sys/net/ipv4/ip_forward
chain=plinius-forward
# The networks the phone serves: the hotspot and the USB network to a computer
served=(ap+ usb+)
# Tunnels: OpenVPN and OpenConnect (tun, tap; vpn from NetworkManager-openconnect), WireGuard,
# L2TP and PPTP (ppp), IPsec interfaces (ipsec, vti, xfrm), Tailscale, ZeroTier. A WireGuard
# connection given a name of its own (not wg…) is not among them.
tunnels=(tun+ tap+ vpn+ wg+ ppp+ ipsec+ vti+ xfrm+ tailscale+ zt+)

# The choice ("yes"/"no") from the file; missing file or key, or anything else: no
get() {
	local val
	val=$(sed -n 's/^[[:space:]]*forward[[:space:]]*=[[:space:]]*\([a-z]*\).*/\1/p' "$conf" 2>/dev/null | tail -n1)
	case $val in yes) echo yes ;; *) echo no ;; esac
}

# Writes the choice, keeping the comments of the file
put() {
	local val=$1 tmp
	tmp=$(mktemp "$conf.XXXXXX")
	if [[ -f $conf ]] && grep -q '^[[:space:]]*forward[[:space:]]*=' "$conf"; then
		sed "s/^[[:space:]]*forward[[:space:]]*=.*/forward=$val/" "$conf" >"$tmp"
	else
		{ [[ -f $conf ]] && cat "$conf"; echo "forward=$val"; } >"$tmp"
	fi
	chmod 644 "$tmp"
	mv -f "$tmp" "$conf"
}

# The rules of mangle's FORWARD (iptables -S), empty when they cannot be read
mangle_forward() {
	"$1" -w -t mangle -S FORWARD 2>/dev/null || true
}

# How many of those rules jump to the chain
jumps() {
	grep -cxF -- "-A FORWARD -j $chain" <<<"$1" || true
}

# Fills the chain in one step (*-restore --noflush: declaring it empties it) and makes the jump
# to it the first rule of mangle's FORWARD, exactly once
isolate() {
	local tool=$1 s t rules n i
	{
		echo '*mangle'
		echo ":$chain - [0:0]"
		echo "-A $chain -i ap+ -o usb+ -j DROP"
		echo "-A $chain -i usb+ -o ap+ -j DROP"
		for s in "${served[@]}"; do
			for t in "${tunnels[@]}"; do
				echo "-A $chain -i $s -o $t -j DROP"
				echo "-A $chain -i $t -o $s -j DROP"
			done
			# Android's own rule allows only answers into it (waydroid-net.sh); the hotspot's
			# and the USB network's ACCEPT come before it
			echo "-A $chain -i $s -o waydroid0 -m conntrack --ctstate NEW -j DROP"
		done
		echo 'COMMIT'
	} | "$tool-restore" -w --noflush
	rules=$(mangle_forward "$tool")
	n=$(jumps "$rules")
	if [[ $n == 1 && $(grep -m1 -- '^-A FORWARD ' <<<"$rules") == "-A FORWARD -j $chain" ]]; then
		return 0
	fi
	for ((i = 0; i < n; i++)); do
		"$tool" -w -t mangle -D FORWARD -j "$chain"
	done
	"$tool" -w -t mangle -I FORWARD 1 -j "$chain"
}

# Removes the jumps and the chain; nothing there is fine
unisolate() {
	local tool=$1 n i
	n=$(jumps "$(mangle_forward "$tool")")
	for ((i = 0; i < n; i++)); do
		"$tool" -w -t mangle -D FORWARD -j "$chain" 2>/dev/null || true
	done
	"$tool" -w -t mangle -F "$chain" 2>/dev/null || true
	"$tool" -w -t mangle -X "$chain" 2>/dev/null || true
}

apply() {
	local policy=DROP tool
	[[ $(get) == yes ]] && policy=ACCEPT
	# The policy first: switched on, forwarding must not start before the firewall says so
	for tool in iptables-legacy ip6tables-legacy; do
		"$tool" -w -P FORWARD "$policy"
		if [[ $policy == ACCEPT ]]; then
			unisolate "$tool"
		else
			isolate "$tool"
		fi
	done
	if [[ $policy == ACCEPT ]]; then
		echo 1 >"$ip_forward"
	fi
}

# Exactly one word: run through pkexec, anything more is refused rather than ignored
if [[ $# -ne 1 ]]; then
	set -- usage
fi
case "$1" in
allow)
	put yes
	apply
	;;
deny)
	put no
	apply
	;;
apply)
	apply
	;;
status)
	echo "forward=$(get)"
	;;
*)
	echo "Usage: plinius-forward-set allow|deny | apply | status" >&2
	exit 2
	;;
esac
