Configuring Linux Firewall (original) (raw)

Last Updated : 11 May, 2026

A Linux firewall is a critical security layer that monitors and controls network traffic, protecting your system from unauthorized access and potential threats. By defining rules, it ensures only legitimate traffic passes while blocking harmful connections. Linux provides tools like iptables and firewalld to effectively manage and secure network communications.

Working of Linux Firewall

A Linux firewall monitors network traffic by inspecting each packet that enters or leaves the system. It applies predefined rules to decide whether the traffic should be allowed, blocked, or redirected, ensuring that only legitimate connections pass through while protecting the system from unauthorized access and attacks. The packet filtering process follows these steps:

**Note: Running firewall commands usually requires sudo privileges.

Method 1: Configuring Firewall with iptables

iptables is a powerful Linux utility for managing network traffic. It allows system administrators to filter packets, block unwanted connections, and define custom security rules. This method is best suited for advanced users or those managing complex networks.

How iptables Works

iptables operates using a three-tier structure

1. Tables

Tables are logical groupings of chains in iptables. Each table is designed for a specific type of packet processing, which allows precise control over network traffic. There are four commonly used tables:

2. Chains

Chains are ordered sequences of rules within a table. Each chain processes packets in a specific direction or scenario. In the filter table, there are three default chains:

3. Rules

Rules are the instructions in iptables that determine how packets should be handled. Each rule contains conditions (criteria) and an action (target). Common actions include:

**Note: Rules are evaluated from top to bottom in a chain. Once a packet matches a rule, the corresponding action is applied, and remaining rules are skipped. Proper ordering is crucial; for instance, an ACCEPT rule must come before a DROP rule for the same IP or port, otherwise the packet may be blocked prematurely.

Step 1: Check Current Rules

Before modifying your firewall, it’s important to see the rules currently in place. Most Linux systems start with no predefined rules, but checking ensures you know the current state.

**Command:

sudo iptables -L

**Output:

Step 2: Clear Existing Rules

Before creating new rules, it’s best to flush existing ones to avoid conflicts. This step resets the chains to a clean state.

**Command:

sudo iptables -F

Step 3: Set Default Policies

Default policies define what happens to packets that do not match any rule in a chain. Setting strict defaults ensures unrecognized traffic is handled safely.

**Command:

sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

Step 4: Allow Essential Traffic (ACCEPT Rule)

To allow essential traffic (such as SSH) while blocking others, you must explicitly accept packets before DROP rules. This ensures important traffic is processed first.

**Syntax:

sudo iptables [-A | -I] -s -p --dport -j

**Note: Always insert ACCEPT rules before DROP rules, otherwise they may be blocked.

**Example: Allow SSH Traffic from a Specific IP

Suppose we want to allow SSH traffic (default port 22) only from the network 192.168.1.3 while other traffic from this IP is blocked.

**Command:

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

This command checks for packets:

**Output:

Troubleshooting ACCEPT Rules

Sometimes, the above command may not allow the packets.

Fix: Insert Rule at the Top

**Command:

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

Check the iptables configuration:

**Command:

sudo iptables -L

**Output:

Step 5: Block Unwanted IPs

To protect your system, you can deny access from known malicious or unwanted IP addresses.

**Syntax:

sudo iptables [-A | -I] -s -j

**Example: Block a Specific IP

Let's assume we want to block the traffic coming from an IP address 192.168.1.3.

**Command:

sudo iptables -A INPUT -s 192.168.1.3 -j DROP

**Optional: Logging Before Dropping

It’s often useful to log traffic before dropping it to monitor potential attacks:

sudo iptables -A INPUT -s 192.168.1.100 -j LOG --log-prefix "Dropped packet: "
sudo iptables -A INPUT -s 192.168.1.100 -j DROP

**Verify Command:

sudo iptables -L

**Output:

Step 6: Deleting a Rule (Optional)

If you want to delete the rule which accepts the traffic, Please follow the below example to understand it properly:

**Syntax:

sudo iptables -D chain_name rule_number

**Example:

Delete the rule that accepts traffic to port 22

**Command:

sudo iptables -D INPUT 1

**Note: Rule numbers start from 1 in the iptables -L --line-numbers listing.

**Output:

Step 7: Saving your Configuration

Saving your iptables configuration is optional on a personal computer, but it is highly recommended on a server. If the server restarts or crashes, unsaved rules will be lost, potentially leaving your system unprotected. The easiest way to persist your firewall rules is by using the iptables-persistent package.

