Configure a Linux Firewall: Three Approaches

Configure a Linux Firewall: Three Approaches

A Linux firewall is crucial for safeguarding your system against unauthorized access and cyber threats. By setting up specific firewall rules, you can manage the traffic that enters and exits your system. Linux provides various tools for firewall management, such as iptables and firewalld, which are effective for securing and controlling your network.

Establishing a firewall on a Linux system is a vital measure to defend against potential intrusions and attacks. Firewalls function as protective barriers between your internal network and external connections, filtering traffic based on established rules. This protection is essential for maintaining the security of your system or server.

This guide will walk you through the process of configuring a firewall in Linux, ensuring that your system remains secure and protected efficiently.

Read More: 4 Linux Distributions That Feel Most Like Windows in 2025

Firewalls: What are They?

A firewall is a security mechanism designed to oversee and regulate both incoming and outgoing network traffic. It serves as a protective barrier between trusted internal networks and untrusted external connections, enforcing established security policies. Firewalls can be deployed in hardware or software forms, with their primary objectives being:

  • Preventing unauthorized access
  • Facilitating legitimate communications
  • Restrict data breaches

Linux Firewall Types

There are several types of firewalls available for Linux, each with its own features and functionalities:

1. iptables

iptables is the most commonly used firewall tool in Linux. It operates by establishing chains of rules that filter network traffic at various points, such as incoming and outgoing connections. This tool functions at both the network layer (Layer 3) and the transport layer (Layer 4).

2. firewalld

firewalld is a more contemporary firewall management tool found in distributions like CentOS, RHEL, and Fedora. It offers a dynamic and user-friendly method for managing firewall rules through the use of zones, making it easier to configure security settings.

3. nftables

nftables serves as the successor to iptables, providing a more efficient and enhanced approach to network traffic filtering. It is designed to replace iptables in newer Linux distributions, offering improved performance and functionality for managing firewall rules.

What are the Workings of a Linux Firewall?

A Linux firewall manages network traffic by applying a set of rules that determine which types of network packets are permitted or blocked. These rules consider several factors, including:

  • IP Address: The origin or destination address of the packet.
  • Port Number: The specific communication port the packet aims to access (for instance, port 80 for HTTP or port 22 for SSH).
  • Protocol: The network protocol being utilized (such as TCP, UDP, ICMP, etc.).
  • Connection State: Whether the packet is part of an existing connection or a new connection request.

When a packet enters or leaves the system, the firewall evaluates it against these rules to decide if it should be allowed through or blocked. If a packet aligns with an “allow” rule, it is permitted to pass; if it corresponds with a “deny” rule, it is blocked.

Firewall Tools

Before diving into configuration, it’s important to familiarize yourself with the common firewall tools available on Linux systems:

1. iptables

iptables is a robust command-line utility used for filtering network traffic. It operates by setting up chains of rules that govern various types of network traffic.

2. UFW (Uncomplicated Firewall)

UFW is a user-friendly interface for iptables, designed to simplify the configuration process for users.

3. firewalld

firewalld is a modern firewall management tool that allows for dynamic configuration. It utilizes zones to establish trust levels for network connections and interfaces, making it easier to manage firewall settings compared to iptables.

4. CSF (ConfigServer Security & Firewall)

CSF is a comprehensive security solution that includes firewall functionalities.

5. ClearOS and OPNsense

These are operating systems focused on firewall capabilities, offering web-based interfaces for easier management.

Comparison table

FeatureEasily NavigableSuitable forDynamic RulesGUI Available
UFWVery EasyBeginnersLimited Yes
firewalldEasyZone-based  managementYesYes
IptablesModerateAdvanced ManagementNoNo

Approach 1: Setup Firewall with iptables

iptables is a sophisticated tool for managing packet filtering and network address translation (NAT). It is best suited for experienced Linux users and system administrators who require fine-grained control over network traffic.

iptables operates using a three-tiered structure:

  1. Tables: These categorize rules based on packet type:
    • INPUT: Packets arriving at the local machine.
    • OUTPUT: Packets originating from the local machine.
    • FORWARD: Packets routed through the machine.
  1. Chains: Within each table, packets traverse a sequence of rules. Processing stops when a matching rule is found, determining the packet’s fate.
  2. Rules: Each rule defines conditions for matching packets and specifies the actions to be taken, such as:
    • ACCEPT: Allow the packet.
    • DROP: Discard the packet silently.
    • REJECT: Discard the packet and send an error message.
    • LOG: Log packet information.
    • JUMP: Redirect the packet to another chain.

Rule order is crucial iptables checks rules from top to bottom. Once a rule is matched, subsequent rules are not evaluated. Therefore, careful rule ordering is essential to prevent unintended consequences.

Step-by-Step Guide

Step 1: Review Current Rules

To begin, examine the current firewall rules by running:

sudo iptables -L
This command displays rules for the INPUT (incoming), FORWARD (forwarding), and OUTPUT (outgoing) chains.

This command displays rules for the INPUT (incoming), FORWARD (forwarding), and OUTPUT (outgoing) chains. If no rules are listed, it means most Linux systems start with no predefined rules.

Columns in the Output:

  • Target: Specifies the action for a packet (e.g., ACCEPT, DROP).
  • prot: Denotes the protocol of the packet (e.g., TCP, IP).
  • source: Shows the packet’s source address.
  • destination: Indicates the packet’s destination address.

Step 2: Reset Existing Rules

