La interfaz está localizada; las descripciones y documentos de las Skills se traducen automáticamente con IA a su idioma. El código, los comandos, rutas y términos técnicos se mantienen en el original, y prevalece el documento del autor.
Explorar Skills
Productividad · SKILL.md

securing-api-gateway-with-aws-waf

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

Documentación de la Skill

GitHub

name: securing-api-gateway-with-aws-waf description: > 通过配置 OWASP Top 10 防护托管规则组(Managed Rule Group)、创建自定义速率限制规则、实施机器人(Bot)控制、设置 IP 信誉过滤以及监控 WAF 指标,使用 AWS WAF 保护 API Gateway 端点。 domain: cybersecurity subdomain: cloud-security tags: [cloud-security, aws, waf, api-gateway, rate-limiting, bot-protection, owasp] version: "1.0" author: mahipal license: Apache-2.0

使用 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 攻击提供基线防护。

# 使用托管规则组创建 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 请求进行节流。

# 获取 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)以检测和管理自动化流量。

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

# 阻止缺少必需 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 并配置全面日志记录。

# 将 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 有效性并调优规则以减少误报。

# 从 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 ACLAWS 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%
Skills guardadas