From 8f6647421e84cebab7caa07391ec90e2b4a6a81f Mon Sep 17 00:00:00 2001 From: "Linnard Alex Brown Jr." Date: Wed, 18 Nov 2026 08:12:54 -0500 Subject: [PATCH 1/4] Fix the baseline review findings; 2.6.0 Secure Boot rollback: a new kernel that cannot be signed is purged together with its systemd-boot entry; a version installed before (even the running kernel) is never purged, its kernel and modules are kept before dpkg and put back, its initramfs generated again. Preconditions (initramfs tool, kernel-install/kernelstub) are checked before dpkg; a missing modules dir stops the install instead of switching kernels. apt repairs are simulated and refused when they would remove packages. The metapackage guard reads Purg lines too. The ESP copy gets the final initramfs whether or not the kernel is signed, and the entry's files are checked. Set Up Signing re-syncs signed kernels with an unsigned ESP copy, replaces an older signed systemd-boot on the ESP, leaves another system's fallback loader alone and writes BOOTX64.CSV atomically. XBOOTLDR entries are found. DKMS 2 status lines and single-quoted/absent BUILT_MODULE_NAME are handled. A MokNew shorter than its attribute bytes reads as damaged. App: closing at the build summary discards the prepared tree and closes; a cancelled control never starts a build. Tar members with ./ prefixes are accepted like the Makefile search reads them. A failed final flush of a download deletes the .part file and retries. The libcheck test really starts its background sleep. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 29 +- CHANGELOG.md | 29 ++ Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 13 +- data/io.github.labj1987.KernelPop.appdata.xml | 1 + scripts/privileged-install.sh | 474 ++++++++++++++---- scripts/tests/test-privileged.sh | 213 +++++++- src/download.rs | 47 +- src/source.rs | 36 +- src/ui.rs | 44 +- tests/libcheck.rs | 18 +- 12 files changed, 767 insertions(+), 141 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 015c7b4..e801729 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,8 +231,14 @@ No kernel that shim would refuse is ever left installed. With Secure Boot enforcing, `--install` requires the key set, the sbsign tools and a key that is enrolled or queued (`secure_boot_preflight`, before dpkg; the app checks the same in `install_blocker` and refuses up front). If signing -then fails, the just-installed packages are purged again -(`rollback_install`) and the run fails. A queued key is fine: the kernel +then fails, `rollback_and_die` undoes the install and the run fails: new +packages are purged and their boot entry removed (`remove_boot_entry`: no +postrm hook removes a systemd-boot entry); a version that was installed +before (a rebuild, maybe of the running kernel) is never purged, its +kernel, System.map, config and modules are kept before dpkg +(`keep_installed_kernel`, hard links) and moved back, and its initramfs is +generated again. Everything the steps after dpkg need (an initramfs tool, +kernel-install or kernelstub) is checked before dpkg. A queued key is fine: the kernel boots once MOK Manager enrolls it. ## Kernel signing @@ -299,6 +305,12 @@ boots once MOK Manager enrolls it. before 2.2.3) gets its package reinstalled, which puts the distribution's copy back. A failed reinstall only logs. Never from the apt hook, which runs inside dpkg. +- systemd-boot entries are looked for on the ESP and then on the XBOOTLDR + partition (`bootctl --print-boot-path`, `KERNEL_POP_XBOOTLDR` in tests); + the paths in an entry are relative to the partition it is on + (`sdboot_entry_root`). After an install the ESP copy is refreshed whether + or not the kernel was signed (the package hook copied the initramfs from + before DKMS) and every file the entry names must exist. - `prune_esp_initrds `: after every kernel-install add and at the end of a systemd-boot install, initramfs files ("initrd", "initrd.img-*") in the entry's ESP directory that the entry does not name are removed @@ -310,8 +322,11 @@ boots once MOK Manager enrolls it. - shim in front of systemd-boot (`setup_shim_chain`, from `do_setup_signing` when `detect_bootloader` says systemd-boot): the layout of Ubuntu's systemd-boot postinst `install_shim` (shim/fb/mm in - `EFI//`, shim at `EFI/BOOT/BOOTX64.EFI`, UCS-2LE - `BOOTX64.CSV` byte-identical to install_shim's, firmware entry + `EFI//`, shim at `EFI/BOOT/BOOTX64.EFI` only over a + fallback loader that is ours (`fallback_is_ours`: none, shim, or + systemd-boot; never Windows' or another distribution's, and then no + fbx64 either), UCS-2LE `BOOTX64.CSV` (written tmp + mv) + byte-identical to install_shim's, firmware entry `` = `EFI//shimx64.efi` with load option `\EFI\systemd\systemd-bootx64.efi \0`), done by the script itself so it also works while GRUB's packages are installed (install_shim returns @@ -356,7 +371,11 @@ boots once MOK Manager enrolls it. run `finish_interrupted_dpkg` first: with files in `/var/lib/dpkg/updates` or any `dpkg --audit` output (a run cut off by a crash or power cut), `dpkg --configure -a`, `apt-get install -f`, and - `--reinstall` of packages whose status has the reinst-required flag. + `--reinstall` of packages whose status has the reinst-required flag. Every +apt repair (`install -f`, that `--reinstall`, the `install -f` after a failed +`dpkg -i`) is simulated first (`apt_removals`: `Remv` and `Purg` lines) and +not run when it would remove a package (after a failed `dpkg -i`, only the +new packages themselves may go, and only when they replaced nothing). ## Build process diff --git a/CHANGELOG.md b/CHANGELOG.md index 608b689..650fe95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,35 @@ One `## — ` heading per released version, newest first. A rele carries its section as written, and the AppStream `` list is generated from these headings. +## 2.6.0 — 2026-11-18 + +- **A kernel that could not be signed under Secure Boot no longer leaves a broken boot entry.** On + systemd-boot, the rollback now removes the boot menu entry too, so the machine does not try the + removed kernel by default on the next start. +- **Reinstalling a kernel version you already have is safe under Secure Boot.** If the new build + cannot be signed, the kernel that was installed before (even the running one) is put back + instead of being removed. +- On systemd-boot and Pop!_OS, the kernel's copy on the EFI partition now always gets the final + initramfs, with the DKMS modules (such as the NVIDIA driver) built in, also without kernel + signing set up. The install checks that every file the boot entry names is there. +- Kernel Pop no longer lets apt remove packages unasked: when repairing an interrupted update or a + failed install would remove packages, it stops and tells you what would go. +- The install checks for an initramfs tool and the boot loader's tools before it installs + anything, instead of failing halfway. +- Removing a kernel now always notices when that would also remove Ubuntu's kernel metapackages. +- Set Up Signing repairs an earlier failed copy of a signed kernel to the EFI partition, and keeps + the systemd-boot on the EFI partition up to date when it was signed before. +- Set Up Signing leaves the fallback boot loader alone on an EFI partition shared with Windows or + another distribution. +- Systems with a separate `/boot` boot partition (XBOOTLDR) are supported for systemd-boot + entries. +- DKMS modules are re-signed on systems with DKMS 2, and for modules whose dkms.conf uses single + quotes or names no module. +- Closing the window while the build summary is open closes it at once and deletes the prepared + source tree. +- Tarballs whose members start with `./` can be built. +- A download that fails on its last write (a full disk) is retried and leaves no partial file. + ## 2.5.2 — 2026-11-16 - **The window takes your desktop's accent colour.** On GNOME, KDE Plasma and COSMIC, primary diff --git a/Cargo.lock b/Cargo.lock index 040bbe3..0843750 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3386,7 +3386,7 @@ dependencies = [ [[package]] name = "kernel-pop" -version = "2.5.2" +version = "2.6.0" dependencies = [ "anyhow", "ashpd", diff --git a/Cargo.toml b/Cargo.toml index 9c87323..9643327 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kernel-pop" -version = "2.5.2" +version = "2.6.0" edition = "2021" rust-version = "1.100" description = "Kernel Pop — GUI that builds kernel.org kernels for this machine and installs them" diff --git a/README.md b/README.md index 759ff52..983849d 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,8 @@ VFS-panics on boot. This app is built around not letting that happen: System tab, once signing is set up - With Secure Boot on, a kernel that could not boot is never installed: the install is refused until signing is set up, and a kernel whose - signing fails is removed again + signing fails is removed again, boot menu entry included (a rebuild of a + version already installed puts the one from before back instead) - Optional kernel signing: a one-time Set Up Signing step creates Kernel Pop's own signing key, signs the installed kernels, puts shim in front of systemd-boot where the firmware starts it directly, and queues the key @@ -275,7 +276,9 @@ absent: put back by reinstalling the package that ships it - copies shim, MOK Manager and the fallback loader to the ESP, puts shim at the fallback path `EFI/BOOT/BOOTX64.EFI`, and writes the `BOOTX64.CSV` - that restores the entry after a firmware reset + that restores the entry after a firmware reset. On an ESP shared with + Windows or another distribution whose loader sits at that path, it is + left alone: the firmware entry below is what starts this system - adds a firmware entry named after the distribution that starts shim with systemd-boot as what it loads, then removes the "Linux Boot Manager" entries `bootctl` adds, which skip shim. Every copy to the ESP must @@ -319,8 +322,10 @@ signed with a key that is enrolled or waiting for enrollment: before anything changes, and the app points you to Set Up Signing. - If signing the new kernel fails, or the copy on the ESP that systemd-boot or kernelstub starts does not carry the signature, its packages are - removed again, so no kernel that shim would refuse is left in the boot - menu. + removed again, with its systemd-boot entry, so no kernel that shim would + refuse is left in the boot menu. A rebuild of a version that was already + installed (the running kernel, say) is never removed: the kernel and + modules from before are put back and its initramfs made again. - If the key is still waiting for enrollment, the kernel is installed and signed, and the install reminds you to confirm the enrollment at the MOK Manager screen on the next reboot; skip that and it will not boot. diff --git a/data/io.github.labj1987.KernelPop.appdata.xml b/data/io.github.labj1987.KernelPop.appdata.xml index aa853a1..fad9f5b 100644 --- a/data/io.github.labj1987.KernelPop.appdata.xml +++ b/data/io.github.labj1987.KernelPop.appdata.xml @@ -30,6 +30,7 @@ System + diff --git a/scripts/privileged-install.sh b/scripts/privileged-install.sh index 1c77f70..b583651 100755 --- a/scripts/privileged-install.sh +++ b/scripts/privileged-install.sh @@ -60,7 +60,8 @@ ARG="${2:-}" # KERNEL_POP_DPKG_ADMIN, KERNEL_POP_PROC, KERNEL_POP_LOCK_WAIT, # KERNEL_POP_LOCK_POLL, KERNEL_POP_SDBOOT, KERNEL_POP_SHIM_LIB, # KERNEL_POP_SDBOOT_STAMP, KERNEL_POP_APT_HOOK, KERNEL_POP_KERNEL_HOOK, -# KERNEL_POP_OS_RELEASE. +# KERNEL_POP_OS_RELEASE, KERNEL_POP_XBOOTLDR (set, even empty: the XBOOTLDR +# partition instead of asking bootctl). boot_dir() { echo "${KERNEL_POP_BOOT:-/boot}"; } modules_dir() { echo "${KERNEL_POP_MODULES:-/lib/modules}"; } @@ -125,18 +126,25 @@ apt_get() { # configured, and apt then refuses everything until "dpkg --configure -a". # Finish it first, the way apt asks for, and reinstall a package dpkg marks # as needing it. Says so on fd 3; a failure is reported by the apt-get that -# follows. +# follows. apt's repairs are simulated first: one that would remove a +# package (apt -f may resolve a half-configured driver by removing it and +# what depends on it) is not run; the run stops and says what it would remove. finish_interrupted_dpkg() { - local pending="" reinst + local pending="" reinst removals [[ -n "$(ls -A "$(dpkg_admin_dir)/updates" 2>/dev/null)" ]] && pending=1 [[ -n "$(dpkg --audit 2>/dev/null)" ]] && pending=1 [[ -n "$pending" ]] || return 0 log >&3 "A package operation was interrupted earlier (a crash or a power cut during an update?). Finishing it first…" DEBIAN_FRONTEND=noninteractive dpkg --configure -a >"$LOGFILE" 2>&1 \ || log >&3 "dpkg --configure -a reported errors — repairing with apt" + removals="$(apt_removals install -f)" + [[ -z "$removals" ]] || refuse_removals "$removals" "apt-get install -f" DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=300 install -f -y >"$LOGFILE" 2>&1 || true reinst="$(dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 2>/dev/null | awk 'substr($1,3,1) == "R" {print $2}')" if [[ -n "$reinst" ]]; then + # shellcheck disable=SC2086 + removals="$(apt_removals install --reinstall $reinst)" + [[ -z "$removals" ]] || refuse_removals "$removals" "apt-get install --reinstall ${reinst//$'\n'/ }" log >&3 "Reinstalling packages the interruption left broken: ${reinst//$'\n'/ }" # shellcheck disable=SC2086 DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=300 install --reinstall -y $reinst >"$LOGFILE" 2>&1 || true @@ -149,6 +157,19 @@ finish_interrupted_dpkg() { return 0 } +# The packages an apt-get run would remove or purge, one per line, from its +# simulation ("Remv [...]", "Purg [...]"). +apt_removals() { + apt-get -s "$@" /dev/null | sed -nE 's/^(Remv|Purg) ([^ ]+).*/\2/p' || true +} + +# Stop instead of letting apt remove packages nobody asked to remove. Says +# so on fd 3, the script's own output. +refuse_removals() { + local removals="$1" cmd="$2" + die >&3 "The package system needs a repair ($cmd), and that repair would remove: ${removals//$'\n'/ }. Kernel Pop does not remove packages unasked, so it stopped here. Run 'sudo $cmd' in a terminal, check what it removes, then try again." +} + # dpkg has no lock timeout: retry while another program holds the lock. # A run that could not take the lock changed nothing, so retrying is safe. dpkg_install() { @@ -247,11 +268,43 @@ grub_entry_path_for_kver() { return 1 } -# The systemd-boot loader entry file for under , or nothing. -# kernel-install writes "version " into each entry; the file name -# (-.conf, "+N-M" when boot counting is on) is the fallback -# for entries without that line. +# The XBOOTLDR partition's mount point (/boot as its own partition, next to +# the ESP), or nothing when there is none: kernel-install then writes the +# entries and kernels there instead of to the ESP. +xbootldr_dir() { + local esp="$1" x + if [[ -v KERNEL_POP_XBOOTLDR ]]; then + x="$KERNEL_POP_XBOOTLDR" + else + x="$(bootctl --print-boot-path 2>/dev/null)" || x="" + fi + [[ -n "$x" && "$x" != "$esp" && -d "$x" ]] && echo "$x" + return 0 +} + +# The partitions systemd-boot reads entries from: the ESP, then XBOOTLDR. +sdboot_roots() { + echo "$1" + xbootldr_dir "$1" +} + +# The partition an entry file lives on: the paths in it are relative to that. +sdboot_entry_root() { echo "${1%/loader/entries/*}"; } + +# The systemd-boot loader entry file for on (or the XBOOTLDR +# partition), or nothing. kernel-install writes "version " into each +# entry; the file name (-.conf, "+N-M" when boot counting +# is on) is the fallback for entries without that line. sdboot_entry_for_kver() { + local esp="$1" kver="$2" part + while IFS= read -r part; do + sdboot_entry_on "$part" "$kver" && return 0 + done < <(sdboot_roots "$esp") + return 0 +} + +# The same on one partition; non-zero when it has no entry for . +sdboot_entry_on() { local esp="$1" kver="$2" f line for f in "$esp"/loader/entries/*.conf; do [[ -f "$f" ]] || continue @@ -270,7 +323,18 @@ sdboot_entry_for_kver() { return 0 fi done - return 0 + return 1 +} + +# Every file an entry names ("linux" and "initrd" lines) exists on its +# partition. Lists the missing ones; non-zero when one is missing. +sdboot_entry_files_present() { + local entry="$1" root p rc=0 + root="$(sdboot_entry_root "$entry")" + while IFS= read -r p; do + [[ -f "$root/${p#/}" ]] || { echo "$root/${p#/}"; rc=1; } + done < <(sed -nE 's/^(linux|initrd)[[:space:]]+(.*[^[:space:]])[[:space:]]*$/\2/p' "$entry") + return "$rc" } # kernel-install writes the initramfs under two names in a kernel's ESP @@ -280,13 +344,14 @@ sdboot_entry_for_kver() { # 220 MB copies per kernel filled a 1 GB ESP). Remove initramfs files in # that directory the entry does not name. Quiet; best effort. prune_esp_initrds() { - local esp="$1" kver="$2" entry dir used=() f name keep + local esp="$1" kver="$2" entry root dir used=() f name keep entry="$(sdboot_entry_for_kver "$esp" "$kver")" [[ -n "$entry" && -f "$entry" ]] || return 0 + root="$(sdboot_entry_root "$entry")" dir="$(sed -nE 's/^linux[[:space:]]+(.*[^[:space:]])[[:space:]]*$/\1/p' "$entry" | head -1)" [[ -n "$dir" ]] || return 0 - dir="$esp$(dirname "$dir")" - [[ -d "$dir" && "$dir" != "$esp" && "$dir" != "$esp/" ]] || return 0 + dir="$root$(dirname "/${dir#/}")" + [[ -d "$dir" && "$dir" != "$root" && "$dir" != "$root/" ]] || return 0 while IFS= read -r f; do used+=("$(basename "$f")"); done \ < <(sed -nE 's/^initrd[[:space:]]+(.*[^[:space:]])[[:space:]]*$/\1/p' "$entry") (( ${#used[@]} > 0 )) || return 0 @@ -341,7 +406,7 @@ esp_image_for_kver() { entry="$(sdboot_entry_for_kver "$esp" "$kver")" if [[ -n "$entry" ]]; then rel="$(sed -n 's/^linux[[:space:]]\{1,\}//p' "$entry" | head -1)" - if [[ -n "$rel" ]]; then echo "$esp/${rel#/}"; fi + if [[ -n "$rel" ]]; then echo "$(sdboot_entry_root "$entry")/${rel#/}"; fi fi ;; kernelstub) @@ -368,7 +433,7 @@ set_boot_once() { ;; systemd-boot) entry="$(sdboot_entry_for_kver "$esp" "$kver")" - [[ -n "$entry" ]] || { log "No systemd-boot entry found for $kver in $esp/loader/entries"; return 1; } + [[ -n "$entry" ]] || { log "No systemd-boot entry found for $kver in $esp/loader/entries (or on the XBOOTLDR partition)"; return 1; } id="$(sdboot_entry_id "$entry")" bootctl set-oneshot "$id" >>"$LOGFILE" 2>&1 \ || { log "bootctl set-oneshot failed for $id"; return 1; } @@ -760,6 +825,21 @@ sync_signed_to_esp() { return 0 } +# Whether the copy the boot loader loads for from the ESP carries the +# Kernel Pop signature; true where the boot loader keeps no copy (GRUB, or a +# kernel kernelstub does not keep). Quiet. +esp_copy_signed() { + local kver="$1" bl esp img + read -r bl esp <<< "$(detect_bootloader)" + case "$bl" in + systemd-boot) ;; + kernelstub) [[ -n "$(kernelstub_slot_for_kver "$kver")" ]] || return 0 ;; + *) return 0 ;; + esac + img="$(esp_image_for_kver "$bl" "$esp" "$kver")" + [[ -n "$img" && -f "$img" ]] && sbverify --cert "$(mok_dir)/signing.pem" "$img" >/dev/null 2>&1 +} + # Secure Boot is on and shim enforces it. mokutil sees shim's validation # switch; the raw EFI variable is the fallback. secure_boot_enforcing() { @@ -837,17 +917,95 @@ trial_sign_image() { log "Checked: the kernel image of $kver can be signed" } -# Undo a just-finished dpkg install: purge exactly the packages of the -# staged .debs. Used when Secure Boot is enforcing and signing failed, so no -# kernel that shim would refuse stays installed (their postrm hooks take the -# kernel out of the boot menu again). -rollback_install() { - local dir="$1" d pkgs=() +# A kernel version that is installed already (a rebuild, maybe of the +# running kernel) is never purged by a rollback: that would take the working +# kernel with it. Before dpkg replaces it, its kernel, System.map, config and +# modules are kept: hard links (dpkg writes new files and renames them over +# the old names, so the links keep the old contents), copies where /boot +# cannot hold links. A rollback moves them back and generates the initramfs +# again from the old modules (dracut rewrites an initramfs in place, so a +# link would not keep it). +KEEP_BOOT="" KEEP_MODS="" +keep_installed_kernel() { + local kver="$1" boot mods f + boot="$(boot_dir)" + mods="$(modules_dir)" + KEEP_BOOT="$boot/.kernel-pop-keep-$kver" + KEEP_MODS="$mods/.kernel-pop-keep-$kver" + rm -rf "$KEEP_BOOT" "$KEEP_MODS" + mkdir -m 0700 "$KEEP_BOOT" || return 1 + for f in vmlinuz System.map config; do + [[ -e "$boot/$f-$kver" ]] || continue + ln "$boot/$f-$kver" "$KEEP_BOOT/" 2>/dev/null || cp -p "$boot/$f-$kver" "$KEEP_BOOT/" || return 1 + done + if [[ -d "$mods/$kver" ]]; then + cp -al "$mods/$kver" "$KEEP_MODS" 2>/dev/null || { rm -rf "$KEEP_MODS"; cp -a "$mods/$kver" "$KEEP_MODS"; } || return 1 + fi +} + +drop_kept_kernel() { + [[ -n "$KEEP_BOOT" ]] && rm -rf "$KEEP_BOOT" + [[ -n "$KEEP_MODS" ]] && rm -rf "$KEEP_MODS" + return 0 +} + +# Put the kept files of back and bring the boot loader's copy in line +# with them. Non-zero when something could not be put back. +restore_kept_kernel() { + local kver="$1" boot mods f + boot="$(boot_dir)" + mods="$(modules_dir)" + [[ -d "$KEEP_BOOT" ]] || return 1 + for f in "$KEEP_BOOT"/*; do + [[ -e "$f" ]] || continue + # Still the same file: nothing replaced it. + if [[ "$f" -ef "$boot/${f##*/}" ]]; then rm -f "$f"; continue; fi + mv -f "$f" "$boot/" || return 1 + done + if [[ -d "$KEEP_MODS" ]]; then + rm -rf "${mods:?}/${kver:?}" && mv -T "$KEEP_MODS" "$mods/$kver" || return 1 + fi + rmdir "$KEEP_BOOT" 2>/dev/null || true + KEEP_BOOT="" KEEP_MODS="" + generate_initramfs "$kver" && [[ -f "$boot/initrd.img-$kver" ]] || return 1 + if signing_key_present && kernel_signed "$kver"; then + write_signed_marker "$kver" || true + sync_signed_to_esp "$kver" || return 1 + else + remove_signed_marker "$kver" + refresh_esp_copy "$kver" || return 1 + fi + log "Put back the $kver installed before: its kernel, initramfs and modules" +} + +# Undo a just-finished dpkg install with Secure Boot enforcing, where the new +# kernel could not boot (signing failed, or its ESP copy is unsigned), then +# stop with . A version installed before is put back from the kept +# files; a new one is purged and its boot menu entry removed (no postrm hook +# removes a systemd-boot entry). +rollback_and_die() { + local dir="$1" kver="$2" why="$3" d pkgs=() + if [[ -n "$KEEP_BOOT" ]]; then + if restore_kept_kernel "$kver"; then + die "$why With Secure Boot enforcing the new build could not boot, so the $kver installed before was put back as it was (kernel, initramfs and modules; the headers are the new build's). Try again, or check the signing setup on the System tab." + fi + die "$why The $kver installed before could not be put back completely, so it may NOT boot while Secure Boot is enforcing. Boot another kernel and install $kver again." + fi + if [[ "$kver" == "$(uname -r)" ]]; then + die "$why $kver is the running kernel, so it was not removed — it will NOT boot again while Secure Boot is enforcing. Install a kernel that boots before rebooting." + fi for d in "$dir"/*.deb; do pkgs+=("$(dpkg-deb -f "$d" Package)") done log "Removing the just-installed packages again: ${pkgs[*]}" - apt_get purge -y "${pkgs[@]}" >>"$LOGFILE" 2>&1 + if ! apt_get purge -y "${pkgs[@]}" >>"$LOGFILE" 2>&1; then + die "$why $kver could not be removed again — it will NOT boot while Secure Boot is enforcing. Remove it on the System tab before rebooting." + fi + remove_signed_marker "$kver" + if ! remove_boot_entry "$kver"; then + die "$why With Secure Boot enforcing it could not boot, so it was removed again, but its boot menu entry may still be there: choose another kernel in the boot menu." + fi + die "$why With Secure Boot enforcing it could not boot, so it was removed again. Nothing is left installed." } # The kernel in /boot is signed but the copy the boot loader loads from the @@ -856,10 +1014,7 @@ rollback_install() { esp_copy_unsigned() { local dir="$1" kver="$2" if secure_boot_enforcing; then - if rollback_install "$dir"; then - die "$kver was signed, but the copy on the ESP the boot loader starts is not (see the SIGN WARNING above). With Secure Boot enforcing it could not boot, so it was removed again. Nothing is left installed." - fi - die "$kver's ESP copy is not signed and it could not be removed again — it will NOT boot while Secure Boot is enforcing. Remove it on the System tab before rebooting." + rollback_and_die "$dir" "$kver" "$kver was signed, but the copy on the ESP the boot loader starts is not (see the SIGN WARNING above)." fi SIGN_FAILED=$((SIGN_FAILED + 1)) log "$kver is installed, but its ESP copy is not signed: it boots only while Secure Boot is off" @@ -1023,6 +1178,13 @@ stage_verified_debs() { STAGE_DIR="" +# The ESP still holds the initramfs the package hook copied, from before the +# DKMS build: it boots, but out-of-tree modules may be missing from it. +esp_initrd_stale() { + DKMS_FAILED=$((DKMS_FAILED + 1)) + log "DKMS WARNING: the ESP copy of $1 could not be refreshed (see above), so it boots with the initramfs from before the DKMS build — out-of-tree modules may be missing early in the boot. Free space on the ESP, then reinstall $1." +} + do_install() { local src="$1" boot mods boot="$(boot_dir)" @@ -1035,7 +1197,7 @@ do_install() { # Everything below works on the private, verified copy only. STAGE_DIR="$(umask 077 && mktemp -d "${KERNEL_POP_STAGING:-/var/tmp}/kernel-pop-install.XXXXXX")" \ || die "Could not create a private staging directory" - trap 'rm -rf "$STAGE_DIR"' EXIT + trap 'rm -rf "$STAGE_DIR"; drop_kept_kernel' EXIT stage_verified_debs "$src" "$STAGE_DIR" local dir="$STAGE_DIR" @@ -1065,9 +1227,11 @@ do_install() { # version by then (a rebuild, maybe of the running kernel). So the image # is signed once here first, on a copy in the private staging dir: a # failure stops before anything is installed. - local existed=0 image_deb="" + local existed=0 image_deb="" own_pkgs=() dpkg-query -W -f '${Status}' "linux-image-$kver" 2>/dev/null | grep -q 'install ok installed' && existed=1 + [[ -e "$boot/vmlinuz-$kver" || -d "$mods/$kver" ]] && existed=1 for d in "${debs[@]}"; do + own_pkgs+=("$(dpkg-deb -f "$d" Package)") [[ "$(dpkg-deb -f "$d" Package)" == "linux-image-$kver" ]] && image_deb="$d" done if secure_boot_enforcing && signing_key_present; then @@ -1075,29 +1239,49 @@ do_install() { || die "Linux $kver could not be signed (see the SIGN WARNING above), so it could not boot while Secure Boot is enforcing. Nothing was installed. Check the signing setup on the System tab." fi - # Snapshot the modules directory so the post-install cross-check is honest - local before_modules - before_modules="$(ls -1 "$mods" 2>/dev/null || true)" + # What the steps after dpkg need, checked before it: a failure there + # would leave a kernel without an initramfs or a boot entry as the + # newest, default one. + [[ "$(initramfs_tool)" != none ]] \ + || die "No initramfs tool is installed (initramfs-tools or dracut), so $kver could not get an initramfs and would not boot. Nothing was installed. Install initramfs-tools, then try again." + local bl esp + read -r bl esp <<< "$(detect_bootloader)" + case "$bl" in + systemd-boot) + command -v kernel-install >/dev/null 2>&1 \ + || die "systemd-boot is the boot loader, but kernel-install (systemd) is missing, so $kver would get no boot menu entry. Nothing was installed." ;; + kernelstub) + command -v kernelstub >/dev/null 2>&1 \ + || die "kernelstub is configured, but the kernelstub command is missing, so $kver would not be copied to the ESP. Nothing was installed." ;; + esac + + # A rollback (Secure Boot enforcing, the new build cannot boot) puts an + # installed version back instead of purging it. + if (( existed )) && secure_boot_enforcing; then + keep_installed_kernel "$kver" \ + || die "Could not keep a copy of the $kver installed now (is /boot full?), which a failed signing would need to put it back. Nothing was installed." + fi log "Installing ${#debs[@]} packages…" if ! dpkg_install "${debs[@]}" >>"$LOGFILE" 2>&1; then - log "dpkg -i reported errors — attempting to fix dependencies…" + log "dpkg -i reported errors — checking what fixing the dependencies would do…" + # apt -f may only take back the packages just installed, and only + # when they replaced nothing. + local removals other + removals="$(apt_removals install -f)" + other="$(grep -vxF -f <(printf '%s\n' "${own_pkgs[@]}") <<< "$removals" || true)" + if [[ -n "$other" ]] || { [[ -n "$removals" ]] && (( existed )); }; then + die "dpkg could not install the packages, and fixing the dependencies (apt-get install -f) would remove: ${removals//$'\n'/ }. Kernel Pop does not remove packages unasked, so it stopped here. Run 'sudo apt-get install -f' in a terminal and check what it removes." + fi apt_get install -f -y >>"$LOGFILE" 2>&1 || die "dpkg install failed and apt-get -f could not repair it" fi log "Packages installed" - # Cross-check: the modules directory for $kver must now exist - if [[ ! -d "$mods/$kver" ]]; then - log "WARNING: $mods/$kver not found after install." - local new_dir - new_dir="$(comm -13 <(echo "$before_modules") <(ls -1 "$mods") | head -1 || true)" - if [[ -n "$new_dir" ]] && valid_kver "$new_dir"; then - log "Using newly appeared modules directory instead: $new_dir" - kver="$new_dir" - else - die "No modules directory appeared for the installed kernel — aborting before initramfs" - fi - fi + # Cross-check: the modules directory for $kver must now exist. Never + # another one: signing, the initramfs and the boot default would then + # act on a kernel other than the one packaged. + [[ -d "$mods/$kver" ]] \ + || die "$mods/$kver did NOT appear after install — the kernel package did not install correctly. DO NOT reboot into $kver." # dpkg can fail while apt-get -f finds nothing to fix and still exit 0; # never declare success unless the kernel image itself is on disk. @@ -1113,13 +1297,7 @@ do_install() { if sign_kernel "$kver"; then signed_now=1 elif secure_boot_enforcing; then - if rollback_install "$dir"; then - if (( existed )); then - die "$kver could not be signed (see the SIGN WARNING above), and with Secure Boot enforcing it could not boot, so it was removed again. It had replaced the $kver installed before, which is gone with it. Try again, or check the signing setup on the System tab." - fi - die "$kver could not be signed (see the SIGN WARNING above), and with Secure Boot enforcing it could not boot, so it was removed again. Nothing is left installed. Try again, or check the signing setup on the System tab." - fi - die "$kver could not be signed and could not be removed again — it will NOT boot while Secure Boot is enforcing. Remove it on the System tab before rebooting." + rollback_and_die "$dir" "$kver" "$kver could not be signed (see the SIGN WARNING above)." else SIGN_FAILED=$((SIGN_FAILED + 1)) log "$kver was installed but could not be signed (see the SIGN WARNING above)" @@ -1147,8 +1325,9 @@ do_install() { log "Verified: $boot/initrd.img-$kver exists" # ── Boot loader: verify (systemd-boot) or update (GRUB) ───────────── - local bl esp - read -r bl esp <<< "$(detect_bootloader)" + # The package hooks copied the kernel and the initramfs of that moment to + # the ESP during dpkg, before DKMS and the initramfs above: copy them + # again, signed or not. case "$bl" in kernelstub) # kernelstub's postinst hook (/etc/kernel/postinst.d/zz-kernelstub) @@ -1163,7 +1342,11 @@ do_install() { efi_img="$(esp_image_for_kver kernelstub "$esp" "$kver")" [[ -n "$efi_img" ]] || die "No EFI/Pop_OS-*/$slot under $esp after install — kernelstub did not sync. Try 'kernelstub -p' — DO NOT reboot expecting the new kernel" log "Verified: kernelstub image $efi_img exists" - if (( signed_now )) && ! sync_signed_to_esp "$kver"; then esp_copy_unsigned "$dir" "$kver"; fi + if (( signed_now )); then + sync_signed_to_esp "$kver" || esp_copy_unsigned "$dir" "$kver" + else + refresh_esp_copy "$kver" || esp_initrd_stale "$kver" + fi fi ;; systemd-boot) @@ -1174,10 +1357,20 @@ do_install() { log "systemd-boot detected (ESP: $esp) — verifying boot menu entry…" local entry entry="$(sdboot_entry_for_kver "$esp" "$kver")" - [[ -n "$entry" ]] || die "No systemd-boot entry appeared for $kver in $esp/loader/entries — DO NOT reboot expecting it in the menu" + [[ -n "$entry" ]] || die "No systemd-boot entry appeared for $kver in $esp/loader/entries (or on the XBOOTLDR partition) — DO NOT reboot expecting it in the menu" log "Verified: boot menu entry $entry exists" - if (( signed_now )) && ! sync_signed_to_esp "$kver"; then esp_copy_unsigned "$dir" "$kver"; fi + if (( signed_now )); then + sync_signed_to_esp "$kver" || esp_copy_unsigned "$dir" "$kver" + else + refresh_esp_copy "$kver" || esp_initrd_stale "$kver" + fi prune_esp_initrds "$esp" "$kver" + entry="$(sdboot_entry_for_kver "$esp" "$kver")" + local missing + if [[ -z "$entry" ]] || ! missing="$(sdboot_entry_files_present "$entry")"; then + die "The boot menu entry for $kver names files that are not there: ${missing:-no entry} — DO NOT reboot into $kver" + fi + log "Verified: the kernel and initramfs ${entry##*/} names are on the boot partition" ;; grub) log "Updating GRUB…" @@ -1231,6 +1424,7 @@ do_install() { if (( SIGN_FAILED > 0 )); then log "SIGN SUMMARY: $kver is installed but unsigned. Secure Boot is not enforcing now, so it boots; sign it before turning Secure Boot on." fi + drop_kept_kernel if (( SB_PENDING )); then log "BOOT PENDING: $kver is signed, but the signing key is still waiting for enrollment. On the next reboot the blue MOK Manager screen appears: choose Enroll MOK, Continue, Yes, then type your password. Skip it and $kver will not boot while Secure Boot is enforcing." log "==== Done. Kernel $kver installed with initramfs verified. Confirm the key enrollment at the next reboot. ====" @@ -1268,6 +1462,51 @@ packages_for_kver() { done < <(dpkg-query -W -f '${db:Status-Abbrev} ${Package}\n' 'linux-*' 2>/dev/null || true) } +# Take a removed kernel out of the boot menu. dpkg has no postrm hook that +# removes a systemd-boot entry (only zz-update-grub exists by default): +# without this, every removed kernel on a systemd-boot machine leaves a +# dangling, unbootable menu entry behind, and a rolled-back newest kernel +# would stay the default. Returns 1 when an entry may be left, 2 when +# update-grub failed. +remove_boot_entry() { + local kver="$1" bl esp part rc=0 + read -r bl esp <<< "$(detect_bootloader)" + case "$bl" in + kernelstub) + # The kernelstub postrm hook (/etc/kernel/postrm.d/zz-kernelstub) + # resyncs the ESP when the packages are purged; kernel-install + # remove does nothing useful here. + log "kernelstub (Pop!_OS) detected — ESP entries are resynced by its postrm hook, not per-version" + ;; + systemd-boot) + log "systemd-boot detected (ESP: $esp) — removing boot menu entry for $kver…" + if command -v kernel-install >/dev/null 2>&1; then + kernel-install remove "$kver" >>"$LOGFILE" 2>&1 \ + || log "WARNING: kernel-install remove failed for $kver" + else + while IFS= read -r part; do + rm -f "$part/loader/entries/"*"-${kver}.conf" "$part/loader/entries/"*"-${kver}+"*.conf + if [[ -r /etc/machine-id ]]; then + rm -rf "${part:?}/$(cat /etc/machine-id)/${kver:?}" + fi + done < <(sdboot_roots "$esp") + fi + if [[ -n "$(sdboot_entry_for_kver "$esp" "$kver")" ]]; then + log "WARNING: the boot menu entry for $kver is still there: $(sdboot_entry_for_kver "$esp" "$kver")" + rc=1 + fi + ;; + grub) + log "Updating GRUB…" + update-grub >>"$LOGFILE" 2>&1 || { log "update-grub failed"; rc=2; } + ;; + *) + log "WARNING: could not detect a supported boot loader (GRUB or systemd-boot). Kernel $kver's files were removed, but its boot menu entry (if any) may still be present — check your boot menu by hand." + ;; + esac + return "$rc" +} + do_remove() { local kver="$1" boot mods boot="$(boot_dir)" @@ -1291,10 +1530,11 @@ do_remove() { # linux-image-generic metapackages (they depend on that exact # version), after which no future kernel update would ever install. # Simulate first and refuse rather than silently break updates. - local sim meta + # apt's simulation says "Purg" for a package a purge takes with it, + # "Remv" for a plain removal. + local meta # shellcheck disable=SC2086 - sim="$(apt-get -s purge $pkgs 2>/dev/null || true)" - meta="$(printf '%s\n' "$sim" | grep '^Remv ' | cut -d' ' -f2 \ + meta="$(apt_removals purge $pkgs \ | grep -E '^linux-(image-|headers-)?(generic|lowlatency|virtual|oem|kvm)(-[a-z0-9.-]+)?$' || true)" if [[ -n "$meta" ]]; then die "Removing $kver would also remove kernel metapackage(s): ${meta//$'\n'/ } — that would stop future kernel updates from installing. Install a newer stock kernel first, or remove manually with 'apt-mark hold' on them." @@ -1311,40 +1551,9 @@ do_remove() { rm -rf "${mods:?}/${kver:?}" fi - # ── Boot loader: clean up (systemd-boot) or update (GRUB) ─────────── - # dpkg has no postrm hook that removes a systemd-boot entry (only - # zz-update-grub exists by default) — without this, every removed - # kernel on a systemd-boot machine leaves a permanently dangling, - # unbootable menu entry behind. - local bl esp - read -r bl esp <<< "$(detect_bootloader)" - case "$bl" in - kernelstub) - # The kernelstub postrm hook (/etc/kernel/postrm.d/zz-kernelstub) - # resyncs the ESP when the packages are purged; kernel-install - # remove does nothing useful here. - log "kernelstub (Pop!_OS) detected — ESP entries are resynced by its postrm hook, not per-version" - ;; - systemd-boot) - log "systemd-boot detected (ESP: $esp) — removing boot menu entry for $kver…" - if command -v kernel-install >/dev/null 2>&1; then - kernel-install remove "$kver" >>"$LOGFILE" 2>&1 \ - || log "WARNING: kernel-install remove failed for $kver — its boot menu entry may be orphaned in $esp/loader/entries" - else - rm -f "$esp/loader/entries/"*"-${kver}.conf" - if [[ -r /etc/machine-id ]]; then - rm -rf "${esp:?}/$(cat /etc/machine-id)/${kver:?}" - fi - fi - ;; - grub) - log "Updating GRUB…" - update-grub >>"$LOGFILE" 2>&1 || die "update-grub failed" - ;; - *) - log "WARNING: could not detect a supported boot loader (GRUB or systemd-boot). Kernel $kver's files were removed, but its boot menu entry (if any) may still be present — check your boot menu by hand." - ;; - esac + local rc=0 + remove_boot_entry "$kver" || rc=$? + (( rc != 2 )) || die "update-grub failed" remove_signed_marker "$kver" log "==== Done. Kernel $kver removed. ====" @@ -1501,8 +1710,9 @@ sign_boot_loader() { fi fi bootctl update --graceful --no-variables >>"$LOGFILE" 2>&1 || true - # bootctl skips a copy of the same version, so check the one on the ESP. - if ! sbverify --cert "$d/signing.pem" "$esp/EFI/systemd/systemd-bootx64.efi" >/dev/null 2>&1; then + # bootctl skips a copy of the same version (and an older copy signed + # with the same key would verify too), so compare the ESP's with it. + if ! cmp -s "$src.signed" "$esp/EFI/systemd/systemd-bootx64.efi"; then esp_install "$src.signed" "$esp/EFI/systemd/systemd-bootx64.efi" || return 1 log "Installed the signed systemd-boot on the ESP" fi @@ -1591,6 +1801,21 @@ install_shim_packages() { done } +# Whether /EFI/BOOT/BOOTX64.EFI may be replaced with shim: it is missing, +# shim-signed's shim, this system's shim on the ESP (EFI/, asked +# before it is updated), or systemd-boot (bootctl installs it there). +fallback_is_ours() { + local esp="$1" vendor="$2" cur f + cur="$esp/EFI/BOOT/BOOTX64.EFI" + [[ -e "$cur" ]] || return 0 + for f in "$(shim_lib_dir)/shimx64.efi.signed" "$esp/EFI/$vendor/shimx64.efi" "$esp/EFI/systemd/systemd-bootx64.efi" \ + "$(sdboot_efi)" "$(sdboot_efi).signed"; do + [[ -s "$f" ]] && cmp -s "$f" "$cur" && return 0 + done + # A systemd-boot of another version names itself in its binary. + grep -aq 'systemd-boot' "$cur" 2>/dev/null && ! grep -aq 'Windows Boot Manager' "$cur" 2>/dev/null +} + # The ESP and firmware side, after install_shim_packages and after the key # is queued for enrollment: systemd-boot signed, shim's files, the firmware # entry. Returns non-zero when the machine still has no shim entry. @@ -1600,6 +1825,9 @@ setup_shim_chain() { vendor="$(esp_vendor)" V="${vendor^}" [[ -f "$lib/shimx64.efi.signed" ]] || { log "SIGN WARNING: shim-signed is not installed"; return 1; } + # Decided before anything on the ESP changes (see below). + local fallback_ours=0 + fallback_is_ours "$esp" "$vendor" && fallback_ours=1 restore_distribution_sdboot sign_boot_loader || return 1 # Every copy must be in place before a firmware entry points at it or the @@ -1610,16 +1838,28 @@ setup_shim_chain() { done # The fallback path: shim there, and fbx64 recreates the firmware entry # from the CSV after a firmware reset. GRUB's CSV passes nothing, which - # would point shim at GRUB. - esp_install "$lib/shimx64.efi.signed" "$esp/EFI/BOOT/BOOTX64.EFI" || return 1 - if [[ -f "$lib/fbx64.efi.signed" ]]; then - esp_install "$lib/fbx64.efi.signed" "$esp/EFI/BOOT/fbx64.efi" || return 1 + # would point shim at GRUB. Only over a fallback loader that is this + # system's (shim, or systemd-boot as bootctl puts it there) or none: on + # an ESP shared with Windows or another distribution the one there is + # theirs, and the firmware entry made below is what starts this system. + if (( fallback_ours )); then + esp_install "$lib/shimx64.efi.signed" "$esp/EFI/BOOT/BOOTX64.EFI" || return 1 + if [[ -f "$lib/fbx64.efi.signed" ]]; then + esp_install "$lib/fbx64.efi.signed" "$esp/EFI/BOOT/fbx64.efi" || return 1 + fi + else + log "Left $esp/EFI/BOOT/BOOTX64.EFI alone: it is another system's boot loader (Windows or another distribution), not shim or systemd-boot. This system starts from its own firmware entry." fi csv="$esp/EFI/$vendor/BOOTX64.CSV" if ! iconv -f UCS-2LE -t UTF-8 "$csv" 2>/dev/null | grep -q 'systemd-bootx64\.efi'; then - printf 'shimx64.efi,%s,\\EFI\\systemd\\systemd-bootx64.efi \\0,This is the boot entry for %s\n' "$V" "$V" \ - | iconv -t UCS-2LE > "$csv" \ - || { log "SIGN WARNING: could not write $csv"; return 1; } + # Written next to it and renamed over it: a full ESP never leaves a + # truncated CSV behind. + if ! { printf 'shimx64.efi,%s,\\EFI\\systemd\\systemd-bootx64.efi \\0,This is the boot entry for %s\n' "$V" "$V" \ + | iconv -t UCS-2LE > "$csv.kernel-pop-new" && mv -f "$csv.kernel-pop-new" "$csv"; }; then + rm -f "$csv.kernel-pop-new" + log "SIGN WARNING: could not write $csv" + return 1 + fi fi if [[ -z "$(shim_sdboot_entries)" ]]; then src="$(findmnt -nvo SOURCE "$esp" 2>/dev/null)" @@ -1646,7 +1886,7 @@ setup_shim_chain() { # key is rebuilt: one built before the key existed (installing shim-signed # creates it too), or signed with an older key under the same name. setup_dkms_key() { - local der ids line m v k + local der ids line m v k mv_ fields=() local -A rebuilt=() der="$(dkms_mok_der)" command -v dkms >/dev/null 2>&1 || return 0 @@ -1660,10 +1900,14 @@ setup_dkms_key() { fi ids="$(cert_key_ids "$der")" while IFS= read -r line; do - # "name/version, kernel, arch: installed" - [[ "$line" =~ ^([^/,]+)/([^,]+),[[:space:]]*([^,]+),[[:space:]]*[^:]+:[[:space:]]*installed ]] || continue - m="${BASH_REMATCH[1]}" v="${BASH_REMATCH[2]}" k="${BASH_REMATCH[3]}" - valid_kver "$k" || continue + # "name/version, kernel, arch: installed" (dkms 3) or + # "name, version, kernel, arch: installed" (dkms 2) + [[ "$(dkms_line_state "$line")" == installed ]] || continue + mv_="$(dkms_line_module "$line")" + m="${mv_%%/*}" v="${mv_#*/}" + IFS=', ' read -ra fields <<< "${line%%:*}" + if [[ "${fields[0]}" == */* ]]; then k="${fields[1]:-}"; else k="${fields[2]:-}"; fi + [[ -n "$m" && -n "$v" && "$v" != "?" ]] && valid_kver "$k" || continue dkms_package_signed "$m" "$v" "$k" "$ids" && continue log "Rebuilding $m $v for $k, signed with the DKMS key…" # install --force alone puts the stored build back unchanged; the @@ -1683,7 +1927,7 @@ setup_dkms_key() { [[ -f "$(boot_dir)/initrd.img-$k" ]] || continue log "Generating the initramfs for $k again, with the signed modules…" if generate_initramfs "$k"; then - refresh_esp_copy "$k" + refresh_esp_copy "$k" || log "SIGN WARNING: the ESP copy of $k's initramfs could not be refreshed — it may still hold unsigned modules" else log "SIGN WARNING: the initramfs for $k could not be generated again — it may still hold unsigned modules" fi @@ -1693,6 +1937,7 @@ setup_dkms_key() { # Copy /boot's kernel and initramfs for to the ESP again where the # boot loader loads them from there (systemd-boot, kernelstub). GRUB reads # /boot itself. +# Non-zero (with a log line) when the copy could not be refreshed. refresh_esp_copy() { local kver="$1" bl esp boot initrd=() boot="$(boot_dir)" @@ -1703,11 +1948,13 @@ refresh_esp_copy() { if kernel-install add "$kver" "$boot/vmlinuz-$kver" "${initrd[@]}" >>"$LOGFILE" 2>&1; then prune_esp_initrds "$esp" "$kver" else - log "SIGN WARNING: kernel-install add failed for $kver — the ESP copy of its initramfs is the old one" + log "kernel-install add failed for $kver — the ESP copy of its kernel and initramfs is the old one" + return 1 fi ;; kernelstub) - kernelstub >>"$LOGFILE" 2>&1 || log "SIGN WARNING: kernelstub failed — the ESP copy of $kver may be the old one" + [[ -n "$(kernelstub_slot_for_kver "$kver")" ]] || return 0 + kernelstub >>"$LOGFILE" 2>&1 || { log "kernelstub failed — the ESP copy of $kver may be the old one"; return 1; } ;; esac return 0 @@ -1726,8 +1973,12 @@ cert_key_ids() { # Whether every module DKMS package / installed for is signed # with one of (cert_key_ids). Its dkms.conf names the modules. dkms_package_signed() { - local m="$1" v="$2" k="$3" ids="$4" conf name f id found=0 + local m="$1" v="$2" k="$3" ids="$4" conf name f id found=0 names conf="${KERNEL_POP_DKMS_TREE:-/var/lib/dkms}/$m/$v/source/dkms.conf" + # Quoted either way, or not at all; without any BUILT_MODULE_NAME, DKMS + # builds one module named after the package. + names="$(sed -nE "s/^[[:space:]]*BUILT_MODULE_NAME\[[0-9]+\]=[\"']?([^\"'[:space:]]+)[\"']?.*/\1/p" "$conf" 2>/dev/null)" + [[ -n "$names" ]] || names="$m" while IFS= read -r name; do # dkms.conf is shell: BUILT_MODULE_NAME[0]="$PACKAGE_NAME" names the package's own module. name="${name//'${PACKAGE_NAME}'/$m}" @@ -1738,7 +1989,7 @@ dkms_package_signed() { id="$(modinfo -F sig_key "$f" 2>/dev/null | tr -d ': ' | tr 'a-f' 'A-F' | sed 's/^0*//')" [[ -n "$id" ]] && grep -qxF "$id" <<< "$ids" || return 1 done - done < <(sed -nE 's/^[[:space:]]*BUILT_MODULE_NAME\[[0-9]+\]="?([^"[:space:]]+)"?.*/\1/p' "$conf" 2>/dev/null) + done <<< "$names" (( found )) } @@ -1859,6 +2110,7 @@ pending_mok_certs() { my ($file, $dir) = @ARGV; open(my $fh, "<:raw", $file) or exit 2; local $/; my $raw = <$fh>; close $fh; + exit 2 if length($raw) < 4; my $data = substr($raw, 4); # efivarfs: 4 attribute bytes first my $x509 = pack("H*", "a159c0a5e494a74a87b5ab155c2bf072"); my ($off, $n, $other) = (0, 0, 0); @@ -2021,6 +2273,8 @@ do_setup_signing() { if kernel_signed "$v"; then write_signed_marker "$v" || log "SIGN WARNING: could not write the signed marker for $v" log "Already signed: $v" + # A copy to the ESP that failed in an earlier run is made now. + esp_copy_signed "$v" || sync_signed_to_esp "$v" || true already=$((already + 1)) elif sign_kernel "$v"; then sync_signed_to_esp "$v" || true diff --git a/scripts/tests/test-privileged.sh b/scripts/tests/test-privileged.sh index f3d64a7..766e5d3 100755 --- a/scripts/tests/test-privileged.sh +++ b/scripts/tests/test-privileged.sh @@ -48,6 +48,8 @@ export KERNEL_POP_APT_HOOK="$tmp/hooks/apt-hook" KERNEL_POP_KERNEL_HOOK="$tmp/ho KERNEL_POP_SDBOOT="$tmp/sdboot/systemd-bootx64.efi" KERNEL_POP_SDBOOT_STAMP="$tmp/sdboot/stamp" \ KERNEL_POP_SHIM_LIB="$tmp/shim-lib" KERNEL_POP_OS_RELEASE="$tmp/os-release" printf 'ID=ubuntu\n' > "$tmp/os-release" +# No XBOOTLDR partition unless a test sets one: bootctl is never asked. +export KERNEL_POP_XBOOTLDR="" deb_allowed "$tmp/linux-image-7.2.12-kernelpop_7.2.12-1_amd64.deb" || bad "deb_allowed image" deb_allowed "$tmp/linux-headers-7.2.12-kernelpop_7.2.12-1_amd64.deb" || bad "deb_allowed headers" @@ -237,6 +239,24 @@ got="$(sdboot_entry_for_kver "$tmp/sd" 6.8.0-45-generic)" got="$(esp_image_for_kver systemd-boot "$tmp/sd" 7.1.3-070103-generic)" [[ "$got" == "$tmp/sd/mid/7.1.3-070103-generic/linux" ]] || bad "esp_image_for_kver systemd-boot got [$got]" [[ -z "$(esp_image_for_kver grub "$tmp/sd" 7.1.3-070103-generic)" ]] || bad "esp_image_for_kver grub should be empty" +# An XBOOTLDR /boot: kernel-install writes the entry and the kernel there +mkdir -p "$tmp/xbl/loader/entries" "$tmp/xbl/mid/7.4.1-kernelpop" +printf 'title Ubuntu\nversion 7.4.1-kernelpop\nlinux /mid/7.4.1-kernelpop/linux\ninitrd /mid/7.4.1-kernelpop/initrd.img-7.4.1-kernelpop\n' > "$tmp/xbl/loader/entries/mid-7.4.1-kernelpop.conf" +touch "$tmp/xbl/mid/7.4.1-kernelpop/linux" "$tmp/xbl/mid/7.4.1-kernelpop/initrd" +[[ -z "$(sdboot_entry_for_kver "$tmp/sd" 7.4.1-kernelpop)" ]] || bad "an XBOOTLDR entry was found without XBOOTLDR" +got="$(KERNEL_POP_XBOOTLDR="$tmp/xbl" sdboot_entry_for_kver "$tmp/sd" 7.4.1-kernelpop)" +[[ "$got" == "$tmp/xbl/loader/entries/mid-7.4.1-kernelpop.conf" ]] || bad "sdboot_entry_for_kver on XBOOTLDR got [$got]" +got="$(KERNEL_POP_XBOOTLDR="$tmp/xbl" esp_image_for_kver systemd-boot "$tmp/sd" 7.4.1-kernelpop)" +[[ "$got" == "$tmp/xbl/mid/7.4.1-kernelpop/linux" ]] || bad "esp_image_for_kver on XBOOTLDR got [$got]" +got="$(KERNEL_POP_XBOOTLDR="$tmp/xbl" sdboot_entry_for_kver "$tmp/sd" 7.1.3-070103-generic)" +[[ "$got" == "$tmp/sd/loader/entries/mid-7.1.3-070103-generic.conf" ]] || bad "the ESP's entries come first, got [$got]" +got="$(sdboot_entry_files_present "$tmp/xbl/loader/entries/mid-7.4.1-kernelpop.conf")" && bad "a missing initrd was not noticed" +[[ "$got" == "$tmp/xbl/mid/7.4.1-kernelpop/initrd.img-7.4.1-kernelpop" ]] || bad "sdboot_entry_files_present listed [$got]" +touch "$tmp/xbl/mid/7.4.1-kernelpop/initrd.img-7.4.1-kernelpop" +sdboot_entry_files_present "$tmp/xbl/loader/entries/mid-7.4.1-kernelpop.conf" >/dev/null || bad "an entry with all its files was refused" +KERNEL_POP_XBOOTLDR="$tmp/xbl" prune_esp_initrds "$tmp/sd" 7.4.1-kernelpop >/dev/null +[[ -e "$tmp/xbl/mid/7.4.1-kernelpop/initrd" ]] && bad "prune did not work on the XBOOTLDR partition" +[[ -f "$tmp/xbl/mid/7.4.1-kernelpop/initrd.img-7.4.1-kernelpop" ]] || bad "prune removed the used initrd on XBOOTLDR" mkdir -p "$tmp/ksboot" "$tmp/ksroot" "$tmp/ksesp/EFI/Pop_OS-abcd" touch "$tmp/ksesp/EFI/Pop_OS-abcd/vmlinuz.efi" "$tmp/ksesp/EFI/Pop_OS-abcd/vmlinuz-previous.efi" @@ -732,6 +752,11 @@ else cmp -s "$KERNEL_POP_MOK_PENDING" "$tmp/list-before" || fail "the shared list changed for a malformed request" done + # Shorter than its attribute bytes: damaged, not empty. + printf 'ab' > "$moknew" + rc=0; pending_mok_certs "$tmp/malformed-out" 2>/dev/null || rc=$? + [[ $rc == 2 ]] || fail "a MokNew shorter than 4 bytes should read as damaged, got $rc" + # A waiting certificate openssl can't read: nothing is revoked, the request stays. printf 'not a certificate' > "$tmp/junk.der" : > "$calls"; write_moknew x509 "$tmp/other/c.der" "$tmp/junk.der" @@ -855,12 +880,37 @@ EOF2 KERNEL_POP_SIGNED_DIR="$root/signed" KERNEL_POP_GRUB_CFG="$root/grub.cfg" \ KERNEL_POP_GRUB_DEFAULTS="$root/default-grub" KERNEL_POP_DKMS_TREE="$root/dkms" if [[ -n "${WITH_KEY:-}" ]]; then touch "$root/mok/signing.key" "$root/mok/signing.pem" "$root/mok/signing.der"; fi + # A version installed before: its files, as dpkg will replace them + if [[ -n "${PREEXIST:-}" ]]; then + echo old-image > "$KERNEL_POP_BOOT/vmlinuz-$kv"; echo old-initrd > "$KERNEL_POP_BOOT/initrd.img-$kv" + mkdir -p "$KERNEL_POP_MODULES/$kv/kernel"; echo old > "$KERNEL_POP_MODULES/$kv/kernel/old.ko" + fi + # Like dpkg: new files are written aside and renamed over the old + # names; the systemd-boot hook writes an entry and copies the kernel. dpkg() { + [[ "$1" == -i ]] || return 0 shift; printf '%s\n' "$@" > "$root/dpkg-args" - touch "$KERNEL_POP_BOOT/vmlinuz-$kv"; mkdir -p "$KERNEL_POP_MODULES/$kv/build" + [[ -n "${DPKG_FAIL:-}" ]] && return 1 + echo new-image > "$KERNEL_POP_BOOT/.new" && mv -f "$KERNEL_POP_BOOT/.new" "$KERNEL_POP_BOOT/vmlinuz-$kv" + if [[ -z "${NO_MODULES:-}" ]]; then + rm -rf "${KERNEL_POP_MODULES:?}/$kv"; mkdir -p "$KERNEL_POP_MODULES/$kv/build"; echo new > "$KERNEL_POP_MODULES/$kv/new.ko" + fi + if [[ -n "${SDBOOT:-}" ]]; then + mkdir -p "$root/esp/loader/entries" "$root/esp/mid/$kv" + printf 'title t\nversion %s\nlinux /mid/%s/linux\ninitrd /mid/%s/initrd.img-%s\n' "$kv" "$kv" "$kv" "$kv" > "$root/esp/loader/entries/mid-$kv.conf" + touch "$root/esp/mid/$kv/linux" "$root/esp/mid/$kv/initrd.img-$kv" + fi + return 0 } - apt-get() { echo "$*" >> "$root/apt-args"; [[ "$3" == "purge" ]]; } - update-initramfs() { touch "$KERNEL_POP_BOOT/initrd.img-$3"; } # -c|-u -k + # Simulations (-s) print $APT_SIM and are logged apart + apt-get() { + if [[ "$1" == -s ]]; then echo "$*" >> "$root/apt-sim"; [[ -n "${APT_SIM:-}" ]] && echo "$APT_SIM"; return 0; fi + echo "$*" >> "$root/apt-args"; [[ "$3" == "purge" ]] + } + kernel-install() { echo "$*" >> "$root/ki-args"; [[ "$1" == add && -n "${KI_FAIL:-}" ]] && return 1; [[ "$1" == remove ]] && rm -f "$root/esp/loader/entries/mid-$2.conf"; return 0; } + # -c|-u -k ; written in place, as dracut does; names the modules it saw + update-initramfs() { echo "initrd from $(ls "$KERNEL_POP_MODULES/$3" | tr '\n' ' ')" > "$KERNEL_POP_BOOT/initrd.img-$3"; } + [[ -n "${NO_IRTOOL:-}" ]] && initramfs_tool() { echo none; } if [[ -n "${DKMS_BROKEN:-}" ]]; then dkms() { [[ "$1" == "status" ]] && echo "nvidia/615.78.08, $kv, x86_64: built"; [[ "$1" == "status" ]]; } else @@ -868,7 +918,6 @@ EOF2 fi if [[ -n "${SDBOOT:-}" ]]; then detect_bootloader() { echo "systemd-boot $root/esp"; } - sdboot_entry_for_kver() { echo "$root/esp/loader/entries/$2.conf"; } sync_signed_to_esp() { [[ -z "${ESP_UNSIGNED:-}" ]] || { log "SIGN WARNING: the ESP copy of $1 does not carry the Kernel Pop signature"; return 1; }; } else detect_bootloader() { echo "grub"; } @@ -940,8 +989,21 @@ EOF2 grep -q "removed again. Nothing is left installed" <<< "$out" || bad "the rollback should be reported: $out" [[ "$(cat "$root/saved")" == "gnulinux-advanced-x>gnulinux-$running-advanced-x" ]] || bad "a rolled-back install changed the default" # The same over an installed kernel of that version: the message says that one is gone too + # The same over an installed kernel of that version (maybe the running + # one): never purged; the kernel, initramfs and modules from before are + # put back. out="$(SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled PREEXIST=1 run_install signfail-over)" && bad "do_install should fail when signing fails under Secure Boot" - grep -q "It had replaced the $kv installed before, which is gone with it" <<< "$out" || bad "the rollback over an installed $kv should say it is gone: $out" + root="$tmp/inst-signfail-over" + grep -q "the $kv installed before was put back as it was" <<< "$out" || bad "the rollback over an installed $kv should put it back: $out" + [[ -e "$root/apt-args" ]] && bad "a version installed before was purged: $(cat "$root/apt-args")" + [[ "$(cat "$root/boot/vmlinuz-$kv")" == old-image ]] || bad "the kernel from before was not put back" + [[ -f "$root/modules/$kv/kernel/old.ko" && ! -e "$root/modules/$kv/new.ko" ]] || bad "the modules from before were not put back" + [[ "$(cat "$root/boot/initrd.img-$kv")" == "initrd from kernel " ]] || bad "the initramfs was not made again from the old modules: $(cat "$root/boot/initrd.img-$kv")" + [[ -z "$(compgen -G "$root/boot/.kernel-pop-keep-*")$(compgen -G "$root/modules/.kernel-pop-keep-*")" ]] || bad "the kept copies were left behind" + # Installed over an installed version, all well: the kept copies go + out="$(SB_ON=1 WITH_KEY=1 SIGN_OK=1 KEY_STATE=enrolled PREEXIST=1 run_install over-ok)" || bad "a reinstall under Secure Boot failed: $out" + [[ "$(cat "$tmp/inst-over-ok/boot/vmlinuz-$kv")" == new-image ]] || bad "a good reinstall did not install the new kernel" + [[ -z "$(compgen -G "$tmp/inst-over-ok/boot/.kernel-pop-keep-*")$(compgen -G "$tmp/inst-over-ok/modules/.kernel-pop-keep-*")" ]] || bad "a good reinstall left the kept copies behind" # The image cannot be signed at all: refused before dpkg, an installed kernel untouched out="$(SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled PREEXIST=1 TRIAL_FAIL=1 run_install trialfail)" && bad "do_install should refuse an image that cannot be signed" [[ -e "$tmp/inst-trialfail/dpkg-args" ]] && bad "dpkg ran although the image could not be signed" @@ -957,6 +1019,11 @@ EOF2 [[ "$(cat "$tmp/inst-espunsigned/apt-args" 2>/dev/null)" == "$APT_OPTS purge -y linux-headers-$kv linux-image-$kv" ]] \ || bad "an unsigned ESP copy under Secure Boot should be rolled back, got [$(cat "$tmp/inst-espunsigned/apt-args" 2>/dev/null)]" grep -q "copy on the ESP the boot loader starts is not" <<< "$out" || bad "the rollback should say the ESP copy is unsigned: $out" + # No postrm hook removes a systemd-boot entry: the rollback does, or the + # unbootable kernel would stay the newest, default entry + grep -qx "remove $kv" "$tmp/inst-espunsigned/ki-args" || bad "the rollback did not remove the boot entry: $(cat "$tmp/inst-espunsigned/ki-args")" + [[ -e "$tmp/inst-espunsigned/esp/loader/entries/mid-$kv.conf" ]] && bad "the rolled-back kernel's boot entry is still there" + grep -q "Nothing is left installed" <<< "$out" || bad "the rollback should say nothing is left: $out" # The same with Secure Boot off: installed, one SIGN WARNING out="$(SDBOOT=1 ESP_UNSIGNED=1 WITH_KEY=1 SIGN_OK=1 run_install espunsigned-off)" || bad "Secure Boot off: an unsigned ESP copy must not fail the install: $out" [[ -e "$tmp/inst-espunsigned-off/apt-args" ]] && bad "Secure Boot off: an unsigned ESP copy must not be rolled back" @@ -964,6 +1031,31 @@ EOF2 # Signed in /boot and on the ESP: installed out="$(SDBOOT=1 SB_ON=1 WITH_KEY=1 SIGN_OK=1 KEY_STATE=enrolled run_install espsigned)" || bad "a signed ESP copy should install: $out" + # systemd-boot without signing: the ESP still gets the final initramfs + # (the package hook copied the one from before DKMS), and the entry's + # files are checked + out="$(SDBOOT=1 run_install sd-unsigned)" || bad "systemd-boot install without signing failed: $out" + grep -qx "add $kv $tmp/inst-sd-unsigned/boot/vmlinuz-$kv $tmp/inst-sd-unsigned/boot/initrd.img-$kv" "$tmp/inst-sd-unsigned/ki-args" \ + || bad "the ESP copy was not refreshed without signing: [$(cat "$tmp/inst-sd-unsigned/ki-args" 2>/dev/null)]" + grep -q "Verified: the kernel and initramfs" <<< "$out" || bad "the entry's files were not checked: $out" + # That copy fails (a full ESP): installed, with one DKMS WARNING + out="$(SDBOOT=1 KI_FAIL=1 run_install sd-kifail)" || bad "a failed ESP refresh should not fail the install: $out" + [[ "$(count 'DKMS WARNING:' "$out")" == 1 ]] || bad "a failed ESP refresh should give one DKMS WARNING: $out" + # No initramfs tool: refused before dpkg + out="$(NO_IRTOOL=1 run_install noir)" && bad "do_install should refuse without an initramfs tool" + [[ -e "$tmp/inst-noir/dpkg-args" ]] && bad "dpkg ran without an initramfs tool" + grep -q "No initramfs tool is installed.*Nothing was installed" <<< "$out" || bad "the refusal should name the missing tool: $out" + # dpkg fails and apt -f would remove another package: not run + out="$(DPKG_FAIL=1 APT_SIM="Remv nvidia-dkms-615 [615.78-1]" run_install aptf)" && bad "do_install should stop when apt -f would remove packages" + grep -q "would remove: nvidia-dkms-615" <<< "$out" || bad "the refusal should name the package: $out" + grep -q "install -f -y" "$tmp/inst-aptf/apt-args" 2>/dev/null && bad "apt-get -f ran although it would remove a package" + # ... or only the new packages themselves (nothing was replaced): allowed + out="$(DPKG_FAIL=1 APT_SIM="Remv linux-image-$kv [7.7.7-1]" run_install aptf-own)" + grep -q "install -f -y" "$tmp/inst-aptf-own/apt-args" 2>/dev/null || bad "apt-get -f should run when it only takes back the new packages: $out" + # The modules directory never appears: stop, never use another one + out="$(NO_MODULES=1 run_install nomods)" && bad "do_install should fail without the modules directory" + grep -q "did NOT appear after install" <<< "$out" || bad "a missing modules directory should be reported: $out" + # Signing fails with Secure Boot off: kept, one SIGN WARNING, summary not counted out="$(WITH_KEY=1 run_install signfail-off)" || bad "do_install (sign fails, Secure Boot off) failed: $out" [[ "$(count 'SIGN WARNING:' "$out")" == 1 ]] || bad "Secure Boot off: one SIGN WARNING line expected" @@ -1120,7 +1212,7 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" } rm -f "$tmp/int-calls" out="$(do_install_build_deps pahole 2>&1 3>&1)" || bad "the install should go on after finishing the interrupted run: $out" - [[ "$(cat "$tmp/int-calls")" == "dpkg --configure -a"$'\n'"apt-get $APT_OPTS install -f -y"$'\n'"apt-get $APT_OPTS install --reinstall -y tailscale"$'\n'"apt-get $APT_OPTS install -y pahole" ]] \ + [[ "$(cat "$tmp/int-calls")" == "dpkg --configure -a"$'\n'"apt-get -s install -f"$'\n'"apt-get $APT_OPTS install -f -y"$'\n'"apt-get -s install --reinstall tailscale"$'\n'"apt-get $APT_OPTS install --reinstall -y tailscale"$'\n'"apt-get $APT_OPTS install -y pahole" ]] \ || bad "interrupted-run repair got [$(cat "$tmp/int-calls")]" grep -q "interrupted earlier" <<<"$out" || bad "the repair should be shown: $out" grep -q "is finished — continuing" <<<"$out" || bad "the repair's end should be shown: $out" @@ -1128,9 +1220,56 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" rm -f "$tmp/int-calls" do_install_build_deps pahole >/dev/null 2>&1 [[ "$(cat "$tmp/int-calls")" == "apt-get $APT_OPTS install -y pahole" ]] || bad "a clean dpkg state still ran a repair: [$(cat "$tmp/int-calls")]" + # A repair that would remove packages is not run + : > "$tmp/dpkg/updates/0004"; echo broken > "$state"; rm -f "$tmp/int-calls" + apt-get() { + echo "apt-get $*" >> "$tmp/int-calls" + [[ "$1" == -s ]] && printf 'Remv nvidia-driver-615 [615.78-1]\nPurg libnvidia-gl-615 [615.78-1]\n' + return 0 + } + out="$( (do_install_build_deps pahole) 2>&1 3>&1)" && bad "a repair that removes packages must stop the run" + grep -q "would remove: nvidia-driver-615 libnvidia-gl-615" <<<"$out" || bad "the refusal should name what would go: $out" + grep -q -- "install -f -y\|install -y pahole" "$tmp/int-calls" && bad "apt-get ran for real: [$(cat "$tmp/int-calls")]" + rm -f "$tmp/dpkg/updates/"* exit "$fails" ) || { echo "FAIL: interrupted dpkg group"; fails=$((fails + 1)); } +# ── Removal: metapackages, boot entries ─────────────────────────────────── +( + fails=0 + export KERNEL_POP_BOOT="$tmp/rm-boot" KERNEL_POP_MODULES="$tmp/rm-mods" + mkdir -p "$KERNEL_POP_BOOT" "$KERNEL_POP_MODULES" + rk=6.8.0-40-generic + touch "$KERNEL_POP_BOOT/vmlinuz-$rk" + dpkg-query() { printf 'ii linux-image-%s\n' "$rk"; } + # apt simulates a purge with "Purg" lines + APT_SIM="Purg linux-image-$rk [6.8.0-40.40]"$'\n'"Purg linux-image-generic [6.8.0.40.40]" + apt-get() { if [[ "$1" == -s ]]; then echo "$APT_SIM"; return 0; fi; echo "$*" >> "$tmp/rm-apt"; } + detect_bootloader() { echo grub; } + update-grub() { :; } + rm -f "$tmp/rm-apt" + out="$( (do_remove "$rk") 2>&1)" && bad "removing a kernel the metapackage needs should be refused" + grep -q "kernel metapackage(s): linux-image-generic" <<<"$out" || bad "the metapackage (Purg) was not named: $out" + [[ -e "$tmp/rm-apt" ]] && bad "apt-get purged although a metapackage would go" + APT_SIM="Remv linux-generic [6.8.0.40.40]" + out="$( (do_remove "$rk") 2>&1)" && bad "a Remv of a metapackage should be refused too" + APT_SIM="Purg linux-image-$rk [6.8.0-40.40]" + out="$( (do_remove "$rk") 2>&1)" || bad "a removal without metapackages failed: $out" + grep -q "purge -y linux-image-$rk" "$tmp/rm-apt" || bad "the kernel was not purged: [$(cat "$tmp/rm-apt" 2>/dev/null)]" + # systemd-boot without kernel-install: the entry goes on the ESP and on XBOOTLDR + ( + resp="$tmp/rm-esp"; rxbl="$tmp/rm-xbl" + mkdir -p "$resp/loader/entries" "$rxbl/loader/entries" + printf 'version %s\n' "$rk" > "$rxbl/loader/entries/mid-$rk.conf" + detect_bootloader() { echo "systemd-boot $resp"; } + command() { [[ "$2" == kernel-install ]] && return 1; builtin command "$@"; } + KERNEL_POP_XBOOTLDR="$rxbl" remove_boot_entry "$rk" >/dev/null || exit 1 + [[ -e "$rxbl/loader/entries/mid-$rk.conf" ]] && exit 2 + exit 0 + ) || bad "remove_boot_entry on XBOOTLDR case $?" + exit "$fails" +) || { echo "FAIL: removal group"; fails=$((fails + 1)); } + # ── shim in front of systemd-boot ──────────────────────────────────────── ( fails=0 @@ -1210,6 +1349,9 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" out="$(sign_boot_loader 2>&1)" grep -q "Signed systemd-boot" <<<"$out" || bad "a new systemd-boot was not signed: $out" [[ "$(head -1 "$KERNEL_POP_SDBOOT.signed")" == sdboot-new ]] || bad "the .signed copy is the old binary" + # bootctl skipped the copy: the older ESP copy, signed with the same key, + # is replaced all the same + cmp -s "$KERNEL_POP_SDBOOT.signed" "$cesp/EFI/systemd/systemd-bootx64.efi" || bad "the ESP kept the older signed systemd-boot" # A full ESP: a copy fails part way. No firmware entry may then point at # shim, the direct systemd-boot entry stays, and the loader already on @@ -1217,7 +1359,7 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" fesp="$tmp/full-esp" mkdir -p "$fesp/EFI/systemd" "$fesp/EFI/BOOT" cp "$KERNEL_POP_SDBOOT" "$fesp/EFI/systemd/systemd-bootx64.efi" - echo old-loader > "$fesp/EFI/BOOT/BOOTX64.EFI" + cp "$KERNEL_POP_SDBOOT" "$fesp/EFI/BOOT/BOOTX64.EFI" # bootctl's fallback copy: ours to replace printf 'Boot0001* Linux Boot Manager\tHD(1,GPT,x,0x800,0x219800)/\\EFI\\systemd\\systemd-bootx64.efi\n' > "$st" : > "$tmp/fw-calls" bootctl() { [[ "$1" == --print-esp-path ]] && echo "$fesp"; return 0; } @@ -1229,8 +1371,31 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" out="$(setup_shim_chain "$fesp" 2>&1)" && bad "setup_shim_chain succeeded although a copy to the ESP failed" grep -q "SIGN WARNING: could not copy" <<<"$out" || bad "a failed ESP copy was not reported: $out" [[ ! -s "$tmp/fw-calls" ]] || bad "firmware entries changed although a copy to the ESP failed: $(cat "$tmp/fw-calls")" - [[ "$(cat "$fesp/EFI/BOOT/BOOTX64.EFI")" == old-loader ]] || bad "a failed copy damaged the loader on the ESP" + cmp -s "$fesp/EFI/BOOT/BOOTX64.EFI" "$KERNEL_POP_SDBOOT" || bad "a failed copy damaged the loader on the ESP" unset -f install + + # An ESP shared with Windows: its fallback loader is left alone (and no + # fbx64 next to it), this system starts from its own firmware entry. + wesp="$tmp/win-esp" + mkdir -p "$wesp/EFI/systemd" "$wesp/EFI/BOOT" + cp "$KERNEL_POP_SDBOOT" "$wesp/EFI/systemd/systemd-bootx64.efi" + echo "Windows Boot Manager bootmgfw" > "$wesp/EFI/BOOT/BOOTX64.EFI" + printf 'Boot0001* Linux Boot Manager\tHD(1,GPT,x,0x800,0x219800)/\\EFI\\systemd\\systemd-bootx64.efi\n' > "$st" + bootctl() { [[ "$1" == --print-esp-path ]] && echo "$wesp"; return 0; } + out="$(setup_shim_chain "$wesp" 2>&1)" || bad "setup_shim_chain failed on a shared ESP: $out" + [[ "$(cat "$wesp/EFI/BOOT/BOOTX64.EFI")" == "Windows Boot Manager bootmgfw" ]] || bad "another system's fallback loader was replaced" + [[ -e "$wesp/EFI/BOOT/fbx64.efi" ]] && bad "fbx64 was put next to another system's fallback loader" + grep -q "Left .*BOOTX64.EFI alone" <<<"$out" || bad "leaving the fallback loader alone was not explained: $out" + [[ -n "$(shim_sdboot_entries)" ]] || bad "no shim firmware entry on a shared ESP" + # Writing the CSV fails part way (full ESP): the old one stays whole + printf 'shimx64.efi,Ubuntu,,This is the boot entry for Ubuntu\n' | iconv -t UCS-2LE > "$wesp/EFI/ubuntu/BOOTX64.CSV" + cp "$wesp/EFI/ubuntu/BOOTX64.CSV" "$tmp/csv-before" + ( + iconv() { if [[ "$*" == "-t UCS-2LE" ]]; then printf 'sh'; return 1; fi; command iconv "$@"; } + setup_shim_chain "$wesp" >/dev/null 2>&1 + ) && bad "setup_shim_chain succeeded although the CSV could not be written" + cmp -s "$wesp/EFI/ubuntu/BOOTX64.CSV" "$tmp/csv-before" || bad "a failed CSV write damaged the CSV" + [[ -e "$wesp/EFI/ubuntu/BOOTX64.CSV.kernel-pop-new" ]] && bad "a failed CSV write left its temp file" bootctl() { [[ "$1" == --print-esp-path ]] && echo "$cesp"; return 0; } # The kernel hook signs only a kernel without any signature @@ -1297,6 +1462,18 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" dkms() { [[ "$1" == status ]] && echo "gpu-unlock/1.0.0, 7.2.6-070206-generic, x86_64: installed"; return 0; } out="$(setup_dkms_key 2>&1)" grep -q "SIGN WARNING: gpu-unlock 1.0.0 for 7.2.6-070206-generic was rebuilt but is still not signed" <<<"$out" || bad "an unsigned rebuild was not reported: $out" + # DKMS 2 prints "name, version, kernel, arch: state": read the same way + : > "$tmp/dkms-calls" + dkms() { + case "$1" in + status) echo "gpu-unlock, 1.0.0, 7.2.6-070206-generic, x86_64: installed"; echo "old, 1, 6.1.0-1-generic, x86_64: built" ;; + *) echo "dkms $*" >> "$tmp/dkms-calls" ;; + esac + return 0 + } + setup_dkms_key >/dev/null 2>&1 + [[ "$(cat "$tmp/dkms-calls")" == $'dkms build --force -m gpu-unlock -v 1.0.0 -k 7.2.6-070206-generic\ndkms install --force -m gpu-unlock -v 1.0.0 -k 7.2.6-070206-generic' ]] \ + || bad "DKMS 2 status lines: [$(cat "$tmp/dkms-calls")]" # A module named after its package ("$PACKAGE_NAME", as many dkms.conf # files write it) is found, and judged by its signature mkdir -p "$KERNEL_POP_DKMS_TREE/v4l2loopback/0.13.2/source" @@ -1307,6 +1484,14 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" dkms_package_signed v4l2loopback 0.13.2 7.2.6-070206-generic "$(cert_key_ids)" || bad "a \${PACKAGE_NAME} module signed with the key counted as unsigned" echo "11:22:33:44" > "$kd/v4l2loopback.ko.zst" dkms_package_signed v4l2loopback 0.13.2 7.2.6-070206-generic "$(cert_key_ids)" && bad "a \${PACKAGE_NAME} module signed with another key counted as signed" + # Single quotes, and no BUILT_MODULE_NAME at all (the package's name then) + echo "9B:1B:75:AD" > "$kd/v4l2loopback.ko.zst" + printf "PACKAGE_NAME='v4l2loopback'\nBUILT_MODULE_NAME[0]='v4l2loopback'\n" > "$KERNEL_POP_DKMS_TREE/v4l2loopback/0.13.2/source/dkms.conf" + dkms_package_signed v4l2loopback 0.13.2 7.2.6-070206-generic "$(cert_key_ids)" || bad "a single-quoted module name was not found" + printf 'PACKAGE_NAME="v4l2loopback"\nMAKE[0]="make"\n' > "$KERNEL_POP_DKMS_TREE/v4l2loopback/0.13.2/source/dkms.conf" + dkms_package_signed v4l2loopback 0.13.2 7.2.6-070206-generic "$(cert_key_ids)" || bad "without BUILT_MODULE_NAME the package's module was not found" + echo "11:22:33:44" > "$kd/v4l2loopback.ko.zst" + dkms_package_signed v4l2loopback 0.13.2 7.2.6-070206-generic "$(cert_key_ids)" && bad "without BUILT_MODULE_NAME a module signed with another key counted as signed" export KERNEL_POP_MODULES="$saved_modules" KERNEL_POP_BOOT="$saved_boot" unset -f modinfo cert_key_ids generate_initramfs refresh_esp_copy @@ -1400,6 +1585,18 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" queue_key_enrollment() { echo queue >> "$order"; die "import failed"; } (printf 'Secret-pw1\n' | do_setup_signing >/dev/null 2>&1) && bad "setup should fail when the enrollment fails" grep -q chain "$order" && bad "the shim chain was set up although the enrollment failed" + # An already-signed kernel whose ESP copy is not signed (an earlier copy + # failed): copied again + : > "$order" + queue_key_enrollment() { :; } + installed_kvers() { printf '9.9.1-old\n9.9.2-ok\n'; } + kernel_signed() { return 0; } + write_signed_marker() { :; } + esp_copy_signed() { [[ "$1" == 9.9.2-ok ]]; } + sync_signed_to_esp() { echo "sync $1" >> "$order"; } + printf 'Secret-pw1\n' | do_setup_signing >/dev/null 2>&1 || bad "do_setup_signing failed with signed kernels" + grep -qx "sync 9.9.1-old" "$order" || bad "an unsigned ESP copy of a signed kernel was not copied again: [$(cat "$order")]" + grep -q "sync 9.9.2-ok" "$order" && bad "a signed ESP copy was copied again" exit "$fails" ) || { echo "FAIL: setup order group"; fails=$((fails + 1)); } diff --git a/src/download.rs b/src/download.rs index 8e03abb..7f75528 100644 --- a/src/download.rs +++ b/src/download.rs @@ -151,8 +151,13 @@ where } } if !failed { - file.flush().await?; - return Ok(()); + // The last buffered write can fail here (a full disk): retried + // like a failed write, its .part file gone. + match flush_part(file, dest).await { + Ok(()) => return Ok(()), + Err(e) => last_err = e, + } + continue; } let _ = tokio::fs::remove_file(dest).await; } @@ -160,6 +165,17 @@ where Err(last_err).context(format!("Download failed after {} attempts", MAX_RETRIES)) } +/// Flushes a finished `.part` file. On failure the file is deleted and the +/// error returned. +async fn flush_part(mut file: W, dest: &Path) -> Result<()> { + if let Err(e) = file.flush().await { + drop(file); + let _ = tokio::fs::remove_file(dest).await; + return Err(e.into()); + } + Ok(()) +} + /// One file to download: where from, and its name in the target directory. #[derive(Debug, Clone)] pub struct Remote { @@ -351,6 +367,33 @@ mod tests { assert_eq!(or_cancel(&AtomicBool::new(false), async { 7 }).await.unwrap(), 7); } + /// A writer whose last flush fails, as a full disk makes it. + struct FullDisk; + impl tokio::io::AsyncWrite for FullDisk { + fn poll_write(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>, buf: &[u8]) -> std::task::Poll> { + std::task::Poll::Ready(Ok(buf.len())) + } + fn poll_flush(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll> { + std::task::Poll::Ready(Err(std::io::Error::from_raw_os_error(28))) + } + fn poll_shutdown(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + } + + #[tokio::test] + async fn a_failed_flush_deletes_the_part_file() { + let part = std::env::temp_dir().join(format!("kernel-pop-test-flush-{}.part", std::process::id())); + std::fs::write(&part, b"partial").unwrap(); + let err = flush_part(FullDisk, &part).await.unwrap_err(); + assert!(err.to_string().contains("No space left"), "{err}"); + assert!(!part.exists()); + std::fs::write(&part, b"whole").unwrap(); + flush_part(tokio::fs::File::create(&part).await.unwrap(), &part).await.unwrap(); + assert!(part.exists()); + std::fs::remove_file(&part).unwrap(); + } + #[test] fn sha256_of_a_file() { let path = std::env::temp_dir().join(format!("kernel-pop-test-{}.bin", std::process::id())); diff --git a/src/source.rs b/src/source.rs index cad00be..57746d1 100644 --- a/src/source.rs +++ b/src/source.rs @@ -202,7 +202,14 @@ pub fn check_single_top_dir(t: &Tarball) -> Result<()> { } let prefix = format!("{}/", t.top_dir); for line in String::from_utf8_lossy(&out.stdout).lines() { - let name = line.trim_prefix("./"); + // "./", "././linux-7.3/..." and the like, as find_makefile reads them. + let mut name = line; + while let Some(rest) = name.strip_prefix("./") { + name = rest; + } + if name.is_empty() || name == "." { + continue; + } if name != t.top_dir && name != prefix && !name.starts_with(&prefix) { bail!("The tarball holds {name}, outside its top-level directory {} — refusing to build it", t.top_dir); } @@ -411,6 +418,33 @@ pub mod tests { std::fs::remove_dir_all(&d).unwrap(); } + #[test] + fn dot_slash_member_names_are_read_like_the_makefile_search() { + let d = scratch("dotslash"); + let mut b = tar::Builder::new(Vec::new()); + for (name, data, dir) in [ + ("./", &b""[..], true), + ("././linux-7.2.12/", b"", true), + ("./linux-7.2.12/Makefile", MAKEFILE.as_bytes(), false), + ("././linux-7.2.12/README", b"x", false), + ] { + // The name as written, "./" kept: set_path would normalise it away. + let mut h = tar::Header::new_gnu(); + h.as_old_mut().name[..name.len()].copy_from_slice(name.as_bytes()); + h.set_size(data.len() as u64); + h.set_mode(if dir { 0o755 } else { 0o644 }); + h.set_entry_type(if dir { tar::EntryType::Directory } else { tar::EntryType::Regular }); + h.set_cksum(); + b.append(&h, data).unwrap(); + } + let xz = d.join("dots.tar.xz"); + compress_to("xz", &b.into_inner().unwrap(), &xz); + let t = inspect(&xz).unwrap(); + assert_eq!(t.top_dir, "linux-7.2.12"); + check_single_top_dir(&t).unwrap(); + std::fs::remove_dir_all(&d).unwrap(); + } + #[test] fn sibling_signature_is_found_next_to_the_tarball() { let d = scratch("sibling"); diff --git a/src/ui.rs b/src/ui.rs index b1b84e1..0d9c946 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -110,6 +110,9 @@ fn busy_refusal(running: Option<&'static str>, closing: bool) -> Option } } +/// The prepared build and its busy guard, held by the build summary dialog. +type SummarySlot = Rc>>; + /// How long closing waits for a cancelled download to stop and delete its /// `.part` file before deleting it itself and closing anyway. const DOWNLOAD_STOP_WAIT: Duration = Duration::from_secs(5); @@ -1087,6 +1090,10 @@ pub struct MainView { download_bar: Option, build_fraction: Option, + /// The build summary dialog's pending build, while that dialog is open: + /// closing the window discards it (no worker runs then to see a cancel). + build_summary: Option, + // Install tab installing: bool, @@ -1154,6 +1161,7 @@ impl MainView { stage_text: None, download_bar: None, build_fraction: None, + build_summary: None, installing: false, log_lines: VecDeque::new(), log_dirty: false, @@ -1304,7 +1312,15 @@ impl MainView { // Nothing new starts while the build stops and the window closes, as // for a download. self.state.borrow_mut().closing = true; - if !control.is_cancelled() { + // At the build summary nothing runs that would see the cancel: the + // dialog holds the configured tree and the busy guard. Discard them + // the way its Cancel does; the window closes once they are gone. + let at_summary = self.build_summary.take().and_then(|slot| slot.borrow_mut().take()); + if let Some((prepared, busy)) = at_summary { + window.close_dialog(cx); + control.cancel(); + self.discard_prepared(prepared, busy, window, cx); + } else if !control.is_cancelled() { control.cancel(); toast(window, cx, "Stopping the build before closing…"); } @@ -2113,25 +2129,39 @@ impl MainView { default: DefaultButton::Action, destructive: false, }; - let slot = Rc::new(RefCell::new(Some((prepared, busy)))); + let slot: SummarySlot = Rc::new(RefCell::new(Some((prepared, busy)))); + this.build_summary = Some(slot.clone()); let cancel_slot = slot.clone(); let go = this.later(cx, move |this, window, cx| { + this.build_summary = None; let Some((prepared, busy)) = slot.borrow_mut().take() else { return }; + // A cancelled control would end the build at once. + if control.is_cancelled() { + this.discard_prepared(prepared, busy, window, cx); + return; + } this.start_build(prepared, busy, control, tree_log, window, cx); }); let cancel = this.later(cx, move |this, window, cx| { + this.build_summary = None; let Some((prepared, busy)) = cancel_slot.borrow_mut().take() else { return }; - this.log("Build not started; the configured tree is deleted."); - // Busy until the tree is gone: a new build at once would extract into it. - this.run(window, cx, async move { tokio::task::spawn_blocking(move || prepared.discard()).await }, move |this, _, window, cx| { - this.finish_build(busy, "", window, cx) - }); + this.discard_prepared(prepared, busy, window, cx); }); show_question(question, go, Some(cancel), window, cx); }, ); } + /// A build that will not start: delete its configured tree, then end the + /// busy state. Busy until the tree is gone: a new build at once would + /// extract into it. + fn discard_prepared(&mut self, prepared: Prepared, busy: BusyGuard, window: &mut Window, cx: &mut Context) { + self.log("Build not started; the configured tree is deleted."); + self.run(window, cx, async move { tokio::task::spawn_blocking(move || prepared.discard()).await }, move |this, _, window, cx| { + this.finish_build(busy, "", window, cx) + }); + } + fn start_build(&mut self, prepared: Prepared, busy: BusyGuard, control: Arc, tree_log: PathBuf, window: &mut Window, cx: &mut Context) { let krel = prepared.summary.kernelrelease.clone(); self.log(format!("Building Linux {krel} — this takes a while; the full output goes to build.log")); diff --git a/tests/libcheck.rs b/tests/libcheck.rs index 0e7ec09..90c7211 100644 --- a/tests/libcheck.rs +++ b/tests/libcheck.rs @@ -443,17 +443,31 @@ fn a_dialog_that_could_not_open_the_display_passes_the_message_on() { let log = dir.join("calls"); // zenity with no display ends with 1, as a closed dialog does, but says why on stderr; and it // leaves a process holding that stderr, which must not be waited for. - script_file(&dir.join("zenity"), &format!("#!/bin/bash\necho zenity >> '{}'\necho 'cannot open display: :9999' >&2\nsleep 5 &\nexit 1\n", log.display())); + // By its full path: PATH holds only the fakes. It records its PID, so the test knows it ran. + let sleep = ["/usr/bin/sleep", "/bin/sleep"].into_iter().find(|p| Path::new(p).exists()).expect("sleep"); + let sleeper = dir.join("sleeper"); + script_file( + &dir.join("zenity"), + &format!( + "#!/bin/bash\necho zenity >> '{}'\necho 'cannot open display: :9999' >&2\n{sleep} 5 &\necho $! > '{}'\nexit 1\n", + log.display(), + sleeper.display() + ), + ); script_file(&dir.join("kdialog"), &format!("#!/bin/bash\necho kdialog >> '{}'\necho 'Failed to open display' >&2\nexit 1\n", log.display())); script_file(&dir.join("notify-send"), &format!("#!/bin/bash\necho notify-send >> '{}'\nexit 0\n", log.display())); let started = std::time::Instant::now(); let calls = show_in(&dir); assert!(started.elapsed() < std::time::Duration::from_secs(3), "{:?}", started.elapsed()); assert_eq!(calls, ["zenity", "kdialog", "notify-send"]); + // The child holding zenity's stderr really ran, and still does: it was not waited for. + let pid = std::fs::read_to_string(&sleeper).expect("the background sleep did not start").trim().to_string(); + assert!(Path::new(&format!("/proc/{pid}")).exists(), "the background sleep {pid} is not running"); + let _ = Command::new("kill").arg(&pid).status(); // The temporary files for their stderr (TMPDIR is this folder here) are gone. let mut left: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); left.sort(); - assert_eq!(left, ["calls", "kdialog", "mktemp", "notify-send", "rm", "zenity"]); + assert_eq!(left, ["calls", "kdialog", "mktemp", "notify-send", "rm", "sleeper", "zenity"]); let _ = std::fs::remove_dir_all(&dir); } From 564ed158aeb6f689c47d5ee71d07eacd926e6372 Mon Sep 17 00:00:00 2001 From: "Linnard Alex Brown Jr." Date: Wed, 18 Nov 2026 08:21:07 -0500 Subject: [PATCH 2/4] Review round 1: safer keep and restore of a reinstalled kernel Only a version whose /boot/vmlinuz exists counts as installed before; a lone leftover modules directory takes the purge path, which now removes it too. rollback_and_die gets `existed` and never purges then. The kept initramfs is copied when /boot has room and moved back, regenerated only otherwise. Any stop after the kept copy and before the install finished puts the old version back (EXIT trap); a restore that fails part way keeps the rest and names its paths. The fallback loader is copied before EFI/ so a partial failure still counts it as ours next run; the dead Windows check is gone. The kernelstub precondition names the leftover configuration file. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 19 ++-- README.md | 3 +- scripts/privileged-install.sh | 152 +++++++++++++++++++++---------- scripts/tests/test-privileged.sh | 32 ++++++- 4 files changed, 150 insertions(+), 56 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e801729..728548d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,12 +232,16 @@ enforcing, `--install` requires the key set, the sbsign tools and a key that is enrolled or queued (`secure_boot_preflight`, before dpkg; the app checks the same in `install_blocker` and refuses up front). If signing then fails, `rollback_and_die` undoes the install and the run fails: new -packages are purged and their boot entry removed (`remove_boot_entry`: no -postrm hook removes a systemd-boot entry); a version that was installed -before (a rebuild, maybe of the running kernel) is never purged, its -kernel, System.map, config and modules are kept before dpkg -(`keep_installed_kernel`, hard links) and moved back, and its initramfs is -generated again. Everything the steps after dpkg need (an initramfs tool, +packages are purged, a leftover `/lib/modules/` removed and their +boot entry removed (`remove_boot_entry`: no postrm hook removes a +systemd-boot entry); a version that was installed before (its +`/boot/vmlinuz-` is there; a rebuild, maybe of the running kernel) is +never purged: its kernel, System.map, config and modules are kept before +dpkg (`keep_installed_kernel`, hard links), its initramfs copied when +`/boot` has room (else generated again on restore), and moved back. Any +other stop after the copy and before the install finished puts it back too +(`kept_kernel_on_exit`, the EXIT trap); a restore that fails part way leaves +the rest where it was kept and names the paths. Everything the steps after dpkg need (an initramfs tool, kernel-install or kernelstub) is checked before dpkg. A queued key is fine: the kernel boots once MOK Manager enrolls it. @@ -325,7 +329,8 @@ boots once MOK Manager enrolls it. `EFI//`, shim at `EFI/BOOT/BOOTX64.EFI` only over a fallback loader that is ours (`fallback_is_ours`: none, shim, or systemd-boot; never Windows' or another distribution's, and then no - fbx64 either), UCS-2LE `BOOTX64.CSV` (written tmp + mv) + fbx64 either; copied before `EFI/`, so a run that fails part way + still sees it as ours next time), UCS-2LE `BOOTX64.CSV` (written tmp + mv) byte-identical to install_shim's, firmware entry `` = `EFI//shimx64.efi` with load option `\EFI\systemd\systemd-bootx64.efi \0`), done by the script itself so it diff --git a/README.md b/README.md index 983849d..1579b2d 100644 --- a/README.md +++ b/README.md @@ -325,7 +325,8 @@ signed with a key that is enrolled or waiting for enrollment: removed again, with its systemd-boot entry, so no kernel that shim would refuse is left in the boot menu. A rebuild of a version that was already installed (the running kernel, say) is never removed: the kernel and - modules from before are put back and its initramfs made again. + modules from before are put back with its initramfs. The same happens when + the install stops for any other reason before it has finished. - If the key is still waiting for enrollment, the kernel is installed and signed, and the install reminds you to confirm the enrollment at the MOK Manager screen on the next reboot; skip that and it will not boot. diff --git a/scripts/privileged-install.sh b/scripts/privileged-install.sh index b583651..7d83757 100755 --- a/scripts/privileged-install.sh +++ b/scripts/privileged-install.sh @@ -917,17 +917,18 @@ trial_sign_image() { log "Checked: the kernel image of $kver can be signed" } -# A kernel version that is installed already (a rebuild, maybe of the -# running kernel) is never purged by a rollback: that would take the working -# kernel with it. Before dpkg replaces it, its kernel, System.map, config and -# modules are kept: hard links (dpkg writes new files and renames them over -# the old names, so the links keep the old contents), copies where /boot -# cannot hold links. A rollback moves them back and generates the initramfs -# again from the old modules (dracut rewrites an initramfs in place, so a -# link would not keep it). -KEEP_BOOT="" KEEP_MODS="" +# A kernel version that is installed already (its /boot/vmlinuz is there: a +# rebuild, maybe of the running kernel) is never purged by a rollback: that +# would take the working kernel with it. Before dpkg replaces it, its kernel, +# System.map, config and modules are kept: hard links (dpkg writes new files +# and renames them over the old names, so the links keep the old contents), +# copies where /boot cannot hold links. Its initramfs is copied when /boot +# has room (dracut rewrites an initramfs in place, so a link would not keep +# it); otherwise it is generated again from the old modules. Any stop after +# that, before the install has finished, puts them back (kept_kernel_on_exit). +KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" keep_installed_kernel() { - local kver="$1" boot mods f + local kver="$1" boot mods f size avail boot="$(boot_dir)" mods="$(modules_dir)" KEEP_BOOT="$boot/.kernel-pop-keep-$kver" @@ -938,36 +939,52 @@ keep_installed_kernel() { [[ -e "$boot/$f-$kver" ]] || continue ln "$boot/$f-$kver" "$KEEP_BOOT/" 2>/dev/null || cp -p "$boot/$f-$kver" "$KEEP_BOOT/" || return 1 done + [[ -f "$KEEP_BOOT/vmlinuz-$kver" ]] || return 1 + if [[ -f "$boot/initrd.img-$kver" ]]; then + # Room for the copy and for the new build's initramfs next to it. + size="$(stat -c %s "$boot/initrd.img-$kver")" + avail="$(boot_free_bytes "$boot")" + if [[ "$avail" =~ ^[0-9]+$ ]] && (( avail > 3 * size )); then + cp -p "$boot/initrd.img-$kver" "$KEEP_BOOT/" || rm -f "$KEEP_BOOT/initrd.img-$kver" + fi + fi if [[ -d "$mods/$kver" ]]; then cp -al "$mods/$kver" "$KEEP_MODS" 2>/dev/null || { rm -rf "$KEEP_MODS"; cp -a "$mods/$kver" "$KEEP_MODS"; } || return 1 fi + KEEP_KVER="$kver" } +# Free bytes on the filesystem holding . +boot_free_bytes() { df -PB1 "$1" 2>/dev/null | awk 'NR == 2 { print $4 }'; } + drop_kept_kernel() { [[ -n "$KEEP_BOOT" ]] && rm -rf "$KEEP_BOOT" [[ -n "$KEEP_MODS" ]] && rm -rf "$KEEP_MODS" + KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" return 0 } +# Where the kept files are, for a message. +kept_paths() { echo "$KEEP_BOOT${KEEP_MODS:+ and $KEEP_MODS}"; } + # Put the kept files of back and bring the boot loader's copy in line -# with them. Non-zero when something could not be put back. +# with them. Non-zero when something could not be put back; whatever was not +# moved back stays where it was kept (named in the log), never deleted. restore_kept_kernel() { local kver="$1" boot mods f boot="$(boot_dir)" mods="$(modules_dir)" - [[ -d "$KEEP_BOOT" ]] || return 1 - for f in "$KEEP_BOOT"/*; do - [[ -e "$f" ]] || continue - # Still the same file: nothing replaced it. - if [[ "$f" -ef "$boot/${f##*/}" ]]; then rm -f "$f"; continue; fi - mv -f "$f" "$boot/" || return 1 - done - if [[ -d "$KEEP_MODS" ]]; then - rm -rf "${mods:?}/${kver:?}" && mv -T "$KEEP_MODS" "$mods/$kver" || return 1 + if ! restore_kept_files "$kver"; then + log "Could not put back every kept file of $kver; what is left is in $(kept_paths)" + KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" + return 1 + fi + KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" + if [[ -f "$boot/initrd.img-$kver.kept" ]]; then + mv -f "$boot/initrd.img-$kver.kept" "$boot/initrd.img-$kver" || return 1 + else + generate_initramfs "$kver" && [[ -f "$boot/initrd.img-$kver" ]] || return 1 fi - rmdir "$KEEP_BOOT" 2>/dev/null || true - KEEP_BOOT="" KEEP_MODS="" - generate_initramfs "$kver" && [[ -f "$boot/initrd.img-$kver" ]] || return 1 if signing_key_present && kernel_signed "$kver"; then write_signed_marker "$kver" || true sync_signed_to_esp "$kver" || return 1 @@ -978,18 +995,54 @@ restore_kept_kernel() { log "Put back the $kver installed before: its kernel, initramfs and modules" } +# The file moves of restore_kept_kernel. The kept initramfs goes back under +# a temporary name (initrd.img-.kept), renamed over the new one last. +restore_kept_files() { + local kver="$1" boot mods f name + boot="$(boot_dir)" + mods="$(modules_dir)" + [[ -d "$KEEP_BOOT" ]] || return 1 + for f in "$KEEP_BOOT"/*; do + [[ -e "$f" ]] || continue + name="${f##*/}" + [[ "$name" == "initrd.img-$kver" ]] && name="$name.kept" + # Still the same file: nothing replaced it. + if [[ "$f" -ef "$boot/$name" ]]; then rm -f "$f"; continue; fi + mv -f "$f" "$boot/$name" || return 1 + done + if [[ -d "$KEEP_MODS" ]]; then + rm -rf "${mods:?}/${kver:?}" && mv -T "$KEEP_MODS" "$mods/$kver" || return 1 + fi + rmdir "$KEEP_BOOT" 2>/dev/null || true +} + +# The EXIT trap of an install: a run that stopped after the kept copy was +# made and before the install finished puts the version from before back, +# since what dpkg left may be unsigned or half installed. Chosen over only +# naming the kept files: with Secure Boot enforcing, that version may be the +# running kernel, and an unsigned one in its place would not boot again. +kept_kernel_on_exit() { + [[ -n "$KEEP_KVER" ]] || return 0 + log "The install stopped before $KEEP_KVER was ready: putting back the $KEEP_KVER installed before…" + restore_kept_kernel "$KEEP_KVER" \ + || log "WARNING: the $KEEP_KVER installed before could not be put back completely — it may NOT boot while Secure Boot is enforcing (see above)" + return 0 +} + # Undo a just-finished dpkg install with Secure Boot enforcing, where the new # kernel could not boot (signing failed, or its ESP copy is unsigned), then -# stop with . A version installed before is put back from the kept -# files; a new one is purged and its boot menu entry removed (no postrm hook -# removes a systemd-boot entry). +# stop with . A version installed before ( 1) is never purged: +# it is put back from the kept files. A new one is purged, its leftover +# modules directory and its boot menu entry removed (no postrm hook removes +# a systemd-boot entry). rollback_and_die() { - local dir="$1" kver="$2" why="$3" d pkgs=() - if [[ -n "$KEEP_BOOT" ]]; then - if restore_kept_kernel "$kver"; then + local dir="$1" kver="$2" existed="$3" why="$4" d pkgs=() kept + if (( existed )); then + kept="$(kept_paths)" + if [[ -n "$KEEP_KVER" ]] && restore_kept_kernel "$kver"; then die "$why With Secure Boot enforcing the new build could not boot, so the $kver installed before was put back as it was (kernel, initramfs and modules; the headers are the new build's). Try again, or check the signing setup on the System tab." fi - die "$why The $kver installed before could not be put back completely, so it may NOT boot while Secure Boot is enforcing. Boot another kernel and install $kver again." + die "$why The $kver installed before could not be put back completely, so it may NOT boot while Secure Boot is enforcing; what was kept of it is in $kept. Boot another kernel and install $kver again." fi if [[ "$kver" == "$(uname -r)" ]]; then die "$why $kver is the running kernel, so it was not removed — it will NOT boot again while Secure Boot is enforcing. Install a kernel that boots before rebooting." @@ -1001,6 +1054,9 @@ rollback_and_die() { if ! apt_get purge -y "${pkgs[@]}" >>"$LOGFILE" 2>&1; then die "$why $kver could not be removed again — it will NOT boot while Secure Boot is enforcing. Remove it on the System tab before rebooting." fi + # Files dpkg did not own (a modules directory left from an earlier + # kernel of that version) go too: nothing of $kver was installed before. + rm -rf "$(modules_dir)/${kver:?}" remove_signed_marker "$kver" if ! remove_boot_entry "$kver"; then die "$why With Secure Boot enforcing it could not boot, so it was removed again, but its boot menu entry may still be there: choose another kernel in the boot menu." @@ -1012,9 +1068,9 @@ rollback_and_die() { # ESP is not known to be. With Secure Boot enforcing it could not boot, so the # install is undone like a failed signing; with it off it is a warning. esp_copy_unsigned() { - local dir="$1" kver="$2" + local dir="$1" kver="$2" existed="$3" if secure_boot_enforcing; then - rollback_and_die "$dir" "$kver" "$kver was signed, but the copy on the ESP the boot loader starts is not (see the SIGN WARNING above)." + rollback_and_die "$dir" "$kver" "$existed" "$kver was signed, but the copy on the ESP the boot loader starts is not (see the SIGN WARNING above)." fi SIGN_FAILED=$((SIGN_FAILED + 1)) log "$kver is installed, but its ESP copy is not signed: it boots only while Secure Boot is off" @@ -1197,7 +1253,7 @@ do_install() { # Everything below works on the private, verified copy only. STAGE_DIR="$(umask 077 && mktemp -d "${KERNEL_POP_STAGING:-/var/tmp}/kernel-pop-install.XXXXXX")" \ || die "Could not create a private staging directory" - trap 'rm -rf "$STAGE_DIR"; drop_kept_kernel' EXIT + trap 'rm -rf "$STAGE_DIR"; kept_kernel_on_exit' EXIT stage_verified_debs "$src" "$STAGE_DIR" local dir="$STAGE_DIR" @@ -1228,8 +1284,10 @@ do_install() { # is signed once here first, on a copy in the private staging dir: a # failure stops before anything is installed. local existed=0 image_deb="" own_pkgs=() - dpkg-query -W -f '${Status}' "linux-image-$kver" 2>/dev/null | grep -q 'install ok installed' && existed=1 - [[ -e "$boot/vmlinuz-$kver" || -d "$mods/$kver" ]] && existed=1 + # Installed before: its kernel image is there (a modules directory alone + # is a leftover, and a package without its image is broken: neither is + # worth keeping). + [[ -f "$boot/vmlinuz-$kver" ]] && existed=1 for d in "${debs[@]}"; do own_pkgs+=("$(dpkg-deb -f "$d" Package)") [[ "$(dpkg-deb -f "$d" Package)" == "linux-image-$kver" ]] && image_deb="$d" @@ -1252,14 +1310,14 @@ do_install() { || die "systemd-boot is the boot loader, but kernel-install (systemd) is missing, so $kver would get no boot menu entry. Nothing was installed." ;; kernelstub) command -v kernelstub >/dev/null 2>&1 \ - || die "kernelstub is configured, but the kernelstub command is missing, so $kver would not be copied to the ESP. Nothing was installed." ;; + || die "kernelstub is configured (/etc/kernelstub/configuration is there), but the kernelstub command is missing, so $kver would not be copied to the ESP. Nothing was installed. If kernelstub is no longer used, that file is a leftover: remove it, then try again." ;; esac # A rollback (Secure Boot enforcing, the new build cannot boot) puts an # installed version back instead of purging it. if (( existed )) && secure_boot_enforcing; then keep_installed_kernel "$kver" \ - || die "Could not keep a copy of the $kver installed now (is /boot full?), which a failed signing would need to put it back. Nothing was installed." + || { drop_kept_kernel; die "Could not keep a copy of the $kver installed now (is /boot full?), which a failed signing would need to put it back. Nothing was installed."; } fi log "Installing ${#debs[@]} packages…" @@ -1297,7 +1355,7 @@ do_install() { if sign_kernel "$kver"; then signed_now=1 elif secure_boot_enforcing; then - rollback_and_die "$dir" "$kver" "$kver could not be signed (see the SIGN WARNING above)." + rollback_and_die "$dir" "$kver" "$existed" "$kver could not be signed (see the SIGN WARNING above)." else SIGN_FAILED=$((SIGN_FAILED + 1)) log "$kver was installed but could not be signed (see the SIGN WARNING above)" @@ -1343,7 +1401,7 @@ do_install() { [[ -n "$efi_img" ]] || die "No EFI/Pop_OS-*/$slot under $esp after install — kernelstub did not sync. Try 'kernelstub -p' — DO NOT reboot expecting the new kernel" log "Verified: kernelstub image $efi_img exists" if (( signed_now )); then - sync_signed_to_esp "$kver" || esp_copy_unsigned "$dir" "$kver" + sync_signed_to_esp "$kver" || esp_copy_unsigned "$dir" "$kver" "$existed" else refresh_esp_copy "$kver" || esp_initrd_stale "$kver" fi @@ -1360,7 +1418,7 @@ do_install() { [[ -n "$entry" ]] || die "No systemd-boot entry appeared for $kver in $esp/loader/entries (or on the XBOOTLDR partition) — DO NOT reboot expecting it in the menu" log "Verified: boot menu entry $entry exists" if (( signed_now )); then - sync_signed_to_esp "$kver" || esp_copy_unsigned "$dir" "$kver" + sync_signed_to_esp "$kver" || esp_copy_unsigned "$dir" "$kver" "$existed" else refresh_esp_copy "$kver" || esp_initrd_stale "$kver" fi @@ -1813,7 +1871,7 @@ fallback_is_ours() { [[ -s "$f" ]] && cmp -s "$f" "$cur" && return 0 done # A systemd-boot of another version names itself in its binary. - grep -aq 'systemd-boot' "$cur" 2>/dev/null && ! grep -aq 'Windows Boot Manager' "$cur" 2>/dev/null + grep -aq 'systemd-boot' "$cur" 2>/dev/null } # The ESP and firmware side, after install_shim_packages and after the key @@ -1832,11 +1890,9 @@ setup_shim_chain() { sign_boot_loader || return 1 # Every copy must be in place before a firmware entry points at it or the # direct systemd-boot entries go. - for f in shim fb mm; do - [[ -f "$lib/${f}x64.efi.signed" ]] || continue - esp_install "$lib/${f}x64.efi.signed" "$esp/EFI/$vendor/${f}x64.efi" || return 1 - done - # The fallback path: shim there, and fbx64 recreates the firmware entry + # The fallback path first: it counts as ours by comparing it with the + # shim in EFI/, so if a copy fails part way the next run still + # sees it as ours. Shim there, and fbx64 recreates the firmware entry # from the CSV after a firmware reset. GRUB's CSV passes nothing, which # would point shim at GRUB. Only over a fallback loader that is this # system's (shim, or systemd-boot as bootctl puts it there) or none: on @@ -1850,6 +1906,10 @@ setup_shim_chain() { else log "Left $esp/EFI/BOOT/BOOTX64.EFI alone: it is another system's boot loader (Windows or another distribution), not shim or systemd-boot. This system starts from its own firmware entry." fi + for f in shim fb mm; do + [[ -f "$lib/${f}x64.efi.signed" ]] || continue + esp_install "$lib/${f}x64.efi.signed" "$esp/EFI/$vendor/${f}x64.efi" || return 1 + done csv="$esp/EFI/$vendor/BOOTX64.CSV" if ! iconv -f UCS-2LE -t UTF-8 "$csv" 2>/dev/null | grep -q 'systemd-bootx64\.efi'; then # Written next to it and renamed over it: a full ESP never leaves a diff --git a/scripts/tests/test-privileged.sh b/scripts/tests/test-privileged.sh index 766e5d3..dcb1470 100755 --- a/scripts/tests/test-privileged.sh +++ b/scripts/tests/test-privileged.sh @@ -885,6 +885,10 @@ EOF2 echo old-image > "$KERNEL_POP_BOOT/vmlinuz-$kv"; echo old-initrd > "$KERNEL_POP_BOOT/initrd.img-$kv" mkdir -p "$KERNEL_POP_MODULES/$kv/kernel"; echo old > "$KERNEL_POP_MODULES/$kv/kernel/old.ko" fi + # Only a modules directory left from an earlier kernel of that version + if [[ -n "${LONE_MODS:-}" ]]; then mkdir -p "$KERNEL_POP_MODULES/$kv"; echo stale > "$KERNEL_POP_MODULES/$kv/stale.ko"; fi + [[ -n "${NO_ROOM:-}" ]] && boot_free_bytes() { echo 0; } + [[ -n "${RESTORE_MV_FAIL:-}" ]] && mv() { [[ "$1" == -T ]] && return 1; command mv "$@"; } # Like dpkg: new files are written aside and renamed over the old # names; the systemd-boot hook writes an entry and copies the kernel. dpkg() { @@ -922,7 +926,7 @@ EOF2 else detect_bootloader() { echo "grub"; } fi - update-grub() { :; } + update-grub() { [[ -z "${GRUB_FAIL:-}" ]]; } grub-editenv() { echo "saved_entry=$(cat "$root/saved")"; } grub-set-default() { echo "$1" > "$root/saved"; } grub-reboot() { echo "$1" > "$root/next"; } @@ -998,8 +1002,29 @@ EOF2 [[ -e "$root/apt-args" ]] && bad "a version installed before was purged: $(cat "$root/apt-args")" [[ "$(cat "$root/boot/vmlinuz-$kv")" == old-image ]] || bad "the kernel from before was not put back" [[ -f "$root/modules/$kv/kernel/old.ko" && ! -e "$root/modules/$kv/new.ko" ]] || bad "the modules from before were not put back" - [[ "$(cat "$root/boot/initrd.img-$kv")" == "initrd from kernel " ]] || bad "the initramfs was not made again from the old modules: $(cat "$root/boot/initrd.img-$kv")" + [[ "$(cat "$root/boot/initrd.img-$kv")" == old-initrd ]] || bad "the kept initramfs was not put back: $(cat "$root/boot/initrd.img-$kv")" [[ -z "$(compgen -G "$root/boot/.kernel-pop-keep-*")$(compgen -G "$root/modules/.kernel-pop-keep-*")" ]] || bad "the kept copies were left behind" + # No room in /boot for a copy of the initramfs: made again from the old modules + out="$(SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled PREEXIST=1 NO_ROOM=1 run_install signfail-noroom)" && bad "do_install should fail when signing fails under Secure Boot" + [[ "$(cat "$tmp/inst-signfail-noroom/boot/initrd.img-$kv")" == "initrd from kernel " ]] || bad "the initramfs was not made again from the old modules: $(cat "$tmp/inst-signfail-noroom/boot/initrd.img-$kv")" + # Only a leftover modules directory: nothing was installed before, so the + # new packages are purged and the leftover goes too + out="$(SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled LONE_MODS=1 run_install lonemods)" && bad "do_install should fail when signing fails under Secure Boot" + root="$tmp/inst-lonemods" + grep -q "Nothing is left installed" <<< "$out" || bad "a leftover modules directory was taken for an installed kernel: $out" + [[ "$(cat "$root/apt-args" 2>/dev/null)" == "$APT_OPTS purge -y linux-headers-$kv linux-image-$kv" ]] || bad "the new packages were not purged: [$(cat "$root/apt-args" 2>/dev/null)]" + [[ -e "$root/modules/$kv" ]] && bad "the leftover modules directory stayed" + # A stop after dpkg that is not a rollback (update-grub fails): the + # version from before is put back all the same + out="$(SB_ON=1 WITH_KEY=1 SIGN_OK=1 KEY_STATE=enrolled PREEXIST=1 GRUB_FAIL=1 run_install grubfail)" && bad "do_install should fail when update-grub fails" + root="$tmp/inst-grubfail" + grep -q "putting back the $kv installed before" <<< "$out" || bad "a stop after dpkg did not put the old version back: $out" + [[ "$(cat "$root/boot/vmlinuz-$kv")" == old-image && -f "$root/modules/$kv/kernel/old.ko" ]] || bad "a stop after dpkg left the new build in place" + # Putting back fails part way: what is left stays kept, and is named + out="$(SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled PREEXIST=1 RESTORE_MV_FAIL=1 run_install restorefail)" && bad "do_install should fail when signing fails under Secure Boot" + root="$tmp/inst-restorefail" + grep -q "what was kept of it is in .*\.kernel-pop-keep-$kv" <<< "$out" || bad "the kept files should be named: $out" + [[ -f "$root/modules/.kernel-pop-keep-$kv/kernel/old.ko" ]] || bad "the kept modules were deleted after a failed restore" # Installed over an installed version, all well: the kept copies go out="$(SB_ON=1 WITH_KEY=1 SIGN_OK=1 KEY_STATE=enrolled PREEXIST=1 run_install over-ok)" || bad "a reinstall under Secure Boot failed: $out" [[ "$(cat "$tmp/inst-over-ok/boot/vmlinuz-$kv")" == new-image ]] || bad "a good reinstall did not install the new kernel" @@ -1372,6 +1397,9 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" grep -q "SIGN WARNING: could not copy" <<<"$out" || bad "a failed ESP copy was not reported: $out" [[ ! -s "$tmp/fw-calls" ]] || bad "firmware entries changed although a copy to the ESP failed: $(cat "$tmp/fw-calls")" cmp -s "$fesp/EFI/BOOT/BOOTX64.EFI" "$KERNEL_POP_SDBOOT" || bad "a failed copy damaged the loader on the ESP" + # The fallback copy goes first: shim in EFI/ubuntu is not updated before + # it, so the next run still knows the fallback loader as ours + [[ -e "$fesp/EFI/ubuntu/shimx64.efi" ]] && bad "EFI/ubuntu was updated before the fallback copy" unset -f install # An ESP shared with Windows: its fallback loader is left alone (and no From d30d4f5573a7ac2d3180e87ab0d4498d94bd4117 Mon Sep 17 00:00:00 2001 From: "Linnard Alex Brown Jr." Date: Wed, 18 Nov 2026 08:25:49 -0500 Subject: [PATCH 3/4] Review round 2: restore a kept kernel only once dpkg has run The package lock wait and the interrupted-run repair now happen before the kept copy is taken, and the EXIT trap restores only once dpkg -i has really run (KEEP_ARMED, cleared again when dpkg only lost the lock race); a stop before that only drops the copy, leaving /boot, the modules and the ESP as they are. A stop by TERM, HUP or INT never restores: the kept files stay and their paths are logged (on fd 3, so the app sees it). rollback_and_die names the kept paths only when files could not be moved back, says separately when the files are back but the initramfs or ESP copy could not follow, and when nothing was kept. A stale initrd.img-.kept is removed before keeping. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 12 ++++--- scripts/privileged-install.sh | 60 +++++++++++++++++++++++++------- scripts/tests/test-privileged.sh | 40 ++++++++++++++++++++- 3 files changed, 94 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 728548d..9f9814e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -238,10 +238,14 @@ systemd-boot entry); a version that was installed before (its `/boot/vmlinuz-` is there; a rebuild, maybe of the running kernel) is never purged: its kernel, System.map, config and modules are kept before dpkg (`keep_installed_kernel`, hard links), its initramfs copied when -`/boot` has room (else generated again on restore), and moved back. Any -other stop after the copy and before the install finished puts it back too -(`kept_kernel_on_exit`, the EXIT trap); a restore that fails part way leaves -the rest where it was kept and names the paths. Everything the steps after dpkg need (an initramfs tool, +`/boot` has room (else generated again on restore), and moved back. The +copy is taken after the package lock wait and the interrupted-run repair. +Any other stop once `dpkg -i` has really run (`KEEP_ARMED`, set in +`dpkg_install`) and before the install finished puts it back too +(`kept_kernel_on_exit`, the EXIT trap); a stop before that only drops the +copy, and a stop by a signal (TERM, HUP, INT) never restores: the kept files +stay and their paths are logged. A restore that fails part way leaves the +rest where it was kept and names the paths. Everything the steps after dpkg need (an initramfs tool, kernel-install or kernelstub) is checked before dpkg. A queued key is fine: the kernel boots once MOK Manager enrolls it. diff --git a/scripts/privileged-install.sh b/scripts/privileged-install.sh index 7d83757..5742386 100755 --- a/scripts/privileged-install.sh +++ b/scripts/privileged-install.sh @@ -178,10 +178,14 @@ dpkg_install() { wait_for_package_lock finish_interrupted_dpkg rc=0 + # From here on, a stop puts a kept kernel back (kept_kernel_on_exit). + [[ -n "$KEEP_KVER" ]] && KEEP_ARMED=1 out="$(dpkg -i "$@" 2>&1)" || rc=$? printf '%s\n' "$out" if (( rc != 0 && tries < 60 )) \ && grep -qE 'dpkg: error: dpkg (frontend lock|status database|lock) (is|was) locked' <<<"$out"; then + # dpkg could not take its lock: it changed nothing. + KEEP_ARMED=0 tries=$(( tries + 1 )) sleep "$LOCK_POLL" continue @@ -926,7 +930,7 @@ trial_sign_image() { # has room (dracut rewrites an initramfs in place, so a link would not keep # it); otherwise it is generated again from the old modules. Any stop after # that, before the install has finished, puts them back (kept_kernel_on_exit). -KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" +KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" KEEP_ARMED=0 KEEP_SIGNAL="" keep_installed_kernel() { local kver="$1" boot mods f size avail boot="$(boot_dir)" @@ -934,6 +938,7 @@ keep_installed_kernel() { KEEP_BOOT="$boot/.kernel-pop-keep-$kver" KEEP_MODS="$mods/.kernel-pop-keep-$kver" rm -rf "$KEEP_BOOT" "$KEEP_MODS" + rm -f "$boot/initrd.img-$kver.kept" mkdir -m 0700 "$KEEP_BOOT" || return 1 for f in vmlinuz System.map config; do [[ -e "$boot/$f-$kver" ]] || continue @@ -960,7 +965,7 @@ boot_free_bytes() { df -PB1 "$1" 2>/dev/null | awk 'NR == 2 { print $4 }'; } drop_kept_kernel() { [[ -n "$KEEP_BOOT" ]] && rm -rf "$KEEP_BOOT" [[ -n "$KEEP_MODS" ]] && rm -rf "$KEEP_MODS" - KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" + KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" KEEP_ARMED=0 return 0 } @@ -968,18 +973,19 @@ drop_kept_kernel() { kept_paths() { echo "$KEEP_BOOT${KEEP_MODS:+ and $KEEP_MODS}"; } # Put the kept files of back and bring the boot loader's copy in line -# with them. Non-zero when something could not be put back; whatever was not -# moved back stays where it was kept (named in the log), never deleted. +# with them. Returns 2 when kept files could not be moved back (what is left +# stays where it was kept, named in the log, never deleted), 1 when they are +# back but the initramfs or the boot loader's copy could not follow. restore_kept_kernel() { local kver="$1" boot mods f boot="$(boot_dir)" mods="$(modules_dir)" if ! restore_kept_files "$kver"; then log "Could not put back every kept file of $kver; what is left is in $(kept_paths)" - KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" - return 1 + KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" KEEP_ARMED=0 + return 2 fi - KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" + KEEP_BOOT="" KEEP_MODS="" KEEP_KVER="" KEEP_ARMED=0 if [[ -f "$boot/initrd.img-$kver.kept" ]]; then mv -f "$boot/initrd.img-$kver.kept" "$boot/initrd.img-$kver" || return 1 else @@ -1021,8 +1027,23 @@ restore_kept_files() { # since what dpkg left may be unsigned or half installed. Chosen over only # naming the kept files: with Secure Boot enforcing, that version may be the # running kernel, and an unsigned one in its place would not boot again. +# +# Only once dpkg -i has really run (KEEP_ARMED): a stop before that (a +# package lock that stays taken, a refused repair) changed nothing, and the +# kept copy, taken before the wait, may be older than the files now there, +# so it is only dropped. A run ended by a signal never restores: dpkg may +# still be at work or cut off halfway, so the kept files stay where they are +# and their paths are logged. kept_kernel_on_exit() { [[ -n "$KEEP_KVER" ]] || return 0 + if (( ! KEEP_ARMED )); then + drop_kept_kernel + return 0 + fi + if [[ -n "$KEEP_SIGNAL" ]]; then + log "WARNING: the install was stopped ($KEEP_SIGNAL) while $KEEP_KVER was being installed. The $KEEP_KVER installed before was not put back; its files are kept in $(kept_paths). With Secure Boot enforcing, do not reboot into $KEEP_KVER before installing it again." + return 0 + fi log "The install stopped before $KEEP_KVER was ready: putting back the $KEEP_KVER installed before…" restore_kept_kernel "$KEEP_KVER" \ || log "WARNING: the $KEEP_KVER installed before could not be put back completely — it may NOT boot while Secure Boot is enforcing (see above)" @@ -1036,13 +1057,18 @@ kept_kernel_on_exit() { # modules directory and its boot menu entry removed (no postrm hook removes # a systemd-boot entry). rollback_and_die() { - local dir="$1" kver="$2" existed="$3" why="$4" d pkgs=() kept + local dir="$1" kver="$2" existed="$3" why="$4" d pkgs=() kept rc=0 if (( existed )); then - kept="$(kept_paths)" - if [[ -n "$KEEP_KVER" ]] && restore_kept_kernel "$kver"; then - die "$why With Secure Boot enforcing the new build could not boot, so the $kver installed before was put back as it was (kernel, initramfs and modules; the headers are the new build's). Try again, or check the signing setup on the System tab." + if [[ -z "$KEEP_KVER" ]]; then + die "$why A $kver was installed before, but no copy of it was kept, so it was not removed: it may NOT boot while Secure Boot is enforcing. Boot another kernel and install $kver again." fi - die "$why The $kver installed before could not be put back completely, so it may NOT boot while Secure Boot is enforcing; what was kept of it is in $kept. Boot another kernel and install $kver again." + kept="$(kept_paths)" + restore_kept_kernel "$kver" || rc=$? + case "$rc" in + 0) die "$why With Secure Boot enforcing the new build could not boot, so the $kver installed before was put back as it was (kernel, initramfs and modules; the headers are the new build's). Try again, or check the signing setup on the System tab." ;; + 2) die "$why The $kver installed before could not be put back completely, so it may NOT boot while Secure Boot is enforcing; what was kept of it is in $kept. Boot another kernel and install $kver again." ;; + *) die "$why The kernel and modules of the $kver installed before were put back, but its initramfs or its copy on the ESP could not follow (see above), so it may NOT boot while Secure Boot is enforcing. Boot another kernel and install $kver again." ;; + esac fi if [[ "$kver" == "$(uname -r)" ]]; then die "$why $kver is the running kernel, so it was not removed — it will NOT boot again while Secure Boot is enforcing. Install a kernel that boots before rebooting." @@ -1253,7 +1279,11 @@ do_install() { # Everything below works on the private, verified copy only. STAGE_DIR="$(umask 077 && mktemp -d "${KERNEL_POP_STAGING:-/var/tmp}/kernel-pop-install.XXXXXX")" \ || die "Could not create a private staging directory" - trap 'rm -rf "$STAGE_DIR"; kept_kernel_on_exit' EXIT + # fd 3: the trap can fire inside a call whose output goes to the log only. + trap 'rm -rf "$STAGE_DIR"; kept_kernel_on_exit >&3' EXIT + trap 'KEEP_SIGNAL=SIGTERM; exit 143' TERM + trap 'KEEP_SIGNAL=SIGHUP; exit 129' HUP + trap 'KEEP_SIGNAL=SIGINT; exit 130' INT stage_verified_debs "$src" "$STAGE_DIR" local dir="$STAGE_DIR" @@ -1316,6 +1346,10 @@ do_install() { # A rollback (Secure Boot enforcing, the new build cannot boot) puts an # installed version back instead of purging it. if (( existed )) && secure_boot_enforcing; then + # Wait for the package lock and finish an interrupted run first: the + # copy is taken after that, as close to dpkg as it can be. + wait_for_package_lock >>"$LOGFILE" 2>&1 + finish_interrupted_dpkg >>"$LOGFILE" 2>&1 keep_installed_kernel "$kver" \ || { drop_kept_kernel; die "Could not keep a copy of the $kver installed now (is /boot full?), which a failed signing would need to put it back. Nothing was installed."; } fi diff --git a/scripts/tests/test-privileged.sh b/scripts/tests/test-privileged.sh index dcb1470..e797d48 100755 --- a/scripts/tests/test-privileged.sh +++ b/scripts/tests/test-privileged.sh @@ -888,12 +888,17 @@ EOF2 # Only a modules directory left from an earlier kernel of that version if [[ -n "${LONE_MODS:-}" ]]; then mkdir -p "$KERNEL_POP_MODULES/$kv"; echo stale > "$KERNEL_POP_MODULES/$kv/stale.ko"; fi [[ -n "${NO_ROOM:-}" ]] && boot_free_bytes() { echo 0; } + [[ -n "${NO_KEEP:-}" ]] && keep_installed_kernel() { :; } + # shellcheck disable=SC2034 # read by wait_for_package_lock + [[ -n "${LOCK_HELD:-}" ]] && { package_lock_holder() { echo "4883 packagekitd"; }; LOCK_WAIT=0; } [[ -n "${RESTORE_MV_FAIL:-}" ]] && mv() { [[ "$1" == -T ]] && return 1; command mv "$@"; } # Like dpkg: new files are written aside and renamed over the old # names; the systemd-boot hook writes an entry and copies the kernel. dpkg() { + [[ "$1" == --audit && -n "${INTERRUPTED:-}" ]] && echo "half-configured: nvidia-dkms-615" [[ "$1" == -i ]] || return 0 shift; printf '%s\n' "$@" > "$root/dpkg-args" + [[ -n "${SIG_DURING:-}" ]] && kill -TERM "$(cat "$root/pid")" [[ -n "${DPKG_FAIL:-}" ]] && return 1 echo new-image > "$KERNEL_POP_BOOT/.new" && mv -f "$KERNEL_POP_BOOT/.new" "$KERNEL_POP_BOOT/vmlinuz-$kv" if [[ -z "${NO_MODULES:-}" ]]; then @@ -936,7 +941,8 @@ EOF2 # The fake packages hold no image: the trial signing is stubbed (tested on a real package below) trial_sign_image() { [[ -z "${TRIAL_FAIL:-}" ]] || { log "SIGN WARNING: stub trial signing failed"; return 1; }; } dpkg-query() { [[ -n "${PREEXIST:-}" && "$*" == *"linux-image-$kv"* ]] && echo "install ok installed"; } - do_install "$root/dl" + echo "$BASHPID" > "$root/pid" + do_install "$root/dl" 3>&1 ) 2>&1 } count() { grep -c "^\[kernel-pop\] $1" <<< "$2"; } @@ -1025,6 +1031,38 @@ EOF2 root="$tmp/inst-restorefail" grep -q "what was kept of it is in .*\.kernel-pop-keep-$kv" <<< "$out" || bad "the kept files should be named: $out" [[ -f "$root/modules/.kernel-pop-keep-$kv/kernel/old.ko" ]] || bad "the kept modules were deleted after a failed restore" + # Stops before dpkg ran (the package lock stays taken, a repair that would + # remove packages): /boot, the modules and the ESP are left as they are + for case in LOCK_HELD INTERRUPTED; do + out="$(export "$case=1"; SDBOOT=1 SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled PREEXIST=1 APT_SIM="Remv nvidia-dkms-615 [1]" run_install "early-$case")" \ + && bad "$case: do_install should stop before dpkg" + root="$tmp/inst-early-$case" + case "$case" in + LOCK_HELD) grep -q "still in use by packagekitd" <<< "$out" || bad "$case: the lock timeout was not reported: $out" ;; + INTERRUPTED) grep -q "would remove: nvidia-dkms-615" <<< "$out" || bad "$case: the refused repair was not reported: $out" ;; + esac + [[ -e "$root/dpkg-args" ]] && bad "$case: dpkg ran" + [[ -e "$root/ki-args" ]] && bad "$case: the ESP was rewritten: $(cat "$root/ki-args")" + grep -q "putting back" <<< "$out" && bad "$case: a stop before dpkg put files back: $out" + [[ "$(cat "$root/boot/vmlinuz-$kv")" == old-image && "$(cat "$root/boot/initrd.img-$kv")" == old-initrd && -f "$root/modules/$kv/kernel/old.ko" ]] \ + || bad "$case: /boot or the modules changed" + [[ -z "$(compgen -G "$root/boot/.kernel-pop-keep-*")$(compgen -G "$root/modules/.kernel-pop-keep-*")" ]] || bad "$case: kept copies were left behind" + done + # The files are back but the ESP copy cannot follow: said so, no kept paths + out="$(SDBOOT=1 KI_FAIL=1 SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled PREEXIST=1 run_install restore-esp)" && bad "do_install should fail when signing fails under Secure Boot" + grep -q "were put back, but its initramfs or its copy on the ESP could not follow" <<< "$out" || bad "a restore whose ESP copy failed: $out" + grep -q "what was kept of it is in" <<< "$out" && bad "kept paths named although every file was moved back: $out" + # Installed before but nothing kept: never purged, said so + out="$(NO_KEEP=1 SB_ON=1 WITH_KEY=1 KEY_STATE=enrolled PREEXIST=1 run_install nokeep)" && bad "do_install should fail when signing fails under Secure Boot" + grep -q "no copy of it was kept, so it was not removed" <<< "$out" || bad "existed without a kept copy: $out" + [[ -e "$tmp/inst-nokeep/apt-args" ]] && bad "a version installed before was purged without a kept copy" + # Stopped by a signal while dpkg runs: nothing is put back, the kept + # files stay and are named + out="$(SIG_DURING=1 SB_ON=1 WITH_KEY=1 SIGN_OK=1 KEY_STATE=enrolled PREEXIST=1 run_install sigterm)" && bad "a stopped install should fail" + root="$tmp/inst-sigterm" + grep -q "was stopped (SIGTERM).*kept in .*\.kernel-pop-keep-$kv" <<< "$out" || bad "a signal should leave the kept files named: $out" + grep -q "putting back" <<< "$out" && bad "a signal must not put files back: $out" + [[ -f "$root/boot/.kernel-pop-keep-$kv/vmlinuz-$kv" && -f "$root/modules/.kernel-pop-keep-$kv/kernel/old.ko" ]] || bad "a signal deleted the kept files" # Installed over an installed version, all well: the kept copies go out="$(SB_ON=1 WITH_KEY=1 SIGN_OK=1 KEY_STATE=enrolled PREEXIST=1 run_install over-ok)" || bad "a reinstall under Secure Boot failed: $out" [[ "$(cat "$tmp/inst-over-ok/boot/vmlinuz-$kv")" == new-image ]] || bad "a good reinstall did not install the new kernel" From 56cdb9d9704edf1f8c58e58dc9d151316d9f1208 Mon Sep 17 00:00:00 2001 From: "Linnard Alex Brown Jr." Date: Wed, 18 Nov 2026 08:27:50 -0500 Subject: [PATCH 4/4] Removing a kernel also removes copies kept for it Review round 3 nit: a copy kept by an install stopped by a signal stayed in /boot and the modules directory for good once the version was removed. do_remove now deletes that version's kept copies too. Co-Authored-By: Claude Opus 5.5 --- scripts/privileged-install.sh | 3 +++ scripts/tests/test-privileged.sh | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/scripts/privileged-install.sh b/scripts/privileged-install.sh index 5742386..b2c65be 100755 --- a/scripts/privileged-install.sh +++ b/scripts/privileged-install.sh @@ -1648,6 +1648,9 @@ do_remove() { (( rc != 2 )) || die "update-grub failed" remove_signed_marker "$kver" + # A copy kept by an install that was stopped by a signal (see + # keep_installed_kernel) has no use once the version itself is gone. + rm -rf "${boot:?}/.kernel-pop-keep-${kver:?}" "${mods:?}/.kernel-pop-keep-${kver:?}" "$boot/initrd.img-$kver.kept" log "==== Done. Kernel $kver removed. ====" } diff --git a/scripts/tests/test-privileged.sh b/scripts/tests/test-privileged.sh index e797d48..0c49b6c 100755 --- a/scripts/tests/test-privileged.sh +++ b/scripts/tests/test-privileged.sh @@ -1317,7 +1317,13 @@ rm -f "$tmp/dpkg/lock-frontend" "$tmp/dpkg/lock" APT_SIM="Remv linux-generic [6.8.0.40.40]" out="$( (do_remove "$rk") 2>&1)" && bad "a Remv of a metapackage should be refused too" APT_SIM="Purg linux-image-$rk [6.8.0-40.40]" + # copies kept by an install stopped by a signal go with the version + mkdir -p "$KERNEL_POP_BOOT/.kernel-pop-keep-$rk" "$KERNEL_POP_MODULES/.kernel-pop-keep-$rk/kernel" + touch "$KERNEL_POP_BOOT/initrd.img-$rk.kept" "$KERNEL_POP_BOOT/.kernel-pop-keep-6.8.0-41-generic" out="$( (do_remove "$rk") 2>&1)" || bad "a removal without metapackages failed: $out" + [[ -e "$KERNEL_POP_BOOT/.kernel-pop-keep-$rk" || -e "$KERNEL_POP_MODULES/.kernel-pop-keep-$rk" || -e "$KERNEL_POP_BOOT/initrd.img-$rk.kept" ]] \ + && bad "the removed version's kept copies were left behind" + [[ -e "$KERNEL_POP_BOOT/.kernel-pop-keep-6.8.0-41-generic" ]] || bad "another version's kept copy was removed" grep -q "purge -y linux-image-$rk" "$tmp/rm-apt" || bad "the kernel was not purged: [$(cat "$tmp/rm-apt" 2>/dev/null)]" # systemd-boot without kernel-install: the entry goes on the ESP and on XBOOTLDR (