Gitleaks Cheatsheet¶
Installation¶
| Platform | Command |
|---|---|
| macOS (Homebrew) | brew install gitleaks |
| Linux (Binary) | wget https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks_linux_x64.tar.gz && tar -xzf gitleaks_linux_x64.tar.gz && sudo mv gitleaks /usr/local/bin/ |
| Ubuntu/Debian (Snap) | sudo snap install gitleaks |
| Arch Linux (AUR) | yay -S gitleaks |
| Windows (Chocolatey) | choco install gitleaks |
| Windows (Scoop) | scoop install gitleaks |
| Docker (All Platforms) | docker pull zricethezav/gitleaks:latest |
| Go Install | go install github.com/gitleaks/gitleaks/v8@latest |
Basic Commands¶
| Command | Description |
|---|---|
gitleaks detect |
Scan current repository for secrets in entire git history |
gitleaks detect -v |
Scan with verbose output showing detailed progress |
gitleaks detect --source /path/to/repo |
Scan a repository at specific location |
gitleaks detect --no-git |
Scan files without git history (for non-git directories) |
gitleaks detect --report-path report.json |
Generate JSON report of findings |
gitleaks detect --report-format csv --report-path report.csv |
Generate CSV format report |
gitleaks detect --report-format sarif --report-path report.sarif |
Generate SARIF report (for GitHub Code Scanning) |
gitleaks protect |
Scan uncommitted changes (ideal for pre-commit hooks) |
gitleaks protect --staged |
Scan only staged changes before commit |
gitleaks detect --redact |
Redact secret values in output for security |
gitleaks detect --exit-code 0 |
Always exit with code 0 (non-blocking scan) |
gitleaks version |
Display installed Gitleaks version |
gitleaks detect --config .gitleaks.toml |
Use custom configuration file |
gitleaks detect --baseline-path baseline.json |
Ignore previously known findings using baseline |
gitleaks detect --log-opts="--all -- path/to/file.js" |
Scan specific files or paths |
Advanced Usage¶
| Command | Description |
|---|---|
gitleaks detect --log-opts="commit1..commit2" |
Scan commits between two specific commit hashes |
gitleaks detect --log-opts="-n 10" |
Scan only the last 10 commits |
gitleaks detect --log-opts="origin/develop" |
Scan specific branch |
gitleaks detect --log-opts="--since='2023-01-01' --until='2023-12-31'" |
Scan commits within date range |
gitleaks detect --log-opts="--author='john@example.com'" |
Scan commits from specific author |
gitleaks detect --threads=8 |
Use 8 threads for parallel scanning (faster) |
gitleaks detect --max-target-megabytes=100 |
Limit scan to files under 100MB |
gitleaks detect --log-level=debug |
Enable debug-level logging for troubleshooting |
gitleaks detect --enable-rule="aws-access-token" |
Enable specific detection rule |
gitleaks detect --disable-rule="generic-api-key" |
Disable specific detection rule |
gitleaks detect --follow-symlinks |
Include symbolic links in scan |
gitleaks detect --log-opts="--all -- . ':(exclude)vendor/*'" |
Exclude vendor directory from scan |
gitleaks detect --log-opts="--all -- . ':(exclude)node_modules/*'" |
Exclude node_modules from scan |
gitleaks protect --no-git |
Scan working directory without git context |
gitleaks detect --report-format json \| jq '.' |
Pretty print JSON output with jq |
gitleaks detect --report-format json \| jq '.[] \| length' |
Count total findings |
docker run -v ${PWD}:/repo zricethezav/gitleaks:latest detect --source="/repo" -v |
Run Gitleaks in Docker container |
gitleaks detect --report-path baseline.json && gitleaks detect --baseline-path baseline.json |
Create and use baseline in one workflow |
Configuration¶
Configuration File Location¶
Gitleaks looks for .gitleaks.toml in the repository root by default.
Basic Configuration Structure¶
title = "Gitleaks Configuration"
[extend]
# Use default rules and extend them
useDefault = true
[[rules]]
id = "custom-api-key"
description = "Custom API Key Pattern"
regex = '''(?i)api[_-]?key[_-]?=["']?([a-z0-9]{32,})["']?'''
tags = ["api", "key"]
secretGroup = 1
[[rules]]
id = "company-secret"
description = "Company Specific Secret Pattern"
regex = '''COMPANY_SECRET_[A-Z0-9]{20}'''
tags = ["company", "secret"]
[allowlist]
description = "Allowlist for false positives"
paths = [
'''\.gitleaks\.toml''',
'''(.*?)(jpg|gif|doc|pdf|bin)$''',
'''vendor/.*''',
'''node_modules/.*'''
]
regexes = [
'''219-09-9999''', # Fake SSN for testing
'''example\.com''',
]
stopwords = [
'''placeholder''',
'''sample''',
'''dummy''',
]
Advanced Rule Configuration¶
# Rule with entropy detection
[[rules]]
id = "high-entropy-string"
description = "High entropy string detection"
regex = '''[a-zA-Z0-9+/]{40,}'''
entropy = 4.5
secretGroup = 0
tags = ["entropy", "generic"]
# Path-specific rule
[[rules]]
id = "aws-key-in-config"
description = "AWS keys in YAML config files"
regex = '''AKIA[0-9A-Z]{16}'''
path = '''.*\.ya?ml$'''
tags = ["aws", "config"]
# Commit allowlist
[allowlist]
commits = [
"a1b2c3d4e5f6", # Known safe commit
]
regexTarget = "match" # or "line"
Environment Variables¶
# Set custom config path
export GITLEAKS_CONFIG=/path/to/config.toml
# Set log level
export GITLEAKS_LOG_LEVEL=debug
# Disable color output
export GITLEAKS_NO_COLOR=true
Common Use Cases¶
Use Case 1: Pre-commit Hook Integration¶
Prevent secrets from being committed locally:
# Create pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/sh
gitleaks protect --staged --redact --verbose
EOF
# Make executable
chmod +x .git/hooks/pre-commit
# Test the hook
git add .
git commit -m "test commit"
Use Case 2: GitHub Actions CI/CD Pipeline¶
Automated secret scanning in pull requests:
# .github/workflows/gitleaks.yml
name: gitleaks
on: [pull_request, push]
jobs:
scan:
name: gitleaks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
Use Case 3: GitLab CI Integration¶
Add to .gitlab-ci.yml:
gitleaks:
stage: test
image: zricethezav/gitleaks:latest
script:
- gitleaks detect --report-format json --report-path gl-secret-detection-report.json
artifacts:
reports:
secret_detection: gl-secret-detection-report.json
allow_failure: false
Use Case 4: Baseline for Existing Repositories¶
Handle legacy secrets while catching new ones:
# Step 1: Create baseline of existing findings
gitleaks detect --report-path gitleaks-baseline.json
# Step 2: Review and document existing secrets
cat gitleaks-baseline.json | jq '.[] | {rule: .RuleID, file: .File}'
# Step 3: Use baseline in future scans (only new secrets fail)
gitleaks detect --baseline-path gitleaks-baseline.json
# Step 4: Add baseline to CI/CD
gitleaks detect --baseline-path gitleaks-baseline.json --report-format sarif --report-path results.sarif
Use Case 5: Scanning Specific Commit Range¶
Audit recent changes during code review:
# Scan last 5 commits
gitleaks detect --log-opts="-n 5" -v
# Scan commits from feature branch
gitleaks detect --log-opts="main..feature/new-api"
# Scan today's commits
gitleaks detect --log-opts="--since='1 day ago'"
# Scan specific author's commits this week
gitleaks detect --log-opts="--author='dev@company.com' --since='1 week ago'"
Use Case 6: Docker-based Scanning¶
Scan without installing Gitleaks locally:
# Scan current directory
docker run -v ${PWD}:/repo zricethezav/gitleaks:latest detect --source="/repo" -v
# Generate report
docker run -v ${PWD}:/repo zricethezav/gitleaks:latest detect --source="/repo" --report-path=/repo/report.json
# Use custom config
docker run -v ${PWD}:/repo zricethezav/gitleaks:latest detect --source="/repo" --config=/repo/.gitleaks.toml
Use Case 7: Custom Rules for Organization¶
Create organization-specific detection patterns:
# Create custom config
cat > .gitleaks.toml << 'EOF'
title = "Company Security Rules"
[extend]
useDefault = true
[[rules]]
id = "company-api-key"
description = "Company API Key Format"
regex = '''COMP_[A-Z]{4}_[a-z0-9]{32}'''
tags = ["company", "api-key"]
[[rules]]
id = "internal-token"
description = "Internal Service Token"
regex = '''INT_TOKEN_[A-F0-9]{40}'''
tags = ["internal", "token"]
[allowlist]
paths = [
'''test/.*''',
'''docs/examples/.*'''
]
EOF
# Run with custom config
gitleaks detect --config .gitleaks.toml -v
Best Practices¶
-
Enable Pre-commit Hooks: Use
gitleaks protectin pre-commit hooks to catch secrets before they enter git history. This is your first line of defense. -
Integrate into CI/CD Early: Add Gitleaks to your CI/CD pipeline as early as possible. Fail builds when secrets are detected to prevent them from reaching production.
-
Use Baseline for Legacy Code: When introducing Gitleaks to existing repositories, create a baseline to avoid overwhelming teams with historical findings while still catching new secrets.
-
Customize Configuration: Extend the default rules with organization-specific patterns. Add your internal secret formats and API key patterns to the
.gitleaks.tomlfile. -
Maintain an Allowlist: Use allowlists judiciously for false positives, but document why each entry is safe. Review allowlists regularly to ensure they remain valid.
-
Redact in Production: Always use
--redactflag when running Gitleaks in CI/CD or shared environments to avoid exposing secrets in logs and reports. -
Scan Multiple Branches: Don't just scan the main branch. Configure CI/CD to scan all branches and pull requests to catch secrets before they're merged.
-
Regular Full Repository Audits: Periodically run full repository scans without baselines to ensure no secrets have slipped through and to catch secrets introduced through merge conflicts.
-
Educate Developers: Train your team on what Gitleaks detects and why. Understanding the tool reduces false positives and increases security awareness.
-
Monitor Performance: For large repositories, use
--threadsto optimize scan time and consider--max-target-megabytesto skip large binary files that slow down scans.
Troubleshooting¶
| Issue | Solution |
|---|---|
| Too many false positives | Create .gitleaks.toml with allowlist entries for known safe patterns. Use stopwords for common test values like "example", "test", "dummy". |
| Scan taking too long | Use --threads=<number> to increase parallelization. Add large binary files to path allowlist. Use --max-target-megabytes to skip large files. |
| Missing secrets I know exist | Check if custom patterns need to be added to .gitleaks.toml. Verify useDefault = true is set to include built-in rules. Test regex patterns separately. |
| Pre-commit hook not working | Ensure hook is executable: chmod +x .git/hooks/pre-commit. Verify Gitleaks is in PATH: which gitleaks. Check hook script has correct shebang: #!/bin/sh. |
| Docker permission errors | Use -v ${PWD}:/repo with correct path. Ensure Docker has permission to mount the volume. On Linux, may need to add :z flag: -v ${PWD}:/repo:z. |
| Baseline not ignoring findings | Verify baseline path is correct. Ensure baseline JSON is valid: cat baseline.json \| jq '.'. Baseline must be created from same repository state. |
| CI/CD pipeline failing unexpectedly | Check exit codes: use --exit-code 0 for non-blocking scans. Review logs with -v flag. Verify config file is accessible in CI environment. |
| Config file not being loaded | Ensure file is named .gitleaks.toml in repo root. Use --config flag to specify custom location. Validate TOML syntax: use online TOML validator. |
| High entropy false positives | Lower entropy threshold in config: entropy = 3.0 instead of default. Add specific high-entropy safe strings to allowlist regexes. |
| Cannot scan large repositories | Use commit range scanning: --log-opts="-n 100" to scan recent commits. Increase memory limits if using Docker. Consider scanning in chunks by date range. |