关于 securing-api-gateway-with-aws-waf
用于为公开的 AWS API Gateway 端点配置 AWS WAF 防护的安全技能,涵盖托管规则、速率限制、机器人控制、自定义规则、日志和监控。
主要功能
- 01配置托管 WAF 规则组
- 02按 IP 设置速率限制
- 03管理机器人流量
- 04编写 API 专用规则
- 05监控日志与指标
适用场景
- 01防护公开 API 免受常见 Web 攻击
- 02限制过量请求与 API 滥用
- 03检测并管理自动化机器人流量
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mukul975/ anthropic-cybersecurity-skills --skill securing-api-gateway-with-aws-waf安装后在 Claude Code 中输入/securing-api-gateway-with-aws-waf确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
LICENSEreferences/api-reference.mdscripts/agent.py详细介绍
使用 AWS WAF 保护 API Gateway
何时使用
- 当部署需要防护常见 Web 攻击的 API Gateway 端点时
- 当实施速率限制和节流以防止 API 滥用和 DDoS 攻击时
- 当为暴露在互联网上的 API 端点构建机器人检测和缓解机制时
- 当合规要求对所有面向公众的 API 端点提供 WAF 保护时
- 当基于 IP 信誉、地理位置或请求模式自定义访问控制时
不要使用 于网络层 DDoS 防护(请使用 AWS Shield)、应用逻辑漏洞(请使用 SAST/DAST 工具),或微服务之间的内部 API 安全(请使用服务网格身份验证和授权)。
先决条件
- 已部署具有公共端点的 AWS API Gateway(REST 或 HTTP API)
- 具有
wafv2:*和apigateway:*操作的 IAM 权限 - 已为 WAF 日志配置 CloudWatch 和 S3 或 Kinesis Firehose
- 了解 API 的预期流量模式以配置速率限制
- 用于自定义 IP 阻止的 IP 信誉列表或威胁情报源
工作流
步骤 1:使用托管规则组创建 WAF Web ACL
创建带有 AWS 托管规则的 Web ACL,以针对 OWASP Top 10 攻击提供基线保护。
# Create a WAF Web ACL with managed rule groups
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"
}
}
]'
步骤 2:添加速率限制规则
配置基于速率的规则,以限制每个 IP 地址的过多 API 请求。
# Get the Web ACL ARN and lock token
WEB_ACL_ARN=$(aws wafv2 list-web-acls --scope REGIONAL \
--query "WebACLs[?Name=='api-gateway-waf'].ARN" --output text)
# Update Web ACL to add rate limiting rule
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"
}
}
]'
步骤 3:实施机器人控制
添加 AWS WAF Bot Control 以检测和管理自动化流量。
# Add Bot Control managed rule group
# (Add to the rules array when updating the 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"
}
}
步骤 4:为 API 特定保护创建自定义规则
为 API 特定的安全需求构建自定义 WAF 规则。
# Block requests without required API key header
{
"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"
}
}
# Geo-restrict to allowed countries
{
"Name": "GeoRestriction",
"Priority": 8,
"Statement": {
"NotStatement": {
"Statement": {
"GeoMatchStatement": {
"CountryCodes": ["US", "CA", "GB", "DE", "FR", "AU"]
}
}
}
},
"Action": {"Block": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "GeoRestriction"
}
}
# Block oversized request bodies (prevent payload attacks)
{
"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"
}
}
步骤 5:将 WAF 与 API Gateway 关联并启用日志记录
将 Web ACL 附加到 API Gateway 阶段并配置全面的日志记录。
# Associate Web ACL with 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
# Enable WAF logging to S3 via Kinesis Firehose
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"}}
]
}'
# Verify association
aws wafv2 get-web-acl-for-resource \
--resource-arn arn:aws:apigateway:us-east-1::/restapis/API_ID/stages/prod
步骤 6:监控 WAF 指标并调整规则
监控 WAF 效果并调整规则以减少误报。
# Get WAF metrics from CloudWatch
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
# Get sampled requests for a specific rule
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
# Check rate-limited IPs
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
# Create CloudWatch alarm for high block rate
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 访问控制列表,定义应用于关联资源的规则集合及其操作(允许、阻止、计数) |
| 托管规则组 | 由 AWS 或第三方供应商维护的预配置 WAF 规则集,用于应对 OWASP Top 10 等常见攻击模式 |
| 基于速率的规则 | 跟踪每个 IP 地址的请求速率,并在 5 分钟窗口内阻止超过定义阈值的流量的 WAF 规则 |
| 机器人控制 | AWS WAF 托管规则组,用于识别和管理自动化流量,包括爬虫、抓取程序和攻击机器人 |
| IP 信誉列表 | AWS 维护的与恶意活动相关的 IP 地址列表,包括僵尸网络、扫描程序和已知攻击者 |
| 自定义响应 | WAF 在阻止请求时返回特定 HTTP 状态代码和自定义响应体的能力 |
工具与系统
- AWS WAF:用于保护 API Gateway、ALB、CloudFront 和 AppSync 端点的 Web 应用防火墙服务
- AWS Managed Rules:由 AWS 安全团队维护的用于常见攻击模式的预构建规则组
- AWS Firewall Manager:在 AWS Organizations 中跨多个账户集中管理 WAF 策略
- Kinesis Firehose:将 WAF 日志流式传输到 S3、Elasticsearch 或第三方分析服务的流式传输服务
- CloudWatch:用于监控 WAF 指标(包括允许、阻止和计数的请求)的监控服务
常见场景
场景:保护公共 API 免受凭证填充和机器人攻击
背景:一个公共 REST API 每小时会收到数千次来自自动化机器人的身份验证尝试,这些机器人针对 /api/auth/login 端点进行凭证填充。
方法:
- 创建 Web ACL,并使用 AWS Managed Rules Common Rule Set 提供基线保护
- 添加基于速率的规则,将登录端点限制为每个 IP 每 5 分钟 100 个请求
- 启用 Bot Control 托管规则以检测并阻止自动化流量
- 添加 IP Reputation List,主动阻止已知恶意 IP
- 创建自定义规则,阻止缺少正确 User-Agent 标头的请求
- 启用 WAF 日志记录,并为高阻止率创建 CloudWatch 告警
- 每周审查采样的已阻止请求,以调整规则并减少误报
注意事项:按 IP 进行速率限制可能会阻止共享 NAT 网关或企业代理后面的合法用户。考虑使用 API key 或基于已认证会话的速率限制,以实现更精细的控制。处于 COMMON 检查级别的 Bot Control 规则可能会阻止合法 API 客户端;请先以 Count 模式运行并审查,然后再切换到 Block。
输出格式
AWS WAF API Gateway Security Report
======================================
Web ACL: api-gateway-waf
Associated Resource: API Gateway - production-api (prod stage)
Report Period: 2026-02-16 to 2026-02-23
TRAFFIC SUMMARY:
Total requests: 2,450,000
Allowed requests: 2,380,000 (97.1%)
Blocked requests: 70,000 (2.9%)
BLOCKS BY RULE:
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%)
TOP BLOCKED IPs:
185.x.x.x: 8,400 requests (rate limited)
45.x.x.x: 5,200 requests (bot detected)
198.x.x.x: 3,100 requests (SQLi attempts)
ATTACK TYPES BLOCKED:
Credential stuffing (login endpoint): 2,000
SQL injection attempts: 5,000
Cross-site scripting: 3,200
Known bad bot traffic: 12,000
Rate limit violations: 28,000
WAF RULE HEALTH:
Rules in Block mode: 8 / 10
Rules in Count mode: 2 / 10 (under evaluation)
False positive rate: < 0.1%
评论
支持 Markdown