From 6c612a427b468600ef89cec233678b84a707ca29 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sat, 28 Nov 2026 08:03:18 +0100 Subject: [PATCH] feat(login-auth): how people log in to the firewall, from config.xml (NetOrk/netork#662) get_web_login_auth() names the auth servers tries, in order (the Local Database when it names none), each with what it asks for: password for local, ldap and voucher, password_otp for totp and ldap-totp, external for radius, unknown otherwise. A name no server has is skipped, as OPNsense skips it. get_ssh_server_auth() reads as openssh_configure_do writes sshd_config: on only with enabled, password and challenge-response login with passwordauth, root with permitrootlogin, a key always. An SSH password goes through the same servers (password_sources). Needs napalm-device-types 4.50.0. --- CHANGELOG.md | 11 ++ README.md | 23 ++++ napalm_opnsense/login_auth.py | 156 +++++++++++++++++++++++++ napalm_opnsense/opnsense.py | 2 + pyproject.toml | 2 +- tests/unit/test_login_auth.py | 212 ++++++++++++++++++++++++++++++++++ 6 files changed, 405 insertions(+), 1 deletion(-) create mode 100644 napalm_opnsense/login_auth.py create mode 100644 tests/unit/test_login_auth.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c1901b0..5b5d5cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Added +- How people log in (NetOrk/netork#662), in napalm-device-types 4.50.0's shapes, read from + config.xml over `/api/core/backup/download/this`. `get_web_login_auth()` returns the auth + servers `` names, in their order, and the Local Database when it + names none. Each server comes with what it asks for: `password` for `local`, `ldap` and + `voucher`, `password_otp` for `totp` and `ldap-totp`, `external` for `radius`, and + `unknown` for any other type. A name no server has is skipped, as OPNsense skips it. + `get_ssh_server_auth()` returns sshd's settings as `openssh_configure_do` writes them: + `server_enabled` from `enabled`, password and challenge-response login from + `passwordauth`, and root login from `permitrootlogin`, each tested for presence as + OPNsense does. A key is always on. `password_sources` lists the same servers, because an + SSH password goes through them. - The firewall's configuration history (NetOrk/netork#2511): `get_config_revisions()` lists the revisions OPNsense keeps of config.xml, newest first, each with its id, its time in UTC, its description, its user and its size; `get_config_revision(id)` diff --git a/README.md b/README.md index 678a701..2b67f60 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,8 @@ arguments. | `get_ntp_servers` | ✅ ⁵ | `GET /api/core/backup/download/this`: `` of config.xml | | `get_time_sync` | ✅ ⁵ | `GET /api/core/backup/download/this` (servers, zone) + `GET /api/ntpd/service/status` (system peer) | | `get_config` | ✅ | `GET /api/core/backup/download/this` (XML) | +| `get_web_login_auth` | ✅ | `GET /api/core/backup/download/this`: the auth servers `` names, in order | +| `get_ssh_server_auth` | ✅ | `GET /api/core/backup/download/this`: `` (on, password, root login) and the same auth servers for an SSH password | | `get_config_revisions()` | ✅ ⁶ | `GET /api/core/backup/backups/this` | | `get_config_revision(revision_id)` | ✅ ⁶ | `GET /api/core/backup/download/this/` (XML) | | `revert_config_revision(revision_id)` | ✅ ⁶ | `POST /api/core/backup/revert_backup/` | @@ -167,6 +169,27 @@ algorithm lists instead: `SSH_SETTINGS_MENU` is the page's menu path and OpenSSH's defaults. In an HA pair the configuration sync carries the section to the backup when its "OpenSSH" item (`ssh`) is ticked. +### How people log in + +`get_web_login_auth()` and `get_ssh_server_auth()` say how people log in to the +firewall, in napalm-device-types' shapes (`WebLoginAuthDict`, `SshServerAuthDict`). +NetOrk/netork#662 judges them for MFA. Both read config.xml, because no API controller +reads these settings. + +- **Web interface.** `` names the auth servers a login is + tried against, in order. Without it, the built-in "Local Database" is used alone. The + first server that accepts the login lets the person in. A name no server has is + skipped, as OPNsense skips it. Each source says what it asks for: `password` (`local`, + `ldap`, `voucher`), `password_otp` (`totp` and `ldap-totp`: the password and a code in + one field, and a user without an OTP seed is refused), `external` (`radius`), or + `unknown` for any other type. +- **SSH.** sshd runs only with `` (`server_enabled`). + `passwordauth` switches password and challenge-response login on together, and + `permitrootlogin` lets root in. Each is tested for presence, as OPNsense tests it. A + key is always accepted, and sshd checks it itself. A password goes through the same + auth servers as the web interface (`password_sources`), because OPNsense's `System` + service runs that list for `sshd`, `login`, `su` and `sudo`. + ### Time sync OPNsense keeps the time servers and the zone in config.xml: ``, diff --git a/napalm_opnsense/login_auth.py b/napalm_opnsense/login_auth.py new file mode 100644 index 0000000..e6dbeae --- /dev/null +++ b/napalm_opnsense/login_auth.py @@ -0,0 +1,156 @@ +"""How people log in to the firewall: the web interface's auth servers, and SSH (NetOrk/netork#662). + +**One list for the web interface, the console and SSH passwords.** +```` names auth servers, comma-separated, by their +````. Without it, only the built-in "Local Database" is used. OPNsense tries a +login against each named server in turn, and the first that accepts it lets the +person in (``AuthenticationFactory::authenticate``). A name no server has is +skipped without a word, and so is the API's own "Local API". Names are not +trimmed. The ``System`` service (``Auth/Services/System.php``) runs the same list +for ``sshd``, ``login``, ``su`` and ``sudo``, so an SSH password or +challenge-response login goes through it too. An SSH key does not: sshd checks +it itself. + +**What each kind of server asks for** (``Auth/*.php``, ``getType()``): + +- ``local`` and ``ldap`` ask for a password, and a ``voucher`` for its code alone. +- ``totp`` and ``ldap-totp`` ask for the password and a code in one field. A user + without an ``otp_seed`` is refused, and no option lets them through. +- ``radius`` hands the login to another system, which may ask for anything. +- Any other type is one this driver does not know. + +**sshd** is written from ```` (``openssh_configure_do`` in +``plugins.inc.d/openssh.inc``): + +- It runs only with ``enabled`` set. The installer's live system is not read. +- ``PasswordAuthentication`` and ``ChallengeResponseAuthentication`` follow + ``passwordauth``, ``PermitRootLogin`` follows ``permitrootlogin``. Each switch is + tested with ``isset``, so an empty element counts as set. +- ``PubkeyAuthentication`` is always on. The rest is FreeBSD's defaults: PAM on, + host-based and GSSAPI off, no ``AuthenticationMethods``. + +All of it is read from config.xml, the download ``get_config`` uses: no API +controller reads these settings, up to 26.7 and on ``master``. +""" + +from __future__ import annotations + +# config.xml as the firewall's own API hands it over; ElementTree resolves no external +# entities, and expat limits entity expansion since 2.4.1. +import xml.etree.ElementTree as ET # nosec B405 +from typing import TYPE_CHECKING + +from napalm_device_types import LoginFactors, LoginSourceDict, SshServerAuthDict, WebLoginAuthDict + +#: config.xml itself (the newest entry of the configuration history). +CONFIG_PATH = "/api/core/backup/download/this" +#: The built-in server's name, and the one used when ``authmode`` names none. +LOCAL_DATABASE = "Local Database" + +#: What each kind of auth server asks for; any other kind is ``unknown``. +FACTORS_BY_KIND: dict[str, LoginFactors] = { + "local": "password", + "ldap": "password", + "voucher": "password", + "totp": "password_otp", + "ldap-totp": "password_otp", + "radius": "external", +} + + +def _system(config_xml: str) -> ET.Element: + # The firewall's own config.xml: see the import. + system = ET.fromstring(config_xml).find("system") # nosec B314 + return system if system is not None else ET.Element("system") + + +def _servers(system: ET.Element) -> dict[str, str]: + """Each auth server's type by its name, the built-in one first (``listServers``). + + A configured server needs both; one named "Local Database" replaces the built-in. + """ + servers = {LOCAL_DATABASE: "local"} + for server in system.findall("authserver"): + name = server.findtext("name") or "" + kind = server.findtext("type") or "" + if name and kind: + servers[name] = kind + return servers + + +def _login_sources(system: ET.Element) -> list[LoginSourceDict]: + authmode = system.findtext("webgui/authmode") or "" + names = authmode.split(",") if authmode else [LOCAL_DATABASE] + servers = _servers(system) + return [ + { + "name": name, + "kind": servers[name], + "factors": FACTORS_BY_KIND.get(servers[name], "unknown"), + } + for name in names + if name in servers + ] + + +def login_sources(config_xml: str) -> list[LoginSourceDict]: + """The servers a login is tried against, in their order. + + :raises xml.etree.ElementTree.ParseError: for a text that is no XML. + """ + return _login_sources(_system(config_xml)) + + +def ssh_server_auth(config_xml: str) -> SshServerAuthDict: + """sshd's login settings as config.xml makes them, and what checks a password. + + :raises xml.etree.ElementTree.ParseError: for a text that is no XML. + """ + system = _system(config_xml) + ssh = system.find("ssh") + + def switched(key: str) -> bool: + return ssh is not None and ssh.find(key) is not None + + password = switched("passwordauth") + return { + "password_authentication": password, + "kbd_interactive_authentication": password, + "pubkey_authentication": True, + "hostbased_authentication": False, + "gssapi_authentication": False, + "authentication_methods": [], + "permit_root_login": "yes" if switched("permitrootlogin") else "no", + "use_pam": True, + "pam_auth_stack": None, + "password_sources": _login_sources(system), + "server_enabled": switched("enabled"), + } + + +class OPNsenseLoginAuthMixin: + """Read how the web interface and SSH let people log in; change nothing.""" + + if TYPE_CHECKING: # pragma: no cover - the driver's REST helper + + def _get_text(self, path: str) -> str: ... + + def get_web_login_auth(self) -> WebLoginAuthDict: + """The auth servers the web interface tries, in their order. + + Example:: + + {"sources": [{"name": "TOTP", "kind": "totp", "factors": "password_otp"}]} + + :raises Exception: when config.xml cannot be read, e.g. by a key without + the backup privilege. + """ + return {"sources": login_sources(self._get_text(CONFIG_PATH))} + + def get_ssh_server_auth(self) -> SshServerAuthDict: + """sshd's login settings from config.xml, with ``password_sources`` and + ``server_enabled`` (napalm-device-types' ``SshServerAuthDict``). + + :raises Exception: when config.xml cannot be read. + """ + return ssh_server_auth(self._get_text(CONFIG_PATH)) diff --git a/napalm_opnsense/opnsense.py b/napalm_opnsense/opnsense.py index db1d1eb..3dba009 100644 --- a/napalm_opnsense/opnsense.py +++ b/napalm_opnsense/opnsense.py @@ -71,6 +71,7 @@ from napalm_opnsense.kea_reservations import ( subnet_containing, ) from napalm_opnsense.listening import parse_socket_statistics, wireguard_listen_ports +from napalm_opnsense.login_auth import OPNsenseLoginAuthMixin from napalm_opnsense.ospf_mixin import OPNsenseOspfMixin from napalm_opnsense.ping_mixin import OPNsensePingMixin from napalm_opnsense.port_forwards import alias_index, port_forwards, wan_interfaces @@ -109,6 +110,7 @@ def _search_rows(data: Any, search: str) -> list[dict[str, Any]]: class OPNsenseDriver( OPNsenseConfigRevisionsMixin, + OPNsenseLoginAuthMixin, OPNsenseTimeSyncMixin, OPNsenseScheduledJobsMixin, OPNsenseSshSettingsMixin, diff --git a/pyproject.toml b/pyproject.toml index f671c45..86e5e85 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.38.0", + "napalm-device-types>=4.50.0", "requests>=2.28.0", ] diff --git a/tests/unit/test_login_auth.py b/tests/unit/test_login_auth.py new file mode 100644 index 0000000..932dfcb --- /dev/null +++ b/tests/unit/test_login_auth.py @@ -0,0 +1,212 @@ +"""How people log in to the firewall: the web interface's auth servers and SSH (NetOrk/netork#662). + +OPNsense tries a login against each server named in ```` +in turn, and the first that accepts it lets the person in +(``AuthenticationFactory::authenticate``). The ``System`` service runs the same list +for ``sshd``, ``login``, ``su`` and ``sudo``, so an SSH password goes through it too. +A key over SSH does not. sshd's settings come from ```` +(``openssh_configure_do``). + +``config_xml_sample.xml`` is OPNsense's own sample: no ``authmode`` (the Local +Database alone) and an ```` without ``enabled`` (sshd off). +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch +from xml.etree.ElementTree import ParseError + +import pytest + +from napalm_opnsense.login_auth import login_sources, ssh_server_auth +from napalm_opnsense.opnsense import OPNsenseDriver + +from .test_time_sync import CONFIG_PATH, CONFIG_XML, Firewall + +TOTP_SERVER = """ + + 65a1 + totp + TOTP + 6 + """ +LDAP_SERVER = """ + + 65a2 + ldap + Directory + """ +LDAP_TOTP_SERVER = """ + + 65a3 + ldap-totp + Directory OTP + """ +RADIUS_SERVER = """ + + 65a4 + radius + RADIUS + """ +PLUGIN_SERVER = """ + + 65a5 + sso-thing + Plugin + """ +ALL_SERVERS = TOTP_SERVER + LDAP_SERVER + LDAP_TOTP_SERVER + RADIUS_SERVER + PLUGIN_SERVER + + +def _config(*, authmode: str | None = None, servers: str = "", ssh: str | None = None) -> str: + """The sample with an ``authmode``, extra ```` entries, another ````.""" + xml = CONFIG_XML + if authmode is not None: + xml = xml.replace( + "1", f"1\n {authmode}" + ) + if ssh is not None: + xml = xml.replace("\n admins\n ", f"{ssh}") + return xml.replace("", f"{servers}\n ", 1) + + +def _source(name: str, kind: str, factors: str) -> dict: + return {"name": name, "kind": kind, "factors": factors} + + +LOCAL = _source("Local Database", "local", "password") +TOTP = _source("TOTP", "totp", "password_otp") + + +class TestLoginSources: + def test_without_authmode_the_local_database_alone(self): + assert login_sources(CONFIG_XML) == [LOCAL] + + def test_an_empty_authmode_is_the_local_database_too(self): + assert login_sources(_config(authmode="")) == [LOCAL] + + def test_each_server_in_the_order_authmode_names_them(self): + xml = _config(authmode="TOTP,Local Database", servers=TOTP_SERVER) + + assert login_sources(xml) == [TOTP, LOCAL] + + def test_what_each_kind_of_server_asks_for(self): + xml = _config(authmode="TOTP,Directory,Directory OTP,RADIUS,Plugin", servers=ALL_SERVERS) + + assert login_sources(xml) == [ + TOTP, + _source("Directory", "ldap", "password"), + _source("Directory OTP", "ldap-totp", "password_otp"), + _source("RADIUS", "radius", "external"), + _source("Plugin", "sso-thing", "unknown"), + ] + + def test_a_name_no_server_has_is_skipped_as_opnsense_skips_it(self): + # get() returns null for it, and authenticate() goes on with the next name. + # Names are not trimmed: " TOTP" is no server's name either. + xml = _config(authmode="Gone,TOTP, TOTP,Local API", servers=TOTP_SERVER) + + assert login_sources(xml) == [TOTP] + + def test_a_server_without_type_or_name_is_not_listed(self): + nameless = "totp" + typeless = "Bare" + xml = _config(authmode="Bare", servers=nameless + typeless) + + assert login_sources(xml) == [] + + def test_a_configured_server_named_local_database_replaces_the_built_in_one(self): + renamed = "totpLocal Database" + + assert login_sources(_config(servers=renamed)) == [ + _source("Local Database", "totp", "password_otp") + ] + + def test_a_text_that_is_no_xml_raises(self): + with pytest.raises(ParseError): + login_sources("login1")) + + assert auth["password_authentication"] is True + assert auth["kbd_interactive_authentication"] is True + + def test_presence_counts_as_opnsense_tests_it_with_isset(self): + auth = ssh_server_auth(_config(ssh="")) + + assert auth["server_enabled"] is True + assert auth["password_authentication"] is True + assert auth["permit_root_login"] == "yes" + + def test_an_ssh_password_goes_through_the_web_interface_s_servers(self): + xml = _config(authmode="TOTP", servers=TOTP_SERVER, ssh=SSH_ON) + + assert ssh_server_auth(xml)["password_sources"] == [TOTP] + + def test_no_ssh_element_at_all_is_off(self): + xml = CONFIG_XML.replace("\n admins\n ", "") + + assert ssh_server_auth(xml)["server_enabled"] is False + + +@pytest.fixture +def driver(): + with patch("napalm_opnsense.opnsense.requests.Session"): + drv = OPNsenseDriver( + hostname="fw", username="k", password="s", optional_args={"verify": False} + ) + drv.session = MagicMock() + yield drv + + +class TestDriver: + def test_the_web_login_from_config_xml(self, driver): + firewall = Firewall(config=_config(authmode="TOTP", servers=TOTP_SERVER)) + driver.session.get.side_effect = firewall.get + + assert driver.get_web_login_auth() == {"sources": [TOTP]} + assert firewall.paths == [CONFIG_PATH] + + def test_the_ssh_login_from_config_xml(self, driver): + firewall = Firewall(config=_config(ssh=SSH_ON)) + driver.session.get.side_effect = firewall.get + + assert driver.get_ssh_server_auth()["server_enabled"] is True + assert firewall.paths == [CONFIG_PATH] + + def test_a_failed_download_raises(self, driver): + import requests + + driver.session.get.side_effect = Firewall(config=requests.HTTPError("403 Forbidden")).get + + with pytest.raises(requests.HTTPError): + driver.get_web_login_auth() + with pytest.raises(requests.HTTPError): + driver.get_ssh_server_auth()