Build a Python Secret Scanner That Finds Leaked Keys in Your Own Code


Every year, thousands of AWS keys, database passwords and private tokens leak because someone committed them to a code repository. Attackers scan public code constantly — a leaked key can be found and abused within minutes. The fix is to catch secrets before they leave your machine. Today we’ll build a scanner that does exactly that.

The Code

import re, sys
from pathlib import Path
PATTERNS = {
"AWS Access Key": r"AKIA[0-9A-Z]{16}",
"AWS Secret Key": r"(?i)aws_secret_access_key.{0,20}['\"][0-9a-zA-Z/+]{40}['\"]",
"Generic API Key": r"(?i)(api[_-]?key|apikey).{0,20}['\"][0-9a-zA-Z\-_]{20,}['\"]",
"Private Key": r"-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----",
"Password in code": r"(?i)(password|passwd|pwd).{0,20}['\"][^'\"]{8,}['\"]",
"GitHub Token": r"ghp_[0-9a-zA-Z]{36}",
"Slack Token": r"xox[baprs]-[0-9a-zA-Z-]{10,}",
"JWT Token": r"eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",
}
SKIP_DIRS = {".git", "__pycache__", "node_modules", ".venv", "venv"}
SKIP_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".ico", ".pdf", ".zip"}
def scan(path: Path):
findings = []
for file in path.rglob("*"):
if not file.is_file():
continue
if any(part in SKIP_DIRS for part in file.parts):
continue
if file.suffix.lower() in SKIP_EXTS:
continue
try:
text = file.read_text(errors="ignore")
except Exception:
continue
for name, pattern in PATTERNS.items():
for m in re.finditer(pattern, text):
line_no = text[:m.start()].count("\n") + 1
findings.append((str(file), line_no, name))
return findings
if __name__ == "__main__":
target = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
results = scan(target)
if not results:
print("No secrets found. Nice work.")
else:
print(f"Found {len(results)} possible secret(s):\n")
for f, line, name in results:
print(f" [{name}] {f}:{line}")
print("\nRotate any real secret immediately — and remove it from git history.")

How It Works

  1. Regex patterns — each secret type has a recognizable shape (AWS keys start with AKIA, GitHub tokens with ghp_), so regular expressions catch them reliably.
  2. Recursive walk — rglob(“*”) visits every file in your project, skipping binary files, dependencies and the .git folder itself.
  3. Line numbers — every hit reports the exact file and line, so you can jump straight to the problem.

Try It

Save as secretscan.py, then run it on one of your own projects: python3 secretscan.py ~/my-project. Try planting a fake key in a test file first to watch it get caught.

What to Do When It Finds Something Real

  • Rotate the secret immediately. Assume it is already compromised — revoke the key and generate a new one.
  • Remove it from git history. Deleting the file is not enough; the secret lives in old commits. Tools like git filter-repo or BFG Repo-Cleaner rewrite history, and GitHub can purge cached copies.
  • Move secrets to environment variables or a secrets manager, and add a .gitignore rule for your .env file.
  • Run the scanner in CI. Hook it into your build pipeline (or use a ready-made tool like Gitleaks or TruffleHog) so a leaked secret blocks the commit instead of reaching the repository.

Level Up

Add entropy detection to catch random-looking strings that match no known pattern, scan pull requests automatically, and extend the pattern list for your team’s services. You just built the first line of defence against the most embarrassing breach in software — your own key, in your own code, in public. Only scan code you own or have written permission to test.

Comments

Popular Posts