Is it possible to route a computer's SSH service through a VPN connection but allow ALL other data to exit through the WAN address? What sort of iptables magic needs to be done to accomplish this?

SSH data → goes through VPN
ALL other data → goes through default route


2 Answers 2


My answer is related to the answer of related, but more complicate question and not tested.

You need the iproute2 package installed.

Add to /etc/iproute2/rt_tables the line

200 vpn-route

and then write a script that you call after VPN is initialized:

# set default gateway of vpn-route
ip route add default via $VPNGATEWAY dev $VPNINTERFACE table vpn-route
# use this for marked packages
ip rule add fwmark 0x1 table vpn-route
# mark outgoing ssh packages
iptables -t mangle -A OUTPUT -o $WANINTERFACE -p tcp --dport 22 -j MARK --set-mark 1
# rewrite source address

Of course, you need to replace the $... variables with their actual values.

PS: If your IP on the WAN-interface is fix, you can replace the last line with iptables -A POSTROUTING -t nat -o $WANINTERFACE -p tcp --dport 22 -j SNAT --to $WANIP


If you want to connect to a server using ssh through VPN since your company requires a VPN connection to access the server, there is another way to bypass the VPN. First, you need to connect to your server using VPN. Then, start ngrok to open a reverse ssh (is this the correct term?)

ngrok tcp 22

This will give you an address and a port. It usually looks like this: 0.tcp.eu.ngrok.io:12345. Now, you can stop your VPN and ssh to your server using the above address and port.

ssh yourname@0.tcp.eu.ngrok.io -p 12345

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.