콘텐츠로 이동

custom-detectors.yaml

플랫폼명령어
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비밀이 발견되면 0이 아닌 코드로 종료
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 조직을 리포지토리 패턴 매칭으로 스캔
trufflehog github --org=myorg --token=ghp_xxxxx --exclude-repos="*-archived"보관된 저장소를 스캔에서 제외
trufflehog github --org=myorg --token=ghp_xxxxx --include-issues --include-pull-requestsGitHub 이슈와 풀 리퀘스트 스캔하기
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}'
```## 고급 사용법
```bash
# 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`### 사용자 정의 탐지기 구성
```text
# .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
```사용자 정의 탐지기 구성 파일을 생성하여 고유한 비밀 패턴을 정의합니다:
```yaml
# .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.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
```### 환경 변수
```groovy
// 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
                '''
            }
        }
    }
}
# 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
```### 제외 패턴 파일
```bash
# 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
```특정 패턴을 제외하기 위한 ```bash
#!/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"
```파일을 생성합니다:
```bash
# 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={}
# 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 -
```### CI/CD 통합 구성
`--only-verified`#### GitHub Actions
`trufflehog git file://.`
`.trufflehogignore`#### GitLab CI
`--filter-entropy`코드베이스를 기반으로 비밀 정보 감지와 거짓 양성(false positive) 최소화 사이의 균형을 맞추기 위해 (기본값 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 positives** | Use `--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 repositories** | Use `--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 GitHub** | Provide authentication token with `--token=ghp_xxxxx`, wait for rate limit reset, or use GitHub Enterprise endpoint if available. |
| **Docker scan fails with permission errors** | Run 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 verified** | Check 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 scans** | Reduce `--concurrency` value, scan in smaller commit ranges using `--since-commit` and `--until-commit`, or increase system memory allocation. |
| **GitLab/GitHub Enterprise connection fails** | Verify custom endpoint URL with `--endpoint` 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 (`2>/dev/null`), or use `jq` to validate and format output (`trufflehog ... --json \ | jq`). |
| **Pre-commit hook not triggering** | Verify 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 fails** | Set AWS credentials via environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`), use `--key` and `--secret` flags, or configure AWS CLI profile. || **사용자 정의 탐지기 작동 안 함** | YAML 구성 파일의 구문을 확인하고, 정규식 패턴이 제대로 이스케이프되었는지 확인하며, 탐지기 이름이 고유한지 검증하고, 정규식 패턴을 별도로 테스트하세요. |