729 lines
30 KiB
Python
729 lines
30 KiB
Python
#!/usr/bin/env python3
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
"""Read-only host profiler, sent to the target on stdin: `ssh host python3 -`.
|
|
|
|
Stdlib only, Python 3.8. It prints one JSON line. That JSON is the contract consumed by the hub tooling
|
|
(`hub profile/suggest`, Go). Fixture examples: probe/fixtures/expected-alpha.json and expected-beta.json.
|
|
|
|
Safety contract (enforced in code, tested in probe/test_hostprobe.py):
|
|
* No writes anywhere on the target: no temp files, no bytecode, no service or package changes.
|
|
* Privilege only through `sudo -n` (never prompts), only for a fixed command allow-list, and only when
|
|
`sudo -n true` succeeded; otherwise the item degrades to an `unreadable` entry.
|
|
* Runtime is bounded (60 s total, 15 s per command) and output is bounded (2 MiB; the largest list is halved
|
|
until it fits and an `unreadable` entry says so).
|
|
* Never reads secrets: no environment variables, .env files, keys, tokens, shadow, sudoers, shell history.
|
|
Systemd unit text is reduced to absolute exec paths, User, Group, OnCalendar, Timer Unit and Description;
|
|
Environment= and command arguments are dropped. Scripts are hashed, never stored. Salt minion config: only
|
|
the `id:` and `master:` lines are kept.
|
|
|
|
Output schema (schema 1). All lists are sorted deterministically. null means "not determinable".
|
|
|
|
schema: 1 int
|
|
probed_at: "YYYY-MM-DDTHH:MM:SSZ" UTC
|
|
unreadable: [{section, item, reason}] what could not be read and why (never silent)
|
|
sections:
|
|
identity: {
|
|
hostname: str, os: {id, version_id, version_codename, pretty_name}, kernel: str, arch: str,
|
|
cpus: int, mem_total_kb: int, root_disk: {total_bytes: int, used_percent: float},
|
|
virtualization: str|null (systemd-detect-virt, "none" on metal), uptime_s: int,
|
|
machine_id_sha256_prefix: str (first 16 hex of sha256 of /etc/machine-id; the id itself is never emitted),
|
|
ssh_host_keys: [{type: str, fingerprint: "SHA256:..."}] from /etc/ssh/ssh_host_*.pub only,
|
|
tailscale0: [str] addresses on interface tailscale0 (empty if none) }
|
|
access: {
|
|
user: str, groups: [str], sudo_nopasswd: bool (`sudo -n true` succeeded),
|
|
sshd: {source: "sshd -T"|"sshd_config.d names"|null, allowusers: [str]|null, allowgroups: [str]|null
|
|
(null = unknown because sshd -T was unreadable; [] = readable and unset),
|
|
passwordauthentication: str, permitrootlogin: str, port: [str] (only with source "sshd -T"),
|
|
config_d_files: [str] (only with the fallback source: file names, never contents)},
|
|
fail2ban|ufw|nft: {installed: bool, active: bool} }
|
|
software: {
|
|
package_manager: "apt-get"|"dnf"|"yum"|"pacman"|null,
|
|
unattended_upgrades: {installed: bool, timer_enabled: bool}, unattended_upgrades_enabled: bool,
|
|
docker_server_version: str|null,
|
|
salt_minion: {installed: bool, version: str|null, active: bool, id: str|null, master: str|null},
|
|
python3: str }
|
|
containers: [{ one per container, sorted by (project, service, name)
|
|
id: str (12 hex), name: str, project: str, service: str, working_dir: str compose labels, "" if none,
|
|
image: str, user: str ("" = image default, usually root), privileged: bool, status: str,
|
|
health: str ("" when the container has no healthcheck; Docker 29 omits State.Health),
|
|
restart_policy: str, ports: [{container_port: int|null, proto: str, host_ip: str, host_port: int}] }]
|
|
services: [{ hand-made units in /etc/systemd/system (regular files only)
|
|
name: str, kind: "service"|"timer", enabled: str, active: str (systemctl states),
|
|
exec_paths: [str] absolute paths found in Exec* lines, user: str|null, group: str|null,
|
|
on_calendar: [str], unit: str|null (timer Unit=), description: str|null,
|
|
hub_managed: bool (name starts with security-hub-) }]
|
|
candidates: [{ exec paths of non-hub units under /srv /opt /usr/local /home
|
|
path: str, unit: str, sha256: str|null, owner: str, group: str, mode: "0755", size: int, note: str (optional) }]
|
|
listening: [{proto: "tcp"|"udp", address: str, port: int, process: str|null (needs sudo -n)}]
|
|
cron: {cron_d: [file names], user_crontabs: bool|null (exist; contents never read)}
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import grp
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import pwd
|
|
import re
|
|
import shutil
|
|
import socket
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from datetime import datetime, timezone
|
|
|
|
SCHEMA = 1
|
|
MAX_RUNTIME_S = 60.0
|
|
CMD_TIMEOUT_S = 15.0
|
|
MAX_OUTPUT_BYTES = 2 * 1024 * 1024
|
|
MAX_CMD_OUTPUT = 1024 * 1024
|
|
MAX_READ_BYTES = 64 * 1024
|
|
MAX_HASH_BYTES = 8 * 1024 * 1024
|
|
MAX_ITEMS = 500
|
|
CANDIDATE_ROOTS = ("/srv/", "/opt/", "/usr/local/", "/home/")
|
|
PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
|
HUB_UNIT_PREFIXES = ("security-hub-",)
|
|
UNIT_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9@:._-]*\.(service|timer)$")
|
|
INSPECT_CHUNK = 40
|
|
|
|
# Docker 29 omits State.Health for containers without a healthcheck, so it is read through `index`.
|
|
# No Env, Cmd, Mounts or other labels are requested.
|
|
DOCKER_INSPECT_TEMPLATE = (
|
|
'{"id":{{json .Id}},"name":{{json .Name}},'
|
|
'"project":{{json (index .Config.Labels "com.docker.compose.project")}},'
|
|
'"service":{{json (index .Config.Labels "com.docker.compose.service")}},'
|
|
'"working_dir":{{json (index .Config.Labels "com.docker.compose.project.working_dir")}},'
|
|
'"image":{{json .Config.Image}},"user":{{json .Config.User}},'
|
|
'"privileged":{{json .HostConfig.Privileged}},"status":{{json .State.Status}},'
|
|
'"health":{{with index .State "Health"}}{{json .Status}}{{else}}""{{end}},'
|
|
'"restart_policy":{{json .HostConfig.RestartPolicy.Name}},'
|
|
'"ports":{{json .NetworkSettings.Ports}}}'
|
|
)
|
|
|
|
# command -> allowed first arguments ("" means no argument). Anything else is refused before it runs.
|
|
ALLOWED_COMMANDS = {
|
|
"docker": {"ps", "inspect", "version"},
|
|
"sshd": {"-T"},
|
|
"ss": {"-H"},
|
|
"ip": {"-o"},
|
|
"systemctl": {"is-enabled", "is-active"},
|
|
"systemd-detect-virt": {""},
|
|
"dpkg-query": {"-W"},
|
|
"ls": {"-1"},
|
|
"true": {""},
|
|
}
|
|
|
|
SECRET_BASENAME_RE = re.compile(
|
|
r"(^\.env|\.env$|^environ$|shadow|sudoers|authorized_keys|known_hosts|history|^id_|htpasswd|netrc"
|
|
r"|token|secret|password|passwd-|credential|\.(key|pem|p12|pfx|kdbx|gpg|asc|age)$)",
|
|
re.IGNORECASE,
|
|
)
|
|
|
|
|
|
class ProbeError(Exception):
|
|
pass
|
|
|
|
|
|
class DeniedPath(PermissionError):
|
|
pass
|
|
|
|
|
|
def denied(path):
|
|
"""True for paths that may hold secret material. Public keys (.pub) are the only key files allowed."""
|
|
norm = os.path.normpath(path)
|
|
base = os.path.basename(norm)
|
|
if norm.endswith(".pub") and not base.startswith(".env"):
|
|
return False
|
|
if "/.ssh/" in norm + "/" or "/sudoers" in norm or norm.startswith("/etc/ssh/ssh_host_"):
|
|
return True
|
|
if norm.startswith("/proc/") and base == "environ":
|
|
return True
|
|
return bool(SECRET_BASENAME_RE.search(base))
|
|
|
|
|
|
def clip(value, limit=256):
|
|
return value[:limit] if isinstance(value, str) else value
|
|
|
|
|
|
def parse_unit_text(text):
|
|
"""Reduce systemd unit text to the few non-secret fields. Arguments and Environment= are dropped."""
|
|
unit = {"exec_paths": [], "user": None, "group": None, "on_calendar": [], "description": None, "unit": None}
|
|
section = ""
|
|
for raw in text.splitlines():
|
|
line = raw.strip()
|
|
if not line or line[0] in "#;":
|
|
continue
|
|
if line.startswith("[") and line.endswith("]"):
|
|
section = line[1:-1]
|
|
continue
|
|
key, sep, value = line.partition("=")
|
|
if not sep:
|
|
continue
|
|
key, value = key.strip(), value.strip()
|
|
if section == "Service" and key in ("ExecStart", "ExecStartPre", "ExecStartPost", "ExecStop"):
|
|
for token in value.lstrip("@-:+!").split():
|
|
if token.startswith("/") and "=" not in token:
|
|
path = token.strip("\"'")
|
|
if path not in unit["exec_paths"]:
|
|
unit["exec_paths"].append(clip(path, 512))
|
|
elif section == "Service" and key == "User":
|
|
unit["user"] = clip(value, 64)
|
|
elif section == "Service" and key == "Group":
|
|
unit["group"] = clip(value, 64)
|
|
elif section == "Timer" and key == "OnCalendar":
|
|
unit["on_calendar"].append(clip(value, 128))
|
|
elif section == "Timer" and key == "Unit":
|
|
unit["unit"] = clip(value, 128)
|
|
elif section == "Unit" and key == "Description":
|
|
unit["description"] = clip(value, 200)
|
|
return unit
|
|
|
|
|
|
def parse_os_release(text):
|
|
out = {}
|
|
for line in text.splitlines():
|
|
key, sep, value = line.partition("=")
|
|
if sep and key in ("ID", "VERSION_ID", "VERSION_CODENAME", "PRETTY_NAME"):
|
|
out[key.lower()] = value.strip().strip("\"'")
|
|
return out
|
|
|
|
|
|
def fingerprint_from_pub(line):
|
|
parts = line.split()
|
|
if len(parts) < 2:
|
|
raise ValueError("not a public key line")
|
|
blob = base64.b64decode(parts[1])
|
|
digest = base64.b64encode(hashlib.sha256(blob).digest()).decode("ascii").rstrip("=")
|
|
return {"type": parts[0], "fingerprint": "SHA256:" + digest}
|
|
|
|
|
|
def parse_sshd_t(text):
|
|
allowed = {"allowusers", "allowgroups", "passwordauthentication", "permitrootlogin", "port"}
|
|
out = {"allowusers": [], "allowgroups": [], "port": []}
|
|
for line in text.splitlines():
|
|
key, _, value = line.strip().partition(" ")
|
|
key = key.lower()
|
|
if key not in allowed:
|
|
continue
|
|
if key in ("allowusers", "allowgroups", "port"):
|
|
out[key].append(value.strip())
|
|
else:
|
|
out[key] = value.strip()
|
|
return out
|
|
|
|
|
|
def parse_ss(text):
|
|
rows = []
|
|
seen = set()
|
|
for line in text.splitlines():
|
|
fields = line.split()
|
|
if len(fields) < 5 or fields[0] not in ("tcp", "udp"):
|
|
continue
|
|
local = fields[4]
|
|
addr, _, port = local.rpartition(":")
|
|
addr = addr.strip("[]").split("%", 1)[0]
|
|
if not port.isdigit():
|
|
continue
|
|
match = re.search(r'\(\("([^"]+)"', line)
|
|
key = (fields[0], addr, int(port))
|
|
if key in seen:
|
|
continue
|
|
seen.add(key)
|
|
rows.append(
|
|
{"proto": fields[0], "address": addr, "port": int(port), "process": match.group(1) if match else None}
|
|
)
|
|
rows.sort(key=lambda r: (r["port"], r["proto"], r["address"]))
|
|
return rows
|
|
|
|
|
|
def parse_ports(raw):
|
|
out = []
|
|
for key, bindings in sorted((raw or {}).items()):
|
|
port, _, proto = key.partition("/")
|
|
for binding in bindings or []:
|
|
host_port = binding.get("HostPort", "")
|
|
if host_port.isdigit():
|
|
out.append(
|
|
{
|
|
"container_port": int(port) if port.isdigit() else None,
|
|
"proto": proto or "tcp",
|
|
"host_ip": binding.get("HostIp", ""),
|
|
"host_port": int(host_port),
|
|
}
|
|
)
|
|
out.sort(key=lambda b: (b["host_port"], b["proto"], b["host_ip"]))
|
|
return out
|
|
|
|
|
|
def parse_container(row):
|
|
return {
|
|
"id": clip(str(row.get("id", "")), 64)[:12],
|
|
"name": clip(str(row.get("name", "")).lstrip("/"), 128),
|
|
"project": clip(row.get("project") or "", 128),
|
|
"service": clip(row.get("service") or "", 128),
|
|
"working_dir": clip(row.get("working_dir") or "", 512),
|
|
"image": clip(row.get("image") or "", 256),
|
|
"user": clip(row.get("user") or "", 64),
|
|
"privileged": bool(row.get("privileged")),
|
|
"status": clip(row.get("status") or "", 32),
|
|
"health": clip(row.get("health") or "", 32),
|
|
"restart_policy": clip(row.get("restart_policy") or "", 32),
|
|
"ports": parse_ports(row.get("ports")),
|
|
}
|
|
|
|
|
|
def default_exec(argv, timeout):
|
|
env = {"PATH": PATH, "LC_ALL": "C"}
|
|
try:
|
|
proc = subprocess.run(
|
|
argv,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
timeout=timeout,
|
|
env=env,
|
|
check=False,
|
|
)
|
|
except FileNotFoundError:
|
|
return 127, ""
|
|
except subprocess.TimeoutExpired:
|
|
return 124, ""
|
|
return proc.returncode, proc.stdout[:MAX_CMD_OUTPUT].decode("utf-8", "replace")
|
|
|
|
|
|
class Probe:
|
|
"""Collects the profile. `root` re-roots file reads; `executor` runs commands (both replaced in tests)."""
|
|
|
|
def __init__(self, root="/", executor=None, which=None, user=None, groups=None, now=None):
|
|
self.root = root.rstrip("/")
|
|
self.executor = executor or default_exec
|
|
self.which = which or (lambda name: shutil.which(name, path=PATH))
|
|
self.user = user
|
|
self.groups = groups
|
|
self.now = now or (lambda: datetime.now(timezone.utc))
|
|
self.started = time.monotonic()
|
|
self.unreadable = []
|
|
self._sudo = None
|
|
|
|
# -- plumbing -------------------------------------------------------------------------------------------
|
|
|
|
def fs(self, path):
|
|
return self.root + path if self.root else path
|
|
|
|
def note(self, section, item, reason):
|
|
self.unreadable.append({"section": section, "item": item, "reason": clip(str(reason), 200)})
|
|
|
|
def remaining(self):
|
|
return MAX_RUNTIME_S - (time.monotonic() - self.started)
|
|
|
|
def read(self, path, limit=MAX_READ_BYTES):
|
|
if denied(path):
|
|
raise DeniedPath("refusing to read " + path)
|
|
with open(self.fs(path), "rb") as handle:
|
|
return handle.read(limit).decode("utf-8", "replace")
|
|
|
|
def listdir(self, path):
|
|
if denied(path + "/x"):
|
|
raise DeniedPath("refusing to list " + path)
|
|
return sorted(os.listdir(self.fs(path)))
|
|
|
|
def run(self, argv, sudo=False):
|
|
"""Run an allow-listed command. Returns (rc, stdout); rc 124 on timeout, 127 if missing, 126 if refused."""
|
|
argv = list(argv)
|
|
first = argv[1] if len(argv) > 1 else ""
|
|
if argv[0] not in ALLOWED_COMMANDS or first not in ALLOWED_COMMANDS[argv[0]]:
|
|
raise ProbeError("command not allowed: " + argv[0])
|
|
if self.remaining() <= 1:
|
|
return 124, ""
|
|
full = (["sudo", "-n"] + argv) if sudo else argv
|
|
return self.executor(full, min(CMD_TIMEOUT_S, self.remaining()))
|
|
|
|
def sudo_ok(self):
|
|
if self._sudo is None:
|
|
rc, _ = self.run(["true"], sudo=True)
|
|
self._sudo = rc == 0
|
|
return self._sudo
|
|
|
|
def systemctl_states(self, verb, names):
|
|
if not names:
|
|
return {}
|
|
_, out = self.run(["systemctl", verb] + names)
|
|
lines = out.splitlines()
|
|
return {name: (lines[i].strip() if i < len(lines) else "unknown") for i, name in enumerate(names)}
|
|
|
|
def docker(self, args):
|
|
"""docker via fixed argv: first as the current user, then through sudo -n when that is available."""
|
|
if not self.which("docker"):
|
|
return None
|
|
rc, out = self.run(["docker"] + args)
|
|
if rc == 0:
|
|
return out
|
|
if self.sudo_ok():
|
|
rc, out = self.run(["docker"] + args, sudo=True)
|
|
if rc == 0:
|
|
return out
|
|
return None
|
|
|
|
# -- sections -------------------------------------------------------------------------------------------
|
|
|
|
def identity(self):
|
|
out = {}
|
|
try:
|
|
out["hostname"] = self.read("/etc/hostname").strip()
|
|
except OSError:
|
|
out["hostname"] = socket.gethostname()
|
|
try:
|
|
out["os"] = parse_os_release(self.read("/etc/os-release"))
|
|
except OSError as exc:
|
|
out["os"] = {}
|
|
self.note("identity", "os-release", exc)
|
|
try:
|
|
out["kernel"] = self.read("/proc/sys/kernel/osrelease").strip()
|
|
except OSError:
|
|
out["kernel"] = os.uname().release
|
|
out["arch"] = self.arch()
|
|
try:
|
|
cpus = sum(
|
|
1 for line in self.read("/proc/cpuinfo", 1024 * 1024).splitlines() if line.startswith("processor")
|
|
)
|
|
except OSError:
|
|
cpus = 0
|
|
out["cpus"] = cpus or os.cpu_count()
|
|
try:
|
|
for line in self.read("/proc/meminfo").splitlines():
|
|
if line.startswith("MemTotal:"):
|
|
out["mem_total_kb"] = int(line.split()[1])
|
|
except (OSError, ValueError, IndexError) as exc:
|
|
self.note("identity", "meminfo", exc)
|
|
try:
|
|
total, used = self.disk_usage()
|
|
out["root_disk"] = {"total_bytes": total, "used_percent": round(100.0 * used / total, 1) if total else None}
|
|
except OSError as exc:
|
|
self.note("identity", "root_disk", exc)
|
|
rc, virt = self.run(["systemd-detect-virt"])
|
|
out["virtualization"] = virt.strip() or None if rc in (0, 1) else None
|
|
try:
|
|
out["uptime_s"] = int(float(self.read("/proc/uptime").split()[0]))
|
|
except (OSError, ValueError, IndexError) as exc:
|
|
self.note("identity", "uptime", exc)
|
|
try:
|
|
machine_id = self.read("/etc/machine-id").strip()
|
|
out["machine_id_sha256_prefix"] = hashlib.sha256(machine_id.encode("utf-8")).hexdigest()[:16]
|
|
except OSError as exc:
|
|
self.note("identity", "machine-id", exc)
|
|
keys = []
|
|
try:
|
|
for name in self.listdir("/etc/ssh"):
|
|
if name.startswith("ssh_host_") and name.endswith(".pub"):
|
|
try:
|
|
keys.append(fingerprint_from_pub(self.read("/etc/ssh/" + name, 8192).splitlines()[0]))
|
|
except (OSError, ValueError, IndexError) as exc:
|
|
self.note("identity", "host key " + name, exc)
|
|
except OSError as exc:
|
|
self.note("identity", "/etc/ssh", exc)
|
|
out["ssh_host_keys"] = keys
|
|
rc, text = self.run(["ip", "-o", "addr", "show", "dev", "tailscale0"])
|
|
addrs = []
|
|
if rc == 0:
|
|
for line in text.splitlines():
|
|
fields = line.split()
|
|
for i, field in enumerate(fields):
|
|
if field in ("inet", "inet6") and i + 1 < len(fields):
|
|
addrs.append(fields[i + 1].split("/")[0])
|
|
out["tailscale0"] = addrs
|
|
return out
|
|
|
|
def arch(self):
|
|
return os.uname().machine
|
|
|
|
def disk_usage(self):
|
|
st = os.statvfs(self.fs("/"))
|
|
total = st.f_blocks * st.f_frsize
|
|
return total, total - st.f_bavail * st.f_frsize
|
|
|
|
def python_version(self):
|
|
return "%d.%d.%d" % sys.version_info[:3]
|
|
|
|
def current_user(self):
|
|
if self.user:
|
|
return self.user
|
|
try:
|
|
return pwd.getpwuid(os.getuid()).pw_name
|
|
except KeyError:
|
|
return str(os.getuid())
|
|
|
|
def current_groups(self):
|
|
if self.groups is not None:
|
|
return list(self.groups)
|
|
names = []
|
|
for gid in os.getgroups():
|
|
try:
|
|
names.append(grp.getgrgid(gid).gr_name)
|
|
except KeyError:
|
|
continue
|
|
return sorted(names)
|
|
|
|
def access(self):
|
|
out = {"user": self.current_user(), "groups": self.current_groups()}
|
|
out["sudo_nopasswd"] = self.sudo_ok()
|
|
sshd = {"source": None, "allowusers": None, "allowgroups": None}
|
|
if out["sudo_nopasswd"]:
|
|
rc, text = self.run(["sshd", "-T"], sudo=True)
|
|
if rc == 0:
|
|
sshd = dict(parse_sshd_t(text), source="sshd -T")
|
|
else:
|
|
self.note("access", "sshd -T", "failed (rc=%s)" % rc)
|
|
else:
|
|
self.note("access", "sshd -T", "sudo -n unavailable")
|
|
if sshd["source"] is None:
|
|
try:
|
|
sshd["config_d_files"] = self.listdir("/etc/ssh/sshd_config.d")
|
|
sshd["source"] = "sshd_config.d names"
|
|
except OSError as exc:
|
|
self.note("access", "sshd_config.d", exc)
|
|
out["sshd"] = sshd
|
|
states = self.systemctl_states("is-active", ["fail2ban.service", "ufw.service", "nftables.service"])
|
|
out["fail2ban"] = {
|
|
"installed": bool(self.which("fail2ban-client")),
|
|
"active": states.get("fail2ban.service") == "active",
|
|
}
|
|
out["ufw"] = {"installed": bool(self.which("ufw")), "active": states.get("ufw.service") == "active"}
|
|
out["nft"] = {"installed": bool(self.which("nft")), "active": states.get("nftables.service") == "active"}
|
|
return out
|
|
|
|
def salt_config(self):
|
|
out = {"id": None, "master": None}
|
|
try:
|
|
out["id"] = clip(self.read("/etc/salt/minion_id", 512).strip().splitlines()[0], 128)
|
|
except (OSError, IndexError):
|
|
pass
|
|
files = ["/etc/salt/minion"]
|
|
try:
|
|
files += ["/etc/salt/minion.d/" + n for n in self.listdir("/etc/salt/minion.d") if n.endswith(".conf")]
|
|
except OSError:
|
|
pass
|
|
for path in files:
|
|
try:
|
|
text = self.read(path)
|
|
except OSError:
|
|
continue
|
|
for line in text.splitlines():
|
|
match = re.match(r"^(id|master):\s*([^#\s]+)\s*(#.*)?$", line)
|
|
if match:
|
|
out[match.group(1)] = clip(match.group(2).strip("\"'"), 128)
|
|
return out
|
|
|
|
def software(self):
|
|
out = {"package_manager": None}
|
|
for name in ("apt-get", "dnf", "yum", "pacman"):
|
|
if self.which(name):
|
|
out["package_manager"] = name
|
|
break
|
|
rc, _ = self.run(["dpkg-query", "-W", "-f=${Version}", "unattended-upgrades"])
|
|
timer = self.systemctl_states("is-enabled", ["apt-daily-upgrade.timer"]).get("apt-daily-upgrade.timer")
|
|
out["unattended_upgrades"] = {"installed": rc == 0, "timer_enabled": timer == "enabled"}
|
|
out["unattended_upgrades_enabled"] = rc == 0 and timer == "enabled"
|
|
version = self.docker(["version", "--format", "{{.Server.Version}}"])
|
|
out["docker_server_version"] = version.strip() if version and version.strip() else None
|
|
rc, ver = self.run(["dpkg-query", "-W", "-f=${Version}", "salt-minion"])
|
|
salt = {"installed": rc == 0, "version": ver.strip() if rc == 0 else None}
|
|
salt["active"] = (
|
|
self.systemctl_states("is-active", ["salt-minion.service"]).get("salt-minion.service") == "active"
|
|
)
|
|
salt.update(self.salt_config())
|
|
out["salt_minion"] = salt
|
|
out["python3"] = self.python_version()
|
|
return out
|
|
|
|
def containers(self):
|
|
out = self.docker(["ps", "-a", "-q", "--no-trunc"])
|
|
if out is None:
|
|
if self.which("docker"):
|
|
self.note("containers", "docker", "docker unavailable for this user and sudo -n")
|
|
return []
|
|
ids = [line.strip() for line in out.splitlines() if re.fullmatch(r"[0-9a-f]{12,64}", line.strip())][:MAX_ITEMS]
|
|
found = []
|
|
for i in range(0, len(ids), INSPECT_CHUNK):
|
|
text = self.docker(["inspect", "--format", DOCKER_INSPECT_TEMPLATE] + ids[i : i + INSPECT_CHUNK])
|
|
if text is None:
|
|
self.note("containers", "docker inspect", "failed")
|
|
break
|
|
for line in text.splitlines():
|
|
if not line.strip():
|
|
continue
|
|
try:
|
|
found.append(parse_container(json.loads(line)))
|
|
except (ValueError, AttributeError) as exc:
|
|
self.note("containers", "inspect line", exc)
|
|
found.sort(key=lambda c: (c["project"], c["service"], c["name"]))
|
|
return found
|
|
|
|
def services(self):
|
|
base = "/etc/systemd/system"
|
|
try:
|
|
names = [n for n in self.listdir(base) if UNIT_NAME_RE.match(n)]
|
|
except OSError as exc:
|
|
self.note("services", base, exc)
|
|
return []
|
|
units = []
|
|
for name in names[:MAX_ITEMS]:
|
|
full = self.fs(base + "/" + name)
|
|
try:
|
|
if not stat.S_ISREG(os.lstat(full).st_mode):
|
|
continue # symlinks (enablement links, aliases) are not hand-made unit files
|
|
info = parse_unit_text(self.read(base + "/" + name))
|
|
except OSError as exc:
|
|
self.note("services", name, exc)
|
|
continue
|
|
info["name"] = name
|
|
info["kind"] = name.rsplit(".", 1)[1]
|
|
info["hub_managed"] = name.startswith(HUB_UNIT_PREFIXES)
|
|
units.append(info)
|
|
enabled = self.systemctl_states("is-enabled", [u["name"] for u in units])
|
|
active = self.systemctl_states("is-active", [u["name"] for u in units])
|
|
for unit in units:
|
|
unit["enabled"] = enabled.get(unit["name"], "unknown")
|
|
unit["active"] = active.get(unit["name"], "unknown")
|
|
return units
|
|
|
|
def file_meta(self, st):
|
|
"""(owner, group, octal mode) of a stat result."""
|
|
try:
|
|
user = pwd.getpwuid(st.st_uid).pw_name
|
|
except KeyError:
|
|
user = str(st.st_uid)
|
|
try:
|
|
group = grp.getgrgid(st.st_gid).gr_name
|
|
except KeyError:
|
|
group = str(st.st_gid)
|
|
return user, group, "%04o" % stat.S_IMODE(st.st_mode)
|
|
|
|
def candidates(self, services):
|
|
found = {}
|
|
for unit in services:
|
|
if unit["hub_managed"]:
|
|
continue
|
|
for path in unit["exec_paths"]:
|
|
if not path.startswith(CANDIDATE_ROOTS) or path in found:
|
|
continue
|
|
entry = {"path": path, "unit": unit["name"], "sha256": None}
|
|
if denied(path):
|
|
entry["note"] = "name looks secret-bearing; not read"
|
|
found[path] = entry
|
|
continue
|
|
try:
|
|
st = os.lstat(self.fs(path))
|
|
except OSError as exc:
|
|
self.note("candidates", path, exc)
|
|
continue
|
|
if not stat.S_ISREG(st.st_mode):
|
|
entry["note"] = "not a regular file"
|
|
found[path] = entry
|
|
continue
|
|
user, group, mode = self.file_meta(st)
|
|
entry.update({"owner": user, "group": group, "mode": mode, "size": st.st_size})
|
|
if st.st_size > MAX_HASH_BYTES:
|
|
entry["note"] = "larger than hash limit"
|
|
else:
|
|
try:
|
|
digest = hashlib.sha256()
|
|
with open(self.fs(path), "rb") as handle:
|
|
for chunk in iter(lambda: handle.read(65536), b""):
|
|
digest.update(chunk)
|
|
entry["sha256"] = digest.hexdigest()
|
|
except OSError as exc:
|
|
self.note("candidates", path, exc)
|
|
found[path] = entry
|
|
return [found[k] for k in sorted(found)]
|
|
|
|
def listening(self):
|
|
use_sudo = self.sudo_ok()
|
|
rc, text = self.run(["ss", "-H", "-lntup"] if use_sudo else ["ss", "-H", "-lntu"], sudo=use_sudo)
|
|
if rc != 0:
|
|
self.note("listening", "ss", "failed (rc=%s)" % rc)
|
|
return []
|
|
if not use_sudo:
|
|
self.note("listening", "process names", "sudo -n unavailable")
|
|
return parse_ss(text)[:MAX_ITEMS]
|
|
|
|
def cron(self):
|
|
out = {"cron_d": [], "user_crontabs": None}
|
|
try:
|
|
out["cron_d"] = [n for n in self.listdir("/etc/cron.d") if not n.startswith(".")]
|
|
except OSError as exc:
|
|
self.note("cron", "/etc/cron.d", exc)
|
|
spool = "/var/spool/cron/crontabs"
|
|
try:
|
|
out["user_crontabs"] = len(self.listdir(spool)) > 0
|
|
except FileNotFoundError:
|
|
out["user_crontabs"] = False
|
|
except PermissionError:
|
|
if self.sudo_ok():
|
|
rc, text = self.run(["ls", "-1", spool], sudo=True)
|
|
out["user_crontabs"] = bool(text.strip()) if rc == 0 else None
|
|
if out["user_crontabs"] is None:
|
|
self.note("cron", spool, "not listable without root")
|
|
return out
|
|
|
|
# -- assembly -------------------------------------------------------------------------------------------
|
|
|
|
def guarded(self, name, func):
|
|
try:
|
|
return func()
|
|
except Exception as exc: # noqa: BLE001 - a probe must report what it could read, never crash on one collector
|
|
self.note(name, "collector", "%s: %s" % (type(exc).__name__, exc))
|
|
return [] if name in ("containers", "services", "candidates", "listening") else {}
|
|
|
|
def collect(self):
|
|
sections = {}
|
|
sections["identity"] = self.guarded("identity", self.identity)
|
|
sections["access"] = self.guarded("access", self.access)
|
|
sections["software"] = self.guarded("software", self.software)
|
|
sections["containers"] = self.guarded("containers", self.containers)
|
|
sections["services"] = self.guarded("services", self.services)
|
|
sections["candidates"] = self.guarded("candidates", lambda: self.candidates(sections["services"]))
|
|
sections["listening"] = self.guarded("listening", self.listening)
|
|
sections["cron"] = self.guarded("cron", self.cron)
|
|
profile = {
|
|
"schema": SCHEMA,
|
|
"probed_at": self.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
"sections": sections,
|
|
"unreadable": self.unreadable,
|
|
}
|
|
return bound_output(profile)
|
|
|
|
|
|
def encoded_size(profile):
|
|
return len(json.dumps(profile, sort_keys=True, separators=(",", ":")).encode("utf-8"))
|
|
|
|
|
|
def bound_output(profile, limit=MAX_OUTPUT_BYTES):
|
|
"""Shrink the largest list until the JSON fits, and record that it happened."""
|
|
truncated = []
|
|
while encoded_size(profile) > limit:
|
|
lists = [(len(v), k) for k, v in profile["sections"].items() if isinstance(v, list) and v]
|
|
if not lists:
|
|
profile["sections"] = {}
|
|
truncated.append("all sections")
|
|
break
|
|
_, key = max(lists)
|
|
profile["sections"][key] = profile["sections"][key][: len(profile["sections"][key]) // 2]
|
|
if key not in truncated:
|
|
truncated.append(key)
|
|
for key in truncated:
|
|
profile["unreadable"].append({"section": key, "item": "output", "reason": "truncated to fit 2 MiB"})
|
|
return profile
|
|
|
|
|
|
def main():
|
|
sys.dont_write_bytecode = True
|
|
profile = Probe().collect()
|
|
sys.stdout.write(json.dumps(profile, sort_keys=True, separators=(",", ":")) + "\n")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|