Ajoute 16 skills de sécurité (sélection web/API)

Tirés de mukul975/anthropic-cybersecurity-skills (commit 54a7988,
Apache-2.0) : contrôle d'accès/IDOR, en-têtes et CSP, CORS, OAuth, JWT,
XSS, fonctions serverless, rate limiting, paquets npm, gitleaks, RGPD,
OWASP API Top 10. Les 800 autres (offensifs, Windows/AD, forensique…)
sont laissés de côté. Voir .claude/skills/README.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-10-08 17:36:57 +00:00
1 parent 080f733ba4
commit c5924cc009
74 files changed
+14803

No files matched your search

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,325 @@
---
name: performing-security-headers-audit
description: Auditing HTTP security headers including CSP, HSTS, X-Frame-Options,
and cookie attributes to identify missing or misconfigured browser-level protections.
domain: cybersecurity
subdomain: web-application-security
tags:
- penetration-testing
- security-headers
- csp
- hsts
- owasp
- web-security
- hardening
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- PR.PS-01
- ID.RA-01
- PR.DS-10
- DE.CM-01
mitre_attack:
- T1190
- T1059.007
- T1505.003
- T1083
---
# Performing Security Headers Audit
## When to Use
- During authorized web application security assessments as a standard configuration review
- When evaluating browser-level protections against XSS, clickjacking, and data leakage
- For compliance assessments requiring security header implementation (PCI DSS, SOC 2)
- When performing initial reconnaissance to identify easy-win security improvements
- During CI/CD pipeline security gate checks for new deployments
## Prerequisites
- **Authorization**: Written scope for the target application (header review is low-risk)
- **curl**: For fetching response headers from target endpoints
- **SecurityHeaders.com**: Online scanner for quick header assessment
- **Mozilla Observatory**: Mozilla's web security testing tool
- **Burp Suite**: For comprehensive header analysis across multiple pages
- **Browser DevTools**: For examining headers and CSP violations in real-time
## Workflow
### Step 1: Collect Security Headers from Target
Retrieve and catalog all security-related response headers.
```bash
# Fetch all response headers
curl -s -I "https://target.example.com/" | grep -iE \
"(strict-transport|content-security|x-frame|x-content-type|x-xss|referrer-policy|permissions-policy|feature-policy|x-permitted|cross-origin|set-cookie|server|x-powered-by|cache-control)"
# Check headers across multiple pages
PAGES=("/" "/login" "/api/health" "/admin" "/account/settings" "/static/app.js")
for page in "${PAGES[@]}"; do
echo "=== $page ==="
curl -s -I "https://target.example.com$page" 2>/dev/null | grep -iE \
"(strict-transport|content-security|x-frame|x-content-type|x-xss|referrer-policy|permissions-policy|set-cookie|server|x-powered)"
echo
done
# Check both HTTP and HTTPS responses
echo "=== HTTP Response ==="
curl -s -I "http://target.example.com/" | head -20
echo "=== HTTPS Response ==="
curl -s -I "https://target.example.com/" | head -20
```
### Step 2: Assess Transport Security (HSTS)
Evaluate HTTP Strict Transport Security configuration.
```bash
# Check HSTS header
curl -s -I "https://target.example.com/" | grep -i "strict-transport-security"
# Expected: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# Verify HSTS attributes:
# max-age: Should be >= 31536000 (1 year) for preload eligibility
# includeSubDomains: Protects all subdomains
# preload: Eligible for browser HSTS preload list
# Check if HTTP redirects to HTTPS
curl -s -I "http://target.example.com/" | head -5
# Should be 301/302 redirect to https://
# Check if HSTS is on the preload list
# Visit: https://hstspreload.org/?domain=target.example.com
# Test for HTTPS-only cookies
curl -s -I "https://target.example.com/login" | grep -i "set-cookie"
# All session cookies should have Secure flag
# Check for mixed content
curl -s "https://target.example.com/" | grep -oP "http://[^\"']+" | head -20
# HTTP resources loaded on HTTPS pages create mixed content vulnerabilities
```
### Step 3: Audit Content Security Policy (CSP)
Analyze CSP headers for effectiveness and potential bypasses.
```bash
# Extract CSP header
CSP=$(curl -s -I "https://target.example.com/" | grep -i "content-security-policy" | cut -d: -f2-)
echo "$CSP"
# Check for dangerous directives:
# 'unsafe-inline' in script-src: Allows inline scripts (XSS risk)
# 'unsafe-eval' in script-src: Allows eval() (XSS risk)
# * in any directive: Allows loading from any origin
# data: in script-src: Allows data: URI scripts
# Missing default-src: No fallback policy
echo "$CSP" | tr ';' '\n' | while read directive; do
echo " $directive"
if echo "$directive" | grep -q "unsafe-inline"; then
echo " WARNING: unsafe-inline allows inline script execution"
fi
if echo "$directive" | grep -q "unsafe-eval"; then
echo " WARNING: unsafe-eval allows eval() calls"
fi
if echo "$directive" | grep -q " \* "; then
echo " WARNING: wildcard allows loading from any origin"
fi
done
# Check for CSP report-only (not enforcing)
curl -s -I "https://target.example.com/" | grep -i "content-security-policy-report-only"
# Report-only does NOT block violations, only logs them
# Test CSP with Google's evaluator
# https://csp-evaluator.withgoogle.com/
# Paste the CSP header for automated analysis
# Check for CSP bypass via whitelisted domains
# If CDN domains are whitelisted, check for JSONP endpoints or angular libraries
```
### Step 4: Check Frame Protection and Click Defense Headers
Verify anti-clickjacking and iframe embedding controls.
```bash
# X-Frame-Options
curl -s -I "https://target.example.com/" | grep -i "x-frame-options"
# Expected: DENY or SAMEORIGIN
# ALLOW-FROM is deprecated and not supported in modern browsers
# CSP frame-ancestors (supersedes X-Frame-Options)
curl -s -I "https://target.example.com/" | grep -i "content-security-policy" | grep -o "frame-ancestors[^;]*"
# Expected: frame-ancestors 'none' or frame-ancestors 'self'
# X-Content-Type-Options
curl -s -I "https://target.example.com/" | grep -i "x-content-type-options"
# Expected: nosniff (prevents MIME type sniffing)
# X-XSS-Protection (legacy, but still useful for older browsers)
curl -s -I "https://target.example.com/" | grep -i "x-xss-protection"
# Expected: 1; mode=block (or 0 if CSP is comprehensive)
# Note: Modern recommendation is 0 (disable) when CSP is present
# Referrer-Policy
curl -s -I "https://target.example.com/" | grep -i "referrer-policy"
# Expected: strict-origin-when-cross-origin or no-referrer
# Prevents sensitive URL data from leaking via Referer header
```
### Step 5: Audit Cookie Security Attributes
Examine session and authentication cookies for security flags.
```bash
# Fetch all Set-Cookie headers
curl -s -I -L "https://target.example.com/login" | grep -i "set-cookie"
# Check each cookie for required attributes:
# Secure: Only sent over HTTPS
# HttpOnly: Not accessible via JavaScript (prevents XSS cookie theft)
# SameSite: Controls cross-site cookie sending (Strict, Lax, None)
# Path: Restricts cookie scope
# Domain: Controls which domains receive the cookie
# Max-Age/Expires: Cookie lifetime
# Automated cookie check
curl -s -I "https://target.example.com/login" | grep -i "set-cookie" | while read line; do
echo "Cookie: $(echo "$line" | grep -oP '[^:]+=[^;]+')"
missing=""
echo "$line" | grep -qi "secure" || missing="$missing Secure"
echo "$line" | grep -qi "httponly" || missing="$missing HttpOnly"
echo "$line" | grep -qi "samesite" || missing="$missing SameSite"
if [ -n "$missing" ]; then
echo " MISSING:$missing"
else
echo " All flags present"
fi
done
# Check for __Host- and __Secure- cookie prefixes
# __Host- cookies must have Secure, Path=/, no Domain
# __Secure- cookies must have Secure flag
```
### Step 6: Check Permissions Policy and Information Disclosure
Review browser feature controls and information leakage headers.
```bash
# Permissions-Policy (formerly Feature-Policy)
curl -s -I "https://target.example.com/" | grep -i "permissions-policy"
# Controls browser features: camera, microphone, geolocation, etc.
# Expected: Restrict unused features
# Example: permissions-policy: camera=(), microphone=(), geolocation=()
# Cross-Origin headers
curl -s -I "https://target.example.com/" | grep -iE "(cross-origin-embedder|cross-origin-opener|cross-origin-resource)"
# COEP: Cross-Origin-Embedder-Policy: require-corp
# COOP: Cross-Origin-Opener-Policy: same-origin
# CORP: Cross-Origin-Resource-Policy: same-origin
# Information disclosure headers to flag
curl -s -I "https://target.example.com/" | grep -iE "(server|x-powered-by|x-aspnet|x-generator)"
# Server: Apache/2.4.52 (should be removed or generic)
# X-Powered-By: PHP/8.1.2 (should be removed)
# These headers reveal technology stack to attackers
# Cache-Control for sensitive pages
curl -s -I "https://target.example.com/account/settings" | grep -i "cache-control"
# Sensitive pages should have: Cache-Control: no-store, no-cache, must-revalidate
# Prevents browser caching of sensitive data
# Generate comprehensive report using online tools
echo "Scan with SecurityHeaders.com: https://securityheaders.com/?q=target.example.com"
echo "Scan with Mozilla Observatory: https://observatory.mozilla.org/analyze/target.example.com"
```
## Key Concepts
| Concept | Description |
|---------|-------------|
| **HSTS** | Forces browsers to only use HTTPS for the domain, preventing protocol downgrade attacks |
| **CSP** | Restricts which resources (scripts, styles, images) can load on the page |
| **X-Frame-Options** | Controls whether the page can be embedded in iframes (clickjacking defense) |
| **X-Content-Type-Options** | Prevents MIME type sniffing; forces browser to respect declared Content-Type |
| **Referrer-Policy** | Controls how much referrer information is sent with cross-origin requests |
| **Permissions-Policy** | Restricts browser features (camera, microphone, geolocation) available to the page |
| **SameSite Cookie** | Controls when cookies are sent in cross-site contexts (Strict, Lax, None) |
| **HSTS Preloading** | Hardcoding HSTS policy in browser source code for first-visit protection |
## Tools & Systems
| Tool | Purpose |
|------|---------|
| **SecurityHeaders.com** | Online scanner providing letter-grade security header assessment |
| **Mozilla Observatory** | Comprehensive web security scanner with scoring and recommendations |
| **CSP Evaluator (Google)** | Analyzes Content Security Policy for weaknesses and bypasses |
| **Burp Suite Professional** | Inspecting response headers across all application pages |
| **securityheaders (CLI)** | Command-line security header scanner |
| **Hardenize** | TLS and security header monitoring service |
## Common Scenarios
### Scenario 1: Complete Header Absence
A legacy application returns no security headers at all. No HSTS, CSP, X-Frame-Options, or cookie security flags. Every page is vulnerable to clickjacking, XSS has no browser-level mitigation, and cookies are sent over HTTP.
### Scenario 2: Weak CSP with unsafe-inline
The CSP header includes `script-src 'self' 'unsafe-inline'`. While it restricts external script loading, the `unsafe-inline` directive allows any inline script to execute, rendering the CSP ineffective against XSS.
### Scenario 3: Session Cookie Without Secure Flag
The session cookie is set without the `Secure` flag. On mixed HTTP/HTTPS sites, the session token can be intercepted by a network attacker via a plain HTTP request.
### Scenario 4: Missing HSTS Enabling SSL Stripping
No HSTS header is present. An attacker on the network can perform an SSL stripping attack, downgrading the victim's HTTPS connection to HTTP and intercepting all traffic.
## Output Format
```
## Security Headers Audit Report
**Target**: target.example.com
**Grade**: D (SecurityHeaders.com)
**Assessment Date**: 2024-01-15
### Headers Assessment
| Header | Status | Current Value | Recommended |
|--------|--------|---------------|-------------|
| Strict-Transport-Security | MISSING | - | max-age=31536000; includeSubDomains; preload |
| Content-Security-Policy | WEAK | script-src 'self' 'unsafe-inline' | script-src 'self' 'nonce-{random}' |
| X-Frame-Options | MISSING | - | DENY |
| X-Content-Type-Options | PRESENT | nosniff | nosniff (OK) |
| Referrer-Policy | MISSING | - | strict-origin-when-cross-origin |
| Permissions-Policy | MISSING | - | camera=(), microphone=(), geolocation=() |
| X-XSS-Protection | MISSING | - | 0 (with strong CSP) |
### Cookie Security
| Cookie | Secure | HttpOnly | SameSite | Path |
|--------|--------|----------|----------|------|
| session | NO | YES | Not set | / |
| user_pref | NO | NO | Not set | / |
| csrf_token | YES | NO | Strict | / |
### Information Disclosure
| Header | Value | Risk |
|--------|-------|------|
| Server | Apache/2.4.52 | Technology fingerprinting |
| X-Powered-By | PHP/8.1.2 | Version-specific exploit targeting |
### Recommendation Priority
1. **Critical**: Add Secure and SameSite flags to session cookie
2. **High**: Implement HSTS with min 1-year max-age
3. **High**: Replace 'unsafe-inline' in CSP with nonce-based policy
4. **Medium**: Add X-Frame-Options: DENY
5. **Medium**: Add Referrer-Policy: strict-origin-when-cross-origin
6. **Low**: Remove Server and X-Powered-By version information
7. **Low**: Add Permissions-Policy to restrict unused browser features
```
@@ -0,0 +1,44 @@
# API Reference: Security Headers Audit
## Security Headers Checked
| Header | Recommended Value | Purpose |
|--------|------------------|---------|
| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` | Force HTTPS |
| `Content-Security-Policy` | `script-src 'self' 'nonce-{random}'` | Restrict resource loading |
| `X-Frame-Options` | `DENY` | Prevent clickjacking |
| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing |
| `Referrer-Policy` | `strict-origin-when-cross-origin` | Control referrer leakage |
| `Permissions-Policy` | `camera=(), microphone=(), geolocation=()` | Restrict browser features |
## Cookie Security Attributes
| Attribute | Description |
|-----------|-------------|
| `Secure` | Only send over HTTPS |
| `HttpOnly` | Not accessible via JavaScript |
| `SameSite=Strict` | No cross-site cookie sending |
| `Path=/` | Restrict cookie scope |
## Online Scanners
| Tool | URL | Description |
|------|-----|-------------|
| SecurityHeaders.com | https://securityheaders.com/ | Letter-grade assessment |
| Mozilla Observatory | https://observatory.mozilla.org/ | Comprehensive scoring |
| CSP Evaluator | https://csp-evaluator.withgoogle.com/ | CSP weakness analysis |
| Hardenize | https://www.hardenize.com/ | TLS and header monitoring |
## Python Libraries
| Library | Version | Purpose |
|---------|---------|---------|
| `requests` | >=2.28 | Fetch HTTP response headers |
| `re` | stdlib | Parse CSP directives and HSTS values |
## References
- OWASP Secure Headers: https://owasp.org/www-project-secure-headers/
- MDN Security Headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
- HSTS Preload: https://hstspreload.org/
- CSP reference: https://content-security-policy.com/
@@ -0,0 +1,276 @@
#!/usr/bin/env python3
"""Agent for performing security headers audit.
Analyzes HTTP response headers for HSTS, CSP, X-Frame-Options,
cookie security attributes, and information disclosure to identify
missing or misconfigured browser-level protections.
"""
import requests
import json
import sys
import re
from datetime import datetime
class SecurityHeadersAgent:
"""Audits HTTP security headers on web applications."""
def __init__(self, target_url):
self.target_url = target_url
if not target_url.startswith("http"):
self.target_url = f"https://{target_url}"
self.session = requests.Session()
self.session.verify = True
def fetch_headers(self, path="/"):
"""Fetch response headers from a target path."""
url = f"{self.target_url.rstrip('/')}{path}"
try:
resp = self.session.get(url, timeout=10, allow_redirects=True)
return {
"url": url,
"status": resp.status_code,
"headers": dict(resp.headers),
"cookies": [
{"name": c.name, "value": c.value[:20], "attributes": {
"secure": c.secure, "httponly": "httponly" in c._rest,
"samesite": c._rest.get("SameSite", c._rest.get("samesite", "Not set")),
"path": c.path, "domain": c.domain,
}} for c in resp.cookies
],
}
except requests.RequestException as e:
return {"url": url, "error": str(e)}
def check_hsts(self, headers):
"""Check HTTP Strict Transport Security configuration."""
hsts = headers.get("Strict-Transport-Security", headers.get("strict-transport-security", ""))
finding = {
"header": "Strict-Transport-Security",
"present": bool(hsts),
"value": hsts,
"severity": "High" if not hsts else "Info",
}
if hsts:
finding["has_includeSubDomains"] = "includesubdomains" in hsts.lower()
finding["has_preload"] = "preload" in hsts.lower()
max_age_match = re.search(r"max-age=(\d+)", hsts)
if max_age_match:
max_age = int(max_age_match.group(1))
finding["max_age"] = max_age
finding["max_age_sufficient"] = max_age >= 31536000
if max_age < 31536000:
finding["severity"] = "Medium"
finding["recommendation"] = "Increase max-age to at least 31536000 (1 year)"
else:
finding["recommendation"] = "Add: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload"
return finding
def check_csp(self, headers):
"""Analyze Content Security Policy for weaknesses."""
csp = headers.get("Content-Security-Policy", headers.get("content-security-policy", ""))
report_only = headers.get("Content-Security-Policy-Report-Only", "")
finding = {
"header": "Content-Security-Policy",
"present": bool(csp),
"value": csp[:500] if csp else "",
"report_only": bool(report_only),
"severity": "High" if not csp else "Info",
"issues": [],
}
if csp:
if "'unsafe-inline'" in csp:
finding["issues"].append("unsafe-inline allows inline script execution (XSS risk)")
finding["severity"] = "High"
if "'unsafe-eval'" in csp:
finding["issues"].append("unsafe-eval allows eval() calls (XSS risk)")
finding["severity"] = "High"
if " * " in f" {csp} " or csp.strip().endswith("*"):
finding["issues"].append("Wildcard (*) allows loading from any origin")
finding["severity"] = "Medium"
if "default-src" not in csp:
finding["issues"].append("Missing default-src fallback directive")
if report_only and not csp:
finding["issues"].append("CSP is report-only, not enforcing")
finding["severity"] = "Medium"
else:
finding["recommendation"] = "Implement Content-Security-Policy with script-src using nonces"
return finding
def check_frame_options(self, headers):
"""Check X-Frame-Options and frame-ancestors."""
xfo = headers.get("X-Frame-Options", headers.get("x-frame-options", ""))
csp = headers.get("Content-Security-Policy", "")
frame_ancestors = ""
if "frame-ancestors" in csp:
match = re.search(r"frame-ancestors\s+([^;]+)", csp)
if match:
frame_ancestors = match.group(1).strip()
finding = {
"header": "X-Frame-Options",
"present": bool(xfo),
"value": xfo,
"frame_ancestors": frame_ancestors,
"severity": "Medium" if not xfo and not frame_ancestors else "Info",
}
if not xfo and not frame_ancestors:
finding["recommendation"] = "Add X-Frame-Options: DENY or CSP frame-ancestors 'none'"
return finding
def check_content_type_options(self, headers):
"""Check X-Content-Type-Options."""
xcto = headers.get("X-Content-Type-Options", headers.get("x-content-type-options", ""))
return {
"header": "X-Content-Type-Options",
"present": bool(xcto),
"value": xcto,
"correct": xcto.lower() == "nosniff" if xcto else False,
"severity": "Medium" if not xcto else "Info",
"recommendation": "Add: X-Content-Type-Options: nosniff" if not xcto else None,
}
def check_referrer_policy(self, headers):
"""Check Referrer-Policy."""
rp = headers.get("Referrer-Policy", headers.get("referrer-policy", ""))
return {
"header": "Referrer-Policy",
"present": bool(rp),
"value": rp,
"severity": "Medium" if not rp else "Info",
"recommendation": "Add: Referrer-Policy: strict-origin-when-cross-origin" if not rp else None,
}
def check_permissions_policy(self, headers):
"""Check Permissions-Policy."""
pp = headers.get("Permissions-Policy", headers.get("permissions-policy", ""))
return {
"header": "Permissions-Policy",
"present": bool(pp),
"value": pp[:200] if pp else "",
"severity": "Low" if not pp else "Info",
"recommendation": "Add: Permissions-Policy: camera=(), microphone=(), geolocation=()" if not pp else None,
}
def check_info_disclosure(self, headers):
"""Check for information disclosure headers."""
findings = []
disclosure_headers = ["Server", "X-Powered-By", "X-AspNet-Version", "X-Generator"]
for h in disclosure_headers:
value = headers.get(h, headers.get(h.lower(), ""))
if value:
findings.append({
"header": h,
"value": value,
"severity": "Low",
"recommendation": f"Remove or genericize {h} header",
})
return findings
def check_cookie_security(self, cookies):
"""Audit cookie security attributes."""
findings = []
for cookie in cookies:
attrs = cookie.get("attributes", {})
issues = []
if not attrs.get("secure"):
issues.append("Missing Secure flag")
if not attrs.get("httponly"):
issues.append("Missing HttpOnly flag")
samesite = str(attrs.get("samesite", "Not set"))
if samesite == "Not set" or samesite == "None":
issues.append(f"SameSite={samesite}")
if issues:
findings.append({
"cookie": cookie["name"],
"issues": issues,
"severity": "High" if "Secure" in str(issues) else "Medium",
})
return findings
def calculate_grade(self, header_findings):
"""Calculate a letter grade based on findings."""
score = 100
for f in header_findings:
if not f.get("present", True):
sev = f.get("severity", "Info")
if sev == "High":
score -= 20
elif sev == "Medium":
score -= 10
elif sev == "Low":
score -= 5
if f.get("issues"):
score -= len(f["issues"]) * 5
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 60:
return "C"
elif score >= 40:
return "D"
return "F"
def run_audit(self, paths=None):
"""Run complete security headers audit."""
if paths is None:
paths = ["/"]
all_findings = []
for path in paths:
response_data = self.fetch_headers(path)
if "error" in response_data:
continue
headers = response_data["headers"]
findings = {
"path": path,
"hsts": self.check_hsts(headers),
"csp": self.check_csp(headers),
"x_frame_options": self.check_frame_options(headers),
"x_content_type_options": self.check_content_type_options(headers),
"referrer_policy": self.check_referrer_policy(headers),
"permissions_policy": self.check_permissions_policy(headers),
"info_disclosure": self.check_info_disclosure(headers),
"cookie_security": self.check_cookie_security(response_data.get("cookies", [])),
}
all_findings.append(findings)
header_checks = []
if all_findings:
f = all_findings[0]
header_checks = [f["hsts"], f["csp"], f["x_frame_options"],
f["x_content_type_options"], f["referrer_policy"],
f["permissions_policy"]]
report = {
"target": self.target_url,
"audit_date": datetime.utcnow().isoformat(),
"grade": self.calculate_grade(header_checks),
"findings": all_findings,
}
print(json.dumps(report, indent=2))
return report
def main():
if len(sys.argv) < 2:
print("Usage: agent.py <target_url> [path1,path2,...]")
sys.exit(1)
target_url = sys.argv[1]
paths = sys.argv[2].split(",") if len(sys.argv) > 2 else ["/"]
agent = SecurityHeadersAgent(target_url)
agent.run_audit(paths)
if __name__ == "__main__":
main()