harden

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Hardening

安全加固

Proactive security improvement suggestions. Unlike vulnerability scanners that find what is broken, this skill identifies what could be better -- defense-in-depth measures, missing security headers, insufficient input validation, absent rate limiting, and other hardening opportunities that reduce the blast radius of future vulnerabilities.
主动安全改进建议。与查找已存在漏洞的漏洞扫描器不同,此Skill识别可优化的方面——纵深防御措施、缺失的安全头、不足的输入验证、缺失的速率限制,以及其他可减少未来漏洞影响范围的加固机会。

Supported Flags

支持的标志

Read
../../shared/schemas/flags.md
for the full flag specification.
FlagHardening Behavior
--scope
Default
changed
. Use
full
for comprehensive hardening review.
--depth quick
Check for missing security headers and obvious hardening gaps only.
--depth standard
Full hardening review: headers, validation, logging, error handling, configuration.
--depth deep
Standard + analyze middleware chains, review all trust boundaries, check defense layering.
--depth expert
Deep + compare against security benchmarks (CIS, OWASP ASVS), generate hardening scorecard.
--severity
Filter suggestions by impact level.
--format
Default
text
. Use
md
for a hardening checklist document.
阅读
../../shared/schemas/flags.md
获取完整的标志规范。
标志加固行为
--scope
默认值为
changed
。使用
full
可进行全面的加固审查。
--depth quick
仅检查缺失的安全头和明显的加固缺口。
--depth standard
完整的加固审查:安全头、验证、日志记录、错误处理、配置。
--depth deep
标准审查 + 分析中间件链、检查所有信任边界、验证防御分层。
--depth expert
深度审查 + 对照安全基准(CIS、OWASP ASVS)进行比较,生成加固评分卡。
--severity
按影响级别过滤建议。
--format
默认值为
text
。使用
md
可生成加固检查清单文档。

Workflow

工作流程

Step 1: Identify Technology Stack

步骤1:识别技术栈

Scan the codebase to determine:
  1. Web framework(s): Express, Django, Flask, Spring, Rails, Next.js, ASP.NET, FastAPI, etc.
  2. Deployment target: Container, serverless, VM, PaaS (from Dockerfile, serverless.yml, etc.).
  3. Reverse proxy/CDN: Nginx, Apache, Cloudflare, AWS ALB (from config files).
  4. Database(s): SQL, NoSQL, cache layers.
  5. Authentication mechanism: Session, JWT, OAuth, SAML.
  6. Existing security middleware: Helmet, django-security, Spring Security, etc.
扫描代码库以确定:
  1. Web框架:Express、Django、Flask、Spring、Rails、Next.js、ASP.NET、FastAPI等。
  2. 部署目标:容器、无服务器、虚拟机、PaaS(从Dockerfile、serverless.yml等文件获取)。
  3. 反向代理/CDN:Nginx、Apache、Cloudflare、AWS ALB(从配置文件获取)。
  4. 数据库:SQL、NoSQL、缓存层。
  5. 认证机制:会话、JWT、OAuth、SAML。
  6. 现有安全中间件:Helmet、django-security、Spring Security等。

Step 2: Check Security Headers

步骤2:检查安全头

Verify the application sets these HTTP response headers (or that a reverse proxy / CDN handles them):
HeaderRecommended ValueImpact
Content-Security-Policy
Strict policy, no
unsafe-inline
/
unsafe-eval
Mitigates XSS
Strict-Transport-Security
max-age=31536000; includeSubDomains; preload
Enforces HTTPS
X-Content-Type-Options
nosniff
Prevents MIME sniffing
X-Frame-Options
DENY
or
SAMEORIGIN
Prevents clickjacking
Referrer-Policy
strict-origin-when-cross-origin
or stricter
Limits referrer leakage
Permissions-Policy
Disable unused browser featuresReduces attack surface
Cross-Origin-Opener-Policy
same-origin
Prevents cross-origin attacks
Cross-Origin-Resource-Policy
same-origin
Controls resource sharing
Cache-Control
no-store
for sensitive responses
Prevents cache leaks
Note: If a reverse proxy config (nginx.conf, etc.) is present and sets these headers, do not flag them as missing from application code.
验证应用是否设置了以下HTTP响应头(或反向代理/CDN是否已处理这些头):
头信息推荐值影响
Content-Security-Policy
严格策略,不使用
unsafe-inline
/
unsafe-eval
缓解XSS攻击
Strict-Transport-Security
max-age=31536000; includeSubDomains; preload
强制使用HTTPS
X-Content-Type-Options
nosniff
防止MIME类型嗅探
X-Frame-Options
DENY
SAMEORIGIN
防止点击劫持
Referrer-Policy
strict-origin-when-cross-origin
或更严格的策略
限制Referrer信息泄露
Permissions-Policy
禁用未使用的浏览器功能减少攻击面
Cross-Origin-Opener-Policy
same-origin
防止跨源攻击
Cross-Origin-Resource-Policy
same-origin
控制资源共享
Cache-Control
敏感响应使用
no-store
防止缓存泄露
注意:如果存在反向代理配置(如nginx.conf等)且已设置这些头,则不要将应用代码中缺失这些头标记为问题。

