[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M758VZF3WMZJ6F0Z346AV9TM":3,"skill-same:01M758VZF3WMZJ6F0Z346AV9TM":73},{"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":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":37,"commitSha":38,"skillDirectory":5,"forksCount":14,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":41,"ownerDescription":6,"updatedAt":42,"install":43,"resources":56},"01M758VZF3WMZJ6F0Z346AV9TM","securing-api-gateway-with-aws-waf",null,"Securing API Gateway endpoints with AWS WAF by configuring managed rule groups for OWASP Top 10 protection, creating custom rate limiting rules, implementing bot control, setting up IP reputation filtering, and monitoring WAF metrics for security effectiveness.","SamuelChien\u002Fmega-skills-collection","SamuelChien","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F4652114?v=4","01M74KK34WVHA0P5ZYSJRDDFMG","Samuel Chien","01M74KK35FQN1N9VZ9EPTH3P2S",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fsecuring-api-gateway-with-aws-waf\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fsecuring-api-gateway-with-aws-waf\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: securing-api-gateway-with-aws-waf\ndescription: >\n  Securing API Gateway endpoints with AWS WAF by configuring managed rule groups for\n  OWASP Top 10 protection, creating custom rate limiting rules, implementing bot control,\n  setting up IP reputation filtering, and monitoring WAF metrics for security effectiveness.\ndomain: cybersecurity\nsubdomain: cloud-security\ntags: [cloud-security, aws, waf, api-gateway, rate-limiting, bot-protection, owasp]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\n---\n\n# Securing API Gateway with AWS WAF\n\n## When to Use\n\n- When deploying API Gateway endpoints that require protection against common web attacks\n- When implementing rate limiting and throttling to prevent API abuse and DDoS attacks\n- When building bot detection and mitigation for API endpoints exposed to the internet\n- When compliance requires WAF protection for all public-facing API endpoints\n- When customizing access controls based on IP reputation, geolocation, or request patterns\n\n**Do not use** for network-level DDoS protection (use AWS Shield), for application logic vulnerabilities (use SAST\u002FDAST tools), or for internal API security between microservices (use service mesh authentication and authorization).\n\n## Prerequisites\n\n- AWS API Gateway (REST or HTTP API) deployed with public endpoints\n- IAM permissions for `wafv2:*` and `apigateway:*` operations\n- CloudWatch and S3 or Kinesis Firehose configured for WAF logging\n- Understanding of the API's expected traffic patterns for rate limiting configuration\n- IP reputation lists or threat intelligence feeds for custom IP blocking\n\n## Workflow\n\n### Step 1: Create a WAF Web ACL with Managed Rule Groups\n\nCreate a Web ACL with AWS Managed Rules for baseline protection against OWASP Top 10 attacks.\n\n```bash\n# Create a WAF Web ACL with managed rule groups\naws wafv2 create-web-acl \\\n  --name api-gateway-waf \\\n  --scope REGIONAL \\\n  --default-action '{\"Allow\":{}}' \\\n  --visibility-config '{\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"api-gateway-waf\"\n  }' \\\n  --rules '[\n    {\n      \"Name\": \"AWSManagedRulesCommonRuleSet\",\n      \"Priority\": 1,\n      \"Statement\": {\n        \"ManagedRuleGroupStatement\": {\n          \"VendorName\": \"AWS\",\n          \"Name\": \"AWSManagedRulesCommonRuleSet\"\n        }\n      },\n      \"OverrideAction\": {\"None\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"CommonRuleSet\"\n      }\n    },\n    {\n      \"Name\": \"AWSManagedRulesKnownBadInputsRuleSet\",\n      \"Priority\": 2,\n      \"Statement\": {\n        \"ManagedRuleGroupStatement\": {\n          \"VendorName\": \"AWS\",\n          \"Name\": \"AWSManagedRulesKnownBadInputsRuleSet\"\n        }\n      },\n      \"OverrideAction\": {\"None\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"KnownBadInputs\"\n      }\n    },\n    {\n      \"Name\": \"AWSManagedRulesSQLiRuleSet\",\n      \"Priority\": 3,\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\": \"AWSManagedRulesAmazonIpReputationList\",\n      \"Priority\": 4,\n      \"Statement\": {\n        \"ManagedRuleGroupStatement\": {\n          \"VendorName\": \"AWS\",\n          \"Name\": \"AWSManagedRulesAmazonIpReputationList\"\n        }\n      },\n      \"OverrideAction\": {\"None\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"IPReputationList\"\n      }\n    }\n  ]'\n```\n\n### Step 2: Add Rate Limiting Rules\n\nConfigure rate-based rules to throttle excessive API requests per IP address.\n\n```bash\n# Get the Web ACL ARN and lock token\nWEB_ACL_ARN=$(aws wafv2 list-web-acls --scope REGIONAL \\\n  --query \"WebACLs[?Name=='api-gateway-waf'].ARN\" --output text)\n\n# Update Web ACL to add rate limiting rule\naws wafv2 update-web-acl \\\n  --name api-gateway-waf \\\n  --scope REGIONAL \\\n  --id $(aws wafv2 list-web-acls --scope REGIONAL --query \"WebACLs[?Name=='api-gateway-waf'].Id\" --output text) \\\n  --lock-token $(aws wafv2 get-web-acl --name api-gateway-waf --scope REGIONAL --id WEB_ACL_ID --query 'LockToken' --output text) \\\n  --default-action '{\"Allow\":{}}' \\\n  --visibility-config '{\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"api-gateway-waf\"\n  }' \\\n  --rules '[\n    {\n      \"Name\": \"RateLimitPerIP\",\n      \"Priority\": 0,\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\": \"RateLimitPerIP\"\n      }\n    },\n    {\n      \"Name\": \"RateLimitLoginEndpoint\",\n      \"Priority\": 5,\n      \"Statement\": {\n        \"RateBasedStatement\": {\n          \"Limit\": 100,\n          \"AggregateKeyType\": \"IP\",\n          \"ScopeDownStatement\": {\n            \"ByteMatchStatement\": {\n              \"FieldToMatch\": {\"UriPath\": {}},\n              \"PositionalConstraint\": \"STARTS_WITH\",\n              \"SearchString\": \"\u002Fapi\u002Fauth\u002Flogin\",\n              \"TextTransformations\": [{\"Priority\": 0, \"Type\": \"LOWERCASE\"}]\n            }\n          }\n        }\n      },\n      \"Action\": {\"Block\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"RateLimitLogin\"\n      }\n    }\n  ]'\n```\n\n### Step 3: Implement Bot Control\n\nAdd AWS WAF Bot Control to detect and manage automated traffic.\n\n```bash\n# Add Bot Control managed rule group\n# (Add to the rules array when updating the Web ACL)\n{\n  \"Name\": \"AWSManagedRulesBotControlRuleSet\",\n  \"Priority\": 6,\n  \"Statement\": {\n    \"ManagedRuleGroupStatement\": {\n      \"VendorName\": \"AWS\",\n      \"Name\": \"AWSManagedRulesBotControlRuleSet\",\n      \"ManagedRuleGroupConfigs\": [{\n        \"AWSManagedRulesBotControlRuleSet\": {\n          \"InspectionLevel\": \"COMMON\"\n        }\n      }],\n      \"ExcludedRules\": [\n        {\"Name\": \"CategoryHttpLibrary\"},\n        {\"Name\": \"SignalNonBrowserUserAgent\"}\n      ]\n    }\n  },\n  \"OverrideAction\": {\"None\": {}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"BotControl\"\n  }\n}\n```\n\n### Step 4: Create Custom Rules for API-Specific Protection\n\nBuild custom WAF rules for API-specific security requirements.\n\n```bash\n# Block requests without required API key header\n{\n  \"Name\": \"RequireAPIKey\",\n  \"Priority\": 7,\n  \"Statement\": {\n    \"NotStatement\": {\n      \"Statement\": {\n        \"ByteMatchStatement\": {\n          \"FieldToMatch\": {\n            \"SingleHeader\": {\"Name\": \"x-api-key\"}\n          },\n          \"PositionalConstraint\": \"EXACTLY\",\n          \"SearchString\": \"\",\n          \"TextTransformations\": [{\"Priority\": 0, \"Type\": \"NONE\"}]\n        }\n      }\n    }\n  },\n  \"Action\": {\"Block\": {\"CustomResponse\": {\"ResponseCode\": 403}}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"RequireAPIKey\"\n  }\n}\n\n# Geo-restrict to allowed countries\n{\n  \"Name\": \"GeoRestriction\",\n  \"Priority\": 8,\n  \"Statement\": {\n    \"NotStatement\": {\n      \"Statement\": {\n        \"GeoMatchStatement\": {\n          \"CountryCodes\": [\"US\", \"CA\", \"GB\", \"DE\", \"FR\", \"AU\"]\n        }\n      }\n    }\n  },\n  \"Action\": {\"Block\": {}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"GeoRestriction\"\n  }\n}\n\n# Block oversized request bodies (prevent payload attacks)\n{\n  \"Name\": \"MaxBodySize\",\n  \"Priority\": 9,\n  \"Statement\": {\n    \"SizeConstraintStatement\": {\n      \"FieldToMatch\": {\"Body\": {\"OversizeHandling\": \"MATCH\"}},\n      \"ComparisonOperator\": \"GT\",\n      \"Size\": 10240,\n      \"TextTransformations\": [{\"Priority\": 0, \"Type\": \"NONE\"}]\n    }\n  },\n  \"Action\": {\"Block\": {}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"MaxBodySize\"\n  }\n}\n```\n\n### Step 5: Associate WAF with API Gateway and Enable Logging\n\nAttach the Web ACL to the API Gateway stage and configure comprehensive logging.\n\n```bash\n# Associate Web ACL with API Gateway\naws wafv2 associate-web-acl \\\n  --web-acl-arn $WEB_ACL_ARN \\\n  --resource-arn arn:aws:apigateway:us-east-1::\u002Frestapis\u002FAPI_ID\u002Fstages\u002Fprod\n\n# Enable WAF logging to S3 via Kinesis Firehose\naws wafv2 put-logging-configuration \\\n  --logging-configuration '{\n    \"ResourceArn\": \"'$WEB_ACL_ARN'\",\n    \"LogDestinationConfigs\": [\n      \"arn:aws:firehose:us-east-1:ACCOUNT:deliverystream\u002Faws-waf-logs-api-gateway\"\n    ],\n    \"RedactedFields\": [\n      {\"SingleHeader\": {\"Name\": \"authorization\"}},\n      {\"SingleHeader\": {\"Name\": \"cookie\"}}\n    ]\n  }'\n\n# Verify association\naws wafv2 get-web-acl-for-resource \\\n  --resource-arn arn:aws:apigateway:us-east-1::\u002Frestapis\u002FAPI_ID\u002Fstages\u002Fprod\n```\n\n### Step 6: Monitor WAF Metrics and Tune Rules\n\nMonitor WAF effectiveness and tune rules to reduce false positives.\n\n```bash\n# Get WAF metrics from CloudWatch\naws cloudwatch get-metric-statistics \\\n  --namespace AWS\u002FWAFV2 \\\n  --metric-name BlockedRequests \\\n  --dimensions Name=WebACL,Value=api-gateway-waf Name=Rule,Value=ALL \\\n  --start-time 2026-02-22T00:00:00Z \\\n  --end-time 2026-02-23T00:00:00Z \\\n  --period 3600 \\\n  --statistics Sum\n\n# Get sampled requests for a specific rule\naws wafv2 get-sampled-requests \\\n  --web-acl-arn $WEB_ACL_ARN \\\n  --rule-metric-name RateLimitPerIP \\\n  --scope REGIONAL \\\n  --time-window '{\"StartTime\":\"2026-02-22T00:00:00Z\",\"EndTime\":\"2026-02-23T00:00:00Z\"}' \\\n  --max-items 50\n\n# Check rate-limited IPs\naws wafv2 get-rate-based-statement-managed-keys \\\n  --web-acl-name api-gateway-waf \\\n  --scope REGIONAL \\\n  --web-acl-id WEB_ACL_ID \\\n  --rule-name RateLimitPerIP\n\n# Create CloudWatch alarm for high block rate\naws cloudwatch put-metric-alarm \\\n  --alarm-name waf-high-block-rate \\\n  --namespace AWS\u002FWAFV2 \\\n  --metric-name BlockedRequests \\\n  --dimensions Name=WebACL,Value=api-gateway-waf Name=Rule,Value=ALL \\\n  --statistic Sum --period 300 --threshold 1000 \\\n  --comparison-operator GreaterThanThreshold \\\n  --evaluation-periods 2 \\\n  --alarm-actions arn:aws:sns:us-east-1:ACCOUNT:security-alerts\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| Web ACL | AWS WAF access control list that defines the collection of rules and their actions (allow, block, count) applied to associated resources |\n| Managed Rule Group | Pre-configured set of WAF rules maintained by AWS or third-party vendors for common attack patterns like OWASP Top 10 |\n| Rate-Based Rule | WAF rule that tracks request rates per IP address and blocks traffic exceeding a defined threshold within a 5-minute window |\n| Bot Control | AWS WAF managed rule group that identifies and manages automated traffic including scrapers, crawlers, and attack bots |\n| IP Reputation List | AWS-maintained list of IP addresses associated with malicious activity including botnets, scanners, and known attackers |\n| Custom Response | WAF capability to return specific HTTP status codes and custom response bodies when blocking requests |\n\n## Tools & Systems\n\n- **AWS WAF**: Web application firewall service for protecting API Gateway, ALB, CloudFront, and AppSync endpoints\n- **AWS Managed Rules**: Pre-built rule groups for common attack patterns maintained by AWS security team\n- **AWS Firewall Manager**: Central management of WAF policies across multiple accounts in AWS Organizations\n- **Kinesis Firehose**: Streaming delivery service for WAF logs to S3, Elasticsearch, or third-party analytics\n- **CloudWatch**: Monitoring service for WAF metrics including allowed, blocked, and counted requests\n\n## Common Scenarios\n\n### Scenario: Protecting a Public API from Credential Stuffing and Bot Attacks\n\n**Context**: A public REST API experiences thousands of authentication attempts per hour from automated bots attempting credential stuffing against the `\u002Fapi\u002Fauth\u002Flogin` endpoint.\n\n**Approach**:\n1. Create a Web ACL with AWS Managed Rules Common Rule Set for baseline protection\n2. Add a rate-based rule limiting the login endpoint to 100 requests per IP per 5 minutes\n3. Enable Bot Control managed rules to detect and block automated traffic\n4. Add IP Reputation List to block known malicious IPs proactively\n5. Create a custom rule blocking requests without proper User-Agent headers\n6. Enable WAF logging and create CloudWatch alarms for high block rates\n7. Review sampled blocked requests weekly to tune rules and reduce false positives\n\n**Pitfalls**: Rate limiting by IP can block legitimate users behind shared NAT gateways or corporate proxies. Consider using API key or authenticated session-based rate limiting for more granular control. Bot Control rules in COMMON inspection level may block legitimate API clients; start in Count mode and review before switching to Block.\n\n## Output Format\n\n```\nAWS WAF API Gateway Security Report\n======================================\nWeb ACL: api-gateway-waf\nAssociated Resource: API Gateway - production-api (prod stage)\nReport Period: 2026-02-16 to 2026-02-23\n\nTRAFFIC SUMMARY:\n  Total requests:              2,450,000\n  Allowed requests:            2,380,000 (97.1%)\n  Blocked requests:               70,000 (2.9%)\n\nBLOCKS BY RULE:\n  RateLimitPerIP:              28,000 (40%)\n  AWSManagedRulesCommonRuleSet: 18,000 (25.7%)\n  BotControl:                  12,000 (17.1%)\n  SQLiRuleSet:                  5,000 (7.1%)\n  IPReputationList:             4,000 (5.7%)\n  RateLimitLogin:               2,000 (2.9%)\n  GeoRestriction:               1,000 (1.4%)\n\nTOP BLOCKED IPs:\n  185.x.x.x:     8,400 requests (rate limited)\n  45.x.x.x:      5,200 requests (bot detected)\n  198.x.x.x:     3,100 requests (SQLi attempts)\n\nATTACK TYPES BLOCKED:\n  Credential stuffing (login endpoint):  2,000\n  SQL injection attempts:                5,000\n  Cross-site scripting:                  3,200\n  Known bad bot traffic:                12,000\n  Rate limit violations:               28,000\n\nWAF RULE HEALTH:\n  Rules in Block mode:    8 \u002F 10\n  Rules in Count mode:    2 \u002F 10 (under evaluation)\n  False positive rate:    \u003C 0.1%\n```\n","# Securing API Gateway with AWS WAF\n\n## When to Use\n\n- When deploying API Gateway endpoints that require protection against common web attacks\n- When implementing rate limiting and throttling to prevent API abuse and DDoS attacks\n- When building bot detection and mitigation for API endpoints exposed to the internet\n- When compliance requires WAF protection for all public-facing API endpoints\n- When customizing access controls based on IP reputation, geolocation, or request patterns\n\n**Do not use** for network-level DDoS protection (use AWS Shield), for application logic vulnerabilities (use SAST\u002FDAST tools), or for internal API security between microservices (use service mesh authentication and authorization).\n\n## Prerequisites\n\n- AWS API Gateway (REST or HTTP API) deployed with public endpoints\n- IAM permissions for `wafv2:*` and `apigateway:*` operations\n- CloudWatch and S3 or Kinesis Firehose configured for WAF logging\n- Understanding of the API's expected traffic patterns for rate limiting configuration\n- IP reputation lists or threat intelligence feeds for custom IP blocking\n\n## Workflow\n\n### Step 1: Create a WAF Web ACL with Managed Rule Groups\n\nCreate a Web ACL with AWS Managed Rules for baseline protection against OWASP Top 10 attacks.\n\n```bash\n# Create a WAF Web ACL with managed rule groups\naws wafv2 create-web-acl \\\n  --name api-gateway-waf \\\n  --scope REGIONAL \\\n  --default-action '{\"Allow\":{}}' \\\n  --visibility-config '{\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"api-gateway-waf\"\n  }' \\\n  --rules '[\n    {\n      \"Name\": \"AWSManagedRulesCommonRuleSet\",\n      \"Priority\": 1,\n      \"Statement\": {\n        \"ManagedRuleGroupStatement\": {\n          \"VendorName\": \"AWS\",\n          \"Name\": \"AWSManagedRulesCommonRuleSet\"\n        }\n      },\n      \"OverrideAction\": {\"None\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"CommonRuleSet\"\n      }\n    },\n    {\n      \"Name\": \"AWSManagedRulesKnownBadInputsRuleSet\",\n      \"Priority\": 2,\n      \"Statement\": {\n        \"ManagedRuleGroupStatement\": {\n          \"VendorName\": \"AWS\",\n          \"Name\": \"AWSManagedRulesKnownBadInputsRuleSet\"\n        }\n      },\n      \"OverrideAction\": {\"None\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"KnownBadInputs\"\n      }\n    },\n    {\n      \"Name\": \"AWSManagedRulesSQLiRuleSet\",\n      \"Priority\": 3,\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\": \"AWSManagedRulesAmazonIpReputationList\",\n      \"Priority\": 4,\n      \"Statement\": {\n        \"ManagedRuleGroupStatement\": {\n          \"VendorName\": \"AWS\",\n          \"Name\": \"AWSManagedRulesAmazonIpReputationList\"\n        }\n      },\n      \"OverrideAction\": {\"None\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"IPReputationList\"\n      }\n    }\n  ]'\n```\n\n### Step 2: Add Rate Limiting Rules\n\nConfigure rate-based rules to throttle excessive API requests per IP address.\n\n```bash\n# Get the Web ACL ARN and lock token\nWEB_ACL_ARN=$(aws wafv2 list-web-acls --scope REGIONAL \\\n  --query \"WebACLs[?Name=='api-gateway-waf'].ARN\" --output text)\n\n# Update Web ACL to add rate limiting rule\naws wafv2 update-web-acl \\\n  --name api-gateway-waf \\\n  --scope REGIONAL \\\n  --id $(aws wafv2 list-web-acls --scope REGIONAL --query \"WebACLs[?Name=='api-gateway-waf'].Id\" --output text) \\\n  --lock-token $(aws wafv2 get-web-acl --name api-gateway-waf --scope REGIONAL --id WEB_ACL_ID --query 'LockToken' --output text) \\\n  --default-action '{\"Allow\":{}}' \\\n  --visibility-config '{\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"api-gateway-waf\"\n  }' \\\n  --rules '[\n    {\n      \"Name\": \"RateLimitPerIP\",\n      \"Priority\": 0,\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\": \"RateLimitPerIP\"\n      }\n    },\n    {\n      \"Name\": \"RateLimitLoginEndpoint\",\n      \"Priority\": 5,\n      \"Statement\": {\n        \"RateBasedStatement\": {\n          \"Limit\": 100,\n          \"AggregateKeyType\": \"IP\",\n          \"ScopeDownStatement\": {\n            \"ByteMatchStatement\": {\n              \"FieldToMatch\": {\"UriPath\": {}},\n              \"PositionalConstraint\": \"STARTS_WITH\",\n              \"SearchString\": \"\u002Fapi\u002Fauth\u002Flogin\",\n              \"TextTransformations\": [{\"Priority\": 0, \"Type\": \"LOWERCASE\"}]\n            }\n          }\n        }\n      },\n      \"Action\": {\"Block\": {}},\n      \"VisibilityConfig\": {\n        \"SampledRequestsEnabled\": true,\n        \"CloudWatchMetricsEnabled\": true,\n        \"MetricName\": \"RateLimitLogin\"\n      }\n    }\n  ]'\n```\n\n### Step 3: Implement Bot Control\n\nAdd AWS WAF Bot Control to detect and manage automated traffic.\n\n```bash\n# Add Bot Control managed rule group\n# (Add to the rules array when updating the Web ACL)\n{\n  \"Name\": \"AWSManagedRulesBotControlRuleSet\",\n  \"Priority\": 6,\n  \"Statement\": {\n    \"ManagedRuleGroupStatement\": {\n      \"VendorName\": \"AWS\",\n      \"Name\": \"AWSManagedRulesBotControlRuleSet\",\n      \"ManagedRuleGroupConfigs\": [{\n        \"AWSManagedRulesBotControlRuleSet\": {\n          \"InspectionLevel\": \"COMMON\"\n        }\n      }],\n      \"ExcludedRules\": [\n        {\"Name\": \"CategoryHttpLibrary\"},\n        {\"Name\": \"SignalNonBrowserUserAgent\"}\n      ]\n    }\n  },\n  \"OverrideAction\": {\"None\": {}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"BotControl\"\n  }\n}\n```\n\n### Step 4: Create Custom Rules for API-Specific Protection\n\nBuild custom WAF rules for API-specific security requirements.\n\n```bash\n# Block requests without required API key header\n{\n  \"Name\": \"RequireAPIKey\",\n  \"Priority\": 7,\n  \"Statement\": {\n    \"NotStatement\": {\n      \"Statement\": {\n        \"ByteMatchStatement\": {\n          \"FieldToMatch\": {\n            \"SingleHeader\": {\"Name\": \"x-api-key\"}\n          },\n          \"PositionalConstraint\": \"EXACTLY\",\n          \"SearchString\": \"\",\n          \"TextTransformations\": [{\"Priority\": 0, \"Type\": \"NONE\"}]\n        }\n      }\n    }\n  },\n  \"Action\": {\"Block\": {\"CustomResponse\": {\"ResponseCode\": 403}}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"RequireAPIKey\"\n  }\n}\n\n# Geo-restrict to allowed countries\n{\n  \"Name\": \"GeoRestriction\",\n  \"Priority\": 8,\n  \"Statement\": {\n    \"NotStatement\": {\n      \"Statement\": {\n        \"GeoMatchStatement\": {\n          \"CountryCodes\": [\"US\", \"CA\", \"GB\", \"DE\", \"FR\", \"AU\"]\n        }\n      }\n    }\n  },\n  \"Action\": {\"Block\": {}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"GeoRestriction\"\n  }\n}\n\n# Block oversized request bodies (prevent payload attacks)\n{\n  \"Name\": \"MaxBodySize\",\n  \"Priority\": 9,\n  \"Statement\": {\n    \"SizeConstraintStatement\": {\n      \"FieldToMatch\": {\"Body\": {\"OversizeHandling\": \"MATCH\"}},\n      \"ComparisonOperator\": \"GT\",\n      \"Size\": 10240,\n      \"TextTransformations\": [{\"Priority\": 0, \"Type\": \"NONE\"}]\n    }\n  },\n  \"Action\": {\"Block\": {}},\n  \"VisibilityConfig\": {\n    \"SampledRequestsEnabled\": true,\n    \"CloudWatchMetricsEnabled\": true,\n    \"MetricName\": \"MaxBodySize\"\n  }\n}\n```\n\n### Step 5: Associate WAF with API Gateway and Enable Logging\n\nAttach the Web ACL to the API Gateway stage and configure comprehensive logging.\n\n```bash\n# Associate Web ACL with API Gateway\naws wafv2 associate-web-acl \\\n  --web-acl-arn $WEB_ACL_ARN \\\n  --resource-arn arn:aws:apigateway:us-east-1::\u002Frestapis\u002FAPI_ID\u002Fstages\u002Fprod\n\n# Enable WAF logging to S3 via Kinesis Firehose\naws wafv2 put-logging-configuration \\\n  --logging-configuration '{\n    \"ResourceArn\": \"'$WEB_ACL_ARN'\",\n    \"LogDestinationConfigs\": [\n      \"arn:aws:firehose:us-east-1:ACCOUNT:deliverystream\u002Faws-waf-logs-api-gateway\"\n    ],\n    \"RedactedFields\": [\n      {\"SingleHeader\": {\"Name\": \"authorization\"}},\n      {\"SingleHeader\": {\"Name\": \"cookie\"}}\n    ]\n  }'\n\n# Verify association\naws wafv2 get-web-acl-for-resource \\\n  --resource-arn arn:aws:apigateway:us-east-1::\u002Frestapis\u002FAPI_ID\u002Fstages\u002Fprod\n```\n\n### Step 6: Monitor WAF Metrics and Tune Rules\n\nMonitor WAF effectiveness and tune rules to reduce false positives.\n\n```bash\n# Get WAF metrics from CloudWatch\naws cloudwatch get-metric-statistics \\\n  --namespace AWS\u002FWAFV2 \\\n  --metric-name BlockedRequests \\\n  --dimensions Name=WebACL,Value=api-gateway-waf Name=Rule,Value=ALL \\\n  --start-time 2026-02-22T00:00:00Z \\\n  --end-time 2026-02-23T00:00:00Z \\\n  --period 3600 \\\n  --statistics Sum\n\n# Get sampled requests for a specific rule\naws wafv2 get-sampled-requests \\\n  --web-acl-arn $WEB_ACL_ARN \\\n  --rule-metric-name RateLimitPerIP \\\n  --scope REGIONAL \\\n  --time-window '{\"StartTime\":\"2026-02-22T00:00:00Z\",\"EndTime\":\"2026-02-23T00:00:00Z\"}' \\\n  --max-items 50\n\n# Check rate-limited IPs\naws wafv2 get-rate-based-statement-managed-keys \\\n  --web-acl-name api-gateway-waf \\\n  --scope REGIONAL \\\n  --web-acl-id WEB_ACL_ID \\\n  --rule-name RateLimitPerIP\n\n# Create CloudWatch alarm for high block rate\naws cloudwatch put-metric-alarm \\\n  --alarm-name waf-high-block-rate \\\n  --namespace AWS\u002FWAFV2 \\\n  --metric-name BlockedRequests \\\n  --dimensions Name=WebACL,Value=api-gateway-waf Name=Rule,Value=ALL \\\n  --statistic Sum --period 300 --threshold 1000 \\\n  --comparison-operator GreaterThanThreshold \\\n  --evaluation-periods 2 \\\n  --alarm-actions arn:aws:sns:us-east-1:ACCOUNT:security-alerts\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| Web ACL | AWS WAF access control list that defines the collection of rules and their actions (allow, block, count) applied to associated resources |\n| Managed Rule Group | Pre-configured set of WAF rules maintained by AWS or third-party vendors for common attack patterns like OWASP Top 10 |\n| Rate-Based Rule | WAF rule that tracks request rates per IP address and blocks traffic exceeding a defined threshold within a 5-minute window |\n| Bot Control | AWS WAF managed rule group that identifies and manages automated traffic including scrapers, crawlers, and attack bots |\n| IP Reputation List | AWS-maintained list of IP addresses associated with malicious activity including botnets, scanners, and known attackers |\n| Custom Response | WAF capability to return specific HTTP status codes and custom response bodies when blocking requests |\n\n## Tools & Systems\n\n- **AWS WAF**: Web application firewall service for protecting API Gateway, ALB, CloudFront, and AppSync endpoints\n- **AWS Managed Rules**: Pre-built rule groups for common attack patterns maintained by AWS security team\n- **AWS Firewall Manager**: Central management of WAF policies across multiple accounts in AWS Organizations\n- **Kinesis Firehose**: Streaming delivery service for WAF logs to S3, Elasticsearch, or third-party analytics\n- **CloudWatch**: Monitoring service for WAF metrics including allowed, blocked, and counted requests\n\n## Common Scenarios\n\n### Scenario: Protecting a Public API from Credential Stuffing and Bot Attacks\n\n**Context**: A public REST API experiences thousands of authentication attempts per hour from automated bots attempting credential stuffing against the `\u002Fapi\u002Fauth\u002Flogin` endpoint.\n\n**Approach**:\n1. Create a Web ACL with AWS Managed Rules Common Rule Set for baseline protection\n2. Add a rate-based rule limiting the login endpoint to 100 requests per IP per 5 minutes\n3. Enable Bot Control managed rules to detect and block automated traffic\n4. Add IP Reputation List to block known malicious IPs proactively\n5. Create a custom rule blocking requests without proper User-Agent headers\n6. Enable WAF logging and create CloudWatch alarms for high block rates\n7. Review sampled blocked requests weekly to tune rules and reduce false positives\n\n**Pitfalls**: Rate limiting by IP can block legitimate users behind shared NAT gateways or corporate proxies. Consider using API key or authenticated session-based rate limiting for more granular control. Bot Control rules in COMMON inspection level may block legitimate API clients; start in Count mode and review before switching to Block.\n\n## Output Format\n\n```\nAWS WAF API Gateway Security Report\n======================================\nWeb ACL: api-gateway-waf\nAssociated Resource: API Gateway - production-api (prod stage)\nReport Period: 2026-02-16 to 2026-02-23\n\nTRAFFIC SUMMARY:\n  Total requests:              2,450,000\n  Allowed requests:            2,380,000 (97.1%)\n  Blocked requests:               70,000 (2.9%)\n\nBLOCKS BY RULE:\n  RateLimitPerIP:              28,000 (40%)\n  AWSManagedRulesCommonRuleSet: 18,000 (25.7%)\n  BotControl:                  12,000 (17.1%)\n  SQLiRuleSet:                  5,000 (7.1%)\n  IPReputationList:             4,000 (5.7%)\n  RateLimitLogin:               2,000 (2.9%)\n  GeoRestriction:               1,000 (1.4%)\n\nTOP BLOCKED IPs:\n  185.x.x.x:     8,400 requests (rate limited)\n  45.x.x.x:      5,200 requests (bot detected)\n  198.x.x.x:     3,100 requests (SQLi attempts)\n\nATTACK TYPES BLOCKED:\n  Credential stuffing (login endpoint):  2,000\n  SQL injection attempts:                5,000\n  Cross-site scripting:                  3,200\n  Known bad bot traffic:                12,000\n  Rate limit violations:               28,000\n\nWAF RULE HEALTH:\n  Rules in Block mode:    8 \u002F 10\n  Rules in Count mode:    2 \u002F 10 (under evaluation)\n  False positive rate:    \u003C 0.1%\n```\n",{"name":5,"tags":25,"author":33,"domain":34,"license":15,"version":35,"subdomain":26,"description":36},[26,27,28,29,30,31,32],"cloud-security","aws","waf","api-gateway","rate-limiting","bot-protection","owasp","mahipal","cybersecurity","1.0","Securing API Gateway endpoints with AWS WAF by configuring managed rule groups for OWASP Top 10 protection, creating custom rate limiting rules, implementing bot control, setting up IP reputation filtering, and monitoring WAF metrics for security effectiveness.\n","main","c2b1fdccc779e99ac814e55fb69ca8d71215dd0f","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection","https:\u002F\u002Fgithub.com\u002FSamuelChien","http:\u002F\u002Fsamuelchien.com\u002F","2026-05-26 08:27:14",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add SamuelChien\u002Fmega-skills-collection --skill securing-api-gateway-with-aws-waf",{"tool":49,"command":50},"bunx","bunx skills add SamuelChien\u002Fmega-skills-collection --skill securing-api-gateway-with-aws-waf",{"tool":52,"command":53},"pnpm","pnpm dlx skills add SamuelChien\u002Fmega-skills-collection --skill securing-api-gateway-with-aws-waf","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fsecuring-api-gateway-with-aws-waf\u002FSKILL.md",true,[57,61,67],{"path":58,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":16},"LICENSE","许可证",11255,{"path":62,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002Fapi-reference.md","REFERENCE","参考文档",2315,"https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fsecuring-api-gateway-with-aws-waf\u002Freferences\u002Fapi-reference.md",{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"scripts\u002Fagent.py","SCRIPT","脚本",7214,"https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fsecuring-api-gateway-with-aws-waf\u002Fscripts\u002Fagent.py",[74,82,89,96,103,110],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":20},"01M76R4WZQZAXGGXMQCA0FZ716","zustand-store-ts","Create Zustand stores with TypeScript, subscribeWithSelector middleware, and proper state\u002Faction separation. Use when building React state management, creating global stores, or implementing reactive state patterns with Zustand.","MIT","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzustand-store-ts\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":20},"01M76R4T9KENDH7FENGZQHBW4G","zustand-store-creator","Zustand Store Creator - Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":20},"01M76R3YWN84B7SANJ52X799ZE","zero-trust-config-helper","Zero Trust Config Helper - Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":20},"01M76R3HNSV2AEYSKHM915GJ58","zapier-integration-helper","Zapier Integration Helper - Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":20},"01M76R3DJSKAT4FA7DV4BF3GCE","zai-cli","Execute z.AI CLI providing vision, search, reader, and GitHub exploration via CLI and MCP.\nUse when user needs image\u002Fvideo analysis, OCR, UI-to-code conversion, error diagnosis,\nreal-time web search, web page to markdown extraction, or GitHub code exploration.\nTrigger with phrases like \"analyze this image\", \"search the web for\", \"read this page\",\n\"explore this repo\", or \"use zai\". Requires Z_AI_API_KEY.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzai-cli\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":20},"01M76R2KAM699XE9AJVAWE4H2E","yt-research","Research competitor YouTube channels, niches, and trending topics for your content strategy.\nUse this skill whenever the user says \"research channels\", \"analyze competitors\", \"find trending topics\",\n\"niche analysis\", \"competitive research\", \"what are other creators doing\", \"scrape YouTube channels\",\nor wants to understand the competitive landscape for a specific tool or topic area. Use when working with yt research. Trigger with 'yt', 'research'.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fyt-research\u002FSKILL.md",[],[]]