mcpField
I
implementing-api-gateway-security-controls

implementing-api-gateway-security-controls

github.com/mukul975安全35.2k211 次安装8 周前更新
代码仓库

关于 implementing-api-gateway-security-controls

供团队配置 API 网关安全控制的实施指南,涵盖集中式身份验证、流量限制、规范校验、TLS、WAF 规则和监控,并强调后端服务仍需自行验证。

主要功能

  1. 01配置集中式身份验证与授权
  2. 02配置速率限制与配额
  3. 03按 OpenAPI 校验请求
  4. 04设置 TLS 与双向 TLS
  5. 05集成 WAF 并监控安全事件

适用场景

  1. 01为微服务 API 配置统一入口
  2. 02限制客户端请求频率与配额
  3. 03阻止不符合 API 规范的请求
  4. 04监控网关安全事件

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill implementing-api-gateway-security-controls

安装后在 Claude Code 中输入/implementing-api-gateway-security-controls确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE
references/
api-reference.md
scripts/
agent.py

详细介绍

实施 API 网关安全控制

适用场景

  • 为微服务 API 部署集中式身份验证与授权层
  • 对所有 API 端点实施速率限制、节流和配额管理
  • 在网关层面配置基于 OpenAPI 规范的请求/响应校验
  • 为 API 流量设置 TLS 终止、双向 TLS 和证书管理
  • 将 WAF 规则与 API 网关集成,以拦截注入、XSS 和已知攻击模式

不要将其作为唯一的安全层。API 网关提供纵深防御,但后端服务也必须校验授权和输入。

前提条件

  • 已选定并部署 API 网关平台(Kong、AWS API Gateway、Azure APIM 或 Apigee)
  • 所有后端 API 的 OpenAPI/Swagger 规范
  • 网关域名的 TLS 证书
  • 已为 OAuth2/OIDC 配置身份提供商(IdP)(Okta、Auth0、Azure AD)
  • 监控和日志基础设施(CloudWatch、Datadog、ELK)
  • 后端服务端点已注册且可从网关访问

工作流

步骤 1:Kong Gateway 安全配置
# kong.yml - Declarative Kong configuration with security plugins
_format_version: "3.0"

services:
  - name: user-service
    url: http://user-service:8080
    routes:
      - name: user-api
        paths:
          - /api/v1/users
        methods:
          - GET
          - POST
          - PUT
          - PATCH
          - DELETE
        strip_path: false

plugins:
  # 1. Authentication: JWT validation
  - name: jwt
    config:
      uri_param_names:
        - jwt
      header_names:
        - Authorization
      claims_to_verify:
        - exp
      maximum_expiration: 3600  # Max 1 hour token TTL

  # 2. Rate Limiting
  - name: rate-limiting
    config:
      minute: 60
      hour: 1000
      policy: redis
      redis_host: redis
      redis_port: 6379
      fault_tolerant: true
      hide_client_headers: false
      limit_by: credential  # Per-user, not per-IP

  # 3. Request Size Limiting
  - name: request-size-limiting
    config:
      allowed_payload_size: 1  # 1 MB max
      size_unit: megabytes

  # 4. IP Restriction (admin endpoints)
  - name: ip-restriction
    service: admin-service
    config:
      allow:
        - 10.0.0.0/8
        - 172.16.0.0/12

  # 5. Bot Detection
  - name: bot-detection
    config:
      deny:
        - "sqlmap"
        - "nikto"
        - "nmap"
        - "masscan"

  # 6. CORS Configuration
  - name: cors
    config:
      origins:
        - "https://app.example.com"
      methods:
        - GET
        - POST
        - PUT
        - PATCH
        - DELETE
      headers:
        - Authorization
        - Content-Type
      credentials: true
      max_age: 3600

  # 7. Response Transformer - Remove sensitive headers
  - name: response-transformer
    config:
      remove:
        headers:
          - X-Powered-By
          - Server
      add:
        headers:
          - "X-Content-Type-Options: nosniff"
          - "X-Frame-Options: DENY"
          - "Strict-Transport-Security: max-age=31536000; includeSubDomains"
          - "Content-Security-Policy: default-src 'none'"
步骤 2:AWS API Gateway 安全配置
import boto3
import json

apigw = boto3.client('apigatewayv2')

# Create API with mutual TLS
api_response = apigw.create_api(
    Name='secure-api',
    ProtocolType='HTTP',
    DisableExecuteApiEndpoint=True,  # Force custom domain
)
api_id = api_response['ApiId']

# Configure authorizer (JWT with Cognito)
authorizer = apigw.create_authorizer(
    ApiId=api_id,
    AuthorizerType='JWT',
    IdentitySource='$request.header.Authorization',
    Name='cognito-jwt-authorizer',
    JwtConfiguration={
        'Audience': ['your-app-client-id'],
        'Issuer': 'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxxxx'
    }
)

# Create route with authorizer
apigw.create_route(
    ApiId=api_id,
    RouteKey='GET /api/v1/users',
    AuthorizerId=authorizer['AuthorizerId'],
    AuthorizationType='JWT',
)

