Raspberry Pi VPN Travel Router

I. Introduction


Functionalities that even a simple consumer device has may entail the use of the internet as mobile.
OS platforms move to cloud-based services for photo-sharing facilities, and messaging, Such loss control activities include video playback, etc. On the same note, the expansion of mobile data networks has enabled always It is in these “always on” connections for such devices, that overall users are surging through data at an unpredicted rate. Mobile carriers have therefore adjusted by bundling data in packages or slabs that usually come in gigabytes. moving away from unlimited data plans. In this regard, users delegate the reliance on Wi-Fi connections, especially available to save their allocated data since they are scarce.

Public wireless hotspots particularly at the local business places may not be established or managed by networking professionals. This can cause severe security problems like no isolation of the various components, that are used between clients, raising the possibility of launching man-in-the-middle attacks. Unrestricted access to the it is possible that through the router and access point’s device administration page an attacker could easily forcibly initiate connections with clients to genuine as well as fake as well as malicious websites.

 

Organizations have always insisted that workers use a VPN to connect to the internal network of the firm. However, the generic concept of benefits is also good for persons who wish to enhance security, overcome geographic restrictions or censorship, or remain anonymous while using the Internet. If for instance, it is a user intending to link multiple devices, this can be quite tiring and time receding as with software VPN turn clients differ from one another and from the operating systems they support whether it is Windows, Mac, or the mobile ones. Besides, some connections and disconnections need to be made once the software is installed and these are the VPNs for each device.


The Raspberry Pi is portable and can easily be taken along when traveling and uses normal electricity. amazingly just the micro-USB charger, makes it easier to carry while traveling as compared to the complicated wires. To connect the Pi to Users have the chance to set a public Wi-Fi and expand the device(s) to the cellular Bluetooth of the Pi simultaneously to discharge the requirement of any sort of wired networking at all. Where only the wired internet connection is possible then the following points have to be considered:
which is also currently available on the Pi it also features an Ethernet port. Connection information and configuration already done could be manipulated like a consumer’s home router through a website interface or screens.

Thus, by having an easily accessible VPN connection, users can protect an increasing number of mobile systems when using public access points such as wireless LANs, Wi-Fi, or other wireless networks. Since all the traffic is rerouted and subsequently encrypted the traffic passes through the VPN connection before it is sent out on the internet, the flow of eavesdropping or man-in-the-middle attacks is minimized. Besides, one could also avoid the web filtering. blocking or slowing that may be against the principles of net neutrality.

II. Requirements

The Pi must allow the final user to connect their device(s) to a safe wireless network. A network that directs all traffic through a tunnel that is encrypted. It must provide support for connectivity. several devices. Moreover, these gadgets are capable of operating on any OS, including mobile systems. on a computer or laptop, as long as they are capable of connecting to a WPA2-secured wireless network. connection via ethernet. There is no extra client required in modern software VPN solutions, unlike the traditional ones.

software needed for user devices to establish a connection. The user should be able to choose between a wired or wireless internet connection for the Pi based on availability. One instance is that coffee shops typically offer WiFi but seldom provide customers with the option to connect using a wired ethernet connection. In certain situations, a location might provide only a wired internet connection, although this is becoming less common.

 

However, the Pi must be able to support both internet connectivity methods. Once connected to the secure wireless hotspot, users can access a web configuration page to select a public wireless network. It should provide them with essential connection details, display the wireless networks accessible, and enable them to join encrypted and unencrypted public networks. Once the Pi has internet access, users should have the ability to link their devices.

extra setup beyond what is typically needed to connect to the internet. The mathematical constant Pi will feature a secure wireless hotspot that looks identical to one created by a router for personal use by a customer. The user does not have to adjust any additional network configurations. rather than just inputting the WPA2 password during connection.

Once a user’s device is linked to the Pi’s Wi-Fi hotspot, they should be able to access the internet right away. They ought to have the capability to utilize any application in the usual manner. There is no indication that the connection is going through a VPN.

III. Use Cases

