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:
sudo iptables --listIf the command is not found, you must install the iptables package. On Debian, Ubuntu, and their derivatives, use:
sudo apt-get updatesudo apt-get install iptablesOn RHEL, CentOS, Fedora, or AlmaLinux:
sudo yum install iptablesDo 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:
sudo iptables -FIf you have custom user-defined chains, remove them as well:
sudo iptables -XFlush the NAT table if you are using it for port forwarding or masquerading:
sudo iptables -t nat -FNow, set the default policies. We want to drop everything coming in, drop everything being forwarded, and allow everything going out:
sudo iptables -P INPUT DROPsudo iptables -P FORWARD DROPsudo iptables -P OUTPUT ACCEPTAt 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:
sudo iptables -A INPUT -i lo -j ACCEPTsudo iptables -A OUTPUT -o lo -j ACCEPTAllow Established and Related Connections
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:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPTThis 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:
sudo iptables -I INPUT -p tcp --dport 22 -j ACCEPTAllow HTTP and HTTPS traffic:
sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPTsudo iptables -I INPUT -p tcp --dport 443 -j ACCEPTLimiting 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:
sudo iptables -I INPUT -p tcp --dport 22 -m limit --limit 3/min --limit-burst 3 -j ACCEPTIf 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):
sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPTIf you want to drop all ICMP traffic to hide the server:
sudo iptables -A INPUT -p icmp -j DROPVerifying 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.
sudo iptables -L -v -nYou 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:
sudo iptables -SPersisting 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:
sudo netfilter-persistent saveIf netfilter-persistent is not installed, install it and save:
sudo apt-get install iptables-persistentsudo netfilter-persistent saveRHEL, CentOS, Fedora, and AlmaLinux
On Red Hat-based systems, the service iptables-services manages the persistence. Save your rules to /etc/sysconfig/iptables:
sudo iptables-save > /etc/sysconfig/iptablesEnsure the iptables service is enabled and started:
sudo systemctl enable iptablessudo systemctl start iptablesSystemd 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.
- Save your rules to a file, for example
/etc/iptables/rules.v4:
sudo iptables-save > /etc/iptables/rules.v4- Create a systemd service file at
/etc/systemd/system/iptables-restore.service:
[Unit]Description=Restore iptables rulesBefore=network-pre.targetWants=network-pre.target
[Service]Type=oneshotExecStart=/sbin/iptables-restore /etc/iptables/rules.v4RemainAfterExit=yes
[Install]WantedBy=multi-user.target- Reload systemd and enable the service:
sudo systemctl daemon-reloadsudo systemctl enable iptables-restore.serviceTroubleshooting 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:
sudo iptables -L -n --line-numbersDelete the rule at line 2:
sudo iptables -D INPUT 2After 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:
sudo systemctl stop firewalldsudo systemctl disable firewalldsudo systemctl start iptablesFor 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:
sudo modprobe ip_conntrackCheck which modules are currently loaded:
lsmod | grep iptableTrade-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:
- Flush all rules.
- Set default policies to DROP (INPUT and FORWARD) and ACCEPT (OUTPUT).
- Allow loopback traffic.
- Allow established and related connections.
- Allow specific services with rate limiting where necessary.
- 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.