Безопасность и аудит

CIS-чеклист Linux

Проверяет базовые настройки Linux по мотивам CIS и считает рейтинг.

Python Linux Продвинутый
Скачать cis_checklist.py
Описание

Что делает скрипт

Скрипт проверяет права на passwd, shadow и group, настройки sshd, sysctl, firewall, auditd, SELinux или AppArmor, обновления, root-аккаунты и синхронизацию времени. Каждый пункт получает статус OK, WARN или FAIL, в конце выводится рейтинг. Это не полный аудит CIS, а быстрый чеклист для регулярной проверки.

Запуск

Быстрый старт

python3 cis_checklist.py

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • sudo python3 cis_checklist.py --verbose
  • python3 cis_checklist.py --json cis.json
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Linux sudo apt install python3
systemd systemctl и timedatectl
Linux sudo apt install systemd
ufw Необязательная проверка firewall
Linux sudo apt install ufw
firewalld Необязательная проверка firewall
Linux sudo apt install firewalld
nftables Необязательная проверка firewall
Linux sudo apt install nftables
iptables Необязательная проверка firewall
Linux sudo apt install iptables
apparmor Проверка AppArmor
Linux sudo apt install apparmor apparmor-utils
selinux-utils Проверка SELinux
Linux sudo apt install selinux-utils
chrony Проверка синхронизации времени
Linux sudo apt install chrony
Исходник

cis_checklist.py

#!/usr/bin/env python3
"""Быстрый чеклист настроек Linux по мотивам CIS."""
from __future__ import annotations

import argparse
import json
import os
import pwd
import shutil
import stat
import subprocess
from pathlib import Path

RESULTS: list[dict[str, str]] = []


def run(command: list[str], timeout: int = 5):
    try:
        return subprocess.run(command, capture_output=True, text=True, timeout=timeout, check=False)
    except (OSError, subprocess.TimeoutExpired):
        return None


def add(status: str, title: str, detail: str = "") -> None:
    RESULTS.append({"status": status, "title": title, "detail": detail})


def read_text(path: str) -> str:
    try:
        return Path(path).read_text(encoding="utf-8", errors="replace")
    except OSError:
        return ""


def sysctl_value(key: str) -> str:
    return read_text("/proc/sys/" + key.replace(".", "/")).strip()


def file_mode_check(path: str, maximum: int) -> None:
    try:
        info = os.stat(path)
    except OSError:
        add("FAIL", f"Права {path}", "файл отсутствует")
        return
    mode = stat.S_IMODE(info.st_mode)
    owner = pwd.getpwuid(info.st_uid).pw_name
    if owner != "root":
        add("FAIL", f"Владелец {path}", f"владелец {owner}, ожидается root")
    elif mode & ~maximum:
        add("FAIL", f"Права {path}", f"{oct(mode)}, ожидается не шире {oct(maximum)}")
    else:
        add("OK", f"Права {path}", oct(mode))


def ssh_values() -> dict[str, str]:
    values: dict[str, str] = {}
    paths = [Path("/etc/ssh/sshd_config")]
    dropin = Path("/etc/ssh/sshd_config.d")
    if dropin.is_dir():
        paths.extend(sorted(dropin.glob("*.conf")))
    for path in paths:
        for line in read_text(str(path)).splitlines():
            text = line.strip()
            if not text or text.startswith("#"):
                continue
            if "=" in text and " " not in text.split("=", 1)[0]:
                key, value = text.split("=", 1)
            else:
                parts = text.split(None, 1)
                if len(parts) != 2:
                    continue
                key, value = parts
            value = value.split("#", 1)[0].strip()
            values[key.strip().lower()] = value
    return values


def firewall_active() -> tuple[bool, str]:
    if shutil.which("ufw"):
        result = run(["ufw", "status"])
        if result and "Status: active" in result.stdout:
            return True, "ufw активен"
    if shutil.which("firewall-cmd"):
        result = run(["firewall-cmd", "--state"])
        if result and result.stdout.strip() == "running":
            return True, "firewalld активен"
    if shutil.which("nft"):
        result = run(["nft", "list", "ruleset"])
        if result and result.stdout.strip():
            return True, "nftables содержит правила"
    if shutil.which("iptables"):
        result = run(["iptables", "-S"])
        if result and any(line.startswith("-A") for line in result.stdout.splitlines()):
            return True, "iptables содержит правила"
    return False, "активный firewall не подтверждён"


