LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Immutable edition: design study (docs/IMMUTABLE.md) and an experimental A/B prototype
Federico Pereira29491b2e60bd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d5e2d3d..c69a5dd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,23 @@ of the matching [GitHub release](https://github.com/lordbasex/LordOS/releases),## [Unreleased]+## [0.8.2] - Unreleased++### Added++- **Design study: an immutable LordOS with A/B system images** ([docs/IMMUTABLE.md](docs/IMMUTABLE.md)).+ It compares dm-verity system partitions, fs-verity, composefs, OSTree, A/B root partitions and+ btrfs snapshots against Debian 13, the Store, the Raspberry Pi 5 and LordOS's threat model, and+ recommends a separate, optional edition: a read-only `/usr` verified by dm-verity in two slots,+ one signed boot image per version, automatic fallback to the previous version when an update+ doesn't start, and `/etc` and the home folders kept on their own partition. The classic edition,+ `install.sh` and in-place updates stay as they are; there is no conversion of existing systems.+- **Experimental build of that design** (`tools/immutable/`, not part of the regular ISO or+ Raspberry Pi image): a disk image for UEFI virtual machines with the A/B layout, a signed+ update into the other slot, and a scripted demonstration in which a deliberately broken version+ fails three times and the machine returns to the previous version on its own. Its payload is a+ minimal Debian 13, not the LordOS desktop yet; the rest of the plan moves to later versions.+## [0.8.1-beta] - 2026-10-19A maintenance and polish release on top of 0.8.0-beta, and the first one that installed systemsdiff --git a/docs/IMMUTABLE.md b/docs/IMMUTABLE.mdnew file mode 100644index 0000000..09ab82f--- /dev/null+++ b/docs/IMMUTABLE.md@@ -0,0 +1,618 @@+# An immutable LordOS (A/B system images): design study++**Status (0.8.2): design study plus an experimental prototype.** Nothing here changes the regular+ISO, the Raspberry Pi image, `install.sh` or the in-place APT updates of [UPDATES.md](UPDATES.md).+The prototype (`tools/immutable/`) builds a separate disk image that boots in a virtual machine; it+is a minimal Debian 13, not the LordOS desktop yet. Every statement below is marked as one of:++- **Verified** — run on VM 122 (Proxmox, Debian 13, QEMU/KVM with UEFI inside it) on 2026-10-19;+- **Checked** — read from Debian 13's packages, kernel configuration or upstream documentation, not run;+- **Design** — a proposal, not built.++This is phase 3 of 3 of "System apps immutable". Phase 1 (0.8.2, [SIGNING.md](SIGNING.md),+"Verified system code") checks LordOS's own JavaScript bundles against a signed manifest; phase 2 marks+system apps as not removable. This study is about the whole system.++## Summary++**Recommendation:** an *image-based* edition built on the systemd model, which Debian 13 already+ships almost completely:++- `/usr` is a **read-only EROFS image on its own partition, verified by dm-verity**, in two slots+ (A and B). The root hash of the running `/usr` is sealed into the kernel command line of a+ **Unified Kernel Image** (UKI), so the boot entry and the system it boots are one signed object.+- **systemd-boot** boots one UKI per installed version and counts boot attempts; a version that+ doesn't reach a healthy desktop three times is abandoned and the previous one boots on its own.+- One **writable root partition** keeps `/etc`, `/var` and `/home`: user data, accounts and+ settings survive every update and every rollback.+- The images are still **built from Debian packages** (the same `.deb`s and package list as the ISO),+ so Debian security updates reach users as new images. Users keep installing apps: `.lpk` apps in+ the home folder as today, and Debian packages as **system extension images** layered over `/usr`+ (later phase).+- The updater is **LordOS's own code** in the package engine (it already has HTTP, OpenPGP+ signatures and SHA-256), following systemd-sysupdate's on-disk conventions, because+ **Debian 13 does not ship systemd-sysupdate** (checked).+- It is a **separate edition**: "LordOS" (classic, apt-managed) stays as it is and stays supported;+ the immutable edition is for new installs from the ISO and a Raspberry Pi image variant. There is+ no in-place migration of existing systems.++**The prototype verified the core of it on a VM** (see "The prototype"): a GPT image with ESP,+two `/usr` slots with dm-verity and a root partition; a signed update written into the inactive slot+and checked against its root hash; the new version booting with boot counting and being marked good;+`/etc` and `/home` kept; a deliberately broken version failing its health check three times and the+machine falling back to the previous version **without anyone touching it**; and a corrupted block of+the running `/usr` being refused by dm-verity. Secure Boot, the TPM, the LordOS desktop on top, the+Raspberry Pi and app layering are **design only**.++**Effort:** about 300–430 hours in five phases after this one (see "Phased plan"); the first usable+experimental edition (PC, UEFI, full desktop, updates from the Store) is phase 1, about 70–100 hours.++## Goals++1. **A read-only, verified `/usr`.** Nothing at run time — not an app, not the user, not root — can+ change a file of the operating system in a way that survives a reboot or goes unnoticed: every+ block is checked against a hash that the boot chain vouches for.+2. **Atomic updates with automatic rollback.** An update is written next to the running system and+ becomes active only by booting it. A power cut in the middle leaves the old system untouched. A+ version that fails to come up is abandoned automatically, and the user can always choose the+ previous version.+3. **User data and configuration preserved.** `/home`, accounts, passwords, network and Wi-Fi+ settings, `/etc` changes and installed apps survive updates and rollbacks.+4. **No regression for the classic edition.** `install.sh` on Debian, apt, the Store's Debian+ packages and the 0.8.1 update path keep working exactly as today.+5. **Low-end hardware first** (a LordOS principle): no extra daemons at run time, reads cost a+ hash per 4 KiB block once, updates don't need twice the RAM, SD cards aren't worn by the scheme.++Not goals: making root powerless at run time (see the threat model), a container-only "everything is+a Flatpak" system, or converting existing installations in place.++## Where LordOS stands today++- `/usr` is an ordinary ext4 directory tree owned by dpkg. Root (or `sudo`) can change any file.+- 0.8.2 phase 1 (`server/src/sec/codesig.c`) checks only LordOS's JavaScript bundles, from inside+ `lord-server`; its threat model says plainly that it does not protect against root, who can+ replace `lord-server` itself (and its compiled-in key).+- Updates are in-place `dpkg` upgrades from the signed APT repository (0.8.1). A broken update is+ fixed by another update; there is no "previous version". A power cut during `dpkg` can leave a+ half-configured system (dpkg recovers most of it, not all).+- On the Raspberry Pi 5 the kernel is not in the repository yet, precisely because a bad kernel+ would leave the board unbootable with no way back ([UPDATES.md](UPDATES.md), "The Raspberry Pi+ kernel"). An A/B scheme with `tryboot` is the missing piece there.++## Threat model++Attackers and failures considered:++| # | Who / what | Example |+|---|---|---|+| T1 | A malicious or compromised app running as the user | a Linux app escaping its restrictions, a hostile `.lpk` |+| T2 | Root at run time | malware that got `sudo`, a compromised root service, a hostile postinst |+| T3 | Offline modification | the disk or SD card edited from another computer; a tampered image; "evil maid" |+| T4 | A broken update | a release that doesn't boot, a kernel that doesn't find the disk, a power cut while updating |+| T5 | Corruption | bit rot, a failing SD card, a bad sector under `/usr` |+| T6 | A hostile mirror or network | a modified image on the download path, a replayed old image |++What each layer stops (✓ stops, ~ partly, ✗ no). "Classic" is today's LordOS with 0.8.2 phase 1.++| | Classic 0.8.2 | Immutable, no Secure Boot (Pi 5 today, PCs with SB off) | Immutable + Secure Boot + measured boot (PC) |+|---|---|---|---|+| T1 app changes system files | ✓ (permissions) | ✓ | ✓ |+| T2 root changes `/usr` at run time | ✗ | ~ (writes to the mounted `/usr` fail; writing the raw partition is caught at read time as I/O errors) | ~ (same) |+| T2 root **persists** a change to `/usr` across reboot | ✗ | ✗ (root rewrites the ESP: a new UKI with a new hash) | ✓ (a UKI not signed with the LordOS key does not boot) |+| T2 root persists through `/etc` or `/var` (a unit in `/etc/systemd`, a cron job, a `.bashrc`) | ✗ | ✗ | ✗ (see below) |+| T3 offline change of `/usr` | ✗ | ✓ detected (dm-verity fails reads) — but the boot partition itself is unsigned, so an offline attacker can replace the kernel and hash | ✓ |+| T3 offline change of `/etc`, `/home` | ✗ | ✗ | ~ (only with the root partition encrypted and sealed to the TPM's measurements) |+| T4 broken update | ~ (fix forward) | ✓ automatic rollback | ✓ |+| T5 corruption of `/usr` | ✗ silent | ✓ detected (verified); with `restart-on-corruption` the other slot boots (design) | ✓ (same) |+| T6 hostile mirror | ✓ (APT signatures) | ✓ (signed SHA256SUMS + root hash) | ✓ |+| T6 rollback to an old, vulnerable image | ~ (APT `Valid-Until` not used yet) | ~ (the updater refuses older versions; the boot menu still offers the previous one by design) | ~ (same; a signed minimum version could be added) |++**What root can still do after this work, honestly:**++- Root can change `/etc`, `/var` and the home folders, and that is where most persistence lives+ (systemd units in `/etc/systemd/system`, timers, `ld.so.preload`, PAM configuration). dm-verity on+ `/usr` does **not** stop a root attacker from coming back after a reboot through `/etc`. The real+ answers are later and harder: signed configuration extensions (`confext`), an `/etc` that the+ system rebuilds from the image plus a small allow-list of user changes, and IPE (the kernel's+ Integrity Policy Enforcement, enabled in Debian 13's kernel: `CONFIG_IPE_PROP_DM_VERITY=y`,+ checked) to allow execution only from verified images. They are listed in phase 5; none is cheap.+- Root can load kernel modules and use `kexec` unless the kernel is in lockdown mode, which Debian+ enables automatically only under Secure Boot.+- Root can write the raw `/usr` partition. dm-verity notices at read time (verified in the+ prototype: I/O errors and a kernel message), and the production option `restart-on-corruption`+ would turn that into a reboot into the other slot. Root can also write a new UKI to the ESP; only+ Secure Boot stops that from booting.++**How it composes with phase 1 (signed code).** With a verified `/usr`, `lord-server`, its+compiled-in release key, the bundles and `code-manifest.json` are all inside the verified image, so+phase 1's stated gap ("root can replace lord-server") closes for anything that must survive a+reboot, as long as the UKI is trusted (Secure Boot on PCs). Phase 1 stays: it costs ~7–34 ms, it+protects the classic edition and development trees, and it gives the clear "this component was+modified" screen instead of an I/O error.++**Secure Boot and measured boot on PCs (design).** The chain would be: firmware (Secure Boot, the+usual third-party CA) → **shim** (signed by that CA; Debian's) → **systemd-boot** (Debian 13 ships a+signed one: `systemd-boot-efi-amd64-signed`, checked) → the **LordOS UKI**, signed with a LordOS+Secure Boot key that the user enrolls once as a Machine Owner Key (shim's MokManager screen on the+first boot after install) → kernel command line with `usrhash=` inside the signed UKI → initrd inside+the signed UKI → dm-verity `/usr`. Because the command line is part of the signed UKI, nobody can+point a signed kernel at a different `/usr`. With a TPM, systemd-stub measures the UKI's sections into+PCR 11; an optionally encrypted root partition can be sealed to a **signed PCR policy**+(`systemd-cryptenroll --tpm2-public-key`), so it unlocks for every LordOS-signed version, including+updates, but not for a foreign kernel. Shipping our own signed shim would need the third-party CA's+review program; enrolling a MOK avoids that and is what users already do for out-of-tree drivers.++**The Raspberry Pi 5.** It has no UEFI Secure Boot. Its firmware has its own signed-boot mode+(a customer key fused into one-time-programmable memory, per board, irreversible), which LordOS+cannot turn on for users. So on the Pi the immutable edition gives integrity at run time,+corruption detection and A/B rollback, **not** protection against an offline attacker who rewrites+the boot partition. That is still a large improvement for the Pi's main failure modes (SD card+corruption, bad kernel updates).++## Options compared++Six ways to make the system immutable. "Fits Debian" means: can we keep building from Debian's+`.deb` packages and keep Debian's security updates flowing.++### A. dm-verity `/usr` partitions, A/B, UKIs (the systemd "image-based OS" model)++The OS is a set of partitions: an ESP with one UKI per version, `/usr` slots each with a verity hash+partition (and optionally a signature partition), and a root partition. Built with `systemd-repart`+(or `mkosi` on top of it), updated with `systemd-sysupdate`, rollback with systemd-boot's boot+assessment. Variants of this design are what Flatcar Container Linux (A/B `/usr` partitions with+dm-verity), GNOME OS (systemd-sysupdate, dm-verity) and KDE Linux (mkosi-built EROFS images updated+by systemd-sysupdate) document publicly; the A/B-partition-plus-verity idea is older still in+embedded systems.++- **Integrity:** strongest of the options: every block, checked by the kernel, root hash in a+ signed UKI. Unchanged blocks cost nothing to verify after the first read.+- **Atomicity / rollback:** the whole `/usr` and kernel switch together on reboot; rollback is+ booting the other entry. Verified in the prototype.+- **Debian fit:** Debian 13 ships `systemd-repart`, `ukify`, `systemd-boot` (with `systemd-bless-boot`+ and `systemd-boot-check-no-failures`), the signed systemd-boot, `systemd-veritysetup`,+ `systemd-sysext`, dracut with `systemd-veritysetup`/`systemd-sysext`/`systemd-repart` modules, EROFS+ and dm-verity in the kernel (`CONFIG_DM_VERITY=m`, `CONFIG_EROFS_FS=m`, root-hash signatures via the+ secondary and platform keyrings), `mkosi` 25 — all checked on VM 122. **It does not ship+ `systemd-sysupdate`** (no package contains it; checked with `apt-cache` and `dpkg -c systemd`), and+ Debian's default `initramfs-tools` cannot set up a verity `/usr` from `usrhash=`; dracut can+ (verified). Debian 13 is merged-`/usr` only, which this model needs (checked: `/bin`, `/lib` are+ symlinks into `/usr`).+- **Cost:** `/usr` must be "hermetic": everything that changes per machine lives in `/etc` or `/var`.+ Debian mostly is, with known exceptions (below). Updates are whole images (deltas later).+- **Pi fit:** dm-verity and EROFS are plain kernel features (the LordOS Pi kernel needs+ `CONFIG_DM_VERITY` and `CONFIG_EROFS_FS` checked/enabled); no systemd-boot, so A/B is done with+ the firmware's `tryboot` instead (below).++### B. fs-verity per file++The kernel seals individual files (ext4, f2fs, btrfs): a sealed file can't change, and its digest+can be signed. Tools are in Debian 13 (`fsverity` 1.6, checked).++- It protects **only files that were sealed**, and nothing in dpkg seals them; root can delete a+ sealed file and put an unsealed one in its place, unless a policy (IPE or IMA appraisal) requires+ a valid digest for everything executed. That policy work is the hard part and is not there.+- No atomicity, no rollback: it is an integrity tool, not an update scheme.+- **Useful as a building block:** for `.lpk` files in the home folder, or with composefs (C). Not+ a whole-system answer by itself. (The first notes for this item named fs-verity; this study+ recommends dm-verity for the system and keeps fs-verity for later, per-file uses.)++### C. composefs (EROFS metadata + overlayfs + fs-verity objects)++A content-addressed object store on a normal writable filesystem, with fs-verity on every object+and a small EROFS image holding the directory tree and the expected digests; overlayfs joins them.+The EROFS image's own fs-verity digest goes on the kernel command line. It is how OSTree's composefs+mode and bootc-based systems verify their trees.++- Integrity close to A (per file instead of per block), with **file-level deduplication**: many+ versions cost only their changed files on disk, and deltas are natural.+- More moving parts: overlayfs semantics, fs-verity on the backing filesystem, the composefs tools.+ **Debian 13 has no composefs package** (checked: no candidate for `composefs`/`libcomposefs1`).+- Worth revisiting once it is packaged in Debian and if A's full-image slots prove too large.++### D. OSTree++A git-like store of system trees, hard-linked into "deployments"; the bootloader picks a deployment;+updates download only changed objects (or static deltas). It has a built-in three-way `/etc` merge,+which solves a problem A has to solve by hand. Debian 13 ships `ostree` 2025.2 (checked). Endless OS+is a Debian-based desktop that has used OSTree for years, which shows that trees built from+Debian packages work with it.++- **Integrity:** without composefs, the deployed files are only protected by a read-only bind+ mount: root can remount and change them. Weaker than A unless combined with C.+- **Rollback:** previous deployments stay bootable; automatic boot assessment needs an extra piece+ (greenboot-style), not in Debian.+- **Debian fit:** building trees is fine; installing extra Debian packages on the client ("package+ layering", as rpm-ostree does for RPM) has no maintained apt equivalent.+- Bigger dependency (libostree, GLib, curl) on every client; LordOS prefers small, own code.++### E. Two full root partitions (A/B root, no verity)++Two copies of the whole root filesystem; the updater writes the inactive one and flips the+bootloader. Vanilla OS's ABRoot (Debian-based) and the embedded updaters RAUC (in Debian 13, checked),+SWUpdate and Mender work like this.++- Simple and robust for **atomicity and rollback**, but without verity it gives **no integrity**:+ root can mount the inactive or active root read-write. With verity it becomes option A with+ `/etc` inside the image, which makes user configuration harder to keep across updates.++### F. Btrfs snapshots ("transactional apt")++The system is a read-only btrfs subvolume; an update is `apt` running inside a new snapshot, which+becomes the default on the next boot (openSUSE MicroOS/Aeon's transactional-update model).++- **Best fit for apt:** users keep installing Debian packages, into a new snapshot.+- **No integrity:** root can flip the subvolume's read-only property. Rollback is good. Btrfs copy-on-+ write on SD cards and very small disks is a cost for the Pi. Every client still runs dpkg+ maintainer scripts, so a broken postinst still breaks the new snapshot (but not the old one).++### Comparison++| | A dm-verity A/B | B fs-verity | C composefs | D OSTree | E A/B root | F btrfs snapshots |+|---|---|---|---|---|---|---|+| Integrity of system files | **strong** (block, kernel, signed UKI) | partial (sealed files only) | strong (per file) | weak (ro bind) | none | none |+| Atomic update | **yes** | no | yes | yes | yes | yes |+| Automatic rollback | **yes** (sd-boot counting, verified) | no | with extra pieces | with extra pieces | yes | with extra pieces |+| In Debian 13 | almost (no sysupdate) | tools only | **no** | yes | partly (RAUC) | yes |+| Keep apt on the client | no (sysext layers) | yes | no | no | no | **yes** |+| Update size | full image (deltas: later) | — | changed files | changed files | full image | changed packages |+| Disk cost | 2 × slot | none | ~1 × + changes | ~1 × + changes | 2 × root | snapshots |+| Raspberry Pi 5 | yes, with `tryboot` | yes | not packaged | possible | yes, with `tryboot` | possible, SD wear |+| Moving parts on the client | kernel + small updater | kernel | kernel + overlayfs + tools | libostree | small updater | btrfs + apt |+| Fits "own small code" | **yes** | yes | partly | no | yes | partly |++Option A is the only one that delivers all three goals with what Debian 13 ships plus a small+updater of our own, and its integrity is the strongest. Its cost — no apt on the client and+full-image downloads — is addressed below (system extensions; chunked deltas).++## Recommended design++### Building images from Debian packages++The image is built on the build machine exactly like the ISO's chroot today (`debootstrap` + the+same package list + `lordos_<version>.deb`), then split:++- `/usr` → **EROFS**, compressed with **lz4hc** (decompression is cheap on low-end CPUs; zstd is an+ option for smaller downloads), built reproducibly (`mkfs.erofs -T0 -U <fixed>`; the prototype gives+ byte-identical blocks for unchanged files, see "Update size") → `veritysetup format` → root hash.+- the kernel, a **dracut** initrd (systemd, dm-verity, EROFS) and the command line with `usrhash=`+ → **UKI** (`ukify`), signed for Secure Boot (phase 2).+- `/etc` and `/var` → the root partition of a fresh install, and a **factory copy** in+ `/usr/share/factory/etc` for updates (below).++So dpkg stays the source of truth for what is in the system, and every Debian security update+becomes a LordOS image release (a weekly security image plus LordOS releases; see "Update size").++### Making Debian's `/usr` hermetic: `/etc`, users, caches++This is where Debian and immutable images rub. Known issues and the planned answer:++| Issue | Answer |+|---|---|+| Packages ship defaults in `/etc` (conffiles), and an update may change them | Each image carries `/usr/share/factory/etc`. On the first boot of a new version, the migration runner (`/usr/lib/lordos/migrate`, already in 0.8.1) does a **three-way merge**: a file the admin never changed (same as the old factory copy) is replaced with the new factory copy; a changed one is kept and the new default goes next to it as `<file>.lordos-new`, reported in the Store; new files are copied. This is how OSTree handles `/etc`. |+| System users and groups made by `adduser` in postinst (`lordos-greeter`, `systemd-*`, `messagebus`…) live in `/etc/passwd` | Ship `sysusers.d` entries for every system user of the image (generated at build time from the chroot's `/etc/passwd`); `systemd-sysusers` creates missing ones on boot. |+| Caches that dpkg triggers rebuild: `ld.so.cache` (in `/etc`!), icon and MIME caches, `gdk-pixbuf` loaders, fontconfig, GSettings schemas | Built at image build time into `/usr`; `ldconfig` at boot only when `/etc/ld.so.conf.d` changed (Debian's `ldconfig.service` already does this with `ConditionNeedsUpdate=/etc`). System extensions trigger a rebuild into `/var/cache` (phase 4). |+| Units enabled with `systemctl enable` create links in `/etc` | Enable LordOS's units from `/usr` (vendor `.wants`/`.requires` links, as the prototype does) or presets applied by the merge; keep the admin's own `systemctl` choices in `/etc`. |+| `/var/lib/dpkg` describes the image, not the machine | Ship it read-only inside `/usr` (`/usr/lib/lordos/dpkg-status`) for the Store's "installed" view and for SBOM-style queries; there is no dpkg database on the client to corrupt. |+| Kernel modules built on the machine (DKMS: some Wi-Fi, out-of-tree GPU drivers) | Not possible on a verified `/usr`. Ship the common ones prebuilt in the image; others need the classic edition. Said clearly in the installer. |+| `install.sh` and Debian derivatives | Classic only: they are someone else's Debian installation. |++### Disk layout: PC (UEFI)++| # | Partition | Type (Discoverable Partitions) | Size | Contents |+|---|---|---|---|---|+| 1 | `lordos-esp` | ESP | 1 GiB | systemd-boot, one UKI per version (`EFI/Linux/lordos_<v>[+tries].efi`), `loader.conf` |+| 2 | `lordos_usr_<v>` | `usr` (x86-64) | 5 GiB | EROFS `/usr`, slot A |+| 3 | `lordos_usr_v_<v>` | `usr-verity` | 64 MiB | dm-verity hash tree of slot A |+| 4 | `lordos_usr_<v>` / `_empty` | `usr` | 5 GiB | slot B |+| 5 | `lordos_usr_v_<v>` / `_empty` | `usr-verity` | 64 MiB | slot B hashes |+| 6 | `lordos-root` | `root` (x86-64) | the rest (min. 8 GiB) | ext4 (or optionally encrypted): `/etc`, `/var`, `/home`, `/swapfile`, `/opt` |++Sizes: the ISO's live system is 1.5 GB uncompressed in 0.7.0 ([ISO.md](ISO.md)); with browsers,+Mesa, firmware and CJK fonts in 0.8.x the `/usr` tree is about 2.5–3 GB, ~1.2–1.6 GB as EROFS/lz4hc+(estimate from the prototype's ratio, 319 MB → 202 MB; **not measured on the full desktop**). A 5 GiB+slot leaves room for years of growth; slot sizes can never change after install, so they are+generous. The hash tree is ~0.8 % of the data (prototype: 1.7 MB for 202 MB). UKIs are ~50 MB with+the prototype's generic initrd (40 MB, every driver); a trimmed initrd brings that to ~25 MB, so+1 GiB of ESP holds plenty. Minimum disk for the immutable edition: 24 GB (classic: 8 GB). The+**installer** (`apps/installer`, `server/src/install/install.c`) gets an "Immutable (experimental)"+choice that writes this layout with `systemd-repart` definitions shipped in the image, and copies+the running slot instead of unsquashing the live system. **BIOS-only PCs:** systemd-boot is UEFI-only,+so they get the classic edition.++### Disk layout: Raspberry Pi 5 (design)++The Pi's firmware reads `autoboot.txt` from the first FAT partition, which can name the boot+partition (`boot_partition=N`) and a different one under `[tryboot]`; `reboot "0 tryboot"` boots the+`[tryboot]` choice **once**, and any later reset returns to the committed one. That is A/B with a+one-shot trial, done by the firmware itself.++| # | Partition | Size | Contents |+|---|---|---|---|+| 1 | `autoboot` (FAT) | 64 MiB | `autoboot.txt` only (`[all] boot_partition=2` / `[tryboot] boot_partition=3`), plus the `ssh`, `remote-desktop`, `lordos-user.txt` switch files |+| 2 | `bootfs-A` (FAT) | 256 MiB | firmware, `kernel_2712.img`, initramfs, DTBs, `config.txt`, `cmdline.txt` with `usrhash=` of slot A |+| 3 | `bootfs-B` (FAT) | 256 MiB | the same for slot B |+| 4–7 | `usr` A, `usr-verity` A, `usr` B, `usr-verity` B | 5 GiB / 64 MiB each | as on the PC (arm64 partition types) |+| 8 | `root` (ext4) | the rest | `/etc`, `/var`, `/home` |++GPT is needed (eight partitions); the Pi 5's bootloader supports GPT and `autoboot.txt`. **Update:**+write the inactive `usr` and `bootfs`, then `reboot "0 tryboot"`. **Commit:** after the health check+passes, rewrite `autoboot.txt` so the new partition is the default (one small write; FAT has no+atomic rename, so what the firmware does with a torn `autoboot.txt` must be tested on the board, and+the write may need to go through two alternating files). **Rollback:** if the trial boot hangs, the hardware **watchdog**+(`dtparam=watchdog=on`, `RuntimeWatchdogSec=` in systemd) resets the board and the firmware boots+the committed partition; if the health check fails, the system simply reboots without `tryboot`.+This also solves the kernel problem of [UPDATES.md](UPDATES.md): the kernel travels inside the+image, with the previous one as the fallback, so Pi kernels can finally be updated from the Store.+Not built or tested; the firmware behaviour is from Raspberry Pi's documentation of `tryboot` and+`autoboot.txt`.++**SD card wear.** `/usr` is never written except by an update (one sequential write of the slot,+~1.5 GB, versus apt's scattered writes of a similar volume for a large upgrade). The root partition+gets the same treatment as today plus `noatime` and a larger ext4 commit interval. Read-only `/usr`+removes the most dangerous failure (a half-written system file after a power cut). The net effect on+wear is neutral-to-better for the system and unchanged for user data.++### Updates++- **Format.** Each version publishes `lordos_usr_<v>.erofs`, `lordos_usr_<v>.verity`,+ `lordos_usr_<v>.roothash` and the signed UKI `lordos_<v>.efi` (Pi: a `bootfs` image), listed in a+ `SHA256SUMS` signed with the LordOS **APT archive key** (OpenPGP Ed25519, which the package engine+ already verifies) — next to the APT repository, e.g. `https://lordos.org/images/stable/<arch>/`.+ The root hash binds the data; the UKI's signature binds the root hash; the `SHA256SUMS` signature+ binds the download.+- **The updater** (design: C, in `server/src/pkg`, a new closed admin action `image-update`; the+ prototype is a shell script with the same steps): check the signature; pick the newest version+ (never older than the running one); invalidate the inactive slot (label `_empty`) *before* writing,+ so a crash never leaves a half slot that looks bootable; write data and hash partitions; **verify+ the written blocks against the root hash** (`veritysetup verify`); set the partition UUIDs derived+ from the root hash and the labels; install the UKI last, as `lordos_<v>+3.efi`. These are+ systemd-sysupdate's conventions (labels `@v`, `+tries` names, `_empty`), so LordOS can switch to+ `systemd-sysupdate` if Debian ships it later, with the same disk.+- **Store → Updates** shows "LordOS 0.9.1 is available" as today; Update downloads and writes the+ inactive slot while the user keeps working; then "Restart required". Nothing is replaced under the+ running session (an improvement over 0.8.1, where files change under it).+- **Update size and bandwidth.** A full image is ~1.2–1.6 GB to download (zstd-19 transfer: the+ prototype's 202 MB EROFS compresses to 167 MB; xz −6 165 MB) against ~6 MB for a `lordos` `.deb`+ today, so full images alone are not acceptable for LordOS users on slow links. Measured on the+ prototype between versions 1 and 2 (a small change in `/usr/lib`): the deterministic EROFS images+ differ in **3 of 51,678 4-KiB blocks**, and `zstd --patch-from` (v1 as dictionary) makes a+ **156 KB** delta instead of 167 MB. Real releases change many packages, and inserting a file+ shifts later data, so fixed offsets won't stay that good; the plan is **content-defined chunking**+ (as casync/desync do): a signed chunk index per version, chunks addressed by SHA-256 and seeded+ from the running slot, so only new chunks are downloaded. Own code in the package engine (phase 4);+ full images remain the fallback. Debian security updates become a weekly image; with chunking the+ download is close to the size of the changed packages.++### Boot assessment and rollback UX++- **Automatic.** A new version boots with 3 tries (`lordos_<v>+3.efi`); systemd-boot renames it on+ every attempt (`+2-1`, `+1-2`, …). When `boot-complete.target` is reached,+ `systemd-bless-boot` renames it to `lordos_<v>.efi` (good). `boot-complete.target` requires the+ **LordOS health check**: in the product, "`lord-sessiond` showed the login screen and the GPU or+ CPU path composited a frame" plus `systemd-boot-check-no-failures`. On failure the health check+ restarts the machine; after the last try systemd-boot treats the entry as bad and boots the+ previous version. In the initrd, `panic=10 rd.emergency=reboot` turns an early failure (no `/usr`,+ a kernel that doesn't find the disk) into a counted attempt too. **Verified in the prototype**+ except the product health check.+- **Telling the user.** After a fallback, the session sees that the booted version is older than the+ newest entry, which is marked bad, and shows: "LordOS 0.9.2 could not start on this computer, so it+ went back to 0.9.1. Your files and settings are unchanged. The update will be offered again when a+ newer version is available." The bad version is remembered and not reinstalled.+- **Choosing the previous version.** The boot menu (shown with a key held, or after a failed boot)+ lists "LordOS 0.9.2" and "LordOS 0.9.1 (previous)". Settings → General → "Restart into the previous+ version" sets a one-shot entry (`LoaderEntryOneShot`, a new closed admin action), and "Keep this+ version" makes it the default.++### Recovery++- **Factory reset:** wipe and recreate the root partition (`systemd-repart` with `FactoryReset=yes`+ definitions, or a boot menu entry with `systemd.factory_reset=1`); `/usr` is untouched, so it takes+ seconds. Offered in Settings for administrators and in the boot menu.+- **Both slots broken** (should not happen: a slot is only replaced when the other one is known+ good): boot the live ISO and reinstall, or repair from it.+- **Corruption:** with `systemd.verity_usr_options=restart-on-corruption` (or `panic-on-corruption`)+ a bad block reboots, the counter drops, and the other slot boots. The prototype uses the default+ (I/O error) to show the error.+- **Forgotten password, broken `/etc`:** as today (live ISO), plus factory reset.++### How users still install Linux apps++The Store keeps working for every kind of app, but where things land changes:++| Kind | Classic | Immutable |+|---|---|---|+| `.lpk` apps | home folder | **the same**, unchanged |+| WebAssembly apps | home folder | the same |+| Debian packages from the Store (Linux apps, codecs, fonts) | `dpkg` into `/usr` | **system extension images** (phase 4): the package engine resolves the packages against the image's own package list, unpacks them (`dpkg-deb -x`, no maintainer scripts), and builds an EROFS `sysext` under `/var/lib/extensions` with an `extension-release` pinned to the image version; `systemd-sysext` overlays it on `/usr`. On every image update the engine rebuilds the extension for the new version before the reboot. Packages whose maintainer scripts do real work (system users, DKMS, services that need enabling) are refused with a clear message, or handled by known rules (sysusers, presets) |+| Large popular apps (browsers, office) | Debian packages | prebuilt, signed **LordOS sysexts** with dm-verity, offered by the Store, or simply included in the image |+| Developer tools (`gcc`, language toolchains, `apt` itself) | apt | a **Debian box**: a `systemd-nspawn` container with full apt, its home shared, apps shown in the launcher (phase 4) |+| Portable per-user apps (single-file app images, user-local installs) | home folder | the same (`~/.local`) |+| `/usr/local` and `/opt` | writable | `/opt` on the root partition (bind or symlink); `/usr/local` as a writable directory from the root partition mounted over the image's empty one |+| Flatpak | not offered | a possible later app source; it is not used for LordOS's own isolation (the policy in [ARCHITECTURE.md](ARCHITECTURE.md) stands). A decision for the project, not part of this design |++Locally built system extensions cannot be signed with a LordOS key, so `systemd-sysext`'s image+policy would accept unsigned extensions only from `/var/lib/extensions`, created by the root-side+package engine, and the Store marks them as "added on this computer". That is the same trust as a+Debian package installed by an administrator today, and less than the verified base.++### Editions and `install.sh`++- **LordOS (classic):** the ISO's default install, the current Pi image and `install.sh` on Debian.+ apt and in-place updates (0.8.1). Supported indefinitely.+- **LordOS Immutable (experimental at first):** an option in the ISO installer (UEFI PCs) and a second+ Raspberry Pi image. Images and updates from the image channel.+- **Migration:** **none in place.** Converting needs repartitioning a disk in use and turning a+ dpkg-managed system into an image, which can't be made safe. Moving is "back up with Backup,+ install the immutable edition, restore the home folder". The live ISO can do it on another disk.++## The prototype++`tools/immutable/build.sh` (POSIX sh, root, Debian 13 amd64) and `tools/immutable/demo.py`. It does+not touch `tools/iso` or `tools/rpi`.++```sh+# on a Debian 13 build host (VM 122), from the repository root+sudo apt-get install --no-install-recommends debootstrap systemd-repart systemd-ukify \+ systemd-boot-efi systemd-boot-tools cryptsetup-bin erofs-utils mtools dosfstools \+ gpg gpg-agent gpgv qemu-system-x86 ovmf zstd+sudo tools/immutable/build.sh all # ~3.5 min: base, releases 1, 2, 3 (bad), disk, publish 1 2+sudo tools/immutable/demo.py # ~8 min: the A/B demonstration in QEMU (KVM, UEFI)+```++What it builds:++- **base:** `debootstrap` trixie (minbase) + systemd, systemd-boot (for `systemd-bless-boot`),+ systemd-cryptsetup, dracut, `linux-image-amd64`, curl, gpgv; a dracut initrd with+ `systemd-veritysetup`; root autologin on the serial console (**prototype only**); a throwaway+ OpenPGP test key whose public half goes into `/usr/share/lordos/immutable/update-keyring.gpg`.+- **release `<v>`:** copies `/usr`, sets `IMAGE_ID=lordos-immutable` / `IMAGE_VERSION=<v>` in+ `os-release`, builds the EROFS image (lz4hc, fixed timestamps and UUID), the dm-verity hash tree,+ and the UKI with `usrhash=`, the verity partition UUIDs derived from the hash and+ `root=PARTLABEL=lordos-root`. Release 3 is built **broken on purpose** (its health check fails).+- **disk:** `systemd-repart` writes the GPT image: ESP 512 MiB (systemd-boot + `lordos_1.efi`),+ slot A (1 GiB) + hashes (64 MiB) with release 1, slot B empty, root ext4 (1 GiB) with `/etc` and+ `/var`. (Slots are small here; see "Disk layouts" for real sizes.)+- **publish:** `SHA256SUMS` over the chosen releases, signed with the test key, served by the demo+ over HTTP.+- **in the image:** `/usr/lib/lordos/immutable/update` (the updater, see "Updates"),+ `/usr/lib/lordos/immutable/health-check` with `lordos-health.service` (required by+ `boot-complete.target`, restarts the machine on failure through `lordos-health-failed.service`),+ both enabled from `/usr` (vendor `.requires` links), not from `/etc`.++### Results (VM 122, 2026-10-19)++++Build: `build.sh all` in **221 s** on VM 122 (4 vCPU Xeon Silver 4108, 4 GB), most of it+`debootstrap` and apt. Sizes: `/usr` tree 319 MB (minimal Debian + kernel modules) → EROFS/lz4hc+**202 MB**, hash tree **1.7 MB**, UKI **50 MB** (40 MB of it the generic dracut initrd). Disk image+3.7 GB apparent, 390 MB actually written (sparse).++The scripted demonstration (`demo.py`, QEMU 10.0 with KVM inside the VM, OVMF, 2 vCPU, 1 GB) ran+end to end with six boots in **175 s** (a run on the previous build) and **281 s** (the final run,+whose first restart spent ~90 s in a shutdown stop job). Excerpts of the final run's serial transcript+(commands as `$`, the console messages of the failed boots as `[console]`; the whole cleaned transcript+is [immutable-demo-transcript.txt](immutable-demo-transcript.txt)):++```text+##### 1. first boot of the factory image+$ /usr/lib/lordos/immutable/update --status+ running: image version 1, /usr = /dev/mapper/usr erofs ro+ slot A: /dev/vda2 label=lordos_usr_1 <- running+ slot B: /dev/vda4 label=_empty+ boot entries (ESP /efi/EFI/Linux):+ lordos_1.efi+$ veritysetup status usr+ /dev/mapper/usr is active and is in use.+ type: VERITY+ status: verified+$ touch /usr/bin/evil+ touch: cannot touch '/usr/bin/evil': Read-only file system+$ echo 'kept across updates' > /etc/lordos-demo.conf; echo 'my file' > /home/demo/notes.txt++##### 2. signed update to version 2 (into slot B)+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642+ signature: good (update key)+ installing version 2 (running 1)+ writing slot B (/dev/vda4, was _empty)+ slot verified against usrhash 5305fd2b…+ version 2 installed; it boots next (3 tries), version 1 stays as the fallback.+ boot entries: lordos_1.efi lordos_2+3.efi+$ systemctl reboot+##### booted after the update+$ cat /usr/lib/lordos/immutable/VERSION+ LordOS immutable prototype, image version 2+$ cat /etc/lordos-demo.conf /home/demo/notes.txt+ kept across updates+ my file+$ journalctl -b -u systemd-bless-boot -o cat+ Marked boot as 'good'. (Boot attempt counter is at 1.)+ boot entries: lordos_1.efi lordos_2.efi++##### 3. a broken release: version 3 (fails its health check) into slot A+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642+ installing version 3 (running 2)+ writing slot A (/dev/vda2, was lordos_usr_1)+ boot entries: lordos_2.efi lordos_3+3.efi+$ systemctl reboot+ [console] lordos: this version failed its health check; restarting in 5 s (attempt 1)+ [console] lordos: this version failed its health check; restarting in 5 s (attempt 2)+ [console] lordos: this version failed its health check; restarting in 5 s (attempt 3)+##### booted on its own after the failed attempts+$ cat /usr/lib/lordos/immutable/VERSION+ LordOS immutable prototype, image version 2+$ /usr/lib/lordos/immutable/update --status+ slot A: /dev/vda2 label=lordos_usr_3+ slot B: /dev/vda4 label=lordos_usr_2 <- running+ boot entries: lordos_2.efi lordos_3+0-3.efi+$ cat /etc/lordos-demo.conf /home/demo/notes.txt+ kept across updates+ my file+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642+ version 3 could not start on this computer (all tries failed); staying on 2 until a newer version is published++##### 3b. a hostile mirror: SHA256SUMS changed on the server (a version 9 added) without the key+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642+ update: SHA256SUMS: BAD or missing signature, nothing installed++##### 4. tampering: corrupt 8 MiB of the running /usr slot underneath dm-verity+$ dd if=/dev/urandom of=/dev/vda4 bs=1M count=8 seek=40 conv=fsync; echo 3 > /proc/sys/vm/drop_caches+$ find /usr -type f -exec cat {} + > /dev/null 2> /tmp/err; grep -c 'Input/output error' /tmp/err+ 228+ [kernel] device-mapper: verity: 253:4: data block 10241 is corrupted+```++What this verifies:++| Claim | Result |+|---|---|+| `/usr` comes from the dm-verity device, mounted read-only, root hash = the UKI's `usrhash=` | ✓ (`veritysetup status`, `findmnt`) |+| Root cannot write `/usr` at run time | ✓ (`Read-only file system`) |+| The updater accepts only a validly signed `SHA256SUMS` and checks every file's SHA-256 | ✓ (a `SHA256SUMS` changed on the server is refused, slots and boot entries unchanged) |+| The written slot is checked block by block against the signed root hash before it can boot | ✓ (`veritysetup verify`, "slot verified") |+| A UKI picks its own slot through the root-hash-derived partition UUIDs | ✓ (versions 1, 2 and 3 booted from the right slot) |+| systemd-boot boots the newest entry, counts tries, and `systemd-bless-boot` marks a healthy boot good | ✓ (`lordos_2+3.efi` → `lordos_2.efi`, "Marked boot as 'good'") |+| A version that fails its health check is retried, then abandoned, and the previous version boots **with no user action** | ✓ (three boots of version 3, `lordos_3+0-3.efi`, version 2 back) |+| `/etc` and `/home` survive an update and a rollback | ✓ |+| A version that used up its tries is not reinstalled | ✓ |+| The factory entry (no counter) needs no assessment | ✓ (`lordos-health` and `systemd-bless-boot` stay inactive on it, as systemd intends for entries without `+tries`) |+| A modified block of the running `/usr` is refused | ✓ (228 files unreadable, `data block … is corrupted`); with `restart-on-corruption` this would reboot into the other slot (not tested) |+| Update delta between two releases (`zstd --patch-from`) | 156 KB instead of 167 MB for a small change; 3 of 51,678 blocks differed (see "Update size and bandwidth") |++### What the prototype does not do (yet)++- The payload is a minimal Debian, not LordOS: no desktop, no `lord-sessiond` health check.+- No Secure Boot (unsigned UKI, OVMF without enrolled keys), no TPM, no verity signature partition.+- The updater is a shell script with `curl` and `gpgv`; the product one is C in the package engine.+- No three-way `/etc` merge (the factory copy is recorded but not used), no sysusers generation,+ no system extensions, no deltas, no Raspberry Pi.+- Root autologin on the serial console: for the scripted demo only.++## Phased plan and effort++Estimates are for one experienced developer working with agents, including VM tests and docs.++| Phase | Version | What | Effort |+|---|---|---|---|+| 0 | 0.8.2 (this item) | Study, prototype (VM-verified A/B with dm-verity, boot counting, automatic rollback) | done |+| 1 | 0.9.x | **Experimental PC edition with the full desktop:** image build from the ISO's chroot (`tools/immutable` grows into it), hermetic `/usr` fixes (factory `/etc` + three-way merge in `migrate`, sysusers for every system user, vendor-enabled units), dracut initrd trimmed, installer option "Immutable (experimental)" with repart definitions, the updater in C (`image-update` admin action, APT-key-signed `SHA256SUMS`), Store → Updates for images, the health check in `lord-sessiond`, fallback notice, "previous version" in Settings, factory reset. VM tests (UEFI), real-PC test | 70–100 h |+| 2 | 0.9.x | **Secure Boot and measured boot:** LordOS Secure Boot key (on the maintainer's Mac, like the other keys), signed UKIs, shim + MOK enrollment step in the installer and its help, verity signature partition, `restart-on-corruption`, optional encrypted root with a signed TPM PCR policy | 40–60 h |+| 3 | 0.9.x–1.0 | **Raspberry Pi 5 immutable image:** GPT + `autoboot.txt`/`tryboot` A/B, watchdog, kernel in the image (closes the Pi kernel gap), LordOS Pi kernel with dm-verity/EROFS checked, board tests (SD and NVMe) | 40–60 h |+| 4 | 1.x | **Apps and bandwidth:** Debian packages as system extensions from the Store, prebuilt signed sysexts, the Debian box container, chunked delta updates (signed chunk index, seeding from the running slot), weekly security images in the release pipeline | 100–140 h |+| 5 | later | **Hardening `/etc` and execution:** signed confexts for LordOS's own configuration, `/etc` reduced to an allow-list of user changes, IPE policy (execute only from verified images), signed minimum version against rollback attacks; decide whether the immutable edition becomes the default | 50–70 h |++Total after this study: **about 300–430 hours**. Each phase is useful on its own and none of them+changes the classic edition.++**What moves to a later version:** everything from phase 1 on. 0.8.2 ships this study and the+experimental build scripts.++## References++- The Discoverable Partitions Specification, the Boot Loader Specification, "Automatic Boot+ Assessment" and the `systemd-repart`, `systemd-sysupdate`, `systemd-sysext`, `systemd-veritysetup`,+ `ukify` and `systemd-bless-boot` manuals (systemd project, version 257 as in Debian 13).+- The kernel's dm-verity, fs-verity, EROFS and IPE documentation.+- Raspberry Pi's documentation of `autoboot.txt`, `tryboot` and the bootloader configuration.+- The public design documentation of Flatcar Container Linux, GNOME OS, KDE Linux, Endless OS,+ OSTree/composefs, Vanilla OS ABRoot, RAUC and openSUSE's transactional-update.diff --git a/docs/README.md b/docs/README.mdindex a822d6d..ab36789 100644--- a/docs/README.md+++ b/docs/README.md@@ -50,6 +50,7 @@ Website: [lordos.org](https://lordos.org) · Brand kit: [LORDOS-BRAND.md](LORDOS| [PRIVACY.md](PRIVACY.md) | App isolation, permissions, and what is isolated today || [FIREWALL.md](FIREWALL.md) | Per-app firewall, restrictions and domain rules || [SIGNING.md](SIGNING.md) | Package signing, trust levels and release signing |+| [IMMUTABLE.md](IMMUTABLE.md) | Design study: an immutable edition with A/B system images (0.8.2, experimental prototype) || [SECURITY-REVIEW-0.8.0.md](SECURITY-REVIEW-0.8.0.md) | Security review before 0.8.0-beta: every finding and its status || [PASSWORDS.md](PASSWORDS.md) | Passwords and the system keyring || [COMPLIANCE.md](COMPLIANCE.md) | Licence compliance, the SBOM, and the standards our processes align with |diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 9c01421..1b02a65 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -508,6 +508,14 @@ Details in `MAIL.md`. Tested on VM 123 against local Dovecot, Postfix and Radica## Before 1.0+- [ ] **Immutable edition (A/B system images)** — 0.8.2 published the design study and an+ experimental, VM-verified prototype (`IMMUTABLE.md`, `tools/immutable/`): read-only `/usr` with+ dm-verity in two slots, one boot image per version, automatic fallback, `/etc` and `/home` kept.+ Still to do, in phases: the full desktop as an image with an "Immutable (experimental)" installer+ option and Store updates (phase 1), Secure Boot and the TPM (phase 2), the Raspberry Pi 5 with+ `tryboot` (phase 3), Debian packages as system extensions and delta updates (phase 4), `/etc` and+ execution hardening (phase 5). The classic edition stays as it is.+- [ ] **Xwayland** (X11 app compatibility). Today LordOS runs Wayland apps only, so programs thatspeak only X11 don't start. Plan:- start `Xwayland` on demand (rootless) when an X11 client connects, with its own `DISPLAY`diff --git a/docs/VM-SETUP.md b/docs/VM-SETUP.mdindex 03f5f28..e12071b 100644--- a/docs/VM-SETUP.md+++ b/docs/VM-SETUP.md@@ -1142,3 +1142,21 @@ folder `~/LordOS-monred`, installed into `/usr/local/lib/lordos` as in step 15 (`lord-qmp-input.py 118 2987 1067` (the VM has two heads, see "Several displays").- The session language, theme and accent were changed for the screenshots and restored from`~/.config-lordos-backup-monred` afterwards.++## Step 29 — 0.8.2: immutable (A/B) prototype (VM 122 `lordos-sandbox`, October 19)++See `IMMUTABLE.md`, "The prototype". On VM 122 (172.17.0.56), in its own folder `~/LordOS-inmut3`+(only `tools/immutable/`) and the work folder `/var/tmp/lordos-immutable` (base tree, images,+throwaway test key). The test images boot in **QEMU inside the VM** (nested KVM, OVMF): the VM's own+disk, boot, network and LordOS installation were not touched.++- **Installed** (`apt-get install --no-install-recommends`): `debootstrap`, `systemd-repart`,+ `systemd-ukify`, `systemd-boot-efi`, `systemd-boot-tools`, `cryptsetup-bin`, `erofs-utils`,+ `qemu-system-x86`, `ovmf`, `gpg`, `gpg-agent`, `gpgv`, `libcryptsetup12`, `mtools`,+ `dosfstools` (and their dependencies). `systemd-boot` itself and dracut were installed only inside+ the image's chroot, never on the VM (dracut would replace the VM's initramfs-tools).+- **Run:** `sudo tools/immutable/build.sh all` and `sudo tools/immutable/demo.py` (as root: `lord`+ is not in the `kvm` group, and it was not added). The demo's HTTP server listens on port 8642+ only while it runs; QEMU uses user-mode networking.+- **Left behind:** the packages above and `/var/tmp/lordos-immutable` (~5 GB; delete it to free the+ space). Nothing else changed.diff --git a/docs/immutable-ab.svg b/docs/immutable-ab.svgnew file mode 100644index 0000000..2604937--- /dev/null+++ b/docs/immutable-ab.svg@@ -0,0 +1,99 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="640" viewBox="0 0 1200 640" font-family="Inter, 'DejaVu Sans', Arial, sans-serif">+ <rect width="1200" height="640" fill="#ffffff"/>+ <text x="40" y="48" font-size="26" font-weight="700" fill="#1d2433">Immutable LordOS (prototype): A/B disk layout and boot assessment</text>+ <text x="40" y="76" font-size="15" fill="#5b6475">GPT disk as built by tools/immutable/build.sh — verified in QEMU (UEFI) on VM 122, 2026-10-19</text>++ <!-- disk layout -->+ <g font-size="14">+ <rect x="40" y="100" width="150" height="110" rx="8" fill="#e8eefc" stroke="#3b5bdb" stroke-width="2"/>+ <text x="115" y="128" text-anchor="middle" font-weight="700" fill="#1d2433">ESP (FAT)</text>+ <text x="115" y="150" text-anchor="middle" fill="#334">systemd-boot</text>+ <text x="115" y="170" text-anchor="middle" fill="#334">lordos_2.efi</text>+ <text x="115" y="190" text-anchor="middle" fill="#334">lordos_3+0-3.efi</text>++ <rect x="200" y="100" width="230" height="110" rx="8" fill="#e6f6ec" stroke="#2f9e44" stroke-width="2"/>+ <text x="315" y="128" text-anchor="middle" font-weight="700" fill="#1d2433">usr slot A (EROFS, ro)</text>+ <text x="315" y="150" text-anchor="middle" fill="#334">lordos_usr_<v></text>+ <text x="315" y="170" text-anchor="middle" fill="#334">UUID = first 128 bits</text>+ <text x="315" y="190" text-anchor="middle" fill="#334">of the root hash</text>++ <rect x="440" y="100" width="90" height="110" rx="8" fill="#e6f6ec" stroke="#2f9e44" stroke-width="2"/>+ <text x="485" y="140" text-anchor="middle" font-weight="700" fill="#1d2433">verity</text>+ <text x="485" y="160" text-anchor="middle" fill="#334">hash</text>+ <text x="485" y="180" text-anchor="middle" fill="#334">tree A</text>++ <rect x="540" y="100" width="230" height="110" rx="8" fill="#fff4e6" stroke="#e8590c" stroke-width="2"/>+ <text x="655" y="128" text-anchor="middle" font-weight="700" fill="#1d2433">usr slot B (EROFS, ro)</text>+ <text x="655" y="150" text-anchor="middle" fill="#334">written by the updater</text>+ <text x="655" y="170" text-anchor="middle" fill="#334">while A runs, checked</text>+ <text x="655" y="190" text-anchor="middle" fill="#334">against the signed hash</text>++ <rect x="780" y="100" width="90" height="110" rx="8" fill="#fff4e6" stroke="#e8590c" stroke-width="2"/>+ <text x="825" y="140" text-anchor="middle" font-weight="700" fill="#1d2433">verity</text>+ <text x="825" y="160" text-anchor="middle" fill="#334">hash</text>+ <text x="825" y="180" text-anchor="middle" fill="#334">tree B</text>++ <rect x="880" y="100" width="280" height="110" rx="8" fill="#f3f0ff" stroke="#7048e8" stroke-width="2"/>+ <text x="1020" y="128" text-anchor="middle" font-weight="700" fill="#1d2433">root (ext4, writable)</text>+ <text x="1020" y="150" text-anchor="middle" fill="#334">/etc /var /home</text>+ <text x="1020" y="170" text-anchor="middle" fill="#334">kept across updates</text>+ <text x="1020" y="190" text-anchor="middle" fill="#334">and rollbacks</text>+ </g>++ <text x="40" y="245" font-size="15" fill="#334">Each UKI carries <tspan font-family="monospace">usrhash=<root hash></tspan> in its sealed command line, so a boot entry can only boot the exact /usr it was built with.</text>++ <!-- flow -->+ <g font-size="14">+ <defs>+ <marker id="a" markerWidth="10" markerHeight="10" refX="9" refY="5" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#5b6475"/></marker>+ </defs>+ <rect x="40" y="280" width="200" height="80" rx="10" fill="#f8f9fb" stroke="#adb5bd"/>+ <text x="140" y="312" text-anchor="middle" font-weight="700" fill="#1d2433">1. Update</text>+ <text x="140" y="334" text-anchor="middle" fill="#334">signed SHA256SUMS,</text>+ <text x="140" y="352" text-anchor="middle" fill="#334">write inactive slot</text>++ <rect x="290" y="280" width="200" height="80" rx="10" fill="#f8f9fb" stroke="#adb5bd"/>+ <text x="390" y="312" text-anchor="middle" font-weight="700" fill="#1d2433">2. New entry</text>+ <text x="390" y="334" text-anchor="middle" fill="#334">lordos_<v>+3.efi</text>+ <text x="390" y="352" text-anchor="middle" fill="#334">3 boot tries</text>++ <rect x="540" y="280" width="200" height="80" rx="10" fill="#f8f9fb" stroke="#adb5bd"/>+ <text x="640" y="312" text-anchor="middle" font-weight="700" fill="#1d2433">3. Restart</text>+ <text x="640" y="334" text-anchor="middle" fill="#334">systemd-boot counts</text>+ <text x="640" y="352" text-anchor="middle" fill="#334">the attempt (+2-1)</text>++ <rect x="790" y="280" width="200" height="80" rx="10" fill="#f8f9fb" stroke="#adb5bd"/>+ <text x="890" y="312" text-anchor="middle" font-weight="700" fill="#1d2433">4. Health check</text>+ <text x="890" y="334" text-anchor="middle" fill="#334">required by</text>+ <text x="890" y="352" text-anchor="middle" fill="#334">boot-complete.target</text>++ <line x1="240" y1="320" x2="286" y2="320" stroke="#5b6475" stroke-width="2" marker-end="url(#a)"/>+ <line x1="490" y1="320" x2="536" y2="320" stroke="#5b6475" stroke-width="2" marker-end="url(#a)"/>+ <line x1="740" y1="320" x2="786" y2="320" stroke="#5b6475" stroke-width="2" marker-end="url(#a)"/>++ <rect x="700" y="420" width="290" height="80" rx="10" fill="#e6f6ec" stroke="#2f9e44" stroke-width="2"/>+ <text x="845" y="452" text-anchor="middle" font-weight="700" fill="#1d2433">OK → marked good</text>+ <text x="845" y="474" text-anchor="middle" fill="#334">systemd-bless-boot renames it</text>+ <text x="845" y="492" text-anchor="middle" fill="#334">to lordos_<v>.efi (verified, v2)</text>++ <rect x="1010" y="420" width="160" height="80" rx="10" fill="#fff0f0" stroke="#e03131" stroke-width="2"/>+ <text x="1090" y="452" text-anchor="middle" font-weight="700" fill="#1d2433">Fails</text>+ <text x="1090" y="474" text-anchor="middle" fill="#334">restart, next try</text>+ <text x="1090" y="492" text-anchor="middle" fill="#334">(+1-2, +0-3)</text>++ <line x1="870" y1="360" x2="850" y2="416" stroke="#2f9e44" stroke-width="2" marker-end="url(#a)"/>+ <line x1="930" y1="360" x2="1060" y2="416" stroke="#e03131" stroke-width="2" marker-end="url(#a)"/>+ <path d="M1090,420 C1090,390 1100,330 994,326" fill="none" stroke="#e03131" stroke-width="2" stroke-dasharray="6 4" marker-end="url(#a)"/>++ <rect x="700" y="540" width="470" height="70" rx="10" fill="#fff4e6" stroke="#e8590c" stroke-width="2"/>+ <text x="935" y="570" text-anchor="middle" font-weight="700" fill="#1d2433">No tries left → entry is bad → previous version boots</text>+ <text x="935" y="592" text-anchor="middle" fill="#334">on its own, from the other slot (verified: v3 ×3 failures → v2)</text>+ <line x1="1090" y1="500" x2="1090" y2="536" stroke="#e8590c" stroke-width="2" marker-end="url(#a)"/>++ <text x="40" y="440" font-size="15" fill="#334">Nothing is replaced under the running system:</text>+ <text x="40" y="462" font-size="15" fill="#334">the old slot stays bootable until the next update</text>+ <text x="40" y="484" font-size="15" fill="#334">overwrites it, and only after the new one was</text>+ <text x="40" y="506" font-size="15" fill="#334">marked good. A corrupted /usr block is refused</text>+ <text x="40" y="528" font-size="15" fill="#334">by dm-verity (I/O error, verified).</text>+ </g>+</svg>diff --git a/docs/immutable-demo-transcript.txt b/docs/immutable-demo-transcript.txtnew file mode 100644index 0000000..f536749--- /dev/null+++ b/docs/immutable-demo-transcript.txt@@ -0,0 +1,146 @@+##### [ 0.0s] copying the factory image (version 1) and fresh UEFI variables+##### [ 4.5s] 1. first boot of the factory image+$ cat /usr/lib/lordos/immutable/VERSION+ LordOS immutable prototype, image version 1, built 2026-10-19T05:14:54Z+$ /usr/lib/lordos/immutable/update --status+ running: image version 1, /usr = /dev/mapper/usr erofs ro+ slot A: /dev/vda2 label=lordos_usr_1 <- running+ slot B: /dev/vda4 label=_empty+ boot entries (ESP /efi/EFI/Linux):+ lordos_1.efi+$ ls /efi > /dev/null; findmnt -lno TARGET,SOURCE,FSTYPE,OPTIONS | grep -E '^(/|/usr|/efi) ' | cut -c1-110+ / /dev/vda6 ext4 rw,relatime+ /usr /dev/mapper/usr erofs ro,relatime,user_xattr,acl,cache_strate+ /efi /dev/vda1 vfat rw,relatime,fmask=0077,dmask=0077,codep+$ veritysetup status usr | sed -n '1,4p;/root hash/p'+ /dev/mapper/usr is active and is in use.+ type: VERITY+ status: verified+ hash type: 1+ root hash: bf374417b142c8bbf506aa09bdeee633e3cfa5f37910872ff4edc24f13ab8dbb+$ touch /usr/bin/evil; echo exit=$?+ touch: cannot touch '/usr/bin/evil': Read-only file system+ exit=1+$ echo 'kept across updates' > /etc/lordos-demo.conf; mkdir -p /home/demo && echo 'my file' > /home/demo/notes.txt; echo ok+ ok+$ systemctl is-active lordos-health systemd-bless-boot; echo+ inactive+ inactive+##### [ 28.2s] 2. signed update to version 2 (into slot B)+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642+ checking http://10.0.2.2:8642+ signature: good (update key)+ installing version 2 (running 1)+ writing slot B (/dev/vda4, was _empty)+ slot verified against usrhash 5305fd2bf370e9b7119ffdd6acd6e128e597c596a163feb4fd950d6e364915a3+ version 2 installed; it boots next (3 tries), version 1 stays as the fallback.+ Restart to finish.+$ /usr/lib/lordos/immutable/update --status+ running: image version 1, /usr = /dev/mapper/usr erofs ro+ slot A: /dev/vda2 label=lordos_usr_1 <- running+ slot B: /dev/vda4 label=lordos_usr_2+ boot entries (ESP /efi/EFI/Linux):+ lordos_1.efi+ lordos_2+3.efi+$ systemctl reboot+##### [ 149.1s] booted after the update+$ cat /usr/lib/lordos/immutable/VERSION+ LordOS immutable prototype, image version 2, built 2026-10-19T05:15:14Z+$ cat /etc/lordos-demo.conf /home/demo/notes.txt+ kept across updates+ my file+$ systemctl is-active lordos-health systemd-bless-boot; journalctl -b -u systemd-bless-boot -o cat | tail -3+ active+ active+ Starting systemd-bless-boot.service - Mark the Current Boot Loader Entry as Good...+ Marked boot as 'good'. (Boot attempt counter is at 1.)+ Finished systemd-bless-boot.service - Mark the Current Boot Loader Entry as Good.+$ /usr/lib/lordos/immutable/update --status+ running: image version 2, /usr = /dev/mapper/usr erofs ro+ slot A: /dev/vda2 label=lordos_usr_1+ slot B: /dev/vda4 label=lordos_usr_2 <- running+ boot entries (ESP /efi/EFI/Linux):+ lordos_1.efi+ lordos_2.efi+##### [ 149.3s] 3. a broken release: version 3 (fails its health check) into slot A+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642+ checking http://10.0.2.2:8642+ signature: good (update key)+ installing version 3 (running 2)+ writing slot A (/dev/vda2, was lordos_usr_1)+ slot verified against usrhash 58641627e865809540d4ee5a93f27e09134584433b2892fc04d3f19ec35aaaff+ version 3 installed; it boots next (3 tries), version 2 stays as the fallback.+ Restart to finish.+$ /usr/lib/lordos/immutable/update --status+ running: image version 2, /usr = /dev/mapper/usr erofs ro+ slot A: /dev/vda2 label=lordos_usr_3+ slot B: /dev/vda4 label=lordos_usr_2 <- running+ boot entries (ESP /efi/EFI/Linux):+ lordos_2.efi+ lordos_3+3.efi+$ systemctl reboot+ [console] lordos: this version failed its health check; restarting in 5 s (systemd-boot counts the attempt)+##### [ 185.4s] version 3 failed its health check (attempt 1); the system restarts itself+ [console] lordos: this version failed its health check; restarting in 5 s (systemd-boot counts the attempt)+##### [ 212.9s] version 3 failed its health check (attempt 2); the system restarts itself+ [console] lordos: this version failed its health check; restarting in 5 s (systemd-boot counts the attempt)+##### [ 240.5s] version 3 failed its health check (attempt 3); the system restarts itself+##### [ 267.9s] booted on its own after the failed attempts+$ cat /usr/lib/lordos/immutable/VERSION+ LordOS immutable prototype, image version 2, built 2026-10-19T05:15:14Z+$ /usr/lib/lordos/immutable/update --status+ running: image version 2, /usr = /dev/mapper/usr erofs ro+ slot A: /dev/vda2 label=lordos_usr_3+ slot B: /dev/vda4 label=lordos_usr_2 <- running+ boot entries (ESP /efi/EFI/Linux):+ lordos_2.efi+ lordos_3+0-3.efi+$ cat /etc/lordos-demo.conf /home/demo/notes.txt+ kept across updates+ my file+$ journalctl -b -1 -u lordos-health -o cat --no-pager | grep health-check+ health-check: FAILED: this test release is built broken on purpose (simulate-broken-release)+$ journalctl --list-boots --no-pager | tail -5+ -4 caac959c230346ad9a4b74a45a360367 Mon 2026-10-19 05:19:11 UTC Mon 2026-10-19 05:19:35 UTC+ -3 631a7513343d442087d2da3ab8603ccf Mon 2026-10-19 05:19:48 UTC Mon 2026-10-19 05:20:01 UTC+ -2 838ac15c526b4d43a464151907ec1c64 Mon 2026-10-19 05:20:14 UTC Mon 2026-10-19 05:20:28 UTC+ -1 81970bae0c824434958bc679dca2bd9f Mon 2026-10-19 05:20:41 UTC Mon 2026-10-19 05:20:55 UTC+ 0 f98762ba2744458b9299f2beb2dcdaea Mon 2026-10-19 05:21:07 UTC Mon 2026-10-19 05:21:15 UTC+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642+ checking http://10.0.2.2:8642+ signature: good (update key)+ version 3 could not start on this computer (all tries failed); staying on 2 until a newer version is published+##### [ 268.3s] 3b. a hostile mirror: SHA256SUMS changed on the server (a version 9 added) without the key+$ /usr/lib/lordos/immutable/update http://10.0.2.2:8642; echo exit=$?+ checking http://10.0.2.2:8642+ update: SHA256SUMS: BAD or missing signature, nothing installed+ exit=1+$ /usr/lib/lordos/immutable/update --status+ running: image version 2, /usr = /dev/mapper/usr erofs ro+ slot A: /dev/vda2 label=lordos_usr_3+ slot B: /dev/vda4 label=lordos_usr_2 <- running+ boot entries (ESP /efi/EFI/Linux):+ lordos_2.efi+ lordos_3+0-3.efi+##### [ 274.6s] 4. tampering: corrupt 8 MiB of the running /usr slot's blocks underneath dm-verity+$ DATA=$(veritysetup status usr | awk '/data device/ {print $3}'); echo $DATA+ /dev/vda4+$ dd if=/dev/urandom of=$DATA bs=1M count=8 seek=40 conv=fsync status=none; echo 3 > /proc/sys/vm/drop_caches; echo written+ written+$ find /usr -type f -exec cat {} + > /dev/null 2> /tmp/err; echo read-errors=$(grep -c 'Input/output error' /tmp/err)+ [kernel] device-mapper: verity: 253:4: data block 10241 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10241 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10241 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10280 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10280 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10280 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10901 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10901 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10901 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10862 is corrupted+ read-errors=228+$ dmesg | grep -m3 'is corrupted'+ [kernel] device-mapper: verity: 253:4: data block 10241 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10241 is corrupted+ [kernel] device-mapper: verity: 253:4: data block 10241 is corrupted+##### [ 281.4s] donediff --git a/tools/immutable/build.sh b/tools/immutable/build.shnew file mode 100755index 0000000..dfd8904--- /dev/null+++ b/tools/immutable/build.sh@@ -0,0 +1,276 @@+#!/bin/sh+# build.sh — EXPERIMENTAL immutable (A/B) LordOS disk image: the prototype of docs/IMMUTABLE.md.+#+# It does not touch the regular ISO (tools/iso) or Raspberry Pi (tools/rpi) builds. What it makes:+# a GPT disk image for UEFI PCs (virtual machines) with+# ESP (systemd-boot + one Unified Kernel Image per installed version, with boot counting)+# usr slot A + its dm-verity hash partition (read-only EROFS, the running version)+# usr slot B + its dm-verity hash partition (empty until the first update)+# root (ext4): /etc, /var, /home — the only writable part, kept across updates+# and the update artifacts (usr image, verity hash, UKI, signed SHA256SUMS) that+# /usr/lib/lordos/immutable/update installs into the other slot.+#+# The payload is a minimal Debian 13 with systemd, NOT the LordOS desktop yet (see docs/IMMUTABLE.md,+# "The prototype"). Updates are signed with a throwaway test key made in the work folder, never with+# a LordOS release key.+#+# Usage (as root, on Debian 13 amd64, from the repository root):+# sudo tools/immutable/build.sh base [work] # debootstrap + kernel + initrd (cached)+# sudo tools/immutable/build.sh release [work] <version> [bad] # usr image, verity, UKI for <version>+# sudo tools/immutable/build.sh disk [work] <version> # disk.raw with <version> in slot A+# sudo tools/immutable/build.sh publish [work] <v>... # signed SHA256SUMS over those releases+# sudo tools/immutable/build.sh all [work] # base, releases 1, 2 and 3 (bad), disk 1, publish 1 2+# Default work folder: /var/tmp/lordos-immutable. Versions are plain integers here (1, 2, 3).+# Packages it needs: see docs/IMMUTABLE.md, "Building the prototype".+set -eu++[ "$(id -u)" = 0 ] || { echo "build.sh: run as root (sudo)" >&2; exit 1; }+HERE=$(cd "$(dirname "$0")" && pwd)+CMD=${1:-}+[ $# -gt 0 ] && shift+WORK=/var/tmp/lordos-immutable+case "${1:-}" in /*) WORK=$1; shift ;; esac+MIRROR=${MIRROR:-http://deb.debian.org/debian}+SUITE=trixie+BASE="$WORK/base"+OUT="$WORK/out"+KEYS="$WORK/keys"+# Slot sizes are fixed for the life of an installation: a later release must fit. The usr image of+# this prototype is ~0.3 GB; the LordOS desktop's is ~2.5 GB (docs/IMMUTABLE.md, "Disk layouts").+SLOT_MB=${SLOT_MB:-1024}+HASH_MB=${HASH_MB:-64}+ROOT_MB=${ROOT_MB:-1024}+UKI_TRIES=${UKI_TRIES:-3}++for t in debootstrap mkfs.erofs veritysetup systemd-repart ukify mcopy mkfs.vfat gpg; do+ command -v "$t" >/dev/null || { echo "build.sh: missing $t (docs/IMMUTABLE.md, building the prototype)" >&2; exit 1; }+done++say() { echo "== $*"; }++umount_base() {+ for m in dev/pts dev proc sys run; do+ mountpoint -q "$BASE/$m" 2>/dev/null && umount -l "$BASE/$m" || true+ done+}++# hex root hash → the two partition UUIDs the Discoverable Partitions Specification derives from it+# (first 128 bits: data partition, last 128 bits: verity partition)+uuid_of() { echo "$1" | sed 's/^\(.\{8\}\)\(.\{4\}\)\(.\{4\}\)\(.\{4\}\)\(.\{12\}\).*/\1-\2-\3-\4-\5/'; }++test_key() {+ [ -s "$KEYS/update-keyring.gpg" ] && return 0+ say "throwaway update signing key (TEST ONLY) in $KEYS"+ mkdir -p "$KEYS"; chmod 700 "$KEYS"+ GNUPGHOME="$KEYS/gnupg"; export GNUPGHOME; mkdir -p "$GNUPGHOME"; chmod 700 "$GNUPGHOME"+ gpg --batch --quiet --passphrase '' --quick-gen-key 'LordOS immutable prototype TEST key' ed25519 sign 1y+ gpg --batch --export > "$KEYS/update-keyring.gpg"+}++cmd_base() {+ test_key+ umount_base+ trap umount_base EXIT+ rm -rf "$BASE"; mkdir -p "$BASE" "$OUT"+ say "debootstrap $SUITE (minbase)"+ debootstrap --variant=minbase --include=systemd,systemd-sysv,udev,kmod,dbus \+ "$SUITE" "$BASE" "$MIRROR" > "$WORK/debootstrap.log" 2>&1 || { tail -20 "$WORK/debootstrap.log"; exit 1; }+ for m in dev dev/pts proc sys run; do mount --bind "/$m" "$BASE/$m"; done+ cat > "$BASE/etc/apt/sources.list" <<EOF+deb $MIRROR $SUITE main+deb $MIRROR $SUITE-updates main+deb http://security.debian.org/debian-security $SUITE-security main+EOF+ # dracut first, so linux-image-amd64 doesn't pull initramfs-tools: Debian's initramfs-tools cannot+ # set up a dm-verity /usr from usrhash=, dracut's systemd-veritysetup module can+ chroot "$BASE" sh -c 'export DEBIAN_FRONTEND=noninteractive+ apt-get update -q && apt-get install -y -q --no-install-recommends dracut dracut-core \+ systemd-cryptsetup cryptsetup-bin systemd-boot systemd-resolved \+ e2fsprogs fdisk util-linux gpgv curl ca-certificates iproute2 procps less \+ && apt-get install -y -q --no-install-recommends linux-image-amd64 && apt-get clean' \+ > "$WORK/apt.log" 2>&1 || { tail -30 "$WORK/apt.log"; exit 1; }+ KVER=$(find "$BASE/lib/modules" -mindepth 1 -maxdepth 1 -printf '%f\n' | sort -V | tail -1)+ echo "$KVER" > "$WORK/kver"++ say "configuration (kernel $KVER)"+ echo lordos-immutable > "$BASE/etc/hostname"+ printf '127.0.0.1 localhost\n127.0.1.1 lordos-immutable\n' > "$BASE/etc/hosts"+ : > "$BASE/etc/machine-id"+ # PROTOTYPE ONLY: root logs in on the serial console without a password, for the scripted demo+ mkdir -p "$BASE/etc/systemd/system/[email protected]"+ # shellcheck disable=SC2016 # $TERM is for systemd to expand, not this shell+ printf '[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin root --keep-baud 115200 %%I $TERM\n' \+ > "$BASE/etc/systemd/system/[email protected]/autologin.conf"+ mkdir -p "$BASE/etc/systemd/network"+ printf '[Match]\nName=en*\n[Network]\nDHCP=yes\n' > "$BASE/etc/systemd/network/20-dhcp.network"+ chroot "$BASE" systemctl enable systemd-networkd systemd-resolved >/dev/null 2>&1 || true+ # the ESP is mounted at /efi (systemd-bless-boot and the updater look there)+ mkdir -p "$BASE/efi"+ printf 'PARTLABEL=lordos-esp /efi vfat umask=0077,x-systemd.automount 0 2\n' > "$BASE/etc/fstab"++ # LordOS's pieces: updater, health check (boot assessment), the update key+ install -D -m 0755 "$HERE/files/update" "$BASE/usr/lib/lordos/immutable/update"+ install -D -m 0755 "$HERE/files/health-check" "$BASE/usr/lib/lordos/immutable/health-check"+ install -D -m 0644 "$HERE/files/lordos-health.service" "$BASE/usr/lib/systemd/system/lordos-health.service"+ install -D -m 0644 "$HERE/files/lordos-health-failed.service" "$BASE/usr/lib/systemd/system/lordos-health-failed.service"+ install -D -m 0644 "$KEYS/update-keyring.gpg" "$BASE/usr/share/lordos/immutable/update-keyring.gpg"+ # enabled from /usr (a vendor .requires link), not /etc: a unit a later release adds is+ # enabled by that release's image alone+ mkdir -p "$BASE/usr/lib/systemd/system/boot-complete.target.requires"+ ln -sf ../lordos-health.service "$BASE/usr/lib/systemd/system/boot-complete.target.requires/lordos-health.service"+ ln -sf ../systemd-boot-check-no-failures.service \+ "$BASE/usr/lib/systemd/system/boot-complete.target.requires/systemd-boot-check-no-failures.service"++ say "initrd (dracut, systemd + dm-verity + EROFS)"+ chroot "$BASE" dracut --force --no-hostonly --kver "$KVER" \+ --add "systemd systemd-veritysetup dm" --omit "plymouth" \+ --add-drivers "erofs dm-verity ext4 vfat virtio_blk virtio_scsi virtio_pci sd_mod nvme ahci" \+ /boot/initrd.lordos > "$WORK/dracut.log" 2>&1 || { tail -30 "$WORK/dracut.log"; exit 1; }+ umount_base+ trap - EXIT+ # factory copy of /etc: what a release ships as defaults, for the three-way /etc merge+ # (docs/IMMUTABLE.md, "/etc"); the prototype only records it+ rm -rf "$BASE/usr/share/factory/etc"; mkdir -p "$BASE/usr/share/factory"+ cp -a "$BASE/etc" "$BASE/usr/share/factory/etc"+ say "base ready: $BASE ($(du -sh "$BASE/usr" | cut -f1) in /usr)"+}++cmd_release() {+ V=${1:?version}; BAD=${2:-}+ case "$V" in *[!0-9]*|'') echo "build.sh: version must be an integer" >&2; exit 1 ;; esac+ [ -d "$BASE/usr" ] || { echo "build.sh: run 'base' first" >&2; exit 1; }+ KVER=$(cat "$WORK/kver")+ R="$OUT/$V"; T="$WORK/tree-$V"+ rm -rf "$R" "$T"; mkdir -p "$R" "$T"+ say "release $V${BAD:+ (bad: fails its health check)}"+ cp -a "$BASE/usr" "$T/usr"+ # identity of this image version (os-release IMAGE_ID / IMAGE_VERSION, as systemd expects)+ sed -i '/^IMAGE_ID=/d;/^IMAGE_VERSION=/d' "$T/usr/lib/os-release"+ printf 'IMAGE_ID=lordos-immutable\nIMAGE_VERSION=%s\n' "$V" >> "$T/usr/lib/os-release"+ printf 'LordOS immutable prototype, image version %s, built %s\n' "$V" "$(date -u +%FT%TZ)" \+ > "$T/usr/lib/lordos/immutable/VERSION"+ if [ "$BAD" = bad ]; then : > "$T/usr/lib/lordos/immutable/simulate-broken-release"; fi++ # read-only EROFS (lz4hc: fast to decompress on low-end CPUs), fixed timestamps and UUID so the+ # same tree gives the same bytes+ mkfs.erofs -zlz4hc,12 -T0 -U "6c6f7264-6f73-4000-8000-$(printf %012d "$V")" \+ "$R/lordos_usr_$V.erofs" "$T/usr" > "$WORK/erofs-$V.log" 2>&1 || { tail "$WORK/erofs-$V.log"; exit 1; }+ veritysetup format "$R/lordos_usr_$V.erofs" "$R/lordos_usr_$V.verity" \+ --root-hash-file="$R/lordos_usr_$V.roothash" > "$WORK/verity-$V.log"+ H=$(cat "$R/lordos_usr_$V.roothash")+ U1=$(uuid_of "$H"); U2=$(uuid_of "$(echo "$H" | cut -c33-64)")+ D=$(stat -c %s "$R/lordos_usr_$V.erofs"); HS=$(stat -c %s "$R/lordos_usr_$V.verity")+ [ "$D" -le $((SLOT_MB * 1048576)) ] && [ "$HS" -le $((HASH_MB * 1048576)) ] \+ || { echo "build.sh: release $V does not fit the slots ($D / $HS bytes)" >&2; exit 1; }++ # The kernel command line is sealed into the UKI: usrhash pins this exact /usr; the verity+ # devices are found by the partition UUIDs derived from it, so the UKI picks its own slot.+ CMDLINE="usrhash=$H systemd.verity_usr_data=PARTUUID=$U1 systemd.verity_usr_hash=PARTUUID=$U2"+ CMDLINE="$CMDLINE mount.usr=/dev/mapper/usr mount.usrfstype=erofs mount.usrflags=ro"+ CMDLINE="$CMDLINE root=PARTLABEL=lordos-root rw console=ttyS0,115200 panic=10 rd.emergency=reboot rd.shell=0"+ ukify build --linux="$BASE/boot/vmlinuz-$KVER" --initrd="$BASE/boot/initrd.lordos" \+ --cmdline="$CMDLINE" --os-release="@$T/usr/lib/os-release" --uname="$KVER" \+ --output="$R/lordos_$V.efi" > "$WORK/ukify-$V.log" 2>&1 || { tail "$WORK/ukify-$V.log"; exit 1; }+ rm -rf "$T"+ say "release $V: usr $(du -h "$R/lordos_usr_$V.erofs" | cut -f1), verity $(du -h "$R/lordos_usr_$V.verity" | cut -f1), UKI $(du -h "$R/lordos_$V.efi" | cut -f1), usrhash $H"+}++cmd_disk() {+ V=${1:?version}+ R="$OUT/$V"+ [ -s "$R/lordos_$V.efi" ] || { echo "build.sh: run 'release $V' first" >&2; exit 1; }+ H=$(cat "$R/lordos_usr_$V.roothash")+ U1=$(uuid_of "$H"); U2=$(uuid_of "$(echo "$H" | cut -c33-64)")+ S="$WORK/stage"; DEF="$WORK/repart.d"+ rm -rf "$S" "$DEF"; mkdir -p "$S/esp/EFI/BOOT" "$S/esp/EFI/systemd" "$S/esp/EFI/Linux" "$S/esp/loader" "$S/rootpart" "$DEF"+ say "disk image with release $V in slot A"+ cp /usr/lib/systemd/boot/efi/systemd-bootx64.efi "$S/esp/EFI/BOOT/BOOTX64.EFI"+ cp /usr/lib/systemd/boot/efi/systemd-bootx64.efi "$S/esp/EFI/systemd/systemd-bootx64.efi"+ printf 'timeout 3\neditor no\nauto-entries no\nauto-firmware no\n' > "$S/esp/loader/loader.conf"+ # the factory image's own version is already known good: no boot counter+ cp "$R/lordos_$V.efi" "$S/esp/EFI/Linux/lordos_$V.efi"+ # root partition: everything but /usr; merged-/usr symlinks (Debian 13 is merged-/usr only)+ (cd "$BASE" && tar --exclude=./usr/* --exclude=./proc/* --exclude=./sys/* --exclude=./dev/* \+ --exclude=./run/* --exclude=./boot/* -cf - .) | tar -C "$S/rootpart" -xf -+ cat > "$DEF/10-esp.conf" <<EOF+[Partition]+Type=esp+Label=lordos-esp+Format=vfat+CopyFiles=/esp:/+SizeMinBytes=512M+SizeMaxBytes=512M+EOF+ cat > "$DEF/20-usr-a.conf" <<EOF+[Partition]+Type=usr+Label=lordos_usr_$V+UUID=$U1+CopyBlocks=$R/lordos_usr_$V.erofs+SizeMinBytes=${SLOT_MB}M+SizeMaxBytes=${SLOT_MB}M+EOF+ cat > "$DEF/21-usr-a-verity.conf" <<EOF+[Partition]+Type=usr-verity+Label=lordos_usr_v_$V+UUID=$U2+CopyBlocks=$R/lordos_usr_$V.verity+SizeMinBytes=${HASH_MB}M+SizeMaxBytes=${HASH_MB}M+EOF+ cat > "$DEF/30-usr-b.conf" <<EOF+[Partition]+Type=usr+Label=_empty+SizeMinBytes=${SLOT_MB}M+SizeMaxBytes=${SLOT_MB}M+EOF+ cat > "$DEF/31-usr-b-verity.conf" <<EOF+[Partition]+Type=usr-verity+Label=_empty+SizeMinBytes=${HASH_MB}M+SizeMaxBytes=${HASH_MB}M+EOF+ cat > "$DEF/40-root.conf" <<EOF+[Partition]+Type=root+Label=lordos-root+Format=ext4+CopyFiles=/rootpart:/+SizeMinBytes=${ROOT_MB}M+EOF+ rm -f "$OUT/disk.raw"+ systemd-repart --empty=create --size=auto --sector-size=512 --dry-run=no --no-pager --definitions="$DEF" \+ --copy-source="$S" "$OUT/disk.raw" > "$WORK/repart.log" 2>&1 || { tail -30 "$WORK/repart.log"; exit 1; }+ rm -rf "$S"+ sfdisk -l "$OUT/disk.raw"+ say "disk ready: $OUT/disk.raw ($(du -h --apparent-size "$OUT/disk.raw" | cut -f1), $(du -h "$OUT/disk.raw" | cut -f1) on disk)"+}++cmd_publish() {+ [ $# -gt 0 ] || { echo "build.sh: publish needs the versions to offer" >&2; exit 1; }+ P="$OUT/updates"+ rm -rf "$P"; mkdir -p "$P"+ for V in "$@"; do+ [ -s "$OUT/$V/lordos_$V.efi" ] || { echo "build.sh: no release $V" >&2; exit 1; }+ cp "$OUT/$V"/lordos_* "$P/"+ done+ chmod 0644 "$P"/lordos_*+ (cd "$P" && sha256sum lordos_* > SHA256SUMS)+ GNUPGHOME="$KEYS/gnupg"; export GNUPGHOME+ gpg --batch --yes --detach-sign --output "$P/SHA256SUMS.gpg" "$P/SHA256SUMS"+ gpgv --keyring "$KEYS/update-keyring.gpg" "$P/SHA256SUMS.gpg" "$P/SHA256SUMS" 2>&1 | tail -1+ say "update server folder: $P (serve it over HTTP; the guest reaches the host at 10.0.2.2)"+ ls -l "$P"+}++case "$CMD" in+ base) cmd_base ;;+ release) cmd_release "$@" ;;+ disk) cmd_disk "$@" ;;+ publish) cmd_publish "$@" ;;+ all) cmd_base; cmd_release 1; cmd_release 2; cmd_release 3 bad; cmd_disk 1; cmd_publish 1 2 ;;+ *) sed -n '2,24p' "$0"; exit 2 ;;+esacdiff --git a/tools/immutable/demo.py b/tools/immutable/demo.pynew file mode 100755index 0000000..8d4a761--- /dev/null+++ b/tools/immutable/demo.py@@ -0,0 +1,204 @@+#!/usr/bin/env python3+"""demo.py — boots the EXPERIMENTAL immutable LordOS image (tools/immutable/build.sh) in QEMU and+runs the A/B demonstration of docs/IMMUTABLE.md over the serial console:++ 1. factory image (version 1): /usr is dm-verity + read-only, /etc and /home writable+ 2. signed update to version 2 into slot B, restart, boot counting, entry blessed, data kept+ 3. update to version 3 (built broken on purpose) into slot A: it fails its health check,+ systemd-boot spends its tries and falls back to version 2 on its own; it is not reinstalled+ 3b. a SHA256SUMS changed on the server without the key is refused before anything is written+ 4. a corrupted block of the running /usr is refused by dm-verity (I/O error)++Usage (on the build host, Debian 13 with qemu-system-x86 and ovmf, as root: the work folder is+root's and the demo re-publishes the update folder with build.sh):+ sudo tools/immutable/demo.py [work folder] # default /var/tmp/lordos-immutable+It never touches the built disk.raw: it boots a copy. The transcript goes to <work>/demo/transcript.txt.+The update server is a local HTTP server on the build host (the guest sees it at 10.0.2.2).+"""+import functools+import http.server+import os+import re+import select+import shutil+import subprocess+import sys+import threading+import time++WORK = sys.argv[1] if len(sys.argv) > 1 else "/var/tmp/lordos-immutable"+HERE = os.path.dirname(os.path.abspath(__file__))+OUT = os.path.join(WORK, "out")+DEMO = os.path.join(WORK, "demo")+PORT = 8642+PROMPT = re.compile(rb"root@lordos-immutable:[^#]*# $")+ANSI = re.compile(rb"\x1b\[[0-9;=?]*[A-Za-z]|\x1b[()][A-Z0-9]|\r")++os.makedirs(DEMO, exist_ok=True)+log = open(os.path.join(DEMO, "transcript.txt"), "wb")+T0 = time.time()+++def note(msg):+ line = f"\n##### [{time.time() - T0:6.1f}s] {msg}\n"+ sys.stdout.write(line)+ sys.stdout.flush()+ log.write(line.encode())+ log.flush()+++class Guest:+ def __init__(self, disk, vars_fd):+ cmd = [+ "qemu-system-x86_64", "-enable-kvm", "-machine", "q35", "-cpu", "host", "-smp", "2",+ "-m", "1024", "-display", "none", "-serial", "stdio", "-monitor", "none",+ "-drive", "if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd",+ "-drive", f"if=pflash,format=raw,file={vars_fd}",+ "-drive", f"file={disk},format=raw,if=virtio,cache=unsafe",+ "-nic", "user,model=virtio-net-pci",+ ]+ self.p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)+ self.buf = b""++ def expect(self, pattern, timeout=180):+ rx = re.compile(pattern) if isinstance(pattern, bytes) else pattern+ end = time.time() + timeout+ while True:+ m = rx.search(self.buf)+ if m:+ out = self.buf[: m.end()]+ self.buf = self.buf[m.end():]+ return out+ left = end - time.time()+ if left <= 0:+ raise TimeoutError(f"timeout waiting for {rx.pattern!r}; last output: {self.buf[-600:]!r}")+ r, _, _ = select.select([self.p.stdout], [], [], min(left, 1.0))+ if r:+ chunk = os.read(self.p.stdout.fileno(), 65536)+ if not chunk:+ raise EOFError("qemu exited")+ clean = ANSI.sub(b"", chunk)+ log.write(clean)+ log.flush()+ self.buf += clean++ def send(self, text):+ self.p.stdin.write(text.encode())+ self.p.stdin.flush()++ def run(self, command, timeout=300):+ # the guest's echo is off (login()); the transcript shows each command as "$ <command>"+ log.write(f"$ {command}\n".encode())+ self.send(command + "\n")+ out = self.expect(PROMPT, timeout)+ return out.decode(errors="replace")++ def login(self, timeout=240):+ """Waits for a fresh boot's automatic serial login and turns the echo off."""+ self.expect(rb"login: root \(automatic login\)", timeout)+ self.expect(PROMPT, 60)+ self.send("stty -echo; bind 'set enable-bracketed-paste off'; export SYSTEMD_COLORS=0 SYSTEMD_PAGER=\n")+ self.expect(PROMPT, 30)++ def reboot(self):+ log.write(b"$ systemctl reboot\n")+ self.send("systemctl reboot\n")++ def stop(self):+ self.p.kill()+ self.p.wait()+++class QuietHandler(http.server.SimpleHTTPRequestHandler):+ def log_message(self, *args):+ pass+++def serve(folder):+ handler = functools.partial(QuietHandler, directory=folder)++ srv = http.server.ThreadingHTTPServer(("0.0.0.0", PORT), handler)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ return srv+++def publish(*versions):+ subprocess.run(["sudo", "env", "PATH=/usr/sbin:/usr/bin:/sbin:/bin", os.path.join(HERE, "build.sh"),+ "publish", WORK, *[str(v) for v in versions]], check=True, stdout=subprocess.DEVNULL)+++def main():+ disk = os.path.join(DEMO, "disk.raw")+ vars_fd = os.path.join(DEMO, "OVMF_VARS.fd")+ note("copying the factory image (version 1) and fresh UEFI variables")+ subprocess.run(["cp", "--sparse=always", os.path.join(OUT, "disk.raw"), disk], check=True)+ shutil.copy("/usr/share/OVMF/OVMF_VARS_4M.fd", vars_fd)+ publish(1, 2)+ serve(os.path.join(OUT, "updates"))+ url = f"http://10.0.2.2:{PORT}"++ g = Guest(disk, vars_fd)+ try:+ note("1. first boot of the factory image")+ g.login()+ for c in ["cat /usr/lib/lordos/immutable/VERSION",+ "/usr/lib/lordos/immutable/update --status",+ "ls /efi > /dev/null; findmnt -lno TARGET,SOURCE,FSTYPE,OPTIONS | grep -E '^(/|/usr|/efi) ' | cut -c1-110",+ "veritysetup status usr | sed -n '1,4p;/root hash/p'",+ "touch /usr/bin/evil; echo exit=$?",+ "echo 'kept across updates' > /etc/lordos-demo.conf; mkdir -p /home/demo && echo 'my file' > /home/demo/notes.txt; echo ok",+ "systemctl is-active lordos-health systemd-bless-boot; echo"]:+ g.run(c)++ note("2. signed update to version 2 (into slot B)")+ g.run(f"/usr/lib/lordos/immutable/update {url}")+ g.run("/usr/lib/lordos/immutable/update --status")+ g.reboot()+ g.login()+ note("booted after the update")+ for c in ["cat /usr/lib/lordos/immutable/VERSION",+ "cat /etc/lordos-demo.conf /home/demo/notes.txt",+ "systemctl is-active lordos-health systemd-bless-boot; journalctl -b -u systemd-bless-boot -o cat | tail -3",+ "/usr/lib/lordos/immutable/update --status"]:+ g.run(c)++ note("3. a broken release: version 3 (fails its health check) into slot A")+ publish(1, 2, 3)+ g.run(f"/usr/lib/lordos/immutable/update {url}")+ g.run("/usr/lib/lordos/immutable/update --status")+ g.reboot()+ for attempt in (1, 2, 3):+ g.expect(rb"lordos: this version failed its health check", 240)+ note(f"version 3 failed its health check (attempt {attempt}); the system restarts itself")+ g.expect(rb"Command line: usrhash=", 120)+ g.login(300)+ note("booted on its own after the failed attempts")+ for c in ["cat /usr/lib/lordos/immutable/VERSION",+ "/usr/lib/lordos/immutable/update --status",+ "cat /etc/lordos-demo.conf /home/demo/notes.txt",+ "journalctl -b -1 -u lordos-health -o cat --no-pager | grep health-check",+ "journalctl --list-boots --no-pager | tail -5",+ f"/usr/lib/lordos/immutable/update {url}"]:+ g.run(c)++ note("3b. a hostile mirror: SHA256SUMS changed on the server (a version 9 added) without the key")+ sums = os.path.join(OUT, "updates", "SHA256SUMS")+ subprocess.run(["sudo", "sh", "-c", f"echo '{'0' * 64} lordos_9.efi' >> {sums}"], check=True)+ g.run(f"/usr/lib/lordos/immutable/update {url}; echo exit=$?")+ g.run("/usr/lib/lordos/immutable/update --status")+ publish(1, 2, 3)++ note("4. tampering: corrupt 8 MiB of the running /usr slot's blocks underneath dm-verity")+ for c in ["DATA=$(veritysetup status usr | awk '/data device/ {print $3}'); echo $DATA",+ "dd if=/dev/urandom of=$DATA bs=1M count=8 seek=40 conv=fsync status=none; echo 3 > /proc/sys/vm/drop_caches; echo written",+ "find /usr -type f -exec cat {} + > /dev/null 2> /tmp/err; echo read-errors=$(grep -c 'Input/output error' /tmp/err)",+ "dmesg | grep -m3 'is corrupted'"]:+ g.run(c, 600)+ note("done")+ finally:+ g.stop()+ print(f"transcript: {os.path.join(DEMO, 'transcript.txt')}")+++if __name__ == "__main__":+ main()diff --git a/tools/immutable/files/health-check b/tools/immutable/files/health-checknew file mode 100755index 0000000..cb1c687--- /dev/null+++ b/tools/immutable/files/health-check@@ -0,0 +1,15 @@+#!/bin/sh+# /usr/lib/lordos/immutable/health-check — PROTOTYPE boot assessment (docs/IMMUTABLE.md).+# Required by boot-complete.target: while it fails, systemd-bless-boot never marks the boot entry+# good, and lordos-health-failed.service restarts, so systemd-boot spends the entry's tries and+# then falls back to the previous version. The real check would be "the login screen came up"+# (lord-sessiond reports ready), not this.+set -eu+fail() { echo "health-check: FAILED: $*"; exit 1; }++findmnt -no SOURCE /usr | grep -qx /dev/mapper/usr || fail "/usr is not the dm-verity device"+findmnt -no OPTIONS /usr | grep -q '^ro' || fail "/usr is not read-only"+[ -e /usr/lib/lordos/immutable/simulate-broken-release ] \+ && fail "this test release is built broken on purpose (simulate-broken-release)"+# shellcheck source=/dev/null+echo "health-check: OK ($(. /usr/lib/os-release; echo "image version $IMAGE_VERSION"), /usr verified read-only)"diff --git a/tools/immutable/files/lordos-health-failed.service b/tools/immutable/files/lordos-health-failed.servicenew file mode 100644index 0000000..370b745--- /dev/null+++ b/tools/immutable/files/lordos-health-failed.service@@ -0,0 +1,8 @@+[Unit]+Description=LordOS health check failed: restart to try again or fall back+DefaultDependencies=no++[Service]+Type=oneshot+ExecStart=/bin/sh -c 'echo "lordos: this version failed its health check; restarting in 5 s (systemd-boot counts the attempt)" > /dev/console; sleep 5'+ExecStart=/usr/bin/systemctl --no-block rebootdiff --git a/tools/immutable/files/lordos-health.service b/tools/immutable/files/lordos-health.servicenew file mode 100644index 0000000..92c4691--- /dev/null+++ b/tools/immutable/files/lordos-health.service@@ -0,0 +1,12 @@+[Unit]+Description=LordOS health check (boot assessment)+Documentation=https://github.com/lordbasex/LordOS/blob/main/docs/IMMUTABLE.md+# boot-complete.target gates systemd-bless-boot.service, which marks the boot entry good+After=multi-user.target+Before=boot-complete.target+OnFailure=lordos-health-failed.service++[Service]+Type=oneshot+RemainAfterExit=yes+ExecStart=/usr/lib/lordos/immutable/health-checkdiff --git a/tools/immutable/files/update b/tools/immutable/files/updatenew file mode 100755index 0000000..c80cf41--- /dev/null+++ b/tools/immutable/files/update@@ -0,0 +1,110 @@+#!/bin/sh+# /usr/lib/lordos/immutable/update — PROTOTYPE A/B updater of the immutable LordOS image+# (docs/IMMUTABLE.md). It follows systemd-sysupdate's on-disk conventions (Debian 13 does not ship+# systemd-sysupdate): partition labels lordos_usr_<v> / lordos_usr_v_<v>, partition UUIDs derived+# from the dm-verity root hash, and a UKI lordos_<v>+<tries>.efi in the ESP for systemd-boot's+# boot counting. The product version would live in LordOS's own package engine (C), not in sh.+#+# update <base URL> install the newest signed version into the inactive slot+# update --status show the slots and the boot entries+set -eu++KEYRING=/usr/share/lordos/immutable/update-keyring.gpg+ESP=/efi+TRIES=3+T_USR=8484680c-9521-48c6-9c11-b0720656f69e+T_USR_VERITY=77ff5f63-e7b6-4633-acf4-1565b864c0e6+STATE=/var/lib/lordos/immutable++die() { echo "update: $*" >&2; exit 1; }+uuid_of() { echo "$1" | sed 's/^\(.\{8\}\)\(.\{4\}\)\(.\{4\}\)\(.\{4\}\)\(.\{12\}\).*/\1-\2-\3-\4-\5/'; }++[ "$(id -u)" = 0 ] || die "run as root"+# shellcheck source=/dev/null+CUR=$(. /usr/lib/os-release; echo "${IMAGE_VERSION:-}")+[ -n "$CUR" ] || die "not an immutable LordOS image (no IMAGE_VERSION)"+CURHASH=$(sed -n 's/.*usrhash=\([0-9a-f]\{64\}\).*/\1/p' /proc/cmdline)+[ -n "$CURHASH" ] || die "booted without usrhash="+CURU=$(uuid_of "$CURHASH")+ROOTDEV=$(findmnt -no SOURCE /)+DISK=/dev/$(lsblk -no PKNAME "$ROOTDEV")++# the usr data / verity partitions in disk order: slot A first, slot B second+parts() { lsblk -nrpo NAME,PARTTYPE,PARTUUID,PARTLABEL "$DISK" | awk -v t="$1" '$2 == t'; }+partnum() { cat "/sys/class/block/$(basename "$1")/partition"; }++status() {+ echo "running: image version $CUR, /usr = $(findmnt -no SOURCE,FSTYPE,OPTIONS /usr | cut -d, -f1)"+ i=0+ parts $T_USR | while read -r n _ u l; do+ i=$((i + 1)); slot=$(echo AB | cut -c$i)+ mark=""; [ "$u" = "$CURU" ] && mark=" <- running"+ echo "slot $slot: $n label=$l$mark"+ done+ echo "boot entries (ESP $ESP/EFI/Linux):"+ find "$ESP/EFI/Linux" -maxdepth 1 -name '*.efi' -printf ' %f\n' | sort+}++[ "${1:-}" = --status ] && { status; exit 0; }+URL=${1:?usage: update <base URL> | --status}++mkdir -p "$STATE"; W="$STATE/download"; rm -rf "$W"; mkdir -p "$W"+echo "checking $URL"+curl -fsS -o "$W/SHA256SUMS" "$URL/SHA256SUMS" || die "cannot download SHA256SUMS"+curl -fsS -o "$W/SHA256SUMS.gpg" "$URL/SHA256SUMS.gpg" || die "cannot download SHA256SUMS.gpg"+gpgv --keyring "$KEYRING" "$W/SHA256SUMS.gpg" "$W/SHA256SUMS" >/dev/null 2>&1 \+ || die "SHA256SUMS: BAD or missing signature, nothing installed"+echo "signature: good (update key)"+NEW=$(sed -n 's/^[0-9a-f]\{64\} lordos_\([0-9]\{1,9\}\)\.efi$/\1/p' "$W/SHA256SUMS" | sort -n | tail -1)+[ -n "$NEW" ] || die "no version listed"+[ "$NEW" -gt "$CUR" ] || { echo "up to date (running $CUR, newest $NEW)"; exit 0; }+# a version that already used up its boot tries on this machine is not installed again+for bad in "$ESP"/EFI/Linux/lordos_"$NEW"+0-*.efi; do+ [ -e "$bad" ] && { echo "version $NEW could not start on this computer (all tries failed); staying on $CUR until a newer version is published"; exit 0; }+done+echo "installing version $NEW (running $CUR)"+for f in lordos_usr_$NEW.erofs lordos_usr_$NEW.verity lordos_usr_$NEW.roothash lordos_$NEW.efi; do+ grep -q " $f\$" "$W/SHA256SUMS" || die "$f is not in the signed list"+ curl -fsS -o "$W/$f" "$URL/$f" || die "cannot download $f"+done+(cd "$W" && grep -E " lordos_(usr_)?$NEW\." SHA256SUMS | sha256sum -c --quiet) || die "SHA-256 mismatch"+NEWHASH=$(cat "$W/lordos_usr_$NEW.roothash")+echo "$NEWHASH" | grep -qx '[0-9a-f]\{64\}' || die "bad root hash"++# the inactive slot: the usr partition that is not backing the running /usr+# shellcheck disable=SC2046 # four words: device and PARTUUID of each slot+set -- $(parts $T_USR | awk '{print $1, $3}')+[ $# -eq 4 ] || die "expected two usr slots"+if [ "$2" = "$CURU" ]; then DATA=$3; IDX=2; elif [ "$4" = "$CURU" ]; then DATA=$1; IDX=1; else die "running slot not found"; fi+HASHDEV=$(parts $T_USR_VERITY | awk -v i=$IDX 'NR == i {print $1}')+[ -b "$DATA" ] && [ -b "$HASHDEV" ] || die "inactive slot not found"+[ "$(stat -c %s "$W/lordos_usr_$NEW.erofs")" -le "$(blockdev --getsize64 "$DATA")" ] || die "image larger than the slot"+OLDLABEL=$(lsblk -no PARTLABEL "$DATA")+echo "writing slot $(echo AB | cut -c$IDX) ($DATA, was $OLDLABEL)"++# 1. invalidate the slot first, so a crash half-way never leaves a bootable-looking slot+sfdisk -q --no-reread --no-tell-kernel --part-label "$DISK" "$(partnum "$DATA")" _empty+sfdisk -q --no-reread --no-tell-kernel --part-label "$DISK" "$(partnum "$HASHDEV")" _empty+OLDV=$(echo "$OLDLABEL" | sed -n 's/^lordos_usr_\([0-9]*\)$/\1/p')+[ -n "$OLDV" ] && rm -f "$ESP"/EFI/Linux/lordos_"$OLDV".efi "$ESP"/EFI/Linux/lordos_"$OLDV"+*.efi+# 2. write and check the blocks against the signed root hash+dd if="$W/lordos_usr_$NEW.erofs" of="$DATA" bs=4M conv=fsync status=none+dd if="$W/lordos_usr_$NEW.verity" of="$HASHDEV" bs=4M conv=fsync status=none+veritysetup verify "$DATA" "$HASHDEV" "$NEWHASH" || die "written slot does not verify"+echo "slot verified against usrhash $NEWHASH"+# 3. name it: UUIDs from the root hash (how the UKI finds it), labels with the version+U1=$(uuid_of "$NEWHASH"); U2=$(uuid_of "$(echo "$NEWHASH" | cut -c33-64)")+sfdisk -q --no-reread --no-tell-kernel --part-uuid "$DISK" "$(partnum "$DATA")" "$U1"+sfdisk -q --no-reread --no-tell-kernel --part-uuid "$DISK" "$(partnum "$HASHDEV")" "$U2"+sfdisk -q --no-reread --no-tell-kernel --part-label "$DISK" "$(partnum "$DATA")" "lordos_usr_$NEW"+sfdisk -q --no-reread --no-tell-kernel --part-label "$DISK" "$(partnum "$HASHDEV")" "lordos_usr_v_$NEW"+partx -u --nr "$(partnum "$DATA")" "$DISK" 2>/dev/null || true+partx -u --nr "$(partnum "$HASHDEV")" "$DISK" 2>/dev/null || true+# 4. last: the boot entry, with TRIES boot attempts before systemd-boot gives up on it+cp "$W/lordos_$NEW.efi" "$ESP/EFI/Linux/.lordos_$NEW.efi.tmp"+sync+mv "$ESP/EFI/Linux/.lordos_$NEW.efi.tmp" "$ESP/EFI/Linux/lordos_$NEW+$TRIES.efi"+sync+rm -rf "$W"+echo "version $NEW installed; it boots next ($TRIES tries), version $CUR stays as the fallback."+echo "Restart to finish."