How to Harden Cloudflare WAF and Stop Origin Bypass

How to Harden Cloudflare WAF and Stop Origin Bypass

👁3views

Lock your origin so it only accepts traffic from Cloudflare, using Authenticated Origin Pulls with mTLS or Cloudflare Tunnel, plus firewall rules allowing only Cloudflare IP ranges. Then remove exposed DNS records that leak the origin IP, tighten broad WAF exceptions, and switch managed rules from log to block mode.

How to Harden Cloudflare WAF and Stop Origin BypassAndrew Baker's Technology Blog Posts, 04/Dec/2026
https://andrewbaker.ninja/2026/12/04/how-to-harden-cloudflare-waf-and-stop-origin-bypass/

Article Summary
  • 1.
    What it is
    Cloudflare WAF hardening means proving every request passes through your Web Application Firewall, not just turning Cloudflare on. The article covers how Cloudflare proxies a request, where origin bypass and WAF skip rules leak traffic, and how audit, baseline and acceptance test scripts close those gaps.
  • 2.
    Why it matters
    Cloudflare WAF protection only holds if the origin cannot be reached any other way and no rule exempts traffic from inspection. Forgotten DNS records, broad skip rules and an exposed origin IP can quietly turn the WAF into decoration.
  • 3.
    Key takeaway
    Allowing only Cloudflare IP ranges at your origin firewall does not prove a request came through your Cloudflare account, because every Cloudflare customer shares those ranges.
7,743 words · ~39 min read

Turning on Cloudflare feels like the job is done. The padlock is there, the orange cloud is lit up next to your DNS (Domain Name System) records, and the dashboard tells you how many threats it stopped this week. None of that proves every request actually passes through your Web Application Firewall (WAF) before it reaches your application. A forgotten DNS record, a broad exception written during a late night debugging session, or an origin server that still answers anyone who knows its IP (Internet Protocol) address can quietly turn the whole thing into decoration.

This post walks through how Cloudflare’s network really handles a request, where the gaps usually are, and how to close them for any site or API behind Cloudflare: a blog, a single page application with an API behind it, or a set of services behind a cloud load balancer. WordPress appears throughout as a worked example, because it has a well known set of sensitive paths and this blog runs on it, but the scripts default to a generic profile and treat WordPress as one option among others. The post ends with a set of scripts that audit a zone through the Cloudflare API (Application Programming Interface), apply a sensible baseline, lock down the origin, and run acceptance tests that prove the bypasses are gone, with a Markdown report of findings at each step. The scripts produce evidence rather than reassurance, so you can hand the whole thing to an engineer, or to an AI coding agent, and get back something you can check.

1. Why “Cloudflare is on” is not the same as “the WAF is enforced”

Cloudflare is a reverse proxy. When a DNS record is proxied, the public sees Cloudflare’s addresses instead of yours, connections terminate at Cloudflare, and your security rules run there before anything is forwarded to your server (the origin). That model only holds if two things are true: the origin cannot be reached any other way, and nothing inside your Cloudflare configuration exempts traffic from the rules you think are protecting you.

Both conditions fail more often than people expect. The origin address leaks through old DNS records, MX (mail exchanger) records, SPF (Sender Policy Framework) entries, certificate transparency logs or the hosting provider’s default hostname, and once someone has it they can talk to the application directly. Inside Cloudflare, an IP Access allow rule, a Skip rule keyed on a User-Agent string, or a configuration rule that downgrades SSL (Secure Sockets Layer, the old name Cloudflare still uses for its TLS, Transport Layer Security, settings) for one path can each wave traffic straight past the WAF, or weaken what happens after it. The most subtle case is that allowing only Cloudflare’s IP ranges at your firewall does not prove the request came through your Cloudflare account, because those ranges are shared by every Cloudflare customer.

What I want at the end is that no unauthenticated external request can reach the origin without passing through the Cloudflare security enforcement path you configured, and no unnecessary rule lets traffic skip the WAF.

2. The rollout plan

The order matters, because several steps take the site down if they run too early. Skim this list now and come back to it after reading the rest; each step links to the script it uses, and the sections that follow explain the terms. Two of them appear here first: Authenticated Origin Pulls (AOP), where Cloudflare presents a client certificate to your origin, and server side request forgery (SSRF), where an application can be made to fetch a URL (Uniform Resource Locator, a web address) an attacker chooses.

  1. Run smoke_test.sh to prove the toolkit starts on your machine.
  2. Run the audit read only, and keep config-export.json somewhere safe. That file and the backups the other scripts write are your rollback evidence.
  3. Run the egress check on anything that fetches URLs for other people, and rerun the audit with --trusted-range and --egress-ip. Anything critical here goes first, because it is a bypass someone can use today.
  4. Fix DNS: proxy or delete every web facing grey cloud record, move mail and SPF away from the web server’s address, and delete forgotten staging records.
  5. Stage the tunnel: add the loopback listener, then run setup_tunnel.sh, which validates on a temporary hostname without touching production DNS. (Using custom AOP instead? Upload and enable the certificate, set the origin to optional verification, confirm it arrives, then require it; see section 6.2.)
  6. Cut over with tunnel_cutover.py, which backs up DNS and rolls back automatically if the site is unhealthy. Keep the old listener running for a day.
  7. Close the origin with origin_firewall.sh. Behind a load balancer, review it with aws_origin_check.sh and require your client certificate there. If the origin address has been public for years, consider changing it, but treat that as hygiene rather than a control; the firewall and authentication are the control.
  8. Run the acceptance tests until every direct access test is PASS. UNVERIFIED is not good enough here: it means the probe proved nothing.
  9. Confirm the origin certificate validates, then run cf_harden.py as a dry run with the options that match your application (--profile wordpress, --login-path, --api-hostname), read the plan, and apply it with --strict-ssl.
  10. Remove broad exceptions one at a time with --delete-ip-allow and --disable-rule, watching Security Events for anything that genuinely needed them and replacing it with a narrow, path scoped exception.
  11. Put admin and login paths behind Access (/wp-admin on WordPress), and close documentation and management endpoints on API hosts.
  12. Run the full acceptance tests with the Analytics token set until they exit 0 (automated sign off), then exercise the main workflows by hand (publish a post on WordPress, run the client test suite against an API) and confirm the integrations.
  13. Save the approved baseline and switch on the daily audit.

To roll back the edge settings, run cf_harden.py --zone example.com --rollback backups/backup-<timestamp>.json as a dry run, read the plan, then add --apply. To roll back the tunnel, run tunnel_cutover.py --rollback backups/dns-before-tunnel-<timestamp>.json --apply, which restores the original records while the old listener is still running. On the origin, nft delete table inet origin_lockdown removes the firewall table. Rehearse at least the edge rollback as a dry run before you need it.

3. How Cloudflare’s anycast network works

Most networks use unicast, where one IP address lives in one place. Cloudflare uses anycast, where the same IP prefixes are announced over the Border Gateway Protocol (BGP), the protocol networks use to tell each other which addresses they can reach, from every one of its data centers at once. Cloudflare says its data centers now sit in more than 330 cities. When your visitor in Cape Town connects to one of those addresses, internet routing delivers the packets to whichever Cloudflare location is closest in network terms (the shortest BGP path, which is usually but not always the closest geographically), so someone in London hitting the same address lands somewhere else entirely.

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#ffffff','primaryTextColor':'#111111','primaryBorderColor':'#f6821f','lineColor':'#f6821f','secondaryColor':'#fff4e6','tertiaryColor':'#ffffff','clusterBkg':'#fff4e6','clusterBorder':'#f6821f','titleColor':'#b35400','edgeLabelBackground':'#ffffff','fontSize':'15px'}}}%%
flowchart LR
    U1["Visitor in Cape Town"] -->|"BGP picks nearest"| JNB["Cloudflare JNB"]
    U2["Visitor in London"] -->|"BGP picks nearest"| LHR["Cloudflare LHR"]
    U3["Bot in Singapore"] -->|"BGP picks nearest"| SIN["Cloudflare SIN"]
    subgraph SG1["Same anycast IP announced everywhere"]
        JNB
        LHR
        SIN
    end
    JNB -->|"origin pull"| O[("Origin")]
    LHR -->|"origin pull"| O
    SIN -->|"origin pull"| O

Cloudflare describes its design as running its services in every data center rather than in specialised regions, and for the request path that matters here the description holds: there is no separate scrubbing center for DDoS (Distributed Denial of Service) traffic and no special WAF cluster in one region; the data center that receives the packet also terminates the TCP (Transmission Control Protocol) and TLS connection, runs the DDoS mitigation, evaluates your WAF rules, checks the cache and, only if needed, opens a connection to your origin. Inside each data center a layer 4 load balancer spreads connections across servers, so the request for your site is not tied to one particular machine.

Anycast DNS completes the picture. Cloudflare’s authoritative nameservers are also anycast, and for a proxied record they answer with Cloudflare’s addresses rather than yours. For a DNS only record (the grey cloud) they return the real address, which is exactly why a single unproxied record pointing at the same server as your website can undo everything else in this post.

Three consequences matter for security. First, your rules are global: change a custom rule and it applies in every location within seconds, so an attacker cannot shop around for a weaker data center. Second, attack traffic is absorbed wherever it lands, so volumetric floods are diluted across the whole network rather than converging on one link. Third, the connections that reach your origin come from Cloudflare’s shared address ranges, the same ranges used to reach millions of other origins on behalf of millions of other accounts. An address match tells you the request came from Cloudflare’s network, and says nothing about whose configuration it passed through.

4. What happens to a request inside a Cloudflare data center

Once the connection is terminated, the request moves through a fixed sequence of phases in Cloudflare’s Ruleset Engine, starting with redirects and URL normalization and ending with Workers. Understanding the order explains most real world bypasses, because a rule in an early phase can change what a later phase sees or whether it runs at all. The simplified request path looks like this:

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#ffffff','primaryTextColor':'#111111','primaryBorderColor':'#f6821f','lineColor':'#f6821f','secondaryColor':'#fff4e6','tertiaryColor':'#ffffff','clusterBkg':'#fff4e6','clusterBorder':'#f6821f','titleColor':'#b35400','edgeLabelBackground':'#ffffff','fontSize':'15px'}}}%%
flowchart TD
    A["TLS terminated at edge"] --> B["Single Redirects"]
    B --> C["URL normalization"]
    C --> D["URL Rewrite Rules"]
    D --> E["Configuration Rules"]
    E --> F["Origin Rules"]
    F --> G["Custom rules: WAF"]
    G --> H["Rate limiting rules"]
    H --> I["Managed rules: WAF"]
    I --> J["Super Bot Fight Mode"]
    J --> K["Access check, Bulk Redirects"]
    K --> L["Request header Transform Rules"]
    L --> M["Cache Rules and cache"]
    M --> N["Snippets, then Workers"]
    N --> O[("Origin")]

That sequence comes from Cloudflare’s published phases list, with Workers placed after the Ruleset Engine phases. Several consequences follow from this order, and they shape what an audit has to look for.

Configuration Rules and Origin Rules run before the WAF. A configuration rule can switch off Browser Integrity Check or downgrade the SSL mode for a hostname or path, and an origin rule can send matching requests to a completely different backend. Neither looks like a firewall rule in the dashboard, which is why they hide so well.

Within the WAF, custom rules run before rate limiting and managed rules, and a Skip action in a custom rule can bypass the rate limiting phase, Super Bot Fight Mode and the managed rules entirely, according to Cloudflare’s interoperability documentation. A skip keyed on a header, cookie or User-Agent therefore hands a master key to anyone who can type that value into curl.

Some older features do not use the Ruleset Engine at all. IP Access Rules, Zone Lockdown, User Agent Blocking, Browser Integrity Check and Security Level are evaluated independently of the phase order, and an IP Access allow rule exempts matching traffic from your security features, including the WAF. Bot Fight Mode also sits outside the phase system, and custom rules cannot skip it.

Finally, Workers and Snippets run after the WAF and can make their own subrequests. Cloudflare documents that a Worker or Snippet fetch() to the same zone is not evaluated by that zone’s custom or managed rules. A Worker that proxies a user supplied path back into your own site is therefore a WAF bypass you wrote yourself.

5. The five ways traffic gets around your WAF

Every finding in an audit like this lands in one of five buckets, and it helps to keep them separate because the fixes are different.

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#ffffff','primaryTextColor':'#111111','primaryBorderColor':'#f6821f','lineColor':'#f6821f','secondaryColor':'#fff4e6','tertiaryColor':'#ffffff','clusterBkg':'#fff4e6','clusterBorder':'#f6821f','titleColor':'#b35400','edgeLabelBackground':'#ffffff','fontSize':'15px'}}}%%
flowchart LR
    V["Visitor"] -->|"your hostname"| E1["Your Cloudflare zone<br/>your WAF rules"]
    E1 -->|"1 intended path"| O[("Origin")]
    X1["Attacker"] -->|"2 direct to origin IP"| O
    X2["Attacker"] -->|"3 own zone, WAF off"| E2["Attacker's Cloudflare zone"]
    E2 -->|"from shared Cloudflare IPs"| O
    X3["Attacker"] -->|"4 matches an exception"| E1
    X4["Attacker"] -->|"5 asks it to fetch a URL"| P["Proxy or integration<br/>inside a trusted network"]
    P -->|"trusted address: unchallenged"| E1
    P -.->|"trusted address: allowed directly"| O

The first bucket is direct origin access: the server answers on ports 80 or 443 to anyone, on IPv4, on IPv6, or through the hosting provider’s default hostname. The fix is network level, and it matters more than anything else in this post.

The second bucket is the shared infrastructure problem. An attacker who knows your origin IP signs up for a free Cloudflare account, adds a domain they control, points a proxied record at your IP and turns every security feature off. Their requests now arrive from genuine Cloudflare addresses, so a firewall that only allows Cloudflare’s ranges lets them straight in. Cloudflare’s own documentation is explicit that the global Authenticated Origin Pulls (AOP) certificate, the shared client certificate Cloudflare can present to origins, is used across all accounts and only proves a request came from the Cloudflare network, not from your account. Only a tunnel or a client certificate that belongs to you closes this one.

The third bucket is exceptions inside your own configuration: IP Access allow rules, Skip rules, managed rule overrides, Page Rules with Disable Security, configuration rules that turn off Browser Integrity Check or downgrade SSL, Access policies with a Bypass decision. These are usually added for a good reason and then outlive it.

The fourth bucket is logic that runs after or around the WAF: Workers, Snippets, Origin Rules and header Transform Rules. These do not skip the WAF so much as change where a request ends up or what the origin believes about it.

The fifth bucket combines the third with something that looks unrelated, and it is the one I would worry about most in a larger organisation. Many teams exempt their own addresses: a skip rule for the office range, a challenge rule written as “challenge everyone except our egress addresses”, or an origin firewall that allows Cloudflare and a corporate range so that internal systems can call the service directly. Each of those is defensible on its own. Now imagine that somewhere inside that trusted network there is a component that fetches URLs on someone else’s behalf: an open proxy left in an integration, a server side request forgery (SSRF) bug, a webhook tester, a link preview service, a marketing automation callback. Anyone on the internet who can make that component fetch a URL now sends requests from a trusted address. Depending on which trust you granted, those requests either pass your edge without a challenge, or skip Cloudflare entirely and land on the origin directly. The exemption and the proxy each look harmless in isolation, and the risk only appears when both exist in the same network.

One check separates those two outcomes: find the public address the fetching component leaves from, then ask whether your Cloudflare rules exempt it (an edge bypass) and whether your origin firewall admits it (a direct path that never meets Cloudflare). Section 6.6 has a script for exactly that.

6. Locking the origin: Cloudflare Tunnel or custom Authenticated Origin Pulls

Restricting inbound HTTP and HTTPS (Hypertext Transfer Protocol, plain and secure) at the host firewall to Cloudflare’s published ranges is necessary but, as section 5 explains, not sufficient on its own. You need one of two architectures on top of it, and for most single sites and small clusters the first is the cleaner answer.

6.1 Option A: Cloudflare Tunnel (preferred)

Cloudflare Tunnel runs a small daemon, cloudflared, on your server. It makes outbound connections to Cloudflare and receives requests through them, so the server does not need to accept any inbound web traffic at all. There is no public origin to find, no IP allowlist to maintain and no way for another Cloudflare account to route to you, because the tunnel is bound to your account’s credentials. The web server only listens on the loopback interface.

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#ffffff','primaryTextColor':'#111111','primaryBorderColor':'#f6821f','lineColor':'#f6821f','secondaryColor':'#fff4e6','tertiaryColor':'#ffffff','clusterBkg':'#fff4e6','clusterBorder':'#f6821f','titleColor':'#b35400','edgeLabelBackground':'#ffffff','fontSize':'15px'}}}%%
flowchart LR
    V["Visitor"] --> E["Cloudflare edge<br/>WAF, Access, cache"]
    E -->|"requests over the tunnel"| C
    subgraph SG1["Origin server, no inbound 80 or 443"]
        C["cloudflared"] -->|"http://127.0.0.1:8080"| W["Web server and application"]
    end
    C -.->|"outbound connections only"| E

The migration runs in three stages so the live site never depends on something you have not tested. First, add a loopback listener to your web server alongside the existing public one; both run side by side. A default server swallows any request with an unexpected Host header. Because the only thing that will connect to 127.0.0.1:8080 is cloudflared, it is safe to take the visitor address from CF-Connecting-IP here, and safe to tell the application that the request arrived over HTTPS, since Always Use HTTPS guarantees that at the edge. Those two decisions become vulnerabilities the moment the origin is publicly reachable, which section 6.4 covers. The example below is nginx in front of WordPress, running PHP (the language WordPress is written in). For any other application keep the listener, the default server, the real IP lines and the deny blocks, and replace the PHP section with your proxy_pass to the application server.

cat > wordpress.tunnel.nginx.conf << 'EOF'
# /etc/nginx/sites-available/example.com: WordPress example; for another app keep
# the listener, default server, real IP and deny blocks and change the app part.
# (tunnel mode)
# Only cloudflared on this host can reach 127.0.0.1:8080.

# Anything with an unexpected Host header gets nothing.
server {
    listen 127.0.0.1:8080 default_server;
    server_name _;
    return 444;
}

server {
    listen 127.0.0.1:8080;
    server_name example.com www.example.com;
    root /var/www/wordpress;
    index index.php;

    # Safe ONLY because the sole client is cloudflared on loopback.
    set_real_ip_from 127.0.0.1;
    real_ip_header CF-Connecting-IP;

    # Same denials as the edge rules, enforced at the origin too.
    # Delete this line if you passed --allow-xmlrpc (Jetpack or a publishing app).
    location = /xmlrpc.php            { deny all; }
    location = /wp-content/debug.log  { deny all; }
    location ~* ^/wp-config\.php      { deny all; }
    location ~ /\.(?!well-known/)     { deny all; }
    location ~* \.(sql|sql\.gz|bak)$  { deny all; }
    # Archives outside uploads (backup plugin dumps); uploads may hold real downloads.
    location ~* ^/(?!wp-content/uploads/).*\.(zip|tar\.gz|tgz)$ { deny all; }
    location ~* ^/wp-content/uploads/.*\.php { deny all; }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;   # adjust to your PHP version
        fastcgi_param HTTPS on;                         # the visitor used HTTPS at the edge
    }
}
EOF

Second, the setup script checks that the loopback listener answers, creates the tunnel with an ingress list that already includes the production hostnames and ends with a catch all 404 (so unknown hostnames never reach the application), and routes only a temporary validation hostname to it. That hostname reaches the application with the canonical Host header, so it renders the real site. Production DNS is not touched, and the script exits with an error if the temporary hostname does not answer with HTTP 200. Set EXPECT_TEXT to something every healthy page contains (wp-content works for WordPress) to make that check stricter.

cat > setup_tunnel.sh << 'EOF'
#!/usr/bin/env bash
# setup_tunnel.sh: stage 1 of the tunnel migration (any HTTP application). Creates the tunnel and runs it
# alongside the live site, routing ONLY a temporary validation hostname to it.
# Production DNS is not touched here; tunnel_cutover.py does that later, with a
# backup and an automatic rollback.
#
# Before running: make nginx listen on 127.0.0.1:8080 as well as on its current
# public listener (see the tunnel nginx config). Both can run side by side.
set -euo pipefail
TUNNEL_NAME="${TUNNEL_NAME:-example-com}"
HOSTNAMES="${HOSTNAMES:-example.com www.example.com}"
TEST_HOST="${TEST_HOST:-tunnel-check.example.com}"
CANONICAL="${CANONICAL:-example.com}"
LOCAL_ORIGIN="${LOCAL_ORIGIN:-http://127.0.0.1:8080}"
EXPECT_TEXT="${EXPECT_TEXT:-}"   # text a healthy page contains (WordPress: wp-content)

# 0. The local listener must already work, or there is nothing to validate.
code="$(curl -s -o /dev/null -w '%{http_code}' -H "Host: ${CANONICAL}" "${LOCAL_ORIGIN}/")"
case "$code" in
  200|301|302) echo "Local listener answers (${code})." ;;
  *) echo "Local listener ${LOCAL_ORIGIN} returned ${code}; fix nginx first."; exit 1 ;;
esac

if ! command -v cloudflared >/dev/null; then
  sudo mkdir -p --mode=0755 /usr/share/keyrings
  curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg >/dev/null
  echo "deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main" |
    sudo tee /etc/apt/sources.list.d/cloudflared.list
  sudo apt-get update && sudo apt-get install -y cloudflared
fi

# Opens a browser link; authorise the zone once. Stores cert.pem in ~/.cloudflared.
[ -f "$HOME/.cloudflared/cert.pem" ] || cloudflared tunnel login

cloudflared tunnel info "$TUNNEL_NAME" >/dev/null 2>&1 || cloudflared tunnel create "$TUNNEL_NAME"
TUNNEL_ID="$(cloudflared tunnel list --output json | python3 -c '
import json, sys
name = sys.argv[1]
print(next(t["id"] for t in json.load(sys.stdin) if t["name"] == name))' "$TUNNEL_NAME")"

sudo mkdir -p /etc/cloudflared
sudo cp "$HOME/.cloudflared/${TUNNEL_ID}.json" /etc/cloudflared/
sudo chmod 600 "/etc/cloudflared/${TUNNEL_ID}.json"

# Production hostnames are listed now so the cutover is only a DNS change.
# The test hostname reaches the app with the canonical Host header.
{
  echo "tunnel: ${TUNNEL_ID}"
  echo "credentials-file: /etc/cloudflared/${TUNNEL_ID}.json"
  echo "ingress:"
  for h in $HOSTNAMES; do
    echo "  - hostname: ${h}"
    echo "    service: ${LOCAL_ORIGIN}"
  done
  echo "  - hostname: ${TEST_HOST}"
  echo "    service: ${LOCAL_ORIGIN}"
  echo "    originRequest:"
  echo "      httpHostHeader: ${CANONICAL}"
  echo "  - service: http_status:404"
} | sudo tee /etc/cloudflared/config.yml

sudo cloudflared tunnel ingress validate --config /etc/cloudflared/config.yml
cloudflared tunnel route dns "$TUNNEL_NAME" "$TEST_HOST"
sudo cloudflared service install 2>/dev/null || sudo systemctl restart cloudflared
sudo systemctl enable --now cloudflared

echo "Waiting for the tunnel and the test hostname..."
for _ in $(seq 1 12); do
  code="$(curl -s -o /tmp/tunnel-check.html -w '%{http_code}' "https://${TEST_HOST}/" || true)"
  if [ "$code" = "200" ] && grep -qiF -- "${EXPECT_TEXT}" /tmp/tunnel-check.html; then
    echo "OK: https://${TEST_HOST}/ serves the site through the tunnel."
    echo "Tunnel ID: ${TUNNEL_ID}"
    echo "Next: python3 tunnel_cutover.py --zone ${CANONICAL} --tunnel-id ${TUNNEL_ID} --test-host ${TEST_HOST} ${EXPECT_TEXT:+--expect-text \"${EXPECT_TEXT}\"}"
    exit 0
  fi
  sleep 10
done
echo "Test hostname did not serve the site (last HTTP ${code}). Production is untouched."
echo "Check: sudo journalctl -u cloudflared -n 50"
exit 1
EOF
chmod +x setup_tunnel.sh

Third, the cutover script moves the production hostnames. It refuses to start unless the validation hostname is healthy, and saves every existing A and AAAA (IPv4 and IPv6 address) and CNAME (canonical name, an alias) record for those names to a backup file. It then makes the whole swap in a single call to Cloudflare’s batch DNS endpoint, which Cloudflare applies in one database transaction: either every old record is replaced by a proxied CNAME to the tunnel, or nothing changes. Doing the same swap as separate delete and create calls is the obvious approach and the dangerous one, because a failure between the two leaves a hostname with no record at all. Propagation from the database to the edge is still not atomic, so expect a few seconds in which some locations answer with the old records and some with the new.

The harder problem is an API call whose outcome you do not know: a timeout or a 5xx error after the request was sent. The script never trusts the response for that. After every write it reads the records back and acts on what is actually there. If they still match the backup, nothing was applied and it stops with production untouched. If they match the target, it carries on to the health check. Anything else is restored from the backup, and the restore is verified the same way and retried. If the batch is refused because Cloudflare will not delete and create the same name in one transaction, the script tries a second atomic shape that rewrites one existing record per hostname in place. If even a restore cannot be verified, because the API has stopped answering, it exits with code 4 and prints the backup path and the manual steps rather than guessing. The health check then tests the live site through Cloudflare for up to two minutes, and restores the backup if the site does not come back; --expect-text makes that check look for specific content rather than any HTTP 200.

