Linux Firewall Security: Pro Tips to Configure Rules, Monitor Traffic & Block Threats

Linux Firewall
InfinitySoftHint Updated Logo

Empower Your Knowledge

We recommend that you study InfinitySoftHint’s helpful and informative blogs so you can enhance your knowledge, stay up to date on the latest technology, read about new, upcoming problems and their solutions, and learn marketing and lead generation tips and ideas.

Table of Contents

A robust firewall can protect your digital fortress. Firewalls protect your domain from digital threats in the vast kingdom of cyber-security. Open-source environments present unique challenges, making Linux system defense extra vital.

Do not worry—we will explain the Linux firewall. This article is for adventurous programmers and covers Linux ecosystem fortification from the basics to the details.

Understanding Firewalls’ Security Importance

Think of firewalls as the security checkpoints at the entrance of our digital network. They are essential for protecting our internal network from the outside world, like the internet.

Firewalls work by examining network traffic and deciding whether to allow or block it based on pre-defined rules. They act as filters for data packets, controlling the flow of information based on factors like:

  • Who is sending the traffic (IP address)
  • Where the traffic is going (IP address and port)
  • The type of communication (protocol)

Modern firewalls are sophisticated and can also:

  • Track ongoing connections (stateful inspection)
  • Analyze the content of the traffic (application-level filtering)
  • Detect and block threats (intrusion prevention)

Essentially, firewalls are a fundamental security measure that helps keep our network safe and secure.

Why Firewalls Matter in 2023?

Cyberthreats have evolved—ransomware, IoT attacks, and cloud breaches demand next-gen defenses. Firewalls remain your first line of defense, but outdated iptables scripts won’t cut it. Modern Linux uses nftablesUFW, and firewalld to combat today’s threats, including:

  • Containerized apps (Docker/Kubernetes)
  • Multi-cloud environments (AWS/Azure)
  • Zero Trust Architecture requirements

Firewalls’ Role in Linux Security

Linux systems rely heavily on firewalls for security. These firewalls control network traffic to prevent unwanted access.

The main tools for Linux firewalls are iptables (older) and nftables (newer). They work by checking network data against a set of rules.

These rules can block or allow traffic based on things like IP addresses and port numbers. This helps protect servers and personal computers from threats.

Tools like firewalld offer an easier way to manage these firewall rules.

In short, Linux firewalls are a vital part of system security, protecting against various cyber threats.

Firewall Types and Operation

Firewall Types and Operation

Firewalls vary in size but usually fall into four categories:

1. Filtering packets

The most straightforward firewall, packet filtering, checks data packets for user-defined rules and admits or rejects them. It decides packet travel permissions at the network level of the OSI model based on source and destination IP addresses, port numbers, and other criteria.

2. Proxy Firewalls

Proxy firewalls interconnect endpoints. They retrieve client resources and hide their identity with their IP address. This firewall enhances security by increasing visibility and modifying network requests.

3. Official Inspection

Stateful inspection (dynamic packet filtering) is a more advanced firewall that monitors current connections to decide which packets to accept. A state table in these firewalls identifies genuine packets in a network conversation.

4. The App Layer

Application-layer firewalls, sometimes called “next-generation firewalls,” block certain apps or files by analyzing sent data. This prevents network intrusion and sensitive data delivery. Due to additional processing, these firewalls may affect network performance.

Cloud & Container Firewalls

AWS/Azure/GCP Security Groups

  • Restrict SSH to your IP only.
  • Use tags to isolate dev/prod environments.

Docker & Kubernetes

  • Block inter-container traffic:
Cloud & Container Firewalls
AWS/Azure/GCP Security Groups
Restrict SSH to your IP only.

Use tags to isolate dev/prod environments.

Docker & Kubernetes
Block inter-container traffic:


docker network create –driver bridge –opt com.docker.network.bridge.enable_icc=false isolated

