Linux – With iptables how to route traffic from virtualbox internal adaptor to eth0 interface

iptableslinux

i was learning iptables a bit deeper and things were going good but i am confused with using DNAT, SNAT and MASQUERADE, i was doing paractice with them and couldn't find a way to simply route traffic from one interface to another like i tried to route traffic from virtualbox host-only adaptor to eth0(i dont really know whether its possible with iptables) , i found several posts on internet about this topic (like routing between wlan0 to eth0 etc) with a lot of iptables syntax but none seems to be working, so can anyone provide the right syntax for this or can even tell may be with some other table in the iptables or at least the use of SNAT,DNAT and MASQUERADE.

Best Answer

Before coming to iptables, it is not the only thing you need. First, on the host you must enable IPv4 forwarding,

 echo 1 > /proc/sys/net/ipv4/ip_forward

and, on the guest, you must setup a default gateway,

 ip route add default via 192.168.56.1 dev eth0

if your internal adapter is using the subnet 192.168.56.0/24 (the default), otherwise change accordingly.

As for iptables: packets coming thru the internal adapter and trying to reach the internet will carry as a source address that of the guest, which on your LAN of course no one knows since it belongs to a different subnet, 192.168.56.1. So it will never receive a reply. Thus we need an iptables rule which will re-write the source address to be that of the host, which can be reached by your router/modem/gateway. iptables itself will keep track of the connection so that the reply packets will be sent correctly to the guest, instead of being withheld by the host; there is no need for us to do anything.

Both of these iptables rules will work,

    iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 
    iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 192.168.1.15

(the above assues that the host has IP address 192.168.1.15 and is connected to your modem/gateway/router via eth0; if not, change accordingly). The difference between these two statements is clear: with SNAT you must explicitly state the interface's IP address, with MASQUERADE you do not. So, if for any reason your interface IP address changes, the rule with SNAT is not correct any longer, while the one with MASQUERADE (which checks the IP address every time it is used) you do not need to adjust the rule. Obviously, MASQUERADE is a tad slower than SNAT.

Personally, I prefer MASQUERADE because it makes my firewall configuration portable, but, as they say, YMMV.

Related Question