The toolkit includes test_tunnel_cutover.py, which runs the cutover against a fake DNS API and injects each of those failures: rejected batches, timeouts before and after the write, a partial write, an unhealthy site, a failing restore and an API that stops answering mid incident. All ten cases must end in a known state, and the smoke test runs them on every edit. Leave the old public listener running for at least a day after the cutover, so a manual rollback has something to roll back to. Close the ports with the firewall script only after that, and delete the validation hostname with --cleanup-test-host.

cat > tunnel_cutover.py << 'EOF'
#!/usr/bin/env python3
"""
tunnel_cutover.py: stage 2 of the tunnel migration. Moves production hostnames
from their current DNS records to the tunnel, with a backup, atomic writes and a
verified rollback.

Dry run by default. Needs CF_API_TOKEN with DNS edit on the zone.

  python3 tunnel_cutover.py --zone example.com --tunnel-id <UUID> \
      --test-host tunnel-check.example.com                 # plan only
  python3 tunnel_cutover.py ... --apply                          # cut over
  python3 tunnel_cutover.py --zone example.com \
      --rollback backups/dns-before-tunnel-<ts>.json --apply     # restore
  python3 tunnel_cutover.py --zone example.com \
      --cleanup-test-host tunnel-check.example.com --apply # after a stable day

How it stays safe:
  * Every change is one call to the batch DNS endpoint, which Cloudflare applies
    in a single database transaction: all of it or none of it. (Propagation to
    the edge is still not atomic, so expect a few seconds of mixed answers.)
  * After every write, whatever the API said (success, error, timeout), the
    script re-reads the records and decides from what is actually there:
      original state -> nothing was applied, stop;
      target state   -> carry on to the health check;
      anything else  -> restore the backup.
  * A restore is verified the same way and retried. If it still cannot be
    verified, the script stops with exit code 4 and prints the backup path and
    the manual steps, rather than guessing.

Exit codes: 0 done, 1 stopped safely (production unchanged or restored),
2 usage, 3 setup error, 4 state could not be verified: act manually now.
"""
import argparse
import datetime as dt
import json
import os
import socket
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

API = "https://api.cloudflare.com/client/v4"
WEB_TYPES = ("A", "AAAA", "CNAME")
KEEP = ("type", "name", "content", "proxied", "ttl", "comment")


def call(method, path, body=None, params=None):
    """Returns (status, payload). Status 0 means the outcome is unknown."""
    url = API + path + ("?" + urllib.parse.urlencode(params) if params else "")
    req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
                                 method=method)
    req.add_header("Authorization", "Bearer " + os.environ["CF_API_TOKEN"])
    req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return r.status, json.loads(r.read().decode() or "{}")
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read().decode() or "{}")
        except Exception:
            return e.code, {"errors": [{"message": str(e)}]}
    except (urllib.error.URLError, socket.timeout, ConnectionError, OSError) as e:
        return 0, {"errors": [{"message": "no definite answer: %s" % e}]}


def errs(payload):
    return "; ".join(str(e.get("message", e)) for e in payload.get("errors") or []) or "unknown"


def read_records(zid, hosts, tries=3):
    """Current web records per host, or None if they cannot be read."""
    for attempt in range(tries):
        out, ok = {}, True
        for h in hosts:
            status, payload = call("GET", "/zones/%s/dns_records" % zid,
                                   params={"name": h, "per_page": 100})
            if status != 200:
                ok = False
                break
            out[h] = [r for r in payload.get("result") or [] if r["type"] in WEB_TYPES]
        if ok:
            return out
        time.sleep(2 * (attempt + 1))
    return None


def fingerprint(recs):
    return sorted((r["type"], r["content"].lower().rstrip("."), bool(r.get("proxied"))) for r in recs)


def classify(current, backup, target):
    """'original', 'target', 'mixed' or 'unknown' across all hosts."""
    if current is None:
        return "unknown"
    states = set()
    for h, recs in current.items():
        if fingerprint(recs) == fingerprint(backup["records"].get(h, [])):
            states.add("original")
        elif fingerprint(recs) == [("CNAME", target.lower(), True)]:
            states.add("target")
        else:
            states.add("other")
    return states.pop() if len(states) == 1 and "other" not in states else "mixed"


def batch(zid, body):
    status, payload = call("POST", "/zones/%s/dns_records/batch" % zid, body)
    if status == 200 and payload.get("success", True):
        return "ok", ""
    if status == 0 or status >= 500:
        return "uncertain", "HTTP %s %s" % (status, errs(payload))
    return "rejected", "HTTP %s %s" % (status, errs(payload))


def cname(h, target):
    return {"type": "CNAME", "name": h, "content": target, "proxied": True, "ttl": 1,
            "comment": "cloudflare tunnel cutover %s" % dt.date.today()}


def cutover_bodies(backup, target):
    """Two atomic ways to make the same swap. The first deletes the old records and
    creates the CNAMEs. The second rewrites one existing record per host in place
    and deletes the rest, for the case where the API refuses a delete and a create
    of the same name inside one batch. Either is all or nothing."""
    first = {"deletes": [{"id": r["id"]} for recs in backup["records"].values() for r in recs],
             "posts": [cname(h, target) for h in backup["records"]]}
    second = {"deletes": [], "puts": [], "posts": []}
    for h, recs in backup["records"].items():
        if recs:
            put = cname(h, target)
            put["id"] = recs[0]["id"]
            second["puts"].append(put)
            second["deletes"] += [{"id": r["id"]} for r in recs[1:]]
        else:
            second["posts"].append(cname(h, target))
    return [("delete and create", first), ("rewrite in place", second)]


def restore(zid, hosts, backup, target, tries=3):
    """Put the backup back and prove it. Returns True only when verified."""
    for attempt in range(1, tries + 1):
        current = read_records(zid, hosts)
        if classify(current, backup, target) == "original":
            print("restore verified: records match the backup")
            return True
        if current is None:
            print("restore attempt %d: cannot read current records" % attempt)
            time.sleep(5 * attempt)
            continue
        body = {"deletes": [{"id": r["id"]} for recs in current.values() for r in recs],
                "posts": [{k: r[k] for k in KEEP if k in r and r[k] is not None}
                          for recs in backup["records"].values() for r in recs]}
        outcome, detail = batch(zid, body)
        print("restore attempt %d: %s %s" % (attempt, outcome, detail))
        time.sleep(2)
    current = read_records(zid, hosts)
    if classify(current, backup, target) == "original":
        print("restore verified: records match the backup")
        return True
    return False


def manual_help(path, zone):
    print("\nSTATE NOT VERIFIED. Act now:")
    print("  1. Check the records in the dashboard: DNS > Records for %s." % zone)
    print("  2. Restore from the backup: python3 tunnel_cutover.py --zone %s --rollback %s --apply"
          % (zone, path))
    print("  3. If the API is down, recreate the records in the backup file by hand.")


EXPECT_TEXT = ""


def healthy(host, tries=1, wait=10):
    last = ""
    for i in range(tries):
        try:
            req = urllib.request.Request("https://%s/" % host,
                                         headers={"User-Agent": "tunnel-cutover-check"})
            with urllib.request.urlopen(req, timeout=20) as r:
                body = r.read(200000).decode(errors="ignore")
                if r.status == 200 and EXPECT_TEXT in body:
                    return True, "HTTP 200%s" % (" containing %r" % EXPECT_TEXT if EXPECT_TEXT else "")
                last = "HTTP %s without %r" % (r.status, EXPECT_TEXT) if r.status == 200 \
                    else "HTTP %s" % r.status
        except Exception as e:
            last = str(e)
        if i + 1 < tries:
            time.sleep(wait)
    return False, last


def main():
    ap = argparse.ArgumentParser(description="Cut production hostnames over to Cloudflare Tunnel")
    ap.add_argument("--zone", required=True)
    ap.add_argument("--tunnel-id")
    ap.add_argument("--hostname", action="append", help="Default: zone and www")
    ap.add_argument("--test-host", help="Hostname already routed to the tunnel (preflight)")
    ap.add_argument("--expect-text", default="",
                    help="Text a healthy page must contain (for WordPress: wp-content). "
                         "Default: any HTTP 200")
    ap.add_argument("--skip-preflight", action="store_true")
    ap.add_argument("--no-auto-rollback", action="store_true")
    ap.add_argument("--rollback", metavar="BACKUP_JSON")
    ap.add_argument("--cleanup-test-host", metavar="HOST")
    ap.add_argument("--backup-dir", default="backups")
    ap.add_argument("--apply", action="store_true")
    a = ap.parse_args()
    global EXPECT_TEXT
    EXPECT_TEXT = a.expect_text
    if "CF_API_TOKEN" not in os.environ:
        print("Set CF_API_TOKEN (DNS edit on the zone).", file=sys.stderr)
        return 3
    status, payload = call("GET", "/zones", params={"name": a.zone})
    if status != 200 or not payload.get("result"):
        print("zone lookup failed: %s" % errs(payload), file=sys.stderr)
        return 3
    zid = payload["result"][0]["id"]
    mode = "APPLY" if a.apply else "DRY RUN"

    if a.rollback:
        backup = json.load(open(a.rollback))
        hosts = list(backup["records"])
        for h in hosts:
            print("[%s] restore %s -> %s" % (mode, h, ", ".join(
                "%s %s" % (r["type"], r["content"]) for r in backup["records"][h]) or "no records"))
        if not a.apply:
            return 0
        if restore(zid, hosts, backup, backup.get("tunnel_target", "")):
            return 0
        manual_help(a.rollback, a.zone)
        return 4

    if a.cleanup_test_host:
        current = read_records(zid, [a.cleanup_test_host]) or {}
        ids = [{"id": r["id"]} for r in current.get(a.cleanup_test_host, [])]
        print("[%s] delete %d record(s) for %s" % (mode, len(ids), a.cleanup_test_host))
        if a.apply and ids:
            outcome, detail = batch(zid, {"deletes": ids})
            print("%s %s" % (outcome, detail))
            return 0 if outcome == "ok" else 1
        return 0

    if not a.tunnel_id:
        ap.error("--tunnel-id is required for a cutover")
    hosts = a.hostname or [a.zone, "www." + a.zone]
    target = "%s.cfargotunnel.com" % a.tunnel_id

    if not a.skip_preflight:
        if not a.test_host:
            ap.error("--test-host is required unless --skip-preflight")
        ok, why = healthy(a.test_host, tries=3)
        print("preflight %s: %s" % (a.test_host, why))
        if not ok:
            print("Preflight failed; production untouched.")
            return 1

    current = read_records(zid, hosts)
    if current is None:
        print("Cannot read the current records; production untouched.")
        return 1
    backup = {"created_utc": dt.datetime.now(dt.timezone.utc).isoformat(), "zone": a.zone,
              "tunnel_target": target, "records": current}
    for h in hosts:
        print("current %s: %s" % (h, ", ".join("%s %s proxied=%s" % (r["type"], r["content"],
                                                                   r.get("proxied"))
                                               for r in current[h]) or "none"))
    os.makedirs(a.backup_dir, exist_ok=True)
    path = os.path.join(a.backup_dir, "dns-before-tunnel-%s.json"
                        % dt.datetime.now().strftime("%Y%m%d-%H%M%S"))
    with open(path, "w") as fh:
        json.dump(backup, fh, indent=2)
    print("backup written: %s" % path)
    for h in hosts:
        print("[%s] %s -> CNAME %s (proxied)" % (mode, h, target))
    if not a.apply:
        print("Dry run only. Rerun with --apply. Rollback: --rollback %s --apply" % path)
        return 0

    state = "original"
    for label, body in cutover_bodies(backup, target):
        outcome, detail = batch(zid, body)
        print("batch (%s): %s %s" % (label, outcome, detail))
        state = classify(read_records(zid, hosts), backup, target)
        print("records now: %s" % state)
        if state == "target":
            break
        if state == "original" and outcome == "rejected":
            continue            # nothing applied; try the in place variant
        break
    if state == "original":
        print("Nothing was applied; production untouched.")
        return 1
    if state != "target":
        print("Records are in an unexpected state (%s); restoring the backup." % state)
        if restore(zid, hosts, backup, target):
            return 1
        manual_help(path, a.zone)
        return 4

    failed = []
    for h in hosts:
        ok, why = healthy(h, tries=12)
        print("health %s: %s" % (h, why))
        if not ok:
            failed.append(h)
    if failed:
        if a.no_auto_rollback:
            print("Unhealthy: %s. Auto rollback disabled; backup: %s" % (", ".join(failed), path))
            return 1
        print("Unhealthy after cutover (%s); restoring the backup." % ", ".join(failed))
        if restore(zid, hosts, backup, target):
            return 1
        manual_help(path, a.zone)
        return 4
    print("Cutover complete. Keep the old listener for a day, then run the firewall step.")
    print("Rollback if needed: python3 tunnel_cutover.py --zone %s --rollback %s --apply"
          % (a.zone, path))
    return 0


if __name__ == "__main__":
    sys.exit(main())
EOF
chmod +x tunnel_cutover.py
cat > test_tunnel_cutover.py << 'EOF'
#!/usr/bin/env python3
"""test_tunnel_cutover.py: failure injection for tunnel_cutover.py.

Runs the cutover against a fake DNS API that applies batches as transactions,
then breaks it in every way that matters: rejected batches, timeouts after and
before the write, a partial write, an unhealthy site, a failing restore and an
API that stops answering. Each case must end in a known state: switched over,
untouched, restored and verified, or exit code 4 with manual instructions.
No network or token needed; smoke_test.sh runs it."""
import contextlib
import copy
import io
import os
import sys
import tempfile

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import tunnel_cutover as t

t.time.sleep = lambda *_: None
os.environ["CF_API_TOKEN"] = "x"
ORIGINAL = {
    "example.com": [{"id": "a1", "type": "A", "name": "example.com", "content": "203.0.113.10", "proxied": True, "ttl": 1},
                          {"id": "a2", "type": "AAAA", "name": "example.com", "content": "2001:db8::10", "proxied": True, "ttl": 1}],
    "www.example.com": [{"id": "w1", "type": "CNAME", "name": "www.example.com", "content": "example.com", "proxied": True, "ttl": 1}],
}


class FakeDNS:
    def __init__(self, script):
        self.db = copy.deepcopy(ORIGINAL)
        self.script = list(script)   # behaviour per batch call
        self.next_id = 100
        self.reads_fail = False

    def apply(self, body):
        db = copy.deepcopy(self.db)
        for d in body.get("deletes", []):
            for h in db:
                db[h] = [r for r in db[h] if r["id"] != d["id"]]
        for p in body.get("puts", []):
            for h in db:
                for i, r in enumerate(db[h]):
                    if r["id"] == p["id"]:
                        db[h][i] = dict(p)
        for p in body.get("posts", []):
            self.next_id += 1
            r = dict(p)
            r["id"] = str(self.next_id)
            db.setdefault(p["name"], []).append(r)
        return db

    def partial(self, body):          # deletes applied, nothing else (no transaction)
        return self.apply({"deletes": body.get("deletes", [])})

    def call(self, method, path, body=None, params=None):
        if path == "/zones":
            return 200, {"result": [{"id": "z"}]}
        if method == "GET":
            if self.reads_fail:
                return 0, {"errors": [{"message": "timeout"}]}
            return 200, {"result": copy.deepcopy(self.db.get(params["name"], []))}
        if path.endswith("/batch"):
            how = self.script.pop(0) if self.script else "ok"
            if how == "ok":
                self.db = self.apply(body); return 200, {"success": True}
            if how == "reject_same_name" and body.get("posts") and body.get("deletes") and not body.get("puts"):
                return 400, {"errors": [{"message": "record with that host already exists"}]}
            if how == "reject_same_name":
                self.db = self.apply(body); return 200, {"success": True}
            if how == "reject":
                return 400, {"errors": [{"message": "rejected"}]}
            if how == "timeout_applied":
                self.db = self.apply(body); return 0, {"errors": [{"message": "timed out"}]}
            if how == "timeout_not_applied":
                return 0, {"errors": [{"message": "timed out"}]}
            if how == "500_partial":
                self.db = self.partial(body); return 500, {"errors": [{"message": "internal"}]}
            if how == "fail_and_break_reads":
                self.db = self.partial(body); self.reads_fail = True
                return 500, {"errors": [{"message": "internal"}]}
        raise AssertionError((method, path))


FAILURES = []


def run(name, script, health=True, expect_rc=None, expect_state=None):
    dns = FakeDNS(script)
    t.call = dns.call
    t.healthy = lambda h, tries=1, wait=10: (h.startswith("tunnel-check") or health, "mock")
    sys.argv = ["x", "--zone", "example.com", "--tunnel-id", "UUID", "--test-host",
                "tunnel-check.example.com", "--apply", "--backup-dir", tempfile.mkdtemp()]
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        rc = t.main()
    dns.reads_fail = False
    final = {h: sorted((r["type"], r["content"]) for r in v) for h, v in dns.db.items()}
    orig = {h: sorted((r["type"], r["content"]) for r in v) for h, v in ORIGINAL.items()}
    tgt = {h: [("CNAME", "UUID.cfargotunnel.com")] for h in ORIGINAL}
    state = "original" if final == orig else "target" if final == tgt else "OTHER %s" % final
    ok = (expect_rc is None or rc == expect_rc) and (expect_state is None or state == expect_state)
    print("%-4s %-52s rc=%s final=%s" % ("ok" if ok else "BAD", name, rc, state))
    if not ok:
        FAILURES.append(name)
        print(buf.getvalue())


run("success", ["ok"], expect_rc=0, expect_state="target")
run("same name delete+create refused, in place rewrite used", ["reject_same_name", "reject_same_name"], expect_rc=0, expect_state="target")
run("both batch shapes rejected: untouched", ["reject", "reject"], expect_rc=1, expect_state="original")
run("timeout but applied: verified, continues", ["timeout_applied"], expect_rc=0, expect_state="target")
run("timeout and not applied: untouched", ["timeout_not_applied"], expect_rc=1, expect_state="original")
run("500 after a partial write (delete, no create): restored", ["500_partial", "ok"], expect_rc=1, expect_state="original")
run("unhealthy after cutover: restored", ["ok", "ok"], health=False, expect_rc=1, expect_state="original")
run("restore batch times out but applied: verified", ["ok", "timeout_applied"], health=False, expect_rc=1, expect_state="original")
run("restore keeps failing: exit 4, manual steps", ["500_partial", "reject", "reject", "reject"], expect_rc=4)
run("reads break mid incident: exit 4", ["fail_and_break_reads"], expect_rc=4)

sys.exit(1 if FAILURES else 0)
EOF
chmod +x test_tunnel_cutover.py

One operational note: Cloudflare’s documentation warns that if you use Super Bot Fight Mode alongside a tunnel, the Definitely Automated setting should stay on Allow, otherwise tunnels can fail with a websocket: bad handshake error.

6.2 Option B: custom Authenticated Origin Pulls

If the host cannot run cloudflared, keep the origin public but make it demand a client certificate that only your Cloudflare zone holds. This is mutual TLS (mTLS): the origin authenticates Cloudflare in the same handshake in which Cloudflare authenticates the origin.

Two points trip people up here. A Cloudflare Origin CA certificate is a server certificate installed on your origin so that Cloudflare can validate it under Full (strict); an AOP certificate is a client certificate that Cloudflare presents to your origin. They authenticate opposite ends of the connection and are not interchangeable. And the shared global AOP certificate is not enough, for the reason in section 5. Generate your own certificate authority (CA) and a leaf client certificate signed by it:

cat > make_aop_cert.sh << 'EOF'
#!/usr/bin/env bash
# make_aop_cert.sh: create a private CA and a client certificate for zone level
# Authenticated Origin Pulls. Keep rootca.key offline; only rootca.crt goes on
# the origin, and only client.crt plus client.key go to Cloudflare.
set -euo pipefail
DOMAIN="${DOMAIN:-example.com}"
DIR="${DIR:-cf-aop}"
mkdir -p "$DIR" && cd "$DIR"
umask 077

# 1. Private CA (passphrase protected), valid five years.
openssl genrsa -aes256 -out rootca.key 4096
openssl req -x509 -new -key rootca.key -sha256 -days 1826 \
  -subj "/CN=${DOMAIN} origin pull CA" -out rootca.crt

# 2. Leaf client certificate Cloudflare will present, valid two years.
openssl req -new -nodes -newkey rsa:4096 -keyout client.key \
  -subj "/CN=cloudflare-aop.${DOMAIN}" -out client.csr
cat > client.v3.ext << 'EXT'
basicConstraints=CA:FALSE
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=clientAuth
EXT
openssl x509 -req -in client.csr -CA rootca.crt -CAkey rootca.key -CAcreateserial \
  -days 730 -sha256 -extfile client.v3.ext -out client.crt

openssl verify -CAfile rootca.crt client.crt
echo "Upload: python3 cf_harden.py --zone ${DOMAIN} --apply --aop-cert ${DIR}/client.crt --aop-key ${DIR}/client.key"
echo "Origin: copy ${DIR}/rootca.crt to /etc/ssl/cf-aop/rootca.crt"
echo "Diary: client.crt expires $(openssl x509 -enddate -noout -in client.crt | cut -d= -f2)"
EOF
chmod +x make_aop_cert.sh

Upload client.crt and client.key to Cloudflare as a zone level AOP certificate (the hardening script in section 10 does this with --aop-cert), enable zone level AOP, and only then make the origin enforce it. Cloudflare’s own guidance is to start with verification set to optional, confirm the certificate arrives, and then require it. The nginx configuration below also rejects TLS handshakes for unknown server names, so scanning the IP with a random SNI (Server Name Indication) gets nothing back.

cat > wordpress.aop.nginx.conf << 'EOF'
# /etc/nginx/sites-available/example.com: WordPress example; for another app keep
# the listener, default server, real IP and deny blocks and change the app part.
# (custom AOP mode)
# Generate the real_ip include with:
#   curl -s https://www.cloudflare.com/ips-v{4,6} | sed 's/^/set_real_ip_from /; s/$/;/' \
#     > /etc/nginx/cloudflare-realip.conf

# Unknown server names: refuse the TLS handshake outright (nginx 1.19.4+).
server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    ssl_reject_handshake on;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com www.example.com;
    root /var/www/wordpress;
    index index.php;

    # Server certificate Cloudflare validates under Full (strict): Origin CA is fine.
    ssl_certificate     /etc/ssl/cf-origin/origin.pem;
    ssl_certificate_key /etc/ssl/cf-origin/origin.key;
    ssl_protocols TLSv1.2 TLSv1.3;

    # Client certificate Cloudflare presents: trust ONLY your own CA.
    # Start with "optional", confirm $ssl_client_verify is SUCCESS in the logs,
    # then switch to "on".
    ssl_client_certificate /etc/ssl/cf-aop/rootca.crt;
    ssl_verify_client on;
    ssl_verify_depth 1;

    # Trust CF-Connecting-IP only from Cloudflare ranges, on an authenticated connection.
    include /etc/nginx/cloudflare-realip.conf;
    real_ip_header CF-Connecting-IP;

    # Delete this line if you passed --allow-xmlrpc (Jetpack or a publishing app).
    location = /xmlrpc.php            { deny all; }
    location = /wp-content/debug.log  { deny all; }
    location ~* ^/wp-config\.php      { deny all; }
    location ~ /\.(?!well-known/)     { deny all; }
    location ~* \.(sql|sql\.gz|bak)$  { deny all; }
    # Archives outside uploads (backup plugin dumps); uploads may hold real downloads.
    location ~* ^/(?!wp-content/uploads/).*\.(zip|tar\.gz|tgz)$ { deny all; }
    location ~* ^/wp-content/uploads/.*\.php { deny all; }

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;   # adjust to your PHP version
    }
}
# No port 80 server block: plain HTTP to the origin is closed at the firewall.
EOF

On Apache the equivalent is SSLVerifyClient require, SSLVerifyDepth 1 and SSLCACertificateFile /etc/ssl/cf-aop/rootca.crt inside the virtual host, with mod_remoteip trusting only Cloudflare’s ranges for CF-Connecting-IP. In this option you still restrict ports 80 and 443 to Cloudflare’s ranges, and you close port 80 entirely, since a client certificate cannot be required on plain HTTP.

6.3 The host firewall

The firewall script handles both options. In tunnel mode it drops all inbound 80 and 443 (including QUIC, the UDP (User Datagram Protocol) based transport under HTTP/3, on port 443) apart from loopback. In nft mode (nftables, the packet filter in modern Linux kernels), ufw mode (Uncomplicated Firewall, the Ubuntu front end to the same filter) or aws mode it fetches Cloudflare’s current published ranges and allows only those. It defaults to a dry run, so you can read exactly what it will do first. Keep an SSH (Secure Shell) session open while you apply it, and if you are on AWS (Amazon Web Services) Lightsail rather than EC2 (Elastic Compute Cloud), set the equivalent rules in the Lightsail networking tab instead of using the aws mode.

cat > origin_firewall.sh << 'EOF'
#!/usr/bin/env bash
# origin_firewall.sh: restrict inbound web traffic on the origin.
#
#   sudo ./origin_firewall.sh tunnel  [--apply]   # close 80/443 completely (Cloudflare Tunnel)
#   sudo ./origin_firewall.sh nft     [--apply]   # allow 80/443 only from Cloudflare (nftables)
#   sudo ./origin_firewall.sh ufw     [--apply]   # same, using ufw
#        ./origin_firewall.sh aws SG_ID [--apply] # same, for an AWS security group (aws cli)
#
# Dry run by default: prints what it would do. Keep an SSH session open while
# you apply it, and remember that a Cloudflare IP allowlist on its own still
# admits every Cloudflare customer. Pair it with zone level AOP, or use a tunnel.
set -euo pipefail

MODE="${1:-}"; shift || true
SG_ID=""
if [ "$MODE" = "aws" ]; then SG_ID="${1:-}"; shift || true; fi
APPLY=0; [ "${1:-}" = "--apply" ] && APPLY=1
PORTS="80,443"