Public WiFi hotspots have become widely available for consumer use across various locations like restaurants and laundromats. Today, people often rely on these hotspots to keep their devices constantly connected online as they expect constant internet access. The Raspberry Pi can enable a secure connection to such hotspots for those seeking a private online experience.

While less common now, some public places like hotels may only provide wired internet access. Both wired and wireless could be options, but the wired connection performs better than a potentially weak wireless signal. This could prevent mobile devices like tablets and phones from accessing the internet since they typically don’t support wired ethernet. However, the Raspberry Pi could connect to the provided ethernet port to get online, and then broadcast a secure wireless hotspot for those mobile devices to utilize.

Public networks may filter certain sites or categories, blocking access. They could also prevent specific protocols often used by torrenting or email clients. Even if sites or protocols aren’t outright blocked, some traffic types may face throttling or prioritization. Assuming the Pi establishes a VPN tunnel, these restrictions could be bypassed. The network would only see VPN traffic and couldn’t prioritize or discriminate specific user services.

VPN traffic routed through the Pi enjoys strong encryption, potentially preventing network adversaries from spying on or intercepting user internet activity. While HTTPS-enabled websites generally allow safe use on public networks, not all sites use HTTPS by default or at all. Plus, some device apps may make insecure web requests without notifying the user, like an email client downloading mail in cleartext. The Pi routes all this traffic securely through a VPN tunnel, removing worries about interception for the user.

IV. Design

A. High-Level Design

Goals

This project aims to develop a secure VPN solution for end users in a compact, straightforward package. The device needs to be lightweight and portable as it will be used while traveling, not requiring a bulky power adapter. However, it must still have enough processing power to run a complete Linux system and function as a network router for multiple devices simultaneously. Minimizing hardware costs is important too, while open-source software keeps development costs at zero. Security serves as a chief motivator as well, only strong encryption can sufficiently safeguard user data passing through the device. The overall goal is to empower users with private, protected connectivity anywhere in a small, energy-efficient design.

Hardware Equipment Required

The key piece of hardware in my design is the Raspberry Pi 2 Model B. This small $35 computer is produced by the Raspberry Pi Foundation. It replaced the original Pi 1 with a faster quad-core processor and 1GB of RAM. Even though the Pi 2 was recently released at that time, I opted for it given the major performance improvements over the Pi 1. Specifically, my project requires the Pi to function as a full wireless and wired router while also handling the overhead of VPN-encrypted traffic. I knew the single-core CPU in the Pi 1 risked bottlenecking performance.

The Raspberry Pi has 4 USB ports, an Ethernet port, an HDMI port for video output, and a Micro SD card slot. It requires a 5V Micro USB power supply like most non-Apple phones use. I bought a dedicated 24W Anker dual USB wall charger for the Pi and used a portable USB power bank for mobility. For storage, I purchased a 16GB MicroSDHC Class 10 card for the operating system to boot from. 16GB provides ample space for the OS and configuration data.

The Pi 2 lacks built-in wireless, so USB adapters are needed – one to connect to public networks, and another to create a private wireless access point. I chose the Edimax EW-7811Un given its Pi compatibility and driver support for hosting an access point. For wired Ethernet, the built-in 10/100 port is used. One remaining USB port connects a keyboard, and an external display plugs into the HDMI port.

Software Requirements

The Raspberry Pi primarily uses Linux-based operating systems, though Windows 10 now offers an embedded version. The Raspberry Pi Foundation provides an installer called NOOBS to select several pre-installed Linux distributions. I chose Raspbian, the Debian-derived OS officially supported for Raspberry Pi. Raspbian optimizes Raspberry Pi hardware, and most guides/tutorials about Pi projects use it. The OS also provides tools to easily configure Raspberry Pi settings.

For VPN connectivity, I used the hosted VPN service VyperVPN to establish an OpenVPN connection from the Pi to the internet. OpenVPN offers better security than PPTP and faster performance than L2TP/IPsec. This requires installing OpenVPN client software on the Pi.

As mentioned, one wireless adapter hosts a private WiFi network for user devices to connect to. This necessitates creating a virtual software-based wireless access point. I used Hostapd, a Linux user space daemon for access points and authentication. A customized Hostapd package included the driver needed for the Edimax adapters in this project.

The Pi also runs a small web server displaying network statistics like the current VPN IP address. I used Flask, a lightweight Python web framework. When users connect to the Pi, they can access this webpage to view the information.

B. Lower Level Design

Operating System Configuration

The Raspbian OS will boot from the 16GB MicroSD card installed in the Raspberry Pi. A password will be set for the default Pi user account. The operating system will run without a full graphical user interface (GUI) or window manager, showing only a terminal console when connecting the Pi to an external display. All necessary project configurations and additions will be made through command-line interfaces. Required packages will be installed using apt-get unless a specific version other than what’s in the default repositories is needed. That ensures the operating system has everything needed to support the goals of this project from initial configuration to ongoing management purely via text-based interaction.

OpenVPN Configuration

VyperVPN, the hosted VPN provider selected, supports the OpenVPN protocol used in this project. VyperVPN manages their software, infrastructure, and servers to anonymously route users’ VPN connections on the web. I downloaded VyperVPN’s root certificate, used to authenticate the server during connection establishment, and a pre-configured .ovpn file specifying how to connect to a remote OpenVPN server. Most settings in this file were left as defaults, including AES-256-CBC for encrypting packets and SHA256 for authentication. Allowed OpenSSL TLS cipher suites, securing the control channel and key exchange, are DHE-RSAAES256-SHA, DHE-DSS-AES256-SHA, and AES256-SHA. I added VyperVPN’s username and password for OpenVPN authentication.

Upon connecting, OpenVPN creates a virtual TUN network adapter called tun0 and obtains an IP address for it from VyperVPN’s DHCP server. This VPN interface routes the user’s internet traffic through VyperVPN’s encrypted tunnel in a plug-and-play manner defined by the configuration file and default security parameters.

Access Point Configuration

The Pi needs to host a wireless access point (WAP) for users to connect to like any other wireless router. Hostapd provides this capability but the standard version lacks support for the specific Edimax USB wireless adapters used here with RTL8188CUS chipsets. A custom Hostapd build with this chipset support is available online and required. I compiled and installed this version on the Pi.

The Hostapd configuration was then modified. The WAP interface was set to wlan0, SSID to “securepinetwork”, WPA2 password “tester123”, channel 1, and chipset-specific hardware settings. Hostapd was started and configured to launch on boot.

Connecting clients should now receive an IP, gateway, and DNS servers. The Dnsmasq package provides DHCP and DNS services available on most Linux distributions. After installing Dnsmasq, its configuration assigned these roles and added them to the system startup. This way, associated clients get full network access through the Pi’s wireless access point.

Network Interface Configuration

The Pi will always have a minimum of three active interfaces: the virtual VPN adapter,
wired/wireless uplink, and secure wireless hotspot.

Tun0: The virtual VPN adapter, receives an IP and gateway via DHCP from VyperVPN.
Anything connecting through this interface gets routed to the internet through a secure VPN
tunnel.
Eth0: Wired uplink interface, receives an IP and gateway via DHCP from the public network.
This provides the Pi with an internet uplink, which it needs to establish a VPN connection to
VyperVPN’s servers.
Wlan0: Wireless hotspot interface, IP is statically set to 192.168.10.1. This represents the
gateway interface used by devices connecting to the secure wireless hotspot.
Wlan1: Wireless uplink interface, receives an IP and gateway via DHCP from the public
network. This provides the Pi with an internet uplink, which it needs to establish a VPN
connection to VyperVPN’s servers.

Firewall/Routing Configuration

The Pi must be configured to route packets across each interface appropriately. To enable this, IP forwarding must be activated in the Linux kernel.

Additionally, iptables packet filtering rules are required. Since the Pi functions as an internet router, Network Address Translation (NAT) should be enabled on the VPN and uplink interfaces: tun0, eth0, and wlan1. This permits translating IP addresses of packets moving from the internal private network to the external public one correctly. Iptables should forward new packets from the private internal network wlan0 through the VPN interface tun0 and returning traffic from tun0 back to wlan0. This permits clients on the private network to access the public internet while blocking unsolicited public internet traffic from reaching the private network.

Figure 3: Software Design Configuration

Figure 4A: Tracing a request from secure hotspot client to internet

Figure 4B: Tracing reply from internet back to secure hotspot client

Web server configuration

A small web server runs on the Pi, accessible only to clients on the secure private network. It hosts a configuration/statistics page displaying network connection details. Flask, a Python web framework, runs it. For isolation, Flask is installed within a virtualenv, keeping the project environment (Python version, libraries etc.) separate. During development/testing, the server binds to all interfaces with debugging enabled.

Flask maps functions to URLs. The /config route serves the configuration page. Users access it by typing the Pi’s IP address, web server port, and /config, like ‘192.168.10.1:5000/config’.

A single Python script contains functions retrieving network interface data from Linux using imported modules. It returns this data in a usable format.

The page is rendered from an HTML template referencing variables passed from the Flask application. When called, render_template displays the template along with variables like public/VPN IPs and visible public wireless networks. Placeholders in the template populate with these values. Available encrypted public networks list along with password fields.

Web server usage

Connecting to an encrypted wireless network requires entering its password in the associated form field. Unencrypted networks omit a password field.

Selecting “connect” submits a POST request back to the application with the selected network and password. These details are written to wpa_supplicant’s configuration file. Wpa_supplicant reloads, initiating a DHCP request on the new network.

Once connected, OpenVPN restarts to reestablish the VPN tunnel securing the private network.

Users can also power down the Pi by selecting the “Power off” button at the bottom of the configuration page. This shuts the system down via the web interface for convenient remote management.

Figure 5: Web Configuration Page

V. Implementation

A. Physical Assembly

For setup, the Raspberry Pi connects to its Anker wall charger power source using a Micro USB cable. Both Edimax wireless adapters plug into USB ports on the Pi. The MicroSD card inserts into the opposite slot. During testing and development, a USB keyboard and HDMI cable provide physical console access by connecting to the Pi as well.

This readies the necessary hardware components and interfaces to carry out configuration, installation of software packages, and validation that all elements function as intended before deployment.

B. Software Configuration

Operating System Installation

The NOOBS installer installs Raspbian. It can be downloaded from its URL.

I used a MicroSD adapter so the 16GB MicroSD card could be inserted into my Windows laptop’s SD card reader. Once visible, I extracted the previously downloaded NOOBS folder to the card.

Removing the MicroSD from the laptop, I inserted it into the Raspberry Pi along with a connected keyboard and HDMI display. Powering on, the Pi boots to a list of installable operating systems. I selected Raspbian to begin installing.

Upon completion, the raspi-config page loaded where I changed the user password and set the region to the US and timezone to PST. I also chose the “command line” boot environment since a desktop GUI isn’t needed. Selecting “Finish” opens the Raspbian terminal.

Most implementation commands require root privileges and will need to be prefixed with sudo. This readies the OS installation for configuring the security router functionality.

I installed Vim for use in editing configuration files:

$ apt-get install vim

Initial connection to an internet uplink

Initial connection to an Internet uplink Connecting to the Internet via ethernet simply involves connecting an ethernet cable to the port on the Pi. The Pi will detect the connection and acquire a public IP address via DHCP. Connecting via WiFi for the first time involves modifications to /etc/network/interfaces and
/etc/wpa_supplicant/wpa_supplicant.conf:

$ vim /etc/network/interfaces

Wlan1 will be the interface used for connecting to a public wireless uplink and should have the
following:

wlan1

