Files

324 lines
10 KiB
Python
Raw Permalink Normal View History

#!/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