Download as pdf or txt
Download as pdf or txt
You are on page 1of 85

Build a Smart Raspberry Pi VPN

Server
+ Tor Router
by Ira Finch
3rd Edition
Rev 3.0
July 14, 2019
Text copyright © 2015-2019 Ira Finch
All Right Reserved
irafinch888@bitman.org

No part of this book may be reproduced in any


form or by any means (with exception to the use
of the code herein in the application of this book)
without the prior written consent of the Author.
The information in this book is distributed on as
“As Is” basis, without warranty of any kind. While
every reasonable effort has been taken in the
preparation of this book, the author shall not
have any liability to any person or entity with
respect to any loss or damage caused, or alleged
to be caused, directly or indirectly, by any
information expressed or implied in this book or
by the computer software and hardware products
described in it.
Table of Contents
PREFACE – Please Read
CHAPTER 1 - Buy Your Hardware
CHAPTER 2 - Load up the Raspberry Pi
CHAPTER 3 - Upgrade the Software
CHAPTER 4 - Install a UPnP Client
CHAPTER 5 - Install and Configure OpenVPN
CHAPTER 6 - Create the Intelligent Python App
CHAPTER 7 - Create and Download Client Certificate Files
CHAPTER 8 - Install and Configure OpenVPN for Android
CHAPTER 9 - Install and Configure Windows OpenVPN GUI
CHAPTER 10 - Ship It!
APPENDIX A - Maintenance
APPENDIX B - Troubleshooting
APPENDIX C – Frequently Asked Questions
APPENDIX D – Harden your SSH Login
APPENDIX E – OpenVPN over SSL
APPENDIX F – Tor (anonymity network)
PREFACE – Please Read
This book covers the Raspberry Pi Zero, B+, 2B,
3A & B, and 4B, and Windows 7+ and Android 4.0+
clients.
NOTE: Every reasonable effort is taken to ensure this book is kept up-to-date
with the ever changing software releases of the programs used. BEFORE
proceeding, please ensure you have the latest book revision from Amazon
and contact Amazon Customer Support to request the latest revision. In
addition, revision and interim changes are made available on the supporting
web site:
http://bitman.org/irafinch/rpivpn
If you feel there is an error or omission, I do apologize. Please allow me the
opportunity to correct such issues before posting a negative review on
Amazon. I read every email, every review, every posting and respond as
quickly as possible. But I am only human, and don't always catch every
change before a reader does.

What's New
The 3rd Edition includes:

Tor – Add a Tor router to your Raspberry Pi, in addition to


VPN, to further protect and secure your online activity,
anonymity and identity.
Simplification – WinSCP, SMTP mail utilities, and
PortMapper (in most cases) have been removed for easier
setup, use and maintenance.
New Python App – The original Bash script for tying
everything together has been rewritten in Python for greater
reliability, easier enhancing and maintenance.

The 2nd Edition adds:

Hardening your SSH Login – how to enable 2-step


authentication to your RPi to make virtually impossible for
hackers to get in.
OpenVPN over SSL – If OpenVPN is blocked or monitored,
running OpenVPN over SSL may help.
Support for All Current Raspberry Pi Models – I've
personally configured and tested the instructions in this
book and the scripts on the Zero, B+, 2B and 3B models.
Speed Testing – Which Pi is right for you? How does
OpenVPN and OpenVPN over SSL impact performance?
There's a chart near the end of this chapter to help and
more information on my web site.

And, as always, I will to continue improving this book, the scripts and
my supporting web site to make this the best how-to guide on
OpenVPN on the Raspberry Pi. Your support, suggestions and
feedback are always welcome.

Why VPN?
VPN stand for Virtual Private Network. It is a data encryption and
forwarding mechanism which allows secure communication over the
Internet without the risk of eavesdropping or content blocking
(censorship).
Corporations use VPN for clients and off-site employees to connect to
their internal network. Individuals use it to access blocked sites or
share information securely.
Take for instance an Open WiFi hot-spot at your local coffee shop. All
the data going across their WiFi network is open and unsecured.
Anyone with the right (free) tools can intercept that data and record
everything you send/receive. Unless you only visit HTTPS sites, you’re
vulnerable to hackers. In addition, being on a public open WiFi
network means that others on that network can ‘see’ your computer
and try to directly hack into it.
If you connect to a VPN Server as soon as you connect to a WiFi hot-
spot, you’re secure. Other uses can still ‘see’ your computer, but they
can’t read what you’re doing, nor can then hack into your computer.
And I’m not just talking PCs here: Smart-phones, tablets, gaming
devices. All are vulnerable on an open WiFi network without VPN.
Why Tor?
Tor is a software tool that enables anonymous internet usage. As
Internet Privacy is being eroded away more and more by governments
and enterprises; tracking, surveillance, targeting and identity theft
become prevalent. Data can, and is, being collected and sold on what
pages we visit, videos we watch, information we read, products we
buy and people we communicate with. Our on-line freedoms, privacy
and identity are disappearing and we have little say in the matter. Tor
can help.
For more information on Tor, please read this Wikipedia page:
https://en.wikipedia.org/wiki/Tor_(anonymity_network)

Why Raspberry Pi?


Raspberry Pi was built to be tinkered with. It’s a very popular, cheap
and powerful computer. Powerful enough to handle multiple
simultaneous VPN client connections. There is a huge community of
RPi (Raspberry Pi) enthusiasts out there and many different Operating
Systems have been developed or ported to it because its so versatile.
Did I say it was cheap? For less than $60, you’ll have all you need for
this project. Think how quickly that will pay for itself in comparison to
paying monthly VPN service fees.

Why build?
You will have total control over your very own VPN Server. You won’t
be sharing bandwidth with others (unless you give them access). You
won’t be paying monthly fees to some corporation. And you won’t
have to worry about your activity being logged and sold (or given
away) to some other corporation or government agency.
It’s fun and educational. You’ll learn a little about the RPi, Linux, VPN,
SSL, Tor, Bash, Python, etc. And once you’re done, you might find
yourself wanting more. There are dozens of projects for the RPi, from
motion detectors to Internet radios that you might find just as
interesting.
Why this book?
There are many sites on the Web that describe pieces and parts to
building a VPN Server, but none that I have found contain complete
step-by-step instructions for doing so. Moreover, none contain
directions on how to build a smart, stand-alone, plug-n-play anywhere
VPN Server (including Tor) using a Raspberry Pi.
What this book covers, from start to finish, is how to build and
configure a Raspberry Pi VPN server that will:
1. Determine its IP Address, the Router’s IP Address, and its
External IP Address.
2. Open ports on whatever router its connected to to allow VPN
and SSH External Access for maintenance.
3. Detect Changes in any of the IP addresses and reconfigure
as required so static IPs are not needed.
4. eMail you with the External IP address, whenever it changes,
so you know where to VPN connect to it.
5. Keep logs of changes and errors.
6. Perform basic housecleaning (i.e. ‘reboot’, clear cache)
periodically for memory leaks, etc.

I’ve built several of these so far so that I can conduct business without
the fear of prying eyes.
I’m very pleased with the stability and power of the Raspberry Pi and
the code I have written to bring all the piece parts together to make it
as maintenance free as possible and as smart as I require.
I think you’ll find it to be the same. But, perhaps you’ll find some area I
missed or think of an enhancement to make it even better. And that
would be wonderful!

A Note About the Code


There are a few code scripts in this book, and while it is possible to
retype them, it's much easier and less error prone to copy/paste them.
So, its recommended that you download the code from my supporting
web site at:
http://bitman.org/irafinch/rpivpn
Or directly from this link:
http://bitman.org/irafinch/rpi-vpn.zip
Then you can copy them from Windows Notepad directly into your
Raspberry Pi and not have to retype everything.

Running the Raspberry Pi VPN Wirelessly


The initial release of this book did not contain instructions for running
wirelessly, only over Ethernet. The main reason for this is that it's not
Plug-n-play. You must manually set the SSID (WiFi Router Name),
security type, and password before you get an IP address...but you
can't remotely set those values until you get an IP address. It's a catch
22.
Here are a few more things to consider when running wirelessly:

Only run your Raspberry Pi VPN wirelessly if you will always


have direct physical access to it. If the SSID, security type,
or password change on your WiFi router, it will lose its IP
address and so you will need to plug a keyboard, mouse and
HDMI monitor into your RPi to change those setting.
Make sure to buy a Raspberry Pi 3 or a compatible USB
WiFi Adapter. Most of these will just require plugging in the
adapter and configuring the connection. Some may require
special software and driver setup and is beyond the scope of
this book. So if in doubt, follow the instructions provided with
your WiFi adapter.

WiFi is unidirectional, or half-duplex. It cannot send and


receive data at the same time. Since a VPN server is
retrieving internet content, encrypting it and then transmitting
it back out the internet to you, a wireless connection
basically halves the throughput speed.
The Raspberry Pi is a low power device and WiFi takes a lot
of power. You should therefore either buy a USB WiFi
adapter that is designed and certified to work when directly
plugged into your RPi, or use a powered USB hub to power
your WiFi adapter.
Low power WiFi adapters designed for the RPi often have a
'sleep mode' when not actively sending/receiving. As a
result, you may experience connection failures on initial
connections and need to retry before successfully
connecting.
Low power WiFi adapters have a shorter range. Because
they are low power, their signal strength is reduced. You will
not be able to place your RPi as far away from your router
as say your laptop, tablet or cell phone

Which Pi to Buy?
Personally, I'd buy the fastest Pi available: currently the model 3B.
Basically, because its still very inexpensive and has more than enough
horsepower to get the job done.
If you're curious how the different models compare against a direct
connection when using OpenVPN and OpenVPN over SSL, the
following chart should help:
This was generated using the data from the SpeedTest.net web site
over a 50Mb/s rated internet service. As you an see, OpenVPN has a
noticeable impact on performance and OpenVPN over SSL slows it
down even more. However, all these Pi models have fairly respectable
speeds (except maybe the Pi Zero).
Please Note: The actual limiting factor of your connection speed will
be your rated Upload Speed. This is because the Raspberry Pi needs
to 'upload' the data, or web site, you requested back to you from its
home internet connection. If this connection has a rating of 50Mb/s
Down and 5Mb/s Up, then 5Mb/s is going to be your best speed.
Again, because it must use that 'Up' link to send the data back to you.
So even a Pi B+ is more than fast enough for most installations – even
for streaming video.
For more (boring) technical details on this data and how it was
generated, visit my supporting web site:
http://bitman.org/irafinch/rpivpn
Note: I did not conduct speed tests while connected through the
Tor Router. And I probably never will. The Tor network is too
unpredictable: traffic is bounced through a random number of
servers for any given connection making performance testing
meaningless. The end result is that you will find that internet
speeds will range from horrible to tolerable at any given moment
through Tor.

What you’ll need


This is a complete list of everything you'll need for this project. Each
item is covered in detail in the following chapters, so don't concern
yourself with getting all the pieces together right now.

● Raspberry Pi Zero, B+, 2B or 3B


☐ For Pi Zero: Mini USB to Ethernet Adapter
● 8GB micro SD card or larger
● 5V 2A mini USB power supply (if it doesn’t come with one
already)
● WiFi Adapter (optional on Zero, B+ & 2B). Either low power or
with Powered USB Hub
☐ For Pi Zero: Mini OTG Adapter for the Wifi to plug into
● Heat sinks (optional, and some kits come with these)
● Raspberry Case (optional, but recommended)
● HDMI Cable and Monitor (just for the initial setup)
● USB Keyboard (again, just for the initial setup)
● USB Mouse (for initial setup only if you will be using a WiFi
Adapter)
● Cat5 (Ethernet) network cable (for a truly plug-n-play anywhere
VPN Server)
● Micro SD Card Reader (if your PC doesn’t have one built-in)
● Raspbian OS
http://www.raspberrypi.org/downloads/
● Free Download Manager (required if you live in a crappy
Internet location)
http://www.freedownloadmanager.org/download.htm
● Win32DiskImager
http://sourceforge.net/projects/win32diskimager/
● OpenVPN
Installed via the Raspbian OS
● stunnel (SSL) – optional
Installed via the Raspbian OS
● Tor – optional
Installed via the Raspbian OS
● PortMapper – optional
http://sourceforge.net/projects/upnp-
portmapper/files/PortMapper-1.9.5.jar/download
● MiniUPnPc
Installed via the Raspbian OS
● Putty
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
● SMTP email addresses to send alerts from and to
● Windows OpenVPN GUI
https://openvpn.net/index.php/open-source/downloads.html
● OpenVPN for Android by Arne Schwabe
https://play.google.com/store/apps/details?
id=de.blinkt.openvpn&hl=en
Note: Programs change, web sites change and sometime go
dark. The Web Addresses provided in this book existed at the
time of this writing. If you find they are no longer valid, please
Google for alternative sites and let me know. My email address is
provided on the Copyright page.
Note: A supporting web site is located at:
http://bitman.org/irafinch/rpivpn
There you will find additional FAQs, Errata, Maintenance and
Troubleshooting pages as well as a User Forum. Please visit that
site if you run into any issues.

