Skip to content
masdzub.com
~/articles/linux — one from the notebook

Hardening Linux with iptables: A Practical Whitelist Approach

Secure your Linux server by implementing a basic firewall using iptables. This guide covers flushing rules, setting a default drop policy, allowing essential traffic, and persisting configurations.

masdzub@website:~$ cat ~/articles/linux-hardening-set-up-a-basic-firewall-with-iptables.aspx.md
# 1 file · 11 min read · topic: linux · status: published

Introduction

This guide establishes a strict baseline firewall on a Linux server using the iptables utility. We begin by flushing all existing rules to ensure a clean state, then set the default INPUT policy to DROP, effectively blocking all unsolicited incoming traffic. We proceed to allow specific services such as SSH and HTTP, manage established connections, and configure persistence so the rules survive reboots. This whitelist method creates a secure environment where only explicitly permitted traffic is allowed to pass.

Prerequisites

You need root access to the server to execute iptables commands. Open a terminal or SSH session and verify your current firewall status by running the following command:

Terminal window
sudo iptables --list

If the command is not found, you must install the iptables package. On Debian, Ubuntu, and their derivatives, use:

Terminal window
sudo apt-get update
sudo apt-get install iptables

On RHEL, CentOS, Fedora, or AlmaLinux:

Terminal window
sudo yum install iptables

Do not proceed until you are certain you have root privileges, as improper rules can lock you out of the server.

Understanding the iptables Architecture

iptables works by matching packets against a chain of rules. Each chain acts as a filter that decides whether to allow or drop a packet based on the criteria defined in the rules. There are three main built-in chains:

  • INPUT: This chain handles incoming packets destined for the local system. This is where we apply most of our hardening rules.
  • OUTPUT: This chain handles outgoing packets created by the local system. By default, we usually allow all outgoing traffic.
  • FORWARD: This chain handles packets being routed through the system (e.g., acting as a router or proxy). We generally drop all forwarded traffic unless the system is explicitly configured as a gateway.

Every packet traverses these chains in order. If a rule matches a packet, the action specified in that rule (ACCEPT, DROP, or REJECT) is executed, and the chain processing for that packet stops. If no rule matches, the default policy of the chain applies.

The Whitelist Strategy

The most secure method for a firewall is the whitelist approach. Instead of guessing which ports are safe to open, we start with the assumption that all incoming traffic is hostile and explicitly permit only what is absolutely necessary. This requires us to set the default policy of the INPUT chain to DROP. Once this is done, we must insert rules at the top of the chain (or ensure they are evaluated before the default drop) to allow essential traffic like loopback interfaces and established connections.

Step-by-Step Configuration

We will build our firewall rules sequentially. Clear all existing rules first to avoid conflicts. Execute the following command to flush the filter table:

Terminal window
sudo iptables -F

If you have custom user-defined chains, remove them as well:

Terminal window
sudo iptables -X

Flush the NAT table if you are using it for port forwarding or masquerading:

Terminal window
sudo iptables -t nat -F

Now, set the default policies. We want to drop everything coming in, drop everything being forwarded, and allow everything going out:

Terminal window
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

At this point, the server is secure but completely inaccessible. We must now add rules to allow the traffic we need.

Allow Loopback Traffic

Loopback traffic refers to communications between processes on the same machine. We must allow this to prevent local services from failing. Run these commands to accept traffic on the lo interface:

Terminal window
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT

When a client connects to your server via SSH or HTTP, the server responds with an acknowledgment. These return packets must be allowed to reach the client, or the connection will fail. iptables can track these connections using the connection tracking module. We append a rule to accept packets that are part of an established connection or related to one:

Terminal window
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

This rule is critical. Without it, even a correctly allowed connection would be dropped immediately after the server attempts to reply.

Allow Specific Services

We now add rules to allow traffic for the services you require. We use the -p flag to specify the protocol (tcp or udp) and the --dport flag to specify the destination port. It is best practice to insert these rules at the beginning of the chain to ensure they are evaluated before the default drop, although with a default drop policy, simply appending them to the end often works if the policy is the last rule evaluated. However, explicit insertion (-I) is safer to guarantee order.

Allow SSH on port 22. Replace 22 with your custom SSH port if you have changed it for security:

Terminal window
sudo iptables -I INPUT -p tcp --dport 22 -j ACCEPT

Allow HTTP and HTTPS traffic:

Terminal window
sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -I INPUT -p tcp --dport 443 -j ACCEPT

Limiting SSH Connection Rate

Brute force attacks attempt to guess your SSH password by making many connection requests rapidly. You can mitigate this by limiting the number of new connections to a specific port per second. The limit module combined with the hashlimit target is effective for this. This rule allows a maximum of 3 new connection attempts per minute from any single IP address:

Terminal window
sudo iptables -I INPUT -p tcp --dport 22 -m limit --limit 3/min --limit-burst 3 -j ACCEPT

If an IP exceeds this rate, subsequent packets are dropped until the limit resets. This protects your SSH daemon from being overwhelmed without blocking legitimate users who might type slowly.

ICMP (Ping) Control

The Internet Control Message Protocol (ICMP) is used for diagnostics like ping. While generally harmless, it can be used to probe for open ports. For a hardened server, you may want to drop ICMP echo requests entirely or limit them.

To allow ping requests but drop them silently (DROP is preferred over REJECT to avoid revealing information about the server):

