Page 1 of 1

Linux server as router/gateway

Posted: Fri Aug 20, 2010 12:33 pm
by ^rooker
I'm writing these few lines down, because it's actually dead-simple, but a few things I always forget when I setup a GNU/Linux box as a gateway/router between networks.
So here's a step-by-step list of things you need to do to NAT-route between 2 networks.

Let's say your network settings are as follows:
a) LAN_INTERFACE="eth0"
b) INET_INTERFACE="eth1"
c) INET_GATEWAY="192.168.1.1"

First things first:
1) Enable IPv4 forwarding:

Edit /etc/sysctl.conf, and enable "net.ipv4.ip_forward=1", to look like this:
# Uncomment the next line to enable packet forwarding for IPv4
net.ipv4.ip_forward=1
In order to enable IPv4 forwarding immediately, do the following:

Code: Select all

sudo su
echo "1" > /proc/sys/net/ipv4/ip_forward
Now, to check if it IPv4 forwarding is enable, type:

Code: Select all

cat /proc/sys/net/ipv4/ip_forward
Should return "1".

2) Enable network-address-translation (NAT) between the networks, using "iptables":

Code: Select all

iptables -t nat -A POSTROUTING -o $INET_INTERFACE -j MASQUERADE
3) Enable some computer on the $INET_INTERFACE network as your default gateway:

Code: Select all

route add default gw $INET_GATEWAY
4) Check the routing:

Code: Select all

route

iptables: Clean configure on Debian

Posted: Wed Dec 10, 2014 4:43 pm
by peter_b
In the Debian Wiki article about iptables it is described how to configure iptables rules persistently.
So, in order to apply the above mentioned routing/iptables setup in a clean, standardized way, do the following:

1) Enable IPv4 forwarding in "/etc/sysctl.conf" as mentioned above.

2) Add the iptables MASQUERADE rule as mentioned above.

3) Write the iptables rules to "/etc/iptables.up.rules" (as root):

Code: Select all

$ iptables-save > /etc/iptables.up.rules
4) Create the file "/etc/network/if-pre-up.d/iptables", with the following content:

Code: Select all

#!/bin/sh
/sbin/iptables-restore < /etc/iptables.up.rules
and mark it executable:

Code: Select all

$ chmod +x /etc/network/if-pre-up.d/iptables

That should be it.