关于 secrets-gitleaks
secrets-gitleaks 是使用 Gitleaks 检测仓库、文件和目录中硬编码凭据的技能。它帮助开发与安全团队将扫描纳入本地检查和 CI/CD,并提供基线、自定义规则及修复指导。
主要功能
- 01扫描仓库与目录
- 02配置提交前钩子
- 03CI/CD 流水线集成指导
- 04基线与增量扫描
- 05配置自定义检测规则
- 06发现报告与修复指导
适用场景
- 01审计仓库中的泄露凭据
- 02在提交前拦截密钥
- 03将密钥扫描加入 CI/CD
- 04跟踪遗留代码中的新增发现
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ agentsecops/ secopsagentkit --skill secrets-gitleaks安装后在 Claude Code 中输入/secrets-gitleaks确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/.gitkeepconfig-balanced.tomlconfig-custom.tomlconfig-strict.tomlgithub-action.ymlgitlab-ci.ymlprecommit-config.yamlreferences/compliance_mapping.mddetection_rules.mdEXAMPLE.mdfalse_positives.mdremediation_guide.md详细介绍
使用 Gitleaks 检测机密信息
概述
Gitleaks 是一款机密信息检测工具,可扫描 Git 仓库、文件和目录,查找硬编码凭据,包括密码、API 密钥、令牌和其他敏感信息。它结合基于正则表达式的模式匹配与 Shannon 熵分析,识别可能导致未授权访问的暴露机密信息。
本技能全面介绍如何将 Gitleaks 集成到 DevSecOps 工作流中,从提交前钩子到 CI/CD 流水线,重点是在代码进入生产环境前防止机密信息泄露。
快速开始
扫描当前仓库中的机密信息:
# Install gitleaks
brew install gitleaks # macOS
# or: docker pull zricethezav/gitleaks:latest
# Scan current git repository
gitleaks detect -v
# Scan specific directory
gitleaks detect --source /path/to/code -v
# Generate report
gitleaks detect --report-path gitleaks-report.json --report-format json
核心工作流
1. 仓库扫描
扫描现有仓库,识别暴露的机密信息:
# Full repository scan with verbose output
gitleaks detect -v --source /path/to/repo
# Scan with custom configuration
gitleaks detect --config .gitleaks.toml -v
# Generate JSON report for further analysis
gitleaks detect --report-path findings.json --report-format json
# Generate SARIF report for GitHub/GitLab integration
gitleaks detect --report-path findings.sarif --report-format sarif
适用场景:初始安全审计、合规检查、事件响应。
2. 提交前钩子保护
从源头防止机密信息被提交:
# Install pre-commit hook (run in repository root)
cat << 'EOF' > .git/hooks/pre-commit
#!/bin/sh
gitleaks protect --verbose --redact --staged
EOF
chmod +x .git/hooks/pre-commit
使用捆绑脚本自动安装钩子:
./scripts/install_precommit.sh
适用场景:开发者工作站设置、团队入职、安全控制强制要求。
3. CI/CD 流水线集成
GitHub Actions
name: gitleaks
on: [push, pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GitLab CI
gitleaks:
image: zricethezav/gitleaks:latest
stage: test
script:
- gitleaks detect --report-path gitleaks.json --report-format json --verbose
artifacts:
paths:
- gitleaks.json
when: always
allow_failure: false
适用场景:自动化安全门禁、拉取请求检查、发布验证。
4. 基线与增量扫描
建立安全基线,并仅跟踪新的机密信息:
# Create initial baseline
gitleaks detect --report-path baseline.json --report-format json
# Subsequent scans detect only new secrets
gitleaks detect --baseline-path baseline.json --report-path new-findings.json -v
适用场景:旧代码库修复、分阶段推广、合规跟踪。
5. 自定义配置
创建自定义 .gitleaks.toml 配置:
title = "Custom Gitleaks Configuration"
[extend]
# Extend default config with custom rules
useDefault = true
[[rules]]
id = "custom-api-key"
description = "Custom API Key Pattern"
regex = '''(?i)(custom_api_key|custom_secret)[\s]*[=:][\s]*['"][a-zA-Z0-9]{32,}['"]'''
tags = ["api-key", "custom"]
[allowlist]
description = "Global allowlist"
paths = [
'''\.md$''', # Ignore markdown files
'''test/fixtures/''', # Ignore test fixtures
]
stopwords = [
'''EXAMPLE''', # Ignore example keys
'''PLACEHOLDER''',
]
使用 assets/ 中捆绑的配置模板:
assets/config-strict.toml- 严格检测(降低漏报)assets/config-balanced.toml- 均衡检测(推荐)assets/config-custom.toml- 自定义规则模板
适用场景:减少误报、添加专有机密信息模式、制定组织标准。
安全注意事项
敏感数据处理
- 机密信息脱敏:在日志和报告中始终使用
--redact标志,防止意外暴露机密信息 - 报告安全:Gitleaks 报告包含检测到的机密信息,应视为机密并加密存储
- Git 历史记录:若在 Git 历史记录中检测到机密信息,必须使用
git filter-repo或BFG Repo-Cleaner等工具彻底删除 - 凭据轮换:所有暴露的机密信息都必须立即轮换,即使已从代码中删除
访问控制
- CI/CD 权限:Gitleaks 扫描需要读取仓库内容和 Git 历史记录的权限
- 报告访问权限:限制对包含敏感发现的扫描报告的访问
- 基线文件:基线 JSON 文件包含机密信息的元数据,应采用与扫描发现相同的保护措施
审计日志记录
为满足合规要求和事件响应需要,请记录以下内容:
- 扫描执行时间戳和范围(仓库、分支、提交范围)
- 检测到的机密信息数量和类型
- 已采取的修复措施(凭据轮换、清理提交历史)
- 误报分类和允许列表更新
合规要求
- PCI-DSS 3.2.1:要求 6.5.3 - 防止支付应用中出现硬编码凭据
- SOC2:CC6.1 - 逻辑访问控制可防止凭据被未授权暴露
- GDPR:第 32 条 - 处理个人数据凭据时应采取适当的安全措施
- CWE-798:使用硬编码凭据
- CWE-259:使用硬编码密码
- OWASP A07:2021:身份识别和身份验证失败
捆绑资源
脚本(scripts/)
install_precommit.sh- 通过配置提示自动安装提交前钩子scan_and_report.py- 执行全面扫描,支持多种输出格式和严重性分类baseline_manager.py- 管理基线创建、比较和增量扫描
参考资料(references/)
detection_rules.md- 内置 Gitleaks 检测规则完整列表及其 CWE 映射remediation_guide.md- 分步密钥补救流程,包括清理 Git 历史记录false_positives.md- 常见误报模式及允许列表配置策略compliance_mapping.md- 与 PCI-DSS、SOC2、GDPR 和 OWASP 要求的详细映射
资源(assets/)
config-strict.toml- 高敏感度配置(最大程度检测)config-balanced.toml- 可用于生产环境的均衡配置config-custom.toml- 包含自定义规则行内文档的模板precommit-config.yaml- Pre-commit 框架配置github-action.yml- 完整的 GitHub Actions 工作流模板gitlab-ci.yml- 完整的 GitLab CI 流水线模板
常见模式
模式 1:初始仓库审计
首次进行密钥扫描以评估安全性:
# 1. Clone repository with full history
git clone --mirror https://github.com/org/repo.git audit-repo
cd audit-repo
# 2. Run comprehensive scan
gitleaks detect --report-path audit-report.json --report-format json -v
# 3. Generate human-readable report
./scripts/scan_and_report.py --input audit-report.json --format markdown --output audit-report.md
# 4. Review findings and classify false positives
# Edit .gitleaks.toml to add allowlist entries
# 5. Create baseline for future scans
cp audit-report.json baseline.json
模式 2:开发者工作站设置
防止开发者意外提交密钥:
# 1. Install gitleaks locally
brew install gitleaks # macOS
# or use package manager for your OS
# 2. Install pre-commit hook
./scripts/install_precommit.sh
# 3. Test hook with dummy commit
echo "api_key = 'EXAMPLE_KEY_12345'" > test.txt
git add test.txt
git commit -m "test" # Should be blocked by gitleaks
# 4. Clean up test
git reset HEAD~1
rm test.txt
模式 3:带基准的 CI/CD 流水线
在持续集成中逐步检测密钥:
# In CI pipeline script:
# 1. Check if baseline exists
if [ -f ".gitleaks-baseline.json" ]; then
# Incremental scan - only new secrets
gitleaks detect \
--baseline-path .gitleaks-baseline.json \
--report-path new-findings.json \
--report-format json \
--exit-code 1 # Fail on new secrets
else
# Initial scan - create baseline
gitleaks detect \
--report-path .gitleaks-baseline.json \
--report-format json \
--exit-code 0 # Don't fail on first scan
fi
# 2. Generate SARIF for GitHub Security tab
if [ -f "new-findings.json" ] && [ -s "new-findings.json" ]; then
gitleaks detect \
--baseline-path .gitleaks-baseline.json \
--report-path results.sarif \
--report-format sarif
fi
模式 4:自定义规则开发
添加组织特有的密钥模式:
# Add to .gitleaks.toml
[[rules]]
id = "acme-corp-api-key"
description = "ACME Corp Internal API Key"
regex = '''(?i)acme[_-]?api[_-]?key[\s]*[=:][\s]*['"]?([a-f0-9]{40})['"]?'''
secretGroup = 1
tags = ["api-key", "acme-internal"]
[[rules]]
id = "acme-corp-database-password"
description = "ACME Corp Database Password Format"
regex = '''(?i)(db_pass|database_password)[\s]*[=:][\s]*['"]([A-Z][a-z0-9@#$%]{15,})['"]'''
secretGroup = 2
tags = ["password", "database", "acme-internal"]
# Test custom rules
# gitleaks detect --config .gitleaks.toml -v
集成点
CI/CD 集成
- GitHub Actions:使用
gitleaks/gitleaks-action@v2与 Security 选项卡进行原生集成 - GitLab CI:基于 Docker 的扫描,并保留制品以供审计追踪
- Jenkins:在流水线阶段通过 Docker 或已安装的二进制文件执行
- CircleCI:支持 Orb 的 Docker 执行器
- Azure Pipelines:基于任务的集成,并发布结果
安全工具生态系统
- SIEM 集成:将 JSON 检测结果导出到 Splunk、ELK 或 Datadog,以便集中监控
- 漏洞管理:将 SARIF 报告导入 Snyk、SonarQube 或 Checkmarx
- 密钥管理:将检测结果与 HashiCorp Vault 或 AWS Secrets Manager 轮换工作流集成
- 工单系统:自动创建 Jira/ServiceNow 工单以跟踪补救进度
SDLC 集成
- 设计阶段:在安全架构评审中纳入密钥检测要求
- 开发阶段:Pre-commit 钩子为开发者提供即时反馈
- 代码审查:PR/MR 检查可防止密钥进入主分支
- 测试阶段:扫描测试环境和基础设施即代码
- 部署阶段:生产发布前的最终验证关卡
- 运维阶段:定期扫描已部署的配置和日志
故障排除
问题:误报过多
症状:合法代码模式被标记为密钥(测试夹具、示例、占位符)
解决方案:
- 检查检测结果以找出模式:
grep -i "example\|test\|placeholder" gitleaks-report.json - 将其添加到
.gitleaks.toml中的允许列表:[allowlist] paths = ['''test/''', '''examples/''', '''\.md$'''] stopwords = ["EXAMPLE", "PLACEHOLDER", "YOUR_API_KEY_HERE"] - 使用提交允许列表处理特定误报:
[allowlist] commits = ["commit-sha-here"] - 查阅
references/false_positives.md,了解常见模式
问题:大型仓库的性能问题
症状:扫描耗时过长(超过 10 分钟)、内存使用量高
解决方案:
- 使用
--log-opts限制 Git 历史记录:gitleaks detect --log-opts="--since=2024-01-01" - 扫描特定分支:
gitleaks detect --log-opts="origin/main" - 使用基准方法,仅扫描近期更改
- 初次扫描时考虑使用浅克隆:
git clone --depth=1000 - 在多个分支或子目录间并行扫描
问题:Pre-commit 钩子阻止有效提交
症状:开发者无法提交包含合法模式的代码
解决方案:
- 添加行内注释以绕过钩子:
# gitleaks:allow - 在
.gitleaks.toml允许列表中为特定模式添加条目 - 使用
--redact安全地检查检测结果:gitleaks protect --staged --redact - 临时绕过(请谨慎使用):
git commit --no-verify - 如果确实需要该模式,请与安全团队一起审查
问题:在 Git 历史记录中发现机密信息
症状:在旧提交中检测到机密信息,但已从当前代码中移除
解决方案:
- 立即轮换已泄露的凭据(最高优先级)
- 对于公开仓库,考虑使用以下工具彻底重写历史记录:
git filter-repo(推荐):git filter-repo --path-glob '*.env' --invert-paths- BFG Repo-Cleaner:
bfg --delete-files credentials.json
- 强制推送清理后的历史记录:
git push --force - 通知所有贡献者变基或重新克隆
- 有关详细操作步骤,请参阅
references/remediation_guide.md - 在安全审计日志中记录事件
问题:未检测到自定义机密信息模式
症状:默认规则未能捕获组织特有的机密信息
解决方案:
- 编写正则表达式模式:使用样例机密信息在 regex101.com 上进行测试
- 在
.gitleaks.toml中添加自定义规则:[[rules]] id = "custom-secret-id" description = "Description" regex = '''your-pattern-here''' secretGroup = 1 # Capture group containing actual secret - 测试模式:
gitleaks detect --config .gitleaks.toml -v --no-git - 如果模式有歧义,请考虑设置熵阈值:
[[rules.Entropies]] Min = "3.5" Max = "7.0" Group = "1" - 使用已知的真实阳性和阴性样例进行验证
高级配置
基于熵的检测
对于没有明确模式的机密信息,请使用 Shannon 熵分析:
[[rules]]
id = "high-entropy-strings"
description = "High entropy strings that may be secrets"
regex = '''[a-zA-Z0-9]{32,}'''
entropy = 4.5 # Shannon entropy threshold
secretGroup = 0
复合规则(v8.28.0+)
检测跨多行或需要结合上下文才能识别的机密信息:
[[rules]]
id = "multi-line-secret"
description = "API key with usage context"
regex = '''api_key[\s]*='''
[[rules.composite]]
pattern = '''initialize_client'''
location = "line" # Must be within same line proximity
distance = 5 # Within 5 lines
全局与规则专属允许列表
# Global allowlist (highest precedence)
[allowlist]
description = "Organization-wide exceptions"
paths = ['''vendor/''', '''node_modules/''']
# Rule-specific allowlist
[[rules]]
id = "generic-api-key"
[rules.allowlist]
description = "Exceptions only for this rule"
regexes = ['''key\s*=\s*EXAMPLE''']