With this guide you will not become an AWS WAF expert, but will get a bit of taste about its capabilities.
1. Introduction and Overview of AWS WAF
AWS Web Application Firewall (WAF) is a managed security service designed to help protect your web applications or APIs from common web exploits and bots. AWS WAF lets you create rules to monitor (count), block, or allow traffic based on criteria such as:
- IP addresses
- HTTP headers
- URI paths
- Request size
- SQL injection attempts
- Cross-Site Scripting (XSS) patterns
- Request rate (rate-based rules)
Additionally, when you use AWS WAF, you automatically get the protections of AWS Shield Standard at no additional cost. AWS Shield Standard is a built-in DDoS protection service for AWS resources (including CloudFront and Route 53) that mitigates common network and transport layer attacks. Together, AWS WAF and AWS Shield Standard provide a layered defense approach: WAF focuses on Layer 7 (application layer) threats, while Shield Standard covers volumetric and SYN flood-type attacks (Layers 3 and 4).
1.1 Resources Protected by AWS WAF
You can attach AWS WAF to the following AWS resources:
- Amazon CloudFront (for global distribution and caching)
- Amazon API Gateway (REST APIs)
- Application Load Balancer (ALB)
- AWS AppSync (GraphQL APIs)
- Amazon Cognito user pools
- AWS App Runner service
- AWS Verified Access instance
Additionally, when you use CloudFront with AWS WAF, you can protect any external or internal origin behind CloudFront, including on-premises servers or third-party cloud environments. CloudFront acts as a secure reverse proxy, letting you apply WAF inspection rules to all inbound requests before they reach your origin, regardless of whether that origin is hosted inside or outside of AWS.
Attaching WAF to these resources allows you to inspect and filter incoming requests based on rules you define (custom rules) or rules you enable from AWS Managed Rule Sets, all while benefiting from the baseline DDoS protections of AWS Shield Standard.
2. Applying AWS WAF: CloudFront vs. Other Resources
2.1 AWS WAF with CloudFront
When integrated with CloudFront, AWS WAF inspects and can block traffic at the edge, before it reaches your origin. Key advantages include:
- Global Edge Presence: Requests are processed at CloudFront edge locations.
- CDN and Caching: CloudFront’s CDN reduces latency and offloads your origin by caching content.
- Secure Reverse Proxy: By placing CloudFront in front of your application (whether it’s hosted within AWS, on-premises, or another cloud), you effectively use it as a secure reverse proxy that can filter traffic globally.
AWS Shield Standard: Automatically protects CloudFront distributions (and other supported AWS resources) against most common DDoS attacks at no extra cost.
If your application needs more nuanced logic than WAF alone can provide, you can extend functionality using:CloudFront Functions: Lightweight JavaScript functions for short-running tasks (up to 1ms) like inspecting headers or rewriting URIs.
Lambda@Edge: A more robust solution if you need to read or modify request/response bodies, implement complex authentication flows, or handle sophisticated transformations.
_Important: If AWS WAF blocks a request at the edge, CloudFront Functions and Lambda@Edge will not trigger for that request.
_
2.2 AWS WAF with Regional Services
AWS WAF can also operate at a regional level by attaching to:
- Application Load Balancer (ALB)
- Amazon API Gateway (REST APIs)
- AWS AppSync (GraphQL APIs)
- Amazon Cognito user pools
- AWS App Runner service
- AWS Verified Access instance
This approach is suitable for applications or microservices that do not require global edge distribution or caching. Key differences from the CloudFront approach include:
1. Latency and Caching
- CloudFront + WAF: Security measures at the edge, lower latency, potential cost savings from caching.
- Regional Services + WAF: Traffic is inspected regionally without inherent CDN caching.
2. Scope and Customization
- CloudFront can use CloudFront Functions or Lambda@Edge for advanced transformations.
- Regional Services can still use custom or managed WAF rules, but do not benefit from global caching.
3. Protecting External Origins
- CloudFront + WAF can protect non-AWS origins by pointing the distribution to external servers.
- Regional services typically secure traffic within AWS unless you design a specific pattern.
3. AWS Managed Rules
AWS Managed Rules are pre-configured, continuously updated rule sets provided by AWS to protect against a wide range of threats. By enabling these managed rules in your AWS WAF, you can quickly cover many common web attacks without having to define every pattern or behavior manually.
3.1 Coverage for OWASP Top 10
Many AWS Managed Rules are designed to help address OWASP Top 10 vulnerabilities, such as:
Injection (SQLi, NoSQL, Command Injection)
- The AWSManagedRulesSQLiRuleSet identifies and blocks SQL injection attempts.
- Common malicious payloads and known injection vectors are covered.
Broken Authentication and Session Management
- Combined with Account Takeover Prevention (ATP), WAF can detect brute force or credential stuffing attempts on login endpoints.
Sensitive Data Exposure
- Managed Rules can flag suspicious payloads or unusual request patterns that might indicate data exfiltration (in conjunction with rate-based rules and SSL/TLS).
XML External Entities (XXE)
- Certain AWS Managed Rule Groups include checks for XML-based threats and malicious entity references.
Broken Access Control
- While some aspects of access control are application-specific, AWS Managed Rules can detect attempts to bypass security controls using known exploit patterns, suspicious HTTP methods, or path tampering.
Security Misconfiguration
- Common Rule Sets automatically update to address vulnerabilities in common frameworks and platforms, reducing the risk of misconfiguration exposure.
Cross-Site Scripting (XSS)
- AWSManagedRulesCommonRuleSet includes signatures for detecting malicious scripts and XSS payloads.
Insecure Deserialization
- Some advanced Managed Rule Groups check for known malicious serialization formats and exploit payloads.
Using Components with Known Vulnerabilities
- AWS regularly updates the Managed Rule Sets to address newly disclosed CVEs, helping you keep pace with emerging threats.
Insufficient Logging and Monitoring
- Although logging itself is not a “rule,” AWS WAF integrates with S3, CloudWatch, and Kinesis Firehose for monitoring. Suspicious requests are clearly tagged and logged, aiding your threat detection strategy.
3.2 Examples of AWS Managed Rule Sets
- AWSManagedRulesCommonRuleSet: Covers a broad range of general vulnerabilities, including XSS, HTTP request smuggling, and some injection signatures.
- AWSManagedRulesSQLiRuleSet: Specifically targets SQL injection patterns.
- AWSManagedRulesAmazonIpReputationList: Blocks or labels requests from known malicious IP addresses or botnets.
- AWSManagedRulesLinuxRuleSet (or similar specialized sets): Target vulnerabilities specific to Linux-based systems.
3.3 Complementing Managed Rules with Custom Logic
While AWS Managed Rules provide excellent baseline coverage, you should monitor traffic in “Count” mode initially to identify potential false positives and tune your rules. You can then add:
- Custom rules for application-specific logic (e.g., blocking certain user agents or disallowed query parameters).
- Rate-based rules to mitigate brute force or scraping attempts.
- Account Takeover Prevention (ATP) for deeper login endpoint protection.
This layered approach (managed rules plus custom refinements) helps ensure robust, OWASP-aligned protection without sacrificing application availability.
4. AWS WAF Fraud Control – Account Takeover Prevention (ATP)
4.1 Overview of ATP
Account Takeover Prevention (ATP) is part of AWS WAF Fraud Control, designed to detect and mitigate unauthorized login attempts:
- Analyzes Login Attempts: Monitors login traffic to identify suspicious behavior (credential stuffing, brute force).
- Risk-Based Scoring: ATP assigns risk scores to login attempts based on factors like repeated login failures or IP reputation.
- Integration with WAF: You can create WAF rules to allow, count, block, or require CAPTCHA on requests flagged by ATP.
By spotting anomalies in login patterns, ATP helps prevent account takeover incidents before they escalate.
4.2 Benefits of Using Email Addresses as Usernames with ATP
When combining ATP with email-based usernames (your application should use usernames in email format), you gain several security and operational advantages:
- Easier Parsing and Validation: An email format (username@domain.com) is consistent, enabling simpler checks for malicious or disposable domains.
- Domain Intelligence: ATP or custom WAF rules can label or block logins from suspicious or disposable email domains.
- Reduced Guesswork: Attackers must guess valid email addresses, which can be less trivial than typical username formats like admin or test.
- Improved Logging: Email addresses provide a clearly identifiable username in the logs for investigating suspicious activity.
- Easier MFA and Recovery: Users often prefer logging in with an email address, simplifying password resets and integrating MFA flows.
- Leverage Compromised Credentials Databases:
- AWS obtains threat intelligence including email/password pairs from public data breaches to help detect credential stuffing or attempts using known compromised credentials.
- Because users commonly reuse email addresses across different services, ATP can cross-reference these compromised credential sets more effectively when your primary username field is an email.
- This synergy helps AWS WAF quickly flag suspicious login attempts, especially when an attacker attempts known leaked email/password pairs from security breaches.
5. Best Practices and Well-Architected Approach for Building Your Rule Base
5.1 Start with Managed Rules, Then Layer Custom Rules
- Baseline Protections (Managed Rules): Quickly address common threats (SQLi, XSS, bad bots) by enabling relevant AWS Managed Rule Sets.
- Custom Rules: Tailor rules to your application’s business logic (e.g., block suspicious headers, limit request sizes, or restrict certain paths).
- Rate-Based Rules: Mitigate DDoS or brute-force attacks by capping requests from a single IP address over a specified period.
- JS Challenge and Captcha: Implement JS challenge and captcha in your application in order to reduce DDoS by automated browsers, CLI and other tools.
5.2 “Count” Mode + Labels, Then Block
A major best practice is to start all rules in “Count” mode and add labels:
- Configure each rule to Count rather than block initially.
- Assign a label to requests that match the rule (e.g., SuspiciousSQLi, XSSAttempt).
- Observe logs to verify these matches are legitimate threats or anomalies.
- Implement a final, catch-all blocking rule that blocks requests carrying labels deemed malicious.
This approach helps reduce false positives while ensuring you have visibility into what would be blocked before actively cutting off traffic as well as centralized control over custom block page headers and responses
5.3 Extend with CloudFront Functions or Lambda@Edge
In cases where AWS WAF rules do not cover a specific use case or you need more dynamic logic, consider:
- CloudFront Functions: Lightweight JavaScript for short-running tasks (up to 1 ms) like inspecting headers, rewriting URIs, or adding custom headers.
- Lambda@Edge: A more robust solution for reading/modifying request or response bodies, implementing complex authentication flows, or dynamic transformations.
Note: If WAF blocks a request, CloudFront Functions or Lambda@Edge will not run for that request.
5.4 Align with AWS Well-Architected Security Pillar
Design your WAF rule base according to AWS’s Well-Architected Security Pillar:
- Identification: Label and log events to understand potential threats.
- Proactive Protection: Use a combination of managed and custom rules.
- Least Privilege: Only allow known safe patterns or domains.
- Automation: Deploy and manage WAF using Infrastructure as Code (CloudFormation, Terraform) for consistency and repeatability.
6. Rule Groups and Rule Labels
6.1 Rule Groups
A Rule Group is a container for one or more WAF rules:
- AWS Managed Rule Groups: Quick to enable, provide coverage for broad classes of attacks.
- Custom Rule Groups: Let you organize your own rules by function (e.g., IP restrictions, user-agent blocks, country blocks).
6.2 Rule Labels
When a request matches a rule, WAF can attach labels for tracking or later decision-making. For example:
- SQLiDetected
- BadBotTraffic
- DisallowedCountry
You can create a final rule that blocks requests carrying specific labels. Labels also appear in WAF logs, helping you analyze and correlate different rule matches.
7. Custom Responses in WAF Rule Actions
AWS WAF supports custom responses for Block actions. Instead of returning a generic 403 Forbidden, you can define:
- Custom HTTP Status Code (e.g., 403, 404, 502, etc.)
- Custom Headers (e.g., to convey an error reason to the client)
- Custom HTML or text Body for the response This feature is useful when you want to provide a branded or instructive error page, or add extra troubleshooting information for the user. Since the request is already blocked, no further edge functions (CloudFront Functions or Lambda@Edge) will execute for that request.
Example: You might choose to return a 403 status with a short HTML body:
{
"Name": "MyWebACL",
"Scope": "CLOUDFRONT",
"DefaultAction": { "Allow": {} },
"Rules": [
{
"Name": "BlockWithCustomResponse",
"Priority": 1,
"Statement": {
"ByteMatchStatement": {
"FieldToMatch": { "SingleHeader": { "Name": "x-bad-header" } },
"PositionalConstraint": "EXACTLY",
"SearchString": "bad-value",
"TextTransformations": [{ "Priority": 0, "Type": "NONE" }]
}
},
"Action": {
"Block": {
"CustomResponse": {
"ResponseCode": 403,
"CustomResponseBodyKey": "CustomHTMLResponse",
"ResponseHeaders": [
{ "Name": "X-Custom-Error", "Value": "BlockedByWAF" }
]
}
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "BlockWithCustomResponseRule"
}
}
],
"CustomResponseBodies": {
"CustomHTMLResponse": {
"ContentType": "TEXT_HTML",
"Content": "<html><body><h1>Access Denied</h1><p>Your request has been blocked.</p></body></html>"
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "MyACLMetric"
}
}
In this example, any request including a header x-bad-header: bad-value is blocked, returning a 403 code with a custom HTML body.
8. Limitations
While AWS WAF is powerful and flexible, you should be aware of some important constraints and limitations:
Rule Capacity (WCU – WAF Capacity Units)
- Each rule (or statement within a rule) consumes a certain number of WCUs based on its complexity. For example, ByteMatchStatement or IP match conditions generally have lower WCU usage, while Regex match statements and complex logical operators can use more.
- There is a maximum WCU limit for each Web ACL. If your rules exceed that limit, you cannot add them all to the same Web ACL. You may need to simplify your rules or optimize your rule groups.
- Monitor your rule WCU usage (in the AWS console or via the CLI) to ensure you stay within allowed capacity.
Regex Complexity
- Very complex regex patterns can quickly use up available WCUs. Simplify your patterns or break them into multiple statements where possible.
Logging Latency
- WAF logs are almost real time when using Cloudwatch and typically appear with a short delay in S3 or Kinesis
Regional vs. Global
- WAF on CloudFront is global; on ALB, API Gateway, etc., it’s regional.
Cost
- Each rule, managed rule group, and request passing through WAF contributes to your monthly bill. Monitor usage carefully.
Inspection Header Size
- WAF regional inspects up to a certain size for request headers/body (e.g., first 16 KB).
- WAF Global (Cloudfront) supports up to 64 KB headers/body inspection
Requests exceeding this limit may not be fully inspected.
Blocking Halts Edge Functions
- If a request is blocked by WAF, CloudFront Functions or Lambda@Edge will not run for that request.
9. Practical Information about Working with Labels
- Defining Labels: Specify labels in your WAF rule actions (console or CLI).
- Combining Labels: Multiple rules can label the same request.
- Match on Labels: A final rule can check if a request has any suspicious labels and block it.
- Debugging: Inspect WAF logs to see which labels are assigned and confirm the accuracy of your rules.
10. Protecting Resources Outside AWS Using CloudFront
One advantage of CloudFront + WAF is the ability to protect external (non-AWS) origins:
- Create a CloudFront distribution that points to your on-premises or third-party cloud origin.
- Attach a WAF Web ACL to that distribution.
- Enable caching for static or cacheable content to reduce load on the external origin.
Secure Reverse Proxy: CloudFront, acting as a secure reverse proxy, inspects all traffic with WAF at the edge before forwarding it to your external servers.
This setup provides global edge security and performance benefits even if your origin is not hosted on AWS.
11. AWS Managed Protections for OWASP Top 10
The OWASP Top 10 is a standard awareness document outlining the most critical web application security risks. AWS WAF addresses several OWASP Top 10 vulnerabilities via AWS Managed Rules and additional features:
Injection
(SQLi, NoSQL, Command Injection)
AWSManagedRulesSQLiRuleSet helps block SQL injection attempts.
Custom rules can detect command injection patterns.
Broken Authentication and Session Management
ATP helps mitigate brute force or credential stuffing.
Rate-based rules can address repeated login attempts.
Sensitive Data Exposure
WAF can block suspicious payloads that may indicate data exfiltration.
Combine with SSL/TLS for encrypted data in transit.
XML External Entities (XXE)
- Custom or third-party rules detect malicious XML patterns.
Broken Access Control
- WAF custom rules can enforce strict path or header-based controls.
- Labels help track role-based or token-based access attempts.
Security Misconfiguration
- AWS Managed Rule Sets automatically update to address new vulnerabilities.
- Custom rules detect unusual HTTP methods or suspicious headers.
Cross-Site Scripting (XSS)
AWSManagedRulesCommonRuleSet includes patterns for typical XSS vectors.
Insecure Deserialization
- Advanced rule sets can detect malicious serialization formats.
- Using Components with Known Vulnerabilities
- Regular updates to AWS Managed Rules help protect against newly disclosed CVEs.
Insufficient Logging and Monitoring
- WAF logging (to S3, CloudWatch, or Kinesis) provides robust, centralized monitoring.
- Combine with Athena or OpenSearch for advanced log analysis.
12. Pricing Model
12.1 AWS WAF Pricing
AWS WAF pricing typically includes four main components:
Web ACLs
- You pay a monthly charge for each web ACL that you create (e.g., around USD $5 per month per web ACL, depending on the region).
- Rules
- Each rule (custom or managed) in your web ACL adds a small monthly cost - often USD $1 per rule per month.
Rule Groups
- Enabling an AWS Managed Rule Group or a third-party rule group from AWS Marketplace can incur a monthly subscription (for the group itself), plus the cost for each rule inside the group if applicable.
Request Volume
- You pay for each million web requests inspected by AWS WAF. The typical rate is around USD $0.60–$1.00 per million requests (exact cost varies by region).
Important:
- Prices vary by AWS Region.
- Third-party managed rule groups may have higher subscription costs than AWS-managed rule sets.
- Overuse of large or complex rules can drive up monthly costs. Monitor usage carefully.
12.2 CloudFront Pricing
Amazon CloudFront has its own separate billing model. Main cost factors include:
Data Transfer Out
You pay for data transferred from CloudFront edge locations to your users. Rates vary by geographic region and volume.
Requests
You pay for HTTPS/HTTP requests served by CloudFront. Pricing can be on the order of USD $0.01 per 10,000 requests in many regions.
CloudFront Functions / Lambda@Edge
- CloudFront Functions: Billed by the number of function invocations (e.g., $0.10 per 1 million invocations).
- Lambda@Edge: Billed by the number of requests plus compute time (GB-seconds).
Optimization Tip: Caching effectively in CloudFront can drastically reduce the number of origin fetches, which lowers data transfer costs and can also reduce Lambda@Edge invocations. However, caching does not reduce the number of WAF inspections, as every client request that hits CloudFront is still processed by WAF (unless previously blocked or allowed by another mechanism).
13. AWS WAF vs. Incapsula (Imperva) vs. Cloudflare vs. AWS WAF with CloudFront
Below is a high-level comparison table, including a separate row for AWS WAF with CloudFront:
Key Takeaways:
- AWS WAF (Regional Services): Ideal for apps that don’t require global edge caching or are purely regional.
- AWS WAF with CloudFront: Global edge distribution, built-in CDN and caching, extends protection to external origins. Additionally, combining AWS WAF with CloudFront Functions and Lambda@Edge provides extended customization flexibility, allowing deep control over each and every HTTP parameter within the session, from rewriting headers to injecting custom logic for advanced routing or security checks.
- Incapsula & Cloudflare: Third-party global security/CDN solutions with their own pricing, feature sets, and potential integration complexities.
14. Conclusion
AWS WAF is a powerful, flexible solution for safeguarding both AWS-hosted and external web applications. With managed rules, custom rules, labels, and a layered “count then block” strategy, you can tailor your defenses while minimizing false positives. Integrating CloudFront adds global edge coverage, caching, and the option to use CloudFront Functions or Lambda@Edge for advanced logic.
Furthermore, AWS Shield Standard is included at no additional cost, protecting your AWS resources from common network and transport-layer DDoS attacks, while WAF focuses on application-layer threats.
Account Takeover Prevention (ATP) further boosts security by analyzing login attempts for suspicious behavior, making it especially effective when users log in with email addresses. This consistency aids in detection and labeling of potentially malicious traffic and benefits from AWS’s threat intelligence on compromised credentials from public data breaches.
Key Implementation Steps
- Enable AWS Managed Rules for immediate protection against common attacks, including OWASP Top 10 vulnerabilities.
- Add Custom Rules to address your application’s unique security needs.
- Leverage Rule Labels and test in “Count” mode before enforcing blocks.
- Adopt a Final Blocking Rule that triggers on suspicious labels (e.g., SQLiDetected, ATPHighRisk).
- Use CloudFront as a secure reverse proxy to protect both AWS and external origins, taking advantage of edge caching.
- Implement ATP to mitigate unauthorized login attempts, benefiting from standardized email-based usernames and compromised credential checks.
- Monitor Limitations such as WAF Capacity Units (WCU), inspection header size, and overall request volume to ensure your rules function effectively at scale.
- Use Custom Responses in block actions for branded or instructive error pages.
- Leverage AWS Shield Standard for built-in DDoS protection, covering the network and transport layers at no extra cost.
- Manage Costs by monitoring the number of web ACLs, rules, and request volume. Optimize with CloudFront caching to reduce origin fetches.
- Regularly Review OWASP Top 10 and confirm your AWS Managed Rule Sets (and custom rules) align with emerging vulnerabilities. By following these best practices and leveraging AWS WAF’s advanced features, you can establish a well-architected, scalable, and cost-effective defense against evolving threats- both within and beyond the AWS ecosystem.
Top comments (0)