Master DDoS Defense: Linux Traffic Scrubbing & Rate Limiting Strategies

This article shares a hands‑on, production‑tested DDoS mitigation guide that covers real‑world attack analysis, layered defense architecture, Linux kernel‑level traffic cleaning with iptables and tc, Nginx + Lua application‑layer protection, automated monitoring, performance tuning, and future trends.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Master DDoS Defense: Linux Traffic Scrubbing & Rate Limiting Strategies

Current DDoS Threat Landscape

Recent large‑scale attacks (e.g., a 500 Gbps flood during a major shopping festival) demonstrate multi‑vector, highly automated traffic that can be launched cheaply and sustained for hours or days.

Multi‑vector attacks : simultaneous L3/L4/L7 traffic.

High automation : bots mimic legitimate user behavior.

Low cost : a one‑hour attack can cost as little as $10.

Extended duration : attacks may last for days.

Core Defense Philosophy – Layered Protection + Dynamic Response

Defense Architecture Design

[User Request] → [CDN/Cloud Protection] → [Hardware Firewall] → [Linux Server] → [Application‑Layer Protection]
   ↓               ↓               ↓               ↓               ↓
   First Line      Second Line     Third Line      Fourth Line     Fifth Line

Linux Kernel‑Level Traffic Scrubbing

1. Advanced iptables Rules

Basic Connection Limits

# Limit concurrent connections per IP on port 80
iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 20 -j DROP

# Limit new connection rate per IP
iptables -A INPUT -p tcp --dport 80 -m recent --set --name WEB
iptables -A INPUT -p tcp --dport 80 -m recent --update --seconds 60 --hitcount 10 --name WEB -j DROP

SYN Flood Protection

# Enable SYN cookies
echo 1 > /proc/sys/net/ipv4/tcp_syncookies

# Increase SYN backlog
echo 2048 > /proc/sys/net/ipv4/tcp_max_syn_backlog

echo 5 > /proc/sys/net/ipv4/tcp_synack_retries

2. tc Traffic Control for Rate Limiting

Shaping Rules

#!/bin/bash
DEV="eth0"
RATE="100mbit"

# Delete old qdisc
tc qdisc del dev $DEV root 2>/dev/null

# Root qdisc
tc qdisc add dev $DEV root handle 1: htb default 999

# Main class – full bandwidth
tc class add dev $DEV parent 1: classid 1:1 htb rate $RATE

# Normal traffic (80% of bandwidth)
tc class add dev $DEV parent 1:1 classid 1:10 htb rate 80mbit ceil 90mbit prio 1

# Suspicious traffic (20% of bandwidth)
tc class add dev $DEV parent 1:1 classid 1:20 htb rate 10mbit ceil 20mbit prio 2

# Filter normal traffic
tc filter add dev $DEV parent 1 protocol ip prio 1 u32 match ip src 0.0.0.0/0 flowid 1:10

3. Kernel Parameter Optimization

# /etc/sysctl.conf – key parameters
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 65536 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.netfilter.nf_conntrack_max = 1000000
net.netfilter.nf_conntrack_tcp_timeout_established = 600
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

Intelligent Traffic Analysis System

Real‑Time Monitoring Script

#!/bin/bash
THRESHOLD=1000   # connections per second threshold
LOGFILE="/var/log/ddos_monitor.log"
while true; do
  CONN_COUNT=$(netstat -an | grep :80 | wc -l)
  TOP_IPS=$(netstat -an | grep :80 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10)
  if [ $CONN_COUNT -gt $THRESHOLD ]; then
    echo "$(date): DDoS detected! Connection count: $CONN_COUNT" >> $LOGFILE
    echo "$TOP_IPS" | while read count ip; do
      if [ $count -gt 100 ]; then
        iptables -I INPUT -s $ip -j DROP
        echo "$(date): Blocked IP $ip with $count connections" >> $LOGFILE
      fi
    done
  fi
  sleep 1
done

Application‑Layer Protection – Nginx + Lua

Advanced Rate‑Limiting Configuration

# nginx.conf core configuration
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=strict:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
    location / {
        # Basic rate limiting
        limit_req zone=general burst=20 nodelay;
        limit_conn conn_limit 10;

        # Geo‑IP filter – allow only CN, US, JP
        if ($geoip_country_code !~ (CN|US|JP)) {
            return 403;
        }

        # Lua‑based dynamic check using Redis
        access_by_lua_block {
            local redis = require "resty.redis"
            local red = redis:new()
            red:set_timeout(1000)
            red:connect("127.0.0.1", 6379)
            local ip = ngx.var.remote_addr
            local key = "rate_limit:" .. ip
            local current = red:get(key)
            if current == ngx.null then
                red:setex(key, 60, 1)
            else
                if tonumber(current) > 100 then
                    ngx.exit(403)
                end
                red:incr(key)
            end
            red:close()
        }
    }
}

Monitoring & Alerting System

Prometheus + Grafana

# prometheus.yml snippet
scrape_configs:
  - job_name: 'ddos-monitor'
    static_configs:
      - targets: ['localhost:9100']
    scrape_interval: 5s
    metrics_path: /metrics

Custom Metrics Export

#!/bin/bash
# Export DDoS metrics to Prometheus

echo "# HELP ddos_connections_total Total connections"
echo "# TYPE ddos_connections_total gauge"
echo "ddos_connections_total $(netstat -an | grep :80 | wc -l)"

echo "# HELP ddos_blocked_ips_total Blocked IP addresses"
echo "# TYPE ddos_blocked_ips_total gauge"
echo "ddos_blocked_ips_total $(iptables -L INPUT -n | grep DROP | wc -l)"

Performance Optimization Tips

Memory Optimization

# Optimize memory allocation
echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
echo 'vm.swappiness = 10' >> /etc/sysctl.conf

CPU Affinity Settings

# Bind network interrupts to specific CPUs
echo 2 > /proc/irq/24/smp_affinity
echo 4 > /proc/irq/25/smp_affinity

Practical Results

Metric                Before   After   Improvement
---------------------------------------------------
Concurrent connections 10,000   100,000 10×
Response time          500ms    50ms    90% reduction
CPU usage              80%      30%     62% reduction
Defense success rate   60%      95%     58% increase

Common Pitfalls & Solutions

Pitfall 1 – Over‑Limiting Affects Legitimate Users

Solution: Implement a whitelist for trusted IP ranges.

# Whitelist trusted IPs
iptables -I INPUT -s 192.168.1.0/24 -j ACCEPT
iptables -I INPUT -s 10.0.0.0/8 -j ACCEPT

Pitfall 2 – Rule Conflicts Cause Protection Failure

Solution: Manage rule priority and regularly audit the rule set.

# Detect conflicting DROP/REJECT rules
iptables-save | grep -E "(DROP|REJECT)" | sort

Future Development Trends

AI‑driven protection : machine‑learning models identify attack patterns.

Edge‑computing defense : block malicious traffic close to the source.

Collaborative defense : multi‑vendor joint mitigation.

Zero‑trust architecture : default‑deny all connections.

Summary & Actionable Recommendations

Layered defense : distribute protection across network, kernel, and application layers.

Continuous monitoring : 24/7 traffic observation with automated alerts.

Rapid response : auto‑block offending IPs and adjust rate limits instantly.

Regular drills : simulate attacks to validate and refine the defense stack.

Diagram
Diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

monitoringLinuxDDoSiptablestc
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.