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

+15 -5
View File
@@ -55,7 +55,7 @@ EOF
[ -f /geminux/prebuilt/kernel/boot/Image.gz ] && \
[ -f /geminux/prebuilt/kernel/boot/mt6797-gemini-pda-geminux.dtb ]; then
echo "[1/2] Installing initramfs & bootimg tools in Docker (repack-only)..."
apk add --no-cache cpio gzip coreutils mkbootimg-osm0sis >/dev/null
apk add --no-cache cpio gzip coreutils mkbootimg-osm0sis kbd kbd-legacy >/dev/null
else
REPACK_ONLY=0
echo "[1/6] Installing Linux 7.3.5 cross-compile & bootimg tools in Docker..."
@@ -84,6 +84,8 @@ EOF
openssl-dev \
linux-headers \
dtc \
kbd \
kbd-legacy \
mkbootimg-osm0sis \
gcc-aarch64 \
g++-aarch64 \
@@ -175,10 +177,13 @@ EOF
for cmd in sh ash mount umount switch_root mkdir mknod chmod chown \
cat cp mv rm ln ls echo printf grep awk sed head tail \
cut tr wc sort uniq find xargs hexdump dd sync sleep usleep \
loadkmap clear stty readlink stat \
poweroff reboot ip ifconfig route basename dirname env touch; do
ln -sf busybox "$stage_dir/bin/$cmd"
done
# Pull static/musl e2fsck + resize2fs if available from aarch64 rootfs/apk
cp /tmp/gemini-us.kmap "$stage_dir/etc/gemini-us.kmap"
chmod 0644 "$stage_dir/etc/gemini-us.kmap"
# Pull static/musl e2fsck + resize2fs + cryptsetup if available from aarch64 rootfs/apk
if [ "$mode" = "recovery" ]; then
cp /geminux/src/initramfs/init-recovery "$stage_dir/init"
else
@@ -188,10 +193,15 @@ EOF
(cd "$stage_dir" && find . -print0 | cpio --null -ov --format=newc --quiet | gzip -9 > "$out_gz")
}
# Also add e2fsprogs (e2fsck, resize2fs) + shared libs for initramfs filesystem safety,
# Also add e2fsprogs (e2fsck, resize2fs), cryptsetup (LUKS2 FDE), + shared libs for initramfs,
# and wireless-regdb so built-in cfg80211 loads regulatory.db at early boot.
apk --root "$SYSROOT_INIT" --arch aarch64 add --no-scripts \
musl e2fsprogs e2fsprogs-extra util-linux-misc wireless-regdb >/dev/null
musl e2fsprogs e2fsprogs-extra util-linux-misc wireless-regdb cryptsetup >/dev/null
(
cd /usr/share/keymaps/legacy/i386/include
loadkeys -b /geminux/overlay/rootfs/etc/keymap/gemini-us.map > /tmp/gemini-us.kmap
)
build_cpio_with_fs() {
mode="$1"
@@ -206,7 +216,7 @@ EOF
mkdir -p "$stage_dir/lib/firmware"
cp -a "$SYSROOT_INIT/lib/firmware/regulatory.db"* "$stage_dir/lib/firmware/"
fi
for tool in e2fsck fsck.ext4 resize2fs blkid; do
for tool in e2fsck fsck.ext4 resize2fs blkid cryptsetup dmsetup; do
if [ -e "$SYSROOT_INIT/sbin/$tool" ]; then
cp -a "$SYSROOT_INIT/sbin/$tool" "$stage_dir/sbin/"
elif [ -e "$SYSROOT_INIT/usr/sbin/$tool" ]; then
+90 -4
View File
@@ -159,21 +159,103 @@ DTB_SZ="$(stat -c %s "$BASE_DIR/prebuilt/kernel/boot/mt6797-gemini-pda-geminux.d
[ "$DTB_SZ" -le 524288 ] || { echo "FAIL: DTB > 512 KiB ($DTB_SZ)" >&2; exit 1; }
python3 - "$IMAGES_DIR/boot-geminux.img" "$IMAGES_DIR/recovery-geminux.img" \
"$BASE_DIR/prebuilt/kernel/boot/config-7.3.5-geminux" "$ROOTFS_DIR" <<'PYEOF'
"$BASE_DIR/prebuilt/kernel/boot/config-7.3.5-geminux" "$ROOTFS_DIR" \
"$BASE_DIR/src/initramfs/init" "$BASE_DIR/src/initramfs/init-recovery" <<'PYEOF'
import gzip
import os
import re
import struct
import subprocess
import sys
def parse_newc_entries(cpio_bytes):
entries = {}
pos = 0
total = len(cpio_bytes)
while pos + 110 <= total:
hdr = cpio_bytes[pos:pos + 110]
if hdr[:6] not in (b"070701", b"070702"):
raise SystemExit(f"FAIL: invalid cpio newc magic at offset {pos}: {hdr[:6]!r}")
filesize = int(hdr[54:62], 16)
namesize = int(hdr[94:102], 16)
name_start = pos + 110
name_end = name_start + namesize
name = cpio_bytes[name_start:name_end].rstrip(b"\x00").decode("utf-8", "replace")
if name == "TRAILER!!!":
break
data_start = (name_end + 3) & ~3
rel = name[2:] if name.startswith("./") else name
entries[rel] = cpio_bytes[data_start:data_start + filesize]
pos = (data_start + filesize + 3) & ~3
return entries
GEMINI_HW_KEYCODES = (
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 42,
44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 56, 57,
103, 105, 106, 108, 125,
)
for init_script in sys.argv[5:7]:
subprocess.run(["sh", "-n", init_script], check=True)
with open(init_script, "r", encoding="utf-8") as f:
txt = f.read()
if "cryptsetup resize" in txt:
raise SystemExit(f"FAIL: redundant interactive 'cryptsetup resize' found in {init_script}")
for line in txt.splitlines():
if "loadkmap" in line and line.count("<") > 1:
raise SystemExit(f"FAIL: double stdin redirection on loadkmap in {init_script}: {line}")
if init_script == sys.argv[5]:
stripped = line.strip()
if stripped.startswith(("resize2fs ", "e2fsck -p ")) and "</dev/null" not in line:
raise SystemExit(f"FAIL: missing '</dev/null' stdin guard in {init_script}: {stripped}")
for path in sys.argv[1:3]:
with open(path, "rb") as f:
hdr = f.read(640)
blob = f.read()
hdr = blob[:640]
if hdr[:8] != b"ANDROID!":
raise SystemExit(f"FAIL: invalid boot image magic in {path}")
kernel_size = struct.unpack("<I", hdr[8:12])[0]
kernel_addr = struct.unpack("<I", hdr[12:16])[0]
ramdisk_size = struct.unpack("<I", hdr[16:20])[0]
page_size = struct.unpack("<I", hdr[36:40])[0] or 2048
if kernel_addr != 0x40080000:
raise SystemExit(
f"FAIL: {path} kernel_addr={kernel_addr:#010x}, expected 0x40080000 for Gemini LK"
)
k_pages = (kernel_size + page_size - 1) // page_size
r_off = (1 + k_pages) * page_size
cpio_bytes = gzip.decompress(blob[r_off:r_off + ramdisk_size])
rd_entries = parse_newc_entries(cpio_bytes)
for req_rd in ("init", "sbin/cryptsetup", "etc/gemini-us.kmap", "bin/loadkmap"):
if req_rd not in rd_entries:
raise SystemExit(f"FAIL: {path} ramdisk missing '{req_rd}'")
rd_init_txt = rd_entries["init"].decode("utf-8", "replace")
if "cryptsetup resize" in rd_init_txt:
raise SystemExit(f"FAIL: {path} init still contains 'cryptsetup resize'")
kmap = rd_entries["etc/gemini-us.kmap"]
if len(kmap) < 7 + 256 + 256 or kmap[:7] != b"bkeymap" or kmap[7] != 1:
raise SystemExit(f"FAIL: {path} invalid bkeymap header in etc/gemini-us.kmap")
map0 = struct.unpack_from("<128H", kmap, 7 + 256)
holes = [kc for kc in GEMINI_HW_KEYCODES if map0[kc] == 0x0200]
if holes:
raise SystemExit(f"FAIL: {path} etc/gemini-us.kmap has unbound Gemini keycodes: {holes}")
for kc, exp, label in (
(28, 0x0201, "Return"),
(42, 0x0700, "LShift"),
(54, 0x0700, "RShift"),
(57, 0x0020, "Space"),
(1, 0x001B, "Escape"),
(125, 0x0701, "AltGr/Fn"),
):
if map0[kc] != exp:
raise SystemExit(
f"FAIL: {path} etc/gemini-us.kmap keycode {kc} ({label}) = {map0[kc]:#06x}, expected {exp:#06x}"
)
cmdline = hdr[64:576].split(b"\x00", 1)[0].decode("ascii", "replace")
for req in ("clk_ignore_unused", "maxcpus=8", "noautodetect"):
if req not in cmdline.split():
@@ -189,8 +271,9 @@ for line in kcfg.splitlines():
break
else:
raise SystemExit(f"FAIL: {sys.argv[3]} missing CONFIG_CMDLINE")
if "CONFIG_REGULATOR_FIXED_VOLTAGE=y" not in kcfg.splitlines():
raise SystemExit(f"FAIL: {sys.argv[3]} missing CONFIG_REGULATOR_FIXED_VOLTAGE=y")
for req_cfg in ("CONFIG_REGULATOR_FIXED_VOLTAGE=y", "CONFIG_BLK_DEV_DM=y", "CONFIG_DM_CRYPT=y"):
if req_cfg not in kcfg.splitlines():
raise SystemExit(f"FAIL: {sys.argv[3]} missing {req_cfg}")
rootfs = sys.argv[4]
for req_rel in ("etc/pam.d/autologin", "etc/init.d/geminux-hwinit",
@@ -200,12 +283,15 @@ for req_rel in ("etc/pam.d/autologin", "etc/init.d/geminux-hwinit",
"usr/sbin/geminux-wifi-nvram", "usr/sbin/geminux-tzctl",
"usr/bin/geminux-datetime",
"usr/bin/bantam",
"etc/keymap/gemini-us.map",
"etc/skel/.gitconfig",
"home/user/.gitconfig",
"etc/NetworkManager/dispatcher.d/30-geminux-chrony",
"etc/polkit-1/rules.d/10-geminux.rules"):
if not os.path.lexists(os.path.join(rootfs, req_rel)):
raise SystemExit(f"FAIL: missing required path {os.path.join(rootfs, req_rel)}")
if not any(os.path.lexists(os.path.join(rootfs, p)) for p in ("sbin/cryptsetup", "usr/sbin/cryptsetup")):
raise SystemExit(f"FAIL: missing cryptsetup binary in {rootfs}")
if os.path.lexists(os.path.join(rootfs, "etc/runlevels/sysinit/hwdrivers")):
raise SystemExit("FAIL: hwdrivers must not be enabled in sysinit")
if os.path.lexists(os.path.join(rootfs, "etc/runlevels/default/wpa_supplicant")):
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env python3
"""Offline ext4 account and SHA-512 ($6$) credential provisioning for Geminux."""
import hashlib
import os
import re
import secrets
import shutil
import subprocess
import tempfile
_B64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
_USERNAME_RE = re.compile(r"^[a-z_][a-z0-9_-]{0,30}$")
RESERVED_USERNAMES = frozenset({
"root", "bin", "daemon", "adm", "lp", "sync", "shutdown", "halt",
"mail", "news", "uucp", "operator", "man", "postmaster", "cron", "ftp",
"sshd", "at", "squid", "xfs", "games", "cyrus", "vpopmail", "ntp",
"smmsp", "guest", "nobody", "klogd", "chrony", "messagebus", "dnsmasq",
"polkitd", "greetd",
})
_SHA512_BYTE_TUPLES = (
(0, 21, 42), (22, 43, 1), (44, 2, 23), (3, 24, 45), (25, 46, 4), (47, 5, 26),
(6, 27, 48), (28, 49, 7), (50, 8, 29), (9, 30, 51), (31, 52, 10), (53, 11, 32),
(12, 33, 54), (34, 55, 13), (56, 14, 35), (15, 36, 57), (37, 58, 16), (59, 17, 38),
(18, 39, 60), (40, 61, 19), (62, 20, 41),
)
class AccountConfig:
"""Provisioning overrides for the desktop user and root credentials."""
def __init__(self, username=None, user_pw_hash=None, root_pw_hash=None):
self.username = username
self.user_pw_hash = user_pw_hash
self.root_pw_hash = root_pw_hash
@property
def has_changes(self):
return bool(self.username or self.user_pw_hash or self.root_pw_hash)
def validate_username(username):
"""Validate a POSIX Linux username suitable for Geminux desktop login."""
if not isinstance(username, str) or not _USERNAME_RE.match(username):
raise ValueError(
f"Invalid username {username!r}: must match ^[a-z_][a-z0-9_-]{{0,30}}$"
)
if username in RESERVED_USERNAMES:
raise ValueError(f"Username {username!r} is reserved for a system account")
return username
def _b64_from_24bit(b2, b1, b0, n):
w = (b2 << 16) | (b1 << 8) | b0
out = []
for _ in range(n):
out.append(_B64[w & 0x3F])
w >>= 6
return "".join(out)
def sha512_crypt(password, salt=None):
"""Compute a standard 5000-round glibc/musl SHA-512 ($6$) shadow hash."""
if not isinstance(password, str) or not password:
raise ValueError("Password must be a non-empty string")
if any(ch in password for ch in ("\x00", "\n", "\r")):
raise ValueError("Password must not contain NUL or newline characters")
if salt is None:
salt = "".join(secrets.choice(_B64) for _ in range(16))
else:
if not isinstance(salt, str) or not (1 <= len(salt) <= 16) or any(ch not in _B64 for ch in salt):
raise ValueError("Salt must be 1..16 crypt-base64 characters")
key = password.encode("utf-8")
sb = salt.encode("ascii")
klen, slen = len(key), len(sb)
b = hashlib.sha512(key + sb + key).digest()
ca = hashlib.sha512(key + sb)
ca.update(b * (klen // 64) + b[:klen % 64])
cnt = klen
while cnt:
ca.update(b if (cnt & 1) else key)
cnt >>= 1
a = ca.digest()
dp = hashlib.sha512(key * klen).digest()
p = dp * (klen // 64) + dp[:klen % 64]
ds = hashlib.sha512(sb * (16 + a[0])).digest()
s = ds * (slen // 64) + ds[:slen % 64]
for i in range(5000):
c = hashlib.sha512()
c.update(p if (i & 1) else a)
if i % 3:
c.update(s)
if i % 7:
c.update(p)
c.update(a if (i & 1) else p)
a = c.digest()
enc = "".join(_b64_from_24bit(a[x], a[y], a[z], 4) for x, y, z in _SHA512_BYTE_TUPLES)
enc += _b64_from_24bit(0, 0, a[63], 2)
return f"$6${salt}${enc}"
def rewrite_account_tables(
passwd_txt,
group_txt,
shadow_txt,
new_username=None,
user_pw_hash=None,
root_pw_hash=None,
desktop_uid=10000,
):
"""Rewrite /etc/passwd, /etc/group, and /etc/shadow contents for the target user and root."""
passwd_rows = [line for line in passwd_txt.splitlines() if line]
group_rows = [line for line in group_txt.splitlines() if line]
shadow_rows = [line for line in shadow_txt.splitlines() if line]
desktop_idx = None
for idx, row in enumerate(passwd_rows):
fields = row.split(":")
if len(fields) >= 6 and fields[2].isdigit() and int(fields[2]) == desktop_uid:
desktop_idx = idx
break
if desktop_idx is None:
for idx, row in enumerate(passwd_rows):
fields = row.split(":")
if len(fields) >= 6 and fields[0] == "user":
desktop_idx = idx
break
if desktop_idx is None:
raise RuntimeError(f"Desktop user (UID {desktop_uid}) not found in /etc/passwd")
pw_fields = passwd_rows[desktop_idx].split(":")
old_username = pw_fields[0]
target_username = new_username if new_username else old_username
if target_username != old_username:
validate_username(target_username)
for idx, row in enumerate(passwd_rows):
fields = row.split(":")
if idx != desktop_idx and fields[0] == target_username:
raise ValueError(f"Username {target_username!r} already exists in /etc/passwd")
for row in group_rows:
fields = row.split(":")
is_desktop_pri = (
fields[0] == old_username or
(len(fields) >= 3 and fields[2].isdigit() and int(fields[2]) == desktop_uid)
)
if not is_desktop_pri and fields[0] == target_username:
raise ValueError(f"Group name {target_username!r} collides with an existing system group")
pw_fields[0] = target_username
pw_fields[5] = f"/home/{target_username}"
passwd_rows[desktop_idx] = ":".join(pw_fields)
for idx, row in enumerate(group_rows):
fields = row.split(":")
is_desktop_pri = (
fields[0] == old_username or
(len(fields) >= 3 and fields[2].isdigit() and int(fields[2]) == desktop_uid)
)
if is_desktop_pri:
fields[0] = target_username
if len(fields) >= 4 and fields[3]:
members = [
target_username if m == old_username else m
for m in fields[3].split(",") if m
]
fields[3] = ",".join(dict.fromkeys(members))
group_rows[idx] = ":".join(fields)
for idx, row in enumerate(shadow_rows):
fields = row.split(":")
if fields[0] == old_username:
fields[0] = target_username
shadow_rows[idx] = ":".join(fields)
if user_pw_hash:
updated = False
for idx, row in enumerate(shadow_rows):
fields = row.split(":")
if fields[0] == target_username and len(fields) >= 2:
fields[1] = user_pw_hash
shadow_rows[idx] = ":".join(fields)
updated = True
break
if not updated:
shadow_rows.append(f"{target_username}:{user_pw_hash}:::::::")
if root_pw_hash:
updated = False
for idx, row in enumerate(shadow_rows):
fields = row.split(":")
if fields[0] == "root" and len(fields) >= 2:
fields[1] = root_pw_hash
shadow_rows[idx] = ":".join(fields)
updated = True
break
if not updated:
shadow_rows.insert(0, f"root:{root_pw_hash}:::::::")
return (
"\n".join(passwd_rows) + "\n",
"\n".join(group_rows) + "\n",
"\n".join(shadow_rows) + "\n",
old_username,
target_username,
)
def _have_host_ext4_tools():
return shutil.which("debugfs") is not None and shutil.which("e2fsck") is not None
def _run_docker_ext4(img_dir, work_dir, shell_cmd, input_text=None):
docker_bin = shutil.which("docker")
if not docker_bin:
raise RuntimeError("Need host debugfs/e2fsck (e2fsprogs) or docker to customize ext4 image")
subprocess.run(
[
docker_bin, "run", "--rm", "-i",
"-v", f"{img_dir}:/img",
"-v", f"{work_dir}:/work",
"alpine:3.24",
"sh", "-eu", "-c",
f"apk add --no-cache e2fsprogs >/dev/null && {shell_cmd}",
],
input=input_text,
text=True,
check=True,
)
def customize_ext4_accounts(ext4_img_path, new_username=None, user_pw_hash=None, root_pw_hash=None):
"""Apply username and shadow password hash changes inside an unmounted ext4 rootfs image."""
if not (new_username or user_pw_hash or root_pw_hash):
return
abs_img = os.path.abspath(ext4_img_path)
if not os.path.isfile(abs_img):
raise FileNotFoundError(f"ext4 image not found: {abs_img}")
img_dir = os.path.dirname(abs_img)
img_name = os.path.basename(abs_img)
use_host = _have_host_ext4_tools()
with tempfile.TemporaryDirectory(prefix="geminux-acct-") as tmp:
if use_host:
for name in ("passwd", "group", "shadow"):
dst = os.path.join(tmp, f"{name}.orig")
subprocess.run(
["debugfs", "-R", f"dump /etc/{name} {dst}", abs_img],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
else:
dump_cmds = " && ".join(
f"debugfs -R 'dump /etc/{name} /work/{name}.orig' '/img/{img_name}' >/dev/null 2>&1"
for name in ("passwd", "group", "shadow")
)
_run_docker_ext4(img_dir, tmp, dump_cmds)
texts = {}
for name in ("passwd", "group", "shadow"):
with open(os.path.join(tmp, f"{name}.orig"), "r", encoding="utf-8") as f:
texts[name] = f.read()
new_pw, new_gr, new_sh, old_user, target_user = rewrite_account_tables(
texts["passwd"],
texts["group"],
texts["shadow"],
new_username=new_username,
user_pw_hash=user_pw_hash,
root_pw_hash=root_pw_hash,
)
out_contents = {"passwd": new_pw, "group": new_gr, "shadow": new_sh}
inodes_spec = (
("passwd", 0, 0, "0100644"),
("group", 0, 0, "0100644"),
("shadow", 0, 42, "0100640"),
)
for name, content in out_contents.items():
p = os.path.join(tmp, name)
with open(p, "w", encoding="utf-8") as f:
f.write(content)
def build_debugfs_script(work_prefix):
cmds = []
if target_user != old_user:
cmds.append(f"ln /home/{old_user} /home/{target_user}")
cmds.append(f"unlink /home/{old_user}")
for name, uid, gid, mode in inodes_spec:
cmds.append(f"rm /etc/{name}")
cmds.append(f"write {work_prefix}/{name} /etc/{name}")
cmds.append(f"set_inode_field /etc/{name} uid {uid}")
cmds.append(f"set_inode_field /etc/{name} gid {gid}")
cmds.append(f"set_inode_field /etc/{name} mode {mode}")
return "\n".join(cmds) + "\n"
if use_host:
script = build_debugfs_script(tmp)
subprocess.run(
["debugfs", "-w", abs_img],
input=script,
text=True,
check=True,
stdout=subprocess.DEVNULL,
)
subprocess.run(["e2fsck", "-fn", abs_img], check=True, stdout=subprocess.DEVNULL)
else:
script = build_debugfs_script("/work")
_run_docker_ext4(
img_dir,
tmp,
f"debugfs -w '/img/{img_name}' >/dev/null && e2fsck -fn '/img/{img_name}' >/dev/null",
input_text=script,
)
return old_user, target_user
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Host-side LUKS2 full-disk encryption image builder for Geminux."""
import os
import shutil
import subprocess
LUKS2_HEADER_PAD_MIB = 32
DEFAULT_PBKDF_MEMORY_KB = 131072
DEFAULT_PBKDF_ITERATIONS = 4
DEFAULT_PBKDF_PARALLEL = 4
class LuksConfig:
"""LUKS2 encryption configuration collected before flashing."""
def __init__(self, enabled=False, passphrase=None):
self.enabled = bool(enabled)
self.passphrase = passphrase
def validate_luks_passphrase(passphrase):
"""Validate a LUKS2 disk passphrase (non-empty UTF-8 string without NUL/newlines)."""
if not isinstance(passphrase, str) or not passphrase:
raise ValueError("LUKS2 passphrase must be a non-empty string")
if any(ch in passphrase for ch in ("\x00", "\n", "\r")):
raise ValueError("LUKS2 passphrase must not contain NUL or newline characters")
return passphrase
def _run_cryptsetup(args, img_dir, input_bytes=None):
host_cs = shutil.which("cryptsetup")
if host_cs is not None:
return subprocess.run(
[host_cs] + args,
input=input_bytes,
check=True,
capture_output=True,
)
docker_bin = shutil.which("docker")
if docker_bin is None:
raise RuntimeError("Need host 'cryptsetup' or 'docker' to encrypt rootfs image")
return subprocess.run(
[
docker_bin, "run", "--rm", "-i",
"-v", f"{img_dir}:/img",
"alpine:3.24",
"sh", "-eu", "-c",
'apk add --no-cache cryptsetup >/dev/null && "$@"',
"_", "cryptsetup",
] + args,
input=input_bytes,
check=True,
capture_output=True,
)
def encrypt_ext4_image_luks2(
ext4_img_path,
passphrase,
pbkdf_memory_kb=DEFAULT_PBKDF_MEMORY_KB,
pbkdf_iterations=DEFAULT_PBKDF_ITERATIONS,
pbkdf_parallel=DEFAULT_PBKDF_PARALLEL,
):
"""Encrypt an ext4 image in place inside a LUKS2 (aes-xts-plain64, Argon2id) container."""
validate_luks_passphrase(passphrase)
abs_img = os.path.abspath(ext4_img_path)
if not os.path.isfile(abs_img):
raise FileNotFoundError(f"ext4 image not found: {abs_img}")
pad_bytes = LUKS2_HEADER_PAD_MIB * 1024 * 1024
with open(abs_img, "r+b") as f:
f.seek(0, os.SEEK_END)
cur_sz = f.tell()
f.truncate(cur_sz + pad_bytes)
use_host = shutil.which("cryptsetup") is not None
img_dir = os.path.dirname(abs_img)
img_arg = abs_img if use_host else f"/img/{os.path.basename(abs_img)}"
pw_bytes = passphrase.encode("utf-8")
_run_cryptsetup(
[
"reencrypt", "--encrypt",
"--disable-locks",
"--type", "luks2",
"--cipher", "aes-xts-plain64",
"--key-size", "512",
"--hash", "sha256",
"--pbkdf", "argon2id",
"--pbkdf-memory", str(int(pbkdf_memory_kb)),
"--pbkdf-force-iterations", str(int(pbkdf_iterations)),
"--pbkdf-parallel", str(int(pbkdf_parallel)),
"--reduce-device-size", f"{LUKS2_HEADER_PAD_MIB}M",
"--batch-mode",
"--key-file", "-",
img_arg,
],
img_dir,
input_bytes=pw_bytes,
)
_run_cryptsetup(["isLuks", "--disable-locks", img_arg], img_dir)
_run_cryptsetup(
["open", "--test-passphrase", "--disable-locks", "--key-file", "-", img_arg],
img_dir,
input_bytes=pw_bytes,
)
+1
View File
@@ -16,6 +16,7 @@ ca-certificates
chrony
chrony-openrc
coreutils
cryptsetup
curl
curl-dev
dbus
+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()