IPTables examples

From Tech-Wiki
Jump to: navigation, search


Allow specific protocol

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

Allow Ping

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

Drop specific IP

iptables -A INPUT -s 200.1.1.1 -j DROP

Drop packet with a specific string in payload: (You'd need a kernel compiled with Netfilter "String match support" enabled)

iptables -A INPUT -m string --algo bm --string "test" -j DROP
iptables -A FORWARD -m string --algo bm --string "test" -j DROP

Port Forwarding

iptables -t nat -A PREROUTING -p tcp -d 192.168.1.3 --dport 2222 -j DNAT --to 192.168.1.3:22

Set packet rate limit

iptables -A OUTPUT -m limit --limit 10/s -j ACCEPT
iptables -A FORWARD -p tcp --syn -m limit --limit 10/s -j ACCEPT

Prevent DoS

iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

NAT on external interface

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

Load Sharing

iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443