Libvirt, UFW and port forwarding via DNAT

I am running several virtual machines on my server for different applications. And I am using port forwarding to route connections to appropriate virtual server. For example, I have separate mail server and I map host's port 25 to this virtual server port 25. I've configure it long time ago and remember struggling with making DNAT forwarding work with libvirt rules. The problem is - libvirt inserts specific rules into iptables BEFORE anything else in there. As a result whatever you define in yours UFW's before.rules will not be applied. There is no way to disable it. There is even bug files and it marked as "wontfix" - https://bugzilla.redhat.com/show_bug.cgi?id=433484

Solution - delete rogue rules after libvirt started. It is half-hack, but it works. I am using Ubuntu and to make it happen every time libvirtd is started, I created following upstart file:

/etc/init/fix-kvm-iptables.conf:
 
description "Fix KVM iptables" 
 
start on started libvirt-bin 
stop on runlevel [!2345] 
 
# delete the rule that prevents forwarding to the VM 
post-start script 
  # it still takes a few seconds for libvirtd to start the virtual 
  # networks and make its (bad) changes to iptables, so wait. 
  sleep 5s 
  logger "Fixing iptables" 
  iptables -D FORWARD -o virbr0 -j REJECT --reject-with icmp-port-unreachable 
  iptables -D FORWARD -j REJECT -i virbr0 --reject-with icmp-port-unreachable 
  iptables -D FORWARD -j ACCEPT -p all -o virbr0 -d 192.168.122.0/24 -m state --state RELATED,ESTABLISHED 
  iptables -D FORWARD -j ACCEPT -i virbr0 -s 192.168.122.0/24 
  iptables -D FORWARD -j ACCEPT -i virbr0 -o virbr0 
end script 

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

To submit this form you need to use Internet Explorer v10+ or recent version of Chrome, Firefox or Safari.