Linux: iptables Configuration and Security

This guide explains how to implement a secure "Default-Deny" firewall strategy using iptables on your Linux server. This method blocks all network traffic unless explicitly permitted.


Warning: The order of these commands is absolutely critical. Executing the final DROP policy before allowing SSH access will instantly lock you out of your server. Always test rules carefully.

1. Defining Base Rules and Safe Execution Order

We must configure the necessary access rules first, before applying the global blocking policy.

Start with a clean configuration by deleting all existing iptables rules.

Flush All Rules
iptables -F

2. Opening Service Ports and Structure

Add rules for all services that need to be externally accessible. For better maintenance, using user-defined chains is recommended.

To keep the INPUT chain clean, create a custom chain for open ports and redirect traffic there.

Create Chain and Jump
# 1. Create new chain iptables -N OPEN_PORTS # 2. Rule: Jump from INPUT to OPEN_PORTS (must be before the final DROP rule!) iptables -A INPUT -j OPEN_PORTS

3. Protection Mechanisms and Logging

Integrate basic protection against floods and ensure proper logging of rejected packets.

Limits the rate of new connections per source IP to mitigate simple floods on a specific port.

Rate Limit for Port 80
# Limits new connections on port 80 to 50 per minute per IP iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --update --seconds 60 --hitcount 50 -j DROP # Allow new connections and add IP to the "recent" list iptables -A INPUT -p tcp --dport 80 -m state --state NEW -m recent --set -j ACCEPT

4. Saving and Making Rules Persistent

iptables rules are temporary after entry and will be lost upon reboot. They must be permanently saved.

Before saving, verify that all rules have been correctly inserted into the chain.

View Rules
iptables -L -n -v

Alternative nftables: On modern distributions, iptables is being succeeded by nftables. If you require a very complex rule set, switching to nftables is recommended for future-proofing your setup.