HTTP Security Headers: The First Line of Defense Against Web Attacks
A practical Fusebox guide to http security headers.
HTTP Security Headers: The First Line of Defense Against Web Attacks
Published: January 2024
Reading time: 10 minutes
Security headers are your website's armor. They prevent XSS, clickjacking, MIME sniffing, and dozens of other attacks. Yet most sites are missing critical headers. Here's how to analyze, implement, and test every security header that matters.
Why Security Headers Matter
The Reality Check
- 77% of websites lack basic security headers
- XSS attacks affect 1 in 3 websites
- Clickjacking used in 70% of phishing attacks
- MIME confusion leads to code execution
- One header can prevent entire attack classes
Real-World Breaches
British Airways (2018): Missing CSP, 380,000 cards stolen
Equifax (2017): No security headers, 147 million affected
Yahoo (2014): Weak headers, 3 billion accounts breached
eBay (2014): XSS via missing headers, forced password reset
TikTok (2020): Clickjacking via missing X-Frame-Options
Quick Security Header Check
1. Current Page Security Analysis
// Analyze security headers on current page
(function checkSecurityHeaders() {
console.log('๐ก๏ธ Security Headers Analysis\n');
// Headers we can check via JavaScript
const checkableHeaders = {
'Strict-Transport-Security': {
check: () => location.protocol === 'https:',
required: true,
description: 'Forces HTTPS connections'
},
'Content-Security-Policy': {
check: () => {
// Check meta tag as fallback
const csp = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
return csp !== null;
},
required: true,
description: 'Prevents XSS and injection attacks'
}
};
// Check what we can from JavaScript
Object.entries(checkableHeaders).forEach(([header, config]) => {
const present = config.check();
console.log(`${present ? 'โ
' : 'โ'} ${header}`);
if (!present && config.required) {
console.log(` โ ๏ธ ${config.description}`);
}
});
// Headers that need server response checking
console.log('\n๐ Headers requiring server check:');
const serverHeaders = [
'X-Content-Type-Options',
'X-Frame-Options',
'X-XSS-Protection',
'Referrer-Policy',
'Permissions-Policy',
'Cross-Origin-Embedder-Policy',
'Cross-Origin-Opener-Policy',
'Cross-Origin-Resource-Policy'
];
serverHeaders.forEach(header => {
console.log(`โข ${header}`);
});
// Make a fetch to check headers
console.log('\n๐ Checking current page headers...\n');
fetch(location.href, { method: 'HEAD' })
.then(response => {
const securityHeaders = {
'strict-transport-security': response.headers.get('strict-transport-security'),
'content-security-policy': response.headers.get('content-security-policy'),
'x-content-type-options': response.headers.get('x-content-type-options'),
'x-frame-options': response.headers.get('x-frame-options'),
'x-xss-protection': response.headers.get('x-xss-protection'),
'referrer-policy': response.headers.get('referrer-policy'),
'permissions-policy': response.headers.get('permissions-policy')
};
let score = 0;
let total = 0;
Object.entries(securityHeaders).forEach(([header, value]) => {
total++;
if (value) {
score++;
console.log(`โ
${header}: ${value.substring(0, 50)}${value.length > 50 ? '...' : ''}`);
} else {
console.log(`โ ${header}: Not set`);
}
});
const percentage = Math.round((score / total) * 100);
console.log(`\n๐ Security Score: ${score}/${total} (${percentage}%)`);
if (percentage < 30) {
console.log('๐ด Critical: Major security headers missing!');
} else if (percentage < 60) {
console.log('๐ก Warning: Important headers missing');
} else if (percentage < 80) {
console.log('๐ข Good: Most headers present');
} else {
console.log('โ
Excellent: Strong security headers');
}
})
.catch(err => {
console.log('โ ๏ธ Could not fetch headers (CORS restriction)');
console.log('Run this check on your own domain for full results');
});
})();
2. Security Header Impact Visualization
// Visualize what each header protects against
function visualizeHeaderProtection() {
console.log('\n๐ก๏ธ Security Headers Protection Matrix\n');
const protectionMatrix = {
'Content-Security-Policy (CSP)': {
protects: ['XSS', 'Code Injection', 'Clickjacking', 'Data Theft'],
attacks: 'Blocks inline scripts, eval(), unsafe sources',
priority: 'CRITICAL'
},
'Strict-Transport-Security (HSTS)': {
protects: ['Protocol Downgrade', 'Cookie Hijacking', 'MITM'],
attacks: 'Forces HTTPS, prevents HTTP access',
priority: 'CRITICAL'
},
'X-Frame-Options': {
protects: ['Clickjacking', 'UI Redressing'],
attacks: 'Prevents site from being framed',
priority: 'HIGH'
},
'X-Content-Type-Options': {
protects: ['MIME Sniffing', 'Drive-by Downloads'],
attacks: 'Prevents browser from guessing content type',
priority: 'HIGH'
},
'Referrer-Policy': {
protects: ['Information Leakage', 'Privacy'],
attacks: 'Controls what data is sent to external sites',
priority: 'MEDIUM'
},
'Permissions-Policy': {
protects: ['Feature Abuse', 'Privacy Violations'],
attacks: 'Controls access to browser APIs',
priority: 'MEDIUM'
}
};
Object.entries(protectionMatrix).forEach(([header, details]) => {
const priorityIcon = details.priority === 'CRITICAL' ? '๐ด' :
details.priority === 'HIGH' ? '๐ก' : '๐ข';
console.log(`${priorityIcon} ${header}`);
console.log(` Protects: ${details.protects.join(', ')}`);
console.log(` How: ${details.attacks}`);
console.log('');
});
}
visualizeHeaderProtection();
Essential Security Headers
1. Content Security Policy (CSP)
// CSP Builder and Analyzer
function buildCSP(options = {}) {
console.log('\n๐ Content Security Policy Builder\n');
// Default secure CSP
const directives = {
'default-src': ["'self'"],
'script-src': ["'self'"],
'style-src': ["'self'", "'unsafe-inline'"], // unsafe-inline often needed for CSS
'img-src': ["'self'", 'data:', 'https:'],
'font-src': ["'self'"],
'connect-src': ["'self'"],
'media-src': ["'self'"],
'object-src': ["'none'"],
'frame-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
'frame-ancestors': ["'none'"],
'upgrade-insecure-requests': []
};
// Apply custom options
if (options.allowGoogle) {
directives['script-src'].push('https://www.google-analytics.com');
directives['img-src'].push('https://www.google-analytics.com');
}
if (options.allowYouTube) {
directives['frame-src'] = ['https://www.youtube.com'];
}
if (options.allowCDN && options.cdnDomain) {
directives['script-src'].push(options.cdnDomain);
directives['style-src'].push(options.cdnDomain);
}
// Build CSP string
const cspString = Object.entries(directives)
.filter(([_, values]) => values.length > 0)
.map(([directive, values]) => {
if (values.length === 0) return directive;
return `${directive} ${values.join(' ')}`;
})
.join('; ');
console.log('Generated CSP:');
console.log(cspString);
// Test CSP impact
console.log('\n๐งช Testing CSP Impact...\n');
const tests = [
{
name: 'Inline Script',
code: '<script>alert("XSS")</script>',
blocked: !directives['script-src'].includes("'unsafe-inline'")
},
{
name: 'External Script',
code: '<script src="https://evil.com/malware.js"></script>',
blocked: !directives['script-src'].includes('https:')
},
{
name: 'Inline Style',
code: '<style>body { display: none; }</style>',
blocked: !directives['style-src'].includes("'unsafe-inline'")
},
{
name: 'Object/Embed',
code: '<object data="malware.swf"></object>',
blocked: directives['object-src'].includes("'none'")
}
];
tests.forEach(test => {
console.log(`${test.blocked ? 'โ
Blocked' : 'โ Allowed'}: ${test.name}`);
console.log(` Example: ${test.code}`);
});
// Implementation guide
console.log('\n๐ Implementation Steps:');
console.log('1. Start in Report-Only mode:');
console.log(' Content-Security-Policy-Report-Only: ' + cspString);
console.log('\n2. Monitor violations for 1-2 weeks');
console.log('\n3. Adjust policy based on legitimate violations');
console.log('\n4. Deploy enforcing mode:');
console.log(' Content-Security-Policy: ' + cspString);
return cspString;
}
// Generate CSP with common options
buildCSP({
allowGoogle: true,
allowYouTube: false,
allowCDN: true,
cdnDomain: 'https://cdn.example.com'
});
2. HSTS (HTTP Strict Transport Security)
// HSTS Configuration Analyzer
function analyzeHSTS() {
console.log('\n๐ HSTS Configuration Guide\n');
const hstsConfigs = {
'Development (Don\'t use)': {
header: 'max-age=0',
description: 'Disables HSTS - NEVER use in production'
},
'Testing (Short duration)': {
header: 'max-age=300',
description: '5 minutes - For initial testing only'
},
'Staging (1 day)': {
header: 'max-age=86400',
description: '1 day - Test before production'
},
'Production (6 months)': {
header: 'max-age=15552000',
description: '6 months - Minimum recommended'
},
'Production + Subdomains': {
header: 'max-age=31536000; includeSubDomains',
description: '1 year + all subdomains'
},
'Maximum Security': {
header: 'max-age=63072000; includeSubDomains; preload',
description: '2 years + subdomains + preload list'
}
};
console.log('HSTS Configuration Levels:\n');
Object.entries(hstsConfigs).forEach(([level, config]) => {
console.log(`๐ ${level}`);
console.log(` Header: ${config.header}`);
console.log(` ${config.description}\n`);
});
// HSTS Preload Checklist
console.log('โ
HSTS Preload Requirements:');
const preloadChecklist = [
'Serve valid certificate',
'Redirect HTTP to HTTPS',
'Serve all subdomains over HTTPS',
'max-age >= 31536000 (1 year)',
'includeSubDomains directive',
'preload directive',
'Submit to hstspreload.org'
];
preloadChecklist.forEach((requirement, index) => {
console.log(`${index + 1}. ${requirement}`);
});
// Common mistakes
console.log('\nโ ๏ธ Common HSTS Mistakes:');
const mistakes = [
{
mistake: 'Setting max-age too high initially',
impact: 'Can lock out users if SSL fails',
fix: 'Start with short duration, increase gradually'
},
{
mistake: 'includeSubDomains without testing',
impact: 'Breaks non-HTTPS subdomains',
fix: 'Audit all subdomains first'
},
{
mistake: 'Using preload without understanding',
impact: 'Very difficult to remove from list',
fix: 'Only use when 100% committed to HTTPS'
}
];
mistakes.forEach(m => {
console.log(`\nโ ${m.mistake}`);
console.log(` Impact: ${m.impact}`);
console.log(` Fix: ${m.fix}`);
});
}
analyzeHSTS();
3. Security Headers for Specific Attacks
// Configure headers for specific attack prevention
function configureAttackPrevention() {
console.log('\nโ๏ธ Attack-Specific Header Configuration\n');
const attackScenarios = {
'Clickjacking Attack': {
headers: {
'X-Frame-Options': 'DENY',
'Content-Security-Policy': "frame-ancestors 'none'"
},
explanation: 'Prevents your site from being embedded in iframes',
realWorld: 'Facebook Like button clickjacking (2010)'
},
'XSS Attack': {
headers: {
'Content-Security-Policy': "default-src 'self'; script-src 'self'",
'X-XSS-Protection': '1; mode=block',
'X-Content-Type-Options': 'nosniff'
},
explanation: 'Blocks inline scripts and unsafe sources',
realWorld: 'MySpace Samy worm (2005)'
},
'MIME Type Confusion': {
headers: {
'X-Content-Type-Options': 'nosniff',
'Content-Type': 'text/html; charset=utf-8'
},
explanation: 'Prevents browser from misinterpreting files',
realWorld: 'IE MIME sniffing vulnerabilities'
},
'Protocol Downgrade': {
headers: {
'Strict-Transport-Security': 'max-age=31536000',
'Content-Security-Policy': 'upgrade-insecure-requests'
},
explanation: 'Forces HTTPS and upgrades HTTP resources',
realWorld: 'NSA QUANTUM attacks'
},
'Information Leakage': {
headers: {
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), camera=(), microphone=()'
},
explanation: 'Controls data sent to third parties',
realWorld: 'Referrer token leaks'
}
};
Object.entries(attackScenarios).forEach(([attack, config]) => {
console.log(`๐ฏ ${attack}`);
console.log(` Real Example: ${config.realWorld}`);
console.log(` Prevention: ${config.explanation}`);
console.log(' Headers:');
Object.entries(config.headers).forEach(([header, value]) => {
console.log(` ${header}: ${value}`);
});
console.log('');
});
}
configureAttackPrevention();
Advanced Security Headers
1. Permissions Policy (Feature Policy)
// Configure Permissions Policy for privacy and security
function configurePermissionsPolicy() {
console.log('\n๐ฆ Permissions Policy Configuration\n');
// Define feature permissions
const features = {
// Dangerous features - usually deny
dangerous: {
'camera': '()',
'microphone': '()',
'geolocation': '()',
'payment': '()',
'usb': '()',
'bluetooth': '()',
'accelerometer': '()',
'gyroscope': '()',
'magnetometer': '()'
},
// Conditional features - allow for self only
conditional: {
'fullscreen': '(self)',
'picture-in-picture': '(self)',
'sync-xhr': '(self)',
'autoplay': '(self)'
},
// Third-party features - be selective
thirdParty: {
'cross-origin-isolated': '()',
'document-domain': '()',
'encrypted-media': '(self)',
'screen-wake-lock': '(self)'
}
};
// Build policy string
const policies = [];
Object.entries(features).forEach(([category, perms]) => {
Object.entries(perms).forEach(([feature, value]) => {
policies.push(`${feature}=${value}`);
});
});
const policyString = policies.join(', ');
console.log('Generated Permissions-Policy:');
console.log(policyString);
// Show impact of each category
console.log('\n๐ Feature Categories:\n');
console.log('๐ด Dangerous Features (Blocked):');
Object.keys(features.dangerous).forEach(feature => {
console.log(` โข ${feature} - Prevents unauthorized access`);
});
console.log('\n๐ก Conditional Features (Self only):');
Object.keys(features.conditional).forEach(feature => {
console.log(` โข ${feature} - Available for your domain only`);
});
console.log('\n๐ข Third-party Features (Restricted):');
Object.keys(features.thirdParty).forEach(feature => {
console.log(` โข ${feature} - Limited to prevent abuse`);
});
// Test current page
console.log('\n๐งช Testing Current Page Permissions:\n');
const testFeatures = ['geolocation', 'camera', 'microphone'];
testFeatures.forEach(feature => {
if (feature in navigator) {
console.log(`${feature}: Available (โ ๏ธ Consider restricting)`);
} else {
console.log(`${feature}: Not available (โ
)`);
}
});
return policyString;
}
configurePermissionsPolicy();
2. CORS and Cross-Origin Headers
// Configure Cross-Origin security headers
function configureCrossOriginSecurity() {
console.log('\n๐ Cross-Origin Security Configuration\n');
const crossOriginHeaders = {
'Cross-Origin-Opener-Policy (COOP)': {
values: {
'unsafe-none': 'Default - No isolation',
'same-origin-allow-popups': 'Allows popups to third-party',
'same-origin': 'Full isolation - Most secure'
},
recommendation: 'same-origin',
use: 'Prevents Spectre attacks via window.opener'
},
'Cross-Origin-Embedder-Policy (COEP)': {
values: {
'unsafe-none': 'Default - No restrictions',
'require-corp': 'All resources must have CORS/CORP'
},
recommendation: 'require-corp',
use: 'Enables SharedArrayBuffer and high-precision timers'
},
'Cross-Origin-Resource-Policy (CORP)': {
values: {
'same-site': 'Only same-site can embed',
'same-origin': 'Only same-origin can embed',
'cross-origin': 'Anyone can embed'
},
recommendation: 'same-origin',
use: 'Controls who can embed your resources'
}
};
console.log('Cross-Origin Headers Explained:\n');
Object.entries(crossOriginHeaders).forEach(([header, config]) => {
console.log(`๐ ${header}`);
console.log(` Purpose: ${config.use}`);
console.log(` Recommended: ${config.recommendation}`);
console.log(' Options:');
Object.entries(config.values).forEach(([value, desc]) => {
const icon = value === config.recommendation ? 'โ
' : ' ';
console.log(` ${icon} ${value}: ${desc}`);
});
console.log('');
});
// Site Isolation Configuration
console.log('๐ Achieving Site Isolation:\n');
console.log('Add these headers for maximum isolation:');
console.log('Cross-Origin-Opener-Policy: same-origin');
console.log('Cross-Origin-Embedder-Policy: require-corp');
console.log('\nBenefits:');
console.log('โข Enables SharedArrayBuffer');
console.log('โข Prevents Spectre attacks');
console.log('โข Isolates your origin\'s process');
console.log('โข Required for some modern APIs');
}
configureCrossOriginSecurity();
Security Header Testing
1. Automated Security Header Validator
// Comprehensive security header validation
function validateSecurityHeaders() {
console.log('\nโ
Security Header Validator\n');
// Make test request
fetch(window.location.href, { method: 'HEAD' })
.then(response => {
const results = {
score: 0,
total: 0,
missing: [],
warnings: [],
good: []
};
// Define header requirements
const requirements = {
'strict-transport-security': {
required: true,
validate: (value) => {
if (!value) return { valid: false, message: 'HSTS not set' };
const maxAge = value.match(/max-age=(\d+)/);
if (!maxAge) return { valid: false, message: 'No max-age' };
const seconds = parseInt(maxAge[1]);
if (seconds < 15552000) {
return { valid: 'warning', message: `max-age only ${seconds}s (6 months recommended)` };
}
return { valid: true, message: 'HSTS properly configured' };
}
},
'content-security-policy': {
required: true,
validate: (value) => {
if (!value) return { valid: false, message: 'No CSP' };
if (value.includes('unsafe-inline') && value.includes('unsafe-eval')) {
return { valid: 'warning', message: 'CSP too permissive (unsafe-inline and unsafe-eval)' };
}
return { valid: true, message: 'CSP configured' };
}
},
'x-frame-options': {
required: true,
validate: (value) => {
if (!value) return { valid: false, message: 'Clickjacking protection missing' };
if (!['DENY', 'SAMEORIGIN'].includes(value)) {
return { valid: 'warning', message: 'X-Frame-Options should be DENY or SAMEORIGIN' };
}
return { valid: true, message: 'Clickjacking protection enabled' };
}
},
'x-content-type-options': {
required: true,
validate: (value) => {
if (value !== 'nosniff') return { valid: false, message: 'MIME sniffing not prevented' };
return { valid: true, message: 'MIME sniffing prevented' };
}
},
'referrer-policy': {
required: false,
validate: (value) => {
if (!value) return { valid: 'warning', message: 'No referrer policy' };
const secure = ['strict-origin', 'strict-origin-when-cross-origin', 'no-referrer'];
if (!secure.includes(value)) {
return { valid: 'warning', message: 'Consider stricter referrer policy' };
}
return { valid: true, message: 'Referrer policy configured' };
}
},
'permissions-policy': {
required: false,
validate: (value) => {
if (!value) return { valid: 'warning', message: 'No permissions policy' };
return { valid: true, message: 'Permissions restricted' };
}
}
};
// Check each header
console.log('๐ Checking headers...\n');
Object.entries(requirements).forEach(([header, config]) => {
results.total++;
const value = response.headers.get(header);
const validation = config.validate(value);
if (validation.valid === true) {
results.score++;
results.good.push(`โ
${header}: ${validation.message}`);
} else if (validation.valid === 'warning') {
results.score += 0.5;
results.warnings.push(`โ ๏ธ ${header}: ${validation.message}`);
} else {
if (config.required) {
results.missing.push(`โ ${header}: ${validation.message}`);
} else {
results.warnings.push(`โ ๏ธ ${header}: ${validation.message}`);
}
}
});
// Display results
if (results.missing.length > 0) {
console.log('โ Missing Required Headers:');
results.missing.forEach(m => console.log(` ${m}`));
console.log('');
}
if (results.warnings.length > 0) {
console.log('โ ๏ธ Warnings:');
results.warnings.forEach(w => console.log(` ${w}`));
console.log('');
}
if (results.good.length > 0) {
console.log('โ
Properly Configured:');
results.good.forEach(g => console.log(` ${g}`));
console.log('');
}
// Calculate grade
const percentage = (results.score / results.total) * 100;
let grade = 'F';
if (percentage >= 90) grade = 'A';
else if (percentage >= 80) grade = 'B';
else if (percentage >= 70) grade = 'C';
else if (percentage >= 60) grade = 'D';
console.log(`๐ Security Grade: ${grade} (${percentage.toFixed(0)}%)`);
// Recommendations
console.log('\n๐ก Quick Fixes:');
if (results.missing.length > 0) {
console.log('1. Add missing security headers immediately');
console.log('2. Start with restrictive values, loosen if needed');
console.log('3. Test in staging before production');
}
})
.catch(() => {
console.log('โ ๏ธ Cannot check headers due to CORS');
console.log('Run this on your own domain or use curl:');
console.log('\ncurl -I https://example.com');
});
}
validateSecurityHeaders();
2. Header Implementation Snippets
// Generate implementation code for different platforms
function generateImplementationCode() {
console.log('\n๐ Security Headers Implementation\n');
const implementations = {
'Apache (.htaccess)': `
# Security Headers for Apache
Header always set X-Frame-Options "DENY"
Header always set X-Content-Type-Options "nosniff"
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"
# HSTS (only on HTTPS)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" "expr=%{HTTPS} == 'on'"
# CSP
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;"`,
'Nginx': `
# Security Headers for Nginx
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
# HSTS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# CSP
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;" always;`,
'Express.js': `
// Security Headers for Express.js
const helmet = require('helmet');
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
}
}));
// Additional custom headers
app.use((req, res, next) => {
res.setHeader('Permissions-Policy', 'geolocation=(), microphone=(), camera=()');
res.setHeader('X-XSS-Protection', '1; mode=block');
next();
});`,
'Next.js': `
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: [
{
key: 'X-Frame-Options',
value: 'DENY'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'X-XSS-Protection',
value: '1; mode=block'
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin'
},
{
key: 'Permissions-Policy',
value: 'geolocation=(), microphone=(), camera=()'
},
{
key: 'Strict-Transport-Security',
value: 'max-age=31536000; includeSubDomains'
},
{
key: 'Content-Security-Policy',
value: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';"
}
]
}
]
}
}`,
'Cloudflare Workers': `
// Cloudflare Workers security headers
addEventListener('fetch', event => {
event.respondWith(addSecurityHeaders(event.request))
})
async function addSecurityHeaders(request) {
const response = await fetch(request)
const newHeaders = new Headers(response.headers)
// Add security headers
newHeaders.set('X-Frame-Options', 'DENY')
newHeaders.set('X-Content-Type-Options', 'nosniff')
newHeaders.set('X-XSS-Protection', '1; mode=block')
newHeaders.set('Referrer-Policy', 'strict-origin-when-cross-origin')
newHeaders.set('Permissions-Policy', 'geolocation=(), microphone=(), camera=()')
newHeaders.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
newHeaders.set('Content-Security-Policy', "default-src 'self';")
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
})
}`
};
Object.entries(implementations).forEach(([platform, code]) => {
console.log(`๐ฆ ${platform}`);
console.log('โ'.repeat(50));
console.log(code);
console.log('\n');
});
console.log('๐ก Implementation Tips:');
console.log('โข Start with CSP in report-only mode');
console.log('โข Test HSTS with short max-age first');
console.log('โข Monitor for broken functionality');
console.log('โข Use security header testing tools');
console.log('โข Document your security policy');
}
generateImplementationCode();
Complete Security Header Audit
Comprehensive Security Analysis
// Run complete security header audit
async function completeSecurityAudit() {
console.log('๐ก๏ธ COMPLETE SECURITY HEADER AUDIT');
console.log('โ'.repeat(50));
console.log(`URL: ${window.location.href}`);
console.log(`Date: ${new Date().toLocaleDateString()}\n`);
const audit = {
headers: {},
score: 0,
vulnerabilities: [],
recommendations: []
};
try {
const response = await fetch(window.location.href, { method: 'HEAD' });
// Check all security headers
const securityHeaders = [
'content-security-policy',
'strict-transport-security',
'x-frame-options',
'x-content-type-options',
'x-xss-protection',
'referrer-policy',
'permissions-policy',
'cross-origin-opener-policy',
'cross-origin-embedder-policy',
'cross-origin-resource-policy'
];
securityHeaders.forEach(header => {
audit.headers[header] = response.headers.get(header) || null;
});
// Phase 1: Header Analysis
console.log('๐ PHASE 1: HEADER ANALYSIS');
console.log('โ'.repeat(40));
Object.entries(audit.headers).forEach(([header, value]) => {
if (value) {
console.log(`โ
${header}: ${value.substring(0, 50)}${value.length > 50 ? '...' : ''}`);
audit.score += 10;
} else {
console.log(`โ ${header}: Not set`);
audit.vulnerabilities.push(`Missing ${header}`);
}
});
// Phase 2: Configuration Quality
console.log('\n๐ PHASE 2: CONFIGURATION QUALITY');
console.log('โ'.repeat(40));
// Check CSP quality
if (audit.headers['content-security-policy']) {
const csp = audit.headers['content-security-policy'];
if (csp.includes('unsafe-inline')) {
console.log('โ ๏ธ CSP allows unsafe-inline scripts');
audit.vulnerabilities.push('Weak CSP: unsafe-inline');
}
if (csp.includes('unsafe-eval')) {
console.log('โ ๏ธ CSP allows unsafe-eval');
audit.vulnerabilities.push('Weak CSP: unsafe-eval');
}
if (!csp.includes('default-src')) {
console.log('โ ๏ธ CSP missing default-src');
audit.recommendations.push('Add default-src to CSP');
}
}
// Check HSTS
if (audit.headers['strict-transport-security']) {
const hsts = audit.headers['strict-transport-security'];
const maxAge = hsts.match(/max-age=(\d+)/);
if (maxAge && parseInt(maxAge[1]) < 15552000) {
console.log('โ ๏ธ HSTS max-age less than 6 months');
audit.recommendations.push('Increase HSTS max-age to at least 6 months');
}
}
// Phase 3: Attack Surface
console.log('\nโ๏ธ PHASE 3: ATTACK SURFACE ANALYSIS');
console.log('โ'.repeat(40));
const attacks = {
'XSS': !audit.headers['content-security-policy'],
'Clickjacking': !audit.headers['x-frame-options'],
'MIME Sniffing': !audit.headers['x-content-type-options'],
'Protocol Downgrade': !audit.headers['strict-transport-security'],
'Information Leakage': !audit.headers['referrer-policy']
};
Object.entries(attacks).forEach(([attack, vulnerable]) => {
console.log(`${vulnerable ? '๐ด Vulnerable' : '๐ข Protected'}: ${attack}`);
if (vulnerable) {
audit.vulnerabilities.push(`Vulnerable to ${attack}`);
}
});
// Phase 4: Recommendations
console.log('\n๐ก PHASE 4: RECOMMENDATIONS');
console.log('โ'.repeat(40));
// Priority recommendations
const priorities = {
'CRITICAL': audit.vulnerabilities.filter(v =>
v.includes('Missing content-security-policy') ||
v.includes('Missing strict-transport-security')
),
'HIGH': audit.vulnerabilities.filter(v =>
v.includes('x-frame-options') ||
v.includes('x-content-type-options')
),
'MEDIUM': audit.recommendations
};
Object.entries(priorities).forEach(([priority, items]) => {
if (items.length > 0) {
console.log(`\n${priority} Priority:`);
items.forEach(item => console.log(` โข ${item}`));
}
});
// Final Score
const finalScore = Math.min(100, audit.score);
const grade = finalScore >= 90 ? 'A' :
finalScore >= 80 ? 'B' :
finalScore >= 70 ? 'C' :
finalScore >= 60 ? 'D' : 'F';
console.log('\n๐ FINAL SCORE');
console.log('โ'.repeat(50));
console.log(`Grade: ${grade} (${finalScore}/100)`);
console.log(`Vulnerabilities: ${audit.vulnerabilities.length}`);
console.log(`Recommendations: ${audit.recommendations.length}`);
if (grade === 'A') {
console.log('\n๐ Excellent security headers!');
} else if (grade === 'F') {
console.log('\n๐จ Critical security issues - immediate action required!');
}
} catch (error) {
console.log('โ ๏ธ Could not complete audit (CORS restriction)');
console.log('Run this audit on your own domain for full results');
}
return audit;
}
// Run the complete audit
completeSecurityAudit();
The Bottom Line
Security headers are your first and best defense:
- One header can prevent entire attack categories
- CSP alone stops most XSS attacks
- HSTS eliminates protocol downgrade attacks
- Default browser behavior is insecure
- Implementation is simple but impact is huge
Start with the critical headers (CSP, HSTS, X-Frame-Options). Test in report-only mode. Monitor for issues. Then enforce. Your users' security depends on these headers.
Analyze security headers instantly: Fusebox checks all security headers, identifies vulnerabilities, and provides implementation guidance while you browse. Secure your sites properly. $29 one-time purchase.