This chapter covers AWS WAF (Web Application Firewall) specifically when integrated with Amazon API Gateway, a key topic for the DVA-C02 exam under Security objective 2.4. You will learn how to protect HTTP/REST APIs from common web exploits like SQL injection and cross-site scripting, and how to implement rate-based rules to mitigate DDoS attacks. Expect this topic to appear in approximately 5-10% of exam questions, typically in scenario-based multiple-choice questions where you must select the correct security measure.
Jump to a section
Imagine a VIP club with a strict bouncer at the door. The club (your API Gateway) has rules about who can enter based on their ID (origin IP), behavior (how many times they've tried to enter recently), and what they're carrying (HTTP headers, body content). The bouncer checks every person against a list of allowed guests (IP allow lists) and a list of troublemakers (IP deny lists). He also has a set of rules: no one wearing red (SQL injection patterns) gets in, no one carrying a backpack with a specific shape (XSS payloads) enters, and if someone tries to push past him repeatedly (rate limiting), they're banned for an hour. The bouncer doesn't open the inner door to the club (your backend) unless the person passes all checks. He can also inspect the contents of bags (request body) for prohibited items (malicious strings). If a rule is triggered, he can either turn the person away (block), let them in but watch them closely (count), or let them in but tag them for extra scrutiny (challenge with CAPTCHA). The club owner can update the bouncer's rulebook instantly without redecorating the club (no code changes).
What is AWS WAF and Why Use It with API Gateway?
AWS WAF is a managed web application firewall service that monitors and controls HTTP(S) requests forwarded to your protected web application resources. When integrated with API Gateway, it sits between the client and your API, inspecting each request before it reaches your backend. The primary purposes are: (1) filtering out malicious requests such as SQL injection (SQLi) and cross-site scripting (XSS), (2) blocking requests from specific IP addresses or geographic regions, (3) rate limiting to prevent abuse and DDoS attacks, and (4) allowing or blocking requests based on custom conditions like header values or query string parameters.
On the DVA-C02 exam, you must understand that AWS WAF is a regional service (not global like CloudFront) and that it can be associated with API Gateway REST APIs, HTTP APIs, and WebSocket APIs (though WebSocket support is limited). The exam focuses on REST APIs and HTTP APIs. Remember: WAF cannot be directly associated with a private API Gateway endpoint (VPCE) – you must use a Network Load Balancer (NLB) in front of the VPC endpoint or use CloudFront.
How AWS WAF Works Internally
When a client sends an HTTP request to an API Gateway endpoint that has an associated Web ACL (Access Control List), the request passes through the WAF before reaching API Gateway. The WAF evaluates the request against all rules in the Web ACL in the order they are defined. Each rule contains a statement that defines the inspection criteria and an action (Allow, Block, Count, or Challenge). The evaluation process is:
Incoming request arrives at the API Gateway edge endpoint (regional or edge-optimized).
WAF intercepts the request at the regional endpoint (for regional APIs) or at the CloudFront edge location (for edge-optimized APIs).
Rule evaluation: The Web ACL processes rules in order. For each rule, the WAF inspects the request based on the rule's statement. Statements can check:
- Origin country (based on IP address) - IP address (in a set or range) - Presence of a label (from prior WAF rules) - Regex pattern in headers, query strings, body, URI path - Size constraints on request components - SQL injection or XSS patterns (via managed rule groups) - Rate of requests from a source IP (rate-based rule) 4. Action execution: If a rule matches, the configured action is taken. If no rule matches, the default action (allow or block) is applied. 5. Request forwarding or blocking: If allowed, the request proceeds to API Gateway, which then invokes the backend integration. If blocked, WAF returns a 403 Forbidden response immediately.
Key Components: Web ACLs, Rules, Rule Groups, and Managed Rule Groups
Web ACL (Web Access Control List): The primary resource that contains rules and is associated with one or more AWS resources (API Gateway stages, CloudFront distributions, Application Load Balancers). Each Web ACL has a default action (Allow or Block) that applies when no rule matches. You can associate a Web ACL with multiple API Gateway stages, but a stage can only have one Web ACL.
Rules: A rule consists of a statement (inspection criteria), an action (Allow, Block, Count, Challenge), and optional priority. Rules are evaluated in ascending priority order (lowest number first). If a rule matches, the action is taken and subsequent rules are not evaluated (unless the action is Count or Challenge, which may continue).
Rule Groups: A collection of reusable rules. You can create your own rule groups or use AWS Managed Rule Groups. Rule groups are referenced in Web ACLs. When you add a rule group, you must specify an override action (Count or None). Count override allows you to see what the rule would block without actually blocking.
- Managed Rule Groups: Pre-configured rule sets maintained by AWS or AWS Marketplace sellers. Key groups for API Gateway include: - AWSManagedRulesCommonRuleSet: Protects against common threats like SQLi, XSS, LFI, RFI, etc. - AWSManagedRulesSQLiRuleSet: Specifically SQL injection. - AWSManagedRulesKnownBadInputsRuleSet: Blocks known bad patterns. - AWSManagedRulesAmazonIpReputationList: Blocks IPs with poor reputation. - AWSManagedRulesAnonymousIpList: Blocks requests from proxies, Tor nodes, etc. - AWSManagedRulesBotControlRuleSet: Blocks or rate-limits bots (additional cost).
Rate-Based Rules
Rate-based rules are essential for DDoS protection. Instead of inspecting individual request attributes, they track the number of requests from a source IP over a rolling 5-minute window. If the request count exceeds a threshold (e.g., 2000 requests per 5 minutes), the rule triggers an action (Block or Count) for that IP. The action lasts until the rate drops below the threshold. Rate-based rules have a default evaluation window of 5 minutes, and the maximum supported rate is 10,000 requests per 5 minutes for each IP (but can be higher with AWS support).
IP Sets and Regex Pattern Sets
IP Set: A collection of IP addresses and CIDR ranges. You can use IP sets in rules to allow or block traffic based on source IP. IP sets are reusable across Web ACLs.
Regex Pattern Set: A collection of regex patterns. Used in rules to match against request components (headers, query strings, body, URI).
Integration with API Gateway
To associate WAF with API Gateway, you create a Web ACL and then associate it with an API Gateway stage using the AWS Console, CLI, or SDK. The API Gateway must be a REST API or HTTP API (not WebSocket for WAF association). The association is at the stage level, meaning you can have different WAF configurations for dev, test, and prod stages. For edge-optimized APIs, WAF operates at the CloudFront edge location, which provides global DDoS protection. For regional APIs, WAF operates at the regional endpoint.
Configuration Example (CLI)
# Create an IP set for allowed IPs
aws wafv2 create-ip-set --name AllowedIPs --scope REGIONAL --ip-address-version IPV4 --addresses '["203.0.113.0/24"]'
# Create a Web ACL with a rule to block requests not from allowed IPs
aws wafv2 create-web-acl --name MyWebACL --scope REGIONAL --default-action Allow={} --rules '
[
{
"Name": "BlockNonAllowedIPs",
"Priority": 0,
"Statement": {
"NotStatement": {
"Statement": {
"IPSetReferenceStatement": {
"ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/AllowedIPs/abc123"
}
}
}
},
"Action": {
"Block": {}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "BlockNonAllowedIPs"
}
}
]' --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=MyWebACL
# Associate Web ACL with API Gateway stage
aws wafv2 associate-web-acl --web-acl-arn arn:aws:wafv2:us-east-1:123456789012:regional/webacl/MyWebACL/abc123 --resource-arn arn:aws:apigateway:us-east-1::/restapis/abc123/stages/prodVisibility and Monitoring
WAF provides sampled requests (up to 100 requests per rule per 5 minutes), CloudWatch metrics (e.g., AllowedRequests, BlockedRequests, CountedRequests), and detailed logs (if enabled). Logs can be sent to S3, CloudWatch Logs, or Kinesis Firehose. Logs include request metadata, rule actions, and labels. This is critical for debugging false positives.
Interaction with Other Services
CloudFront: WAF can be associated with CloudFront distributions, providing protection at the edge. For edge-optimized API Gateway, WAF is automatically integrated via CloudFront.
AWS Shield: AWS WAF works alongside AWS Shield (Standard and Advanced) for DDoS protection. Shield Standard is free and included; Shield Advanced provides additional DDoS mitigation and cost protection.
AWS Firewall Manager: Centrally manage WAF rules across accounts and resources.
AWS Lambda: You can use Lambda functions as targets for custom WAF rules (e.g., to perform complex checks) via the "Rule action: Custom response" or by using Lambda@Edge with CloudFront.
Important Limits and Defaults
Web ACLs per region per account: 100 (default, can be increased)
Rules per Web ACL: 100 (default)
IP sets per account per region: 50
Regex pattern sets per account per region: 10
Maximum size of a request body that WAF inspects: 8 KB (if you need more, you must use CloudFront with WAF and enable body inspection up to 64 KB)
Rate-based rule evaluation window: 5 minutes (fixed)
Rate limit threshold: Minimum 100 requests per 5 minutes, maximum 10,000 per 5 minutes (default, can be increased with support)
What the Exam Tests
For DVA-C02, you must know:
How to associate WAF with API Gateway (stage-level)
The difference between regional and edge-optimized APIs regarding WAF
The types of rules: IP-based, string matching, regex, SQLi/XSS, rate-based
The actions: Allow, Block, Count, Challenge (Challenge is for CAPTCHA)
How to use managed rule groups
That WAF does NOT support WebSocket APIs directly (but can be used with CloudFront in front)
That WAF is regional, not global (except when used with CloudFront)
The default action for a Web ACL
That rate-based rules use a 5-minute window
That you can use AWS WAF to protect against DDoS at layer 7 (application layer)
Create a Web ACL
First, you define a Web ACL in the AWS WAF service. You must specify the scope: REGIONAL (for API Gateway regional endpoints) or CLOUDFRONT (for edge-optimized APIs via CloudFront). The Web ACL includes a default action (Allow or Block) that applies when no rule matches. You also configure visibility settings like sampling and CloudWatch metrics. Use the AWS Management Console, CLI, or SDK. Example CLI command: aws wafv2 create-web-acl --name MyACL --scope REGIONAL --default-action Allow={} --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=MyACL
Define rules or use managed rule groups
Add rules to the Web ACL. Each rule has a name, priority (integer), statement (the condition to match), and action (Allow, Block, Count, Challenge). You can create custom rules for IP sets, regex patterns, string matching, size constraints, SQL injection, XSS, or rate-based rules. Alternatively, add AWS Managed Rule Groups like AWSManagedRulesCommonRuleSet. When adding a rule group, you can set an override action to Count (to evaluate without blocking) or None. Rules are evaluated in priority order. For rate-based rules, specify the rate limit (requests per 5 minutes) and the action.
Associate Web ACL with API Gateway stage
Once the Web ACL is created, you associate it with a specific API Gateway stage (e.g., prod, dev). This is done using the resource ARN of the stage. For REST APIs, the ARN format is arn:aws:apigateway:region::/restapis/api-id/stages/stage-name. For HTTP APIs, it is arn:aws:apigateway:region::/apis/api-id/stages/stage-name. Use the CLI: aws wafv2 associate-web-acl --web-acl-arn <web-acl-arn> --resource-arn <stage-arn>. A stage can only have one Web ACL, but a Web ACL can be associated with multiple stages (across different APIs).
Test and monitor traffic
After association, test your API by sending requests that should be allowed and blocked. Monitor CloudWatch metrics (AllowedRequests, BlockedRequests, CountedRequests) for the Web ACL. Enable WAF logging to capture detailed request information. Sampled requests (up to 100 per rule per 5 minutes) show you what matched each rule. If you see false positives (legitimate traffic blocked), adjust rules by changing actions to Count, modifying statements, or reordering priorities. Use the Count action to evaluate rules without blocking before enforcing them.
Update rules as needed
Web ACLs can be updated without disassociating from the API Gateway. You can add, remove, or modify rules, change priorities, or update IP sets. Changes take effect within seconds. Use versioning for rule groups if you need to roll back. For managed rule groups, AWS automatically updates them, but you can set a version to pin. Regularly review logs and metrics to fine-tune rules. If you need to block a specific IP that is attacking, you can add an IP set rule with Block action and update the IP set dynamically via automation.
Enterprise Scenario 1: E-commerce API Protection
A large e-commerce company exposes a REST API for product search and checkout. They face constant SQL injection and XSS attempts, as well as bots scraping product data. They deploy AWS WAF with API Gateway by creating a Web ACL with the AWSManagedRulesCommonRuleSet (covers SQLi, XSS, LFI, RFI) and the AWSManagedRulesAmazonIpReputationList. They also add a custom rate-based rule limiting each IP to 500 requests per 5 minutes to prevent scraping. The Web ACL is associated with the prod stage of the API. They enable logging to S3 for compliance and analysis. Initially, they set managed rules to Count to identify false positives. After a week, they switch to Block. They also use IP sets to allow their internal monitoring tools. The result: attack attempts drop by 95%, and false positives are minimal.
Enterprise Scenario 2: Financial Services Geo-Blocking
A fintech company provides a REST API for account management. Regulatory requirements mandate that only users from certain countries can access the API. They use AWS WAF with a geographic match rule to allow traffic only from the US and Canada. They create an IP set for their corporate VPN ranges and allow those. They also use the AWSManagedRulesKnownBadInputsRuleSet to block common attack patterns. The Web ACL is associated with the API Gateway stage. They use CloudWatch metrics to monitor blocked requests from other countries. When a legitimate user from a blocked country contacts support, they can add their IP to an allow list via an IP set update. This geo-blocking is lightweight and avoids code changes.
Scenario 3: Startup with DDoS Mitigation
A startup launches a new mobile app backed by an HTTP API on API Gateway. During launch, they experience a layer 7 DDoS attack. They quickly create a rate-based rule limiting each IP to 100 requests per 5 minutes and block traffic from known bad IPs using the AmazonIpReputationList managed rule group. They also enable AWS Shield Advanced for additional DDoS protection (costly but necessary). The Web ACL is associated with the API Gateway stage. They monitor the attack in real-time via CloudWatch and adjust the rate limit as needed. Post-attack, they add custom rules to block specific user agents and headers used by the attackers.
Common misconfiguration: Not setting a default action correctly. If the default action is Allow, a rule with Block action must be explicitly created to block traffic. If no rule matches, the request is allowed. Many beginners forget to set a default action of Block for deny-by-default security. Also, forgetting to enable logging makes troubleshooting false positives difficult.
What DVA-C02 tests on this topic
Under objective 2.4 (Security), the exam expects you to know how to use AWS WAF to protect API Gateway APIs. Specific points:
Association: WAF is associated at the API Gateway stage level, not the API level.
Scope: For edge-optimized APIs, WAF uses CloudFront scope; for regional APIs, use REGIONAL scope.
Actions: Allow, Block, Count, Challenge (CAPTCHA). Challenge is not commonly tested but appears in some questions.
Managed rule groups: Know the names and purposes of common ones: CommonRuleSet, SQLiRuleSet, KnownBadInputs, AmazonIpReputationList, AnonymousIpList.
Rate-based rules: 5-minute window, threshold in requests per 5 minutes, action applies to source IP.
Default action: Allow or Block.
WAF does not support WebSocket APIs directly (but can be used with CloudFront in front).
WAF is a regional service (except when associated with CloudFront).
Common wrong answers and why 1. "Use AWS Shield Advanced instead of WAF" – Shield Advanced provides DDoS protection at layer 3/4, but WAF is needed for layer 7 inspection. The exam may ask for both. 2. "Associate WAF at the API level, not stage" – Incorrect; it's stage-level. 3. "WAF can be associated with any API Gateway endpoint type" – False; private APIs cannot have WAF directly; you need NLB or CloudFront. 4. "Rate-based rules use a 1-minute window" – Wrong; it's 5 minutes. 5. "WAF rules are evaluated in random order" – False; they are evaluated in priority order (ascending).
Numbers and terms to memorize - 8 KB max request body size for WAF inspection (without CloudFront). - 5-minute evaluation window for rate-based rules. - Rate limit default max: 10,000 requests per 5 minutes per IP (can be increased). - 100 Web ACLs per region per account (default). - 100 rules per Web ACL (default). - 50 IP sets per account per region. - 10 regex pattern sets per account per region.
Edge cases - If you need to inspect request bodies larger than 8 KB, you must use CloudFront with WAF and enable body inspection (up to 64 KB). - WAF does not support custom responses for blocked requests by default (you can use custom response bodies but only in certain cases). - When using AWS Managed Rule Groups, you can override the action to Count to test before blocking. - WAF integration with API Gateway is not available for WebSocket APIs; you must use CloudFront in front.
How to eliminate wrong answers - If the question mentions "rate limiting" and the answer says "use WAF rate-based rule," that is correct. If it says "use API Gateway throttling," that is also correct (but different). Know the difference: API Gateway throttling is per-account or per-stage, not per-IP; WAF rate-based is per-IP. - If the question asks for "SQL injection protection," the correct answer is WAF with managed rule group or custom SQLi rule. Do not choose "use Lambda authorizer" – that is for authentication, not injection filtering. - If the question is about "blocking traffic from specific countries," the correct answer is WAF with geographic match condition. Do not choose "use API Gateway resource policy" – resource policies are for IAM-based access control, not geo-blocking.
AWS WAF is associated with API Gateway at the stage level, not the API level.
For regional APIs, use REGIONAL scope; for edge-optimized, use CLOUDFRONT scope.
Rate-based rules use a rolling 5-minute window to track requests per source IP.
Default maximum request body size inspected by WAF is 8 KB; use CloudFront to inspect up to 64 KB.
Managed rule groups include CommonRuleSet, SQLiRuleSet, KnownBadInputs, AmazonIpReputationList, and AnonymousIpList.
WAF actions: Allow, Block, Count, Challenge (CAPTCHA).
WAF cannot be directly associated with private API Gateway endpoints (use NLB or CloudFront).
You can override managed rule group actions to Count for testing before blocking.
Web ACLs have a default action (Allow or Block) that applies when no rule matches.
WAF provides sampled requests, CloudWatch metrics, and detailed logs for monitoring.
IP sets and regex pattern sets are reusable across Web ACLs.
WAF is a regional service; it becomes global only when associated with CloudFront.
These come up on the exam all the time. Here's how to tell them apart.
AWS WAF with API Gateway
Inspects request content (SQLi, XSS, etc.)
Rate limits per source IP address
Blocks or counts based on IP reputation
Geographic blocking (country-level)
Works at layer 7 (application layer)
API Gateway Throttling (Usage Plans)
Only controls request rate per API key or per stage
Does not inspect request content
Cannot block by IP or geography
Throttles based on tokens (burst and steady-state)
Works at API Gateway level, not per client IP
Mistake
AWS WAF is a global service like CloudFront.
Correct
AWS WAF is a regional service. When used with CloudFront, it is deployed globally at edge locations, but the service itself is regional. For API Gateway regional endpoints, WAF operates in the same region as the API.
Mistake
You can associate a Web ACL with a private API Gateway endpoint.
Correct
WAF cannot be directly associated with a private API Gateway (VPC endpoint). You must place a Network Load Balancer (NLB) in front of the VPC endpoint or use CloudFront with an origin access identity (OAI) to apply WAF.
Mistake
Rate-based rules reset every minute.
Correct
Rate-based rules use a rolling 5-minute window. The count is continuously updated, and the action is applied as long as the rate exceeds the threshold. It does not reset at fixed intervals.
Mistake
WAF can inspect request bodies up to 64 KB by default.
Correct
By default, WAF inspects only the first 8 KB of the request body. To inspect up to 64 KB, you must use CloudFront with WAF and enable body inspection via the CloudFront distribution settings.
Mistake
AWS WAF Managed Rule Groups are updated automatically and you cannot control versions.
Correct
You can pin a specific version of a managed rule group (e.g., Version_1.0) to avoid unexpected changes. If you don't pin, AWS updates the rule group automatically. Pinning is recommended for production.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
Yes, AWS WAF supports both REST APIs and HTTP APIs. You associate a Web ACL with a specific stage of the API. For HTTP APIs, the resource ARN format is arn:aws:apigateway:region::/apis/api-id/stages/stage-name. The same rules and managed rule groups apply. Note that WAF does not support WebSocket APIs directly; you need to use CloudFront in front of the WebSocket API and associate WAF with the CloudFront distribution.
AWS WAF is a web application firewall that inspects HTTP/HTTPS requests at layer 7 to block common attacks like SQL injection and XSS. AWS Shield is a DDoS protection service. Shield Standard is free and protects against layer 3/4 attacks. Shield Advanced provides additional protection, cost protection against scaling, and access to a DDoS response team. They are complementary: you can use WAF with Shield for comprehensive protection.
You can use the Count action for rules. When a rule is set to Count, WAF evaluates the request but does not block it. It increments the Count metric and logs the match. This allows you to see how many requests would be blocked without affecting traffic. You can also use sampled requests and logs to analyze matches. After confirming the rule works correctly, change the action to Block.
Yes, you can create custom rules that inspect query string parameters using string matching or regex. For example, to block requests where the query string contains 'admin', you can use a rule with a statement that checks the query string. You can also use size constraint rules to block oversized query strings. Managed rule groups like CommonRuleSet already protect against common injection patterns in query strings.
When the request rate from a source IP exceeds the threshold in the rolling 5-minute window, the rule action (typically Block) is applied to subsequent requests from that IP. The action continues until the rate drops below the threshold. The IP is not permanently blocked; it is only blocked as long as the rate is high. This helps mitigate DDoS attacks while allowing legitimate traffic after the attack subsides.
Yes, you can configure custom response bodies for Block actions. When you create a rule with Block action, you can specify a custom response body (e.g., an HTML page) and a response code (e.g., 403). The custom response is returned to the client instead of the default 403 Forbidden. This is useful for branding or providing user-friendly error messages.
You can automate IP set updates using AWS Lambda and API calls. For example, when a CloudWatch alarm triggers due to high error rates, a Lambda function can add the attacker's IP to an IP set that is referenced by a WAF rule with Block action. The update takes effect within seconds. This is commonly used for auto-mitigation of attacks.
You've just covered AWS WAF for API Gateway — now see how well it sticks with free DVA-C02 practice questions. Full explanations included, no account needed.
Done with this chapter?