securing-api-gateway-with-aws-waf

通过配置 OWASP Top 10 防护托管规则组(Managed Rule Group)、创建自定义速率限制规则、实施机器人(Bot)控制、设置 IP 信誉过滤以及监控 WAF 指标,使用 AWS WAF 保护 API Gateway 端点。

9 stars

Best use case

securing-api-gateway-with-aws-waf is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

通过配置 OWASP Top 10 防护托管规则组(Managed Rule Group)、创建自定义速率限制规则、实施机器人(Bot)控制、设置 IP 信誉过滤以及监控 WAF 指标,使用 AWS WAF 保护 API Gateway 端点。

Teams using securing-api-gateway-with-aws-waf 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

$curl -o ~/.claude/skills/securing-api-gateway-with-aws-waf/SKILL.md --create-dirs "https://raw.githubusercontent.com/killvxk/cybersecurity-skills-zh/main/skills/securing-api-gateway-with-aws-waf/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/securing-api-gateway-with-aws-waf/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How securing-api-gateway-with-aws-waf Compares

Feature / Agentsecuring-api-gateway-with-aws-wafStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

通过配置 OWASP Top 10 防护托管规则组(Managed Rule Group)、创建自定义速率限制规则、实施机器人(Bot)控制、设置 IP 信誉过滤以及监控 WAF 指标,使用 AWS WAF 保护 API Gateway 端点。

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

# 使用 AWS WAF 保护 API Gateway

## 适用场景

- 部署需要防护常见 Web 攻击的 API Gateway 端点时
- 实施速率限制(Rate Limiting)和节流以防止 API 滥用和 DDoS 攻击时
- 为向互联网暴露的 API 端点构建机器人检测和缓解措施时
- 合规要求对所有面向公众的 API 端点实施 WAF 保护时
- 根据 IP 信誉、地理位置或请求模式自定义访问控制时

**不适用于**:网络层 DDoS 防护(使用 AWS Shield)、应用逻辑漏洞(使用 SAST/DAST 工具),或微服务之间的内部 API 安全(使用服务网格认证和授权)。

## 前置条件

- 已部署具有公开端点的 AWS API Gateway(REST 或 HTTP API)
- 具有 `wafv2:*` 和 `apigateway:*` 操作的 IAM 权限
- 已配置 CloudWatch 和 S3 或 Kinesis Firehose 用于 WAF 日志记录
- 了解 API 的预期流量模式,用于速率限制配置
- IP 信誉列表或威胁情报(Threat Intelligence)源,用于自定义 IP 封锁

## 工作流程

### 步骤 1:使用托管规则组创建 WAF Web ACL

创建包含 AWS 托管规则的 Web ACL,对 OWASP Top 10 攻击提供基线防护。

```bash
# 使用托管规则组创建 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"
      }
    }
  ]'
```

### 步骤 2:添加速率限制规则

配置基于速率的规则,对每个 IP 地址的过量 API 请求进行节流。

```bash
# 获取 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"
      }
    }
  ]'
```

### 步骤 3:实施机器人控制

添加 AWS WAF 机器人控制(Bot Control)以检测和管理自动化流量。

```bash
# 添加机器人控制托管规则组
# (在更新 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 规则。

```bash
# 阻止缺少必需 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"
  }
}
```

### 步骤 5:将 WAF 关联到 API Gateway 并启用日志记录

将 Web ACL 附加到 API Gateway Stage 并配置全面日志记录。

```bash
# 将 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
```

### 步骤 6:监控 WAF 指标并调优规则

监控 WAF 有效性并调优规则以减少误报。

```bash
# 从 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 状态码和自定义响应内容 |

## 工具与系统

- **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` 端点的认证尝试(凭据填充攻击)。

**方法**:
1. 创建包含 AWS 托管规则通用规则集的 Web ACL,提供基线防护
2. 添加基于速率的规则,将登录端点限制为每 IP 每 5 分钟 100 次请求
3. 启用机器人控制托管规则,检测并阻止自动化流量
4. 添加 IP 信誉列表,主动阻止已知恶意 IP
5. 创建自定义规则,阻止缺少正确 User-Agent 头部的请求
6. 启用 WAF 日志记录,并为高拦截率创建 CloudWatch 告警
7. 每周审查采样的被阻止请求,调优规则并减少误报

**常见陷阱**:按 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%
```

Related Skills

securing-serverless-functions

9
from killvxk/cybersecurity-skills-zh

本技能涵盖 AWS Lambda、Azure Functions 和 Google Cloud Functions 等无服务器计算平台的安全加固,涉及最小权限 IAM 角色、依赖漏洞扫描、密钥管理集成、输入验证、函数 URL 认证以及运行时监控,以防范注入攻击、凭证窃取和供应链攻击。