What you’ll get


In the end, you’ll have your own server, completely under your control,
with little fear of some hacker, corporation or government entity
gathering your data for whatever purpose they wish.
With VPN: You will have a secure, encrypted connection to the
internet from any WiFi access point, or even over a Cellular Data
connection.
With SSL (optional): You will be able to hide the fact you are using
VPN, and further secure your connection, where applicable.
With Tor (optional): You will be able to anonymously communicate
over the Internet (web, email, video, chat, etc) with little risk of being
surveilled or tracked.
CHAPTER 1 - Buy Your Hardware
NOTE: Every reasonable effort is taken to ensure this book is
kept up-to-date with the ever changing software releases of the
programs used. BEFORE proceeding, please ensure you have
the latest revision from Amazon and contact Amazon Customer
Support to request the latest revision. In addition, revision and
interim changes are made available on the supporting web site:
http://bitman.org/irafinch/rpivpn
If you feel there is an error or omission, I do apologize. Please
allow me the opportunity to correct such issues before posting
a negative review on Amazon. I read every email, every review,
every posting and respond as quickly as possible. But I am only
human, and don't always catch every change before a reader
does.
The only cost to the project is the hardware (and my book). All the
software needed for this project is freeware / open source. And that
is the best kind, IMHO. But if you find something you like and it
works well for you, a donation to the author(s) is always in order.
So here’s the list of what you’ll need:

1. Raspberry Pi Zero, B+, 2B or 3B


For Pi Zero: Mini USB to Ethernet Adapter
2. Micro USB Power Supply (5V 2A)
3. Micro SD memory card (8GB recommended at least)
4. WiFi Adapter (optional for Zero, B+ & 2B). Either low power
or with a Powered USB Hub
For Pi Zero: Mini OTG Adapter for the Wifi to plug into
5. Heat sinks (some kits come with it, and this is optional)
6. SD Card Reader (only if you PC doesn’t already have an
SD Card slot)
7. Raspberry Pi Zero, B+ or 2B/3B Case (optional, but
recommended)
8. Cat5 (Ethernet) network cable
You can get all these items on Amazon, BestBuy, Microcenter,
Taobao, AliExpress, etc. Some places have ‘starter’ kits which have
everything we need, plus a little more. Don’t buy the kits with the
software installed, we’ll be installing it ourselves – and its free. So
why pay extra?
Note: You only need a WiFi adapter if you wish to run your
Raspberry Pi wirelessly. Please read the Preface under
Running the Raspberry Pi VPN Wirelessly for important
information regarding this.
Once you get all the hardware, put the RPi (Raspberry Pi) in its case
and plug it in. Now wonder in its shininess as nothing happens!

We need to install the software now, its just a dumb box at this point.
So just unplug it for now.
Yup, this was a very short chapter. They get longer…
CHAPTER 2 - Load up the Raspberry Pi
Now, if you live in a place where the Internet sucks and downloading
large files takes forever (or never), you’re gonna need Free
Download Manager. It’s a life-saver. It supports up to 10
simultaneous downloads, cutting up that large file into 10 slices and
downloading each one concurrently. It auto-recovers and auto-
resumes and can turn a day long download into just a few minutes.
It’s saved my soul on many occasion:
Free Download Manager:
http://www.freedownloadmanager.org/download.htm
Note: All the software needed for this project is freeware / open
source. And that is the best kind, IMHO. But if you find
something you like and it works well for you, a donation to the
author(s) is always in order.
Next, download the Raspbian OS from here:
http://www.raspberrypi.org/downloads/
Click on the RASPBIAN Icon and then on the Download ZIP button
on under the RASPBIAN JESSIE heading (or whichever is newest)
Note: I recommend downloading the LITE (not FULL) version
of Raspbian software as the Full version contains a lot of extra
stuff we don't need. Plus, the full version will boot into the
Desktop mode and we'll be doing everything from the
command prompt instead.
If you using Internet Explorer (IE), clicking on the Download ZIP link
should start Free Download Manager to download the file (if you
installed its Browser Extension). Otherwise, just right-click on the
Download ZIP link, select ‘Copy Link Address’ and paste the link into
the ‘Add Download’ window (click on the (+) button) of Free
Download Manager.
Now you need to download Win32DiskImager to make an image of
the Raspbian OS on your SD card from here:
http://sourceforge.net/projects/win32diskimager/
Click on the Files heading for the latest version. Its not a large file
(about 13MB) so it should not take long. Run it to install it.
Once it has finished downloading and is installed:
1. Insert your SD card into the SD card reader and note which
drive letter it assigned.
If its not formatted for Fat32, you’ll need to do that now.
2. Extract the Rasbian OS from the Raspbian OS ZIP file.
3. Run Win32DiskImager as Administrator by right-clicking
on the program and selecting Run as Administrator.
4. Select that Raspbian OS image file (.img).
5. Select the Drive Letter of the Micro SD Card.
Make sure you select the CORRECT drive letter or you
could wipe out your Windows PC!!
6. Click Write and wait for it to complete.
7. Exit Win32DiskImage
8. Open the SD Card in Explorer and create a file at its root
called ssh (all lowercase and no extension). This enables
SSH (Secure Shell) logins.
9. Eject the SD card.

You’re not done yet!


If you look at the SD card in Windows, you’ll see that its total
capacity is now MUCH less (about 56MB). Don’t fret. Raspbian OS
is a Unix variant and so the file and partition structure is unknown to
Windows.
Now we need to boot up the OS on your RPi, allocate the partition so
the OS can use all the SD card space, and then update the software
packages to the latest version.
Insert the Micro SD card into your RPi, then connect it to your
monitor with the HDMI Cable, then the USB Keyboard, and then the
power cord to boot it up. You’ll see a ton of text messages scroll by
as it boots. Then it will prompt for your login. Enter pi and then
raspberry for the password.
Note: If you download the Full version of the Raspbian
software, it will boot you up into the GUI (desktop) interface.
We don't need that at this time, so just exit via Menu →
Shutdown → Logout to get back to the command prompt.
Now, at the prompt type:
sudo raspi-config
Press enter and it will display a screen similar to this:
Highlight Advanced Options and press enter, then Expand
Filesystem and press enter. Once its finished it will tell you to
complete the operation by rebooting – but we are not ready to do
that quite yet. Select OK to return to the menu.
Now we need to change the default password (raspberry). This is
VERY important! Your Raspberry Pi (RPi) will be exposed on the
Internet and without a good strong password, every script-kiddy on
earth will hack into it and cause you lots of grief. So make it at least
10 characters and a mix of UPPERCASE, lowercase and numbers.
Throw in some symbols for good measure as well.

1. Select Change User Password.


2. An info screen appears about changing the password.
Click OK and you’re dropped to a command prompt to
enter in a new password. You’ll see no characters on the
screen as you type, but you will be asked to enter it again
to verify. Then it will say it is changed.
3. Remember your password! Write it down and lock it in a
safe.
4. Click OK and you’ll return to the setup screen.

Now we need to set international options so everything work properly


for the country/language you’re using.

1. Select Localisation Options.


2. Use the three new options to set up the Locale, Timezone
for wherever you’re going to house this puppy.
3. Select the first option to Change Locale.
4. You’ll get a list of Locales. The first two characters are the
language, the next two are the country codes and the last
set is ISO or UTF-8 character sets (you can select more
than one). UTF-8 is recommended for compatibility. So for
me it would be:
en_US.UTF-8 UTF-8 (English, United States, UTF-8
character set)
5. Then click OK and select it as the default.

Now we need to set the timezone for where you’re going to be


running your RPi.

1. From the main menu, select Localisation Options.


2. Now select Change Timezone.
3. Select the timezone you’ll be running your RPi in. For me,
that is US, then my specific timezone.

Note for Wireless: If you have a Pi 3 or are running Wireless,


you should probably also set Localisation Options / Change Wi-
fi Country. Then select the country in which you are running
your Pi. You don't want to run afoul of local regulations.
You may also wish to give your RPi a name, especially if you have
more than one, for easy identification. To do so, select Network
Options / Hostname and enter your name for this RPi, following the
naming guidelines on the screen. Then select OK to return to the
main menu.
Lastly, we need to set the RPi to wait for the Network as boot time.
This is new with the latest version of Raspbian and is required so
that OpenVPN starts up properly.
Select option Boot Options. Then select Wait for Network at Boot
and answer Yes and then select OK. If we don't do this, OpenVPN
won't start properly when the RPi reboots and we won't be able to
VPN into it.
We are now ready to Reboot for all these changes to take effect.
From the main menu select Finish and answer Yes.
You have now successfully installed Raspbian OS on your RPi. It’s
no longer brainless, but still doesn’t have anything to do yet.
CHAPTER 3 - Upgrade the Software
SSH (Secure Shell) is already installed with the Raspbian OS, so all
we need now is to download and install Putty on your Windows PC,
found here (puTTY For Windows on Intel x86):
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
Login to your RPi using the ‘pi’ username and the password you set
in the previous chapter.
Now we need to find the RPi’s IP address on your network. Plug an
Ethernet cable into you RPi and into your network router and type:
hostname -I
The IP address will be shown on the next line. Run Putty in Windows
and enter that IP address and port 22. You’ll probably want to save
this config as we’ll be using it a lot.
Note: We are not using a static IP address as we don’t know
the internal IP address structure of our permanent home. By
using Dynamic IP addressing, and a little smarts on the RPi
side, we can make it adapt and adjust to just about any
environment we plug it into. So at the moment, try not to power
down or disconnect the Ethernet cable, as your RPi may get a
new IP address.
Click Open to connect. And log in with your pi username and new
password. You’ll get a pop-up window saying “The server’s host key
is not cached in the registry…blah blah blah“. Just click Yes.
You can now logout of your keyboard/monitor session and
disconnect them. We will be running ‘headless’ through SSH from
now on.
Even though we just installed the latest Raspbian OS build, we still
need to make sure all its parts are up to date.
From the # prompt, enter:
sudo apt-get update
then, after that’s done, enter:
sudo apt-get upgrade
You’ll get prompted to install updates, if there are any. Just answer
‘Y’.This may take a while, so be patient.
WiFi Setup (optional)
Note: Please read the Preface under Running the Raspberry Pi
VPN Wirelessly for important information regarding this.
Having read all that, if you still wish to run your RPi over WiFi, here
are the basic steps to set it up. First, let’s get into root user mode.
Enter:
sudo -s
Then enter the following to set up wifi:
nano
/etc/wpa_supplicant/wpa_supplicant.conf
Then enter these lines to the bottom of the file:
network={
ssid="Your_SSID"
psk="Your_wifi_password"
}
Where Your_SSID is the WiFi ID of your Wireless Router, and
Your_wifi_password is the password required to connect to it. Keep
the double-quotes.
Press Ctrl+X together to exit. Answer ‘Y’ to save and then press
Enter to write it out.
Next we need to find the name of the Wifi Adapter. Enter the
following command:
ifconfig
And look for a line that starts with wl in the first column. It will be 5 –
15 characters long, up to (but not including) the colon (:). Write this
name down.
Now, we need to shut down and restart the wireless interface to
enable our changes. Enter:
ifdown adaptername
ifup adaptername
Where adaptername is the name you wrote down from the ifconfig
command above.
Wait a minute or so and then enter:
ifconfig adaptername
You should now see it assigned an ip address on the inet addr: line,
Write that IP address down, you'll need it going forward. Change
the IP address in Putty from before to this new one, and save the
configuration.
You can now unplug the Ethernet cable and re-connect to you RPi
from Putty using the new WiFi address.
CHAPTER 4 - Install a UPnP Client
Universal Plug-n-Play (UPnP) is a protocol to open ports on your
Internet router so that applications can talk to each other across the
Internet. We need this so that Putty can talk to your RPi once it is
installed in its remote location, and so that the OpenVPN client on
your Windows and/or Android devices can use it.
The RPi VPN Server we are building is nearly maintenance free. But
from time to time, you’ll want to check on it and update its software.
SSH with Putty allows us to do all that, and the UPnP software
ensures we can get to our RPi from anywhere in the world.