auto wlan1
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
We then edit /etc/wpa_supplicant/wpa_supplicant.conf to specify a wireless network for
wpa_supplicant to connect to:
$ vim /etc/wpa_supplicant/wpa_supplicant.conf
Finally, we can restart networking
$ service networking restart
OpenVPN Setup

  1. Download and install the OpenVPN package:
    $ apt-get install openvpn
  2. Download the OpenVPN configuration package from VyperVPN:
    22
    https://support.goldenfrog.com/hc/enus/article_attachments/205311978/VyprVPNOpenVPNFiles.zip
  3. Extract the zip and save the .ovpn file (I chose the USA – Los Angeles.ovpn file based on
    location) to /etc/openvpn/client.conf
  4. Create a login file under /etc/openvpn, with the first line containing the VyperVPN user
    and second line the password. This allows OpenVPN to login automatically without
    prompting for credentials
    $ vim /etc/openvpn/login.txt

  5. Edit /etc/openvpn/client.conf, find the line containing “auth-user-pass” and append
    “login.txt” to the end of the line:
    $ vim /etc/openvpn/client.conf
    auth-user-pass login.txt
  6. Enable the NTP service to ensure the Pi has a matching timestamp for OpenVPN:
    $ service ntp start
    $ update-rc.d ntp enable
  7. Start OpenVPN as a service and enable startup when the Pi boots:
    $ service openvpn start
    $ update-rc.d openvpn enable
  8. The Pi should now establish a VPN connection using the supplied OpenVPN connection.
    It will be accessible on the tun0 interface

Secure Access Point Setup- Hostapd
Download, extract, and install the custom version of Hostapd with driver support for the Edimax
wireless cards:
$ wget https://github.com/jenssegers/RTL8188-
hostapd/archive/v1.1.tar.gz
$ tar -zxvf v1.1.tar.gz
$ cd RTL8188-hostapd-1.1/hostapd
$ make
$ make install
Edit the Hostapd configuration to contain the following:
$ vim /etc/hostapd/hostapd.conf

Basic configuration

interface=wlan0
ssid=securepinetwork
channel=1

bridge=br0

WPA and WPA2 configuration

macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=3
wpa_passphrase=tester123
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP

Hardware configuration

driver=rtl871xdrv
ieee80211n=1
hw_mode=g
device_name=RTL8192CU
manufacturer=Realtek
Start the Hostapd service and enable startup when the Pi boots:
$ service hostapd start
$ update-rc.d hostapd enable
Secure Access Point Setup-DHCP/DNS
Install DNSmasq:
$ apt-get install dnsmasq
Edit the configuration to set DHCP options. The DHCP server should serve addresses from
192.168.10.10-192.168.10.200. It should push DHCP options for the gateway/router,
192.168.10.1 (the Pi itself) and DNS server, also 192.168.10.1.
$ vim /etc/hostapd/hostapd.conf
interface=wlan0 #wlan0 is our adapter for the hotspot
dhcp-range=wlan0,192.168.10.10,192.168.10.200,2h
dhcp-option=3,192.168.10.1 #router
dhcp-option=6,192.168.10.1 #dns server
dhcp-authoritative #make clients grab a new IP
We will actually start the DHCP server in the next section after the network interfaces are
probably configured first

Network Interface Setup
I configured the interfaces configuration file with the following:
$ vim /etc/network/interfaces

Web Server Setup
First, install Python and Virtualenv:
$ apt-get install python-dev
$ apt-get install python-virtualenv
Create a Python virtual environment for Flask to use (we’ll call “wiconfig”) and activate it:
$ cd /home/pi
$ virtualenv wiconfig
$ . wiconfig/bin/activate

Now install Flask inside the virtual environment:
$ pip install Flask
We can create the folder structure, with “app” containing the application itself:
$ cd wiconfig
$ mkdir app
$ mkdir app/static
$ mkdir app/templates
Next, create an initialization script for the “app” package:
$ vim app/init.py
from flask import Flask
app = Flask(name)
from app import views
This will create the application object and import the “views” module. The views model
responds to requests from clients accessing the web server (e.g. web browsers). Our view
function maps to a single request URL, the default root directory. It should be saved as views.py:
$ vim app/views.py

Finally, we create a script that starts our web server with the application, run.py:
$ vim run.py

!flask/bin/python

