driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m11s
driver / test (3.12) (pull_request) Failing after 1m9s
driver / test (3.13) (pull_request) Failing after 1m0s
driver / lowest (pull_request) Failing after 29s
driver / build (pull_request) Successful in 37s
driver / security (pull_request) Successful in 1m17s
CI / driver (pull_request) Failing after 3m1s
driver / publish (pull_request) Skipped
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
243 lines
9.0 KiB
Python
243 lines
9.0 KiB
Python
"""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"
|