fix(rest): verify the API certificate by its fingerprint (#17) #23
No files matched your search
@@ -7,6 +7,10 @@ All notable changes to this driver. The format follows
|
|||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### Changed
|
### 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.
|
||||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
- 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).
|
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
|
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
|
||||||
@@ -17,6 +21,19 @@ All notable changes to this driver. The format follows
|
|||||||
a session log object, which older releases do not accept.
|
a session log object, which older releases do not accept.
|
||||||
|
|
||||||
### Fixed
|
### 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.
|
||||||
|
- 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).
|
||||||
- `cli()` over the REST API returns the command's output. It returned the API's
|
- `cli()` over the REST API returns the command's output. It returned the API's
|
||||||
base64 encoding of it as it came, NUL byte included.
|
base64 encoding of it as it came, NUL byte included.
|
||||||
- `configure_snmp_agent` over the REST API opens its temporary SSH session on port 22.
|
- `configure_snmp_agent` over the REST API opens its temporary SSH session on port 22.
|
||||||
|
|||||||
@@ -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
|
Override the transport with `optional_args={"transport": "ssh_legacy"}` to skip
|
||||||
auto-detection.
|
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: a switch with a pinned certificate is not logged in to over it.
|
||||||
|
|
||||||
## Switch prerequisites
|
## Switch prerequisites
|
||||||
|
|
||||||
### REST API (newer switches, e.g. 2530, 2540)
|
### REST API (newer switches, e.g. 2530, 2540)
|
||||||
@@ -63,7 +81,7 @@ with Driver(
|
|||||||
optional_args={
|
optional_args={
|
||||||
# "transport": "ssh", # force transport (api/ssh/ssh_legacy/telnet)
|
# "transport": "ssh", # force transport (api/ssh/ssh_legacy/telnet)
|
||||||
# "port": 22,
|
# "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)
|
# "api_version": "v7", # API version hint (v3/v6/v7)
|
||||||
# "secret": "enablepassword", # enable password for CLI
|
# "secret": "enablepassword", # enable password for CLI
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ Used automatically by ProcurveDriver when the REST API is reachable.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from contextlib import nullcontext
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
@@ -14,9 +16,13 @@ import urllib3
|
|||||||
from napalm.base import helpers as napalm_helpers
|
from napalm.base import helpers as napalm_helpers
|
||||||
from napalm.base.exceptions import ConnectAuthError, ConnectionException
|
from napalm.base.exceptions import ConnectAuthError, ConnectionException
|
||||||
from napalm_device_types import add_lag_interfaces
|
from napalm_device_types import add_lag_interfaces
|
||||||
|
from napalm_device_types.tls_certificates import CertificateCheck
|
||||||
|
|
||||||
logger = logging.getLogger("napalm_procurve.api")
|
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:
|
class ProcurveApiClient:
|
||||||
"""Thin wrapper around ArubaOS REST API sessions.
|
"""Thin wrapper around ArubaOS REST API sessions.
|
||||||
@@ -104,8 +110,21 @@ class ProcurveApiClient:
|
|||||||
# Session management
|
# Session management
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def connect(self) -> None:
|
def connect(
|
||||||
"""Open an authenticated REST API session."""
|
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:
|
if not self._base_url:
|
||||||
raise ConnectionException(
|
raise ConnectionException(
|
||||||
"ProcurveApiClient.connect() called before api_version/proto set. "
|
"ProcurveApiClient.connect() called before api_version/proto set. "
|
||||||
@@ -114,16 +133,28 @@ class ProcurveApiClient:
|
|||||||
if not self.ssl_verify:
|
if not self.ssl_verify:
|
||||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||||
|
|
||||||
self._session = requests.Session()
|
check = self._open_session(certificate_args, check_timeout)
|
||||||
self._session.verify = self.ssl_verify
|
|
||||||
self._session.headers.update({"Content-Type": "application/json", "Connection": "close"})
|
|
||||||
|
|
||||||
url = self._base_url + "login-sessions"
|
url = self._base_url + "login-sessions"
|
||||||
|
with check.refusing() if check is not None else nullcontext():
|
||||||
resp = self._session.post(
|
resp = self._session.post(
|
||||||
url,
|
url,
|
||||||
json={"userName": self.username, "password": self.password},
|
json={"userName": self.username, "password": self.password},
|
||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
)
|
)
|
||||||
|
self._require_login(resp)
|
||||||
|
# AOS-Switch returns the session cookie in the JSON body rather than
|
||||||
|
# via Set-Cookie — it must be sent back as a Cookie header on every
|
||||||
|
# subsequent request, otherwise writes (POST/PUT/DELETE) are rejected
|
||||||
|
# with "Access is unauthorized" while reads still succeed.
|
||||||
|
cookie = resp.json().get("cookie")
|
||||||
|
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 _require_login(self, resp: requests.Response) -> None:
|
||||||
|
"""Raise unless *resp* is a successful login."""
|
||||||
if "html" in resp.headers.get("Content-Type", "").lower():
|
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.
|
# The web UI's "session timed out" page, for any user (#13): not a login result.
|
||||||
raise ConnectionException(
|
raise ConnectionException(
|
||||||
@@ -134,14 +165,20 @@ class ProcurveApiClient:
|
|||||||
raise ConnectAuthError(
|
raise ConnectAuthError(
|
||||||
f"REST API login failed (HTTP {resp.status_code}) for {self.hostname}"
|
f"REST API login failed (HTTP {resp.status_code}) for {self.hostname}"
|
||||||
)
|
)
|
||||||
# AOS-Switch returns the session cookie in the JSON body rather than
|
|
||||||
# via Set-Cookie — it must be sent back as a Cookie header on every
|
def _open_session(
|
||||||
# subsequent request, otherwise writes (POST/PUT/DELETE) are rejected
|
self, certificate_args: Mapping[str, Any] | None, check_timeout: float
|
||||||
# with "Access is unauthorized" while reads still succeed.
|
) -> CertificateCheck | None:
|
||||||
cookie = resp.json().get("cookie")
|
"""A new session; over HTTPS pinned to the switch's certificate, checked first."""
|
||||||
if cookie:
|
self._session = requests.Session()
|
||||||
self._session.headers.update({"Cookie": cookie})
|
self._session.verify = self.ssl_verify
|
||||||
logger.debug("REST API login OK for %s", self.hostname)
|
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:
|
def setup(self, api_version: str, proto: str) -> None:
|
||||||
"""Set the API version and protocol (called after probe())."""
|
"""Set the API version and protocol (called after probe())."""
|
||||||
|
|||||||
+25
-28
@@ -41,11 +41,12 @@ from napalm_device_types.ssh_host_keys import (
|
|||||||
HostKeyCheck,
|
HostKeyCheck,
|
||||||
SshHostKeyMismatch,
|
SshHostKeyMismatch,
|
||||||
)
|
)
|
||||||
|
from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch
|
||||||
from netmiko import ConnectHandler
|
from netmiko import ConnectHandler
|
||||||
from netmiko.exceptions import NetmikoAuthenticationException
|
from netmiko.exceptions import NetmikoAuthenticationException
|
||||||
|
|
||||||
from napalm_procurve import parsers
|
from napalm_procurve import parsers
|
||||||
from napalm_procurve.api_client import ProcurveApiClient
|
from napalm_procurve.api_client import HTTPS_PORT, ProcurveApiClient
|
||||||
from napalm_procurve.connect_reasons import NO_FREE_TELNET_SESSION, TelnetTranscript, failure_reason
|
from napalm_procurve.connect_reasons import NO_FREE_TELNET_SESSION, TelnetTranscript, failure_reason
|
||||||
|
|
||||||
logger = logging.getLogger("napalm_procurve")
|
logger = logging.getLogger("napalm_procurve")
|
||||||
@@ -143,9 +144,6 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
|||||||
self.port: int = optional_args.get("port", 22)
|
self.port: int = optional_args.get("port", 22)
|
||||||
self.telnet_port: int = optional_args.get("telnet_port", 23)
|
self.telnet_port: int = optional_args.get("telnet_port", 23)
|
||||||
self.force_transport: str | None = optional_args.get("transport")
|
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")
|
self.api_version_hint: str | None = optional_args.get("api_version")
|
||||||
# Enable password for CLI (defaults to login password)
|
# Enable password for CLI (defaults to login password)
|
||||||
self._secret: str = optional_args.get("secret", password)
|
self._secret: str = optional_args.get("secret", password)
|
||||||
@@ -154,10 +152,12 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
|||||||
logger.setLevel(logging.DEBUG)
|
logger.setLevel(logging.DEBUG)
|
||||||
|
|
||||||
self.netmiko_optional_args = netmiko_args(optional_args)
|
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] = {
|
self._host_key_args: dict[str, Any] = {
|
||||||
k: optional_args[k] for k in (KNOWN_KEYS_ARG, OBSERVER_ARG) if k in optional_args
|
k: optional_args[k] for k in (KNOWN_KEYS_ARG, OBSERVER_ARG) if k in optional_args
|
||||||
}
|
}
|
||||||
|
self._optional_args = optional_args
|
||||||
|
|
||||||
# --- runtime state ---
|
# --- runtime state ---
|
||||||
# Active transport: "api" | "ssh" | "ssh_legacy" | "telnet"
|
# Active transport: "api" | "ssh" | "ssh_legacy" | "telnet"
|
||||||
@@ -257,54 +257,51 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def _try_api(self) -> bool:
|
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)
|
probe_timeout = min(self.timeout, 15)
|
||||||
logger.info("Probing REST API for %s (timeout=%ds)", self.hostname, probe_timeout)
|
logger.info("Probing REST API for %s (timeout=%ds)", self.hostname, probe_timeout)
|
||||||
# Probe without SSL verification — no credentials are sent during probing,
|
# The probe sends no credentials; the login checks the certificate first.
|
||||||
# so this is safe and avoids failing on self-signed certificates.
|
|
||||||
ver, proto = ProcurveApiClient.probe(self.hostname, timeout=probe_timeout, ssl_verify=False)
|
ver, proto = ProcurveApiClient.probe(self.hostname, timeout=probe_timeout, ssl_verify=False)
|
||||||
# Allow hint override (e.g. user knows the API version)
|
# Allow hint override (e.g. user knows the API version)
|
||||||
if self.api_version_hint and proto:
|
if self.api_version_hint and proto:
|
||||||
ver = self.api_version_hint
|
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)
|
logger.warning("REST API not detected on %s — falling back to CLI", self.hostname)
|
||||||
self._attempts.append("api: not detected")
|
self._attempts.append("api: not detected")
|
||||||
return False
|
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
|
||||||
|
|
||||||
# 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(
|
client = ProcurveApiClient(
|
||||||
hostname=self.hostname,
|
hostname=self.hostname,
|
||||||
username=self.username,
|
username=self.username,
|
||||||
password=self.password,
|
password=self.password,
|
||||||
timeout=self.timeout,
|
timeout=self.timeout,
|
||||||
ssl_verify=ssl_verify,
|
|
||||||
api_version=ver,
|
api_version=ver,
|
||||||
)
|
)
|
||||||
client.setup(ver, proto)
|
client.setup(ver, proto)
|
||||||
try:
|
try:
|
||||||
client.connect()
|
client.connect(certificate_args=self._optional_args, check_timeout=probe_timeout)
|
||||||
|
except TlsCertificateMismatch:
|
||||||
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.debug("REST API connect failed (ssl_verify=%s): %s", ssl_verify, exc)
|
logger.warning("REST API connect failed for %s — falling back to CLI", self.hostname)
|
||||||
error = exc
|
self._attempts.append(f"api: {exc}")
|
||||||
continue
|
return False
|
||||||
self._api = client
|
self._api = client
|
||||||
self._transport = "api"
|
self._transport = "api"
|
||||||
logger.info(
|
logger.info("Connected to %s via REST API (%s %s)", self.hostname, proto, ver)
|
||||||
"Connected to %s via REST API (%s %s, ssl_verify=%s)",
|
|
||||||
self.hostname,
|
|
||||||
proto,
|
|
||||||
ver,
|
|
||||||
ssl_verify,
|
|
||||||
)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
logger.warning("REST API connect failed for %s — falling back to CLI", self.hostname)
|
def _certificate_pinned(self) -> bool:
|
||||||
self._attempts.append(f"api: {error}")
|
return CertificateCheck(self._optional_args, self.hostname, HTTPS_PORT).expected is not None
|
||||||
return False
|
|
||||||
|
|
||||||
def _netmiko_kwargs(self, legacy: bool = False) -> dict:
|
def _netmiko_kwargs(self, legacy: bool = False) -> dict:
|
||||||
"""Return kwargs for ConnectHandler, merging explicit fields with netmiko_optional_args.
|
"""Return kwargs for ConnectHandler, merging explicit fields with netmiko_optional_args.
|
||||||
|
|||||||
+1
-1
@@ -22,7 +22,7 @@ classifiers = [
|
|||||||
]
|
]
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
"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
|
"netmiko>=4.3.0", # takes a SessionLog object as session_log
|
||||||
"paramiko>=5.0.0", # CVE-2026-44405
|
"paramiko>=5.0.0", # CVE-2026-44405
|
||||||
"netaddr>=0.7.10",
|
"netaddr>=0.7.10",
|
||||||
|
|||||||
@@ -27,7 +27,7 @@
|
|||||||
"napalm_procurve.procurve"
|
"napalm_procurve.procurve"
|
||||||
],
|
],
|
||||||
"python_file_lines": {
|
"python_file_lines": {
|
||||||
"napalm_procurve/procurve.py": 1390
|
"napalm_procurve/procurve.py": 1387
|
||||||
},
|
},
|
||||||
"untyped_public": []
|
"untyped_public": []
|
||||||
}
|
}
|
||||||
@@ -20,6 +20,7 @@ from napalm_procurve.procurve import ProcurveDriver
|
|||||||
|
|
||||||
HANDLER = "napalm_procurve.procurve.ConnectHandler"
|
HANDLER = "napalm_procurve.procurve.ConnectHandler"
|
||||||
PROBE = "napalm_procurve.procurve.ProcurveApiClient.probe"
|
PROBE = "napalm_procurve.procurve.ProcurveApiClient.probe"
|
||||||
|
FETCH_CERTIFICATE = "napalm_device_types.tls_certificates.fetch_certificate"
|
||||||
|
|
||||||
# What a ProCurve 2520G prints instead of a login prompt when every session is taken.
|
# 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"
|
NO_FREE_SESSION = "Sorry, the maximum number of telnet sessions are active. Try again later.\r\n"
|
||||||
@@ -119,7 +120,11 @@ def _client_answering(status: int, content_type: str) -> ProcurveApiClient:
|
|||||||
session = MagicMock()
|
session = MagicMock()
|
||||||
session.post.return_value = response
|
session.post.return_value = response
|
||||||
session.headers = {}
|
session.headers = {}
|
||||||
with patch("napalm_procurve.api_client.requests.Session", return_value=session):
|
with (
|
||||||
|
patch("napalm_procurve.api_client.requests.Session", return_value=session),
|
||||||
|
# The certificate is checked before the login (#17); this is the switch's own.
|
||||||
|
patch(FETCH_CERTIFICATE, return_value=b"the switch's certificate"),
|
||||||
|
):
|
||||||
client.connect()
|
client.connect()
|
||||||
return client
|
return client
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
"""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"
|
||||||
|
|
||||||
|
|
||||||
|
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"
|
||||||
Reference in new issue
Block a user