Skip to content

Instantly share code, notes, and snippets.

@sshimko
Created May 15, 2022 17:50
Show Gist options
  • Save sshimko/cd03799bdc7af549834751cd386b6603 to your computer and use it in GitHub Desktop.
Save sshimko/cd03799bdc7af549834751cd386b6603 to your computer and use it in GitHub Desktop.
Libvirt Allow New to Guests
#!/bin/bash
# libvirt is rude and clobbers rules but lets us hook in via /etc/libvirt/hooks/network, update the IP and NIC if you need to.
# This adds a simple rule to accept NEW incoming packets on a host so a guest (or perhaps something like a UPNP daemon on the host) can determine what comes and goes
# What is looks like before:
# ACCEPT all -- * virbr0 0.0.0.0/0 192.168.122.0/24 ctstate RELATED,ESTABLISHED
# REJECT all -- * virbr0 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
# What it looks like after
# ACCEPT all -- * virbr0 0.0.0.0/0 192.168.122.0/24 state NEW
# ACCEPT all -- * virbr0 0.0.0.0/0 192.168.122.0/24 ctstate RELATED,ESTABLISHED
# REJECT all -- * virbr0 0.0.0.0/0 0.0.0.0/0 reject-with icmp-port-unreachable
# when network is destroyed
if [[ "$2" = "stopped" ]]; then
while /usr/sbin/iptables -C LIBVIRT_FWI -o virbr0 -d 192.168.122.0/24 -m state --state NEW -j ACCEPT 2>/dev/null; do
/usr/sbin/iptables -D LIBVIRT_FWI -o virbr0 -d 192.168.122.0/24 -m state --state NEW -j ACCEPT
done
exit
fi
# only adds the rule when something added to the bridge, not when the bridge is created.
if [[ "$2" == "port-created" || "$2" == "updated" ]]; then
num=$(/usr/sbin/iptables -nL LIBVIRT_FWI --line-num 2>/dev/null|grep -E '^[^1]\s+ACCEPT all -- 0.0.0.0/0 192.168.122.0/24 state NEW'|awk '{ print $1;}')
# if there is a rule, but not in the first position, remove
if [[ x"$num" != "x" && x"$num" != "x1" ]]; then
while /usr/sbin/iptables -C LIBVIRT_FWI -o virbr0 -d 192.168.122.0/24 -m state --state NEW -j ACCEPT 2>/dev/null; do
/usr/sbin/iptables -D LIBVIRT_FWI -o virbr0 -d 192.168.122.0/24 -m state --state NEW -j ACCEPT
done
fi
# now add ours to the first position
/usr/sbin/iptables -I LIBVIRT_FWI -o virbr0 -d 192.168.122.0/24 -m state --state NEW -j ACCEPT
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment