iptables: A Beginner's Guide to the Linux Firewall

Understanding Iptables: A Linux Firewall Guide
Iptables represents a highly adaptable firewall solution specifically designed for Linux-based operating systems. Its utility spans a wide range of users, from those newly exploring Linux to experienced system administrators.
The versatility of iptables allows it to be leveraged in numerous ways to enhance system security. This guide will demonstrate how to effectively configure this powerful Linux firewall.
Key Features and Benefits
Iptables operates by defining rules that dictate how network traffic is handled. These rules can be customized to permit, deny, or manipulate packets based on various criteria.
The core strength of iptables lies in its ability to provide granular control over network access. This allows for the creation of highly specific security policies.
Configuration Basics
Configuring iptables involves defining a series of rules organized into tables. Each table corresponds to a different type of network traffic.
Common tables include 'filter' (for general filtering), 'nat' (for network address translation), and 'mangle' (for packet alteration). Understanding these tables is crucial for effective configuration.
Practical Applications
- Blocking unwanted traffic: Iptables can be used to block connections from specific IP addresses or networks.
- Port forwarding: Redirect incoming traffic on a specific port to another port or machine.
- Network Address Translation (NAT): Allow multiple devices on a private network to share a single public IP address.
These are just a few examples of the many ways iptables can be utilized to secure and manage a Linux system. Properly configured rules are essential for maintaining a robust security posture.
Photo by ezioman.
Understanding iptables
iptables functions as a command-line firewall, employing a system of policy chains to either permit or deny network traffic. Upon an attempt to initiate a connection to your system, iptables scans its rule set for a matching entry.
Should a suitable rule not be located, the firewall defaults to a pre-configured action. This action determines whether the connection is accepted or rejected.
Installation and Availability
The iptables utility is typically included by default in most Linux distributions. Updating or installing the package is straightforward using the following command:
sudo apt-get install iptables
Alternatives and Precautions
Graphical user interfaces, such as Firestarter, offer alternative methods for managing iptables. However, mastering a few core iptables commands is generally not overly complex.
Extreme caution is advised when configuring iptables rules, especially during remote administration via SSH. A single incorrect command has the potential to cause a permanent lockout, requiring physical access to rectify the issue.
Furthermore, securing your SSH server is crucial if you choose to expose its port to the network.
Key Considerations
It's important to remember that iptables operates based on the order of rules. The first matching rule dictates the action taken.
Regularly saving your iptables configuration is essential to ensure that your firewall rules persist across system reboots.
Types of Chains
iptables employs three distinct chains for packet filtering: input, forward, and output.
Input – This chain governs the handling of incoming connections. For instance, when a user initiates an SSH connection to your computer or server, iptables evaluates the source IP address and port against the rules defined within the input chain.
Forward – The forward chain is utilized for connections arriving at the system but not intended for it directly. Consider a router; data frequently passes through it without being destined for the router itself, being instead forwarded to its ultimate destination. Unless your system performs routing, Network Address Translation (NAT), or similar functions, this chain likely remains unused.
A simple method exists to determine if your system utilizes or requires the forward chain.
iptables -L -v
The following illustrates a server that has been operational for several weeks without restrictions on network traffic. Observe that the input chain has processed 11GB of packets, while the output chain has handled 17GB. Notably, the forward chain has not processed any packets.
This outcome is typical for a server not functioning as a forwarding device or pass-through point.
Output – This chain manages outgoing connections. For example, if you attempt to ping howtogeek.com, iptables will consult its output chain to assess the rules pertaining to ICMP (ping) and the destination address before permitting or denying the connection.
Important Consideration
Although initiating a ping to an external host appears to involve only the output chain, remember that receiving the response necessitates the use of the input chain as well. When securing your system with iptables, recognize that many protocols require bidirectional communication, thus necessitating proper configuration of both input and output chains. SSH is a protocol often overlooked when configuring both chains.
Default Policy Chain Configuration
Prior to establishing specific rules, it’s crucial to determine the default behavior for each of the three chains. Essentially, this defines how iptables will handle connections that do not correspond to any pre-defined rules.
To ascertain the current configuration of your policy chains regarding unmatched traffic, execute the following command:
iptables -L
This command displays the current rules and default policies for each chain.
As illustrated, the grep command was also employed to refine the output, providing a more focused view. In the provided example, the chains are presently configured to accept traffic.
In most scenarios, configuring your system to accept connections by default is the preferred approach. This setting is typically already in place unless you have previously modified the policy chain rules.
To explicitly set the default policy to accept connections, use these commands:
iptables --policy INPUT ACCEPT
iptables --policy OUTPUT ACCEPT
iptables --policy FORWARD ACCEPT
By establishing an 'accept' default, you can subsequently utilize iptables to block specific IP addresses or port numbers, while maintaining acceptance of all other connections. Further commands for this purpose will be discussed shortly.
Alternatively, if you prefer to deny all connections and selectively permit only those you explicitly authorize, you should modify the default policy of your chains to 'drop'. This approach is generally suitable for servers hosting sensitive data and interacting with a limited, known set of IP addresses.
iptables --policy INPUT DROP
iptables --policy OUTPUT DROP
iptables --policy FORWARD DROP
This configuration ensures that only explicitly allowed connections are permitted, enhancing security for sensitive environments.
Connection-Specific Actions in iptables
Once default chain policies are established, rules can be added to iptables to define how the system responds to connections originating from or destined for specific IP addresses or ports. This guide will detail the three fundamental and frequently employed responses available.
Available Responses
- Accept - Permits the connection to proceed.
- Drop - Silently discards the connection, as if it never occurred. This approach is preferred when concealing the system's presence from the source.
- Reject - Denies the connection and sends an error message back to the source. This is useful for informing a specific source that their connection attempt was blocked by the firewall.
The distinctions between these responses are best illustrated by examining the results of a PC attempting to ping a Linux machine configured with each respective iptables setting.
Here's how an Accept rule manifests:

