How to Manage Linux System Routing Rules With Iptables

December 5th, 2022
How to Manage Linux System Routing Rules With Iptables

Iptables is a user-space utility program for managing firewall rules on a Linux kernel. It is a powerful security tool that keeps your system safe by blocking undesired network traffic, allowing expected traffic, redirecting packets to other TCP/UDP ports, and warding off DDoS attacks among others.

How Does Iptables Work?

Iptables uses filters organized into tables that contain a set of rules called chains that determine how network traffic packets are treated. Iptables monitors traffic flowing to and from a Linux server and checks to see if a connection or network packet matches a rule. If a connection is matched to a rule, a specific action is applied to the data packet based on the rule chain. If no rule is found, the default policy configured is applied.

In this tutorial, you will learn how to manage the Linux firewall using Iptables.

How To Install Iptables on Linux

Iptables comes installed by default on most modern Linux distributions including Ubuntu, Debian, RHEL, Rocky Linux, and AlmaLinux.

In case Iptables is not installed on your distribution, here’s how you can get started.

Iptables For Ubuntu / Debian

If you are running a Ubuntu / Debian server, install Iptables by running the following commands:

sudo apt update
sudo apt install iptables 

Once installed, you can confirm if Iptables is installed using the command:

iptables --version

OR

iptables -V

iptables --version

NOTE:

Since Ubuntu 22.04 nf_table has replaced iptables as the default firewall backend system.

Nftables ships with numerous benefits in terms of flexibility and performance when defining and deploying firewall rules, especially for systems using both IPv4 and Ipv6. The traditional Iptables utility now configures the nftables kernel backend, while the new nft userspace tool allows the creation of more flexible rules not currently supported by iptables.

Iptables For RHEL / CentOS Stream / Fedora Rocky / AlmaLinux

If you are running a modern RHEL system or a Red Hat derivative, follow the steps outlined.

First, update the packages:

sudo dnf update

Next, install iptables using the following command:

sudo dnf install iptables-services

After successful installation, verify that iptables is installed:

rpm -qa | grep -i iptables-services

Then start and enable Iptables in order to start upon a reboot

sudo systemctl start iptables
sudo systemctl enable iptables

Finally, confirm that iptables is running

sudo systemctl status iptables

Exploring Iptables Chain Rules

At a high-level, Iptables is made up of multiple tables which contain multiple chains.

A chain is a set of built-in or user defined rules.

Rules contain criteria and a target which determine how incoming and outgoing packets are treated.

If a criterion is matched, an action is executed based on the values specified on the target. If not matched, it moves on to the next rule.

In a nutshell, Iptables takes the following structure:

Iptables -> Tables -> Chains -> Rules.

Iptables provides the following salient built-in tables.

FILTER TABLE

This is the default table that provides the following built-in chains:

INPUT - Intended for packets coming to the local server.

OUTPUT - Intended for outbound packets. These are locally generated data packets that are heading out of the server.

FORWARD - This is a rule intended for a data packet routed to another NIC (Network Interface Card) on the server. It's meant for packets routed through the server.

NAT TABLE

This is a table for packets that are intended to initiate a new connection to the system.

PREROUTING – Alters inbound packets as soon as they get access to the system.

POSTROUTNG - Alters data packets after routing. In this case, packet translation occurs when the packets are outbound.

OUTPUT - This is a chain for altering locally generated data packets.

MANGLE TABLE

This is a table that is used for specialized packet alteration. It comprises the following five chains:

INPUT - Alters incoming network packets targeted for the host.

OUTPUT - Alters locally-generated network packets before they leave the host.

FORWARD — Alters network packets routed through the host.

PREROUTING — Alters incoming network packets before they are routed.

POSTROUTING — Alters network packets before they head out of the system.

Iptables Target Values

When a data packet matches a rule, it is assigned one of the following target values:

ACCEPT: Allows the packet to have entry to the system

DROP: Blocks entry of the packet to the system

RETURN: Prevents the packet from going through a chain and, instead, instructs it to go back to the previous chain.

