iptables for libvirt

Posted on 2018-02-14 in sysadmin

iptables for forwarding entire ip addresses to an internal IP

This is one way of achieving forwarding a whole IP to an internal IP. Personally i now use macvtap interfaces on the host, so the VM sits directly at layer 2 and the host doesn't have to worry about it, however sometimes you will want be able to block specific ports from ingress / egress on your vm and this solution helps.

1
2
3
4
5
6
7
8
# VM is allowed to receive packets
sudo iptables -I FORWARD -o virbr0 -d {internal_ip} -j ACCEPT

# All packets arriving at {external_ip} need to go to {internal_ip}
sudo iptables -t nat -I PREROUTING -p tcp -d {external_ip} -j DNAT --to {internal_ip}

# All packets leaving {internal_ip} should go from {external_ip}
sudo iptables -t nat -I POSTROUTING -s {internal_ip} -j SNAT --to-source {external_ip}

Iptables for forwarding a single port

If you only want to open pinholes from the internet to your libvirt VMs, you'll want to add a specific rule for each port.

1
2
3
4
5
# Allow the server to receive packets aimed at the port we're forwarding
iptables -I FORWARD -m state --state NEW,RELATED,ESTABLISHED -p tcp --dport {port_number} -d {internal_ip} -j ACCEPT

# Forward packets arriving on the port on the host to the port on the internal ip
iptables -t nat -I PREROUTING -p tcp --dport {port_number} -j DNAT --to-destination {internal_ip}:{port_number}

Note that this will forward packets arriving on any interface where there isn't already a rule in place! If you only want to forward packets from a specific external IP, change the second line to:

1
iptables -t nat -I PREROUTING -p tcp -d {external_ip} --dport {port_number} -j DNAT --to-destination {internal_ip}:{port_number}

Making iptables persist across reboots

To make iptables persist across reboots, i sugges using debian's iptables-persistent package.

1
2
sudo apt-get install iptables-persistent
sudo service netfilter-persistent save