DEV Community

appierun
appierun

Posted on

Audit HTTP Security Headers Across a Sitemap with Python (Standard Library Only): Missing HSTS, CSP and Cookie Flags

Most online header checkers test one URL, usually the homepage. That is where the theme or the CDN sets everything correctly. The gaps sit elsewhere: a blog that still runs on an older install under /blog, a booking page from a plugin that sets its own cookie, a landing page served by a different app. If you look after websites for clients (a small agency with a dozen local business sites, say), you want one run per site that checks every page the client cares about and tells you where the headers differ.

This post builds that check in Python using only the standard library (urllib, ssl, xml.etree, csv, concurrent.futures). You give it a sitemap. It fetches every URL, probes the plain-HTTP version of each one, and flags:

  • pages where plain HTTP serves the page instead of redirecting to HTTPS
  • missing or short-lived Strict-Transport-Security
  • missing Content-Security-Policy, or a policy that allows 'unsafe-inline' scripts
  • no protection against framing (no frame-ancestors and no usable X-Frame-Options)
  • missing X-Content-Type-Options: nosniff, a missing or unsafe-url Referrer-Policy, and a missing Permissions-Policy
  • the legacy X-XSS-Protection: 1 filter switched on
  • headers that announce your stack and version (Server: Apache/2.4.41, X-Powered-By: PHP/7.4.33)
  • cookies without Secure, HttpOnly or SameSite
  • security headers that are set on some pages but not others

It writes a CSV with one row per issue and prints a summary. Every output below comes from a real run against a small fictional test site on localhost, which you can rebuild from the code in this post.

Sources opened on 24 Nov 2026: MDN's reference pages for Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, X-XSS-Protection and Set-Cookie, and the OWASP Secure Headers Project with its published lists of headers to add and headers to remove (both showing "last_update_utc": "2026-11-23"). The test site ("Hollis Street Dental") is fictional and runs on localhost. Appie free-tool descriptions are as of 24 Nov 2026, checked on the tool's page that day.

Disclosure: Appie.run publishes this article. One free tool mentioned near the end is ours. The script does not depend on it.

What this is (and is not)

Security headers are instructions from the server to the browser: only use HTTPS for this host, do not let other sites put this page in a frame, do not guess file types, send less referrer data. They are cheap to set and easy to lose when a site has more than one moving part.

This script checks whether those headers are present and sensibly configured on each page. It is not a vulnerability scanner, it does not test your forms or logins, and a clean report does not mean a site is secure. Treat it as a hygiene check you can run on every client site each month.

What the references say

HSTS. MDN: the header "informs browsers that the host should only be accessed using HTTPS, and that any future attempts to access it using HTTP should automatically be upgraded to HTTPS." Two details matter for an audit. First, "Browsers ignore the header if sent over HTTP," so it only counts on HTTPS responses. Second, for preloading, "the max-age directive must be at least 31536000 (1 year)." The script uses one year as its threshold. OWASP's recommended value is max-age=63072000; includeSubDomains (two years).

Framing. MDN on X-Frame-Options: if it is not sent and the site has no other way to restrict embedding, "such as the frame-ancestors CSP directive," then "the browser will allow other sites to embed this document." DENY and SAMEORIGIN are the valid values. ALLOW-FROM "is an obsolete directive. Modern browsers that encounter response headers with this directive will ignore the header completely." So the script treats ALLOW-FROM as no protection.

nosniff. MDN on X-Content-Type-Options: "Site security testers usually expect this header to be set." With nosniff, the browser blocks scripts and stylesheets whose MIME type does not match, and uses the declared Content-Type for everything else.

Referrer-Policy. MDN describes unsafe-url as sending the origin, path and query string for every request, regardless of security. That can leak URLs with tokens or search terms to third parties, including over plain HTTP. OWASP's recommended value is no-referrer; many sites use strict-origin-when-cross-origin.

X-XSS-Protection. MDN marks it non-standard and warns that "in some cases, X-XSS-Protection can create XSS vulnerabilities in otherwise safe websites." It recommends using Content-Security-Policy instead. The script flags any value that turns the filter on (1, 1; mode=block).

Headers to remove. OWASP keeps a list of response headers that only describe your stack, including Server, X-Powered-By, X-AspNet-Version and X-Generator. The script checks a short subset and only flags Server when it contains a version number.

Cookies. MDN's Set-Cookie reference documents the Secure, HttpOnly and SameSite attributes. The script flags cookies that lack any of them, with one caveat covered later: a cookie that your own JavaScript needs to read cannot be HttpOnly.

How the audit works

  1. Read the sitemap (and any child sitemaps in a sitemap index).
  2. Fetch each URL over HTTPS, following redirects, and keep the response headers.
  3. Request the http:// version of the same URL without following redirects. A 301/308 to an https:// URL is good; a 200 means plain HTTP serves the page.
  4. Run each page's headers through the checks and give every finding a severity (high, medium, low, info).
  5. Count which security headers appear on which pages, and list headers that are present on some pages but missing on others. That pattern usually means a second app, theme or server is serving part of the site.
  6. Write a CSV sorted by severity and print a summary.

The script

Save this as security_headers_audit.py. It needs Python 3.9 or newer and nothing else.

#!/usr/bin/env python3
"""Audit HTTP security headers for every URL in a sitemap.

Standard library only. Usage:
    python3 security_headers_audit.py https://example.com/sitemap.xml --csv headers_report.csv
"""
import argparse, csv, re, ssl, sys, urllib.error, urllib.request
import xml.etree.ElementTree as ET
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlsplit, urlunsplit

UA = "security-headers-audit/1.0 (+https://dev.to/appierun_66)"
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
ONE_YEAR = 31536000
# Headers that only describe your stack. Trimmed from OWASP's "headers to remove" list.
LEAKY = ["server", "x-powered-by", "x-aspnet-version", "x-aspnetmvc-version", "x-generator", "x-cms"]
SEVERITY_ORDER = {"high": 0, "medium": 1, "low": 2, "info": 3}


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


def make_opener(ctx, follow=True):
    handlers = [urllib.request.HTTPSHandler(context=ctx)]
    if not follow:
        handlers.append(NoRedirect())
    return urllib.request.build_opener(*handlers)


def fetch(opener, url, timeout=15):
    """Return (status, final_url, headers). headers is a list of (name, value) pairs."""
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    try:
        with opener.open(req, timeout=timeout) as r:
            return r.status, r.geturl(), r.headers.items()
    except urllib.error.HTTPError as e:
        return e.code, url, e.headers.items() if e.headers else []
    except Exception as e:
        return None, url, [("x-audit-error", str(e)[:120])]


def sitemap_urls(opener, url, seen=None):
    seen = seen or set()
    if url in seen:
        return []
    seen.add(url)
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with opener.open(req, timeout=20) as r:
        root = ET.fromstring(r.read())
    if root.tag == NS + "sitemapindex":
        out = []
        for loc in root.iter(NS + "loc"):
            out += sitemap_urls(opener, loc.text.strip(), seen)
        return out
    return [loc.text.strip() for loc in root.iter(NS + "loc")]


def http_variant(url, http_port=None):
    parts = urlsplit(url)
    host = parts.hostname
    netloc = f"{host}:{http_port}" if http_port else host
    return urlunsplit(("http", netloc, parts.path or "/", parts.query, ""))