Terminal window
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

If you want to drop all ICMP traffic to hide the server:

Terminal window
sudo iptables -A INPUT -p icmp -j DROP

Verifying the Rules

You can view the list of active rules to verify your configuration. The -v flag shows detailed information including packet and byte counts, while the -n flag displays IP addresses and ports numerically, preventing DNS resolution delays.

Terminal window
sudo iptables -L -v -n

You should see the rules you added, followed by a potential “Chain DROP (policy DROP)” line indicating the default policy. The order of rules is important. Use the -S (or --list-rules) command to see the rules in the order they are evaluated:

Terminal window
sudo iptables -S

Persisting Rules Across Reboots

The iptables rules exist only in memory while the system is running. A reboot will wipe them out, leaving your server open. To make the rules persistent, you must save them to a file. The method depends on your Linux distribution.

Debian, Ubuntu, and derivatives

The iptables-persistent package handles this automatically. During installation, it will ask you to save current rules. If you installed without the package, you can save the rules manually and use a systemd service to reload them.

First, save the current rules:

Terminal window
sudo netfilter-persistent save

If netfilter-persistent is not installed, install it and save:

Terminal window
sudo apt-get install iptables-persistent
sudo netfilter-persistent save

RHEL, CentOS, Fedora, and AlmaLinux

On Red Hat-based systems, the service iptables-services manages the persistence. Save your rules to /etc/sysconfig/iptables:

Terminal window
sudo iptables-save > /etc/sysconfig/iptables

Ensure the iptables service is enabled and started:

Terminal window
sudo systemctl enable iptables
sudo systemctl start iptables

Systemd Timer (Universal Approach)

For a more modern and robust method that works across distributions, you can create a systemd service that runs iptables-restore from a file whenever the network interface comes up or at boot.

  1. Save your rules to a file, for example /etc/iptables/rules.v4:
Terminal window
sudo iptables-save > /etc/iptables/rules.v4
  1. Create a systemd service file at /etc/systemd/system/iptables-restore.service:
[Unit]
Description=Restore iptables rules
Before=network-pre.target
Wants=network-pre.target
[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore /etc/iptables/rules.v4
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
  1. Reload systemd and enable the service:
Terminal window
sudo systemctl daemon-reload
sudo systemctl enable iptables-restore.service

Troubleshooting Common Issues

Lockout Scenarios

The most dangerous risk when hardening a firewall is locking yourself out. If you mistakenly block the port you are using to log in, you cannot fix it remotely. To prevent this, use rate limiting on your SSH port, as demonstrated earlier. If you lock yourself out anyway, you must access the console or use a rescue environment (like a VNC console in a cloud provider) to remove the offending rule.

To remove a specific rule, you need its rule number. View the list with numbers:

Terminal window
sudo iptables -L -n --line-numbers

Delete the rule at line 2:

Terminal window
sudo iptables -D INPUT 2

After making changes, verify the rules immediately to ensure you can still connect.

Conflicts with firewalld

Modern Red Hat-based systems often come with firewalld enabled by default. firewalld manages iptables rules internally and can conflict with direct iptables commands. If you make changes with iptables but see them disappear after a short time, firewalld is likely overwriting them.

To stop firewalld temporarily to apply your iptables rules:

Terminal window
sudo systemctl stop firewalld
sudo systemctl disable firewalld
sudo systemctl start iptables

For the long term, you can disable firewalld entirely or configure it to use your custom rules. However, for a basic hardening guide, stopping the service is the simplest path.

Modules Not Loading

If you attempt to use a module, such as conntrack, and receive an error, the kernel module may not be loaded. You can load it manually:

Terminal window
sudo modprobe ip_conntrack

Check which modules are currently loaded:

Terminal window
lsmod | grep iptable

Trade-offs and Modern Alternatives

While iptables is the industry standard and provides granular control, it is verbose and difficult to read. A small mistake can result in a completely locked server.

nftables

Linux has moved toward nftables (netfilter tables), which is the successor to iptables. It offers a more efficient and unified interface. However, it requires a different syntax and is not supported by older distributions. If you are setting up a brand new server in 2026, checking if nftables is available is wise, though iptables remains the universally supported fallback.

UFW (Uncomplicated Firewall)

If you find the syntax of iptables too complex, ufw is a front-end designed to make it easier. It provides simple commands like allow 22 and deny 80. While easier, it obscures the underlying rules and can be less flexible than raw iptables. For a deep hardening scenario where you need to understand every packet flow, raw iptables is superior.

Cloud Security Groups

If your server is hosted on a cloud provider (AWS EC2, Google Cloud, Azure), you must configure the network security groups in addition to local iptables. Cloud firewalls act at the hypervisor level before traffic even reaches the instance. While iptables hardens the operating system itself, cloud firewalls provide the first layer of defense against IP spoofing and DDoS attacks originating from the internet.

Summary of the Hardened Rule Set

A robust, persistent iptables configuration typically follows this pattern:

  1. Flush all rules.
  2. Set default policies to DROP (INPUT and FORWARD) and ACCEPT (OUTPUT).
  3. Allow loopback traffic.
  4. Allow established and related connections.
  5. Allow specific services with rate limiting where necessary.
  6. Save the rules to a file and configure a systemd service to restore them on boot.

This configuration ensures that only traffic you explicitly allow can enter your system, providing a strong foundation for server hardening.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.