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

+323 -3
View File
@@ -2,6 +2,7 @@
"""Offline test suite for Geminux flash-mtk GPT builder, safety guards, and firmware extractor."""
import os
import re
import shutil
import struct
import subprocess
@@ -17,6 +18,12 @@ if os.path.isdir(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,
@@ -431,6 +438,299 @@ def test_xflash_shutdown_wire_packet():
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_cli_help():
res = subprocess.run(
[os.path.join(BASE_DIR, "flash-mtk.sh"), "--help"],
@@ -439,9 +739,26 @@ def test_cli_help():
check=False,
)
assert res.returncode == 0, res.stderr
assert "--only-backup" in res.stdout and "--flash-full" in res.stdout
assert "--reboot" in res.stdout and "--poweroff" in res.stdout and "--no-reboot" in res.stdout
assert "--wait-timeout" in res.stdout
for flag in (
"--only-backup",
"--flash-full",
"--flash-rootfs-only",
"--customize-rootfs",
"--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")
@@ -453,6 +770,9 @@ def main():
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_cli_help()