Add flasher credential provisioning, LUKS2 FDE, LED fixes, and docs

This commit is contained in:
Luxferre committed 2026-11-23 08:21:37 +02:00
1 parent 2706b9a901
commit b7dca4f15f
49 files changed
+1524 -183

No files matched your search

+248 -14
View File
@@ -5,6 +5,7 @@ Uses vendored GPLv3 mtkclient transport (no proprietary MediaTek FlashTool).
"""
import argparse
import getpass
import hashlib
import logging
import os
@@ -21,6 +22,17 @@ for p in (VENDOR_MTK, SCRIPTS_DIR):
if p not in sys.path:
sys.path.insert(0, p)
from geminux_accounts import (
AccountConfig,
customize_ext4_accounts,
sha512_crypt,
validate_username,
)
from geminux_luks import (
LuksConfig,
encrypt_ext4_image_luks2,
validate_luks_passphrase,
)
from geminux_gpt import (
SECTOR_SIZE,
GPT_ARRAY_SECTORS,
@@ -279,7 +291,177 @@ def extract_fw_from_device(da_handler, fw_out_dir):
print(f"[+] Extracted {len(found)} firmware blob(s) to {fw_out_dir}.")
def flash_full(mtk, da_handler, args):
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):
backup_dir = args.backup_dir
if not args.skip_backup:
run_backup(mtk, da_handler, backup_dir)
@@ -344,22 +526,21 @@ def flash_full(mtk, da_handler, args):
write_partition_checked(da_handler, "recovery", rec_img, verify=True)
write_partition_checked(da_handler, "boot2", boot_img, verify=True)
# Convert sparse rootfs if needed before writing to 'linux'
with open(root_img, "rb") as rf:
is_sparse = rf.read(4) == SPARSE_MAGIC
if is_sparse:
if shutil.which("simg2img") is None:
raise RuntimeError("simg2img is required to unsparse geminux-rootfs.img")
with tempfile.TemporaryDirectory(prefix="geminux-rawroot-") as tmp:
raw_root = os.path.join(tmp, "linux.raw.img")
subprocess.run(["simg2img", root_img, raw_root], check=True)
write_partition_checked(da_handler, "linux", raw_root, verify=False)
else:
write_partition_checked(da_handler, "linux", root_img, verify=False)
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("[+] Full Geminux installation complete!")
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!")
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")
@@ -424,6 +605,10 @@ def build_arg_parser():
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")
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")
mode.add_argument("--restore-backup", metavar="DIR",
help="Restore GPT and backed-up partitions from DIR")
mode.add_argument("--reboot", action="store_true",
@@ -431,6 +616,28 @@ def build_arg_parser():
mode.add_argument("--poweroff", action="store_true",
help="Connect to BROM/DA and cleanly power off out of DA mode")
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)")
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"),
@@ -464,6 +671,28 @@ def main():
return 1
return 0
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
mtk, da_handler = connect_mtk(
loader_path=args.da,
preloader_path=args.preloader,
@@ -495,13 +724,18 @@ def main():
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
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
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:
flash_full(mtk, da_handler, args)
flash_full(mtk, 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