|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +from collections.abc import Sequence |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | + |
| 10 | +# ------------------------- |
| 11 | +# Default secret patterns |
| 12 | +# ------------------------- |
| 13 | + |
| 14 | +DEFAULT_PATTERNS: dict[str, str] = { |
| 15 | + # GitLab |
| 16 | + "gitlab_pat": r"glpat-[0-9A-Za-z_-]{20,}", |
| 17 | + "gitlab_runner_token": r"glrt-[0-9A-Za-z_-]{20,}", |
| 18 | + |
| 19 | + # GitHub |
| 20 | + "github_pat": r"ghp_[0-9A-Za-z]{36}", |
| 21 | + "github_fine_grained_pat": r"github_pat_[0-9A-Za-z_]{82}", |
| 22 | + |
| 23 | + # AWS |
| 24 | + "aws_access_key": r"AKIA[0-9A-Z]{16}", |
| 25 | + "aws_secret_key": r"(?i)aws(.{0,20})?(secret|access)[-_ ]?key(.{0,20})?['\"][0-9a-zA-Z/+]{40}['\"]", |
| 26 | + |
| 27 | + # Generic |
| 28 | + "generic_secret": r"(?i)(password|passwd|pwd|secret|token|api[_-]?key)\s*=\s*['\"].+['\"]", |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +def load_custom_patterns(path: Path) -> dict[str, str]: |
| 34 | + patterns: dict[str, str] = {} |
| 35 | + for i, line in enumerate(path.read_text().splitlines(), start=1): |
| 36 | + line = line.strip() |
| 37 | + if not line or line.startswith("#"): |
| 38 | + continue |
| 39 | + patterns[f"custom_rule_{i}"] = line |
| 40 | + return patterns |
| 41 | + |
| 42 | + |
| 43 | +def is_binary(data: bytes) -> bool: |
| 44 | + return b"\x00" in data |
| 45 | + |
| 46 | + |
| 47 | +def git_tracked_files() -> list[Path]: |
| 48 | + """Return all git-tracked files in the repo.""" |
| 49 | + result = subprocess.run( |
| 50 | + ["git", "ls-files"], |
| 51 | + stdout=subprocess.PIPE, |
| 52 | + stderr=subprocess.DEVNULL, |
| 53 | + text=True, |
| 54 | + check=False, |
| 55 | + ) |
| 56 | + return [Path(p) for p in result.stdout.splitlines() if p] |
| 57 | + |
| 58 | + |
| 59 | +def main(argv: Sequence[str] | None = None) -> int: |
| 60 | + parser = argparse.ArgumentParser(description="Detect exposed secrets in repository") |
| 61 | + parser.add_argument( |
| 62 | + "--rules", |
| 63 | + type=Path, |
| 64 | + help="File containing custom regex rules (one per line)", |
| 65 | + ) |
| 66 | + parser.add_argument( |
| 67 | + "filenames", |
| 68 | + nargs="*", |
| 69 | + help="Files to scan (if empty, scans entire repo)", |
| 70 | + ) |
| 71 | + |
| 72 | + args = parser.parse_args(argv) |
| 73 | + |
| 74 | + patterns = dict(DEFAULT_PATTERNS) |
| 75 | + |
| 76 | + if args.rules: |
| 77 | + if not args.rules.is_file(): |
| 78 | + print(f"Rules file not found: {args.rules}") |
| 79 | + return 2 |
| 80 | + patterns.update(load_custom_patterns(args.rules)) |
| 81 | + |
| 82 | + compiled = { |
| 83 | + name: re.compile(regex) |
| 84 | + for name, regex in patterns.items() |
| 85 | + } |
| 86 | + |
| 87 | + files: list[Path] |
| 88 | + if args.filenames: |
| 89 | + files = [Path(f) for f in args.filenames] |
| 90 | + else: |
| 91 | + files = git_tracked_files() |
| 92 | + |
| 93 | + findings: list[tuple[Path, str]] = [] |
| 94 | + |
| 95 | + for path in files: |
| 96 | + if not path.is_file(): |
| 97 | + continue |
| 98 | + |
| 99 | + try: |
| 100 | + data = path.read_bytes() |
| 101 | + except OSError: |
| 102 | + continue |
| 103 | + |
| 104 | + if is_binary(data): |
| 105 | + continue |
| 106 | + |
| 107 | + text = data.decode(errors="ignore") |
| 108 | + |
| 109 | + for rule, regex in compiled.items(): |
| 110 | + if regex.search(text): |
| 111 | + findings.append((path, rule)) |
| 112 | + |
| 113 | + if findings: |
| 114 | + print("Potential secrets detected:") |
| 115 | + for path, rule in findings: |
| 116 | + print(f" - {path} (matched: {rule})") |
| 117 | + return 1 |
| 118 | + |
| 119 | + return 0 |
| 120 | + |
| 121 | + |
| 122 | +if __name__ == "__main__": |
| 123 | + raise SystemExit(main()) |
0 commit comments