MiniUPnP
MiniUPnP is the easiest to install, and also the fastest running. So
we are going to install that one initially. If you have issues getting
MiniUPnP to work with your router, you can refer to the second part
of this chapter to install PortMapper, an alternate UPnP software
package.
If you’re not already logged into your RPi with puTTY, do so now and
set to root user with:
sudo -s
Now run the installation commands for command-line MiniUPnP and
its Python module:
apt-get install miniupnpc
apt-get install python-pip
pip install miniupnpc
Answer ‘Y’ to any prompt about additional disk space, etc.
The first command installing the command-line upnpc program for
testing. The second command installs the Python Package Installer
(PIP) that is used in the third command to install the miniupnpc
Python package used layer in our Python script.
Now to test it. Enter the following:
upnpc -s
Among all the junk it spits out, there should be a line starting with:
Found valid IGD
However, if you don’t see that, or instead find error messages such
as “No IGD UPnP Device found on the network !”, then MiniUPnP
is unable to connect to your router. This could be due to UPnP not
being enabled on your router, or MiniUPnP is not compatible with
your router. Please refer to your router's user manual to ensure it
supports UPnP and how to enable it.
If MiniUPnP is not working with your router, and it supports UPnP,
continue on to the next section, PortMapper (alternative to
MiniUPnP) to use it instead. Otherwise, we are done with this
chapter!
Note: If your router does not support UPnP or you do not wish
to enable it, please refer to Appendix C - Frequently Asked
Questions under What if my Router does not support UPnP
or I don't want to enable it?

PortMapper (alternative to MiniUPnP)


You’re here because MiniUPnP couldn’t talk to your router even
though it supports UPnP and its turned on. Fear not, we have an
alternative.
PortMapper is a Java App, and as such requires more work to install
it. It also runs a little slow, but that shouldn’t be an issue for us.
If you’re not already logged into your RPi with puTTY, do so now and
set to root user and change over to the ‘root’ folder:
sudo -s
cd /root
Now run the wget command to download PortMapper (all one line,
copy/paste into putty):
wget -O PortMapper.jar https://downloads.sourceforge.net/project/upnp-
portmapper/PortMapper-1.9.5.jar
Or download the script from here: http://bitman.org/irafinch/rpi-
vpn.zip
The wget command ‘web-gets’ PortMapper-1.9.5.jar and renames it
to just PortMapper.jar (its much easier to work with that way).
Note: I have tested this with v1.9.5 of PortMapper ONLY.
There may be newer versions of this program (and some are
Alpha (untested) releases). Using any other version may not
work and is not supported.
PortMapper requires Java Runtime Enviroment (JRE) and
depending on what flavor of Raspbian you downloaded, it may not
be installed. So we will run the installation command for JRE to
ensure we have it:
apt-get install default-jre-headless
If it is already there, you'll see a message saying so and that it's up
to date. If not, you will be prompted to install it along with its space
requirements. Just reply with a 'Y'
We’re doing a ‘headless’ install because we are only talking to the
RPi over SSH and not through a GUI (Graphical User Interface), so
we don’t need all those extra components. Still, its a little large and
make take some time to install.
Now lets test it and make sure it can talk to your router. Enter this
single line:
java -jar PortMapper.jar -s | grep 'Router Info:'
This will spit out about a dozen lines (if its working properly). These
should contain information like your router Name, Manufacturer,
Model, etc. If you don’t see this information, or you see error
messages instead, then PortMapper is not compatible with your
router. Please refer to Appendix C - Frequently Asked Questions
under What if my Router does not support UPnP or I don't want
to enable it?
Otherwise, we’re done with this chapter! That wasn’t so bad. On to
the next step.
CHAPTER 5 - Install and Configure OpenVPN
Finally!
If you’re not already logged into your RPi with PuTTY, do so now and
set to root user with:
sudo -s
For Wireless : OpenVPN on Jessie doesn't play nice with WiFi
adapters. It tears down the Wifi connection when it starts up.
So, if you are running your RPi wirelessly, then we need to edit
a file first:
1. Enter: nano /etc/default/ifplugd
2. Edit the HOTPLUG_INTERFACES line to look like this:
HOTPLUG_INTERFACES="eth0 wlan0"
3. Press Ctrl+X and Y to save and exit.

Note: The above ifplugd file does not apply to Raspberry Pi 3


models or the Stretch or Buster version of Raspbian.
So, now enter the following at the # prompt on your Raspberry Pi:
apt-get install openvpn
Another prompt will appearing telling you how much space this will
require and asking you if you want to continue with the install. Just
reply ‘Y’.

Notice the last line before the # prompt? Yup, you now have a
working VPN Server! But…
The problem is, no one can talk to it or even knows how to talk to it.
So we still have a little more work to do.
We need to generate some keys, both public and private to be used
to connect to our RPi VPN server. We’ll be using RSA (Rivest-
Shamir-Adleman) Cryptosystem. It’s already built into the OpenVPN,
so all we need to do is tell OpenVPN to use it.
Now enter the following at the # prompt (its one long line):
cp -r /usr/share/easy-rsa /etc/openvpn/easy-
rsa
This copies the RSA software from the ‘examples’ directory to the
‘etc’ directory so we can make changes and not screw up the
original.
Now we just ‘change directory’ over to our working copy so we can
muck with it:
cd /etc/openvpn/easy-rsa
And make a working copy of the vars.example file:
cp vars.example vars
There is no need to change any of the options in the vars file at this
point, the defaults work well for this setup.
Now its time to generate the CA (Certificate Authority) certificate and
the Root CA certificate. That’s the first step in creating a pair of keys
(server and client) to use our VPN server. So do the following:

1. Initialize the Initialize the Public Key Infrastructure (PKI).


This creates the structure for our master Certificate of
Authority (CA), and the Public & Private key pairs (it
doesn’t actually create these keys, just the structures):

./easyrsa init-pki
2. Build our CA, enter:

./easyrsa build-ca nopass


You can leave off the ‘nopass’ option and it will prompt you
for a passphrase. You’ll need this every time you connect
to the OpenVPN Server. But if you don’t publicly share your
Certificate Authority, there is no need to password protect it
with a passphrase.

You will now be prompted to enter a ‘Common Name’. I recommend


using the Raspberry Pi’s Host Name, if you gave it one, or a unique
name for this server. If you create more than one Raspberry Pi VPN
Server, it will make it easier to tell them apart.
Note: Remember this Common Name that you entered! You’ll
need that later.
Now its time to build the Root CA Certificate, so enter the following
at the # prompt:
./easyrsa gen-req servername nopass
servername is just what you entered above for ‘Common Name’.
You didn’t forget it already, did you?
You will also be prompted for the ‘Common Name’ again, but it
should default to the servername entered, so just press Enter.
Now we need to sign this server certificate so it can be used:
./easyrsa sign-req server servername
Where servername, again, is the Server Name you chose above.
Then just answer ‘yes’ to the prompt to Confirm this request.
Next is to create the Diffie-Hellman key exchange. This allow two
computers to exchange secret keys without knowing who they are
beforehand. Enter (this may take a while...like hours if you’re using
2048 bit Key Size – highly recommended):
./easyrsa gen-dh
Grab some coffee (or a movie if you used 2048 bit Key Size) and
come back here when it’s finished. Sometimes, if you’re really lucky,
this can go quick if it finds a suitable random prime key pair early.
Now there is an extra security step we should take to help prevent
Denial of Service (DoS) attacks. We need to build the Hash Based
Message Authentication Code (HMAC). If the OpenVPN server sees
a VPN request without this code, it won’t even respond – thus
preventing DoS attacks. Just enter:
openvpn --genkey --secret pki/ta.key
Next we need to create a server configuration file that tells OpenVPN
how to run on this RPi. Enter this command at the # prompt:
nano /etc/openvpn/server/server.conf
Then copy/paste the following into the nano window:
# local 111.111.111.111
dev tun
proto udp
port 1194
ca /etc/openvpn/easy-rsa/pki/ca.crt
cert /etc/openvpn/easy-rsa/pki/issued/SERVERNAME.crt # TBD - Change
SERVERNAME to your Server name
key /etc/openvpn/easy-rsa/pki/private/SERVERNAME.key # TBD - Change
SERVERNAME to your Server name
dh /etc/openvpn/easy-rsa/pki/dh.pem
server 10.8.0.0 255.255.255.0
ifconfig 10.8.0.1 10.8.0.2
push "route 10.8.0.1 255.255.255.255"
push "route 10.8.0.0 255.255.255.0"
push "route 111.111.111.111 255.255.255.0"
push "dhcp-option DNS 222.222.222.222"
push "redirect-gateway def1"
client-to-client
duplicate-cn
keepalive 10 120
tls-auth /etc/openvpn/easy-rsa/pki/ta.key 0
compress lzo
persist-key
persist-tun
user nobody
group nogroup
cipher AES-128-CBC
log /var/log/openvpn.log
status /var/log/openvpn-status.log 20
verb 1

Note: To paste in Putty, just click the right mouse button.


Or download the script from here: http://bitman.org/irafinch/rpi-
vpn.zip
There are two lines you need to change. They are all marked with ‘#
TBD’ on them. Set your OpenVPN Server name in place of
SERVERNAME (it is CaSe Sensitive!).
Press Ctrl+X and Y to save and exit.
Note: Don’t worry about the funky 111.111.111.111 and
222.222.222.222 IP Addresses, our nifty little script in the next
chapter will set that all up for us.
Almost done. Next piece is setting a server configuration file that
allows OpenVPN to send/receive data (packet forwarding) . By
default, Raspbian OS blocks all this. Enter:
nano /etc/sysctl.conf
And remove the # from the beginning of this line to activate it:
#net.ipv4.ip_forward=1
Press Ctrl+X and Y to save and exit. Then enter this to apply this
change:
sysctl -p
Next, we need to open Raspbian’s Firewall just a bit to allow
OpenVPN to communicate with the outside world. To do this we
need to create a new file. So enter:
nano /root/open_vpn_firewall.sh
And copy/paste in these lines:
#!/bin/sh
sleep 30
Adapter=`ip -o link show | awk '{print $2,$9}' | grep 'UP'| awk -F: '{print $1}'`
if [ -z "$Adapter" ]
then
Adapter='eth0'
fi
echo "Adapter = |$Adapter|"
/sbin/iptables -t nat -A POSTROUTING -o $Adapter -j MASQUERADE
/sbin/iptables -A FORWARD -i $Adapter -o tun0 -m state --state
RELATED,ESTABLISHED -j ACCEPT
/sbin/iptables -A FORWARD -i tun0 -o $Adapter -j ACCEPT

Or download the script from here: http://bitman.org/irafinch/rpi-


