VMs/startnat.sh

65 lines
1.7 KiB
Bash
Executable File

#!/bin/bash -e
DIR="$(dirname "${BASH_SOURCE[0]}")"
fix_nft_drops() {
local j h chain
: > "$DIR/restore-nft.conf"
j="$(nft -j list chains | jq '.[][].chain | select(.policy == "drop")')"
while read -r h; do
mapfile -t chain < <(jq -r "select(.policy != \"accept\" and .hook == \"$h\") | .family,.table,.name,.policy" <<< "$j")
if [ -n "${chain[0]}" ]; then
nft add chain "${chain[0]}" "${chain[1]}" "${chain[2]}" '{ policy accept; }'
echo "add chain ${chain[0]} ${chain[1]} ${chain[2]} { policy ${chain[3]}; }" >> "$DIR/restore-nft.conf"
fi
done < <(nft -j list chains | jq -r '.[][].chain | select(.table == "qemu") | .hook')
}
command -V dnsmasq > /dev/null
command -V nft > /dev/null
if [ "$EUID" != 0 ]; then
echo 'this script must be run as root' >&2
exit 1
fi
BRIDGE="${1-virbr0}"
modprobe nft_masq
sysctl net.ipv4.conf.all.forwarding=1
if ! ip link show "$BRIDGE" 2> /dev/null; then
ip link add "$BRIDGE" type bridge
fi
ip link set dev "$BRIDGE" up
ip address flush dev "$BRIDGE"
ip address add 192.168.123.1/24 dev "$BRIDGE"
nft -f- <<EOF
destroy table ip qemu;
table ip qemu {
chain input {
type filter hook input priority filter; policy accept;
iifname "$BRIDGE" counter
}
chain forward {
type filter hook forward priority filter; policy accept;
iifname "$BRIDGE" counter
}
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
masquerade
}
}
EOF
fix_nft_drops
if ! pidof dnsmasq | grep -q "$(cat /var/run/dnsmasq-virbr0.pid)"; then
dnsmasq -z \
-i "$BRIDGE" \
-F 192.168.123.2,192.168.123.254,255.255.255.0 \
-x /var/run/dnsmasq-virbr0.pid \
--server 1.1.1.1
fi