Build a VPN using only OpenSSH
From Sfvlug
Contents |
Introduction
I have written about OpenSSH a few times in the past. It is an amazing tool that can do lots of things. Recently, some of us discovered it can completely replace dedicated VPN programs like OpenVPN. Don't get me wrong, OpenVPN is a great program, but under certain circumstances using OpenSSH can be a lot less effort.
To start with, you need root access on both ends of the VPN. If you don't have root access on one or both ends, then whoever does needs to set this up for you.
In this example, we will show a connection from a home computer to an office network. This example shows a one-to-many VPN relationship. It is possible to extend this configuration to a many-to-many VPN by repeating some of the steps from the office side on the home side.
Home Network
The home network will be 192.168.1.0/24. Although it isn't important, for the sake of completeness, the client computer will have an address of 192.168.1.100.
Office Network
The office network will be 10.0.0.0/24. In our example, we will be making a connection to a computer which has an internal address of 10.0.0.200.
VPN Network
In order to create our VPN, we need to set up tuntap networking on both sides before establishing the tunnel. We will use the 172.16.2.0/24 network for this. On the home side, we will assign 172.16.2.100 and on the office side it will be 172.16.2.200.
Preparation: Office
Before we can set up a VPN tunnel, we need to create a tunnel network interface. So either prepare this via SSH, then log out and log back in with the tunnel, or do this all in advance before you leave for home. Simply run the following commands as root.
OpenSSH will not allow a tunnel to be created on the server side unless it is configured to do so. First edit /etc/ssh/sshd_config, and allow tunneling.
PermitTunnel yes
Restart sshd and enter these commands.
echo 1 > /proc/sys/net/ipv4/ip_forward ip tuntap add tun0 mode tun user ''your username'' ifconfig tun0 172.16.2.200 pointopoint 172.16.2.100 netmask 255.255.255.0 iptables -t nat -A POSTROUTING -o eth0 -s 172.16.2.0/24 -j MASQUERADE
Connecting
Now that we have a tunnel interface waiting for us on the remote end back at the office, let's configure the local tunnel interface and connect it to the remote.
ip tuntap add tun0 mode tun user ''your username'' ifconfig tun0 172.16.2.100 pointopoint 172.16.2.200 netmask 255.255.255.0 route add -net 10.0.0.0 netmask 255.255.255.0 gw 172.16.2.100
Return to your unprivileged user account and log in.
ssh -w 0:0 office.example.com
Jeff 03:42, 21 August 2011 (UTC)