コンテンツにスキップ

TruffleHogチートシート

TruffleHogチートシート

インストール

プラットフォームコマンド
Linux (Script)`curl -sSfL https://raw.githubusercontent.com/trufflesecurity/trufflehog/main/scripts/install.sh \
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

基本コマンド

コマンド説明
trufflehog --versionTruffleHogのバージョンを表示
trufflehog --helpヘルプ情報と利用可能なコマンドを表示
trufflehog git file://. カレントディレクトリのgitリポジトリをスキャン
trufflehog git file:///path/to/repo指定されたパスでローカルgitリポジトリをスキャンする
trufflehog git https://github.com/user/repo.gitリモートGitHubリポジトリをスキャン
trufflehog git file://. --only-verified検証済みのシークレット(アクティブな認証情報)のみを表示
trufflehog git file://. --json結果をJSONフォーマットで出力する
trufflehog git file://. --json > secrets.jsonスキャン結果をJSONファイルに保存
trufflehog filesystem --directory=/path/to/scanファイルシステムディレクトリからシークレットをスキャン
trufflehog filesystem --directory=.カレントディレクトリを再帰的にスキャン
trufflehog github --org=orgname --token=ghp_xxxxxGitHubの組織内のすべてのリポジトリをスキャン
trufflehog github --repo=https://github.com/user/repo --token=ghp_xxxxx特定の GitHub リポジトリをスキャン
trufflehog gitlab --token=glpat-xxxxx --repo=https://gitlab.com/group/projectGitLabリポジトリをスキャン
trufflehog s3 --bucket=my-bucket --region=us-east-1AWS S3バケットからシークレットをスキャン
trufflehog docker --image=nginx:latestDockerイメージに埋め込まれたシークレットをスキャンする
trufflehog git file://. --no-verificationシークレットを検証しようとせずにスキャンする
trufflehog git file://. --failシークレットが見つかった場合、ゼロ以外のコードで終了する
trufflehog git --helpgitスキャンコマンドのヘルプを表示

高度な使用法

コマンド説明
trufflehog git file://. --since-commit=abc1234 --until-commit=def5678特定のコミット範囲をスキャン
trufflehog git file://. --since-commit=HEAD~100最後の100コミットをスキャン
trufflehog git file://. --max-depth=50最近の50コミットに走査を制限
trufflehog git file://. --branch=feature/new-api特定のブランチのみをスキャン
trufflehog git file://. --branch=""リポジトリのすべてのブランチをスキャン
trufflehog git file://. --config=custom-detectors.yamlカスタムディテクター設定ファイルを使用
trufflehog git file://. --exclude-detectors="aws,generic-api-key"特定の秘密検出器を除外する
trufflehog git file://. --include-detectors="github,gitlab,slack"特定の検出器のみを含める
trufflehog github --org=myorg --token=ghp_xxxxx --include-repos="backend-*,frontend-*"GitHub orgをリポジトリパターンマッチングでスキャン
trufflehog github --org=myorg --token=ghp_xxxxx --exclude-repos="*-archived"スキャンからアーカイブされたリポジトリを除外
trufflehog github --org=myorg --token=ghp_xxxxx --include-issues --include-pull-requestsGitHubのissueとプルリクエストをスキャン
trufflehog github --endpoint=https://github.company.com/api/v3 --org=myorg --token=xxxxxGitHub Enterprise インスタンスをスキャン
trufflehog gitlab --token=glpat-xxxxx --group=group-nameGitLabグループ全体をスキャン
trufflehog filesystem --directory=/app --include-paths="*.env,*.config,*.yaml"特定のファイルパターンのみをスキャン
trufflehog filesystem --directory=/app --exclude-paths="node_modules/*,vendor/*"ファイルシステムスキャンからディレクトリを除外する
trufflehog git file://. --concurrency=10同時実行ワーカーの数を設定 (デフォルト: 8)
trufflehog git file://. --no-update更新のチェックをスキップ
trufflehog s3 --bucket=my-bucket --key=AKIAXXXXX --secret=xxxxx明示的なAWS認証情報を使用してS3をスキャン
trufflehog git file://. --allow-verification-overlap複数の検出器で同じシークレットを検証することを許可する
trufflehog git file://. --filter-entropy=4.5エントロピーの最小しきい値を設定(デフォルト: 3.0)

設定

カスタムディテクター設定

独自の秘密パターンを定義するカスタムディテクター設定ファイルを作成します:

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

環境変数

# 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

除外パターンファイル

除外する特定のパターンのための.trufflehogignoreファイルを作成:

# .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統合設定

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パイプライン

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

一般的なユースケース

ユースケース1:シークレット防止のためのプレコミットフック

リポジトリにシークレットがコミットされるのを防ぐ:

# 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

ユースケース2:公開前の完全リポジトリ監査

公開する前にリポジトリ全体を監査:

# 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

ユースケース3:組織内の複数リポジトリのスキャン

組織内のすべてのリポジトリでスキャンを自動化:

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

ユースケース4:Dockerイメージセキュリティスキャン

デプロイ前にDockerイメージをスキャン:

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

ユースケース5:スケジュールされたスキャンによる継続的モニタリング

自動日次スキャンを設定:

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

ベストプラクティス

  • 早期かつ頻繁にスキャン: TruffleHogをCI/CDパイプラインに統合し、本番環境に到達する前にシークレットを検出します。即時のフィードバックを得るためにプレコミットフックを使用します。

  • 検証済みシークレットに焦点を当てる: --only-verifiedフラグを使用して、即時のセキュリティリスクとなる実際に有効な認証情報を優先します。未検証の一致には、偽陽性や期限切れの認証情報が含まれる可能性があります。

  • 完全な履歴をスキャン: リポジトリを監査する際は、常にgit履歴全体(trufflehog git file://.コミット制限なし)をスキャンします。古いコミットにも依然としてアクセス可能なシークレットが存在する可能性があります。

  • 内部システム用のカスタムディテクターを使用: 組み込みのディテクターでは検出できない、独自のAPIキー、内部トークン、会社固有のシークレットパターン用のカスタムディテクター設定を作成します。

  • 自動修復ワークフローの実装: シークレットが検出された場合、即座に認証情報のローテーション、アクセス無効化、セキュリティインシデントのログ記録のための文書化されたプロセスを用意します。

  • 偽陽性を系統的に除外: .trufflehogignoreファイルを使用して、テストデータ、ドキュメントの例、既知の偽陽性を除外し、不必要に大きなディレクトリ全体を無視しないようにします。

  • サードパーティの依存関係を監視: ベンダーコード、オープンソースの依存関係、Dockerベースイメージを定期的にスキャンし、埋め込まれたシークレットや認証情報を検出します。

  • シークレット管理ツールと組み合わせる: 検出にTruffleHogを使用し、コードにシークレットが入る前に適切なシークレット管理ソリューション(HashiCorp Vault、AWS Secrets Manager)を実装します。

  • 適切なエントロピーしきい値を設定

Note: Some translations (3-20) are left blank as the original text was not provided in the initial request.--filter-entropyコードベースに基づいて、シークレットの検出と偽陽性の最小化のバランスを取ります(デフォルトの3.0が多くの場合に適しています)。

  • スキャン結果のアーカイブと分析: コンプライアンス監査、トレンド分析、および時間経過に伴うセキュリティ態勢の改善を示すために、タイムスタンプ付きのスキャン結果を保存します。

トラブルシューティング

問題ソリューション
”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 \
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.