Capture Secure WiFi network, share internet through new DHCP ethernet

This is like a second part after I have mastered Switch between WiFi networks without reboot

This instruction is tested on Raspberry Pi 3 using Raspian Stretch Lite.

Install DHCP and DNS server. This is all in one package:
sudo apt-get install dnsmasq -y
Modify network interfaces:
sudo nano /etc/network/interfaces
Allow WiFi addapter to work as Plug and Play and set static address for wired connection:
allow-hotplug eth0  
iface eth0 inet static  
    address 192.168.2.1
    netmask 255.255.255.0
    network 192.168.2.0
    broadcast 192.168.2.255
Backup and create new dnsmasq configuration:
sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig  
sudo nano /etc/dnsmasq.conf
Paste content:
interface=eth0      # Use interface eth0  
listen-address=192.168.2.1 # listen on  
# Bind to the interface to make sure we aren't sending things 
# elsewhere  
bind-interfaces
server=8.8.8.8       # Forward DNS requests to Google DNS  
domain-needed        # Don't forward short names  
# Never forward addresses in the non-routed address spaces.
bogus-priv
# Assign IP addresses between 192.168.2.2 and 192.168.2.100 with a
# 12 hour lease time
dhcp-range=192.168.2.2,192.168.2.100,12h
Enable instant packet forwarding:
sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
Enable packet forwarding automatically after next reboot:
sed -i "s/^.*net\.ipv4\.ip_forward=.$/net\.ipv4\.ip_forward=1/" /etc/sysctl.conf
Configure iptables. This is the magical place where the internet connection is getting shared from wireless to wired situation:
sudo iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE  
sudo iptables -A FORWARD -i wlan0 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT  
sudo iptables -A FORWARD -i eth0 -o wlan0 -j ACCEPT
Save iptables configuration into a file:
sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"
Open again:
sudo nano /etc/network/interfaces
Tell the network configuration to load iptables after the network interface is up:
pre-up iptables-restore < /etc/iptables.ipv4.nat
Restart network interface:
sudo /etc/init.d/networking restart
Plug new device into ethernet port and celebrate.

No comments: