AWS WAF Guide: Secure Your Web Apps Effectively | Quantum Bits
Insight
AWS WAF Implementation: A Practical Guide to Securing AWS Web Applications
Tech TeamNovember 16, 2026
AWS WAF Implementation: A Practical Guide to Securing AWS Web Applications
Qbits
AWS WAF Implementation: A Practical Guide to Securing AWS Web Applications
A product team ships a customer dashboard, a subscription portal, and a public API on AWS. Traffic grows, which is good news. Then the logs start showing odd requests: query strings full of SQL fragments, form fields carrying <script> tags, thousands of login attempts per minute from a handful of addresses, and API clients that never behave like real users.
None of this is exotic. Public web applications attract automated probing the moment they're reachable. Security groups and network ACLs control which ports and addresses can connect, but they don't read the HTTP request itself. A request to port 443 that carries an injection payload looks the same to a network firewall as a legitimate one.
That gap is where AWS WAF implementation comes in. AWS WAF inspects HTTP and HTTPS requests at the application layer and applies rules you define. In this guide we use a hypothetical SaaS scenario to walk through the architecture, a native Terraform implementation, rule tuning, and monitoring, and we're candid about what a web application firewall can and can't do.
Understanding AWS WAF
AWS WAF is a managed web application firewall. It evaluates incoming web requests against rules and decides what to do with each one.
Key concepts:
Web ACL (Web Access Control List): the container for your protections. It holds an ordered list of rules, a default action, and visibility settings. You associate a Web ACL with a protected resource.
Rules and rule groups: a rule contains a statement (for example, "the URI starts with /admin" or "this IP sent more than N requests") and an action. Rule groups bundle rules for reuse.
AWS Managed Rule Groups: rule groups maintained by AWS, covering common categories of web threats. You enable them rather than writing the logic yourself.
Actions:Allow, Block, and Count. Count records a match without blocking, which makes it the safe way to test a rule against real traffic.
Rate-based rules: count requests per aggregation key (often the client IP) over a time window and act when a threshold is exceeded.
About the author
Tech Team
Tech Team covers the latest in technology, offering helpful articles, practical guides, and expert insights to keep readers informed about digital trends, tools, and innovation.
Product strategyCloud architectureDevOps deliverySoftware support
Send us a message
Fill out the form below and we'll get back to you soon.
Supported resources: Amazon CloudFront distributions, Application Load Balancers, Amazon API Gateway REST APIs, AWS AppSync, and Amazon Cognito user pools, among others.
How it differs from a traditional network firewall. Network firewalls and security groups work mainly at layers 3 and 4, filtering by IP, port, and protocol. AWS WAF works at layer 7, inspecting the content of HTTP requests: URIs, headers, query strings, cookies, and bodies. You need both. They answer different questions.
Problem Scenario: A Growing SaaS Platform Under Pressure
This is a hypothetical scenario created for demonstration. It isn't an actual Qbits customer case, and no real traffic figures are used.
Imagine LedgerLane, a SaaS platform offering customer dashboards, account management, subscriptions, and public APIs. Its AWS environment includes:
Amazon EC2 instances running the application
An Application Load Balancer distributing traffic
Amazon CloudFront for content delivery
Amazon RDS for application data
An Amazon VPC for network isolation
The security team notices four patterns:
SQL injection attempts. Manipulated parameters designed to alter database queries.
Cross-site scripting (XSS). Script content submitted through inputs, hoping it runs in another user's browser.
Automated bot traffic. Scripted clients hammering login endpoints and public APIs.
Excessive request rates. A few IP addresses generating unusual volumes that strain the application.
Left unaddressed, these can mean unauthorized access attempts, exposure of sensitive data if an application flaw exists, extra load on application servers and the database, degraded service, higher infrastructure costs, and a worse customer experience.
Proposed Solution: Put AWS WAF in Front of the Application
The plan is to inspect requests at the edge, before they reach the load balancer and application. The security controls:
ControlPurposeAWS Managed Rules: Common Rule SetBroad protection against common web exploits, including cross-site scripting patterns and oversized or malformed requestsAWS Managed Rules: SQL Database Rule SetInspects requests for SQL injection patternsAWS Managed Rules: Known Bad Inputs Rule SetMatches request patterns associated with exploiting known vulnerabilitiesRate-based rulesLimits excessive request volumes per clientCustom rulesApplication-specific protection, such as tighter limits on login and restricted admin pathsBot Control (optional)Additional bot management through the AWS WAF Bot Control managed rule group, which carries extra cost
An important caveat: AWS WAF is an additional layer, not a guarantee. It does not automatically prevent every SQL injection, XSS, DDoS, or bot request. Managed rules catch known patterns; novel or heavily obfuscated attacks can slip through, and legitimate requests can occasionally be flagged. WAF must complement secure coding (parameterized queries, output encoding, input validation), strong authentication and authorization, patching, and other AWS security controls.
Proposed Architecture
Topology chosen for this article: CloudFront is the public entry point, and a CloudFront-scoped Web ACL is attached to the distribution. The ALB is restricted so it only accepts traffic coming from CloudFront. At the end of the Terraform section we show the variation for an ALB-only setup using a regional Web ACL.
CloudFront-scoped Web ACLs (scope = "CLOUDFRONT") are global resources that must be created and managed in the US East (N. Virginia), us-east-1 region, regardless of where your application runs. You attach them via the CloudFront distribution's web_acl_id, not through an association resource.
Regional Web ACLs (scope = "REGIONAL") protect ALBs, API Gateway REST API stages, and similar resources, and must be in the same region as the protected resource. You attach them with a Web ACL association.
A single Web ACL has one scope. You can't attach one Web ACL to both a CloudFront distribution and an ALB. If you want WAF at both layers, create two Web ACLs, one per scope.
If CloudFront fronts the ALB, attackers can bypass the edge by calling the ALB directly. Restrict the ALB to CloudFront (shown below), or the WAF won't see that traffic.
Prerequisites
An AWS account with a defined environment for the work.
IAM permissions to manage WAFv2, CloudFront, CloudWatch, SNS, and related resources. Use least privilege rather than administrator access.
Terraform (1.5 or later is a sensible baseline), to define the setup as reviewable code.
AWS CLI, configured with credentials, for authentication and for verifying results.
The official AWS Terraform provider (hashicorp/aws, version 5.x here).
An existing CloudFront distribution and ALB, since this guide adds protection to existing infrastructure.
The existing application stack (EC2, RDS, VPC).
Basic Terraform and AWS networking knowledge.
Terraform Implementation: Configuring AWS WAF
We use native aws_wafv2_* resources, with no third-party module. A suggested layout:
waf/
├── versions.tf # Terraform and provider configuration
├── variables.tf
├── waf.tf # Web ACL, IP sets, rules
├── logging.tf # Logging configuration
└── alarms.tf # CloudWatch alarm and SNS
Step 1: Configure the Terraform AWS provider
# versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
# Default provider: your application's region
provider "aws" {
region = var.region
}
# CloudFront-scoped WAF resources must be managed in us-east-1
provider "aws" {
alias = "us_east_1"
region = "us-east-1"
}
# variables.tf
variable "name" { type = string } # e.g. "ledgerlane"
variable "region" { type = string }
variable "enforce_managed_rules" {
type = bool
default = false # false = Count mode (test); true = enforce rule actions
description = "Run managed rule groups in Count mode until tuned"
}
variable "office_cidrs" { type = list(string) }
variable "general_rate_limit" { type = number, default = 2000 } # per 5 min, hypothetical
variable "login_rate_limit" { type = number, default = 20 } # per 1 min, hypothetical
variable "alert_email" { type = string }
Step 2: Define the Web ACL
The Web ACL needs a name, description, scope, default action, and a visibility configuration for CloudWatch metrics and sampled requests.
The default action applies to requests that match no blocking rule. For a public application, allow is typical: you block known-bad traffic and let everything else through. A block default fits closed applications, such as an internal tool, where you explicitly allow known-good traffic. Choose based on how well you can enumerate legitimate traffic, because a block default can lock out real users.
The full Web ACL appears below, assembled over Steps 3 to 5. Rules are evaluated in ascending priority order, so cheap, decisive rules (path restrictions, rate limits) come before the managed rule groups.
# waf.tf (part 1: Web ACL shell and IP set)
resource "aws_wafv2_ip_set" "office" {
provider = aws.us_east_1
name = "${var.name}-office"
scope = "CLOUDFRONT"
ip_address_version = "IPV4"
addresses = var.office_cidrs
}
locals {
managed_rules = {
common = { name = "AWSManagedRulesCommonRuleSet", priority = 30 }
sqli = { name = "AWSManagedRulesSQLiRuleSet", priority = 40 }
badin = { name = "AWSManagedRulesKnownBadInputsRuleSet", priority = 50 }
}
}
resource "aws_wafv2_web_acl" "app" {
provider = aws.us_east_1
name = "${var.name}-web-acl"
description = "Web ACL protecting the ${var.name} application"
scope = "CLOUDFRONT"
default_action {
allow {}
}
visibility_config {
cloudwatch_metrics_enabled = true
metric_name = "${var.name}-web-acl"
sampled_requests_enabled = true
}
# Rules from Steps 3-5 go here
}
Step 3: Add AWS Managed Rules
Inside the Web ACL, one dynamic block creates all three managed rule groups from the locals map:
AWSManagedRulesCommonRuleSet covers general web exploit patterns, including cross-site scripting checks across cookies, query arguments, body, and URI path, plus size restrictions and malformed-request checks.
AWSManagedRulesSQLiRuleSet inspects request components for SQL injection patterns.
AWSManagedRulesKnownBadInputsRuleSet matches inputs associated with exploiting known vulnerabilities.
Three concepts matter here:
Priority sets evaluation order. Leave gaps (10, 20, 30) so you can insert rules later.
Override action. For a rule group, count {} overrides the rule group's own actions so everything is counted instead of blocked, while none {} leaves the group's actions in place. This is different from the action block used on your own rules.
Visibility configuration controls the CloudWatch metric name for each rule, which is what you'll chart later.
Start in Count mode. With enforce_managed_rules = false, you can review what would have been blocked against real traffic, then switch to enforcement once you've handled false positives. For a finer approach, override just one noisy rule inside a group:
managed_rule_group_statement {
name = "AWSManagedRulesCommonRuleSet"
vendor_name = "AWS"
rule_action_override {
name = "SizeRestrictions_BODY" # e.g. legitimate large uploads
action_to_use {
count {}
}
}
}
Each managed group also consumes web ACL capacity units (WCUs), and a Web ACL has a capacity limit, so check the documented WCU values when planning.
Aggregation:IP counts requests separately per client address. Other options include forwarded IP and custom keys.
Evaluation window: how far back WAF looks when counting. Valid values are 60, 120, 300, and 600 seconds. It does not set how often WAF checks.
Limit: the threshold per aggregation instance; the minimum allowed is 10. WAF enforces rate limits approximately, not to the exact request.
Scope-down statement: narrows which requests are counted (used next).
Action: here block, but count is a good starting point.
The numbers above are hypothetical. The right values depend on your traffic. Observe normal per-client request rates first, set limits comfortably above them, and tune from there. Also note that behind another proxy, the IP WAF sees may be the proxy's; use forwarded IP aggregation where appropriate.
You can match on URI path, HTTP method, headers, query strings, IP sets, and more. Keep conditions narrow. A rule that blocks /api from anyone outside an IP set is easy to write and easy to regret. Run new custom rules in Count mode first by changing block {} to count {}.
Optional: Bot Control. The Bot Control managed rule group is separate from the three above and has additional cost, so review current pricing before enabling it. A cautious starting point is the common inspection level in Count mode:
If a different Terraform stack manages the distribution, pass the ARN through a variable or remote state output.
Close the bypass. Restrict the ALB's security group to CloudFront's origin-facing addresses, and optionally require a secret header that CloudFront adds to origin requests:
Variation: ALB as the entry point (regional Web ACL). Change scope to "REGIONAL", drop the us_east_1 provider alias so the Web ACL is created in the ALB's region, create the IP set with scope = "REGIONAL", and associate it:
terraform init # downloads providers, initializes the working directory
terraform fmt # optional: standardizes formatting
terraform validate # checks syntax and internal consistency
terraform plan -out=waf.tfplan # previews the changes without applying
terraform apply waf.tfplan # applies exactly the plan you reviewed
Before applying, read the plan carefully. Confirm the Web ACL scope and provider alias are correct, rules are in the intended Count or Block mode, no unrelated resources change, and the distribution update touches only web_acl_id. Because the Web ACL attaches to a production entry point, apply to a non-production environment first.
Visual Insights: What to Look at in the Console
The screenshots below are placeholders to capture from your own environment. They are not from a real Qbits deployment, and no traffic figures are implied.
1. Web ACL configuration. The Web ACL overview shows scope, default action, associated resources, and ordered rules.
📷 Placeholder: AWS WAF console, Web ACL overview.
2. Managed rule groups. Show the Common, SQLi, and Known Bad Inputs groups with their priorities and Count/None override state.
📷 Placeholder: managed rule group configuration.
3. Integration with the application. Show the distribution's WAF setting (or the ALB association) confirming the Web ACL is attached.
📷 Placeholder: resource association.
4. Traffic analysis. The Web ACL's metrics show allowed, blocked, and counted requests over time, which gives you the overall picture and exposes sudden shifts.
📷 Placeholder: CloudWatch dashboard with AllowedRequests, BlockedRequests, CountedRequests.
5. Rule-level activity. Because each rule has its own metric name, you can chart which rules fire most. A rule that dominates the counts deserves attention: either you're under sustained attack on that vector, or the rule is producing false positives. Use sampled requests and logs to tell which.
📷 Placeholder: per-rule metrics or log-based dashboard.
Monitoring and Alerting
Three data sources do different jobs, and it helps to keep them straight:
SourceWhat it tells youCloudWatch metricsAggregate counts (allowed, blocked, counted) per Web ACL and per rule. Good for trends and alarms.WAF logsPer-request detail: URI, headers, matched rules, action, client IP. Good for investigation and false-positive analysis.AWS CloudTrailManagement activity: who created or changed a Web ACL, rule, or IP set. Not request traffic.
Enable logging. WAF logs can go to CloudWatch Logs, S3, or Kinesis Data Firehose. For CloudWatch Logs, the log group name must start with aws-waf-logs-, and for a CloudFront-scoped ACL it must be in us-east-1.
Dropping allowed requests lowers log cost but removes context. For investigations, you may want them. Note too that when WAF logs to CloudWatch Logs, it manages a log resource policy; in larger accounts, manage that policy explicitly to avoid conflicts.
Alarm on blocked-request spikes, with SNS notification:
# alarms.tf
resource "aws_sns_topic" "security" {
provider = aws.us_east_1
name = "${var.name}-security-alerts"
}
resource "aws_sns_topic_subscription" "email" {
provider = aws.us_east_1
topic_arn = aws_sns_topic.security.arn
protocol = "email"
endpoint = var.alert_email
}
resource "aws_cloudwatch_metric_alarm" "blocked_spike" {
provider = aws.us_east_1
alarm_name = "${var.name}-waf-blocked-requests-spike"
namespace = "AWS/WAFV2"
metric_name = "BlockedRequests"
statistic = "Sum"
period = 300
evaluation_periods = 2
threshold = 500 # hypothetical; tune to your baseline
comparison_operator = "GreaterThanThreshold"
treat_missing_data = "notBreaching"
dimensions = {
WebACL = aws_wafv2_web_acl.app.name
Rule = "ALL"
Region = "Global" # CloudFront scope; use the region name for regional ACLs
}
alarm_actions = [aws_sns_topic.security.arn]
}
Verify the dimension values in the CloudWatch console after deployment; they're easy to get slightly wrong. Alarms keyed to individual rule metrics (for example, the login rate limit) can also tell you when someone is hammering authentication.
What to look for:
Sudden jumps in blocked requests, which may indicate a campaign or a newly broken rule.
Repeated hits on the login rate rule, which suggests credential stuffing or brute forcing.
Frequently triggered rules, which tell you where to focus attention.
Unusual traffic patterns, such as unexpected paths, user agents, or countries.
Potential false positives, such as a legitimate user or integration blocked repeatedly by the same rule.
Use CloudTrail to answer "who changed this rule, and when?", especially in incident reviews.
Security Best Practices for AWS WAF
Start new managed rules in Count mode so you can see their effect before blocking real users.
Review sampled requests and logs before enabling blocking. Look at what would have been blocked and confirm it's malicious.
Apply least-privilege IAM for who can change Web ACLs, rules, and logging. A weakened WAF can be as dangerous as none.
Use rate-based rules for excessive request patterns, with stricter limits on sensitive endpoints.
Protect sensitive endpoints such as login, password reset, signup, and admin paths with dedicated rules.
Review and update managed rule groups. AWS updates them over time; check release notes and whether you pin a version.
Monitor for false positives and use targeted rule overrides instead of disabling whole groups.
Enable WAF logging, redacting sensitive fields.
Create CloudWatch alarms for suspicious activity.
Validate input in the application. WAF is not a substitute for parameterized queries and output encoding.
Combine WAF with secure authentication and authorization, including MFA and least-privilege access in the app.
Review rules regularly, because applications, traffic, and threats change.
WAF belongs in a layered strategy: network controls, WAF, secure code, identity and access management, encryption, patching, and monitoring. Any single layer can be bypassed or misconfigured, and the others still need to hold.
Expected Security Improvements
Security concernBefore WAFAfter WAFSQL injection attemptsNo dedicated WAF inspection layerRequests evaluated against SQLi rulesXSS attemptsLimited web-layer filteringRequests inspected using applicable managed rulesExcessive requestsApplication may receive high request volumesRate-based rules can restrict matching trafficSuspicious inputsLimited centralized request filteringKnown bad input rules can identify matching patternsSecurity visibilityLimited request-level visibilityWAF metrics and logs support analysis
These are capabilities, not guarantees. WAF does not detect every malicious request, and tuning is part of the work. The value comes from adding a filtering and visibility layer, then improving it with evidence.
Conclusion: Strengthening Application Security with AWS WAF
A successful AWS WAF implementation isn't a one-time deployment. In this guide, we placed a CloudFront-scoped Web ACL in front of a hypothetical SaaS application, added managed rules for common exploits, SQL injection, and known bad inputs, layered on rate-based and application-specific rules, defined everything in native Terraform, and set up logging and alarms. The practices that make it work in production are testing in Count mode, tuning against real traffic, watching metrics and logs, and reviewing rules regularly.
WAF is one layer in a security architecture that also includes secure application code, locked-down origins, identity controls, and operational monitoring. Teams that treat it as a living part of their cloud infrastructure, with its configuration in version control and its signals reviewed, get far more from it than teams that switch it on and forget it.
AWS Infrastructure Security: Essential Practices for a Secure and Reliable Cloud Environment
Qbits
Tech Team
AWS Infrastructure Security: Essential Practices for a Secure and Reliable Cloud Environment
AWS Cost Optimization: A Practical Guide to Building Cost-Efficient Cloud Infrastructure Picture a SaaS company that launches on AWS with a modest setup: a...