To auto-block scanners in AWS WAF from a decoy URL you need five parts: a path that nothing legitimate links to, an event when someone requests that path, an AWS WAF IP set with a block rule that references it, a Lambda function that adds the caller's address to the IP set with GetIPSet and UpdateIPSet, and a clean-up job that removes each address after a fixed time. This guide shows each part in Terraform and Python, as we built it for a conference demo stand in November 2026, with the numbers we measured and the guard rails that keep the block list from hurting you.
Last checked: 25 November 2026. Written by Ilia Dubovskii, founder of Beamreach. The numbers are from our conference demo stand; the code is a minimal version adapted from that stand.
The short version
- A decoy URL is a trustworthy signal because no legitimate user or service has a reason to request it, so a request to the decoy URL can drive an automatic block without a human.
- On our conference demo stand in November 2026 the caller's address was in the AWS WAF IP set 0.4 to 1.7 seconds after the request, and AWS WAF served a 403 to that address after about 12 seconds.
-
UpdateIPSetreplaces the whole address list, so the Lambda function must callGetIPSetfirst, change the list, and send the list back with theLockTokenfrom the read. - Every block needs an expiry. Our stand lifts each block after one hour with a scheduled clean-up, because an address changes hands and a list that only grows ends up blocking customers.
- An IP block is cheap for an attacker to get around. The block removes mass scanners; the block does not contain an attacker who is already inside.
- The AWS WAF block action described here is a conference build. The AWS WAF block action is not in a Compass release.
What the pattern does, and what we measured
The pattern turns one request to a decoy URL into a temporary block of the address that made the request. The flow has four steps:
- A scanner requests the decoy path through the Application Load Balancer.
- The application that serves the decoy path puts one message on an Amazon SQS queue: the path, the client address, the time.
- A Lambda function reads the message, checks the address against the guard rails, and adds the address to an AWS WAF IP set.
- A block rule in the web ACL references the IP set, so AWS WAF answers the next requests from that address with a 403. A scheduled run of the same Lambda function removes the address one hour later.
We measured these numbers on our conference demo stand in November 2026. The stand was a decoy file server on AWS Fargate behind an Application Load Balancer and AWS WAF, built for our DevOpsDays Portugal talk.
| Step | Measured on the stand, November 2026 |
|---|---|
| Decoy request to the address being in the AWS WAF IP set | 0.4 to 1.7 seconds |
| Until AWS WAF served a 403 to that address | about 12 seconds |
| Clean container replacing the one that served the decoy | about 40 seconds |
| First real scanner to trip the decoy | 10 minutes after the TLS certificate was issued |
The gap between 1.7 seconds and 12 seconds is AWS WAF propagation. The UpdateIPSet reference says a change can take "from a few seconds to a number of minutes" to reach every place the web ACL is used, and that a new address "might be blocked in one area while still allowed in another" during that time. Plan for the scanner to get a few more requests through after the trip.
The stand also restarted the container that served the decoy. This guide covers only the AWS WAF block.
The decoy path and how the hit is detected
A decoy path is a URL that the real application never uses and that no page, sitemap or client links to. Our stand served an open directory listing with a file named passwords.txt in it, because the stand was built for an audience to find. For a production service, pick a path that only something guessing would ask for, for example /.env or /backup.sql on a service that has no such file. Do not link the decoy path from anywhere a search engine crawler follows.
How the stand detects the hit. On our stand the detection is in the application. The handler for the decoy path builds one JSON event and sends the event to an SQS queue from a background thread, so the response is not delayed. The stand does not read AWS WAF logs or load balancer logs. The application reads the client address from the last entry of the X-Forwarded-For header. An Application Load Balancer in its default append mode appends the address of the client that connected to the load balancer to that header, so the last entry was written by the load balancer, and every entry to the left of the last one is whatever the client chose to send.
# In the application that serves the decoy path. # Adapted from our stand; test it in a sandbox account first. import json import os from datetime import datetime, timezone import boto3 sqs = boto3.client("sqs") QUEUE_URL = os.environ["ALERT_QUEUE_URL"] def client_ip(headers, peer_address): # The load balancer appends the address it saw. Anything left of that is the client's own claim. forwarded = [p.strip() for p in (headers.get("X-Forwarded-For") or "").split(",") if p.strip()] return forwarded[-1] if forwarded else peer_address def on_decoy_request(headers, peer_address, path): sqs.send_message(QueueUrl=QUEUE_URL, MessageBody=json.dumps({ "kind": "decoy_file_opened", "path": path, "source_ip": client_ip(headers, peer_address), "at": datetime.now(timezone.utc).isoformat(), })) The task role of the application needs one permission for this: sqs:SendMessage on that one queue.
Alternatives. There are three other ways to detect a request to a decoy path on AWS. We did not build or time them.
| Detection | How it works | What to know |
|---|---|---|
| Event from the application (our stand) | The decoy handler sends a message to SQS | Needs a few lines in the application. We measured 0.4 to 1.7 seconds from the request to the IP set. |
| AWS WAF rule with a count action | A rule matches the decoy path with a Count action and adds a label. AWS WAF logs go to a CloudWatch Logs group, and a subscription filter sends matching records to the Lambda function | No application change. The log record carries httpRequest.clientIp and the labels. The log group name must start with aws-waf-logs-, and logging is charged separately. |
| Application log line | The application logs the hit; a CloudWatch Logs subscription filter sends the line to the Lambda function | Works when you cannot give the application SQS access. The address is only as good as what the application logged. |
| Load balancer access logs | Parse the Application Load Balancer access logs in Amazon S3 | Too slow for this job: Elastic Load Balancing publishes a log file every 5 minutes and logs requests "on a best-effort basis". |
The Count action is non-terminating: AWS WAF counts the request and carries on with the remaining rules, so the decoy still answers. A CloudWatch Logs subscription filter can deliver matching log events to a Lambda function.
The IP set and the block rule in Terraform
An AWS WAF IP set is a named list of addresses in CIDR notation. A rule in the web ACL references the IP set with an ip_set_reference_statement and blocks every request whose source address is in the list. Three details matter.
- One IP set per address family.
ip_address_versionisIPV4orIPV6, and an IP set holds one of them. Our stand had only an IPv4 set. The code below has both. - Terraform must not own the addresses. The Lambda function changes the list at run time. Without
ignore_changes = [addresses], the nextterraform applyresets the list to empty and lifts every block. - The scope must match the resource.
REGIONALis for an Application Load Balancer, an API Gateway REST API and the other regional resources.CLOUDFRONTis for a CloudFront distribution, and for that scope every API call must go to theus-east-1endpoint. In Terraform a CloudFront distribution takes the web ACL through its ownweb_acl_idargument, not throughaws_wafv2_web_acl_association.
# Adapted from our stand; test it in a sandbox account first. resource "aws_wafv2_ip_set" "decoy_v4" { name = "decoy-blocked-v4" description = "decoy blocks" scope = "REGIONAL" ip_address_version = "IPV4" addresses = [] lifecycle { ignore_changes = [addresses] } # the Lambda function owns the contents } resource "aws_wafv2_ip_set" "decoy_v6" { name = "decoy-blocked-v6" description = "decoy blocks" scope = "REGIONAL" ip_address_version = "IPV6" addresses = [] lifecycle { ignore_changes = [addresses] } } resource "aws_wafv2_web_acl" "app" { name = "app" scope = "REGIONAL" default_action { allow {} } rule { name = "decoy-blocked-v4" priority = 1 action { block {} } statement { ip_set_reference_statement { arn = aws_wafv2_ip_set.decoy_v4.arn } } visibility_config { cloudwatch_metrics_enabled = true metric_name = "decoy-blocked-v4" sampled_requests_enabled = false } } rule { name = "decoy-blocked-v6" priority = 2 action { block {} } statement { ip_set_reference_statement { arn = aws_wafv2_ip_set.decoy_v6.arn } } visibility_config { cloudwatch_metrics_enabled = true metric_name = "decoy-blocked-v6" sampled_requests_enabled = false } } visibility_config { cloudwatch_metrics_enabled = true metric_name = "app" sampled_requests_enabled = false } } resource "aws_wafv2_web_acl_association" "alb" { resource_arn = aws_lb.app.arn web_acl_arn = aws_wafv2_web_acl.app.arn } Give the block rules the lowest priority numbers. AWS WAF evaluates rules from the lowest numeric priority up and stops at the first match with a terminating action, so a blocked address costs you no further rule evaluation.
A block {} action answers with HTTP 403 by default. Our stand returned its own HTML page instead: a custom_response_body block in the web ACL, and a custom_response block inside block with response_code = 403 and a custom_response_body_key. A custom response body can be at most 4 KB. The page told the visitor that the file was a decoy and that the block lifts by itself within an hour, which matters when the visitor is a person on a shared network.
The Lambda function: GetIPSet, then UpdateIPSet with the LockToken
The AWS WAF API has no call that adds one address to an IP set. UpdateIPSet "completely replaces the mutable specifications" of the IP set with what you send. The sequence is therefore always the same:
- Call
GetIPSetwithName,ScopeandId. The response holdsIPSet.Addressesand aLockToken. - Add the address to the list in memory, as
203.0.113.7/32for IPv4 or as a/128for IPv6. - Call
UpdateIPSetwithName,Scope,Id, the fullAddresseslist and theLockTokenfrom step 1. Send theDescriptionagain too, because the call replaces it. - If another writer changed the IP set in between, AWS WAF rejects the call with
WAFOptimisticLockException. Read again and retry.
The quotas shape the design. AWS WAF allows one request per second per account per Region for any single update action, and five per second for any single get action. A scan from many addresses at once would hit that quota with one update per address. The function below therefore adds every address in an SQS batch with a single UpdateIPSet call, and the event source mapping caps concurrency at 2. Our stand used a batch size of 1 and retried on lock conflicts, which was enough for a demo.
# responder.py: adapted from our stand; test it in a sandbox account first. # We ran this version only against a stubbed AWS WAF client, not against a real account. import ipaddress import json import os import time import boto3 from boto3.dynamodb.conditions import Key BLOCK_TTL = int(os.environ.get("BLOCK_TTL", "3600")) # seconds a block lasts MAX_ENTRIES = int(os.environ.get("MAX_ENTRIES", "500")) # our cap; the AWS limit is 10,000 per IP set LOCK_RETRIES = 8 NEVER_BLOCK = [ ipaddress.ip_network(n.strip()) for n in os.environ.get("NEVER_BLOCK", "").split(",") if n.strip() ] SCOPE = os.environ.get("WAF_SCOPE", "REGIONAL") # An IP set holds IPv4 or IPv6 addresses, never both: one set per version. IP_SETS = { 4: {"Name": os.environ["IPSET_V4_NAME"], "Id": os.environ["IPSET_V4_ID"], "Scope": SCOPE}, 6: {"Name": os.environ["IPSET_V6_NAME"], "Id": os.environ["IPSET_V6_ID"], "Scope": SCOPE}, } waf = boto3.client("wafv2") table = boto3.resource("dynamodb").Table(os.environ["TABLE"]) def single_address(text): """One public address as a /32 or /128 network, or None when it must not be blocked.""" try: addr = ipaddress.ip_address(str(text).strip()) except ValueError: return None if not addr.is_global: # private, loopback, link-local, reserved return None if any(addr in net for net in NEVER_BLOCK): # your NAT, office, monitoring return None return ipaddress.ip_network(addr) # /32 for IPv4, /128 for IPv6 def edit(version, add=(), remove=()): """GetIPSet, change the list, UpdateIPSet with the LockToken. Read again if someone else wrote first.""" ref = IP_SETS[version] for attempt in range(LOCK_RETRIES): got = waf.get_ip_set(**ref) current = {ipaddress.ip_network(a, strict=False) for a in got["IPSet"]["Addresses"]} wanted = (current | set(add)) - set(remove) if wanted == current: return len(current) if len(wanted) > len(current) and len(wanted) > MAX_ENTRIES: print(f"IP set {ref['Name']} is at the cap of {MAX_ENTRIES}; not adding") wanted = current - set(remove) if wanted == current: return len(current) try: waf.update_ip_set( **ref, Addresses=sorted(str(n) for n in wanted), # the whole list: UpdateIPSet replaces it LockToken=got["LockToken"], Description=got["IPSet"].get("Description") or "decoy blocks", ) return len(wanted) except waf.exceptions.WAFOptimisticLockException: time.sleep(0.15 * (attempt + 1)) raise RuntimeError("the IP set kept changing; giving up so the queue retries") def block(networks): now = int(time.time()) for version in (4, 6): nets = {n for n in networks if n.version == version} if not nets: continue for net in nets: # write the expiry row first: a block without a row would never be lifted table.put_item(Item={"pk": "BLOCK", "sk": str(net), "expires_at": now + BLOCK_TTL}) edit(version, add=nets) def expire(): now = int(time.time()) rows = table.query(KeyConditionExpression=Key("pk").eq("BLOCK"))["Items"] old = [r for r in rows if int(r["expires_at"]) <= now] for version in (4, 6): nets = {ipaddress.ip_network(r["sk"]) for r in old} nets = {n for n in nets if n.version == version} if nets: edit(version, remove=nets) for row in old: table.delete_item(Key={"pk": "BLOCK", "sk": row["sk"]}) return len(old) def handler(event, context=None): if event.get("op") == "expire": # the scheduled rule sends {"op": "expire"} return {"expired": expire()} networks = set() for record in event.get("Records", []): # SQS batch body = json.loads(record["body"]) if body.get("kind") != "decoy_file_opened": continue net = single_address(body.get("source_ip", "")) if net: networks.add(net) if networks: block(networks) return {"blocked": len(networks)} The role of the Lambda function needs two AWS WAF actions, wafv2:GetIPSet and wafv2:UpdateIPSet, on the two IP set ARNs and nothing else in AWS WAF. With that grant the function cannot touch a rule, a web ACL or any other list. Our stand used exactly this grant for its single IP set.
# Adapted from our stand; test it in a sandbox account first. # Not shown: aws_iam_role.responder (trusted by lambda.amazonaws.com, with AWSLambdaBasicExecutionRole) # and the zip build of responder.py. variable "never_block" { type = list(string) default = [] # CIDR ranges: your NAT gateways, office, monitoring, partners } resource "aws_sqs_queue" "decoy" { name = "decoy-alerts" visibility_timeout_seconds = 180 message_retention_seconds = 3600 } resource "aws_dynamodb_table" "blocks" { name = "decoy-blocks" billing_mode = "PAY_PER_REQUEST" hash_key = "pk" range_key = "sk" attribute { name = "pk" type = "S" } attribute { name = "sk" type = "S" } } resource "aws_iam_role_policy" "responder" { role = aws_iam_role.responder.id policy = jsonencode({ Version = "2012-10-17", Statement = [ { Effect = "Allow", Action = ["wafv2:GetIPSet", "wafv2:UpdateIPSet"], Resource = [aws_wafv2_ip_set.decoy_v4.arn, aws_wafv2_ip_set.decoy_v6.arn] }, { Effect = "Allow", Action = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"], Resource = aws_sqs_queue.decoy.arn }, { Effect = "Allow", Action = ["dynamodb:PutItem", "dynamodb:DeleteItem", "dynamodb:Query"], Resource = aws_dynamodb_table.blocks.arn } ] }) } resource "aws_lambda_function" "responder" { function_name = "decoy-responder" role = aws_iam_role.responder.arn runtime = "python3.12" handler Source:https://dev.to/beamreachcloud/auto-block-scanners-in-aws-waf-from-a-decoy-url-a-build-guide-2b64