Skip to content

Instantly share code, notes, and snippets.

@Juul
Last active June 9, 2022 04:01
Show Gist options
  • Save Juul/eb4f47cc4b8ab77f081fa8ed5d30b709 to your computer and use it in GitHub Desktop.
Save Juul/eb4f47cc4b8ab77f081fa8ed5d30b709 to your computer and use it in GitHub Desktop.
How to quickly configure your box as a gateway granting devices connected on ethernet access to wifi network
First ensure your ethernet isn't managed by network-manager by adding the following to `/etc/NetworkManager/NetworkManager.conf`:
```
[keyfile]
unmanaged-devices=mac:00:11:22:33:44
```
Replacing the MAC address with that of your ethernet device.
Then run:
```
sudo systemctl restart NetworkManager
```
Install dnsmasq which we'll use only as a DHCP server:
```
sudo apt install dnsmasq
```
Stop it and prevent it from starting on boot
```
sudo systemctl stop dnsmasq
sudo systemctl disable dnsmasq
```
Run the following script as root to set a static IP on your ethernet interface, configure iptables as a NAT gateway and start dnsmasq as a DHCP server.
Remember to replace the interface names.
```
#!/bin/bash
# Check if root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
ETH=enp0s25
WLAN=wlp4s0
IP=172.23.0.1/24
DHCPRANGE=172.23.0.50,172.23.0.150
# Set stat IP
ip addr flush dev $ETH
ip addr add dev $ETH $IP
ip link set dev $ETH up
# Configure as NAT gateway
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -P FORWARD ACCEPT
iptables -t nat -F POSTROUTING
iptables -t nat -A POSTROUTING -o $WLAN -j MASQUERADE
# Start dnsmasq as DHCP server and keep in foreground
dnsmasq --conf-file=/dev/null --bind-dynamic -i $ETH --no-daemon --dhcp-option=6,$IP --dhcp-range=${DHCPRANGE},10m --log-dhcp --log-facility -
```
To disable, hit ctrl-c to stop dnsmasq then do something like this:
```
iptables -t nat -F POSTROUTING
iptables -F FORWARD
echo "0" > /proc/sys/net/ipv4/ip_forward
ip link set dev $ETH down
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment