Build a Python Security Headers Checker (Full Code Included)


Every time your browser loads a website, the server sends invisible instructions called HTTP security headers. They tell the browser: “never load this site over plain HTTP,” “block scripts from untrusted sources,” “don’t let this page be embedded in an iframe.” Missing headers are one of the most common findings in security audits — and they’re trivially easy to check for.

The Headers That Matter

  • Strict-Transport-Security — forces HTTPS, killing downgrade attacks.
  • Content-Security-Policy — restricts which scripts can run, blocking most XSS attacks.
  • X-Frame-Options — prevents clickjacking by blocking iframe embedding.
  • X-Content-Type-Options — stops the browser from misinterpreting file types.

The Script

This checker scans any URL and reports which headers are present or missing. For educational use on sites you own or public test sites:

import requests
import sys
IMPORTANT_HEADERS = {
"Strict-Transport-Security": "Forces HTTPS — blocks downgrade attacks",
"Content-Security-Policy": "Restricts scripts — blocks most XSS",
"X-Frame-Options": "Blocks iframe embedding — stops clickjacking",
"X-Content-Type-Options": "Stops MIME sniffing attacks",
"Referrer-Policy": "Controls what info leaks to other sites",
}
def check_headers(url):
if not url.startswith("http"):
url = "https://" + url
try:
r = requests.get(url, timeout=10)
except requests.RequestException as e:
print(f"Could not reach {url}: {e}")
return
print(f"\nSecurity header report for {url}\n" + "-" * 40)
for header, desc in IMPORTANT_HEADERS.items():
if header.lower() in (h.lower() for h in r.headers):
print(f"[OK] {header}")
else:
print(f"[MISSING] {header} — {desc}")
print("-" * 40)
if __name__ == "__main__":
target = sys.argv[1] if len(sys.argv) > 1 else input("Enter URL: ")
check_headers(target)

How to Use It

Save it as headers.py, install the requests library (pip install requests), and run python headers.py example.com. The report shows exactly which protections are missing — the same information security auditors charge for.

Make It Better

Try extending the script: check header values (a weak Content-Security-Policy is barely better than none), scan a list of URLs from a file, or flag sites missing HTTPS entirely. Every feature you add is real defensive security skill — the kind that makes websites safer.

Comments

Popular Posts