How to create simplest possible iptables firewall

Create simplest possible iptables firewall with quite relaxed rules that will allow all outgoing traffic, incoming icmp packets and ssh connections on eth0 interface.

# Flush INPUT/OUTPUT/FORWARD chains
iptables -F INPUT
iptables -F OUTPUT
iptables -F FORWARD

# Drop invalid packets
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

# Pass everything on loopback
iptables -A INPUT  -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# Accept incoming packets for established connections
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Accept incoming ICMP
iptables -A INPUT -p icmp -j ACCEPT

# Accept incoming SSH on eth0 interface
iptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT

# Accept connections
iptables -P OUTPUT ACCEPT

# Drop everything else on INPUT/FORWARD
iptables -P INPUT   DROP
iptables -P FORWARD DROP

List all firewall rules to verify that executed commands are applied as desired.

$ sudo iptables -L -v -n
Chain INPUT (policy DROP 1 packets, 32 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID
    0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0           
  252 19645 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
    0     0 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0           
    1    60 ACCEPT     tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22

Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 188 packets, 30167 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  *      lo      0.0.0.0/0            0.0.0.0/0   

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system. He is also open for new opportunities and challenges.