24 Января, 2019

Setup a Home Router using IPTables

Денис Забияко
Setting up IPTables for NAT routing
The following configuration is used on a Linksys WRT54GL with OpenWRT WhiteRussion v5.

Must have at least 2 NICs, one for WAN, one for LAN.
Must have support for IPTables and NAT in your kernel.
I am using dnsmasq as DNS and DHCP servers --

Add this line to enable dhcp:
Restrict dnsmasq to just the LAN interface

Setup IPTables

# First we flush our current rules
iptables -F
iptables -t nat -F

# Setup default policies to handle unmatched traffic unless otherwise defined
iptables -P INPUT ACCEPT
iptables -P FORWARD DROP

# Define interfaces, eg:
export LAN=eth0
export WAN=eth1

# Lock down some services so they only work from the LAN
iptables -I INPUT 1 -i ${LAN} -j ACCEPT
iptables -I INPUT 1 -i lo -j ACCEPT
iptables -A INPUT -p UDP --dport bootps -i ! ${LAN} -j REJECT
iptables -A INPUT -p UDP --dport domain -i ! ${LAN} -j REJECT

# Allow SSH access from WAN
iptables -A INPUT -p TCP --dport ssh -i ${WAN} -j ACCEPT

# Disallow traffic to privileged ports - optional, think it through.
iptables -A INPUT -p TCP -i ! ${LAN} -d 0/0 --dport 0:1023 -j DROP
iptables -A INPUT -p UDP -i ! ${LAN} -d 0/0 --dport 0:1023 -j DROP

# Finally, add the rules for NAT
iptables -I FORWARD -i ${LAN} -d -j DROP
iptables -A FORWARD -i ${LAN} -s -j ACCEPT
iptables -A FORWARD -i ${WAN} -d -j ACCEPT
iptables -t nat -A POSTROUTING -o ${WAN} -j MASQUERADE

# Tell the kernel that ip forwarding is OK
echo 1 > /proc/sys/net/ipv4/ip_forward
for f in /proc/sys/net/ipv4/conf/*/rp_filter ; do echo 1 > $f ; done

Save the IPTables configuration:

/etc/init.d/iptables save

Edit sysctl.conf and enable IP forwarding in the kernel:
net.ipv4.ip_forward = 1
net.ipv4.conf.default.rp_filter = 1

# May need to add the following if you use DHCP on WAN
net.ipv4.ip_dynaddr = 1