# Configure throttling
apigw.create_stage(
    ApiId=api_id,
    StageName='prod',
    DefaultRouteSettings={
        'ThrottlingBurstLimit': 100,
        'ThrottlingRateLimit': 50.0,  # 50 requests per second
    },
    AccessLogSettings={
        'DestinationArn': 'arn:aws:logs:us-east-1:123456789:log-group:api-access-logs',
        'Format': json.dumps({
            'requestId': '$context.requestId',
            'ip': '$context.identity.sourceIp',
            'caller': '$context.identity.caller',
            'user': '$context.identity.user',
            'requestTime': '$context.requestTime',
            'httpMethod': '$context.httpMethod',
            'resourcePath': '$context.resourcePath',
            'status': '$context.status',
            'protocol': '$context.protocol',
            'responseLength': '$context.responseLength'
        })
    }
)

# WAF association
waf = boto3.client('wafv2')
web_acl = waf.create_web_acl(
    Name='api-security-acl',
    Scope='REGIONAL',
    DefaultAction={'Allow': {}},
    Rules=[
        {
            'Name': 'AWS-AWSManagedRulesSQLiRuleSet',
            'Priority': 1,
            'Statement': {
                'ManagedRuleGroupStatement': {
                    'VendorName': 'AWS',
                    'Name': 'AWSManagedRulesSQLiRuleSet'
                }
            },
            'OverrideAction': {'None': {}},
            'VisibilityConfig': {
                'SampledRequestsEnabled': True,
                'CloudWatchMetricsEnabled': True,
                'MetricName': 'SQLiRuleSet'
            }
        },
        {
            'Name': 'RateLimit',
            'Priority': 2,
            'Statement': {
                'RateBasedStatement': {
                    'Limit': 2000,
                    'AggregateKeyType': 'IP'
                }
            },
            'Action': {'Block': {}},
            'VisibilityConfig': {
                'SampledRequestsEnabled': True,
                'CloudWatchMetricsEnabled': True,
                'MetricName': 'RateLimitRule'
            }
        },
    ],
    VisibilityConfig={
        'SampledRequestsEnabled': True,
        'CloudWatchMetricsEnabled': True,
        'MetricName': 'ApiSecurityACL'
    }
)
步骤 3:使用 OpenAPI Schema 进行请求校验
# Kong OAS Validation Plugin configuration
plugins:
  - name: oas-validation
    config:
      api_spec: |
        openapi: "3.0.3"
        info:
          title: Secure API
          version: "1.0"
        paths:
          /api/v1/users:
            post:
              requestBody:
                required: true
                content:
                  application/json:
                    schema:
                      type: object
                      required: [name, email]
                      properties:
                        name:
                          type: string
                          maxLength: 100
                          pattern: "^[a-zA-Z ]+$"
                        email:
                          type: string
                          format: email
                          maxLength: 255
                      additionalProperties: false  # Block mass assignment
              responses:
                '201':
                  description: User created
      validate_request_body: true
      validate_request_header_params: true
      validate_request_query_params: true
      validate_request_uri_params: true
      verbose_response: false  # Do not expose schema details in errors
步骤 4:双向 TLS 配置
# Generate CA and client certificates for mTLS
# 1. Create CA
openssl genrsa -out ca.key 4096
openssl req -new -x509 -key ca.key -out ca.crt -days 365 \
    -subj "/CN=API Gateway CA/O=Example Corp"

# 2. Create client certificate
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr \
    -subj "/CN=api-client/O=Example Corp"
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \
    -CAcreateserial -out client.crt -days 365

# Kong mTLS configuration
# Upload CA certificate to Kong
curl -X POST http://kong-admin:8001/ca_certificates \
    -F "[email protected]"

# Enable mTLS plugin
curl -X POST http://kong-admin:8001/services/user-service/plugins \
    --data "name=mtls-auth" \
    --data "config.ca_certificates[]=$(cat ca_cert_id)" \
    --data "config.revocation_check_mode=SKIP" \
    --data "config.authenticated_group_by=CN"
步骤 5:日志与监控配置
# CloudWatch monitoring for API security events
import boto3

cloudwatch = boto3.client('cloudwatch')
logs = boto3.client('logs')

# Create metric filters for security events
security_filters = [
    {
        'name': 'UnauthorizedAccess',
        'pattern': '{ $.status = 401 || $.status = 403 }',
        'metric': 'UnauthorizedAccessCount'
    },
    {
        'name': 'RateLimitHits',
        'pattern': '{ $.status = 429 }',
        'metric': 'RateLimitHitCount'
    },
    {
        'name': 'ServerErrors',
        'pattern': '{ $.status >= 500 }',
        'metric': 'ServerErrorCount'
    },
    {
        'name': 'LargeResponses',
        'pattern': '{ $.responseLength > 1000000 }',
        'metric': 'LargeResponseCount'
    },
]

