HTML_TAG_80_📄 Genera Gitleaks PDF Guida_HTML_TAG_81 Traduzione:
Gitleaks Cheatsheet¶
Installazione¶
Tabella_84_
Comandi di base¶
Tabella_85_
Uso avanzato¶
Tabella_86_
Configurazione¶
Configuration File Location¶
Gitleaks cerca .gitleaks.toml nella root del repository per impostazione predefinita.
Struttura di configurazione di base¶
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''',
]
Configurazione delle regole avanzate¶
# 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"
Variabili ambientali¶
# 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: Integrazione del gancio pre-commesso¶
Evitare che i segreti si impegnino a livello locale:
# 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¶
Scansione segreta automatizzata nelle richieste di estrazione:
# .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 Integrazione¶
Aggiungi a __INLINE_CODE_52_:
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¶
Mantenere segreti legacy durante la cattura di nuovi:
# 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 recenti modifiche durante la revisione del codice:
# 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: Scanning basato su Docker¶
Scansione senza installazione 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: Regole doganali per l'organizzazione¶
Creare modelli di rilevamento specifici dell'organizzazione:
# 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
Migliori Pratiche¶
-
Abilita Pre-commit Hooks: Usa
gitleaks protect_ in ganci pre-commit per catturare segreti prima di entrare nella cronologia git. Questa e' la tua prima linea di difesa. -
Integrate in CI/CD Early. Aggiungi Gitleaks al tuo canale CI/CD il prima possibile. Fail costruisce quando i segreti vengono rilevati per impedire loro di raggiungere la produzione.
-
** Utilizzare Baseline per Codice Legacy**: Durante l'introduzione di Gitleaks ai repository esistenti, creare una linea di base per evitare squadre schiaccianti con risultati storici mentre ancora cattura nuovi segreti.
-
Configurazione personalizzata Estendere le regole predefinite con i modelli specifici dell'organizzazione. Aggiungi i tuoi formati segreti interni e i modelli chiave API al file
.gitleaks.toml. -
Maintain a Allowlist: Utilizzare le liste dei permessi in giudizio per i falsi positivi, ma documentare perché ogni voce è sicura. Verificare le liste dei permessi regolarmente per garantire che rimangano valide.
-
Redact in Production: Utilizzare sempre la bandiera
--redactquando si esegue Gitleaks in ambienti CI/CD o condivisi per evitare di esporre segreti nei registri e nei rapporti. -
Scan Multiple Branches. Non controllare il ramo principale. Configurare CI/CD per eseguire la scansione di tutti i rami e tirare richieste di catturare i segreti prima di essere fusi.
Regolare Full Repository Audits: eseguire periodicamente le scansioni del repository completo senza linee di base per garantire che nessun segreto è scivolato attraverso e per catturare i segreti introdotti attraverso conflitti di fusione.
Educate Developers: Allena il tuo team su ciò che Gitleaks rileva e perché. Capire lo strumento riduce i falsi positivi e aumenta la consapevolezza della sicurezza.
-
Monitor Performance # Per grandi repository, utilizzare
--threadsper ottimizzare il tempo di scansione e considerare--max-target-megabytesper saltare grandi file binari che rallentano le scansioni.¶
Risoluzione dei problemi¶
| 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. |
| Cannot scandisce grandi repository | Utilizzare la scansione dell'intervallo di commit: --log-opts="-n 100" per eseguire la scansione di impegni recenti. Aumentare i limiti di memoria se si utilizza Docker. Considera la scansione in pezzi per data range. # |