mcpField
S
security-hardening

security-hardening

github.com/rohitg00安全2.8k195 次安装24 周前更新
代码仓库

关于 security-hardening

security-hardening 是帮助开发者在部署前加固 Web 应用和 API 的实用技能,涵盖输入验证、注入防护、身份验证、密钥管理、依赖审计及部署检查清单。

主要功能

  1. 01输入验证与输出编码
  2. 02SQL 注入防护
  3. 03CSRF 与内容安全策略
  4. 04安全标头与速率限制
  5. 05JWT 与密钥管理实践
  6. 06依赖审计与部署检查清单

适用场景

  1. 01部署前审查 API
  2. 02降低注入与 XSS 风险
  3. 03设置身份验证和速率限制策略
  4. 04在 CI 中检查依赖与密钥

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/rohitg00/awesome-claude-code-toolkit --skill security-hardening

安装后在 Claude Code 中输入/security-hardening确认已加载。

详细介绍

安全加固

输入验证

在边界处验证所有输入。切勿只依赖客户端验证。

import { z } from 'zod';

const CreateUserSchema = z.object({
  email: z.string().email().max(255),
  name: z.string().min(1).max(100).regex(/^[a-zA-Z\s'-]+$/),
  age: z.number().int().min(13).max(150),
});

function createUser(req: Request) {
  const result = CreateUserSchema.safeParse(req.body);
  if (!result.success) {
    return { status: 400, errors: result.error.flatten().fieldErrors };
  }
  // result.data is typed and validated
}

规则:

  • 验证每项输入的类型、长度、格式和范围
  • 使用允许列表,而非拒绝列表(只接受已知的合法内容,拒绝其他所有内容)
  • 验证文件上传:检查 MIME 类型、文件扩展名和魔数
  • 在服务器/代理层限制请求正文大小(例如,最大为 1MB)

输出编码

// Prevent XSS: encode output based on context
// HTML context: use framework auto-escaping (React does this by default)
// Never use dangerouslySetInnerHTML with user input

// URL context: encode parameters
const safeUrl = `/search?q=${encodeURIComponent(userInput)}`;

// JSON context: use JSON.stringify (handles escaping)
const safeJson = JSON.stringify({ query: userInput });

切勿使用用户输入构造 HTML 字符串。使用启用了自动转义的模板引擎。

SQL 注入防护

# NEVER do this
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

# Always use parameterized queries
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
// NEVER do this
db.query(`SELECT * FROM users WHERE email = '${email}'`);

// Always use parameterized queries
db.query("SELECT * FROM users WHERE email = $1", [email]);

使用 ORM 或查询构建器。如果编写原始 SQL,始终使用参数化查询。

CSRF 防护

// Server: generate and validate CSRF tokens
import { randomBytes } from 'crypto';

function generateCsrfToken(): string {
  return randomBytes(32).toString('hex');
}

// Middleware: validate on state-changing requests
function csrfMiddleware(req, res, next) {
  if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
    const token = req.headers['x-csrf-token'] || req.body._csrf;
    if (!timingSafeEqual(token, req.session.csrfToken)) {
      return res.status(403).json({ error: 'Invalid CSRF token' });
    }
  }
  next();
}

对于使用基于令牌的身份验证(Bearer 令牌)的 API,无需防范 CSRF,因为浏览器不会自动发送该令牌。

内容安全策略

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-{random}';
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  font-src 'self';
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';

先采用严格策略,再按需放宽。对于内联脚本,使用 nonce,而非 unsafe-inline。使用 report-uri 指令报告违规情况。先通过 Content-Security-Policy-Report-Only 测试。

安全标头

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()

在每个响应中设置这些标头。使用 helmet(Node.js)或同等的中间件。

速率限制

// Per-user, per-endpoint rate limiting
const rateLimits = {
  'POST /auth/login':    { window: '15m', max: 5 },
  'POST /auth/register': { window: '1h',  max: 3 },
  'POST /api/*':         { window: '1m',  max: 60 },
  'GET /api/*':          { window: '1m',  max: 120 },
};

使用滑动窗口算法。在 Redis 中存储计数器。返回带有 Retry-After 标头的 429。对身份验证端点施加更严格的限制。

JWT 最佳实践

  • 访问令牌使用较短的有效期(15 分钟)
  • 使用存储在 httpOnly Cookie 中的刷新令牌(7-30 天)
  • 微服务使用 RS256(非对称),单体应用使用 HS256(对称)签名
  • 切勿在 JWT 载荷中存储敏感数据(载荷经过 Base64 编码,并未加密)
  • 每次请求都验证 iss、aud、exp 和 nbf 声明
  • 通过拒绝列表或较短的有效期与轮换机制实现令牌撤销
// Verify JWT with all checks
const payload = jwt.verify(token, publicKey, {
  algorithms: ['RS256'],
  issuer: 'auth.example.com',
  audience: 'api.example.com',
  clockTolerance: 30,
});

密钥管理

  • 切勿将密钥提交到版本控制中(使用 .gitignore 忽略 .env)
  • 使用环境变量存储运行时密钥
  • 在生产环境中使用密钥管理器(AWS Secrets Manager、HashiCorp Vault、Doppler)
  • 定期轮换密钥(API 密钥最长有效期为 90 天)
  • 为不同环境使用不同的密钥(dev/staging/prod)
  • 在 CI 中扫描泄露的密钥:trufflehog、gitleaks、git-secrets
# Check for secrets in git history
gitleaks detect --source . --verbose

# Pre-commit hook to prevent secret commits
gitleaks protect --staged

依赖项审计

# Node.js
npm audit --production
npx better-npm-audit audit --level=high

# Python
pip-audit
safety check

# Go
govulncheck ./...

在 CI 中对每个 PR 运行依赖项审计。发现严重/高危漏洞时阻止合并。固定依赖项版本。每周通过自动化 PR 更新依赖项(Dependabot、Renovate)。

部署前检查清单

  1. 使用架构验证所有输入
  2. SQL 查询使用参数化
  3. 已配置安全标头
  4. 已通过 HSTS 强制使用 HTTPS
  5. 密钥已移至代码之外
  6. 已审计依赖项,且不存在严重漏洞
  7. 所有公共端点均已启用速率限制
  8. 身份验证令牌会过期并轮换
  9. 错误消息不会泄露内部详情
  10. 日志记录安全事件,但不包含敏感数据

评论

支持 Markdown