Back to HomeDDoS Protection

DDoS Defense Tutorial: Complete Implementation Guide from Basic Configuration to Advanced Protection (2025)

12 min min read
#DDoS defense#defense tutorial#WAF configuration#CDN protection#Cloudflare#nginx#firewall#Rate Limiting#incident response#security implementation

DDoS Defense Tutorial: Complete Implementation Guide from Basic Configuration to Advanced Protection (2025)

"We're under DDoS attack, the website's down, the boss is calling, what do I do?"

This situation is something many engineers have experienced. Without preparation, you can only scramble when it happens.

This article will guide you step-by-step in building a DDoS defense system. From network equipment, servers, applications to CDN, each layer includes specific configuration examples. After reading and implementing, your website will have basic attack resistance capability.

Engineer configuring firewall rules at computer, screen showing iptables commands and traffic monitoring graphs


Basic Principles of DDoS Defense

Before starting configuration, understand several important principles.

Multi-Layered Defense Architecture

Effective DDoS defense doesn't rely on a single tool, but a combination of multiple defense lines.

Defense Layers (from outside to inside):

  1. ISP/Cloud Layer: Filter traffic before it enters your network
  2. Border Network Layer: Router, firewall filtering
  3. Server Layer: Operating system and network service configuration
  4. Application Layer: WAF, rate limiting, verification mechanisms

Each layer blocks some attacks, and together they form effective defense.

Defense Strategy: Detection, Mitigation, Response

Detection

  • Monitor traffic anomalies
  • Set alert thresholds
  • Understand normal traffic baseline

Mitigation

  • Filter malicious traffic
  • Distribute attack load
  • Expand resources to absorb attacks

Response

  • Emergency switch mechanisms
  • Notification processes
  • Post-incident analysis and improvement

Balancing Cost and Protection Level

There's no 100% perfect protection solution. You need to find balance between cost and risk.

Protection LevelMonthly CostDefendable Attack ScaleSuitable For
Basic$0-$50Several GbpsPersonal websites, small businesses
Advanced$200-$1,000Tens of GbpsMedium enterprises, e-commerce
Enterprise$3,000+Tbps levelLarge enterprises, financial industry

Understand attack types first to choose the correct defense strategy. Check out Complete DDoS Attack Analysis: L3/L4/L7 Attack Types.


Network Equipment Layer Defense Configuration

This layer's goal is to filter obvious attacks before traffic reaches servers.

Router / Firewall Basic Configuration

1. iptables Basic Protection (Linux)

# Limit SYN packet rate
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT
iptables -A INPUT -p tcp --syn -j DROP

# Limit ICMP packets
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

# Drop invalid packets
iptables -A INPUT -m state --state INVALID -j DROP

# Prevent Port Scanning
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

2. Enable SYN Cookie

# Check current setting
cat /proc/sys/net/ipv4/tcp_syncookies

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

# Make permanent, add to /etc/sysctl.conf
net.ipv4.tcp_syncookies = 1

3. Adjust TCP Parameters

# /etc/sysctl.conf

# Increase half-open connection queue size
net.ipv4.tcp_max_syn_backlog = 65536

# Reduce SYN-ACK retry count
net.ipv4.tcp_synack_retries = 2

# Reduce TIME_WAIT connections
net.ipv4.tcp_tw_reuse = 1

# Apply settings
sysctl -p

ISP Level Protection Application

If you use HiNet or other ISPs, you can apply for upstream protection:

Chunghwa Telecom DDoS Protection Service:

  • Contact enterprise customer service or account manager
  • Provide IP ranges to protect
  • Configure protection thresholds and strategies

Advantages:

  • Filters traffic before it enters your facility
  • Can block very large-scale attacks
  • No changes to existing architecture needed

Disadvantages:

  • Higher cost (monthly fees typically start at tens of thousands NT$)
  • Less configuration flexibility
  • Must be their ISP customer

Traffic Monitoring and Alert Configuration

Without monitoring, you don't know when you're being attacked.

Using Prometheus + Grafana for Monitoring:

# prometheus.yml - Monitor network traffic
scrape_configs:
  - job_name: 'node'
    static_configs:
      - targets: ['localhost:9100']

