AWS Builder Center
DNS Knocking on AWS: Port Knocking Goes Serverless

DNS Knocking on AWS: Port Knocking Goes Serverless

What happens when two security dinosaurs, a little whiskey, and memories of iptables-era port knocking meet AWS serverless architecture? This article explores DNS knocking with Route 53, CloudFront Functions, CloudWatch Logs, Lambda, EventBridge, and AWS WAF to provide temporary QA access without tracking constantly changing home or mobile IP addresses. It is part security pattern, part tabletop exercise, and part internet archaeology.

There are two kinds of security tabletop exercises.
The official ones involve threat models, incident cards, and someone saying, “Let’s assume the attacker has compromised the coffee machine.”
The unofficial ones happen over whiskey, when two security engineers remember how they used to protect PBX servers with iptables and port knocking—and decide to rebuild the idea with AWS services.
Co-authored with  Amit Blum , this article turns that conversation into a serverless design using Route 53, CloudFront, Lambda, and AWS WAF.

From port knocking to DNS knocking

Classic port knocking used a sequence of connection attempts on closed ports. The sequence was not the application protocol; it was a signal to the firewall: “Someone who knows the pattern is asking for temporary access.”
The AWS version can use DNS as the signal. A QA engineer opens a small static page, chooses an environment such as  system1 , and the browser is redirected to a unique, deliberately nonexistent hostname. Amazon Route 53 logs the resulting  NXDOMAIN , and that log becomes an event for a serverless workflow.
The workflow can temporarily add the QA client’s public address to the appropriate AWS WAF IP set for the selected environment. The protected workload could be a CloudFront-backed web application, an API Gateway and Lambda service, a container platform such as Amazon EKS or Amazon ECS, or a traditional EC2 service behind its load balancer. Existing ingress controls and security groups remain focused on trusted AWS front doors and service-to-service paths instead of tracking changing home or mobile addresses.
QA device
→ Amazon S3 static page through CloudFront
→ CloudFront Function
→ unique NXDOMAIN hostname
→ Route 53 public query log
→ CloudWatch Logs subscription filter
→ access Lambda
→ AWS WAF IP set
The subscription filter performs the cheap first pass: it matches the expected knock suffix and  NXDOMAIN  response. The Lambda then parses the batch, verifies the HMAC, and updates WAF directly. EventBridge is optional when the design grows and DNS detection, authorization, WAF updates, notifications, and audit consumers should be separate subscribers.
This is not a replacement for identity-based authentication. It is a temporary network access switch for a trusted testing workflow.

What the QA user experiences

The knock is deliberately separate from the destination application:
  1. The QA engineer opens the static access page, selects  system1 , and chooses a duration.
  1. CloudFront returns a redirect to a unique hostname under the knock zone.
  1. The browser performs a DNS lookup for that hostname. The lookup intentionally returns  NXDOMAIN ; it is the signal, not a web page.
  1. The subscription Lambda validates the request and temporarily adds the client’s public IP prefix to the WAF IP set for  system1 .
  1. The QA engineer opens the destination hostname they already know, for example  system1.qa.example.com .
  1. CloudFront or the application’s front door now allows the request. After the duration expires, the cleanup Lambda removes the WAF entry and access stops.
The protected system is never hidden inside the DNS redirect, and the redirect does not navigate the user to  system1 . It only opens the temporary network path. A top-level redirect may leave the browser showing an expected DNS error after the knock; a friendlier page can trigger the unique lookup in the background and display “Access request sent” while the QA engineer opens the known destination in a separate tab.
Think of it as a tabletop exercise where the dice are replaced by DNS resolvers and the game master is a Lambda function. The important difference is that this game can change a real WAF rule, so the rules need to be written down before anyone rolls.

AWS building blocks

1. Amazon S3 and CloudFront

Store the page in a private S3 bucket and serve it through CloudFront. Use Origin Access Control so viewers cannot bypass CloudFront and read the bucket directly. The page can contain a simple system selector and a duration input.
The CloudFront distribution uses a viewer-request CloudFront Function. CloudFront Functions can read the query string, access the viewer IP, and return a 302 response without requiring an application server. The  CloudFront Functions event structure  exposes the viewer IP as  event.viewer.ip .

2. Route 53 public query logging

Create a public hosted zone for a dedicated knock suffix, such as  knock.example.com . Do not create records for the generated names; the desired response is  NXDOMAIN .
Enable  Route 53 public DNS query logging  and send it to a CloudWatch Logs group. For public hosted zones, the log group must be in  us-east-1 .
Route 53 logs the query name, record type, response code, timestamp, resolver address, and optional EDNS Client Subnet. The resolver address is usually not the QA client’s address. The client address comes from CloudFront and is carried in the signed hostname.
DNS is inherently lossy: recursive resolvers can cache NXDOMAIN responses, users can use DNS-over-HTTPS, and Route 53 logs only queries that actually reach Route 53. A unique hostname on every attempt reduces cache reuse but cannot guarantee delivery.

