Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0be871207 | ||
|
|
02336c20ed | ||
|
|
94279de382 | ||
|
|
2374d57b7d | ||
|
|
6c612a427b | ||
|
|
6c1aaf1690 | ||
|
|
9c31afd5d7 | ||
|
|
521f7c5d73 | ||
|
|
a65a3ed6e3 | ||
|
|
5a20023c54 | ||
|
|
9d7cb64dac | ||
|
|
6fdc3ff2c7 |
No files matched your search
@@ -6,6 +6,62 @@ 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
|
||||
|
||||
@@ -16,7 +16,7 @@ NAPALM community driver for **OPNsense** firewalls (read-only, via REST API).
|
||||
|---|---|
|
||||
| Python | 3.12 |
|
||||
| NAPALM | 4.0 |
|
||||
| napalm-device-types | 4.26.0 |
|
||||
| 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` |
|
||||
@@ -101,6 +107,8 @@ arguments.
|
||||
> ² 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
|
||||
|
||||
@@ -161,6 +169,95 @@ algorithm lists instead: `SSH_SETTINGS_MENU` is the page's menu path and
|
||||
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
|
||||
@@ -223,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
|
||||
|
||||
@@ -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
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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))
|
||||
+37
-73
@@ -62,6 +62,8 @@ 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,
|
||||
@@ -70,12 +72,14 @@ from napalm_opnsense.kea_reservations import (
|
||||
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.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
|
||||
|
||||
@@ -97,7 +101,19 @@ def _opnsense_version(versions: Any) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
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,
|
||||
@@ -113,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),
|
||||
]
|
||||
@@ -774,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.
|
||||
|
||||
@@ -1111,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.
|
||||
|
||||
@@ -1239,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", ""),
|
||||
@@ -1253,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]:
|
||||
@@ -1271,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]:
|
||||
@@ -1286,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]:
|
||||
@@ -1316,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]:
|
||||
@@ -2200,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.
|
||||
|
||||
|
||||
@@ -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}
|
||||
+1
-1
@@ -23,7 +23,7 @@ classifiers = [
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.27.0",
|
||||
"napalm-device-types>=4.50.0",
|
||||
"requests>=2.28.0",
|
||||
]
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
"napalm_opnsense.resolver_mixin"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_opnsense/opnsense.py": 3055
|
||||
"napalm_opnsense/opnsense.py": 3019
|
||||
},
|
||||
"untyped_public": [
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config"
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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"}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
+39
-40
@@ -798,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()
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1289,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
|
||||
@@ -1375,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
|
||||
|
||||
@@ -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()
|
||||
@@ -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")
|
||||
@@ -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)."""
|
||||
|
||||
Reference in new issue
Block a user