Iptables – libvirt and host firewall

firewalliptableskvm-virtualizationlibvirt

Hiho!

I'm using libvirt with kvm and that works great. My desire is to lock down the host system using a host firewall. Up to today I always used shorewall as my iptables mangement utility of choice. But this conflicts with libvirt's iptables management. I used libvirt to configure NAT for kvm guests. Libvirt sets up MASQ for that using iptables which works fine. But as soon as shorewall starts, it flushes the iptables and sets them up according to the configuration made in the shorewall files. What I then tried is to "translate" all libvirt iptables rules into shorewall to prevent losing functionality. But this works only partly and is an ugly hack anyway. As soon as I change the network config with libvirt for a guest, I have to make changes to shorewall as well. So what would be the proper way to both secure the host system as well as using libvirt to manage the network of the kvm guests? Is libvirt coupled with firewalld in the CentOS world?
cheerio!

Best Answer

Maybe you can use libvirt's hook script. You script a shell script that libvirt will execute as soon as your VM is started.

Create the file /etc/libvirt/hooks/qemu with this inside:

    #!/bin/bash
    if [ "${1}" = "<the name of your vm>" ] ; then
      VM_NAME=${1}
      VM_IP=172.16.20.10
      if [ "${2}" = "prepare" ] ; then
        iptables -t nat -I POSTROUTING -s ${VM_IP} -o eth0 \
            -m comment --comment "${VM_NAME} nat" -j MASQUERADE
      elif [ "%{2}" = release" ] ; then
        iptables -t nat -D POSTROUTING -s ${VM_IP} -o eth0 \
            -m comment --comment "${VM_NAME} nat" -j MASQUERADE
    fi

Make sure you substitute the <the name of yout vm> and the value of VM_IP appropriately. Make the file executable too: chmod +x /etc/libvirt/hooks/qemu.

Now, every time libvirt start your VM, it will prepare the NAT configuration and after VM stop, will deconfigure the NAT.

For more information, you can look at here and here