def main() -> int:
    parser = argparse.ArgumentParser(description="CIS-чеклист Linux")
    parser.add_argument("--verbose", action="store_true", help="Показывать детали для OK")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    args = parser.parse_args()

    file_mode_check("/etc/passwd", 0o644)
    file_mode_check("/etc/shadow", 0o640)
    file_mode_check("/etc/group", 0o644)
    if Path("/etc/gshadow").exists():
        file_mode_check("/etc/gshadow", 0o640)

    ssh = ssh_values()
    root_login = ssh.get("permitrootlogin", "не задан")
    if root_login.lower() == "no":
        add("OK", "SSH: root login запрещён")
    elif root_login.lower() in {"prohibit-password", "without-password"}:
        add("WARN", "SSH: root login только по ключу", root_login)
    else:
        add("FAIL", "SSH: root login", root_login)

    password_auth = ssh.get("passwordauthentication", "не задан")
    if password_auth.lower() == "no":
        add("OK", "SSH: парольный вход выключен")
    elif password_auth.lower() == "yes":
        add("FAIL", "SSH: парольный вход включён")
    else:
        add("WARN", "SSH: passwordauthentication", password_auth)

    empty = ssh.get("permitemptypasswords", "не задан")
    add("OK" if empty.lower() == "no" else "FAIL", "SSH: пустые пароли", empty)

    max_auth = ssh.get("maxauthtries", "не задан")
    try:
        max_auth_ok = int(max_auth) <= 4
    except ValueError:
        max_auth_ok = False
    add("OK" if max_auth_ok else "WARN", "SSH: MaxAuthTries", max_auth)

    checks = {
        "kernel.randomize_va_space": "2",
        "net.ipv4.ip_forward": "0",
        "net.ipv4.conf.all.accept_redirects": "0",
        "net.ipv4.conf.all.send_redirects": "0",
        "net.ipv4.tcp_syncookies": "1",
        "kernel.dmesg_restrict": "1",
        "fs.suid_dumpable": "0",
    }
    for key, expected in checks.items():
        value = sysctl_value(key)
        if value == expected:
            add("OK", f"sysctl {key}", value)
        else:
            add("WARN", f"sysctl {key}", f"{value or 'нет'}, ожидается {expected}")

    active, detail = firewall_active()
    add("OK" if active else "FAIL", "Firewall", detail)

    audit_status = run(["systemctl", "is-active", "auditd"]) if shutil.which("systemctl") else None
    if audit_status and audit_status.stdout.strip() == "active":
        add("OK", "auditd", "активен")
    else:
        add("WARN", "auditd", "не активен или не установлен")

    mac_ok = False
    mac_detail = "не обнаружено"
    if shutil.which("getenforce"):
        result = run(["getenforce"])
        if result:
            mac_detail = result.stdout.strip()
            mac_ok = mac_detail.lower() == "enforcing"
    elif shutil.which("aa-status"):
        result = run(["aa-status", "--enabled"])
        mac_ok = bool(result and result.returncode == 0)
        mac_detail = "AppArmor включён" if mac_ok else "AppArmor выключен"
    add("OK" if mac_ok else "WARN", "SELinux или AppArmor", mac_detail)

    updates_ok = False
    update_detail = "механизм автообновлений не найден"
    auto = read_text("/etc/apt/apt.conf.d/20auto-upgrades")
    if 'Unattended-Upgrade "1"' in auto:
        updates_ok = True
        update_detail = "unattended-upgrades включён"
    elif shutil.which("systemctl"):
        result = run(["systemctl", "is-enabled", "dnf-automatic.timer"])
        if result and result.stdout.strip() == "enabled":
            updates_ok = True
            update_detail = "dnf-automatic.timer включён"
    add("OK" if updates_ok else "WARN", "Автообновления", update_detail)

    root_users = [user.pw_name for user in pwd.getpwall() if user.pw_uid == 0]
    if root_users == ["root"]:
        add("OK", "UID 0", "только root")
    else:
        add("FAIL", "UID 0", ", ".join(root_users))

    shadow = read_text("/etc/shadow")
    if not shadow:
        add("WARN", "Пустые пароли", "нет доступа к /etc/shadow")
    else:
        empty_users = [line.split(":", 1)[0] for line in shadow.splitlines() if len(line.split(":")) > 1 and line.split(":")[1] == ""]
        add("OK" if not empty_users else "FAIL", "Пустые пароли", ", ".join(empty_users) or "не найдены")

    time_ok = False
    time_detail = "статус неизвестен"
    if shutil.which("timedatectl"):
        result = run(["timedatectl", "show", "-p", "NTPSynchronized", "--value"])
        if result:
            time_detail = result.stdout.strip()
            time_ok = time_detail == "yes"
    if not time_ok and shutil.which("chronyc"):
        result = run(["chronyc", "tracking"])
        if result and "Leap status" in result.stdout:
            time_ok = True
            time_detail = "chrony работает"
    add("OK" if time_ok else "WARN", "Синхронизация времени", time_detail)

    points = {"OK": 1.0, "WARN": 0.5, "FAIL": 0.0}
    score = sum(points[item["status"]] for item in RESULTS) / len(RESULTS) * 100

    print("== CIS-чеклист ==")
    for item in RESULTS:
        if item["status"] != "OK" or args.verbose:
            suffix = f": {item['detail']}" if item["detail"] else ""
            print(f"[{item['status']}] {item['title']}{suffix}")
    counts = {status: sum(1 for item in RESULTS if item["status"] == status) for status in ("OK", "WARN", "FAIL")}
    print()
    print(f"OK: {counts['OK']}, WARN: {counts['WARN']}, FAIL: {counts['FAIL']}")
    print(f"Рейтинг: {score:.0f}%")

    if args.json:
        payload = {"score": round(score, 1), "counts": counts, "checks": RESULTS}
        args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        print(f"JSON сохранён: {args.json}")
    return 1 if counts["FAIL"] else 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get security-cis-checklist
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Безопасность и аудит

Проверка прав, хеши, сертификаты, подозрительные файлы и базовая защита.