for sf in security_filters:
    logs.put_metric_filter(
        logGroupName='api-access-logs',
        filterName=sf['name'],
        filterPattern=sf['pattern'],
        metricTransformations=[{
            'metricName': sf['metric'],
            'metricNamespace': 'APISecurityMetrics',
            'metricValue': '1',
            'defaultValue': 0
        }]
    )

# Create alarm for unusual 401/403 spike
cloudwatch.put_metric_alarm(
    AlarmName='API-UnauthorizedAccessSpike',
    MetricName='UnauthorizedAccessCount',
    Namespace='APISecurityMetrics',
    Statistic='Sum',
    Period=300,  # 5 minutes
    EvaluationPeriods=1,
    Threshold=100,
    ComparisonOperator='GreaterThanThreshold',
    AlarmActions=['arn:aws:sns:us-east-1:123456789:security-alerts'],
    AlarmDescription='More than 100 unauthorized access attempts in 5 minutes'
)

关键概念

术语定义
API 网关所有 API 流量的集中式入口点,在路由到后端服务之前强制执行身份验证、授权、速率限制和请求校验
速率限制在时间窗口内控制每个客户端的 API 请求数量,以防止滥用并确保公平的资源分配
请求校验在转发到后端服务之前,验证传入的 API 请求是否符合预期的 schema(数据类型、必填字段、值范围)
双向 TLS(mTLS)客户端和服务器都出示证书的双向 TLS 身份验证,为 API 到 API 的通信提供强身份验证
WAF 集成在 API 网关上应用 Web 应用防火墙规则,以拦截常见攻击模式(SQLi、XSS、路径遍历)
OAuth2/OIDC基于令牌的身份验证协议,网关在允许访问之前会针对身份提供商校验 JWT 令牌

工具与系统

  • Kong Gateway:开源 API 网关,拥有庞大的插件生态系统,用于安全、速率限制和身份验证
  • AWS API Gateway:托管式 API 网关服务,内置节流、WAF 集成和 Lambda 授权方
  • Azure API Management:企业级 API 网关,具有基于策略的安全、开发者门户和 Azure AD 集成
  • Apigee(Google Cloud):API 管理平台,具有威胁防护、配额管理和 API 分析功能
  • Envoy Proxy:高性能代理,在服务网格架构中用作 API 网关,具有可扩展的过滤器链

常见场景

场景:使用 Kong Gateway 保护微服务 API

背景:某公司正在从单体 API 迁移到微服务。每个微服务都有自己的 REST API。安全团队需要在不修改每个服务的情况下实现集中式身份验证、限流和请求校验。

方法:

  1. 将 Kong Gateway 部署为单一入口点,将流量路由到 8 个后端微服务
  2. 配置 JWT 校验插件,根据公司的 Keycloak IdP 验证令牌
  3. 应用限流:普通用户 60 请求/分钟,高级用户 300/分钟,通过 JWT 声明识别
  4. 启用 OAS 校验插件,拒绝不符合 OpenAPI 规范的请求(阻止批量赋值和注入)
  5. 为网关后面的服务间通信配置 mTLS
  6. 设置响应转换器,移除 Server 和 X-Powered-By 响应头,并添加安全响应头
  7. 集成 AWS WAF,以提供 SQL 注入和 XSS 防护规则
  8. 将访问日志配置到 CloudWatch,并设置安全指标过滤器和告警

陷阱:

  • 仅依赖网关进行授权,而后端服务也需要验证权限
  • 未按已认证用户配置限流(仅按 IP 限流会让攻击者通过轮换 IP 绕过)
  • 使用网关的详细错误响应,泄露内部服务架构
  • 部署后未使用安全工具测试网关配置
  • 缺失网关与后端服务之间的双向 TLS,导致可直接访问后端

输出格式

## API Gateway Security Configuration Report

**Gateway**: Kong 3.5 (Kubernetes deployment)
**Backend Services**: 8 microservices
**Date**: 2024-12-15

### Security Controls Implemented

| Control | Plugin/Feature | Configuration |
|---------|---------------|---------------|
| Authentication | JWT Plugin | Cognito IdP, 1-hour max TTL |
| Rate Limiting | Rate Limiting Plugin | 60 req/min (user), Redis-backed |
| Request Validation | OAS Validation | Strict mode, no additional properties |
| TLS | Kong TLS | TLS 1.3 only, HSTS enabled |
| mTLS | mTLS Auth Plugin | Client cert required for admin APIs |
| WAF | AWS WAF | SQLi, XSS, rate-based rules |
| Headers | Response Transformer | Server header removed, security headers added |
| Logging | HTTP Log Plugin | CloudWatch, security metric filters |

### Verification Results

- JWT validation: Expired/invalid tokens correctly rejected (tested 50 payloads)
- Rate limiting: Enforced at 60 req/min, 429 returned with Retry-After header
- Request validation: Malformed requests rejected with 400 (tested 30 invalid payloads)
- mTLS: Requests without client certificate rejected with 401
- WAF: SQL injection payloads blocked (tested top 100 SQLi patterns)

评论

支持 Markdown