vpn.zip
Press Ctrl+X and Y to save and exit.
Note: It’s a long line so it might wrap and look funny. Just
resize the Putty window horizontally to see it all. And again,
don’t worry about the 111.111.111.111 ip address. Our script will
handle that.
We just created a Bash script, and we need to make it executable
and set it so that it runs every time our RPi boots. So enter these 2
commands to make it executable and owned by ‘root':
chmod 700 /root/open_vpn_firewall.sh
chown root /root/open_vpn_firewall.sh
And that’s it for this step! Yeah!!!
CHAPTER 6 - Create the Intelligent Python App
Previous revision of this book included a Bash script to add some
smarts to our VPN server and tie everything together. But bash is not
very powerful and the script was getting too large to maintain and
update. So, I’ve converted it to Python, the native programming
language of Raspbian, and that’s what we will be installing and
configuring in this chapter.
This Python app has many functions to keep our RPi up and running
smoothly. It will:
1. Check the RPi, Router, and External IP addresses regularly to
make any changes to the system when needed.
2. Notify you via email if something fails or a change is required on
the client side.
3. Regularly check the applicable UPnP Port Forwards to ensure
they are present, active and correct.
4. Log all its activity and errors for review and debugging (if
needed)
To begin, if you’re not already logged into your RPi with PuTTY, do
so now and set to root user with:
sudo -s
We need to install a small package that our script uses to support
the Stretch release of Raspbian:
pip install netifaces
The allows the script to get the network interfaces names under
Stretch, which are vastly different than previous version of Raspbian.
Now enter the following to switch over to the /root directory:
cd /root
And then enter:
nano check_ip.py
Note: Previous revisions of this book included this script in the
text. However, the check_ip.py script is too large, making it
very difficult to effectively copy/paste into the Putty window (it
may take a while to paste). So, please instead download the
script from the following link and copy and paste (right-mouse
click) into the putty window. Apologies for any inconvenience
this may cause. You’ll thank me later...
Download the script from here: http://bitman.org/irafinch/rpi-
vpn.zip
There are 13 lines near the top of the script that you may need to
change. We will go over them one by one:
ExtVPNPort = 1194
This is External Port for VPN connections. It is the Internet-facing
port, not the Port on the RPi. Normally, you can leave this at the
default of 1194. However, some ISPs, such as AT&T u-Verse &
Google Fiber, reserve that port for their own use. If in doubt, set this
to a Port number above 8000. For example, 8194 is a good choice.
ExtSSHPort = 22
This is the External Port for SSH (Putty) connections. It is the
Internet-facing port, not the Port on the RPi. Normally, you can leave
this at the default of 22. However, some ISPs, such as AT&T u-Verse
& Google Fiber, reserve that port for their own use. If in doubt, set
this to a Port number above 8000. For example, 8022 is a good
choice.
ExtSSLPort = 0
We’re not using SSL yet. That’s in later in Appendix E – OpenVPN
over SSL. So we can leave it at 0 (disabled) for now.
Adapter = 'eth0'
If this is commented out in your version of check_ip.py, then do not
alter it. The script determines this value automatically.
Otherwise, this is the Network attachment to your RPi. The default is
eth0 , which is its Ethernet plug. If you are setting your RPi up using
wifi, change this to 'wlan0' (including the single quotes)
UseMiniUPnP = True
You set up a UPnP client in Chapter 4 – Install a UPnP Client. The
default one is MiniUPnP. If that one worked for you, then you don’t
need to change this setting. However, if it failed, or you don’t wish to
use UPnP and will map the Ports manually, then set this to False
UsePortMapper = False
If MiniUPnP did not work for you in Chapter 4 – Install a UPnP
Client, and PortMapper worked, then change this to True . If
however neither one worked, or you don’t want to use UPnP and will
map the Ports manually in the router, then leave this as False
ServerName = 'RaspberryPi'
This is the name that will be put in the Subject line of any emails sent
from the RPi. If you gave your RPi a name in Chapter 2 – Load up
the Raspberry Pi, you can enter it here as well, or use a totally
different name, or leave it as is. Just remember to include the single
quotes around it.
EmailTo = 'me@email.com'
This is the email address the RPi will send status and alert
messages to when necessary. Set this your email box where you
would like to receive these. Be sure to include the single quotes
around it.
EmailFrom = 'myself@email.com'
This is the email address that you want to show as where the emails
came from. This does not have to be a real email address. Its just for
your reference. You can leave it at the default, set it to a real email
address you own, or to something that will help you identify the
emails as coming from the RPi. Just be sure to include the single
quotes around it.
SMTPHost = 'smtpout.emailserver.com'
This the SMTP (Simple Mail Transport Protocol) Host on which your
email box is hosted (EmailTo or EmailFrom). You will need contact
your email provider, or find their support web site to get this server
name. Be sure to include the single quotes around it.
SMTPPort = 465
This is the SMTP Port you email service provider uses for receiving
and sending emails. Normally, this is 465, but may be different
depending on your email service Ports 25 and 587 are also common.
You will need contact your email provider, or find their support web
site to get this Port number. Do not put quotes around this number.
SMTPUsername = 'username'
This is your Username for your SMTP email account on the
SMTPHost entered above. Be sure to include the single quotes
around it.
SMTPPassword = 'password'
This is your Password for the SMTP email account on the
SMTPHost entered above. Be sure to include the single quotes
around it.
Note: Please do not change any other settings in the
check_ip.py app. Doing so will probably result it in not working
with possible loss of data.
When done, press Ctrl+X and Y to save and exit.
Next we need to make this new script executable and set the owner
to ‘root’. Enter these 2 commands at the # prompt:
chmod 700 check_ip.py
chown root check_ip.py
Before going any further, lets check that our email settings are
correct and that the check_ip.py app can send you emails. Enter:
./check_ip.py -e
This will send a test email to EmailTo address you set above. If after
a few minutes, you don’t receive that email. Check the check_ip.log
file for any errors and make corrections to the corresponding settings
in check_ip.py :
To check the check_ip.log file: cat check_ip.log
To edit the check_ip.py app: nano check_ip.py
Lastly, we need to add Cron job entries to execute our check_ip.py
script every hour, restart OpenVPN every day, restart our RPi every
week and clean out the cache every month. Enter:
crontab -e
Select the default editor (nano) and copy/paste these lines to the
bottom of the file:
# Open the Firewall for VPN at Boot
@reboot /root/open_vpn_firewall.sh &
# Start the OpenVPN Server at Boot
@reboot /bin/systemctl start openvpn-server@server
# Check Our IPs and PortMappings at 5 after every hour
5 * * * * /root/check_ip.py > /root/cron.log 2>&1
# Restart Raspi at 5pm every Sunday: 0 17 * * 0
0 17 * * 0 /root/check_ip.py -r > /root/cron.log 2>&1
# restart openvpn daily at 5:10pm : 10 17
10 17 * * * /root/check_ip.py -v > /root/cron.log 2>&1
# clean the filesystem on the first day of each month at 4:55
55 16 1 * * /root/check_ip.py -c > /root/cron.log 2>&1

Or download the script from here: http://bitman.org/irafinch/rpi-


vpn.zip
Press Ctrl+X and Y to save and exit.
Now, rather than waiting up to an hour for our check_ip.py script to
run and configure our ports, etc., lets just run it now (note: your RPi
will reboot!):
./check_ip.py
If everything goes as planned. It will reboot. Shortly thereafter you
will get an email similar to the following:
Subject: RaspberryPi Status
Ext: 110.94.105.63
Rtr: 192.168.1.1
Rpi: 192.168.1.105
The first line is your RPi’s External IP address. The second line is
your Router’s Internal IP Address and the last line is your RPi’s
Internal IP Address. If/when the External IP address changes, you
will receive an email like this from your RPi so you know where he is
and can SSH and OpenVPN into him again.
At this point, you may wish to backup your RPi in case something
bad happens. While you could just run through this book again to
rebuild it, it might be easier to just back the Micro SD card up to your
Windows PC. Then you can just quickly restore it if needed.
See the Appendix for instructions on backing up and restoring your
RPi VPN Server.
On to the next step.
CHAPTER 7 - Create and Download Client
Certificate Files
From creating our Server Certificates back in Chapter 5, we know
they are good for 10 years, so we only have to do that step once
every decade!
However, we should create and download a Client Certificate for
each PC/Android device we want to connect to it. We could just
make one and use it on all devices, but only one of them would be
able to connect at a time.
We need to do some Initial Setup, then after that, creating Client
Certificate files is a snap.
If you’re not already logged into your RPi with PuTTY, do so now and
set to root user with:
sudo -s
Now create a defaults file by entering the following 2 commands:
cd /etc/openvpn/easy-rsa/pki
nano defaults.txt
Then copy/paste the following lines into it (remember to paste in
Putty, just click the right mouse button):
client
remote 000.000.000.000 1194
verb 1
nobind
mute 20
dev tun
compress lzo
proto udp
persist-tun
persist-key
key-direction 1
cipher AES-128-CBC
remote-cert-tls server
mute-replay-warnings
resolv-retry infinite
Or download the script from here: http://bitman.org/irafinch/rpi-
vpn.zip
Replace the 000.000.000.000 with your RPi’s External IP Address
(remember, that is the first line of the email your RPi sent you from
the previous Chapter). If you changed the external port for VPN from
1194 to something else, you’ll need to change that number as well.
Then Ctrl+X and Y to save and exit.

Lather, rinse, repeat…


This part you will need to repeat for every Client Certificate you need
to build.
If you’re not already logged into your RPi with PuTTY, do so now and
set to root user with:
sudo -s
So now we need to change over to the easy-rsa directory and build
the Client Certificate files by entering these 3 commands at the #
prompt:
cd /etc/openvpn/easy-rsa
./easyrsa gen-req ClientName nopass
Where ClientName is the name you wish to call this Client Certificate
file we are about to create. I’ve found that it’s easy for me to keep
track of my client files if I give them names that contain the VPN
server they connect to and the client device I will use them on. For
instance, if my RPi VPN server is called ‘Thor’ and I want to use this
Client Certificate on my Android phone, I might called it
Thor.Nexus6. One for my PC I could call Thor.Asus, etc., etc.,
etc…
There is a single prompt for ‘Common Name’ that should already
default to the ClientName entered above, so just press Enter.
Now we need to sign the client certificate request:
./easyrsa sign-req client ClientName
Where ClientName is the name you used above when you
generated the certificate. Just answer ‘yes’ to the prompt to Confirm
the request.
Now change directories over to ‘pki’ and run our check_ip.py script to
build the opvn file:
cd pki
/root/check_ip.py -m ClientName
Where ClientName is what you specified in the ./build-key
ClientName above.
When complete you will have created a Client Certificate file of
ClientName.ovpn that you must install on your client device. We’ll
cover that in the next two chapters.
If you need to create another Client Certificate file, just go back to
Lather, Rinse, Repeat… above.
Now to Download
You should be in the pki folder on your RPi, if not enter:
cd /etc/openvpn/easy-rsa/pki
Now follow these steps to copy your Client Certificate to your
Windows PC:
1. Enter: clear
This clears the Putty Screen.
2. Click on the Putty Icon in the upper-left corner of its window and
select Clear Scrollback
This clears the scrollback buffer in Putty so we don’t copy data
we don’t want.
3. Now enter: cat ClientName.ovpn
Where ClientName.ovpn is the ClientName you used to create
your client certificates above.
4. Click again on the Putty Icon in the upper-left corner of its
windows and now select Copy All to Clipboard
5. Open Notepad in your Windows PC and select Edit then Paste
6. Delete the first and last lines of the text pasted so that it starts
with client and ends with </tls-auth>
7. Now save your Client Certificate on your Windows PC giving it
the same name as before and with the .ovpn extension. You
will need to change the Save as type: selection to All Files
(*.*) to keep the .ovpn file extension.
CHAPTER 8 - Install and Configure OpenVPN for
Android
We’re actually going to install and configure on Android phone first.
Why? Because we can we can disconnect from WiFi on Android and
use 3g/4g data service to test the VPN server 'remotely'. Most
Windows machines don’t have wireless data plans and you can’t test
this setup if you’re on the same network as your RPi.
Note: If you don’t have an Android phone, then you need to connect
your Windows PC or Android Device to another network to test this
setup: Starbucks, an Airport, a friend’s home, etc., and skip to
Chapter 9.

1. Plug your Android phone in via USB.


2. Copy the *.ovpn file you created for your Android phone
over to it.
3. Disconnect your Android from your Windows PC.
4. Install OpenVPN for Android by Arne Schwabe via
Google Play Store. Requires Android OS 4.0 or newer:
https://play.google.com/store/apps/details?
id=de.blinkt.openvpn&hl=en

Note: If you can’t access the Google Play Store, then:

1. Open your Web Browser on your Android phone and go to


