Files
geminux/scripts/test-flash-mtk-gpt.py
T

1053 lines
40 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
"""Offline test suite for Geminux flash-mtk GPT builder, safety guards, and firmware extractor."""
import os
import re
import shutil
import struct
import subprocess
import sys
import tempfile
import uuid
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts")
FLASH_DEPS = os.path.join(BASE_DIR, ".flash-deps")
if os.path.isdir(FLASH_DEPS):
sys.path.insert(0, FLASH_DEPS)
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, SCRIPTS_DIR)
from geminux_accounts import (
customize_ext4_accounts,
rewrite_account_tables,
sha512_crypt,
validate_username,
)
from geminux_gpt import (
BASIC_DATA_TYPE_GUID,
GPT_ARRAY_SECTORS,
GPT_ENTRY_COUNT,
GPT_ENTRY_SIZE,
LINUX_FS_TYPE_GUID,
PROTECTED_END_LBA,
SECTOR_SIZE,
GptEntry,
GptHeader,
build_geminux_gpts,
parse_primary_gpt,
verify_gpt_crcs,
)
import importlib.util
def _load_mod(name, path):
sp = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(sp)
sp.loader.exec_module(mod)
return mod
extract_firmware = _load_mod(
"extract_vendor_fw", os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py")
).extract_firmware
flash_mtk = _load_mod("flash_mtk", os.path.join(BASE_DIR, "flash-mtk.py"))
def make_synthetic_gemini_pgpt(total_sectors):
# Replicate Planet Computers Gemini x27 SYS1..SYS34 partitions
parts_spec = [
("recovery", 0x8000, 0x1000000),
("para", 0x1008000, 0x80000),
("expdb", 0x1088000, 0xa00000),
("frp", 0x1a88000, 0x100000),
("nvcfg", 0x1b88000, 0x800000),
("nvdata", 0x2388000, 0x2000000),
("metadata", 0x4388000, 0x2000000),
("protect1", 0x6388000, 0x800000),
("protect2", 0x6b88000, 0xc78000),
("seccfg", 0x7800000, 0x800000),
("oemkeystore", 0x8000000, 0x200000),
("proinfo", 0x8200000, 0x300000),
("md1img", 0x8500000, 0x1800000),
("md1dsp", 0x9d00000, 0x400000),
("md1arm7", 0xa100000, 0x300000),
("md3img", 0xa400000, 0x500000),
("scp1", 0xa900000, 0x100000),
("scp2", 0xaa00000, 0x100000),
("nvram", 0xab00000, 0x500000),
("lk", 0xb000000, 0x80000),
("lk2", 0xb080000, 0x80000),
("boot", 0xb100000, 0x1000000),
("logo", 0xc100000, 0x800000),
("tee1", 0xc900000, 0x500000),
("tee2", 0xce00000, 0x500000),
("keystore", 0xd300000, 0xd00000),
("system", 0xe000000, 0xa0000000),
("cache", 0xae000000, 0x1b000000),
("userdata", 0xc9000000, (total_sectors - 32768 - 64) * SECTOR_SIZE - 0xc9000000),
]
entries = []
for name, start_b, size_b in parts_spec:
first_lba = start_b // SECTOR_SIZE
last_lba = (start_b + size_b) // SECTOR_SIZE - 1
entries.append(GptEntry(
BASIC_DATA_TYPE_GUID,
uuid.uuid4().bytes_le,
first_lba,
last_lba,
0,
name,
))
flashinfo_sectors = 0x1000000 // SECTOR_SIZE
flashinfo_first = total_sectors - 34 - flashinfo_sectors
entries.append(GptEntry(
BASIC_DATA_TYPE_GUID,
uuid.uuid4().bytes_le,
flashinfo_first,
flashinfo_first + flashinfo_sectors - 1,
0,
"flashinfo",
))
part_array = bytearray(GPT_ENTRY_COUNT * GPT_ENTRY_SIZE)
for i, e in enumerate(entries):
part_array[i * GPT_ENTRY_SIZE:(i + 1) * GPT_ENTRY_SIZE] = e.to_bytes()
raw_hdr = struct.pack(
"<8sIIIIQQQQ16sQIII",
b"EFI PART",
0x00010000,
92,
0,
0,
1,
total_sectors - 1,
34,
total_sectors - 34,
uuid.uuid4().bytes_le,
2,
GPT_ENTRY_COUNT,
GPT_ENTRY_SIZE,
0,
).ljust(SECTOR_SIZE, b"\x00")
hdr = GptHeader(raw_hdr)
hdr_bytes = hdr.pack_with_crcs(bytes(part_array))
mbr = bytearray(SECTOR_SIZE)
mbr[510:512] = b"\x55\xAA"
return bytes(mbr) + hdr_bytes + bytes(part_array)
def test_gpt_repartition():
# ~64 GB eMMC sector count
total_sectors = 122142720
orig_pgpt = make_synthetic_gemini_pgpt(total_sectors)
_, orig_hdr, orig_entries = parse_primary_gpt(orig_pgpt)
new_pgpt, new_sgpt, new_entries = build_geminux_gpts(orig_pgpt, total_sectors)
assert len(new_pgpt) == 34 * SECTOR_SIZE
assert len(new_sgpt) == 33 * SECTOR_SIZE
_, pri_hdr, parsed_entries = parse_primary_gpt(new_pgpt)
verify_gpt_crcs(pri_hdr, new_pgpt[2 * SECTOR_SIZE:])
# Verify backup GPT CRCs as well
bak_entries_bytes = new_sgpt[:GPT_ARRAY_SECTORS * SECTOR_SIZE]
bak_hdr = GptHeader(new_sgpt[GPT_ARRAY_SECTORS * SECTOR_SIZE:])
verify_gpt_crcs(bak_hdr, bak_entries_bytes)
assert bak_hdr.current_lba == total_sectors - 1
assert bak_hdr.backup_lba == 1
assert bak_hdr.part_entry_start_lba == total_sectors - 1 - GPT_ARRAY_SECTORS
# Check every pre-0x0E000000 partition is preserved byte-for-byte
orig_pre = [e for e in orig_entries if e.last_lba < PROTECTED_END_LBA]
new_pre = [e for e in parsed_entries if e.last_lba < PROTECTED_END_LBA]
assert len(orig_pre) == len(new_pre) == 26
for a, b in zip(orig_pre, new_pre):
assert a.to_bytes() == b.to_bytes(), f"Mismatch in preserved partition {a.name}"
names = [e.name for e in parsed_entries]
assert "system" not in names
assert "cache" not in names
assert "userdata" not in names
assert "linux" in names
assert "boot2" in names
assert "flashinfo" in names
linux_p = next(e for e in parsed_entries if e.name == "linux")
boot2_p = next(e for e in parsed_entries if e.name == "boot2")
flash_p = next(e for e in parsed_entries if e.name == "flashinfo")
assert linux_p.type_guid == LINUX_FS_TYPE_GUID
assert linux_p.first_lba == PROTECTED_END_LBA
assert linux_p.last_lba == boot2_p.first_lba - 1
linux_gib = (linux_p.sectors * SECTOR_SIZE) / (1024 ** 3)
assert linux_gib > 57.5, f"Expected >57.5 GiB linux partition, got {linux_gib:.2f}"
assert boot2_p.sectors * SECTOR_SIZE == 0x1000000
assert boot2_p.last_lba < flash_p.first_lba
print(f"[PASS] GPT repartitioning verified (linux={linux_gib:.2f} GiB, 26 protected partitions intact)")
def test_write_safety():
for protected in ("preloader", "nvram", "proinfo", "protect1", "protect2", "lk", "tee1", "md1img"):
blocked = False
try:
flash_mtk.enforce_write_safety(protected, allow_protected=False)
except PermissionError:
blocked = True
assert blocked, f"Protected partition {protected} was NOT blocked!"
flash_mtk.enforce_write_safety(protected, allow_protected=True)
for allowed in ("boot", "recovery", "boot2", "linux"):
flash_mtk.enforce_write_safety(allowed, allow_protected=False)
print("[PASS] Protected partition write-denylist verified")
def test_firmware_extraction():
if shutil.which("mke2fs") is None or shutil.which("debugfs") is None:
print("[SKIP] mke2fs/debugfs not available on host for ext4 extraction test")
return
with tempfile.TemporaryDirectory(prefix="geminux-fwtest-") as tmp:
src_tree = os.path.join(tmp, "sysroot", "vendor", "firmware")
os.makedirs(src_tree, exist_ok=True)
expected = {
"ROMv3_patch_1_0_hdr.bin": b"ROMV3_0" * 64,
"ROMv3_patch_1_1_hdr.bin": b"ROMV3_1" * 64,
"WIFI_RAM_CODE_6797": b"WIFI_FW" * 128,
"WMT_SOC.cfg": b"coex=1\n",
"pcm_suspend.bin": b"PCM_SUSPEND" * 16,
}
for name, data in expected.items():
with open(os.path.join(src_tree, name), "wb") as f:
f.write(data)
sys_img = os.path.join(tmp, "system.img")
subprocess.run(
["mke2fs", "-t", "ext4", "-F", "-q", "-d", os.path.join(tmp, "sysroot"), sys_img, "4M"],
check=True,
)
out_dir = os.path.join(tmp, "fw-out")
found, missing = extract_firmware(sys_img, out_dir)
assert not missing, f"Missing firmware blobs: {missing}"
assert set(found.keys()) == set(expected.keys())
for name, data in expected.items():
with open(os.path.join(out_dir, name), "rb") as f:
assert f.read() == data
assert os.path.isfile(os.path.join(out_dir, "MANIFEST.sha256"))
print("[PASS] Stock system.img firmware extraction verified")
def test_mtkclient_gpt_settings():
from types import SimpleNamespace
vendor_mtk = os.path.join(BASE_DIR, "vendor", "mtkclient")
if vendor_mtk not in sys.path:
sys.path.insert(0, vendor_mtk)
from mtkclient.Library.partition import Partition
cfg = flash_mtk.create_mtk_config()
assert cfg.gpt_settings is not None, "create_mtk_config() left cfg.gpt_settings as None"
assert cfg.gpt_settings.gpt_num_part_entries == 0
total_sectors = 122142720
pgpt = make_synthetic_gemini_pgpt(total_sectors)
# Ensure protective MBR has EFI partition entry matching hardware GPT
pgpt_arr = bytearray(pgpt)
pgpt_arr[0x1BE:0x1CE] = struct.pack("<B3sB3sII", 0x00, b"\x00\x02\x00", 0xEE, b"\xff\xff\xff", 1, total_sectors - 1)
pgpt = bytes(pgpt_arr)
def fake_readflash(addr, length, filename="", parttype="user", display=False):
chunk = pgpt[addr:addr + length]
return chunk.ljust(length, b"\x00")
daconfig = SimpleNamespace(storage=SimpleNamespace(flashsize=total_sectors * SECTOR_SIZE), pagesize=SECTOR_SIZE)
daloader = SimpleNamespace(daconfig=daconfig, readflash=fake_readflash)
fake_mtk = SimpleNamespace(config=cfg, daloader=daloader)
part = Partition(fake_mtk, fake_readflash, lambda: (b"", None))
_, guid_gpt = part.get_gpt(cfg.gpt_settings, "user")
assert guid_gpt is not None, "Partition.get_gpt failed with GptSettings(0, 0, 0)"
names = [e.name for e in guid_gpt.partentries]
assert "proinfo" in names and "nvram" in names and "linux" not in names, f"Unexpected entries: {names}"
print(f"[PASS] mtkclient GptSettings regression verified ({len(names)} partitions parsed)")
def test_finish_da_session():
from types import SimpleNamespace
with tempfile.TemporaryDirectory(prefix="geminux-da-exit-") as tmp:
state_file = os.path.join(tmp, ".state")
calls = []
class FakeDaloader:
def shutdown(self, bootmode=0):
calls.append(("shutdown", bootmode))
class FakePort:
def close(self):
calls.append(("close",))
fake_mtk = SimpleNamespace(
config=SimpleNamespace(hwparam_path=tmp),
daloader=FakeDaloader(),
port=FakePort(),
)
with open(state_file, "w") as f:
f.write("cached")
flash_mtk.finish_da_session(fake_mtk, reboot=True)
assert not os.path.exists(state_file), ".state file was not cleaned on DA reboot"
assert calls == [("shutdown", 1), ("close",)], f"Unexpected calls: {calls}"
calls.clear()
flash_mtk.finish_da_session(fake_mtk, reboot=False)
assert calls == [("shutdown", 0), ("close",)], f"Unexpected calls: {calls}"
print("[PASS] DA shutdown/reboot session cleanup verified")
def test_fast_preloader_handshake():
from types import SimpleNamespace
from mtkclient.Library.Port import Port
def run_case(initial_packets, coalesced_dup=False):
rx_packets = list(initial_packets)
tx_seen = []
class FakeEndpoint:
def __init__(self, is_in):
self.is_in = is_in
self.wMaxPacketSize = 512
def write(self, data, timeout=200):
tx_seen.append(bytes(data))
if data == b"\xa0":
if coalesced_dup:
rx_packets.append(b"READY\x5f\x5f")
else:
rx_packets.append(b"\x5f")
elif data == b"\x0a":
rx_packets.append(b"\xf5")
elif data == b"\x50":
rx_packets.append(b"\xaf")
elif data == b"\x05":
rx_packets.append(b"\xfa")
return len(data)
def read(self, size, timeout=100):
if not rx_packets:
return b""
pkt = rx_packets[0]
if size < len(pkt):
raise OSError("LIBUSB_ERROR_OVERFLOW")
rx_packets.pop(0)
return pkt
fake_cdc = SimpleNamespace(
pid=0x2000,
EP_OUT=FakeEndpoint(False),
EP_IN=FakeEndpoint(True),
set_line_coding=lambda *a, **kw: None,
setcontrollinestate=lambda *a, **kw: None,
)
fake_port = Port.__new__(Port)
fake_port.cdc = fake_cdc
fake_port.info = lambda *a, **kw: None
fake_port.debug = lambda *a, **kw: None
fake_port.warning = lambda *a, **kw: None
fake_port.error = lambda *a, **kw: None
assert fake_port.run_handshake(retries=25) is True, (
f"Preloader handshake failed (initial={initial_packets}, tx={tx_seen})"
)
assert tx_seen[-4:] == [b"\xa0", b"\x0a", b"\x50", b"\x05"], (
f"Unexpected handshake TX sequence: {tx_seen}"
)
run_case([b"READY\r\n"])
run_case([b"READY"], coalesced_dup=True)
parsed = flash_mtk.build_arg_parser().parse_args(["--wait-timeout", "450"])
assert parsed.wait_timeout == 450
cfg = flash_mtk.create_mtk_config(wait_timeout=450)
assert cfg.wait_timeout == 450
print("[PASS] Fast BROM/Preloader handshake (maxinsize, no overflow, READY-tolerant) verified")
def test_xflash_shutdown_wire_packet():
from types import SimpleNamespace
vendor_mtk = os.path.join(BASE_DIR, "vendor", "mtkclient")
if vendor_mtk not in sys.path:
sys.path.insert(0, vendor_mtk)
import mtkclient.Library.Connection.usblib as usblib
import mtkclient.Library.DA.xflash.xflash_lib as xflash_lib
from mtkclient.Library.DA.xflash.xflash_param import Cmd
orig_sleep = xflash_lib.time.sleep
sleep_calls = []
try:
xflash_lib.time.sleep = lambda sec: sleep_calls.append(sec)
for bootmode, expected in (
(1, (1, 100, 0, 1, 0, 1, 0)),
(0, (0, 0, 0, 0, 0, 1, 0)),
):
sent = []
close_calls = []
sleep_calls.clear()
da = xflash_lib.DAXFlash.__new__(xflash_lib.DAXFlash)
da.cmd = Cmd()
da.eh = SimpleNamespace(status=hex)
da.error = lambda *a, **kw: None
da.xsend = lambda data, *a, **kw: (sent.append(data), True)[1]
da.status = lambda: 0
da.mtk = SimpleNamespace(
port=SimpleNamespace(close=lambda reset=False: close_calls.append(reset))
)
assert da.shutdown(async_mode=0, dl_bit=0, bootmode=bootmode) is True
assert len(sent) == 2 and sent[0] == Cmd.SHUTDOWN, f"Unexpected commands: {sent}"
assert len(sent[1]) == 28, f"Expected 28-byte shutdown_ctrl, got {len(sent[1])} bytes"
unpacked = struct.unpack("<IIIIIII", sent[1])
assert unpacked == expected, f"bootmode={bootmode}: got {unpacked}, expected {expected}"
assert close_calls == [False], f"Unexpected port.close(reset=...) calls: {close_calls}"
assert sleep_calls == [0.35], f"Expected 0.35s disconnect wait, got {sleep_calls}"
class FakeDev:
def __init__(self):
self._ctx = SimpleNamespace(dispose=lambda dev: None)
def reset(self):
raise OSError(2, "Entity not found")
info_msgs = []
debug_msgs = []
usblib.time.sleep = lambda sec: None
uc = usblib.UsbClass.__new__(usblib.UsbClass)
uc.rxleft = bytearray()
uc.connected = True
uc.interface = 0
uc.device = FakeDev()
uc.info = lambda msg: info_msgs.append(msg)
uc.debug = lambda msg: debug_msgs.append(msg)
uc.close(reset=True)
assert info_msgs == [], f"Unexpected info log on expected ENOENT disconnect: {info_msgs}"
assert len(debug_msgs) == 1 and "Entity not found" in debug_msgs[0], debug_msgs
assert uc.connected is False
finally:
xflash_lib.time.sleep = orig_sleep
print("[PASS] XFlash 28-byte shutdown wire packet and ENOENT suppression verified")
def test_sha512_crypt_and_username_validation():
openssl = shutil.which("openssl")
for pw, salt in (
("geminux", "geminux"),
("Tr0ub4dor&3!", "AbCdEf0123456789"),
("p@ss word/with+chars", "Z9y8X7w6"),
):
hashed = sha512_crypt(pw, salt=salt)
assert hashed.startswith(f"$6${salt}$") and len(hashed) == 4 + len(salt) + 86
if openssl:
expected = subprocess.check_output(
[openssl, "passwd", "-6", "-salt", salt, pw], text=True
).strip()
assert hashed == expected, f"Hash mismatch: {hashed} != {expected}"
rand_hash = sha512_crypt("anotherSecret!")
parts = rand_hash.split("$")
assert len(parts) == 4 and parts[1] == "6" and len(parts[2]) == 16 and len(parts[3]) == 86
for bad_pw in ("", "line\nbreak", "nul\x00byte", "cr\rchar"):
raised = False
try:
sha512_crypt(bad_pw)
except ValueError:
raised = True
assert raised, f"Bad password {bad_pw!r} was not rejected"
assert validate_username("pdaowner") == "pdaowner"
assert validate_username("_dev_01") == "_dev_01"
for bad_user in ("", "root", "chrony", "123bad", "bad space", "UpperCase", "a" * 32):
raised = False
try:
validate_username(bad_user)
except ValueError:
raised = True
assert raised, f"Invalid/reserved username {bad_user!r} was not rejected"
print("[PASS] Pure-Python sha512_crypt ($6$) and username validation verified")
def test_account_customization_ext4():
if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck")):
print("[SKIP] mke2fs/debugfs/e2fsck not available on host for account customization test")
return
with tempfile.TemporaryDirectory(prefix="geminux-acct-test-") as tmp:
sysroot = os.path.join(tmp, "sysroot")
os.makedirs(os.path.join(sysroot, "etc"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "home", "user", ".ssh"), exist_ok=True)
with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f:
f.write(
"root:x:0:0:root:/root:/bin/bash\n"
"chrony:x:101:102:chrony:/dev/null:/sbin/nologin\n"
"user:x:10000:10000::/home/user:/bin/bash\n"
)
with open(os.path.join(sysroot, "etc", "group"), "w", encoding="utf-8") as f:
f.write(
"root:x:0:root\n"
"wheel:x:10:root,user\n"
"audio:x:18:user\n"
"netdev:x:28:user\n"
"plugdev:x:106:user\n"
"pipewire:x:107:user\n"
"seat:x:108:user\n"
"user:x:10000:\n"
)
with open(os.path.join(sysroot, "etc", "shadow"), "w", encoding="utf-8") as f:
f.write(
"root:$6$oldsalt$oldhashroot:::::::\n"
"chrony:!:::::::\n"
"user:$6$oldsalt$oldhashuser:::::::\n"
)
with open(os.path.join(sysroot, "home", "user", ".gitconfig"), "w", encoding="utf-8") as f:
f.write("[pull]\n\trebase = false\n")
with open(os.path.join(sysroot, "home", "user", ".ssh", "authorized_keys"), "w", encoding="utf-8") as f:
f.write("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest\n")
img_dir = os.path.join(tmp, "images")
os.makedirs(img_dir, exist_ok=True)
orig_img = os.path.join(img_dir, "geminux-rootfs.img")
out_img = os.path.join(tmp, "custom-rootfs.img")
subprocess.run(
["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, orig_img, "8M"],
check=True,
)
subprocess.run(
["debugfs", "-w", orig_img],
input="\n".join([
"set_inode_field /home/user uid 10000",
"set_inode_field /home/user gid 10000",
"set_inode_field /home/user/.gitconfig uid 10000",
"set_inode_field /home/user/.gitconfig gid 10000",
"set_inode_field /home/user/.ssh uid 10000",
"set_inode_field /home/user/.ssh gid 10000",
"set_inode_field /home/user/.ssh/authorized_keys uid 10000",
"set_inode_field /home/user/.ssh/authorized_keys gid 10000",
]) + "\n",
text=True,
check=True,
stdout=subprocess.DEVNULL,
)
orig_sha = flash_mtk.sha256_file(orig_img)
res = subprocess.run(
[
os.path.join(BASE_DIR, "flash-mtk.sh"),
"--customize-rootfs", out_img,
"--images-dir", img_dir,
"--username", "pdaowner",
"--user-password", "testUserPw!9",
"--root-password", "testRootPw!9",
],
capture_output=True,
text=True,
check=False,
)
assert res.returncode == 0, f"customize-rootfs failed: {res.stdout}\n{res.stderr}"
assert flash_mtk.sha256_file(orig_img) == orig_sha, "Source rootfs image was mutated!"
e2 = subprocess.run(["e2fsck", "-fn", out_img], capture_output=True, text=True)
assert e2.returncode == 0, f"e2fsck failed: {e2.stdout}\n{e2.stderr}"
for rel in ("/home/pdaowner/.gitconfig", "/home/pdaowner/.ssh/authorized_keys"):
st = subprocess.run(
["debugfs", "-R", f"stat {rel}", out_img],
capture_output=True,
text=True,
check=True,
)
assert re.search(r"User:\s*10000\b", st.stdout), f"{rel} lost UID 10000:\n{st.stdout}"
old_st = subprocess.run(
["debugfs", "-R", "stat /home/user", out_img],
capture_output=True,
text=True,
check=False,
)
assert "File not found" in (old_st.stdout + old_st.stderr), old_st.stdout + old_st.stderr
sh_stat = subprocess.run(
["debugfs", "-R", "stat /etc/shadow", out_img],
capture_output=True,
text=True,
check=True,
)
assert "Type: regular" in sh_stat.stdout, sh_stat.stdout
assert re.search(r"Mode:\s*0640\b", sh_stat.stdout), sh_stat.stdout
assert re.search(r"User:\s*0\b", sh_stat.stdout), sh_stat.stdout
assert re.search(r"Group:\s*42\b", sh_stat.stdout), sh_stat.stdout
pw_txt = subprocess.check_output(["debugfs", "-R", "cat /etc/passwd", out_img], text=True)
gr_txt = subprocess.check_output(["debugfs", "-R", "cat /etc/group", out_img], text=True)
sh_txt = subprocess.check_output(["debugfs", "-R", "cat /etc/shadow", out_img], text=True)
assert "pdaowner:x:10000:10000::/home/pdaowner:/bin/bash" in pw_txt, pw_txt
assert "user:" not in pw_txt
for gname in ("wheel", "audio", "netdev", "plugdev", "pipewire", "seat"):
assert any(line.startswith(f"{gname}:") and "pdaowner" in line.split(":")[3].split(",")
for line in gr_txt.splitlines()), gr_txt
assert "pdaowner:x:10000:" in gr_txt and "user:x:10000:" not in gr_txt, gr_txt
sh_rows = {row.split(":")[0]: row.split(":")[1] for row in sh_txt.splitlines() if row}
assert "user" not in sh_rows and "pdaowner" in sh_rows and "root" in sh_rows
u_salt = sh_rows["pdaowner"].split("$")[2]
r_salt = sh_rows["root"].split("$")[2]
assert sh_rows["pdaowner"] == sha512_crypt("testUserPw!9", salt=u_salt)
assert sh_rows["root"] == sha512_crypt("testRootPw!9", salt=r_salt)
print("[PASS] Offline ext4 account renaming and shadow password customization verified")
def _xts_decrypt_ext4(enc_path, vk64, payload_offset, payload_bytes, out_dec_path):
from Crypto.Cipher import AES
c_data = AES.new(vk64[:32], AES.MODE_ECB)
c_tweak = AES.new(vk64[32:], AES.MODE_ECB)
with open(enc_path, "rb") as sf, open(out_dec_path, "wb") as df:
sf.seek(payload_offset)
sectors = payload_bytes // 512
for sec_idx in range(sectors):
sec = sf.read(512)
t = int.from_bytes(c_tweak.encrypt(struct.pack("<QQ", sec_idx, 0)), "little")
out = bytearray(512)
for blk in range(0, 512, 16):
tb = t.to_bytes(16, "little")
cc = bytes(a ^ b for a, b in zip(sec[blk:blk + 16], tb))
pp = c_data.decrypt(cc)
out[blk:blk + 16] = bytes(a ^ b for a, b in zip(pp, tb))
t = ((t << 1) ^ (0x87 if (t >> 127) else 0)) & ((1 << 128) - 1)
df.write(out)
def test_luks2_encryption_offline():
import pty
if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck", "cryptsetup")):
print("[SKIP] mke2fs/debugfs/e2fsck/cryptsetup not available for LUKS2 offline test")
return
with tempfile.TemporaryDirectory(prefix="geminux-luks-test-") as tmp:
sysroot = os.path.join(tmp, "sysroot")
os.makedirs(os.path.join(sysroot, "etc"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "home", "user"), exist_ok=True)
with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f:
f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n")
with open(os.path.join(sysroot, "etc", "group"), "w", encoding="utf-8") as f:
f.write("root:x:0:root\nwheel:x:10:root,user\nuser:x:10000:\n")
with open(os.path.join(sysroot, "etc", "shadow"), "w", encoding="utf-8") as f:
f.write("root:$6$oldsalt$old:::::::\nuser:$6$oldsalt$old:::::::\n")
with open(os.path.join(sysroot, "home", "user", ".gitconfig"), "w", encoding="utf-8") as f:
f.write("[pull]\n\trebase = false\n")
img_dir = os.path.join(tmp, "images")
os.makedirs(img_dir, exist_ok=True)
orig_img = os.path.join(img_dir, "geminux-rootfs.img")
enc_out = os.path.join(tmp, "enc-rootfs.img")
subprocess.run(
["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, orig_img, "8M"],
check=True,
)
orig_sha = flash_mtk.sha256_file(orig_img)
orig_bytes = os.path.getsize(orig_img)
res = subprocess.run(
[
os.path.join(BASE_DIR, "flash-mtk.sh"),
"--customize-rootfs", enc_out,
"--images-dir", img_dir,
"--username", "luksuser",
"--user-password", "uPw!77",
"--root-password", "rPw!77",
"--luks-password", "DiskPass#2026",
],
capture_output=True,
text=True,
check=False,
)
assert res.returncode == 0, f"encrypted customize-rootfs failed: {res.stdout}\n{res.stderr}"
assert flash_mtk.sha256_file(orig_img) == orig_sha, "Source rootfs image was mutated!"
assert subprocess.run(["cryptsetup", "isLuks", "--disable-locks", enc_out]).returncode == 0
assert subprocess.run(
["cryptsetup", "open", "--test-passphrase", "--disable-locks", "--key-file", "-", enc_out],
input=b"DiskPass#2026",
).returncode == 0
assert subprocess.run(
["cryptsetup", "open", "--test-passphrase", "--disable-locks", "--key-file", "-", enc_out],
input=b"WrongPass",
).returncode != 0
# Verify interactive PTY unlock (simulating PID 1 initramfs prompt on /dev/tty1)
mfd, sfd = pty.openpty()
pty_proc = subprocess.Popen(
["cryptsetup", "open", "--test-passphrase", "--disable-locks", enc_out],
stdin=sfd, stdout=sfd, stderr=sfd, close_fds=True, start_new_session=True,
)
os.close(sfd)
prompt_buf = b""
while b":" not in prompt_buf:
prompt_buf += os.read(mfd, 256)
os.write(mfd, b"DiskPass#2026\n")
pty_rc = pty_proc.wait(timeout=10)
os.close(mfd)
assert pty_rc == 0, f"Interactive PTY passphrase check failed rc={pty_rc}"
vk_file = os.path.join(tmp, "vk.bin")
dump = subprocess.check_output(
[
"cryptsetup", "luksDump", "--disable-locks", "--dump-volume-key",
"--volume-key-file", vk_file, "--batch-mode", "--key-file", "-", enc_out,
],
input="DiskPass#2026".encode("utf-8"),
text=False,
).decode("utf-8")
m_off = re.search(r"Payload offset:\s*(\d+)", dump)
assert m_off, dump
payload_offset = int(m_off.group(1)) * 512
assert os.path.getsize(enc_out) >= payload_offset + orig_bytes
with open(vk_file, "rb") as vf:
vk64 = vf.read()
dec_img = os.path.join(tmp, "dec-rootfs.img")
_xts_decrypt_ext4(enc_out, vk64, payload_offset, orig_bytes, dec_img)
e2 = subprocess.run(["e2fsck", "-fn", dec_img], capture_output=True, text=True)
assert e2.returncode == 0, f"Decrypted ext4 failed e2fsck: {e2.stdout}\n{e2.stderr}"
pw_txt = subprocess.check_output(["debugfs", "-R", "cat /etc/passwd", dec_img], text=True)
assert "luksuser:x:10000:10000::/home/luksuser:/bin/bash" in pw_txt, pw_txt
st = subprocess.run(
["debugfs", "-R", "stat /home/luksuser/.gitconfig", dec_img],
capture_output=True, text=True, check=True,
)
assert "Type: regular" in st.stdout, st.stdout
print("[PASS] Offline LUKS2 encryption, PTY passphrase unlock, and XTS-256 ext4 decryption verified")
def test_firmware_injection_ext4():
if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck")):
print("[SKIP] mke2fs/debugfs/e2fsck not available for firmware injection test")
return
fw_mod = flash_mtk.load_firmware_module()
with tempfile.TemporaryDirectory(prefix="geminux-fwinj-test-") as tmp:
sysroot = os.path.join(tmp, "sysroot")
os.makedirs(os.path.join(sysroot, "etc"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "home", "user"), exist_ok=True)
with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f:
f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n")
with open(os.path.join(sysroot, "etc", "group"), "w", encoding="utf-8") as f:
f.write("root:x:0:root\nuser:x:10000:\n")
with open(os.path.join(sysroot, "etc", "shadow"), "w", encoding="utf-8") as f:
f.write("root:*:::::::\nuser:*:::::::\n")
fw_dir = os.path.join(tmp, "fw")
os.makedirs(fw_dir, exist_ok=True)
expected_blobs = {
"WIFI_RAM_CODE_6797": b"WIFI_FW_HDR" * 100,
"WMT_SOC.cfg": b"cfg=1\n",
"ROMv3_patch_1_0_hdr.bin": b"ROM10",
"pcm_suspend.bin": b"PCM_SUSPEND",
}
for name, data in expected_blobs.items():
with open(os.path.join(fw_dir, name), "wb") as bf:
bf.write(data)
with open(os.path.join(fw_dir, "ignored.txt"), "w", encoding="utf-8") as uf:
uf.write("ignore-me\n")
img_dir = os.path.join(tmp, "images")
os.makedirs(img_dir, exist_ok=True)
orig_img = os.path.join(img_dir, "geminux-rootfs.img")
out_img = os.path.join(tmp, "out-rootfs.img")
subprocess.run(
["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, orig_img, "8M"],
check=True,
)
orig_sha = flash_mtk.sha256_file(orig_img)
res = subprocess.run(
[
os.path.join(BASE_DIR, "flash-mtk.sh"),
"--customize-rootfs", out_img,
"--images-dir", img_dir,
"--firmware-dir", fw_dir,
"--use-default-credentials",
],
capture_output=True, text=True, check=False,
)
assert res.returncode == 0, f"customize-rootfs fw inject failed: {res.stdout}\n{res.stderr}"
assert flash_mtk.sha256_file(orig_img) == orig_sha, "Source rootfs image was mutated!"
e2 = subprocess.run(["e2fsck", "-fn", out_img], capture_output=True, text=True)
assert e2.returncode == 0, f"e2fsck failed after fw inject: {e2.stdout}\n{e2.stderr}"
ls_entries = fw_mod.debugfs_ls(out_img, "lib/firmware/mediatek/mt6797")
assert set(ls_entries) == set(expected_blobs.keys()), ls_entries
for name, expected in expected_blobs.items():
dump_p = os.path.join(tmp, f"dump-{name}")
assert fw_mod.debugfs_dump(out_img, f"lib/firmware/mediatek/mt6797/{name}", dump_p)
with open(dump_p, "rb") as df:
assert df.read() == expected
st = subprocess.run(
["debugfs", "-R", f"stat /lib/firmware/mediatek/mt6797/{name}", out_img],
capture_output=True, text=True, check=True,
)
assert re.search(r"Mode:\s*0644\b", st.stdout), st.stdout
# Verify --skip-firmware-inject skips injection
out_skip = os.path.join(tmp, "out-skip.img")
res_skip = subprocess.run(
[
os.path.join(BASE_DIR, "flash-mtk.sh"),
"--customize-rootfs", out_skip,
"--images-dir", img_dir,
"--firmware-dir", fw_dir,
"--skip-firmware-inject",
"--use-default-credentials",
],
capture_output=True, text=True, check=False,
)
assert res_skip.returncode == 0, res_skip.stderr
assert fw_mod.debugfs_ls(out_skip, "lib/firmware/mediatek/mt6797") == []
print("[PASS] Offline MT6797 firmware ext4 injection verified")
def test_release_zip_packager():
import datetime
import zipfile
if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck")):
print("[SKIP] mke2fs/debugfs/e2fsck not available for release ZIP packager test")
return
pkg_mod = _load_mod(
"package_release_zip", os.path.join(SCRIPTS_DIR, "package-release-zip.py")
)
git_res = subprocess.run(
["git", "-C", BASE_DIR, "log", "-1", "--format=%ct %h"],
capture_output=True, text=True, check=True,
)
git_ts_str, git_sha = git_res.stdout.strip().split()
expected_date = datetime.datetime.fromtimestamp(
int(git_ts_str), tz=datetime.timezone.utc
).strftime("%Y%m%d")
expected_ver = f"{expected_date}-{git_sha}"
with tempfile.TemporaryDirectory(prefix="geminux-zip-test-") as tmp:
saved_ver = os.environ.pop("GEMINUX_VERSION", None)
saved_cname = os.environ.pop("GEMINUX_CODENAME", None)
try:
assert pkg_mod.resolve_release_version() == expected_ver
assert pkg_mod.resolve_release_version() != "0.1.0"
assert pkg_mod.resolve_release_version("custom-1.2") == "custom-1.2"
os.environ["GEMINUX_VERSION"] = "env-9.9"
assert pkg_mod.resolve_release_version() == "env-9.9"
os.environ.pop("GEMINUX_VERSION", None)
fallback_ver = pkg_mod.resolve_release_version(repo_dir=tmp)
assert isinstance(fallback_ver, str) and len(fallback_ver) > 0
finally:
if saved_ver is not None:
os.environ["GEMINUX_VERSION"] = saved_ver
else:
os.environ.pop("GEMINUX_VERSION", None)
if saved_cname is not None:
os.environ["GEMINUX_CODENAME"] = saved_cname
else:
os.environ.pop("GEMINUX_CODENAME", None)
sysroot = os.path.join(tmp, "sysroot")
os.makedirs(os.path.join(sysroot, "etc", "ssh"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "root", ".ssh"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "home", "user", ".ssh"), exist_ok=True)
os.makedirs(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797"), exist_ok=True)
with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f:
f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n")
with open(os.path.join(sysroot, "etc", "ssh", "sshd_config"), "w", encoding="utf-8") as f:
f.write("Port 22\n")
with open(os.path.join(sysroot, "etc", "ssh", "ssh_host_ed25519_key"), "w", encoding="utf-8") as f:
f.write("PRIVATE HOST KEY\n")
with open(os.path.join(sysroot, "etc", "ssh", "ssh_host_ed25519_key.pub"), "w", encoding="utf-8") as f:
f.write("ssh-ed25519 AAAAC3...\n")
with open(os.path.join(sysroot, "root", ".ssh", "authorized_keys"), "w", encoding="utf-8") as f:
f.write("ssh-ed25519 AAAA_USER_KEY\n")
with open(os.path.join(sysroot, "home", "user", ".ssh", "authorized_keys"), "w", encoding="utf-8") as f:
f.write("ssh-ed25519 AAAA_USER_KEY\n")
with open(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797", "WIFI_RAM_CODE_6797"), "wb") as f:
f.write(b"PROPRIETARY_WIFI_BLOB")
with open(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797", "MANIFEST.sha256"), "w", encoding="utf-8") as f:
f.write("abc WIFI_RAM_CODE_6797\n")
img_dir = os.path.join(tmp, "images")
os.makedirs(img_dir, exist_ok=True)
with open(os.path.join(img_dir, "boot-geminux.img"), "wb") as f:
f.write(b"ANDROID!" + b"\x00" * 4088)
with open(os.path.join(img_dir, "recovery-geminux.img"), "wb") as f:
f.write(b"ANDROID!" + b"\x11" * 4088)
root_img = os.path.join(img_dir, "geminux-rootfs.img")
subprocess.run(
["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, root_img, "8M"],
check=True,
)
orig_root_sha = flash_mtk.sha256_file(root_img)
pkg_env = dict(os.environ)
pkg_env.pop("GEMINUX_VERSION", None)
pkg_env.pop("GEMINUX_CODENAME", None)
top = f"geminux-{expected_ver}-helio-gemini-x27"
out_zip = os.path.join(tmp, f"{top}.zip")
res = subprocess.run(
[
os.path.join(BASE_DIR, "package-image.sh"),
"--images-dir", img_dir,
"--output", out_zip,
],
env=pkg_env, capture_output=True, text=True, check=False,
)
assert res.returncode == 0, f"package-image.sh failed:\n{res.stdout}\n{res.stderr}"
assert flash_mtk.sha256_file(root_img) == orig_root_sha, "Source rootfs image was mutated!"
assert os.path.isfile(out_zip) and os.path.isfile(out_zip + ".sha256")
with zipfile.ZipFile(out_zip, "r") as zf:
assert zf.testzip() is None
names = set(zf.namelist())
for req in (
f"{top}/FLASH-INSTRUCTIONS.txt",
f"{top}/SHA256SUMS.txt",
f"{top}/flash-mtk.sh",
f"{top}/flash-mtk.py",
f"{top}/images/boot-geminux.img",
f"{top}/images/recovery-geminux.img",
f"{top}/images/geminux-rootfs.img",
f"{top}/scripts/bootstrap-flash-deps.sh",
f"{top}/scripts/extract-vendor-fw.py",
f"{top}/scripts/geminux_accounts.py",
f"{top}/scripts/geminux_gpt.py",
f"{top}/scripts/geminux_luks.py",
f"{top}/vendor/mtkclient/mtkclient/Loader/MTK_DA_V5_MT6797.bin",
):
assert req in names, f"ZIP missing {req}"
assert not any("__pycache__" in n or n.endswith((".pyc", ".pyo")) for n in names), "Found bytecode in ZIP"
sh_info = zf.getinfo(f"{top}/flash-mtk.sh")
assert ((sh_info.external_attr >> 16) & 0o111) == 0o111, "flash-mtk.sh missing +x attr"
txt = zf.read(f"{top}/FLASH-INSTRUCTIONS.txt").decode("utf-8")
for needle in (
f"Release: {expected_ver} (helio)",
f"unzip {top}.zip",
"./flash-mtk.sh --flash-full",
"sha256sum -c SHA256SUMS.txt",
"LEFT USB-C port",
"Docker is NOT required",
):
assert needle in txt, f"FLASH-INSTRUCTIONS.txt missing {needle!r}"
assert "0.1.0" not in txt, "FLASH-INSTRUCTIONS.txt unexpectedly contains fallback version 0.1.0"
# Extract with unzip to verify preserved executable bits, SHA256SUMS, and flasher launch
ext_dir = os.path.join(tmp, "extracted")
os.makedirs(ext_dir, exist_ok=True)
subprocess.run(["unzip", "-q", out_zip, "-d", ext_dir], check=True)
rel_dir = os.path.join(ext_dir, top)
subprocess.run(["sha256sum", "-c", "SHA256SUMS.txt"], cwd=rel_dir, check=True, stdout=subprocess.DEVNULL)
ext_env = dict(os.environ)
if os.path.isdir(FLASH_DEPS):
ext_env["PYTHONPATH"] = FLASH_DEPS
hres = subprocess.run(
["./flash-mtk.sh", "--help"],
cwd=rel_dir, env=ext_env, capture_output=True, text=True, check=False,
)
assert hres.returncode == 0, f"Extracted flash-mtk.sh --help failed:\n{hres.stdout}\n{hres.stderr}"
sanitized_img = os.path.join(rel_dir, "images", "geminux-rootfs.img")
assert subprocess.run(["e2fsck", "-fn", sanitized_img], capture_output=True).returncode == 0
fw_mod = flash_mtk.load_firmware_module()
fw_entries = set(fw_mod.debugfs_ls(sanitized_img, "lib/firmware/mediatek/mt6797"))
assert {"WIFI_RAM_CODE_6797", "MANIFEST.sha256"}.issubset(fw_entries), (
f"Default package-image.sh must keep MT6797 firmware blobs; got {sorted(fw_entries)}"
)
assert [n for n, _m in pkg_mod._debugfs_ls_details(sanitized_img, "etc/ssh") if n.startswith("ssh_host_")] == []
assert "sshd_config" in fw_mod.debugfs_ls(sanitized_img, "etc/ssh")
assert not fw_mod._debugfs_path_exists(sanitized_img, "/root/.ssh/authorized_keys")
assert not fw_mod._debugfs_path_exists(sanitized_img, "/home/user/.ssh/authorized_keys")
stripped_top = "geminux-custom-ver-helio-gemini-x27"
stripped_zip = os.path.join(tmp, f"{stripped_top}-stripped.zip")
sres = subprocess.run(
[
os.path.join(BASE_DIR, "package-image.sh"),
"--images-dir", img_dir,
"--output", stripped_zip,
"--version", "custom-ver",
"--codename", "helio",
"--strip-firmware",
],
env=pkg_env, capture_output=True, text=True, check=False,
)
assert sres.returncode == 0, f"package-image.sh --strip-firmware failed:\n{sres.stdout}\n{sres.stderr}"
strip_dir = os.path.join(tmp, "extracted-stripped")
os.makedirs(strip_dir, exist_ok=True)
subprocess.run(["unzip", "-q", stripped_zip, "-d", strip_dir], check=True)
stripped_img = os.path.join(strip_dir, stripped_top, "images", "geminux-rootfs.img")
assert subprocess.run(["e2fsck", "-fn", stripped_img], capture_output=True).returncode == 0
assert fw_mod.debugfs_ls(stripped_img, "lib/firmware/mediatek/mt6797") == []
print("[PASS] Release ZIP packager (sanitized rootfs, FLASH-INSTRUCTIONS.txt, SHA256SUMS, runnable flasher) verified")
def test_cli_help():
res = subprocess.run(
[os.path.join(BASE_DIR, "flash-mtk.sh"), "--help"],
capture_output=True,
text=True,
check=False,
)
assert res.returncode == 0, res.stderr
for flag in (
"--only-backup",
"--flash-full",
"--flash-rootfs-only",
"--customize-rootfs",
"--skip-firmware-inject",
"--username",
"--user-password",
"--ask-user-password",
"--root-password",
"--ask-root-password",
"--use-default-credentials",
"--encrypt",
"--luks-password",
"--ask-luks-password",
"--reboot",
"--poweroff",
"--no-reboot",
"--wait-timeout",
):
assert flag in res.stdout, f"Missing CLI option {flag} in --help"
print("[PASS] flash-mtk.sh --help verified")
def main():
test_gpt_repartition()
test_write_safety()
test_firmware_extraction()
test_mtkclient_gpt_settings()
test_finish_da_session()
test_fast_preloader_handshake()
test_xflash_shutdown_wire_packet()
test_sha512_crypt_and_username_validation()
test_account_customization_ext4()
test_luks2_encryption_offline()
test_firmware_injection_ext4()
test_release_zip_packager()
test_cli_help()
if __name__ == "__main__":
main()