Merge pull request 'fix(system): set_hostname quotes the name in its root commands (#64)' (#65) from fix/hostname-quote-2456 into main
driver / standard (push) Successful in 15s
driver / lint (push) Successful in 12s
driver / types (push) Successful in 55s
driver / test (3.12) (push) Successful in 1m0s
driver / test (3.13) (push) Successful in 52s
driver / lowest (push) Successful in 30s
driver / build (push) Successful in 29s
driver / security (push) Successful in 1m1s
CI / driver (push) Successful in 2m28s
driver / publish (push) Skipped

This commit was merged in pull request #65.
This commit is contained in:
christianmanivong committed 2026-11-13 08:55:13 +00:00
commit 6fccd7a8f0
7 files changed
+119 -27

No files matched your search

+12 -7
View File
@@ -9,13 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
- Time sync on both drivers (NetOrk/netork#2365), through napalm-device-types' - Time sync on both drivers (NetOrk/netork#2365), through napalm-device-types'
`TimeSyncMixin` (4.35.0); both write the servers and the zone. Neither API keeps time `TimeSyncMixin` (4.36.0); both write the servers and the zone. Neither API keeps time
servers -- both products run chrony on Debian -- so `get_time_sync()` reads chrony's servers -- both products run chrony on Debian -- so `get_time_sync()` reads chrony's
sources, whether it is synchronised and the zone (`timedatectl`) in one round trip over sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised and
the driver's SSH session (`PosixTimeSyncMixin`), and the zone from `GET the zone (`timedatectl`) in one round trip over the driver's SSH session
/nodes/{node}/time` only where the host names none. `configure_time_sync()` writes the (`PosixTimeSyncMixin`), and the zone from `GET /nodes/{node}/time` only where the host
servers to `/etc/chrony/sources.d/netork.sources` with every other source commented out names none. `configure_time_sync()` writes the servers to
(Debian's vendor pool, the DHCP `sourcedir`) and reloads or restarts chrony; the zone `/etc/chrony/sources.d/netork.sources` with every other configured source commented out
(Debian's vendor pool; the DHCP `sourcedir` stays) and reloads or restarts chrony; the zone
goes through `PUT /nodes/{node}/time`, Proxmox's own call, so `/etc/timezone` and the goes through `PUT /nodes/{node}/time`, Proxmox's own call, so `/etc/timezone` and the
web UI follow `/etc/localtime`. The token needs `Sys.Modify` for it (PVE on web UI follow `/etc/localtime`. The token needs `Sys.Modify` for it (PVE on
`/nodes/{node}`, PBS on `/system/time`). Only the node of the connection is read and `/nodes/{node}`, PBS on `/system/time`). Only the node of the connection is read and
@@ -45,9 +46,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them. in its own daemons; `get_clusters()` and `get_backup_jobs()` keep them.
### Changed ### Changed
- Requires napalm-device-types 4.35.0. - Requires napalm-device-types 4.36.0.
### Fixed ### Fixed
- `set_hostname()` hands the name to the shell quoted (`shlex.quote`): to `hostname`, to
`postconf -e` and in the paths of the `/etc/pve/nodes` move (#64, NetOrk/netork#2456). They
stood between single quotes of their own, so a name with a single quote ended them and
the rest ran as root (`x';reboot;'`).
- `get_ntp_servers()` read `GET /nodes/{node}/ntp`, a path Proxmox VE does not have, and so - `get_ntp_servers()` read `GET /nodes/{node}/ntp`, a path Proxmox VE does not have, and so
always reported no servers. It now reports chrony's configured sources, the ones always reported no servers. It now reports chrony's configured sources, the ones
`get_time_sync()` reads, and the backup server has it too. `get_time_sync()` reads, and the backup server has it too.
+2 -2
View File
@@ -129,8 +129,8 @@ device = driver(
| `get_scheduled_jobs` | cron, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers, as root over SSH (napalm-device-types' `PosixScheduledJobsMixin`); `pve-*` units, `pvesr.timer` and `/etc/cron.d/vzdump` are `platform` | | `get_scheduled_jobs` | cron, `/etc/cron.d`, user crontabs, run-parts, anacron, systemd timers, as root over SSH (napalm-device-types' `PosixScheduledJobsMixin`); `pve-*` units, `pvesr.timer` and `/etc/cron.d/vzdump` are `platform` |
| `manage_scheduled_job(key, action, digest=)` | enable, disable, run now; a `/etc/cron.d/vzdump` line only runs | | `manage_scheduled_job(key, action, digest=)` | enable, disable, run now; a `/etc/cron.d/vzdump` line only runs |
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer | | `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | an application's own job, as a systemd timer |
| `get_time_sync` | chrony's sources and whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none | | `get_time_sync` | chrony's sources, the ones DHCP gave apart (`dhcp_ntp_servers`), whether it is synchronised, the zone from `timedatectl`, in one round trip over SSH (napalm-device-types' `PosixTimeSyncMixin`); the zone from `GET /nodes/{node}/time` only where the host names none |
| `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other source commented out, then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock | | `configure_time_sync(ntp_servers=, timezone=)` | servers to `/etc/chrony/sources.d/netork.sources`, every other configured source commented out (DHCP's `sourcedir` stays), then a reload or a restart of chrony; the zone through `PUT /nodes/{node}/time` (the token needs `Sys.Modify` on `/nodes/{node}`), so `/etc/timezone` and the web UI follow. Only this node: in a cluster each node keeps its own clock |
**Not implemented** (raise `NotImplementedError`): **Not implemented** (raise `NotImplementedError`):
`get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`, `get_bgp_config`, `get_bgp_neighbors`, `get_bgp_neighbors_detail`,
+10 -9
View File
@@ -23,6 +23,7 @@ from __future__ import annotations
import ipaddress import ipaddress
import logging import logging
import re import re
import shlex
from typing import Any from typing import Any
from napalm.base.exceptions import CommandErrorException from napalm.base.exceptions import CommandErrorException
@@ -453,12 +454,13 @@ class ProxmoxSystemMixin:
) )
# ── 4. Postfix myhostname ───────────────────────────────────────── # ── 4. Postfix myhostname ─────────────────────────────────────────
postfix = shlex.quote(f"myhostname = {fqdn}")
self._exec_ssh_command( self._exec_ssh_command(
f"command -v postconf >/dev/null 2>&1 && postconf -e 'myhostname = {fqdn}' || true" f"command -v postconf >/dev/null 2>&1 && postconf -e {postfix} || true"
) )
# ── 5. Apply hostname at runtime ───────────────────────────────── # ── 5. Apply hostname at runtime ─────────────────────────────────
self._exec_ssh_command(f"hostname '{short_hostname}'") self._exec_ssh_command(f"hostname {shlex.quote(short_hostname)}")
# ── 6. Migrate /etc/pve/nodes/<old> → /etc/pve/nodes/<new> ────── # ── 6. Migrate /etc/pve/nodes/<old> → /etc/pve/nodes/<new> ──────
# Proxmox stores VM and CT configs under /etc/pve/nodes/<nodename>/. # Proxmox stores VM and CT configs under /etc/pve/nodes/<nodename>/.
@@ -467,16 +469,15 @@ class ProxmoxSystemMixin:
# Without this step the node boots under the new hostname, finds an # Without this step the node boots under the new hostname, finds an
# empty /etc/pve/nodes/<new>/ and all VMs appear missing. # empty /etc/pve/nodes/<new>/ and all VMs appear missing.
if old_short and old_short != short_hostname: if old_short and old_short != short_hostname:
pve_old = f"/etc/pve/nodes/{old_short}" pve_old = shlex.quote(f"/etc/pve/nodes/{old_short}")
pve_new = f"/etc/pve/nodes/{short_hostname}" pve_new = shlex.quote(f"/etc/pve/nodes/{short_hostname}")
migrate_out = self._exec_ssh_command( migrate_out = self._exec_ssh_command(
f"if [ -d '{pve_old}' ] && [ ! -e '{pve_new}' ]; then" f"if [ -d {pve_old} ] && [ ! -e {pve_new} ]; then"
f" mv '{pve_old}' '{pve_new}'" f" mv {pve_old} {pve_new} && echo migrated {pve_old} '->' {pve_new};"
f" && echo 'migrated {pve_old} -> {pve_new}';" f"elif [ -d {pve_new} ]; then"
f"elif [ -d '{pve_new}' ]; then"
f" echo 'target already exists, skipping migration';" f" echo 'target already exists, skipping migration';"
f"else" f"else"
f" echo 'source {pve_old} not found, skipping migration';" f" echo source {pve_old} 'not found, skipping migration';"
f"fi" f"fi"
) )
logger.info("Proxmox node dir migration: %s", migrate_out) logger.info("Proxmox node dir migration: %s", migrate_out)
+3 -2
View File
@@ -3,8 +3,9 @@
Neither API keeps time servers: ``/nodes/{node}/time`` knows only the zone, and Neither API keeps time servers: ``/nodes/{node}/time`` knows only the zone, and
both products run chrony on Debian. So the servers are both products run chrony on Debian. So the servers are
:class:`~napalm_device_types.PosixTimeSyncMixin`'s, over the driver's SSH session :class:`~napalm_device_types.PosixTimeSyncMixin`'s, over the driver's SSH session
(``run_command``, root): read from chrony's configuration, written to (``run_command``, root): read from chrony's configuration, DHCP's apart, written to
``/etc/chrony/sources.d/netork.sources`` with every other source commented out. ``/etc/chrony/sources.d/netork.sources`` with every other configured source commented
out; the DHCP client's ``sourcedir`` stays.
The zone is read with them, from the host (``timedatectl``, the zone the node's The zone is read with them, from the host (``timedatectl``, the zone the node's
clock really runs in), and the API's ``GET /nodes/{node}/time`` answers only when clock really runs in), and the API's ``GET /nodes/{node}/time`` answers only when
+1 -1
View File
@@ -21,7 +21,7 @@ classifiers = [
requires-python = ">=3.12" requires-python = ">=3.12"
dependencies = [ dependencies = [
"napalm>=5.0.0", "napalm>=5.0.0",
"napalm_device_types>=4.35.0", # TimeSyncMixin, PosixTimeSyncMixin "napalm_device_types>=4.36.0", # TimeSyncMixin, PosixTimeSyncMixin (DHCP's servers)
"paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py) "paramiko>=5.0.0", # CVE-2026-44405; imported directly for the node's SSH session (_base.py)
"proxmoxer>=2.0.0", "proxmoxer>=2.0.0",
"netaddr>=0.9.0", "netaddr>=0.9.0",
+46
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import base64 import base64
import re import re
import shlex
import pytest import pytest
from napalm.base.exceptions import CommandErrorException from napalm.base.exceptions import CommandErrorException
@@ -105,3 +106,48 @@ def test_an_unreadable_cluster_check_refuses_too(driver, node):
driver.set_hostname("new") driver.set_hostname("new")
assert [c for c in node.ran if "corosync.conf" not in c] == [] assert [c for c in node.ran if "corosync.conf" not in c] == []
# ── the name reaches the shell quoted (NetOrk/netork#2456) ──────────────────
#
# The name went into the root commands between single quotes of their own, so a name
# with a single quote ended them: ``x';reboot;'`` ran ``reboot``. Each command now
# hands it on as one shell word, whatever it holds.
INJECTED = "x';reboot;'"
def _run(node: _Node, start: str) -> str:
return next(c for c in node.ran if c.startswith(start))
def test_the_runtime_hostname_is_one_word(driver, node):
driver.set_hostname(f"{INJECTED}.dom.lan")
assert shlex.split(_run(node, "hostname ")) == ["hostname", INJECTED]
def test_postfix_gets_the_fqdn_as_one_word(driver, node):
driver.set_hostname(f"{INJECTED}.dom.lan")
words = shlex.split(_run(node, "command -v postconf"))
assert words[words.index("-e") + 1] == f"myhostname = {INJECTED}.dom.lan"
def test_the_node_directory_is_moved_by_quoted_paths(driver, node):
driver.set_hostname(INJECTED)
words = shlex.split(_run(node, "if [ -d"))
assert words[words.index("mv") + 1 : words.index("mv") + 3] == [
"/etc/pve/nodes/pve",
f"/etc/pve/nodes/{INJECTED}",
]
@pytest.mark.parametrize("name", [INJECTED, "$(reboot)", "`reboot`", "a b"])
def test_no_command_runs_what_the_name_holds(driver, node, name):
driver.set_hostname(name)
for command in node.ran:
words = list(shlex.shlex(command, posix=True, punctuation_chars=True))
assert "reboot" not in words, command
+45 -6
View File
@@ -69,12 +69,19 @@ _MARK = "#napalm-time-sync: "
def _reading( def _reading(
zone: str = "Europe/Berlin", *, servers: tuple[str, ...] = (), timedatectl: bool = True zone: str = "Europe/Berlin",
*,
servers: tuple[str, ...] = (),
dhcp: tuple[str, ...] = (),
deaf_to_dhcp: bool = False,
timedatectl: bool = True,
) -> str: ) -> str:
"""What the reading prints; *servers* in netOrk's sources file, the vendor's pool """What the reading prints; *servers* in netOrk's sources file, the vendor's pool
commented out with it (as a write leaves the host).""" commented out with it (as a write leaves the host), *dhcp* in the DHCP client's
sources file. *deaf_to_dhcp* is a host napalm-device-types 4.35.0 aligned: its write
commented out the DHCP ``sourcedir`` too."""
written = bool(servers) written = bool(servers)
conf = _CHRONY_CONF.format(pool=_MARK if written else "", dhcp=_MARK if written else "") conf = _CHRONY_CONF.format(pool=_MARK if written else "", dhcp=_MARK if deaf_to_dhcp else "")
parts = ["@@ts timedatectl"] parts = ["@@ts timedatectl"]
if timedatectl: if timedatectl:
parts += [ parts += [
@@ -89,6 +96,10 @@ def _reading(
parts += ["@@ts zone", zone if timedatectl else ""] parts += ["@@ts zone", zone if timedatectl else ""]
parts += ["@@ts active", _ACTIVE_CHRONY, "@@ts timesync", "@@ts chronyc", _CHRONYC_SYNCED] parts += ["@@ts active", _ACTIVE_CHRONY, "@@ts timesync", "@@ts chronyc", _CHRONYC_SYNCED]
parts += ["@@ts chrony 0 main /etc/chrony/chrony.conf", conf, ""] parts += ["@@ts chrony 0 main /etc/chrony/chrony.conf", conf, ""]
if dhcp:
parts += ["@@ts chrony 11 sourcedir /run/chrony-dhcp/vmbr0.sources"]
parts += [f"server {s} iburst" for s in dhcp]
parts += [""]
if written: if written:
parts += ["@@ts chrony 14 sourcedir /etc/chrony/sources.d/netork.sources"] parts += ["@@ts chrony 14 sourcedir /etc/chrony/sources.d/netork.sources"]
parts += [f"{'pool' if '.pool.' in s else 'server'} {s} iburst" for s in servers] parts += [f"{'pool' if '.pool.' in s else 'server'} {s} iburst" for s in servers]
@@ -169,6 +180,7 @@ def test_pve_reads_chrony_and_the_zone_in_one_round_trip() -> None:
assert driver.get_time_sync() == { assert driver.get_time_sync() == {
"ntp_servers": ["2.debian.pool.ntp.org"], "ntp_servers": ["2.debian.pool.ntp.org"],
"dhcp_ntp_servers": [],
"timezone": "Europe/Berlin", "timezone": "Europe/Berlin",
"synchronized": True, "synchronized": True,
"daemon": "chrony", "daemon": "chrony",
@@ -183,6 +195,7 @@ def test_pbs_reads_chrony_and_the_zone() -> None:
assert driver.get_time_sync() == { assert driver.get_time_sync() == {
"ntp_servers": ["10.0.0.1"], "ntp_servers": ["10.0.0.1"],
"dhcp_ntp_servers": [],
"timezone": "Europe/Vienna", "timezone": "Europe/Vienna",
"synchronized": True, "synchronized": True,
"daemon": "chrony", "daemon": "chrony",
@@ -191,6 +204,17 @@ def test_pbs_reads_chrony_and_the_zone() -> None:
assert not [c for c in api.calls if c[0] != "GET"] assert not [c for c in api.calls if c[0] != "GET"]
def test_servers_from_dhcp_are_read_apart_from_the_configured_ones() -> None:
"""A node that gets its time giver by DHCP (option 42): chrony reads the DHCP
client's sources file, and those servers are not the node's own (NetOrk/netork#2380)."""
driver, _, _ = _pve(_reading(dhcp=("192.168.1.1",)))
reading = driver.get_time_sync()
assert reading["ntp_servers"] == ["2.debian.pool.ntp.org"]
assert reading["dhcp_ntp_servers"] == ["192.168.1.1"]
def test_a_host_without_a_zone_of_its_own_reads_the_apis() -> None: def test_a_host_without_a_zone_of_its_own_reads_the_apis() -> None:
"""No timedatectl and no /etc/timezone or /etc/localtime link: the API's word.""" """No timedatectl and no /etc/timezone or /etc/localtime link: the API's word."""
driver, api, _ = _pve(_reading(timedatectl=False)) driver, api, _ = _pve(_reading(timedatectl=False))
@@ -315,10 +339,25 @@ def test_servers_go_to_chronys_sources_d_and_the_vendor_pool_stops_counting(make
assert any( assert any(
"/etc/chrony/sources.d/netork.sources" in c and c.startswith("install") for c in root "/etc/chrony/sources.d/netork.sources" in c and c.startswith("install") for c in root
) )
# line 8 is the vendor's pool, line 11 the DHCP sourcedir: both in the main file, # line 8 is the vendor's pool, in the main file, which chronyd reads only when it
# which chronyd reads only when it starts. # starts. Line 11, the DHCP client's sourcedir, stays: DHCP's servers count.
sed = next(c for c in root if c.startswith("sed -i")) sed = next(c for c in root if c.startswith("sed -i"))
assert "8{" in sed and "11{" in sed and sed.endswith("/etc/chrony/chrony.conf") assert "8{" in sed and "11{" not in sed and sed.endswith("/etc/chrony/chrony.conf")
assert root[-1] == "systemctl restart chrony.service"
def test_a_write_gives_back_the_dhcp_sourcedir_an_earlier_write_took() -> None:
"""A node napalm-device-types 4.35.0 aligned hears DHCP again (NetOrk/netork#2380)."""
servers = ("10.0.0.1",)
driver, _, shell = _pve(_reading(servers=servers, deaf_to_dhcp=True), _reading(servers=servers))
result = driver.configure_time_sync(ntp_servers=list(servers))
assert result["success"], result["output"]
root = shell.root()
sed = next(c for c in root if c.startswith("sed -i"))
assert "11{s/^#napalm-time-sync: (sourcedir" in sed
assert sed.endswith("/etc/chrony/chrony.conf")
assert root[-1] == "systemctl restart chrony.service" assert root[-1] == "systemctl restart chrony.service"