Step 3: Review CORS Configuration

步骤3:审查CORS配置

Check for overly permissive CORS settings:
  1. Access-Control-Allow-Origin: *
    on authenticated endpoints.
  2. Reflecting the
    Origin
    header without validation.
  3. Access-Control-Allow-Credentials: true
    with wildcard origins.
  4. Overly broad allowed methods or headers.
  5. Missing
    Vary: Origin
    when origin is dynamic.
检查是否存在过于宽松的CORS设置:
  1. 认证端点使用
    Access-Control-Allow-Origin: *
  2. 未经验证就反射
    Origin
    头。
  3. 通配符源与
    Access-Control-Allow-Credentials: true
    同时使用。
  4. 允许的方法或头过于宽泛。
  5. 当源为动态时缺少
    Vary: Origin

Step 4: Assess Input Validation

步骤4:评估输入验证

For each entry point discovered (or in scope):
  1. Schema validation: Are request bodies validated against a schema (Joi, Zod, Pydantic, JSON Schema)?
  2. Type coercion: Are string inputs properly typed before use?
  3. Length limits: Are string lengths bounded? Are array sizes limited?
  4. Allowlist vs denylist: Is validation positive (allowlist) rather than negative (denylist)?
  5. Nested input: Are deeply nested objects limited to prevent DoS?
  6. File validation: Are uploaded files validated beyond extension (magic bytes, size limits)?
针对每个发现的(或在范围内的)入口点:
  1. Schema验证:请求体是否针对Schema进行验证(如Joi、Zod、Pydantic、JSON Schema)?
  2. 类型转换:字符串输入在使用前是否正确转换类型?
  3. 长度限制:字符串长度是否有边界?数组大小是否有限制?
  4. 白名单 vs 黑名单:验证是否为正向(白名单)而非反向(黑名单)?
  5. 嵌套输入:深度嵌套对象是否有限制以防止DoS攻击?
  6. 文件验证:上传的文件是否除扩展名外还进行了验证(如魔术字节、大小限制)?

Step 5: Check Rate Limiting

步骤5:检查速率限制

Identify endpoints that should have rate limiting:
  1. Authentication endpoints: Login, registration, password reset, MFA verification.
  2. API endpoints: Especially those that are computationally expensive or return sensitive data.
  3. File upload endpoints: To prevent storage exhaustion.
  4. Search/query endpoints: To prevent enumeration and DoS.
Check if rate limiting is implemented and whether limits are reasonable.
识别应实施速率限制的端点:
  1. 认证端点:登录、注册、密码重置、MFA验证。
  2. API端点:尤其是计算密集型或返回敏感数据的端点。
  3. 文件上传端点:防止存储耗尽。
  4. 搜索/查询端点:防止枚举和DoS攻击。
检查是否已实施速率限制,以及限制是否合理。

Step 6: Review Error Handling and Information Disclosure

步骤6:审查错误处理和信息泄露

  1. Stack traces: Are stack traces exposed in production error responses?
  2. Verbose errors: Do error messages reveal internal paths, versions, or database details?
  3. Error differentiation: Do auth errors distinguish between "user not found" and "wrong password" (enables enumeration)?
  4. Default error pages: Are framework default error pages replaced?
  5. Debug mode: Is debug mode disabled in production configuration?
  1. 堆栈跟踪:生产环境的错误响应中是否暴露堆栈跟踪?
  2. 详细错误:错误消息是否泄露内部路径、版本或数据库细节?
  3. 错误区分:认证错误是否区分“用户不存在”和“密码错误”(这会导致枚举攻击)?
  4. 默认错误页面:是否替换了框架的默认错误页面?
  5. 调试模式:生产配置中是否禁用了调试模式?

Step 7: Assess Security Logging

步骤7:评估安全日志记录

Check that these security-relevant events are logged:
  1. Authentication events: Login success/failure, logout, password changes.
  2. Authorization failures: Access denied events with user and resource context.
  3. Input validation failures: Rejected requests with sanitized details.
  4. Administrative actions: Config changes, user management, privilege changes.
  5. Sensitive data access: Audit trail for PII/financial data reads.
