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
This commit is contained in:
Christian Manivong committed 2026-11-01 22:18:33 +01:00
1 parent 58428042f1
commit cb7268b89c
6 files changed
+320 -54

No files matched your search

+44 -11
View File
@@ -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())."""
+31 -41
View File
@@ -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.