2014-09-02 - connection tunneling with SSH

OpenSSH logo everyone knows that OpenSSH can do port forwarding. not everyone knows, that it can (nearly) as easily do connection tunneling, using tun. the spell is ssh -w 0:0 hostname. now you have tun0 interfaces on both ends of communication channel (note: “0:0” means tun0 on both ends). the simple script to setup whole communication and do masquerade to enable tunneled network connection for a remote end can be easily created, using following steps.

first TUN interfaces need to be created on both sides – this is done by ssh. assume some-remote-host is a host tunnel needs to be established with. before you start add a following line to the /etc/ssh/sshd_config:

PermitTunnel yes

this enables tunnels creation. this option is disabled by default, and most likely it is not present even in a commented-out for in the config. add it manually, if needed and restart ssh daemon. having this done establish tunel interfaces on both sides:

ssh -f -w 0:0 some-remote-host true

next configure tunnel on the remote end. network will consist of two hosts: (local machine) and (on some-remote-host).

ssh root@some-remote-host ifconfig tun0 netmask up
ssh root@some-remote-host route add -net dev tun0

now configure tunnel locally.

ifconfig tun0 netmask up
sleep 0.3 # needed for tun0 to become ready... dunno why - race?
route add -net dev tun0

at this stage both machines are able to ping each other (assuming firewalls are not blocking the traffic).

to enable network, tunneled via newly setup tun0 interfaces, local machine needs to be added as a default gateway on the remote end:

ssh root@some-remote-host route add default gw dev tun0

…and masquerade needs to be enabled, along with forwarding:

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

technically that's all folks! :) if you do this often, this can be scripted easily. if you have via-key authorization configured, this will be fully automated.

blog/2014/09/02/connection_tunneling_with_ssh.txt · Last modified: 2014/09/02 18:32 by basz
Back to top
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0