All posts

Hardening AWS WAF for WordPress with AI: Claude Code and CloudWatch

How I moved WordPress sites to AWS, let Claude read the logs with read-only access, and found bots taking the PHP workers on servers that were never busy.

A panda gatekeeper sips coffee while disguised robots queue at a gate, one bounces off a 404 door, real visitors walk through, and a small AI robot points to a pattern in a long log.

Average CPU on every server sat in the low single digits, yet some sites were still returning 502 errors. Bots were taking the PHP workers. I found out why by having an AI read the logs.

Here's how I got there. Over the last few weeks I moved a set of websites, mostly WordPress, to AWS. The main reason was simple: the old host had no WAF built in. I also wanted something I'd put off for years: servers built from code, kept in git, documented and reviewable. With an AI helping write it, I finally got it done.

Why the WAF needed a load balancer and fixed IPs

On AWS, a WAF can't attach to a server. It attaches to something in front of it, such as an Application Load Balancer or CloudFront.

Architecture diagram. Visitor requests go through DNS and Global Accelerator, with two fixed IPs, to an internal load balancer with the WAF, then to EC2 in a private subnet and RDS. WAF, PHP-FPM and load balancer logs go to CloudWatch Logs and S3, which Claude Code reads with a read-only profile and reports findings to me. I deploy infrastructure and server builds with CDK and Systems Manager using a separate deploy profile.
Tap or click the diagram to open it full size.

Why Global Accelerator? An Application Load Balancer has no fixed IP, and some DNS setups can only point a root domain like example.com at an IP address. Global Accelerator gives two fixed IPs. It also lets the load balancer stay internal, with no direct path from the internet, and it passes the visitor's real IP through, which the per-IP WAF rules depend on. If your DNS can point the root domain at a hostname (Route 53 can), you can skip it and use a public load balancer.

Every server is a git repo

Each setup is its own repo with the same rules:

  • AWS CDK in TypeScript for the infrastructure, one stack per concern (network, data, server, edge, CDN, ops).
  • The server build (Apache, PHP-FPM, Redis, backups) is shell scripts in the repo, tested first in a local arm64 Docker container that matches the Graviton server.
  • No open SSH port, no SSH keys to add for each developer, and no web-based database manager on the server. Shell access, database tunnels and installs go through AWS Systems Manager.
  • A runbook in each repo, with a deploy log: each deploy, who ran it, which commit.

The day-to-day loop looks like this:

bash
pnpm gate                       # typecheck, lint, tests, cdk synth
pnpm stack:diff Edge            # always read the diff first
pnpm stack:deploy Edge          # me, deploy profile: one stack at a time, never --all
pnpm server:publish             # me: upload the server build to S3
pnpm server:apply               # me: run it on the instance via SSM

Not every site got the same build. Busy sites got the load balancer, WAF and managed database; smaller ones got a single server. Same conventions, different architecture.

The shared conventions paid off later. When one setup hit a problem, the others usually had it too, and the fix could be copied across as-is.

Where Claude came in

I did this with Claude Code, with one hard rule:

Claude never runs an AWS command that changes anything. Every deploy is run by me.

So Claude reads, queries, explains and writes code. I review the diff and press deploy.

A rule in a text file isn't enough. What makes it stick is splitting the AWS profiles:

  • A read profile for Claude. A role with ViewOnlyAccess plus read access to the log groups and the load balancer's log bucket. No secrets, no shell sessions, no writes.
  • A deploy profile for me. Every script that writes to AWS (deploy, publish, apply) names this profile, and only I run them. Scripts that only read take the profile from the environment, so Claude's runs use the read profile.
  • Claude Code settings or a hook as a seatbelt. They block obvious mistakes, but they can be bypassed. The stronger boundary is the role: a write sent with the read profile is refused by AWS. The part to get right is keeping the deploy profile out of Claude's reach, for example with a separate login that you start only when you deploy.

Around that, account guardrails that don't depend on Claude: a service control policy keeps workload accounts to two regions (global services aside), the developer role can deploy but can't read secrets or delete data outside a CloudFormation diff, and CloudTrail keeps a year of management events. Those policies are in git too.

The building part was useful. The part that changed how I work was the review afterwards.

The servers weren't busy. The PHP workers were.

A few days after the first sites went live, I asked Claude for a platform review: alarms, load balancer metrics, PHP-FPM logs, WAF logs, all read-only. It pulled them with the AWS CLI and CloudWatch Logs Insights. The logs include visitor IPs, so check your AI plan's data settings before you point it at production logs.

The first finding was the one in the opening: CPU was fine, and the errors came from PHP worker pools filling up as bots took the slots real visitors needed.

Three patterns stood out. The first two filled a worker pool and caused 502 errors:

  • A burst of about 700 IPs loading one page each. No single IP looked bad.
  • A burst from automation tools and headless browsers, going by their user agents.
  • A scraper on rotating proxies: a fixed list of about 85 URLs in under a minute, a new IP each run, 4–5 runs a day, always sending Firefox/131.0.

The WAF was already blocking thousands of scanner requests a day. These bots got through because each request looked fine on its own. The pattern only showed when you looked at all of them together.

Finding that by hand means exporting logs, grepping, pivoting in a spreadsheet, and doing it again the next day.

Count first, then enforce

