executing-plans
executing-plans
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available
securing-api-gateway-with-aws-waf通过配置 OWASP Top 10 防护托管规则组(Managed Rule Group)、创建自定义速率限制规则、实施机器人(Bot)控制、设置 IP 信誉过滤以及监控 WAF 指标,使用 AWS WAF 保护 API Gateway 端点。
Independent GitHub snapshot · Automated classification · Original documentation governs
不适用于:网络层 DDoS 防护(使用 AWS Shield)、应用逻辑漏洞(使用 SAST/DAST 工具),或微服务之间的内部 API 安全(使用服务网格认证和授权)。
wafv2:* 和 apigateway:* 操作的 IAM 权限创建包含 AWS 托管规则的 Web ACL,对 OWASP Top 10 攻击提供基线防护。
# 使用托管规则组创建 WAF Web ACL
aws wafv2 create-web-acl \
--name api-gateway-waf \
--scope REGIONAL \
--default-action '{"Allow":{}}' \
--visibility-config '{
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "api-gateway-waf"
}' \
--rules '[
{
"Name": "AWSManagedRulesCommonRuleSet",
"Priority": 1,
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesCommonRuleSet"
}
},
"OverrideAction": {"None": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "CommonRuleSet"
}
},
{
"Name": "AWSManagedRulesKnownBadInputsRuleSet",
"Priority": 2,
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesKnownBadInputsRuleSet"
}
},
"OverrideAction": {"None": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "KnownBadInputs"
}
},
{
"Name": "AWSManagedRulesSQLiRuleSet",
"Priority": 3,
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesSQLiRuleSet"
}
},
"OverrideAction": {"None": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "SQLiRuleSet"
}
},
{
"Name": "AWSManagedRulesAmazonIpReputationList",
"Priority": 4,
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesAmazonIpReputationList"
}
},
"OverrideAction": {"None": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "IPReputationList"
}
}
]'
配置基于速率的规则,对每个 IP 地址的过量 API 请求进行节流。
# 获取 Web ACL ARN 和锁令牌
WEB_ACL_ARN=$(aws wafv2 list-web-acls --scope REGIONAL \
--query "WebACLs[?Name=='api-gateway-waf'].ARN" --output text)
# 更新 Web ACL 以添加速率限制规则
aws wafv2 update-web-acl \
--name api-gateway-waf \
--scope REGIONAL \
--id $(aws wafv2 list-web-acls --scope REGIONAL --query "WebACLs[?Name=='api-gateway-waf'].Id" --output text) \
--lock-token $(aws wafv2 get-web-acl --name api-gateway-waf --scope REGIONAL --id WEB_ACL_ID --query 'LockToken' --output text) \
--default-action '{"Allow":{}}' \
--visibility-config '{
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "api-gateway-waf"
}' \
--rules '[
{
"Name": "RateLimitPerIP",
"Priority": 0,
"Statement": {
"RateBasedStatement": {
"Limit": 2000,
"AggregateKeyType": "IP"
}
},
"Action": {"Block": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "RateLimitPerIP"
}
},
{
"Name": "RateLimitLoginEndpoint",
"Priority": 5,
"Statement": {
"RateBasedStatement": {
"Limit": 100,
"AggregateKeyType": "IP",
"ScopeDownStatement": {
"ByteMatchStatement": {
"FieldToMatch": {"UriPath": {}},
"PositionalConstraint": "STARTS_WITH",
"SearchString": "/api/auth/login",
"TextTransformations": [{"Priority": 0, "Type": "LOWERCASE"}]
}
}
}
},
"Action": {"Block": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "RateLimitLogin"
}
}
]'
添加 AWS WAF 机器人控制(Bot Control)以检测和管理自动化流量。
# 添加机器人控制托管规则组
# (在更新 Web ACL 时添加到规则数组中)
{
"Name": "AWSManagedRulesBotControlRuleSet",
"Priority": 6,
"Statement": {
"ManagedRuleGroupStatement": {
"VendorName": "AWS",
"Name": "AWSManagedRulesBotControlRuleSet",
"ManagedRuleGroupConfigs": [{
"AWSManagedRulesBotControlRuleSet": {
"InspectionLevel": "COMMON"
}
}],
"ExcludedRules": [
{"Name": "CategoryHttpLibrary"},
{"Name": "SignalNonBrowserUserAgent"}
]
}
},
"OverrideAction": {"None": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "BotControl"
}
}
为 API 特定的安全需求构建自定义 WAF 规则。
# 阻止缺少必需 API 密钥头部的请求
{
"Name": "RequireAPIKey",
"Priority": 7,
"Statement": {
"NotStatement": {
"Statement": {
"ByteMatchStatement": {
"FieldToMatch": {
"SingleHeader": {"Name": "x-api-key"}
},
"PositionalConstraint": "EXACTLY",
"SearchString": "",
"TextTransformations": [{"Priority": 0, "Type": "NONE"}]
}
}
}
},
"Action": {"Block": {"CustomResponse": {"ResponseCode": 403}}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "RequireAPIKey"
}
}
# 限制允许的国家/地区
{
"Name": "GeoRestriction",
"Priority": 8,
"Statement": {
"NotStatement": {
"Statement": {
"GeoMatchStatement": {
"CountryCodes": ["US", "CA", "GB", "DE", "FR", "AU"]
}
}
}
},
"Action": {"Block": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "GeoRestriction"
}
}
# 阻止超大请求体(防止载荷攻击)
{
"Name": "MaxBodySize",
"Priority": 9,
"Statement": {
"SizeConstraintStatement": {
"FieldToMatch": {"Body": {"OversizeHandling": "MATCH"}},
"ComparisonOperator": "GT",
"Size": 10240,
"TextTransformations": [{"Priority": 0, "Type": "NONE"}]
}
},
"Action": {"Block": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "MaxBodySize"
}
}
将 Web ACL 附加到 API Gateway Stage 并配置全面日志记录。
# 将 Web ACL 关联到 API Gateway
aws wafv2 associate-web-acl \
--web-acl-arn $WEB_ACL_ARN \
--resource-arn arn:aws:apigateway:us-east-1::/restapis/API_ID/stages/prod
# 通过 Kinesis Firehose 将 WAF 日志发送到 S3
aws wafv2 put-logging-configuration \
--logging-configuration '{
"ResourceArn": "'$WEB_ACL_ARN'",
"LogDestinationConfigs": [
"arn:aws:firehose:us-east-1:ACCOUNT:deliverystream/aws-waf-logs-api-gateway"
],
"RedactedFields": [
{"SingleHeader": {"Name": "authorization"}},
{"SingleHeader": {"Name": "cookie"}}
]
}'
# 验证关联状态
aws wafv2 get-web-acl-for-resource \
--resource-arn arn:aws:apigateway:us-east-1::/restapis/API_ID/stages/prod
监控 WAF 有效性并调优规则以减少误报。
# 从 CloudWatch 获取 WAF 指标
aws cloudwatch get-metric-statistics \
--namespace AWS/WAFV2 \
--metric-name BlockedRequests \
--dimensions Name=WebACL,Value=api-gateway-waf Name=Rule,Value=ALL \
--start-time 2026-02-22T00:00:00Z \
--end-time 2026-02-23T00:00:00Z \
--period 3600 \
--statistics Sum
# 获取特定规则的采样请求
aws wafv2 get-sampled-requests \
--web-acl-arn $WEB_ACL_ARN \
--rule-metric-name RateLimitPerIP \
--scope REGIONAL \
--time-window '{"StartTime":"2026-02-22T00:00:00Z","EndTime":"2026-02-23T00:00:00Z"}' \
--max-items 50
# 检查被速率限制的 IP
aws wafv2 get-rate-based-statement-managed-keys \
--web-acl-name api-gateway-waf \
--scope REGIONAL \
--web-acl-id WEB_ACL_ID \
--rule-name RateLimitPerIP
# 创建高拦截率 CloudWatch 告警
aws cloudwatch put-metric-alarm \
--alarm-name waf-high-block-rate \
--namespace AWS/WAFV2 \
--metric-name BlockedRequests \
--dimensions Name=WebACL,Value=api-gateway-waf Name=Rule,Value=ALL \
--statistic Sum --period 300 --threshold 1000 \
--comparison-operator GreaterThanThreshold \
--evaluation-periods 2 \
--alarm-actions arn:aws:sns:us-east-1:ACCOUNT:security-alerts
| 术语 | 定义 |
|---|---|
| Web ACL | AWS WAF 访问控制列表,定义应用于关联资源的规则集合及其操作(允许、阻止、计数) |
| 托管规则组(Managed Rule Group) | AWS 或第三方供应商维护的预配置 WAF 规则集,用于防护 OWASP Top 10 等常见攻击模式 |
| 基于速率的规则(Rate-Based Rule) | 跟踪每个 IP 地址请求速率,在 5 分钟窗口内超出定义阈值时阻止流量的 WAF 规则 |
| 机器人控制(Bot Control) | AWS WAF 托管规则组,识别并管理包括爬虫、抓取工具和攻击机器人在内的自动化流量 |
| IP 信誉列表(IP Reputation List) | AWS 维护的与恶意活动相关的 IP 地址列表,包括僵尸网络、扫描器和已知攻击者 |
| 自定义响应(Custom Response) | WAF 功能,在阻止请求时返回特定 HTTP 状态码和自定义响应内容 |
场景背景:公开 REST API 每小时经历数千次自动机器人针对 /api/auth/login 端点的认证尝试(凭据填充攻击)。
方法:
常见陷阱:按 IP 进行速率限制可能会阻止共享 NAT 网关或企业代理后面的合法用户。考虑使用基于 API 密钥或经过认证的会话进行速率限制,以实现更精细的控制。通用检查级别的机器人控制规则可能会阻止合法的 API 客户端;先以 Count 模式启动,审查后再切换到 Block 模式。
AWS WAF API Gateway 安全报告
======================================
Web ACL: api-gateway-waf
关联资源: API Gateway - production-api(prod 阶段)
报告周期: 2026-02-16 至 2026-02-23
流量摘要:
总请求数: 2,450,000
允许的请求数: 2,380,000(97.1%)
阻止的请求数: 70,000(2.9%)
按规则分类的阻止数:
RateLimitPerIP: 28,000(40%)
AWSManagedRulesCommonRuleSet: 18,000(25.7%)
BotControl: 12,000(17.1%)
SQLiRuleSet: 5,000(7.1%)
IPReputationList: 4,000(5.7%)
RateLimitLogin: 2,000(2.9%)
GeoRestriction: 1,000(1.4%)
被阻止的最多 IP:
185.x.x.x: 8,400 次请求(速率限制)
45.x.x.x: 5,200 次请求(检测到机器人)
198.x.x.x: 3,100 次请求(SQL 注入尝试)
阻止的攻击类型:
凭据填充(登录端点): 2,000
SQL 注入尝试: 5,000
XSS: 3,200
已知恶意机器人流量: 12,000
速率限制违规: 28,000
WAF 规则健康状态:
阻止模式规则: 8 / 10
计数模式规则: 2 / 10(评估中)
误报率: < 0.1%