One of the fundamental functions of a router is to forward traffic between our internal network and the internet.
In order to use the Raspberry Pi, or any Linux machine, as a router, the first thing we need to do is to enable packet forwarding.
Since I’m using Ubuntu 20.04 on my PiRouter, I can enable IPv4 forwarding instantly by executing, as sudo, the following command:
sysctl -w net.ipv4.ip_forward=1
| Remember to run these commands as root, or with sudo.
To make the change permanent, I need to modify /etc/sysctl.conf
, adding the following line at the end of the file:
net.ipv4.ip_forward=1
This will ensure that IPv4 forwarding will be enabled on boot.
Now, I need to setup iptables
rules in my firewall so that the PiRouter accepts and forwards the traffic it receives from my internal network/interface (lan0
) to my external interface/internet (wan0
).
This can be accomplished by executing the following commands:
iptables -A FORWARD -i lan0 -j ACCEPT
iptables -A POSTROUTING -o wan0 -j MASQUERADE
These rules will only be active until we reboot, so it’s important to save them. I use iptables-persistent
, which can be installed using the following command:
apt install iptables-persistent
After the installation, the setup will ask if you wish to save the current rules. By clicking Yes, we save our forwarding rules to /etc/iptables/rules.v4
, and they’ll be loaded every time our router boots.
Finally, we can ensure that the IPTables Persistent service is enabled and running by executing the following commands:
systemctl enable netfilter-persistent.service
systemctl start netfilter-persistent.service
Having done all of these steps, we now have a Raspberry Pi that will forward traffic between interfaces, however it’s still not ready to be used as a router, since we’re still missing a DHCP server and a DNS server. I’ll be covering these key pieces in the next post.