The broad bot rules went in count mode first: a rule in count mode only logs, it doesn't block. Narrow blocks for one known IP or user agent went straight in. The three bot rules:

  • BotUserAgents: block known automation user agents.
  • PageSurge: count anonymous page loads across all IPs together; past a threshold, challenge each of them. This is aimed at crawls like the 700-IP one.
  • PageRatePerIp: challenge one IP that loads far more pages a minute than any real visitor.

Here's the per-IP rule in CDK:

ts
{
  name: 'PageRatePerIp',
  priority: 10,  // any unique number
  action: enforceBots ? { challenge: {} } : { count: {} },
  statement: {
    rateBasedStatement: {
      limit: config.waf.pagesPerIpPerMinute,
      evaluationWindowSec: 60,
      aggregateKeyType: 'IP',
      scopeDownStatement: anonymousPageLoad,
    },
  },
  visibilityConfig: visibility('PageRatePerIp'),
},

The thresholds came from the data, not a guess: well above the busiest real visitor and the busiest search crawler in the logs.

After a few days in count mode, I checked who would have been hit. The WAF writes its logs to CloudWatch, in a log group whose name starts with aws-waf-logs-. In the console, open CloudWatch → Logs Insights, pick that log group and a time range, and run this query:

filter @message like /"ruleId":"(BotUserAgents|PageSurge|PageRatePerIp)"/
| stats count(*) as hits by httpRequest.clientIp
| sort hits desc

Claude ran the same query from the CLI with aws logs start-query and get-query-results. Counted matches show up in each log entry under nonTerminatingMatchingRules, so they're there even though nothing was blocked.

I went through the list and found no real visitors among them. So the rules went to enforce: one config value, pnpm gate, diff, deploy.

Make "no" cheap

The next review found something less obvious. A lot of the worker time wasn't going to real pages at all. It went to saying "no":

  • Scanners guessing paths like /.env, /wp-config.php.bak or /swagger.json. Each guess started WordPress just to build a 404 page.
  • Requests for a missing icon or image, which fell through to the app the same way.
  • Redirects that only added a trailing slash, each one handled by WordPress.

The fix was the same each time: let Apache answer before PHP starts. Missing .php, .html, .yaml, .md and static files, known probe paths, and trailing-slash redirects now get Apache's own response.

One more, slightly different: bots and link previews sending Accept: */*. The page cache plugin we use serves cached pages only to requests that ask for text/html, so these got a page built from scratch every time. One Apache line that rewrites the exact value */* to text/html,*/* lets the cache serve them.

The results on the busiest setup, with the same window before and after each change:

  • Guessed .php paths: p95 from 5.4 s to 0.001 s.
  • Link-preview loads: p95 from 2.8 s to 0.006 s (the site's own code also changed in that window).
  • Pool-full warnings: 23–43 a day to 1–4 a day over three weeks, from all the changes together (these fixes, the WAF rules and larger pools), not counting a weekly scan covered below.

The server stayed the same size; only the worker pools grew.

Bots that work around the rules

The Firefox/131 scraper was harder. Each run stayed just under the per-IP limit, so the rate rule never caught it, and it kept filling the worker pool.

Firefox 131 is from October 2024 and updates itself. A real person still on it is rare. A real browser passes the challenge on its own in a moment; a scraper without a full browser doesn't. So one more rule: challenge anonymous page loads from that exact user agent.

ts
{
  name: 'ChallengeUserAgents',
  // priority and visibilityConfig as in the rule above
  action: enforceBots ? { challenge: {} } : { count: {} },
  statement: {
    andStatement: {
      statements: [userAgentIs(['Firefox/131.0']), ...anonymousPageLoadParts],
    },
  },
}

In the three days before the rule, 2,117 of its requests reached the server. In the three days after, one did.

The scraper wasn't the only one working around the rules. A vulnerability scan ran every Saturday. The WAF blocked about 100,000 of its requests in under two hours, and the few thousand that got through still filled every worker pool. I blocked its IPs. The next Saturday it came back from a different cloud provider.

So an IP block is a patch, not a fix. A scraper can change its user agent, a scanner can change its network. That's fine: the next review will show it, and each rule is a small config change.

Automated bots, automated reading

What worked for me:

  • AI reads, I decide. Claude does the tedious part: queries, pivots, spotting the pattern. I decide what to block.
  • Look at requests together. The worst bots look fine one request at a time.
  • Almost everything is code. A WAF rule is a reviewed diff, not a click in a console I'll forget about. An Apache rule is tested in a local Docker container before it goes near the server.
  • Write it down. Every review and every deploy goes in the runbook, so the next one starts from there.

There was a time when trouble was easy to spot: a DDoS attack that took the site down, a defaced home page, a spam bot flooding the contact form, someone guessing the admin password all night. Now it's scrapers, bots and vulnerability scanners all day, and I still don't know why most of them bother. The logs were always there, and so were tools to read them. What I rarely had was the time to connect individual requests with the server warnings every time a client said a site was slow. With the logs in CloudWatch and AI drafting the queries, that now takes a conversation instead of an afternoon.

A note: this is what I went through, not a best-practice guide or a standard. Much of it came from trial and error, one change at a time, on a test setup first. Your setup, your company's policies and the tools you have will lead to a different answer, and there are surely better ways to do some of this. I hope some of it helps.

What's next

Right now I start each review by hand. Next, I want an agent to do it: read the logs at the end of each day, compare them with a normal day, and flag anything new. Same rule as before: it reads and reports, I decide what to block.

Category
Tags