feat(login-auth): how people log in to the firewall, from config.xml (NetOrk/netork#662) #51

Merged
christianmanivong merged 1 commits from feature/login-auth into main 2026-11-28 07:52:53 +00:00
6 changed files with 405 additions and 1 deletions

No files matched your search

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