# Alert rules
groups:
  - name: ddos_alerts
    rules:
      - alert: HighNetworkTraffic
        expr: rate(node_network_receive_bytes_total[1m]) > 100000000
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: "Abnormal high traffic warning"
          description: "Inbound traffic exceeds 100 MB/s"

Configure LINE or Slack Alert Notifications:

# alertmanager.yml
receivers:
  - name: 'slack-notifications'
    slack_configs:
      - api_url: 'https://hooks.slack.com/services/xxx'
        channel: '#alerts'
        text: '{{ .CommonAnnotations.description }}'

Monitoring dashboard showing network traffic graphs and alert status with flashing red warning lights


Server Layer Hardening Measures

This layer's goal is to make servers more resistant to attacks.

Operating System Level Tuning

1. Increase File Descriptor Limits

# /etc/security/limits.conf
* soft nofile 65536
* hard nofile 65536

# /etc/sysctl.conf
fs.file-max = 2097152

2. Adjust Network Buffers

# /etc/sysctl.conf

# Increase receive buffer
net.core.rmem_max = 16777216
net.core.rmem_default = 1048576

# Increase send buffer
net.core.wmem_max = 16777216
net.core.wmem_default = 1048576

# Increase connection queue
net.core.somaxconn = 65536
net.core.netdev_max_backlog = 65536

3. Enable Connection Tracking Optimization

# Increase connection tracking table size
net.netfilter.nf_conntrack_max = 1000000

# Reduce connection tracking timeout
net.netfilter.nf_conntrack_tcp_timeout_established = 600
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 30

Web Server Configuration Optimization

Nginx Defense Configuration:

# /etc/nginx/nginx.conf

# Connection limits
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

http {
    # Limit connections per IP
    limit_conn conn_limit 20;

    # Limit request rate
    limit_req zone=req_limit burst=20 nodelay;

    # Set connection timeouts
    client_body_timeout 10s;
    client_header_timeout 10s;
    keepalive_timeout 65s;
    send_timeout 10s;

    # Limit request size
    client_max_body_size 10m;
    client_body_buffer_size 128k;
}

server {
    # Block specific User-Agents
    if ($http_user_agent ~* (bot|crawler|spider)) {
        return 403;
    }

    # Block empty User-Agents
    if ($http_user_agent = "") {
        return 403;
    }
}

Apache Defense Configuration:

# /etc/apache2/apache2.conf

# Limit connections
MaxRequestWorkers 400
ServerLimit 400

# Set timeouts
Timeout 60
KeepAliveTimeout 5

# Limit request size
LimitRequestBody 10485760
LimitRequestFields 50
LimitRequestFieldSize 8190

Resource Isolation and Scaling

Using Docker for Service Isolation:

# docker-compose.yml
version: '3'
services:
  web:
    image: nginx
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 2G
        reservations:
          cpus: '0.5'
          memory: 512M

Configure Auto Scaling (AWS Example):

# CloudFormation snippet
AutoScalingGroup:
  Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    MinSize: 2
    MaxSize: 10
    TargetGroupARNs:
      - !Ref ALBTargetGroup

ScalingPolicy:
  Type: AWS::AutoScaling::ScalingPolicy
  Properties:
    PolicyType: TargetTrackingScaling
    TargetTrackingConfiguration:
      PredefinedMetricSpecification:
        PredefinedMetricType: ASGAverageCPUUtilization
      TargetValue: 70

Need a Second Opinion on Architecture Design?

DDoS defense involves network, server, and application layers. Designing the correct architecture can yield twice the results with half the effort.

Schedule architecture consultation and let experienced experts help you:

  • Evaluate existing architecture's attack resistance
  • Design multi-layered defense strategy
  • Plan cost-optimized protection solutions

Application Layer Defense Strategies

This layer is the last line of defense and key to defending against L7 attacks.

WAF (Web Application Firewall) Configuration

Using ModSecurity (Open Source WAF):

# Install ModSecurity
apt-get install libapache2-mod-security2

# Enable OWASP Core Rule Set
cd /etc/modsecurity
git clone https://github.com/coreruleset/coreruleset.git
cp coreruleset/crs-setup.conf.example crs-setup.conf
# /etc/modsecurity/modsecurity.conf

# Enable protection mode
SecRuleEngine On

