Merge remote-tracking branch 'origin/main' into fix/rest-cert-tofu-17
The REST login now checks the certificate before it posts the password (#17) and then tells a web page from a refused login (#13); the two login-answer checks moved into _require_login so connect() stays within the function-length limit. #13's REST tests stand in for the switch's certificate, since connect() fetches it before the login.
This commit is contained in:
commit
586632efe0
13 files changed
+517
-75
No files matched your search
+28
-11
@@ -6,6 +6,19 @@ All notable changes to this driver. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### 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
|
||||
3.12 venv no longer has.
|
||||
- The floor on urllib3 is 1.26.5: older releases bundle a `six` that Python 3.12
|
||||
cannot import.
|
||||
- The floor on netmiko is 4.3.0: the Telnet login reads the switch's greeting through
|
||||
a session log object, which older releases do not accept.
|
||||
|
||||
### 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:
|
||||
@@ -20,17 +33,21 @@ All notable changes to this driver. The format follows
|
||||
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).
|
||||
|
||||
### 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
|
||||
3.12 venv no longer has.
|
||||
- The floor on urllib3 is 1.26.5: older releases bundle a `six` that Python 3.12
|
||||
cannot import.
|
||||
- `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.
|
||||
- `configure_snmp_agent` over the REST API opens its temporary SSH session on port 22.
|
||||
It used `optional_args["port"]`, which names the REST API's port when REST is the
|
||||
transport, so the SNMP setup failed on switches managed over REST.
|
||||
- A switch whose Telnet sessions are all taken is reported as such ("the switch has no
|
||||
free session"), as a connection error. It was reported as an authentication failure,
|
||||
which pointed at the password.
|
||||
- A REST API that answers the login with an HTML page is reported as "answered with a
|
||||
web page instead of JSON", not as a failed login.
|
||||
- An SSH attempt that failed for another reason than a timeout, such as no common key
|
||||
exchange algorithm, names that reason instead of "timed out".
|
||||
- `get_snmp_config` reads the switch's communities over the REST API too. It returned
|
||||
`None` there, so a switch managed over REST always read as having no SNMP. A read that
|
||||
fails now raises instead of reading as "no SNMP" (REST transport).
|
||||
|
||||
## [0.6.0] - 2026-10-23
|
||||
|
||||
|
||||
@@ -141,10 +141,7 @@ class ProcurveApiClient:
|
||||
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}"
|
||||
)
|
||||
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
|
||||
@@ -156,6 +153,19 @@ class ProcurveApiClient:
|
||||
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():
|
||||
# The web UI's "session timed out" page, for any user (#13): not a login result.
|
||||
raise ConnectionException(
|
||||
f"REST API on {self.hostname} answered with a web page instead of JSON "
|
||||
f"(HTTP {resp.status_code})"
|
||||
)
|
||||
if resp.status_code != 201:
|
||||
raise ConnectAuthError(
|
||||
f"REST API login failed (HTTP {resp.status_code}) for {self.hostname}"
|
||||
)
|
||||
|
||||
def _open_session(
|
||||
self, certificate_args: Mapping[str, Any] | None, check_timeout: float
|
||||
) -> CertificateCheck | None:
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Licensed under the Apache License, Version 2.0
|
||||
|
||||
"""Why a transport failed, in the switch's terms rather than netmiko's.
|
||||
|
||||
netmiko reports a Telnet greeting that refuses every login as a failed login,
|
||||
and every paramiko error during the SSH handshake as a timeout. These helpers
|
||||
recover what actually happened, so a busy switch does not read as a wrong
|
||||
password and a key-exchange mismatch not as an unreachable host.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from netmiko.exceptions import NetmikoTimeoutException
|
||||
from netmiko.session_log import SessionLog
|
||||
|
||||
#: What the switch prints instead of a login prompt when every Telnet session is taken.
|
||||
_NO_FREE_SESSION = re.compile(r"maximum number of telnet sessions", re.I)
|
||||
|
||||
#: Only the greeting matters; the session that follows is not kept in memory.
|
||||
_GREETING_CHARS = 4096
|
||||
|
||||
NO_FREE_TELNET_SESSION = "the switch has no free session (maximum number of telnet sessions active)"
|
||||
|
||||
|
||||
class TelnetTranscript(SessionLog):
|
||||
"""The start of what the switch sent, in memory; netmiko's writes are not recorded."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(record_writes=False)
|
||||
self.text = ""
|
||||
|
||||
def write(self, data: str) -> None:
|
||||
"""Keep the start of what netmiko read from the channel."""
|
||||
if len(self.text) < _GREETING_CHARS:
|
||||
self.text += data
|
||||
|
||||
@property
|
||||
def no_free_session(self) -> bool:
|
||||
"""Whether the switch refused the session before any login."""
|
||||
return bool(_NO_FREE_SESSION.search(self.text))
|
||||
|
||||
|
||||
def failure_reason(exc: Exception) -> str:
|
||||
"""The reason to record for a failed SSH attempt.
|
||||
|
||||
netmiko raises :class:`NetmikoTimeoutException` for a socket error and for any
|
||||
paramiko error alike; the original one is its context.
|
||||
"""
|
||||
if not isinstance(exc, NetmikoTimeoutException):
|
||||
return str(exc)
|
||||
cause = exc.__cause__ or exc.__context__
|
||||
if cause is None or isinstance(cause, TimeoutError):
|
||||
return "timed out"
|
||||
return str(cause) or type(cause).__name__
|
||||
@@ -7,6 +7,7 @@ command output strings. The same parsers are shared by the SSH and Telnet
|
||||
backends.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import re
|
||||
|
||||
#: get_users' password field: the switch never shows a password, so it stays empty.
|
||||
@@ -927,3 +928,9 @@ def derive_port_pvids(vlans: dict[int, dict]) -> dict[str, int]:
|
||||
pvids[port] = 1
|
||||
|
||||
return pvids
|
||||
|
||||
|
||||
def parse_cli_answer(answer: dict[str, str]) -> str:
|
||||
"""The output in a REST ``/cli`` answer: base64, the switch ends it with a NUL byte."""
|
||||
encoded = answer.get("result_base64_encoded", "")
|
||||
return base64.b64decode(encoded).decode("utf-8", "replace").rstrip("\x00")
|
||||
+47
-54
@@ -34,7 +34,7 @@ from napalm_device_types import (
|
||||
add_lag_interfaces,
|
||||
run_fix_steps,
|
||||
)
|
||||
from napalm_device_types.models import InterfaceConfigDict, VlanConfigDict
|
||||
from napalm_device_types.models import InterfaceConfigDict, SNMPConfigDict, VlanConfigDict
|
||||
from napalm_device_types.ssh_host_keys import (
|
||||
KNOWN_KEYS_ARG,
|
||||
OBSERVER_ARG,
|
||||
@@ -43,13 +43,11 @@ from napalm_device_types.ssh_host_keys import (
|
||||
)
|
||||
from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch
|
||||
from netmiko import ConnectHandler
|
||||
from netmiko.exceptions import (
|
||||
NetmikoAuthenticationException,
|
||||
NetmikoTimeoutException,
|
||||
)
|
||||
from netmiko.exceptions import NetmikoAuthenticationException
|
||||
|
||||
from napalm_procurve import parsers
|
||||
from napalm_procurve.api_client import HTTPS_PORT, ProcurveApiClient
|
||||
from napalm_procurve.connect_reasons import NO_FREE_TELNET_SESSION, TelnetTranscript, failure_reason
|
||||
|
||||
logger = logging.getLogger("napalm_procurve")
|
||||
|
||||
@@ -80,6 +78,7 @@ _SSH_DISABLED_LEGACY = {
|
||||
}
|
||||
|
||||
|
||||
_SSH_PORT_BESIDE_API = 22 # SSH beside the REST API: ``port`` then is the API's (#17)
|
||||
#: What may stand in a quoted CLI value: no whitespace, quote or #.
|
||||
_CLI_WORD = re.compile(r'^[^\s"#]+$')
|
||||
|
||||
@@ -359,18 +358,15 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
raise
|
||||
except NetmikoAuthenticationException as exc:
|
||||
raise self._auth_failure(transport, exc) from exc
|
||||
except NetmikoTimeoutException:
|
||||
logger.debug("%s timeout for %s", label, self.hostname)
|
||||
self._attempts.append(f"{transport}: timed out")
|
||||
return False
|
||||
except Exception as exc:
|
||||
logger.debug("%s failed for %s: %s", label, self.hostname, exc)
|
||||
self._attempts.append(f"{transport}: {exc}")
|
||||
self._attempts.append(f"{transport}: {failure_reason(exc)}")
|
||||
return False
|
||||
|
||||
def _try_telnet(self) -> bool:
|
||||
"""Probe and connect via Telnet. Returns True on success."""
|
||||
logger.debug("Trying Telnet for %s", self.hostname)
|
||||
transcript = TelnetTranscript() # a full switch refuses before the login (#13)
|
||||
try:
|
||||
conn = ConnectHandler(
|
||||
device_type=self.NETMIKO_DEVICE_TYPE_TELNET,
|
||||
@@ -380,13 +376,17 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
secret=self._secret,
|
||||
port=self.telnet_port,
|
||||
timeout=self.timeout,
|
||||
session_log=transcript,
|
||||
)
|
||||
self._device = conn
|
||||
self._transport = "telnet"
|
||||
logger.info("Connected to %s via Telnet", self.hostname)
|
||||
return True
|
||||
except NetmikoAuthenticationException as exc:
|
||||
raise self._auth_failure("telnet", exc) from exc
|
||||
if not transcript.no_free_session:
|
||||
raise self._auth_failure("telnet", exc) from exc
|
||||
self._attempts.append(f"telnet: {NO_FREE_TELNET_SESSION}")
|
||||
return False
|
||||
except Exception as exc:
|
||||
logger.debug("Telnet failed for %s: %s", self.hostname, exc)
|
||||
self._attempts.append(f"telnet: {exc}")
|
||||
@@ -660,11 +660,10 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
|
||||
HP ProCurve switches do not support exec_channel SSH; they require
|
||||
an interactive shell (invoke_shell), which netmiko's hp_procurve
|
||||
device type handles correctly. Port 22 is used explicitly because
|
||||
self.port is the REST API port (443) in API transport mode.
|
||||
device type handles correctly. Port 22: ``port`` is the REST API's.
|
||||
"""
|
||||
try:
|
||||
conn = self._ssh_connect(port=22) # always SSH — self.port is the REST API port
|
||||
conn = self._ssh_connect(port=_SSH_PORT_BESIDE_API)
|
||||
try:
|
||||
return conn.send_command("show running-config")
|
||||
finally:
|
||||
@@ -1143,7 +1142,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
for cmd in commands:
|
||||
resp = self._api.post("cli", json={"cmd": cmd})
|
||||
if resp.ok:
|
||||
results[cmd] = resp.json().get("result_base64_encoded", "")
|
||||
results[cmd] = parsers.parse_cli_answer(resp.json())
|
||||
else:
|
||||
results[cmd] = f"Error: HTTP {resp.status_code}"
|
||||
return results
|
||||
@@ -1202,47 +1201,41 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
"""Return device warnings. SNMP detection handled by poll task."""
|
||||
return []
|
||||
|
||||
def get_snmp_config(self):
|
||||
"""Return SNMP config if a community is configured on the switch."""
|
||||
try:
|
||||
from napalm_device_types.models import SNMPConfigDict
|
||||
except ImportError:
|
||||
return None
|
||||
def get_snmp_config(self) -> SNMPConfigDict | None:
|
||||
"""The community of the built-in agent, read-only preferred; None without one.
|
||||
|
||||
# Use a single command with short read_timeout to avoid blocking the poll.
|
||||
try:
|
||||
out = (
|
||||
self._device.send_command(
|
||||
"show snmp-server",
|
||||
expect_string=rf"{re.escape(self._device.base_prompt)}[>#]",
|
||||
read_timeout=10,
|
||||
).strip()
|
||||
if self._device
|
||||
else ""
|
||||
)
|
||||
except Exception:
|
||||
Over REST, ``show snmp-server`` runs through the API's ``/cli`` endpoint (#10).
|
||||
"""
|
||||
if self._transport == "api":
|
||||
out = self._api_show("show snmp-server")
|
||||
else:
|
||||
# Use a single command with short read_timeout to avoid blocking the poll.
|
||||
try:
|
||||
out = (
|
||||
self._device.send_command(
|
||||
"show snmp-server",
|
||||
expect_string=rf"{re.escape(self._device.base_prompt)}[>#]",
|
||||
read_timeout=10,
|
||||
)
|
||||
if self._device
|
||||
else ""
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
communities = parsers.parse_snmp_info(out)["community"]
|
||||
if not communities:
|
||||
return None
|
||||
if not out:
|
||||
return None
|
||||
|
||||
# Parse communities from output
|
||||
community = None
|
||||
for line in out.splitlines():
|
||||
m = re.match(r"\s+(\S+)\s+(Manager|Operator)\s+(Restricted|Unrestricted)", line, re.I)
|
||||
if m:
|
||||
comm = m.group(1)
|
||||
access = m.group(3).lower()
|
||||
if access == "restricted": # read-only — prefer this
|
||||
community = comm
|
||||
break
|
||||
elif community is None:
|
||||
community = comm # fallback to first found
|
||||
|
||||
if not community:
|
||||
return None
|
||||
|
||||
read_only = [name for name, c in communities.items() if c["mode"] == "ro"]
|
||||
community = (read_only or list(communities))[0]
|
||||
return SNMPConfigDict(running=True, community=community, port=161, version="2c")
|
||||
|
||||
def _api_show(self, command: str) -> str:
|
||||
"""The output of a show command through the REST API's ``/cli`` endpoint."""
|
||||
resp = self._api.post("cli", json={"cmd": command})
|
||||
if not resp.ok or resp.json().get("status") == "CCS_FAILURE":
|
||||
raise CommandErrorException(f"{command!r} over REST: HTTP {resp.status_code}")
|
||||
return parsers.parse_cli_answer(resp.json())
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# SNMP agent (napalm-device-types SnmpAgentMixin): the caller's values
|
||||
# ------------------------------------------------------------------
|
||||
@@ -1251,7 +1244,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
"""The agent is built in; configure community, contact and location, then save.
|
||||
|
||||
The REST API has no writable SNMP endpoint, so over REST a temporary SSH
|
||||
session runs the config-mode CLI.
|
||||
session on port 22 runs the config-mode CLI.
|
||||
"""
|
||||
steps = [
|
||||
("install", lambda: {"ok": True, "output": "the SNMP agent is built in"}),
|
||||
@@ -1266,7 +1259,7 @@ class ProcurveDriver(ConfigLifecycleMixin, SwitchDriver):
|
||||
ssh_error = ""
|
||||
for legacy in (False, True):
|
||||
try:
|
||||
self._device = self._ssh_connect(legacy)
|
||||
self._device = self._ssh_connect(legacy, port=_SSH_PORT_BESIDE_API)
|
||||
self._transport = "ssh_legacy" if legacy else "ssh"
|
||||
break
|
||||
except SshHostKeyMismatch as exc: # the same host either way
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ classifiers = [
|
||||
dependencies = [
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm-device-types>=4.21.1",
|
||||
"netmiko>=4.0.0",
|
||||
"netmiko>=4.3.0", # takes a SessionLog object as session_log
|
||||
"paramiko>=5.0.0", # CVE-2026-44405
|
||||
"netaddr>=0.7.10",
|
||||
"requests>=2.25.0",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
CiBTTk1QIENvbW11bml0aWVzCgogIENvbW11bml0eSBOYW1lICAgICAgICAgICAgICAgICAgIE1JQiBWaWV3IFdyaXRlIEFjY2VzcwogIC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tIC0tLS0tLS0tIC0tLS0tLS0tLS0tLQogIHB1YmxpYyAgICAgICAgICAgICAgICAgICAgICAgICAgIE9wZXJhdG9yIFJlc3RyaWN0ZWQgIAogCiBUcmFwIFJlY2VpdmVycwoKICBMaW5rLUNoYW5nZSBUcmFwcyBFbmFibGVkIG9uIFBvcnRzIFtBbGxdIDogQWxsCgogIFRyYXBzIENhdGVnb3J5ICAgICAgICAgICAgICAgICAgICAgICAgICBDdXJyZW50IFN0YXR1cyAKICBfX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fICAgX19fX19fX19fX19fX19fX19fIAogIFNOTVAgQXV0aGVudGljYXRpb24gICAgICAgICAgICAgICAgICAgOiBFeHRlbmRlZCAKICBQYXNzd29yZCBjaGFuZ2UgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBMb2dpbiBmYWlsdXJlcyAgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBQb3J0LVNlY3VyaXR5ICAgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBBdXRob3JpemF0aW9uIFNlcnZlciBDb250YWN0ICAgICAgICAgIDogRW5hYmxlZCAKICBESENQLVNub29waW5nICAgICAgICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBESENQdjYtU25vb3BpbmcgT3V0IG9mIFJlc291cmNlICAgICAgIDogRW5hYmxlZCAKICBESENQdjYtU25vb3BpbmcgRXJyYW50IFJlcGxpZXMgICAgICAgIDogRW5hYmxlZCAKICBEeW5hbWljIEFSUCBQcm90ZWN0aW9uICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBEeW5hbWljIElQIExvY2tkb3duICAgICAgICAgICAgICAgICAgIDogRW5hYmxlZCAKICBEeW5hbWljIElQdjYgTG9ja2Rvd24gT3V0IG9mIFJlc291cmNlIDogRW5hYmxlZCAKICBEeW5hbWljIElQdjYgTG9ja2Rvd24gVmlvbGF0aW9ucyAgICAgIDogRW5hYmxlZCAKICBTdGFydHVwIENvbmZpZyBjaGFuZ2UgICAgICAgICAgICAgICAgIDogRGlzYWJsZWQKICBSdW5uaW5nIENvbmZpZyBDaGFuZ2UgICAgICAgICAgICAgICAgIDogRGlzYWJsZWQKICBNQUMgYWRkcmVzcyB0YWJsZSBjaGFuZ2VzICAgICAgICAgICAgIDogRGlzYWJsZWQKICBNQUMgQWRkcmVzcyBDb3VudCAgICAgICAgICAgICAgICAgICAgIDogRGlzYWJsZWQKCiAgTlRQLUNsaWVudCAgICAgICAgICAgICAgICAgICAgICAgICAgICA6IERpc2FibGVkCgogIEFkZHJlc3MgICAgICAgICAgICAgICAgQ29tbXVuaXR5ICAgICAgICAgICAgICBFdmVudHMgICBUeXBlICAgUmV0cnkgICBUaW1lb3V0CiAgLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSAtLS0tLS0tLS0tLS0tLS0tLS0tLS0tIC0tLS0tLS0tIC0tLS0tLSAtLS0tLS0tIC0tLS0tLS0KICAxOTIuMC4yLjI1NCAgICAgICAgICAgIHB1YmxpYyAgICAgICAgICAgICAgICAgTm9uZSAgICAgdHJhcCAgIDMgICAgICAgMTUgICAgIAogCgogRXhjbHVkZWQgTUlCcwoKCiBTbm1wIFJlc3BvbnNlIFBkdSBTb3VyY2UtSVAgSW5mb3JtYXRpb24KCiAgU2VsZWN0aW9uIFBvbGljeSAgIDogcmZjMTUxNyAgICAgICAgICAgICAKCiBUcmFwIFBkdSBTb3VyY2UtSVAgSW5mb3JtYXRpb24KCiAgU2VsZWN0aW9uIFBvbGljeSAgIDogcmZjMTUxNyAgICAgICAgICAgICAKCgoA
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
|
||||
SNMP Communities
|
||||
|
||||
Community Name MIB View Write Access
|
||||
-------------------------------- -------- ------------
|
||||
public Operator Restricted
|
||||
|
||||
Trap Receivers
|
||||
|
||||
Link-Change Traps Enabled on Ports [All] : All
|
||||
|
||||
Traps Category Current Status
|
||||
_____________________________________ __________________
|
||||
SNMP Authentication : Extended
|
||||
Password change : Enabled
|
||||
Login failures : Enabled
|
||||
Port-Security : Enabled
|
||||
Authorization Server Contact : Enabled
|
||||
DHCP-Snooping : Enabled
|
||||
DHCPv6-Snooping Out of Resource : Enabled
|
||||
DHCPv6-Snooping Errant Replies : Enabled
|
||||
Dynamic ARP Protection : Enabled
|
||||
Dynamic IP Lockdown : Enabled
|
||||
Dynamic IPv6 Lockdown Out of Resource : Enabled
|
||||
Dynamic IPv6 Lockdown Violations : Enabled
|
||||
Startup Config change : Disabled
|
||||
Running Config Change : Disabled
|
||||
MAC address table changes : Disabled
|
||||
MAC Address Count : Disabled
|
||||
|
||||
NTP-Client : Disabled
|
||||
|
||||
Address Community Events Type Retry Timeout
|
||||
---------------------- ---------------------- -------- ------ ------- -------
|
||||
192.0.2.254 public None trap 3 15
|
||||
|
||||
|
||||
Excluded MIBs
|
||||
|
||||
|
||||
Snmp Response Pdu Source-IP Information
|
||||
|
||||
Selection Policy : rfc1517
|
||||
|
||||
Trap Pdu Source-IP Information
|
||||
|
||||
Selection Policy : rfc1517
|
||||
|
||||
|
||||
@@ -27,9 +27,7 @@
|
||||
"napalm_procurve.procurve"
|
||||
],
|
||||
"python_file_lines": {
|
||||
"napalm_procurve/procurve.py": 1394
|
||||
"napalm_procurve/procurve.py": 1387
|
||||
},
|
||||
"untyped_public": [
|
||||
"napalm_procurve/procurve.py::ProcurveDriver.get_snmp_config"
|
||||
]
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
"""cli() over REST returns the command's output, not the API's base64 of it.
|
||||
|
||||
The REST ``/cli`` endpoint answers ``{"result_base64_encoded": ...}``: the output in
|
||||
base64, ending in a NUL byte. cli() returned that string as it came.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from napalm_procurve.procurve import ProcurveDriver
|
||||
|
||||
FIXTURES = Path(__file__).parent.parent / "fixtures"
|
||||
|
||||
SHOW_SNMP_SERVER = (FIXTURES / "procurve-show-snmp-server.txt").read_text(encoding="utf-8")
|
||||
SHOW_SNMP_SERVER_REST = (FIXTURES / "procurve-rest-cli-show-snmp-server.b64").read_text().strip()
|
||||
|
||||
|
||||
def _rest_driver(resp: MagicMock) -> ProcurveDriver:
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
driver._api.post.return_value = resp
|
||||
return driver
|
||||
|
||||
|
||||
def test_over_rest_cli_returns_the_decoded_output():
|
||||
resp = MagicMock(ok=True, status_code=200)
|
||||
resp.json.return_value = {
|
||||
"cmd": "show snmp-server",
|
||||
"result_base64_encoded": SHOW_SNMP_SERVER_REST,
|
||||
"status": "CCS_SUCCESS",
|
||||
}
|
||||
|
||||
out = _rest_driver(resp).cli(["show snmp-server"])
|
||||
|
||||
assert out == {"show snmp-server": SHOW_SNMP_SERVER}
|
||||
|
||||
|
||||
def test_over_rest_cli_names_a_failed_request():
|
||||
resp = MagicMock(ok=False, status_code=401)
|
||||
|
||||
assert _rest_driver(resp).cli(["show version"]) == {"show version": "Error: HTTP 401"}
|
||||
@@ -0,0 +1,156 @@
|
||||
"""A failed connection names what the switch actually said (#13).
|
||||
|
||||
A switch whose Telnet sessions are all taken, a REST API that answers with the
|
||||
web UI's HTML page, and an SSH key exchange that found no common algorithm were
|
||||
all reported as a wrong password or a timeout, which sends the operator after
|
||||
the credentials instead of the session table.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import paramiko
|
||||
import pytest
|
||||
from napalm.base.exceptions import ConnectAuthError, ConnectionException
|
||||
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
|
||||
|
||||
from napalm_procurve.api_client import ProcurveApiClient
|
||||
from napalm_procurve.procurve import ProcurveDriver
|
||||
|
||||
HANDLER = "napalm_procurve.procurve.ConnectHandler"
|
||||
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.
|
||||
NO_FREE_SESSION = "Sorry, the maximum number of telnet sessions are active. Try again later.\r\n"
|
||||
|
||||
|
||||
def _telnet_refused(greeting: str):
|
||||
def connect(**kwargs):
|
||||
if kwargs["device_type"] != ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
|
||||
raise OSError("no route to host")
|
||||
kwargs["session_log"].write(greeting)
|
||||
raise NetmikoAuthenticationException(f"Login failed: {kwargs['host']}")
|
||||
|
||||
return connect
|
||||
|
||||
|
||||
def _open(connect, **optional_args) -> ConnectionException:
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args=optional_args)
|
||||
with patch(PROBE, return_value=(None, None)), patch(HANDLER, side_effect=connect):
|
||||
with pytest.raises(ConnectionException) as exc_info:
|
||||
driver.open()
|
||||
return exc_info.value
|
||||
|
||||
|
||||
# --- Telnet -----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_no_free_telnet_session_is_a_connection_error_not_a_wrong_password():
|
||||
error = _open(_telnet_refused(NO_FREE_SESSION))
|
||||
|
||||
msg = str(error)
|
||||
assert "Authentication failed" not in msg
|
||||
assert "telnet: the switch has no free session (maximum number of telnet sessions" in msg
|
||||
|
||||
|
||||
def test_a_refused_telnet_login_is_still_an_authentication_failure():
|
||||
error = _open(_telnet_refused("Password: \r\nInvalid password\r\n"))
|
||||
|
||||
assert "Authentication failed for 10.0.0.40 via telnet" in str(error)
|
||||
|
||||
|
||||
def test_the_telnet_transcript_records_what_the_switch_sent_not_the_password():
|
||||
sessions: list = []
|
||||
|
||||
def connect(**kwargs):
|
||||
sessions.append(kwargs["session_log"])
|
||||
return MagicMock()
|
||||
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args={"transport": "telnet"})
|
||||
with patch(HANDLER, side_effect=connect):
|
||||
driver.open()
|
||||
|
||||
assert sessions[0].record_writes is False
|
||||
|
||||
|
||||
# --- SSH --------------------------------------------------------------------
|
||||
|
||||
|
||||
def _wrapped(cause: Exception) -> NetmikoTimeoutException:
|
||||
"""What netmiko raises: its own exception, the paramiko or socket error as context."""
|
||||
exc = NetmikoTimeoutException("A paramiko SSHException occurred during connection creation")
|
||||
exc.__context__ = cause
|
||||
return exc
|
||||
|
||||
|
||||
def test_an_ssh_key_exchange_failure_is_named_not_reported_as_a_timeout():
|
||||
no_kex = paramiko.ssh_exception.IncompatiblePeer(
|
||||
"Incompatible ssh peer (no acceptable kex algorithm)"
|
||||
)
|
||||
|
||||
def connect(**kwargs):
|
||||
if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
|
||||
raise OSError("no route to host")
|
||||
raise _wrapped(no_kex)
|
||||
|
||||
msg = str(_open(connect))
|
||||
|
||||
assert "ssh: Incompatible ssh peer (no acceptable kex algorithm)" in msg
|
||||
assert "ssh: timed out" not in msg
|
||||
|
||||
|
||||
def test_an_ssh_timeout_is_still_reported_as_one():
|
||||
def connect(**kwargs):
|
||||
if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
|
||||
raise OSError("no route to host")
|
||||
raise _wrapped(TimeoutError("timed out"))
|
||||
|
||||
assert "ssh: timed out" in str(_open(connect))
|
||||
|
||||
|
||||
# --- REST -------------------------------------------------------------------
|
||||
|
||||
|
||||
def _client_answering(status: int, content_type: str) -> ProcurveApiClient:
|
||||
client = ProcurveApiClient("10.0.0.40", "manager", "s3cret")
|
||||
client.setup("v7", "https")
|
||||
response = MagicMock(status_code=status, headers={"Content-Type": content_type})
|
||||
session = MagicMock()
|
||||
session.post.return_value = response
|
||||
session.headers = {}
|
||||
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()
|
||||
return client
|
||||
|
||||
|
||||
def test_a_web_page_instead_of_a_rest_answer_is_not_a_login_failure():
|
||||
with pytest.raises(ConnectionException) as exc_info:
|
||||
_client_answering(200, "text/html; charset=utf-8")
|
||||
|
||||
assert not isinstance(exc_info.value, ConnectAuthError)
|
||||
assert str(exc_info.value) == (
|
||||
"REST API on 10.0.0.40 answered with a web page instead of JSON (HTTP 200)"
|
||||
)
|
||||
|
||||
|
||||
def test_a_refused_rest_login_is_still_an_authentication_failure():
|
||||
with pytest.raises(ConnectAuthError, match=r"REST API login failed \(HTTP 401\)"):
|
||||
_client_answering(401, "application/json")
|
||||
|
||||
|
||||
def test_the_transcript_keeps_the_greeting_not_the_whole_session():
|
||||
from napalm_procurve.connect_reasons import TelnetTranscript
|
||||
|
||||
transcript = TelnetTranscript()
|
||||
transcript.write(NO_FREE_SESSION)
|
||||
for _ in range(1000):
|
||||
transcript.write("show running-config output\r\n" * 10)
|
||||
|
||||
assert transcript.no_free_session
|
||||
assert len(transcript.text) < 10_000
|
||||
@@ -0,0 +1,98 @@
|
||||
"""get_snmp_config reads the switch's communities over every transport (#10).
|
||||
|
||||
Over the REST API there is no CLI session, so the getter returned None and a
|
||||
switch managed over REST always read as "SNMP not configured". The API's
|
||||
``/cli`` endpoint runs ``show snmp-server`` and answers with the output in
|
||||
base64, which the SSH path's parser reads.
|
||||
|
||||
The fixtures are ``show snmp-server`` recorded from a ProCurve switch: as the SSH
|
||||
CLI prints it, and as the REST ``/cli`` endpoint answers it (base64, ending in a
|
||||
NUL byte); the trap receiver's address is replaced.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
from napalm_procurve.procurve import ProcurveDriver
|
||||
|
||||
FIXTURES = Path(__file__).parent.parent / "fixtures"
|
||||
|
||||
SHOW_SNMP_SERVER = (FIXTURES / "procurve-show-snmp-server.txt").read_text(encoding="utf-8")
|
||||
SHOW_SNMP_SERVER_REST = (FIXTURES / "procurve-rest-cli-show-snmp-server.b64").read_text().strip()
|
||||
|
||||
_PUBLIC = " public Operator Restricted \n"
|
||||
assert SHOW_SNMP_SERVER.count(_PUBLIC) == 1
|
||||
#: The recording with a read-write community put in before the read-only one.
|
||||
TWO_COMMUNITIES = SHOW_SNMP_SERVER.replace(
|
||||
_PUBLIC, " private Manager Unrestricted\n" + _PUBLIC
|
||||
)
|
||||
|
||||
#: The recording with its only community removed.
|
||||
NO_COMMUNITY = SHOW_SNMP_SERVER.replace(_PUBLIC, "")
|
||||
|
||||
|
||||
def _b64(output: str) -> str:
|
||||
return base64.b64encode(output.encode()).decode()
|
||||
|
||||
|
||||
def _cli_answer(encoded: str, status: str = "CCS_SUCCESS", http: int = 200) -> MagicMock:
|
||||
resp = MagicMock(ok=200 <= http < 300, status_code=http, text="")
|
||||
resp.json.return_value = {
|
||||
"cmd": "show snmp-server",
|
||||
"result_base64_encoded": encoded,
|
||||
"status": status,
|
||||
}
|
||||
return resp
|
||||
|
||||
|
||||
def _rest_driver(resp: MagicMock) -> ProcurveDriver:
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
driver._api.post.return_value = resp
|
||||
return driver
|
||||
|
||||
|
||||
def test_over_rest_the_community_is_read_through_the_cli_endpoint():
|
||||
driver = _rest_driver(_cli_answer(SHOW_SNMP_SERVER_REST))
|
||||
|
||||
config = driver.get_snmp_config()
|
||||
|
||||
assert config == {"running": True, "community": "public", "port": 161, "version": "2c"}
|
||||
driver._api.post.assert_called_once_with("cli", json={"cmd": "show snmp-server"})
|
||||
|
||||
|
||||
def test_over_rest_a_switch_without_a_community_has_no_snmp_config():
|
||||
assert _rest_driver(_cli_answer(_b64(NO_COMMUNITY))).get_snmp_config() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"resp",
|
||||
[
|
||||
_cli_answer("", http=401),
|
||||
_cli_answer(_b64("Invalid input: snmp-server"), status="CCS_FAILURE"),
|
||||
],
|
||||
)
|
||||
def test_over_rest_a_failed_read_raises_instead_of_reading_as_no_snmp(resp):
|
||||
with pytest.raises(CommandErrorException, match="show snmp-server"):
|
||||
_rest_driver(resp).get_snmp_config()
|
||||
|
||||
|
||||
def test_over_ssh_the_read_only_community_is_preferred():
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "ssh"
|
||||
driver._device = MagicMock(base_prompt="swt")
|
||||
driver._device.send_command.return_value = TWO_COMMUNITIES
|
||||
|
||||
assert driver.get_snmp_config() == {
|
||||
"running": True,
|
||||
"community": "public",
|
||||
"port": 161,
|
||||
"version": "2c",
|
||||
}
|
||||
@@ -104,7 +104,7 @@ def test_the_config_fallback_checks_the_key_of_port_22():
|
||||
|
||||
def test_the_snmp_fix_over_rest_stops_at_a_changed_key():
|
||||
seen: list = []
|
||||
driver = _driver(seen, {"443": SshHostKey.of(OTHER_KEY).as_dict()}, port=443)
|
||||
driver = _driver(seen, {"22": SshHostKey.of(OTHER_KEY).as_dict()}, port=443)
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
with patch(HANDLER, side_effect=_refuse) as handler:
|
||||
@@ -112,3 +112,16 @@ def test_the_snmp_fix_over_rest_stops_at_a_changed_key():
|
||||
assert result["success"] is False
|
||||
assert handler.call_count == 1
|
||||
assert "host key" in str(result)
|
||||
|
||||
|
||||
def test_the_snmp_fix_over_rest_opens_ssh_on_port_22_not_the_api_port():
|
||||
"""``port`` is the REST API's port when REST is the transport (#17)."""
|
||||
seen: list = []
|
||||
driver = _driver(seen, {"22": SshHostKey.of(SERVER_KEY).as_dict()}, port=443)
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
with patch(HANDLER, return_value=_device()) as handler:
|
||||
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
assert handler.call_args.kwargs["port"] == 22
|
||||
assert handler.call_args.kwargs["ssh_strict"] is True
|
||||
assert (seen[0]["port"], seen[0]["accepted"]) == (22, True)
|
||||
Reference in new issue
Block a user