From cb7268b89cdd2eee98b2c091175798a6de467e2b Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 22:18:33 +0100 Subject: [PATCH 1/3] fix(rest): verify the API certificate by its fingerprint The REST login never verified the switch in practice: with ssl_verify off nothing was checked, and with it on a self-signed certificate (the one every ProCurve ships) failed the CA check and the login was retried with verification off. Either way the password went to whatever answered on port 443. The certificate is now checked by its SHA-256 fingerprint, trust on first use (napalm-device-types tls_certificates): the caller passes the fingerprint to expect in optional_args["tls_fingerprints"] and receives every one seen through optional_args["tls_certificate_observer"]. A different certificate ends open() with TlsCertificateMismatch before the password is sent, without trying SSH or Telnet, which would reach the same host with the same password. The session is pinned to the checked certificate for every later connection. ssl_verify no longer has an effect, and the unverified retry is gone. Closes #17 --- CHANGELOG.md | 14 ++ README.md | 20 ++- napalm_procurve/api_client.py | 55 ++++++-- napalm_procurve/procurve.py | 72 ++++------ tests/quality_baseline.json | 2 +- tests/unit/test_rest_certificate.py | 211 ++++++++++++++++++++++++++++ 6 files changed, 320 insertions(+), 54 deletions(-) create mode 100644 tests/unit/test_rest_certificate.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d3265a2..01bf9e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,21 @@ All notable changes to this driver. The format follows ## [Unreleased] +### Fixed +- The REST API's certificate is verified. A switch's self-signed certificate is checked + by its SHA-256 fingerprint, not by a CA, with trust on first use: + `optional_args["tls_fingerprints"]` (`{"443": "SHA256:AB:CD:…"}`) holds the fingerprint + to expect and `optional_args["tls_certificate_observer"]` receives every one seen. A + different certificate is refused before the password is sent and ends `open()` with + `TlsCertificateMismatch` (a `ConnectionException` naming both fingerprints); the driver + does not fall back to SSH or Telnet then. Every connection of the REST session is held + to the certificate checked (#17). +- A REST login that failed is no longer retried with certificate verification turned off. + ### Changed +- `ssl_verify` (`verify_ssl`, `verify`) no longer has any effect: the REST certificate is + verified by its fingerprint instead. Callers that set it to `True` had their login + retried without verification whenever the self-signed certificate failed the CA check. - Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6). - The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python diff --git a/README.md b/README.md index abd78c6..dba4484 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,24 @@ The driver probes transports in order and uses the first one that succeeds: Override the transport with `optional_args={"transport": "ssh_legacy"}` to skip auto-detection. +## Host verification + +The switch's identity is checked before any password is sent, on every transport that +has one (napalm-device-types): + +- **SSH:** the host key, trust on first use: `optional_args["ssh_host_keys"]` holds the + key to expect, `optional_args["ssh_host_key_observer"]` receives the one seen. +- **REST API over HTTPS:** the certificate, by its SHA-256 fingerprint and not by a CA + (ProCurves ship self-signed certificates), trust on first use: + `optional_args["tls_fingerprints"]` = `{"443": "SHA256:AB:CD:…"}` holds the fingerprint + to expect, `optional_args["tls_certificate_observer"]` receives the one seen. Without a + fingerprint the first certificate is accepted. + +A refused host key or certificate ends `open()` with a `ConnectionException` naming both +fingerprints. The driver does not try the next transport then: it would reach the same +host with the same password, over Telnet in clear text. Plain HTTP REST has no +certificate to check. + ## Switch prerequisites ### REST API (newer switches, e.g. 2530, 2540) @@ -63,7 +81,7 @@ with Driver( optional_args={ # "transport": "ssh", # force transport (api/ssh/ssh_legacy/telnet) # "port": 22, - # "ssl_verify": False, # disable SSL cert check for API + # "tls_fingerprints": {"443": "SHA256:AB:CD:…"}, # REST certificate to expect # "api_version": "v7", # API version hint (v3/v6/v7) # "secret": "enablepassword", # enable password for CLI }, diff --git a/napalm_procurve/api_client.py b/napalm_procurve/api_client.py index 6a840b7..76c766f 100644 --- a/napalm_procurve/api_client.py +++ b/napalm_procurve/api_client.py @@ -7,6 +7,8 @@ Used automatically by ProcurveDriver when the REST API is reachable. """ import logging +from collections.abc import Mapping +from contextlib import nullcontext from typing import Any import requests @@ -14,9 +16,13 @@ import urllib3 from napalm.base import helpers as napalm_helpers from napalm.base.exceptions import ConnectAuthError, ConnectionException from napalm_device_types import add_lag_interfaces +from napalm_device_types.tls_certificates import CertificateCheck logger = logging.getLogger("napalm_procurve.api") +#: The port the REST API listens on over HTTPS; its URLs name no other. +HTTPS_PORT = 443 + class ProcurveApiClient: """Thin wrapper around ArubaOS REST API sessions. @@ -104,8 +110,21 @@ class ProcurveApiClient: # Session management # ------------------------------------------------------------------ - def connect(self) -> None: - """Open an authenticated REST API session.""" + def connect( + self, + certificate_args: Mapping[str, Any] | None = None, + check_timeout: float = 15, + ) -> None: + """Open an authenticated REST API session. + + Over HTTPS the switch's certificate is checked first, by its fingerprint + and not by a CA (napalm-device-types ``tls_certificates``, #17): + *certificate_args* are the driver's ``optional_args`` with the + fingerprint to expect and the observer. The session is pinned to that + certificate, so the login is sent to no other; a refused one raises + ``TlsCertificateMismatch``. The certificate is reported once the login + stands. + """ if not self._base_url: raise ConnectionException( "ProcurveApiClient.connect() called before api_version/proto set. " @@ -114,16 +133,14 @@ class ProcurveApiClient: if not self.ssl_verify: urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) - self._session = requests.Session() - self._session.verify = self.ssl_verify - self._session.headers.update({"Content-Type": "application/json", "Connection": "close"}) - + check = self._open_session(certificate_args, check_timeout) url = self._base_url + "login-sessions" - resp = self._session.post( - url, - json={"userName": self.username, "password": self.password}, - timeout=self.timeout, - ) + with check.refusing() if check is not None else nullcontext(): + resp = self._session.post( + url, + json={"userName": self.username, "password": self.password}, + timeout=self.timeout, + ) if resp.status_code != 201: raise ConnectAuthError( f"REST API login failed (HTTP {resp.status_code}) for {self.hostname}" @@ -136,6 +153,22 @@ class ProcurveApiClient: if cookie: self._session.headers.update({"Cookie": cookie}) logger.debug("REST API login OK for %s", self.hostname) + if check is not None: + check.observe() + + def _open_session( + self, certificate_args: Mapping[str, Any] | None, check_timeout: float + ) -> CertificateCheck | None: + """A new session; over HTTPS pinned to the switch's certificate, checked first.""" + self._session = requests.Session() + self._session.verify = self.ssl_verify + self._session.headers.update({"Content-Type": "application/json", "Connection": "close"}) + if self._proto != "https": + return None + check = CertificateCheck(certificate_args, self.hostname, HTTPS_PORT) + check.verify_server(check_timeout) + check.pin(self._session) + return check def setup(self, api_version: str, proto: str) -> None: """Set the API version and protocol (called after probe()).""" diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index fdb9404..76c7533 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -41,6 +41,7 @@ from napalm_device_types.ssh_host_keys import ( HostKeyCheck, SshHostKeyMismatch, ) +from napalm_device_types.tls_certificates import TlsCertificateMismatch from netmiko import ConnectHandler from netmiko.exceptions import ( NetmikoAuthenticationException, @@ -144,9 +145,6 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): self.port: int = optional_args.get("port", 22) self.telnet_port: int = optional_args.get("telnet_port", 23) self.force_transport: str | None = optional_args.get("transport") - self.ssl_verify: bool = optional_args.get( - "ssl_verify", optional_args.get("verify_ssl", optional_args.get("verify", False)) - ) self.api_version_hint: str | None = optional_args.get("api_version") # Enable password for CLI (defaults to login password) self._secret: str = optional_args.get("secret", password) @@ -155,10 +153,12 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): logger.setLevel(logging.DEBUG) self.netmiko_optional_args = netmiko_args(optional_args) - # The host keys to expect and where the one seen is reported (netork#1167). + # The host keys to expect and where the one seen is reported (netork#1167); the + # REST API's certificate is checked the same way, with its own two keys (#17). self._host_key_args: dict[str, Any] = { k: optional_args[k] for k in (KNOWN_KEYS_ARG, OBSERVER_ARG) if k in optional_args } + self._optional_args = optional_args # --- runtime state --- # Active transport: "api" | "ssh" | "ssh_legacy" | "telnet" @@ -258,54 +258,44 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): # ------------------------------------------------------------------ def _try_api(self) -> bool: - """Probe and connect via REST API. Returns True on success.""" + """Probe and connect via REST API. Returns True on success. + + A refused certificate (``tls_certificates``, #17) ends ``open()``: SSH and + Telnet would reach the same host with the same password. + """ probe_timeout = min(self.timeout, 15) logger.info("Probing REST API for %s (timeout=%ds)", self.hostname, probe_timeout) - # Probe without SSL verification — no credentials are sent during probing, - # so this is safe and avoids failing on self-signed certificates. + # The probe sends no credentials; the login checks the certificate first. ver, proto = ProcurveApiClient.probe(self.hostname, timeout=probe_timeout, ssl_verify=False) # Allow hint override (e.g. user knows the API version) if self.api_version_hint and proto: ver = self.api_version_hint - if not ver: + if not ver or not proto: logger.warning("REST API not detected on %s — falling back to CLI", self.hostname) self._attempts.append("api: not detected") return False - # Try connecting with the requested SSL setting first; if it fails due to a - # self-signed certificate (ssl_verify=True), transparently retry unverified. - error: Exception | None = None - for ssl_verify in [self.ssl_verify] if not self.ssl_verify else [True, False]: - client = ProcurveApiClient( - hostname=self.hostname, - username=self.username, - password=self.password, - timeout=self.timeout, - ssl_verify=ssl_verify, - api_version=ver, - ) - client.setup(ver, proto) - try: - client.connect() - except Exception as exc: - logger.debug("REST API connect failed (ssl_verify=%s): %s", ssl_verify, exc) - error = exc - continue - self._api = client - self._transport = "api" - logger.info( - "Connected to %s via REST API (%s %s, ssl_verify=%s)", - self.hostname, - proto, - ver, - ssl_verify, - ) - return True - - logger.warning("REST API connect failed for %s — falling back to CLI", self.hostname) - self._attempts.append(f"api: {error}") - return False + client = ProcurveApiClient( + hostname=self.hostname, + username=self.username, + password=self.password, + timeout=self.timeout, + api_version=ver, + ) + client.setup(ver, proto) + try: + client.connect(certificate_args=self._optional_args, check_timeout=probe_timeout) + except TlsCertificateMismatch: + raise + except Exception as exc: + logger.warning("REST API connect failed for %s — falling back to CLI", self.hostname) + self._attempts.append(f"api: {exc}") + return False + self._api = client + self._transport = "api" + logger.info("Connected to %s via REST API (%s %s)", self.hostname, proto, ver) + return True def _netmiko_kwargs(self, legacy: bool = False) -> dict: """Return kwargs for ConnectHandler, merging explicit fields with netmiko_optional_args. diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index e824903..da90cab 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": 1387 }, "untyped_public": [ "napalm_procurve/procurve.py::ProcurveDriver.get_snmp_config" diff --git a/tests/unit/test_rest_certificate.py b/tests/unit/test_rest_certificate.py new file mode 100644 index 0000000..7e76c22 --- /dev/null +++ b/tests/unit/test_rest_certificate.py @@ -0,0 +1,211 @@ +"""The REST API's certificate is verified by its fingerprint, trust on first use (#17). + +ProCurves ship self-signed certificates, so a CA check fails on every one of them; the +driver used to retry the login unverified when it did, which sent the password to +whatever answered on port 443. Now the certificate is pinned: the fingerprint to expect +comes in ``optional_args["tls_fingerprints"]``, the one seen goes to +``optional_args["tls_certificate_observer"]`` (napalm-device-types ``tls_certificates``). +A refused certificate ends ``open()``: no login is sent, and there is no fall-back to SSH +or Telnet, which would hand the same host the password (in clear text, for Telnet). +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest +import requests +from napalm_device_types.tls_certificates import ( + KNOWN_FINGERPRINTS_ARG, + OBSERVER_ARG, + TlsCertificateMismatch, + fingerprint, +) +from urllib3.util.ssl_ import assert_fingerprint + +from napalm_procurve.procurve import ProcurveDriver + +SWITCH_DER = b"the switch's self-signed certificate" +IMPOSTOR_DER = b"another certificate" +SWITCH_FP = fingerprint(SWITCH_DER) +IMPOSTOR_FP = fingerprint(IMPOSTOR_DER) + +PROBE = "napalm_procurve.procurve.ProcurveApiClient.probe" +FETCH = "napalm_device_types.tls_certificates.fetch_certificate" +HANDLER = "napalm_procurve.procurve.ConnectHandler" + + +@pytest.fixture(autouse=True) +def _no_network(): + """Tests open no socket; NAPALM's ``__del__`` asks a REST session ``is_alive`` too.""" + refuse = requests.exceptions.ConnectionError("tests open no socket") + with patch.object(requests.adapters.HTTPAdapter, "send", side_effect=refuse): + yield + + +def _driver(seen: list, known: str | None = None, **extra) -> ProcurveDriver: + args: dict = {OBSERVER_ARG: seen.append, **extra} + if known is not None: + args[KNOWN_FINGERPRINTS_ARG] = {"443": known} + return ProcurveDriver("10.0.0.4", "manager", "s3cret", optional_args=args) + + +def _login_ok() -> MagicMock: + resp = MagicMock(status_code=201) + resp.json.return_value = {"cookie": "sessionId=abc"} + return resp + + +def _no_cli(**_kwargs): + raise AssertionError("fell back to the CLI") + + +def _pinned(driver: ProcurveDriver) -> str: + adapter = driver._api._session.get_adapter("https://10.0.0.4/rest/v7/") + return adapter.poolmanager.connection_pool_kw["assert_fingerprint"] + + +class TestFirstUse: + def test_accepts_the_certificate_pins_the_session_and_reports_it(self): + seen: list = [] + driver = _driver(seen) + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, return_value=SWITCH_DER), + patch.object(requests.Session, "post", return_value=_login_ok()) as post, + patch(HANDLER, side_effect=_no_cli), + ): + driver.open() + assert driver._transport == "api" + assert post.call_count == 1 + assert _pinned(driver) == SWITCH_FP.removeprefix("SHA256:").replace(":", "").lower() + assert seen == [ + { + "host": "10.0.0.4", + "port": 443, + "seen": {"fingerprint": SWITCH_FP}, + "expected": None, + "accepted": True, + } + ] + + def test_nothing_is_reported_when_the_login_fails(self): + seen: list = [] + driver = _driver(seen, transport="api") + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, return_value=SWITCH_DER), + patch.object(requests.Session, "post", return_value=MagicMock(status_code=401)), + pytest.raises(Exception, match="api"), + ): + driver.open() + assert seen == [] + + +class TestKnownCertificate: + def test_the_pinned_certificate_connects(self): + seen: list = [] + driver = _driver(seen, known=SWITCH_FP) + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, return_value=SWITCH_DER), + patch.object(requests.Session, "post", return_value=_login_ok()), + ): + driver.open() + assert driver._transport == "api" + assert seen[0]["accepted"] is True + assert seen[0]["expected"] == {"fingerprint": SWITCH_FP} + + def test_another_certificate_is_refused_before_the_login_and_without_a_fallback(self): + seen: list = [] + driver = _driver(seen, known=SWITCH_FP) + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, return_value=IMPOSTOR_DER), + patch.object(requests.Session, "post") as post, + patch(HANDLER, side_effect=_no_cli), + pytest.raises(TlsCertificateMismatch) as caught, + ): + driver.open() + post.assert_not_called() + assert SWITCH_FP in str(caught.value) + assert IMPOSTOR_FP in str(caught.value) + assert seen[0]["accepted"] is False + assert seen[0]["seen"] == {"fingerprint": IMPOSTOR_FP} + + def test_a_certificate_changed_between_check_and_login_is_refused_too(self): + def refuse(*_args, **_kwargs): + try: + assert_fingerprint(IMPOSTOR_DER, SWITCH_FP.removeprefix("SHA256:")) + except Exception as exc: + raise requests.exceptions.SSLError(exc) from exc + + seen: list = [] + driver = _driver(seen, known=SWITCH_FP) + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, return_value=SWITCH_DER), + patch.object(requests.Session, "post", side_effect=refuse), + patch(HANDLER, side_effect=_no_cli), + pytest.raises(TlsCertificateMismatch), + ): + driver.open() + assert seen[-1]["accepted"] is False + assert seen[-1]["seen"] == {"fingerprint": IMPOSTOR_FP} + + +class TestNoUnverifiedRetry: + def test_the_login_is_sent_once_and_never_unpinned(self): + """ssl_verify=True used to retry a failed login with verification off.""" + sessions: list = [] + + def login(session, *_args, **_kwargs): + sessions.append(session) + raise requests.exceptions.ConnectionError("connection reset") + + driver = _driver([], ssl_verify=True) + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, return_value=SWITCH_DER), + patch.object(requests.Session, "post", autospec=True, side_effect=login), + patch(HANDLER, side_effect=Exception("SSH refused")), + pytest.raises(Exception, match="api: connection reset"), + ): + driver.open() + assert len(sessions) == 1 + adapter = sessions[0].get_adapter("https://10.0.0.4/rest/v7/") + assert adapter.poolmanager.connection_pool_kw["assert_fingerprint"] + + def test_no_ca_is_consulted_for_a_self_signed_certificate(self): + driver = _driver([], ssl_verify=True) + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, return_value=SWITCH_DER), + patch.object(requests.Session, "post", return_value=_login_ok()), + ): + driver.open() + assert driver._api._session.verify is False + + +class TestUnreachable: + def test_no_certificate_to_read_is_a_failed_rest_attempt(self): + driver = _driver([], transport="api") + with ( + patch(PROBE, return_value=("v7", "https")), + patch(FETCH, side_effect=ConnectionRefusedError("connection refused")), + patch.object(requests.Session, "post") as post, + pytest.raises(Exception, match="api: .*connection refused"), + ): + driver.open() + post.assert_not_called() + + def test_plain_http_has_no_certificate_to_check(self): + driver = _driver([]) + with ( + patch(PROBE, return_value=("v7", "http")), + patch(FETCH) as fetch, + patch.object(requests.Session, "post", return_value=_login_ok()), + ): + driver.open() + fetch.assert_not_called() + assert driver._transport == "api" -- 2.54.1 From e51ddcd151495296f51e51e1b213e77133e6eac3 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 22:24:30 +0100 Subject: [PATCH 2/3] fix(rest): no plain-HTTP login for a switch with a pinned certificate The probe falls back to HTTP when HTTPS does not answer. For a switch known by its certificate that is a downgrade anyone who blocks port 443 can force: the login would go out in clear text, unchecked. With a pinned fingerprint the REST API is skipped then and the CLI transports are tried; without one, plain HTTP is used as before. Refs #17 --- CHANGELOG.md | 4 ++++ README.md | 2 +- napalm_procurve/procurve.py | 11 ++++++++-- tests/quality_baseline.json | 2 +- tests/unit/test_rest_certificate.py | 31 +++++++++++++++++++++++++++++ 5 files changed, 46 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01bf9e1..02ed381 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ All notable changes to this driver. The format follows does not fall back to SSH or Telnet then. Every connection of the REST session is held to the certificate checked (#17). - A REST login that failed is no longer retried with certificate verification turned off. +- A switch whose certificate is pinned is not logged in to over plain HTTP: when only + HTTP answers, the REST API is skipped and the CLI transports are tried. Blocking port + 443 would otherwise downgrade the login to clear text. Without a pin, plain HTTP is + used as before (#17). ### Changed - `ssl_verify` (`verify_ssl`, `verify`) no longer has any effect: the REST certificate is diff --git a/README.md b/README.md index dba4484..4ba3c75 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ has one (napalm-device-types): A refused host key or certificate ends `open()` with a `ConnectionException` naming both fingerprints. The driver does not try the next transport then: it would reach the same host with the same password, over Telnet in clear text. Plain HTTP REST has no -certificate to check. +certificate to check: a switch with a pinned certificate is not logged in to over it. ## Switch prerequisites diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 76c7533..eddf673 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -41,7 +41,7 @@ from napalm_device_types.ssh_host_keys import ( HostKeyCheck, SshHostKeyMismatch, ) -from napalm_device_types.tls_certificates import TlsCertificateMismatch +from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch from netmiko import ConnectHandler from netmiko.exceptions import ( NetmikoAuthenticationException, @@ -49,7 +49,7 @@ from netmiko.exceptions import ( ) from napalm_procurve import parsers -from napalm_procurve.api_client import ProcurveApiClient +from napalm_procurve.api_client import HTTPS_PORT, ProcurveApiClient logger = logging.getLogger("napalm_procurve") @@ -275,6 +275,10 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): logger.warning("REST API not detected on %s — falling back to CLI", self.hostname) self._attempts.append("api: not detected") return False + if proto == "http" and self._certificate_pinned(): + # Port 443 blocked would otherwise downgrade the login to clear text (#17). + self._attempts.append("api: only plain HTTP answered, the certificate is pinned") + return False client = ProcurveApiClient( hostname=self.hostname, @@ -297,6 +301,9 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver): logger.info("Connected to %s via REST API (%s %s)", self.hostname, proto, ver) return True + def _certificate_pinned(self) -> bool: + return CertificateCheck(self._optional_args, self.hostname, HTTPS_PORT).expected is not None + def _netmiko_kwargs(self, legacy: bool = False) -> dict: """Return kwargs for ConnectHandler, merging explicit fields with netmiko_optional_args. diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index da90cab..068daeb 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": 1387 + "napalm_procurve/procurve.py": 1394 }, "untyped_public": [ "napalm_procurve/procurve.py::ProcurveDriver.get_snmp_config" diff --git a/tests/unit/test_rest_certificate.py b/tests/unit/test_rest_certificate.py index 7e76c22..3b09778 100644 --- a/tests/unit/test_rest_certificate.py +++ b/tests/unit/test_rest_certificate.py @@ -209,3 +209,34 @@ class TestUnreachable: driver.open() fetch.assert_not_called() assert driver._transport == "api" + + +class TestNoPlainHttpWhenPinned: + """A switch known by its certificate is not logged in to over plain HTTP. + + Blocking port 443 would otherwise downgrade the login to clear text, unchecked. + """ + + def test_a_pinned_switch_that_answers_only_http_gets_no_rest_login(self): + driver = _driver([], known=SWITCH_FP) + cli = MagicMock() + cli.base_prompt = "switch" + with ( + patch(PROBE, return_value=("v7", "http")), + patch.object(requests.Session, "post") as post, + patch.object(ProcurveDriver, "_ssh_connect", return_value=cli), + ): + driver.open() + post.assert_not_called() + assert driver._transport == "ssh" + assert any("plain HTTP" in a for a in driver._attempts) + + def test_without_a_pin_plain_http_is_used_as_before(self): + driver = _driver([]) + with ( + patch(PROBE, return_value=("v7", "http")), + patch.object(requests.Session, "post", return_value=_login_ok()) as post, + ): + driver.open() + assert post.call_count == 1 + assert driver._transport == "api" -- 2.54.1 From b3c239d98889268b8b0bab18e1ccf031b8bba59a Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Mon, 2 Nov 2026 00:37:23 +0100 Subject: [PATCH 3/3] chore(deps): floor napalm-device-types at 4.23.0 4.23.0 is on PyPI with everything this branch uses, the REST certificate check (tls_certificates) included. --- CHANGELOG.md | 1 + pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b45565d..562b772 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this driver. The format follows ## [Unreleased] ### Changed +- The floor on napalm-device-types is 4.23.0, the first release with what this driver uses. - `ssl_verify` (`verify_ssl`, `verify`) no longer has any effect: the REST certificate is verified by its fingerprint instead. Callers that set it to `True` had their login retried without verification whenever the self-signed certificate failed the CA check. diff --git a/pyproject.toml b/pyproject.toml index 7a95fe3..83457c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.21.1", + "napalm-device-types>=4.23.0", "netmiko>=4.3.0", # takes a SessionLog object as session_log "paramiko>=5.0.0", # CVE-2026-44405 "netaddr>=0.7.10", -- 2.54.1