🔒 Security

DDoS

Distributed Denial of Service

A cyberattack in which many systems (a botnet) simultaneously generate massive traffic to exhaust the resources of a target server or network and make normal service impossible. In September 2025, Cloudflare mitigated a 22.2Tbps attack, setting a new record. Attack scale has grown more than 20-fold in five years, from 1-2Tbps in 2020, and multilayer defense against both L3/L4 volumetric attacks and L7 application attacks is essential.

📖 Detailed Explanation

DDoS attacks are classified according to the OSI 7-layer model. L3/L4 volumetric attacks (SYN Flood, UDP Flood, ICMP Flood) exhaust network bandwidth and server connection tables. L7 application attacks (HTTP Flood, Slowloris, DNS Query Flood) are more sophisticated and drain a web application's resources (CPU, memory, DB connections). Modern attackers combine the two in multi-vector attacks, and no single layer of defense can counter them.

The scale of DDoS attacks is growing exponentially. The largest attacks, at 1-2Tbps in 2020, surged to 22.2Tbps in 2025. This is due to the spread of IoT botnets (Mirai variants), increasingly sophisticated reflection/amplification techniques (DNS, NTP, Memcached amplification), and the growth of the DDoS-as-a-Service criminal market. Experts predict that 50-100Tbps attacks may be possible within 2-3 years. Attacks of this scale can never be absorbed by a single organization's infrastructure, so cloud-based distributed defense is essential.

The core of cloud DDoS protection services is the Anycast network. Services such as Cloudflare (200+ Tbps), AWS Shield, and Akamai absorb attacks by distributing traffic across hundreds of PoPs (Points of Presence) worldwide. Cloudflare provides automatic detection and mitigation within 3 seconds, and AWS Shield Advanced offers 24/7 DDoS Response Team (DRT) support and cost protection. As of December 2025, Cloudflare holds a 17.8% market share and AWS Shield 5.2%.

The 2025 DDoS defense trends are AI/ML-based real-time detection, Zero Trust integration, and stronger API protection. Traditional threshold-based detection struggles to tell normal traffic surges from attacks, while ML models analyze traffic patterns, geographic distribution, and request characteristics to identify even sophisticated L7 attacks. As attacks targeting API endpoints surge in particular, the API-specific features of WAF and Rate Limiting have become important. Using Bot Management to distinguish legitimate users from malicious bots is also central to L7 defense.

💻 Code Example

# Nginx DDoS 방어 설정 예제

# 1. Rate Limiting 설정
# /etc/nginx/nginx.conf

