69 lines
1.9 KiB
Python
69 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Reject obvious reusable credentials without printing their values."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
PROJECT = Path(__file__).resolve().parents[1]
|
|
PATTERNS = (
|
|
re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),
|
|
re.compile(r"\b(?:ghp|github_pat|glpat|gitea)_[A-Za-z0-9_-]{16,}\b"),
|
|
re.compile(r"https?://[^/\s:@]+:[^/\s@]{8,}@"),
|
|
re.compile(
|
|
r"(?i)\b(?:password|passwd|api[_-]?key|access[_-]?token|secret)"
|
|
r"\s*[:=]\s*[\"'][A-Za-z0-9+/=_-]{12,}[\"']"
|
|
),
|
|
)
|
|
|
|
|
|
def tracked_files() -> list[Path]:
|
|
result = subprocess.run(
|
|
["git", "ls-files", "-z"],
|
|
cwd=PROJECT,
|
|
check=True,
|
|
capture_output=True,
|
|
)
|
|
return [
|
|
PROJECT / item.decode("utf-8")
|
|
for item in result.stdout.split(b"\0")
|
|
if item
|
|
]
|
|
|
|
|
|
def main() -> int:
|
|
findings: list[tuple[str, int, int]] = []
|
|
for path in tracked_files():
|
|
try:
|
|
text = path.read_text(encoding="utf-8")
|
|
except (OSError, UnicodeDecodeError):
|
|
continue
|
|
for line_number, line in enumerate(text.splitlines(), start=1):
|
|
for pattern_number, pattern in enumerate(PATTERNS, start=1):
|
|
if pattern.search(line):
|
|
findings.append(
|
|
(
|
|
path.relative_to(PROJECT).as_posix(),
|
|
line_number,
|
|
pattern_number,
|
|
)
|
|
)
|
|
if findings:
|
|
for path, line_number, pattern_number in findings:
|
|
print(
|
|
f"credential-like content: {path}:{line_number} "
|
|
f"(rule {pattern_number})",
|
|
file=sys.stderr,
|
|
)
|
|
return 1
|
|
print("tracked secret scan: OK")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|