securing-remote-access-to-ot-environment

9
from killvxk/cybersecurity-skills-zh

本技能涵盖为操作员、工程师和供应商实施OT/ICS环境的安全远程访问,同时防止可能危害工业运营的未授权访问。涉及跳板服务器架构、多因素认证、会话记录、特权访问管理、供应商远程访问控制,以及符合IEC 62443和NERC CIP-005远程访问要求。

securing-kubernetes-on-cloud

9
from killvxk/cybersecurity-skills-zh

本技能涵盖通过实施 Pod 安全标准(Pod Security Standards)、网络策略、工作负载身份、RBAC 权限控制、镜像准入控制和运行时安全监控,对 EKS、AKS 和 GKE 上的托管 Kubernetes 集群进行加固。涉及云平台特定安全功能,包括 EKS 的 IRSA、GKE 的工作负载身份(Workload Identity)以及 AKS 的托管身份(Managed Identity)。

securing-historian-server-in-ot-environment

9
from killvxk/cybersecurity-skills-zh

本技能涵盖在OT环境中加固和保护过程历史数据服务器(OSIsoft PI、Honeywell PHD、GE Proficy、AVEVA Historian)。涉及跨Purdue模型各层级的网络部署、历史数据服务器接口的访问控制、通过数据二极管或PI-to-PI连接器在DMZ中进行数据复制、历史数据查询中的SQL注入防护,以及用于安全分析、法规报告和过程优化的过程数据完整性保护。

securing-helm-chart-deployments

9
from killvxk/cybersecurity-skills-zh

通过验证 Chart 完整性、扫描模板中的错误配置并在 Kubernetes 发布中强制执行安全上下文,保护 Helm Chart 部署安全。

securing-github-actions-workflows

9
from killvxk/cybersecurity-skills-zh

本技能涵盖加固 GitHub Actions 工作流以防范供应链攻击、凭据盗窃和权限提升。 内容包括将 action 固定到 SHA 摘要、最小化 GITHUB_TOKEN 权限、防止机密泄露、 防止工作流表达式中的脚本注入,以及为工作流变更实施必要的审阅者机制。

securing-container-registry-with-harbor

9
from killvxk/cybersecurity-skills-zh

Harbor 是一个开源容器镜像仓库,提供安全功能包括漏洞扫描(集成 Trivy)、镜像签名(Notary/Cosign)、RBAC、内容信任策略(Content Trust)、复制和审计日志。配置这些功能以强制执行镜像来源验证、防止有漏洞镜像部署并维护仓库访问控制。

securing-container-registry-images

9
from killvxk/cybersecurity-skills-zh

通过使用 Trivy 和 Grype 实施漏洞扫描、使用 Cosign 和 Sigstore 强制执行镜像签名、配置镜像仓库访问控制,以及构建阻止部署未扫描或未签名镜像的 CI/CD 流水线,来保护容器仓库(Container Registry)中的镜像安全。

securing-aws-iam-permissions

9
from killvxk/cybersecurity-skills-zh

本技能引导从业者加固 AWS 身份和访问管理(Identity and Access Management)配置,在云账户中强制执行最小权限(Least Privilege)访问。涵盖 IAM 策略范围界定、权限边界(Permission Boundary)、Access Analyzer 集成和凭据轮换策略,以降低受损身份的影响范围。

implementing-proofpoint-email-security-gateway

9
from killvxk/cybersecurity-skills-zh

部署和配置 Proofpoint Email Protection 作为安全邮件网关,在邮件到达用户收件箱之前检测并拦截钓鱼、恶意软件、BEC 和垃圾邮件。

implementing-api-gateway-security-controls

9
from killvxk/cybersecurity-skills-zh

在API网关层实施安全控制,包括认证强制执行、速率限制、请求验证、IP白名单、TLS终止和威胁防护。 配置API网关(Kong、AWS API Gateway、Azure APIM、Apigee)作为集中式安全执行点, 在流量到达后端服务前对所有API流量进行验证、节流和监控。

detecting-spearphishing-with-email-gateway

9
from killvxk/cybersecurity-skills-zh

鱼叉式网络钓鱼(Spearphishing)使用个性化、经过研究的内容针对特定个人,可绕过通用垃圾邮件过滤器。邮件安全网关(SEG)如 Microsoft Defender for Office 365、Proofpoint、Mimecast 和 Barracuda 提供高级检测能力,包括行为分析、URL 引爆、附件沙箱和冒充检测。本技能涵盖配置这些网关以检测和拦截定向钓鱼攻击。