9 min read

Intermediate

Secrets Scanning & Harvesting

Developers leak credentials constantly. API keys in commits, tokens in build logs, passwords in config files. Your job is to find them before (or after) they do.

Low-Hanging Fruit

Secret scanning is often the fastest path to initial access. A single leaked AWS key or GitHub token can compromise entire organizations.

Where Secrets Hide

📁 Source Code

  • Git history (deleted but recoverable)
  • Config files (.env, config.yml)
  • Hardcoded in source
  • Test files with real creds

🔧 CI/CD Artifacts

  • Build logs (masked but leaked)
  • Pipeline artifacts
  • Container layers
  • Debug outputs

☁️ Cloud & Infra

  • S3 buckets (public)
  • Instance metadata
  • Terraform state files
  • Kubernetes secrets (base64)

🌐 Public Exposure

  • Pastebin / Gists
  • Stack Overflow answers
  • Documentation sites
  • JS source maps

Secret Lifecycle & Exposure Points

TruffleHog

The gold standard for secret detection. Scans git history, verifies if secrets are still valid.

TruffleHog Commands
# Install
pip install trufflehog
# or
brew install trufflehog

# Scan a GitHub repo (includes all history)
trufflehog git https://github.com/target/repo --only-verified

# Scan local repo
trufflehog git file://. --only-verified

# Scan entire GitHub org
trufflehog github --org=target-org --only-verified

# Scan with all detectors (slower but thorough)
trufflehog git https://github.com/target/repo

# Output as JSON for parsing
trufflehog git https://github.com/target/repo --json > secrets.json

# Scan specific branch
trufflehog git https://github.com/target/repo --branch=develop

# Scan filesystem (non-git)
trufflehog filesystem /path/to/code

# Scan S3 bucket
trufflehog s3 --bucket=target-bucket

GitLeaks

GitLeaks Commands
# Install
brew install gitleaks
# or download from releases

# Scan repo (current state)
gitleaks detect --source=/path/to/repo

# Scan including git history
gitleaks detect --source=/path/to/repo --log-opts="--all"

# Scan remote repo
gitleaks detect --source=https://github.com/target/repo

# Output report
gitleaks detect --source=. --report-path=leaks.json --report-format=json

# Use custom rules
gitleaks detect --source=. --config=custom-rules.toml

# Scan staged changes (pre-commit hook)
gitleaks protect --staged

# Verbose output
gitleaks detect --source=. --verbose

GitHub Dorking

GitHub Search Queries for Secrets
# AWS Keys
org:targetcompany AWS_ACCESS_KEY_ID
org:targetcompany AKIA
filename:.env AWS_SECRET_ACCESS_KEY

# API Keys & Tokens
org:targetcompany api_key
org:targetcompany apikey
org:targetcompany api-key
org:targetcompany "Authorization: Bearer"

# Passwords
org:targetcompany password
org:targetcompany passwd
org:targetcompany "password ="
filename:config password

# Private Keys
org:targetcompany "BEGIN RSA PRIVATE KEY"
org:targetcompany "BEGIN OPENSSH PRIVATE KEY"
filename:id_rsa

# Database Credentials
org:targetcompany "mongodb+srv://"
org:targetcompany "postgres://"
org:targetcompany "mysql://"
org:targetcompany connection_string

# Cloud Config
org:targetcompany "client_secret"
org:targetcompany "subscription_id"
org:targetcompany "tenant_id"

# Specific Files
org:targetcompany filename:.env
org:targetcompany filename:credentials
org:targetcompany filename:secrets.yml
org:targetcompany filename:.npmrc _authToken

CI/CD Log Harvesting

Extracting Secrets from Build Logs
# GitHub Actions logs
# Go to: Actions > Workflow Run > Download logs
# Or via API:
curl -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/owner/repo/actions/runs/RUN_ID/logs

# Common leakage patterns in logs:
# - echo statements printing env vars
# - Debug mode enabled
# - Error messages with connection strings
# - npm install showing .npmrc content

# Search downloaded logs
grep -r "password|secret|key|token|api" logs/

# Jenkins console output
curl -u user:token http://jenkins/job/JobName/lastBuild/consoleText | \
  grep -i "password|secret|key|token"

# GitLab job logs
curl --header "PRIVATE-TOKEN: $TOKEN" \
  "https://gitlab.com/api/v4/projects/ID/jobs/JOB_ID/trace"

Secret Patterns

Secret Type Pattern Example
AWS Access Key AKIA[0-9A-Z]16 AKIAIOSFODNN7EXAMPLE
GitHub Token ghp_[a-zA-Z0-9]36 ghp_xxxxxxxxxxxxxxxxxxxx
Slack Token xox[baprs]-[0-9a-zA-Z-]+ xoxb-123456789-abcdefgh
Private Key -----BEGIN .* PRIVATE KEY----- -----BEGIN RSA PRIVATE KEY-----
JWT eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]* eyJhbGciOiJIUzI1NiIs...
Stripe Key sk_live_[0-9a-zA-Z]24 sk_live_xxxxxxxxxxxxxxxx

Container Layer Analysis

Finding Secrets in Docker Layers
# Pull and analyze image layers
docker pull target-image:latest

# Use dive to explore layers
dive target-image:latest
# Look for: .env files, config files, removed secrets

# Extract all layers manually
docker save target-image:latest -o image.tar
tar -xf image.tar
# Each layer is a tar, extract and search

# Search extracted layers
find . -name "*.tar" -exec tar -tf {} \; | grep -i "env|config|secret"

# Use container-diff
container-diff analyze target-image:latest --type=file

# Trivy for secrets in images
trivy image --scanners secret target-image:latest

Validating Found Secrets

Testing Leaked Credentials
# AWS - Test if key is valid
aws sts get-caller-identity

# GitHub - Test token
curl -H "Authorization: token LEAKED_TOKEN" https://api.github.com/user

# Slack - Test token  
curl -X POST https://slack.com/api/auth.test -d "token=LEAKED_TOKEN"

# Stripe - Test key
curl https://api.stripe.com/v1/charges -u sk_live_LEAKED:

# Google Cloud - Test service account
gcloud auth activate-service-account --key-file=leaked-key.json
gcloud projects list

# Azure - Test credentials
az login --service-principal -u CLIENT_ID -p CLIENT_SECRET --tenant TENANT_ID

# NPM - Test token
npm whoami --registry=https://registry.npmjs.org --//registry.npmjs.org/:_authToken=LEAKED

# TruffleHog validates automatically with --only-verified flag

Tools

Real-World: Uber Breach via Hardcoded Credentials (2016)

Engineers committed AWS credentials into a private GitHub repo. Attackers accessed the repo, found the keys, and exfiltrated data on 57 million riders and drivers. The breach resulted in a $148M settlement. Lesson: Private repos are not secret vaults — scan everything.

Secrets Scanning Labs

Practice finding and remediating leaked secrets.

Git History Secret Mining Custom Lab easy
Clone a repository with intentionally committed secrets in old commitsRun TruffleHog with --since-commit and --entropy flagsRun Gitleaks with a custom .gitleaks.toml configCompare results: TruffleHog (verified) vs Gitleaks (regex) vs HardcodesUse git-filter-repo to permanently remove secrets from history
CI/CD Log Harvesting Custom Lab medium
Access a Jenkins/GitLab instance and review build console outputSearch for masked and unmasked secrets in build logsCheck environment variable dumps from debug stepsAnalyze artifact stores for bundled .env or credentials filesImplement log redaction and secret masking policies

📋 Framework Alignment

OWASP CI/CD: CICD-SEC-6 (Insufficient Credential Hygiene), CICD-SEC-7 (Insecure System Configuration) | MITRE ATT&CK: T1552.001 (Credentials In Files), T1552.004 (Private Keys) | CIS Controls: 16.4 (Establish Process for Credential Mgmt), 3.12 (Network Segment Sensitive Data)

