39 Commits
Author SHA1 Message Date
christianmanivong e0be871207 Merge pull request 'feat(power): shut the firewall down through its firmware API (NetOrk/netork#2841)' (#52) from feature/host-shutdown-2841 into main
driver / lint (push) Successful in 13s
driver / lowest (push) Successful in 28s
driver / test (3.13) (push) Successful in 58s
driver / build (push) Successful in 28s
driver / security (push) Successful in 52s
driver / publish (push) Skipped
driver / standard (push) Successful in 15s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 1m5s
CI / driver (push) Successful in 2m3s
2026-11-29 22:07:28 +00:00
Christian Manivong 02336c20ed refactor(power): the firmware's reboot, power-off and status in a mixin of their own (NetOrk/netork#2841)
driver / lowest (pull_request) Successful in 27s
driver / test (3.13) (pull_request) Successful in 59s
driver / test (3.12) (pull_request) Successful in 1m4s
driver / build (pull_request) Successful in 24s
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Successful in 2m4s
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 54s
driver / publish (pull_request) Skipped
opnsense.py must not grow (python_file_lines, 3022): reboot_host,
shutdown_host and get_host_status, all three the firmware controller's,
move to firmware_power.py (OPNsenseFirmwarePowerMixin), and opnsense.py
shrinks to 3019 lines, recorded in the baseline. Behaviour unchanged; the
645 tests pass as they were.
2026-11-29 23:00:57 +01:00
Christian Manivong 94279de382 feat(power): shut the firewall down through its firmware API (NetOrk/netork#2841)
driver / lowest (pull_request) Successful in 32s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Failing after 1m59s
driver / standard (pull_request) Failing after 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 50s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / publish (pull_request) Skipped
shutdown_host() posts /api/core/firmware/poweroff, the clean halt with
power off that OPNsense has had since 16.1.15, next to the
firmware/reboot that reboot_host() uses. A refused request raises
RuntimeError with the firewall's answer.
2026-11-29 11:32:33 +01:00
christianmanivong 2374d57b7d Merge pull request 'feat(login-auth): how people log in to the firewall, from config.xml (NetOrk/netork#662)' (#51) from feature/login-auth into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m3s
driver / lowest (push) Successful in 31s
driver / build (push) Successful in 28s
driver / security (push) Successful in 1m1s
driver / publish (push) Skipped
driver / standard (push) Failing after 17s
driver / types (push) Successful in 1m6s
driver / test (3.12) (push) Successful in 1m7s
CI / driver (push) Failing after 2m21s
2026-11-28 07:52:53 +00:00
Christian Manivong 6c612a427b feat(login-auth): how people log in to the firewall, from config.xml (NetOrk/netork#662)
driver / test (3.13) (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 31s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Failing after 2m21s
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Failing after 18s
driver / types (pull_request) Successful in 58s
driver / publish (pull_request) Skipped
get_web_login_auth() names the auth servers <system><webgui><authmode> tries,
in order (the Local Database when it names none), each with what it asks for:
password for local, ldap and voucher, password_otp for totp and ldap-totp,
external for radius, unknown otherwise. A name no server has is skipped, as
OPNsense skips it. get_ssh_server_auth() reads <system><ssh> as
openssh_configure_do writes sshd_config: on only with enabled, password and
challenge-response login with passwordauth, root with permitrootlogin, a key
always. An SSH password goes through the same servers (password_sources).
Needs napalm-device-types 4.50.0.
2026-11-28 08:03:18 +01:00
christianmanivong 6c1aaf1690 Merge pull request 'fix(radius): the getters raise when the firewall does not answer (#49)' (#50) from fix/radius-read-errors into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 55s
driver / lowest (push) Successful in 34s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m30s
driver / publish (push) Skipped
driver / standard (push) Failing after 15s
driver / types (push) Successful in 56s
driver / test (3.12) (push) Successful in 1m3s
CI / driver (push) Failing after 3m2s
2026-11-15 19:24:02 +00:00
Christian Manivong 9c31afd5d7 fix(radius): the getters raise when the firewall does not answer (#49)
driver / test (3.13) (pull_request) Successful in 1m0s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m3s
CI / driver (pull_request) Failing after 2m21s
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / publish (pull_request) Skipped
get_radius_clients() and get_radius_users() caught every exception and
returned [], so a caller could not tell no entries from no answer. netOrk
asks them whether an entry whose add was cut off is on the firewall, and an
empty list would have made it forget a NAS client still live there. Both now
raise for a failed request or an answer without rows; an empty list is the
firewall's answer, which RADIUS_READS_RAISE = True declares. A saved add
whose id lookup fails still answers success, with no id.

Closes #49
2026-11-15 19:02:08 +01:00
christianmanivong 521f7c5d73 Merge pull request 'feat(config): list, read and revert the firewall's config revisions' (#48) from feat/config-revisions into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 57s
driver / lowest (push) Successful in 33s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m4s
driver / publish (push) Skipped
driver / standard (push) Successful in 16s
driver / types (push) Successful in 1m0s
driver / test (3.12) (push) Successful in 1m12s
CI / driver (push) Successful in 2m44s
2026-11-13 22:10:02 +00:00
Christian Manivong a65a3ed6e3 refactor(config): take the revision contract from napalm-device-types
driver / test (3.13) (pull_request) Successful in 1m3s
driver / lowest (pull_request) Successful in 35s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Successful in 2m44s
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m0s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / publish (pull_request) Skipped
napalm-device-types 4.38.0 declares ConfigRevisionsMixin: the listing,
the reading, ConfigRevisionDict and the exceptions, and the revert as a
template. The driver keeps the device communication: the three backup
API calls, the revert step, and config_revision_content(), which leaves
out the <revision> block every save writes into config.xml and the
indentation between elements.

The template reads the newest revision after the revert and checks that
it holds the revision's configuration. OPNsense answers "reverted" even
when restoreBackup() could not load the file and kept the previous one;
that now raises ConfigRevertFailed instead of passing. A refusal of the
firewall raises ConfigRevertFailed too. An id the history does not list
still never reaches a request path.

Refs NetOrk/netork#2511
2026-11-13 22:33:58 +01:00
Christian Manivong 5a20023c54 feat(config): list, read and revert the firewall's config revisions
driver / test (3.13) (pull_request) Successful in 1m4s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / lowest (pull_request) Successful in 30s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Successful in 2m25s
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 57s
driver / publish (pull_request) Skipped
OPNsense has no API that takes an uploaded config.xml: the backup API
lists the history in /conf/backup, hands out a revision and reverts to
one that is already on the firewall. A full replace exists only on the
legacy page diag_backup.php. So an application restores a configuration
by reverting to the revision that holds it (NetOrk/netork#2511).

get_config_revisions() lists the history newest first: id, time in UTC
(time_iso is in the firewall's zone), description, user and size.
get_config_revision(id) returns one revision's config.xml.
revert_config_revision(id) calls revert_backup and refuses an id that is
not in the history now; an id that is no file name of the history never
reaches a request path. A revert only saves config.xml as a new newest
revision: no service is reloaded and the firewall does not reboot.

load_replace_candidate is None instead of NAPALM's stub that raised, so
a capability check sees that the driver replaces nothing. The helper
that finds the newest backup for rollback() moves to the new module,
which keeps opnsense.py under its recorded size.

Refs NetOrk/netork#2511
2026-11-13 22:21:58 +01:00
christianmanivong 9d7cb64dac Merge pull request 'feat(time-sync): read the time servers and zone of config.xml (NetOrk/netork#2363)' (#47) from feature/time-sync-2363 into main
driver / lint (push) Successful in 13s
driver / lowest (push) Successful in 32s
driver / test (3.13) (push) Successful in 1m7s
driver / build (push) Successful in 31s
driver / security (push) Successful in 59s
driver / publish (push) Skipped
driver / standard (push) Successful in 14s
driver / types (push) Successful in 57s
driver / test (3.12) (push) Successful in 1m2s
CI / driver (push) Successful in 2m28s
2026-11-11 14:29:05 +00:00
Christian Manivong 6fdc3ff2c7 feat(time-sync): read the time servers and zone of config.xml (NetOrk/netork#2363)
driver / test (3.13) (pull_request) Successful in 1m3s
driver / lowest (pull_request) Successful in 36s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 2m33s
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / publish (pull_request) Skipped
netOrk aligns every device with one list of time servers and a zone per
site (NetOrk/netork#2360) through napalm-device-types 4.35.0's
TimeSyncMixin. OPNsense keeps both in config.xml, <system><timeservers>
and <system><timezone>, set on the legacy pages services_ntpd.php and
system_general.php. No API controller reads or writes them, on 26.7 and
on master, so get_time_sync() reads them from the configuration download
get_config already uses and asks /api/ntpd/service/status whether ntpd
follows a system peer.

The driver writes neither value: time_sync_writes is empty and
configure_time_sync is None. Restoring an edited config.xml or running
the initial setup wizard would rewrite far more than the clock, on a box
that is often the gateway and its LAN's time server. TIME_SERVERS_MENU
and TIME_ZONE_MENU say where a person sets them, as SSH_SETTINGS_MENU
does for the SSH algorithms.

get_ntp_servers() now returns the same configured list. It read a
"peers" field the status endpoint does not have (it answers with ntpq's
associations as "rows") and so never found a server.
2026-11-11 15:20:29 +01:00
christianmanivong a6c3eb2604 Merge pull request 'chore(release): 0.6.0' (#46) from chore/release-0.6.0 into main
driver / lint (push) Successful in 20s
driver / test (3.13) (push) Successful in 1m9s
driver / lowest (push) Successful in 45s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m10s
driver / publish (push) Successful in 36s
driver / types (push) Successful in 1m11s
driver / standard (push) Successful in 18s
driver / test (3.12) (push) Successful in 1m15s
CI / driver (push) Successful in 3m40s
2026-11-07 19:05:46 +00:00
Christian Manivong 688918cf31 chore(release): 0.6.0
driver / test (3.13) (pull_request) Successful in 58s
driver / test (3.12) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 36s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Successful in 2m34s
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m12s
driver / publish (pull_request) Skipped
2026-11-07 19:58:43 +01:00
christianmanivong 7b35ade410 Merge pull request 'feat(ssh): say where the SSH algorithm lists are set' (#45) from feat/ssh-hardening-1769 into main
driver / lint (push) Successful in 17s
driver / test (3.13) (push) Successful in 1m18s
driver / lowest (push) Successful in 48s
driver / build (push) Successful in 34s
driver / security (push) Successful in 1m14s
driver / publish (push) Skipped
driver / standard (push) Successful in 17s
driver / types (push) Successful in 1m6s
driver / test (3.12) (push) Successful in 1m6s
CI / driver (push) Successful in 2m54s
2026-11-07 18:58:37 +00:00
Christian Manivong b50732c63c feat(ssh): say where the SSH algorithm lists are set
driver / test (3.13) (pull_request) Successful in 1m13s
driver / lowest (pull_request) Successful in 40s
driver / build (pull_request) Successful in 37s
driver / security (pull_request) Successful in 1m6s
CI / driver (pull_request) Successful in 2m37s
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m13s
driver / test (3.12) (pull_request) Successful in 1m15s
driver / publish (pull_request) Skipped
OPNsense writes sshd_config from config.xml (<system><ssh>), set on the
legacy Administration page; no API controller reads or writes that
section (26.1, 26.7, master). The driver cannot harden the SSH server,
so it declares, as data, the page and the field of each algorithm list:
SSH_SETTINGS_MENU and SSH_SETTINGS_FIELDS, keyed like device-types'
SSH_ALGORITHM_CLASSES. An application tells a person what to set there.

The CARP master check moves to virtual_ips, next to the CARP reader, so
opnsense.py stays under its line ratchet.

Refs NetOrk/netork#1769
2026-11-07 16:39:12 +01:00
christianmanivong 0289963af8 Merge pull request 'feat(scheduled-jobs): the cron jobs of config.xml over the REST API (#43)' (#44) from feature/scheduled-jobs into main
driver / lint (push) Successful in 14s
driver / test (3.13) (push) Successful in 59s
driver / lowest (push) Successful in 39s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m18s
driver / publish (push) Skipped
driver / standard (push) Successful in 15s
driver / types (push) Successful in 1m0s
driver / test (3.12) (push) Successful in 1m3s
CI / driver (push) Successful in 2m50s
2026-11-03 08:20:26 +00:00
Christian Manivong f75d1c8334 chore(scheduled-jobs): require napalm-device-types 4.27.0
driver / test (3.13) (pull_request) Successful in 1m1s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Successful in 2m30s
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 1m7s
driver / publish (pull_request) Skipped
4.26.0 went out with the sshd drop-in change; the scheduled-jobs
contract is in 4.27.0.
2026-11-03 08:35:59 +01:00
Christian Manivong c4ff19ac20 feat(scheduled-jobs): the cron jobs of config.xml over the REST API (#43)
driver / test (3.13) (pull_request) Failing after 18s
driver / lowest (pull_request) Failing after 17s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Failing after 40s
CI / driver (pull_request) Failing after 1m25s
driver / standard (pull_request) Successful in 25s
driver / lint (pull_request) Successful in 26s
driver / types (pull_request) Failing after 35s
driver / test (3.12) (pull_request) Failing after 21s
driver / publish (pull_request) Skipped
OPNsense keeps its cron jobs in its configuration and runs each as a
configd action, so the POSIX implementation does not fit: the driver has
no shell, and a job's command is not a shell line. The cron API reads and
writes them instead.

get_scheduled_jobs reads every job in one request (/api/cron/settings/get,
which carries the selected action rather than its display text). A job
another component registered is platform, one written by
put_scheduled_job carries the napalm-scheduled-job marker in its
description and is application, the rest admin. Every job can be enabled
and disabled; only an application's job is edited or deleted.
put_scheduled_job takes a configd action as command and refuses one
configd does not offer; get_scheduled_job_commands lists them. Running a
job now is refused: the API cannot run a configd action. Every write
reads the job again and refuses one whose digest changed.

Parameters are written one per line and only without blanks, quotes or
backslashes: OPNsense up to 26.1 splits them as a shell would, 26.7 takes
a line per argument, and only such arguments mean the same to both.

Requires napalm-device-types 4.26.0.

Closes #43
2026-11-03 05:44:29 +01:00
christianmanivong 80d6b8cb71 Merge pull request 'fix: DNS detection and Kea search raise on a failed read, hermetic open() test (#39, #40, #41)' (#42) from fix/bugs-2026-11-02 into main
driver / lint (push) Successful in 15s
driver / test (3.13) (push) Successful in 1m21s
driver / lowest (push) Successful in 39s
driver / build (push) Successful in 31s
driver / security (push) Successful in 1m20s
driver / publish (push) Skipped
driver / standard (push) Successful in 23s
driver / types (push) Successful in 1m14s
driver / test (3.12) (push) Successful in 1m21s
CI / driver (push) Successful in 3m10s
2026-11-02 08:20:45 +00:00
Christian Manivong 6ac7a6f6a2 refactor(dhcp): move the Kea subnet lookup into kea_reservations
driver / test (3.12) (pull_request) Successful in 1m17s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / lowest (pull_request) Successful in 36s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m7s
CI / driver (pull_request) Successful in 2m56s
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m10s
driver / publish (pull_request) Skipped
create_dhcp_reservation and _kea_subnet_uuid_for each walked the
searchSubnet rows for the one holding an address. Both now call the
pure subnet_containing(), which brings create_dhcp_reservation under
the complexity limit and back below its recorded length after #40;
the quality baseline records the shrunk entries.
2026-11-02 08:51:21 +01:00
Christian Manivong 96a4a139d0 fix(tests): keep the open() failure test off the network
driver / test (3.13) (pull_request) Successful in 1m28s
driver / lowest (pull_request) Successful in 56s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Failing after 3m33s
driver / standard (pull_request) Failing after 20s
driver / lint (pull_request) Successful in 21s
driver / types (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 1m44s
driver / publish (pull_request) Skipped
test_open_raises_connection_exception_on_error called open() on
"unreachable.invalid" unpatched, so the unit test resolved the name
through the host's resolver and depended on it failing fast. Patch
requests.Session.get to refuse the connection and check that open()
raises ConnectionException and leaves no session behind.

Closes #41
2026-11-02 08:37:58 +01:00
Christian Manivong 0f730a4b9d fix(dhcp): raise when the Kea reservation search fails
create_dhcp_reservation searched for an existing reservation so a retry
updates it, but a failed search was logged at debug level and the add
went ahead: a write based on a read that did not happen. Raise a
RuntimeError naming searchReservation before anything is written.

Closes #40
2026-11-02 08:37:06 +01:00
Christian Manivong 901df1b523 fix(dns): raise when the DNS service detection fails
_detect_active_dns caught every error from /api/core/service/search and
returned None, so get_dns_entries() reported a transient API error as an
empty list (no DNS service) and sync_dns_zone() blamed the DNS service.
Let the request error propagate; None only when the list was read and
neither Unbound nor Dnsmasq runs.

Closes #39
2026-11-02 08:35:49 +01:00
christianmanivong 91a17b54a8 Merge pull request 'fix: is_alive port, DNS override read failure, Kea reservation MAC (#15, #14, #26)' (#38) from fix/bugs-2026-11 into main
driver / lint (push) Successful in 13s
driver / test (3.13) (push) Successful in 1m13s
driver / lowest (push) Successful in 47s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m15s
driver / publish (push) Skipped
driver / standard (push) Successful in 16s
driver / types (push) Successful in 1m3s
driver / test (3.12) (push) Successful in 1m26s
CI / driver (push) Successful in 3m10s
2026-11-01 22:00:10 +00:00
Christian Manivong ea0a52717e fix(dhcp): match Kea reservations on address and MAC
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m2s
CI / driver (pull_request) Successful in 2m45s
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 1m16s
driver / publish (pull_request) Skipped
create_dhcp_reservation and delete_dhcp_reservation_and_lease looked a
reservation up by its address alone. A reservation another MAC held for
the address, made by hand or left from an earlier host, was overwritten
on create and removed on delete, together with that host's lease.

Create now raises instead of taking it over, and delete leaves another
MAC's reservation and lease in place and names that MAC in the new
reservation_other_mac field. The matching lives in kea_reservations, a
module under strict typing.

Closes #26
2026-11-01 21:50:15 +01:00
Christian Manivong 4fc7b2424e fix(dns): raise when the host overrides cannot be read
The Unbound and Dnsmasq override reads logged any error and returned an
empty list. sync_dns_zone took that for "no overrides": it deleted
nothing and added every record again, so a transient API error left
each record twice on the firewall. The reads now raise, which stops the
sync before it writes and lets get_dns_entries callers tell a failed
read from an empty one.

Closes #14
2026-11-01 21:45:12 +01:00
Christian Manivong 4e377923db fix(connection): probe the API port from base_url in is_alive
is_alive always opened port 443 on the hostname, so a firewall whose API
is reached through base_url on another port (https://fw:8443) read as
dead. The probe now takes host and port from base_url, falling back to
the scheme's default port.

Closes #15
2026-11-01 21:44:51 +01:00
christianmanivong e2cac52a12 Merge pull request 'fix: the SNMP agent setup sends only what os-net-snmp 26.x knows (#36)' (#37) from fix/snmp-agent-26x into main
driver / lint (push) Successful in 14s
driver / lowest (push) Successful in 51s
driver / test (3.13) (push) Successful in 1m9s
driver / build (push) Successful in 36s
driver / security (push) Successful in 1m19s
driver / publish (push) Skipped
driver / standard (push) Successful in 15s
driver / test (3.12) (push) Failing after 5s
driver / types (push) Successful in 1m10s
CI / driver (push) Failing after 2m30s
2026-11-01 06:29:28 +00:00
Christian Manivong 0bb59b60a0 refactor: the SNMP agent config step keeps under the complexity ratchet (#36)
driver / test (3.12) (pull_request) Successful in 1m22s
driver / test (3.13) (pull_request) Successful in 1m18s
driver / lowest (pull_request) Successful in 34s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 55s
CI / driver (pull_request) Successful in 55s
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m10s
driver / publish (pull_request) Skipped
_write_snmp_agent_config came out at complexity 11 and failed the
standard job. The community check and the listen address now live in
their own helpers; the baseline follows the file's new length.
2026-11-01 07:25:49 +01:00
Christian Manivong 8bf76aa346 fix: the SNMP agent setup sends only what os-net-snmp 26.x knows (#36)
driver / test (3.13) (pull_request) Successful in 1m1s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Failing after 2m15s
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Failing after 16s
driver / types (pull_request) Successful in 1m9s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / publish (pull_request) Skipped
The configure step posted contact, location, sysobjid and bindip, and
listen in the shape get returns. OPNsense 26.x refuses a field its model
does not have with HTTP 500, so the setup failed on every current box.
It now sends syscontact/syslocation, listen as a string, and contact and
location only when the caller gives them: an empty one would have blanked
the operator's.
2026-10-31 07:17:04 +01:00
christianmanivong c02a745bb3 Merge pull request 'fix: an ARP entry's expiry is no age' (#35) from fix/arp-unknown-age into main
driver / lint (push) Successful in 15s
driver / lowest (push) Successful in 43s
driver / test (3.13) (push) Successful in 1m13s
driver / build (push) Failing after 5s
driver / security (push) Successful in 1m12s
driver / publish (push) Skipped
driver / standard (push) Successful in 17s
driver / types (push) Successful in 1m13s
driver / test (3.12) (push) Successful in 1m34s
CI / driver (push) Failing after 3m15s
2026-10-30 09:11:49 +00:00
Christian Manivong bb0810d693 fix: an ARP entry's expiry is no age
driver / lowest (pull_request) Successful in 37s
driver / test (3.13) (pull_request) Successful in 1m27s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Successful in 3m12s
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m6s
driver / test (3.12) (pull_request) Successful in 1m27s
driver / publish (pull_request) Skipped
get_arp_table and get_ipv6_neighbors_table reported expires, the seconds
left until the entry expires: an entry refreshed a second ago looked 20
minutes old. Both now report ARP_AGE_UNKNOWN (-1.0).

NetOrk/netork#1327
2026-10-30 08:37:08 +01:00
christianmanivong 0176656743 Merge pull request 'chore: Python 3.12 is the floor (NAPALM/driver-standard#6)' (#34) from chore/python-312-floor into main
driver / lint (push) Successful in 12s
driver / test (3.13) (push) Successful in 1m0s
driver / lowest (push) Successful in 30s
driver / build (push) Successful in 28s
driver / security (push) Successful in 56s
driver / publish (push) Skipped
driver / standard (push) Successful in 17s
driver / types (push) Successful in 57s
driver / test (3.12) (push) Successful in 1m3s
CI / driver (push) Successful in 2m28s
2026-10-27 11:13:50 +00:00
Christian Manivong b49fd8f56d fix: the floor on napalm is 5.1 (NAPALM/driver-standard#6)
driver / test (3.13) (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 30s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 58s
CI / driver (pull_request) Successful in 2m27s
driver / standard (pull_request) Successful in 15s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 1m0s
driver / publish (pull_request) Skipped
napalm 5.0 and older import pkg_resources, which a Python 3.12 venv no
longer has, so the lowest job failed on them.
2026-10-27 10:49:30 +01:00
Christian Manivong 72b4806c65 chore: Python 3.12 is the floor (NAPALM/driver-standard#6)
driver / lowest (pull_request) Failing after 38s
driver / test (3.13) (pull_request) Successful in 1m13s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Failing after 2m49s
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 52s
driver / test (3.12) (pull_request) Successful in 1m18s
driver / publish (pull_request) Skipped
netOrk runs every driver in its own containers on Python 3.12, so 3.10
and 3.11 are no longer supported or tested. requires-python, mypy and
ruff move to 3.12, along with what ruff's pyupgrade rules then rewrite.
2026-10-27 10:18:58 +01:00
christianmanivong 9115628abe Merge pull request 'fix: WireGuard peers keep their tunnel key when others come and go (#32)' (#33) from fix/wireguard-stable-keys-32 into main
driver / lint (push) Successful in 16s
driver / test (3.11) (push) Successful in 1m28s
driver / lowest (push) Successful in 40s
driver / test (3.13) (push) Successful in 1m8s
driver / build (push) Successful in 32s
driver / security (push) Successful in 1m11s
driver / publish (push) Skipped
driver / standard (push) Successful in 20s
driver / types (push) Successful in 1m1s
driver / test (3.10) (push) Successful in 1m19s
driver / test (3.12) (push) Successful in 1m18s
CI / driver (push) Successful in 3m31s
2026-10-27 09:06:56 +00:00
Christian Manivong eaafa540e5 refactor: WireGuard tunnels are read in their own module (#32)
driver / test (3.10) (pull_request) Failing after 6s
driver / test (3.11) (pull_request) Successful in 1m5s
driver / lowest (pull_request) Successful in 33s
driver / test (3.13) (pull_request) Successful in 59s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m1s
CI / driver (pull_request) Failing after 2m25s
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m5s
driver / publish (pull_request) Skipped
get_vpn_tunnels() grew past the quality baseline with the key fix. The
WireGuard part is pure parsing of /api/wireguard/service/show, like the
listen ports in listening.py, so it moves to wireguard.py and the driver
calls it. opnsense.py shrinks from 3125 to 3082 lines.
2026-10-27 10:03:30 +01:00
Christian Manivong 9f45952605 fix: WireGuard peers keep their tunnel key when others come and go (#32)
driver / test (3.10) (pull_request) Failing after 3s
driver / test (3.11) (pull_request) Failing after 6s
driver / lowest (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 1m39s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m11s
CI / driver (pull_request) Failing after 3m12s
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Failing after 17s
driver / types (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m42s
driver / publish (pull_request) Skipped
get_vpn_tunnels() keyed WireGuard peers with a running counter over the
peer rows, so a peer added ahead of an existing one renumbered every peer
after it. Whatever a consumer stores per key moved with it: netOrk's site
link and tunnel check ended up on a new, offline peer and alarmed while the
real tunnel was up.

The key is now the interface and the start of the public key, as in
napalm-linux, made URL-safe because the key is a path segment. Two peers
sharing the prefix get the whole key; a row without a public key keeps its
position. IPsec and OpenVPN keys were already stable.

Every WireGuard key changes once; netOrk carries its
per-tunnel metadata across (netork#1654).
2026-10-27 09:20:30 +01:00
30 changed files with 3902 additions and 382 deletions

No files matched your search

+120
View File
@@ -6,6 +6,126 @@ All notable changes to this driver. The format follows
## [Unreleased]
### Added
- Shutting the firewall down (NetOrk/netork#2841): `shutdown_host()` from
napalm-device-types' `HostShutdownMixin` halts the firewall and powers it off through
`POST /api/core/firmware/poweroff` (OPNsense 16.1.15 and later), the clean shutdown of
*Power → Power Off*, as `reboot_host()` restarts it through `firmware/reboot`. A
refused request raises `RuntimeError` with the firewall's answer.
- How people log in (NetOrk/netork#662), in napalm-device-types 4.50.0's shapes, read from
config.xml over `/api/core/backup/download/this`. `get_web_login_auth()` returns the auth
servers `<system><webgui><authmode>` names, in their order, and the Local Database when it
names none. Each server comes with what it asks for: `password` for `local`, `ldap` and
`voucher`, `password_otp` for `totp` and `ldap-totp`, `external` for `radius`, and
`unknown` for any other type. A name no server has is skipped, as OPNsense skips it.
`get_ssh_server_auth()` returns sshd's settings as `openssh_configure_do` writes them:
`server_enabled` from `enabled`, password and challenge-response login from
`passwordauth`, and root login from `permitrootlogin`, each tested for presence as
OPNsense does. A key is always on. `password_sources` lists the same servers, because an
SSH password goes through them.
- The firewall's configuration history (NetOrk/netork#2511): `get_config_revisions()`
lists the revisions OPNsense keeps of config.xml, newest first, each with its id, its
time in UTC, its description, its user and its size; `get_config_revision(id)`
returns one revision's config.xml; `revert_config_revision(id)` makes it the
configuration again through `/api/core/backup/revert_backup`, refuses an id that is
not in the history (`UnknownConfigRevision`), and raises `ConfigRevertFailed` when the
newest revision afterwards does not hold the revision's configuration -- OPNsense
answers "reverted" even when it kept the previous file. `config_revision_content()`
compares config.xml without the `<revision>` block every save writes. The contract is
napalm-device-types 4.38.0's `ConfigRevisionsMixin`. A revert saves config.xml and
nothing else: no service is reloaded and the firewall does not reboot.
- Time sync (NetOrk/netork#2363): `get_time_sync()` from napalm-device-types 4.35.0's
`TimeSyncMixin` reads the time servers (`<system><timeservers>`, in their order) and
the zone (`<system><timezone>`, an IANA name; none is the `Etc/UTC` OPNsense runs
then) from config.xml over `/api/core/backup/download/this`, and whether ntpd
follows a system peer from `/api/ntpd/service/status`. Both values are set on legacy
pages that no API controller reads or writes, up to 26.7 and on `master`, so the
driver writes neither: `time_sync_writes` is empty, `configure_time_sync` is None,
and `TIME_SERVERS_MENU` (*Services → Network Time → General*) and `TIME_ZONE_MENU`
(*System → Settings → General*) say where a person sets them.
### Changed
- Requires napalm-device-types 4.35.0, which declares the time-sync contract.
- Requires napalm-device-types 4.38.0, which declares the configuration-history
contract.
- `load_replace_candidate` is `None` instead of NAPALM's stub that raised, so a caller
can tell that the driver replaces no configuration: OPNsense has no API that takes an
uploaded config.xml.
### Fixed
- `get_radius_clients()` and `get_radius_users()` raise when the firewall does not
answer or the answer holds no `rows`, instead of returning `[]`, so an empty list
means FreeRADIUS has none (#49). `RADIUS_READS_RAISE = True` on the driver says so.
A saved add whose id lookup fails still answers `success`, with no id.
- `get_ntp_servers()` lists the configured servers of config.xml, the same list as
`get_time_sync()`. It read a `peers` field `/api/ntpd/service/status` does not
have -- the endpoint answers with ntpq's associations as `rows` -- and so found no
server. A failed read now raises instead of reading as "no servers".
## [0.6.0] - 2026-11-07
### Added
- Where the SSH server's algorithm lists are set (NetOrk/netork#1769):
`SSH_SETTINGS_MENU` (*System → Settings → Administration → Secure Shell*) and
`SSH_SETTINGS_FIELDS`, each list's field by its algorithm class. OPNsense writes
sshd_config from config.xml and has no API for that section, so the driver does not
harden the SSH server itself; an application tells a person what to set there.
- Scheduled jobs (NetOrk/netork#1933, #43): `get_scheduled_jobs()` reads every cron job
of config.xml over `/api/cron/settings/get`, with who owns it -- another component's
job is `platform`, one written by `put_scheduled_job()` `application`, the rest
`admin`. `manage_scheduled_job()` enables and disables any of them;
`put_scheduled_job()` and `delete_scheduled_job()` write and remove an application's
own, whose command is a configd action. `get_scheduled_job_commands()` lists the
actions configd offers. Running a job now is refused: the API cannot run a configd
action. Every write reads the job again first and refuses one that changed.
### Changed
- Requires napalm-device-types 4.26.0, which declares the scheduled-jobs contract.
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
3.12 venv no longer has.
### Fixed
- `is_alive()` checks the host and port named in `base_url` (`https://fw:8443`) instead
of always port 443 on the hostname, so a firewall whose API listens elsewhere no
longer reads as dead (#15).
- `sync_dns_zone()` and `get_dns_entries()` raise when the host overrides cannot be
read. A transient API error used to read as "no overrides": the sync then deleted
nothing and added every record a second time (#14).
- `create_dhcp_reservation()` no longer takes over a Kea reservation another MAC
holds for the address (made by hand, say): it raises `RuntimeError` and leaves it
as it is. `delete_dhcp_reservation_and_lease()` removes only the reservation and
lease of the given MAC and reports another host's reservation for the address in
the new `reservation_other_mac` field (#26).
- `configure_snmp_agent()` works on OPNsense 26.x again. The configure step sent
fields the os-net-snmp model does not have (`contact`, `location`, `sysobjid`,
`bindip`) and `listen` in the shape `get` returns rather than as a string, which
26.x refuses with HTTP 500. It now sends `syscontact`/`syslocation`, and only when
the caller gives them, so an operator's sysContact and sysLocation are no longer
blanked (#36).
- `get_arp_table()` and `get_ipv6_neighbors_table()` report an unknown age as `-1.0`
(napalm-device-types' `ARP_AGE_UNKNOWN`). They reported `expires`, the seconds
left until the entry expires, which is no age: an entry refreshed a second ago
looked 20 minutes old (NetOrk/netork#1327).
- `get_vpn_tunnels()` keys a WireGuard peer by its interface and the start of its
public key (`wireguard-wg0-aBcD1234`, URL-safe) instead of its position, so a peer
added ahead of another no longer renumbers it (#32). Every WireGuard key changes
once with this release.
- `get_dns_entries()` raises when the service list (`/api/core/service/search`)
cannot be read, instead of returning an empty list as if neither Unbound nor
Dnsmasq ran: a transient API error made the firewall look as if it had no DNS
records. `sync_dns_zone()` raises that API error instead of "No active DNS
service (Unbound or Dnsmasq) detected" (#39).
- `create_dhcp_reservation()` raises `RuntimeError` naming `searchReservation` when
the search for an existing reservation fails, and writes nothing. It used to add
the reservation anyway: a retry then failed with "Kea rejected DHCP reservation"
instead of the real error, or left two reservations for one address, which Kea
refuses to load (#40).
- The unit tests no longer reach the network: the test of a failed `open()` looked
up a real host name and waited for the resolver, so it hung or behaved differently
on a build host with a slow resolver or one that answers every name (#41).
## [0.5.0] - 2026-10-23
The first release on PyPI.
+145 -5
View File
@@ -14,9 +14,9 @@ NAPALM community driver for **OPNsense** firewalls (read-only, via REST API).
| Dependency | Minimum version |
|---|---|
| Python | 3.10 |
| Python | 3.12 |
| NAPALM | 4.0 |
| napalm-device-types | 4.21.1 |
| napalm-device-types | 4.38.0 |
| requests | 2.28 |
## Installation
@@ -82,8 +82,14 @@ arguments.
| `get_environment` | ✅ | `GET /api/diagnostics/system/system_resources` + `system_temperature` |
| `get_lldp_neighbors` | ✅ ¹ | `GET /api/lldpd/service/neighbor` |
| `get_lldp_neighbors_detail` | ✅ ¹ | `GET /api/lldpd/service/neighbor` |
| `get_ntp_servers` | ✅ | `GET /api/ntpd/service/status` |
| `get_ntp_servers` | ✅ ⁵ | `GET /api/core/backup/download/this`: `<system><timeservers>` of config.xml |
| `get_time_sync` | ✅ ⁵ | `GET /api/core/backup/download/this` (servers, zone) + `GET /api/ntpd/service/status` (system peer) |
| `get_config` | ✅ | `GET /api/core/backup/download/this` (XML) |
| `get_web_login_auth` | ✅ | `GET /api/core/backup/download/this`: the auth servers `<system><webgui><authmode>` names, in order |
| `get_ssh_server_auth` | ✅ | `GET /api/core/backup/download/this`: `<system><ssh>` (on, password, root login) and the same auth servers for an SSH password |
| `get_config_revisions()` | ✅ ⁶ | `GET /api/core/backup/backups/this` |
| `get_config_revision(revision_id)` | ✅ ⁶ | `GET /api/core/backup/download/this/<id>` (XML) |
| `revert_config_revision(revision_id)` | ✅ ⁶ | `POST /api/core/backup/revert_backup/<id>` |
| `is_alive` | ✅ | TCP socket check |
| `get_bgp_neighbors` | ✅ ² | `GET /api/quagga/bgp/get` + `GET /api/quagga/diagnostics/bgpneighbors` |
| `get_vlans` | ✅ | `GET /api/interfaces/vlan_settings/search_item` |
@@ -92,10 +98,17 @@ arguments.
| `get_listening_sockets` | ✅ | `GET /api/diagnostics/interface/get_socket_statistics` + `/api/core/service/search` + `/api/wireguard/service/show` (WireGuard's kernel sockets by listen port) |
| `get_virtual_ips` | ✅ | `GET /api/interfaces/overview/export`: every address bound to a CARP VHID (CARP address and IP aliases on it), with this node's CARP state. `interfaces/vip_settings` is not read: it carries the CARP passwords |
| `ping_sweep` | ✅ ³ | same endpoints, one batch of parallel jobs at a time |
| `get_scheduled_jobs()` | ✅ ⁴ | `GET /api/cron/settings/get`: every cron job of config.xml |
| `manage_scheduled_job(key, action, digest=)` | ✅ ⁴ | enable, disable: `POST /api/cron/settings/toggle_job/<uuid>/1` (or `/0`) + `/api/cron/service/reconfigure`; run now is refused |
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | ✅ ⁴ | an application's own job: `add_job`, `set_job/<uuid>`, `del_job/<uuid>` + `reconfigure` |
| `get_scheduled_job_commands()` | ✅ ⁴ | `GET /api/cron/settings/get_job`: the configd actions a job can run |
> ¹ Requires the `os-lldpd` plugin. Returns empty dict if the plugin is not installed.
> ² Requires the `os-frr` (FRR/Quagga) plugin. Returns empty dict if the plugin is not installed or FRR is not running.
> ³ Overrides the generic per-host loop from `napalm-device-types`.
> ⁴ See [Scheduled jobs](#scheduled-jobs).
> ⁵ See [Time sync](#time-sync).
> ⁶ See [Configuration history](#configuration-history).
### Ping
@@ -120,6 +133,131 @@ statistics line lands in the log slightly after the request that triggered it.
`ttl` and `vrf` are accepted for NAPALM compatibility and ignored — the API
has no equivalent.
### Scheduled jobs
OPNsense keeps its cron jobs in config.xml (System → Settings → Cron), and each
runs a **configd action**, not a shell line. `key` is `opnsense:<uuid>`, `kind`
`cron`, `source` `config.xml`, `run_as` `root`. A job another component
registered (its origin is not `cron`, such as the intrusion detection's rule
update) is `platform`; one whose description starts with
`napalm-scheduled-job: <name>` was written by `put_scheduled_job` and is the only
kind that can be edited or deleted; every other job is `admin`. Every job can be
enabled and disabled.
`put_scheduled_job` takes a configd action as `command`, with its parameters as
the words after it: the actions are what `get_scheduled_job_commands()` lists,
anything else is refused (`ScheduledJobRefused`), and so is `@reboot` and a
parameter with blanks, quotes or backslashes, which OPNsense releases before and
after 26.7 would split differently. The schedule is written as its five fields,
month and weekday names as numbers.
Not covered: the API cannot run a configd action now, so no job takes `run`;
what OPNsense writes into the crontab beyond config.xml (`periodic`, the
plugins' system jobs) cannot be read over the API; the time zone is not read
(`None`).
### SSH server settings
OPNsense writes sshd_config from config.xml (`<system><ssh>`: `kex`, `ciphers`,
`macs`, `keys`, `keysig`), set on the legacy page *System → Settings →
Administration → Secure Shell* (`system_advanced_admin.php`). No API controller
reads or writes that section, up to OPNsense 26.7 and on `master`, so the driver
does not offer `harden_ssh_server`. It says, as data, where a person sets the
algorithm lists instead: `SSH_SETTINGS_MENU` is the page's menu path and
`SSH_SETTINGS_FIELDS` names each list's field by its algorithm class
(napalm-device-types' `SSH_ALGORITHM_CLASSES`). A field left empty means
OpenSSH's defaults. In an HA pair the configuration sync carries the section to
the backup when its "OpenSSH" item (`ssh`) is ticked.
### How people log in
`get_web_login_auth()` and `get_ssh_server_auth()` say how people log in to the
firewall, in napalm-device-types' shapes (`WebLoginAuthDict`, `SshServerAuthDict`).
NetOrk/netork#662 judges them for MFA. Both read config.xml, because no API controller
reads these settings.
- **Web interface.** `<system><webgui><authmode>` names the auth servers a login is
tried against, in order. Without it, the built-in "Local Database" is used alone. The
first server that accepts the login lets the person in. A name no server has is
skipped, as OPNsense skips it. Each source says what it asks for: `password` (`local`,
`ldap`, `voucher`), `password_otp` (`totp` and `ldap-totp`: the password and a code in
one field, and a user without an OTP seed is refused), `external` (`radius`), or
`unknown` for any other type.
- **SSH.** sshd runs only with `<system><ssh><enabled>` (`server_enabled`).
`passwordauth` switches password and challenge-response login on together, and
`permitrootlogin` lets root in. Each is tested for presence, as OPNsense tests it. A
key is always accepted, and sshd checks it itself. A password goes through the same
auth servers as the web interface (`password_sources`), because OPNsense's `System`
service runs that list for `sshd`, `login`, `su` and `sudo`.
### Time sync
OPNsense keeps the time servers and the zone in config.xml: `<system><timeservers>`,
space-separated in the order of *Services → Network Time → General*
(`services_ntpd.php`), and `<system><timezone>`, an IANA name set on *System →
Settings → General* (`system_general.php`). `get_time_sync()` reads both from the
configuration download `get_config` uses, and `get_ntp_servers()` returns the same
servers. An empty or missing zone reads as `Etc/UTC`, the zone OPNsense runs in
then. `synchronized` is whether `/api/ntpd/service/status` (`ntpq -pnw` as rows) has
a system peer (`*`): False without servers, since OPNsense does not run ntpd then,
and None when the status cannot be read. `daemon` is `ntpd`. The API key needs the
privilege to download the configuration, as for `get_config`.
Both pages are legacy PHP, and no API controller reads or writes either value, up
to OPNsense 26.7 and on `master`; the initial setup wizard writes the zone only
together with the hostname, the interfaces and the root password. So the driver
writes neither: `time_sync_writes` is empty and `configure_time_sync` is None.
`TIME_SERVERS_MENU` and `TIME_ZONE_MENU` are the pages' menu paths, for telling a
person where to set them. Which interfaces ntpd serves time on is not touched. In an
HA pair the configuration sync carries the servers to the backup when its "Network
Time" item (`ntpd`) is ticked; the zone is not synchronised.
### Configuration history
OPNsense keeps a copy of config.xml for every save in `/conf/backup`
(*System → Configuration → History*), `<system><backupcount>` of them (100 when unset);
the next save drops the oldest. `get_config_revisions()` lists them newest first, the
first being the configuration in place now:
```python
[
{
"id": "config-1794603885.1239.xml", # what the two methods below take
"time": "2026-11-13T21:04:45+00:00", # UTC, whatever zone the firewall runs in
"description": "/api/firewall/filter/apply made changes", # None when empty
"user": "apiuser@192.0.2.10", # None when empty
"size": 58213, # bytes
},
]
```
The contract is napalm-device-types' `ConfigRevisionsMixin`; this driver does the API
calls. `get_config_revision(revision_id)` returns that revision's config.xml as text.
`revert_config_revision(revision_id)` makes it the configuration again and returns the
revision in place afterwards. It refuses an id that is not in the history now
(`UnknownConfigRevision`, a `ValueError`) before anything changes, reads the revision,
calls `revert_backup`, and then checks that the newest revision holds the revision's
configuration: OPNsense answers `reverted` even when it could not load the file and kept
the previous one. A refusal of the firewall (for a user with `user-config-readonly`) or
a failed check raises `ConfigRevertFailed`, a `RuntimeError`. That is five requests.
`config_revision_content(text)` is config.xml without the `<revision>` block every save
writes (who, when, from where), in canonical XML, with the indentation between elements
left out: two revisions with the same configuration compare equal through it.
**What a revert does.** OPNsense copies the revision over config.xml and saves it. The
history gets a new newest entry with the revision's content, described as
`/api/core/backup/revert_backup/<id> made changes` by the API key's user, and the
oldest entry may drop out. That is all, and it is done when the request returns:
**no service is reloaded and the firewall does not reboot**, so it keeps running with
the settings it had until a subsystem's settings are applied or it restarts. The
`config` system hooks run afterwards; core installs none, a plugin such as git-backup
does. The revert starts no HA configuration sync.
There is no API that takes an uploaded config.xml (the full restore exists only on the
legacy page `diag_backup.php`, behind a GUI login), so the driver offers no
`load_replace_candidate`: it is `None`. A configuration that is no longer in the
history cannot be put back through the API. The API key needs the backup privilege.
## Config management
OPNsense does not expose a single generic "push config" endpoint. Config is
@@ -182,7 +320,9 @@ d.close()
### Limitations
- `load_replace_candidate` is not supported (no XML upload endpoint in the JSON API).
- `load_replace_candidate` is `None` (no XML upload endpoint in the JSON API); a revision
of the firewall's own history can be reverted to instead, see
[Configuration history](#configuration-history).
- Non-route config (firewall rules, DHCP, DNS, interfaces, …) must be managed
via OPNsense module-specific controllers — outside the scope of this driver.
- `rollback()` reverts the entire `config.xml` to the pre-commit state (not just
@@ -212,7 +352,7 @@ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
## CI
[.gitea/workflows/ci.yml](.gitea/workflows/ci.yml) calls the shared workflow of the
driver standard: ruff, mypy, the tests on Python 3.10–3.13 and at the lowest declared
driver standard: ruff, mypy, the tests on Python 3.12 and 3.13 and at the lowest declared
versions, bandit, pip-audit and a build check. A release tag publishes to PyPI.
## License
+20
View File
@@ -0,0 +1,20 @@
"""Where the OPNsense REST API listens, read from the driver's ``base_url``."""
from __future__ import annotations
from urllib.parse import urlsplit
#: The port the API listens on when ``base_url`` names none, per scheme.
DEFAULT_PORTS = {"https": 443, "http": 80}
#: Seconds the driver's reachability probe waits for the API port to accept.
ALIVE_TIMEOUT = 5
def api_endpoint(base_url: str, fallback_host: str) -> tuple[str, int]:
"""``https://fw:8443`` -> ``("fw", 8443)``: the host and port of the REST API.
Without a port the scheme's default applies; without a host, *fallback_host*.
"""
parts = urlsplit(base_url)
port = parts.port or DEFAULT_PORTS.get(parts.scheme.lower(), DEFAULT_PORTS["https"])
return parts.hostname or fallback_host, port
+204
View File
@@ -0,0 +1,204 @@
"""The firewall's own configuration history (NetOrk/netork#2511).
napalm-device-types' ``ConfigRevisionsMixin`` is the contract: it declares the listing
and the reading and runs the revert as a template -- refuse an id that is not in the
history, read the revision, revert, check that the newest revision holds it. This
module talks to the firewall: the three API calls, and ``config_revision_content``,
which leaves out the ``<revision>`` block every save writes into config.xml.
OPNsense keeps a copy of config.xml for every save, as ``/conf/backup/config-<unix
time>.xml`` -- *System → Configuration → History*. It keeps ``<system><backupcount>``
of them (100 when unset) and drops the oldest on the next save. The newest is the
copy of the configuration in place now.
No API takes an uploaded config.xml: the backup API (``/api/core/backup/``) lists the
history, hands out a revision and reverts to one, but only to a revision that is
already on the firewall; a full replace exists only on the legacy page
``diag_backup.php``. So the driver has no ``load_replace_candidate``, and an
application restores a configuration by reverting to the revision that holds it.
A revert (``revert_backup``) copies the revision over config.xml and saves it: the
history gets a new newest entry with the revision's content, described as
``/api/core/backup/revert_backup/<id> made changes`` and by the API key's user, and
the oldest entry may drop out. That is all, and it is done when the request returns:
OPNsense reloads no service and does not reboot, so the running firewall keeps the
state it had until a subsystem's settings are applied or it restarts. The ``config``
system hooks run afterwards (``/usr/local/etc/rc.syshook.d/config``, from syslog);
core installs none, a plugin such as git-backup does. The revert starts no HA
configuration sync.
"""
from __future__ import annotations
import logging
import re
# config.xml as the firewall's own API hands it over; ElementTree resolves no external
# entities, and expat limits entity expansion since 2.4.1.
import xml.etree.ElementTree as ET # nosec B405
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from napalm_device_types import (
ConfigRevertFailed,
ConfigRevisionDict,
ConfigRevisionsMixin,
UnknownConfigRevision,
)
logger = logging.getLogger(__name__)
#: The history of this firewall, newest first.
HISTORY_PATH = "/api/core/backup/backups/this"
#: One revision's config.xml; the answer is empty for a name with no file.
DOWNLOAD_PATH = "/api/core/backup/download/this/{revision_id}"
#: Copy a revision over config.xml and save it.
REVERT_PATH = "/api/core/backup/revert_backup/{revision_id}"
#: What ``revert_backup`` answers for a revision it has no file for.
_NOT_FOUND = "not_found"
_REVERTED = "reverted"
#: What every save writes into config.xml anew: who saved it, when, from where.
_STAMP = "revision"
#: A revision's file name in /conf/backup: its unix time, and ``_<ns>`` after a save
#: within the same microsecond. Nothing else may reach a request path.
_REVISION_ID = re.compile(r"config-([0-9]+(?:\.[0-9]+)?)(?:_[0-9]+)?\.xml")
def _checked_id(revision_id: object) -> str:
if not isinstance(revision_id, str) or not _REVISION_ID.fullmatch(revision_id):
raise UnknownConfigRevision(revision_id)
return revision_id
def _utc(value: Any) -> str | None:
try:
seconds = float(value)
except (TypeError, ValueError):
return None
return datetime.fromtimestamp(seconds, UTC).isoformat(timespec="seconds")
def _text(value: Any) -> str | None:
return value.strip() or None if isinstance(value, str) else None
def _stamp(revision: ConfigRevisionDict) -> float:
found = _REVISION_ID.fullmatch(revision["id"])
return float(found.group(1)) if found else 0.0
def _revision(item: Any) -> ConfigRevisionDict | None:
if not isinstance(item, dict):
return None
revision_id = item.get("id")
if not isinstance(revision_id, str):
return None
found = _REVISION_ID.fullmatch(revision_id)
if found is None:
return None
size = item.get("filesize")
return {
"id": revision_id,
# The revision's own time; the file name's when it has none.
"time": _utc(item.get("time")) or _utc(found.group(1)),
"description": _text(item.get("description")),
"user": _text(item.get("username")),
"size": size if isinstance(size, int) and not isinstance(size, bool) else None,
}
def config_revisions(answer: Any) -> list[ConfigRevisionDict]:
"""The revisions of a ``backups/this`` *answer*, newest first.
An entry without a usable id is left out: nothing could read or revert it.
:raises ValueError: for an answer that is no history, which is not "no revisions".
"""
items = answer.get("items") if isinstance(answer, dict) else None
if not isinstance(items, list):
raise ValueError("the firewall answered with no configuration history")
revisions = [r for r in map(_revision, items) if r is not None]
# By the file name's time, as OPNsense itself orders them.
revisions.sort(key=_stamp, reverse=True)
return revisions
class OPNsenseConfigRevisionsMixin(ConfigRevisionsMixin):
"""List, read and revert to the firewall's configuration revisions; see the module."""
#: No API takes an uploaded config.xml (NAPALM's base stub would only raise).
load_replace_candidate = None
if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers
def _get(self, path: str) -> dict[str, Any]: ...
def _get_text(self, path: str) -> str: ...
def _post(self, path: str, data: dict[str, Any] | None = None) -> dict[str, Any]: ...
def get_config_revisions(self) -> list[ConfigRevisionDict]:
"""The firewall's configuration history, newest first; the first is in place now.
:raises Exception: when the history cannot be read, e.g. by a key without the
backup privilege.
"""
return config_revisions(self._get(HISTORY_PATH))
def get_config_revision(self, revision_id: str) -> str:
"""The config.xml of revision *revision_id*, as the firewall keeps it.
:raises UnknownConfigRevision: for an id that is not in the history.
:raises Exception: when the firewall cannot be read.
"""
checked = _checked_id(revision_id)
text = self._get_text(DOWNLOAD_PATH.format(revision_id=checked))
if not text.strip():
raise UnknownConfigRevision(checked)
return text
def config_revision_content(self, text: str) -> str:
"""config.xml without the root's ``<revision>`` block, canonical (XML C14N).
The indentation between elements does not count; a value's own blanks do.
:raises xml.etree.ElementTree.ParseError: for a text that is no XML.
"""
# The firewall's own config.xml: see the import.
root = ET.fromstring(text) # nosec B314
for stamp in root.findall(_STAMP):
root.remove(stamp)
for element in root.iter():
if element.text is not None and not element.text.strip():
element.text = None
if element.tail is not None and not element.tail.strip():
element.tail = None
return ET.canonicalize(ET.tostring(root, encoding="unicode"))
def _revert_to_config_revision(self, revision_id: str) -> None:
"""``revert_backup``: config.xml becomes the revision, saved as the newest one."""
checked = _checked_id(revision_id)
answer = self._post(REVERT_PATH.format(revision_id=checked))
status = answer.get("status") if isinstance(answer, dict) else None
if status == _NOT_FOUND:
raise UnknownConfigRevision(checked)
if status != _REVERTED:
reason = answer.get("errorMessage") if isinstance(answer, dict) else None
raise ConfigRevertFailed(
f"The firewall did not revert to {checked}: {reason or status}"
)
def _get_latest_backup_id(self) -> str | None:
"""Return the ID of the most recent server-side config backup, or ``None``.
Calls ``GET /api/core/backup/backups/this``. The response is sorted
newest-first by OPNsense. Returns ``None`` when no backups exist or
the request fails.
"""
try:
data = self._get(HISTORY_PATH)
items = data.get("items", [])
return items[0]["id"] if items else None
except Exception as exc:
logger.debug("No backup snapshots found: %s", exc)
return None
+54
View File
@@ -0,0 +1,54 @@
"""Restarting and shutting the firewall down, through its firmware API (NetOrk/netork#2841).
``reboot_host`` and ``shutdown_host`` (napalm-device-types ``HostRebootMixin``,
``HostShutdownMixin``) and ``get_host_status`` (``HostStatusMixin``) are the
firmware controller's: ``POST /api/core/firmware/reboot`` and ``…/poweroff``, which
OPNsense has had since 16.1.15, and ``GET /api/core/firmware/status``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
class OPNsenseFirmwarePowerMixin:
if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers
def _get(self, path: str) -> dict[str, Any]: ...
def _post(self, path: str, data: dict[str, Any] | None = None) -> dict[str, Any]: ...
def reboot_host(self) -> None:
"""Restart the firewall through its firmware API (``HostRebootMixin``).
:raises RuntimeError: when the API refuses the request.
"""
try:
self._post("/api/core/firmware/reboot")
except Exception as exc:
raise RuntimeError(f"The firewall refused to reboot: {exc}") from exc
def shutdown_host(self) -> None:
"""Halt the firewall and power it off through its firmware API
(``HostShutdownMixin``).
Calls ``POST /api/core/firmware/poweroff``, which runs configd's ``firmware
poweroff`` detached, the clean shutdown of *Power → Power Off*, and answers
before the firewall goes down.
:raises RuntimeError: when the API refuses the request.
"""
try:
self._post("/api/core/firmware/poweroff")
except Exception as exc:
raise RuntimeError(f"The firewall refused to shut down: {exc}") from exc
def get_host_status(self) -> dict[str, Any]:
"""Whether the firewall needs a reboot to finish an update; it does not
patch itself as far as netOrk can tell."""
pending = self._get("/api/core/firmware/status").get("needs_reboot") == "1"
return {
"reboot_required": pending,
"reboot_reason": "the firmware status reports a pending reboot" if pending else None,
"auto_updates": None,
}
+75
View File
@@ -0,0 +1,75 @@
"""Which Kea DHCPv4 reservation or lease is whose, read from the os-kea API rows.
A reservation is the pair of an address and a MAC. Matching on the address alone
takes over or removes another host's reservation once an address was reused or
edited by hand (#26), so every lookup here checks both.
"""
from __future__ import annotations
from ipaddress import ip_address, ip_network
from typing import Any
from napalm_device_types.dhcp import normalize_mac
#: Where a ``leases4/search`` row keeps the client's MAC: os-kea, then plain Kea.
_LEASE_MAC_FIELDS = ("hwaddr", "hw-address")
def _mac_of(row: dict[str, Any], *fields: str) -> str:
return normalize_mac(next((str(row[f]) for f in fields if row.get(f)), ""))
def subnet_containing(rows: list[dict[str, Any]], ip: str) -> dict[str, Any] | None:
"""The first ``searchSubnet`` row whose subnet holds *ip*; None when none does.
A row without a readable ``subnet`` is skipped.
"""
address = ip_address(ip)
for row in rows:
try:
if address in ip_network(str(row["subnet"]).strip(), strict=False):
return row
except (ValueError, KeyError):
continue
return None
def split_by_mac(rows: list[dict[str, Any]], mac: str) -> tuple[dict[str, Any] | None, str]:
"""``(the row *mac* holds, the MAC of a row another host holds)`` among *rows*.
*rows* are ``searchReservation`` rows for one address; either part is
``None`` or ``""`` when there is none.
"""
wanted = normalize_mac(mac)
own = next((row for row in rows if _mac_of(row, "hw_address") == wanted), None)
others = [_mac_of(row, "hw_address") for row in rows]
return own, next((m for m in others if m and m != wanted), "")
def lease_held(rows: list[dict[str, Any]], ip: str, mac: str) -> bool:
"""Whether a ``leases4/search`` row gives *ip* to *mac*."""
return any(
(row.get("address") or row.get("ip-address")) == ip
and _mac_of(row, *_LEASE_MAC_FIELDS) == normalize_mac(mac)
for row in rows
)
def reservation_unchanged(row: dict[str, Any], wanted: dict[str, Any], subnet_cidr: str) -> bool:
"""Whether a ``searchReservation`` row already holds every field we would write.
The MAC is compared normalised: Kea keeps it as it was entered, in
either case and with ``:`` or ``-``. The subnet is a model relation that
comes back as the subnet's CIDR or its UUID depending on the OPNsense
version, so either counts. A field the row does not carry counts as a
difference -- writing once too often is the safe side.
"""
if str(row.get("subnet") or "").strip() not in {wanted["subnet"], subnet_cidr}:
return False
if normalize_mac(row.get("hw_address")) != normalize_mac(wanted["hw_address"]):
return False
return all(
str(row.get(field) or "") == str(wanted[field] or "")
for field in ("ip_address", "hostname", "description")
)
+156
View File
@@ -0,0 +1,156 @@
"""How people log in to the firewall: the web interface's auth servers, and SSH (NetOrk/netork#662).
**One list for the web interface, the console and SSH passwords.**
``<system><webgui><authmode>`` names auth servers, comma-separated, by their
``<name>``. Without it, only the built-in "Local Database" is used. OPNsense tries a
login against each named server in turn, and the first that accepts it lets the
person in (``AuthenticationFactory::authenticate``). A name no server has is
skipped without a word, and so is the API's own "Local API". Names are not
trimmed. The ``System`` service (``Auth/Services/System.php``) runs the same list
for ``sshd``, ``login``, ``su`` and ``sudo``, so an SSH password or
challenge-response login goes through it too. An SSH key does not: sshd checks
it itself.
**What each kind of server asks for** (``Auth/*.php``, ``getType()``):
- ``local`` and ``ldap`` ask for a password, and a ``voucher`` for its code alone.
- ``totp`` and ``ldap-totp`` ask for the password and a code in one field. A user
without an ``otp_seed`` is refused, and no option lets them through.
- ``radius`` hands the login to another system, which may ask for anything.
- Any other type is one this driver does not know.
**sshd** is written from ``<system><ssh>`` (``openssh_configure_do`` in
``plugins.inc.d/openssh.inc``):
- It runs only with ``enabled`` set. The installer's live system is not read.
- ``PasswordAuthentication`` and ``ChallengeResponseAuthentication`` follow
``passwordauth``, ``PermitRootLogin`` follows ``permitrootlogin``. Each switch is
tested with ``isset``, so an empty element counts as set.
- ``PubkeyAuthentication`` is always on. The rest is FreeBSD's defaults: PAM on,
host-based and GSSAPI off, no ``AuthenticationMethods``.
All of it is read from config.xml, the download ``get_config`` uses: no API
controller reads these settings, up to 26.7 and on ``master``.
"""
from __future__ import annotations
# config.xml as the firewall's own API hands it over; ElementTree resolves no external
# entities, and expat limits entity expansion since 2.4.1.
import xml.etree.ElementTree as ET # nosec B405
from typing import TYPE_CHECKING
from napalm_device_types import LoginFactors, LoginSourceDict, SshServerAuthDict, WebLoginAuthDict
#: config.xml itself (the newest entry of the configuration history).
CONFIG_PATH = "/api/core/backup/download/this"
#: The built-in server's name, and the one used when ``authmode`` names none.
LOCAL_DATABASE = "Local Database"
#: What each kind of auth server asks for; any other kind is ``unknown``.
FACTORS_BY_KIND: dict[str, LoginFactors] = {
"local": "password",
"ldap": "password",
"voucher": "password",
"totp": "password_otp",
"ldap-totp": "password_otp",
"radius": "external",
}
def _system(config_xml: str) -> ET.Element:
# The firewall's own config.xml: see the import.
system = ET.fromstring(config_xml).find("system") # nosec B314
return system if system is not None else ET.Element("system")
def _servers(system: ET.Element) -> dict[str, str]:
"""Each auth server's type by its name, the built-in one first (``listServers``).
A configured server needs both; one named "Local Database" replaces the built-in.
"""
servers = {LOCAL_DATABASE: "local"}
for server in system.findall("authserver"):
name = server.findtext("name") or ""
kind = server.findtext("type") or ""
if name and kind:
servers[name] = kind
return servers
def _login_sources(system: ET.Element) -> list[LoginSourceDict]:
authmode = system.findtext("webgui/authmode") or ""
names = authmode.split(",") if authmode else [LOCAL_DATABASE]
servers = _servers(system)
return [
{
"name": name,
"kind": servers[name],
"factors": FACTORS_BY_KIND.get(servers[name], "unknown"),
}
for name in names
if name in servers
]
def login_sources(config_xml: str) -> list[LoginSourceDict]:
"""The servers a login is tried against, in their order.
:raises xml.etree.ElementTree.ParseError: for a text that is no XML.
"""
return _login_sources(_system(config_xml))
def ssh_server_auth(config_xml: str) -> SshServerAuthDict:
"""sshd's login settings as config.xml makes them, and what checks a password.
:raises xml.etree.ElementTree.ParseError: for a text that is no XML.
"""
system = _system(config_xml)
ssh = system.find("ssh")
def switched(key: str) -> bool:
return ssh is not None and ssh.find(key) is not None
password = switched("passwordauth")
return {
"password_authentication": password,
"kbd_interactive_authentication": password,
"pubkey_authentication": True,
"hostbased_authentication": False,
"gssapi_authentication": False,
"authentication_methods": [],
"permit_root_login": "yes" if switched("permitrootlogin") else "no",
"use_pam": True,
"pam_auth_stack": None,
"password_sources": _login_sources(system),
"server_enabled": switched("enabled"),
}
class OPNsenseLoginAuthMixin:
"""Read how the web interface and SSH let people log in; change nothing."""
if TYPE_CHECKING: # pragma: no cover - the driver's REST helper
def _get_text(self, path: str) -> str: ...
def get_web_login_auth(self) -> WebLoginAuthDict:
"""The auth servers the web interface tries, in their order.
Example::
{"sources": [{"name": "TOTP", "kind": "totp", "factors": "password_otp"}]}
:raises Exception: when config.xml cannot be read, e.g. by a key without
the backup privilege.
"""
return {"sources": login_sources(self._get_text(CONFIG_PATH))}
def get_ssh_server_auth(self) -> SshServerAuthDict:
"""sshd's login settings from config.xml, with ``password_sources`` and
``server_enabled`` (napalm-device-types' ``SshServerAuthDict``).
:raises Exception: when config.xml cannot be read.
"""
return ssh_server_auth(self._get_text(CONFIG_PATH))
+198 -304
View File
@@ -41,7 +41,6 @@ import logging
import re
import socket
import time
from ipaddress import ip_address, ip_network
from typing import Any
import requests
@@ -62,13 +61,27 @@ from napalm_device_types.models import (
)
from requests.exceptions import RequestException
from napalm_opnsense.api_endpoint import ALIVE_TIMEOUT, api_endpoint
from napalm_opnsense.config_revisions import OPNsenseConfigRevisionsMixin
from napalm_opnsense.firmware_power import OPNsenseFirmwarePowerMixin
from napalm_opnsense.ha import config_sync, dhcp_ha
from napalm_opnsense.kea_reservations import (
lease_held,
reservation_unchanged,
split_by_mac,
subnet_containing,
)
from napalm_opnsense.listening import parse_socket_statistics, wireguard_listen_ports
from napalm_opnsense.login_auth import OPNsenseLoginAuthMixin
from napalm_opnsense.ospf_mixin import OPNsenseOspfMixin
from napalm_opnsense.ping_mixin import OPNsensePingMixin
from napalm_opnsense.port_forwards import alias_index, port_forwards, wan_interfaces
from napalm_opnsense.resolver_mixin import OPNsenseResolverMixin
from napalm_opnsense.virtual_ips import carp_addresses
from napalm_opnsense.scheduled_jobs import OPNsenseScheduledJobsMixin
from napalm_opnsense.ssh_settings import OPNsenseSshSettingsMixin
from napalm_opnsense.time_sync import OPNsenseTimeSyncMixin
from napalm_opnsense.virtual_ips import carp_addresses, carp_master
from napalm_opnsense.wireguard import wireguard_tunnels
logger = logging.getLogger(__name__)
@@ -88,12 +101,21 @@ def _opnsense_version(versions: Any) -> str:
return ""
def _carp_master(entry: dict[str, Any]) -> bool:
"""Whether this node is MASTER for an interface address bound to a CARP VHID."""
return str(entry.get("status") or "").strip().upper() == "MASTER"
def _search_rows(data: Any, search: str) -> list[dict[str, Any]]:
"""The ``rows`` of a FreeRADIUS search answer; raises for an answer without them."""
rows = data.get("rows") if isinstance(data, dict) else None
if not isinstance(rows, list):
raise RuntimeError(f"FreeRADIUS {search} answered without rows: {data!r:.200}")
return [row for row in rows if isinstance(row, dict)]
class OPNsenseDriver(
OPNsenseFirmwarePowerMixin,
OPNsenseConfigRevisionsMixin,
OPNsenseLoginAuthMixin,
OPNsenseTimeSyncMixin,
OPNsenseScheduledJobsMixin,
OPNsenseSshSettingsMixin,
OPNsensePingMixin,
ConfigSyncMixin,
OPNsenseResolverMixin,
@@ -107,6 +129,9 @@ class OPNsenseDriver(
DRIVER_NAME = "opnsense"
# Everything runs over the REST API; there is no SSH session to open.
USES_SSH = False
# get_radius_clients()/get_radius_users() raise when the firewall does not answer,
# so an empty list is its answer (#49): a caller may take it as "none there".
RADIUS_READS_RAISE = True
SNMP_FINGERPRINT = [
FingerprintRule("opnsense", weight=8.0, mandatory=True),
]
@@ -189,9 +214,8 @@ class OPNsenseDriver(
if self.session is None:
return {"is_alive": False}
try:
host = self.hostname
port = 443
with socket.create_connection((host, port), timeout=5):
endpoint = api_endpoint(self.base_url, self.hostname)
with socket.create_connection(endpoint, timeout=ALIVE_TIMEOUT):
pass
return {"is_alive": True}
except OSError:
@@ -383,11 +407,11 @@ class OPNsenseDriver(
_add(name, addr6, "ipv6")
for family in ("ipv4", "ipv6"):
for entry in iface.get(family) or []:
if isinstance(entry, dict) and entry.get("vhid") and _carp_master(entry):
if isinstance(entry, dict) and entry.get("vhid") and carp_master(entry):
_add(name, entry.get("ipaddr") or "", family)
if not addr4:
for entry in iface.get("ipv4") or []:
if entry.get("vhid") and not _carp_master(entry):
if entry.get("vhid") and not carp_master(entry):
continue
ip_field = entry.get("ipaddr") or entry.get("ip", "")
subnet = entry.get("subnetbits") or entry.get("prefix_length")
@@ -396,7 +420,7 @@ class OPNsenseDriver(
_add(name, cidr, "ipv4")
if not addr6:
for entry in iface.get("ipv6") or []:
if entry.get("vhid") and not _carp_master(entry):
if entry.get("vhid") and not carp_master(entry):
continue
ip_field = entry.get("ipaddr") or entry.get("ip", "")
prefix = entry.get("prefixlen") or entry.get("prefix_length")
@@ -497,7 +521,7 @@ class OPNsenseDriver(
Calls ``GET /api/diagnostics/interface/get_arp``.
Each entry contains: ``interface``, ``mac``, ``ip``, ``age``.
Each entry contains: ``interface``, ``mac``, ``ip``, ``age`` (-1.0, unknown).
"""
data = self._get("/api/diagnostics/interface/get_arp")
arp_table: list[dict[str, Any]] = []
@@ -508,7 +532,7 @@ class OPNsenseDriver(
"interface": entry.get("intf") or entry.get("interface", ""),
"mac": (entry.get("mac") or "").lower(),
"ip": entry.get("ip") or entry.get("address", ""),
"age": float(entry.get("expires", 0)),
"age": -1.0, # `expires` counts down to expiry; it is no age
}
)
@@ -681,7 +705,7 @@ class OPNsenseDriver(
Calls ``GET /api/diagnostics/interface/get_ndp``.
Each entry contains: ``interface``, ``mac``, ``ip``, ``age``,
Each entry contains: ``interface``, ``mac``, ``ip``, ``age`` (-1.0, unknown),
``state`` (best-effort from NDP flags).
"""
data = self._get("/api/diagnostics/interface/get_ndp")
@@ -694,7 +718,7 @@ class OPNsenseDriver(
"interface": entry.get("intf") or entry.get("interface", ""),
"mac": (entry.get("mac") or "").lower(),
"ip": entry.get("ip") or entry.get("address", ""),
"age": float(entry.get("expires", 0)),
"age": -1.0, # `expires` counts down to expiry; it is no age
"state": entry.get("state", ""),
}
)
@@ -769,28 +793,6 @@ class OPNsenseDriver(
)
return details
def get_ntp_servers(self) -> dict[str, dict[str, Any]]:
"""Return configured NTP servers.
Calls ``GET /api/ntpd/service/status`` which includes the list of
configured peer addresses in the ``peers`` field.
Returns a dict keyed by server address with an empty value dict
(NAPALM standard format).
"""
try:
data = self._get("/api/ntpd/service/status")
except Exception as exc:
logger.debug("NTP status fetch failed (plugin not installed?): %s", exc)
return {}
servers: dict[str, dict[str, Any]] = {}
for peer in data.get("peers", []):
addr = peer.get("address") or peer.get("remote", "")
if addr:
servers[addr] = {}
return servers
def get_vlans(self) -> dict[str, dict[str, Any]]:
"""Return configured VLANs.
@@ -1106,21 +1108,6 @@ class OPNsenseDriver(
# Internal helpers (config management)
# ------------------------------------------------------------------
def _get_latest_backup_id(self) -> str | None:
"""Return the ID of the most recent server-side config backup, or ``None``.
Calls ``GET /api/core/backup/backups/this``. The response is sorted
newest-first by OPNsense. Returns ``None`` when no backups exist or
the request fails.
"""
try:
data = self._get("/api/core/backup/backups/this")
items = data.get("items", [])
return items[0]["id"] if items else None
except Exception as exc:
logger.debug("No backup snapshots found: %s", exc)
return None
def _fetch_current_routes(self) -> list[dict[str, Any]]:
"""Return the current static routes from the OPNsense API.
@@ -1234,13 +1221,11 @@ class OPNsenseDriver(
def get_radius_clients(self) -> list[dict[str, Any]]:
"""Return configured FreeRADIUS NAS clients.
Calls ``GET /api/freeradius/client/search_client``.
Calls ``GET /api/freeradius/client/search_client``. Raises when the
request fails or the answer holds no ``rows`` list: an empty list means
the firewall has no clients, never that it did not answer (#49).
"""
try:
data = self._get("/api/freeradius/client/search_client")
except Exception as exc:
logger.warning("get_radius_clients() failed: %s", exc)
return []
data = self._get("/api/freeradius/client/search_client")
return [
{
"id": row.get("uuid", ""),
@@ -1248,7 +1233,7 @@ class OPNsenseDriver(
"ip": row.get("ip", ""),
"enabled": row.get("enabled") == "1",
}
for row in data.get("rows", [])
for row in _search_rows(data, "search_client")
]
def create_radius_client(self, name: str, ip: str, secret: str) -> dict[str, Any]:
@@ -1266,7 +1251,11 @@ class OPNsenseDriver(
if result.get("result") != "saved":
return {"success": False, "validations": result.get("validations", {})}
self._post("/api/freeradius/service/reconfigure")
created = next((c for c in self.get_radius_clients() if c["name"] == name), None)
try:
created = next((c for c in self.get_radius_clients() if c["name"] == name), None)
except Exception as exc: # the add went through; only its id is unknown
logger.warning("create_radius_client(): looking up the new client failed: %s", exc)
created = None
return {"success": True, "id": created["id"] if created else None}
def delete_radius_client(self, client_id: str) -> dict[str, Any]:
@@ -1281,20 +1270,16 @@ class OPNsenseDriver(
"""Return configured FreeRADIUS users.
Calls ``GET /api/freeradius/user/search_user``. Never includes the
password field.
password field. Raises like ``get_radius_clients()`` (#49).
"""
try:
data = self._get("/api/freeradius/user/search_user")
except Exception as exc:
logger.warning("get_radius_users() failed: %s", exc)
return []
data = self._get("/api/freeradius/user/search_user")
return [
{
"id": row.get("uuid", ""),
"username": row.get("username", ""),
"enabled": row.get("enabled") == "1",
}
for row in data.get("rows", [])
for row in _search_rows(data, "search_user")
]
def create_radius_user(self, username: str, password: str) -> dict[str, Any]:
@@ -1311,7 +1296,11 @@ class OPNsenseDriver(
if result.get("result") != "saved":
return {"success": False, "validations": result.get("validations", {})}
self._post("/api/freeradius/service/reconfigure")
created = next((u for u in self.get_radius_users() if u["username"] == username), None)
try:
created = next((u for u in self.get_radius_users() if u["username"] == username), None)
except Exception as exc: # the add went through; only its id is unknown
logger.warning("create_radius_user(): looking up the new user failed: %s", exc)
created = None
return {"success": True, "id": created["id"] if created else None}
def delete_radius_user(self, user_id: str) -> dict[str, Any]:
@@ -1451,42 +1440,21 @@ class OPNsenseDriver(
:param hostname: optional hostname to record on the reservation.
:raises ValueError: if no Kea subnet contains ``ip``.
:raises RuntimeError: if Kea rejects the reservation (validation
errors) or the Kea plugin isn't installed/enabled.
errors), the Kea plugin isn't installed/enabled, the search for an
existing reservation fails (nothing is written then), or ``ip`` is
already reserved for another MAC (left untouched; the caller decides).
"""
try:
subnets = self._get("/api/kea/dhcpv4/searchSubnet").get("rows") or []
except Exception as exc:
raise RuntimeError(f"Kea DHCPv4 plugin unavailable: {exc}") from exc
ip_obj = ip_address(ip)
subnet_uuid = None
subnet_cidr = ""
for row in subnets:
try:
if ip_obj in ip_network(row["subnet"], strict=False):
subnet_uuid = row["uuid"]
subnet_cidr = str(row["subnet"]).strip()
break
except ValueError:
continue
if subnet_uuid is None:
subnet_row = subnet_containing(subnets, ip)
if subnet_row is None:
raise ValueError(f"No Kea-managed subnet contains {ip}")
subnet_uuid, subnet_cidr = subnet_row["uuid"], str(subnet_row["subnet"]).strip()
# Idempotency: reuse an existing reservation for this IP if one
# already exists (e.g. a retried provisioning job), rather than
# creating a duplicate Kea rejects anyway.
existing_row: dict[str, Any] | None = None
try:
existing = self._post(
"/api/kea/dhcpv4/searchReservation",
{"current": 1, "rowCount": -1, "searchPhrase": ip},
)
for row in existing.get("rows") or []:
if row.get("ip_address") == ip:
existing_row = row
break
except Exception as exc:
logger.debug("Kea reservation search failed, proceeding to add: %s", exc)
existing_row = self._kea_own_reservation(ip, mac)
payload = {
"reservation": {
@@ -1497,7 +1465,7 @@ class OPNsenseDriver(
"description": self._NETORK_TAG,
}
}
if existing_row is not None and self._kea_reservation_unchanged(
if existing_row is not None and reservation_unchanged(
existing_row, payload["reservation"], subnet_cidr
):
logger.debug("Kea reservation for %s is already as requested, not touched", ip)
@@ -1515,26 +1483,25 @@ class OPNsenseDriver(
self._post("/api/kea/service/reconfigure")
@staticmethod
def _kea_reservation_unchanged(
row: dict[str, Any], wanted: dict[str, Any], subnet_cidr: str
) -> bool:
"""Whether a ``searchReservation`` row already holds every field we would write.
The MAC is compared normalised: Kea keeps it as it was entered, in
either case and with ``:`` or ``-``. The subnet is a model relation that
comes back as the subnet's CIDR or its UUID depending on the OPNsense
version, so either counts. A field the row does not carry counts as a
difference -- writing once too often is the safe side.
"""
if str(row.get("subnet") or "").strip() not in {wanted["subnet"], subnet_cidr}:
return False
if normalize_mac(row.get("hw_address")) != normalize_mac(wanted["hw_address"]):
return False
return all(
str(row.get(field) or "") == str(wanted[field] or "")
for field in ("ip_address", "hostname", "description")
def _kea_reservations_at(self, ip: str) -> list[dict[str, Any]]:
"""The ``searchReservation`` rows for *ip* -- the search is a phrase match."""
found = self._post(
"/api/kea/dhcpv4/searchReservation",
{"current": 1, "rowCount": -1, "searchPhrase": ip},
)
return [row for row in found.get("rows") or [] if row.get("ip_address") == ip]
def _kea_own_reservation(self, ip: str, mac: str) -> dict[str, Any] | None:
"""*mac*'s reservation for *ip*, updated in place on a retry; raises if another
MAC holds *ip* (#26) or the search fails (#40)."""
try:
rows = self._kea_reservations_at(ip)
except RequestException as exc:
raise RuntimeError(f"Kea searchReservation for {ip} failed: {exc}") from exc
own, other = split_by_mac(rows, mac)
if own is None and other:
raise RuntimeError(f"Kea already reserves {ip} for {other}, not {normalize_mac(mac)}")
return own
def delete_dhcp_reservation_and_lease(self, mac: str, ip: str) -> dict[str, Any]:
"""Remove a Kea DHCPv4 static reservation and any active lease for (mac, ip).
@@ -1564,10 +1531,14 @@ class OPNsenseDriver(
returns ``{"status": "error", "message": "Missing lease IP
parameter"}``; only ``POST /api/kea/leases4/del_lease/{ip}`` works.
Both match on ``ip`` and ``mac``: another MAC's (an address reused or
edited by hand) is left alone, its reservation reported (#26).
:param mac: NIC MAC address of the reservation to remove.
:param ip: IP address of the reservation/lease to remove.
:returns: {"reservation_found", "reservation_deleted", "lease_found",
"lease_deleted"} — all bool.
"lease_deleted"} — all bool — and ``reservation_other_mac``, the MAC
another host holds a reservation for ``ip`` under ("" if none).
:raises RuntimeError: Kea plugin unavailable, or Kea rejects
deletion of a reservation that does exist.
"""
@@ -1576,26 +1547,22 @@ class OPNsenseDriver(
"reservation_deleted": False,
"lease_found": False,
"lease_deleted": False,
"reservation_other_mac": "",
}
# --- Reservation ---
try:
existing = self._post(
"/api/kea/dhcpv4/searchReservation",
{"current": 1, "rowCount": -1, "searchPhrase": ip},
)
rows = self._kea_reservations_at(ip)
except Exception as exc:
raise RuntimeError(f"Kea DHCPv4 plugin unavailable: {exc}") from exc
reservation_uuid = None
for row in existing.get("rows") or []:
if row.get("ip_address") == ip:
reservation_uuid = row.get("uuid")
break
own, result["reservation_other_mac"] = split_by_mac(rows, mac)
if result["reservation_other_mac"]:
logger.warning("Kea reservation of another MAC for %s left alone", ip)
if reservation_uuid:
if own and own.get("uuid"):
result["reservation_found"] = True
del_result = self._post(f"/api/kea/dhcpv4/delReservation/{reservation_uuid}")
del_result = self._post(f"/api/kea/dhcpv4/delReservation/{own['uuid']}")
if del_result.get("result") != "deleted":
raise RuntimeError(f"Kea rejected reservation delete for {ip}: {del_result}")
result["reservation_deleted"] = True
@@ -1605,7 +1572,7 @@ class OPNsenseDriver(
try:
leases = self._get("/api/kea/leases4/search")
rows = leases.get("rows") or leases.get("leases") or []
if any((row.get("address") or row.get("ip-address")) == ip for row in rows):
if lease_held(rows, ip, mac):
result["lease_found"] = True
del_lease = self._post(f"/api/kea/leases4/del_lease/{ip}")
result["lease_deleted"] = bool(
@@ -1643,14 +1610,10 @@ class OPNsenseDriver(
return str(row["uuid"])
raise ValueError(f"No Kea-managed subnet matches {subnet}")
ip_obj = ip_address(ip)
for row in rows:
try:
if ip_obj in ip_network(row["subnet"], strict=False):
return str(row["uuid"])
except (ValueError, KeyError):
continue
raise ValueError(f"No Kea-managed subnet contains {ip}")
row = subnet_containing(rows, ip)
if row is None:
raise ValueError(f"No Kea-managed subnet contains {ip}")
return str(row["uuid"])
def get_dhcp_reservations(self) -> list[dict[str, Any]]:
"""Return all Kea DHCPv4 static reservations, vendor-neutral.
@@ -2011,9 +1974,7 @@ class OPNsenseDriver(
``enable`` and ``disable`` are not supported on OPNsense (plugins
are enabled/disabled by installing or removing them).
"""
import re as _re
if not _re.match(r"^[a-zA-Z0-9_\-]+$", name):
if not re.match(r"^[a-zA-Z0-9_\-]+$", name):
raise ValueError(f"Invalid service name: {name!r}")
if action not in ("start", "stop", "restart"):
return {
@@ -2167,51 +2128,7 @@ class OPNsenseDriver(
# ── WireGuard ──────────────────────────────────────────────────────
try:
# /api/wireguard/service/show returns structured JSON:
# {"total": N, "rows": [
# {"if":"wg0", "type":"interface", ...},
# {"if":"wg0", "type":"peer", "public-key":"...",
# "endpoint":"1.2.3.4:51820", "transfer-rx":N, "transfer-tx":N,
# "name":"HCQ", "peer-status":"online",
# "latest-handshake-age":45, "ifname":"HCQ"}, ...
# ]}
data = self._get("/api/wireguard/service/show")
rows = data.get("rows", []) if isinstance(data, dict) else []
wg_idx = 0
for row in rows:
if row.get("type") != "peer":
continue
wg_idx += 1
endpoint = (row.get("endpoint") or "").strip()
if endpoint and endpoint != "(none)":
remote_ip = endpoint.rsplit(":", 1)[0].strip("[]")
else:
remote_ip = ""
is_up = row.get("peer-status") == "online"
bytes_in = int(row.get("transfer-rx") or 0)
bytes_out = int(row.get("transfer-tx") or 0)
hs_age = row.get("latest-handshake-age")
uptime = int(hs_age) if hs_age else 0
description = (
(row.get("name") or "").strip()
or (row.get("ifname") or "").strip()
or f"wg-peer-{wg_idx}"
)
tunnels[f"wireguard-{wg_idx}"] = {
"type": "WireGuard",
"local_endpoint": "",
"remote_endpoint": remote_ip,
"is_up": is_up,
"uptime": uptime,
"bytes_in": bytes_in,
"bytes_out": bytes_out,
"description": description,
}
tunnels.update(wireguard_tunnels(self._get("/api/wireguard/service/show")))
except Exception as exc:
logger.debug("WireGuard status fetch failed (plugin not installed?): %s", exc)
@@ -2267,26 +2184,6 @@ class OPNsenseDriver(
),
}
def reboot_host(self) -> None:
"""Restart the firewall through its firmware API (``HostRebootMixin``).
:raises RuntimeError: when the API refuses the request.
"""
try:
self._post("/api/core/firmware/reboot")
except Exception as exc:
raise RuntimeError(f"The firewall refused to reboot: {exc}") from exc
def get_host_status(self) -> dict[str, Any]:
"""Whether the firewall needs a reboot to finish an update; it does not
patch itself as far as netOrk can tell."""
pending = self._get("/api/core/firmware/status").get("needs_reboot") == "1"
return {
"reboot_required": pending,
"reboot_reason": "the firmware status reports a pending reboot" if pending else None,
"auto_updates": None,
}
def apply_updates(self, packages: list[str]) -> dict[str, Any]:
"""Start the firmware upgrade of *packages*, or of everything for none.
@@ -2481,6 +2378,8 @@ class OPNsenseDriver(
#: old any-source rule is recognised by its older description.
_SNMP_RULE_PREFIX = "napalm-opnsense: SNMP from "
_SNMP_RULE_OLD = "[netork] Allow SNMP"
#: The caller's system values and the os-net-snmp fields they go to.
_SNMP_SYSTEM_FIELDS = {"contact": "syscontact", "location": "syslocation"}
def _install_snmp_agent(self) -> FixStepOutcomeDict:
# Installing over an installed os-net-snmp starts an async reinstall that
@@ -2495,34 +2394,33 @@ class OPNsenseDriver(
time.sleep(5) # the install settles before its API answers
return {"ok": result.get("status") == "ok", "output": f"os-net-snmp install: {result}"}
def _write_snmp_agent_config(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
community = settings["community"]
@staticmethod
def _check_snmp_community(community: str) -> None:
if not community or any(c.isspace() or c in '"#' for c in community):
raise ValueError("the community must be one word without quotes or #")
listen = settings.get("listen") or self.hostname
def _snmp_listen_address(self, settings: SnmpAgentSettingsDict) -> str:
try:
listen_val = {str(ipaddress.ip_address(listen)): {"selected": 1}}
return str(ipaddress.ip_address(settings.get("listen") or self.hostname))
except ValueError:
listen_val = {} # a DNS name binds nothing; snmpd then listens everywhere
result = self._post(
"/api/netsnmp/general/set",
{
"general": {
"enabled": "1",
"community": community,
"contact": settings.get("contact", ""),
"location": settings.get("location", ""),
"sysobjid": "",
"bindip": "",
"listen": listen_val,
}
},
)
return "" # a DNS name binds nothing; snmpd then listens everywhere
def _write_snmp_agent_config(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
community = settings["community"]
self._check_snmp_community(community)
listen_val = self._snmp_listen_address(settings)
general = {"enabled": "1", "community": community, "listen": listen_val}
# Only what the caller gives: an empty one would blank the operator's.
for key, field in self._SNMP_SYSTEM_FIELDS.items():
if settings.get(key):
general[field] = settings[key]
# The plugin's model refuses any field it does not have, with a 500 (#36).
result = self._post("/api/netsnmp/general/set", {"general": general})
if result.get("result") != "saved":
return {"ok": False, "output": f"configuration refused: {result}"}
return {
"ok": True,
"output": f"community set, listen {list(listen_val) or 'all addresses'}",
"output": f"community set, listen {listen_val or 'all addresses'}",
}
def _allow_snmp_sources(self, settings: SnmpAgentSettingsDict) -> FixStepOutcomeDict:
@@ -2849,15 +2747,16 @@ class OPNsenseDriver(
# ------------------------------------------------------------------
def _detect_active_dns(self) -> str | None:
"""Return 'unbound' or 'dnsmasq' depending on which service is running."""
try:
data = self._get("/api/core/service/search")
for row in data.get("rows", []):
name = (row.get("name") or "").lower()
if name in ("unbound", "dnsmasq") and row.get("running"):
return name
except Exception as exc:
logger.warning("DNS service detection failed: %s", exc)
"""Return 'unbound' or 'dnsmasq' depending on which service is running.
None only when the service list was read and neither runs; a failed
read raises, so it cannot pass for "no DNS service".
"""
data = self._get("/api/core/service/search")
for row in data.get("rows", []):
name = (row.get("name") or "").lower()
if name in ("unbound", "dnsmasq") and row.get("running"):
return name
return None
def get_dns_entries(self) -> list[dict[str, Any]]:
@@ -2865,7 +2764,8 @@ class OPNsenseDriver(
Checks whether Unbound (DNS Resolver) or Dnsmasq (DNS Forwarder) is
running and returns host overrides from whichever is active. If neither
is running, returns an empty list.
is running, returns an empty list. A failed read of the service list
or of the overrides raises.
Each entry::
@@ -2891,81 +2791,75 @@ class OPNsenseDriver(
def _get_unbound_host_overrides(self) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
seen: set[tuple[str, str, str, str]] = set()
try:
data = self._post(
"/api/unbound/settings/searchhostoverride",
{"current": 1, "rowCount": -1, "searchPhrase": ""},
)
rows = data.get("rows", []) or []
# searchhostoverride lists alias records alongside the host override
# they hang off, each under its own UUID. OPNsense flags them, so
# skip them by that flag and report every remaining row as it is —
# including two rows that happen to hold the same name and address.
# Those are duplicates on the device, and sync_dns_zone can only
# clear the copies it is told about.
flagged = any("isAlias" in row for row in rows)
for row in rows:
if flagged and row.get("isAlias"):
data = self._post(
"/api/unbound/settings/searchhostoverride",
{"current": 1, "rowCount": -1, "searchPhrase": ""},
)
rows = data.get("rows", []) or []
# searchhostoverride lists alias records alongside the host override
# they hang off, each under its own UUID. OPNsense flags them, so
# skip them by that flag and report every remaining row as it is —
# including two rows that happen to hold the same name and address.
# Those are duplicates on the device, and sync_dns_zone can only
# clear the copies it is told about.
flagged = any("isAlias" in row for row in rows)
for row in rows:
if flagged and row.get("isAlias"):
continue
host = row.get("hostname", "") or ""
domain = row.get("domain", "") or ""
fqdn = f"{host}.{domain}" if host and domain else host or domain
ip = row.get("server", "") or ""
rr = row.get("rr", "A") or "A"
if not flagged:
# Releases without the flag give nothing to tell an alias
# apart from a copy, so collapsing by content stays the
# safer read there.
key = (host.lower(), domain.lower(), ip, rr)
if key in seen:
continue
host = row.get("hostname", "") or ""
domain = row.get("domain", "") or ""
fqdn = f"{host}.{domain}" if host and domain else host or domain
ip = row.get("server", "") or ""
rr = row.get("rr", "A") or "A"
if not flagged:
# Releases without the flag give nothing to tell an alias
# apart from a copy, so collapsing by content stays the
# safer read there.
key = (host.lower(), domain.lower(), ip, rr)
if key in seen:
continue
seen.add(key)
# The auto-PTR flag is "addptr" since 25.x, "ptrrecord" before.
ptr = row.get("addptr", row.get("ptrrecord", "1"))
result.append(
{
"uuid": row.get("uuid", ""),
"hostname": host,
"domain": domain,
"fqdn": fqdn,
"ip": ip,
"record_type": rr,
"description": row.get("description", "") or "",
"enabled": str(row.get("enabled", "1")) == "1",
"ptrrecord": str(ptr) == "1",
"service": "unbound",
}
)
except Exception as exc:
logger.warning("Failed to fetch Unbound host overrides: %s", exc)
seen.add(key)
# The auto-PTR flag is "addptr" since 25.x, "ptrrecord" before.
ptr = row.get("addptr", row.get("ptrrecord", "1"))
result.append(
{
"uuid": row.get("uuid", ""),
"hostname": host,
"domain": domain,
"fqdn": fqdn,
"ip": ip,
"record_type": rr,
"description": row.get("description", "") or "",
"enabled": str(row.get("enabled", "1")) == "1",
"ptrrecord": str(ptr) == "1",
"service": "unbound",
}
)
return sorted(result, key=lambda e: e["fqdn"].lower())
def _get_dnsmasq_host_overrides(self) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
try:
data = self._post(
"/api/dnsmasq/settings/searchhostoverride",
{"current": 1, "rowCount": -1, "searchPhrase": ""},
data = self._post(
"/api/dnsmasq/settings/searchhostoverride",
{"current": 1, "rowCount": -1, "searchPhrase": ""},
)
for row in data.get("rows", []):
host = row.get("host", "") or ""
domain = row.get("domain", "") or ""
fqdn = f"{host}.{domain}" if host and domain else host or domain
result.append(
{
"uuid": row.get("uuid", ""),
"hostname": host,
"domain": domain,
"fqdn": fqdn,
"ip": row.get("ip", "") or "",
"record_type": "A",
"description": row.get("description", "") or "",
"enabled": str(row.get("enabled", "1")) == "1",
"service": "dnsmasq",
}
)
for row in data.get("rows", []):
host = row.get("host", "") or ""
domain = row.get("domain", "") or ""
fqdn = f"{host}.{domain}" if host and domain else host or domain
result.append(
{
"uuid": row.get("uuid", ""),
"hostname": host,
"domain": domain,
"fqdn": fqdn,
"ip": row.get("ip", "") or "",
"record_type": "A",
"description": row.get("description", "") or "",
"enabled": str(row.get("enabled", "1")) == "1",
"service": "dnsmasq",
}
)
except Exception as exc:
logger.warning("Failed to fetch Dnsmasq host overrides: %s", exc)
return sorted(result, key=lambda e: e["fqdn"].lower())
def set_dns_entry(self, uuid: str, service: str, data: dict[str, Any]) -> dict[str, Any]:
+314
View File
@@ -0,0 +1,314 @@
"""Scheduled jobs on OPNsense: the cron jobs of its configuration (napalm-device-types).
OPNsense keeps its cron jobs in config.xml (System > Settings > Cron) and writes
them into the crontab itself; each job runs one **configd action** with optional
parameters, never a shell line. The REST API reads and writes them:
``/api/cron/settings/get`` answers with every job at once, the action as the
option its ``command`` list has selected; ``get_job`` without a uuid is a blank
job whose ``command`` options are the actions configd offers; ``add_job``,
``set_job``, ``del_job`` and ``toggle_job`` write, ``/api/cron/service/reconfigure``
regenerates the crontab. OPNsense routes ``search_jobs`` and ``searchJobs`` to the
same action; the snake-case spelling is the documented one.
**Who owns a job.** A job another component registered (its ``origin`` is not
``cron``: the intrusion detection's rule update, say) is ``platform``. A job whose
description starts with ``napalm-scheduled-job: <name>`` was written through
:meth:`OPNsenseScheduledJobsMixin.put_scheduled_job` (``application``); every other
one an admin made (``admin``). Every job can be enabled and disabled; only an
application's job can be edited or deleted.
**Not here.** The API cannot run a configd action now, so no job takes ``run``.
What OPNsense puts in the crontab beyond config.xml -- ``periodic``, the plugins'
own system jobs -- is not reachable over the API and is not read. The time zone
is not read either (None).
**Parameters, one per line.** Up to 26.1 OPNsense split the parameters the way a
shell does; 26.7 takes one argument per line. Arguments without blanks, quotes
or backslashes, one per line, mean the same to both, so those are all a job
written here takes.
"""
from __future__ import annotations
import re
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from napalm_device_types.cron import ALIASES, is_reboot
from napalm_device_types.scheduled_jobs import (
ACTIONS,
DELETE,
EDIT,
ScheduledJobChanged,
ScheduledJobDict,
ScheduledJobRefused,
ScheduledJobResultDict,
ScheduledJobsMixin,
ScheduledJobSpecDict,
ScheduledJobsReadingDict,
check_job_name,
check_spec,
job_digest,
)
_SETTINGS = "/api/cron/settings"
_RECONFIGURE = "/api/cron/service/reconfigure"
_KEY = "opnsense:"
#: The origin of a job made in the cron settings themselves.
_OWN_ORIGIN = "cron"
#: How a job written by put_scheduled_job begins its description.
MARKER = "napalm-scheduled-job: "
_FIELDS = ("minutes", "hours", "days", "months", "weekdays")
_SWITCH = ["enable", "disable"]
_OWN = [*_SWITCH, EDIT, DELETE]
#: OPNsense's month and weekday fields take numbers (months also upper case names).
_MONTHS = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")
_WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
_NAME = re.compile(r"[A-Za-z]+")
#: A parameter every OPNsense release hands configd as one argument.
_PLAIN_ARGUMENT = re.compile(r"[^\s'\"\\]+")
def _selected(field: Any) -> str:
"""The option a list field has selected (none: ""); a plain value as it is."""
if not isinstance(field, dict):
return str(field or "")
chosen = (k for k, o in field.items() if isinstance(o, dict) and o.get("selected") in (1, "1"))
return next(chosen, "")
def _command(node: dict[str, Any]) -> str:
"""The configd action and its parameters, as one line."""
parameters = str(node.get("parameters") or "").splitlines()
return " ".join([_selected(node.get("command")), *(p.strip() for p in parameters if p.strip())])
def _schedule(uuid: str, node: dict[str, Any]) -> str:
fields = [node.get(field) for field in _FIELDS]
if not all(isinstance(f, str) and f.strip() for f in fields):
raise ValueError(f"cron job {uuid} came back without its schedule")
return " ".join(str(f).strip() for f in fields)
def _ownership(origin: str, description: str) -> tuple[str, str | None, str]:
"""(managed_by, the application's job name or None, the description to show)."""
if origin != _OWN_ORIGIN:
return "platform", None, description
if not description.startswith(MARKER):
return "admin", None, description
name, _, rest = description[len(MARKER) :].partition(" ")
try:
check_job_name(name)
except ScheduledJobRefused:
return "admin", None, description
return "application", name, rest.strip()
def scheduled_job(uuid: str, node: dict[str, Any]) -> ScheduledJobDict:
"""One job of the cron settings, as napalm-device-types reads it."""
origin = str(node.get("origin") or _OWN_ORIGIN)
managed_by, name, description = _ownership(origin, str(node.get("description") or ""))
job: dict[str, Any] = {
"key": f"{_KEY}{uuid}",
"kind": "cron",
"source": "config.xml",
# The crontab line calls configctl; configd runs the action as root.
"run_as": "root",
"schedule": _schedule(uuid, node),
"schedule_kind": "cron",
"command": _command(node),
"enabled": str(node.get("enabled")) == "1",
"managed_by": managed_by,
"actions": list(_OWN if name else _SWITCH),
}
if name:
job["name"] = name
if description:
job["description"] = description
job["digest"] = job_digest(job)
return job # type: ignore[return-value]
def scheduled_jobs(answer: Any) -> list[ScheduledJobDict]:
"""Every job in an answer of ``/api/cron/settings/get``.
:raises ValueError: when the answer has no list of jobs -- never "no jobs".
"""
try:
jobs = answer["job"]["jobs"]["job"]
except (KeyError, TypeError) as exc:
raise ValueError("the cron settings came back without their jobs") from exc
if jobs == []: # an empty ArrayField comes back as a JSON list
return []
if not isinstance(jobs, dict):
raise ValueError(f"the cron settings came back with jobs as {type(jobs).__name__}")
return [scheduled_job(uuid, node) for uuid, node in jobs.items()]
def _numbers(field: str, names: tuple[str, ...], low: int) -> str:
return _NAME.sub(lambda m: str(names.index(m.group().lower()) + low), field)
def cron_fields(schedule: str) -> dict[str, str]:
"""The five fields OPNsense stores of *schedule*, which :func:`check_spec` passed."""
if is_reboot(schedule):
raise ScheduledJobRefused("OPNsense's cron jobs have no @reboot")
text = schedule.strip()
fields = ALIASES.get(text.lower(), text).split()
fields[3] = _numbers(fields[3], _MONTHS, 1)
fields[4] = _numbers(fields[4], _WEEKDAYS, 0)
return dict(zip(_FIELDS, fields, strict=True))
def configd_action(command: str, actions: Iterable[str]) -> tuple[str, list[str]]:
"""(the configd action *command* names, its parameters).
The action is the longest one configd offers that *command* starts with; the
words after it are its parameters.
"""
if "\n" in command.strip():
raise ScheduledJobRefused("an OPNsense job runs one configd action, on one line")
words = command.split()
known = set(actions)
for end in range(len(words), 0, -1):
action = " ".join(words[:end])
if action in known:
parameters = words[end:]
for parameter in parameters:
if not _PLAIN_ARGUMENT.fullmatch(parameter):
raise ScheduledJobRefused(f"not a parameter OPNsense passes on: {parameter!r}")
return action, parameters
raise ScheduledJobRefused(
f"configd offers no action {command!r}; get_scheduled_job_commands() lists them"
)
def _saved(result: dict[str, Any], what: str) -> None:
if result.get("result") == "saved":
return
if result.get("validations"):
raise ScheduledJobRefused(f"OPNsense refused {what}: {result['validations']}")
raise RuntimeError(f"OPNsense did not save {what}: {result}")
class OPNsenseScheduledJobsMixin(ScheduledJobsMixin):
"""The cron jobs of config.xml; needs the driver's ``_get`` and ``_post``."""
if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers
def _get(self, path: str) -> dict[str, Any]: ...
def _post(self, path: str, data: dict[str, Any] | None = None) -> dict[str, Any]: ...
def get_scheduled_job_commands(self) -> list[dict[str, str]]:
"""The configd actions a job can run: ``[{"command", "description"}]``, by command.
:raises ValueError: when the list came back empty -- configd did not answer.
"""
answer = self._get(f"{_SETTINGS}/get_job")
job = answer.get("job") if isinstance(answer, dict) else None
options = job.get("command") if isinstance(job, dict) else None
if not isinstance(options, dict) or not options:
raise ValueError("the cron settings came back without configd's actions")
return [
{"command": key, "description": str(option.get("value") or key)}
for key, option in sorted(options.items())
if key and isinstance(option, dict)
]
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
"""Every cron job of config.xml, in one request; the time zone is not read.
:raises ValueError: when the answer came back without its jobs.
"""
return {"jobs": scheduled_jobs(self._get(f"{_SETTINGS}/get")), "time_zone": None}
def _sj_job(self, key: str, digest: str) -> ScheduledJobDict:
job = next((j for j in self.get_scheduled_jobs()["jobs"] if j["key"] == key), None)
if job is None:
raise LookupError(f"no scheduled job {key}")
if job["digest"] != digest:
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
return job
def _sj_own(self, name: str, digest: str | None) -> ScheduledJobDict | None:
jobs = self.get_scheduled_jobs()["jobs"]
current = next((j for j in jobs if j.get("name") == name), None)
if digest is None:
if current is not None:
raise ScheduledJobChanged(f"a job {name} is there already")
return None
if current is None:
raise LookupError(f"no scheduled job named {name}")
if current["digest"] != digest:
raise ScheduledJobChanged(f"{current['key']} changed on the host since it was read")
return current
def _sj_reload(self) -> None:
result = self._post(_RECONFIGURE)
if result.get("status") != "ok":
raise RuntimeError(f"cron did not reload: {result}")
def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict:
"""Enable or disable the job *key*; no job runs now (the API cannot)."""
if action not in ACTIONS:
raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}")
job = self._sj_job(key, digest)
if action not in job["actions"]:
raise ScheduledJobRefused(
f"{key} cannot {action}: OPNsense's API does not run a configd action now"
)
flag = "1" if action == "enable" else "0"
uuid = key.removeprefix(_KEY)
result = self._post(f"{_SETTINGS}/toggle_job/{uuid}/{flag}")
if result.get("result") not in ("Enabled", "Disabled"):
raise RuntimeError(f"OPNsense did not {action} {key}: {result}")
self._sj_reload()
return {"success": True, "output": f"{key} {action}d"}
def put_scheduled_job(
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
) -> ScheduledJobResultDict:
"""Create or change the application's job ``spec["name"]``.
``command`` is a configd action (:meth:`get_scheduled_job_commands`), with
its parameters after it.
"""
check_spec(spec)
if spec["run_as"] != "root":
raise ScheduledJobRefused("an OPNsense job runs its configd action as root")
fields = cron_fields(spec["schedule"])
commands = (c["command"] for c in self.get_scheduled_job_commands())
action, parameters = configd_action(spec["command"], commands)
current = self._sj_own(spec["name"], digest)
job = {
"enabled": "1" if spec["enabled"] else "0",
**fields,
"command": action,
"parameters": "\n".join(parameters),
"description": f"{MARKER}{spec['name']} {spec.get('description') or ''}".rstrip(),
}
if current is None:
result = self._post(f"{_SETTINGS}/add_job", {"job": job})
uuid = str(result.get("uuid") or "")
else:
uuid = current["key"].removeprefix(_KEY)
result = self._post(f"{_SETTINGS}/set_job/{uuid}", {"job": job})
_saved(result, f"the job {spec['name']}")
self._sj_reload()
return {"success": True, "output": f"{_KEY}{uuid} {'changed' if current else 'created'}"}
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
"""Delete the application's job *key*; any other job is only switched."""
job = self._sj_job(key, digest)
if job["managed_by"] != "application":
raise ScheduledJobRefused(
f"{key} was not written by an application; it is only switched"
)
result = self._post(f"{_SETTINGS}/del_job/{key.removeprefix(_KEY)}")
if result.get("result") != "deleted":
raise RuntimeError(f"OPNsense did not delete {key}: {result}")
self._sj_reload()
return {"success": True, "output": f"{key} deleted"}
+32
View File
@@ -0,0 +1,32 @@
"""Where the firewall's SSH server takes its algorithm lists from (NetOrk/netork#1769).
OPNsense writes sshd_config itself, from config.xml (``<system><ssh>``: ``kex``,
``ciphers``, ``macs``, ``keys`` and ``keysig``, comma-separated), whenever the
service is configured (``openssh_configure_do`` in ``plugins.inc.d/openssh.inc``).
The section is set on the legacy page ``system_advanced_admin.php``; no API
controller reads or writes it, up to 26.7 and on ``master``. So this driver cannot
take algorithms out of what sshd offers -- it does not offer ``harden_ssh_server``
-- and says, as data, where a person sets the lists instead.
A field left empty is OpenSSH's defaults. In an HA pair the configuration sync
carries the section to the backup when its "OpenSSH" item is ticked (sync id
``ssh``, :data:`napalm_opnsense.ha.SYNC_ITEM_SERVICES`).
"""
from __future__ import annotations
class OPNsenseSshSettingsMixin:
"""The page and fields that set the SSH server's algorithm lists, as the web
interface names them."""
#: The menu path to the page, ending in the section that holds the lists.
SSH_SETTINGS_MENU: tuple[str, ...] = ("System", "Settings", "Administration", "Secure Shell")
#: Each list's field, by its algorithm class (napalm-device-types'
#: ``SSH_ALGORITHM_CLASSES``).
SSH_SETTINGS_FIELDS: dict[str, str] = {
"kex": "Key exchange algorithms",
"cipher": "Ciphers",
"mac": "MACs",
"hostkey": "Host key algorithms",
}
+115
View File
@@ -0,0 +1,115 @@
"""The firewall's time servers and time zone (napalm-device-types, NetOrk/netork#2363).
OPNsense keeps both in config.xml: ``<system><timeservers>``, space-separated in the
order of *Services → Network Time → General* (``services_ntpd.php``), and
``<system><timezone>``, an IANA name set on *System → Settings → General*
(``system_general.php``). An empty or missing zone runs as ``Etc/UTC``
(``system_timezone_configure``); without time servers OPNsense does not run ntpd at
all (``ntpd_enabled``). Both pages are legacy PHP: no API controller reads or writes
either value, up to 26.7 and on ``master`` (the initial setup wizard writes the zone,
but only together with the hostname, the interfaces and the root password).
So the driver reads both from config.xml -- the download ``get_config`` uses -- and
asks ntpd over ``/api/ntpd/service/status`` (``ntpq -pnw`` as rows) whether the clock
follows a system peer. It writes neither: ``time_sync_writes`` is empty,
``configure_time_sync`` is None, and :data:`TIME_SERVERS_MENU` and
:data:`TIME_ZONE_MENU` say, as data, where a person sets them. Nothing here touches
which interfaces ntpd serves time on. In an HA pair the configuration sync carries
the servers to the backup when its "Network Time" item (``ntpd``) is ticked; the
zone is not synchronised.
"""
from __future__ import annotations
# config.xml as the firewall's own API hands it over; ElementTree resolves no external
# entities, and expat limits entity expansion since 2.4.1.
import xml.etree.ElementTree as ET # nosec B405
from typing import TYPE_CHECKING, Any, ClassVar
from napalm_device_types import TimeSyncDict, TimeSyncMixin
#: config.xml itself (the newest entry of the configuration history).
CONFIG_PATH = "/api/core/backup/download/this"
#: ntpd's associations, one row per line of ``ntpq -pnw``.
STATUS_PATH = "/api/ntpd/service/status"
#: The zone OPNsense runs in when config.xml names none.
DEFAULT_ZONE = "Etc/UTC"
#: How ``ntpq`` marks the system peer, the source the clock follows.
_SYSTEM_PEER = "*"
def time_settings(config_xml: str) -> tuple[list[str], str]:
"""``(servers, zone)`` as *config_xml* names them; no zone is :data:`DEFAULT_ZONE`.
:raises xml.etree.ElementTree.ParseError: for a text that is no XML.
"""
# The firewall's own config.xml: see the import.
system = ET.fromstring(config_xml).find("system") # nosec B314
if system is None:
return [], DEFAULT_ZONE
servers = (system.findtext("timeservers") or "").split()
zone = (system.findtext("timezone") or "").strip()
return servers, zone or DEFAULT_ZONE
def follows_a_peer(status: Any) -> bool | None:
"""Whether ntpd's *status* answer has a system peer; None for another shape."""
rows = status.get("rows") if isinstance(status, dict) else None
if not isinstance(rows, list):
return None
return any(isinstance(row, dict) and row.get("status") == _SYSTEM_PEER for row in rows)
class OPNsenseTimeSyncMixin(TimeSyncMixin):
"""Read the time servers and the zone; writing them is left to a person."""
#: Neither value has an API that writes it.
time_sync_writes: ClassVar[frozenset[str]] = frozenset()
configure_time_sync = None # type: ignore[assignment]
#: The menu path to the page that lists the time servers ("Time servers").
TIME_SERVERS_MENU: tuple[str, ...] = ("Services", "Network Time", "General")
#: The menu path to the page that sets the zone ("Time zone").
TIME_ZONE_MENU: tuple[str, ...] = ("System", "Settings", "General")
if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers
def _get(self, path: str) -> dict[str, Any]: ...
def _get_text(self, path: str) -> str: ...
def _time_settings(self) -> tuple[list[str], str]:
return time_settings(self._get_text(CONFIG_PATH))
def get_time_sync(self) -> TimeSyncDict:
"""The servers and zone of config.xml, and whether ntpd follows one of them.
``synchronized`` is False without servers (ntpd does not run then) and None
when ntpd's status cannot be read.
:raises Exception: when config.xml cannot be read, e.g. by a key without
the backup privilege.
"""
servers, zone = self._time_settings()
synchronized: bool | None = False
if servers:
try:
synchronized = follows_a_peer(self._get(STATUS_PATH))
except Exception: # the status is an extra; the settings were read
synchronized = None
return {
"ntp_servers": servers,
"timezone": zone,
"synchronized": synchronized,
"daemon": "ntpd",
}
def get_ntp_servers(self) -> dict[str, dict[str, Any]]:
"""The configured servers, in their order, each with an empty dict (NAPALM's shape).
The same list as ``get_time_sync()["ntp_servers"]``.
:raises Exception: when config.xml cannot be read.
"""
servers, _zone = self._time_settings()
return {server: {} for server in servers}
+5
View File
@@ -31,6 +31,11 @@ _CARP_STATES: dict[str, tuple[bool, bool]] = {
}
def carp_master(entry: dict[str, Any]) -> bool:
"""Whether this node is MASTER for an interface address bound to a CARP VHID."""
return str(entry.get("status") or "").strip().upper() == "MASTER"
def _address(text: str) -> tuple[str, int | None] | None:
"""``"10.0.0.1/24"`` -> ``("10.0.0.1", 24)``; None for what is no address."""
host, slash, prefix = text.partition("/")
+73
View File
@@ -0,0 +1,73 @@
"""WireGuard peers as VPN tunnels. Pure: no I/O.
``/api/wireguard/service/show`` lists every WireGuard interface and peer::
{"total": N, "rows": [
{"if": "wg0", "type": "interface", ...},
{"if": "wg0", "type": "peer", "public-key": "...",
"endpoint": "1.2.3.4:51820", "transfer-rx": N, "transfer-tx": N,
"name": "office", "peer-status": "online",
"latest-handshake-age": 45, "ifname": "office"}, ...
]}
**The key is the peer, not its place.** It used to be a running counter, so a
peer added ahead of another renumbered it, and whatever a consumer keeps per
key (netOrk's site link, its tunnel check) moved to a different peer (#32).
Now it is the interface and the start of the public key, as napalm-linux does
it, with the base64 made URL-safe because the key is used as a path segment.
Two peers sharing the prefix get the whole key; a row without a public key
keeps its position.
"""
from __future__ import annotations
from typing import Any
#: How much of a public key names a peer, the same length as napalm-linux uses.
_KEY_PREFIX = 8
def _key(row: dict[str, Any], position: int, taken: dict[str, Any]) -> str:
public_key = (row.get("public-key") or "").strip()
if not public_key:
return f"wireguard-{position}"
safe = public_key.rstrip("=").replace("+", "-").replace("/", "_")
key = f"wireguard-{row.get('if') or 'wg'}-{safe[:_KEY_PREFIX]}"
if key in taken:
key = f"wireguard-{row.get('if') or 'wg'}-{safe}"
return key
def _remote_ip(row: dict[str, Any]) -> str:
endpoint = (row.get("endpoint") or "").strip()
if not endpoint or endpoint == "(none)":
return ""
return endpoint.rsplit(":", 1)[0].strip("[]")
def _tunnel(row: dict[str, Any], position: int) -> dict[str, Any]:
handshake_age = row.get("latest-handshake-age")
return {
"type": "WireGuard",
"local_endpoint": "",
"remote_endpoint": _remote_ip(row),
"is_up": row.get("peer-status") == "online",
"uptime": int(handshake_age) if handshake_age else 0,
"bytes_in": int(row.get("transfer-rx") or 0),
"bytes_out": int(row.get("transfer-tx") or 0),
"description": (
(row.get("name") or "").strip()
or (row.get("ifname") or "").strip()
or f"wg-peer-{position}"
),
}
def wireguard_tunnels(show: Any) -> dict[str, dict[str, Any]]:
"""One ``VPNTunnelDict`` per peer in ``/api/wireguard/service/show``, by tunnel key."""
rows = show.get("rows", []) if isinstance(show, dict) else []
tunnels: dict[str, dict[str, Any]] = {}
peers = [row for row in rows if isinstance(row, dict) and row.get("type") == "peer"]
for position, row in enumerate(peers, start=1):
tunnels[_key(row, position, tunnels)] = _tunnel(row, position)
return tunnels
+6 -8
View File
@@ -4,19 +4,17 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-opnsense"
version = "0.5.0"
version = "0.6.0"
description = "NAPALM driver for OPNsense (read-only via REST API)."
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
requires-python = ">=3.12"
authors = [
{ name = "Christian Manivong" },
]
classifiers = [
"Topic :: Utilities",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Operating System :: POSIX :: Linux",
@@ -24,8 +22,8 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"napalm>=4.0.0",
"napalm-device-types>=4.21.1",
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.50.0",
"requests>=2.28.0",
]
@@ -54,7 +52,7 @@ napalm_opnsense = ["py.typed"]
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
@@ -64,7 +62,7 @@ select = ["E", "F", "I", "UP", "B"]
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.10"
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
+6 -8
View File
@@ -6,12 +6,11 @@
"napalm_opnsense/listening.py::_service_of": 12,
"napalm_opnsense/listening.py::_socket": 19,
"napalm_opnsense/opnsense.py::OPNsenseDriver._allow_snmp_sources": 11,
"napalm_opnsense/opnsense.py::OPNsenseDriver._get_unbound_host_overrides": 17,
"napalm_opnsense/opnsense.py::OPNsenseDriver._get_unbound_host_overrides": 16,
"napalm_opnsense/opnsense.py::OPNsenseDriver._kea_read_list": 11,
"napalm_opnsense/opnsense.py::OPNsenseDriver.apply_dhcp_subnet": 21,
"napalm_opnsense/opnsense.py::OPNsenseDriver.apply_firewall_rule": 11,
"napalm_opnsense/opnsense.py::OPNsenseDriver.create_dhcp_reservation": 16,
"napalm_opnsense/opnsense.py::OPNsenseDriver.delete_dhcp_reservation_and_lease": 14,
"napalm_opnsense/opnsense.py::OPNsenseDriver.delete_dhcp_reservation_and_lease": 11,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_bgp_neighbors": 16,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases": 15,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases._parse_kea": 14,
@@ -24,17 +23,16 @@
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_lldp_neighbors_detail": 12,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_networks": 25,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_route_to": 23,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_vpn_tunnels": 60,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_vpn_tunnels": 47,
"napalm_opnsense/opnsense.py::OPNsenseDriver.load_merge_candidate": 13,
"napalm_opnsense/opnsense.py::OPNsenseDriver.sync_dns_zone": 20,
"napalm_opnsense/port_forwards.py::_forwards_of": 12,
"napalm_opnsense/virtual_ips.py::carp_addresses": 14
},
"function_lines": {
"napalm_opnsense/opnsense.py::OPNsenseDriver._get_unbound_host_overrides": 51,
"napalm_opnsense/opnsense.py::OPNsenseDriver._regenerate_web_cert": 51,
"napalm_opnsense/opnsense.py::OPNsenseDriver.apply_dhcp_subnet": 60,
"napalm_opnsense/opnsense.py::OPNsenseDriver.create_dhcp_reservation": 85,
"napalm_opnsense/opnsense.py::OPNsenseDriver.create_dhcp_reservation": 64,
"napalm_opnsense/opnsense.py::OPNsenseDriver.delete_dhcp_reservation_and_lease": 79,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_bgp_neighbors": 86,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases": 106,
@@ -43,7 +41,7 @@
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_interfaces_ip": 68,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_networks": 85,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_route_to": 85,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_vpn_tunnels": 189,
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_vpn_tunnels": 145,
"napalm_opnsense/opnsense.py::OPNsenseDriver.load_merge_candidate": 56,
"napalm_opnsense/opnsense.py::OPNsenseDriver.sync_dns_zone": 112
},
@@ -57,7 +55,7 @@
"napalm_opnsense.resolver_mixin"
],
"python_file_lines": {
"napalm_opnsense/opnsense.py": 3125
"napalm_opnsense/opnsense.py": 3019
},
"untyped_public": [
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config"
+164
View File
@@ -0,0 +1,164 @@
<?xml version="1.0"?>
<opnsense>
<trigger_initial_wizard/>
<theme>opnsense</theme>
<system>
<optimization>normal</optimization>
<hostname>OPNsense</hostname>
<domain>internal</domain>
<dnsallowoverride>1</dnsallowoverride>
<dnsallowoverride_exclude/>
<group>
<name>admins</name>
<description>System Administrators</description>
<scope>system</scope>
<gid>1999</gid>
<member>0</member>
<priv>page-all</priv>
</group>
<timezone>Etc/UTC</timezone>
<timeservers>0.opnsense.pool.ntp.org 1.opnsense.pool.ntp.org 2.opnsense.pool.ntp.org 3.opnsense.pool.ntp.org</timeservers>
<webgui>
<protocol>https</protocol>
<noroot>1</noroot>
</webgui>
<disablenatreflection>yes</disablenatreflection>
<usevirtualterminal>1</usevirtualterminal>
<disableconsolemenu/>
<ipv6allow>1</ipv6allow>
<powerd_ac_mode>hadp</powerd_ac_mode>
<powerd_battery_mode>hadp</powerd_battery_mode>
<powerd_normal_mode>hadp</powerd_normal_mode>
<bogons>
<interval>monthly</interval>
</bogons>
<pf_share_forward>1</pf_share_forward>
<lb_use_sticky>1</lb_use_sticky>
<ssh>
<group>admins</group>
</ssh>
</system>
<interfaces>
<wan>
<enable>1</enable>
<if>mismatch1</if>
<descr/>
<spoofmac/>
<ipaddr>dhcp</ipaddr>
<ipaddrv6>dhcp6</ipaddrv6>
<blockpriv>1</blockpriv>
<blockbogons>1</blockbogons>
<dhcphostname/>
<dhcp6-ia-pd-len>0</dhcp6-ia-pd-len>
</wan>
<lan>
<enable>1</enable>
<if>mismatch0</if>
<descr/>
<spoofmac/>
<ipaddr>192.168.1.1</ipaddr>
<subnet>24</subnet>
<ipaddrv6>idassoc6</ipaddrv6>
<track6-interface>wan</track6-interface>
<track6-prefix-id>0</track6-prefix-id>
</lan>
</interfaces>
<dnsmasq>
<enable>1</enable>
<port>53053</port>
<interface>lan</interface>
<dhcp>
<enable_ra>1</enable_ra>
</dhcp>
<dhcp_ranges>
<interface>lan</interface>
<start_addr>192.168.1.100</start_addr>
<end_addr>192.168.1.199</end_addr>
</dhcp_ranges>
<dhcp_ranges>
<interface>lan</interface>
<start_addr>::1000</start_addr>
<end_addr>::2000</end_addr>
<constructor>lan</constructor>
<ra_mode>slaac</ra_mode>
</dhcp_ranges>
</dnsmasq>
<unbound>
<enable>1</enable>
</unbound>
<nat>
<outbound>
<mode>automatic</mode>
</outbound>
</nat>
<filter>
</filter>
<rrd>
<enable/>
</rrd>
<ntpd>
<prefer>0.opnsense.pool.ntp.org</prefer>
<ispool>0.opnsense.pool.ntp.org 1.opnsense.pool.ntp.org 2.opnsense.pool.ntp.org 3.opnsense.pool.ntp.org</ispool>
</ntpd>
<OPNsense>
<Firewall>
<Filter>
<rules>
<rule>
<enabled>1</enabled>
<statetype>keep</statetype>
<state-policy/>
<sequence>1</sequence>
<action>pass</action>
<quick>1</quick>
<interfacenot>0</interfacenot>
<interface>lan</interface>
<direction>in</direction>
<ipprotocol>inet</ipprotocol>
<protocol>any</protocol>
<source_net>lan</source_net>
<source_not>0</source_not>
<source_port/>
<destination_net>any</destination_net>
<destination_not>0</destination_not>
<disablereplyto>0</disablereplyto>
<log>0</log>
<allowopts>0</allowopts>
<nosync>0</nosync>
<nopfsync>0</nopfsync>
<statetimeout/>
<tcpflags_any>0</tcpflags_any>
<description>Default allow LAN to any rule</description>
</rule>
<rule>
<enabled>1</enabled>
<statetype>keep</statetype>
<state-policy/>
<sequence>11</sequence>
<action>pass</action>
<quick>1</quick>
<interfacenot>0</interfacenot>
<interface>lan</interface>
<direction>in</direction>
<ipprotocol>inet6</ipprotocol>
<protocol>any</protocol>
<source_net>lan</source_net>
<source_not>0</source_not>
<destination_net>any</destination_net>
<destination_not>0</destination_not>
<disablereplyto>0</disablereplyto>
<log>0</log>
<allowopts>0</allowopts>
<nosync>0</nosync>
<nopfsync>0</nopfsync>
<tcpflags_any>0</tcpflags_any>
<description>Default allow LAN IPv6 to any rule</description>
</rule>
</rules>
<snatrules/>
<npt/>
<onetoone/>
</Filter>
</Firewall>
</OPNsense>
</opnsense>
@@ -0,0 +1,36 @@
{
"items": [
{
"time": "1794603885.12",
"time_iso": "2026-11-13T22:04:45+01:00",
"description": "/api/firewall/filter/apply made changes",
"username": "apiuser@192.0.2.10",
"filesize": 58213,
"id": "config-1794603885.1239.xml"
},
{
"time": "1794603482.87",
"time_iso": "2026-11-13T21:58:02+01:00",
"description": "/system_general.php made changes",
"username": "root@192.0.2.20",
"filesize": 58190,
"id": "config-1794603482.8721.xml"
},
{
"time": "1794475810.05",
"time_iso": "2026-11-12T10:30:10+01:00",
"description": "/api/core/backup/revert_backup/config-1793516400.0012.xml made changes",
"username": "apiuser@192.0.2.10",
"filesize": 57944,
"id": "config-1794475810.0548_123456789.xml"
},
{
"time": "1793516400.00",
"time_iso": "2026-11-01T08:00:00+01:00",
"description": "",
"username": "",
"filesize": 57944,
"id": "config-1793516400.0012.xml"
}
]
}
+198
View File
@@ -0,0 +1,198 @@
{
"job": {
"jobs": {
"job": {
"0b6e3c52-6a1e-4c7a-9a0e-2f0a1d6c3b11": {
"origin": "cron",
"enabled": "1",
"minutes": "0",
"hours": "3",
"days": "*",
"months": "*",
"weekdays": "1-5",
"who": "root",
"command": {
"filter refresh_aliases": {
"value": "Update and reload firewall aliases",
"selected": 0
},
"firmware auto-update": {
"value": "Automatic firmware update",
"selected": 0
},
"ids update": {
"value": "Update and reload intrusion detection rules",
"selected": 0
},
"system ha_reconfigure_backup": {
"value": "HA update and reconfigure backup",
"selected": 0
},
"system remote backup": {
"value": "Remote backup",
"selected": 1
},
"unbound dnsbl": {
"value": "Update Unbound DNSBLs",
"selected": 0
}
},
"parameters": "",
"description": "Nightly configuration backup"
},
"1f2d8e04-93b7-4f4e-8c55-7d1e0c9a2b22": {
"origin": "IDS",
"enabled": "0",
"minutes": "30",
"hours": "1",
"days": "*",
"months": "*",
"weekdays": "*",
"who": "root",
"command": {
"filter refresh_aliases": {
"value": "Update and reload firewall aliases",
"selected": 0
},
"firmware auto-update": {
"value": "Automatic firmware update",
"selected": 0
},
"ids update": {
"value": "Update and reload intrusion detection rules",
"selected": 1
},
"system ha_reconfigure_backup": {
"value": "HA update and reconfigure backup",
"selected": 0
},
"system remote backup": {
"value": "Remote backup",
"selected": 0
},
"unbound dnsbl": {
"value": "Update Unbound DNSBLs",
"selected": 0
}
},
"parameters": "",
"description": "ids rule updates"
},
"2a7c9b16-4d3e-4b8f-a1c2-5e6f7a8b9c33": {
"origin": "cron",
"enabled": "1",
"minutes": "*/15",
"hours": "*",
"days": "*",
"months": "*",
"weekdays": "*",
"who": "root",
"command": {
"filter refresh_aliases": {
"value": "Update and reload firewall aliases",
"selected": 0
},
"firmware auto-update": {
"value": "Automatic firmware update",
"selected": 0
},
"ids update": {
"value": "Update and reload intrusion detection rules",
"selected": 0
},
"system ha_reconfigure_backup": {
"value": "HA update and reconfigure backup",
"selected": 0
},
"system remote backup": {
"value": "Remote backup",
"selected": 0
},
"unbound dnsbl": {
"value": "Update Unbound DNSBLs",
"selected": 1
}
},
"parameters": "",
"description": "napalm-scheduled-job: dnsbl-refresh Refresh the DNS blocklists"
},
"3c8d0e27-5f4a-4c9b-b2d3-6f7a8b9c0d44": {
"origin": "cron",
"enabled": "1",
"minutes": "0",
"hours": "4",
"days": "1",
"months": "*",
"weekdays": "*",
"who": "root",
"command": {
"filter refresh_aliases": {
"value": "Update and reload firewall aliases",
"selected": 1
},
"firmware auto-update": {
"value": "Automatic firmware update",
"selected": 0
},
"ids update": {
"value": "Update and reload intrusion detection rules",
"selected": 0
},
"system ha_reconfigure_backup": {
"value": "HA update and reconfigure backup",
"selected": 0
},
"system remote backup": {
"value": "Remote backup",
"selected": 0
},
"unbound dnsbl": {
"value": "Update Unbound DNSBLs",
"selected": 0
}
},
"parameters": "--quiet\n--all\n",
"description": "Monthly alias refresh"
},
"4d9e1f38-6a5b-4dac-83e4-7a8b9c0d1e55": {
"origin": "cron",
"enabled": "0",
"minutes": "0",
"hours": "5",
"days": "*",
"months": "*",
"weekdays": "0",
"who": "root",
"command": {
"filter refresh_aliases": {
"value": "Update and reload firewall aliases",
"selected": 0
},
"firmware auto-update": {
"value": "Automatic firmware update",
"selected": 1
},
"ids update": {
"value": "Update and reload intrusion detection rules",
"selected": 0
},
"system ha_reconfigure_backup": {
"value": "HA update and reconfigure backup",
"selected": 0
},
"system remote backup": {
"value": "Remote backup",
"selected": 0
},
"unbound dnsbl": {
"value": "Update Unbound DNSBLs",
"selected": 0
}
},
"parameters": "",
"description": "napalm-scheduled-job: Not_A_Name written by hand"
}
}
}
}
}
@@ -0,0 +1,40 @@
{
"job": {
"origin": "cron",
"enabled": "1",
"minutes": "0",
"hours": "0",
"days": "*",
"months": "*",
"weekdays": "*",
"who": "root",
"command": {
"filter refresh_aliases": {
"value": "Update and reload firewall aliases",
"selected": 0
},
"firmware auto-update": {
"value": "Automatic firmware update",
"selected": 0
},
"ids update": {
"value": "Update and reload intrusion detection rules",
"selected": 0
},
"system ha_reconfigure_backup": {
"value": "HA update and reconfigure backup",
"selected": 0
},
"system remote backup": {
"value": "Remote backup",
"selected": 0
},
"unbound dnsbl": {
"value": "Update Unbound DNSBLs",
"selected": 0
}
},
"parameters": "",
"description": ""
}
}
@@ -0,0 +1,12 @@
{
"total": 5,
"rowCount": 5,
"current": 1,
"rows": [
{"status": "__pool", "server": "0.opnsense.pool.ntp.org", "refid": ".POOL.", "stratum": "16", "type": "p", "when": "-", "poll": "64", "reach": "0", "delay": "0.000", "offset": "+0.000", "jitter": "0.000"},
{"status": "__pool", "server": "1.opnsense.pool.ntp.org", "refid": ".POOL.", "stratum": "16", "type": "p", "when": "-", "poll": "64", "reach": "0", "delay": "0.000", "offset": "+0.000", "jitter": "0.000"},
{"status": "*", "server": "162.159.200.1", "refid": "10.217.8.4", "stratum": "3", "type": "u", "when": "33", "poll": "64", "reach": "377", "delay": "10.123", "offset": "-0.456", "jitter": "0.789"},
{"status": "+", "server": "194.59.205.229", "refid": "192.53.103.103", "stratum": "2", "type": "u", "when": "12", "poll": "64", "reach": "377", "delay": "12.801", "offset": "+0.214", "jitter": "0.333"},
{"status": "-", "server": "85.214.38.116", "refid": "131.188.3.222", "stratum": "2", "type": "u", "when": "41", "poll": "64", "reach": "377", "delay": "14.002", "offset": "+1.870", "jitter": "0.902"}
]
}
+415
View File
@@ -0,0 +1,415 @@
"""The firewall's own configuration history: list it, read a revision, revert to one.
NetOrk/netork#2511: OPNsense has no API that takes an uploaded config.xml, so an
application restores a configuration by finding the revision in the firewall's own
history whose content it wants and reverting to that one.
``core_backup_backups_this.json`` has the shape ``/api/core/backup/backups/this`` answers
with on 24.7 up to 26.7 and ``master`` (``OPNsense\\Core\\Api\\BackupController``):
newest first, ``time`` the revision's unix time with two decimals, ``time_iso`` the same
in the firewall's own zone (here +01:00), ``id`` the file name in ``/conf/backup``. The
values are made up; the oldest is a revision without description and user, as the
first configuration of a new install is.
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
from xml.etree.ElementTree import ParseError
import pytest
import requests
from napalm_device_types import ConfigRevertFailed, ConfigRevisionsMixin, UnknownConfigRevision
from napalm_opnsense.opnsense import OPNsenseDriver
FIXTURES = Path(__file__).parent / "fixtures"
HISTORY = json.loads((FIXTURES / "core_backup_backups_this.json").read_text())
CONFIG_XML = (FIXTURES / "config_xml_sample.xml").read_text()
HISTORY_PATH = "/api/core/backup/backups/this"
NEWEST = "config-1794603885.1239.xml"
OLDEST = "config-1793516400.0012.xml"
WITH_SUFFIX = "config-1794475810.0548_123456789.xml"
#: The id of the revision a revert saves, as the fake firewall names it.
REVERTED = "config-1794700000.0001.xml"
def _stamped(config: str, user: str, time: str) -> str:
"""*config* with the <revision> block every save writes into config.xml."""
block = (
f" <revision>\n <username>{user}</username>\n <time>{time}</time>\n"
" <description>/api/core/backup/revert_backup made changes</description>\n"
" </revision>\n"
)
return config.replace("</opnsense>", block + "</opnsense>")
#: The oldest revision is the sample; every later one names the host otherwise.
FILES = {
OLDEST: _stamped(CONFIG_XML, "root@192.0.2.20", "1793516400.00"),
WITH_SUFFIX: _stamped(CONFIG_XML, "apiuser@192.0.2.10", "1794475810.05"),
"config-1794603482.8721.xml": _stamped(
CONFIG_XML.replace("<hostname>OPNsense</hostname>", "<hostname>gw</hostname>"),
"root@192.0.2.20",
"1794603482.87",
),
NEWEST: _stamped(
CONFIG_XML.replace("<hostname>OPNsense</hostname>", "<hostname>gw1</hostname>"),
"apiuser@192.0.2.10",
"1794603885.12",
),
}
class Firewall:
"""Answers as the firewall's backup API would; every request is recorded.
A revert it takes saves the revision as a new newest one, restamped; one it does
not take (``takes=False``) still answers "reverted", as OPNsense does when it falls
back to the previous file.
"""
def __init__(self, history=HISTORY, files=None, revert_answer=None, takes=True):
self.history = copy.deepcopy(history)
self.files = dict(FILES if files is None else files)
self.revert_answer = revert_answer or {"status": "reverted"}
self.takes = takes
self.requests: list[tuple[str, str]] = []
def get(self, url, timeout=None):
path = url.removeprefix("https://fw")
self.requests.append(("GET", path))
response = MagicMock()
response.raise_for_status.return_value = None
if path == HISTORY_PATH:
if isinstance(self.history, Exception):
response.raise_for_status.side_effect = self.history
response.json.return_value = self.history
return response
prefix = "/api/core/backup/download/this/"
if path.startswith(prefix):
# BackupController::downloadAction sends nothing for a name it has no file for.
response.text = self.files.get(path.removeprefix(prefix), "")
response.json.side_effect = json.JSONDecodeError("Expecting value", "<", 0)
return response
raise AssertionError(f"unexpected GET {path}")
def post(self, url, json=None, timeout=None):
path = url.removeprefix("https://fw")
self.requests.append(("POST", path))
response = MagicMock()
response.raise_for_status.return_value = None
if isinstance(self.revert_answer, Exception):
response.raise_for_status.side_effect = self.revert_answer
elif self.revert_answer.get("status") == "reverted" and self.takes:
self._save(path.rsplit("/", 1)[1])
response.json.return_value = self.revert_answer
return response
def _save(self, revision_id):
body = self.files[revision_id].split(" <revision>")[0] + "</opnsense>\n"
self.files[REVERTED] = _stamped(body, "apiuser@192.0.2.10", "1794700000.00")
item = {"time": "1794700000.00", "description": "", "username": "", "id": REVERTED}
self.history["items"].insert(0, item)
@property
def posts(self) -> list[str]:
return [path for method, path in self.requests if method == "POST"]
@pytest.fixture
def driver():
with patch("napalm_opnsense.opnsense.requests.Session"):
drv = OPNsenseDriver(
hostname="fw", username="k", password="s", optional_args={"verify": False}
)
drv.session = MagicMock()
yield drv
def _on(driver, firewall: Firewall) -> Firewall:
driver.session.get.side_effect = firewall.get
driver.session.post.side_effect = firewall.post
return firewall
class TestGetConfigRevisions:
def test_every_revision_newest_first(self, driver):
_on(driver, Firewall())
revisions = driver.get_config_revisions()
assert [r["id"] for r in revisions] == [
NEWEST,
"config-1794603482.8721.xml",
WITH_SUFFIX,
OLDEST,
]
def test_a_revision_as_the_firewall_describes_it(self, driver):
_on(driver, Firewall())
assert driver.get_config_revisions()[0] == {
"id": NEWEST,
"time": "2026-11-13T21:04:45+00:00",
"description": "/api/firewall/filter/apply made changes",
"user": "apiuser@192.0.2.10",
"size": 58213,
}
def test_the_time_is_utc_whatever_zone_the_firewall_runs_in(self, driver):
# time_iso is in the firewall's zone (+01:00 here); time is unix seconds.
_on(driver, Firewall())
times = [r["time"] for r in driver.get_config_revisions()]
assert times == [
"2026-11-13T21:04:45+00:00",
"2026-11-13T20:58:02+00:00",
"2026-11-12T09:30:10+00:00",
"2026-11-01T07:00:00+00:00",
]
def test_no_description_and_no_user_are_none(self, driver):
_on(driver, Firewall())
oldest = driver.get_config_revisions()[-1]
assert (oldest["description"], oldest["user"]) == (None, None)
def test_newest_first_even_when_the_answer_is_not_sorted(self, driver):
items = list(reversed(HISTORY["items"]))
_on(driver, Firewall(history={"items": items}))
assert driver.get_config_revisions()[0]["id"] == NEWEST
def test_without_a_time_the_file_name_tells_it(self, driver):
item = {"id": OLDEST, "description": "", "username": "", "filesize": 1}
_on(driver, Firewall(history={"items": [item]}))
assert driver.get_config_revisions()[0]["time"] == "2026-11-01T07:00:00+00:00"
def test_a_time_and_size_of_another_shape_are_none(self, driver):
item = {"id": "config-1.xml", "time": "soon", "filesize": "big", "description": 7}
_on(driver, Firewall(history={"items": [item, "noise"]}))
assert driver.get_config_revisions() == [
{
"id": "config-1.xml",
"time": "1970-01-01T00:00:01+00:00",
"description": None,
"user": None,
"size": None,
}
]
def test_an_entry_without_a_usable_id_is_left_out(self, driver):
# Nothing could read or revert it: the id goes into the request path.
items = [
{"id": "../config.xml", "time": "1"},
{"id": "config-1/../../x.xml", "time": "1"},
{"time": "1"},
HISTORY["items"][0],
]
_on(driver, Firewall(history={"items": items}))
assert [r["id"] for r in driver.get_config_revisions()] == [NEWEST]
def test_no_history_is_an_empty_list(self, driver):
_on(driver, Firewall(history={"items": []}))
assert driver.get_config_revisions() == []
def test_a_failed_read_raises(self, driver):
_on(driver, Firewall(history=requests.HTTPError("403 Forbidden")))
with pytest.raises(requests.HTTPError, match="403"):
driver.get_config_revisions()
@pytest.mark.parametrize("answer", [[], {"items": "x"}, {}], ids=["list", "items", "empty"])
def test_an_answer_of_another_shape_raises(self, driver, answer):
# "No history" would be a reading; this is none.
_on(driver, Firewall(history=answer))
with pytest.raises(ValueError, match="history"):
driver.get_config_revisions()
def test_a_reading_only_reads(self, driver):
firewall = _on(driver, Firewall())
driver.get_config_revisions()
assert firewall.requests == [("GET", HISTORY_PATH)]
class TestGetConfigRevision:
def test_the_revisions_config_xml(self, driver):
firewall = _on(driver, Firewall())
assert driver.get_config_revision(OLDEST) == FILES[OLDEST]
assert firewall.requests == [("GET", f"/api/core/backup/download/this/{OLDEST}")]
def test_a_revision_the_firewall_has_no_file_for_raises(self, driver):
# Rotated out of the history: the download answers with nothing.
_on(driver, Firewall(files={}))
with pytest.raises(UnknownConfigRevision, match=OLDEST):
driver.get_config_revision(OLDEST)
@pytest.mark.parametrize(
"revision_id",
["", "config.xml", "../config.xml", "config-1/../../x.xml", "config-1.xml?x=1", None],
)
def test_an_id_that_names_no_revision_is_refused_before_any_request(self, driver, revision_id):
firewall = _on(driver, Firewall())
with pytest.raises(UnknownConfigRevision):
driver.get_config_revision(revision_id)
assert firewall.requests == []
def test_a_failed_read_raises(self, driver):
resp = MagicMock()
resp.raise_for_status.side_effect = requests.HTTPError("403 Forbidden")
driver.session.get.return_value = resp
with pytest.raises(requests.HTTPError, match="403"):
driver.get_config_revision(OLDEST)
class TestRevertConfigRevision:
def test_reverts_through_the_backup_api_and_checks_the_result(self, driver):
firewall = _on(driver, Firewall())
now = driver.revert_config_revision(OLDEST)
assert now["id"] == REVERTED
assert firewall.requests == [
("GET", HISTORY_PATH),
("GET", f"/api/core/backup/download/this/{OLDEST}"),
("POST", f"/api/core/backup/revert_backup/{OLDEST}"),
("GET", HISTORY_PATH),
("GET", f"/api/core/backup/download/this/{REVERTED}"),
]
def test_an_id_with_the_suffix_of_a_fast_save(self, driver):
firewall = _on(driver, Firewall())
driver.revert_config_revision(WITH_SUFFIX)
assert firewall.posts == [f"/api/core/backup/revert_backup/{WITH_SUFFIX}"]
def test_a_revert_the_firewall_did_not_take_fails(self, driver):
# restoreBackup() falls back to the previous file and the answer is "reverted".
_on(driver, Firewall(takes=False))
with pytest.raises(ConfigRevertFailed, match=OLDEST):
driver.revert_config_revision(OLDEST)
def test_a_revision_not_in_the_history_is_refused(self, driver):
firewall = _on(driver, Firewall())
with pytest.raises(UnknownConfigRevision, match="config-1000000000.5.xml"):
driver.revert_config_revision("config-1000000000.5.xml")
assert firewall.posts == []
@pytest.mark.parametrize("revision_id", ["", "../config.xml", "config-1.xml/x", None])
def test_an_id_that_names_no_revision_never_reaches_a_request_path(self, driver, revision_id):
firewall = _on(driver, Firewall())
with pytest.raises(UnknownConfigRevision):
driver.revert_config_revision(revision_id)
assert firewall.requests == [("GET", HISTORY_PATH)]
def test_a_history_that_cannot_be_read_reverts_nothing(self, driver):
firewall = _on(driver, Firewall(history=requests.HTTPError("403 Forbidden")))
with pytest.raises(requests.HTTPError):
driver.revert_config_revision(OLDEST)
assert firewall.posts == []
def test_a_revision_gone_by_the_time_of_the_revert_is_unknown(self, driver):
_on(driver, Firewall(revert_answer={"status": "not_found"}))
with pytest.raises(UnknownConfigRevision, match=OLDEST):
driver.revert_config_revision(OLDEST)
def test_a_key_that_may_not_write_is_refused_with_the_firewalls_reason(self, driver):
# user-config-readonly: throwReadOnly() answers with an errorMessage.
reason = "User apiuser denied for write access (user-config-readonly set)"
_on(driver, Firewall(revert_answer={"errorMessage": reason, "errorTitle": "Error"}))
with pytest.raises(ConfigRevertFailed, match="user-config-readonly"):
driver.revert_config_revision(OLDEST)
def test_any_other_answer_is_a_failed_revert(self, driver):
_on(driver, Firewall(revert_answer={"status": "failed"}))
with pytest.raises(ConfigRevertFailed, match="failed"):
driver.revert_config_revision(OLDEST)
def test_an_http_error_raises(self, driver):
_on(driver, Firewall(revert_answer=requests.HTTPError("500 Server Error")))
with pytest.raises(requests.HTTPError, match="500"):
driver.revert_config_revision(OLDEST)
class TestConfigRevisionContent:
def test_the_revision_block_does_not_count(self, driver):
# Same configuration, saved by someone else at another time.
assert driver.config_revision_content(FILES[OLDEST]) == driver.config_revision_content(
FILES[WITH_SUFFIX]
)
def test_a_changed_setting_counts(self, driver):
assert driver.config_revision_content(FILES[OLDEST]) != driver.config_revision_content(
FILES[NEWEST]
)
def test_a_configuration_without_a_revision_block(self, driver):
stamped = driver.config_revision_content(FILES[OLDEST])
assert driver.config_revision_content(CONFIG_XML) == stamped
def test_a_revision_element_deeper_down_counts(self, driver):
# Only the root's <revision> is the save's stamp.
deeper = CONFIG_XML.replace("<theme>", "<theme><revision>7</revision>", 1)
assert driver.config_revision_content(deeper) != driver.config_revision_content(CONFIG_XML)
def test_how_the_xml_is_written_does_not_count(self, driver):
# Attribute order, quotes and empty elements are no difference of the configuration.
a = '<?xml version="1.0"?>\n<opnsense><x a="1" b="2"></x></opnsense>'
b = "<opnsense><x b='2' a='1'/></opnsense>"
assert driver.config_revision_content(a) == driver.config_revision_content(b)
def test_the_blanks_of_a_value_count(self, driver):
padded = CONFIG_XML.replace("<theme>opnsense</theme>", "<theme>opnsense </theme>")
assert driver.config_revision_content(padded) != driver.config_revision_content(CONFIG_XML)
def test_text_that_is_no_xml_raises(self, driver):
with pytest.raises(ParseError):
driver.config_revision_content("<html><body>Login")
class TestWhatTheDriverOffers:
def test_it_keeps_the_contract_of_device_types(self):
assert issubclass(OPNsenseDriver, ConfigRevisionsMixin)
def test_it_reads_and_reverts_revisions(self):
for name in ("get_config_revisions", "get_config_revision", "revert_config_revision"):
assert callable(getattr(OPNsenseDriver, name, None)), name
def test_it_replaces_no_configuration(self):
# No API takes an uploaded config.xml: an application asks for this and gets no.
assert getattr(OPNsenseDriver, "load_replace_candidate", None) is None
+273 -53
View File
@@ -132,8 +132,14 @@ class TestOpenClose:
password="s",
optional_args={"verify": False},
)
with pytest.raises(ConnectionException):
drv.open()
refused = requests.exceptions.ConnectionError("Connection refused")
with patch.object(requests.Session, "get", side_effect=refused) as get:
with pytest.raises(ConnectionException, match="Connection refused"):
drv.open()
get.assert_called_once()
assert get.call_args.args[0] == "https://unreachable.invalid/api/core/system/status"
assert drv.session is None
def test_close_clears_session(self, driver):
driver.close()
@@ -164,6 +170,30 @@ class TestIsAlive:
result = driver.is_alive()
assert result == {"is_alive": False}
@pytest.mark.parametrize(
("base_url", "expected"),
[
(None, ("opnsense.example.com", 443)),
("https://fw.example.com:8443", ("fw.example.com", 8443)),
("https://fw.example.com:8443/", ("fw.example.com", 8443)),
("https://fw.example.com", ("fw.example.com", 443)),
("http://fw.example.com", ("fw.example.com", 80)),
("https://[2001:db8::1]:4443", ("2001:db8::1", 4443)),
],
)
def test_probes_the_host_and_port_of_base_url(self, base_url, expected):
"""#15: an API on another port than 443 must not read as dead."""
args = {"verify": False}
if base_url is not None:
args["base_url"] = base_url
drv = OPNsenseDriver("opnsense.example.com", "u", "p", optional_args=args)
drv.session = MagicMock()
with patch("napalm_opnsense.opnsense.socket.create_connection") as mock_conn:
mock_conn.return_value.__enter__ = MagicMock(return_value=None)
mock_conn.return_value.__exit__ = MagicMock(return_value=False)
assert drv.is_alive() == {"is_alive": True}
assert mock_conn.call_args.args[0] == expected
# ---------------------------------------------------------------------------
# _get()
@@ -343,6 +373,13 @@ class TestGetInterfacesIp:
class TestGetArpTable:
def test_expires_is_not_an_age(self, driver):
"""``expires`` counts down to the entry's expiry; it says nothing about
when the neighbour was last confirmed. Reported as the age, an entry
refreshed a second ago looked 20 minutes old (NetOrk/netork#1327)."""
driver._get = lambda path: ARP_RESPONSE
assert {e["age"] for e in driver.get_arp_table()} == {-1.0}
def test_entry_count(self, driver):
driver._get = lambda path: ARP_RESPONSE
table = driver.get_arp_table()
@@ -681,6 +718,10 @@ class TestGetIpv6NeighborsTable:
driver._get = lambda path: {"rows": []}
assert driver.get_ipv6_neighbors_table() == []
def test_expires_is_not_an_age(self, driver):
driver._get = lambda path: NDP_RESPONSE
assert {e["age"] for e in driver.get_ipv6_neighbors_table()} == {-1.0}
# ---------------------------------------------------------------------------
# get_lldp_neighbors() / get_lldp_neighbors_detail()
@@ -757,44 +798,6 @@ class TestGetLldpNeighborsDetail:
assert driver.get_lldp_neighbors_detail() == {}
# ---------------------------------------------------------------------------
# get_ntp_servers()
# ---------------------------------------------------------------------------
NTP_STATUS_RESPONSE = {
"peers": [
{"address": "pool.ntp.org", "state": "synced"},
{"address": "time.cloudflare.com", "state": "candidate"},
]
}
class TestGetNtpServers:
def test_entry_count(self, driver):
driver._get = lambda path: NTP_STATUS_RESPONSE
servers = driver.get_ntp_servers()
assert len(servers) == 2
def test_server_addresses(self, driver):
driver._get = lambda path: NTP_STATUS_RESPONSE
servers = driver.get_ntp_servers()
assert "pool.ntp.org" in servers
assert "time.cloudflare.com" in servers
def test_value_is_empty_dict(self, driver):
driver._get = lambda path: NTP_STATUS_RESPONSE
for v in driver.get_ntp_servers().values():
assert v == {}
def test_endpoint_failure_returns_empty(self, driver):
driver._get = lambda path: (_ for _ in ()).throw(Exception("service not running"))
assert driver.get_ntp_servers() == {}
def test_empty_peers(self, driver):
driver._get = lambda path: {"peers": []}
assert driver.get_ntp_servers() == {}
# ---------------------------------------------------------------------------
# get_vlans()
# ---------------------------------------------------------------------------
@@ -1248,12 +1251,33 @@ class TestGetRadiusClients:
driver.get_radius_clients()
assert calls == ["/api/freeradius/client/search_client"]
def test_api_error_returns_empty_list(self, driver):
def test_a_failed_read_raises_rather_than_answering_none(self, driver):
"""An empty list must mean the firewall has none (#49)."""
driver._get = lambda path: (_ for _ in ()).throw(Exception("404"))
with pytest.raises(Exception, match="404"):
driver.get_radius_clients()
def test_an_answer_without_rows_raises(self, driver):
driver._get = lambda path: {"error": "plugin not installed"}
with pytest.raises(RuntimeError, match="rows"):
driver.get_radius_clients()
def test_no_clients_is_an_empty_list(self, driver):
driver._get = lambda path: {"rows": [], "total": 0}
assert driver.get_radius_clients() == []
def test_the_driver_says_its_reads_raise(self, driver):
assert type(driver).RADIUS_READS_RAISE is True
class TestCreateRadiusClient:
def test_a_saved_add_whose_lookup_fails_is_still_a_success(self, driver):
"""The add went through: its id is unknown, the add is not undone (#49)."""
driver._post = lambda path, data=None: {"result": "saved"}
driver._get = lambda path: (_ for _ in ()).throw(Exception("timeout"))
result = driver.create_radius_client("ap-lobby", "10.0.0.5/32", "s3cr3t")
assert result == {"success": True, "id": None}
def test_success_returns_remote_id(self, driver):
driver._post = lambda path, data=None: {"result": "saved"}
driver._get = lambda path: RADIUS_CLIENTS_RESPONSE
@@ -1334,12 +1358,28 @@ class TestGetRadiusUsers:
driver.get_radius_users()
assert calls == ["/api/freeradius/user/search_user"]
def test_api_error_returns_empty_list(self, driver):
def test_a_failed_read_raises_rather_than_answering_none(self, driver):
driver._get = lambda path: (_ for _ in ()).throw(Exception("404"))
with pytest.raises(Exception, match="404"):
driver.get_radius_users()
def test_an_answer_without_rows_raises(self, driver):
driver._get = lambda path: {"error": "plugin not installed"}
with pytest.raises(RuntimeError, match="rows"):
driver.get_radius_users()
def test_no_users_is_an_empty_list(self, driver):
driver._get = lambda path: {"rows": [], "total": 0}
assert driver.get_radius_users() == []
class TestCreateRadiusUser:
def test_a_saved_add_whose_lookup_fails_is_still_a_success(self, driver):
driver._post = lambda path, data=None: {"result": "saved"}
driver._get = lambda path: (_ for _ in ()).throw(Exception("timeout"))
result = driver.create_radius_user("jdoe", "hunter2")
assert result == {"success": True, "id": None}
def test_success_returns_remote_id(self, driver):
driver._post = lambda path, data=None: {"result": "saved"}
driver._get = lambda path: RADIUS_USERS_RESPONSE
@@ -1811,6 +1851,18 @@ KEA_SUBNETS_RESPONSE = {
}
def _reservation_row(mac, ip="172.22.8.253", uuid="existing-uuid-456"):
"""A searchReservation row, in the shape the os-kea plugin returns it."""
return {
"uuid": uuid,
"subnet": "172.22.8.0/24",
"ip_address": ip,
"hw_address": mac,
"hostname": "",
"description": "[netork]",
}
class TestCreateDhcpReservation:
def test_adds_new_reservation_when_none_exists(self, driver):
driver.session.get.return_value = _make_json_response(KEA_SUBNETS_RESPONSE)
@@ -1841,14 +1893,14 @@ class TestCreateDhcpReservation:
def test_updates_existing_reservation_for_same_ip(self, driver):
driver.session.get.return_value = _make_json_response(KEA_SUBNETS_RESPONSE)
driver.session.post.side_effect = [
_make_json_response(
{"rows": [{"uuid": "existing-uuid-456", "ip_address": "172.22.8.253"}]}
),
_make_json_response({"rows": [_reservation_row("02-AA-BB-CC-DD-EE")]}),
_make_json_response({"result": "saved", "uuid": "existing-uuid-456"}),
_make_json_response({"status": "ok"}),
]
driver.create_dhcp_reservation(mac="02:aa:bb:cc:dd:ee", ip="172.22.8.253")
driver.create_dhcp_reservation(
mac="02:aa:bb:cc:dd:ee", ip="172.22.8.253", hostname="new-vm"
)
set_call = driver.session.post.call_args_list[1]
assert (
@@ -1897,7 +1949,6 @@ class TestCreateDhcpReservation:
@pytest.mark.parametrize(
"field, live_value",
[
("hw_address", "02:aa:bb:cc:dd:ff"),
("hostname", "old-vm"),
("description", "made by hand"),
("subnet", "172.22.0.0/24"),
@@ -1933,6 +1984,23 @@ class TestCreateDhcpReservation:
"https://opnsense.example.com/api/kea/service/reconfigure",
]
def test_does_not_take_over_another_macs_reservation(self, driver):
"""#26: a reservation for the IP held by another MAC (made by hand, say)
was overwritten with the new MAC and the netOrk tag. It now raises and
leaves the firewall as it is; the caller decides."""
driver.session.get.return_value = _make_json_response(KEA_SUBNETS_RESPONSE)
driver.session.post.side_effect = [
_make_json_response({"rows": [_reservation_row("02:11:22:33:44:55")]}),
]
with pytest.raises(RuntimeError, match="02:11:22:33:44:55"):
driver.create_dhcp_reservation(
mac="02:aa:bb:cc:dd:ee", ip="172.22.8.253", hostname="new-vm"
)
# searchReservation only -- no setReservation, no service/reconfigure.
assert driver.session.post.call_count == 1
def test_raises_when_ip_not_in_any_kea_subnet(self, driver):
driver.session.get.return_value = _make_json_response(KEA_SUBNETS_RESPONSE)
@@ -1967,6 +2035,33 @@ class TestCreateDhcpReservation:
driver.session.post.assert_not_called()
# The search is what makes a retry update its reservation instead of adding a
# second one for the address: a write must not follow a search that failed (#40).
@pytest.mark.parametrize(
"error",
[
requests.exceptions.HTTPError("500 Server Error"),
requests.exceptions.ConnectionError("reset by peer"),
],
ids=["http-error", "connection-error"],
)
def test_failed_reservation_search_raises_before_any_write(self, driver, error):
driver.session.get.return_value = _make_json_response(KEA_SUBNETS_RESPONSE)
driver.session.post.side_effect = [
error, # searchReservation
_make_json_response({"result": "saved", "uuid": "new-uuid-123"}),
_make_json_response({"status": "ok"}),
]
with pytest.raises(RuntimeError, match="searchReservation") as raised:
driver.create_dhcp_reservation(mac="02:aa:bb:cc:dd:ee", ip="172.22.8.253")
assert raised.value.__cause__ is error
assert [c.args[0] for c in driver.session.post.call_args_list] == [
"https://opnsense.example.com/api/kea/dhcpv4/searchReservation"
]
# ---------------------------------------------------------------------------
# delete_dhcp_reservation_and_lease()
@@ -1977,7 +2072,7 @@ class TestDeleteDhcpReservationAndLease:
def test_deletes_existing_reservation_and_lease(self, driver):
driver.session.post.side_effect = [
_make_json_response(
{"rows": [{"uuid": "existing-uuid-456", "ip_address": "172.22.8.253"}]}
{"rows": [_reservation_row("02:aa:bb:cc:dd:ee")]}
), # searchReservation — match
_make_json_response({"result": "deleted"}), # delReservation
_make_json_response({"status": "ok"}), # service/reconfigure
@@ -1996,6 +2091,7 @@ class TestDeleteDhcpReservationAndLease:
"reservation_deleted": True,
"lease_found": True,
"lease_deleted": True,
"reservation_other_mac": "",
}
del_res_call = driver.session.post.call_args_list[1]
assert (
@@ -2029,15 +2125,66 @@ class TestDeleteDhcpReservationAndLease:
"reservation_deleted": False,
"lease_found": False,
"lease_deleted": False,
"reservation_other_mac": "",
}
# Only searchReservation was called — no delReservation/reconfigure/delLease.
assert driver.session.post.call_count == 1
def test_reservation_delete_raises_when_kea_rejects(self, driver):
def test_leaves_another_macs_reservation_and_lease_alone(self, driver):
"""#26: the IP was matched alone, so after an address was reused or
edited by hand the call removed another host's reservation and lease."""
driver.session.post.return_value = _make_json_response(
{"rows": [_reservation_row("02:11:22:33:44:55")]}
)
driver.session.get.return_value = _make_json_response(
{"rows": [{"address": "172.22.8.253", "hwaddr": "02:11:22:33:44:55"}]}
)
result = driver.delete_dhcp_reservation_and_lease(
mac="02:aa:bb:cc:dd:ee", ip="172.22.8.253"
)
assert result == {
"reservation_found": False,
"reservation_deleted": False,
"lease_found": False,
"lease_deleted": False,
"reservation_other_mac": "02:11:22:33:44:55",
}
# searchReservation only -- no delReservation, reconfigure or del_lease.
assert [c.args[0] for c in driver.session.post.call_args_list] == [
"https://opnsense.example.com/api/kea/dhcpv4/searchReservation"
]
def test_deletes_its_own_reservation_next_to_another_macs(self, driver):
"""The search is a phrase match, so it can list another MAC's row too."""
driver.session.post.side_effect = [
_make_json_response(
{"rows": [{"uuid": "existing-uuid-456", "ip_address": "172.22.8.253"}]}
{
"rows": [
_reservation_row("02:11:22:33:44:55", uuid="foreign-uuid"),
_reservation_row("02:aa:bb:cc:dd:ee", uuid="own-uuid"),
]
}
),
_make_json_response({"result": "deleted"}),
_make_json_response({"status": "ok"}),
]
driver.session.get.return_value = _make_json_response({"rows": []})
result = driver.delete_dhcp_reservation_and_lease(
mac="02:aa:bb:cc:dd:ee", ip="172.22.8.253"
)
assert result["reservation_deleted"] is True
assert result["reservation_other_mac"] == "02:11:22:33:44:55"
assert driver.session.post.call_args_list[1].args[0] == (
"https://opnsense.example.com/api/kea/dhcpv4/delReservation/own-uuid"
)
def test_reservation_delete_raises_when_kea_rejects(self, driver):
driver.session.post.side_effect = [
_make_json_response({"rows": [_reservation_row("02:AA:BB:CC:DD:EE")]}),
_make_json_response({"result": "not found"}), # delReservation rejected
]
@@ -2049,9 +2196,7 @@ class TestDeleteDhcpReservationAndLease:
def test_lease_delete_failure_is_non_fatal(self, driver):
driver.session.post.side_effect = [
_make_json_response(
{"rows": [{"uuid": "existing-uuid-456", "ip_address": "172.22.8.253"}]}
),
_make_json_response({"rows": [_reservation_row("02:AA:BB:CC:DD:EE")]}),
_make_json_response({"result": "deleted"}),
_make_json_response({"status": "ok"}),
]
@@ -2853,6 +2998,81 @@ class TestSyncDnsZone:
assert len([p for p, _ in calls if p.endswith("addhostoverride")]) == 1
@pytest.mark.parametrize("service", ["unbound", "dnsmasq"])
def test_a_failed_read_raises_and_changes_nothing(self, driver, service):
"""#14: a sync on an inventory it could not read deleted nothing and
added every record a second time."""
calls = []
def _post(path, data=None):
calls.append(path)
if path.endswith("searchhostoverride"):
raise requests.exceptions.ConnectionError("reset by peer")
return {"result": "saved"}
driver._detect_active_dns = lambda: service
driver._post = _post
with pytest.raises(requests.exceptions.ConnectionError):
driver.sync_dns_zone(
"office.local",
[{"hostname": "nas", "ip": "172.22.40.8", "record_type": "A", "enabled": True}],
)
assert calls == [f"/api/{service}/settings/searchhostoverride"]
class TestHostOverrideReadFailure:
"""A failed read raises: an empty list would say the firewall has no overrides."""
@pytest.mark.parametrize("service", ["unbound", "dnsmasq"])
def test_get_dns_entries_raises_when_the_search_fails(self, driver, service):
def _post(path, data=None):
raise requests.exceptions.HTTPError("500 Server Error")
driver._detect_active_dns = lambda: service
driver._post = _post
with pytest.raises(requests.exceptions.HTTPError):
driver.get_dns_entries()
class TestDnsServiceDetection:
"""A failed service search raises: None would say neither Unbound nor Dnsmasq runs (#39)."""
def test_get_dns_entries_raises_when_the_service_search_fails(self, driver):
driver.session.get.side_effect = requests.exceptions.ConnectionError("reset by peer")
with pytest.raises(requests.exceptions.ConnectionError):
driver.get_dns_entries()
driver.session.post.assert_not_called()
def test_sync_dns_zone_reports_the_api_error_and_writes_nothing(self, driver):
driver.session.get.side_effect = requests.exceptions.HTTPError("502 Bad Gateway")
with pytest.raises(requests.exceptions.HTTPError, match="502"):
driver.sync_dns_zone(
"office.local",
[{"hostname": "nas", "ip": "172.22.40.8", "record_type": "A", "enabled": True}],
)
driver.session.post.assert_not_called()
def test_get_dns_entries_is_empty_when_neither_service_runs(self, driver):
driver.session.get.return_value = _make_json_response(
{
"rows": [
{"name": "unbound", "running": 0},
{"name": "dnsmasq", "running": 0},
{"name": "sshd", "running": 1},
]
}
)
assert driver.get_dns_entries() == []
driver.session.post.assert_not_called()
# ---------------------------------------------------------------------------
# uninstall_package – says what it cannot do
+90
View File
@@ -0,0 +1,90 @@
"""Matching Kea reservations and leases on address and MAC (#26)."""
from napalm_opnsense.kea_reservations import (
lease_held,
reservation_unchanged,
split_by_mac,
subnet_containing,
)
def _row(mac, uuid="u-1"):
return {"uuid": uuid, "ip_address": "172.22.8.253", "hw_address": mac}
class TestSplitByMac:
def test_no_rows_is_neither_own_nor_other(self):
assert split_by_mac([], "02:aa:bb:cc:dd:ee") == (None, "")
def test_own_row_matches_whatever_the_mac_spelling(self):
row = _row("02-AA-BB-CC-DD-EE")
assert split_by_mac([row], "02:aa:bb:cc:dd:ee") == (row, "")
def test_another_hosts_row_is_reported_by_its_mac(self):
assert split_by_mac([_row("02-11-22-33-44-55")], "02:aa:bb:cc:dd:ee") == (
None,
"02:11:22:33:44:55",
)
def test_a_row_without_mac_is_no_ones(self):
"""It cannot be shown to be the caller's, so it is never taken as such."""
row = {"uuid": "u-1", "ip_address": "172.22.8.253"}
assert split_by_mac([row], "02:aa:bb:cc:dd:ee") == (None, "")
def test_another_hosts_mac_is_found_behind_a_row_without_one(self):
rows = [{"uuid": "u-0", "ip_address": "172.22.8.253"}, _row("02:11:22:33:44:55")]
assert split_by_mac(rows, "02:aa:bb:cc:dd:ee") == (None, "02:11:22:33:44:55")
class TestLeaseHeld:
def test_os_kea_lease_of_the_mac(self):
rows = [{"address": "172.22.8.253", "hwaddr": "02:AA:BB:CC:DD:EE"}]
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is True
def test_plain_kea_lease_of_the_mac(self):
rows = [{"ip-address": "172.22.8.253", "hw-address": "02:aa:bb:cc:dd:ee"}]
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is True
def test_lease_of_another_mac(self):
rows = [{"address": "172.22.8.253", "hwaddr": "02:11:22:33:44:55"}]
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is False
def test_lease_of_another_address(self):
rows = [{"address": "172.22.8.254", "hwaddr": "02:aa:bb:cc:dd:ee"}]
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is False
class TestReservationUnchanged:
WANTED = {
"subnet": "subnet-uuid",
"ip_address": "172.22.8.253",
"hw_address": "02:aa:bb:cc:dd:ee",
"hostname": "new-vm",
"description": "[netork]",
}
def test_a_different_mac_is_a_change(self):
row = dict(self.WANTED, hw_address="02:11:22:33:44:55")
assert reservation_unchanged(row, self.WANTED, "172.22.8.0/24") is False
def test_the_same_reservation_is_unchanged(self):
row = dict(self.WANTED, hw_address="02-AA-BB-CC-DD-EE", subnet="172.22.8.0/24")
assert reservation_unchanged(row, self.WANTED, "172.22.8.0/24") is True
class TestSubnetContaining:
ROWS = [
{"uuid": "s-broken", "subnet": "not-a-cidr"},
{"uuid": "s-nocidr"},
{"uuid": "s-8", "subnet": " 172.22.8.0/24 "},
{"uuid": "s-wide", "subnet": "172.22.0.0/16"},
]
def test_first_subnet_holding_the_address_wins(self):
assert subnet_containing(self.ROWS, "172.22.8.253") == self.ROWS[2]
def test_rows_without_a_readable_subnet_are_skipped(self):
assert subnet_containing(self.ROWS, "172.22.9.1") == self.ROWS[3]
def test_none_when_no_subnet_holds_the_address(self):
assert subnet_containing(self.ROWS, "10.99.99.99") is None
+212
View File
@@ -0,0 +1,212 @@
"""How people log in to the firewall: the web interface's auth servers and SSH (NetOrk/netork#662).
OPNsense tries a login against each server named in ``<system><webgui><authmode>``
in turn, and the first that accepts it lets the person in
(``AuthenticationFactory::authenticate``). The ``System`` service runs the same list
for ``sshd``, ``login``, ``su`` and ``sudo``, so an SSH password goes through it too.
A key over SSH does not. sshd's settings come from ``<system><ssh>``
(``openssh_configure_do``).
``config_xml_sample.xml`` is OPNsense's own sample: no ``authmode`` (the Local
Database alone) and an ``<ssh>`` without ``enabled`` (sshd off).
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from xml.etree.ElementTree import ParseError
import pytest
from napalm_opnsense.login_auth import login_sources, ssh_server_auth
from napalm_opnsense.opnsense import OPNsenseDriver
from .test_time_sync import CONFIG_PATH, CONFIG_XML, Firewall
TOTP_SERVER = """
<authserver>
<refid>65a1</refid>
<type>totp</type>
<name>TOTP</name>
<otpLength>6</otpLength>
</authserver>"""
LDAP_SERVER = """
<authserver>
<refid>65a2</refid>
<type>ldap</type>
<name>Directory</name>
</authserver>"""
LDAP_TOTP_SERVER = """
<authserver>
<refid>65a3</refid>
<type>ldap-totp</type>
<name>Directory OTP</name>
</authserver>"""
RADIUS_SERVER = """
<authserver>
<refid>65a4</refid>
<type>radius</type>
<name>RADIUS</name>
</authserver>"""
PLUGIN_SERVER = """
<authserver>
<refid>65a5</refid>
<type>sso-thing</type>
<name>Plugin</name>
</authserver>"""
ALL_SERVERS = TOTP_SERVER + LDAP_SERVER + LDAP_TOTP_SERVER + RADIUS_SERVER + PLUGIN_SERVER
def _config(*, authmode: str | None = None, servers: str = "", ssh: str | None = None) -> str:
"""The sample with an ``authmode``, extra ``<authserver>`` entries, another ``<ssh>``."""
xml = CONFIG_XML
if authmode is not None:
xml = xml.replace(
"<noroot>1</noroot>", f"<noroot>1</noroot>\n <authmode>{authmode}</authmode>"
)
if ssh is not None:
xml = xml.replace("<ssh>\n <group>admins</group>\n </ssh>", f"<ssh>{ssh}</ssh>")
return xml.replace("</system>", f"{servers}\n </system>", 1)
def _source(name: str, kind: str, factors: str) -> dict:
return {"name": name, "kind": kind, "factors": factors}
LOCAL = _source("Local Database", "local", "password")
TOTP = _source("TOTP", "totp", "password_otp")
class TestLoginSources:
def test_without_authmode_the_local_database_alone(self):
assert login_sources(CONFIG_XML) == [LOCAL]
def test_an_empty_authmode_is_the_local_database_too(self):
assert login_sources(_config(authmode="")) == [LOCAL]
def test_each_server_in_the_order_authmode_names_them(self):
xml = _config(authmode="TOTP,Local Database", servers=TOTP_SERVER)
assert login_sources(xml) == [TOTP, LOCAL]
def test_what_each_kind_of_server_asks_for(self):
xml = _config(authmode="TOTP,Directory,Directory OTP,RADIUS,Plugin", servers=ALL_SERVERS)
assert login_sources(xml) == [
TOTP,
_source("Directory", "ldap", "password"),
_source("Directory OTP", "ldap-totp", "password_otp"),
_source("RADIUS", "radius", "external"),
_source("Plugin", "sso-thing", "unknown"),
]
def test_a_name_no_server_has_is_skipped_as_opnsense_skips_it(self):
# get() returns null for it, and authenticate() goes on with the next name.
# Names are not trimmed: " TOTP" is no server's name either.
xml = _config(authmode="Gone,TOTP, TOTP,Local API", servers=TOTP_SERVER)
assert login_sources(xml) == [TOTP]
def test_a_server_without_type_or_name_is_not_listed(self):
nameless = "<authserver><type>totp</type><name/></authserver>"
typeless = "<authserver><type/><name>Bare</name></authserver>"
xml = _config(authmode="Bare", servers=nameless + typeless)
assert login_sources(xml) == []
def test_a_configured_server_named_local_database_replaces_the_built_in_one(self):
renamed = "<authserver><type>totp</type><name>Local Database</name></authserver>"
assert login_sources(_config(servers=renamed)) == [
_source("Local Database", "totp", "password_otp")
]
def test_a_text_that_is_no_xml_raises(self):
with pytest.raises(ParseError):
login_sources("<html>login</html")
SSH_ON = "<enabled>enabled</enabled><group>admins</group>"
SSH_KEYS_ONLY = {
"password_authentication": False,
"kbd_interactive_authentication": False,
"pubkey_authentication": True,
"hostbased_authentication": False,
"gssapi_authentication": False,
"authentication_methods": [],
"permit_root_login": "no",
"use_pam": True,
"pam_auth_stack": None,
}
class TestSshServerAuth:
def test_without_enabled_sshd_is_off(self):
auth = ssh_server_auth(CONFIG_XML)
assert auth["server_enabled"] is False
assert auth["password_sources"] == [LOCAL]
def test_enabled_with_keys_only(self):
auth = ssh_server_auth(_config(ssh=SSH_ON))
assert auth == {**SSH_KEYS_ONLY, "password_sources": [LOCAL], "server_enabled": True}
def test_password_login_switches_challenge_response_on_with_it(self):
auth = ssh_server_auth(_config(ssh=SSH_ON + "<passwordauth>1</passwordauth>"))
assert auth["password_authentication"] is True
assert auth["kbd_interactive_authentication"] is True
def test_presence_counts_as_opnsense_tests_it_with_isset(self):
auth = ssh_server_auth(_config(ssh="<enabled/><passwordauth/><permitrootlogin/>"))
assert auth["server_enabled"] is True
assert auth["password_authentication"] is True
assert auth["permit_root_login"] == "yes"
def test_an_ssh_password_goes_through_the_web_interface_s_servers(self):
xml = _config(authmode="TOTP", servers=TOTP_SERVER, ssh=SSH_ON)
assert ssh_server_auth(xml)["password_sources"] == [TOTP]
def test_no_ssh_element_at_all_is_off(self):
xml = CONFIG_XML.replace("<ssh>\n <group>admins</group>\n </ssh>", "")
assert ssh_server_auth(xml)["server_enabled"] is False
@pytest.fixture
def driver():
with patch("napalm_opnsense.opnsense.requests.Session"):
drv = OPNsenseDriver(
hostname="fw", username="k", password="s", optional_args={"verify": False}
)
drv.session = MagicMock()
yield drv
class TestDriver:
def test_the_web_login_from_config_xml(self, driver):
firewall = Firewall(config=_config(authmode="TOTP", servers=TOTP_SERVER))
driver.session.get.side_effect = firewall.get
assert driver.get_web_login_auth() == {"sources": [TOTP]}
assert firewall.paths == [CONFIG_PATH]
def test_the_ssh_login_from_config_xml(self, driver):
firewall = Firewall(config=_config(ssh=SSH_ON))
driver.session.get.side_effect = firewall.get
assert driver.get_ssh_server_auth()["server_enabled"] is True
assert firewall.paths == [CONFIG_PATH]
def test_a_failed_download_raises(self, driver):
import requests
driver.session.get.side_effect = Firewall(config=requests.HTTPError("403 Forbidden")).get
with pytest.raises(requests.HTTPError):
driver.get_web_login_auth()
with pytest.raises(requests.HTTPError):
driver.get_ssh_server_auth()
+495
View File
@@ -0,0 +1,495 @@
"""Scheduled jobs on OPNsense: the cron jobs of config.xml, over the REST API (#43).
OPNsense keeps its cron jobs in its configuration (``System > Settings > Cron``)
and runs each as a configd action. ``/api/cron/settings/get`` answers with every
job, the action as the option its ``command`` list has selected;
``get_job`` without a uuid is a blank job, and its ``command`` options are the
actions configd offers. The fixtures are synthetic, in the shape of an OPNsense
26.7 answer: an admin's job, one the intrusion detection registered (origin
``IDS``), one an application wrote, one with parameters, and one whose marker
names no valid job.
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from napalm_device_types import ScheduledJobsMixin
from napalm_device_types.scheduled_jobs import (
ScheduledJobChanged,
ScheduledJobRefused,
job_digest,
)
from napalm_opnsense.opnsense import OPNsenseDriver
FIXTURES = Path(__file__).parent / "fixtures"
SETTINGS = json.loads((FIXTURES / "cron_settings_get.json").read_text())
BLANK_JOB = json.loads((FIXTURES / "cron_settings_get_job.json").read_text())
ADMIN = "opnsense:0b6e3c52-6a1e-4c7a-9a0e-2f0a1d6c3b11"
PLATFORM = "opnsense:1f2d8e04-93b7-4f4e-8c55-7d1e0c9a2b22"
OWN = "opnsense:2a7c9b16-4d3e-4b8f-a1c2-5e6f7a8b9c33"
OWN_UUID = OWN.removeprefix("opnsense:")
WITH_PARAMETERS = "opnsense:3c8d0e27-5f4a-4c9b-b2d3-6f7a8b9c0d44"
BAD_MARKER = "opnsense:4d9e1f38-6a5b-4dac-83e4-7a8b9c0d1e55"
SAVED = {"result": "saved"}
RELOADED = {"status": "ok"}
class Firewall:
"""Answers the cron API as a firewall would, and records every POST."""
def __init__(self, settings=SETTINGS, blank=BLANK_JOB, answers=None):
self.settings = copy.deepcopy(settings)
self.blank = blank
self.answers = answers or {}
self.posts: list[tuple[str, dict | None]] = []
def get(self, path: str):
if path == "/api/cron/settings/get":
return self.settings
if path == "/api/cron/settings/get_job":
return self.blank
raise AssertionError(f"unexpected GET {path}")
def post(self, path: str, data=None):
self.posts.append((path, data))
for prefix, answer in self.answers.items():
if path.startswith(prefix):
return answer
if path == "/api/cron/service/reconfigure":
return RELOADED
if path.startswith("/api/cron/settings/toggle_job/"):
return {"result": "Enabled" if path.endswith("/1") else "Disabled", "changed": True}
if path.startswith("/api/cron/settings/del_job/"):
return {"result": "deleted"}
if path == "/api/cron/settings/add_job":
return {"result": "saved", "uuid": "5eaf2049-7b6c-4ebd-94f5-8b9c0d1e2f66"}
if path.startswith("/api/cron/settings/set_job/"):
return SAVED
raise AssertionError(f"unexpected POST {path}")
@property
def paths(self) -> list[str]:
return [path for path, _ in self.posts]
def _driver(firewall: Firewall) -> OPNsenseDriver:
with patch("napalm_opnsense.opnsense.requests.Session"):
drv = OPNsenseDriver(hostname="fw", username="k", password="s")
drv.session = MagicMock()
drv._get = firewall.get # type: ignore[method-assign]
drv._post = firewall.post # type: ignore[method-assign]
return drv
def _jobs(firewall: Firewall | None = None) -> dict[str, dict]:
reading = _driver(firewall or Firewall()).get_scheduled_jobs()
return {job["key"]: job for job in reading["jobs"]}
def _digest(key: str) -> str:
return _jobs()[key]["digest"]
def _spec(**over) -> dict:
spec = {
"name": "alias-refresh",
"schedule": "*/30 * * * *",
"run_as": "root",
"command": "filter refresh_aliases",
"enabled": True,
"description": "Keep the aliases fresh",
}
spec.update(over)
return spec
def test_the_driver_offers_every_verb():
assert issubclass(OPNsenseDriver, ScheduledJobsMixin)
for verb in (
"get_scheduled_jobs",
"manage_scheduled_job",
"put_scheduled_job",
"delete_scheduled_job",
"get_scheduled_job_commands",
):
assert callable(getattr(OPNsenseDriver, verb))
class TestReading:
def test_every_job_of_the_configuration(self):
reading = _driver(Firewall()).get_scheduled_jobs()
assert reading["time_zone"] is None
assert [job["key"] for job in reading["jobs"]] == [
ADMIN,
PLATFORM,
OWN,
WITH_PARAMETERS,
BAD_MARKER,
]
def test_an_admins_job(self):
job = _jobs()[ADMIN]
assert job == {
"key": ADMIN,
"kind": "cron",
"source": "config.xml",
"run_as": "root",
"schedule": "0 3 * * 1-5",
"schedule_kind": "cron",
"command": "system remote backup",
"enabled": True,
"managed_by": "admin",
"actions": ["enable", "disable"],
"description": "Nightly configuration backup",
"digest": job["digest"],
}
assert job["digest"] == job_digest(job)
def test_a_job_another_service_registered_is_the_platforms(self):
job = _jobs()[PLATFORM]
assert (job["managed_by"], job["enabled"], job["command"]) == (
"platform",
False,
"ids update",
)
assert job["actions"] == ["enable", "disable"]
def test_a_job_an_application_wrote_carries_its_name(self):
job = _jobs()[OWN]
assert job["managed_by"] == "application"
assert job["name"] == "dnsbl-refresh"
assert job["description"] == "Refresh the DNS blocklists"
assert job["actions"] == ["enable", "disable", "edit", "delete"]
def test_a_marker_without_a_valid_name_is_an_admins_job(self):
job = _jobs()[BAD_MARKER]
assert job["managed_by"] == "admin"
assert "name" not in job
assert job["description"] == "napalm-scheduled-job: Not_A_Name written by hand"
def test_a_marker_on_another_services_job_is_still_the_platforms(self):
firewall = Firewall()
node = firewall.settings["job"]["jobs"]["job"][PLATFORM.removeprefix("opnsense:")]
node["description"] = "napalm-scheduled-job: ids-update taken over"
job = _jobs(firewall)[PLATFORM]
assert job["managed_by"] == "platform"
assert "name" not in job
def test_the_parameters_follow_the_action(self):
assert _jobs()[WITH_PARAMETERS]["command"] == "filter refresh_aliases --quiet --all"
def test_a_job_with_no_description_has_none(self):
firewall = Firewall()
firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["description"] = ""
assert "description" not in _jobs(firewall)[ADMIN]
def test_an_action_configd_no_longer_offers_reads_as_no_command(self):
firewall = Firewall()
node = firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]
node["command"] = {k: {**v, "selected": 0} for k, v in node["command"].items()}
assert _jobs(firewall)[ADMIN]["command"] == ""
def test_a_command_given_as_a_plain_value_is_taken_as_it_is(self):
firewall = Firewall()
node = firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]
node["command"] = "system remote backup"
assert _jobs(firewall)[ADMIN]["command"] == "system remote backup"
def test_enabling_a_job_changes_its_digest(self):
firewall = Firewall()
firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["enabled"] = "0"
assert _jobs(firewall)[ADMIN]["digest"] != _digest(ADMIN)
def test_no_jobs_is_an_empty_list(self):
firewall = Firewall(settings={"job": {"jobs": {"job": []}}})
assert _driver(firewall).get_scheduled_jobs()["jobs"] == []
@pytest.mark.parametrize(
"answer",
[{}, [], {"job": {}}, {"job": {"jobs": {}}}, {"job": {"jobs": {"job": "x"}}}],
)
def test_an_answer_without_the_jobs_raises(self, answer):
with pytest.raises(ValueError, match="jobs"):
_driver(Firewall(settings=answer)).get_scheduled_jobs()
def test_a_job_without_its_schedule_raises(self):
firewall = Firewall()
del firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["hours"]
with pytest.raises(ValueError, match="schedule"):
_driver(firewall).get_scheduled_jobs()
class TestCommands:
def test_the_actions_configd_offers(self):
commands = _driver(Firewall()).get_scheduled_job_commands()
assert commands[0] == {
"command": "filter refresh_aliases",
"description": "Update and reload firewall aliases",
}
assert [c["command"] for c in commands] == [
"filter refresh_aliases",
"firmware auto-update",
"ids update",
"system ha_reconfigure_backup",
"system remote backup",
"unbound dnsbl",
]
def test_the_blank_placeholder_is_no_action(self):
blank = copy.deepcopy(BLANK_JOB)
blank["job"]["command"][""] = {"value": "None", "selected": 1}
commands = _driver(Firewall(blank=blank)).get_scheduled_job_commands()
assert "" not in [c["command"] for c in commands]
@pytest.mark.parametrize(
"answer", [{}, [], {"job": []}, {"job": {"command": {}}}, {"job": {"command": "x"}}]
)
def test_no_actions_raises(self, answer):
# configd that did not answer leaves the list empty: that is no reading.
with pytest.raises(ValueError, match="configd"):
_driver(Firewall(blank=answer)).get_scheduled_job_commands()
class TestManage:
@pytest.mark.parametrize(
"action, flag, word", [("enable", "1", "enabled"), ("disable", "0", "disabled")]
)
def test_switching_a_job_toggles_it_and_reloads_cron(self, action, flag, word):
firewall = Firewall()
result = _driver(firewall).manage_scheduled_job(PLATFORM, action, digest=_digest(PLATFORM))
assert result == {"success": True, "output": f"{PLATFORM} {word}"}
assert firewall.paths == [
f"/api/cron/settings/toggle_job/{PLATFORM.removeprefix('opnsense:')}/{flag}",
"/api/cron/service/reconfigure",
]
def test_running_a_job_now_is_refused(self):
firewall = Firewall()
with pytest.raises(ScheduledJobRefused, match="run"):
_driver(firewall).manage_scheduled_job(ADMIN, "run", digest=_digest(ADMIN))
assert firewall.posts == []
def test_an_unknown_action_is_refused(self):
with pytest.raises(ScheduledJobRefused, match="unknown action"):
_driver(Firewall()).manage_scheduled_job(ADMIN, "edit", digest=_digest(ADMIN))
def test_an_unknown_job_raises_lookup_error(self):
with pytest.raises(LookupError):
_driver(Firewall()).manage_scheduled_job("opnsense:nope", "enable", digest="x")
def test_a_job_changed_since_it_was_read_is_not_touched(self):
firewall = Firewall()
with pytest.raises(ScheduledJobChanged):
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest="0" * 16)
assert firewall.posts == []
def test_a_refused_toggle_raises_and_cron_is_not_reloaded(self):
firewall = Firewall(answers={"/api/cron/settings/toggle_job/": {"result": "failed"}})
with pytest.raises(RuntimeError, match="failed"):
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest=_digest(ADMIN))
assert "/api/cron/service/reconfigure" not in firewall.paths
def test_a_cron_that_does_not_reload_raises(self):
firewall = Firewall(answers={"/api/cron/service/reconfigure": {"status": "failed"}})
with pytest.raises(RuntimeError, match="reload"):
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest=_digest(ADMIN))
class TestPut:
def test_a_new_job_is_added_with_its_marker_and_cron_reloads(self):
firewall = Firewall()
result = _driver(firewall).put_scheduled_job(_spec())
assert result == {
"success": True,
"output": "opnsense:5eaf2049-7b6c-4ebd-94f5-8b9c0d1e2f66 created",
}
assert firewall.posts == [
(
"/api/cron/settings/add_job",
{
"job": {
"enabled": "1",
"minutes": "*/30",
"hours": "*",
"days": "*",
"months": "*",
"weekdays": "*",
"command": "filter refresh_aliases",
"parameters": "",
"description": "napalm-scheduled-job: alias-refresh Keep the aliases fresh",
}
},
),
("/api/cron/service/reconfigure", None),
]
def test_an_application_job_is_changed_in_place(self):
firewall = Firewall()
spec = _spec(name="dnsbl-refresh", command="unbound dnsbl", enabled=False)
del spec["description"]
result = _driver(firewall).put_scheduled_job(spec, digest=_digest(OWN))
assert result == {"success": True, "output": f"{OWN} changed"}
path, data = firewall.posts[0]
assert path == f"/api/cron/settings/set_job/{OWN_UUID}"
assert data["job"]["enabled"] == "0"
assert data["job"]["description"] == "napalm-scheduled-job: dnsbl-refresh"
assert firewall.paths[-1] == "/api/cron/service/reconfigure"
def test_the_words_after_the_action_are_its_parameters_one_per_line(self):
firewall = Firewall()
_driver(firewall).put_scheduled_job(
_spec(command=" filter refresh_aliases --quiet --all ")
)
job = firewall.posts[0][1]["job"]
assert (job["command"], job["parameters"]) == ("filter refresh_aliases", "--quiet\n--all")
def test_the_longest_action_the_command_starts_with_wins(self):
blank = copy.deepcopy(BLANK_JOB)
blank["job"]["command"]["filter"] = {"value": "Reload the filter", "selected": 0}
firewall = Firewall(blank=blank)
_driver(firewall).put_scheduled_job(_spec(command="filter refresh_aliases"))
job = firewall.posts[0][1]["job"]
assert (job["command"], job["parameters"]) == ("filter refresh_aliases", "")
@pytest.mark.parametrize(
"schedule, fields",
[
("@daily", ("0", "0", "*", "*", "*")),
("@hourly", ("0", "*", "*", "*", "*")),
("0 6 * jan-Mar MON-fri", ("0", "6", "*", "1-3", "1-5")),
("5 4 1,15 * sun,7", ("5", "4", "1,15", "*", "0,7")),
],
)
def test_the_schedule_is_written_as_its_five_fields(self, schedule, fields):
firewall = Firewall()
_driver(firewall).put_scheduled_job(_spec(schedule=schedule))
job = firewall.posts[0][1]["job"]
assert tuple(job[f] for f in ("minutes", "hours", "days", "months", "weekdays")) == fields
@pytest.mark.parametrize(
"over, match",
[
({"schedule": "@reboot"}, "@reboot"),
({"run_as": "nobody"}, "root"),
({"command": "rm -rf /"}, "configd offers no action"),
({"command": "filter refresh_aliases\nids update"}, "one line"),
({"command": "filter refresh_aliases 'a b'"}, "parameter"),
({"command": "filter refresh_aliases a\\b"}, "parameter"),
({"name": "Not A Name"}, "job name"),
({"schedule": "61 * * * *"}, "range"),
],
)
def test_what_opnsense_cannot_take_is_refused_before_anything_is_written(self, over, match):
firewall = Firewall()
with pytest.raises(ScheduledJobRefused, match=match):
_driver(firewall).put_scheduled_job(_spec(**over))
assert firewall.posts == []
def test_a_new_job_whose_name_is_taken_is_not_written(self):
firewall = Firewall()
with pytest.raises(ScheduledJobChanged, match="dnsbl-refresh"):
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"))
assert firewall.posts == []
def test_a_change_to_a_job_that_is_gone_raises_lookup_error(self):
with pytest.raises(LookupError, match="alias-refresh"):
_driver(Firewall()).put_scheduled_job(_spec(), digest="0" * 16)
def test_a_change_to_a_job_changed_since_it_was_read_is_not_written(self):
firewall = Firewall()
with pytest.raises(ScheduledJobChanged):
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"), digest="0" * 16)
assert firewall.posts == []
def test_what_opnsense_refuses_to_save_is_refused(self):
refusal = {"result": "failed", "validations": {"job.description": "Text too long"}}
firewall = Firewall(answers={"/api/cron/settings/add_job": refusal})
with pytest.raises(ScheduledJobRefused, match="Text too long"):
_driver(firewall).put_scheduled_job(_spec())
assert "/api/cron/service/reconfigure" not in firewall.paths
def test_a_failed_save_without_a_reason_raises(self):
firewall = Firewall(answers={"/api/cron/settings/set_job/": {"result": "failed"}})
with pytest.raises(RuntimeError, match="failed"):
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"), digest=_digest(OWN))
assert "/api/cron/service/reconfigure" not in firewall.paths
class TestDelete:
def test_an_application_job_is_deleted_and_cron_reloads(self):
firewall = Firewall()
result = _driver(firewall).delete_scheduled_job(OWN, digest=_digest(OWN))
assert result == {"success": True, "output": f"{OWN} deleted"}
assert firewall.paths == [
f"/api/cron/settings/del_job/{OWN_UUID}",
"/api/cron/service/reconfigure",
]
@pytest.mark.parametrize("key", [ADMIN, PLATFORM, BAD_MARKER])
def test_a_job_no_application_wrote_is_only_switched(self, key):
firewall = Firewall()
with pytest.raises(ScheduledJobRefused, match="only switched"):
_driver(firewall).delete_scheduled_job(key, digest=_digest(key))
assert firewall.posts == []
def test_a_job_changed_since_it_was_read_is_not_deleted(self):
firewall = Firewall()
with pytest.raises(ScheduledJobChanged):
_driver(firewall).delete_scheduled_job(OWN, digest="0" * 16)
assert firewall.posts == []
def test_a_delete_opnsense_did_not_do_raises(self):
firewall = Firewall(answers={"/api/cron/settings/del_job/": {"result": "not found"}})
with pytest.raises(RuntimeError, match="not found"):
_driver(firewall).delete_scheduled_job(OWN, digest=_digest(OWN))
assert "/api/cron/service/reconfigure" not in firewall.paths
+35 -4
View File
@@ -12,9 +12,25 @@ from __future__ import annotations
from unittest.mock import MagicMock
import pytest
import requests
from napalm_opnsense.opnsense import OPNsenseDriver
#: The plugin's settings as OPNsense 26.7 serves them (gw-01, 2026-10-31). Its
#: model knows exactly these fields, and a set naming any other one, or giving a
#: field anything but a string, is a 500 (#36).
MODEL = {
"enabled": "0",
"community": "public",
"syslocation": "Home",
"syscontact": "admin@example.org",
"l3visibility": "1",
"versionoid": "1",
"enableagentx": "1",
"enableobservium": "1",
"listen": {"10.0.0.1": {"value": "10.0.0.1", "selected": 1}},
}
SETTINGS = {
"community": "c0mm",
"allowed_sources": ["10.7.224.20", "10.7.225.0/24"],
@@ -34,12 +50,15 @@ class _Api:
def get(self, path):
if path == "/api/netsnmp/general/get":
return {"general": {"enabled": "0"}} if self.installed else {}
return {"general": dict(MODEL)} if self.installed else {}
raise AssertionError(path)
def post(self, path, body=None):
self.posts.append((path, body))
if path == "/api/netsnmp/general/set":
general = (body or {}).get("general", {})
if any(k not in MODEL or not isinstance(v, str) for k, v in general.items()):
raise requests.HTTPError(f"500 Server Error: Internal Server Error for url: {path}")
return {"result": self.saved}
if path == "/api/firewall/filter/searchRule":
return {"rows": self.rules}
@@ -83,12 +102,24 @@ class TestTheCallersValues:
assert result["success"] is True
general = _body(api, "/api/netsnmp/general/set")["general"]
assert general["enabled"] == "1"
assert (general["community"], general["contact"], general["location"]) == (
assert (general["community"], general["syscontact"], general["syslocation"]) == (
"c0mm",
"ops",
"rack 1",
)
assert general["listen"] == {"10.0.0.1": {"selected": 1}}
assert general["listen"] == "10.0.0.1"
def test_only_fields_the_plugins_model_has_are_sent(self, driver, api):
result = driver.configure_snmp_agent({**SETTINGS, "listen": "10.0.0.1"})
assert result["success"] is True
assert set(_body(api, "/api/netsnmp/general/set")["general"]) <= set(MODEL)
def test_contact_and_location_the_caller_leaves_out_stay_as_they_are(self, driver, api):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
general = _body(api, "/api/netsnmp/general/set")["general"]
assert "syscontact" not in general and "syslocation" not in general
def test_nothing_of_an_application_is_built_in(self, driver, api):
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
@@ -103,7 +134,7 @@ class TestTheCallersValues:
d.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
assert _body(api, "/api/netsnmp/general/set")["general"]["listen"] == {}
assert _body(api, "/api/netsnmp/general/set")["general"]["listen"] == ""
def test_a_rejected_configuration_fails_the_fix(self, driver, api):
api.saved = "failed"
+36
View File
@@ -0,0 +1,36 @@
"""Where the SSH server's algorithm lists are set (NetOrk/netork#1769).
OPNsense writes sshd_config from config.xml (``<system><ssh>``), and no API
controller reads or writes that section: the lists are set on the legacy
Administration page. The driver therefore does not harden the SSH server; it
says, as data, where a person sets the lists by hand.
"""
from __future__ import annotations
from napalm_device_types.ssh_server import SSH_ALGORITHM_CLASSES
from napalm_opnsense import OPNsenseDriver
def test_the_page_that_sets_the_lists():
assert OPNsenseDriver.SSH_SETTINGS_MENU == (
"System",
"Settings",
"Administration",
"Secure Shell",
)
def test_a_field_for_every_algorithm_class():
assert OPNsenseDriver.SSH_SETTINGS_FIELDS == {
"kex": "Key exchange algorithms",
"cipher": "Ciphers",
"mac": "MACs",
"hostkey": "Host key algorithms",
}
assert set(OPNsenseDriver.SSH_SETTINGS_FIELDS) == set(SSH_ALGORITHM_CLASSES)
def test_the_driver_does_not_harden_the_ssh_server_itself():
assert not callable(getattr(OPNsenseDriver, "harden_ssh_server", None))
+251
View File
@@ -0,0 +1,251 @@
"""Time sync on OPNsense: the time servers and the zone of config.xml (NetOrk/netork#2363).
OPNsense keeps both in its configuration: ``<system><timeservers>``, space-separated
in the order of *Services -> Network Time -> General*, and ``<system><timezone>``, an
IANA name set on *System -> Settings -> General*. No API controller reads or writes
either, up to 26.7 and on ``master``: both pages are legacy PHP. So the driver reads
them from config.xml (``/api/core/backup/download/this``, as ``get_config`` does),
asks ntpd over ``/api/ntpd/service/status`` whether the clock follows a peer, and
writes nothing: ``time_sync_writes`` is empty and ``configure_time_sync`` is None.
``config_xml_sample.xml`` is OPNsense's own ``src/etc/config.xml.sample`` (core
``master``, 2026-11) without the default root user. ``ntpd_service_status.json`` is
the answer of ``/api/ntpd/service/status`` in its 26.7 shape: ``ntpq -pnw`` as rows,
the pool associations marked ``__pool``, the system peer ``*``.
"""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import MagicMock, patch
from xml.etree.ElementTree import ParseError
import pytest
import requests
from napalm_device_types import TimeSyncMixin
from napalm_opnsense.opnsense import OPNsenseDriver
FIXTURES = Path(__file__).parent / "fixtures"
CONFIG_XML = (FIXTURES / "config_xml_sample.xml").read_text()
NTPD_STATUS = json.loads((FIXTURES / "ntpd_service_status.json").read_text())
CONFIG_PATH = "/api/core/backup/download/this"
STATUS_PATH = "/api/ntpd/service/status"
POOLS = [f"{n}.opnsense.pool.ntp.org" for n in range(4)]
def _configured(servers: str | None = None, zone: str | None = None) -> str:
"""The sample config.xml with other time servers or another zone ("" = element empty,
None = as the sample has it)."""
xml = CONFIG_XML
if servers is not None:
xml = xml.replace(" ".join(POOLS), servers)
if zone is not None:
xml = xml.replace("<timezone>Etc/UTC</timezone>", f"<timezone>{zone}</timezone>")
return xml
def _without(element: str, xml: str = CONFIG_XML) -> str:
start = xml.index(f"<{element}>")
end = xml.index(f"</{element}>") + len(f"</{element}>")
return xml[:start] + xml[end:]
class Firewall:
"""Answers GETs as the firewall's API would; every request is recorded."""
def __init__(self, config=CONFIG_XML, status=NTPD_STATUS, status_error=None):
self.config = config
self.status = status
self.status_error = status_error
self.paths: list[str] = []
def get(self, url, timeout=None):
path = url.removeprefix("https://fw")
self.paths.append(path)
response = MagicMock()
response.raise_for_status.return_value = None
if path == CONFIG_PATH:
if isinstance(self.config, Exception):
response.raise_for_status.side_effect = self.config
response.text = self.config
response.json.side_effect = json.JSONDecodeError("Expecting value", "<", 0)
return response
if path == STATUS_PATH:
if self.status_error is not None:
response.raise_for_status.side_effect = self.status_error
response.json.return_value = self.status
return response
raise AssertionError(f"unexpected GET {path}")
@pytest.fixture
def driver():
with patch("napalm_opnsense.opnsense.requests.Session"):
drv = OPNsenseDriver(
hostname="fw", username="k", password="s", optional_args={"verify": False}
)
drv.session = MagicMock()
yield drv
def _on(driver, firewall: Firewall) -> Firewall:
driver.session.get.side_effect = firewall.get
return firewall
class TestGetTimeSync:
def test_the_servers_and_zone_of_config_xml(self, driver):
_on(driver, Firewall())
assert driver.get_time_sync() == {
"ntp_servers": POOLS,
"timezone": "Etc/UTC",
"synchronized": True,
"daemon": "ntpd",
}
def test_the_servers_in_the_order_the_firewall_keeps_them(self, driver):
_on(driver, Firewall(config=_configured("10.0.0.1 ptbtime1.ptb.de time.cloudflare.com")))
assert driver.get_time_sync()["ntp_servers"] == [
"10.0.0.1",
"ptbtime1.ptb.de",
"time.cloudflare.com",
]
def test_the_zone_by_its_iana_name(self, driver):
_on(driver, Firewall(config=_configured(zone="Europe/Berlin")))
assert driver.get_time_sync()["timezone"] == "Europe/Berlin"
@pytest.mark.parametrize(
"config", [_configured(zone=""), _without("timezone")], ids=["empty", "missing"]
)
def test_no_zone_is_the_utc_opnsense_runs_then(self, driver, config):
# system_timezone_configure() puts Etc/UTC in place for an empty or missing zone.
_on(driver, Firewall(config=config))
assert driver.get_time_sync()["timezone"] == "Etc/UTC"
@pytest.mark.parametrize(
"config", [_configured(servers=""), _without("timeservers")], ids=["empty", "missing"]
)
def test_no_servers_is_an_unsynchronised_clock_and_ntpd_is_not_asked(self, driver, config):
# Without <timeservers> OPNsense does not run ntpd (ntpd_enabled()).
firewall = _on(driver, Firewall(config=config))
sync = driver.get_time_sync()
assert sync["ntp_servers"] == []
assert sync["synchronized"] is False
assert STATUS_PATH not in firewall.paths
def test_a_configuration_without_a_system_section(self, driver):
_on(driver, Firewall(config=_without("system")))
sync = driver.get_time_sync()
assert (sync["ntp_servers"], sync["timezone"]) == ([], "Etc/UTC")
def test_no_system_peer_is_an_unsynchronised_clock(self, driver):
rows = [
dict(row, status="+" if row["status"] == "*" else row["status"])
for row in NTPD_STATUS["rows"]
]
_on(driver, Firewall(status={**NTPD_STATUS, "rows": rows}))
assert driver.get_time_sync()["synchronized"] is False
def test_ntpd_without_peers_yet_is_an_unsynchronised_clock(self, driver):
_on(driver, Firewall(status={"total": 0, "rowCount": 0, "current": 1, "rows": []}))
assert driver.get_time_sync()["synchronized"] is False
@pytest.mark.parametrize("status", [None, [], {"rows": "x"}], ids=["null", "list", "rows"])
def test_a_status_of_another_shape_is_unknown(self, driver, status):
_on(driver, Firewall(status=status))
assert driver.get_time_sync()["synchronized"] is None
def test_a_failed_status_read_is_unknown_and_keeps_the_rest(self, driver):
_on(driver, Firewall(status_error=requests.HTTPError("403 Forbidden")))
sync = driver.get_time_sync()
assert sync["synchronized"] is None
assert sync["ntp_servers"] == POOLS
assert sync["timezone"] == "Etc/UTC"
def test_a_failed_configuration_read_raises(self, driver):
# "No servers" would be a reading; a key without the backup privilege is none.
_on(driver, Firewall(config=requests.HTTPError("403 Forbidden")))
with pytest.raises(requests.HTTPError, match="403"):
driver.get_time_sync()
def test_a_configuration_that_is_no_xml_raises(self, driver):
_on(driver, Firewall(config="<html><body>Login</body>"))
with pytest.raises(ParseError):
driver.get_time_sync()
def test_a_reading_only_reads(self, driver):
firewall = _on(driver, Firewall())
driver.get_time_sync()
assert firewall.paths == [CONFIG_PATH, STATUS_PATH]
driver.session.post.assert_not_called()
class TestGetNtpServers:
def test_the_configured_servers_as_napalm_keys_them(self, driver):
_on(driver, Firewall())
servers = driver.get_ntp_servers()
assert servers == {name: {} for name in POOLS}
assert list(servers) == POOLS
def test_the_same_servers_as_get_time_sync(self, driver):
_on(driver, Firewall(config=_configured("10.0.0.1 ptbtime1.ptb.de")))
assert list(driver.get_ntp_servers()) == driver.get_time_sync()["ntp_servers"]
def test_only_the_configuration_is_read(self, driver):
firewall = _on(driver, Firewall())
driver.get_ntp_servers()
assert firewall.paths == [CONFIG_PATH]
def test_no_servers_configured(self, driver):
_on(driver, Firewall(config=_without("timeservers")))
assert driver.get_ntp_servers() == {}
def test_a_failed_read_raises_instead_of_reading_as_no_servers(self, driver):
_on(driver, Firewall(config=requests.HTTPError("403 Forbidden")))
with pytest.raises(requests.HTTPError):
driver.get_ntp_servers()
class TestWhatTheDriverOffers:
def test_it_reads_time_sync(self):
assert issubclass(OPNsenseDriver, TimeSyncMixin)
assert callable(getattr(OPNsenseDriver, "get_time_sync", None))
def test_it_writes_nothing(self):
# Both values are set on legacy pages; no API controller writes them.
assert OPNsenseDriver.time_sync_writes == frozenset()
assert getattr(OPNsenseDriver, "configure_time_sync", None) is None
def test_where_a_person_sets_the_servers(self):
assert OPNsenseDriver.TIME_SERVERS_MENU == ("Services", "Network Time", "General")
def test_where_a_person_sets_the_zone(self):
assert OPNsenseDriver.TIME_ZONE_MENU == ("System", "Settings", "General")
+16
View File
@@ -140,6 +140,22 @@ class TestRebootHost:
driver.reboot_host()
class TestShutdownHost:
"""``shutdown_host`` halts and powers the firewall off through its firmware API
(netOrk #2841)."""
def test_the_firmware_api_is_asked(self, driver):
with patch.object(driver, "_post", return_value={"status": "ok"}) as post:
driver.shutdown_host()
post.assert_called_once_with("/api/core/firmware/poweroff")
def test_a_refusal_is_raised_with_the_answer(self, driver):
with patch.object(driver, "_post", side_effect=ConnectionError("403 Forbidden")):
with pytest.raises(RuntimeError, match="refused to shut down: 403 Forbidden"):
driver.shutdown_host()
def test_no_warnings_of_its_own():
"""The pending updates are get_available_updates; the caller names
updates_available from them (netOrk #1111)."""
+106
View File
@@ -0,0 +1,106 @@
"""WireGuard peers in ``get_vpn_tunnels()`` keep their key when others come and go (#32).
The key was a running counter over the peer rows, so a peer added ahead of an
existing one renumbered every peer after it, and whatever a consumer stored per
key (netOrk's site link, its tunnel check) silently moved to another peer. A
peer is its interface and its public key, so that is what the key is made of.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from napalm_opnsense.opnsense import OPNsenseDriver
OFFICE = {
"if": "wg0",
"type": "peer",
"name": "office",
"public-key": "aBcD1234efGH5678ijKL9012mnOP3456qrST7890uvw=",
"endpoint": "198.51.100.7:51820",
"peer-status": "online",
"transfer-rx": 10,
"transfer-tx": 20,
"latest-handshake-age": 45,
}
LAPTOP = {
"if": "wg0",
"type": "peer",
"name": "laptop",
"public-key": "Zz9/+yXw8765vuTS4321rqPO0987nmLK6543jiHG210=",
"endpoint": "(none)",
"peer-status": "offline",
}
SERVER = {
"if": "wg1",
"type": "peer",
"name": "server",
"public-key": "QqQqWwWwEeEeRrRrTtTtYyYyUuUuIiIiOoOoPpPp123=",
"endpoint": "203.0.113.9:51821",
"peer-status": "online",
}
def _driver(*rows: dict) -> OPNsenseDriver:
with patch("napalm_opnsense.opnsense.requests.Session"):
drv = OPNsenseDriver(hostname="fw", username="k", password="s")
drv.session = MagicMock()
show = {"rows": [{"if": "wg0", "type": "interface"}, *rows]}
def get(path: str) -> dict:
if path == "/api/wireguard/service/show":
return show
raise RuntimeError("not installed") # IPsec and OpenVPN are not part of this
drv._get = get # type: ignore[method-assign]
return drv
def _by_name(tunnels: dict) -> dict[str, str]:
return {t["description"]: key for key, t in tunnels.items()}
class TestTheKey:
def test_is_the_interface_and_the_start_of_the_public_key(self):
assert list(_driver(OFFICE).get_vpn_tunnels()) == ["wireguard-wg0-aBcD1234"]
def test_survives_a_peer_added_ahead_of_it(self):
before = _by_name(_driver(OFFICE, SERVER).get_vpn_tunnels())
after = _by_name(_driver(OFFICE, LAPTOP, SERVER).get_vpn_tunnels())
assert after["server"] == before["server"]
assert after["office"] == before["office"]
def test_is_safe_in_a_url_path(self):
# The key is a path segment (PATCH /devices/{id}/vpn-tunnels/{key}), and
# a "/" from base64 would split it even when encoded.
key = _by_name(_driver(LAPTOP).get_vpn_tunnels())["laptop"]
assert key == "wireguard-wg0-Zz9_-yXw"
def test_two_peers_with_the_same_key_start_both_stay(self):
twin = {
**SERVER,
"if": "wg0",
"name": "twin",
"public-key": OFFICE["public-key"][:8] + "x=",
}
tunnels = _driver(OFFICE, twin).get_vpn_tunnels()
assert len(tunnels) == 2
def test_without_a_public_key_falls_back_to_the_position(self):
keyless = {k: v for k, v in OFFICE.items() if k != "public-key"}
assert list(_driver(keyless).get_vpn_tunnels()) == ["wireguard-1"]
class TestTheEntry:
def test_carries_the_peer_s_reading(self):
tunnel = _driver(OFFICE).get_vpn_tunnels()["wireguard-wg0-aBcD1234"]
assert tunnel == {
"type": "WireGuard",
"local_endpoint": "",
"remote_endpoint": "198.51.100.7",
"is_up": True,
"uptime": 45,
"bytes_in": 10,
"bytes_out": 20,
"description": "office",
}