Sign In
Sign In

iptables: Overview and Practical Use

iptables: Overview and Practical Use
Hostman Team
Technical writer
Network
05.11.2024
Reading time: 11 min

The iptables utility allows you to manage the network firewall in Linux distributions. iptables is a popular command-line utility for interacting with the built-in Linux kernel firewall called Netfilter, which has been included in the Linux kernel since version 2.4. 

In this article, we will examine how iptables works and go through practical usage examples.

Installing iptables

As mentioned, iptables is included in nearly all Linux distributions, from the most common (Ubuntu, Debian, RHEL) to distributions like openSUSE, Arch Linux, Gentoo, and others. First, let's check if iptables is already installed on your server by displaying its version with the command:

iptables --version

If this command returns a version number, iptables is already installed on the system. However, if you see the message iptables: command not found, you’ll need to install it manually. Below are instructions for installing iptables using package managers across various Linux distributions. Alternatively, you can compile and install iptables from the source code.

APT

For APT-based distributions (Ubuntu/Debian/Linux Mint/Kali Linux), use the command:

apt -y install iptables

RPM

For RPM-based distributions (CentOS, Fedora, Red Hat Enterprise Linux, ALT Linux), use one of the following commands:

For the YUM package manager:

yum -y install iptables

For the DNF package manager:

dnf -y install iptables

Pacman

For Pacman-based distributions (Arch Linux, ArchLabs, Manjaro), use the command:

pacman -S iptables

All commands must be run as the root user or as a regular user with sudo privileges.

How iptables Works

iptables operates using a system of rules. These rules control incoming and outgoing traffic, organized into chains that either allow or block traffic.

A more detailed breakdown of how iptables works is as follows:

  • Network packets pass through one or more chains.
  • As a network packet moves through a chain, each rule in that chain is applied to it. During this process, the packet is checked against specified criteria. If it does not meet a criterion, a specific action is applied to it. These actions can include allowing or blocking traffic, among other operations.

Key iptables Terminology

While working with iptables, you may encounter the following terms:

  • Chain: A sequence or set of rules that determine how traffic will be handled.
  • Rules: Defined actions that contain criteria and a target or goal.
  • Module: An added feature that provides extra options for iptables, allowing for more extensive and complex traffic filtering rules.
  • Table: An abstraction in iptables that stores chains of rules. iptables includes the following tables: Security, Raw, NAT, Filter, and Mangle. Each table has a specific function, described below.

iptables Tables

Filter Table

The Filter table is the default table, using three chains: OUTPUT, FORWARD, and INPUT.

  • INPUT: Controls incoming connections. For instance, this might manage incoming SSH connections.
  • FORWARD: Manages incoming connections not directed to the local device, typically used on a router.
  • OUTPUT: Controls outgoing connections, such as navigating to a website using a browser.

NAT Table

The NAT (Network Address Translation) table includes three chains: PREROUTING, POSTROUTING, and OUTPUT.

  • PREROUTING: Determines the destination IP address of a packet.
  • POSTROUTING: Alters the source IP address.
  • OUTPUT: Changes the target address of outgoing packets.

Mangle Table

The Mangle table is used to modify packet IP headers.

Raw Table

The Raw table provides a mechanism for marking packets to bypass connection tracking.

Security Table

The Security table enables interaction with various OS security mechanisms, such as SELinux.

iptables Rules

The rules in iptables are designed to control incoming and outgoing network traffic. Rules can also be used to configure port forwarding and create protocol-specific rules.

Each rule is made up of criteria and a target. The criteria of a rule are matched, and the specified actions are applied to the target object. If a packet doesn’t match a rule’s criteria, the next rule is processed. The decisions made by iptables are called actions. Below is a list of key actions for handling connections:

  • ACCEPT: Opens (allows) the connection.
  • DROP: Closes the connection without sending a response to the client.
  • QUEUE: Sends the packet to a queue for further processing by an external application.
  • RETURN: Returns the packet to the previous rule, stopping the processing of the current rule.
  • REJECT: Blocks the connection and sends an error message in response.
  • DENY: Drops the incoming connection without sending a response.
  • ESTABLISHED: Marks an already established connection, as the session has already received at least one packet

Practical Application of iptables

Let's look at using iptables in practice. All the commands below will work on any Linux distribution. iptables commands must be run as the root user or a regular user with sudo privileges.

To display the current iptables configuration (including all existing rules), use the command:

iptables --list