# DDoS related rules
SecRule REQUEST_HEADERS:User-Agent "@rx ^$" \
    "id:1000,phase:1,deny,status:403,msg:'Empty User-Agent'"

SecRule &REQUEST_HEADERS:Host "@eq 0" \
    "id:1001,phase:1,deny,status:403,msg:'Missing Host Header'"

Cloudflare WAF Configuration:

In Cloudflare Dashboard:

  1. Go to Security > WAF
  2. Enable Managed Rules
  3. Set custom rules:
# Block suspicious requests
(http.request.uri.query contains "eval(") or
(http.request.uri.query contains "base64_decode") or
(http.user_agent contains "sqlmap")

Request Verification Mechanisms

CAPTCHA Integration (reCAPTCHA v3):

<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITE_KEY"></script>
<script>
grecaptcha.ready(function() {
    grecaptcha.execute('YOUR_SITE_KEY', {action: 'submit'})
    .then(function(token) {
        document.getElementById('g-recaptcha-response').value = token;
    });
});
</script>
# Backend verification (Python)
import requests

def verify_recaptcha(token):
    response = requests.post(
        'https://www.google.com/recaptcha/api/siteverify',
        data={
            'secret': 'YOUR_SECRET_KEY',
            'response': token
        }
    )
    result = response.json()
    return result.get('success') and result.get('score', 0) > 0.5

JavaScript Challenge:

<script>
document.cookie = "js_check=" + (2 + 3) + "; path=/";
</script>
# Nginx verification
location / {
    if ($cookie_js_check != "5") {
        return 403;
    }
    proxy_pass http://backend;
}

API Protection Measures

Rate Limiting Implementation (Node.js):

const rateLimit = require('express-rate-limit');

const apiLimiter = rateLimit({
    windowMs: 1 * 60 * 1000, // 1 minute
    max: 100, // Max 100 requests per IP
    message: {
        error: 'Too many requests, please try again later.'
    },
    standardHeaders: true,
    legacyHeaders: false,
});

app.use('/api/', apiLimiter);

API Key Verification:

const validateApiKey = (req, res, next) => {
    const apiKey = req.headers['x-api-key'];

    if (!apiKey || !isValidApiKey(apiKey)) {
        return res.status(401).json({ error: 'Invalid API key' });
    }

    // Check API Key usage
    if (isRateLimitExceeded(apiKey)) {
        return res.status(429).json({ error: 'Rate limit exceeded' });
    }

    next();
};

CDN Integration and Configuration Tutorial

CDN is one of the most effective tools for DDoS defense.

How CDN Helps Defend Against DDoS

1. Distribute Attack Traffic

  • Global hundreds of nodes share traffic
  • Attackers need to attack all nodes

2. Hide Origin IP

  • Attackers cannot directly attack your server
  • All traffic goes through CDN

3. Edge Filtering

  • Block malicious traffic at edge nodes
  • Reduce origin server burden

4. Large Bandwidth Absorption

  • CDN bandwidth is typically at Tbps level
  • Small-scale attacks have no effect

Cloudflare Configuration Implementation

Step 1: Add Website

  1. Register Cloudflare account
  2. Add your domain
  3. Change DNS nameservers to point to Cloudflare

Step 2: Basic Security Settings

Dashboard > Security > Settings

- Security Level: Medium or High
- Challenge Passage: 30 minutes
- Browser Integrity Check: On

Step 3: DDoS Protection Settings

Dashboard > Security > DDoS

- HTTP DDoS attack protection: On
- Sensitivity: High
- Action: Block

Step 4: Rate Limiting Rules

Dashboard > Security > WAF > Rate limiting rules

Example rule:
- If same IP requests more than 100 times in 10 seconds
- Action: Block for 1 hour

Step 5: Firewall Rules

Dashboard > Security > WAF > Custom rules

# Block specific countries (if you don't need traffic from those regions)
(ip.geoip.country in {"CN" "RU"}) and not cf.client.bot

# Protect login page
(http.request.uri.path contains "/login") and
(cf.threat_score gt 10)

Other CDN Protection Configuration

AWS CloudFront + Shield:

# CloudFormation
Distribution:
  Type: AWS::CloudFront::Distribution
  Properties:
    DistributionConfig:
      Origins:
        - DomainName: !GetAtt ALB.DNSName
          CustomOriginConfig:
            HTTPPort: 80
            OriginProtocolPolicy: http-only
      DefaultCacheBehavior:
        AllowedMethods: [GET, HEAD, OPTIONS]
        CachedMethods: [GET, HEAD]
        ViewerProtocolPolicy: redirect-to-https

