Remote access: change configuration

This commit is contained in:
Romain Bazile 2021-11-03 18:05:42 +01:00
parent 317df93428
commit 1497a4ad9e
6 changed files with 319 additions and 383 deletions

View file

@ -2,15 +2,17 @@
This tutorial is adapted from a tutorial that you can find [here](https://www.raspberryconnect.com/projects/65-raspberrypi-hotspot-accesspoints/157-raspberry-pi-auto-wifi-hotspot-switch-internet). This tutorial is adapted from a tutorial that you can find [here](https://www.raspberryconnect.com/projects/65-raspberrypi-hotspot-accesspoints/157-raspberry-pi-auto-wifi-hotspot-switch-internet).
All the files modified in this document are also available in the repository, in the folder `scripts/raspbian_configuration`. The architecture of this folder shows where each file belong.
In order to work as an access point, the Raspberry Pi will need to have access point software installed, along with DHCP server software to provide connecting devices with a network address. In order to work as an access point, the Raspberry Pi will need to have access point software installed, along with DHCP server software to provide connecting devices with a network address.
To create an access point, we'll need DNSMasq and HostAPD. Install all the required software in one go with this command:: To create an access point, we'll need DNSMasq and HostAPD. Install all the required software in one go with this command::
``` ```sh
sudo apt install dnsmasq hostapd sudo apt install dnsmasq hostapd
``` ```
Since the configuration files are not ready yet, turn the new software off as follows:: Since the configuration files are not ready yet, turn the new software off as follows::
``` ```sh
sudo systemctl unmask hostapd sudo systemctl unmask hostapd
sudo systemctl disable dnsmasq sudo systemctl disable dnsmasq
sudo systemctl disable hostapd sudo systemctl disable hostapd
@ -55,7 +57,7 @@ The country_code should be set to your country to comply with local RF laws. You
To save the config file press `CTRL+O` and to exit press `CTRL+X`. To save the config file press `CTRL+O` and to exit press `CTRL+X`.
We also use a special function to change the network name to the machine name. Add this to `/etc/rc.local` with `sudo nano /etc/rc.local`: We also use a special function to change the network name to the machine name. Add this to `/etc/rc.local` with `sudo nano /etc/rc.local`:
``` ```sh
# Replace wifi hostname # Replace wifi hostname
sed -i "s/^ssid.*/ssid=PlanktoScope-$(python3 -c "import planktoscope.uuidName as uuidName; print(uuidName.machineName(machine=uuidName.getSerial()).replace(' ','_'))")/" /etc/hostapd/hostapd.conf sed -i "s/^ssid.*/ssid=PlanktoScope-$(python3 -c "import planktoscope.uuidName as uuidName; print(uuidName.machineName(machine=uuidName.getSerial()).replace(' ','_'))")/" /etc/hostapd/hostapd.conf
``` ```
@ -82,6 +84,14 @@ server=1.1.1.1
domain-needed domain-needed
bogus-priv bogus-priv
dhcp-range=192.168.4.100,192.168.4.200,12h dhcp-range=192.168.4.100,192.168.4.200,12h
#AutoEthernet config
interface=eth0
bind-dynamic
server=1.1.1.1
domain-needed
bogus-priv
dhcp-range=192.168.5.100,192.168.5.200,12h
``` ```
and then save `CTRL+O` and exit `CTRL+X`. and then save `CTRL+O` and exit `CTRL+X`.
@ -91,27 +101,41 @@ Reload dnsmasq to use the updated configuration:
sudo systemctl reload dnsmasq sudo systemctl reload dnsmasq
``` ```
## IP forwarding
While the RPi is in hotspot mode ip forwarding needs to be on so the internet works when an ethernet cable is attached. The autohotspot script will switch ip forwarding on and off between network mode and hotspot mode but it needs to be on by default for the script to manage ip forwarding. Edit `/etc/sysctl.conf` with `sudo nano /etc/sysctl.conf` and change the line 28 so it reads as follows:
```
# Uncomment the next line to enable packet forwarding for IPv4
net.ipv4.ip_forward=1
```
Save and exit.
## DHCPCD ## DHCPCD
DHCPCD is the software that manages the network setup. The next step is to stop dhcpcd from starting the wifi network so the autohotspot script in the next step takes control of that. Ethernet will still be managed by dhcpcd. DHCPCD is the software that manages the network setup. The next step is to stop dhcpcd from starting the wifi network so the autohotspot script in the next step takes control of that. Ethernet will still be managed by dhcpcd.
This will also create a fallback configuration to a static IP if no DHCP server is present on the Ethernet network.
Just add this line to the end of /etc/dhcpcd.conf with `sudo nano /etc/dhcpcd.conf`: Just add this line to the end of /etc/dhcpcd.conf with `sudo nano /etc/dhcpcd.conf`:
``` ```
nohook wpa_supplicant nohook wpa_supplicant
# define static profile
profile static_eth0
static ip_address=192.168.5.1/24
static routers=192.168.5.1
static domain_name_servers=192.168.5.1
# fallback to static profile on eth0
interface eth0
fallback static_eth0
``` ```
Save and exit. Save and exit.
For the fallback Ethernet network to work, we also need to add a hook to DHCPCD so it starts up the local DHCP server (dnsmasq). Edit the file `/etc/dhcpcd.enter-hook` with `sudo nano /etc/dhcpcd.enter-hook`:
```sh
if [ "$interface" = "eth0" ] && [ "$if_up" ]; then
systemctl start dnsmasq
if [ "$reason" = "STATIC" ] || [ "$reason" = "TIMEOUT" ] || [ "$reason" = "EXPIRE" ] || [ "$reason" = "NAK" ]; then
systemctl start dnsmasq
elif [ "$reason" = "NOCARRIER" ] || [ "$reason" = "INFORM" ] || [ "$reason" = "DEPARTED" ]; then
systemctl stop dnsmasq
fi
fi
```
## Autohotspot service file ## Autohotspot service file
@ -165,18 +189,25 @@ If no wifi signal is found for a known SSID then the script will shutdown the wi
The script works with SSID's that contain spaces and by entering your routers MAC address it can be used with hidden SSID's. The script works with SSID's that contain spaces and by entering your routers MAC address it can be used with hidden SSID's.
!!! info !!! info
Hidden SSIDs Hidden SSIDs
If your routers SSID is not broadcast/hidden then find this section in the script If your routers SSID is not broadcast/hidden then find this section in the script
``` ```
#Enter the Routers Mac Addresses for hidden SSIDs, seperated by spaces ie #Enter the Routers Mac Addresses for hidden SSIDs, seperated by spaces ie
#( '11:22:33:44:55:66' 'aa:bb:cc:dd:ee:ff' ) #( '11:22:33:44:55:66' 'aa:bb:cc:dd:ee:ff' )
mac=() mac=()
``` ```
and enter you routers MAC address in the brackets of mac=() as shown in the example. Make sure mutiple MAC addresses are seperated by a space. and enter you routers MAC address in the brackets of mac=() as shown in the example. Make sure mutiple MAC addresses are seperated by a space.
Create a new file with the command `sudo nano /usr/bin/autohotspotN` and add the following: Create a new file with the command `sudo nano /usr/bin/autohotspotN` and add the following:
```sh ```sh
#!/bin/bash #!/bin/bash
#version 0.96-N/HS-I #version 0.961-N/HS-I-PlanktonPlanet
#changes by PlanktonPlanet includes the following:
#- formatting and shellcheck validation
#- removal of ip forwarding setup
#You may share this script on the condition a reference to RaspberryConnect.com #You may share this script on the condition a reference to RaspberryConnect.com
#must be included in copies or derivatives of this script. #must be included in copies or derivatives of this script.
@ -192,15 +223,9 @@ wifidev="wlan0" #device name to use. Default is wlan0.
ethdev="eth0" #Ethernet port to use with IP tables ethdev="eth0" #Ethernet port to use with IP tables
#use the command: iw dev ,to see wifi interface name #use the command: iw dev ,to see wifi interface name
IFSdef=$IFS #These two lines capture the wifi networks the RPi is setup to use
cnt=0 wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' | sed 's/\r//g' | awk 'BEGIN{ORS=","} {print}' | sed 's/\"/''/g' | sed 's/,$//')
#These four lines capture the wifi networks the RPi is setup to use IFS="," read -r -a ssids <<<"$wpassid"
wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' ORS=',' | sed 's/\"/''/g' | sed 's/,$//')
wpassid=$(echo "${wpassid//[$'\r\n']}")
IFS=","
ssids=($wpassid)
IFS=$IFSdef #reset back to defaults
#Note:If you only want to check for certain SSIDs #Note:If you only want to check for certain SSIDs
#Remove the # in in front of ssids=('mySSID1'.... below and put a # infront of all four lines above #Remove the # in in front of ssids=('mySSID1'.... below and put a # infront of all four lines above
@ -213,49 +238,37 @@ mac=()
ssidsmac=("${ssids[@]}" "${mac[@]}") #combines ssid and MAC for checking ssidsmac=("${ssids[@]}" "${mac[@]}") #combines ssid and MAC for checking
createAdHocNetwork() createAdHocNetwork() {
{
echo "Creating Hotspot" echo "Creating Hotspot"
ip link set dev "$wifidev" down ip link set dev "$wifidev" down
ip a add 192.168.4.1/24 brd + dev "$wifidev" ip a add 192.168.4.1/24 brd + dev "$wifidev"
ip link set dev "$wifidev" up ip link set dev "$wifidev" up
dhcpcd -k "$wifidev" >/dev/null 2>&1 dhcpcd -k "$wifidev" >/dev/null 2>&1
iptables -t nat -A POSTROUTING -o "$ethdev" -j MASQUERADE
iptables -A FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
systemctl start dnsmasq systemctl start dnsmasq
systemctl start hostapd systemctl start hostapd
echo 1 > /proc/sys/net/ipv4/ip_forward
} }
KillHotspot() KillHotspot() {
{
echo "Shutting Down Hotspot" echo "Shutting Down Hotspot"
ip link set dev "$wifidev" down ip link set dev "$wifidev" down
systemctl stop hostapd systemctl stop hostapd
systemctl stop dnsmasq systemctl stop dnsmasq
iptables -D FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -D FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
echo 0 > /proc/sys/net/ipv4/ip_forward
ip addr flush dev "$wifidev" ip addr flush dev "$wifidev"
ip link set dev "$wifidev" up ip link set dev "$wifidev" up
dhcpcd -n "$wifidev" >/dev/null 2>&1 dhcpcd -n "$wifidev" >/dev/null 2>&1
} }
ChkWifiUp() ChkWifiUp() {
{
echo "Checking WiFi connection ok" echo "Checking WiFi connection ok"
sleep 20 #give time for connection to be completed to router sleep 20 #give time for connection to be completed to router
if ! wpa_cli -i "$wifidev" status | grep 'ip_address' >/dev/null 2>&1 if ! wpa_cli -i "$wifidev" status | grep 'ip_address' >/dev/null 2>&1; then #Failed to connect to wifi (check your wifi settings, password etc)
then #Failed to connect to wifi (check your wifi settings, password etc)
echo 'Wifi failed to connect, falling back to Hotspot.' echo 'Wifi failed to connect, falling back to Hotspot.'
wpa_cli terminate "$wifidev" >/dev/null 2>&1 wpa_cli terminate "$wifidev" >/dev/null 2>&1
createAdHocNetwork createAdHocNetwork
fi fi
} }
chksys() chksys() {
{
#After some system updates hostapd gets masked using Raspbian Buster, and above. This checks and fixes #After some system updates hostapd gets masked using Raspbian Buster, and above. This checks and fixes
#the issue and also checks dnsmasq is ok so the hotspot can be generated. #the issue and also checks dnsmasq is ok so the hotspot can be generated.
#Check Hostapd is unmasked and disabled #Check Hostapd is unmasked and disabled
@ -276,20 +289,18 @@ chksys()
fi fi
} }
FindSSID() {
FindSSID()
{
#Check to see what SSID's and MAC addresses are in range #Check to see what SSID's and MAC addresses are in range
ssidChk=('NoSSid') ssidChk='NoSSid'
i=0; j=0 i=0
until [ $i -eq 1 ] #wait for wifi if busy, usb wifi is slower. j=0
do until [ $i -eq 1 ]; do #wait for wifi if busy, usb wifi is slower.
ssidreply=$((iw dev "$wifidev" scan ap-force | egrep "^BSS|SSID:") 2>&1) >/dev/null 2>&1 ssidreply=$( (iw dev "$wifidev" scan ap-force | grep -E "^BSS|SSID:") 2>&1) >/dev/null 2>&1
#echo "SSid's in range: " $ssidreply #echo "SSid's in range: " $ssidreply
printf '%s\n' "${ssidreply[@]}" printf '%s\n' "${ssidreply[@]}"
echo "Device Available Check try " $j echo "Device Available Check try " $j
if (($j >= 10)); then #if busy 10 times goto hotspot if ((j >= 5)); then #if busy 5 times goto hotspot
echo "Device busy or unavailable 10 times, going to Hotspot" echo "Device busy or unavailable 5 times, going to Hotspot"
ssidreply="" ssidreply=""
i=1 i=1
elif echo "$ssidreply" | grep "No such device (-19)" >/dev/null 2>&1; then elif echo "$ssidreply" | grep "No such device (-19)" >/dev/null 2>&1; then
@ -317,10 +328,8 @@ do
fi fi
done done
for ssid in "${ssidsmac[@]}" for ssid in "${ssidsmac[@]}"; do
do if (echo "$ssidreply" | grep -F -- "$ssid") >/dev/null 2>&1; then
if (echo "$ssidreply" | grep "$ssid") >/dev/null 2>&1
then
#Valid SSid found, passing to script #Valid SSid found, passing to script
echo "Valid SSID Detected, assesing Wifi status" echo "Valid SSID Detected, assesing Wifi status"
ssidChk=$ssid ssidChk=$ssid
@ -333,8 +342,7 @@ do
done done
} }
NoDevice() NoDevice() {
{
#if no wifi device,ie usb wifi removed, activate wifi so when it is #if no wifi device,ie usb wifi removed, activate wifi so when it is
#reconnected wifi to a router will be available #reconnected wifi to a router will be available
echo "No wifi device connected" echo "No wifi device connected"
@ -346,17 +354,13 @@ chksys
FindSSID FindSSID
#Create Hotspot or connect to valid wifi networks #Create Hotspot or connect to valid wifi networks
if [ "$ssidChk" != "NoSSid" ] if [ "$ssidChk" != "NoSSid" ]; then
then if systemctl status hostapd | grep "(running)" >/dev/null 2>&1; then #hotspot running and ssid in range
echo 0 > /proc/sys/net/ipv4/ip_forward #deactivate ip forwarding
if systemctl status hostapd | grep "(running)" >/dev/null 2>&1
then #hotspot running and ssid in range
KillHotspot KillHotspot
echo "Hotspot Deactivated, Bringing Wifi Up" echo "Hotspot Deactivated, Bringing Wifi Up"
wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1 wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
ChkWifiUp ChkWifiUp
elif { wpa_cli -i "$wifidev" status | grep 'ip_address'; } >/dev/null 2>&1 elif { wpa_cli -i "$wifidev" status | grep 'ip_address'; } >/dev/null 2>&1; then #Already connected
then #Already connected
echo "Wifi already connected to a network" echo "Wifi already connected to a network"
else #ssid exists and no hotspot running connect to wifi network else #ssid exists and no hotspot running connect to wifi network
echo "Connecting to the WiFi Network" echo "Connecting to the WiFi Network"
@ -364,15 +368,15 @@ then
ChkWifiUp ChkWifiUp
fi fi
else #ssid or MAC address not in range else #ssid or MAC address not in range
if systemctl status hostapd | grep "(running)" >/dev/null 2>&1 if systemctl status hostapd | grep "(running)" >/dev/null 2>&1; then
then
echo "Hostspot already active" echo "Hostspot already active"
elif { wpa_cli status | grep "$wifidev"; } >/dev/null 2>&1 elif { wpa_cli status | grep "$wifidev"; } >/dev/null 2>&1; then
then
echo "Cleaning wifi files and Activating Hotspot" echo "Cleaning wifi files and Activating Hotspot"
wpa_cli terminate >/dev/null 2>&1 wpa_cli terminate >/dev/null 2>&1
ip addr flush "$wifidev" ip addr flush "$wifidev"
ip link set dev "$wifidev" down ip link set dev "$wifidev" down
# ip addr flush "$ethdev"
# ip link set dev "$ethdev" down
rm -r /var/run/wpa_supplicant >/dev/null 2>&1 rm -r /var/run/wpa_supplicant >/dev/null 2>&1
createAdHocNetwork createAdHocNetwork
else #"No SSID, activating Hotspot" else #"No SSID, activating Hotspot"

View file

@ -59,3 +59,13 @@ slaac private
#fallback static_eth0 #fallback static_eth0
nohook wpa_supplicant nohook wpa_supplicant
# define static profile
profile static_eth0
static ip_address=192.168.5.1/24
static routers=192.168.5.1
static domain_name_servers=192.168.5.1
# fallback to static profile on eth0
interface eth0
fallback static_eth0

View file

@ -0,0 +1,8 @@
if [ "$interface" = "eth0" ] && [ "$if_up" ]; then
systemctl start dnsmasq
if [ "$reason" = "STATIC" ] || [ "$reason" = "TIMEOUT" ] || [ "$reason" = "EXPIRE" ] || [ "$reason" = "NAK" ]; then
systemctl start dnsmasq
elif [ "$reason" = "NOCARRIER" ] || [ "$reason" = "INFORM" ] || [ "$reason" = "DEPARTED" ]; then
systemctl stop dnsmasq
fi
fi

View file

@ -494,7 +494,6 @@
# to 5. See page 19 of # to 5. See page 19 of
# http://download.intel.com/design/archives/wfm/downloads/pxespec.pdf # http://download.intel.com/design/archives/wfm/downloads/pxespec.pdf
# Enable dnsmasq's built-in TFTP server # Enable dnsmasq's built-in TFTP server
#enable-tftp #enable-tftp
@ -682,7 +681,6 @@
dhcp-mac=set:client_is_a_pi,B8:27:EB:*:*:* dhcp-mac=set:client_is_a_pi,B8:27:EB:*:*:*
dhcp-reply-delay=tag:client_is_a_pi,2 dhcp-reply-delay=tag:client_is_a_pi,2
#AutoHotspot config #AutoHotspot config
interface=wlan0 interface=wlan0
bind-dynamic bind-dynamic
@ -690,3 +688,11 @@ server=1.1.1.1
domain-needed domain-needed
bogus-priv bogus-priv
dhcp-range=192.168.4.100,192.168.4.200,12h dhcp-range=192.168.4.100,192.168.4.200,12h
#AutoEthernet config
interface=eth0
bind-dynamic
server=1.1.1.1
domain-needed
bogus-priv
dhcp-range=192.168.5.100,192.168.5.200,12h

View file

@ -1,68 +0,0 @@
#
# /etc/sysctl.conf - Configuration file for setting system variables
# See /etc/sysctl.d/ for additional system variables.
# See sysctl.conf (5) for information.
#
#kernel.domainname = example.com
# Uncomment the following to stop low-level messages on console
#kernel.printk = 3 4 1 3
##############################################################3
# Functions previously found in netbase
#
# Uncomment the next two lines to enable Spoof protection (reverse-path filter)
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
#net.ipv4.conf.default.rp_filter=1
#net.ipv4.conf.all.rp_filter=1
# Uncomment the next line to enable TCP/IP SYN cookies
# See http://lwn.net/Articles/277146/
# Note: This may impact IPv6 TCP sessions too
#net.ipv4.tcp_syncookies=1
# Uncomment the next line to enable packet forwarding for IPv4
net.ipv4.ip_forward=1
# Uncomment the next line to enable packet forwarding for IPv6
# Enabling this option disables Stateless Address Autoconfiguration
# based on Router Advertisements for this host
#net.ipv6.conf.all.forwarding=1
###################################################################
# Additional settings - these settings can improve the network
# security of the host and prevent against some network attacks
# including spoofing attacks and man in the middle attacks through
# redirection. Some network environments, however, require that these
# settings are disabled so review and enable them as needed.
#
# Do not accept ICMP redirects (prevent MITM attacks)
#net.ipv4.conf.all.accept_redirects = 0
#net.ipv6.conf.all.accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net.ipv4.conf.all.secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
#net.ipv4.conf.all.send_redirects = 0
#
# Do not accept IP source route packets (we are not a router)
#net.ipv4.conf.all.accept_source_route = 0
#net.ipv6.conf.all.accept_source_route = 0
#
# Log Martian Packets
#net.ipv4.conf.all.log_martians = 1
#
###################################################################
# Magic system request Key
# 0=disable, 1=enable all, >1 bitmask of sysrq functions
# See https://www.kernel.org/doc/html/latest/admin-guide/sysrq.html
# for what other values do
#kernel.sysrq=438

View file

@ -1,5 +1,9 @@
#!/bin/bash #!/bin/bash
#version 0.96-N/HS-I #version 0.961-N/HS-I-PlanktonPlanet
#changes by PlanktonPlanet includes the following:
#- formatting and shellcheck validation
#- removal of ip forwarding setup
#You may share this script on the condition a reference to RaspberryConnect.com #You may share this script on the condition a reference to RaspberryConnect.com
#must be included in copies or derivatives of this script. #must be included in copies or derivatives of this script.
@ -15,15 +19,9 @@ wifidev="wlan0" #device name to use. Default is wlan0.
ethdev="eth0" #Ethernet port to use with IP tables ethdev="eth0" #Ethernet port to use with IP tables
#use the command: iw dev ,to see wifi interface name #use the command: iw dev ,to see wifi interface name
IFSdef=$IFS #These two lines capture the wifi networks the RPi is setup to use
cnt=0 wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' | sed 's/\r//g' | awk 'BEGIN{ORS=","} {print}' | sed 's/\"/''/g' | sed 's/,$//')
#These four lines capture the wifi networks the RPi is setup to use IFS="," read -r -a ssids <<<"$wpassid"
wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' ORS=',' | sed 's/\"/''/g' | sed 's/,$//')
wpassid=$(echo "${wpassid//[$'\r\n']}")
IFS=","
ssids=($wpassid)
IFS=$IFSdef #reset back to defaults
#Note:If you only want to check for certain SSIDs #Note:If you only want to check for certain SSIDs
#Remove the # in in front of ssids=('mySSID1'.... below and put a # infront of all four lines above #Remove the # in in front of ssids=('mySSID1'.... below and put a # infront of all four lines above
@ -36,49 +34,37 @@ mac=()
ssidsmac=("${ssids[@]}" "${mac[@]}") #combines ssid and MAC for checking ssidsmac=("${ssids[@]}" "${mac[@]}") #combines ssid and MAC for checking
createAdHocNetwork() createAdHocNetwork() {
{
echo "Creating Hotspot" echo "Creating Hotspot"
ip link set dev "$wifidev" down ip link set dev "$wifidev" down
ip a add 192.168.4.1/24 brd + dev "$wifidev" ip a add 192.168.4.1/24 brd + dev "$wifidev"
ip link set dev "$wifidev" up ip link set dev "$wifidev" up
dhcpcd -k "$wifidev" >/dev/null 2>&1 dhcpcd -k "$wifidev" >/dev/null 2>&1
iptables -t nat -A POSTROUTING -o "$ethdev" -j MASQUERADE
iptables -A FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
systemctl start dnsmasq systemctl start dnsmasq
systemctl start hostapd systemctl start hostapd
echo 1 > /proc/sys/net/ipv4/ip_forward
} }
KillHotspot() KillHotspot() {
{
echo "Shutting Down Hotspot" echo "Shutting Down Hotspot"
ip link set dev "$wifidev" down ip link set dev "$wifidev" down
systemctl stop hostapd systemctl stop hostapd
systemctl stop dnsmasq systemctl stop dnsmasq
iptables -D FORWARD -i "$ethdev" -o "$wifidev" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -D FORWARD -i "$wifidev" -o "$ethdev" -j ACCEPT
echo 0 > /proc/sys/net/ipv4/ip_forward
ip addr flush dev "$wifidev" ip addr flush dev "$wifidev"
ip link set dev "$wifidev" up ip link set dev "$wifidev" up
dhcpcd -n "$wifidev" >/dev/null 2>&1 dhcpcd -n "$wifidev" >/dev/null 2>&1
} }
ChkWifiUp() ChkWifiUp() {
{
echo "Checking WiFi connection ok" echo "Checking WiFi connection ok"
sleep 20 #give time for connection to be completed to router sleep 20 #give time for connection to be completed to router
if ! wpa_cli -i "$wifidev" status | grep 'ip_address' >/dev/null 2>&1 if ! wpa_cli -i "$wifidev" status | grep 'ip_address' >/dev/null 2>&1; then #Failed to connect to wifi (check your wifi settings, password etc)
then #Failed to connect to wifi (check your wifi settings, password etc)
echo 'Wifi failed to connect, falling back to Hotspot.' echo 'Wifi failed to connect, falling back to Hotspot.'
wpa_cli terminate "$wifidev" >/dev/null 2>&1 wpa_cli terminate "$wifidev" >/dev/null 2>&1
createAdHocNetwork createAdHocNetwork
fi fi
} }
chksys() chksys() {
{
#After some system updates hostapd gets masked using Raspbian Buster, and above. This checks and fixes #After some system updates hostapd gets masked using Raspbian Buster, and above. This checks and fixes
#the issue and also checks dnsmasq is ok so the hotspot can be generated. #the issue and also checks dnsmasq is ok so the hotspot can be generated.
#Check Hostapd is unmasked and disabled #Check Hostapd is unmasked and disabled
@ -99,20 +85,18 @@ chksys()
fi fi
} }
FindSSID() {
FindSSID()
{
#Check to see what SSID's and MAC addresses are in range #Check to see what SSID's and MAC addresses are in range
ssidChk=('NoSSid') ssidChk='NoSSid'
i=0; j=0 i=0
until [ $i -eq 1 ] #wait for wifi if busy, usb wifi is slower. j=0
do until [ $i -eq 1 ]; do #wait for wifi if busy, usb wifi is slower.
ssidreply=$((iw dev "$wifidev" scan ap-force | egrep "^BSS|SSID:") 2>&1) >/dev/null 2>&1 ssidreply=$( (iw dev "$wifidev" scan ap-force | grep -E "^BSS|SSID:") 2>&1) >/dev/null 2>&1
#echo "SSid's in range: " $ssidreply #echo "SSid's in range: " $ssidreply
printf '%s\n' "${ssidreply[@]}" printf '%s\n' "${ssidreply[@]}"
echo "Device Available Check try " $j echo "Device Available Check try " $j
if (($j >= 10)); then #if busy 10 times goto hotspot if ((j >= 5)); then #if busy 5 times goto hotspot
echo "Device busy or unavailable 10 times, going to Hotspot" echo "Device busy or unavailable 5 times, going to Hotspot"
ssidreply="" ssidreply=""
i=1 i=1
elif echo "$ssidreply" | grep "No such device (-19)" >/dev/null 2>&1; then elif echo "$ssidreply" | grep "No such device (-19)" >/dev/null 2>&1; then
@ -140,10 +124,8 @@ do
fi fi
done done
for ssid in "${ssidsmac[@]}" for ssid in "${ssidsmac[@]}"; do
do if (echo "$ssidreply" | grep -F -- "$ssid") >/dev/null 2>&1; then
if (echo "$ssidreply" | grep "$ssid") >/dev/null 2>&1
then
#Valid SSid found, passing to script #Valid SSid found, passing to script
echo "Valid SSID Detected, assesing Wifi status" echo "Valid SSID Detected, assesing Wifi status"
ssidChk=$ssid ssidChk=$ssid
@ -156,8 +138,7 @@ do
done done
} }
NoDevice() NoDevice() {
{
#if no wifi device,ie usb wifi removed, activate wifi so when it is #if no wifi device,ie usb wifi removed, activate wifi so when it is
#reconnected wifi to a router will be available #reconnected wifi to a router will be available
echo "No wifi device connected" echo "No wifi device connected"
@ -169,17 +150,13 @@ chksys
FindSSID FindSSID
#Create Hotspot or connect to valid wifi networks #Create Hotspot or connect to valid wifi networks
if [ "$ssidChk" != "NoSSid" ] if [ "$ssidChk" != "NoSSid" ]; then
then if systemctl status hostapd | grep "(running)" >/dev/null 2>&1; then #hotspot running and ssid in range
echo 0 > /proc/sys/net/ipv4/ip_forward #deactivate ip forwarding
if systemctl status hostapd | grep "(running)" >/dev/null 2>&1
then #hotspot running and ssid in range
KillHotspot KillHotspot
echo "Hotspot Deactivated, Bringing Wifi Up" echo "Hotspot Deactivated, Bringing Wifi Up"
wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1 wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
ChkWifiUp ChkWifiUp
elif { wpa_cli -i "$wifidev" status | grep 'ip_address'; } >/dev/null 2>&1 elif { wpa_cli -i "$wifidev" status | grep 'ip_address'; } >/dev/null 2>&1; then #Already connected
then #Already connected
echo "Wifi already connected to a network" echo "Wifi already connected to a network"
else #ssid exists and no hotspot running connect to wifi network else #ssid exists and no hotspot running connect to wifi network
echo "Connecting to the WiFi Network" echo "Connecting to the WiFi Network"
@ -187,19 +164,18 @@ then
ChkWifiUp ChkWifiUp
fi fi
else #ssid or MAC address not in range else #ssid or MAC address not in range
if systemctl status hostapd | grep "(running)" >/dev/null 2>&1 if systemctl status hostapd | grep "(running)" >/dev/null 2>&1; then
then
echo "Hostspot already active" echo "Hostspot already active"
elif { wpa_cli status | grep "$wifidev"; } >/dev/null 2>&1 elif { wpa_cli status | grep "$wifidev"; } >/dev/null 2>&1; then
then
echo "Cleaning wifi files and Activating Hotspot" echo "Cleaning wifi files and Activating Hotspot"
wpa_cli terminate >/dev/null 2>&1 wpa_cli terminate >/dev/null 2>&1
ip addr flush "$wifidev" ip addr flush "$wifidev"
ip link set dev "$wifidev" down ip link set dev "$wifidev" down
# ip addr flush "$ethdev"
# ip link set dev "$ethdev" down
rm -r /var/run/wpa_supplicant >/dev/null 2>&1 rm -r /var/run/wpa_supplicant >/dev/null 2>&1
createAdHocNetwork createAdHocNetwork
else #"No SSID, activating Hotspot" else #"No SSID, activating Hotspot"
createAdHocNetwork createAdHocNetwork
fi fi
fi fi