85c00f9e 64b3 4cea 9647 13304c7bb8c6

For a more detailed output, which includes the number and size of processed packets in the INPUT, FORWARD, and OUTPUT chains, along with IP addresses and port numbers in numeric format, use:

iptables --line-numbers -L -v -n

Ee0b2682 A15a 4737 Ad14 F4f1ebefd20e

You can also specify a specific chain to display rules for just that chain, such as:

iptables -L INPUT
iptables -L FORWARD
iptables -L OUTPUT

Initially, iptables does not create or store any rule chains, so the output of these commands may be empty.

Blocking IP Addresses

To block a specific IP address, add a rule to the INPUT chain and specify the appropriate table. In the command below, the table is explicitly set. If the -t option is omitted, the rule is added to the default Filter table. For example, to block the IP address 10.0.36.126:

iptables -t filter -A INPUT -s 10.0.36.126 -j REJECT

This command uses the following options:

  • -t: Specifies the table for the rule.
  • -A: Adds the rule to the specified chain, in this case, the INPUT chain.
  • -s: Specifies the source IP address to which the action applies.
  • -j: Specifies the action to take; here, traffic is rejected (action REJECT).

To block an entire subnet, specify it with the -s option:

iptables -A INPUT -s 10.0.36.0/24 -j REJECT

Or, you can specify the subnet mask in full format:

iptables -A INPUT -s 10.0.36.0/255.255.255.0 -j REJECT

To block outgoing traffic to a specific IP address, use the OUTPUT chain and the -d option:

iptables -A OUTPUT -d 10.0.36.126 -j REJECT

Blocking Ports

Ports can be blocked by specifying them directly. This is done with the --dport option, which designates the port of the service. Instead of a port number, you can use the service name. You must specify the protocol as well. For example, to block SSH connections from host 10.0.36.126 using the TCP protocol:

iptables -A INPUT -p tcp --dport ssh -s 10.0.36.126 -j REJECT

For the UDP protocol, use:

iptables -A INPUT -p udp --dport ssh -s 10.0.36.126 -j REJECT

Alternatively, to block SSH connections from 10.0.36.126 using the SSH service port (22), use:

iptables -A INPUT -p tcp --dport 22 -s 10.0.36.126 -j REJECT

To block SSH connections from any IP address over TCP:

iptables -A INPUT -p tcp --dport ssh -j DROP

Allowing an IP Address

To allow traffic from a specific IP address, use the ACCEPT action. In the example below, all traffic from the IP address 10.0.36.126 is allowed:

iptables -A INPUT -s 10.0.36.126 -j ACCEPT

To allow traffic from a specific range of IP addresses, for example, from 10.0.36.126 to 10.0.36.156, use the iprange module and the --src-range option:

iptables -A INPUT -m iprange --src-range 10.0.36.126-10.0.36.156 -j ACCEPT

Here:

  • iprange: A module for working with IP address ranges.
  • --src-range: Specifies the source IP address range.

To perform the reverse operation (allowing all traffic from the server to a specific IP range from 10.0.36.126 to 10.0.36.156), use the --dst-range option:

iptables -A OUTPUT -m iprange --dst-range 10.0.36.126-10.0.36.156 -j ACCEPT
  • --dst-range: Specifies the destination IP address range.

Opening Ports

To open a port, specify the protocol using the -p option. Supported protocols include tcp, udp, etc. A full list of supported protocols can be found in /etc/protocols:

cat /etc/protocols

Specify the port using the --dport option. You can use either numeric values or service names. The ACCEPT action is used to open ports.

To open port 22 for TCP traffic from IP address 10.0.36.126:

iptables -A INPUT -p tcp --dport 22 -s 10.0.36.126 -j ACCEPT

To open multiple ports at once, use the multiport module and the --dports option, listing the ports separated by commas. For example, to open ports 22, 80, and 443 over TCP from IP address 10.0.36.126:

iptables -A INPUT -p tcp -m multiport --dports 22,80,443 -s 10.0.36.126 -j ACCEPT
  • multiport: A module for managing multiple ports simultaneously.
  • --dports: Specifies multiple ports, unlike --dport, which supports only a single port.

Blocking ICMP Traffic

One commonly used feature in iptables is blocking ICMP traffic, often generated by the ping utility. To block incoming ICMP traffic, use the following command:

iptables -A INPUT -j DROP -p icmp --icmp-type echo-request

Image7

