Iptables – Route all wlan0 traffic over tun0

iptablesrouteroutingvpn

I'm looking for a way to route all wlan0 traffic (tcp and udp) over tun0 (openvpn).

However, all other traffic originating from the device itself should not be routed through tun0.

I'm guessing this could be realized using iptables or route, but none of my options seem to work.

# route add -net 0.0.0.0 gw 172.27.0.1 dev wlan0
SIOCADDRT: No such process

Info:
This is because the VPN server is not redundant, and wlan users are not really important. However, all services running on the device are fairly important and having a VPN virtual machine with no SLA on it is just a bad idea. Trying to minimize the odds of something going wrong.
So setting the VPN server as default gateway is not really an option.
I also want all wlan0 user to use the VPN server's IP address as external IP.

Edit with the script provided:

root@ft-genesi-xxx ~ # route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
172.27.0.17     0.0.0.0         255.255.255.255 UH    0      0        0 tun0
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 eth0
10.13.37.0      0.0.0.0         255.255.255.0   U     0      0        0 wlan0
172.27.0.0      172.27.0.17     255.255.192.0   UG    0      0        0 tun0
0.0.0.0         192.168.1.1     0.0.0.0         UG    0      0        0 eth0
root@ft-genesi-xxx ~ # ./test.sh 
RTNETLINK answers: No such process
root@ft-genesi-xxx ~ # cat test.sh 
#!/bin/sh
IP=/sbin/ip
# replace with the range of your wlan network, or use fwmark instead
${IP} rule add from 10.13.37.0/24 table from-wlan
${IP} route add default dev tun0 via 127.72.0.1 table from-wlan
${IP} route add 10.13.37.0/24 dev wlan0 table from-wlan

Best Answer

I believe this should get you going:

/usr/sbin/ip route add default via 172.27.0.17 dev tun0 table 200
/usr/sbin/ip rule add from 10.13.37.0/24 table 200
/usr/sbin/ip route flush cache

This is exactly what I did within my setup here. The only difference is I wanted to route a single host (/32) instead of a whole network (/24).