#!/usr/bin/env python3 """Поиск признаков секретов в текстовых файлах.""" from __future__ import annotations import argparse import json import re from pathlib import Path PATTERNS = [ ("private-key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----")), ("aws-key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")), ("github-token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36}\b")), ("slack-token", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,48}\b")), ("bearer-token", re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{20,}")), ("possible-secret", re.compile(r"(?i)\b(?:api[_-]?key|secret|token|password)\b\s*[:=]\s*[\"']?([A-Za-z0-9_\-]{12,})")), ] SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"} BINARY_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".pdf", ".zip", ".gz", ".7z", ".exe", ".dll", ".mp3", ".mp4", ".docx", ".xlsx"} def masked(value: str) -> str: value = value.strip().strip("\"'") if len(value) <= 8: return value[:1] + "***" return value[:4] + "..." + value[-2:] def collect(root: Path, pattern: str) -> list[Path]: if root.is_file(): return [root] files = [] for path in sorted(root.rglob(pattern)): if not path.is_file() or path.suffix.lower() in BINARY_SUFFIXES: continue if any(part in SKIP_DIRS for part in path.parts): continue files.append(path) return files def main() -> int: parser = argparse.ArgumentParser(description="Найти секреты в текстовых файлах") parser.add_argument("--path", type=Path, required=True, help="Файл или папка") parser.add_argument("--glob", default="*", help="Маска файлов") parser.add_argument("--max-size", type=int, default=5, help="Максимальный размер файла в МБ") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") parser.add_argument("--fail-on-found", action="store_true", help="Код 1 при находках") args = parser.parse_args() root = args.path.expanduser().resolve() if not root.exists(): parser.error(f"Путь не найден: {root}") limit = args.max_size * 1024 * 1024 findings = [] for source in collect(root, args.glob): try: if source.stat().st_size > limit: continue data = source.read_bytes() except OSError as error: print(f"Пропуск {source}: {error}") continue if b"\0" in data[:4096]: continue text = data.decode("utf-8", errors="replace") for number, line in enumerate(text.splitlines(), 1): for kind, pattern in PATTERNS: for match in pattern.finditer(line): value = match.group(1) if match.lastindex else match.group(0) findings.append({ "file": str(source), "line": number, "type": kind, "preview": masked(value), }) if not findings: print("Признаки секретов не найдены") return 0 for item in findings: print(f"{item['file']}:{item['line']}: {item['type']}: {item['preview']}") print(f"Находок: {len(findings)}") if args.json: args.json.expanduser().write_text( json.dumps({"findings": findings}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"JSON: {args.json}") return 1 if args.fail_on_found else 0 if __name__ == "__main__": raise SystemExit(main())