From f8cd02d808680b052e47f1f9039a6eb97c47acff Mon Sep 17 00:00:00 2001 From: Joe Alicata Date: Mon, 19 Oct 2026 13:00:29 -0400 Subject: [PATCH 1/2] flame 0.1.0: rebase shell 0.2.24 and firstboot 0.1.3 hooks Rebase the native development proposal onto current main and prepare the five focused review branches. Preserve SOC-compatible and AVB validation, serial-pinned Fastboot writes and fresh/shared SSH support. Resolve GPT partition names, clarify rescue-key authority and buttons- only recovery, shorten agent evidence, and assess the direct-ABL candidate without new hardware claims. Keep userdata flashing out and mark the GPT writer pending the maintainer policy exception. Co-Authored-By: Codex --- bin/omamobile | 151 ++++++++++++-- device/flame/ABL-PLAN.md | 47 +++++ device/flame/BOOT-PLAN.md | 197 ++++++++++++++++++ device/flame/BRINGUP-M1.md | 9 + device/flame/native/README.md | 174 ++++++++++++++++ device/flame/native/RESULTS.md | 122 +++++++++++ device/flame/native/boot_success_apply.py | 94 +++++++++ device/flame/native/boot_success_plan.py | 70 +++++++ device/flame/native/build | 95 +++++++++ device/flame/native/device.conf | 14 ++ device/flame/native/init | 184 ++++++++++++++++ device/flame/native/read_gpt.py | 165 +++++++++++++++ device/flame/native/validation/load-idle.sh | 89 ++++++++ docs/DEVICES.md | 4 + docs/RELEASES.md | 9 + packages/omamobile-device-flame/LICENSE | 21 ++ packages/omamobile-device-flame/PKGBUILD | 11 + packages/omamobile-device-flame/README.md | 27 +++ .../bin/omamobile-flame-configure-user | 70 +++++++ packages/omamobile-device-flame/install | 16 ++ packages/omamobile-device-flame/test/all | 54 +++++ .../test/storage-guard.py | 25 +++ .../vendor/bin/flame-partition-links | 20 ++ .../vendor/bin/flame-storage-guard | 38 ++++ .../vendor/bin/flame-wifi-start | 103 +++++++++ .../NetworkManager/conf.d/10-flame-usb.conf | 4 + .../90-flame-software-rendering.conf | 5 + .../lib/modprobe.d/omamobile-flame.conf | 7 + .../journald.conf.d/90-flame-standalone.conf | 5 + .../lib/systemd/network/10-flame-usb.network | 15 ++ .../system.conf.d/10-flame-watchdog.conf | 5 + .../system/flame-storage-guard.service | 15 ++ .../lib/systemd/system/flame-wifi.service | 19 ++ .../flame-software-rendering.conf | 4 + .../lib/udev/rules.d/10-flame-storage.rules | 3 + packages/omamobile-device-flame/version | 1 + .../bin/omamobile-firstboot | 6 + packages/omamobile-firstboot/test/all | 12 ++ packages/omamobile-firstboot/version | 2 +- .../omamobile-shell/bin/omamobile-setup-user | 10 +- packages/omamobile-shell/version | 2 +- rootfs/build-inside | 7 +- tests/all | 11 +- tests/flame-boot-success.py | 154 ++++++++++++++ tests/flame-images | 121 +++++++++++ tests/flame-root-guard.py | 30 +++ tests/phone-ssh | 57 +++++ tests/rootfs-smoke | 12 ++ tools/build-flame-loader | 76 +++++++ tools/build-flame-system | 80 +++++++ tools/build-rootfs | 6 +- tools/phone-ssh | 44 +++- 52 files changed, 2486 insertions(+), 36 deletions(-) create mode 100644 device/flame/ABL-PLAN.md create mode 100644 device/flame/BOOT-PLAN.md create mode 100644 device/flame/native/README.md create mode 100644 device/flame/native/RESULTS.md create mode 100644 device/flame/native/boot_success_apply.py create mode 100644 device/flame/native/boot_success_plan.py create mode 100644 device/flame/native/build create mode 100644 device/flame/native/device.conf create mode 100644 device/flame/native/init create mode 100644 device/flame/native/read_gpt.py create mode 100755 device/flame/native/validation/load-idle.sh create mode 100644 packages/omamobile-device-flame/LICENSE create mode 100644 packages/omamobile-device-flame/PKGBUILD create mode 100644 packages/omamobile-device-flame/README.md create mode 100755 packages/omamobile-device-flame/bin/omamobile-flame-configure-user create mode 100755 packages/omamobile-device-flame/install create mode 100755 packages/omamobile-device-flame/test/all create mode 100644 packages/omamobile-device-flame/test/storage-guard.py create mode 100755 packages/omamobile-device-flame/vendor/bin/flame-partition-links create mode 100755 packages/omamobile-device-flame/vendor/bin/flame-storage-guard create mode 100755 packages/omamobile-device-flame/vendor/bin/flame-wifi-start create mode 100644 packages/omamobile-device-flame/vendor/lib/NetworkManager/conf.d/10-flame-usb.conf create mode 100644 packages/omamobile-device-flame/vendor/lib/environment.d/90-flame-software-rendering.conf create mode 100644 packages/omamobile-device-flame/vendor/lib/modprobe.d/omamobile-flame.conf create mode 100644 packages/omamobile-device-flame/vendor/lib/systemd/journald.conf.d/90-flame-standalone.conf create mode 100644 packages/omamobile-device-flame/vendor/lib/systemd/network/10-flame-usb.network create mode 100644 packages/omamobile-device-flame/vendor/lib/systemd/system.conf.d/10-flame-watchdog.conf create mode 100644 packages/omamobile-device-flame/vendor/lib/systemd/system/flame-storage-guard.service create mode 100644 packages/omamobile-device-flame/vendor/lib/systemd/system/flame-wifi.service create mode 100644 packages/omamobile-device-flame/vendor/lib/systemd/system/sddm.service.d/flame-software-rendering.conf create mode 100644 packages/omamobile-device-flame/vendor/lib/udev/rules.d/10-flame-storage.rules create mode 100644 packages/omamobile-device-flame/version create mode 100644 tests/flame-boot-success.py create mode 100755 tests/flame-images create mode 100644 tests/flame-root-guard.py create mode 100755 tests/phone-ssh create mode 100755 tools/build-flame-loader create mode 100755 tools/build-flame-system diff --git a/bin/omamobile b/bin/omamobile index b8ea30aeb..87b0867bd 100755 --- a/bin/omamobile +++ b/bin/omamobile @@ -61,6 +61,10 @@ UFS_RW_ALLOWED="boot_b init_boot_b vendor_boot_b vendor_kernel_boot_b dtbo_b use # backslashes, so other tools can read it too. Nothing in it is executed. load_device() { local file="$ROOT/device/$DEVICE/device.conf" line n=0 key p + if [[ ${FLAME_NATIVE:-0} == 1 ]]; then + [[ $DEVICE == flame ]] || die "FLAME_NATIVE=1 requires DEVICE=flame" + file="$ROOT/device/flame/native/device.conf" + fi local quoted='^([A-Z][A-Z0-9_]*)="([^"$`\\]*)"$' bare='^([A-Z][A-Z0-9_]*)=([^"$`\\'"'"'[:space:]]*)$' DEV_BOOT_METHOD=android-v4 # legacy descriptors omit it [[ $DEVICE =~ ^[a-z0-9]+$ ]] || die "DEVICE must be a codename, not '$DEVICE'" @@ -74,27 +78,37 @@ load_device() { die "$file:$n: not a KEY=value line" fi done < "$file" - [[ $DEV_BOOT_METHOD == android-v4 ]] \ - || die "$file: unsupported BOOT_METHOD=$DEV_BOOT_METHOD; this command supports only android-v4" - for key in CODENAME SOC PACKAGE DTB DTBO_SOURCE DTBO_BOARD_ID DTBO_BOARD_REV VENDOR_CMDLINE \ - VENDOR_PAGESIZE OS_VERSION OS_PATCH_LEVEL BOOT_IMAGES UFS_RW INITRAMFS_INIT PANEL_SIZE; do + local required="CODENAME SOC BOOT_IMAGES UFS_RW PANEL_SIZE" + case $DEV_BOOT_METHOD in + android-v4) + required+=" PACKAGE DTB DTBO_SOURCE DTBO_BOARD_ID DTBO_BOARD_REV VENDOR_CMDLINE VENDOR_PAGESIZE OS_VERSION OS_PATCH_LEVEL INITRAMFS_INIT" + ;; + uboot-ext4) + [[ ${DEV_CODENAME:-} == flame && ${DEV_SOC:-} == sm8150 ]] || die "$file: unsupported BOOT_METHOD=$DEV_BOOT_METHOD; uboot-ext4 is implemented only for flame" + [[ ${DEV_BOOT_IMAGES:-} == boot && ${DEV_UFS_RW:-} == 'boot_b userdata' ]] || die 'uboot-ext4 requires boot only and UFS_RW="boot_b userdata"' + ;; + *) die "$file: unsupported BOOT_METHOD=$DEV_BOOT_METHOD; use a supported device profile" ;; + esac + for key in $required; do p="DEV_$key" [[ -n ${!p:-} ]] || die "$file: $key is missing" done - # ABL picks the base DTB by /soc_id (gs101, gs201) or by /soc_compatible - # (zuma): a descriptor names exactly one of the two. - if [[ -n ${DEV_SOC_IDS:-} && -n ${DEV_SOC_COMPATIBLE:-} ]]; then - die "$file: SOC_IDS and SOC_COMPATIBLE are exclusive; name the one this bootloader matches on" - elif [[ -z ${DEV_SOC_IDS:-} && -z ${DEV_SOC_COMPATIBLE:-} ]]; then - die "$file: SOC_IDS is missing (or SOC_COMPATIBLE, for a bootloader that matches /soc_compatible)" + if [[ $DEV_BOOT_METHOD == android-v4 ]]; then + # ABL picks the base DTB by /soc_id (gs101, gs201) or by /soc_compatible + # (zuma): a descriptor names exactly one of the two. + if [[ -n ${DEV_SOC_IDS:-} && -n ${DEV_SOC_COMPATIBLE:-} ]]; then + die "$file: SOC_IDS and SOC_COMPATIBLE are exclusive; name the one this bootloader matches on" + elif [[ -z ${DEV_SOC_IDS:-} && -z ${DEV_SOC_COMPATIBLE:-} ]]; then + die "$file: SOC_IDS is missing (or SOC_COMPATIBLE, for a bootloader that matches /soc_compatible)" + fi + local sc='^[a-z0-9]+(-[a-z0-9]+)*:0x[0-9a-f]+:[0-9]+:[0-9]+:[0-9]+$' labels=" " + for p in ${DEV_SOC_COMPATIBLE:-}; do + [[ $p =~ $sc ]] || die "$file: SOC_COMPATIBLE entries are label:product_id:major:minor:pkg_mode, not $p" + # One child node per entry: the label names it, so it must be unique + [[ $labels != *" ${p%%:*} "* ]] || die "$file: SOC_COMPATIBLE names ${p%%:*} twice" + labels+="${p%%:*} " + done fi - local sc='^[a-z0-9]+(-[a-z0-9]+)*:0x[0-9a-f]+:[0-9]+:[0-9]+:[0-9]+$' labels=" " - for p in ${DEV_SOC_COMPATIBLE:-}; do - [[ $p =~ $sc ]] || die "$file: SOC_COMPATIBLE entries are label:product_id:major:minor:pkg_mode, not $p" - # One child node per entry: the label names it, so it must be unique - [[ $labels != *" ${p%%:*} "* ]] || die "$file: SOC_COMPATIBLE names ${p%%:*} twice" - labels+="${p%%:*} " - done [[ $DEV_CODENAME == "$DEVICE" ]] || die "$file: CODENAME=$DEV_CODENAME, expected $DEVICE" # Safety: the guard's allowlist may name slot B's boot images and userdata # only, must hold userdata, and every boot image we write must be on it. @@ -119,9 +133,11 @@ load_device() { [[ $seen != *" $p "* ]] || die "$file: BOOT_IMAGES names $p twice" seen+="$p " done - for p in boot vendor_boot dtbo; do - [[ $seen == *" $p "* ]] || die "$file: BOOT_IMAGES must include $p" - done + if [[ $DEV_BOOT_METHOD == android-v4 ]]; then + for p in boot vendor_boot dtbo; do + [[ $seen == *" $p "* ]] || die "$file: BOOT_IMAGES must include $p" + done + fi # AVB hash footers, for a bootloader whose vbmeta chains these partitions # (zuma): image:partition_size, each a boot image, named once, the size # a whole number of 4 KiB blocks. Their rollback index and security patch @@ -329,6 +345,7 @@ cmd_initramfs_config() { cmd_initramfs() { local dl="$WORK/downloads/alpine" stage="$KERNEL_OUT/initramfs" ver=3.24.2 load_device + [[ $DEV_BOOT_METHOD == android-v4 ]] || die "use tools/build-flame-system for the native flame payload" # A leading slash is repo-root relative, so devices share initramfs/init. # Anything else is relative to device//. local init @@ -452,6 +469,45 @@ cmd_initramfs() { cmd_images() { load_device + if [[ $DEV_BOOT_METHOD == uboot-ext4 ]]; then + local image=${UBOOT_IMAGE:-} expected=${UBOOT_SHA256:-} got role=${FLAME_BOOT_ROLE:-loader} + [[ $role == loader || $role == stock-recovery ]] || die 'FLAME_BOOT_ROLE must be loader or stock-recovery' + [[ -f $image && $expected =~ ^[a-f0-9]{64}$ ]] || die 'supply the reviewed UBOOT_IMAGE and UBOOT_SHA256' + got=$(sha256sum < "$image" | cut -d' ' -f1) + [[ $got == "$expected" ]] || die 'U-Boot image checksum mismatch' + python3 - "$image" "$role" <<'PY' +import pathlib, struct, sys +p = pathlib.Path(sys.argv[1]) +with p.open('rb') as stream: + header = stream.read(48) +version = 0 if sys.argv[2] == 'loader' else 2 +if len(header) != 48 or header[:8] != b'ANDROID!' or struct.unpack_from(' "$KERNEL_OUT/images/DEVICE" + printf '%s\n' "$DEV_BOOT_METHOD" > "$KERNEL_OUT/images/BOOT_METHOD" + printf '%s\n' "$role" > "$KERNEL_OUT/images/BOOT_ROLE" + (cd "$KERNEL_OUT/images" && sha256sum boot.img > SHA256SUMS) + say 'Staged reviewed U-Boot image; Linux stays in /boot/omamobile/boot.img on userdata' + return + fi local img="$KERNEL_OUT/images" tools="$SRC_DIR/system/tools/mkbootimg" local dtc="$KERNEL_OUT/scripts/dtc/dtc" boot="$KERNEL_OUT/arch/arm64/boot" local dtb="$boot/dts/$DEV_DTB" @@ -663,6 +719,18 @@ fastboot_serial() { } cmd_fastboot() { + if [[ ${FLAME_NATIVE:-0} == 1 ]]; then + load_device + in_fastboot && return 0 + "$ROOT/tools/phone-ssh" 'systemctl --no-block --reboot-argument=bootloader reboot' \ + || die 'native flame reboot request failed; use Power + Volume Down' + local attempt + for ((attempt=0; attempt<30; attempt++)); do + sleep 2 + in_fastboot && return 0 + done + die 'native flame did not enter Android fastboot; use the buttons. No slot-A fallback attempted.' + fi local ssh="$ROOT/tools/phone-ssh" i in_fastboot && { say "Already in fastboot"; return 0; } for i in $(seq 1 12); do @@ -699,19 +767,54 @@ cmd_flash() { serial=$(fastboot_serial) || exit 1 # Every image and allowlist entry first: never start writing slot B and # find out halfway that a later image is missing. + if [[ $DEV_BOOT_METHOD == uboot-ext4 ]]; then + [[ $(cat "$img/BOOT_METHOD" 2>/dev/null) == uboot-ext4 ]] || die 'image boot method mismatch' + (cd "$img" && sha256sum -c SHA256SUMS) || die 'staged boot checksum mismatch' + local facts role + role=$(cat "$img/BOOT_ROLE" 2>/dev/null) + [[ $role == loader || $role == stock-recovery ]] || die 'missing flame image role' + facts='' + local variable value + for variable in product unlocked current-slot version-bootloader slot-successful:b; do + value=$(timeout 10 fastboot -s "$serial" getvar "$variable" 2>&1) || die "cannot inspect Android fastboot: $variable" + facts+="$value"$'\n' + done + [[ $facts != *U-Boot* ]] || die 'return to Android fastboot before flashing' + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])product:[[:space:]]*flame[[:space:]]*$' || die 'connected product is not flame' + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])unlocked:[[:space:]]*yes[[:space:]]*$' || die 'bootloader is locked' + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])current-slot:[[:space:]]*b[[:space:]]*$' || die 'flame requires the already-active, recovery-tested slot B' + if [[ $role == loader ]]; then + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])slot-successful:b:[[:space:]]*yes[[:space:]]*$' || die 'slot B must already be marked successful' + fi + fi + # Check every file before starting any write, including shared Android paths. for p in $DEV_BOOT_IMAGES; do slot_b_allowed "$p" || die "${p}_b is not on device/$DEVICE's storage-guard allowlist; refusing" [[ -f "$img/$p.img" ]] || die "missing $img/$p.img (run: omamobile images)" done local out rc for p in $DEV_BOOT_IMAGES; do + if [[ $DEV_BOOT_METHOD == uboot-ext4 && $(cat "$img/BOOT_ROLE") == loader ]]; then + timeout 30 fastboot -s "$serial" erase "${p}_b" || die 'boot B erase failed; staying in fastboot' + fi rc=0 out=$(timeout 60 fastboot -s "$serial" flash "${p}_b" "$img/$p.img" 2>&1) || rc=$? echo "$out" | grep -E 'OKAY|FAIL' | tail -1 | sed "s/^/$p: /" || true - # Stop before activating or rebooting into a half-written slot B + # Stop before activating or rebooting into a half-written slot B. ((rc == 0)) || die "flashing ${p}_b failed (exit $rc): slot B is incomplete, flash again before rebooting" done - timeout 20 fastboot -s "$serial" --set-active=b >/dev/null 2>&1 + if [[ $DEV_BOOT_METHOD == uboot-ext4 && $(cat "$img/BOOT_ROLE") == stock-recovery ]]; then + say 'Verified stock boot B restored; staying in Android fastboot. Factory-reset Android data through recovery before starting Android.' + return + fi + # Keep flame's existing successful-slot metadata: set_active would reset it, + # and its protected devinfo is never written by the Linux development root. + if [[ $DEV_BOOT_METHOD == android-v4 ]]; then + timeout 20 fastboot -s "$serial" --set-active=b >/dev/null 2>&1 + else + timeout 10 fastboot -s "$serial" getvar slot-successful:b 2>&1 | grep -Eq '(^|[[:space:]])slot-successful:b:[[:space:]]*yes[[:space:]]*$' \ + || die 'slot B success is clear; staying in fastboot. The boot-success policy decision is pending; use physical Fastboot recovery before any further boots.' + fi timeout 20 fastboot -s "$serial" reboot >/dev/null 2>&1 say "Booting slot B; waiting for SSH" local i @@ -719,12 +822,16 @@ cmd_flash() { "$ROOT/tools/phone-ssh" 'uname -v; cut -d" " -f1 /proc/uptime' 2>/dev/null && return 0 sleep 2 done + if [[ $DEV_BOOT_METHOD == uboot-ext4 ]]; then + die 'no SSH after flame boot; use the buttons to return to Android fastboot and follow the native recovery runbook' + fi die "no SSH after boot (the safety net returns to fastboot within about a minute)" } cmd_push() { local img="$KERNEL_OUT/images" ssh="$ROOT/tools/phone-ssh" p dev want got rel load_device + [[ $DEV_BOOT_METHOD == android-v4 ]] || die "native flame writes require Android fastboot; use flash" images_for_device "$img" "$ssh" true || die "phone not reachable at 172.16.42.1" # Refuse before any write. A phone whose initramfs has no reboot-to would diff --git a/device/flame/ABL-PLAN.md b/device/flame/ABL-PLAN.md new file mode 100644 index 000000000..88e624ee4 --- /dev/null +++ b/device/flame/ABL-PLAN.md @@ -0,0 +1,47 @@ + +# flame: direct ABL candidate, not a verified boot path + +Status: 2026-10-26, host assessment only. The measured Pixel 4 installation +still uses U-Boot. The Pixel 4 XL report in +[PR #52](https://github.com/derekross/omarchy-mobile/pull/52), +[BRINGUP-M1 at c0375d7](https://github.com/HemangKumawat/omarchy-mobile/blob/c0375d71e70bbba6a94c7901caa6bc01d3c8ed08/device/coral/BRINGUP-M1.md), +is a candidate recipe for the shared `c2f2-0.5-8906123` bootloader family. +Derek's [review](https://github.com/derekross/omarchy-mobile/pull/52#issuecomment-6428244248) +asks for the missing source branches and slot evidence. Its hardware results +have not been reproduced on flame and do not change flame's device matrix. + +## Source and image gates + +| Reported ABL requirement | Flame evidence / next gate | +| --- | --- | +| ARM64 Image `text_offset=0x80000` | The retained `7.0.0-sm8150` flame Image has `text_offset=0x0` (read-only host header inspection). Build a published, pinned GPL kernel branch with the reviewed `head.S` change; validate the built header. The current input does not pass this gate. | +| Modern LZ4 frame, magic `04 22 4d 18` | Build from that kernel's uncompressed Image with modern frame compression, then decompress and compare. The gzip payload used by U-Boot is not this ABL input. | +| Two base DTBs with `qcom,msm-id` revisions `<339 0x20000>` and `<339 0x20001>`, `qcom,board-id=<0 0>`, and symbols | Use the public flame DTS and its panel/touch configuration. Publish any source change in the kernel repository; validate both generated DTBs and retain their source pins. Coral's panel/board DTB is not a flame input. | +| Matched no-op `dtbo` entries | Derive count, IDs and revisions from the owner's own flame factory image and retain them privately. The coral MP1.0/index-11 values are evidence for coral only. Review a flame-specific guarded boot/dtbo path before any slot-B write. | + +The recipe needs Android header v2 with base `0`, page size `4096`, +kernel offset `0x8000`, ramdisk offset `0x01000000`, tags offset `0x100`, +and DTB offset `0x01f00000`. These values are a reported candidate, not a +flame boot test. The native U-Boot payload instead uses its standard +sentinel base `0x10000000`; the two images must never be interchanged. +Keep image roles and hashes separate. + +## Hardware gates after source and host validation + +Each step requires the owner's approval, current verified private backups, +physical Android Fastboot access, PID 1's watchdog, external logs and a fresh +independent RAM recovery login. This handset has no bootable stock A; +**recovery is the buttons alone** to Fastboot, with stock B backups ready. + +| Step | Expect / pass | Stop condition | Rollback | Risk | +| --- | --- | --- | --- | --- | +| Read-only slot/source check | Own boot/dtbo backups; B active; each slot's success/unbootable/retry flags and available bootloader versions recorded privately; source/header/DT checks pass | Missing or ambiguous evidence | Keep the current installation | Low | +| Separately reviewed candidate boot/dtbo stage | Named `boot_b`/`dtbo_b` writes only through a guarded flame-specific tool path, and only after explicit approval | No reviewed path, slot/size/hash mismatch, exhausted/unsuccessful B | Stay in Fastboot with private stock B images retained | High | +| Approved candidate boot | Guard holds; fresh root and RAM rescue logins; watchdog handoff; readable display | Hang, missing USB/control or unexpected write | Buttons to Android Fastboot | Medium | +| Approved normal/battery restarts | Fresh boot, clear UI, Wi-Fi traffic and protected hashes unchanged | Recovery loop, display fault, missing control | Buttons to Android Fastboot | Medium | + +Direct ABL could remove U-Boot and its small-image header-prefix erase. +It does not settle the boot-success policy: writing `boot_b` cleared its +success flag on the measured flame handset. GPT and userdata writes remain +held for the maintainer's named policy decision. No PMIC/PON latch or charger +register mechanism from the coral report is adopted by this assessment. diff --git a/device/flame/BOOT-PLAN.md b/device/flame/BOOT-PLAN.md new file mode 100644 index 000000000..8636cef70 --- /dev/null +++ b/device/flame/BOOT-PLAN.md @@ -0,0 +1,197 @@ + +# flame: installed loader and boot-success metadata + +**Policy hold (2026-10-26):** the SG_IO metadata writer below is a proposal. +It cannot land or run under current AGENTS.md until the maintainer approves +a named exception. A phone owner's hardware approval alone does not change +that repository policy. The proposed userdata flash is also held out of the +boot-method plumbing; no unsuffixed flash command is added by that split. + +Status: kernel `7.0.0-sm8150`, tested 2026-10-19; native profile requires +`DEVICE=flame FLAME_NATIVE=1`. The default profile remains RAM-only. +This is a development procedure for the measured Pixel 4 layout, not a +general Qualcomm installer. Stock A on this handset is unbootable. + +## Measured failures and corrections + +1. Writing the small header-v0 U-Boot image over stock boot B left old + Android ramdisk-size, OS-version and command-line bytes where the new + header contained zeros. The compressed U-Boot payload matched, but the + complete image prefix did not. Erasing **only `boot_b`** before flashing + the checked image produced an exact match, including every header byte. + The loader path in `bin/omamobile flash` now performs that erase. +2. Flashing boot B cleared `slot-successful:b`, even without `set_active`. + Preserving an already-successful flag is therefore insufficient. The + boot tool stops in Android fastboot when the flag is clear; it must not + declare a permanent installation complete or start repeated slot boots. +3. Pixel 4 uses Qualcomm GPT attributes for boot control. Its `devinfo` + is not the Tensor `DEVI` structure. Do not use the cheetah boot-success + writer on flame. The [coral HAL][coral] uses the [QCOM boot-control + implementation][bootctrl] and [coral GPT utilities][gpt]. The success + flag is bit 6 of attribute byte 6 (bit 54 of the 64-bit GPT attributes). + `isSlotMarkedSuccessful` queries the `boot_b` entry for slot B. +4. UFS LUN letters changed across a reboot. The NV partitions remained + byte-for-byte unchanged, but old `/dev/sdX` paths pointed at different + partitions. the packaged `flame-partition-links` helper now resolves unique GPT names into + root-only RAM symlinks and checks their read-only flags. The private + calibration manifest uses those links, so Wi-Fi's guard survives that + enumeration change. +5. A private bring-up journal override used `ForwardToConsole=yes` and + `TTYPath=/dev/ttyGS0`. After unplugging, the charger reported offline + while the USB controller still reported configured. The journal captured + 105 `remote wakeup not configured` errors in the four seconds before its + final shutdown record. Forwarding those errors back to the same USB + terminal creates a feedback path. The standalone journal configuration + disables that forwarding while retaining local logs. That change alone + did not pass the battery restart gate: the next shutdown progressed, + but the handset still required reconnection. +6. The native payload also requested `console=tty0 console=ttyGS0,115200`. + Linux uses the last console for `/dev/console` ([console documentation][console]), + so disabling journal forwarding did not remove USB from the normal + console path. The standalone payload uses `console=tty0` only; the + kernel, DT and ramdisk stay unchanged. The native builder now uses this + setting. Keep USB serial login an explicit attached-only debugging step. + +7. A later unreadable restart display led to a concrete U-Boot simplefb defect: + a missing `rot` property left an uninitialized value, and the probe ignored + framebuffer stride. The corrected driver defaults rotation and validates + row layout. The installed correction passed normal, deliberate-crash and + unplugged restarts. This is not proof of the original spontaneous runtime + reset cause. The separate GPL source and the new host-only configuration + are pinned by `tools/build-flame-loader`; see [native results](native/RESULTS.md). + +[coral]: https://android.googlesource.com/device/google/coral/+/refs/heads/android13-release/bootctrl/Android.bp +[bootctrl]: https://android.googlesource.com/platform/hardware/qcom/bootctrl/+/refs/heads/android13-release/boot_control.cpp +[gpt]: https://android.googlesource.com/device/google/coral/+/refs/heads/android13-release/gpt-utils/gpt-utils.h +[console]: https://docs.kernel.org/admin-guide/serial-console.html + +## Constrained boot-success exception + +Marking B successful is a separate, explicitly authorized boot-metadata +transaction. The implementation changes only boot B's success bit and +the two table/header checksums. It never changes partition GUIDs, names, +bounds, other attributes, remaining attempts, PMBR, or table padding. +It never creates `/dev/sda` or clears a read-only flag. This exception is +not a general permission for raw SCSI writes or additional writable nodes. +It is not enabled as an automatic startup service. + +The measured main LUN has 4096-byte sectors, 15 entries of 128 bytes, and +boot B at entry index 6. Both GPT copies are validated. The backup header +retains a primary-array pointer of LBA 2, while its physical table is +immediately before the final header. The helper verifies and preserves this +legacy layout rather than silently rewriting it into another GPT format. + +The tools are deliberately separate: + +- `native/read_gpt.py` permits only read-capacity and read commands, through + the existing, verified `boot_b` block node resolved by unique `PARTNAME`. + Both it and the final RO check resolve `userdata` by `PARTNAME` too, + require a common parent LUN, and reject missing/duplicate labels. It saves both GPT copies and + the surrounding reserved sectors. Its output contains identifiers and + must stay outside the repository. +- `native/boot_success_plan.py BEFORE.json PLAN.json` is host-only. It + validates the backup and proposes exactly four sector writes, backup + first. Only the boot-success bit and checksum bytes differ. +- `native/boot_success_apply.py` requires the backup and plan checksums, + the exact reviewed loader file and checksum, and the explicit apply + flag. It refuses a changed live GPT, changed plan, wrong model/layout, + inactive/unbootable B, or an installed loader that differs from the + reference. Every sector is read back before the next write; the complete + GPT reservation is compared afterward. Failed writes are never retried + automatically. An already-successful B needs no transaction. + +All three Python files run together from a root-only RAM directory on the +native phone. Keep the original snapshot and plan on the computer as well. +Stage the reviewed loader there for the exact-prefix check. Example of the +final command, **after** those files and safety checks are in place: + +```sh +python3 /run/flame-boot-repair/boot_success_apply.py \ + --backup /run/flame-boot-repair/before.json \ + --backup-sha256 "$verified_backup_sha256" \ + --plan /run/flame-boot-repair/plan.json \ + --plan-sha256 "$verified_plan_sha256" \ + --loader /run/flame-boot-repair/loader.img \ + --loader-sha256 "$reviewed_loader_sha256" \ + --apply-only-boot-b-successful +``` + +Use a current checksum-verified private backup set, PID 1's hardware watchdog, +external logging and an independent RAM return-to-fastboot timer. The +calibration manifest must already use the label-based RAM links. Cancel +the timer only after a fresh recovery SSH login. An unexpected result is +a stop condition, not a reason to weaken the guard or restore calibration. + +The apply command checks that PID 1 holds the watchdog and that this timer +is running. Arm it from the independently verified **RAM recovery SSH** +session (port 2222), not from an unverified root filesystem connection: + +```sh +cat > /run/flame-boot-repair-deadman.sh <<'EOF' +#!/bin/sh +/bin/busybox sleep 120 +/sbin/reboot-to bootloader +EOF +nohup /bin/sh /run/flame-boot-repair-deadman.sh \ + >/run/flame-boot-repair-deadman.log 2>&1 /run/flame-boot-repair-deadman.pid +``` + +Keep the computer's logging connection open, apply the reviewed transaction +from native Arch, then use a **new** RAM SSH login to check and stop the +saved timer PID. Do not leave a successful repair waiting for that reboot. + +## Installation and recovery gates + +| Step | Expect / pass | Stop condition | Rollback | Risk | +| --- | --- | --- | --- | --- | +| Check the recovery image, owner backups and temporary storage loader | Matching factory boot B retained; native ext4 root and reviewed loader already tested | Missing evidence or checksum mismatch | Stay in Android fastboot | Low | +| Stage the exact loader with `bin/omamobile images` | Checked `DEVICE`, role and image checksum | Wrong header/device/hash | Delete local staged output | Low | +| Install with `bin/omamobile flash` | Only boot B erased/written; flag-clear result stays in fastboot | Any identity, erase or flash failure | Restore the checked stock boot B through `stock-recovery` role; Android also needs a data reset | High | +| Historical failed-installation repair (policy hold) | B is still active, bootable and has attempts remaining | Wrong slot or exhausted B | Stay in fastboot | High | +| Temporarily boot the same reviewed storage loader | Native root, guard, watchdog and control return | Wrong root, storage error or missing control | Buttons to Android fastboot | Medium | +| Snapshot, review and apply the constrained success transaction | Exact loader prefix; one success bit plus checksums; all other GPT bytes and protected hashes unchanged | Any precondition/write/readback mismatch | Stop; preserve both GPT snapshots and Android fastboot | High | +| Restart into Android fastboot and inspect B | `slot-successful:b:yes`, `slot-unbootable:b:no` | Flag missing or slot changed | Remain in fastboot | Low | +| Start normally, then restart from Linux | Different boot ID, native desktop and automatic WLAN association; HTTPS and protected hashes pass | Recovery screen, missing control, firmware/storage/GPU fault | Android fastboot with the buttons | Medium | + +Synthetic tests cover the exact write scope/order, padding preservation, +checksums, stale/tampered plans, wrong loader bytes and failures at each +write. Keep those fixtures synthetic; never add a real GPT snapshot. + +## Earlier hardware result + +The corrected loader prefix matched exactly. The constrained transaction +read back every changed sector and preserved all other GPT bytes and all +storage read-only flags. Android fastboot then reported B successful and +bootable. Starting the installed loader normally, followed by two Linux +restarts, reached native Arch and the desktop each time. WLAN associated +automatically, interface-bound HTTPS returned HTTP 200, and all seven +protected calibration/modem hashes matched. A separate read after those +restarts confirmed the success flag remained set. Complete updated private +partition backups were also verified. + +Those first repeat boots had USB connected. With the standalone screen-console +payload, a further connected restart passed, followed by an automatic restart +triggered after cable removal. The owner confirmed the PIN screen returned +while unplugged. A fresh USB login then verified a different boot ID, active +desktop/guard/WLAN services, automatic association, HTTPS 200 and unchanged +protected hashes. The preceding shutdown journal contained no remote-wakeup +errors. The boot-success bit persisted, and no temporary restart units remained. +The repacked payload changed only its Android command-line bytes; kernel, +ramdisk, DT and installed U-Boot loader were unchanged. + +## Current validation boundary (2026-10-19) + +The later display-corrected installed loader passed four connected starts, +one deliberate crash recovery and an unplugged restart observed by the owner. +Five further display power cycles and the bounded paced-load/idle run passed. +Both GPT CRCs and boot B success remained valid, and all seven protected-data +hashes matched. No metadata transaction is needed again for that handset. + +The new recipe removes unused write/menu facilities and adds an invalid-width +arithmetic guard. The native builder also exits on its first guard failure +and no longer starts a USB getty automatically. These publication changes +were host tested/rebuilt, not flashed as part of preparing this PR. Do not +transfer the installed-image test results to these new image bytes without +a new approved RAM boot. Full evidence and remaining limits are in +[native/RESULTS.md](native/RESULTS.md). diff --git a/device/flame/BRINGUP-M1.md b/device/flame/BRINGUP-M1.md index 113a3323f..b219e8452 100644 --- a/device/flame/BRINGUP-M1.md +++ b/device/flame/BRINGUP-M1.md @@ -287,3 +287,12 @@ and panic reset have not been exercised on the phone. The provisioning container integration and root-image smoke test were skipped because their test image and a completed Omarchy root image were not present. ShellCheck passed for the new scripts. + +## Separate native-root development path (2026-10-19) + +The default descriptor and first-light tool above remain RAM-only. The explicit +`FLAME_NATIVE=1` profile, runtime package, source-pinned loader build and +separate userdata/boot-B gates are documented in +[native/README.md](native/README.md), with bounded handset results and +host-only publication changes in [native/RESULTS.md](native/RESULTS.md). +This does not establish a release installer or a healthy stock A fallback. diff --git a/device/flame/native/README.md b/device/flame/native/README.md new file mode 100644 index 000000000..4c36ba720 --- /dev/null +++ b/device/flame/native/README.md @@ -0,0 +1,174 @@ + +# flame: experimental permanent installation + +Status: 2026-10-19, measured on Pixel 4 with Linux `7.0.0-sm8150`. +Native Arch on ext4 `userdata` and a U-Boot loader in `boot_b` passed the +[recorded restart, display and app checks](RESULTS.md). This is an opt-in +contributor workflow, **not a release installer**. The published loader recipe +has additional host-only changes and needs a fresh approved RAM test. + +The ordinary `device/flame/device.conf` remains RAM-only. Only +`DEVICE=flame FLAME_NATIVE=1` selects [native/device.conf](device.conf). +The generic `tools/install-phone` still refuses flame. Native `push` and the +Tensor initramfs/image layout are refused; native boot writes go through +`bin/omamobile flash`. Nothing here automatically repairs GPT metadata, +selects a slot, restores calibration, or installs a separate Codex desktop app. + +## Prerequisites and source + +Read [BOOT-PLAN](../BOOT-PLAN.md) and the repository safety rules first. +Obtain the owner's approval for every hardware reboot or write. Keep a current +verified private backup set, matching factory image, physical Fastboot access, +and the exact stock boot/DTBO backups. The tested handset's stock A is +**unbootable**; it is not an available fallback. Restoring Android after this +installation also needs a factory data reset. Never relock the bootloader. + +| Component | Source / role | +| --- | --- | +| U-Boot base | Andrew Gigena's GPL flame tree, `0c42ac323aea8368b0624e405ded403351022df2`, [source](https://gitlab.com/andrewgigena/u-boot/-/commit/0c42ac323aea8368b0624e405ded403351022df2) | +| Display fix and standalone configuration | [GPL source](https://github.com/wirelessjoe/u-boot/tree/e210c6956ce90e48b667eb15a8c6f20bc292b52e), pinned by `tools/build-flame-loader`; includes the missing-rotation/stride correction, overflow fixture and compiled-environment checks | +| Linux inputs | The matching kernel, DTB, watchdog and modules listed in [BRINGUP-M1](../BRINGUP-M1.md); documentary firewall additions remain in [kernel-extra.config](../kernel-extra.config) | +| Native root | `omamobile-device-flame` plus the normal Omarchy Mobile packages; the owner supplies local first-boot configuration and SSH keys | +| Wi-Fi | Separate firmware/NV gates below; no Google firmware or device data is distributed | + +The automatic U-Boot path waits two seconds, scans UFS, resolves GPT +`userdata`, reads `/boot/omamobile/boot.img` through ext4 and runs `bootm`. +Healthy boots do not wait for USB. Failure enters download-only Fastboot. +The new configuration has a volatile environment and removes EFI/FAT writes, +DFU, USB mass-storage and fastboot OEM run facilities. It is not a hardware +storage guard: never issue interactive U-Boot storage-write commands. + +## Build on the host + +The loader tool needs a Linux environment with an aarch64 GCC cross compiler, +make, dtc, flex, bison, OpenSSL/UUID development headers and Python 3. Supply +AOSP `mkbootimg.py` together with its `gki/` helpers. It does not use the phone. + +```sh +git clone https://github.com/wirelessjoe/u-boot /path/to/u-boot +cd /path/to/u-boot +git checkout e210c6956ce90e48b667eb15a8c6f20bc292b52e +cd /path/to/omarchy-mobile +tools/build-flame-loader --uboot /path/to/u-boot \ + --mkbootimg /path/to/mkbootimg.py --out /private/output/loader +``` + +Build the native Linux payload with `tools/build-flame-system`, using the +same input flags as `tools/build-flame-probe`. Use a fresh output directory. +It verifies Pixel 4/SM8150, ARM64 Image magic and watchdog vermagic. The +native init has a separate initial allowlist of `boot_b userdata`; it never +clears read-only flags or recreates `/dev/sda`. All other UFS nodes remain +protected through the handoff to Arch. + +The default native payload disables all remote processors. `--wifi` enables +only `/soc@0/remoteproc@4080000` after checking that its compatible is +`qcom,sm8150-mpss-pas`. It does not supply firmware, start the radio or enable +its service. Keep the other DSPs disabled. The final Android command line +uses `console=tty0` only: a USB console or journal forwarding to ttyGS0 can +stall a restart after unplugging. ACM is available for explicit attached-only +debugging; it is not a standalone boot console. + +`DEVICE=flame FLAME_NATIVE=1 tools/build-rootfs --keep-raw` selects the flame +package and ext4 features compatible with the storage loader. It still needs +the normal signed local package repository and the complete matching modules. +The image has no owner, credentials, SSH host keys or Google firmware. A full +new signed root build is not part of the recorded host validation. + +## Root preparation and the current write boundary + +The native builder selects `omamobile-device-flame`, with first-boot 0.1.3 +and shell 0.2.24 hooks. Keep all images, owner configuration, public keys, +firmware and current backup manifests outside Git. Root image preparation +is host-only; this split does not add a userdata flash command. The proposed +userdata write and GPT transaction await the maintainer's policy decision +in [the original review](https://github.com/derekross/omarchy-mobile/pull/17#issuecomment-6428241495). +The generic installer remains unavailable for flame. + +The loader plumbing accepts only the checked header-v0 loader or a verified +64 MiB stock header-v2 boot B backup. Every Fastboot query/write is pinned to +one selected handset, using current main's `FASTBOOT_SERIAL` selection. A +loader install requires already-active successful B, erases/writes only boot B, +and stops in Fastboot if the success flag is cleared. It never selects a slot +or starts a GPT repair. Do not repeatedly boot an unsuccessful B. + +The native package enables only the storage guard. Its dependencies include +Foot, `xdg-terminal-exec` and `udiskie`. SDDM/user services use the tested +software-rendering fallback. Normal user setup selects 2.5 scale and merges +the tested 0.6 Chrome scale only if Chrome is installed. The helper preserves +other flags and backs up prior files. The upstream AI Agent chooser is used. + +## Rescue SSH and its authority + +The initramfs listener on `172.16.42.1:22` and the RAM rescue listener on +`172.16.42.1:2222` use the **same builder-supplied `key.pub`**, installed as +`/root/.ssh/authorized_keys` in each filesystem. The second listener survives +`switch_root` in a separate RAM root, with the real root bind-mounted +**read-write at `/realroot`**. Its key grants recovery write access to that +root; a separate process is not a separate credential or storage boundary. +The storage guard still protects other partitions. + +The initial rescue listener is IPv4-only. A host using USB IPv6 needs an +explicit USB-only IPv6 RAM listener, a key verified through the trusted Arch +connection and a fresh independently pinned login. Do not assume the root +filesystem's SSH connection proves RAM recovery works. + +The `phone-ssh` options support a known scoped USB endpoint, an explicit key +and a strict known-hosts file. Shared connections retain upstream's +`OMAMOBILE_SSH_SHARE=1`, `--fresh` and `--stop`; use `--fresh` to prove that +USB or firewall changes left a new connection possible. There is no LAN scan. + +## Gates before another hardware test + +These are separate owner-approved operations; the new split is host-tested. +Stock A is unbootable on the measured handset: recovery is **the buttons +alone** to reach Android Fastboot, with the verified stock B backups ready. + +| Gate | Expect / pass | Stop condition | Rollback | Risk | +| --- | --- | --- | --- | --- | +| Offline source/image check | Pinned sources, matching modules, checked image header/hash, clean ext4 and private backup set | Missing provenance or any mismatch | Discard local output | Low | +| Approved temporary boot of reviewed loader/native payload | Correct root, absent whole-disk node, protected partitions RO, PID 1 watchdog, clear UI and fresh root/rescue logins | Wrong root, storage/display fault or lost control | Physical Android Fastboot | Medium | +| Optional guarded Wi-Fi start | Current firmware/NV checks, association, bound HTTPS, hashes unchanged | Firmware/storage error or failed-start marker | Independent RAM recovery timer / physical Fastboot | Medium | +| Approved boot B loader write | One handset selected, exact reviewed bytes, active B; stop on clear success flag | Any identity/write/metadata error | Stay in Fastboot; separately approved stock B restoration | High | +| GPT success / userdata write | **Blocked pending a named maintainer policy exception** | No policy decision | Keep current installation and private backups | High | +| Approved connected/battery restart | New boot, clear UI, fresh SSH, Wi-Fi and protected hashes pass | Loop, unreadable display or missing control | Physical Android Fastboot | Medium | + +Arm a host log stream, PID 1 watchdog and an independent RAM recovery timer +before a risky driver/USB test. Cancel the timer only after a **fresh** RAM +recovery login. Do not use U-Boot or SCSI writes to work around the pending +metadata policy. [Direct ABL boot](../ABL-PLAN.md) is a candidate from the +Pixel 4 XL report, with no flame hardware result yet. + +## Wi-Fi provisioning remains a separate gate + +Ship `flame-wifi.service` disabled. The owner supplies matching `rmtfs` and +`tqftpserv`, modem/WLAN firmware, API metadata, and raw factory +`ath10k/WCN3990/hw1.0/board.bin`. Keep generic `board-2.bin` (including +compressed and update-directory copies) outside every firmware search path: +API 2 takes precedence over the tested raw factory board file. + +Create private manifests at `/etc/omamobile/flame-calibration.sha256` and +`flame-firmware.sha256`. Calibration paths use unique GPT-name links under +`/run/omamobile/flame-partitions`; LUN letters changed in a measured reboot. +Keep current protected NV copies, mode 0600, in root-only +`/var/lib/omamobile/flame/nv` as `modem_fs1`, `modem_fs2`, `modem_fsg`, +`modem_fsc`. Refresh the backup and copies after any stock Android boot. +The helper verifies current real-partition hashes before using RAM shadows; +rmtfs never gets the protected NV block nodes. Preserve its failed-start +marker until logs have been reviewed. Do not retry a failed radio loop or +load the untested UART pin overlay. Bluetooth stays blacklisted. + +## Recovery and limits + +To restore only the verified 64 MiB stock boot B backup, stage it with +`FLAME_BOOT_ROLE=stock-recovery`, `UBOOT_IMAGE`, `UBOOT_SHA256`, `DEVICE=flame` +and `FLAME_NATIVE=1`. The flash tool writes only boot B and stays in Android +Fastboot. Restoring Android requires the matching factory data-reset path; +this loses native userdata. Never restore calibration as a routine rollback. +This stock restore role has mock coverage; the full post-native Android +restore/factory-reset cycle has not been performed on the handset. + +Hardware acceleration, Bluetooth pairing, modem calls, audio/camera and +release-quality power management are not established by these tests. Large +USB output still needs small verified transfers. The original spontaneous +runtime-reset cause remains unresolved. Read [RESULTS](RESULTS.md) before +interpreting the successful restart tests as general reliability evidence. diff --git a/device/flame/native/RESULTS.md b/device/flame/native/RESULTS.md new file mode 100644 index 000000000..d55e41077 --- /dev/null +++ b/device/flame/native/RESULTS.md @@ -0,0 +1,122 @@ + +# Pixel 4 native-install validation — 2026-10-19 + +The handset ran Linux `7.0.0-sm8150`, native Arch on ext4 `userdata`, +Hyprland/Quickshell with software rendering, and a storage-loading U-Boot in +`boot_b`. Results below describe that measured development installation, +not a release claim for every Pixel 4 or the new recipe's exact output. +The review split was refreshed against main on 2026-10-26; no new hardware +result is implied by that rebase. +Private logs, backup manifests, device identifiers, credentials, NV data and +firmware are retained off-repository. No such input or binary is published. + +## Measured handset procedure + +| Check | Observed result | Scope / limit | +| --- | --- | --- | +| Native root handoff | Arch, PID 1 watchdog, storage guard and mobile home/PIN UI reached from ext4 userdata | The root was assembled locally, including owner inputs and matching external firewall modules | +| Installed loader bytes | Full reviewed image prefix matched, including zero-valued header fields | Boot B was erased before the small header-v0 image was written; payload-only comparison previously missed stale header bytes | +| Boot-success correction | Four sectors, backup table/header first, then primary table/header; each read back; only B success bit and required CRCs changed | Explicit owner-approved one-time GPT exception; no automatic boot-success service; no calibration writes | +| Normal connected starts | Initial normal installed-loader start plus three further connected restarts passed | Different boot IDs; guard/desktop/Wi-Fi services active and protected hashes matched; not an endurance run | +| Deliberate abrupt restart | After stopping the display manager and syncing data, one intentional kernel panic returned automatically to Linux | Wi-Fi association, interface-bound HTTPS 200 and protected hashes passed; this was a deliberate test, not an observed spontaneous fault | +| Unplugged restart | A one-shot trigger requested one normal restart after charger-offline detection; owner saw a clear PIN screen before reconnecting | Fresh USB login verified new boot, Wi-Fi/HTTPS and protected hashes; trigger was transient and cannot repeat after reboot | +| Display power cycles | One earlier on/off/on check and five additional cycles passed at the existing 90 Hz mode | Reported off/on state and same boot checked; independent RAM recovery login passed and timer was cancelled; final PIN image was readable | +| Paced load / idle | Two 64 MiB hash workers at approximately 50% duty for 120 s, then 180 s without synthetic load; 301 s elapsed; same boot | Highest sampled sensor 60.8°C; hash loops, services, protected data and Wi-Fi HTTPS passed; not a full-load endurance pass | +| Full-duty stress attempt | Stopped at the first 10 s temperature check, processor sensor 71.7°C | Conservative test cutoff was 70°C, below the kernel's existing CPU thermal-control trips; workers stopped, temperature recovered and no reboot occurred; cooling settings unchanged | +| Protected data | Seven current calibration/modem hashes matched; complete 12-partition backup set verified off-device | Counts/results only; no real hashes, partition contents or device identifiers are published | +| Chrome license / scrolling | Native Wayland, disabled GPU and scale factor 0.6 fit the license dialog; owner accepted it and confirmed finger scrolling on a webpage | Chrome was owner-installed; no license was accepted automatically; profile retained; Chrome is not added as a project dependency | +| Agent app | The owner signed in and a short prompt replied normally | Controlled retry passed; an earlier full reset remains unexplained | +| Final state | Both GPT CRCs valid, B success set, other metadata/reserved bytes preserved outside B attributes/required CRCs; fresh SSH, Wi-Fi/HTTPS and protected hashes passed | No failed system units or active test/recovery timers; temporary IPv6 recovery listener removed; Docker builders stopped after work | + +The U-Boot driver correction is [cefacc22](https://github.com/wirelessjoe/u-boot/commit/cefacc22d1377071d70e5bc93e48ddbaf40fe65a): +missing `rot` no longer leaves a stack value in console selection, and the +probe honors and bounds framebuffer stride. The installed test image used +that driver plus the same peripheral USB DT and two-second storage path. +The later generic invalid-width guard and smaller configuration are separated +below; they were not silently substituted for the measured installed image. + +The standalone Linux payload used `console=tty0` only, and the journal did +not forward to ttyGS0. Earlier journal-only changes were insufficient while +USB remained the last Linux console. The final battery restart passed after +USB was removed from the console path. A USB replug/SSH failure alone was +not counted as a spontaneous reboot: a fresh boot-ID check distinguished a +large-transfer stall from an actual reset. + +## Host checks for this PR + +- `tests/all`: passed, including retained shared guard/USB-product/boot-method + tests and new native loader staging/role refusal, serial selection, first-guard + fail-fast, GPT failure/readback/padding, PARTNAME discovery and scoped/shared-SSH fixtures. + Container provisioning and root-image smoke cases skip when their optional + fixtures are unavailable; a new signed complete root image was not built. +- `packages/omamobile-device-flame/test/all`: guard-only activation, disabled + Wi-Fi unit, standalone journal and owner configuration merge/backup/repeat + checks passed. The browser helper preserves unrelated flags and refuses an + unknown monitor layout rather than overwriting it by guesswork. +- `packages/omamobile-shell/test/all`: passed with the documented optional + tool-dependent skips. The refreshed hooks are shell 0.2.24 and first-boot 0.1.3; + those package versions have host checks, with no fresh phone install. +- ShellCheck passed for added scripts. Changed legacy scripts were checked + with their pre-existing diagnostics excluded; no new warning was retained. +- `tools/build-flame-loader`: complete `W=1` build, generated configuration + and compiled environment inspection, Android header/payload checks and + output checksums passed. Inherited platform DTS/missing-prototype warnings + remain; the changed simplefb driver produced no new warning. +- The actual simplefb probe ran under host ASan/UBSan for missing/explicit + rotation, packed/padded/16-bit rows, invalid stride/buffer size and overflow. + The original driver is rejected by the regression fixture. Strict checkpatch + passed with sign-off omitted (human DCO still required for upstream) and + only the new-file MAINTAINERS advisory excluded for the new board/test files. +- `tools/build-flame-system --wifi`: rebuilt and inspected on the host with + the supplied matching kernel/watchdog and local public key. The resulting + image/key material stays private; nothing was booted or flashed in PR prep. + +### Changes requiring a new hardware gate + +The pinned U-Boot source is +[`e210c6956ce90e48b667eb15a8c6f20bc292b52e`](https://github.com/wirelessjoe/u-boot/tree/e210c6956ce90e48b667eb15a8c6f20bc292b52e). +Compared with the handset's tested image, it removes unused EFI/FAT-write, +DFU, mass-storage, environment-save and fastboot OEM facilities/menu entries +and adds an invalid-width arithmetic guard. Its healthy boot sequence and +USB role remain the measured ones. The new package explicitly supplies the watchdog/USB network policy measured +on the hand-built root, and first-boot 0.1.3 scopes recovery/DHCP firewall +rules to native flame on USB. The native init also now exits on the +first storage-guard failure and leaves USB getty startup explicit rather +than automatic. These outputs were host-built/checked only. Package assembly was host-fixture tested. The proposed userdata writer +is held out of the low-risk split pending the maintainer's policy decision. Perform the native runbook's new approved +RAM boot and recovery gates before installing any new output image. + +## Reproducing the bounded load check + +After owner approval, protected-data preflight, a fresh independent recovery +login and an external host kernel-log stream, stage `validation/load-idle.sh` +in RAM. PID 1 must hold the watchdog. Run it in a transient unit so an SSH +loss cannot leave workers running indefinitely: + +```sh +systemd-run --wait --pipe --collect --unit=flame-native-validation \ + --property=RuntimeMaxSec=340 --property=KillMode=control-group \ + /bin/bash /run/load-idle.sh +``` + +Keep output private. Stop on a temperature cutoff or new error. Require the +same boot, final service/Wi-Fi/protected-data checks and an inactive unit. +Screen cycles and each restart remain separate human-approved gates; never +turn the deliberate panic test into an automatic startup hook. + +## Open limits + +### Intermittent runtime reset + +One owner-reported full reset near agent sign-in remains unexplained. A +controlled sign-in and prompt retry passed on the same boot, with host +capture and unchanged protected hashes. No implementation change explains +that pass; sustained use and the reset investigation remain open. + +The original spontaneous runtime-reset cause is **not conclusively identified**. +The bounded tests did not reproduce an unplanned reset. Hardware GPU +acceleration remains disabled, Bluetooth firmware download/pairing has not +passed, and large phone-to-host USB output can stall (64 KiB verified +retrievals worked). Calls, audio/cameras, full Android rollback/factory reset, +release power management and long-term stability are not established. +A successful temporary boot or one working app does not close those gates. diff --git a/device/flame/native/boot_success_apply.py b/device/flame/native/boot_success_apply.py new file mode 100644 index 000000000..d82a6f34c --- /dev/null +++ b/device/flame/native/boot_success_apply.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Explicit one-time boot_b GPT success transaction; no RO flags are changed.""" +import argparse +import base64 +import ctypes as C +import hashlib +import json +import os +from pathlib import Path +import struct +import subprocess + +from read_gpt import Header, Reader, require, snapshot, verify_storage +from boot_success_plan import plan + + +def verify_safety_net(): + held = False + for fd in Path('/proc/1/fd').iterdir(): + try: + held = held or os.readlink(fd) == '/dev/watchdog0' + except FileNotFoundError: + continue + require(held, 'PID 1 must hold the hardware watchdog') + pid = int(Path('/run/rescue/run/flame-boot-repair-deadman.pid').read_text().strip()) + require(pid > 1, 'invalid recovery timer PID') + require(b'flame-boot-repair-deadman.sh' in Path('/proc/' + str(pid) + '/cmdline').read_bytes(), + 'independent RAM recovery timer is not running') + + +def verify_loader(image, expected_sha256, installed): + require(4096 < len(image) <= 4*1024*1024, 'unsupported loader size') + require(hashlib.sha256(image).hexdigest() == expected_sha256, 'loader checksum mismatch') + require(image[:8] == b'ANDROID!', 'loader header missing') + require(struct.unpack_from('QI', lba, 1) + bytes(2) + cmd = C.create_string_buffer(cdb); data = C.create_string_buffer(new); sense = C.create_string_buffer(96) + h = Header(interface_id=ord('S'), dxfer_direction=-2, cmd_len=16, + mx_sb_len=96, dxfer_len=r.bs, dxferp=C.addressof(data), + cmdp=C.addressof(cmd), sbp=C.addressof(sense), timeout=15000) + result = r.libc.ioctl(r.fd, 0x2285, C.byref(h)) + require(result == 0, 'write ioctl failed, errno=' + str(C.get_errno())) + require(not (h.status or h.host_status or h.driver_status or h.resid), 'SCSI write did not complete cleanly') + require(r.read(lba) == new, 'sector readback mismatch; stop without further writes') + print('Verified metadata sector', number, 'of 4', flush=True) + after = snapshot(r) + expected = dict(before['blocks']) + for w in approved['writes_backup_first']: + expected[str(w['lba'])] = w['new'] + require(after['blocks'] == expected, 'unplanned GPT byte change') + b = [p for p in after['partitions'] if p['name'] == 'boot_b'] + require(len(b) == 1 and b[0]['attributes'] & (1 << 54), 'successful flag did not read back') + require(verify_storage() == (r.boot_node, r.userdata_node, r.disk_node), + 'partition nodes changed during the transaction') + print('BOOT_B_SUCCESSFUL_READBACK_VERIFIED; all other GPT bytes and storage RO flags preserved', flush=True) + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('--backup', required=True) + p.add_argument('--backup-sha256', required=True) + p.add_argument('--plan', required=True) + p.add_argument('--plan-sha256', required=True) + p.add_argument('--loader', required=True) + p.add_argument('--loader-sha256', required=True) + p.add_argument('--apply-only-boot-b-successful', action='store_true', required=True) + args = p.parse_args() + backup = Path(args.backup).read_bytes(); approved = Path(args.plan).read_bytes() + require(hashlib.sha256(backup).hexdigest() == args.backup_sha256, 'backup checksum mismatch') + require(hashlib.sha256(approved).hexdigest() == args.plan_sha256, 'plan checksum mismatch') + subprocess.run(['systemctl', 'is-active', '--quiet', 'flame-storage-guard.service'], check=True) + subprocess.run(['/usr/bin/flame-partition-links'], check=True) + subprocess.run(['sha256sum', '--check', '--status', '/etc/omamobile/flame-calibration.sha256'], check=True) + verify_safety_net() + r = Reader() + image = Path(args.loader).read_bytes() + verify_loader(image, args.loader_sha256, os.pread(r.fd, len(image), 0)) + apply(r, json.loads(backup), json.loads(approved)) diff --git a/device/flame/native/boot_success_plan.py b/device/flame/native/boot_success_plan.py new file mode 100644 index 000000000..df6509285 --- /dev/null +++ b/device/flame/native/boot_success_plan.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Plan exactly one Qualcomm boot_b successful bit, preserving both GPT copies.""" +import base64 +import copy +import hashlib +import json +import struct +import sys +import zlib +from pathlib import Path + + +def require(ok, message): + if not ok: + raise RuntimeError(message) + + +def digest(value): + return hashlib.sha256(value).hexdigest() + + +def plan(snapshot): + bs = snapshot['sector_size']; last = snapshot['last_lba'] + require(bs == 4096 and last > 1024, 'unsupported disk geometry') + old = {int(k): base64.b64decode(v, validate=True) for k, v in snapshot['blocks'].items()} + require(all(len(v) == bs for v in old.values()), 'invalid sector backup') + headers = [snapshot['primary'], snapshot['backup']] + require(all(h['count'] == 15 and h['entry_size'] == 128 and h['blocks'] == 1 for h in headers), 'unverified partition layout') + require(headers[0]['physical_entries'] == 2 and headers[1]['physical_entries'] == last-1, 'unverified GPT locations') + require(set(old) == set(range(6)) | set(range(last-4, last+1)), 'incomplete GPT backup') + new = copy.copy(old) + tables = [] + for location, h in zip((1, last), headers): + raw = old[location]; table = old[h['physical_entries']] + require(raw[:8] == b'EFI PART', 'bad signature') + require(struct.unpack_from('&2; exit 1; +} +case " $(fdtget /input/flame.dtb / compatible) " in + *' qcom,sm8150 '*) ;; + *) echo 'Not an SM8150 device tree' >&2; exit 1 ;; +esac +gzip -t /input/kernel || { echo 'Expected a gzip-compressed ARM64 Image' >&2; exit 1; } +gzip -dc /input/kernel > /tmp/Image +python3 - <<'PY' +from pathlib import Path +import sys +with Path('/tmp/Image').open('rb') as stream: + stream.seek(56) + if stream.read(4) != b'ARM\x64': + sys.exit('Kernel has no ARM64 Image header') +PY +release=$(strings /tmp/Image | sed -n 's/^Linux version \([^ ]*\) .*/\1/p' | head -1) +rm /tmp/Image + +stage=/tmp/rootfs +mkdir -p "$stage" +apk --root "$stage" --initdb --no-cache \ + --repositories-file /etc/apk/repositories --keys-dir /etc/apk/keys add \ + alpine-baselayout busybox dropbear iproute2 util-linux busybox-extras e2fsprogs +install -m755 /system-init "$stage/init" +mkdir -p "$stage/root/.ssh" "$stage/proc" "$stage/sys" "$stage/dev" "$stage/run" +cp /input/key.pub "$stage/root/.ssh/authorized_keys" +chmod 700 "$stage/root/.ssh" +chmod 600 "$stage/root/.ssh/authorized_keys" +gcc -Os -static -o "$stage/sbin/reboot-to" \ + /src/packages/omamobile-device-cheetah/src/reboot-to.c +mkdir -p "$stage/lib/modules" +module=$stage/lib/modules/qcom-wdt.ko +if zstd -t /input/watchdog 2>/dev/null; then + zstd -dc /input/watchdog > "$module" +else + cp /input/watchdog "$module" +fi +[ "$(modinfo -F name "$module")" = qcom_wdt ] || { echo 'Expected qcom-wdt module' >&2; exit 1; } +if [ -z "$release" ] || [ "$(modinfo -F vermagic "$module" | cut -d ' ' -f1)" != "$release" ]; then + echo 'Watchdog module does not match the kernel release' >&2 + exit 1 +fi +[ -z "$(modinfo -F depends "$module")" ] || { echo 'Watchdog needs additional modules' >&2; exit 1; } + +# A separate RAM rescue root survives the desktop handoff. +rescue=/tmp/rescue-base +mkdir -p "$rescue" +apk --root "$rescue" --initdb --no-cache \ + --repositories-file /etc/apk/repositories --keys-dir /etc/apk/keys add \ + alpine-baselayout busybox dropbear iproute2 util-linux +mkdir -p "$rescue/root/.ssh" "$rescue/proc" "$rescue/sys" "$rescue/dev" "$rescue/run" "$rescue/realroot" +cp /input/key.pub "$rescue/root/.ssh/authorized_keys" +chmod 700 "$rescue/root/.ssh" +chmod 600 "$rescue/root/.ssh/authorized_keys" +cp "$stage/sbin/reboot-to" "$rescue/sbin/reboot-to" +mv "$rescue" "$stage/rescue-base" + +# No vendor firmware enters the probe. Only the watchdog module is included; +# remote processors stay disabled unless the explicit Wi-Fi profile below is used. +cp /input/flame.dtb /out/flame.dtb +usb=/soc@0/usb@a6f8800/usb@a600000 +fdtput -t s /out/flame.dtb "$usb" dr_mode peripheral +fdtput -d /out/flame.dtb "$usb" usb-role-switch +for node in remoteproc@2400000 remoteproc@4080000 remoteproc@8300000 remoteproc@17300000; do + fdtput -t s /out/flame.dtb "/soc@0/$node" status disabled +done +if [ "${FLAME_WIFI:-0}" = 1 ]; then + [ "$(fdtget /out/flame.dtb /soc@0/remoteproc@4080000 compatible)" = qcom,sm8150-mpss-pas ] || exit 1 + fdtput -t s /out/flame.dtb /soc@0/remoteproc@4080000 status okay +fi +(cd "$stage" && find . -print0 | cpio --null --quiet -o -H newc --owner=0:0) \ + | gzip -n -9 > /out/initramfs.cpio.gz +# U-Boot recognizes these standard Android addresses as sentinels: decompress +# to its kernel_addr_r and leave the ramdisk in its download buffer. Using +# Android ABL's base=0 instead asks U-Boot to write to physical 0x8000. +# Keep /dev/console off USB for standalone operation. USB networking and an +# explicitly started serial login remain available without being boot consoles. +python3 /mkbootimg/mkbootimg.py --header_version 2 \ + --base 0x10000000 --kernel_offset 0x8000 --ramdisk_offset 0x1000000 \ + --dtb_offset 0x1f00000 --pagesize 4096 \ + --kernel /input/kernel --ramdisk /out/initramfs.cpio.gz --dtb /out/flame.dtb \ + --os_version 13.0.0 --os_patch_level 2022-10 \ + --cmdline 'console=tty0 rdinit=/init clk_ignore_unused pd_ignore_unused fw_devlink=permissive panic=10 printk.devkmsg=on' \ + -o /out/boot.img +size=$(stat -c %s /out/boot.img) +[ "$size" -le 67108864 ] || { rm /out/boot.img; echo 'Probe exceeds the 64 MiB boot partition' >&2; exit 1; } +(cd /out && sha256sum boot.img flame.dtb initramfs.cpio.gz > SHA256SUMS) diff --git a/device/flame/native/device.conf b/device/flame/native/device.conf new file mode 100644 index 000000000..72cb62f86 --- /dev/null +++ b/device/flame/native/device.conf @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: MIT +# Explicit opt-in development profile: DEVICE=flame FLAME_NATIVE=1. +# The default device/flame/device.conf remains RAM-only. +# Experimental U-Boot layout. Requires a locally built, reviewed loader and +# a separately tested native root. No Tensor images or DTBO are written. +CODENAME=flame +NAME="Google Pixel 4" +SOC=sm8150 +COMPATIBLE="google,floral-sm8150" +BOOT_METHOD=uboot-ext4 +BOOT_IMAGES="boot" +UFS_RW="boot_b userdata" +PANEL_SIZE=1080x2280 +PACKAGE=omamobile-device-flame diff --git a/device/flame/native/init b/device/flame/native/init new file mode 100644 index 000000000..41911e79c --- /dev/null +++ b/device/flame/native/init @@ -0,0 +1,184 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT +# Pixel 4 development root boot. Only userdata and boot_b are writable. +export PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + +# PID 1 exiting on a mount failure deliberately panics (panic=10), rather +# than exposing a root shell with an uninitialized storage guard. +mount -t proc proc /proc || exit 1 +mount -t sysfs sysfs /sys || exit 1 +mount -t devtmpfs devtmpfs /dev || exit 1 +mkdir -p /dev/pts /run +mount -t devpts devpts /dev/pts || exit 1 +mount -t tmpfs tmpfs /run || exit 1 +mount -t configfs configfs /sys/kernel/config || exit 1 + +say() { + echo "omamobile-flame: $*" > /dev/kmsg + echo "omamobile-flame: $*" > /dev/tty0 2>/dev/null +} + +# New install boot only: the owner authorized using userdata and boot_b. +# This is a separate init, never a relaxation of a running RAM-only probe. +UFS_RW="boot_b userdata" +part_name() { sed -n 's/^PARTNAME=//p' "$1/uevent"; } +storage_guard() { + for s in /sys/class/block/sd*; do + [ -r "$s/ro" ] || continue + name=${s##*/} + if [ "$name" = sda ]; then + rm -f /dev/sda + continue + fi + [ -b "/dev/$name" ] || continue + part=$(part_name "$s") + case "$name" in + sda[0-9]*) + # A previously read-only device stays so; never use --setrw. + case " $UFS_RW " in *" $part "*) continue ;; esac ;; + esac + [ "$(cat "$s/ro")" = 1 ] && continue + if ! blockdev --setro "/dev/$name" || [ "$(cat "$s/ro")" != 1 ]; then + say "FAILED to protect /dev/$name" + return 1 + fi + done + [ ! -e /dev/sda ] +} +storage_guard || exit 1 +( + while :; do + if ! storage_guard; then + killall dropbear getty 2>/dev/null + echo c > /proc/sysrq-trigger + exit 1 + fi + sleep 0.2 + done +) & + +hostname omamobile-flame +say "Pixel 4 development root boot: $(uname -r)" + +# Take over the hardware watchdog before running probes. If the kernel +# stalls, its keeper stalls too and recovery requires Android fastboot and the verified stock boot image. +if ! insmod /lib/modules/qcom-wdt.ko; then + say 'Watchdog module failed; returning to bootloader' + reboot-to bootloader + while :; do sleep 60; done +fi +for _ in $(seq 1 5); do + [ -c /dev/watchdog0 ] && break + sleep 1 +done +if [ -c /dev/watchdog0 ]; then + watchdog -F -t 5 -T 30 /dev/watchdog0 & +else + say 'No watchdog device; returning to bootloader' + reboot-to bootloader + while :; do sleep 60; done +fi + +# CDC NCM works with Linux and macOS without a proprietary host driver. +g=/sys/kernel/config/usb_gadget/omamobile +mkdir -p "$g/strings/0x409" "$g/configs/c.1/strings/0x409" +echo 0x1d6b > "$g/idVendor" +echo 0x0104 > "$g/idProduct" +echo 'Omarchy Mobile' > "$g/strings/0x409/manufacturer" +echo 'Pixel 4 (Omarchy Mobile)' > "$g/strings/0x409/product" +echo omamobile-flame > "$g/strings/0x409/serialnumber" +echo 'NCM + ACM' > "$g/configs/c.1/strings/0x409/configuration" +mkdir -p "$g/functions/ncm.usb0" "$g/functions/acm.GS0" +ln -s "$g/functions/ncm.usb0" "$g/configs/c.1/" +ln -s "$g/functions/acm.GS0" "$g/configs/c.1/" + +udc="" +for _ in $(seq 1 30); do + for controller in /sys/class/udc/*; do + [ -e "$controller" ] && udc=${controller##*/} && break + done + [ -n "$udc" ] && break + sleep 1 +done +if [ -n "$udc" ] && echo "$udc" > "$g/UDC"; then + say "USB gadget bound to $udc" +else + say 'No USB controller; return to Android fastboot with the buttons' +fi + +ip link set lo up +ip addr add 172.16.42.1/24 dev usb0 +ip link set usb0 up +cat > /run/udhcpd.conf <<'CONF' +start 172.16.42.2 +end 172.16.42.2 +interface usb0 +option subnet 255.255.255.0 +lease_file /run/udhcpd.leases +CONF +touch /run/udhcpd.leases +udhcpd /run/udhcpd.conf + +# Only the locally supplied public key grants SSH access. Host keys are +# generated in the RAM filesystem; no identity or vendor firmware is shipped. +mkdir -p /etc/dropbear +dropbear -R -E -s -j -k -p 172.16.42.1:22 +say 'USB ready; protected storage; waiting for the Omarchy root' + +# ACM is for an explicitly started attached-only debug session. Never start +# an automatic USB getty in the standalone boot path. + +# Recover both an initial failure and a later disconnection. The helper uses +# RESTART2 to request Android fastboot; no filesystems need shutting down. +( + missing=0 + while :; do + if grep -qx configured /sys/class/udc/*/state 2>/dev/null; then + missing=0 + else + missing=$((missing + 1)) + fi + if [ "$missing" -ge 90 ]; then + say 'USB disconnected for 90 s; returning to bootloader' + reboot-to bootloader + fi + sleep 1 + done +) & + +# The root is located by its GPT name and label, never by a guessed number. +rootdev="" +for _ in $(seq 1 20); do + storage_guard || exit 1 + for node in /sys/class/block/sda[0-9]*; do + [ -r "$node/uevent" ] || continue + [ "$(part_name "$node")" = userdata ] || continue + [ -z "$rootdev" ] || { say 'Duplicate userdata partition'; exit 1; } + rootdev=/dev/${node##*/} + done + [ -n "$rootdev" ] && break + sleep 1 +done +[ -b "$rootdev" ] || { say 'No userdata partition'; exit 1; } +[ "$(blockdev --getro "$rootdev")" = 0 ] || { say 'Root is read-only; refusing to weaken guard'; exit 1; } +[ "$(blkid -s LABEL -o value "$rootdev")" = omamobile-root ] || { say 'Wrong root label'; exit 1; } +fsck_status=0 +e2fsck -p "$rootdev" || fsck_status=$? +[ "$fsck_status" -le 1 ] || { say 'Root filesystem check failed'; exit 1; } +mkdir -p /newroot +mount -t ext4 -o rw,relatime "$rootdev" /newroot || exit 1 +[ -x /newroot/usr/lib/systemd/systemd ] || { say 'Root has no systemd'; exit 1; } +[ -f /newroot/usr/share/omamobile/flame-root ] || { say 'Root is not a flame development image'; exit 1; } +cp -a /rescue-base /run/rescue || exit 1 +say 'Starting Arch and Omarchy on userdata' +kill -9 -1 2>/dev/null +for m in /dev /proc /sys /run; do + mkdir -p "/newroot$m" + mount --move "$m" "/newroot$m" || exit 1 +done +for m in /dev /proc /sys; do + mount --bind "/newroot$m" "/newroot/run/rescue$m" || exit 1 +done +mount --bind /newroot /newroot/run/rescue/realroot || exit 1 +chroot /newroot/run/rescue /usr/sbin/dropbear -R -E -s -j -k -p 172.16.42.1:2222 || exit 1 +exec switch_root /newroot /usr/lib/systemd/systemd diff --git a/device/flame/native/read_gpt.py b/device/flame/native/read_gpt.py new file mode 100644 index 000000000..4d2066d1d --- /dev/null +++ b/device/flame/native/read_gpt.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Read-only SCSI/GPT snapshot through the existing boot_b partition node.""" +import base64 +import ctypes as C +import hashlib +import json +import os +from pathlib import Path +import stat +import struct +import sys +import zlib + + +class Header(C.Structure): + _fields_ = [ + ('interface_id', C.c_int), ('dxfer_direction', C.c_int), + ('cmd_len', C.c_ubyte), ('mx_sb_len', C.c_ubyte), + ('iovec_count', C.c_ushort), ('dxfer_len', C.c_uint), + ('dxferp', C.c_void_p), ('cmdp', C.c_void_p), ('sbp', C.c_void_p), + ('timeout', C.c_uint), ('flags', C.c_uint), ('pack_id', C.c_int), + ('usr_ptr', C.c_void_p), ('status', C.c_ubyte), + ('masked_status', C.c_ubyte), ('msg_status', C.c_ubyte), + ('sb_len_wr', C.c_ubyte), ('host_status', C.c_ushort), + ('driver_status', C.c_ushort), ('resid', C.c_int), + ('duration', C.c_uint), ('info', C.c_uint), + ] + + +def require(ok, message): + if not ok: + raise RuntimeError(message) + + +def resolve_layout(sysfs=None): + """Resolve unique boot_b/userdata partitions and their shared UFS LUN.""" + sysfs = Path('/sys/class/block') if sysfs is None else sysfs + found = {'boot_b': [], 'userdata': []} + for node in sysfs.glob('sd*'): + try: + lines = (node / 'uevent').read_text().splitlines() + except FileNotFoundError: + continue + for name in found: + if 'PARTNAME=' + name in lines: + found[name].append(node) + require(all(len(nodes) == 1 for nodes in found.values()), 'missing or ambiguous boot_b/userdata PARTNAME') + boot, userdata = found['boot_b'][0], found['userdata'][0] + require(all((node / 'partition').is_file() for node in (boot, userdata)), 'expected partition nodes') + parent = boot.resolve().parent + require(userdata.resolve().parent == parent, 'boot_b and userdata are on different LUNs') + disk = sysfs / parent.name + require(disk.resolve() == parent and 'DEVTYPE=disk' in (disk / 'uevent').read_text().splitlines(), 'unverified parent LUN') + return boot, userdata, disk + + +def verify_storage(sysfs=None, devdir=None): + sysfs = Path('/sys/class/block') if sysfs is None else sysfs + devdir = Path('/dev') if devdir is None else devdir + boot, userdata, disk = resolve_layout(sysfs) + require(not (devdir / disk.name).exists(), 'whole-disk node must stay absent') + for node in sysfs.glob('sd*'): + if node.name in (disk.name, userdata.name): + continue + require((node / 'ro').read_text().strip() == '1', 'protected storage is writable') + return boot, userdata, disk + + +class Reader: + def __init__(self): + require(Path('/usr/share/omamobile/flame-root').is_file(), 'wrong root') + require(Path('/proc/device-tree/model').read_bytes().rstrip(b'\0') == b'Google Pixel 4', 'wrong model') + self.boot_node, self.userdata_node, self.disk_node = verify_storage() + device = Path('/dev') / self.boot_node.name + require(stat.S_ISBLK(device.stat().st_mode), 'expected block node') + self.fd = os.open(device, os.O_RDONLY | os.O_CLOEXEC) + self.libc = C.CDLL(None, use_errno=True) + self.libc.ioctl.argtypes = [C.c_int, C.c_ulong, C.c_void_p] + cdb = bytes([0x9e, 0x10]) + bytes(8) + struct.pack('>I', 32) + bytes(2) + cap = self.request(cdb, 32) + self.last, self.bs = struct.unpack_from('>QI', cap) + require(self.bs == 4096, 'unexpected sector size') + require((self.last + 1) * self.bs == int((self.disk_node / 'size').read_text()) * 512, 'capacity mismatch') + + def request(self, cdb, count): + require(cdb[0] in (0x88, 0x9e), 'read-only commands only') + data = C.create_string_buffer(count) + cmd = C.create_string_buffer(cdb) + sense = C.create_string_buffer(96) + h = Header(interface_id=ord('S'), dxfer_direction=-3, cmd_len=len(cdb), + mx_sb_len=96, dxfer_len=count, dxferp=C.addressof(data), + cmdp=C.addressof(cmd), sbp=C.addressof(sense), timeout=15000) + result = self.libc.ioctl(self.fd, 0x2285, C.byref(h)) + require(result == 0, 'SG_IO failed, errno=' + str(C.get_errno())) + require(not (h.status or h.host_status or h.driver_status or h.resid), + 'SCSI read failed: status=' + str((h.status, h.host_status, h.driver_status, h.resid))) + return data.raw + + def read(self, lba, count=1): + require(0 <= lba <= self.last and 1 <= count <= 256 and lba + count <= self.last + 1, 'read outside capacity') + cdb = bytes([0x88, 0]) + struct.pack('>QI', lba, count) + bytes(2) + return self.request(cdb, self.bs * count) + + +def parse_header(raw, expected, last, bs): + require(raw[:8] == b'EFI PART', 'GPT signature missing') + rev, size, crc, reserved = struct.unpack_from('<4I', raw, 8) + require(rev == 0x10000 and size == 92 and reserved == 0, 'unknown GPT header') + chk = bytearray(raw[:size]); chk[16:20] = bytes(4) + require(zlib.crc32(chk) == crc, 'GPT header checksum mismatch') + current, alternate, first, end = struct.unpack_from('<4Q', raw, 24) + entries, n, es, table_crc = struct.unpack_from('= 2 and entries + blocks <= first) or + (expected == last and ((entries > end and entries + blocks <= last) or entries == 2)), + 'GPT entries overlap data') + return {'entries': entries, 'count': n, 'entry_size': es, 'crc': table_crc, + 'first': first, 'end': end, 'blocks': blocks, 'guid': raw[56:72].hex()} + + +def snapshot(reader): + p = reader.read(1); b = reader.read(reader.last) + ph = parse_header(p, 1, reader.last, reader.bs) + bh = parse_header(b, reader.last, reader.last, reader.bs) + require(all(ph[k] == bh[k] for k in ('count', 'entry_size', 'first', 'end', 'guid')), 'GPT copies disagree') + bh['physical_entries'] = reader.last - bh['blocks'] if bh['entries'] == ph['entries'] else bh['entries'] + require(bh['physical_entries'] > bh['end'], 'physical backup array overlaps data') + ph['physical_entries'] = ph['entries'] + pt = reader.read(ph['physical_entries'], ph['blocks']); bt = reader.read(bh['physical_entries'], bh['blocks']) + used = ph['count'] * ph['entry_size'] + require(zlib.crc32(pt[:used]) == ph['crc'] and zlib.crc32(bt[:used]) == bh['crc'], 'GPT array checksum mismatch') + require(pt[:used] == bt[:used], 'GPT arrays disagree') + parts = [] + for i in range(ph['count']): + entry = pt[i * 128:(i + 1) * 128] + if entry[:16] == bytes(16): + continue + name = entry[56:128].decode('utf-16le').split('\0', 1)[0] + start, end, attributes = struct.unpack_from('<3Q', entry, 32) + parts.append({'index': i, 'name': name, 'start': start, 'end': end, 'attributes': attributes}) + boot = [p for p in parts if p['name'] == 'boot_b'] + require(len(boot) == 1 and boot[0]['index'] == 6, 'boot_b index mismatch') + require(boot[0]['start'] * reader.bs == int((reader.boot_node / 'start').read_text()) * 512, 'boot_b start mismatch') + require((boot[0]['end'] - boot[0]['start'] + 1) * reader.bs == int((reader.boot_node / 'size').read_text()) * 512, 'boot_b size mismatch') + blocks = {0: reader.read(0), 1: p, reader.last: b} + require(ph['first'] <= 256 and reader.last - bh['end'] <= 256, 'excessive GPT reservation') + for lba in list(range(ph['first'])) + list(range(bh['end'] + 1, reader.last + 1)): + blocks[lba] = reader.read(lba) + for header, table in ((ph, pt), (bh, bt)): + for i in range(header['blocks']): + blocks[header['physical_entries'] + i] = table[i * reader.bs:(i + 1) * reader.bs] + return {'sector_size': reader.bs, 'last_lba': reader.last, 'primary': ph, + 'backup': bh, 'partitions': parts, 'blocks': {str(k): base64.b64encode(v).decode() for k, v in blocks.items()}} + + +if __name__ == '__main__': + result = snapshot(Reader()) + json.dump(result, sys.stdout, indent=2) + print() diff --git a/device/flame/native/validation/load-idle.sh b/device/flame/native/validation/load-idle.sh new file mode 100755 index 000000000..f23df761d --- /dev/null +++ b/device/flame/native/validation/load-idle.sh @@ -0,0 +1,89 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +set -euo pipefail +python3 - <<'PY' +from pathlib import Path +import hashlib,json,multiprocessing as mp,subprocess,time + +assert Path('/usr/share/omamobile/flame-root').is_file(),'Not a native flame root' +assert Path('/proc/device-tree/model').read_bytes().rstrip(b'\0')==b'Google Pixel 4','Wrong model' +subprocess.run(['sha256sum','-c','/etc/omamobile/flame-calibration.sha256'],check=True,stdout=subprocess.DEVNULL) +held=False +for fd in Path('/proc/1/fd').iterdir(): + try:held=held or fd.resolve().as_posix()=='/dev/watchdog0' + except FileNotFoundError:pass +assert held,'PID 1 must hold the watchdog' +boot_path=Path('/proc/sys/kernel/random/boot_id') +boot=boot_path.read_text().strip() +started=time.monotonic() +zones=[] +for p in sorted(Path('/sys/class/thermal').glob('thermal_zone*')): + try: + label=(p/'type').read_text().strip() + temperature=int((p/'temp').read_text()) + except (OSError,ValueError): + continue + if -20000 <= temperature <= 150000: + zones.append((p,label)) +assert zones,'No thermal readings available' +maxima={} +context=mp.get_context('fork') +stop=context.Event() + +def worker(queue): + try: + block=bytes(range(256))*(256*1024) # 64 MiB per worker, 128 MiB total. + expected=hashlib.sha256(block).digest() + count=0 + while not stop.is_set(): + before=time.monotonic() + assert hashlib.sha256(block).digest()==expected,'Memory checksum changed' + count+=1 + stop.wait(max(.02,time.monotonic()-before)) # About 50% duty per worker. + queue.put(('pass',count)) + except BaseException as error: + queue.put(('error',repr(error))) + +def check(phase): + assert boot_path.read_text().strip()==boot,'Unexpected restart' + assert not Path('/dev/sda').exists(),'Whole-disk node appeared' + values={} + for p,label in zones: + value=int((p/'temp').read_text()) + key=p.name+':'+label + maxima[key]=max(value,maxima.get(key,value)) + values[key]=value + ceiling=45000 if 'batt' in label.lower() else 70000 + assert value < ceiling, f'Thermal stop: {label}={value}' + subprocess.run(['systemctl','is-active','--quiet','flame-storage-guard','flame-wifi','sddm'],check=True,timeout=10) + print(json.dumps({'phase':phase,'elapsed_s':round(time.monotonic()-started),'boot':boot,'temperatures_mC':values}),flush=True) + +queue=context.Queue() +workers=[context.Process(target=worker,args=(queue,)) for _ in range(2)] +check('preflight') +print('BOUNDED_LOAD: two CPU workers at about 50% duty, 128 MiB total, 120 seconds; then 180 seconds idle',flush=True) +try: + for process in workers:process.start() + deadline=time.monotonic()+120 + while time.monotonic()0 for result in results),results +print('WORKERS_VERIFIED',results,flush=True) +deadline=time.monotonic()+180 +while time.monotonic()=0.2.24' 'omamobile-firstboot>=0.1.3' foot xdg-terminal-exec udiskie) +check() { "$startdir/test/all"; } +package() { "$startdir/install" "$pkgdir"; } diff --git a/packages/omamobile-device-flame/README.md b/packages/omamobile-device-flame/README.md new file mode 100644 index 000000000..8ec36e661 --- /dev/null +++ b/packages/omamobile-device-flame/README.md @@ -0,0 +1,27 @@ + +# omamobile-device-flame + +Experimental Pixel 4 native-root policy. Install only into the opt-in flame +root described in [the native runbook](../../device/flame/native/README.md). +The package enables the storage guard, hides protected partitions from desktop +disk tools, keeps the journal off USB, and selects the tested software-rendering +fallback for SDDM and user services. PID 1 feeds the 30-second watchdog; USB +networkd/DHCP stays separate from NetworkManager, and first-boot 0.1.3 adds +USB-only recovery/DHCP firewall rules. It does not mark a boot slot successful. + +Foot, xdg-terminal-exec and udiskie are explicit dependencies so hand-built +roots cannot omit the terminal or disk helpers used by upstream Omarchy. +The existing AI Agent shortcut and chooser remain upstream's; no separate +Codex desktop app or agent selection is installed by this package. + +`omamobile-flame-configure-user` seeds the tested 2.5 display scale. Its optional +`--chrome` switch merges the tested Wayland/software-rendering/0.6 scale flags +for an already installed Chrome browser. Other flags are preserved and prior +files are backed up under the owner's private state directory. It never +accepts a browser license or starts the browser. Chrome is not a dependency. +Normal mobile user setup calls `--chrome-if-installed` once for flame roots. + +Wi-Fi's unit is shipped **disabled**. Before enabling it, supply the owner's +matching firmware and current verified private manifests/NV shadows and pass +the native Wi-Fi gates. No firmware, calibration, host keys or credentials +are in this package. Keep `ftm5_fw.ftb` absent before the first touch test. diff --git a/packages/omamobile-device-flame/bin/omamobile-flame-configure-user b/packages/omamobile-device-flame/bin/omamobile-flame-configure-user new file mode 100755 index 000000000..d20d36aa1 --- /dev/null +++ b/packages/omamobile-device-flame/bin/omamobile-flame-configure-user @@ -0,0 +1,70 @@ +#!/usr/bin/python3 +# SPDX-License-Identifier: MIT +"""Seed the measured flame scale; optionally fix an owner-installed Chrome.""" +import argparse +from pathlib import Path +import os +import re +import shutil +import tempfile + + +def replace(home, path, content): + if path.exists() and path.read_text() == content: + return + backup = home / '.local/state/omamobile/flame-config-backups' + if path.exists(): + backup.mkdir(parents=True, exist_ok=True, mode=0o700) + saved = backup / path.name + if not saved.exists(): + shutil.copy2(path, saved) + saved.chmod(0o600) + path.parent.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent) + try: + with os.fdopen(fd, 'w') as stream: + stream.write(content) + os.replace(name, path) + finally: + Path(name).unlink(missing_ok=True) + + +def configure(home, chrome=False): + monitors = home / '.config/hypr/monitors.lua' + if not monitors.exists(): + raise RuntimeError('Run normal Omarchy Mobile user setup first') + original = monitors.read_text() + content, count = re.subn(r'^local omarchy_monitor_scale = .*$', + 'local omarchy_monitor_scale = 2.5', original, + flags=re.MULTILINE) + if count != 1: + raise RuntimeError('Expected one Omarchy monitor-scale declaration') + replace(home, monitors, content) + if chrome: + flags = home / '.config/chrome-flags.conf' + lines = flags.read_text().splitlines() if flags.exists() else [] + keys = ('--disable-gpu', '--ozone-platform', '--force-device-scale-factor') + kept = [line for line in lines if not any( + line.strip() == key or line.strip().startswith(key + '=') for key in keys)] + kept += ['--disable-gpu', '--ozone-platform=wayland', + '--force-device-scale-factor=0.6'] + replace(home, flags, '\n'.join(kept) + '\n') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--chrome', action='store_true', help='merge the tested Chrome flags') + parser.add_argument('--chrome-if-installed', action='store_true') + args = parser.parse_args() + if os.getuid() == 0: + parser.error('run as the desktop owner, not root') + if not Path('/usr/share/omamobile/flame-root').is_file(): + parser.error('not a flame native root') + chrome = args.chrome or (args.chrome_if_installed and bool( + shutil.which('google-chrome-stable') or shutil.which('google-chrome'))) + configure(Path.home(), chrome) + print('Flame display defaults configured' + ('; Chrome flags merged' if chrome else '')) + + +if __name__ == '__main__': + main() diff --git a/packages/omamobile-device-flame/install b/packages/omamobile-device-flame/install new file mode 100755 index 000000000..2e4ccff3e --- /dev/null +++ b/packages/omamobile-device-flame/install @@ -0,0 +1,16 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")" +destination=${1:?Usage: install ABSOLUTE_STAGING_DIRECTORY} +[[ $destination == /* && $destination != / ]] || exit 1 +for file in bin/*; do install -Dm755 "$file" "$destination/usr/bin/${file##*/}"; done +for file in vendor/bin/*; do install -Dm755 "$file" "$destination/usr/bin/${file##*/}"; done +while IFS= read -r -d '' file; do + install -Dm644 "$file" "$destination/usr/lib/${file#vendor/lib/}" +done < <(find vendor/lib -type f -print0) +install -d "$destination/usr/lib/systemd/system/sysinit.target.wants" +ln -sfn ../flame-storage-guard.service "$destination/usr/lib/systemd/system/sysinit.target.wants/flame-storage-guard.service" +install -Dm644 version "$destination/usr/share/omamobile/device-flame/version" +install -Dm644 LICENSE "$destination/usr/share/licenses/omamobile-device-flame/LICENSE" +install -Dm644 /dev/null "$destination/usr/share/omamobile/flame-root" diff --git a/packages/omamobile-device-flame/test/all b/packages/omamobile-device-flame/test/all new file mode 100755 index 000000000..d5541ebb7 --- /dev/null +++ b/packages/omamobile-device-flame/test/all @@ -0,0 +1,54 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +set -euo pipefail +export PYTHONDONTWRITEBYTECODE=1 +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +bash -n install +python3 -B test/storage-guard.py +sh -n vendor/bin/flame-storage-guard +bash -n vendor/bin/flame-wifi-start vendor/bin/flame-partition-links +./install "$scratch/root" +test -f "$scratch/root/usr/share/omamobile/flame-root" +test -L "$scratch/root/usr/lib/systemd/system/sysinit.target.wants/flame-storage-guard.service" +test ! -e "$scratch/root/usr/lib/systemd/system/multi-user.target.wants/flame-wifi.service" +test -f "$scratch/root/usr/lib/systemd/journald.conf.d/90-flame-standalone.conf" +grep -q '^ForwardToConsole=no$' "$scratch/root/usr/lib/systemd/journald.conf.d/90-flame-standalone.conf" +grep -qx 'RuntimeWatchdogSec=30s' "$scratch/root/usr/lib/systemd/system.conf.d/10-flame-watchdog.conf" +grep -qx 'RebootWatchdogSec=1min' "$scratch/root/usr/lib/systemd/system.conf.d/10-flame-watchdog.conf" +grep -qx 'Name=usb0' "$scratch/root/usr/lib/systemd/network/10-flame-usb.network" +grep -qx 'EmitRouter=no' "$scratch/root/usr/lib/systemd/network/10-flame-usb.network" +if grep -q '^Gateway=' "$scratch/root/usr/lib/systemd/network/10-flame-usb.network"; then + echo 'not ok - USB must not become the default gateway' >&2 + exit 1 +fi +python3 - <<'PY' +from pathlib import Path +import importlib.machinery,importlib.util,tempfile +path=Path('bin/omamobile-flame-configure-user') +loader=importlib.machinery.SourceFileLoader('flame_user',str(path)) +spec=importlib.util.spec_from_loader(loader.name,loader) +module=importlib.util.module_from_spec(spec);loader.exec_module(module) +with tempfile.TemporaryDirectory() as folder: + home=Path(folder);monitor=home/'.config/hypr/monitors.lua' + monitor.parent.mkdir(parents=True);monitor.write_text('local omarchy_monitor_scale = 3\n-- owner setting\n') + chrome=home/'.config/chrome-flags.conf' + chrome.write_text('--force-device-scale-factor=0.83\n--ozone-platform=x11\n--lang=fr\n# owner comment\n') + module.configure(home,chrome=True) + assert monitor.read_text()=='local omarchy_monitor_scale = 2.5\n-- owner setting\n' + assert chrome.read_text()=='--lang=fr\n# owner comment\n--disable-gpu\n--ozone-platform=wayland\n--force-device-scale-factor=0.6\n' + backup=home/'.local/state/omamobile/flame-config-backups/chrome-flags.conf' + assert '--force-device-scale-factor=0.83' in backup.read_text() + before=chrome.read_bytes();saved=backup.read_bytes() + module.configure(home,chrome=True) + assert chrome.read_bytes()==before and backup.read_bytes()==saved + assert chrome.stat().st_mode & 0o777==0o600 + # A manually maintained monitor layout must not be overwritten by guesswork. + monitor.write_text('-- custom layout\n') + try:module.configure(home,chrome=True) + except RuntimeError:pass + else:raise AssertionError('unknown monitor configuration accepted') + assert monitor.read_text()=='-- custom layout\n' +print('ok - flame package stages guard-only activation; user settings merge, backup and repeat safely') +PY diff --git a/packages/omamobile-device-flame/test/storage-guard.py b/packages/omamobile-device-flame/test/storage-guard.py new file mode 100644 index 000000000..1a49b4e2a --- /dev/null +++ b/packages/omamobile-device-flame/test/storage-guard.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +from pathlib import Path +import tempfile,subprocess,os +source=(Path(__file__).resolve().parents[1]/'vendor/bin/flame-storage-guard').read_text() +body='UFS_RW="boot_b userdata"'+source.split('UFS_RW="boot_b userdata"',1)[1].split('\nwhile :; do',1)[0] +with tempfile.TemporaryDirectory() as d: + p=Path(d); sys=p/'sys';dev=p/'dev';bin=p/'bin' + for x in (sys,dev,bin):x.mkdir() + body=body.replace('/sys/class/block/',str(sys)+'/').replace('/dev/',str(dev)+'/').replace('[ -b ','[ -f ') + (p/'guard').write_text('say() { echo "$*" >&2; }\n'+body+'\nstorage_guard\n') + (bin/'blockdev').write_text('#!/bin/sh\n[ "$1" = --setro ] || exit 92\n[ "${MODE:-}" != fail ] || exit 1\n[ "${MODE:-}" != lie ] || exit 0\necho 1 > "$SYS/${2##*/}/ro"\n') + (bin/'blockdev').chmod(0o755) + def add(n,part='',ro='0'): + (sys/n).mkdir();(sys/n/'ro').write_text(ro+'\n');(sys/n/'uevent').write_text('PARTNAME='+part+'\n' if part else '');(dev/n).touch() + def run(mode=''): + return subprocess.run(['sh',str(p/'guard')],env=dict(os.environ,PATH=str(bin)+':'+os.environ['PATH'],SYS=str(sys),MODE=mode),capture_output=True) + for n,part in [('sda',''),('sda2','persist'),('sda6','boot_a'),('sda7','boot_b'),('sda15','userdata'),('sdb',''),('sde33','devinfo'),('sdf2','modemst1'),('sdf3','userdata')]:add(n,part) + assert run().returncode==0 + assert not (dev/'sda').exists() + for n in ['sda2','sda6','sdb','sde33','sdf2','sdf3']:assert (sys/n/'ro').read_text().strip()=='1',n + for n in ['sda7','sda15']:assert (sys/n/'ro').read_text().strip()=='0',n + (sys/'sda7'/'ro').write_text('1\n');(dev/'sda').touch();assert run().returncode==0;assert not (dev/'sda').exists();assert (sys/'sda7'/'ro').read_text().strip()=='1' + add('sdg');assert run('fail').returncode!=0;assert run('lie').returncode!=0 + print('Root guard: exact sda allowlist, all calibration protected, other-LUN userdata rejected, whole node removed, existing RO preserved, failure closed') diff --git a/packages/omamobile-device-flame/vendor/bin/flame-partition-links b/packages/omamobile-device-flame/vendor/bin/flame-partition-links new file mode 100755 index 000000000..d883cc972 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/bin/flame-partition-links @@ -0,0 +1,20 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# UFS LUN discovery order can change across boots. Never persist /dev/sdX paths. +set -euo pipefail +test -f /usr/share/omamobile/flame-root +test ! -e /dev/sda +directory=/run/omamobile/flame-partitions +install -d -m 700 "$directory" +for part in persist modemst1 modemst2 fsg fsc modem_a modem_b devinfo; do + target='' + for candidate in /sys/class/block/sd*/uevent; do + if grep -Fx "PARTNAME=$part" "$candidate" >/dev/null; then + [[ -z $target ]] || { echo 'Ambiguous protected partition' >&2; exit 1; } + target=/dev/$(basename "$(dirname "$candidate")") + fi + done + [[ -n $target && -b $target ]] || { echo 'Protected partition absent' >&2; exit 1; } + [[ $(blockdev --getro "$target") == 1 ]] || { echo 'Protected partition is writable' >&2; exit 1; } + ln -sfn "$target" "$directory/$part" +done diff --git a/packages/omamobile-device-flame/vendor/bin/flame-storage-guard b/packages/omamobile-device-flame/vendor/bin/flame-storage-guard new file mode 100755 index 000000000..effd2549d --- /dev/null +++ b/packages/omamobile-device-flame/vendor/bin/flame-storage-guard @@ -0,0 +1,38 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT +# Development storage guard; never clear an existing read-only flag. +export PATH=/usr/bin:/bin +say() { echo "omamobile-flame-guard: $*" >/dev/kmsg; } +UFS_RW="boot_b userdata" +part_name() { sed -n 's/^PARTNAME=//p' "$1/uevent"; } +storage_guard() { + for s in /sys/class/block/sd*; do + [ -r "$s/ro" ] || continue + name=${s##*/} + if [ "$name" = sda ]; then + rm -f /dev/sda + continue + fi + [ -b "/dev/$name" ] || continue + part=$(part_name "$s") + case "$name" in + sda[0-9]*) + # A previously read-only device stays so; never use --setrw. + case " $UFS_RW " in *" $part "*) continue ;; esac ;; + esac + [ "$(cat "$s/ro")" = 1 ] && continue + if ! blockdev --setro "/dev/$name" || [ "$(cat "$s/ro")" != 1 ]; then + say "FAILED to protect /dev/$name" + return 1 + fi + done + [ ! -e /dev/sda ] +} +while :; do + if ! storage_guard; then + say 'Storage protection failed; forcing recovery' + echo c >/proc/sysrq-trigger + exit 1 + fi + sleep 0.2 +done diff --git a/packages/omamobile-device-flame/vendor/bin/flame-wifi-start b/packages/omamobile-device-flame/vendor/bin/flame-wifi-start new file mode 100755 index 000000000..1dff1d6cc --- /dev/null +++ b/packages/omamobile-device-flame/vendor/bin/flame-wifi-start @@ -0,0 +1,103 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Experimental flame radio startup. Owner firmware and NV stay off-repository. +set -euo pipefail + +fail() { echo "flame Wi-Fi: $*" >&2; exit 1; } +test -f /usr/share/omamobile/flame-root || fail 'wrong root' +[[ $(tr -d '\0' /dev/null || fail 'wrong device' +systemctl is-active --quiet flame-storage-guard.service +test ! -e /dev/sda || fail 'whole-disk node exists' +blockdev --setro /dev/sda7 +for node in /sys/class/block/sd*; do + case ${node##*/} in sda|sda15) continue;; esac + [[ $(cat "$node/ro") == 1 ]] || fail 'protected storage is writable' +done + +/usr/bin/flame-partition-links +sha256sum --check --status /etc/omamobile/flame-calibration.sha256 +sha256sum --check --status /etc/omamobile/flame-firmware.sha256 +# Firmware API 2 wins over the factory API 1 board file, including compressed +# copies and files restored by a linux-firmware upgrade. Fail before MPSS starts. +[[ -z $(cat /sys/module/firmware_class/parameters/path) ]] || fail 'custom firmware search path' +for root in /usr/lib/firmware/updates/"$(uname -r)" /usr/lib/firmware/updates \ + /usr/lib/firmware/"$(uname -r)" /usr/lib/firmware; do + for file in "$root"/ath10k/WCN3990/hw1.0/board-2.bin{,.xz,.zst}; do + [[ ! -e $file ]] || fail 'generic API 2 board data overrides factory board.bin' + done +done + +# Verify each shadow against the currently protected partition, not merely an +# older shadow manifest. rmtfs receives RAM files and never the real NV nodes. +for pair in modemst1:modem_fs1 modemst2:modem_fs2 fsg:modem_fsg fsc:modem_fsc; do + part=${pair%%:*}; file=${pair#*:}; source_node='' + for candidate in /sys/class/block/sd*/uevent; do + if grep -Fx "PARTNAME=$part" "$candidate" >/dev/null; then + [[ -z $source_node ]] || fail 'ambiguous NV partition' + source_node=/dev/$(basename "$(dirname "$candidate")") + fi + done + [[ -n $source_node ]] || fail 'NV partition is absent' + [[ $(sha256sum "$source_node" | cut -d' ' -f1) == \ + $(sha256sum "/var/lib/omamobile/flame/nv/$file" | cut -d' ' -f1) ]] || fail 'stale NV shadow' +done + +wifi_ready() { + # systemd may rename wlan0 (wld0 on the tested native root). + for iface in /sys/class/net/*; do + [[ ! -d $iface/wireless ]] || return 0 + done + return 1 +} +wifi_ready && exit 0 +state=/var/lib/omamobile/flame/wifi-starting +[[ ! -e $state ]] || fail 'previous startup did not complete; inspect logs before clearing marker' +install -d -m 700 /var/lib/omamobile/flame +touch "$state" +sync -f "$state" + +for program in rmtfs tqftpserv; do test -x "/usr/local/sbin/$program"; done +install -d -m 700 /run/rmtfs +for file in modem_fs1 modem_fs2 modem_fsg modem_fsc; do + install -m 600 "/var/lib/omamobile/flame/nv/$file" "/run/rmtfs/$file" +done +modprobe qrtr_smd +modprobe qcom_q6v5_pas +test -c /dev/qcom_rmtfs_mem1 +rm -f /dev/mem +# Refuse existing filesystem servers: their options and backing data are unknown. +! pgrep -x rmtfs >/dev/null || fail 'rmtfs already running' +! pgrep -x tqftpserv >/dev/null || fail 'tqftpserv already running' +install -d -m 700 /var/log/omamobile +/usr/local/sbin/tqftpserv >>/var/log/omamobile/flame-tqftp.log 2>&1 & +/usr/local/sbin/rmtfs -r -v -o /run/rmtfs >>/var/log/omamobile/flame-rmtfs.log 2>&1 & +sleep 1 +pgrep -x tqftpserv >/dev/null +pgrep -x rmtfs >/dev/null +mpss='' +for candidate in /sys/class/remoteproc/remoteproc*; do + [[ -f $candidate/name ]] || continue + [[ $(cat "$candidate/name") == modem ]] || continue + [[ -z $mpss ]] || fail 'ambiguous modem processor' + mpss=$candidate +done +[[ -n $mpss ]] || fail 'MPSS is absent' +# Repeated resets after a WLAN firmware fault previously stalled UFS. +echo disabled >"$mpss/recovery" +[[ $(cat "$mpss/state") == offline ]] || fail 'MPSS is already started' +echo start >"$mpss/state" +[[ $(cat "$mpss/state") == running ]] +modprobe ath10k_snoc +modprobe qcom_pd_mapper +for _ in {1..45}; do + if wifi_ready; then + rm "$state" + sync -f /var/lib/omamobile/flame + echo 'WLAN ready; modem filesystem uses verified read-only RAM shadows' + exit 0 + fi + sleep 1 +done +fail 'no WLAN interface after firmware startup' diff --git a/packages/omamobile-device-flame/vendor/lib/NetworkManager/conf.d/10-flame-usb.conf b/packages/omamobile-device-flame/vendor/lib/NetworkManager/conf.d/10-flame-usb.conf new file mode 100644 index 000000000..dfdd6d916 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/NetworkManager/conf.d/10-flame-usb.conf @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: MIT +# systemd-networkd owns the USB gadget; NetworkManager owns Wi-Fi. +[keyfile] +unmanaged-devices=interface-name:usb0 diff --git a/packages/omamobile-device-flame/vendor/lib/environment.d/90-flame-software-rendering.conf b/packages/omamobile-device-flame/vendor/lib/environment.d/90-flame-software-rendering.conf new file mode 100644 index 000000000..0e69be034 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/environment.d/90-flame-software-rendering.conf @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: MIT +# Hardware acceleration faulted on the tested A640 setup. Keep the tested fallback. +LIBGL_ALWAYS_SOFTWARE=1 +GALLIUM_DRIVER=llvmpipe +__EGL_VENDOR_LIBRARY_FILENAMES=/usr/share/glvnd/egl_vendor.d/50_mesa.json diff --git a/packages/omamobile-device-flame/vendor/lib/modprobe.d/omamobile-flame.conf b/packages/omamobile-device-flame/vendor/lib/modprobe.d/omamobile-flame.conf new file mode 100644 index 000000000..e292865d0 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/modprobe.d/omamobile-flame.conf @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: MIT +# Wi-Fi is loaded only by the separately gated firmware/NV-shadow helper. +blacklist ath10k_snoc +# No Bluetooth firmware download/pairing pass. No UART pin experiment is shipped. +blacklist hci_uart +# The uninitialized RTC reset the clock during initial provisioning. +blacklist rtc_pm8xxx diff --git a/packages/omamobile-device-flame/vendor/lib/systemd/journald.conf.d/90-flame-standalone.conf b/packages/omamobile-device-flame/vendor/lib/systemd/journald.conf.d/90-flame-standalone.conf new file mode 100644 index 000000000..29b42513b --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/systemd/journald.conf.d/90-flame-standalone.conf @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: MIT +# Forwarding journal messages to ttyGS0 can feed USB wakeup errors back into +# the same suspended connection after unplugging. Keep logs in the journal. +[Journal] +ForwardToConsole=no diff --git a/packages/omamobile-device-flame/vendor/lib/systemd/network/10-flame-usb.network b/packages/omamobile-device-flame/vendor/lib/systemd/network/10-flame-usb.network new file mode 100644 index 000000000..8f782dfb4 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/systemd/network/10-flame-usb.network @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: MIT +[Match] +Name=usb0 + +[Network] +Address=172.16.42.1/24 +DHCPServer=yes +LinkLocalAddressing=ipv6 +ConfigureWithoutCarrier=yes + +[DHCPServer] +PoolOffset=2 +PoolSize=1 +EmitRouter=no +EmitDNS=no diff --git a/packages/omamobile-device-flame/vendor/lib/systemd/system.conf.d/10-flame-watchdog.conf b/packages/omamobile-device-flame/vendor/lib/systemd/system.conf.d/10-flame-watchdog.conf new file mode 100644 index 000000000..8ffdecac9 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/systemd/system.conf.d/10-flame-watchdog.conf @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: MIT +# The initramfs takes over the Qualcomm watchdog before the Arch handoff. +[Manager] +RuntimeWatchdogSec=30s +RebootWatchdogSec=1min diff --git a/packages/omamobile-device-flame/vendor/lib/systemd/system/flame-storage-guard.service b/packages/omamobile-device-flame/vendor/lib/systemd/system/flame-storage-guard.service new file mode 100644 index 000000000..b4a52a3ab --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/systemd/system/flame-storage-guard.service @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: MIT +[Unit] +Description=Pixel 4 protected storage guard +DefaultDependencies=no +Before=systemd-udevd.service sysinit.target shutdown.target +Conflicts=shutdown.target + +[Service] +Type=exec +ExecStart=/usr/bin/flame-storage-guard +Restart=always +RestartSec=0 + +[Install] +WantedBy=sysinit.target diff --git a/packages/omamobile-device-flame/vendor/lib/systemd/system/flame-wifi.service b/packages/omamobile-device-flame/vendor/lib/systemd/system/flame-wifi.service new file mode 100644 index 000000000..b1a79b479 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/systemd/system/flame-wifi.service @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: MIT +[Unit] +Description=Experimental Pixel 4 Wi-Fi with protected NV shadows +Requires=flame-storage-guard.service +After=flame-storage-guard.service systemd-udev-settle.service +Before=NetworkManager.service +ConditionPathExists=/etc/omamobile/flame-firmware.sha256 + +[Service] +Type=oneshot +ExecStart=/usr/bin/flame-wifi-start +RemainAfterExit=yes +TimeoutStartSec=75 +# Keep the filesystem servers for the lifetime of this boot. Do not restart a +# failed processor or stop/unload drivers during bring-up. +KillMode=process + +[Install] +WantedBy=multi-user.target diff --git a/packages/omamobile-device-flame/vendor/lib/systemd/system/sddm.service.d/flame-software-rendering.conf b/packages/omamobile-device-flame/vendor/lib/systemd/system/sddm.service.d/flame-software-rendering.conf new file mode 100644 index 000000000..aba362ba3 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/systemd/system/sddm.service.d/flame-software-rendering.conf @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: MIT +[Service] +Environment=LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe +Environment=__EGL_VENDOR_LIBRARY_FILENAMES=/usr/share/glvnd/egl_vendor.d/50_mesa.json diff --git a/packages/omamobile-device-flame/vendor/lib/udev/rules.d/10-flame-storage.rules b/packages/omamobile-device-flame/vendor/lib/udev/rules.d/10-flame-storage.rules new file mode 100644 index 000000000..637f88f90 --- /dev/null +++ b/packages/omamobile-device-flame/vendor/lib/udev/rules.d/10-flame-storage.rules @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +SUBSYSTEM=="block", KERNEL=="sda", MODE="0000", ENV{UDISKS_IGNORE}="1", RUN+="/usr/bin/rm -f /dev/%k" +SUBSYSTEM=="block", KERNEL=="sd*[0-9]*", ENV{ID_PART_ENTRY_NAME}!="userdata", ENV{UDISKS_IGNORE}="1" diff --git a/packages/omamobile-device-flame/version b/packages/omamobile-device-flame/version new file mode 100644 index 000000000..6e8bf73aa --- /dev/null +++ b/packages/omamobile-device-flame/version @@ -0,0 +1 @@ +0.1.0 diff --git a/packages/omamobile-firstboot/bin/omamobile-firstboot b/packages/omamobile-firstboot/bin/omamobile-firstboot index f951476b1..8a3d7404c 100755 --- a/packages/omamobile-firstboot/bin/omamobile-firstboot +++ b/packages/omamobile-firstboot/bin/omamobile-firstboot @@ -336,6 +336,12 @@ s_services() { ufw allow 53317/udp ufw allow 53317/tcp ufw allow in on usb0 to any port 22 proto tcp + if [[ -f $ROOT/usr/share/omamobile/flame-root ]]; then + # Native flame keeps an independent RAM rescue listener and a USB DHCP + # server. These rules apply only to the physical gadget, never Wi-Fi. + ufw allow in on usb0 to any port 2222 proto tcp + ufw allow in on usb0 to any port 67 proto udp + fi # Active from the next boot, as Omarchy's installer leaves it sed -i 's/^ENABLED=.*/ENABLED=yes/' "$ROOT/etc/ufw/ufw.conf" } diff --git a/packages/omamobile-firstboot/test/all b/packages/omamobile-firstboot/test/all index 429925390..d52fbe5e0 100755 --- a/packages/omamobile-firstboot/test/all +++ b/packages/omamobile-firstboot/test/all @@ -186,6 +186,18 @@ grep -q '^usermod -aG wheel,audio,video,input' "$CALLS" || fail "a second run up [[ $(grep -cxF "$KEY" "$R/home/alice/.ssh/authorized_keys") == 1 ]] || fail "a second run doesn't duplicate the key" pass "running again is safe" +# Only the explicit native-root marker opens RAM rescue and DHCP, on USB. +if grep -Eq '^ufw allow .*port (2222|67) ' "$CALLS"; then fail "normal roots get no flame recovery/DHCP rules"; fi +mkdir -p "$R/usr/share/omamobile" +touch "$R/usr/share/omamobile/flame-root" +: > "$CALLS" +good > "$R/etc/omamobile/firstboot.conf" +run || { cat "$t/run.out"; fail "flame services run"; } +grep -qx 'ufw allow in on usb0 to any port 2222 proto tcp' "$CALLS" || fail "flame recovery is USB-only" +grep -qx 'ufw allow in on usb0 to any port 67 proto udp' "$CALLS" || fail "flame DHCP is USB-only" +rm "$R/usr/share/omamobile/flame-root" +pass "native flame recovery and DHCP rules are marker-gated and USB-only" + # An essential step failing keeps the conf (minus the Wi-Fi secret) for the next boot rm -f "$R/var/lib/omamobile/firstboot/user" sed -i '/^alice:/d' "$R/etc/passwd" diff --git a/packages/omamobile-firstboot/version b/packages/omamobile-firstboot/version index d917d3e26..b1e80bb24 100644 --- a/packages/omamobile-firstboot/version +++ b/packages/omamobile-firstboot/version @@ -1 +1 @@ -0.1.2 +0.1.3 diff --git a/packages/omamobile-shell/bin/omamobile-setup-user b/packages/omamobile-shell/bin/omamobile-setup-user index 2e671b278..1ce0f6bca 100755 --- a/packages/omamobile-shell/bin/omamobile-setup-user +++ b/packages/omamobile-shell/bin/omamobile-setup-user @@ -100,9 +100,15 @@ if omarchy-done ensure omamobile-credential-type; then fi fi -# Phone scale: 1440x3120 at 3 is 480x1040 logical, seeded once +# Phone scale, seeded once: 3 normally; flame uses the measured 2.5 scale. if omarchy-done ensure omamobile-monitor-scale; then - sed -i 's/^local omarchy_monitor_scale = .*/local omarchy_monitor_scale = 3/' ~/.config/hypr/monitors.lua + scale=3 + [[ ! -f /usr/share/omamobile/flame-root ]] || scale=2.5 + sed -i "s/^local omarchy_monitor_scale = .*/local omarchy_monitor_scale = $scale/" ~/.config/hypr/monitors.lua +fi + +if [[ -f /usr/share/omamobile/flame-root ]] && omarchy-done ensure omamobile-flame-user-defaults; then + omamobile-flame-configure-user --chrome-if-installed fi # Touch phone: no pointer on screen (it still hides on touch if a USB mouse is diff --git a/packages/omamobile-shell/version b/packages/omamobile-shell/version index 521eb3d6e..ac1661553 100644 --- a/packages/omamobile-shell/version +++ b/packages/omamobile-shell/version @@ -1 +1 @@ -0.2.23 +0.2.24 diff --git a/rootfs/build-inside b/rootfs/build-inside index c0d4ad1c2..2a38b9afe 100755 --- a/rootfs/build-inside +++ b/rootfs/build-inside @@ -167,6 +167,11 @@ size=$(( (used * 12 / 10 + 768 + 63) / 64 * 64 )) rm -f /out/rootfs.img truncate -s "${size}M" /out/rootfs.img # -m 1: 1% reserved for root, not 5% of a ~100 GB userdata -mkfs.ext4 -q -L omamobile-root -m 1 -d "$T" /out/rootfs.img +features=() +if [[ $DEVICE == flame && ${FLAME_NATIVE:-0} == 1 ]]; then + # The tested storage loader does not support these newer ext4 features. + features=(-O "^orphan_file,^metadata_csum_seed") +fi +mkfs.ext4 -q -L omamobile-root -m 1 "${features[@]}" -d "$T" /out/rootfs.img e2fsck -fn /out/rootfs.img >/dev/null echo " ${used} MiB of files in a ${size} MiB file system" diff --git a/tests/all b/tests/all index d06659ec9..4568c3bc1 100755 --- a/tests/all +++ b/tests/all @@ -13,16 +13,21 @@ cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." for f in tools/install-phone tools/phone-provision tools/build-rootfs tools/build-packages tools/make-bundle \ tools/lib/alarm.sh tools/lib/alarm-setup rootfs/build-inside tests/*; do [[ -f $f ]] || continue # tests/owl is the OWL conformance suite's folder + if [[ $f == *.py ]]; then + python3 -B -c 'import ast,sys; ast.parse(open(sys.argv[1]).read())' "$f" + continue + fi bash -n "$f" || { echo "not ok - $f parses" >&2; exit 1; } done sh -n initramfs/init sh -n device/flame/initramfs/init sh -n device/flame/initramfs/build -bash -n tools/build-flame-probe +bash -n tools/build-flame-probe tools/build-flame-system tools/build-flame-loader +sh -n device/flame/native/init device/flame/native/build echo "ok - scripts parse" -for t in tests/pr-check tests/kernel-pr-check tests/install-phone tests/phone-provision tests/initramfs-grow tests/images-layout tests/device-overlays tests/simplefb-trigger tests/storage-guard tests/usb-product tests/boot-method tests/flame-probe packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all; do +for t in tests/pr-check tests/kernel-pr-check tests/install-phone tests/phone-provision tests/initramfs-grow tests/images-layout tests/device-overlays tests/simplefb-trigger tests/storage-guard tests/usb-product tests/boot-method tests/flame-probe tests/flame-images tests/flame-root-guard.py tests/flame-boot-success.py tests/phone-ssh packages/omamobile-device-flame/test/all packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all; do echo "# $t" - "$t" + if [[ $t == *.py ]]; then python3 -B "$t"; else "$t"; fi done shopt -s nullglob latest="" diff --git a/tests/flame-boot-success.py b/tests/flame-boot-success.py new file mode 100644 index 000000000..15a022605 --- /dev/null +++ b/tests/flame-boot-success.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Synthetic GPT and SCSI backend; never opens a host or phone block device.""" +import base64 +import contextlib +import copy +import ctypes as C +import hashlib +import importlib.util +import io +from pathlib import Path +import struct +import sys +import tempfile +import zlib + +source = Path(__file__).resolve().parents[1] / 'device/flame/native' +def module(name, file): + spec = importlib.util.spec_from_file_location(name, source / file) + result = importlib.util.module_from_spec(spec) + sys.modules[name] = result + spec.loader.exec_module(result) + return result + +read = module('read_gpt', 'read_gpt.py') +planner = module('boot_success_plan', 'boot_success_plan.py') +writer = module('boot_success_apply', 'boot_success_apply.py') +BS, LAST = 4096, 4095 +table = bytearray(15 * 128) +entry = bytearray(128) +entry[:16] = bytes([1]) * 16 +entry[16:32] = bytes([2]) * 16 +struct.pack_into('<3Q', entry, 32, 100, 199, 0x16 << 48) +entry[56:68] = 'boot_b'.encode('utf-16le') +table[6*128:7*128] = entry +crc = zlib.crc32(table) +def header(lba, padding): + h = bytearray([padding] * BS) + h[:92] = bytes(92) + h[:8] = b'EFI PART' + struct.pack_into('<4I', h, 8, 0x10000, 92, 0, 0) + struct.pack_into('<4Q', h, 24, lba, LAST if lba == 1 else 1, 6, LAST-5) + h[56:72] = bytes([3]) * 16 + # Match coral's legacy backup pointer; physical backup array is LAST-1. + struct.pack_into('QI', cmd, 2) + assert fd == -1 and operation == 0x2285 + assert cmd[:2] == bytes([0x8a, 8]) and count == 1 + assert h.dxfer_direction == -2 and h.dxfer_len == BS + assert lba == [LAST-1, LAST, 2, 1][len(self.calls)] + self.calls.append(lba) + if len(self.calls) == self.failure: h.status = 2 + else: self.mem[lba] = C.string_at(h.dxferp, BS) + return 0 + +before = read.snapshot(Memory()) +approved = planner.plan(before) +def refuses(action): + try: action() + except RuntimeError: return + raise AssertionError('unsafe action accepted') + +assert read.verify_storage(sysfs, devdir) == (boot_node, userdata_node, disk_node) +(devdir / disk_node.name).touch() +refuses(lambda: read.verify_storage(sysfs, devdir)) +(devdir / disk_node.name).unlink() +(sysfs / 'sdb2' / 'ro').write_text('0') +refuses(lambda: read.verify_storage(sysfs, devdir)) +(sysfs / 'sdb2' / 'ro').write_text('1') +extra = node('sdb3', 'userdata', 'sdb', ro='0') +refuses(lambda: read.resolve_layout(sysfs)) +extra.unlink() +(userdata_node / 'uevent').write_text('PARTNAME=not-userdata') +refuses(lambda: read.resolve_layout(sysfs)) +extra.symlink_to(root / 'devices/sdb/sdb3') +refuses(lambda: read.resolve_layout(sysfs)) +extra.unlink() +(userdata_node / 'uevent').write_text('PARTNAME=userdata') + +with contextlib.redirect_stdout(io.StringIO()): + m = Memory() + writer.apply(m, before, approved) + after = read.snapshot(m) + assert len(m.calls) == 4 + assert next(p for p in after['partitions'] if p['name'] == 'boot_b')['attributes'] == (0x56 << 48) + # Distinct primary/backup padding, PMBR, unrelated entries and gaps survive. + for lba in original: + if lba not in (1, 2, LAST-1, LAST): assert m.mem[lba] == original[lba] + assert m.mem[2][15*128:] == original[2][15*128:] + assert m.mem[LAST-1][15*128:] == original[LAST-1][15*128:] + refuses(lambda: planner.plan(after)) # No repeat write to an already successful B. + for step in range(1, 5): + m = Memory(step) + refuses(lambda: writer.apply(m, before, approved)) + assert len(m.calls) == step + m = Memory(); m.mem[0] = bytes([1]) + m.mem[0][1:] + refuses(lambda: writer.apply(m, before, approved)); assert not m.calls + m = Memory(); changed = copy.deepcopy(approved); changed['writes_backup_first'][0]['lba'] = 0 + refuses(lambda: writer.apply(m, before, changed)); assert not m.calls + corrupt = copy.deepcopy(before); corrupt['blocks']['2'] = base64.b64encode(bytes(BS)).decode() + refuses(lambda: planner.plan(corrupt)) + missing = copy.deepcopy(before); del missing['blocks']['0'] + refuses(lambda: planner.plan(missing)) + image = bytearray(8192); image[:8] = b'ANDROID!'; struct.pack_into('"$t/repo/omamobile.conf" +printf '#!/bin/sh\nexit 0\n' >"$t/repo/tools/phone-ssh" +chmod +x "$t/repo/tools/phone-ssh" +python3 - "$t/loader.img" <<'PY' +from pathlib import Path +import sys, struct +data=bytearray(8192);data[:8]=b'ANDROID!' +struct.pack_into('<3I',data,8,64,0x8000,0) +struct.pack_into('"$t/bin/fastboot" <<'EOF' +#!/bin/sh +echo "$*" >>"$TEST_TMP/calls" +if [ "$1" = devices ]; then + printf 'FAKEPHONE\tfastboot\n' + [ "${TEST_TWO_PHONES:-0}" != 1 ] || printf 'FAKEOTHER\tfastboot\n' + exit 0 +fi +[ "$1" = -s ] && [ "$2" = FAKEPHONE ] || exit 91 +shift 2 +case "$1 $2" in + 'getvar slot-successful:b') + if [ -e "$TEST_TMP/flashed" ] && [ "${TEST_POST_FLASH_SUCCESSFUL:-yes}" = no ]; then + echo '(bootloader) slot-successful:b:no' + else grep 'slot-successful:b:' "$TEST_TMP/facts"; fi ;; + 'getvar version-bootloader') echo '(bootloader) version-bootloader:FAKE-ABL' ;; + getvar*) grep -E "(^| )$2:" "$TEST_TMP/facts" ;; + 'erase boot_b') [ "${TEST_ERASE_FAIL:-0}" = 0 ] || exit 1; echo OKAY ;; + 'flash boot_b') [ "${TEST_FLASH_FAIL:-0}" = 0 ] || exit 1; touch "$TEST_TMP/flashed"; echo OKAY ;; + 'reboot ') echo OKAY ;; + *) exit 92 ;; +esac +EOF +chmod +x "$t/bin/fastboot" +export TEST_TMP=$t +facts() { rm -f "$t/flashed"; printf '(bootloader) product:%s\n(bootloader) unlocked:%s\n(bootloader) current-slot:%s\n(bootloader) slot-successful:b:%s\n' "$1" "$2" "$3" "$4" >"$t/facts"; } +om() { FLAME_NATIVE=1 PATH="$t/bin:$PATH" KERNEL_OUT="$t/out" UBOOT_IMAGE="$t/loader.img" UBOOT_SHA256="$sum" "$t/repo/bin/omamobile" "$@" >"$t/log" 2>&1; } +sum=$(sha256sum <"$t/loader.img" | cut -d' ' -f1) +om images || { cat "$t/log"; exit 1; } +cmp "$t/loader.img" "$t/out/images/boot.img" +[[ $(cat "$t/out/images/DEVICE") == flame && $(cat "$t/out/images/BOOT_METHOD") == uboot-ext4 ]] +facts flame yes b yes +om flash || { cat "$t/log"; exit 1; } +[[ $(grep -c '^-s FAKEPHONE flash ' "$t/calls") -eq 1 ]] +grep -q '^-s FAKEPHONE flash boot_b ' "$t/calls" +if grep -q -- '--set-active' "$t/calls"; then exit 1; fi +printf 'product: flame\nunlocked: yes\ncurrent-slot: b\nslot-successful:b: yes\n' >"$t/facts" +om flash || { cat "$t/log"; exit 1; } +for bad in 'other yes b yes' 'flame no b yes' 'flame yes a yes' 'flame yes b no'; do + # Split only these fixed test tokens. + # shellcheck disable=SC2086 + facts $bad + : >"$t/calls" + if om flash; then echo "not ok - accepted $bad"; exit 1; fi + if grep -q '^-s FAKEPHONE flash ' "$t/calls"; then exit 1; fi +done +facts flame yes b yes +export TEST_POST_FLASH_SUCCESSFUL=no +: >"$t/calls" +if om flash; then echo 'not ok - rebooted with unsuccessful B'; exit 1; fi +grep -q '^-s FAKEPHONE erase boot_b$' "$t/calls" +grep -q '^-s FAKEPHONE flash boot_b ' "$t/calls" +if grep -q '^-s FAKEPHONE reboot' "$t/calls"; then exit 1; fi +unset TEST_POST_FLASH_SUCCESSFUL +facts flame yes b yes +export TEST_ERASE_FAIL=1 +: >"$t/calls" +if om flash; then echo 'not ok - ignored erase failure'; exit 1; fi +if grep -q '^-s FAKEPHONE flash ' "$t/calls"; then exit 1; fi +unset TEST_ERASE_FAIL +export TEST_TWO_PHONES=1 +: >"$t/calls" +if om flash; then echo 'not ok - ambiguous phone selection'; exit 1; fi +if grep -Eq ' erase | flash ' "$t/calls"; then exit 1; fi +FASTBOOT_SERIAL=FAKEPHONE om flash || { cat "$t/log"; exit 1; } +unset TEST_TWO_PHONES +export FLAME_BOOT_ROLE=userdata +: >"$t/calls" +if om images; then echo 'not ok - staged pending-policy userdata role'; exit 1; fi +if grep -Eq ' erase | flash ' "$t/calls"; then exit 1; fi +unset FLAME_BOOT_ROLE +facts flame yes b yes +printf changed >>"$t/out/images/boot.img" +: >"$t/calls" +if om flash; then echo 'not ok - accepted modified image'; exit 1; fi +if grep -q '^-s FAKEPHONE flash ' "$t/calls"; then exit 1; fi +sum=$(printf '%064d' 0) +if om images; then echo 'not ok - accepted incorrect source checksum'; exit 1; fi +if om push; then echo 'not ok - accepted unimplemented direct write'; exit 1; fi +python3 - "$t/loader.img" <<'PY' +from pathlib import Path +import struct, sys +p=Path(sys.argv[1]) +with p.open('wb') as f: + header=bytearray(48) + header[:8]=b'ANDROID!' + struct.pack_into('"$t/calls" +om flash || { cat "$t/log"; exit 1; } +grep -q '^-s FAKEPHONE flash boot_b ' "$t/calls" +if grep -q '^-s FAKEPHONE reboot' "$t/calls"; then echo 'not ok - stock recovery rebooted before data reset'; exit 1; fi +echo 'ok - flame stages only checked U-Boot; flash verifies product, unlock and existing successful B' diff --git a/tests/flame-root-guard.py b/tests/flame-root-guard.py new file mode 100644 index 000000000..d48621b9f --- /dev/null +++ b/tests/flame-root-guard.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +from pathlib import Path +import tempfile,subprocess,os +source=(Path(__file__).resolve().parents[1]/'device/flame/native/init').read_text() +body='UFS_RW="boot_b userdata"'+source.split('UFS_RW="boot_b userdata"',1)[1].split('\nstorage_guard ||',1)[0] +with tempfile.TemporaryDirectory() as d: + p=Path(d); sys=p/'sys';dev=p/'dev';bin=p/'bin' + for x in (sys,dev,bin):x.mkdir() + body=body.replace('/sys/class/block/',str(sys)+'/').replace('/dev/',str(dev)+'/').replace('[ -b ','[ -f ') + (p/'guard').write_text('say() { echo "$*" >&2; }\n'+body+'\nstorage_guard\n') + (bin/'blockdev').write_text('#!/bin/sh\n[ "$1" = --setro ] || exit 92\n[ "${MODE:-}" != fail ] || exit 1\n[ "${MODE:-}" != lie ] || exit 0\necho 1 > "$SYS/${2##*/}/ro"\n') + (bin/'blockdev').chmod(0o755) + def add(n,part='',ro='0'): + (sys/n).mkdir();(sys/n/'ro').write_text(ro+'\n');(sys/n/'uevent').write_text('PARTNAME='+part+'\n' if part else '');(dev/n).touch() + def run(mode=''): + return subprocess.run(['sh',str(p/'guard')],env=dict(os.environ,PATH=str(bin)+':'+os.environ['PATH'],SYS=str(sys),MODE=mode),capture_output=True) + for n,part in [('sda',''),('sda2','persist'),('sda6','boot_a'),('sda7','boot_b'),('sda15','userdata'),('sdb',''),('sde33','devinfo'),('sdf2','modemst1'),('sdf3','userdata')]:add(n,part) + assert run().returncode==0 + assert not (dev/'sda').exists() + for n in ['sda2','sda6','sdb','sde33','sdf2','sdf3']:assert (sys/n/'ro').read_text().strip()=='1',n + for n in ['sda7','sda15']:assert (sys/n/'ro').read_text().strip()=='0',n + (sys/'sda7'/'ro').write_text('1\n');(dev/'sda').touch();assert run().returncode==0;assert not (dev/'sda').exists();assert (sys/'sda7'/'ro').read_text().strip()=='1' + add('sdg');assert run('fail').returncode!=0;assert run('lie').returncode!=0 + first_pass=source.split('\nstorage_guard ||',1)[1].split('\n(',1)[0] + (p/'startup').write_text('say() { echo \"$*\" >&2; }\nsleep() { exit 94; }\n'+body+'\nstorage_guard ||'+first_pass+'\nexit 93\n') + for mode in ('fail','lie'): + result=subprocess.run(['sh',str(p/'startup')],env=dict(os.environ,PATH=str(bin)+':'+os.environ['PATH'],SYS=str(sys),MODE=mode),timeout=2,capture_output=True) + assert result.returncode==1,result + print('Root guard: exact sda allowlist, all calibration protected, other-LUN userdata rejected, whole node removed, existing RO preserved, failure closed') diff --git a/tests/phone-ssh b/tests/phone-ssh new file mode 100755 index 000000000..d2c05b797 --- /dev/null +++ b/tests/phone-ssh @@ -0,0 +1,57 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Validate host configuration without opening a connection. +# shellcheck disable=SC2016 +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +cat >"$scratch/ssh" <<'SH' +#!/bin/sh +printf '%s\n' "$@" +SH +chmod +x "$scratch/ssh" +export PATH="$scratch:$PATH" +unset OMAMOBILE_SSH_HOST OMAMOBILE_SSH_KEY OMAMOBILE_SSH_KNOWN_HOSTS OMAMOBILE_SSH_SHARE +tools/phone-ssh 'printf "%s" "$HOME"' >"$scratch/default" +grep -Fx root@172.16.42.1 "$scratch/default" >/dev/null +grep -Fx 'printf "%s" "$HOME"' "$scratch/default" >/dev/null +export OMAMOBILE_SSH_HOST='root@fe80::1234%usb-test' +export OMAMOBILE_SSH_KEY="$scratch/key with spaces" +export OMAMOBILE_SSH_KNOWN_HOSTS="$scratch/known hosts" +printf 'fake known host\n' >"$OMAMOBILE_SSH_KNOWN_HOSTS" +tools/phone-ssh 'uname -r' >"$scratch/configured" +grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/configured" >/dev/null +grep -Fx -- "$OMAMOBILE_SSH_KEY" "$scratch/configured" >/dev/null +grep -Fx -- "UserKnownHostsFile=$OMAMOBILE_SSH_KNOWN_HOSTS" "$scratch/configured" >/dev/null +grep -Fx StrictHostKeyChecking=yes "$scratch/configured" >/dev/null +if OMAMOBILE_SSH_HOST=-V tools/phone-ssh true >"$scratch/bad" 2>/dev/null; then + echo 'not ok - option-like SSH host accepted' >&2; exit 1 +fi +[[ ! -s $scratch/bad ]] +export OMAMOBILE_SSH_SHARE=1 +tools/phone-ssh 'uname -r' >"$scratch/shared" +grep -Fx ControlMaster=auto "$scratch/shared" >/dev/null +grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/shared" >/dev/null +shared=$(sed -n '/^ControlPath=/p' "$scratch/shared") +[[ $shared == *-%C && $shared != 'ControlPath=/tmp/omamobile-ssh-%C' ]] +tools/phone-ssh --fresh 'uname -r' >"$scratch/fresh" +grep -Fx ControlPath=none "$scratch/fresh" >/dev/null +grep -Fx ControlMaster=no "$scratch/fresh" >/dev/null +if grep -Fx ControlMaster=auto "$scratch/fresh"; then exit 1; fi +tools/phone-ssh --stop >"$scratch/stop" +grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/stop" >/dev/null +grep -Fx -- "$shared" "$scratch/stop" >/dev/null +grep -Fx -- -O "$scratch/stop" >/dev/null +OMAMOBILE_SSH_KEY="$scratch/other identity" tools/phone-ssh true >"$scratch/other" +[[ $(sed -n '/^ControlPath=/p' "$scratch/other") != "$shared" ]] +printf 'changed host key\n' >"$OMAMOBILE_SSH_KNOWN_HOSTS" +tools/phone-ssh true >"$scratch/changed" +[[ $(sed -n '/^ControlPath=/p' "$scratch/changed") != "$shared" ]] +# Default connections retain upstream's socket and --stop target. +unset OMAMOBILE_SSH_HOST OMAMOBILE_SSH_KEY OMAMOBILE_SSH_KNOWN_HOSTS +tools/phone-ssh true >"$scratch/default-shared" +grep -Fx 'ControlPath='"${XDG_RUNTIME_DIR:-/tmp}"'/omamobile-ssh-%C' "$scratch/default-shared" >/dev/null +tools/phone-ssh --fresh true >"$scratch/default-fresh" +grep -Fx ControlPath=none "$scratch/default-fresh" >/dev/null +echo 'ok - phone SSH options preserve sharing/fresh/stop and isolate identity/host-key policy' diff --git a/tests/rootfs-smoke b/tests/rootfs-smoke index 09ff148c9..277800fc1 100755 --- a/tests/rootfs-smoke +++ b/tests/rootfs-smoke @@ -67,6 +67,18 @@ release=$(sed -n 's/^kernel modules: \([^ ]*\) .*/\1/p' <<<"$manifest") grep -q '^omamobile-device-[a-z0-9]* .* omamobile$' <<<"$manifest" || fail "a device package from [omamobile] in the MANIFEST" pass "MANIFEST, device package, modules for $release" +if grep -q '^device: flame (omamobile-device-flame)$' <<<"$manifest"; then + for path in /usr/share/omamobile/flame-root /usr/bin/flame-storage-guard \ + /usr/lib/systemd/system/sysinit.target.wants/flame-storage-guard.service \ + /usr/lib/udev/rules.d/10-flame-storage.rules /usr/bin/xdg-terminal-exec /usr/bin/foot /usr/bin/udiskie; do + exists "$path" || fail "flame runtime dependency: $path" + done + grep -q '^ForwardToConsole=no$' <<<"$(cat_ /usr/lib/systemd/journald.conf.d/90-flame-standalone.conf)" || fail "flame journal must stay off USB" + exists /usr/lib/firmware/ftm5_fw.ftb && fail "flame touch firmware-update gate" + exists /usr/lib/systemd/system/multi-user.target.wants/flame-wifi.service && fail "Wi-Fi must remain owner-gated" + pass "flame guard and desktop dependencies; Wi-Fi/touch firmware gates" +fi + # Images from before omamobile-omarchy patched Omarchy in build-inside if exists /usr/bin/omamobile-omarchy-patches; then exists /usr/share/libalpm/hooks/95-omamobile-omarchy-patches.hook || fail "the Omarchy re-patch hook is installed" diff --git a/tools/build-flame-loader b/tools/build-flame-loader new file mode 100755 index 000000000..798d06fc5 --- /dev/null +++ b/tools/build-flame-loader @@ -0,0 +1,76 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Build the opt-in native storage loader on a Linux build host. No phone access. +# Requires git, make, aarch64-linux-gnu-gcc, dtc, flex, bison, Python 3, +# OpenSSL/UUID development headers and AOSP's mkbootimg.py with its gki helpers. +# Clone https://github.com/wirelessjoe/u-boot and check out the revision below. +set -euo pipefail +revision=e210c6956ce90e48b667eb15a8c6f20bc292b52e +source_dir="" mkbootimg="" out="" jobs=4 +die() { echo "error: $*" >&2; exit 1; } +while (($#)); do + case $1 in + --uboot) source_dir=${2:?}; shift ;; + --mkbootimg) mkbootimg=${2:?}; shift ;; + --out) out=${2:?}; shift ;; + --jobs) jobs=${2:?}; shift ;; + -h|--help) echo 'tools/build-flame-loader --uboot DIR --mkbootimg FILE --out FRESH_DIR [--jobs N]'; exit 0 ;; + *) die "unknown argument: $1" ;; + esac + shift +done +[[ -d $source_dir && -f $mkbootimg && -n $out && $jobs =~ ^[1-9][0-9]*$ ]] || die 'supply source, AOSP mkbootimg and fresh output paths' +source_dir=$(cd -- "$source_dir" && pwd) +mkbootimg=$(python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$mkbootimg") +[[ $(git -C "$source_dir" rev-parse HEAD) == "$revision" ]] || die 'wrong U-Boot source revision' +git -C "$source_dir" diff --quiet HEAD -- || die 'U-Boot source has tracked local changes' +[[ ! -e $out ]] || die 'choose a fresh output directory' +mkdir -p "$out" +out=$(cd -- "$out" && pwd) +export SOURCE_DATE_EPOCH +SOURCE_DATE_EPOCH=$(git -C "$source_dir" log -1 --format=%ct) +cross=${CROSS_COMPILE:-aarch64-linux-gnu-} +make -C "$source_dir" O="$out/uboot" ARCH=arm CROSS_COMPILE="$cross" qcom_flame_omamobile_defconfig +make -C "$source_dir" O="$out/uboot" ARCH=arm CROSS_COMPILE="$cross" W=1 -j"$jobs" +python3 - "$out" "$revision" <<'PY' +from pathlib import Path +import gzip,hashlib,json,re,sys +out=Path(sys.argv[1]);build=out/'uboot' +config=(build/'.config').read_text().splitlines() +for key in ('EFI_LOADER','FAT_WRITE','FASTBOOT_FLASH','CMD_USB_MASS_STORAGE', + 'USB_FUNCTION_MASS_STORAGE','CMD_SAVEENV','CMD_DFU','DFU_SCSI', + 'DFU_MMC','FASTBOOT_OEM_RUN','FASTBOOT_OEM_BOARD','FASTBOOT_CMD_OEM_CONSOLE'): + assert 'CONFIG_'+key+'=y' not in config,'Unexpected write facility: '+key +assert 'CONFIG_ENV_IS_NOWHERE=y' in config +header=(build/'include/generated/defaultenv_autogenerated.h').read_text() +data=bytes(int(v,16) for v in re.findall(r'0x([0-9a-fA-F]{2})',header)) +env=dict(item.split('=',1) for item in data.decode().split('\0') if '=' in item) +assert env['preboot']=='sleep 2; scsi scan' +assert env['bootcmd']=='run native_boot; run fastboot' +assert 'part number scsi 0 userdata rootpart' in env['native_boot'] +assert '/boot/omamobile/boot.img' in env['native_boot'] +assert 'usbacm' not in env['stdout'] and 'usbacm' not in env['stderr'] +assert not any('ums ' in v or 'bootefi' in v for k,v in env.items() if k.startswith('bootmenu_')) +raw=(build/'u-boot-nodtb.bin').read_bytes() +dtb=(build/'dts/upstream/src/arm64/qcom/sm8150-google-flame.dtb').read_bytes() +(out/'u-boot.gz-dtb').write_bytes(gzip.compress(raw,compresslevel=9,mtime=0)+dtb) +(out/'BUILD.json').write_text(json.dumps({'source_revision':sys.argv[2], + 'config_sha256':hashlib.sha256((build/'.config').read_bytes()).hexdigest(), + 'loader_sha256':hashlib.sha256(raw).hexdigest(),'dtb_sha256':hashlib.sha256(dtb).hexdigest(), + 'compiled_environment_checked':True,'hardware_status':'host build only; new approved RAM boot required'},indent=2)+'\n') +PY +python3 "$mkbootimg" --header_version 0 --base 0 --kernel_offset 0x8000 \ + --ramdisk_offset 0 --second_offset 0 --tags_offset 0x100 --pagesize 4096 \ + --kernel "$out/u-boot.gz-dtb" -o "$out/boot.img" +python3 - "$out/boot.img" <<'PY' +from pathlib import Path +import struct,sys +data=Path(sys.argv[1]).read_bytes() +assert data[:8]==b'ANDROID!' and 4096 SHA256SUMS) +echo "Built $out/boot.img; no phone accessed. Follow the native RAM-boot gates before flashing." diff --git a/tools/build-flame-system b/tools/build-flame-system new file mode 100755 index 000000000..b12702bbd --- /dev/null +++ b/tools/build-flame-system @@ -0,0 +1,80 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Build the experimental Pixel 4 native-root boot image, host only. +# At boot, its init may write only userdata and boot_b; read the native runbook. +# +# Usage: tools/build-flame-system --kernel Image.gz --dtb flame.dtb \ +# --watchdog-module qcom-wdt.ko.zst \ +# --ssh-key ~/.ssh/id_ed25519.pub --mkbootimg /path/to/mkbootimg.py \ +# --out /path/to/output +# +# The kernel must have UFS, USB DWC3/QCOM, configfs NCM/ACM and devtmpfs +# built in (the supplied SM8150 kernel does). Only its matching watchdog +# module is loaded. Remote processors stay disabled unless --wifi explicitly +# enables the previously tested MPSS node; firmware/NV gates still apply. +# Supply the original sm8150-google-flame.dtb, not a Tensor or coral DTB. +# mkbootimg.py and its gki/ helpers come from AOSP system/tools/mkbootimg. +# Docker runs an aarch64 Alpine builder; x86 hosts need a binfmt handler. +# Boot this image from U-Boot's fastboot server, not Android's fastboot. +set -euo pipefail +ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +kernel="" dtb="" watchdog="" key="" mkbootimg="" out="" wifi=0 +die() { echo "error: $*" >&2; exit 1; } +while (($#)); do + case $1 in + --kernel) kernel=${2:?}; shift ;; + --dtb) dtb=${2:?}; shift ;; + --watchdog-module) watchdog=${2:?}; shift ;; + --ssh-key) key=${2:?}; shift ;; + --mkbootimg) mkbootimg=${2:?}; shift ;; + --out) out=${2:?}; shift ;; + --wifi) wifi=1 ;; + -h|--help) sed -n '3,18p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) die "unknown argument: $1" ;; + esac + shift +done +command -v docker >/dev/null || die 'Docker is required' +command -v python3 >/dev/null || die 'Python 3 is required' +for path in "$kernel" "$dtb" "$watchdog" "$key" "$mkbootimg"; do + [[ -n $path && -f $path ]] || die 'supply --kernel, --dtb, --watchdog-module, --ssh-key and --mkbootimg files' +done +[[ -n $out ]] || die 'supply --out DIR' + +# Normalize paths portably (macOS readlink lacks -f on older releases), so +# relative paths and spaces survive Docker's bind mount parsing. +absolute() { python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$1"; } +kernel=$(absolute "$kernel") dtb=$(absolute "$dtb") key=$(absolute "$key") +watchdog=$(absolute "$watchdog") +mkbootimg=$(absolute "$mkbootimg") out=$(absolute "$out") +for path in "$ROOT" "$kernel" "$dtb" "$watchdog" "$key" "$mkbootimg" "$out"; do + [[ $path != *,* ]] || die 'Docker bind paths cannot contain commas' +done +[[ $(basename "$mkbootimg") == mkbootimg.py ]] || die '--mkbootimg must name AOSP mkbootimg.py' +[[ ! -e $out/boot.img ]] || die "$out/boot.img already exists; choose a fresh output directory" +python3 - "$key" <<'PY' +import base64, pathlib, struct, sys +data = pathlib.Path(sys.argv[1]).read_text().split() +if len(data) < 2 or data[0] not in ('ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256'): + sys.exit('--ssh-key must be an OpenSSH PUBLIC key, never a private key') +try: + raw = base64.b64decode(data[1], validate=True) + n, = struct.unpack('>I', raw[:4]) + assert raw[4:4+n].decode() == data[0] +except (ValueError, struct.error, AssertionError, UnicodeError): + sys.exit('invalid SSH public key') +PY + +mkdir -p "$out" +docker run --rm --platform linux/arm64 \ + --mount "type=bind,source=$ROOT,target=/src,readonly" \ + --mount "type=bind,source=$kernel,target=/input/kernel,readonly" \ + --mount "type=bind,source=$dtb,target=/input/flame.dtb,readonly" \ + --mount "type=bind,source=$watchdog,target=/input/watchdog,readonly" \ + --mount "type=bind,source=$key,target=/input/key.pub,readonly" \ + --mount "type=bind,source=$(dirname "$mkbootimg"),target=/mkbootimg,readonly" \ + --mount "type=bind,source=$out,target=/out" \ + --mount "type=bind,source=$ROOT/device/flame/native/init,target=/system-init,readonly" \ + --env FLAME_WIFI="$wifi" \ + alpine:3.22 sh /src/device/flame/native/build +echo "Built $out/boot.img (U-Boot native-root development image; no phone was accessed)" diff --git a/tools/build-rootfs b/tools/build-rootfs index 8f22f450e..2ee49860a 100755 --- a/tools/build-rootfs +++ b/tools/build-rootfs @@ -61,6 +61,10 @@ done [[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || alarm_die "bad version '$VERSION'" [[ $DEVICE =~ ^[a-z0-9]+$ ]] || alarm_die "DEVICE must be a codename" conf=device/$DEVICE/device.conf +if [[ ${FLAME_NATIVE:-0} == 1 ]]; then + [[ $DEVICE == flame ]] || alarm_die "FLAME_NATIVE=1 requires DEVICE=flame" + conf=device/flame/native/device.conf +fi [[ -f $conf ]] || alarm_die "no $conf" DEVICE_PACKAGE=$(sed -n 's/^PACKAGE=\([a-z0-9-]*\)$/\1/p' "$conf") [[ -n $DEVICE_PACKAGE ]] || alarm_die "$conf has no PACKAGE" @@ -95,7 +99,7 @@ docker run --rm --privileged --platform linux/arm64 \ -v "$ROOT:/src:ro" -v "$ROOT/out/repo:/repo:ro" -v "$modules:/modules:ro" \ -v "$volume:/target" -v "$work:/out" -v "$ALARM_CACHE/pkg:/var/cache/pacman/pkg" \ -e VERSION="$VERSION" -e DEVICE="$DEVICE" -e DEVICE_PACKAGE="$DEVICE_PACKAGE" \ - -e ROOTFS_PACKAGES="$ROOTFS_PACKAGES" \ + -e ROOTFS_PACKAGES="$ROOTFS_PACKAGES" -e FLAME_NATIVE="${FLAME_NATIVE:-0}" \ -e KERNEL_RELEASE="$release" -e MODULES_SHA256="$(sha256sum < "$modules" | cut -d' ' -f1)" \ -e GIT_COMMIT="$commit" -e ALARM_SHA256="$(sha256sum < "$ALARM_TARBALL" | cut -d' ' -f1)" \ -e OMARCHY_CHANNEL="$OMARCHY_CHANNEL" -e ALLOW_MISSING="$ALLOW_MISSING" \ diff --git a/tools/phone-ssh b/tools/phone-ssh index cbed22daa..c5fd279d6 100755 --- a/tools/phone-ssh +++ b/tools/phone-ssh @@ -12,15 +12,49 @@ # a check that a step left SSH working (a USB or firewall change, AGENTS.md # section 1) must use --fresh, which never shares. --stop closes the shared # connection. -opts=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -o ConnectTimeout=6) +set -euo pipefail +target=${OMAMOBILE_SSH_HOST:-root@172.16.42.1} +[[ $target != -* && $target != *[[:space:]]* ]] || { + echo 'phone-ssh: invalid OMAMOBILE_SSH_HOST' >&2; exit 1; +} +key=${OMAMOBILE_SSH_KEY:-} +known=${OMAMOBILE_SSH_KNOWN_HOSTS:-} +opts=(-o LogLevel=ERROR -o ConnectTimeout=6) +if [[ -n $known ]]; then + opts+=(-o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known") +else + opts+=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null) +fi +[[ -z $key ]] || opts+=(-o IdentitiesOnly=yes -i "$key") path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-%C" +if [[ $target != root@172.16.42.1 || -n $key$known ]]; then + # %C separates endpoints, but not identities or host-key policies. Never + # reuse an unchecked master for a later strict connection. Python 3 is + # needed only for sharing/stopping a connection with explicit options. + if [[ ${OMAMOBILE_SSH_SHARE:-0} == 1 && ${1:-} != --fresh || ${1:-} == --stop ]]; then + context=$(python3 - "$target" "$key" "$known" <<'PY' +import hashlib, sys +from pathlib import Path +h = hashlib.sha256() +for value in sys.argv[1:]: + h.update(value.encode()); h.update(b'\0') +if sys.argv[3]: + h.update(Path(sys.argv[3]).read_bytes()) +print(h.hexdigest()[:24]) +PY + ) + path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-$context-%C" + fi +fi case ${1:-} in --fresh) shift; opts+=(-o ControlMaster=no -o ControlPath=none) ;; - --stop) exec ssh "${opts[@]}" -o ControlPath="$path" -O exit root@172.16.42.1 2>/dev/null ;; + --stop) exec ssh "${opts[@]}" -o ControlPath="$path" -O exit "$target" 2>/dev/null ;; *) # Keepalives end a master whose phone rebooted within about 6 s, so # calls after a reboot don't wait on a dead connection. - [[ ${OMAMOBILE_SSH_SHARE:-0} == 1 ]] && opts+=(-o ControlMaster=auto -o ControlPath="$path" - -o ControlPersist=60 -o ServerAliveInterval=2 -o ServerAliveCountMax=3) ;; + if [[ ${OMAMOBILE_SSH_SHARE:-0} == 1 ]]; then + opts+=(-o ControlMaster=auto -o ControlPath="$path" + -o ControlPersist=60 -o ServerAliveInterval=2 -o ServerAliveCountMax=3) + fi ;; esac -exec ssh "${opts[@]}" root@172.16.42.1 "$@" +exec ssh "${opts[@]}" "$target" "$@" From 448877b256e07ae6b2cb70100418f75244de1202 Mon Sep 17 00:00:00 2001 From: Joe Alicata Date: Mon, 26 Oct 2026 18:37:47 -0400 Subject: [PATCH 2/2] flame 0.1.0: integrate split review corrections Quote explicit known-host paths for OpenSSH and isolate masters by canonical paths and file contents. Link unavailable companions to the immutable rebased review snapshot and state runtime ordering. Co-Authored-By: Codex --- device/flame/BOOT-PLAN.md | 4 +- device/flame/native/README.md | 9 +++- packages/omamobile-device-flame/README.md | 4 +- tests/phone-ssh | 21 +++++++- tools/phone-ssh | 64 +++++++++++++++-------- 5 files changed, 75 insertions(+), 27 deletions(-) diff --git a/device/flame/BOOT-PLAN.md b/device/flame/BOOT-PLAN.md index 8636cef70..2ff3f393b 100644 --- a/device/flame/BOOT-PLAN.md +++ b/device/flame/BOOT-PLAN.md @@ -58,7 +58,7 @@ general Qualcomm installer. Stock A on this handset is unbootable. row layout. The installed correction passed normal, deliberate-crash and unplugged restarts. This is not proof of the original spontaneous runtime reset cause. The separate GPL source and the new host-only configuration - are pinned by `tools/build-flame-loader`; see [native results](native/RESULTS.md). + are pinned by `tools/build-flame-loader`; see [native results](https://github.com/wirelessjoe/omarchy-mobile/blob/c6ce0c41f58a387f18e4f06a6de1a283698c9500/device/flame/native/RESULTS.md). [coral]: https://android.googlesource.com/device/google/coral/+/refs/heads/android13-release/bootctrl/Android.bp [bootctrl]: https://android.googlesource.com/platform/hardware/qcom/bootctrl/+/refs/heads/android13-release/boot_control.cpp @@ -194,4 +194,4 @@ and no longer starts a USB getty automatically. These publication changes were host tested/rebuilt, not flashed as part of preparing this PR. Do not transfer the installed-image test results to these new image bytes without a new approved RAM boot. Full evidence and remaining limits are in -[native/RESULTS.md](native/RESULTS.md). +[native/RESULTS.md](https://github.com/wirelessjoe/omarchy-mobile/blob/c6ce0c41f58a387f18e4f06a6de1a283698c9500/device/flame/native/RESULTS.md). diff --git a/device/flame/native/README.md b/device/flame/native/README.md index 4c36ba720..9e68a09b6 100644 --- a/device/flame/native/README.md +++ b/device/flame/native/README.md @@ -8,15 +8,20 @@ contributor workflow, **not a release installer**. The published loader recipe has additional host-only changes and needs a fresh approved RAM test. The ordinary `device/flame/device.conf` remains RAM-only. Only -`DEVICE=flame FLAME_NATIVE=1` selects [native/device.conf](device.conf). +`DEVICE=flame FLAME_NATIVE=1` selects [native/device.conf (review snapshot)](https://github.com/wirelessjoe/omarchy-mobile/blob/c6ce0c41f58a387f18e4f06a6de1a283698c9500/device/flame/native/device.conf). The generic `tools/install-phone` still refuses flame. Native `push` and the Tensor initramfs/image layout are refused; native boot writes go through `bin/omamobile flash`. Nothing here automatically repairs GPT metadata, selects a slot, restores calibration, or installs a separate Codex desktop app. +The runtime package must land before native root/build use. Boot plumbing +and SSH options are separate review components. Links to companion files +pin the original review snapshot while those components land; the basic +recovery procedure below is independent of the held GPT proposal. + ## Prerequisites and source -Read [BOOT-PLAN](../BOOT-PLAN.md) and the repository safety rules first. +Read [proposed BOOT-PLAN](https://github.com/wirelessjoe/omarchy-mobile/blob/c6ce0c41f58a387f18e4f06a6de1a283698c9500/device/flame/BOOT-PLAN.md) and the repository safety rules first. Obtain the owner's approval for every hardware reboot or write. Keep a current verified private backup set, matching factory image, physical Fastboot access, and the exact stock boot/DTBO backups. The tested handset's stock A is diff --git a/packages/omamobile-device-flame/README.md b/packages/omamobile-device-flame/README.md index 8ec36e661..3c007e883 100644 --- a/packages/omamobile-device-flame/README.md +++ b/packages/omamobile-device-flame/README.md @@ -2,7 +2,9 @@ # omamobile-device-flame Experimental Pixel 4 native-root policy. Install only into the opt-in flame -root described in [the native runbook](../../device/flame/native/README.md). +root described in [the native runbook (review snapshot)](https://github.com/wirelessjoe/omarchy-mobile/blob/c6ce0c41f58a387f18e4f06a6de1a283698c9500/device/flame/native/README.md). +The runtime must be available before using the separate native boot/root +plumbing. This split itself installs no boot image or GPT writer. The package enables the storage guard, hides protected partitions from desktop disk tools, keeps the journal off USB, and selects the tested software-rendering fallback for SDDM and user services. PID 1 feeds the 30-second watchdog; USB diff --git a/tests/phone-ssh b/tests/phone-ssh index d2c05b797..8a62a3be0 100755 --- a/tests/phone-ssh +++ b/tests/phone-ssh @@ -5,6 +5,7 @@ set -euo pipefail cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." scratch=$(mktemp -d) +scratch=$(cd "$scratch" && pwd -P) trap 'rm -rf "$scratch"' EXIT cat >"$scratch/ssh" <<'SH' #!/bin/sh @@ -18,13 +19,15 @@ grep -Fx root@172.16.42.1 "$scratch/default" >/dev/null grep -Fx 'printf "%s" "$HOME"' "$scratch/default" >/dev/null export OMAMOBILE_SSH_HOST='root@fe80::1234%usb-test' export OMAMOBILE_SSH_KEY="$scratch/key with spaces" +printf 'fake identity\n' >"$OMAMOBILE_SSH_KEY" export OMAMOBILE_SSH_KNOWN_HOSTS="$scratch/known hosts" printf 'fake known host\n' >"$OMAMOBILE_SSH_KNOWN_HOSTS" tools/phone-ssh 'uname -r' >"$scratch/configured" grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/configured" >/dev/null grep -Fx -- "$OMAMOBILE_SSH_KEY" "$scratch/configured" >/dev/null -grep -Fx -- "UserKnownHostsFile=$OMAMOBILE_SSH_KNOWN_HOSTS" "$scratch/configured" >/dev/null +grep -Fx -- 'UserKnownHostsFile="'"$OMAMOBILE_SSH_KNOWN_HOSTS"'"' "$scratch/configured" >/dev/null grep -Fx StrictHostKeyChecking=yes "$scratch/configured" >/dev/null +grep -Fx ControlPath=none "$scratch/configured" >/dev/null if OMAMOBILE_SSH_HOST=-V tools/phone-ssh true >"$scratch/bad" 2>/dev/null; then echo 'not ok - option-like SSH host accepted' >&2; exit 1 fi @@ -43,11 +46,27 @@ tools/phone-ssh --stop >"$scratch/stop" grep -Fx -- "$OMAMOBILE_SSH_HOST" "$scratch/stop" >/dev/null grep -Fx -- "$shared" "$scratch/stop" >/dev/null grep -Fx -- -O "$scratch/stop" >/dev/null +printf 'other fake identity\n' >"$scratch/other identity" OMAMOBILE_SSH_KEY="$scratch/other identity" tools/phone-ssh true >"$scratch/other" [[ $(sed -n '/^ControlPath=/p' "$scratch/other") != "$shared" ]] printf 'changed host key\n' >"$OMAMOBILE_SSH_KNOWN_HOSTS" tools/phone-ssh true >"$scratch/changed" [[ $(sed -n '/^ControlPath=/p' "$scratch/changed") != "$shared" ]] +printf 'rotated fake identity\n' >"$OMAMOBILE_SSH_KEY" +tools/phone-ssh true >"$scratch/rotated" +[[ $(sed -n '/^ControlPath=/p' "$scratch/rotated") != $(sed -n '/^ControlPath=/p' "$scratch/changed") ]] +mkdir -p "$scratch/one" "$scratch/two" +printf 'first fake identity\n' >"$scratch/one/id" +printf 'second fake identity\n' >"$scratch/two/id" +repo=$PWD +(cd "$scratch/one"; OMAMOBILE_SSH_KEY=id "$repo/tools/phone-ssh" true) >"$scratch/relative-one" +(cd "$scratch/two"; OMAMOBILE_SSH_KEY=id "$repo/tools/phone-ssh" true) >"$scratch/relative-two" +[[ $(sed -n '/^ControlPath=/p' "$scratch/relative-one") != $(sed -n '/^ControlPath=/p' "$scratch/relative-two") ]] +printf 'fake key\n' >"$scratch/token%key" +if OMAMOBILE_SSH_KEY="$scratch/token%key" tools/phone-ssh true >"$scratch/token" 2>/dev/null; then + echo 'not ok - ambiguous SSH expansion in explicit path'; exit 1 +fi +[[ ! -s $scratch/token ]] # Default connections retain upstream's socket and --stop target. unset OMAMOBILE_SSH_HOST OMAMOBILE_SSH_KEY OMAMOBILE_SSH_KNOWN_HOSTS tools/phone-ssh true >"$scratch/default-shared" diff --git a/tools/phone-ssh b/tools/phone-ssh index c5fd279d6..b2cda7772 100755 --- a/tools/phone-ssh +++ b/tools/phone-ssh @@ -19,33 +19,51 @@ target=${OMAMOBILE_SSH_HOST:-root@172.16.42.1} } key=${OMAMOBILE_SSH_KEY:-} known=${OMAMOBILE_SSH_KNOWN_HOSTS:-} +custom=0 +path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-%C" +if [[ $target != root@172.16.42.1 || -n $key$known ]]; then + custom=1 + # OpenSSH's %C omits identity/trust policy. Normalize explicit paths and + # include contents so cwd changes and key rotations never reuse a master. + # Python 3 is required only for these explicit connection options. + normalized=$(python3 - "$target" "$key" "$known" <<'PYCONTEXT' +import hashlib, sys +from pathlib import Path +h = hashlib.sha256(); h.update(sys.argv[1].encode() + b'\0') +paths = [] +for label, value in zip(('identity', 'known-hosts'), sys.argv[2:]): + if any(token in value for token in ('\n', '\r', '%', '${')): + sys.exit('phone-ssh: file paths must be literal, without newlines or OpenSSH expansion tokens') + path = Path(value).expanduser().resolve() if value else None + paths.append(str(path) if path else '') + h.update((str(path) if path else '').encode() + b'\0') + if path: + try: + if not path.is_file(): + raise OSError('not a regular file') + h.update(path.read_bytes()) + except OSError: + sys.exit('phone-ssh: cannot read explicit ' + label + ' file') + h.update(b'\0') +print(*paths, h.hexdigest()[:24], sep='\n') +PYCONTEXT + ) + key=${normalized%%$'\n'*} + normalized=${normalized#*$'\n'} + known=${normalized%%$'\n'*} + context=${normalized#*$'\n'} + path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-$context-%C" +fi opts=(-o LogLevel=ERROR -o ConnectTimeout=6) if [[ -n $known ]]; then - opts+=(-o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$known") + # This -o value is parsed again as ssh_config: protect spaces and quotes. + quoted=${known//\\/\\\\} + quoted=${quoted//\"/\\\"} + opts+=(-o StrictHostKeyChecking=yes -o "UserKnownHostsFile=\"$quoted\"") else opts+=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null) fi [[ -z $key ]] || opts+=(-o IdentitiesOnly=yes -i "$key") -path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-%C" -if [[ $target != root@172.16.42.1 || -n $key$known ]]; then - # %C separates endpoints, but not identities or host-key policies. Never - # reuse an unchecked master for a later strict connection. Python 3 is - # needed only for sharing/stopping a connection with explicit options. - if [[ ${OMAMOBILE_SSH_SHARE:-0} == 1 && ${1:-} != --fresh || ${1:-} == --stop ]]; then - context=$(python3 - "$target" "$key" "$known" <<'PY' -import hashlib, sys -from pathlib import Path -h = hashlib.sha256() -for value in sys.argv[1:]: - h.update(value.encode()); h.update(b'\0') -if sys.argv[3]: - h.update(Path(sys.argv[3]).read_bytes()) -print(h.hexdigest()[:24]) -PY - ) - path="${XDG_RUNTIME_DIR:-/tmp}/omamobile-ssh-$context-%C" - fi -fi case ${1:-} in --fresh) shift; opts+=(-o ControlMaster=no -o ControlPath=none) ;; --stop) exec ssh "${opts[@]}" -o ControlPath="$path" -O exit "$target" 2>/dev/null ;; @@ -55,6 +73,10 @@ case ${1:-} in if [[ ${OMAMOBILE_SSH_SHARE:-0} == 1 ]]; then opts+=(-o ControlMaster=auto -o ControlPath="$path" -o ControlPersist=60 -o ServerAliveInterval=2 -o ServerAliveCountMax=3) + elif ((custom)); then + # A user's ssh_config may enable sharing globally. Explicit identity + # and trust options must apply to a new connection unless requested. + opts+=(-o ControlMaster=no -o ControlPath=none) fi ;; esac exec ssh "${opts[@]}" "$target" "$@"