security-documentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSecurity Documentation
安全文档
Overview
概述
Create comprehensive security documentation including policies, guidelines, compliance requirements, and best practices for secure application development and operations.
创建全面的安全文档,包括策略、指南、合规要求以及安全应用开发与运维的最佳实践。
When to Use
适用场景
- Security policies
- Compliance documentation (SOC 2, GDPR, HIPAA)
- Security guidelines and best practices
- Incident response plans
- Access control policies
- Data protection policies
- Vulnerability disclosure policies
- Security audit reports
- 安全策略
- 合规文档(SOC 2、GDPR、HIPAA)
- 安全指南与最佳实践
- 事件响应计划
- 访问控制策略
- 数据保护策略
- 漏洞披露策略
- 安全审计报告
Security Policy Template
安全策略模板
markdown
undefinedmarkdown
undefinedSecurity Policy
安全策略
Version: 2.0
Last Updated: 2025-01-15
Review Schedule: Quarterly
Owner: Security Team
Contact: security@example.com
版本: 2.0
最后更新日期: 2025-01-15
审核周期: 每季度
负责人: 安全团队
联系方式: security@example.com
Table of Contents
目录
1. Overview
1. 概述
Purpose
目的
This security policy defines the security standards, practices, and procedures to protect [Company Name]'s information assets, customer data, and infrastructure.
本安全策略定义了保护[公司名称]信息资产、客户数据和基础设施的安全标准、实践与流程。
Objectives
目标
- Protect confidentiality, integrity, and availability of data
- Comply with regulatory requirements (GDPR, SOC 2, etc.)
- Minimize security risks and vulnerabilities
- Establish clear security responsibilities
- Define incident response procedures
- 保护数据的保密性、完整性和可用性
- 符合监管要求(GDPR、SOC 2等)
- 最小化安全风险与漏洞
- 明确安全职责
- 定义事件响应流程
Scope
适用范围
This policy applies to:
- All employees, contractors, and third-party vendors
- All systems, applications, and infrastructure
- All customer and company data
- Both on-premise and cloud resources
本策略适用于:
- 所有员工、承包商和第三方供应商
- 所有系统、应用和基础设施
- 所有客户与公司数据
- 本地与云资源
2. Authentication & Access Control
2. 身份验证与访问控制
2.1 Password Requirements
2.1 密码要求
Minimum Requirements:
- Length: Minimum 12 characters
- Complexity: Mix of uppercase, lowercase, numbers, and symbols
- History: Cannot reuse last 5 passwords
- Expiration: 90 days (for privileged accounts)
- Lockout: 5 failed attempts triggers 30-minute lockout
Example Strong Password:
Good: MyC0mplex!Pass#2025
Bad: password123Implementation:
javascript
// Password validation
function validatePassword(password) {
const minLength = 12;
const requirements = {
length: password.length >= minLength,
uppercase: /[A-Z]/.test(password),
lowercase: /[a-z]/.test(password),
number: /[0-9]/.test(password),
special: /[!@#$%^&*(),.?":{}|<>]/.test(password)
};
return Object.values(requirements).every(Boolean);
}最低要求:
- 长度:至少12个字符
- 复杂度:混合大小写字母、数字和符号
- 历史记录:不能重复使用最近5个密码
- 有效期:特权账户90天
- 锁定:5次失败尝试触发30分钟锁定
强密码示例:
合格: MyC0mplex!Pass#2025
不合格: password123实现代码:
javascript
// Password validation
function validatePassword(password) {
const minLength = 12;
const requirements = {
length: password.length >= minLength,
uppercase: /[A-Z]/.test(password),
lowercase: /[a-z]/.test(password),
number: /[0-9]/.test(password),
special: /[!@#$%^&*(),.?":{}|<>]/.test(password)
};
return Object.values(requirements).every(Boolean);
}2.2 Multi-Factor Authentication (MFA)
2.2 多因素认证(MFA)
Requirements:
- Mandatory for:
- Production system access
- Administrative accounts
- Customer-facing applications
- VPN access
- Source code repositories
Supported Methods:
- TOTP (Google Authenticator, Authy)
- SMS (backup only, not primary)
- Hardware tokens (YubiKey)
- Biometric (fingerprint, Face ID)
Implementation:
javascript
// MFA verification
async function verifyMFA(userId, token) {
const user = await User.findById(userId);
const secret = user.twoFactorSecret;
// Verify TOTP token
const isValid = speakeasy.totp.verify({
secret,
encoding: 'base32',
token,
window: 2 // Allow 1 minute time drift
});
if (isValid) {
await logSecurityEvent('mfa_success', userId);
return true;
}
await logSecurityEvent('mfa_failure', userId);
return false;
}要求:
- 强制启用场景:
- 生产系统访问
- 管理员账户
- 面向客户的应用
- VPN访问
- 源代码仓库
支持的方式:
- TOTP(Google Authenticator、Authy)
- SMS(仅作为备用,非主要方式)
- 硬件令牌(YubiKey)
- 生物识别(指纹、Face ID)
实现代码:
javascript
// MFA verification
async function verifyMFA(userId, token) {
const user = await User.findById(userId);
const secret = user.twoFactorSecret;
// Verify TOTP token
const isValid = speakeasy.totp.verify({
secret,
encoding: 'base32',
token,
window: 2 // Allow 1 minute time drift
});
if (isValid) {
await logSecurityEvent('mfa_success', userId);
return true;
}
await logSecurityEvent('mfa_failure', userId);
return false;
}2.3 Role-Based Access Control (RBAC)
2.3 基于角色的访问控制(RBAC)
Principle of Least Privilege: Users receive minimum access needed for their role.
Roles:
| Role | Permissions | Access Level |
|---|---|---|
| Admin | Full system access | Read/Write/Delete All |
| Developer | Code, staging env | Read/Write Dev/Staging |
| Support | Customer data (limited) | Read customer data |
| Auditor | Logs, audit trails | Read-only all |
| User | Own data only | Read/Write own data |
Implementation:
javascript
// Permission middleware
const requirePermission = (permission) => {
return async (req, res, next) => {
const user = req.user;
const userPermissions = await getUserPermissions(user.role);
if (!userPermissions.includes(permission)) {
await logSecurityEvent('unauthorized_access', user.id, {
permission,
endpoint: req.path
});
return res.status(403).json({
error: 'Insufficient permissions',
required: permission
});
}
next();
};
};
// Usage
app.delete('/api/users/:id', requirePermission('users:delete'), deleteUser);最小权限原则: 用户仅获得其角色所需的最小访问权限。
角色定义:
| 角色 | 权限 | 访问级别 |
|---|---|---|
| 管理员 | 系统完全访问权限 | 全读写删除 |
| 开发人员 | 代码、预发布环境 | 开发/预发布环境读写 |
| 支持人员 | 受限客户数据 | 只读客户数据 |
| 审计人员 | 日志、审计轨迹 | 全只读 |
| 普通用户 | 仅自身数据 | 自身数据读写 |
实现代码:
javascript
// Permission middleware
const requirePermission = (permission) => {
return async (req, res, next) => {
const user = req.user;
const userPermissions = await getUserPermissions(user.role);
if (!userPermissions.includes(permission)) {
await logSecurityEvent('unauthorized_access', user.id, {
permission,
endpoint: req.path
});
return res.status(403).json({
error: 'Insufficient permissions',
required: permission
});
}
next();
};
};
// Usage
app.delete('/api/users/:id', requirePermission('users:delete'), deleteUser);3. Data Protection
3. 数据保护
3.1 Data Classification
3.1 数据分类
| Classification | Description | Examples | Protection |
|---|---|---|---|
| Public | Non-sensitive, publicly available | Marketing materials | None required |
| Internal | Internal use only | Company policies | Access control |
| Confidential | Sensitive business data | Financial reports | Encryption + MFA |
| Restricted | Highly sensitive | PII, passwords, keys | Encryption + strict access |
| 分类 | 描述 | 示例 | 保护措施 |
|---|---|---|---|
| 公开 | 非敏感,可公开获取 | 营销材料 | 无强制要求 |
| 内部 | 仅限内部使用 | 公司政策 | 访问控制 |
| 机密 | 敏感业务数据 | 财务报告 | 加密 + MFA |
| 受限 | 高度敏感 | 个人身份信息(PII)、密码、密钥 | 加密 + 严格访问控制 |
3.2 Encryption Standards
3.2 加密标准
Data at Rest:
- Algorithm: AES-256
- Key Management: AWS KMS / HashiCorp Vault
- Database: Transparent Data Encryption (TDE)
javascript
// Encrypt sensitive data before storage
const crypto = require('crypto');
function encryptData(plaintext, key) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
return {
encrypted,
iv: iv.toString('hex'),
authTag: authTag.toString('hex')
};
}Data in Transit:
- Protocol: TLS 1.3 (minimum TLS 1.2)
- Cipher Suites: Strong ciphers only
- Certificate: Valid SSL/TLS certificate
nginx
undefined静态数据:
- 算法: AES-256
- 密钥管理: AWS KMS / HashiCorp Vault
- 数据库: 透明数据加密(TDE)
javascript
// Encrypt sensitive data before storage
const crypto = require('crypto');
function encryptData(plaintext, key) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
return {
encrypted,
iv: iv.toString('hex'),
authTag: authTag.toString('hex')
};
}传输中数据:
- 协议: TLS 1.3(最低要求TLS 1.2)
- 密码套件: 仅使用强密码套件
- 证书: 有效的SSL/TLS证书
nginx
undefinedNginx TLS configuration
Nginx TLS configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
undefinedssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
undefined3.3 Data Retention
3.3 数据保留
| Data Type | Retention Period | Deletion Method |
|---|---|---|
| Customer data | Until account deletion + 30 days | Secure wipe |
| Access logs | 90 days | Automated deletion |
| Audit logs | 7 years | Archived, then deleted |
| Backups | 30 days | Overwrite + shred |
| 数据类型 | 保留周期 | 删除方式 |
|---|---|---|
| 客户数据 | 账户删除后再保留30天 | 安全擦除 |
| 访问日志 | 90天 | 自动删除 |
| 审计日志 | 7年 | 归档后删除 |
| 备份 | 30天 | 覆盖 + 粉碎 |
4. Application Security
4. 应用安全
4.1 Secure Coding Practices
4.1 安全编码实践
Input Validation:
javascript
// ✅ Good - Validate and sanitize input
const validator = require('validator');
function createUser(req, res) {
const { email, name } = req.body;
// Validate email
if (!validator.isEmail(email)) {
return res.status(400).json({ error: 'Invalid email' });
}
// Sanitize name
const sanitizedName = validator.escape(name);
// Use parameterized queries
db.query(
'INSERT INTO users (email, name) VALUES ($1, $2)',
[email, sanitizedName]
);
}
// ❌ Bad - SQL injection vulnerability
function createUserBad(req, res) {
const { email, name } = req.body;
db.query(`INSERT INTO users VALUES ('${email}', '${name}')`);
}XSS Prevention:
javascript
// Content Security Policy headers
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
);
next();
});
// Sanitize output
import DOMPurify from 'isomorphic-dompurify';
function renderComment(comment) {
const clean = DOMPurify.sanitize(comment, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong'],
ALLOWED_ATTR: []
});
return clean;
}输入验证:
javascript
// ✅ Good - Validate and sanitize input
const validator = require('validator');
function createUser(req, res) {
const { email, name } = req.body;
// Validate email
if (!validator.isEmail(email)) {
return res.status(400).json({ error: 'Invalid email' });
}
// Sanitize name
const sanitizedName = validator.escape(name);
// Use parameterized queries
db.query(
'INSERT INTO users (email, name) VALUES ($1, $2)',
[email, sanitizedName]
);
}
// ❌ Bad - SQL injection vulnerability
function createUserBad(req, res) {
const { email, name } = req.body;
db.query(`INSERT INTO users VALUES ('${email}', '${name}')`);
}XSS防护:
javascript
// Content Security Policy headers
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"
);
next();
});
// Sanitize output
import DOMPurify from 'isomorphic-dompurify';
function renderComment(comment) {
const clean = DOMPurify.sanitize(comment, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong'],
ALLOWED_ATTR: []
});
return clean;
}4.2 Security Headers
4.2 安全头部
javascript
// Security headers middleware
app.use((req, res, next) => {
// Prevent clickjacking
res.setHeader('X-Frame-Options', 'DENY');
// XSS protection
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-XSS-Protection', '1; mode=block');
// HTTPS enforcement
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
// Referrer policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});javascript
// Security headers middleware
app.use((req, res, next) => {
// Prevent clickjacking
res.setHeader('X-Frame-Options', 'DENY');
// XSS protection
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-XSS-Protection', '1; mode=block');
// HTTPS enforcement
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
// Referrer policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});4.3 API Security
4.3 API安全
Rate Limiting:
javascript
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP',
standardHeaders: true,
legacyHeaders: false
});
app.use('/api/', limiter);速率限制:
javascript
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP',
standardHeaders: true,
legacyHeaders: false
});
app.use('/api/', limiter);5. Infrastructure Security
5. 基础设施安全
5.1 Network Security
5.1 网络安全
Firewall Rules:
- Default deny all
- Allow only required ports
- Whitelist trusted IPs for admin access
bash
undefined防火墙规则:
- 默认拒绝所有流量
- 仅允许必要端口
- 管理员访问仅白名单可信IP
bash
undefinedExample iptables rules
Example iptables rules
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
Allow SSH from specific IP
Allow SSH from specific IP
iptables -A INPUT -p tcp -s 203.0.113.0/24 --dport 22 -j ACCEPT
iptables -A INPUT -p tcp -s 203.0.113.0/24 --dport 22 -j ACCEPT
Allow HTTP/HTTPS
Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
undefinediptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
undefined5.2 Server Hardening
5.2 服务器加固
Checklist:
- Disable root SSH login
- Use SSH keys, disable password auth
- Install security updates automatically
- Enable firewall (ufw/iptables)
- Configure fail2ban
- Disable unused services
- Enable audit logging
- Set up intrusion detection (AIDE, Tripwire)
检查清单:
- 禁用root用户SSH登录
- 使用SSH密钥,禁用密码认证
- 自动安装安全更新
- 启用防火墙(ufw/iptables)
- 配置fail2ban
- 禁用未使用的服务
- 启用审计日志
- 设置入侵检测(AIDE、Tripwire)
6. Incident Response
6. 事件响应
6.1 Security Incident Severity
6.1 安全事件严重等级
| Severity | Description | Response Time | Examples |
|---|---|---|---|
| Critical | Massive data breach, ransomware | Immediate | Database exposed, encryption compromised |
| High | Significant security compromise | < 1 hour | Admin account compromised, DDoS |
| Medium | Limited security issue | < 4 hours | XSS vulnerability, phishing attempt |
| Low | Minor security concern | < 24 hours | Weak password, outdated library |
| 等级 | 描述 | 响应时间 | 示例 |
|---|---|---|---|
| 关键 | 大规模数据泄露、勒索软件 | 立即响应 | 数据库暴露、加密被破解 |
| 高 | 严重安全入侵 | < 1小时 | 管理员账户被盗、DDoS攻击 |
| 中 | 有限安全问题 | < 4小时 | XSS漏洞、钓鱼尝试 |
| 低 | 轻微安全隐患 | < 24小时 | 弱密码、过时依赖库 |
6.2 Incident Response Plan
6.2 事件响应计划
Phase 1: Detection (0-15 minutes)
- Alert received via monitoring/user report
- Triage severity level
- Assemble incident response team
- Create incident ticket
Phase 2: Containment (15-60 minutes)
- Isolate affected systems
- Block malicious IPs/domains
- Revoke compromised credentials
- Enable additional monitoring
Phase 3: Investigation (1-4 hours)
- Analyze logs and forensics
- Identify attack vector
- Determine scope of breach
- Document findings
Phase 4: Eradication (4-24 hours)
- Remove malware/backdoors
- Patch vulnerabilities
- Update security controls
- Verify systems are clean
Phase 5: Recovery (24-48 hours)
- Restore from clean backups
- Gradually restore services
- Monitor for re-infection
- Update documentation
Phase 6: Post-Incident (1 week)
- Conduct post-mortem
- Update security policies
- Implement preventive measures
- Train team on lessons learned
阶段1:检测(0-15分钟)
- 收到监控/用户报告的警报
- 评估严重等级
- 组建事件响应团队
- 创建事件工单
阶段2:遏制(15-60分钟)
- 隔离受影响系统
- 阻止恶意IP/域名
- 吊销泄露的凭证
- 启用额外监控
阶段3:调查(1-4小时)
- 分析日志与取证
- 识别攻击向量
- 确定泄露范围
- 记录调查结果
阶段4:根除(4-24小时)
- 移除恶意软件/后门
- 修复漏洞
- 更新安全控制措施
- 验证系统已清理
阶段5:恢复(24-48小时)
- 从干净备份恢复
- 逐步恢复服务
- 监控是否再次感染
- 更新文档
阶段6:事后处理(1周内)
- 开展事后复盘
- 更新安全策略
- 实施预防措施
- 培训团队吸取经验教训
7. Compliance
7. 合规性
7.1 GDPR Compliance
7.1 GDPR合规
Requirements:
- Data processing records
- Privacy policy
- Cookie consent
- Data subject rights (access, deletion, portability)
- Data breach notification (72 hours)
- Data Protection Impact Assessment (DPIA)
要求:
- 数据处理记录
- 隐私政策
- Cookie同意机制
- 数据主体权利(访问、删除、可携带性)
- 数据泄露通知(72小时内)
- 数据保护影响评估(DPIA)
7.2 SOC 2 Compliance
7.2 SOC 2合规
Trust Services Criteria:
- Security: Protect against unauthorized access
- Availability: System is available as committed
- Processing Integrity: Processing is complete and accurate
- Confidentiality: Confidential information is protected
- Privacy: Personal information is properly handled
信任服务准则:
- 安全: 防止未授权访问
- 可用性: 系统按承诺可用
- 处理完整性: 处理过程完整准确
- 保密性: 机密信息受保护
- 隐私: 个人信息妥善处理
8. Vulnerability Disclosure
8. 漏洞披露
Reporting Security Issues
安全问题上报
Contact: security@example.com
PGP Key: [Link to public key]
Reward Program:
- Critical: $5,000 - $10,000
- High: $1,000 - $5,000
- Medium: $500 - $1,000
- Low: $100 - $500
Scope:
- ✅ In scope: Production systems, APIs, mobile apps
- ❌ Out of scope: Test environments, third-party services
联系方式: security@example.com
PGP密钥: [公钥链接]
奖励计划:
- 关键: $5,000 - $10,000
- 高: $1,000 - $5,000
- 中: $500 - $1,000
- 低: $100 - $500
范围:
- ✅ 纳入范围:生产系统、API、移动应用
- ❌ 排除范围:测试环境、第三方服务
9. Security Audit Log
9. 安全审计日志
All security events must be logged:
javascript
function logSecurityEvent(event, userId, metadata = {}) {
logger.security({
timestamp: new Date().toISOString(),
event,
userId,
ip: metadata.ip,
userAgent: metadata.userAgent,
resource: metadata.resource,
outcome: metadata.outcome
});
}
// Events to log:
// - login_success, login_failure
// - password_change
// - mfa_enabled, mfa_disabled
// - permission_change
// - data_export
// - admin_actionundefined所有安全事件必须记录:
javascript
function logSecurityEvent(event, userId, metadata = {}) {
logger.security({
timestamp: new Date().toISOString(),
event,
userId,
ip: metadata.ip,
userAgent: metadata.userAgent,
resource: metadata.resource,
outcome: metadata.outcome
});
}
// Events to log:
// - login_success, login_failure
// - password_change
// - mfa_enabled, mfa_disabled
// - permission_change
// - data_export
// - admin_actionBest Practices
最佳实践
✅ DO
✅ 建议
- Follow principle of least privilege
- Encrypt sensitive data
- Implement MFA everywhere
- Log security events
- Regular security audits
- Keep systems updated
- Document security policies
- Train employees regularly
- Have incident response plan
- Test backups regularly
- 遵循最小权限原则
- 加密敏感数据
- 全面实施MFA
- 记录安全事件
- 定期安全审计
- 保持系统更新
- 文档化安全策略
- 定期员工培训
- 制定事件响应计划
- 定期测试备份
❌ DON'T
❌ 禁止
- Store passwords in plaintext
- Skip input validation
- Ignore security headers
- Share credentials
- Hardcode secrets in code
- Skip security testing
- Ignore vulnerability reports
- 明文存储密码
- 跳过输入验证
- 忽略安全头部
- 共享凭证
- 代码中硬编码密钥
- 跳过安全测试
- 忽略漏洞报告