2026-11-22 10:49:59 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
"""Pure-Python MediaTek BROM/DA Flasher for Geminux (Gemini PDA MT6797X).
|
|
|
|
|
|
|
|
|
|
Uses vendored GPLv3 mtkclient transport (no proprietary MediaTek FlashTool).
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import argparse
|
2026-11-23 08:21:37 +02:00
|
|
|
import getpass
|
2026-11-22 10:49:59 +02:00
|
|
|
import hashlib
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
|
|
|
|
import shutil
|
|
|
|
|
import subprocess
|
|
|
|
|
import sys
|
|
|
|
|
import tempfile
|
|
|
|
|
import time
|
|
|
|
|
|
|
|
|
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
VENDOR_MTK = os.path.join(BASE_DIR, "vendor", "mtkclient")
|
|
|
|
|
SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts")
|
|
|
|
|
for p in (VENDOR_MTK, SCRIPTS_DIR):
|
|
|
|
|
if p not in sys.path:
|
|
|
|
|
sys.path.insert(0, p)
|
|
|
|
|
|
2026-11-23 08:21:37 +02:00
|
|
|
from geminux_accounts import (
|
|
|
|
|
AccountConfig,
|
|
|
|
|
customize_ext4_accounts,
|
|
|
|
|
sha512_crypt,
|
|
|
|
|
validate_username,
|
|
|
|
|
)
|
|
|
|
|
from geminux_luks import (
|
|
|
|
|
LuksConfig,
|
|
|
|
|
encrypt_ext4_image_luks2,
|
|
|
|
|
validate_luks_passphrase,
|
|
|
|
|
)
|
2026-11-22 10:49:59 +02:00
|
|
|
from geminux_gpt import (
|
|
|
|
|
SECTOR_SIZE,
|
|
|
|
|
GPT_ARRAY_SECTORS,
|
|
|
|
|
PROTECTED_END_LBA,
|
|
|
|
|
build_geminux_gpts,
|
|
|
|
|
parse_primary_gpt,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Critical factory/firmware/bootloader partitions blocked from accidental writes.
|
|
|
|
|
PROTECTED_PARTITIONS = frozenset({
|
|
|
|
|
"preloader",
|
|
|
|
|
"pgpt",
|
|
|
|
|
"sgpt",
|
|
|
|
|
"para",
|
|
|
|
|
"expdb",
|
|
|
|
|
"frp",
|
|
|
|
|
"nvcfg",
|
|
|
|
|
"nvdata",
|
|
|
|
|
"metadata",
|
|
|
|
|
"protect1",
|
|
|
|
|
"protect2",
|
|
|
|
|
"seccfg",
|
|
|
|
|
"oemkeystore",
|
|
|
|
|
"proinfo",
|
|
|
|
|
"md1img",
|
|
|
|
|
"md1dsp",
|
|
|
|
|
"md1arm7",
|
|
|
|
|
"md3img",
|
|
|
|
|
"scp1",
|
|
|
|
|
"scp2",
|
|
|
|
|
"nvram",
|
|
|
|
|
"lk",
|
|
|
|
|
"lk2",
|
|
|
|
|
"logo",
|
|
|
|
|
"tee1",
|
|
|
|
|
"tee2",
|
|
|
|
|
"keystore",
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
BACKUP_PARTITIONS = (
|
|
|
|
|
"proinfo",
|
|
|
|
|
"nvram",
|
|
|
|
|
"protect1",
|
|
|
|
|
"protect2",
|
|
|
|
|
"nvcfg",
|
|
|
|
|
"nvdata",
|
|
|
|
|
"seccfg",
|
|
|
|
|
"para",
|
|
|
|
|
"lk",
|
|
|
|
|
"lk2",
|
|
|
|
|
"tee1",
|
|
|
|
|
"tee2",
|
|
|
|
|
"md1img",
|
|
|
|
|
"md1dsp",
|
|
|
|
|
"md1arm7",
|
|
|
|
|
"md3img",
|
|
|
|
|
"scp1",
|
|
|
|
|
"scp2",
|
|
|
|
|
"boot",
|
|
|
|
|
"recovery",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
SPARSE_MAGIC = b"\x3a\xff\x26\xed"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def sha256_bytes(data):
|
|
|
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def sha256_file(path):
|
|
|
|
|
h = hashlib.sha256()
|
|
|
|
|
with open(path, "rb") as f:
|
|
|
|
|
while True:
|
|
|
|
|
chunk = f.read(1048576)
|
|
|
|
|
if not chunk:
|
|
|
|
|
break
|
|
|
|
|
h.update(chunk)
|
|
|
|
|
return h.hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def enforce_write_safety(partition_name, allow_protected=False):
|
|
|
|
|
"""Reject writes to protected MediaTek calibration/radio/bootloader partitions."""
|
|
|
|
|
if partition_name.lower() in PROTECTED_PARTITIONS and not allow_protected:
|
|
|
|
|
raise PermissionError(
|
|
|
|
|
f"Refusing to overwrite protected partition '{partition_name}'. "
|
|
|
|
|
"Pass --restore-backup or --danger-allow-protected only if you are certain."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def create_mtk_config(loader_path=None, preloader_path=None, verbose=False, wait_timeout=300):
|
|
|
|
|
from mtkclient.config.mtk_config import MtkConfig
|
|
|
|
|
from mtkclient.Library.Partitions.gpt import GptSettings
|
|
|
|
|
|
|
|
|
|
loglevel = logging.DEBUG if verbose else logging.INFO
|
|
|
|
|
cfg = MtkConfig(loglevel=loglevel, gui=None, guiprogress=None)
|
|
|
|
|
cfg.gpt_settings = GptSettings(0, 0, 0)
|
|
|
|
|
cfg.wait_timeout = wait_timeout
|
|
|
|
|
if loader_path:
|
|
|
|
|
if not os.path.isfile(loader_path):
|
|
|
|
|
raise FileNotFoundError(f"DA loader not found: {loader_path}")
|
|
|
|
|
cfg.loader = loader_path
|
|
|
|
|
if preloader_path and os.path.isfile(preloader_path):
|
|
|
|
|
cfg.preloader_filename = preloader_path
|
|
|
|
|
with open(preloader_path, "rb") as f:
|
|
|
|
|
cfg.preloader = f.read()
|
|
|
|
|
return cfg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def connect_mtk(loader_path=None, preloader_path=None, verbose=False, wait_timeout=300):
|
|
|
|
|
from mtkclient.Library.mtk_class import Mtk
|
|
|
|
|
from mtkclient.Library.DA.mtk_da_handler import DaHandler
|
|
|
|
|
|
|
|
|
|
loglevel = logging.DEBUG if verbose else logging.INFO
|
|
|
|
|
cfg = create_mtk_config(
|
|
|
|
|
loader_path=loader_path,
|
|
|
|
|
preloader_path=preloader_path,
|
|
|
|
|
verbose=verbose,
|
|
|
|
|
wait_timeout=wait_timeout,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
mtk = Mtk(config=cfg, loglevel=loglevel)
|
|
|
|
|
da_handler = DaHandler(mtk, loglevel)
|
|
|
|
|
wait_desc = f"up to {wait_timeout}s" if wait_timeout > 0 else "indefinitely"
|
|
|
|
|
print(
|
|
|
|
|
f"[*] Waiting {wait_desc} for Gemini PDA on left USB-C port "
|
|
|
|
|
"(plug in powered-off PDA, or hold Esc + side Power for ~12s to force-reset)..."
|
|
|
|
|
)
|
|
|
|
|
mtk = da_handler.connect(mtk, BASE_DIR)
|
|
|
|
|
if mtk is None:
|
|
|
|
|
raise RuntimeError("Failed to establish MediaTek BROM/Preloader connection")
|
|
|
|
|
mtk = da_handler.configure_da(mtk)
|
|
|
|
|
if mtk is None:
|
|
|
|
|
raise RuntimeError("Failed to initialize MediaTek Download Agent (DA)")
|
|
|
|
|
return mtk, da_handler
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_emmc_total_sectors(mtk):
|
|
|
|
|
flashsize = mtk.daloader.daconfig.storage.flashsize
|
|
|
|
|
if not flashsize:
|
|
|
|
|
raise RuntimeError("DA reported zero eMMC flash size")
|
|
|
|
|
return flashsize // SECTOR_SIZE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def run_backup(mtk, da_handler, backup_dir):
|
|
|
|
|
os.makedirs(backup_dir, exist_ok=True)
|
|
|
|
|
print(f"[*] Backing up Gemini PDA critical partitions into {backup_dir}...")
|
|
|
|
|
manifest = {}
|
|
|
|
|
|
|
|
|
|
# Dump primary GPT (34 sectors = 17 KiB) and backup GPT (last 33 sectors)
|
|
|
|
|
total_sectors = get_emmc_total_sectors(mtk)
|
|
|
|
|
pgpt_path = os.path.join(backup_dir, "pgpt.bin")
|
|
|
|
|
if not da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, pgpt_path, "user", display=True):
|
|
|
|
|
raise RuntimeError("Failed to read primary GPT (pgpt)")
|
|
|
|
|
manifest["pgpt.bin"] = sha256_file(pgpt_path)
|
|
|
|
|
|
|
|
|
|
sgpt_lba = total_sectors - (GPT_ARRAY_SECTORS + 1)
|
|
|
|
|
sgpt_path = os.path.join(backup_dir, "sgpt.bin")
|
|
|
|
|
if not da_handler.da_rs(sgpt_lba, GPT_ARRAY_SECTORS + 1, sgpt_path, "user", display=True):
|
|
|
|
|
raise RuntimeError("Failed to read backup GPT (sgpt)")
|
|
|
|
|
manifest["sgpt.bin"] = sha256_file(sgpt_path)
|
|
|
|
|
|
|
|
|
|
# Dump EMMC_BOOT1 preloader
|
|
|
|
|
pre_path = os.path.join(backup_dir, "preloader.bin")
|
|
|
|
|
if da_handler.da_read("preloader", "boot1", pre_path, display=True) is not None and os.path.isfile(pre_path):
|
|
|
|
|
manifest["preloader.bin"] = sha256_file(pre_path)
|
|
|
|
|
|
|
|
|
|
for part in BACKUP_PARTITIONS:
|
|
|
|
|
out_file = os.path.join(backup_dir, f"{part}.img")
|
|
|
|
|
da_handler.da_read(part, "user", out_file, display=True)
|
|
|
|
|
if not os.path.isfile(out_file) or os.path.getsize(out_file) == 0:
|
|
|
|
|
raise RuntimeError(f"Backup failed or empty for partition '{part}'")
|
|
|
|
|
manifest[f"{part}.img"] = sha256_file(out_file)
|
|
|
|
|
|
|
|
|
|
# Sanity check nvram is non-zero
|
|
|
|
|
nvram_file = os.path.join(backup_dir, "nvram.img")
|
|
|
|
|
with open(nvram_file, "rb") as f:
|
|
|
|
|
sample = f.read(4096)
|
|
|
|
|
if sample == b"\x00" * len(sample):
|
|
|
|
|
print("[!] Warning: first 4 KiB of nvram.img is all zeros; verify backup before flashing!")
|
|
|
|
|
|
|
|
|
|
manifest_path = os.path.join(backup_dir, "MANIFEST.sha256")
|
|
|
|
|
with open(manifest_path, "w") as mf:
|
|
|
|
|
for name in sorted(manifest):
|
|
|
|
|
mf.write(f"{manifest[name]} {name}\n")
|
|
|
|
|
print(f"[+] Backup verified and written to {backup_dir} ({len(manifest)} files).")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def verify_written_partition(da_handler, part_name, expected_path):
|
|
|
|
|
expected_size = os.path.getsize(expected_path)
|
|
|
|
|
expected_hash = sha256_file(expected_path)
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-vfy-") as tmp:
|
|
|
|
|
rb = os.path.join(tmp, f"{part_name}.readback.img")
|
|
|
|
|
da_handler.da_read(part_name, "user", rb, offset=0, length=expected_size, display=False)
|
|
|
|
|
if not os.path.isfile(rb) or os.path.getsize(rb) != expected_size:
|
|
|
|
|
actual_sz = os.path.getsize(rb) if os.path.isfile(rb) else 0
|
|
|
|
|
raise RuntimeError(
|
|
|
|
|
f"Readback failed for '{part_name}': expected {expected_size} B, got {actual_sz} B"
|
|
|
|
|
)
|
|
|
|
|
actual_hash = sha256_file(rb)
|
|
|
|
|
if actual_hash != expected_hash:
|
|
|
|
|
raise RuntimeError(
|
|
|
|
|
f"Readback verification FAILED for '{part_name}': expected {expected_hash}, got {actual_hash}"
|
|
|
|
|
)
|
|
|
|
|
print(f"[+] Readback SHA-256 verified for '{part_name}' ({expected_size} bytes).")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write_partition_checked(da_handler, part_name, img_path, verify=True, allow_protected=False):
|
|
|
|
|
enforce_write_safety(part_name, allow_protected=allow_protected)
|
|
|
|
|
if not os.path.isfile(img_path):
|
|
|
|
|
raise FileNotFoundError(f"Image not found: {img_path}")
|
|
|
|
|
found, res = da_handler.mtk.daloader.detect_partition(part_name, "user")
|
|
|
|
|
if not found or res is None:
|
|
|
|
|
raise RuntimeError(f"Partition '{part_name}' not found on device")
|
|
|
|
|
part_bytes = res.sectors * da_handler.config.pagesize
|
|
|
|
|
img_size = os.path.getsize(img_path)
|
|
|
|
|
if img_size > part_bytes:
|
|
|
|
|
raise RuntimeError(
|
|
|
|
|
f"Image '{img_path}' ({img_size} B) exceeds partition '{part_name}' ({part_bytes} B)"
|
|
|
|
|
)
|
|
|
|
|
print(f"[*] Flashing '{part_name}' from {img_path}...")
|
|
|
|
|
ok = da_handler.mtk.daloader.writeflash(
|
|
|
|
|
addr=res.sector * da_handler.config.pagesize,
|
|
|
|
|
length=part_bytes,
|
|
|
|
|
filename=img_path,
|
|
|
|
|
parttype="user",
|
|
|
|
|
display=True,
|
|
|
|
|
)
|
|
|
|
|
if not ok:
|
|
|
|
|
raise RuntimeError(f"Failed to write partition '{part_name}' from {img_path}")
|
|
|
|
|
if verify:
|
|
|
|
|
verify_written_partition(da_handler, part_name, img_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_extract_firmware():
|
|
|
|
|
import importlib.util
|
|
|
|
|
fw_path = os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py")
|
|
|
|
|
sp = importlib.util.spec_from_file_location("extract_vendor_fw", fw_path)
|
|
|
|
|
mod = importlib.util.module_from_spec(sp)
|
|
|
|
|
sp.loader.exec_module(mod)
|
|
|
|
|
return mod.extract_firmware
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def extract_fw_from_device(da_handler, fw_out_dir):
|
|
|
|
|
extract_firmware = load_extract_firmware()
|
|
|
|
|
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-sys-") as tmp:
|
|
|
|
|
sys_img = os.path.join(tmp, "system.img")
|
|
|
|
|
print("[*] Reading stock 'system' partition to extract Wi-Fi/BT/SPM firmware blobs...")
|
|
|
|
|
da_handler.da_read("system", "user", sys_img, display=True)
|
|
|
|
|
if not os.path.isfile(sys_img) or os.path.getsize(sys_img) == 0:
|
|
|
|
|
raise RuntimeError("Could not read stock 'system' partition")
|
|
|
|
|
found, missing = extract_firmware(sys_img, fw_out_dir)
|
|
|
|
|
if missing:
|
|
|
|
|
print(f"[!] Warning: missing firmware blobs from stock system: {', '.join(missing)}")
|
|
|
|
|
else:
|
|
|
|
|
print(f"[+] Extracted {len(found)} firmware blob(s) to {fw_out_dir}.")
|
|
|
|
|
|
|
|
|
|
|
2026-11-23 08:21:37 +02:00
|
|
|
def prompt_confirmed_password(label, required=False):
|
|
|
|
|
"""Prompt securely via TTY for a password and confirmation."""
|
|
|
|
|
while True:
|
|
|
|
|
hint = "" if required else " (Enter to keep image default)"
|
|
|
|
|
pw = getpass.getpass(f"Password for '{label}'{hint}: ")
|
|
|
|
|
if not pw:
|
|
|
|
|
if required:
|
|
|
|
|
print("[!] Password cannot be empty.")
|
|
|
|
|
continue
|
|
|
|
|
return None
|
|
|
|
|
if any(ch in pw for ch in ("\x00", "\n", "\r")):
|
|
|
|
|
print("[!] Password must not contain NUL or newline characters.")
|
|
|
|
|
continue
|
|
|
|
|
pw2 = getpass.getpass(f"Confirm password for '{label}': ")
|
|
|
|
|
if pw != pw2:
|
|
|
|
|
print("[!] Passwords do not match; try again.")
|
|
|
|
|
continue
|
|
|
|
|
return pw
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def resolve_account_config(args, interactive=None):
|
|
|
|
|
"""Resolve username and SHA-512 ($6$) hashes before connecting USB."""
|
|
|
|
|
if args.user_password is not None and args.ask_user_password:
|
|
|
|
|
raise ValueError("Cannot combine --user-password and --ask-user-password")
|
|
|
|
|
if args.root_password is not None and args.ask_root_password:
|
|
|
|
|
raise ValueError("Cannot combine --root-password and --ask-root-password")
|
|
|
|
|
|
|
|
|
|
is_tty = sys.stdin.isatty() if interactive is None else bool(interactive)
|
|
|
|
|
prompt_interactive = is_tty and not args.use_default_credentials
|
|
|
|
|
|
|
|
|
|
username = args.username
|
|
|
|
|
if username is not None:
|
|
|
|
|
validate_username(username)
|
|
|
|
|
elif prompt_interactive:
|
|
|
|
|
while True:
|
|
|
|
|
entered = input("Desktop username [user]: ").strip()
|
|
|
|
|
if not entered:
|
|
|
|
|
username = None
|
|
|
|
|
break
|
|
|
|
|
try:
|
|
|
|
|
username = validate_username(entered)
|
|
|
|
|
break
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
print(f"[!] {exc}")
|
|
|
|
|
|
|
|
|
|
eff_user = username or "user"
|
|
|
|
|
|
|
|
|
|
if args.user_password is not None:
|
|
|
|
|
user_pw = args.user_password
|
|
|
|
|
elif args.ask_user_password:
|
|
|
|
|
user_pw = prompt_confirmed_password(eff_user, required=True)
|
|
|
|
|
elif prompt_interactive:
|
|
|
|
|
user_pw = prompt_confirmed_password(eff_user, required=False)
|
|
|
|
|
else:
|
|
|
|
|
user_pw = None
|
|
|
|
|
|
|
|
|
|
if args.root_password is not None:
|
|
|
|
|
root_pw = args.root_password
|
|
|
|
|
elif args.ask_root_password:
|
|
|
|
|
root_pw = prompt_confirmed_password("root", required=True)
|
|
|
|
|
elif prompt_interactive:
|
|
|
|
|
root_pw = prompt_confirmed_password("root", required=False)
|
|
|
|
|
else:
|
|
|
|
|
root_pw = None
|
|
|
|
|
|
|
|
|
|
user_pw_hash = sha512_crypt(user_pw) if user_pw is not None else None
|
|
|
|
|
root_pw_hash = sha512_crypt(root_pw) if root_pw is not None else None
|
|
|
|
|
return AccountConfig(
|
|
|
|
|
username=username,
|
|
|
|
|
user_pw_hash=user_pw_hash,
|
|
|
|
|
root_pw_hash=root_pw_hash,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def resolve_luks_config(args, interactive=None):
|
|
|
|
|
"""Resolve optional LUKS2 encryption passphrase before connecting USB."""
|
|
|
|
|
if args.luks_password is not None and args.ask_luks_password:
|
|
|
|
|
raise ValueError("Cannot combine --luks-password and --ask-luks-password")
|
|
|
|
|
|
|
|
|
|
if args.luks_password is not None:
|
|
|
|
|
validate_luks_passphrase(args.luks_password)
|
|
|
|
|
return LuksConfig(enabled=True, passphrase=args.luks_password)
|
|
|
|
|
|
|
|
|
|
if args.ask_luks_password or args.encrypt:
|
|
|
|
|
pw = prompt_confirmed_password("LUKS2 disk encryption", required=True)
|
|
|
|
|
return LuksConfig(enabled=True, passphrase=pw)
|
|
|
|
|
|
|
|
|
|
is_tty = sys.stdin.isatty() if interactive is None else bool(interactive)
|
|
|
|
|
if is_tty and not args.use_default_credentials and not args.customize_rootfs:
|
|
|
|
|
while True:
|
|
|
|
|
ans = input("Enable LUKS2 full-disk encryption? [y/N]: ").strip().lower()
|
|
|
|
|
if ans in ("", "n", "no"):
|
|
|
|
|
break
|
|
|
|
|
if ans in ("y", "yes"):
|
|
|
|
|
pw = prompt_confirmed_password("LUKS2 disk encryption", required=True)
|
|
|
|
|
return LuksConfig(enabled=True, passphrase=pw)
|
|
|
|
|
print("[!] Please answer 'y' or 'n'.")
|
|
|
|
|
|
|
|
|
|
return LuksConfig(enabled=False, passphrase=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def copy_raw_image(src, dst):
|
|
|
|
|
if shutil.which("cp"):
|
|
|
|
|
subprocess.run(["cp", "--reflink=auto", "--sparse=always", src, dst], check=True)
|
|
|
|
|
else:
|
|
|
|
|
shutil.copyfile(src, dst)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def stage_rootfs_image(root_img, account_cfg, tmp_dir, always_copy=False, luks_cfg=None):
|
|
|
|
|
"""Unsparse if needed and apply offline account/LUKS2 provisioning in tmp_dir."""
|
|
|
|
|
if not os.path.isfile(root_img):
|
|
|
|
|
raise FileNotFoundError(f"Rootfs image not found: {root_img}")
|
|
|
|
|
with open(root_img, "rb") as rf:
|
|
|
|
|
is_sparse = rf.read(4) == SPARSE_MAGIC
|
|
|
|
|
|
|
|
|
|
has_changes = bool(account_cfg and account_cfg.has_changes)
|
|
|
|
|
has_luks = bool(luks_cfg and luks_cfg.enabled)
|
|
|
|
|
if not is_sparse and not has_changes and not has_luks and not always_copy:
|
|
|
|
|
return root_img
|
|
|
|
|
|
|
|
|
|
staged = os.path.join(tmp_dir, "linux.raw.img")
|
|
|
|
|
if is_sparse:
|
|
|
|
|
if shutil.which("simg2img") is None:
|
|
|
|
|
raise RuntimeError("simg2img is required to unsparse geminux-rootfs.img")
|
|
|
|
|
subprocess.run(["simg2img", root_img, staged], check=True)
|
|
|
|
|
else:
|
|
|
|
|
copy_raw_image(root_img, staged)
|
|
|
|
|
|
|
|
|
|
if has_changes:
|
|
|
|
|
customize_ext4_accounts(
|
|
|
|
|
staged,
|
|
|
|
|
new_username=account_cfg.username,
|
|
|
|
|
user_pw_hash=account_cfg.user_pw_hash,
|
|
|
|
|
root_pw_hash=account_cfg.root_pw_hash,
|
|
|
|
|
)
|
|
|
|
|
summary = []
|
|
|
|
|
if account_cfg.username:
|
|
|
|
|
summary.append(f"username={account_cfg.username}")
|
|
|
|
|
if account_cfg.user_pw_hash:
|
|
|
|
|
summary.append("user password updated")
|
|
|
|
|
if account_cfg.root_pw_hash:
|
|
|
|
|
summary.append("root password updated")
|
|
|
|
|
print(f"[+] Provisioned rootfs credentials ({', '.join(summary)}).")
|
|
|
|
|
|
|
|
|
|
if has_luks:
|
|
|
|
|
print("[*] Encrypting staged rootfs image with LUKS2 (aes-xts-plain64, Argon2id)...")
|
|
|
|
|
encrypt_ext4_image_luks2(staged, luks_cfg.passphrase)
|
|
|
|
|
print("[+] LUKS2 full-disk encryption image verified.")
|
|
|
|
|
|
|
|
|
|
return staged
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def customize_rootfs_offline(args, account_cfg, luks_cfg=None):
|
|
|
|
|
"""Write an offline customized (and optionally LUKS2-encrypted) rootfs copy."""
|
|
|
|
|
root_img = os.path.join(args.images_dir, "geminux-rootfs.img")
|
|
|
|
|
out_img = os.path.abspath(args.customize_rootfs)
|
|
|
|
|
out_dir = os.path.dirname(out_img) or "."
|
|
|
|
|
os.makedirs(out_dir, exist_ok=True)
|
|
|
|
|
has_luks = bool(luks_cfg and luks_cfg.enabled)
|
|
|
|
|
with tempfile.TemporaryDirectory(dir=out_dir, prefix=".geminux-cust-") as tmp:
|
|
|
|
|
staged = stage_rootfs_image(
|
|
|
|
|
root_img, account_cfg, tmp, always_copy=True, luks_cfg=luks_cfg
|
|
|
|
|
)
|
|
|
|
|
if not has_luks and (not account_cfg or not account_cfg.has_changes) and shutil.which("e2fsck"):
|
|
|
|
|
subprocess.run(["e2fsck", "-fn", staged], check=True, stdout=subprocess.DEVNULL)
|
|
|
|
|
os.replace(staged, out_img)
|
|
|
|
|
kind = "LUKS2-encrypted" if has_luks else "customized ext4"
|
|
|
|
|
print(f"[+] Wrote {kind} rootfs image to {out_img}.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def flash_full(mtk, da_handler, args, account_cfg=None, luks_cfg=None):
|
2026-11-22 10:49:59 +02:00
|
|
|
backup_dir = args.backup_dir
|
|
|
|
|
if not args.skip_backup:
|
|
|
|
|
run_backup(mtk, da_handler, backup_dir)
|
|
|
|
|
elif not os.path.isdir(backup_dir) or not os.path.isfile(os.path.join(backup_dir, "nvram.img")):
|
|
|
|
|
raise RuntimeError("--skip-backup passed, but no valid nvram.img found in backup dir")
|
|
|
|
|
|
|
|
|
|
if not args.skip_firmware_extract:
|
|
|
|
|
req_check = os.path.join(args.firmware_dir, "WIFI_RAM_CODE_6797")
|
|
|
|
|
if not os.path.isfile(req_check):
|
|
|
|
|
extract_fw_from_device(da_handler, args.firmware_dir)
|
|
|
|
|
print("[*] Note: Rebuild rootfs image if extracted firmware was not yet bundled in images/geminux-rootfs.img.")
|
|
|
|
|
|
|
|
|
|
total_sectors = get_emmc_total_sectors(mtk)
|
|
|
|
|
pgpt_raw = da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, "", "user", display=False)
|
|
|
|
|
if isinstance(pgpt_raw, bool) or not pgpt_raw:
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-gpt-") as tmp:
|
|
|
|
|
pfile = os.path.join(tmp, "pgpt.bin")
|
|
|
|
|
if not da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, pfile, "user", display=False):
|
|
|
|
|
raise RuntimeError("Failed to read live primary GPT")
|
|
|
|
|
with open(pfile, "rb") as f:
|
|
|
|
|
pgpt_raw = f.read()
|
|
|
|
|
|
|
|
|
|
new_pgpt, new_sgpt, new_entries = build_geminux_gpts(
|
|
|
|
|
pgpt_raw, total_sectors, force_layout=args.force_gpt
|
|
|
|
|
)
|
|
|
|
|
linux_entry = next(e for e in new_entries if e.name == "linux")
|
|
|
|
|
boot2_entry = next(e for e in new_entries if e.name == "boot2")
|
|
|
|
|
print(
|
|
|
|
|
f"[*] Repartitioning eMMC ({total_sectors} sectors): "
|
|
|
|
|
f"linux={linux_entry.sectors * SECTOR_SIZE / (1024 ** 3):.2f} GiB @ LBA {linux_entry.first_lba}, "
|
|
|
|
|
f"boot2=16 MiB @ LBA {boot2_entry.first_lba}"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-newgpt-") as tmp:
|
|
|
|
|
pgpt_out = os.path.join(tmp, "pgpt.new.bin")
|
|
|
|
|
sgpt_out = os.path.join(tmp, "sgpt.new.bin")
|
|
|
|
|
with open(pgpt_out, "wb") as f:
|
|
|
|
|
f.write(new_pgpt)
|
|
|
|
|
with open(sgpt_out, "wb") as f:
|
|
|
|
|
f.write(new_sgpt)
|
|
|
|
|
|
|
|
|
|
# Write Primary GPT (LBA 0..33) & Backup GPT (end of disk)
|
|
|
|
|
if not da_handler.da_wo(0, len(new_pgpt), pgpt_out, "user"):
|
|
|
|
|
raise RuntimeError("Failed writing updated primary GPT")
|
|
|
|
|
sgpt_byte_off = (total_sectors - (GPT_ARRAY_SECTORS + 1)) * SECTOR_SIZE
|
|
|
|
|
if not da_handler.da_wo(sgpt_byte_off, len(new_sgpt), sgpt_out, "user"):
|
|
|
|
|
raise RuntimeError("Failed writing updated backup GPT")
|
|
|
|
|
|
|
|
|
|
# Mandatory readback check on written GPTs
|
|
|
|
|
rb_pgpt = os.path.join(tmp, "pgpt.rb.bin")
|
|
|
|
|
da_handler.da_rs(0, 2 + GPT_ARRAY_SECTORS, rb_pgpt, "user", display=False)
|
|
|
|
|
with open(rb_pgpt, "rb") as f:
|
|
|
|
|
if f.read(len(new_pgpt)) != new_pgpt:
|
|
|
|
|
raise RuntimeError("Primary GPT readback verification FAILED!")
|
|
|
|
|
print("[+] Updated GPT readback verified.")
|
|
|
|
|
|
|
|
|
|
boot_img = os.path.join(args.images_dir, "boot-geminux.img")
|
|
|
|
|
rec_img = os.path.join(args.images_dir, "recovery-geminux.img")
|
|
|
|
|
root_img = os.path.join(args.images_dir, "geminux-rootfs.img")
|
|
|
|
|
|
|
|
|
|
write_partition_checked(da_handler, "boot", boot_img, verify=True)
|
|
|
|
|
write_partition_checked(da_handler, "recovery", rec_img, verify=True)
|
|
|
|
|
write_partition_checked(da_handler, "boot2", boot_img, verify=True)
|
|
|
|
|
|
2026-11-23 08:21:37 +02:00
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-stage-") as tmp:
|
|
|
|
|
staged_root = stage_rootfs_image(root_img, account_cfg, tmp, luks_cfg=luks_cfg)
|
|
|
|
|
write_partition_checked(da_handler, "linux", staged_root, verify=False)
|
2026-11-22 10:49:59 +02:00
|
|
|
|
|
|
|
|
print("[+] Full Geminux installation complete!")
|
|
|
|
|
|
|
|
|
|
|
2026-11-23 08:21:37 +02:00
|
|
|
def flash_rootfs_only(da_handler, args, account_cfg=None, luks_cfg=None):
|
|
|
|
|
root_img = os.path.join(args.images_dir, "geminux-rootfs.img")
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="geminux-stage-") as tmp:
|
|
|
|
|
staged_root = stage_rootfs_image(root_img, account_cfg, tmp, luks_cfg=luks_cfg)
|
|
|
|
|
write_partition_checked(da_handler, "linux", staged_root, verify=False)
|
|
|
|
|
print("[+] Geminux rootfs update complete!")
|
|
|
|
|
|
|
|
|
|
|
2026-11-22 10:49:59 +02:00
|
|
|
def flash_kernel_only(da_handler, args):
|
|
|
|
|
boot_img = os.path.join(args.images_dir, "boot-geminux.img")
|
|
|
|
|
rec_img = os.path.join(args.images_dir, "recovery-geminux.img")
|
|
|
|
|
write_partition_checked(da_handler, "boot", boot_img, verify=True)
|
|
|
|
|
write_partition_checked(da_handler, "boot2", boot_img, verify=True)
|
|
|
|
|
if os.path.isfile(rec_img):
|
|
|
|
|
write_partition_checked(da_handler, "recovery", rec_img, verify=True)
|
|
|
|
|
print("[+] Kernel/recovery slots updated cleanly.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def restore_backup(mtk, da_handler, backup_dir):
|
|
|
|
|
if not os.path.isdir(backup_dir):
|
|
|
|
|
raise FileNotFoundError(f"Backup directory not found: {backup_dir}")
|
|
|
|
|
pgpt_file = os.path.join(backup_dir, "pgpt.bin")
|
|
|
|
|
sgpt_file = os.path.join(backup_dir, "sgpt.bin")
|
|
|
|
|
if os.path.isfile(pgpt_file):
|
|
|
|
|
da_handler.da_wo(0, os.path.getsize(pgpt_file), pgpt_file, "user")
|
|
|
|
|
if os.path.isfile(sgpt_file):
|
|
|
|
|
total_sectors = get_emmc_total_sectors(mtk)
|
|
|
|
|
sgpt_off = (total_sectors - (GPT_ARRAY_SECTORS + 1)) * SECTOR_SIZE
|
|
|
|
|
da_handler.da_wo(sgpt_off, os.path.getsize(sgpt_file), sgpt_file, "user")
|
|
|
|
|
|
|
|
|
|
for name in sorted(os.listdir(backup_dir)):
|
|
|
|
|
if not name.endswith(".img"):
|
|
|
|
|
continue
|
|
|
|
|
part = name[:-4]
|
|
|
|
|
path = os.path.join(backup_dir, name)
|
|
|
|
|
write_partition_checked(da_handler, part, path, verify=False, allow_protected=True)
|
|
|
|
|
print(f"[+] Restored backup from {backup_dir}.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def finish_da_session(mtk, reboot=False):
|
|
|
|
|
"""Cleanly exit DA mode by rebooting to OS (bootmode=1) or powering off (bootmode=0)."""
|
|
|
|
|
state_file = os.path.join(getattr(mtk.config, "hwparam_path", "."), ".state")
|
|
|
|
|
if os.path.exists(state_file):
|
|
|
|
|
try:
|
|
|
|
|
os.remove(state_file)
|
|
|
|
|
except OSError:
|
|
|
|
|
pass
|
|
|
|
|
bootmode = 1 if reboot else 0
|
|
|
|
|
print("[*] Handing device back to bootloader (USB disconnect is expected)...")
|
|
|
|
|
try:
|
|
|
|
|
mtk.daloader.shutdown(bootmode=bootmode)
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
logging.debug("DA shutdown handshake raised %s", exc)
|
|
|
|
|
try:
|
|
|
|
|
mtk.port.close()
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def build_arg_parser():
|
|
|
|
|
p = argparse.ArgumentParser(
|
|
|
|
|
description="Geminux pure-Linux MediaTek BROM/DA Flasher for Planet Computers Gemini PDA (x27)"
|
|
|
|
|
)
|
|
|
|
|
mode = p.add_mutually_exclusive_group()
|
|
|
|
|
mode.add_argument("--flash-full", action="store_true",
|
|
|
|
|
help="Backup device, repartition full eMMC for Geminux, and flash all images (default)")
|
|
|
|
|
mode.add_argument("--only-backup", action="store_true",
|
|
|
|
|
help="Only dump & verify GPT, nvram, bootloader, and radio partitions")
|
|
|
|
|
mode.add_argument("--extract-firmware", action="store_true",
|
|
|
|
|
help="Extract MT6797 Wi-Fi/BT/SPM blobs from device 'system' or --system-img")
|
|
|
|
|
mode.add_argument("--flash-kernel-only", action="store_true",
|
|
|
|
|
help="Update only boot, boot2, and recovery images without touching GPT or linux")
|
2026-11-23 08:21:37 +02:00
|
|
|
mode.add_argument("--flash-rootfs-only", action="store_true",
|
|
|
|
|
help="Update only the linux rootfs partition without touching GPT or boot/recovery")
|
|
|
|
|
mode.add_argument("--customize-rootfs", metavar="OUT_IMG",
|
|
|
|
|
help="Offline: write customized geminux-rootfs.img to OUT_IMG without USB flashing")
|
2026-11-22 10:49:59 +02:00
|
|
|
mode.add_argument("--restore-backup", metavar="DIR",
|
|
|
|
|
help="Restore GPT and backed-up partitions from DIR")
|
|
|
|
|
mode.add_argument("--reboot", action="store_true",
|
|
|
|
|
help="Connect to BROM/DA and trigger immediate device reboot")
|
|
|
|
|
mode.add_argument("--poweroff", action="store_true",
|
|
|
|
|
help="Connect to BROM/DA and cleanly power off out of DA mode")
|
|
|
|
|
|
2026-11-23 08:21:37 +02:00
|
|
|
creds = p.add_argument_group("Account & credential options")
|
|
|
|
|
creds.add_argument("--username", metavar="USER",
|
|
|
|
|
help="Desktop account username (UID 10000; default in image: user)")
|
|
|
|
|
creds.add_argument("--user-password", metavar="PASS",
|
|
|
|
|
help="Set desktop user password non-interactively")
|
|
|
|
|
creds.add_argument("--ask-user-password", action="store_true",
|
|
|
|
|
help="Prompt securely for desktop user password before flashing")
|
|
|
|
|
creds.add_argument("--root-password", metavar="PASS",
|
|
|
|
|
help="Set root password non-interactively")
|
|
|
|
|
creds.add_argument("--ask-root-password", action="store_true",
|
|
|
|
|
help="Prompt securely for root password before flashing")
|
|
|
|
|
creds.add_argument("--use-default-credentials", action="store_true",
|
|
|
|
|
help="Skip interactive credential prompts and keep image defaults")
|
|
|
|
|
|
|
|
|
|
enc = p.add_argument_group("Full-disk encryption options")
|
|
|
|
|
enc.add_argument("--encrypt", action="store_true",
|
|
|
|
|
help="Encrypt the linux rootfs partition with LUKS2 (aes-xts-plain64, Argon2id)")
|
|
|
|
|
enc.add_argument("--luks-password", metavar="PASS",
|
|
|
|
|
help="Set LUKS2 disk encryption passphrase non-interactively (implies --encrypt)")
|
|
|
|
|
enc.add_argument("--ask-luks-password", action="store_true",
|
|
|
|
|
help="Prompt securely for LUKS2 disk encryption passphrase (implies --encrypt)")
|
|
|
|
|
|
2026-11-22 10:49:59 +02:00
|
|
|
p.add_argument("--backup-dir", default=os.path.join(BASE_DIR, "backup", time.strftime("%Y%m%d-%H%M%S")),
|
|
|
|
|
help="Directory for partition backups")
|
|
|
|
|
p.add_argument("--images-dir", default=os.path.join(BASE_DIR, "images"),
|
|
|
|
|
help="Directory containing boot-geminux.img, recovery-geminux.img, geminux-rootfs.img")
|
|
|
|
|
p.add_argument("--firmware-dir", default=os.path.join(BASE_DIR, "firmware-cache", "mt6797"),
|
|
|
|
|
help="Directory for extracted MT6797 firmware blobs")
|
|
|
|
|
p.add_argument("--system-img", help="Local Android system.img file for --extract-firmware")
|
|
|
|
|
p.add_argument("--da", help="Optional custom MediaTek DA binary path (e.g. MTK_AllInOne_DA.bin)")
|
|
|
|
|
p.add_argument("--preloader", help="Optional preloader binary path for DRAM init")
|
|
|
|
|
p.add_argument("--skip-backup", action="store_true", help="Skip backup if already taken in --backup-dir")
|
|
|
|
|
p.add_argument("--skip-firmware-extract", action="store_true", help="Skip automatic firmware extraction")
|
|
|
|
|
p.add_argument("--force-gpt", action="store_true", help="Allow repartitioning unrecognized GPT layouts")
|
|
|
|
|
p.add_argument("--no-reboot", action="store_true",
|
|
|
|
|
help="Power off instead of auto-rebooting after flashing")
|
|
|
|
|
p.add_argument("--wait-timeout", type=int, default=300,
|
|
|
|
|
help="Seconds to wait for MediaTek BROM/Preloader USB connection (default: 300, 0 = infinite)")
|
|
|
|
|
p.add_argument("-v", "--verbose", action="store_true", help="Verbose USB/DA protocol logging")
|
|
|
|
|
return p
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
parser = build_arg_parser()
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
if args.extract_firmware and args.system_img:
|
|
|
|
|
extract_firmware = load_extract_firmware()
|
|
|
|
|
found, missing = extract_firmware(args.system_img, args.firmware_dir)
|
|
|
|
|
print(f"[+] Extracted {len(found)} file(s) from {args.system_img} to {args.firmware_dir}.")
|
|
|
|
|
if missing:
|
|
|
|
|
print(f"[!] Missing required blobs: {', '.join(missing)}", file=sys.stderr)
|
|
|
|
|
return 1
|
|
|
|
|
return 0
|
|
|
|
|
|
2026-11-23 08:21:37 +02:00
|
|
|
needs_rootfs_cfg = bool(
|
|
|
|
|
args.customize_rootfs or
|
|
|
|
|
args.flash_rootfs_only or
|
|
|
|
|
not (
|
|
|
|
|
args.extract_firmware or args.only_backup or args.flash_kernel_only or
|
|
|
|
|
args.restore_backup or args.reboot or args.poweroff
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
account_cfg = None
|
|
|
|
|
luks_cfg = None
|
|
|
|
|
if needs_rootfs_cfg:
|
|
|
|
|
try:
|
|
|
|
|
account_cfg = resolve_account_config(args)
|
|
|
|
|
luks_cfg = resolve_luks_config(args)
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
print(f"[!] {exc}", file=sys.stderr)
|
|
|
|
|
return 1
|
|
|
|
|
|
|
|
|
|
if args.customize_rootfs:
|
|
|
|
|
customize_rootfs_offline(args, account_cfg, luks_cfg=luks_cfg)
|
|
|
|
|
return 0
|
|
|
|
|
|
2026-11-22 10:49:59 +02:00
|
|
|
mtk, da_handler = connect_mtk(
|
|
|
|
|
loader_path=args.da,
|
|
|
|
|
preloader_path=args.preloader,
|
|
|
|
|
verbose=args.verbose,
|
|
|
|
|
wait_timeout=args.wait_timeout,
|
|
|
|
|
)
|
|
|
|
|
finished = False
|
|
|
|
|
try:
|
|
|
|
|
if args.reboot:
|
|
|
|
|
finish_da_session(mtk, reboot=True)
|
|
|
|
|
print("[+] Triggering device reboot...")
|
|
|
|
|
finished = True
|
|
|
|
|
elif args.poweroff:
|
|
|
|
|
finish_da_session(mtk, reboot=False)
|
|
|
|
|
print("[+] Powered off out of DA mode.")
|
|
|
|
|
finished = True
|
|
|
|
|
elif args.only_backup:
|
|
|
|
|
run_backup(mtk, da_handler, args.backup_dir)
|
|
|
|
|
finish_da_session(mtk, reboot=False)
|
|
|
|
|
print("[+] Powered off out of DA mode.")
|
|
|
|
|
finished = True
|
|
|
|
|
elif args.extract_firmware:
|
|
|
|
|
extract_fw_from_device(da_handler, args.firmware_dir)
|
|
|
|
|
finish_da_session(mtk, reboot=False)
|
|
|
|
|
print("[+] Powered off out of DA mode.")
|
|
|
|
|
finished = True
|
|
|
|
|
elif args.flash_kernel_only:
|
|
|
|
|
flash_kernel_only(da_handler, args)
|
|
|
|
|
finish_da_session(mtk, reboot=not args.no_reboot)
|
|
|
|
|
print("[+] Powered off out of DA mode." if args.no_reboot else "[+] Triggering device reboot...")
|
|
|
|
|
finished = True
|
2026-11-23 08:21:37 +02:00
|
|
|
elif args.flash_rootfs_only:
|
|
|
|
|
flash_rootfs_only(da_handler, args, account_cfg=account_cfg, luks_cfg=luks_cfg)
|
|
|
|
|
finish_da_session(mtk, reboot=not args.no_reboot)
|
|
|
|
|
print("[+] Powered off out of DA mode." if args.no_reboot else "[+] Triggering device reboot...")
|
|
|
|
|
finished = True
|
2026-11-22 10:49:59 +02:00
|
|
|
elif args.restore_backup:
|
|
|
|
|
restore_backup(mtk, da_handler, args.restore_backup)
|
|
|
|
|
finish_da_session(mtk, reboot=not args.no_reboot)
|
|
|
|
|
print("[+] Powered off out of DA mode." if args.no_reboot else "[+] Triggering device reboot...")
|
|
|
|
|
finished = True
|
|
|
|
|
else:
|
2026-11-23 08:21:37 +02:00
|
|
|
flash_full(mtk, da_handler, args, account_cfg=account_cfg, luks_cfg=luks_cfg)
|
2026-11-22 10:49:59 +02:00
|
|
|
finish_da_session(mtk, reboot=not args.no_reboot)
|
|
|
|
|
print("[+] Powered off out of DA mode." if args.no_reboot else "[+] Triggering device reboot...")
|
|
|
|
|
finished = True
|
|
|
|
|
finally:
|
|
|
|
|
if not finished:
|
|
|
|
|
try:
|
|
|
|
|
mtk.port.close()
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
sys.exit(main())
|