implementing-ddos-mitigation-with-cloudflare について
Cloudflare の DDoS 防御を設定するセキュリティスキルです。マネージドルールセット、レート制限、WAF ルール、オリジン保護、自動化、監視を扱います。
主な機能
- 01DDoS マネージドルールセットの設定
- 02レート制限と WAF ルールの設定
- 03オリジンサーバーへのアクセス制限
- 04Under Attack Mode の自動化
- 05攻撃イベントとアラートの監視
活用シーン
- 01ドメインへの DDoS 対策の導入
- 02直接アクセスを防ぐオリジン保護
- 03防御設定の調整と攻撃イベントの監視
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ mukul975/ anthropic-cybersecurity-skills --skill implementing-ddos-mitigation-with-cloudflareインストール後、Claude Code で/implementing-ddos-mitigation-with-cloudflareを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
LICENSEreferences/api-reference.mdscripts/agent.py詳細
Cloudflare による DDoS 緩和の実装
概要
Cloudflare は、300 を超えるデータセンターと 477 Tbps 以上の容量を持つグローバルネットワーク全体で、多層的な DDoS 保護を提供しています。このプラットフォームは、L3/4 のボリューム型攻撃(SYN フラッド、UDP 増幅、DNS リフレクション)、プロトコル攻撃(Ping of Death、Smurf)、L7 のアプリケーション層攻撃(HTTP フラッド、Slowloris、キャッシュバスティング)から保護します。Cloudflare の自律検知システムは、トラフィックプロファイリング、機械学習、適応型ルールセットを使用して、約 3 秒以内に攻撃を検知し、緩和します。このスキルでは、マネージドルールセット、WAF ルール、レート制限、Bot Management、オリジンサーバーの強化など、Cloudflare の DDoS 保護スタックの設定について説明します。
使用する場面
- 環境に Cloudflare による DDoS 緩和機能をデプロイまたは設定する場合
- コンプライアンス要件に沿ったセキュリティ制御を確立する場合
- この分野のセキュリティアーキテクチャを構築または改善する場合
- この実装を必要とするセキュリティ評価を実施する場合
前提条件
- Cloudflare アカウント(WAF には Pro プラン以上、高度な DDoS 保護には Enterprise プラン)
- DNS が Cloudflare のネームサーバーに委任されたドメイン
- オリジンサーバーの IP アドレス
- 通常のトラフィックパターンとピーク時のトラフィック量に関する理解
- 自動化用の Cloudflare API トークン
基本概念
DDoS 攻撃の分類
| レイヤー | 攻撃タイプ | 例 | Cloudflare の保護 |
|---|---|---|---|
| L3/4 | ボリューム型 | SYN フラッド、UDP フラッド、DNS 増幅 | ネットワーク層 DDoS マネージドルール |
| L3/4 | プロトコル | Ping of Death、Smurf、IP フラグメンテーション | 高度な TCP 保護 |
| L7 | アプリケーション | HTTP フラッド、Slowloris、キャッシュバスティング | HTTP DDoS マネージドルール、WAF、レート制限 |
| DNS | DNS 固有 | DNS クエリフラッド、NXDOMAIN 攻撃 | 高度な DNS 保護 |
Cloudflare の保護スタック
Internet Traffic
│
▼
┌─────────────────────────┐
│ Cloudflare Edge (PoP) │
│ ┌───────────────────┐ │
│ │ L3/4 DDoS Mgd Rules│ │ ← Volumetric/Protocol mitigation
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ IP Access Rules │ │ ← Country/ASN/IP blocks
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ Bot Management │ │ ← Bot score, JS challenge
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ WAF Managed Rules │ │ ← OWASP, Cloudflare, Custom
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ Rate Limiting │ │ ← Request rate enforcement
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ HTTP DDoS Mgd Rules│ │ ← L7 flood detection
│ └───────────────────┘ │
└─────────────────────────┘
│
▼
Origin Server
ワークフロー
ステップ 1:ドメインを Cloudflare にオンボーディングする
# Add domain via API
curl -X POST "https://api.cloudflare.com/client/v4/zones" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"name": "example.com",
"type": "full",
"plan": {"id": "enterprise"}
}'
# Update DNS records (proxy enabled for DDoS protection)
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type": "A",
"name": "example.com",
"content": "203.0.113.50",
"proxied": true,
"ttl": 1
}'
ステップ 2:DDoS マネージドルールセットを設定する
HTTP DDoS 攻撃保護のオーバーライド:
# List HTTP DDoS managed ruleset
curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/ddos_l7/entrypoint" \
-H "Authorization: Bearer $CF_API_TOKEN"
# Override HTTP DDoS sensitivity and action
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/ddos_l7/entrypoint" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"rules": [{
"action": "execute",
"action_parameters": {
"id": "4d21379b4f9f4bb088e0729962c8b3cf",
"overrides": {
"rules": [{
"id": "fdfdac75430c4c47a422bdc024aab531",
"sensitivity_level": "medium",
"action": "block"
}],
"sensitivity_level": "high"
}
},
"expression": "true"
}]
}'
ネットワーク層 DDoS 保護のオーバーライド:
curl -X PUT "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/rulesets/phases/ddos_l4/entrypoint" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"rules": [{
"action": "execute",
"action_parameters": {
"id": "3b64149bfa6e4220bbbc2bd6db7c867e",
"overrides": {
"sensitivity_level": "high"
}
},
"expression": "true"
}]
}'
ステップ 3:レート制限ルールを設定する
# Create rate limiting rule for login endpoint
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_ratelimit/entrypoint" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"rules": [
{
"description": "Rate limit login attempts",
"expression": "(http.request.uri.path eq \"/api/login\")",
"action": "block",
"ratelimit": {
"characteristics": ["cf.colo.id", "ip.src"],
"period": 60,
"requests_per_period": 10,
"mitigation_timeout": 600
}
},
{
"description": "Rate limit API endpoints",
"expression": "(http.request.uri.path matches \"^/api/\")",
"action": "managed_challenge",
"ratelimit": {
"characteristics": ["cf.colo.id", "ip.src"],
"period": 60,
"requests_per_period": 100,
"mitigation_timeout": 300
}
},
{
"description": "Global rate limit per IP",
"expression": "true",
"action": "managed_challenge",
"ratelimit": {
"characteristics": ["ip.src"],
"period": 10,
"requests_per_period": 50,
"mitigation_timeout": 60
}
}
]
}'
ステップ 4:WAF カスタムルールを設定する
# Block known attack patterns
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_firewall_custom/entrypoint" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"rules": [
{
"description": "Block requests from known bad ASNs",
"expression": "(ip.geoip.asnum in {12345 67890})",
"action": "block"
},
{
"description": "Challenge requests without User-Agent",
"expression": "(not http.user_agent ne \"\")",
"action": "managed_challenge"
},
{
"description": "Block high-risk countries for admin paths",
"expression": "(http.request.uri.path contains \"/admin\" and not ip.geoip.country in {\"US\" \"CA\" \"GB\"})",
"action": "block"
},
{
"description": "Block oversized request bodies",
"expression": "(http.request.body.size gt 10000000)",
"action": "block"
}
]
}'
ステップ 5:オリジンを保護する
オリジンサーバーが Cloudflare からのトラフィックのみを受け入れるようにします。
# Get Cloudflare IP ranges
curl https://api.cloudflare.com/client/v4/ips
# Configure origin server firewall (iptables)
# Allow only Cloudflare IPs
for ip in $(curl -s https://www.cloudflare.com/ips-v4); do
iptables -A INPUT -p tcp --dport 443 -s $ip -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -s $ip -j ACCEPT
done
# Drop all other HTTP/HTTPS traffic
iptables -A INPUT -p tcp --dport 443 -j DROP
iptables -A INPUT -p tcp --dport 80 -j DROP
# Enable Authenticated Origin Pulls (mutual TLS)
# Download Cloudflare origin CA certificate
curl -o /etc/ssl/cloudflare-origin-pull.pem \
https://developers.cloudflare.com/ssl/static/authenticated_origin_pull_ca.pem
# Nginx configuration for authenticated origin pulls
# ssl_client_certificate /etc/ssl/cloudflare-origin-pull.pem;
# ssl_verify_client on;
ステップ 6:「攻撃を受けています」モードの自動化を有効にする
#!/usr/bin/env python3
"""Auto-enable Cloudflare Under Attack Mode based on traffic anomalies."""
import requests
import time
import sys
CF_API_TOKEN = "your-api-token"
ZONE_ID = "your-zone-id"
HEADERS = {
"Authorization": f"Bearer {CF_API_TOKEN}",
"Content-Type": "application/json",
}
BASE_URL = f"https://api.cloudflare.com/client/v4/zones/{ZONE_ID}"
NORMAL_RPS_THRESHOLD = 5000 # Requests per second threshold
CHECK_INTERVAL = 30 # Seconds between checks
def get_current_security_level():
"""Get current security level setting."""
resp = requests.get(
f"{BASE_URL}/settings/security_level",
headers=HEADERS
)
return resp.json()["result"]["value"]
def set_security_level(level: str):
"""Set security level (off, essentially_off, low, medium, high, under_attack)."""
resp = requests.patch(
f"{BASE_URL}/settings/security_level",
headers=HEADERS,
json={"value": level}
)
result = resp.json()
if result["success"]:
print(f"[+] Security level set to: {level}")
else:
print(f"[-] Failed to set security level: {result['errors']}")
return result["success"]
def get_traffic_analytics():
"""Get recent traffic data from Cloudflare analytics."""
query = """
query {
viewer {
zones(filter: {zoneTag: "%s"}) {
httpRequests1mGroups(limit: 1, orderBy: [datetime_DESC]) {
sum {
requests
threats
}
dimensions {
datetime
}
}
}
}
}
""" % ZONE_ID
resp = requests.post(
"https://api.cloudflare.com/client/v4/graphql",
headers=HEADERS,
json={"query": query}
)
return resp.json()
def monitor_and_respond():
"""Monitor traffic and auto-enable under attack mode."""
current_level = get_current_security_level()
print(f"[*] Current security level: {current_level}")
print(f"[*] Monitoring traffic (threshold: {NORMAL_RPS_THRESHOLD} RPS)...")
attack_mode_active = False
consecutive_normal = 0
while True:
try:
analytics = get_traffic_analytics()
zones = analytics.get("data", {}).get("viewer", {}).get("zones", [])
if zones and zones[0].get("httpRequests1mGroups"):
data = zones[0]["httpRequests1mGroups"][0]["sum"]
rps = data["requests"] / 60
threats = data["threats"]
print(f"[*] Current RPS: {rps:.0f}, Threats: {threats}")
if rps > NORMAL_RPS_THRESHOLD and not attack_mode_active:
print(f"[!] Traffic spike detected: {rps:.0f} RPS")
set_security_level("under_attack")
attack_mode_active = True
consecutive_normal = 0
elif rps <= NORMAL_RPS_THRESHOLD and attack_mode_active:
consecutive_normal += 1
if consecutive_normal >= 5:
print("[+] Traffic normalized, disabling under attack mode")
set_security_level("high")
attack_mode_active = False
consecutive_normal = 0
except Exception as e:
print(f"[-] Error: {e}")
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
monitor_and_respond()
監視とアラート
Cloudflare ダッシュボードのメトリクス
- ファイアウォールイベント - ブロックされたリクエスト、チャレンジされたリクエスト、レート制限されたリクエストを確認します
- DDoS 分析 - 攻撃の規模、継続時間、種類、緩和状況
- トラフィック分析 - 時間別のリクエスト量、帯域幅、エラー率
- ボット分析 - ボットスコアの分布、検証済みボットと自動化された脅威の比較
アラートの設定
# Create notification policy for DDoS attacks
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/alerting/v3/policies" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"name": "DDoS Attack Alert",
"alert_type": "dos_attack_l7",
"enabled": true,
"mechanisms": {
"email": [{"id": "[email protected]"}],
"webhooks": [{"id": "webhook-id"}]
},
"filters": {
"zones": ["'$ZONE_ID'"]
}
}'
ベストプラクティス
- すべての DNS レコードをプロキシする - オリジンを指すすべての A/AAAA/CNAME レコードがプロキシされていることを確認します(オレンジ色の雲)
- オリジン IP を隠す - オリジンサーバーの IP を決して公開せず、Cloudflare Tunnel を使用するか、Cloudflare の IP のみを許可します
- ログモードから始める - 「Block」に切り替える前に、DDoS ルールのオーバーライドを「Log」アクションでテストします
- 多層防御を実施する - マネージドルールセット、レート制限、WAF ルール、Bot Management を組み合わせます
- 感度を調整する - トラフィックでの誤検知率に基づいて DDoS ルールの感度を調整します
- キャッシュ戦略 - 攻撃中のオリジン負荷を軽減するため、キャッシュヒット率を最大化します
- Waiting Room - トラフィック急増時に重要なページを保護するため、Cloudflare Waiting Room を設定します
- 認証済みオリジン - オリジンへの直接攻撃を防ぐため、Authenticated Origin Pulls を有効にします
参考資料
コメント
Markdown 対応