The outcome of a Drop rule is as follows:

Finally, a Reject rule produces this result:

Controlling Network Connections with iptables
Having established your policy chains, the next step involves configuring iptables to permit or deny connections originating from specific addresses, address blocks, and ports. The following examples utilize the DROP action, however, this can be readily altered to ACCEPT or REJECT, contingent upon your requirements and the configuration of your policy chains.
It’s important to note that these examples employ iptables -A to append new rules to existing chains. Iptables processes rules sequentially, starting from the top, and ceases evaluation upon finding a matching rule.
Rule Insertion
Should a rule need to be positioned above another within the chain, the iptables -I [chain] [number] command can be used. This allows for precise specification of the rule's position in the list.
Blocking Connections Based on Source
The following sections demonstrate how to control network traffic based on its origin.
Connections from a Single IP Address
To prevent all connections originating from the IP address 10.10.10.10, the following command is used:
iptables -A INPUT -s 10.10.10.10 -j DROP
Connections from an IP Address Range
To block all IP addresses within the 10.10.10.0/24 network range, utilize either netmask or CIDR notation:
iptables -A INPUT -s 10.10.10.0/24 -j DROP
Alternatively, you can specify the range using a full netmask:
iptables -A INPUT -s 10.10.10.0/255.255.255.0 -j DROP
Controlling Connections by Port
Specific ports can also be targeted for blocking.
Blocking Connections to a Specific Port
The following example demonstrates blocking SSH connections originating from 10.10.10.10:
iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP
The protocol or port number can be substituted for "ssh". The -p tcp flag indicates that the rule applies to TCP connections. For UDP-based protocols, -p udp should be used instead.
Blocking Connections to a Port from Any IP Address
To block SSH connections from all IP addresses, the command is:
iptables -A INPUT -p tcp --dport ssh -j DROP
Connection States Explained
Many network protocols necessitate bidirectional communication. For instance, enabling SSH access to your system requires rules governing both incoming and outgoing traffic.
However, a common requirement is to permit only inbound connections. Adding a rule to the output chain could inadvertently authorize outgoing SSH attempts. This is where connection states become crucial.
Understanding Connection States
Connection states provide the granularity needed to authorize two-way communication while restricting the initiation of connections to a single direction.
Consider a scenario where SSH connections originating from 10.10.10.10 are allowed, but connections destined for that address are blocked.
Despite this restriction, the system can still transmit data back over an established SSH session, facilitating communication between the two hosts.
Illustrative iptables Rules
The following iptables rules demonstrate this functionality:
- Input Rule:
iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -m state --state NEW,ESTABLISHED -j ACCEPT - This rule accepts TCP packets destined for the SSH port (port 22) originating from 10.10.10.10, provided they are either initiating a new connection (NEW) or are part of an existing connection (ESTABLISHED).
- Output Rule:
iptables -A OUTPUT -p tcp --sport 22 -d 10.10.10.10 -m state --state ESTABLISHED -j ACCEPT - This rule accepts TCP packets originating from port 22 (SSH) destined for 10.10.10.10, but only if they belong to an already established connection (ESTABLISHED).
Effectively, these rules allow a response to an incoming SSH connection, but prevent the system from initiating an SSH connection to 10.10.10.10.
Key Takeaways
Utilizing connection states allows for precise control over network traffic, enabling secure and tailored communication policies. This is particularly important when managing access to sensitive services like SSH.
Preserving iptables Modifications
Alterations made to your iptables rules are not permanent and will be lost upon the next service restart. To avoid this, a specific command must be run to store these configurations.
The exact command varies based on the Linux distribution being used.
Saving Rules on Ubuntu
On Ubuntu systems, the following command is utilized to save the current iptables configuration:
sudo /sbin/iptables-save
Saving Rules on Red Hat and CentOS
For systems running Red Hat or CentOS, one of the following commands can be employed to preserve the iptables rules:
/sbin/service iptables save
Alternatively, you can use:
/etc/init.d/iptables save
Executing either of these commands ensures that your iptables settings are retained even after a system reboot or service restart.
Iptables Commands
To view the currently established iptables rules, utilize the following command:
iptables -L
Employing the -v flag will display detailed packet and byte counts. Furthermore, the -n option ensures that all outputs, including hostnames, protocols, and networks, are presented numerically.
All existing rules can be removed by executing the flush command.
iptables -F
This effectively resets the firewall configuration.
Common Linux Commands
Below is a categorized listing of frequently used Linux commands:
- Files: tar, pv, cat, tac, chmod, grep, diff, sed, ar, man, pushd, popd, fsck, testdisk, seq, fd, pandoc, cd, $PATH, awk, join, jq, fold, uniq, journalctl, tail, stat, ls, fstab, echo, less, chgrp, chown, rev, look, strings, type, rename, zip, unzip, mount, umount, install, fdisk, mkfs, rm, rmdir, rsync, df, gpg, vi, nano, mkdir, du, ln, patch, convert, rclone, shred, srm, scp, gzip, chattr, cut, find, umask, wc, tr
- Processes: alias, screen, top, nice, renice, progress, strace, systemd, tmux, chsh, history, at, batch, free, which, dmesg, chfn, usermod, ps, chroot, xargs, tty, pinky, lsof, vmstat, timeout, wall, yes, kill, sleep, sudo, su, time, groupadd, usermod, groups, lshw, shutdown, reboot, halt, poweroff, passwd, lscpu, crontab, date, bg, fg, pidof, nohup, pmap
- Networking: netstat, ping, traceroute, ip, ss, whois, fail2ban, bmon, dig, finger, nmap, ftp, curl, wget, who, whoami, w, iptables, ssh-keygen, ufw, arping, firewalld
RELATED: Top Linux Laptops for Developers and Enthusiasts