Verify logs do NOT contain: passwords, tokens, credit card numbers, SSNs, or other sensitive data.
检查是否记录了以下安全相关事件:
  1. 认证事件:登录成功/失败、登出、密码修改。
  2. 授权失败:带有用户和资源上下文的访问拒绝事件。
  3. 输入验证失败:带有清理后细节的被拒绝请求。
  4. 管理操作:配置更改、用户管理、权限变更。
  5. 敏感数据访问:PII/财务数据读取的审计跟踪。
验证日志中不包含:密码、令牌、信用卡号、社保号或其他敏感数据。

Step 8: Check Defensive Coding Patterns

步骤8:检查防御性编码模式

  1. Fail-closed defaults: Do authorization checks default to deny?
  2. Secure defaults: Are new configurations secure by default?
  3. Least privilege: Do database connections, API keys, and service accounts use minimal permissions?
  4. Timeout configuration: Do HTTP clients, database connections, and external calls have timeouts?
  5. Resource limits: Are memory/CPU-intensive operations bounded?
  6. Dependency security: Is
    npm audit
    /
    pip audit
    / equivalent run in CI?
  1. 默认关闭:授权检查是否默认拒绝?
  2. 安全默认值:新配置是否默认安全?
  3. 最小权限:数据库连接、API密钥和服务账户是否使用最小权限?
  4. 超时配置:HTTP客户端、数据库连接和外部调用是否设置了超时?
  5. 资源限制:内存/CPU密集型操作是否有边界?
  6. 依赖安全:CI流程中是否运行
    npm audit
    /
    pip audit
    或等效工具?

Step 9: Report

步骤9:报告

Output hardening suggestions grouped by category.
按类别分组输出加固建议。

Output Format

输出格式

Hardening suggestions are advisory and use a lighter format than vulnerability findings.
undefined
加固建议为 advisory 性质,格式比漏洞发现更简洁。
undefined

Security Hardening Report

安全加固报告

Summary

摘要

  • Hardening suggestions: N
  • By priority: N HIGH, N MEDIUM, N LOW
  • Categories covered: headers, cors, validation, rate-limiting, logging, error-handling, config
  • 加固建议数量:N
  • 按优先级划分:N 高,N 中,N 低
  • 覆盖类别:安全头、CORS、验证、速率限制、日志记录、错误处理、配置

HIGH Priority

高优先级

[H-001] Missing Content-Security-Policy header

[H-001] 缺失Content-Security-Policy头

Category: Headers | Effort: Low Location: src/middleware/security.ts Current: No CSP header set Recommended: Add strict CSP via helmet
js
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'"],
    styleSrc: ["'self'", "'unsafe-inline'"],
    imgSrc: ["'self'", "data:"],
  }
}));
类别:安全头 | 实施难度:低 位置:src/middleware/security.ts 当前状态:未设置CSP头 建议:通过helmet添加严格的CSP
js
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'"],
    styleSrc: ["'self'", "'unsafe-inline'"],
    imgSrc: ["'self'", "data:"],
  }
}));

MEDIUM Priority

中优先级

...
...

LOW Priority

低优先级

...

When hardening gaps represent actual vulnerabilities (e.g., CORS misconfiguration allowing credential theft), emit a formal finding using `../../shared/schemas/findings.md`.

Finding ID prefix: **HARD** (e.g., `HARD-001`).

- `metadata.tool`: `"harden"`
- `references.cwe`: Varies by suggestion (e.g., `CWE-693` Protection Mechanism Failure, `CWE-16` Configuration)
...

当加固缺口代表实际漏洞时(例如,CORS配置错误导致凭证被盗),使用`../../shared/schemas/findings.md`生成正式的发现报告。

发现ID前缀:**HARD**(例如,`HARD-001`)。

- `metadata.tool`: `"harden"`
- `references.cwe`: 根据建议不同而变化(例如,`CWE-693` 保护机制失效,`CWE-16` 配置错误)

Pragmatism Notes

实用注意事项

  • Hardening is contextual. An internal admin tool has different requirements than a public API.
  • Do not recommend CSP for a CLI tool or rate limiting for a batch job.
  • If a CDN or reverse proxy handles headers, note that rather than flagging missing headers in app code.
  • Prioritize suggestions that are easy to implement with high security impact.
  • Acknowledge when existing security measures are already good. Not every review needs findings.
  • Some frameworks (Next.js, Rails) include secure defaults. Credit what is already done well.
  • 加固是上下文相关的。内部管理工具与公共API的要求不同。
  • 不要为CLI工具推荐CSP,也不要为批处理作业推荐速率限制。
  • 如果CDN或反向代理已处理安全头,则应注明这一点,而不是标记应用代码中缺失这些头。
  • 优先推荐易于实施且安全影响高的建议。
  • 当现有安全措施已经良好时,要予以认可。并非每次审查都需要发现问题。
  • 某些框架(如Next.js、Rails)包含安全默认值。要认可已做得好的部分。