Let’s now focus on some of the useful and widely used iptables commands used for managing firewall rules.

List Iptables Firewall Rules

To list all the available firewall rules, run the command:

sudo iptables -L -n -v

Once the command is executed, you will get output that resembles what we have below. It’s worth noting that since you are starting on a clean slate, you won’t get any user-defined rules printed on the terminal.

List iptables firewall rules

Let’s have a look at the command options:

-L or --list: Lists all the firewall rules in all the chains.

-n or --numeric: Displays the numeric output of addresses and ports.

-v or --verbose: Prints out verbose output.

To view rules for a specific table, pass the -t option followed by the name of the table. For example, to check the rules defined in the NAT table, run the following command:

sudo iptables -L -v -n -t nat

Check iptables rules for nat table

To check the rules defined in the filter table execute the command:

sudo iptables -L -v -n -t filter

For the mangle table, run

sudo iptables -L -v -n -t mangle

How To Define Iptables Rule Chains

Creating an Itables rule simply implies appending a new rule to the chain. To achieve this, you need to pass the -A flag (Append) after the iptables command like so:

 sudo iptables -A <chain> -i <interface> -p <protocol (tcp/udp) > -s <source> --dport <port no.> -j <target>

The -A (append) flag instructs iptables that you are adding a new rule to a chain. Here are some of the options that are used alongside the append option:

-p (protocol) - This option specifies the network protocol on which the filtering process will take place. Examples include TCP and UDP to mention a few.

-i (interface)- Refers to the physical network interface where packet filtering will occur. For example, eth0, enp0s3, ens33, etc.

-s (source) - This is the IP address or FQDN ( Fully Qualified Domain Name ) from which the traffic comes.

--dport (--destination-port ) - This stands for the destination port. It matches the target port of the connection.

-j (target) - This is the target of the rule. It specifies the action to be taken if the packet matches a rule. A target can be a built-in target ( such as ACCEPT, DROP, RETURN ) or a user-defined chain which determines how the packets will be treated.

If you do not use the -t flag with the iptables command, it will use the default filter table type.

Block an IP Address on Iptables

In case you detect unusual or suspicious behavior from an IP address, you can block it using the following command where xxx.xxx.xxx.xxx is the IP address of the remote host.

sudo iptables -A INPUT -s xxx.xxx.xxx.xxx -j DROP

In addition, you can specify a protocol, for instance, TCP using the -p option.

For example, to block TCP traffic coming from IP 173.82.232.55, run the command:

sudo iptables -A INPUT -p tcp -s 173.82.232.55 -j DROP

Block traffic from an IP address

Unblock an IP Address on Iptables

To unblock traffic from an IP address, pass the -D or --delete option as shown. If you had specified the protocol when blocking the traffic from the remote host, remember to specify it again in the command.

sudo iptables -D INPUT -p tcp -s 173.82.232.55 -j DROP

Remove blacklisted IP address

Open a Port(s) On Iptables

To allow or open a single port in Iptables, run the following command where xxxx is the port number.

sudo iptables -A INPUT -p tcp --dport xxxx -j ACCEPT

For example, to allow the default MySQL port 3306, run the command:

sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

To confirm that the rule has been applied, list the Iptables rules as shown.

sudo iptables -L

List iptables rules

To open multiple ports in one command, list the ports separated by a comma as follows.

sudo iptables -A INPUT  -p tcp -m multiport --dports 22,80,443,3389 -j ACCEPT

Iptables open multiple ports

Allow a Network subnet On A Particular Port In Iptables

Sometimes, you might want to allow certain connections on a specific port to a specific network subnet. Suppose you want to limit incoming SSH connections only to the 192.168.40.0/24 subnet.

You can achieve this using the command:

sudo iptables -A INPUT -p tcp -d 192.168.40.0/24 --dport 22 -j ACCEPT

Iptables allow traffic from a subnet

To allow outgoing SSH connection to the same network range, run the command:

sudo iptables -A OUTPUT -p tcp -d 192.168.40.0/24 --dport 22 -j ACCEPT