Akamai Configuration Key Points:

  • Enable Kona Site Defender
  • Configure Rate Controls
  • Deploy Bot Manager

Need more protection service comparisons? Check out DDoS Protection Service Comparison: Cloudflare, Chunghwa Telecom, AWS Shield Complete Review.

Cloudflare dashboard showing statistics of successfully blocked DDoS attacks


Emergency Response SOP

Even with comprehensive defense, you need to prepare for "what if."

Processing Flow When DDoS Attack Occurs

Phase 1: Detection and Confirmation (0-5 minutes)

  1. Receive alert or user report
  2. Confirm it's a DDoS attack (not normal traffic peak or system issue)
  3. Notify response team

Confirmation Methods:

  • Traffic suddenly surges (10x or more)
  • Source IPs distributed across multiple countries
  • Abnormal request patterns (same User-Agent, same path)

Phase 2: Initial Response (5-15 minutes)

  1. Enable CDN's Under Attack Mode
  2. Increase Rate Limiting thresholds
  3. Block obvious attack sources
# Quickly block many IPs
iptables -A INPUT -s 1.2.3.0/24 -j DROP

# Or use ipset for batch blocking
ipset create blocklist hash:net
ipset add blocklist 1.2.3.0/24
iptables -A INPUT -m set --match-set blocklist src -j DROP

Phase 3: Escalated Response (15-60 minutes)

  1. Contact ISP for upstream filtering
  2. Enable backup IP or backup site
  3. Route traffic to DDoS scrubbing service if necessary

Phase 4: Continuous Monitoring and Adjustment

  1. Monitor whether attack is subsiding
  2. Adjust defense rules
  3. Prepare for next wave of attacks

Emergency Contact List Preparation

Prepare this information in advance:

ContactContact InfoResponsibility
ISP Technical SupportPhone/EmailUpstream filtering
CDN Customer ServicePhone/EmailProtection upgrade
Cloud Service ProviderSupport PortalResource expansion
Security ConsultantPhone/EmailTechnical support
LegalPhone/EmailReporting/Evidence preservation

Post-Incident Review and Improvement

After the attack ends, conduct a review:

1. Collect Data

  • Attack timeline
  • Attack scale and type
  • Effectiveness of defense measures

2. Analysis Report

  • What was done well?
  • What can be improved?
  • What defense measures need to be added?

3. Update SOP

  • Update response procedures based on experience
  • Update contact lists
  • Schedule drills

After completing configuration, don't forget to test your DDoS defense capabilities to confirm defenses are actually effective.


Need Professional Help Building DDoS Defense?

DDoS defense involves multiple layers. Figuring it out yourself may waste a lot of time.

Schedule a free security assessment, and we can help you:

  • Evaluate existing defense capabilities
  • Design suitable protection architecture
  • Establish response procedures

All consultations are completely confidential with no sales pressure.


Defense Configuration Checklist

After completing this article's configurations, use this checklist to confirm:

Network Layer

  • iptables basic rules configured
  • SYN Cookie enabled
  • TCP parameters optimized
  • Traffic monitoring established

Server Layer

  • File descriptor limits adjusted
  • Network buffers optimized
  • Web server rate limiting configured
  • Connection timeouts set

Application Layer

  • WAF deployed
  • Rate Limiting enabled
  • CAPTCHA/JS Challenge configured
  • API protection implemented

CDN

  • CDN integrated
  • DDoS protection enabled
  • Rate Limiting rules configured
  • Origin IP hidden

Response Preparation

  • Emergency contact list prepared
  • Response SOP established
  • Backup solutions prepared
  • Team has conducted drills

Further Reading


References

  1. Cloudflare DDoS Protection Documentation
  2. Nginx Rate Limiting
  3. Linux Kernel Networking Parameters
  4. OWASP ModSecurity Core Rule Set
  5. AWS Shield Best Practices

Need Professional Cloud Advice?

Whether you're evaluating cloud platforms, optimizing existing architecture, or looking for cost-saving solutions, we can help

Book Free Consultation

Related Articles