Zum Inhalt
_ _

Truffle Hog Cheatsheet

• Installation

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

oder Grundlegende Befehle

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

/ Fortgeschrittene Nutzung

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)

Konfiguration

Individuelle Detector Konfiguration

Erstellen Sie eine benutzerdefinierte Detektorkonfigurationsdatei, um Ihre eigenen geheimen Muster zu definieren:

# 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}'

Umgebungsvariablen

# 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

Erstellen Sie eine .trufflehogignore-Datei, um bestimmte Muster auszuschließen:

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

CI/CD Integration Configuration

GitHub Aktionen

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

Häufige Anwendungsfälle

Use Case 1: PreCommit Hook for Secret Prevention

Verhindern Sie Geheimnisse vor der Verpflichtung zu Ihrem Repository:

# 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: Vollständiges Repository Audit vor der Öffentlichkeit

Prüfung eines gesamten Projektarchivs, bevor es veröffentlicht wird:

# 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: Scannen mehrerer Repositories in Organisation

Automatisches Scannen über alle Organisations-Repositories:

#!/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

Scannen von Docker-Bildern vor der Bereitstellung:

# 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={}

Use Case 5: Kontinuierliche Überwachung mit Scheduled Scans

Automatisches tägliches Scannen einrichten:

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

oder Best Practices

  • ** Scan Früh und oft*: Integrieren Sie Trüffel Steigen Sie in Ihre CI/CD-Pipeline, um Geheimnisse zu fangen, bevor sie die Produktion erreichen. Verwenden Sie vorkommit Haken für sofortiges Feedback an Entwickler.

  • **Focus on Verified Secrets First*: Verwenden Sie --only-verified Flagge, um aktiv gültige Anmeldeinformationen zu priorisieren, die unmittelbare Sicherheitsrisiken darstellen. Unverifizierte Spiele können falsche positive oder abgelaufene Anmeldeinformationen enthalten.

  • ** Vollständige Geschichte scannen*: Beim Auditieren von Repositories scannen Sie immer die gesamte Git-Geschichte (trufflehog git file://. ohne Limits), da Geheimnisse in alten Commits existieren können, die noch zugänglich sind.

  • **Benutzerdefinierte Detektoren für interne Systeme*: Erstellen Sie benutzerdefinierte Detektorkonfigurationen für proprietäre API-Tasten, interne Token und unternehmensspezifische geheime Muster, die eingebaute Detektoren nicht fangen.

  • **Implementieren Sie automatisierte Workflows*: Wenn Geheimnisse erkannt werden, haben Sie einen dokumentierten Prozess für sofortige Anmeldedrehung, Zugriff Widerruf und Sicherheitseinfall Protokollierung.

  • **Exclude Falsche Positive systematisch*: Verwenden Sie .trufflehogignore Dateien, um Testdaten, Dokumentationsbeispiele und bekannte falsche Positive auszuschließen, anstatt ganze Verzeichnisse unnötig zu ignorieren.

  • **Monitor Drittparteiabhängigkeiten*: Scannen Sie regelmäßig Herstellercode, Open-Source-Abhängigkeiten und Docker-Basisbilder, da sie eingebettete Geheimnisse oder Anmeldeinformationen enthalten können.

  • ** Kombinieren Sie mit Secret Management Tools*: Hog für die Erkennung, aber implementieren richtige geheime Management-Lösungen (HashiCorp Vault, AWS Secrets Manager), um zu verhindern, dass Geheimnisse an erster Stelle Code eingeben.

  • **Set Appropriate Entropy Thresholds*: Adjust --filter-entropy basierend auf Ihrer Codebasis, um zwischen einholenden Geheimnissen und der Minimierung falscher Positives auszugleichen (Standard 3.0 funktioniert für die meisten Fälle).

  • **Archive and Analyze Scan Results*: Speichern Sie Scan-Ergebnisse mit Zeitstempeln für Compliance-Auditing, Trendanalyse und demonstrieren Sie die Verbesserungen der Sicherheit im Laufe der Zeit.

Fehlerbehebung

Issue Solution
"No git repository found" Ensure you're in a git repository directory or use INLINE_CODE_63 to initialize. For remote repos, check URL syntax and network connectivity.
High number of false positives Use INLINE_CODE_64 to show only active secrets, increase INLINE_CODE_65 threshold (e.g., INLINE_CODE_66), or create custom exclude patterns in INLINE_CODE_67.
Scan is very slow on large repositories Use INLINE_CODE_68 to limit commit history depth, INLINE_CODE_69 to scan recent changes only, or increase INLINE_CODE_70 value (e.g., INLINE_CODE_71).
"Rate limit exceeded" for GitHub Provide authentication token with INLINE_CODE_72, wait for rate limit reset, or use GitHub Enterprise endpoint if available.
Docker scan fails with permission errors Run Docker commands with INLINE_CODE_73, add user to docker group (INLINE_CODE_74), or use INLINE_CODE_75.
Secrets not being verified Check internet connectivity for verification requests, use INLINE_CODE_76 if multiple detectors should verify, or disable verification with INLINE_CODE_77 for offline scanning.
Out of memory errors on large scans Reduce INLINE_CODE_78 value, scan in smaller commit ranges using INLINE_CODE_79 and INLINE_CODE_80, or increase system memory allocation.
GitLab/GitHub Enterprise connection fails Verify custom endpoint URL with INLINE_CODE_81 flag, check token permissions (needs read access to repos), and ensure SSL certificates are valid.
JSON output is malformed Ensure you're using latest TruffleHog version, redirect stderr separately (INLINE_CODE_82), or use INLINE_CODE_83 to validate and format output (INLINE_CODE_84).
Pre-commit hook not triggering Verify hook is executable (INLINE_CODE_85), check shebang line is correct (INLINE_CODE_86), and ensure TruffleHog is in PATH.
S3 scan authentication fails Set AWS credentials via environment variables (INLINE_CODE_87, INLINE_CODE_88), use INLINE_CODE_89 and INLINE_CODE_90 flags, or configure AWS CLI profile.
Kundendetektoren, die nicht arbeiten Gültige YAML-Syntax in config-Datei, sicherstellen, dass Regex-Muster richtig entkommen, überprüfen Detektornamen sind einzigartig, und testen Regex-Muster getrennt.