this web site:
http://www.apk20.com/apk/239707/
2. Click on the blue Download APK from APK20 link to
download this app.
3. If you get a pop-up about this type of file may harm your
device, just click on OK
4. Go to Setting on your phone and check Unknown Source
under Security
5. Drop down the task bar and click on it.
6. It will open Package Installer and ask if you want to install
this application, just click on Install

Now that you have OpenVPN for Android installed, to test this setup,
follow these steps on your Android:

1. Turn off WiFi.


2. Open the OpenVPN for Android App
3. Click on the Folder icon in the upper right.
4. Find your .ovpn Client Certificate file and Select it.
5. Click on diskette (or check mark) icon to save and it will
show up in your list of profiles.

To connect, just click on the Profile Name. After a few seconds of


negotiations with your RPI, you should get a 'Connected' message
and a little key in your status bar.
Any application you run that connects to the Internet (web browsers,
email clients, etc.) will do so through the VPN client and your RPi
VPN server and be secure from prying eyes.
To disconnect, just drag down the notification bar and click on
Disconnect.
Please refer to Appendix A – Maintenance, What to do if the external
IP address changes, for steps to update your OpenVPN for Android
client file if/when the external IP address of your RPi changes.
CHAPTER 9 - Install and Configure Windows
OpenVPN GUI
Note: Most Windows machines don’t have wireless data plans
and you can’t test this setup if you’re on the same network as
your RPi. You need to instead connect your Windows PC to
another network to test this setup: Starbucks, an Airport, a
friend’s home, etc.
Installation and Configuration of the Windows OpenVPN client is
easy and straightforward. But you need to be an Administrator on
your PC in order to install and run it.
The first thing you will need to do is download the OpenVPN GUI
client from this web site:
https://openvpn.net/index.php/open-source/downloads.html
1. Select the appropriate Installer for your version of Windows
to download it.
It’s only about 2MB in size, so it should download fairly
quickly.
2. Run the App to install it.
3. Open Windows Explorer and copy your OpenVPN client
file (.ovpn) you created and downloaded in Chapter 7.
4. Navigate over to the C:\Program Files\OpenVPN\config
folder and paste that file into this folder.
5. Run the App and click OK on any warnings you get about
running this program.

You’ll now see a new icon in your system tray. It looks like a gray
window with a padlock on it. Right click on the icon and click on
Connect. A log window will appear showing the progress of
connecting to you RPi VPN Server. Once it has connected
successfully, the icon will turn green and the padlock will be closed
(locked) indicating a secure connection.
Any Windows application you run that connects to the Internet (web
browsers, email clients, etc.) will do so through the VPN client and
your RPi VPN server and be secure from prying eyes.
To disconnect, just right-click on the icon and select Disconnect.
Please refer to Appendix A – Maintenance, What to do if the external
IP address changes, for steps to update your Windows OpenVPN
GUI client file if/when the external IP address of your RPi changes.
CHAPTER 10 - Ship It!
Time to put your RPi in its Forever Home.
Now, if you are building an RPi VPN to access blocked content, it
needs to be outside the network that is doing the blocking. However,
if you're following this project to protect yourself on open WiFi hot-
spots, you only need place it in your home attached to your Internet
router.
Note: I am not advocating illegal activity. Any rules, regulations,
policies or laws broken in the use of this VPN server is your
own responsibility and absolutely no responsibility or liability on
the part of the Author is expressed or implied. You are doing so
at your own risk, period.
So, now, if you need to send it somewhere to live, just shut it down
using the following command:
sudo shutdown -h now
Unplug the network cable and power cable and put everything in a
box and send it to wherever it needs to go.
Note: As covered in the Preface of this book, running your RPi
VPN Server Wirelessly prevents you from shipping it to a
remote location and having someone just 'plug it in'. The SSID
(wifi name), password, security type need to be set manually
for wherever it is being installed. See Appendix A for directions.
For Ethernet: The recipient on the other end just needs to plug it
into their router and plug in the power. Within an hour, you will get an
email from your RPi with its new External, Internal, and Router’s IP
addresses. At that time you will need to edit your .ovpn config files to
use the new External IP address. This is also covered in Appendix A.

For Android
1. Run the OpenVPN for Android App on your Android
device.
2. Click on the Setting Icon to the right of the profile to be
changed
3. Click on the Server List tab
4. Enter the new External IP address into the Server Address
edit box that you received in the email from your RPi
Remember the External IP address is the FIRST address
listed in the email
5. Click the back arrow to exit and you’re done.

For Windows
1. Right-click on WordPad in the Accessories folder of the
Start Menu and select Run as Administrator.
2. Click on Open in the WordPad Menu and navigate to:
C:\Program Files\OpenVPN\config
3. Select All Documents from the All WordPad Documents
drop-down
4. Open your OpenVPN Client config file (.ovpn)
5. Find the line starting with remote and change the External
IP address shown to the one given in the email from your
RPi
Remember the External IP address is the FIRST address
listed in the email.
6. Click on the Save icon in the title bar and close WordPad.

Any time you receive and email from your RPi where the External IP
address has changed, you will need to make these changes in your
OpenVPN Client config file(s). You do not need to re-create these
files as you did in Chapter 7 until 10 years have passed -or- you re-
create the Server keys in Chapter 5 (for some reason).
APPENDIX A - Maintenance
I said this was nearly maintenance free. Nothing runs forever without
a little help.
Additional Maintenance tips can be found on my supporting web site
for this book at: http://bitman.org/irafinch/rpivpn/

What to do if the external IP address changes


Most modems connected to the Internet are run under DHCP
(Dynamic Host Configuration Protocol) and so their assigned IP
address can, and does change. The ISP (Internet Service Provider)
may push a software update, or reboot the modem, or just reset the
IP address to something different. These can happen at any time,
but it’s been my experience that it is rare (like once or twice a year)
and therefore not much of a headache to deal with when it does.
When the External IP address changes (your ISP’s modem IP
address), your RPi VPN server will detect this within an hour and
send you an email stating so. It will look something like this:
Subject: RaspberryPi IP Change
110.94.105.63
192.168.1.1
192.168.1.105
The first line is the new External IP address, the second is the
Router’s internal IP address and the third line is your RPi’s internal
IP address. It is the first line we are interested in.
For PuTTY
If you need to access your RPi remotely using PuTTY, then you'll
need to edit your session in PuTTY to use the new address:
1. Run putty.exe in Windows
2. Selected your RPi session and click on Load.
Or just create a new session by skipping this step.
3. Enter the External IP address (the first line) from the email into
the Host Name box
4. Enter the External Port number you set for SSH in Chapter 6
(ExtSSHPort)
5. Select SSH for the Connection type.
6. Give it a name (if its a new session) in the Saved Sessions edit
box.
7. Click on the Save button.
Note: If your RPi VPN is on the same internal network as your
Windows PC, then just use the Internal IP address in the email
(the third line) in step 3 and port 22 in step 4.

OpenVPN
We need to edit the OpenVPN Client config file(s) (.ovpn) to set this
new address. To do so, follow these steps for the device that needs
changing:

For Android

For standard OpenVPN connections:


1. Run the OpenVPN for Android App on your Android
device.
2. Click on the Edit Icon to the right of the profile to be
changed
3. Click on the Server List tab
4. Enter the new External IP address into the Server Address
edit box that you received in the email from your RPi
Remember: the External IP address is the FIRST address
listed in the email
5. Click the back arrow to exit and you’re done.

For OpenVPN over SSL connections:


1. Run the SSLDroid App on your Android device.
2. Click on the Tunnel name for your connection.
3. Edit the Remote Host field and enter the new External IP
Address that you received in the email from your RPi
Remember: the External IP Address is the FIRST address
listed in the email.
4. Click Apply and exit the App.
5. Run the OpenVPN for Android app
6. Click on the Edit Icon to the right of the profile to be changed
7. Scroll to the ADVANCED tab and click on it
8. Click on Custom Options at the bottom of the page and
replace the IP address on the route line with then new External
IP Address that you received in the email from your RPi
Don't change the mask (255.255.255.255)
9. Click OK and then the back arrow to exit and you’re done.

For Windows
For standard OpenVPN connections:
1. Right-click on the OpenVPN GUI icon in the System Tray
2. Hover over your Client Configuration name in the pop-up
menu
3. Click on Edit Config in the pop-up side menu
4. Change the IP address on the remote line sent from your
RPi (Ext)
Do not change the port number after the IP address
5. Click on File then Save, and then File and Exit

For OpenVPN over SSL connections:


1. Run the stunnel application
2. Right-mouse click its Icon and select Edit Configuration
3. Scroll down to your RPi Server Name in brackets
4. Edit the connect = line and replace the old IP address with
the new External IP Address to the one given in the email
from your RPi
Remember: the External IP Address is the FIRST address
listed in the email
5. File Exit and Save
6. Run the OpenVPN GUI
7. Right-mouse click on its icon and mouse-over OpenVPN
Server connect to change and select Edit Config
8. Find the route line and change the IP address on it to the
new External IP Address that you received in the email
from your RPi
Don't change the mask (255.255.255.255)
9. File Save and Exit

Backing up your RPi


At some point, you may wish to backup your RPi in case something
bad happens. While you could just run through this book again to
rebuild it, it might be easier to just back the Micro SD card up to your
Windows PC. Then you can just quickly restore it if needed.
Note: These instructions are only if you have your RPi with you
and it’s NOT located remotely where you cannot physically get
your hands on it.
To backup your RPi, follow these steps:

1. Run PuTTY on your Windows PC and log into you RPi


2. Shut it it down by entering this command:
sudo shutdown -h now
3. Unplug the power cable and remove the Micro SD card.
4. Insert the Micro SD card into your card reader on your
Windows PC
5. Execute Win32DiskImager (that we installed in Chapter 2)
as Administrator by right-clicking on the program and
selecting Run as Administrator.
6. Select the Device Drive Letter of your SD Card in the drop-
down box on the right.
Make sure you select the CORRECT drive letter or you
could wipe out your Windows PC!!
7. Click on the folder Icon to set the location and filename for
the Image.
You need to enter a new filename for the disk image with
the .img extension and then click on open.
8. Now click on the Read button
This will read the Micro SD card and write its image to the
filename you specified.
9. Once it is finished, close Win32DiskImager and eject the
Micro SD card.
You can then put it back in your RPi and plug the power
back it.

If you need/want to create a new RPi image onto an SD card, just


follow the same steps we did in Chapter 2 for loading the Raspbian
OS image:

1. Insert your SD card into the SD card reader and note which
drive letter it assigned.
If its not formatted for Fat32, you’ll need to do that now.
2. Run Win32DiskImager as Administrator by right-clicking
on the program and selecting Run as Administrator.
3. Select the RPi image backup you previously created.
4. Select the Drive Letter of the Micro SD Card.
Make sure you select the CORRECT drive letter or you
could wipe out your Windows PC!!
5. Click Write and wait for it to complete.
6. Exit Win32DiskImage and eject the SD card.

Updating the RPi software


Software is updated all the time. New features and functions are
added, bugs are fixed and, most importantly, security holes are
closed. You’ll probably want to update the software on your RPi
periodically (every few months or so) to ensure everything is up-to-
date, stable and secure. This is pretty easy and can be done no
matter where your RPi is located:
Note: This may disconnect any active OpenVPN sessions
running on your RPi.
1. Run PuTTY on your Windows PC and log into your RPi
2. Enter this command at the # prompt to update the list of
programs and versions available:
sudo apt-get update
3. Now run this command to actually update the software on
your RPi:
sudo apt-get upgrade
4. Once it is finished, you’re up-to-date and there is no need
to reboot unless instructed to do so.
If you are prompted to reboot, enter: sudo shutdown
-r now
And you’re done!

WiFi: Changing the SSID, Security Type or


