Skip to content

TruffleHog Cheatsheet

TruffleHog Cheatsheet

Installation

PlatformCommand
Linux (Script)curl -sSfL https://raw.githubusercontent.com/trufflesecurity/trufflehog/main/scripts/install.sh | sh -s -- -b /usr/local/bin
Debian/Ubuntuwget https://github.com/trufflesecurity/trufflehog/releases/download/v3.63.0/trufflehog_3.63.0_linux_amd64.deb && sudo dpkg -i trufflehog_3.63.0_linux_amd64.deb
RHEL/CentOS/Fedorawget https://github.com/trufflesecurity/trufflehog/releases/download/v3.63.0/trufflehog_3.63.0_linux_amd64.rpm && sudo rpm -i trufflehog_3.63.0_linux_amd64.rpm
macOS (Homebrew)brew install trufflehog
Windows (Scoop)scoop bucket add trufflesecurity https://github.com/trufflesecurity/scoop-bucket.git && scoop install trufflehog
Windows (Chocolatey)choco install trufflehog
Dockerdocker pull trufflesecurity/trufflehog:latest
From Sourcegit clone https://github.com/trufflesecurity/trufflehog.git && cd trufflehog && go install
Verify Installationtrufflehog --version

Basic Commands

CommandDescription
trufflehog --versionDisplay TruffleHog version
trufflehog --helpShow help information and available commands
trufflehog git file://. Scan current directory’s git repository
trufflehog git file:///path/to/repoScan local git repository at specified path
trufflehog git https://github.com/user/repo.gitScan remote GitHub repository
trufflehog git file://. --only-verifiedShow only verified secrets (active credentials)
trufflehog git file://. --jsonOutput results in JSON format
trufflehog git file://. --json > secrets.jsonSave scan results to JSON file
trufflehog filesystem --directory=/path/to/scanScan filesystem directory for secrets
trufflehog filesystem --directory=.Scan current directory recursively
trufflehog github --org=orgname --token=ghp_xxxxxScan all repositories in GitHub organization
trufflehog github --repo=https://github.com/user/repo --token=ghp_xxxxxScan specific GitHub repository
trufflehog gitlab --token=glpat-xxxxx --repo=https://gitlab.com/group/projectScan GitLab repository
trufflehog s3 --bucket=my-bucket --region=us-east-1Scan AWS S3 bucket for secrets
trufflehog docker --image=nginx:latestScan Docker image for embedded secrets
trufflehog git file://. --no-verificationScan without attempting to verify secrets
trufflehog git file://. --failExit with non-zero code if secrets found
trufflehog git --helpShow help for git scanning command

Advanced Usage

CommandDescription
trufflehog git file://. --since-commit=abc1234 --until-commit=def5678Scan specific commit range
trufflehog git file://. --since-commit=HEAD~100Scan last 100 commits
trufflehog git file://. --max-depth=50Limit scan to 50 most recent commits
trufflehog git file://. --branch=feature/new-apiScan specific branch only
trufflehog git file://. --branch=""Scan all branches in repository
trufflehog git file://. --config=custom-detectors.yamlUse custom detector configuration file
trufflehog git file://. --exclude-detectors="aws,generic-api-key"Exclude specific secret detectors
trufflehog git file://. --include-detectors="github,gitlab,slack"Include only specific detectors
trufflehog github --org=myorg --token=ghp_xxxxx --include-repos="backend-*,frontend-*"Scan GitHub org with repository pattern matching
trufflehog github --org=myorg --token=ghp_xxxxx --exclude-repos="*-archived"Exclude archived repositories from scan
trufflehog github --org=myorg --token=ghp_xxxxx --include-issues --include-pull-requestsScan GitHub issues and pull requests
trufflehog github --endpoint=https://github.company.com/api/v3 --org=myorg --token=xxxxxScan GitHub Enterprise instance
trufflehog gitlab --token=glpat-xxxxx --group=group-nameScan entire GitLab group
trufflehog filesystem --directory=/app --include-paths="*.env,*.config,*.yaml"Scan specific file patterns only
trufflehog filesystem --directory=/app --exclude-paths="node_modules/*,vendor/*"Exclude directories from filesystem scan
trufflehog git file://. --concurrency=10Set number of concurrent workers (default: 8)
trufflehog git file://. --no-updateSkip checking for updates
trufflehog s3 --bucket=my-bucket --key=AKIAXXXXX --secret=xxxxxScan S3 with explicit AWS credentials
trufflehog git file://. --allow-verification-overlapAllow multiple detectors to verify same secret
trufflehog git file://. --filter-entropy=4.5Set minimum entropy threshold (default: 3.0)

