Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e300c740e | ||
|
|
0598a183df | ||
|
|
b6bb13009f | ||
|
|
59839b4efa | ||
|
|
c0453655b7 | ||
|
|
dc0d6345a8 | ||
|
|
f9088bae3a | ||
|
|
b37672a269 | ||
|
|
63ffc64050 | ||
|
|
b792f6d210 |
No files matched your search
@@ -7,6 +7,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.19.0] - 2026-11-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `install_cpu_microcode()` on both drivers (napalm-device-types' `CpuMicrocodeMixin`, 4.53.0,
|
||||||
|
NetOrk/netork#2838): the CPU vendor's microcode on a node that runs on its own CPU. A Proxmox
|
||||||
|
install enables no `non-free-firmware`, where Debian keeps `intel-microcode` and
|
||||||
|
`amd64-microcode`: it is added to Debian's own sources (never to Proxmox's or another
|
||||||
|
vendor's), the index is loaded with `apt-get update` over the exec path -- waited for, unlike
|
||||||
|
the API's refresh task -- and the package installed. Refused on a node that runs virtualized
|
||||||
|
(a PBS in a VM): its host loads the microcode. The microcode loads at the next boot.
|
||||||
|
- The hardening reading carries `virtualization` and `cpu_vendor` (napalm-device-types 4.53.0).
|
||||||
|
|
||||||
|
## [0.18.0] - 2026-11-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_pve_firewall()` on the PVE driver (NetOrk/netork#2654): the PVE firewall as the operator
|
||||||
|
wrote it, read only -- the datacenter's options, rules, security groups, IP sets and aliases,
|
||||||
|
this node's options and rules, and every guest's on this node with which of its NICs carry
|
||||||
|
`firewall=1`. Each rule keeps PVE's own fields and says where it came from. A part PVE refuses
|
||||||
|
is None, not empty: an unread level is no claim. Nothing is written; pve-firewall rules stay
|
||||||
|
the operator's.
|
||||||
|
- `get_host_firewall()` on the PVE driver (napalm-device-types' `HostFirewallMixin`): what the
|
||||||
|
node has loaded -- proxmox-firewall's nftables tables on PVE 9, pve-firewall's iptables chains
|
||||||
|
before -- read as root over SSH, as for any Linux host.
|
||||||
|
- `get_hardening()` on both drivers (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776):
|
||||||
|
the security modules, SELinux and AppArmor, the crypto policy and FIPS mode, what the kernel
|
||||||
|
reports for each CPU vulnerability, and the kernel command line (`mitigations=`, `nosmt`). One
|
||||||
|
fixed, read-only command over the exec path, which is root's login, so AppArmor's profiles per
|
||||||
|
mode are read too. A hypervisor's guests share its CPU, so its CPU vulnerabilities matter most.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Needs napalm-device-types 4.48.0 or later (`HardeningMixin`).
|
||||||
|
|
||||||
|
## [0.16.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `get_services_need_restart()` on both drivers (napalm-device-types' `ServicesRestartMixin`,
|
||||||
|
NetOrk/netork#2750): the services that still run code an update replaced on disk, so they
|
||||||
|
keep the old library until they restart. One fixed, read-only command over the exec path,
|
||||||
|
which is root's login: `needs-restarting -s`, else `needrestart` in list-only mode, else the
|
||||||
|
processes whose `/proc/<pid>/maps` maps deleted code, each named by its cgroup's service. A
|
||||||
|
running VM's QEMU (`qemu.slice`) is listed as a process; an LXC container's processes are
|
||||||
|
left out, since a container updates itself. It runs only when the login is root
|
||||||
|
(`id -u` is 0): another login gets no report and the read raises, rather than read as
|
||||||
|
clean what it cannot see. No stdin.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Needs napalm-device-types 4.46.0 or later (`ServicesRestartMixin`, with an LXC
|
||||||
|
container's processes left out).
|
||||||
|
|
||||||
## [0.15.0] - 2026-11-26
|
## [0.15.0] - 2026-11-26
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -132,6 +132,11 @@ device = driver(
|
|||||||
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
|
| `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
|
||||||
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
|
||||||
| `get_certificates` | `GET /nodes/{node}/certificates/info`, in netOrk's contract shape: `{name, issuer, valid_from, valid_to, in_use_by}` (Unix timestamps; the file name, the issuer's CN; `in_use_by` 1 for the one pveproxy serves, `pveproxy-ssl.pem` before `pve-ssl.pem`), plus `subject`, `fingerprint` and `acme`: true for `pveproxy-ssl.pem` when the node's config names an ACME domain (one more call, `GET /nodes/{node}/config`). Never the PEM. `[]` when unreadable |
|
| `get_certificates` | `GET /nodes/{node}/certificates/info`, in netOrk's contract shape: `{name, issuer, valid_from, valid_to, in_use_by}` (Unix timestamps; the file name, the issuer's CN; `in_use_by` 1 for the one pveproxy serves, `pveproxy-ssl.pem` before `pve-ssl.pem`), plus `subject`, `fingerprint` and `acme`: true for `pveproxy-ssl.pem` when the node's config names an ACME domain (one more call, `GET /nodes/{node}/config`). Never the PEM. `[]` when unreadable |
|
||||||
|
| `get_services_need_restart` | the services that still run code an update replaced on disk, as root over SSH (napalm-device-types' `ServicesRestartMixin`): `needrestart` in list-only mode where it is installed, else the processes whose `/proc/<pid>/maps` maps deleted code. A running VM's QEMU is a process (`processes`), an LXC container's processes are left out (the container updates itself). Only as root: another SSH login gets no reading, rather than a clean one |
|
||||||
|
| `get_pve_firewall` | the PVE firewall as the operator wrote it, read only (NetOrk/netork#2654): the datacenter's `options`, `rules`, security `groups` (name → rules), `ipsets` (name → `[{cidr, nomatch, comment}]`) and `aliases` (name → cidr), this node's `options` and `rules`, and every guest's on this node (`vmid`, `type`, `name`, `options`, `rules`, and `nics`: `[{name, firewall}]` from `netN … firewall=1`). Each rule keeps PVE's fields and its `origin` (`cluster`, `group`, `node`, `guest`). A part PVE refuses is `null`, never empty |
|
||||||
|
| `get_host_firewall` | what the node has loaded, as for any Linux host (napalm-device-types' `HostFirewallMixin`): `nft list ruleset` (PVE 9's proxmox-firewall) or `iptables-save` (pve-firewall), as root over SSH |
|
||||||
|
| `get_hardening` | how the node is hardened (napalm-device-types' `HardeningMixin`, NetOrk/netork#2776): security modules, SELinux and AppArmor, crypto policy, FIPS mode, CPU vulnerabilities, kernel command line, whether the node runs virtualized and its CPU vendor, as root over SSH. On the backup server too |
|
||||||
|
| `install_cpu_microcode` | the CPU vendor's microcode (`intel-microcode`, `amd64-microcode`; napalm-device-types' `CpuMicrocodeMixin`, NetOrk/netork#2838): Debian's `non-free-firmware` added to Debian's own sources where missing, `apt-get update` over SSH (waited for, unlike the API's refresh task), then the install. Refused on a node that runs virtualized. Loads at the next boot. On the backup server too |
|
||||||
|
|
||||||
**Not implemented** (raise `NotImplementedError`):
|
**Not implemented** (raise `NotImplementedError`):
|
||||||
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
|
||||||
@@ -189,7 +194,7 @@ the disks and ZFS pools the server manages itself.
|
|||||||
| `get_facts`, `get_interfaces`, `get_interfaces_ip`, `get_environment` | the API; host name, DMI and MAC addresses over SSH |
|
| `get_facts`, `get_interfaces`, `get_interfaces_ip`, `get_environment` | the API; host name, DMI and MAC addresses over SSH |
|
||||||
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
|
| `get_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
|
||||||
| `get_licenses` | `pbs-subscription` |
|
| `get_licenses` | `pbs-subscription` |
|
||||||
| packages, updates, services, kernel, listening sockets, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
| packages, updates, services, kernel, listening sockets, services still running replaced code, sshd hardening, `reboot_host`, `shutdown_host` | as on Proxmox VE |
|
||||||
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
| scheduled jobs | as on Proxmox VE; `proxmox-backup*` units are `platform`. Verify, prune, sync and GC jobs are `get_backup_jobs`, not scheduled jobs |
|
||||||
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
| `get_time_sync`, `configure_time_sync`, `get_ntp_servers` | as on Proxmox VE, the zone through `/nodes/localhost/time` (writing it needs `Sys.Modify` on `/system/time`) |
|
||||||
| `get_certificates` | as on Proxmox VE, from `/nodes/localhost/certificates/info` and `/nodes/localhost/config`: one certificate, `proxy.pem`, which ACME renews where a domain is configured |
|
| `get_certificates` | as on Proxmox VE, from `/nodes/localhost/certificates/info` and `/nodes/localhost/config`: one certificate, `proxy.pem`, which ACME renews where a domain is configured |
|
||||||
@@ -238,6 +243,7 @@ napalm_proxmox/
|
|||||||
├── pbs_backups.py # The backup-server role: datastores, groups, jobs, remotes, actions
|
├── pbs_backups.py # The backup-server role: datastores, groups, jobs, remotes, actions
|
||||||
├── pbs_host.py # The backup server as a host: facts, interfaces, disks, ZFS pools
|
├── pbs_host.py # The backup server as a host: facts, interfaces, disks, ZFS pools
|
||||||
├── certificates.py # get_certificates on both: the node's TLS certificates, and ACME
|
├── certificates.py # get_certificates on both: the node's TLS certificates, and ACME
|
||||||
|
├── firewall_mixin.py # get_pve_firewall: the PVE firewall at every level, read only
|
||||||
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
└── utils.py # MAC normalisation, CIDR parsing, ARP/OVS parsers
|
||||||
tests/
|
tests/
|
||||||
├── conftest.py # Shared fixtures and mock API payloads
|
├── conftest.py # Shared fixtures and mock API payloads
|
||||||
@@ -250,6 +256,8 @@ tests/
|
|||||||
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
├── test_misc.py # NTP statistics, SNMP, users, config, ping, traceroute, CLI, LLDP
|
||||||
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
├── test_time_sync.py # get_time_sync / configure_time_sync on both drivers
|
||||||
├── test_certificates.py # get_certificates on both drivers
|
├── test_certificates.py # get_certificates on both drivers
|
||||||
|
├── test_firewall.py # get_pve_firewall and get_host_firewall
|
||||||
|
├── test_hardening.py # get_hardening and install_cpu_microcode on both drivers
|
||||||
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
├── test_utils.py # Unit tests for napalm_proxmox.utils
|
||||||
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
|
||||||
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
|
||||||
|
|||||||
@@ -17,8 +17,10 @@ from typing import Any
|
|||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
BackupServerDriver,
|
BackupServerDriver,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
FingerprintRule,
|
FingerprintRule,
|
||||||
|
HardeningMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
@@ -27,6 +29,7 @@ from napalm_device_types import (
|
|||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
PortSpec,
|
PortSpec,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
StorageDriver,
|
StorageDriver,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
@@ -64,15 +67,18 @@ class ProxmoxBackupDriver(
|
|||||||
BackupServerDriver,
|
BackupServerDriver,
|
||||||
StorageDriver,
|
StorageDriver,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
|
HardeningMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
LogSourcesMixin,
|
LogSourcesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
ProxmoxScheduledJobsMixin,
|
ProxmoxScheduledJobsMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
ProxmoxZabbixAgentMixin,
|
ProxmoxZabbixAgentMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
|
|||||||
@@ -27,8 +27,11 @@ from typing import Any
|
|||||||
from napalm.base.exceptions import ConnectionException
|
from napalm.base.exceptions import ConnectionException
|
||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
FingerprintRule,
|
FingerprintRule,
|
||||||
|
HardeningMixin,
|
||||||
|
HostFirewallMixin,
|
||||||
HostStatusMixin,
|
HostStatusMixin,
|
||||||
HypervisorDriver,
|
HypervisorDriver,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
@@ -38,6 +41,7 @@ from napalm_device_types import (
|
|||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
PortSpec,
|
PortSpec,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
@@ -53,6 +57,7 @@ from napalm_proxmox.certificates import ProxmoxCertificatesMixin
|
|||||||
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
|
||||||
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
|
||||||
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
|
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
|
||||||
|
from napalm_proxmox.firewall_mixin import ProxmoxFirewallMixin
|
||||||
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
from napalm_proxmox.host_mixin import ProxmoxHostMixin
|
||||||
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
|
||||||
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
|
||||||
@@ -97,10 +102,14 @@ class ProxmoxDriver(
|
|||||||
ProxmoxRoutingMixin,
|
ProxmoxRoutingMixin,
|
||||||
ProxmoxSystemMixin,
|
ProxmoxSystemMixin,
|
||||||
ProxmoxHostMixin,
|
ProxmoxHostMixin,
|
||||||
|
ProxmoxFirewallMixin,
|
||||||
KernelFactsMixin,
|
KernelFactsMixin,
|
||||||
|
HostFirewallMixin,
|
||||||
|
HardeningMixin,
|
||||||
ServicePackagesMixin,
|
ServicePackagesMixin,
|
||||||
ListeningSocketsMixin,
|
ListeningSocketsMixin,
|
||||||
LogSourcesMixin,
|
LogSourcesMixin,
|
||||||
|
ServicesRestartMixin,
|
||||||
SystemIdentityMixin,
|
SystemIdentityMixin,
|
||||||
SystemdServicesMixin,
|
SystemdServicesMixin,
|
||||||
ProxmoxScheduledJobsMixin,
|
ProxmoxScheduledJobsMixin,
|
||||||
@@ -113,6 +122,7 @@ class ProxmoxDriver(
|
|||||||
LicenseMixin,
|
LicenseMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
ProxmoxZabbixAgentMixin,
|
ProxmoxZabbixAgentMixin,
|
||||||
|
CpuMicrocodeMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
OpenSshServerMixin,
|
OpenSshServerMixin,
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
"""The PVE firewall of the cluster, read-only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall()`` reads what the operator wrote, at every level PVE has one:
|
||||||
|
the datacenter's options, rules, security groups, IP sets and aliases, the node's
|
||||||
|
options and rules, and each guest's on this node -- options, rules, and which NICs
|
||||||
|
carry ``firewall=1``. The datacenter level is the cluster's (pmxcfs keeps it once
|
||||||
|
for every node), so every node reads the same; a node reads its own guests, the
|
||||||
|
ones it runs. Nothing is written: pve-firewall rules are the operator's (see
|
||||||
|
``host_mixin``), and netOrk only reads them.
|
||||||
|
|
||||||
|
Each rule keeps PVE's own fields -- ``pos``, ``type`` (``in``, ``out``, ``group``,
|
||||||
|
``forward``), ``action`` (``ACCEPT``, ``DROP``, ``REJECT``, or a group's name),
|
||||||
|
``macro``, ``source``, ``dest``, ``proto``, ``dport``, ``sport``, ``iface``,
|
||||||
|
``enable``, ``comment`` -- and says where it came from (``origin``: ``cluster``,
|
||||||
|
``node``, ``guest`` or ``group``). A level whose call is refused (no
|
||||||
|
``Sys.Audit``/``VM.Audit``) is None, not empty: an unread level is no claim.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_JsonDict = dict[str, Any]
|
||||||
|
|
||||||
|
#: The rule fields kept as PVE returns them.
|
||||||
|
_RULE_FIELDS = (
|
||||||
|
"pos",
|
||||||
|
"type",
|
||||||
|
"action",
|
||||||
|
"macro",
|
||||||
|
"source",
|
||||||
|
"dest",
|
||||||
|
"proto",
|
||||||
|
"dport",
|
||||||
|
"sport",
|
||||||
|
"iface",
|
||||||
|
"comment",
|
||||||
|
"log",
|
||||||
|
"icmp-type",
|
||||||
|
)
|
||||||
|
#: A guest's NIC keys: ``net0`` … for both QEMU and LXC.
|
||||||
|
_NIC = re.compile(r"^net\d+$")
|
||||||
|
|
||||||
|
|
||||||
|
def _rule(raw: _JsonDict, origin: str) -> _JsonDict:
|
||||||
|
found = {k.replace("-", "_"): raw[k] for k in _RULE_FIELDS if raw.get(k) not in (None, "")}
|
||||||
|
found["enable"] = str(raw.get("enable", 1)) not in ("0", "")
|
||||||
|
found["origin"] = origin
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _rules(rows: Any, origin: str) -> list[_JsonDict]:
|
||||||
|
return [_rule(r, origin) for r in rows or [] if isinstance(r, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def nic_firewalls(config: _JsonDict) -> list[_JsonDict]:
|
||||||
|
"""Each NIC of a guest config with whether ``firewall=1`` is set on it."""
|
||||||
|
found = []
|
||||||
|
for key in sorted(k for k in config if _NIC.match(k)):
|
||||||
|
options = dict(part.split("=", 1) for part in str(config[key]).split(",") if "=" in part)
|
||||||
|
found.append({"name": key, "firewall": options.get("firewall") == "1"})
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _read(call: Any, what: str) -> Any:
|
||||||
|
"""One GET; None when PVE refuses or fails it -- an unread level, not an empty one."""
|
||||||
|
try:
|
||||||
|
return call.get()
|
||||||
|
except Exception as exc: # noqa: BLE001 - proxmoxer raises its own and requests' errors
|
||||||
|
logger.warning("get_pve_firewall: %s not read: %s", what, exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _rules_or_none(rows: Any, origin: str) -> list[_JsonDict] | None:
|
||||||
|
return None if rows is None else _rules(rows, origin)
|
||||||
|
|
||||||
|
|
||||||
|
def _named(rows: Any, key: str) -> list[str]:
|
||||||
|
return [str(r[key]) for r in rows or [] if isinstance(r, dict) and r.get(key)]
|
||||||
|
|
||||||
|
|
||||||
|
def _groups(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
"""Each security group's rules; a group whose rules are refused has none listed."""
|
||||||
|
listed = _read(fw.groups, "security groups")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: _rules(_read(fw.groups(name), f"group {name}"), "group")
|
||||||
|
for name in _named(listed, "group")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _entry(raw: _JsonDict) -> _JsonDict:
|
||||||
|
return {
|
||||||
|
"cidr": raw.get("cidr"),
|
||||||
|
"nomatch": bool(raw.get("nomatch")),
|
||||||
|
"comment": raw.get("comment"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ipsets(fw: Any) -> dict[str, list[_JsonDict]] | None:
|
||||||
|
listed = _read(fw.ipset, "IP sets")
|
||||||
|
if listed is None:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
name: [
|
||||||
|
_entry(e) for e in _read(fw.ipset(name), f"IP set {name}") or [] if isinstance(e, dict)
|
||||||
|
]
|
||||||
|
for name in _named(listed, "name")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _aliases(rows: Any) -> dict[str, Any] | None:
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(a["name"]): a.get("cidr") for a in rows if isinstance(a, dict) and a.get("name")}
|
||||||
|
|
||||||
|
|
||||||
|
class ProxmoxFirewallMixin:
|
||||||
|
"""``get_pve_firewall`` for the PVE driver: the cluster's firewall as written, read only."""
|
||||||
|
|
||||||
|
_node_name: str
|
||||||
|
|
||||||
|
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
|
||||||
|
_api: Any
|
||||||
|
|
||||||
|
def _node_api(self) -> Any: ...
|
||||||
|
|
||||||
|
def _cluster_firewall(self) -> _JsonDict:
|
||||||
|
fw = self._api.cluster.firewall
|
||||||
|
return {
|
||||||
|
"options": _read(fw.options, "datacenter options"),
|
||||||
|
"rules": _rules_or_none(_read(fw.rules, "datacenter rules"), "cluster"),
|
||||||
|
"groups": _groups(fw),
|
||||||
|
"ipsets": _ipsets(fw),
|
||||||
|
"aliases": _aliases(_read(fw.aliases, "aliases")),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guest_firewall(self, kind: str, guest: _JsonDict) -> _JsonDict:
|
||||||
|
vmid = int(guest.get("vmid", 0))
|
||||||
|
api = getattr(self._node_api(), kind)(vmid)
|
||||||
|
rules = _read(api.firewall.rules, f"{kind} {vmid} rules")
|
||||||
|
config = _read(api.config, f"{kind} {vmid} config")
|
||||||
|
return {
|
||||||
|
"vmid": str(vmid),
|
||||||
|
"type": "vm" if kind == "qemu" else "container",
|
||||||
|
"name": guest.get("name") or "",
|
||||||
|
"node": self._node_name,
|
||||||
|
"options": _read(api.firewall.options, f"{kind} {vmid} options"),
|
||||||
|
"rules": _rules_or_none(rules, "guest"),
|
||||||
|
"nics": None if config is None else nic_firewalls(config),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _guests(self) -> list[_JsonDict]:
|
||||||
|
found: list[_JsonDict] = []
|
||||||
|
for kind in ("qemu", "lxc"):
|
||||||
|
for guest in _read(getattr(self._node_api(), kind), f"{kind} guests") or []:
|
||||||
|
if isinstance(guest, dict) and guest.get("vmid") is not None:
|
||||||
|
found.append(self._guest_firewall(kind, guest))
|
||||||
|
return found
|
||||||
|
|
||||||
|
def get_pve_firewall(self) -> _JsonDict:
|
||||||
|
"""
|
||||||
|
Return the PVE firewall as the operator wrote it: the datacenter level, this
|
||||||
|
node's, and every guest's on this node. Read only.
|
||||||
|
|
||||||
|
* cluster (dict) - ``options``, ``rules``, ``groups`` (name -> rules),
|
||||||
|
``ipsets`` (name -> ``[{cidr, nomatch, comment}]``), ``aliases`` (name -> cidr)
|
||||||
|
* node (dict) - ``name``, ``options``, ``rules``
|
||||||
|
* guests (list) - ``vmid``, ``type`` (``vm``/``container``), ``name``, ``node``,
|
||||||
|
``options``, ``rules``, ``nics`` (``[{name, firewall}]``)
|
||||||
|
|
||||||
|
Any part PVE refuses is None, never empty. Each rule carries PVE's fields and
|
||||||
|
its ``origin`` (``cluster``, ``group``, ``node``, ``guest``).
|
||||||
|
"""
|
||||||
|
node = self._node_api().firewall
|
||||||
|
rules = _read(node.rules, "node rules")
|
||||||
|
return {
|
||||||
|
"cluster": self._cluster_firewall(),
|
||||||
|
"node": {
|
||||||
|
"name": self._node_name,
|
||||||
|
"options": _read(node.options, "node options"),
|
||||||
|
"rules": _rules_or_none(rules, "node"),
|
||||||
|
},
|
||||||
|
"guests": self._guests(),
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
"""What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts.
|
"""What a Proxmox VE node and a Proxmox Backup Server share as Debian hosts.
|
||||||
|
|
||||||
The transports for napalm-device-types' host readers (kernel facts, service
|
The transports for napalm-device-types' host readers (kernel facts, service
|
||||||
packages, system identity, listening sockets, systemd services, host status,
|
packages, system identity, listening sockets, the services that still run replaced
|
||||||
apt's proxy), packages and APT updates, the subscription, root file writes,
|
code, systemd services, host status, apt's proxy), packages and APT updates, the
|
||||||
and restarting or shutting the host down. All of it is the same on both
|
subscription, root file writes, and restarting or shutting the host down. All of it
|
||||||
products: the same ``/nodes/{node}/apt``, ``/subscription`` and ``/status``
|
is the same on both products: the same ``/nodes/{node}/apt``, ``/subscription`` and
|
||||||
endpoints, and root's shell over the driver's own SSH session.
|
``/status`` endpoints, and root's shell over the driver's own SSH session.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -72,6 +72,18 @@ class ProxmoxHostMixin:
|
|||||||
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
|
||||||
return self._exec_ssh_command(command)
|
return self._exec_ssh_command(command)
|
||||||
|
|
||||||
|
def _run_hardening_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``HardeningMixin.get_hardening`` (NetOrk/netork#2776): the exec
|
||||||
|
path, which is root's login, so AppArmor's profiles per mode are read too. Another
|
||||||
|
login reads the rest without them, as napalm-device-types' fallback does. No stdin."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_host_firewall_command(self, command: str, *, privileged: bool) -> str:
|
||||||
|
"""The transport for ``HostFirewallMixin.get_host_firewall``: the exec path, which
|
||||||
|
runs as root either way. What the node has loaded -- proxmox-firewall's nftables
|
||||||
|
tables on PVE 9, pve-firewall's iptables chains before (NetOrk/netork#2654)."""
|
||||||
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
def _run_service_packages_command(self, command: str) -> str:
|
def _run_service_packages_command(self, command: str) -> str:
|
||||||
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
|
||||||
return str(self._exec_ssh_command(command))
|
return str(self._exec_ssh_command(command))
|
||||||
@@ -91,6 +103,13 @@ class ProxmoxHostMixin:
|
|||||||
which runs as root either way."""
|
which runs as root either way."""
|
||||||
return str(self._exec_ssh_command(command))
|
return str(self._exec_ssh_command(command))
|
||||||
|
|
||||||
|
def _run_services_restart_command(self, command: str) -> str:
|
||||||
|
"""The transport for ``ServicesRestartMixin.get_services_need_restart``: the exec
|
||||||
|
path, which is root's login as a rule. Run only as root: a reading of the login's
|
||||||
|
own processes would read as clean, so another login prints nothing and the parse
|
||||||
|
raises (NetOrk/netork#2750). No stdin."""
|
||||||
|
return str(self._exec_ssh_command(f'[ "$(id -u)" = 0 ] && {command}'))
|
||||||
|
|
||||||
def get_packages(self) -> list[PackageDict]:
|
def get_packages(self) -> list[PackageDict]:
|
||||||
"""Return installed Debian packages with available-update info.
|
"""Return installed Debian packages with available-update info.
|
||||||
|
|
||||||
@@ -242,6 +261,14 @@ class ProxmoxHostMixin:
|
|||||||
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
def _write_apt_file(self, path: str, content: str) -> FixStepOutcomeDict:
|
||||||
return self._write_root_file(path, content)
|
return self._write_root_file(path, content)
|
||||||
|
|
||||||
|
def _reload_package_index(self) -> FixStepOutcomeDict:
|
||||||
|
"""``CpuMicrocodeMixin``'s index load (NetOrk/netork#2838): ``apt-get update`` on the
|
||||||
|
exec path, done when it returns. ``refresh_available_updates`` only starts the API's
|
||||||
|
task, and the install that follows would race it."""
|
||||||
|
return self._step(
|
||||||
|
"DEBIAN_FRONTEND=noninteractive apt-get update", "package index loaded again"
|
||||||
|
)
|
||||||
|
|
||||||
def _allow_sources(
|
def _allow_sources(
|
||||||
self, allowed: list[str], port: int, proto: str, purpose: str
|
self, allowed: list[str], port: int, proto: str, purpose: str
|
||||||
) -> FixStepOutcomeDict:
|
) -> FixStepOutcomeDict:
|
||||||
|
|||||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "napalm-proxmox"
|
name = "napalm-proxmox"
|
||||||
version = "0.15.0"
|
version = "0.19.0"
|
||||||
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
license = "Apache-2.0"
|
license = "Apache-2.0"
|
||||||
@@ -21,7 +21,7 @@ classifiers = [
|
|||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"napalm>=5.0.0",
|
"napalm>=5.0.0",
|
||||||
"napalm_device_types>=4.44.0", # CredentialExpiryMixin, UpdateHistoryDict, VMDict.uid
|
"napalm_device_types>=4.53.0", # CpuMicrocodeMixin; virtualization in the hardening
|
||||||
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
|
||||||
"proxmoxer>=2.0.0",
|
"proxmoxer>=2.0.0",
|
||||||
"netaddr>=0.9.0",
|
"netaddr>=0.9.0",
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
"""The PVE firewall, read only (NetOrk/netork#2654).
|
||||||
|
|
||||||
|
``get_pve_firewall`` reads the datacenter level -- options, rules, security groups,
|
||||||
|
IP sets, aliases -- the node's options and rules, and every guest's on the node with
|
||||||
|
which of its NICs carry ``firewall=1``. Each rule says where it came from. A level
|
||||||
|
PVE refuses is None, not empty. ``get_host_firewall`` reads what the node has loaded
|
||||||
|
(``nft list ruleset`` / ``iptables-save``), as for any Linux host.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_proxmox.firewall_mixin import nic_firewalls
|
||||||
|
|
||||||
|
DC_OPTIONS = {"enable": 1, "policy_in": "DROP", "policy_out": "ACCEPT"}
|
||||||
|
DC_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"macro": "SSH",
|
||||||
|
"source": "+dc/admins",
|
||||||
|
"enable": 1,
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
GROUP_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "proto": "tcp", "dport": "80,443", "enable": 1}
|
||||||
|
]
|
||||||
|
IPSET = [{"cidr": "198.51.100.0/24", "comment": "office"}, {"cidr": "198.51.100.7", "nomatch": 1}]
|
||||||
|
ALIASES = [{"name": "monitor", "cidr": "203.0.113.5/32", "comment": "zabbix"}]
|
||||||
|
NODE_RULES = [
|
||||||
|
{"pos": 0, "type": "in", "action": "ACCEPT", "dport": "8006", "proto": "tcp", "enable": 0}
|
||||||
|
]
|
||||||
|
GUEST_OPTIONS = {"enable": 1, "policy_in": "DROP"}
|
||||||
|
GUEST_RULES = [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"enable": 1,
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
},
|
||||||
|
{"pos": 1, "type": "group", "action": "web", "enable": 1},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _api() -> MagicMock:
|
||||||
|
api = MagicMock()
|
||||||
|
fw = api.cluster.firewall
|
||||||
|
fw.options.get.return_value = DC_OPTIONS
|
||||||
|
fw.rules.get.return_value = DC_RULES
|
||||||
|
fw.groups.get.return_value = [{"group": "web", "comment": "web servers"}]
|
||||||
|
fw.groups.return_value.get.return_value = GROUP_RULES
|
||||||
|
fw.ipset.get.return_value = [{"name": "admins"}]
|
||||||
|
fw.ipset.return_value.get.return_value = IPSET
|
||||||
|
fw.aliases.get.return_value = ALIASES
|
||||||
|
node = api.nodes.return_value
|
||||||
|
node.firewall.options.get.return_value = {"enable": 1}
|
||||||
|
node.firewall.rules.get.return_value = NODE_RULES
|
||||||
|
node.qemu.get.return_value = [{"vmid": 100, "name": "web-01"}]
|
||||||
|
vm = node.qemu.return_value
|
||||||
|
vm.firewall.options.get.return_value = GUEST_OPTIONS
|
||||||
|
vm.firewall.rules.get.return_value = GUEST_RULES
|
||||||
|
vm.config.get.return_value = {
|
||||||
|
"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=1",
|
||||||
|
"net1": "virtio=AA:BB:CC:DD:EE:02,bridge=vmbr1",
|
||||||
|
"name": "web-01",
|
||||||
|
}
|
||||||
|
node.lxc.get.return_value = [{"vmid": 200, "name": "dns-01"}]
|
||||||
|
ct = node.lxc.return_value
|
||||||
|
ct.firewall.options.get.return_value = {}
|
||||||
|
ct.firewall.rules.get.return_value = []
|
||||||
|
ct.config.get.return_value = {"net0": "name=eth0,bridge=vmbr0,firewall=1,ip=dhcp"}
|
||||||
|
return api
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fw_driver(driver):
|
||||||
|
driver._api = _api()
|
||||||
|
return driver
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheDatacenter:
|
||||||
|
def test_options_rules_groups_ipsets_aliases(self, fw_driver):
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["options"] == DC_OPTIONS
|
||||||
|
assert [
|
||||||
|
(r["origin"], r["type"], r.get("macro"), r["enable"]) for r in cluster["rules"]
|
||||||
|
] == [
|
||||||
|
("cluster", "in", "SSH", True),
|
||||||
|
("cluster", "group", None, True),
|
||||||
|
]
|
||||||
|
assert cluster["groups"] == {
|
||||||
|
"web": [
|
||||||
|
{
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "80,443",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "group",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["ipsets"] == {
|
||||||
|
"admins": [
|
||||||
|
{"cidr": "198.51.100.0/24", "nomatch": False, "comment": "office"},
|
||||||
|
{"cidr": "198.51.100.7", "nomatch": True, "comment": None},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
def test_a_level_pve_refuses_is_none_not_empty(self, fw_driver):
|
||||||
|
fw_driver._api.cluster.firewall.ipset.get.side_effect = RuntimeError("403 Forbidden")
|
||||||
|
|
||||||
|
cluster = fw_driver.get_pve_firewall()["cluster"]
|
||||||
|
|
||||||
|
assert cluster["ipsets"] is None
|
||||||
|
assert cluster["aliases"] == {"monitor": "203.0.113.5/32"}
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheNodeAndItsGuests:
|
||||||
|
def test_the_nodes_rules_keep_their_switch(self, fw_driver):
|
||||||
|
node = fw_driver.get_pve_firewall()["node"]
|
||||||
|
|
||||||
|
assert node["name"] == fw_driver._node_name
|
||||||
|
assert node["options"] == {"enable": 1}
|
||||||
|
assert node["rules"][0]["enable"] is False
|
||||||
|
assert node["rules"][0]["origin"] == "node"
|
||||||
|
|
||||||
|
def test_every_guest_with_its_rules_and_nics(self, fw_driver):
|
||||||
|
guests = fw_driver.get_pve_firewall()["guests"]
|
||||||
|
|
||||||
|
assert [(g["vmid"], g["type"], g["name"]) for g in guests] == [
|
||||||
|
("100", "vm", "web-01"),
|
||||||
|
("200", "container", "dns-01"),
|
||||||
|
]
|
||||||
|
vm = guests[0]
|
||||||
|
assert vm["options"] == GUEST_OPTIONS
|
||||||
|
assert vm["rules"][0] == {
|
||||||
|
"pos": 0,
|
||||||
|
"type": "in",
|
||||||
|
"action": "ACCEPT",
|
||||||
|
"proto": "tcp",
|
||||||
|
"dport": "22",
|
||||||
|
"source": "monitor",
|
||||||
|
"comment": "zabbix ssh",
|
||||||
|
"enable": True,
|
||||||
|
"origin": "guest",
|
||||||
|
}
|
||||||
|
assert vm["nics"] == [
|
||||||
|
{"name": "net0", "firewall": True},
|
||||||
|
{"name": "net1", "firewall": False},
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_a_guest_whose_config_is_refused_has_no_nics_reading(self, fw_driver):
|
||||||
|
fw_driver._api.nodes.return_value.qemu.return_value.config.get.side_effect = RuntimeError(
|
||||||
|
"403"
|
||||||
|
)
|
||||||
|
|
||||||
|
vm = fw_driver.get_pve_firewall()["guests"][0]
|
||||||
|
|
||||||
|
assert vm["nics"] is None
|
||||||
|
assert vm["rules"] is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_nic_without_the_flag_is_not_filtered():
|
||||||
|
assert nic_firewalls({"net0": "virtio=AA:BB:CC:DD:EE:01,bridge=vmbr0,firewall=0"}) == [
|
||||||
|
{"name": "net0", "firewall": False}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheLoadedRuleset:
|
||||||
|
def test_the_node_reads_its_netfilter_rules_like_a_linux_host(self, driver):
|
||||||
|
seen: list[str] = []
|
||||||
|
|
||||||
|
def run(command: str) -> str:
|
||||||
|
seen.append(command)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
driver._exec_ssh_command = run # type: ignore[method-assign]
|
||||||
|
|
||||||
|
assert hasattr(driver, "get_host_firewall")
|
||||||
|
try:
|
||||||
|
driver.get_host_firewall()
|
||||||
|
except Exception:
|
||||||
|
pass # an empty answer is no report; the transport is what is tested here
|
||||||
|
assert seen and "nft" in seen[0] and "iptables-save" in seen[0]
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""`get_hardening`: how the node is hardened (NetOrk/netork#2776).
|
||||||
|
|
||||||
|
A hypervisor is where CPU vulnerabilities matter most: its guests share the CPU.
|
||||||
|
The command and its parse are napalm-device-types' (``HardeningMixin``); both
|
||||||
|
drivers carry the command over their own exec path, which is root's login, so
|
||||||
|
AppArmor's profiles per mode are read as well.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import HardeningMixin
|
||||||
|
|
||||||
|
from napalm_proxmox.backup_driver import ProxmoxBackupDriver
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
WIRE = "\n".join(
|
||||||
|
[
|
||||||
|
"HARDENING_BEGIN",
|
||||||
|
"[lsm]",
|
||||||
|
"lockdown,capability,landlock,yama,apparmor,bpf",
|
||||||
|
"[cmdline]",
|
||||||
|
"BOOT_IMAGE=/boot/vmlinuz-6.8.12-4-pve root=/dev/mapper/pve-root ro mitigations=off",
|
||||||
|
"[fips]",
|
||||||
|
"0",
|
||||||
|
"[apparmor_enabled]",
|
||||||
|
"Y",
|
||||||
|
"[os]",
|
||||||
|
"ID=debian",
|
||||||
|
"[cpu_vulnerabilities]",
|
||||||
|
"/sys/devices/system/cpu/vulnerabilities/mds:Vulnerable; SMT vulnerable",
|
||||||
|
"/sys/devices/system/cpu/vulnerabilities/meltdown:Not affected",
|
||||||
|
"HARDENING_END",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_declare_the_contract(cls):
|
||||||
|
assert issubclass(cls, HardeningMixin)
|
||||||
|
assert hasattr(cls, "get_hardening")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_node_runs_the_shared_command_over_its_exec_path(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||||
|
reading = driver.get_hardening()
|
||||||
|
|
||||||
|
exec_.assert_called_once()
|
||||||
|
assert "HARDENING_" in exec_.call_args.args[0]
|
||||||
|
assert reading["lsm"] == ["lockdown", "capability", "landlock", "yama", "apparmor", "bpf"]
|
||||||
|
assert reading["mitigations"] == "off"
|
||||||
|
assert reading["cpu_vulnerabilities"]["mds"] == "Vulnerable; SMT vulnerable"
|
||||||
|
assert reading["os_ids"] == ["debian"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_it_the_same_way():
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
|
||||||
|
with patch.object(drv, "_exec_ssh_command", return_value=WIRE):
|
||||||
|
reading = drv.get_hardening()
|
||||||
|
|
||||||
|
assert reading["cpu_vulnerabilities"]["meltdown"] == "Not affected"
|
||||||
|
|
||||||
|
|
||||||
|
def test_output_without_a_report_raises(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=""):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_hardening()
|
||||||
|
|
||||||
|
|
||||||
|
class TestCpuMicrocode:
|
||||||
|
"""``install_cpu_microcode`` (napalm-device-types ``CpuMicrocodeMixin``, NetOrk/netork#2838):
|
||||||
|
a node runs on its own CPU, and Proxmox's own install enables no ``non-free-firmware``."""
|
||||||
|
|
||||||
|
SOURCES = "/etc/apt/sources.list.d/debian.sources"
|
||||||
|
TEXT = (
|
||||||
|
"Types: deb\nURIs: http://deb.debian.org/debian/\nSuites: trixie trixie-updates\n"
|
||||||
|
"Components: main contrib\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _node(self, drv, *, virtualization="none"):
|
||||||
|
import base64
|
||||||
|
|
||||||
|
ran: list[str] = []
|
||||||
|
file_lines = "".join(f"|{line}\n" for line in self.TEXT.split("\n"))
|
||||||
|
report = (
|
||||||
|
"ARELEASE_BEGIN\n@@os\n|ID=debian\n|VERSION_CODENAME=trixie\n"
|
||||||
|
f"@@file {self.SOURCES}\n{file_lines}ARELEASE_END\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def exec_(command):
|
||||||
|
ran.append(command)
|
||||||
|
if command.startswith("base64 "):
|
||||||
|
return base64.b64encode(self.TEXT.encode()).decode()
|
||||||
|
if "ARELEASE_" in command:
|
||||||
|
return report
|
||||||
|
return "done\n__PVE_RC=0"
|
||||||
|
|
||||||
|
drv.get_hardening = lambda: {
|
||||||
|
"os_ids": ["debian"],
|
||||||
|
"virtualization": virtualization,
|
||||||
|
"cpu_vendor": "GenuineIntel",
|
||||||
|
}
|
||||||
|
drv.get_packages = lambda: []
|
||||||
|
drv.refresh_available_updates = lambda: pytest.fail("the API refresh does not wait")
|
||||||
|
drv._exec_ssh_command = exec_
|
||||||
|
return ran
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_carry_it(self, cls):
|
||||||
|
assert callable(getattr(cls, "install_cpu_microcode", None))
|
||||||
|
|
||||||
|
def test_the_component_then_apt_get_update_then_the_package(self, driver):
|
||||||
|
ran = self._node(driver)
|
||||||
|
|
||||||
|
result = driver.install_cpu_microcode()
|
||||||
|
|
||||||
|
assert result["success"] is True, result["output"]
|
||||||
|
assert result["sources_changed"] is True
|
||||||
|
written = next(c for c in ran if "install -m 644" in c)
|
||||||
|
assert self.SOURCES in written
|
||||||
|
update = next(i for i, c in enumerate(ran) if "apt-get update" in c)
|
||||||
|
install = next(i for i, c in enumerate(ran) if "apt-get install -y intel-microcode" in c)
|
||||||
|
assert ran.index(written) < update < install
|
||||||
|
|
||||||
|
def test_a_virtual_backup_server_installs_nothing(self):
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
ran = self._node(drv, virtualization="kvm")
|
||||||
|
|
||||||
|
result = drv.install_cpu_microcode()
|
||||||
|
|
||||||
|
assert result["success"] is False
|
||||||
|
assert "its host does" in result["output"]
|
||||||
|
assert ran == []
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""`get_services_need_restart`: the services on the node that still run replaced code.
|
||||||
|
|
||||||
|
An openssl or glibc update replaces the files on disk; every daemon that had them
|
||||||
|
loaded keeps the old code until it restarts (NetOrk/netork#2750). On a hypervisor that
|
||||||
|
is where a restart instead of a reboot matters most. The command and its parse are
|
||||||
|
napalm-device-types' (``ServicesRestartMixin``); the driver only carries the command
|
||||||
|
over its exec path, which runs as root. A login that is not root gets no reading: it
|
||||||
|
would see only its own processes and read as clean.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import ServicesRestartMixin
|
||||||
|
|
||||||
|
from napalm_proxmox import ProxmoxBackupDriver
|
||||||
|
from napalm_proxmox.driver import ProxmoxDriver
|
||||||
|
|
||||||
|
#: A PVE node after an openssl update, read by the /proc scan (no needrestart):
|
||||||
|
#: pveproxy and a running VM's QEMU still map the old library, and so does a
|
||||||
|
#: container's own nginx, which the container updates itself.
|
||||||
|
WIRE = (
|
||||||
|
"RST_BEGIN\n[maps]\n"
|
||||||
|
"2101 pveproxy worker\n"
|
||||||
|
"3100 kvm\n"
|
||||||
|
"4100 nginx\n"
|
||||||
|
"[cgroups]\n"
|
||||||
|
"2101 0::/system.slice/pveproxy.service\n"
|
||||||
|
"3100 0::/qemu.slice/101.scope\n"
|
||||||
|
"4100 0::/lxc/200/ns/system.slice/nginx.service\n"
|
||||||
|
"RST_END\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("driver_class", [ProxmoxDriver, ProxmoxBackupDriver])
|
||||||
|
def test_both_drivers_declare_the_contract(driver_class):
|
||||||
|
assert issubclass(driver_class, ServicesRestartMixin)
|
||||||
|
|
||||||
|
|
||||||
|
def test_it_reads_as_root_over_the_exec_path(driver):
|
||||||
|
with patch.object(driver, "_exec_ssh_command", return_value=WIRE) as exec_:
|
||||||
|
reading = driver.get_services_need_restart()
|
||||||
|
|
||||||
|
[command] = [c.args[0] for c in exec_.call_args_list]
|
||||||
|
assert command.startswith('[ "$(id -u)" = 0 ] && sh -c \'')
|
||||||
|
assert reading == {
|
||||||
|
"source": "maps",
|
||||||
|
"units": ["pveproxy"],
|
||||||
|
"processes": [{"pid": 3100, "name": "kvm"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_backup_server_reads_it_the_same_way():
|
||||||
|
drv = ProxmoxBackupDriver("192.0.2.80", "root", "", optional_args={"token_name": "a!b"})
|
||||||
|
wire = "RST_BEGIN\n[needrestart]\nNEEDRESTART-SVC: proxmox-backup-proxy.service\nRST_END\n"
|
||||||
|
|
||||||
|
with patch.object(drv, "_exec_ssh_command", return_value=wire):
|
||||||
|
reading = drv.get_services_need_restart()
|
||||||
|
|
||||||
|
assert reading["units"] == ["proxmox-backup-proxy"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_login_other_than_root_gets_no_reading(driver):
|
||||||
|
"""The guard runs nothing but as root, so no report comes back and the parse raises."""
|
||||||
|
|
||||||
|
def as_this_user(command: str) -> str:
|
||||||
|
return subprocess.run(["sh", "-c", command], capture_output=True, text=True).stdout
|
||||||
|
|
||||||
|
if subprocess.run(["id", "-u"], capture_output=True, text=True).stdout.strip() == "0":
|
||||||
|
pytest.skip("runs as root here")
|
||||||
|
with patch.object(driver, "_exec_ssh_command", side_effect=as_this_user):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
driver.get_services_need_restart()
|
||||||
Reference in new issue
Block a user