Linux tutorials

KVM and UFW port forwarding

This is a tutorial on how to use KVM virtualization using UFW firewall on Ubuntu Server


Let´s find out if virtualization is possible on this phsyical server
 egrep -c '(vmx|svm)' /proc/cpuinfo 
Install KVM packages
 sudo apt install -y qemu qemu-kvm libvirt-daemon libvirt-clients bridge-utils libvirt-daemon-system dnsmasq qemu-utils virt-viewer virtinst ufw tightvncserver 
Make sure libvirtd is running
sudo systemctl enable --now libvirtd
sudo systemctl start libvirtd
sudo systemctl status libvirtd
Guest OS – Debian 10 buster. Let´s download the iso.
Let´s create a virtual disk with the size of 25GB for our Guest OS
 fallocate -l 25G buster.img 
Let´s install Guest OS Debian 10 buster with 4 cpu and 4GB of ram.
 virt-install --name=buster --os-variant=debian10 --vcpu=4 --ram=4096 --graphics vnc,port=5901,listen= --cdrom=/root/debian-10.6.0-amd64-netinst.iso --network bridge:virbr0 --disk /root/buster.img 


UFW and port forwarding

Let´s assume we installed our Debian with IP


Find out info about our installed Guest OS
virsh net-list
virsh net-info default
virsh net-dumpxml default
NB! By default all incoming traffic is blocked.
To bypass that run:
iptables -A FORWARD -d -o virbr0 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT


By default KVM NAT configuration does not include NEW state on ufw configuration.
To solve this issue we are going to create a “hook”
cd /etc/libvirt/hooks/
nano qemu
/sbin/iptables -I FORWARD 1 -o virbr0 -m state -d --state NEW,RELATED,ESTABLISHED -j ACCEPT
chmod +x /etc/libvirt/hooks/qemu


Let´s create port forwarding via UFW
Add to the very beginning of file /etc/ufw/before.rules
In this example we use x.x.x.x instead of actual external IP
# KVM/libvirt Forward Ports to guests with Iptables (UFW) #
-A PREROUTING -d x.x.x.x -p tcp --dport 2222 -j DNAT --to-destination -m comment --comment "SSH port forwarding"


Let´s apply our firewall rules
bash /etc/libvirt/hooks/qemu
ufw enable -y
ufw reload
ufw allow 22
ufw allow 2222
ufw reload
That´s it! You should be able to login to Guest OS.

Leave a Reply

Your email address will not be published. Required fields are marked *