The Iron Gate: Advanced Firewalling with nftables
·TechSoftware Development

The Iron Gate: Advanced Firewalling with nftables

Move beyond simple open/close rules. Master 'nftables', the modern Linux firewall engine. Learn to write 'Rich Rules' for rate limiting, IP blocking, and logging. Understand the logic of Chains, Sets, and Tables.

Advanced Firewalling: The Art of nftables

In Module 10, we learned to use UFW and Firewalld. These are great "Auto-pilot" tools. But if you want to stop a complex DDoS attack, limit traffic on a specific subnet, or create custom logging for security audits, you need to speak the raw language of the Kernel.

That language is nftables.

nftables replaced the legendary iptables significantly by making the syntax cleaner and the performance much higher. It allows you to build a custom "Security Hierarchy" that fits your server's specific needs perfectly.


1. The nftables Hierarchy: Tables, Chains, and Rules

nftables is organized like a giant file cabinet:

  1. Table: The cabinet itself (e.g., "Filtering Table").
  2. Chain: The drawers in the cabinet (e.g., "Inbound Drawer," "Output Drawer").
  3. Rule: The individual files in the drawer (e.g., "Allow Port 22," "Drop Port 80").
graph LR
    P[Packet In] --> T[Table: filter]
    T --> C[Chain: input]
    C --> R1[Rule: Drop SSH from Russia]
    R1 --> R2[Rule: Allow Web traffic]
    R2 --> R3[Rule: Drop Everything else]

2. Basic Filtering Syntax

With nftables, you can build your entire firewall in one command or one file.

# 1. Create the table
sudo nft add table inet filter

# 2. Create the inbound chain
sudo nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }

# 3. Add rules
sudo nft add rule inet filter input tcp dport 22 accept
sudo nft add rule inet filter input iifname "lo" accept

Crucial Logic: The policy drop at the end of the chain is your "Default Deny" shield.


3. "Rich Rules": Rate Limiting and Sets

Raw rules are great, but "Rich" rules are what make nftables powerful for security engineers.

I. IP Sets (The Blacklist)

Instead of writing 100 rules for 100 bad IPs, you create a "Set" and one rule to block them all.

# Create a set of attackers
sudo nft add set inet filter attackers { type ipv4_addr \; }

# Add an IP to the blacklist
sudo nft add element inet filter attackers { 1.2.3.4, 5.6.7.8 }

# Block everyone in that set
sudo nft add rule inet filter input ip saddr @attackers drop

II. Rate Limiting (Anti-Brute Force)

Prevent someone from knocking on your SSH "Door" 50 times a second.

sudo nft add rule inet filter input tcp dport 22 limit rate 5/minute accept

4. Verdicts: What happens to the packet?

  • accept: Let it through.
  • drop: Stop it immediately (the sender gets no notification).
  • reject: Stop it and send an "Access Denied" message back.
  • log: Record the packet's info in dmesg without making a final decision yet.

5. Practical: The "Stealth" Firewall

A professional firewall doesn't respond to pings. This makes your server "invisible" to simple scanning tools.

# Drop all ICMP pings
sudo nft add rule inet filter input icmp type echo-request drop

6. Example: A Firewall Rule Synchronizer (Python)

In a cluster, you want every server to have the same "Blacklist." Here is a Python script that reads a list of IPs from a central file and pushes them into the server's nftables set.

import subprocess
import os

def sync_blacklist(ip_list_path):
    """
    Syncs a text file of IPs into an nftables set named 'attackers'.
    """
    if not os.path.exists(ip_list_path):
        print("Blacklist file not found.")
        return

    with open(ip_list_path, 'r') as f:
        ips = [line.strip() for line in f if line.strip()]

    print(f"Syncing {len(ips)} IPs into nftables...")
    
    # Clear old set elements if needed or just add new ones
    for ip in ips:
        cmd = ["sudo", "nft", "add", "element", "inet", "filter", "attackers", "{", ip, "}"]
        subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        
    print("[SUCCESS] Blacklist synchronized.")

if __name__ == "__main__":
    # Create dummy list for demo
    with open("bad_ips.txt", "w") as f:
        f.write("192.168.1.100\n10.0.0.5\n")
        
    sync_blacklist("bad_ips.txt")

7. Professional Tip: Check 'nft list ruleset'

Unlike older tools, nftables can show you your entire configuration in a single, clean output that looks just like the commands you typed. This makes it incredibly easy to copy your config from a dev server to a production server.

sudo nft list ruleset > /etc/nftables.conf

8. Summary

nftables is the sovereign engine of Linux security.

  • Sets allow you to manage thousands of IPs with zero performance loss.
  • Rate Limiting protects you from automated script-kiddie attacks.
  • Policy Drop is your "Safe Mode."
  • inet Family allows you to protect IPv4 and IPv6 with a single rule.

In the next lesson, we will move from security to architecture: VLANs and Bonding for high-availability networking.

Quiz Questions

  1. Why is the "Set" feature in nftables better than writing individual rules for each IP?
  2. What is the difference between the drop and reject verdicts?
  3. Which table family (ip, ip6, or inet) should you use for a modern dual-stack server?

Continue to Lesson 4: VLANs and Bonding—High Availability Networking.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn