12.8M
Secrets exposed in public GitHub repositories in 2023, up 28% from 2022 (GitGuardian State of Secrets Sprawl)
5 years
Average age of a leaked secret still valid and being exploited when discovered by GitGuardian's monitoring
46 seconds
Average time between a secret being pushed to GitHub and its first use by an automated attacker scanner
90%
Of secrets found in source code originate from developer tools (IDE plugins, CLI tools, local .env files accidentally committed)

SponsoredRetool

Retool's new app builder is where AI-generated code ships safely

Building apps with AI is easy. Getting them to production safely is another story.

Start building for free today

The fastest path from a developer laptop to a cloud account compromise runs through a .env file committed to a git repository. Automated scanners index public GitHub continuously and begin testing discovered credentials within seconds of a commit. Internal repositories carry the same risk once an attacker gains initial access to your network or developer environment. A layered secrets detection program: pre-commit prevention, CI/CD gate scanning, continuous repository monitoring: makes secrets leaks detectable before they become incidents.

Prevention: Pre-Commit Hook Scanning with Gitleaks

Gitleaks is an open-source secrets scanner that runs as a pre-commit hook, blocking commits that contain detected secrets before they enter the repository.

Install Gitleaks as a pre-commit hook

Install Gitleaks via brew install gitleaks or download the binary. Add to your project's .pre-commit-config.yaml: repos: [{repo: 'https://github.com/gitleaks/gitleaks', rev: 'v8.21.0', hooks: [{id: gitleaks}]}]. Run pre-commit install to activate. Every git commit now runs Gitleaks before the commit lands.

Configure a custom ruleset for your environment

Create a .gitleaks.toml in the project root to add rules for secrets unique to your environment (internal API key formats, database connection string patterns). Also add a [allowlist] section with regexes for known false positives: test API keys in test fixture files, for example. The default ruleset covers AWS keys, GitHub tokens, Stripe keys, and 150+ other patterns.

Enforce pre-commit in CI to catch developers who skip local hooks

Pre-commit hooks can be bypassed with --no-verify. Add a Gitleaks scan step to your CI pipeline that runs on every PR: gitleaks detect --source . --log-opts 'origin/main..HEAD'. This scans only the commits in the PR, not the entire history, keeping scan time under 10 seconds for typical PRs. Fail the PR check if Gitleaks finds a secret.

Scan .env and config files explicitly

Add --include '*.env,*.env.*,config/*.yml,*.json' to your Gitleaks command to explicitly scan config file patterns. Many teams exclude these from .gitignore but forget that historical commits may include them. Gitleaks will catch them in new commits; Trufflehog covers the history scan.

Detection: Scanning Git History with Trufflehog

Trufflehog scans git history entropy and pattern matches to find secrets that may have been committed months or years ago. It is the go-to tool for retroactive repository audits.

Run a full repository history scan

trufflehog git file://. --only-verified scans the entire commit history of the current repository and only reports secrets that successfully authenticate against their respective service (live key verification). This dramatically reduces false positives: a finding from --only-verified is a confirmed live credential, not just a pattern match.

Scan across all repositories in your organization

trufflehog github --org=your-org-name --token=$GITHUB_TOKEN scans all repositories in a GitHub organization. Run this as a scheduled nightly scan and pipe output to your SIEM or alerting system. For GitLab: trufflehog gitlab --token=$GITLAB_TOKEN. For Bitbucket: use the --endpoint flag.

Scan CI/CD pipeline logs and artifacts

trufflehog docker --image=your-registry/image:tag scans container image layers for secrets baked into the build. trufflehog s3 --bucket=your-build-bucket scans build artifact storage. Pipeline logs can contain secrets printed by misconfigured debug logging: scan them as part of the initial discovery.

Respond to findings: invalidate first, then remove from history

When Trufflehog finds a live secret: (1) immediately invalidate the credential through the issuing service: do not wait to assess scope first; (2) check access logs for the credential's use since the commit date; (3) open a security investigation if unauthorized use is found; (4) only after invalidation, optionally use git-filter-repo or BFG Repo-Cleaner to remove the secret from history. Removing from history does not invalidate the credential: always rotate first.

Free daily briefing

Briefings like this, every morning before 9am.

Threat intel, active CVEs, and campaign alerts, distilled for practitioners. 50,000+ subscribers. No noise.

Continuous Monitoring: GitGuardian for Enterprise Environments

GitGuardian provides continuous real-time scanning across all repositories, CI/CD systems, and developer tools with sub-minute detection latency and automated alerting to repository owners.

Connect GitGuardian to your SCM and CI/CD

GitGuardian integrates with GitHub, GitLab, Bitbucket, Azure DevOps, and CI/CD platforms via webhooks. Every push event triggers a scan. The integration takes under 30 minutes to deploy organization-wide. GitGuardian's Public Monitoring feature also alerts you when secrets associated with your organization's domains appear in public repositories outside your control.

Use GitGuardian's developer workflow integrations

GitGuardian provides a VS Code extension, a JetBrains plugin, and a CLI (ggshield) that scan locally before code leaves the developer's machine. Installing ggshield as a pre-commit hook via ggshield secret scan pre-commit adds an additional layer before code reaches the SCM. The enterprise license includes developer-facing remediation guidance so developers can fix the finding without security team intervention.

Triage incidents using GitGuardian's ITSM integrations

GitGuardian integrates with Jira, PagerDuty, and Slack to create incidents and notify repository owners automatically. Configure per-secret-type severity thresholds: AWS access keys trigger a P1 PagerDuty alert; internal configuration passwords create a Jira ticket for the team. This automates the first-mile response without requiring the security team to manually triage every finding.

Remediation: Secrets Rotation Workflows

A detected secret requires immediate rotation. Establish a rotation runbook before a detection event so that rotation happens in minutes, not hours.

Establish a secrets rotation checklist per secret type

AWS IAM keys: IAM console > Access Keys > Deactivate > create new key > update application > delete old key. GitHub PATs: Settings > Developer Settings > Tokens > Revoke > create scoped replacement. Database passwords: rotate in secrets manager (AWS Secrets Manager, HashiCorp Vault) which propagates to applications via secret rotation Lambda/Vault agent. Document the rotation procedure for every credential type in your environment before an incident requires it.

Use environment-specific secrets with automated rotation

Move credentials from source code to a secrets manager: AWS Secrets Manager (automatic rotation for RDS, Redshift, DocumentDB), HashiCorp Vault (dynamic secrets: credentials that expire automatically and are never stored statically), Azure Key Vault, or GCP Secret Manager. Applications retrieve secrets at runtime via SDK rather than environment variables or config files. This eliminates the class of leaks that come from config files committed by accident.

Check if the leaked credential was used before rotation

For AWS keys: CloudTrail > Event History > filter by the Access Key ID, sorted by earliest event. For GitHub tokens: check the token's activity via the GitHub API audit log. For Stripe/Twilio/SendGrid API keys: check their respective access logs and usage dashboards. If you find unauthorized usage, escalate from rotation to incident response: preserve evidence, engage IR team, assess blast radius.

The bottom line

The 46-second window between a public GitHub commit and the first automated credential test is not a statistic to debate -- it is an architectural constraint that makes pre-commit prevention non-negotiable. Deploy Gitleaks as a pre-commit hook today, add a Gitleaks scan to every PR's CI pipeline as a second layer, and schedule a monthly Trufflehog --only-verified scan across all repositories to surface historical leaks. Any confirmed live credential found by scanning should be rotated within 15 minutes and treated as a potential incident pending access log review.

Frequently asked questions

What is the difference between Gitleaks and Trufflehog?

Gitleaks is optimized for prevention (pre-commit hooks and CI/CD gates): it is fast, runs on each commit, and has a broad pattern ruleset covering 150+ secret types. Trufflehog is optimized for retroactive discovery: it performs entropy analysis and live credential verification (--only-verified) to confirm whether a discovered secret is still active. In practice: use Gitleaks as your pre-commit hook and in CI, and Trufflehog for periodic full history scans and one-time repository audits when onboarding a new application or after a suspected incident.

How do I scan private repositories I don't manage?

For GitHub organizations where you are an org owner: trufflehog github --org=orgname --token=$GITHUB_PAT with a PAT that has repo scope. For acquired company repositories or third-party repositories where you have access: clone locally and run trufflehog git file://path. For repositories you cannot access directly, GitGuardian's Public Monitoring monitors GitHub, GitLab, and Bitbucket for secrets that match your organization's patterns (domain names, key formats) appearing in public repositories, including forks of your private repos.

What do I do if a secret has been in git history for two years?

Assume it has been exploited. The 46-second exposure window applies to public repos; for internal repos it depends on when an attacker gained access. Immediately invalidate and rotate the credential. Check the credential's access logs for the full period it was valid: AWS CloudTrail, application logs, the API provider's audit log. Assess whether any actions taken with the credential caused data access, privilege escalation, or lateral movement. If unauthorized access is confirmed, escalate to incident response. Then, optionally use git-filter-repo or BFG Repo-Cleaner to remove the secret from history (to prevent future compromises), but this is secondary to the rotation and forensics.

How do we prevent .env files from being committed?

Add .env, .env.*, *.env, .env.local, .env.production to .gitignore at the repository root. Add a Gitleaks rule that explicitly detects .env file content patterns as a second layer. Add a README.md section documenting that .env files contain secrets and should never be committed. Use a .env.example file with placeholder values to document required environment variables without their values. None of these prevent a developer from using git add -f to force-add a .gitignore'd file: the CI/CD Gitleaks gate catches that.

Are secrets detection tools effective against secrets in binary files or compressed artifacts?

Most secrets detection tools focus on text content and have limited effectiveness against binary files. Trufflehog has Docker image layer scanning (docker --image flag) which decompresses layers and scans for secrets in plaintext within the image layers. For compressed artifacts in S3 or build storage, Trufflehog's S3 scanner handles common archive formats. For truly binary artifacts, manual inspection or artifact analysis tools are required. The better control is to prevent secrets from entering build artifacts in the first place via build-time secrets injection (Docker BuildKit --secret flag) rather than post-build scanning.

What secrets detection coverage does SOC 2 require?

SOC 2 Type II does not have a specific secrets detection control, but the CC6 (Logical and Physical Access Controls) and CC7 (System Operations) criteria require that access credentials are protected and that security events are monitored. Evidence for these criteria includes: code review processes that prevent hardcoded credentials (documented procedure referencing your pre-commit scanning tool), monitoring for unauthorized credential use (CloudTrail alerting, GitGuardian findings), and credential rotation procedures. A secrets detection program with documented tooling, demonstrated CI/CD enforcement, and rotation runbooks provides strong evidence across multiple SOC 2 criteria.

How do we handle false positives in secrets scanning results?

False positives come from test fixtures containing fake credentials, internal tools using custom key formats that match generic entropy patterns, and documentation examples. Handle them by: (1) adding a gitleaks:allow comment on the specific line to whitelist a known-safe pattern in Gitleaks; (2) adding an allowlist regex to .gitleaks.toml for project-wide patterns; (3) using Trufflehog's --only-verified flag to verify against the issuing service before alerting: this eliminates the vast majority of false positives at the cost of making external API calls during scanning. Track false positive rates per rule and disable rules with >90% false positive rates.

Sources & references

  1. Gitleaks GitHub Repository
  2. Trufflehog GitHub Repository
  3. GitGuardian Enterprise Documentation
  4. OWASP Secrets Management Cheat Sheet

Free resources

25
Free download

Critical CVE Reference Card 2025–2026

25 actively exploited vulnerabilities with CVSS scores, exploit status, and patch availability. Print it, pin it, share it with your SOC team.

No spam. Unsubscribe anytime.

Free download

Ransomware Incident Response Playbook

Step-by-step 24-hour IR checklist covering detection, containment, eradication, and recovery. Built for SOC teams, IR leads, and CISOs.

No spam. Unsubscribe anytime.

Free newsletter

Get threat intel before your inbox does.

50,000+ security professionals read Decryption Digest for early warnings on zero-days, ransomware, and nation-state campaigns. Free, daily, no spam.

Unsubscribe anytime. We never sell your data.

Eric Bang
Author

Founder & Cybersecurity Evangelist, Decryption Digest

Cybersecurity professional with expertise in threat intelligence, vulnerability research, and enterprise security. Covers zero-days, ransomware, and nation-state operations for 50,000+ security professionals every morning.

Black Hat Giveaway

Win a $2,495 Black Hat pass.

Full-access to Black Hat USA 2026 in Las Vegas. Subscribe free to enter.

Joins Decryption Digest daily briefing. Unsubscribe anytime.

Giveaway: Black Hat USA 2026 Full-Access Pass ($2,495 value)

Details →
Daily Briefing

Subscribe to enter the giveaway

Every subscriber is automatically entered. You also get daily threat intel every morning: zero-days, ransomware, and nation-state campaigns. Free. No spam.

Already subscribed? You're already entered.

Giveaway

Win a $2,495 Black Hat USA 2026 pass.