Nat – Forwarding traffic from TUN device (C++ backend) to the default gateway

forwardingicmpnat;routingtun

The following problem is just a piece of the bigger solution I have a problem with. All other elements seem working so far, so I'll try to describe very small piece which I have problem with.

I've got a linux machine, with tun0 (tunneling interface) and eth0 (witch is my default gateway to the internet).

Goal: my goal is to receive packets incoming from tun0, and forward them to the default gateway. So actually quite simple NAT case, where I want to "share" internet with tun0 which fakes physical interface.

Tun has been created using

sudo openvpn --mktun --dev tun0 --user USER
sudo ip addr add 10.2.0.1/24 dev tun0
sudo ip link set tun0 up

So I have it up and running, I can ping it etc. Furthermore, I have C++ application, which attaches to this TUN device, can read from and write to it. (fti: here is a tutorial I've followed: http://backreference.org/2010/03/26/tuntap-interface-tutorial/)

I dumped some correct ICMP (ping) request made to 8.8.8.8 into the byte array in C++. Now, using my program I write it to the tun0 device. ICMP request has

  • source (10.2.0.10) – so kernel knows the route back (the same subnet)
  • destination (8.8.8.8) – Google's DNS
  • correct checksum etc. (in Wireshark /TShark it appears correctly on tun0)

Then, I have following routes:

iptables -F # flush
iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
iptables --append FORWARD --in-interface tun0 -j ACCEPT

And here I'm stuck 🙁 Packet does not get forwarded to the default gw (tshark sees it only on tun0 as received which i guess it's correct)

What's missing? Maybe some alternative approach (but it has to be done using tun device, and I have to be able to r/w to it).
Additional info:

  • forwarding is enabled (/proc/sys/net/ipv4/ip_forward)
  • 8.8.8.8 is reachable through eth0 (from local)
  • default gateway is correct (from ISP via eth0)
  • i've tried switching off rp_tables(echo 0 > /proc/sys/net/ipv4/conf/eth5/rp_filter)
  • and many others…

Thanks in advance for any hints!

Best Answer

Alternative solution would be using bridge.So you can bridge your tun0 with eth0 and there is no need for nat or setting ip on tun0 you just put IPs from the same subnet of eth0 and same gateway you are using right now on clients' tunnel interfaces.

Commands for setting a bridge up:

# brctl addbr br0
# brctl addif br0 eth0 tun0

www.tldp.org/HOWTO/BRIDGE-STP-HOWTO/set-up-the-bridge

To use brctl you have to install bridge-utils package.
If your distro is Ubuntu: aptitude install bridge-utils

Related Topic