Linux & Servers guides, explanations and reader checklists on whilenetworking.com

Hardening Linux Web Servers Against DDoS Attacks Using iptables and nftables

Distributed Denial of Service (DDoS) attacks remain a persistent threat to web infrastructure, aiming to overwhelm server resources with malicious traffic.…

Distributed Denial of Service (DDoS) attacks remain a persistent threat to web infrastructure, aiming to overwhelm server resources with malicious traffic. For Linux administrators managing high-availability environments, understanding how to leverage native packet filtering tools is essential for maintaining uptime. This guide focuses on practical hardening techniques using iptables and its modern successor, nftables. By configuring these tools correctly, you can drop suspicious packets before they consume bandwidth or CPU cycles, ensuring your web server remains responsive during an attack.

It is important to note that while firewall rules provide a critical first line of defense, they are not a silver bullet. The effectiveness of any rule set depends heavily on the specific type of attack (e.g., volumetric, application-layer, or amplification) and the underlying network architecture. Furthermore, terms, availability, eligibility, laws, and prices regarding managed security services depend on your specific insurer, policy, and jurisdiction. This article provides informational guidance on technical configurations only; it does not constitute individualized financial or legal advice. Always verify current rules with your ISP or cloud provider, as some environments restrict low-level packet filtering capabilities.

Understanding the Shift from iptables to nftables

Historically, iptables has been the standard firewall utility for Linux distributions like CentOS and Ubuntu. However, modern kernels now support nftables, a unified framework that replaces iptables. While many tutorials still reference iptables, migrating to or writing rules in the nftables syntax is often recommended because it offers better performance and a single language to manage multiple layers of networking (firewall, nat, routing).

When evaluating which tool to use, consider your distribution’s version. Older systems may only support iptables, but new deployments should default to nftables. The core logic remains similar: define rules that match incoming traffic and decide whether to ACCEPT, DROP, or REJECT it. In a DDoS scenario, the goal is to create rules that drop known malicious patterns quickly. For instance, you might want to drop packets from IP addresses that have sent more than a certain number of connection requests within a short timeframe.

Implementing Rate Limiting to Absorb Floods

One of the most effective strategies against DDoS floods (such as SYN floods or UDP floods) is rate limiting. This technique allows legitimate traffic to pass through while throttling excessive connections from a single source. In nftables, this is achieved using the limit statement.

A common configuration involves allowing only a specific number of new TCP connections per second from any given IP address. If an attacker attempts to open thousands of connections, the firewall will drop the surplus packets after the limit is reached. For example, you can configure the system to allow 25 new connections per second or 100 per minute. Any traffic exceeding this threshold is dropped. This prevents the server’s connection table from filling up, which would otherwise lead to a denial of service for legitimate users.

When implementing rate limiting, it is crucial to distinguish between “new” connections and established ones. You should apply strict limits to new connections but allow established sessions to continue until they naturally time out. This ensures that if a user refreshes their page multiple times quickly, the connection is not prematurely terminated. Conversely, an attacker trying to establish a massive number of new handshakes will be blocked immediately after crossing the threshold.

Filtering Known Malicious Traffic and Protocols

Beyond rate limiting, you must filter traffic based on known attack signatures or suspicious protocols. Amplification attacks often exploit open services like DNS, NTP, or SSDP to reflect traffic back at the target. You can harden your server by dropping packets destined for these services if they originate from external networks or if the packet size is unusually large.

For example, you can write a rule to drop UDP packets targeting port 53 (DNS) that are larger than a specific byte count, effectively mitigating DNS amplification attempts. Similarly, you can block traffic on ports that are not required for your web application stack. If your server only needs HTTP (port 80) and HTTPS (port 443), all other incoming UDP or raw TCP traffic should be dropped by default. This minimizes the attack surface available to botnets scanning for vulnerabilities.

It is also wise to implement geo-blocking if your business model does not serve specific regions. If you do not have customers in a particular country, dropping packets from that IP range can significantly reduce the volume of potential attacks originating from those locations. Always ensure that your blocking logic accounts for legitimate traffic patterns to avoid false positives that could impact your reputation or sales.

Handling SYN Floods with Specific Flags

SYN floods are a classic form of DDoS attack where attackers send TCP packets with the SYN flag set but without completing the handshake. This exhausts the server’s memory allocated for connection tracking. To mitigate this, you can use the syncookie feature or specific iptables/nftables rules that track incomplete handshakes.

In an nftables table, you can match packets with the SYN flag set and drop them if the source IP has already sent a similar number of SYN packets recently. This effectively implements a sliding window rate limit specifically for the handshake phase. Additionally, enabling TCP SYN cookies at the kernel level allows the server to accept connections even when its connection tracking table is full, sending a special cookie instead of allocating memory. The client must then prove it owns the IP address by responding to the challenge before a real connection is established.

Real-World Configuration Checklist and Best Practices

To translate these concepts into action, consider using a structured checklist during your server hardening process. Start by backing up your current firewall rules, as aggressive changes can accidentally block legitimate traffic. Next, define your baseline: identify which ports are essential and ensure all others are closed or rate-limited.

  1. Backup Current State: Export your existing nftables ruleset to a file for restoration if needed.
  2. Set Default Policies: Ensure the default policy for incoming traffic is set to drop. Only explicitly allow necessary ports like 80 and 443.
  3. Configure Rate Limits: Add rules to limit new TCP connections per source IP (e.g., 25/sec).
  4. Filter Amplification Vectors: Drop large UDP packets on non-essential reflection ports.
  5. Enable SYN Cookies: Verify that the kernel parameter net.ipv4.tcp_syncookies is enabled.
  6. Test Rules Gradually: Apply changes in a staging environment first, or use a low-priority queue to monitor traffic impact before making them permanent.

Remember that firewall rules are just one layer of defense. If an attack exceeds your bandwidth capacity, no amount of packet filtering will stop the saturation. In such cases, integrating with upstream providers who offer scrubbing services is necessary. Always document your rule changes and review them periodically, as botnet tactics evolve rapidly. By combining nftables rate limiting with kernel hardening and upstream mitigation strategies, you create a robust defense that significantly increases the difficulty for attackers to bring your web server down.