Raspberry Pi VPN Gateway

Introduction: Raspberry Pi VPN Gateway

Update 2018-01-07:

  • Updated things missing and changes made needed for the current version of Raspian.
  • Also created a specific guide for NordVPN.

There are a few different uses for VPN. Either you want to protect your privacy and private data from prying eyes or you need to source from another country. Sourcing from another country can be very useful to get access to services not provided in your country. There are a number of VPN services out there today and most of them offer easy to use software for your computer and apps for your tablet or phone. But if you have other devices not supported by the software that you want to go over the VPN? Then build a gateway that gives you internet access over the VPN.

If you look at your basic network setup you have a "default gateway" which is used for any ip-address not located in your current subnet (very simplified). So if you setup a gateway that can route internet traffic over an established VPN connection any network enabled device can take advantage of the VPN tunnel.

My major use case in my San Francisco apartment is a VPN tunnel to my native Sweden so I can stream Swedish play channels on my media players and smart TV. This is a pretty common use case for most people in need of a VPN tunnel. Since my media players and smart TV's aren't supported by the VPN software I built one out of a Raspberry Pi.

You can pick one up for under $40 on Amazon. I do however recommend that you buy a case and decent power adapter as well. For this instructable you need:

  • Raspberry Pi 2 or 3
  • A case of your liking
  • A decent power adapter
  • A network cable

Step 1: Choosing Your VPN Service

The important thing when selecting a VPN service is that it meets your requirements. For this use case I needed a VPN service with a Swedish exit point, that is the most important thing since I need the Swedish services to be convinced that I'm in Sweden. Over the years I have used several different supliers and below are the things I take into concideration when selecting the VPN supplier for the specific use case:

Free test

I want a free test period or a small amount of test data to get a feel for the software or app. Also I want to test the performance and overall experience before I pay for it. It's also nice to check that my idea will work before I start paying.

Privacy

If the implementation is for privacy concerns then it's really important what the privacy policy states. It's also important what country the company operates from and what laws are protecting your privacy. The really privacy concerned users should look at a service that states that no traffic logs are stored and allow anonymous payments via Bitcoin for example.

Allowed traffic

There might be limitations on what type of traffic you will be allowed to run. The more serious supliers usually block peer-to-peer traffic. This is not only to avoid legal issues but to be able to maintain performance for all users. There are how ever a lot of good suppliers out there that allows peer-to-peer and still deliver a high quality service. But if that isn't your main recuirment I recommend to select a service that doesn't allow peer-to-peer.

Data cap

Never use a service who keeps a data cap over their paying users. This will just run out at the worst possible time exactly like the data on your phone just before the funny part in a video clip!

Exit countrys

Depending on the use case this has different importance. For a use case like mine, where I need to end up in a specific country, of course that needs to be on the list. I also need to be allowed to select which country I exit in. There are services where you are unable to select exit country, stay away from those. You can end up in a country with bad performance or privacy laws. Even if you don't need a specific country you should still select a service with a few different countrys to show from to be able to find one with good performance.

Type of software and support

This is one of the main reasons why I prefer services with a free test. There are so many providers with bad software that are buggy, insecure or just don't work. For a Raspberry Pi implementation I need a provider that supports OpenVPN.

My selection

For this build I went with Tunnel Bear. A free test up to 500GB is offered so I could test that I could actually stream before I payed anything. They are based in Canada which, next to Sweden, have some of the strongest privacy laws in the world. No data cap on payed service and I'm also allowed to have several devices connected at once. So protection for my phone, tablet and computer while traveling on unsecure wifi is sorted as well. Exit node in Sweden is supported, it's actually provided via Bahnhof which is known for strong privacy in Sweden. For the payed plans they offer OpenVPN support. They do not for the free test but it was enough to run that from my laptop to make sure that the streaming services worked.

Step 2: Install the Raspberry Pi

For implementations like this I use the Raspbian Lite operating system. Since I have no need for the GUI at all. You can get the latest release here.

I use Win32DiskImager to load the .img file on the SD-card for the Raspberry Pi.

Once the Raspberry Pi have booted I look in my routers DHCP list to get the IP-address and then connect over SSH with Putty. Standard username and password are pi/raspberry

Once connected I run the raspi-config tool to change the basic settings.

sudo raspi-config

The most importent things to take care of in this config is:

  • Expand file system
  • Change password

You can also change the hostname of your Raspberry Pi if you like. My DHCP have very long leases and I can also reserve a specific address. If you don't have that ability you have to configure the Raspberry Pi to use a static IP-address. Since other devices will use this as there default gateway it is important that it keeps using the same IP-address. Here is a post I wrote about setting a static IP in Raspbian Jessie.

Then we need to upgrade everything to the latest version:

sudo apt-get update
sudo apt-get upgrade sudo apt-get dist-upgrade

Step 3: Install OpenVPN

Now we need to install OpenVPN on the Raspberry Pi.

sudo apt-get install openvpn

Then we need to make sure the service starts properly.

sudo systemctl enable openvpn

When the installation is finished we need to copy the OpenVPN config files and certificates to the box. This will be provided to you by your VPN provider. In my case, using TunnelBear, I found there blog post about Linux Support. On that page there is a link to zip file containing everything we need.

The file contains the certificate files and a .opvn configuration file for each country you can tunnel to. You need all the certificate files and the .opvn configuration file for the country of your choice, in my case Sweden. Unzip the files needed and the use winscp to upload the files to your Raspberry Pi. The same username/password as used for SSH will bring you to /home/pi, just drop the files there.

Then we go back to the SSH terminal and move the files over to the OpenVPN folder. First command is just to make sure we are in the /home/pi folder.

cd /home/pi
sudo mv * /etc/openvpn/

Now we need to do some modifications to the files. First we need to rename the configuration file from .ovpn to .conf. Any file ending in .conf in the /etc/openvpn folder will automatically start when the OpenVPN daemon is started. First we need to get into that directory.

cd /etc/openvpn

Then we change the name of the config file. You can name it anything you want as long as it ends in .conf. I prefer to use file names without blank spaces, in this case I'm going with swe.conf.

sudo mv *.ovpn swe.conf

Then we need an authentication file containing the username and password used for the VPN tunnel. Open up a text editor and write the username and password on separate lines. We will call this file auth.txt.

sudo nano auth.txt

The content should be like this example:

username
password

Then use CTRL + O to write to the file and the CTRL + X to exit the nano text editor. We also need to protect the auth.txt file containing our credentials.

sudo chmod 600 /etc/openvpn/auth.txt

Then we need to edit the config file to make sure all paths are correct and add a reference to the newly created auth.txt file.

sudo nano swe.conf

The lines that needs to be changed are the ones referring to other files, they need to be absolute paths. In this example this is what we are looking for:

ca CACertificate.crt
cert UserCertificate.crt
key PrivateKey.key

We change them to absolut paths like this:

ca /etc/openvpn/CACertificate.crt
cert /etc/openvpn/UserCertificate.crt
key /etc/openvpn/PrivateKey.key

Then at the end of the file we add a reference to the auth.txt file, like this:

auth-user-pass /etc/openvpn/auth.txt

Once again we use CTRL + O to save the file and then CTRL + X to exit nano. Now we can restart the OpenVPN daemon and see that the tunnel is working.

sudo service openvpn restart 

If you run the command ifconfig you should see a tun0 adapter in addition to your eth0 and lo adapters if the tunnel is up. You can also run the command this command to check your public IP:

wget http://ipinfo.io/ip -qO -

If you are having issues getting the tunnel up first try rebooting your Raspberry Pi and then double check the configuration for errors.

Step 4: Setup Routing

Now we need to enable IP forwarding. It enables the network traffic to flow in from one of the network interfaces and out the other. Essentially creating a router.

sudo /bin/su -c "echo -e '\n#Enable IP Routing\nnet.ipv4.ip_forward = 1' > /etc/sysctl.conf"

If you run sudo sysctl -p you should see this printed on the screen:

net.ipv4.ip_forward = 1

Now routing is enabled and traffic can go through the Raspberry Pi, over the tunnel and out on the internet.

Step 5: Setup Firewall and NAT

Since we will have several clients on the inside accessing the internet over one public IP address we need to use NAT. It stands for network address translation and will keep track on which client requested what traffic when the information returns over the tunnel. We also need to setup some security around the Raspberry Pi it self and the tunnel.

sudo iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE

Enabling NAT.

sudo iptables -A FORWARD -i eth0 -o tun0 -j ACCEPT

Allowing any traffic from eth0 (internal) to go over tun0 (tunnel).

sudo iptables -A FORWARD -i tun0 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT

Allowing traffic from tun0 (tunnel) to go back over eth0 (internal). Since we specify the state RELATED,ESTABLISHED it will be limited to connection initiated from the internal network. Blocking external traffic trying to initiate a new connection.

sudo iptables -A INPUT -i lo -j ACCEPT

Allowing the Raspberry Pi's own loopback traffic.

sudo iptables -A INPUT -i eth0 -p icmp -j ACCEPT

Allowing computers on the local network to ping the Raspberry Pi.

sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT

Allowing SSH from the internal network.

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Allowing all traffic initiated by the Raspberry Pi to return. This is the same state principal as earlier.

sudo iptables -P FORWARD DROP
sudo iptables -P INPUT DROP
sudo iptables -L

If traffic doesn't match any of the the rules specified it will be dropped.

