From ef1900c32a8e753252f22ce3a5f2556f04f883d4 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Mon, 2 Nov 2026 10:09:27 +0100 Subject: [PATCH] feat(ssh): harden the node's sshd through a run_command channel (#50) A Proxmox node runs Debian's stock OpenSSH, so OpenSshServerMixin works there as on a plain Linux host. What it needed was run_command: an exec channel on the node's SSH session, via napalm-device-types' run_on_transport. The USES_SSH comment said there was no SSH session; it now says what the flag means to netOrk. --- CHANGELOG.md | 10 ++++ napalm_proxmox/driver.py | 34 ++++++++++- tests/test_ssh_server.py | 125 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+), 1 deletion(-) create mode 100644 tests/test_ssh_server.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d0976c6..deeb4a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- The node's sshd can be hardened: `OpenSshServerMixin` (napalm-device-types) gives + `harden_ssh_server` and `exempt_from_ssh_penalties`, so netOrk's SSH algorithm fix + works on a Proxmox node as on a plain Linux host. A node runs Debian's stock + OpenSSH with an `sshd_config.d` include, so the change is a drop-in there (#50). +- `run_command(command, *, privileged=False, timeout=60, stdin=None)`, the public + command channel: an exec channel on the node's SSH session with stdout, stderr and + the exit status kept apart. `privileged` needs nothing more on a node logged in as + root; a command that cannot run or outlasts its timeout raises `ConnectionException`. + ### Changed - The floor on napalm-device-types is 4.23.0, the first release with what this driver uses. - Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver diff --git a/napalm_proxmox/driver.py b/napalm_proxmox/driver.py index 5a1c40a..2aae130 100644 --- a/napalm_proxmox/driver.py +++ b/napalm_proxmox/driver.py @@ -35,6 +35,7 @@ from typing import Any from napalm.base.exceptions import ConnectionException from napalm_device_types import ( AptProxyMixin, + CommandResult, EnsurePackageMixin, FingerprintRule, HostStatusMixin, @@ -42,12 +43,14 @@ from napalm_device_types import ( KernelFactsMixin, LicenseMixin, ListeningSocketsMixin, + OpenSshServerMixin, PortSpec, ServicePackagesMixin, SnmpAgentMixin, SystemdServicesMixin, SystemIdentityMixin, ) +from napalm_device_types.channel import run_on_transport from napalm_device_types.ssh_host_keys import HostKeyCheck try: @@ -103,13 +106,15 @@ class ProxmoxDriver( SnmpAgentMixin, EnsurePackageMixin, AptProxyMixin, + OpenSshServerMixin, HypervisorDriver, ): """NAPALM driver for Proxmox VE nodes.""" VENDOR = "Proxmox" DRIVER_NAME = "proxmox" - # Everything runs over the Proxmox REST API; there is no SSH session. + # netOrk reaches the node through the REST API and does not log in over SSH + # itself; the driver's own SSH session (_node_ssh) runs the node's shell. USES_SSH = False # A PVE node reboots through a full init sequence plus storage checks. REBOOT_SETTLE_SECONDS = 90 @@ -326,6 +331,33 @@ class ProxmoxDriver( logger.debug("%s: stderr of a node command: %s", self.hostname, err[-300:]) return out.strip() + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: + """Run *command* on an exec channel of the node's SSH session (``CommandChannelMixin``). + + stdout, stderr and the exit status come back apart; *stdin*, if given, is + written and then closed. *privileged* needs nothing more: the node is + logged in as root, as for every other command this driver runs there. + + :raises ConnectionException: when the command could not run, or did not + finish within *timeout* seconds. + """ + try: + transport = self._node_ssh().get_transport() + return run_on_transport(transport, command, stdin=stdin, timeout=timeout) + except ConnectionException: + raise + except _ssh_errors() as exc: + raise ConnectionException( + f"Cannot run a command on {self.hostname} over SSH: {exc}" + ) from exc + def _node_ssh(self) -> Any: # paramiko.SSHClient; paramiko is imported lazily """The SSH session to the node on port 22, opened once. diff --git a/tests/test_ssh_server.py b/tests/test_ssh_server.py new file mode 100644 index 0000000..a42aa11 --- /dev/null +++ b/tests/test_ssh_server.py @@ -0,0 +1,125 @@ +"""The node's sshd can be hardened: a node runs Debian's stock OpenSSH (NetOrk/netork#1027). + +Proxmox VE leaves sshd_config to Debian, with ``Include /etc/ssh/sshd_config.d/*.conf``, +so napalm-device-types' ``OpenSshServerMixin`` works as it does on a plain Linux host. +What it needs from the driver is ``run_command``: an exec channel on the node's SSH +session, with stdin, stderr and the exit status kept apart. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock + +import paramiko +import pytest +from napalm.base.exceptions import ConnectionException +from napalm_device_types import CommandResult + +from napalm_proxmox.driver import ProxmoxDriver + + +class _Channel: + """An exec channel that prints *out* and *err* and exits with *status*.""" + + def __init__(self, out: bytes = b"", err: bytes = b"", status: int = 0) -> None: + self._out, self._err, self._status = out, err, status + self.command: str | None = None + self.stdin = b"" + self.write_shut = False + self.closed = False + + def settimeout(self, timeout: float | None) -> None: + pass + + def exec_command(self, command: str) -> None: + self.command = command + + def sendall(self, data: bytes) -> None: + self.stdin += data + + def shutdown_write(self) -> None: + self.write_shut = True + + def recv_ready(self) -> bool: + return bool(self._out) + + def recv_stderr_ready(self) -> bool: + return bool(self._err) + + def exit_status_ready(self) -> bool: + return True + + def recv(self, size: int) -> bytes: + chunk, self._out = self._out[:size], self._out[size:] + return chunk + + def recv_stderr(self, size: int) -> bytes: + chunk, self._err = self._err[:size], self._err[size:] + return chunk + + def recv_exit_status(self) -> int: + return self._status + + def close(self) -> None: + self.closed = True + + +def _driver(channel: _Channel) -> ProxmoxDriver: + driver = ProxmoxDriver("10.0.0.9", "root", "s3cret") + driver._node_name = "pve1" + driver._api = MagicMock() + session = MagicMock() + session.get_transport.return_value.open_session.return_value = channel + driver._node_ssh = MagicMock(return_value=session) # type: ignore[method-assign] + return driver + + +def test_the_driver_offers_the_ssh_hardening(): + assert callable(getattr(ProxmoxDriver, "harden_ssh_server", None)) + assert callable(getattr(ProxmoxDriver, "exempt_from_ssh_penalties", None)) + + +def test_a_command_reports_stdout_stderr_and_its_exit_status(): + channel = _Channel(b"root\n", b"a warning\n", 3) + + result = _driver(channel).run_command("id -un") + + assert result == CommandResult("root\n", "a warning\n", 3) + assert channel.command == "id -un" + assert channel.closed + + +def test_stdin_reaches_the_command_and_is_closed(): + channel = _Channel() + + _driver(channel).run_command("cat > /tmp/x", stdin=b"PasswordAuthentication no\n") + + assert channel.stdin == b"PasswordAuthentication no\n" + assert channel.write_shut + + +def test_privileged_needs_nothing_more_as_the_node_is_logged_in_as_root(): + channel = _Channel() + + _driver(channel).run_command("sshd -T", privileged=True) + + assert channel.command == "sshd -T" + + +def test_a_command_that_cannot_run_raises(): + driver = _driver(_Channel()) + driver._node_ssh = MagicMock( # type: ignore[method-assign] + side_effect=paramiko.AuthenticationException("Authentication failed.") + ) + + with pytest.raises(ConnectionException, match="Authentication failed"): + driver.run_command("true") + + +def test_a_command_that_outlasts_its_timeout_raises(): + class _Hangs(_Channel): + def exit_status_ready(self) -> bool: + return False + + with pytest.raises(ConnectionException, match="did not finish"): + _driver(_Hangs()).run_command("sleep 60", timeout=0.05)