This command will prevent the ping command from receiving a response without displaying an error message. If you want to display an error message like "Destination Port Unreachable," replace the DROP action with REJECT:

iptables -A INPUT -j REJECT -p icmp --icmp-type echo-request

123

Allowing ICMP Traffic

To allow previously blocked ICMP traffic, run the following command:

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

However, it’s important to note that if ICMP traffic was previously blocked with this command:

iptables -A INPUT -j DROP -p icmp --icmp-type echo-request

and then allowed with:

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

the ICMP traffic will still be blocked, as the drop rule will be the first rule in the INPUT chain.

Blocking Traffic by MAC Address

In addition to IP addresses, traffic can be blocked based on the device’s MAC address. Below is an example to block traffic from a device with the MAC address 00:0c:29:ed:a9:60:

iptables -A INPUT -m mac --mac-source 00:0c:29:ed:a9:60 -j DROP
  • mac: A module for working with device MAC addresses.
  • mac-source: Specifies the MAC address of the device.

Allowing Traffic by MAC Address

To allow traffic from a specific MAC address, use this command:

iptables -A INPUT -m mac --mac-source 00:0c:29:ed:a9:60 -j ACCEPT

Blocking traffic by MAC address with iptables will only work if the devices are on the same network segment. For broader use cases, blocking traffic by IP address is generally more effective.

Allowing Traffic on the Loopback Interface

Traffic on the loopback interface can also be controlled. To allow incoming traffic on the loopback interface, use:

iptables -A INPUT -i lo -j ACCEPT

For outgoing traffic on the loopback interface, the command is:

iptables -A OUTPUT -o lo -j ACCEPT

Restricting Network Access by Schedule

One of the useful features of iptables is the ability to temporarily allow or restrict traffic to specific services or ports based on a schedule. For example, let’s say we want to allow incoming SSH access only on weekdays, Monday through Friday, from 9 AM to 6 PM. The command would look like this:

iptables -A INPUT -p tcp --dport 22 -m time --timestart 09:00 --timestop 18:00 --weekdays Mon,Tue,Wed,Thu,Fri -j ACCEPT
  • time: Module for working with time-based rules.
  • timestart: Specifies the start time for the rule.
  • timestop: Specifies the end time for the rule.
  • weekdays: Specifies the days of the week when the rule will be active, separated by commas. Supported values are: Mon, Tue, Wed, Thu, Fri, Sat, Sun, or numbers 1 to 7.

Saving iptables Rules

By default, user-created iptables rules are not saved automatically. This means that the rules are cleared after a server reboot or shutdown. To save the rules, install the iptables-persistent package with the following command:

apt -y install iptables-persistent

During the installation, two dialog boxes will appear, allowing you to save the current rules to /etc/iptables/rules.v4 for IPv4 and /etc/iptables/rules.v6 for IPv6.

To manually save all rules for the IPv4 protocol, use:

iptables-save > /etc/iptables/rules.v4

For IPv6 rules, use:

ip6tables-save > /etc/iptables/rules.v6

This method has a significant advantage: saved rules can be restored from the file, which is helpful, for example, when transferring rules to another host. To restore previously saved rules, run:

iptables-restore < /etc/iptables/rules.v4

If executing this command on a different host, transfer the rule file first and then execute the restore command.

Deleting Rules in iptables

You can delete rules in iptables using several methods.

Deleting a Specific Rule

One way to delete a rule is to target a specific rule in a chain using its line number. To display the rule numbers, use:

iptables -L --line-numbers

Image10

For example, in the INPUT chain, we might see two rules that open ports 80 and 443 over TCP for IP addresses 10.0.36.126 (rule number 1) and 10.0.36.127 (rule number 2). To delete rule number 2, use:

iptables -D INPUT 2

Then, display the list of all current rules to verify:

iptables -L --line-numbers

Rule number 2 should now be removed successfully.

Image1

Deleting All Rules in a Specific Chain

You can also delete all rules in a specific chain at once. For example, to clear all rules in the OUTPUT chain:

iptables -F OUTPUT

Deleting All Rules

To delete all rules across all chains, simply run:

iptables -F

Use caution with this command, as it will remove all existing rules, including potentially essential ones.

Conclusion

In summary, iptables is a powerful tool for managing the built-in firewall in Linux-based operating systems. Its extensive features and modular support allow flexible configuration for controlling network traffic.

For more detailed information on iptables, consult the official documentation or use the man iptables command in Linux-based systems.

Network
05.11.2024
Reading time: 11 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us