run() { if [ "$APPLY" = "1" ]; then echo "+ $*"; eval "$@"; else echo "would run: $*"; fi; }

fetch_ranges() {
  V4="$(curl -fsS --max-time 15 https://www.cloudflare.com/ips-v4)"
  V6="$(curl -fsS --max-time 15 https://www.cloudflare.com/ips-v6)"
  [ -n "$V4" ] && [ -n "$V6" ] || { echo "could not fetch Cloudflare ranges"; exit 1; }
  echo "Cloudflare ranges: $(echo "$V4" | wc -l) IPv4, $(echo "$V6" | wc -l) IPv6"
}

case "$MODE" in
  tunnel)
    # cloudflared dials out, so nothing needs to reach 80/443 from outside.
    conf="table inet origin_lockdown {
  chain input {
    type filter hook input priority -10; policy accept;
    iifname \"lo\" accept
    tcp dport { ${PORTS} } drop
    udp dport 443 drop
  }
}"
    echo "$conf"
    if [ "$APPLY" = "1" ]; then
      nft delete table inet origin_lockdown 2>/dev/null || true
      echo "$conf" | nft -f -
      echo "Applied. Persist it by adding the table to /etc/nftables.conf."
    fi
    ;;
  nft)
    fetch_ranges
    conf="table inet origin_lockdown {
  set cf4 { type ipv4_addr; flags interval; elements = { $(echo $V4 | tr ' ' ',') } }
  set cf6 { type ipv6_addr; flags interval; elements = { $(echo $V6 | tr ' ' ',') } }
  chain input {
    type filter hook input priority -10; policy accept;
    iifname \"lo\" accept
    tcp dport { ${PORTS} } ip saddr @cf4 accept
    tcp dport { ${PORTS} } ip6 saddr @cf6 accept
    tcp dport { ${PORTS} } drop
    udp dport 443 drop
  }
}"
    echo "$conf"
    if [ "$APPLY" = "1" ]; then
      nft delete table inet origin_lockdown 2>/dev/null || true
      echo "$conf" | nft -f -
      echo "Applied. Refresh the ranges weekly (cron) and persist in /etc/nftables.conf."
    fi
    ;;
  ufw)
    fetch_ranges
    for p in 80 443 "80/tcp" "443/tcp" http https "Nginx Full" "Apache Full"; do
      run "ufw delete allow '$p' 2>/dev/null || true"
    done
    for cidr in $V4 $V6; do
      run "ufw allow proto tcp from $cidr to any port ${PORTS} comment cloudflare"
    done
    run "ufw reload"
    ;;
  aws)
    [ -n "$SG_ID" ] || { echo "usage: $0 aws sg-0123456789 [--apply]"; exit 2; }
    fetch_ranges
    for port in 80 443; do
      run "aws ec2 revoke-security-group-ingress --group-id $SG_ID --protocol tcp --port $port --cidr 0.0.0.0/0 || true"
      run "aws ec2 revoke-security-group-ingress --group-id $SG_ID --ip-permissions IpProtocol=tcp,FromPort=$port,ToPort=$port,Ipv6Ranges='[{CidrIpv6=::/0}]' || true"
      for cidr in $V4; do
        run "aws ec2 authorize-security-group-ingress --group-id $SG_ID --ip-permissions IpProtocol=tcp,FromPort=$port,ToPort=$port,IpRanges='[{CidrIp=$cidr,Description=cloudflare}]'"
      done
      for cidr in $V6; do
        run "aws ec2 authorize-security-group-ingress --group-id $SG_ID --ip-permissions IpProtocol=tcp,FromPort=$port,ToPort=$port,Ipv6Ranges='[{CidrIpv6=$cidr,Description=cloudflare}]'"
      done
    done
    ;;
  *)
    sed -n '2,12p' "$0"; exit 2 ;;
esac
EOF
chmod +x origin_firewall.sh

6.4 Header trust at the origin

Once the network path is locked, check what the origin believes. Headers such as CF-Connecting-IP, True-Client-IP, X-Forwarded-For, X-Real-IP, X-Forwarded-Host, X-Forwarded-Proto and Forwarded are just text a client can send. They are trustworthy only when they arrive over a connection you have authenticated, which means loopback from cloudflared, or a connection that has passed client certificate verification. Look in four places: the web server (real_ip_header and set_real_ip_from in nginx, RemoteIPHeader in Apache), the application’s own proxy settings (server.forward-headers-strategy in Spring Boot, trust proxy in Express, the $_SERVER['HTTPS'] = 'on' snippet in WordPress’s wp-config.php), any security plugin or middleware with a “how should we detect the visitor IP” setting, and any rate limiting or allow list code. If the web server already resolves the visitor address from a trusted proxy, make everything downstream use that resolved address (REMOTE_ADDR in PHP) so nothing parses the headers itself.

6.5 When the origin is a cloud load balancer

Larger deployments rarely expose a single server. More often Cloudflare sends traffic to a public cloud load balancer, which forwards it to a cluster, and that load balancer is frequently shared by several services. Three things change. The “host firewall” is now the load balancer’s security group, so every source range on it must be either a Cloudflare range or a deliberate, documented exception, and every exception reaches every service behind that listener, not only the one it was added for. Address based trust in Cloudflare is exactly as weak here as it is on a single server, but AWS Application Load Balancers support mutual TLS in verify mode against a trust store, so you can load the CA from section 6.2 into a trust store and require your own Cloudflare client certificate at the load balancer. Alternatively, run cloudflared as a deployment inside the cluster, point it at the ingress service, and remove the public load balancer altogether. Finally, switch the load balancer’s access logs on. If they are off, the only record of who reached the services is whatever the ingress and flow logs happen to keep, and flow logs carry addresses, not requests.

The script below reviews a load balancer read only: it lists every source range allowed on the listener ports and labels each one Cloudflare or not, reports the mutual TLS mode of each listener and whether access logs are on, and, given one or more egress addresses, says whether each would be admitted directly.

cat > aws_origin_check.sh << 'EOF'
#!/usr/bin/env bash
# aws_origin_check.sh: read only review of an AWS load balancer that sits behind
# Cloudflare. It answers four questions:
#   1. Which source ranges can reach the listeners, and which are NOT Cloudflare?
#      Every non Cloudflare range is a path that never meets your WAF.
#   2. Does the load balancer require a client certificate (mTLS verify mode),
#      or does it trust Cloudflare by address alone?
#   3. Are access logs on? Without them there is no record of who got in.
#   4. Optional: would a given egress address be let straight in?
#
#   ./aws_origin_check.sh my-public-alb [EGRESS_IP ...]
#
# Needs: aws cli (read only credentials: elasticloadbalancing:Describe*,
# ec2:DescribeSecurityGroups, ec2:GetManagedPrefixListEntries), curl, python3.
set -uo pipefail
LB="${1:?usage: $0 <load-balancer-name> [egress-ip ...]}"; shift
EGRESS="$*"
OUT="${OUT:-lb-check-$(date -u +%Y%m%d-%H%M%S).md}"

lb_json="$(aws elbv2 describe-load-balancers --names "$LB" --output json)" || exit 3
arn="$(printf '%s' "$lb_json" | python3 -c 'import json,sys; print(json.load(sys.stdin)["LoadBalancers"][0]["LoadBalancerArn"])')"
sgs="$(printf '%s' "$lb_json" | python3 -c 'import json,sys; print(" ".join(json.load(sys.stdin)["LoadBalancers"][0].get("SecurityGroups", [])))')"
attrs="$(aws elbv2 describe-load-balancer-attributes --load-balancer-arn "$arn" --output json)"
listeners="$(aws elbv2 describe-listeners --load-balancer-arn "$arn" --output json)"
sg_json='{"SecurityGroups": []}'
[ -n "$sgs" ] && sg_json="$(aws ec2 describe-security-groups --group-ids $sgs --output json)"

# Expand any prefix lists referenced by the security groups.
pl_ids="$(printf '%s' "$sg_json" | python3 -c '
import json, sys
ids = {p["PrefixListId"] for g in json.load(sys.stdin)["SecurityGroups"]
       for perm in g["IpPermissions"] for p in perm.get("PrefixListIds", [])}
print(" ".join(sorted(ids)))')"
pl_json="{}"
if [ -n "$pl_ids" ]; then
  pl_json="$(for id in $pl_ids; do
    printf '"%s": ' "$id"; aws ec2 get-managed-prefix-list-entries --prefix-list-id "$id" --output json; echo ','
  done | sed '$ s/,$//' | { echo '{'; cat; echo '}'; })"
fi
cf_ranges="$(curl -fsS --max-time 15 https://api.cloudflare.com/client/v4/ips)" || exit 3

export LB EGRESS OUT lb_json attrs listeners sg_json pl_json cf_ranges
python3 - << 'PY'
import ipaddress, json, os, sys
cf = json.loads(os.environ["cf_ranges"])["result"]
cf_nets = [ipaddress.ip_network(c) for c in cf["ipv4_cidrs"] + cf["ipv6_cidrs"]]
lb = json.loads(os.environ["lb_json"])["LoadBalancers"][0]
attrs = {a["Key"]: a["Value"] for a in json.loads(os.environ["attrs"])["Attributes"]}
listeners = json.loads(os.environ["listeners"])["Listeners"]
groups = json.loads(os.environ["sg_json"])["SecurityGroups"]
plists = json.loads(os.environ["pl_json"] or "{}")
egress = [ipaddress.ip_address(e) for e in os.environ["EGRESS"].split()]
ports = {l["Port"] for l in listeners}

def is_cf(net):
    return any(net.version == c.version and net.subnet_of(c) for c in cf_nets)

findings, sources = [], []
for g in groups:
    for perm in g["IpPermissions"]:
        lo, hi = perm.get("FromPort", 0), perm.get("ToPort", 65535)
        proto = perm.get("IpProtocol")
        if proto not in ("tcp", "-1") or not any(lo <= p <= hi for p in ports) and proto != "-1":
            continue
        cidrs = [(r["CidrIp"], r.get("Description", "")) for r in perm.get("IpRanges", [])]
        cidrs += [(r["CidrIpv6"], r.get("Description", "")) for r in perm.get("Ipv6Ranges", [])]
        for p in perm.get("PrefixListIds", []):
            for e in plists.get(p["PrefixListId"], {}).get("Entries", []):
                cidrs.append((e["Cidr"], "prefix list %s %s" % (p["PrefixListId"], e.get("Description", ""))))
        for pair in perm.get("UserIdGroupPairs", []):
            sources.append((g["GroupId"], "%s-%s" % (lo, hi), "security group " + pair["GroupId"], "n/a", ""))
        for cidr, desc in cidrs:
            net = ipaddress.ip_network(cidr, strict=False)
            kind = "cloudflare" if is_cf(net) else "NOT CLOUDFLARE"
            sources.append((g["GroupId"], "%s-%s" % (lo, hi), cidr, kind, desc))
            if kind != "cloudflare":
                sev = "CRITICAL" if net.prefixlen == 0 else "HIGH"
                findings.append((sev, "Range %s (%s) reaches the load balancer without passing "
                                 "Cloudflare. Anything in it that proxies or fetches URLs for "
                                 "others is a direct path to every service behind this listener."
                                 % (cidr, desc or "no description")))

mtls = {l["Port"]: (l.get("MutualAuthentication") or {}).get("Mode", "off") for l in listeners}
for port, mode in mtls.items():
    if mode != "verify":
        findings.append(("HIGH", "Listener %s has mutual TLS mode '%s'. Trust in Cloudflare is by "
                         "address only, so another Cloudflare account pointed at this load balancer "
                         "arrives from a trusted address. Use verify mode with a trust store holding "
                         "your own AOP CA, or move to Cloudflare Tunnel." % (port, mode)))
if attrs.get("access_logs.s3.enabled") != "true":
    findings.append(("HIGH", "Access logs are off. If something does get through, there is no "
                     "load balancer record of it."))
if attrs.get("routing.http.drop_invalid_header_fields.enabled") not in ("true", None):
    findings.append(("LOW", "Invalid header fields are not dropped."))
for ip in egress:
    allowed = [s for s in sources if s[3] != "n/a" and ip.version == ipaddress.ip_network(s[2], strict=False).version
               and ip in ipaddress.ip_network(s[2], strict=False)]
    if allowed:
        kinds = {a[3] for a in allowed}
        if "NOT CLOUDFLARE" in kinds:
            findings.append(("CRITICAL", "Egress address %s is allowed DIRECTLY by %s: it can reach "
                             "the services without meeting Cloudflare." % (ip, ", ".join(a[2] for a in allowed))))
        else:
            findings.append(("INFO", "Egress address %s is a Cloudflare address." % ip))
    else:
        findings.append(("INFO", "Egress address %s is not allowed directly; any bypass from it "
                         "must be happening at the edge (check cf_audit.py --egress-ip)." % ip))

order = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]
findings.sort(key=lambda f: order.index(f[0]))
lines = ["# Load balancer review: %s" % os.environ["LB"], "",
         "Scheme %s, type %s, listeners %s." % (lb.get("Scheme"), lb.get("Type"), sorted(ports)), "",
         "## Findings", ""]
lines += ["- **%s** %s" % f for f in findings] or ["- none"]
lines += ["", "## Sources allowed on listener ports", "",
          "| Security group | Ports | Source | Classification | Description |", "|---|---|---|---|---|"]
lines += ["| %s | %s | %s | %s | %s |" % s for s in sources]
lines += ["", "Listener mutual TLS: " + ", ".join("%s=%s" % kv for kv in sorted(mtls.items())),
          "Access logs: %s" % attrs.get("access_logs.s3.enabled"), "",
          "Note: one load balancer shared by many services shares its exposure too. A range "
          "added for one service reaches every service behind the same listener."]
open(os.environ["OUT"], "w").write("\n".join(lines) + "\n")
print("\n".join(lines))
sys.exit(2 if findings and findings[0][0] == "CRITICAL" else 1 if any(f[0] == "HIGH" for f in findings) else 0)
PY
EOF
chmod +x aws_origin_check.sh

6.6 The egress check

Run this on any system that fetches URLs for other people, with the ranges your rules and firewalls trust. It reports the system’s public IPv4 and IPv6 egress addresses, says whether they fall inside a trusted range, and prints the two follow up commands: cf_audit.py --egress-ip to list the Cloudflare rules that would exempt that address, and aws_origin_check.sh to see whether the load balancer would admit it directly. The audit also accepts --trusted-range, which raises any IP Access allow rule, skip rule or “challenge everyone except” rule covering those ranges to critical, including ranges held in account IP lists that the rules reference by name.

cat > egress_check.sh << 'EOF'
#!/usr/bin/env bash
# egress_check.sh: find the public address a system leaves from, and whether
# that address falls inside any range you trust (office, VPN, a firewall
# allowlist at the origin). Run it ON the system in question: a server that
# hosts an integration, a proxy, a webhook relay, anything that fetches URLs
# on someone else's behalf.
#
#   TRUSTED_RANGES="198.51.100.0/24 2001:db8:10::/48" ./egress_check.sh
#
# The answer separates two very different problems. If the address is inside a
# trusted range, anyone who can make that system fetch a URL inherits the trust,
# at the edge and possibly straight to the origin. If it is not, the exposure is
# limited to whatever the edge does for ordinary traffic.
set -uo pipefail
TRUSTED_RANGES="${TRUSTED_RANGES:-}"

egress() { # family
  curl -s "-$1" --max-time 8 https://www.cloudflare.com/cdn-cgi/trace 2>/dev/null |
    sed -n 's/^ip=//p'
}
V4="$(egress 4)"; V6="$(egress 6)"
echo "Egress IPv4: ${V4:-none}"
echo "Egress IPv6: ${V6:-none}"
[ -z "$V4$V6" ] && { echo "No outbound HTTPS from here; check proxies or egress rules."; exit 1; }

python3 - "$TRUSTED_RANGES" $V4 $V6 << 'PY'
import ipaddress, sys
ranges = [ipaddress.ip_network(r, strict=False) for r in sys.argv[1].split()]
hit = False
for addr in sys.argv[2:]:
    ip = ipaddress.ip_address(addr)
    inside = [str(r) for r in ranges if ip.version == r.version and ip in r]
    if inside:
        hit = True
        print("INSIDE TRUSTED RANGE: %s is in %s" % (addr, ", ".join(inside)))
    else:
        print("outside trusted ranges: %s" % addr)
if not ranges:
    print("No TRUSTED_RANGES given; pass the ranges your edge rules and origin firewall trust.")
print()
print("Next: python3 cf_audit.py --zone <zone> " +
      " ".join("--egress-ip %s" % a for a in sys.argv[2:]) +
      "   # which Cloudflare rules exempt it")
print("      ./aws_origin_check.sh <load-balancer-name> " + " ".join(sys.argv[2:]) +
      "   # can it reach the origin directly")
sys.exit(2 if hit else 0)
PY
EOF
chmod +x egress_check.sh

The durable fix is to stop granting trust by address at all. Staff reach internal tooling through Cloudflare Access with multi factor authentication (MFA), systems that need to call an API get a service token or a client certificate, and the edge challenge applies to everyone. Where a shared firewall rule cannot be removed quickly because other services depend on it, a narrow emergency block on the specific egress addresses of the fetching component, with a tested rollback, buys time while the address based trust is retired.

7. Baseline settings at the edge

With the origin closed, the edge configuration is what actually protects the application. These are the targets the scripts check and, where safe, apply.

AreaSettingTarget
TLSEncryption modeFull (strict)
TLSMinimum TLS version1.2, with TLS 1.3 on
TLSAlways Use HTTPS, Automatic HTTPS RewritesOn
TLSHTTP Strict Transport Security (HSTS)On after testing, no subdomains or preload until every hostname is validated
OriginAuthenticationTunnel, or zone level AOP with your own certificate
WAFManaged rulesCloudflare Managed Ruleset on Pro and above; Free Managed Ruleset on Free
WAFOWASP Core Ruleset (Open Worldwide Application Security Project)Pro and above, log first, then block
WAFURL normalizationIncoming URLs normalized
WAFLeaked credentials detectionOn
WAFBrowser Integrity CheckOn
WAFSecurity LevelLeave alone: it now only switches Under Attack mode, which belongs on during an attack and off afterwards
AccountMFAHardware keys or passkeys for every member
AccountDNSSEC (DNS Security Extensions), registrar lockOn

Security Level deserves a note, because many older guides treat a low setting as a bypass. Cloudflare has since repurposed it: in the new dashboard, the API and Terraform it is the switch for Under Attack mode, and the threat score that the old Low, Medium and High levels were built on is now always 0. Any custom rule that still tests cf.threat_score therefore no longer does what it was written for, and the audit flags those rules instead of the setting.

Plan limits shape what is possible here. Cloudflare’s WAF documentation lists one rate limiting rule on the Free plan, and only the Free Managed Ruleset; the full Cloudflare Managed Ruleset and the OWASP Core Ruleset need Pro or higher. The Free plan also caps custom rules at a small number, which is why the hardening script folds all the sensitive path blocks into a single rule.

7.1 Application rules: a generic baseline and a WordPress profile

The hardening script always writes one block rule for files that no public site should serve, whatever runs behind it: any path segment that starts with a dot (so .env, .git and .aws are caught at any depth, such as inside a plugin or static folder, while /.well-known/ stays open for certificate validation), database dumps, .bak files, and archives (.zip, .tar.gz, .tgz), which is where backup jobs tend to leave copies of a site. Folders that legitimately publish downloads are excluded with --public-prefix. If your application has a login page, --login-path adds a Managed Challenge rule and a rate limiting rule for it, and --api-hostname adds the API rule described in section 7.4.

--profile wordpress adds what is specific to WordPress. It blocks xmlrpc.php, WordPress’s XML-RPC (Extensible Markup Language remote procedure call) endpoint for remote publishing, unless you pass --allow-xmlrpc because Jetpack or a publishing app needs it; in that case also delete the matching xmlrpc.php line in the nginx configuration, or the origin will still refuse it. It also blocks wp-config.php and its backups, debug.log, PHP files under uploads, and the common backup plugin folders. It sets /wp-login.php as the login path and treats /wp-content/uploads/ as a public folder for archives, because sites publish downloads there. Other platforms have their own equivalents, such as Drupal’s settings.php, or Laravel’s storage/logs and Rails’ config/master.key when a web root is misconfigured, and adding them to the expression is a few lines in custom_rules(). With the WordPress profile, for the apex and www hostnames, the block expression looks like this:

(http.host in {"example.com" "www.example.com"}) and (
  lower(http.request.uri.path) eq "/xmlrpc.php"
  or starts_with(lower(http.request.uri.path), "/wp-config.php")
  or (lower(http.request.uri.path) contains "/."
      and not starts_with(lower(http.request.uri.path), "/.well-known/"))
  or lower(http.request.uri.path) eq "/wp-content/debug.log"
  or (starts_with(lower(http.request.uri.path), "/wp-content/uploads/")
      and lower(http.request.uri.path) contains ".php")
  or ends_with(lower(http.request.uri.path), ".sql")
  or ends_with(lower(http.request.uri.path), ".sql.gz")
  or ends_with(lower(http.request.uri.path), ".bak")
  or ((ends_with(lower(http.request.uri.path), ".zip")
       or ends_with(lower(http.request.uri.path), ".tar.gz")
       or ends_with(lower(http.request.uri.path), ".tgz"))
      and not starts_with(lower(http.request.uri.path), "/wp-content/uploads/"))
  or starts_with(lower(http.request.uri.path), "/wp-content/ai1wm-backups")
  or starts_with(lower(http.request.uri.path), "/wp-content/updraft")
  or starts_with(lower(http.request.uri.path), "/wp-content/backup")
)

The login rule puts a Managed Challenge on the login path, and the rate limiting rule blocks a single address that makes more than five login requests in ten seconds at one data center. The two work together in a way that is easy to misread: because custom rules run before rate limiting, an unsolved challenge stops the request before the rate limiter counts it, so the rate limit only bites on clients that have already passed the challenge. That is the population you want it to bite on. Treat it as a backstop rather than the main control: five requests per ten seconds per address per data center does nothing against slow or widely distributed credential stuffing, which is what the challenge, Access and the application’s own MFA are for. These edge rules are a first line, not a replacement for the same denials at the origin, which is why the nginx configurations above repeat them.

Before you challenge or block a path prefix, find out which endpoints under it the front end calls anonymously, because blocking them breaks the site in ways that look like random bugs. On WordPress that means /wp-admin/admin-ajax.php (the AJAX, Asynchronous JavaScript and XML, endpoint) and /wp-json/ (the REST, Representational State Transfer, API), which themes, plugins and the block editor depend on, so the profile leaves them alone. Apply targeted controls to specific routes if you need them, for example limiting /wp-json/wp/v2/users to logged in users, rather than putting the whole namespace behind a challenge. The same reasoning applies to a single page application’s public API calls.

7.2 Caching that cannot leak a logged in page

A Cache Everything rule without exclusions is one of the few configurations that can actively leak data, because a page rendered for a logged in user can be stored and served to the next anonymous visitor. If you cache HTML (HyperText Markup Language, the pages themselves), the rule must exclude any request that carries a session cookie, and must never match admin, login, preview or personalised API paths. On WordPress the cookies are wordpress_logged_in_ and wp-postpass_ and the paths are /wp-admin, /wp-login.php and ?preview=true; on other stacks, use whatever your session cookie is called. The audit flags cache rules and legacy Page Rules that cache without any cookie based exclusion, and the acceptance tests send a fake session cookie (SESSION_COOKIE) and request your PRIVATE_PATHS to confirm nothing comes back as a cache HIT.

7.3 Cloudflare Access in front of administration

The strongest control for any administration interface is to put it, and the login page that leads to it, behind Cloudflare Access, which is free for small teams, with an identity provider that enforces MFA and a short session duration. Access checks identity at the edge, so a credential stuffing bot never sees the application’s login form. Two cautions apply. Exclude anything under the admin path that the public front end calls (on WordPress, /wp-admin/admin-ajax.php), or give it its own Bypass policy scoped to that one path. And give approved automation its own service token rather than an IP based Bypass policy, otherwise the exception becomes the next audit finding. If Access does not fit your workflow, keep strong MFA in the application plus the challenge and rate limit above.

7.4 API hosts: documentation, management endpoints and token checks

API hosts have their own version of a leaked configuration file. Spring Boot services and gateways commonly ship Swagger UI (user interface) and OpenAPI documents, which hand an attacker a complete map of every route and parameter, and Spring Boot Actuator management endpoints, which by default expose only health over the web but can expose configuration, mappings and even heap dumps if a deployed image widens management.endpoints.web.exposure.include. Block those paths at the edge first, because that can happen in minutes, and then turn them off in production configuration (springdoc.api-docs.enabled=false, springdoc.swagger-ui.enabled=false, and exposure limited to health). The hardening script does the edge part with --api-hostname, and --api-block-root when the gateway serves Swagger UI at /. The acceptance tests check the same paths with API_HOSTS, and test the API’s load balancer directly with API_ORIGIN.

Two checks belong in code review rather than at the edge, because no WAF can see them. Access tokens must be validated for audience as well as issuer, otherwise a token minted for a different client of the same identity provider is accepted. And every route should require authentication unless it is explicitly marked public, so a route added in a hurry fails closed. Finally, look for services that read X-Forwarded-For or similar headers for allow lists or rate limits. Unless the header is set by a proxy that the service only accepts connections from, a client can write whatever address it likes into it, and the allow list or rate limit becomes optional.

Remember too that the gateway routes in your repository describe what you intended to deploy. When the question is what is actually exposed, read the live routes and the configuration each gateway loaded from inside the platform, and test from outside.

8. The toolkit

The rest of this post is a handful of scripts and a scheduler. They use only the Python standard library, curl, openssl and dig, so they run on a laptop, a CI (continuous integration) runner or the origin itself without installing anything.

