Networking

iptables CLI

iptables commands for Linux firewall configuration.

30 commands
Windows MacOS Linux
#firewall #security

List Rules

List all rules with line numbers and counters
iptables -L -n -v
List INPUT chain rules with line numbers
iptables -L INPUT -n --line-numbers
List NAT table rules with verbose output
iptables -L -t nat -n -v
Show all rules in iptables-save format
iptables -S
List FORWARD chain rules with counters
iptables -L FORWARD -n -v

Add Rules

Allow incoming SSH traffic
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Allow incoming HTTP traffic
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
Allow traffic from a subnet
iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT
Allow ping requests
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Drop all other incoming traffic
iptables -A INPUT -j DROP
Insert HTTPS rule at top of chain
iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT

Delete Rules

Delete a specific rule by specification
iptables -D INPUT -p tcp --dport 80 -j ACCEPT
Delete rule number 3 from INPUT chain
iptables -D INPUT 3
Flush all rules from all chains
iptables -F
Flush all rules from INPUT chain only
iptables -F INPUT
Delete all user-defined chains
iptables -X

NAT & Port Forwarding

Enable NAT masquerading on eth0
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Redirect port 8080 to port 80
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80
Forward port 80 to internal host
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.0.0.2:80
Source NAT for a subnet
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j SNAT --to-source 1.2.3.4

Save & Restore

Save current rules to a file
iptables-save > /etc/iptables/rules.v4
Restore rules from a file
iptables-restore < /etc/iptables/rules.v4
Persist rules across reboots on Debian
netfilter-persistent save
Set default INPUT policy to DROP
iptables -P INPUT DROP
Set default FORWARD policy to DROP
iptables -P FORWARD DROP
Set default OUTPUT policy to ACCEPT
iptables -P OUTPUT ACCEPT

Quick Commands

List all firewall rules with verbose output
iptables -L -n -v
Allow incoming SSH connections on port 22
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Save current firewall rules to a file
iptables-save > /etc/iptables/rules.v4