Imagine a small business operating its network without proper security measures. Employees regularly connect to the internet for accessing various websites and applications. If an employee accidentally clicks on a malicious link while browsing, it triggers a malware download and begins to spread across the network. Without any protective mechanisms in place, the network becomes vulnerable to external threats. Cybercriminals could exploit this lack of security to infiltrate the system.
A firewall acts as a protective barrier between a trusted internal network and untrusted external networks. It monitors all the traffic based on predetermined security rules.
Businesses around the globe rely on Linux for their server operations. More than 70% of web servers use Linux, thanks to its flexibility, performance, reliability, cost-effectiveness, and robust security features. Most Linux distributions already come with built-in firewall solutions like iptables and firewalld. Administrators can create specific rules to allow or deny traffic based on various criteria, such as IP addresses and ports.
If your job is to manage and maintain a Linux system, then you should know the Linux firewall configuration. In this guide, we will take a look at different types of Linux Firewalls and also how to configure a Linux Firewall.
Outline
Toggle- What Is A Firewall?
- Types Of Linux Firewalls
- Prerequisites For Configuring Your Linux Firewall
- How To Configure A Linux Firewall?
What Is A Firewall?
As more devices connect to the internet, the risk of cyberattacks increases exponentially. Hackers and cybercriminals constantly look for vulnerabilities in networks, systems, and devices. One of the most effective tools to defend against these threats is a firewall. Firewalls act as gatekeepers that decide which traffic can enter or leave a network.
A firewall is a security system designed to control the flow of network traffic. It monitors both incoming and outgoing data and decides whether to allow or block specific traffic based on a set of predefined rules. These rules often focus on IP addresses, ports, or protocols and act as filters that let only authorized traffic pass through while stopping unwanted or malicious attempts.
Firewalls are often the first line of defense in cybersecurity strategies. Without them, networks remain exposed to a wide range of threats (hacking attempts, malware infections, data breaches, etc.). They can exist as software (installed on a device), hardware (integrated into network infrastructure, such as routers), or a combination of both.
Types Of Linux Firewalls
Linux firewalls hold a special place in the world of cybersecurity. Unlike proprietary systems, Linux firewalls benefit from open-source communities. Linux firewalls are particularly popular in server environments as Linux distros are very common in web servers, cloud computing, and enterprise infrastructure. Large tech companies, data centers, and even governments rely on Linux firewalls to protect sensitive data and applications.
Linux firewalls come in different types and we can organize them into two main groups: user-space utilities and kernel-level components.
User-space firewalls operate above the kernel and allow us to manage firewall rules and policies through software interfaces. The three most widely used user-space firewall tools on Linux are:
- iptables
- nftables
- firewalld
While user-space firewalls operate above the kernel, kernel-level components handle the actual packet filtering and processing. Netfilter is the networking-related framework of the Linux Kernel.
iptables
As per a recent study, iptables remains a primary choice among Linux system administrators for managing packet filtering and NAT. It has a granular control over incoming and outgoing network traffic. Administrators can create, modify, and delete rules for different network protocols and ports. iptables interact with the kernel-level Netfilter framework to filter packets based on the rules defined by the user.
The three primary components of iptables are: rules, chains, and tables.
Rules are statements that define conditions for the packets to trigger an action. For example, a rule could block all traffic from a specific IP address or allow traffic only on port 80 (HTTP). If a packet matches a rule, iptables executes the corresponding action, known as a target. Common targets are:
- ACCEPT: Allows the packet to pass through.
- DROP: Silently drops the packet, preventing it from reaching its destination.
- REJECT: Similar to DROP, but the sender receives an error message.
- SNAT/DNAT: These targets allow for Source NAT and Destination NAT respectively.
Chains are a series of rules that packets are evaluated against. The main chains are:
- INPUT: Applies to packets destined for the host system itself (incoming packets).
- OUTPUT: Used for packets originating from the host system (outgoing packets).
- FORWARD: For packets passing through the machine to another destination (routers and gateways).
In addition to these default chains, you can create custom chains.
A table defines the specific kind of packet filtering or transformation process. The most commonly used tables include:
- Filter Table: Responsible for basic packet filtering tasks. It decides whether to allow or block traffic using chains.
- NAT Table: Used to rewrite packet source or destination addresses. It is typically used for port forwarding.
- Mangle Table: Allows modifying of specific packet header fields. Often used for altering the Type of Service (TOS) or setting the Differentiated Services Code Point (DSCP) values.
- Raw Table: Handles connection tracking.
nftables
nftables are a modern replacement for iptables and address some of its limitations. It simplifies rule management and generally has a better performance. Unlike iptables, which uses multiple tables for different tasks, nftables operates with a unified approach. nftables also supports both IPv4 and IPv6 protocols natively.
firewalld
Another user-space firewall tool is firewalld. It simplifies firewall management for users by providing a higher-level abstraction over iptables and nftables. You can define rules based on zones that represent different trust levels (public, private, and internal networks). One of the main advantages of firewalld is its dynamic rule management where we can modify firewall settings in real-time without restarting the service or interrupting active connections.
Netfilter
Coming to the kernel-level part of the firewall, Netfilter is the core framework that intercepts and processes packets as they pass through the system. Netfilter handles the actual packet filtering, processing, and network address translation (NAT). It works directly with the Linux kernel to apply filtering rules defined by user-space tools like iptables or nftables.
Prerequisites For Configuring Your Linux Firewall
Before configuring a Linux firewall, you need to take some necessary pre-configuration steps such as installing the appropriate firewall tools, verifying that the firewall service is active, etc. The following tables show simple commands for installing iptables, firewalld, and nftables on different Linux distros.
Firewall | Linux Distro | Command |
iptables | Debian-based (Ubuntu) | sudo apt-get install iptables |
Red Hat-based (CentOS, Fedora) | sudo yum install iptables | |
nftables | Debian-based (Ubuntu) | sudo apt-get install nftables |
Red Hat-based (CentOS, Fedora) | sudo yum install nftables |
To preserve your iptables rules even after reboot, you must install the iptables persistent package using the following command:
sudo apt-get install iptables-persistent
If you want a simple firewall management tool, ufw (Uncomplicated Firewall) has an easier command-line interface. It abstracts complex rules into simplified commands. To install ufw, you can use the command sudo apt install ufw.
On CentOS or other Red Hat-based systems, ufw may require additional repositories. Hence, most users opt for firewalld. To install firewalld: sudo yum install firewalld. If you have a Fedora-based system that uses dnf package manager, the command would be: sudo dnf install firewalld.
After installing the firewall tool, you have to verify that the firewall service is active. If the firewall is inactive, none of the configured rules will take effect. To check if iptables is active and view the current rules, use the following command:
sudo iptables -L
This command lists all active rules. If no rules appear, the firewall might be inactive, or no rules have been configured yet.
If you are using firewalld, checking its status is just as simple. Use the following command to verify if firewalld is running:
sudo firewall-cmd –state
If the output shows “running,” then firewalld is active and ready for configuration.
Alternatively, you can also use:
sudo systemctl status firewalld
How To Configure A Linux Firewall?
iptables Commands For Configuring Linux Firewall
1. Listing Current Rules
To view the current rules in iptables:
sudo iptables -L
To get more detailed information (packet and byte counts for each rule):
sudo iptables -L -v
2. Setting Default Policies
To set the default policy of the INPUT chain to drop all incoming traffic:
sudo iptables -P INPUT DROP
To allow all outgoing traffic by default:
sudo iptables -P OUTPUT ACCEPT
3. Enable Loopback Traffic (Localhost)
Loopback traffic occurs when a system communicates with itself through the loopback interface (lo).
To allow incoming loopback traffic:
sudo iptables -A INPUT -i lo -j ACCEPT
This command appends a rule to the INPUT chain.
To permit outgoing loopback:
sudo iptables -A OUTPUT -o lo -j ACCEPT
4. Allow Traffic
To allow HTTP traffic (which operates on port 80):
sudo iptables -A INPUT -p tcp –dport 80 -j ACCEPT
This command appends a rule to the INPUT chain to accept TCP traffic on port 80.
For HTTPS traffic (which operates on port 443)
sudo iptables -A INPUT -p tcp –dport 443 -j ACCEPT
To permit SSH connections (which use port 22)
sudo iptables -A INPUT -p tcp –dport 22 -j ACCEPT
5. Block Specific Traffic
To block all incoming traffic from a particular port or protocol:
sudo iptables -A INPUT -p tcp –dport 25 -j DROP
This command drops all incoming traffic on port 25, which is commonly used for email (SMTP).
6. Control Traffic By IP Address
To accept traffic from a specific IP address:
sudo iptables -A INPUT -s 192.168.1.50 -j ACCEPT
This rule allows all incoming traffic from the IP address 192.168.1.50.
If you need to restrict the rule to a specific protocol, such as TCP:
sudo iptables -A INPUT -p tcp -s 192.168.1.50 -j ACCEPT
To block all traffic from a particular IP address:
sudo iptables -A INPUT -s 192.168.1.50 -j DROP
If you need to reject traffic from a range of IP addresses, you can specify the range using CIDR notation.
sudo iptables -A INPUT -s 192.168.1.0/24 -j REJECT
This command blocks traffic from the entire IP range 192.168.1.0 to 192.168.1.255. Unlike DROP, which silently discards packets, REJECT sends a message back to the sender.
7. NAT Configuration (Port Forwarding)
Port forwarding is commonly used in Network Address Translation (NAT) setups to forward traffic from a specific external port to an internal machine. To forwards traffic arriving on port 8080 of the external interface to port 80 of the internal IP 192.168.1.100:
sudo iptables -t nat -A PREROUTING -p tcp –dport 8080 -j DNAT –to-destination 192.168.1.100:80
The nat table in iptables appends this rule to the PREROUTING chain to handle traffic before it reaches the system.
8. Saving And Loading Rules
Iptables rules are stored in memory, and they reset after a system reboot unless saved. To save the current rules:
sudo iptables-save > /etc/iptables/rules.v4
This command writes the active rules into a file that can be reloaded later.
To restore the saved rules:
sudo iptables-restore < /etc/iptables/rules.v4
You may also need to use iptables-persistent or using a similar service to automatically reload rules during system startup.
9. Deleting Rules
To delete a rule:
iptables -D INPUT 2
This command removes the second rule in the INPUT chain.
Configuring Linux Firewall Using ufw (Uncomplicated Firewall)
Originally developed for Ubuntu, ufw (Uncomplicated Firewall) is a user-friendly frontend tool to the more complex and powerful iptables.
1. Enabling And Disabling ufw
To enable the firewall:
sudo ufw enable
To disable ufw:
sudo ufw disable
2. Checking The Status
To verify if ufw is active or to review its current rules, you can use the status command:
sudo ufw status
If you want a more detailed output, including whether the rules apply to incoming or outgoing traffic, use:
sudo ufw status verbose
3. Allowing And Denying Services Or Ports
If you want to allow incoming traffic on port 80 (HTTP), you would run:
sudo ufw allow 80
Alternatively, you can allow a service by name, such as:
sudo ufw allow http
You can allow or deny service from /etc/services using ufw. Some common services are ssh, smtp, and http.
To deny traffic to a specific port, use:
sudo ufw deny 80
4. Allowing And Denying IP Addresses
To allow all traffic from a particular IP:
sudo ufw allow from 192.168.1.100
If you want to block traffic from an IP:
sudo ufw deny from 192.168.1.100
5. Resetting ufw
If you need to remove all existing rules and start over, the reset command is helpful:
sudo ufw reset
This command deletes all current rules and disables the firewall. After resetting, you must re-enable ufw and add new rules.
6. Deleting Rules
To remove a rule allowing traffic on port 80:
sudo ufw delete allow 80
You can list all rules with ufw status numbered and delete a rule by its number.
7. Limiting Connections
To limit connections on a particular port, such as SSH (port 22):
sudo ufw limit 22/tcp
This command restricts repeated connections from the same IP within a short period to protect against brute-force attacks.
8. Logging Activity
To monitor what the firewall is doing, ufw has a logging feature. You can enable logging with:
sudo ufw logging on
This command starts logging traffic that hits the firewall.
To disable logging:
sudo ufw logging off
Configuring Linux Firewall Using Firewalld
Firewalld is a dynamic firewall management tool for Linux systems that adapts to network changes and allows modifications without service interruptions. It simplifies firewall management through a daemon process with both graphical and command-line interfaces. This tool is popular in Red Hat-based distributions (Fedora, CentOS, and RHEL).
One of the key advantages of Firewalld is its use of zones, which are pre-configured environments with different levels of trust and control. Firewalld supports both IPv4 and IPv6 protocols and integrates with a variety of backend systems.
1. Start And Enable firewalld
Before configuring firewalld, the firewalld daemon must be running. To start firewalld:
sudo systemctl start firewalld
To enable firewalld automatically on every system boot:
sudo systemctl enable firewalld
2. Check The Status Of firewalld
To verify if firewalld is running, you can check its status using:
sudo systemctl status firewalld or sudo firewall-cmd –state
3. List Available Zones And Active Zone
firewalld uses zones to manage traffic. To list all the available zones:
sudo firewall-cmd –get-zones
This command outputs a list of all available zones. Common zones include “public,” “home,” “work,” and “dmz.”
To know which zone an interface belongs to:
sudo firewall-cmd –get-active-zones
4. Assign A Zone To An Interface
Assigning a network interface to a specific zone allows you to control its traffic behavior. To change the zone for an interface:
sudo firewall-cmd –zone=home –change-interface=eth0
5. Open And Close A Port
Opening a port allows traffic for a specific service or application while closing a port stops traffic on that specific service. This is one of the most common firewall operations. To open a port:
sudo firewall-cmd –zone=public –add-port=8080/tcp –permanent
To close a port:
sudo firewall-cmd –zone=public –remove-port=8080/tcp –permanent
To view all currently open ports in a zone:
sudo firewall-cmd –list-ports
6. Reload firewalld Rules
After making changes to the firewall rules, reloading firewalld applies these changes without restarting the entire service. To reload firewalld:
sudo firewall-cmd –reload
7. Add Or Remove A Service
firewalld has predefined services that simplify allowing traffic for common applications like SSH or HTTP.
To add a service:
sudo firewall-cmd –zone=public –add-service=http –permanent
When you no longer need a service, you can remove it from the firewall. To remove a service:
sudo firewall-cmd –zone=public –remove-service=http –permanent
8. Block An IP Address
To block an IP address, you will need to add a rich rule that drops traffic from the specific IP.
sudo firewall-cmd –zone=public –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.100″ drop’ –permanent
Configuring Linux Firewall Using csf (ConfigServer Firewall)
ConfigServer Firewall (csf) is a popular security tool for Linux-based systems to manage incoming and outgoing network traffic. It integrates well with various control panels such as cPanel, DirectAdmin, and Webmin. csf has both command-line interface (CLI) and a web interface for managing firewall rules and it works by configuring iptables.
1. Install csf
- Set The Directory To Download: cd /usr/src
- Download The CSF Package: wget https://download.configserver.com/csf.tgz
- Extract The CSF Package: tar -xzf csf.tgz
- Open The Directory: cd csf
- Install CSF: sh install.sh (or sh install.cpanel.sh in case of cPanel)
2. Start Or Stop csf
To start csf:
sudo csf -s
This command activates csf and begins implementing the firewall rules defined in its configuration files (view configuration file using sudo nano /etc/csf/csf.conf).
To stop csf:
sudo csf -f
Restarting csf is necessary when you make changes to its configuration. To restart csf:
sudo csf -r
To check the current status:
sudo csf -l
3. Allow Or Deny IP Addresses
To allow traffic from a specific IP address:
sudo csf -a 192.168.1.100
To block/deny an IP address:
sudo csf -d 192.168.1.101
4. Remove An IP From Allow Or Deny Lists
To remove an IP address from the allow list:
sudo csf -ar 192.168.1.100
To remove an IP address from the deny list:
sudo csf -dr 192.168.1.101
5. Temporary IP Address Blocking Or Allowing
To temporarily allow an IP address for a specific period:
sudo csf -ta 192.168.1.102 3600
This command allows the IP for 3600 seconds (1 hour). After the time expires, csf automatically revokes the allowance.
To temporarily block an IP address for a specific period (for example, 2 hours or 7200 seconds):
sudo csf -td 192.168.1.103 7200
Configuring Linux Firewall Using OPNsense
OPNsense is an open-source firewall and routing platform initially forked from the popular pfSense project. It is suitable for both home networks and enterprise environments. Unlike many other firewall solutions, OPNsense comes with a modern web interface.
Access The Web Interface
To access OPNsense, connect a computer to the firewall and enter the firewall’s IP address in a web browser. After you log in with your credentials, you’ll see the dashboard.
Configure A Basic Firewall Rule
- In the web interface, navigate to Firewall > Rules.
- Select the interface (e.g., LAN or WAN) where you want the rule to apply.
- Click the Add (+) button to create a new rule.
- Specify the source and destination for the traffic. For example, to allow traffic from a local computer to access the internet, choose the LAN interface, then select “LAN net” as the source and “any” as the destination.
- Choose the desired protocol (e.g., TCP, UDP, or ICMP) and the destination port (e.g., 80 for HTTP or 443 for HTTPS).
- Set the action (Allow/Deny) and save the rule.
- Apply the changes to activate the rule.
NAT / Port Forwarding
- Go to Firewall > NAT > Port Forward.
- Click Add (+) to create a new rule.
- Choose the WAN interface as the “interface” for the rule.
- Set the destination address (your public IP or WAN address).
- In the “Destination Port” field, specify the port you want to forward (e.g., port 80 for HTTP).
- In the “Redirect Target IP” field, enter the internal IP address of the device or server that will receive the traffic.
- Apply the changes and create a firewall rule to allow the forwarded traffic.
Block An IP Address
- Go to Firewall > Aliases. Add a new alias for the IP or range of IPs you wish to block.
- Now, go to Firewall > Rules and select the interface (WAN for external IPs or LAN for internal IPs).
- Click the Add (+) button to create a new rule.
- Set Action to “Block” and use the alias you created as the source or destination.