Linux iptables is a user-space application program that allows a system administrator to configure the tables provided by the Linux kernel firewall (implemented as different Netfilter modules) and the chains and rules it stores.
Few points to note about iptable rules:
- First matching rules applies in case multiple rules match.
- Rules added using iptables are not persisted automatically. These will be lost if system reboots.
Here are some handy examples using iptables for IPv4 (for IPv6 use ip6tables, iptables-save, iptables-restore)
List iptable rules
- List all rules
## -n (numeric) -v (verbose) $ sudo iptables -L -n -v Chain INPUT (policy ACCEPT 465 packets, 33446 bytes) pkts bytes target prot opt in out source destination 4 220 DROP tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain OUTPUT (policy ACCEPT 345 packets, 74880 bytes) pkts bytes target prot opt in out source destination
- List specific chain rules (INPUT/FORWARD/OUTPUT)
## -n (numeric) -v (verbose) $ sudo iptables -L INPUT -n -v Chain INPUT (policy ACCEPT 456 packets, 32854 bytes) pkts bytes target prot opt in out source destination 4 220 DROP tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
- List all rules with line numbers
$ sudo iptables -n -L -v --line-numbers
Save and restore iptables
- Save iptables to a file
$ sudo iptables-save > iptable_filename
- Load iptables frm a file
$ sudo iptables-restore < iptable_filename
Add (Append) iptable rules
- Port based rules
Allow only connection to port 22, 80 and 443$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT $ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT $ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT $ sudo iptables -A INPUT -j DROP $ sudo iptables -n -L INPUT -v --line-numbers Chain INPUT (policy ACCEPT 0 packets, 0 bytes) num pkts bytes target prot opt in out source destination 1 257 18272 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 2 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 3 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443 4 0 0 DROP all -- * * 0.0.0.0/0 0.0.0.0/0
- IP based rules
Allow a port access from an IP$ sudo iptables -A INPUT -p tcp --dport 8081 -s 172.30.0.211 -j ACCEPT
Insert a rule before a specific numbered rule
To insert a rule before rule number 4 in INPUT chain
$ sudo iptables -I INPUT 4 -p tcp --dport 8081 -j ACCEPT
Delete iptable rules
- Delete a specific numbered rule
$ sudo iptables -D INPUT 4
- Delete/Flush all rules
$ sudo iptables -F