3. CloudWatch Logs and Lambda

Attach a CloudWatch Logs subscription filter to the Route 53 log group. The filter should discard ordinary DNS traffic before Lambda sees it, using the dedicated suffix and  NXDOMAIN  as coarse criteria. A conceptual space-delimited filter looks like:
"NXDOMAIN" "knock.example.com"
The exact pattern should be tested against the emitted Route 53 log lines. It is a prefilter, not a security boundary: it cannot validate the complete hostname structure or HMAC. Matching batches invoke Lambda in near real time. The Lambda should:
  1. Parse the Route 53 log line.
  1. Require the expected hosted-zone ID, query suffix, and  NXDOMAIN  response.
  1. Extract the hostname labels.
  1. Rebuild the canonical payload.
  1. Verify the HMAC.
  1. Validate the system, IP family, prefix, and duration.
  1. Update WAF directly, or publish a custom EventBridge event for a separate access Lambda.
CloudWatch Logs subscriptions provide at-least-once delivery, so the handler must tolerate duplicates. A random DNS label prevents cache collisions, but it is not replay protection. Strict single-use behavior would require storing a nonce or another replay record.

4. EventBridge and AWS WAF

The detector Lambda can publish an event such as:
{
"source": "dns-knocking",
"detail-type": "Temporary QA Access Requested",
"detail": {
"system": "system1",
"ip_prefix": "198.51.100.20/32",
"minutes": 30
}
}
An EventBridge rule can route the event to an access Lambda. That Lambda updates a Global (CloudFront) AWS WAF IP set; regional IP sets cannot protect a CloudFront distribution. AWS WAF supports IPv4 and IPv6 CIDR ranges, so an IPv4 client can be represented as  /32 , while an IPv6 client can be normalized to  /64  if that is the intended access boundary. See  Managing AWS WAF IP sets .
For multiple systems, use a separate IP set per system or maintain a mapping from system name to WAF IP set ARN. The access Lambda must use  GetIPSet  and the returned lock token before calling  UpdateIPSet , and should preserve addresses added by other valid QA sessions.

5. EventBridge Scheduler for cleanup

WAF IP set entries do not expire by themselves. After adding an address, the access Lambda creates a one-time EventBridge Scheduler schedule for the requested duration. The schedule invokes a cleanup Lambda, which removes the address from the appropriate WAF IP set after the access window expires.
The cleanup payload should include the system, address, and a grant identifier. The cleanup Lambda must remove the address only if it is still associated with that temporary grant; otherwise, an old cleanup job could accidentally remove a newer QA session’s access. For shared IPs, a small DynamoDB reference counter or grant table may be needed to prevent one session from removing access still required by another session.
 EventBridge Scheduler  supports one-time schedules. Delete completed schedules so a busy test environment does not accumulate unnecessary schedule resources. If exact per-session cleanup is not required, a periodic cleanup Lambda can instead scan the active grants and reconcile WAF IP sets.

The hostname and HMAC

A practical hostname can look like this for an IPv4 client:
q7m4k2.system1.c6336414.30.<hmac>.knock.example.com
For an IPv6  /64  client, the same request could look like this:
q7m4k2.system1.20010db812345678.30.<hmac>.knock.example.com
The  <hmac>  value is intentionally shown as a placeholder because it is calculated from the deployment secret and the complete payload.
The labels represent:
  • a random value, making every DNS request unique;
  • the system to open;
  • the CloudFront-observed client IP prefix, encoded with DNS-safe characters;
  • the requested duration in minutes;
  • an HMAC over the complete request, including the client IP prefix.
The IP is visible in this stateless design. HMAC does not encrypt data; it makes tampering detectable. Someone can read the hostname, but changing  system1 , the address, or  30  minutes invalidates the HMAC. Hiding the IP would require real encryption or server-side state.
Use lowercase Base32 or hexadecimal for DNS labels. Ordinary Base64 contains characters such as  + ,  / , and  = , and uppercase letters are unsafe because DNS names are case-insensitive. Each label can be at most 63 bytes, and the complete DNS name can be at most 253 characters.

What encoded IP means

The IP prefix is encoded, not encrypted. Encoding only changes the representation so the value fits safely inside a DNS label.
For example, with lowercase hexadecimal:
IPv4 address: 198.51.100.20
Encoded label: c6336414

