From ff3f2aa48d2e0f5bfad387e1c1515ca45785f031 Mon Sep 17 00:00:00 2001 From: Guilherme Costa Date: Fri, 20 Nov 2026 10:18:40 +0000 Subject: [PATCH 1/5] fix(scripts): regenerate machine-id and SSH host keys per board on first boot --- scripts/hostname-helper.sh | 58 +++++++++++++++++++- tests/scripts/test_hostname_helper.py | 77 ++++++++++++++++++++++++++- 2 files changed, 132 insertions(+), 3 deletions(-) diff --git a/scripts/hostname-helper.sh b/scripts/hostname-helper.sh index b51e0424..46215966 100755 --- a/scripts/hostname-helper.sh +++ b/scripts/hostname-helper.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Give each board a hostname derived from its CPU serial, before the network comes up. +# Give each board a hostname from its CPU serial and, at boot, its own machine identity. # Pass --install-only to refresh the unit without renaming the running system. set -eu @@ -26,7 +26,9 @@ SCRIPT_PATH="$(readlink -f "$0")" BRAND_PREFIX="BLOCKS" MODEL="RF50" INSTALL_ONLY=false +BOOT=false [ "${1:-}" = "--install-only" ] && INSTALL_ONLY=true +[ "${1:-}" = "--boot" ] && BOOT=true # The unit already runs as root and sudo may not resolve this early in boot, so only escalate when needed. as_root() { @@ -49,7 +51,7 @@ Wants=network-pre.target [Service] Type=oneshot -ExecStart=$SCRIPT_PATH +ExecStart=$SCRIPT_PATH --boot RemainAfterExit=yes [Install] @@ -99,6 +101,55 @@ set_hostname() { ensure_hosts_entry "$want" } +new_machine_id() { + local root="$1" id tmp + id="$(tr -d '-' /dev/null || return 1 + as_root chmod 0444 "$tmp" || return 1 + as_root mv -f "$tmp" "$root/etc/machine-id" || return 1 + # A regular-file copy would keep the old id for dbus. + if [ -d "$root/var/lib/dbus" ]; then + as_root ln -sfn /etc/machine-id "$root/var/lib/dbus/machine-id" || return 1 + fi +} + +new_ssh_host_keys() { + local root="$1" stage="$1/etc/ssh/.hostkeys-new" + command -v ssh-keygen >/dev/null || return 0 + as_root rm -rf "$stage" + if ! as_root mkdir -p "$stage/etc/ssh" || ! as_root ssh-keygen -A -f "$stage" >/dev/null; then + as_root rm -rf "$stage" + echo_error "ssh-keygen failed, keeping the current SSH host keys" + return 1 + fi + # Rename over the old keys so sshd never finds none. + as_root mv -f "$stage"/etc/ssh/ssh_host_* "$root/etc/ssh/" || return 1 + as_root rm -rf "$stage" +} + +ensure_identity() { + local serial="$1" root="${2:-}" marker + marker="$root/var/lib/blocksscreen/identity-serial" + # Cloned images share machine-id (NetworkManager's IPv6 address seed) and SSH host keys. + if [ "$(cat "$marker" 2>/dev/null || true)" = "$serial" ]; then + return 0 + fi + echo_info "First boot on this board, regenerating machine-id and SSH host keys..." + # Without the marker, the next boot retries. + new_machine_id "$root" || return 0 + new_ssh_host_keys "$root" || return 0 + as_root mkdir -p "$(dirname "$marker")" + printf '%s\n' "$serial" | as_root tee "$marker" >/dev/null + echo_ok "Machine identity regenerated" +} + main() { echo_info "Script running on $SCRIPT_PATH..." install_service @@ -114,6 +165,9 @@ main() { esac set_hostname "$BRAND_PREFIX-$MODEL-$SERIAL" + # Only at boot, before NetworkManager, dbus and sshd read the identity. + $BOOT && ensure_identity "$SERIAL" + return 0 } # Sourcing (tests) only defines the functions. diff --git a/tests/scripts/test_hostname_helper.py b/tests/scripts/test_hostname_helper.py index 622d026b..5699e5f4 100644 --- a/tests/scripts/test_hostname_helper.py +++ b/tests/scripts/test_hostname_helper.py @@ -1,7 +1,10 @@ -"""Guard: hostname-helper.sh leaves exactly one 127.0.1.1 line in /etc/hosts.""" +"""Guard: hostname-helper.sh keeps /etc/hosts tidy and regenerates cloned identity.""" from __future__ import annotations +import os +import re +import shutil import subprocess from pathlib import Path @@ -50,3 +53,75 @@ def test_correct_file_is_left_alone(tmp_path: Path) -> None: before = hosts.stat().st_mtime_ns assert "Rewriting" not in _ensure(hosts) assert hosts.stat().st_mtime_ns == before + + +_CLONED_ID = "9c0eb5db83f14867bd94d9388132e18f\n" +_OLD_KEY = "ssh-ed25519 AAAAold root@image\n" + + +def _cloned_root(tmp_path: Path) -> Path: + """Build a fake root carrying the shared image identity.""" + root = tmp_path / "root" + (root / "etc" / "ssh").mkdir(parents=True) + (root / "var" / "lib" / "dbus").mkdir(parents=True) + (root / "etc" / "machine-id").write_text(_CLONED_ID) + (root / "var" / "lib" / "dbus" / "machine-id").write_text(_CLONED_ID) + (root / "etc" / "ssh" / "ssh_host_ed25519_key.pub").write_text(_OLD_KEY) + return root + + +def _identity(root: Path, serial: str, path: str | None = None) -> None: + """Source the helper with root writes stubbed out and run ensure_identity.""" + script = f'source "{_HELPER}"; as_root() {{ "$@"; }}; ensure_identity "$1" "$2"' + env = {**os.environ, "PATH": path or os.environ["PATH"]} + subprocess.run( + ["bash", "-c", script, "bash", serial, str(root)], + capture_output=True, + text=True, + timeout=60, + check=True, + env=env, + ) + + +@pytest.mark.skipif(shutil.which("ssh-keygen") is None, reason="needs ssh-keygen") +def test_identity_regenerates_once_per_serial(tmp_path: Path) -> None: + root = _cloned_root(tmp_path) + machine_id = root / "etc" / "machine-id" + _identity(root, "aaaa") + first = machine_id.read_text() + assert re.fullmatch(r"[0-9a-f]{32}\n", first) and first != _CLONED_ID + assert ( + os.readlink(root / "var" / "lib" / "dbus" / "machine-id") == "/etc/machine-id" + ) + pub = (root / "etc" / "ssh" / "ssh_host_ed25519_key.pub").read_text() + assert pub.startswith("ssh-ed25519 ") and pub != _OLD_KEY + assert not (root / "etc" / "ssh" / ".hostkeys-new").exists() + _identity(root, "aaaa") + assert machine_id.read_text() == first + # Same SD card in another board. + _identity(root, "bbbb") + assert machine_id.read_text() != first + + +def test_identity_keygen_failure_keeps_keys_and_retries(tmp_path: Path) -> None: + root = _cloned_root(tmp_path) + stubs = tmp_path / "bin" + stubs.mkdir() + keygen = stubs / "ssh-keygen" + keygen.write_text("#!/bin/sh\nexit 1\n") + keygen.chmod(0o755) + _identity(root, "aaaa", path=f"{stubs}:{os.environ['PATH']}") + assert (root / "etc" / "ssh" / "ssh_host_ed25519_key.pub").read_text() == _OLD_KEY + assert not (root / "var" / "lib" / "blocksscreen" / "identity-serial").exists() + + +def test_unit_regenerates_only_at_boot() -> None: + res = subprocess.run( + ["bash", "-c", f'source "{_HELPER}"; service_unit'], + capture_output=True, + text=True, + timeout=10, + check=True, + ) + assert re.search(r"^ExecStart=\S+ --boot$", res.stdout, re.M) From 762e693b89cb1b1a217687c0e24719e534cc4166 Mon Sep 17 00:00:00 2001 From: Guilherme Costa Date: Fri, 20 Nov 2026 10:23:03 +0000 Subject: [PATCH 2/5] test(scripts): tidy per-board identity tests --- tests/scripts/test_hostname_helper.py | 84 +++++++++++++++------------ 1 file changed, 46 insertions(+), 38 deletions(-) diff --git a/tests/scripts/test_hostname_helper.py b/tests/scripts/test_hostname_helper.py index 5699e5f4..71b78022 100644 --- a/tests/scripts/test_hostname_helper.py +++ b/tests/scripts/test_hostname_helper.py @@ -55,65 +55,73 @@ def test_correct_file_is_left_alone(tmp_path: Path) -> None: assert hosts.stat().st_mtime_ns == before -_CLONED_ID = "9c0eb5db83f14867bd94d9388132e18f\n" -_OLD_KEY = "ssh-ed25519 AAAAold root@image\n" - - -def _cloned_root(tmp_path: Path) -> Path: - """Build a fake root carrying the shared image identity.""" +_MACHINE_ID = Path("etc/machine-id") +_DBUS_MACHINE_ID = Path("var/lib/dbus/machine-id") +_HOST_KEY = Path("etc/ssh/ssh_host_ed25519_key.pub") +_MARKER = Path("var/lib/blocksscreen/identity-serial") +_IMAGE_ID = "0" * 31 + "1\n" +_IMAGE_KEY = "ssh-ed25519 IMAGE-KEY root@image\n" +_SERIAL = "1000000000000001" +_OTHER_SERIAL = "1000000000000002" + + +@pytest.fixture +def cloned_root(tmp_path: Path) -> Path: + """Fake root filesystem carrying the identity shared by a cloned image.""" root = tmp_path / "root" - (root / "etc" / "ssh").mkdir(parents=True) - (root / "var" / "lib" / "dbus").mkdir(parents=True) - (root / "etc" / "machine-id").write_text(_CLONED_ID) - (root / "var" / "lib" / "dbus" / "machine-id").write_text(_CLONED_ID) - (root / "etc" / "ssh" / "ssh_host_ed25519_key.pub").write_text(_OLD_KEY) + for rel, content in ( + (_MACHINE_ID, _IMAGE_ID), + (_DBUS_MACHINE_ID, _IMAGE_ID), + (_HOST_KEY, _IMAGE_KEY), + ): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_text(content) return root -def _identity(root: Path, serial: str, path: str | None = None) -> None: +def _ensure_identity(root: Path, serial: str, path: str | None = None) -> None: """Source the helper with root writes stubbed out and run ensure_identity.""" script = f'source "{_HELPER}"; as_root() {{ "$@"; }}; ensure_identity "$1" "$2"' - env = {**os.environ, "PATH": path or os.environ["PATH"]} subprocess.run( ["bash", "-c", script, "bash", serial, str(root)], capture_output=True, text=True, timeout=60, check=True, - env=env, + env={**os.environ, "PATH": path or os.environ["PATH"]}, ) @pytest.mark.skipif(shutil.which("ssh-keygen") is None, reason="needs ssh-keygen") -def test_identity_regenerates_once_per_serial(tmp_path: Path) -> None: - root = _cloned_root(tmp_path) - machine_id = root / "etc" / "machine-id" - _identity(root, "aaaa") - first = machine_id.read_text() - assert re.fullmatch(r"[0-9a-f]{32}\n", first) and first != _CLONED_ID - assert ( - os.readlink(root / "var" / "lib" / "dbus" / "machine-id") == "/etc/machine-id" - ) - pub = (root / "etc" / "ssh" / "ssh_host_ed25519_key.pub").read_text() - assert pub.startswith("ssh-ed25519 ") and pub != _OLD_KEY - assert not (root / "etc" / "ssh" / ".hostkeys-new").exists() - _identity(root, "aaaa") - assert machine_id.read_text() == first - # Same SD card in another board. - _identity(root, "bbbb") - assert machine_id.read_text() != first - - -def test_identity_keygen_failure_keeps_keys_and_retries(tmp_path: Path) -> None: - root = _cloned_root(tmp_path) +def test_identity_regenerates_once_per_serial(cloned_root: Path) -> None: + _ensure_identity(cloned_root, _SERIAL) + machine_id = (cloned_root / _MACHINE_ID).read_text() + assert re.fullmatch(r"[0-9a-f]{32}\n", machine_id) and machine_id != _IMAGE_ID + assert os.readlink(cloned_root / _DBUS_MACHINE_ID) == "/etc/machine-id" + host_key = (cloned_root / _HOST_KEY).read_text() + assert host_key.startswith("ssh-ed25519 ") and host_key != _IMAGE_KEY + assert not (cloned_root / "etc/ssh/.hostkeys-new").exists() + assert (cloned_root / _MARKER).read_text() == f"{_SERIAL}\n" + + _ensure_identity(cloned_root, _SERIAL) + assert (cloned_root / _MACHINE_ID).read_text() == machine_id + + # Same SD card moved to another board. + _ensure_identity(cloned_root, _OTHER_SERIAL) + assert (cloned_root / _MACHINE_ID).read_text() != machine_id + + +def test_identity_keygen_failure_keeps_keys_and_retries( + cloned_root: Path, tmp_path: Path +) -> None: stubs = tmp_path / "bin" stubs.mkdir() keygen = stubs / "ssh-keygen" keygen.write_text("#!/bin/sh\nexit 1\n") keygen.chmod(0o755) - _identity(root, "aaaa", path=f"{stubs}:{os.environ['PATH']}") - assert (root / "etc" / "ssh" / "ssh_host_ed25519_key.pub").read_text() == _OLD_KEY - assert not (root / "var" / "lib" / "blocksscreen" / "identity-serial").exists() + _ensure_identity(cloned_root, _SERIAL, path=f"{stubs}:{os.environ['PATH']}") + assert (cloned_root / _HOST_KEY).read_text() == _IMAGE_KEY + assert not (cloned_root / _MARKER).exists() def test_unit_regenerates_only_at_boot() -> None: From c4b0dd42d1d21c17ec574c644c992d291c8459a9 Mon Sep 17 00:00:00 2001 From: Guilherme Costa Date: Fri, 20 Nov 2026 10:36:07 +0000 Subject: [PATCH 3/5] fix(scripts): gate identity regeneration on early boot, not a unit flag --- scripts/hostname-helper.sh | 14 ++++++++------ tests/scripts/test_hostname_helper.py | 18 +++++++++++++----- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/scripts/hostname-helper.sh b/scripts/hostname-helper.sh index 46215966..70593096 100755 --- a/scripts/hostname-helper.sh +++ b/scripts/hostname-helper.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Give each board a hostname from its CPU serial and, at boot, its own machine identity. +# Give each board a hostname from its CPU serial and, early in boot, its own machine identity. # Pass --install-only to refresh the unit without renaming the running system. set -eu @@ -26,9 +26,7 @@ SCRIPT_PATH="$(readlink -f "$0")" BRAND_PREFIX="BLOCKS" MODEL="RF50" INSTALL_ONLY=false -BOOT=false [ "${1:-}" = "--install-only" ] && INSTALL_ONLY=true -[ "${1:-}" = "--boot" ] && BOOT=true # The unit already runs as root and sudo may not resolve this early in boot, so only escalate when needed. as_root() { @@ -51,7 +49,7 @@ Wants=network-pre.target [Service] Type=oneshot -ExecStart=$SCRIPT_PATH --boot +ExecStart=$SCRIPT_PATH RemainAfterExit=yes [Install] @@ -134,6 +132,11 @@ new_ssh_host_keys() { as_root rm -rf "$stage" } +# Before basic.target nothing has read the identity; unlike a unit flag, this also works under old unit files. +early_boot() { + [ "$(systemctl is-system-running 2>/dev/null || true)" = "initializing" ] +} + ensure_identity() { local serial="$1" root="${2:-}" marker marker="$root/var/lib/blocksscreen/identity-serial" @@ -165,8 +168,7 @@ main() { esac set_hostname "$BRAND_PREFIX-$MODEL-$SERIAL" - # Only at boot, before NetworkManager, dbus and sshd read the identity. - $BOOT && ensure_identity "$SERIAL" + early_boot && ensure_identity "$SERIAL" return 0 } diff --git a/tests/scripts/test_hostname_helper.py b/tests/scripts/test_hostname_helper.py index 71b78022..03312bbb 100644 --- a/tests/scripts/test_hostname_helper.py +++ b/tests/scripts/test_hostname_helper.py @@ -124,12 +124,20 @@ def test_identity_keygen_failure_keeps_keys_and_retries( assert not (cloned_root / _MARKER).exists() -def test_unit_regenerates_only_at_boot() -> None: +@pytest.mark.parametrize( + ("state", "expected"), + [("initializing", 0), ("starting", 1), ("running", 1), ("degraded", 1)], +) +def test_identity_only_before_basic_target( + tmp_path: Path, state: str, expected: int +) -> None: + systemctl = tmp_path / "systemctl" + systemctl.write_text(f"#!/bin/sh\necho {state}\nexit 1\n") + systemctl.chmod(0o755) res = subprocess.run( - ["bash", "-c", f'source "{_HELPER}"; service_unit'], + ["bash", "-c", f'source "{_HELPER}"; early_boot'], capture_output=True, - text=True, timeout=10, - check=True, + env={**os.environ, "PATH": f"{tmp_path}:{os.environ['PATH']}"}, ) - assert re.search(r"^ExecStart=\S+ --boot$", res.stdout, re.M) + assert res.returncode == expected From 955e478267c4af292776040f82868922dc78bddb Mon Sep 17 00:00:00 2001 From: Guilherme Costa Date: Fri, 20 Nov 2026 10:46:42 +0000 Subject: [PATCH 4/5] fix(hostname): stage host keys before machine-id, drop stale keys and v1 NM secret --- scripts/hostname-helper.sh | 45 ++++++++++++++++++++++----- tests/scripts/test_hostname_helper.py | 25 +++++++++++++-- 2 files changed, 59 insertions(+), 11 deletions(-) diff --git a/scripts/hostname-helper.sh b/scripts/hostname-helper.sh index 70593096..9d59f3da 100755 --- a/scripts/hostname-helper.sh +++ b/scripts/hostname-helper.sh @@ -118,38 +118,67 @@ new_machine_id() { fi } -new_ssh_host_keys() { - local root="$1" stage="$1/etc/ssh/.hostkeys-new" - command -v ssh-keygen >/dev/null || return 0 +stage_ssh_host_keys() { + local stage="$1" as_root rm -rf "$stage" if ! as_root mkdir -p "$stage/etc/ssh" || ! as_root ssh-keygen -A -f "$stage" >/dev/null; then as_root rm -rf "$stage" - echo_error "ssh-keygen failed, keeping the current SSH host keys" + echo_error "ssh-keygen failed, keeping the current identity" return 1 fi +} + +install_ssh_host_keys() { + local root="$1" stage="$2" key + # Key types ssh-keygen -A no longer makes would stay shared with every other board. + for key in "$root"/etc/ssh/ssh_host_*; do + [ -e "$stage/etc/ssh/${key##*/}" ] || as_root rm -f "$key" || return 1 + done # Rename over the old keys so sshd never finds none. as_root mv -f "$stage"/etc/ssh/ssh_host_* "$root/etc/ssh/" || return 1 as_root rm -rf "$stage" } +# Only v2 keys ("nm-v2:") are hashed with the machine-id; NM writes a fresh v2 key when none exists. +drop_v1_nm_secret_key() { + local key="$1/var/lib/NetworkManager/secret_key" + as_root test -f "$key" || return 0 + [ "$(as_root head -c 6 "$key")" = "nm-v2:" ] && return 0 + as_root rm -f "$key" +} + # Before basic.target nothing has read the identity; unlike a unit flag, this also works under old unit files. early_boot() { [ "$(systemctl is-system-running 2>/dev/null || true)" = "initializing" ] } ensure_identity() { - local serial="$1" root="${2:-}" marker + local serial="$1" root="${2:-}" marker stage keys=false marker="$root/var/lib/blocksscreen/identity-serial" + stage="$root/etc/ssh/.hostkeys-new" # Cloned images share machine-id (NetworkManager's IPv6 address seed) and SSH host keys. if [ "$(cat "$marker" 2>/dev/null || true)" = "$serial" ]; then return 0 fi echo_info "First boot on this board, regenerating machine-id and SSH host keys..." - # Without the marker, the next boot retries. - new_machine_id "$root" || return 0 - new_ssh_host_keys "$root" || return 0 + # Keys are staged first: a failure leaves the old identity whole, and without the marker the next boot retries. + if command -v ssh-keygen >/dev/null; then + stage_ssh_host_keys "$stage" || return 0 + keys=true + fi + if ! new_machine_id "$root"; then + as_root rm -rf "$stage" + return 0 + fi + if $keys; then + install_ssh_host_keys "$root" "$stage" || return 0 + fi + drop_v1_nm_secret_key "$root" || return 0 + # Flush the new identity before the marker that claims it. + sync as_root mkdir -p "$(dirname "$marker")" printf '%s\n' "$serial" | as_root tee "$marker" >/dev/null + sync echo_ok "Machine identity regenerated" } diff --git a/tests/scripts/test_hostname_helper.py b/tests/scripts/test_hostname_helper.py index 03312bbb..ae9c57dd 100644 --- a/tests/scripts/test_hostname_helper.py +++ b/tests/scripts/test_hostname_helper.py @@ -58,6 +58,8 @@ def test_correct_file_is_left_alone(tmp_path: Path) -> None: _MACHINE_ID = Path("etc/machine-id") _DBUS_MACHINE_ID = Path("var/lib/dbus/machine-id") _HOST_KEY = Path("etc/ssh/ssh_host_ed25519_key.pub") +_STALE_KEY = Path("etc/ssh/ssh_host_dsa_key") +_NM_SECRET = Path("var/lib/NetworkManager/secret_key") _MARKER = Path("var/lib/blocksscreen/identity-serial") _IMAGE_ID = "0" * 31 + "1\n" _IMAGE_KEY = "ssh-ed25519 IMAGE-KEY root@image\n" @@ -73,6 +75,7 @@ def cloned_root(tmp_path: Path) -> Path: (_MACHINE_ID, _IMAGE_ID), (_DBUS_MACHINE_ID, _IMAGE_ID), (_HOST_KEY, _IMAGE_KEY), + (_STALE_KEY, _IMAGE_KEY), ): (root / rel).parent.mkdir(parents=True, exist_ok=True) (root / rel).write_text(content) @@ -101,6 +104,7 @@ def test_identity_regenerates_once_per_serial(cloned_root: Path) -> None: host_key = (cloned_root / _HOST_KEY).read_text() assert host_key.startswith("ssh-ed25519 ") and host_key != _IMAGE_KEY assert not (cloned_root / "etc/ssh/.hostkeys-new").exists() + assert not (cloned_root / _STALE_KEY).exists() assert (cloned_root / _MARKER).read_text() == f"{_SERIAL}\n" _ensure_identity(cloned_root, _SERIAL) @@ -119,9 +123,24 @@ def test_identity_keygen_failure_keeps_keys_and_retries( keygen = stubs / "ssh-keygen" keygen.write_text("#!/bin/sh\nexit 1\n") keygen.chmod(0o755) - _ensure_identity(cloned_root, _SERIAL, path=f"{stubs}:{os.environ['PATH']}") - assert (cloned_root / _HOST_KEY).read_text() == _IMAGE_KEY - assert not (cloned_root / _MARKER).exists() + for _ in range(2): + _ensure_identity(cloned_root, _SERIAL, path=f"{stubs}:{os.environ['PATH']}") + assert (cloned_root / _MACHINE_ID).read_text() == _IMAGE_ID + assert (cloned_root / _HOST_KEY).read_text() == _IMAGE_KEY + assert not (cloned_root / _MARKER).exists() + + +@pytest.mark.parametrize( + ("key", "kept"), [("nm-v2:" + "a" * 32, True), ("a" * 32, False)], ids=["v2", "v1"] +) +def test_identity_drops_only_v1_nm_secret_key( + cloned_root: Path, key: str, kept: bool +) -> None: + secret = cloned_root / _NM_SECRET + secret.parent.mkdir(parents=True) + secret.write_text(key) + _ensure_identity(cloned_root, _SERIAL) + assert secret.exists() == kept @pytest.mark.parametrize( From 8e1ce3f84ae9e12982307b08ebe368196927a43d Mon Sep 17 00:00:00 2001 From: Guilherme Costa Date: Fri, 20 Nov 2026 11:22:13 +0000 Subject: [PATCH 5/5] fix(hostname): per-step identity markers, install keys before dropping stale ones --- scripts/hostname-helper.sh | 70 +++++++++++++++------------ tests/scripts/test_hostname_helper.py | 42 +++++++++++----- 2 files changed, 68 insertions(+), 44 deletions(-) diff --git a/scripts/hostname-helper.sh b/scripts/hostname-helper.sh index 9d59f3da..7b7f46f3 100755 --- a/scripts/hostname-helper.sh +++ b/scripts/hostname-helper.sh @@ -123,63 +123,69 @@ stage_ssh_host_keys() { as_root rm -rf "$stage" if ! as_root mkdir -p "$stage/etc/ssh" || ! as_root ssh-keygen -A -f "$stage" >/dev/null; then as_root rm -rf "$stage" - echo_error "ssh-keygen failed, keeping the current identity" + echo_error "ssh-keygen failed, keeping the current SSH host keys" return 1 fi } install_ssh_host_keys() { - local root="$1" stage="$2" key - # Key types ssh-keygen -A no longer makes would stay shared with every other board. + local root="$1" stage="$2" key stale=() + # Old types ssh-keygen -A no longer makes stay shared, and host certificates no longer match the new keys. for key in "$root"/etc/ssh/ssh_host_*; do - [ -e "$stage/etc/ssh/${key##*/}" ] || as_root rm -f "$key" || return 1 + if [ -e "$key" ] && [ ! -e "$stage/etc/ssh/${key##*/}" ]; then + stale+=("$key") + fi done - # Rename over the old keys so sshd never finds none. + # Install before deleting, so a failed rename never leaves a key type missing. as_root mv -f "$stage"/etc/ssh/ssh_host_* "$root/etc/ssh/" || return 1 - as_root rm -rf "$stage" + if [ "${#stale[@]}" -gt 0 ]; then + as_root rm -f "${stale[@]}" || echo_error "Could not remove stale SSH host keys" + fi + as_root rm -rf "$stage" || true } # Only v2 keys ("nm-v2:") are hashed with the machine-id; NM writes a fresh v2 key when none exists. drop_v1_nm_secret_key() { local key="$1/var/lib/NetworkManager/secret_key" as_root test -f "$key" || return 0 - [ "$(as_root head -c 6 "$key")" = "nm-v2:" ] && return 0 + [ "$(as_root head -c 6 "$key" | tr -d '\0')" = "nm-v2:" ] && return 0 as_root rm -f "$key" } -# Before basic.target nothing has read the identity; unlike a unit flag, this also works under old unit files. +# Before basic.target nothing has read the identity; as root, systemctl reaches PID 1 without dbus. early_boot() { [ "$(systemctl is-system-running 2>/dev/null || true)" = "initializing" ] } +# Flushes the step's changes first, so the marker never claims work still in the page cache. +mark_done() { + local marker="$1" serial="$2" + sync + as_root mkdir -p "$(dirname "$marker")" || return 1 + printf '%s\n' "$serial" | as_root tee "$marker" >/dev/null || return 1 + sync +} + +# One marker per step: a later failure retries only that step, never re-rolling an earlier one. ensure_identity() { - local serial="$1" root="${2:-}" marker stage keys=false - marker="$root/var/lib/blocksscreen/identity-serial" - stage="$root/etc/ssh/.hostkeys-new" + local serial="$1" root="${2:-}" state + state="$root/var/lib/blocksscreen" # Cloned images share machine-id (NetworkManager's IPv6 address seed) and SSH host keys. - if [ "$(cat "$marker" 2>/dev/null || true)" = "$serial" ]; then - return 0 + if [ "$(cat "$state/identity-serial" 2>/dev/null || true)" != "$serial" ]; then + echo_info "First boot on this board, regenerating machine-id..." + new_machine_id "$root" || return 0 + drop_v1_nm_secret_key "$root" || echo_error "Could not remove the v1 NetworkManager secret_key" + mark_done "$state/identity-serial" "$serial" || return 0 + echo_ok "machine-id regenerated" fi - echo_info "First boot on this board, regenerating machine-id and SSH host keys..." - # Keys are staged first: a failure leaves the old identity whole, and without the marker the next boot retries. - if command -v ssh-keygen >/dev/null; then - stage_ssh_host_keys "$stage" || return 0 - keys=true + if command -v ssh-keygen >/dev/null && + [ "$(cat "$state/hostkeys-serial" 2>/dev/null || true)" != "$serial" ]; then + echo_info "Regenerating SSH host keys..." + stage_ssh_host_keys "$root/etc/ssh/.hostkeys-new" || return 0 + install_ssh_host_keys "$root" "$root/etc/ssh/.hostkeys-new" || return 0 + mark_done "$state/hostkeys-serial" "$serial" || return 0 + echo_ok "SSH host keys regenerated" fi - if ! new_machine_id "$root"; then - as_root rm -rf "$stage" - return 0 - fi - if $keys; then - install_ssh_host_keys "$root" "$stage" || return 0 - fi - drop_v1_nm_secret_key "$root" || return 0 - # Flush the new identity before the marker that claims it. - sync - as_root mkdir -p "$(dirname "$marker")" - printf '%s\n' "$serial" | as_root tee "$marker" >/dev/null - sync - echo_ok "Machine identity regenerated" } main() { diff --git a/tests/scripts/test_hostname_helper.py b/tests/scripts/test_hostname_helper.py index ae9c57dd..82ce6fe9 100644 --- a/tests/scripts/test_hostname_helper.py +++ b/tests/scripts/test_hostname_helper.py @@ -60,7 +60,8 @@ def test_correct_file_is_left_alone(tmp_path: Path) -> None: _HOST_KEY = Path("etc/ssh/ssh_host_ed25519_key.pub") _STALE_KEY = Path("etc/ssh/ssh_host_dsa_key") _NM_SECRET = Path("var/lib/NetworkManager/secret_key") -_MARKER = Path("var/lib/blocksscreen/identity-serial") +_ID_MARKER = Path("var/lib/blocksscreen/identity-serial") +_KEYS_MARKER = Path("var/lib/blocksscreen/hostkeys-serial") _IMAGE_ID = "0" * 31 + "1\n" _IMAGE_KEY = "ssh-ed25519 IMAGE-KEY root@image\n" _SERIAL = "1000000000000001" @@ -95,7 +96,12 @@ def _ensure_identity(root: Path, serial: str, path: str | None = None) -> None: ) -@pytest.mark.skipif(shutil.which("ssh-keygen") is None, reason="needs ssh-keygen") +_NEEDS_KEYGEN = pytest.mark.skipif( + shutil.which("ssh-keygen") is None, reason="needs ssh-keygen" +) + + +@_NEEDS_KEYGEN def test_identity_regenerates_once_per_serial(cloned_root: Path) -> None: _ensure_identity(cloned_root, _SERIAL) machine_id = (cloned_root / _MACHINE_ID).read_text() @@ -105,7 +111,8 @@ def test_identity_regenerates_once_per_serial(cloned_root: Path) -> None: assert host_key.startswith("ssh-ed25519 ") and host_key != _IMAGE_KEY assert not (cloned_root / "etc/ssh/.hostkeys-new").exists() assert not (cloned_root / _STALE_KEY).exists() - assert (cloned_root / _MARKER).read_text() == f"{_SERIAL}\n" + assert (cloned_root / _ID_MARKER).read_text() == f"{_SERIAL}\n" + assert (cloned_root / _KEYS_MARKER).read_text() == f"{_SERIAL}\n" _ensure_identity(cloned_root, _SERIAL) assert (cloned_root / _MACHINE_ID).read_text() == machine_id @@ -115,7 +122,8 @@ def test_identity_regenerates_once_per_serial(cloned_root: Path) -> None: assert (cloned_root / _MACHINE_ID).read_text() != machine_id -def test_identity_keygen_failure_keeps_keys_and_retries( +@_NEEDS_KEYGEN +def test_identity_keygen_failure_retries_only_the_keys( cloned_root: Path, tmp_path: Path ) -> None: stubs = tmp_path / "bin" @@ -123,22 +131,32 @@ def test_identity_keygen_failure_keeps_keys_and_retries( keygen = stubs / "ssh-keygen" keygen.write_text("#!/bin/sh\nexit 1\n") keygen.chmod(0o755) - for _ in range(2): - _ensure_identity(cloned_root, _SERIAL, path=f"{stubs}:{os.environ['PATH']}") - assert (cloned_root / _MACHINE_ID).read_text() == _IMAGE_ID - assert (cloned_root / _HOST_KEY).read_text() == _IMAGE_KEY - assert not (cloned_root / _MARKER).exists() + failing = f"{stubs}:{os.environ['PATH']}" + _ensure_identity(cloned_root, _SERIAL, path=failing) + machine_id = (cloned_root / _MACHINE_ID).read_text() + assert machine_id != _IMAGE_ID + + _ensure_identity(cloned_root, _SERIAL, path=failing) + assert (cloned_root / _MACHINE_ID).read_text() == machine_id + assert (cloned_root / _HOST_KEY).read_text() == _IMAGE_KEY + assert not (cloned_root / _KEYS_MARKER).exists() + + _ensure_identity(cloned_root, _SERIAL) + assert (cloned_root / _MACHINE_ID).read_text() == machine_id + assert (cloned_root / _HOST_KEY).read_text() != _IMAGE_KEY @pytest.mark.parametrize( - ("key", "kept"), [("nm-v2:" + "a" * 32, True), ("a" * 32, False)], ids=["v2", "v1"] + ("key", "kept"), + [(b"nm-v2:" + b"\xa5" * 32, True), (b"\0\xa5" * 16, False)], + ids=["v2", "v1-binary"], ) def test_identity_drops_only_v1_nm_secret_key( - cloned_root: Path, key: str, kept: bool + cloned_root: Path, key: bytes, kept: bool ) -> None: secret = cloned_root / _NM_SECRET secret.parent.mkdir(parents=True) - secret.write_text(key) + secret.write_bytes(key) _ensure_identity(cloned_root, _SERIAL) assert secret.exists() == kept