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.
wget https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.6.0-amd64-netinst.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=0.0.0.0 --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 192.168.122.141
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 192.168.122.0/24 -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 #!/bin/bash /sbin/iptables -I FORWARD 1 -o virbr0 -m state -d 192.168.122.0/24 --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) # *nat :PREROUTING ACCEPT [0:0] -A PREROUTING -d x.x.x.x -p tcp --dport 2222 -j DNAT --to-destination 192.168.122.141:22 -m comment --comment "SSH port forwarding" COMMIT
Let´s apply our firewall rules
bash /etc/libvirt/hooks/qemu ufw enable -y ufw reload ufw allow 22 ufw allow 2222 ufw reload