"""set_hostname quotes the name for the shell (NetOrk/netork#2456). The name went into ``uci set system.@system[0].hostname=''`` between single quotes of its own, so a name with a single quote ended them: ``x';reboot;'`` ran ``reboot`` as root. The name now reaches ``uci`` as one word, whatever it holds. """ from __future__ import annotations import shlex from unittest.mock import MagicMock, patch import pytest from napalm_openwrt.openwrt import OpenWrtDriver @pytest.fixture def driver(): with patch("napalm_openwrt.openwrt.ConnectHandler"): drv = OpenWrtDriver(hostname="192.0.2.1", username="root", password="") drv._send_command = MagicMock(return_value="") return drv def _uci_set(command: str) -> list[str]: """The words of the ``uci set`` the command runs, as the shell splits them.""" first = command.split(" && ")[0] return shlex.split(first) @pytest.mark.parametrize("name", ["ap-garden", "x';reboot;'", "a b", "$(reboot)", "`reboot`"]) def test_the_name_reaches_uci_as_one_word(driver, name): driver.set_hostname(name) [command] = [call.args[0] for call in driver._send_command.call_args_list] assert _uci_set(command) == ["uci", "set", f"system.@system[0].hostname={name}"] assert command.endswith(" && uci commit system && /etc/init.d/system reload") def test_a_quote_in_the_name_runs_nothing(driver): driver.set_hostname("x';reboot;'") [command] = [call.args[0] for call in driver._send_command.call_args_list] # Split as the shell does, the commands are uci's and the reload, nothing else. lexer = shlex.shlex(command, posix=True, punctuation_chars=True) words = list(lexer) assert "reboot" not in words assert words.count(";") == 0