def check_page(url, headers, http_status, http_location):
    """Return a list of (issue, severity, detail)."""
    issues = []
    h = defaultdict(list)
    for k, v in headers:
        h[k.lower()].append(v.strip())
    first = lambda name: h[name][0] if h.get(name) else None
    https = url.startswith("https://")

    # 1. HTTPS and the plain-HTTP door
    if not https:
        issues.append(("not_https", "high", "page URL in sitemap is http://"))
    elif http_status is not None:
        if http_status in (301, 302, 307, 308):
            if not (http_location or "").startswith("https://"):
                issues.append(("http_redirects_elsewhere", "medium", f"http -> {http_location}"))
        elif http_status == 200:
            issues.append(("http_no_redirect", "high", "plain HTTP serves the page with 200"))

    # 2. HSTS
    hsts = first("strict-transport-security")
    if https:
        if not hsts:
            issues.append(("hsts_missing", "high", ""))
        else:
            m = re.search(r"max-age\s*=\s*\"?(\d+)", hsts, re.I)
            age = int(m.group(1)) if m else 0
            if age < ONE_YEAR:
                issues.append(("hsts_short_max_age", "medium", f"max-age={age}"))

    # 3. CSP
    csp = first("content-security-policy")
    if not csp:
        ro = " (only Content-Security-Policy-Report-Only is set)" if first("content-security-policy-report-only") else ""
        issues.append(("csp_missing", "medium", ro.strip()))
        directives = {}
    else:
        directives = {}
        for part in csp.split(";"):
            bits = part.strip().split()
            if bits:
                directives[bits[0].lower()] = [b.lower() for b in bits[1:]]
        scripts = directives.get("script-src", directives.get("default-src", []))
        has_nonce_or_hash = any(s.startswith(("'nonce-", "'sha256-", "'sha384-", "'sha512-")) for s in scripts)
        if "'unsafe-inline'" in scripts and not has_nonce_or_hash:
            issues.append(("csp_unsafe_inline_scripts", "medium", "script-src allows 'unsafe-inline'"))
        if "'unsafe-eval'" in scripts:
            issues.append(("csp_unsafe_eval", "low", "script-src allows 'unsafe-eval'"))

    # 4. Framing (clickjacking)
    xfo = (first("x-frame-options") or "").upper()
    has_fa = "frame-ancestors" in directives
    if xfo.startswith("ALLOW-FROM"):
        issues.append(("xfo_allow_from_obsolete", "low", "browsers ignore ALLOW-FROM"))
    if not has_fa and xfo not in ("DENY", "SAMEORIGIN"):
        issues.append(("framing_unprotected", "medium", "no frame-ancestors and no usable X-Frame-Options"))

    # 5. Smaller headers
    if (first("x-content-type-options") or "").lower() != "nosniff":
        issues.append(("nosniff_missing", "low", ""))
    rp = (first("referrer-policy") or "").lower()
    if not rp:
        issues.append(("referrer_policy_missing", "low", "browser default applies"))
    elif "unsafe-url" in rp:
        issues.append(("referrer_policy_unsafe_url", "medium", "full URL sent to every site, including over http"))
    if not first("permissions-policy"):
        issues.append(("permissions_policy_missing", "info", ""))
    xxp = first("x-xss-protection")
    if xxp and xxp.strip().startswith("1"):
        issues.append(("x_xss_protection_enabled", "low", f"'{xxp}' (MDN: use CSP; send 0 or nothing)"))

    # 6. Headers that describe your stack
    for name in LEAKY:
        for v in h.get(name, []):
            if name != "server" or re.search(r"\d", v):
                issues.append(("stack_header", "low", f"{name}: {v}"))

    # 7. Cookies
    for c in h.get("set-cookie", []):
        cname = c.split("=", 1)[0]
        attrs = c.lower()
        missing = [a for a, key in (("Secure", "; secure"), ("HttpOnly", "; httponly"), ("SameSite", "samesite="))
                   if key not in attrs]
        if missing:
            issues.append(("cookie_missing_flags", "medium", f"{cname}: missing {', '.join(missing)}"))

    if first("x-audit-error"):
        issues.append(("fetch_error", "high", first("x-audit-error")))
    return issues


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("sitemap")
    ap.add_argument("--csv", default="headers_report.csv")
    ap.add_argument("--cafile", help="extra CA bundle, e.g. for a self-signed test server")
    ap.add_argument("--http-port", type=int, help="port for the plain-HTTP probe (default 80)")
    ap.add_argument("--workers", type=int, default=4)
    args = ap.parse_args()

    ctx = ssl.create_default_context(cafile=args.cafile) if args.cafile else ssl.create_default_context()
    follow, nofollow = make_opener(ctx), make_opener(ctx, follow=False)
    urls = sitemap_urls(follow, args.sitemap)

    def audit(url):
        status, final, headers = fetch(follow, url)
        http_status, http_loc = None, None
        if url.startswith("https://"):
            s, _, hh = fetch(nofollow, http_variant(url, args.http_port))
            http_status = s
            http_loc = dict((k.lower(), v) for k, v in hh).get("location")
        return url, status, headers, check_page(final, headers, http_status, http_loc)

    with ThreadPoolExecutor(args.workers) as pool:
        results = list(pool.map(audit, urls))

    rows, by_issue, flagged = [], defaultdict(set), 0
    present = defaultdict(set)
    for url, status, headers, issues in results:
        for k, _ in headers:
            present[k.lower()].add(url)
        if issues:
            flagged += 1
        for issue, sev, detail in issues:
            by_issue[(issue, sev)].add(url)
            rows.append({"url": url, "status": status, "issue": issue, "severity": sev, "detail": detail})

    rows.sort(key=lambda r: (SEVERITY_ORDER[r["severity"]], r["url"], r["issue"]))
    with open(args.csv, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=["url", "status", "issue", "severity", "detail"])
        w.writeheader()
        w.writerows(rows)

    print(f"Checked {len(urls)} URLs from {args.sitemap}")
    print(f"{flagged} of {len(urls)} pages have at least one issue\n")
    for (issue, sev), pages in sorted(by_issue.items(), key=lambda x: (SEVERITY_ORDER[x[0][1]], -len(x[1]))):
        print(f"  {sev:<6} {issue:<28} {len(pages)} page(s)")

    watched = ["strict-transport-security", "content-security-policy", "x-content-type-options",
               "referrer-policy", "permissions-policy"]
    uneven = [(name, len(present[name])) for name in watched if 0 < len(present[name]) < len(urls)]
    if uneven:
        print("\nSet on some pages but not others (often a second app or theme):")
        for name, n in uneven:
            missing = sorted(set(urls) - present[name])
            print(f"  {name}: {n}/{len(urls)} pages; missing on {', '.join(urlsplit(u).path for u in missing)}")
    print(f"\nDetails: {args.csv}")