ScriptChanges anything?Purpose
cf_audit.pyNoReads the zone and account through the API, writes report.md, findings.json and a raw config-export.json, and compares against an approved baseline
cf_harden.pyOnly with --applyApplies the baseline (generic, or --profile wordpress), writes a backup first, and can roll back
origin_firewall.shOnly with --applyCloses or restricts ports 80 and 443 on the origin
cf_origin_tests.shNoRuns the acceptance tests from outside and writes a pass or fail report
aws_origin_check.shNoReviews a cloud load balancer: non Cloudflare sources, mutual TLS mode, access logs
egress_check.shNoFinds a system’s egress address and whether any trusted range covers it
setup_tunnel.sh, tunnel_cutover.pyCutover only with --applyStage and cut over to Cloudflare Tunnel, with DNS backup and automatic rollback
wordpress.tunnel.nginx.conf, wordpress.aop.nginx.confn/aExample origin configurations for WordPress; the listener, real IP and deny blocks apply to any application
smoke_test.shNoProves every script starts and runs the cutover failure scenarios; run it after any edit and in CI
test_tunnel_cutover.pyNoInjects API failures into the cutover against a fake DNS API

Create two API tokens. The audit token is read only and scoped to the one zone and its account; give it read access to Zone, DNS, Zone Settings, SSL and Certificates, Zone WAF, Firewall Services, Page Rules, Configuration Rules, Cache Rules, Transform Rules, Origin Rules, Workers Routes, Bot Management, Logs and Snippets, plus account level read for Access apps and policies, Cloudflare Tunnel, Notifications, Account Settings and API Tokens, and Analytics read so the acceptance tests can correlate Ray IDs with Security Events. Permission names shift a little over time, and that is fine: anything the token cannot read appears in the report under “Not verified”, never under “passed”. The hardening token gets edit rights on the zone only (DNS edit included, for the tunnel cutover), and you revoke it when the work is done. Never paste either token into a report or a commit.

Before anything else, and after any edit to the scripts, run the smoke test. It needs no tokens or network. It proves that every script at least starts and that the tunnel cutover recovers from each injected failure, which is the cheapest way to catch a broken copy and paste from this page.

cat > smoke_test.sh << 'EOF'
#!/usr/bin/env bash
# smoke_test.sh: prove every script in the toolkit at least starts, and that the
# tunnel cutover recovers from every injected failure. Run it after
# any edit, and in CI before the daily audit. Needs no network or tokens.
set -u
fail=0
for py in cf_audit.py cf_harden.py tunnel_cutover.py test_tunnel_cutover.py; do
  [ "$py" = test_tunnel_cutover.py ] && { python3 -m py_compile "$py" && echo "ok    $py compiles" || fail=1; continue; }
  if python3 -m py_compile "$py" && python3 "$py" --help >/dev/null 2>&1; then
    echo "ok    $py --help"
  else
    echo "FAIL  $py"; python3 "$py" --help 2>&1 | tail -3; fail=1
  fi
done
if python3 test_tunnel_cutover.py >/tmp/cutover-test.log 2>&1; then
  echo "ok    tunnel cutover failure scenarios ($(grep -c '^ok' /tmp/cutover-test.log) passed)"
else
  echo "FAIL  tunnel cutover scenarios"; cat /tmp/cutover-test.log; fail=1
fi
for sh in cf_origin_tests.sh origin_firewall.sh aws_origin_check.sh egress_check.sh \
          setup_tunnel.sh make_aop_cert.sh run_audit.sh run_tests.sh; do
  if bash -n "$sh"; then echo "ok    bash -n $sh"; else echo "FAIL  $sh"; fail=1; fi
