Владельцы файлов и ACL
Ищет файлы с неизвестными владельцами и нестандартными расширенными ACL.
Что делает скрипт
Скрипт обходит каталог, сверяет UID и GID с локальными базами пользователей и групп и отмечает осиротевшие записи и файлы, принадлежащие nobody. Дополнительно через getfacl собираются именованные записи ACL и mask. Символические ссылки не раскрываются, содержимое файлов не читается.
Быстрый старт
python3 audit_owner_acl.py --path /srv
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python3 audit_owner_acl.py --path /var/www --limit 100python3 audit_owner_acl.py --path . --no-acl --json report.json
Что понадобится
sudo apt install python3
sudo apt install acl
audit_owner_acl.py
#!/usr/bin/env python3
"""Аудит владельцев файлов и расширенных ACL."""
from __future__ import annotations
import argparse
import json
import os
import pwd
import grp
import shutil
import stat
import subprocess
from pathlib import Path
SKIP_ROOT = {"/proc", "/sys", "/dev", "/run", "/snap"}
def lookup_user(uid: int, cache: dict[int, tuple[str, bool]]) -> tuple[str, bool]:
if uid not in cache:
try:
cache[uid] = (pwd.getpwuid(uid).pw_name, True)
except KeyError:
cache[uid] = (f"UID {uid}", False)
return cache[uid]
def lookup_group(gid: int, cache: dict[int, tuple[str, bool]]) -> tuple[str, bool]:
if gid not in cache:
try:
cache[gid] = (grp.getgrgid(gid).gr_name, True)
except KeyError:
cache[gid] = (f"GID {gid}", False)
return cache[gid]
def scan_acl(root: Path, limit: int) -> tuple[list[dict[str, str]], int]:
getfacl = shutil.which("getfacl")
if not getfacl:
return [], 0
try:
result = subprocess.run(
[getfacl, "-R", "-P", "-p", str(root)],
capture_output=True,
text=True,
errors="replace",
timeout=300,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return [], 0
current = ""
entries: list[dict[str, str]] = []
total = 0
for line in result.stdout.splitlines():
if line.startswith("# file: "):
current = line[8:].strip()
continue
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
is_default = stripped.startswith("default:")
parts = stripped.split(":")
named = False
if is_default and len(parts) >= 4 and parts[2]:
named = True
elif not is_default and len(parts) >= 3 and parts[1]:
named = True
if stripped.startswith("mask:") or stripped.startswith("default:mask:"):
named = True
if named:
total += 1
if len(entries) < limit:
entries.append({"path": current, "entry": stripped})
return entries, total
def main() -> int:
parser = argparse.ArgumentParser(description="Аудит владельцев и ACL")
parser.add_argument("--path", type=Path, default=Path("."), help="Каталог для проверки")
parser.add_argument("--limit", type=int, default=50, help="Сколько записей показать")
parser.add_argument("--no-acl", action="store_true", help="Не запускать getfacl")
parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
args = parser.parse_args()
root = args.path.expanduser().resolve()
if not root.is_dir():
parser.error(f"Каталог не найден: {root}")
if args.limit < 1:
parser.error("--limit должен быть положительным")
user_cache: dict[int, tuple[str, bool]] = {}
group_cache: dict[int, tuple[str, bool]] = {}
issues: list[dict[str, object]] = []
total = 0
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
if str(root) == "/":
dirnames[:] = [d for d in dirnames if os.path.join(dirpath, d) not in SKIP_ROOT]
for name in dirnames + filenames:
path = Path(dirpath) / name
try:
info = path.lstat()
except OSError:
continue
total += 1
user, known_user = lookup_user(info.st_uid, user_cache)
group, known_group = lookup_group(info.st_gid, group_cache)
reasons = []
if not known_user:
reasons.append("неизвестный UID")
if not known_group:
reasons.append("неизвестный GID")
if user == "nobody":
reasons.append("владелец nobody")
if group in {"nogroup", "nobody"}:
reasons.append(f"группа {group}")
if reasons and len(issues) < args.limit:
issues.append(
{
"path": str(path),
"uid": info.st_uid,
"gid": info.st_gid,
"user": user,
"group": group,
"reasons": reasons,
}
)
acl_entries: list[dict[str, str]] = []
acl_total = 0
if not args.no_acl:
acl_entries, acl_total = scan_acl(root, args.limit)
print(f"Каталог: {root}")
print(f"Проверено объектов: {total}")
print(f"Проблем с владельцами: {len(issues)}")
print(f"Расширенных ACL: {acl_total}")
print()
if issues:
print("== Владельцы ==")
for item in issues:
reasons = ", ".join(item["reasons"]) # type: ignore[arg-type]
print(f" {item['path']}: {item['user']}:{item['group']} ({reasons})")
print()
if acl_entries:
print("== ACL ==")
for item in acl_entries:
print(f" {item['path']}: {item['entry']}")
print()
if not issues and not acl_entries:
print("Подозрительных владельцев и расширенных ACL не найдено.")
if args.json:
payload = {
"root": str(root),
"total": total,
"owner_issues": issues,
"acl_entries": acl_entries,
"acl_total": acl_total,
}
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())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.