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

+1 -1
View File
@@ -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"
+211
View File
@@ -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"