Evidence to Capture

A secret finding is a claim about liveness and exposure window. The string itself is the least useful part of it, and the least safe to paste into a report.

Location and revision: Commit SHA, file path and line, plus whether the value is still present at HEAD or only reachable through history.

Detector and rule: Tool, version and rule identifier, so a second person can reproduce the hit and know why the pattern matched.

Verification state: Whether the value authenticated against the provider, and what the response told you (identity, scope, permissions). Describe the response, never the secret.

Credential identity and expiry: The account or role the credential maps to, its scopes, and its expiry. Together these set the impact, and they are usually what the client did not know.

Exposure window: First commit date through revocation date, with whether the repository, log or artefact was publicly reachable during that window.

Leak channel: Where the value actually surfaced: git history, a build log line, an image layer, an uploaded artefact or a public paste, with the retrieval date.

Likely False Positives

Secret scanning is a regex business, and most raw hits are not credentials. Verification is what turns a hit into a finding.

  • Placeholder or example value: Documentation keys such as the AWS example access key match the pattern perfectly and authenticate against nothing. Check the value against the provider before escalating.
  • Already expired or revoked: A credential that stopped working before discovery is a hygiene finding. Say so plainly rather than implying live access.
  • Synthetic test fixture: Test suites contain fake tokens on purpose. If the value is not a real credential, the finding is that a scanner will keep flagging it, not a breach.
  • Unverified regex hit: A detector run without verification produces candidates. Treat them as leads and never as findings until something authenticates.
  • Masked log value: A masked value in a build log is redaction working. It is a finding only if you can reconstruct the value from the surrounding output.
  • Never left the machine: A commit on a local branch that was never pushed has no exposure window and no third party, so the response is rotation and cleaner pre-commit hooks.

Testing Checklist

Scope and tooling

  • ☐ Full git history scanned, not just the current tree
  • ☐ Both a verified scanner and a rules-based scanner run, results compared
  • ☐ Build logs and artefacts included in scope
  • ☐ Container image layers included in scope
  • ☐ Public exposure checked separately (forks, pastes, dumps)
  • ☐ Tool versions and rule sets recorded for the report

Triage and verification

  • ☐ Every candidate classified as live, revoked, placeholder or unknown
  • ☐ Live credentials validated with a read-only call only
  • ☐ Identity and scope of each live credential recorded
  • ☐ Detection time and revocation time captured for the window
  • ☐ Blast radius traced (what the credential can reach)
  • ☐ Owner and rotation path identified per credential

Containment

  • ☐ Credential rotated, not just deleted from the file
  • ☐ Old value confirmed dead by testing it afterwards
  • ☐ Access logs reviewed for use during the exposure window
  • ☐ Downstream systems that cached the secret updated
  • ☐ History rewrite decision recorded with its trade-offs
  • ☐ Push protection and pre-commit hooks enabled to stop the next one

Remediation

Containment

  • • Rotate first and clean the repository second: a value removed from history but still valid is still live for anyone who already cloned it.
  • • Review the credential provider access logs for the whole exposure window, because rotation tells you nothing about what was already done.
  • • Rewrite history only after rotation and after confirming no active clones need the old commits; git filter-repo is a coordination exercise, not a cleanup step.
  • • Invalidate any cached copy: artefact stores, package caches, CI cache volumes and image layers that embedded the value.

Prevention

  • • Enable provider push protection so a live credential cannot be committed at all, and enable the same scanning on every fork and mirror.
  • • Move to short-lived credentials: OIDC federation for cloud, workload identity for registries, so there is no long-lived value to leak.
  • • Mask and redact at the pipeline level, and disable debug echo of environment variables so the log channel stops being a leak channel.
  • • Run a pre-commit scanner locally and the same rules in CI, so the developer sees the hit before the pipeline does.

CWE References: CWE-798, CWE-532, CWE-522