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: 192.168.66.6 (local machine) and 192.168.66.7 (on some-remote-host).
ssh root@some-remote-host ifconfig tun0 192.168.66.7 netmask 255.255.255.0 up ssh root@some-remote-host route add -net 192.168.66.0/24 dev tun0
now configure tunnel locally.
ifconfig tun0 192.168.66.6 netmask 255.255.255.0 up sleep 0.3 # needed for tun0 to become ready... dunno why - race? route add -net 192.168.66.0/24 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 192.168.66.6 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 iptables -P FORWARD ACCEPT
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.