fix(vlans): set_vlan refuses a name with line breaks or double quotes (#28) #29
No files matched your search
@@ -42,6 +42,10 @@ 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
|
||||||
|
- `set_vlan()` refuses a name, `set_interface()` a description, with a line break or a
|
||||||
|
double quote (`ValueError`), over every transport, before anything is sent (#28,
|
||||||
|
NetOrk/netork#2455). Over SSH each went into `name "<value>"` in config mode: a line
|
||||||
|
break ended that line and the switch ran the rest as commands, then `write memory`.
|
||||||
- The REST API's certificate is verified. A switch's self-signed certificate is checked
|
- 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:
|
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
|
`optional_args["tls_fingerprints"]` (`{"443": "SHA256:AB:CD:…"}`) holds the fingerprint
|
||||||
|
|||||||
@@ -911,3 +911,49 @@ 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."""
|
"""The output in a REST ``/cli`` answer: base64, the switch ends it with a NUL byte."""
|
||||||
encoded = answer.get("result_base64_encoded", "")
|
encoded = answer.get("result_base64_encoded", "")
|
||||||
return base64.b64decode(encoded).decode("utf-8", "replace").rstrip("\x00")
|
return base64.b64decode(encoded).decode("utf-8", "replace").rstrip("\x00")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# ping
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _ping_result(sent: int, received: int, rtt: tuple[float, float, float]) -> dict:
|
||||||
|
"""NAPALM's ping ``success`` dict; *rtt* is (min, avg, max)."""
|
||||||
|
rtt_min, rtt_avg, rtt_max = rtt
|
||||||
|
return {
|
||||||
|
"success": {
|
||||||
|
"probes_sent": sent,
|
||||||
|
"packet_loss": sent - received,
|
||||||
|
"rtt_min": rtt_min,
|
||||||
|
"rtt_max": rtt_max,
|
||||||
|
"rtt_avg": rtt_avg,
|
||||||
|
"rtt_stddev": 0.0,
|
||||||
|
"results": [{"ip_address": "", "rtt": rtt_avg}] * received,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_ping_output(output: str, count: int) -> dict:
|
||||||
|
"""Parse ProCurve CLI ping output into NAPALM ping result dict.
|
||||||
|
|
||||||
|
ProCurve ping output::
|
||||||
|
|
||||||
|
PING 10.0.0.1: 100 data bytes
|
||||||
|
!!!!
|
||||||
|
----10.0.0.1 PING Statistics----
|
||||||
|
5 packets transmitted, 5 packets received, 0% packet loss
|
||||||
|
round-trip (ms) min/avg/max = 0/0/1
|
||||||
|
"""
|
||||||
|
m = re.search(r"(\d+)\s+packets\s+transmitted,\s+(\d+)\s+packets\s+received", output, re.I)
|
||||||
|
if not m:
|
||||||
|
if "unreachable" in output.lower() or "no route" in output.lower():
|
||||||
|
return _ping_result(count, 0, (0.0, 0.0, 0.0))
|
||||||
|
return {"error": "Could not parse ping output"}
|
||||||
|
|
||||||
|
# RTT line: "round-trip (ms) min/avg/max = 0/0/1"
|
||||||
|
rtt_m = re.search(r"min/avg/max\s*=\s*([\d.]+)/([\d.]+)/([\d.]+)", output, re.I)
|
||||||
|
rtt = (0.0, 0.0, 0.0)
|
||||||
|
if rtt_m:
|
||||||
|
rtt = (float(rtt_m.group(1)), float(rtt_m.group(2)), float(rtt_m.group(3)))
|
||||||
|
return _ping_result(int(m.group(1)), int(m.group(2)), rtt)
|
||||||
+23
-68
@@ -85,6 +85,15 @@ _SSH_PORT_BESIDE_API = 22 # SSH beside the REST API: ``port`` then is the API's
|
|||||||
#: What may stand in a quoted CLI value: no whitespace, quote or #.
|
#: What may stand in a quoted CLI value: no whitespace, quote or #.
|
||||||
_CLI_WORD = re.compile(r'^[^\s"#]+$')
|
_CLI_WORD = re.compile(r'^[^\s"#]+$')
|
||||||
|
|
||||||
|
#: What ends a quoted CLI value early: a line break ends its line, a double quote the value.
|
||||||
|
_BREAKS_CLI_VALUE = re.compile(r'[\r\n"]')
|
||||||
|
|
||||||
|
|
||||||
|
def _check_cli_value(what: str, value: str | None) -> None:
|
||||||
|
"""Refuse a value that would break out of its ``name "..."`` line (NetOrk/netork#2455)."""
|
||||||
|
if value is not None and _BREAKS_CLI_VALUE.search(value):
|
||||||
|
raise ValueError(f"{what} {value!r} must be one line without double quotes")
|
||||||
|
|
||||||
|
|
||||||
class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver):
|
class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver):
|
||||||
"""NAPALM driver for HPE/Aruba ProCurve switches.
|
"""NAPALM driver for HPE/Aruba ProCurve switches.
|
||||||
@@ -820,7 +829,13 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver):
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def set_vlan(self, vlan_id: int, config: VlanConfigDict) -> None:
|
def set_vlan(self, vlan_id: int, config: VlanConfigDict) -> None:
|
||||||
"""Create or update a VLAN on the switch."""
|
"""Create or update a VLAN on the switch.
|
||||||
|
|
||||||
|
A name with a line break or a double quote is refused before anything is
|
||||||
|
sent, over every transport: over SSH it ended its ``name "..."`` line and
|
||||||
|
the switch ran the rest as commands.
|
||||||
|
"""
|
||||||
|
_check_cli_value("VLAN name", config.get("name"))
|
||||||
if self._transport == "api":
|
if self._transport == "api":
|
||||||
self._api_set_vlan(vlan_id, config)
|
self._api_set_vlan(vlan_id, config)
|
||||||
else:
|
else:
|
||||||
@@ -911,7 +926,12 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver):
|
|||||||
self._save_config()
|
self._save_config()
|
||||||
|
|
||||||
def set_interface(self, interface: str, config: InterfaceConfigDict) -> None:
|
def set_interface(self, interface: str, config: InterfaceConfigDict) -> None:
|
||||||
"""Configure a switch interface (mode, VLAN membership)."""
|
"""Configure a switch interface (mode, VLAN membership).
|
||||||
|
|
||||||
|
A description with a line break or a double quote is refused before anything
|
||||||
|
is sent, over every transport: over SSH it ended its ``name "..."`` line.
|
||||||
|
"""
|
||||||
|
_check_cli_value("description", config.get("description"))
|
||||||
if self._transport == "api":
|
if self._transport == "api":
|
||||||
self._api_set_interface(interface, config)
|
self._api_set_interface(interface, config)
|
||||||
else:
|
else:
|
||||||
@@ -1088,7 +1108,7 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver):
|
|||||||
if source:
|
if source:
|
||||||
cmd += f" source {source}"
|
cmd += f" source {source}"
|
||||||
out = self._send_command(cmd)
|
out = self._send_command(cmd)
|
||||||
return _parse_ping_output(out, count)
|
return parsers.parse_ping_output(out, count)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# NAPALM: cli
|
# NAPALM: cli
|
||||||
@@ -1278,68 +1298,3 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver):
|
|||||||
if re.search(rf"^\s*{re.escape(settings['community'])}\s", shown, re.M):
|
if re.search(rf"^\s*{re.escape(settings['community'])}\s", shown, re.M):
|
||||||
return {"ok": True, "output": "configuration saved; the community is active"}
|
return {"ok": True, "output": "configuration saved; the community is active"}
|
||||||
return {"ok": False, "output": f"saved, but the community is not shown: {shown[:200]}"}
|
return {"ok": False, "output": f"saved, but the community is not shown: {shown[:200]}"}
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Helpers
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_ping_output(output: str, count: int) -> dict:
|
|
||||||
"""Parse ProCurve CLI ping output into NAPALM ping result dict.
|
|
||||||
|
|
||||||
ProCurve ping output::
|
|
||||||
|
|
||||||
PING 10.0.0.1: 100 data bytes
|
|
||||||
!!!!
|
|
||||||
----10.0.0.1 PING Statistics----
|
|
||||||
5 packets transmitted, 5 packets received, 0% packet loss
|
|
||||||
round-trip (ms) min/avg/max = 0/0/1
|
|
||||||
"""
|
|
||||||
# Packet statistics line
|
|
||||||
m = re.search(
|
|
||||||
r"(\d+)\s+packets\s+transmitted,\s+(\d+)\s+packets\s+received",
|
|
||||||
output,
|
|
||||||
re.I,
|
|
||||||
)
|
|
||||||
if not m:
|
|
||||||
# Check for total failure
|
|
||||||
if "unreachable" in output.lower() or "no route" in output.lower():
|
|
||||||
return {
|
|
||||||
"success": {
|
|
||||||
"probes_sent": count,
|
|
||||||
"packet_loss": count,
|
|
||||||
"rtt_min": 0.0,
|
|
||||||
"rtt_max": 0.0,
|
|
||||||
"rtt_avg": 0.0,
|
|
||||||
"rtt_stddev": 0.0,
|
|
||||||
"results": [],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {"error": "Could not parse ping output"}
|
|
||||||
|
|
||||||
sent = int(m.group(1))
|
|
||||||
received = int(m.group(2))
|
|
||||||
loss = sent - received
|
|
||||||
|
|
||||||
# RTT line: "round-trip (ms) min/avg/max = 0/0/1"
|
|
||||||
rtt_min = rtt_avg = rtt_max = 0.0
|
|
||||||
rtt_m = re.search(r"min/avg/max\s*=\s*([\d.]+)/([\d.]+)/([\d.]+)", output, re.I)
|
|
||||||
if rtt_m:
|
|
||||||
rtt_min = float(rtt_m.group(1))
|
|
||||||
rtt_avg = float(rtt_m.group(2))
|
|
||||||
rtt_max = float(rtt_m.group(3))
|
|
||||||
|
|
||||||
results = [{"ip_address": "", "rtt": rtt_avg}] * received
|
|
||||||
|
|
||||||
return {
|
|
||||||
"success": {
|
|
||||||
"probes_sent": sent,
|
|
||||||
"packet_loss": loss,
|
|
||||||
"rtt_min": rtt_min,
|
|
||||||
"rtt_max": rtt_max,
|
|
||||||
"rtt_avg": rtt_avg,
|
|
||||||
"rtt_stddev": 0.0,
|
|
||||||
"results": results,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,8 +18,7 @@
|
|||||||
"napalm_procurve/parsers.py::parse_ip_interfaces": 58,
|
"napalm_procurve/parsers.py::parse_ip_interfaces": 58,
|
||||||
"napalm_procurve/parsers.py::parse_lldp_neighbors_detail": 59,
|
"napalm_procurve/parsers.py::parse_lldp_neighbors_detail": 59,
|
||||||
"napalm_procurve/parsers.py::parse_system_info": 80,
|
"napalm_procurve/parsers.py::parse_system_info": 80,
|
||||||
"napalm_procurve/parsers.py::parse_vlans_from_running_config": 79,
|
"napalm_procurve/parsers.py::parse_vlans_from_running_config": 79
|
||||||
"napalm_procurve/procurve.py::_parse_ping_output": 58
|
|
||||||
},
|
},
|
||||||
"mypy_relaxed": [
|
"mypy_relaxed": [
|
||||||
"napalm_procurve.api_client",
|
"napalm_procurve.api_client",
|
||||||
@@ -27,7 +26,7 @@
|
|||||||
"napalm_procurve.procurve"
|
"napalm_procurve.procurve"
|
||||||
],
|
],
|
||||||
"python_file_lines": {
|
"python_file_lines": {
|
||||||
"napalm_procurve/procurve.py": 1345
|
"napalm_procurve/procurve.py": 1300
|
||||||
},
|
},
|
||||||
"untyped_public": []
|
"untyped_public": []
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""set_vlan and set_interface refuse values that would break out of their CLI line
|
||||||
|
(#28, NetOrk/netork#2455).
|
||||||
|
|
||||||
|
Over SSH the name goes into ``name "<name>"`` in config mode, one line of a
|
||||||
|
block sent line by line. A line break in the name ended that line and sent
|
||||||
|
the rest to the switch as commands of its own; a double quote ended the name.
|
||||||
|
A name with ``\\r``, ``\\n`` or ``"`` is refused before anything is sent, over
|
||||||
|
REST as well, so both transports take the same names.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from napalm_procurve.procurve import ProcurveDriver
|
||||||
|
|
||||||
|
#: The name from the security report: a quote ends the name, a line break the line.
|
||||||
|
INJECTED = 'guest"\npassword manager user-name x plaintext y\nexit\nvlan 42\n name "guest'
|
||||||
|
|
||||||
|
|
||||||
|
def _driver(transport: str) -> ProcurveDriver:
|
||||||
|
d = ProcurveDriver("10.0.0.40", "admin", "pw")
|
||||||
|
d._transport = transport
|
||||||
|
d._api = MagicMock()
|
||||||
|
d._device = MagicMock()
|
||||||
|
d.applied: list[str] = []
|
||||||
|
d._enter_config_mode = MagicMock()
|
||||||
|
d._exit_config_mode = MagicMock()
|
||||||
|
d._save_config = MagicMock()
|
||||||
|
d._apply_config_lines = lambda text: d.applied.append(text) or []
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("transport", ["ssh", "api"])
|
||||||
|
@pytest.mark.parametrize("name", [INJECTED, "a\nb", "a\rb", 'say "hi"'])
|
||||||
|
def test_a_name_with_a_line_break_or_a_double_quote_is_refused(transport, name):
|
||||||
|
driver = _driver(transport)
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="VLAN name"):
|
||||||
|
driver.set_vlan(42, {"name": name})
|
||||||
|
|
||||||
|
assert driver.applied == []
|
||||||
|
driver._enter_config_mode.assert_not_called()
|
||||||
|
driver._api.post.assert_not_called()
|
||||||
|
driver._save_config.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_plain_name_is_sent_quoted():
|
||||||
|
driver = _driver("ssh")
|
||||||
|
|
||||||
|
driver.set_vlan(42, {"name": "guest wifi"})
|
||||||
|
|
||||||
|
assert driver.applied == ['vlan 42\n name "guest wifi"\nexit']
|
||||||
|
driver._save_config.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_vlan_without_a_name_is_sent_without_one():
|
||||||
|
driver = _driver("ssh")
|
||||||
|
|
||||||
|
driver.set_vlan(42, {})
|
||||||
|
|
||||||
|
assert driver.applied == ["vlan 42\nexit"]
|
||||||
|
|
||||||
|
|
||||||
|
# ── a port's description: set_interface (#28) ───────────────────────────────
|
||||||
|
#
|
||||||
|
# Over SSH the description goes into `` name "<desc>"`` under ``interface <port>``,
|
||||||
|
# one line of the same kind of block: a line break ran the rest as commands, a double
|
||||||
|
# quote ended the value. Refused the same way, over every transport.
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("transport", ["ssh", "api"])
|
||||||
|
@pytest.mark.parametrize("description", ["uplink\nexit\nno password manager", "a\rb", 'to "core"'])
|
||||||
|
def test_a_description_with_a_line_break_or_a_double_quote_is_refused(transport, description):
|
||||||
|
driver = _driver(transport)
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="description"):
|
||||||
|
driver.set_interface("4", {"description": description})
|
||||||
|
|
||||||
|
assert driver.applied == []
|
||||||
|
driver._enter_config_mode.assert_not_called()
|
||||||
|
driver._api.post.assert_not_called()
|
||||||
|
driver._api.put.assert_not_called()
|
||||||
|
driver._api.patch.assert_not_called()
|
||||||
|
driver._save_config.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_one_line_description_is_sent_quoted():
|
||||||
|
driver = _driver("ssh")
|
||||||
|
|
||||||
|
driver.set_interface("4", {"description": "to core-sw"})
|
||||||
|
|
||||||
|
assert driver.applied == ['interface 4\n name "to core-sw"\nexit']
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_empty_description_clears_the_name():
|
||||||
|
driver = _driver("ssh")
|
||||||
|
|
||||||
|
driver.set_interface("4", {"description": ""})
|
||||||
|
|
||||||
|
assert driver.applied == ["interface 4\n no name\nexit"]
|
||||||
@@ -6,7 +6,7 @@ import pytest
|
|||||||
from napalm.base.exceptions import ConnectionException
|
from napalm.base.exceptions import ConnectionException
|
||||||
|
|
||||||
from napalm_procurve import parsers
|
from napalm_procurve import parsers
|
||||||
from napalm_procurve.procurve import _SSH_DISABLED_STANDARD, ProcurveDriver, _parse_ping_output
|
from napalm_procurve.procurve import _SSH_DISABLED_STANDARD, ProcurveDriver
|
||||||
|
|
||||||
# ===========================================================================
|
# ===========================================================================
|
||||||
# Sample CLI output fixtures (captured from real ProCurve devices)
|
# Sample CLI output fixtures (captured from real ProCurve devices)
|
||||||
@@ -362,16 +362,27 @@ class TestParseIpInterfaces:
|
|||||||
|
|
||||||
class TestParsePingOutput:
|
class TestParsePingOutput:
|
||||||
def test_success(self):
|
def test_success(self):
|
||||||
result = _parse_ping_output(PING_OUTPUT_SUCCESS, 5)
|
result = parsers.parse_ping_output(PING_OUTPUT_SUCCESS, 5)
|
||||||
assert result["success"]["probes_sent"] == 5
|
assert result["success"]["probes_sent"] == 5
|
||||||
assert result["success"]["packet_loss"] == 0
|
assert result["success"]["packet_loss"] == 0
|
||||||
assert result["success"]["rtt_avg"] == 1.0
|
assert result["success"]["rtt_avg"] == 1.0
|
||||||
|
|
||||||
def test_failure(self):
|
def test_failure(self):
|
||||||
result = _parse_ping_output(PING_OUTPUT_FAILURE, 5)
|
result = parsers.parse_ping_output(PING_OUTPUT_FAILURE, 5)
|
||||||
assert result["success"]["probes_sent"] == 5
|
assert result["success"]["probes_sent"] == 5
|
||||||
assert result["success"]["packet_loss"] == 5
|
assert result["success"]["packet_loss"] == 5
|
||||||
|
|
||||||
|
def test_unreachable_counts_every_probe_lost(self):
|
||||||
|
result = parsers.parse_ping_output("Request timed out: host unreachable", 3)
|
||||||
|
assert result["success"]["probes_sent"] == 3
|
||||||
|
assert result["success"]["packet_loss"] == 3
|
||||||
|
assert result["success"]["results"] == []
|
||||||
|
|
||||||
|
def test_unknown_output_is_an_error(self):
|
||||||
|
assert parsers.parse_ping_output("Invalid input: pong", 3) == {
|
||||||
|
"error": "Could not parse ping output"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
# ===========================================================================
|
# ===========================================================================
|
||||||
# Driver integration tests (mocked netmiko)
|
# Driver integration tests (mocked netmiko)
|
||||||
|
|||||||
Reference in new issue
Block a user