#!/usr/bin/python3 -I """chandra-face: face unlock for Chandra, in the style of Howdy (docs/face-unlock.md). chandra-face status [--user U] what is set up (anyone) chandra-face list [--user U] enrolled faces: id, label, date (anyone) chandra-face enroll [--user U] [--label L] add a face from the camera (root) chandra-face remove ID [--user U] forget one face (root) chandra-face clear [--user U] forget every face (root) chandra-face test [--user U] look for the face now and print the scores (root) chandra-face compare --user U what the PAM module runs: exit 0 match, 1 no match, 2 face unlock can't be used (root) chandra-face pam [status|enable|disable] [SERVICE...] put pam_chandra_face.so into /etc/pam.d/SERVICE (root; default polkit-1 sudo) chandra-face fetch-models download the face models (root) Root commands started by another user re-run themselves through run0 or pkexec, so polkit asks for an administrator's password first (in Chandra's own dialog). Options: --config PATH (default /etc/chandra/face.conf), --machine (output as "kind text" lines for the compositor and the PAM module: info, error, progress, face, done). Safety: the camera images never leave this process and are never written anywhere; only face embeddings (feature vectors) are stored, in /var/lib/chandra-face/USER/faces.json, owned by root, mode 0600. compare refuses a store that someone else could have written. 2D face recognition can be fooled by a good photo, more easily with an RGB webcam than an IR camera; see the docs. """ import configparser import hashlib import json import math import os import pwd import re import shutil import stat import sys import tempfile import time DEFAULT_CONFIG = "/etc/chandra/face.conf" MARK = "# added by chandra-face" PAM_LINE = "-auth sufficient pam_chandra_face.so " + MARK DEFAULT_SERVICES = ["polkit-1", "sudo"] MODELS = { "face_detection_yunet_2023mar.onnx": ( "https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/" "face_detection_yunet/face_detection_yunet_2023mar.onnx", "8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4", ), "face_recognition_sface_2021dec.onnx": ( "https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/" "face_recognition_sface/face_recognition_sface_2021dec.onnx", "0ba9fbfa01b5270c96627c4ef784da859931e02f04419c829e83484087c34e79", ), } USER_RE = re.compile(r"^[a-z_][a-z0-9_.-]{0,31}\$?$", re.I) class Fail(Exception): """A user-facing error; `code` is the exit status.""" def __init__(self, msg, code=1): super().__init__(msg) self.code = code # ---------------------------------------------------------------- configuration class Config: def __init__(self, path=DEFAULT_CONFIG): cp = configparser.ConfigParser(inline_comment_prefixes=("#", ";")) self.path = path self.exists = False if path and os.path.exists(path): check_trusted(path, "config") cp.read(path) self.exists = True s = cp["face"] if cp.has_section("face") else {} def get(k, d): return s.get(k, d) if s else d self.enabled = get("enabled", "yes").lower() in ("yes", "true", "1", "on") self.backend = get("backend", "opencv") self.device = get("device", "/dev/video0") self.timeout = float(get("timeout", "4")) self.threshold = float(get("threshold", "0.42")) self.matches = max(1, int(get("matches", "2"))) self.dark = float(get("dark", "25")) self.min_face = int(get("min_face", "80")) self.require_ir = get("require_ir", "no").lower() in ("yes", "true", "1", "on") self.store = get("store", "/var/lib/chandra-face") self.models = get("models", "/usr/local/share/chandra/face") self.enroll_frames = max(1, int(get("enroll_frames", "5"))) self.pam_dir = get("pam_dir", "/etc/pam.d") self.frame_delay = float(get("frame_delay", "0")) def check_trusted(path, what): """Refuse files and dirs that someone other than root (or us) could have changed.""" st = os.lstat(path) if stat.S_ISLNK(st.st_mode): raise Fail("%s %s is a symlink" % (what, path), 2) if st.st_uid not in (0, os.geteuid()): raise Fail("%s %s is not owned by root" % (what, path), 2) if st.st_mode & 0o022: raise Fail("%s %s can be written by others" % (what, path), 2) # ---------------------------------------------------------------- output class Out: """Machine lines ("info text") for the compositor and the PAM module, plain text otherwise.""" def __init__(self, machine): self.machine = machine def emit(self, kind, text): if self.machine: sys.stdout.write("%s %s\n" % (kind, text.replace("\n", " "))) elif kind == "error": sys.stderr.write("chandra-face: %s\n" % text) elif kind in ("info", "done", "progress"): sys.stdout.write(text + "\n") else: sys.stdout.write("%s %s\n" % (kind, text)) (sys.stdout if self.machine or kind != "error" else sys.stderr).flush() def info(self, t): self.emit("info", t) def error(self, t): self.emit("error", t) # ---------------------------------------------------------------- store def check_user(user): if not user or not USER_RE.match(user): raise Fail("bad user name %r" % user, 2) try: return pwd.getpwnam(user) except KeyError: raise Fail("no such user %r" % user, 2) def user_dir(cfg, user): return os.path.join(cfg.store, user) def load_faces(cfg, user, trusted=True): """The user's enrolled faces: [{id, label, created, vectors}].""" d = user_dir(cfg, user) f = os.path.join(d, "faces.json") if not os.path.exists(f): return [] if trusted: check_trusted(cfg.store, "store") check_trusted(d, "store") check_trusted(f, "face data") fd = os.open(f, os.O_RDONLY | os.O_NOFOLLOW) with os.fdopen(fd) as fh: data = json.load(fh) return data.get("faces", []) def list_labels(cfg, user): """[(id, label, created)] from the readable list (no biometric data), else faces.json.""" p = os.path.join(user_dir(cfg, user), "faces.list") out = [] if os.path.exists(p): with open(p) as fh: for line in fh: parts = line.rstrip("\n").split("\t") if len(parts) == 3: out.append((int(parts[0]), parts[1], parts[2])) return out try: return [(f["id"], f["label"], f["created"]) for f in load_faces(cfg, user)] except (OSError, ValueError, Fail): return [] def write_atomic(path, text, mode): d = os.path.dirname(path) fd, tmp = tempfile.mkstemp(dir=d, prefix=".tmp-") try: os.fchmod(fd, mode) with os.fdopen(fd, "w") as fh: fh.write(text) fh.flush() os.fsync(fh.fileno()) os.replace(tmp, path) except BaseException: if os.path.exists(tmp): os.unlink(tmp) raise def save_faces(cfg, user, faces): old = os.umask(0o022) try: if not os.path.isdir(cfg.store): os.makedirs(cfg.store, 0o755) d = user_dir(cfg, user) if not os.path.isdir(d): os.mkdir(d, 0o755) check_trusted(cfg.store, "store") check_trusted(d, "store") if not faces: for n in ("faces.json", "faces.list"): p = os.path.join(d, n) if os.path.exists(p): os.unlink(p) os.rmdir(d) return write_atomic(os.path.join(d, "faces.json"), json.dumps({"version": 1, "faces": faces}), 0o600) lines = "".join("%d\t%s\t%s\n" % (f["id"], f["label"], f["created"]) for f in faces) write_atomic(os.path.join(d, "faces.list"), lines, 0o644) finally: os.umask(old) # ---------------------------------------------------------------- recognition def cosine(a, b): num = sum(x * y for x, y in zip(a, b)) na = math.sqrt(sum(x * x for x in a)) nb = math.sqrt(sum(y * y for y in b)) return num / (na * nb) if na > 0 and nb > 0 else -1.0 class Face: def __init__(self, x, y, w, h, raw=None): self.x, self.y, self.w, self.h, self.raw = x, y, w, h, raw class OpenCVRecognizer: """YuNet finds faces, SFace turns an aligned face into a 128-number embedding.""" def __init__(self, cfg): try: import cv2 # noqa import numpy # noqa except ImportError: raise Fail("python3-opencv (with numpy) is not installed", 2) import cv2 import numpy as np self.cv2, self.np = cv2, np if not hasattr(cv2, "FaceDetectorYN"): raise Fail("OpenCV %s is too old (4.5.4+ needed)" % cv2.__version__, 2) det = os.path.join(cfg.models, "face_detection_yunet_2023mar.onnx") rec = os.path.join(cfg.models, "face_recognition_sface_2021dec.onnx") for p in (det, rec): if not os.path.exists(p): raise Fail("face models missing: run chandra-face fetch-models", 2) check_trusted(p, "model") self.det = cv2.FaceDetectorYN.create(det, "", (320, 320), 0.8, 0.3, 5) self.rec = cv2.FaceRecognizerSF.create(rec, "") def gray(self, frame): if frame.ndim == 2: return True b, g, r = frame[:, :, 0], frame[:, :, 1], frame[:, :, 2] return bool((abs(b.astype(int) - g).mean() < 2) and (abs(g.astype(int) - r).mean() < 2)) def brightness(self, frame): return float(frame.mean()) def detect(self, frame): if frame.ndim == 2: frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR) h, w = frame.shape[:2] self.det.setInputSize((w, h)) _, faces = self.det.detect(frame) if faces is None: return [] return [Face(int(f[0]), int(f[1]), int(f[2]), int(f[3]), f) for f in faces] def embed(self, frame, face): if frame.ndim == 2: frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR) crop = self.rec.alignCrop(frame, face.raw) v = self.rec.feature(crop).flatten() return [float(x) for x in v] class FakeRecognizer: """For tests without a camera or OpenCV: frames are grayscale PGM images; a frame shows a "face" when it has contrast, and its embedding is the 4x4 block means around the average.""" def __init__(self, cfg): pass def gray(self, frame): return True def brightness(self, frame): n = sum(len(r) for r in frame) return sum(sum(r) for r in frame) / n if n else 0.0 def detect(self, frame): flat = [v for r in frame for v in r] if not flat or max(flat) - min(flat) < 40: return [] return [Face(0, 0, len(frame[0]), len(frame))] def embed(self, frame, face): h, w = len(frame), len(frame[0]) out = [] for by in range(4): for bx in range(4): vals = [frame[y][x] for y in range(by * h // 4, (by + 1) * h // 4) for x in range(bx * w // 4, (bx + 1) * w // 4)] out.append(sum(vals) / max(1, len(vals))) m = sum(out) / len(out) return [v - m for v in out] def make_recognizer(cfg): if cfg.backend == "fake": return FakeRecognizer(cfg) if cfg.backend == "opencv": return OpenCVRecognizer(cfg) raise Fail("unknown backend %r" % cfg.backend, 2) def read_pnm(path): """A binary PGM (P5) or PPM (P6) as rows of gray values.""" with open(path, "rb") as fh: data = fh.read() toks, i = [], 0 while len(toks) < 4: while data[i:i + 1].isspace(): i += 1 if data[i:i + 1] == b"#": while data[i:i + 1] not in (b"\n", b""): i += 1 continue j = i while not data[j:j + 1].isspace(): j += 1 toks.append(data[i:j]) i = j i += 1 kind, w, h = toks[0], int(toks[1]), int(toks[2]) px = data[i:] if kind == b"P5": return [list(px[y * w:(y + 1) * w]) for y in range(h)] if kind == b"P6": return [[(px[(y * w + x) * 3] + px[(y * w + x) * 3 + 1] + px[(y * w + x) * 3 + 2]) // 3 for x in range(w)] for y in range(h)] raise Fail("%s: not a binary PGM/PPM" % path, 2) class ImageCamera: """`images:DIR`: the image files in DIR, in name order, as camera frames (for tests).""" def __init__(self, spec, cfg): d = spec[len("images:"):] self.files = sorted(os.path.join(d, f) for f in os.listdir(d) if not f.startswith(".")) self.i = 0 self.cfg = cfg def read(self): if self.i >= len(self.files): return None f = self.files[self.i] self.i += 1 if self.cfg.frame_delay: time.sleep(self.cfg.frame_delay) if f.endswith((".pgm", ".ppm")): frame = read_pnm(f) if self.cfg.backend != "fake": import numpy as np frame = np.array(frame, dtype=np.uint8) return frame import cv2 return cv2.imread(f) def close(self): pass class V4L2Camera: def __init__(self, device): import cv2 self.cv2 = cv2 dev = int(device) if device.isdigit() else device self.cap = cv2.VideoCapture(dev, cv2.CAP_V4L2) if not self.cap.isOpened(): raise Fail("camera %s not available" % device, 2) def read(self): ok, frame = self.cap.read() return frame if ok else None def close(self): self.cap.release() def open_camera(cfg): if cfg.device.startswith("images:"): return ImageCamera(cfg.device, cfg) if not cfg.device.isdigit() and not os.path.exists(cfg.device): raise Fail("no camera at %s" % cfg.device, 2) return V4L2Camera(cfg.device) def frames(cam, seconds): """Frames until `seconds` pass or the camera ends.""" end = time.monotonic() + seconds while time.monotonic() < end: f = cam.read() if f is None: return yield f def largest(dets): return max(dets, key=lambda d: d.w * d.h) # ---------------------------------------------------------------- commands def cmd_compare(cfg, user, out, verbose=False): """Look for `user`'s face. 0: recognized, 1: not, 2: face unlock can't be used here.""" check_user(user) if not cfg.enabled: return 2 faces = load_faces(cfg, user) vectors = [v for f in faces for v in f.get("vectors", [])] if not vectors: return 2 # nothing enrolled: stay quiet, PAM goes on to the password try: rec = make_recognizer(cfg) cam = open_camera(cfg) except Fail as e: out.error("Face unlock: %s" % e) return 2 out.info("Face unlock: looking for %s…" % user) hits = seen = dark = total = 0 best = -1.0 try: for frame in frames(cam, cfg.timeout): total += 1 if rec.brightness(frame) < cfg.dark: dark += 1 continue dets = rec.detect(frame) if not dets: continue face = largest(dets) if face.w < cfg.min_face and face.h < cfg.min_face and cfg.backend != "fake": continue if cfg.require_ir and not rec.gray(frame): out.error("Face unlock: needs an infrared camera (require_ir)") return 2 seen += 1 v = rec.embed(frame, face) score = max(cosine(v, s) for s in vectors) best = max(best, score) if verbose: out.emit("score", "%.3f" % score) if score >= cfg.threshold: hits += 1 if hits >= cfg.matches: out.info("Face unlock: recognized %s" % user) return 0 finally: cam.close() if verbose: out.emit("best", "%.3f" % best) if total == 0: out.error("Face unlock: the camera gave no picture") elif seen == 0 and dark == total: out.error("Face unlock: the camera picture is too dark") elif seen == 0: out.error("Face unlock: no face in view") else: out.error("Face unlock: face not recognized") return 1 def cmd_enroll(cfg, user, label, out): check_user(user) rec = make_recognizer(cfg) cam = open_camera(cfg) out.info("Look at the camera…") vecs = [] many = 0 try: for frame in frames(cam, max(cfg.timeout * 3, 10)): if rec.brightness(frame) < cfg.dark: continue dets = rec.detect(frame) if len(dets) > 1: many += 1 continue if not dets: continue face = dets[0] if face.w < cfg.min_face and face.h < cfg.min_face and cfg.backend != "fake": continue vecs.append(rec.embed(frame, face)) out.emit("progress", "%d/%d" % (len(vecs), cfg.enroll_frames)) if len(vecs) >= cfg.enroll_frames: break finally: cam.close() if len(vecs) < cfg.enroll_frames: if many: raise Fail("more than one face in view: be alone in front of the camera") raise Fail("couldn't see a face clearly: look at the camera in good light and try again") faces = load_faces(cfg, user) nid = max([f["id"] for f in faces] + [0]) + 1 label = (label or "Face %d" % nid).replace("\t", " ").replace("\n", " ")[:60] faces.append({"id": nid, "label": label, "created": time.strftime("%Y-%m-%d"), "vectors": [[round(x, 6) for x in v] for v in vecs]}) save_faces(cfg, user, faces) out.emit("done", "Added %s" % label) return 0 def cmd_remove(cfg, user, ident, out): check_user(user) faces = load_faces(cfg, user) keep = [f for f in faces if str(f["id"]) != str(ident)] if len(keep) == len(faces): raise Fail("no face %s for %s" % (ident, user)) save_faces(cfg, user, keep) out.emit("done", "Removed face %s" % ident) return 0 def cmd_clear(cfg, user, out): check_user(user) save_faces(cfg, user, []) out.emit("done", "Removed every face of %s" % user) return 0 def pam_services(cfg, module): """The PAM services whose file uses `module` on an auth line.""" out = [] try: names = sorted(os.listdir(cfg.pam_dir)) except OSError: return out for n in names: p = os.path.join(cfg.pam_dir, n) try: with open(p) as fh: for line in fh: t = line.split("#", 1)[0].split() if len(t) >= 3 and t[0].lstrip("-") == "auth" and any(module in w for w in t[1:]): out.append(n) break except (OSError, UnicodeDecodeError): pass return out def pam_enable(cfg, service, out): if not re.match(r"^[a-z0-9_.-]+$", service): raise Fail("bad service name %r" % service) p = os.path.join(cfg.pam_dir, service) if not os.path.exists(p): vendor = os.path.join("/usr/lib/pam.d", service) if not os.path.exists(vendor): raise Fail("no PAM service %s" % service) shutil.copyfile(vendor, p) with open(p) as fh: lines = fh.read().split("\n") if any("pam_chandra_face.so" in l and not l.lstrip().startswith("#") for l in lines): out.emit("done", "%s already uses face unlock" % service) return 0 bak = p + ".chandra-face.bak" if not os.path.exists(bak): shutil.copy2(p, bak) # Before the first auth line, so the face is tried first and the password after it. # Debian's sudo has no auth line of its own, only "@include common-auth": go before that. at = next((i for i, l in enumerate(lines) if l.split() and l.split()[0].lstrip("-") in ("auth", "@include")), None) if at is None: at = next((i for i, l in enumerate(lines) if l.strip() and not l.startswith("#")), len(lines)) lines.insert(at, PAM_LINE) write_atomic(p, "\n".join(lines), stat.S_IMODE(os.stat(p).st_mode)) out.emit("done", "%s: face unlock first, then the password" % service) return 0 def pam_disable(cfg, service, out): if not re.match(r"^[a-z0-9_.-]+$", service): raise Fail("bad service name %r" % service) p = os.path.join(cfg.pam_dir, service) if not os.path.exists(p): return 0 with open(p) as fh: lines = fh.read().split("\n") keep = [l for l in lines if "pam_chandra_face.so" not in l or l.lstrip().startswith("#")] if len(keep) != len(lines): write_atomic(p, "\n".join(keep), stat.S_IMODE(os.stat(p).st_mode)) out.emit("done", "%s: password only" % service) return 0 def cmd_status(cfg, user, out): """Lines: backend, problem (why it can't work, if so), pam (services), howdy, face rows.""" problem = "" backend = cfg.backend if not cfg.enabled: problem = "turned off in %s" % cfg.path elif backend == "opencv": try: import cv2 # noqa except ImportError: problem = "python3-opencv is not installed" if not problem: for m in MODELS: if not os.path.exists(os.path.join(cfg.models, m)): problem = "face models missing: run chandra-face fetch-models" break if not problem and not cfg.device.startswith("images:") and not cfg.device.isdigit() \ and not os.path.exists(cfg.device): problem = "no camera at %s" % cfg.device out.emit("backend", backend) out.emit("device", cfg.device) if problem: out.emit("problem", problem) out.emit("pam", ",".join(pam_services(cfg, "pam_chandra_face.so"))) howdy = pam_services(cfg, "pam_howdy.so") if howdy: out.emit("howdy", ",".join(howdy)) for i, label, created in list_labels(cfg, user): out.emit("face", "%d\t%s\t%s" % (i, label, created)) return 0 def cmd_fetch_models(cfg, out): import urllib.request os.makedirs(cfg.models, 0o755, exist_ok=True) for name, (url, sha) in MODELS.items(): dst = os.path.join(cfg.models, name) if os.path.exists(dst) and hashlib.sha256(open(dst, "rb").read()).hexdigest() == sha: out.info("%s is there" % name) continue out.info("downloading %s" % name) data = urllib.request.urlopen(url, timeout=60).read() got = hashlib.sha256(data).hexdigest() if got != sha: raise Fail("%s: checksum mismatch (%s)" % (name, got)) fd, tmp = tempfile.mkstemp(dir=cfg.models) with os.fdopen(fd, "wb") as fh: fh.write(data) os.chmod(tmp, 0o644) os.replace(tmp, dst) out.emit("done", "models in %s" % cfg.models) return 0 # ---------------------------------------------------------------- main ROOT_CMDS = ("enroll", "remove", "clear", "test", "compare", "fetch-models") def elevate(argv, user): """Run this command again as root through run0 (systemd) or pkexec: polkit asks first.""" me = os.path.realpath(sys.argv[0]) args = [me] + argv if "--user" not in argv: args += ["--user", user] run0 = shutil.which("run0") if run0 and os.path.isdir("/run/systemd/system"): os.execv(run0, [run0, "--background=", "--"] + ["/usr/bin/python3", "-I"] + args) pk = shutil.which("pkexec") if pk: os.execv(pk, [pk, "/usr/bin/python3", "-I"] + args) raise Fail("needs root, and neither run0 nor pkexec is installed") def main(argv): args = list(argv) machine = "--machine" in args if machine: args.remove("--machine") out = Out(machine) cfg_path = DEFAULT_CONFIG user = None label = None no_elevate = False rest = [] i = 0 while i < len(args): a = args[i] if a in ("--config", "--user", "--label") and i + 1 < len(args): if a == "--config": cfg_path = args[i + 1] elif a == "--user": user = args[i + 1] else: label = args[i + 1] i += 2 continue if a == "--no-elevate": no_elevate = True elif a in ("-h", "--help"): print(__doc__) return 0 else: rest.append(a) i += 1 if not rest: print(__doc__) return 2 cmd, params = rest[0], rest[1:] if user is None: user = pwd.getpwuid(os.getuid()).pw_name pam_change = cmd == "pam" and params[:1] in (["enable"], ["disable"]) try: if (cmd in ROOT_CMDS or pam_change) and os.geteuid() != 0 and not no_elevate: # compare must never elevate: the PAM module already runs it as root. if cmd == "compare": raise Fail("compare runs as root (from the PAM module)", 2) elevate(argv, user) cfg = Config(cfg_path) if cmd == "status": return cmd_status(cfg, user, out) if cmd == "list": for i2, l, c in list_labels(cfg, user): out.emit("face", "%d\t%s\t%s" % (i2, l, c)) return 0 if cmd == "compare": return cmd_compare(cfg, user, out) if cmd == "test": return cmd_compare(cfg, user, out, verbose=True) if cmd == "enroll": return cmd_enroll(cfg, user, label, out) if cmd == "remove": if not params: raise Fail("remove ID") return cmd_remove(cfg, user, params[0], out) if cmd == "clear": return cmd_clear(cfg, user, out) if cmd == "fetch-models": return cmd_fetch_models(cfg, out) if cmd == "pam": what = params[0] if params else "status" services = params[1:] or DEFAULT_SERVICES if what == "status": out.emit("pam", ",".join(pam_services(cfg, "pam_chandra_face.so"))) return 0 for s in services: (pam_enable if what == "enable" else pam_disable)(cfg, s, out) return 0 raise Fail("unknown command %r" % cmd, 2) except Fail as e: out.error(str(e)) return e.code except KeyboardInterrupt: return 1 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))