[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71GPK13C3DTCVPD4Z2WYEX7":3,"skill-same:01M71GPK13C3DTCVPD4Z2WYEX7":101},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":74,"commitSha":75,"skillDirectory":76,"forksCount":14,"repositoryHtmlUrl":77,"repositoryHomepageUrl":6,"ownerHtmlUrl":78,"ownerBlogUrl":6,"ownerDescription":79,"updatedAt":80,"install":81,"resources":94},"01M71GPK13C3DTCVPD4Z2WYEX7","api-gateway-exploit",null,"Implements security controls at the API gateway layer including authentication enforcement, rate limiting, request validation, IP allowlisting, TLS termination, and threat protection. The engineer configures API gateways (Kong, AWS API Gateway, Azure APIM, Apigee) to act as a centralized security enforcement point that validates, throttles, and monitors all API traffic before it reaches backend services. Activates for requests involving API gateway security, API management security, gateway authentication, or centralized API protection.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fgateway\u002Fexploit\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"exploit","api gateway","gateway","api gateway exploit","api","at","request","de","Bash","cybersecurity","kong","traffic","tls","aws-api-gateway","api-security","ip","engineer","authentication","cm","backend services","2026-11-10 10:12:30",false,"---\nname: api-gateway-exploit\ndescription: Implements security controls at the API gateway layer including authentication enforcement, rate limiting, request validation, IP allowlisting, TLS termination, and threat protection. The engineer configures API gateways (Kong, AWS API Gateway, Azure APIM, Apigee) to act as a centralized security enforcement point that validates, throttles, and monitors all API traffic before it reaches backend services. Activates for requests involving API gateway security, API management security, gateway authentication, or centralized API protection.\ndomain: cybersecurity\nsubdomain: api-security\ntags:\n- api-security\n- api-gateway\n- kong\n- aws-api-gateway\n- rate-limiting\n- waf\nnist_csf:\n- PR.PS-01\n- ID.RA-01\n- PR.DS-10\n- DE.CM-01\nmodel: sonnet\nmaxTurns: 20\ntools: [Read, Bash, Glob, Grep]\nmitre_attack:\n- T1189\ncwe:\n- CWE-79\ncapec: []\n---\n\n# Implementing API Gateway Security Controls\n\n## When to Use\n\n- Deploying a centralized authentication and authorization layer for microservice APIs\n- Implementing rate limiting, throttling, and quota management across all API endpoints\n- Configuring request\u002Fresponse validation against OpenAPI specifications at the gateway level\n- Setting up TLS termination, mutual TLS, and certificate management for API traffic\n- Integrating WAF rules with the API gateway to block injection, XSS, and known attack patterns\n\n**Do not use** as the sole security layer. API gateways provide defense in depth but backend services must also validate authorization and input.\n\n## Prerequisites\n\n- API gateway platform selected and deployed (Kong, AWS API Gateway, Azure APIM, or Apigee)\n- OpenAPI\u002FSwagger specifications for all backend APIs\n- TLS certificates for the gateway domain\n- Identity provider (IdP) configured for OAuth2\u002FOIDC (Okta, Auth0, Azure AD)\n- Monitoring and logging infrastructure (CloudWatch, Datadog, ELK)\n- Backend service endpoints registered and reachable from the gateway\n\n## Workflow\n\n### Step 1: Kong Gateway Security Configuration\n\n```yaml\n# kong.yml - Declarative Kong configuration with security plugins\n_format_version: \"3.0\"\n\nservices:\n  - name: user-service\n    url: http:\u002F\u002Fuser-service:8080\n    routes:\n      - name: user-api\n        paths:\n          - \u002Fapi\u002Fv1\u002Fusers\n        methods:\n          - GET\n          - POST\n          - PUT\n          - PATCH\n          - DELETE\n        strip_path: false\n\nplugins:\n  # 1. Authentication: JWT validation\n  - name: jwt\n    config:\n      uri_param_names:\n        - jwt\n      header_names:\n        - Authorization\n      claims_to_verify:\n        - exp\n      maximum_expiration: 3600  # Max 1 hour token TTL\n\n  # 2. Rate Limiting\n  - name: rate-limiting\n    config:\n      minute: 60\n      hour: 1000\n      policy: redis\n      redis_host: redis\n      redis_port: 6379\n      fault_tolerant: true\n      hide_client_headers: false\n      limit_by: credential  # Per-user, not per-IP\n\n  # 3. Request Size Limiting\n  - name: request-size-limiting\n    config:\n      allowed_payload_size: 1  # 1 MB max\n      size_unit: megabytes\n\n  # 4. IP Restriction (admin endpoints)\n  - name: ip-restriction\n    service: admin-service\n    config:\n      allow:\n        - 10.0.0.0\u002F8\n        - 172.16.0.0\u002F12\n\n  # 5. Bot Detection\n  - name: bot-detection\n    config:\n      deny:\n        - \"sqlmap\"\n        - \"nikto\"\n        - \"nmap\"\n        - \"masscan\"\n\n  # 6. CORS Configuration\n  - name: cors\n    config:\n      origins:\n        - \"https:\u002F\u002Fapp.example.com\"\n      methods:\n        - GET\n        - POST\n        - PUT\n        - PATCH\n        - DELETE\n      headers:\n        - Authorization\n        - Content-Type\n      credentials: true\n      max_age: 3600\n\n  # 7. Response Transformer - Remove sensitive headers\n  - name: response-transformer\n    config:\n      remove:\n        headers:\n          - X-Powered-By\n          - Server\n      add:\n        headers:\n          - \"X-Content-Type-Options: nosniff\"\n          - \"X-Frame-Options: DENY\"\n          - \"Strict-Transport-Security: max-age=31536000; includeSubDomains\"\n          - \"Content-Security-Policy: default-src 'none'\"\n```\n\n### Step 2: AWS API Gateway Security Configuration\n\n```python\nimport boto3\nimport json\n\napigw = boto3.client('apigatewayv2')\n\n# Create API with mutual TLS\napi_response = apigw.create_api(\n    Name='secure-api',\n    ProtocolType='HTTP',\n    DisableExecuteApiEndpoint=True,  # Force custom domain\n)\napi_id = api_response['ApiId']\n\n# Configure authorizer (JWT with Cognito)\nauthorizer = apigw.create_authorizer(\n    ApiId=api_id,\n    AuthorizerType='JWT',\n    IdentitySource='$request.header.Authorization',\n    Name='cognito-jwt-authorizer',\n    JwtConfiguration={\n        'Audience': ['your-app-client-id'],\n        'Issuer': 'https:\u002F\u002Fcognito-idp.us-east-1.amazonaws.com\u002Fus-east-1_xxxxx'\n    }\n)\n\n# Create route with authorizer\napigw.create_route(\n    ApiId=api_id,\n    RouteKey='GET \u002Fapi\u002Fv1\u002Fusers',\n    AuthorizerId=authorizer['AuthorizerId'],\n    AuthorizationType='JWT',\n)\n\n# Configure throttling\napigw.create_stage(\n    ApiId=api_id,\n    StageName='prod',\n    DefaultRouteSettings={\n        'ThrottlingBurstLimit': 100,\n        'ThrottlingRateLimit': 50.0,  # 50 requests per second\n    },\n    AccessLogSettings={\n        'DestinationArn': 'arn:aws:logs:us-east-1:123456789:log-group:api-access-logs',\n        'Format': json.dumps({\n            'requestId': '$context.requestId',\n            'ip': '$context.identity.sourceIp',\n            'caller': '$context.identity.caller',\n            'user': '$context.identity.user',\n            'requestTime': '$context.requestTime',\n            'httpMethod': '$context.httpMethod',\n            'resourcePath': '$context.resourcePath',\n            'status': '$context.status',\n            'protocol': '$context.protocol',\n            'responseLength': '$context.responseLength'\n        })\n    }\n)\n\n# WAF association\nwaf = boto3.client('wafv2')\nweb_acl = waf.create_web_acl(\n    Name='api-security-acl',\n    Scope='REGIONAL',\n    DefaultAction={'Allow': {}},\n    Rules=[\n        {\n            'Name': 'AWS-AWSManagedRulesSQLiRuleSet',\n            'Priority': 1,\n            'Statement': {\n                'ManagedRuleGroupStatement': {\n                    'VendorName': 'AWS',\n                    'Name': 'AWSManagedRulesSQLiRuleSet'\n                }\n            },\n            'OverrideAction': {'None': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'SQLiRuleSet'\n            }\n        },\n        {\n            'Name': 'RateLimit',\n            'Priority': 2,\n            'Statement': {\n                'RateBasedStatement': {\n                    'Limit': 2000,\n                    'AggregateKeyType': 'IP'\n                }\n            },\n            'Action': {'Block': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'RateLimitRule'\n            }\n        },\n    ],\n    VisibilityConfig={\n        'SampledRequestsEnabled': True,\n        'CloudWatchMetricsEnabled': True,\n        'MetricName': 'ApiSecurityACL'\n    }\n)\n```\n\n### Step 3: Request Validation with OpenAPI Schema\n\n```yaml\n# Kong OAS Validation Plugin configuration\nplugins:\n  - name: oas-validation\n    config:\n      api_spec: |\n        openapi: \"3.0.3\"\n        info:\n          title: Secure API\n          version: \"1.0\"\n        paths:\n          \u002Fapi\u002Fv1\u002Fusers:\n            post:\n              requestBody:\n                required: true\n                content:\n                  application\u002Fjson:\n                    schema:\n                      type: object\n                      required: [name, email]\n                      properties:\n                        name:\n                          type: string\n                          maxLength: 100\n                          pattern: \"^[a-zA-Z ]+$\"\n                        email:\n                          type: string\n                          format: email\n                          maxLength: 255\n                      additionalProperties: false  # Block mass assignment\n              responses:\n                '201':\n                  description: User created\n      validate_request_body: true\n      validate_request_header_params: true\n      validate_request_query_params: true\n      validate_request_uri_params: true\n      verbose_response: false  # Do not expose schema details in errors\n```\n\n### Step 4: Mutual TLS Configuration\n\n```bash\n# Generate CA and client certificates for mTLS\n# 1. Create CA\nopenssl genrsa -out ca.key 4096\nopenssl req -new -x509 -key ca.key -out ca.crt -days 365 \\\n    -subj \"\u002FCN=API Gateway CA\u002FO=Example Corp\"\n\n# 2. Create client certificate\nopenssl genrsa -out client.key 2048\nopenssl req -new -key client.key -out client.csr \\\n    -subj \"\u002FCN=api-client\u002FO=Example Corp\"\nopenssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \\\n    -CAcreateserial -out client.crt -days 365\n\n# Kong mTLS configuration\n# Upload CA certificate to Kong\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fca_certificates \\\n    -F \"cert=@ca.crt\"\n\n# Enable mTLS plugin\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fservices\u002Fuser-service\u002Fplugins \\\n    --data \"name=mtls-auth\" \\\n    --data \"config.ca_certificates[]=$(cat ca_cert_id)\" \\\n    --data \"config.revocation_check_mode=SKIP\" \\\n    --data \"config.authenticated_group_by=CN\"\n```\n\n### Step 5: Logging and Monitoring Configuration\n\n```python\n# CloudWatch monitoring for API security events\nimport boto3\n\ncloudwatch = boto3.client('cloudwatch')\nlogs = boto3.client('logs')\n\n# Create metric filters for security events\nsecurity_filters = [\n    {\n        'name': 'UnauthorizedAccess',\n        'pattern': '{ $.status = 401 || $.status = 403 }',\n        'metric': 'UnauthorizedAccessCount'\n    },\n    {\n        'name': 'RateLimitHits',\n        'pattern': '{ $.status = 429 }',\n        'metric': 'RateLimitHitCount'\n    },\n    {\n        'name': 'ServerErrors',\n        'pattern': '{ $.status >= 500 }',\n        'metric': 'ServerErrorCount'\n    },\n    {\n        'name': 'LargeResponses',\n        'pattern': '{ $.responseLength > 1000000 }',\n        'metric': 'LargeResponseCount'\n    },\n]\n\nfor sf in security_filters:\n    logs.put_metric_filter(\n        logGroupName='api-access-logs',\n        filterName=sf['name'],\n        filterPattern=sf['pattern'],\n        metricTransformations=[{\n            'metricName': sf['metric'],\n            'metricNamespace': 'APISecurityMetrics',\n            'metricValue': '1',\n            'defaultValue': 0\n        }]\n    )\n\n# Create alarm for unusual 401\u002F403 spike\ncloudwatch.put_metric_alarm(\n    AlarmName='API-UnauthorizedAccessSpike',\n    MetricName='UnauthorizedAccessCount',\n    Namespace='APISecurityMetrics',\n    Statistic='Sum',\n    Period=300,  # 5 minutes\n    EvaluationPeriods=1,\n    Threshold=100,\n    ComparisonOperator='GreaterThanThreshold',\n    AlarmActions=['arn:aws:sns:us-east-1:123456789:security-alerts'],\n    AlarmDescription='More than 100 unauthorized access attempts in 5 minutes'\n)\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **API Gateway** | Centralized entry point for all API traffic that enforces authentication, authorization, rate limiting, and request validation before routing to backend services |\n| **Rate Limiting** | Controlling the number of API requests per client within a time window to prevent abuse and ensure fair resource allocation |\n| **Request Validation** | Verifying that incoming API requests conform to the expected schema (data types, required fields, value ranges) before forwarding to backend services |\n| **Mutual TLS (mTLS)** | Two-way TLS authentication where both the client and server present certificates, providing strong identity verification for API-to-API communication |\n| **WAF Integration** | Web Application Firewall rules applied at the API gateway to block common attack patterns (SQLi, XSS, path traversal) |\n| **OAuth2\u002FOIDC** | Token-based authentication protocols where the gateway validates JWT tokens against an identity provider before allowing access |\n\n## Tools & Systems\n\n- **Kong Gateway**: Open-source API gateway with extensive plugin ecosystem for security, rate limiting, and authentication\n- **AWS API Gateway**: Managed API gateway service with built-in throttling, WAF integration, and Lambda authorizers\n- **Azure API Management**: Enterprise API gateway with policy-based security, developer portal, and Azure AD integration\n- **Apigee (Google Cloud)**: API management platform with threat protection, quota management, and API analytics\n- **Envoy Proxy**: High-performance proxy used as API gateway in service mesh architectures with extensive filter chain\n\n## Common Scenarios\n\n### Scenario: Securing a Microservice API with Kong Gateway\n\n**Context**: A company is migrating from a monolithic API to microservices. Each microservice has its own REST API. The security team needs to implement centralized authentication, rate limiting, and request validation without modifying each service.\n\n**Approach**:\n1. Deploy Kong Gateway as the single entry point, routing traffic to 8 backend microservices\n2. Configure JWT validation plugin to verify tokens against the company's Keycloak IdP\n3. Apply rate limiting: 60 requests\u002Fminute for regular users, 300\u002Fminute for premium users, identified by JWT claims\n4. Enable OAS validation plugin to reject requests that do not match the OpenAPI spec (blocks mass assignment and injection)\n5. Configure mTLS for service-to-service communication behind the gateway\n6. Set up response transformer to remove Server and X-Powered-By headers and add security headers\n7. Integrate with AWS WAF for SQL injection and XSS protection rules\n8. Configure access logging to CloudWatch with security metric filters and alerting\n\n**Pitfalls**:\n- Relying solely on the gateway for authorization when backend services also need to verify permissions\n- Not configuring rate limiting per authenticated user (per-IP only allows attackers to bypass with IP rotation)\n- Using verbose error responses from the gateway that reveal internal service architecture\n- Not testing the gateway configuration with security tools after deployment\n- Missing mutual TLS between the gateway and backend services, allowing direct backend access\n\n## Output Format\n\n```\n## API Gateway Security Configuration Report\n\n**Gateway**: Kong 3.5 (Kubernetes deployment)\n**Backend Services**: 8 microservices\n**Date**: 2024-12-15\n\n### Security Controls Implemented\n\n| Control | Plugin\u002FFeature | Configuration |\n|---------|---------------|---------------|\n| Authentication | JWT Plugin | Cognito IdP, 1-hour max TTL |\n| Rate Limiting | Rate Limiting Plugin | 60 req\u002Fmin (user), Redis-backed |\n| Request Validation | OAS Validation | Strict mode, no additional properties |\n| TLS | Kong TLS | TLS 1.3 only, HSTS enabled |\n| mTLS | mTLS Auth Plugin | Client cert required for admin APIs |\n| WAF | AWS WAF | SQLi, XSS, rate-based rules |\n| Headers | Response Transformer | Server header removed, security headers added |\n| Logging | HTTP Log Plugin | CloudWatch, security metric filters |\n\n### Verification Results\n\n- JWT validation: Expired\u002Finvalid tokens correctly rejected (tested 50 payloads)\n- Rate limiting: Enforced at 60 req\u002Fmin, 429 returned with Retry-After header\n- Request validation: Malformed requests rejected with 400 (tested 30 invalid payloads)\n- mTLS: Requests without client certificate rejected with 401\n- WAF: SQL injection payloads blocked (tested top 100 SQLi patterns)\n```\n","# Implementing API Gateway Security Controls\n\n## When to Use\n\n- Deploying a centralized authentication and authorization layer for microservice APIs\n- Implementing rate limiting, throttling, and quota management across all API endpoints\n- Configuring request\u002Fresponse validation against OpenAPI specifications at the gateway level\n- Setting up TLS termination, mutual TLS, and certificate management for API traffic\n- Integrating WAF rules with the API gateway to block injection, XSS, and known attack patterns\n\n**Do not use** as the sole security layer. API gateways provide defense in depth but backend services must also validate authorization and input.\n\n## Prerequisites\n\n- API gateway platform selected and deployed (Kong, AWS API Gateway, Azure APIM, or Apigee)\n- OpenAPI\u002FSwagger specifications for all backend APIs\n- TLS certificates for the gateway domain\n- Identity provider (IdP) configured for OAuth2\u002FOIDC (Okta, Auth0, Azure AD)\n- Monitoring and logging infrastructure (CloudWatch, Datadog, ELK)\n- Backend service endpoints registered and reachable from the gateway\n\n## Workflow\n\n### Step 1: Kong Gateway Security Configuration\n\n```yaml\n# kong.yml - Declarative Kong configuration with security plugins\n_format_version: \"3.0\"\n\nservices:\n  - name: user-service\n    url: http:\u002F\u002Fuser-service:8080\n    routes:\n      - name: user-api\n        paths:\n          - \u002Fapi\u002Fv1\u002Fusers\n        methods:\n          - GET\n          - POST\n          - PUT\n          - PATCH\n          - DELETE\n        strip_path: false\n\nplugins:\n  # 1. Authentication: JWT validation\n  - name: jwt\n    config:\n      uri_param_names:\n        - jwt\n      header_names:\n        - Authorization\n      claims_to_verify:\n        - exp\n      maximum_expiration: 3600  # Max 1 hour token TTL\n\n  # 2. Rate Limiting\n  - name: rate-limiting\n    config:\n      minute: 60\n      hour: 1000\n      policy: redis\n      redis_host: redis\n      redis_port: 6379\n      fault_tolerant: true\n      hide_client_headers: false\n      limit_by: credential  # Per-user, not per-IP\n\n  # 3. Request Size Limiting\n  - name: request-size-limiting\n    config:\n      allowed_payload_size: 1  # 1 MB max\n      size_unit: megabytes\n\n  # 4. IP Restriction (admin endpoints)\n  - name: ip-restriction\n    service: admin-service\n    config:\n      allow:\n        - 10.0.0.0\u002F8\n        - 172.16.0.0\u002F12\n\n  # 5. Bot Detection\n  - name: bot-detection\n    config:\n      deny:\n        - \"sqlmap\"\n        - \"nikto\"\n        - \"nmap\"\n        - \"masscan\"\n\n  # 6. CORS Configuration\n  - name: cors\n    config:\n      origins:\n        - \"https:\u002F\u002Fapp.example.com\"\n      methods:\n        - GET\n        - POST\n        - PUT\n        - PATCH\n        - DELETE\n      headers:\n        - Authorization\n        - Content-Type\n      credentials: true\n      max_age: 3600\n\n  # 7. Response Transformer - Remove sensitive headers\n  - name: response-transformer\n    config:\n      remove:\n        headers:\n          - X-Powered-By\n          - Server\n      add:\n        headers:\n          - \"X-Content-Type-Options: nosniff\"\n          - \"X-Frame-Options: DENY\"\n          - \"Strict-Transport-Security: max-age=31536000; includeSubDomains\"\n          - \"Content-Security-Policy: default-src 'none'\"\n```\n\n### Step 2: AWS API Gateway Security Configuration\n\n```python\nimport boto3\nimport json\n\napigw = boto3.client('apigatewayv2')\n\n# Create API with mutual TLS\napi_response = apigw.create_api(\n    Name='secure-api',\n    ProtocolType='HTTP',\n    DisableExecuteApiEndpoint=True,  # Force custom domain\n)\napi_id = api_response['ApiId']\n\n# Configure authorizer (JWT with Cognito)\nauthorizer = apigw.create_authorizer(\n    ApiId=api_id,\n    AuthorizerType='JWT',\n    IdentitySource='$request.header.Authorization',\n    Name='cognito-jwt-authorizer',\n    JwtConfiguration={\n        'Audience': ['your-app-client-id'],\n        'Issuer': 'https:\u002F\u002Fcognito-idp.us-east-1.amazonaws.com\u002Fus-east-1_xxxxx'\n    }\n)\n\n# Create route with authorizer\napigw.create_route(\n    ApiId=api_id,\n    RouteKey='GET \u002Fapi\u002Fv1\u002Fusers',\n    AuthorizerId=authorizer['AuthorizerId'],\n    AuthorizationType='JWT',\n)\n\n# Configure throttling\napigw.create_stage(\n    ApiId=api_id,\n    StageName='prod',\n    DefaultRouteSettings={\n        'ThrottlingBurstLimit': 100,\n        'ThrottlingRateLimit': 50.0,  # 50 requests per second\n    },\n    AccessLogSettings={\n        'DestinationArn': 'arn:aws:logs:us-east-1:123456789:log-group:api-access-logs',\n        'Format': json.dumps({\n            'requestId': '$context.requestId',\n            'ip': '$context.identity.sourceIp',\n            'caller': '$context.identity.caller',\n            'user': '$context.identity.user',\n            'requestTime': '$context.requestTime',\n            'httpMethod': '$context.httpMethod',\n            'resourcePath': '$context.resourcePath',\n            'status': '$context.status',\n            'protocol': '$context.protocol',\n            'responseLength': '$context.responseLength'\n        })\n    }\n)\n\n# WAF association\nwaf = boto3.client('wafv2')\nweb_acl = waf.create_web_acl(\n    Name='api-security-acl',\n    Scope='REGIONAL',\n    DefaultAction={'Allow': {}},\n    Rules=[\n        {\n            'Name': 'AWS-AWSManagedRulesSQLiRuleSet',\n            'Priority': 1,\n            'Statement': {\n                'ManagedRuleGroupStatement': {\n                    'VendorName': 'AWS',\n                    'Name': 'AWSManagedRulesSQLiRuleSet'\n                }\n            },\n            'OverrideAction': {'None': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'SQLiRuleSet'\n            }\n        },\n        {\n            'Name': 'RateLimit',\n            'Priority': 2,\n            'Statement': {\n                'RateBasedStatement': {\n                    'Limit': 2000,\n                    'AggregateKeyType': 'IP'\n                }\n            },\n            'Action': {'Block': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'RateLimitRule'\n            }\n        },\n    ],\n    VisibilityConfig={\n        'SampledRequestsEnabled': True,\n        'CloudWatchMetricsEnabled': True,\n        'MetricName': 'ApiSecurityACL'\n    }\n)\n```\n\n### Step 3: Request Validation with OpenAPI Schema\n\n```yaml\n# Kong OAS Validation Plugin configuration\nplugins:\n  - name: oas-validation\n    config:\n      api_spec: |\n        openapi: \"3.0.3\"\n        info:\n          title: Secure API\n          version: \"1.0\"\n        paths:\n          \u002Fapi\u002Fv1\u002Fusers:\n            post:\n              requestBody:\n                required: true\n                content:\n                  application\u002Fjson:\n                    schema:\n                      type: object\n                      required: [name, email]\n                      properties:\n                        name:\n                          type: string\n                          maxLength: 100\n                          pattern: \"^[a-zA-Z ]+$\"\n                        email:\n                          type: string\n                          format: email\n                          maxLength: 255\n                      additionalProperties: false  # Block mass assignment\n              responses:\n                '201':\n                  description: User created\n      validate_request_body: true\n      validate_request_header_params: true\n      validate_request_query_params: true\n      validate_request_uri_params: true\n      verbose_response: false  # Do not expose schema details in errors\n```\n\n### Step 4: Mutual TLS Configuration\n\n```bash\n# Generate CA and client certificates for mTLS\n# 1. Create CA\nopenssl genrsa -out ca.key 4096\nopenssl req -new -x509 -key ca.key -out ca.crt -days 365 \\\n    -subj \"\u002FCN=API Gateway CA\u002FO=Example Corp\"\n\n# 2. Create client certificate\nopenssl genrsa -out client.key 2048\nopenssl req -new -key client.key -out client.csr \\\n    -subj \"\u002FCN=api-client\u002FO=Example Corp\"\nopenssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \\\n    -CAcreateserial -out client.crt -days 365\n\n# Kong mTLS configuration\n# Upload CA certificate to Kong\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fca_certificates \\\n    -F \"cert=@ca.crt\"\n\n# Enable mTLS plugin\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fservices\u002Fuser-service\u002Fplugins \\\n    --data \"name=mtls-auth\" \\\n    --data \"config.ca_certificates[]=$(cat ca_cert_id)\" \\\n    --data \"config.revocation_check_mode=SKIP\" \\\n    --data \"config.authenticated_group_by=CN\"\n```\n\n### Step 5: Logging and Monitoring Configuration\n\n```python\n# CloudWatch monitoring for API security events\nimport boto3\n\ncloudwatch = boto3.client('cloudwatch')\nlogs = boto3.client('logs')\n\n# Create metric filters for security events\nsecurity_filters = [\n    {\n        'name': 'UnauthorizedAccess',\n        'pattern': '{ $.status = 401 || $.status = 403 }',\n        'metric': 'UnauthorizedAccessCount'\n    },\n    {\n        'name': 'RateLimitHits',\n        'pattern': '{ $.status = 429 }',\n        'metric': 'RateLimitHitCount'\n    },\n    {\n        'name': 'ServerErrors',\n        'pattern': '{ $.status >= 500 }',\n        'metric': 'ServerErrorCount'\n    },\n    {\n        'name': 'LargeResponses',\n        'pattern': '{ $.responseLength > 1000000 }',\n        'metric': 'LargeResponseCount'\n    },\n]\n\nfor sf in security_filters:\n    logs.put_metric_filter(\n        logGroupName='api-access-logs',\n        filterName=sf['name'],\n        filterPattern=sf['pattern'],\n        metricTransformations=[{\n            'metricName': sf['metric'],\n            'metricNamespace': 'APISecurityMetrics',\n            'metricValue': '1',\n            'defaultValue': 0\n        }]\n    )\n\n# Create alarm for unusual 401\u002F403 spike\ncloudwatch.put_metric_alarm(\n    AlarmName='API-UnauthorizedAccessSpike',\n    MetricName='UnauthorizedAccessCount',\n    Namespace='APISecurityMetrics',\n    Statistic='Sum',\n    Period=300,  # 5 minutes\n    EvaluationPeriods=1,\n    Threshold=100,\n    ComparisonOperator='GreaterThanThreshold',\n    AlarmActions=['arn:aws:sns:us-east-1:123456789:security-alerts'],\n    AlarmDescription='More than 100 unauthorized access attempts in 5 minutes'\n)\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **API Gateway** | Centralized entry point for all API traffic that enforces authentication, authorization, rate limiting, and request validation before routing to backend services |\n| **Rate Limiting** | Controlling the number of API requests per client within a time window to prevent abuse and ensure fair resource allocation |\n| **Request Validation** | Verifying that incoming API requests conform to the expected schema (data types, required fields, value ranges) before forwarding to backend services |\n| **Mutual TLS (mTLS)** | Two-way TLS authentication where both the client and server present certificates, providing strong identity verification for API-to-API communication |\n| **WAF Integration** | Web Application Firewall rules applied at the API gateway to block common attack patterns (SQLi, XSS, path traversal) |\n| **OAuth2\u002FOIDC** | Token-based authentication protocols where the gateway validates JWT tokens against an identity provider before allowing access |\n\n## Tools & Systems\n\n- **Kong Gateway**: Open-source API gateway with extensive plugin ecosystem for security, rate limiting, and authentication\n- **AWS API Gateway**: Managed API gateway service with built-in throttling, WAF integration, and Lambda authorizers\n- **Azure API Management**: Enterprise API gateway with policy-based security, developer portal, and Azure AD integration\n- **Apigee (Google Cloud)**: API management platform with threat protection, quota management, and API analytics\n- **Envoy Proxy**: High-performance proxy used as API gateway in service mesh architectures with extensive filter chain\n\n## Common Scenarios\n\n### Scenario: Securing a Microservice API with Kong Gateway\n\n**Context**: A company is migrating from a monolithic API to microservices. Each microservice has its own REST API. The security team needs to implement centralized authentication, rate limiting, and request validation without modifying each service.\n\n**Approach**:\n1. Deploy Kong Gateway as the single entry point, routing traffic to 8 backend microservices\n2. Configure JWT validation plugin to verify tokens against the company's Keycloak IdP\n3. Apply rate limiting: 60 requests\u002Fminute for regular users, 300\u002Fminute for premium users, identified by JWT claims\n4. Enable OAS validation plugin to reject requests that do not match the OpenAPI spec (blocks mass assignment and injection)\n5. Configure mTLS for service-to-service communication behind the gateway\n6. Set up response transformer to remove Server and X-Powered-By headers and add security headers\n7. Integrate with AWS WAF for SQL injection and XSS protection rules\n8. Configure access logging to CloudWatch with security metric filters and alerting\n\n**Pitfalls**:\n- Relying solely on the gateway for authorization when backend services also need to verify permissions\n- Not configuring rate limiting per authenticated user (per-IP only allows attackers to bypass with IP rotation)\n- Using verbose error responses from the gateway that reveal internal service architecture\n- Not testing the gateway configuration with security tools after deployment\n- Missing mutual TLS between the gateway and backend services, allowing direct backend access\n\n## Output Format\n\n```\n## API Gateway Security Configuration Report\n\n**Gateway**: Kong 3.5 (Kubernetes deployment)\n**Backend Services**: 8 microservices\n**Date**: 2024-12-15\n\n### Security Controls Implemented\n\n| Control | Plugin\u002FFeature | Configuration |\n|---------|---------------|---------------|\n| Authentication | JWT Plugin | Cognito IdP, 1-hour max TTL |\n| Rate Limiting | Rate Limiting Plugin | 60 req\u002Fmin (user), Redis-backed |\n| Request Validation | OAS Validation | Strict mode, no additional properties |\n| TLS | Kong TLS | TLS 1.3 only, HSTS enabled |\n| mTLS | mTLS Auth Plugin | Client cert required for admin APIs |\n| WAF | AWS WAF | SQLi, XSS, rate-based rules |\n| Headers | Response Transformer | Server header removed, security headers added |\n| Logging | HTTP Log Plugin | CloudWatch, security metric filters |\n\n### Verification Results\n\n- JWT validation: Expired\u002Finvalid tokens correctly rejected (tested 50 payloads)\n- Rate limiting: Enforced at 60 req\u002Fmin, 429 returned with Retry-After header\n- Request validation: Malformed requests rejected with 400 (tested 30 invalid payloads)\n- mTLS: Requests without client certificate rejected with 401\n- WAF: SQL injection payloads blocked (tested top 100 SQLi patterns)\n```\n",{"cwe":54,"name":5,"tags":56,"capec":60,"model":61,"tools":62,"domain":38,"maxTurns":66,"nist_csf":67,"subdomain":43,"description":7,"mitre_attack":72},[55],"CWE-79",[43,57,39,42,58,59],"api-gateway","rate-limiting","waf",[],"sonnet",[63,37,64,65],"Read","Glob","Grep",20,[68,69,70,71],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[73],"T1189","main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fweb-application\u002Fapi\u002Fgateway\u002Fexploit","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":82,"prompt":92,"zipAvailable":93},[83,86,89],{"tool":84,"command":85},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill api-gateway-exploit",{"tool":87,"command":88},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill api-gateway-exploit",{"tool":90,"command":91},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill api-gateway-exploit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fgateway\u002Fexploit\u002FSKILL.md",true,[95],{"path":96,"resourceType":97,"resourceTypeDesc":98,"sizeBytes":99,"sourceHtmlUrl":100},"index.json","REFERENCE","参考文档",688,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fgateway\u002Fexploit\u002Findex.json",[102,125,145,166,188,203],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":49},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[109,110,111,112,113,36,47,114,115,116,117,118,119,120,121,122,123,38,124],"services","detect","services wmi persistence detect","wmi","persistence","process","activescript","event","subscriptions","commandline-consumer","repository","subscription","event-subscription","t1546.003","forensics","process-forensics",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":49},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[29,109,132,112,133,134,40,38,37,135,136,137,138,139,36,140,141,142,143,144],"services wmi exec exploit","exec","remote","analysis","team","across","crackmapexec","native","command","lateral movement","read","lateral-movement","Impacket",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":151,"publishedAt":49},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[152,153,154,155,156,157,38,37,158,135,159,160,36,142,161,162,163,164,165,61],"artifact","registry","registry artifact extract","extract","evidence-collection","artifact-analysis","collection","analyze","uncover","software","activity","digital-forensics","windows-registry","regripper",{"skillNo":167,"name":168,"nameZh":6,"description":169,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":170,"categories":171,"keywords":172,"publishedAt":49},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[110,173,174,175,176,177,178,47,179,38,124,180,181,182,183,184,185,186,187,36],"processes token impersonate detect","token","processes","attacks","windows","escalation","techniques","privilege-escalation","seimpersonate","token-impersonation","printspoofer","exploitation","potato","impersonation","via",{"skillNo":189,"name":190,"nameZh":6,"description":191,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":192,"categories":193,"keywords":194,"publishedAt":49},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[195,196,110,197,175,177,198,47,199,179,38,124,135,33,200,201,202,187,36,114],"thread","processes thread injection detect","injection","memory","process-injection","apc-injection","thread-injection","nt-api",{"skillNo":204,"name":205,"nameZh":6,"description":206,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":207,"categories":208,"keywords":209,"publishedAt":49},"01M71HA7H311V5G14WMX58HQSS","processes-hollow-technique-detect","Detect process hollowing (RunPE) by identifying processes with mismatched image paths between PEB and VAD tree, or unmapped PE headers in memory.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fhollow\u002Ftechnique\u002Fdetect\u002FSKILL.md",[],[210,110,175,211,198,47,212,213,38,124,214,215,216,217,218,219,36,114,220,221],"processes hollow technique detect","tree","memory-forensics","process-hollow","peb","runpe","image","pe-header","in memory","with","mismatched","headers"]