done
if command -v shellcheck >/dev/null; then
  shellcheck -S error ./*.sh && echo "ok    shellcheck" || fail=1
fi
exit $fail
EOF
chmod +x smoke_test.sh

9. Script 1: the read only audit

The audit walks every place a bypass can hide: DNS records (including SPF records and MX hosts that reveal the origin address), zone settings, zone level AOP, every Ruleset Engine phase at zone and account level, IP Access Rules, legacy firewall rules and Page Rules, Workers routes, Snippets, URL normalization, leaked credentials detection, Bot Fight Mode, DNSSEC, Logpush, Access applications and policies, tunnels and their ingress rules, account members without MFA, stale or over privileged API tokens, notification policies and the registrar lock. It also flags any rule that still depends on the retired threat score, and Under Attack mode left on for the whole zone. It reads each zone setting individually, because Cloudflare has deprecated the bulk settings endpoint. Each finding carries a severity, the evidence that produced it and a recommendation. The file checks are generic by default; --profile wordpress adds the WordPress paths, and --login-path and --admin-path tell it which login pages should be challenged and which admin paths should sit behind Access.

Skip rules get the most attention. The script classifies the condition on each one as “everything” (an expression of true), “spoofable” (built on User-Agent, headers, cookies, referer or query strings), “network” (source address, country or ASN, the Autonomous System Number that identifies a network) or “scoped” (path or host only), and grades it by what it skips. A spoofable skip of the managed rules is critical; a path scoped exception for one rule is a low severity item to document.

cat > cf_audit.py << 'EOF'
#!/usr/bin/env python3
"""
cf_audit.py: read only audit of a Cloudflare zone for WAF bypasses, origin
exposure and weak security settings. Produces a Markdown report, a JSON
findings file and a raw configuration export (your rollback evidence).

It never changes anything. Give it a read only API token.

Usage:
  export CF_API_TOKEN="..."            # read only token
  python3 cf_audit.py --zone example.com \
      [--origin-ip 203.0.113.10] [--origin-ip 2001:db8::10] \
      [--out-dir ./audit] [--save-baseline baseline.json] [--baseline baseline.json]

Exit codes (useful for cron and CI):
  0 = no critical or high findings, 1 = high findings, 2 = critical findings,
  3 = could not run (bad token, zone not found).
"""
import argparse
import datetime as dt
import hashlib
import ipaddress
import json
import os
import re
import socket
import sys
import urllib.error
import urllib.parse
import urllib.request

API = "https://api.cloudflare.com/client/v4"
SEVERITIES = ["critical", "high", "medium", "low", "info"]

SECURITY_PHASES = {
    "http_request_firewall_managed",
    "http_ratelimit",
    "http_request_sbfm",
}
ZONE_PHASES = [
    "http_request_dynamic_redirect",
    "http_request_transform",
    "http_config_settings",
    "http_request_origin",
    "ddos_l7",
    "http_request_firewall_custom",
    "http_ratelimit",
    "http_request_firewall_managed",
    "http_request_late_transform",
    "http_request_cache_settings",
    "http_response_headers_transform",
]
ACCOUNT_PHASES = [
    "http_request_firewall_custom",
    "http_ratelimit",
    "http_request_firewall_managed",
]
# Fields a client controls completely. Trusting them for a skip is a bypass.
SPOOFABLE = re.compile(
    r"http\.user_agent|http\.request\.headers|http\.cookie|http\.referer|"
    r"http\.x_forwarded_for|http\.request\.body|http\.request\.uri\.query|"
    r"http\.request\.uri\.args"
)
NETWORK_IDENTITY = re.compile(
    r"ip\.src|ip\.geoip\.country|ip\.src\.country|ip\.geoip\.asnum|"
    r"ip\.src\.asnum|ip\.geoip\.continent|ip\.src\.continent"
)
TRUST_HEADERS = {
    "cf-connecting-ip", "true-client-ip", "x-forwarded-for", "x-real-ip",
    "x-forwarded-host", "x-forwarded-proto", "forwarded", "host",
}
CHALLENGE_ACTIONS = {"block", "managed_challenge", "challenge", "js_challenge"}
MAIL_HINT = re.compile(r"^(mail|smtp|imap|pop|pop3|mx|autodiscover|autoconfig|webmail)\b|_domainkey|^_")


def now_utc():
    return dt.datetime.now(dt.timezone.utc)


class CF:
    """Tiny Cloudflare API client using only the standard library."""

    def __init__(self, token):
        self.token = token

    def call(self, method, path, body=None, params=None):
        url = API + path
        if params:
            url += "?" + urllib.parse.urlencode(params)
        data = json.dumps(body).encode() if body is not None else None
        req = urllib.request.Request(url, data=data, method=method)
        req.add_header("Authorization", "Bearer " + self.token)
        req.add_header("Content-Type", "application/json")
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                raw = resp.read().decode() or "{}"
                return resp.status, json.loads(raw)
        except urllib.error.HTTPError as err:
            try:
                payload = json.loads(err.read().decode() or "{}")
            except Exception:
                payload = {"success": False, "errors": [{"message": str(err)}]}
            return err.code, payload
        except urllib.error.URLError as err:
            return 0, {"success": False, "errors": [{"message": str(err.reason)}]}

    def get_all(self, path, params=None, per_page=100, max_pages=50):
        """Follow page based pagination. Returns (status, payload, items)."""
        items, page = [], 1
        while page <= max_pages:
            query = dict(params or {})
            query.update({"page": page, "per_page": per_page})
            status, payload = self.call("GET", path, params=query)
            if status != 200 or not payload.get("success", False):
                return status, payload, items
            result = payload.get("result") or []
            items.extend(result)
            info = payload.get("result_info") or {}
            total_pages = info.get("total_pages")
            if not result or (total_pages and page >= total_pages) or (
                not total_pages and len(result) < per_page
            ):
                return 200, payload, items
            page += 1
        return 200, {}, items


def errmsg(payload):
    errs = payload.get("errors") or []
    return "; ".join(str(e.get("message", e)) for e in errs) or "unknown error"


class Audit:
    def __init__(self, cf, zone_name, origin_ips, account_id=None, trusted=None, egress=None,
                 profile="generic", login_paths=None, admin_paths=None):
        self.cf = cf
        self.profile = profile
        wp = profile == "wordpress"
        self.login_paths = login_paths or (["/wp-login.php"] if wp else [])
        self.admin_paths = admin_paths or (["/wp-admin", "/wp-login.php"] if wp else [])
        # Ranges you trust (office, VPN, corporate egress) and the addresses that
        # anything which fetches URLs for other people leaves from. If an exemption
        # covers them, anyone who can reach that fetcher inherits the exemption.
        self.risky_nets = []
        for item in list(trusted or []) + list(egress or []):
            self.risky_nets.append((item, ipaddress.ip_network(item, strict=False)))
        self.list_cache = None
        self.zone_name = zone_name.lower().rstrip(".")
        self.account_id = account_id
        self.origin_ips = set(origin_ips)
        self.findings = []
        self.unverified = []
        self.passed = []
        self.export = {"generated_utc": now_utc().isoformat(), "zone": zone_name}
        self.snapshot = {}
        self.zone = None
        self.zone_id = None
        self.plan = "unknown"
        self.tunnel_hostnames = set()
        self.cf_ranges = []

    # helpers
    def add(self, severity, area, title, detail, recommendation, evidence=None):
        self.findings.append({
            "severity": severity, "area": area, "title": title, "detail": detail,
            "recommendation": recommendation, "evidence": evidence,
        })

    def ok(self, area, text):
        self.passed.append({"area": area, "check": text})

    def fetch(self, area, path, params=None, paginate=False, quiet_404=False):
        if paginate:
            status, payload, items = self.cf.get_all(path, params)
            if status == 200:
                self.export[path] = items
                return items
        else:
            status, payload = self.cf.call("GET", path, params=params)
            if status == 200 and payload.get("success", True):
                result = payload.get("result")
                self.export[path] = result
                return result
        if status == 404 and quiet_404:
            self.export[path] = None
            return None
        self.unverified.append({
            "area": area, "endpoint": path, "http_status": status,
            "reason": errmsg(payload),
        })
        return None

    def in_zone(self, host):
        host = (host or "").lower().rstrip(".")
        return host == self.zone_name or host.endswith("." + self.zone_name)

    def is_cloudflare_ip(self, ip):
        try:
            addr = ipaddress.ip_address(ip)
        except ValueError:
            return False
        return any(addr in net for net in self.cf_ranges)

    IP_TOKEN = re.compile(r"(?<![\w.:])((?:\d{1,3}\.){3}\d{1,3}(?:/\d{1,2})?|"
                          r"[0-9a-fA-F]{0,4}(?::[0-9a-fA-F]{0,4}){2,7}(?:/\d{1,3})?)(?![\w.:])")

    def lists(self):
        """Account IP lists by name, so rules using $list_name can be resolved."""
        if self.list_cache is None:
            self.list_cache = {}
            if self.account_id:
                status, payload = self.cf.call("GET", "/accounts/%s/rules/lists" % self.account_id)
                if status == 200:
                    for lst in payload.get("result") or []:
                        if lst.get("kind") != "ip":
                            continue
                        _, _, items = self.cf.get_all("/accounts/%s/rules/lists/%s/items"
                                                      % (self.account_id, lst["id"]))
                        self.list_cache[lst["name"]] = [i.get("ip") for i in items if i.get("ip")]
                    self.export["ip_lists"] = self.list_cache
        return self.list_cache

    def networks_in(self, expr):
        nets = []
        tokens = self.IP_TOKEN.findall(expr or "")
        for name in re.findall(r"\$([A-Za-z0-9_]+)", expr or ""):
            tokens += self.lists().get(name, [])
        for tok in tokens:
            try:
                nets.append(ipaddress.ip_network(tok, strict=False))
            except ValueError:
                pass
        return nets

    def risky_overlap(self, nets):
        hits = []
        for label, risky in self.risky_nets:
            for net in nets:
                if net.version == risky.version and net.overlaps(risky):
                    hits.append("%s covers %s" % (net, label))
        return hits

    # checks
    def load_zone(self):
        status, payload = self.cf.call("GET", "/zones", params={"name": self.zone_name})
        if status != 200 or not payload.get("result"):
            raise SystemExit("Zone lookup failed (%s): %s" % (status, errmsg(payload)))
        self.zone = payload["result"][0]
        self.zone_id = self.zone["id"]
        self.account_id = self.account_id or self.zone.get("account", {}).get("id")
        plan = self.zone.get("plan", {})
        self.plan = (plan.get("legacy_id") or plan.get("name") or "unknown").lower()
        self.export["zone_details"] = self.zone
        # Cloudflare's published ranges (no auth needed).
        status, payload = self.cf.call("GET", "/ips")
        if status == 200:
            res = payload.get("result", {})
            for cidr in res.get("ipv4_cidrs", []) + res.get("ipv6_cidrs", []):
                self.cf_ranges.append(ipaddress.ip_network(cidr))
            self.export["cloudflare_ips"] = res

    def check_dns(self):
        z = self.zone_id
        records = self.fetch("DNS", "/zones/%s/dns_records" % z, paginate=True)
        if records is None:
            return
        proxied_targets = set()
        for r in records:
            if r.get("proxied") and r["type"] in ("A", "AAAA"):
                proxied_targets.add(r["content"])
                self.origin_ips.add(r["content"])
            if r.get("proxied") and r["type"] == "CNAME":
                target = r["content"].lower()
                if target.endswith(".cfargotunnel.com"):
                    self.tunnel_hostnames.add(r["name"].lower())
                else:
                    # A proxied CNAME to an external hostname is an origin hostname
                    # that anyone can resolve. Treat its addresses as origin addresses.
                    try:
                        for info in socket.getaddrinfo(target, None):
                            self.origin_ips.add(info[4][0])
                    except socket.gaierror:
                        pass
                    if not self.in_zone(target):
                        self.add("medium", "DNS", "Origin is a publicly resolvable hostname",
                                 "%s is proxied to %s. That hostname resolves publicly and "
                                 "may serve the application directly." % (r["name"], target),
                                 "Confirm the provider hostname cannot serve the site "
                                 "(acceptance test: alternative origin hostname).",
                                 {"record": r["name"], "target": target})

        unproxied = []
        for r in records:
            rtype, name, content = r["type"], r["name"].lower(), r.get("content", "")
            if rtype in ("A", "AAAA", "CNAME") and not r.get("proxied"):
                unproxied.append("%s|%s|%s" % (name, rtype, content))
                if content in self.origin_ips:
                    self.add("critical", "DNS", "DNS only record publishes the origin IP",
                             "%s (%s) is not proxied and points at %s, which is also a proxied "
                             "origin. Anyone can read the origin address from public DNS."
                             % (name, rtype, content),
                             "Proxy or delete the record, move the service to a different "
                             "address, and lock the origin down so the address no longer matters.",
                             {"record": name, "type": rtype, "content": content})
                elif MAIL_HINT.search(name.split(".")[0]) or name.startswith("_"):
                    self.add("medium", "DNS", "DNS only service record",
                             "%s (%s) -> %s is DNS only. Fine for mail, but confirm it is not "
                             "the web server." % (name, rtype, content),
                             "Make sure mail and other services never share the web origin IP.",
                             {"record": name, "content": content})
                elif rtype == "CNAME" and content.lower().endswith(".cfargotunnel.com"):
                    self.add("high", "DNS", "Tunnel hostname is not proxied",
                             "%s points at a tunnel but is DNS only, so it will not route." % name,
                             "Set the record to proxied.", {"record": name})
                else:
                    self.add("high", "DNS", "Unproxied web facing record",
                             "%s (%s) -> %s bypasses Cloudflare entirely." % (name, rtype, content),
                             "Proxy it if it is a website, delete it if it is forgotten "
                             "(old staging, dev, test).",
                             {"record": name, "type": rtype, "content": content})

        # MX hosts resolving to an origin address.
        for r in records:
            if r["type"] == "MX":
                target = r["content"].rstrip(".")
                try:
                    addrs = {i[4][0] for i in socket.getaddrinfo(target, 25)}
                except socket.gaierror:
                    addrs = set()
                shared = addrs & self.origin_ips
                if shared:
                    self.add("high", "DNS", "Mail server shares the web origin IP",
                             "MX %s resolves to %s, which is also the web origin."
                             % (target, ", ".join(sorted(shared))),
                             "Move mail to a separate host or provider.",
                             {"mx": target, "shared": sorted(shared)})

        # SPF records frequently leak the origin with ip4:/ip6: mechanisms.
        for r in records:
            if r["type"] == "TXT" and "v=spf1" in r.get("content", ""):
                for mech in re.findall(r"ip[46]:([0-9a-fA-F:./]+)", r["content"]):
                    try:
                        net = ipaddress.ip_network(mech, strict=False)
                    except ValueError:
                        continue
                    hits = [ip for ip in self.origin_ips
                            if self._ip_in(ip, net)]
                    if hits:
                        self.add("high", "DNS", "SPF record publishes the origin IP",
                                 "SPF on %s includes %s, which covers origin %s."
                                 % (r["name"], mech, ", ".join(hits)),
                                 "Send mail from a separate host or a mail provider and "
                                 "remove the origin address from SPF.",
                                 {"record": r["name"], "mechanism": mech})

        web = [r for r in records if r["type"] in ("A", "AAAA", "CNAME")]
        if web and all(r.get("proxied") for r in web):
            self.ok("DNS", "All A, AAAA and CNAME records are proxied")
        self.snapshot["unproxied_dns"] = sorted(unproxied)

    @staticmethod
    def _ip_in(ip, net):
        try:
            return ipaddress.ip_address(ip) in net
        except ValueError:
            return False

    def check_settings(self):
        z = self.zone_id
        # Per setting reads: the bulk GET /zones/{id}/settings endpoint is deprecated.
        settings = {}
        for sid in ("ssl", "min_tls_version", "tls_1_3", "always_use_https",
                    "automatic_https_rewrites", "security_header", "browser_check",
                    "security_level", "tls_client_auth"):
            val = self.fetch("SSL/TLS settings", "/zones/%s/settings/%s" % (z, sid))
            if isinstance(val, dict):
                settings[sid] = val.get("value")
        if not settings:
            return
        keep = ("ssl", "min_tls_version", "tls_1_3", "always_use_https",
                "automatic_https_rewrites", "security_header", "browser_check",
                "security_level", "tls_client_auth")
        self.snapshot["settings"] = {k: settings.get(k) for k in keep}

        ssl = settings.get("ssl")
        if ssl in ("off", "flexible"):
            self.add("critical", "SSL/TLS", "Encryption mode is %s" % ssl,
                     "Traffic between Cloudflare and the origin is plain HTTP, or not "
                     "authenticated at all.",
                     "Install a valid origin certificate (Origin CA is fine) and set "
                     "Full (strict).", {"ssl": ssl})
        elif ssl == "full":
            self.add("high", "SSL/TLS", "Encryption mode is Full, not Full (strict)",
                     "Cloudflare encrypts to the origin but does not validate its "
                     "certificate, so the origin connection can be impersonated.",
                     "Set Full (strict) once the origin certificate validates.",
                     {"ssl": ssl})
        elif ssl == "strict":
            self.ok("SSL/TLS", "Encryption mode is Full (strict)")

        mtv = settings.get("min_tls_version")
        if mtv in ("1.0", "1.1"):
            self.add("medium", "SSL/TLS", "Minimum TLS version is %s" % mtv,
                     "Clients can negotiate deprecated protocol versions.",
                     "Set the minimum TLS version to 1.2.", {"min_tls_version": mtv})
        elif mtv:
            self.ok("SSL/TLS", "Minimum TLS version is %s" % mtv)
        if settings.get("tls_1_3") == "off":
            self.add("low", "SSL/TLS", "TLS 1.3 is disabled", "", "Enable TLS 1.3.")
        if settings.get("always_use_https") != "on":
            self.add("medium", "SSL/TLS", "Always Use HTTPS is off",
                     "Plain HTTP requests are served rather than redirected.",
                     "Enable Always Use HTTPS.")
        if settings.get("automatic_https_rewrites") != "on":
            self.add("low", "SSL/TLS", "Automatic HTTPS Rewrites is off",
                     "Mixed content links may remain.", "Enable it unless it breaks pages.")
        hsts = (settings.get("security_header") or {}).get("strict_transport_security", {})
        if not hsts.get("enabled"):
            self.add("low", "SSL/TLS", "HSTS is not enabled",
                     "Browsers can be downgraded to HTTP on first visit.",
                     "Enable HSTS with a short max age first, without subdomains or preload, "
                     "then lengthen it after testing.")
        elif hsts.get("include_subdomains") or hsts.get("preload"):
            self.add("info", "SSL/TLS", "HSTS covers subdomains or is preload ready",
                     "Every subdomain must serve valid HTTPS or it becomes unreachable.",
                     "Confirm every hostname in the zone serves HTTPS.", hsts)
        if settings.get("security_level") == "under_attack":
            self.add("medium", "WAF", "Under Attack mode is on for the whole zone",
                     "Security Level now only switches Under Attack mode. Left on, it puts a "
                     "Managed Challenge in front of every request and can break API clients "
                     "and integrations.",
                     "Switch it off when the attack ends, or scope it with a configuration rule.")
        if settings.get("browser_check") == "off":
            self.add("low", "WAF", "Browser Integrity Check is off", "",
                     "Enable it unless an integration breaks.")
        if settings.get("tls_client_auth") == "on":
            self.add("info", "Origin", "Global Authenticated Origin Pulls is on",
                     "The global certificate is shared by every Cloudflare customer, so it "
                     "proves the request came through Cloudflare, not through your account.",
                     "Use zone level AOP with your own certificate, or a tunnel.")

    def check_origin_auth(self):
        z = self.zone_id
        aop = self.fetch("Origin authentication",
                         "/zones/%s/origin_tls_client_auth/settings" % z) or {}
        certs = self.fetch("Origin authentication",
                           "/zones/%s/origin_tls_client_auth" % z) or []
        host_certs = self.fetch("Origin authentication",
                                "/zones/%s/origin_tls_client_auth/hostnames/certificates" % z) or []
        enabled = bool(aop.get("enabled")) if isinstance(aop, dict) else False
        self.snapshot["zone_aop_enabled"] = enabled
        web_hosts = {self.zone_name, "www." + self.zone_name}
        tunnel_covers = web_hosts & self.tunnel_hostnames
        if tunnel_covers:
            self.ok("Origin", "Tunnel serves: " + ", ".join(sorted(tunnel_covers)))
        if not enabled and not tunnel_covers:
            self.add("critical", "Origin", "No origin authentication",
                     "Neither zone level Authenticated Origin Pulls nor a Cloudflare Tunnel "
                     "protects the origin. An IP allowlist alone admits any Cloudflare "
                     "customer, because another account can point its own zone at your "
                     "origin IP with every security feature switched off.",
                     "Move the site behind Cloudflare Tunnel, or enable zone level AOP with "
                     "your own client certificate and enforce it at the origin.")
        elif enabled:
            self.ok("Origin", "Zone level Authenticated Origin Pulls enabled at Cloudflare "
                    "(origin enforcement must be proven by the acceptance tests)")
            if not certs:
                self.add("high", "Origin", "Zone level AOP enabled without a custom certificate",
                         "Without an uploaded certificate Cloudflare presents the shared one.",
                         "Upload your own leaf certificate.")
        for cert in list(certs or []) + list(host_certs or []):
            exp = cert.get("expires_on")
            if not exp:
                continue
            try:
                when = dt.datetime.fromisoformat(exp.replace("Z", "+00:00"))
            except ValueError:
                continue
            days = (when - now_utc()).days
            if days < 30:
                self.add("medium" if days >= 0 else "critical", "Origin",
                         "AOP client certificate expires in %d days" % days,
                         "Certificate %s expires %s." % (cert.get("id"), exp),
                         "Rotate it before expiry and test the origin again.")

    def analyse_condition(self, expr):
        expr = expr or ""
        flat = expr.strip().lower()
        if flat in ("true", "(true)", ""):
            return "everything"
        if SPOOFABLE.search(expr):
            return "spoofable"
        if NETWORK_IDENTITY.search(expr):
            return "network"
        return "scoped"

    def check_rulesets(self):
        z = self.zone_id
        available = self.fetch("WAF", "/zones/%s/rulesets" % z) or []
        names = {r["id"]: r.get("name", r["id"]) for r in available}
        self.export["managed_ruleset_names"] = names
        skip_fingerprints, executes, origin_rules, config_rules = [], [], [], []

        entrypoints = {}
        for phase in ZONE_PHASES:
            ep = self.fetch("Rulesets", "/zones/%s/rulesets/phases/%s/entrypoint" % (z, phase),
                            quiet_404=True)
            entrypoints[("zone", phase)] = ep
        if self.account_id:
            for phase in ACCOUNT_PHASES:
                status, payload = self.cf.call(
                    "GET", "/accounts/%s/rulesets/phases/%s/entrypoint" % (self.account_id, phase))
                if status == 200:
                    entrypoints[("account", phase)] = payload.get("result")
                    self.export["account:" + phase] = payload.get("result")

        for (level, phase), ep in entrypoints.items():
            if not ep:
                continue
            for rule in ep.get("rules", []):
                action = rule.get("action")
                expr = rule.get("expression", "")
                ap = rule.get("action_parameters") or {}
                desc = rule.get("description") or rule.get("id")
                ev = {"level": level, "phase": phase, "rule_id": rule.get("id"),
                      "description": desc, "expression": expr, "action": action,
                      "action_parameters": ap, "enabled": rule.get("enabled", True)}
                if not rule.get("enabled", True):
                    if action == "execute" and phase == "http_request_firewall_managed":
                        self.add("high", "WAF", "Managed ruleset deployment is disabled",
                                 "%s rule '%s' would execute %s but is disabled."
                                 % (level, desc, names.get(ap.get("id"), ap.get("id"))),
                                 "Re enable it and handle false positives with narrow exceptions.",
                                 ev)
                    continue

                nets = self.networks_in(expr)
                exempts = re.search(r"not\s*\(?\s*ip\.src", expr or "") is not None
                hits = self.risky_overlap(nets)
                if hits and (action == "skip" or (exempts and action in CHALLENGE_ACTIONS)):
                    self.add("critical", "Trusted addresses",
                             "Exemption covers a trusted or egress address",
                             "%s %s rule '%s' (%s) exempts traffic from addresses that include: %s. "
                             "Anything inside that network which fetches URLs on someone else's "
                             "behalf (an open proxy, an SSRF bug, a webhook tester, a marketing "
                             "or link preview integration) hands the exemption to whoever "
                             "controls the URL." % (level, phase, desc, action, "; ".join(hits)),
                             "Remove address based trust. Give staff and integrations an "
                             "identity instead (Cloudflare Access, service tokens, mTLS).", ev)
                elif exempts and action in CHALLENGE_ACTIONS and nets:
                    self.add("high", "WAF", "Challenge or block rule exempts source addresses",
                             "%s rule '%s' (%s) excludes %d address range(s) from its check: %s"
                             % (phase, desc, action, len(nets), expr),
                             "Treat this like a skip rule: every exempted range must be "
                             "documented, owned and free of anything that proxies requests. "
                             "Pass your corporate ranges with --trusted-range to test them.", ev)

                if "cf.threat_score" in (expr or ""):
                    self.add("medium", "WAF", "Rule depends on the threat score",
                             "Rule '%s' uses cf.threat_score, which Cloudflare now always sets "
                             "to 0, so this condition no longer does what it was written for: %s"
                             % (desc, expr),
                             "Rewrite it with bot, leaked credential or WAF attack score fields, "
                             "or delete it.", ev)

                if action == "skip":
                    kind = self.analyse_condition(expr)
                    skips_waf = (ap.get("ruleset") == "current"
                                 or bool(set(ap.get("phases", [])) & SECURITY_PHASES)
                                 or bool(ap.get("products")))
                    skip_fingerprints.append("%s|%s|%s|%s" % (level, phase, expr,
                                                              json.dumps(ap, sort_keys=True)))
                    if phase == "http_request_firewall_managed":
                        sev = {"everything": "high", "spoofable": "high",
                               "network": "medium", "scoped": "low"}[kind]
                        title = "Managed rules exception (%s condition)" % kind
                        rec = ("Scope the exception to one path and the specific rule IDs "
                               "that false positive. Never key it on headers, cookies or "
                               "user agents.")
                    else:
                        sev = {"everything": "critical", "spoofable": "critical",
                               "network": "high", "scoped": "medium"}[kind]
                        if not skips_waf:
                            sev = "low" if kind == "scoped" else "medium"
                        title = "Skip rule bypasses security (%s condition)" % kind
                        rec = ("Delete it, or narrow it to the exact path and the exact "
                               "product or rule IDs needed. Client controlled fields "
                               "(User-Agent, headers, cookies) can be set by anyone.")
                    self.add(sev, "WAF", title,
                             "%s %s rule '%s' skips %s when: %s"
                             % (level, phase, desc,
                                json.dumps({k: ap[k] for k in ap if k in
                                            ("ruleset", "phases", "products", "rulesets", "rules")}),
                                expr), rec, ev)

                if phase == "http_request_firewall_managed" and action == "execute":
                    rid = ap.get("id")
                    executes.append(rid)
                    ov = ap.get("overrides") or {}
                    if ov.get("enabled") is False:
                        self.add("high", "WAF", "Managed ruleset switched off by override",
                                 "%s is deployed but every rule is disabled." % names.get(rid, rid),
                                 "Remove the ruleset level override.", ev)
                    if ov.get("action") in ("log",):
                        self.add("medium", "WAF", "Managed ruleset in log only mode",
                                 "%s logs instead of blocking." % names.get(rid, rid),
                                 "Review security events, then move to blocking.", ev)
                    off = [r for r in ov.get("rules", []) if r.get("enabled") is False]
                    off += [c for c in ov.get("categories", []) if c.get("enabled") is False]
                    if off:
                        self.add("medium", "WAF", "Managed rules disabled by override",
                                 "%d rule or category overrides disable protection in %s."
                                 % (len(off), names.get(rid, rid)),
                                 "Document each one (purpose, owner, still needed?).",
                                 {"rule": ev, "disabled": off})

                if phase == "http_config_settings" and action == "set_config":
                    config_rules.append(json.dumps({"e": expr, "p": ap}, sort_keys=True))
                    bad = []
                    if ap.get("ssl") in ("off", "flexible"):
                        bad.append(("critical", "ssl=%s" % ap["ssl"]))
                    if ap.get("ssl") == "full":
                        bad.append(("high", "ssl=full"))
                    if ap.get("security_level") == "under_attack":
                        bad.append(("info", "Under Attack mode for matching requests"))
                    if ap.get("bic") is False:
                        bad.append(("low", "browser integrity check off"))
                    if ap.get("automatic_https_rewrites") is False:
                        bad.append(("low", "automatic HTTPS rewrites off"))
                    for sev, what in bad:
                        self.add(sev, "Configuration rules", "Configuration rule weakens security",
                                 "Rule '%s' sets %s when: %s" % (desc, what, expr),
                                 "Remove the override or scope it to a path that genuinely "
                                 "needs it.", ev)

                if phase == "http_request_origin" and action == "route":
                    origin_rules.append(json.dumps({"e": expr, "p": ap}, sort_keys=True))
                    self.add("high" if ap.get("origin") else "medium", "Origin rules",
                             "Origin rule changes the backend",
                             "Rule '%s' routes to %s when: %s" % (desc, json.dumps(ap), expr),
                             "Confirm the alternate backend is locked down exactly like the "
                             "main origin, or remove the rule.", ev)

                if phase in ("http_request_late_transform", "http_request_transform") \
                        and action == "rewrite":
                    headers = {h.lower() for h in (ap.get("headers") or {})}
                    touched = headers & TRUST_HEADERS
                    if touched:
                        self.add("high", "Transform rules", "Transform rule sets a trust header",
                                 "Rule '%s' modifies %s." % (desc, ", ".join(sorted(touched))),
                                 "The origin may make security decisions on these headers. "
                                 "Remove the rewrite unless you understand exactly why it exists.",
                                 ev)

                if phase == "http_request_cache_settings" and action == "set_cache_settings":
                    caches = ap.get("cache") is True
                    sensitive = re.search(r"admin|login|account|preview|wp-json|/api", expr or "")
                    bypass_cookie = "http.cookie" in (expr or "") or \
                        "wp-settings" in (expr or "")
                    kind = self.analyse_condition(expr)
                    if caches and sensitive and " not " not in (" " + expr + " "):
                        self.add("critical", "Cache", "Cache rule may cache private pages",
                                 "Rule '%s' enables caching on: %s" % (desc, expr),
                                 "Never cache admin, login, preview or personalised API "
                                 "responses.", ev)
                    elif caches and kind in ("everything", "scoped") and not bypass_cookie:
                        self.add("high", "Cache", "Cache everything without a logged in bypass",
                                 "Rule '%s' caches HTML without any cookie based exclusion, "
                                 "so a page rendered for a logged in user could be served to "
                                 "visitors." % desc,
                                 "Exclude requests carrying your session cookie (for WordPress, "
                                 "'and not http.cookie contains \"wordpress_logged_in\"'), and "
                                 "exclude admin, login, preview and personalised API paths.", ev)

                if phase == "ddos_l7":
                    ov = ap.get("overrides") or {}
                    risky = [r for r in [ov] + ov.get("rules", []) if
                             r.get("sensitivity_level") == "eoff" or r.get("action") == "log"]
                    if risky:
                        self.add("high", "DDoS", "HTTP DDoS protection weakened by override",
                                 "Rule '%s' sets log only or essentially off." % desc,
                                 "Restore default sensitivity.", ev)

        # managed ruleset coverage
        executed_names = {names.get(i, i) for i in executes}
        self.snapshot["managed_executes"] = sorted(executed_names)
        is_free = self.plan in ("free", "free website")
        if is_free:
            self.add("info", "WAF", "Free plan: Free Managed Ruleset only",
                     "The full Cloudflare Managed Ruleset and the OWASP Core Ruleset need Pro "
                     "or higher. The Free Managed Ruleset is deployed automatically.",
                     "Consider Pro if you want the full managed and OWASP rulesets.")
        else:
            if not any("Cloudflare Managed Ruleset" == n for n in executed_names):
                self.add("high", "WAF", "Cloudflare Managed Ruleset not deployed",
                         "Your plan includes it but no rule executes it.",
                         "Deploy it in the managed rules phase (cf_harden.py does this).")
            else:
                self.ok("WAF", "Cloudflare Managed Ruleset deployed")
            if not any("OWASP" in n for n in executed_names):
                self.add("medium", "WAF", "OWASP Core Ruleset not deployed",
                         "Available on your plan but not executed.",
                         "Deploy it in log mode first, review, then enforce.")
            else:
                self.ok("WAF", "OWASP Core Ruleset deployed")

        # Baseline protections in custom rules: generic, then per profile
        custom = entrypoints.get(("zone", "http_request_firewall_custom")) or {}
        crules = [r for r in custom.get("rules", []) if r.get("enabled", True)]
        blob = lambda acts: " ".join(r.get("expression", "") for r in crules
                                     if r.get("action") in acts)
        blocks = blob({"block"})
        challenges = blob({"block", "managed_challenge", "challenge", "js_challenge"})
        checks = [
            (".env", ".env is not blocked at the edge", "high"),
            ("/.git", ".git is not blocked at the edge", "high"),
            (".sql", "Database dumps (.sql) are not blocked at the edge", "medium"),
        ]
        if self.profile == "wordpress":
            checks += [
                ("xmlrpc.php", "XML-RPC is not blocked", "medium"),
                ("wp-config.php", "wp-config.php is not blocked at the edge", "high"),
                ("debug.log", "debug.log is not blocked at the edge", "high"),
                ("/wp-content/uploads/", "PHP in uploads is not blocked at the edge", "high"),
            ]
        area = "WordPress" if self.profile == "wordpress" else "Sensitive files"
        for needle, title, sev in checks:
            dot_rule = '"/."' in blocks and needle in (".env", "/.git")
            if needle in blocks or dot_rule:
                self.ok(area, "Block rule covers %s" % needle)
            else:
                self.add(sev, area, title, "No enabled block rule mentions %s." % needle,
                         "Add the baseline block rule (cf_harden.py) and enforce the same at "
                         "the origin.")
        rl = entrypoints.get(("zone", "http_ratelimit")) or {}
        rl_blob = " ".join(r.get("expression", "") for r in rl.get("rules", []))
        for path in self.login_paths:
            if path.lower() in challenges.lower():
                self.ok("Login", "%s is challenged or blocked" % path)
            else:
                self.add("high", "Login", "%s has no challenge" % path,
                         "Login is exposed to credential stuffing at full speed.",
                         "Add a Managed Challenge rule, a rate limiting rule, or put it behind Access.")
            if path in rl_blob:
                self.ok("Login", "%s is rate limited" % path)
            else:
                self.add("medium", "Login", "No rate limiting rule for %s" % path, "",
                         "Add one as a backstop (the Free plan includes one rate limiting rule).")
        if not self.login_paths:
            self.add("info", "Login", "No login path given",
                     "Login protection was not checked.",
                     "Pass --login-path (or --profile wordpress) to check it.")

        self.snapshot["skip_rules"] = sorted(skip_fingerprints)
        self.snapshot["origin_rules"] = sorted(origin_rules)
        self.snapshot["config_rules"] = sorted(config_rules)

    def check_ip_access_rules(self):
        paths = ["/zones/%s/firewall/access_rules/rules" % self.zone_id]
        if self.account_id:
            paths.append("/accounts/%s/firewall/access_rules/rules" % self.account_id)
        allows = []
        for path in paths:
            rules = self.fetch("IP Access Rules", path, paginate=True) or []
            for r in rules:
                if r.get("mode") != "whitelist":
                    continue
                cfg = r.get("configuration", {})
                target, value = cfg.get("target"), cfg.get("value", "")
                allows.append("%s|%s|%s" % (r.get("id"), target, value))
                sev = "high"
                hits = []
                if target in ("ip", "ip_range", "ip6"):
                    try:
                        hits = self.risky_overlap([ipaddress.ip_network(value, strict=False)])
                    except ValueError:
                        pass
                if hits:
                    self.add("critical", "Trusted addresses",
                             "IP Access allow rule covers a trusted or egress address",
                             "%s allows %s (%s). Anything in that network that fetches URLs for "
                             "others becomes a way past every Cloudflare control."
                             % (path.split("/")[1][:-1], value, "; ".join(hits)),
                             "Delete it and give the people or systems behind it an identity.", r)
                    continue
                if target in ("asn", "country"):
                    sev = "critical"
                elif target == "ip_range":
                    try:
                        net = ipaddress.ip_network(value, strict=False)
                        if (net.version == 4 and net.prefixlen < 24) or \
                                (net.version == 6 and net.prefixlen < 48):
                            sev = "critical"
                    except ValueError:
                        pass
                self.add(sev, "IP Access Rules", "Allow rule bypasses every security feature",
                         "%s allow for %s %s (notes: %s). Allowed traffic skips WAF, managed "
                         "rules and rate limiting." % (path.split("/")[1][:-1], target, value,
                                                       r.get("notes", "")),
                         "Delete it. If an integration really needs an exception, write a "
                         "narrow skip for one path and one product instead.", r)
        if not allows:
            self.ok("IP Access Rules", "No allow (whitelist) IP Access Rules")
        self.snapshot["ip_allow_rules"] = sorted(allows)

    def check_legacy(self):
        z = self.zone_id
        status, payload = self.cf.call("GET", "/zones/%s/firewall/rules" % z)
        if status == 200:
            legacy = payload.get("result") or []
            self.export["legacy_firewall_rules"] = legacy
            for r in legacy:
                if r.get("action") in ("allow", "bypass") and not r.get("paused"):
                    self.add("high", "Legacy firewall rules", "Legacy allow or bypass rule",
                             "Rule '%s' (%s) on: %s" % (r.get("description"), r.get("action"),
                                                        (r.get("filter") or {}).get("expression")),
                             "Migrate to custom rules and remove the bypass.", r)

        rules = self.fetch("Page Rules", "/zones/%s/pagerules" % z) or []
        for pr in rules:
            if pr.get("status") != "active":
                continue
            target = " ".join(t.get("constraint", {}).get("value", "")
                              for t in pr.get("targets", []))
            acts = {a["id"]: a.get("value") for a in pr.get("actions", [])}
            ev = {"target": target, "actions": acts, "id": pr.get("id")}
            if "disable_security" in acts:
                self.add("critical", "Page Rules", "Page Rule disables security",
                         "Target %s uses Disable Security." % target, "Delete the action.", ev)
            if "security_level" in acts:
                self.add("info", "Page Rules", "Page Rule sets Security Level",
                         "Target %s sets %s. Security Level now only controls Under Attack mode, "
                         "so this is legacy configuration." % (target, acts["security_level"]),
                         "Migrate or delete the Page Rule.", ev)
            if acts.get("waf") == "off":
                self.add("high", "Page Rules", "Page Rule turns the legacy WAF off",
                         "Target %s." % target, "Remove the action.", ev)
            if acts.get("ssl") in ("off", "flexible", "full"):
                self.add("critical" if acts["ssl"] != "full" else "high", "Page Rules",
                         "Page Rule downgrades SSL to %s" % acts["ssl"], "Target %s." % target,
                         "Remove the action.", ev)
            if acts.get("browser_check") == "off":
                self.add("low", "Page Rules", "Page Rule disables Browser Integrity Check",
                         "Target %s." % target, "Remove unless required.", ev)
            if "resolve_override" in acts or "host_header_override" in acts:
                self.add("high", "Page Rules", "Page Rule changes the origin",
                         "Target %s overrides resolution or Host." % target,
                         "Confirm the alternate backend is locked down.", ev)
            if acts.get("cache_level") == "cache_everything":
                if re.search(r"admin|login|account|preview", target):
                    self.add("critical", "Page Rules", "Cache Everything on admin or login",
                             "Target %s." % target, "Remove immediately.", ev)
                elif "bypass_cache_on_cookie" not in acts:
                    self.add("high", "Page Rules", "Cache Everything without cookie bypass",
                             "Target %s may cache logged in HTML." % target,
                             "Replace with a Cache Rule that excludes session cookies "
                             "(wordpress_logged_in on WordPress) and admin, login and preview "
                             "paths.", ev)
        if rules:
            self.add("info", "Page Rules", "%d legacy Page Rules present" % len(rules),
                     "Page Rules are legacy; their settings can silently override newer rules.",
                     "Migrate them to Rules (configuration, cache, redirect) and delete them.")

    def check_workers_snippets(self):
        z = self.zone_id
        routes = self.fetch("Workers", "/zones/%s/workers/routes" % z) or []
        fp = []
        for r in routes:
            fp.append("%s|%s" % (r.get("pattern"), r.get("script")))
            self.add("medium", "Workers", "Worker route on the zone",
                     "%s runs script %s. A Worker fetch() to the same zone is not evaluated "
                     "by your custom or managed rules, and fetch() to another hostname can "
                     "reach an alternate origin." % (r.get("pattern"), r.get("script")),
                     "Review the code: no fetch() to raw origin IPs, no forwarding of "
                     "attacker controlled URLs, no same zone fetch of protected paths.", r)
        self.snapshot["worker_routes"] = sorted(fp)
        snippets = self.fetch("Snippets", "/zones/%s/snippets" % z, quiet_404=True) or []
        for s in snippets if isinstance(snippets, list) else []:
            self.add("medium", "Snippets", "Snippet present",
                     "Snippet %s changes request handling after the WAF." % s.get("snippet_name"),
                     "Review its logic for routing and header changes.", s)

    def check_zone_features(self):
        z = self.zone_id
        norm = self.fetch("WAF", "/zones/%s/url_normalization" % z)
        if isinstance(norm, dict):
            if norm.get("scope") == "none":
                self.add("medium", "WAF", "URL normalization disabled",
                         "Encoded or oddly formed paths can slip past path based rules.",
                         "Enable normalization of incoming URLs.", norm)
            else:
                self.ok("WAF", "URL normalization scope: %s" % norm.get("scope"))
        leaked = self.fetch("WAF", "/zones/%s/leaked-credential-checks" % z)
        if isinstance(leaked, dict):
            if leaked.get("enabled"):
                self.ok("WAF", "Leaked credentials detection enabled")
            else:
                self.add("low", "WAF", "Leaked credentials detection disabled", "",
                         "Enable it; it adds detection fields you can act on in custom rules.")
        bots = self.fetch("Bots", "/zones/%s/bot_management" % z)
        if isinstance(bots, dict):
            self.export["bot_management"] = bots
            if bots.get("fight_mode"):
                self.add("info", "Bots", "Bot Fight Mode is on",
                         "Custom rules cannot skip Bot Fight Mode. Watch for broken "
                         "integrations (webhooks, uptime monitors).",
                         "If an integration breaks, consider Super Bot Fight Mode (Pro) "
                         "where exceptions are possible.")
        dnssec = self.fetch("Account", "/zones/%s/dnssec" % z)
        if isinstance(dnssec, dict):
            if dnssec.get("status") == "active":
                self.ok("Account", "DNSSEC active")
            else:
                self.add("medium", "Account", "DNSSEC not active",
                         "Status: %s." % dnssec.get("status"),
                         "Enable DNSSEC and add the DS record at the registrar.")
        jobs = self.fetch("Logging", "/zones/%s/logpush/jobs" % z)
        self.snapshot["logpush_jobs"] = sorted(str(j.get("id")) for j in (jobs or []))
        if jobs == []:
            self.add("info", "Logging", "No Logpush jobs",
                     "Logpush is mostly an Enterprise feature; on lower plans rely on Security "
                     "Events and origin logs.", "Export logs to independent storage where you can.")

    def check_account(self):
        a = self.account_id
        if not a:
            self.unverified.append({"area": "Account", "endpoint": "-", "http_status": 0,
                                    "reason": "no account id"})
            return
        apps = self.fetch("Access", "/accounts/%s/access/apps" % a, paginate=True) or []
        admin_protected = False
        for app in apps:
            domains = [app.get("domain", "")] + [d.get("uri", "") if isinstance(d, dict) else d
                                                 for d in app.get("destinations", []) or []]
            domains += app.get("self_hosted_domains", []) or []
            if not any(self.in_zone(d.split("/")[0]) for d in domains if d):
                continue
            if any(path in d for d in domains for path in self.admin_paths):
                admin_protected = True
            policies = app.get("policies")
            if policies is None:
                policies = self.fetch("Access", "/accounts/%s/access/apps/%s/policies"
                                      % (a, app.get("id"))) or []
            for p in policies:
                decision = p.get("decision")
                if decision in ("bypass", "non_identity"):
                    everyone = any("everyone" in inc for inc in p.get("include", []))
                    self.add("high" if everyone else "medium", "Access",
                             "Access policy with %s decision" % decision,
                             "App '%s' (%s) policy '%s' lets requests through without "
                             "identity." % (app.get("name"), ", ".join(d for d in domains if d),
                                            p.get("name")),
                             "Use service tokens for automation instead of bypass policies.",
                             {"app": app.get("name"), "policy": p})
        if not self.admin_paths:
            self.add("info", "Access", "No admin path given",
                     "Whether administration is behind Cloudflare Access was not checked.",
                     "Pass --admin-path (or --profile wordpress) to check it.")
        elif admin_protected:
            self.ok("Access", "An Access application covers %s" % ", ".join(self.admin_paths))
        else:
            self.add("medium", "Access", "Administration not behind Cloudflare Access",
                     "No Access application covers %s." % ", ".join(self.admin_paths),
                     "Protect them with Access and MFA (free for up to 50 users).")

        tunnels = self.fetch("Tunnels", "/accounts/%s/cfd_tunnel" % a,
                             params={"is_deleted": "false"}) or []
        for t in tunnels:
            if t.get("status") in ("down", "inactive"):
                self.add("low", "Tunnels", "Tunnel %s is %s" % (t.get("name"), t.get("status")),
                         "", "Delete unused tunnels.")
            cfg = self.fetch("Tunnels", "/accounts/%s/cfd_tunnel/%s/configurations"
                             % (a, t.get("id")), quiet_404=True) or {}
            ingress = ((cfg.get("config") or {}).get("ingress")) or []
            if ingress:
                last = ingress[-1]
                if not str(last.get("service", "")).startswith("http_status:"):
                    self.add("medium", "Tunnels", "Tunnel catch all routes to a real service",
                             "Tunnel %s sends unknown hostnames to %s." % (t.get("name"),
                                                                         last.get("service")),
                             "End the ingress list with service: http_status:404.", ingress)
                for rule in ingress:
                    if (rule.get("originRequest") or {}).get("noTLSVerify"):
                        self.add("low", "Tunnels", "Tunnel skips origin TLS verification",
                                 "Ingress %s has noTLSVerify." % rule.get("hostname"),
                                 "Use http to localhost or a verifiable certificate.", rule)

        members = self.fetch("Account", "/accounts/%s/members" % a, paginate=True) or []
        supers = 0
        for m in members:
            user = m.get("user") or {}
            roles = [r.get("name", "") for r in m.get("roles", [])]
            if any("Super Administrator" in r for r in roles):
                supers += 1
            if user.get("two_factor_authentication_enabled") is False:
                self.add("high", "Account", "Member without MFA",
                         "%s has account access without two factor authentication."
                         % user.get("email"), "Require MFA, preferably a security key.",
                         {"email": user.get("email"), "roles": roles})
        if supers > 2:
            self.add("medium", "Account", "%d Super Administrators" % supers, "",
                     "Reduce to the minimum and use scoped roles.")

        status, payload, tokens = self.cf.get_all("/user/tokens")
        if status == 200:
            self.export["user_tokens_metadata"] = tokens
            for tok in tokens:
                if tok.get("status") != "active":
                    continue
                last = tok.get("last_used_on")
                stale = not last
                if last:
                    try:
                        stale = (now_utc() - dt.datetime.fromisoformat(
                            last.replace("Z", "+00:00"))).days > 90
                    except ValueError:
                        stale = False
                if stale:
                    self.add("low", "Account", "Unused API token",
                             "Token '%s' has not been used in 90 days." % tok.get("name"),
                             "Revoke it.", {"name": tok.get("name"), "last_used_on": last})
                for pol in tok.get("policies", []):
                    res = json.dumps(pol.get("resources", {}))
                    perms = " ".join(p.get("name", "") for p in pol.get("permission_groups", []))
                    if "zone.*" in res and "Write" in perms:
                        self.add("medium", "Account", "Token can edit every zone",
                                 "Token '%s' has write permissions on all zones." % tok.get("name"),
                                 "Scope tokens to the zone and the permissions they need.",
                                 {"name": tok.get("name")})
        else:
            self.unverified.append({"area": "Account", "endpoint": "/user/tokens",
                                    "http_status": status, "reason": errmsg(payload)})

        policies = self.fetch("Logging", "/accounts/%s/alerting/v3/policies" % a) or []
        self.snapshot["notification_policies"] = sorted(p.get("name", "") for p in policies)
        if not policies:
            self.add("medium", "Logging", "No notification policies",
                     "Nobody is told when security relevant settings change.",
                     "Create alerts, and run this audit daily with --baseline.")

        status, payload = self.cf.call("GET", "/accounts/%s/registrar/domains/%s"
                                       % (a, self.zone_name))
        if status == 200:
            locked = (payload.get("result") or {}).get("locked")
            if locked:
                self.ok("Account", "Registrar lock enabled")
            else:
                self.add("medium", "Account", "Registrar lock disabled", "",
                         "Enable the transfer lock.")
        else:
            self.unverified.append({"area": "Account", "endpoint": "registrar",
                                    "http_status": status,
                                    "reason": "Not on Cloudflare Registrar or no permission; "
                                              "check the lock at your registrar."})

    def compare_baseline(self, baseline):
        def diff(key, sev, title, rec):
            old, new = set(baseline.get(key, [])), set(self.snapshot.get(key, []))
            added, removed = sorted(new - old), sorted(old - new)
            if added or removed:
                self.add(sev, "Drift", title, "Added: %s. Removed: %s." % (added, removed), rec,
                         {"added": added, "removed": removed})

        diff("skip_rules", "critical", "Skip rules changed since baseline",
             "Confirm the change was approved, then refresh the baseline.")
        diff("ip_allow_rules", "high", "IP allow rules changed since baseline",
             "Confirm or revert.")
        diff("unproxied_dns", "high", "Unproxied DNS records changed since baseline",
             "Confirm or revert.")
        diff("origin_rules", "high", "Origin rules changed since baseline", "Confirm or revert.")
        diff("worker_routes", "high", "Worker routes changed since baseline", "Confirm or revert.")
        diff("config_rules", "high", "Configuration rules changed since baseline",
             "Confirm or revert.")
        diff("notification_policies", "high", "Notification policies changed since baseline",
             "Confirm or revert.")
        diff("logpush_jobs", "high", "Logpush jobs changed since baseline", "Confirm or revert.")
        old_m = set(baseline.get("managed_executes", []))
        new_m = set(self.snapshot.get("managed_executes", []))
        if old_m - new_m:
            self.add("high", "Drift", "Managed ruleset removed since baseline",
                     "No longer deployed: %s." % sorted(old_m - new_m), "Redeploy it.")
        if baseline.get("zone_aop_enabled") and not self.snapshot.get("zone_aop_enabled"):
            self.add("critical", "Drift", "Origin authentication disabled since baseline", "",
                     "Re enable zone level AOP.")
        old_s, new_s = baseline.get("settings", {}), self.snapshot.get("settings", {})
        for key in sorted(set(old_s) | set(new_s)):
            if old_s.get(key) != new_s.get(key):
                sev = "critical" if key == "ssl" else "high"
                self.add(sev, "Drift", "Setting %s changed since baseline" % key,
                         "Was %s, now %s." % (json.dumps(old_s.get(key)), json.dumps(new_s.get(key))),
                         "Confirm or revert.")

    def run(self):
        self.load_zone()
        self.check_dns()
        self.check_settings()
        self.check_origin_auth()
        self.check_rulesets()
        self.check_ip_access_rules()
        self.check_legacy()
        self.check_workers_snippets()
        self.check_zone_features()
        self.check_account()
        self.findings.sort(key=lambda f: SEVERITIES.index(f["severity"]))


def render_markdown(audit):
    counts = {s: sum(1 for f in audit.findings if f["severity"] == s) for s in SEVERITIES}
    lines = [
        "# Cloudflare security audit: %s" % audit.zone_name,
        "",
        "Generated %s UTC. Plan: %s. Zone ID: %s." % (
            now_utc().strftime("%Y-%m-%d %H:%M"), audit.plan, audit.zone_id),
        "",
        "| Severity | Count |", "|---|---|",
    ]
    lines += ["| %s | %d |" % (s, counts[s]) for s in SEVERITIES]
    lines += ["", "Origin addresses considered: %s" % (", ".join(sorted(audit.origin_ips)) or "none"),
              "", "## Findings", ""]
    if not audit.findings:
        lines.append("No findings.")
    for i, f in enumerate(audit.findings, 1):
        lines += ["### %d. [%s] %s: %s" % (i, f["severity"].upper(), f["area"], f["title"]), ""]
        if f["detail"]:
            lines += [f["detail"], ""]
        lines += ["Recommendation: " + f["recommendation"], ""]
        if f["evidence"] is not None:
            ev = json.dumps(f["evidence"], indent=2, sort_keys=True, default=str)
            if len(ev) > 1500:
                ev = ev[:1500] + "\n... (truncated; full data in config-export.json)"
            lines += ["```json", ev, "```", ""]
    lines += ["## Checks that passed", ""]
    lines += ["- %s: %s" % (p["area"], p["check"]) for p in audit.passed] or ["- none"]
    lines += ["", "## Not verified", "",
              "These checks could not be run (usually a missing token permission or a plan "
              "limit). Treat them as unknown, not as passed.", ""]
    lines += ["- %s: `%s` (HTTP %s) %s" % (u["area"], u["endpoint"], u["http_status"], u["reason"])
              for u in audit.unverified] or ["- none"]
    lines += ["", "## Not covered by this script", "",
              "- Whether the origin actually refuses direct connections: run cf_origin_tests.sh.",
              "- Origin web server, application and plugin trust of forwarded headers: review by hand.",
              "- Worker and Snippet source code: review by hand.",
              "- Historical DNS exposure: check passive DNS services for old A records.", ""]
    return "\n".join(lines)


def main():
    ap = argparse.ArgumentParser(description="Read only Cloudflare WAF and origin audit")
    ap.add_argument("--zone", required=True)
    ap.add_argument("--account-id")
    ap.add_argument("--origin-ip", action="append", default=[],
                    help="Known origin address (repeatable). Proxied A/AAAA targets are added "
                         "automatically.")
    ap.add_argument("--profile", choices=["generic", "wordpress"], default="generic",
                    help="wordpress adds WordPress file checks and uses /wp-login.php and "
                         "/wp-admin as login and admin paths")
    ap.add_argument("--login-path", action="append", default=[],
                    help="Login path that should be challenged and rate limited (repeatable)")
    ap.add_argument("--admin-path", action="append", default=[],
                    help="Admin path that should sit behind Cloudflare Access (repeatable)")
    ap.add_argument("--trusted-range", action="append", default=[],
                    help="Corporate, office or VPN range you trust (repeatable). Exemptions "
                         "covering it are reported as critical.")
    ap.add_argument("--egress-ip", action="append", default=[],
                    help="Public egress address of a system that fetches URLs for others "
                         "(proxy, integration). Answers: which rules would exempt it?")
    ap.add_argument("--out-dir", default="audit-" + now_utc().strftime("%Y%m%d-%H%M%S"))
    ap.add_argument("--baseline", help="Compare against this approved baseline JSON")
    ap.add_argument("--save-baseline", help="Write the current snapshot as a new baseline")
    args = ap.parse_args()

    token = os.environ.get("CF_API_TOKEN")
    if not token:
        print("Set CF_API_TOKEN to a read only API token.", file=sys.stderr)
        return 3
    cf = CF(token)
    status, payload = cf.call("GET", "/user/tokens/verify")
    if status != 200 and args.account_id:
        status, payload = cf.call("GET", "/accounts/%s/tokens/verify" % args.account_id)
    if status != 200:
        print("Token verification failed: %s" % errmsg(payload), file=sys.stderr)
        return 3

    audit = Audit(cf, args.zone, args.origin_ip, args.account_id,
                  args.trusted_range, args.egress_ip, args.profile,
                  args.login_path, args.admin_path)
    try:
        audit.run()
    except SystemExit as err:
        print(err, file=sys.stderr)
        return 3
    if args.baseline:
        with open(args.baseline) as fh:
            audit.compare_baseline(json.load(fh))
        audit.findings.sort(key=lambda f: SEVERITIES.index(f["severity"]))

    os.makedirs(args.out_dir, exist_ok=True)
    with open(os.path.join(args.out_dir, "report.md"), "w") as fh:
        fh.write(render_markdown(audit))
    with open(os.path.join(args.out_dir, "findings.json"), "w") as fh:
        json.dump({"zone": audit.zone_name, "plan": audit.plan, "findings": audit.findings,
                   "passed": audit.passed, "unverified": audit.unverified,
                   "snapshot": audit.snapshot}, fh, indent=2, default=str)
    with open(os.path.join(args.out_dir, "config-export.json"), "w") as fh:
        json.dump(audit.export, fh, indent=2, default=str)
    if args.save_baseline:
        snap = dict(audit.snapshot)
        snap["_sha256"] = hashlib.sha256(json.dumps(snap, sort_keys=True).encode()).hexdigest()
        with open(args.save_baseline, "w") as fh:
            json.dump(snap, fh, indent=2, sort_keys=True)

    sev = {f["severity"] for f in audit.findings}
    summary = ", ".join("%d %s" % (sum(1 for f in audit.findings if f["severity"] == s), s)
                        for s in SEVERITIES)
    print("Report: %s/report.md (%s; %d checks not verified)"
          % (args.out_dir, summary, len(audit.unverified)))
    return 2 if "critical" in sev else 1 if "high" in sev else 0


if __name__ == "__main__":
    sys.exit(main())
EOF
chmod +x cf_audit.py

Run it, read the report, and save the first clean run as your baseline once you have approved it:

cat > run_audit.sh << 'EOF'
#!/usr/bin/env bash
# run_audit.sh: run the read only audit and keep each report.
set -uo pipefail
: "${CF_API_TOKEN:?export CF_API_TOKEN with the READ ONLY token first}"
ZONE="${ZONE:-example.com}"
OUT="audits/$(date -u +%Y%m%d-%H%M%S)"

# First run: no baseline yet. Add --origin-ip for any address you know the
# origin has used, so the DNS checks can spot it in mail and SPF records.
rc=0
if [ -f baseline.json ]; then
  python3 cf_audit.py --zone "$ZONE" --out-dir "$OUT" --baseline baseline.json "$@" || rc=$?
else
  python3 cf_audit.py --zone "$ZONE" --out-dir "$OUT" "$@" || rc=$?
fi
echo "Read ${OUT}/report.md. When every finding is fixed or accepted, approve a baseline:"
echo "  python3 cf_audit.py --zone $ZONE --out-dir $OUT --save-baseline baseline.json"
exit $rc
EOF
chmod +x run_audit.sh

The exit code is 2 if there are critical findings and 1 for high, which is what makes it useful in a scheduler later.

10. Script 2: applying the baseline

cf_harden.py is a dry run until you pass --apply. With --apply it makes two passes: the first only reads, and writes a timestamped backup of every setting and ruleset phase it is about to touch; the second makes the changes. Every rule it creates carries a fixed ref, so running it twice changes nothing, and running it after someone edits a baseline rule puts it back. It will not set Full (strict) unless you pass --strict-ssl, because doing that before the origin has a valid certificate takes the site down with 526 errors. HSTS is opt in for the same reason, and starts at a one day max age. The application rules come from section 7.1: the generic block rule always, the WordPress additions with --profile wordpress, login protection with --login-path, and the API rule with --api-hostname. It leaves Security Level alone, except to switch Under Attack mode off when you pass --end-under-attack.

It deliberately does not delete existing exceptions on its own judgement. Removing an IP allow rule or a Skip rule is a decision that needs the context of why it was added, so you pass the IDs from the audit report explicitly with --delete-ip-allow and --disable-rule, and the backup captures them for rollback.

cat > cf_harden.py << 'EOF'
#!/usr/bin/env python3
"""
cf_harden.py: apply a security baseline to a Cloudflare zone, with optional
application profiles (--profile wordpress) and API host rules (--api-hostname).

Dry run by default: it prints what it would change and touches nothing.
With --apply it first writes a backup of everything it is about to change,
then makes the changes. --rollback restores a backup.

Usage:
  export CF_API_TOKEN="..."            # edit token, separate from the audit token
  python3 cf_harden.py --zone example.com                 # dry run
  python3 cf_harden.py --zone example.com --apply --strict-ssl
  python3 cf_harden.py --zone example.com --profile wordpress           # WordPress site
  python3 cf_harden.py --zone example.com --login-path /login \
      --api-hostname api.example.com                                     # app plus API
  python3 cf_harden.py --zone example.com --apply \
      --aop-cert cf-aop/client.crt --aop-key cf-aop/client.key
  python3 cf_harden.py --zone example.com --rollback backups/backup-20261204-1800.json --apply

What it changes (each item can be switched off):
  * TLS settings: Full (strict) [only with --strict-ssl], minimum TLS 1.2, TLS 1.3,
    Always Use HTTPS, Automatic HTTPS Rewrites, Browser Integrity Check.
    HSTS only with --hsts. Under Attack mode switched off only with --end-under-attack.
  * URL normalization of incoming URLs.
  * A block rule for files no site should serve (dotfiles at any depth, database
    dumps, backups, archives outside public folders), plus WordPress paths with
    --profile wordpress.
  * A managed challenge and a rate limiting rule on login paths (--login-path, or
    /wp-login.php with --profile wordpress).
  * Optional (--api-hostname): block Swagger, OpenAPI and actuator paths on API hosts.
  * Cloudflare Managed Ruleset (block) and OWASP Core Ruleset (log) on Pro and above.
  * Leaked credentials detection.
  * Optional: upload a zone level AOP client certificate and enable it.
  * Optional: delete named IP Access allow rules, disable named WAF rules.
"""
import argparse
import datetime as dt
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

API = "https://api.cloudflare.com/client/v4"
REF_BLOCK = "baseline_block_sensitive"
REF_LOGIN = "baseline_login_challenge"
REF_RL = "baseline_login_ratelimit"
# Rules created by earlier releases under WordPress specific names are adopted,
# not duplicated.
LEGACY_REFS = {REF_BLOCK: "baseline_wp_block_sensitive",
               REF_LOGIN: "baseline_wp_login_challenge",
               REF_RL: "baseline_wp_login_ratelimit"}
PROFILE_DEFAULTS = {
    "generic": {"login_paths": [], "public_prefixes": []},
    "wordpress": {"login_paths": ["/wp-login.php"], "public_prefixes": ["/wp-content/uploads/"]},
}
REF_API = "baseline_api_surface"
REF_MANAGED = "baseline_cf_managed"
REF_OWASP = "baseline_cf_owasp"
RULE_KEYS = ("action", "action_parameters", "expression", "description", "enabled",
             "ref", "ratelimit", "logging")


class CF:
    def __init__(self, token):
        self.token = token

    def call(self, method, path, body=None, params=None):
        url = API + path
        if params:
            url += "?" + urllib.parse.urlencode(params)
        data = json.dumps(body).encode() if body is not None else None
        req = urllib.request.Request(url, data=data, method=method)
        req.add_header("Authorization", "Bearer " + self.token)
        req.add_header("Content-Type", "application/json")
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                return resp.status, json.loads(resp.read().decode() or "{}")
        except urllib.error.HTTPError as err:
            try:
                return err.code, json.loads(err.read().decode() or "{}")
            except Exception:
                return err.code, {"success": False, "errors": [{"message": str(err)}]}
        except urllib.error.URLError as err:
            return 0, {"success": False, "errors": [{"message": str(err.reason)}]}


def errmsg(payload):
    return "; ".join(str(e.get("message", e)) for e in payload.get("errors") or []) or "unknown"


class Harden:
    def __init__(self, cf, args):
        self.cf = cf
        self.args = args
        self.apply = args.apply
        self.plan_lines = []
        self.failures = []
        self.backup = {"created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
                       "zone": args.zone, "settings": {}, "rulesets": {},
                       "url_normalization": None, "leaked_credentials": None,
                       "aop_enabled": None, "deleted_access_rules": [],
                       "disabled_rules": []}
        status, payload = cf.call("GET", "/zones", params={"name": args.zone})
        if status != 200 or not payload.get("result"):
            raise SystemExit("Zone lookup failed: %s" % errmsg(payload))
        zone = payload["result"][0]
        self.z = zone["id"]
        plan = zone.get("plan", {})
        self.plan = (plan.get("legacy_id") or plan.get("name") or "").lower()
        self.free = self.plan in ("free", "free website")
        hosts = args.hostname or [args.zone, "www." + args.zone]
        self.host_set = "{" + " ".join('"%s"' % h for h in hosts) + "}"
        defaults = PROFILE_DEFAULTS[args.profile]
        self.login_paths = args.login_path or defaults["login_paths"]
        self.public_prefixes = (args.public_prefix or []) + defaults["public_prefixes"]

    # plumbing
    def say(self, text):
        self.plan_lines.append(text)
        print(("APPLY  " if self.apply else "PLAN   ") + text)

    def do(self, method, path, body=None, what=""):
        if not self.apply:
            return True, None
        status, payload = self.cf.call(method, path, body)
        if status in (200, 201) and payload.get("success", True):
            return True, payload.get("result")
        self.failures.append("%s: HTTP %s %s" % (what or path, status, errmsg(payload)))
        print("FAILED %s: HTTP %s %s" % (what or path, status, errmsg(payload)))
        return False, None

    def entrypoint(self, phase):
        status, payload = self.cf.call(
            "GET", "/zones/%s/rulesets/phases/%s/entrypoint" % (self.z, phase))
        if status == 200:
            return payload.get("result")
        if status == 404:
            return None
        raise SystemExit("Cannot read %s entrypoint: HTTP %s %s" % (phase, status, errmsg(payload)))

    def remember_phase(self, phase, ep):
        if phase not in self.backup["rulesets"]:
            self.backup["rulesets"][phase] = (
                [{k: r[k] for k in RULE_KEYS if k in r} for r in ep.get("rules", [])]
                if ep else None)

    def ensure_rule(self, phase, rule, position_first=False, max_rules=None):
        """Create or update a rule identified by its ref. Idempotent."""
        ep = self.entrypoint(phase)
        self.remember_phase(phase, ep)
        rules = (ep or {}).get("rules", [])
        refs = {rule["ref"], LEGACY_REFS.get(rule["ref"])}
        existing = next((r for r in rules if r.get("ref") in refs), None)
        if existing:
            same = all(existing.get(k) == rule.get(k) for k in rule if k != "ref")
            if same:
                print("OK     %s: rule '%s' already in place" % (phase, rule["description"]))
                return
            self.say("%s: update rule '%s'" % (phase, rule["description"]))
            self.do("PATCH", "/zones/%s/rulesets/%s/rules/%s" % (self.z, ep["id"], existing["id"]),
                    rule, "update " + rule["ref"])
            return
        if max_rules is not None and len(rules) >= max_rules:
            msg = ("%s: cannot add '%s', the plan limit of %d rules is used. Merge or remove "
                   "rules first." % (phase, rule["description"], max_rules))
            print("SKIP   " + msg)
            self.failures.append(msg)
            return
        self.say("%s: add rule '%s'\n         expression: %s"
                 % (phase, rule["description"], rule["expression"]))
        if ep:
            body = dict(rule)
            if position_first and rules:
                body["position"] = {"index": 1}
            self.do("POST", "/zones/%s/rulesets/%s/rules" % (self.z, ep["id"]), body,
                    "add " + rule["ref"])
        else:
            self.do("PUT", "/zones/%s/rulesets/phases/%s/entrypoint" % (self.z, phase),
                    {"rules": [rule]}, "create %s entrypoint" % phase)

    # steps
    def settings(self):
        desired = {
            "min_tls_version": "1.2",
            "tls_1_3": "on",
            "always_use_https": "on",
            "automatic_https_rewrites": "on",
            "browser_check": "on",
        }
        if self.args.strict_ssl:
            desired["ssl"] = "strict"
        # Security Level is no longer a reputation threshold: it now only switches
        # Under Attack mode. Leave it alone unless it was left on by mistake.
        status, payload = self.cf.call("GET", "/zones/%s/settings/security_level" % self.z)
        if status == 200 and payload["result"]["value"] == "under_attack" and self.args.end_under_attack:
            desired["security_level"] = "medium"
        if self.args.hsts:
            desired["security_header"] = {"strict_transport_security": {
                "enabled": True, "max_age": self.args.hsts_max_age,
                "include_subdomains": False, "preload": False, "nosniff": True}}
        for sid, value in desired.items():
            status, payload = self.cf.call("GET", "/zones/%s/settings/%s" % (self.z, sid))
            if status != 200:
                self.failures.append("read setting %s: %s" % (sid, errmsg(payload)))
                continue
            current = payload["result"]["value"]
            if current == value:
                print("OK     setting %s = %s" % (sid, json.dumps(value)))
                continue
            self.backup["settings"][sid] = current
            self.say("setting %s: %s -> %s" % (sid, json.dumps(current), json.dumps(value)))
            self.do("PATCH", "/zones/%s/settings/%s" % (self.z, sid), {"value": value}, sid)
        if not self.args.strict_ssl:
            print("NOTE   SSL mode untouched. Prove the origin certificate validates, then rerun "
                  "with --strict-ssl.")

    def url_normalization(self):
        status, payload = self.cf.call("GET", "/zones/%s/url_normalization" % self.z)
        if status != 200:
            self.failures.append("read url_normalization: " + errmsg(payload))
            return
        cur = payload["result"]
        if cur.get("scope") in ("incoming", "both"):
            print("OK     URL normalization scope %s" % cur["scope"])
            return
        self.backup["url_normalization"] = cur
        self.say("URL normalization: %s -> cloudflare/incoming" % json.dumps(cur))
        self.do("PUT", "/zones/%s/url_normalization" % self.z,
                {"type": "cloudflare", "scope": "incoming"}, "url_normalization")

    def custom_rules(self):
        p = 'lower(http.request.uri.path)'
        # Generic baseline: things no public site should ever serve.
        parts = [
            # Any path segment starting with a dot (.env, .git, .htpasswd, .aws)
            # at any depth, except /.well-known/ which certificate validation needs.
            '(%s contains "/." and not starts_with(%s, "/.well-known/"))' % (p, p),
            'ends_with(%s, ".sql")' % p,
            'ends_with(%s, ".sql.gz")' % p,
            'ends_with(%s, ".bak")' % p,
        ]
        # Archives are where backup jobs leave dumps. Folders that publish real
        # downloads are excluded (--public-prefix; WordPress: uploads).
        archives = '(ends_with(%s, ".zip") or ends_with(%s, ".tar.gz") or ends_with(%s, ".tgz"))' % (p, p, p)
        for prefix in self.public_prefixes:
            archives += ' and not starts_with(%s, "%s")' % (p, prefix)
        parts.append("(%s)" % archives)
        if self.args.profile == "wordpress":
            parts += [
                'starts_with(%s, "/wp-config.php")' % p,
                '%s eq "/wp-content/debug.log"' % p,
                '(starts_with(%s, "/wp-content/uploads/") and %s contains ".php")' % (p, p),
                'starts_with(%s, "/wp-content/ai1wm-backups")' % p,
                'starts_with(%s, "/wp-content/updraft")' % p,
                'starts_with(%s, "/wp-content/backup")' % p,
            ]
            if not self.args.allow_xmlrpc:
                parts.insert(0, '%s eq "/xmlrpc.php"' % p)
        block = {
            "ref": REF_BLOCK,
            "description": "Baseline: block sensitive files (%s profile)" % self.args.profile,
            "action": "block",
            "enabled": True,
            "expression": "(http.host in %s) and (%s)" % (self.host_set, " or ".join(parts)),
        }
        limit = 5 if self.free else None
        self.ensure_rule("http_request_firewall_custom", block, position_first=True,
                         max_rules=limit)
        if self.login_paths and not self.args.no_login_challenge:
            paths = "{" + " ".join('"%s"' % x.lower() for x in self.login_paths) + "}"
            login = {
                "ref": REF_LOGIN,
                "description": "Baseline: managed challenge on login paths",
                "action": "managed_challenge",
                "enabled": True,
                "expression": "(http.host in %s) and (%s in %s)" % (self.host_set, p, paths),
            }
            self.ensure_rule("http_request_firewall_custom", login, position_first=True,
                             max_rules=limit)
        elif not self.login_paths:
            print("NOTE   No login path given (--login-path), so no login challenge or rate limit.")

    def api_surface(self):
        """Block API documentation and Spring Boot management paths on API hosts."""
        if not self.args.api_hostname:
            return
        hosts = "{" + " ".join('"%s"' % h for h in self.args.api_hostname) + "}"
        p = 'lower(http.request.uri.path)'
        prefixes = ["/swagger-ui", "/swagger-resources", "/v2/api-docs", "/v3/api-docs",
                    "/api-docs", "/openapi", "/actuator", "/management", "/webjars/swagger"]
        parts = ['starts_with(%s, "%s")' % (p, x) for x in prefixes]
        parts += ['%s contains "/swagger-ui"' % p, '%s contains "/v3/api-docs"' % p,
                  '%s contains "/actuator/"' % p, '%s eq "/"' % p if self.args.api_block_root else None]
        parts = [x for x in parts if x]
        rule = {
            "ref": REF_API,
            "description": "Baseline: block API docs and management endpoints",
            "action": "block",
            "enabled": True,
            "expression": "(http.host in %s) and (%s)" % (hosts, " or ".join(parts)),
        }
        self.ensure_rule("http_request_firewall_custom", rule, position_first=True,
                         max_rules=5 if self.free else None)

    def rate_limit(self):
        # Free plan: one rule, 10 second period and timeout, limited fields.
        if not self.login_paths:
            return
        paths = "{" + " ".join('"%s"' % x for x in self.login_paths) + "}"
        expr = '(http.request.uri.path in %s)' % paths
        if not self.free:
            expr = '(http.request.uri.path in %s and http.request.method eq "POST")' % paths
        rule = {
            "ref": REF_RL,
            "description": "Baseline: rate limit login paths",
            "action": "block",
            "enabled": True,
            "expression": expr,
            "ratelimit": {
                "characteristics": ["cf.colo.id", "ip.src"],
                "period": self.args.rl_period,
                "requests_per_period": self.args.rl_requests,
                "mitigation_timeout": self.args.rl_timeout,
            },
        }
        self.ensure_rule("http_ratelimit", rule, max_rules=1 if self.free else None)

    def managed(self):
        if self.free:
            print("NOTE   Free plan: the Free Managed Ruleset is deployed automatically. The full "
                  "Managed and OWASP rulesets need Pro.")
            return
        status, payload = self.cf.call("GET", "/zones/%s/rulesets" % self.z)
        if status != 200:
            self.failures.append("list rulesets: " + errmsg(payload))
            return
        by_name = {r.get("name"): r["id"] for r in payload["result"] if r.get("kind") == "managed"}
        ep = self.entrypoint("http_request_firewall_managed")
        executed = {(r.get("action_parameters") or {}).get("id")
                    for r in (ep or {}).get("rules", []) if r.get("action") == "execute"}
        wanted = [("Cloudflare Managed Ruleset", REF_MANAGED, None)]
        owasp_override = None if self.args.owasp_enforce else {"action": "log"}
        wanted.append(("Cloudflare OWASP Core Ruleset", REF_OWASP, owasp_override))
        for name, ref, overrides in wanted:
            rid = by_name.get(name)
            if not rid:
                print("NOTE   %s not available to this zone" % name)
                continue
            if rid in executed:
                print("OK     %s already deployed" % name)
                continue
            ap = {"id": rid}
            if overrides:
                ap["overrides"] = overrides
            self.ensure_rule("http_request_firewall_managed", {
                "ref": ref, "description": "Baseline: execute " + name,
                "action": "execute", "enabled": True, "expression": "true",
                "action_parameters": ap})

    def leaked_credentials(self):
        status, payload = self.cf.call("GET", "/zones/%s/leaked-credential-checks" % self.z)
        if status != 200:
            print("NOTE   leaked credentials detection not readable: " + errmsg(payload))
            return
        if payload["result"].get("enabled"):
            print("OK     leaked credentials detection enabled")
            return
        self.backup["leaked_credentials"] = payload["result"]
        self.say("leaked credentials detection: off -> on")
        self.do("POST", "/zones/%s/leaked-credential-checks" % self.z, {"enabled": True},
                "leaked credentials")

    def aop(self):
        if not (self.args.aop_cert or self.args.aop_enable_only):
            return
        status, payload = self.cf.call("GET", "/zones/%s/origin_tls_client_auth/settings" % self.z)
        self.backup["aop_enabled"] = (payload.get("result") or {}).get("enabled", False)
        if self.args.aop_cert:
            with open(self.args.aop_cert) as fh:
                cert = fh.read()
            with open(self.args.aop_key) as fh:
                key = fh.read()
            self.say("upload zone level AOP client certificate %s" % self.args.aop_cert)
            self.do("POST", "/zones/%s/origin_tls_client_auth" % self.z,
                    {"certificate": cert, "private_key": key}, "upload AOP certificate")
        self.say("enable zone level Authenticated Origin Pulls")
        self.do("PUT", "/zones/%s/origin_tls_client_auth/settings" % self.z, {"enabled": True},
                "enable AOP")
        print("NOTE   Cloudflare now presents your certificate. Enforce it at the origin "
              "(ssl_verify_client on) only after origin logs show it arriving.")

    def removals(self):
        for rule_id in self.args.delete_ip_allow or []:
            path = "/zones/%s/firewall/access_rules/rules/%s" % (self.z, rule_id)
            status, payload = self.cf.call("GET", "/zones/%s/firewall/access_rules/rules"
                                           % self.z, params={"per_page": 1000})
            match = next((r for r in payload.get("result") or [] if r["id"] == rule_id), None)
            if not match:
                self.failures.append("IP access rule %s not found at zone level" % rule_id)
                continue
            self.backup["deleted_access_rules"].append(match)
            self.say("delete IP Access allow rule %s (%s)" % (rule_id, match.get("configuration")))
            self.do("DELETE", path, None, "delete access rule " + rule_id)
        for spec in self.args.disable_rule or []:
            phase, rule_id = spec.split(":", 1)
            ep = self.entrypoint(phase)
            self.remember_phase(phase, ep)
            match = next((r for r in (ep or {}).get("rules", []) if r["id"] == rule_id), None)
            if not match:
                self.failures.append("rule %s not found in %s" % (rule_id, phase))
                continue
            self.backup["disabled_rules"].append({"phase": phase, "id": rule_id})
            self.say("disable %s rule '%s'" % (phase, match.get("description") or rule_id))
            self.do("PATCH", "/zones/%s/rulesets/%s/rules/%s" % (self.z, ep["id"], rule_id),
                    {k: match[k] for k in ("action", "expression", "description",
                                           "action_parameters", "ratelimit") if k in match}
                    | {"enabled": False}, "disable " + rule_id)

    def rollback(self, path):
        with open(path) as fh:
            bk = json.load(fh)
        for sid, value in bk.get("settings", {}).items():
            self.say("restore setting %s -> %s" % (sid, json.dumps(value)))
            self.do("PATCH", "/zones/%s/settings/%s" % (self.z, sid), {"value": value}, sid)
        if bk.get("url_normalization"):
            un = bk["url_normalization"]
            self.say("restore URL normalization -> %s" % json.dumps(un))
            self.do("PUT", "/zones/%s/url_normalization" % self.z,
                    {"type": un.get("type", "cloudflare"), "scope": un.get("scope", "none")})
        if bk.get("leaked_credentials") is not None:
            self.say("restore leaked credentials -> %s" % bk["leaked_credentials"])
            self.do("POST", "/zones/%s/leaked-credential-checks" % self.z,
                    {"enabled": bool(bk["leaked_credentials"].get("enabled"))})
        if bk.get("aop_enabled") is not None:
            self.say("restore zone AOP enabled -> %s" % bk["aop_enabled"])
            self.do("PUT", "/zones/%s/origin_tls_client_auth/settings" % self.z,
                    {"enabled": bk["aop_enabled"]})
        for phase, rules in bk.get("rulesets", {}).items():
            self.say("restore %s entrypoint (%d rules)" % (phase, len(rules or [])))
            self.do("PUT", "/zones/%s/rulesets/phases/%s/entrypoint" % (self.z, phase),
                    {"rules": rules or []}, "restore " + phase)
        for rule in bk.get("deleted_access_rules", []):
            self.say("recreate IP Access rule %s" % rule.get("configuration"))
            self.do("POST", "/zones/%s/firewall/access_rules/rules" % self.z,
                    {"mode": rule["mode"], "configuration": rule["configuration"],
                     "notes": rule.get("notes", "")})

    def write_backup(self):
        os.makedirs(self.args.backup_dir, exist_ok=True)
        name = "backup-%s.json" % dt.datetime.now().strftime("%Y%m%d-%H%M%S")
        path = os.path.join(self.args.backup_dir, name)
        with open(path, "w") as fh:
            json.dump(self.backup, fh, indent=2)
        return path


def main():
    ap = argparse.ArgumentParser(description="Apply a security baseline to a Cloudflare zone")
    ap.add_argument("--zone", required=True)
    ap.add_argument("--hostname", action="append",
                    help="Hostnames the baseline rules cover (default: zone and www)")
    ap.add_argument("--profile", choices=sorted(PROFILE_DEFAULTS), default="generic",
                    help="generic (default) or wordpress, which adds WordPress paths, "
                         "/wp-login.php as the login path and uploads as a public folder")
    ap.add_argument("--login-path", action="append",
                    help="Login path to challenge and rate limit (repeatable)")
    ap.add_argument("--public-prefix", action="append",
                    help="Path prefix that legitimately serves archives (repeatable)")
    ap.add_argument("--apply", action="store_true", help="Make changes (default is a dry run)")
    ap.add_argument("--strict-ssl", action="store_true",
                    help="Set Full (strict). Only after the origin certificate validates.")
    ap.add_argument("--hsts", action="store_true", help="Enable HSTS (no subdomains, no preload)")
    ap.add_argument("--hsts-max-age", type=int, default=86400,
                    help="Start small (one day), raise after testing")
    ap.add_argument("--allow-xmlrpc", action="store_true",
                    help="wordpress profile: do not block xmlrpc.php (Jetpack or a publishing app)")
    ap.add_argument("--no-login-challenge", action="store_true",
                    help="Skip the login challenge (for example when Access protects it)")
    ap.add_argument("--api-hostname", action="append",
                    help="API host whose docs (Swagger, OpenAPI) and management (actuator) "
                         "paths should be blocked at the edge (repeatable)")
    ap.add_argument("--api-block-root", action="store_true",
                    help="Also block '/' on API hosts (when the gateway serves Swagger UI at the root)")
    ap.add_argument("--end-under-attack", action="store_true",
                    help="Switch Under Attack mode off if it is still on")
    ap.add_argument("--rl-requests", type=int, default=5)
    ap.add_argument("--rl-period", type=int, default=10)
    ap.add_argument("--rl-timeout", type=int, default=10)
    ap.add_argument("--owasp-enforce", action="store_true",
                    help="Deploy OWASP in blocking mode instead of log mode")
    ap.add_argument("--aop-cert", help="Leaf client certificate (PEM) for zone level AOP")
    ap.add_argument("--aop-key", help="Private key for --aop-cert")
    ap.add_argument("--aop-enable-only", action="store_true",
                    help="Enable zone level AOP using an already uploaded certificate")
    ap.add_argument("--delete-ip-allow", action="append", metavar="RULE_ID",
                    help="Delete a zone IP Access allow rule (repeatable)")
    ap.add_argument("--disable-rule", action="append", metavar="PHASE:RULE_ID",
                    help="Disable a ruleset rule, e.g. http_request_firewall_custom:abc123")
    ap.add_argument("--rollback", metavar="BACKUP_JSON", help="Restore a backup file")
    ap.add_argument("--backup-dir", default="backups")
    args = ap.parse_args()
    if args.aop_cert and not args.aop_key:
        ap.error("--aop-cert needs --aop-key")

    token = os.environ.get("CF_API_TOKEN")
    if not token:
        print("Set CF_API_TOKEN to an API token with edit rights on the zone.", file=sys.stderr)
        return 3
    h = Harden(CF(token), args)
    print("Zone %s, plan %s, mode %s\n" % (args.zone, h.plan or "unknown",
                                          "APPLY" if args.apply else "DRY RUN"))
    if args.rollback:
        h.rollback(args.rollback)
    else:
        # Read everything first so the backup is complete before any write.
        steps = [h.settings, h.url_normalization, h.custom_rules, h.api_surface, h.rate_limit, h.managed,
                 h.leaked_credentials, h.aop, h.removals]
        if args.apply:
            apply_flag, h.apply = True, False
            print("Pass 1: reading current state for the backup\n")
            for step in steps:
                step()
            path = h.write_backup()
            print("\nBackup written to %s (rollback: --rollback %s --apply)\n" % (path, path))
            print("Pass 2: applying\n")
            h.apply, h.failures, h.plan_lines = apply_flag, [], []
            h.backup_written = path
            for step in steps:
                step()
        else:
            for step in steps:
                step()
    print("\n%d change(s) %s, %d problem(s)."
          % (len(h.plan_lines), "made" if args.apply else "planned", len(h.failures)))
    for f in h.failures:
        print("  - " + f)
    return 1 if h.failures else 0


if __name__ == "__main__":
    sys.exit(main())
EOF
chmod +x cf_harden.py

11. Script 3: the acceptance tests

Configuration only tells you what should happen. These tests, run from a machine outside your hosting network, show what does happen. They connect straight to the origin on IPv4 and IPv6 with and without a valid Host header, try the provider’s hostnames, present no client certificate and then an untrusted one, send spoofed forwarding headers and a Googlebot User-Agent to see whether any decision changes, request a set of sensitive files, check the login challenge and admin protection when you name those paths, send a fake session cookie to look for cached private pages, confirm that normal pages, robots.txt and the sitemap still work, check documentation and management endpoints on API hosts, and check the TLS floor, HTTPS redirect and HSTS header. PROFILE=wordpress fills in the WordPress paths and cookie name and adds XML-RPC, REST and public AJAX checks.

The trickiest test is the second bucket from section 5. To prove another Cloudflare account cannot reach your origin, create a free zone in a separate Cloudflare account using a throwaway domain you own, add a proxied A record pointing at your origin IP with every security feature off, and pass that hostname as FOREIGN_HOST. Configure that zone the way a careful attacker would: set its SSL/TLS mode to Full, so it connects to your origin on port 443 rather than port 80 (new zones may otherwise choose Flexible), and turn on global Authenticated Origin Pulls there, so it presents the shared Cloudflare client certificate. Without those two settings, a custom AOP origin passes the test simply because port 80 is closed, and the test never asks the question that matters, which is whether your origin rejects the shared certificate. With a tunnel there is nothing listening, and with custom AOP the origin rejects the shared certificate, so you should see a Cloudflare 52x error. If you see your site, the origin trusts anything that comes from Cloudflare’s ranges.

Every result is one of PASS, FAIL or UNVERIFIED, and the difference between the last two matters. FAIL means the test produced evidence that a control is broken. UNVERIFIED means it produced no evidence either way, and it never counts as a pass. The script exits 0 (automated sign off) only when nothing failed and nothing required is unverified, 1 when something failed, and 2 when sign off is withheld for missing evidence; MANUAL items always need a person and are listed separately.

The direct to origin probes show why this matters. In both modes the firewall should make the web listener unreachable from outside, so only “connection refused” or “timed out” counts as a PASS. If a TCP connection completes at all, the result is FAIL, even when TLS or the application then rejects the request, because the listener itself is exposed. Any other curl error, such as a malformed URL, a name that does not resolve or a local proxy answering on the target’s behalf, is UNVERIFIED. Treating curl errors as passes is the classic way these scripts lie: a typo in the origin address would produce a green result. The probes also bypass any configured HTTP proxy, which would otherwise answer for the target and distort the result. Because the firewall stops outside probes before TLS, client certificate enforcement in AOP mode cannot be exercised from your laptop at all. Run the script on the origin with CERT_TEST_TARGET=127.0.0.1 to test nginx directly; until you do, that check reports UNVERIFIED.

A 403 response with a cf-ray header proves less than it seems to. The Ray ID shows the request passed through Cloudflare, but the 403 could still have come from the origin, so a WAF test that stops there can pass on a site where the WAF does nothing. With CF_API_TOKEN set to a read only token that has Analytics read, the script looks up each Ray ID in Security Events through the GraphQL Analytics API. It marks the WAF, XML-RPC and login checks PASS only when the event shows the expected action from a custom rule, and FAIL when an event shows a different action. If no event appears within two minutes, the result is UNVERIFIED rather than FAIL, because Cloudflare samples Security Events at higher volumes and an individual event may never be listed; check that Ray ID by hand. Without the token these checks are UNVERIFIED too. The requests are deliberately benign, and the WAF test carries a unique marker so you can find it in the logs. Only run the tests against infrastructure you own.

cat > cf_origin_tests.sh << 'EOF'
#!/usr/bin/env bash
# cf_origin_tests.sh: non destructive acceptance tests for a site or API behind
# Cloudflare, with an optional WordPress profile. Run it from a machine OUTSIDE
# your hosting network
# (your laptop), only against infrastructure you own.
#
# Configuration through environment variables:
#   DOMAIN            site hostname (default example.com)
#   PROFILE           generic (default) or wordpress. wordpress sets the defaults
#                     below to WordPress paths and adds XML-RPC, REST and AJAX checks
#   LOGIN_PATH        login page to check for a challenge (wordpress: /wp-login.php)
#   ADMIN_PATH        admin path to check for Access (wordpress: /wp-admin/)
#   SESSION_COOKIE    session cookie name prefix for the cache test
#                     (default session_; wordpress: wordpress_logged_in_)
#   PRIVATE_PATHS     space separated paths that must never be cached
#   SITEMAP_PATHS     sitemap paths to try (wordpress: /wp-sitemap.xml /sitemap_index.xml)
#   EXTRA_SENSITIVE   extra paths that must be denied (space separated)
#   APP_MARKER        regex that identifies your application in a response body,
#                     used to say "served the application" in evidence
#   ORIGIN_IPV4       origin public IPv4 address (optional but strongly advised)
#   ORIGIN_IPV6       origin public IPv6 address (optional)
#   ALT_HOSTS         space separated provider hostnames for the origin
#                     (for example "ec2-203-0-113-10.compute-1.amazonaws.com")
#   FOREIGN_HOST      a hostname in a DIFFERENT Cloudflare account, proxied to
#                     your origin IP, to prove another customer cannot reach it.
#                     Set that zone's SSL/TLS mode to Full (so it uses port 443,
#                     not 80) and turn on global Authenticated Origin Pulls there
#                     (so it presents the shared certificate). Otherwise a closed
#                     port 80 makes the test pass without testing anything.
#   MODE              tunnel or aop (default tunnel)
#   CERT_TEST_TARGET  aop mode only: address that reaches nginx WITHOUT the firewall
#                     in the way, so client certificate enforcement can be exercised.
#                     Run the script on the origin with CERT_TEST_TARGET=127.0.0.1.
#
# Result meanings: PASS = proven. FAIL = proven broken. UNVERIFIED = the test could
# not produce evidence either way (probe error, missing input, missing telemetry).
# Exit code: 0 only when nothing failed and nothing required is unverified
# (automated sign-off); 1 = at least one FAIL; 2 = no FAIL but sign-off withheld.
# MANUAL items always need a human and are listed separately.
#   ALLOW_XMLRPC      wordpress profile: set to 1 if xmlrpc.php must stay reachable
#   API_HOSTS         space separated API hostnames to check for exposed docs and
#                     management endpoints (for example "api.example.com")
#   API_ORIGIN        the API's own load balancer hostname, to prove it refuses
#                     traffic that did not come through your Cloudflare zone
#   OUT_DIR           where to write the report (default ./acceptance)
#   CF_API_TOKEN      optional read only token with Analytics read. When set, WAF
#                     results only PASS once the Ray ID is found in Security Events
#                     with the expected action and source. Without it they are
#                     reported as UNVERIFIED with the Ray ID to look up by hand.
#
# Needs: bash, curl, openssl, dig, python3.
set -u

DOMAIN="${DOMAIN:-example.com}"
PROFILE="${PROFILE:-generic}"
if [ "$PROFILE" = "wordpress" ]; then
  LOGIN_PATH="${LOGIN_PATH-/wp-login.php}"
  ADMIN_PATH="${ADMIN_PATH-/wp-admin/}"
  SESSION_COOKIE="${SESSION_COOKIE:-wordpress_logged_in_}"
  PRIVATE_PATHS="${PRIVATE_PATHS-/?preview=true /wp-admin/admin-ajax.php}"
  SITEMAP_PATHS="${SITEMAP_PATHS-/wp-sitemap.xml /sitemap_index.xml}"
  APP_MARKER="${APP_MARKER:-wp-content|wp-includes|wp-json}"
fi
LOGIN_PATH="${LOGIN_PATH:-}"
ADMIN_PATH="${ADMIN_PATH:-}"
SESSION_COOKIE="${SESSION_COOKIE:-session_}"
PRIVATE_PATHS="${PRIVATE_PATHS:-}"
SITEMAP_PATHS="${SITEMAP_PATHS:-/sitemap.xml}"
EXTRA_SENSITIVE="${EXTRA_SENSITIVE:-}"
APP_MARKER="${APP_MARKER:-<html|<!doctype|swagger|openapi}"
ORIGIN_IPV4="${ORIGIN_IPV4:-}"
ORIGIN_IPV6="${ORIGIN_IPV6:-}"
ALT_HOSTS="${ALT_HOSTS:-}"
FOREIGN_HOST="${FOREIGN_HOST:-}"
MODE="${MODE:-tunnel}"
CERT_TEST_TARGET="${CERT_TEST_TARGET:-}"
ALLOW_XMLRPC="${ALLOW_XMLRPC:-0}"
API_HOSTS="${API_HOSTS:-}"
API_ORIGIN="${API_ORIGIN:-}"
OUT_DIR="${OUT_DIR:-./acceptance}"
CF_API_TOKEN="${CF_API_TOKEN:-}"
STAMP="$(date -u +%Y%m%d-%H%M%S)"
MARKER="cfaudit-${STAMP}"
REPORT="${OUT_DIR}/acceptance-${STAMP}.md"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
mkdir -p "$OUT_DIR"

for bin in curl openssl dig python3; do
  command -v "$bin" >/dev/null || { echo "missing dependency: $bin"; exit 3; }
done

PASS=0; FAIL=0; UNVER=0; OTHER=0; N=0
ROWS=""

record() { # status, name, expected, evidence
  N=$((N + 1))
  case "$1" in
    PASS) PASS=$((PASS + 1)) ;;
    FAIL) FAIL=$((FAIL + 1)) ;;
    UNVERIFIED) UNVER=$((UNVER + 1)) ;;
    *) OTHER=$((OTHER + 1)) ;;
  esac
  local ev="${4//|/\\|}"
  ev="${ev//$'\n'/ }"
  ROWS+="| ${N} | ${2} | ${3} | **${1}** | ${ev:0:300} |"$'\n'
  printf '%-7s %s: %s\n' "$1" "$2" "${4:0:160}"
}

# fetch URL [curl args...]  -> sets CODE, HDRS, BODY_HAS_APP, CURL_RC
fetch() {
  local url="$1"; shift
  : > "$TMP/h"; : > "$TMP/b"
  # --noproxy: a local HTTP proxy would answer on the target's behalf and
  # turn DNS failures or closed ports into misleading results.
  CODE="$(curl -sS --noproxy '*' -o "$TMP/b" -D "$TMP/h" -w '%{http_code}' \
    --connect-timeout 6 --max-time 15 "$@" "$url" 2>"$TMP/err")"
  CURL_RC=$?
  HDRS="$(tr -d '\r' < "$TMP/h")"
  if grep -qiE "$APP_MARKER" "$TMP/b" 2>/dev/null; then
    BODY_HAS_APP=1
  else
    BODY_HAS_APP=0
  fi
  ERR="$(head -c 200 "$TMP/err")"
}

hdr() { printf '%s\n' "$HDRS" | grep -i "^$1:" | head -1 | cut -d' ' -f2- ; }

# A 403 with a cf-ray header only proves the request passed through Cloudflare;
# the origin could have produced the 403 itself. Correlate the Ray ID with
# Security Events (GraphQL Analytics API) to prove which Cloudflare rule acted.
# verify_ray RAY ACTION [SOURCE] -> prints "PASS|..." "FAIL|..." or "UNVERIFIED|..."
verify_ray() {
  local ray="${1%%-*}" action="$2" source="${3:-}"
  if [ -z "$ray" ]; then echo "FAIL|no cf-ray header, request did not pass Cloudflare"; return; fi
  if [ -z "$CF_API_TOKEN" ]; then
    echo "UNVERIFIED|look up Ray ID ${ray} in Security Events (expect ${action}${source:+ from ${source}})"
    return
  fi
  CF_API_TOKEN="$CF_API_TOKEN" python3 -c '
import json, os, sys, time, urllib.request
domain, ray, action, source = sys.argv[1:5]
tok = os.environ["CF_API_TOKEN"]
def call(url, body=None):
    req = urllib.request.Request(url, data=json.dumps(body).encode() if body else None,
                                 headers={"Authorization": "Bearer " + tok,
                                          "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)
try:
    zone = call("https://api.cloudflare.com/client/v4/zones?name=" + domain)["result"][0]["id"]
except Exception as e:
    print("UNVERIFIED|zone lookup failed (%s); look up Ray ID %s by hand" % (e, ray)); sys.exit()
since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 3600))
query = ("query($zone: string, $ray: string, $since: Time) { viewer { zones(filter: {zoneTag: $zone}) {"
         " firewallEventsAdaptive(limit: 10, filter: {rayName: $ray, datetime_geq: $since}) {"
         " action source ruleId rayName clientRequestPath datetime } } } }")
events = []
for _ in range(12):  # events can take a minute or two to appear
    try:
        data = call("https://api.cloudflare.com/client/v4/graphql",
                    {"query": query, "variables": {"zone": zone, "ray": ray, "since": since}})
    except Exception as e:
        print("UNVERIFIED|GraphQL query failed (%s); look up Ray ID %s by hand" % (e, ray)); sys.exit()
    if data.get("errors"):
        print("UNVERIFIED|GraphQL error: %s" % data["errors"][0].get("message")); sys.exit()
    events = data["data"]["viewer"]["zones"][0]["firewallEventsAdaptive"]
    if events:
        break
    time.sleep(10)
if not events:
    print("UNVERIFIED|Ray ID %s has no security event after two minutes. Security Events can be "
          "sampled, so this is missing evidence, not proof of failure; check the Ray ID by hand "
          "and confirm the 403 is not origin generated" % ray); sys.exit()
match = [e for e in events if e["action"] == action and (not source or e["source"] == source)]
if match:
    e = match[0]
    print("PASS|Ray %s: %s by %s rule %s" % (ray, e["action"], e["source"], e["ruleId"]))
else:
    got = ", ".join("%s/%s" % (e["action"], e["source"]) for e in events)
    print("FAIL|Ray %s: expected %s%s, got %s" % (ray, action, "/" + source if source else "", got))
' "$DOMAIN" "$ray" "$action" "$source"
}

# Classify a direct to origin probe from OUTSIDE. In both modes the firewall must
# make the web listener unreachable, so only "connection refused" or "timed out"
# proves anything. Any TCP connection that completes is a FAIL, even if TLS or the
# application then rejects it, because the listener itself is exposed. Any other
# curl error (bad URL, DNS failure, local problem) is UNVERIFIED, never PASS.
#   curl exit codes: 6 resolve, 7 refused, 28 timeout, 35 TLS handshake,
#                    52 empty reply, 56 receive failure
classify_origin() {
  if grep -qiE 'proxy|CONNECT tunnel' "$TMP/err" 2>/dev/null; then
    echo "UNVERIFIED|a proxy was involved (${ERR}); rerun from a direct connection"; return
  fi
  case "$CURL_RC" in
    7)  echo "PASS|connection refused: no reachable web listener" ;;
    28) echo "PASS|timed out: no reachable web listener" ;;
    6)  echo "UNVERIFIED|name did not resolve (${ERR}); fix the hostname and rerun" ;;
    35|52|56)
        echo "FAIL|a listener accepted the TCP connection (curl rc=${CURL_RC}: ${ERR}); the firewall is not closing it" ;;
    0)
        if [ "$BODY_HAS_APP" = "1" ]; then
          echo "FAIL|origin served the application directly (HTTP ${CODE})"
        else
          echo "FAIL|origin answered HTTP ${CODE} directly; the listener is reachable"
        fi ;;
    *)  echo "UNVERIFIED|probe error, no evidence either way (curl rc=${CURL_RC}: ${ERR})" ;;
  esac
}

# Client certificate enforcement, tested from a path that bypasses the firewall.
# PASS only on a handshake rejection or nginx's explicit certificate error page.
classify_cert() {
  case "$CURL_RC" in
    35|56) echo "PASS|TLS handshake rejected (curl rc=${CURL_RC})" ;;
    0)
      if [ "$BODY_HAS_APP" = "1" ] || [[ "$CODE" =~ ^[23] ]]; then
        echo "FAIL|served HTTP ${CODE} without a trusted client certificate"
      elif [ "$CODE" = "400" ] && grep -qiE 'ssl certificate|client certificate' "$TMP/b"; then
        echo "PASS|rejected with HTTP 400 certificate error"
      else
        echo "UNVERIFIED|HTTP ${CODE} without a certificate error; inspect by hand"
      fi ;;
    *) echo "UNVERIFIED|probe error (curl rc=${CURL_RC}: ${ERR})" ;;
  esac
}

probe_origin() { # name, ip, extra host header
  local name="$1" ip="$2" host="${3:-$DOMAIN}"
  local res
  fetch "https://${host}/" -k --resolve "${host}:443:${ip}"
  res="$(classify_origin)"
  record "${res%%|*}" "$name (HTTPS)" "listener unreachable" "${res#*|}"
  fetch "http://${host}/" --resolve "${host}:80:${ip}"
  res="$(classify_origin)"
  record "${res%%|*}" "$name (HTTP)" "listener unreachable" "${res#*|}"
}

echo "Acceptance tests for ${DOMAIN} (profile ${PROFILE}, mode ${MODE}), marker ${MARKER}"
echo

# 1. DNS points at Cloudflare only
CF_RANGES="$(curl -sS --max-time 10 https://api.cloudflare.com/client/v4/ips)"
for name in "$DOMAIN" "www.$DOMAIN"; do
  addrs="$(dig +short A "$name"; dig +short AAAA "$name")"
  addrs="$(printf '%s\n' "$addrs" | grep -E '^[0-9a-fA-F:.]+$' || true)"
  if [ -z "$addrs" ]; then
    record SKIP "DNS ${name}" "resolves only to Cloudflare" "no A/AAAA records"
    continue
  fi
  verdict="$(printf '%s' "$CF_RANGES" | python3 -c '
import ipaddress, json, sys
data = json.load(sys.stdin)["result"]
nets = [ipaddress.ip_network(c) for c in data["ipv4_cidrs"] + data["ipv6_cidrs"]]
bad = [a for a in sys.argv[1].split() if not any(ipaddress.ip_address(a) in n for n in nets)]
print("FAIL|non Cloudflare: " + " ".join(bad) if bad else "PASS|all addresses in Cloudflare ranges")
' "$addrs")"
  record "${verdict%%|*}" "DNS ${name}" "resolves only to Cloudflare" "${verdict#*|}: $(echo $addrs)"
done

# 2. Direct origin access
if [ -n "$ORIGIN_IPV4" ]; then
  probe_origin "Origin IPv4 ${ORIGIN_IPV4}" "$ORIGIN_IPV4"
  probe_origin "Origin IPv4 unexpected Host" "$ORIGIN_IPV4" "unknown-${STAMP}.invalid"
else
  record UNVERIFIED "Origin IPv4" "listener unreachable" "ORIGIN_IPV4 not set; the most important test did not run"
fi
if [ -n "$ORIGIN_IPV6" ]; then
  probe_origin "Origin IPv6 ${ORIGIN_IPV6}" "[${ORIGIN_IPV6}]"
else
  record SKIP "Origin IPv6" "direct access rejected" "ORIGIN_IPV6 not set"
fi

# 3. Provider hostnames
for alt in $ALT_HOSTS; do
  fetch "https://${alt}/" -k
  res="$(classify_origin)"
  record "${res%%|*}" "Alternative hostname ${alt}" "application not served" "${res#*|}"
  fetch "http://${alt}/"
  res="$(classify_origin)"
  record "${res%%|*}" "Alternative hostname ${alt} (HTTP)" "application not served" "${res#*|}"
done
[ -z "$ALT_HOSTS" ] && record SKIP "Alternative origin hostname" "application not served" "ALT_HOSTS not set"

# 4. Another Cloudflare account pointed at the origin
if [ -n "$FOREIGN_HOST" ]; then
  fetch "https://${FOREIGN_HOST}/"
  if [ "$BODY_HAS_APP" = "1" ] || [[ "$CODE" =~ ^(200|301|302)$ ]]; then
    record FAIL "External Cloudflare zone" "origin refuses it (52x)" "HTTP ${CODE}, the site is reachable through another account"
  else
    record PASS "External Cloudflare zone" "origin refuses it (52x)" "HTTP ${CODE} via ${FOREIGN_HOST}"
  fi
else
  record UNVERIFIED "External Cloudflare zone" "origin refuses it (52x)" \
    "Create a free zone in a separate Cloudflare account, proxy an A record to the origin IP, set its SSL mode to Full and enable global AOP there, then set FOREIGN_HOST and rerun"
fi

# 5 and 6. Client certificate checks at the origin
if [ "$MODE" = "tunnel" ]; then
  record SKIP "Client certificate tests" "not applicable" "tunnel mode: the listener tests above must prove there is no public listener"
elif [ -z "$CERT_TEST_TARGET" ]; then
  record UNVERIFIED "Client certificate enforcement" "missing or untrusted certificate rejected" \
    "the firewall stops outside probes reaching TLS, so enforcement was not exercised; rerun on the origin with CERT_TEST_TARGET=127.0.0.1"
else
  fetch "https://${DOMAIN}/" -k --resolve "${DOMAIN}:443:${CERT_TEST_TARGET}"
  res="$(classify_cert)"
  record "${res%%|*}" "Missing client certificate" "rejected" "${res#*|}"
  openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=untrusted-test" \
    -keyout "$TMP/k.pem" -out "$TMP/c.pem" >/dev/null 2>&1
  fetch "https://${DOMAIN}/" -k --resolve "${DOMAIN}:443:${CERT_TEST_TARGET}" \
    --cert "$TMP/c.pem" --key "$TMP/k.pem"
  res="$(classify_cert)"
  record "${res%%|*}" "Untrusted client certificate" "rejected" "${res#*|}"
fi

# 7. WAF enforcement with a benign request (the marker makes it easy to find in logs)
fetch "https://${DOMAIN}/.env?${MARKER}"
if [ "$CODE" = "403" ]; then
  res="$(verify_ray "$(hdr cf-ray)" block firewallCustom)"
  record "${res%%|*}" "WAF enforcement" "403 from a Cloudflare custom rule" "${res#*|}"
else
  record FAIL "WAF enforcement" "403 from a Cloudflare custom rule" "HTTP ${CODE}, server $(hdr server)"
fi

# 8. Forwarded headers cannot change a decision. Uses the login path when there
# is one (a challenge is easy to compare), otherwise the blocked .env request.
probe_path="${LOGIN_PATH:-/.env}"
fetch "https://${DOMAIN}${probe_path}"
base_code="$CODE"; base_mit="$(hdr cf-mitigated)"
fetch "https://${DOMAIN}${probe_path}" \
  -H "X-Forwarded-For: 127.0.0.1" -H "CF-Connecting-IP: 127.0.0.1" \
  -H "True-Client-IP: 127.0.0.1" -H "X-Real-IP: 127.0.0.1" \
  -H "X-Forwarded-Host: localhost" -H "Forwarded: for=127.0.0.1;host=localhost" \
  -H "User-Agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
if [ "$CODE" = "$base_code" ] && [ "$(hdr cf-mitigated)" = "$base_mit" ]; then
  record PASS "Forwarded headers (edge)" "same decision with spoofed headers" "${probe_path}: HTTP ${CODE}, cf-mitigated '${base_mit}' both times"
else
  record FAIL "Forwarded headers (edge)" "same decision with spoofed headers" "${probe_path} without: ${base_code}/${base_mit}; with: ${CODE}/$(hdr cf-mitigated)"
fi
record MANUAL "Forwarded headers (origin)" "origin trusts them only from the tunnel or Cloudflare" \
  "Review the web server (nginx real_ip, Apache mod_remoteip), the application and any security plugins"

# 9. Sensitive files: generic set, plus the profile's own
SENSITIVE="/.env /.git/config /.git/HEAD /static/.git/config /.aws/credentials /backup.sql /backup.zip /db.sql.gz /site.tar.gz"
[ "$PROFILE" = "wordpress" ] && SENSITIVE+=" /wp-config.php /wp-config.php.bak /wp-content/debug.log /wp-content/uploads/test.php /wp-content/plugins/x/.git/config"
SENSITIVE+=" ${EXTRA_SENSITIVE}"
bad=""
for path in $SENSITIVE; do
  fetch "https://${DOMAIN}${path}"
  [[ "$CODE" =~ ^(403|404|410)$ ]] || bad+="${path}=${CODE} "
done
if [ -z "$bad" ]; then
  record PASS "Sensitive files" "403 or 404" "all denied: ${SENSITIVE}"
else
  record FAIL "Sensitive files" "403 or 404" "$bad"
fi

# 10. XML-RPC (wordpress profile)
if [ "$PROFILE" = "wordpress" ]; then
  if [ "$ALLOW_XMLRPC" = "1" ]; then
    record SKIP "XML-RPC" "blocked" "ALLOW_XMLRPC=1"
  else
    fetch "https://${DOMAIN}/xmlrpc.php" -X POST -H "Content-Type: text/xml" \
      --data '<?xml version="1.0"?><methodCall><methodName>system.listMethods</methodName></methodCall>'
    if [ "$CODE" = "403" ]; then
      res="$(verify_ray "$(hdr cf-ray)" block firewallCustom)"
      record "${res%%|*}" "XML-RPC" "blocked by Cloudflare" "${res#*|}"
    else
      record FAIL "XML-RPC" "blocked by Cloudflare" "HTTP ${CODE}"
    fi
  fi
fi

# 11. Login challenge (rate limiting sits behind the challenge, so verify it with cf_audit.py)
if [ -n "$LOGIN_PATH" ]; then
  fetch "https://${DOMAIN}${LOGIN_PATH}"
  if [ "$(hdr cf-mitigated)" = "challenge" ]; then
    res="$(verify_ray "$(hdr cf-ray)" managed_challenge firewallCustom)"
    record "${res%%|*}" "Login ${LOGIN_PATH}" "Managed Challenge from a custom rule" "${res#*|} (rate limit rule: see audit)"
  elif printf '%s' "$(hdr location)" | grep -q cloudflareaccess.com; then
    record PASS "Login ${LOGIN_PATH}" "Access or challenge" "redirected to Cloudflare Access"
  else
    record FAIL "Login ${LOGIN_PATH}" "Managed Challenge or Access" "HTTP ${CODE}, no challenge"
  fi
else
  record SKIP "Login protection" "challenge or Access" "LOGIN_PATH not set"
fi

# 12. Administration
if [ -n "$ADMIN_PATH" ]; then
  fetch "https://${DOMAIN}${ADMIN_PATH}"
  loc="$(hdr location)"
  if printf '%s' "$loc" | grep -q cloudflareaccess.com; then
    record PASS "Administration ${ADMIN_PATH}" "Cloudflare Access" "redirect to Access"
  elif [[ "$CODE" =~ ^(30[1-8])$ ]] && [ -n "$LOGIN_PATH" ] && printf '%s' "$loc" | grep -q "$LOGIN_PATH"; then
    record WARN "Administration ${ADMIN_PATH}" "Cloudflare Access" "application login only (no Access in front)"
  elif [ "$(hdr cf-mitigated)" = "challenge" ] || [[ "$CODE" =~ ^(401|403)$ ]]; then
    record PASS "Administration ${ADMIN_PATH}" "authentication enforced" "HTTP ${CODE}"
  else
    record FAIL "Administration ${ADMIN_PATH}" "authentication enforced" "HTTP ${CODE}"
  fi
else
  record SKIP "Administration" "Access or authentication" "ADMIN_PATH not set"
fi

# 13. Authenticated content is never served from cache
bad=""
fetch "https://${DOMAIN}/" -H "Cookie: ${SESSION_COOKIE}${STAMP}=x"
[ "$(hdr cf-cache-status)" = "HIT" ] && bad+="/ with session cookie=HIT "
for path in $PRIVATE_PATHS; do
  fetch "https://${DOMAIN}${path}"
  [ "$(hdr cf-cache-status)" = "HIT" ] && bad+="${path}=HIT "
done
if [ -z "$bad" ]; then
  record PASS "Authenticated caching" "never HIT" "no cached private responses observed (cookie ${SESSION_COOKIE}*, ${PRIVATE_PATHS:-no private paths})"
else
  record FAIL "Authenticated caching" "never HIT" "$bad"
fi

# 14. Normal traffic still works, plus the profile's public endpoints
fetch "https://${DOMAIN}/"
if [ "$CODE" = "200" ] && [ -n "$(hdr cf-ray)" ]; then
  record PASS "Normal website traffic" "200 via Cloudflare" "HTTP 200, cache $(hdr cf-cache-status)"
else
  record FAIL "Normal website traffic" "200 via Cloudflare" "HTTP ${CODE}"
fi
if [ "$PROFILE" = "wordpress" ]; then
  fetch "https://${DOMAIN}/wp-json/"
  [ "$CODE" = "200" ] && record PASS "WordPress REST API" "200" "wp-json reachable" \
                      || record WARN "WordPress REST API" "200" "HTTP ${CODE} (fine if intentionally restricted)"
  fetch "https://${DOMAIN}/wp-admin/admin-ajax.php" -X POST --data "action=${MARKER}"
  if [[ "$CODE" =~ ^(200|400)$ ]] && [ -z "$(hdr cf-mitigated)" ]; then
    record PASS "WordPress public AJAX" "reaches WordPress" "HTTP ${CODE} from WordPress"
  else
    record WARN "WordPress public AJAX" "reaches WordPress" "HTTP ${CODE} cf-mitigated '$(hdr cf-mitigated)'"
  fi
fi

# 15. Search engines
fetch "https://${DOMAIN}/robots.txt"; robots="$CODE"
sm="n/a"
for path in $SITEMAP_PATHS; do
  fetch "https://${DOMAIN}${path}"; sm="$CODE"
  [ "$sm" = "200" ] && break
done
if [ "$robots" = "200" ] && [[ "$sm" =~ ^(200|n/a)$ ]]; then
  record PASS "Search engine access" "robots (and sitemap) 200" "robots ${robots}, sitemap ${sm}"
else
  record FAIL "Search engine access" "robots (and sitemap) 200" "robots ${robots}, sitemap ${sm}"
fi

# 16. TLS
if openssl s_client -connect "${DOMAIN}:443" -servername "$DOMAIN" -tls1_1 \
     -cipher 'DEFAULT:@SECLEVEL=0' </dev/null >/dev/null 2>&1; then
  record FAIL "Minimum TLS 1.2" "TLS 1.1 refused" "TLS 1.1 handshake succeeded"
else
  record PASS "Minimum TLS 1.2" "TLS 1.1 refused" "TLS 1.1 handshake failed"
fi
if openssl s_client -connect "${DOMAIN}:443" -servername "$DOMAIN" -tls1_3 </dev/null >/dev/null 2>&1; then
  record PASS "TLS 1.3" "available" "handshake ok"
else
  record FAIL "TLS 1.3" "available" "handshake failed"
fi
fetch "http://${DOMAIN}/"
if [[ "$CODE" =~ ^30[178]$ ]] && printf '%s' "$(hdr location)" | grep -q '^https://'; then
  record PASS "Always Use HTTPS" "redirect to https" "HTTP ${CODE}"
else
  record FAIL "Always Use HTTPS" "redirect to https" "HTTP ${CODE}"
fi
fetch "https://${DOMAIN}/"
hsts="$(hdr strict-transport-security)"
[ -n "$hsts" ] && record PASS "HSTS" "header present" "$hsts" \
               || record WARN "HSTS" "header present" "not set yet"

# API hosts: documentation and management endpoints must not answer
API_PATHS="/swagger-ui/index.html /swagger-ui.html /v3/api-docs /v2/api-docs /openapi.json \
/actuator /actuator/env /actuator/heapdump /actuator/mappings /actuator/configprops /management/env"
for api in $API_HOSTS; do
  bad=""
  for path in $API_PATHS; do
    fetch "https://${api}${path}"
    if [[ "$CODE" =~ ^2 ]]; then bad+="${path}=${CODE} "; fi
  done
  fetch "https://${api}/"
  grep -qi 'swagger' "$TMP/b" && bad+="/ serves Swagger UI "
  if [ -z "$bad" ]; then
    record PASS "API surface ${api}" "docs and management closed" "none of ${API_PATHS// /, } answered 2xx"
  else
    record FAIL "API surface ${api}" "docs and management closed" "$bad"
  fi
  # A spoofed client address must not change the answer.
  fetch "https://${api}/actuator/env" -H "X-Forwarded-For: 127.0.0.1" -H "X-Real-IP: 127.0.0.1"
  if [[ "$CODE" =~ ^2 ]]; then
    record FAIL "Forwarded headers ${api}" "no change with spoofed address" "actuator/env answered ${CODE}"
  else
    record PASS "Forwarded headers ${api}" "no change with spoofed address" "HTTP ${CODE}"
  fi
done
if [ -n "$API_ORIGIN" ]; then
  fetch "https://${API_ORIGIN}/" -k
  res="$(classify_origin)"
  record "${res%%|*}" "API origin ${API_ORIGIN} direct" "refused without your Cloudflare zone" "${res#*|}"
  fetch "https://${API_ORIGIN}/actuator/health" -k
  res="$(classify_origin)"
  record "${res%%|*}" "API origin management direct" "refused" "${res#*|}"
fi

# 17 to 20. Things a script cannot prove on its own
record MANUAL "Core workflows" "sign in and the main write paths work" "For WordPress: log in, edit a draft, publish, check scheduled posts. For an API: run the client test suite"
record MANUAL "Integrations" "approved integrations work" "Webhooks, uptime monitors, backups, partner callbacks (Jetpack on WordPress)"
record MANUAL "Security logging" "test events visible" "Search Security Events for marker ${MARKER} (the /.env request above)"
record MANUAL "Rollback" "documented and rehearsed" "Run cf_harden.py --rollback <backup> in dry run and confirm the plan"

{
  echo "# Acceptance tests: ${DOMAIN}"
  echo
  echo "Run ${STAMP} UTC from $(hostname). Profile: ${PROFILE}. Mode: ${MODE}. Log marker: \`${MARKER}\`."
  echo
  if [ "$FAIL" -gt 0 ]; then
    echo "**Automated sign-off: FAILED** (${FAIL} failed)."
  elif [ "$UNVER" -gt 0 ]; then
    echo "**Automated sign-off: WITHHELD** (${UNVER} unverified: no evidence either way)."
  else
    echo "**Automated sign-off: GRANTED.** MANUAL items below still need a human."
  fi
  echo
  echo "Passed ${PASS}, failed ${FAIL}, unverified ${UNVER}, other ${OTHER} (skip, warn, manual) out of ${N}."
  echo
  echo "| # | Test | Expected | Result | Evidence |"
  echo "|---|---|---|---|---|"
  printf '%s' "$ROWS"
} > "$REPORT"

echo
echo "Passed ${PASS}, failed ${FAIL}, unverified ${UNVER}, other ${OTHER}. Report: ${REPORT}"
if [ "$FAIL" -gt 0 ]; then exit 1; fi
if [ "$UNVER" -gt 0 ]; then echo "Sign-off withheld: unverified checks remain."; exit 2; fi
exit 0
EOF
chmod +x cf_origin_tests.sh

Run it with your own values:

cat > run_tests.sh << 'EOF'
#!/usr/bin/env bash
# run_tests.sh: example invocation of the acceptance tests. Replace the values.
set -euo pipefail
export DOMAIN="example.com"
export PROFILE="generic"                   # or wordpress
export LOGIN_PATH=""                       # e.g. /login (wordpress default: /wp-login.php)
export ADMIN_PATH=""                       # e.g. /admin/ (wordpress default: /wp-admin/)
export MODE="tunnel"                       # or aop
export CERT_TEST_TARGET=""                 # aop only: 127.0.0.1 when run on the origin
export ORIGIN_IPV4="203.0.113.10"          # the server's public IPv4
export ORIGIN_IPV6=""                      # its IPv6, if it has one
export ALT_HOSTS="ec2-203-0-113-10.compute-1.amazonaws.com"
export FOREIGN_HOST=""                     # proxied hostname in a different Cloudflare account
export API_HOSTS=""                        # API hostnames to check for exposed docs and actuator
export API_ORIGIN=""                       # the API load balancer hostname, to test directly
./cf_origin_tests.sh
EOF
chmod +x run_tests.sh

A few items are marked MANUAL because a script cannot honestly prove them: that the main workflows still work (publishing and editing on WordPress, the client test suite against an API), that integrations such as webhooks, backups, uptime monitors and partner callbacks still work, that the marked test request appears in your logs, and that the rollback plan works. Do them by hand and record the result next to the generated table.

12. Making it continuous

A configuration that was clean on the day of the audit drifts. Someone adds a Skip rule to fix a broken webhook, a DNS record goes grey during a migration, a managed ruleset gets switched off to chase a false positive and never comes back. The audit script already compares against a saved baseline, and raises a critical finding for a new Skip rule or disabled origin authentication, and high findings for new unproxied records, new IP allow rules, changed origin rules, Worker routes, configuration rules, logging and settings. All that is left is to run it every day with the read only token and keep the history. A GitHub Actions workflow is the simplest way to do that, because the baseline lives in version control and every run’s report is kept as an artifact:

mkdir -p .github/workflows
cat > .github/workflows/cloudflare-audit.yml << 'EOF'
# .github/workflows/cloudflare-audit.yml
# Daily read only audit. Store the read only token as the CF_AUDIT_TOKEN secret,
# and commit the toolkit (including smoke_test.sh) and an approved baseline.json.
name: cloudflare-audit
on:
  schedule:
    - cron: "17 4 * * *"      # daily, 04:17 UTC
  workflow_dispatch: {}
permissions:
  contents: read
jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Smoke test the toolkit
        run: ./smoke_test.sh
      - name: Run audit against the approved baseline
        env:
          CF_API_TOKEN: ${{ secrets.CF_AUDIT_TOKEN }}
        run: |
          python3 cf_audit.py --zone example.com --out-dir out --baseline baseline.json
      - name: Keep the report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: cloudflare-audit-${{ github.run_id }}
          path: out/
          retention-days: 400
# A failed run (exit 1 or 2) triggers GitHub's failure notification email.
EOF

Pair it with Cloudflare’s own notification policies for security events and certificate expiry, and if your plan includes Logpush, ship firewall events to storage you control. When the daily audit fails, either the change was unapproved and you revert it, or it was approved and you refresh the baseline in a reviewed commit, which leaves an audit trail of every exception you ever accepted.

13. What the scripts cannot tell you

A green report proves less than it appears to. The audit reads configuration through the API, so it cannot see the code inside Workers or Snippets, how your application or its plugins decide on a visitor’s IP, or whether your origin’s web server trusts forwarded headers; those need a human review. Its heuristics for spoofable conditions and risky cache rules will occasionally flag something that is fine, which is why each finding carries its evidence. It cannot see historical DNS, so check a passive DNS service for addresses your site used to have. And the acceptance tests only prove what is reachable from where you ran them, so run them from outside your hosting provider’s network, ideally from two places.

Do not report a control as implemented until a test has shown it working. Cloudflare being enabled is a starting point. Protection means an origin that refuses everything except an authenticated path from your own account, an edge with no blanket exemptions, and a daily job that alerts you the moment either stops being true.

Leave a comment

Your email address will not be published. Your first comment is held for approval.