Distributed Denial of Service (DDoS) attacks can cripple your Linux server and disrupt services. This comprehensive guide will teach you how to implement multiple layers of protection to keep your server secure and available even under attack.
1. Understanding DDoS Attacks
DDoS attacks overwhelm your server with massive traffic from multiple sources. Common types include:
- Volume-based attacks: UDP floods, ICMP floods
- Protocol attacks: SYN floods, ACK floods
- Application layer attacks: HTTP floods, slowloris attacks
2. System Preparation
Update Your System
sudo apt update && sudo apt upgrade -y
# For RHEL/CentOS
sudo yum update -y
Enable Sysctl Tuning
# Edit /etc/sysctl.conf
sudo nano /etc/sysctl.conf
Add these kernel parameters:
# DDoS Protection Settings
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5
net.ipv4.ip_forward = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
Apply the changes:
sudo sysctl -p
3. Firewall Configuration
Using UFW (Ubuntu)
# Install UFW
sudo apt install ufw
# Default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow essential services
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Enable rate limiting for SSH
sudo ufw limit ssh
# Enable firewall
sudo ufw enable
Using iptables (Advanced)
# Create new chains
sudo iptables -N INPUT_CHAIN
sudo iptables -N SYN_PROTECTION
sudo iptables -N LOGGING
# Basic protection rules
sudo iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
sudo iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
sudo iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
# SYN flood protection
sudo iptables -A SYN_PROTECTION -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j RETURN
sudo iptables -A SYN_PROTECTION -p tcp --syn -j DROP
# Rate limiting
sudo iptables -A INPUT_CHAIN -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
sudo iptables -A INPUT_CHAIN -p tcp --dport 443 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
# Log and drop suspicious traffic
sudo iptables -A LOGGING -m limit --limit 5/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4
sudo iptables -A LOGGING -j DROP
4. Install Fail2Ban
# Install Fail2Ban
sudo apt install fail2ban
# Create local configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Edit the configuration:
sudo nano /etc/fail2ban/jail.local
Add these settings:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
backend = systemd
[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3
[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
[nginx-limit-req]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
Start and enable Fail2Ban:
sudo systemctl restart fail2ban
sudo systemctl enable fail2ban
5. Nginx Rate Limiting
Configure Rate Limits
# Edit nginx.conf
sudo nano /etc/nginx/nginx.conf
Add to http block:
# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_req_zone $binary_remote_addr zone=static:10m rate=30r/s;
# Connection limiting
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
Apply to server blocks:
server {
# Rate limiting
limit_req zone=api burst=20 nodelay;
limit_req zone=login burst=5 nodelay;
limit_req zone=static burst=50 nodelay;
# Connection limiting
limit_conn conn_limit_per_ip 20;
# DDoS protection
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
# Buffer sizes
client_body_buffer_size 128K;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
client_max_body_size 10m;
}
6. Apache Rate Limiting
Install mod_evasive
# For Ubuntu/Debian
sudo apt install libapache2-mod-evasive
# For RHEL/CentOS
sudo yum install mod_evasive
# Enable the module
sudo a2enmod evasive
sudo systemctl restart apache2
Configure mod_evasive:
sudo nano /etc/apache2/mods-enabled/evasive.conf
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
DOSEmailNotify [email protected]
DOSLogDir "/var/log/mod_evasive"
</IfModule>
7. Cloudflare Setup
Free DDoS Protection
- Sign up for Cloudflare account
- Add your domain to Cloudflare
- Update your nameservers to Cloudflare's
- Enable "I'm Under Attack Mode" during attacks
Security Settings
- Security Level: High or Medium
- Challenge Passage: 30 minutes
- Browser Integrity Check: Enabled
- Web Application Firewall: Enabled
8. Advanced DDoS Protection
Install DDoS Deflate
# Download and install
wget https://github.com/ddos/deflate/archive/master.zip
unzip master.zip
cd deflate-master
sudo chmod +x install.sh
sudo ./install.sh
Configure DDoS Deflate
sudo nano /usr/local/ddos/ignore.ip.list
sudo nano /usr/local/ddos/ddos.conf
Key settings:
NO_OF_CONNECTIONS=150
BAN_PERIOD=600
EMAIL_TO="[email protected]"
APF_BAN=1
KILL=0
9. Monitoring and Detection
Real-time Monitoring
# Monitor connections
sudo netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr
# Monitor SYN packets
sudo netstat -s | grep SYN
# Check for suspicious IPs
sudo ss -tan state all | awk '{print $4}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -n 10
Install Monitoring Tools
# Install htop and iotop
sudo apt install htop iotop
# Install nethogs for network monitoring
sudo apt install nethogs
# Install goaccess for log analysis
sudo apt install goaccess
10. Emergency Response
During an Attack
- Stay Calm: Don't panic, follow your plan
- Identify Source: Check logs for attack patterns
- Block IPs: Use iptables to block malicious IPs
- Enable Cloudflare: Activate "I'm Under Attack Mode"
- Contact ISP: Report the attack to your hosting provider
Emergency Commands
# Block specific IP
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
# Block entire subnet
sudo iptables -A INPUT -s 192.168.1.0/24 -j DROP
# Save iptables rules
sudo iptables-save > /etc/iptables/rules.v4
# Monitor in real-time
sudo watch -n 1 'netstat -an | grep :80 | wc -l'
11. Testing Your Protection
Stress Testing Tools
# Install siege for testing
sudo apt install siege
# Test your server (only on your own server!)
siege -c 100 -t 30S http://yourdomain.com
# Use hping3 for SYN flood testing (careful!)
sudo hping3 -S --flood -p 80 your-server-ip
Validation Checklist
- ✅ Firewall rules are active
- ✅ Rate limiting is configured
- ✅ Fail2Ban is running
- ✅ Logs are being monitored
- ✅ Cloudflare is enabled
- ✅ Backup plan is ready
12. Best Practices
- Regular Updates: Keep all software updated
- Monitor Logs: Check server logs daily
- Backup Configuration: Document your protection setup
- Test Regularly: Validate your protection measures
- Have a Plan: Know what to do during an attack
- Use CDN: Cloudflare or similar services
- Load Balancing: Distribute traffic across servers
- Redundancy: Have backup servers ready
13. Conclusion
DDoS protection requires a multi-layered approach. By implementing these measures, you'll significantly improve your server's resilience against attacks. Remember that no protection is 100% foolproof, but proper configuration and monitoring can minimize the impact of most attacks.
Stay vigilant, keep your systems updated, and always have an emergency response plan ready. The key to surviving DDoS attacks is preparation and quick response.