- Kubernetes Network Policies:  
```yaml  
apiVersion: networking.k8s.io/v1  
kind: NetworkPolicy  
spec:  
  podSelector: { matchLabels: role: db }  
  ingress:  
  - from:  
    - podSelector: { matchLabels: role: api }  
    ports: [ { protocol: TCP, port: 3306 } ]  

Step-by-Step Linux Firewall Setup

Build your firewall now that you understand the different types. Step-by-step instructions for setting up a basic Linux firewall with ‘iptables’:

Step 1. Iptables Installation

First, install ‘iptables’ on Linux. Most distributions include it, but your 

The package manager can install it.

Install iptables in Ubuntu using the `apt-get` command.

sudo apt-get update
sudo apt-get install iptables

Install iptables in Ubuntu using apt-get

An alert guardian watches. After installing your firewall, verify its status to ensure it works correctly. Follow these commands to monitor your Linux firewall:

sudo systemctl status iptables
systemctl to check if service is online

If iptables service is inactive, then you can run it using the following command:

sudo systemctl start iptables

Step 2. Check Current Default Policies

Before changing anything, it’s good to know the current default policies.

sudo iptables -L

iptables default policy in ubuntu

Step 3. Setting Default Policies

By default, iptables firewalls allow all traffic, leaving your system susceptible. Set your default policies to DROP or REJECT to block all traffic until approved.

Set Default Policies to DROP:

DROP silently discards the packet without sending any response.

To set the default policy to drop, you can use the following commands:

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

This will drop all incoming, outgoing, and forwarded packets by default.

On the other hand, REJECT it can not be used as a chain policy.

Step 4. Rulemaking

Write your rules using iptables or a script. Based on your system’s network requirements, accept or prohibit traffic.

To get started with using iptables you must first understand its basic syntax and structure. The following is an example of a simple iptables rule:

sudo iptables -A INPUT -s 192.168.1.0/24 -j ACCEPT

This rule allows all incoming traffic from the specified source IP address range (192.168.1.0/24) to be accepted.

You can also specify a specific port or protocol in the rule, for example:

sudo iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT

This rule specifies that only TCP traffic on port 22 from the specified source IP address range will be accepted.

On the other hand, if you want to block certain traffic, you can use the DROP or REJECT action in your rule. The difference between these two actions is that DROP silently discards the packet without sending any response, while REJECT it sends back an error message to the source indicating that the packet was rejected.

sudo iptables -A INPUT -s 192.168.1.0/24 -j DROP

This rule blocks all incoming traffic from the specified source IP address range.

You can also use REJECT if it meets your requirements.

sudo iptables -A INPUT -s 192.168.1.0/24 -j REJECT

In addition to creating individual rules, you can also create chains to organize and group related rules. This allows for easier management and troubleshooting of your firewall configuration.

When configuring iptables It is important to keep in mind the order in which rules are evaluated. Rules are processed from top to bottom, so the first matching rule will be applied. Therefore, it is important to have more specific rules at the top and more general rules at the bottom.

Step 5. Save Configuration

Once you have created your desired rules, it is important to save them so they can be loaded on system boot. This can be done using the iptables-save command which will save all the current rules in a file. To load these saved rules on system boot, you can use the iptables-restore command.

To save rules use this command:

sudo iptables-save

To restore the rules after reboot use this command:

sudo iptables-restore

Restore Rules on Startup

To ensure that the configured rules on your Ubuntu system persist after a reboot, you can use iptables-persistent. This package is designed to save the current iptables rule configuration into files and restore them at boot time.

Installing iptables-persistent

To install iptables-persistent, open your terminal and run the following command:

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

You may be prompted to confirm the installation, enter y and press Enter to proceed.

While installing the package, you will be asked to save the IPv4 and IPv6 rules configuration files.

Move the selected option to Yes and enter

Here is what it looks like:

iptables-persistent configuration for iptables rules of ipv4

iptables-persistent configuration for iptables rules of ipv6

Once installed, you can configure your desired iptables rules by editing the /etc/iptables/rules.v4 or /etc/iptables/rules.v6 files. These files contain the IPv4 and IPv6 rules respectively.

You view the file to see saved iptable rules, use nano to view the file:

To view ipv4 rules:

sudo nano /etc/iptables/rules.v4

To view ipv6 rules:

sudo nano /etc/iptables/rules.v6

You can write your own rules in this file as described below.

For example, to allow incoming SSH connections on port 22, you can add the following rule:

-A INPUT -p tcp --dport 22 -j ACCEPT

You can refer to the official iptables documentation for more details on configuring rules.

Now you can reboot the System and check the iptables rule again.

Reset Iptables rules and save in the configuration file

Let’s reset iptables the rules and write the changes in iptables the rules configuration file.

sudo iptables -F

To write changes in configuration files for persistence, use this command:

sudo su -c 'iptables-save > /etc/iptables/rules.v4'

Managing Rules for Optimal Security

Managing Rules for Optimal Security

Firewall rules based on numerous parameters affect packet behavior. Linux system security depends on managing these rules. These methods will help you handle firewall rules:

1. Regularly Review Rules

Make sure your firewall meets network security demands via rule audits. Remove outdated or irrelevant rules.

2. Prioritize Rules

Organize rules well. First, matches set the rules handled from the top down. Put critical rules first for faster processing.

3. Use Descriptive Comments

Use comments to clarify your rule sets. Use them to justify regulations and significant changes.

Advanced Threat Defense

Zero Trust Practices

  • Deny-by-defaultsudo nft add chain inet filter input { policy drop \; }
  • Microsegmentation: Isolate VLANs using nftables sets.

Automation & Monitoring

  • Ansible Firewall Rules:
- name: Allow HTTPS  
  community.general.nftables:  
    chain: input  
    rule: 'tcp dport 443 accept'  
    state: present  
  • Fail2ban Integration:
sudo fail2ban-client set sshd banip 192.168.1.100  

6 Proven Fixes for Linux Firewall Performance Issues

Optimize nftables, UFW, and Cloud Rules Like a Pro

1. Streamline Bloated Rule Sets with nftables Sets

Problem: Thousands of individual IP/port rules slow down packet processing.
Solution: Group IPs/ports into nftables sets for O(1) lookup time.

# Create an IP whitelist set  
sudo nft add set inet filter trusted_ips { type ipv4_addr \; }  

# Add IPs to the set  
sudo nft add element inet filter trusted_ips { 192.168.1.10, 10.0.0.5 }  

# Reference the set in rules  
sudo nft add rule inet filter input ip saddr @trusted_ips accept  

Pro Tip: Use dynamic sets with timeout 1h to auto-expire temporary entries.

2. Tame Connection Tracking Overhead

Problemconntrack table overload from NAT/stateful rules causes high CPU.
Fix: Limit table size and shorten timeouts:

# Set max connections (default: 32k)  
echo 65536 > /proc/sys/net/nf_conntrack_max  

# Reduce TCP timeout to 1 hour (default: 5 days!)  
echo 3600 > /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established  

Pro Tip: Monitor usage with sudo conntrack -L | wc -l.

3. Optimize Container Traffic (Docker/Kubernetes)

Problem: Firewall rules interfere with Docker/K8s overlay networks.
Fix: Bypass rules for container interfaces:

# Allow all traffic on Docker's bridge  
sudo nft add rule inet filter input meta iifname "docker0" accept  

# Or whitelist Kubernetes pods  
sudo nft add rule inet filter input ip saddr 10.244.0.0/16 accept  

Pro Tip: Use Calico Network Policies for granular container control.

4. Automate Rule Management with Ansible

Problem: Manual edits lead to messy, unoptimized rules.
Solution: Enforce clean templates via automation:

- name: Apply lean firewall rules  
  community.general.nftables:  
    rules: |  
      table inet filter {  
        chain input {  
          type filter hook input priority 0;  
          ct state established,related accept  
          tcp dport { 22, 80, 443 } accept  
          drop  
        }  
      }  

Pro Tip: Store configs in Git for version control and rollbacks.

5. Audit & Benchmark Rules Regularly

Problem: Hidden inefficiencies in legacy rules.
Fix:

  • Dry-run testssudo nft --check -f /etc/nftables.conf
  • Performance metrics:
# Track rule processing time  
sudo nft --handle --numeric list chain inet filter input  

# Monitor CPU usage  
pidstat -C nftables -l 2 5  

Pro Tip: Use nft monitor trace to identify rarely-hit rules.

6. Leverage Hardware Acceleration

Problem: Software-based filtering bottlenecks gigabit traffic.
Solution: Offload to NIC hardware (if supported):

# Enable XDP acceleration for nftables  
sudo ethtool -K eth0 hw-tc-offload on  

# Check offload capabilities  
ethtool -k eth0 | grep hw-tc  

Pro Tip: Test with iperf3 before/after enabling.

Key Takeaways

  • Replace linear rules with nftables sets for instant lookups.
  • Limit conntrack tables and automate cleanup.
  • Whitelist container networks instead of micro-managing.
  • Use Ansible/Git to enforce clean, versioned rules.
  • Audit monthly with nft --check and conntrack -L.

Modern Linux Firewall Tools: Ditch Iptables

1. nftables (The iptables Successor)

Unified syntax, faster performance, and IPv6/IPv4 dual-stack support. Preinstalled on kernels 3.13+.

Basic Setup Example:

sudo systemctl enable --now nftables  
sudo nft add table inet filter  
sudo nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }  
sudo nft add rule inet filter input ct state established,related accept  
sudo nft add rule inet filter input tcp dport { 22, 80, 443 } accept  
sudo nft list ruleset > /etc/nftables.conf  # Save rules  

2. UFW (Uncomplicated Firewall)

Beginner-friendly tool for Ubuntu/Debian:

3. Firewalld (RHEL/CentOS/Fedora)

Dynamic zones and rich rules for enterprise setups:

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

Linux Firewall Security Best Practices

Best practices for castle fortification:

1. Backup Rules:

sudo nft list ruleset > /backup/nft-config-$(date +%F).txt  

2. Update Religiously: Patch CVE vulnerabilities with sudo apt update && sudo apt upgrade.

3. Log Aggregation: Forward logs to SIEM tools (ELK Stack, Splunk).

4. Performance Checks:

sudo nft list ruleset > /backup/nft-config-$(date +%F).txt  

Troubleshooting Cheat Sheet

IssueSolution
Locked out of SSH?Reboot into GRUB recovery mode, disable firewall
Slow network?Audit rules with sudo nft monitor trace
Docker ports blocked?Add --iptables=false to dockerd flags

FAQs

Q: Is iptables deprecated?

Yes. Migrate to nftables—it’s backward-compatible (iptables-translate converts old rules).

Q: How to block cryptojacking?

sudo nft add set inet filter bad_ips { type ipv4_addr \; }  
sudo nft add rule inet filter input ip saddr @bad_ips drop  
# Update 'bad_ips' via threat intel feeds  

Q: Secure a WordPress server?

sudo ufw allow 80,443/tcp  
sudo ufw deny out 25  # Block spam SMTP  
sudo apt install fail2ban  

Q: Firewall for Kubernetes?

Use Cilium or Calico for eBPF-powered network policies.

Q: How do I configure my Linux firewall to handle IPv6 traffic?

Yes, you may configure your IPv6 firewall with ip6tables IPv6 firewalls are included in most recent Linux versions.

Q: What is the difference between UFW and iptables?

An easy-to-use front-end for handling ‘iptables‘ rules is ‘UFW.’ It facilitates iptables rule creation and management using simpler syntax.

Q: What about managing many network interfaces?

Different interfaces can have different rules. Use ‘iptables -A’ to add rules to a chain for a specific interface or ‘iptables-restore’ and ‘iptables-save’ to build and apply alternative configuration files.

Q: How do I boot my firewall first?

By configuring unit files, you can organize system boot services. This starts your firewall before any service needs it.

Q: Can Linux operate several firewalls?

Multiple firewalls can be run on one system, although beginners should avoid it. Adding layers of protection increases complexity and requires prudence and awareness.

With this guide’s advice, you can build solid defenses and protect your Linux system. Whether setting up your first firewall or improving an existing one, every step you take improves digital security.

Conclusion

This guide has walked you through the fundamentals of iptables in Ubuntu, from viewing and managing firewall rules to saving and restoring configurations. By mastering commands like iptables -L and iptables-save You’ve gained the skills to control network traffic and protect your system from unauthorized access. These foundational steps ensure your server remains secure against common threats.

Iptables remains a critical tool for Linux security, offering granular control over network policies. However, continuous learning and experimentation are key—test custom rules, refine configurations, and always maintain backups of your firewall settings. This proactive approach minimizes risks during misconfigurations or failures, keeping your Ubuntu servers resilient.

Looking ahead, modern security demands more than just iptables. In 2023, adopt nftables (its faster successor), automate rules with tools like Ansible, and integrate cloud-native strategies for Kubernetes or multi-cloud environments. By blending traditional knowledge with these advanced practices, you’ll build a fortress-like system ready to counter zero-day exploits and rank as a top-tier “secure Linux server” resource.

Recent Blogs

© 2025 InfinitySoftHint your problem solution hub for all time. 

Our Services

Web Development

Software & App Development

Ecommerce Development

Content & Copywriting

Digital Media Marketing

Explore Our Services

Contact Now
Skip for now...