Linux server as router/gateway

Step-by-Step descriptions of how to do things.
Post Reply
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

Linux server as router/gateway

Post 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
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
User avatar
peter_b
Chatterbox
Posts: 383
Joined: Tue Nov 12, 2013 2:05 am

iptables: Clean configure on Debian

Post 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.
Post Reply