sudo apt-get install iptables-persistent
sudo systemctl enable netfilter-persistent

First line installs a peace of code that makes the iptable rules we just created persistent between reboots. The second one saves the rules after you changed them. This time it's enough to run the first one. If you change the rules run the second one to save. Iptable rules are in effect as soon as you add them if you mess up and lose access just reboot and the ones not already saved will revert.

Step 6: Conclusion

Now you can use this tunnel from any device or computer on the same network. Just change the default gateway to whatever IP-address your Raspberry Pi has. In my case both my Kodi media centers (one bedroom and one livingroom) uses this connection so I can stream my Swedish play channels. Of course there are other things you can use this for as well.

Just keep in mind that depending on the VPN supplier you chose and the speed of your internet connection there might be slow performance.

If you have any questions or want me to clarify anything let me know in the comments! For more tech post please visit my blogg Hackviking!

1 Person Made This Project!

Recommendations

  • Game Design: Student Design Challenge

    Game Design: Student Design Challenge
  • Big and Small Contest

    Big and Small Contest
  • Make It Bridge

    Make It Bridge

53 Comments

0
thjperry
thjperry

Question 1 year ago

Could you use something like this in conjunction with an ASUS router? I’m wanting to only apply my VPN to my game consoles without affecting other devices using Hulu or Netflix, could this accomplish that?

0
techmario4789
techmario4789

Question 2 years ago

Thanks for the detailed instructions. I followed the instructions and was able to get openvpn setup and working on the Pi. However, I also have Pihole running on the Pi. For some reason, I cannot access the PiHole Admin web page after installing OpenPVN. I checked pihole status and it appears to be up and running. Also checked processes on pi and lighttpd which is the web server used by Pihole is also running. I'm not sure if I need to do anything with the firewall rules to get connectivity restored to the pihole admin web page. Here's what my IPTables looks like

Chain INPUT (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere
ACCEPT icmp -- anywhere anywhere
ACCEPT tcp -- anywhere anywhere tcp dpt:ssh
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

Chain FORWARD (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

1
simon0362
simon0362

2 years ago

Geeeeeeeeeeeeee, thank you so much.
I have an instance of OpenVPN running on a VPS (virtual private server for clarity) in my target country but some devices are unable to have an OpenVPN client installed. I went down the route of setting up a RPi very successfully but was then left with the instruction to "change the device gateway to the RPi IP address and it should all work" - which it didn't.

YOU are the first person to explain a) what to do and b) why you are doing it.....
Followed the instructions to the letter and my devices have sprung into life.

As an aside and hopefully to help others, renting a VPS and installing OpenVPN server on it (remotely) has the advantage that you gain a completely anonomous IP address that is visibly no different from a residential one - so not subject to being categorised as coming from a web VPN supplier.

Many thanks again.
Simon

0
greysolive13
greysolive13

2 years ago

useful tutorials! thanks a lot

0
kküpeli
kküpeli

2 years ago

Saved me a good amount of time. I am using OpenVPN to access office VPN which does not allow simultenaous connections for my user, now it is solved :)

1
big1tasty
big1tasty

Question 2 years ago