if __name__ == "__main__":
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

A few choices worth knowing:

  • Two openers. One follows redirects (for the page itself); the other does not (for the plain-HTTP probe), so you see the 301 and its Location instead of the final page.
  • --http-port. On a real site the HTTP probe uses port 80. The flag exists so the test site can run HTTP and HTTPS on two local ports.
  • --cafile. Lets you trust a self-signed certificate for local testing without turning off certificate checks.
  • Nonces and hashes. 'unsafe-inline' in script-src is not flagged when the same directive also carries a nonce or hash. MDN's script-src page shows that a policy with 'unsafe-inline' plus a nonce acts as nonce-only in browsers that support CSP Level 2, so the fallback is there for older browsers.
  • Headers on errors. If a page returns 404 or 500, its headers are still checked. Error pages are often served by a different layer and miss headers.

The test site

The test site is a fictional dental practice with eight pages. The main pages come from a theme that sets most headers but with weak values: a one-day HSTS max-age, 'unsafe-inline' scripts for a booking widget, Referrer-Policy: unsafe-url and no frame protection. The blog runs on an older stack that sends version headers and nothing else, and plain HTTP serves it without redirecting. The booking page sets a session cookie with no flags, turns on the legacy XSS filter and uses ALLOW-FROM. The privacy page has X-Frame-Options: SAMEORIGIN, so it should pass the framing check.

build_fixture.py writes the pages, the sitemap and two header configs (before and after):

"""Build the fictional "Hollis Street Dental" test site for the security headers audit.
Pages go in ./site, and the response headers for each path go in headers-before.json / headers-after.json."""
import json, os

BASE = "https://localhost:8491"
PAGES = {
    "/": "Hollis Street Dental",
    "/services": "Our services",
    "/services/implants": "Dental implants",
    "/book": "Book an appointment",
    "/contact": "Contact us",
    "/blog": "Blog",
    "/blog/whitening-myths": "Five whitening myths",
    "/privacy": "Privacy notice",
}

os.makedirs("site", exist_ok=True)
for path, title in PAGES.items():
    name = "index" if path == "/" else path.strip("/").replace("/", "__")
    form = ('<form method="post" action="/book"><input name="name"><button>Book</button></form>'
            if path == "/book" else "")
    html = (f"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>{title} | Hollis Street Dental</title>"
            f"</head><body><h1>{title}</h1><p>Fictional test page for a headers audit.</p>{form}</body></html>")
    with open(f"site/{name}.html", "w") as f:
        f.write(html)

urls = "".join(f"<url><loc>{BASE}{p}</loc></url>" for p in PAGES)
with open("site/sitemap.xml", "w") as f:
    f.write(f'<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{urls}</urlset>')

GOOD = {
    "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
    "Content-Security-Policy": "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'",
    "X-Content-Type-Options": "nosniff",
    "Referrer-Policy": "strict-origin-when-cross-origin",
    "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
}

# BEFORE: the main pages come from a theme with most headers set, but with a short HSTS max-age,
# 'unsafe-inline' scripts and no frame protection. The blog runs on an older stack with leaky
# headers and nothing else, and plain HTTP serves it without redirecting. The booking page sets
# a session cookie without flags and turns on the legacy XSS filter.
theme = {
    "Strict-Transport-Security": "max-age=86400",
    "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-inline' https://widgets.example-booking.test",
    "X-Content-Type-Options": "nosniff",
    "Referrer-Policy": "unsafe-url",
}
blog = {"Server": "Apache/2.4.41 (Ubuntu)", "X-Powered-By": "PHP/7.4.33", "X-Generator": "WordPress 5.8.1"}
before = {}
for p in PAGES:
    h = dict(blog) if p.startswith("/blog") else dict(theme)
    if p == "/book":
        h["X-XSS-Protection"] = "1; mode=block"
        h["X-Frame-Options"] = "ALLOW-FROM https://partner.example.test"
        h["Set-Cookie"] = "booking_session=abc123; Path=/"
    if p == "/privacy":
        h["X-Frame-Options"] = "SAMEORIGIN"
    before[p] = {"headers": h, "http_redirect": not p.startswith("/blog")}

after = {}
for p in PAGES:
    h = dict(GOOD)
    if p == "/book":
        h["Set-Cookie"] = "booking_session=abc123; Path=/; Secure; HttpOnly; SameSite=Lax"
    after[p] = {"headers": h, "http_redirect": True}

json.dump(before, open("headers-before.json", "w"), indent=2)
json.dump(after, open("headers-after.json", "w"), indent=2)
print(f"built {len(PAGES)} pages")
Enter fullscreen mode Exit fullscreen mode

serve_fixture.py serves the site over HTTPS on port 8491 with a self-signed certificate, and plain HTTP on port 8091 (redirecting or not, per the config):

"""Serve ./site over HTTPS on localhost:8491 (self-signed cert) and plain HTTP on localhost:8091.
Response headers per path come from the JSON file given as the first argument."""
import functools, http.server, json, os, ssl, sys, threading

CONF = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "headers-before.json"))

def page_conf(path):
    path = path.split("?")[0].split("#")[0].rstrip("/") or "/"
    return path, CONF.get(path)

class Handler(http.server.SimpleHTTPRequestHandler):
    server_version = ""   # we set Server ourselves when the config asks for it
    sys_version = ""
    def version_string(self):
        return self.headers_conf.get("Server", "fixture") if hasattr(self, "headers_conf") else "fixture"
    def translate_path(self, path):
        p = path.split("?")[0].split("#")[0].rstrip("/") or "/"
        if p == "/":
            p = "/index.html"
        elif not os.path.splitext(p)[1]:
            p = "/" + p.strip("/").replace("/", "__") + ".html"
        return super().translate_path(p)
    def end_headers(self):
        path, conf = page_conf(self.path)
        if conf:
            for k, v in conf["headers"].items():
                if k != "Server":
                    self.send_header(k, v)
        super().end_headers()
    def send_head(self):
        path, conf = page_conf(self.path)
        self.headers_conf = conf["headers"] if conf else {}
        return super().send_head()
    def log_message(self, *a):
        pass

class PlainHTTP(Handler):
    def send_head(self):
        path, conf = page_conf(self.path)
        if conf is None or conf["http_redirect"]:
            self.headers_conf = {}
            self.send_response(301)
            self.send_header("Location", "https://localhost:8491" + self.path)
            self.send_header("Content-Length", "0")
            http.server.BaseHTTPRequestHandler.end_headers(self)
            return None
        return super().send_head()

srv = http.server.ThreadingHTTPServer(("127.0.0.1", 8491), functools.partial(Handler, directory="site"))
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("cert.pem", "key.pem")
srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
threading.Thread(target=http.server.ThreadingHTTPServer(
    ("127.0.0.1", 8091), functools.partial(PlainHTTP, directory="site")).serve_forever, daemon=True).start()
srv.serve_forever()
Enter fullscreen mode Exit fullscreen mode

Build it, create a local certificate and start the "before" server:

python3 build_fixture.py
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 30 \
  -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost"
python3 serve_fixture.py headers-before.json &
Enter fullscreen mode Exit fullscreen mode

Running it

python3 security_headers_audit.py https://localhost:8491/sitemap.xml \
  --cafile cert.pem --http-port 8091 --csv headers_report_before.csv
Enter fullscreen mode Exit fullscreen mode

Output:

Checked 8 URLs from https://localhost:8491/sitemap.xml
8 of 8 pages have at least one issue

  high   http_no_redirect             2 page(s)
  high   hsts_missing                 2 page(s)
  medium framing_unprotected          7 page(s)
  medium hsts_short_max_age           6 page(s)
  medium csp_unsafe_inline_scripts    6 page(s)
  medium referrer_policy_unsafe_url   6 page(s)
  medium csp_missing                  2 page(s)
  medium cookie_missing_flags         1 page(s)
  low    nosniff_missing              2 page(s)
  low    referrer_policy_missing      2 page(s)
  low    stack_header                 2 page(s)
  low    xfo_allow_from_obsolete      1 page(s)
  low    x_xss_protection_enabled     1 page(s)
  info   permissions_policy_missing   8 page(s)

Set on some pages but not others (often a second app or theme):
  strict-transport-security: 6/8 pages; missing on /blog, /blog/whitening-myths
  content-security-policy: 6/8 pages; missing on /blog, /blog/whitening-myths
  x-content-type-options: 6/8 pages; missing on /blog, /blog/whitening-myths
  referrer-policy: 6/8 pages; missing on /blog, /blog/whitening-myths

Details: headers_report_before.csv
Enter fullscreen mode Exit fullscreen mode

Every planted problem shows up, and the "set on some pages but not others" block points straight at the blog. On a real client site, that block is often the most useful part of the report: it tells you there is a second system to fix, not eight separate pages.

The first rows of the CSV (sorted by severity, then URL):

url,status,issue,severity,detail
https://localhost:8491/blog,200,hsts_missing,high,
https://localhost:8491/blog,200,http_no_redirect,high,plain HTTP serves the page with 200
https://localhost:8491/blog/whitening-myths,200,hsts_missing,high,
https://localhost:8491/blog/whitening-myths,200,http_no_redirect,high,plain HTTP serves the page with 200
https://localhost:8491/,200,csp_unsafe_inline_scripts,medium,script-src allows 'unsafe-inline'
https://localhost:8491/,200,framing_unprotected,medium,no frame-ancestors and no usable X-Frame-Options
https://localhost:8491/,200,hsts_short_max_age,medium,max-age=86400
https://localhost:8491/,200,referrer_policy_unsafe_url,medium,"full URL sent to every site, including over http"
https://localhost:8491/blog,200,csp_missing,medium,
https://localhost:8491/blog,200,framing_unprotected,medium,no frame-ancestors and no usable X-Frame-Options
https://localhost:8491/blog/whitening-myths,200,csp_missing,medium,
Enter fullscreen mode Exit fullscreen mode

And the booking page's low-severity rows:

https://localhost:8491/book,200,csp_unsafe_inline_scripts,medium,script-src allows 'unsafe-inline'
https://localhost:8491/book,200,x_xss_protection_enabled,low,'1; mode=block' (MDN: use CSP; send 0 or nothing)
https://localhost:8491/book,200,xfo_allow_from_obsolete,low,browsers ignore ALLOW-FROM
Enter fullscreen mode Exit fullscreen mode

Fixing it and running again

The "after" config sends the same set of headers on every page, from one place:

Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Set-Cookie: booking_session=abc123; Path=/; Secure; HttpOnly; SameSite=Lax   (booking page only)
Enter fullscreen mode Exit fullscreen mode

Plain HTTP now redirects for every path, the blog's version headers are gone, X-XSS-Protection and ALLOW-FROM are removed, and frame-ancestors 'self' replaces X-Frame-Options. In the fixed CSP, the booking widget's script origin was dropped because the test site does not load it. On a real site you would list the widget's origin in script-src instead of allowing 'unsafe-inline'.

Restart the server with the fixed config and run the same command:

kill %1
python3 serve_fixture.py headers-after.json &
python3 security_headers_audit.py https://localhost:8491/sitemap.xml \
  --cafile cert.pem --http-port 8091 --csv headers_report_after.csv
Enter fullscreen mode Exit fullscreen mode
Checked 8 URLs from https://localhost:8491/sitemap.xml
0 of 8 pages have at least one issue


Details: headers_report_after.csv
Enter fullscreen mode Exit fullscreen mode

Running it on a client site

  • Ask first. Run it only on sites you look after or have permission to test. It sends one HTTPS and one HTTP request per sitemap URL, which is light, but it is still traffic.
  • Use the full sitemap. Many CMS sitemaps are indexes with child sitemaps for posts, pages and products. The script follows the index, so point it at the root.
  • Read the "some pages but not others" block first. If the blog, a booking plugin or a landing-page builder misses headers, fix it where those pages are served (the CDN, the web server config or the plugin), not page by page.
  • HttpOnly is a judgment call. A cookie your own JavaScript reads (an analytics or attribution cookie, for example) cannot be HttpOnly, so cookie_missing_flags with only HttpOnly missing is worth a look, not an automatic fix. Session and login cookies should have all three flags.
  • CSP takes care. A strict policy can break analytics, chat widgets, booking tools and embedded maps. Start with Content-Security-Policy-Report-Only (the script notes when only that header is present), watch the reports, then enforce. Replace 'unsafe-inline' with nonces, hashes or explicit origins where you can.
  • HSTS takes care too. Once a browser has seen a long max-age, it will refuse plain HTTP for that host for the whole period. Make sure every subdomain works over HTTPS before adding includeSubDomains, and raise max-age in steps.
  • Headers set in HTML do not count. MDN notes that X-Frame-Options in a <meta> tag "has no effect." The script reads only response headers, which matches how browsers apply these.
  • Be polite. The default is 4 workers. Use --workers 2 on small shared hosting.

What to fix first

  1. http_no_redirect and hsts_missing. These are about every visitor's connection. Usually one redirect rule and one header at the server or CDN.
  2. cookie_missing_flags on session or booking cookies. Add Secure, HttpOnly and SameSite in the plugin or app that sets them.
  3. framing_unprotected. Add frame-ancestors 'self' (or 'none') to the CSP, or X-Frame-Options: SAMEORIGIN if you have no CSP yet.
  4. CSP gaps. Add a policy in report-only mode, then tighten.
  5. The low and info rows. nosniff, Referrer-Policy, Permissions-Policy, removing version headers and the legacy XSS filter. All one-line changes, best done together.

Related free tool

Before you audit a client's site, you need its sitemap URL, and on a site with several sections you also want the full list of pages to check. Our free Sitemap URL Extractor takes a sitemap URL or pasted XML and gives you one URL per line from the loc tags (for a sitemap index, it lists the child sitemaps so you can open each one). It does not look at headers; that is what the script is for.

If you also want to check that HTTPS pages do not load HTTP resources, our earlier post on finding mixed content across your sitemap pairs well with this one.

FAQ

Which security headers should every site send?
OWASP's Secure Headers Project publishes a list of headers to add with recommended values, including Strict-Transport-Security, Content-Security-Policy, X-Content-Type-Options, Referrer-Policy, Permissions-Policy and X-Frame-Options. Use it as a starting point and test each one against the site's widgets and embeds.

Why does the script ignore HSTS on HTTP responses?
MDN says browsers ignore the header when it arrives over plain HTTP. Only the HTTPS response counts.

Should I still send X-XSS-Protection?
MDN recommends Content-Security-Policy instead and warns the filter can create vulnerabilities in some cases. The script flags it only when it turns the filter on; X-XSS-Protection: 0 or no header at all passes.

Is X-Frame-Options or frame-ancestors better?
MDN points to frame-ancestors in a CSP for "more comprehensive options." The script accepts either. If both are present, browsers that support frame-ancestors use it.

Does a clean report mean the site is secure?
No. It means the headers on the pages in the sitemap are present and configured sensibly. Pages outside the sitemap, logins, forms, plugins and server software need their own checks.


If you are onboarding a new client site, our free Sitemap URL Extractor gives you the page list in one step, so you can point this script at the right sitemap.

RG, Founder, Appie.run

Top comments (0)