#!/usr/bin/env python3 """Чтение и проверка прав SSH-конфигурации macOS.""" from __future__ import annotations import argparse import json import os import stat import subprocess from pathlib import Path def mode(path: Path) -> str: try: return oct(stat.S_IMODE(path.stat().st_mode)) except OSError: return "?" def parse_config(path: Path) -> list[dict]: hosts: list[dict] = [] current: dict | None = None if not path.is_file(): return hosts for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines(): line = raw_line.strip() if not line or line.startswith("#"): continue parts = line.split(None, 1) if len(parts) != 2: continue key, value = parts[0].lower(), parts[1].strip() if key == "host": current = {"host": value, "hostname": "", "user": "", "port": "22"} hosts.append(current) elif current is not None and key in {"hostname", "user", "port"}: current[key] = value return hosts def fingerprints(directory: Path) -> list[dict]: result = [] ssh_keygen = "ssh-keygen" for path in sorted(directory.glob("*.pub")): check = subprocess.run( [ssh_keygen, "-lf", str(path)], capture_output=True, text=True, check=False, ) detail = check.stdout.strip() if check.returncode == 0 else check.stderr.strip() result.append({"path": str(path), "fingerprint": detail}) return result def main() -> int: parser = argparse.ArgumentParser(description="Аудит SSH") parser.add_argument("--json", type=Path) args = parser.parse_args() directory = Path.home() / ".ssh" report = { "directory": str(directory), "exists": directory.is_dir(), "directory_mode": mode(directory) if directory.exists() else "", "files": [], "hosts": [], "keys": [], "authorized_keys": 0, } if directory.is_dir(): for path in sorted(directory.iterdir()): if path.is_file(): report["files"].append({"name": path.name, "mode": mode(path), "size": path.stat().st_size}) report["hosts"] = parse_config(directory / "config") report["keys"] = fingerprints(directory) authorized = directory / "authorized_keys" if authorized.is_file(): report["authorized_keys"] = sum( 1 for line in authorized.read_text(encoding="utf-8", errors="replace").splitlines() if line.strip() and not line.lstrip().startswith("#") ) if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Каталог: {directory}") if not report["exists"]: print("Каталог ~/.ssh не найден.") return 0 print(f"Права каталога: {report['directory_mode']} (ожидается 0o700).") print("\nФайлы:") for item in report["files"]: note = "" if item["name"].startswith("id_") and not item["name"].endswith(".pub") and item["mode"] not in {"0o600", "0o400"}: note = " - слишком открытые права" print(f" {item['name']:<24} {item['mode']:<6} {item['size']} байт{note}") print("\nХосты из config:") if report["hosts"]: for host in report["hosts"]: print(f" {host['host']:<24} {host['hostname'] or '-':<28} {host['user'] or '-':<12} порт {host['port']}") else: print(" не найдены") print("\nПубличные ключи:") if report["keys"]: for key in report["keys"]: print(f" {Path(key['path']).name}: {key['fingerprint']}") else: print(" не найдены") print(f"\nСтрок в authorized_keys: {report['authorized_keys']}.") return 0 if __name__ == "__main__": raise SystemExit(main())