Compare commits

...
Author SHA1 Message Date
Christian Manivong 93ba43071b docs(login): an account that only holds API tokens counts as a login (NetOrk/netork#662)
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Failing after 16s
driver / lowest (pull_request) Successful in 34s
driver / types (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 1m13s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Failing after 1m48s
driver / publish (pull_request) Skipped
The API says whether a user has a second factor, not whether it has a
password; a second factor on such an account leaves its tokens alone.
2026-11-29 00:29:54 +01:00
Christian Manivong f554e2cc79 feat(login): get_web_login_auth on PVE and PBS, a source per realm, 0.20.0 (NetOrk/netork#662)
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 37s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / security (pull_request) Successful in 53s
driver / build (pull_request) Successful in 49s
CI / driver (pull_request) Failing after 2m8s
driver / publish (pull_request) Skipped
A Proxmox login names its realm, so each realm with someone who can log in
is a source of napalm-device-types' WebLoginAuthDict. It asks for a password
and a one-time code when the PVE realm's own tfa is set, or when every
enabled, unexpired user of it has an enabled second factor (/access/tfa);
a password alone when one user has none; OpenID is external.

Both servers list only the caller in /access/users and /access/tfa when the
login may not see the others, so the driver checks /access/permissions
first: Sys.Audit or User.Modify on /access/groups on PVE, Sys.Audit on
/access/users on PBS. Without it the read raises PermissionError rather
than judge the server by one account.

Needs napalm-device-types 4.50.0.
2026-11-29 00:19:52 +01:00
christianmanivong 0598a183df Merge pull request 'feat: read the PVE firewall, the node's loaded ruleset, and the hardening reading (NetOrk/netork#2654, #2776)' (#80) from feature/pve-firewall-2654 into main
driver / types (push) Successful in 56s
driver / standard (push) Successful in 18s
driver / lint (push) Successful in 14s
driver / test (3.12) (push) Successful in 1m7s
driver / test (3.13) (push) Successful in 1m1s
driver / lowest (push) Successful in 33s
driver / build (push) Successful in 29s
driver / security (push) Successful in 1m5s
driver / publish (push) Successful in 29s
CI / driver (push) Successful in 3m15s
2026-11-28 08:30:02 +00:00
Christian Manivong b6bb13009f feat(hardening): get_hardening on both drivers over the exec path; needs device-types 4.48.0 (NetOrk/netork#2776)
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 1m7s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / lowest (pull_request) Successful in 37s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Successful in 2m29s
driver / publish (pull_request) Skipped
2026-11-28 08:01:27 +01:00
Christian Manivong 59839b4efa chore(release): 0.18.0
driver / lint (pull_request) Successful in 16s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 57s
driver / test (3.13) (pull_request) Successful in 59s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Successful in 2m21s
driver / publish (pull_request) Skipped
2026-11-28 05:02:52 +01:00
Christian Manivong c0453655b7 feat(firewall): read the PVE firewall at every level, and the node's loaded ruleset (NetOrk/netork#2654) 2026-11-28 04:59:05 +01:00
christianmanivong dc0d6345a8 Merge pull request 'feat(services-restart): which services on the node still run replaced code, as root (NetOrk/netork#2750)' (#77) from feature/services-need-restart into main
driver / types (push) Successful in 55s
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 15s
driver / test (3.12) (push) Successful in 1m10s
driver / lowest (push) Successful in 33s
driver / test (3.13) (push) Successful in 1m1s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m13s
driver / publish (push) Successful in 31s
CI / driver (push) Successful in 3m27s
2026-11-26 19:41:28 +00:00
Christian Manivong f9088bae3a Merge remote-tracking branch 'origin/main' into feature/services-need-restart
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m5s
driver / test (3.13) (pull_request) Successful in 1m9s
driver / test (3.12) (pull_request) Successful in 1m17s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Successful in 2m33s
driver / publish (pull_request) Skipped
# Conflicts:
#	CHANGELOG.md
#	README.md
#	pyproject.toml
2026-11-26 19:52:53 +01:00
christianmanivong ca44e4405d Merge pull request 'feat(certificates): get_certificates on both drivers, with ACME, 0.15.0 (NetOrk/netork#2656)' (#75) from feature/certificates-2656 into main
driver / types (push) Successful in 1m0s
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m11s
driver / lowest (push) Successful in 33s
driver / test (3.13) (push) Successful in 1m6s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m6s
driver / publish (push) Successful in 29s
CI / driver (push) Successful in 3m20s
2026-11-26 18:46:01 +00:00
Christian Manivong b37672a269 Merge origin/main (0.14.0) into feature/services-need-restart
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Failing after 25s
driver / test (3.12) (pull_request) Failing after 17s
driver / test (3.13) (pull_request) Failing after 17s
driver / lowest (pull_request) Failing after 18s
driver / security (pull_request) Failing after 37s
driver / build (pull_request) Successful in 32s
CI / driver (pull_request) Failing after 1m32s
driver / publish (pull_request) Skipped
Needs napalm-device-types 4.46.0: ServicesRestartMixin with an LXC
container's processes left out, and 0.14.0's CredentialExpiryMixin.
2026-11-26 19:26:58 +01:00
Christian Manivong bc5127b80f chore(release): 0.15.0
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / test (3.13) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Successful in 2m35s
driver / publish (pull_request) Skipped
2026-11-26 19:26:24 +01:00
Christian Manivong 24089412a7 Merge remote-tracking branch 'origin/main' into feature/certificates-2656
# Conflicts:
#	CHANGELOG.md
#	napalm_proxmox/driver.py
2026-11-26 19:26:13 +01:00
Christian Manivong 63ffc64050 chore(release): 0.16.0
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Failing after 58s
driver / test (3.12) (pull_request) Failing after 57s
driver / test (3.13) (pull_request) Failing after 52s
driver / lowest (pull_request) Failing after 27s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Failing after 2m45s
driver / publish (pull_request) Skipped
2026-11-26 19:01:33 +01:00
Christian Manivong b792f6d210 feat(services-restart): which services on the node still run replaced code, as root (NetOrk/netork#2750)
Both drivers mix in napalm-device-types' ServicesRestartMixin. The command
goes over the exec path, root's login as a rule, behind an id -u guard: a
login other than root would see only its own processes and read as
clean, so it prints nothing and the read raises. A running VM's QEMU is
listed as a process; an LXC container's processes are left out by the
parse, since a container updates itself. No stdin.
2026-11-26 18:55:13 +01:00
Christian Manivong 1db3fb329f chore(release): 0.14.0
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 50s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m7s
driver / lowest (pull_request) Successful in 33s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Successful in 2m21s
driver / publish (pull_request) Skipped
2026-11-26 17:59:41 +01:00
Christian Manivong ff4ccc4818 feat(certificates): get_certificates on both drivers, with ACME (NetOrk/netork#2656)
The node's TLS certificates from GET /nodes/{node}/certificates/info (PBS:
/nodes/localhost/certificates/info) in netOrk's certificate contract,
{name, issuer, valid_from, valid_to, in_use_by} with Unix timestamps, so
netOrk's expiry warnings cover a node's web UI and API certificate.

One more call, the node's config, says whether ACME renews the certificate
the proxy serves (acme). The PEM is not returned; unreadable certificates
are [] and an unreadable config reads as no ACME.
2026-11-26 17:59:35 +01:00
15 changed files with 1473 additions and 13 deletions

No files matched your search

+68
View File
@@ -7,6 +7,74 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.20.0] - 2026-11-29
### Added
- `get_web_login_auth()` on both drivers (napalm-device-types' `WebLoginAuthDict`,
NetOrk/netork#662): how the web interface lets people log in, one source per realm with
someone who can log in. A realm asks for a password and a one-time code when its own `tfa`
is set (PVE) or every enabled, unexpired user of it has an enabled second factor
(`/access/tfa`); a password alone when one user has none; OpenID is `external`. Read only.
The API login needs `Sys.Audit` or `User.Modify` on `/access/groups` on Proxmox VE and
`Sys.Audit` on `/access/users` on PBS: without it both list only the caller, so the driver
checks `/access/permissions` first and raises `PermissionError` rather than judge the
server by one account.
### Changed
- Needs napalm-device-types 4.50.0 or later (`WebLoginAuthDict`).
## [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
### Added
- `get_certificates()` on both drivers (NetOrk/netork#2656): the node's TLS certificates from
`GET /nodes/{node}/certificates/info` (PBS: `/nodes/localhost/certificates/info`) in
netOrk's certificate contract, `{name, issuer, valid_from, valid_to, in_use_by}` with Unix
timestamps, so netOrk's expiry warnings cover a node's web UI and API certificate.
`name` is the file name (`pve-root-ca.pem`, `pve-ssl.pem`, `pveproxy-ssl.pem`; `proxy.pem` on
PBS), `issuer` and `subject` the common names, `in_use_by` 1 for the certificate the proxy
serves. `acme` is true for the certificate ACME renews (`pveproxy-ssl.pem`, PBS `proxy.pem`)
when the node's config names a domain, read with one more call (`GET /nodes/{node}/config`);
an unreadable config reads as no ACME. The PEM is not returned. Unreadable certificates are
`[]`, as on OPNsense.
## [0.14.0] - 2026-11-26
### Added
+16 -2
View File
@@ -17,7 +17,7 @@ It supports all three networking domains of Proxmox VE:
- Python ≥ 3.12
- NAPALM ≥ 5.0.0
- napalm-device-types ≥ 4.22.0
- napalm-device-types ≥ 4.50.0
- proxmoxer ≥ 2.0.0
- netaddr ≥ 0.9.0
- requests ≥ 2.31.0
@@ -131,6 +131,12 @@ device = driver(
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
| `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 |
| `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, as root over SSH. On the backup server too |
| `get_web_login_auth` | how the web interface lets people log in (napalm-device-types' `WebLoginAuthDict`, NetOrk/netork#662): one source per realm with someone who can log in, by realm name. `password_otp` when the realm's own `tfa` is set or every enabled, unexpired user of it has an enabled second factor (`GET /access/tfa`: TOTP, WebAuthn, U2F, Yubico or recovery keys), `password` when one has none (often `root@pam`, or an account that only holds API tokens: the API does not say whether a user has a password, and a second factor on it does not affect its tokens), `external` for OpenID, `unknown` for a realm type the driver does not know. Needs `Sys.Audit` or `User.Modify` on `/access/groups` (the `PVEAuditor` role on `/` has it): without it PVE lists only the caller, so the driver raises `PermissionError` instead of judging the datacenter by one account. API tokens skip the second factor by design and are not web logins. On the backup server too |
**Not implemented** (raise `NotImplementedError`):
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
@@ -188,9 +194,11 @@ 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_disks`, `get_disk_pools` | `/nodes/localhost/disks/{list,zfs}` |
| `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 |
| `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_web_login_auth` | as on Proxmox VE, from `/access/domains`, `/access/users` and `/access/tfa`; PBS has no realm-wide `tfa`, so each user's second factors decide. Needs `Sys.Audit` on `/access/users` (the `Audit` role on `/` has it), checked first: without it PBS lists only the caller |
**API token rights.** Reading needs the role `Audit` on `/` (`Sys.Audit`,
`Datastore.Audit`); the remotes need `Remote.Audit` on `/remote` as well, which
@@ -235,6 +243,8 @@ napalm_proxmox/
├── backup_driver.py # ProxmoxBackupDriver (proxmox_backup)
├── 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
├── 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
tests/
├── conftest.py # Shared fixtures and mock API payloads
@@ -246,6 +256,10 @@ tests/
├── test_ovs_and_arp.py # get_arp_table, get_mac_address_table, ARP/OVS utils
├── 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_certificates.py # get_certificates on both drivers
├── test_firewall.py # get_pve_firewall and get_host_firewall
├── test_hardening.py # get_hardening on both drivers
├── test_web_login.py # get_web_login_auth on both drivers
├── test_utils.py # Unit tests for napalm_proxmox.utils
├── fixtures/pbs_api.json # What a Proxmox Backup Server 4.2 answered (sanitised)
├── pbs_fake.py # A proxmoxer stand-in answering from that recording
+10
View File
@@ -19,6 +19,7 @@ from napalm_device_types import (
BackupServerDriver,
EnsurePackageMixin,
FingerprintRule,
HardeningMixin,
HostStatusMixin,
KernelFactsMixin,
LicenseMixin,
@@ -27,6 +28,7 @@ from napalm_device_types import (
OpenSshServerMixin,
PortSpec,
ServicePackagesMixin,
ServicesRestartMixin,
StorageDriver,
SystemdServicesMixin,
SystemIdentityMixin,
@@ -38,12 +40,14 @@ except ImportError as exc: # pragma: no cover - proxmoxer is a dependency
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.certificates import PbsCertificatesMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.pbs_backups import ProxmoxBackupServerMixin
from napalm_proxmox.pbs_host import ProxmoxPbsHostMixin
from napalm_proxmox.running_backups import PbsRunningBackupsMixin
from napalm_proxmox.scheduled_jobs import PBS_PLATFORM_SOURCES, ProxmoxScheduledJobsMixin
from napalm_proxmox.time_sync import ProxmoxTimeSyncMixin
from napalm_proxmox.web_login import ProxmoxWebLoginMixin
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
logger = logging.getLogger(__name__)
@@ -59,12 +63,16 @@ class ProxmoxBackupDriver(
ProxmoxPbsHostMixin,
ProxmoxHostMixin,
ProxmoxTimeSyncMixin,
PbsCertificatesMixin,
ProxmoxWebLoginMixin,
BackupServerDriver,
StorageDriver,
KernelFactsMixin,
HardeningMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
LogSourcesMixin,
ServicesRestartMixin,
SystemIdentityMixin,
SystemdServicesMixin,
ProxmoxScheduledJobsMixin,
@@ -88,6 +96,8 @@ class ProxmoxBackupDriver(
FULL_UPGRADE = True
#: The backup server's own timer is ``platform``.
PLATFORM_SOURCES = PBS_PLATFORM_SOURCES
#: Shows every user and their second factors (``web_login``).
WEB_LOGIN_PRIVILEGE = ("/access/users", ("Sys.Audit",))
PORT_SPECS = [
PortSpec("https", 8007, weight=8.0),
]
+115
View File
@@ -0,0 +1,115 @@
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
driver set: one ``{name, issuer, valid_from, valid_to, in_use_by}`` per
certificate, the validity as Unix timestamps. netOrk's expiry warnings read it
from every driver that has it.
Both products list their certificates at ``GET /nodes/{node}/certificates/info``
(PBS: ``/nodes/localhost/certificates/info``). Proxmox VE has three: its
cluster's CA (``pve-root-ca.pem``), the node certificate the CA signed
(``pve-ssl.pem``) and, where one was uploaded or ACME ordered one,
``pveproxy-ssl.pem``, which ``pveproxy`` then serves instead. A backup server has
one, ``proxy.pem``. ``in_use_by`` is 1 for the certificate the web UI and API
serve, 0 for the others.
One call more, the node's ``config``, says whether ACME renews the served
certificate (``acme``): a domain is configured (``acmedomain0``…, or
``domains=`` in the older ``acme`` property). The daily update job of either
product renews it 30 days before it runs out, so an ACME certificate close to
its end means the renewal failed. A config that cannot be read means no ACME.
``name`` is the file name, as the products' own certificate lists show it;
``issuer`` and ``subject`` are the common names. The PEM never leaves the node
reading: netOrk keeps only what it shows.
"""
from __future__ import annotations
import logging
import re
from typing import TYPE_CHECKING, Any, ClassVar
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: ``CN=x`` in either form the products print a name in: ``/O=y/CN=x`` (PVE) or
#: ``CN = x, O = y`` (PBS).
_COMMON_NAME = re.compile(r"(?:^|[/,])\s*CN\s*=\s*([^/,]+)")
def common_name(name: str | None) -> str:
"""The CN of a distinguished name as Proxmox prints it, else the name itself."""
if not name:
return ""
found = _COMMON_NAME.search(name)
return found.group(1).strip() if found else name.strip()
def _seconds(value: Any) -> int:
try:
return int(value or 0)
except (TypeError, ValueError):
return 0
def acme_configured(config: _JsonDict) -> bool:
"""Whether the node's config names a domain for ACME to order a certificate for."""
if any(key.startswith("acmedomain") and value for key, value in config.items()):
return True
return "domains=" in str(config.get("acme") or "")
class ProxmoxCertificatesMixin:
"""``get_certificates`` for a Proxmox VE node; the backup server sets its file names."""
#: The files the proxy serves, the first one present wins.
served_certificates: ClassVar[tuple[str, ...]] = ("pveproxy-ssl.pem", "pve-ssl.pem")
#: The file an ACME order writes.
acme_certificate: ClassVar[str] = "pveproxy-ssl.pem"
_node_name: str
if TYPE_CHECKING: # pragma: no cover - the driver's (napalm_proxmox._base)
def _node_api(self) -> Any: ...
def get_certificates(self) -> list[_JsonDict]:
"""The node's certificates in netOrk's contract shape; ``[]`` when unreadable."""
try:
rows = self._node_api().certificates.info.get() or []
except Exception as exc:
logger.warning("get_certificates() failed on %s: %s", self._node_name, exc)
return []
files = [row.get("filename") for row in rows]
served = next((f for f in self.served_certificates if f in files), None)
acme = self.acme_certificate in files and self._acme_configured()
return [self._certificate(row, served, acme) for row in rows]
def _acme_configured(self) -> bool:
try:
return acme_configured(self._node_api().config.get() or {})
except Exception as exc:
logger.debug("node config unreadable on %s: %s", self._node_name, exc)
return False
def _certificate(self, row: _JsonDict, served: str | None, acme: bool) -> _JsonDict:
filename = str(row.get("filename") or "")
return {
"name": filename,
"issuer": common_name(row.get("issuer")),
"valid_from": _seconds(row.get("notbefore")),
"valid_to": _seconds(row.get("notafter")),
"in_use_by": 1 if filename == served else 0,
"subject": common_name(row.get("subject")),
"fingerprint": row.get("fingerprint") or "",
"acme": acme and filename == self.acme_certificate,
}
class PbsCertificatesMixin(ProxmoxCertificatesMixin):
"""A backup server has one certificate, ``proxy.pem``, which ACME renews too."""
served_certificates: ClassVar[tuple[str, ...]] = ("proxy.pem",)
acme_certificate: ClassVar[str] = "proxy.pem"
+14
View File
@@ -29,6 +29,8 @@ from napalm_device_types import (
AptProxyMixin,
EnsurePackageMixin,
FingerprintRule,
HardeningMixin,
HostFirewallMixin,
HostStatusMixin,
HypervisorDriver,
KernelFactsMixin,
@@ -38,6 +40,7 @@ from napalm_device_types import (
OpenSshServerMixin,
PortSpec,
ServicePackagesMixin,
ServicesRestartMixin,
SnmpAgentMixin,
SystemdServicesMixin,
SystemIdentityMixin,
@@ -49,9 +52,11 @@ except ImportError as exc:
raise ImportError("proxmoxer is required: pip install proxmoxer") from exc
from napalm_proxmox._base import ProxmoxBase
from napalm_proxmox.certificates import ProxmoxCertificatesMixin
from napalm_proxmox.cluster_mixin import ProxmoxClusterMixin
from napalm_proxmox.config_mixin import ProxmoxConfigMixin
from napalm_proxmox.credential_expiry import ProxmoxCredentialExpiryMixin
from napalm_proxmox.firewall_mixin import ProxmoxFirewallMixin
from napalm_proxmox.host_mixin import ProxmoxHostMixin
from napalm_proxmox.interfaces_mixin import ProxmoxInterfaceMixin
from napalm_proxmox.lldp_mixin import ProxmoxLLDPMixin
@@ -67,6 +72,7 @@ from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
from napalm_proxmox.web_login import ProxmoxWebLoginMixin
from napalm_proxmox.zabbix_agent import ProxmoxZabbixAgentMixin
logger = logging.getLogger(__name__)
@@ -96,16 +102,22 @@ class ProxmoxDriver(
ProxmoxRoutingMixin,
ProxmoxSystemMixin,
ProxmoxHostMixin,
ProxmoxFirewallMixin,
KernelFactsMixin,
HostFirewallMixin,
HardeningMixin,
ServicePackagesMixin,
ListeningSocketsMixin,
LogSourcesMixin,
ServicesRestartMixin,
SystemIdentityMixin,
SystemdServicesMixin,
ProxmoxScheduledJobsMixin,
ProxmoxRunningBackupsMixin,
ProxmoxTimeSyncMixin,
ProxmoxCertificatesMixin,
ProxmoxCredentialExpiryMixin,
ProxmoxWebLoginMixin,
ProxmoxUpdateHistoryMixin,
HostStatusMixin,
LicenseMixin,
@@ -131,6 +143,8 @@ class ProxmoxDriver(
FULL_UPGRADE = True
#: Proxmox VE's own timers and cron file are ``platform``.
PLATFORM_SOURCES = PVE_PLATFORM_SOURCES
#: Shows every user and their second factors (``web_login``).
WEB_LOGIN_PRIVILEGE = ("/access/groups", ("Sys.Audit", "User.Modify"))
#: ``/etc/cron.d/vzdump`` links into ``/etc/pve`` (pmxcfs); its lines are only run.
RUN_ONLY_SOURCES = ("/etc/cron.d/vzdump",)
PORT_SPECS = [
+190
View File
@@ -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(),
}
+24 -5
View File
@@ -1,11 +1,11 @@
"""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
packages, system identity, listening sockets, systemd services, host status,
apt's proxy), packages and APT updates, the subscription, root file writes,
and restarting or shutting the host down. All of it is the same on both
products: the same ``/nodes/{node}/apt``, ``/subscription`` and ``/status``
endpoints, and root's shell over the driver's own SSH session.
packages, system identity, listening sockets, the services that still run replaced
code, systemd services, host status, apt's proxy), packages and APT updates, the
subscription, root file writes, and restarting or shutting the host down. All of it
is the same on both products: the same ``/nodes/{node}/apt``, ``/subscription`` and
``/status`` endpoints, and root's shell over the driver's own SSH session.
"""
from __future__ import annotations
@@ -72,6 +72,18 @@ class ProxmoxHostMixin:
"""The transport for ``KernelFactsMixin.get_kernel_facts``: the exec path."""
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:
"""The transport for ``ServicePackagesMixin.get_service_packages``: the exec path."""
return str(self._exec_ssh_command(command))
@@ -91,6 +103,13 @@ class ProxmoxHostMixin:
which runs as root either way."""
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]:
"""Return installed Debian packages with available-update info.
+172
View File
@@ -0,0 +1,172 @@
"""How people log in to the web interface of Proxmox VE and PBS (NetOrk/netork#662).
napalm-device-types' ``WebLoginAuthDict``: the sources a login is checked against,
each with what it asks for. Read only.
**A realm is a source.** Every login names its realm (``root@pam``, ``alice@pve``)
and is checked by that realm alone, so each realm with someone who can log in is
one source: ``{"name": "pam", "kind": "pam", "factors": "password"}``. The sources
come in name order; the login box offers all of them.
**What a realm asks for** depends on its users. PVE and PBS ask every user for a
second factor who has one: an enabled TOTP, WebAuthn, U2F or Yubico entry, or
recovery keys (proxmox-tfa's ``TfaUserData::challenge``). Without one, the
password alone gets in. So a realm is
- ``external`` when it is OpenID: the provider decides, and netOrk cannot see how;
- ``unknown`` when it is of a kind this driver does not know;
- ``password_otp`` when the PVE realm's own ``tfa`` is set (``oath`` or
``yubico``): PVE then refuses a user without a second factor ("missing required
2nd keys", ``PVE::AccessControl::authenticate_2nd_new_do``);
- ``password_otp`` when every user of the realm who can log in has a second factor;
- ``password`` otherwise. ``root@pam`` always exists and is often the one without.
The API says whether a user has a second factor, not whether it has a password, so
an account that only holds API tokens counts as a login too. Giving it a second
factor is the fix: its tokens do not ask for one.
A user who is disabled or whose account has expired cannot log in and does not
count; a realm without anyone who can is no source (except OpenID, which can
create its users at their first login). API tokens bypass the second factor by
design; they are API access, not a web login, and are left out.
**The privilege the API login needs.** Both servers answer ``/access/users`` and
``/access/tfa`` with the caller alone, not with a 403, when the caller may not
see the others. A reading from such a login would judge the datacenter by one
account, so the driver checks the privilege first (``/access/permissions``) and
raises ``PermissionError`` without it:
- **Proxmox VE:** ``Sys.Audit`` or ``User.Modify`` on ``/access/groups``
(``PVE/API2/User.pm`` and ``TFA.pm``), e.g. the ``PVEAuditor`` role on ``/``.
- **PBS:** ``Sys.Audit`` on ``/access/users`` (``src/api2/access/user.rs`` and
``tfa.rs``), e.g. the ``Audit`` role on ``/``.
A privilege-separated token needs it itself, not only its user.
"""
from __future__ import annotations
import time
from collections.abc import Iterable
from typing import Any
from napalm_device_types import LoginFactors, LoginSourceDict, WebLoginAuthDict
from proxmoxer.core import ResourceException
_JsonDict = dict[str, Any]
#: Realm kinds that check a password themselves, on PVE and PBS.
PASSWORD_REALMS = frozenset({"pam", "pve", "pbs", "ldap", "ad"})
#: The built-in realms, which PBS's ``/access/domains`` may leave out.
BUILT_IN_REALMS = {"pam": "pam", "pve": "pve", "pbs": "pbs"}
def _active(user: _JsonDict, now: int) -> bool:
"""Whether *user* can log in: enabled (``1``/``true``, the default) and not expired."""
expire = int(user.get("expire") or 0)
return bool(user.get("enable", True)) and not (expire and expire <= now)
def _with_second_factor(tfa: Iterable[_JsonDict]) -> set[str]:
"""The users with at least one enabled TFA entry; ``enable`` is only sent when off."""
return {
str(user.get("userid"))
for user in tfa
if any(entry.get("enable", True) for entry in user.get("entries") or ())
}
def _realm_of(userid: str) -> str:
return userid.rpartition("@")[2]
def _factors(kind: str, realm_tfa: bool, members: list[str], second: set[str]) -> LoginFactors:
if kind == "openid":
return "external"
if kind not in PASSWORD_REALMS:
return "unknown"
if realm_tfa or all(userid in second for userid in members):
return "password_otp"
return "password"
def web_login_sources(
*,
realms: list[_JsonDict],
users: list[_JsonDict],
tfa: list[_JsonDict],
now: int,
) -> list[LoginSourceDict]:
"""The realms a login can name, each with what it asks for, by realm name.
*realms* is ``/access/domains``, *users* ``/access/users`` and *tfa*
``/access/tfa``, each as the server answered; *now* is unix seconds.
"""
configured = {str(r.get("realm")): r for r in realms if r.get("realm")}
members: dict[str, list[str]] = {}
kinds: dict[str, str] = {}
for user in users:
userid = str(user.get("userid") or "")
realm = _realm_of(userid)
if user.get("realm-type"):
kinds.setdefault(realm, str(user["realm-type"]))
if userid and _active(user, now):
members.setdefault(realm, []).append(userid)
second = _with_second_factor(tfa)
sources: list[LoginSourceDict] = []
for name in sorted(set(configured) | set(members)):
config = configured.get(name, {})
kind = str(config.get("type") or kinds.get(name) or BUILT_IN_REALMS.get(name, ""))
logins = members.get(name, [])
if not logins and kind in PASSWORD_REALMS:
continue
factors = _factors(kind, bool(config.get("tfa")), logins, second)
sources.append({"name": name, "kind": kind, "factors": factors})
return sources
class ProxmoxWebLoginMixin:
"""``get_web_login_auth`` for both drivers; each names the privilege its server
filters the user lists by."""
_api: Any
#: The ACL path and the privileges, any one of which shows every user.
WEB_LOGIN_PRIVILEGE: tuple[str, tuple[str, ...]]
def get_web_login_auth(self) -> WebLoginAuthDict:
"""The realms a login can name, each with what it asks for.
Example::
{"sources": [{"name": "pam", "kind": "pam", "factors": "password"}]}
:raises PermissionError: when the API login lacks the privilege that shows
every user (see the module docstring), or a read is refused.
"""
self._require_user_audit()
return {
"sources": web_login_sources(
realms=self._web_login_read("access/domains"),
users=self._web_login_read("access/users"),
tfa=self._web_login_read("access/tfa"),
now=int(time.time()),
)
}
def _require_user_audit(self) -> None:
path, privileges = self.WEB_LOGIN_PRIVILEGE
held = self._web_login_read("access/permissions", path=path)
granted = held.get(path) if isinstance(held, dict) else None
if not any(privilege in (granted or {}) for privilege in privileges):
raise PermissionError(
f"the API login lacks {' or '.join(privileges)} on {path}; the server "
"would list only the login's own user"
)
def _web_login_read(self, endpoint: str, /, **params: Any) -> Any:
try:
return self._api.get(endpoint, **params) or []
except ResourceException as exc:
if exc.status_code in (401, 403):
raise PermissionError(f"GET {endpoint} was refused: {exc}") from exc
raise
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-proxmox"
version = "0.14.0"
version = "0.20.0"
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
readme = "README.md"
license = "Apache-2.0"
@@ -21,7 +21,7 @@ classifiers = [
requires-python = ">=3.12"
dependencies = [
"napalm>=5.0.0",
"napalm_device_types>=4.44.0", # CredentialExpiryMixin, UpdateHistoryDict, VMDict.uid
"napalm_device_types>=4.50.0", # WebLoginAuthDict; HardeningMixin
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
"proxmoxer>=2.0.0",
"netaddr>=0.9.0",
+4 -4
View File
@@ -82,16 +82,16 @@ class FakePbsApi:
raise AttributeError(name)
return _Resource(self, name)
def get(self, path: str, **params: Any) -> Any:
def get(self, path: str, /, **params: Any) -> Any:
return self._answer("GET", path, params)
def post(self, path: str, **params: Any) -> Any:
def post(self, path: str, /, **params: Any) -> Any:
return self._answer("POST", path, params)
def put(self, path: str, **params: Any) -> Any:
def put(self, path: str, /, **params: Any) -> Any:
return self._answer("PUT", path, params)
def delete(self, path: str, **params: Any) -> Any:
def delete(self, path: str, /, **params: Any) -> Any:
return self._answer("DELETE", path, params)
+255
View File
@@ -0,0 +1,255 @@
"""The node's TLS certificates and whether ACME renews them (NetOrk/netork#2656).
``get_certificates`` answers netOrk's certificate contract, the one the OPNsense
driver set: ``{name, issuer, valid_from, valid_to, in_use_by}`` with Unix
timestamps, so netOrk's expiry warnings apply to a Proxmox node as to any device.
The source is ``GET /nodes/{node}/certificates/info`` (PBS:
``/nodes/localhost/certificates/info``), and one more call, the node's
``config``, tells whether ACME renews the certificate the proxy serves.
The responses are shaped as Proxmox VE 8 and PBS 3 answer (``pvenode cert info``,
``proxmox-backup-manager cert info``), the PEM left out.
"""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from proxmoxer.core import ResourceException
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
from tests.conftest import _build_mock_api
from tests.pbs_fake import FakePbsApi
ROOT_CA = {
"filename": "pve-root-ca.pem",
"fingerprint": "5E:41:...:0A",
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
"notafter": 2017526400,
"notbefore": 1702166400,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": [],
"subject": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
}
PVE_SSL = {
"filename": "pve-ssl.pem",
"fingerprint": "A1:B2:...:C3",
"issuer": "/CN=Proxmox Virtual Environment/OU=2d4e8a1c-7b9f/O=PVE Cluster Manager CA",
"notafter": 1765238400,
"notbefore": 1702166400,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": [
"127.0.0.1",
"0000:0000:0000:0000:0000:0000:0000:0001",
"localhost",
"pve1",
"pve1.example.com",
],
"subject": "/OU=PVE Cluster Node/O=Proxmox Virtual Environment/CN=pve1.example.com",
}
PVEPROXY_SSL = {
"filename": "pveproxy-ssl.pem",
"fingerprint": "D4:E5:...:F6",
"issuer": "/C=US/O=Let's Encrypt/CN=R11",
"notafter": 1771977600,
"notbefore": 1764201600,
"public-key-bits": 2048,
"public-key-type": "rsaEncryption",
"san": ["pve1.example.com"],
"subject": "/CN=pve1.example.com",
}
ACME_CONFIG = {
"acme": "account=default",
"acmedomain0": "domain=pve1.example.com,plugin=cloudflare",
"digest": "4f0c...",
}
PROXY_PEM = {
"filename": "proxy.pem",
"fingerprint": "0A:1B:...:2C",
"issuer": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
"notafter": 2017526400,
"notbefore": 1702166400,
"public-key-bits": 4096,
"public-key-type": "rsaEncryption",
"san": ["IP Address:127.0.0.1", "DNS:localhost", "DNS:pbs1", "DNS:pbs1.example.com"],
"subject": "CN = pbs1.example.com, O = Proxmox Backup Server, OU = 4c6e1d2a",
}
def _pve(info: Any, config: Any = None) -> tuple[ProxmoxDriver, Any]:
driver = ProxmoxDriver(
"pve1.example.com", "root", "secret", optional_args={"verify_ssl": False}
)
api = _build_mock_api()
node = api.nodes.return_value
if isinstance(info, Exception):
node.certificates.info.get.side_effect = info
else:
node.certificates.info.get.return_value = info
if isinstance(config, Exception):
node.config.get.side_effect = config
else:
node.config.get.return_value = config or {}
with patch("napalm_proxmox.driver.ProxmoxAPI", return_value=api):
driver.open()
return driver, api
def _pbs(**responses: Any) -> tuple[ProxmoxBackupDriver, FakePbsApi]:
api = FakePbsApi(**responses)
driver = ProxmoxBackupDriver("pbs1.example.com", "root@pam", "secret")
with patch("napalm_proxmox.backup_driver.ProxmoxAPI", return_value=api):
driver.open()
return driver, api
# -- Proxmox VE -------------------------------------------------------------------------------
def test_every_certificate_of_the_node_in_the_contract_shape() -> None:
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL])
certs = driver.get_certificates()
api.nodes.assert_any_call("pve1")
assert certs == [
{
"name": "pve-root-ca.pem",
"issuer": "Proxmox Virtual Environment",
"valid_from": 1702166400,
"valid_to": 2017526400,
"in_use_by": 0,
"subject": "Proxmox Virtual Environment",
"fingerprint": "5E:41:...:0A",
"acme": False,
},
{
"name": "pve-ssl.pem",
"issuer": "Proxmox Virtual Environment",
"valid_from": 1702166400,
"valid_to": 1765238400,
"in_use_by": 0,
"subject": "pve1.example.com",
"fingerprint": "A1:B2:...:C3",
"acme": False,
},
{
"name": "pveproxy-ssl.pem",
"issuer": "R11",
"valid_from": 1764201600,
"valid_to": 1771977600,
"in_use_by": 1,
"subject": "pve1.example.com",
"fingerprint": "D4:E5:...:F6",
"acme": False,
},
]
def test_the_timestamps_are_integers() -> None:
driver, _ = _pve([{**PVE_SSL, "notafter": "1765238400", "notbefore": None}])
(cert,) = driver.get_certificates()
assert cert["valid_to"] == 1765238400
assert cert["valid_from"] == 0
def test_without_a_custom_certificate_pveproxy_serves_pve_ssl() -> None:
driver, _ = _pve([ROOT_CA, PVE_SSL])
in_use = {c["name"]: c["in_use_by"] for c in driver.get_certificates()}
assert in_use == {"pve-root-ca.pem": 0, "pve-ssl.pem": 1}
def test_acme_renews_the_certificate_pveproxy_serves() -> None:
driver, api = _pve([ROOT_CA, PVE_SSL, PVEPROXY_SSL], ACME_CONFIG)
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
assert acme == {"pve-root-ca.pem": False, "pve-ssl.pem": False, "pveproxy-ssl.pem": True}
# One call more than the certificates: the node's config.
api.nodes.return_value.config.get.assert_called_once_with()
def test_acme_in_its_older_form_names_the_domains_in_acme() -> None:
config = {"acme": "account=default,domains=pve1.example.com"}
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], config)
acme = {c["name"]: c["acme"] for c in driver.get_certificates()}
assert acme == {"pve-ssl.pem": False, "pveproxy-ssl.pem": True}
def test_an_acme_account_without_domains_renews_nothing() -> None:
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], {"acme": "account=default"})
assert not any(c["acme"] for c in driver.get_certificates())
def test_acme_never_renews_pve_ssl() -> None:
# Without pveproxy-ssl.pem there is no ACME certificate yet, even with domains set.
driver, _ = _pve([ROOT_CA, PVE_SSL], ACME_CONFIG)
assert not any(c["acme"] for c in driver.get_certificates())
def test_an_unreadable_config_reads_as_no_acme() -> None:
driver, _ = _pve([PVE_SSL, PVEPROXY_SSL], ResourceException(403, "Forbidden", "no Sys.Audit"))
certs = driver.get_certificates()
assert [c["name"] for c in certs] == ["pve-ssl.pem", "pveproxy-ssl.pem"]
assert not any(c["acme"] for c in certs)
def test_unreadable_certificates_are_none_rather_than_a_failed_poll() -> None:
driver, api = _pve(ResourceException(403, "Forbidden", "no Sys.Audit"))
assert driver.get_certificates() == []
api.nodes.return_value.config.get.assert_not_called()
# -- Proxmox Backup Server ---------------------------------------------------------------------
def test_the_backup_server_reads_localhost() -> None:
driver, api = _pbs(
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": {}}
)
assert driver.get_certificates() == [
{
"name": "proxy.pem",
"issuer": "pbs1.example.com",
"valid_from": 1702166400,
"valid_to": 2017526400,
"in_use_by": 1,
"subject": "pbs1.example.com",
"fingerprint": "0A:1B:...:2C",
"acme": False,
}
]
assert ("GET", "nodes/localhost/certificates/info", {}) in api.calls
def test_acme_renews_the_backup_servers_proxy_certificate() -> None:
config = {"acme": "account=default", "acmedomain0": "domain=pbs1.example.com"}
driver, _ = _pbs(
**{"nodes/localhost/certificates/info": [PROXY_PEM], "nodes/localhost/config": config}
)
(cert,) = driver.get_certificates()
assert cert["acme"] is True
@pytest.mark.parametrize("cls", [ProxmoxDriver, ProxmoxBackupDriver], ids=["pve", "pbs"])
def test_both_drivers_have_it(cls: type) -> None:
assert callable(getattr(cls, "get_certificates", None))
+197
View File
@@ -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]
+71
View File
@@ -0,0 +1,71 @@
"""`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()
+76
View File
@@ -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()
+259
View File
@@ -0,0 +1,259 @@
"""get_web_login_auth: how the web interface lets people log in (NetOrk/netork#662).
A Proxmox login names its realm (``root@pam``, ``alice@pve``), so every realm
with someone who can log in is a source. What a source asks for depends on its
users: PVE and PBS ask for a second factor of every user who has one
(``/access/tfa``), and a PVE realm whose ``tfa`` is set refuses users without
one. OpenID hands the login to its provider.
The answers follow the API schema of pve-access-control (``PVE/API2/User.pm``,
``TFA.pm``, ``Domains.pm``) and proxmox-backup (``src/api2/access/``). A TFA
entry carries ``enable`` only when it is off (proxmox-tfa's ``TfaInfo``); PVE
writes ``enable`` on a user as 0 or 1, PBS as a boolean or not at all.
"""
from __future__ import annotations
from typing import Any
import pytest
from napalm_device_types import WebLoginAuthDict
from napalm_proxmox import ProxmoxBackupDriver, ProxmoxDriver
from napalm_proxmox.web_login import web_login_sources
from tests.pbs_fake import FakePbsApi, forbidden
NOW = 1_800_000_000
PAST = NOW - 86_400
FUTURE = NOW + 86_400
def _user(userid: str, **fields: Any) -> dict[str, Any]:
return {"userid": userid, "enable": 1, "expire": 0, **fields}
def _totp(userid: str, **fields: Any) -> dict[str, Any]:
entry = {"type": "totp", "id": "totp-1", "description": "phone", "created": PAST, **fields}
return {"userid": userid, "entries": [entry]}
def _source(name: str, kind: str, factors: str) -> dict[str, str]:
return {"name": name, "kind": kind, "factors": factors}
PVE_REALMS = [
{"realm": "pve", "type": "pve", "comment": "Proxmox VE authentication server"},
{"realm": "pam", "type": "pam", "comment": "Linux PAM standard authentication"},
]
def _sources(realms=PVE_REALMS, users=(), tfa=()) -> list:
return web_login_sources(realms=list(realms), users=list(users), tfa=list(tfa), now=NOW)
class TestRealms:
def test_a_user_without_a_second_factor_makes_the_realm_a_password(self):
assert _sources(users=[_user("root@pam")]) == [_source("pam", "pam", "password")]
def test_every_user_with_a_second_factor_makes_it_two_factors(self):
users = [_user("root@pam"), _user("ops@pam")]
tfa = [_totp("root@pam"), _totp("ops@pam")]
assert _sources(users=users, tfa=tfa) == [_source("pam", "pam", "password_otp")]
def test_one_user_without_is_enough_for_a_password(self):
users = [_user("root@pam"), _user("ops@pam")]
assert _sources(users=users, tfa=[_totp("ops@pam")]) == [_source("pam", "pam", "password")]
def test_each_realm_with_a_user_is_a_source_in_name_order(self):
users = [_user("root@pam"), _user("alice@pve")]
assert _sources(users=users, tfa=[_totp("alice@pve")]) == [
_source("pam", "pam", "password"),
_source("pve", "pve", "password_otp"),
]
def test_a_realm_nobody_can_log_in_to_is_no_source(self):
users = [_user("root@pam"), _user("old@pve", enable=0), _user("gone@pve", expire=PAST)]
assert _sources(users=users, tfa=[_totp("root@pam")]) == [
_source("pam", "pam", "password_otp")
]
def test_an_account_that_expires_later_still_logs_in(self):
users = [_user("root@pam", expire=FUTURE)]
assert _sources(users=users) == [_source("pam", "pam", "password")]
def test_a_realm_that_requires_a_second_factor_counts_as_two(self):
realms = [*PVE_REALMS, {"realm": "corp", "type": "ad", "tfa": "oath"}]
users = [_user("root@pam"), _user("bob@corp")]
assert _sources(realms, users, [_totp("root@pam")]) == [
_source("corp", "ad", "password_otp"),
_source("pam", "pam", "password_otp"),
]
def test_a_yubico_realm_requires_its_otp_too(self):
realms = [{"realm": "pve", "type": "pve", "tfa": "yubico"}]
assert _sources(realms, [_user("bob@pve")]) == [_source("pve", "pve", "password_otp")]
def test_an_openid_realm_is_its_providers_call(self):
realms = [*PVE_REALMS, {"realm": "sso", "type": "openid"}]
users = [_user("root@pam")]
assert _sources(realms, users, [_totp("root@pam")]) == [
_source("pam", "pam", "password_otp"),
_source("sso", "openid", "external"),
]
def test_an_unknown_realm_type_is_unknown(self):
realms = [{"realm": "pam", "type": "pam"}, {"realm": "x", "type": "plugin"}]
assert _sources(realms, [_user("root@pam")], [_totp("root@pam")]) == [
_source("pam", "pam", "password_otp"),
_source("x", "plugin", "unknown"),
]
def test_a_realm_missing_from_the_list_takes_the_users_realm_type(self):
"""PVE names it on each user; PBS's domains.cfg may leave out pam and pbs."""
users = [_user("root@pam"), _user("ci@pbs"), _user("x@gone", **{"realm-type": "ldap"})]
assert _sources([], users) == [
_source("gone", "ldap", "password"),
_source("pam", "pam", "password"),
_source("pbs", "pbs", "password"),
]
def test_a_realm_of_no_known_type_is_unknown(self):
assert _sources([], [_user("x@where")]) == [_source("where", "", "unknown")]
class TestSecondFactors:
def test_a_disabled_entry_is_no_second_factor(self):
tfa = [_totp("root@pam", enable=False)]
assert _sources(users=[_user("root@pam")], tfa=tfa) == [_source("pam", "pam", "password")]
@pytest.mark.parametrize("kind", ["totp", "webauthn", "u2f", "yubico", "recovery"])
def test_every_kind_of_entry_is_a_second_factor(self, kind):
tfa = [{"userid": "root@pam", "entries": [{"type": kind, "id": kind}]}]
assert _sources(users=[_user("root@pam")], tfa=tfa)[0]["factors"] == "password_otp"
def test_a_user_with_an_empty_entry_list_has_none(self):
tfa = [{"userid": "root@pam", "entries": []}]
assert _sources(users=[_user("root@pam")], tfa=tfa)[0]["factors"] == "password"
def test_pbs_booleans_and_missing_fields(self):
users = [{"userid": "root@pam"}, {"userid": "old@pbs", "enable": False}]
assert _sources([], users) == [_source("pam", "pam", "password")]
class FakeApi(FakePbsApi):
"""The same fake, without the recorded PBS answers."""
def __init__(self, **responses: Any) -> None:
super().__init__()
self.responses = responses
def _pve(**responses: Any) -> ProxmoxDriver:
drv = ProxmoxDriver("pve1", "netork@pve", "secret")
drv._api = FakeApi(**responses)
return drv
def _pbs(**responses: Any) -> ProxmoxBackupDriver:
drv = ProxmoxBackupDriver("pbs1", "netork@pbs", "secret")
drv._api = FakePbsApi(**responses)
return drv
PVE_ANSWERS: dict[str, Any] = {
"access/permissions?path=/access/groups": {"/access/groups": {"Sys.Audit": 1}},
"access/domains": PVE_REALMS,
"access/users": [_user("root@pam", **{"realm-type": "pam"})],
"access/tfa": [_totp("root@pam")],
}
PBS_ANSWERS: dict[str, Any] = {
"access/permissions?path=/access/users": {"/access/users": {"Sys.Audit": True}},
"access/domains": [
{"realm": "pam", "type": "pam", "comment": "Linux PAM standard authentication"},
{"realm": "pbs", "type": "pbs", "comment": "Proxmox Backup authentication server"},
],
"access/users": [{"userid": "root@pam", "enable": True, "expire": 0}],
"access/tfa": [],
}
class TestProxmoxVe:
def test_reads_users_their_second_factors_and_the_realms(self):
drv = _pve(**PVE_ANSWERS)
reading: WebLoginAuthDict = drv.get_web_login_auth()
assert reading == {"sources": [_source("pam", "pam", "password_otp")]}
assert [path for _, path, _ in drv._api.calls] == [
"access/permissions",
"access/domains",
"access/users",
"access/tfa",
]
@pytest.mark.parametrize("privilege", ["Sys.Audit", "User.Modify"])
def test_either_privilege_on_access_groups_shows_every_user(self, privilege):
drv = _pve(
**{
**PVE_ANSWERS,
"access/permissions?path=/access/groups": {"/access/groups": {privilege: 0}},
}
)
assert drv.get_web_login_auth()["sources"]
def test_without_the_privilege_the_lists_would_be_filtered_so_it_is_not_read(self):
"""PVE answers ``/access/users`` and ``/access/tfa`` with the caller alone,
not with a 403: a token that sees only itself must not pass for a datacenter."""
drv = _pve(**{**PVE_ANSWERS, "access/permissions?path=/access/groups": {}})
with pytest.raises(PermissionError, match=r"Sys\.Audit.*/access/groups"):
drv.get_web_login_auth()
assert [path for _, path, _ in drv._api.calls] == ["access/permissions"]
def test_a_refused_read_is_a_permission_error(self):
drv = _pve(**{**PVE_ANSWERS, "access/tfa": forbidden()})
with pytest.raises(PermissionError):
drv.get_web_login_auth()
class TestProxmoxBackupServer:
def test_reads_users_their_second_factors_and_the_realms(self):
drv = _pbs(**PBS_ANSWERS)
assert drv.get_web_login_auth() == {"sources": [_source("pam", "pam", "password")]}
def test_a_token_without_sys_audit_on_access_users_is_not_read(self):
drv = _pbs(
**{
**PBS_ANSWERS,
"access/permissions?path=/access/users": {"/access/users": {"User.Modify": True}},
}
)
with pytest.raises(PermissionError, match=r"Sys\.Audit.*/access/users"):
drv.get_web_login_auth()
def test_another_failure_propagates(self):
from proxmoxer.core import ResourceException
drv = _pbs(**{**PBS_ANSWERS, "access/users": ResourceException(500, "Error", "boom")})
with pytest.raises(ResourceException):
drv.get_web_login_auth()