Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

tools: the provenance check also finds writes to the phone's storage in C; its own test suite

shimokudc5503ad9579
diff --git a/ci/github-check.yml b/ci/github-check.yml
index 598e8a3..828ab37 100644
--- a/ci/github-check.yml
+++ b/ci/github-check.yml
@@ -23,11 +23,8 @@ jobs:
# (This replaces two lines of the form `! git ls-files | grep ...`: bash -e does not stop on
# a negated pipeline, so the first of them could never fail, and a committed screenshot passed.)
python3 tools/provenance-check.py
- - name: The provenance check itself catches what it should
- run: |
- d=$(mktemp -d); git init -q "$d"; cp tools/provenance-check.py "$d/"; mkdir "$d/tools"; mv "$d/provenance-check.py" "$d/tools/"; : > "$d/tools/provenance.allow"
- printf '\x89PNG\r\n\x1a\nx' > "$d/shot.png"; git -C "$d" add -A
- if python3 "$d/tools/provenance-check.py" >/dev/null; then echo "a screenshot got through the provenance check"; exit 1; fi
+ - name: The provenance check itself: what it lets through and what it stops
+ run: python3 tools/provenance-test.py
- name: The kernel patch applies to Apple's tree
run: |
git clone -q --depth 1 --branch xnu-8796.121.2 https://github.com/apple-oss-distributions/xnu.git /tmp/xnu
diff --git a/tools/provenance-check.py b/tools/provenance-check.py
index 713fb57..0b29d0f 100644
--- a/tools/provenance-check.py
+++ b/tools/provenance-check.py
@@ -46,6 +46,10 @@ HEX_LINES_LIMIT = 200
FLASHY = re.compile(r"fastboot\s+(flash|erase|format|flashing|oem\s+unlock|oem\s+lock|set_active)\b|"
r"\bdd\s+[^|;&\n]*of=/dev/(block|mmcblk|sd[a-z]|nvme)|\bmke2fs\b.*\b/dev/|"
r"\badb\s+(shell\s+)?(su\s+-c\s+)?['\"]?(flash_image|erase_image|blkdiscard)")
+# ... and in C: the loader's write to a block device, and the kernel's UFS driver's. Both are limited in code to
+# the partitions named in the `flash` lines of tools/provenance.allow, and both are declared there.
+FLASHY_C = re.compile(r"\bwrite_blocks\s*\(|\bBLOCK_OP_WRITE\b")
+C_WRITERS = re.compile(r"^(xnuloader/[^/]+|xnu/files/bsd/dev/hakios\.ufs[^/]*)\.c$")
SCRIPT_DIRS = ("tools/", "devices/", "qemu/", "sysimage/", "xnuloader/", "userland/build.sh")
SCRIPT_FILES = ("xl", "Makefile", "xnu-build.sh")
# this file and the doctor mention these commands in order to look for them
@@ -139,16 +143,17 @@ def main():
problems.append("%s: %s -- marked vendor (proprietary): remove it from the tree" % (path, why))
elif status == "pending":
warnings.append("%s: %s -- pending: %s" % (path, why, reason))
- # scripts that would write to the phone's flash
- if path not in SKIP_SCAN and (path in SCRIPT_FILES or path.startswith(SCRIPT_DIRS)) and \
- path.endswith((".sh", ".py", "xl", "Makefile")):
+ # scripts, and C code of the loader and the UFS driver, that would write to the phone's storage
+ scan_c = bool(C_WRITERS.match(path))
+ is_script = (path in SCRIPT_FILES or path.startswith(SCRIPT_DIRS)) and path.endswith((".sh", ".py", "xl", "Makefile"))
+ if path not in SKIP_SCAN and (scan_c or is_script):
try:
text = open(full, "r", errors="replace").read()
except OSError:
continue
for n, line in enumerate(text.splitlines(), 1):
code = line.split("#", 1)[0] if path.endswith((".sh", "xl", "Makefile")) else line
- found = FLASHY.search(code)
+ found = (FLASHY_C if scan_c else FLASHY).search(code)
if not found:
continue
hit = match(rules, path, flash=True)
@@ -164,6 +169,14 @@ def main():
% (path, hit[1]))
break
+ # a declared writer is a statement about a file, so it is listed even if no pattern fired in it today
+ for status, glob, reason, _ in rules:
+ if status == "flash":
+ for p in files:
+ if fnmatch.fnmatchcase(p, glob) and p not in used:
+ used.add(p)
+ explained.append((p, "declared writer to the phone's storage", "flash", reason,
+ os.path.getsize(os.path.join(root, p))))
# an entry that matches nothing has gone stale: a rule for a file that left the tree is clutter that
# would explain a file that comes back
# (a `vendor` line is a tripwire: it stays after the files are gone, so that putting them back fails)
diff --git a/tools/provenance-test.py b/tools/provenance-test.py
new file mode 100644
index 0000000..4ff92d5
--- /dev/null
+++ b/tools/provenance-test.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+"""tools/provenance-check.py on small repositories of its own: what it lets through and what it stops.
+
+Every kind of violation has a case that must fail and the same case, explained in tools/provenance.allow,
+that must pass; a clean tree passes; a `vendor` line is a tripwire that stays quiet while the files are
+gone and fails when one comes back; a stale line is reported; a comment that only mentions a flash
+command is not a flash command.
+"""
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+CHECK = os.path.join(HERE, "provenance-check.py")
+PNG = b"\x89PNG\r\n\x1a\n" + b"x" * 64
+MACHO = b"\xcf\xfa\xed\xfe\x07\x00\x00\x01" + b"not really a kernel"
+FIRMWARE = ("static const unsigned char fw[] = {\n" + "0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,\n" * 250 + "};\n").encode()
+failures = []
+
+
+def repo(files, allow=""):
+ d = tempfile.mkdtemp(prefix="provenance-test-")
+ subprocess.run(["git", "init", "-q", d], check=True)
+ files = dict(files)
+ files["tools/provenance.allow"] = allow
+ for name, data in files.items():
+ path = os.path.join(d, name)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ open(path, "wb").write(data if isinstance(data, bytes) else data.encode())
+ subprocess.run(["git", "-C", d, "add", "-A"], check=True, capture_output=True)
+ return d
+
+
+def check(label, files, allow, ok, expect=()):
+ d = repo(files, allow)
+ try:
+ r = subprocess.run([sys.executable, CHECK, "--root", d], capture_output=True, text=True)
+ finally:
+ shutil.rmtree(d, ignore_errors=True)
+ out = r.stdout + r.stderr
+ good = (r.returncode == 0) == ok and all(e in out for e in expect)
+ print("%s %s" % ("ok " if good else "FAIL", label))
+ if not good:
+ failures.append(label)
+ print(" want exit %s and %r; got exit %d:\n %s" % (0 if ok else 1, list(expect), r.returncode,
+ out.strip().replace("\n", "\n ")[:500]))
+
+
+SRC = {"src/ok.c": "int main(void) { return 0; }\n"}
+
+check("a clean tree passes", SRC, "", True)
+
+check("a screenshot, unexplained, fails", {**SRC, "docs/home.png": PNG}, "", False, ["docs/home.png"])
+check("a screenshot, explained, passes", {**SRC, "docs/home.png": PNG}, "open docs/home.png my own drawing\n", True)
+
+check("an unexplained Mach-O fails", {**SRC, "bin/stray": MACHO}, "", False, ["Mach-O"])
+check("a Mach-O built from the tree passes", {**SRC, "bin/stray": MACHO}, "open bin/* built from src/ok.c\n", True)
+
+for kind, data in (("an IPSW", b"PK\x03\x04" + b"\0" * 20), ("a font", b"\0\1\0\0" + b"\0" * 20)):
+ name = "x.ipsw" if kind == "an IPSW" else "x.ttf"
+ check("%s fails" % kind, {**SRC, name: data}, "", False, [name])
+
+check("a path through a cryptex fails", {**SRC, "sysimage/cryptex/readme.txt": "hi\n"}, "", False, ["cryptex"])
+
+flash_sh = {"tools/flash-it.sh": "#!/bin/sh\nfastboot flash boot x.img\n"}
+check("a script that flashes fails", {**SRC, **flash_sh}, "", False, ["writes to the phone"])
+check("a script that flashes, declared, passes with a warning", {**SRC, **flash_sh}, "flash tools/flash-it.sh a one-time job\n", True, ["declared exception"])
+check("a flash command in a comment is not a flash command", {**SRC, "tools/note.sh": "# never run: fastboot flash boot x.img\necho hi\n"}, "", True)
+check("erase and oem unlock are caught too", {**SRC, "tools/a.sh": "fastboot erase userdata\n", "tools/b.sh": "fastboot oem unlock\n"}, "", False, ["tools/a.sh", "tools/b.sh"])
+
+loader = {"xnuloader/loader.c": "void f(void) { bio->write_blocks(bio, 0, 0, 1, b); }\n"}
+check("the loader writing blocks, undeclared, fails", {**SRC, **loader}, "", False, ["xnuloader/loader.c"])
+check("the loader writing blocks, declared, passes", {**SRC, **loader}, "flash xnuloader/loader.c its log to logdump\n", True, ["xnuloader/loader.c"])
+check("a C file elsewhere may use the name", {**SRC, "src/other.c": "int write_blocks(int x);\n"}, "", True)
+
+check("firmware compiled into a header fails", {**SRC, "src/fw.h": FIRMWARE}, "", False, ["src/fw.h"])
+check("... explained as pending: passes, with a warning", {**SRC, "src/fw.h": FIRMWARE}, "pending src/fw.h waiting for the vendor\n", True, ["pending"])
+
+vendor_tracked = {**SRC, "vendor/driver.efi": b"MZ\x90\0" + b"\0" * 32}
+check("a vendor file tracked fails", vendor_tracked, "vendor vendor/* the vendor's\n", False, ["vendor (proprietary)"])
+check("a vendor line with the files gone: quiet, no stale warning", SRC, "vendor vendor/* the vendor's\n", True)
+check("an open line that matches nothing is reported as stale", SRC, "open nothing/here/* gone\n", True, ["stale"])
+
+check("a bad status in the allowlist is an error", SRC, "maybe docs/x something\n", False, ["provenance.allow"])
+check("the report lists a declared writer", {**SRC, **flash_sh}, "flash tools/flash-it.sh a one-time job\n", True)
+
+if failures:
+ sys.exit("provenance-test: %d FAILED" % len(failures))
+print("provenance-test: all passed")
diff --git a/tools/provenance.allow b/tools/provenance.allow
index d6b999c..3421d91 100644
--- a/tools/provenance.allow
+++ b/tools/provenance.allow
@@ -23,5 +23,9 @@ pending xnu/files/bsd/dev/hakios.focaltech_fw.h FocalTech's firmware as a C a
vendor devices/poco-x5-pro/uefi/files/Binaries/redwood/* UEFI drivers extracted from the vendor's xbl firmware (QcomPkg, MiPkg, RawFiles and the EDK2 modules as the vendor built them)
vendor devices/poco-x5-pro/prebuilt/SILICIUM_UEFI.fd the built UEFI image: carries those drivers
-# --- scripts that may write to the phone's storage -----------------------------------------------------------
-flash tools/userdata-carve.py prints the dd commands that cut the `darwin` partition off the end of Android's userdata (a new GPT); a person runs them once, by hand, under Android, and only for ufs_write=1 / var_store=1 persistence; the default run writes nothing
+# --- everything that can write to the phone's storage: a short list, each limited in code --------------------
+# (the default run writes one thing: the loader's own log into the phone's logdump partition)
+flash xnuloader/loader.c the loader writes its own log (a few KB) into the phone's `logdump` partition at the end of a run and, only with ufs_write=1, into the partition `darwin` from BLOCK_WRITE_FIRST on; it REFUSES every other write (BLOCK_OP_WRITE: "not darwin ... never")
+flash xnu/files/bsd/dev/hakios.ufs.c the kernel's side: no write at all without ufs_write=1, then only /dev/rufs_darwin, whole blocks from UFS_WRITE_FIRST on, and one writer at a time
+flash tools/darwin-write.py writes an image into `darwin` from Android (adb, root) after checking the GPT, the partition's identity and the block range, only to /dev/block/by-name/darwin, reading every write back; every attempt is logged
+flash tools/userdata-carve.py prints the dd commands that cut the `darwin` partition off the end of Android's userdata (a new GPT); a person runs them once, by hand, under Android, and only for the optional persistence; the default run needs no such partition