from app import app
app.debug = True
app.run(host=’0.0.0.0′)
So, our directory structure is as follows:
|—-wiconfig/
|——–app/
|————static/
|————templates/
|————init.py
|————views.py
|——–bin/
|——–include/
|——–lib/
|——–local/
We can start the server by executing run.py from the command line. The webpage itself can then
be accessed at http://192.168.10.1:5000/config when connected to the secure wireless hotspot.

VI. Results/Conclusions

I successfully followed my planned design, enabling clients to connect to a secure wireless hotspot routing all traffic through VyperVPN’s servers via an OpenVPN tunnel. The Pi supports either a public wired or wireless internet uplink. Configuring a wireless uplink required more implementation work for the web configuration page, as it must provide a preferred SSID and password for the Pi. Without this page, users connecting to the secure hotspot have no way to specify the wireless network.

Client performance connecting to the secure hotspot is generally consistent. Connections form quickly and internet access loads rapidly. Its range is less than a traditional router with higher power transmission but sufficient for intended short-range use. Download speeds are noticeably reduced versus direct public network connections, likely due to encryption overhead, hardware limitations, and using wireless for both uplink and hotspot. A more powerful system like the Raspberry Pi 3 may improve performance, though the Pi showed minimal CPU load during testing.

Early issues involved the Pi’s power source. A cheap phone charger occasionally caused errors referencing power in the OS console, sometimes temporarily corrupting the file system and preventing booting. Running fsck fixed this by repairing the MicroSD. I attributed this to the USB wireless adapters and keyboard drawing significant power over the USB bus. A higher-quality charger/cable remedied reliability problems. Alternately, using a powered USB hub could isolate devices from the Pi’s USB bus.

My original plan enabled ethernet or wireless client connection, but I opted only for wireless hotspot access. Nearly all modern devices support wireless, while performance impacts are small. Ethernet would introduce more configuration complexity versus the simplified wireless approach.

VI. Next Steps

Public networks like hotels often require accepting a captive portal before internet access. This prevents VPN establishment, temporarily exposing the client. For the Pi, captive portals could block the secure hotspot until the user accepts. One solution is MAC address cloning – having the Pi and client share an address so both authenticate after the user accepts.

Further development could enhance the VPN configuration page. Adding details like connected client counts and history assists in troubleshooting connectivity. Support for WPA-Enterprise networks like Cal Poly’s Mustang Wireless would expand compatibility. The page could store preferences for multiple wireless networks, adding or removing between uses.

Much testing occurred without security measures for public use. Additional precautions are needed. The web server should disable debugging, firewall public access, and migrate from Flask’s built-in server to production-grade Apache or NGINX. Form input on the configuration page requires validation and sanitization.

Performance may improve using a more powerful device than the Raspberry Pi for stronger wireless and throughput. However, this reduces portability advantages when traveling.

Appendix A. Iptables Rules

*nat
:PREROUTING ACCEPT [82:6649]
:INPUT ACCEPT [21:1600]
:OUTPUT ACCEPT [40:2782]
:POSTROUTING ACCEPT [6:426]
-A POSTROUTING -o eth0 -m comment -j MASQUERADE
-A POSTROUTING -o wlan1 -m comment -j MASQUERADE
-A POSTROUTING -o tun0 -m comment -j MASQUERADE
COMMIT

Completed on Wed Oct 28 20:26:49 2015

Generated by iptables-save v1.4.14 on Wed Oct 28 20:26:49 2015

*filter
:INPUT ACCEPT [981:687162]
:FORWARD ACCEPT [1669:717210]
:OUTPUT ACCEPT [939:205723]
-A FORWARD -s 192.168.10.0/24 -i wlan0 -o tun0 -m comment –comment
“Allow only traffic from clients to tun0” -j ACCEPT
-A FORWARD -i tun0 -o wlan0 -m conntrack –ctstate ESTABLISHED,RELATED
-m comment –comment “Allow only traffic from clients to tun0” -j
ACCEPT
-P FORWARD DROP
COMMIT

Appendix B. Web configuration page source

Views.py (main application)