http {
    # Rate Limiting Zone 정의
    # $binary_remote_addr: 클라이언트 IP별 제한
    # zone=req_limit:10m: 10MB 메모리로 약 160,000 IP 추적
    # rate=10r/s: 초당 10 요청 허용

    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;

    # 연결 수 제한
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    # 기본 타임아웃 설정 (Slowloris 방어)
    client_body_timeout 10s;
    client_header_timeout 10s;
    keepalive_timeout 30s;
    send_timeout 10s;

    # 요청 크기 제한 (Buffer Overflow 방어)
    client_body_buffer_size 1k;
    client_header_buffer_size 1k;
    client_max_body_size 1m;
    large_client_header_buffers 2 1k;

    # 서버 블록
    server {
        listen 80;
        server_name example.com;

        # 전역 Rate Limiting
        # burst=20: 버스트 20 요청 허용
        # nodelay: 버스트 즉시 처리 (지연 없음)
        limit_req zone=req_limit burst=20 nodelay;

        # 연결 제한: IP당 최대 10개 동시 연결
        limit_conn conn_limit 10;

        # Rate Limit 초과 시 응답 코드
        limit_req_status 429;
        limit_conn_status 429;

        # 로그인 엔드포인트 강화된 제한
        location /api/login {
            limit_req zone=login_limit burst=5 nodelay;

            proxy_pass http://backend;
        }

        # 정적 자산은 제한 완화
        location /static/ {
            limit_req zone=req_limit burst=100 nodelay;
            expires 1d;
            add_header Cache-Control "public, immutable";
        }

        # API 엔드포인트
        location /api/ {
            # IP당 Rate Limit
            limit_req zone=req_limit burst=30 nodelay;

            # 악성 User-Agent 차단
            if ($http_user_agent ~* (curl|wget|python|libwww|java|httpclient)) {
                return 403;
            }

            # 빈 User-Agent 차단
            if ($http_user_agent = "") {
                return 403;
            }

            proxy_pass http://backend;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        # 에러 페이지
        error_page 429 /429.html;
        location = /429.html {
            internal;
            default_type text/html;
            return 429 '
                
                429 Too Many Requests
                
                    

429 Too Many Requests

요청이 너무 많습니다. 잠시 후 다시 시도해주세요.

'; } } # 업스트림 서버 (Load Balancing) upstream backend { least_conn; # 연결 수 최소 서버로 분배 server 10.0.0.1:8080 weight=3; server 10.0.0.2:8080 weight=2; server 10.0.0.3:8080 backup; # 백업 서버 # Health Check keepalive 32; } } # /etc/nginx/conf.d/geo-block.conf # 특정 국가 차단 (GeoIP2 모듈 필요) # geo $blocked_country { # default 0; # # 공격 빈발 국가 차단 (예시) # include /etc/nginx/geo-block-list.conf; # } # # server { # if ($blocked_country) { # return 403; # } # }
# Cloudflare API를 사용한 DDoS 방어 자동화 - Python
import requests
import json
from datetime import datetime, timedelta

class CloudflareDDoSDefense:
    """Cloudflare API를 통한 DDoS 방어 자동화"""

    def __init__(self, api_token: str, zone_id: str):
        self.api_token = api_token
        self.zone_id = zone_id
        self.base_url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}"
        self.headers = {
            "Authorization": f"Bearer {api_token}",
            "Content-Type": "application/json"
        }

    def get_analytics(self, minutes: int = 60):
        """트래픽 분석 데이터 조회"""
        since = (datetime.utcnow() - timedelta(minutes=minutes)).isoformat() + "Z"

        response = requests.get(
            f"{self.base_url}/analytics/dashboard",
            headers=self.headers,
            params={"since": since, "continuous": "true"}
        )

        return response.json()

    def get_ddos_events(self):
        """DDoS 공격 이벤트 조회"""
        response = requests.get(
            f"{self.base_url}/security/events",
            headers=self.headers,
            params={
                "action": "challenge,block,managed_challenge",
                "source": "l7ddos",
                "limit": 100
            }
        )

        return response.json()

    def create_rate_limit_rule(self, path: str, threshold: int, period: int):
        """Rate Limit 규칙 생성"""
        rule = {
            "description": f"Rate limit for {path}",
            "match": {
                "request": {
                    "url": f"*{path}*",
                    "schemes": ["HTTP", "HTTPS"],
                    "methods": ["GET", "POST"]
                }
            },
            "threshold": threshold,
            "period": period,
            "action": {
                "mode": "challenge",
                "timeout": 3600
            }
        }

        response = requests.post(
            f"{self.base_url}/rate_limits",
            headers=self.headers,
            json=rule
        )

        return response.json()

    def create_firewall_rule(self, expression: str, action: str = "block"):
        """방화벽 규칙 생성"""
        # 먼저 필터 생성
        filter_response = requests.post(
            f"{self.base_url}/filters",
            headers=self.headers,
            json=[{"expression": expression}]
        )

        if not filter_response.json()["success"]:
            return filter_response.json()

        filter_id = filter_response.json()["result"][0]["id"]

        # 방화벽 규칙 생성
        rule_response = requests.post(
            f"{self.base_url}/firewall/rules",
            headers=self.headers,
            json=[{
                "filter": {"id": filter_id},
                "action": action,
                "description": f"Auto-created rule: {expression[:50]}"
            }]
        )

        return rule_response.json()

    def enable_under_attack_mode(self):
        """Under Attack Mode 활성화 (긴급 상황)"""
        response = requests.patch(
            f"{self.base_url}/settings/security_level",
            headers=self.headers,
            json={"value": "under_attack"}
        )

        return response.json()

    def disable_under_attack_mode(self):
        """Under Attack Mode 비활성화"""
        response = requests.patch(
            f"{self.base_url}/settings/security_level",
            headers=self.headers,
            json={"value": "high"}  # 또는 medium, low
        )

        return response.json()

    def block_ip(self, ip: str, note: str = ""):
        """특정 IP 차단"""
        response = requests.post(
            f"{self.base_url}/firewall/access_rules/rules",
            headers=self.headers,
            json={
                "mode": "block",
                "configuration": {
                    "target": "ip",
                    "value": ip
                },
                "notes": note or f"Blocked by automation at {datetime.utcnow()}"
            }
        )

        return response.json()

    def block_country(self, country_code: str):
        """특정 국가 차단"""
        response = requests.post(
            f"{self.base_url}/firewall/access_rules/rules",
            headers=self.headers,
            json={
                "mode": "block",
                "configuration": {
                    "target": "country",
                    "value": country_code
                },
                "notes": f"Country block: {country_code}"
            }
        )

        return response.json()

    def get_bot_management_analytics(self):
        """Bot Management 분석"""
        response = requests.get(
            f"{self.base_url}/bot_management/summary",
            headers=self.headers
        )

        return response.json()


# 자동 방어 스크립트 예시
def auto_defend(cf: CloudflareDDoSDefense):
    """트래픽 분석 및 자동 방어"""

    # 최근 5분 분석
    analytics = cf.get_analytics(minutes=5)

    # 요청 수 급증 감지
    total_requests = analytics["result"]["totals"]["requests"]["all"]
    avg_requests = analytics["result"]["totals"]["requests"]["cached"] + \
                   analytics["result"]["totals"]["requests"]["uncached"]

    # 임계값 초과 시 Under Attack Mode
    THRESHOLD = 100000  # 5분 내 10만 요청

    if total_requests > THRESHOLD:
        print(f"[ALERT] High traffic detected: {total_requests} requests")
        cf.enable_under_attack_mode()

        # Slack/PagerDuty 알림 (실제 구현 필요)
        # notify_team(f"DDoS Alert: {total_requests} requests in 5 min")

    # DDoS 이벤트 확인
    events = cf.get_ddos_events()
    if events.get("result"):
        for event in events["result"][:10]:
            print(f"DDoS Event: {event['action']} from {event.get('clientIP', 'unknown')}")


if __name__ == "__main__":
    cf = CloudflareDDoSDefense(
        api_token="your-api-token",
        zone_id="your-zone-id"
    )

    # Under Attack Mode 긴급 활성화
    # cf.enable_under_attack_mode()

    # 특정 패턴 차단
    cf.create_firewall_rule(
        expression='(http.request.uri.path contains "/wp-login.php") and (cf.threat_score gt 10)',
        action="block"
    )

    # API Rate Limiting
    cf.create_rate_limit_rule(
        path="/api/",
        threshold=100,  # 100 요청
        period=60       # 60초당
    )
# AWS Shield Advanced + WAF 설정 - CloudFormation

AWSTemplateFormatVersion: '2010-09-09'
Description: 'DDoS Protection with AWS Shield Advanced and WAF'

Parameters:
  Environment:
    Type: String
    Default: production
  ApplicationName:
    Type: String
    Default: my-app

Resources:
  # WAF WebACL
  WebACL:
    Type: AWS::WAFv2::WebACL
    Properties:
      Name: !Sub '${ApplicationName}-webacl'
      Description: DDoS and Bot Protection
      Scope: REGIONAL  # CLOUDFRONT for CloudFront
      DefaultAction:
        Allow: {}
      VisibilityConfig:
        CloudWatchMetricsEnabled: true
        MetricName: !Sub '${ApplicationName}-webacl'
        SampledRequestsEnabled: true

      Rules:
        # 1. AWS Managed Rules - Common Rule Set
        - Name: AWSManagedRulesCommonRuleSet
          Priority: 1
          OverrideAction:
            None: {}
          VisibilityConfig:
            CloudWatchMetricsEnabled: true
            MetricName: AWSManagedRulesCommon
            SampledRequestsEnabled: true
          Statement:
            ManagedRuleGroupStatement:
              VendorName: AWS
              Name: AWSManagedRulesCommonRuleSet

        # 2. AWS Managed Rules - Known Bad Inputs
        - Name: AWSManagedRulesKnownBadInputsRuleSet
          Priority: 2
          OverrideAction:
            None: {}
          VisibilityConfig:
            CloudWatchMetricsEnabled: true
            MetricName: AWSManagedRulesKnownBadInputs
            SampledRequestsEnabled: true
          Statement:
            ManagedRuleGroupStatement:
              VendorName: AWS
              Name: AWSManagedRulesKnownBadInputsRuleSet

        # 3. Rate Limiting Rule
        - Name: RateLimitRule
          Priority: 3
          Action:
            Block: {}
          VisibilityConfig:
            CloudWatchMetricsEnabled: true
            MetricName: RateLimitRule
            SampledRequestsEnabled: true
          Statement:
            RateBasedStatement:
              Limit: 2000  # 5분간 2000 요청
              AggregateKeyType: IP

        # 4. API 엔드포인트 강화된 Rate Limit
        - Name: APIRateLimitRule
          Priority: 4
          Action:
            Block: {}
          VisibilityConfig:
            CloudWatchMetricsEnabled: true
            MetricName: APIRateLimitRule
            SampledRequestsEnabled: true
          Statement:
            RateBasedStatement:
              Limit: 500  # 5분간 500 요청
              AggregateKeyType: IP
              ScopeDownStatement:
                ByteMatchStatement:
                  FieldToMatch:
                    UriPath: {}
                  PositionalConstraint: STARTS_WITH
                  SearchString: '/api/'
                  TextTransformations:
                    - Priority: 0
                      Type: LOWERCASE

        # 5. Geo Blocking (특정 국가 차단)
        - Name: GeoBlockRule
          Priority: 5
          Action:
            Block: {}
          VisibilityConfig:
            CloudWatchMetricsEnabled: true
            MetricName: GeoBlockRule
            SampledRequestsEnabled: true
          Statement:
            GeoMatchStatement:
              CountryCodes:
                - XX  # 차단할 국가 코드

        # 6. Bot Control (추가 비용)
        - Name: AWSManagedRulesBotControlRuleSet
          Priority: 6
          OverrideAction:
            None: {}
          VisibilityConfig:
            CloudWatchMetricsEnabled: true
            MetricName: BotControl
            SampledRequestsEnabled: true
          Statement:
            ManagedRuleGroupStatement:
              VendorName: AWS
              Name: AWSManagedRulesBotControlRuleSet

  # ALB에 WebACL 연결
  WebACLAssociation:
    Type: AWS::WAFv2::WebACLAssociation
    Properties:
      ResourceArn: !Ref ApplicationLoadBalancer
      WebACLArn: !GetAtt WebACL.Arn

  # Shield Advanced Protection (구독 필요: $3000/월)
  # ShieldProtection:
  #   Type: AWS::Shield::Protection
  #   Properties:
  #     Name: !Sub '${ApplicationName}-shield'
  #     ResourceArn: !Ref ApplicationLoadBalancer

  # CloudWatch 알람 - DDoS 탐지
  DDoSAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmName: !Sub '${ApplicationName}-ddos-detected'
      AlarmDescription: 'Potential DDoS attack detected'
      MetricName: BlockedRequests
      Namespace: AWS/WAFV2
      Statistic: Sum
      Period: 300
      EvaluationPeriods: 1
      Threshold: 1000
      ComparisonOperator: GreaterThanThreshold
      Dimensions:
        - Name: WebACL
          Value: !Sub '${ApplicationName}-webacl'
        - Name: Region
          Value: !Ref AWS::Region
        - Name: Rule
          Value: RateLimitRule
      AlarmActions:
        - !Ref AlertSNSTopic

  # SNS Topic for Alerts
  AlertSNSTopic:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: !Sub '${ApplicationName}-ddos-alerts'

Outputs:
  WebACLArn:
    Description: WebACL ARN
    Value: !GetAtt WebACL.Arn
  WebACLId:
    Description: WebACL ID
    Value: !Ref WebACL

🗣️ Say It Like This in Practice

💬 In an infrastructure architecture meeting
"DDoS defense must be built in multiple layers. Put Cloudflare or AWS Shield in front of the CDN to absorb L3/L4 volumetric attacks, and use a WAF to filter L7 application attacks. Attacks of up to 22Tbps appeared in 2025, so it's impossible with our own infrastructure alone, and a cloud service with a 200Tbps+ network is a must."
💬 During an emergency response
"An L7 HTTP Flood attack is currently in progress. We've enabled Cloudflare Under Attack Mode and are blocking the attacking IP ranges. We've tightened Rate Limiting on the API endpoints to 100req/min. Legitimate users may be affected, so I'll ask the CS team to post a notice, analyze the attack pattern, and add WAF rules. I'll give a status update in 30 minutes."
💬 In a cost optimization discussion
"For a small scale, start with the Cloudflare Free/Pro plan. Basic DDoS protection is included, and Pro is $20 per month. AWS Shield Standard is also free, but it only defends against L3/L4. If you need L7 protection and expert support, there's Shield Advanced ($3000/month), which includes protection against cost spikes caused by DDoS, making costs predictable."

⚠️ Cautions & Best Practices

❌
Relying on single-layer defense

Having only a WAF or only a CDN is not enough. You need multi-layer defense: CDN/Shield for L3/L4 attacks, and WAF + Rate Limiting for L7 attacks. Attackers use multiple vectors at the same time.

❌
Exposing the origin IP directly

Even if you use a CDN, if the origin server IP is exposed, attackers can bypass the CDN and attack it directly. Whitelist only CDN IPs for the origin IP, and change the IP if it has ever been exposed in DNS history.

❌
No advance response plan

If you start looking for a response after an attack occurs, it's already too late. Document a DDoS response playbook and define contact channels, escalation paths, and mitigation procedures in advance. Verify your response capability with quarterly drills.

✅
DDoS defense best practices

Use a cloud-based DDoS protection service, keep the origin IP private and whitelist only CDN IPs, apply Rate Limiting and Bot Management, absorb surges with auto scaling, run regular load tests and capacity planning, document and drill the response playbook, and automate monitoring and alerts.

🔗 Related Terms

📚 Learn More