diff --git a/CHANGELOG.md b/CHANGELOG.md index 847c85a..688bf4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,106 @@ recorded here; their history is the git log. ## [Unreleased] +## [4.56.0] - 2026-12-02 + +### Added +- `HostStorageMixin`: a host's disks, pools, volumes and drive health without the storage + role (NetOrk/netork#2896, #2705). It declares `get_disks`, `get_disk_pools` and + `get_volumes` in `StorageDriver`'s shapes, and `get_disk_smart()`, a dict of + `DiskSmartDict` keyed by the disk's slot: model, serial, type, size, health (`"ok"`, + `"warning"`, `"failed"`, `"unknown"`), wearout, temperature, percentage used, available + spare, reallocated sectors, power-on hours, and optionally the highest temperature and + the uncorrected read and write errors -- `None` where the drive does not report one. + These are the keys Proxmox's `get_disk_smart` already fills. A disk that does not say + reads temperature `-1` and health `"unknown"` in `get_disks` and is left out of + `get_disk_smart`. Nothing changes for `StorageDriver`. +- `HostVolumeDict`: a `LogicalVolumeDict` with an optional `file_system` and `health`. +- New values in existing string fields: a disk's `type` may be `"unknown"`, a pool's + `type` `"storage-spaces"` and its `level` `"parity"`. +- `clean_system_identity(...)`: the SMBIOS identity and system firmware from values a host + read some other way than the DMI files -- Windows through its CIM classes + (NetOrk/netork#2888) -- with the same placeholders empty as `parse_system_identity`, + which now uses it. The release date is passed as `YYYY-MM-DD`; anything else reads as no + date. +- `UserDict.sid` (optional): the account's security identifier on a host that names + accounts by one (Windows, NetOrk/netork#2889). `uid` stays an int: there, the relative + identifier, the SID's last part. +- Login accounts and login sessions from another platform than Linux (NetOrk/netork#2895), + for Windows hosts in the access review. All optional, so the Linux reading and every + driver that builds one stay as they are: + - `LoginAccountDict` may carry `sid` (Windows' security identifier; `uid` is then the + RID, the SID's last part), `administrator` (a member of the host's Administrators) and + `remote_desktop` (may log in at a remote desktop), each `None` where not read. + - `LoginAccountsDict` may carry `groups`: the host's groups that grant administering it + or a remote desktop login (`LoginGroupDict`: name, SID, `grants` of `LOGIN_GRANTS`, + members), with every member as the host names it, a directory's accounts and groups + included (`LoginGroupMemberDict`: name, SID, `local`, `group`). + - `LoginSessionsDict` may carry `records_since`: the oldest entry the record the sessions + came from still holds, so a log that rotated within the window does not read as + "nobody logged in" before it. +- A Windows host's firewall as a reading of its own (NetOrk/netork#2894), carried by + `get_host_firewall` beside the netfilter one: `HostFirewallDict` gains the optional key + `windows` (`WindowsFirewallDict`), with `sources` `["windows-firewall"]` and no chains. + It holds the three profiles (`WindowsFirewallProfileDict`: on or off, default inbound and + outbound action, "block all incoming connections", whether local rules apply), every + enabled rule of the active policy with its filters (`WindowsFirewallRuleDict`: profiles, + protocol, ports, addresses, program, service, app package, interfaces and their types, + IPsec authentication, where the rule comes from, group policy included), and which + profile each connected interface is in (`WindowsFirewallConnectionDict`). + `WINDOWS_FIREWALL_PROFILES` names the profiles. An application that knows only chains + finds none in a Windows reading, and proves nothing from it. +- `WindowsFeaturesMixin.get_windows_features()` (NetOrk/netork#2898), declared: every + optional feature a Windows host's image knows (`WindowsFeaturesDict`), each with its name + as Windows spells it (`SMB1Protocol`, `MSMQ-Server`, `IIS-WebServerRole`) and its state + (`WINDOWS_FEATURE_STATES`: enabled, disabled, absent, unknown). What turns a CVE that + needs a role or feature into "met" or "not met" on a host. + +### Changed +- The netfilter shapes (`HostFirewallDict`, `NetfilterChainDict`, `NetfilterRuleDict`, + `NetfilterMatchDict`) moved to `napalm_device_types.host_firewall_models`; `models` + re-exports them, so every import keeps working. +- `HostEventsMixin.get_host_events(since=None)`, declared: what a host's own log recorded + that says something is wrong with it (NetOrk/netork#2897), for an application that warns + of it. A fixed set of kinds (`HOST_EVENT_KINDS`): unexpected shutdowns, system crashes + with their stop code, fatal and corrected hardware errors, disk and file system errors, + programs and services that crashed. Each `HostEventDict` names its kind, time (ISO, UTC), + what it is about in words that do not depend on the host's language, where it was + recorded and the host's message, cut to `HOST_EVENT_MESSAGE_CHARS`; `host_event()` builds + one. The reading covers `HOST_EVENT_WINDOW_DAYS` (7) days by default and says which kinds + it read up to its bound (`capped`) and which it could not read (`unread`). +- Log sources of kind `"eventlog"`: a Windows event channel, named by the new optional + `LogSourceDict.channel`, with its `.evtx` file as `path` (`eventlog_source()`, + `LOG_SOURCE_KINDS`, `EVENTLOG`). +- `ServiceDict` says how a service's last run ended, all optional: `result` in systemd's + `Result` words (`SERVICE_RESULT_SUCCESS`, `SERVICE_RESULT_EXIT_CODE`), `exit_code`, + `trigger_start` and the `account` it runs as, so that a service that died is told from + one stopped on purpose. `ServiceDict` is exported from the package. +- `HostRepairMixin`: a host's own checks and repairs as a fixed catalog of runs + (NetOrk/netork#2899), one method each: `verify_system_files()`, `repair_system_files()`, + `check_component_store()`, `repair_component_store()`, `update_antimalware_signatures()` + and `scan_antimalware(quick=True)`. Each streams the tool's output line by line to `log`, + is bounded in time (by the driver, or tighter by the caller's `limit` in seconds) + and returns a `HostRepairResultDict` (`success`, `output`, `exit_code`, `error`). A check + never repairs: a repair is a method of its own. Not on any role base; a driver defines the + runs its host can do, and `offered_host_repairs(driver_cls)` lists them. +- `tool_outcome(lines, exit_code, tool=...)`: the result of a run from its tool's output and + exit code. Exit code 0 succeeds; any other, or none, fails with the tool's last lines. A + negative (signed 32-bit) exit code is read as unsigned, and an HRESULT shows in hex. The + kept output is bounded to its last 64,000 characters. +- `UpdateDict` takes four optional fields for a source that says more of an update than a + package name (NetOrk/netork#2892): `title`, the vendor's `advisories` it ships (Windows + Update's KB articles), the `cves` it fixes on this host, and the vendor's own rating + (`vendor_severity`, Windows Update's `MsrcSeverity`). `UpdateHistoryPackageDict` takes an + optional `title`. Every reader that leaves them out still conforms. +- A host's security posture in `HardeningDict` (NetOrk/netork#2893), as optional keys a + driver fills where it reads them, so a Windows host's protection fits the same reading as + a Linux host's hardening: `secure_boot` (`SecureBootState`: `on`, `off`, `unsupported`), + `tpm` (`TpmDict`), `disk_encryption` (`DiskEncryptionDict` with an `EncryptedVolumeDict` + per volume and its `VolumeProtection`), `antimalware` (`AntimalwareDict`, its + `AntimalwareMode` telling whether another product protects the host), `firewall_profiles` + (`FirewallProfileDict`, on or off) and `vbs` (`VbsDict`, `VbsStatus`). Everything Linux + fills stays required and unchanged; `parse_hardening` fills none of the new keys. + ## [4.55.0] - 2026-12-01 ### Added diff --git a/README.md b/README.md index 8248567..6257efe 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,18 @@ on its own CPU; on Debian with its archive's firmware component added first; change in one call overrides the template method. A driver mixes in the fixes its device can take; none is on a role base. They replace `run_device_action`, which is deprecated. +**Repair runs are a fixed catalog** (`napalm_device_types.host_repairs`). A host's own +checks and repairs of its system are one method per run, so the method list is the guard: +`HostRepairMixin.verify_system_files()`, `repair_system_files()`, +`check_component_store()`, `repair_component_store()`, `update_antimalware_signatures()` +and `scan_antimalware(quick)`. Each takes `log` for every line of the tool's output as the +host prints it, is bounded in time by the driver (or tighter by the caller's `limit`) and +returns a `HostRepairResultDict` +(`success`, `output`, `exit_code`, `error`); `tool_outcome(lines, exit_code, tool=...)` +builds it, so every driver fails a run the same way (a non-zero exit code, with the tool's +last lines). A repair is a method of its own beside its check, and a driver defines only +the runs it can do: `offered_host_repairs(driver_cls)` lists them. None restarts the host. + **SNMP is the application's** (`docs/STRUCTURE.md`). `HealthMetricsMixin` is deprecated since 4.12 and goes in 5.0. A driver does not collect over SNMP; a driver whose device publishes its health values under OIDs of its own declares them as data: @@ -181,6 +193,15 @@ command line, `ID`/`ID_LIKE` from `/etc/os-release`, whether the host runs virtu (`systemd-detect-virt`, else the `hypervisor` CPU flag) and the CPU's `vendor_id`. Read as root first and, where root 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". +`HardeningDict` also carries a host's security posture in terms no OS owns, as optional keys +a driver fills where it reads them (NetOrk/netork#2893): `secure_boot` (`on`, `off`, or +`unsupported` on a BIOS boot), `tpm` (`TpmDict`), `disk_encryption` (`DiskEncryptionDict`: +the provider, whether it is installed, and each volume's protection, status and cipher), +`antimalware` (`AntimalwareDict`: enabled, real-time protection, the mode -- `passive` and +`edr_block` when another product protects the host -- and the signatures' date and age), +`firewall_profiles` (each profile on or off; the rules are the host firewall reading's) and +`vbs` (virtualization-based security and the services it runs). The Linux reading fills +none of them yet. They carry state, never a secret: no recovery password or key protector. `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 @@ -190,7 +211,11 @@ knows, and where it came from; its lock and expiry from `passwd -S` and `chage - 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=)`. +`_run_login_accounts_command(command, privileged=)`. Another platform fills the same reading +from its own sources and may add optional keys (NetOrk/netork#2895): an account's `sid` +(Windows; `uid` is then the RID), `administrator` and `remote_desktop`, and the reading's +`groups` -- the host's groups that grant one of `LOGIN_GRANTS`, with every member, a +directory's included. `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 @@ -204,7 +229,9 @@ connection. Which other sessions an application opened itself is the application 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". +`LoginSessionsUnavailable`, never "nobody logged in". Another platform may add +`records_since`, the oldest entry its record still holds (Windows' Security log rotates by +size): a login before it is unknown, not absent. `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 @@ -309,6 +336,17 @@ text, never left out. A driver supplies `_run_host_firewall_command(command, pri tools need root, so a host where neither could be read raises `HostFirewallUnavailable` rather than reading as one without rules. Whether the rules keep a service unreachable is the consumer's call. +A Windows host's firewall is not netfilter, and its reading is not squeezed into chains: +`get_host_firewall` of a Windows driver returns `sources` `["windows-firewall"]`, no chains, +and `windows` (`WindowsFirewallDict`) -- the three profiles with their default actions, every +enabled rule with its filters (a program and a service as well as ports and addresses), and +the profile each connected interface is in. An application that knows only chains finds +none there and proves nothing from it. + +`WindowsFeaturesMixin` (`get_windows_features`) is declared for a Windows driver: every +optional feature of the host's image with its state, under the names Windows gives them on a +client and a server alike (`SMB1Protocol`, `MSMQ-Server`). A name the reading does not list +is not spelled as Windows spells it, or not a feature of this host -- not "off". `VirtualIpsMixin` (`get_virtual_ips`) reads the addresses a host's HA configuration lets float between machines: vip-manager (5.x's `--config` YAML, 1.x's `-ip=${VIP_IP}` resolved @@ -366,6 +404,9 @@ driver supplies `_run_system_identity_command(command, privileged=)`. The same round trip reads the host's system firmware (BIOS or UEFI): `bios_vendor`, `bios_version` and `bios_date` (`YYYY-MM-DD`, from sysfs's `MM/DD/YYYY`). Only the vendors' text defaults read as empty there; a short version such as `1` is a version. +A host that reads the same tables through an interface of its own (Windows' CIM classes) +implements `get_system_identity` itself and hands the values to `clean_system_identity`, +which applies the same rules. `OpenSshServerMixin` (`harden_ssh_server`, `get_ssh_server_algorithms`) takes algorithms out of what an OpenSSH server offers -- the ones ssh-audit flags. It reads the lists sshd @@ -410,7 +451,35 @@ driver mixes it in and supplies `run_command`. **Update readers raise when they cannot read.** `get_available_updates` returns an empty list only when nothing is pending; netOrk keeps "pending since" per package, and an empty -list for "don't know" would reset it. +list for "don't know" would reset it. A source that names more than a package may say so +on each update, all optional: its `title`, the vendor's `advisories` it ships ("KB5070000"), +the `cves` it fixes on this host and the vendor's own rating (`vendor_severity`) -- what +Windows Update reports for every update it offers (NetOrk/netork#2892). + +A Windows host has no journal and no log files a process holds open: its logs are its event +channels. A driver for it implements `get_log_sources` itself and lists each channel as a +source of kind `"eventlog"` (`eventlog_source(channel, path, size, modified)`, one of +`LOG_SOURCE_KINDS`), named by `channel` -- the name a log reader takes (CrowdSec's +`event_channel`, Wazuh's `eventchannel`) -- with its `.evtx` file as `path`. `journald` is +False there and `forwarding` None. + +`HostEventsMixin` (`get_host_events(since=None)`) only declares: what a host's own log +recorded that says something is wrong with it, read from its event log or its journal by the +driver. A fixed set of kinds (`HOST_EVENT_KINDS`: an unexpected shutdown, a system crash with +its stop code, a fatal or a corrected hardware error, a disk or file system error, a program's +or a service's crash), never the log itself; each event with its time, what it is about in +words that do not depend on the host's language (`subject`), where it was recorded and the +host's message cut to `HOST_EVENT_MESSAGE_CHARS` (`host_event()` builds one). The reading +covers `HOST_EVENT_WINDOW_DAYS` days unless the caller names a start; `capped` names the kinds +read up to the driver's bound, `unread` those it could not read this time. Whether an event is +a problem is the application's to decide. + +`ServiceDict` says, beside whether a service runs, how its last run ended where the driver can +tell (all optional): `result` in systemd's `Result` words (`SERVICE_RESULT_SUCCESS`, +`SERVICE_RESULT_EXIT_CODE`, `signal` …; None where it has not run since the host started), +`exit_code`, `trigger_start` for a service a trigger starts and idleness stops, and the +`account` it runs as. A service that is enabled, not running and whose last run did not +succeed has failed; one stopped on purpose has not. `SystemdServicesMixin` (`get_services`, `manage_service`) is mixed in the same way, by the drivers whose host runs systemd. Listing the services, checking a unit name and @@ -682,6 +751,16 @@ DHCP server handed out. It is apart from `DhcpServerMixin`, since an access poin leases without being a DHCP server anybody manages; a driver mixes it in itself. A failed read raises; a device that serves none returns `[]`. +`HostStorageMixin` (NetOrk/netork#2896) carries a host's own storage without the storage +role: `get_disks`, `get_disk_pools`, `get_volumes` in `StorageDriver`'s shapes and +`get_disk_smart`, drive health per disk (`DiskSmartDict`: health, temperature, wear, +power-on hours, uncorrected errors; `None` where the drive does not say). A Windows or +Linux host mixes it in and stays a host; a storage appliance that reads drive health may +mix it in beside its role. A volume may carry `HostVolumeDict`'s file system and health. +Where a disk does not say -- a virtual disk, a RAID controller's logical disk -- its +temperature is `-1` and its health `"unknown"`, never a zero or a `"healthy"` nobody +measured, and `get_disk_smart` leaves it out. + ### Fingerprints `DeviceTypeDriver` carries what discovery matches a device against: `PORT_SPECS`, @@ -815,7 +894,8 @@ class LinuxDriver(OSDriver): ... def get_os_users(self): - # return List[UserDict] -- not NAPALM's get_users, whose shape differs + # return List[UserDict] -- not NAPALM's get_users, whose shape differs; + # a host that names accounts by a SID (Windows) adds "sid", with the RID as uid ... def get_processes(self): diff --git a/docs/STRUCTURE.md b/docs/STRUCTURE.md index 31cf0d4..d7b7504 100644 --- a/docs/STRUCTURE.md +++ b/docs/STRUCTURE.md @@ -36,7 +36,7 @@ application SNMP polling, ping sweeps, discovery scoring, guest | Kind | Rule | Modules | |---|---|---| | **Role** | Declares only, under `TYPE_CHECKING`. No runtime method. | `access_point`, `switch`, `firewall`, `hypervisor`, `os`, `storage`, `phone`, `media`, `residential_gateway`, `management_controller`, `backup_server` | -| **Capability** | Declares only. | `packages`, `services`, `updates`, `nat_vpn`, `mac_acl`, `config_lifecycle`, `interface_filter`, `host_reboot`, `dhcp_leases`, `wireless_writes`, `ap_config` | +| **Capability** | Declares only. | `packages`, `services`, `updates`, `nat_vpn`, `mac_acl`, `config_lifecycle`, `interface_filter`, `host_reboot`, `dhcp_leases`, `wireless_writes`, `ap_config`, `host_storage` | | **Template** | A concrete method that runs a fixed sequence of abstract steps. A driver implements the steps, or overrides the whole method when its device does it in one go. All values come from the caller. | the fix routines below | | **Contract types** | Interfaces and data shapes other packages implement or fill. | `CommandChannelMixin`, `CommandResult`, `ByteStream`; the declaration of `ContainerEngineMixin`; the reader mixins' public method declarations; the SNMP profile type; `models` | | **Reconciler** | Concrete and vendor-neutral, without I/O of its own. | `firewall_rules` and `dhcp` diff/apply, `_matching`, `_dhcp_order`, `lag` | diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index b6ff305..ad24871 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -51,6 +51,8 @@ instead of being restated on every role that happens to need it: * :class:`~napalm_device_types.host_status.HostStatusMixin` * :class:`~napalm_device_types.host_reboot.HostRebootMixin` * :class:`~napalm_device_types.host_shutdown.HostShutdownMixin` +* :class:`~napalm_device_types.host_storage.HostStorageMixin` +* :class:`~napalm_device_types.host_repairs.HostRepairMixin` * :class:`~napalm_device_types.interface_filter.InterfaceFilterMixin` * :class:`~napalm_device_types.kernel.KernelFactsMixin` * :class:`~napalm_device_types.listening.ListeningSocketsMixin` @@ -58,7 +60,9 @@ instead of being restated on every role that happens to need it: * :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_events.HostEventsMixin` * :class:`~napalm_device_types.host_firewall.HostFirewallMixin` +* :class:`~napalm_device_types.windows_features.WindowsFeaturesMixin` * :class:`~napalm_device_types.mac_acl.MacAclMixin` * :class:`~napalm_device_types.ap_config.ApConfigMixin` * :class:`~napalm_device_types.wireless_writes.WirelessWritesMixin` @@ -202,20 +206,49 @@ from napalm_device_types.fixes import ( ) from napalm_device_types.hardening import ( HARDENING_COMMAND, + AntimalwareDict, + DiskEncryptionDict, + EncryptedVolumeDict, + FirewallProfileDict, HardeningDict, HardeningMixin, + TpmDict, + VbsDict, cpu_vulnerability_state, parse_hardening, ) from napalm_device_types.health_metrics import HealthMetricsMixin +from napalm_device_types.host_events import ( + HOST_EVENT_KINDS, + HOST_EVENT_MESSAGE_CHARS, + HOST_EVENT_WINDOW_DAYS, + HostEventDict, + HostEventsDict, + HostEventsMixin, + host_event, +) from napalm_device_types.host_firewall import ( HostFirewallMixin, HostFirewallUnavailable, parse_host_firewall, ) +from napalm_device_types.host_firewall_models import ( + WINDOWS_FIREWALL_PROFILES, + WindowsFirewallConnectionDict, + WindowsFirewallDict, + WindowsFirewallProfileDict, + WindowsFirewallRuleDict, +) from napalm_device_types.host_reboot import HostRebootMixin +from napalm_device_types.host_repairs import ( + HostRepairMixin, + HostRepairResultDict, + offered_host_repairs, + tool_outcome, +) from napalm_device_types.host_shutdown import HostShutdownMixin from napalm_device_types.host_status import HOST_STATUS_COMMAND, HostStatusMixin, parse_host_status +from napalm_device_types.host_storage import DiskSmartDict, HostStorageMixin, HostVolumeDict from napalm_device_types.hypervisor import HypervisorDriver from napalm_device_types.interface_filter import InterfaceFilterMixin from napalm_device_types.kernel import ( @@ -257,19 +290,25 @@ from napalm_device_types.log_forwarding import ( parse_rsyslog, ) from napalm_device_types.log_sources import ( + EVENTLOG, + LOG_SOURCE_KINDS, LOG_SOURCES_COMMAND, LogSourceDict, LogSourcesDict, LogSourcesMixin, LogSourcesUnavailable, + eventlog_source, parse_log_forwarding, parse_log_sources, ) from napalm_device_types.login_accounts import ( LOGIN_ACCOUNTS_COMMAND, + LOGIN_GRANTS, LoginAccountDict, LoginAccountsDict, LoginAccountsMixin, + LoginGroupDict, + LoginGroupMemberDict, login_capable, parse_login_accounts, ) @@ -294,6 +333,8 @@ from napalm_device_types.management_controller import ManagementControllerDriver from napalm_device_types.media import MediaDriver from napalm_device_types.models import ( POWER_ACTIONS, + SERVICE_RESULT_EXIT_CODE, + SERVICE_RESULT_SUCCESS, ConfigSyncDict, DhcpHaDict, DhcpHaPeerDict, @@ -311,6 +352,7 @@ from napalm_device_types.models import ( OspfInterfaceDict, PowerAction, PowerStateDict, + ServiceDict, SnmpAgentSettingsDict, UpdateProgressDict, ) @@ -437,6 +479,7 @@ from napalm_device_types.switch import SwitchDriver from napalm_device_types.system_identity import ( SYSTEM_IDENTITY_COMMAND, SystemIdentityMixin, + clean_system_identity, is_placeholder_identity, parse_system_identity, ) @@ -468,6 +511,12 @@ from napalm_device_types.virtual_ips import ( ) from napalm_device_types.vm_migration import MigrationPreflightDict from napalm_device_types.vm_stop_request import VmStopRequestMixin +from napalm_device_types.windows_features import ( + WINDOWS_FEATURE_STATES, + WindowsFeatureDict, + WindowsFeaturesDict, + WindowsFeaturesMixin, +) from napalm_device_types.wireless_writes import AUTO_CHANNEL, WirelessWritesMixin from napalm_device_types.zabbix_agent import ( ZabbixAgentSettingsDict, @@ -612,14 +661,31 @@ __all__ = [ "HealthMetricsMixin", "HOST_STATUS_COMMAND", "HostStatusMixin", + "HOST_EVENT_KINDS", + "HOST_EVENT_MESSAGE_CHARS", + "HOST_EVENT_WINDOW_DAYS", + "HostEventDict", + "HostEventsDict", + "HostEventsMixin", + "host_event", "HostRebootMixin", "HostShutdownMixin", + "HostStorageMixin", + "HostVolumeDict", + "DiskSmartDict", + "HostRepairMixin", + "HostRepairResultDict", + "offered_host_repairs", + "tool_outcome", "HypervisorDriver", "InterfaceFilterMixin", "MacAclMixin", "ManagementControllerDriver", "ARP_AGE_UNKNOWN", "POWER_ACTIONS", + "SERVICE_RESULT_EXIT_CODE", + "SERVICE_RESULT_SUCCESS", + "ServiceDict", "PowerAction", "PowerStateDict", "HardwareInventoryDict", @@ -654,12 +720,21 @@ __all__ = [ "firmware_component", "microcode_package", "HardeningDict", + "AntimalwareDict", + "DiskEncryptionDict", + "EncryptedVolumeDict", + "FirewallProfileDict", + "TpmDict", + "VbsDict", "cpu_vulnerability_state", "parse_hardening", "LOGIN_ACCOUNTS_COMMAND", "LoginAccountDict", "LoginAccountsDict", "LoginAccountsMixin", + "LOGIN_GRANTS", + "LoginGroupDict", + "LoginGroupMemberDict", "login_capable", "parse_login_accounts", "LOGIN_SESSIONS_COMMAND", @@ -682,9 +757,21 @@ __all__ = [ "HostFirewallMixin", "HostFirewallUnavailable", "parse_host_firewall", + "WINDOWS_FIREWALL_PROFILES", + "WindowsFirewallConnectionDict", + "WindowsFirewallDict", + "WindowsFirewallProfileDict", + "WindowsFirewallRuleDict", + "WINDOWS_FEATURE_STATES", + "WindowsFeatureDict", + "WindowsFeaturesDict", + "WindowsFeaturesMixin", "ListeningSocketsMixin", "ListeningSocketsUnavailable", "LOG_SOURCES_COMMAND", + "EVENTLOG", + "LOG_SOURCE_KINDS", + "eventlog_source", "FileInputDict", "ForwardRuleDict", "LogForwardingDict", @@ -754,6 +841,7 @@ __all__ = [ "service_clusters_command", "SystemIdentityMixin", "SYSTEM_IDENTITY_COMMAND", + "clean_system_identity", "is_placeholder_identity", "parse_system_identity", "OpenSshServerMixin", diff --git a/napalm_device_types/hardening.py b/napalm_device_types/hardening.py index 4431252..b545d89 100644 --- a/napalm_device_types/hardening.py +++ b/napalm_device_types/hardening.py @@ -28,14 +28,22 @@ here once and a driver only carries the command across. **Not read is None, neve empty or off:** a section the command did not print -- a file missing, a tool not installed, root refused -- comes back ``None``, so a consumer never reads "not looked" as "clean". + +**The security posture, on any OS** (NetOrk/netork#2893). Six optional keys answer the +first questions about a host's protection in terms no OS owns: ``secure_boot``, ``tpm``, +``disk_encryption`` (per volume), ``antimalware``, ``firewall_profiles`` and ``vbs`` +(virtualization-based security). A driver that reads them fills them; one that does not +leaves them out, which reads the same as ``None``: not read. ``parse_hardening`` (Linux) +fills none of them yet. They carry state only, never a secret: no recovery password, no +key protector, no key. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict reads ``NotRequired`` off the +# evaluated annotations, and HardeningDict's posture keys are optional. import json import re from shlex import quote -from typing import TYPE_CHECKING, Literal, TypedDict +from typing import TYPE_CHECKING, Literal, NotRequired, TypedDict from napalm_device_types.terminal import strip_terminal_codes @@ -98,6 +106,86 @@ class AppArmorDict(TypedDict): profiles: dict[str, int] | None +#: Secure Boot: "on" or "off" on a UEFI host; "unsupported" where the firmware has none +#: (a BIOS boot), which is no finding. +SecureBootState = Literal["on", "off", "unsupported"] +#: Whether a volume's encryption protects it now: "off" too where it is encrypted but its +#: protection is suspended, or its key sits in the clear on the volume. +VolumeProtection = Literal["on", "off", "unknown"] +#: Who protects the host: "active" the product itself; "passive" and "sxs_passive" another +#: product does, and this one only scans on demand; "edr_block" another product does, and +#: this one's EDR blocks what it detects after the fact. +AntimalwareMode = Literal["active", "passive", "edr_block", "sxs_passive"] +#: Virtualization-based security: "configured" is switched on but not running (yet). +VbsStatus = Literal["off", "configured", "running"] + + +class TpmDict(TypedDict): + """The host's Trusted Platform Module. ``None`` in a field: could not be read.""" + + present: bool # False: the host has no TPM, or the firmware hides it + enabled: bool | None + activated: bool | None + owned: bool | None # taken into use by the OS + version: str | None # the specification's version: "2.0", "1.2" + manufacturer: str | None # the vendor's ID as the TPM gives it: "INTC", "AMD", "MSFT" + + +class EncryptedVolumeDict(TypedDict): + """One volume the host's disk encryption knows.""" + + volume: str # where it is mounted: "C:", "/", "/home" + system: bool # the volume the OS runs from + protection: VolumeProtection + #: "fully_encrypted", "fully_decrypted", "encrypting", "decrypting", + #: "encryption_paused", "decryption_paused"; None where the tool gives none. + status: str | None + method: str | None # the cipher, in snake case: "xts_aes_128", "aes_256", ... + + +class DiskEncryptionDict(TypedDict): + """The host's own disk encryption: BitLocker on Windows, LUKS on Linux.""" + + provider: str # "bitlocker", "luks" + #: False where the host does not have it (BitLocker is a feature a Windows Server + #: installs first): no volume can be encrypted with it, ``volumes`` is empty. + installed: bool + volumes: list[EncryptedVolumeDict] + + +class AntimalwareDict(TypedDict): + """The host's own antimalware product, as it reports itself. ``None``: not read.""" + + product: str # "Microsoft Defender Antivirus" + enabled: bool | None # its scanning engine is on + real_time: bool | None # it scans files as they are opened + mode: AntimalwareMode | None + signatures_updated: int | None # when its signatures were last updated, unix seconds + signature_age_days: int | None # their age in days, as the product counts it + signature_version: str | None + tamper_protected: bool | None # its settings are locked against local changes + + +class FirewallProfileDict(TypedDict): + """One profile of the host's own firewall: whether it filters at all. + + Its rules are not here: what they let through is the host firewall reading's. + """ + + name: str # lowercase: "domain", "private", "public" + enabled: bool | None + + +class VbsDict(TypedDict): + """Virtualization-based security: the hypervisor-isolated part of the OS.""" + + status: VbsStatus | None + #: The services it runs, in snake case: "credential_guard", "hvci" (memory + #: integrity), "system_guard", "smm_firmware_measurement", "kernel_shadow_stacks", + #: "kernel_shadow_stacks_audit", "hypervisor_paging_translation"; None where not read. + running: list[str] | None + + class HardeningDict(TypedDict): """What :meth:`HardeningMixin.get_hardening` read. ``None``: not read, never "off".""" @@ -117,6 +205,13 @@ class HardeningDict(TypedDict): #: ``hypervisor`` CPU flag tells it. virtualization: str | None cpu_vendor: str | None # the first vendor_id of /proc/cpuinfo: "GenuineIntel", ... + # The security posture (NetOrk/netork#2893); left out where the driver does not read it. + secure_boot: NotRequired[SecureBootState | None] + tpm: NotRequired[TpmDict | None] + disk_encryption: NotRequired[DiskEncryptionDict | None] + antimalware: NotRequired[AntimalwareDict | None] # None also where it reports nothing + firewall_profiles: NotRequired[list[FirewallProfileDict] | None] + vbs: NotRequired[VbsDict | None] def cpu_vulnerability_state(text: str) -> CpuVulnerabilityState: @@ -350,6 +445,10 @@ class HardeningMixin: own hardware; "vm" where only the ``hypervisor`` CPU flag tells it * cpu_vendor (str or None) - ``vendor_id`` of ``/proc/cpuinfo`` + A driver may add the security posture (``secure_boot``, ``tpm``, + ``disk_encryption``, ``antimalware``, ``firewall_profiles``, ``vbs``); this Linux + reading does not yet. + ``None`` means not read. Read as root first, for AppArmor's profiles; where root is refused, as the login user, without them. diff --git a/napalm_device_types/host_events.py b/napalm_device_types/host_events.py new file mode 100644 index 0000000..fd01a63 --- /dev/null +++ b/napalm_device_types/host_events.py @@ -0,0 +1,157 @@ +"""What a host's own log recorded that says something is wrong with it (NetOrk/netork#2897). + +A crash, a power loss, a hardware error the CPU or the memory corrected, a disk +that reports bad blocks, a program that keeps dying: the host writes each of them +down itself -- Windows in its event log, Linux in its journal -- and nothing on the +outside sees it. :meth:`HostEventsMixin.get_host_events` reads those, and only +those: a fixed set of kinds (:data:`HOST_EVENT_KINDS`), not the log. Each event says +its kind, when it happened, what it is about where the host names that in words +that do not depend on its language (a stop code, a disk, a program's path, a +service), and where it was recorded. Whether that is a problem, and from how many, +is the application's to decide. + +**Bounded.** The reading covers :data:`HOST_EVENT_WINDOW_DAYS` days unless the +caller names a start, and a driver reads at most a fixed number of events of each +query, newest first; a kind read up to that bound is in ``capped``, so a count of it +is "at least". A host's message is cut to :data:`HOST_EVENT_MESSAGE_CHARS`. + +**Not read is not nothing.** A kind the driver could not read -- its log missing, +the query refused -- is in ``unread``; a kind neither read nor unread is one the +driver does not read at all. Only a kind that was read and found nothing means +nothing happened. +""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import TYPE_CHECKING, TypedDict + +#: The host stopped without shutting down: power lost, a reset, or a crash. +UNEXPECTED_SHUTDOWN = "unexpected_shutdown" +#: The operating system stopped itself on an error it could not go on from: a +#: Windows bugcheck, a Linux kernel panic. ``subject`` is the stop code. +SYSTEM_CRASH = "system_crash" +#: The hardware reported an error it could not correct (Windows' WHEA, a machine check). +HARDWARE_ERROR_FATAL = "hardware_error_fatal" +#: The hardware reported an error and corrected it: harmless once, a failing part +#: when it repeats. +HARDWARE_ERROR_CORRECTED = "hardware_error_corrected" +#: A disk or a file system reported an error: a bad block, a retried I/O, a +#: corruption. ``subject`` is the disk or the volume. +DISK_ERROR = "disk_error" +#: A program crashed. ``subject`` is its path, or its name where the host gives no path. +APP_CRASH = "app_crash" +#: A service ended without being stopped. ``subject`` is the service as the host names it. +SERVICE_CRASH = "service_crash" + +#: Every kind of event the reading knows, in this order. +HOST_EVENT_KINDS = ( + UNEXPECTED_SHUTDOWN, + SYSTEM_CRASH, + HARDWARE_ERROR_FATAL, + HARDWARE_ERROR_CORRECTED, + DISK_ERROR, + APP_CRASH, + SERVICE_CRASH, +) + +#: How far back the reading goes when the caller names no start. +HOST_EVENT_WINDOW_DAYS = 7 +#: The characters of a host's message an event keeps. +HOST_EVENT_MESSAGE_CHARS = 300 + + +class HostEventDict(TypedDict): + """One event the host recorded.""" + + kind: str # one of HOST_EVENT_KINDS + time: str # ISO 8601 in UTC + #: What it is about, in words that do not depend on the host's language: the + #: stop code, the disk or volume, the program's path, the service; None where + #: the host does not say. + subject: str | None + #: Where the host recorded it: ``System: Microsoft-Windows-Kernel-Power 41``. + source: str + #: The host's own text, in its language, cut to HOST_EVENT_MESSAGE_CHARS; None + #: where it has none or the driver does not read it. + message: str | None + + +class HostEventsDict(TypedDict): + """What :meth:`HostEventsMixin.get_host_events` read.""" + + since: str # the start of the reading, ISO 8601 in UTC + events: list[HostEventDict] # newest first + #: Kinds read up to the driver's bound: there may be older ones in the window. + capped: list[str] + #: Kinds the driver reads and could not read this time. + unread: list[str] + + +def _text(value: str | None, limit: int | None = None) -> str | None: + text = (value or "").strip() + if limit is not None: + text = text[:limit].strip() + return text or None + + +def host_event( + kind: str, + at: float, + source: str, + subject: str | None, + message: str | None = None, +) -> HostEventDict: + """One event: *at* in unix seconds, *message* cut to :data:`HOST_EVENT_MESSAGE_CHARS`. + + :raises ValueError: for a kind :data:`HOST_EVENT_KINDS` does not name. + """ + if kind not in HOST_EVENT_KINDS: + raise ValueError(f"{kind!r} is not a host event kind") + return { + "kind": kind, + "time": datetime.fromtimestamp(at, UTC).isoformat(), + "subject": _text(subject), + "source": source, + "message": _text(message, HOST_EVENT_MESSAGE_CHARS), + } + + +class HostEventsMixin: + """Declares :meth:`get_host_events` for a driver that reads its host's own log. + + A contract, declared under ``if TYPE_CHECKING``: how the events are read is the + host's (Windows' event log, a journal), so a driver implements it, and + ``hasattr(driver, "get_host_events")`` stays truthful. + """ + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def get_host_events(self, since: float | None = None) -> HostEventsDict: + """ + Returns the events of :data:`HOST_EVENT_KINDS` the host recorded since + *since* (unix seconds), by default over the last + :data:`HOST_EVENT_WINDOW_DAYS` days. + + * since (str) - the start of the reading, ISO 8601 UTC + * events (list) - newest first, see :class:`HostEventDict` + * capped (list) - kinds read up to the driver's bound + * unread (list) - kinds the driver could not read this time + + Example:: + + { + "since": "2026-11-24T10:00:00+00:00", + "events": [ + {"kind": "system_crash", "time": "2026-11-30T03:12:09+00:00", + "subject": "0x0000009f", + "source": "System: Microsoft-Windows-WER-SystemErrorReporting 1001", + "message": "The computer has rebooted from a bugcheck. ..."}, + ], + "capped": [], + "unread": [], + } + + :raises ValueError: when the reading came back without a report. + """ + ... diff --git a/napalm_device_types/host_firewall_models.py b/napalm_device_types/host_firewall_models.py new file mode 100644 index 0000000..9fdf054 --- /dev/null +++ b/napalm_device_types/host_firewall_models.py @@ -0,0 +1,151 @@ +"""The shapes of a host's own firewall (``get_host_firewall``). + +A module of its own rather than in :mod:`napalm_device_types.models`, which re-exports +the netfilter ones: the reading grew a Windows shape beside them (NetOrk/netork#2894), +and ``models`` is at its recorded size. + +**Two shapes, one reading.** A Linux host's rules are netfilter chains; a Windows host's +are the Windows Firewall's (Windows Defender Firewall with Advanced Security): rules that +belong to profiles, a profile active per network connection, and a rule that matches the +program and the service that listen as well as ports and addresses. Squeezed into chains +that would lose the program and the profile, so the Windows reading is a shape of its own +(``windows``), carried by the same ``HostFirewallDict`` with no chains. An application +that knows only chains finds none there, and proves nothing from it. +""" + +# No ``from __future__ import annotations``: TypedDict reads ``NotRequired`` from the +# evaluated annotation, and a string one would make ``windows`` a required key. +from typing import Final, NotRequired + +from typing_extensions import TypedDict + +#: The Windows Firewall's profiles, in Windows' own order. +WINDOWS_FIREWALL_PROFILES: Final = ("domain", "private", "public") + + +class NetfilterMatchDict(TypedDict): + """One condition of a netfilter rule. + + ``field`` is one of ``iifname``, ``oifname``, ``saddr``, ``daddr``, + ``l4proto``, ``dport``, ``sport``, ``ct_state``, ``ct_orig_dport``, + ``nfproto`` -- or ``unknown``, whose single value is the condition's text. + The rule matches when the field's value is (``==``) or is not (``!=``) one + of ``values``: interface names (``eth*`` a wildcard), CIDRs, protocol names, + ports (``8000-8010`` a range), conntrack states in lower case. + """ + + field: str + op: str # "==" or "!=" + values: list[str] + + +class NetfilterRuleDict(TypedDict): + """One rule: every match must hold, then the verdict applies. + + ``verdict`` is ``accept``, ``drop``, ``reject``, ``return``, ``jump`` or + ``goto`` (to ``target``), ``continue`` (a rule that only counts, logs or + marks), or ``other`` -- NAT, a queue, a verdict map -- with ``target`` naming it. + """ + + matches: list[NetfilterMatchDict] + verdict: str + target: str | None + text: str # the rule as iptables-save printed it, or as one nft-style line + + +class NetfilterChainDict(TypedDict): + """A chain. A base chain has a ``hook``, ``priority`` and ``policy``; a chain + reached only by ``jump``/``goto`` has None for all three.""" + + family: str # "ip", "ip6", "inet", "bridge", "arp", "netdev" + table: str + name: str + type: str | None # "filter", "nat", "route" + hook: str | None # "prerouting", "input", "forward", "output", "postrouting", ... + priority: int | None + policy: str | None # "accept" or "drop" + rules: list[NetfilterRuleDict] + + +class WindowsFirewallProfileDict(TypedDict): + """One profile's settings, as the host applies them (group policy over local). + + ``None`` is "not read". ``block_all_inbound`` is "block all incoming connections, + including those in the list of allowed apps": allow rules do not count then. + ``local_rules`` is False where group policy has the host ignore its local rules. + """ + + name: str # one of WINDOWS_FIREWALL_PROFILES + enabled: bool | None + default_inbound: str | None # "allow" or "block" + default_outbound: str | None # "allow" or "block" + block_all_inbound: bool | None + local_rules: bool | None + + +class WindowsFirewallRuleDict(TypedDict): + """One enabled rule of the active policy, with its filters joined to it. + + A filter that is ``None`` matches anything. Addresses are CIDRs (a single address as + ``/32`` or ``/128``, a range as the CIDRs that cover it) or one of Windows' keywords in + lower case (``localsubnet``, ``intranet``, ``dns``, ...). Ports are numbers, ranges + (``8000-8010``) or keywords (``rpc``, ``rpcepmap``, ...). ``program`` is the path as + the rule names it, environment variables unexpanded + (``%SystemRoot%\\system32\\svchost.exe``), or ``System`` for the kernel's own + sockets (http.sys, SMB). + """ + + id: str # the rule's InstanceID (its Name) + name: str # DisplayName + group: str | None # DisplayGroup + direction: str # "inbound" or "outbound" + action: str # "allow" or "block" + profiles: list[str] | None # of WINDOWS_FIREWALL_PROFILES; None: every profile + protocol: str | None # "tcp", "udp", "icmpv4", "icmpv6", or a protocol number; None: any + local_ports: list[str] | None + remote_ports: list[str] | None + local_addresses: list[str] | None + remote_addresses: list[str] | None + program: str | None + service: str | None # a service's short name, or "*" for any service + package: str | None # an app container's package SID + interfaces: list[str] | None # interface aliases + interface_types: list[str] | None # "wired", "wireless", "remote_access" + #: The rule asks for IPsec authentication ("allow if secure"). + authenticated: bool + #: An authenticated allow rule that overrides block rules. + override_block: bool + #: Where the rule comes from: "local", "group_policy", "dynamic", "generated", + #: "hardcoded", "mdm", ..., in lower case. + source: str | None + + +class WindowsFirewallConnectionDict(TypedDict): + """Which profile applies on an interface: its network connection's category.""" + + interface: str # the interface alias, as the interfaces reading names it + profile: str # one of WINDOWS_FIREWALL_PROFILES + + +class WindowsFirewallDict(TypedDict): + """A Windows host's firewall: its three profiles, its enabled rules and the profile + each connected interface is in. ``connections`` is None when it was not read.""" + + profiles: list[WindowsFirewallProfileDict] + rules: list[WindowsFirewallRuleDict] + connections: list[WindowsFirewallConnectionDict] | None + + +class HostFirewallDict(TypedDict): + """What ``HostFirewallMixin.get_host_firewall`` read. + + ``sources`` names what was read: ``nftables``, ``iptables-nft`` (the tables + iptables manages, taken from ``iptables-save`` because nft shows their + extensions opaquely) and ``iptables-legacy`` (a ruleset of its own) -- or + ``windows-firewall``, whose reading is ``windows``. + """ + + sources: list[str] + chains: list[NetfilterChainDict] + #: A Windows host's firewall (``sources`` ``["windows-firewall"]``, no chains). + windows: NotRequired[WindowsFirewallDict] diff --git a/napalm_device_types/host_repairs.py b/napalm_device_types/host_repairs.py new file mode 100644 index 0000000..6eb332f --- /dev/null +++ b/napalm_device_types/host_repairs.py @@ -0,0 +1,194 @@ +"""Repair runs: a host's own checks and repairs of its system, one method per run. + +A fixed catalog, not a command line: each run is a method of its own, so the list of +methods is the guard -- an application can start these runs and nothing else. A driver +mixes :class:`HostRepairMixin` in where its host has the tools and defines the runs it +can do; the others stay declared only, so ``hasattr`` (or :func:`offered_host_repairs`) +tells an application which to offer. A run that changes the host is a method of its own +(``repair_system_files`` beside ``verify_system_files``), so offering a check never +offers the repair. + +The runs are long -- minutes, a component store's scan up to half an hour -- so each +takes ``log``, which receives every line of the tool's output as the host prints it, +and each is bounded in time: by the driver, or tighter by the caller's ``limit``. They +are runs an application starts, never part of a reading. None restarts the host: a +repair that wants a restart says so in its output, and restarting is the caller's. + +:func:`tool_outcome` is the shared part of every run: the tool's exit code decides, a +failure names the tool's last lines, and the output the result keeps is bounded. + +Declared under ``if TYPE_CHECKING``: a contract, not a placeholder (see the package +docstring). Not mixed into any role base. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, NotRequired + +from typing_extensions import TypedDict + +#: Receives one line of a tool's output, without its line break. +LineLog = Callable[[str], None] + +#: The runs of the catalog, in the order an application lists them. +HOST_REPAIR_METHODS: tuple[str, ...] = ( + "verify_system_files", + "repair_system_files", + "check_component_store", + "repair_component_store", + "update_antimalware_signatures", + "scan_antimalware", +) + +#: How many of a failed tool's last lines its ``error`` names. +FAILURE_TAIL_LINES = 10 +#: The most characters of output a result keeps: the end, where tools say how they ended. +OUTPUT_LIMIT = 64_000 + +# Exit codes at or above this are HRESULTs (0x8007…, 0x800F…) and read better in hex. +_HRESULT_FLOOR = 0x8000_0000 +_UINT32 = 0xFFFF_FFFF + + +class HostRepairResultDict(TypedDict): + """How a repair run ended (every method of :class:`HostRepairMixin`).""" + + success: bool # the tool ended with exit code 0 + output: str # the tool's output as text, its end kept within OUTPUT_LIMIT + exit_code: int | None # unsigned; None where the tool gave none (cut off, not started) + error: NotRequired[str] # on failure: the exit code and the tool's last lines + + +def _exit_code_text(code: int) -> str: + return f"0x{code:X}" if code >= _HRESULT_FLOOR else str(code) + + +def _bounded(text: str) -> str: + return text if len(text) <= OUTPUT_LIMIT else text[-OUTPUT_LIMIT:] + + +def tool_outcome(lines: Sequence[str], exit_code: int | None, *, tool: str) -> HostRepairResultDict: + """The result of a run whose tool printed *lines* and ended with *exit_code*. + + Exit code 0 succeeds. Any other, or none, fails, and ``error`` names it with the + tool's last non-blank lines. A negative code is a signed 32-bit one (.NET's + ``Process.ExitCode``) and is read as unsigned, so an HRESULT keeps its usual form. + """ + code = None if exit_code is None else exit_code & _UINT32 + result: HostRepairResultDict = { + "success": code == 0, + "output": _bounded("\n".join(lines)), + "exit_code": code, + } + if code == 0: + return result + said = [line for line in lines if line.strip()][-FAILURE_TAIL_LINES:] + head = ( + f"{tool} ended without an exit code" + if code is None + else f"{tool} ended with exit code {_exit_code_text(code)}" + ) + result["error"] = f"{head}: " + "\n".join(said) if said else head + return result + + +def offered_host_repairs(driver_cls: type) -> list[str]: + """The runs of the catalog *driver_cls* defines, in the catalog's order.""" + return [name for name in HOST_REPAIR_METHODS if callable(getattr(driver_cls, name, None))] + + +class HostRepairMixin: + """A host's checks and repairs of its own system files, its component store and its + antimalware, as fixed runs. See the module docstring.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def verify_system_files( + self, *, log: LineLog | None = None, limit: float | None = None + ) -> HostRepairResultDict: + """ + Checks the protected system files against the host's own record of them, + and changes nothing (Windows: ``sfc /verifyonly``). + + :param log: Receives each line of the tool's output as the host prints it. + :param limit: The longest the run may take, in seconds; None for the + driver's own bound. A run still going then is stopped and fails. + :returns: How it ended (:class:`HostRepairResultDict`). A check that finds + damaged files can still end with exit code 0: the verdict is in the + output, in the host's language. + """ + ... + + def repair_system_files( + self, *, log: LineLog | None = None, limit: float | None = None + ) -> HostRepairResultDict: + """ + Checks the protected system files and replaces damaged ones from the host's + own store (Windows: ``sfc /scannow``). Changes the host; does not restart it. + + :param log: As :meth:`verify_system_files`; *limit* too. + """ + ... + + def check_component_store( + self, *, log: LineLog | None = None, limit: float | None = None + ) -> HostRepairResultDict: + """ + Scans the store the system files are repaired from for damage, and changes + nothing (Windows: ``DISM /Online /Cleanup-Image /ScanHealth``). Takes up to + half an hour. + + :param log: As :meth:`verify_system_files`; *limit* too. + """ + ... + + def repair_component_store( + self, *, log: LineLog | None = None, limit: float | None = None + ) -> HostRepairResultDict: + """ + Repairs that store from a repair source (Windows: ``DISM /Online + /Cleanup-Image /RestoreHealth``, from Windows Update unless a policy names + another source). Changes the host; does not restart it. + + :param log: As :meth:`verify_system_files`; *limit* too. + """ + ... + + def update_antimalware_signatures( + self, *, log: LineLog | None = None, limit: float | None = None + ) -> HostRepairResultDict: + """ + Updates the host's antimalware signatures from the sources the host is set + to use (Windows: ``Update-MpSignature``). A host without the antimalware + fails with a result that says so, not with an exception. + + :param log: As :meth:`verify_system_files`, *limit* too; *log* also + receives the signature version before and after. + """ + ... + + def scan_antimalware( + self, quick: bool = True, *, log: LineLog | None = None, limit: float | None = None + ) -> HostRepairResultDict: + """ + Scans the host with its antimalware (Windows: ``Start-MpScan``): the places + malware usually sits when *quick*, every file otherwise. What the scan finds + is handled as the antimalware is set to handle it; the output names it. + + :param quick: A quick scan (minutes) rather than a full one (hours). + :param log: As :meth:`verify_system_files`; *limit* too. + """ + ... + + +__all__ = [ + "FAILURE_TAIL_LINES", + "HOST_REPAIR_METHODS", + "OUTPUT_LIMIT", + "HostRepairMixin", + "HostRepairResultDict", + "LineLog", + "offered_host_repairs", + "tool_outcome", +] diff --git a/napalm_device_types/host_storage.py b/napalm_device_types/host_storage.py new file mode 100644 index 0000000..80e1f4b --- /dev/null +++ b/napalm_device_types/host_storage.py @@ -0,0 +1,126 @@ +"""A host's own disks, volumes and drive health (NetOrk/netork#2896, #2705). + +:class:`~napalm_device_types.storage.StorageDriver` is a *role*: a driver that inherits +it is shown as a storage device. A Windows server or a Linux host has disks, pools and +volumes too, and is still a host. :class:`HostStorageMixin` carries the same getters -- +and the drive health reading, :meth:`~HostStorageMixin.get_disk_smart` -- with no role, +so an OS driver reports them and stays what it is. A storage appliance that also reads +drive health may mix it in beside its role. + +Declared under ``if TYPE_CHECKING``, like every capability: a driver has a getter at +runtime only when it reads that part, so ``hasattr`` tells a caller which parts to ask +for. A getter that cannot look raises; one that looked and found none returns empty. + +The shapes are the storage role's (``PhysicalDiskDict``, ``DiskPoolDict``, +``LogicalVolumeDict``) with two additions a host fills where it can: +:class:`HostVolumeDict`, a volume with its file system and health, and +:class:`DiskSmartDict`, a disk's drive health. +""" + +from typing import TYPE_CHECKING, NotRequired, TypedDict + +from napalm_device_types.models import ( + DiskPoolDict, + LogicalVolumeDict, + PhysicalDiskDict, +) + + +class HostVolumeDict(LogicalVolumeDict): + """A volume as a host reports it: a ``LogicalVolumeDict`` and, where known, the + file system on it and the volume's own health.""" + + file_system: NotRequired[str] # "NTFS", "ReFS", "ext4", "xfs"; empty when raw + health: NotRequired[str] # "healthy", "warning", "failed", "unknown" + + +class DiskSmartDict(TypedDict): + """One disk's drive health: its self-reported counters, ``None`` where the drive or + its controller does not report one. + + The keys up to ``power_on_hours`` are what drivers filled before the contract named + them (Proxmox reads them through its API from smartctl); the rest are optional. + """ + + model: str + serial: str + type: str # "hdd", "ssd", "nvme", "unknown" + size: int # bytes + #: The drive's verdict: "ok" (smartctl's "passed" where a driver passes it through), + #: "warning", "failed", or "unknown". + health: str + wearout: int | None # life left, percent (100 = new) + temperature: int | None # Celsius + percentage_used: int | None # wear, percent of the rated endurance used + available_spare: int | None # percent + reallocated_sectors: int | None + power_on_hours: int | None + temperature_max: NotRequired[int | None] # Celsius, the highest the drive recorded + read_errors_uncorrected: NotRequired[int | None] + write_errors_uncorrected: NotRequired[int | None] + + +class HostStorageMixin: + """A host's disks, pools, volumes and drive health, without the storage role.""" + + if TYPE_CHECKING: + + def get_disks(self) -> list[PhysicalDiskDict]: + """ + The host's physical disks, as ``StorageDriver.get_disks`` documents them. + + ``temperature`` is ``-1`` and ``health`` ``"unknown"`` where the disk does not + say -- a virtual disk, or a logical disk of a hardware RAID controller -- never + a zero or a ``"healthy"`` nobody measured. ``type`` is ``"unknown"`` where + the host cannot tell the medium. A virtual disk the host builds from other + disks (a Storage Spaces or md volume) is no physical disk; its members are. + """ + ... + + def get_disk_pools(self) -> dict[str, DiskPoolDict]: + """ + The pools the host builds from its disks, as ``StorageDriver.get_disk_pools`` + documents them; ``{}`` when it has none. Besides the role's types, ``type`` + may be ``"storage-spaces"`` and ``level`` ``"parity"``. + """ + ... + + def get_volumes(self) -> dict[str, LogicalVolumeDict]: + """ + The host's mounted volumes, as ``StorageDriver.get_volumes`` documents them, + keyed by where they are mounted. Each may carry :class:`HostVolumeDict`'s + optional keys. A field the host has no notion of reads empty: ``pool`` ``""`` + where the volume belongs to none, ``compression`` ``""`` where unknown. + """ + ... + + def get_disk_smart(self) -> dict[str, DiskSmartDict]: + """ + Drive health per disk, keyed as ``get_disks``' ``slot``. + + Only disks that report something are listed: a virtual disk with no + counters is left out rather than listed with nothing in it, so a host + whose disks report nothing returns ``{}``. + + Example:: + + { + "PhysicalDisk0": { + "model": "Samsung SSD 980 PRO 1TB", + "serial": "S5GXNX0T123456", + "type": "nvme", + "size": 1000204886016, + "health": "ok", + "wearout": None, + "temperature": 41, + "percentage_used": 3, + "available_spare": None, + "reallocated_sectors": None, + "power_on_hours": 5120, + "temperature_max": 68, + "read_errors_uncorrected": 0, + "write_errors_uncorrected": 0, + }, + } + """ + ... diff --git a/napalm_device_types/log_sources.py b/napalm_device_types/log_sources.py index cdb6a26..53d0225 100644 --- a/napalm_device_types/log_sources.py +++ b/napalm_device_types/log_sources.py @@ -45,28 +45,55 @@ from __future__ import annotations import re from datetime import UTC, datetime from shlex import quote -from typing import TYPE_CHECKING, TypedDict +from typing import TYPE_CHECKING, NotRequired, TypedDict from napalm_device_types.listening import _cgroup_paths, _container, _sections, _unit from napalm_device_types.log_forwarding import LogForwardingDict, log_forwarding, parse_rsyslog from napalm_device_types.terminal import strip_terminal_codes +#: A Windows event channel (NetOrk/netork#2897). +EVENTLOG = "eventlog" +#: Every kind of log source, in this order. +LOG_SOURCE_KINDS = ("journald", "file", "container", EVENTLOG) + class LogSourceDict(TypedDict): - """A log the host writes: a unit's journal, a file a process holds open, or a - container's stream as the engine keeps it. + """A log the host writes: a unit's journal, a file a process holds open, a + container's stream as the engine keeps it, or a Windows event channel. ``path`` is as its writer sees it: a file a container writes is named inside that container. Whether anything reads the log is the consumer's question. """ - kind: str # "journald", "file" or "container" - path: str | None # the file; None for a journal + kind: str # one of LOG_SOURCE_KINDS + path: str | None # the file (an event channel's .evtx); None for a journal unit: str | None # the journal's unit, or the file writer's service; without ".service" container_id: str | None # the full container ID: the writer's, or the stream's process: str | None # the first process writing the file; None when only readers hold it size: int | None # bytes; None for a journal, or when the file could not be read modified: str | None # the last write, ISO 8601 UTC; None as for size + #: The event channel an "eventlog" source is read by -- ``System``, + #: ``Microsoft-Windows-Sysmon/Operational`` --, what a log reader names it by; + #: absent for the other kinds. + channel: NotRequired[str] + + +def eventlog_source( + channel: str, path: str | None, size: int | None, modified: float | None +) -> LogSourceDict: + """A Windows event channel as a source: *path* its ``.evtx`` file, *size* in bytes, + *modified* its last write in unix seconds (NetOrk/netork#2897). No process holds it + for writing that a reading could name: the Event Log service writes them all.""" + return { + "kind": EVENTLOG, + "path": path, + "unit": None, + "container_id": None, + "process": None, + "size": size, + "modified": None if modified is None else datetime.fromtimestamp(modified, UTC).isoformat(), + "channel": channel, + } class LogSourcesDict(TypedDict): @@ -75,7 +102,9 @@ class LogSourcesDict(TypedDict): ``attributed`` is False when the reading ran without root: only the login user's own processes show their files then, so a missing log means "not told", not "not there". ``journald`` is False on a host without systemd's - journal, where no unit has one. + journal, where no unit has one -- a Windows host among them, whose logs are + its event channels (``"eventlog"``). ``forwarding`` is None where the reading + cannot tell where the logs go. """ attributed: bool diff --git a/napalm_device_types/login_accounts.py b/napalm_device_types/login_accounts.py index 4b76c35..97b2932 100644 --- a/napalm_device_types/login_accounts.py +++ b/napalm_device_types/login_accounts.py @@ -21,6 +21,13 @@ host that is every account with a shell, not only the ones an application create 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". + +**Another platform** (NetOrk/netork#2895) fills the same reading from its own sources and +may add the optional keys: an account's ``sid`` (Windows' security identifier, whose last +part, the RID, is then its ``uid``), whether it can administer the host (``administrator``) +and log in at a remote desktop (``remote_desktop``), and the reading's ``groups`` -- the +host's groups that grant one of :data:`LOGIN_GRANTS`, with every member, a directory's +included. The Linux reading sets none of them. """ from __future__ import annotations @@ -102,10 +109,35 @@ _MUST_CHANGE = "password must be changed" _Sections = dict[tuple[str, str | None], list[str]] -class LoginAccountDict(TypedDict): +#: What a group in :class:`LoginGroupDict` grants its members: administering the host, and +#: logging in at a remote desktop. +LOGIN_GRANTS = ("administrator", "remote_desktop") + + +class _PlatformLoginAccountDict(TypedDict, total=False): + """The keys of :class:`LoginAccountDict` only another platform than Linux sets. + + A base of their own, as ``total=False``: ``NotRequired`` under postponed annotations + is not seen by the class at runtime. + """ + + #: The account's security identifier (Windows); its ``uid`` is then the RID, the + #: SID's last part. + sid: str + #: Can administer the host: a member of its Administrators (``S-1-5-32-544``) on + #: Windows. None: not read. + administrator: bool | None + #: May log in at a remote desktop: the host takes such logins, and the account holds + #: the right to (Windows: ``SeRemoteInteractiveLogonRight``, not denied). None: not + #: read. + remote_desktop: bool | None + + +class LoginAccountDict(_PlatformLoginAccountDict): """One login-capable account. ``None`` in a field: could not be read.""" name: str + #: The POSIX UID; on Windows the RID (the last part of ``sid``). uid: int home: str shell: str @@ -114,7 +146,7 @@ class LoginAccountDict(TypedDict): 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 + last_login_source: str | None # one of LOGIN_SOURCES; "sam" on Windows 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" @@ -127,13 +159,47 @@ class LoginAccountDict(TypedDict): failed_logins_capped: bool -class LoginAccountsDict(TypedDict): +class LoginGroupMemberDict(TypedDict): + """One member of a :class:`LoginGroupDict`, as the host names it.""" + + #: ``DOMAIN\\name``, the host's own name for its own accounts; the SID where the + #: host can no longer resolve it. + name: str + sid: str | None + #: An account or group of the host itself; False: a directory's (a domain, Entra + #: ID). None: not known. + local: bool | None + #: A group, whose own members hold what it grants too. None: not known. + group: bool | None + + +class LoginGroupDict(TypedDict): + """A group of the host that grants its members one of :data:`LOGIN_GRANTS`.""" + + #: As the host names it, in its language ("Administratoren"). + name: str + sid: str | None + #: Of :data:`LOGIN_GRANTS`. + grants: list[str] + members: list[LoginGroupMemberDict] + + +class _PlatformLoginAccountsDict(TypedDict, total=False): + """The keys of :class:`LoginAccountsDict` only another platform than Linux sets.""" + + #: The groups that grant administering the host or a remote desktop login, with every + #: member, a directory's too: who holds it beside the host's own accounts. + groups: list[LoginGroupDict] + + +class LoginAccountsDict(_PlatformLoginAccountsDict): """What :meth:`LoginAccountsMixin.get_login_accounts` read.""" accounts: list[LoginAccountDict] - #: The sources of the last logins the host has, of LOGIN_SOURCES; empty: none. + #: The sources of the last logins the host has, of LOGIN_SOURCES (Windows: "sam"); + #: empty: none. login_sources: list[str] - #: "lastb" or "faillock"; None: neither could be read. + #: "lastb" or "faillock" (Windows: "sam"); None: neither could be read. failed_logins_source: str | None #: Read as root: the lock, the expiry and the failures are known. privileged: bool diff --git a/napalm_device_types/login_sessions.py b/napalm_device_types/login_sessions.py index 6e28733..468a824 100644 --- a/napalm_device_types/login_sessions.py +++ b/napalm_device_types/login_sessions.py @@ -95,8 +95,9 @@ _Sections = dict[tuple[str, str | None], list[str]] class LoginSessionDict(TypedDict): """One interactive login the host recorded.""" + #: The account; on Windows ``DOMAIN\\name`` for a directory's account. user: str - tty: str # "pts/0", "tty1", "ttyS0" + tty: str # "pts/0", "tty1", "ttyS0"; on Windows "console" or "rdp" #: 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. @@ -107,11 +108,24 @@ class LoginSessionDict(TypedDict): ended: str | None -class LoginSessionsDict(TypedDict): +class _PlatformLoginSessionsDict(TypedDict, total=False): + """The key of :class:`LoginSessionsDict` only another platform than Linux sets. + + A base of its own, as ``total=False``: ``NotRequired`` under postponed annotations is + not seen by the class at runtime. + """ + + #: The oldest entry the record the sessions came from still holds, ISO 8601 in UTC + #: (Windows' Security log, which rotates by size). Later than the window's start, a + #: login before it is unknown, not absent. None: the record is empty. + records_since: str | None + + +class LoginSessionsDict(_PlatformLoginSessionsDict): """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``). + #: The address the reading's own SSH session comes from (on Windows: its WinRM + #: session); 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] diff --git a/napalm_device_types/models.py b/napalm_device_types/models.py index 60f6744..d4df73c 100644 --- a/napalm_device_types/models.py +++ b/napalm_device_types/models.py @@ -9,7 +9,9 @@ from typing import Literal, NotRequired, get_args from typing_extensions import TypedDict # The SNMP health profile shapes live in snmp_health_profile.py, those of the access -# point getters in access_point_models.py; re-exported here, where they were. +# point getters in access_point_models.py, an OS's accounts and processes in +# os_models.py, the host firewall's in host_firewall_models.py; re-exported here, +# where they were. from napalm_device_types.access_point_models import ChannelScanEntryDict as ChannelScanEntryDict from napalm_device_types.access_point_models import ( FastTransitionConfigDict as FastTransitionConfigDict, @@ -21,7 +23,13 @@ from napalm_device_types.access_point_models import SSIDBridgeDict as SSIDBridge from napalm_device_types.access_point_models import SSIDDict as SSIDDict from napalm_device_types.access_point_models import WirelessClientDict as WirelessClientDict from napalm_device_types.access_point_models import WirelessConfigDict as WirelessConfigDict +from napalm_device_types.host_firewall_models import HostFirewallDict as HostFirewallDict +from napalm_device_types.host_firewall_models import NetfilterChainDict as NetfilterChainDict +from napalm_device_types.host_firewall_models import NetfilterMatchDict as NetfilterMatchDict +from napalm_device_types.host_firewall_models import NetfilterRuleDict as NetfilterRuleDict from napalm_device_types.kernel_models import KernelFactsDict as KernelFactsDict +from napalm_device_types.os_models import ProcessDict as ProcessDict +from napalm_device_types.os_models import UserDict as UserDict from napalm_device_types.snmp_health_profile import SnmpHealthProfile as SnmpHealthProfile from napalm_device_types.snmp_health_profile import SnmpInterfacesSpec as SnmpInterfacesSpec from napalm_device_types.snmp_health_profile import SnmpMemorySpec as SnmpMemorySpec @@ -68,20 +76,44 @@ class PackageDict(TypedDict): source: str +#: A service's last run ended as it should, or it has not ended (systemd's ``Result``). +SERVICE_RESULT_SUCCESS = "success" +#: A service's last run ended with an exit code that is not success. +SERVICE_RESULT_EXIT_CODE = "exit-code" + + class ServiceDict(TypedDict): - """A system service managed by the device's init system (e.g. procd on OpenWrt).""" + """A system service managed by the device's init system (e.g. procd on OpenWrt). + + The optional fields tell a service that died from one stopped on purpose + (NetOrk/netork#2897, #2703); a driver that cannot tell leaves them out. + """ name: str running: bool enabled: bool pid: int # 0 if not running + #: How its last run ended, in systemd's ``Result`` words: SERVICE_RESULT_SUCCESS, + #: SERVICE_RESULT_EXIT_CODE, ``signal``, ``core-dump``, ``timeout`` …; None where + #: it has not run since the host started. + result: NotRequired[str | None] + #: The code its last run ended with, where that was not success; else None. + exit_code: NotRequired[int | None] + #: Started by a trigger (a device, a network change, a request) and stopped when + #: idle, so that it is stopped while enabled says nothing. + trigger_start: NotRequired[bool] + #: The account it runs as: ``LocalSystem``, ``NT AUTHORITY\NetworkService``, + #: ``CORP\svc-backup``, ``www-data``; None where the driver does not say. + account: NotRequired[str | None] class UpdateDict(TypedDict): """A software package that has a newer version available in the package repository. ``origin`` and ``security`` are optional: a reader that cannot tell leaves - them out, and netOrk treats a missing ``security`` as unknown. + them out, and netOrk treats a missing ``security`` as unknown. So are + ``title``, ``advisories``, ``cves`` and ``vendor_severity``, which only a source + that names them fills. """ name: str @@ -91,6 +123,18 @@ class UpdateDict(TypedDict): origin: NotRequired[str | None] #: True for a security update, False for a known other one, None when unknown. security: NotRequired[bool | None] + #: What the source calls the update, where its name is no package: Windows Update's + #: title, "2026-11 Cumulative Update for ... (KB5070000)" (NetOrk/netork#2892). + title: NotRequired[str | None] + #: The vendor's advisories the update ships, e.g. Windows Update's ``KBArticleIDs`` + #: as "KB5070000"; empty or left out when the source names none. + advisories: NotRequired[list[str]] + #: The CVEs the source says the update fixes on this host (Windows Update's + #: ``CveIDs``): the host's own word that each applies until the update is installed. + cves: NotRequired[list[str]] + #: The vendor's rating, in the vendor's word: Windows Update's ``MsrcSeverity`` + #: ("Critical", "Important", "Moderate", "Low"); None when it gives none. + vendor_severity: NotRequired[str | None] class InterruptedPackageDict(TypedDict): @@ -305,62 +349,6 @@ class ListeningSocketsDict(TypedDict): sockets: list[ListeningSocketDict] -class NetfilterMatchDict(TypedDict): - """One condition of a netfilter rule. - - ``field`` is one of ``iifname``, ``oifname``, ``saddr``, ``daddr``, - ``l4proto``, ``dport``, ``sport``, ``ct_state``, ``ct_orig_dport``, - ``nfproto`` -- or ``unknown``, whose single value is the condition's text. - The rule matches when the field's value is (``==``) or is not (``!=``) one - of ``values``: interface names (``eth*`` a wildcard), CIDRs, protocol names, - ports (``8000-8010`` a range), conntrack states in lower case. - """ - - field: str - op: str # "==" or "!=" - values: list[str] - - -class NetfilterRuleDict(TypedDict): - """One rule: every match must hold, then the verdict applies. - - ``verdict`` is ``accept``, ``drop``, ``reject``, ``return``, ``jump`` or - ``goto`` (to ``target``), ``continue`` (a rule that only counts, logs or - marks), or ``other`` -- NAT, a queue, a verdict map -- with ``target`` naming it. - """ - - matches: list[NetfilterMatchDict] - verdict: str - target: str | None - text: str # the rule as iptables-save printed it, or as one nft-style line - - -class NetfilterChainDict(TypedDict): - """A chain. A base chain has a ``hook``, ``priority`` and ``policy``; a chain - reached only by ``jump``/``goto`` has None for all three.""" - - family: str # "ip", "ip6", "inet", "bridge", "arp", "netdev" - table: str - name: str - type: str | None # "filter", "nat", "route" - hook: str | None # "prerouting", "input", "forward", "output", "postrouting", ... - priority: int | None - policy: str | None # "accept" or "drop" - rules: list[NetfilterRuleDict] - - -class HostFirewallDict(TypedDict): - """What ``HostFirewallMixin.get_host_firewall`` read. - - ``sources`` names what was read: ``nftables``, ``iptables-nft`` (the tables - iptables manages, taken from ``iptables-save`` because nft shows their - extensions opaquely) and ``iptables-legacy`` (a ruleset of its own). - """ - - sources: list[str] - chains: list[NetfilterChainDict] - - class VirtualIpDict(TypedDict): """An address the host's HA configuration lets float between machines. @@ -911,33 +899,6 @@ class ReplicationJobDict(TypedDict): # --------------------------------------------------------------------------- -class UserDict(TypedDict): - """A local OS user account.""" - - username: str - uid: int - gid: int - home: str - shell: str - groups: list[str] # all supplementary group names - - -class ProcessDict(TypedDict): - """A running OS process.""" - - pid: int - ppid: int - user: str - cpu: float # CPU utilisation 0.0–100.0 - memory: float # RSS percentage of total RAM 0.0–100.0 - vsz: int # virtual memory size in KiB - rss: int # resident set size in KiB - tty: str # controlling terminal; empty string if none - state: str # "R" running, "S" sleeping, "D" uninterruptible, "Z" zombie, etc. - started: str # start time string as reported by ``ps`` (e.g. "12:34" or "May28") - command: str # full command line - - class ApplyUpdatesResultDict(TypedDict): """Result of an ``apply_updates()`` call.""" diff --git a/napalm_device_types/os_models.py b/napalm_device_types/os_models.py new file mode 100644 index 0000000..14ba2f0 --- /dev/null +++ b/napalm_device_types/os_models.py @@ -0,0 +1,41 @@ +"""What an OS driver reports about the host's accounts and processes (``OSDriver``). + +``get_os_users`` gives :class:`UserDict`, ``get_processes`` :class:`ProcessDict`. Both +lived in :mod:`napalm_device_types.models` and are re-exported there. +""" + +from typing import NotRequired + +from typing_extensions import TypedDict + + +class UserDict(TypedDict): + """A local OS user account.""" + + username: str + #: POSIX's uid; on Windows the relative identifier, the last part of the SID + #: (500 for the built-in Administrator, 1000 and up for accounts created). + uid: int + gid: int + home: str + shell: str + groups: list[str] # all supplementary group names + #: The account's security identifier, where the host names accounts by one + #: (Windows: "S-1-5-21-...-1001"); left out on a POSIX host. + sid: NotRequired[str] + + +class ProcessDict(TypedDict): + """A running OS process.""" + + pid: int + ppid: int + user: str + cpu: float # CPU utilisation 0.0–100.0 + memory: float # RSS percentage of total RAM 0.0–100.0 + vsz: int # virtual memory size in KiB + rss: int # resident set size in KiB + tty: str # controlling terminal; empty string if none + state: str # "R" running, "S" sleeping, "D" uninterruptible, "Z" zombie, etc. + started: str # start time string as reported by ``ps`` (e.g. "12:34" or "May28") + command: str # full command line diff --git a/napalm_device_types/services.py b/napalm_device_types/services.py index 5e43ec2..912efa6 100644 --- a/napalm_device_types/services.py +++ b/napalm_device_types/services.py @@ -31,6 +31,14 @@ class ServiceControlMixin: * enabled (bool) - ``True`` if the service starts automatically at boot * pid (int) - process ID of the main service process; 0 if not running + Optional, where the driver can tell (NetOrk/netork#2897): + + * result (str) - how its last run ended, in systemd's ``Result`` words + (``success``, ``exit-code``, ``signal`` ...); None if it has not run since boot + * exit_code (int) - the code its last run ended with where that was not success + * trigger_start (bool) - a trigger starts it and idleness stops it + * account (str) - the account it runs as + Example:: [ diff --git a/napalm_device_types/system_identity.py b/napalm_device_types/system_identity.py index a32a89c..2ef44a1 100644 --- a/napalm_device_types/system_identity.py +++ b/napalm_device_types/system_identity.py @@ -19,6 +19,10 @@ it they come back empty, which is "not known", not a mismatch. reads the identity reads it too. It is a fact about the host, not part of its identity: its placeholders are the vendors' text defaults, never a short value (a version of ``1`` is a version), and sysfs's ``MM/DD/YYYY`` release date is given as ISO 8601. + +**Other hosts** read the same SMBIOS tables through an interface of their own -- +Windows through its CIM classes (NetOrk/netork#2888) -- and hand the values to +:func:`clean_system_identity`, which applies the same placeholder rules. """ from __future__ import annotations @@ -124,6 +128,36 @@ def _iso_date(value: str) -> str: return "" +def _iso_or_empty(value: str) -> str: + """*value* when it is an ISO ``YYYY-MM-DD`` date, else no date.""" + value = value.strip() + try: + return date.fromisoformat(value).isoformat() if len(value) == 10 else "" + except ValueError: + return "" + + +def clean_system_identity( + *, + system_uuid: str, + product_serial: str, + board_serial: str, + bios_vendor: str, + bios_version: str, + bios_date: str, +) -> SystemIdentityDict: + """The identity from values a host read some other way than the DMI files, with the + same placeholders empty; *bios_date* is the release date as ``YYYY-MM-DD``.""" + return { + "system_uuid": _clean(system_uuid).lower(), + "product_serial": _clean(product_serial), + "board_serial": _clean(board_serial), + "bios_vendor": _clean_text(bios_vendor), + "bios_version": _clean_text(bios_version), + "bios_date": _iso_or_empty(bios_date), + } + + def parse_system_identity(output: str) -> SystemIdentityDict: """The identity from :data:`SYSTEM_IDENTITY_COMMAND`'s output, placeholders empty. @@ -136,16 +170,15 @@ def parse_system_identity(output: str) -> SystemIdentityDict: except ValueError: raise ValueError("system identity: no intact IDBEGIN/IDEND frame") from None fields = (lines[start:end] + [""] * len(_FILES))[: len(_FILES)] - uuid, product_serial, board_serial = (_clean(f) for f in fields[:3]) - bios_vendor, bios_version, bios_date = fields[3:] - return { - "system_uuid": uuid.lower(), - "product_serial": product_serial, - "board_serial": board_serial, - "bios_vendor": _clean_text(bios_vendor), - "bios_version": _clean_text(bios_version), - "bios_date": _iso_date(bios_date), - } + uuid, product_serial, board_serial, bios_vendor, bios_version, bios_date = fields + return clean_system_identity( + system_uuid=uuid, + product_serial=product_serial, + board_serial=board_serial, + bios_vendor=bios_vendor, + bios_version=bios_version, + bios_date=_iso_date(bios_date), + ) class SystemIdentityMixin: diff --git a/napalm_device_types/updates.py b/napalm_device_types/updates.py index ea33bf5..05cc8df 100644 --- a/napalm_device_types/updates.py +++ b/napalm_device_types/updates.py @@ -13,7 +13,7 @@ this class in can never shadow a working implementation from a sibling base. from __future__ import annotations from collections.abc import Callable -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, NotRequired from typing_extensions import TypedDict @@ -35,6 +35,9 @@ class UpdateHistoryPackageDict(TypedDict): action: UpdateHistoryAction # "disappear": dpkg dropped it, its files taken by another old_version: str | None # None where nothing was installed before new_version: str | None # None where nothing is installed after + #: What the source calls it, where the name is no package: Windows Update's title + #: (NetOrk/netork#2892). + title: NotRequired[str | None] class UpdateHistoryDict(TypedDict): @@ -80,6 +83,9 @@ class UpdateMixin: * origin (string, optional) - where it comes from, e.g. apt's suites * security (bool or None, optional) - a security update; leave it out or None when the source does not say + * title, advisories, cves, vendor_severity (optional) - what a source + that names more than a package says of it: Windows Update's title, + ``KBArticleIDs``, ``CveIDs`` and ``MsrcSeverity`` (NetOrk/netork#2892) **An empty list means nothing is pending.** A reader that cannot read -- no package index yet, an API that did not answer -- raises diff --git a/napalm_device_types/windows_features.py b/napalm_device_types/windows_features.py new file mode 100644 index 0000000..51b1e2d --- /dev/null +++ b/napalm_device_types/windows_features.py @@ -0,0 +1,68 @@ +"""A Windows host's optional features: which are on (NetOrk/netork#2898). + +Many Windows vulnerabilities hit a role or feature only: the DNS Server, Hyper-V, IIS, +SMB 1.0, Message Queuing, Remote Desktop Services. Whether a host has one switched on +is what turns such a CVE's precondition into "met" or "not met" there, where the +platform alone leaves it open. + +**One namespace, client and server alike.** The names are the optional features' +(``FeatureName`` of ``Get-WindowsOptionalFeature -Online``, ``Name`` of +``Win32_OptionalFeature``): ``SMB1Protocol``, ``MSMQ-Server``, ``IIS-WebServerRole``, +``Microsoft-Hyper-V``, ``DNS-Server-Full-Role``. A Windows Server lists its roles there +too, under these names rather than Server Manager's (``FS-SMB1``, ``DNS``), so one name +answers on a client and a server. + +**Every feature the image knows is listed**, switched on or not: ``enabled``, +``disabled``, ``absent`` (its payload removed) or ``unknown``. A name the reading does +not list is therefore not one of this host's features -- or not spelled as Windows +spells it, which is why a consumer should not read it as "off". + +Declared under ``if TYPE_CHECKING``, like +:class:`~napalm_device_types.services.ServiceControlMixin`: a contract, never a +placeholder that could shadow an implementation. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Final + +from typing_extensions import TypedDict + +#: The states a feature is reported in. +WINDOWS_FEATURE_STATES: Final = ("enabled", "disabled", "absent", "unknown") + + +class WindowsFeatureDict(TypedDict): + """One optional feature: its name as Windows spells it, and its state.""" + + name: str + state: str # one of WINDOWS_FEATURE_STATES + + +class WindowsFeaturesDict(TypedDict): + """Every optional feature the host's image knows.""" + + features: list[WindowsFeatureDict] + + +class WindowsFeaturesMixin: + """Adds :meth:`get_windows_features` to a driver for a Windows host.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def get_windows_features(self) -> WindowsFeaturesDict: + """ + Returns every optional feature the host's image knows, with its state. + + * features (list) - ``{"name": str, "state": str}``; the state one of + ``enabled``, ``disabled``, ``absent``, ``unknown`` + + Example:: + + {"features": [ + {"name": "SMB1Protocol", "state": "disabled"}, + {"name": "MSMQ-Server", "state": "enabled"}, + {"name": "Microsoft-Hyper-V", "state": "absent"}, + ]} + """ + ... diff --git a/pyproject.toml b/pyproject.toml index ec9f8ed..7e1d16c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-device-types" -version = "4.55.0" +version = "4.56.0" description = "Abstract device-type base classes for NAPALM drivers" readme = "README.md" requires-python = ">=3.12" diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 1aaf91a..e8a0c5f 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -31,7 +31,7 @@ }, "mypy_relaxed": [], "python_file_lines": { - "napalm_device_types/models.py": 1336 + "napalm_device_types/models.py": 1297 }, "untyped_public": [] } diff --git a/tests/test_eventlog_sources.py b/tests/test_eventlog_sources.py new file mode 100644 index 0000000..35d76c3 --- /dev/null +++ b/tests/test_eventlog_sources.py @@ -0,0 +1,50 @@ +"""A Windows event channel as a log source (NetOrk/netork#2897). + +A Windows host keeps its logs in event channels (``System``, ``Security``, +``Microsoft-Windows-Sysmon/Operational``), not in a journal or in files a process +holds open. A log reader takes a channel by its name -- CrowdSec's +``event_channel``, Wazuh's ``eventchannel`` -- so a channel is a source of its own +kind, named by its channel; ``path`` is the ``.evtx`` file behind it. +""" + +from __future__ import annotations + +from typing import NotRequired, get_origin, get_type_hints + +from napalm_device_types import EVENTLOG, LOG_SOURCE_KINDS, LogSourceDict, eventlog_source + + +def test_the_kinds_a_source_can_be(): + assert LOG_SOURCE_KINDS == ("journald", "file", "container", "eventlog") + assert EVENTLOG == "eventlog" + + +def test_a_channel_is_named_by_its_channel(): + source = eventlog_source( + "Microsoft-Windows-Sysmon/Operational", + r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx", + 1052672, + 1764583200, + ) + assert source == { + "kind": "eventlog", + "path": r"C:\Windows\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx", + "unit": None, + "container_id": None, + "process": None, + "size": 1052672, + "modified": "2025-12-01T10:00:00+00:00", + "channel": "Microsoft-Windows-Sysmon/Operational", + } + + +def test_a_channel_without_a_file_or_a_last_write_says_none(): + source = eventlog_source("Application", None, None, None) + assert (source["path"], source["size"], source["modified"]) == (None, None, None) + + +def test_the_channel_is_optional_for_the_other_kinds(): + """Additive: a journal, a file and a container's stream carry no channel.""" + hints = get_type_hints(LogSourceDict, include_extras=True) + assert get_origin(hints["channel"]) is NotRequired + assert get_origin(hints["kind"]) is None diff --git a/tests/test_hardening_posture.py b/tests/test_hardening_posture.py new file mode 100644 index 0000000..a392c35 --- /dev/null +++ b/tests/test_hardening_posture.py @@ -0,0 +1,141 @@ +"""The OS-neutral security posture in HardeningDict (NetOrk/netork#2893). + +Secure Boot, the TPM, disk encryption per volume, the antimalware product, the host +firewall's profiles and virtualization-based security: optional keys beside what a Linux +host reports, so a Windows host's reading fits the same shape and Linux's stays as it is. +""" + +from __future__ import annotations + +from typing import get_args, get_type_hints + +from napalm_device_types import ( + AntimalwareDict, + DiskEncryptionDict, + EncryptedVolumeDict, + FirewallProfileDict, + HardeningDict, + TpmDict, + VbsDict, +) +from napalm_device_types.hardening import ( + AntimalwareMode, + SecureBootState, + VbsStatus, + VolumeProtection, + parse_hardening, +) + +LINUX_KEYS = frozenset( + { + "lsm", + "selinux", + "apparmor", + "crypto_policy", + "fips", + "cpu_vulnerabilities", + "cmdline", + "mitigations", + "nosmt", + "os_ids", + "virtualization", + "cpu_vendor", + } +) +POSTURE_KEYS = frozenset( + {"secure_boot", "tpm", "disk_encryption", "antimalware", "firewall_profiles", "vbs"} +) + + +def test_what_linux_fills_stays_required(): + assert HardeningDict.__required_keys__ == LINUX_KEYS + + +def test_the_posture_keys_are_optional(): + assert HardeningDict.__optional_keys__ == POSTURE_KEYS + + +def test_a_linux_reading_carries_none_of_them(): + reading = parse_hardening("HARDENING_BEGIN\n[fips]\n0\nHARDENING_END\n") + + assert set(reading) == LINUX_KEYS + + +def test_the_words_each_state_takes(): + assert set(get_args(SecureBootState)) == {"on", "off", "unsupported"} + assert set(get_args(VolumeProtection)) == {"on", "off", "unknown"} + assert set(get_args(AntimalwareMode)) == {"active", "passive", "edr_block", "sxs_passive"} + assert set(get_args(VbsStatus)) == {"off", "configured", "running"} + + +def test_the_shapes(): + assert set(get_type_hints(TpmDict)) == { + "present", + "enabled", + "activated", + "owned", + "version", + "manufacturer", + } + assert set(get_type_hints(EncryptedVolumeDict)) == { + "volume", + "system", + "protection", + "status", + "method", + } + assert set(get_type_hints(DiskEncryptionDict)) == {"provider", "installed", "volumes"} + assert set(get_type_hints(AntimalwareDict)) == { + "product", + "enabled", + "real_time", + "mode", + "signatures_updated", + "signature_age_days", + "signature_version", + "tamper_protected", + } + assert set(get_type_hints(FirewallProfileDict)) == {"name", "enabled"} + assert set(get_type_hints(VbsDict)) == {"status", "running"} + + +def test_a_windows_reading_fits_the_shape(): + reading: HardeningDict = { + **dict.fromkeys(LINUX_KEYS), # type: ignore[typeddict-item] + "secure_boot": "on", + "tpm": { + "present": True, + "enabled": True, + "activated": True, + "owned": True, + "version": "2.0", + "manufacturer": "INTC", + }, + "disk_encryption": { + "provider": "bitlocker", + "installed": True, + "volumes": [ + { + "volume": "C:", + "system": True, + "protection": "on", + "status": "fully_encrypted", + "method": "xts_aes_128", + } + ], + }, + "antimalware": { + "product": "Microsoft Defender Antivirus", + "enabled": True, + "real_time": True, + "mode": "active", + "signatures_updated": 1764547200, + "signature_age_days": 0, + "signature_version": "1.443.512.0", + "tamper_protected": True, + }, + "firewall_profiles": [{"name": "domain", "enabled": True}], + "vbs": {"status": "running", "running": ["credential_guard", "hvci"]}, + } + + assert set(reading) == LINUX_KEYS | POSTURE_KEYS diff --git a/tests/test_host_events.py b/tests/test_host_events.py new file mode 100644 index 0000000..763cf02 --- /dev/null +++ b/tests/test_host_events.py @@ -0,0 +1,90 @@ +"""get_host_events: what a host's own log recorded that says something is wrong with it. + +A crash, a power loss, a hardware error or a program that keeps dying is written +down by the host itself, in its event log or its journal; nothing on the outside +sees it. The reading is the same shape for every operating system: each event as +its kind, when, what it is about and where the host recorded it. Whether that is +a problem is the application's to decide (NetOrk/netork#2897). +""" + +from __future__ import annotations + +from typing import get_type_hints + +import pytest + +from napalm_device_types import ( + HOST_EVENT_KINDS, + HOST_EVENT_MESSAGE_CHARS, + HOST_EVENT_WINDOW_DAYS, + HostEventDict, + HostEventsDict, + HostEventsMixin, + host_event, +) + + +class TestTheKinds: + def test_every_kind_the_contract_names(self): + assert HOST_EVENT_KINDS == ( + "unexpected_shutdown", + "system_crash", + "hardware_error_fatal", + "hardware_error_corrected", + "disk_error", + "app_crash", + "service_crash", + ) + + def test_the_window_is_a_week(self): + assert HOST_EVENT_WINDOW_DAYS == 7 + + +class TestHostEvent: + def test_the_time_is_iso_in_utc(self): + event = host_event("system_crash", 1764583200, "System: BugCheck 1001", "0x0000009f") + assert event == { + "kind": "system_crash", + "time": "2025-12-01T10:00:00+00:00", + "subject": "0x0000009f", + "source": "System: BugCheck 1001", + "message": None, + } + + def test_the_message_is_cut_to_its_limit(self): + event = host_event("disk_error", 0, "System: disk 7", None, "x" * 1000) + assert event["message"] == "x" * HOST_EVENT_MESSAGE_CHARS + + def test_the_message_keeps_its_words_without_the_surrounding_space(self): + event = host_event("disk_error", 0, "System: disk 7", None, " bad block\r\n ") + assert event["message"] == "bad block" + + @pytest.mark.parametrize("empty", ["", " ", None]) + def test_an_empty_subject_or_message_is_none(self, empty): + event = host_event("app_crash", 0, "Application: Application Error 1000", empty, empty) + assert event["subject"] is None + assert event["message"] is None + + def test_an_unknown_kind_is_refused(self): + with pytest.raises(ValueError, match="bluescreen"): + host_event("bluescreen", 0, "System", None) + + +class TestTheContract: + def test_the_getter_is_declared_only(self): + """A contract: nothing at runtime until a driver implements it, so + ``hasattr(driver, "get_host_events")`` stays truthful.""" + assert not hasattr(HostEventsMixin(), "get_host_events") + + def test_the_reading_says_what_it_could_not_read(self): + hints = get_type_hints(HostEventsDict) + assert set(hints) == {"since", "events", "capped", "unread"} + + def test_an_event_names_its_kind_time_subject_source_and_message(self): + assert set(get_type_hints(HostEventDict)) == { + "kind", + "time", + "subject", + "source", + "message", + } diff --git a/tests/test_host_repairs.py b/tests/test_host_repairs.py new file mode 100644 index 0000000..9f8475a --- /dev/null +++ b/tests/test_host_repairs.py @@ -0,0 +1,131 @@ +"""HostRepairMixin: a host's own checks and repairs of its system, as fixed runs (NetOrk/netork#2899). + +One method per run, declared and not implemented, so ``hasattr`` tells an application +which runs a driver offers. ``tool_outcome`` is the shared part of every run: a tool's +exit code decides, a failure names the tool's last lines, and the output is bounded. +""" + +from __future__ import annotations + +import inspect + +import pytest + +from napalm_device_types import ( + DeviceTypeDriver, + HostRepairMixin, + HostRepairResultDict, + tool_outcome, +) +from napalm_device_types.host_repairs import ( + FAILURE_TAIL_LINES, + HOST_REPAIR_METHODS, + OUTPUT_LIMIT, + LineLog, + offered_host_repairs, +) + +_RUNS = ( + "verify_system_files", + "repair_system_files", + "check_component_store", + "repair_component_store", + "update_antimalware_signatures", + "scan_antimalware", +) + + +class TestContract: + @pytest.mark.parametrize("name", _RUNS) + def test_declared_not_implemented(self, name): + assert not hasattr(HostRepairMixin, name) + + @pytest.mark.parametrize("name", _RUNS) + def test_each_run_is_documented(self, name): + source = inspect.getsource(HostRepairMixin) + assert f"def {name}(" in source + assert "log: LineLog | None = None" in source + assert "limit: float | None = None" in source + + def test_not_on_any_role_base(self): + # A driver mixes it in where its host has these tools. + assert not issubclass(DeviceTypeDriver, HostRepairMixin) + + def test_the_catalog_names_every_run(self): + assert set(HOST_REPAIR_METHODS) == set(_RUNS) + + def test_a_line_log_takes_one_line(self): + lines: list[str] = [] + log: LineLog = lines.append + log("x") + assert lines == ["x"] + + +class TestOffered: + def test_only_the_runs_a_driver_defines(self): + class _Host(HostRepairMixin): + def verify_system_files(self, *, log=None): # noqa: ARG002 + return tool_outcome(["ok"], 0, tool="sfc") + + def update_antimalware_signatures(self, *, log=None): # noqa: ARG002 + return tool_outcome([], 0, tool="Update-MpSignature") + + assert offered_host_repairs(_Host) == [ + "verify_system_files", + "update_antimalware_signatures", + ] + + def test_a_run_set_to_none_is_not_offered(self): + class _Host(HostRepairMixin): + scan_antimalware = None + + assert offered_host_repairs(_Host) == [] + + def test_a_driver_without_the_mixin_offers_none(self): + assert offered_host_repairs(object) == [] + + +class TestToolOutcome: + def test_exit_code_zero_succeeds_with_the_whole_output(self): + result: HostRepairResultDict = tool_outcome(["one", "two"], 0, tool="sfc") + assert result == {"success": True, "output": "one\ntwo", "exit_code": 0} + + def test_a_non_zero_exit_code_fails_with_the_last_lines(self): + lines = [f"line {n}" for n in range(30)] + result = tool_outcome(lines, 5, tool="DISM") + + assert result["success"] is False + assert result["exit_code"] == 5 + assert result["error"].startswith("DISM ended with exit code 5:") + tail = result["error"].split(":", 1)[1].strip().splitlines() + assert tail == lines[-FAILURE_TAIL_LINES:] + + def test_a_failure_without_output_names_the_code_only(self): + result = tool_outcome([], 2, tool="sfc") + assert result["error"] == "sfc ended with exit code 2" + + def test_exit_codes_are_shown_as_hex_when_they_are_hresults(self): + result = tool_outcome(["Error: 0x800f081f"], 0x800F081F, tool="DISM") + assert result["error"].startswith("DISM ended with exit code 0x800F081F:") + + def test_a_negative_exit_code_is_read_as_unsigned(self): + # .NET's Process.ExitCode is an Int32: 0x800F081F arrives as -2146498529. + result = tool_outcome([], -2146498529, tool="DISM") + assert result["exit_code"] == 0x800F081F + assert "0x800F081F" in result["error"] + + def test_no_exit_code_is_a_failure(self): + result = tool_outcome(["started"], None, tool="sfc") + assert result["success"] is False + assert result["exit_code"] is None + assert result["error"] == "sfc ended without an exit code: started" + + def test_blank_lines_are_not_the_tail(self): + result = tool_outcome(["the reason", "", " "], 1, tool="sfc") + assert result["error"] == "sfc ended with exit code 1: the reason" + + def test_the_output_keeps_its_end_within_the_limit(self): + lines = ["x" * 1000] * (OUTPUT_LIMIT // 1000 + 50) + ["the end"] + result = tool_outcome(lines, 0, tool="sfc") + assert len(result["output"]) <= OUTPUT_LIMIT + assert result["output"].endswith("the end") diff --git a/tests/test_host_storage.py b/tests/test_host_storage.py new file mode 100644 index 0000000..e9e9eb0 --- /dev/null +++ b/tests/test_host_storage.py @@ -0,0 +1,80 @@ +"""HostStorageMixin: a host's disks, volumes and drive health without being a storage +device (NetOrk/netork#2896, #2705). + +``StorageDriver`` is a role: a driver that inherits it is shown as storage. A Windows or +Linux host has disks too, and is still a host. The mixin carries the same getters with no +role, so an OS driver reports its disks and stays what it is. +""" + +from __future__ import annotations + +import inspect +from typing import get_type_hints + +from napalm_device_types import ( + DiskSmartDict, + HostStorageMixin, + HostVolumeDict, + OSDriver, + StorageDriver, +) +from napalm_device_types.models import LogicalVolumeDict +from napalm_device_types.roles import primary_role_of, role_keys_of + +GETTERS = ("get_disks", "get_disk_pools", "get_volumes", "get_disk_smart") + + +def test_declared_not_implemented(): + """hasattr is the application's capability probe; only a driver that reads a part + may answer True.""" + for name in GETTERS: + assert not hasattr(HostStorageMixin, name), name + + +def test_declarations_document_the_contract(): + source = inspect.getsource(HostStorageMixin) + for name in GETTERS: + assert f"def {name}(self)" in source, name + + +def test_carries_no_role(): + class WindowsHost(HostStorageMixin, OSDriver): + ROLE = "windows" + + assert role_keys_of(WindowsHost) == ["windows"] + assert primary_role_of(WindowsHost) == "windows" + + +def test_a_storage_device_with_the_mixin_stays_storage(): + class Nas(StorageDriver, HostStorageMixin, OSDriver): + pass + + assert primary_role_of(Nas) == "storage" + + +def test_disk_smart_keeps_the_shape_drivers_already_fill(): + """Proxmox's ``get_disk_smart`` filled these keys before there was a contract; the + contract names them, and adds the error counters and the highest temperature.""" + hints = get_type_hints(DiskSmartDict) + assert { + "model", + "serial", + "type", + "size", + "health", + "wearout", + "temperature", + "percentage_used", + "available_spare", + "reallocated_sectors", + "power_on_hours", + } <= set(hints) + assert {"temperature_max", "read_errors_uncorrected", "write_errors_uncorrected"} <= ( + DiskSmartDict.__optional_keys__ + ) + + +def test_a_host_volume_is_a_logical_volume_with_optional_extras(): + assert set(get_type_hints(LogicalVolumeDict)) <= set(get_type_hints(HostVolumeDict)) + assert {"file_system", "health"} <= HostVolumeDict.__optional_keys__ + assert LogicalVolumeDict.__required_keys__ <= HostVolumeDict.__required_keys__ diff --git a/tests/test_login_accounts.py b/tests/test_login_accounts.py index 3af90ae..20e8c4b 100644 --- a/tests/test_login_accounts.py +++ b/tests/test_login_accounts.py @@ -481,3 +481,46 @@ class TestTheCommand: reading = parse_login_accounts(out) assert isinstance(reading["accounts"], list) + + +class TestWhatAnotherPlatformAdds: + """Keys a Windows host fills (NetOrk/netork#2895), optional, so the Linux reading and + every driver that builds one stay as they are.""" + + def test_the_account_keys_linux_fills_stay_required(self): + from napalm_device_types.login_accounts import LoginAccountDict + + assert {"name", "uid", "home", "shell", "locked"} <= LoginAccountDict.__required_keys__ + assert LoginAccountDict.__optional_keys__ == frozenset( + {"sid", "administrator", "remote_desktop"} + ) + + def test_the_reading_may_name_the_privileged_groups(self): + from napalm_device_types.login_accounts import ( + LoginAccountsDict, + LoginGroupDict, + LoginGroupMemberDict, + ) + + assert LoginAccountsDict.__optional_keys__ == frozenset({"groups"}) + assert LoginGroupDict.__required_keys__ == frozenset({"name", "sid", "grants", "members"}) + assert LoginGroupMemberDict.__required_keys__ == frozenset( + {"name", "sid", "local", "group"} + ) + + def test_the_grants_are_named(self): + from napalm_device_types.login_accounts import LOGIN_GRANTS + + assert LOGIN_GRANTS == ("administrator", "remote_desktop") + + def test_the_linux_reading_sets_none_of_them(self): + reading = parse_login_accounts(_wire(DEBIAN_12)) + + assert "groups" not in reading + for account in reading["accounts"]: + assert not {"sid", "administrator", "remote_desktop"} & account.keys() + + def test_they_are_exported(self): + import napalm_device_types as dt + + assert dt.LoginGroupDict and dt.LoginGroupMemberDict and dt.LOGIN_GRANTS diff --git a/tests/test_login_sessions.py b/tests/test_login_sessions.py index 30615a5..1668dba 100644 --- a/tests/test_login_sessions.py +++ b/tests/test_login_sessions.py @@ -290,3 +290,18 @@ class TestTheCommand: except LoginSessionsUnavailable: # a host without login records return assert isinstance(reading["sessions"], list) + + +class TestWhatAnotherPlatformAdds: + """A key a Windows host fills (NetOrk/netork#2895), optional, so the Linux reading and + every driver that builds one stay as they are.""" + + def test_the_keys_linux_fills_stay_required(self): + from napalm_device_types.login_sessions import LoginSessionDict, LoginSessionsDict + + assert LoginSessionsDict.__required_keys__ == frozenset({"own_address", "sessions"}) + assert LoginSessionsDict.__optional_keys__ == frozenset({"records_since"}) + assert LoginSessionDict.__optional_keys__ == frozenset() + + def test_the_linux_reading_does_not_set_it(self): + assert "records_since" not in parse_login_sessions(_wire(DEBIAN_12)) diff --git a/tests/test_os_users.py b/tests/test_os_users.py new file mode 100644 index 0000000..90cdd72 --- /dev/null +++ b/tests/test_os_users.py @@ -0,0 +1,24 @@ +"""``UserDict``: a local OS account, as ``get_os_users`` lists it (NetOrk/netork#2889). + +POSIX numbers each account with a uid; Windows names it with a security identifier +(SID). The uid stays an int for every driver, and a driver that has a SID gives it +beside it, so nothing that reads ``uid`` today changes. +""" + +from __future__ import annotations + +from typing import get_type_hints + +from napalm_device_types.models import UserDict + + +def test_a_posix_account_needs_no_sid(): + assert UserDict.__required_keys__ == frozenset( + {"username", "uid", "gid", "home", "shell", "groups"} + ) + + +def test_an_account_may_carry_its_sid_beside_its_uid(): + assert get_type_hints(UserDict)["sid"] is str + assert "sid" in UserDict.__optional_keys__ + assert get_type_hints(UserDict)["uid"] is int diff --git a/tests/test_pve93_contracts.py b/tests/test_pve93_contracts.py index 97a512b..9ffd1f4 100644 --- a/tests/test_pve93_contracts.py +++ b/tests/test_pve93_contracts.py @@ -51,6 +51,7 @@ def test_an_update_transaction_is_its_packages_and_who_asked_for_it(): "action", "old_version", "new_version", + "title", # optional: what Windows calls the update (NetOrk/netork#2892) } actions = typing.get_args(get_type_hints(UpdateHistoryPackageDict)["action"]) assert set(actions) == { diff --git a/tests/test_service_result.py b/tests/test_service_result.py new file mode 100644 index 0000000..8d7c189 --- /dev/null +++ b/tests/test_service_result.py @@ -0,0 +1,23 @@ +"""How a service's last run ended, beside whether it runs (NetOrk/netork#2897, #2703). + +``running=False`` alone does not tell a service that died from one stopped on +purpose. The service manager knows: systemd's ``Result`` (``exit-code``, +``signal``, ``core-dump``, ``timeout`` …), Windows' exit code of the service. So +:class:`ServiceDict` carries the result in systemd's words, the exit code where +there is one, whether the service only runs when a trigger starts it, and the +account it runs as. All optional: a driver that cannot tell leaves them out. +""" + +from __future__ import annotations + +from napalm_device_types import SERVICE_RESULT_EXIT_CODE, SERVICE_RESULT_SUCCESS, ServiceDict + + +def test_the_result_is_said_in_systemds_words(): + assert SERVICE_RESULT_SUCCESS == "success" + assert SERVICE_RESULT_EXIT_CODE == "exit-code" + + +def test_the_new_fields_are_optional(): + assert ServiceDict.__required_keys__ == {"name", "running", "enabled", "pid"} + assert ServiceDict.__optional_keys__ == {"result", "exit_code", "trigger_start", "account"} diff --git a/tests/test_system_identity.py b/tests/test_system_identity.py index 40365ca..0fdb8ec 100644 --- a/tests/test_system_identity.py +++ b/tests/test_system_identity.py @@ -7,6 +7,7 @@ import pytest from napalm_device_types import ( SYSTEM_IDENTITY_COMMAND, SystemIdentityMixin, + clean_system_identity, is_placeholder_identity, parse_system_identity, ) @@ -153,6 +154,62 @@ def test_terminal_noise_around_the_frame_is_ignored(): assert parse_system_identity("\x1b[?2004h" + _out(UUID, "S1", "B1"))["board_serial"] == "B1" +# ── values read some other way ──────────────────────────────────────────────── + + +def _values(**changes: str) -> dict[str, str]: + values = { + "system_uuid": UUID, + "product_serial": "S1", + "board_serial": "B1", + "bios_vendor": "Dell Inc.", + "bios_version": "2.19.0", + "bios_date": "2023-08-14", + } + return {**values, **changes} + + +def test_values_read_without_the_dmi_files_are_cleaned_the_same_way(): + # A host that reads its SMBIOS tables through its own interface (Windows' CIM classes) + # hands the values over one by one; the placeholders are the same vendors'. + assert clean_system_identity(**_values()) == { + "system_uuid": "31303043-534d-c40c-7a72-6f1300000000", + "product_serial": "S1", + "board_serial": "B1", + "bios_vendor": "Dell Inc.", + "bios_version": "2.19.0", + "bios_date": "2023-08-14", + } + + +@pytest.mark.parametrize( + "field", ["system_uuid", "product_serial", "board_serial"], ids=["uuid", "product", "board"] +) +@pytest.mark.parametrize( + "value", + ["To be filled by O.E.M.", "Default string", "00000000-0000-0000-0000-000000000000", " "], +) +def test_a_placeholder_identity_value_reads_as_empty(field, value): + assert clean_system_identity(**_values(**{field: value}))[field] == "" + + +def test_a_firmware_text_is_cleaned_as_the_dmi_files_are(): + identity = clean_system_identity(**_values(bios_vendor="Default string", bios_version="1")) + assert identity["bios_vendor"] == "" + assert identity["bios_version"] == "1" + + +@pytest.mark.parametrize("date", ["", "08/14/2023", "2023-13-01", "2023-08-14T00:00:00"]) +def test_a_firmware_date_must_be_an_iso_date(date): + assert clean_system_identity(**_values(bios_date=date))["bios_date"] == "" + + +def test_values_are_stripped(): + identity = clean_system_identity(**_values(board_serial=" B1 ", bios_date=" 2023-08-14 ")) + assert identity["board_serial"] == "B1" + assert identity["bios_date"] == "2023-08-14" + + # ── the mixin ───────────────────────────────────────────────────────────────── diff --git a/tests/test_updates.py b/tests/test_updates.py index 6f068b3..7121263 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -47,3 +47,29 @@ def test_apply_updates_takes_a_log_callback_by_keyword_only(): def test_apply_updates_still_hides_at_runtime(): assert not hasattr(napalm_device_types.UpdateMixin, "apply_updates") + + +def test_a_pending_update_can_name_what_it_fixes(): + """A source that says which advisories and CVEs an update closes, and how its + vendor rates it (Windows Update's ``KBArticleIDs``, ``CveIDs``, ``MsrcSeverity``, + NetOrk/netork#2892), can pass that on. Optional: every reader that says nothing + of it still conforms.""" + from typing import get_type_hints + + from napalm_device_types.models import UpdateDict + + hints = get_type_hints(UpdateDict) + assert {"title", "advisories", "cves", "vendor_severity"} <= set(hints) + assert UpdateDict.__required_keys__ == {"name", "current_version", "new_version"} + + +def test_a_past_update_can_carry_its_title(): + """Windows names an update by its title, not by a package (NetOrk/netork#2892).""" + from typing import get_type_hints + + from napalm_device_types.updates import UpdateHistoryPackageDict + + assert "title" in get_type_hints(UpdateHistoryPackageDict, include_extras=True) + assert "NotRequired" in str( + get_type_hints(UpdateHistoryPackageDict, include_extras=True)["title"] + ) diff --git a/tests/test_windows_contracts.py b/tests/test_windows_contracts.py new file mode 100644 index 0000000..74a0e84 --- /dev/null +++ b/tests/test_windows_contracts.py @@ -0,0 +1,73 @@ +"""The Windows host firewall and the Windows features, as contracts (NetOrk/netork#2894, #2898). + +A Windows host's firewall is not netfilter: rules belong to profiles (Domain, +Private, Public), a profile is active per network connection, and a rule matches +a program and a service as well as ports and addresses. So the reading has a +shape of its own, next to the netfilter one rather than squeezed into it, and +``get_host_firewall`` stays the one getter an application asks. +""" + +from __future__ import annotations + +from typing import get_type_hints + +from napalm_device_types import ( + WINDOWS_FEATURE_STATES, + WINDOWS_FIREWALL_PROFILES, + WindowsFeatureDict, + WindowsFeaturesDict, + WindowsFeaturesMixin, + WindowsFirewallConnectionDict, + WindowsFirewallDict, + WindowsFirewallProfileDict, + WindowsFirewallRuleDict, +) +from napalm_device_types.host_firewall_models import HostFirewallDict as Moved +from napalm_device_types.models import ( + HostFirewallDict, + NetfilterChainDict, + NetfilterMatchDict, + NetfilterRuleDict, +) + + +def test_the_netfilter_shapes_are_still_importable_from_models(): + assert HostFirewallDict is Moved + assert set(get_type_hints(NetfilterChainDict)) == { + "family", "table", "name", "type", "hook", "priority", "policy", "rules", + } # fmt: skip + assert set(get_type_hints(NetfilterRuleDict)) == {"matches", "verdict", "target", "text"} + assert set(get_type_hints(NetfilterMatchDict)) == {"field", "op", "values"} + + +def test_a_host_firewall_reading_may_carry_a_windows_firewall_beside_its_chains(): + assert set(get_type_hints(HostFirewallDict)) == {"sources", "chains", "windows"} + assert "windows" in HostFirewallDict.__optional_keys__ + assert {"sources", "chains"} <= HostFirewallDict.__required_keys__ + + +def test_the_windows_firewall_has_profiles_rules_and_the_profile_of_each_connection(): + assert set(get_type_hints(WindowsFirewallDict)) == {"profiles", "rules", "connections"} + assert set(get_type_hints(WindowsFirewallProfileDict)) == { + "name", "enabled", "default_inbound", "default_outbound", "block_all_inbound", + "local_rules", + } # fmt: skip + assert set(get_type_hints(WindowsFirewallConnectionDict)) == {"interface", "profile"} + assert WINDOWS_FIREWALL_PROFILES == ("domain", "private", "public") + + +def test_a_windows_rule_carries_every_filter_that_decides_what_it_matches(): + assert set(get_type_hints(WindowsFirewallRuleDict)) == { + "id", "name", "group", "direction", "action", "profiles", "protocol", + "local_ports", "remote_ports", "local_addresses", "remote_addresses", + "program", "service", "package", "interfaces", "interface_types", + "authenticated", "override_block", "source", + } # fmt: skip + + +def test_windows_features_are_a_declared_contract(): + assert set(get_type_hints(WindowsFeaturesDict)) == {"features"} + assert set(get_type_hints(WindowsFeatureDict)) == {"name", "state"} + assert WINDOWS_FEATURE_STATES == ("enabled", "disabled", "absent", "unknown") + # Declared for type checkers only: mixing it in never shadows an implementation. + assert not hasattr(WindowsFeaturesMixin, "get_windows_features")