How to use an Amazon EC2 instance as a VPN server


One day I was doing some testing and I wanted to be sure it wasn’t my DNS/Routes that were causing the response time issues. A co-worker suggested using an EC2 instance as a VPN server. I thought that would be perfect!

I’m going to assume that you have the knowledge of starting up an Ubuntu EC2 instance.

First up is installing OpenVPN and enabling ip forwarding:

sudo apt-get install -y openvpn
sudo modprobe iptable_nat
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
sudo iptables -t nat -A POSTROUTING -s 10.4.0.1/2 -o eth0 -j MASQUERADE

Next up is generating a shared key for authentication/encryption.

cd /etc/openvpn
sudo openvpn --genkey --secret ovpn.key

Here’s a basic conf file (/etc/openvpn/openvpn.conf). Read the OpenVPN man page for more options.

port 1194
proto tcp-server
dev tun1
ifconfig 10.4.0.1 10.4.0.2
status server-tcp.log
verb 3
secret  ovpn.key

Now to start it and follow the status:

sudo service openvpn start
tail -f /etc/openvpn/server-tcp.log

Make sure tcp port 1194 is open in your instance’s security group!

scp/email/ftp/rsync/nc the ovpn.key file to your client machine.
Start OpenVPN client on your client machine:

export EC2_IP=0.0.0.0
sudo openvpn                    \
  --proto tcp-client            \
  --remote $EC2_IP          \
  --port 1194                     \
  --dev tun1                    \
  --secret ovpn.key             \
  --redirect-gateway def1       \
  --ifconfig 10.4.0.2 10.4.0.1  \
  --daemon

Now if you visit www.whatismyip.org it should be your EC2 Instance’s IP.

, ,