Engineer a security headers baseline across apps with automated scanning, differential…
- User
Engineer a security headers baseline across apps with automated scanning, differential reporting, and exception handling.
Assistant
Engineer a security headers baseline across apps with automated scanning, differential reporting, and exception handling.
The user wants to engineer a "security headers baseline" across applications. This involves three key components:
This is a system design/engineering task. I should structure the response as a comprehensive guide or a blueprint for building this system.
Key Components to Cover:
security-headers.com API (if allowed), or better, an open-source tool like zaproxy or a custom Python script using requests and hstspreload libraries for granular control. Let's suggest a custom Python script or a CI/CD integration (GitHub Actions/GitLab CI) for "Engineering" it.Structure of the Response:
Refining the Content:
requests library. I'll write a mock script that fetches headers and validates them.set(current_headers) - set(baseline). Store results in a results.json.exceptions list with expiration dates (so they don't last forever).Drafting the Solution:
Self-Correction/Edge Cases:
Final Polish: The tone should be professional and architectural. "Engineer" implies building a robust system, not just running a tool once.
Step-by-Step Plan:
baseline_policy.yml.requests.exceptions logic in the policy.Let's write the code. I'll provide a modular Python approach.
I will include a specific section on what headers to include (HSTS, CSP, X-Content-Type-Options, etc.) but keep the configuration flexible.
Let's assemble. This engineering challenge requires a system that treats security headers as "Infrastructure as Code." We need to move away from ad-hoc checks to a stateful, version-controlled, and automated pipeline.
Below is a comprehensive blueprint for building a Security Headers Baseline System.
Instead of hardcoding checks, we define a generic policy file. This allows you to apply different standards to different apps (e.g., stricter for banking apps, looser for marketing sites).
File: security_policy.yaml
version: 1.0
global_standards:
- header: "Strict-Transport-Security"
# Regex ensures max-age is at least 6 months
value: "max-age=\\d{7,}.*includeSubDomains"
severity: "critical"
description: "Ensures HTTPS enforcement."
- header: "X-Content-Type-Options"
value: "nosniff"
severity: "high"
- header: "Content-Security-Policy"
# Complex check: ensure 'unsafe-inline' is not present
value: "^(?!.*unsafe-inline).*$"
severity: "critical"
- header: "X-Frame-Options"
value: "DENY|SAMEORIGIN"
severity: "medium"
application_overrides:
# Legacy marketing site that cannot support CSP yet
"marketing-site":
- header: "Content-Security-Policy"
action: "ignore" # Exception handling
reason: "Legacy JS requires eval"
expires: "2023-12-31"
We will build a Python script that performs three tasks: Fetch, Validate, and Diff.
Prerequisites: pip install requests pyyaml jsondiff
File: header_scanner.py
import requests
import yaml
import json
import re
import os
from datetime import datetime
from jsondiff import diff
class HeaderScanner:
def __init__(self, policy_file, history_dir="scan_history"):
with open(policy_file, 'r') as f:
self.policy = yaml.safe_load(f)
self.history_dir = history_dir
os.makedirs(self.history_dir, exist_ok=True)
def fetch_headers(self, url):
try:
# Use HEAD request for speed, fallback to GET if needed
response = requests.head(url, timeout=10, allow_redirects=True)
return dict(response.headers)
except Exception as e:
return {"error": str(e)}
def validate_headers(self, headers, app_name):
results = {"compliant": [], "violations": [], "skipped": []}
# Determine which rules apply
rules = self.policy['global_standards']
overrides = self.policy.get('application_overrides', {}).get(app_name, [])
for rule in rules:
header_name = rule['header']
expected_pattern = rule['value']
severity = rule['severity']
# Check for Exceptions
exception = next((o for o in overrides if o['header'] == header_name), None)
if exception:
# Check if exception expired
exp_date = datetime.strptime(exception['expires'], "%Y-%m-%d")
if datetime.now() < exp_date:
results['skipped'].append({
"header": header_name,
"reason": exception['reason']
})
continue
# Validation Logic
actual_value = headers.get(header_name)
if not actual_value:
results['violations'].append({
"header": header_name,
"severity": severity,
"error": "Missing Header"
})
elif not re.search(expected_pattern, actual_value):
results['violations'].append({
"header": header_name,
"severity": severity,
"expected": expected_pattern,
"actual": actual_value,
"error": "Value Mismatch"
})
else:
results['compliant'].append(header_name)
return results
def run_differential_report(self, app_name, current_scan):
"""
Compares current scan with the last 'golden' scan to detect drift.
"""
history_file = os.path.join(self.history_dir, f"{app_name}.json")
if not os.path.exists(history_file):
print(f"[{app_name}] No history found. Establishing baseline.")
with open(history_file, 'w') as f:
json.dump(current_scan, f)
return {"status": "baseline_created"}
with open(history_file, 'r') as f:
last_scan = json.load(f)
# Compare raw headers to detect ANY change (even if compliant)
# This detects if an admin changed a header value manually
delta = diff(last_scan.get('raw_headers', {}), current_scan.get('raw_headers', {}))
# Update history if scan is compliant
if not current_scan['results']['violations']:
with open(history_file, 'w') as f:
json.dump(current_scan, f)
return delta
# --- Execution Logic ---
if __name__ == "__main__":
# Mock Inventory
apps = [
{"name": "main-app", "url": "https://google.com"}, # Using google just for demo headers
{"name": "marketing-site", "url": "https://example.com"}
]
scanner = HeaderScanner('security_policy.yaml')
for app in apps:
print(f"\n--- Scanning: {app['name']} ---")
raw_headers = scanner.fetch_headers(app['url'])
validation_results = scanner.validate_headers(raw_headers, app['name'])
scan_payload = {
"timestamp": datetime.now().isoformat(),
"raw_headers": raw_headers,
"results": validation_results
}
# Differential Reporting
delta = scanner.run_differential_report(app['name'], scan_payload)
# Output
print(f"Violations: {len(validation_results['violations'])}")
if validation_results['violations']:
print(json.dumps(validation_results['violations'], indent=2))
if delta:
print(f"\n[!] DRIFT DETECTED: Configuration changed since last run:")
print(json.dumps(delta, indent=2))
Automated scanners fail if they are too rigid. The system must handle exceptions gracefully without ignoring security.
The Workflow:
application_overrides in the YAML.expires date.
SKIPPED (Compliant with Exception).Audit Trail: Every time an exception is invoked, it should be logged to a SIEM or printed in the report so you know why a specific app is failing standard baseline checks.
There are two types of reporting required:
Compliance Reporting (Snapshot): "Does App X pass the baseline today?"
Differential Reporting (Drift): "Did App X change since yesterday?"
max-age or remove X-Frame-Options tomorrow. The app might still pass a lax baseline, but the change is suspicious.run_differential_report function in the Python script uses jsondiff to compare the raw header map against the stored JSON state.Do not run this manually. Embed it into your pipeline.
GitHub Actions Example:
name: Security Header Baseline Check
on:
schedule:
- cron: '0 8 * * *' # Daily scan
workflow_dispatch:
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install Dependencies
run: pip install requests pyyaml jsondiff
- name: Run Header Baseline Scan
run: python header_scanner.py
id: scan_output
- name: Alert on Failure
if: failure() # Or custom logic based on output
run: |
# Send Slack webhook or create GitHub Issue
echo "::error::Security Header Baseline Drift or Violation Detected"