How to set up Iptables for Firewalling

Below is a list of iptables options

-A appends a rule to a chain
-F flushes all rules from a chain
-P sets default target for a chain
-L lists rules in chain
-D deletes a rule that matches its argument
-N okay sets up a new chain in this case, called okay

-j specifies target (default targets are ACCEPT,DROP,REJECT)
-p specifies ip protocol (tcp,udp,icmp..)
-s specifies source host/subnet in x.x.x.x/[0-32] format..ip with bitmask
-d specifies destination host/subnet....same format
-i specifies the interface the rule applies to (eth0,eth1)
-f matches packet fragments

tcp options ( to be used with -p tcp ):
--sport (can also use --source-port) specifies source port number or range,

--dport (can also use --destination-port) same thing, just the destination port.

--tcp-flags matches when its second argument is flagged, and the rest of the
flags specified in its first argument are cleared.

Using iptables as the firewall, create a shell script with a filename of setIptables.sh located in the /etc/sysconfig folder. An example of one is listed below:

 

# eth0 is trusted LAN
# eth1 is un-trusted area
#
# (1) policies -Set to drop ALL packets

iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# (2) User-defined chain for accepted TCP packets
iptables -N okay
iptables -A okay -p TCP --syn -j ACCEPT
iptables -A okay -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A okay -p TCP -j DROP

# (3) INPUT chain rules
# Rules for incoming packets from LAN
#
# accept everything on the LAN
iptables -A INPUT -p ALL -i eth0 -s 192.168.101.0/24 -j ACCEPT
#localhost too!
iptables -A INPUT -p ALL -i lo -s 127.0.0.1 -j ACCEPT
#Also accept time sync server...
iptables -A INPUT -p ALL -i eth0 -s 193.67.79.202 -j ACCEPT
#
# Drop anything that requests a connection
#
#iptables -A INPUT -i eth0 -p tcp --syn -j DROP
#


# (5) output chain rules
# only output packets with local addresses (no spoofing)
# checks to see if source is an address from one of this computer's
# network interfaces
#
iptables -A OUTPUT -p ALL -s 127.0.0.1 -j ACCEPT
# line below is set to eth0's IP address
iptables -A OUTPUT -p ALL -s 192.168.101.4 -j ACCEPT
#

# Line below is for the time server

iptables -A OUTPUT -p ALL -d 193.67.79.202 -j ACCEPT

# (6) POSTROUTING chain rules
# below is for when the firewall is connected to the internet

iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
iptables -A FORWARD -s 192.168.0.0/24 -j ACCEPT
iptables -A FORWARD -d 192.168.0.0/24 -j ACCEPT
iptables -A FORWARD -s ! 192.168.0.0/24 -j DROP


To make these additions permanent, make a backup of the old iptables file, and create a new one.

cp /etc/sysconfig/iptables /etc/sysconfig/iptables.old

iptables-save > /etc/sysconfig/iptables

Then restart the network daemon: /etc/init.d/network restart

Restart iptables as well: /etc/init.d/iptables restart

To check the iptables rules, type the following: iptables -L