Iptables tutorial and examples
Delete existing rules:
iptables -F or iptables --flush
Set Default Chain Policies:
iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT DROP
Block an IP Address:
iptables -A INPUT -s a.b.c.d -j DROP iptables -A input -i eth0 -p tcp -s <ip_addr> -j DROP
Allow access to SSH:
iptables -A INPUT -i eth0 -p tcp --dport
Allow inbound connections from a specific network :
iptables -A INPUT -i eth0 -p tcp -s <ip_address/24> --dport
Redirecting requests to a different Ip address :
vi /etc/sysctl.conf net.ipv4_forward=1 sysctl -p
iptables -t nat -A PREROUTING -p tcp --dport port -j DNAT --to-destination ip:port iptables -t nat -A POSTROUTING -j MASQUERADE
Access to multiple ports :
iptables -A INPUT -i eth0 -p tcp -m multiport --dports 20,21,22 -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -0 eth0 -p tcp -m multiport --dports 20,21,22 -m state --state ESTABLISHED -j ACCEPT
Load Balance incoming traffic :
iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.1:80 iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.2:80 iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.3:80
Allow Ping from Outside :
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT
Forward Internal network To External :
iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
Allow NIS Connections :
Do a grep on rpcinfo to find the port
rpcinfo -p | grep ypbind
And allow the ports.
Prevent DOS Attacks :
iptables -A INPUT -p tcp --dport 80 -m limit --limit 20/minute --limit-burst 150 -j ACCEPT
[ -m limit : use iptables limit extension , –limit 20/minute : maximum 20 connections for minute, –limit-burst 150 : The limit will be enforced only after the total number of connection has reached the burst level ]
Port Forwarding :
iptables -t nat -A PREROUTING -p tcp -d 192.168.100.5 --dport 80 -j DNAT --to 192.168.100.100:8080
Logging Dropped Packets:
a. Create a Chain:
iptables -N LOGGING
b. Force all inbound connections to jump to Logging Chain
iptables -A INPUT -j LOGGING
c. Log the packets with a prefix.
iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "Dropped Packet" --log-level 7
d. Drop the packets.
iptables -A LOGGING -j DROP