older kernel firewall, superseded by nftables
iptables has three commonly used tables: filter, nat and mangle. The filter table acts as regular firewall filtering
Chains in iptables are sets of rules.
INPUT → packets coming in
OUTPUT → packets going out
FORWARD → packets routed through
PREROUTING → alter packets before INPUT
POSTROUTING → alter packets after OUTPUT
iptables -nL List numbered rules; add -v for verbose
iptables-save dump iptables rules
iptables -F flush rules
iptables -X delete empty chains
iptables -P INPUT DROP Set policy to drop incoming packets for INPUT
iptables -A INPUT -i lo -j ACCEPT Append rule to INPUT chain to accept packets on loopback
iptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT Append rule to INPUT chain to accept TCP dest port 22 packets on eth0
iptables -A INPUT -i eth0 -s 10.10.10.0/24 -p tcp -j ACCEPT Allow inbound TCP traffic from input eth0 with source network 10.10.10.0/24
iptables -A OUTPUT -o eth0 -d 10.10.10.0/24 -p tcp -j ACCEPT Allow outbound TCP traffic to output eth0 with dest network 10.10.10.0/24
iptables -A INPUT -p icmp --icmp-type any -j ACCEPT Allow inbound ICMP traffic
Source NAT changes the source IP address in a packet before it leaves the system. It uses the POSTROUTING chain.
Example: packets coming from 172.16.52.0/24 exiting through eth2 will get source IP of 123.124.125.126
iptables -t nat -A POSTROUTING -o eth2 -s 172.16.52.0/24 -j SNAT --to-source 123.124.125.126
DNAT changes the destination IP address in a packet after it enters the system. It uses the PREROUTING chain.
It is typically used to redirect requests to an internal server (DMZ) on a private address range.
Example: redirect ssh connections from wan (eth1) to 192.168.1.1
iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 22 -j DNAT --to-destination 192.168.1.1