Zum Inhalt

_

_

_

Gitleaks Cheatsheet

• Installation

Platform Command
macOS (Homebrew) INLINE_CODE_10
Linux (Binary) INLINE_CODE_11
Ubuntu/Debian (Snap) INLINE_CODE_12
Arch Linux (AUR) INLINE_CODE_13
Windows (Chocolatey) INLINE_CODE_14
Windows (Scoop) INLINE_CODE_15
Docker (All Platforms) INLINE_CODE_16
Go Install INLINE_CODE_17
_
oder Grundlegende Befehle
Command Description
INLINE_CODE_18 Scan current repository for secrets in entire git history
INLINE_CODE_19 Scan with verbose output showing detailed progress
INLINE_CODE_20 Scan a repository at specific location
INLINE_CODE_21 Scan files without git history (for non-git directories)
INLINE_CODE_22 Generate JSON report of findings
INLINE_CODE_23 Generate CSV format report
INLINE_CODE_24 Generate SARIF report (for GitHub Code Scanning)
INLINE_CODE_25 Scan uncommitted changes (ideal for pre-commit hooks)
INLINE_CODE_26 Scan only staged changes before commit
INLINE_CODE_27 Redact secret values in output for security
INLINE_CODE_28 Always exit with code 0 (non-blocking scan)
INLINE_CODE_29 Display installed Gitleaks version
INLINE_CODE_30 Use custom configuration file
INLINE_CODE_31 Ignore previously known findings using baseline
INLINE_CODE_32 Scan specific files or paths
_
/ Fortgeschrittene Nutzung
Command Description
INLINE_CODE_33 Scan commits between two specific commit hashes
INLINE_CODE_34 Scan only the last 10 commits
INLINE_CODE_35 Scan specific branch
INLINE_CODE_36 Scan commits within date range
INLINE_CODE_37 Scan commits from specific author
INLINE_CODE_38 Use 8 threads for parallel scanning (faster)
INLINE_CODE_39 Limit scan to files under 100MB
INLINE_CODE_40 Enable debug-level logging for troubleshooting
INLINE_CODE_41 Enable specific detection rule
INLINE_CODE_42 Disable specific detection rule
INLINE_CODE_43 Include symbolic links in scan
INLINE_CODE_44 Exclude vendor directory from scan
INLINE_CODE_45 Exclude node_modules from scan
INLINE_CODE_46 Scan working directory without git context
INLINE_CODE_47 Pretty print JSON output with jq
INLINE_CODE_48 Count total findings
INLINE_CODE_49 Run Gitleaks in Docker container
INLINE_CODE_50 Create and use baseline in one workflow
_
Konfiguration

Konfiguration der Datei