from future import print_function
from app import app
from flask import Flask, render_template, request, redirect, url_for
import socket
import subprocess
import sys
import os
import netifaces
import wifi
from wifi import Cell,Scheme
@app.route(‘/config’, methods=[‘GET’, ‘POST’])
def config():
REMOTE_SERVER = “www.google.com”
# adjust for what’s the internet interface
# check if eth0 is active, otherwise default to wireless. get IP if active.
try:
addrs = netifaces.ifaddresses(‘eth0’)
myip = addrs[netifaces.AF_INET][0]
myrealip= myip[‘addr’] + ” (connected via ethernet)”
except:
myrealip=”N/A”

# check to see if wlan1 is active, get IP if active
try:
addrs = netifaces.ifaddresses(‘wlan1’)
myip = addrs[netifaces.AF_INET][0]
myrealip= myip[‘addr’] + ” (connected via wireless)”
except:
myrealip=”N/A”

# check to see if tun0 (vpn) is active, get IP if active
try:
vpn_addrs = netifaces.ifaddresses(‘tun0’)
myvpnip = vpn_addrs[netifaces.AF_INET][0]
myvpnrealip= myvpnip[‘addr’]
except:
myvpnrealip=”N/A”
try:
# check to see if we can resolve hostname
host = socket.gethostbyname(REMOTE_SERVER)
# connect to the host – can we actually reach it?
s = socket.create_connection((host, 80), 2)
connected=”Connected”

except:
connected=”Not Connected”

#get available wireless networks
networks = Cell.all(‘wlan1’)
results = {}
# form to get ssid/password and connect
select_ssid = “N/A”

select_password = “password”
# get current SSID from wpa_supplicant service
wpa_process = subprocess.Popen(“wpa_cli status | grep ^ssid”, shell=True,
stdout=subprocess.PIPE)
stdout_wpa_process = wpa_process.communicate()[0].split(‘\n’)[0]
print(stdout_wpa_process[5:], file=sys.stderr)
current_ssid = stdout_wpa_process[5:]
if request.method == “POST”:
try:
# check to see if power off button submitted, if so turn off the Pi
poweroff = request.form[‘poweroff’]
if poweroff == “true”:
print(‘powering off…’, file=sys.stderr)
subprocess.call([‘poweroff’], shell=True)
return ‘Powering off…’
# get SSID from form
select_ssid = request.form[‘ssid’]
# get password from form, assume no password if blank
try:
select_password = request.form[‘password’]
except:
select_password = “”
# write configuration file for wpa_supplicant
wpa_config = open(“/etc/wpa_supplicant/wpa_supplicant.conf”, ‘w’)
wpa_config.write(“ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n”)
wpa_config.write(“network={\n”)
wpa_config.write(‘ssid=”‘ + select_ssid + ‘”\n’)
# if no password, the network is assumed to be unencrypted
if select_password == “”:
wpa_config.write(‘key_mgmt=NONE\n}\n\n’)
# password provided so set it in the configuration
else:
wpa_config.write(‘psk=”‘ + select_password + ‘”\n’)
wpa_config.write(‘proto=RSN\nkey_mgmt=WPA-PSK\npairwise=CCMP
TKIP\ngroup=CCMP TKIP\nauth_alg=OPEN\n}\n\n’)
# close configuration file
wpa_config.close()
# tell wpa_supplicant to reload configuration file
subprocess.call([‘wpa_cli reconfigure’], shell=True)

# kill all previous instances of dhcp client subprocess.call([‘killall dhclient’], shell=True) # call dhclient to acquire a public IP via DHCP subprocess.call([‘dhclient wlan1 -v’], shell=True) # restart OpenVPN subprocess.call([‘sleep 5 && service openvpn restart’], shell=True) # return a 302 redirect back to config page after form submitted return redirect(url_for(‘config’)) except: # something bad happened print(‘exception’, file=sys.stderr) # render template return render_template(‘index.html’, connected=connected, myrealip=myrealip, myvpnrealip=myvpnrealip, networks=networks, current_ssid=current_ssid)

Source: Raspberry Pi VPN Travel Router


About The Author

Muhammad Bilal

I am highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Scroll to Top