Compare commits
56
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6c3eb2604 | ||
|
|
688918cf31 | ||
|
|
7b35ade410 | ||
|
|
b50732c63c | ||
|
|
0289963af8 | ||
|
|
f75d1c8334 | ||
|
|
c4ff19ac20 | ||
|
|
80d6b8cb71 | ||
|
|
6ac7a6f6a2 | ||
|
|
96a4a139d0 | ||
|
|
0f730a4b9d | ||
|
|
901df1b523 | ||
|
|
91a17b54a8 | ||
|
|
ea0a52717e | ||
|
|
4fc7b2424e | ||
|
|
4e377923db | ||
|
|
e2cac52a12 | ||
|
|
0bb59b60a0 | ||
|
|
8bf76aa346 | ||
|
|
c02a745bb3 | ||
|
|
bb0810d693 | ||
|
|
0176656743 | ||
|
|
b49fd8f56d | ||
|
|
72b4806c65 | ||
|
|
9115628abe | ||
|
|
eaafa540e5 | ||
|
|
9f45952605 | ||
|
|
63ce6e78bd | ||
|
|
ae732fd7c8 | ||
|
|
6e0e206e06 | ||
|
|
8815c4a584 | ||
|
|
571d9abb5f | ||
|
|
692a584fd2 | ||
|
|
68dbd5891c | ||
|
|
5a6e573300 | ||
|
|
59796b3fa1 | ||
|
|
6a91f43fc3 | ||
|
|
fc4658f016 | ||
|
|
7183da24fb | ||
|
|
5ab33d67f3 | ||
|
|
39cc177bf2 | ||
|
|
c4edfc88e4 | ||
|
|
9fe6245940 | ||
|
|
e3ed0f1bdd | ||
|
|
055ec3da71 | ||
|
|
e334dc0058 | ||
|
|
5a1aa66db4 | ||
|
|
5b54174cc4 | ||
|
|
2af99995e9 | ||
|
|
c868d41322 | ||
|
|
00172f7a69 | ||
|
|
e318c97c20 | ||
|
|
852c1d59df | ||
|
|
fa88850535 | ||
|
|
2fb1226734 | ||
|
|
8ce7ea52e7 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
driver:
|
||||
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
|
||||
with:
|
||||
standard-ref: main
|
||||
secrets:
|
||||
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
||||
@@ -1,48 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
branches: ["**"]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.10", "3.11", "3.12"]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: pip
|
||||
|
||||
- name: Install package with dev extras
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
# napalm-device-types lives in git.netork.io/NAPALM, not on PyPI: without this
|
||||
# pip looks there, finds an unrelated 0.1.0 and the job dies before any test.
|
||||
python -m pip install "napalm-device-types @ git+https://git.netork.io/NAPALM/napalm-device-types.git"
|
||||
python -m pip install -e ".[dev]"
|
||||
|
||||
- name: Run unit tests
|
||||
run: |
|
||||
python -m pytest -q --tb=short
|
||||
|
||||
- name: Build wheel and sdist
|
||||
run: |
|
||||
python -m pip install build
|
||||
python -m build
|
||||
|
||||
- name: Upload dist artifacts
|
||||
# v4 refuses to run on Gitea ("not currently supported on GHES").
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: dist-${{ matrix.python-version }}
|
||||
path: dist/*
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this driver. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/), versions follow
|
||||
[Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.6.0] - 2026-11-07
|
||||
|
||||
### Added
|
||||
- Where the SSH server's algorithm lists are set (NetOrk/netork#1769):
|
||||
`SSH_SETTINGS_MENU` (*System → Settings → Administration → Secure Shell*) and
|
||||
`SSH_SETTINGS_FIELDS`, each list's field by its algorithm class. OPNsense writes
|
||||
sshd_config from config.xml and has no API for that section, so the driver does not
|
||||
harden the SSH server itself; an application tells a person what to set there.
|
||||
- Scheduled jobs (NetOrk/netork#1933, #43): `get_scheduled_jobs()` reads every cron job
|
||||
of config.xml over `/api/cron/settings/get`, with who owns it -- another component's
|
||||
job is `platform`, one written by `put_scheduled_job()` `application`, the rest
|
||||
`admin`. `manage_scheduled_job()` enables and disables any of them;
|
||||
`put_scheduled_job()` and `delete_scheduled_job()` write and remove an application's
|
||||
own, whose command is a configd action. `get_scheduled_job_commands()` lists the
|
||||
actions configd offers. Running a job now is refused: the API cannot run a configd
|
||||
action. Every write reads the job again first and refuses one that changed.
|
||||
|
||||
### Changed
|
||||
- Requires napalm-device-types 4.26.0, which declares the scheduled-jobs contract.
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
|
||||
3.12 venv no longer has.
|
||||
|
||||
### Fixed
|
||||
- `is_alive()` checks the host and port named in `base_url` (`https://fw:8443`) instead
|
||||
of always port 443 on the hostname, so a firewall whose API listens elsewhere no
|
||||
longer reads as dead (#15).
|
||||
- `sync_dns_zone()` and `get_dns_entries()` raise when the host overrides cannot be
|
||||
read. A transient API error used to read as "no overrides": the sync then deleted
|
||||
nothing and added every record a second time (#14).
|
||||
- `create_dhcp_reservation()` no longer takes over a Kea reservation another MAC
|
||||
holds for the address (made by hand, say): it raises `RuntimeError` and leaves it
|
||||
as it is. `delete_dhcp_reservation_and_lease()` removes only the reservation and
|
||||
lease of the given MAC and reports another host's reservation for the address in
|
||||
the new `reservation_other_mac` field (#26).
|
||||
- `configure_snmp_agent()` works on OPNsense 26.x again. The configure step sent
|
||||
fields the os-net-snmp model does not have (`contact`, `location`, `sysobjid`,
|
||||
`bindip`) and `listen` in the shape `get` returns rather than as a string, which
|
||||
26.x refuses with HTTP 500. It now sends `syscontact`/`syslocation`, and only when
|
||||
the caller gives them, so an operator's sysContact and sysLocation are no longer
|
||||
blanked (#36).
|
||||
- `get_arp_table()` and `get_ipv6_neighbors_table()` report an unknown age as `-1.0`
|
||||
(napalm-device-types' `ARP_AGE_UNKNOWN`). They reported `expires`, the seconds
|
||||
left until the entry expires, which is no age: an entry refreshed a second ago
|
||||
looked 20 minutes old (NetOrk/netork#1327).
|
||||
- `get_vpn_tunnels()` keys a WireGuard peer by its interface and the start of its
|
||||
public key (`wireguard-wg0-aBcD1234`, URL-safe) instead of its position, so a peer
|
||||
added ahead of another no longer renumbers it (#32). Every WireGuard key changes
|
||||
once with this release.
|
||||
- `get_dns_entries()` raises when the service list (`/api/core/service/search`)
|
||||
cannot be read, instead of returning an empty list as if neither Unbound nor
|
||||
Dnsmasq ran: a transient API error made the firewall look as if it had no DNS
|
||||
records. `sync_dns_zone()` raises that API error instead of "No active DNS
|
||||
service (Unbound or Dnsmasq) detected" (#39).
|
||||
- `create_dhcp_reservation()` raises `RuntimeError` naming `searchReservation` when
|
||||
the search for an existing reservation fails, and writes nothing. It used to add
|
||||
the reservation anyway: a retry then failed with "Kea rejected DHCP reservation"
|
||||
instead of the real error, or left two reservations for one address, which Kea
|
||||
refuses to load (#40).
|
||||
- The unit tests no longer reach the network: the test of a failed `open()` looked
|
||||
up a real host name and waited for the resolver, so it hung or behaved differently
|
||||
on a build host with a slow resolver or one that answers every name (#41).
|
||||
|
||||
## [0.5.0] - 2026-10-23
|
||||
|
||||
The first release on PyPI.
|
||||
|
||||
### Changed
|
||||
- The driver follows the NAPALM driver standard
|
||||
(https://git.netork.io/NAPALM/driver-standard): CI on Gitea runs ruff, mypy, the
|
||||
tests on Python 3.10–3.13 and at the lowest declared versions, bandit, pip-audit and
|
||||
a build check, and a release tag publishes to PyPI. The package now ships `py.typed`
|
||||
and a LICENSE file. Python 3.10 remains the floor. Requires napalm-device-types
|
||||
4.21.1.
|
||||
|
||||
### Fixed
|
||||
- `get_dhcp_leases()` raises when Kea, ISC DHCP and the ARP fallback all failed,
|
||||
instead of returning an empty list that looks like a server without leases (#27).
|
||||
- `create_dhcp_reservation()` leaves a reservation that already holds what was asked
|
||||
alone, and does not reconfigure (restart) Kea for it.
|
||||
|
||||
## [0.4.0] - 2026-10-18
|
||||
|
||||
### Added
|
||||
- napalm-device-types 4.17's public contracts: `apply_updates()` passes the packages it
|
||||
is given and `get_update_progress()` reports the upgrade's state and log;
|
||||
`get_dns_forwards()`, `set_dns_forward()` and `remove_dns_forward()` for Unbound;
|
||||
`get_ospf()`. Requires napalm-device-types 4.17.0.
|
||||
|
||||
## [0.3.0] - 2026-10-17
|
||||
|
||||
### Removed
|
||||
- **Breaking:** `get_device_warnings()`. The pending updates are in
|
||||
`get_available_updates()`.
|
||||
|
||||
## [0.2.0] - 2026-10-17
|
||||
|
||||
### Changed
|
||||
- **Breaking:** `run_device_action` is removed. The SNMP agent is set up through
|
||||
napalm-device-types 4.13's `configure_snmp_agent` with the caller's community,
|
||||
contact, location and listen address, and the firewall opens UDP/161 only to the
|
||||
allowed sources (#13).
|
||||
@@ -0,0 +1,191 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship made available under
|
||||
the License, as indicated by a copyright notice that is included in
|
||||
or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other transformations
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
||||
in the Work by the copyright owner or by an individual or Legal Entity
|
||||
authorized to submit on behalf of the copyright owner. For the purposes
|
||||
of this definition, "submitted" means any form of electronic, verbal,
|
||||
or written communication sent to the Licensor or its representatives,
|
||||
including but not limited to communication on electronic mailing lists,
|
||||
source code control systems, and issue tracking systems that are managed
|
||||
by, or on behalf of, the Licensor for the purpose of discussing and
|
||||
improving the Work, but excluding communication that is conspicuously
|
||||
marked or designated in writing by the copyright owner as "Not a
|
||||
Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
||||
whom a Contribution has been received by the Licensor and incorporated
|
||||
within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by the combined Contribution(s) and the Work
|
||||
to which such Contribution(s) was submitted. If You institute patent
|
||||
litigation against any entity (including a cross-claim or counterclaim
|
||||
in a lawsuit) alleging that the Work or any Contribution embodied
|
||||
within the Work constitutes direct or contributory patent infringement,
|
||||
then any patent licenses granted to You under this License for that
|
||||
Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative
|
||||
Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, You must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, in
|
||||
at least one of the following places: within a NOTICE text file
|
||||
distributed as part of the Derivative Works; within the Source
|
||||
form or documentation, if provided along with the Derivative
|
||||
Works; or, within a display generated by the Derivative Works,
|
||||
if and wherever such third-party notices normally appear. The
|
||||
contents of the NOTICE file are for informational purposes only
|
||||
and do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own license statement for Your modifications and
|
||||
may provide additional grant of rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of the Work,
|
||||
and to permit persons to whom the Work is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any conditions of TITLE,
|
||||
MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or exemplary damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (even if such Contributor has been advised of the possibility
|
||||
of such damages).
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may offer only
|
||||
conditions consistent with this License, subject to the following
|
||||
additional conditions:
|
||||
|
||||
(a) You may offer additional warranty, indemnity, or other liability
|
||||
terms and conditions; and
|
||||
|
||||
(b) You may offer support for the Work in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format in question. It may also be
|
||||
possible to make it available with a creative commons license.
|
||||
|
||||
Copyright 2026 Christian Manivong
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -14,8 +14,9 @@ NAPALM community driver for **OPNsense** firewalls (read-only, via REST API).
|
||||
|
||||
| Dependency | Minimum version |
|
||||
|---|---|
|
||||
| Python | 3.9 |
|
||||
| Python | 3.12 |
|
||||
| NAPALM | 4.0 |
|
||||
| napalm-device-types | 4.26.0 |
|
||||
| requests | 2.28 |
|
||||
|
||||
## Installation
|
||||
@@ -27,7 +28,7 @@ pip install napalm-opnsense
|
||||
Or from source:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/napalm-automation-community/napalm-opnsense
|
||||
git clone https://git.netork.io/NAPALM/napalm-opnsense
|
||||
cd napalm-opnsense
|
||||
pip install -e .
|
||||
```
|
||||
@@ -57,7 +58,7 @@ API keys**.
|
||||
Pass the credentials via `optional_args`:
|
||||
|
||||
```python
|
||||
optional_args={
|
||||
optional_args = {
|
||||
"api_key": "your-api-key",
|
||||
"api_secret": "your-api-secret",
|
||||
"verify": False, # set to a CA bundle path or True in production
|
||||
@@ -71,9 +72,9 @@ arguments.
|
||||
|
||||
| Getter | Status | OPNsense API Endpoint |
|
||||
|---|---|---|
|
||||
| `get_facts` | ✅ | `GET /api/core/system/status` |
|
||||
| `get_facts` | ✅ | `GET /api/diagnostics/system/system_information` (name, version) + `GET /api/core/system/status` (fallback on older versions) |
|
||||
| `get_interfaces` | ✅ | `GET /api/interfaces/overview/export` |
|
||||
| `get_interfaces_ip` | ✅ | `GET /api/interfaces/addresses/export` |
|
||||
| `get_interfaces_ip` | ✅ | `GET /api/interfaces/overview/export`; a CARP address only on the node that is MASTER for it |
|
||||
| `get_interfaces_counters` | ✅ | `GET /api/diagnostics/interface/get_interface_statistics` |
|
||||
| `get_arp_table` | ✅ | `GET /api/diagnostics/interface/get_arp` |
|
||||
| `get_ipv6_neighbors_table` | ✅ | `GET /api/diagnostics/interface/get_ndp` |
|
||||
@@ -88,11 +89,18 @@ arguments.
|
||||
| `get_vlans` | ✅ | `GET /api/interfaces/vlan_settings/search_item` |
|
||||
| `get_mac_address_table` | ❌ | Not applicable (firewall, no L2 switching) |
|
||||
| `ping` | ✅ | `POST /api/diagnostics/ping/set` + `start` + `search_jobs` + `stop`/`remove` |
|
||||
| `get_listening_sockets` | ✅ | `GET /api/diagnostics/interface/get_socket_statistics` + `/api/core/service/search` + `/api/wireguard/service/show` (WireGuard's kernel sockets by listen port) |
|
||||
| `get_virtual_ips` | ✅ | `GET /api/interfaces/overview/export`: every address bound to a CARP VHID (CARP address and IP aliases on it), with this node's CARP state. `interfaces/vip_settings` is not read: it carries the CARP passwords |
|
||||
| `ping_sweep` | ✅ ³ | same endpoints, one batch of parallel jobs at a time |
|
||||
| `get_scheduled_jobs()` | ✅ ⁴ | `GET /api/cron/settings/get`: every cron job of config.xml |
|
||||
| `manage_scheduled_job(key, action, digest=)` | ✅ ⁴ | enable, disable: `POST /api/cron/settings/toggle_job/<uuid>/1` (or `/0`) + `/api/cron/service/reconfigure`; run now is refused |
|
||||
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | ✅ ⁴ | an application's own job: `add_job`, `set_job/<uuid>`, `del_job/<uuid>` + `reconfigure` |
|
||||
| `get_scheduled_job_commands()` | ✅ ⁴ | `GET /api/cron/settings/get_job`: the configd actions a job can run |
|
||||
|
||||
> ¹ Requires the `os-lldpd` plugin. Returns empty dict if the plugin is not installed.
|
||||
> ² Requires the `os-frr` (FRR/Quagga) plugin. Returns empty dict if the plugin is not installed or FRR is not running.
|
||||
> ³ Overrides the generic per-host loop from `napalm-device-types`.
|
||||
> ⁴ See [Scheduled jobs](#scheduled-jobs).
|
||||
|
||||
### Ping
|
||||
|
||||
@@ -117,6 +125,42 @@ statistics line lands in the log slightly after the request that triggered it.
|
||||
`ttl` and `vrf` are accepted for NAPALM compatibility and ignored — the API
|
||||
has no equivalent.
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
OPNsense keeps its cron jobs in config.xml (System → Settings → Cron), and each
|
||||
runs a **configd action**, not a shell line. `key` is `opnsense:<uuid>`, `kind`
|
||||
`cron`, `source` `config.xml`, `run_as` `root`. A job another component
|
||||
registered (its origin is not `cron`, such as the intrusion detection's rule
|
||||
update) is `platform`; one whose description starts with
|
||||
`napalm-scheduled-job: <name>` was written by `put_scheduled_job` and is the only
|
||||
kind that can be edited or deleted; every other job is `admin`. Every job can be
|
||||
enabled and disabled.
|
||||
|
||||
`put_scheduled_job` takes a configd action as `command`, with its parameters as
|
||||
the words after it: the actions are what `get_scheduled_job_commands()` lists,
|
||||
anything else is refused (`ScheduledJobRefused`), and so is `@reboot` and a
|
||||
parameter with blanks, quotes or backslashes, which OPNsense releases before and
|
||||
after 26.7 would split differently. The schedule is written as its five fields,
|
||||
month and weekday names as numbers.
|
||||
|
||||
Not covered: the API cannot run a configd action now, so no job takes `run`;
|
||||
what OPNsense writes into the crontab beyond config.xml (`periodic`, the
|
||||
plugins' system jobs) cannot be read over the API; the time zone is not read
|
||||
(`None`).
|
||||
|
||||
### SSH server settings
|
||||
|
||||
OPNsense writes sshd_config from config.xml (`<system><ssh>`: `kex`, `ciphers`,
|
||||
`macs`, `keys`, `keysig`), set on the legacy page *System → Settings →
|
||||
Administration → Secure Shell* (`system_advanced_admin.php`). No API controller
|
||||
reads or writes that section, up to OPNsense 26.7 and on `master`, so the driver
|
||||
does not offer `harden_ssh_server`. It says, as data, where a person sets the
|
||||
algorithm lists instead: `SSH_SETTINGS_MENU` is the page's menu path and
|
||||
`SSH_SETTINGS_FIELDS` names each list's field by its algorithm class
|
||||
(napalm-device-types' `SSH_ALGORITHM_CLASSES`). A field left empty means
|
||||
OpenSSH's defaults. In an HA pair the configuration sync carries the section to
|
||||
the backup when its "OpenSSH" item (`ssh`) is ticked.
|
||||
|
||||
## Config management
|
||||
|
||||
OPNsense does not expose a single generic "push config" endpoint. Config is
|
||||
@@ -171,9 +215,9 @@ d.open()
|
||||
routes = json.dumps([{"network": "10.0.0.0/8", "gateway": "WAN_GW"}])
|
||||
d.load_merge_candidate(config=routes)
|
||||
|
||||
print(d.compare_config()) # unified diff
|
||||
d.commit_config() # applies routes and calls reconfigure
|
||||
d.rollback() # removes the routes just added
|
||||
print(d.compare_config()) # unified diff
|
||||
d.commit_config() # applies routes and calls reconfigure
|
||||
d.rollback() # removes the routes just added
|
||||
d.close()
|
||||
```
|
||||
|
||||
@@ -199,19 +243,18 @@ d.close()
|
||||
|
||||
## Development
|
||||
|
||||
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
|
||||
|
||||
```bash
|
||||
pip install -e ".[dev]"
|
||||
pytest tests/
|
||||
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
||||
.venv/bin/pytest --cov
|
||||
```
|
||||
|
||||
## CI
|
||||
|
||||
This project includes a GitHub Actions workflow that:
|
||||
- Runs unit tests across Python 3.9–3.12
|
||||
- Builds sdist and wheel
|
||||
- Uploads build artifacts
|
||||
|
||||
See [.github/workflows/ci.yml](.github/workflows/ci.yml).
|
||||
[.gitea/workflows/ci.yml](.gitea/workflows/ci.yml) calls the shared workflow of the
|
||||
driver standard: ruff, mypy, the tests on Python 3.12 and 3.13 and at the lowest declared
|
||||
versions, bandit, pip-audit and a build check. A release tag publishes to PyPI.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Where the OPNsense REST API listens, read from the driver's ``base_url``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
#: The port the API listens on when ``base_url`` names none, per scheme.
|
||||
DEFAULT_PORTS = {"https": 443, "http": 80}
|
||||
#: Seconds the driver's reachability probe waits for the API port to accept.
|
||||
ALIVE_TIMEOUT = 5
|
||||
|
||||
|
||||
def api_endpoint(base_url: str, fallback_host: str) -> tuple[str, int]:
|
||||
"""``https://fw:8443`` -> ``("fw", 8443)``: the host and port of the REST API.
|
||||
|
||||
Without a port the scheme's default applies; without a host, *fallback_host*.
|
||||
"""
|
||||
parts = urlsplit(base_url)
|
||||
port = parts.port or DEFAULT_PORTS.get(parts.scheme.lower(), DEFAULT_PORTS["https"])
|
||||
return parts.hostname or fallback_host, port
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Kea's HA peers and the firewall's configuration sync, as facts (netOrk #1125).
|
||||
|
||||
Two answers of the OPNsense API, read as they are:
|
||||
|
||||
* ``/api/kea/dhcpv4/get`` (its ``ha`` section) and ``/api/kea/dhcpv4/searchPeer``:
|
||||
whether Kea's HA hook is on, which peer this firewall is, and each peer's name,
|
||||
role and HA listener URL. Configuration, not state -- Kea's control agent, which
|
||||
knows whether the pair is in hot standby right now, listens on localhost only.
|
||||
* ``/api/core/hasync/get``: the address this firewall pushes its configuration
|
||||
to (``synchronizetoip``) and the ticked sync items. An item is named by
|
||||
OPNsense's sync section, not by the service it covers; :data:`SYNC_ITEM_SERVICES`
|
||||
maps the ones that are a service to the name ``get_services`` reports.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.models import ConfigSyncDict, DhcpHaDict, DhcpHaPeerDict
|
||||
|
||||
#: Kea's DHCPv4 server as ``get_services`` names it.
|
||||
KEA_SERVICE = "kea-dhcp"
|
||||
|
||||
#: Sync item -> the service it carries the configuration of, by the name
|
||||
#: ``get_services`` reports. Items that are configuration only (aliases, rules,
|
||||
#: NAT, users ...) have no service and are reported as unmapped.
|
||||
SYNC_ITEM_SERVICES: dict[str, str] = {
|
||||
"captiveportal": "captiveportal",
|
||||
"cron": "cron",
|
||||
"ddclient": "ddclient",
|
||||
"dnsforwarder": "dnsmasq",
|
||||
"dnsresolver": "unbound",
|
||||
"hostwatch": "hostwatch",
|
||||
"kea": KEA_SERVICE,
|
||||
"mdns-repeater": "mdns-repeater",
|
||||
"netsnmp": "snmpd",
|
||||
"ntpd": "ntpd",
|
||||
"qemuguestagent": "qemu-ga",
|
||||
"quagga": "frr",
|
||||
"radvd": "radvd",
|
||||
"squid": "squid",
|
||||
"ssh": "openssh",
|
||||
"sysctl": "sysctl",
|
||||
"syslog-ng": "syslog-ng",
|
||||
"webgui": "webgui",
|
||||
"wireguard": "wireguard",
|
||||
"zabbixagent": "zabbix_agentd",
|
||||
}
|
||||
|
||||
|
||||
def _section(answer: Any, *path: str) -> dict:
|
||||
node = answer
|
||||
for key in path:
|
||||
if not isinstance(node, dict) or not isinstance(node.get(key), dict):
|
||||
raise ValueError(f"unexpected answer: no {'.'.join(path)}")
|
||||
node = node[key]
|
||||
return node
|
||||
|
||||
|
||||
def dhcp_ha(settings: Any, peers: Any) -> DhcpHaDict:
|
||||
"""Kea's HA configuration from the two answers.
|
||||
|
||||
``this_server_name`` is empty while left at its default, the hostname; the
|
||||
effective name is then in its ``%`` twin.
|
||||
|
||||
:raises ValueError: when *settings* has no ``dhcpv4.ha`` section.
|
||||
"""
|
||||
ha = _section(settings, "dhcpv4", "ha")
|
||||
result: DhcpHaDict = {
|
||||
"service": KEA_SERVICE,
|
||||
"enabled": str(ha.get("enabled", "0")) == "1",
|
||||
"peers": [],
|
||||
}
|
||||
this_server = str(ha.get("this_server_name") or ha.get("%this_server_name") or "").strip()
|
||||
if this_server:
|
||||
result["this_server"] = this_server
|
||||
rows = peers.get("rows") if isinstance(peers, dict) else None
|
||||
for row in rows or []:
|
||||
if not isinstance(row, dict) or not row.get("name"):
|
||||
continue
|
||||
peer: DhcpHaPeerDict = {"name": str(row["name"]), "role": str(row.get("role") or "")}
|
||||
if row.get("url"):
|
||||
peer["url"] = str(row["url"])
|
||||
result["peers"].append(peer)
|
||||
return result
|
||||
|
||||
|
||||
def config_sync(answer: Any) -> ConfigSyncDict:
|
||||
"""Where this firewall pushes its configuration, and which services' it pushes.
|
||||
|
||||
Ticked items without a target address push nothing, so they count for nothing.
|
||||
|
||||
:raises ValueError: when *answer* has no ``hasync`` section.
|
||||
"""
|
||||
section = _section(answer, "hasync")
|
||||
peer = str(section.get("synchronizetoip") or "").strip() or None
|
||||
if peer is None:
|
||||
return {"peer": None, "services": [], "unmapped": []}
|
||||
items = section.get("syncitems")
|
||||
ticked = sorted(
|
||||
name
|
||||
for name, item in (items.items() if isinstance(items, dict) else [])
|
||||
if isinstance(item, dict) and str(item.get("selected", "0")) == "1"
|
||||
)
|
||||
return {
|
||||
"peer": peer,
|
||||
"services": sorted({SYNC_ITEM_SERVICES[i] for i in ticked if i in SYNC_ITEM_SERVICES}),
|
||||
"unmapped": [i for i in ticked if i not in SYNC_ITEM_SERVICES],
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Which Kea DHCPv4 reservation or lease is whose, read from the os-kea API rows.
|
||||
|
||||
A reservation is the pair of an address and a MAC. Matching on the address alone
|
||||
takes over or removes another host's reservation once an address was reused or
|
||||
edited by hand (#26), so every lookup here checks both.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ipaddress import ip_address, ip_network
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.dhcp import normalize_mac
|
||||
|
||||
#: Where a ``leases4/search`` row keeps the client's MAC: os-kea, then plain Kea.
|
||||
_LEASE_MAC_FIELDS = ("hwaddr", "hw-address")
|
||||
|
||||
|
||||
def _mac_of(row: dict[str, Any], *fields: str) -> str:
|
||||
return normalize_mac(next((str(row[f]) for f in fields if row.get(f)), ""))
|
||||
|
||||
|
||||
def subnet_containing(rows: list[dict[str, Any]], ip: str) -> dict[str, Any] | None:
|
||||
"""The first ``searchSubnet`` row whose subnet holds *ip*; None when none does.
|
||||
|
||||
A row without a readable ``subnet`` is skipped.
|
||||
"""
|
||||
address = ip_address(ip)
|
||||
for row in rows:
|
||||
try:
|
||||
if address in ip_network(str(row["subnet"]).strip(), strict=False):
|
||||
return row
|
||||
except (ValueError, KeyError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def split_by_mac(rows: list[dict[str, Any]], mac: str) -> tuple[dict[str, Any] | None, str]:
|
||||
"""``(the row *mac* holds, the MAC of a row another host holds)`` among *rows*.
|
||||
|
||||
*rows* are ``searchReservation`` rows for one address; either part is
|
||||
``None`` or ``""`` when there is none.
|
||||
"""
|
||||
wanted = normalize_mac(mac)
|
||||
own = next((row for row in rows if _mac_of(row, "hw_address") == wanted), None)
|
||||
others = [_mac_of(row, "hw_address") for row in rows]
|
||||
return own, next((m for m in others if m and m != wanted), "")
|
||||
|
||||
|
||||
def lease_held(rows: list[dict[str, Any]], ip: str, mac: str) -> bool:
|
||||
"""Whether a ``leases4/search`` row gives *ip* to *mac*."""
|
||||
return any(
|
||||
(row.get("address") or row.get("ip-address")) == ip
|
||||
and _mac_of(row, *_LEASE_MAC_FIELDS) == normalize_mac(mac)
|
||||
for row in rows
|
||||
)
|
||||
|
||||
|
||||
def reservation_unchanged(row: dict[str, Any], wanted: dict[str, Any], subnet_cidr: str) -> bool:
|
||||
"""Whether a ``searchReservation`` row already holds every field we would write.
|
||||
|
||||
The MAC is compared normalised: Kea keeps it as it was entered, in
|
||||
either case and with ``:`` or ``-``. The subnet is a model relation that
|
||||
comes back as the subnet's CIDR or its UUID depending on the OPNsense
|
||||
version, so either counts. A field the row does not carry counts as a
|
||||
difference -- writing once too often is the safe side.
|
||||
"""
|
||||
if str(row.get("subnet") or "").strip() not in {wanted["subnet"], subnet_cidr}:
|
||||
return False
|
||||
if normalize_mac(row.get("hw_address")) != normalize_mac(wanted["hw_address"]):
|
||||
return False
|
||||
return all(
|
||||
str(row.get(field) or "") == str(wanted[field] or "")
|
||||
for field in ("ip_address", "hostname", "description")
|
||||
)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""What listens on the firewall, and which OPNsense service it is. Pure: no I/O.
|
||||
|
||||
``/api/diagnostics/interface/get_socket_statistics`` is netstat's socket list
|
||||
with sockstat's user, command and PID merged in, read by configd as root. The
|
||||
contract this serves -- ``napalm_device_types.models.ListeningSocketsDict`` --
|
||||
wants the sockets that listen: a TCP socket in LISTEN and a bound UDP socket,
|
||||
both without a peer (``*:*``).
|
||||
|
||||
**Which service.** netOrk keeps a firewall's services under the names of its
|
||||
service list (``/api/core/service/search``), so a socket's ``unit`` is one of
|
||||
those names, or None. The statistics name the process, cut to ten characters
|
||||
by FreeBSD (``mdns-repea``): a name the service list has wins, then one the
|
||||
command starts with or -- cut short -- is the start of, then the few daemons
|
||||
whose service is called otherwise (``sshd`` is ``openssh``, ``ospfd`` is
|
||||
``frr``). The admin UI and the captive portal are both lighttpd; the portal's
|
||||
runs as ``www``.
|
||||
|
||||
**WireGuard has no process.** Its sockets belong to the kernel (``??``) and are
|
||||
told by the listen ports of the WireGuard interfaces.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.models import ListeningSocketDict
|
||||
|
||||
#: FRR's daemons, all under the one service ``frr``.
|
||||
_FRR_DAEMONS = "zebra mgmtd staticd ospfd ospf6d bgpd bfdd ripd ripngd isisd pimd watchfrr".split()
|
||||
#: Daemons whose OPNsense service has another name, by the command as reported.
|
||||
_SERVICE_OF: dict[str, str] = {
|
||||
"sshd": "openssh",
|
||||
"kea-ctrl-a": "kea-dhcp",
|
||||
"kea-ctrl-agent": "kea-dhcp",
|
||||
"charon": "strongswan",
|
||||
**{daemon: "frr" for daemon in _FRR_DAEMONS},
|
||||
}
|
||||
#: FreeBSD cuts a command at this many characters in the socket list.
|
||||
_COMMAND_LENGTH = 10
|
||||
#: Below this length a service name is too short to match a command's start (``pf``).
|
||||
_PREFIX_MIN = 4
|
||||
_NOBODY = "??"
|
||||
_PEERLESS = "*"
|
||||
|
||||
|
||||
def _service_of(command: str, user: str, services: set[str]) -> str | None:
|
||||
if command == "lighttpd":
|
||||
name = "captiveportal" if user == "www" else "webgui"
|
||||
return name if name in services else None
|
||||
if command in services:
|
||||
return command
|
||||
alias = _SERVICE_OF.get(command)
|
||||
if alias in services:
|
||||
return alias
|
||||
matches = [
|
||||
name
|
||||
for name in services
|
||||
if (len(name) >= _PREFIX_MIN and command.startswith(name))
|
||||
or (len(command) == _COMMAND_LENGTH and name.startswith(command))
|
||||
]
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
|
||||
|
||||
def _address(protocol: str, address: str) -> tuple:
|
||||
"""``(address, interface)``: ``*`` is every address of the socket's family."""
|
||||
if address == "*":
|
||||
# A reported wildcard address (data from sockstat), not a bind.
|
||||
return ("::" if protocol.endswith("6") else "0.0.0.0"), None # nosec B104
|
||||
host, _, zone = address.partition("%")
|
||||
return host, zone or None
|
||||
|
||||
|
||||
def _socket(
|
||||
entry: dict[str, Any], services: set[str], wireguard_ports: set[int]
|
||||
) -> ListeningSocketDict | None:
|
||||
protocol = str(entry.get("protocol") or "")
|
||||
proto = protocol[:3]
|
||||
local, remote = entry.get("local") or {}, entry.get("remote") or {}
|
||||
port = str(local.get("port") or "")
|
||||
if proto not in ("tcp", "udp") or not port.isdigit():
|
||||
return None
|
||||
if remote.get("address") != _PEERLESS or remote.get("port") != _PEERLESS:
|
||||
return None
|
||||
command, pid = str(entry.get("command") or _NOBODY), str(entry.get("pid") or _NOBODY)
|
||||
process = None if command == _NOBODY else command
|
||||
if process is not None:
|
||||
unit = _service_of(process, str(entry.get("user") or ""), services)
|
||||
elif proto == "udp" and int(port) in wireguard_ports and "wireguard" in services:
|
||||
unit = "wireguard"
|
||||
else:
|
||||
unit = None
|
||||
address, interface = _address(protocol, str(local.get("address") or ""))
|
||||
return {
|
||||
"proto": proto,
|
||||
"address": address,
|
||||
"port": int(port),
|
||||
"interface": interface,
|
||||
"process": process,
|
||||
"pid": int(pid) if pid.isdigit() else None,
|
||||
"unit": unit,
|
||||
"container_id": None,
|
||||
}
|
||||
|
||||
|
||||
def wireguard_listen_ports(show: dict[str, Any]) -> set[int]:
|
||||
"""The listen ports of the WireGuard interfaces in ``/api/wireguard/service/show``."""
|
||||
ports: set[int] = set()
|
||||
for row in show.get("rows") or []:
|
||||
port = str(row.get("listen-port") or "")
|
||||
if row.get("type") == "interface" and port.isdigit():
|
||||
ports.add(int(port))
|
||||
return ports
|
||||
|
||||
|
||||
def parse_socket_statistics(
|
||||
statistics: dict[str, Any], services: Iterable[str], wireguard_ports: set[int]
|
||||
) -> list[ListeningSocketDict]:
|
||||
"""The listening sockets of ``get_socket_statistics``, sorted by protocol,
|
||||
port and address. Every section is read: the UNIX sockets have no ``local``."""
|
||||
names = set(services)
|
||||
sockets: list[ListeningSocketDict] = []
|
||||
for section in (statistics.get("statistics") or {}).values():
|
||||
for entry in (section or {}).values() if isinstance(section, dict) else ():
|
||||
socket = _socket(entry, names, wireguard_ports) if isinstance(entry, dict) else None
|
||||
if socket is not None:
|
||||
sockets.append(socket)
|
||||
return sorted(
|
||||
sockets, key=lambda s: (s["proto"], s["port"], s["address"], s["interface"] or "")
|
||||
)
|
||||
+653
-531
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,43 @@
|
||||
"""FRR's OSPF state in neutral terms (napalm-device-types ``OspfMixin``).
|
||||
|
||||
Reads the os-frr plugin's diagnostics (``/api/quagga/diagnostics/...``); the
|
||||
field names are FRR's. Whether an interface without neighbours or without
|
||||
authentication is a problem is the caller's to decide.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import OspfMixin
|
||||
|
||||
_DIAG = "/api/quagga/diagnostics"
|
||||
|
||||
|
||||
def _interface(ifc: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"address": ifc.get("ipAddress") or "",
|
||||
"prefix_length": int(ifc.get("ipAddressPrefixlen") or 0),
|
||||
"area": ifc.get("area") or "",
|
||||
"network_type": ifc.get("networkType") or "",
|
||||
"authentication": ifc.get("authentication") or "",
|
||||
"neighbors": int(ifc.get("nbrCount") or 0),
|
||||
"neighbors_adjacent": int(ifc.get("nbrAdjacentCount") or 0),
|
||||
"cost": int(ifc.get("cost") or 0),
|
||||
}
|
||||
|
||||
|
||||
class OPNsenseOspfMixin(OspfMixin):
|
||||
"""Needs the driver's ``_get``."""
|
||||
|
||||
def get_ospf(self) -> dict[str, Any]:
|
||||
"""Router ID, areas and OSPF per interface; empty when OSPF does not run."""
|
||||
overview = self._get(f"{_DIAG}/ospfoverview").get("response") or {} # type: ignore[attr-defined]
|
||||
interfaces = (self._get(f"{_DIAG}/ospfinterface").get("response") or {}).get(
|
||||
"interfaces"
|
||||
) or {} # type: ignore[attr-defined]
|
||||
return {
|
||||
"router_id": overview.get("routerId") or None,
|
||||
"areas": list((overview.get("areas") or {}).keys()),
|
||||
"interfaces": {name: _interface(ifc) for name, ifc in interfaces.items()},
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
@@ -45,8 +44,9 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Callable, Iterable
|
||||
from ipaddress import ip_address
|
||||
from typing import Any, Callable, Iterable, Optional
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -78,7 +78,7 @@ class OPNsensePingMixin:
|
||||
PING_SWEEP_MAX_TARGETS: int = 512
|
||||
|
||||
# Provided by the driver this mixin is mixed into.
|
||||
_ping_model_path_cache: Optional[tuple[str, ...]] = None
|
||||
_ping_model_path_cache: tuple[str, ...] | None = None
|
||||
|
||||
# ── NAPALM ───────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -119,9 +119,9 @@ class OPNsensePingMixin:
|
||||
*,
|
||||
count: int = 1,
|
||||
timeout: int = 1,
|
||||
max_targets: Optional[int] = None,
|
||||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||||
should_stop: Optional[Callable[[], bool]] = None,
|
||||
max_targets: int | None = None,
|
||||
on_progress: Callable[[int, int], None] | None = None,
|
||||
should_stop: Callable[[], bool] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Ping many destinations, one batch of parallel firewall jobs at a time.
|
||||
|
||||
@@ -245,9 +245,7 @@ class OPNsensePingMixin:
|
||||
if attempt:
|
||||
time.sleep(_POLL_INTERVAL)
|
||||
rows = {
|
||||
job_id: row
|
||||
for job_id, row in self._read_ping_jobs().items()
|
||||
if job_id in wanted
|
||||
job_id: row for job_id, row in self._read_ping_jobs().items() if job_id in wanted
|
||||
}
|
||||
if wanted and all(
|
||||
_as_int(rows.get(job_id, {}).get("send")) >= count for job_id in wanted
|
||||
@@ -325,7 +323,7 @@ class OPNsensePingMixin:
|
||||
|
||||
@staticmethod
|
||||
def _row_to_napalm_reply(
|
||||
destination: str, row: Optional[dict[str, Any]], *, count: int
|
||||
destination: str, row: dict[str, Any] | None, *, count: int
|
||||
) -> dict[str, Any]:
|
||||
"""Turn one ``search_jobs`` row into NAPALM's ping reply shape.
|
||||
|
||||
|
||||
@@ -18,11 +18,12 @@ from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
#: Port names OPNsense accepts in a rule. ``socket.getservbyname`` knows them
|
||||
#: too, but only where ``/etc/services`` exists -- a slim container has none.
|
||||
WELL_KNOWN_PORTS: Dict[str, int] = {
|
||||
WELL_KNOWN_PORTS: dict[str, int] = {
|
||||
"ftp": 21,
|
||||
"ssh": 22,
|
||||
"telnet": 23,
|
||||
@@ -49,7 +50,7 @@ WELL_KNOWN_PORTS: Dict[str, int] = {
|
||||
#: Alias types whose entries can be addresses.
|
||||
_ADDRESS_ALIASES = ("host", "network")
|
||||
|
||||
AliasIndex = Dict[str, Tuple[str, List[str]]]
|
||||
AliasIndex = dict[str, tuple[str, list[str]]]
|
||||
|
||||
|
||||
def wan_interfaces(overview: Any) -> set:
|
||||
@@ -61,20 +62,23 @@ def wan_interfaces(overview: Any) -> set:
|
||||
def alias_index(rows: Iterable[dict]) -> AliasIndex:
|
||||
"""``name -> (type, entries)`` from the alias list."""
|
||||
return {
|
||||
r["name"]: (r.get("type", ""), [e.strip() for e in str(r.get("content", "")).splitlines() if e.strip()])
|
||||
r["name"]: (
|
||||
r.get("type", ""),
|
||||
[e.strip() for e in str(r.get("content", "")).splitlines() if e.strip()],
|
||||
)
|
||||
for r in rows
|
||||
if r.get("name")
|
||||
}
|
||||
|
||||
|
||||
def _as_address(value: str) -> Optional[str]:
|
||||
def _as_address(value: str) -> str | None:
|
||||
try:
|
||||
return str(ipaddress.ip_address(value))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _addresses(target: str, aliases: AliasIndex) -> List[str]:
|
||||
def _addresses(target: str, aliases: AliasIndex) -> list[str]:
|
||||
"""The addresses a rule sends to: a literal, or a host/network alias's.
|
||||
|
||||
Anything else -- an interface address, a name resolved by DNS -- gives no
|
||||
@@ -89,7 +93,7 @@ def _addresses(target: str, aliases: AliasIndex) -> List[str]:
|
||||
return [a for a in (_as_address(e) for e in entries) if a]
|
||||
|
||||
|
||||
def _port(value: Any, protocol: str, aliases: AliasIndex) -> Optional[int]:
|
||||
def _port(value: Any, protocol: str, aliases: AliasIndex) -> int | None:
|
||||
"""A rule's port as a number: literal, start of a range, alias or name.
|
||||
|
||||
No port at all means every port, which the contract writes as 0.
|
||||
@@ -115,7 +119,7 @@ def _faces_the_wan(rule: dict, wan: set) -> bool:
|
||||
return bool(set(str(rule.get("interface", "")).split(",")) & wan)
|
||||
|
||||
|
||||
def _remote_host(rule: dict) -> Optional[str]:
|
||||
def _remote_host(rule: dict) -> str | None:
|
||||
"""A source restriction; an inverted one ("all but X") restricts nothing."""
|
||||
source = str(rule.get("source.network") or "").strip()
|
||||
if source in ("", "any") or rule.get("source.not") == "1":
|
||||
@@ -123,11 +127,11 @@ def _remote_host(rule: dict) -> Optional[str]:
|
||||
return source
|
||||
|
||||
|
||||
def _forwards_of(rule: dict, aliases: AliasIndex) -> List[dict]:
|
||||
def _forwards_of(rule: dict, aliases: AliasIndex) -> list[dict]:
|
||||
protocols = [p.upper() for p in str(rule.get("protocol") or "any").split("/") if p]
|
||||
target = str(rule.get("target", "")).strip()
|
||||
remote = _remote_host(rule)
|
||||
result: List[dict] = []
|
||||
result: list[dict] = []
|
||||
for protocol in protocols:
|
||||
external = _port(rule.get("destination.port", ""), protocol.lower(), aliases)
|
||||
if external is None:
|
||||
@@ -150,9 +154,9 @@ def _forwards_of(rule: dict, aliases: AliasIndex) -> List[dict]:
|
||||
return result
|
||||
|
||||
|
||||
def port_forwards(rules: Iterable[dict], wan: set, aliases: AliasIndex) -> List[dict]:
|
||||
def port_forwards(rules: Iterable[dict], wan: set, aliases: AliasIndex) -> list[dict]:
|
||||
"""The destination-NAT rules on a WAN interface, as ``PortForwardDict`` entries."""
|
||||
result: List[dict] = []
|
||||
result: list[dict] = []
|
||||
for rule in rules:
|
||||
if _faces_the_wan(rule, wan):
|
||||
result.extend(_forwards_of(rule, aliases))
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,75 @@
|
||||
"""Unbound's domain forwards (napalm-device-types ``DnsForwardMixin``).
|
||||
|
||||
OPNsense keeps forwards and DNS-over-TLS servers in one model (``dot``); a
|
||||
forward is a row of type ``forward``. Every change is applied with a
|
||||
reconfigure before the method returns.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import DnsForwardMixin
|
||||
|
||||
_SETTINGS = "/api/unbound/settings"
|
||||
_RECONFIGURE = "/api/unbound/service/reconfigure"
|
||||
|
||||
|
||||
def _domain(name: str) -> str:
|
||||
return name.strip().rstrip(".")
|
||||
|
||||
|
||||
class OPNsenseResolverMixin(DnsForwardMixin):
|
||||
"""Needs the driver's ``_post``."""
|
||||
|
||||
def _forward_rows(self) -> list[dict[str, Any]]:
|
||||
rows = self._post(f"{_SETTINGS}/searchForward", {}).get("rows") or [] # type: ignore[attr-defined]
|
||||
return [r for r in rows if r.get("type", "forward") == "forward"]
|
||||
|
||||
def _saved(self, result: dict[str, Any], what: str) -> None:
|
||||
if result.get("result") not in ("saved", "deleted", None):
|
||||
raise RuntimeError(f"Unbound refused {what}: {result.get('validations') or result}")
|
||||
|
||||
def get_dns_forwards(self) -> list[dict[str, Any]]:
|
||||
"""Every forward Unbound has, enabled or not; DNS-over-TLS servers are not forwards."""
|
||||
return [
|
||||
{
|
||||
"domain": _domain(r.get("domain", "")),
|
||||
"server": r.get("server", ""),
|
||||
"port": int(r.get("port") or 53),
|
||||
"enabled": str(r.get("enabled", "1")) == "1",
|
||||
}
|
||||
for r in self._forward_rows()
|
||||
]
|
||||
|
||||
def set_dns_forward(self, domain: str, server: str, port: int = 53) -> None:
|
||||
"""Forward *domain* to *server*; an existing forward of the domain is changed."""
|
||||
name = _domain(domain)
|
||||
row = {
|
||||
"enabled": "1",
|
||||
"type": "forward",
|
||||
"domain": name,
|
||||
"server": server,
|
||||
"port": str(port),
|
||||
}
|
||||
known = [r for r in self._forward_rows() if _domain(r.get("domain", "")) == name]
|
||||
if known:
|
||||
result = self._post(f"{_SETTINGS}/setForward/{known[0]['uuid']}", {"dot": row}) # type: ignore[attr-defined]
|
||||
else:
|
||||
result = self._post(f"{_SETTINGS}/addForward", {"dot": row}) # type: ignore[attr-defined]
|
||||
self._saved(result or {}, f"the forward of {name}")
|
||||
self._post(_RECONFIGURE) # type: ignore[attr-defined]
|
||||
|
||||
def remove_dns_forward(self, domain: str) -> None:
|
||||
"""Delete every forward of *domain*; nothing to do when there is none."""
|
||||
name = _domain(domain)
|
||||
uuids = [
|
||||
r["uuid"]
|
||||
for r in self._forward_rows()
|
||||
if _domain(r.get("domain", "")) == name and r.get("uuid")
|
||||
]
|
||||
if not uuids:
|
||||
return
|
||||
for uuid in uuids:
|
||||
self._post(f"{_SETTINGS}/delForward/{uuid}") # type: ignore[attr-defined]
|
||||
self._post(_RECONFIGURE) # type: ignore[attr-defined]
|
||||
@@ -0,0 +1,314 @@
|
||||
"""Scheduled jobs on OPNsense: the cron jobs of its configuration (napalm-device-types).
|
||||
|
||||
OPNsense keeps its cron jobs in config.xml (System > Settings > Cron) and writes
|
||||
them into the crontab itself; each job runs one **configd action** with optional
|
||||
parameters, never a shell line. The REST API reads and writes them:
|
||||
``/api/cron/settings/get`` answers with every job at once, the action as the
|
||||
option its ``command`` list has selected; ``get_job`` without a uuid is a blank
|
||||
job whose ``command`` options are the actions configd offers; ``add_job``,
|
||||
``set_job``, ``del_job`` and ``toggle_job`` write, ``/api/cron/service/reconfigure``
|
||||
regenerates the crontab. OPNsense routes ``search_jobs`` and ``searchJobs`` to the
|
||||
same action; the snake-case spelling is the documented one.
|
||||
|
||||
**Who owns a job.** A job another component registered (its ``origin`` is not
|
||||
``cron``: the intrusion detection's rule update, say) is ``platform``. A job whose
|
||||
description starts with ``napalm-scheduled-job: <name>`` was written through
|
||||
:meth:`OPNsenseScheduledJobsMixin.put_scheduled_job` (``application``); every other
|
||||
one an admin made (``admin``). Every job can be enabled and disabled; only an
|
||||
application's job can be edited or deleted.
|
||||
|
||||
**Not here.** The API cannot run a configd action now, so no job takes ``run``.
|
||||
What OPNsense puts in the crontab beyond config.xml -- ``periodic``, the plugins'
|
||||
own system jobs -- is not reachable over the API and is not read. The time zone
|
||||
is not read either (None).
|
||||
|
||||
**Parameters, one per line.** Up to 26.1 OPNsense split the parameters the way a
|
||||
shell does; 26.7 takes one argument per line. Arguments without blanks, quotes
|
||||
or backslashes, one per line, mean the same to both, so those are all a job
|
||||
written here takes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types.cron import ALIASES, is_reboot
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
ACTIONS,
|
||||
DELETE,
|
||||
EDIT,
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobDict,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobResultDict,
|
||||
ScheduledJobsMixin,
|
||||
ScheduledJobSpecDict,
|
||||
ScheduledJobsReadingDict,
|
||||
check_job_name,
|
||||
check_spec,
|
||||
job_digest,
|
||||
)
|
||||
|
||||
_SETTINGS = "/api/cron/settings"
|
||||
_RECONFIGURE = "/api/cron/service/reconfigure"
|
||||
_KEY = "opnsense:"
|
||||
#: The origin of a job made in the cron settings themselves.
|
||||
_OWN_ORIGIN = "cron"
|
||||
#: How a job written by put_scheduled_job begins its description.
|
||||
MARKER = "napalm-scheduled-job: "
|
||||
|
||||
_FIELDS = ("minutes", "hours", "days", "months", "weekdays")
|
||||
_SWITCH = ["enable", "disable"]
|
||||
_OWN = [*_SWITCH, EDIT, DELETE]
|
||||
|
||||
#: OPNsense's month and weekday fields take numbers (months also upper case names).
|
||||
_MONTHS = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")
|
||||
_WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
|
||||
_NAME = re.compile(r"[A-Za-z]+")
|
||||
#: A parameter every OPNsense release hands configd as one argument.
|
||||
_PLAIN_ARGUMENT = re.compile(r"[^\s'\"\\]+")
|
||||
|
||||
|
||||
def _selected(field: Any) -> str:
|
||||
"""The option a list field has selected (none: ""); a plain value as it is."""
|
||||
if not isinstance(field, dict):
|
||||
return str(field or "")
|
||||
chosen = (k for k, o in field.items() if isinstance(o, dict) and o.get("selected") in (1, "1"))
|
||||
return next(chosen, "")
|
||||
|
||||
|
||||
def _command(node: dict[str, Any]) -> str:
|
||||
"""The configd action and its parameters, as one line."""
|
||||
parameters = str(node.get("parameters") or "").splitlines()
|
||||
return " ".join([_selected(node.get("command")), *(p.strip() for p in parameters if p.strip())])
|
||||
|
||||
|
||||
def _schedule(uuid: str, node: dict[str, Any]) -> str:
|
||||
fields = [node.get(field) for field in _FIELDS]
|
||||
if not all(isinstance(f, str) and f.strip() for f in fields):
|
||||
raise ValueError(f"cron job {uuid} came back without its schedule")
|
||||
return " ".join(str(f).strip() for f in fields)
|
||||
|
||||
|
||||
def _ownership(origin: str, description: str) -> tuple[str, str | None, str]:
|
||||
"""(managed_by, the application's job name or None, the description to show)."""
|
||||
if origin != _OWN_ORIGIN:
|
||||
return "platform", None, description
|
||||
if not description.startswith(MARKER):
|
||||
return "admin", None, description
|
||||
name, _, rest = description[len(MARKER) :].partition(" ")
|
||||
try:
|
||||
check_job_name(name)
|
||||
except ScheduledJobRefused:
|
||||
return "admin", None, description
|
||||
return "application", name, rest.strip()
|
||||
|
||||
|
||||
def scheduled_job(uuid: str, node: dict[str, Any]) -> ScheduledJobDict:
|
||||
"""One job of the cron settings, as napalm-device-types reads it."""
|
||||
origin = str(node.get("origin") or _OWN_ORIGIN)
|
||||
managed_by, name, description = _ownership(origin, str(node.get("description") or ""))
|
||||
job: dict[str, Any] = {
|
||||
"key": f"{_KEY}{uuid}",
|
||||
"kind": "cron",
|
||||
"source": "config.xml",
|
||||
# The crontab line calls configctl; configd runs the action as root.
|
||||
"run_as": "root",
|
||||
"schedule": _schedule(uuid, node),
|
||||
"schedule_kind": "cron",
|
||||
"command": _command(node),
|
||||
"enabled": str(node.get("enabled")) == "1",
|
||||
"managed_by": managed_by,
|
||||
"actions": list(_OWN if name else _SWITCH),
|
||||
}
|
||||
if name:
|
||||
job["name"] = name
|
||||
if description:
|
||||
job["description"] = description
|
||||
job["digest"] = job_digest(job)
|
||||
return job # type: ignore[return-value]
|
||||
|
||||
|
||||
def scheduled_jobs(answer: Any) -> list[ScheduledJobDict]:
|
||||
"""Every job in an answer of ``/api/cron/settings/get``.
|
||||
|
||||
:raises ValueError: when the answer has no list of jobs -- never "no jobs".
|
||||
"""
|
||||
try:
|
||||
jobs = answer["job"]["jobs"]["job"]
|
||||
except (KeyError, TypeError) as exc:
|
||||
raise ValueError("the cron settings came back without their jobs") from exc
|
||||
if jobs == []: # an empty ArrayField comes back as a JSON list
|
||||
return []
|
||||
if not isinstance(jobs, dict):
|
||||
raise ValueError(f"the cron settings came back with jobs as {type(jobs).__name__}")
|
||||
return [scheduled_job(uuid, node) for uuid, node in jobs.items()]
|
||||
|
||||
|
||||
def _numbers(field: str, names: tuple[str, ...], low: int) -> str:
|
||||
return _NAME.sub(lambda m: str(names.index(m.group().lower()) + low), field)
|
||||
|
||||
|
||||
def cron_fields(schedule: str) -> dict[str, str]:
|
||||
"""The five fields OPNsense stores of *schedule*, which :func:`check_spec` passed."""
|
||||
if is_reboot(schedule):
|
||||
raise ScheduledJobRefused("OPNsense's cron jobs have no @reboot")
|
||||
text = schedule.strip()
|
||||
fields = ALIASES.get(text.lower(), text).split()
|
||||
fields[3] = _numbers(fields[3], _MONTHS, 1)
|
||||
fields[4] = _numbers(fields[4], _WEEKDAYS, 0)
|
||||
return dict(zip(_FIELDS, fields, strict=True))
|
||||
|
||||
|
||||
def configd_action(command: str, actions: Iterable[str]) -> tuple[str, list[str]]:
|
||||
"""(the configd action *command* names, its parameters).
|
||||
|
||||
The action is the longest one configd offers that *command* starts with; the
|
||||
words after it are its parameters.
|
||||
"""
|
||||
if "\n" in command.strip():
|
||||
raise ScheduledJobRefused("an OPNsense job runs one configd action, on one line")
|
||||
words = command.split()
|
||||
known = set(actions)
|
||||
for end in range(len(words), 0, -1):
|
||||
action = " ".join(words[:end])
|
||||
if action in known:
|
||||
parameters = words[end:]
|
||||
for parameter in parameters:
|
||||
if not _PLAIN_ARGUMENT.fullmatch(parameter):
|
||||
raise ScheduledJobRefused(f"not a parameter OPNsense passes on: {parameter!r}")
|
||||
return action, parameters
|
||||
raise ScheduledJobRefused(
|
||||
f"configd offers no action {command!r}; get_scheduled_job_commands() lists them"
|
||||
)
|
||||
|
||||
|
||||
def _saved(result: dict[str, Any], what: str) -> None:
|
||||
if result.get("result") == "saved":
|
||||
return
|
||||
if result.get("validations"):
|
||||
raise ScheduledJobRefused(f"OPNsense refused {what}: {result['validations']}")
|
||||
raise RuntimeError(f"OPNsense did not save {what}: {result}")
|
||||
|
||||
|
||||
class OPNsenseScheduledJobsMixin(ScheduledJobsMixin):
|
||||
"""The cron jobs of config.xml; needs the driver's ``_get`` and ``_post``."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's REST helpers
|
||||
|
||||
def _get(self, path: str) -> dict[str, Any]: ...
|
||||
|
||||
def _post(self, path: str, data: dict[str, Any] | None = None) -> dict[str, Any]: ...
|
||||
|
||||
def get_scheduled_job_commands(self) -> list[dict[str, str]]:
|
||||
"""The configd actions a job can run: ``[{"command", "description"}]``, by command.
|
||||
|
||||
:raises ValueError: when the list came back empty -- configd did not answer.
|
||||
"""
|
||||
answer = self._get(f"{_SETTINGS}/get_job")
|
||||
job = answer.get("job") if isinstance(answer, dict) else None
|
||||
options = job.get("command") if isinstance(job, dict) else None
|
||||
if not isinstance(options, dict) or not options:
|
||||
raise ValueError("the cron settings came back without configd's actions")
|
||||
return [
|
||||
{"command": key, "description": str(option.get("value") or key)}
|
||||
for key, option in sorted(options.items())
|
||||
if key and isinstance(option, dict)
|
||||
]
|
||||
|
||||
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
|
||||
"""Every cron job of config.xml, in one request; the time zone is not read.
|
||||
|
||||
:raises ValueError: when the answer came back without its jobs.
|
||||
"""
|
||||
return {"jobs": scheduled_jobs(self._get(f"{_SETTINGS}/get")), "time_zone": None}
|
||||
|
||||
def _sj_job(self, key: str, digest: str) -> ScheduledJobDict:
|
||||
job = next((j for j in self.get_scheduled_jobs()["jobs"] if j["key"] == key), None)
|
||||
if job is None:
|
||||
raise LookupError(f"no scheduled job {key}")
|
||||
if job["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"{key} changed on the host since it was read")
|
||||
return job
|
||||
|
||||
def _sj_own(self, name: str, digest: str | None) -> ScheduledJobDict | None:
|
||||
jobs = self.get_scheduled_jobs()["jobs"]
|
||||
current = next((j for j in jobs if j.get("name") == name), None)
|
||||
if digest is None:
|
||||
if current is not None:
|
||||
raise ScheduledJobChanged(f"a job {name} is there already")
|
||||
return None
|
||||
if current is None:
|
||||
raise LookupError(f"no scheduled job named {name}")
|
||||
if current["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"{current['key']} changed on the host since it was read")
|
||||
return current
|
||||
|
||||
def _sj_reload(self) -> None:
|
||||
result = self._post(_RECONFIGURE)
|
||||
if result.get("status") != "ok":
|
||||
raise RuntimeError(f"cron did not reload: {result}")
|
||||
|
||||
def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Enable or disable the job *key*; no job runs now (the API cannot)."""
|
||||
if action not in ACTIONS:
|
||||
raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}")
|
||||
job = self._sj_job(key, digest)
|
||||
if action not in job["actions"]:
|
||||
raise ScheduledJobRefused(
|
||||
f"{key} cannot {action}: OPNsense's API does not run a configd action now"
|
||||
)
|
||||
flag = "1" if action == "enable" else "0"
|
||||
uuid = key.removeprefix(_KEY)
|
||||
result = self._post(f"{_SETTINGS}/toggle_job/{uuid}/{flag}")
|
||||
if result.get("result") not in ("Enabled", "Disabled"):
|
||||
raise RuntimeError(f"OPNsense did not {action} {key}: {result}")
|
||||
self._sj_reload()
|
||||
return {"success": True, "output": f"{key} {action}d"}
|
||||
|
||||
def put_scheduled_job(
|
||||
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Create or change the application's job ``spec["name"]``.
|
||||
|
||||
``command`` is a configd action (:meth:`get_scheduled_job_commands`), with
|
||||
its parameters after it.
|
||||
"""
|
||||
check_spec(spec)
|
||||
if spec["run_as"] != "root":
|
||||
raise ScheduledJobRefused("an OPNsense job runs its configd action as root")
|
||||
fields = cron_fields(spec["schedule"])
|
||||
commands = (c["command"] for c in self.get_scheduled_job_commands())
|
||||
action, parameters = configd_action(spec["command"], commands)
|
||||
current = self._sj_own(spec["name"], digest)
|
||||
job = {
|
||||
"enabled": "1" if spec["enabled"] else "0",
|
||||
**fields,
|
||||
"command": action,
|
||||
"parameters": "\n".join(parameters),
|
||||
"description": f"{MARKER}{spec['name']} {spec.get('description') or ''}".rstrip(),
|
||||
}
|
||||
if current is None:
|
||||
result = self._post(f"{_SETTINGS}/add_job", {"job": job})
|
||||
uuid = str(result.get("uuid") or "")
|
||||
else:
|
||||
uuid = current["key"].removeprefix(_KEY)
|
||||
result = self._post(f"{_SETTINGS}/set_job/{uuid}", {"job": job})
|
||||
_saved(result, f"the job {spec['name']}")
|
||||
self._sj_reload()
|
||||
return {"success": True, "output": f"{_KEY}{uuid} {'changed' if current else 'created'}"}
|
||||
|
||||
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Delete the application's job *key*; any other job is only switched."""
|
||||
job = self._sj_job(key, digest)
|
||||
if job["managed_by"] != "application":
|
||||
raise ScheduledJobRefused(
|
||||
f"{key} was not written by an application; it is only switched"
|
||||
)
|
||||
result = self._post(f"{_SETTINGS}/del_job/{key.removeprefix(_KEY)}")
|
||||
if result.get("result") != "deleted":
|
||||
raise RuntimeError(f"OPNsense did not delete {key}: {result}")
|
||||
self._sj_reload()
|
||||
return {"success": True, "output": f"{key} deleted"}
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Where the firewall's SSH server takes its algorithm lists from (NetOrk/netork#1769).
|
||||
|
||||
OPNsense writes sshd_config itself, from config.xml (``<system><ssh>``: ``kex``,
|
||||
``ciphers``, ``macs``, ``keys`` and ``keysig``, comma-separated), whenever the
|
||||
service is configured (``openssh_configure_do`` in ``plugins.inc.d/openssh.inc``).
|
||||
The section is set on the legacy page ``system_advanced_admin.php``; no API
|
||||
controller reads or writes it, up to 26.7 and on ``master``. So this driver cannot
|
||||
take algorithms out of what sshd offers -- it does not offer ``harden_ssh_server``
|
||||
-- and says, as data, where a person sets the lists instead.
|
||||
|
||||
A field left empty is OpenSSH's defaults. In an HA pair the configuration sync
|
||||
carries the section to the backup when its "OpenSSH" item is ticked (sync id
|
||||
``ssh``, :data:`napalm_opnsense.ha.SYNC_ITEM_SERVICES`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class OPNsenseSshSettingsMixin:
|
||||
"""The page and fields that set the SSH server's algorithm lists, as the web
|
||||
interface names them."""
|
||||
|
||||
#: The menu path to the page, ending in the section that holds the lists.
|
||||
SSH_SETTINGS_MENU: tuple[str, ...] = ("System", "Settings", "Administration", "Secure Shell")
|
||||
#: Each list's field, by its algorithm class (napalm-device-types'
|
||||
#: ``SSH_ALGORITHM_CLASSES``).
|
||||
SSH_SETTINGS_FIELDS: dict[str, str] = {
|
||||
"kex": "Key exchange algorithms",
|
||||
"cipher": "Ciphers",
|
||||
"mac": "MACs",
|
||||
"hostkey": "Host key algorithms",
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
"""The firewall's CARP addresses, read from its interface overview (netOrk #1121).
|
||||
|
||||
``/api/interfaces/overview/export`` lists every address of an interface; one bound
|
||||
to a CARP VHID carries ``vhid`` and this node's CARP ``status``. That covers the
|
||||
CARP address itself and an IP alias bound to its VHID alike -- both float with the
|
||||
VHID's MASTER. An address without a VHID stays on this node and is no virtual IP.
|
||||
|
||||
``interfaces/vip_settings/search_item`` would list the same addresses, but with
|
||||
each VHID's CARP password in it. The overview has none, so a secret never reaches
|
||||
the caller.
|
||||
|
||||
What a state means -- MASTER holds, BACKUP stands by -- is CARP protocol
|
||||
knowledge, so it lives here with the driver that speaks CARP
|
||||
(:func:`carp_virtual_ip`), not in napalm-device-types, which carries only the
|
||||
shape of the reading.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types.models import VirtualIpDict
|
||||
|
||||
#: CARP's state of a VHID on one member -> (running, holds).
|
||||
_CARP_STATES: dict[str, tuple[bool, bool]] = {
|
||||
"MASTER": (True, True),
|
||||
"BACKUP": (True, False),
|
||||
"INIT": (False, False),
|
||||
"DISABLED": (False, False),
|
||||
}
|
||||
|
||||
|
||||
def carp_master(entry: dict[str, Any]) -> bool:
|
||||
"""Whether this node is MASTER for an interface address bound to a CARP VHID."""
|
||||
return str(entry.get("status") or "").strip().upper() == "MASTER"
|
||||
|
||||
|
||||
def _address(text: str) -> tuple[str, int | None] | None:
|
||||
"""``"10.0.0.1/24"`` -> ``("10.0.0.1", 24)``; None for what is no address."""
|
||||
host, slash, prefix = text.partition("/")
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return None
|
||||
if not slash:
|
||||
return str(address), None
|
||||
if not prefix.isdigit() or int(prefix) > address.max_prefixlen:
|
||||
return None
|
||||
return str(address), int(prefix)
|
||||
|
||||
|
||||
def carp_virtual_ip(
|
||||
*,
|
||||
address: str,
|
||||
prefix_length: int | None,
|
||||
vhid: object,
|
||||
state: str | None,
|
||||
instance: str,
|
||||
interface: str | None,
|
||||
) -> VirtualIpDict | None:
|
||||
"""One address bound to a CARP VHID, as a virtual IP; None for what is no address.
|
||||
|
||||
Who holds it comes from CARP's *state* on this member, not from its
|
||||
interfaces: MASTER holds it, BACKUP stands by, INIT and DISABLED neither run
|
||||
nor hold. A state this does not know says nothing (``running`` and ``holds``
|
||||
None), and the caller falls back on the interfaces. *address* may carry its
|
||||
prefix (``"10.0.0.1/24"``), which then wins over *prefix_length*.
|
||||
"""
|
||||
parsed = _address(address.strip()) if address else None
|
||||
if parsed is None:
|
||||
return None
|
||||
normalised, written = parsed
|
||||
prefix = written if written is not None else prefix_length
|
||||
if prefix is not None and not 0 <= prefix <= ipaddress.ip_address(normalised).max_prefixlen:
|
||||
prefix = None
|
||||
vhid_text = str(vhid).strip() if vhid is not None else ""
|
||||
running, holds = _CARP_STATES.get((state or "").strip().upper(), (None, None))
|
||||
return {
|
||||
"mechanism": "carp",
|
||||
"instance": instance or f"vhid {vhid_text}",
|
||||
"address": normalised,
|
||||
"prefix_length": prefix,
|
||||
"interface": interface,
|
||||
"group_key": f"vhid:{vhid_text}" if vhid_text.isdigit() else None,
|
||||
"running": running,
|
||||
"holds": holds,
|
||||
}
|
||||
|
||||
|
||||
def _interfaces(overview: Any) -> list[Any]:
|
||||
"""The interface list, whether the answer is the list or wraps it."""
|
||||
if isinstance(overview, dict):
|
||||
return overview.get("interfaces") or []
|
||||
if isinstance(overview, list):
|
||||
return overview
|
||||
raise ValueError(f"unexpected interface overview: {type(overview).__name__}")
|
||||
|
||||
|
||||
def carp_addresses(overview: Any) -> list[VirtualIpDict]:
|
||||
"""Every address bound to a CARP VHID in *overview*, sorted by address.
|
||||
|
||||
:raises ValueError: when the answer is neither the interface list nor wraps it.
|
||||
"""
|
||||
entries: list[VirtualIpDict] = []
|
||||
for interface in _interfaces(overview):
|
||||
if not isinstance(interface, dict):
|
||||
continue
|
||||
identifier = interface.get("identifier") or ""
|
||||
for family in ("ipv4", "ipv6"):
|
||||
for address in interface.get(family) or []:
|
||||
if not isinstance(address, dict) or not address.get("vhid"):
|
||||
continue
|
||||
entry = carp_virtual_ip(
|
||||
address=str(address.get("ipaddr") or ""),
|
||||
prefix_length=None,
|
||||
vhid=address.get("vhid"),
|
||||
state=address.get("status"),
|
||||
instance=interface.get("description") or identifier,
|
||||
interface=interface.get("device") or identifier or None,
|
||||
)
|
||||
if entry is not None:
|
||||
entries.append(entry)
|
||||
return sorted(entries, key=_order)
|
||||
|
||||
|
||||
def _order(entry: VirtualIpDict) -> tuple[int, int]:
|
||||
address = ipaddress.ip_address(entry["address"])
|
||||
return address.version, int(address)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""WireGuard peers as VPN tunnels. Pure: no I/O.
|
||||
|
||||
``/api/wireguard/service/show`` lists every WireGuard interface and peer::
|
||||
|
||||
{"total": N, "rows": [
|
||||
{"if": "wg0", "type": "interface", ...},
|
||||
{"if": "wg0", "type": "peer", "public-key": "...",
|
||||
"endpoint": "1.2.3.4:51820", "transfer-rx": N, "transfer-tx": N,
|
||||
"name": "office", "peer-status": "online",
|
||||
"latest-handshake-age": 45, "ifname": "office"}, ...
|
||||
]}
|
||||
|
||||
**The key is the peer, not its place.** It used to be a running counter, so a
|
||||
peer added ahead of another renumbered it, and whatever a consumer keeps per
|
||||
key (netOrk's site link, its tunnel check) moved to a different peer (#32).
|
||||
Now it is the interface and the start of the public key, as napalm-linux does
|
||||
it, with the base64 made URL-safe because the key is used as a path segment.
|
||||
Two peers sharing the prefix get the whole key; a row without a public key
|
||||
keeps its position.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
#: How much of a public key names a peer, the same length as napalm-linux uses.
|
||||
_KEY_PREFIX = 8
|
||||
|
||||
|
||||
def _key(row: dict[str, Any], position: int, taken: dict[str, Any]) -> str:
|
||||
public_key = (row.get("public-key") or "").strip()
|
||||
if not public_key:
|
||||
return f"wireguard-{position}"
|
||||
safe = public_key.rstrip("=").replace("+", "-").replace("/", "_")
|
||||
key = f"wireguard-{row.get('if') or 'wg'}-{safe[:_KEY_PREFIX]}"
|
||||
if key in taken:
|
||||
key = f"wireguard-{row.get('if') or 'wg'}-{safe}"
|
||||
return key
|
||||
|
||||
|
||||
def _remote_ip(row: dict[str, Any]) -> str:
|
||||
endpoint = (row.get("endpoint") or "").strip()
|
||||
if not endpoint or endpoint == "(none)":
|
||||
return ""
|
||||
return endpoint.rsplit(":", 1)[0].strip("[]")
|
||||
|
||||
|
||||
def _tunnel(row: dict[str, Any], position: int) -> dict[str, Any]:
|
||||
handshake_age = row.get("latest-handshake-age")
|
||||
return {
|
||||
"type": "WireGuard",
|
||||
"local_endpoint": "",
|
||||
"remote_endpoint": _remote_ip(row),
|
||||
"is_up": row.get("peer-status") == "online",
|
||||
"uptime": int(handshake_age) if handshake_age else 0,
|
||||
"bytes_in": int(row.get("transfer-rx") or 0),
|
||||
"bytes_out": int(row.get("transfer-tx") or 0),
|
||||
"description": (
|
||||
(row.get("name") or "").strip()
|
||||
or (row.get("ifname") or "").strip()
|
||||
or f"wg-peer-{position}"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def wireguard_tunnels(show: Any) -> dict[str, dict[str, Any]]:
|
||||
"""One ``VPNTunnelDict`` per peer in ``/api/wireguard/service/show``, by tunnel key."""
|
||||
rows = show.get("rows", []) if isinstance(show, dict) else []
|
||||
tunnels: dict[str, dict[str, Any]] = {}
|
||||
peers = [row for row in rows if isinstance(row, dict) and row.get("type") == "peer"]
|
||||
for position, row in enumerate(peers, start=1):
|
||||
tunnels[_key(row, position, tunnels)] = _tunnel(row, position)
|
||||
return tunnels
|
||||
+55
-15
@@ -1,54 +1,94 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68", "wheel"]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-opnsense"
|
||||
version = "0.1.0"
|
||||
version = "0.6.0"
|
||||
description = "NAPALM driver for OPNsense (read-only via REST API)."
|
||||
readme = "README.md"
|
||||
license = { text = "Apache-2.0" }
|
||||
requires-python = ">=3.10"
|
||||
license = "Apache-2.0"
|
||||
requires-python = ">=3.12"
|
||||
authors = [
|
||||
{ name = "Christian Manivong" },
|
||||
]
|
||||
classifiers = [
|
||||
"Topic :: Utilities",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Operating System :: POSIX :: Linux",
|
||||
"Operating System :: MacOS",
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0.0",
|
||||
"napalm_device_types>=0.2.0",
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.27.0",
|
||||
"requests>=2.28.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest",
|
||||
"pytest-cov",
|
||||
"black",
|
||||
"ruff",
|
||||
"pytest>=8",
|
||||
"pytest-cov>=5",
|
||||
"mypy>=1.11",
|
||||
"ruff>=0.6",
|
||||
]
|
||||
|
||||
[project.entry-points."napalm.drivers"]
|
||||
opnsense = "napalm_opnsense.opnsense:OPNsenseDriver"
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/napalm-automation-community/napalm-opnsense"
|
||||
Repository = "https://git.netork.io/NAPALM/napalm-opnsense"
|
||||
Issues = "https://git.netork.io/NAPALM/napalm-opnsense/issues"
|
||||
Changelog = "https://git.netork.io/NAPALM/napalm-opnsense/src/branch/main/CHANGELOG.md"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["napalm_opnsense*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
napalm_opnsense = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py39"
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# Recorded device output keeps its lines.
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = ["napalm.*", "requests.*"]
|
||||
ignore_missing_imports = true
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
# Not yet under strict mypy (quality baseline); may only shrink.
|
||||
module = [
|
||||
"napalm_opnsense.ha",
|
||||
"napalm_opnsense.listening",
|
||||
"napalm_opnsense.opnsense",
|
||||
"napalm_opnsense.ospf_mixin",
|
||||
"napalm_opnsense.ping_mixin",
|
||||
"napalm_opnsense.port_forwards",
|
||||
"napalm_opnsense.resolver_mixin",
|
||||
]
|
||||
ignore_errors = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["napalm_opnsense"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 79
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"coverage_floor": 79.0,
|
||||
"function_complexity": {
|
||||
"napalm_opnsense/ha.py::config_sync": 12,
|
||||
"napalm_opnsense/ha.py::dhcp_ha": 11,
|
||||
"napalm_opnsense/listening.py::_service_of": 12,
|
||||
"napalm_opnsense/listening.py::_socket": 19,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver._allow_snmp_sources": 11,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver._get_unbound_host_overrides": 16,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver._kea_read_list": 11,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.apply_dhcp_subnet": 21,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.apply_firewall_rule": 11,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.delete_dhcp_reservation_and_lease": 11,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_bgp_neighbors": 16,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases": 15,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases._parse_kea": 14,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_reservations": 15,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_subnets": 17,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_facts": 12,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_firewall_rules": 30,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_interfaces": 13,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_interfaces_ip": 34,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_lldp_neighbors_detail": 12,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_networks": 25,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_route_to": 23,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_vpn_tunnels": 47,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.load_merge_candidate": 13,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.sync_dns_zone": 20,
|
||||
"napalm_opnsense/port_forwards.py::_forwards_of": 12,
|
||||
"napalm_opnsense/virtual_ips.py::carp_addresses": 14
|
||||
},
|
||||
"function_lines": {
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver._regenerate_web_cert": 51,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.apply_dhcp_subnet": 60,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.create_dhcp_reservation": 64,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.delete_dhcp_reservation_and_lease": 79,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_bgp_neighbors": 86,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_leases": 106,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_dhcp_subnets": 60,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_firewall_rules": 84,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_interfaces_ip": 68,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_networks": 85,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_route_to": 85,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_vpn_tunnels": 145,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.load_merge_candidate": 56,
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.sync_dns_zone": 112
|
||||
},
|
||||
"mypy_relaxed": [
|
||||
"napalm_opnsense.ha",
|
||||
"napalm_opnsense.listening",
|
||||
"napalm_opnsense.opnsense",
|
||||
"napalm_opnsense.ospf_mixin",
|
||||
"napalm_opnsense.ping_mixin",
|
||||
"napalm_opnsense.port_forwards",
|
||||
"napalm_opnsense.resolver_mixin"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_opnsense/opnsense.py": 3055
|
||||
},
|
||||
"untyped_public": [
|
||||
"napalm_opnsense/opnsense.py::OPNsenseDriver.get_snmp_config"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
{
|
||||
"job": {
|
||||
"jobs": {
|
||||
"job": {
|
||||
"0b6e3c52-6a1e-4c7a-9a0e-2f0a1d6c3b11": {
|
||||
"origin": "cron",
|
||||
"enabled": "1",
|
||||
"minutes": "0",
|
||||
"hours": "3",
|
||||
"days": "*",
|
||||
"months": "*",
|
||||
"weekdays": "1-5",
|
||||
"who": "root",
|
||||
"command": {
|
||||
"filter refresh_aliases": {
|
||||
"value": "Update and reload firewall aliases",
|
||||
"selected": 0
|
||||
},
|
||||
"firmware auto-update": {
|
||||
"value": "Automatic firmware update",
|
||||
"selected": 0
|
||||
},
|
||||
"ids update": {
|
||||
"value": "Update and reload intrusion detection rules",
|
||||
"selected": 0
|
||||
},
|
||||
"system ha_reconfigure_backup": {
|
||||
"value": "HA update and reconfigure backup",
|
||||
"selected": 0
|
||||
},
|
||||
"system remote backup": {
|
||||
"value": "Remote backup",
|
||||
"selected": 1
|
||||
},
|
||||
"unbound dnsbl": {
|
||||
"value": "Update Unbound DNSBLs",
|
||||
"selected": 0
|
||||
}
|
||||
},
|
||||
"parameters": "",
|
||||
"description": "Nightly configuration backup"
|
||||
},
|
||||
"1f2d8e04-93b7-4f4e-8c55-7d1e0c9a2b22": {
|
||||
"origin": "IDS",
|
||||
"enabled": "0",
|
||||
"minutes": "30",
|
||||
"hours": "1",
|
||||
"days": "*",
|
||||
"months": "*",
|
||||
"weekdays": "*",
|
||||
"who": "root",
|
||||
"command": {
|
||||
"filter refresh_aliases": {
|
||||
"value": "Update and reload firewall aliases",
|
||||
"selected": 0
|
||||
},
|
||||
"firmware auto-update": {
|
||||
"value": "Automatic firmware update",
|
||||
"selected": 0
|
||||
},
|
||||
"ids update": {
|
||||
"value": "Update and reload intrusion detection rules",
|
||||
"selected": 1
|
||||
},
|
||||
"system ha_reconfigure_backup": {
|
||||
"value": "HA update and reconfigure backup",
|
||||
"selected": 0
|
||||
},
|
||||
"system remote backup": {
|
||||
"value": "Remote backup",
|
||||
"selected": 0
|
||||
},
|
||||
"unbound dnsbl": {
|
||||
"value": "Update Unbound DNSBLs",
|
||||
"selected": 0
|
||||
}
|
||||
},
|
||||
"parameters": "",
|
||||
"description": "ids rule updates"
|
||||
},
|
||||
"2a7c9b16-4d3e-4b8f-a1c2-5e6f7a8b9c33": {
|
||||
"origin": "cron",
|
||||
"enabled": "1",
|
||||
"minutes": "*/15",
|
||||
"hours": "*",
|
||||
"days": "*",
|
||||
"months": "*",
|
||||
"weekdays": "*",
|
||||
"who": "root",
|
||||
"command": {
|
||||
"filter refresh_aliases": {
|
||||
"value": "Update and reload firewall aliases",
|
||||
"selected": 0
|
||||
},
|
||||
"firmware auto-update": {
|
||||
"value": "Automatic firmware update",
|
||||
"selected": 0
|
||||
},
|
||||
"ids update": {
|
||||
"value": "Update and reload intrusion detection rules",
|
||||
"selected": 0
|
||||
},
|
||||
"system ha_reconfigure_backup": {
|
||||
"value": "HA update and reconfigure backup",
|
||||
"selected": 0
|
||||
},
|
||||
"system remote backup": {
|
||||
"value": "Remote backup",
|
||||
"selected": 0
|
||||
},
|
||||
"unbound dnsbl": {
|
||||
"value": "Update Unbound DNSBLs",
|
||||
"selected": 1
|
||||
}
|
||||
},
|
||||
"parameters": "",
|
||||
"description": "napalm-scheduled-job: dnsbl-refresh Refresh the DNS blocklists"
|
||||
},
|
||||
"3c8d0e27-5f4a-4c9b-b2d3-6f7a8b9c0d44": {
|
||||
"origin": "cron",
|
||||
"enabled": "1",
|
||||
"minutes": "0",
|
||||
"hours": "4",
|
||||
"days": "1",
|
||||
"months": "*",
|
||||
"weekdays": "*",
|
||||
"who": "root",
|
||||
"command": {
|
||||
"filter refresh_aliases": {
|
||||
"value": "Update and reload firewall aliases",
|
||||
"selected": 1
|
||||
},
|
||||
"firmware auto-update": {
|
||||
"value": "Automatic firmware update",
|
||||
"selected": 0
|
||||
},
|
||||
"ids update": {
|
||||
"value": "Update and reload intrusion detection rules",
|
||||
"selected": 0
|
||||
},
|
||||
"system ha_reconfigure_backup": {
|
||||
"value": "HA update and reconfigure backup",
|
||||
"selected": 0
|
||||
},
|
||||
"system remote backup": {
|
||||
"value": "Remote backup",
|
||||
"selected": 0
|
||||
},
|
||||
"unbound dnsbl": {
|
||||
"value": "Update Unbound DNSBLs",
|
||||
"selected": 0
|
||||
}
|
||||
},
|
||||
"parameters": "--quiet\n--all\n",
|
||||
"description": "Monthly alias refresh"
|
||||
},
|
||||
"4d9e1f38-6a5b-4dac-83e4-7a8b9c0d1e55": {
|
||||
"origin": "cron",
|
||||
"enabled": "0",
|
||||
"minutes": "0",
|
||||
"hours": "5",
|
||||
"days": "*",
|
||||
"months": "*",
|
||||
"weekdays": "0",
|
||||
"who": "root",
|
||||
"command": {
|
||||
"filter refresh_aliases": {
|
||||
"value": "Update and reload firewall aliases",
|
||||
"selected": 0
|
||||
},
|
||||
"firmware auto-update": {
|
||||
"value": "Automatic firmware update",
|
||||
"selected": 1
|
||||
},
|
||||
"ids update": {
|
||||
"value": "Update and reload intrusion detection rules",
|
||||
"selected": 0
|
||||
},
|
||||
"system ha_reconfigure_backup": {
|
||||
"value": "HA update and reconfigure backup",
|
||||
"selected": 0
|
||||
},
|
||||
"system remote backup": {
|
||||
"value": "Remote backup",
|
||||
"selected": 0
|
||||
},
|
||||
"unbound dnsbl": {
|
||||
"value": "Update Unbound DNSBLs",
|
||||
"selected": 0
|
||||
}
|
||||
},
|
||||
"parameters": "",
|
||||
"description": "napalm-scheduled-job: Not_A_Name written by hand"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"job": {
|
||||
"origin": "cron",
|
||||
"enabled": "1",
|
||||
"minutes": "0",
|
||||
"hours": "0",
|
||||
"days": "*",
|
||||
"months": "*",
|
||||
"weekdays": "*",
|
||||
"who": "root",
|
||||
"command": {
|
||||
"filter refresh_aliases": {
|
||||
"value": "Update and reload firewall aliases",
|
||||
"selected": 0
|
||||
},
|
||||
"firmware auto-update": {
|
||||
"value": "Automatic firmware update",
|
||||
"selected": 0
|
||||
},
|
||||
"ids update": {
|
||||
"value": "Update and reload intrusion detection rules",
|
||||
"selected": 0
|
||||
},
|
||||
"system ha_reconfigure_backup": {
|
||||
"value": "HA update and reconfigure backup",
|
||||
"selected": 0
|
||||
},
|
||||
"system remote backup": {
|
||||
"value": "Remote backup",
|
||||
"selected": 0
|
||||
},
|
||||
"unbound dnsbl": {
|
||||
"value": "Update Unbound DNSBLs",
|
||||
"selected": 0
|
||||
}
|
||||
},
|
||||
"parameters": "",
|
||||
"description": ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
{
|
||||
"gw-01": {
|
||||
"kea_dhcpv4_get": {
|
||||
"dhcpv4": {
|
||||
"ha": {
|
||||
"enabled": "1",
|
||||
"this_server_name": "",
|
||||
"max_unacked_clients": "2",
|
||||
"%this_server_name": "gw"
|
||||
}
|
||||
}
|
||||
},
|
||||
"kea_dhcpv4_searchPeer": {
|
||||
"rows": [
|
||||
{
|
||||
"uuid": "574e7b41-a5c7-4682-bc63-f4a99e07f262",
|
||||
"name": "gw",
|
||||
"role": "primary",
|
||||
"%role": "Primary",
|
||||
"url": "http://10.5.100.2:8001/"
|
||||
},
|
||||
{
|
||||
"uuid": "d6a4e812-4bc8-4713-bebb-b330ea65f587",
|
||||
"name": "gw-02",
|
||||
"role": "standby",
|
||||
"%role": "Standby",
|
||||
"url": "http://10.5.100.3:8001/"
|
||||
}
|
||||
],
|
||||
"rowCount": 2,
|
||||
"total": 2,
|
||||
"current": 1
|
||||
},
|
||||
"core_hasync_get": {
|
||||
"hasync": {
|
||||
"synchronizetoip": "10.5.100.3",
|
||||
"syncitems": {
|
||||
"aliases": {
|
||||
"value": "Aliases",
|
||||
"selected": 1
|
||||
},
|
||||
"authservers": {
|
||||
"value": "Authentication Servers",
|
||||
"selected": 1
|
||||
},
|
||||
"captiveportal": {
|
||||
"value": "Captive Portal",
|
||||
"selected": 1
|
||||
},
|
||||
"certs": {
|
||||
"value": "Certificates and Authorities",
|
||||
"selected": 1
|
||||
},
|
||||
"cron": {
|
||||
"value": "Cron",
|
||||
"selected": 0
|
||||
},
|
||||
"ddclient": {
|
||||
"value": "ddclient",
|
||||
"selected": 1
|
||||
},
|
||||
"dhcrelay": {
|
||||
"value": "DHCRelay",
|
||||
"selected": 0
|
||||
},
|
||||
"dnsforwarder": {
|
||||
"value": "Dnsmasq DNS/DHCP",
|
||||
"selected": 0
|
||||
},
|
||||
"categories": {
|
||||
"value": "Firewall Categories",
|
||||
"selected": 1
|
||||
},
|
||||
"ifgroups": {
|
||||
"value": "Firewall Groups",
|
||||
"selected": 1
|
||||
},
|
||||
"lvtemplate": {
|
||||
"value": "Firewall Log Templates",
|
||||
"selected": 1
|
||||
},
|
||||
"rules": {
|
||||
"value": "Firewall Rules",
|
||||
"selected": 1
|
||||
},
|
||||
"schedules": {
|
||||
"value": "Firewall Schedules",
|
||||
"selected": 1
|
||||
},
|
||||
"freeradius": {
|
||||
"value": "Freeradius",
|
||||
"selected": 0
|
||||
},
|
||||
"quagga": {
|
||||
"value": "FRR",
|
||||
"selected": 0
|
||||
},
|
||||
"hostwatch": {
|
||||
"value": "Host discovery service",
|
||||
"selected": 0
|
||||
},
|
||||
"suricata": {
|
||||
"value": "Intrusion Detection",
|
||||
"selected": 0
|
||||
},
|
||||
"ipsec": {
|
||||
"value": "IPsec",
|
||||
"selected": 0
|
||||
},
|
||||
"kea": {
|
||||
"value": "Kea DHCP",
|
||||
"selected": 1
|
||||
},
|
||||
"mdns-repeater": {
|
||||
"value": "mDNS Repeater",
|
||||
"selected": 0
|
||||
},
|
||||
"monit": {
|
||||
"value": "Monit System Monitoring",
|
||||
"selected": 0
|
||||
},
|
||||
"nat": {
|
||||
"value": "NAT",
|
||||
"selected": 1
|
||||
},
|
||||
"syslog": {
|
||||
"value": "Netflow / Insight",
|
||||
"selected": 0
|
||||
},
|
||||
"netsnmp": {
|
||||
"value": "Netsnmp",
|
||||
"selected": 0
|
||||
},
|
||||
"ntpd": {
|
||||
"value": "Network Time",
|
||||
"selected": 1
|
||||
},
|
||||
"opendns": {
|
||||
"value": "OpenDNS",
|
||||
"selected": 0
|
||||
},
|
||||
"ssh": {
|
||||
"value": "OpenSSH",
|
||||
"selected": 1
|
||||
},
|
||||
"openvpn": {
|
||||
"value": "OpenVPN",
|
||||
"selected": 0
|
||||
},
|
||||
"qemuguestagent": {
|
||||
"value": "QEMU Guest Agent",
|
||||
"selected": 1
|
||||
},
|
||||
"radvd": {
|
||||
"value": "Router Advertisements",
|
||||
"selected": 0
|
||||
},
|
||||
"shaper": {
|
||||
"value": "Shaper",
|
||||
"selected": 0
|
||||
},
|
||||
"squid": {
|
||||
"value": "Squid Web Proxy",
|
||||
"selected": 0
|
||||
},
|
||||
"staticroutes": {
|
||||
"value": "Static Routes",
|
||||
"selected": 1
|
||||
},
|
||||
"syslog-ng": {
|
||||
"value": "System logging",
|
||||
"selected": 1
|
||||
},
|
||||
"sysctl": {
|
||||
"value": "System Tunables",
|
||||
"selected": 1
|
||||
},
|
||||
"dnsresolver": {
|
||||
"value": "Unbound DNS",
|
||||
"selected": 1
|
||||
},
|
||||
"users": {
|
||||
"value": "Users and Groups",
|
||||
"selected": 1
|
||||
},
|
||||
"virtualip": {
|
||||
"value": "Virtual IPs",
|
||||
"selected": 1
|
||||
},
|
||||
"wol": {
|
||||
"value": "Wake on LAN",
|
||||
"selected": 0
|
||||
},
|
||||
"webgui": {
|
||||
"value": "Web GUI",
|
||||
"selected": 1
|
||||
},
|
||||
"wireguard": {
|
||||
"value": "WireGuard",
|
||||
"selected": 1
|
||||
},
|
||||
"zabbixagent": {
|
||||
"value": "Zabbix monitoring agent",
|
||||
"selected": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"gw-02": {
|
||||
"kea_dhcpv4_get": {
|
||||
"dhcpv4": {
|
||||
"ha": {
|
||||
"enabled": "1",
|
||||
"this_server_name": "",
|
||||
"max_unacked_clients": "2",
|
||||
"%this_server_name": "gw-02"
|
||||
}
|
||||
}
|
||||
},
|
||||
"kea_dhcpv4_searchPeer": {
|
||||
"rows": [
|
||||
{
|
||||
"uuid": "574e7b41-a5c7-4682-bc63-f4a99e07f262",
|
||||
"name": "gw",
|
||||
"role": "primary",
|
||||
"%role": "Primary",
|
||||
"url": "http://10.5.100.2:8001/"
|
||||
},
|
||||
{
|
||||
"uuid": "d6a4e812-4bc8-4713-bebb-b330ea65f587",
|
||||
"name": "gw-02",
|
||||
"role": "standby",
|
||||
"%role": "Standby",
|
||||
"url": "http://10.5.100.3:8001/"
|
||||
}
|
||||
],
|
||||
"rowCount": 2,
|
||||
"total": 2,
|
||||
"current": 1
|
||||
},
|
||||
"core_hasync_get": {
|
||||
"hasync": {
|
||||
"synchronizetoip": "",
|
||||
"syncitems": {
|
||||
"aliases": {
|
||||
"value": "Aliases",
|
||||
"selected": 0
|
||||
},
|
||||
"authservers": {
|
||||
"value": "Authentication Servers",
|
||||
"selected": 0
|
||||
},
|
||||
"captiveportal": {
|
||||
"value": "Captive Portal",
|
||||
"selected": 0
|
||||
},
|
||||
"certs": {
|
||||
"value": "Certificates and Authorities",
|
||||
"selected": 0
|
||||
},
|
||||
"cron": {
|
||||
"value": "Cron",
|
||||
"selected": 0
|
||||
},
|
||||
"ddclient": {
|
||||
"value": "ddclient",
|
||||
"selected": 0
|
||||
},
|
||||
"dhcrelay": {
|
||||
"value": "DHCRelay",
|
||||
"selected": 0
|
||||
},
|
||||
"dnsforwarder": {
|
||||
"value": "Dnsmasq DNS/DHCP",
|
||||
"selected": 0
|
||||
},
|
||||
"categories": {
|
||||
"value": "Firewall Categories",
|
||||
"selected": 0
|
||||
},
|
||||
"ifgroups": {
|
||||
"value": "Firewall Groups",
|
||||
"selected": 0
|
||||
},
|
||||
"lvtemplate": {
|
||||
"value": "Firewall Log Templates",
|
||||
"selected": 0
|
||||
},
|
||||
"rules": {
|
||||
"value": "Firewall Rules",
|
||||
"selected": 0
|
||||
},
|
||||
"schedules": {
|
||||
"value": "Firewall Schedules",
|
||||
"selected": 0
|
||||
},
|
||||
"freeradius": {
|
||||
"value": "Freeradius",
|
||||
"selected": 0
|
||||
},
|
||||
"quagga": {
|
||||
"value": "FRR",
|
||||
"selected": 0
|
||||
},
|
||||
"hostwatch": {
|
||||
"value": "Host discovery service",
|
||||
"selected": 0
|
||||
},
|
||||
"suricata": {
|
||||
"value": "Intrusion Detection",
|
||||
"selected": 0
|
||||
},
|
||||
"ipsec": {
|
||||
"value": "IPsec",
|
||||
"selected": 0
|
||||
},
|
||||
"kea": {
|
||||
"value": "Kea DHCP",
|
||||
"selected": 0
|
||||
},
|
||||
"mdns-repeater": {
|
||||
"value": "mDNS Repeater",
|
||||
"selected": 0
|
||||
},
|
||||
"monit": {
|
||||
"value": "Monit System Monitoring",
|
||||
"selected": 0
|
||||
},
|
||||
"nat": {
|
||||
"value": "NAT",
|
||||
"selected": 0
|
||||
},
|
||||
"syslog": {
|
||||
"value": "Netflow / Insight",
|
||||
"selected": 0
|
||||
},
|
||||
"netsnmp": {
|
||||
"value": "Netsnmp",
|
||||
"selected": 0
|
||||
},
|
||||
"ntpd": {
|
||||
"value": "Network Time",
|
||||
"selected": 0
|
||||
},
|
||||
"opendns": {
|
||||
"value": "OpenDNS",
|
||||
"selected": 0
|
||||
},
|
||||
"ssh": {
|
||||
"value": "OpenSSH",
|
||||
"selected": 0
|
||||
},
|
||||
"openvpn": {
|
||||
"value": "OpenVPN",
|
||||
"selected": 0
|
||||
},
|
||||
"qemuguestagent": {
|
||||
"value": "QEMU Guest Agent",
|
||||
"selected": 0
|
||||
},
|
||||
"radvd": {
|
||||
"value": "Router Advertisements",
|
||||
"selected": 0
|
||||
},
|
||||
"shaper": {
|
||||
"value": "Shaper",
|
||||
"selected": 0
|
||||
},
|
||||
"squid": {
|
||||
"value": "Squid Web Proxy",
|
||||
"selected": 0
|
||||
},
|
||||
"staticroutes": {
|
||||
"value": "Static Routes",
|
||||
"selected": 0
|
||||
},
|
||||
"syslog-ng": {
|
||||
"value": "System logging",
|
||||
"selected": 0
|
||||
},
|
||||
"sysctl": {
|
||||
"value": "System Tunables",
|
||||
"selected": 0
|
||||
},
|
||||
"dnsresolver": {
|
||||
"value": "Unbound DNS",
|
||||
"selected": 0
|
||||
},
|
||||
"users": {
|
||||
"value": "Users and Groups",
|
||||
"selected": 0
|
||||
},
|
||||
"virtualip": {
|
||||
"value": "Virtual IPs",
|
||||
"selected": 0
|
||||
},
|
||||
"wol": {
|
||||
"value": "Wake on LAN",
|
||||
"selected": 0
|
||||
},
|
||||
"webgui": {
|
||||
"value": "Web GUI",
|
||||
"selected": 0
|
||||
},
|
||||
"wireguard": {
|
||||
"value": "WireGuard",
|
||||
"selected": 0
|
||||
},
|
||||
"zabbixagent": {
|
||||
"value": "Zabbix monitoring agent",
|
||||
"selected": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
[
|
||||
{
|
||||
"identifier": "lan",
|
||||
"device": "em0",
|
||||
"description": "MGMT",
|
||||
"addr4": "192.0.2.2/24",
|
||||
"ipv4": [
|
||||
{"ipaddr": "192.0.2.2/24"},
|
||||
{"ipaddr": "192.0.2.1/24", "vhid": "108", "status": "MASTER", "advbase": "1", "advskew": "0", "peer": "224.0.0.18", "peer6": "ff02::12"}
|
||||
],
|
||||
"ipv6": [
|
||||
{"ipaddr": "fe80::1:2/64"},
|
||||
{"ipaddr": "2001:db8:8::1/64", "vhid": "108", "status": "MASTER", "advbase": "1", "advskew": "0", "peer": "224.0.0.18", "peer6": "ff02::12"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"identifier": "opt2",
|
||||
"device": "vlan0040",
|
||||
"description": "SERVER",
|
||||
"addr4": "198.51.100.2/24",
|
||||
"ipv4": [
|
||||
{"ipaddr": "198.51.100.2/24"},
|
||||
{"ipaddr": "198.51.100.140/32", "vhid": "140", "status": "MASTER", "advbase": "1", "advskew": "0", "peer": "224.0.0.18", "peer6": "ff02::12"},
|
||||
{"ipaddr": "198.51.100.1/24", "vhid": "140", "status": "MASTER", "advbase": "1", "advskew": "0", "peer": "224.0.0.18", "peer6": "ff02::12"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"identifier": "opt9",
|
||||
"device": "vlan0011",
|
||||
"description": "",
|
||||
"addr4": "203.0.113.2/24",
|
||||
"ipv4": [
|
||||
{"ipaddr": "203.0.113.2/24"},
|
||||
{"ipaddr": "203.0.113.1/24", "vhid": "111", "status": "INIT", "advbase": "1", "advskew": "0", "peer": "224.0.0.18", "peer6": "ff02::12"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"identifier": "opt3",
|
||||
"device": "vlan0020",
|
||||
"description": "IOT",
|
||||
"addr4": "192.0.2.130/25",
|
||||
"ipv4": [
|
||||
{"ipaddr": "192.0.2.130/25"},
|
||||
{"ipaddr": "192.0.2.140/32"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"identifier": "lo0",
|
||||
"device": "lo0",
|
||||
"description": "Loopback",
|
||||
"addr4": "127.0.0.1/8",
|
||||
"ipv4": [{"ipaddr": "127.0.0.1/8"}],
|
||||
"ipv6": [{"ipaddr": "::1/128"}, {"ipaddr": "fe80::1/64"}]
|
||||
},
|
||||
{
|
||||
"identifier": "wg1",
|
||||
"device": "wg1",
|
||||
"description": "WireGuard",
|
||||
"addr4": "",
|
||||
"ipv4": null
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,935 @@
|
||||
{
|
||||
"statistics": {
|
||||
"Active Internet connections": {
|
||||
"tcp4/[192.0.2.1:443-192.0.2.50:38544]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "443",
|
||||
"0": "192.0.2.1:443"
|
||||
},
|
||||
"remote": {
|
||||
"address": "192.0.2.50",
|
||||
"port": "38544",
|
||||
"0": "192.0.2.50:38544"
|
||||
},
|
||||
"receive-high-water": 65700,
|
||||
"send-high-water": 65700,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 525600,
|
||||
"send-mbuf-bytes-max": 525600,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "7199.77",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "0.02",
|
||||
"flow-id": "f6ae054e",
|
||||
"flow-type": 130,
|
||||
"user": "root",
|
||||
"command": "lighttpd",
|
||||
"pid": "46564",
|
||||
"fd": "19",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[192.0.2.1:443-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "443",
|
||||
"0": "192.0.2.1:443"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "33552.00",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "lighttpd",
|
||||
"pid": "46564",
|
||||
"fd": "11",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[198.51.100.1:443-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "198.51.100.1",
|
||||
"port": "443",
|
||||
"0": "198.51.100.1:443"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "33552.00",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "lighttpd",
|
||||
"pid": "46564",
|
||||
"fd": "10",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[127.0.0.1:443-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "127.0.0.1",
|
||||
"port": "443",
|
||||
"0": "127.0.0.1:443"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "33552.00",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "lighttpd",
|
||||
"pid": "46564",
|
||||
"fd": "7",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[192.0.2.1:80-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "80",
|
||||
"0": "192.0.2.1:80"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "33552.00",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "lighttpd",
|
||||
"pid": "46564",
|
||||
"fd": "16",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[*:8000-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "8000",
|
||||
"0": "*:8000"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "41043.28",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "www",
|
||||
"command": "lighttpd",
|
||||
"pid": "7612",
|
||||
"fd": "7",
|
||||
"proto": "tcp4",
|
||||
"listen-queue-sizes": {
|
||||
"qlen": "0",
|
||||
"incqlen": "0",
|
||||
"maxqlen": "128"
|
||||
}
|
||||
},
|
||||
"tcp6/[*:8000-*:*]": {
|
||||
"protocol": "tcp6",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "8000",
|
||||
"0": "*:8000"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "41043.28",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "www",
|
||||
"command": "lighttpd",
|
||||
"pid": "7612",
|
||||
"fd": "4",
|
||||
"proto": "tcp6",
|
||||
"listen-queue-sizes": {
|
||||
"qlen": "0",
|
||||
"incqlen": "0",
|
||||
"maxqlen": "128"
|
||||
}
|
||||
},
|
||||
"tcp4/[192.0.2.1:8080-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "8080",
|
||||
"0": "192.0.2.1:8080"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "21096.55",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "crowdsec",
|
||||
"pid": "90423",
|
||||
"fd": "26",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[127.0.0.1:6060-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "127.0.0.1",
|
||||
"port": "6060",
|
||||
"0": "127.0.0.1:6060"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "41044.32",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "crowdsec",
|
||||
"pid": "90423",
|
||||
"fd": "20",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[192.0.2.1:10050-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "10050",
|
||||
"0": "192.0.2.1:10050"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "41044.31",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "zabbix",
|
||||
"command": "zabbix_age",
|
||||
"pid": "70051",
|
||||
"fd": "5",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[192.0.2.1:22-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "22",
|
||||
"0": "192.0.2.1:22"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "41054.14",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "sshd",
|
||||
"pid": "12554",
|
||||
"fd": "6",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[127.0.0.1:22-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "127.0.0.1",
|
||||
"port": "22",
|
||||
"0": "127.0.0.1:22"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "41054.14",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "sshd",
|
||||
"pid": "12554",
|
||||
"fd": "11",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[203.0.113.1:53-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "203.0.113.1",
|
||||
"port": "53",
|
||||
"0": "203.0.113.1:53"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "9830.17",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "unbound",
|
||||
"command": "unbound",
|
||||
"pid": "10992",
|
||||
"fd": "116",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[127.0.0.1:953-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "127.0.0.1",
|
||||
"port": "953",
|
||||
"0": "127.0.0.1:953"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "9830.17",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "unbound",
|
||||
"command": "unbound",
|
||||
"pid": "10992",
|
||||
"fd": "117",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[127.0.0.1:8000-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "127.0.0.1",
|
||||
"port": "8000",
|
||||
"0": "127.0.0.1:8000"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "10006.15",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "kea-ctrl-a",
|
||||
"pid": "14979",
|
||||
"fd": "7",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"tcp4/[127.0.0.1:2604-*:*]": {
|
||||
"protocol": "tcp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "127.0.0.1",
|
||||
"port": "2604",
|
||||
"0": "127.0.0.1:2604"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 0,
|
||||
"send-high-water": 0,
|
||||
"receive-low-water": 0,
|
||||
"send-low-water": 0,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 0,
|
||||
"send-mbuf-bytes-max": 0,
|
||||
"retransmit-timer": "0.00",
|
||||
"persist-timer": "0.00",
|
||||
"keepalive-timer": "0.00",
|
||||
"msl2-timer": "0.00",
|
||||
"delay-ack-timer": "0.00",
|
||||
"inactivity-timer": "41047.92",
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "frr",
|
||||
"command": "ospfd",
|
||||
"pid": "89416",
|
||||
"fd": "11",
|
||||
"proto": "tcp4"
|
||||
},
|
||||
"udp4/[203.0.113.1:53-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "203.0.113.1",
|
||||
"port": "53",
|
||||
"0": "203.0.113.1:53"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "b8a211",
|
||||
"flow-type": 63,
|
||||
"user": "unbound",
|
||||
"command": "unbound",
|
||||
"pid": "10992",
|
||||
"fd": "115",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp4/[192.0.2.1:67-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "67",
|
||||
"0": "192.0.2.1:67"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "b899f5",
|
||||
"flow-type": 63,
|
||||
"user": "root",
|
||||
"command": "kea-dhcp4",
|
||||
"pid": "12917",
|
||||
"fd": "19",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp4/[*:123-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "123",
|
||||
"0": "*:123"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "c23b49",
|
||||
"flow-type": 63,
|
||||
"user": "root",
|
||||
"command": "ntpd",
|
||||
"pid": "69031",
|
||||
"fd": "21",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp6/[*:123-*:*]": {
|
||||
"protocol": "udp6",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "123",
|
||||
"0": "*:123"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "root",
|
||||
"command": "ntpd",
|
||||
"pid": "69031",
|
||||
"fd": "20",
|
||||
"proto": "udp6"
|
||||
},
|
||||
"udp4/[198.51.100.1:5353-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 42052,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "198.51.100.1",
|
||||
"port": "5353",
|
||||
"0": "198.51.100.1:5353"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 321536,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "13f3",
|
||||
"flow-type": 63,
|
||||
"user": "root",
|
||||
"command": "mdns-repea",
|
||||
"pid": "12222",
|
||||
"fd": "10",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp4/[*:1900-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "1900",
|
||||
"0": "*:1900"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "c27",
|
||||
"flow-type": 63,
|
||||
"user": "root",
|
||||
"command": "udpbroadca",
|
||||
"pid": "78873",
|
||||
"fd": "3",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp4/[192.0.2.1:161-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "192.0.2.1",
|
||||
"port": "161",
|
||||
"0": "192.0.2.1:161"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "130d",
|
||||
"flow-type": 63,
|
||||
"user": "root",
|
||||
"command": "snmpd",
|
||||
"pid": "53743",
|
||||
"fd": "8",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp4/[*:51821-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "51821",
|
||||
"0": "*:51821"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "945",
|
||||
"flow-type": 63,
|
||||
"user": "??",
|
||||
"command": "??",
|
||||
"pid": "??",
|
||||
"fd": "??",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp6/[*:51821-*:*]": {
|
||||
"protocol": "udp6",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "51821",
|
||||
"0": "*:51821"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "0",
|
||||
"flow-type": 0,
|
||||
"user": "??",
|
||||
"command": "??",
|
||||
"pid": "??",
|
||||
"fd": "??",
|
||||
"proto": "udp6"
|
||||
},
|
||||
"udp4/[*:29281-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "29281",
|
||||
"0": "*:29281"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "c23c01",
|
||||
"flow-type": 63,
|
||||
"user": "??",
|
||||
"command": "??",
|
||||
"pid": "??",
|
||||
"fd": "??",
|
||||
"proto": "udp4"
|
||||
},
|
||||
"udp4/[*:*-*:*]": {
|
||||
"protocol": "udp4",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"local": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"remote": {
|
||||
"address": "*",
|
||||
"port": "*",
|
||||
"0": "*:*"
|
||||
},
|
||||
"receive-high-water": 42080,
|
||||
"send-high-water": 57344,
|
||||
"receive-low-water": 1,
|
||||
"send-low-water": 2048,
|
||||
"receive-mbuf-bytes": 0,
|
||||
"send-mbuf-bytes": 0,
|
||||
"receive-mbuf-bytes-max": 336640,
|
||||
"send-mbuf-bytes-max": 458752,
|
||||
"flow-id": "1441",
|
||||
"flow-type": 63,
|
||||
"user": "_lldpd",
|
||||
"command": "lldpd",
|
||||
"pid": "72768",
|
||||
"fd": "6",
|
||||
"proto": "udp4"
|
||||
}
|
||||
},
|
||||
"Active UNIX domain sockets": {
|
||||
"fffff80016c50c80 - /var/run/configd.socket": {
|
||||
"address": "fffff80016c50c80",
|
||||
"type": "stream",
|
||||
"receive-bytes-waiting": 0,
|
||||
"send-bytes-waiting": 0,
|
||||
"vnode": "0",
|
||||
"connection": "fffff8006e7b8640",
|
||||
"first-reference": "0",
|
||||
"next-reference": "0",
|
||||
"path": "/var/run/configd.socket"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"""carp_virtual_ip: one CARP address as a virtual IP, with its holder in the reading.
|
||||
|
||||
CARP differs from vip-manager and keepalived in what the caller can see. The
|
||||
address is configured on every member, and the interface list of a firewall need
|
||||
not show it at all -- so the interfaces cannot say who holds it. CARP's own state
|
||||
can: the member in MASTER holds it, a BACKUP stands by. That is CARP protocol
|
||||
knowledge, so it lives with the driver that speaks CARP (netOrk #1121), not in
|
||||
napalm-device-types.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.virtual_ips import carp_virtual_ip
|
||||
|
||||
|
||||
def _entry(**overrides):
|
||||
fields = {
|
||||
"address": "172.22.8.1",
|
||||
"prefix_length": 24,
|
||||
"vhid": "108",
|
||||
"state": "MASTER",
|
||||
"instance": "MGMT",
|
||||
"interface": "vtnet0",
|
||||
}
|
||||
fields.update(overrides)
|
||||
return carp_virtual_ip(**fields)
|
||||
|
||||
|
||||
def test_a_master_holds_the_address():
|
||||
assert _entry() == {
|
||||
"mechanism": "carp",
|
||||
"instance": "MGMT",
|
||||
"address": "172.22.8.1",
|
||||
"prefix_length": 24,
|
||||
"interface": "vtnet0",
|
||||
"group_key": "vhid:108",
|
||||
"running": True,
|
||||
"holds": True,
|
||||
}
|
||||
|
||||
|
||||
def test_a_backup_stands_by():
|
||||
entry = _entry(state="BACKUP")
|
||||
assert entry is not None
|
||||
assert (entry["running"], entry["holds"]) == (True, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", ["INIT", "DISABLED"])
|
||||
def test_a_member_whose_carp_is_not_up_neither_runs_nor_holds(state):
|
||||
entry = _entry(state=state)
|
||||
assert entry is not None
|
||||
assert (entry["running"], entry["holds"]) == (False, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", [None, "", "SOMETHING-NEW"])
|
||||
def test_an_unknown_state_says_nothing_about_the_holder(state):
|
||||
"""None leaves the holder to the interfaces, as for the other mechanisms."""
|
||||
entry = _entry(state=state)
|
||||
assert entry is not None
|
||||
assert (entry["running"], entry["holds"]) == (None, None)
|
||||
|
||||
|
||||
def test_the_state_is_read_case_blind():
|
||||
entry = _entry(state=" master ")
|
||||
assert entry is not None
|
||||
assert entry["holds"] is True
|
||||
|
||||
|
||||
def test_the_address_is_normalised():
|
||||
entry = _entry(address="FD00::0001", prefix_length=64)
|
||||
assert entry is not None
|
||||
assert entry["address"] == "fd00::1"
|
||||
|
||||
|
||||
def test_an_address_written_with_its_prefix_takes_that_prefix():
|
||||
entry = _entry(address="10.42.100.1/24", prefix_length=None)
|
||||
assert entry is not None
|
||||
assert (entry["address"], entry["prefix_length"]) == ("10.42.100.1", 24)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", ["", "not-an-address", "10.0.0.300"])
|
||||
def test_what_is_no_address_is_no_virtual_ip(address):
|
||||
assert _entry(address=address) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix", [33, -1])
|
||||
def test_an_impossible_prefix_is_dropped(prefix):
|
||||
entry = _entry(prefix_length=prefix)
|
||||
assert entry is not None
|
||||
assert entry["prefix_length"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("vhid", [None, "", "abc"])
|
||||
def test_without_a_numeric_vhid_there_is_no_group(vhid):
|
||||
entry = _entry(vhid=vhid)
|
||||
assert entry is not None
|
||||
assert entry["group_key"] is None
|
||||
|
||||
|
||||
def test_a_vhid_given_as_a_number_groups_the_same_way():
|
||||
entry = _entry(vhid=108)
|
||||
assert entry is not None
|
||||
assert entry["group_key"] == "vhid:108"
|
||||
|
||||
|
||||
def test_an_empty_instance_falls_back_to_the_vhid():
|
||||
entry = _entry(instance="")
|
||||
assert entry is not None
|
||||
assert entry["instance"] == "vhid 108"
|
||||
@@ -0,0 +1,109 @@
|
||||
"""``get_dhcp_leases()``: an empty answer is only ever a real one (#27).
|
||||
|
||||
The getter tries Kea, then ISC DHCP, then falls back to the ARP table (rows
|
||||
with ``state: "arp"``). A caller stores the answer as the server's lease set,
|
||||
so ``[]`` must mean "a lease source answered and has no leases". When no lease
|
||||
source answered and the ARP fallback gives nothing either, the getter raises:
|
||||
an empty list there would wipe the leases the caller knows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
KEA = "/api/kea/leases4/search"
|
||||
ISC = "/api/dhcpv4/leases/searchlease"
|
||||
ARP = "/api/diagnostics/interface/get_arp"
|
||||
|
||||
KEA_ROW = {"hwaddr": "AA:BB:CC:DD:EE:01", "address": "10.0.0.11", "hostname": "nas", "state": "0"}
|
||||
ISC_ROW = {"mac": "aa:bb:cc:dd:ee:02", "address": "10.0.0.12", "ends": "1700000000"}
|
||||
ARP_ROW = {"intf": "igb0", "mac": "AA:BB:CC:DD:EE:03", "ip": "10.0.0.13", "expires": "1200"}
|
||||
|
||||
|
||||
def _driver(kea=None, isc=None, arp=None) -> OPNsenseDriver:
|
||||
"""Each source answers its value, or raises it when it is an exception."""
|
||||
|
||||
def answer(value):
|
||||
if isinstance(value, Exception):
|
||||
raise value
|
||||
return value
|
||||
|
||||
driver = OPNsenseDriver("gw-01", "user", "secret")
|
||||
driver._get = MagicMock(side_effect=lambda path: answer({KEA: kea, ARP: arp}[path]))
|
||||
driver._post = MagicMock(side_effect=lambda path, data=None: answer({ISC: isc}[path]))
|
||||
return driver
|
||||
|
||||
|
||||
def _macs(leases: list[dict]) -> list[str]:
|
||||
return [lease["mac"] for lease in leases]
|
||||
|
||||
|
||||
class TestALeaseSourceAnswers:
|
||||
def test_kea_leases_come_first(self):
|
||||
driver = _driver(kea={"rows": [KEA_ROW]}, isc=RuntimeError("404"), arp=RuntimeError("x"))
|
||||
assert _macs(driver.get_dhcp_leases()) == ["aa:bb:cc:dd:ee:01"]
|
||||
|
||||
def test_isc_leases_when_kea_has_none(self):
|
||||
driver = _driver(kea={"rows": []}, isc={"rows": [ISC_ROW]}, arp=RuntimeError("x"))
|
||||
assert _macs(driver.get_dhcp_leases()) == ["aa:bb:cc:dd:ee:02"]
|
||||
|
||||
def test_isc_leases_when_kea_fails(self):
|
||||
driver = _driver(kea=RuntimeError("404"), isc={"rows": [ISC_ROW]}, arp=RuntimeError("x"))
|
||||
assert _macs(driver.get_dhcp_leases()) == ["aa:bb:cc:dd:ee:02"]
|
||||
|
||||
|
||||
class TestTheArpFallback:
|
||||
"""No source has leases: the ARP table stands in, marked ``state: "arp"`` (#1168)."""
|
||||
|
||||
def test_when_both_lease_sources_fail(self):
|
||||
driver = _driver(kea=RuntimeError("404"), isc=RuntimeError("404"), arp=[ARP_ROW])
|
||||
leases = driver.get_dhcp_leases()
|
||||
assert leases == [
|
||||
{
|
||||
"mac": "aa:bb:cc:dd:ee:03",
|
||||
"ip": "10.0.0.13",
|
||||
"hostname": "",
|
||||
"lease_end": 0,
|
||||
"state": "arp",
|
||||
}
|
||||
]
|
||||
|
||||
def test_when_a_lease_source_answers_empty(self):
|
||||
driver = _driver(kea={"rows": []}, isc=RuntimeError("404"), arp=[ARP_ROW])
|
||||
assert [lease["state"] for lease in driver.get_dhcp_leases()] == ["arp"]
|
||||
|
||||
|
||||
class TestAnEmptyAnswer:
|
||||
"""[] only when Kea or ISC answered and has no leases."""
|
||||
|
||||
def test_kea_empty_and_no_arp_fallback(self):
|
||||
driver = _driver(kea={"rows": []}, isc=RuntimeError("404"), arp=RuntimeError("timeout"))
|
||||
assert driver.get_dhcp_leases() == []
|
||||
|
||||
def test_isc_empty_and_an_empty_arp_table(self):
|
||||
driver = _driver(kea=RuntimeError("404"), isc={"rows": []}, arp=[])
|
||||
assert driver.get_dhcp_leases() == []
|
||||
|
||||
|
||||
class TestNothingAnswered:
|
||||
"""No lease source answered and the fallback gave no rows: that is no answer."""
|
||||
|
||||
def test_all_three_fail(self):
|
||||
driver = _driver(
|
||||
kea=RuntimeError("kea down"), isc=RuntimeError("isc down"), arp=RuntimeError("arp down")
|
||||
)
|
||||
with pytest.raises(RuntimeError) as excinfo:
|
||||
driver.get_dhcp_leases()
|
||||
message = str(excinfo.value)
|
||||
assert "kea down" in message
|
||||
assert "isc down" in message
|
||||
assert "arp down" in message
|
||||
|
||||
def test_lease_sources_fail_and_the_arp_table_is_empty(self):
|
||||
driver = _driver(kea=RuntimeError("kea down"), isc=RuntimeError("isc down"), arp=[])
|
||||
with pytest.raises(RuntimeError, match="kea down"):
|
||||
driver.get_dhcp_leases()
|
||||
+629
-100
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,145 @@
|
||||
"""Kea's HA peers and the firewall's configuration sync, as facts (netOrk #1125).
|
||||
|
||||
The fixture is what gw-01 and gw-02 answered on 2026-10-16: Kea in hot standby
|
||||
(gw primary, gw-02 standby) and gw-01 pushing its configuration, Kea and
|
||||
Unbound included, to gw-02.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.ha import config_sync, dhcp_ha
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
PAIR = json.loads((Path(__file__).parent / "fixtures" / "ha_pair.json").read_text())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver() -> OPNsenseDriver:
|
||||
d = OPNsenseDriver("gw-01", "user", "secret")
|
||||
d._session = MagicMock()
|
||||
return d
|
||||
|
||||
|
||||
def _answers(node: str):
|
||||
def _get(path: str):
|
||||
return {
|
||||
"/api/kea/dhcpv4/get": PAIR[node]["kea_dhcpv4_get"],
|
||||
"/api/kea/dhcpv4/searchPeer": PAIR[node]["kea_dhcpv4_searchPeer"],
|
||||
"/api/core/hasync/get": PAIR[node]["core_hasync_get"],
|
||||
}[path]
|
||||
|
||||
return _get
|
||||
|
||||
|
||||
class TestDhcpHa:
|
||||
def test_reads_the_peers_with_their_roles(self, driver):
|
||||
driver._get = _answers("gw-01")
|
||||
|
||||
ha = driver.get_dhcp_ha()
|
||||
|
||||
assert ha["service"] == "kea-dhcp"
|
||||
assert ha["enabled"] is True
|
||||
assert ha["peers"] == [
|
||||
{"name": "gw", "role": "primary", "url": "http://10.5.100.2:8001/"},
|
||||
{"name": "gw-02", "role": "standby", "url": "http://10.5.100.3:8001/"},
|
||||
]
|
||||
|
||||
def test_names_this_server_from_the_effective_value(self, driver):
|
||||
"""`this_server_name` is empty when left at its default -- the
|
||||
hostname; the effective name is in its `%` twin."""
|
||||
driver._get = _answers("gw-02")
|
||||
|
||||
assert driver.get_dhcp_ha()["this_server"] == "gw-02"
|
||||
|
||||
def test_an_explicit_server_name_wins(self):
|
||||
ha = dhcp_ha(
|
||||
{
|
||||
"dhcpv4": {
|
||||
"ha": {"enabled": "1", "this_server_name": "left", "%this_server_name": "x"}
|
||||
}
|
||||
},
|
||||
{"rows": []},
|
||||
)
|
||||
assert ha["this_server"] == "left"
|
||||
|
||||
def test_ha_switched_off(self):
|
||||
ha = dhcp_ha({"dhcpv4": {"ha": {"enabled": "0", "this_server_name": ""}}}, {"rows": []})
|
||||
|
||||
assert ha["enabled"] is False
|
||||
assert ha["peers"] == []
|
||||
assert "this_server" not in ha
|
||||
|
||||
def test_a_peer_without_url_has_no_url_key(self):
|
||||
ha = dhcp_ha(
|
||||
{"dhcpv4": {"ha": {"enabled": "1"}}},
|
||||
{"rows": [{"name": "a", "role": "primary", "url": ""}]},
|
||||
)
|
||||
assert ha["peers"] == [{"name": "a", "role": "primary"}]
|
||||
|
||||
def test_a_failed_read_raises_and_never_says_off(self, driver):
|
||||
driver._get = MagicMock(side_effect=RuntimeError("timeout"))
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
driver.get_dhcp_ha()
|
||||
|
||||
def test_an_answer_without_the_ha_section_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
dhcp_ha({"dhcpv4": {}}, {"rows": []})
|
||||
|
||||
|
||||
class TestConfigSync:
|
||||
def test_the_pushing_side_names_its_peer_and_services(self, driver):
|
||||
driver._get = _answers("gw-01")
|
||||
|
||||
sync = driver.get_config_sync()
|
||||
|
||||
assert sync["peer"] == "10.5.100.3"
|
||||
assert {"kea-dhcp", "unbound", "ntpd", "openssh", "wireguard"} <= set(sync["services"])
|
||||
assert sync["services"] == sorted(sync["services"])
|
||||
|
||||
def test_items_without_a_service_stay_visible(self, driver):
|
||||
driver._get = _answers("gw-01")
|
||||
|
||||
unmapped = driver.get_config_sync()["unmapped"]
|
||||
|
||||
assert {"aliases", "rules", "virtualip"} <= set(unmapped)
|
||||
assert "kea" not in unmapped
|
||||
|
||||
def test_only_selected_items_count(self, driver):
|
||||
driver._get = _answers("gw-01")
|
||||
|
||||
sync = driver.get_config_sync()
|
||||
|
||||
assert "dnsmasq" not in sync["services"] # dnsforwarder: not selected
|
||||
assert "cron" not in sync["unmapped"] and "cron" not in sync["services"]
|
||||
|
||||
def test_the_receiving_side_pushes_to_no_one(self, driver):
|
||||
driver._get = _answers("gw-02")
|
||||
|
||||
sync = driver.get_config_sync()
|
||||
|
||||
assert sync == {"peer": None, "services": [], "unmapped": []}
|
||||
|
||||
def test_without_a_peer_selected_items_are_not_pushed(self):
|
||||
"""Ticked items without a target address push nothing."""
|
||||
answer = {
|
||||
"hasync": {"synchronizetoip": "", "syncitems": {"kea": {"value": "Kea", "selected": 1}}}
|
||||
}
|
||||
|
||||
assert config_sync(answer) == {"peer": None, "services": [], "unmapped": []}
|
||||
|
||||
def test_a_failed_read_raises(self, driver):
|
||||
driver._get = MagicMock(side_effect=RuntimeError("timeout"))
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
driver.get_config_sync()
|
||||
|
||||
def test_an_answer_without_the_section_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
config_sync({"something": {}})
|
||||
@@ -0,0 +1,132 @@
|
||||
"""What the firewall is called, which version it runs, and which addresses it serves.
|
||||
|
||||
``/api/core/system/status`` on OPNsense 26.7 carries neither name nor version
|
||||
(``metadata`` and ``subsystems`` only), so every firewall read as nameless and
|
||||
"unknown". ``/api/diagnostics/system/system_information`` has both: ``name`` is
|
||||
the FQDN, ``versions[0]`` reads ``"OPNsense 26.7.7-amd64"``.
|
||||
|
||||
An address bound to a CARP VHID sits on the interface of every node, in state
|
||||
MASTER or BACKUP. Only the MASTER answers for it, so only there is it one of the
|
||||
node's addresses -- the same as keepalived, where only the master has the address
|
||||
at all (netOrk #1121: a virtual IP's badge sits on its holder's interface).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
OVERVIEW = json.loads(
|
||||
(Path(__file__).parent / "fixtures" / "interfaces_overview_carp.json").read_text()
|
||||
)
|
||||
SYSTEM_INFORMATION = {
|
||||
"name": "gw-02.home.manivong.de",
|
||||
"versions": ["OPNsense 26.7.7-amd64", "FreeBSD 15.1-RELEASE-p4", "OpenSSL 3.5.9"],
|
||||
}
|
||||
STATUS_26_7 = {"metadata": {"translations": {}}, "subsystems": {}}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver() -> OPNsenseDriver:
|
||||
with patch("napalm_opnsense.opnsense.requests.Session"):
|
||||
return OPNsenseDriver(hostname="fw", username="k", password="s")
|
||||
|
||||
|
||||
def _answers(driver, system_information=SYSTEM_INFORMATION, status=STATUS_26_7, overview=OVERVIEW):
|
||||
def get(path: str):
|
||||
if path == "/api/diagnostics/system/system_information":
|
||||
if isinstance(system_information, Exception):
|
||||
raise system_information
|
||||
return system_information
|
||||
if path == "/api/core/system/status":
|
||||
return status
|
||||
if path == "/api/interfaces/overview/export":
|
||||
return overview
|
||||
raise AssertionError(f"unexpected GET {path}")
|
||||
|
||||
driver._get = get
|
||||
return driver
|
||||
|
||||
|
||||
class TestIdentity:
|
||||
def test_the_name_is_the_short_host_and_the_fqdn_the_whole(self, driver):
|
||||
facts = _answers(driver).get_facts()
|
||||
assert (facts["hostname"], facts["fqdn"]) == ("gw-02", "gw-02.home.manivong.de")
|
||||
|
||||
def test_the_version_comes_without_the_architecture(self, driver):
|
||||
assert _answers(driver).get_facts()["os_version"] == "26.7.7"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"line, version",
|
||||
[
|
||||
("OPNsense 26.7.7_1-aarch64", "26.7.7_1"),
|
||||
("OPNsense 25.1", "25.1"),
|
||||
("OPNsense 24.7.12-i386", "24.7.12"),
|
||||
],
|
||||
)
|
||||
def test_version_spellings(self, driver, line, version):
|
||||
info = {"name": "fw", "versions": [line]}
|
||||
assert _answers(driver, system_information=info).get_facts()["os_version"] == version
|
||||
|
||||
def test_a_name_without_a_domain_is_both(self, driver):
|
||||
facts = _answers(driver, system_information={"name": "fw", "versions": []}).get_facts()
|
||||
assert (facts["hostname"], facts["fqdn"]) == ("fw", "fw")
|
||||
|
||||
def test_without_system_information_the_status_answer_still_counts(self, driver):
|
||||
"""An older OPNsense, or an API key without the diagnostics privilege."""
|
||||
status = {"hostname": "opnsense01", "version": "24.7"}
|
||||
facts = _answers(driver, system_information=RuntimeError("403"), status=status).get_facts()
|
||||
assert (facts["hostname"], facts["os_version"]) == ("opnsense01", "24.7")
|
||||
|
||||
def test_nothing_known_is_empty_and_unknown(self, driver):
|
||||
facts = _answers(driver, system_information={}).get_facts()
|
||||
assert (facts["hostname"], facts["fqdn"], facts["os_version"]) == ("", "", "unknown")
|
||||
|
||||
|
||||
class TestHeldAddresses:
|
||||
def test_the_master_serves_its_carp_addresses(self, driver):
|
||||
result = _answers(driver).get_interfaces_ip()
|
||||
assert set(result["em0"]["ipv4"]) == {"192.0.2.2", "192.0.2.1"}
|
||||
assert result["em0"]["ipv4"]["192.0.2.1"] == {"prefix_length": 24}
|
||||
assert set(result["vlan0040"]["ipv4"]) == {
|
||||
"198.51.100.2",
|
||||
"198.51.100.1",
|
||||
"198.51.100.140",
|
||||
}
|
||||
|
||||
def test_a_backup_serves_its_own_address_only(self, driver):
|
||||
backup = json.loads(json.dumps(OVERVIEW).replace('"MASTER"', '"BACKUP"'))
|
||||
result = _answers(driver, overview=backup).get_interfaces_ip()
|
||||
assert set(result["em0"]["ipv4"]) == {"192.0.2.2"}
|
||||
assert set(result["vlan0040"]["ipv4"]) == {"198.51.100.2"}
|
||||
|
||||
def test_a_vhid_that_is_not_up_is_not_served(self, driver):
|
||||
result = _answers(driver).get_interfaces_ip()
|
||||
assert set(result["vlan0011"]["ipv4"]) == {"203.0.113.2"}
|
||||
|
||||
def test_a_held_ipv6_carp_address_is_served(self, driver):
|
||||
result = _answers(driver).get_interfaces_ip()
|
||||
assert "2001:db8:8::1" in result["em0"]["ipv6"]
|
||||
|
||||
def test_an_address_without_a_vhid_is_left_as_before(self, driver):
|
||||
"""Only CARP addresses are added; a plain alias is a separate question."""
|
||||
result = _answers(driver).get_interfaces_ip()
|
||||
assert set(result["vlan0020"]["ipv4"]) == {"192.0.2.130"}
|
||||
|
||||
def test_without_a_primary_address_the_list_still_leaves_out_a_backup(self, driver):
|
||||
overview = [
|
||||
{
|
||||
"device": "vlan0099",
|
||||
"ipv4": [
|
||||
{"ipaddr": "192.0.2.66/26"},
|
||||
{"ipaddr": "192.0.2.65/26", "vhid": "199", "status": "BACKUP"},
|
||||
],
|
||||
}
|
||||
]
|
||||
result = _answers(driver, overview=overview).get_interfaces_ip()
|
||||
assert set(result["vlan0099"]["ipv4"]) == {"192.0.2.66"}
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Matching Kea reservations and leases on address and MAC (#26)."""
|
||||
|
||||
from napalm_opnsense.kea_reservations import (
|
||||
lease_held,
|
||||
reservation_unchanged,
|
||||
split_by_mac,
|
||||
subnet_containing,
|
||||
)
|
||||
|
||||
|
||||
def _row(mac, uuid="u-1"):
|
||||
return {"uuid": uuid, "ip_address": "172.22.8.253", "hw_address": mac}
|
||||
|
||||
|
||||
class TestSplitByMac:
|
||||
def test_no_rows_is_neither_own_nor_other(self):
|
||||
assert split_by_mac([], "02:aa:bb:cc:dd:ee") == (None, "")
|
||||
|
||||
def test_own_row_matches_whatever_the_mac_spelling(self):
|
||||
row = _row("02-AA-BB-CC-DD-EE")
|
||||
assert split_by_mac([row], "02:aa:bb:cc:dd:ee") == (row, "")
|
||||
|
||||
def test_another_hosts_row_is_reported_by_its_mac(self):
|
||||
assert split_by_mac([_row("02-11-22-33-44-55")], "02:aa:bb:cc:dd:ee") == (
|
||||
None,
|
||||
"02:11:22:33:44:55",
|
||||
)
|
||||
|
||||
def test_a_row_without_mac_is_no_ones(self):
|
||||
"""It cannot be shown to be the caller's, so it is never taken as such."""
|
||||
row = {"uuid": "u-1", "ip_address": "172.22.8.253"}
|
||||
assert split_by_mac([row], "02:aa:bb:cc:dd:ee") == (None, "")
|
||||
|
||||
def test_another_hosts_mac_is_found_behind_a_row_without_one(self):
|
||||
rows = [{"uuid": "u-0", "ip_address": "172.22.8.253"}, _row("02:11:22:33:44:55")]
|
||||
assert split_by_mac(rows, "02:aa:bb:cc:dd:ee") == (None, "02:11:22:33:44:55")
|
||||
|
||||
|
||||
class TestLeaseHeld:
|
||||
def test_os_kea_lease_of_the_mac(self):
|
||||
rows = [{"address": "172.22.8.253", "hwaddr": "02:AA:BB:CC:DD:EE"}]
|
||||
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is True
|
||||
|
||||
def test_plain_kea_lease_of_the_mac(self):
|
||||
rows = [{"ip-address": "172.22.8.253", "hw-address": "02:aa:bb:cc:dd:ee"}]
|
||||
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is True
|
||||
|
||||
def test_lease_of_another_mac(self):
|
||||
rows = [{"address": "172.22.8.253", "hwaddr": "02:11:22:33:44:55"}]
|
||||
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is False
|
||||
|
||||
def test_lease_of_another_address(self):
|
||||
rows = [{"address": "172.22.8.254", "hwaddr": "02:aa:bb:cc:dd:ee"}]
|
||||
assert lease_held(rows, "172.22.8.253", "02:aa:bb:cc:dd:ee") is False
|
||||
|
||||
|
||||
class TestReservationUnchanged:
|
||||
WANTED = {
|
||||
"subnet": "subnet-uuid",
|
||||
"ip_address": "172.22.8.253",
|
||||
"hw_address": "02:aa:bb:cc:dd:ee",
|
||||
"hostname": "new-vm",
|
||||
"description": "[netork]",
|
||||
}
|
||||
|
||||
def test_a_different_mac_is_a_change(self):
|
||||
row = dict(self.WANTED, hw_address="02:11:22:33:44:55")
|
||||
assert reservation_unchanged(row, self.WANTED, "172.22.8.0/24") is False
|
||||
|
||||
def test_the_same_reservation_is_unchanged(self):
|
||||
row = dict(self.WANTED, hw_address="02-AA-BB-CC-DD-EE", subnet="172.22.8.0/24")
|
||||
assert reservation_unchanged(row, self.WANTED, "172.22.8.0/24") is True
|
||||
|
||||
|
||||
class TestSubnetContaining:
|
||||
ROWS = [
|
||||
{"uuid": "s-broken", "subnet": "not-a-cidr"},
|
||||
{"uuid": "s-nocidr"},
|
||||
{"uuid": "s-8", "subnet": " 172.22.8.0/24 "},
|
||||
{"uuid": "s-wide", "subnet": "172.22.0.0/16"},
|
||||
]
|
||||
|
||||
def test_first_subnet_holding_the_address_wins(self):
|
||||
assert subnet_containing(self.ROWS, "172.22.8.253") == self.ROWS[2]
|
||||
|
||||
def test_rows_without_a_readable_subnet_are_skipped(self):
|
||||
assert subnet_containing(self.ROWS, "172.22.9.1") == self.ROWS[3]
|
||||
|
||||
def test_none_when_no_subnet_holds_the_address(self):
|
||||
assert subnet_containing(self.ROWS, "10.99.99.99") is None
|
||||
@@ -0,0 +1,147 @@
|
||||
"""What listens on an OPNsense firewall, and which OPNsense service it is (netOrk #673).
|
||||
|
||||
OPNsense answers through its API, ``diagnostics/interface/get_socket_statistics``:
|
||||
netstat's sockets with sockstat's user, command and PID merged in, read by configd
|
||||
as root. A socket that listens has no peer (``*:*``). Which service holds it comes
|
||||
from the command -- cut to ten characters by FreeBSD -- matched against the
|
||||
firewall's own service list; WireGuard's sockets belong to the kernel and are
|
||||
told by their port.
|
||||
|
||||
The fixture is a real OPNsense 26.7.5 firewall's answer, cut down, with
|
||||
documentation addresses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
STATISTICS = json.loads((Path(__file__).parent / "fixtures" / "socket_statistics.json").read_text())
|
||||
SERVICES = [
|
||||
"acme", "captiveportal", "configd", "cron", "crowdsec", "frr", "kea-dhcp", "lldpd",
|
||||
"login", "mdns-repeater", "ntpd", "openssh", "pf", "snmpd", "udpbroadcastrelay",
|
||||
"unbound", "webgui", "wireguard", "zabbix_agentd",
|
||||
] # fmt: skip
|
||||
WIREGUARD = {
|
||||
"rows": [
|
||||
{"if": "wg1", "type": "interface", "listen-port": "51821", "status": "up"},
|
||||
{"if": "wg1", "type": "peer", "allowed-ips": "10.99.99.2/32"},
|
||||
{"if": "wg2", "type": "interface", "listen-port": "29281", "status": "up"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _driver(services=SERVICES, wireguard=WIREGUARD) -> OPNsenseDriver:
|
||||
with patch("napalm_opnsense.opnsense.requests.Session"):
|
||||
drv = OPNsenseDriver(hostname="fw", username="k", password="s")
|
||||
drv.session = MagicMock()
|
||||
|
||||
def get(path: str) -> dict:
|
||||
if path == "/api/diagnostics/interface/get_socket_statistics":
|
||||
return STATISTICS
|
||||
if path == "/api/core/service/search":
|
||||
return {"rows": [{"id": n, "name": n, "running": 1} for n in services]}
|
||||
if path == "/api/wireguard/service/show":
|
||||
if isinstance(wireguard, Exception):
|
||||
raise wireguard
|
||||
return wireguard
|
||||
raise AssertionError(f"unexpected GET {path}")
|
||||
|
||||
drv._get = get # type: ignore[method-assign]
|
||||
return drv
|
||||
|
||||
|
||||
def _sockets(drv: OPNsenseDriver | None = None) -> dict:
|
||||
reading = (drv or _driver()).get_listening_sockets()
|
||||
return {(s["proto"], s["port"], s["address"]): s for s in reading["sockets"]}
|
||||
|
||||
|
||||
class TestTheReading:
|
||||
def test_read_as_root(self):
|
||||
assert _driver().get_listening_sockets()["attributed"] is True
|
||||
|
||||
def test_a_socket_comes_with_its_process_and_service(self):
|
||||
assert _sockets()[("tcp", 8080, "192.0.2.1")] == {
|
||||
"proto": "tcp",
|
||||
"address": "192.0.2.1",
|
||||
"port": 8080,
|
||||
"interface": None,
|
||||
"process": "crowdsec",
|
||||
"pid": 90423,
|
||||
"unit": "crowdsec",
|
||||
"container_id": None,
|
||||
}
|
||||
|
||||
def test_only_what_listens(self):
|
||||
"""A connection has a peer; a socket without a port listens on nothing."""
|
||||
sockets = _driver().get_listening_sockets()["sockets"]
|
||||
|
||||
assert len(sockets) == 25
|
||||
assert all(s["port"] > 0 for s in sockets)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"proto, port, address",
|
||||
[
|
||||
("tcp", 8000, "0.0.0.0"),
|
||||
("tcp", 8000, "::"),
|
||||
("udp", 123, "0.0.0.0"),
|
||||
("udp", 123, "::"),
|
||||
],
|
||||
)
|
||||
def test_every_address_of_a_family_is_its_any_address(self, proto, port, address):
|
||||
assert (proto, port, address) in _sockets()
|
||||
|
||||
def test_sorted_by_protocol_port_and_address(self):
|
||||
sockets = _driver().get_listening_sockets()["sockets"]
|
||||
keys = [(s["proto"], s["port"], s["address"]) for s in sockets]
|
||||
|
||||
assert keys == sorted(keys)
|
||||
|
||||
|
||||
class TestWhichService:
|
||||
@pytest.mark.parametrize(
|
||||
"proto, port, address, service",
|
||||
[
|
||||
("tcp", 22, "192.0.2.1", "openssh"),
|
||||
("tcp", 443, "192.0.2.1", "webgui"),
|
||||
("tcp", 8000, "0.0.0.0", "captiveportal"), # lighttpd as www
|
||||
("udp", 67, "192.0.2.1", "kea-dhcp"), # kea-dhcp4
|
||||
("tcp", 8000, "127.0.0.1", "kea-dhcp"), # kea-ctrl-agent, cut short
|
||||
("tcp", 2604, "127.0.0.1", "frr"), # ospfd
|
||||
("udp", 5353, "198.51.100.1", "mdns-repeater"), # cut short
|
||||
("udp", 1900, "0.0.0.0", "udpbroadcastrelay"),
|
||||
("tcp", 10050, "192.0.2.1", "zabbix_agentd"),
|
||||
("udp", 53, "203.0.113.1", "unbound"),
|
||||
("udp", 123, "0.0.0.0", "ntpd"),
|
||||
],
|
||||
)
|
||||
def test_by_its_command(self, proto, port, address, service):
|
||||
assert _sockets()[(proto, port, address)]["unit"] == service
|
||||
|
||||
def test_the_command_stays_as_reported(self):
|
||||
assert _sockets()[("udp", 5353, "198.51.100.1")]["process"] == "mdns-repea"
|
||||
|
||||
def test_a_service_the_firewall_does_not_list_is_none(self):
|
||||
without_snmpd = [n for n in SERVICES if n != "snmpd"]
|
||||
|
||||
assert _sockets(_driver(services=without_snmpd))[("udp", 161, "192.0.2.1")]["unit"] is None
|
||||
|
||||
def test_wireguard_s_kernel_sockets_by_their_port(self):
|
||||
wg = _sockets()[("udp", 51821, "0.0.0.0")]
|
||||
|
||||
assert (wg["process"], wg["pid"], wg["unit"]) == (None, None, "wireguard")
|
||||
|
||||
def test_without_wireguard_a_kernel_socket_is_nobody_s(self):
|
||||
sockets = _sockets(_driver(wireguard=RuntimeError("404")))
|
||||
|
||||
assert sockets[("udp", 29281, "0.0.0.0")]["unit"] is None
|
||||
|
||||
|
||||
def test_netork_finds_it():
|
||||
"""netOrk asks ``hasattr(driver, "get_listening_sockets")``."""
|
||||
assert hasattr(OPNsenseDriver, "get_listening_sockets")
|
||||
@@ -6,11 +6,11 @@ has to be stopped and removed again. These tests drive that whole lifecycle
|
||||
against a fake ``_get`` / ``_post``.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fake API
|
||||
@@ -28,11 +28,11 @@ class FakePingAPI:
|
||||
#: to assume one, which is why nothing caught the payload going to the
|
||||
#: wrong node.
|
||||
self.model_path = tuple(model_path)
|
||||
self.created = [] # payloads passed to set
|
||||
self.started = [] # job ids passed to start
|
||||
self.stopped = [] # job ids passed to stop
|
||||
self.removed = [] # job ids passed to remove
|
||||
self.jobs = {} # job id -> hostname
|
||||
self.created = [] # payloads passed to set
|
||||
self.started = [] # job ids passed to start
|
||||
self.stopped = [] # job ids passed to stop
|
||||
self.removed = [] # job ids passed to remove
|
||||
self.jobs = {} # job id -> hostname
|
||||
self.search_calls = 0
|
||||
self._next_id = 0
|
||||
|
||||
|
||||
@@ -112,7 +112,10 @@ class TestWhereItGoes:
|
||||
assert entry["internal_ip"] == "10.0.0.9"
|
||||
|
||||
def test_an_alias_with_two_hosts_is_two_forwards(self):
|
||||
assert [e["internal_ip"] for e in _read(_rule(target="web_pair"))] == ["10.0.0.5", "10.0.0.6"]
|
||||
assert [e["internal_ip"] for e in _read(_rule(target="web_pair"))] == [
|
||||
"10.0.0.5",
|
||||
"10.0.0.6",
|
||||
]
|
||||
|
||||
def test_an_alias_that_names_a_host_by_dns_is_skipped(self):
|
||||
"""No address to put the forward on; guessing one would be worse."""
|
||||
@@ -129,7 +132,14 @@ class TestWhereItGoes:
|
||||
class TestPorts:
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[("443", 443), ("https", 443), ("http", 80), ("postgres", 5432), ("8000-8010", 8000), ("8000:8010", 8000)],
|
||||
[
|
||||
("443", 443),
|
||||
("https", 443),
|
||||
("http", 80),
|
||||
("postgres", 5432),
|
||||
("8000-8010", 8000),
|
||||
("8000:8010", 8000),
|
||||
],
|
||||
)
|
||||
def test_the_external_port(self, value, expected):
|
||||
(entry,) = _read(_rule(**{"destination.port": value}))
|
||||
@@ -173,7 +183,7 @@ class TestNameAndSource:
|
||||
assert "remote_host" not in entry
|
||||
|
||||
def test_an_inverted_source_has_no_remote_host(self):
|
||||
""""Everyone but X" is as good as anyone for whether it is reachable."""
|
||||
""" "Everyone but X" is as good as anyone for whether it is reachable."""
|
||||
(entry,) = _read(_rule(**{"source.network": "203.0.113.7", "source.not": "1"}))
|
||||
assert "remote_host" not in entry
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
"""What netOrk reached through ``_get``/``_post``, as public methods (netOrk #1113).
|
||||
|
||||
netOrk followed the firmware upgrade, edited Unbound's forwards and read FRR's
|
||||
OSPF state through this driver's private REST helpers. The contracts are
|
||||
napalm-device-types 4.17's; the OPNsense API calls and FRR's field names stay
|
||||
here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
|
||||
@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 TestUpdateProgress:
|
||||
@pytest.mark.parametrize(
|
||||
"status, state",
|
||||
[
|
||||
("running", "running"),
|
||||
("done", "done"),
|
||||
("error", "failed"),
|
||||
("", "idle"),
|
||||
(None, "idle"),
|
||||
],
|
||||
)
|
||||
def test_the_upgrade_status_as_a_state(self, driver, status, state):
|
||||
st = {"status": status, "log": "***GOT REQUEST TO UPGRADE***\nfetching\n"}
|
||||
with patch.object(driver, "_get", return_value=st) as get:
|
||||
progress = driver.get_update_progress()
|
||||
|
||||
get.assert_called_once_with("/api/core/firmware/upgradestatus")
|
||||
assert progress == {"state": state, "log": "***GOT REQUEST TO UPGRADE***\nfetching\n"}
|
||||
|
||||
def test_the_packages_go_with_the_upgrade(self, driver):
|
||||
"""netOrk named the packages it upgrades; ``apply_updates`` dropped them."""
|
||||
with patch.object(driver, "_post", return_value={"status": "ok"}) as post:
|
||||
result = driver.apply_updates(["opnsense", "openssl"])
|
||||
|
||||
post.assert_called_once_with(
|
||||
"/api/core/firmware/upgrade", {"upgrade_packages": ["opnsense", "openssl"]}
|
||||
)
|
||||
assert result["success"] is True
|
||||
|
||||
def test_no_packages_is_the_whole_upgrade(self, driver):
|
||||
with patch.object(driver, "_post", return_value={"status": "ok"}) as post:
|
||||
driver.apply_updates([])
|
||||
|
||||
post.assert_called_once_with("/api/core/firmware/upgrade")
|
||||
|
||||
|
||||
ROWS = [
|
||||
{
|
||||
"uuid": "u1",
|
||||
"enabled": "1",
|
||||
"type": "forward",
|
||||
"domain": "lab.example",
|
||||
"server": "10.0.0.53",
|
||||
"port": "53",
|
||||
},
|
||||
{
|
||||
"uuid": "u2",
|
||||
"enabled": "0",
|
||||
"type": "forward",
|
||||
"domain": "old.example",
|
||||
"server": "10.0.0.9",
|
||||
"port": "",
|
||||
},
|
||||
{"uuid": "u3", "enabled": "1", "type": "dot", "domain": "", "server": "9.9.9.9", "port": "853"},
|
||||
]
|
||||
|
||||
|
||||
class TestDnsForwards:
|
||||
def _post(self, calls):
|
||||
def post(path, data=None):
|
||||
calls.append((path, data))
|
||||
if path.endswith("searchForward"):
|
||||
return {"rows": ROWS}
|
||||
return {"result": "saved", "status": "ok"}
|
||||
|
||||
return post
|
||||
|
||||
def test_the_forwards_without_dns_over_tls(self, driver):
|
||||
calls = []
|
||||
with patch.object(driver, "_post", side_effect=self._post(calls)):
|
||||
forwards = driver.get_dns_forwards()
|
||||
|
||||
assert forwards == [
|
||||
{"domain": "lab.example", "server": "10.0.0.53", "port": 53, "enabled": True},
|
||||
{"domain": "old.example", "server": "10.0.0.9", "port": 53, "enabled": False},
|
||||
]
|
||||
|
||||
def test_a_new_domain_is_added_and_applied(self, driver):
|
||||
calls = []
|
||||
with patch.object(driver, "_post", side_effect=self._post(calls)):
|
||||
driver.set_dns_forward("new.example.", "10.0.0.53")
|
||||
|
||||
paths = [p for p, _ in calls]
|
||||
assert paths[-2:] == [
|
||||
"/api/unbound/settings/addForward",
|
||||
"/api/unbound/service/reconfigure",
|
||||
]
|
||||
added = calls[-2][1]["dot"]
|
||||
assert added == {
|
||||
"enabled": "1",
|
||||
"type": "forward",
|
||||
"domain": "new.example",
|
||||
"server": "10.0.0.53",
|
||||
"port": "53",
|
||||
}
|
||||
|
||||
def test_a_known_domain_is_changed_not_doubled(self, driver):
|
||||
calls = []
|
||||
with patch.object(driver, "_post", side_effect=self._post(calls)):
|
||||
driver.set_dns_forward("lab.example", "10.0.0.54", port=5353)
|
||||
|
||||
paths = [p for p, _ in calls]
|
||||
assert "/api/unbound/settings/setForward/u1" in paths
|
||||
assert "/api/unbound/settings/addForward" not in paths
|
||||
|
||||
def test_a_refusal_is_raised(self, driver):
|
||||
def post(path, data=None):
|
||||
if path.endswith("searchForward"):
|
||||
return {"rows": []}
|
||||
return {"result": "failed", "validations": {"dot.server": "invalid"}}
|
||||
|
||||
with (
|
||||
patch.object(driver, "_post", side_effect=post),
|
||||
pytest.raises(RuntimeError, match="invalid"),
|
||||
):
|
||||
driver.set_dns_forward("x.example", "not-an-ip")
|
||||
|
||||
def test_removing_deletes_every_forward_of_the_domain(self, driver):
|
||||
calls = []
|
||||
with patch.object(driver, "_post", side_effect=self._post(calls)):
|
||||
driver.remove_dns_forward("lab.example.")
|
||||
|
||||
paths = [p for p, _ in calls]
|
||||
assert paths[-2:] == [
|
||||
"/api/unbound/settings/delForward/u1",
|
||||
"/api/unbound/service/reconfigure",
|
||||
]
|
||||
|
||||
def test_removing_an_unknown_domain_changes_nothing(self, driver):
|
||||
calls = []
|
||||
with patch.object(driver, "_post", side_effect=self._post(calls)):
|
||||
driver.remove_dns_forward("nothing.example")
|
||||
|
||||
assert [p for p, _ in calls] == ["/api/unbound/settings/searchForward"]
|
||||
|
||||
|
||||
OVERVIEW = {"response": {"routerId": "10.255.0.1", "areas": {"0.0.0.0": {}, "0.0.0.1": {}}}}
|
||||
INTERFACES = {
|
||||
"response": {
|
||||
"interfaces": {
|
||||
"wg0": {
|
||||
"ipAddress": "10.255.0.1",
|
||||
"ipAddressPrefixlen": 24,
|
||||
"area": "0.0.0.0",
|
||||
"networkType": "POINTOPOINT",
|
||||
"authentication": "MessageDigest",
|
||||
"nbrCount": 2,
|
||||
"nbrAdjacentCount": 1,
|
||||
"cost": 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class TestOspf:
|
||||
def test_frr_in_neutral_terms(self, driver):
|
||||
def get(path):
|
||||
return OVERVIEW if path.endswith("ospfoverview") else INTERFACES
|
||||
|
||||
with patch.object(driver, "_get", side_effect=get):
|
||||
ospf = driver.get_ospf()
|
||||
|
||||
assert ospf == {
|
||||
"router_id": "10.255.0.1",
|
||||
"areas": ["0.0.0.0", "0.0.0.1"],
|
||||
"interfaces": {
|
||||
"wg0": {
|
||||
"address": "10.255.0.1",
|
||||
"prefix_length": 24,
|
||||
"area": "0.0.0.0",
|
||||
"network_type": "POINTOPOINT",
|
||||
"authentication": "MessageDigest",
|
||||
"neighbors": 2,
|
||||
"neighbors_adjacent": 1,
|
||||
"cost": 10,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
def test_no_ospf_running(self, driver):
|
||||
with patch.object(driver, "_get", return_value={"response": {}}):
|
||||
assert driver.get_ospf() == {"router_id": None, "areas": [], "interfaces": {}}
|
||||
@@ -0,0 +1,495 @@
|
||||
"""Scheduled jobs on OPNsense: the cron jobs of config.xml, over the REST API (#43).
|
||||
|
||||
OPNsense keeps its cron jobs in its configuration (``System > Settings > Cron``)
|
||||
and runs each as a configd action. ``/api/cron/settings/get`` answers with every
|
||||
job, the action as the option its ``command`` list has selected;
|
||||
``get_job`` without a uuid is a blank job, and its ``command`` options are the
|
||||
actions configd offers. The fixtures are synthetic, in the shape of an OPNsense
|
||||
26.7 answer: an admin's job, one the intrusion detection registered (origin
|
||||
``IDS``), one an application wrote, one with parameters, and one whose marker
|
||||
names no valid job.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import ScheduledJobsMixin
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobRefused,
|
||||
job_digest,
|
||||
)
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
SETTINGS = json.loads((FIXTURES / "cron_settings_get.json").read_text())
|
||||
BLANK_JOB = json.loads((FIXTURES / "cron_settings_get_job.json").read_text())
|
||||
|
||||
ADMIN = "opnsense:0b6e3c52-6a1e-4c7a-9a0e-2f0a1d6c3b11"
|
||||
PLATFORM = "opnsense:1f2d8e04-93b7-4f4e-8c55-7d1e0c9a2b22"
|
||||
OWN = "opnsense:2a7c9b16-4d3e-4b8f-a1c2-5e6f7a8b9c33"
|
||||
OWN_UUID = OWN.removeprefix("opnsense:")
|
||||
WITH_PARAMETERS = "opnsense:3c8d0e27-5f4a-4c9b-b2d3-6f7a8b9c0d44"
|
||||
BAD_MARKER = "opnsense:4d9e1f38-6a5b-4dac-83e4-7a8b9c0d1e55"
|
||||
|
||||
SAVED = {"result": "saved"}
|
||||
RELOADED = {"status": "ok"}
|
||||
|
||||
|
||||
class Firewall:
|
||||
"""Answers the cron API as a firewall would, and records every POST."""
|
||||
|
||||
def __init__(self, settings=SETTINGS, blank=BLANK_JOB, answers=None):
|
||||
self.settings = copy.deepcopy(settings)
|
||||
self.blank = blank
|
||||
self.answers = answers or {}
|
||||
self.posts: list[tuple[str, dict | None]] = []
|
||||
|
||||
def get(self, path: str):
|
||||
if path == "/api/cron/settings/get":
|
||||
return self.settings
|
||||
if path == "/api/cron/settings/get_job":
|
||||
return self.blank
|
||||
raise AssertionError(f"unexpected GET {path}")
|
||||
|
||||
def post(self, path: str, data=None):
|
||||
self.posts.append((path, data))
|
||||
for prefix, answer in self.answers.items():
|
||||
if path.startswith(prefix):
|
||||
return answer
|
||||
if path == "/api/cron/service/reconfigure":
|
||||
return RELOADED
|
||||
if path.startswith("/api/cron/settings/toggle_job/"):
|
||||
return {"result": "Enabled" if path.endswith("/1") else "Disabled", "changed": True}
|
||||
if path.startswith("/api/cron/settings/del_job/"):
|
||||
return {"result": "deleted"}
|
||||
if path == "/api/cron/settings/add_job":
|
||||
return {"result": "saved", "uuid": "5eaf2049-7b6c-4ebd-94f5-8b9c0d1e2f66"}
|
||||
if path.startswith("/api/cron/settings/set_job/"):
|
||||
return SAVED
|
||||
raise AssertionError(f"unexpected POST {path}")
|
||||
|
||||
@property
|
||||
def paths(self) -> list[str]:
|
||||
return [path for path, _ in self.posts]
|
||||
|
||||
|
||||
def _driver(firewall: Firewall) -> OPNsenseDriver:
|
||||
with patch("napalm_opnsense.opnsense.requests.Session"):
|
||||
drv = OPNsenseDriver(hostname="fw", username="k", password="s")
|
||||
drv.session = MagicMock()
|
||||
drv._get = firewall.get # type: ignore[method-assign]
|
||||
drv._post = firewall.post # type: ignore[method-assign]
|
||||
return drv
|
||||
|
||||
|
||||
def _jobs(firewall: Firewall | None = None) -> dict[str, dict]:
|
||||
reading = _driver(firewall or Firewall()).get_scheduled_jobs()
|
||||
return {job["key"]: job for job in reading["jobs"]}
|
||||
|
||||
|
||||
def _digest(key: str) -> str:
|
||||
return _jobs()[key]["digest"]
|
||||
|
||||
|
||||
def _spec(**over) -> dict:
|
||||
spec = {
|
||||
"name": "alias-refresh",
|
||||
"schedule": "*/30 * * * *",
|
||||
"run_as": "root",
|
||||
"command": "filter refresh_aliases",
|
||||
"enabled": True,
|
||||
"description": "Keep the aliases fresh",
|
||||
}
|
||||
spec.update(over)
|
||||
return spec
|
||||
|
||||
|
||||
def test_the_driver_offers_every_verb():
|
||||
assert issubclass(OPNsenseDriver, ScheduledJobsMixin)
|
||||
for verb in (
|
||||
"get_scheduled_jobs",
|
||||
"manage_scheduled_job",
|
||||
"put_scheduled_job",
|
||||
"delete_scheduled_job",
|
||||
"get_scheduled_job_commands",
|
||||
):
|
||||
assert callable(getattr(OPNsenseDriver, verb))
|
||||
|
||||
|
||||
class TestReading:
|
||||
def test_every_job_of_the_configuration(self):
|
||||
reading = _driver(Firewall()).get_scheduled_jobs()
|
||||
|
||||
assert reading["time_zone"] is None
|
||||
assert [job["key"] for job in reading["jobs"]] == [
|
||||
ADMIN,
|
||||
PLATFORM,
|
||||
OWN,
|
||||
WITH_PARAMETERS,
|
||||
BAD_MARKER,
|
||||
]
|
||||
|
||||
def test_an_admins_job(self):
|
||||
job = _jobs()[ADMIN]
|
||||
|
||||
assert job == {
|
||||
"key": ADMIN,
|
||||
"kind": "cron",
|
||||
"source": "config.xml",
|
||||
"run_as": "root",
|
||||
"schedule": "0 3 * * 1-5",
|
||||
"schedule_kind": "cron",
|
||||
"command": "system remote backup",
|
||||
"enabled": True,
|
||||
"managed_by": "admin",
|
||||
"actions": ["enable", "disable"],
|
||||
"description": "Nightly configuration backup",
|
||||
"digest": job["digest"],
|
||||
}
|
||||
assert job["digest"] == job_digest(job)
|
||||
|
||||
def test_a_job_another_service_registered_is_the_platforms(self):
|
||||
job = _jobs()[PLATFORM]
|
||||
|
||||
assert (job["managed_by"], job["enabled"], job["command"]) == (
|
||||
"platform",
|
||||
False,
|
||||
"ids update",
|
||||
)
|
||||
assert job["actions"] == ["enable", "disable"]
|
||||
|
||||
def test_a_job_an_application_wrote_carries_its_name(self):
|
||||
job = _jobs()[OWN]
|
||||
|
||||
assert job["managed_by"] == "application"
|
||||
assert job["name"] == "dnsbl-refresh"
|
||||
assert job["description"] == "Refresh the DNS blocklists"
|
||||
assert job["actions"] == ["enable", "disable", "edit", "delete"]
|
||||
|
||||
def test_a_marker_without_a_valid_name_is_an_admins_job(self):
|
||||
job = _jobs()[BAD_MARKER]
|
||||
|
||||
assert job["managed_by"] == "admin"
|
||||
assert "name" not in job
|
||||
assert job["description"] == "napalm-scheduled-job: Not_A_Name written by hand"
|
||||
|
||||
def test_a_marker_on_another_services_job_is_still_the_platforms(self):
|
||||
firewall = Firewall()
|
||||
node = firewall.settings["job"]["jobs"]["job"][PLATFORM.removeprefix("opnsense:")]
|
||||
node["description"] = "napalm-scheduled-job: ids-update taken over"
|
||||
|
||||
job = _jobs(firewall)[PLATFORM]
|
||||
|
||||
assert job["managed_by"] == "platform"
|
||||
assert "name" not in job
|
||||
|
||||
def test_the_parameters_follow_the_action(self):
|
||||
assert _jobs()[WITH_PARAMETERS]["command"] == "filter refresh_aliases --quiet --all"
|
||||
|
||||
def test_a_job_with_no_description_has_none(self):
|
||||
firewall = Firewall()
|
||||
firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["description"] = ""
|
||||
|
||||
assert "description" not in _jobs(firewall)[ADMIN]
|
||||
|
||||
def test_an_action_configd_no_longer_offers_reads_as_no_command(self):
|
||||
firewall = Firewall()
|
||||
node = firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]
|
||||
node["command"] = {k: {**v, "selected": 0} for k, v in node["command"].items()}
|
||||
|
||||
assert _jobs(firewall)[ADMIN]["command"] == ""
|
||||
|
||||
def test_a_command_given_as_a_plain_value_is_taken_as_it_is(self):
|
||||
firewall = Firewall()
|
||||
node = firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]
|
||||
node["command"] = "system remote backup"
|
||||
|
||||
assert _jobs(firewall)[ADMIN]["command"] == "system remote backup"
|
||||
|
||||
def test_enabling_a_job_changes_its_digest(self):
|
||||
firewall = Firewall()
|
||||
firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["enabled"] = "0"
|
||||
|
||||
assert _jobs(firewall)[ADMIN]["digest"] != _digest(ADMIN)
|
||||
|
||||
def test_no_jobs_is_an_empty_list(self):
|
||||
firewall = Firewall(settings={"job": {"jobs": {"job": []}}})
|
||||
|
||||
assert _driver(firewall).get_scheduled_jobs()["jobs"] == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"answer",
|
||||
[{}, [], {"job": {}}, {"job": {"jobs": {}}}, {"job": {"jobs": {"job": "x"}}}],
|
||||
)
|
||||
def test_an_answer_without_the_jobs_raises(self, answer):
|
||||
with pytest.raises(ValueError, match="jobs"):
|
||||
_driver(Firewall(settings=answer)).get_scheduled_jobs()
|
||||
|
||||
def test_a_job_without_its_schedule_raises(self):
|
||||
firewall = Firewall()
|
||||
del firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["hours"]
|
||||
|
||||
with pytest.raises(ValueError, match="schedule"):
|
||||
_driver(firewall).get_scheduled_jobs()
|
||||
|
||||
|
||||
class TestCommands:
|
||||
def test_the_actions_configd_offers(self):
|
||||
commands = _driver(Firewall()).get_scheduled_job_commands()
|
||||
|
||||
assert commands[0] == {
|
||||
"command": "filter refresh_aliases",
|
||||
"description": "Update and reload firewall aliases",
|
||||
}
|
||||
assert [c["command"] for c in commands] == [
|
||||
"filter refresh_aliases",
|
||||
"firmware auto-update",
|
||||
"ids update",
|
||||
"system ha_reconfigure_backup",
|
||||
"system remote backup",
|
||||
"unbound dnsbl",
|
||||
]
|
||||
|
||||
def test_the_blank_placeholder_is_no_action(self):
|
||||
blank = copy.deepcopy(BLANK_JOB)
|
||||
blank["job"]["command"][""] = {"value": "None", "selected": 1}
|
||||
|
||||
commands = _driver(Firewall(blank=blank)).get_scheduled_job_commands()
|
||||
|
||||
assert "" not in [c["command"] for c in commands]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"answer", [{}, [], {"job": []}, {"job": {"command": {}}}, {"job": {"command": "x"}}]
|
||||
)
|
||||
def test_no_actions_raises(self, answer):
|
||||
# configd that did not answer leaves the list empty: that is no reading.
|
||||
with pytest.raises(ValueError, match="configd"):
|
||||
_driver(Firewall(blank=answer)).get_scheduled_job_commands()
|
||||
|
||||
|
||||
class TestManage:
|
||||
@pytest.mark.parametrize(
|
||||
"action, flag, word", [("enable", "1", "enabled"), ("disable", "0", "disabled")]
|
||||
)
|
||||
def test_switching_a_job_toggles_it_and_reloads_cron(self, action, flag, word):
|
||||
firewall = Firewall()
|
||||
|
||||
result = _driver(firewall).manage_scheduled_job(PLATFORM, action, digest=_digest(PLATFORM))
|
||||
|
||||
assert result == {"success": True, "output": f"{PLATFORM} {word}"}
|
||||
assert firewall.paths == [
|
||||
f"/api/cron/settings/toggle_job/{PLATFORM.removeprefix('opnsense:')}/{flag}",
|
||||
"/api/cron/service/reconfigure",
|
||||
]
|
||||
|
||||
def test_running_a_job_now_is_refused(self):
|
||||
firewall = Firewall()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="run"):
|
||||
_driver(firewall).manage_scheduled_job(ADMIN, "run", digest=_digest(ADMIN))
|
||||
assert firewall.posts == []
|
||||
|
||||
def test_an_unknown_action_is_refused(self):
|
||||
with pytest.raises(ScheduledJobRefused, match="unknown action"):
|
||||
_driver(Firewall()).manage_scheduled_job(ADMIN, "edit", digest=_digest(ADMIN))
|
||||
|
||||
def test_an_unknown_job_raises_lookup_error(self):
|
||||
with pytest.raises(LookupError):
|
||||
_driver(Firewall()).manage_scheduled_job("opnsense:nope", "enable", digest="x")
|
||||
|
||||
def test_a_job_changed_since_it_was_read_is_not_touched(self):
|
||||
firewall = Firewall()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest="0" * 16)
|
||||
assert firewall.posts == []
|
||||
|
||||
def test_a_refused_toggle_raises_and_cron_is_not_reloaded(self):
|
||||
firewall = Firewall(answers={"/api/cron/settings/toggle_job/": {"result": "failed"}})
|
||||
|
||||
with pytest.raises(RuntimeError, match="failed"):
|
||||
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest=_digest(ADMIN))
|
||||
assert "/api/cron/service/reconfigure" not in firewall.paths
|
||||
|
||||
def test_a_cron_that_does_not_reload_raises(self):
|
||||
firewall = Firewall(answers={"/api/cron/service/reconfigure": {"status": "failed"}})
|
||||
|
||||
with pytest.raises(RuntimeError, match="reload"):
|
||||
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest=_digest(ADMIN))
|
||||
|
||||
|
||||
class TestPut:
|
||||
def test_a_new_job_is_added_with_its_marker_and_cron_reloads(self):
|
||||
firewall = Firewall()
|
||||
|
||||
result = _driver(firewall).put_scheduled_job(_spec())
|
||||
|
||||
assert result == {
|
||||
"success": True,
|
||||
"output": "opnsense:5eaf2049-7b6c-4ebd-94f5-8b9c0d1e2f66 created",
|
||||
}
|
||||
assert firewall.posts == [
|
||||
(
|
||||
"/api/cron/settings/add_job",
|
||||
{
|
||||
"job": {
|
||||
"enabled": "1",
|
||||
"minutes": "*/30",
|
||||
"hours": "*",
|
||||
"days": "*",
|
||||
"months": "*",
|
||||
"weekdays": "*",
|
||||
"command": "filter refresh_aliases",
|
||||
"parameters": "",
|
||||
"description": "napalm-scheduled-job: alias-refresh Keep the aliases fresh",
|
||||
}
|
||||
},
|
||||
),
|
||||
("/api/cron/service/reconfigure", None),
|
||||
]
|
||||
|
||||
def test_an_application_job_is_changed_in_place(self):
|
||||
firewall = Firewall()
|
||||
spec = _spec(name="dnsbl-refresh", command="unbound dnsbl", enabled=False)
|
||||
del spec["description"]
|
||||
|
||||
result = _driver(firewall).put_scheduled_job(spec, digest=_digest(OWN))
|
||||
|
||||
assert result == {"success": True, "output": f"{OWN} changed"}
|
||||
path, data = firewall.posts[0]
|
||||
assert path == f"/api/cron/settings/set_job/{OWN_UUID}"
|
||||
assert data["job"]["enabled"] == "0"
|
||||
assert data["job"]["description"] == "napalm-scheduled-job: dnsbl-refresh"
|
||||
assert firewall.paths[-1] == "/api/cron/service/reconfigure"
|
||||
|
||||
def test_the_words_after_the_action_are_its_parameters_one_per_line(self):
|
||||
firewall = Firewall()
|
||||
|
||||
_driver(firewall).put_scheduled_job(
|
||||
_spec(command=" filter refresh_aliases --quiet --all ")
|
||||
)
|
||||
|
||||
job = firewall.posts[0][1]["job"]
|
||||
assert (job["command"], job["parameters"]) == ("filter refresh_aliases", "--quiet\n--all")
|
||||
|
||||
def test_the_longest_action_the_command_starts_with_wins(self):
|
||||
blank = copy.deepcopy(BLANK_JOB)
|
||||
blank["job"]["command"]["filter"] = {"value": "Reload the filter", "selected": 0}
|
||||
firewall = Firewall(blank=blank)
|
||||
|
||||
_driver(firewall).put_scheduled_job(_spec(command="filter refresh_aliases"))
|
||||
|
||||
job = firewall.posts[0][1]["job"]
|
||||
assert (job["command"], job["parameters"]) == ("filter refresh_aliases", "")
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"schedule, fields",
|
||||
[
|
||||
("@daily", ("0", "0", "*", "*", "*")),
|
||||
("@hourly", ("0", "*", "*", "*", "*")),
|
||||
("0 6 * jan-Mar MON-fri", ("0", "6", "*", "1-3", "1-5")),
|
||||
("5 4 1,15 * sun,7", ("5", "4", "1,15", "*", "0,7")),
|
||||
],
|
||||
)
|
||||
def test_the_schedule_is_written_as_its_five_fields(self, schedule, fields):
|
||||
firewall = Firewall()
|
||||
|
||||
_driver(firewall).put_scheduled_job(_spec(schedule=schedule))
|
||||
|
||||
job = firewall.posts[0][1]["job"]
|
||||
assert tuple(job[f] for f in ("minutes", "hours", "days", "months", "weekdays")) == fields
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"over, match",
|
||||
[
|
||||
({"schedule": "@reboot"}, "@reboot"),
|
||||
({"run_as": "nobody"}, "root"),
|
||||
({"command": "rm -rf /"}, "configd offers no action"),
|
||||
({"command": "filter refresh_aliases\nids update"}, "one line"),
|
||||
({"command": "filter refresh_aliases 'a b'"}, "parameter"),
|
||||
({"command": "filter refresh_aliases a\\b"}, "parameter"),
|
||||
({"name": "Not A Name"}, "job name"),
|
||||
({"schedule": "61 * * * *"}, "range"),
|
||||
],
|
||||
)
|
||||
def test_what_opnsense_cannot_take_is_refused_before_anything_is_written(self, over, match):
|
||||
firewall = Firewall()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match=match):
|
||||
_driver(firewall).put_scheduled_job(_spec(**over))
|
||||
assert firewall.posts == []
|
||||
|
||||
def test_a_new_job_whose_name_is_taken_is_not_written(self):
|
||||
firewall = Firewall()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged, match="dnsbl-refresh"):
|
||||
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"))
|
||||
assert firewall.posts == []
|
||||
|
||||
def test_a_change_to_a_job_that_is_gone_raises_lookup_error(self):
|
||||
with pytest.raises(LookupError, match="alias-refresh"):
|
||||
_driver(Firewall()).put_scheduled_job(_spec(), digest="0" * 16)
|
||||
|
||||
def test_a_change_to_a_job_changed_since_it_was_read_is_not_written(self):
|
||||
firewall = Firewall()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"), digest="0" * 16)
|
||||
assert firewall.posts == []
|
||||
|
||||
def test_what_opnsense_refuses_to_save_is_refused(self):
|
||||
refusal = {"result": "failed", "validations": {"job.description": "Text too long"}}
|
||||
firewall = Firewall(answers={"/api/cron/settings/add_job": refusal})
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="Text too long"):
|
||||
_driver(firewall).put_scheduled_job(_spec())
|
||||
assert "/api/cron/service/reconfigure" not in firewall.paths
|
||||
|
||||
def test_a_failed_save_without_a_reason_raises(self):
|
||||
firewall = Firewall(answers={"/api/cron/settings/set_job/": {"result": "failed"}})
|
||||
|
||||
with pytest.raises(RuntimeError, match="failed"):
|
||||
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"), digest=_digest(OWN))
|
||||
assert "/api/cron/service/reconfigure" not in firewall.paths
|
||||
|
||||
|
||||
class TestDelete:
|
||||
def test_an_application_job_is_deleted_and_cron_reloads(self):
|
||||
firewall = Firewall()
|
||||
|
||||
result = _driver(firewall).delete_scheduled_job(OWN, digest=_digest(OWN))
|
||||
|
||||
assert result == {"success": True, "output": f"{OWN} deleted"}
|
||||
assert firewall.paths == [
|
||||
f"/api/cron/settings/del_job/{OWN_UUID}",
|
||||
"/api/cron/service/reconfigure",
|
||||
]
|
||||
|
||||
@pytest.mark.parametrize("key", [ADMIN, PLATFORM, BAD_MARKER])
|
||||
def test_a_job_no_application_wrote_is_only_switched(self, key):
|
||||
firewall = Firewall()
|
||||
|
||||
with pytest.raises(ScheduledJobRefused, match="only switched"):
|
||||
_driver(firewall).delete_scheduled_job(key, digest=_digest(key))
|
||||
assert firewall.posts == []
|
||||
|
||||
def test_a_job_changed_since_it_was_read_is_not_deleted(self):
|
||||
firewall = Firewall()
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
_driver(firewall).delete_scheduled_job(OWN, digest="0" * 16)
|
||||
assert firewall.posts == []
|
||||
|
||||
def test_a_delete_opnsense_did_not_do_raises(self):
|
||||
firewall = Firewall(answers={"/api/cron/settings/del_job/": {"result": "not found"}})
|
||||
|
||||
with pytest.raises(RuntimeError, match="not found"):
|
||||
_driver(firewall).delete_scheduled_job(OWN, digest=_digest(OWN))
|
||||
assert "/api/cron/service/reconfigure" not in firewall.paths
|
||||
@@ -0,0 +1,212 @@
|
||||
"""The SNMP agent, set up through napalm-device-types' ``configure_snmp_agent``.
|
||||
|
||||
``fix_snmp`` enabled os-net-snmp with community "public" and opened UDP/161 on
|
||||
every interface to every source (#13). The template's steps take every value
|
||||
from the caller: community, contact, location, listen address, and the sources
|
||||
the firewall lets through -- one pass rule each, and the old any-source rule
|
||||
goes when sources are given.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
#: The plugin's settings as OPNsense 26.7 serves them (gw-01, 2026-10-31). Its
|
||||
#: model knows exactly these fields, and a set naming any other one, or giving a
|
||||
#: field anything but a string, is a 500 (#36).
|
||||
MODEL = {
|
||||
"enabled": "0",
|
||||
"community": "public",
|
||||
"syslocation": "Home",
|
||||
"syscontact": "admin@example.org",
|
||||
"l3visibility": "1",
|
||||
"versionoid": "1",
|
||||
"enableagentx": "1",
|
||||
"enableobservium": "1",
|
||||
"listen": {"10.0.0.1": {"value": "10.0.0.1", "selected": 1}},
|
||||
}
|
||||
|
||||
SETTINGS = {
|
||||
"community": "c0mm",
|
||||
"allowed_sources": ["10.7.224.20", "10.7.225.0/24"],
|
||||
"contact": "ops",
|
||||
"location": "rack 1",
|
||||
}
|
||||
|
||||
|
||||
class _Api:
|
||||
"""A firewall's REST API: answers by path, records every POST."""
|
||||
|
||||
def __init__(self, *, installed=True, rules=(), saved="saved"):
|
||||
self.installed = installed
|
||||
self.rules = list(rules)
|
||||
self.saved = saved
|
||||
self.posts: list[tuple[str, dict | None]] = []
|
||||
|
||||
def get(self, path):
|
||||
if path == "/api/netsnmp/general/get":
|
||||
return {"general": dict(MODEL)} if self.installed else {}
|
||||
raise AssertionError(path)
|
||||
|
||||
def post(self, path, body=None):
|
||||
self.posts.append((path, body))
|
||||
if path == "/api/netsnmp/general/set":
|
||||
general = (body or {}).get("general", {})
|
||||
if any(k not in MODEL or not isinstance(v, str) for k, v in general.items()):
|
||||
raise requests.HTTPError(f"500 Server Error: Internal Server Error for url: {path}")
|
||||
return {"result": self.saved}
|
||||
if path == "/api/firewall/filter/searchRule":
|
||||
return {"rows": self.rules}
|
||||
if path.startswith("/api/firewall/filter/addRule"):
|
||||
return {"result": "saved", "uuid": "new"}
|
||||
if path.startswith("/api/firewall/filter/delRule/"):
|
||||
return {"result": "deleted"}
|
||||
if path in ("/api/firewall/filter/apply", "/api/netsnmp/service/restart"):
|
||||
return {"status": "ok"}
|
||||
if path.startswith("/api/core/firmware/install/"):
|
||||
return {"status": "ok", "msg_uuid": "x"}
|
||||
raise AssertionError(path)
|
||||
|
||||
def paths(self):
|
||||
return [p for p, _ in self.posts]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api():
|
||||
return _Api()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver(api, monkeypatch):
|
||||
d = OPNsenseDriver("10.0.0.1", "key", "secret")
|
||||
d._session = MagicMock()
|
||||
d._get = api.get
|
||||
d._post = api.post
|
||||
monkeypatch.setattr("time.sleep", lambda s: None)
|
||||
return d
|
||||
|
||||
|
||||
def _body(api, path):
|
||||
return next(b for p, b in api.posts if p == path)
|
||||
|
||||
|
||||
class TestTheCallersValues:
|
||||
def test_community_contact_location_and_listen(self, driver, api):
|
||||
result = driver.configure_snmp_agent({**SETTINGS, "listen": "10.0.0.1"})
|
||||
|
||||
assert result["success"] is True
|
||||
general = _body(api, "/api/netsnmp/general/set")["general"]
|
||||
assert general["enabled"] == "1"
|
||||
assert (general["community"], general["syscontact"], general["syslocation"]) == (
|
||||
"c0mm",
|
||||
"ops",
|
||||
"rack 1",
|
||||
)
|
||||
assert general["listen"] == "10.0.0.1"
|
||||
|
||||
def test_only_fields_the_plugins_model_has_are_sent(self, driver, api):
|
||||
result = driver.configure_snmp_agent({**SETTINGS, "listen": "10.0.0.1"})
|
||||
|
||||
assert result["success"] is True
|
||||
assert set(_body(api, "/api/netsnmp/general/set")["general"]) <= set(MODEL)
|
||||
|
||||
def test_contact_and_location_the_caller_leaves_out_stay_as_they_are(self, driver, api):
|
||||
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
|
||||
general = _body(api, "/api/netsnmp/general/set")["general"]
|
||||
assert "syscontact" not in general and "syslocation" not in general
|
||||
|
||||
def test_nothing_of_an_application_is_built_in(self, driver, api):
|
||||
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
|
||||
sent = repr(api.posts)
|
||||
assert "public" not in sent and "netork" not in sent.lower()
|
||||
|
||||
def test_a_dns_name_is_not_a_listen_address(self, api, monkeypatch):
|
||||
d = OPNsenseDriver("gw-01.lan", "key", "secret")
|
||||
d._session, d._get, d._post = MagicMock(), api.get, api.post
|
||||
monkeypatch.setattr("time.sleep", lambda s: None)
|
||||
|
||||
d.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
|
||||
assert _body(api, "/api/netsnmp/general/set")["general"]["listen"] == ""
|
||||
|
||||
def test_a_rejected_configuration_fails_the_fix(self, driver, api):
|
||||
api.saved = "failed"
|
||||
|
||||
result = driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert "/api/netsnmp/service/restart" not in api.paths()
|
||||
|
||||
|
||||
class TestTheFirewall:
|
||||
def test_one_pass_rule_per_allowed_source(self, driver, api):
|
||||
driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
rules = [b["rule"] for p, b in api.posts if p == "/api/firewall/filter/addRule"]
|
||||
assert [r["source_net"] for r in rules] == ["10.7.224.20/32", "10.7.225.0/24"]
|
||||
assert all(r["destination_port"] == "161" and r["protocol"] == "udp" for r in rules)
|
||||
assert all("netork" not in r["descr"].lower() for r in rules)
|
||||
assert "/api/firewall/filter/apply" in api.paths()
|
||||
|
||||
def test_the_old_any_source_rule_goes(self, api, driver):
|
||||
api.rules = [{"uuid": "old-1", "description": "[netork] Allow SNMP", "source_net": "any"}]
|
||||
|
||||
driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert "/api/firewall/filter/delRule/old-1" in api.paths()
|
||||
|
||||
def test_rules_of_an_earlier_run_are_replaced_not_doubled(self, api, driver):
|
||||
api.rules = [{"uuid": "r1", "description": "napalm-opnsense: SNMP from 10.7.224.20/32"}]
|
||||
|
||||
driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert "/api/firewall/filter/delRule/r1" in api.paths()
|
||||
assert sum(p == "/api/firewall/filter/addRule" for p in api.paths()) == 2
|
||||
|
||||
def test_an_operators_rule_is_left_alone(self, api, driver):
|
||||
api.rules = [{"uuid": "mine", "description": "SNMP from the monitoring VLAN"}]
|
||||
|
||||
driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert not any(p.startswith("/api/firewall/filter/delRule/") for p in api.paths())
|
||||
|
||||
def test_no_sources_leave_the_firewall_alone(self, driver, api):
|
||||
result = driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any(p.startswith("/api/firewall/") for p in api.paths())
|
||||
|
||||
|
||||
class TestInstallAndStart:
|
||||
def test_an_installed_plugin_is_not_reinstalled(self, driver, api):
|
||||
driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert not any(p.startswith("/api/core/firmware/install/") for p in api.paths())
|
||||
assert api.paths()[-1] == "/api/netsnmp/service/restart"
|
||||
|
||||
def test_a_missing_plugin_is_installed_first(self, api, driver):
|
||||
api.installed = False
|
||||
|
||||
driver.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert api.paths()[0] == "/api/core/firmware/install/os-net-snmp"
|
||||
|
||||
|
||||
def test_the_old_action_is_gone():
|
||||
assert not hasattr(OPNsenseDriver, "run_device_action")
|
||||
assert not hasattr(OPNsenseDriver, "_action_fix_snmp")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("community", ["two words", 'q"uote', ""])
|
||||
def test_a_community_that_is_not_one_word_is_refused(driver, api, community):
|
||||
result = driver.configure_snmp_agent({"community": community, "allowed_sources": []})
|
||||
|
||||
assert result["success"] is False
|
||||
assert "/api/netsnmp/general/set" not in api.paths()
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Where the SSH server's algorithm lists are set (NetOrk/netork#1769).
|
||||
|
||||
OPNsense writes sshd_config from config.xml (``<system><ssh>``), and no API
|
||||
controller reads or writes that section: the lists are set on the legacy
|
||||
Administration page. The driver therefore does not harden the SSH server; it
|
||||
says, as data, where a person sets the lists by hand.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_device_types.ssh_server import SSH_ALGORITHM_CLASSES
|
||||
|
||||
from napalm_opnsense import OPNsenseDriver
|
||||
|
||||
|
||||
def test_the_page_that_sets_the_lists():
|
||||
assert OPNsenseDriver.SSH_SETTINGS_MENU == (
|
||||
"System",
|
||||
"Settings",
|
||||
"Administration",
|
||||
"Secure Shell",
|
||||
)
|
||||
|
||||
|
||||
def test_a_field_for_every_algorithm_class():
|
||||
assert OPNsenseDriver.SSH_SETTINGS_FIELDS == {
|
||||
"kex": "Key exchange algorithms",
|
||||
"cipher": "Ciphers",
|
||||
"mac": "MACs",
|
||||
"hostkey": "Host key algorithms",
|
||||
}
|
||||
assert set(OPNsenseDriver.SSH_SETTINGS_FIELDS) == set(SSH_ALGORITHM_CLASSES)
|
||||
|
||||
|
||||
def test_the_driver_does_not_harden_the_ssh_server_itself():
|
||||
assert not callable(getattr(OPNsenseDriver, "harden_ssh_server", None))
|
||||
@@ -138,3 +138,11 @@ class TestRebootHost:
|
||||
with patch.object(driver, "_post", side_effect=ConnectionError("403 Forbidden")):
|
||||
with pytest.raises(RuntimeError, match="403"):
|
||||
driver.reboot_host()
|
||||
|
||||
|
||||
def test_no_warnings_of_its_own():
|
||||
"""The pending updates are get_available_updates; the caller names
|
||||
updates_available from them (netOrk #1111)."""
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
assert "get_device_warnings" not in vars(OPNsenseDriver)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""The firewall's CARP addresses, with who holds each (netOrk #1121).
|
||||
|
||||
``/api/interfaces/overview/export`` -- the source ``get_interfaces_ip`` reads --
|
||||
lists every address on an interface, and an address bound to a CARP VHID carries
|
||||
the VHID and this node's CARP state. That covers both the CARP address itself and
|
||||
an IP alias bound to its VHID: both float with the VHID's MASTER. An address
|
||||
without a VHID stays on this node and is no virtual IP.
|
||||
|
||||
The overview has no CARP password in it; ``interfaces/vip_settings`` would, which
|
||||
is why it is not read. The fixture is the shape of a real OPNsense 26.7 answer,
|
||||
cut down, with documentation addresses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
from napalm_opnsense.virtual_ips import carp_addresses
|
||||
|
||||
OVERVIEW = json.loads(
|
||||
(Path(__file__).parent / "fixtures" / "interfaces_overview_carp.json").read_text()
|
||||
)
|
||||
|
||||
|
||||
def _driver(overview=OVERVIEW) -> OPNsenseDriver:
|
||||
with patch("napalm_opnsense.opnsense.requests.Session"):
|
||||
drv = OPNsenseDriver(hostname="fw", username="k", password="s")
|
||||
drv.session = MagicMock()
|
||||
|
||||
def get(path: str):
|
||||
if path == "/api/interfaces/overview/export":
|
||||
if isinstance(overview, Exception):
|
||||
raise overview
|
||||
return overview
|
||||
raise AssertionError(f"unexpected GET {path}")
|
||||
|
||||
drv._get = get # type: ignore[method-assign]
|
||||
return drv
|
||||
|
||||
|
||||
def _by_address(entries) -> dict:
|
||||
return {e["address"]: e for e in entries}
|
||||
|
||||
|
||||
class TestCarpAddresses:
|
||||
def test_every_address_bound_to_a_vhid_is_a_virtual_ip(self):
|
||||
assert [e["address"] for e in carp_addresses(OVERVIEW)] == [
|
||||
"192.0.2.1",
|
||||
"198.51.100.1",
|
||||
"198.51.100.140",
|
||||
"203.0.113.1",
|
||||
"2001:db8:8::1",
|
||||
]
|
||||
|
||||
def test_an_address_without_a_vhid_stays_on_this_node(self):
|
||||
addresses = {e["address"] for e in carp_addresses(OVERVIEW)}
|
||||
assert not addresses & {"192.0.2.2", "192.0.2.140", "127.0.0.1", "fe80::1"}
|
||||
|
||||
def test_the_carp_address_carries_its_interface_and_state(self):
|
||||
assert _by_address(carp_addresses(OVERVIEW))["192.0.2.1"] == {
|
||||
"mechanism": "carp",
|
||||
"instance": "MGMT",
|
||||
"address": "192.0.2.1",
|
||||
"prefix_length": 24,
|
||||
"interface": "em0",
|
||||
"group_key": "vhid:108",
|
||||
"running": True,
|
||||
"holds": True,
|
||||
}
|
||||
|
||||
def test_an_alias_on_a_vhid_follows_that_vhid(self):
|
||||
alias = _by_address(carp_addresses(OVERVIEW))["198.51.100.140"]
|
||||
assert (alias["group_key"], alias["prefix_length"], alias["holds"]) == (
|
||||
"vhid:140",
|
||||
32,
|
||||
True,
|
||||
)
|
||||
|
||||
def test_a_vhid_not_up_neither_runs_nor_holds(self):
|
||||
entry = _by_address(carp_addresses(OVERVIEW))["203.0.113.1"]
|
||||
assert (entry["running"], entry["holds"]) == (False, False)
|
||||
|
||||
def test_an_interface_without_a_description_is_named_by_its_identifier(self):
|
||||
assert _by_address(carp_addresses(OVERVIEW))["203.0.113.1"]["instance"] == "opt9"
|
||||
|
||||
def test_on_a_backup_node_nothing_is_held(self):
|
||||
backup = json.loads(json.dumps(OVERVIEW).replace('"MASTER"', '"BACKUP"'))
|
||||
entries = carp_addresses(backup)
|
||||
assert entries and all(e["holds"] is False for e in entries)
|
||||
|
||||
def test_the_answer_wrapped_in_an_object_reads_the_same(self):
|
||||
assert carp_addresses({"interfaces": OVERVIEW}) == carp_addresses(OVERVIEW)
|
||||
|
||||
@pytest.mark.parametrize("answer", [[], {}, {"interfaces": None}])
|
||||
def test_a_firewall_without_interfaces_has_none(self, answer):
|
||||
assert carp_addresses(answer) == []
|
||||
|
||||
@pytest.mark.parametrize("answer", ["nonsense", None, 42])
|
||||
def test_an_answer_of_another_shape_is_refused(self, answer):
|
||||
with pytest.raises(ValueError):
|
||||
carp_addresses(answer)
|
||||
|
||||
def test_odd_entries_are_skipped(self):
|
||||
overview = [
|
||||
{"identifier": "opt1", "ipv4": ["192.0.2.9/24", {"vhid": "1"}, None]},
|
||||
"not-an-interface",
|
||||
{"identifier": "opt2", "ipv4": [{"ipaddr": "bogus", "vhid": "2"}]},
|
||||
]
|
||||
assert carp_addresses(overview) == []
|
||||
|
||||
|
||||
class TestGetVirtualIps:
|
||||
def test_a_firewall_reports_carp_and_does_not_look_for_the_linux_mechanisms(self):
|
||||
reading = _driver().get_virtual_ips()
|
||||
assert reading["vip_manager"] is None
|
||||
assert reading["keepalived"] is None
|
||||
assert len(reading["carp"]) == 5
|
||||
|
||||
def test_a_firewall_without_carp_reports_an_empty_list(self):
|
||||
reading = _driver(overview=[OVERVIEW[3], OVERVIEW[4]]).get_virtual_ips()
|
||||
assert reading["carp"] == []
|
||||
|
||||
def test_a_failed_request_is_raised_not_reported_as_none_declared(self):
|
||||
with pytest.raises(RuntimeError):
|
||||
_driver(overview=RuntimeError("API down")).get_virtual_ips()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""WireGuard peers in ``get_vpn_tunnels()`` keep their key when others come and go (#32).
|
||||
|
||||
The key was a running counter over the peer rows, so a peer added ahead of an
|
||||
existing one renumbered every peer after it, and whatever a consumer stored per
|
||||
key (netOrk's site link, its tunnel check) silently moved to another peer. A
|
||||
peer is its interface and its public key, so that is what the key is made of.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from napalm_opnsense.opnsense import OPNsenseDriver
|
||||
|
||||
OFFICE = {
|
||||
"if": "wg0",
|
||||
"type": "peer",
|
||||
"name": "office",
|
||||
"public-key": "aBcD1234efGH5678ijKL9012mnOP3456qrST7890uvw=",
|
||||
"endpoint": "198.51.100.7:51820",
|
||||
"peer-status": "online",
|
||||
"transfer-rx": 10,
|
||||
"transfer-tx": 20,
|
||||
"latest-handshake-age": 45,
|
||||
}
|
||||
LAPTOP = {
|
||||
"if": "wg0",
|
||||
"type": "peer",
|
||||
"name": "laptop",
|
||||
"public-key": "Zz9/+yXw8765vuTS4321rqPO0987nmLK6543jiHG210=",
|
||||
"endpoint": "(none)",
|
||||
"peer-status": "offline",
|
||||
}
|
||||
SERVER = {
|
||||
"if": "wg1",
|
||||
"type": "peer",
|
||||
"name": "server",
|
||||
"public-key": "QqQqWwWwEeEeRrRrTtTtYyYyUuUuIiIiOoOoPpPp123=",
|
||||
"endpoint": "203.0.113.9:51821",
|
||||
"peer-status": "online",
|
||||
}
|
||||
|
||||
|
||||
def _driver(*rows: dict) -> OPNsenseDriver:
|
||||
with patch("napalm_opnsense.opnsense.requests.Session"):
|
||||
drv = OPNsenseDriver(hostname="fw", username="k", password="s")
|
||||
drv.session = MagicMock()
|
||||
show = {"rows": [{"if": "wg0", "type": "interface"}, *rows]}
|
||||
|
||||
def get(path: str) -> dict:
|
||||
if path == "/api/wireguard/service/show":
|
||||
return show
|
||||
raise RuntimeError("not installed") # IPsec and OpenVPN are not part of this
|
||||
|
||||
drv._get = get # type: ignore[method-assign]
|
||||
return drv
|
||||
|
||||
|
||||
def _by_name(tunnels: dict) -> dict[str, str]:
|
||||
return {t["description"]: key for key, t in tunnels.items()}
|
||||
|
||||
|
||||
class TestTheKey:
|
||||
def test_is_the_interface_and_the_start_of_the_public_key(self):
|
||||
assert list(_driver(OFFICE).get_vpn_tunnels()) == ["wireguard-wg0-aBcD1234"]
|
||||
|
||||
def test_survives_a_peer_added_ahead_of_it(self):
|
||||
before = _by_name(_driver(OFFICE, SERVER).get_vpn_tunnels())
|
||||
after = _by_name(_driver(OFFICE, LAPTOP, SERVER).get_vpn_tunnels())
|
||||
assert after["server"] == before["server"]
|
||||
assert after["office"] == before["office"]
|
||||
|
||||
def test_is_safe_in_a_url_path(self):
|
||||
# The key is a path segment (PATCH /devices/{id}/vpn-tunnels/{key}), and
|
||||
# a "/" from base64 would split it even when encoded.
|
||||
key = _by_name(_driver(LAPTOP).get_vpn_tunnels())["laptop"]
|
||||
assert key == "wireguard-wg0-Zz9_-yXw"
|
||||
|
||||
def test_two_peers_with_the_same_key_start_both_stay(self):
|
||||
twin = {
|
||||
**SERVER,
|
||||
"if": "wg0",
|
||||
"name": "twin",
|
||||
"public-key": OFFICE["public-key"][:8] + "x=",
|
||||
}
|
||||
tunnels = _driver(OFFICE, twin).get_vpn_tunnels()
|
||||
assert len(tunnels) == 2
|
||||
|
||||
def test_without_a_public_key_falls_back_to_the_position(self):
|
||||
keyless = {k: v for k, v in OFFICE.items() if k != "public-key"}
|
||||
assert list(_driver(keyless).get_vpn_tunnels()) == ["wireguard-1"]
|
||||
|
||||
|
||||
class TestTheEntry:
|
||||
def test_carries_the_peer_s_reading(self):
|
||||
tunnel = _driver(OFFICE).get_vpn_tunnels()["wireguard-wg0-aBcD1234"]
|
||||
assert tunnel == {
|
||||
"type": "WireGuard",
|
||||
"local_endpoint": "",
|
||||
"remote_endpoint": "198.51.100.7",
|
||||
"is_up": True,
|
||||
"uptime": 45,
|
||||
"bytes_in": 10,
|
||||
"bytes_out": 20,
|
||||
"description": "office",
|
||||
}
|
||||
Reference in new issue
Block a user