Linux

Аудит параметров sysctl

Сверяет сетевые и ядерные sysctl с безопасными значениями и печатает команды исправления.

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

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

Скрипт читает /proc/sys и сравнивает ключевые параметры с рекомендациями: ASLR, ptrace_scope, protected links, rp_filter, redirects, syncookies и другие. Выводятся OK, WARN и INFO, флаг --fix только печатает команды sysctl -w. Никакие значения не изменяются.

Запуск

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

python sysctl_audit.py

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

Примеры

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

  • python sysctl_audit.py
  • python sysctl_audit.py --fix
  • python sysctl_audit.py --router --json sysctl.json
Зависимости

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

Python 3.10+ Только стандартная библиотека
Linux sudo apt install python3
Исходник

sysctl_audit.py

#!/usr/bin/env python3
"""Аудит sysctl по безопасным значениям."""
from __future__ import annotations

import argparse
import json
from dataclasses import asdict, dataclass
from pathlib import Path

CHECKS = [
    ("kernel.randomize_va_space", "2", "eq", "ASLR"),
    ("kernel.dmesg_restrict", "1", "eq", "Ограничение dmesg"),
    ("kernel.kptr_restrict", "1", "ge", "Скрытие адресов ядра"),
    ("kernel.yama.ptrace_scope", "1", "ge", "Ограничение ptrace"),
    ("kernel.unprivileged_bpf_disabled", "1", "any", "Запрет unprivileged BPF"),
    ("kernel.unprivileged_userns_clone", "0", "eq", "Запрет unprivileged user namespaces"),
    ("fs.protected_hardlinks", "1", "eq", "Защита hardlinks"),
    ("fs.protected_symlinks", "1", "eq", "Защита symlinks"),
    ("fs.suid_dumpable", "0", "eq", "Запрет core dump для SUID"),
    ("net.ipv4.conf.all.rp_filter", "1", "eq", "Reverse path filter"),
    ("net.ipv4.conf.default.rp_filter", "1", "eq", "Reverse path filter по умолчанию"),
    ("net.ipv4.conf.all.accept_redirects", "0", "eq", "ICMP redirects"),
    ("net.ipv4.conf.all.send_redirects", "0", "eq", "Отправка ICMP redirects"),
    ("net.ipv4.conf.all.accept_source_route", "0", "eq", "Source routing"),
    ("net.ipv4.tcp_syncookies", "1", "eq", "SYN cookies"),
    ("net.ipv4.icmp_echo_ignore_broadcasts", "1", "eq", "Игнор broadcast ping"),
    ("net.ipv4.conf.all.log_martians", "1", "eq", "Логирование martians"),
    ("net.ipv6.conf.all.accept_redirects", "0", "eq", "IPv6 redirects"),
    ("net.ipv4.ip_forward", "0", "eq", "IP forwarding"),
    ("net.ipv6.conf.all.forwarding", "0", "eq", "IPv6 forwarding"),
]

INFO_KEYS = [
    ("vm.swappiness", "Агрессивность swap"),
    ("vm.dirty_ratio", "Порог грязных страниц"),
    ("fs.file-max", "Максимум файловых дескрипторов"),
    ("net.core.somaxconn", "Очередь accept"),
    ("net.ipv4.tcp_congestion_control", "Алгоритм TCP"),
]


@dataclass
class Result:
    key: str
    value: str
    expected: str
    status: str
    note: str


def read_value(key: str) -> str | None:
    path = Path("/proc/sys") / key.replace(".", "/")
    try:
        return path.read_text(encoding="utf-8").strip()
    except OSError:
        return None


def compare(actual: str, expected: str, mode: str) -> bool:
    if mode == "eq":
        return actual == expected
    if mode == "ge":
        try:
            return int(actual) >= int(expected)
        except ValueError:
            return False
    if mode == "any":
        allowed = {"1", "2"} if expected == "1" else {expected}
        return actual in allowed
    return False


def main() -> int:
    parser = argparse.ArgumentParser(description="Аудит sysctl Linux")
    parser.add_argument("--router", action="store_true", help="Разрешить IP forwarding")
    parser.add_argument("--fix", action="store_true", help="Показать команды исправления, не выполнять их")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    args = parser.parse_args()

    results: list[Result] = []
    fixes: list[str] = []
    for key, expected, mode, note in CHECKS:
        if args.router and "forwarding" in key:
            continue
        actual = read_value(key)
        if actual is None:
            results.append(Result(key, "-", expected, "INFO", note + ": параметр недоступен"))
            continue
        if compare(actual, expected, mode):
            results.append(Result(key, actual, expected, "OK", note))
        else:
            results.append(Result(key, actual, expected, "WARN", note))
            fixes.append(f"sysctl -w {key}={expected}")

    for key, note in INFO_KEYS:
        actual = read_value(key)
        if actual is not None:
            results.append(Result(key, actual, "-", "INFO", note))

    print(f"{'СТАТУС':<7} {'ПАРАМЕТР':<48} {'ЗНАЧЕНИЕ':<12} ОЖИДАНИЕ")
    print("-" * 105)
    for item in results:
        print(f"{item.status:<7} {item.key:<48} {item.value:<12} {item.expected}")
    warnings = sum(1 for item in results if item.status == "WARN")
    print(f"\nПроверено: {len(CHECKS)}, предупреждений: {warnings}")

    if args.fix and fixes:
        print("\nКоманды для исправления (не выполнены):")
        for command in fixes:
            print(f"  sudo {command}")

    if args.json:
        args.json.write_text(json.dumps({"results": [asdict(item) for item in results], "fixes": fixes}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        print(f"JSON сохранён: {args.json}")

    return 1 if warnings else 0


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

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

CLI 1.0.0

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

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

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

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

Категория

Linux

Bash и Python для серверов, рабочих станций и повседневных задач Linux.