**Install iptables-persistent

You can install it from Ubuntu’s default repositories:

**Command:

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

**Save Your Configuration

Once installed, save your current iptables rules with:

sudo invoke-rc.d iptables-persistent save

Method 2: Configuring Firewall with firewalld

firewalld simplifies firewall management by using zones, which are collections of rules that apply to network interfaces. Common zones include public, work, and home. Zones allow you to define different trust levels for different networks.

Step 1: Install firewalld

Install firewalld and start the service:

**Command:

sudo apt-get install firewalld
sudo systemctl start firewalld
sudo systemctl enable firewalld

Step 2: Assign Network Interfaces to Zones

Zones are assigned to network interfaces to define the level of trust.

**Example: Assign interface eth0 to the public zone:

**Command:

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

**Apply changes immediately (reload rules):

sudo firewall-cmd --reload

Step 3: Allow Services in Zones

You can allow predefined services (like HTTP, SSH) within specific zones.

**Example: Permit HTTP traffic in the public zone:

**Command:

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

**Note: You can also allow other common services, like ssh, https, smtp using the same command.

Step 4: View Active Zones and Rules

Check which zones are active and what rules are applied:

**Command:

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

Step 5: Example Use Case

You can create a home zone that allows only trusted devices while blocking all external access. Assign your home network interface to this zone and allow only necessary services like SSH or HTTP.

sudo firewall-cmd --zone=home --add-interface=eth1 --permanent
sudo firewall-cmd --zone=home --add-service=ssh --permanent
sudo firewall-cmd --reload

Method 3: Configuring Firewall with UFW (Uncomplicated Firewall)

UFW is a beginner-friendly firewall tool for Linux, ideal for quickly securing a personal system. It provides a simple command-line interface to manage firewall rules without the complexity of iptables.

Step 1: Enable UFW

Activate UFW to start filtering traffic:

**Command:

sudo ufw enable

**Note: If connected via SSH: make sure SSH is allowed first, otherwise you may lock yourself out.

**Optional Safety Tip:

This ensures you maintain remote access before enabling the firewall.

sudo ufw allow ssh
sudo ufw enable

Step 2: Allow Specific Services

Permit trusted services to pass through the firewall.

**Example: Allow SSH traffic:

**Command:

sudo ufw allow ssh

Step 3: Block Traffic to Specific Ports

You can deny traffic to ports that should not be accessed.

Example: Block traffic to port 8080:

**Command:

sudo ufw deny 8080

Step 4: View Firewall Status and Rules

Check the current UFW status and active rules:

**Command:

sudo ufw status verbose

Additional Useful Commands

**1. Enable Logging: Track blocked or allowed connections

sudo ufw logging on
sudo ufw logging high # For detailed logs

**2. Delete Rules: Remove specific rules

sudo ufw delete allow ssh
sudo ufw delete deny 8080

**3. Reset UFW: Clear all rules and restore defaults

sudo ufw reset

Common Mistakes to Avoid

1. Not Saving Rules

Forgetting to save changes can result in loss of firewall configurations after a reboot. Always persist your rules using tools like iptables-persistent (iptables), firewalld --permanent, or UFW’s built-in persistence.

2. Over-Blocking Traffic

Be careful when applying DROP rules or restrictive default policies. Overly strict rules can lock you out of your own system, especially SSH access.

3. Misapplying Zones (firewalld)

Ensure network interfaces are assigned to the correct zone. Assigning an interface to the wrong zone may block legitimate traffic or expose your system unnecessarily.

Tips for Effective Firewall Management

1. Understand Your Network Needs

Identify the services and ports your system actually requires and block everything else. This minimizes potential attack surfaces.

2. Use Logging for Monitoring

Enable logging to track allowed and blocked traffic, which is useful for troubleshooting and security auditing.

**For firewalld:

**Command:

sudo firewall-cmd --set-log-denied=all

**For iptables: Use the LOG target to record dropped packets.

**Command:

sudo iptables -A INPUT -s -j LOG --log-prefix "Dropped packet: "

3. Test Firewall Rules

Use tools like nmap to scan your system and verify that only intended ports and services are open. Testing ensures rules are applied correctly and no unintended access exists.

4. Automate Rule Application

Use scripts or automation tools (like Ansible or system startup scripts) to consistently apply firewall rules across reboots or multiple systems. This reduces manual errors and ensures consistency.