#!/usr/bin/env python3 """Аудит точек автозапуска в Linux, macOS и Windows.""" from __future__ import annotations import argparse import json import os import platform import plistlib import re from pathlib import Path SUSPICIOUS_MARKERS = ( "/tmp/", "/var/tmp/", "/dev/shm/", "\\temp\\", "\\appdata\\local\\temp\\", "\\users\\public\\", ) def reasons_for(command: str) -> list[str]: lower = command.lower() reasons = [] if any(marker in lower for marker in SUSPICIOUS_MARKERS): reasons.append("временный каталог") if "powershell" in lower and ("-enc" in lower or "-encodedcommand" in lower): reasons.append("закодированная команда PowerShell") if re.search(r"(curl|wget|bitsadmin|certutil).*(http|ftp|\|)", lower): reasons.append("загрузка из сети") return sorted(set(reasons)) def mask_command(command: str) -> str: return re.sub(r"(?i)(password|passwd|token|secret|api[_-]?key)([=:]\s*)(\S+)", r"\1\2***", command) def add_entry(entries: list[dict[str, object]], source: str, name: str, command: str) -> None: command = command.strip() if not command: return reasons = reasons_for(command) entries.append( { "source": source, "name": name, "command": mask_command(command), "reasons": reasons, } ) def linux_entries(entries: list[dict[str, object]]) -> None: home = Path.home() for base in (home / ".config" / "autostart", Path("/etc/xdg/autostart")): if not base.is_dir(): continue for path in sorted(base.glob("*.desktop")): try: text = path.read_text(encoding="utf-8", errors="replace") except OSError: continue values = {} for line in text.splitlines(): if "=" in line and not line.lstrip().startswith("#"): key, value = line.split("=", 1) values[key.strip()] = value.strip() if values.get("Hidden", "").lower() == "true": continue add_entry(entries, "desktop", values.get("Name", path.stem), values.get("Exec", "")) for base in (home / ".config" / "systemd" / "user",): if not base.is_dir(): continue for path in sorted(base.glob("*.service")): try: text = path.read_text(encoding="utf-8", errors="replace") except OSError: continue for line in text.splitlines(): if line.startswith("ExecStart="): add_entry(entries, "systemd-user", path.name, line.split("=", 1)[1]) def macos_entries(entries: list[dict[str, object]]) -> None: home = Path.home() for base in (home / "Library" / "LaunchAgents", Path("/Library/LaunchAgents"), Path("/Library/LaunchDaemons")): if not base.is_dir(): continue for path in sorted(base.glob("*.plist")): try: data = plistlib.loads(path.read_bytes()) except (OSError, ValueError): continue if not isinstance(data, dict): continue label = str(data.get("Label", path.stem)) arguments = data.get("ProgramArguments") if isinstance(arguments, list): command = " ".join(str(item) for item in arguments) else: command = str(data.get("Program", "")) add_entry(entries, "launchd", label, command) def windows_entries(entries: list[dict[str, object]]) -> None: startup_dirs = [] appdata = os.environ.get("APPDATA") programdata = os.environ.get("PROGRAMDATA") if appdata: startup_dirs.append(Path(appdata) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup") if programdata: startup_dirs.append(Path(programdata) / "Microsoft" / "Windows" / "Start Menu" / "Programs" / "Startup") for base in startup_dirs: if not base.is_dir(): continue for path in sorted(base.glob("*")): add_entry(entries, "startup-folder", path.name, str(path)) try: import winreg except ImportError: return keys = ( (winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run"), (winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\RunOnce"), (winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\Run"), (winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion\RunOnce"), (winreg.HKEY_LOCAL_MACHINE, r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run"), ) for root, subkey in keys: try: with winreg.OpenKey(root, subkey) as key: index = 0 while True: try: name, value, _kind = winreg.EnumValue(key, index) except OSError: break add_entry(entries, "registry-run", name, str(value)) index += 1 except OSError: continue def main() -> int: parser = argparse.ArgumentParser(description="Аудит автозагрузки") parser.add_argument("--limit", type=int, default=100, help="Максимум записей") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() entries: list[dict[str, object]] = [] system = platform.system() if system == "Linux": linux_entries(entries) elif system == "Darwin": macos_entries(entries) elif system == "Windows": windows_entries(entries) else: print(f"Платформа {system} не поддерживается.") return 2 suspicious = [item for item in entries if item["reasons"]] print(f"Платформа: {system}") print(f"Записей автозагрузки: {len(entries)}") print(f"С замечаниями: {len(suspicious)}") print() for item in entries[: args.limit]: mark = " [!]" if item["reasons"] else "" print(f" {item['source']}: {item['name']}{mark}") print(f" {item['command']}") if item["reasons"]: print(f" причины: {', '.join(item['reasons'])}") if args.json: payload = {"platform": system, "entries": entries} 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())