IPv6 /64 prefix: 2001:db8:1234:5678::/64
Encoded label: 20010db812345678
The  /32  and  /64  lengths are understood by the Lambda from the address family and decoded byte length; they do not need to appear in the hostname. For IPv6, Lambda masks the lower 64 bits before encoding so every address in the selected prefix produces the same access range.
The duration is user input, but the CloudFront Function normalizes it before signing:
1 minute → 1
30 minutes → 30
999 minutes → 120
invalid input → configured safe default
The maximum should be enforced again in Lambda. The user may request 120 minutes, but cannot modify an already-issued hostname from 30 to 120 without invalidating the HMAC.

CloudFront Function example

CloudFront Functions runtime 2.0 provides HMAC helpers and can read an associated KeyValueStore. The following example shows the control flow;  encodeIpPrefix  represents a reviewed DNS-safe encoder that emits lowercase text and normalizes IPv6 to  /64  when required.
import cf from 'cloudfront';
var crypto = require('crypto');
var kvsHandle = cf.kvs();

function hmacHex(secret, value) {
return crypto.createHmac('sha256', secret)
.update(value)
.digest('hex');
}

function queryValue(querystring, name) {
return querystring[name] && querystring[name].value;
}

async function handler(event) {
var request = event.request;
var qs = request.querystring || {};
var system = queryValue(qs, 'system');
var minutes = parseInt(queryValue(qs, 'minutes'), 10);
var sharedSecret = await kvsHandle.get('dns-knock-hmac-secret');

var allowedSystems = {
system1: true,
system2: true
};

if (!allowedSystems[system]) {
return { statusCode: 404, statusDescription: 'Unknown system' };
}

if (!isFinite(minutes) || minutes < 1) {
minutes = 15;
}
if (minutes > 120) {
minutes = 120;
}

var nonce = Math.random().toString(36).substring(2, 14);
var ipPrefix = encodeIpPrefix(event.viewer.ip);
var payload = ['v1', system, ipPrefix, minutes, nonce].join('|');
var mac = hmacHex(sharedSecret, payload);
var host = nonce + '.' + system + '.' + ipPrefix + '.' +
minutes + '.' + mac + '.knock.example.com';

return {
statusCode: 302,
statusDescription: 'Found',
headers: {
location: { value: 'https://' + host + '/' }
}
};
}
The shared secret is a deployment concern. A CloudFront Function can read configuration from  CloudFront KeyValueStore , so the HMAC key can be kept out of the function source and rotated by updating a versioned key-value entry. The store is still readable by the associated function at the edge, so it should be treated as protected configuration rather than a high-assurance secret vault. Anyone who can read the key-value entry or modify the associated function should be treated as able to obtain the HMAC secret.

IAM and operational safeguards

Keep the permissions narrow:
  • Route 53: allow query-log delivery to the designated CloudWatch Logs group.
  • Subscription Lambda: read and validate only the expected log format, then publish to the dedicated EventBridge bus.
  • Access Lambda: update only the named CloudFront-scope WAF IP sets and create only the required Scheduler jobs.
  • Cleanup Lambda: remove only addresses belonging to its temporary grant.
  • EventBridge: allow only the intended Lambda targets.
Add CloudWatch alarms for malformed tokens, unexpected systems, HMAC failures, WAF update failures, cleanup failures, and unusually high knock volume. Keep CloudTrail enabled for WAF, EventBridge Scheduler, and IAM activity.

What could go wrong?

DNS is wonderfully useful and wonderfully weird. Recursive resolvers cache NXDOMAIN responses, clients may use DNS-over-HTTPS, logs can arrive more than once, and a home Wi-Fi public NAT address may be shared by many people. A  /64  IPv6 grant is even broader by design.
There is another important failure mode: DNS security protection may stop the knock before it reaches Route 53. Corporate resolvers, endpoint security products, DNS firewalls, and managed resolver services can classify randomized hostnames as domain-generation, tunneling, or other suspicious DNS behavior. They may block the query, answer locally, sinkhole it, or rewrite the response. In that case, Route 53 receives no query and the Lambda workflow never starts. Test from the real QA networks, and consider an explicit allowlist for the knock suffix or an HTTPS fallback. AWS  Route 53 Resolver DNS Firewall  is an example of a control that can influence DNS behavior and logging.
This pattern is therefore best suited to controlled QA access, not as the only protection for a sensitive production application. It is a modern, temporary network switch—not authentication.
The final pattern is familiar, just wearing a cloud costume:
old port knock
→ Route 53 NXDOMAIN signal
→ CloudWatch Logs event
→ Lambda and EventBridge
→ temporary AWS WAF access
→ EventBridge Scheduler cleanup
The dinosaurs may have learned a few new tricks after all.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article