mcpField
S
secrets-scanner

secrets-scanner

github.com/patricio0312rev安全63273 次安装41 周前更新
代码仓库

关于 secrets-scanner

secrets-scanner 是用于检测代码库凭据泄漏的安全技能,介绍基于模式的扫描、提交前与 CI 检查、自定义扫描器及泄漏处置步骤。

主要功能

  1. 01检测文件中的凭据模式
  2. 02配置 Gitleaks 和 detect-secrets 钩子
  3. 03将密钥扫描加入 CI 工作流
  4. 04创建 TypeScript 自定义扫描器
  5. 05记录凭据泄漏处置步骤

适用场景

  1. 01提交前检查暂存变更
  2. 02在 CI 中扫描仓库
  3. 03查找源文件中的凭据
  4. 04处理发现的密钥泄漏

安装

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

$npx skills add https://github.com/patricio0312rev/skills --skill secrets-scanner

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

详细介绍

密钥扫描器

检测并防止代码库中的凭据泄露。

密钥检测模式

# .gitleaks.toml
title = "Gitleaks Configuration"

[[rules]]
id = "aws-access-key"
description = "AWS Access Key"
regex = '''(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]

[[rules]]
id = "aws-secret-key"
description = "AWS Secret Key"
regex = '''(?i)aws(.{0,20})?(?-i)['\"][0-9a-zA-Z\/+]{40}['\"]'''
tags = ["key", "AWS"]

[[rules]]
id = "github-token"
description = "GitHub Personal Access Token"
regex = '''ghp_[0-9a-zA-Z]{36}'''
tags = ["key", "GitHub"]

[[rules]]
id = "github-oauth"
description = "GitHub OAuth Token"
regex = '''gho_[0-9a-zA-Z]{36}'''
tags = ["key", "GitHub"]

[[rules]]
id = "slack-webhook"
description = "Slack Webhook URL"
regex = '''https://hooks\.slack\.com/services/T[a-zA-Z0-9_]{8,10}/B[a-zA-Z0-9_]{8,10}/[a-zA-Z0-9_]{24}'''
tags = ["webhook", "Slack"]

[[rules]]
id = "private-key"
description = "Private Key"
regex = '''-----BEGIN (RSA|OPENSSH|DSA|EC|PGP) PRIVATE KEY-----'''
tags = ["key", "private"]

[[rules]]
id = "generic-api-key"
description = "Generic API Key"
regex = '''(?i)(api[_-]?key|apikey|access[_-]?key)(.{0,20})?['"][0-9a-zA-Z]{32,}['"]'''
tags = ["key", "generic"]

[[rules]]
id = "database-connection"
description = "Database Connection String"
regex = '''(?i)(postgresql|mysql|mongodb):\/\/[^\s:]+:[^\s@]+@[^\s\/]+'''
tags = ["database", "credentials"]

[allowlist]
description = "Allowlist"
paths = [
  '''node_modules/''',
  '''\.git/''',
  '''\.lock$''',
]

regexes = [
  '''EXAMPLE_KEY_123''',
  '''your_api_key_here''',
  '''<API_KEY>''',
]

## Pre-commit Hook Setup

```yaml
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.0
    hooks:
      - id: gitleaks

  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.4.0
    hooks:
      - id: detect-secrets
        args: ['--baseline', '.secrets.baseline']

  - repo: local
    hooks:
      - id: check-env-files
        name: Check for .env files
        entry: bash -c 'if git diff --cached --name-only | grep -E "\.env$"; then echo "❌ .env file detected! Add to .gitignore"; exit 1; fi'
        language: system
        pass_filenames: false
# Install pre-commit
pip install pre-commit

# Install hooks
pre-commit install

# Run on all files
pre-commit run --all-files

CI 集成

# .github/workflows/secrets-scan.yml
name: Secrets Scan

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]

jobs:
  gitleaks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Full history for scanning

      - name: Run Gitleaks
        uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}

  trufflehog:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: TruffleHog OSS
        uses: trufflesecurity/trufflehog@main
        with:
          path: ./
          base: ${{ github.event.repository.default_branch }}
          head: HEAD
          extra_args: --debug --only-verified

自定义密钥扫描器

// scripts/scan-secrets.ts
import * as fs from "fs";
import * as path from "path";

interface SecretPattern {
  name: string;
  regex: RegExp;
  severity: "critical" | "high" | "medium";
}

const SECRET_PATTERNS: SecretPattern[] = [
  {
    name: "AWS Access Key",
    regex: /(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}/g,
    severity: "critical",
  },
  {
    name: "Private Key",
    regex: /-----BEGIN (RSA|OPENSSH|DSA|EC|PGP) PRIVATE KEY-----/g,
    severity: "critical",
  },
  {
    name: "Generic API Key",
    regex:
      /['"]?[a-zA-Z0-9_-]*api[_-]?key['"]?\s*[:=]\s*['"][a-zA-Z0-9]{32,}['"]/gi,
    severity: "high",
  },
  {
    name: "Database URL",
    regex: /(postgresql|mysql|mongodb):\/\/[^\s:]+:[^\s@]+@[^\s\/]+/gi,
    severity: "critical",
  },
  {
    name: "JWT Token",
    regex: /eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,
    severity: "high",
  },
];

interface SecretFinding {
  file: string;
  line: number;
  column: number;
  pattern: string;
  match: string;
  severity: string;
}

function scanFile(filePath: string): SecretFinding[] {
  const findings: SecretFinding[] = [];
  const content = fs.readFileSync(filePath, "utf-8");
  const lines = content.split("\n");

  lines.forEach((line, lineIndex) => {
    SECRET_PATTERNS.forEach((pattern) => {
      const matches = line.matchAll(pattern.regex);

      for (const match of matches) {
        findings.push({
          file: filePath,
          line: lineIndex + 1,
          column: match.index || 0,
          pattern: pattern.name,
          match: match[0].substring(0, 50) + "...",
          severity: pattern.severity,
        });
      }
    });
  });

  return findings;
}

function scanDirectory(dir: string): SecretFinding[] {
  const findings: SecretFinding[] = [];
  const files = fs.readdirSync(dir, { withFileTypes: true });

  const ignorePaths = ["node_modules", ".git", "dist", "build"];

  files.forEach((file) => {
    const fullPath = path.join(dir, file.name);

    if (file.isDirectory() && !ignorePaths.includes(file.name)) {
      findings.push(...scanDirectory(fullPath));
    } else if (file.isFile()) {
      findings.push(...scanFile(fullPath));
    }
  });

  return findings;
}

// Run scan
const findings = scanDirectory("./src");

if (findings.length > 0) {
  console.error("🚨 Secrets detected!\n");

  findings.forEach((f) => {
    console.error(
      `[${f.severity.toUpperCase()}] ${f.file}:${f.line}:${f.column}`
    );
    console.error(`  Pattern: ${f.pattern}`);
    console.error(`  Match: ${f.match}\n`);
  });

  process.exit(1);
} else {
  console.log("✅ No secrets detected");
}

补救步骤

# Secret Leak Remediation Checklist

## Immediate Actions (< 1 hour)

1. **Revoke the compromised secret**

   - [ ] Deactivate API key/token immediately
   - [ ] Rotate credentials in production
   - [ ] Update all services using the secret

2. **Remove from git history**

   ```bash
   # Using BFG Repo-Cleaner
   bfg --replace-text secrets.txt repo.git
   git reflog expire --expire=now --all
   git gc --prune=now --aggressive

   # Force push (requires team coordination)
   git push --force --all
   ```
  1. 通知相关人员
    • 安全团队
    • DevOps 团队
    • 服务负责人
    • 管理层(如果是公开仓库)

短期措施(< 24 小时)

  1. 审计访问日志

    • 检查 CloudWatch/CloudTrail 是否存在可疑活动
    • 检查 API 使用情况,确认是否存在未经授权的访问
    • 检查是否发生数据外泄
  2. 更新密钥管理

    • 存储在保险库中(AWS Secrets Manager、HashiCorp Vault)
    • 使用环境变量
    • 删除硬编码的密钥
  3. 添加扫描

    • 安装 pre-commit 钩子
    • 添加 CI 密钥扫描
    • 设置监控警报

长期措施(< 1 周)

  1. 审查并改进
    • 开展安全培训
    • 更新密钥管理策略
    • 制定密钥轮换计划
    • 记录事件及经验教训

## Secret Management Best Practices

```typescript
// ❌ BAD: Hardcoded secrets
const API_KEY = 'sk_live_abc123xyz789';
const db = connect('mongodb://admin:password@localhost');

// ✅ GOOD: Environment variables
const API_KEY = process.env.API_KEY;
const db = connect(process.env.DATABASE_URL);

// ✅ BETTER: Secret management service
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';

async function getSecret(secretName: string): Promise<string> {
  const client = new SecretsManagerClient({ region: 'us-east-1' });
  const response = await client.send(
    new GetSecretValueCommand({ SecretId: secretName })
  );
  return response.SecretString!;
}

const apiKey = await getSecret('prod/api/stripe-key');

GitHub 密钥扫描

# Enable GitHub secret scanning (Enterprise)
# Settings → Security & analysis → Secret scanning

# Configure custom patterns
# .github/secret_scanning.yml
patterns:
  - name: Company API Key
    pattern: "company_[a-zA-Z0-9]{32}"
    secret_type: company_api_key

环境变量验证

// config/env-validation.ts
import { z } from "zod";

const envSchema = z
  .object({
    NODE_ENV: z.enum(["development", "production", "test"]),
    DATABASE_URL: z.string().url(),
    API_KEY: z.string().min(32),
    JWT_SECRET: z.string().min(64),
    // Never allow default/example values in production
  })
  .refine((env) => {
    if (env.NODE_ENV === "production") {
      const invalidValues = ["example", "test", "localhost", "changeme"];
      return !invalidValues.some((val) =>
        Object.values(env).some((envVal) =>
          String(envVal).toLowerCase().includes(val)
        )
      );
    }
    return true;
  }, "Production environment cannot use example/test values");

// Validate on startup
try {
  envSchema.parse(process.env);
} catch (error) {
  console.error("❌ Invalid environment configuration:", error);
  process.exit(1);
}

监控与警报

// monitoring/secret-monitoring.ts
import {
  CloudWatchClient,
  PutMetricDataCommand,
} from "@aws-sdk/client-cloudwatch";

async function monitorSecretUsage(secretName: string) {
  const cloudwatch = new CloudWatchClient();

  await cloudwatch.send(
    new PutMetricDataCommand({
      Namespace: "Security/Secrets",
      MetricData: [
        {
          MetricName: "SecretAccess",
          Value: 1,
          Unit: "Count",
          Dimensions: [
            {
              Name: "SecretName",
              Value: secretName,
            },
          ],
        },
      ],
    })
  );
}

// Alert on unusual secret access patterns

最佳实践

  1. 切勿提交密钥:使用 .gitignore 忽略 .env 文件
  2. 使用密钥管理器:AWS Secrets Manager、Vault
  3. 定期轮换:采用 90 天轮换策略
  4. 持续扫描:提交前扫描 + CI 扫描 + 定期扫描
  5. 最小权限:将密钥访问权限降至最低
  6. 审计日志:跟踪密钥访问情况
  7. 事件响应:准备好补救预案

输出检查清单

  • 已创建 Gitleaks 配置
  • 已安装 pre-commit 钩子
  • 已配置 CI 密钥扫描
  • 已实现自定义扫描器(可选)
  • 已记录补救预案
  • 已落实密钥管理最佳实践
  • 已验证环境配置
  • 已设置监控和警报
  • .gitignore 已包含 .env 文件
  • 团队已接受密钥处理培训

评论

支持 Markdown