This is an old revision of the document!
IPTables
General Information
Build a basic IPTables firewall config with no defined rules.
Checklist
- Distros: All
Quick Firewall; Copy and Paste
iptables -F INPUT iptables -A INPUT -i lo -m comment --comment "Loopback Operations" -j ACCEPT iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -m comment --comment "Related,Established Conn" -j ACCEPT iptables -A INPUT -p icmp -m comment --comment "ICMP Requests" -j ACCEPT iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m comment --comment "SSH Access" -j ACCEPT iptables -A INPUT -m comment --comment "Drop All Else" -j DROP iptables -P INPUT DROP
At any point: List all rules, with line numbers, verbose, numeric output:
iptables -L --line-numbers -vn
The Rules, Explained
1) Allow loopback operations
iptables -A INPUT -i lo -m comment --comment "Loopback Operations" -j ACCEPT
2) Accept any related/established connections (ctstate is the successor to the state module)
iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -m comment --comment "Related,Established Conn" -j ACCEPT
if the above doesn't work, that module is not available, do this:
iptables -A INPUT -m state --state RELATED,ESTABLISHED -m comment --comment "Related,Established Conn" -j ACCEPT
3) Accept icmp (ping) requests
iptables -A INPUT -p icmp -m comment --comment "ICMP Requests" -j ACCEPT
4) Allow ssh to server
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m comment --comment "SSH Access" -j ACCEPT
5) Drop all other traffic
iptables -A INPUT -m comment --comment "Drop All Else" -j DROP
6) Policy set to drop (in case the last drop rule is deleted)
iptables -P INPUT DROP
7) Save the rules
- Ubuntu: Install iptables-persistant
apt-get install iptables-persistant
- CentOS: Run the iptables save service command
/sbin/service iptables save
Other Examples
Insert
Insert at rule# 5, with Comment (192.168.1.200 = Monitoring Server)
iptables --insert INPUT 5 --source 192.168.1.200/32 --protocol tcp --dport 161 --in-interface eth0 -m comment --comment "Nagios SNMP" --jump ACCEPT
Redirect
Redirect Outside Traffic to a Different Port (Server is 192.168.1.101)
iptables -t nat -A PREROUTING -d 192.168.1.101 -p udp -m udp --dport 514 -m comment --comment "Redirect Syslogs(514) to Splunk Syslog port 1028" -j DNAT --to-destination 192.168.1.101:1028
Connection Tracking
Guard against brute force SSH attempts
1) Add sources connecting to destination port 22 to the list “sshlist”
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name sshlist --rsource -m comment --comment "Track SSH Connections"
2) If the remote source has not attempted to connect 3+ times within 60 seconds, accept
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent ! --rcheck --seconds 60 --hitcount 3 --name sshlist --rsource -m comment --comment "Accept < 3 ssh attempts in 60 secs" -j ACCEPT