feat(logins): every account a person can log in with, as one read-only reading (NetOrk/netork#2707)

LoginAccountsMixin.get_login_accounts: root and UID 1000 on with a login
shell, from /etc/passwd without the comment field; the newest last login of
lastlog2, lastlog, wtmpdb last and last, with where it came from; the
password state and expiry from passwd -S and chage -l; the failed attempts
since the last login from lastb, else faillock. Root first, the login user
where root is refused, when what needs root is None.
This commit is contained in:
christianmanivong committed 2026-11-28 03:46:33 +01:00
1 parent 07920941c8
commit 91b939236f
4 files changed
+950

No files matched your search

+15
View File
@@ -54,6 +54,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.kernel.KernelFactsMixin`
* :class:`~napalm_device_types.listening.ListeningSocketsMixin`
* :class:`~napalm_device_types.local_accounts.LocalAccountsMixin`
* :class:`~napalm_device_types.login_accounts.LoginAccountsMixin`
* :class:`~napalm_device_types.log_sources.LogSourcesMixin`
* :class:`~napalm_device_types.host_firewall.HostFirewallMixin`
* :class:`~napalm_device_types.mac_acl.MacAclMixin`
@@ -227,6 +228,14 @@ from napalm_device_types.log_sources import (
parse_log_forwarding,
parse_log_sources,
)
from napalm_device_types.login_accounts import (
LOGIN_ACCOUNTS_COMMAND,
LoginAccountDict,
LoginAccountsDict,
LoginAccountsMixin,
login_capable,
parse_login_accounts,
)
from napalm_device_types.mac_acl import MacAclMixin
from napalm_device_types.management_controller import ManagementControllerDriver
from napalm_device_types.media import MediaDriver
@@ -569,6 +578,12 @@ __all__ = [
"HardeningDict",
"cpu_vulnerability_state",
"parse_hardening",
"LOGIN_ACCOUNTS_COMMAND",
"LoginAccountDict",
"LoginAccountsDict",
"LoginAccountsMixin",
"login_capable",
"parse_login_accounts",
"SERVICE_PACKAGES_COMMAND",
"SERVICES_RESTART_COMMAND",
"ServicesRestartMixin",
+442
View File
@@ -0,0 +1,442 @@
"""Every account a person can log in with on a Linux host, and how it is used (NetOrk/netork#2707).
An access review asks who can get into the systems people actually log in to. On a
host that is every account with a shell, not only the ones an application created:
- **The accounts:** ``/etc/passwd``, root and UID 1000 on, with a shell that lets them
in (not ``nologin`` or ``false``; :func:`login_capable`). Only the name, UID, home and
shell cross: the comment field is a person's name. Accounts from a directory (SSSD,
an AD join) are not in ``/etc/passwd`` and are not read: the directory reviews them.
- **The last login,** from every source the host has -- ``lastlog2`` (util-linux 2.40
on), the legacy ``lastlog``, ``wtmpdb last`` and ``last`` (wtmp) -- the newest of them
wins, with the tool that told it. A host upgraded to lastlog2 keeps an old lastlog
file, a desktop login reaches wtmp and not lastlog: no single source is the whole story.
- **Lock and expiry,** from ``passwd -S`` (the password set, locked or empty) and
``chage -l`` (password change, password and account expiry), as root. An account is
``locked`` when its password is locked or it expired -- ``usermod -L -e 1`` does both.
- **The failed attempts since the last login,** a number per account: from ``lastb``
(btmp; the newest :data:`FAILED_LOGINS_READ` per account) where the host keeps it,
else from ``pam_faillock``'s tally, which a successful login resets. Root only.
One fixed command, read-only, the same on every Linux host; ``LC_ALL=C`` keeps the tools'
dates in one format. **Not read is None, never "no":** read as the login user, the lock,
the expiry and the failures are ``None``, not "unlocked" or "none failed".
"""
from __future__ import annotations
import re
from collections.abc import Iterable
from datetime import UTC, date, datetime
from shlex import quote
from typing import TYPE_CHECKING, TypedDict
from napalm_device_types.terminal import strip_terminal_codes
_BEGIN = "LOGINS_BEGIN"
_END = "LOGINS_END"
#: The failed attempts ``lastb`` hands over per account, newest first: a host on the
#: internet collects millions in btmp. A count that reaches it is "at least".
FAILED_LOGINS_READ = 1000
#: Root, and people: UID 1000 on, without the overflow UID ``nobody`` has.
_FIRST_PERSON_UID = 1000
_NOBODY_UID = 65534
_NO_LOGIN_SHELLS = frozenset({"nologin", "false"})
#: The awk filter for a login-capable ``/etc/passwd`` line; :func:`login_capable` again.
_CAPABLE = f"($3==0||$3>={_FIRST_PERSON_UID})&&$3!={_NOBODY_UID}&&$7!~/(^|\\/)(nologin|false)$/"
#: Keeps the lines of the accounts in ``$u``, the first *n* of each.
_KEEP = 'awk -v u=" $u " -v n={n} \'index(u, " " $1 " ") && c[$1]++ < n\''
#: One line, POSIX ``sh``, read-only, no stdin (a sudo password must not reach a tool).
#: The frame markers are printed in two halves so that a transport which echoes the
#: command does not show them early. ``passwd``, ``chage`` and ``faillock`` live in
#: ``/usr/sbin`` on some systems, outside a login user's ``PATH``.
LOGIN_ACCOUNTS_COMMAND = (
"exec </dev/null; PATH=$PATH:/usr/sbin:/sbin; LC_ALL=C; export LC_ALL; "
f"u=$(awk -F: '{_CAPABLE}{{print $1}}' /etc/passwd 2>/dev/null | tr '\\n' ' '); "
'h() { command -v "$1" >/dev/null 2>&1; }; '
"printf '%s%s\\n' LOGINS_ BEGIN; "
"echo '[uid]'; id -u; echo '[now]'; date -u +%Y-%m-%d; "
f'echo \'[passwd]\'; awk -F: \'{_CAPABLE}{{print $1":"$3":"$6":"$7}}\' /etc/passwd; '
f"if h lastlog2; then echo '[lastlog2]'; lastlog2 2>/dev/null | {_KEEP.format(n=1)}; fi; "
f"if h lastlog; then echo '[lastlog]'; lastlog 2>/dev/null | {_KEEP.format(n=1)}; fi; "
"if h wtmpdb && wtmpdb last --time-format iso -n 1 >/dev/null 2>&1; then echo '[wtmpdb]'; "
f"wtmpdb last --time-format iso 2>/dev/null | {_KEEP.format(n=1)}; fi; "
"if h last && last --time-format iso -n 1 >/dev/null 2>&1; then echo '[wtmp]'; "
f"last --time-format iso -w 2>/dev/null | {_KEEP.format(n=1)}; fi; "
"if h lastb && lastb --time-format iso -n 1 >/dev/null 2>&1; then echo '[lastb]'; "
f"lastb --time-format iso -w 2>/dev/null | {_KEEP.format(n=FAILED_LOGINS_READ)}; fi; "
'for n in $u; do echo "[passwd_status $n]"; passwd -S "$n" 2>/dev/null; '
'echo "[chage $n]"; chage -l "$n" 2>/dev/null; '
'if h faillock; then echo "[faillock $n]"; faillock --user "$n" 2>/dev/null; fi; done; '
"printf '%s%s\\n' LOGINS_ END"
)
#: The tools a last login can come from, in the order they are named.
LOGIN_SOURCES = ("lastlog2", "lastlog", "wtmpdb", "wtmp")
_SECTION = re.compile(r"^\[([a-z0-9_]+)(?: (\S+))?\]$")
#: ``%a %b %e %H:%M:%S %z %Y``, lastlog's and lastlog2's date, at the end of a line.
_LASTLOG_DATE = re.compile(r"\s(\w{3} \w{3} +\d{1,2} \d{2}:\d{2}:\d{2}(?: [+-]\d{4})? \d{4})$")
_ISO = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")
#: A row of a ``faillock`` tally starts with its date.
_ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2} ")
#: ``passwd -S``'s second word: shadow's and libuser's.
_PASSWORD_STATES = {"P": "set", "PS": "set", "L": "locked", "LK": "locked", "NP": "none"}
_NEVER = "never"
_MUST_CHANGE = "password must be changed"
_Sections = dict[tuple[str, str | None], list[str]]
class LoginAccountDict(TypedDict):
"""One login-capable account. ``None`` in a field: could not be read."""
name: str
uid: int
home: str
shell: str
#: The newest login any source knows, ISO 8601 in UTC; None: never, or not read
#: (``login_sources`` empty).
last_login: str | None
last_login_from: str | None # the remote host; None for a console login
last_login_port: str | None # the terminal: "pts/0", "tty1", ":0"
last_login_source: str | None # one of LOGIN_SOURCES
password: str | None # "set", "locked" or "none" (passwd -S)
password_changed: str | None # ISO date; None: never set, or not read
password_expires: str | None # ISO date, "never" or "must_change"
account_expires: str | None # ISO date or "never"
#: The password locked, or the account expired on the host's date.
locked: bool | None
#: Failed attempts since the last login (lastb), or in the tally (faillock).
failed_logins: int | None
#: The count reached FAILED_LOGINS_READ: there may be more.
failed_logins_capped: bool
class LoginAccountsDict(TypedDict):
"""What :meth:`LoginAccountsMixin.get_login_accounts` read."""
accounts: list[LoginAccountDict]
#: The sources of the last logins the host has, of LOGIN_SOURCES; empty: none.
login_sources: list[str]
#: "lastb" or "faillock"; None: neither could be read.
failed_logins_source: str | None
#: Read as root: the lock, the expiry and the failures are known.
privileged: bool
class _Login(TypedDict):
at: datetime
port: str | None
host: str | None
source: str
def login_capable(uid: int, shell: str) -> bool:
"""Whether an account with *uid* and *shell* is one a person logs in with: root, or
UID 1000 on (not ``nobody``'s), and a shell that is not ``nologin`` or ``false``.
An empty shell is ``/bin/sh``."""
if uid != 0 and (uid < _FIRST_PERSON_UID or uid == _NOBODY_UID):
return False
return shell.rsplit("/", 1)[-1] not in _NO_LOGIN_SHELLS
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 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, arg: str | None = None) -> str | None:
lines = sections.get((key, arg))
return lines[0].strip() if lines else None
def _accounts(sections: _Sections) -> list[tuple[str, int, str, str]]:
accounts = []
for line in sections.get(("passwd", None), []):
fields = line.strip().split(":")
if len(fields) != 4 or not fields[1].isdigit():
continue
name, uid, home, shell = fields[0], int(fields[1]), fields[2], fields[3]
if login_capable(uid, shell):
accounts.append((name, uid, home, shell))
return accounts
def _where(middle: list[str]) -> tuple[str | None, str | None]:
"""The terminal and the remote host between a line's name and its date."""
port = middle[0] if middle else None
host = middle[1] if len(middle) > 1 else None
return port, host
def _lastlog_line(line: str, source: str) -> tuple[str, _Login] | None:
"""A ``lastlog``/``lastlog2`` line; None for "Never logged in" or a header."""
found = _LASTLOG_DATE.search(line)
if not found:
return None
text = " ".join(found.group(1).split())
try:
if re.search(r" [+-]\d{4} ", text):
at = datetime.strptime(text, "%a %b %d %H:%M:%S %z %Y")
else:
at = datetime.strptime(text, "%a %b %d %H:%M:%S %Y").replace(tzinfo=UTC)
except ValueError:
return None
words = line[: found.start()].split()
port, host = _where(words[1:])
return words[0], {"at": at, "port": port, "host": host, "source": source}
def _iso_line(line: str, source: str) -> tuple[str, _Login] | None:
"""A ``last``/``lastb``/``wtmpdb last`` line in ``--time-format iso``."""
words = line.split()
for index, word in enumerate(words[1:], start=1):
if _ISO.match(word):
try:
at = datetime.fromisoformat(word)
except ValueError:
return None
if at.tzinfo is None:
at = at.replace(tzinfo=UTC)
port, host = _where(words[1:index])
return words[0], {"at": at, "port": port, "host": host, "source": source}
return None
def _source_logins(sections: _Sections, source: str) -> Iterable[tuple[str, _Login]]:
parse = _lastlog_line if source in ("lastlog2", "lastlog") else _iso_line
for line in sections.get((source, None), []):
parsed = parse(line, source)
if parsed is not None:
yield parsed
def _last_logins(sections: _Sections, sources: list[str]) -> dict[str, _Login]:
"""Each account's newest login over every source read."""
newest: dict[str, _Login] = {}
for source in sources:
for name, login in _source_logins(sections, source):
if name not in newest or login["at"] > newest[name]["at"]:
newest[name] = login
return newest
def _chage_date(value: str) -> str | None:
try:
return datetime.strptime(value, "%b %d, %Y").date().isoformat()
except ValueError:
return None
def _chage(lines: list[str]) -> dict[str, str]:
fields = {}
for line in lines:
key, sep, value = line.partition(":")
if sep:
fields[" ".join(key.split()).lower()] = value.strip()
return fields
def _expiry(value: str | None, *, must_change: bool = False) -> str | None:
"""A chage date as ISO, "never", "must_change"; None when it does not read as one."""
if value is None:
return None
if value == _NEVER:
return _NEVER
if value == _MUST_CHANGE:
return "must_change" if must_change else None
return _chage_date(value)
def _password(sections: _Sections, name: str) -> str | None:
words = (_first(sections, "passwd_status", name) or "").split()
if len(words) < 2 or words[0] != name:
return None
return _PASSWORD_STATES.get(words[1])
def _expired(account_expires: str | None, today: date | None) -> bool | None:
"""Whether the account expired on the host's date; pam_unix refuses it from that day."""
if account_expires is None:
return None
if account_expires == _NEVER:
return False
return None if today is None else date.fromisoformat(account_expires) <= today
def _locked(password: str | None, account_expires: str | None, today: date | None) -> bool | None:
"""Locked when either says so, open when both say not, else unknown."""
password_locked = None if password is None else password == "locked"
expired = _expired(account_expires, today)
if password_locked or expired:
return True
if password_locked is False and expired is False:
return False
return None
def _today(sections: _Sections) -> date | None:
try:
return date.fromisoformat(_first(sections, "now") or "")
except ValueError:
return None
def _faillock(lines: list[str] | None) -> int | None:
"""The valid failures in a ``faillock --user`` tally; None without its table."""
if not lines or not any(line.split()[:1] == ["When"] for line in lines):
return None
return sum(1 for line in lines if _ISO_DATE.match(line.strip()) and line.split()[-1] == "V")
def _btmp(sections: _Sections) -> dict[str, list[datetime]]:
failures: dict[str, list[datetime]] = {}
for name, login in _source_logins(sections, "lastb"):
failures.setdefault(name, []).append(login["at"])
return failures
def _failures(
sections: _Sections, name: str, last: _Login | None, btmp: dict[str, list[datetime]] | None
) -> tuple[int | None, bool]:
"""Failed attempts since *last* and whether the count is capped: lastb first."""
if btmp is not None:
seen = btmp.get(name, [])
count = sum(1 for at in seen if last is None or at > last["at"])
return count, count >= FAILED_LOGINS_READ
return _faillock(sections.get(("faillock", name))), False
def _failed_source(sections: _Sections, names: list[str]) -> str | None:
if ("lastb", None) in sections:
return "lastb"
if any(_faillock(sections.get(("faillock", name))) is not None for name in names):
return "faillock"
return None
def _account(
sections: _Sections,
entry: tuple[str, int, str, str],
last: _Login | None,
btmp: dict[str, list[datetime]] | None,
) -> LoginAccountDict:
name, uid, home, shell = entry
chage = _chage(sections.get(("chage", name), []))
password = _password(sections, name)
account_expires = _expiry(chage.get("account expires"))
failed, capped = _failures(sections, name, last, btmp)
return {
"name": name,
"uid": uid,
"home": home,
"shell": shell,
"last_login": None if last is None else last["at"].astimezone(UTC).isoformat(),
"last_login_from": None if last is None else last["host"],
"last_login_port": None if last is None else last["port"],
"last_login_source": None if last is None else last["source"],
"password": password,
"password_changed": _chage_date(chage.get("last password change", "")),
"password_expires": _expiry(chage.get("password expires"), must_change=True),
"account_expires": account_expires,
"locked": _locked(password, account_expires, _today(sections)),
"failed_logins": failed,
"failed_logins_capped": capped,
}
def parse_login_accounts(output: str) -> LoginAccountsDict:
"""Parse what :data:`LOGIN_ACCOUNTS_COMMAND` printed.
:raises ValueError: when the output carries no intact report.
"""
sections = _sections(output)
entries = _accounts(sections)
sources = [source for source in LOGIN_SOURCES if (source, None) in sections]
logins = _last_logins(sections, sources)
btmp = _btmp(sections) if ("lastb", None) in sections else None
return {
"accounts": [_account(sections, e, logins.get(e[0]), btmp) for e in entries],
"login_sources": sources,
"failed_logins_source": _failed_source(sections, [e[0] for e in entries]),
"privileged": _first(sections, "uid") == "0",
}
class LoginAccountsMixin:
"""Adds :meth:`get_login_accounts` 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_accounts_command` --
how a command reaches its host, and how it gains root there. Mixed in by the drivers
that can, so ``hasattr(driver, "get_login_accounts")`` stays a truthful answer.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def _run_login_accounts_command(self, command: str, *, privileged: bool) -> str:
"""Run *command* on the host and return what it printed; as root when
*privileged*. The command is a single ``sh -c`` invocation; it reads no stdin."""
...
def get_login_accounts(self) -> LoginAccountsDict:
"""
Returns every account on the host a person can log in with, and how it is used.
* accounts (list) - root and UID 1000 on with a login shell, in ``/etc/passwd``'s
order: name, uid, home, shell; last_login (ISO, UTC), last_login_from,
last_login_port and last_login_source; password ("set", "locked", "none"),
password_changed, password_expires and account_expires (ISO date, "never",
"must_change"), locked; failed_logins since the last login and
failed_logins_capped
* login_sources (list) - which of lastlog2, lastlog, wtmpdb, wtmp the host has
* failed_logins_source (str or None) - "lastb" or "faillock"
* privileged (bool) - read as root
``None`` in a field means not read. Read as root first; where root is refused, as
the login user: the last logins only.
Example::
{
"accounts": [{"name": "alice", "uid": 1000, "home": "/home/alice",
"shell": "/bin/bash",
"last_login": "2026-11-27T21:01:02+00:00",
"last_login_from": "192.0.2.10", "last_login_port": "pts/0",
"last_login_source": "lastlog", "password": "set",
"password_changed": "2026-11-01",
"password_expires": "never", "account_expires": "never",
"locked": False, "failed_logins": 2,
"failed_logins_capped": False}],
"login_sources": ["lastlog", "wtmp"],
"failed_logins_source": "lastb",
"privileged": True,
}
:raises ValueError: if neither reading carried an intact report.
"""
command = f"sh -c {quote(LOGIN_ACCOUNTS_COMMAND)}"
try:
return parse_login_accounts(self._run_login_accounts_command(command, privileged=True))
except ValueError:
pass
return parse_login_accounts(self._run_login_accounts_command(command, privileged=False))