Make a Router from a Linux Box Jan 21st 2021 Words: 267

Sometimes I need a secondary gateway in my network, or simply want to provide Internet access for another device using my Linux box. The trick is simple, in this example, I am using a Raspberry Pi 4B with Rasbian 10 installation.

Configure the Interface used as LAN

Set the interface address to static and assign a network segment to it, in this example, 192.168.168.1 is assigned to eth0, with network mask 255.255.255.0.

[https://www.raspberrypi.org/documentation/configuration/tcpip/](Raspberry Pi Document: TCP/IP networking)

edit /etc/dhcpcd.conf

1
2
interface eth0
static ip_address=192.168.168.1/24

Enable Forwarding

edit /etc/sysctl.conf

Add the following line:

1
net.ipv4.ip_forward=1

Enable Masquerading

Install iptables-persistent so the rules can persist between reboots.

1
sudo apt install iptables-persistent

edit /etc/iptables/rules.v4, assume wlan0 is the interface used to access the Internet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
*filter

# Firewall (Optional)
-A FORWARD -m state -–state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i wlan0 -d 192.168.168.1/24 -j DROP

COMMIT


*nat

-A POSTROUTING -o wlan0 -j MASQUERADE

COMMIT

Use dnsmasq as DHCP server

Install with:

1
sudo apt install dnsmasq

edit /etc/dnsmasq.conf:

1
2
except-interface=wlan0
dhcp-range=192.168.168.100,192.168.168.254,255.255.255.0,3h

Build iPXE

1
2
3
git clone git://git.ipxe.org/ipxe.git

cd ipxe/src

create ipxe/src/boot.txt

1
2
3
4
#!ipxe

dhcp
chain http://192.168.168.1/boot
1
2
3
4
5
# Legacy
make bin/undionly.kpxe EMBED=boot.txt

# UEFI
make bin-x86_64-efi/ipxe.efi EMBED=boot.txt