diff --git a/boot/initramfs/root/init b/boot/initramfs/root/init index 8077943fc..963a12787 100755 --- a/boot/initramfs/root/init +++ b/boot/initramfs/root/init @@ -13,6 +13,30 @@ exec /dev/console 2>&1 stop() { echo "orchard initrd: $1" + # The serial-only rescue gadget is offered only for orchard.root=dm: those + # roots are the one stop path with no other way in (the whole disk map is + # checked here), and it exists so a bad map can be inspected over USB. On + # every other stop() it would raise a second gadget and a second shell on + # ttyGS0 where the normal gadget may already be up, and no board has booted + # that path yet. Widen it once a RAM boot has shown it safe. + if [ -n "$mapped_root" ]; then + if usb_gadget rescue; then + echo 'Starting a rescue shell on USB serial.' + ( + while :; do + if [ -c /dev/ttyGS0 ]; then + ( + echo "orchard initrd: $1" + exec setsid sh -i + ) /dev/ttyGS0 2>&1 + fi + sleep 1 + done + ) & + else + echo 'orchard initrd: USB serial rescue is unavailable.' + fi + fi echo 'Starting a shell on the console; the system did not start.' if [ -c /dev/ttyGS0 ]; then echo "orchard initrd: $1" >/dev/ttyGS0 2>&1 @@ -21,7 +45,55 @@ stop() { exec sh } -root= mode=rw flags= fstype= init=/sbin/init +# USB for the host: a serial console (ttyGS0), and on normal boots network +# (usb0) and the installed system's name. +usb_gadget() { + g=/sys/kernel/config/usb_gadget/orchard-system + mkdir -p /sys/kernel/config && mount -t configfs -o nodev,noexec,nosuid configfs /sys/kernel/config 2>/dev/null + [ ! -e "$g" ] || return 0 + if [ "${1:-}" = rescue ]; then + name='Orchard initrd rescue' + configuration='USB serial rescue' + else + name=$(sed -n 's/^NAME=//p' /newroot/etc/os-release /newroot/usr/lib/os-release 2>/dev/null | head -1 | tr -d "\"'") + configuration='USB network and serial' + fi + board=$(tr '\000' '\n' < /proc/device-tree/compatible | head -1) + # One serial for every boot of this unit (docs/device-protocol.md), or + # the per-boot one if the helper fails: USB must always come up. + serial=$(sh /etc/orchard/usb-identity 2>/dev/null) || + serial="BOOT:$(cat /proc/sys/kernel/random/boot_id) BOARD:${board#apple,}" + # Apple's vendor ID with a product ID macOS lists among the devices it + # grants 2400 mA (docs/device-protocol.md), so a Mac charges the tablet + # at full speed. As an interface-association composite (class 0xef/2/1) + # macOS binds its generic composite driver, which delivers the grant, + # and still the CDC network and serial drivers. + mkdir "$g" && + echo 0x05ac > "$g/idVendor" && + if [ "${1:-}" = rescue ]; then + echo 0x4144 > "$g/idProduct" + else + echo 0x1014 > "$g/idProduct" + fi && + echo 0xef > "$g/bDeviceClass" && + echo 0x02 > "$g/bDeviceSubClass" && + echo 0x01 > "$g/bDeviceProtocol" && + mkdir -p "$g/strings/0x409" "$g/configs/c.1/strings/0x409" && + echo 'Orchard Linux' > "$g/strings/0x409/manufacturer" && + echo "${name:-Linux}" > "$g/strings/0x409/product" && + echo "$serial" > "$g/strings/0x409/serialnumber" && + echo "$configuration" > "$g/configs/c.1/strings/0x409/configuration" && + echo 500 > "$g/configs/c.1/MaxPower" && + mkdir "$g/functions/acm.usb0" && + if [ "${1:-}" != rescue ]; then + mkdir "$g/functions/ncm.usb0" && + ln -s "$g/functions/ncm.usb0" "$g/configs/c.1/ncm.usb0" + fi && + ln -s "$g/functions/acm.usb0" "$g/configs/c.1/acm.usb0" && + basename "$(ls -d /sys/class/udc/* | head -1)" > "$g/UDC" +} + +root= mode=rw flags= fstype= init=/sbin/init mapped_root= overlay= lwvm_crc= for argument in $(cat /proc/cmdline); do case "$argument" in root=PARTUUID=*) root=$(echo "${argument#root=PARTUUID=}" | tr A-F a-f) ;; @@ -29,6 +101,9 @@ for argument in $(cat /proc/cmdline); do rootflags=*) flags=${argument#rootflags=} ;; ro | rw) mode=$argument ;; init=*) init=${argument#init=} ;; + orchard.root=dm) mapped_root=1 ;; + orchard.overlay=tmpfs) overlay=1 ;; + orchard.lwvm_crc=*) lwvm_crc=${argument#orchard.lwvm_crc=} ;; esac done @@ -54,6 +129,7 @@ if [ -r /run/orchard/disk ]; then [ -b "$disk" ] && : < "$disk" fi [ -n "$root" ] || stop 'the boot entry names no root=PARTUUID=' +[ -z "$mapped_root" ] || [ -n "$overlay" ] || stop 'orchard.root=dm requires orchard.overlay=tmpfs' # gpt_partuuid DISK SECTOR_SIZE NUMBER: the unique GUID of GPT entry NUMBER, # read from the disk itself: the kernel's uevent does not report PARTUUID. @@ -78,9 +154,7 @@ lwvm_partuuid() { echo "$1$2$3$4-$5$6-$7$8-$9${10}-${11}${12}${13}${14}${15}${16}" } -device= -ticks=0 -while [ -z "$device" ]; do +partition_root() { for number in /sys/class/block/*/partition; do [ -e "$number" ] || continue part=${number%/partition} @@ -90,59 +164,123 @@ while [ -z "$device" ]; do id=$(gpt_partuuid "/dev/$disk" "$sector" "$(cat "$number")") || id=$(lwvm_partuuid "/dev/$disk" "$(cat "$number")") if [ "$id" = "$root" ]; then - device=/dev/${part##*/} - break + echo "/dev/${part##*/}" + return fi done +} + +# dm-mod.create registers the mapping before /init. Match its UUID to the +# LwVM PARTUUID, since the assigned dm-N number depends on other mappings. +dm_root() { + for part in /sys/class/block/dm-*; do + [ -r "$part/dm/uuid" ] || continue + [ "$(cat "$part/dm/uuid")" = "orchard-lwvm-$root" ] || continue + [ "$(cat "$part/ro")" = 1 ] || continue + [ -b "/dev/${part##*/}" ] || continue + echo "/dev/${part##*/}" + return + done +} + +# Print the current LwVM header's CRC as the four stored bytes, in hex. +# Verify the checksum before considering the backup: a valid primary takes +# precedence, even if an older backup happens to match the boot entry. +lwvm_header_crc() { + local header=$1 sectors=$2 stored calculated + [ "$(wc -c < "$header")" -eq 4096 ] || return 1 + [ "$(od -An -tx1 -v -N 16 "$header" | tr -d ' \n')" = 6a9088cf8afd630ae351e24887e0b98b ] || return 1 + set -- $(od -An -tx1 -v -j 32 -N 8 "$header") + [ "$#" -eq 8 ] && [ "$((0x$8$7$6$5$4$3$2$1))" -eq "$((sectors * 512))" ] || return 1 + stored=$(od -An -tx1 -v -j 44 -N 4 "$header" | tr -d ' \n') + # gzip's trailer starts with the same little-endian CRC32 that LwVM uses. + calculated=$( + { head -c 44 "$header"; printf '\000\000\000\000'; tail -c 4048 "$header"; } | + gzip -c | tail -c 8 | od -An -tx1 -v -N 4 | tr -d ' \n' + ) + [ "${#stored}" -eq 8 ] && [ "$stored" = "$calculated" ] || return 1 + echo "$stored" +} + +# Arguments: whole backing disk and disk size in 512-byte sectors from sysfs. +lwvm_disk_crc() { + local header crc chunk + [ "$2" -ge 16384 ] || return 1 + # /dev is the devtmpfs mounted at the top of this script; /newroot does not exist yet. + header=$(mktemp /dev/.lwvm-header.XXXXXX) || return 1 + if dd if="$1" of="$header" bs=4096 count=1 2>/dev/null && crc=$(lwvm_header_crc "$header" "$2"); then + : + else + chunk=16 + while [ $((chunk * 1024)) -lt "$2" ]; do + chunk=$((chunk * 2)) + done + crc= + if dd if="$1" of="$header" bs=4096 skip=$((chunk / 8 - 1)) count=1 2>/dev/null; then + crc=$(lwvm_header_crc "$header" "$2") + fi + fi + rm -f "$header" + [ -n "$crc" ] || return 1 + echo "$crc" +} + +check_lwvm_mapping() { + [ "${#lwvm_crc}" -eq 8 ] || stop 'the boot entry needs orchard.lwvm_crc= with eight hex digits' + case "$lwvm_crc" in + *[!0-9a-f]*) stop 'the boot entry needs orchard.lwvm_crc= with eight hex digits' ;; + esac + set -- "/sys/class/block/${device##*/}/slaves/"* + [ "$#" -eq 1 ] && [ -e "$1" ] || stop "expected one backing disk for $device" + disk=/dev/${1##*/} + sectors=$(cat "$1/size") || stop "could not read the size of $disk" + actual_crc=$(lwvm_disk_crc "$disk" "$sectors") || stop "could not read a valid LwVM header on $disk" + [ "$actual_crc" = "$lwvm_crc" ] || + stop "LwVM header CRC mismatch on $disk (expected $lwvm_crc, found $actual_crc); regenerate the boot options" +} + +description="partition $root" +[ -z "$mapped_root" ] || description="read-only device-mapper root $root" +ticks=0 +while :; do + if [ -n "$mapped_root" ]; then + device=$(dm_root) + else + device=$(partition_root) + fi [ -n "$device" ] && break if sleep 0.05 2>/dev/null; then ticks=$((ticks + 1)) - [ "$ticks" -le 600 ] || stop "no partition $root after 30 s" else ticks=$((ticks + 20)) - [ "$ticks" -le 600 ] || stop "no partition $root after 30 s" sleep 1 fi + [ "$ticks" -lt 600 ] || stop "no $description after 30 s" done -mkdir -p /newroot -mount ${fstype:+-t "$fstype"} -o "$mode${flags:+,$flags}" "$device" /newroot || stop "could not mount $device" -[ -x "/newroot$init" ] || [ -L "/newroot$init" ] || stop "the root has no $init" +[ -z "$mapped_root" ] || check_lwvm_mapping -# USB for the host: network (usb0) and a serial console (ttyGS0), named after -# the system, so `orchard devices` sees it. What runs on them is the system's. -usb_gadget() { - g=/sys/kernel/config/usb_gadget/orchard-system - mkdir -p /sys/kernel/config && mount -t configfs -o nodev,noexec,nosuid configfs /sys/kernel/config 2>/dev/null - [ ! -e "$g" ] || return 0 - name=$(sed -n 's/^NAME=//p' /newroot/etc/os-release /newroot/usr/lib/os-release 2>/dev/null | head -1 | tr -d "\"'") - board=$(tr '\000' '\n' < /proc/device-tree/compatible | head -1) - # One serial for every boot of this unit (docs/device-protocol.md), or - # the per-boot one if the helper fails: USB must always come up. - serial=$(sh /etc/orchard/usb-identity 2>/dev/null) || - serial="BOOT:$(cat /proc/sys/kernel/random/boot_id) BOARD:${board#apple,}" - # Apple's vendor ID with a product ID macOS lists among the devices it - # grants 2400 mA (docs/device-protocol.md), so a Mac charges the tablet - # at full speed. As an interface-association composite (class 0xef/2/1) - # macOS binds its generic composite driver, which delivers the grant, - # and still the CDC network and serial drivers. - mkdir "$g" && - echo 0x05ac > "$g/idVendor" && - echo 0x1014 > "$g/idProduct" && - echo 0xef > "$g/bDeviceClass" && - echo 0x02 > "$g/bDeviceSubClass" && - echo 0x01 > "$g/bDeviceProtocol" && - mkdir -p "$g/strings/0x409" "$g/configs/c.1/strings/0x409" && - echo 'Orchard Linux' > "$g/strings/0x409/manufacturer" && - echo "${name:-Linux}" > "$g/strings/0x409/product" && - echo "$serial" > "$g/strings/0x409/serialnumber" && - echo 'USB network and serial' > "$g/configs/c.1/strings/0x409/configuration" && - echo 500 > "$g/configs/c.1/MaxPower" && - mkdir "$g/functions/ncm.usb0" "$g/functions/acm.usb0" && - ln -s "$g/functions/ncm.usb0" "$g/configs/c.1/ncm.usb0" && - ln -s "$g/functions/acm.usb0" "$g/configs/c.1/acm.usb0" && - basename "$(ls -d /sys/class/udc/* | head -1)" > "$g/UDC" +mount_root() { + mkdir -p /newroot || stop 'could not create the root mount point' + if [ -z "$overlay" ]; then + mount ${fstype:+-t "$fstype"} -o "$mode${flags:+,$flags}" "$device" /newroot || + stop "could not mount $device" + return + fi + + # Keep the filesystem and the overlay's backing directories on separate + # mounts. OverlayFS holds references to both after switch_root. + mkdir -p /root-lower /root-overlay || stop 'could not create the overlay mount points' + mount ${fstype:+-t "$fstype"} -o "${flags:+$flags,}ro" "$device" /root-lower || + stop "could not mount $device read-only" + mount -t tmpfs -o mode=0755,size=40% tmpfs /root-overlay || stop 'could not mount the overlay tmpfs' + mkdir /root-overlay/upper /root-overlay/work || stop 'could not create the overlay directories' + mount -t overlay -o lowerdir=/root-lower,upperdir=/root-overlay/upper,workdir=/root-overlay/work overlay /newroot || + stop 'could not mount the root overlay' } +mount_root +[ -x "/newroot$init" ] || [ -L "/newroot$init" ] || stop "the root has no $init" + usb_gadget || echo 'orchard initrd: no USB gadget; continuing without USB' for name in dev proc sys; do diff --git a/docs/boot-contract.md b/docs/boot-contract.md index 22152d5f4..6ecc17a7b 100644 --- a/docs/boot-contract.md +++ b/docs/boot-contract.md @@ -105,6 +105,16 @@ modules only. It loads them, waits up to 30 s for the partition that given) and starts its `/sbin/init` (or `init=`). If any step fails, it says which one and opens a shell on the console. +`orchard.overlay=tmpfs` makes the initrd mount the root filesystem read-only +and start the system on an OverlayFS mount backed by tmpfs (limited to 40% +of RAM). All changes to that overlay disappear at reboot. Cleanly unmount the +lower filesystem before boot: journal replay cannot write to a read-only +backing device, and skipping replay could expose an inconsistent filesystem. +The installed system must not try to fsck or remount the lower filesystem +through an `/` entry in `/etc/fstab`. The overlay +requires kernel tmpfs and OverlayFS support. Without the option the initrd +mounts the filesystem directly as usual. + ## Partitions (GPT) | Partition | Type GUID | Filesystem | Count | @@ -130,6 +140,47 @@ take over. Meanwhile the host keeps the Cascadia bundle that starts the installed system (its tree's `bootargs` carry `root=PARTUUID=`), which has to be placed where iOS's boot chain finds it. +### Booting an existing scattered Linux partition + +The kernel's LwVM reader only registers contiguous partitions. To boot a +scattered Linux partition, generate the entry's options on the host from a +current 4096-byte LwVM header (primary or copy) and the partition's GUID: + +```sh +bin/orchard python -m orchard.lwvm_root lwvm-header.bin LINUX-PARTUUID +``` + +The generator also accepts a disk image or block device, in which case it +reads the primary header and checks the recorded medium size against its +backing size. The options include `root=PARTUUID=…`, `orchard.root=dm`, +`orchard.overlay=tmpfs`, `orchard.lwvm_crc=` (the four stored CRC bytes as +lowercase hex), and a quoted `dm-mod.create=` with a read-only linear map. +The backing disk defaults to `/dev/applesftl0`; pass `--disk` if +the kernel exposes it under another name. Use the emitted line as the root +options for the entry or pass it as `bootargs` to Cascadia assembly, keeping +the literal double quotes around the map. Include any board-specific +console arguments as usual. The complete armv7 command line must fit in +1023 bytes; maps that would exceed that limit by themselves are rejected. + +This path requires an armv7 kernel with `CONFIG_MD=y`, `CONFIG_BLK_DEV_DM=y` +and `CONFIG_DM_INIT=y` built in; the armv7 kernel configuration +(`kernel/configs/apple-armv7/config`) enables all three. The backing disk +must be available at device-mapper initialization. + +The shared initrd waits up to 30 s for the read-only mapper device whose +UUID matches the root PARTUUID. Before mounting, it verifies the LwVM +header checksum and medium size against the mapping's backing disk and +compares the checksum with `orchard.lwvm_crc=`. It uses the backup at the +end of the first chunk only if the primary is unreadable or invalid. If the +mapper device never appears, the header cannot be read, or the checksum +differs, the initrd stops and offers a serial-only USB (ACM) rescue shell +in addition to the local console when the USB controller is available. + +Recompute the options and regenerate the payload whenever the LwVM map +changes. This path boots an already prepared filesystem. The shared initrd's +device-mapper path has not yet booted on a device; one RAM boot is pending. The automatic +installer does not generate these options or populate scattered partitions. + ## Entries The layout follows BLS: diff --git a/docs/device-protocol.md b/docs/device-protocol.md index a912f52fa..68f5d87dc 100644 --- a/docs/device-protocol.md +++ b/docs/device-protocol.md @@ -32,6 +32,12 @@ serial. No descriptor changes per boot, so macOS can retain accessory approval. Trees without a serial number warn and retain the legacy `BOOT:` identity to keep rescue USB available; those still need approval each boot. +The installed initrd's [scattered LwVM root rescue](boot-contract.md#booting-an-existing-scattered-linux-partition) +uses `0x05ac:0x4144` and the same stable `BOARD: ID:` serial +(or the same `BOOT:` fallback). Hosts may list it as a RAM payload because +it shares the RAM product ID. It offers only an ACM console, without USB +networking or the RAM session's SSH bootstrap. + For RAM sessions, ACM returns `/proc/sys/kernel/random/boot_id` and the SSH host public key together on every connection. The host validates the boot ID and pins that boot's key. Installed systems use their persistent SSH keys and diff --git a/src/orchard/lwvm_root.py b/src/orchard/lwvm_root.py new file mode 100644 index 000000000..e4490d25f --- /dev/null +++ b/src/orchard/lwvm_root.py @@ -0,0 +1,115 @@ +"""Write armv7 boot options for a read-only LwVM root with a RAM overlay.""" +import argparse +import os +from pathlib import Path +import re +import stat +import struct +import uuid +import zlib + + +HEADER_BYTES = 4096 +SECTOR_BYTES = 512 +CHUNKS = 1024 +MAGIC = uuid.UUID('6a9088cf-8afd-630a-e351-e24887e0b98b').bytes +LINUX_TYPE = uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes +ARM_COMMAND_LINE_SIZE = 1024 # includes the terminating NUL + + +def linear_runs(header, partuuid, media_bytes=None): + """Return merged (logical start, length, physical start) in 512-byte sectors.""" + if len(header) != HEADER_BYTES or header[:16] != MAGIC: + raise ValueError('Expected a 4096-byte CRC-protected LwVM header') + media, count, stored_crc = struct.unpack_from('> 12, entry & 0xfff + if partition == 0xf: + continue + if not 0 < physical < media // chunk or partition >= count: + raise ValueError('Invalid LwVM chunk owner or physical address') + if partition == owner: + if logical >= needed or logical in physical_chunks: + raise ValueError('LwVM root has an out-of-range or duplicate logical chunk') + physical_chunks[logical] = physical + if len(physical_chunks) != needed: + raise ValueError('LwVM root chunk coverage is incomplete') + + runs = [] + for index in range(needed): + logical = index * chunk + length = min(chunk, size - logical) + physical = physical_chunks[index] * chunk + if runs and runs[-1][2] + runs[-1][1] == physical: + runs[-1][1] += length + else: + runs.append([logical, length, physical]) + return [tuple(value // SECTOR_BYTES for value in run) for run in runs] + + +def boot_options(header, partuuid, disk='/dev/applesftl0', *, media_bytes=None): + """Return kernel options for the selected partition, using DISK on the device.""" + if not re.fullmatch(r'/dev/[a-zA-Z0-9_-]+', disk): + raise ValueError('Expected the backing disk as a simple /dev/ block device path') + partuuid = uuid.UUID(partuuid) + table = ','.join(f'{start} {length} linear {disk} {offset}' + for start, length, offset in linear_runs(header, partuuid, media_bytes)) + options = (f'root=PARTUUID={partuuid} ro orchard.root=dm orchard.overlay=tmpfs ' + f'orchard.lwvm_crc={header[0x2c:0x30].hex()} ' + f'dm-mod.create="orchard-root,orchard-lwvm-{partuuid},,ro,{table}"') + if len(options) >= ARM_COMMAND_LINE_SIZE: + raise ValueError('LwVM mapping does not fit in the armv7 kernel command line') + return options + + +def read_header(path): + """Read a header dump or the start of a disk image/block device, with its size if known.""" + with path.open('rb') as source: + info = os.fstat(source.fileno()) + media_bytes = None + if stat.S_ISBLK(info.st_mode): + media_bytes = source.seek(0, os.SEEK_END) + source.seek(0) + elif stat.S_ISREG(info.st_mode) and info.st_size != HEADER_BYTES: + media_bytes = info.st_size + return source.read(HEADER_BYTES), media_bytes + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('header', type=Path, help='4096-byte LwVM header (primary or copy), disk image or block device') + parser.add_argument('partuuid', help='Linux partition GUID') + parser.add_argument('--disk', default='/dev/applesftl0', help='backing disk path on the device') + args = parser.parse_args() + try: + header, media_bytes = read_header(args.header) + print(boot_options(header, args.partuuid, args.disk, media_bytes=media_bytes)) + except (OSError, ValueError) as error: + parser.error(str(error)) + + +if __name__ == '__main__': + main() diff --git a/tests/fixtures/p105-scattered-lwvm.bin b/tests/fixtures/p105-scattered-lwvm.bin new file mode 100644 index 000000000..8542c2153 Binary files /dev/null and b/tests/fixtures/p105-scattered-lwvm.bin differ diff --git a/tests/test_identity.py b/tests/test_identity.py index 06c272dbc..6849aa735 100644 --- a/tests/test_identity.py +++ b/tests/test_identity.py @@ -148,12 +148,15 @@ def test_missing_or_empty_serial_preserves_rescue_usb_with_a_warning(self): def test_installed_and_ram_gadgets_use_the_same_stable_serial_before_binding(self): (self.tree / 'serial-number').write_bytes(b'HardwareSerialA\0') expected = self.serial().stdout.strip() - for relative in ('boot/initramfs/root/init', 'boot/session/usb-session'): - with self.subTest(path=relative): + for relative, rescue in (('boot/initramfs/root/init', False), ('boot/initramfs/root/init', True), + ('boot/session/usb-session', False)): + with self.subTest(path=relative, rescue=rescue): source = (ROOT / relative).read_text() if relative.endswith('/init'): start = source.index('usb_gadget() {') - source = source[start:source.index('\nusb_gadget ||', start)] + '\nusb_gadget' + source = source[start:source.index('\n}', start) + 2] + '\nusb_gadget' + if rescue: + source = source.replace('orchard-system', 'orchard-rescue-fixture') + ' rescue' else: source = source[source.index('name=$(cat'):source.index('\nifconfig ')] for directory in ('sys/kernel/config/usb_gadget', 'sys/class/udc/usbdev', @@ -170,11 +173,15 @@ def test_installed_and_ram_gadgets_use_the_same_stable_serial_before_binding(sel subprocess.run(['sh', '-ec', 'mount() { :; };\n' + source], check=True, capture_output=True, env={**os.environ, 'ORCHARD_DEVICE_TREE': str(self.tree)}) name = 'orchard-system' if relative.endswith('/init') else 'ram-test' + if rescue: + name = 'orchard-rescue-fixture' gadget = self.root / 'sys/kernel/config/usb_gadget' / name self.assertEqual((gadget / 'strings/0x409/serialnumber').read_text().strip(), expected) self.assertEqual((gadget / 'UDC').read_text().strip(), 'usbdev') - for function in ('ncm.usb0', 'acm.usb0'): - self.assertTrue((gadget / 'configs/c.1' / function).is_symlink()) + self.assertTrue((gadget / 'configs/c.1/acm.usb0').is_symlink()) + self.assertEqual((gadget / 'configs/c.1/ncm.usb0').is_symlink(), not rescue) + if rescue: + self.assertEqual((gadget / 'idProduct').read_text().strip(), '0x4144') if __name__ == '__main__': @@ -185,7 +192,7 @@ class MacCurrentIdentity(unittest.TestCase): def test_the_installed_gadget_asks_for_the_mac_current_identity(self): init = (ROOT / 'boot/initramfs/root/init').read_text() - gadget = init[init.index('usb_gadget() {'):init.index('\nusb_gadget ||')] + start = init.index('usb_gadget() {') + gadget = init[start:init.index('\n}', start)] self.assertIn('echo 0x1014 > "$g/idProduct"', gadget) self.assertIn('echo 0xef > "$g/bDeviceClass"', gadget) - diff --git a/tests/test_lwvm_root.py b/tests/test_lwvm_root.py new file mode 100644 index 000000000..a3f37f1f8 --- /dev/null +++ b/tests/test_lwvm_root.py @@ -0,0 +1,283 @@ +"""Scattered LwVM boot options and the shared initrd's overlay mount sequence.""" +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +import uuid +import zlib + +from test_cascadia_loader import PROFILE, cascadia, kernel, loader, tree +from orchard import lwvm_root + + +HERE = Path(__file__).resolve().parent +# The measured 16 GB P105 header after installing the third partition. Only +# the medium and non-Linux partition UUIDs were replaced and the CRC updated. +FIXTURE = HERE / 'fixtures/p105-scattered-lwvm.bin' +PARTUUID = uuid.UUID('1746a46a-ffc1-4a28-844f-0b168b79185f') +SECTORS_PER_CHUNK = 32768 +RUNS = [(0, 19529728, 8978432), (19529728, 163840, 30048256), (19693568, 532840, 30474240)] +MEDIA = 16_000_000_000 +INIT = (HERE.parent / 'boot/initramfs/root/init').read_text() + + +def init_function(name): + return re.search(rf'^{name}\(\) \{{.*?^\}}', INIT, re.M | re.S).group(0) + + +def update_crc(header): + struct.pack_into('&2; exit 1; }\ncheck_lwvm_mapping\n' + result = subprocess.run([*self.shell, f'device=/dev/dm-3 lwvm_crc=$1\n{script}', 'sh', expected], + env=self.env, capture_output=True, text=True, timeout=10) + self.assertEqual([path.name for path in (root / 'dev').glob('.lwvm*')], [], + 'the check left a temporary file behind') + self.assertFalse((root / 'newroot').exists(), 'the check must not need /newroot') + return result + + def test_matching_primary_or_valid_backup_accepts_the_boot_options(self): + header = FIXTURE.read_bytes() + damaged = bytearray(header) + damaged[-1] ^= 1 + wrong_size = bytearray(header) + struct.pack_into('&2; exit 1; } + ''' + script = f'device=/dev/dm-3 mode=rw flags=relatime,rw fstype=ext4 overlay=$1 fail=$2\n{mocks}\n{function}\nmount_root' + return subprocess.run(['sh', '-c', script, 'sh', overlay, fail_at], + capture_output=True, text=True, timeout=10) + + def test_normal_root_uses_the_existing_rw_mount(self): + result = self.mount_commands('') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, 'mount -t ext4 -o rw,relatime,rw /dev/dm-3 /newroot\n') + + def test_overlay_forces_a_read_only_lower_mount(self): + result = self.mount_commands('1') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), [ + 'mount -t ext4 -o relatime,rw,ro /dev/dm-3 /root-lower', + 'mount -t tmpfs -o mode=0755,size=40% tmpfs /root-overlay', + 'mount -t overlay -o lowerdir=/root-lower,upperdir=/root-overlay/upper,workdir=/root-overlay/work overlay /newroot', + ]) + + def test_lower_mount_failure_never_proceeds_to_overlay(self): + result = self.mount_commands('1', '/root-lower') + self.assertEqual(result.returncode, 1) + self.assertEqual(result.stderr, 'could not mount /dev/dm-3 read-only\n') + self.assertEqual(len(result.stdout.splitlines()), 1)