TruffleHog
Truffle Hog Cheatsheet
Instalación¶
| Platform | Command |
|---|---|
| Linux (Script) | INLINE_CODE_11 |
| Debian/Ubuntu | INLINE_CODE_12 |
| RHEL/CentOS/Fedora | INLINE_CODE_13 |
| macOS (Homebrew) | INLINE_CODE_14 |
| Windows (Scoop) | INLINE_CODE_15 |
| Windows (Chocolatey) | INLINE_CODE_16 |
| Docker | INLINE_CODE_17 |
| From Source | INLINE_CODE_18 |
| Verify Installation | INLINE_CODE_19 |
Comandos básicos¶
| Command | Description |
|---|---|
| INLINE_CODE_20 | Display TruffleHog version |
| INLINE_CODE_21 | Show help information and available commands |
| INLINE_CODE_22 | Scan current directory's git repository |
| INLINE_CODE_23 | Scan local git repository at specified path |
| INLINE_CODE_24 | Scan remote GitHub repository |
| INLINE_CODE_25 | Show only verified secrets (active credentials) |
| INLINE_CODE_26 | Output results in JSON format |
| INLINE_CODE_27 | Save scan results to JSON file |
| INLINE_CODE_28 | Scan filesystem directory for secrets |
| INLINE_CODE_29 | Scan current directory recursively |
| INLINE_CODE_30 | Scan all repositories in GitHub organization |
| INLINE_CODE_31 | Scan specific GitHub repository |
| INLINE_CODE_32 | Scan GitLab repository |
| INLINE_CODE_33 | Scan AWS S3 bucket for secrets |
| INLINE_CODE_34 | Scan Docker image for embedded secrets |
| INLINE_CODE_35 | Scan without attempting to verify secrets |
| INLINE_CODE_36 | Exit with non-zero code if secrets found |
| INLINE_CODE_37 | Show help for git scanning command |
Advanced Usage¶
| Command | Description |
|---|---|
| INLINE_CODE_38 | Scan specific commit range |
| INLINE_CODE_39 | Scan last 100 commits |
| INLINE_CODE_40 | Limit scan to 50 most recent commits |
| INLINE_CODE_41 | Scan specific branch only |
| INLINE_CODE_42 | Scan all branches in repository |
| INLINE_CODE_43 | Use custom detector configuration file |
| INLINE_CODE_44 | Exclude specific secret detectors |
| INLINE_CODE_45 | Include only specific detectors |
| INLINE_CODE_46 | Scan GitHub org with repository pattern matching |
| INLINE_CODE_47 | Exclude archived repositories from scan |
| INLINE_CODE_48 | Scan GitHub issues and pull requests |
| INLINE_CODE_49 | Scan GitHub Enterprise instance |
| INLINE_CODE_50 | Scan entire GitLab group |
| INLINE_CODE_51 | Scan specific file patterns only |
| INLINE_CODE_52 | Exclude directories from filesystem scan |
| INLINE_CODE_53 | Set number of concurrent workers (default: 8) |
| INLINE_CODE_54 | Skip checking for updates |
| INLINE_CODE_55 | Scan S3 with explicit AWS credentials |
| INLINE_CODE_56 | Allow multiple detectors to verify same secret |
| INLINE_CODE_57 | Set minimum entropy threshold (default: 3.0) |
Configuración¶
Configuración de detectores personalizados
Cree un archivo de configuración de detector personalizado para definir sus propios patrones secretos:
# custom-detectors.yaml
detectors:
- name: CustomAPIKey
keywords:
- custom_api_key
- customapikey
regex:
apikey: '[A-Za-z0-9]{32}'
verify:
- endpoint: 'https://api.example.com/verify'
unsafe: false
headers:
- 'Authorization: Bearer {apikey}'
successIndicators:
- '"status":"valid"'
failureIndicators:
- '"status":"invalid"'
- name: InternalToken
keywords:
- internal_token
- company_token
regex:
token: 'int_[A-Za-z0-9]{40}'
Environment Variables¶
# GitHub token for scanning private repositories
export GITHUB_TOKEN=ghp_xxxxxxxxxxxxx
# GitLab token for scanning
export GITLAB_TOKEN=glpat-xxxxxxxxxxxxx
# AWS credentials for S3 scanning
export AWS_ACCESS_KEY_ID=AKIAXXXXXXXXXXXXX
export AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export AWS_REGION=us-east-1
Exclude Patterns File¶
Crear un archivo .trufflehogignore para excluir patrones específicos:
# .trufflehogignore
# Exclude test files
**/test/**
**/tests/**
**/*_test.go
# Exclude dependencies
node_modules/
vendor/
.venv/
# Exclude specific false positives
docs/examples/fake-credentials.md
scripts/test-data.json
Configuración de integración CI/CD
GitHub Actions¶
# .github/workflows/trufflehog.yml
name: TruffleHog Secret Scanning
on: [push, pull_request]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: TruffleHog Scan
uses: trufflesecurity/trufflehog@main
with:
path: ./
base: ${{ github.event.repository.default_branch }}
head: HEAD
extra_args: --only-verified --fail
GitLab CI¶
# .gitlab-ci.yml
trufflehog-scan:
stage: security
image: trufflesecurity/trufflehog:latest
script:
- trufflehog git file://. --only-verified --fail --json > trufflehog-report.json
artifacts:
reports:
sast: trufflehog-report.json
when: always
allow_failure: false
Jenkins Pipeline¶
// Jenkinsfile
pipeline {
agent any
stages {
stage('Secret Scanning') {
steps {
sh '''
docker run --rm -v $(pwd):/scan \
trufflesecurity/trufflehog:latest \
git file:///scan --only-verified --fail
'''
}
}
}
}
Common Use Cases¶
Use Case 1: Pre-Commit Hook for Secret Prevention¶
Impida que los secretos se comprometan a su repositorio:
# Create pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
echo "Running TruffleHog secret scan..."
trufflehog git file://. --since-commit=HEAD --only-verified --fail
if [ $? -ne 0 ]; then
echo "⚠️ TruffleHog detected secrets! Commit aborted."
exit 1
fi
echo "✓ No secrets detected"
EOF
# Make executable
chmod +x .git/hooks/pre-commit
Use Case 2: Full Repository Audit before Going Public¶
Auditoría un repositorio completo antes de hacerlo público:
# Comprehensive scan of entire history
trufflehog git file://. --json --no-update > full-audit.json
# Review verified secrets only
trufflehog git file://. --only-verified --json | jq '.[] | {detector: .DetectorName, file: .SourceMetadata.Data.Git.file, commit: .SourceMetadata.Data.Git.commit}'
# Generate summary report
trufflehog git file://. --json | jq -r '.[] | "\(.DetectorName): \(.SourceMetadata.Data.Git.file)"' | sort | uniq -c | sort -rn
Use Case 3: Scanning Multiple Repositories in Organization¶
Automatizar el escaneo en todos los repositorios de la organización:
#!/bin/bash
# scan-org.sh
ORG_NAME="mycompany"
GITHUB_TOKEN="ghp_xxxxxxxxxxxxx"
OUTPUT_DIR="./scan-results"
mkdir -p $OUTPUT_DIR
# Scan entire organization
trufflehog github \
--org=$ORG_NAME \
--token=$GITHUB_TOKEN \
--only-verified \
--json > $OUTPUT_DIR/org-scan-$(date +%Y%m%d).json
# Generate summary
jq -r '.[] | "\(.SourceMetadata.Data.Github.repository): \(.DetectorName)"' \
$OUTPUT_DIR/org-scan-$(date +%Y%m%d).json | \
sort | uniq -c | sort -rn > $OUTPUT_DIR/summary.txt
echo "Scan complete. Results in $OUTPUT_DIR"
Use Case 4: Docker Image Security Scanning¶
Imágenes de Scan Docker antes del despliegue:
# Scan production image
trufflehog docker --image=myapp:latest --only-verified --json > docker-scan.json
# Scan multiple images
for image in nginx:latest postgres:14 redis:alpine; do
echo "Scanning $image..."
trufflehog docker --image=$image --only-verified
done
# Scan local images
docker images --format "{{.Repository}}:{{.Tag}}" | \
grep -v "<none>" | \
xargs -I {} trufflehog docker --image={}
Caso 5: Monitoreo continuo con escaneos programados¶
Escaneo diario automatizado:
# Create monitoring script
cat > /usr/local/bin/trufflehog-monitor.sh << 'EOF'
#!/bin/bash
REPOS_DIR="/opt/repositories"
REPORT_DIR="/var/log/trufflehog"
DATE=$(date +%Y%m%d)
mkdir -p $REPORT_DIR
for repo in $REPOS_DIR/*; do
if [ -d "$repo/.git" ]; then
repo_name=$(basename $repo)
echo "Scanning $repo_name..."
cd $repo
git pull --quiet
trufflehog git file://. --only-verified --json \
> $REPORT_DIR/${repo_name}-${DATE}.json
# Alert if secrets found
if [ $(jq length $REPORT_DIR/${repo_name}-${DATE}.json) -gt 0 ]; then
echo "⚠️ Secrets found in $repo_name" | \
mail -s "TruffleHog Alert: $repo_name" security@company.com
fi
fi
done
EOF
chmod +x /usr/local/bin/trufflehog-monitor.sh
# Add to crontab (daily at 2 AM)
echo "0 2 * * * /usr/local/bin/trufflehog-monitor.sh" | crontab -
Buenas prácticas¶
-
Scan Early y A menudo: Integrar Truffle Sube a su oleoducto CI/CD para capturar secretos antes de llegar a la producción. Utilice los ganchos pre-commit para la retroalimentación inmediata para los desarrolladores.
-
Focus on Verified Secrets First: Use
--only-verifiedbandera para priorizar credenciales válidas que plantean riesgos inmediatos de seguridad. Los partidos no verificados pueden incluir falsos positivos o credenciales expiradas. -
Historia completa de Escocia**: Al auditar los repositorios, escanee siempre toda la historia del git (
trufflehog git file://._ sin límites de compromiso) ya que los secretos pueden existir en los viejos compromisos que todavía son accesibles. -
Use Detectores Personalizados para Sistemas Internos: Crear configuraciones de detectores personalizados para claves patentadas de API, fichas internas y patrones secretos específicos de la empresa que los detectores incorporados no atraparán.
Implement Automated Remediation Workflows: Cuando se detectan secretos, tienen un proceso documentado para la rotación credencial inmediata, revocación de acceso y registro de incidentes de seguridad.
Exclude False Positives Systematically: Use .trufflehogignore_ ficheros para excluir datos de prueba, ejemplos de documentación y falsos positivos conocidos en lugar de ignorar directorios enteros innecesariamente.
Monitor Third-Party Dependencies: Explorar regularmente código de proveedores, dependencias de código abierto y imágenes de base de Docker, ya que pueden contener secretos o credenciales incrustadas.
- Combine with Secret Management Tools: Use Truffle Hog para la detección, pero implementar soluciones adecuadas de gestión secreta (HashiCorp Vault, AWS Secrets Manager) para evitar que los secretos entren en código en primer lugar.
Set Appropriate Entropy Thresholds: Adjust --filter-entropy basado en tu base de código para equilibrar entre capturar secretos y minimizar falsos positivos (default 3.0 trabaja para la mayoría de los casos).
Archive and Analyze Scan Results: Resultados de la exploración de la tienda con los tiempos para la auditoría de cumplimiento, el análisis de tendencias y la demostración de mejoras de la postura de seguridad con el tiempo.
Troubleshooting¶
__TABLE_101_ Los detectores de clientes que no funcionan TEN Validate Sintaxis YAML en el archivo de config, aseguran que los patrones de regex se escapan correctamente, verifican los nombres de los detectores son únicos, y prueba patrones de regex por separado. Silencio