Pular para o conteúdo

custom-detectors.yaml

PlataformaComando
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
ComandoDescrição
trufflehog --versionExibir versão do TruffleHog
trufflehog --helpMostrar informações de ajuda e comandos disponíveis
trufflehog git file://. Escanear repositório git do diretório atual
trufflehog git file:///path/to/repoEscanear repositório git local no caminho especificado
trufflehog git https://github.com/user/repo.gitEscanear repositório GitHub remoto
trufflehog git file://. --only-verifiedMostrar apenas segredos verificados (credenciais ativas)
trufflehog git file://. --jsonResultados de saída em formato JSON
trufflehog git file://. --json > secrets.jsonSalvar resultados de varredura em arquivo JSON
trufflehog filesystem --directory=/path/to/scanVerificar diretório do sistema de arquivos em busca de segredos
trufflehog filesystem --directory=.Digitalizar diretório atual recursivamente
trufflehog github --org=orgname --token=ghp_xxxxxDigitalizar todos os repositórios na organização do GitHub
trufflehog github --repo=https://github.com/user/repo --token=ghp_xxxxxEscanear repositório específico do GitHub
trufflehog gitlab --token=glpat-xxxxx --repo=https://gitlab.com/group/projectEscanear repositório GitLab
trufflehog s3 --bucket=my-bucket --region=us-east-1Escanear bucket AWS S3 em busca de segredos
trufflehog docker --image=nginx:latestDigitalizar imagem Docker em busca de segredos embutidos
trufflehog git file://. --no-verificationDigitalizar sem tentar verificar segredos
trufflehog git file://. --failSair com código não zero se segredos forem encontrados
trufflehog git --helpMostrar ajuda para o comando de varredura do git
ComandoDescrição
trufflehog git file://. --since-commit=abc1234 --until-commit=def5678Varrer intervalo de commits específico
trufflehog git file://. --since-commit=HEAD~100Escanear últimos 100 commits
trufflehog git file://. --max-depth=50Limitar varredura para os 50 commits mais recentes
trufflehog git file://. --branch=feature/new-apiEscanear apenas branch específica
trufflehog git file://. --branch=""Verificar todos os branches no repositório
trufflehog git file://. --config=custom-detectors.yamlUse arquivo de configuração de detector personalizado
trufflehog git file://. --exclude-detectors="aws,generic-api-key"Excluir detectores de segredos específicos
trufflehog git file://. --include-detectors="github,gitlab,slack"Incluir apenas detectores específicos
trufflehog github --org=myorg --token=ghp_xxxxx --include-repos="backend-*,frontend-*"Escanear organização do GitHub com padrão de correspondência de repositório
trufflehog github --org=myorg --token=ghp_xxxxx --exclude-repos="*-archived"Excluir repositórios arquivados da varredura
trufflehog github --org=myorg --token=ghp_xxxxx --include-issues --include-pull-requestsEscanear issues e pull requests do GitHub
trufflehog github --endpoint=https://github.company.com/api/v3 --org=myorg --token=xxxxxDigitalizar instância do GitHub Enterprise
trufflehog gitlab --token=glpat-xxxxx --group=group-nameDigitalizar todo o grupo do GitLab
trufflehog filesystem --directory=/app --include-paths="*.env,*.config,*.yaml"Digitalizar apenas padrões de arquivos específicos
trufflehog filesystem --directory=/app --exclude-paths="node_modules/*,vendor/*"Excluir diretórios da varredura do sistema de arquivos
trufflehog git file://. --concurrency=10Definir número de workers concorrentes (padrão: 8)
trufflehog git file://. --no-updateIgnorar verificação de atualizações
trufflehog s3 --bucket=my-bucket --key=AKIAXXXXX --secret=xxxxxDigitalizar S3 com credenciais AWS explícitas
trufflehog git file://. --allow-verification-overlapPermitir que múltiplos detectores verifiquem o mesmo segredo
trufflehog git file://. --filter-entropy=4.5Definir limite mínimo de entropia (padrão: 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}'
```## Uso Avançado
```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
```## Configuração
`.trufflehogignore`### Configuração de Detector Personalizado
```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
```Crie um arquivo de configuração de detector personalizado para definir seus próprios padrões de segredos:
```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
```### Variáveis de Ambiente
```yaml
# .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
```### Arquivo de Padrões de Exclusão
```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
                '''
            }
        }
    }
}
```Crie um arquivo para excluir padrões específicos:
```bash
# 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
```### Configuração de Integração CI/CD
```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
```#### GitHub Actions
```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"
```#### GitLab CI
```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={}
```#### Pipeline do Jenkins
```bash
# 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 -
```## Casos de Uso Comuns
`--only-verified`### Caso de Uso 1: Hook de Pré-Commit para Prevenção de Segredos
`trufflehog git file://.`Previna segredos de serem commitados no seu repositório:
`.trufflehogignore`### Caso de Uso 2: Auditoria Completa do Repositório Antes de Torná-lo Público
`--filter-entropy`com base no seu código para equilibrar entre detectar segredos e minimizar falsos positivos (o padrão 3.0 funciona para a maioria dos casos).

- **Arquivar e Analisar Resultados de Varredura**: Armazene resultados de varredura com carimbos de tempo para auditoria de conformidade, análise de tendências e demonstração de melhorias na postura de segurança ao longo do tempo.

## Resolução de Problemas

| Problema | Solução |
|-------|----------|
| **"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. || **Detectores personalizados não funcionando** | Valide a sintaxe YAML no arquivo de configuração, certifique-se de que os padrões de expressão regular estejam corretamente escapados, verifique se os nomes dos detectores são únicos e teste os padrões de expressão regular separadamente. |