#!/usr/bin/env python3 """Поиск файлов с приватными ключами без вывода секретов.""" from __future__ import annotations import argparse import json import os import stat from pathlib import Path MARKERS = ( (b"-----BEGIN OPENSSH PRIVATE KEY-----", "OpenSSH"), (b"-----BEGIN RSA PRIVATE KEY-----", "RSA"), (b"-----BEGIN EC PRIVATE KEY-----", "EC"), (b"-----BEGIN DSA PRIVATE KEY-----", "DSA"), (b"-----BEGIN ENCRYPTED PRIVATE KEY-----", "PKCS#8 encrypted"), (b"-----BEGIN PRIVATE KEY-----", "PKCS#8"), ) def detect(head: bytes) -> str | None: for marker, label in MARKERS: if marker in head: return label return None def scan(root: Path, max_size: int, limit: int) -> tuple[int, list[dict[str, object]]]: found: list[dict[str, object]] = [] inspected = 0 for dirpath, _dirnames, filenames in os.walk(root, followlinks=False): for name in filenames: path = Path(dirpath) / name try: info = path.lstat() except OSError: continue if not stat.S_ISREG(info.st_mode) or info.st_size > max_size: continue try: with path.open("rb") as handle: head = handle.read(8192) except OSError: continue inspected += 1 key_type = detect(head) if not key_type: continue mode = stat.filemode(info.st_mode) found.append( { "path": str(path), "type": key_type, "size": info.st_size, "mode": mode, "world_readable": bool(info.st_mode & 0o004), "group_readable": bool(info.st_mode & 0o040), "encrypted_header": b"ENCRYPTED" in head, } ) if len(found) >= limit: return inspected, found return inspected, found def main() -> int: parser = argparse.ArgumentParser(description="Поиск приватных ключей") parser.add_argument("--path", type=Path, default=Path("."), help="Каталог для поиска") parser.add_argument("--max-size", type=int, default=5 * 1024 * 1024, help="Пропускать файлы больше N байт") parser.add_argument("--limit", type=int, default=100, help="Максимум находок") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() root = args.path.expanduser().resolve() if not root.is_dir(): parser.error(f"Каталог не найден: {root}") if args.max_size < 1024 or args.limit < 1: parser.error("Проверьте --max-size и --limit") inspected, found = scan(root, args.max_size, args.limit) print(f"Каталог: {root}") print(f"Просмотрено файлов: {inspected}") print(f"Найдено приватных ключей: {len(found)}") if found: print() for item in found: flags = [] if item["world_readable"]: flags.append("читается всеми") if item["group_readable"]: flags.append("читается группой") if item["encrypted_header"]: flags.append("заголовок ENCRYPTED") suffix = f" [{', '.join(flags)}]" if flags else "" print(f" {item['path']}: {item['type']}, {item['mode']}, {item['size']} байт{suffix}") print() print("Содержимое ключей не выводилось. Проверьте, нужны ли эти файлы в проекте.") if args.json: payload = {"root": str(root), "inspected": inspected, "keys": found} args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"JSON сохранён: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())