Password on you RPi
Your RPi VPN server is not totally Plug-n-play when connected via
WiFi. If the Router's SSID (name), security type, or password ever
changes, you must manually set these values in your RP. This can
only be done if you have direct, physical access to your RPi:
1. Plug an HDMI monitor, and keyboard into the RPi
2. If nothing appears on the monitor, you will need to restart the
RPi. The only way to do this at this point is to unplug its power
cord, wait about 10 seconds, and then plug it back in.
3. Log in with the keyboard and enter: sudo -s
4. Now enter the following to edit the config file:
nano
/etc/wpa_supplicant/wpa_supplicant.conf
5. Change the SSID (WiFi router name) field if needed.
6. Change the psk (password) field if needed.
7. The key_mgmt field shouldn't need to be modified unless you
changed to an older, less secure, key method (not
recommended)
8. Press Ctrl+X and Y to save and exit.
9. Now reboot the RPi from the Putty window, enter:
sudo shutdown -r now
After logging back in using Putty (to verify WiFi is working properly),
you can unplug the keyboard and HDMI monitor.
APPENDIX B - Troubleshooting
The supporting web site for my book can be found at:
http://bitman.org/irafinch/rpivpn
There you will find additional and updated Errata and
Troubleshooting pages not contained here.
Significant changes to this book will result in uploading a new
revision to the Kindle Book Store and noted in the book's description.
Below are some common issues that may be encountered in setting
up your Raspberry Pi VPN Server.

OpenVPN Server Won’t Auto-Start on Reboot


If you cannot connect to your RPi using OpenVPN and get the error
“connection refused” or a “TLS” error, it may be that OpenVPN is not
auto-starting on boot.
If you have a Raspberry Pi 3B, there appears to be an issue in the
latest Raspbian Jessie builds that prevents OpenVPN from binding
to the ‘local’ address given in the server.conf file when there are 2
network adapters (the RPi 3 has a Wireless and an Ethernet
adapter).
Check the openvpn.log file for Socket bind failed on local address,
or similar:

sudo -s
cat /var/log/openvpn.log
If this is the case, the current workaround is to comment out the
local line in server.conf :

nano /etc/openvpn/server.conf
Then just place a ‘#’ (without the quotes) in front of local line. Ctrl+X
and Y to save and exit. Then reboot:

shutdown -r now
Otherwise, refer to the Help / Troubleshooting page on the
supporting website for more information, or contact the author
directly via the email address given on the copyright page of this
book.

OpenVPN over SSL Won't Connect


SSL Port 443 may be blocked, or in use, by your Internet Service
Provider (ISP).
There are some ISPs that use or block SSL port 443 for their own
use: firmware updates and modem diagnostics. AT&T uVerse and
Google Fiber are two I personally know of that do this.
The easiest solution to this is to just use another port instead of 443.
Usually anything above 8000 is open for personal use.
There are just a few places this would need to be changed:
1. The /root/check_ip.py script: Change the ExtSSLPort to your
new Port Number:

sudo nano /root/check_ip.py


2. SSLDroid on your Android Device: Change the Tunnel Remote
Port to your new Port Number
3.
stunnel on Windows: Edit Configuration and set the Port on
the connect line to your new Port Number
Restart stunnel on your RPi and try to connect again:

sudo /root/check_ip.py -s

PortMapper / MiniUPnPc Issues


Cannot Find Router
The most common reasons for this is that the router does not
support UPnP or it is not enabled. Please refer to your router's user
manual to ensure it supports UPnP and how to enable it.
If it has been a number of months since your router has been
rebooted, you can try doing that to resolve this. You can do so either
through the router's administration page (check the manual), or by
unplugging it for 20 seconds and then plugging it back it.
If your router does not support UPnP, or you do not wish to enable it,
please refer to Appendix C, under What if my Router does not
support UPnP or I don't want to enable it?
Missing Files
This is most often due to using a different version of PortMapper
than the one specified in this book. It is highly recommended that
you only use v1.9.5 of PortMapper as other versions have not been
tested, and some are Alpha or Beta versions that contain bugs.

Router Issues
No UPnP Support
If your router does not support UPnP, it is still possible to use it – it
just won't be portable or as dynamic in its auto-configuration. Please
refer to Appendix C under What if my Router does not support UPnP
or I don't want to enable it?

Connection Issues
VPN Client Connects but No Internet
If you can connect to the RPi VPN Server, but cannot access the
Internet with either a Web Browser, eMail or internet app, then its
probably due to the firewall on Raspbian OS.
Review Chapter 5 and ensure everything is set up and configured as
described. Specifically check the last part of that chapter where
open_vpn_firewall.sh is created and added to the /etc/rc.local
file. This opens the firewall in the Raspbian OS and allows OpenVPN
to receive and transmit.
There is also a bug in the current Jessie version (Nov 2015) that is
keeping the firewall rules from running at startup. A work-around to
this is to set that script to run after everything else has started.

sudo -s
nano /etc/rc.local
add /etc/open_vpn_firewall.sh on a line just before the exit 0 in
the script.
Press Ctrl+X and Y to save and exit.

VPN Client Connects but is really slow and/or times out often
This most often is due to a poor or slow internet connection on you
Android or Windows device, especially over Cellular Data Networks.
This is also common if you RPi VPN Server is located overseas.
There is not much that can be done in this situation other than try to
get a better Cell Signal or use a faster internet connection.
Another, less likely scenario is an ISP (Internet Service Provider)
between you and you RPi has changed the Maximum Transmission
Unit (MTU) size to something less than the standard of 1500 bytes.
Some foreign ISPs are known to do this to discourage the use of
VPN services. If you feel this might be the case, you can add the
tun-mtu 1300 parameter on a new line at the end of the
server.conf and the defaults.txt files created in Chapter 5 and
Chapter 7, respectively.
You will need to restart the OpenVPN service on the RPi through
Putty:
sudo -s
/root/check_ip.py -v
You will also need to rebuild and download a new client .ovpn file as
described in Chapter 7. Or if you are an experienced Windows or
Android user, you can edit the .ovpn client file directly using
WordPad in Windows and the VPN for Android app on your
Android device to add the tun-mtu 1300 parameter.
Lastly, it could be that your ISP is blocking OpenVPN connections.
Refer to APPENDIX E – OpenVPN over SSL for instructions on
using SSL with OpenVPN.
VPN Client, or Putty fails to connect and times out
Ensure you have the correct External IP address set in the
defaults.txt file created in Chapter 7. If need to edit that file to set a
different IP address, then please refer to Appendix A, What to do if
the external IP address changes.
If you are running your RPi wirelessly, then your WiFi adapter
probably has a sleep mode to conserve power. You may need to try
connecting to it 2-3 times to wake it up before it is successful.
This also has the same causes as the above topic VPN Client
Connects but is really slow and/or times out often. Please refer to
that section for help.

Putty Issues
Can't Paste Text into Putty Window
There are five ways to paste text into the Putty window. First copy
the text from this book in your Kindle reader App by highlighting it
and using Ctrl+C, then try the following to paste into the Nano editor
of the Putty Window:

1. Right-Mouse click for a two-button mouse.


2. Middle-Mouse click for a three-button mouse.
3. Shift+Ins keys together
4. Fn+Shift+Ins keys together for combo delete/insert keyboard
key
5. Ctrl+Right-Mouse click and select Paste from pop-up menu

Kindle Reader Issues


Can't Copy from Kindle Reader and Paste into Putty Window
If you are experiencing issues with Copy/Past from Kindle Reader
into the Putty Window (eg: formatting is lost, extra text is added,
etc.), then download the scripts from the link below. You can then
use Notepad to open the scripts and then copy/paste them into
Putty:
http://bitman.org/irafinch/rpi-vpn.zip

Contacting the Author


If you encounter errors in this book, confusion with the instructions,
or have constructive criticisms/suggestions for improvement, please
feel free to contact the author via the email below:
irafinch888@bitman.org
website: http://bitman.org/irafinch/rpivpn
APPENDIX C – Frequently Asked Questions
Below are some common FAQs regarding this book.
Additional, updated FAQs can be found on my supporting web site
at: http://bitman.org/irafinch/rpivpn
Can I run my RPi VPN Server Wirelessly to my Router?
Yes. There are instructions in the book on how to do that, but it is
generally not recommended. The throughput can be much less and
retries more frequent, thus impacting performance. See the Preface
for more information.
Can I Use Apple and/or Unix VPN client devices?
This should be possible. You will need to find similar VPN clients for
the Apple and Unix devices that can import standard .opvn
configuration files, and follow those instructions for doing so. I don't
have experience in that area, so will not be able to help.
Also note that as of this writing, you cannot set the tun-mtu
parameter on iOS devices (as given in VPN Client Connects but is
really slow and/or times out often above). So if your ISP has set a
lower MTU value, VPN won't work.
What if my Router does not support UPnP or I don't want to
enable it?
Most routers will allow you to set Single Port Forwarding. You will
need to manually configure Port Forwarding of external ports for
SSH and VPN (as set in the check_ip.py script in Chapter 6) to
forward to ports 22 and 1194, respectively, of your RPi's IP
Address.
The RPi uses DHCP (Dynamic Host Configuration Protocol) by
default and not Static IP addresses. So you would also need to
configure your RPi to use Static IP addresses so that it IP address
does not change if/when it reboots. There are many web sites that
explain how to set up Static IP addressing. Just Google for
Raspbery Pi Static IP setup.
Note: There is a bug in the current Jessie build (Nov 2015) that
prevents Static IP setup using the standard method (I'm finding
lots of bugs in Jessie..). If you experience problems with this,
check out this Thread on the Raspberry Pi Forum for a
workaround:
https://www.raspberrypi.org/forums/viewtopic.php?
f=91&t=124423
As this setup makes the RPi not portable, and configurations for Port
Forwarding greatly vary from router to router, it is beyond the scope
of this book and I will be unable to assist with this.
You will also need to edit the check_ip.py script we created in
Chapter 6.
If you have version 2.6 or later of the check_ip.py script, the changes
are easy:

sudo -s
nano /root/check_ip.py
Change these three lines at the start of the script, setting their Port
Numbers to 0 :

ExtVPNPort=0
ExtSSHPort=0
ExtSSLPort=0
This will prevent PortMapper from trying to use UPnP to set the Port
Forwards on your router.
To disable the use of UPnP completely, also change these lines as
follow:

UsePortMapper=False
UseMiniUPnP=False
You can download the latest version here:
http://bitman.org/irafinch/rpi-vpn.zip
If you have an older version of check_ip.sh and don't want to
download the latest check_ip.py, we need to edit the check_ip.sh
script to remove the PortMapper calls:

sudo -s
nano /root/check_ip.sh
Using Ctrl+K, remove all the lines in that script between:
#
# Loop through each UPnP device that looks like a Router with
each Lib
# and match its Index back to the real router's IP Address
#
AND
#
# Check if any IP changed and email me if so
#
And that should take care of it.
I cannot provide any assistance with this change as it breaks my
script and is untested.
Will these instructions work with the Raspberry Pi Zero?
It should, but I honestly don't know for sure. It all depends on
compatibility of the SMTP Mail services, VPN Service, and
PortMapper with that device and it's Operating System. I hope to test
that device out in the future.
APPENDIX D – Harden your SSH Login
This Appendix applies only after you have built your RPi VPN Server
and have it running successfully.
Hopefully you've chosen a very strong password for your 'pi'
username login. After all, as we discussed in Chapter 2, it is exposed
on the Internet through SSH. If you want to increase security on this
front, as I have, you can install and enable Google 2-Step
Verification on your RPi.
Note: This is not a tutorial on Google's 2-Step Verification
service or its companion Android Authenticator App. If you are
not familiar with this service and do not already have the
Authenticator App on your Android device, please do not
attempt to run this service on your RPi. You could easily lock
yourself out, requiring a complete wipe and reload of your RPi's
SD Card.
You can read/learn more about Google 2-Step Verification here:
https://www.google.com/landing/2step/
So, if you already use Google Authenticator, have the app installed
on your Android Phone and are comfortable using it, then these
instructions will show you how to set up your RPI VPN server with 2
Step Authentication for SSH logins. This will:
Help prevent Man In The Middle Attacks
Harden your RPi against brute-force login attempts
Further secure your RPi even if your password is
compromised

Furthermore, 2 Step Authentication is completely stand-alone on


your RPi: It does not need to talk to Google at any time.
Note: Once you have enabled 2 Step Authentication on your
RPi, you will always need to have your Android phone with you
and use the Google Authenticator app to login - OR - have the
saved Emergency Scratch Codes (that will be generated) with
you.
Step 1. Install Google Authenticator on your RPi
Login to your RPi and switch over the to root user:

