Phase 1

1. View Current Rules

Check if you already have firewall rules running.

1
sudo iptables -L -v -n

2.

If you want a clean slate, flush the existing rules. Note: If the default policy is currently set to DROP, running this will lock you out immediately. Only run this if the policy is ACCEPT.

1
2
3
4
5
6
sudo iptables -P INPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -P OUTPUT ACCEPT

# flush all rules
sudo iptables -F

Phase 2: Building the “Allow” List

A good firewall follows the principle of “Default Deny”. We will add the “Allow” rules first, and then enable the “Block” policy at the end.

Step 1: Allow “Loopback” Traffic

Your server needs to talk to itself.

1
sudo iptables -A INPUT -i lo -j ACCEPT

Step 2: Allow Established Connections

This is the most critical rule for a stateful firewall. It ensures that if you send a request out (like apt update), the server accepts the reply.

1
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  • -m conntrack: Use the connection tracking module.
  • --ctstate ESTABLISHED: Allow traffic belonging to an existing connection.

Step 3: Allow SSH

We must explicitly allow traffic on port 22 (or your custom SSH port).

1
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Step 4: Allow Web Traffic

Open the ports for your web server.

1
2
3
4
5
# HTTP
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# HTTPS
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Phase 3: Closing the Gates

Now that we have listed everyone allowed to enter, we change the default policy to DROP. This means any packet that didn’t match the rules above will be discarded.

Step 5: Set Default Policy

1
sudo iptables -P INPUT DROP
  • Note: We usually leave OUTPUT as ACCEPT unless you have high-security requirements.

Step 6: Verify

Check your work. You should see packet counters rising for the allowed rules.

1
sudo iptables -L -v -n

Phase 4: Persistence

By default, iptables rules are lost on reboot. You must save them.

For Ubuntu/Debian:

1
2
3
4
5
# Install the persistent package if you haven't
sudo apt install iptables-persistent

# Save current rules
sudo netfilter-persistent save