Phase 1
1. View Current Rules
Check if you already have firewall rules running.
| |
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.
| |
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.
| |
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.
| |
-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).
| |
Step 4: Allow Web Traffic
Open the ports for your web server.
| |
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
| |
- Note: We usually leave
OUTPUTasACCEPTunless you have high-security requirements.
Step 6: Verify
Check your work. You should see packet counters rising for the allowed rules.
| |
Phase 4: Persistence
By default, iptables rules are lost on reboot. You must save them.
For Ubuntu/Debian:
| |