diff --git a/CHANGELOG.md b/CHANGELOG.md index d67fe1e..847c85a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ recorded here; their history is the git log. ## [Unreleased] +## [4.55.0] - 2026-12-01 + +### Added +- `LoginSessionsMixin.get_login_sessions()`: the interactive logins a Linux host recorded + over the last seven days (NetOrk/netork#2881), for an application that wants to know + which shells did not go through it. Each session names its account, terminal, the + address it came from (None at the host's console), start and end (ISO, UTC; the end None + while it runs). Read from `wtmpdb last` and `last` with `--time-format iso`, bounded with + `--since` on the host, a session in both records once. Only terminals count + (`is_interactive`): reboot entries, X displays, `ssh:notty` and windows of `screen` do not. + `own_address` is the driver's own SSH session's client address (`SSH_CONNECTION`), whose + sessions are left out. One fixed, read-only command as the login user; a driver supplies + `_run_login_sessions_command(command)`. A host whose `last` takes no `--time-format` + raises `LoginSessionsUnavailable`. + ## [4.54.0] - 2026-11-29 ### Added diff --git a/README.md b/README.md index e9e6d2a..8248567 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,20 @@ failed attempts since that login, from `lastb` (the newest 1000 per account) or when the lock, the expiry and the failures are `None`. A driver supplies `_run_login_accounts_command(command, privileged=)`. +`LoginSessionsMixin` (`get_login_sessions`) is mixed in the same way: the interactive logins +the host recorded over the last seven days -- each with its account, terminal, the address +it came from (None at the host's own console), start and end in ISO UTC -- from `wtmpdb last` +and `last` (wtmp), whichever the host has, bounded with `--since` on the host where the tool +takes it. Only a terminal counts (`pts/N`, `ttyN`, a serial or hypervisor console): not a +reboot entry, an X display, `ssh:notty`, nor a window of `screen`. `own_address` is where the +driver's own SSH session comes from as the host sees it (`SSH_CONNECTION`), and its sessions +are left out, on the host already: a client that opens a terminal adds one with every +connection. Which other sessions an application opened itself is the application's to know. +A driver supplies `_run_login_sessions_command(command)`, run as the login user, never +through `sudo`, which would drop `SSH_CONNECTION`; the records are readable to everyone. A +host with no record the reading can read (BusyBox's `last`) raises +`LoginSessionsUnavailable`, never "nobody logged in". + `ServicePackagesMixin` (`get_service_packages`) is mixed in the same way: which installed packages each systemd service is made of — the one shipping its unit file and the one shipping the binary its `ExecStart` runs, by `dpkg -S` or `rpm -qf`, not the libraries diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index a8a851a..b6ff305 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -56,6 +56,7 @@ instead of being restated on every role that happens to need it: * :class:`~napalm_device_types.listening.ListeningSocketsMixin` * :class:`~napalm_device_types.local_accounts.LocalAccountsMixin` * :class:`~napalm_device_types.login_accounts.LoginAccountsMixin` +* :class:`~napalm_device_types.login_sessions.LoginSessionsMixin` * :class:`~napalm_device_types.log_sources.LogSourcesMixin` * :class:`~napalm_device_types.host_firewall.HostFirewallMixin` * :class:`~napalm_device_types.mac_acl.MacAclMixin` @@ -272,6 +273,16 @@ from napalm_device_types.login_accounts import ( login_capable, parse_login_accounts, ) +from napalm_device_types.login_sessions import ( + LOGIN_SESSIONS_COMMAND, + LoginSessionDict, + LoginSessionsDict, + LoginSessionsMixin, + LoginSessionsUnavailable, + is_interactive, + parse_login_sessions, + session_address, +) from napalm_device_types.login_sources import ( LOGIN_FACTORS, LoginFactors, @@ -651,6 +662,14 @@ __all__ = [ "LoginAccountsMixin", "login_capable", "parse_login_accounts", + "LOGIN_SESSIONS_COMMAND", + "LoginSessionDict", + "LoginSessionsDict", + "LoginSessionsMixin", + "LoginSessionsUnavailable", + "is_interactive", + "parse_login_sessions", + "session_address", "SERVICE_PACKAGES_COMMAND", "SERVICES_RESTART_COMMAND", "ServicesRestartMixin", diff --git a/napalm_device_types/login_sessions.py b/napalm_device_types/login_sessions.py new file mode 100644 index 0000000..6e28733 --- /dev/null +++ b/napalm_device_types/login_sessions.py @@ -0,0 +1,318 @@ +"""The interactive logins a Linux host recorded, and where they came from (NetOrk/netork#2881). + +An application that opens every shell it offers through itself wants to know about the +ones that did not go through it: someone with their own key or a device password who +ran ``ssh`` from a laptop. The host records those itself, without an agent: + +- **The sessions,** from every login record the host has -- ``wtmpdb last`` (Debian 13, + openSUSE) and ``last`` (wtmp) -- with ISO times, over the last + :data:`SESSION_WINDOW_DAYS` days (``--since`` where the tool takes it, else here). A + session in both records is one. The newest :data:`SESSIONS_READ` are read. +- **Interactive only** (:func:`is_interactive`): a terminal -- ``pts/N``, ``ttyN``, a + serial or hypervisor console -- not a reboot or shutdown entry, an X display, + ``ssh:notty`` or an FTP daemon's line, nor a window of ``screen`` inside another session. +- **The reading's own address** (``own_address``): where the SSH session that reads + comes from, as the host sees it (``SSH_CONNECTION``). Its sessions are left out, on the + host already: a client that opens a terminal to read -- netmiko does -- adds one with + every connection. Which other addresses are the application's own is the caller's to + know. + +One fixed command, read-only, as the login user: the login records are readable to +everyone, and ``sudo`` resets the environment, ``SSH_CONNECTION`` with it. ``LC_ALL=C`` +keeps the tools' words in English. **Not read is an error, never "no sessions":** a host +whose ``last`` takes no ``--time-format`` (BusyBox) raises :class:`LoginSessionsUnavailable`. +""" + +from __future__ import annotations + +import ipaddress +import re +from datetime import UTC, datetime, timedelta +from shlex import quote +from typing import TYPE_CHECKING, TypedDict + +from napalm_device_types.terminal import strip_terminal_codes + +_BEGIN = "LOGSESSIONS_BEGIN" +_END = "LOGSESSIONS_END" + +#: How far back the reading goes. +SESSION_WINDOW_DAYS = 7 +#: The sessions read per record, newest first, after the reading's own are left out. +SESSIONS_READ = 1000 + +#: Reads one record: ``$1`` names its section, the rest is the tool. ``-i`` gives the +#: address the session came from rather than a name, where the tool takes it; ``--since`` +#: bounds the reading on the host. The awk program leaves out the reading's own address +#: (the third field) and keeps the newest :data:`SESSIONS_READ`. +_READ_RECORD = ( + "r() { t=$1; shift; " + '"$@" --time-format iso -w -n 1 >/dev/null 2>&1 || return 0; ' + 'i=; "$@" --time-format iso -w -i -n 1 >/dev/null 2>&1 && i=-i; ' + 'if [ -n "$s" ] && "$@" --time-format iso -w -s "$s" -n 1 >/dev/null 2>&1; then ' + 'echo "[$t since]"; "$@" --time-format iso -w $i -s "$s" 2>/dev/null | k; ' + 'else echo "[$t]"; "$@" --time-format iso -w $i 2>/dev/null | k; fi; }; ' +) + +#: One line, POSIX ``sh``, read-only, no stdin. The frame markers are printed in two +#: halves so that a transport which echoes the command does not show them early. +LOGIN_SESSIONS_COMMAND = ( + "exec /dev/null); " + 'h() { command -v "$1" >/dev/null 2>&1; }; ' + f"k() {{ awk -v o=\"$o\" -v n={SESSIONS_READ} '$3 != o && c++ < n'; }}; " + f"{_READ_RECORD}" + "printf '%s%s\\n' LOGSESSIONS_ BEGIN; " + "echo '[own]'; echo \"$o\"; echo '[now]'; date -u +%Y-%m-%dT%H:%M:%SZ; " + "if h wtmpdb; then r wtmpdb wtmpdb last; fi; " + "if h last; then r wtmp last; fi; " + "printf '%s%s\\n' LOGSESSIONS_ END" +) + +#: The records a session can come from, in the order they are read. +SESSION_SOURCES = ("wtmpdb", "wtmp") + +#: The entries a login record keeps that are no one's login. +_SYSTEM_ENTRIES = frozenset({"reboot", "shutdown", "runlevel"}) +#: A terminal a person types into: a pseudo-terminal, a virtual or serial console, a +#: hypervisor's console. ``ssh:notty``, an X display (``:0``) and ``ftpd`` are not. +_TERMINAL = re.compile(r"^(pts/\d+|tty[A-Za-z]*\d+|console|hvc\d+)$") +#: A host field that is no remote host: the console. ``last -i`` prints the unspecified +#: address for it, which :func:`session_address` reads as none too. +_NO_HOST = frozenset({"", "-"}) + +_SECTION = re.compile(r"^\[([a-z0-9_]+)(?: (\S+))?\]$") +_ISO = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}") +#: How long a session lasted, where it ended in a crash or a shutdown: ``(01:00)``, +#: ``(1+02:03)``. +_DURATION = re.compile(r"^\((?:(\d+)\+)?(\d+):(\d{2})\)$") + +_Sections = dict[tuple[str, str | None], list[str]] + + +class LoginSessionDict(TypedDict): + """One interactive login the host recorded.""" + + user: str + tty: str # "pts/0", "tty1", "ttyS0" + #: Where it came from, an IP address as the record has it (IPv6 compressed), or the + #: name sshd recorded where the tool could not give the address; None for a login at + #: the host's own console. + address: str | None + started: str # ISO 8601 in UTC + #: When it ended, ISO 8601 in UTC; None while it runs, or when the record does not + #: say (``gone - no logout``). + ended: str | None + + +class LoginSessionsDict(TypedDict): + """What :meth:`LoginSessionsMixin.get_login_sessions` read.""" + + #: The address the reading's own SSH session comes from; None when the host does not + #: say (no ``SSH_CONNECTION``). + own_address: str | None + #: Newest first, the reading's own left out. + sessions: list[LoginSessionDict] + + +class LoginSessionsUnavailable(ValueError): + """The host has no login record this reading can read.""" + + +def session_address(raw: str | None) -> str | None: + """*raw* from a login record or ``SSH_CONNECTION`` as one address: None for no remote + host, an IPv4-mapped IPv6 address as IPv4, IPv6 compressed, a name as it is.""" + if raw is None or raw.strip() in _NO_HOST: + return None + text = raw.strip() + try: + address = ipaddress.ip_address(text) + except ValueError: + return text + if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None: + address = address.ipv4_mapped + return None if address.is_unspecified else address.compressed + + +def is_interactive(user: str, tty: str, host: str | None) -> bool: + """Whether a record's line is a person's login at a terminal. + + Not a reboot, shutdown or runlevel entry, and a terminal :data:`_TERMINAL` names. A + host field starting with ``:`` is an X display or a window of ``screen`` + (``:pts/1:S.0``): a session inside another, not a login. + """ + if user in _SYSTEM_ENTRIES or not _TERMINAL.match(tty): + return False + return not (host or "").startswith(":") + + +def _sections(output: str) -> _Sections: + lines = [line.rstrip() for line in strip_terminal_codes(output).splitlines()] + stripped = [line.strip() for line in lines] + try: + start = stripped.index(_BEGIN) + end = stripped.index(_END, start) + except ValueError: + raise ValueError("no intact login session report in the output") from None + sections: _Sections = {} + current: list[str] = [] + for line in lines[start + 1 : end]: + header = _SECTION.match(line.strip()) + if header: + current = sections.setdefault((header.group(1), header.group(2)), []) + elif line.strip(): + current.append(line) + return sections + + +def _first(sections: _Sections, key: str) -> str | None: + lines = sections.get((key, None)) + return lines[0].strip() if lines else None + + +def _time(word: str) -> datetime | None: + try: + at = datetime.fromisoformat(word) + except ValueError: + return None + return at if at.tzinfo is not None else at.replace(tzinfo=UTC) + + +def _duration(words: list[str]) -> timedelta | None: + for word in words: + found = _DURATION.match(word) + if found: + days, hours, minutes = (int(part or 0) for part in found.groups()) + return timedelta(days=days, hours=hours, minutes=minutes) + return None + + +def _end(started: datetime, rest: list[str]) -> datetime | None: + """The end the words after the start say: a time, or the start plus the duration + after ``crash``/``down``; None while running or when the record does not say.""" + words = [word for word in rest if word != "-"] + if not words or words[0] in ("still", "gone"): + return None + if _ISO.match(words[0]): + return _time(words[0]) + if words[0] in ("crash", "down"): + lasted = _duration(words[1:]) + return None if lasted is None else started + lasted + return None + + +def _line(line: str) -> tuple[str, str, str | None, datetime, datetime | None] | None: + """A record's line in ``--time-format iso``: user, terminal, host, start, end.""" + words = line.split() + for index, word in enumerate(words[2:], start=2): + if _ISO.match(word): + started = _time(word) + if started is None: + return None + host = words[2] if index > 2 else None + return words[0], words[1], host, started, _end(started, words[index + 1 :]) + return None + + +def _iso(at: datetime | None) -> str | None: + return None if at is None else at.astimezone(UTC).isoformat() + + +def _since(sections: _Sections) -> datetime | None: + now = _time((_first(sections, "now") or "").replace("Z", "+00:00")) + return None if now is None else now - timedelta(days=SESSION_WINDOW_DAYS) + + +_Key = tuple[str, str, datetime] + + +def _session( + line: str, own: str | None, since: datetime | None +) -> tuple[_Key, LoginSessionDict] | None: + """*line* as a session, keyed for the dedup; None when it is none to report: not a + login at a terminal, the reading's own, or older than *since*.""" + parsed = _line(line) + if parsed is None: + return None + user, tty, host, started, ended = parsed + address = session_address(host) + if not is_interactive(user, tty, host) or (own is not None and address == own): + return None + if since is not None and started < since: + return None + session: LoginSessionDict = { + "user": user, + "tty": tty, + "address": address, + "started": started.astimezone(UTC).isoformat(), + "ended": _iso(ended), + } + return (user, tty, started), session + + +def parse_login_sessions(output: str) -> LoginSessionsDict: + """Parse what :data:`LOGIN_SESSIONS_COMMAND` printed. + + :raises LoginSessionsUnavailable: when the host had no login record to read. + :raises ValueError: when the output carries no intact report. + """ + sections = _sections(output) + # A record that printed no line is read all the same: no one logged in. + keys = [k for k in sections if k[0] in SESSION_SOURCES] + if not keys: + raise LoginSessionsUnavailable("no login record could be read") + own = session_address(_first(sections, "own")) + since = _since(sections) + seen: dict[_Key, LoginSessionDict] = {} + for key in keys: + for line in sections[key]: + found = _session(line, own, since) + if found is not None: + seen.setdefault(*found) + newest = sorted(seen.items(), key=lambda item: item[0][2], reverse=True) + return {"own_address": own, "sessions": [session for _, session in newest]} + + +class LoginSessionsMixin: + """Adds :meth:`get_login_sessions` to a driver that can run a command on a Linux host. + + The template form (README, "Function classes"): the command and its parse are the + same everywhere, and a driver supplies only :meth:`_run_login_sessions_command` -- + how a command reaches its host. Mixed in by the drivers that can, so + ``hasattr(driver, "get_login_sessions")`` stays a truthful answer. + """ + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _run_login_sessions_command(self, command: str) -> str: + """Run *command* on the host as the login user, in the SSH session the driver + holds, and return what it printed. Not through ``sudo``: it would drop + ``SSH_CONNECTION``. The command is a single ``sh -c`` invocation; it reads no + stdin.""" + ... + + def get_login_sessions(self) -> LoginSessionsDict: + """ + Returns the interactive logins the host recorded over the last seven days. + + * own_address (str or None) - the address the driver's own SSH session comes from, + as the host sees it + * sessions (list) - newest first, the driver's own left out: user, tty, address + (None for the host's own console), started and ended (ISO, UTC; ended None while + the session runs or when the record does not say) + + Example:: + + { + "own_address": "198.51.100.2", + "sessions": [{"user": "alice", "tty": "pts/1", "address": "192.0.2.10", + "started": "2026-11-30T09:15:02+00:00", "ended": None}], + } + + :raises LoginSessionsUnavailable: when the host has no login record it can read. + :raises ValueError: when the output carried no intact report. + """ + command = f"sh -c {quote(LOGIN_SESSIONS_COMMAND)}" + return parse_login_sessions(self._run_login_sessions_command(command)) diff --git a/pyproject.toml b/pyproject.toml index cc9acbc..ec9f8ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-device-types" -version = "4.54.0" +version = "4.55.0" description = "Abstract device-type base classes for NAPALM drivers" readme = "README.md" requires-python = ">=3.12" diff --git a/tests/test_login_sessions.py b/tests/test_login_sessions.py new file mode 100644 index 0000000..30615a5 --- /dev/null +++ b/tests/test_login_sessions.py @@ -0,0 +1,292 @@ +"""get_login_sessions: the interactive logins a Linux host recorded (NetOrk/netork#2881). + +The sessions come from the host's login records -- ``wtmpdb last`` and ``last`` (wtmp), +whichever it has -- over the last seven days, with ISO times. Only interactive sessions +count: a terminal (``pts/N``, ``ttyN``, a serial console), not a reboot, an X display or +``ssh:notty``. ``own_address`` is where the reading's own SSH session comes from, as the +host sees it (``SSH_CONNECTION``); the reading's own sessions are left out, since every +connection a client opens with a terminal is one of them. +""" + +from __future__ import annotations + +import os +import subprocess + +import pytest + +from napalm_device_types import OSDriver +from napalm_device_types.login_sessions import ( + LOGIN_SESSIONS_COMMAND, + SESSION_WINDOW_DAYS, + SESSIONS_READ, + LoginSessionsMixin, + LoginSessionsUnavailable, + is_interactive, + parse_login_sessions, + session_address, +) + +#: Debian 12 (util-linux 2.38): wtmp through ``last --time-format iso -w -i``, bounded +#: with ``--since`` on the host. alice is still logged in, root's console session ended +#: in a crash, bob came over IPv6, carol's session ended when the host went down. +DEBIAN_12 = [ + ("own", "198.51.100.2"), + ("now", "2026-11-30T12:00:00Z"), + ( + "wtmp since", + "alice pts/1 192.0.2.10 2026-11-30T10:15:02+01:00 still logged in\n" + "root tty1 0.0.0.0 2026-11-29T08:00:00+01:00 - crash (01:00)\n" + "reboot system boot 0.0.0.0 2026-11-29T07:59:00+01:00 still running\n" + "bob pts/2 2001:db8::5 2026-11-28T09:00:00+01:00 - 2026-11-28T09:10:00+01:00 (00:10)\n" + "alice pts/3 192.0.2.10 2026-11-27T10:00:00+01:00 gone - no logout\n" + "carol pts/4 203.0.113.7 2026-11-27T11:00:00+01:00 - down (1+02:03)\n" + "\n" + "wtmp begins 2026-11-01T00:00:01+01:00", + ), +] + +#: Debian 13: wtmpdb's ``last``, whose ISO offsets have no colon. +DEBIAN_13 = [ + ("own", "198.51.100.2"), + ("now", "2026-11-30T12:00:00Z"), + ( + "wtmpdb since", + "alice pts/0 192.0.2.10 2026-11-30T10:15:02+0100 - still logged in\n" + "reboot system boot 6.12.57+deb13-amd64 2026-11-29T07:59:00+0100 - still running\n" + "bob pts/1 2001:db8::6 2026-11-28T09:00:00+0100 - 2026-11-28T09:10:00+0100 (00:10)\n" + "\n" + "wtmpdb begins Sun Nov 1 00:00:01 2026", + ), +] + +#: AlmaLinux 9 (util-linux 2.37) with ``UseDNS yes``: sshd recorded a name, and this +#: ``last`` took neither ``-i`` nor ``--since``, so the host sent the newest lines unbounded. +ALMA_9 = [ + ("own", "198.51.100.2"), + ("now", "2026-11-30T12:00:00Z"), + ( + "wtmp", + "alice pts/0 laptop.example.com 2026-11-29T22:01:02+01:00 - 2026-11-29T23:00:00+01:00 (00:59)\n" + "alice pts/0 laptop.example.com 2026-11-10T22:01:02+01:00 - 2026-11-10T23:00:00+01:00 (00:59)", + ), +] + + +def _wire(sections: list[tuple[str, str]], *, noise: str = "") -> str: + """The report as the command prints it, framed.""" + body = "".join(f"[{name}]\n{text}\n" for name, text in sections) + return f"{noise}LOGSESSIONS_BEGIN\n{body}LOGSESSIONS_END\n" + + +class TestDebian12: + def test_the_interactive_sessions_newest_first(self): + reading = parse_login_sessions(_wire(DEBIAN_12)) + + assert [(s["user"], s["tty"]) for s in reading["sessions"]] == [ + ("alice", "pts/1"), + ("root", "tty1"), + ("bob", "pts/2"), + ("carol", "pts/4"), + ("alice", "pts/3"), + ] + + def test_times_are_iso_in_utc(self): + alice = parse_login_sessions(_wire(DEBIAN_12))["sessions"][0] + + assert alice == { + "user": "alice", + "tty": "pts/1", + "address": "192.0.2.10", + "started": "2026-11-30T09:15:02+00:00", + "ended": None, + } + + def test_an_ended_session_has_its_end(self): + bob = parse_login_sessions(_wire(DEBIAN_12))["sessions"][2] + + assert bob["address"] == "2001:db8::5" + assert bob["ended"] == "2026-11-28T08:10:00+00:00" + + def test_a_crash_or_shutdown_ends_after_the_duration(self): + sessions = parse_login_sessions(_wire(DEBIAN_12))["sessions"] + + assert sessions[1]["ended"] == "2026-11-29T08:00:00+00:00" # root, crash, (01:00) + assert sessions[3]["ended"] == "2026-11-28T12:03:00+00:00" # carol, down, (1+02:03) + + def test_a_session_gone_without_logout_has_no_end(self): + assert parse_login_sessions(_wire(DEBIAN_12))["sessions"][4]["ended"] is None + + def test_a_console_login_has_no_address(self): + assert parse_login_sessions(_wire(DEBIAN_12))["sessions"][1]["address"] is None + + def test_own_address(self): + assert parse_login_sessions(_wire(DEBIAN_12))["own_address"] == "198.51.100.2" + + +class TestDebian13: + def test_wtmpdb_with_offsets_without_a_colon(self): + sessions = parse_login_sessions(_wire(DEBIAN_13))["sessions"] + + assert [(s["user"], s["started"], s["ended"]) for s in sessions] == [ + ("alice", "2026-11-30T09:15:02+00:00", None), + ("bob", "2026-11-28T08:00:00+00:00", "2026-11-28T08:10:00+00:00"), + ] + + def test_a_session_in_wtmp_and_wtmpdb_is_one(self): + """A host upgraded to wtmpdb keeps its old wtmp, and ``last`` may be wtmpdb's.""" + both = [*DEBIAN_13, ("wtmp since", DEBIAN_13[2][1].replace("+0100", "+01:00"))] + + sessions = parse_login_sessions(_wire(both))["sessions"] + + assert [s["user"] for s in sessions] == ["alice", "bob"] + + +class TestAlma9: + def test_a_recorded_name_stays_a_name(self): + session = parse_login_sessions(_wire(ALMA_9))["sessions"][0] + + assert session["address"] == "laptop.example.com" + + def test_an_unbounded_reading_keeps_the_window(self): + """Without ``--since`` the host sends what it has; older logins are left out here.""" + sessions = parse_login_sessions(_wire(ALMA_9))["sessions"] + + assert [s["started"] for s in sessions] == ["2026-11-29T21:01:02+00:00"] + + +class TestOwnSessions: + def test_the_readings_own_sessions_are_left_out(self): + own = [ + ("own", "192.0.2.10"), + ("now", "2026-11-30T12:00:00Z"), + DEBIAN_12[2], + ] + + users = [s["user"] for s in parse_login_sessions(_wire(own))["sessions"]] + + assert "alice" not in users + assert users == ["root", "bob", "carol"] + + def test_no_ssh_connection_is_no_own_address(self): + reading = parse_login_sessions(_wire([("own", ""), *DEBIAN_12[1:]])) + + assert reading["own_address"] is None + assert len(reading["sessions"]) == 5 + + def test_a_v4_mapped_own_address_is_the_v4_address(self): + reading = parse_login_sessions(_wire([("own", "::ffff:192.0.2.10"), *DEBIAN_12[1:]])) + + assert reading["own_address"] == "192.0.2.10" + assert "alice" not in [s["user"] for s in reading["sessions"]] + + +class TestUnreadable: + def test_no_login_records_raise(self): + """BusyBox's ``last`` takes no ``--time-format``: nothing was read, which is not + "nobody logged in".""" + with pytest.raises(LoginSessionsUnavailable): + parse_login_sessions(_wire([("own", "198.51.100.2"), ("now", "2026-11-30T12:00:00Z")])) + + def test_no_intact_report_raises(self): + with pytest.raises(ValueError): + parse_login_sessions("sh: 1: last: not found\n") + + def test_noise_before_the_frame(self): + reading = parse_login_sessions(_wire(DEBIAN_13, noise="Last login: yesterday\n")) + + assert len(reading["sessions"]) == 2 + + def test_a_line_without_a_time_is_skipped(self): + broken = [*DEBIAN_12[:2], ("wtmp since", "alice pts/1 192.0.2.10 garbage")] + + assert parse_login_sessions(_wire(broken))["sessions"] == [] + + def test_a_reading_without_its_time_keeps_every_session(self): + reading = parse_login_sessions(_wire([DEBIAN_12[0], ALMA_9[2]])) + + assert len(reading["sessions"]) == 2 + + +class TestInteractive: + @pytest.mark.parametrize( + "tty", ["pts/0", "pts/17", "tty1", "ttyS0", "ttyAMA0", "console", "hvc0"] + ) + def test_a_terminal_is_interactive(self, tty): + assert is_interactive("alice", tty, "192.0.2.10") + + @pytest.mark.parametrize("tty", ["ssh:notty", ":0", "ftpd1234", "system", "~"]) + def test_anything_else_is_not(self, tty): + assert not is_interactive("alice", tty, "192.0.2.10") + + @pytest.mark.parametrize("user", ["reboot", "shutdown", "runlevel"]) + def test_a_system_entry_is_not(self, user): + assert not is_interactive(user, "tty1", None) + + def test_a_window_of_screen_or_an_x_display_is_not_a_login(self): + assert not is_interactive("alice", "pts/3", ":pts/1:S.0") + assert not is_interactive("alice", "pts/3", ":0") + + +class TestSessionAddress: + @pytest.mark.parametrize("raw", [None, "", "-", "0.0.0.0", "::"]) + def test_no_remote_host(self, raw): + assert session_address(raw) is None + + def test_ipv6_is_compressed(self): + assert session_address("2001:0db8:0000:0000:0000:0000:0000:0005") == "2001:db8::5" + + def test_a_name_stays(self): + assert session_address("laptop.example.com") == "laptop.example.com" + + +class _Driver(OSDriver, LoginSessionsMixin): + def __init__(self, output: str): + self.output = output + self.calls: list[str] = [] + + def _run_login_sessions_command(self, command: str) -> str: + self.calls.append(command) + return self.output + + +class TestTheMixin: + def test_the_command_goes_to_sh_as_the_login_user(self): + """``sudo`` resets the environment, and ``SSH_CONNECTION`` with it: the hook takes + no ``privileged``, the login records are readable to everyone.""" + driver = _Driver(_wire(DEBIAN_12)) + + reading = driver.get_login_sessions() + + assert driver.calls[0].startswith("sh -c ") + assert reading["own_address"] == "198.51.100.2" + + def test_only_a_driver_that_mixes_it_in_has_it(self): + assert not hasattr(OSDriver, "get_login_sessions") + + +class TestTheCommand: + def test_the_frame_is_not_in_the_command_itself(self): + assert "LOGSESSIONS_BEGIN" not in LOGIN_SESSIONS_COMMAND + assert "LOGSESSIONS_END" not in LOGIN_SESSIONS_COMMAND + + def test_it_changes_nothing_and_reads_no_stdin(self): + assert LOGIN_SESSIONS_COMMAND.startswith("exec ", ">>", "rm ", "truncate", "sudo"): + assert verb not in LOGIN_SESSIONS_COMMAND + + def test_the_window_and_the_cap(self): + assert str(SESSION_WINDOW_DAYS * 86400) in LOGIN_SESSIONS_COMMAND + assert f"n={SESSIONS_READ}" in LOGIN_SESSIONS_COMMAND + + @pytest.mark.skipif(os.uname().sysname != "Linux", reason="reads a Linux host") + def test_it_runs_and_parses_on_this_host(self): + out = subprocess.run( + ["sh", "-c", LOGIN_SESSIONS_COMMAND], capture_output=True, text=True, timeout=60 + ).stdout + + try: + reading = parse_login_sessions(out) + except LoginSessionsUnavailable: # a host without login records + return + assert isinstance(reading["sessions"], list)