diff --git a/README.md b/README.md index 6ccc38d9b..736a1cd52 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,16 @@ tools/phone-provision FACTORY.zip # after the first boot: firmware from your The kernel and boot images come from `bin/omamobile kernel`, `modules`, `initramfs` and `images` (CONTRIBUTING.md §4). Step by step, with what to expect at each point: [device/cheetah/REINSTALL-RUNBOOK.md](device/cheetah/REINSTALL-RUNBOOK.md). +## Experimental POCO F3 port + +POCO F3 (`alioth`) uses a prebuilt `6.15.1-sm8250` kernel from +[mainlining/linux, nikroks/alioth at 022f7f8](https://github.com/mainlining/linux/tree/022f7f866a9377c34301e60ba131121c624d2e56), +extracted from the pinned [2026-09-28 reference release](https://github.com/Sucharek233/pmos-alioth-builds/releases/tag/2026-09-28_935d1cb). +A clean install of this branch is still pending. Use the dedicated +[build, backup and flashing guide](device/alioth/FLASH-RUNBOOK.md) and read +its [hardware limits and source-build path](device/alioth/BRINGUP-M1.md). +Its Android-v0 boot layout uses a separate guarded installer. + ## Layout | Path | What it is | diff --git a/bin/omamobile b/bin/omamobile index b8ea30aeb..57f4813bd 100755 --- a/bin/omamobile +++ b/bin/omamobile @@ -691,6 +691,9 @@ cmd_fastboot() { } cmd_flash() { + if [[ $DEVICE == alioth ]]; then + exec python3 "$ROOT/tools/alioth/install.py" "$@" + fi local img="$KERNEL_OUT/images" p load_device images_for_device "$img" @@ -810,7 +813,7 @@ case "${1:-}" in images) cmd_images ;; kexec) cmd_kexec ;; fastboot) cmd_fastboot ;; - flash) cmd_flash ;; + flash) shift; cmd_flash "$@" ;; push) cmd_push ;; kernel-shell) cmd_kernel_shell ;; *) usage ;; diff --git a/device/alioth/BRINGUP-M1.md b/device/alioth/BRINGUP-M1.md new file mode 100644 index 000000000..7aba46525 --- /dev/null +++ b/device/alioth/BRINGUP-M1.md @@ -0,0 +1,162 @@ + +# POCO F3 initial native port + +Status (2026-10-21): experimental installed native desktop verified on one +POCO F3. The public source workflow has built and passed offline validation +in an independent checkout; it has not had a clean physical reflash. Use the +[installation runbook](FLASH-RUNBOOK.md), including its backup and rescue +gates. This is a source-build port, not a ready-to-download public image. + +## Sources and layout + +[V] Board: `alioth`, Qualcomm SM8250 family / Snapdragon 870, Adreno 650, +1080x2400 display. It uses an Android v0 boot image with an appended DTB. +The Pixel Android-v4 image/push helpers are unsuitable and remain blocked. +Only `DEVICE=alioth bin/omamobile flash` dispatches to the dedicated guarded +initial installer. No kernel driver or DTS patch is included here. + +[V] The kernel, DTB, matching modules and runtime are extracted locally from +the checksum-pinned [2026-09-28 reference release](https://github.com/Sucharek233/pmos-alioth-builds/releases/tag/2026-09-28_935d1cb): +SHA-256 `17901fd0f9a96284c42b93ad1c9093aaf9bf79db62d084d80ee72afb4b29bb84`, +Linux `6.15.1-sm8250`. The source workflow is +[Sucharek233/alioth-nightly-builds](https://github.com/Sucharek233/alioth-nightly-builds/tree/935d1cb409341c17a40663167edd5c3c50c2e986). +Kernel source is [mainlining/linux, nikroks/alioth](https://github.com/mainlining/linux/tree/022f7f866a9377c34301e60ba131121c624d2e56). +Source provenance does not imply a bit-identical source rebuild. The next +kernel gate is to build that pinned tree with the extracted reference config, +compare its modules/DTB and Android-v0 packaging, and test it in guarded RAM +rescue before any slot-B install. That source-build gate has not passed. Credit to +the reference maintainers, postmarketOS/Nura, mainlining and upstream Linux. +This PR ships none of their binary images or runtime firmware. + +[V] The shared initramfs is retained, with board-checked settings and the +Qualcomm panel/watchdog modules. Its in-kernel storage read-only flags +survive switch_root; the device package keeps the whole-disk node absent +and hides Android partitions from desktop tools. The root label must match +before fsck, resizing or mounting can run. Rescue explicitly skips all three. +No Pixel register probes or boot-success metadata writers are installed. + +[V] `boot_b` is the only persistently flashed boot image. `dtbo_b` is erased +to avoid applying the original Android overlay to the appended mainline +DTB. The reference module archive is included in both the boot/root paths; +every embedded module must match the release before a build is accepted. + +## Hardware evidence and limits + +The observations below are from the installed test phone on reference +6.15.1-sm8250, including live firstboot fixes. They are not a claim that every +newly rebuilt byte or every F3 regional variant has been flashed. + +| Feature | Evidence/status | +| --- | --- | +| Boot and root | Native Arch/Omarchy booted from userdata; PIN unlock and normal reboot verified | +| Storage | Whole main-disk node absent; 11 discovered NV/calibration partitions read-only and original backups unchanged | +| Display/GPU/touch | Hardware-rendered Omarchy, direct touch and remote keyboard input verified | +| USB | Rescue and installed-root SSH; separate host identities; reconnected after reboot | +| Wi-Fi | Connection and HTTPS verified; native nftables firewall preserves USB control access | +| Battery/charging | Battery readout and charging indication observed; no independent charging-safety/power characterization | +| Buttons | Kernel exposes keys; full mapping/long-press behavior remains to be evaluated | +| Torch | Standard LED worked manually; initial shell still needs its board-specific selector | +| Bluetooth/NFC | Later manual bring-up on the test phone is outside this initial package; not claimed ready here | +| Cameras/audio | Drivers/devices partly enumerate; no usable camera pipeline or verified playback/capture | +| Sensors | Measurements obtained manually, but cold-start registry discovery stalls; proxy masked | +| Calls/SMS/MMS/data/GPS | Unsupported | +| Haptics/fingerprint | Unsupported | +| Suspend | Disabled until tested; screen blanking is separate from system suspend | +| A/B success marking | Not implemented for Xiaomi; physical FASTBOOT remains the recovery path | + +The stock build tested was global MIUI V14.0.8.0.TKHMIXM. Other bootloader/ +firmware/regional combinations are untested. Original boot/dtbo/vendor_boot +and NV backups must belong to the phone being installed, regardless of build. + +## Firstboot and kernel compatibility + +[V] Interactive systemd-firstboot must be masked: otherwise the timezone +prompt blocks the noninteractive provisioning/access path. Seed a build-time +clock lower bound before package key initialization; do not write the RTC. +The device package supplies a native nftables firewall because the reference +kernel lacks expressions used by UFW. The generic firstboot hook uses the +device firewall when present and keeps the Pixel behavior otherwise. + +[V] The reference kernel lacks Landlock. Pacman 7.1's filesystem sandbox +therefore needs `DisableSandboxFilesystem`; its download user and syscall +filtering remain enabled. The limited workaround passed a signed package +download on the phone. The package helper checks the ARM64 Landlock ABI and +removes only its own setting when a future supported kernel is used and the +helper is rerun. It never sets the broader `DisableSandbox` option. + +Systemd 262's newer socket coredump collector requires Linux >=6.19; +the root builder gates those units while retaining the legacy collector. + +The later Landlock/Waydroid kernel and Unexpected-style keyboard trials are +deliberately outside this first installation PR. Their success on one test +phone does not establish a public initial-install/release workflow. + +## Offline checks and next hardware gate + +Run `tests/all` for existing-device regressions and `tests/alioth` for the +F3's fixed targets, explicit wipe confirmation, backup/readback binding, +dry-run isolation, root-label guard, mirror timeout, device package and +overlay containment. `tools/alioth/build.py` additionally checks real ARM +payloads, module vermagic, the root filesystem, sparse round-trip and an +authenticated login to the packed ARM Dropbear in an isolated container. +It also mounts the personalized root read-only, parses firstboot settings, +runs ARM systemd/Hyprland/Quickshell version checks, resolves the desktop +and mobile-app shared libraries, and validates OpenSSH configuration. +QEMU user emulation cannot test OpenSSH's seccomp sandbox; verifying a login +to this new root still requires a real ARM kernel. These offline checks +never query a phone. + +Local validation (2026-10-22 UTC, code commit `29ec52a52873`): + +- [V] The documented build entrypoint completed on Linux/x86_64 with ARM + emulation, dedicated local keys and all ten locally signed packages. + The root contains stable Omarchy `4.0.6-1`, Hyprland `0.56.2-7`, the F3 + package `0.1.0-1` and matching `6.15.1-sm8250` modules. All 12 mobile + Omarchy patches applied. +- [V] Generic root-image smoke, personalized ext4 consistency, byte-identical + sparse round-trip, boot/rescue payload checks, ARM userspace/library + checks, OpenSSH configuration and packed Dropbear authentication passed. +- [V] `tests/all` passed, including the 17 installer gates, provisioning + fixture, storage guard, client/mirroring checks and overlay containment. + The actual built-image installer dry run passed with a fastboot trap; + no fastboot process was executed. +- [V] The pinned official TWRP image reduced to 96 MiB with identical boot + payload, AVB metadata and footer; its embedded hash verification passed. + No keys, images, firmware, backups or raw logs are included in the PR. + +Next high-risk hardware gate: a clean install from this branch on an +unlocked alioth with verified original backups. Pass: fresh rescue SSH and +guards before the wipe, then a complete native firstboot, display/touch, +Wi-Fi and USB after a reboot. Stop: any identity/hash/guard failure, missing +USB, heat, repeated reset or failed flash. Rollback: preserved slot A and +the phone's own original images; Android recovery must reset replaced +userdata. Never restore NV or relock as part of routine rollback. + +## PR review revision (2026-10-26) + +Rebased onto upstream `671b089`. The root-label gate uses `LC_ALL=C dumpe2fs` +instead of util-linux-only `blkid` options. Real ARM BusyBox 1.37 and ext4 +fixtures reproduce the incompatible full-line output and verify both the +accepted root label and rejection of Android/unlabelled data. Existing roots +must carry `omamobile-root`; otherwise boot stays in rescue without repair. + +The firstboot RTC lower bound, systemd-firstboot mask and old-kernel coredump +gating now apply only to alioth. Its firstboot drop-in orders after +`time-set.target` without pulling that target in. Shell 0.2.24 and firstboot +0.1.3 preserve upstream's touch/autologin changes; device 0.1.1 requires them. +Private signing/SSH files use `keys/alioth/`; F3 packages and generic roots use +`out/alioth/repo` and `out/alioth/`. The initial installer reads the serial once +and pins all later fastboot checks and writes to it. Probe help and dry-run +output disclose the dtbo erase and persistent slot selection. + +Host suites, including the rebased Pixel installer tests, shell, firstboot, +real ext4 provisioning and owner-key isolation, pass. The fresh private build +also passes: ten locally signed packages, all 15 Omarchy patches, rootfs smoke, +personalized ext4 and sparse round-trip verification, normal/rescue boot image +checks, ARM userspace library resolution and actual SSH configuration checks. +The packed ARM Dropbear accepts the dedicated key and executes ARM userspace. +Package signature verification remained enabled throughout. The source-build +tag `pr25-private-build-source-20261026` identifies the equivalent code used +for this build; subsequent changes record validation and refine commit text. +No phone was accessed by the build. A clean physical installation of this +new assembly remains pending; existing-phone results are a separate gate. diff --git a/device/alioth/FLASH-RUNBOOK.md b/device/alioth/FLASH-RUNBOOK.md new file mode 100644 index 000000000..839010699 --- /dev/null +++ b/device/alioth/FLASH-RUNBOOK.md @@ -0,0 +1,232 @@ + +# Install native Omarchy on a POCO F3 + +Experimental, for **POCO F3 / fastboot product `alioth`**. Read the +[hardware status](BRINGUP-M1.md) first. This installs native Arch Linux ARM +and Omarchy. Calls, SMS/MMS, mobile data, GPS, cameras, audio and vibration +are not supported by this initial profile. Suspend is disabled. + +Installation **erases all Android userdata**, including encryption metadata. +Slot A's boot images are preserved, but its Android installation will need +a factory reset to use the replaced userdata. Never relock the bootloader. +The installer does not unlock it or write radio, bootloader, vbmeta or NV. + +All commands below run from the repository root on a Linux computer. The +build phase does not access a phone. A dry run does not even query fastboot. +Every hardware-changing step is a separate decision: read its plan before +running it, and be ready to recover the phone with the physical buttons. + +## Prepare the computer and build — low risk + +Use an unlocked F3 and a reliable USB cable. Back up wanted Android files +before unlocking or installing. Keep the correct Xiaomi factory archive +for the phone's installed regional build as a recovery resource; do not +substitute an older firmware or run its bulk flashing scripts. + +The build host needs Docker access and an aarch64 binfmt handler +(`qemu-aarch64` under `/proc/sys/fs/binfmt_misc`), Python 3.12+, Bash, GnuPG, +OpenSSH, OpenSSL, curl, tar, zstd, cpio, e2fsprogs (`debugfs`, `e2fsck`, +`dumpe2fs`), Android sparse-image tools (`simg2img`, `img2simg`), AOSP +`mkbootimg` and `avbtool`, and `adb`/`fastboot`. The existing package builder +also needs `repo-add`, `bsdtar` and a C compiler. For an x86 host, the rootfs +build uses QEMU user emulation. Allow at least 80 GB of free disk space; +package caches and image validation copies can require more. + +An Omarchy host supplies `/usr/share/pacman/keyrings/omarchy{.gpg,-trusted,-revoked}`. +On another distribution, obtain and verify the official Omarchy keyring +first, then set `OMARCHY_KEYRING_DIR` to its directory. Do not disable package +signature checks to get a build through. + +```sh +python3 tools/alioth/build.py --username mobile --timezone UTC +``` + +Choose your own non-system username and IANA timezone. The script generates +dedicated SSH and local package-signing keys, downloads the +[pinned F3 reference release](https://github.com/Sucharek233/pmos-alioth-builds/releases/tag/2026-09-28_935d1cb), +checks its SHA-256, extracts its unmodified kernel/DTB and matching runtime, +and builds the Omarchy root and private boot images. It uses stable Omarchy +by default; distribution package versions are recorded in the root manifest. +An already downloaded reference can be supplied with `--reference-archive`. +The F3 builder uses a signing-key-specific cache below +`out/alioth/build-cache/` (or below `ALARM_CACHE` when supplied), avoiding +same-version packages left over from another local signing key. + +Expect: all build, image, filesystem, sparse round-trip, ARM userspace and +packed Dropbear login checks pass. Stop on any failure. Rollback: discard +the failed local outputs; no phone has been accessed. A package-server +download timeout during this local phase can be retried with the same build +command, which reuses verified caches. Keep signature checks enabled. +These are not bit-for-bit reproducible distribution package builds: +repositories can advance between builds. + +Images are in `out/alioth/images/`. The random initial PIN is stored locally +in `keys/alioth/alioth-credentials.json`. Keep **all `keys/` and `out/` private**: +boot images contain your SSH authorization and private rescue host identity; +root images contain your initial credential and downloaded runtime firmware. +Do not attach these files, backups, logs or screenshots to a public PR. +Only source is published by this port; it does not offer a public prebuilt +image or redistribute the reference firmware. + +## Preserve the original partitions — moderate risk + +Download `twrp-3.7.1_12-0-alioth.img` from the +[official Team Win download page](https://dl.twrp.me/alioth/twrp-3.7.1_12-0-alioth.img.html) +into `out/alioth/inputs/`. The helper accepts only SHA-256 +`bf5bf3300da28abbef0493829a35fcd703424c1255172f5613789a7e2cfed2e3`. + +```sh +python3 tools/alioth/prepare-recovery-ramboot.py +``` + +This removes padding to fit the bootloader's RAM-download limit. Original +boot payload, AVB metadata and footer must remain identical, and avbtool's +embedded hash check must pass. No recovery is installed persistently. + +Enter FASTBOOT with Volume Down + Power. The following queries are read-only: + +```sh +fastboot getvar product +fastboot getvar unlocked +fastboot getvar current-slot +``` + +Expect `alioth`, unlocked, slot A. Stop otherwise. Do not paste full fastboot +dumps into an issue: they contain identifiers. Then explicitly choose to +temporarily boot recovery: + +```sh +fastboot boot out/alioth/inputs/twrp-3.7.1_12-0-alioth-ramboot-96MiB.img +``` + +Keep recovery read-only. Do not install TWRP, format data or enable ADB +sideload. When root ADB is available, capture and verify original partitions: + +```sh +python3 tools/alioth/backup-recovery.py +``` + +Record the printed **manifest file** path, for example: + +```sh +BACKUPS=keys/alioth/backups/alioth-YYYYMMDD-HHMMSS/BACKUP-MANIFEST.json +``` + +Expect A/B boot, dtbo, vendor_boot and all required/discovered NV backups, +with phone and host SHA-256 agreeing. Stop if any backup fails. Rollback: +return to FASTBOOT and boot slot A; recovery was never flashed. After any +stock Android boot, take fresh backups before continuing because Android +changes NV state. These backups do not include personal Android userdata. + +## Prove rescue access before erasing Android — moderate risk + +Return to FASTBOOT. Review the plan, then choose the temporary rescue trial: + +```sh +DEVICE=alioth bin/omamobile flash --probe --dry-run +DEVICE=alioth bin/omamobile flash --probe --flash --backups "$BACKUPS" +``` + +This **erases `dtbo_b`**, selects B and RAM-boots the rescue image. It does +not flash or mount userdata. The rescue command line disables root mounting +and resizing. This is not a zero-write probe: original dtbo_b is backed up. + +```sh +python3 tools/alioth/phone-client.py host-up +python3 tools/alioth/phone-client.py doctor +python3 tools/alioth/phone-client.py shell +``` + +Expect key-authenticated rescue SSH at 172.16.42.1, kernel 6.15.1-sm8250, +userdata unmounted, protected partitions read-only and the main whole-disk +node absent. `host-up` configures only the image's synthetic USB interface, +without a default route. Check guards from the shell before proceeding: + +```sh +test ! -e /dev/sda +cat /proc/mounts +for p in /sys/class/block/*; do + [ -r "$p/partition" ] || continue + cat "$p/uevent" "$p/ro" +done +``` + +Only userdata may be writable in this rescue build. Stop on a guard failure, +repeated watchdog resets, overheating or missing SSH. Rollback before a +userdata flash: hold Volume Down + Power, select slot A and reboot. This +retains Android data but invalidates the NV backup for the next attempt. + +## Flash the reviewed image — high risk; erases Android data + +From FASTBOOT, select A **without booting Android**, so the initial-install +preflight can check the same starting state as the backup: + +```sh +fastboot --set-active=a +DEVICE=alioth bin/omamobile flash --dry-run +DEVICE=alioth bin/omamobile flash --flash --confirm-erase-userdata --backups "$BACKUPS" +``` + +Preflight checks product, unlock state, slot, actual partition sizes, pinned +recovery, personalized-image hashes and the original backup manifest bound +to this phone. Write targets are literals in code: userdata (64 MiB sparse +transfers), dtbo_b erase, then boot_b. No manifest can redirect writes to +another partition. Slot A, vendor_boot, vbmeta, radio and NV are never written. + +Stop on the first failed command. Do not blindly rerun a long transfer. +If USB bulk transfer stalls, physically restart FASTBOOT and try another +cable/USB port or a USB 2.0 hub. A successful `fastboot devices` listing alone +does not reset a stalled bulk connection. + +If userdata finished but boot installation was interrupted, preserve the +same images and backups. RAM-boot rescue again, verify the entire unmounted +root, return to FASTBOOT, select A without booting Android, then finish: + +```sh +python3 tools/alioth/verify-device-root.py --backups "$BACKUPS" +# After returning to FASTBOOT and selecting A without booting Android: +DEVICE=alioth bin/omamobile flash --finish-boot --dry-run +DEVICE=alioth bin/omamobile flash --finish-boot --flash \ + --backups "$BACKUPS" --verified-root keys/alioth/alioth-userdata-verified.json +``` + +Completion requires a phone-bound full root readback less than 30 minutes +old. It does not resend userdata. Mounting/changing userdata invalidates it. + +## First login and recovery + +Keep USB attached while the root grows and firstboot provisions the account. +Unlock with the PIN in your private credentials file, then change it using +the native Omarchy Mobile credential controls. Connect Wi-Fi in quick +settings. Controls are in the top bar; later custom Settings/keyboard work +is not part of this initial port. + +```sh +python3 tools/alioth/phone-client.py doctor +python3 tools/alioth/phone-client.py screenshot out/alioth/desktop.png +python3 tools/alioth/phone-client.py shell +``` + +Capture private logs before further experiments. Do not publish them raw. +Automatic Xiaomi A/B boot-success marking is not implemented. Avoid repeated +failed boots; if the bootloader changes slots, use physical FASTBOOT and +reselect B. Software reboot-to-bootloader is unreliable on this kernel. + +To return to stock, use FASTBOOT to select A, then the original Android +recovery's factory reset to recreate Android userdata. That destroys the +Omarchy root. If slot A does not boot, stop and construct a restore plan from +your own verified originals and correct factory build. Restoring NV or +relocking the bootloader is never a routine recovery step. + +### Private build isolation + +F3 signing/SSH keys, credentials and backup receipts live only under +`keys/alioth/`. The F3 builder explicitly selects `out/alioth/repo` for its +locally signed packages and `out/alioth/` for generic root images. The Pixel +release signing key and `out/repo` remain independent. Old checkouts keep +working as-is; do not move the maintainer key into this namespace. For an +existing F3 owner, copy only the dedicated SSH key/owner settings deliberately +or generate fresh F3 keys and rebuild; do not assume the old images match. + +`--probe` erases `dtbo_b` and leaves slot B active. It temporarily boots a +rescue image without mounting userdata; it is not a read-only phone operation. diff --git a/device/alioth/device.conf b/device/alioth/device.conf new file mode 100644 index 000000000..beb5b4c1d --- /dev/null +++ b/device/alioth/device.conf @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: MIT +CODENAME=alioth +NAME="POCO F3" +SOC=sm8250 +COMPATIBLE="xiaomi,alioth" +BOOT_METHOD=android-v0-appended-dtb +PACKAGE=omamobile-device-alioth +ROOTFS_PROFILE=alioth +ROOTFS_DIST_PACKAGES="vulkan-freedreno linux-firmware-atheros linux-firmware-qcom" +KERNEL_RELEASE=6.15.1-sm8250 +BOOT_IMAGES="boot" +UFS_RW="userdata" +PANEL_SIZE=1080x2400 +MONITOR_SCALE=2.25 diff --git a/docs/DEVICES.md b/docs/DEVICES.md index b501fa226..6dc7ef9a5 100644 --- a/docs/DEVICES.md +++ b/docs/DEVICES.md @@ -24,8 +24,15 @@ The status of each device, as verified on real hardware. Rows in the matrix have | Pixel 4 | flame | SM8150 (Snapdragon 855) | testing (temporary RAM boot; [notes](../device/flame/BRINGUP-M1.md)) | testing (RAM probe; all UFS read-only) | testing (1080x2280 console; software desktop in separate Arch payload) | testing (separate Arch payload; FD640 contexts, llvmpipe desktop) | testing (separate Arch payload; events and PIN unlock verified) | no | testing (NCM + ACM + SSH; sustained transfers can disconnect) | testing (guarded RAM scan; association untested) | no | no | no | no | no | no | - | no | no | no | no | no | no | - | | Pixel 9a ([notes](../device/tegu/NOTES.md)) | tegu | zumapro (Tensor G4) | WIP ([#28](https://github.com/derekross/omarchy-mobile/issues/28): SoC patches merging into linux-omarchy-mobile; the board DTS isn't public yet) | WIP | WIP (DSI panel, 1080x2424; unpublished kernel) | WIP (Panthor, the desktop renders; unpublished kernel) | WIP | WIP (gpio-keys; unpublished kernel) | WIP | WIP (brcmfmac joins WPA2; driver in review, [kernel #56](https://github.com/derekross/linux-omarchy-mobile/pull/56)) | WIP (powered; unpublished kernel) | WIP (the gauge reads; unpublished kernel) | no | no | no | no | WIP (audio and sensors; unpublished kernel) | WIP (speakers capped, mics, A2DP; unpublished kernel) | WIP (accelerometer, light, proximity; unpublished kernel) | no | no | no | no | no | | Pixel 8 Pro ([notes](../device/husky/NOTES.md)) | husky | zuma (Tensor G3) | WIP ([#1](https://github.com/derekross/omarchy-mobile/issues/1): our kernel boots from slot B; the zuma device tree is in review, [kernel #13](https://github.com/derekross/linux-omarchy-mobile/pull/13)) | testing (UFS at HS-G4 behind the read-only guard; Arch on `userdata`; [UFS-PLAN](../device/husky/UFS-PLAN.md)) | WIP (simple-framebuffer console) | no | no | no | testing (USB and SSH) | no | no | no | no | no | no | no | no | no | no | no | no | no | no | no | +| POCO F3 | alioth | SM8250 family (Snapdragon 870) | testing ([native port](../device/alioth/BRINGUP-M1.md)) | testing (guarded) | testing (1080x2400) | testing (Adreno 650) | testing | testing | testing | testing | no (initial profile) | testing | testing (USB indication) | no | testing (manual) | no | - | no | no (proxy masked) | no | WIP (enumerates) | no | no (disabled) | no | | *Template* | *codename* | *SoC* | | | | | | | | | | | | | | | | | | | | | | | +The F3 uses a prebuilt `6.15.1-sm8250` kernel from +[mainlining/linux, nikroks/alioth at 022f7f8](https://github.com/mainlining/linux/tree/022f7f866a9377c34301e60ba131121c624d2e56), +extracted from a pinned reference release, with matching modules. No binary +is redistributed here. [Provenance and path to building it here](../device/alioth/BRINGUP-M1.md#sources-and-layout). +All F3 positive results remain **testing** until a clean install of this branch passes. + ## cheetah (Pixel 7 Pro) in detail | Subsystem | Status | Notes | Plan | @@ -70,4 +77,4 @@ Devices we'd like to support, with the closest starting point. Open an issue to | Pixel 9 family | tokay, caiman, komodo, comet, tegu | zumapro (Tensor G4) | 9a (tegu): WIP, in the matrix above; SoC patches are merging into linux-omarchy-mobile, the board DTS isn't public yet; tracking [#28](https://github.com/derekross/omarchy-mobile/issues/28) | | Pixel 10 family | mustang (10 Pro XL) | laguna (Tensor G5) | 10 Pro XL (mustang): stock facts, contributors welcome ([#18](https://github.com/derekross/omarchy-mobile/issues/18)) | | Pixel 11 Pro, 11 Pro Fold | grizzly, yogi | malibu (Tensor G6) | stock facts, contributors welcome: 11 Pro ([#26](https://github.com/derekross/omarchy-mobile/issues/26)), 11 Pro Fold ([#40](https://github.com/derekross/omarchy-mobile/issues/40)) | -| POCO F3 | alioth | SM8250 (Snapdragon 870) | the first non-Pixel port: a guarded installer and root image in review ([#25](https://github.com/derekross/omarchy-mobile/pull/25)) | +| POCO F3 | alioth | SM8250 (Snapdragon 870) | testing: a guarded installer and root image in review; clean install pending ([#25](https://github.com/derekross/omarchy-mobile/pull/25)) | diff --git a/docs/RELEASES.md b/docs/RELEASES.md index 00bcc507d..e09b2b013 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -65,6 +65,8 @@ Bring-up tools (`*-stage`, `display-hz`, `usbc-deadman`) stay per plan: they pok | `COMPATIBLE` | `google,gs201-cheetah` | First DT root compatible; firmware names and the device check at install time use it | | `PACKAGE` | `omamobile-device-cheetah` | The device's package (and, for now, where the initramfs C helpers' sources live) | | `ROOTFS_PACKAGES` | `omamobile-audio omamobile-sensors omamobile-gnss omamobile-fingerprint omamobile-modem` | Optional. The board's own packages that `tools/build-rootfs` installs on top of the shared `rootfs/packages.omamobile`: ones tuned to this phone, which another device's image must not pull in | +| `ROOTFS_PROFILE` | unset | Optional package-list suffix: `alioth` selects `rootfs/packages.omamobile-alioth` instead of the shared Pixel profile | +| `ROOTFS_DIST_PACKAGES` | unset | Optional distribution packages, unlike locally built board packages; alioth uses Freedreno and Qualcomm firmware packages | | `DTB` | `exynos/google/gs201-cheetah.dtb` | Under `arch/arm64/boot/dts` in the kernel build, and under `dtbs/` in the kernel package | | `SOC_IDS` | `b0:0x9855001 a0:0x9855000` | `label:soc_id`. The first is what the DTB is built with; each other entry is a copy with `/soc_id` rewritten. Order is the order in `dtb.img` | | `SOC_COMPATIBLE` | (zuma: `b0-foplp:0x9865:1:0:0 b1-foplp:0x9865:1:1:0`; zumapro: `a1-ipop:0x9875:0:1:1`) | For a bootloader that matches the base DTB on `/soc_compatible` instead of `/soc_id` (zuma, zumapro). `label:product_id:major:minor:pkg_mode`, one entry per child node: the label, upper-cased with `-` as `_`, is the node name, so each label appears once. The DTB ships once, unchanged; `images` checks that it has a `/soc_compatible` node holding exactly these children. A descriptor names exactly one of `SOC_IDS` and `SOC_COMPATIBLE`, and `tools/install-phone` checks the same | @@ -75,7 +77,7 @@ Bring-up tools (`*-stage`, `display-hz`, `usbc-deadman`) stay per plan: they pok | `OS_VERSION`, `OS_PATCH_LEVEL` | `17.0.0`, `2026-07` | The `init_boot` header values (the `boot` header's, on a device without `init_boot`) | | `AVB_FOOTERS` | (zuma: `boot:0x4000000 init_boot:0x800000`) | Optional. For a bootloader whose `vbmeta` chains these partitions and, even unlocked, refuses one with no AVB footer (zuma). `image:partition_size`, each a `BOOT_IMAGES` entry, once; the size is the slot's partition size in bytes (stock's footer, `avbtool info_image`, or `fastboot getvar partition-size:_b`), a multiple of 4096. `images` adds a hash footer to each, padding it to that size, signed with AOSP's test key (an unlocked bootloader accepts any key); needs `external/avb` under `SRC_DIR` (or `AVBTOOL`, `AVB_KEY`) and `openssl` | | `AVB_ROLLBACK_INDEX`, `AVB_SECURITY_PATCH` | `1791158400`, `2026-10-05` | Required with `AVB_FOOTERS`, refused without it: stock's rollback index and `com.android.build..security_patch` from its footers. The `os_version` property is `OS_VERSION`'s major | -| `BOOT_METHOD` | `android-v4` (default when omitted) | Generic images, flash, push and installer accept only `android-v4`; other methods are refused before phone access. `ram-only` marks a probe with no persistent install support | +| `BOOT_METHOD` | `android-v4` (default when omitted) | Generic image/push/installer paths accept only `android-v4`. The dedicated `DEVICE=alioth bin/omamobile flash` path handles `android-v0-appended-dtb`; see alioth/FLASH-RUNBOOK.md. `ram-only` marks a probe with no persistent install support | | `BOOT_IMAGES` | `boot init_boot vendor_boot vendor_kernel_boot dtbo` | The images written to slot B (the `_b` suffix is added by the tools and is not configurable). `boot`, `vendor_boot` and `dtbo` are always there. Without `init_boot`, `boot` carries the empty generic ramdisk and the OS version; without `vendor_kernel_boot`, `vendor_boot` carries the DTB and the initramfs (the Pixel 6: `boot vendor_boot dtbo`) | | `UFS_RW` | `boot_b … dtbo_b userdata` | The storage guard's allowlist, packed into the initramfs as `/etc/omamobile-ufs-rw`. Only slot B's boot images (`boot_b`, `init_boot_b`, `vendor_boot_b`, `vendor_kernel_boot_b`, `dtbo_b`) and `userdata` are accepted, `userdata` and every `BOOT_IMAGES` entry must be on it, and each name only once. The init fails closed: a missing, empty or malformed file, or any other name in it, leaves every partition read-only | | `INITRAMFS_INIT` | `/initramfs/init` | The init script. A leading `/` is relative to the repo root, so devices share one script. Any other value is relative to the descriptor | diff --git a/initramfs/init b/initramfs/init index 800c9474a..48ca9e9a4 100755 --- a/initramfs/init +++ b/initramfs/init @@ -354,6 +354,12 @@ boot_arch() { done [ -n "$dev" ] || { say "arch: no userdata partition"; return 1; } [ "$(cat /sys/block/sda/${dev#/dev/}/ro)" = 0 ] || { say "arch: userdata is read-only"; return 1; } + # A boot-only trial must never repair or mount the existing Android data. + # Require our image label before any operation that could change userdata. + [ "$(LC_ALL=C dumpe2fs -h "$dev" 2>/dev/null | sed -n 's/^Filesystem volume name: *//p')" = omamobile-root ] || { + say "arch: userdata is not labelled omamobile-root (staying in initramfs)" + return 1 + } mkdir -p /newroot e2fsck -p "$dev" >/dev/null 2>&1 grow_root "$dev" diff --git a/packages/omamobile-device-alioth/10-alioth-storage.rules b/packages/omamobile-device-alioth/10-alioth-storage.rules new file mode 100644 index 000000000..6c3772579 --- /dev/null +++ b/packages/omamobile-device-alioth/10-alioth-storage.rules @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: MIT +# Continue the initramfs guard: all non-userdata partitions stay hidden. +# udev must not recreate the main LUN's deleted whole-disk node. +SUBSYSTEM=="block", KERNEL=="sda", MODE="0000", ENV{UDISKS_IGNORE}="1", RUN+="/usr/bin/rm -f /dev/sda" +SUBSYSTEM=="block", KERNEL=="sd[a-z][0-9]*", ENV{ID_PART_ENTRY_NAME}!="userdata", ENV{UDISKS_IGNORE}="1" diff --git a/packages/omamobile-device-alioth/10-usb-unmanaged.conf b/packages/omamobile-device-alioth/10-usb-unmanaged.conf new file mode 100644 index 000000000..ae76c0819 --- /dev/null +++ b/packages/omamobile-device-alioth/10-usb-unmanaged.conf @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +[keyfile] +unmanaged-devices=interface-name:usb0 diff --git a/packages/omamobile-device-alioth/10-wifi-powersave.conf b/packages/omamobile-device-alioth/10-wifi-powersave.conf new file mode 100644 index 000000000..fd18b62a1 --- /dev/null +++ b/packages/omamobile-device-alioth/10-wifi-powersave.conf @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +[connection] +wifi.powersave=2 diff --git a/packages/omamobile-device-alioth/20-alioth-firstboot.conf b/packages/omamobile-device-alioth/20-alioth-firstboot.conf new file mode 100644 index 000000000..d74b37629 --- /dev/null +++ b/packages/omamobile-device-alioth/20-alioth-firstboot.conf @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: MIT +[Unit] +After=time-set.target +Wants=systemd-timesyncd.service diff --git a/packages/omamobile-device-alioth/20-alioth-power.conf b/packages/omamobile-device-alioth/20-alioth-power.conf new file mode 100644 index 000000000..8d5bc46d6 --- /dev/null +++ b/packages/omamobile-device-alioth/20-alioth-power.conf @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: MIT +[Login] +HandlePowerKey=ignore +HandlePowerKeyLongPress=poweroff +IdleAction=ignore diff --git a/packages/omamobile-device-alioth/20-alioth-sleep.conf b/packages/omamobile-device-alioth/20-alioth-sleep.conf new file mode 100644 index 000000000..5949e5e5c --- /dev/null +++ b/packages/omamobile-device-alioth/20-alioth-sleep.conf @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: MIT +[Sleep] +AllowSuspend=no +AllowHibernation=no +AllowHybridSleep=no +AllowSuspendThenHibernate=no diff --git a/packages/omamobile-device-alioth/20-alioth-watchdog.conf b/packages/omamobile-device-alioth/20-alioth-watchdog.conf new file mode 100644 index 000000000..2264f89a3 --- /dev/null +++ b/packages/omamobile-device-alioth/20-alioth-watchdog.conf @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: MIT +[Manager] +RuntimeWatchdogSec=30s +RebootWatchdogSec=1min diff --git a/packages/omamobile-device-alioth/20-usb-gadget.network b/packages/omamobile-device-alioth/20-usb-gadget.network new file mode 100644 index 000000000..557d0c7e4 --- /dev/null +++ b/packages/omamobile-device-alioth/20-usb-gadget.network @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: MIT +[Match] +Name=usb0 + +[Network] +Address=172.16.42.1/24 +ConfigureWithoutCarrier=yes +LinkLocalAddressing=no +IPv6AcceptRA=no +DHCPServer=yes + +[DHCPServer] +PoolOffset=2 +PoolSize=1 +EmitRouter=no +EmitDNS=no diff --git a/packages/omamobile-device-alioth/LICENSE b/packages/omamobile-device-alioth/LICENSE new file mode 100644 index 000000000..f407f722f --- /dev/null +++ b/packages/omamobile-device-alioth/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Derek Ross and Omarchy Mobile contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/omamobile-device-alioth/PKGBUILD b/packages/omamobile-device-alioth/PKGBUILD new file mode 100644 index 000000000..e27b2c64b --- /dev/null +++ b/packages/omamobile-device-alioth/PKGBUILD @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: MIT +pkgname=omamobile-device-alioth +pkgver=$(cat "${startdir:-.}/version") +pkgrel=1 +pkgdesc="Experimental POCO F3 support: USB access, native firewall and safe power policy" +arch=(aarch64) +url="https://github.com/derekross/omarchy-mobile" +license=(MIT) +depends=(bash python systemd networkmanager openssh iproute2 nftables 'omamobile-shell>=0.2.24' 'omamobile-firstboot>=0.1.3') + +build() { + cc -O2 -Wall -Wextra -Werror -o "$srcdir/reboot-to" "$startdir/reboot-to.c" +} + +check() { "$startdir/test/all"; } + +package() { "$startdir/install" "$pkgdir" "$srcdir/reboot-to"; } diff --git a/packages/omamobile-device-alioth/README.md b/packages/omamobile-device-alioth/README.md new file mode 100644 index 000000000..bb202eb12 --- /dev/null +++ b/packages/omamobile-device-alioth/README.md @@ -0,0 +1,18 @@ + +# omamobile-device-alioth + +Initial experimental POCO F3 support for the pinned 6.15.1 reference kernel: +USB networking, key-authenticated access through firstboot, native nftables +firewall, display scale, watchdog and disabled suspend. No Pixel hardware, +slot-success or calibration writers are installed. The sensor proxy stays +masked until cold-start initialization is repeatable. + +`omamobile-setup-system` configures locale/time and the limited pacman +Landlock workaround. A future Landlock-capable kernel can remove the +helper's own setting by rerunning it. DownloadUser and syscall filtering +are retained. No service is started by the package build/install scripts. + +Build with `tools/build-packages packages/omamobile-device-alioth` and run +`test/all` for local staging, syntax, udev and kernel-compatibility checks. +See [the flashing runbook](../../device/alioth/FLASH-RUNBOOK.md) for the full +image and backup workflow. This package alone is not a flashable image. diff --git a/packages/omamobile-device-alioth/firewall.nft b/packages/omamobile-device-alioth/firewall.nft new file mode 100644 index 000000000..7a963eb51 --- /dev/null +++ b/packages/omamobile-device-alioth/firewall.nft @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: MIT +# Native expressions supported by the pinned alioth kernel. UFW's xtables +# compatibility expressions are unavailable in that reference build. +# Replacing only this table leaves other applications' tables untouched. +add table inet omamobile +flush table inet omamobile +table inet omamobile { + chain input { + type filter hook input priority 10; policy drop; + iifname "lo" accept + ct state established,related accept + ct state invalid drop + ip protocol icmp accept + meta l4proto ipv6-icmp accept + udp sport 67 udp dport 68 accept + udp sport 547 udp dport 546 accept + iifname "usb0" udp sport 68 udp dport 67 accept + iifname "usb0" ip daddr 172.16.42.1 tcp dport { 22, 5900 } accept + ip daddr 224.0.0.251 udp dport 5353 accept + ip6 daddr ff02::fb udp dport 5353 accept + ip daddr 239.255.255.250 udp dport 1900 accept + udp dport 53317 accept + tcp dport 53317 accept + } + chain forward { + type filter hook forward priority 10; policy drop; + } + chain output { + type filter hook output priority 10; policy accept; + } +} diff --git a/packages/omamobile-device-alioth/install b/packages/omamobile-device-alioth/install new file mode 100755 index 000000000..1777ba8ef --- /dev/null +++ b/packages/omamobile-device-alioth/install @@ -0,0 +1,23 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")" +target=${1:?staging root required} +[[ $target == /* && $target != / ]] || { echo 'Use an absolute staging directory' >&2; exit 1; } +install -Dm755 "${2:?compiled reboot-to required}" "$target/usr/bin/reboot-to" +install -Dm755 omamobile-setup-system "$target/usr/bin/omamobile-setup-system" +install -Dm755 omamobile-device-clock "$target/usr/bin/omamobile-device-clock" +install -Dm644 20-alioth-firstboot.conf "$target/usr/lib/systemd/system/omamobile-firstboot.service.d/20-alioth.conf" +install -Dm755 omamobile-device-firewall "$target/usr/bin/omamobile-device-firewall" +install -Dm644 kernel-compat.py "$target/usr/lib/omamobile/alioth/kernel-compat.py" +install -Dm644 20-usb-gadget.network "$target/usr/lib/systemd/network/20-usb-gadget.network" +install -Dm644 10-usb-unmanaged.conf "$target/etc/NetworkManager/conf.d/10-omamobile-usb.conf" +install -Dm644 10-wifi-powersave.conf "$target/etc/NetworkManager/conf.d/10-alioth-wifi-powersave.conf" +install -Dm644 20-alioth-power.conf "$target/usr/lib/systemd/logind.conf.d/20-alioth-power.conf" +install -Dm644 20-alioth-sleep.conf "$target/usr/lib/systemd/sleep.conf.d/20-alioth-sleep.conf" +install -Dm644 20-alioth-watchdog.conf "$target/usr/lib/systemd/system.conf.d/20-alioth-watchdog.conf" +install -Dm644 monitor-scale "$target/etc/omamobile/monitor-scale" +install -Dm644 10-alioth-storage.rules "$target/usr/lib/udev/rules.d/10-alioth-storage.rules" +install -Dm644 firewall.nft "$target/usr/share/omamobile/alioth/firewall.nft" +install -Dm644 omamobile-firewall.service "$target/usr/lib/systemd/system/omamobile-firewall.service" +install -Dm644 LICENSE "$target/usr/share/licenses/omamobile-device-alioth/LICENSE" diff --git a/packages/omamobile-device-alioth/kernel-compat.py b/packages/omamobile-device-alioth/kernel-compat.py new file mode 100644 index 000000000..86699b571 --- /dev/null +++ b/packages/omamobile-device-alioth/kernel-compat.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Limit pacman's legacy-kernel workaround to its filesystem sandbox.""" +import ctypes +import errno +import os +from pathlib import Path + +BLOCK = ("# omamobile-alioth: reference kernel lacks Landlock.\n" + "# DownloadUser and syscall filtering remain enabled.\n" + "DisableSandboxFilesystem\n") + + +def configure(text, abi): + text = text.replace(BLOCK, "") + if abi > 0: + return text + if "DisableSandboxFilesystem" in text: + return text # preserve a separately managed setting + if text.count("[options]\n") != 1: + raise ValueError("Expected one pacman [options] section") + return text.replace("[options]\n", "[options]\n" + BLOCK, 1) + + +def main(): + if os.uname().machine != "aarch64": + raise SystemExit("This helper requires the alioth ARM64 kernel") + libc = ctypes.CDLL(None, use_errno=True) + abi = libc.syscall(444, 0, 0, 1) + if abi < 0 and ctypes.get_errno() != errno.ENOSYS: + raise SystemExit("Unexpected Landlock query failure; pacman config unchanged") + path = Path("/etc/pacman.conf") + before = path.read_text() + after = configure(before, abi) + if before != after: + backup = path.with_name("pacman.conf.before-alioth-compat") + if not backup.exists(): + backup.write_text(before) + backup.chmod(0o600) + path.write_text(after) + + +if __name__ == "__main__": + main() diff --git a/packages/omamobile-device-alioth/monitor-scale b/packages/omamobile-device-alioth/monitor-scale new file mode 100644 index 000000000..8bd2249ac --- /dev/null +++ b/packages/omamobile-device-alioth/monitor-scale @@ -0,0 +1 @@ +2.25 diff --git a/packages/omamobile-device-alioth/omamobile-device-clock b/packages/omamobile-device-alioth/omamobile-device-clock new file mode 100644 index 000000000..3334b6caa --- /dev/null +++ b/packages/omamobile-device-alioth/omamobile-device-clock @@ -0,0 +1,11 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# The reference RTC can precede signing-key creation dates. Never write the RTC. +set -euo pipefail +epoch=0 +for file in /usr/lib/clock-epoch /var/lib/systemd/timesync/clock; do + [[ -f $file ]] || continue + stamp=$(stat -c %Y "$file") + if ((stamp > epoch)); then epoch=$stamp; fi +done +if ((epoch > $(date +%s))); then date -s "@$epoch" >/dev/null; fi diff --git a/packages/omamobile-device-alioth/omamobile-device-firewall b/packages/omamobile-device-alioth/omamobile-device-firewall new file mode 100644 index 000000000..7aa605f24 --- /dev/null +++ b/packages/omamobile-device-alioth/omamobile-device-firewall @@ -0,0 +1,8 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Called by firstboot instead of UFW on the alioth reference kernel. +# During bring-up, arm a timed stop and confirm a fresh SSH login first. +set -euo pipefail +ufw disable +systemctl disable ufw.service +systemctl enable --now omamobile-firewall.service diff --git a/packages/omamobile-device-alioth/omamobile-firewall.service b/packages/omamobile-device-alioth/omamobile-firewall.service new file mode 100644 index 000000000..7b0babec1 --- /dev/null +++ b/packages/omamobile-device-alioth/omamobile-firewall.service @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: MIT +[Unit] +Description=Omarchy Mobile native firewall for the alioth reference kernel +After=ufw.service +Before=sshd.service + +[Service] +Type=oneshot +RemainAfterExit=yes +ExecStart=/usr/bin/nft -f /usr/share/omamobile/alioth/firewall.nft +ExecReload=/usr/bin/nft -f /usr/share/omamobile/alioth/firewall.nft +ExecStop=/usr/bin/nft delete table inet omamobile + +[Install] +WantedBy=multi-user.target diff --git a/packages/omamobile-device-alioth/omamobile-setup-system b/packages/omamobile-device-alioth/omamobile-setup-system new file mode 100755 index 000000000..5b5f1bb70 --- /dev/null +++ b/packages/omamobile-device-alioth/omamobile-setup-system @@ -0,0 +1,15 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +set -euo pipefail +sed -i 's/^#\(en_US.UTF-8 UTF-8\)/\1/' /etc/locale.gen +locale-gen >/dev/null +echo 'LANG=en_US.UTF-8' > /etc/locale.conf +if [[ -n ${1:-} ]]; then + [[ $1 != /* && $1 != *..* && -f /usr/share/zoneinfo/$1 ]] || exit 1 + ln -sfn "/usr/share/zoneinfo/$1" /etc/localtime +fi +systemctl enable --now systemd-timesyncd.service +python3 /usr/lib/omamobile/alioth/kernel-compat.py +# The reference sensor stack spins while waiting for DSP registry data. +# Keep it off until repeatable cold-boot initialization is implemented. +systemctl mask iio-sensor-proxy.service diff --git a/packages/omamobile-device-alioth/reboot-to.c b/packages/omamobile-device-alioth/reboot-to.c new file mode 120000 index 000000000..a9a93a310 --- /dev/null +++ b/packages/omamobile-device-alioth/reboot-to.c @@ -0,0 +1 @@ +../omamobile-device-cheetah/src/reboot-to.c \ No newline at end of file diff --git a/packages/omamobile-device-alioth/test/all b/packages/omamobile-device-alioth/test/all new file mode 100755 index 000000000..7355460ad --- /dev/null +++ b/packages/omamobile-device-alioth/test/all @@ -0,0 +1,55 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +for file in install omamobile-setup-system omamobile-device-firewall omamobile-device-clock; do bash -n "$file"; done +t=$(mktemp -d); trap 'rm -rf "$t"' EXIT +cc -O2 -Wall -Wextra -Werror -o "$t/reboot-to" reboot-to.c +./install "$t/root" "$t/reboot-to" +for path in usr/bin/reboot-to usr/bin/omamobile-setup-system usr/bin/omamobile-device-firewall \ + usr/lib/udev/rules.d/10-alioth-storage.rules usr/lib/systemd/network/20-usb-gadget.network \ + usr/lib/systemd/system/omamobile-firewall.service usr/lib/omamobile/alioth/kernel-compat.py; do + [[ -f $t/root/$path ]] || { echo "Missing staged file: $path" >&2; exit 1; } +done +if command -v udevadm >/dev/null && udevadm --help | grep -q 'verify'; then + udevadm verify 10-alioth-storage.rules +else + echo 'ok - udev rule validation # SKIP this host lacks udevadm verify' +fi +python3 -I - "$t/root" <<'PY' +from pathlib import Path +import shlex +import sys +root = Path(sys.argv[1]) +for unit in (root / 'usr/lib/systemd/system').glob('*.service'): + for line in unit.read_text().splitlines(): + if not line.startswith('Exec') or '=' not in line: + continue + command = shlex.split(line.split('=', 1)[1])[0] + if Path(command).name.startswith('omamobile-'): + assert (root / command.lstrip('/')).is_file(), 'Unit references an unstaged helper' +print('ok - every device-specific service executable is staged') +PY +python3 -I - <<'PY' +import importlib.util +from pathlib import Path +spec = importlib.util.spec_from_file_location('compat', 'kernel-compat.py') +compat = importlib.util.module_from_spec(spec); spec.loader.exec_module(compat) +original = '[options]\nDownloadUser = alpm\n[core]\nServer = example\n' +legacy = compat.configure(original, -1) +assert 'DisableSandboxFilesystem\n' in legacy +assert 'DownloadUser = alpm' in legacy and '\nDisableSandbox\n' not in legacy +assert compat.configure(legacy, -1) == legacy +assert compat.configure(legacy, 7) == original +custom = original.replace('[options]\n', '[options]\nDisableSandboxFilesystem\n') +assert compat.configure(custom, 7) == custom +assert compat.configure(custom, -1) == custom +try: + compat.configure('[core]\n', -1) +except ValueError: + pass +else: + raise AssertionError('Malformed pacman config accepted') +print('ok - legacy kernel workaround is idempotent, limited, and removable') +PY +echo 'ok - device package stages without executing any reboot or hardware command' diff --git a/packages/omamobile-device-alioth/version b/packages/omamobile-device-alioth/version new file mode 100644 index 000000000..17e51c385 --- /dev/null +++ b/packages/omamobile-device-alioth/version @@ -0,0 +1 @@ +0.1.1 diff --git a/packages/omamobile-firstboot/bin/omamobile-firstboot b/packages/omamobile-firstboot/bin/omamobile-firstboot index f951476b1..7d98e17c4 100755 --- a/packages/omamobile-firstboot/bin/omamobile-firstboot +++ b/packages/omamobile-firstboot/bin/omamobile-firstboot @@ -211,6 +211,9 @@ step() { } s_keyring() { + if [[ -z $ROOT && -x /usr/bin/omamobile-device-clock ]]; then + /usr/bin/omamobile-device-clock + fi if [[ ! -f $ROOT/etc/pacman.d/gnupg/trustdb.gpg ]]; then pacman-key --init fi @@ -296,7 +299,8 @@ s_omarchy_system() { for part in config hardware login post-install; do while read -r leaf; do rel=${leaf#"$install/"} - if [[ " ${SKIP[*]} " == *" $rel "* ]]; then + if [[ " ${SKIP[*]} " == *" $rel "* ]] || + { [[ $rel == config/firewall.sh ]] && [[ -x $ROOT/usr/bin/omamobile-device-firewall ]]; }; then echo " skip $rel (not for a phone)" continue fi @@ -325,12 +329,17 @@ s_services() { local unit for unit in NetworkManager.service systemd-networkd.service systemd-resolved.service sshd.service \ sddm.service bluetooth.service systemd-timesyncd.service ufw.service; do + [[ $unit == ufw.service && -x $ROOT/usr/bin/omamobile-device-firewall ]] && continue systemctl enable "$unit" || echo " could not enable $unit" done systemctl mask systemd-networkd-wait-online.service NetworkManager-wait-online.service || true if [[ ! -L $ROOT/etc/resolv.conf ]]; then ln -sfn /run/systemd/resolve/stub-resolv.conf "$ROOT/etc/resolv.conf" fi + if [[ -x $ROOT/usr/bin/omamobile-device-firewall ]]; then + "$ROOT/usr/bin/omamobile-device-firewall" + return + fi ufw default deny incoming ufw default allow outgoing ufw allow 53317/udp diff --git a/packages/omamobile-firstboot/test/all b/packages/omamobile-firstboot/test/all index 429925390..8c0f81307 100755 --- a/packages/omamobile-firstboot/test/all +++ b/packages/omamobile-firstboot/test/all @@ -186,6 +186,24 @@ 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" +# A device may need native firewall rules its kernel actually supports. +mkdir -p "$R/usr/bin" +printf '#!/bin/bash\necho device-firewall >> "$CALLS"\n' > "$R/usr/bin/omamobile-device-firewall" +chmod +x "$R/usr/bin/omamobile-device-firewall" +: > "$CALLS" +good | sed '/^WIFI_/d' > "$R/etc/omamobile/firstboot.conf" +run || fail "the device firewall succeeds" +grep -qx device-firewall "$CALLS" || fail "the device firewall is called" +grep -q '^ufw ' "$CALLS" && fail "device firewall bypasses UFW rules" +grep -qx 'systemctl enable ufw.service' "$CALLS" && fail "device firewall does not enable UFW" +pass "a device firewall replaces UFW setup" +printf '#!/bin/bash\nexit 7\n' > "$R/usr/bin/omamobile-device-firewall" +good | sed '/^WIFI_/d' > "$R/etc/omamobile/firstboot.conf" +run && fail "a failed device firewall fails provisioning" +[[ -f $R/etc/omamobile/firstboot.conf ]] || fail "a failed device firewall retains provisioning" +rm "$R/usr/bin/omamobile-device-firewall" +pass "a device firewall failure keeps the conf" + # 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..a92e1779c 100755 --- a/packages/omamobile-shell/bin/omamobile-setup-user +++ b/packages/omamobile-shell/bin/omamobile-setup-user @@ -102,7 +102,12 @@ fi # Phone scale: 1440x3120 at 3 is 480x1040 logical, seeded once 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 + if [[ -f /etc/omamobile/monitor-scale ]]; then + read -r scale /dev/null available() { pacman -Sp --print-format %n "$1" >/dev/null 2>&1; } mapfile -t base < <(list /src/rootfs/packages.base) -mapfile -t ours < <(list /src/rootfs/packages.omamobile) +profile=/src/rootfs/packages.omamobile +if [[ -n ${ROOTFS_PROFILE:-} ]]; then + [[ $ROOTFS_PROFILE =~ ^[a-z0-9-]+$ ]] || die "invalid rootfs profile" + profile=/src/rootfs/packages.omamobile-$ROOTFS_PROFILE + [[ -f $profile ]] || die "missing profile $profile" +fi +mapfile -t ours < <(list "$profile") ours+=("$DEVICE_PACKAGE") read -ra board <<<"${ROOTFS_PACKAGES:-}" ours+=("${board[@]}") +read -ra dist <<<"${ROOTFS_DIST_PACKAGES:-}" missing=() skipped_ours=() for p in "${base[@]}"; do available "$p" || missing+=("$p"); done +for p in "${dist[@]}"; do available "$p" || missing+=("$p"); done ((${#missing[@]} == 0)) || die "not in any repository: ${missing[*]}" # Every package of ours must come from [omamobile], not a same-named one # elsewhere (Mesa, Hyprland, libcamera are in Arch Linux ARM and [omarchy] @@ -48,7 +57,7 @@ done ((${#missing[@]} == 0)) || die "not in out/repo: ${missing[*]} (build them: tools/build-packages; or allow: --allow-missing)" say "Base system and Omarchy (${#base[@]} packages)" -pacstrap -C /etc/pacman.conf -c -M "$T" "${base[@]}" >/var/log/pacstrap-base.log 2>&1 || { tail -40 /var/log/pacstrap-base.log; die "pacstrap failed"; } +pacstrap -C /etc/pacman.conf -c -M "$T" "${base[@]}" "${dist[@]}" >/var/log/pacstrap-base.log 2>&1 || { tail -40 /var/log/pacstrap-base.log; die "pacstrap failed"; } omarchy_list=$T/usr/share/omarchy/install/omarchy-base.packages [[ -f $omarchy_list ]] || die "no $omarchy_list in the omarchy package" @@ -120,8 +129,16 @@ fi say "Services" systemctl --root="$T" enable NetworkManager.service systemd-networkd.service systemd-resolved.service \ sshd.service sddm.service >/dev/null 2>&1 +# Our provisioning unit applies the saved locale/timezone/user settings. +# systemd's earlier interactive firstboot would block SSH and that unit. systemctl --root="$T" mask systemd-networkd-wait-online.service NetworkManager-wait-online.service >/dev/null 2>&1 ln -sfn /run/systemd/resolve/stub-resolv.conf "$T/etc/resolv.conf" +if [[ $DEVICE == alioth ]]; then + systemctl --root="$T" mask systemd-firstboot.service >/dev/null 2>&1 + for unit in systemd-coredumpd.service systemd-coredump-register.service; do + install -Dm644 /src/rootfs/coredump-kernel.conf "$T/etc/systemd/system/$unit.d/90-kernel-version.conf" + done +fi echo omamobile > "$T/etc/hostname" say "Removing per-machine state" @@ -132,22 +149,31 @@ sed -i 's/^root:[^:]*:/root:!*:/' "$T/etc/shadow" rm -rf "$T/etc/pacman.d/gnupg" # firstboot makes the phone's own keyring rm -f "$T"/etc/ssh/ssh_host_* # sshd makes the phone's own host keys printf 'uninitialized\n' > "$T/etc/machine-id" # systemd makes the phone's own id +# A freshly flashed phone's RTC may precede package signing dates. PID 1 uses +# this build-time lower bound before firstboot initializes the package keys. +if [[ $DEVICE == alioth ]]; then touch "$T/usr/lib/clock-epoch"; fi rm -f "$T/var/lib/systemd/random-seed" "$T/var/lib/dbus/machine-id" rm -rf "$T"/root/.ssh "$T"/root/.bash_history "$T"/root/.gnupg rm -rf "$T"/etc/NetworkManager/system-connections/* "$T"/var/lib/NetworkManager/* rm -rf "$T"/var/cache/pacman/pkg/* "$T"/var/log/journal/* "$T"/tmp/* "$T"/var/tmp/* find "$T/var/log" -type f -exec truncate -s 0 {} + +if [[ -f /overlay.tar ]]; then + say "Device firmware and runtime overlay" + python3 /src/tools/lib/rootfs-overlay.py extract /overlay.tar "$T" +fi + say "MANIFEST" { echo "# Omarchy Mobile root image" echo "version: $VERSION" - echo "device: $DEVICE ($DEVICE_PACKAGE${ROOTFS_PACKAGES:+ $ROOTFS_PACKAGES})" + echo "device: $DEVICE ($DEVICE_PACKAGE${ROOTFS_PACKAGES:+ $ROOTFS_PACKAGES}${ROOTFS_DIST_PACKAGES:+ $ROOTFS_DIST_PACKAGES})" echo "built: $(date -u +%Y-%m-%dT%H:%M:%SZ)" echo "repository commit: $GIT_COMMIT" echo "arch linux arm tarball sha256: $ALARM_SHA256" echo "omarchy channel: $OMARCHY_CHANNEL" echo "kernel modules: $KERNEL_RELEASE (tarball sha256 $MODULES_SHA256)" + [[ ! -f /overlay.tar ]] || echo "device overlay sha256: $(sha256sum /overlay.tar | cut -d' ' -f1)" echo "omarchy patches applied: ${applied[*]:-none}" echo "omarchy patches already in omarchy: ${upstream[*]:-none}" echo "omarchy packages not built for aarch64: ${unavailable[*]:-none}" diff --git a/rootfs/coredump-kernel.conf b/rootfs/coredump-kernel.conf new file mode 100644 index 000000000..5962ba603 --- /dev/null +++ b/rootfs/coredump-kernel.conf @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: MIT +# systemd 262's socket collector needs PIDFD_INFO_COREDUMP_SIGNAL (Linux 6.19). +# Gate before ExecCondition so older kernels do not hit a restart/start limit. +# The legacy pipe/socket collector remains available. +# https://github.com/systemd/systemd/issues/43963 +[Unit] +ConditionKernelVersion=>=6.19 diff --git a/rootfs/packages.omamobile-alioth b/rootfs/packages.omamobile-alioth new file mode 100644 index 000000000..d1546e141 --- /dev/null +++ b/rootfs/packages.omamobile-alioth @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: MIT +# Qualcomm first-boot profile. Generic Mesa/libcamera/Hyprland come from the +# distribution repositories. Do not install Pixel-only GPU or hardware packages. +omamobile-keyring +omamobile-firstboot +omamobile-omarchy +omamobile-shell +omamobile-owl-widgets +omamobile-apps +omamobile-mirror +omacam +neard diff --git a/tests/alioth b/tests/alioth new file mode 100755 index 000000000..500cf5175 --- /dev/null +++ b/tests/alioth @@ -0,0 +1,54 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Local fixtures only: never query, reboot or flash a phone. +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +for test in test-install.py test-build-isolation.py test-storageguard.py test-client-guard.py test-rfb.py; do + python3 "tools/alioth/$test" +done +python3 tools/alioth/test-provision.py +packages/omamobile-device-alioth/test/all +python3 -I - <<'PY' +from pathlib import Path +import importlib.util +import io +import tarfile +import tempfile +spec = importlib.util.spec_from_file_location('overlay', 'tools/lib/rootfs-overlay.py') +overlay = importlib.util.module_from_spec(spec); spec.loader.exec_module(overlay) +with tempfile.TemporaryDirectory() as directory: + base = Path(directory); target = base / 'target'; target.mkdir() + good = base / 'good.tar' + with tarfile.open(good, 'w') as archive: + info = tarfile.TarInfo('usr/lib/firmware/example'); info.size = 2 + archive.addfile(info, io.BytesIO(b'ok')) + link = tarfile.TarInfo('usr/lib/firmware/alias'); link.type = tarfile.SYMTYPE; link.linkname = 'example' + archive.addfile(link) + overlay.extract(good, target) + assert (target / 'usr/lib/firmware/alias').read_bytes() == b'ok' + for name, destination in [('absolute', '/outside'), ('parent', '../outside')]: + bad = base / (name + '.tar') + with tarfile.open(bad, 'w') as archive: + info = tarfile.TarInfo(destination); info.size = 3 + archive.addfile(info, io.BytesIO(b'bad')) + try: + overlay.extract(bad, target) + except (ValueError, tarfile.FilterError): + pass + else: + raise AssertionError('Escaping member accepted') + # A lexically internal symlink can escape after an earlier alias changes + # its parent depth; data_filter must resolve the actual extraction path. + bad = base / 'links.tar' + with tarfile.open(bad, 'w') as archive: + link = tarfile.TarInfo('alias'); link.type = tarfile.SYMTYPE; link.linkname = '.'; archive.addfile(link) + link = tarfile.TarInfo('alias/deep/escape'); link.type = tarfile.SYMTYPE; link.linkname = '../../outside'; archive.addfile(link) + try: + overlay.extract(bad, target) + except tarfile.FilterError: + pass + else: + raise AssertionError('Escaping symlink chain accepted') + assert not (base / 'outside').exists() +print('ok - runtime overlays preserve valid aliases and reject escapes') +PY diff --git a/tests/all b/tests/all index d06659ec9..48ce99859 100755 --- a/tests/all +++ b/tests/all @@ -20,7 +20,7 @@ sh -n device/flame/initramfs/init sh -n device/flame/initramfs/build bash -n tools/build-flame-probe 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/alioth packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all; do echo "# $t" "$t" done diff --git a/tools/alioth/backup-recovery.py b/tools/alioth/backup-recovery.py new file mode 100644 index 000000000..7c0bafb7c --- /dev/null +++ b/tools/alioth/backup-recovery.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Read original F3 boot/NV partitions from temporary TWRP into private backups.""" +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import time +from backup_recovery_names import REQUIRED_BACKUPS as REQUIRED + +ROOT = Path(__file__).resolve().parents[2] + + +def adb(*args): + return subprocess.check_output(["adb", "-d", *args], text=True).strip() + + +def main(): + if adb("shell", "id", "-u") != "0": + raise SystemExit("Read-only backup requires root ADB from temporary TWRP; no reboot or write was attempted") + subprocess.run(["adb", "-d", "shell", "test -x /sbin/twrp || test -x /system/bin/twrp"], check=True) + if adb("shell", "getprop", "ro.product.device") not in ("alioth", "aliothin"): + raise SystemExit("Connected recovery is not alioth") + names = set(adb("shell", "ls", "/dev/block/by-name").split()) + if not REQUIRED <= names: + raise SystemExit("Required F3 partitions missing; inspect the layout without writing anything") + selected = REQUIRED | {n for n in names if re.fullmatch(r"fsc|efs.*|mdm.*efs.*|modem_[ab]", n)} + if not all(re.fullmatch(r"[a-z0-9_]+", n) for n in selected): + raise SystemExit("Unexpected partition name") + serial = adb("get-serialno") + private = ROOT / "keys/alioth" + private.mkdir(mode=0o700, parents=True, exist_ok=True) + private.chmod(0o700) + base = private / "backups" + base.mkdir(mode=0o700, exist_ok=True) + base.chmod(0o700) + out = base / time.strftime("alioth-%Y%m%d-%H%M%S", time.gmtime()) + out.mkdir(parents=True, mode=0o700) + records = {} + for name in sorted(selected): + device = "/dev/block/by-name/" + name + expected = int(adb("shell", "blockdev", "--getsize64", device)) + if not (0 < expected <= 512 * 1024 * 1024): + raise SystemExit("Unexpected partition size; backup stopped") + target = out / (name + ".img") + # Recovery's exec-out merges the remote stdout and stderr streams. + # Suppress dd's status remotely so it cannot be appended to the image. + proc = subprocess.Popen(["adb", "-d", "exec-out", + f"dd if={device} bs=1048576 2>/dev/null"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + h, size = hashlib.sha256(), 0 + with target.open("wb") as dest: + target.chmod(0o600) + for data in iter(lambda: proc.stdout.read(1024 * 1024), b""): + dest.write(data) + h.update(data) + size += len(data) + errors = proc.stderr.read() + if proc.wait() or size != expected: + raise SystemExit(f"Incomplete backup for {name}; no device writes were made") + device_sha256 = adb("shell", "sha256sum", device).split()[0] + if device_sha256 != h.hexdigest(): + raise SystemExit(f"Device/off-device checksum differs for {name}; backup stopped") + target.chmod(0o600) + records[name] = {"file": target.name, "bytes": size, "sha256": h.hexdigest()} + print(f"Read and checksummed {name} ({size} bytes)", flush=True) + receipt = {"device": "alioth", "serial_sha256": hashlib.sha256(serial.encode()).hexdigest(), + "read_only_capture": True, "device_sha256_verified": True, + "partitions": records, "phone_written": False} + manifest = out / "BACKUP-MANIFEST.json" + manifest.write_text(json.dumps(receipt, indent=2) + "\n") + manifest.chmod(0o600) + print(f"Private backup manifest: {manifest}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/backup_recovery_names.py b/tools/alioth/backup_recovery_names.py new file mode 100644 index 000000000..d67404233 --- /dev/null +++ b/tools/alioth/backup_recovery_names.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +REQUIRED_BACKUPS = {"boot_a", "boot_b", "dtbo_a", "dtbo_b", "vendor_boot_a", "vendor_boot_b", + "persist", "modemst1", "modemst2", "fsg"} diff --git a/tools/alioth/build-boot.py b/tools/alioth/build-boot.py new file mode 100644 index 000000000..74d568992 --- /dev/null +++ b/tools/alioth/build-boot.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Pack the pinned F3 kernel and custom initramfs into an Android v0 image.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import struct +import subprocess + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + os.umask(0o077) + parser = argparse.ArgumentParser() + parser.add_argument("--out", type=Path, default=ROOT / "out/alioth") + args = parser.parse_args() + out = args.out.resolve() + out.mkdir(parents=True, exist_ok=True) + out.chmod(0o700) + ref = out / "reference" + key = ROOT / "keys/alioth/alioth_ed25519.pub" + if not key.read_text().startswith("ssh-ed25519 "): + raise SystemExit("Dedicated SSH PUBLIC key missing") + metadata = json.loads((ref / "REFERENCE.json").read_text()) + for name, expected in metadata["boot_sha256"].items(): + if hashlib.sha256((ref / name).read_bytes()).hexdigest() != expected: + raise SystemExit(f"Reference input changed: {name}") + subprocess.run(["docker", "pull", "--platform", "linux/arm64", "alpine:3.22"], check=True) + digest = json.loads(subprocess.check_output(["docker", "image", "inspect", "alpine:3.22"]))[0]["RepoDigests"][0] + subprocess.run(["docker", "run", "--rm", "--platform", "linux/arm64", + "-v", f"{ROOT}:/src:ro", "-v", f"{ref}:/reference:ro", + "-v", f"{key}:/input/key.pub:ro", "-v", f"{out}:/out", + "-e", f"OUT_UID={os.getuid()}", "-e", f"OUT_GID={os.getgid()}", + digest, "sh", "/src/tools/alioth/build-initramfs.sh"], check=True) + images = out / "images" + images.mkdir(exist_ok=True) + images.chmod(0o700) + pack = ["mkbootimg", "--header_version", "0", "--base", "0x00000000", + "--kernel_offset", "0x00008000", "--ramdisk_offset", "0x01000000", + "--second_offset", "0x00f00000", "--tags_offset", "0x00000100", + "--pagesize", "4096", "--kernel", str(ref / "Image.gz-dtb"), + "--ramdisk", str(out / "initramfs.cpio.gz")] + cmdline = "console=tty0 rdinit=/init panic=10 printk.devkmsg=on rootwait" + subprocess.run(pack + ["--cmdline", cmdline, "--output", str(images / "boot.img")], check=True) + subprocess.run(pack + ["--cmdline", cmdline + " omamobile.initramfs omamobile.noresize", + "--output", str(images / "boot-rescue.img")], check=True) + boot = (images / "boot.img").read_bytes() + if boot[:8] != b"ANDROID!" or struct.unpack_from(" 192 * 1024 * 1024: + raise SystemExit("Boot image exceeds the documented alioth boot partition") + (images / "DEVICE").write_text("alioth\n") + manifest = {"device": "alioth", "kernel_release": metadata["kernel_release"], + "reference": metadata, "alpine_builder": digest, + "ssh_public_key_sha256": hashlib.sha256(key.read_bytes()).hexdigest(), + "initramfs_sha256": hashlib.sha256((out / "initramfs.cpio.gz").read_bytes()).hexdigest(), + "init_source_sha256": hashlib.sha256((ROOT / "initramfs/init").read_bytes()).hexdigest(), + "builder_source_sha256": hashlib.sha256((ROOT / "tools/alioth/build-initramfs.sh").read_bytes()).hexdigest(), + "boot_bytes": len(boot), "boot_sha256": hashlib.sha256(boot).hexdigest(), + "rescue_boot_bytes": (images / "boot-rescue.img").stat().st_size, + "rescue_boot_sha256": hashlib.sha256((images / "boot-rescue.img").read_bytes()).hexdigest(), + "phone_accessed": False, "hardware_boot_tested": False} + (images / "BOOT-MANIFEST.json").write_text(json.dumps(manifest, indent=2) + "\n") + print(f"Packed alioth boot.img ({len(boot)} bytes)", flush=True) + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/build-initramfs.sh b/tools/alioth/build-initramfs.sh new file mode 100644 index 000000000..7a11af620 --- /dev/null +++ b/tools/alioth/build-initramfs.sh @@ -0,0 +1,88 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT +# Runs in the recorded aarch64 Alpine container. Only local image files change. +set -eu +apk add --no-cache cpio gcc musl-dev gzip kmod python3 dropbear +stage=/tmp/alioth-initramfs +mkdir -p "$stage" +apk --root "$stage" --initdb --no-cache \ + --repositories-file /etc/apk/repositories --keys-dir /etc/apk/keys add \ + alpine-baselayout busybox busybox-extras dropbear iproute2 util-linux \ + e2fsprogs e2fsprogs-extra kmod +mkdir -p "$stage/proc" "$stage/sys" "$stage/dev" "$stage/run" "$stage/root/.ssh" \ + "$stage/usr/lib/modules" "$stage/usr/lib/firmware" "$stage/etc/dropbear" "$stage/usr/local/bin" +# Alpine is not usr-merged. kmod and the kernel look below /lib. +ln -s ../usr/lib/modules "$stage/lib/modules" +ln -s ../usr/lib/firmware "$stage/lib/firmware" +cp /input/key.pub "$stage/root/.ssh/authorized_keys" +chmod 700 "$stage/root/.ssh" +chmod 600 "$stage/root/.ssh/authorized_keys" +# Keep the rescue server's identity stable across boots of this owner's +# images. This private key remains in ignored local output, never in git. +hostkey=/out/dropbear_ed25519_host_key +if [ ! -s "$hostkey" ]; then + umask 077 + dropbearkey -t ed25519 -f "$hostkey" >/dev/null 2>&1 +fi +cp "$hostkey" "$stage/etc/dropbear/dropbear_ed25519_host_key" +chmod 600 "$stage/etc/dropbear/dropbear_ed25519_host_key" +chown "${OUT_UID:-0}:${OUT_GID:-0}" "$hostkey" +release=$(cat /reference/include/config/kernel.release) +case "$release" in 6.15.1-sm8250) ;; *) echo 'Unreviewed kernel release' >&2; exit 1 ;; esac +cp -a /reference/modules/modules/"$release" "$stage/usr/lib/modules/" +cp -a /reference/boot-firmware/. "$stage/usr/lib/firmware/" +depmod -b "$stage" "$release" +for module in qcom-wdt panel-samsung-ams667xx01; do + path=$(modinfo -b "$stage" -k "$release" -n "$module") + [ "$(modinfo -F vermagic "$path" | cut -d ' ' -f1)" = "$release" ] || exit 1 +done +cp /src/initramfs/init "$stage/init" +python3 - "$stage/init" "$release" <<'PY' +from pathlib import Path +import sys +p = Path(sys.argv[1]) +s = p.read_text() +needle = 'hostname omamobile\n' +assert s.count(needle) == 1 +s = s.replace(needle, '''# Matching Qualcomm watchdog and panel modules are required before Arch. +modprobe qcom-wdt || echo "omamobile: qcom watchdog module failed" >/dev/kmsg +if [ -c /dev/watchdog0 ]; then + watchdog -t 5 -T 30 /dev/watchdog0 +fi +modprobe panel-samsung-ams667xx01 || echo "omamobile: panel module failed" >/dev/kmsg +hostname omamobile +''') +needle = 'mkdir -p $g/functions/ncm.usb0 $g/functions/acm.GS0\n' +assert s.count(needle) == 1 +s = s.replace(needle, needle + '''# Locally administered addresses, unrelated to the phone's factory identity. +echo 02:10:42:00:00:01 > $g/functions/ncm.usb0/dev_addr +echo 02:10:42:00:00:02 > $g/functions/ncm.usb0/host_addr +''') +needle = 'dropbear -R -E -p 22' +assert s.count(needle) == 1 +s = s.replace(needle, 'dropbear -R -E -s -p 172.16.42.1:22') +p.write_text(s) +PY +chmod 755 "$stage/init" +echo xiaomi,alioth > "$stage/etc/omamobile-compatible" +echo userdata > "$stage/etc/omamobile-ufs-rw" +echo 'POCO F3 Omarchy' > "$stage/etc/omamobile-usb-product" +gcc -Os -static -o "$stage/usr/local/bin/reboot-to" \ + /src/packages/omamobile-device-cheetah/src/reboot-to.c +# Verify userspace actually executes under ARM emulation before packaging. +chroot "$stage" /bin/busybox true +chroot "$stage" /usr/sbin/dropbear -h >/tmp/dropbear-help 2>&1 || [ "$?" = 1 ] +grep -q 'Dropbear' /tmp/dropbear-help +python3 - "$stage" <<'PY' +import os +from pathlib import Path +import sys +root = Path(sys.argv[1]) +for path in list(root.rglob('*')) + [root]: + os.utime(path, (1790636353, 1790636353), follow_symlinks=False) +PY +(cd "$stage" && find . -print0 | sort -z | cpio --null --quiet -o -H newc --owner=0:0 --reproducible) \ + | gzip -n -9 > /out/initramfs.cpio.gz +cp /tmp/dropbear-help /out/dropbear-help.txt +chown "${OUT_UID:-0}:${OUT_GID:-0}" /out/initramfs.cpio.gz /out/dropbear-help.txt +echo "ARM initramfs built; UFS guard permits userdata only" diff --git a/tools/alioth/build.py b/tools/alioth/build.py new file mode 100644 index 000000000..fb3dddd47 --- /dev/null +++ b/tools/alioth/build.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Build an owner's private alioth images locally; never flash or query a phone.""" +import argparse +import datetime +import hashlib +import os +import re +from pathlib import Path +import subprocess +from zoneinfo import ZoneInfo + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--username", required=True) + parser.add_argument("--timezone", default="UTC") + parser.add_argument("--reference-archive", type=Path) + parser.add_argument("--version", default="alioth-" + datetime.date.today().isoformat()) + args = parser.parse_args() + if not re.fullmatch(r'[a-z_][a-z0-9_-]{0,31}', args.username): + parser.error('username must be a valid local login') + if not re.fullmatch(r'[0-9A-Za-z._-]+', args.version): + parser.error('version may contain only letters, digits, dot, underscore and hyphen') + try: + ZoneInfo(args.timezone) + except (ValueError, KeyError): + parser.error('timezone must be an installed IANA timezone') + reference_archive = args.reference_archive.resolve() if args.reference_archive else None + os.chdir(ROOT) + os.umask(0o077) + env = dict(os.environ, DEVICE="alioth", OMARCHY_CHANNEL=os.environ.get("OMARCHY_CHANNEL", "stable"), + OMAMOBILE_KEYRING_DIR=str(ROOT / "keys/alioth/build-keyring"), KERNEL_OUT=str(ROOT / "out/alioth/reference"), + OMAMOBILE_SIGNING_DIR=str(ROOT / "keys/alioth"), + OMAMOBILE_REPO_DIR=str(ROOT / "out/alioth/repo"), + OMAMOBILE_ROOTFS_OUT=str(ROOT / "out/alioth")) + + def run(*command): + subprocess.run(command, env=env, check=True) + + run("python3", "tools/alioth/init-keys.py") + # A package with the same name/version can already be cached under a + # different local signing key. Never import that key or relax signatures. + key_tag = hashlib.sha256((ROOT / "keys/alioth/build-keyring/omamobile.gpg").read_bytes()).hexdigest()[:16] + cache_base = Path(os.environ.get("ALARM_CACHE", ROOT / "out/alioth/build-cache")).expanduser().resolve() + env["ALARM_CACHE"] = str(cache_base / key_tag) + download = ["python3", "tools/alioth/download-reference.py"] + if reference_archive: + download += ["--archive", str(reference_archive)] + run(*download) + run("python3", "tools/alioth/prepare-reference.py", "--inputs", "out/alioth/inputs", "--out", "out/alioth/reference") + run("python3", "tools/alioth/prepare-overlay.py") + profile = (ROOT / "rootfs/packages.omamobile-alioth").read_text().splitlines() + packages = [line.split("#", 1)[0].strip() for line in profile] + packages = list(dict.fromkeys([p for p in packages if p] + ["omamobile-device-alioth"])) + run("tools/build-packages", *("packages/" + name for name in packages)) + run("tools/build-rootfs", "--keep-raw", "--version", args.version, "--overlay", "out/alioth/root-overlay.tar") + run("python3", "tools/alioth/provision-image.py", "--root-image", + f"out/alioth/omamobile-rootfs-{args.version}-aarch64.img", "--username", args.username, "--timezone", args.timezone) + run("python3", "tools/alioth/build-boot.py") + run("python3", "tools/alioth/verify-image.py") + run("tools/alioth/smoke-userspace.sh", "out/alioth/images/rootfs.img") + run("tools/alioth/test-initramfs-ssh.sh") + print("Private images validated in out/alioth/images. No phone accessed.") + print("Next: read device/alioth/FLASH-RUNBOOK.md. Building does not authorize flashing.") + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/download-reference.py b/tools/alioth/download-reference.py new file mode 100644 index 000000000..3215d51ff --- /dev/null +++ b/tools/alioth/download-reference.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Fetch the pinned reference kernel/runtime archive; never access a phone.""" +import argparse +import hashlib +from pathlib import Path +import shutil +import urllib.request +import zipfile + +ROOT = Path(__file__).resolve().parents[2] +NAME = "xiaomi-alioth-2026-09-28.zip" +URL = "https://github.com/Sucharek233/pmos-alioth-builds/releases/download/2026-09-28_935d1cb/xiaomi-alioth.zip" +SHA256 = "17901fd0f9a96284c42b93ad1c9093aaf9bf79db62d084d80ee72afb4b29bb84" +MEMBERS = {"boot-xiaomi-alioth.img", "rootfs-xiaomi-alioth.img"} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--inputs", type=Path, default=ROOT / "out/alioth/inputs") + parser.add_argument("--archive", type=Path, help="use an already downloaded archive") + args = parser.parse_args() + args.inputs.mkdir(parents=True, exist_ok=True) + archive = args.inputs / NAME + if args.archive: + if args.archive.resolve() != archive.resolve(): + shutil.copyfile(args.archive, archive) + elif not archive.exists(): + temporary = archive.with_suffix(".zip.part") + with urllib.request.urlopen(URL, timeout=60) as src, temporary.open("wb") as dst: + shutil.copyfileobj(src, dst, 1024 * 1024) + temporary.replace(archive) + with archive.open("rb") as src: + actual = hashlib.file_digest(src, "sha256").hexdigest() + if actual != SHA256: + raise SystemExit("Reference SHA-256 differs; nothing extracted") + destination = args.inputs / "linux-reference" + destination.mkdir(exist_ok=True) + with zipfile.ZipFile(archive) as src: + if set(src.namelist()) != MEMBERS or len(src.namelist()) != len(MEMBERS): + raise SystemExit("Unexpected reference archive members") + for name in sorted(MEMBERS): + with src.open(name) as source, (destination / name).open("wb") as target: + shutil.copyfileobj(source, target, 1024 * 1024) + print("Pinned reference verified and extracted locally; no phone accessed") + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/init-keys.py b/tools/alioth/init-keys.py new file mode 100644 index 000000000..4591ecb9c --- /dev/null +++ b/tools/alioth/init-keys.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Generate local build/SSH keys without changing the committed keyring.""" +import os +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[2] + + +def run(command, **kwargs): + return subprocess.check_output(command, stderr=subprocess.PIPE, **kwargs) + + +def main(): + os.umask(0o077) + private = ROOT / "keys/alioth" + private.mkdir(mode=0o700, parents=True, exist_ok=True) + private.chmod(0o700) + ssh = private / "alioth_ed25519" + if not ssh.exists(): + run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "alioth-local", "-f", str(ssh)]) + public = run(["ssh-keygen", "-y", "-f", str(ssh)]) + ssh.with_suffix(".pub").write_bytes(public) + gnupg = private / "gnupg" + gnupg.mkdir(mode=0o700, exist_ok=True) + prefix = ["gpg", "--homedir", str(gnupg), "--batch"] + fingerprint = private / "fingerprint" + if not fingerprint.exists(): + existing = run(prefix + ["--with-colons", "--list-secret-keys"]) + if b"sec:" in existing: + raise SystemExit("Existing signing keys without a selected fingerprint; choose one explicitly") + run(prefix + ["--pinentry-mode", "loopback", "--passphrase", "", "--quick-gen-key", + "Local Omarchy Mobile build", "ed25519", "sign", "1y"]) + listing = run(prefix + ["--with-colons", "--list-secret-keys"]).decode() + fingerprint.write_text(next(line.split(":")[9] for line in listing.splitlines() + if line.startswith("fpr:")) + "\n") + key = fingerprint.read_text().strip() + run(prefix + ["--list-secret-keys", key]) + ring = private / "build-keyring" + ring.mkdir(mode=0o700, exist_ok=True) + (ring / "omamobile.gpg").write_bytes(run(prefix + ["--export-options", "export-minimal", "--export", key])) + (ring / "omamobile-trusted").write_text(key + ":6:\n") + (ring / "omamobile-revoked").write_text("") + print("Local keys ready in ignored keys/alioth/. Set OMAMOBILE_KEYRING_DIR=$PWD/keys/alioth/build-keyring") + print("Do not publish keys/, personalized images, backups or downloaded firmware") + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/install.py b/tools/alioth/install.py new file mode 100644 index 000000000..b3c349e49 --- /dev/null +++ b/tools/alioth/install.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Gated initial F3 install. Default is an offline, read-only command plan.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import shlex +import struct +import subprocess +import time +from backup_recovery_names import REQUIRED_BACKUPS + +ROOT = Path(__file__).resolve().parents[2] +RECOVERY = ROOT / "out/alioth/inputs/twrp-3.7.1_12-0-alioth.img" +RECOVERY_SHA256 = "bf5bf3300da28abbef0493829a35fcd703424c1255172f5613789a7e2cfed2e3" + + +def digest(path): + h = hashlib.sha256() + with path.open("rb") as src: + for b in iter(lambda: src.read(4 * 1024 * 1024), b""): + h.update(b) + return h.hexdigest() + + +def verify_images(directory): + boot = json.loads((directory / "BOOT-MANIFEST.json").read_text()) + root = json.loads((directory / "ROOT-MANIFEST.json").read_text()) + if boot["device"] != "alioth" or root["device"] != "alioth": + raise ValueError("Images are not marked for alioth") + for name, expected in (("boot.img", boot["boot_sha256"]), + ("boot-rescue.img", boot["rescue_boot_sha256"]), + ("rootfs-sparse.img", root["rootfs_sparse_sha256"])): + if digest(directory / name) != expected: + raise ValueError(f"Image checksum mismatch: {name}") + with (directory / "rootfs-sparse.img").open("rb") as src: + header = src.read(28) + if len(header) != 28: + raise ValueError("Truncated sparse image") + magic, major, minor, file_header, chunk_header, block, count, chunks, crc = struct.unpack("/dev/null) == ok ]] || omarchy-brightness-display on']) + + +def screenshot(path): + # Compressed compositor capture is faster than raw RFB over USB and avoids + # wayvnc's placeholder/stalled capture during screen blanking transitions. + owner = json.loads((ROOT / "out/alioth/images/ROOT-MANIFEST.json").read_text())["username"] + command = ["systemd-run", "--user", "--machine=" + owner + "@", "--wait", "--pipe", "--collect", "--quiet", + "/usr/bin/grim", "-"] + result = subprocess.run(ssh_options() + [shlex.join(command)], check=True, stdout=subprocess.PIPE, timeout=25) + if not result.stdout.startswith(b"\x89PNG\r\n\x1a\n"): + raise ValueError("Compositor did not return a PNG screenshot") + path.touch(mode=0o600) + path.chmod(0o600) + path.write_bytes(result.stdout) + print(path) + + +@contextmanager +def screen(): + guarded_mirror("on") + with socket.socket() as allocator: + allocator.bind(("127.0.0.1", 0)) + port = allocator.getsockname()[1] + options = ssh_options() + tunnel = subprocess.Popen(options[:-1] + ["-N", "-L", f"127.0.0.1:{port}:{ADDRESS}:5900", options[-1]]) + try: + stream = None + for _ in range(50): + if tunnel.poll() is not None: + raise ConnectionError("SSH tunnel failed") + try: + stream = socket.create_connection(("127.0.0.1", port), timeout=2) + stream.settimeout(20) + break + except OSError: + time.sleep(0.2) + if stream is None: + raise ConnectionError("USB mirror did not become reachable") + with stream: + yield RFB(stream) + finally: + tunnel.terminate() + try: + tunnel.wait(timeout=5) + except subprocess.TimeoutExpired: + tunnel.kill() + tunnel.wait() + + +def host_up(): + links = json.loads(subprocess.check_output(["ip", "-j", "link", "show"], text=True)) + found = [l["ifname"] for l in links if l.get("address", "").lower() == "02:10:42:00:00:02"] + if len(found) != 1: + raise SystemExit("The F3 Omarchy USB interface is not connected; no host network changes made") + interface, name = found[0], "omarchy-poco-f3" + exists = subprocess.run(["nmcli", "connection", "show", name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if exists.returncode: + subprocess.run(["nmcli", "connection", "add", "type", "ethernet", "con-name", name, + "ifname", interface, "ipv4.method", "manual", "ipv4.addresses", "172.16.42.2/24", + "ipv4.never-default", "yes", "ipv6.method", "disabled"], check=True) + else: + subprocess.run(["nmcli", "connection", "modify", name, "connection.interface-name", interface], check=True) + subprocess.run(["nmcli", "connection", "up", name, "ifname", interface], check=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + sub = p.add_subparsers(dest="action", required=True) + sub.add_parser("host-up", help="Configure only the matching USB Ethernet interface") + sub.add_parser("doctor", help="Read kernel, USB, SSH and boot-service state") + sub.add_parser("shell", help="Interactive SSH shell with the dedicated key") + sub.add_parser("wake", help="Wake the screen through the logged-in user's Omarchy session") + sub.add_parser("mirror-off", help="Stop mirroring with a timed firewall undo around the change") + cmd = sub.add_parser("exec"); cmd.add_argument("command", nargs=argparse.REMAINDER) + shot = sub.add_parser("screenshot"); shot.add_argument("path", type=Path) + tap = sub.add_parser("tap"); tap.add_argument("x", type=int); tap.add_argument("y", type=int) + text = sub.add_parser("type"); text.add_argument("text") + key = sub.add_parser("key"); key.add_argument("combination", help="For example Return, Ctrl+l, Super+Space") + a = p.parse_args() + if a.action == "host-up": + host_up() + elif a.action == "shell": + subprocess.run(ssh_options(), check=True) + elif a.action == "wake": + wake() + elif a.action == "mirror-off": + guarded_mirror("off") + elif a.action == "exec": + if not a.command: + p.error("exec requires a command") + run_ssh(a.command) + elif a.action == "doctor": + run_ssh(["sh", "-c", "uname -r; ip -4 -br address show usb0; " + "if command -v systemctl >/dev/null; then systemctl --failed --no-pager; " + "systemctl is-active sshd systemd-networkd; fi"]) + elif a.action == "screenshot": + screenshot(a.path) + else: + with screen() as client: + if a.action == "tap": + client.tap(a.x, a.y) + elif a.action == "type": + client.type(a.text) + else: + named = {"return": 0xff0d, "enter": 0xff0d, "tab": 0xff09, "escape": 0xff1b, + "esc": 0xff1b, "backspace": 0xff08, "space": 0x20, "ctrl": 0xffe3, + "alt": 0xffe9, "shift": 0xffe1, "super": 0xffeb, "left": 0xff51, + "up": 0xff52, "right": 0xff53, "down": 0xff54} + symbols = [] + for name in a.combination.split("+"): + value = named.get(name.lower(), ord(name) if len(name) == 1 else None) + if value is None: + p.error(f"Unknown key {name}") + symbols.append(value) + for value in symbols: + client.key(value, True) + for value in reversed(symbols): + client.key(value, False) + # Allow the SSH tunnel to forward the final input before closing. + time.sleep(0.2) + + +if __name__ == "__main__": + try: + main() + except (ConnectionError, OSError, subprocess.CalledProcessError, ValueError) as e: + sys.exit(str(e)) diff --git a/tools/alioth/prepare-overlay.py b/tools/alioth/prepare-overlay.py new file mode 100644 index 000000000..8cf377d62 --- /dev/null +++ b/tools/alioth/prepare-overlay.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Prepare local-only F3 firmware/ALSA inputs. Never download or touch a phone.""" +import json +from pathlib import Path +import shutil +import tarfile + +ROOT = Path(__file__).resolve().parents[2] +OUT = ROOT / "out/alioth" + + +def main(): + reference = OUT / "reference" + overlay = OUT / "root-overlay" + # Rebuild our staging tree, including firmware alias symlinks, from the + # immutable reference. copytree cannot overwrite an existing symlink. + if overlay.exists(): + shutil.rmtree(overlay) + overlay.mkdir(exist_ok=True) + firmware = overlay / "usr/lib/firmware" + shutil.copytree(reference / "firmware/firmware", firmware, dirs_exist_ok=True, symlinks=True) + ucm = overlay / "usr/share/alsa/ucm2" + shutil.copytree(reference / "ucm2/ucm2/Xiaomi/alioth", ucm / "Xiaomi/alioth", dirs_exist_ok=True) + (ucm / "conf.d/sm8250").mkdir(parents=True, exist_ok=True) + link = ucm / "conf.d/sm8250/xiaomi-alioth.conf" + if not link.exists() and not link.is_symlink(): + link.symlink_to("../../Xiaomi/alioth/alioth.conf") + (overlay / "etc").mkdir(exist_ok=True) + (overlay / "etc/fstab").write_text("# POCO F3 Omarchy: userdata only\nLABEL=omamobile-root / ext4 rw,noatime 0 1\n") + # The Pixel device package supplied this common pacman include. Keep the + # F3 image's local signed repository usable without installing that package. + mirror = overlay / "etc/pacman.d/omamobile-mirrorlist" + mirror.parent.mkdir(parents=True, exist_ok=True) + mirror.write_text("# Local signed Omarchy Mobile packages\nServer = file:///var/lib/omamobile/repo/$arch\n") + # No addresses, calibration dumps, accounts or credentials enter this overlay. + with tarfile.open(OUT / "root-overlay.tar", "w") as archive: + for path in sorted(overlay.rglob("*")): + info = archive.gettarinfo(str(path), arcname=str(path.relative_to(overlay))) + info.uid = info.gid = 0 + info.uname = info.gname = "root" + if path.is_file() and not path.is_symlink(): + with path.open("rb") as source: + archive.addfile(info, source) + else: + archive.addfile(info) + print("Prepared local F3 firmware and ALSA overlay", flush=True) + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/prepare-recovery-ramboot.py b/tools/alioth/prepare-recovery-ramboot.py new file mode 100644 index 000000000..caff80108 --- /dev/null +++ b/tools/alioth/prepare-recovery-ramboot.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Remove TWRP image padding offline, preserving every boot and AVB byte.""" +import hashlib +import argparse +import json +from pathlib import Path +import shutil +import struct +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +SOURCE = ROOT / "out/alioth/inputs/twrp-3.7.1_12-0-alioth.img" +EXPECTED = "bf5bf3300da28abbef0493829a35fcd703424c1255172f5613789a7e2cfed2e3" +SIZE = 96 * 1024 * 1024 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--image", type=Path, default=SOURCE) + args = parser.parse_args() + source = args.image.resolve() + original = source.read_bytes() + if hashlib.sha256(original).hexdigest() != EXPECTED: + raise SystemExit("Official recovery checksum mismatch; no image changed") + magic, major, minor, payload, offset, metadata, reserved = struct.unpack( + ">4sIIQQQ28s", original[-64:]) + if (magic != b"AVBf" or major != 1 or payload != 77209600 + or offset != payload or metadata != 704 or offset + metadata >= SIZE - 64): + raise SystemExit("Unexpected recovery AVB layout; no image changed") + target = source.with_name("twrp-3.7.1_12-0-alioth-ramboot-96MiB.img") + # avbtool expects a file named boot.img when verifying the boot descriptor. + with tempfile.TemporaryDirectory(dir=source.parent) as scratch: + candidate = Path(scratch) / "boot.img" + shutil.copyfile(source, candidate) + subprocess.run(["avbtool", "resize_image", "--image", str(candidate), + "--partition_size", str(SIZE)], check=True) + resized = candidate.read_bytes() + if (len(resized) != SIZE or resized[:payload] != original[:payload] + or resized[offset:offset + metadata] != original[offset:offset + metadata] + or resized[-64:] != original[-64:]): + raise SystemExit("Recovery contents changed; derived image rejected") + subprocess.run(["avbtool", "verify_image", "--image", str(candidate)], check=True) + candidate.replace(target) + receipt = { + "source": source.name, "source_sha256": EXPECTED, + "derived": target.name, "derived_bytes": SIZE, + "derived_sha256": hashlib.sha256(resized).hexdigest(), + "operation": "avbtool resize_image to 96 MiB; only padding removed; " + "original boot payload, vbmeta, footer byte-identical", + "original_payload_bytes": payload, "temporary_ram_boot_only": True, + } + target.with_suffix(".json").write_text(json.dumps(receipt, indent=2) + "\n") + print(f"Verified RAM-boot recovery: {target}") + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/prepare-reference.py b/tools/alioth/prepare-reference.py new file mode 100644 index 000000000..6a56775e8 --- /dev/null +++ b/tools/alioth/prepare-reference.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Extract the checksum-pinned F3 kernel and matching runtime files, offline.""" +import argparse +import gzip +import hashlib +import json +from pathlib import Path +import shutil +import struct +import subprocess +import zlib + +EXPECTED = "17901fd0f9a96284c42b93ad1c9093aaf9bf79db62d084d80ee72afb4b29bb84" +RELEASE = "6.15.1-sm8250" + + +def digest(path): + h = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b""): + h.update(chunk) + return h.hexdigest() + + +def cpio_files(data): + pos = 0 + while pos + 110 <= len(data): + header = data[pos:pos + 110] + if header[:6] not in (b"070701", b"070702"): + raise ValueError("invalid newc header") + fields = [int(header[6 + i * 8:14 + i * 8], 16) for i in range(13)] + size, namesize = fields[6], fields[11] + name = data[pos + 110:pos + 110 + namesize - 1].decode() + start = (pos + 110 + namesize + 3) & ~3 + if name == "TRAILER!!!": + return + yield name.removeprefix("./"), fields[1], data[start:start + size] + pos = (start + size + 3) & ~3 + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--inputs", type=Path, required=True) + p.add_argument("--out", type=Path, required=True) + args = p.parse_args() + archive = args.inputs / "xiaomi-alioth-2026-09-28.zip" + if digest(archive) != EXPECTED: + raise SystemExit("Reference archive checksum mismatch") + out = args.out.resolve() + (out / "include/config").mkdir(parents=True, exist_ok=True) + (out / "include/config/kernel.release").write_text(RELEASE + "\n") + marker = out / "REFERENCE.json" + if marker.exists(): + old = json.loads(marker.read_text()) + if old.get("source_sha256") == EXPECTED and all( + digest(out / f) == s for f, s in old["boot_sha256"].items() + ): + print("Pinned reference already prepared", flush=True) + return + raise SystemExit("Existing reference outputs differ; use a fresh output directory") + out.mkdir(parents=True, exist_ok=True) + source = args.inputs / "linux-reference" + boot = (source / "boot-xiaomi-alioth.img").read_bytes() + if boot[:8] != b"ANDROID!": + raise SystemExit("No Android boot header") + fields = struct.unpack_from("<10I", boot, 8) + kernel_size, ramdisk_size, page, version = fields[0], fields[2], fields[7], fields[8] + if page != 4096 or version != 0: + raise SystemExit("Unexpected reference boot format") + kernel = boot[page:page + kernel_size] + z = zlib.decompressobj(31) + image = z.decompress(kernel) + z.flush() + tail = z.unused_data + if image[56:60] != b"ARM\x64" or tail[:4] != bytes.fromhex("d00dfeed"): + raise SystemExit("Expected an ARM64 gzip Image with appended DTB") + if b"Linux version " + RELEASE.encode() + b" " not in image: + raise SystemExit("Unexpected kernel release") + if b"xiaomi,alioth\0" not in tail or b"qcom,sm8250\0" not in tail: + raise SystemExit("Reference DTB is not alioth/SM8250") + (out / "Image.gz-dtb").write_bytes(kernel) + (out / "alioth.dtb").write_bytes(tail[:struct.unpack_from(">I", tail, 4)[0]]) + start = image.index(b"IKCFG_ST") + 8 + end = image.index(b"IKCFG_ED", start) + config = gzip.decompress(image[start:end]) + (out / "kernel.config").write_bytes(config) + for option in ("USB_CONFIGFS_NCM", "USB_CONFIGFS_ACM", "USB_DWC3_QCOM", + "SCSI_UFS_QCOM", "EXT4_FS", "DEVTMPFS", "TYPEC_QCOM_PMIC"): + if f"CONFIG_{option}=y\n".encode() not in config: + raise SystemExit(f"Early-boot prerequisite is not built in: {option}") + ramdisk_offset = ((page + kernel_size + page - 1) // page) * page + ramdisk = gzip.decompress(boot[ramdisk_offset:ramdisk_offset + ramdisk_size]) + fw = out / "boot-firmware" + for name, mode, data in cpio_files(ramdisk): + if not name.startswith("usr/lib/firmware/"): + continue + relative = Path(name).relative_to("usr/lib/firmware") + if relative.is_absolute() or ".." in relative.parts: + raise SystemExit("Unsafe firmware archive path") + dest = fw / relative + if mode & 0o170000 == 0o040000: + dest.mkdir(parents=True, exist_ok=True) + elif mode & 0o170000 == 0o100000: + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + elif mode & 0o170000 == 0o120000: + raise SystemExit("Unexpected firmware symlink; inspect before importing") + raw = out / "reference.raw" + ext4 = out / "reference-root.ext4" + subprocess.run(["simg2img", str(source / "rootfs-xiaomi-alioth.img"), str(raw)], check=True) + with raw.open("rb") as src: + src.seek(4096) + header = src.read(4096) + if header[:8] != b"EFI PART": + raise SystemExit("No GPT at 4096-byte sector boundary") + table, count, entrysize = struct.unpack_from(" 256 or entrysize != 128: + raise SystemExit("Unexpected GPT layout") + src.seek(table * 4096) + entries = src.read(count * entrysize) + root = entries[entrysize:2 * entrysize] + start, end = struct.unpack_from("I", read_exact(stream, 4))[0]: + raise ConnectionError("VNC authentication failed") + stream.sendall(b"\x01") # shared session + header = read_exact(stream, 24) + self.width, self.height = struct.unpack_from(">HH", header) + length = struct.unpack_from(">I", header, 20)[0] + if length > 65536 or not (0 < self.width <= 8192 and 0 < self.height <= 8192): + raise ValueError("Unexpected framebuffer dimensions or name") + read_exact(stream, length) + # Request native little-endian 32-bit BGRX and only raw pixels. + fmt = struct.pack(">BBBBHHHBBB3x", 32, 24, 0, 1, 255, 255, 255, 16, 8, 0) + stream.sendall(b"\x00\x00\x00\x00" + fmt) + stream.sendall(struct.pack(">BBHii", 2, 0, 2, 0, -223)) + + def pointer(self, x, y, mask=0): + if not (0 <= x < self.width and 0 <= y < self.height and 0 <= mask <= 255): + raise ValueError("Pointer coordinate outside the phone screen") + self.s.sendall(struct.pack(">BBHH", 5, mask, x, y)) + + def tap(self, x, y): + self.pointer(x, y, 1) + self.pointer(x, y, 0) + + def key(self, keysym, down): + self.s.sendall(struct.pack(">BBHI", 4, bool(down), 0, keysym)) + + def type(self, text): + for character in text: + code = ord(character) + symbol = code if code <= 255 else 0x01000000 | code + self.key(symbol, True) + self.key(symbol, False) + + def screenshot(self): + self.s.sendall(struct.pack(">BBHHHH", 3, 0, 0, 0, self.width, self.height)) + pixels = bytearray(self.width * self.height * 3) + while True: + message = read_exact(self.s, 1)[0] + if message == 2: # bell + continue + if message == 3: # clipboard + length = struct.unpack(">3xI", read_exact(self.s, 7))[0] + if length > 16 * 1024 * 1024: + raise ValueError("Unexpected clipboard length") + read_exact(self.s, length) + continue + if message != 0: + raise ValueError(f"Unsupported VNC server message {message}") + count = struct.unpack(">xH", read_exact(self.s, 3))[0] + painted = False + for _ in range(count): + x, y, width, height, encoding = struct.unpack(">HHHHi", read_exact(self.s, 12)) + if encoding == -223: + if not (0 < width <= 8192 and 0 < height <= 8192): + raise ValueError("Unexpected resized framebuffer") + self.width, self.height = width, height + pixels = bytearray(width * height * 3) + continue + if encoding != 0 or x + width > self.width or y + height > self.height: + raise ValueError("Unexpected framebuffer rectangle") + raw = read_exact(self.s, width * height * 4) + painted = True + rgb = bytearray(width * height * 3) + rgb[0::3], rgb[1::3], rgb[2::3] = raw[2::4], raw[1::4], raw[0::4] + for row in range(height): + target = ((y + row) * self.width + x) * 3 + source = row * width * 3 + pixels[target:target + width * 3] = rgb[source:source + width * 3] + if painted: + return png(self.width, self.height, pixels) + self.s.sendall(struct.pack(">BBHHHH", 3, 0, 0, 0, self.width, self.height)) + + +def png(width, height, pixels): + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + rows = b"".join(b"\0" + pixels[y * width * 3:(y + 1) * width * 3] for y in range(height)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows, 3)) + chunk(b"IEND", b"")) diff --git a/tools/alioth/smoke-userspace.sh b/tools/alioth/smoke-userspace.sh new file mode 100755 index 000000000..eb5b8e131 --- /dev/null +++ b/tools/alioth/smoke-userspace.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Read-only local-image smoke, under ARM emulation. Never connects to the phone. +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." +root=$PWD +image=$(readlink -f "${1:-out/alioth/images/rootfs.img}") +source tools/lib/alarm.sh +alarm_fetch +builder=$(alarm_build_image "$root") +[[ -f $image ]] || { echo 'Personalized root image missing' >&2; exit 1; } +docker run --rm -i --privileged --network none --platform linux/arm64 \ + -v "$image:/input.img:ro" \ + "$builder" bash -s <<'INNER' +set -euo pipefail +mkdir -p /image-root +# Create device nodes only in this disposable container's /dev. The loop is +# allocated from the kernel's free list and bound read-only to our local file. +[[ -e /dev/loop-control ]] || mknod /dev/loop-control c 10 237 +number=$(python - <<'PY' +import fcntl, os +fd = os.open('/dev/loop-control', os.O_RDWR) +try: + print(fcntl.ioctl(fd, 0x4c82)) +finally: + os.close(fd) +PY +) +loop=/dev/loop$number +[[ -e $loop ]] || mknod "$loop" b 7 "$number" +losetup --read-only "$loop" /input.img +cleanup() { + umount -R /image-root 2>/dev/null || true + losetup -d "$loop" +} +trap cleanup EXIT +mount -t ext4 -o ro,noload "$loop" /image-root +mount -t tmpfs tmpfs /image-root/run +mount -t proc proc /image-root/proc +mount -t tmpfs tmpfs /image-root/dev +for spec in "null 1 3" "random 1 8" "urandom 1 9"; do + read -r name major minor <<<"$spec" + mknod -m 666 "/image-root/dev/$name" c "$major" "$minor" +done +ln -s /proc/self/fd /image-root/dev/fd +mkdir -p /image-root/run/alioth-check /image-root/run/sshd +chmod 700 /image-root/run/alioth-check +run() { chroot /image-root /usr/bin/env XDG_RUNTIME_DIR=/run/alioth-check "$@"; } +run /usr/bin/omamobile-firstboot --check +echo 'ok - firstboot parses the actual personalized image' +run /usr/lib/systemd/systemd --version | head -2 +run /usr/bin/Hyprland --version +run /usr/bin/env QT_QPA_PLATFORM=offscreen XDG_RUNTIME_DIR=/run/alioth-check /usr/bin/quickshell --version +for binary in /usr/bin/Hyprland /usr/bin/quickshell /usr/bin/wayvnc /usr/bin/omacam /usr/bin/squeekboard; do + deps=$(run /usr/bin/ldd "$binary") + [[ $deps != *'not found'* ]] || { printf '%s\n' "$deps"; exit 1; } + echo "ok - ARM shared libraries resolve: $binary" +done +run /usr/bin/ssh-keygen -q -t ed25519 -N '' -f /run/alioth-check/host-key +run /usr/bin/sshd -t -h /run/alioth-check/host-key +echo 'ok - actual OpenSSH configuration validates' +# QEMU user emulation cannot install OpenSSH's seccomp filter. Do not +# disable its sandbox or claim this configuration check proves a real login. +echo 'ok - OpenSSH configuration checked; full sandboxed login needs a real ARM kernel' +echo 'ok - all writes stayed in container tmpfs; image was mounted read-only without journal replay' +INNER diff --git a/tools/alioth/test-build-isolation.py b/tools/alioth/test-build-isolation.py new file mode 100644 index 000000000..f227c5ebd --- /dev/null +++ b/tools/alioth/test-build-isolation.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Prove owner builds cannot replace the maintainer signing/release outputs.""" +import contextlib +import importlib.util +import io +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] + +with tempfile.TemporaryDirectory(prefix='alioth-isolation-') as directory: + project = Path(directory) / 'checkout with spaces' + tools = project / 'tools/alioth' + tools.mkdir(parents=True) + for name in ('init-keys.py', 'build.py'): + shutil.copyfile(ROOT / 'tools/alioth' / name, tools / name) + sentinels = { + 'keys/fingerprint': b'maintainer fingerprint\n', + 'keys/gnupg/keep': b'maintainer secret key placeholder', + 'out/repo/aarch64/omamobile.db': b'maintainer package database', + 'out/omamobile-rootfs-release-aarch64.img': b'Pixel root image', + } + for name, data in sentinels.items(): + path = project / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + subprocess.run([sys.executable, str(tools / 'init-keys.py')], check=True, stdout=subprocess.DEVNULL) + assert (project / 'keys/alioth/fingerprint').is_file() + assert (project / 'keys/alioth/gnupg').is_dir() + assert (project / 'keys/alioth/alioth_ed25519').stat().st_mode & 0o777 == 0o600 + profile = project / 'rootfs' + profile.mkdir() + shutil.copyfile(ROOT / 'rootfs/packages.omamobile-alioth', profile / 'packages.omamobile-alioth') + spec = importlib.util.spec_from_file_location('build', tools / 'build.py') + build = importlib.util.module_from_spec(spec) + spec.loader.exec_module(build) + calls = [] + def run(command, *, env, check): + calls.append((command, env.copy())) + assert env['OMAMOBILE_REPO_DIR'] == str(project / 'out/alioth/repo') + assert env['OMAMOBILE_ROOTFS_OUT'] == str(project / 'out/alioth') + assert env['OMAMOBILE_SIGNING_DIR'] == str(project / 'keys/alioth') + assert env['OMAMOBILE_KEYRING_DIR'] == str(project / 'keys/alioth/build-keyring') + cwd = Path.cwd() + old_mask = os.umask(0o077) + try: + with patch.object(sys, 'argv', ['build.py', '--username', 'mobile']), \ + patch.object(build.subprocess, 'run', side_effect=run), contextlib.redirect_stdout(io.StringIO()): + build.main() + finally: + os.chdir(cwd) + os.umask(old_mask) + command = next(c for c, _ in calls if 'tools/alioth/provision-image.py' in c) + assert command[command.index('--root-image') + 1].startswith('out/alioth/') + assert any(c[0] == 'tools/build-packages' for c, _ in calls) + assert any(c[0] == 'tools/build-rootfs' for c, _ in calls) + for name, data in sentinels.items(): + assert (project / name).read_bytes() == data, 'maintainer file changed: ' + name + # Stop gpg-agent before deleting its temporary homedir. + subprocess.run(['gpgconf', '--homedir', str(project / 'keys/alioth/gnupg'), '--kill', 'gpg-agent'], check=True) +print('ok - actual F3 key generation preserves maintainer keys; build commands isolate repository and root output') diff --git a/tools/alioth/test-client-guard.py b/tools/alioth/test-client-guard.py new file mode 100644 index 000000000..d8bb57e11 --- /dev/null +++ b/tools/alioth/test-client-guard.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Check mirroring leaves its timed stop armed on a broken SSH path.""" +import importlib.util +from pathlib import Path +import subprocess +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).parent)) +spec = importlib.util.spec_from_file_location("client", Path(__file__).with_name("phone-client.py")) +client = importlib.util.module_from_spec(spec) +spec.loader.exec_module(client) + + +class MirrorGuard(unittest.TestCase): + def test_success_cancels_only_after_fresh_ssh(self): + with patch.object(client, "run_ssh") as ssh: + client.guarded_mirror("on") + commands = [call.args[0] for call in ssh.call_args_list] + self.assertEqual(commands[0][0], "systemd-run") + self.assertIn("--on-active=90", commands[0]) + self.assertEqual(commands[0][-2:], ["/usr/bin/omamobile-mirror", "off"]) + self.assertEqual(commands[1:3], [["omamobile-mirror", "on"], ["true"]]) + self.assertEqual(commands[3][:2], ["systemctl", "stop"]) + self.assertEqual(commands[3][2], commands[0][1].removeprefix("--unit=") + ".timer") + + def test_mirror_failure_keeps_timer(self): + failure = subprocess.CalledProcessError(1, "synthetic SSH failure") + with patch.object(client, "run_ssh", side_effect=[None, failure]) as ssh: + with self.assertRaises(subprocess.CalledProcessError): + client.guarded_mirror("on") + self.assertEqual(ssh.call_count, 2) + + def test_fresh_ssh_failure_keeps_timer(self): + failure = subprocess.CalledProcessError(1, "synthetic SSH failure") + with patch.object(client, "run_ssh", side_effect=[None, None, failure]) as ssh: + with self.assertRaises(subprocess.CalledProcessError): + client.guarded_mirror("off") + self.assertEqual(ssh.call_count, 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/alioth/test-initramfs-ssh.sh b/tools/alioth/test-initramfs-ssh.sh new file mode 100755 index 000000000..536930722 --- /dev/null +++ b/tools/alioth/test-initramfs-ssh.sh @@ -0,0 +1,35 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Exercise the packed ARM Dropbear and public key in a disposable container. +# Does not run /init or expose any phone/block-device mounts to the container. +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." +root=$PWD +image_out=$(realpath "${1:-out/alioth}") +name=omamobile-alioth-ssh-check-$$ +cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; } +trap cleanup EXIT +docker run --detach --name "$name" --platform linux/arm64 \ + -p 127.0.0.1::2222 --tmpfs /testroot:rw,exec \ + -v "$image_out/initramfs.cpio.gz:/initramfs.cpio.gz:ro" \ + alpine@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 \ + sh -c 'set -eu; cd /testroot; zcat /initramfs.cpio.gz | cpio -idm --quiet; + chroot /testroot /bin/busybox sh -n /init; + test -e dev/null || mknod -m 666 dev/null c 1 3; + test -e dev/urandom || mknod -m 666 dev/urandom c 1 9; + exec chroot /testroot /usr/sbin/dropbear -F -R -E -s -p 2222' >/dev/null +port=$(docker port "$name" 2222/tcp) +port=${port##*:} +passed=0 +for attempt in $(seq 1 20); do + if ssh -F /dev/null -i "$root/keys/alioth/alioth_ed25519" -p "$port" \ + -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no \ + -o UserKnownHostsFile=/dev/null -o ConnectTimeout=2 -o LogLevel=ERROR \ + root@127.0.0.1 /bin/busybox true 2>/dev/null; then + passed=1; break + fi + sleep 1 +done +if ((!passed)); then docker logs "$name"; exit 1; fi +echo 'ok - packed ARM Dropbear accepts the dedicated key and executes ARM userspace' +echo 'ok - password authentication disabled; no init, storage guard or phone command executed' diff --git a/tools/alioth/test-install.py b/tools/alioth/test-install.py new file mode 100644 index 000000000..711f6a4b6 --- /dev/null +++ b/tools/alioth/test-install.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise destructive-install gates with local fixtures; never call fastboot.""" +import importlib.util +import contextlib +import io +import json +from pathlib import Path +import struct +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).parent)) +spec = importlib.util.spec_from_file_location("installer", Path(__file__).with_name("install.py")) +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) + + +class InstallGates(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + for name in ("boot.img", "boot-rescue.img"): + (self.root / name).write_bytes(name.encode()) + (self.root / "rootfs-sparse.img").write_bytes( + struct.pack("", "boot"]) + + def test_full_plan_only_writes_allowed_targets(self): + commands = installer.plan(self.root) + self.assertEqual([command[command.index("flash") + 1] for command in commands if "flash" in command], + ["userdata", "boot_b"]) + self.assertEqual([command[command.index("erase") + 1] for command in commands if "erase" in command], ["dtbo_b"]) + self.assertEqual(installer.verify_images(self.root), (self.boot, self.fs)) + + def proof(self, **changes): + receipt = dict(device="alioth", kernel_release="6.15.1-sm8250", + read_only_capture=True, rescue_boot=True, userdata_unmounted=True, + storage_guard_passed=True, captured_at=installer.time.time(), + serial_sha256=installer.hashlib.sha256(b"synthetic-phone").hexdigest(), + rootfs_bytes=self.fs["rootfs_bytes"], rootfs_sha256=self.fs["rootfs_sha256"]) + receipt.update(changes) + self.write("proof.json", receipt) + return self.root / "proof.json" + + def test_finish_requires_matching_readback(self): + installer.verify_device_root(self.proof(), self.fs, "synthetic-phone") + with self.assertRaisesRegex(ValueError, "differs from the prepared image"): + installer.verify_device_root(self.proof(rootfs_sha256="changed"), self.fs, "synthetic-phone") + + def test_finish_rejects_wrong_phone(self): + with self.assertRaisesRegex(ValueError, "different phone"): + installer.verify_device_root(self.proof(), self.fs, "other-phone") + + def test_finish_rejects_stale_readback(self): + with self.assertRaisesRegex(ValueError, "stale"): + installer.verify_device_root(self.proof(captured_at=installer.time.time() - 1801), self.fs, "synthetic-phone") + + def test_finish_rejects_mounted_root(self): + with self.assertRaisesRegex(ValueError, "unmounted"): + installer.verify_device_root(self.proof(userdata_unmounted=False), self.fs, "synthetic-phone") + + def test_finish_never_reflashes_userdata(self): + commands = installer.plan(self.root, finish_boot=True) + self.assertFalse(any("userdata" in command for command in commands)) + self.assertEqual([c[c.index("flash") + 1] for c in commands if "flash" in c], ["boot_b"]) + self.assertEqual([c[c.index("erase") + 1] for c in commands if "erase" in c], ["dtbo_b"]) + + def test_dry_run_never_queries_or_mutates_phone(self): + argv = ['install.py', '--images', str(self.root), '--flash', '--dry-run'] + with patch.object(sys, 'argv', argv), patch.object(installer, 'getvar') as getvar, \ + patch.object(installer.subprocess, 'run') as run, contextlib.redirect_stdout(io.StringIO()): + installer.main() + getvar.assert_not_called() + run.assert_not_called() + + def test_missing_wipe_confirmation_stops_before_phone_access(self): + argv = ['install.py', '--images', str(self.root), '--flash', '--backups', 'unused.json'] + with patch.object(sys, 'argv', argv), patch.object(installer, 'getvar') as getvar, \ + patch.object(installer.subprocess, 'run') as run, contextlib.redirect_stdout(io.StringIO()): + with self.assertRaisesRegex(SystemExit, 'userdata-loss confirmation'): + installer.main() + getvar.assert_not_called() + run.assert_not_called() + + def test_wrong_product_or_slot_never_reaches_writes(self): + argv = ['install.py', '--images', str(self.root), '--flash', + '--confirm-erase-userdata', '--backups', 'unused.json'] + for values in ({'product': 'other'}, {'product': 'alioth', 'unlocked': 'yes', 'current-slot': 'b'}): + with patch.object(sys, 'argv', argv), patch.object(installer, 'verify_recovery'), \ + patch.object(installer, 'getvar', side_effect=lambda key, serial=None: 'synthetic-phone' if key == 'serialno' else values[key]), \ + patch.object(installer.subprocess, 'run') as run, contextlib.redirect_stdout(io.StringIO()): + with self.assertRaises(SystemExit): + installer.main() + run.assert_not_called() + + def test_device_selection_pinned_after_single_serial_read(self): + self.boot['boot_bytes'] = 4096 + self.write('BOOT-MANIFEST.json', self.boot) + argv = ['install.py', '--images', str(self.root), '--flash', + '--confirm-erase-userdata', '--backups', 'unused.json'] + calls = [] + def fastboot(command, **kwargs): + calls.append(command) + if 'getvar' in command: + name = command[-1] + if name == 'serialno': + self.assertEqual(command, ['fastboot', 'getvar', 'serialno']) + value = 'synthetic-phone' + else: + self.assertEqual(command[:3], ['fastboot', '-s', 'synthetic-phone']) + value = {'product': 'alioth', 'unlocked': 'yes', 'current-slot': 'a'}.get(name, '0x100000') + return installer.subprocess.CompletedProcess(command, 0, '', name + ': ' + value) + self.assertEqual(command[:3], ['fastboot', '-s', 'synthetic-phone']) + return installer.subprocess.CompletedProcess(command, 0) + with patch.object(sys, 'argv', argv), patch.object(installer, 'verify_recovery'), \ + patch.object(installer, 'verify_backups'), patch.object(installer.subprocess, 'run', side_effect=fastboot), \ + contextlib.redirect_stdout(io.StringIO()): + installer.main() + self.assertEqual(sum(c[-2:] == ['getvar', 'serialno'] for c in calls), 1) + self.assertTrue(any('flash' in c for c in calls)) + + def test_probe_discloses_persistent_changes_without_phone_access(self): + argv = ['install.py', '--images', str(self.root), '--probe'] + output = io.StringIO() + with patch.object(sys, 'argv', argv), patch.object(installer.subprocess, 'run') as run, \ + contextlib.redirect_stdout(output): + installer.main() + run.assert_not_called() + self.assertIn('erases dtbo_b and leaves slot B active', output.getvalue()) + + def test_unpinned_recovery_rejected(self): + image = self.root / 'recovery.img'; image.write_bytes(b'unknown image') + with self.assertRaisesRegex(ValueError, 'integrity check failed'): + installer.verify_recovery(image) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/alioth/test-provision.py b/tools/alioth/test-provision.py new file mode 100644 index 000000000..299f8dd1f --- /dev/null +++ b/tools/alioth/test-provision.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Provision a tiny ext4 fixture in a path containing spaces; no phone access.""" +from pathlib import Path +import os +import pwd +import shutil +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +TOOLS = ['mke2fs', 'debugfs', 'e2fsck', 'img2simg', 'openssl', 'ssh-keygen'] +missing = [name for name in TOOLS if not shutil.which(name)] +if missing: + print('ok - owner-image fixture # SKIP missing: ' + ', '.join(missing)) + raise SystemExit(0) + + +def run(command, **kwargs): + return subprocess.run(command, capture_output=True, **kwargs) + + +with tempfile.TemporaryDirectory(prefix='alioth-provision-') as directory: + project = Path(directory) / 'checkout with spaces' + tools = project / 'tools/alioth'; tools.mkdir(parents=True) + shutil.copyfile(ROOT / 'tools/alioth/provision-image.py', tools / 'provision-image.py') + checker = project / 'packages/omamobile-firstboot/bin'; checker.mkdir(parents=True) + shutil.copyfile(ROOT / 'packages/omamobile-firstboot/bin/omamobile-firstboot', checker / 'omamobile-firstboot') + private = project / 'keys/alioth'; private.mkdir(mode=0o700, parents=True) + result = run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-f', str(private / 'alioth_ed25519')]) + assert result.returncode == 0, 'Fixture SSH key generation failed' + tree = project / 'fixture-root' + (tree / 'etc/omamobile').mkdir(parents=True); (tree / 'root').mkdir() + (tree / 'etc/passwd').write_text('root:x:0:0:root:/root:/bin/bash\n') + image = project / 'generic.img' + result = run(['mke2fs', '-q', '-t', 'ext4', '-L', 'omamobile-root', '-d', str(tree), str(image), '32M']) + assert result.returncode == 0, 'Fixture ext4 creation failed' + command = ['python3', str(tools / 'provision-image.py'), '--root-image', str(image), '--timezone', 'UTC'] + result = run(command + ['--username', 'root']) + assert result.returncode != 0, 'Reserved account accepted' + assert not (private / 'alioth-credentials.json').exists(), 'Invalid owner settings persisted' + assert not (project / 'out/alioth/images/rootfs.img').exists(), 'Invalid owner changed image' + # When possible, exercise the build host's existing account name: it must + # be validated against the target passwd, not against the host's users. + username = pwd.getpwuid(os.getuid()).pw_name if os.getuid() >= 1000 else 'mobile' + result = run(command + ['--username', username]) + assert result.returncode == 0, 'Valid owner provisioning failed' + assert (private / 'alioth-credentials.json').stat().st_mode & 0o777 == 0o600 + assert (project / 'out/alioth/images/rootfs.img').stat().st_mode & 0o777 == 0o600 + assert (project / 'out/alioth/images/rootfs-sparse.img').is_file() +print('ok - real ext4 provisioning supports spaces, validates target accounts, and keeps credentials private') diff --git a/tools/alioth/test-rfb.py b/tools/alioth/test-rfb.py new file mode 100644 index 000000000..5a05939b2 --- /dev/null +++ b/tools/alioth/test-rfb.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise the real RFB wire protocol against a local socket server.""" +import socket +import struct +import threading +import unittest +import zlib +from rfb import RFB, read_exact + + +class ProtocolTest(unittest.TestCase): + def session(self, server): + left, right = socket.socketpair() + left.settimeout(3) + right.settimeout(3) + errors = [] + + def serve(): + try: + with right: + right.sendall(b"RFB 003.008\n") + self.assertEqual(read_exact(right, 12), b"RFB 003.008\n") + right.sendall(b"\x01\x01") + self.assertEqual(read_exact(right, 1), b"\x01") + right.sendall(b"\0\0\0\0") + self.assertEqual(read_exact(right, 1), b"\x01") + right.sendall(struct.pack(">HH", 2, 2) + b"\0" * 16 + struct.pack(">I", 4) + b"test") + self.assertEqual(read_exact(right, 20)[:4], b"\0\0\0\0") + self.assertEqual(read_exact(right, 12), struct.pack(">BBHii", 2, 0, 2, 0, -223)) + server(right) + except BaseException as error: + errors.append(error) + thread = threading.Thread(target=serve) + thread.start() + return left, thread, errors + + def test_capture_real_pixels_and_png(self): + def server(stream): + self.assertEqual(read_exact(stream, 10), struct.pack(">BBHHHH", 3, 0, 0, 0, 2, 2)) + # Red, green, blue, white, encoded as requested little-endian BGRX. + stream.sendall(b"\0\0\0\1" + struct.pack(">HHHHi", 0, 0, 2, 2, 0) + + bytes.fromhex("0000ff0000ff0000ff000000ffffff00")) + stream, thread, errors = self.session(server) + with stream: + image = RFB(stream).screenshot() + thread.join(3) + self.assertFalse(errors, errors) + self.assertTrue(image.startswith(b"\x89PNG\r\n\x1a\n")) + self.assertEqual(struct.unpack_from(">II", image, 16), (2, 2)) + pos, pixels = 8, b"" + while pos < len(image): + size = struct.unpack_from(">I", image, pos)[0] + if image[pos + 4:pos + 8] == b"IDAT": + pixels += image[pos + 8:pos + 8 + size] + pos += size + 12 + self.assertEqual(zlib.decompress(pixels), bytes.fromhex("00ff000000ff00000000ffffffff")) + + def test_pointer_and_unicode_keyboard(self): + def server(stream): + self.assertEqual(read_exact(stream, 6), struct.pack(">BBHH", 5, 1, 1, 0)) + self.assertEqual(read_exact(stream, 6), struct.pack(">BBHH", 5, 0, 1, 0)) + self.assertEqual(read_exact(stream, 8), struct.pack(">BBHI", 4, 1, 0, 0x010003bb)) + self.assertEqual(read_exact(stream, 8), struct.pack(">BBHI", 4, 0, 0, 0x010003bb)) + stream, thread, errors = self.session(server) + with stream: + client = RFB(stream) + with self.assertRaises(ValueError): + client.tap(2, 0) + client.tap(1, 0) + client.type("λ") + thread.join(3) + self.assertFalse(errors, errors) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/alioth/test-storageguard.py b/tools/alioth/test-storageguard.py new file mode 100644 index 000000000..98d2a4c12 --- /dev/null +++ b/tools/alioth/test-storageguard.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise the boot function against scratch sysfs and blocked write commands.""" +import os +from pathlib import Path +import subprocess +import shutil +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class RootGuard(unittest.TestCase): + def exercise(self, label, real=False): + source = (ROOT / "initramfs/init").read_text() + start = source.index("boot_arch() {") + end = source.index("\nboot_arch\n", start) + function = source[start:end] + with tempfile.TemporaryDirectory() as directory: + base = Path(directory) + sys = base / "sys/block/sda/sda35" + sys.mkdir(parents=True) + (sys / "uevent").write_text("PARTNAME=userdata\n") + (sys / "ro").write_text("0\n") + (base / "cmdline").write_text("") + function = function.replace("/sys/block/sda", str(base / "sys/block/sda")) + function = function.replace("/proc/cmdline", str(base / "cmdline")) + function = function.replace("/newroot", str(base / "newroot")) + if real: + image = base / "root.img" + with image.open("wb") as output: + output.truncate(16 * 1024 * 1024) + subprocess.run(["mke2fs", "-q", "-t", "ext4", "-L", label, str(image)], check=True) + # Busybox ignores util-linux's label/output selectors. Retain + # the actual full-line behaviour as the regression trigger. + output = subprocess.check_output(["busybox", "blkid", "-s", "LABEL", "-o", "value", str(image)], text=True) + if label: + self.assertIn('LABEL="' + label + '"', output) + self.assertNotEqual(output.strip(), label) + function = function.replace('dumpe2fs -h "$dev"', 'dumpe2fs -h "' + str(image) + '"') + # Never invoke a block operation, mount, process kill or switch_root. + script = ''' +say() { :; } +blkid() { echo forbidden-blkid >> "$MARKER"; return 99; } +dumpe2fs() { printf 'Filesystem volume name: %s\\n' "$LABEL"; } +e2fsck() { echo repair >> "$MARKER"; } +grow_root() { echo grow >> "$MARKER"; } +mount() { echo mount >> "$MARKER"; return 1; } +kill() { echo forbidden-kill >> "$MARKER"; return 99; } +switch_root() { echo forbidden-switch >> "$MARKER"; return 99; } +''' + function + '\nboot_arch\n' + if real: + script = '\n'.join(line for line in script.splitlines() if not line.startswith('dumpe2fs()')) + env = os.environ.copy() + env.update(LABEL=label, MARKER=str(base / "writes")) + result = subprocess.run((["busybox", "sh", "-c", script] if real else ["bash", "-c", script]), env=env, capture_output=True, text=True) + marker = base / "writes" + return result.returncode, marker.read_text() if marker.exists() else "" + + def test_existing_android_is_never_repaired_or_mounted(self): + for label in ("", "userdata", "android", "anything-else"): + status, writes = self.exercise(label) + self.assertEqual(status, 1) + self.assertEqual(writes, "", label) + + def test_only_explicit_omarchy_root_reaches_write_steps(self): + status, writes = self.exercise("omamobile-root") + self.assertEqual(status, 1) # the fake mount deliberately refuses + self.assertEqual(writes.splitlines(), ["repair", "grow", "mount"]) + + @unittest.skipUnless(all(shutil.which(t) for t in ('busybox', 'mke2fs', 'dumpe2fs')), 'real Busybox/e2fsprogs required') + def test_real_busybox_and_ext4_labels(self): + for label in ('omamobile-root', 'userdata', ''): + status, writes = self.exercise(label, real=True) + self.assertEqual(status, 1) + self.assertEqual(writes.splitlines(), ['repair', 'grow', 'mount'] if label == 'omamobile-root' else []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/alioth/verify-device-root.py b/tools/alioth/verify-device-root.py new file mode 100644 index 000000000..055e4032f --- /dev/null +++ b/tools/alioth/verify-device-root.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Read back the complete flashed root from rescue, before mounting it.""" +import argparse +import hashlib +import importlib.util +import json +from pathlib import Path +import re +import shlex +import subprocess +import time + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location("phone_client", Path(__file__).with_name("phone-client.py")) +client = importlib.util.module_from_spec(spec) +spec.loader.exec_module(client) +SSH_OPTIONS = None + + +def remote(script, timeout=30): + global SSH_OPTIONS + if SSH_OPTIONS is None: + SSH_OPTIONS = client.ssh_options() + return subprocess.check_output(SSH_OPTIONS + [shlex.join(["sh", "-c", script])], + text=True, timeout=timeout).strip() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--backups", type=Path, required=True) + args = parser.parse_args() + target = ROOT / "keys/alioth/alioth-userdata-verified.json" + target.unlink(missing_ok=True) + backup = json.loads(args.backups.read_text()) + root = json.loads((ROOT / "out/alioth/images/ROOT-MANIFEST.json").read_text()) + release = remote("uname -r") + if release != "6.15.1-sm8250": + raise SystemExit("Unexpected rescue kernel") + cmdline = remote("cat /proc/cmdline") + if not {"omamobile.initramfs", "omamobile.noresize"} <= set(cmdline.split()): + raise SystemExit("Must run from the unmounted rescue boot") + serial = re.search(r"(?:^| )androidboot.serialno=([^ ]+)", cmdline) + if not serial or hashlib.sha256(serial[1].encode()).hexdigest() != backup["serial_sha256"]: + raise SystemExit("Rescue phone identity differs from the original backups") + if not remote("cat /proc/device-tree/compatible").startswith("xiaomi,alioth\0"): + raise SystemExit("Rescue device tree is not alioth") + userdata = remote('''set -e +for p in /sys/class/block/*; do + if grep -qx PARTNAME=userdata "$p/uevent" 2>/dev/null; then echo "/dev/${p##*/}"; fi +done +''') + if not re.fullmatch(r"/dev/sda[0-9]+", userdata): + raise SystemExit("Unexpected or ambiguous userdata layout") + remote('''set -e +test ! -e /dev/sda +test -z "$(awk '$1 ~ /^\\/dev\\/sd/ {print}' /proc/mounts)" +test "$(cat /sys/class/block/''' + userdata.removeprefix('/dev/') + '''/ro)" = 0 +for p in /sys/class/block/sd*; do + [ -r "$p/ro" ] || continue + [ "$(cat "$p/ro")" = 0 ] || continue + case "${p##*/}" in sda|''' + userdata.removeprefix('/dev/') + ''') ;; *) exit 1 ;; esac +done +echo guard-passed +''') + size = root["rootfs_bytes"] + if size % 1048576 or size > int(remote("blockdev --getsize64 " + userdata)): + raise SystemExit("Unexpected root size") + print("Reading and hashing the entire flashed root without mounting it...", flush=True) + actual = remote(f"dd if={userdata} bs=1048576 count={size // 1048576} 2>/dev/null | sha256sum", 600).split()[0] + if actual != root["rootfs_sha256"]: + raise SystemExit("Flashed root checksum differs; no completion receipt written") + receipt = dict(device="alioth", kernel_release=release, captured_at=time.time(), + serial_sha256=backup["serial_sha256"], read_only_capture=True, + rescue_boot=True, userdata_unmounted=True, storage_guard_passed=True, + rootfs_bytes=size, rootfs_sha256=actual) + target.touch(mode=0o600, exist_ok=True) + target.chmod(0o600) + target.write_text(json.dumps(receipt, indent=2) + "\n") + print("Complete device root matches the prepared raw image. Private receipt:", target) + + +if __name__ == "__main__": + main() diff --git a/tools/alioth/verify-image.py b/tools/alioth/verify-image.py new file mode 100644 index 000000000..0af0a9636 --- /dev/null +++ b/tools/alioth/verify-image.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Offline checks of the F3 boot payload, root, sparse transport and access path.""" +import argparse +import gzip +import hashlib +import importlib.util +import json +from pathlib import Path +import struct +import subprocess + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location("reference", Path(__file__).with_name("prepare-reference.py")) +reference = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reference) + + +def check(condition, description): + if not condition: + raise SystemExit("FAILED: " + description) + print("ok - " + description, flush=True) + + +def read_image_file(image, name): + return subprocess.check_output(["debugfs", "-R", "cat " + name, str(image)], stderr=subprocess.DEVNULL) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--boot-only", action="store_true") + parser.add_argument("--images", type=Path, default=ROOT / "out/alioth/images") + args = parser.parse_args() + images = args.images.resolve() + manifest = json.loads((images / "BOOT-MANIFEST.json").read_text()) + release = manifest["kernel_release"] + public = (ROOT / "keys/alioth/alioth_ed25519.pub").read_bytes() + for filename, expected, rescue in (("boot.img", manifest["boot_sha256"], False), + ("boot-rescue.img", manifest["rescue_boot_sha256"], True)): + data = (images / filename).read_bytes() + check(hashlib.sha256(data).hexdigest() == expected, filename + " checksum") + fields = struct.unpack_from("<10I", data, 8) + kernel, ramdisk, page, version = fields[0], fields[2], fields[7], fields[8] + check(data[:8] == b"ANDROID!" and page == 4096 and version == 0, filename + " Android v0 / 4096-byte pages") + check(data[page:page + kernel] == (images.parent / "reference/Image.gz-dtb").read_bytes(), filename + " exact pinned alioth kernel/DTB") + offset = ((page + kernel + page - 1) // page) * page + payload = data[offset:offset + ramdisk] + check(hashlib.sha256(payload).hexdigest() == manifest["initramfs_sha256"], filename + " initramfs checksum") + files = {n: (mode, content) for n, mode, content in reference.cpio_files(gzip.decompress(payload))} + init = files["init"][1].decode() + check(files["etc/omamobile-compatible"][1] == b"xiaomi,alioth\n", filename + " board guard") + check(files["etc/omamobile-ufs-rw"][1] == b"userdata\n", filename + " userdata-only UFS write allowlist") + check("etc/omamobile-simplefb-trig" not in files and "etc/omamobile-bringup-probe" not in files, + filename + " no Pixel register probes") + check(files["root/.ssh/authorized_keys"][1] == public and files["root/.ssh/authorized_keys"][0] & 0o777 == 0o600, + filename + " dedicated SSH public key and permissions") + hostkey = "etc/dropbear/dropbear_ed25519_host_key" + check(files[hostkey][1] == (images.parent / "dropbear_ed25519_host_key").read_bytes() + and files[hostkey][0] & 0o777 == 0o600, + filename + " stable private rescue host identity") + check("dropbear -R -E -s -p 172.16.42.1:22" in init and "02:10:42:00:00:02" in init, + filename + " key-only SSH and predictable USB Ethernet") + check('modprobe qcom-wdt' in init and 'watchdog -t 5 -T 30' in init, filename + " early matching watchdog") + module_files = [(n, content) for n, (mode, content) in files.items() + if n.startswith("usr/lib/modules/") and n.endswith(".ko")] + check(bool(module_files) and all(n.startswith(f"usr/lib/modules/{release}/") + and b"vermagic=" + release.encode() + b" " in content + for n, content in module_files), filename + " initramfs modules match release") + if release != "6.15.1-sm8250": + check('kernel-trial.pending' in init and 'unacknowledged kernel trial' in init, + filename + " trial hang marker and rescue fallback") + check('LC_ALL=C dumpe2fs -h' in init and '= omamobile-root' in init, filename + " root-label gate before mount") + binaries = [(name, content) for name, (mode, content) in files.items() + if content.startswith(b"\x7fELF") and name.startswith(("bin/", "sbin/", "usr/bin/", "usr/sbin/"))] + check(len(binaries) >= 5 and all(struct.unpack_from("/dev/null cleanup() { docker volume rm -f "$volume" >/dev/null 2>&1 || true; } trap cleanup EXIT @@ -92,10 +123,13 @@ start=$(date +%s) alarm_say "Building $name for $DEVICE (kernel $release)" commit=$(git rev-parse --short=12 HEAD)$(git diff --quiet HEAD -- rootfs packages tools device 2>/dev/null || echo "-dirty") docker run --rm --privileged --platform linux/arm64 \ - -v "$ROOT:/src:ro" -v "$ROOT/out/repo:/repo:ro" -v "$modules:/modules:ro" \ + "${overlay_args[@]}" \ + -v "$ROOT:/src:ro" -v "${repo%/aarch64}:/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_DIST_PACKAGES="$ROOTFS_DIST_PACKAGES" \ + -e ROOTFS_PROFILE="$ROOTFS_PROFILE" \ -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/lib/alarm.sh b/tools/lib/alarm.sh index 075814186..600ef9b7b 100644 --- a/tools/lib/alarm.sh +++ b/tools/lib/alarm.sh @@ -101,7 +101,9 @@ alarm_build_image() { done ctx=$(mktemp -d) cp "$OMARCHY_KEYRING_DIR"/omarchy{.gpg,-trusted,-revoked} "$ctx/" - cp "$root"/packages/omamobile-keyring/omamobile{.gpg,-trusted,-revoked} "$ctx/" + # A local builder can sign its own repository without editing committed keys. + local mobile_keyring=${OMAMOBILE_KEYRING_DIR:-$root/packages/omamobile-keyring} + cp "$mobile_keyring"/omamobile{.gpg,-trusted,-revoked} "$ctx/" cp "$root/tools/lib/alarm-setup" "$ctx/setup" hash=$( (echo "$base $OMARCHY_CHANNEL $(id -u)"; cat "$ctx"/*) | sha256sum | cut -c1-16) tag=omamobile-alarm-build:$hash diff --git a/tools/lib/rootfs-overlay.py b/tools/lib/rootfs-overlay.py new file mode 100644 index 000000000..77bf26fe4 --- /dev/null +++ b/tools/lib/rootfs-overlay.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Extract a local runtime overlay with Python's path/link containment checks.""" +from pathlib import Path, PurePosixPath +import sys +import tarfile + + +def extract(archive, target): + target = Path(target).resolve() + if target == Path('/') or not target.is_dir(): + raise ValueError('An existing staging directory is required') + with tarfile.open(archive) as source: + for entry in source: + path = PurePosixPath(entry.name) + if path.is_absolute() or '..' in path.parts: + raise ValueError('Unsafe overlay path') + if not (entry.isdir() or entry.isfile() or entry.issym()): + raise ValueError('Overlay may contain only files, directories and symlinks') + source.extractall(target, filter='data') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[1] != 'extract': + raise SystemExit('Usage: rootfs-overlay.py extract ARCHIVE STAGING_DIRECTORY') + extract(sys.argv[2], sys.argv[3])