Marcio Cunha

How to block port scans at the edge with nftables

Learn how to create efficient nftables rules to detect and mitigate port scans before they reach your internal network services.

Marcio Cunha•5 min
Also available in:PortuguêsEspañol
Summary
  • Port scans map vulnerabilities by probing active network services prior to targeted attacks.
  • Nftables replaces iptables with a unified syntax and improves filtering performance in the Linux kernel.
  • Dynamic sets store suspicious IPs at runtime without bloating the configuration file.
  • Simultaneous connection counting identifies automated bots by monitoring scanning behavior.
  • Rate-limiting rules drop excessive packets and protect computing resources against exhaustion.

The invisible danger of port scans on the internet

Imagine your house has hundreds of doors and windows facing the street, and someone walks by testing every single one to see which ones are unlocked. In network architecture, this automated probing is called a port scan, a process where malicious software sends data packets to tens of thousands of numeric addresses looking for vulnerable services. In practice, this means any server connected to the internet suffers silent intrusion attempts dozens of times a day, long before an actual attack takes place.

To shield your infrastructure against this preliminary mapping, your first line of defense must be the router or firewall at the network edge. When combined with advanced practices like how to block malicious traffic at the edge with eBPF and XDP, we drastically reduce the risk of internal server compromise. The goal is to prevent attackers from discovering which ports are open, making your system invisible to scanning bots.

Why nftables replaces legacy iptables with advantages

For many years, the iptables utility was the absolute king of packet filtering in the Linux operating system. However, its structure suffered from code duplication for IPv4 and IPv6, alongside severe performance drops when complex rules were added in sequence. Nftables emerged to unify all this logic into a modern architecture that interacts directly with the kernel's network subsystem, processing rules much faster and more elegantly.

In practice, this means we can write cleaner rule sets that are easier to read and consume less CPU memory when inspecting network traffic. This efficiency is vital when handling thousands of packets per second from suspicious IP addresses trying to probe random ports. If you have previously used simpler tools like how to unblock ports in the Linux firewall with UFW for basic rule management, you will notice that nftables offers surgical, low-level control over every packet crossing the network interface.

Configuring the base table and chains in nftables

Before creating sophisticated blocks, we need to structure the skeleton of our firewall using the nftables command-line utility. The nftables ecosystem works with tables containing chains, and these chains organize the exact moment network packets are inspected, whether right at the interface entry or before reaching applications.

To start configuring our edge defense mechanism, execute the following command sequence in your Linux server terminal with administrative privileges:

  1. Create the main inet table to cover both IPv4 and IPv6 traffic:
    nft add table inet firewall
  2. Add the input chain to intercept packets arriving from outside:
    nft add chain inet firewall input { type filter hook input priority filter \; policy accept \; }
  3. Define a dedicated chain to log and handle suspicious scanning packets:
    nft add chain inet firewall varredura

Detecting scanning behavior with dynamic sets

A classic port scan betrays itself through haste: the attacker attempts to open connections across dozens of different ports within seconds. To catch this behavior red-handed, nftables allows you to create dynamic sets that temporarily store IP addresses exceeding a reasonable threshold of connection attempts.

In practice, we tell the firewall to monitor requests on closed ports and, if an IP reaches more than five attempts in ten seconds, automatically add it to a temporary blacklist. This approach resembles robust strategies applied in how to block SSH brute force attacks with Fail2Ban, but operating directly in kernel space for maximum response speed and lower resource consumption.

Writing practical mitigation rules in nftables

With the concepts and base structure defined, it is time to apply the rules that will do the heavy lifting of filtering and blocking. We will configure nftables to identify repetitive probing patterns and drop corresponding packets before they consume processing power from our internal services.

To apply these protection rules permanently and functionally, use the following commands in your production environment:

  1. Create a dynamic set named 'port_scanners' that expires after a one-minute block:
    nft add set inet firewall port_scanners { type ipv4_addr\; flags dynamic, timeout\; timeout 1m\; size 65535\; }
  2. Add the rule that inserts offending IPs into the dynamic set upon exceeding the scan limit:
    nft add rule inet firewall input tcp flags \& (syn\|ack) == syn add @port_scanners { ip saddr ct count over 5 } drop
  3. Ensure any packet coming from an IP already present in the blacklist is summarily ignored:
    nft add rule inet firewall input ip saddr @port_scanners drop

Validating and monitoring firewall effectiveness

Implementing security rules without testing them is like putting a padlock on a door without checking if the key actually turns. After configuring nftables, it is crucial to perform audits by simulating scans from an external machine to ensure the firewall responds exactly as expected.

You can use legitimate network auditing tools to fire test packets against your public IP and then inspect the behavior of the dynamic set using the nftables listing command. If you notice legitimate traffic being affected by false positives, simply adjust the numerical attempt limit or the set expiration time in your configuration script.

Final Considerations

Blocking port scans at the network edge using nftables transforms an exposed server into a silent fortress, capable of repelling automated probes before they compromise service stability. By uniting dynamic sets, intelligent packet counting, and the native performance of the Linux kernel, we build an impenetrable barrier against daily internet mapping.

Keeping this defense active requires continuous monitoring and fine-tuning of blocking thresholds to balance rigid security with legitimate accessibility. With a well-planned firewall architecture, you protect your computing resources and gain the operational peace of mind needed to focus on growing your technological projects.