Configuring NAT Network for VM

On 2016/02/20 at 21:15

I just went to a meetup talking about netfilter, conntrack and sip in Linux kernel. I used to use Virt-Manager to setup NAT+DHCP for me. I think it is a good time to practice setting up the NAT network and playing with iptables. So the following is my setting notes.

Create a tap device

TUN and TAP are virtual network devices. Here I create a tap0 device and set its ip to 192.168.123.1.

$ sudo tunctl -u fatminmin -t tap0
$ sudo ifconfig tap0 192.168.123.1 up

Configuring NAT with iptables

I enabled ip_forward feature and accept all forwarding packets send from/to tap0. Then, the most important thing to do is to set MASQUERADE mode for SNAT and the NAT starts working after issuing iptable-save.

$ echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
$ sudo iptables -A FORWARD -i tap0 -j ACCEPT
$ sudo iptables -A FORWARD -o tap0 -j ACCEPT
$ sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
$ sudo iptables-save

Starting VMs

Finally, I can just start the VM by specifying using tap0 as tap device and set up the ip settings in the VM manually.

$ sudo qemu-system-x86_64 --enable-kvm \                                                                                                                                                   
-smp 4 -m 4096 -cpu host -vga std \
-drive file=./kali.img,if=virtio \
-net nic,model=virtio -net tap,ifname=tap0,script=no \
-boot d \
-usbdevice tablet

IP settings in VM * IP: 192.168.123.100 * Netmask: 255.255.255.0 * Gateway: 192.168.123.1

Comments