Compare commits

...
7 Commits
Author SHA1 Message Date
christianmanivong 5b4195f028 Merge pull request 'feat(logins): every account a person can log in with, as one read-only reading, 4.51.0 (NetOrk/netork#2707)' (#138) from feature/host-logins into main
driver / types (push) Successful in 56s
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 13s
driver / test (3.12) (push) Successful in 1m17s
driver / test (3.13) (push) Successful in 1m6s
driver / lowest (push) Successful in 41s
driver / build (push) Successful in 33s
driver / security (push) Successful in 1m3s
driver / publish (push) Successful in 28s
CI / driver (push) Successful in 3m18s
2026-11-28 09:31:37 +00:00
christianmanivong e25aebbe45 fix(logins): the password states are named constants, not literals in a comparison (NetOrk/netork#2707)
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 17s
driver / types (pull_request) Successful in 52s
driver / test (3.13) (pull_request) Successful in 1m0s
driver / lowest (pull_request) Successful in 38s
driver / test (3.12) (pull_request) Successful in 1m18s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m19s
driver / publish (pull_request) Skipped
bandit reads password == "locked" as a hardcoded password (B105) and fails
the security job. A state word is none; STATE_SET, STATE_LOCKED and
STATE_NONE name them.
2026-11-28 09:42:10 +01:00
christianmanivong 4b4797e383 Merge NAPALM/napalm-device-types main (4.50.0) into feature/host-logins
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Successful in 21s
driver / types (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 1m19s
driver / test (3.12) (pull_request) Successful in 1m26s
driver / lowest (pull_request) Successful in 47s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Failing after 1m5s
CI / driver (pull_request) Failing after 2m45s
driver / publish (pull_request) Skipped
v4.50.0 went to #140, so this branch's release is 4.51.0 now.
2026-11-28 08:22:46 +01:00
christianmanivong 917e9e570d Merge pull request 'feat(login-sources): where a device checks a login, and what each place asks for, 4.50.0 (NetOrk/netork#662)' (#140) from feature/web-login-auth into main
driver / types (push) Successful in 57s
driver / standard (push) Successful in 18s
driver / lint (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m19s
driver / test (3.13) (push) Successful in 1m11s
driver / lowest (push) Successful in 46s
driver / build (push) Successful in 32s
driver / security (push) Successful in 59s
driver / publish (push) Successful in 30s
CI / driver (push) Successful in 3m39s
2026-11-28 07:06:53 +00:00
christianmanivong d778c805c1 feat(login-sources): where a device checks a login, and what each place asks for, 4.50.0 (NetOrk/netork#662)
driver / standard (pull_request) Successful in 20s
driver / lint (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Successful in 1m22s
driver / test (3.13) (pull_request) Successful in 1m13s
driver / lowest (pull_request) Successful in 43s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 3m0s
driver / publish (pull_request) Skipped
LoginSourceDict names one source with the device's word for its kind and what
it asks for: password, password_otp, external or unknown. WebLoginAuthDict is
what a driver's get_web_login_auth returns, every source the web interface
tries, in the device's order. SshServerAuthDict takes password_sources and
server_enabled for a platform that writes sshd_config itself.
2026-11-28 08:02:12 +01:00
christianmanivong 14217b6eeb chore(release): 4.50.0
driver / lint (pull_request) Successful in 16s
driver / standard (pull_request) Successful in 20s
driver / types (pull_request) Successful in 1m3s
driver / test (3.13) (pull_request) Successful in 1m19s
driver / test (3.12) (pull_request) Successful in 1m24s
driver / lowest (pull_request) Successful in 45s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Failing after 1m2s
CI / driver (pull_request) Failing after 2m41s
driver / publish (pull_request) Skipped
2026-11-28 03:46:33 +01:00
christianmanivong 91b939236f 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.
2026-11-28 03:46:33 +01:00
9 changed files with 1144 additions and 2 deletions

No files matched your search

+36
View File
@@ -7,6 +7,42 @@ recorded here; their history is the git log.
## [Unreleased]
## [4.51.0] - 2026-11-28
### Added
- `LoginAccountsMixin.get_login_accounts()`: every account on a Linux host a person can
log in with, read with one fixed, read-only command (NetOrk/netork#2707). Root and UID
1000 on with a login shell (`login_capable`), from `/etc/passwd` -- name, UID, home and
shell only, never the comment field; accounts from a directory are not there and not
read. Each with its last login (ISO, UTC), where it came from and which tool told it:
the newest of `lastlog2`, `lastlog`, `wtmpdb last` and `last`, so a host upgraded to
lastlog2 or a desktop login only wtmp saw still reads right. Its password state
(`passwd -S`: `set`, `locked`, `none`), password change, password and account expiry
(`chage -l`: an ISO date, `never`, `must_change`), and `locked` -- the password locked or
the account expired on the host's date. The failed attempts since the last login as a
number: from `lastb` (the newest `FAILED_LOGINS_READ`, 1000, per account;
`failed_logins_capped` when reached), else `pam_faillock`'s tally. `LC_ALL=C`, no stdin,
no password hash read. Root first; where root is refused, as the login user, when the
lock, the expiry and the failures are `None`. A driver supplies
`_run_login_accounts_command(command, *, privileged)`.
- `parse_login_accounts`, `LOGIN_ACCOUNTS_COMMAND`, `login_capable`, and the
`LoginAccountDict` and `LoginAccountsDict` shapes (in `login_accounts`).
## [4.50.0] - 2026-11-28
### Added
- `login_sources`: where a device checks a person's login, and what each place asks for
(NetOrk/netork#662). `LoginSourceDict` names one source with the device's own word for its
kind and what it asks for (`LoginFactors`: `password`, `password_otp`, `external`,
`unknown`; all four in `LOGIN_FACTORS`). `WebLoginAuthDict` is the reading a driver returns
from `get_web_login_auth`: every source the web interface tries, in the device's order.
There is no mixin, so `hasattr(driver, "get_web_login_auth")` stays a truthful answer.
- `SshServerAuthDict` takes two optional keys for a platform that writes sshd_config itself
and is read from its own configuration. `password_sources` says what checks a password or
keyboard-interactive login where the platform decides that rather than PAM's stack.
`server_enabled` is False when the platform's SSH server is switched off. Readings from
`sshd -T` leave both out.
## [4.49.0] - 2026-11-28
### Added
+19
View File
@@ -171,6 +171,16 @@ command line, and `ID`/`ID_LIKE` from `/etc/os-release`. Read as root first and,
is refused, as the login user without the profile counts. A driver supplies
`_run_hardening_command(command, privileged=)`; what was not read is `None`, never "off".
`LoginAccountsMixin` (`get_login_accounts`) is mixed in the same way: every account on the
host a person can log in with -- root and UID 1000 on, with a shell that is not `nologin` or
`false`, from `/etc/passwd` (name, UID, home and shell only; directory accounts are not read)
-- with its last login, the newest any of `lastlog2`, `lastlog`, `wtmpdb last` and `last`
knows, and where it came from; its lock and expiry from `passwd -S` and `chage -l`; and the
failed attempts since that login, from `lastb` (the newest 1000 per account) or else
`pam_faillock`'s tally. Read as root first and, where root is refused, as the login user,
when the lock, the expiry and the failures are `None`. A driver supplies
`_run_login_accounts_command(command, privileged=)`.
`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
@@ -354,6 +364,15 @@ login user and followed through `@include`, `include` and `substack`. Which of t
second factor is the consumer's call. `Match` blocks are not read. `OpenSshServerMixin`
carries it; a driver can also mix it in alone and supply `run_command`.
`login_sources` describes where a device checks a person's login, for platforms that try a
login against a list of authentication servers and let in whatever the first one accepts
(OPNsense). A driver that can read its web interface's list implements
`get_web_login_auth() -> WebLoginAuthDict`: each source with its name, the device's word for
its kind, and what it asks for (`password`, `password_otp`, `external` or `unknown`). Such a
platform's `get_ssh_server_auth` may add `password_sources` (what checks an SSH password)
and `server_enabled` (False when SSH is off) to `SshServerAuthDict`. Which source counts as
a second factor is the consumer's call.
`SudoHistoryMixin` (`get_history_sudo_lines`, `remove_history_sudo_lines`) deals with what
a driver left behind when it typed `echo '<password>' | sudo -S -p "" …` into an interactive
shell: that line, password and all, in the login user's shell history, and files its partial
+25
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,20 @@ 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.login_sources import (
LOGIN_FACTORS,
LoginFactors,
LoginSourceDict,
WebLoginAuthDict,
)
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 +584,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",
@@ -657,6 +678,10 @@ __all__ = [
"parse_system_identity",
"OpenSshServerMixin",
"PamAuthEntryDict",
"LOGIN_FACTORS",
"LoginFactors",
"LoginSourceDict",
"WebLoginAuthDict",
"SshServerAuthDict",
"SshServerAuthMixin",
"SSHD_EFFECTIVE_COMMAND",
+452
View File
@@ -0,0 +1,452 @@
"""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} ")
#: The states of an account's password, as the reading names them. Named, not literals in
#: a comparison: a state word is no password, but a scanner reading ``password == "..."``
#: takes it for one (bandit B105).
STATE_SET, STATE_LOCKED, STATE_NONE = "set", "locked", "none"
#: ``passwd -S``'s second word: shadow's and libuser's.
_PASSWORD_STATES = {
"P": STATE_SET,
"PS": STATE_SET,
"L": STATE_LOCKED,
"LK": STATE_LOCKED,
"NP": STATE_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 == STATE_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))
+59
View File
@@ -0,0 +1,59 @@
"""Where a device checks a person's login, and what each place asks for.
Some platforms keep their own list of authentication servers and try a login
against each in turn, and the first one that accepts it lets the person in. On
OPNsense that list (*System → Settings → Administration → Authentication*) serves
the web interface, the console and sshd's password login alike. Whether a password
alone gets in then depends on every server in the list, not on one switch. So the
driver names each place it tries, in the device's own order, with what that place
asks for. Which of them counts as a second factor for a policy is the consumer's
call (NetOrk/netork#662).
Two readings carry these sources:
- ``get_web_login_auth`` returns :class:`WebLoginAuthDict`: how the device's web
interface lets people log in. A driver that cannot tell does not have the method,
so ``hasattr`` stays a truthful answer.
- :class:`~napalm_device_types.ssh_server_auth.SshServerAuthDict` takes
``password_sources`` where the platform, not PAM's stack, decides what checks a
password over SSH.
What a source asks for (:data:`LOGIN_FACTORS`):
- ``password``: a password alone, as with local accounts or an LDAP bind.
- ``password_otp``: a password and a one-time code together. Without a code
there is no login.
- ``external``: another system decides, for example a RADIUS server. How many
factors it asks for cannot be seen from the device.
- ``unknown``: a kind of source the driver does not know.
"""
from __future__ import annotations
from typing import Literal, TypedDict
LoginFactors = Literal["password", "password_otp", "external", "unknown"]
#: Every value of :data:`LoginFactors`, in the order of the module docstring.
LOGIN_FACTORS: tuple[LoginFactors, ...] = ("password", "password_otp", "external", "unknown")
class LoginSourceDict(TypedDict):
"""One place a login is checked.
``{"name": "TOTP", "kind": "totp", "factors": "password_otp"}``
"""
#: The source's name as the device shows it.
name: str
#: The device's own word for the kind, as written: ``local``, ``totp``, ``radius``.
kind: str
factors: LoginFactors
class WebLoginAuthDict(TypedDict):
"""How a device's web interface lets people log in, as ``get_web_login_auth`` read it."""
#: Every source a login is tried against, in the device's order. A login that
#: any one of them accepts gets in.
sources: list[LoginSourceDict]
+24 -1
View File
@@ -30,6 +30,8 @@ import re
from collections.abc import Mapping
from typing import TYPE_CHECKING, TypedDict
from napalm_device_types.login_sources import LoginSourceDict
if TYPE_CHECKING: # pragma: no cover - for type checkers only
from napalm_device_types.channel import CommandResult
@@ -62,7 +64,18 @@ class PamAuthEntryDict(TypedDict):
args: list[str]
class SshServerAuthDict(TypedDict):
class _PlatformSshAuthDict(TypedDict, total=False):
"""The keys of :class:`SshServerAuthDict` only a platform that writes sshd_config sets.
A base of their own, as ``total=False``: ``NotRequired`` under postponed
annotations is not seen by the class at runtime.
"""
password_sources: list[LoginSourceDict]
server_enabled: bool
class SshServerAuthDict(_PlatformSshAuthDict):
"""How an OpenSSH server lets people log in, as ``get_ssh_server_auth`` read it.
The global settings ``sshd -T`` prints. A ``Match`` block can change them for
@@ -77,6 +90,16 @@ class SshServerAuthDict(TypedDict):
``use_pam`` is None where sshd has no PAM (OpenBSD). ``pam_auth_stack`` is the
``auth`` stack PAM runs for sshd, includes and substacks followed; None when
PAM is off or its files gave nothing for sshd.
Two keys only a platform that writes sshd_config itself sets, read from its
own configuration rather than from a running sshd:
- ``password_sources``: what checks a password or keyboard-interactive login,
where the platform decides that rather than PAM's stack. OPNsense's PAM
module tries its authentication servers. Absent where the stack says it.
- ``server_enabled``: False when the platform's SSH server is switched off.
Nobody then logs in over SSH, whatever the other keys say. Absent where the
reading came from a running sshd.
"""
password_authentication: bool
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-device-types"
version = "4.49.0"
version = "4.51.0"
description = "Abstract device-type base classes for NAPALM drivers"
readme = "README.md"
requires-python = ">=3.12"
+483
View File
@@ -0,0 +1,483 @@
"""get_login_accounts: every account on a Linux host a person can log in with (NetOrk/netork#2707).
The accounts come from ``/etc/passwd`` (root and UID 1000 on, with a shell that lets
them in), their last login from whichever of ``lastlog2``, ``lastlog``, ``wtmpdb last``
and ``last`` the host has, their lock and expiry from ``passwd -S`` and ``chage -l``,
and the failed attempts since their last login from ``lastb`` or ``faillock``. The
last three need root; read as the login user they are ``None``, never "unlocked" or
"no failures".
"""
from __future__ import annotations
import os
import subprocess
import pytest
from napalm_device_types import OSDriver
from napalm_device_types.login_accounts import (
FAILED_LOGINS_READ,
LOGIN_ACCOUNTS_COMMAND,
LoginAccountsMixin,
login_capable,
parse_login_accounts,
)
PASSWD = (
"root:0:/root:/bin/bash\n"
"alice:1000:/home/alice:/bin/bash\n"
"bob:1001:/home/bob:/usr/bin/zsh\n"
"deploy:1002:/srv/deploy:/bin/sh"
)
#: Debian 12 as root: the legacy lastlog, wtmp through ``last``, btmp through ``lastb``,
#: Debian's ``passwd -S``. alice logs in over SSH, bob never did, deploy is locked by
#: netOrk (``usermod -L -e 1``).
DEBIAN_12 = [
("uid", "0"),
("now", "2026-11-28"),
("passwd", PASSWD),
(
"lastlog",
"Username Port From Latest\n"
"root tty1 Mon Oct 5 09:12:44 +0200 2026\n"
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026\n"
"bob **Never logged in**\n"
"deploy pts/1 198.51.100.7 Sat Aug 1 10:00:00 +0200 2026",
),
(
"wtmp",
"alice pts/0 192.0.2.10 2026-11-27T22:01:02+01:00 - 2026-11-27T23:00:00+01:00 (00:59)\n"
"root tty1 2026-10-05T09:12:44+02:00 - 2026-10-05T09:20:00+02:00 (00:07)",
),
(
"lastb",
"alice ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)\n"
"alice ssh:notty 203.0.113.5 2026-11-28T01:02:01+01:00 - 2026-11-28T01:02:01+01:00 (00:00)\n"
"alice ssh:notty 203.0.113.5 2026-11-26T08:00:00+01:00 - 2026-11-26T08:00:00+01:00 (00:00)\n"
"root ssh:notty 203.0.113.9 2026-11-20T03:00:00+01:00 - 2026-11-20T03:00:00+01:00 (00:00)\n"
"root ssh:notty 203.0.113.9 2026-11-19T03:00:00+01:00 - 2026-11-19T03:00:00+01:00 (00:00)",
),
("passwd_status root", "root P 2026-01-15 0 99999 7 -1"),
(
"chage root",
"Last password change\t\t\t\t\t: Jan 15, 2026\n"
"Password expires\t\t\t\t\t: never\n"
"Password inactive\t\t\t\t\t: never\n"
"Account expires\t\t\t\t\t\t: never\n"
"Minimum number of days between password change\t\t: 0\n"
"Maximum number of days between password change\t\t: 99999\n"
"Number of days of warning before password expires\t: 7",
),
("passwd_status alice", "alice P 11/01/2026 0 90 7 -1"),
(
"chage alice",
"Last password change\t\t\t\t\t: Nov 01, 2026\n"
"Password expires\t\t\t\t\t: Jan 30, 2027\n"
"Password inactive\t\t\t\t\t: never\n"
"Account expires\t\t\t\t\t\t: Dec 31, 2026",
),
("passwd_status bob", "bob NP 2026-11-01 0 99999 7 -1"),
(
"chage bob",
"Last password change\t\t\t\t\t: password must be changed\n"
"Password expires\t\t\t\t\t: password must be changed\n"
"Password inactive\t\t\t\t\t: password must be changed\n"
"Account expires\t\t\t\t\t\t: never",
),
("passwd_status deploy", "deploy L 2026-08-01 0 99999 7 -1"),
(
"chage deploy",
"Last password change\t\t\t\t\t: Aug 01, 2026\n"
"Password expires\t\t\t\t\t: never\n"
"Password inactive\t\t\t\t\t: never\n"
"Account expires\t\t\t\t\t\t: Jan 02, 1970",
),
]
#: Debian 13 as root: lastlog2 and wtmpdb, no btmp; pam_faillock counts failures.
DEBIAN_13 = [
("uid", "0"),
("now", "2026-11-28"),
("passwd", "root:0:/root:/bin/bash\nalice:1000:/home/alice:/bin/bash"),
(
"lastlog2",
"Username Port From Latest\n"
"alice pts/2 2001:db8::5 Thu Nov 26 18:30:00 +0100 2026\n"
"root **Never logged in**",
),
(
"wtmpdb",
"alice pts/3 2001:db8::6 2026-11-27T07:15:00+01:00 - 2026-11-27T07:20:00+01:00 (00:05)",
),
("passwd_status root", "root L 2026-11-01 0 99999 7 -1"),
("chage root", "Account expires\t\t\t\t\t\t: never"),
(
"faillock root",
"root:\nWhen Type Source Valid",
),
("passwd_status alice", "alice P 2026-11-01 0 99999 7 -1"),
("chage alice", "Account expires\t\t\t\t\t\t: never"),
(
"faillock alice",
"alice:\n"
"When Type Source Valid\n"
"2026-11-28 01:02:03 RHOST 203.0.113.5 V\n"
"2026-11-28 01:02:09 RHOST 203.0.113.5 V\n"
"2026-11-27 23:00:00 TTY tty2 I",
),
]
#: AlmaLinux 9 as root: libuser's ``passwd -S`` with its comment.
ALMA_9 = [
("uid", "0"),
("now", "2026-11-28"),
("passwd", "alice:1000:/home/alice:/bin/bash"),
(
"lastlog",
"Username Port From Latest\n"
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026",
),
("passwd_status alice", "alice LK 2026-11-01 0 99999 7 -1 (Password locked.)"),
("chage alice", "Account expires\t\t\t\t\t\t: never"),
]
#: The same Debian host read as the login user: no root, so no lock, expiry or failures.
AS_LOGIN_USER = [
("uid", "1000"),
("now", "2026-11-28"),
("passwd", PASSWD),
(
"lastlog",
"Username Port From Latest\n"
"alice pts/0 192.0.2.10 Fri Nov 27 22:01:02 +0100 2026",
),
("passwd_status root", ""),
("chage root", ""),
("faillock root", ""),
("passwd_status alice", ""),
("chage alice", "Account expires\t\t\t\t\t\t: never"),
("faillock alice", ""),
]
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}LOGINS_BEGIN\n{body}LOGINS_END\n"
def _by_name(reading):
return {account["name"]: account for account in reading["accounts"]}
class TestDebian12:
def test_every_login_capable_account_in_passwd_order(self):
reading = parse_login_accounts(_wire(DEBIAN_12))
assert [a["name"] for a in reading["accounts"]] == ["root", "alice", "bob", "deploy"]
assert reading["privileged"] is True
assert reading["login_sources"] == ["lastlog", "wtmp"]
assert reading["failed_logins_source"] == "lastb"
def test_the_last_login_with_where_it_came_from(self):
alice = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["alice"]
assert alice["uid"] == 1000
assert alice["home"] == "/home/alice"
assert alice["shell"] == "/bin/bash"
assert alice["last_login"] == "2026-11-27T21:01:02+00:00"
assert alice["last_login_from"] == "192.0.2.10"
assert alice["last_login_port"] == "pts/0"
assert alice["last_login_source"] == "lastlog"
def test_never_logged_in(self):
bob = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["bob"]
assert bob["last_login"] is None
assert bob["last_login_source"] is None
def test_a_console_login_has_a_port_and_no_host(self):
root = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["root"]
assert root["last_login"] == "2026-10-05T07:12:44+00:00"
assert (root["last_login_port"], root["last_login_from"]) == ("tty1", None)
def test_password_and_expiry(self):
accounts = _by_name(parse_login_accounts(_wire(DEBIAN_12)))
assert accounts["alice"]["password"] == "set"
assert accounts["alice"]["password_changed"] == "2026-11-01"
assert accounts["alice"]["password_expires"] == "2027-01-30"
assert accounts["alice"]["account_expires"] == "2026-12-31"
assert accounts["alice"]["locked"] is False
assert accounts["root"]["password_expires"] == "never"
assert accounts["root"]["account_expires"] == "never"
def test_no_password_that_must_be_changed(self):
bob = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["bob"]
assert bob["password"] == "none"
assert bob["password_changed"] is None
assert bob["password_expires"] == "must_change"
assert bob["locked"] is False
def test_locked_as_netork_locks_an_account(self):
"""``usermod -L -e 1``: the password locked and the account expired in 1970."""
deploy = _by_name(parse_login_accounts(_wire(DEBIAN_12)))["deploy"]
assert deploy["password"] == "locked"
assert deploy["account_expires"] == "1970-01-02"
assert deploy["locked"] is True
def test_failed_logins_since_the_last_one_that_worked(self):
accounts = _by_name(parse_login_accounts(_wire(DEBIAN_12)))
# alice's last login was 2026-11-27 22:01; two failures came after it.
assert accounts["alice"]["failed_logins"] == 2
# root last logged in on 2026-10-05: both failures are later.
assert accounts["root"]["failed_logins"] == 2
# No line in btmp: none, and btmp was read.
assert accounts["bob"]["failed_logins"] == 0
assert accounts["alice"]["failed_logins_capped"] is False
class TestDebian13:
def test_the_newest_login_over_every_source(self):
"""lastlog2 saw alice on the 26th, wtmpdb on the 27th: the 27th is her last login."""
reading = parse_login_accounts(_wire(DEBIAN_13))
alice = _by_name(reading)["alice"]
assert reading["login_sources"] == ["lastlog2", "wtmpdb"]
assert alice["last_login"] == "2026-11-27T06:15:00+00:00"
assert alice["last_login_source"] == "wtmpdb"
assert alice["last_login_from"] == "2001:db8::6"
def test_faillock_counts_its_valid_failures(self):
reading = parse_login_accounts(_wire(DEBIAN_13))
accounts = _by_name(reading)
assert reading["failed_logins_source"] == "faillock"
assert accounts["alice"]["failed_logins"] == 2
assert accounts["root"]["failed_logins"] == 0
def test_a_locked_password_locks_the_account(self):
root = _by_name(parse_login_accounts(_wire(DEBIAN_13)))["root"]
assert (root["password"], root["locked"]) == ("locked", True)
class TestAlma9:
def test_libusers_status_words(self):
alice = _by_name(parse_login_accounts(_wire(ALMA_9)))["alice"]
assert alice["password"] == "locked"
assert alice["locked"] is True
def test_without_lastb_or_faillock_failures_are_unread(self):
reading = parse_login_accounts(_wire(ALMA_9))
assert reading["failed_logins_source"] is None
assert _by_name(reading)["alice"]["failed_logins"] is None
class TestAsTheLoginUser:
def test_what_needs_root_is_none(self):
reading = parse_login_accounts(_wire(AS_LOGIN_USER))
root = _by_name(reading)["root"]
assert reading["privileged"] is False
assert reading["failed_logins_source"] is None
assert root["password"] is None
assert root["password_expires"] is None
assert root["account_expires"] is None
assert root["locked"] is None
assert root["failed_logins"] is None
def test_the_last_login_is_still_read(self):
alice = _by_name(parse_login_accounts(_wire(AS_LOGIN_USER)))["alice"]
assert alice["last_login"] == "2026-11-27T21:01:02+00:00"
# Its own chage is readable without root.
assert alice["account_expires"] == "never"
class TestNotReadIsNone:
def test_no_login_source_is_not_never(self):
"""A host without any of the tools: the last login is unread, not "never"."""
reading = parse_login_accounts(
_wire([("uid", "0"), ("now", "2026-11-28"), ("passwd", PASSWD)])
)
assert reading["login_sources"] == []
assert all(a["last_login"] is None for a in reading["accounts"])
def test_output_without_the_frame_raises(self):
with pytest.raises(ValueError):
parse_login_accounts("sudo: a password is required\n")
def test_whatever_surrounds_the_frame_is_ignored(self):
noise = "Last login: today\nprintf '%s%s\\n' LOGINS_ BEGIN; ...\n"
assert len(parse_login_accounts(_wire(DEBIAN_12, noise=noise))["accounts"]) == 4
def test_a_line_none_of_the_formats_knows_is_left_out(self):
reading = parse_login_accounts(
_wire(
[
("uid", "0"),
("passwd", "alice:1000:/home/alice:/bin/bash\nbroken line"),
("lastlog", "alice pts/0 somewhere yesterday"),
("wtmp", "alice pts/0 nowhere\nwtmp begins 2026-01-01T00:00:00+00:00"),
("passwd_status alice", "alice"),
("chage alice", "Account expires : sometime"),
]
)
)
alice = _by_name(reading)["alice"]
assert [a["name"] for a in reading["accounts"]] == ["alice"]
assert alice["last_login"] is None
assert alice["password"] is None
assert alice["account_expires"] is None
assert alice["locked"] is None
class TestFailedLogins:
def test_without_a_last_login_every_failure_counts(self):
reading = parse_login_accounts(
_wire(
[
("uid", "0"),
("passwd", "bob:1001:/home/bob:/bin/bash"),
(
"lastb",
"bob ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)",
),
]
)
)
assert _by_name(reading)["bob"]["failed_logins"] == 1
def test_a_full_read_is_capped(self):
"""The command keeps the newest :data:`FAILED_LOGINS_READ` per account: a count
that reaches it is "at least"."""
line = "alice ssh:notty 203.0.113.5 2026-11-28T01:02:03+01:00 - 2026-11-28T01:02:03+01:00 (00:00)"
reading = parse_login_accounts(
_wire(
[
("uid", "0"),
("passwd", "alice:1000:/home/alice:/bin/bash"),
("lastb", "\n".join([line] * FAILED_LOGINS_READ)),
]
)
)
alice = _by_name(reading)["alice"]
assert alice["failed_logins"] == FAILED_LOGINS_READ
assert alice["failed_logins_capped"] is True
class TestLoginCapable:
@pytest.mark.parametrize(
"uid, shell, capable",
[
(0, "/bin/bash", True),
(1000, "/bin/sh", True),
(1000, "", True),
(999, "/bin/bash", False),
(65534, "/bin/sh", False),
(1000, "/usr/sbin/nologin", False),
(1000, "/sbin/nologin", False),
(1000, "/bin/false", False),
(1000, "/usr/bin/false", False),
],
)
def test_root_and_people_with_a_shell(self, uid, shell, capable):
assert login_capable(uid, shell) is capable
def test_a_service_account_in_passwd_is_left_out(self):
reading = parse_login_accounts(
_wire(
[
("uid", "0"),
(
"passwd",
"root:0:/root:/bin/bash\n"
"netork:900:/var/lib/netork:/bin/bash\n"
"nobody:65534:/nonexistent:/usr/sbin/nologin\n"
"svc:1003:/srv/svc:/usr/sbin/nologin",
),
]
)
)
assert [a["name"] for a in reading["accounts"]] == ["root"]
class _Driver(OSDriver, LoginAccountsMixin):
def __init__(self, outputs):
self.outputs = list(outputs)
self.calls: list[tuple[str, bool]] = []
def _run_login_accounts_command(self, command: str, *, privileged: bool) -> str:
self.calls.append((command, privileged))
return self.outputs.pop(0)
class TestTheMixin:
def test_read_as_root_first(self):
driver = _Driver([_wire(DEBIAN_12)])
reading = driver.get_login_accounts()
assert driver.calls[0][1] is True
assert reading["privileged"] is True
def test_root_refused_reads_as_the_login_user(self):
driver = _Driver(["sudo: a password is required\n", _wire(AS_LOGIN_USER)])
reading = driver.get_login_accounts()
assert [privileged for _, privileged in driver.calls] == [True, False]
assert reading["privileged"] is False
def test_the_command_goes_to_sh(self):
driver = _Driver([_wire(ALMA_9)])
driver.get_login_accounts()
assert driver.calls[0][0].startswith("sh -c ")
class TestTheCommand:
def test_the_frame_is_not_in_the_command_itself(self):
assert "LOGINS_BEGIN" not in LOGIN_ACCOUNTS_COMMAND
assert "LOGINS_END" not in LOGIN_ACCOUNTS_COMMAND
def test_it_changes_nothing(self):
for verb in ("usermod", "passwd -l", "chage -E", "--reset", "lastlog2 -C", " > ", ">>"):
assert verb not in LOGIN_ACCOUNTS_COMMAND
def test_it_reads_no_stdin_and_sends_no_password_hash(self):
"""A sudo password on stdin must not reach a tool; the hashes in ``/etc/shadow``
are never read: ``passwd -S`` and ``chage -l`` say what is needed."""
assert LOGIN_ACCOUNTS_COMMAND.startswith("exec </dev/null; ")
assert "shadow" not in LOGIN_ACCOUNTS_COMMAND
def test_no_gecos_field_leaves_the_host(self):
"""The fifth field of ``/etc/passwd`` is a person's name; only name, uid, home and
shell are printed."""
assert '{print $1":"$3":"$6":"$7}' in LOGIN_ACCOUNTS_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_ACCOUNTS_COMMAND], capture_output=True, text=True, timeout=60
).stdout
reading = parse_login_accounts(out)
assert isinstance(reading["accounts"], list)
+45
View File
@@ -0,0 +1,45 @@
"""Where a device checks a login, and what each place asks for (NetOrk/netork#662).
The module is a contract, not a reader: the shapes a driver returns from
``get_web_login_auth`` and, where its platform says it, in ``get_ssh_server_auth``.
These tests pin the vocabulary consumers match on.
"""
from __future__ import annotations
from typing import get_args, get_type_hints
import napalm_device_types
from napalm_device_types.login_sources import (
LOGIN_FACTORS,
LoginFactors,
LoginSourceDict,
WebLoginAuthDict,
)
from napalm_device_types.ssh_server_auth import SshServerAuthDict
def test_the_factor_names_are_the_literal_s():
assert LOGIN_FACTORS == get_args(LoginFactors)
assert LOGIN_FACTORS == ("password", "password_otp", "external", "unknown")
def test_a_source_names_itself_its_kind_and_what_it_asks_for():
assert set(get_type_hints(LoginSourceDict)) == {"name", "kind", "factors"}
def test_a_web_reading_is_its_sources_in_the_device_s_order():
assert set(get_type_hints(WebLoginAuthDict)) == {"sources"}
def test_an_ssh_reading_may_say_where_a_password_is_checked_and_that_sshd_is_off():
optional = SshServerAuthDict.__optional_keys__
assert {"password_sources", "server_enabled"} <= optional
# The keys every OpenSSH reading carries stay required.
assert "password_authentication" in SshServerAuthDict.__required_keys__
def test_the_package_exports_the_shapes():
for name in ("LOGIN_FACTORS", "LoginFactors", "LoginSourceDict", "WebLoginAuthDict"):
assert name in napalm_device_types.__all__
assert hasattr(napalm_device_types, name)