#!/usr/bin/python3 """Privileged helper for the Face Login window, started through pkexec. It acts only for the user who ran pkexec and accepts a fixed set of commands: enable-unlock | disable-unlock | refresh-unlock | enroll LABEL | remove ID set KEY VALUE """ import os import pathlib import pwd import re import subprocess import sys PAM_FILE = pathlib.Path("/etc/pam.d/gdm-password") PAM_VENDOR = pathlib.Path("/usr/lib/pam.d/gdm-password") MODELS = pathlib.Path("/etc/howdy/models") HOWDY = "/usr/bin/howdy" LOCK_CHECK = "/usr/libexec/howdy-settings/session-locked" ENROLL = "/usr/libexec/howdy-settings/enroll" BLOCK = [ "# howdy-settings: face unlock on the lock screen only", f"auth [success=ignore default=1] pam_exec.so quiet {LOCK_CHECK}", "auth sufficient pam_howdy.so", ] SETTINGS = { "certainty": (float, 1.0, 6.0), "dark_threshold": (int, 0, 100), "timeout": (int, 1, 15), } class HelperError(Exception): pass def is_enabled(text): return BLOCK[0] in text.splitlines() def enable(text): if is_enabled(text): return text lines = text.splitlines() auth = [i for i, line in enumerate(lines) if re.match(r"-?auth\s", line)] if not auth: raise HelperError("no auth line in the PAM file") permit = [i for i in auth if "pam_selinux_permit.so" in lines[i]] at = permit[0] + 1 if permit else auth[0] return "\n".join(lines[:at] + BLOCK + lines[at:]) + "\n" def disable(text): lines = text.splitlines() if BLOCK[0] not in lines: return text at = lines.index(BLOCK[0]) if lines[at:at + len(BLOCK)] != BLOCK: raise HelperError(f"{PAM_FILE} was edited by hand, change it yourself") return "\n".join(lines[:at] + lines[at + len(BLOCK):]) + "\n" def is_current(copy, vendor): """True when the copy in /etc is the vendor file plus our block, so a GDM update to the vendor file has not been missed.""" return copy == enable(vendor) def check_label(label): label = label.strip() if not 0 < len(label) <= 24 or "," in label or not label.isprintable(): raise HelperError("a label has 1 to 24 printable characters and no commas") return label def check_model_id(model_id): if not model_id.isdigit(): raise HelperError("a model ID is a number") return model_id def check_setting(key, value): if key == "device_path": path = pathlib.Path(value) if path.parent != pathlib.Path("/dev/v4l/by-path") or not path.is_char_device(): raise HelperError("the camera must be a device in /dev/v4l/by-path") return value if key not in SETTINGS: raise HelperError(f"{key} cannot be changed here") kind, low, high = SETTINGS[key] try: number = kind(value) except ValueError: raise HelperError(f"{key} must be a number") from None if not low <= number <= high: raise HelperError(f"{key} must be between {low} and {high}") return value def write_pam(text): if text == PAM_VENDOR.read_text(): PAM_FILE.unlink(missing_ok=True) return temp = PAM_FILE.with_name(PAM_FILE.name + ".howdy-settings") temp.write_text(text) temp.chmod(0o644) temp.replace(PAM_FILE) subprocess.run(["restorecon", str(PAM_FILE)], check=True) def current_pam(): return (PAM_FILE if PAM_FILE.exists() else PAM_VENDOR).read_text() def howdy(*args): subprocess.run([HOWDY, *args], check=True) def share_models(user): """Let the owner read their face models, for the window and the recognition test.""" path = MODELS / f"{user}.dat" if path.exists(): os.chown(path, 0, pwd.getpwnam(user).pw_gid) path.chmod(0o640) def run(user, command, args): if command == "enable-unlock" and not args: howdy("set", "workaround", "input") write_pam(enable(current_pam())) elif command == "refresh-unlock" and not args: write_pam(enable(PAM_VENDOR.read_text())) elif command == "disable-unlock" and not args: write_pam(disable(current_pam())) elif command == "enroll" and len(args) == 1: subprocess.run([ENROLL, user, check_label(args[0])], check=True) share_models(user) elif command == "remove" and len(args) == 1: howdy("-U", user, "-y", "remove", check_model_id(args[0])) share_models(user) elif command == "set" and len(args) == 2: howdy("set", args[0], check_setting(*args)) else: raise HelperError(f"unknown command: {' '.join([command, *args])}") def main(argv): if "PKEXEC_UID" not in os.environ: raise HelperError("run this through pkexec") if len(argv) < 2: raise HelperError(__doc__.strip()) user = pwd.getpwuid(int(os.environ["PKEXEC_UID"])).pw_name run(user, argv[1], argv[2:]) if __name__ == "__main__": try: main(sys.argv) except HelperError as error: sys.exit(f"howdy-settings: {error}") except subprocess.CalledProcessError as error: sys.exit(f"howdy-settings: {error.cmd[0]} failed with code {error.returncode}")