Monday, January 24, 2011

IPTABLES on CentOS / Fedora / RedHat

Since kernel version 2.4, there is a built in system for package filtering known as Netfilter. To use Netfilter, during kernel compiling CONFIG_NETFILTER must be included. Also ip_forward must be enabled:
echo 1 > /proc/sys/net/ipv4/ip_forward
Package filtering works on Internet layer of TCP/IP protocol. Filtering rules can be defined based on a transport layer header(port number) and connection layer (source IP address). During filtering, package content is not being checked.
Netfilter filtering chains work in kernel mode. In user mode works special tool called – iptables, which requires root user privilegies and it's used to configure:
- filter chains,
- NAT tables,
- mangle tables.
Netfilter uses three filters, INPUT, OUTPUT, FORWARD, realised in form of chains. Each chain contains a set of rules that filters packages. If some package sattisfies a rule, an action gets to be applied, like accepting or rejecting package.
Iptables commands:
-A (Add rule to the end of chain).
-D (Delete rule from chain).
-R (Replace rule in chain).
-I (Add numeric rule in chain).
-L (List rules).
-F (Delete all rules from chain).
Deleting the chains:
# iptables -F INPUT
# iptables -F OUTPUT
# iptables -F FORWARD
Here are some basic examples of iptables usage.
1. Blocking IP with iptables:
# iptables -A INPUT -s -j DROP
# iptables -A OUTPUT -d -j DROP
* instead can be added.
2. Opening ports:
First thing you need to do is check if ports are already opened. It's done using nmap, free program, and it's distributed in most distros.
# nmap -sT
22/tcp open ssh
80/tcp open http
443/tcp open https
Nmap run completed -- 1 IP address scanned in 0.941 seconds.
As we see, on this list port 25 is not opened. Let's open port 25 for SMTP traffic.
# iptables -A INPUT -p tcp --dport 25 -j ACCEPT
3. Enabling other hosts to ping:
# iptables -A INPUT -p icmp -s –icmp-type echo-request -j ACCEPT
# iptables -A INPUT -p icmp -d –icmp-type echo-reply -j ACCEPT
4. Restricting access by time of the day:
# iptables -A INPUT -p tcp -s 0/0 --sport 513:65535 -d --dport 22 -m state
--state NEW,ESTABLISHED -m time --timestart 09:00 --timestop 18:00
--days Mon,Tue,Wed,Thu,Fri -j ACCEPT  

5. Keeping logs about rejected packages:

# iptables -A OUTPUT -j LOG
# iptables -A OUTPUT -j DROP
# iptables -A INPUT -j LOG
# iptables -A INPUT -j DROP
# iptables -A FORWARD -j LOG
# iptables -A FORWARD -j DROP
Post a Comment