implementing-ddos-mitigation-with-cloudflare
配置 Cloudflare DDoS 防护,包括托管规则集、速率限制、WAF 规则、Bot 管理和源站保护,以缓解容量型、协议型和应用层攻击。
Best use case
implementing-ddos-mitigation-with-cloudflare is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
配置 Cloudflare DDoS 防护,包括托管规则集、速率限制、WAF 规则、Bot 管理和源站保护,以缓解容量型、协议型和应用层攻击。
Teams using implementing-ddos-mitigation-with-cloudflare should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/implementing-ddos-mitigation-with-cloudflare/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How implementing-ddos-mitigation-with-cloudflare Compares
| Feature / Agent | implementing-ddos-mitigation-with-cloudflare | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
配置 Cloudflare DDoS 防护,包括托管规则集、速率限制、WAF 规则、Bot 管理和源站保护,以缓解容量型、协议型和应用层攻击。
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# 使用 Cloudflare 实施 DDoS 缓解
## 概述
Cloudflare 通过其遍布全球 300 多个数据中心、477+ Tbps 容量的网络提供多层 DDoS(分布式拒绝服务)防护。该平台防护 L3/4 容量型攻击(SYN 洪水、UDP 放大、DNS 反射)、协议攻击(Ping of Death、Smurf)和 L7 应用层攻击(HTTP 洪水、Slowloris、缓存破坏)。Cloudflare 的自主检测系统使用流量分析、机器学习和自适应规则集,在约 3 秒内识别并缓解攻击。本技能涵盖配置 Cloudflare DDoS 防护栈,包括托管规则集、WAF 规则、速率限制、Bot 管理和源站服务器加固。
## 前置条件
- 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 防护栈
```
互联网流量
│
▼
┌─────────────────────────┐
│ Cloudflare 边缘节点(PoP)│
│ ┌───────────────────┐ │
│ │ L3/4 DDoS 托管规则 │ │ ← 容量型/协议型缓解
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ IP 访问规则 │ │ ← 国家/ASN/IP 封锁
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ Bot 管理 │ │ ← Bot 评分、JS 验证
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ WAF 托管规则 │ │ ← OWASP、Cloudflare、自定义
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ 速率限制 │ │ ← 请求速率执行
│ └───────────────────┘ │
│ ┌───────────────────┐ │
│ │ HTTP DDoS 托管规则 │ │ ← L7 洪水检测
│ └───────────────────┘ │
└─────────────────────────┘
│
▼
源站服务器
```
## 步骤
### 步骤 1:将域名接入 Cloudflare
```bash
# 通过 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"}
}'
# 更新 DNS 记录(启用代理以获得 DDoS 防护)
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 攻击防护覆盖:**
```bash
# 列出 HTTP DDoS 托管规则集
curl -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/ddos_l7/entrypoint" \
-H "Authorization: Bearer $CF_API_TOKEN"
# 覆盖 HTTP DDoS 灵敏度和动作
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 防护覆盖:**
```bash
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:配置速率限制规则
```bash
# 为登录端点创建速率限制规则
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 自定义规则
```bash
# 阻止已知攻击模式
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 的流量:
```bash
# 获取 Cloudflare IP 范围
curl https://api.cloudflare.com/client/v4/ips
# 配置源站服务器防火墙(iptables)
# 只允许 Cloudflare IP
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
# 丢弃所有其他 HTTP/HTTPS 流量
iptables -A INPUT -p tcp --dport 443 -j DROP
iptables -A INPUT -p tcp --dport 80 -j DROP
# 启用认证源站拉取(双向 TLS)
# 下载 Cloudflare 源站 CA 证书
curl -o /etc/ssl/cloudflare-origin-pull.pem \
https://developers.cloudflare.com/ssl/static/authenticated_origin_pull_ca.pem
# Nginx 认证源站拉取配置
# ssl_client_certificate /etc/ssl/cloudflare-origin-pull.pem;
# ssl_verify_client on;
```
### 步骤 6:启用攻击模式自动化
```python
#!/usr/bin/env python3
"""根据流量异常自动启用 Cloudflare 攻击模式。"""
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 # 每秒请求数阈值
CHECK_INTERVAL = 30 # 检查间隔秒数
def get_current_security_level():
"""获取当前安全级别设置。"""
resp = requests.get(
f"{BASE_URL}/settings/security_level",
headers=HEADERS
)
return resp.json()["result"]["value"]
def set_security_level(level: str):
"""设置安全级别(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"[+] 安全级别已设置为:{level}")
else:
print(f"[-] 设置安全级别失败:{result['errors']}")
return result["success"]
def get_traffic_analytics():
"""从 Cloudflare 分析获取近期流量数据。"""
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():
"""监控流量并自动启用攻击模式。"""
current_level = get_current_security_level()
print(f"[*] 当前安全级别:{current_level}")
print(f"[*] 监控流量(阈值:{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"[*] 当前 RPS:{rps:.0f},威胁数:{threats}")
if rps > NORMAL_RPS_THRESHOLD and not attack_mode_active:
print(f"[!] 检测到流量峰值:{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("[+] 流量已恢复正常,禁用攻击模式")
set_security_level("high")
attack_mode_active = False
consecutive_normal = 0
except Exception as e:
print(f"[-] 错误:{e}")
time.sleep(CHECK_INTERVAL)
if __name__ == "__main__":
monitor_and_respond()
```
## 监控与告警
### Cloudflare 控制台指标
- **防火墙事件**——查看被封锁的请求、受挑战的请求、速率受限的请求
- **DDoS 分析**——攻击规模、持续时间、类型和缓解状态
- **流量分析**——按时间的请求量、带宽、错误率
- **Bot 分析**——Bot 评分分布、已验证 Bot 与自动化威胁对比
### 告警配置
```bash
# 为 DDoS 攻击创建通知策略
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": "soc@example.com"}],
"webhooks": [{"id": "webhook-id"}]
},
"filters": {
"zones": ["'$ZONE_ID'"]
}
}'
```
## 最佳实践
- **代理所有 DNS 记录**——确保所有指向源站的 A/AAAA/CNAME 记录均已代理(橙色云朵图标)
- **隐藏源站 IP**——绝不暴露源站服务器 IP;使用 Cloudflare Tunnel 或仅限 Cloudflare IP 访问
- **先以日志模式开始**——在切换到"阻止"之前,先以"日志"动作测试 DDoS 规则覆盖
- **分层防御**——结合托管规则集、速率限制、WAF 规则和 Bot 管理
- **调整灵敏度**——根据流量中的误报率调整 DDoS 规则灵敏度
- **缓存策略**——最大化缓存命中率,在攻击期间降低源站负载
- **等候室**——为关键页面在流量激增时配置 Cloudflare 等候室(Waiting Room)
- **认证源站**——启用认证源站拉取,防止直接攻击源站
## 参考资料
- [Cloudflare DDoS 防护文档](https://developers.cloudflare.com/ddos-protection/)
- [Cloudflare WAF 文档](https://developers.cloudflare.com/waf/)
- [Cloudflare 速率限制](https://developers.cloudflare.com/waf/rate-limiting-rules/)
- [Cloudflare IP 范围](https://www.cloudflare.com/ips/)Related Skills
implementing-zero-trust-with-hashicorp-boundary
使用 HashiCorp Boundary 实现具备动态凭据代理、会话录制和 Vault 集成的身份感知零信任基础设施访问管理。
implementing-zero-trust-with-beyondcorp
使用身份感知代理(IAP,Identity-Aware Proxy)、上下文感知访问策略、设备信任验证和 Access Context Manager,部署 Google BeyondCorp Enterprise 零信任访问控制,对 GCP 资源和内部应用强制执行基于身份和安全态势的访问。
implementing-zero-trust-network-access
通过配置身份感知代理、微分段、基于条件访问策略的持续验证,以及在 AWS、Azure 和 GCP 环境中以 BeyondCorp 风格的架构替代传统 VPN 访问,在云环境中实施零信任网络访问(ZTNA)。
implementing-zero-trust-network-access-with-zscaler
使用 Zscaler 实施零信任网络访问(Zero Trust Network Access,ZTNA),通过 Zscaler Private Access(ZPA)配置应用分段、访问策略和连接器,替代传统 VPN 架构
implementing-zero-trust-in-cloud
本技能指导组织按照 NIST SP 800-207 和 Google BeyondCorp 原则在云环境中实施零信任(Zero Trust)架构,涵盖以身份为中心的访问控制、微分段(Micro-Segmentation)、持续验证、设备信任评估,以及部署身份感知代理(Identity-Aware Proxy)以消除 AWS、Azure 和 GCP 环境中的隐式网络信任。
implementing-zero-trust-for-saas-applications
使用 CASB、SSPM、条件访问策略、OAuth 应用治理和会话控制,为 SaaS 应用实施零信任访问控制, 对云托管服务强制执行身份验证、设备合规性检查和数据保护。
implementing-zero-trust-dns-with-nextdns
将 NextDNS 实施为零信任 DNS 过滤层,提供加密解析、威胁情报阻断、隐私保护,以及跨所有端点的组织策略执行。
implementing-zero-standing-privilege-with-cyberark
部署 CyberArk Secure Cloud Access,通过基于时间、权限和审批控制的即时访问,在混合云和多云环境中消除常设权限。
implementing-zero-knowledge-proof-for-authentication
零知识证明(ZKP)允许证明者在不泄露秘密本身的情况下证明对某个秘密(如密码或私钥)的了解。本技能实现 Schnorr 身份识别协议和使用离散对数问题的简化 ZKPP,使服务器永远不需要获取用户密码即可完成认证。
implementing-web-application-logging-with-modsecurity
配置带有 OWASP 核心规则集(CRS)的 ModSecurity WAF,实现 Web 应用程序日志记录, 调整规则以减少误报,分析审计日志进行攻击检测,并为应用程序特定威胁实现自定义 SecRules。 分析师配置 SecRuleEngine、SecAuditEngine 和 CRS 偏执级别,以在安全覆盖范围和运营稳定性之间取得平衡。 适用于涉及 WAF 配置、ModSecurity 规则调整、Web 应用审计日志或 CRS 部署的场景。
implementing-vulnerability-sla-breach-alerting
为漏洞修复 SLA 违规构建自动化告警,包含基于严重程度的时间线、升级工作流和合规性报告仪表板。
implementing-vulnerability-remediation-sla
漏洞修复 SLA(服务级别协议)根据严重程度、资产重要性和漏洞利用可用性定义修补或缓解已识别漏洞的强制时限。有效的 SLA 计划推动责任落实、确保一致的修复时间线,并为漏洞管理成熟度提供可衡量的 KPI。