Saltar a contenido
_ _

Gitleaks Cheatsheet

Instalación

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

Comandos básicos

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

Advanced Usage

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

Configuración

Ubicación del archivo de configuración

Gitleaks busca .gitleaks.toml_ en la raíz del repositorio por defecto.

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

Configuración avanzada de reglas

# 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

Evitar que los secretos se cometan localmente:

# 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

Escaneo secreto automatizado en las solicitudes de tirada:

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

Añadir a .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: Base de referencia para los depósitos existentes

Maneja los secretos legados al capturar nuevos:

# 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

Cambios recientes de auditoría durante el examen del código:

# 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

Escáner sin instalar Gitleaks localmente:

# 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

Crear patrones de detección específicos para la organización:

# 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

Buenas prácticas

  • Activar el precompromiso Hooks**: Use gitleaks protect en ganchos pre-commit para capturar secretos antes de entrar en la historia del git. Esta es tu primera línea de defensa.

Integrar en el CI/CD Early: Añadir Gitleaks a su oleoducto CI/CD lo antes posible. Fail construye cuando se detectan secretos para evitar que lleguen a la producción.

Use Baseline for Legacy Code: Al introducir Gitleaks a los repositorios existentes, crear una base de referencia para evitar abrumadores equipos con hallazgos históricos mientras todavía captan nuevos secretos.

  • Configuración personalizada: Extender las reglas predeterminadas con patrones específicos de organización. Añada sus formatos secretos internos y patrones de clave API al archivo .gitleaks.toml.

  • Mantenga un Permiso: Use los permisores con juicio por falsos positivos, pero documente por qué cada entrada es segura. Revise regularmente los permisores para asegurarse de que siguen siendo válidos.

  • Actuar en la producción: Usar siempre __INLINE_CODE_55_ bandera al ejecutar Gitleaks en CI/CD o entornos compartidos para evitar exponer secretos en registros e informes.

  • Scan Multiple Branchs: No escanee la rama principal. Configure CI/CD para escanear todas las ramas y obtener solicitudes para capturar secretos antes de que se fusionen.

  • ** Auditorías del Repositorio Completo Regional**: Ejecutar periódicamente escaneos completos de repositorio sin bases de referencia para asegurar que ningún secreto se haya deslizado y para capturar secretos introducidos a través de conflictos de fusión.

  • Educar Desarrolladores: Entrenar a tu equipo en lo que Gitleaks detecta y por qué. Comprender la herramienta reduce falsos positivos y aumenta la conciencia de seguridad.

  • Monitor Performance: Para los repositorios grandes, utilice --threads para optimizar el tiempo de exploración y considerar --max-target-megabytes para saltar grandes archivos binarios que ralentizan los escaneos.

Troubleshooting

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.
eterna No se puede escanear grandes repositorios ← Utilizar el análisis del rango de compromiso: --log-opts="-n 100" para escanear recientes commits. Aumente los límites de memoria si usa Docker. Considere el escaneo en trozos por rango de fecha. Silencio