Compare commits

..
7 Commits
Author SHA1 Message Date
christianmanivong 5b26e7d2bc Merge pull request 'feat(access-point): declared AP writes and a DHCP lease reader, 4.54.0 (NetOrk/netork#695)' (#142) from feature/ap-dhcp-contracts-695 into main
driver / lowest (push) Successful in 41s
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 1m1s
driver / test (3.12) (push) Successful in 1m11s
driver / test (3.13) (push) Successful in 1m13s
driver / build (push) Successful in 31s
driver / security (push) Successful in 57s
driver / publish (push) Successful in 29s
CI / driver (push) Successful in 3m18s
2026-11-29 22:03:13 +00:00
christianmanivong eb8b2dbea7 chore(release): 4.54.0
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 42s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m14s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 53s
CI / driver (pull_request) Successful in 1m49s
driver / publish (pull_request) Skipped
2026-11-29 20:48:04 +01:00
christianmanivong 2ad1ead2f5 refactor(access-point): the new shapes beside their declarations, models.py within its ratchet
DhcpLeaseDict lives in dhcp_leases, the AP shapes in
access_point_models; models.py stays at its recorded size.
2026-11-29 20:48:04 +01:00
christianmanivong 0db9c9ba65 feat(access-point): declared writes for SSIDs, radios, VLAN names and the AP configuration, and a DHCP lease reader (NetOrk/netork#695)
WirelessWritesMixin declares push_ssid_config(ssid, SsidConfigDict), a
partial write, and set_radio_channels({radio: channel}), every radio in
one restart; AccessPointDriver and ResidentialGatewayDriver carry it.
AccessPointDriver declares set_vlan_name(vlan_id, name) and, through
ApConfigMixin, apply_ap_config(ApConfigDict, parts): the desired state
in vendor-neutral terms, of which the driver writes the parts the caller
found different, answered by ApConfigResultDict. The part names and
their I/O-free readers live in ap_config.

DhcpLeasesMixin declares get_dhcp_leases() with DhcpLeaseDict, apart
from DhcpServerMixin, so an access point can report the leases it serves.
2026-11-29 20:27:31 +01:00
christianmanivong 059d97f6de feat(updates): apply_updates takes an optional log callback (NetOrk/netork#1112)
UpdateMixin.apply_updates declares a keyword-only log, as
harden_ssh_server does: it receives each line of the package manager's
output as the host prints it. A driver that cannot stream does not call
it and returns the output at the end, as before; the declaration stays
compatible with every driver that implements it without the keyword.
2026-11-29 20:18:31 +01:00
christianmanivong e2970831f8 Merge pull request 'feat(hardening): virtualization and CPU vendor, and installing the CPU microcode, 4.53.0 (NetOrk/netork#2838)' (#141) from feature/cpu-microcode into main
driver / types (push) Successful in 53s
driver / standard (push) Successful in 24s
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 1m3s
driver / build (push) Successful in 26s
driver / lowest (push) Successful in 53s
driver / test (3.12) (push) Successful in 1m38s
driver / security (push) Successful in 57s
driver / publish (push) Successful in 43s
CI / driver (push) Successful in 2m49s
2026-11-28 23:10:03 +00:00
christianmanivong 7451fc9dfc feat(hardening): where the OS runs and whose CPU it is, and installing the CPU microcode, 4.53.0 (NetOrk/netork#2838)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 1m11s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 27s
driver / types (pull_request) Successful in 1m50s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 2m12s
driver / publish (pull_request) Skipped
get_hardening() reads virtualization (systemd-detect-virt, else the cpuinfo
hypervisor flag) and cpu_vendor. CpuMicrocodeMixin.install_cpu_microcode()
refuses a guest, picks the package of the distribution and CPU vendor
(microcode_package), adds Debian's firmware component to Debian's own sources
where it is missing, reloads the index and installs the package; it loads at
the next boot.
2026-11-29 00:06:50 +01:00
18 changed files with 1636 additions and 6 deletions

No files matched your search

+59
View File
@@ -7,6 +7,65 @@ recorded here; their history is the git log.
## [Unreleased]
## [4.54.0] - 2026-11-29
### Added
- An access point's writes as declared methods (NetOrk/netork#695), so an application no
longer builds the device's commands itself:
- `WirelessWritesMixin`, on `AccessPointDriver` and `ResidentialGatewayDriver`:
`push_ssid_config(ssid, SsidConfigDict)` writes the settings it is given (encryption,
key, hidden, enabled, disassoc_low_ack, max_inactivity) to every interface serving the
SSID and leaves the rest; `set_radio_channels({radio: channel})` changes every radio in
one go, with one restart of the wireless stack (`AUTO_CHANNEL`, 0, lets a radio choose).
A refused step raises.
- `AccessPointDriver.set_vlan_name(vlan_id, name)`: names a VLAN the access point
carries; True when written, False when it carries no such VLAN. An access point needs
no `set_vlan`, which creates VLANs on a switch.
- `ApConfigMixin.apply_ap_config(ApConfigDict, parts)`, on `AccessPointDriver`: the
access point's desired configuration, of which the driver writes the parts the caller
found different. `ApConfigDict` (and `ApSsidConfigDict` per SSID) names radios,
remote syslog, web interface, SSH, the management VLAN, the bridge and its spanning
tree, 802.11r and the SSIDs in vendor-neutral terms; `ApConfigResultDict` says which
parts were written, which were not (unknown, or missing a value they need, such as a
key), whether the device restarts, and what was sent with every passphrase masked.
The parts are `AP_CONFIG_PARTS`, `network/vlan/<vid>` and
`wireless/<ssid>/<attribute>` (`AP_CONFIG_SSID_ATTRIBUTES`); `ap_config_ssid_part`,
`ap_config_vlan_part` and `is_ap_config_part` read them.
- `DhcpLeasesMixin.get_dhcp_leases()`, a list of `DhcpLeaseDict` (mac, ip, hostname,
lease_end, state): the leases a DHCP server handed out, in a mixin of its own, apart from
`DhcpServerMixin`, so that an access point can report them. A failed read raises; a
device that serves none returns `[]`. A driver that already has the method keeps
working; it declares the mixin by adding it to its bases.
- `UpdateMixin.apply_updates(packages, *, log=None)`: an optional keyword-only `log` that
receives each line of the package manager's output as the host prints it
(NetOrk/netork#1112), as `harden_ssh_server(..., log=...)` does. A driver that cannot
stream does not call it and returns the output at the end, as before; `output` holds the
whole output either way. Drivers without it keep conforming.
## [4.53.0] - 2026-11-28
### Added
- `get_hardening()` reads whether the host runs on its own hardware, and whose CPU it is
(NetOrk/netork#2838): `virtualization`, `systemd-detect-virt`'s word (`none` on bare
metal, else the hypervisor or container engine, lowercased), else `vm` or `none` from the
`hypervisor` flag of `/proc/cpuinfo` where systemd-detect-virt is not installed; and
`cpu_vendor`, the first `vendor_id` of `/proc/cpuinfo` (`GenuineIntel`, `AuthenticAMD`;
None without one, as on ARM). Read-only, like the rest of the reading.
- `CpuMicrocodeMixin.install_cpu_microcode()`: the CPU vendor's microcode on a host that
runs on its own CPU, in three steps. `read` refuses a guest (a guest loads no microcode,
its host does) and a host whose virtualization could not be told, and picks the package
(`microcode_package`): `intel-microcode`/`amd64-microcode` on Debian and Ubuntu,
`microcode_ctl`/`linux-firmware` on Enterprise Linux and Fedora,
`ucode-intel`/`ucode-amd` on SUSE; none elsewhere. `sources`, on a Debian host only,
adds Debian's firmware component (`firmware_component`: `non-free-firmware`, `non-free`
up to bullseye) to every enabled source of Debian's own archive that has `main`, and
loads the package index again; another vendor's source is never touched
(`add_component`). `install` is `ensure_package`'s. The microcode loads at the next boot;
the restart is the caller's. Returns `CpuMicrocodeFixDict` (the fix, `package`,
`sources_changed`). On no role base: a driver mixes it in. The index is loaded again through
`_reload_package_index`, `refresh_available_updates` by default; a driver whose refresh only
starts a task overrides it with one that waits.
## [4.52.0] - 2026-11-28
### Added
+22 -1
View File
@@ -129,6 +129,9 @@ else Zabbix's repository, configure, firewall, enable and restart; the driver wr
configuration and opens the firewall; an `active_only` agent gets `StartAgents=0` and no
firewall opening), `EnsurePackageMixin.ensure_package(name)`,
`PackageProxyMixin.configure_package_proxy(url)`,
`CpuMicrocodeMixin.install_cpu_microcode()` (the CPU vendor's microcode on a host that runs
on its own CPU; on Debian with its archive's firmware component added first;
`napalm_device_types.cpu_microcode`),
`TimeSyncMixin.configure_time_sync(ntp_servers, timezone)` and
`ContainerEngineMixin.grant_container_engine_access(user)`. A driver whose device takes the
change in one call overrides the template method. A driver mixes in the fixes its device
@@ -174,7 +177,8 @@ its kernel and its own tools say it, in one read-only command. The active securi
the one part that needs root), the crypto policy (`update-crypto-policies --show`) and FIPS
mode, the kernel's answer for each CPU vulnerability (`/sys/devices/system/cpu/vulnerabilities`,
put in one word by `cpu_vulnerability_state`), `mitigations=` and `nosmt` from the kernel
command line, and `ID`/`ID_LIKE` from `/etc/os-release`. Read as root first and, where root
command line, `ID`/`ID_LIKE` from `/etc/os-release`, whether the host runs virtualized
(`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".
@@ -647,6 +651,23 @@ since both commonly run the DHCP server for their networks).
`ConfigLifecycleMixin` (config load/compare/commit/rollback) is mixed in by a
driver itself.
An access point's writes (NetOrk/netork#695): `WirelessWritesMixin` declares
`push_ssid_config(ssid, SsidConfigDict)`, a partial write of an SSID's settings, and
`set_radio_channels({radio: channel})`, every radio in one go with one restart of the
wireless stack (`AUTO_CHANNEL`, 0, lets a radio choose); both come with
`AccessPointDriver` and `ResidentialGatewayDriver`. `AccessPointDriver` also declares
`set_vlan_name(vlan_id, name)`, a narrow write instead of the switch's `set_vlan`, and
`ApConfigMixin.apply_ap_config(ApConfigDict, parts)`: the access point's desired
configuration, of which the driver writes the parts the caller names
(`AP_CONFIG_PARTS`, `network/vlan/<vid>`, `wireless/<ssid>/<attribute>`; read them with
`ap_config_ssid_part`, `ap_config_vlan_part`, `is_ap_config_part`). The caller compares,
the driver writes; it answers with `ApConfigResultDict`.
`DhcpLeasesMixin` (`get_dhcp_leases()`, a list of `DhcpLeaseDict`) reads the leases a
DHCP server handed out. It is apart from `DhcpServerMixin`, since an access point serves
leases without being a DHCP server anybody manages; a driver mixes it in itself. A failed
read raises; a device that serves none returns `[]`.
### Fingerprints
`DeviceTypeDriver` carries what discovery matches a device against: `PORT_SPECS`,
+1 -1
View File
@@ -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` |
| **Capability** | Declares only. | `packages`, `services`, `updates`, `nat_vpn`, `mac_acl`, `config_lifecycle`, `interface_filter`, `host_reboot`, `dhcp_leases`, `wireless_writes`, `ap_config` |
| **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` |
+45
View File
@@ -44,6 +44,7 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.container_engine.ContainerEngineMixin`
* :class:`~napalm_device_types.credential_expiry.CredentialExpiryMixin`
* :class:`~napalm_device_types.dhcp.DhcpServerMixin`
* :class:`~napalm_device_types.dhcp_leases.DhcpLeasesMixin`
* :class:`~napalm_device_types.firewall_rules.FirewallRuleMixin`
* :class:`~napalm_device_types.hardening.HardeningMixin`
* :class:`~napalm_device_types.health_metrics.HealthMetricsMixin`
@@ -58,6 +59,8 @@ instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.log_sources.LogSourcesMixin`
* :class:`~napalm_device_types.host_firewall.HostFirewallMixin`
* :class:`~napalm_device_types.mac_acl.MacAclMixin`
* :class:`~napalm_device_types.ap_config.ApConfigMixin`
* :class:`~napalm_device_types.wireless_writes.WirelessWritesMixin`
* :class:`~napalm_device_types.nat_vpn.NatVpnMixin`
* :class:`~napalm_device_types.packages.PackageManagementMixin`
* :class:`~napalm_device_types.ping_sweep.PingSweepMixin`
@@ -83,6 +86,20 @@ Introspection -- :func:`~napalm_device_types.roles.roles_of`,
"""
from napalm_device_types.access_point import AccessPointDriver
from napalm_device_types.access_point_models import (
ApConfigDict,
ApConfigResultDict,
ApSsidConfigDict,
SsidConfigDict,
)
from napalm_device_types.ap_config import (
AP_CONFIG_PARTS,
AP_CONFIG_SSID_ATTRIBUTES,
ApConfigMixin,
ap_config_ssid_part,
ap_config_vlan_part,
is_ap_config_part,
)
from napalm_device_types.apt_history import (
APT_HISTORY_COMMAND,
AptHistoryMixin,
@@ -156,12 +173,20 @@ from napalm_device_types.container_engine import (
ContainerEngineMixin,
ContainerEngineUnavailable,
)
from napalm_device_types.cpu_microcode import (
CpuMicrocodeFixDict,
CpuMicrocodeMixin,
add_component,
firmware_component,
microcode_package,
)
from napalm_device_types.credential_expiry import (
CredentialExpiryDict,
CredentialExpiryMixin,
CredentialKind,
)
from napalm_device_types.dhcp import DhcpApplyError, DhcpServerMixin, normalize_cidr, normalize_mac
from napalm_device_types.dhcp_leases import DhcpLeaseDict, DhcpLeasesMixin
from napalm_device_types.dns_forward import DnsForwardMixin
from napalm_device_types.firewall import FirewallDriver
from napalm_device_types.firewall_rules import FirewallRuleMixin
@@ -432,6 +457,7 @@ 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.wireless_writes import AUTO_CHANNEL, WirelessWritesMixin
from napalm_device_types.zabbix_agent import (
ZabbixAgentSettingsDict,
check_zabbix_agent_settings,
@@ -554,6 +580,20 @@ __all__ = [
"DeviceTypeDriver",
"DhcpApplyError",
"DhcpServerMixin",
"DhcpLeaseDict",
"DhcpLeasesMixin",
"AP_CONFIG_PARTS",
"AP_CONFIG_SSID_ATTRIBUTES",
"ApConfigDict",
"ApConfigMixin",
"ApConfigResultDict",
"ApSsidConfigDict",
"ap_config_ssid_part",
"ap_config_vlan_part",
"is_ap_config_part",
"AUTO_CHANNEL",
"SsidConfigDict",
"WirelessWritesMixin",
"FingerprintRule",
"rules_max_weight",
"FirewallDriver",
@@ -597,6 +637,11 @@ __all__ = [
"parse_canonical_status",
"HARDENING_COMMAND",
"HardeningMixin",
"CpuMicrocodeFixDict",
"CpuMicrocodeMixin",
"add_component",
"firmware_component",
"microcode_package",
"HardeningDict",
"cpu_vulnerability_state",
"parse_hardening",
+18
View File
@@ -12,6 +12,7 @@ Usage::
from typing import TYPE_CHECKING
from napalm_device_types.ap_config import ApConfigMixin
from napalm_device_types.base import DeviceTypeDriver
from napalm_device_types.health_metrics import HealthMetricsMixin
from napalm_device_types.interface_filter import InterfaceFilterMixin
@@ -27,9 +28,12 @@ from napalm_device_types.models import (
from napalm_device_types.packages import PackageManagementMixin
from napalm_device_types.services import ServiceControlMixin
from napalm_device_types.updates import UpdateMixin
from napalm_device_types.wireless_writes import WirelessWritesMixin
class AccessPointDriver(
WirelessWritesMixin,
ApConfigMixin,
MacAclMixin,
UpdateMixin,
ServiceControlMixin,
@@ -61,6 +65,20 @@ class AccessPointDriver(
if TYPE_CHECKING:
def set_vlan_name(self, vlan_id: int, name: str) -> bool:
"""
Names the VLAN *vlan_id* the access point carries *name*.
Narrow on purpose: an access point carries the VLANs its SSIDs are
bridged into, and naming one is all it takes. It is no switch, and
does not create VLANs or set ports (``SwitchDriver.set_vlan``).
:returns: True when written; False when the device carries no VLAN
*vlan_id* that takes a name.
:raises Exception: when the device refuses the write.
"""
...
def get_wireless_config(self) -> WirelessConfigDict:
"""
Returns global wireless configuration parameters that apply across
@@ -113,3 +113,80 @@ class SSIDBridgeDict(TypedDict):
vlan_id: int
tagged: bool
client_isolation: bool
class SsidConfigDict(TypedDict, total=False):
"""What ``push_ssid_config`` writes to an SSID; a key left out is left as it is.
``encryption`` is the mode in hostapd's terms (``none``, ``psk2``, ``sae``,
``sae-mixed``, ...), ``key`` its passphrase. Which writes are safe -- never a
keyed mode without a key -- is the caller's policy, not the driver's.
"""
encryption: str
key: str
hidden: bool
enabled: bool
disassoc_low_ack: bool
max_inactivity: int # seconds
class ApSsidConfigDict(TypedDict):
"""One SSID of an access point's desired configuration (``ApConfigDict.ssids``)."""
name: str
vlan_id: NotRequired[int | None] # the VLAN its clients are bridged into
bands: NotRequired[list[str]] # "2.4 GHz", "5 GHz", "6 GHz"; empty: every band
encryption: NotRequired[str] # as in SsidConfigDict; "none" when open
key: NotRequired[str] # the passphrase; left out where none is on record
hidden: NotRequired[bool]
enabled: NotRequired[bool]
client_isolation: NotRequired[bool]
max_clients: NotRequired[int | None] # None: no limit
disassoc_low_ack: NotRequired[bool | None] # None: the device's default
max_inactivity: NotRequired[int | None] # seconds; None: the device's default
acl_mode: NotRequired[str] # "off" | "whitelist" | "blacklist"
acl_macs: NotRequired[list[str]] # the MACs of the list acl_mode names
fast_transition: NotRequired[bool] # 802.11r, in ApConfigDict.mobility_domain
class ApConfigDict(TypedDict, total=False):
"""An access point's desired configuration, as ``apply_ap_config`` writes it.
The caller decides which parts differ (``AP_CONFIG_PARTS``); the driver turns
the values those parts need into its device's commands. A value a part needs
and the dict lacks leaves that part unwritten (``ApConfigResultDict.skipped``).
"""
country_code: str # ISO 3166-1 alpha-2, for every radio
htmode_5g: str # the 5 GHz radio's channel width mode, e.g. "VHT80"
htmode_2g: str # the 2.4 GHz radio's, e.g. "HT20"
syslog_host: str # remote syslog target
syslog_port: int # UDP
web_ui: bool # whether the device serves its web interface
ssh_port: int
ssh_password_auth: bool # whether SSH takes a password login, root's included
management_vlan_id: int | None # the VLAN the device is managed in; None: no VLANs
management_untagged: bool # the management VLAN untagged (native) on the uplink
bridge_stp: bool # spanning tree on the bridge the SSIDs' VLANs share
mobility_domain: str # 802.11r mobility domain, 4 hex digits
ft_over_ds: bool # 802.11r over the distribution system rather than the air
ssids: list[ApSsidConfigDict]
class ApConfigResultDict(TypedDict):
"""What ``apply_ap_config`` did.
``applied`` and ``skipped`` are parts of those asked for: ``skipped`` the
ones the driver wrote nothing for -- a part it does not know, or one whose
values are missing, such as a keyed mode without a key. ``restarts`` says the
device restarts to apply them; the session is usually gone then.
``commands`` is what was sent, every passphrase masked; ``log`` where the
device keeps the output, "" when it keeps none.
"""
applied: list[str]
skipped: list[str]
restarts: bool
commands: str
log: str
+114
View File
@@ -0,0 +1,114 @@
"""An access point's configuration, applied as desired state.
The caller compares what it wants with what the device reports and names the
parts that differ; :meth:`ApConfigMixin.apply_ap_config` gets the whole desired
state and those parts, and writes them the way its device takes them. The
comparison is the caller's, the commands the driver's.
A part is a fixed name (``AP_CONFIG_PARTS``), ``network/vlan/<vid>`` for one VLAN
of the bridge, or ``wireless/<ssid>/<attribute>`` for one setting of an SSID
(``AP_CONFIG_SSID_ATTRIBUTES``). The helpers below read them; they do no I/O.
Declared under ``if TYPE_CHECKING``: only a driver that applies a configuration
defines ``apply_ap_config``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from napalm_device_types.access_point_models import ApConfigDict, ApConfigResultDict
#: The parts without a subject, and the values of ``ApConfigDict`` each writes.
AP_CONFIG_PARTS = frozenset(
{
"radio/country", # country_code, on every radio
"radio/5g_htmode", # htmode_5g
"radio/2g_htmode", # htmode_2g
"system/syslog", # syslog_host, syslog_port
"system/web_ui", # web_ui
"system/ssh_port", # ssh_port
"system/password_auth", # ssh_password_auth
"network/bridge", # the bridge with every VLAN the SSIDs and management use
"network/bridge_stp", # bridge_stp
}
)
#: What ``wireless/<ssid>/<attribute>`` may name: "missing" creates the SSID,
#: "passphrase" writes its key, "acl" its MAC list, "ft" its 802.11r settings; the
#: rest write the value of ``ApSsidConfigDict`` of that name ("vlan" vlan_id).
AP_CONFIG_SSID_ATTRIBUTES = frozenset(
{
"missing",
"vlan",
"bands",
"encryption",
"passphrase",
"hidden",
"enabled",
"client_isolation",
"max_clients",
"disassoc_low_ack",
"max_inactivity",
"acl",
"ft",
}
)
_SSID_PREFIX = "wireless/"
_VLAN_PREFIX = "network/vlan/"
_VLAN_IDS = range(1, 4095)
def ap_config_ssid_part(part: str) -> tuple[str, str] | None:
"""``(ssid, attribute)`` of a ``wireless/<ssid>/<attribute>`` part; None for any other.
Split at the last slash: an SSID may hold one, an attribute never does.
"""
if not part.startswith(_SSID_PREFIX):
return None
ssid, _, attribute = part[len(_SSID_PREFIX) :].rpartition("/")
if not ssid or attribute not in AP_CONFIG_SSID_ATTRIBUTES:
return None
return ssid, attribute
def ap_config_vlan_part(part: str) -> int | None:
"""The VLAN id of a ``network/vlan/<vid>`` part; None for any other."""
if not part.startswith(_VLAN_PREFIX):
return None
vid = part[len(_VLAN_PREFIX) :]
if not vid.isdigit() or int(vid) not in _VLAN_IDS:
return None
return int(vid)
def is_ap_config_part(part: str) -> bool:
"""Whether *part* is one ``apply_ap_config`` knows."""
return (
part in AP_CONFIG_PARTS
or ap_config_vlan_part(part) is not None
or ap_config_ssid_part(part) is not None
)
class ApConfigMixin:
if TYPE_CHECKING:
def apply_ap_config(self, config: ApConfigDict, parts: list[str]) -> ApConfigResultDict:
"""
Writes the *parts* of *config* to the device.
Only the parts named are written, each from the values of *config* it
needs (see ``AP_CONFIG_PARTS``). A part the driver does not know, or
whose values *config* lacks -- a keyed SSID without its key -- is
written not at all and comes back in ``skipped``: never half of it.
A part that rebuilds the device's network (``network/bridge``) may
restart the device; ``restarts`` then says so, and the caller waits
before it reads the device again.
:raises Exception: when the device refuses the write, or the commands
cannot be handed to it.
"""
...
+309
View File
@@ -0,0 +1,309 @@
"""The CPU vendor's microcode, installed on a host that runs on its own CPU (NetOrk/netork#2706).
A CPU vulnerability the kernel reports ``Vulnerable: ... no microcode`` closes with the
microcode the CPU's vendor ships: the distribution packages it, and the initramfs loads
it early at the next boot. Installing it is the fix; the restart that loads it is the
caller's to schedule.
- **Which package** (:func:`microcode_package`): by the distribution's family
(``ID``/``ID_LIKE``) and the CPU's ``vendor_id``. Debian and Ubuntu:
``intel-microcode``, ``amd64-microcode``; Enterprise Linux and Fedora:
``microcode_ctl``, ``linux-firmware``; SUSE: ``ucode-intel``, ``ucode-amd``. Elsewhere
(Arch, Alpine, an appliance) the boot loader has to load it, which is not a package's
to change: no package.
- **Not on a guest.** A guest loads no microcode and sees only the CPU features its
hypervisor passes through: the hardening reading's ``virtualization`` must be
``none``.
- **Debian's component** (:func:`firmware_component`, :func:`add_component`): Debian keeps
the packages in ``non-free-firmware`` (``non-free`` up to bullseye), which a Proxmox VE or
Proxmox Backup Server install does not enable. On a Debian host (``ID=debian``) every
enabled source of Debian's own archive (a host under ``debian.org``) that has ``main``
gets the component, and the package index is loaded again. Another vendor's source is
never touched; Ubuntu ships the packages in its own components.
A template like the fixes of :mod:`napalm_device_types.fixes`: a driver mixes
:class:`CpuMicrocodeMixin` in where it has ``get_hardening``, ``ensure_package`` (with
``get_packages``), :class:`~napalm_device_types.apt_releases.AptReleaseMixin`'s transports
and ``refresh_available_updates`` (or its own ``_reload_package_index``, where the refresh
only starts a task). It is on no role base, so
``callable(getattr(driver, "install_cpu_microcode", None))`` stays a truthful answer.
"""
from __future__ import annotations
import base64
import shlex
from collections.abc import Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from urllib.parse import urlsplit
from napalm_device_types.apt_releases import _LIST_LINE, _code, _is_deb822, _paragraphs
from napalm_device_types.fixes import run_fix_steps
from napalm_device_types.models import FixResultDict, FixStepOutcomeDict
if TYPE_CHECKING: # pragma: no cover
from napalm_device_types.apt_releases import AptReleasesDict, AptSourceDict
_INTEL = "GenuineIntel"
_AMD = "AuthenticAMD"
#: Family -> the IDs that name it, and the package per CPU vendor.
_FAMILIES: tuple[tuple[frozenset[str], dict[str, str]], ...] = (
(frozenset({"debian", "ubuntu"}), {_INTEL: "intel-microcode", _AMD: "amd64-microcode"}),
(frozenset({"rhel", "centos", "fedora"}), {_INTEL: "microcode_ctl", _AMD: "linux-firmware"}),
(frozenset({"suse", "opensuse", "sles"}), {_INTEL: "ucode-intel", _AMD: "ucode-amd"}),
)
_DEBIAN_PACKAGES = frozenset(_FAMILIES[0][1].values())
#: Debian's releases before bookworm, which had no ``non-free-firmware``.
_BEFORE_FIRMWARE = frozenset({"squeeze", "wheezy", "jessie", "stretch", "buster", "bullseye"})
def _family_ids(os_ids: Sequence[str]) -> set[str]:
ids = {i.lower() for i in os_ids}
if any(i.startswith("opensuse") for i in ids):
ids.add("opensuse")
return ids
def microcode_package(os_ids: Sequence[str] | None, cpu_vendor: str | None) -> str | None:
"""The package that brings the CPU's microcode on this distribution; None where none does.
*os_ids* are ``ID`` then ``ID_LIKE`` (the hardening reading's ``os_ids``),
*cpu_vendor* is ``/proc/cpuinfo``'s ``vendor_id``.
"""
if not os_ids or not cpu_vendor:
return None
ids = _family_ids(os_ids)
for names, packages in _FAMILIES:
if ids & names:
return packages.get(cpu_vendor)
return None
def firmware_component(codename: str) -> str:
"""Debian's component for firmware and microcode in release *codename*."""
return "non-free" if codename.strip().lower() in _BEFORE_FIRMWARE else "non-free-firmware"
def _is_debian_archive(uri: str) -> bool:
try:
host = (urlsplit(uri).hostname or "").lower()
except ValueError:
return False
return host == "debian.org" or host.endswith(".debian.org")
def _wants(uris: Sequence[str], components: Sequence[str], component: str) -> bool:
"""Whether a source of Debian's own archive, with ``main``, lacks *component*."""
return (
bool(uris)
and all(_is_debian_archive(u) for u in uris)
and "main" in components
and component not in components
)
def _add_to_list_line(line: str, component: str) -> tuple[str, int]:
code = _code(line)
entry = _LIST_LINE.match(code)
if not entry or not _wants([entry.group(3)], entry.group(5).split(), component):
return line, 0
stripped = code.rstrip()
return f"{stripped} {component}{code[len(stripped) :]}{line[len(code) :]}", 1
def _add_to_deb822(lines: list[str], component: str) -> int:
changed = 0
for paragraph in _paragraphs(lines):
components = paragraph.fields.get("components")
if not paragraph.enabled or components is None:
continue
if not _wants(paragraph.value("uris").split(), components.value.split(), component):
continue
last = components.lines[-1]
lines[last] = f"{lines[last].rstrip()} {component}"
changed += 1
return changed
def add_component(text: str, component: str, *, deb822: bool) -> tuple[str, int]:
"""*text*, an apt source file, with *component* on each of Debian's own sources; and how many.
Only enabled sources (not a commented-out line, not a paragraph with ``Enabled: no``)
whose URIs are all under ``debian.org`` and that have ``main``. A source that has it
already, and every other vendor's, stays as it is; so do comments.
"""
lines = text.split("\n")
if deb822:
changed = _add_to_deb822(lines, component)
else:
changed = 0
for index, line in enumerate(lines):
lines[index], count = _add_to_list_line(line, component)
changed += count
return "\n".join(lines), changed
class CpuMicrocodeFixDict(FixResultDict):
"""What ``install_cpu_microcode`` did: the fix, its package, whether apt's sources changed."""
package: str | None
sources_changed: bool
@dataclass
class _Plan:
package: str | None = None
debian: bool = False
installed: bool = False
sources_changed: bool = False
class CpuMicrocodeMixin:
"""Installs the CPU vendor's microcode on a host that runs on its own CPU.
Three steps: ``read`` (the hardening reading: not a guest, and a package for this
distribution and CPU), ``sources`` (on Debian, its archive's firmware component) and
``install``. Nothing is installed or written when a step before fails. The microcode
loads at the next boot; restarting is the caller's.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def get_hardening(self) -> Any: ...
def get_packages(self) -> Any: ...
def ensure_package(self, name: str) -> FixResultDict: ...
def get_apt_source_releases(self) -> AptReleasesDict | None: ...
def _run_apt_command(self, command: str) -> str: ...
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict: ...
def refresh_available_updates(self) -> dict[str, Any]: ...
def install_cpu_microcode(self) -> CpuMicrocodeFixDict:
"""Install the microcode package for the host's CPU and distribution."""
plan = _Plan()
result = run_fix_steps(
[
("read", lambda: self._microcode_read(plan)),
("sources", lambda: self._microcode_sources(plan)),
("install", lambda: self._microcode_install(plan)),
]
)
return {**result, "package": plan.package, "sources_changed": plan.sources_changed}
def _microcode_read(self, plan: _Plan) -> FixStepOutcomeDict:
reading = self.get_hardening()
refused = _refused_guest(reading.get("virtualization"))
if refused:
return {"ok": False, "output": refused}
os_ids = list(reading.get("os_ids") or [])
vendor = reading.get("cpu_vendor")
plan.package = microcode_package(os_ids, vendor)
if plan.package is None:
return {"ok": False, "output": _no_package(os_ids, vendor)}
plan.debian = plan.package in _DEBIAN_PACKAGES and os_ids[:1] == ["debian"]
plan.installed = any(
p.get("name") == plan.package and p.get("installed") for p in self.get_packages()
)
return {"ok": True, "output": f"{vendor} CPU on {' '.join(os_ids)}: {plan.package}"}
def _microcode_sources(self, plan: _Plan) -> FixStepOutcomeDict:
if plan.installed:
return {"ok": True, "output": f"{plan.package} is installed already: nothing to add"}
if not plan.debian:
return {"ok": True, "output": "the distribution's own sources carry it"}
releases = self.get_apt_source_releases()
if releases is None:
return {"ok": False, "output": "not an apt host"}
component = firmware_component(releases["codename"])
files = _files_wanting(releases["sources"], component)
if not files:
return {"ok": True, "output": f"Debian's sources already carry {component}"}
said: list[str] = []
for path in files:
outcome = self._add_component_to(path, component, plan)
if not outcome["ok"]:
return {"ok": False, "output": "\n".join([*said, outcome["output"]])}
said.append(outcome["output"])
if not plan.sources_changed:
return {"ok": True, "output": "\n".join(said)}
loaded = self._reload_package_index()
return {"ok": loaded["ok"], "output": "\n".join([*said, loaded["output"]])}
def _reload_package_index(self) -> FixStepOutcomeDict:
"""Load the package index again, and be done when it returns: the install comes next.
``refresh_available_updates`` by default. A driver whose refresh only starts a task
(Proxmox's ``POST apt/update``) overrides this with one that waits.
"""
refreshed = self.refresh_available_updates()
output = str(refreshed.get("output", "")).strip()
if not refreshed.get("success"):
return {"ok": False, "output": f"apt-get update: {output}"}
return {"ok": True, "output": "package index loaded again"}
def _add_component_to(self, path: str, component: str, plan: _Plan) -> FixStepOutcomeDict:
encoded = "".join(self._run_apt_command(f"base64 {shlex.quote(path)}").split())
text = base64.b64decode(encoded).decode()
new, count = add_component(text, component, deb822=_is_deb822(path))
if not count:
return {"ok": True, "output": f"{path} carries {component} already"}
written = self._write_apt_file(path, new)
if not written["ok"]:
return written
plan.sources_changed = True
return {"ok": True, "output": f"{path}: {component} added"}
def _microcode_install(self, plan: _Plan) -> FixStepOutcomeDict:
if plan.package is None: # pragma: no cover - the read step failed otherwise
return {"ok": False, "output": "no package"}
result = self.ensure_package(plan.package)
if not result["steps"]:
return {"ok": False, "output": result["output"] or f"{plan.package} not installed"}
step = result["steps"][-1]
if not step["ok"]:
return {"ok": False, "output": step["output"]}
return {"ok": True, "output": f"{step['output']}; the microcode loads at the next boot"}
def _refused_guest(virtualization: str | None) -> str | None:
"""Why a host with this ``virtualization`` takes no microcode; None on bare metal."""
if virtualization is None:
return "could not tell whether the host is virtual"
if virtualization != "none":
return f"runs virtualized ({virtualization}): a guest loads no microcode: its host does"
return None
def _no_package(os_ids: Sequence[str], vendor: str | None) -> str:
if not vendor:
return "the CPU vendor was not read"
if microcode_package(os_ids, _INTEL) is None:
return f"no microcode package is known for {' '.join(os_ids) or 'this distribution'}"
return f"no microcode package is known for a {vendor} CPU"
def _files_wanting(sources: Sequence[AptSourceDict], component: str) -> list[str]:
"""The source files with a source of Debian's archive that lacks *component*, in order."""
files: list[str] = []
for source in sources:
wants = _wants([source["uri"]], source["components"], component)
if wants and source["file"] not in files:
files.append(source["file"])
return files
__all__ = [
"CpuMicrocodeFixDict",
"CpuMicrocodeMixin",
"add_component",
"firmware_component",
"microcode_package",
]
+61
View File
@@ -0,0 +1,61 @@
"""The leases a DHCP server handed out, wherever it runs.
Its own mixin, apart from :class:`~napalm_device_types.dhcp.DhcpServerMixin`:
an access point or a router often serves leases from a server nobody manages
through the driver, and reading them needs nothing of the reservations and
subnets that mixin declares. A driver that manages a DHCP server and reads its
leases mixes in both.
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder. Only a driver
that reads leases defines ``get_dhcp_leases``, so
``callable(getattr(driver, "get_dhcp_leases", None))`` tells a caller whether to ask.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from typing_extensions import TypedDict
class DhcpLeaseDict(TypedDict):
"""A lease a DHCP server handed out (``DhcpLeasesMixin.get_dhcp_leases``).
``mac`` lower-case and colon-separated; ``hostname`` "" when the client sent
none; ``lease_end`` the Unix time the lease ends, 0 when it does not end or is
not known; ``state`` the server's own word for it ("" when it has none).
"""
mac: str
ip: str
hostname: str
lease_end: int
state: str
class DhcpLeasesMixin:
if TYPE_CHECKING:
def get_dhcp_leases(self) -> list[DhcpLeaseDict]:
"""
Returns the leases the device's DHCP server holds now.
A device that serves no leases -- an access point whose DHCP server is
off -- returns ``[]``: that is an answer, and it says there are none.
:raises Exception: when the leases cannot be read. An empty list for
"could not read" would make a broken server look like an idle one.
Example::
[
{
"mac": "aa:bb:cc:dd:ee:01",
"ip": "192.168.1.42",
"hostname": "laptop",
"lease_end": 1764432000,
"state": "active",
}
]
"""
...
+41 -1
View File
@@ -1,6 +1,6 @@
"""How a Linux host is hardened, as its kernel and its own tools say it (NetOrk/netork#2706).
Five things, each read where the host itself keeps it:
Six things, each read where the host itself keeps it:
- **The security modules in force:** ``/sys/kernel/security/lsm`` lists the active
LSMs. SELinux's mode comes from ``getenforce`` (or ``/sys/fs/selinux/enforce``), the
@@ -17,6 +17,11 @@ Five things, each read where the host itself keeps it:
- **The distribution's IDs** (``ID`` and ``ID_LIKE`` from ``/etc/os-release``), so a
consumer can tell an Enterprise Linux host, where SELinux is the distribution's own
module, from one that merely has it installed.
- **Whether the host runs on its own hardware, and whose CPU it is:**
``systemd-detect-virt`` (``none`` on bare metal, else the hypervisor or container
engine), else the ``hypervisor`` flag a hypervisor sets in its guests' ``/proc/cpuinfo``;
and the CPU's ``vendor_id``. A CPU vulnerability on a guest is its host's to close: a
guest loads no microcode and sees only the CPU features its hypervisor passes through.
One fixed command, read-only, the same on every Linux host, so it and its parse live
here once and a driver only carries the command across. **Not read is None, never
@@ -62,6 +67,11 @@ HARDENING_COMMAND = (
f"grep -H . {_VULNERABILITIES}/* 2>/dev/null; fi; "
"if command -v aa-status >/dev/null 2>&1; then echo '[aa_status]'; "
"aa-status --json 2>/dev/null; echo; fi; "
"if command -v systemd-detect-virt >/dev/null 2>&1; then echo '[virtualization]'; "
"systemd-detect-virt 2>/dev/null; fi; "
"if [ -r /proc/cpuinfo ]; then echo '[cpu_hypervisor]'; "
"grep -c -m1 -E '^flags.*[[:space:]]hypervisor([[:space:]]|$)' /proc/cpuinfo; "
"echo '[cpu_vendor]'; grep -m1 '^vendor_id' /proc/cpuinfo; fi; "
"printf '%s%s\\n' HARDENING_ END"
)
@@ -102,6 +112,11 @@ class HardeningDict(TypedDict):
mitigations: str | None # mitigations= on the command line; "auto" when not given
nosmt: bool | None # SMT switched off by the command line
os_ids: list[str] | None # ID, then ID_LIKE, from /etc/os-release, lowercased
#: ``systemd-detect-virt``, lowercased: "none" on the host's own hardware, else the
#: hypervisor or container engine ("kvm", "vmware", "lxc", ...); "vm" where only the
#: ``hypervisor`` CPU flag tells it.
virtualization: str | None
cpu_vendor: str | None # the first vendor_id of /proc/cpuinfo: "GenuineIntel", ...
def cpu_vulnerability_state(text: str) -> CpuVulnerabilityState:
@@ -258,6 +273,24 @@ def _os_ids(sections: dict[str, list[str]]) -> list[str] | None:
return ids
def _virtualization(sections: dict[str, list[str]]) -> str | None:
"""``systemd-detect-virt``'s word first, else the ``hypervisor`` CPU flag."""
detected = _first(sections, "virtualization")
if detected:
return detected.lower()
flag = _first(sections, "cpu_hypervisor")
if flag is None or not flag.isdigit():
return None
return "vm" if int(flag) else "none"
def _cpu_vendor(sections: dict[str, list[str]]) -> str | None:
line = _first(sections, "cpu_vendor")
if line is None:
return None
return line.partition(":")[2].strip() or None
def parse_hardening(output: str) -> HardeningDict:
"""Parse what :data:`HARDENING_COMMAND` printed.
@@ -279,6 +312,8 @@ def parse_hardening(output: str) -> HardeningDict:
"mitigations": mitigations,
"nosmt": nosmt,
"os_ids": _os_ids(sections),
"virtualization": _virtualization(sections),
"cpu_vendor": _cpu_vendor(sections),
}
@@ -311,6 +346,9 @@ class HardeningMixin:
* cpu_vulnerabilities (dict or None) - name -> the kernel's text
* cmdline (str or None), mitigations (str or None), nosmt (bool or None)
* os_ids (list or None) - ``ID`` and ``ID_LIKE`` from ``/etc/os-release``
* virtualization (str or None) - ``systemd-detect-virt``: "none" on the host's
own hardware; "vm" where only the ``hypervisor`` CPU flag tells it
* cpu_vendor (str or None) - ``vendor_id`` of ``/proc/cpuinfo``
``None`` means not read. Read as root first, for AppArmor's profiles; where root
is refused, as the login user, without them.
@@ -329,6 +367,8 @@ class HardeningMixin:
"mitigations": "auto",
"nosmt": False,
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
"virtualization": "none",
"cpu_vendor": "GenuineIntel",
}
:raises ValueError: if neither reading carried an intact report.
+4 -1
View File
@@ -32,9 +32,12 @@ from napalm_device_types.models import (
WirelessClientDict,
)
from napalm_device_types.nat_vpn import NatVpnMixin
from napalm_device_types.wireless_writes import WirelessWritesMixin
class ResidentialGatewayDriver(NatVpnMixin, HealthMetricsMixin, DhcpServerMixin, DeviceTypeDriver):
class ResidentialGatewayDriver(
WirelessWritesMixin, NatVpnMixin, HealthMetricsMixin, DhcpServerMixin, DeviceTypeDriver
):
"""
Abstract intermediate driver for residential gateways (router + firewall + AP).
+11 -1
View File
@@ -12,6 +12,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_extensions import TypedDict
@@ -182,7 +183,12 @@ class UpdateMixin:
"""
...
def apply_updates(self, packages: list[str]) -> ApplyUpdatesResultDict:
def apply_updates(
self,
packages: list[str],
*,
log: Callable[[str], None] | None = None,
) -> ApplyUpdatesResultDict:
"""
Upgrades the given packages to the newest available version.
@@ -193,6 +199,10 @@ class UpdateMixin:
:param packages: List of package names to upgrade. Each name must
match ``^[a-zA-Z0-9_\\-\\+\\.]+$``; a :exc:`ValueError` is raised
for any name that does not conform.
:param log: Receives each line of the package manager's output as the
host prints it, so a caller can follow a long run. A driver that
cannot stream does not call it and returns the output at the end,
as without it; ``output`` holds the whole output either way.
:returns: A dict with:
* success (bool) – ``True`` if the package manager exited without error
+59
View File
@@ -0,0 +1,59 @@
"""Writes to a device's SSIDs and radios: what an access point or a gateway's
built-in Wi-Fi takes.
Declared under ``if TYPE_CHECKING``: a contract, not a placeholder. Only a driver
that can write them defines these, so ``callable(getattr(driver, name, None))``
tells a caller whether to offer the write.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from napalm_device_types.access_point_models import SsidConfigDict
#: The channel that lets a radio choose its own (``set_radio_channels``).
AUTO_CHANNEL = 0
class WirelessWritesMixin:
if TYPE_CHECKING:
def push_ssid_config(self, ssid: str, config: SsidConfigDict) -> None:
"""
Writes *config* to every interface that serves the SSID *ssid*.
Partial: a key *config* leaves out is left as the device has it, and an
empty *config* writes nothing. The values are written as given; whether
a write is safe -- a keyed mode only together with its key -- is the
caller's decision.
:raises ValueError: for a value the device cannot take, before anything
is sent.
:raises Exception: when no interface serves *ssid*, or the device
refuses a step. What was staged before is not applied.
Example::
driver.push_ssid_config("Guest", {"hidden": True, "max_inactivity": 300})
"""
...
def set_radio_channels(self, channels: dict[str, int]) -> None:
"""
Sets each radio of *channels* (radio name -> channel) to its channel.
``AUTO_CHANNEL`` (0) lets the radio choose. Every radio changes in one
go, with one restart of the wireless stack, however many there are:
restarting per radio would take the Wi-Fi down once for each.
:raises ValueError: for a radio name or channel the device cannot take,
before anything is sent.
:raises Exception: when the device refuses a step; then no radio
changes and nothing restarts.
Example::
driver.set_radio_channels({"radio0": 36, "radio1": 0})
"""
...
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-device-types"
version = "4.52.0"
version = "4.54.0"
description = "Abstract device-type base classes for NAPALM drivers"
readme = "README.md"
requires-python = ">=3.12"
+264
View File
@@ -0,0 +1,264 @@
"""The access point's writes and the DHCP lease reader, as declared (NetOrk/netork#695).
netOrk wrote an OpenWrt AP's SSID settings, radio channels, VLAN names and AP
profile as UCI itself, and read leases from no AP at all. Each becomes a declared
method with a vendor-neutral shape; the driver turns it into its device's commands.
"""
from __future__ import annotations
import ast
import inspect
from typing import get_type_hints
import pytest
import napalm_device_types
from napalm_device_types import (
AP_CONFIG_PARTS,
AP_CONFIG_SSID_ATTRIBUTES,
AUTO_CHANNEL,
AccessPointDriver,
ApConfigDict,
ApConfigMixin,
ApConfigResultDict,
ApSsidConfigDict,
DhcpLeaseDict,
DhcpLeasesMixin,
ResidentialGatewayDriver,
SsidConfigDict,
WirelessWritesMixin,
access_point,
ap_config,
ap_config_ssid_part,
ap_config_vlan_part,
dhcp_leases,
is_ap_config_part,
wireless_writes,
)
def _declared(module) -> dict[str, ast.FunctionDef]:
"""Every function the module's source defines, by name (declarations included)."""
return {
node.name: node
for node in ast.walk(ast.parse(inspect.getsource(module)))
if isinstance(node, ast.FunctionDef)
}
def _args(node: ast.FunctionDef) -> tuple[list[str], list[str]]:
return [a.arg for a in node.args.args], [a.arg for a in node.args.kwonlyargs]
class TestShapes:
def test_a_lease_is_the_five_fields_every_server_reports(self):
assert set(get_type_hints(DhcpLeaseDict)) == {
"mac",
"ip",
"hostname",
"lease_end",
"state",
}
def test_an_ssid_push_is_a_partial_dict(self):
assert set(get_type_hints(SsidConfigDict)) == {
"encryption",
"key",
"hidden",
"enabled",
"disassoc_low_ack",
"max_inactivity",
}
assert SsidConfigDict.__required_keys__ == frozenset()
def test_the_ap_configuration_is_desired_state_in_neutral_terms(self):
assert set(get_type_hints(ApConfigDict)) == {
"country_code",
"htmode_5g",
"htmode_2g",
"syslog_host",
"syslog_port",
"web_ui",
"ssh_port",
"ssh_password_auth",
"management_vlan_id",
"management_untagged",
"bridge_stp",
"mobility_domain",
"ft_over_ds",
"ssids",
}
assert ApConfigDict.__required_keys__ == frozenset()
def test_an_ssid_of_the_configuration_is_named(self):
assert ApSsidConfigDict.__required_keys__ == frozenset({"name"})
assert set(get_type_hints(ApSsidConfigDict)) == {
"name",
"vlan_id",
"bands",
"encryption",
"key",
"hidden",
"enabled",
"client_isolation",
"max_clients",
"disassoc_low_ack",
"max_inactivity",
"acl_mode",
"acl_macs",
"fast_transition",
}
def test_an_apply_says_what_it_wrote_and_what_it_could_not(self):
assert set(get_type_hints(ApConfigResultDict)) == {
"applied",
"skipped",
"restarts",
"commands",
"log",
}
class TestDeclarations:
def test_the_lease_reader_has_its_own_mixin(self):
"""An access point serves leases without being a DHCP server to manage."""
assert _args(_declared(dhcp_leases)["get_dhcp_leases"]) == (["self"], [])
assert not hasattr(DhcpLeasesMixin, "get_dhcp_leases")
assert not issubclass(AccessPointDriver, DhcpLeasesMixin)
def test_ssid_and_channel_writes(self):
declared = _declared(wireless_writes)
assert _args(declared["push_ssid_config"]) == (["self", "ssid", "config"], [])
assert _args(declared["set_radio_channels"]) == (["self", "channels"], [])
for name in ("push_ssid_config", "set_radio_channels"):
assert not hasattr(WirelessWritesMixin, name), name
def test_the_ap_configuration_apply(self):
assert _args(_declared(ap_config)["apply_ap_config"]) == (
["self", "config", "parts"],
[],
)
assert not hasattr(ApConfigMixin, "apply_ap_config")
def test_the_vlan_name_is_a_narrow_write_of_the_access_point(self):
assert _args(_declared(access_point)["set_vlan_name"]) == (
["self", "vlan_id", "name"],
[],
)
assert not hasattr(AccessPointDriver, "set_vlan_name")
assert not hasattr(AccessPointDriver, "set_vlan")
@pytest.mark.parametrize(
("role", "mixin"),
[
(AccessPointDriver, WirelessWritesMixin),
(AccessPointDriver, ApConfigMixin),
(ResidentialGatewayDriver, WirelessWritesMixin),
],
)
def test_the_roles_that_carry_them(self, role, mixin):
assert issubclass(role, mixin)
def test_exported(self):
for name in (
"DhcpLeaseDict",
"DhcpLeasesMixin",
"SsidConfigDict",
"WirelessWritesMixin",
"AUTO_CHANNEL",
"ApConfigDict",
"ApSsidConfigDict",
"ApConfigResultDict",
"ApConfigMixin",
"AP_CONFIG_PARTS",
"AP_CONFIG_SSID_ATTRIBUTES",
"ap_config_ssid_part",
"ap_config_vlan_part",
"is_ap_config_part",
):
assert name in napalm_device_types.__all__, name
def test_the_shapes_live_beside_their_declarations(self):
from napalm_device_types import access_point_models, dhcp_leases
assert dhcp_leases.DhcpLeaseDict is DhcpLeaseDict
assert access_point_models.SsidConfigDict is SsidConfigDict
assert access_point_models.ApConfigDict is ApConfigDict
class TestParts:
def test_auto_is_channel_zero(self):
assert AUTO_CHANNEL == 0
def test_the_fixed_parts(self):
assert {
"radio/country",
"radio/5g_htmode",
"radio/2g_htmode",
"system/syslog",
"system/web_ui",
"system/ssh_port",
"system/password_auth",
"network/bridge",
"network/bridge_stp",
} == AP_CONFIG_PARTS
def test_an_ssid_part_is_split_at_its_last_slash(self):
"""An SSID may hold a slash; the attribute never does."""
assert ap_config_ssid_part("wireless/Home/hidden") == ("Home", "hidden")
assert ap_config_ssid_part("wireless/a/b/encryption") == ("a/b", "encryption")
@pytest.mark.parametrize(
"part",
[
"wireless/Home/colour",
"wireless/hidden",
"wireless//hidden",
"network/vlan/10",
"radio/country",
],
)
def test_no_ssid_part(self, part):
assert ap_config_ssid_part(part) is None
def test_a_vlan_part(self):
assert ap_config_vlan_part("network/vlan/10") == 10
@pytest.mark.parametrize(
"part", ["network/vlan/", "network/vlan/x", "network/vlan/0", "network/vlan/4095"]
)
def test_no_vlan_part(self, part):
assert ap_config_vlan_part(part) is None
@pytest.mark.parametrize(
("part", "known"),
[
("radio/country", True),
("network/vlan/20", True),
("wireless/Guest/acl", True),
("wireless/Guest/passphrase", True),
("system/luci", False),
("wireless/Guest/extra/x", False),
("", False),
],
)
def test_known_parts(self, part, known):
assert is_ap_config_part(part) is known
def test_every_attribute_an_ssid_part_names(self):
assert {
"missing",
"vlan",
"bands",
"encryption",
"passphrase",
"hidden",
"enabled",
"client_isolation",
"max_clients",
"disassoc_low_ack",
"max_inactivity",
"acl",
"ft",
} == AP_CONFIG_SSID_ATTRIBUTES
+476
View File
@@ -0,0 +1,476 @@
"""install_cpu_microcode: the CPU vendor's microcode on a host that runs on its own CPU.
A CPU vulnerability the kernel reports ``Vulnerable: ... no microcode`` closes with the
microcode the CPU's vendor ships, which the distribution packages and the initramfs
loads at the next boot (NetOrk/netork#2706). A guest loads none: its host does. Debian
keeps the packages in ``non-free-firmware`` (``non-free`` up to bullseye), a component
a Proxmox VE install does not enable; the fix adds it to Debian's own sources.
"""
from __future__ import annotations
import base64
import shlex
from typing import Any
import pytest
from napalm_device_types import OSDriver
from napalm_device_types.apt_releases import AptReleaseMixin
from napalm_device_types.cpu_microcode import (
CpuMicrocodeMixin,
add_component,
firmware_component,
microcode_package,
)
from napalm_device_types.fixes import EnsurePackageMixin
class TestThePackage:
@pytest.mark.parametrize(
"os_ids, vendor, package",
[
(["debian"], "GenuineIntel", "intel-microcode"),
(["debian"], "AuthenticAMD", "amd64-microcode"),
(["ubuntu", "debian"], "GenuineIntel", "intel-microcode"),
(["linuxmint", "ubuntu", "debian"], "AuthenticAMD", "amd64-microcode"),
(["almalinux", "rhel", "centos", "fedora"], "GenuineIntel", "microcode_ctl"),
(["rocky", "rhel", "centos", "fedora"], "AuthenticAMD", "linux-firmware"),
(["fedora"], "GenuineIntel", "microcode_ctl"),
(["opensuse-leap", "suse", "opensuse"], "GenuineIntel", "ucode-intel"),
(["opensuse-tumbleweed"], "AuthenticAMD", "ucode-amd"),
(["sles"], "GenuineIntel", "ucode-intel"),
],
)
def test_by_distribution_and_vendor(self, os_ids, vendor, package):
assert microcode_package(os_ids, vendor) == package
@pytest.mark.parametrize(
"os_ids, vendor",
[
(["arch"], "GenuineIntel"), # a boot loader entry loads it: not ours to write
(["alpine"], "AuthenticAMD"),
(["qts"], "GenuineIntel"),
(["debian"], "HygonGenuine"),
(["debian"], None),
(None, "GenuineIntel"),
([], "GenuineIntel"),
],
)
def test_none_where_no_package_loads_it(self, os_ids, vendor):
assert microcode_package(os_ids, vendor) is None
class TestTheComponent:
@pytest.mark.parametrize(
"codename, component",
[
("jessie", "non-free"),
("stretch", "non-free"),
("buster", "non-free"),
("bullseye", "non-free"),
("bookworm", "non-free-firmware"),
("trixie", "non-free-firmware"),
("forky", "non-free-firmware"),
],
)
def test_non_free_firmware_from_bookworm_on(self, codename, component):
assert firmware_component(codename) == component
PVE_DEB822 = """\
Types: deb
URIs: http://deb.debian.org/debian/
Suites: trixie trixie-updates
Components: main contrib
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
# The security updates.
Types: deb
URIs: http://security.debian.org/debian-security/
Suites: trixie-security
Components: main
contrib
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
Types: deb
URIs: http://deb.debian.org/debian/
Suites: trixie-backports
Components: main
Enabled: no
"""
class TestAddComponentDeb822:
def test_every_enabled_debian_paragraph_gets_it(self):
new, count = add_component(PVE_DEB822, "non-free-firmware", deb822=True)
assert count == 2
assert "Components: main contrib non-free-firmware\n" in new
assert "Components: main\n contrib non-free-firmware\n" in new
# The disabled paragraph stays as it was.
assert new.rstrip().endswith("Components: main\nEnabled: no")
assert "# The security updates." in new
def test_already_there_is_left(self):
text = "Types: deb\nURIs: https://deb.debian.org/debian\nSuites: bookworm\n" + (
"Components: main non-free-firmware\n"
)
assert add_component(text, "non-free-firmware", deb822=True) == (text, 0)
@pytest.mark.parametrize(
"uri",
[
"http://download.proxmox.com/debian/pve",
"https://download.docker.com/linux/debian",
"http://debian.example.org/debian",
"http://notdebian.org/debian",
],
)
def test_a_source_that_is_not_debians_is_left(self, uri):
text = f"Types: deb\nURIs: {uri}\nSuites: trixie\nComponents: main\n"
assert add_component(text, "non-free-firmware", deb822=True) == (text, 0)
def test_a_mirror_of_debian_org_counts(self):
text = (
"Types: deb\nURIs: http://ftp.de.debian.org/debian\nSuites: trixie\nComponents: main\n"
)
new, count = add_component(text, "non-free-firmware", deb822=True)
assert count == 1
assert "Components: main non-free-firmware" in new
def test_a_paragraph_without_main_is_left(self):
"""``pve-no-subscription`` is not ``main``; nor is a third-party ``stable``."""
text = (
"Types: deb\nURIs: http://deb.debian.org/debian\nSuites: trixie\nComponents: contrib\n"
)
assert add_component(text, "non-free-firmware", deb822=True)[1] == 0
def test_a_paragraph_with_another_vendors_uri_beside_debians_is_left(self):
text = (
"Types: deb\nURIs: http://deb.debian.org/debian http://mirror.example.com/debian\n"
"Suites: trixie\nComponents: main\n"
)
assert add_component(text, "non-free-firmware", deb822=True)[1] == 0
class TestAddComponentList:
def test_a_debian_line_gets_it_and_its_comment_stays(self):
text = (
"deb http://ftp.debian.org/debian bookworm main contrib # the archive\n"
"deb [arch=amd64 signed-by=/k.gpg] http://security.debian.org bookworm-security main\n"
"# deb http://deb.debian.org/debian bookworm-backports main\n"
"deb http://download.proxmox.com/debian/pve bookworm pve-no-subscription\n"
"deb http://deb.debian.org/debian bookworm-updates main non-free-firmware\n"
)
new, count = add_component(text, "non-free-firmware", deb822=False)
assert count == 2
assert new.splitlines() == [
"deb http://ftp.debian.org/debian bookworm main contrib non-free-firmware # the archive",
"deb [arch=amd64 signed-by=/k.gpg] http://security.debian.org bookworm-security main "
"non-free-firmware",
"# deb http://deb.debian.org/debian bookworm-backports main",
"deb http://download.proxmox.com/debian/pve bookworm pve-no-subscription",
"deb http://deb.debian.org/debian bookworm-updates main non-free-firmware",
]
def test_bullseye_takes_non_free(self):
text = "deb http://deb.debian.org/debian bullseye main\n"
assert add_component(text, "non-free", deb822=False) == (
"deb http://deb.debian.org/debian bullseye main non-free\n",
1,
)
def test_a_uri_that_does_not_parse_is_not_debians(self):
text = "deb http://[::1/debian trixie main\n"
assert add_component(text, "non-free-firmware", deb822=False)[1] == 0
def test_deb_src_too(self):
text = "deb-src http://deb.debian.org/debian trixie main\n"
assert add_component(text, "non-free-firmware", deb822=False)[1] == 1
def _hardening(**overrides: Any) -> dict[str, Any]:
reading: dict[str, Any] = {
"os_ids": ["debian"],
"virtualization": "none",
"cpu_vendor": "GenuineIntel",
}
reading.update(overrides)
return reading
_SOURCES = "/etc/apt/sources.list.d/debian.sources"
_PVE_LIST = "/etc/apt/sources.list.d/pve-no-subscription.list"
_PVE_LIST_TEXT = "deb http://download.proxmox.com/debian/pve trixie pve-no-subscription\n"
class _Host(OSDriver, CpuMicrocodeMixin, EnsurePackageMixin, AptReleaseMixin):
"""A Debian host with apt: its files, its packages, and what it was asked."""
def __init__(self, hardening: dict[str, Any], *, installed: tuple[str, ...] = ()) -> None:
self.hardening = hardening
self.installed = list(installed)
self.files = {_SOURCES: PVE_DEB822, _PVE_LIST: _PVE_LIST_TEXT}
self.written: dict[str, str] = {}
self.refreshed = 0
self.os_release = "ID=debian\nVERSION_CODENAME=trixie\n"
def get_hardening(self) -> Any:
return self.hardening
def get_packages(self) -> Any:
return [{"name": n, "installed": True} for n in self.installed]
def install_package(self, name: str, version: str = "") -> None:
self.installed.append(name)
def refresh_available_updates(self) -> dict[str, Any]:
self.refreshed += 1
return {"success": True, "output": "Hit:1 http://deb.debian.org/debian trixie InRelease"}
def _run_apt_command(self, command: str) -> str:
if command.startswith("base64 "):
path = shlex.split(command)[1]
return base64.b64encode(self.files[path].encode()).decode()
body = "".join(
f"@@file {path}\n" + "".join(f"|{line}\n" for line in text.split("\n"))
for path, text in self.files.items()
)
os_release = "".join(f"|{line}\n" for line in self.os_release.splitlines())
return f"ARELEASE_BEGIN\n@@os\n{os_release}{body}ARELEASE_END\n"
def _write_apt_file(self, path: str, content: str) -> Any:
self.files[path] = content
self.written[path] = content
return {"ok": True, "output": f"wrote {path}"}
class TestTheFix:
def test_proxmox_ve_without_the_component_gets_it_then_the_package(self):
host = _Host(_hardening())
result = host.install_cpu_microcode()
assert result["success"] is True
assert [s["step"] for s in result["steps"]] == ["read", "sources", "install"]
assert result["package"] == "intel-microcode"
assert result["sources_changed"] is True
assert list(host.written) == [_SOURCES]
assert "Components: main contrib non-free-firmware" in host.files[_SOURCES]
assert host.files[_PVE_LIST] == _PVE_LIST_TEXT
assert host.refreshed == 1
assert host.installed == ["intel-microcode"]
assert result["output"].splitlines()[-1].endswith("loads at the next boot")
def test_sources_that_carry_it_are_not_written(self):
host = _Host(_hardening())
host.files[_SOURCES] = add_component(PVE_DEB822, "non-free-firmware", deb822=True)[0]
result = host.install_cpu_microcode()
assert result["success"] is True
assert result["sources_changed"] is False
assert host.written == {} and host.refreshed == 0
assert "already carry non-free-firmware" in result["steps"][1]["output"]
def test_installed_already_touches_nothing(self):
host = _Host(_hardening(), installed=("intel-microcode",))
result = host.install_cpu_microcode()
assert result["success"] is True
assert host.written == {} and host.refreshed == 0
assert host.installed == ["intel-microcode"]
assert "already installed" in result["steps"][2]["output"]
def test_bullseye_adds_non_free(self):
host = _Host(_hardening(cpu_vendor="AuthenticAMD"))
host.os_release = "ID=debian\nVERSION_CODENAME=bullseye\n"
host.files = {"/etc/apt/sources.list": "deb http://deb.debian.org/debian bullseye main\n"}
result = host.install_cpu_microcode()
assert result["success"] is True
assert result["package"] == "amd64-microcode"
assert host.files["/etc/apt/sources.list"] == (
"deb http://deb.debian.org/debian bullseye main non-free\n"
)
def test_ubuntu_needs_no_sources(self):
host = _Host(_hardening(os_ids=["ubuntu", "debian"]))
result = host.install_cpu_microcode()
assert result["success"] is True
assert host.written == {} and host.refreshed == 0
assert host.installed == ["intel-microcode"]
def test_enterprise_linux_installs_from_its_own_sources(self):
host = _Host(_hardening(os_ids=["almalinux", "rhel", "centos", "fedora"]))
result = host.install_cpu_microcode()
assert result["success"] is True
assert host.installed == ["microcode_ctl"]
assert host.written == {}
@pytest.mark.parametrize("virtualization", ["kvm", "vm", "lxc"])
def test_a_guest_is_refused(self, virtualization):
host = _Host(_hardening(virtualization=virtualization))
result = host.install_cpu_microcode()
assert result["success"] is False
assert [s["step"] for s in result["steps"]] == ["read"]
assert "its host does" in result["output"]
assert host.installed == [] and host.written == {}
def test_unknown_virtualization_is_refused(self):
result = _Host(_hardening(virtualization=None)).install_cpu_microcode()
assert result["success"] is False
assert "could not tell whether the host is virtual" in result["output"]
@pytest.mark.parametrize(
"overrides, said",
[
({"cpu_vendor": None}, "CPU vendor"),
({"cpu_vendor": "HygonGenuine"}, "HygonGenuine"),
({"os_ids": ["arch"]}, "arch"),
],
)
def test_no_package_says_why(self, overrides, said):
result = _Host(_hardening(**overrides)).install_cpu_microcode()
assert result["success"] is False
assert result["package"] is None
assert said in result["output"]
def test_a_failed_index_refresh_fails_the_fix(self):
host = _Host(_hardening())
host.refresh_available_updates = lambda: {"success": False, "output": "E: 404"} # type: ignore[method-assign]
result = host.install_cpu_microcode()
assert result["success"] is False
assert [s["step"] for s in result["steps"]] == ["read", "sources"]
assert "E: 404" in result["output"]
assert host.installed == []
def test_a_driver_may_load_the_index_its_own_way(self):
"""Proxmox's refresh only starts a task: its driver waits for apt itself."""
host = _Host(_hardening())
ran: list[str] = []
host._reload_package_index = lambda: (
ran.append("apt-get update")
or { # type: ignore[method-assign]
"ok": True,
"output": "apt-get update done",
}
)
result = host.install_cpu_microcode()
assert result["success"] is True
assert ran == ["apt-get update"] and host.refreshed == 0
assert "apt-get update done" in result["steps"][1]["output"]
def test_a_failed_write_fails_the_fix(self):
host = _Host(_hardening())
host._write_apt_file = lambda path, content: {"ok": False, "output": "denied"} # type: ignore[method-assign]
result = host.install_cpu_microcode()
assert result["success"] is False
assert "denied" in result["output"]
assert host.installed == []
def test_a_reading_that_fails_fails_the_fix(self):
host = _Host(_hardening())
def broken() -> Any:
raise ValueError("no intact hardening report in the output")
host.get_hardening = broken # type: ignore[method-assign]
result = host.install_cpu_microcode()
assert result["success"] is False
assert "no intact hardening report" in result["output"]
def test_not_an_apt_host_fails_the_sources(self):
host = _Host(_hardening())
host.get_apt_source_releases = lambda: None # type: ignore[method-assign]
result = host.install_cpu_microcode()
assert result["success"] is False
assert "not an apt host" in result["output"]
def test_a_listed_source_the_rewrite_leaves_writes_nothing(self):
"""A paragraph that names Debian's archive beside another vendor's mirror: apt
lists the Debian URI, the rewrite leaves the paragraph alone."""
host = _Host(_hardening())
host.files = {
_SOURCES: "Types: deb\nURIs: http://deb.debian.org/debian http://m.example.com/d\n"
"Suites: trixie\nComponents: main\n"
}
result = host.install_cpu_microcode()
assert result["success"] is True
assert result["sources_changed"] is False
assert host.written == {} and host.refreshed == 0
assert "carries non-free-firmware already" in result["steps"][1]["output"]
def test_a_failed_install_fails_the_fix(self):
host = _Host(_hardening(os_ids=["ubuntu", "debian"]))
def refuse(name: str, version: str = "") -> Any:
raise RuntimeError("E: Unable to locate package intel-microcode")
host.install_package = refuse # type: ignore[method-assign]
result = host.install_cpu_microcode()
assert result["success"] is False
assert "Unable to locate package" in result["steps"][-1]["output"]
def test_an_ensure_package_without_steps_fails(self):
host = _Host(_hardening(os_ids=["ubuntu", "debian"]))
host.ensure_package = lambda name: {"success": False, "steps": [], "output": ""} # type: ignore[method-assign]
result = host.install_cpu_microcode()
assert result["success"] is False
assert "intel-microcode not installed" in result["output"]
def test_not_on_any_role_base(self):
from napalm_device_types import DeviceTypeDriver
assert not hasattr(DeviceTypeDriver, "install_cpu_microcode")
def test_exported_from_the_package():
import napalm_device_types as ndt
for name in (
"CpuMicrocodeMixin",
"CpuMicrocodeFixDict",
"microcode_package",
"firmware_component",
"add_component",
):
assert hasattr(ndt, name), name
+45
View File
@@ -43,6 +43,9 @@ ALMA_9 = [
"BHI: Not affected\n"
"/sys/devices/system/cpu/vulnerabilities/mmio_stale_data:Unknown: No mitigations",
),
("virtualization", "kvm"),
("cpu_hypervisor", "1"),
("cpu_vendor", "vendor_id\t: AuthenticAMD"),
]
AA_STATUS = {
@@ -124,6 +127,8 @@ class TestTheFixtures:
"mitigations": "auto",
"nosmt": False,
"os_ids": ["almalinux", "rhel", "centos", "fedora"],
"virtualization": "kvm",
"cpu_vendor": "AuthenticAMD",
}
def test_ubuntu_24_04_apparmor_with_its_profiles(self):
@@ -170,6 +175,8 @@ class TestNotReadIsNone:
"mitigations": None,
"nosmt": None,
"os_ids": None,
"virtualization": None,
"cpu_vendor": None,
}
def test_an_empty_vulnerabilities_directory_is_read_and_empty(self):
@@ -303,6 +310,43 @@ class TestCommandLine:
assert (reading["mitigations"], reading["nosmt"]) == (mitigations, nosmt)
class TestVirtualization:
"""Whether the host runs on its own hardware: ``systemd-detect-virt`` where it is
installed, else the ``hypervisor`` CPU flag a hypervisor sets for its guests."""
@pytest.mark.parametrize(
"sections, virtualization",
[
([("virtualization", "none"), ("cpu_hypervisor", "0")], "none"),
([("virtualization", "kvm"), ("cpu_hypervisor", "1")], "kvm"),
([("virtualization", "lxc"), ("cpu_hypervisor", "0")], "lxc"),
([("virtualization", "VMware")], "vmware"),
([("cpu_hypervisor", "1")], "vm"),
([("cpu_hypervisor", "0")], "none"),
([("virtualization", ""), ("cpu_hypervisor", "1")], "vm"),
([("cpu_hypervisor", "nonsense")], None),
([], None),
],
)
def test_detect_virt_first_then_the_cpu_flag(self, sections, virtualization):
assert parse_hardening(_wire(sections))["virtualization"] == virtualization
@pytest.mark.parametrize(
"line, vendor",
[
("vendor_id\t: GenuineIntel", "GenuineIntel"),
("vendor_id : AuthenticAMD", "AuthenticAMD"),
("vendor_id\t:", None),
],
)
def test_the_cpu_vendor(self, line, vendor):
assert parse_hardening(_wire([("cpu_vendor", line)]))["cpu_vendor"] == vendor
def test_no_vendor_line_is_unread(self):
"""An ARM CPU's ``/proc/cpuinfo`` has no ``vendor_id``."""
assert parse_hardening(_wire([("cpu_vendor", "")]))["cpu_vendor"] is None
class TestCryptoPolicy:
def test_a_subpolicy_is_kept(self):
reading = parse_hardening(_wire([("crypto_policy", "LEGACY:AD-SUPPORT"), ("fips", "1")]))
@@ -389,3 +433,4 @@ class TestTheCommand:
assert reading["cmdline"] is not None
assert reading["mitigations"] is not None
assert reading["virtualization"] is not None
+29
View File
@@ -2,6 +2,9 @@
from __future__ import annotations
import ast
import inspect
import napalm_device_types
from napalm_device_types.updates import PackageIndexMissing
@@ -18,3 +21,29 @@ def test_a_missing_index_is_its_own_failure():
def test_it_is_exported_from_the_package():
assert napalm_device_types.PackageIndexMissing is PackageIndexMissing
assert "PackageIndexMissing" in napalm_device_types.__all__
def _declared_apply_updates():
"""``UpdateMixin.apply_updates`` as declared (under ``TYPE_CHECKING``, so read from source)."""
from napalm_device_types import updates
for node in ast.walk(ast.parse(inspect.getsource(updates))):
if isinstance(node, ast.FunctionDef) and node.name == "apply_updates":
return node
raise AssertionError("apply_updates is not declared")
def test_apply_updates_takes_a_log_callback_by_keyword_only():
"""A caller can follow the host's output as it comes (NetOrk/netork#1112); the
positional signature stays as it was, so existing drivers keep conforming."""
node = _declared_apply_updates()
assert [a.arg for a in node.args.args] == ["self", "packages"]
assert [a.arg for a in node.args.kwonlyargs] == ["log"]
(default,) = node.args.kw_defaults
assert isinstance(default, ast.Constant) and default.value is None
assert ast.unparse(node.args.kwonlyargs[0].annotation) == "Callable[[str], None] | None"
def test_apply_updates_still_hides_at_runtime():
assert not hasattr(napalm_device_types.UpdateMixin, "apply_updates")