July 02, 2022 (updated at: April 28, 2024)
Basic survival guide and commands for iptables
iptables is a Linux firewall tool that manages packet routing and can block or allow traffic based on rules like a packet’s origin or destination.
Its settings are organized in tables which contain sets of rules, called chains, that will filter data packets.
# Lists existing rules with the "specification" syntax
iptables -S
# Delete a rule by its specification string
iptables -D <spec>
# List existing rules by chain and alongside packet matching statistics
iptables -L -v --line-numbers
# Delete a rule by its row index
iptables -D <chain> <num>
# Reset the packet counters on all chains
iptables -Z
# Accept all requests from an IP
iptables -I INPUT -s <ip> -j ACCEPT
# Drop all requests from an IP
iptables -I INPUT -s <ip> -j DROP
# Accept all incoming TCP traffic to a given port
iptables -I INPUT -m state --state NEW -p tcp --dport <port> -j ACCEPT
# Drop all requests from a range of IPs
iptables -I INPUT -m iprange --src-range <ip_range_start>-<ip_range_end> -j DROP
# Drop all traffic (must be run after acceptance rules; `-A` stands for "append")
iptables -A INPUT -j DROP
# Delete all current rules
iptables -F
# Restore iptables rules from last persisted version
iptables-restore < /etc/iptables/rules.v4
# Persist changes to disk
/sbin/iptables-save
# Depending on your setup, you may need to run another command instead
netfilter-persistent save