Configuration

Custom Detector Configuration

Create a custom detector configuration file to define your own secret patterns:

# 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

Create a .trufflehogignore file to exclude specific patterns:

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

Prevent secrets from being committed to your 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: Full Repository Audit Before Going Public

Audit an entire repository before making it public:

# 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

Automate scanning across all organization 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

Scan Docker images before deployment:

# 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: Continuous Monitoring with Scheduled Scans

Set up automated daily scanning:

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

Best Practices

  • Scan Early and Often: Integrate TruffleHog into your CI/CD pipeline to catch secrets before they reach production. Use pre-commit hooks for immediate feedback to developers.

  • Focus on Verified Secrets First: Use --only-verified flag to prioritize actively valid credentials that pose immediate security risks. Unverified matches may include false positives or expired credentials.

  • Scan Complete History: When auditing repositories, always scan the entire git history (trufflehog git file://. without commit limits) as secrets may exist in old commits that are still accessible.

  • Use Custom Detectors for Internal Systems: Create custom detector configurations for proprietary API keys, internal tokens, and company-specific secret patterns that built-in detectors won’t catch.

  • Implement Automated Remediation Workflows: When secrets are detected, have a documented process for immediate credential rotation, access revocation, and security incident logging.

  • Exclude False Positives Systematically: Use .trufflehogignore files to exclude test data, documentation examples, and known false positives rather than ignoring entire directories unnecessarily.

  • Monitor Third-Party Dependencies: Regularly scan vendor code, open-source dependencies, and Docker base images as they may contain embedded secrets or credentials.

  • Combine with Secret Management Tools: Use TruffleHog for detection but implement proper secret management solutions (HashiCorp Vault, AWS Secrets Manager) to prevent secrets from entering code in the first place.

  • Set Appropriate Entropy Thresholds: Adjust --filter-entropy based on your codebase to balance between catching secrets and minimizing false positives (default 3.0 works for most cases).

  • Archive and Analyze Scan Results: Store scan results with timestamps for compliance auditing, trend analysis, and demonstrating security posture improvements over time.

Troubleshooting

IssueSolution
”No git repository found”Ensure you’re in a git repository directory or use git init to initialize. For remote repos, check URL syntax and network connectivity.
High number of false positivesUse --only-verified to show only active secrets, increase --filter-entropy threshold (e.g., --filter-entropy=4.5), or create custom exclude patterns in .trufflehogignore.
Scan is very slow on large repositoriesUse --max-depth to limit commit history depth, --since-commit to scan recent changes only, or increase --concurrency value (e.g., --concurrency=16).
”Rate limit exceeded” for GitHubProvide authentication token with --token=ghp_xxxxx, wait for rate limit reset, or use GitHub Enterprise endpoint if available.
Docker scan fails with permission errorsRun Docker commands with sudo, add user to docker group (sudo usermod -aG docker $USER), or use docker run --rm -v $(pwd):/scan trufflesecurity/trufflehog:latest.
Secrets not being verifiedCheck internet connectivity for verification requests, use --allow-verification-overlap if multiple detectors should verify, or disable verification with --no-verification for offline scanning.
Out of memory errors on large scansReduce --concurrency value, scan in smaller commit ranges using --since-commit and --until-commit, or increase system memory allocation.
GitLab/GitHub Enterprise connection failsVerify custom endpoint URL with --endpoint flag, check token permissions (needs read access to repos), and ensure SSL certificates are valid.
JSON output is malformedEnsure you’re using latest TruffleHog version, redirect stderr separately (2>/dev/null), or use jq to validate and format output (trufflehog ... --json | jq).
Pre-commit hook not triggeringVerify hook is executable (chmod +x .git/hooks/pre-commit), check shebang line is correct (#!/bin/bash), and ensure TruffleHog is in PATH.
S3 scan authentication failsSet AWS credentials via environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY), use --key and --secret flags, or configure AWS CLI profile.
Custom detectors not workingValidate YAML syntax in config file, ensure regex patterns are properly escaped, verify detector names are unique, and test regex patterns separately.