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"