sudo -s
Now install the package:

apt-get install libpam-google-authenticator


Step 2. Edit it's config files
We need to set Google Authenticator to work with SSH:

nano /etc/pam.d/sshd
And add this line anywhere in the file:
auth required pam_google_authenticator.so
Press Ctrl+X and Y to save and exit.t.
Now, enable Google Authenticator in the SSH Config file:

nano /etc/ssh/sshd_config
Find the following line and change it from no to yes:
ChallengeResponseAuthentication yes
Press Ctrl+X and Y to save and exit.
Step 3. Activate 2 Step Authentication for Your Login Account
You probably login to your RPi as 'pi' user. So lets get back to that
account to activate it:

exit
Your RPi prompt should now be pi@servername (where servername
is the name of your RPi). Now enter:
google-authenticator
You will be shown a QR code you can scan into the Android Google
Authenticator App (or enter in the Secret Key). It will also give you 5
Emergency Scratch Codes that you should write down and save in
case you can't use your Google Authenticator App on you Android
device.
I recommend answering 'Y' to all the questions - except the fourth
one: increasing the windows from 1:30min up to 4min. You shouldn't
have problems in this area, so I suggest entering 'N' on that one.
Step 4. Restart SSH and Test
Restart SSH with the following command:

sudo service ssh restart


To test, start another Putty session and try to log into your RPi.
Note: Do NOT close your current Putty/SSH window. If there
are problems, you're still logged into it and can undo these
setting to get back to a working environment.
Your login prompts will now be different:
login as: your username (probably pi)
Using keyboard-interactive authentication.
Password: your standard password just as before
Using keyboard-interactive authentication.
Verification code: the verification code from the Google
Authenticator App
If everything worked correctly, you'll now be logged in and no one will
be able to hack into your RPi without your Android device running
Google Authenticator - so don't loose your phone!
Enjoy your new level of piece of mind!
Note: If you can't log in, Switch back to 'root' account ( sudo -
s ) on your first SSH window. Then go back to Step 2 above
and undo those changes to the two files. Then restart SSH
again ( sudo service ssh restart ). You should now be
able to log into your second SSH window. Now review all the
steps in this article to see if you miss-typed, or missed
anything.
APPENDIX E – OpenVPN over SSL
This Appendix applies only after you have built your RPi VPN Server
and have it running successfully.
There are situations where OpenVPN (or VPN in general) won't work
as some internet providers do not allow VPN over their networks.
One solution to this problem is to encapsulate VPN data in SSL
(Secure Socket Layer) packets. There is a much less likelihood of
SSL data being blocked. If you are in this situation, this chapter may
help.
NOTE: If VPN is blocked by your ISP (Internet Service
Provider), Company, or Host, there may be a regulation,
legal agreement, or state/federal law behind it. Therefore,
bypassing this restriction by using OpenVPN over SSL
may very well be illegal and doing so could get the you in a
lot of trouble. So just as stated in the Copyright page of
this book, the author shall not have any liability to any
person or entity with respect to any loss or damage
caused, or alleged to be caused, directly or indirectly, by
any information expressed or implied in this book, or web
site, or by the computer software and hardware products
described in it. You have been warned. You're on your own.

Overview: Let's Pause and Talk About What


We're Going to do Here
The following diagram should help illustrate this new setup:
1. The browser (or other internet app) on your Windows/Android
device requests something from the Internet - like a web page.
2. OpenVPN Client takes that data request and encrypts it with
VPN and sends it out port 1194
3. Stunnel Client gets that data via port 1194 and encapsulates it
into SSL packets and sends it out port 443 through the
(restricted) Internet to our waiting RPi.
4. Stunnel Server on our RPi reads the data via port 443 and
decrypts/de-encapsulates it from the SSL and passes it to
OpenVPN server via Port 1194.
5. OpenVPN Server reads the data from port 1194 and decrypts
the VPN data and sends the internet request out to the free and
open Internet.
6. Response data from the Internet just goes backward through
this process, ending up back at the internet app on your device
that requested it.

Caveats:
1. You will be encrypting and decrypting the data twice: once for
OpenVPN and then again for SSL. This can slow things down
2. You must use TCP for OpenVPN and SSL. UDP can't be used.
This can also slow things down.
3. Your RPi OpenVPN server must always run OpenVPN over
SSL for all connections. This is a extra connection step that you
didn't need to do before, and extra software to configure and
maintain.
4. You might be breaking the law (as stated previously)
Still want to proceed? Let's do it!

Setting up your RPI for OpenVPN over SSL


Log into your RPi and set yourself as root:

sudo -s

1. Update Your RPi Software and Install stunnel4


stunnel4 is the Raspbian implementation of SSL.
We need to ensure that all the software is current on your RPi before
proceeding, otherwise we might encounter bugs and other issues.
So execute these commands from the RPi prompt to update its
software and install stunnel4:

apt-get update
apt-get upgrade
apt-get install stunnel4

2. Create the Private Server SSL Key &


Certificate
Just as with OpenVPN, SSL requires a Server Key and Certificate –
hence the double encryption.
These 3 commands will create our private server SSL Keys to use
when talking to it:

cd /etc/stunnel
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out
server.csr
The second command creates the server key with 2048 bit
encryption. It is slower, but more secure. So you can change it to a
lower value, like 1024, but its not recommended.
The last command above is very similar to when we created the
OpenVPN server keys. It will ask for a bunch of optional fields to be
entered. You can set them to whatever you wish, or just leave blank.
However, I like to set the Common Name field to the same as the
Server's Hostname your set your RPi to in Chapter 5, with an 'SSL'
suffix. This just makes it easier for me to keep track of the Keys and
Servers they belong to.
All fields after "Common Name" should be left blank.
Now we will create the certificate and combine it with the key. We're
setting the certificate to be good for 10 years, just like the OpenVPN
certificate.
Enter these 5 commands (the first command is really long and may
appear on multiple lines):

openssl x509 -req -days 3650 -in server.csr -


signkey server.key -out server.crt
cat server.key > server.pem
cat server.crt >> server.pem
chmod 400 server.pem
chown root server.pem

3. Enable stunnel and Configure it


Edit the stunnel4 file using the following command:

nano /etc/default/stunnel4
And add this line to the end of the file:
ENABLED=1
Press Ctrl+X and Y to save and exit.
Now we need to create the stunnel.conf file:

nano /etc/stunnel/stunnel.conf
It's a new file, so it will be empty. Fill it with the following:
sslVersion = all
options = NO_SSLv2
cert = /etc/stunnel/server.pem
pid = /var/run/stunnel.pid
output = /var/log/stunnel
socket = l:TCP_NODELAY=1

[openvpn]
client = no
accept = 443
connect = 000.000.000.000:1194
Or download the script from here: http://bitman.org/irafinch/rpi-
vpn.zip
Note: Replace the 000.000.000.000 with your RPi's IP address.
This can be found in the first line of the /root/check_ip.txt file.
The 'trick' we are performing here is in the [openvpn] section. This
tells stunnel that we are a Host, not a Client, to accept data through
port 443 (standard SSL port) from outside requests, and then
forward those data packets to port 1194 (OpenVPN Port) on our
Raspberry Pi.
Press Ctrl+X and Y to save and exit.

4. Change OpenVPN to Use TCP Instead of UDP


SSL (stunnel) only works with TCP data, not UDP. While this will be
a bit slower, its better than nothing at all (if you can't get through with
straight OpenVPN).
So let's edit the OpenVPN Server Config file:

nano /etc/openvpn/server/server.conf
Find and change the proto udp line to: proto tcp
Press Ctrl+X and Y to save and exit.

5. Edit the Defaults.txt file for Future Clients


Make a note of your RPi External IP address as shown in the third
line of the /root/check_ip.txt file:

cat /root/check_ip.txt
If you create any new Client Certificates, you will want them to
default to the correct VPN Host (localhost), Port (1194) and Protocol
(TCP). So we need to edit that file now:

nano /etc/openvpn/easy-rsa/pki/defaults.txt
Change the remote line to: remote localhost 1194
Change the proto line to: proto tcp
Now add the following line to end of the file:
route 000.000.000.000 255.255.255.255 net_gateway

Set the 000.000.000.000 to your RPi External IP address from the


/root/check_ip.txt file from above.
Press Ctrl+X and Y to save and exit.
This last line (route) prevents OpenVPN from catching the data SSL
is sending to your RPi and re-encoding it (again!).

6. Modify the check_ip.py script


Change over to the root folder:
cd /root
The check_ip.py script supports SSL. If you have an older version
called check_ip.sh, download the latest from here:
http://bitman.org/irafinch/rpi-vpn.zip

Note: If you are replacing on older version of the check_ip.sh


script, write down the values you have set for the following
items listed at the top of your current check_ip.sh script:
1. Load the check_ip.sh into the editor:
nano ./check_ip.sh
2. Write down values of these settings: ExtSSHPort,
EmailAddr, ServerName, Adapter
3. Press Ctrl+X and Y to save and exit.
4. Now delete the old script:
rm ./check_ip.sh
5. And copy/paste the new script into the nano editor:
nano ./check_ip.py
(Right-mouse click to paste into nano)

In the nano editor ( nano ./check_ip.py) , change the


ExtSSLPort line to: ExtSSLPort=443
Then change the ExtVPNPort line to: ExtVPNPort=0
OpenVPN is no longer used externally to your client. Its data is
passed to SSL which then talks externally to the SSL Clients. Hence
we disable its External VPN Port by setting it to 0.
If you replaced your previous check_ip.sh script, then update the
values for ExtSSHPort, EmailAddr, ServerName and Adapter.
Press Ctrl+X and Y to save and exit.
Let's make sure it is set to to 'executable' and root ownership:
chmod 700 ./check_ip.py
chown root ./check_ip.py

7. Add a Cron Job to restart SSL


Add it to our cron job:

crontab -e
Add these lines to the end of the file:
# restart openssl daily at 5:10pm : 10 17
10 17 * * * /root/check_ip.py -s > /root/cron.log 2>&1

Press Ctrl+X and Y to save and exit.

8. Run the Script & Restart the RPi


Now we need to run the check_ip.py script so that it can make
UPnP Port Mapping changes and verify the configuration. This
should not restart your RPi unless its IP address has changed:

./check_ip.py
If you do not receive any emailed error messages, we can proceed
with restarting your RPi to enable OpenVPN over SSL:

./check_ip.py -r
We're done with the RPi set up. Now we need to makes changes to
the Android and Windows clients

Configuring Android Clients for OpenVPN over


SSL
We need a new APP on our Android device. I recommend
SSLDroid. It's what I will be providing instructions for. Other APPs
may work just as well, or better, but I have not tested them and
cannot help debug them if there are issues.
From the Google Play store, find SSLDroid by Balint Kovacs and
download and install it.
Note: If you cannot access the Google Play store, you may be
able to find it on the web download the apk from there. Just
make sure its by Balint Kovacs.
First run your Android Open VPN Client, OpenVPN for Android:
1. Click on the Edit icon next to your Profile name
2. Select the SERVER LIST tab
3. Write down the Server Address and then change it to:
localhost
4. Change Server Port to: 1194
5. Change Protocol to: TCP
6. Select the ADVANCED tab (scroll/drag the tabs to the left)
7. Scroll down to Custom Options and select it.
8. Add the following to line to end of the list:
route 000.000.000.000 255.255.255.255 net_gateway
And replace the 000.000.000.000 with the External IP address
of your RPi (from step 3 above)