Allow outbound SSH connections to an IP range

Block a Port(s) On Iptables

To block or drop incoming packets from a specific port, use the following syntax where xxxx is the port number.

sudo iptables -A INPUT -p tcp --dport xxxx -j DROP

For example, to block incoming web traffic on port 80, run the command:

sudo iptables -A INPUT -p tcp --dport 80 -j DROP

Block port 80 on iptables

To block the port on a specific network interface, pass the -i flag as shown in the following syntax.

sudo iptables -A INPUT  -i interface-name -p tcp --dport xxxx -j DROP

In the following example, incoming web traffic on port 80 is blocked on the ens33 network interface.

sudo iptables -A INPUT -i ens33 -p tcp --dport 80 -j DROP

Block traffic from port 80 on a specific network interface

To block an outgoing port, replace the INPUT option with the OUTPUT parameter as shown in the following syntax.

sudo iptables -A OUTPUT -p tcp --dport xxxx -j DROP

For example, to block outbound traffic on FTP port 21, run the command:

sudo iptables -A OUTPUT -p tcp --dport 21 -j DROP

Block outgoing traffic on port 21

To block a port only for a specific IP address, for instance, 172.16.10.10, run the command:

sudo iptables -A OUTPUT -p tcp -d 172.16.10.10 --dport 25 -j DROP

Block a port for a specific IP address

Block Incoming Ping Requests on Iptables

For security reasons, you might want to block incoming ping requests from botnets, hackers, or nefarious individuals who might be conducting some reconnaissance on your system to determine whether your system is reachable.

You can block incoming ping requests by using the following command. The -i flag specifies a network interface. In this case it’s ens33.

sudo iptables -A INPUT -p icmp -i ens33 -j DROP

Block incoming ping requests on a specific network interface

Block Access From Specific Mac Addresses on Iptables

You can limit access to your system by blocking a remote system’s mac address using the --mac-source option followed by its mac address as follows.

sudo iptables -A INPUT -m mac --mac-source 00:00:00:00:00:00 -j DROP

Block a specific device on iptables

Flush IPtables Firewall Rules

To start from a clean slate, delete or flush all firewall chains or rules using the following command.

sudo iptables -F

Flush iptables rules

To flush firewall rules for a specific table, specify the table using the -t option as follows. In the examples below, we are flushing the firewall rules for the NAT and MANGLE filters.

sudo iptables -t nat -F
sudo iptables -t mangle -F

Save Iptables Firewall Rules

To save the chain rules that you have defined and make them persistent after a reboot, use the iptables-save command as shown. In this example, we have saved the firewall rules in the iptables.rules file in the home directory.

sudo iptables-save > ~/iptables.rules

Save iptables rules to a file

Restore Iptables Firewall Rules From a File

If you wish to restore firewall rules from your previously created file, use the iptables-restore command. The command takes the following format.

sudo iptables-restore < ~/iptables.rules

Restore iptables rules from a file

Conclusion

Iptables is a powerful security tool that safeguards your Linux system through a set of network traffic management options that control how network packets are routed. This gives you the autonomy to manage the flow of traffic across your Linux Server. For more information regarding Iptables, check out the official documentation.

Winnie is a seasoned Linux Systems administrator, currently specializing in writing technical Linux tutorials. With over seven years of experience in deploying and working with major Linux distributions such as Ubuntu, Debian, RHEL, OpenSUSE, and ArchLinux, she has written detailed and well-written "How to" Linux guides and tutorials. Winnie holds a Bachelor's Degree in Computer Science from Masinde Muliro University, Kenya and resides in Nairobi, Kenya. She is an expert in authoring Linux and DevOps topics involving Docker, Ansible, and Kubernetes. She currently works as a freelance technical writer and consultant. In her previous roles, she worked in the capacity of an IT support specialist and Linux administrator. Her key roles included offering level 1 and 2 support to both in-house and remote staff and managing and monitoring Linux servers.

Start Building Now

Deploy your new Cloud VPS server in 3 minutes starting from $5.83 / month.

We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: 5bc831c3.737