From c4cd0bbdf3e26d0b51c71ac42b1f111d078b2c2b Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 12 Nov 2026 22:25:56 +0100 Subject: [PATCH 1/3] fix(vlans): set_vlan refuses a name with line breaks or double quotes (#28) Over SSH the name went into `name ""` in config mode, one line of a block sent line by line before `write memory`: a line break ended the line and the switch ran the rest as commands, a double quote ended the name. netOrk replays VLAN names other devices reported here (NetOrk/netork#2455). set_vlan() now raises ValueError for a name containing \r, \n or ", before anything is sent, over every transport. --- CHANGELOG.md | 4 +++ napalm_procurve/procurve.py | 17 +++++++++- tests/unit/test_vlan_name.py | 63 ++++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 tests/unit/test_vlan_name.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 49a15da..b6d975b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,10 @@ All notable changes to this driver. The format follows a session log object, which older releases do not accept. ### Fixed +- `set_vlan()` refuses a name with a line break or a double quote (`ValueError`), over + every transport, before anything is sent (#28, NetOrk/netork#2455). Over SSH the name went + into `name ""` 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 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 diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 7c09dec..13f69ae 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -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 #. _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_vlan_name(name: str | None) -> None: + """Refuse a VLAN name that would break out of its ``name "..."`` line (NetOrk/netork#2455).""" + if name is not None and _BREAKS_CLI_VALUE.search(name): + raise ValueError(f"VLAN name {name!r} must be one line without double quotes") + class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver): """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: - """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_vlan_name(config.get("name")) if self._transport == "api": self._api_set_vlan(vlan_id, config) else: diff --git a/tests/unit/test_vlan_name.py b/tests/unit/test_vlan_name.py new file mode 100644 index 0000000..70807ff --- /dev/null +++ b/tests/unit/test_vlan_name.py @@ -0,0 +1,63 @@ +"""set_vlan refuses a name that would break out of its CLI line (NetOrk/netork#2455). + +Over SSH the name goes into ``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"] -- 2.54.1 From e06811de50228f678f724ac1f8a770cdd23a3e12 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 12 Nov 2026 23:01:38 +0100 Subject: [PATCH 2/3] fix(interfaces): set_interface refuses a description with line breaks or double quotes (#28) Over SSH the description went into ` name ""` under `interface `, one line of a block sent line by line before `write memory`: a line break ran the rest as commands, a double quote ended the value. It is the same injection as set_vlan's name (NetOrk/netork#2455). set_interface() now raises ValueError for a description containing \r, \n or ", before anything is sent, over every transport, through the same check as set_vlan (_check_cli_value). The tests move to test_cli_values.py, which covers both. --- CHANGELOG.md | 8 ++-- napalm_procurve/procurve.py | 17 +++++--- .../{test_vlan_name.py => test_cli_values.py} | 42 ++++++++++++++++++- 3 files changed, 56 insertions(+), 11 deletions(-) rename tests/unit/{test_vlan_name.py => test_cli_values.py} (56%) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6d975b..a5d1666 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,10 +42,10 @@ All notable changes to this driver. The format follows a session log object, which older releases do not accept. ### Fixed -- `set_vlan()` refuses a name with a line break or a double quote (`ValueError`), over - every transport, before anything is sent (#28, NetOrk/netork#2455). Over SSH the name went - into `name ""` in config mode: a line break ended that line and the switch ran the - rest as commands, then `write memory`. +- `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 ""` 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 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 diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 13f69ae..11a4c03 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -89,10 +89,10 @@ _CLI_WORD = re.compile(r'^[^\s"#]+$') _BREAKS_CLI_VALUE = re.compile(r'[\r\n"]') -def _check_vlan_name(name: str | None) -> None: - """Refuse a VLAN name that would break out of its ``name "..."`` line (NetOrk/netork#2455).""" - if name is not None and _BREAKS_CLI_VALUE.search(name): - raise ValueError(f"VLAN name {name!r} must be one line without double quotes") +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): @@ -835,7 +835,7 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver): sent, over every transport: over SSH it ended its ``name "..."`` line and the switch ran the rest as commands. """ - _check_vlan_name(config.get("name")) + _check_cli_value("VLAN name", config.get("name")) if self._transport == "api": self._api_set_vlan(vlan_id, config) else: @@ -926,7 +926,12 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver): self._save_config() 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": self._api_set_interface(interface, config) else: diff --git a/tests/unit/test_vlan_name.py b/tests/unit/test_cli_values.py similarity index 56% rename from tests/unit/test_vlan_name.py rename to tests/unit/test_cli_values.py index 70807ff..e954fb8 100644 --- a/tests/unit/test_vlan_name.py +++ b/tests/unit/test_cli_values.py @@ -1,4 +1,5 @@ -"""set_vlan refuses a name that would break out of its CLI line (NetOrk/netork#2455). +"""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 ""`` in config mode, one line of a block sent line by line. A line break in the name ended that line and sent @@ -61,3 +62,42 @@ def test_a_vlan_without_a_name_is_sent_without_one(): driver.set_vlan(42, {}) assert driver.applied == ["vlan 42\nexit"] + + +# ── a port's description: set_interface (#28) ─────────────────────────────── +# +# Over SSH the description goes into `` name ""`` under ``interface ``, +# 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"] -- 2.54.1 From 23e799ee8d62c55d471a0794620bf0c5c658b458 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Fri, 13 Nov 2026 08:57:42 +0100 Subject: [PATCH 3/3] refactor(ping): the ping output parser lives with the other CLI parsers (#28) The checks against line breaks and double quotes made procurve.py 20 lines longer than the quality ratchet allows (1365, recorded 1345). The module-level ping parser moves to parsers.py, which holds every other pure CLI parser, as parse_ping_output; its two result dicts become one helper, so it is no longer over 50 lines. Behaviour is unchanged; tests for an unreachable target and an unknown answer are added. The baseline is lowered to what is measured now (procurve.py 1300, the ping entry gone). --- napalm_procurve/parsers.py | 46 +++++++++++++++++++++++++ napalm_procurve/procurve.py | 67 +------------------------------------ tests/quality_baseline.json | 5 ++- tests/unit/test_driver.py | 17 ++++++++-- 4 files changed, 63 insertions(+), 72 deletions(-) diff --git a/napalm_procurve/parsers.py b/napalm_procurve/parsers.py index dd5110b..cb69144 100644 --- a/napalm_procurve/parsers.py +++ b/napalm_procurve/parsers.py @@ -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.""" encoded = answer.get("result_base64_encoded", "") 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) diff --git a/napalm_procurve/procurve.py b/napalm_procurve/procurve.py index 11a4c03..0610359 100644 --- a/napalm_procurve/procurve.py +++ b/napalm_procurve/procurve.py @@ -1108,7 +1108,7 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver): if source: cmd += f" source {source}" out = self._send_command(cmd) - return _parse_ping_output(out, count) + return parsers.parse_ping_output(out, count) # ------------------------------------------------------------------ # NAPALM: cli @@ -1298,68 +1298,3 @@ class ProcurveDriver(ProcurveTimeSyncMixin, ConfigLifecycleMixin, SwitchDriver): 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": 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, - } - } diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 7f82314..33d8550 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -18,8 +18,7 @@ "napalm_procurve/parsers.py::parse_ip_interfaces": 58, "napalm_procurve/parsers.py::parse_lldp_neighbors_detail": 59, "napalm_procurve/parsers.py::parse_system_info": 80, - "napalm_procurve/parsers.py::parse_vlans_from_running_config": 79, - "napalm_procurve/procurve.py::_parse_ping_output": 58 + "napalm_procurve/parsers.py::parse_vlans_from_running_config": 79 }, "mypy_relaxed": [ "napalm_procurve.api_client", @@ -27,7 +26,7 @@ "napalm_procurve.procurve" ], "python_file_lines": { - "napalm_procurve/procurve.py": 1345 + "napalm_procurve/procurve.py": 1300 }, "untyped_public": [] } diff --git a/tests/unit/test_driver.py b/tests/unit/test_driver.py index 974054c..fb61f5c 100644 --- a/tests/unit/test_driver.py +++ b/tests/unit/test_driver.py @@ -6,7 +6,7 @@ import pytest from napalm.base.exceptions import ConnectionException 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) @@ -362,16 +362,27 @@ class TestParseIpInterfaces: class TestParsePingOutput: 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"]["packet_loss"] == 0 assert result["success"]["rtt_avg"] == 1.0 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"]["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) -- 2.54.1