May 20, 2014

Configure RHEL 6 as Router

Introduction

In this blog I will show you how to configure a RHEL 6 server as router for LAN (eth1) and WAN (eth0).

Enable IP forwarding

First we need to enable IP forwarding.

$ sysctl -w "net.ipv4.ip_forward=1"
net.ipv4.ip_forward = 1

And to verify.

$ sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1

To make it permanent, you need to edit /etc/sysctl.conf.

$ grep "^net.ipv4.ip_forward" /etc/sysctl.conf 
net.ipv4.ip_forward = 1

Configure Router Server Network

Before we begin, we disable NetworkManager.

$ service NetworkManager stop
$ chkconfig NetworkManager off

Then we manually edit our network configuration files.

We begin with our WAN (eth0) card.

$ cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
HWADDR=64:70:02:11:d9:83
NM_CONTROLLED=no
ONBOOT=yes
BOOTPROTO=none
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=192.168.1.1

And continue with our LAN (eth1) card.

$ cat /etc/sysconfig/network-scripts/ifcfg-eth1
DEVICE=eth1
TYPE=Ethernet
HWADDR=64:70:02:13:CB:95
NM_CONTROLLED=no
ONBOOT=yes
BOOTPROTO=none
IPADDR=192.168.2.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=192.168.1.1

The above HWADDR is different for your environment. To get yours use ifconfig.

$ ifconfig 
eth0      Link encap:Ethernet  HWaddr 64:70:02:11:D9:83  
...
eth1      Link encap:Ethernet  HWaddr 64:70:02:13:CB:95  
...

Finally restart network service and check new ip addresses are set, via ip or ifconfig command.

$ service network restart

$ ip addr show
...
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
...
    inet 192.168.1.100/24 brd 192.168.1.255 scope global eth0
...
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
...
    inet 192.168.2.100/24 brd 192.168.2.255 scope global eth1
...

iptables

Now we are ready to configure iptables. First flush existing rules.

$ iptables -t filter -F
$ iptables -t nat -F
$ iptables -t mangle -F

Then add the MASQUERADE roule to the WAN (eth0) card

$ iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Finally save iptables configuration.

$ service iptables save

Test

I have connected a separate machine on LAN and configure it manually with static IP.

$IP: 192.168.2.3
NETMASK: 255.255.255.0
GATEWAY: 192.168.2.100
DNS1: 192.168.2.100

Now we can ping 192.168.2.100 (gateway), 192.168.1.100 (rhel 6 router), 192.168.1.1 (WAN GATEWAY) and finally www.google.com.