Merge pull request 'feat(ssh): harden the node's sshd through a run_command channel (#50)' (#51) from feat/ssh-hardening into main
driver / lint (push) Successful in 14s
driver / standard (push) Successful in 15s
driver / test (3.12) (push) Failing after 5s
driver / lowest (push) Successful in 32s
driver / types (push) Successful in 1m1s
driver / test (3.13) (push) Successful in 1m6s
driver / build (push) Successful in 26s
driver / security (push) Successful in 1m5s
CI / driver (push) Failing after 1m56s
driver / publish (push) Skipped

This commit was merged in pull request #51.
This commit is contained in:
christianmanivong committed 2026-11-02 11:39:45 +00:00
commit a4c220d2e3
3 files changed
+168 -1

No files matched your search

+10
View File
@@ -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.24.0, the first release with what this driver
uses (its shared `lldpctl` parser).
+33 -1
View File
@@ -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.
+125
View File
@@ -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)