Hi, i did the steps like showen and connecting fine to my vpn. Also the gateway works just fine. However if try to watch netflix or primevideo i get the proxy/vpn message.
If i join on the same Server on my PC it works just fine. does anyone has an idea?
(DNS LeakSites say i'm fine, even with IPV6 disablet)

0
andr3w2
andr3w2

Question 2 years ago

Hi, I took this tutorial again and I must say that it is the only one that worke for me! I use Openppn on Debian 10 . But there is a problem, when RPI disconnect from the Internet, then restarting and restoring the connection immediately, following your steps (4-6) I cannot always direct local traffic again to the raspberry tunnel . It's difficult to explain, sometimes it works, sometimes it doesn't. I want to understand if I am taking one step more or one less.
This is my ip table:

target prot opt source destination
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
ACCEPT all -- anywhere anywhere
ACCEPT tcp -- anywhere anywhere tcp dpt:ssh
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
Chain FORWARD (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
ACCEPT all -- anywhere anywhere
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
Chain OUTPUT (policy ACCEPT)
target prot opt source destination

0
b1narys.pov
b1narys.pov

Question 3 years ago

How do I revert the iptables? it screwed everything for me

0
ted_mosby
ted_mosby

4 years ago

Awesome tutorial!! Works great for my Apple TV. Geoblocking within EU should be a crime!

0
hulst
hulst

4 years ago

Really great tutorial,
I am wondering if I can build it as a "load balancer"?
Meaning I can enter several vpn servers, which will be used random.
Or when one is unavailable, another will be used?

0
zzzuam
zzzuam

6 years ago

What a great tutorial. Exactly what I needed/wanted. Works great with my Apple TV. Small thing missing in the tutorial; SSH is off by default so you have to know how to enable it on a headless install.

0
iancarbarns
iancarbarns

Reply 4 years ago

This probably didn't work when you wrote it, but current Raspbian releases allow you to do a completely headless setup (ie never having a keyboard, mouse or monitor connected). It's great for Pi Zero W with it's few physical connections!

All you need do is:

1. on your computer, open up the visible(non-linux) partition on SD card

2. add an empty file called SSH (no extension, no content, just the filename)

3. add a file called wpa_supplicant.conf
with the following content added with Notepad++ (not a word processor - the file is very sensitive to format and CR vs CRLF). My example here will automatically connect the Pi to the first one of two networks (ie my 5GHz preferred to my 2.4GHz) - you can omit one of the blocks [and the priority=x lines] if you only have 1 network.

In the below, the formatting has unfortunately been destroyed by this forum. Each of the lines starting ssid, psk, key, id and priority need to be indented by 4 spaces. Change the Network name and passphrase to match your network (Duh!!)

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB

network={
ssid="Network1name"
psk="Network1passphrase"
key_mgmt=WPA-PSK
id_str="5Ghz"
priority=9
}

network={
ssid="Network2name"
psk="Network2passphrase"
key_mgmt=WPA-PSK
id_str="2.4GHz"
priority=8
}

Then when you reboot the Pi, it will connect to your network with SSH enabled so you can immediately log in over SSH. (you'll need to find its IP address eg from your router)

Note that these 2 files are deleted when the Pi processes them, so you should keep copies for re-use (they can be in the same place on the SD card with different filenames)

0
AdamC289
AdamC289

5 years ago

Hey, thanks for a great tutorial - got the pi up and running as instructed.

However, my devices connect to the LAN via my router and if i redirect the gateway to the pi i don't receive an IP.

So how would you configure a wireless laptop to go via the pi/vpn/router?

Thanks again.

0
Hackviking
Hackviking

Reply 5 years ago

Just give it a fixed IP address in the same subnet and it should work just fine. A more "sexy" approach would be to add a DHCP server to the Pi but that would require some more work.

0
iancarbarns
iancarbarns

Reply 4 years ago

That's not right (and you're the author!).

For the device you want to give VPN'd access to (whether wireless or wired), you need to go into it's connection settings. Usually this will be set to automatic (so it gets it's settings from the router). Change this to 'Manual' (or change existing manual settings) so that the IP address for "Gateway" (called "Router" on some devices eg iPhone) is the IP address of Raspberry Pi, instead of that of your router.

On a home network, this would often be a change from 192.168.1.1 to 192.168.1.xxx where xxx is the Pi's IP address.

You may be forced to change the DNS server address as well. Try entering the Pi's IP address there as well; if that doesn't work, use 1.1.1.1 and 1.0.0.1 (the Cloudflare DNS servers; or you can use Google's 8.8.8.8 and 8.8.4.4 or any others you know and like ...)

0
RobinPi
RobinPi

5 years ago

Thanks for the tutorial.

I'd love to to take it one step further and enable the Pi to also act as a wireless access point.

e.g This tutorial covers Part 1:

Router >> Pi connected by Ethernet. Pi generates a VPN tunnel for wired devices.

Part 2 would be:

Turn Raspberry Pi's as a wireless access point with it's own SSID so that mobile, tablet, Chromecast, etc can also connect to the VPN over WiFi.

But not sure how to do this last bit.

0
Hackviking
Hackviking

Reply 5 years ago

It's pretty straight forward if you search for tutorials setting up the pi as an access point (AP) and then more or less follow the steps again but against wlan0 instead of eth0.

0
RobinPi
RobinPi

Reply 5 years ago

Thanks, I'll have a look :)

0
iancarbarns
iancarbarns

Reply 4 years ago

Did you ever get this working?

I've had a Pi running as per this tutorial and another running as a VPN Access Point. Then occurred to me that one Pi should be able to do both, and am nearly successful. The tip was that need to open a second VPN channel (eg, have 2x *.conf files). Then one loads as tun0 (used in iptables for eth0) and the second loads as tun1 (used in iptables for wlan0 set up as an access point as per other tutorials).

Aside: For use as an access point, a finding not covered in other tutorials was a need to add @reboot (sleep 20;sudo service dnsmasq restart) & in crontab else the access point did not assign IP addresses.

Presently, I have VPN sevice on LAN over the Pi's eth0, and can see WiFi with my new ssid, and can connect to it, but it's not providing internet access. I'm still trying fiddling with the many possible settings; hope to be successful soon and will share instructions if so.

0
bigbadbobbyd
bigbadbobbyd

Question 5 years ago on Step 1

how can i forward ipv6 with ipv4? is that possible?