From ee49948b2bfa40070ffbeed978b4154f0e00b7ae Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 21:48:56 +0100 Subject: [PATCH] fix(connect): name a full switch and a web page, not a bad password A switch whose Telnet sessions were all taken, and a REST API answering the login with the web UI's HTML page, were both reported as an authentication failure, which sent the operator after the password. The Telnet login now keeps the switch's greeting in an in-memory session log and reports a full switch as a connection error; an HTML answer to the REST login says so. An SSH attempt records netmiko's underlying error instead of "timed out" when it was not a timeout. Session log objects need netmiko 4.3.0, which becomes the floor. Closes #13 --- CHANGELOG.md | 9 ++ napalm_procurve/api_client.py | 6 ++ napalm_procurve/connect_reasons.py | 56 +++++++++++ napalm_procurve/procurve.py | 19 ++-- pyproject.toml | 2 +- tests/quality_baseline.json | 2 +- tests/unit/test_connect_reasons.py | 151 +++++++++++++++++++++++++++++ 7 files changed, 233 insertions(+), 12 deletions(-) create mode 100644 napalm_procurve/connect_reasons.py create mode 100644 tests/unit/test_connect_reasons.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ea54f2d..6886adf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,11 +13,20 @@ All notable changes to this driver. The format follows 3.12 venv no longer has. - The floor on urllib3 is 1.26.5: older releases bundle a `six` that Python 3.12 cannot import. +- The floor on netmiko is 4.3.0: the Telnet login reads the switch's greeting through + a session log object, which older releases do not accept. ### Fixed - `configure_snmp_agent` over the REST API opens its temporary SSH session on port 22. It used `optional_args["port"]`, which names the REST API's port when REST is the transport, so the SNMP setup failed on switches managed over REST. +- A switch whose Telnet sessions are all taken is reported as such ("the switch has no + free session"), as a connection error. It was reported as an authentication failure, + which pointed at the password. +- A REST API that answers the login with an HTML page is reported as "answered with a + web page instead of JSON", not as a failed login. +- An SSH attempt that failed for another reason than a timeout, such as no common key + exchange algorithm, names that reason instead of "timed out". ## [0.6.0] - 2026-10-23 diff --git a/napalm_procurve/api_client.py b/napalm_procurve/api_client.py index 6a840b7..f64a0de 100644 --- a/napalm_procurve/api_client.py +++ b/napalm_procurve/api_client.py @@ -124,6 +124,12 @@ class ProcurveApiClient: json={"userName": self.username, "password": self.password}, timeout=self.timeout, ) + if "html" in resp.headers.get("Content-Type", "").lower(): + # The web UI's "session timed out" page, for any user (#13): not a login result. + raise ConnectionException( + f"REST API on {self.hostname} answered with a web page instead of JSON " + f"(HTTP {resp.status_code})" + ) if resp.status_code != 201: raise ConnectAuthError( f"REST API login failed (HTTP {resp.status_code}) for {self.hostname}" diff --git a/napalm_procurve/connect_reasons.py b/napalm_procurve/connect_reasons.py new file mode 100644 index 0000000..d6cddf4 --- /dev/null +++ b/napalm_procurve/connect_reasons.py @@ -0,0 +1,56 @@ +# Licensed under the Apache License, Version 2.0 + +"""Why a transport failed, in the switch's terms rather than netmiko's. + +netmiko reports a Telnet greeting that refuses every login as a failed login, +and every paramiko error during the SSH handshake as a timeout. These helpers +recover what actually happened, so a busy switch does not read as a wrong +password and a key-exchange mismatch not as an unreachable host. +""" + +from __future__ import annotations + +import re + +from netmiko.exceptions import NetmikoTimeoutException +from netmiko.session_log import SessionLog + +#: What the switch prints instead of a login prompt when every Telnet session is taken. +_NO_FREE_SESSION = re.compile(r"maximum number of telnet sessions", re.I) + +#: Only the greeting matters; the session that follows is not kept in memory. +_GREETING_CHARS = 4096 + +NO_FREE_TELNET_SESSION = "the switch has no free session (maximum number of telnet sessions active)" + + +class TelnetTranscript(SessionLog): + """The start of what the switch sent, in memory; netmiko's writes are not recorded.""" + + def __init__(self) -> None: + super().__init__(record_writes=False) + self.text = "" + + def write(self, data: str) -> None: + """Keep the start of what netmiko read from the channel.""" + if len(self.text) < _GREETING_CHARS: + self.text += data + + @property + def no_free_session(self) -> bool: + """Whether the switch refused the session before any login.""" + return bool(_NO_FREE_SESSION.search(self.text)) + + +def failure_reason(exc: Exception) -> str: + """The reason to record for a failed SSH attempt. + + netmiko raises :class:`NetmikoTimeoutException` for a socket error and for any + paramiko error alike; the original one is its context. + """ + if not isinstance(exc, NetmikoTimeoutException): + return str(exc) + cause = exc.__cause__ or exc.__context__ + if cause is None or isinstance(cause, TimeoutError): + return "timed out" + return str(cause) or type(cause).__name__ diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 92f3e8d..57d439f 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -42,13 +42,11 @@ from napalm_device_types.ssh_host_keys import ( SshHostKeyMismatch, ) from netmiko import ConnectHandler -from netmiko.exceptions import ( - NetmikoAuthenticationException, - NetmikoTimeoutException, -) +from netmiko.exceptions import NetmikoAuthenticationException from napalm_procurve import parsers from napalm_procurve.api_client import ProcurveApiClient +from napalm_procurve.connect_reasons import NO_FREE_TELNET_SESSION, TelnetTranscript, failure_reason logger = logging.getLogger("napalm_procurve") @@ -363,18 +361,15 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): raise except NetmikoAuthenticationException as exc: raise self._auth_failure(transport, exc) from exc - except NetmikoTimeoutException: - logger.debug("%s timeout for %s", label, self.hostname) - self._attempts.append(f"{transport}: timed out") - return False except Exception as exc: logger.debug("%s failed for %s: %s", label, self.hostname, exc) - self._attempts.append(f"{transport}: {exc}") + self._attempts.append(f"{transport}: {failure_reason(exc)}") return False def _try_telnet(self) -> bool: """Probe and connect via Telnet. Returns True on success.""" logger.debug("Trying Telnet for %s", self.hostname) + transcript = TelnetTranscript() # a full switch refuses before the login (#13) try: conn = ConnectHandler( device_type=self.NETMIKO_DEVICE_TYPE_TELNET, @@ -384,13 +379,17 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): secret=self._secret, port=self.telnet_port, timeout=self.timeout, + session_log=transcript, ) self._device = conn self._transport = "telnet" logger.info("Connected to %s via Telnet", self.hostname) return True except NetmikoAuthenticationException as exc: - raise self._auth_failure("telnet", exc) from exc + if not transcript.no_free_session: + raise self._auth_failure("telnet", exc) from exc + self._attempts.append(f"telnet: {NO_FREE_TELNET_SESSION}") + return False except Exception as exc: logger.debug("Telnet failed for %s: %s", self.hostname, exc) self._attempts.append(f"telnet: {exc}") diff --git a/pyproject.toml b/pyproject.toml index e600527..7a95fe3 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.21.1", - "netmiko>=4.0.0", + "netmiko>=4.3.0", # takes a SessionLog object as session_log "paramiko>=5.0.0", # CVE-2026-44405 "netaddr>=0.7.10", "requests>=2.25.0", diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index e824903..bc105ba 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -27,7 +27,7 @@ "napalm_procurve.procurve" ], "python_file_lines": { - "napalm_procurve/procurve.py": 1397 + "napalm_procurve/procurve.py": 1396 }, "untyped_public": [ "napalm_procurve/procurve.py::ProcurveDriver.get_snmp_config" diff --git a/tests/unit/test_connect_reasons.py b/tests/unit/test_connect_reasons.py new file mode 100644 index 0000000..dc6c69f --- /dev/null +++ b/tests/unit/test_connect_reasons.py @@ -0,0 +1,151 @@ +"""A failed connection names what the switch actually said (#13). + +A switch whose Telnet sessions are all taken, a REST API that answers with the +web UI's HTML page, and an SSH key exchange that found no common algorithm were +all reported as a wrong password or a timeout, which sends the operator after +the credentials instead of the session table. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import paramiko +import pytest +from napalm.base.exceptions import ConnectAuthError, ConnectionException +from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException + +from napalm_procurve.api_client import ProcurveApiClient +from napalm_procurve.procurve import ProcurveDriver + +HANDLER = "napalm_procurve.procurve.ConnectHandler" +PROBE = "napalm_procurve.procurve.ProcurveApiClient.probe" + +# What a ProCurve 2520G prints instead of a login prompt when every session is taken. +NO_FREE_SESSION = "Sorry, the maximum number of telnet sessions are active. Try again later.\r\n" + + +def _telnet_refused(greeting: str): + def connect(**kwargs): + if kwargs["device_type"] != ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET: + raise OSError("no route to host") + kwargs["session_log"].write(greeting) + raise NetmikoAuthenticationException(f"Login failed: {kwargs['host']}") + + return connect + + +def _open(connect, **optional_args) -> ConnectionException: + driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args=optional_args) + with patch(PROBE, return_value=(None, None)), patch(HANDLER, side_effect=connect): + with pytest.raises(ConnectionException) as exc_info: + driver.open() + return exc_info.value + + +# --- Telnet ----------------------------------------------------------------- + + +def test_no_free_telnet_session_is_a_connection_error_not_a_wrong_password(): + error = _open(_telnet_refused(NO_FREE_SESSION)) + + msg = str(error) + assert "Authentication failed" not in msg + assert "telnet: the switch has no free session (maximum number of telnet sessions" in msg + + +def test_a_refused_telnet_login_is_still_an_authentication_failure(): + error = _open(_telnet_refused("Password: \r\nInvalid password\r\n")) + + assert "Authentication failed for 10.0.0.40 via telnet" in str(error) + + +def test_the_telnet_transcript_records_what_the_switch_sent_not_the_password(): + sessions: list = [] + + def connect(**kwargs): + sessions.append(kwargs["session_log"]) + return MagicMock() + + driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args={"transport": "telnet"}) + with patch(HANDLER, side_effect=connect): + driver.open() + + assert sessions[0].record_writes is False + + +# --- SSH -------------------------------------------------------------------- + + +def _wrapped(cause: Exception) -> NetmikoTimeoutException: + """What netmiko raises: its own exception, the paramiko or socket error as context.""" + exc = NetmikoTimeoutException("A paramiko SSHException occurred during connection creation") + exc.__context__ = cause + return exc + + +def test_an_ssh_key_exchange_failure_is_named_not_reported_as_a_timeout(): + no_kex = paramiko.ssh_exception.IncompatiblePeer( + "Incompatible ssh peer (no acceptable kex algorithm)" + ) + + def connect(**kwargs): + if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET: + raise OSError("no route to host") + raise _wrapped(no_kex) + + msg = str(_open(connect)) + + assert "ssh: Incompatible ssh peer (no acceptable kex algorithm)" in msg + assert "ssh: timed out" not in msg + + +def test_an_ssh_timeout_is_still_reported_as_one(): + def connect(**kwargs): + if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET: + raise OSError("no route to host") + raise _wrapped(TimeoutError("timed out")) + + assert "ssh: timed out" in str(_open(connect)) + + +# --- REST ------------------------------------------------------------------- + + +def _client_answering(status: int, content_type: str) -> ProcurveApiClient: + client = ProcurveApiClient("10.0.0.40", "manager", "s3cret") + client.setup("v7", "https") + response = MagicMock(status_code=status, headers={"Content-Type": content_type}) + session = MagicMock() + session.post.return_value = response + session.headers = {} + with patch("napalm_procurve.api_client.requests.Session", return_value=session): + client.connect() + return client + + +def test_a_web_page_instead_of_a_rest_answer_is_not_a_login_failure(): + with pytest.raises(ConnectionException) as exc_info: + _client_answering(200, "text/html; charset=utf-8") + + assert not isinstance(exc_info.value, ConnectAuthError) + assert str(exc_info.value) == ( + "REST API on 10.0.0.40 answered with a web page instead of JSON (HTTP 200)" + ) + + +def test_a_refused_rest_login_is_still_an_authentication_failure(): + with pytest.raises(ConnectAuthError, match=r"REST API login failed \(HTTP 401\)"): + _client_answering(401, "application/json") + + +def test_the_transcript_keeps_the_greeting_not_the_whole_session(): + from napalm_procurve.connect_reasons import TelnetTranscript + + transcript = TelnetTranscript() + transcript.write(NO_FREE_SESSION) + for _ in range(1000): + transcript.write("show running-config output\r\n" * 10) + + assert transcript.no_free_session + assert len(transcript.text) < 10_000