From fd1d90c88c617626be1b3cef7d64c0fcfbcb3cc4 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sat, 14 Nov 2026 00:04:32 +0100 Subject: [PATCH] fix(ssh): a refused RSA/ECDSA key is an authentication failure (NetOrk/netork#2512) open() handed the key file netOrk passes in key_file to paramiko as key_filename. For a key file, SSHClient._auth tries the key as every key type and keeps only the last error, so a host turning down an RSA or ECDSA key raised "SSH to failed: encountered RSA key, expected OPENSSH key" instead of "Authentication failed.", which pointed at the key rather than at the host that refused it. Ed25519 keys were not affected: they are the last type tried. The key is now loaded once with its own type (PKey.from_path) and passed as pkey=, as netOrk's own SSH sessions do since NetOrk/netork#2480. A key file that cannot be read raises ConnectionException before anything is dialled. Tested against an in-process SSH server on loopback, with RSA, ECDSA and Ed25519 keys refused and accepted. --- CHANGELOG.md | 7 +++ napalm_bsd/base.py | 18 +++++- tests/test_key_login.py | 136 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 tests/test_key_login.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bd2538..f3ed11e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 3.12 venv no longer has. ### Fixed +- A host turning down an RSA or ECDSA key is an authentication failure: + `open()` raises `ConnectionException("SSH to failed: Authentication failed.")`. + The key went to paramiko as `key_filename`, which tries a key file as every key type + and keeps the last error, so the refusal read "encountered RSA key, expected OPENSSH + key". The key is now loaded once as its own type and passed as `pkey`; a key file that + cannot be read raises `ConnectionException` before anything is dialled + (NetOrk/netork#2512). - An OpenBSD host no longer reads as 100 % busy (#7). net-snmp on OpenBSD answers `ssCpuIdle` with 0 on an idle machine, so `OpenBSDDriver` declares the CPU unknown in its `SNMP_HEALTH_PROFILE` (`{"cpu": {"unknown": True}}`), and the application diff --git a/napalm_bsd/base.py b/napalm_bsd/base.py index 40aafd8..2fd298c 100644 --- a/napalm_bsd/base.py +++ b/napalm_bsd/base.py @@ -89,6 +89,21 @@ def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str: return "\n".join(lines) + "\n" +def _load_key(key_file: str | None) -> paramiko.PKey | None: + """The private key in *key_file*, loaded as the type it is; None without one. + + Handed a key file, paramiko tries it as every key type and keeps the last + error, so a host turning down an RSA or ECDSA key read "encountered RSA key, + expected OPENSSH key" instead of the refusal it was (NetOrk/netork#2512). + """ + if not key_file: + return None + try: + return paramiko.PKey.from_path(key_file) + except (OSError, ValueError, TypeError, paramiko.UnknownKeyType) as exc: + raise ConnectionException(f"SSH key {key_file} could not be read: {exc}") from exc + + class BsdDriver( BsdScheduledJobsMixin, SnmpAgentMixin, @@ -150,13 +165,14 @@ class BsdDriver( # -- connection -------------------------------------------------------------- def open(self) -> None: + pkey = _load_key(self._key_file) client = paramiko.SSHClient() try: self._host_key.connect( client, username=self.username, password=self.password or None, - key_filename=self._key_file, + pkey=pkey, allow_agent=self._allow_agent, look_for_keys=self._look_for_keys, timeout=self.timeout, diff --git a/tests/test_key_login.py b/tests/test_key_login.py new file mode 100644 index 0000000..a1fd519 --- /dev/null +++ b/tests/test_key_login.py @@ -0,0 +1,136 @@ +"""open() logs in with the key netOrk hands it, whatever its type (NetOrk/netork#2512). + +Against a real SSH server on loopback. Handed the key as ``key_filename``, +paramiko tried it as every key type and kept the last error, so a host turning +down an RSA or ECDSA key read "encountered RSA key, expected OPENSSH key" +instead of the refusal it was. +""" + +from __future__ import annotations + +import io +import socket +import threading +from pathlib import Path +from typing import Any + +import paramiko +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ed25519 +from napalm.base.exceptions import ConnectionException + +from napalm_bsd import FreeBSDDriver + +KEY_KINDS = ("rsa", "ecdsa", "ed25519") + + +def _private_key(kind: str) -> tuple[paramiko.PKey, str]: + """A new key of *kind* and its text: RSA and ECDSA as PEM, Ed25519 as OpenSSH.""" + if kind == "ed25519": + text = ( + ed25519.Ed25519PrivateKey.generate() + .private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.OpenSSH, + serialization.NoEncryption(), + ) + .decode() + ) + return paramiko.Ed25519Key.from_private_key(io.StringIO(text)), text + key: paramiko.PKey = ( + paramiko.RSAKey.generate(2048) if kind == "rsa" else paramiko.ECDSAKey.generate() + ) + pem = io.StringIO() + key.write_private_key(pem) + return key, pem.getvalue() + + +class _SshHost(paramiko.ServerInterface): + """Serves one connection on a loopback port; accepts only *accept_key*.""" + + def __init__(self, accept_key: paramiko.PKey | None = None) -> None: + self.accept_key = accept_key + self.tried: list[str] = [] + self._listener = socket.create_server(("127.0.0.1", 0)) + self.port = self._listener.getsockname()[1] + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def get_allowed_auths(self, username: str) -> str: + return "publickey" + + def check_auth_publickey(self, username: str, key: Any) -> int: + self.tried.append(key.get_name()) + if self.accept_key is not None and key.get_base64() == self.accept_key.get_base64(): + return paramiko.AUTH_SUCCESSFUL + return paramiko.AUTH_FAILED + + def _serve(self) -> None: + self._listener.settimeout(10) + try: + sock = self._listener.accept()[0] + except OSError: + return + finally: + self._listener.close() + transport = paramiko.Transport(sock) + transport.add_server_key(paramiko.ECDSAKey.generate()) + try: + transport.start_server(server=self) + transport.join(10) # until the client hangs up + except Exception: # noqa: BLE001 - a refused client ends the server + return + finally: + transport.close() + + def join(self) -> None: + self._thread.join(10) + + +def _driver(host: _SshHost, key_file: Path) -> FreeBSDDriver: + return FreeBSDDriver( + "127.0.0.1", "netork", "", optional_args={"port": host.port, "key_file": str(key_file)} + ) + + +@pytest.mark.parametrize("kind", KEY_KINDS) +def test_a_refused_key_is_an_authentication_failure(tmp_path: Path, kind: str) -> None: + host = _SshHost() + key_file = tmp_path / "key" + key_file.write_text(_private_key(kind)[1]) + + with pytest.raises(ConnectionException, match="Authentication failed") as refused: + _driver(host, key_file).open() + host.join() + + assert "expected OPENSSH key" not in str(refused.value) + assert len(host.tried) == 1 + + +@pytest.mark.parametrize("kind", KEY_KINDS) +def test_an_accepted_key_logs_in(tmp_path: Path, kind: str) -> None: + key, text = _private_key(kind) + host = _SshHost(accept_key=key) + key_file = tmp_path / "key" + key_file.write_text(text) + + driver = _driver(host, key_file) + driver.open() + try: + assert driver.is_alive() == {"is_alive": True} + finally: + driver.close() + host.join() + + +def test_a_key_it_cannot_read_is_a_connection_failure(tmp_path: Path) -> None: + """Before any connection: nothing is dialled with a key that is no key.""" + key_file = tmp_path / "key" + key_file.write_text( + "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----\n" + ) + driver = FreeBSDDriver("192.0.2.1", "netork", "", optional_args={"key_file": str(key_file)}) + + with pytest.raises(ConnectionException, match="key"): + driver.open()