Gitleaks sucht standardmäßig .gitleaks.toml im Repository-Root.

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''',
]

Erweiterte Regelkonfiguration

# 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"

Umgebungsvariablen

# 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

Häufige Anwendungsfälle

Use Case 1: Precommit Hook Integration

Verhindern Sie, dass Geheimnisse vor Ort begangen werden:

# 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

Automatisches geheimes Scannen in Zuganfragen:

# .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

.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 für bestehende Repositories

Legen Sie Legacy-Geheimnisse, während Sie neue fangen:

# 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: Scannen bestimmter Commit-Bereich

Prüfung neuer Änderungen während der 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: Dockerbasiertes Scanning

Scannen ohne Installation Gitleaks lokal:

# 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

Organisationsspezifische Nachweismuster erstellen:

# 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

oder Best Practices

  • Empfehlung aktivieren Hooks: Verwenden Sie gitleaks protect in vorkommit Haken, um Geheimnisse zu fangen, bevor sie Git-Geschichte eingeben. Das ist deine erste Verteidigungslinie.

  • **Integration in CI/CD Early*: Fügen Sie Gitleaks so früh wie möglich zu Ihrer CI/CD-Pipeline hinzu. Fehler baut, wenn Geheimnisse erkannt werden, um zu verhindern, dass sie Produktion erreichen.

  • Use Baseline for Legacy Code: Bei der Einführung von Gitleaks zu bestehenden Repositories, schaffen Sie eine Basislinie, um überwältigende Teams mit historischen Erkenntnissen zu vermeiden, während immer noch neue Geheimnisse zu fangen.

  • **Konfiguration anpassen*: Erweitern Sie die Standardregeln mit organisatorischen Mustern. Fügen Sie Ihre internen geheimen Formate und API-Schlüsselmuster in die .gitleaks.toml Datei ein.

  • Hinzulassung: Benutzen Sie zulässige Listen für falsche Positive, aber dokumentieren Sie, warum jeder Eintrag sicher ist. Prüfen Sie regelmäßig, um sicherzustellen, dass sie gültig bleiben.

  • **Redact in Production*: Verwenden Sie immer --redact-Flag, wenn Sie Gitleaks in CI/CD oder gemeinsame Umgebungen ausführen, um Geheimnisse in Protokollen und Berichten zu vermeiden.

  • ** Mehrere Filialen scannen*: Scannen Sie nicht einfach den Hauptzweig. Konfigurieren Sie CI/CD, um alle Zweige zu scannen und Anfragen zu ziehen, um Geheimnisse zu fangen, bevor sie zusammengeführt werden.

  • Regular Full Repository Audits: Regelmäßig laufen volle Repository-Scans ohne Basislinien, um sicherzustellen, dass keine Geheimnisse durchrutschen und Geheimnisse durch Zusammenführung Konflikte eingeführt werden.

  • **Educate Developers*: Trainieren Sie Ihr Team, was Gitleaks erkennt und warum. Das Verständnis des Werkzeuges reduziert falsche Positive und erhöht das Sicherheitsbewusstsein.

  • Monitor Performance: Für große Repositories verwenden Sie --threads, um die Scanzeit zu optimieren und --max-target-megabytes zu überspringen große binäre Dateien, die Scans verlangsamen.

Fehlerbehebung

Issue Solution
Too many false positives Create INLINE_CODE_58 with allowlist entries for known safe patterns. Use INLINE_CODE_59 for common test values like "example", "test", "dummy".
Scan taking too long Use INLINE_CODE_60 to increase parallelization. Add large binary files to path allowlist. Use INLINE_CODE_61 to skip large files.
Missing secrets I know exist Check if custom patterns need to be added to INLINE_CODE_62. Verify INLINE_CODE_63 is set to include built-in rules. Test regex patterns separately.
Pre-commit hook not working Ensure hook is executable: INLINE_CODE_64. Verify Gitleaks is in PATH: INLINE_CODE_65. Check hook script has correct shebang: INLINE_CODE_66.
Docker permission errors Use INLINE_CODE_67 with correct path. Ensure Docker has permission to mount the volume. On Linux, may need to add INLINE_CODE_68 flag: INLINE_CODE_69.
Baseline not ignoring findings Verify baseline path is correct. Ensure baseline JSON is valid: INLINE_CODE_70. Baseline must be created from same repository state.
CI/CD pipeline failing unexpectedly Check exit codes: use INLINE_CODE_71 for non-blocking scans. Review logs with INLINE_CODE_72 flag. Verify config file is accessible in CI environment.
Config file not being loaded Ensure file is named INLINE_CODE_73 in repo root. Use INLINE_CODE_74 flag to specify custom location. Validate TOML syntax: use online TOML validator.
High entropy false positives Lower entropy threshold in config: INLINE_CODE_75 instead of default. Add specific high-entropy safe strings to allowlist regexes.
Kann große Repositories nicht scannen Bestimmte Reichweiten-Scannen verwenden: --log-opts="-n 100"_, um neue Commits zu scannen. Erhöhen Sie die Speichergrenzen, wenn Sie Docker verwenden. Betrachten Sie das Scannen in Stücken nach Datumsbereich.