9. Click OK
10. Now click on the ALLOWED APPS tab
11. Find SSLDroid and check the box next to it
This excludes its data from being processed by OpenVPN for
Android
12. Click the Android Back button repeatedly to back out of
the OpenVPN for Android app.
Note: you will only need to do steps 10 & 11 for existing
OpenVPN client certificates. Any new client certificates you
create on your RPi will have these options already set from
step 5 of the previous section: Setting up your RPI for
OpenVPN over SSL
Now run SSLDroid and:
1. From its app menu, select Add Tunnel
2. Give it a meaningful Tunnel name, like the RPi Server it will
connect to.
3. Set Local Port to: 1194
4. Set Remote Host to the External IP address of your RPi (from
Step 3 of OpenVPN for Android changes above)
5. Set the Remote Port to: 443
6. Leave all other fields blank and click Apply
We are done setting up your Android Device!
To test, disable Wifi mode on your Android so we access your
network and RPi externally from the Internet, then:
1. Run SSLDroid and from its App menu select Start Service.
Its little green icon should appear in the Notification Bar
2. Exit SSLDroid. The icon should remain in the Notification Bar.
3. Run OpenVPN for Android and click on your profile to run it.
You should see it connect to your RPI just as before but using
IP address 127.0.0.1 (localhost) and port 1194
Note: Now, every time you wish to connect to your RPI, you will
need to repeat those above three steps. And you can only
connect using OpenVPN over SSL. Straight OpenVPN will no
longer work (as we covered at the beginning of this Appendix).
If you are unable to connect, please review all the steps in this
chapter to ensure it is all set up correctly. Also refer to the
Troubleshooting Appendix in the book and on the supporting web
site: http://bitman.org/irafinch/rpivpn

Configuring Windows Clients for OpenVPN over


SSL
For Windows PCs, we need a new application as well. I use, and
recommend, stunnel by Michal Trojnara. You can get this from his
homepage at: https://www.stunnel.org
Click on the Downloads link on the left and select the stunnel-x.xx-
installer.exe link (where x.xx is the latest version of his software).
Download and install it.
First we need to change the OpenVPN GUI Configuration:
1. Run OpenVPN GUI and right-mouse click on its icon in the
System Tray
2. Mouse over the configuration you want to change and select
Edit Config
3. Write down IP address given on the Remote line and then
change it to:
localhost 1194
4. Change the proto line to: proto tcp
5. Scroll to the bottom of the file and add this line:
route 000.000.000.000 255.255.255.255 net_gateway
And replace the 000.000.000.000 with the External IP address
of your RPi (from step 3 above)
6. File Save and Exit
Note: You will only need to do the above steps for existing
OpenVPN client certificates. Any new client certificates you
create on your RPi will have these options already set from
step 5 of the previous section: Setting up your RPI for
OpenVPN over SSL

Now run stunnel and:


1. Right-mouse click on its Icon in the System Tray
2. Select Edit Configuation
3. Add these 4 lines to the end of the file:
[ServerName]
client = yes
accept = 127.0.0.1:1194
connect = 000.000.000.000:443
Where ServerName is the Name of your RPI OpenVPN/SSL
Server, and 000.000.000.000 is its external IP Address.

4. File Save and Exit


We are done setting up the Windows Client!
To test, you'll need to take your Windows PC to a remote location so
we can connect to to your RPi over the internet. Then:
1. Run stunnel
2. Run OpenVPN GUI
3. Right-click on the OpenVPN Icon and mouse-over the
configuration you want to use and select Connect
You should see it connect to your RPI just as before but using
IP address 127.0.0.1 (localhost) and port 1194
Note: Now, every time you with to connect to your RPI, you will
need to repeat those above three steps. And you can only
connect using OpenVPN over SSL. Straight OpenVPN will no
longer work (as we covered at the beginning of this Appendix).
If you are unable to connect, please review all the steps in this
chapter to ensure it is all set up correctly. Also refer to the
Troubleshooting Appendix in the book and on the supporting web
site: http://bitman.org/irafinch/rpivpn
APPENDIX F – Tor (anonymity network)
This Appendix applies only after you have built your RPi VPN Server
and have it running successfully. You do not need be using SSL or
have it enabled to use Tor, but it doesn’t hurt either.
Note: If you do not know what Tor is, stop right now and read
this Wikipedia article first to decide if you want to go down this
rabbit hole:
https://en.wikipedia.org/wiki/Tor_(anonymity_network)
Still here? Excellent. Lets get started.
What we will build here is a Tor Router on top of our VPN Server - all
on our single Raspberry Pi. This will encrypt your data between your
Android/Windows devices and the RPi through OpenVPN, and then
further encrypt and anonymize your activity by passing your data
through the Tor network. Thus making it extremely difficult for
anyone to eavesdrop on your activities or steal your data/identity. No
changes need to be made on your Android/Windows devices. It will
all be transparent to them.
There are limitations, and this is just one part to protecting yourself
and your identity on the Internet. Refer to the Wikipedia article above
for its limitations – if you haven’t already.
To start, enter these 4 command to update/upgrade your Raspbian
OS and install Tor:

sudo -s
apt-get update
apt-get upgrade
apt-get install tor
Next step it to edit the Tor configuration file, torrc:

nano /etc/tor/torrc
Copy/Paste the following lines at the top of the torrc file:
Log notice file /var/log/tor/notices.log
VirtualAddrNetworkIPv4 10.192.0.0/16
TransPort 9040
TransListenAddress 10.8.0.1
DNSPort 9053
DNSListenAddress 10.8.0.1
AutomapHostsOnResolve 1

Or download the script from here: http://bitman.org/irafinch/rpi-


vpn.zip
Press Ctrl+X and Y to save and exit.
The Tor virtual network is on 10.192.x.x while it will listen for data on
the 10.8.x.x network. Note that this ‘listening’ network is the same
one OpenVPN uses for its virtual network – that’s how we will tie
them together. You’ll see that next...
Now we need to modify the OpenVPN server.conf file to allow Tor to
interface with it. Enter:

nano /etc/openvpn/server.conf
Now comment out these 6 lines by placing a # character in front of
them, as shown:
Note: The local, last route and dhcp-option IP addresses will
be different depending on your network. They are your
Raspberry PI’s IP address for the local and last route and your
Router’s IP address on the dhcp-option.
# local 192.168.3.50
# ifconfig 10.8.0.1 10.8.0.2
# push "route 10.8.0.1 255.255.255.255"
# push "route 10.8.0.0 255.255.255.0"
# push "route 192.168.3.50 255.255.255.0"
# push "dhcp-option DNS 192.168.3.1"

Then we need to change this line:


push "redirect-gateway def1"
To look like this:
push "redirect-gateway def1 bypass-dhcp"
Press Ctrl+X and Y to save and exit.
There is still the server 10.8.0.0 255.255.255.0 line in the
server.conf file. That’s the same network that Tor will listen on, tying
the two services together.
The /root/open_vpn_firewall.sh script is no longer useful as we’ll be
replacing it with a much larger, more complex, one. So lets, just
disable it. Enter:

crontab -e
And comment out @reboot command by placing a # character in
front of it:
# @reboot /root/open_vpn_firewall.sh &

Press Ctrl+X and Y to save and exit.


For our new iptables rules, we’ll put this file in the /root folder to
make it easier to find and manager. We’re also going to give it a new
name:

nano /root/iptables_rules.sh
Copy/Paste the following lines into the empty nano editor window:
#!/bin/bash

sleep 30
Adapter=`ip -o link show | awk '{print $2,$9}' | grep 'UP'| awk -F: '{print $1}'`
if [ -z "$Adapter" ]
then
Adapter='eth0'
fi
echo "Adapter = |$Adapter|"

# Clear iptables
iptables -F
iptables -t nat -F
iptables -X
# Accept Established, Related connections
iptables -A INPUT -i $Adapter -m state --state ESTABLISHED,RELATED -j
ACCEPT
iptables -A OUTPUT -o $Adapter -m state --state ESTABLISHED,RELATED -j
ACCEPT
iptables -A INPUT -i tun0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -o tun0 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i tun0 -o lo -m state --state ESTABLISHED,RELATED -j
ACCEPT
iptables -A FORWARD -i tun0 -o lo -j ACCEPT
iptables -A FORWARD -i lo -o tun0 -m state --state ESTABLISHED,RELATED -j
ACCEPT
iptables -A FORWARD -i lo -o tun0 -j ACCEPT

# Accept localhostloop
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# Accept SSH
iptables -A INPUT -i $Adapter -p tcp -m tcp --dport 22 -j ACCEPT

# Accept Tor Ports


iptables -A INPUT -i $Adapter -p tcp -m tcp -m multiport --dports 9001,9030 -j
ACCEPT

# Accept OpenVPN
iptables -A INPUT -i $Adapter -p udp -m udp --dport 1194 -j ACCEPT
iptables -A INPUT -i tun0 -s 10.8.0.0/24 -p udp -m udp --dport 123 -j ACCEPT
iptables -A INPUT -i tun0 -s 10.8.0.0/24 -p udp -m udp --dport 53 -j ACCEPT
iptables -A INPUT -i tun0 -s 10.8.0.0/24 -p tcp -m tcp -j ACCEPT

# Tor Transparent Proxy


iptables -t nat -A OUTPUT -o tun0 -j RETURN
iptables -t nat -A PREROUTING -i tun0 -p udp -m udp --dport 123 -j REDIRECT --
to-ports 123
iptables -t nat -A PREROUTING -i tun0 -p udp --dport 53 -j REDIRECT --to-ports
9053
iptables -t nat -A PREROUTING -i tun0 -p tcp --syn -j REDIRECT --to-ports 9040
iptables -t nat -A OUTPUT -o lo -j RETURN
iptables -t nat -A OUTPUT -m owner --uid-owner "debian-tor" -j RETURN
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m owner --uid-owner "debian-tor" -j ACCEPT
for NET in 127.0.0.0/8; do
iptables -A OUTPUT -d $NET -j ACCEPT
done
iptables -A OUTPUT -p udp -m udp --dport 123 -j ACCEPT
Or download the script from here: http://bitman.org/irafinch/rpi-
vpn.zip
Press Ctrl+X and Y to save and exit.
Set the script to Executable and Root owner with these 2
commands:

chmod 700 /root/iptables_rules.sh


chown root /root/iptables_rules.sh
Now we need to add this to our rc.local to execute at boot:
nano /etc/rc.local
And paste these lines near the bottom of the file just before the exit
0 line:
# Open the Firewall for Tor at Boot
/root/iptables_rules.sh &
Press Ctrl+X and Y to save and exit.
This last part is a bit kludgy as I have yet to find a better way to do it.
Basically Tor and OpenVPN where meant to run on independent
servers if you want them to talk to each other. That’s one reason
iptables_rules.sh is so large and complex. But now that they are tied
together, Tor must start after OpenVPN is up and running, otherwise
it won’t find that 10.8.x.x virtual network OpenVPN creates, and thus
fail.
Ideally, we would set Tor to be dependent OpenVPN by adding
openvpn.service to the tor.service file on the After= line. But that
just kills Tor on start up.
Until such time as I find a better way to do this, we’re stuck with this:

update-rc.d tor disable


This disables Tor from starting automatically when the RPi boots.
Otherwise it will just fail.
Now, create a start up script for Tor:

nano /root/tor_startup.sh
Copy/Paste the following 3 lines into the empty nano window:
#!/bin/sh
sleep 30
/usr/sbin/service tor start
Press Ctrl+X and Y to save and exit.
Set the script to Executable and Root owner with these 2
commands:

chmod 700 /root/tor_startup.sh


chown root /root/tor_startup.sh
Now we will add this script to crontab so that it will run when our RPi
starts up:

crontab -e
And paste these lines at the bottom of the file:
# Start Tor after Boot
@reboot /root/tor_startup.sh &
Press Ctrl+X and Y to save and exit.
Note: Don’t forget the & on the end. It tells Raspbian to run that
script but don’t wait for it to finish, just keep going. Otherwise
we may end up waiting 30 seconds for your RPi to boot.
This script will wait 30 seconds after the RPi boots and then start the
Tor service. By that time, everything (including OpenVPN), should be
up and running and ready.
Now just reboot your Pi, wait 30 seconds for Tor to initialize, then try
connecting to it via OpenVPN from outside your network. Once
connected, browse to any of these web sites to see what your public
IP address is now. It should be different that your actual one if Tor is
working properly:
http://whatsmyip.co
http://icanhazip.com
If you try google.com, you may even get a different
language/country version!
If you run into any problems and it does not appear to be working
properly:

Review/repeat the steps in this Appendix


Examine the tor log file: cat /var/log/tor/notices.log
Examine the openvpn log file: cat /var/log/openvpn.log
Check the Help / Troubleshooting page on my web site:
http://bitman.org/irafinch/rpivpn
Contact me via my email address: irafinch888@bitman.org

You might also like