Skip to content
Threats Guide

firewall_rules.txt

Firewall Rules for DDoS Mitigation

  • prevention
  • text
  • 302 lines

Run security tools only on systems you own or have written permission to test.

Source

View on GitHub
# Firewall Rules for DDoS Mitigation# Location: 01-network-security/ddos-attacks/prevention/firewall_rules.txt## These rules can be used with iptables (Linux) or adapted for other firewalls# IMPORTANT: Test in staging environment before applying to production ===============================================================================# IPTABLES RULES (Linux)=============================================================================== # 1. Basic Rate Limiting------------------------------------------------------------------------------ # Limit new TCP connections per IP (prevents SYN flood)iptables -A INPUT -p tcp --syn -m connlimit --connlimit-above 100 -j DROPiptables -A INPUT -p tcp --syn -m limit --limit 10/s --limit-burst 20 -j ACCEPT # Limit ICMP (ping) requestsiptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/second -j ACCEPTiptables -A INPUT -p icmp --icmp-type echo-request -j DROP # Limit UDP traffic (prevents UDP flood)iptables -A INPUT -p udp -m limit --limit 20/s --limit-burst 50 -j ACCEPTiptables -A INPUT -p udp -j DROP # 2. Connection Tracking------------------------------------------------------------------------------ # Drop invalid packetsiptables -A INPUT -m state --state INVALID -j DROP # Limit simultaneous connections per IPiptables -A INPUT -p tcp --syn -m connlimit --connlimit-above 50 -j REJECT --reject-with tcp-reset # 3. Port Specific Rules------------------------------------------------------------------------------ # Web server protection (port 80/443)iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 100 -j DROPiptables -A INPUT -p tcp --dport 443 -m connlimit --connlimit-above 100 -j DROP # SSH protection (port 22) - prevent brute forceiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --setiptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 -j DROP # DNS protection (port 53)iptables -A INPUT -p udp --dport 53 -m limit --limit 100/s --limit-burst 200 -j ACCEPTiptables -A INPUT -p udp --dport 53 -j DROP # 4. IP Based Filtering------------------------------------------------------------------------------ # Drop traffic from specific countries (using ipset)ipset create blocklist hash:netiptables -I INPUT -m set --match-set blocklist src -j DROP # Rate limit per IPiptables -A INPUT -m hashlimit --hashlimit-name per_ip_limit \         --hashlimit-mode srcip --hashlimit-srcmask 32 \         --hashlimit-above 1000/minute --hashlimit-burst 100 -j DROP # 5. SYN Flood Protection------------------------------------------------------------------------------ # Enable SYN cookies (kernel level)echo 1 > /proc/sys/net/ipv4/tcp_syncookies # Reduce SYN-RECEIVED connection timeoutecho 10 > /proc/sys/net/ipv4/tcp_synack_retries # Increase SYN backlogecho 2048 > /proc/sys/net/ipv4/tcp_max_syn_backlog # 6. Advanced Rules------------------------------------------------------------------------------ # Drop fragmented packets (common in some DDoS attacks)iptables -A INPUT -f -j DROP # Drop XMAS packetsiptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP # Drop NULL packetsiptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP # 7. Whitelist Trusted IPs------------------------------------------------------------------------------ # Allow trusted IPs without restrictionsiptables -I INPUT -s 192.168.1.0/24 -j ACCEPTiptables -I INPUT -s 10.0.0.0/8 -j ACCEPT # 8. Logging Suspicious Activity------------------------------------------------------------------------------ # Log dropped packets (with rate limiting to avoid log flood)iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "DDoS_DROP: " --log-level 4 ===============================================================================# NFTABLES RULES (Modern Linux)=============================================================================== # Create tablenft add table inet ddos_protection # Create chainnft add chain inet ddos_protection input { type filter hook input priority 0\; } # Rate limiting rulesnft add rule inet ddos_protection input tcp flags syn limit rate 10/second acceptnft add rule inet ddos_protection input tcp flags syn drop # Connection limitnft add rule inet ddos_protection input tcp flags syn ct count over 100 drop # Port specific limitsnft add rule inet ddos_protection input tcp dport 80 limit rate 1000/second acceptnft add rule inet ddos_protection input tcp dport 80 drop ===============================================================================# PF RULES (FreeBSD/OpenBSD)------------------------------------------------------------------------------ # Rate limitpass in proto tcp from any to any port www keep state (max-src-conn 100, max-src-conn-rate 200/5) # Block excessive connectionsblock drop in quick proto tcp from any to any port ssh flags S/SA keep state (max-src-conn 5, max-src-conn-rate 3/30) ===============================================================================# CISCO IOS RULES------------------------------------------------------------------------------ ! Rate limit TCP SYN packetsaccess-list 100 permit tcp any host YOUR_SERVER_IP establishedaccess-list 100 deny tcp any host YOUR_SERVER_IP ! Rate limit ICMPaccess-list 101 permit icmp any host YOUR_SERVER_IP echo-replyaccess-list 101 deny icmp any any echo-request ! Apply to interfaceinterface GigabitEthernet0/0 ip access-group 100 in ip access-group 101 in ===============================================================================# CLOUDFLARE / CDN RULES------------------------------------------------------------------------------ # Rate Limiting Rule (JSON format for API){  "description": "DDoS Protection Rule",  "expression": "(http.request.method in {'POST' 'PUT'})",  "action": "block",  "ratelimit": {    "characteristics": ["ip.src"],    "period": 60,    "requests_per_period": 100,    "mitigation_timeout": 600  }} ===============================================================================# KERNEL TUNING (/etc/sysctl.conf)------------------------------------------------------------------------------ # TCP/IP stack hardeningnet.ipv4.tcp_syncookies = 1net.ipv4.tcp_syn_retries = 2net.ipv4.tcp_synack_retries = 2net.ipv4.tcp_max_syn_backlog = 4096net.ipv4.tcp_fin_timeout = 10net.ipv4.tcp_keepalive_time = 300net.ipv4.tcp_keepalive_probes = 5net.ipv4.tcp_keepalive_intvl = 15 # Connection trackingnet.netfilter.nf_conntrack_max = 2000000net.netfilter.nf_conntrack_tcp_timeout_established = 600 # ICMP rate limitingnet.ipv4.icmp_ratelimit = 100net.ipv4.icmp_ratemask = 6160 # IP fragmentationnet.ipv4.ipfrag_high_thresh = 512000net.ipv4.ipfrag_low_thresh = 384000 ===============================================================================# APPLICATION LEVEL RULES (NGINX)------------------------------------------------------------------------------ # /etc/nginx/nginx.conf http {    # Rate limiting zones    limit_req_zone $binary_remote_addr zone=login:10m rate=10r/m;    limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;        # Connection limiting    limit_conn conn_limit 10;        # Client timeouts    client_body_timeout 10s;    client_header_timeout 10s;    keepalive_timeout 5s;    send_timeout 10s;        # Buffer sizes    client_body_buffer_size 16k;    client_header_buffer_size 1k;    large_client_header_buffers 4 8k;        server {        location /login {            limit_req zone=login burst=5 delay=3;            proxy_pass http://backend;        }                location /api/ {            limit_req zone=api burst=200 nodelay;            proxy_pass http://api_backend;        }    }} ===============================================================================# APPLICATION LEVEL RULES (APACHE)------------------------------------------------------------------------------ # /etc/apache2/apache2.conf or .htaccess # mod_evasive configuration<IfModule mod_evasive20.c>    DOSHashTableSize    3097    DOSPageCount        5    DOSSiteCount        50    DOSPageInterval     1    DOSSiteInterval     1    DOSBlockingPeriod   300    DOSEmailNotify      admin@example.com    DOSSystemCommand    "sudo /sbin/iptables -A INPUT -s %s -j DROP"    DOSLogDir           "/var/log/mod_evasive"</IfModule> # mod_ratelimit<IfModule mod_ratelimit.c>    <Location /api/>        SetOutputFilter RATE_LIMIT        SetEnv rate-limit 400    </Location></IfModule> ===============================================================================# MONITORING AND ALERTING------------------------------------------------------------------------------ # Simple monitoring script (check_ddos.sh)#!/bin/bash # Check for high connection ratesCONNECTIONS=$(netstat -an | grep :80 | wc -l)SYN_COUNT=$(netstat -an | grep SYN_RECV | wc -l) if [ $CONNECTIONS -gt 10000 ]; then    echo "High connection count: $CONNECTIONS" | mail -s "DDoS Alert" admin@example.comfi if [ $SYN_COUNT -gt 1000 ]; then    echo "High SYN_RECV count: $SYN_COUNT" | mail -s "Possible SYN Flood" admin@example.comfi ===============================================================================# IMPORTANT NOTES=============================================================================== 1. TESTING   - Always test rules in a staging environment first   - Monitor impact on legitimate users   - Have rollback procedures ready 2. MAINTENANCE   - Review and update rules regularly   - Monitor logs for false positives   - Adjust thresholds based on normal traffic patterns 3. DEFENSE IN DEPTH   - Combine firewall rules with application-level protection   - Use CDN and DDoS protection services for large attacks   - Implement monitoring and alerting 4. LEGAL COMPLIANCE   - Ensure compliance with local laws and regulations   - Document all rules and changes   - Maintain audit trails ===============================================================================# END OF RULES===============================================================================