iptables is a user-space utility program that allows a system administrator to configure the IP packet filter rules of the Linux kernel firewall.
Basic Commands
sudo iptables -L # List all rules
sudo iptables -L -v -n # List rules with verbosity and numeric IPs/ports
sudo iptables -S # Print rules in command format
sudo iptables -F # Flush (delete) all rulesDefault Policies
sudo iptables -P INPUT DROP # Drop incoming traffic by default
sudo iptables -P FORWARD DROP # Drop forwarding traffic by default
sudo iptables -P OUTPUT ACCEPT # Allow outgoing traffic by defaultAllowing Traffic
# Allow Loopback (localhost)
sudo iptables -A INPUT -i lo -j ACCEPT
# Allow established and related connections (Crucial!)
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (Port 22)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP and HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow Ping (ICMP)
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPTDropping and Blocking
# Drop traffic from a specific IP
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
# Drop a specific port
sudo iptables -A INPUT -p tcp --dport 23 -j DROPSaving Rules
Rules added via command line are lost on reboot. You must save them.
# Ubuntu/Debian (requires iptables-persistent package)
sudo netfilter-persistent save
# RHEL/CentOS
sudo service iptables save
# or
sudo iptables-save > /etc/sysconfig/iptables