#!/usr/bin/env python3 """Аудит задач cron без изменения системы.""" from __future__ import annotations import argparse import json import os import re import shlex import stat import subprocess from dataclasses import asdict, dataclass from pathlib import Path SYSTEM_FILES = [Path("/etc/crontab")] CRON_DIRS = [Path("/etc/cron.d")] SPOOL_DIRS = [Path("/var/spool/cron/crontabs"), Path("/var/spool/cron")] DANGEROUS = re.compile(r"(curl|wget)[^|]*\|\s*(ba)?sh", re.IGNORECASE) @dataclass class Entry: source: str schedule: str user: str command: str note: str def read_text(path: Path) -> str: try: return path.read_text(encoding="utf-8", errors="replace") except OSError: return "" def command_notes(command: str) -> str: notes = [] if DANGEROUS.search(command): notes.append("запуск скачанного кода") if "/tmp/" in command or "/var/tmp/" in command: notes.append("использует временный каталог") if "base64" in command and ("-d" in command or "--decode" in command): notes.append("декодирование base64") try: tokens = shlex.split(command) except ValueError: tokens = command.split() if tokens and tokens[0].startswith("/"): binary = Path(tokens[0]) if not binary.exists(): notes.append("файл команды не найден") else: try: mode = binary.stat().st_mode if mode & stat.S_IWOTH: notes.append("команда доступна на запись всем") except OSError: pass return ", ".join(notes) def parse_file(path: Path, default_user: str, source: str) -> list[Entry]: entries: list[Entry] = [] text = read_text(path) if not text: return entries for raw in text.splitlines(): line = raw.strip() if not line or line.startswith("#"): continue first = line.split(None, 1)[0] if "=" in first and not first.startswith("/") and not line.startswith("@"): continue if line.startswith("@"): parts = line.split(None, 2) if len(parts) == 3: schedule, user, command = parts elif len(parts) == 2: schedule, command = parts user = default_user else: continue else: parts = line.split(None, 6) if len(parts) == 7: schedule = " ".join(parts[:5]) user = parts[5] command = parts[6] elif len(parts) == 6: schedule = " ".join(parts[:5]) user = default_user command = parts[5] else: continue entries.append(Entry(source, schedule, user, command, command_notes(command))) return entries def user_crontab() -> list[Entry]: result = subprocess.run(["crontab", "-l"], capture_output=True, text=True, check=False) if result.returncode != 0 or not result.stdout: return [] entries = [] for raw in result.stdout.splitlines(): line = raw.strip() if not line or line.startswith("#"): continue if line.startswith("@"): parts = line.split(None, 1) if len(parts) == 2: entries.append(Entry("crontab текущего пользователя", parts[0], os.environ.get("USER", "user"), parts[1], command_notes(parts[1]))) continue parts = line.split(None, 5) if len(parts) == 6: schedule = " ".join(parts[:5]) command = parts[5] entries.append(Entry("crontab текущего пользователя", schedule, os.environ.get("USER", "user"), command, command_notes(command))) return entries def collect() -> tuple[list[Entry], list[str]]: entries: list[Entry] = [] problems: list[str] = [] for path in SYSTEM_FILES: if path.exists(): if not os.access(path, os.R_OK): problems.append(f"нет доступа на чтение: {path}") continue entries.extend(parse_file(path, "root", str(path))) for directory in CRON_DIRS: try: if not directory.is_dir(): continue children = sorted(directory.iterdir()) except OSError as error: problems.append(f"нет доступа к {directory}: {error}") continue for path in children: if not path.is_file() or path.name.startswith("."): continue if not os.access(path, os.R_OK): problems.append(f"нет доступа на чтение: {path}") continue entries.extend(parse_file(path, "root", str(path))) for directory in SPOOL_DIRS: try: if not directory.is_dir(): continue children = sorted(directory.iterdir()) except OSError as error: problems.append(f"нет доступа к {directory}: {error}") continue for path in children: if not path.is_file(): continue if not os.access(path, os.R_OK): problems.append(f"нет доступа на чтение: {path}") continue entries.extend(parse_file(path, path.name, str(path))) entries.extend(user_crontab()) entries.sort(key=lambda item: (item.source, item.schedule)) return entries, problems def main() -> int: parser = argparse.ArgumentParser(description="Аудит задач cron") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") parser.add_argument("--warnings-only", action="store_true", help="Показать только записи с замечаниями") args = parser.parse_args() entries, problems = collect() shown = [item for item in entries if item.note] if args.warnings_only else entries if not shown: print("Задачи cron не найдены." if not entries else "Записей с замечаниями нет.") else: print(f"{'ИСТОЧНИК':<34} {'РАСПИСАНИЕ':<18} {'ПОЛЬЗОВАТЕЛЬ':<12} КОМАНДА") print("-" * 110) for item in shown: command = item.command if len(item.command) <= 70 else item.command[:67] + "..." print(f"{item.source:<34} {item.schedule:<18} {item.user:<12} {command}") if item.note: print(f"{'':<34} замечание: {item.note}") if problems: print("\nОграничения доступа (для полного аудита запустите от root):") for problem in problems: print(f" - {problem}") warning_count = sum(1 for item in entries if item.note) print(f"\nВсего записей: {len(entries)}, с замечаниями: {warning_count}") if args.json: args.json.write_text( json.dumps( { "entries": [asdict(item) for item in entries], "problems": problems, "warning_count": warning_count, }, ensure_ascii=False, indent=2, ) + "\n", encoding="utf-8", ) print(f"Отчёт сохранён: {args.json}") return 1 if warning_count else 0 if __name__ == "__main__": raise SystemExit(main())