To clear all current rules and start with a clean slate, use:

sudo iptables -F

Step 3: Modify Default Chain Policies

The default policy for each chain is typically set to ACCEPT. To change this, use:

sudo iptables -P <Chain_Name> <Action>

Example:
To block traffic being forwarded by your system:

sudo iptables -P FORWARD DROP

This command prevents any traffic from being routed through your system.

Step 4: Add a DROP Rule

Start defining your firewall policies by focusing on the INPUT chain for incoming traffic.

Syntax:

sudo iptables -A/-I <chain_name> -s <source_ip> -j <action>

Example:
To block traffic from IP 192.168.1.3:

sudo iptables -A INPUT -s 192.168.1.3 -j DROP

Explanation:

  • -A INPUT: Appends the rule to the end of the INPUT chain.
  • -I INPUT: Inserts the rule at the top of the chain.
  • -s 192.168.1.3: Filters packets originating from 192.168.1.3.
  • -j DROP: Drops packets matching the criteria.

Check the changes by executing the following command:

sudo iptables -L

As a result,

When you then run sudo iptables -L, the output will reflect this new rule.

Step 5: Add an ACCEPT Rule

To permit traffic on specific ports, such as SSH (port 22), use:

Syntax:

sudo iptables -A/-I <chain_name> -s <source_ip> -p <protocol> --dport <port_number> -j <action>

Example:
Allow packets from 192.168.1.3 using TCP protocol to port 22:

sudo iptables -A INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT

Troubleshooting:
Rules are processed in order. If a DROP rule for 192.168.1.3 precedes the ACCEPT rule, packets will not reach the ACCEPT rule. Fix this by inserting the ACCEPT rule at the top:

sudo iptables -I INPUT -s 192.168.1.3 -p tcp --dport 22 -j ACCEPT

The output will show the current rules in the INPUT chain, and it should look something like this:

If a DROP rule for 192.168.1.3 precedes the ACCEPT rule

Step 6: Remove a Rule (Optional)

To delete a rule, use:

sudo iptables -D <chain_name> <rule_number>

Example:
Remove the first rule in the INPUT chain:

sudo iptables -D INPUT 1

Output

Remove the first rule in the INPUT chain

Step 7: Save Your Configuration

If configuring a firewall on a server, save the settings to prevent loss during a reboot. Install the iptables-persistent package:

sudo apt-get update
sudo apt-get install iptables-persistent

Save the configuration with:

sudo invoke-rc.d iptables-persistent save

Approach 2: Setup Firewall with firewalld

firewalld simplifies firewall management by organizing rules into zones (e.g., public, work, home).

Step 1: Install and Enable

Install firewalld using

sudo apt-get install firewalld.

Start and enable firewalld as a service:

sudo systemctl start firewalld
sudo systemctl enable firewalld

Step 2: Assign Interfaces

Assign network interfaces to specific zones. For example, assign eth0 to the “public” zone using:

sudo firewall-cmd --zone=public --add-interface=eth0 --permanent

Step 3: Allow Services

Permit specific services within a zone. For example, allow HTTP traffic in the “public” zone:

sudo firewall-cmd –zone=public –add-service=http –permanent
sudo firewall-cmd –reload

Step 4: View Status

Check active zones and their associated rules:

sudo firewall-cmd –get-active-zones
sudo firewall-cmd –list-all

The above demonstrated firewalld configuration, including the creation of a “home” zone that restricts access to trusted devices while blocking all external connections.

Approach 3: Setup Firewall with UFW (Uncomplicated Firewall)

This guide demonstrates a simple yet effective approach to securing your personal Linux machine using the user-friendly UFW firewall.

Step 1

Enable UFW: Start by activating UFW with the c.ommand

sudo ufw enable.

Step 2

Allow Essential Services: Permit necessary services, such as SSH, using the command

sudo ufw allow ssh

Step 3

Block Unwanted Traffic: Block traffic to specific ports, like port 8080, with the command

udo ufw deny 8080.

Step 4

Verify Firewall Status: Check the current firewall status using the command

sudo ufw status.

Preventing Common Errors

Transient Rules: Neglecting to save firewall rule changes can result in lost configurations upon system reboot.

Excessive Blocking: Overly restrictive DROP rules can inadvertently block essential traffic, potentially locking you out of the system.

Zone Misconfiguration (firewalld): Inaccurate assignment of network interfaces to firewalld zones can lead to unexpected traffic blocking or exposure.

Read More: How to Use SCP Command on Linux

Essential Tips for Managing Your Firewall

Assess Your Network Requirements: Determine the specific ports and services essential for your system’s operation and block all others.

Implement Robust Logging: Enable logging to monitor both allowed and blocked traffic, facilitating effective troubleshooting. Utilize commands like

 sudo firewall-cmd –set-log-denied=all for firewalld or the LOG target for iptables to record dropped packets.

Thoroughly Test Firewall Rules: Employ tools like nmap to scan your system and verify that only the intended ports are accessible.

Automate Firewall Configurations: Develop startup scripts or leverage tools such as Ansible to streamline and automate the application of firewall rules.

Wrap Up

This guide provides straightforward steps for setting up a firewall on your Linux system and enhancing its security against potential threats. Whether you are configuring basic or complex rules or utilizing UFW or other tools, a properly configured firewall is crucial for system security. Regular updates and consistent monitoring are essential to maintain a secure Linux environment and prevent unauthorized access or cyberattacks.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top