#!/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) chandra-face camera [--label L] the "Add a face" window's camera, run as you: streams a small live picture with the face box, keeps snaps (their embeddings) in memory, and on "apply" saves the snaps and removals in one root step (one password) chandra-face cameras the cameras here, and why one can't be used (anyone) chandra-face set-camera PATH use the camera at PATH (root; edits face.conf) chandra-face apply [--user U] add and remove faces in one go, from JSON on stdin: {"add": [{"label", "vectors"}], "remove": [ids]} (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 fcntl import glob import struct import hashlib import json import math import os import pwd import re import shutil import stat import sys import select import subprocess 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", "12")) self.detect_score = float(get("detect_score", "0.65")) 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 & 0o002 or (st.st_mode & 0o020 and st.st_gid != 0): 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("OpenCV is missing: run just install", 2) import cv2 import numpy as np self.cv2, self.np = cv2, np try: cv2.utils.logging.setLogLevel(cv2.utils.logging.LOG_LEVEL_ERROR) except AttributeError: pass 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), cfg.detect_score, 0.3, 5) self.rec = cv2.FaceRecognizerSF.create(rec, "") self._clahe = cv2.createCLAHE(clipLimit=2.2, tileGridSize=(8, 8)) self._detect_gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 1.5)) * 255.0, 0, 255).astype(np.uint8) 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 _enhance_for_detect(self, frame): """Lift dark frames with mild gamma + LAB CLAHE so YuNet/SFace can read shadow detail.""" if frame.ndim == 2: frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR) lifted = self.cv2.LUT(frame, self._detect_gamma_lut) h, w = lifted.shape[:2] if min(h, w) < 16: return lifted lab = self.cv2.cvtColor(lifted, self.cv2.COLOR_BGR2LAB) l_ch, a_ch, b_ch = self.cv2.split(lab) l_ch = self._clahe.apply(l_ch) return self.cv2.cvtColor(self.cv2.merge([l_ch, a_ch, b_ch]), self.cv2.COLOR_LAB2BGR) 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 and float(frame.mean()) < 90.0: enhanced = self._enhance_for_detect(frame) _, faces = self.det.detect(enhanced) 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) if float(frame.mean()) < 55.0: frame = self._enhance_for_detect(frame) 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, loop=False): 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 self.loop = loop def read(self): if self.loop and self.files: self.i %= len(self.files) 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 VIDIOC_QUERYCAP = 0x80685600 V4L2_CAP_VIDEO_CAPTURE = 0x1 V4L2_CAP_VIDEO_CAPTURE_MPLANE = 0x1000 V4L2_CAP_DEVICE_CAPS = 0x80000000 def query_camera(path): """(name, "") when `path` is a V4L2 node that captures pictures, else (name or "", why not).""" try: fd = os.open(path, os.O_RDWR | os.O_NONBLOCK) except OSError as e: why = e.strerror or str(e) if e.errno in (13, 1): # EACCES, EPERM why += " (you need access to it: be logged in at this seat, or in the video group)" return "", why try: buf = bytearray(104) try: fcntl.ioctl(fd, VIDIOC_QUERYCAP, buf) except OSError as e: return "", "not a V4L2 camera (%s)" % (e.strerror or e) name = bytes(buf[16:48]).split(b"\0")[0].decode("utf-8", "replace") caps, dev_caps = struct.unpack_from(" " "Session > Add or remove faces, or run chandra-face set-camera PATH" % (path, why, cameras_text(list_cameras()))) name, why = query_camera(path) if why: return "camera %s: %s; %s" % (path, why, cameras_text(list_cameras())) return "" QUAD_BAYER_MODELS = {"imx371"} VIDIOC_G_CTRL = 0xC008561B VIDIOC_S_CTRL = 0xC008561C VIDIOC_QUERYCTRL = 0xC0445624 V4L2_CID_EXPOSURE = 0x00980911 V4L2_CID_VBLANK = 0x009E0901 V4L2_CID_ANALOGUE_GAIN = 0x009E0903 V4L2_CID_DIGITAL_GAIN = 0x009F0905 _QUAD_TONE_LUT = None def _build_tone_lut(np_mod): """Build 4096-entry uint8 tone LUT: linear 0..160, smooth highlight roll-off to 768, gamma 2.2.""" x = np_mod.linspace(0.0, 768.0, 4096, dtype=np_mod.float32) t = np_mod.maximum(x - 160.0, 0.0) / 95.0 y = np_mod.where(x <= 160.0, x, 160.0 + 95.0 * (t / (1.0 + 0.65 * t))) y = np_mod.clip(y / 255.0, 0.0, 1.0) return np_mod.clip((y ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) def _get_tone_lut(np_mod): global _QUAD_TONE_LUT if _QUAD_TONE_LUT is None: _QUAD_TONE_LUT = _build_tone_lut(np_mod) return _QUAD_TONE_LUT def find_sensor_subdev(model): """Find /dev/v4l-subdevN matching sensor `model`, or None.""" if not model: return None want = model.lower() for p in sorted(glob.glob("/sys/class/video4linux/v4l-subdev*/name")): try: with open(p) as fh: name = fh.read().strip().lower() except OSError: continue if name == want or name.startswith(want + " "): return "/dev/" + os.path.basename(os.path.dirname(p)) return None class _V4L2SubdevIO: """Thin ioctl wrapper over a V4L2 subdevice file descriptor.""" def __init__(self, path): self.fd = os.open(path, os.O_RDWR) def query(self, cid): buf = bytearray(68) struct.pack_into("= 0: try: os.close(self.fd) finally: self.fd = -1 class QuadSensorAE: """Direct V4L2 subdev auto-exposure and gain controller for Raw-only Quad-Bayer capture.""" def __init__(self, subdev_path, io=None): self.io = io if io is not None else _V4L2SubdevIO(subdev_path) self._closed = False try: self.vb_min, self.vb_max, _, _ = self.io.query(V4L2_CID_VBLANK) self.exp_min, self.exp_max_now, _, _ = self.io.query(V4L2_CID_EXPOSURE) self.ag_min, self.ag_max, _, _ = self.io.query(V4L2_CID_ANALOGUE_GAIN) self.init_vblank = self.io.get(V4L2_CID_VBLANK) self.init_exp = self.io.get(V4L2_CID_EXPOSURE) self.init_ag = self.io.get(V4L2_CID_ANALOGUE_GAIN) try: self.dg_min, self.dg_max, _, _ = self.io.query(V4L2_CID_DIGITAL_GAIN) self.init_dg = self.io.get(V4L2_CID_DIGITAL_GAIN) self.has_dgain = True except OSError: self.dg_min, self.dg_max, self.init_dg, self.has_dgain = 1024, 1024, 1024, False except Exception: self.io.close() raise self.exp_base_max = max(self.exp_min + 1, self.exp_max_now - max(0, self.init_vblank - self.vb_min)) self.vb_cap = min(self.vb_max, 9500) self.exp_lowlight_max = min(self.exp_base_max + max(0, self.vb_cap - self.vb_min), 12000) self.ag_max_x = 512.0 / max(512 - min(self.ag_max, 504), 1) self.dg_max_x = min(self.dg_max / 1024.0, 4.0) if self.has_dgain else 1.0 self.e_min = float(max(20, self.exp_min)) self.e_max = float(self.exp_lowlight_max) * self.ag_max_x * self.dg_max_x self.cur_vblank = self.init_vblank self.cur_exp = self.init_exp self.cur_ag = self.init_ag self.cur_dg = self.init_dg self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x) self.cooldown = 0 def plan(self, ev_total): """Map scalar exposure target E = exp * ag_x * dg_x to (vblank, exp, ag_code, dg_code).""" ev = max(self.e_min, min(float(ev_total), self.e_max)) mid_ag = min(8.0, self.ag_max_x) if ev <= self.exp_base_max: exp, ag_x, dg_x, vb = int(round(ev)), 1.0, 1.0, self.vb_min elif ev <= self.exp_base_max * mid_ag: exp = self.exp_base_max ag_x = ev / max(exp, 1) dg_x, vb = 1.0, self.vb_min elif ev <= self.exp_lowlight_max * mid_ag: ag_x = mid_ag exp = int(round(ev / ag_x)) dg_x = 1.0 vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) elif ev <= self.exp_lowlight_max * self.ag_max_x: exp = self.exp_lowlight_max vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) ag_x = ev / max(exp, 1) dg_x = 1.0 else: exp = self.exp_lowlight_max vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) ag_x = self.ag_max_x dg_x = ev / max(exp * ag_x, 1.0) vb = max(self.vb_min, min(vb, self.vb_cap)) exp = max(self.exp_min, min(exp, self.exp_lowlight_max)) ag_code = int(round(512.0 * (1.0 - 1.0 / max(ag_x, 1.0)))) ag_code = max(self.ag_min, min(ag_code, self.ag_max)) dg_code = int(round(1024.0 * max(dg_x, 1.0))) if self.has_dgain else 1024 if self.has_dgain: dg_code = max(min(1024, self.dg_max), min(dg_code, self.dg_max)) return vb, exp, ag_code, dg_code def _apply_exp_vblank(self, vb, exp): """Enforce sensor ordering: raise VBLANK before raising EXPOSURE; shrink EXPOSURE before shrinking VBLANK.""" if vb > self.cur_vblank: self.io.set(V4L2_CID_VBLANK, vb) self.io.set(V4L2_CID_EXPOSURE, exp) elif vb < self.cur_vblank: self.io.set(V4L2_CID_EXPOSURE, exp) self.io.set(V4L2_CID_VBLANK, vb) else: self.io.set(V4L2_CID_EXPOSURE, exp) def _apply(self, vb, exp, ag_code, dg_code): self._apply_exp_vblank(vb, exp) self.io.set(V4L2_CID_ANALOGUE_GAIN, ag_code) if self.has_dgain: self.io.set(V4L2_CID_DIGITAL_GAIN, dg_code) self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg = vb, exp, ag_code, dg_code def apply_initial(self): self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x) vb, exp, ag, dg = self.plan(self.ev_total) self._apply(vb, exp, ag, dg) self.cooldown = 2 def update(self, raw_p50, raw_p95): """Adjust exposure/gain from raw 0..255 luma stats with 2-frame pipeline settling cooldown.""" if self.cooldown > 0: self.cooldown -= 1 return False if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0: return False ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) if raw_p95 > 240.0: ratio = min(ratio, max(0.25, 200.0 / max(raw_p95, 1.0))) elif raw_p95 > 120.0 and raw_p95 * ratio > 235.0: ratio = max(0.25, min(ratio, 235.0 / raw_p95)) new_ev = max(self.e_min, min(self.ev_total * (ratio ** 0.75), self.e_max)) if abs(new_ev - self.ev_total) <= self.ev_total * 0.05: return False vb, exp, ag, dg = self.plan(new_ev) self.ev_total = new_ev if (vb, exp, ag, dg) != (self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg): self._apply(vb, exp, ag, dg) self.cooldown = 2 return True return False def close(self): if self._closed: return self._closed = True try: if self.has_dgain: try: self.io.set(V4L2_CID_DIGITAL_GAIN, self.init_dg) except Exception: pass try: self.io.set(V4L2_CID_ANALOGUE_GAIN, self.init_ag) except Exception: pass try: self._apply_exp_vblank(self.init_vblank, self.init_exp) except Exception: pass finally: self.io.close() def rotate_bgr(bgr, rot, cv2_mod): """Rotate BGR frame according to libcamera.properties.Rotation (CCW mounting angle).""" rot_i = int(rot) % 360 if rot_i == 90: return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE) if rot_i == 180: return cv2_mod.rotate(bgr, cv2_mod.ROTATE_180) if rot_i == 270: return cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE) return bgr def debayer_quad_csi2p( raw_buf, width, height, stride, rot=0, offset=0, target_size=(640, 480), gamma_lut=None, tone_lut=None, return_stats=False, cv2_mod=None, np_mod=None, ): """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into upright BGR uint8.""" if np_mod is None: import numpy as np_mod if cv2_mod is None: import cv2 as cv2_mod arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride)) even_h = (height // 2) * 2 even_w = (width // 4) * 4 row_bytes = (even_w // 4) * 5 p8 = arr[:even_h, :row_bytes].reshape((even_h // 2, 2, even_w // 4, 5))[:, :, :, :4] s = p8[:, 0, :, :].astype(np_mod.uint16) s += p8[:, 1, :, :] bayer10 = np_mod.ascontiguousarray((s[:, :, 0::2] + s[:, :, 1::2]).reshape((even_h // 2, even_w // 2))) bgr16 = cv2_mod.cvtColor(bayer10, cv2_mod.COLOR_BayerBG2BGR) if target_size is not None: bgr16 = cv2_mod.resize(bgr16, target_size, interpolation=cv2_mod.INTER_AREA) f = bgr16.astype(np_mod.float32) fh, fw = f.shape[:2] sub_raw = f[8:-8:4, 8:-8:4] if (fh > 32 and fw > 32) else f black = float(np_mod.clip(np_mod.percentile(sub_raw, 1), 0.0, 64.0)) f = np_mod.maximum(f - black, 0.0) * (255.0 / max(1020.0 - black, 1.0)) sub = f[::4, ::4] if (fh >= 32 and fw >= 32) else f means = sub.mean(axis=(0, 1)) avg = float(means.mean()) raw_luma = sub.mean(axis=2) raw_p50 = float(np_mod.percentile(raw_luma, 50)) raw_p95 = float(np_mod.percentile(raw_luma, 95)) if avg > 0.25: gains = np_mod.clip(avg / np_mod.maximum(means, max(avg * 0.4, 0.25)), 0.7, 2.0) else: gains = np_mod.ones(3, dtype=np_mod.float32) if raw_p95 < 0.8 and avg < 0.35: boost = 1.0 else: boost = float(np_mod.clip(52.0 / max(raw_p50, avg, 0.25), 1.0, 20.0)) if raw_p95 * boost > 240.0: boost = max(1.0, min(boost, 300.0 / max(raw_p95, 1.0))) if tone_lut is None: tone_lut = _get_tone_lut(np_mod) idx = np_mod.clip((f * (gains * boost) * (4095.0 / 768.0)).astype(np_mod.int32), 0, 4095) out = tone_lut[idx] if boost > 1.8 and out.shape[0] >= 64 and out.shape[1] >= 64: lab = cv2_mod.cvtColor(out, cv2_mod.COLOR_BGR2LAB) l_ch, a_ch, b_ch = cv2_mod.split(lab) l_ch = cv2_mod.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l_ch) a_ch = cv2_mod.GaussianBlur(a_ch, (5, 5), 0) b_ch = cv2_mod.GaussianBlur(b_ch, (5, 5), 0) out = cv2_mod.cvtColor(cv2_mod.merge([l_ch, a_ch, b_ch]), cv2_mod.COLOR_LAB2BGR) res = np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) if return_stats: return res, (raw_p50, raw_p95) return res class LibcameraCamera: """Capture BGR frames via python-libcamera (MIPI/SoftISP phone cameras).""" def __init__(self, device): problem = camera_problem(device) if problem: raise Fail(problem, 2) import cv2 import mmap import numpy as np libcamera = _import_libcamera() self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None) self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None self._tone_lut = _build_tone_lut(np) self.sc = None self.raw_sc = None self.alloc = None self.requests = [] self._started = False self._ae = None cid = device[len("libcamera:"):] self.cm = libcamera.CameraManager.singleton() self.cam = self.cm.get(cid) if self.cam is None: raise Fail("camera %s disappeared" % device, 2) self.rot = int(self.cam.properties.get(libcamera.properties.Rotation) or 0) self.model = str(self.cam.properties.get(libcamera.properties.Model) or "").lower() try: self.cam.acquire() except Exception as e: raise Fail("couldn't acquire camera %s: %s" % (device, e), 2) try: if self.model in QUAD_BAYER_MODELS: subdev = find_sensor_subdev(self.model) if subdev: ae = None try: ae = QuadSensorAE(subdev) cfg = self.cam.generate_configuration([libcamera.StreamRole.Raw]) if cfg is not None and len(cfg) >= 1: cfg.validate() self.cam.configure(cfg) self.raw_sc = cfg.at(0) self.sc = None self._ae = ae except Exception: if ae is not None: ae.close() self._ae = None self.raw_sc = None if self.raw_sc is None: try: cfg = self.cam.generate_configuration([ libcamera.StreamRole.Viewfinder, libcamera.StreamRole.Raw, ]) if cfg is not None and len(cfg) >= 2: cfg.at(0).size = libcamera.Size(640, 480) cfg.validate() self.cam.configure(cfg) self.sc = cfg.at(0) self.raw_sc = cfg.at(1) except Exception: self.raw_sc = None if self.sc is None and self.raw_sc is None: cfg = self.cam.generate_configuration([libcamera.StreamRole.Viewfinder]) self.sc = cfg.at(0) self.sc.size = libcamera.Size(640, 480) cfg.validate() self.cam.configure(cfg) self.alloc = libcamera.FrameBufferAllocator(self.cam) self.requests = [] if self.sc is not None and self.raw_sc is not None: if self.alloc.allocate(self.sc.stream) <= 0 or self.alloc.allocate(self.raw_sc.stream) <= 0: raise Fail("couldn't allocate camera buffers for %s" % device, 2) for b0, b1 in zip(self.alloc.buffers(self.sc.stream), self.alloc.buffers(self.raw_sc.stream)): r = self.cam.create_request() r.add_buffer(self.sc.stream, b0) r.add_buffer(self.raw_sc.stream, b1) self.requests.append(r) elif self.raw_sc is not None: if self.alloc.allocate(self.raw_sc.stream) <= 0: raise Fail("couldn't allocate raw buffers for %s" % device, 2) for b in self.alloc.buffers(self.raw_sc.stream): r = self.cam.create_request() r.add_buffer(self.raw_sc.stream, b) self.requests.append(r) else: if self.alloc.allocate(self.sc.stream) <= 0: raise Fail("couldn't allocate camera buffers for %s" % device, 2) for buf in self.alloc.buffers(self.sc.stream): r = self.cam.create_request() r.add_buffer(self.sc.stream, buf) self.requests.append(r) self.cm.get_ready_requests() self.cam.start() self._started = True if self._ae is not None: try: self._ae.apply_initial() except Exception: self._ae.close() self._ae = None for r in self.requests: self.cam.queue_request(r) except Exception as e: self.close() if isinstance(e, Fail): raise raise Fail("couldn't start libcamera %s: %s" % (device, e), 2) self._first = True def _to_bgr(self, buf): p = buf.planes[0] w, h, stride = self.sc.size.width, self.sc.size.height, self.sc.stride fmt = str(self.sc.pixel_format) with self.mmap.mmap(p.fd, p.offset + p.length, self.mmap.MAP_SHARED, self.mmap.PROT_READ) as mm: raw = bytes(mm[p.offset:p.offset + p.length]) arr = self.np.frombuffer(raw, dtype=self.np.uint8) if fmt in ("ABGR8888", "XBGR8888", "ARGB8888", "XRGB8888"): img = arr[:h * stride].reshape((h, stride // 4, 4))[:, :w, :3] bgr = self.np.ascontiguousarray(img[:, :, ::-1]) if "BGR" in fmt else self.np.ascontiguousarray(img) elif fmt in ("RGB888", "BGR888"): img = arr[:h * stride].reshape((h, stride // 3, 3))[:, :w, :] bgr = self.np.ascontiguousarray(img[:, :, ::-1]) if fmt == "RGB888" else self.np.ascontiguousarray(img) else: raise Fail("unsupported libcamera pixel format %s" % fmt, 2) return self.np.ascontiguousarray(rotate_bgr(bgr, self.rot, self.cv2)) def _raw_to_bgr(self, buf): p = buf.planes[0] w, h, stride = self.raw_sc.size.width, self.raw_sc.size.height, self.raw_sc.stride fmt = str(self.raw_sc.pixel_format) if "CSI2P" not in fmt.upper(): raise Fail("unsupported quad raw format %s" % fmt, 2) with self.mmap.mmap(p.fd, p.offset + p.length, self.mmap.MAP_SHARED, self.mmap.PROT_READ) as mm: frame, (raw_p50, raw_p95) = debayer_quad_csi2p( mm, w, h, stride, rot=self.rot, offset=p.offset, target_size=(640, 480), tone_lut=self._tone_lut, return_stats=True, cv2_mod=self.cv2, np_mod=self.np, ) if self._ae is not None: try: self._ae.update(raw_p50, raw_p95) except Exception: pass return frame def _requeue(self, req): if self._reuse_arg is not None: try: req.reuse(self._reuse_arg) except TypeError: self._reuse_arg = None req.reuse() else: req.reuse() self.cam.queue_request(req) def read(self): timeout = 3.0 if self._first else 1.5 self._first = False deadline = time.monotonic() + timeout while time.monotonic() < deadline: ready = self.cm.get_ready_requests() if ready: for old in ready[:-1]: self._requeue(old) req = ready[-1] frame = None try: if req.status == self.libcamera.Request.Status.Complete: if self.raw_sc is not None and self.raw_sc.stream in req.buffers: frame = self._raw_to_bgr(req.buffers[self.raw_sc.stream]) elif self.sc is not None and self.sc.stream in req.buffers: frame = self._to_bgr(req.buffers[self.sc.stream]) finally: self._requeue(req) if frame is not None: return frame time.sleep(0.01) return None def close(self): if getattr(self, "_ae", None) is not None: try: self._ae.close() except Exception: pass self._ae = None try: if getattr(self, "_started", False): self.cam.stop() except Exception: pass self._started = False try: self.cm.get_ready_requests() except Exception: pass self.requests = [] self.alloc = None self.sc = None self.raw_sc = None try: self.cam.release() except Exception: pass class V4L2Camera: def __init__(self, device): problem = camera_problem(device) if problem: raise Fail(problem, 2) 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("OpenCV couldn't start camera %s (is another app using it?)" % device, 2) ok, _ = self.cap.read() if not ok: self.cap.release() raise Fail("camera %s gives no picture (is another app using it?)" % 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, loop=False): if cfg.device.startswith("images:"): return ImageCamera(cfg.device, cfg, loop) if cfg.device.startswith("libcamera:"): return LibcameraCamera(cfg.device) 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 = clean_label(label, nid) 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 clean_label(label, nid): return (label or "Face %d" % nid).replace("\t", " ").replace("\n", " ").strip()[:60] or "Face %d" % nid MAX_APPLY = 1 << 20 def cmd_apply(cfg, user, out, data=None): """Add and remove faces in one step (what the "Add a face" window's Apply runs as root). The embeddings come from the user's own camera process: anyone who can type the admin password could enroll any face anyway, so the password is the check, as for enroll.""" check_user(user) if data is None: data = sys.stdin.buffer.read(MAX_APPLY + 1) if len(data) > MAX_APPLY: raise Fail("too much data") try: req = json.loads(data.decode("utf-8") or "{}") except ValueError: raise Fail("bad request") if not isinstance(req, dict): raise Fail("bad request") adds = req.get("add") or [] removes = [str(r) for r in (req.get("remove") or [])] if not isinstance(adds, list) or len(adds) > 8: raise Fail("bad request") faces = load_faces(cfg, user) dims = {len(v) for f in faces for v in f.get("vectors", [])} new = [] for a in adds: vecs = a.get("vectors") if isinstance(a, dict) else None if not isinstance(vecs, list) or not 1 <= len(vecs) <= 32: raise Fail("bad face data") for v in vecs: if not isinstance(v, list) or not 4 <= len(v) <= 1024 or \ not all(isinstance(x, (int, float)) and math.isfinite(x) for x in v): raise Fail("bad face data") dims.add(len(v)) if len(dims) > 1: raise Fail("face data from another recognizer") label = a.get("label") if isinstance(a.get("label"), str) else "" new.append((label, vecs)) known = {str(f["id"]) for f in faces} missing = [r for r in removes if r not in known] if missing: raise Fail("no face %s for %s" % (", ".join(missing), user)) nid = max([f["id"] for f in faces] + [0]) # ids aren't reused faces = [f for f in faces if str(f["id"]) not in removes] for label, vecs in new: nid += 1 faces.append({"id": nid, "label": clean_label(label, nid), "created": time.strftime("%Y-%m-%d"), "vectors": [[round(float(x), 6) for x in v] for v in vecs]}) save_faces(cfg, user, faces) parts = [] if new: parts.append("added %s" % ", ".join(f["label"] for f in faces[-len(new):])) if removes: parts.append("removed %d face%s" % (len(removes), "" if len(removes) == 1 else "s")) msg = " and ".join(parts) or "nothing to change" out.emit("done", msg[:1].upper() + msg[1:]) return 0 PREVIEW_W = 320 THUMB = 96 def resize_rows(rows, w, h): """Nearest-pixel resize of rows of gray values (the fake camera's frames).""" sh, sw = len(rows), len(rows[0]) return [[rows[y * sh // h][x * sw // w] for x in range(w)] for y in range(h)] def rgb_bytes(frame, rec, box=None, size=None): """`frame` (or its `box` = (x, y, w, h)) as RGB bytes at `size` = (w, h).""" if isinstance(frame, list): if box: x, y, w, h = box frame = [r[x:x + w] for r in frame[y:y + h]] g = resize_rows(frame, *size) return bytes(v for r in g for v in r for _ in range(3)) cv2 = rec.cv2 if hasattr(rec, "cv2") else __import__("cv2") if box: x, y, w, h = box frame = frame[y:y + h, x:x + w] if frame.ndim == 2: frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR) frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA) return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB).tobytes() def frame_size(frame): if isinstance(frame, list): return len(frame[0]), len(frame) return frame.shape[1], frame.shape[0] def send_blob(header, data): """A binary message: `header LEN` on a line, then LEN bytes.""" sys.stdout.flush() sys.stdout.buffer.write(("%s %d\n" % (header, len(data))).encode()) sys.stdout.buffer.write(data) sys.stdout.buffer.flush() def elevated(args): """argv running chandra-face `args` as root through run0 or pkexec (polkit asks first).""" me = os.path.realpath(sys.argv[0]) run0 = shutil.which("run0") if run0 and os.path.isdir("/run/systemd/system"): return [run0, "--background=", "--", sys.executable, "-I", me] + args pk = shutil.which("pkexec") if pk: return [pk, sys.executable, "-I", me] + args raise Fail("needs root, and neither run0 nor pkexec is installed") def cmd_camera(cfg, user, label, out, cfg_path, no_elevate): """The "Add a face" window's camera, run as the session user (no root, no password). Out ("--machine" lines): `frame W H BX BY BW BH LEN` + LEN bytes of RGB (the live picture, about 12 a second; the box is -1s without one face), `snap ID W H LEN` + RGB (a kept snap, cropped to the face), `info` / `error` / `done` lines, `applied CODE` at the end of an apply. In (stdin lines): `snap`, `drop ID`, `apply REMOVE-IDS` (comma-separated, may be empty), `quit`. After a failed apply (no password, say) the camera starts again and the snaps are kept. The pictures stay in this process's memory: nothing is written to disk; only the embeddings of the snaps kept go to the root `apply`, through a pipe.""" check_user(user) rec = make_recognizer(cfg) try: cam = open_camera(cfg, loop=True) except Fail as e: # Say why, and which cameras there are: the window offers them. out.error(str(e)) cmd_cameras(out) return e.code snaps = {} # id -> embedding next_id = 1 last = None last_sent = 0.0 pending = b"" out.info("Look at the camera and press Snap") try: while True: frame = cam.read() if frame is None: out.error("The camera gave no picture") return 2 if isinstance(cam, ImageCamera): time.sleep(max(cfg.frame_delay, 0.03)) last = frame now = time.monotonic() if now - last_sent >= 0.08: last_sent = now w, h = frame_size(frame) pw = min(PREVIEW_W, w) ph = max(1, h * pw // w) dets = rec.detect(frame) if rec.brightness(frame) >= cfg.dark else [] bx = (-1, -1, -1, -1) if len(dets) == 1: d = dets[0] bx = (d.x * pw // w, d.y * ph // h, d.w * pw // w, d.h * ph // h) send_blob("frame %d %d %d %d %d %d" % ((pw, ph) + bx), rgb_bytes(frame, rec, size=(pw, ph))) r, _, _ = select.select([0], [], [], 0) if not r: continue got = os.read(0, 4096) if not got: return 0 pending += got while b"\n" in pending: line, pending = pending.split(b"\n", 1) words = line.decode("utf-8", "replace").strip().split(" ", 1) cmd, arg = words[0], (words[1] if len(words) > 1 else "") if cmd == "quit": return 0 if cmd == "drop": snaps.pop(arg, None) elif cmd == "snap": v, why, box = snap_face(cfg, rec, last) if v is None: out.error(why) continue sid = str(next_id) next_id += 1 snaps[sid] = v send_blob("snap %s %d %d" % (sid, THUMB, THUMB), rgb_bytes(last, rec, box, (THUMB, THUMB))) elif cmd == "apply": cam.close() cam = None removes = [r for r in arg.split(",") if r.strip()] req = {"add": [{"label": label or "", "vectors": list(snaps.values())}] if snaps else [], "remove": removes} code = run_apply(cfg, user, out, req, cfg_path, no_elevate) out.emit("applied", str(code)) if code == 0: return 0 # The password was refused or cancelled: back to the camera, snaps kept. cam = open_camera(cfg, loop=True) finally: if cam is not None: cam.close() def snap_face(cfg, rec, frame): """(embedding, "", square face box) for the one face in `frame`, or (None, why, None).""" if frame is None: return None, "No picture yet", None if rec.brightness(frame) < cfg.dark: return None, "The picture is too dark", None dets = rec.detect(frame) if not dets: return None, "No face in view", None if len(dets) > 1: return None, "More than one face in view", None d = dets[0] if d.w < cfg.min_face and d.h < cfg.min_face and cfg.backend != "fake": return None, "Come closer to the camera", None if cfg.require_ir and not rec.gray(frame): return None, "Needs an infrared camera (require_ir)", None v = [round(x, 6) for x in rec.embed(frame, d)] w, h = frame_size(frame) side = min(int(max(d.w, d.h) * 1.4), w, h) x = min(max(0, d.x + d.w // 2 - side // 2), w - side) y = min(max(0, d.y + d.h // 2 - side // 2), h - side) return v, "", (x, y, side, side) def run_apply(cfg, user, out, req, cfg_path, no_elevate): """Run `apply` as root with `req` on its stdin, passing on what it says.""" data = json.dumps(req).encode() if os.geteuid() == 0 or no_elevate: try: return cmd_apply(cfg, user, out, data) except Fail as e: out.error(str(e)) return e.code args = ["apply", "--machine", "--user", user] if cfg_path != DEFAULT_CONFIG: args += ["--config", cfg_path] out.info("Waiting for the password…") p = subprocess.Popen(elevated(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) try: p.stdin.write(data) p.stdin.close() except BrokenPipeError: pass said = False for raw in p.stdout: line = raw.decode("utf-8", "replace").rstrip("\n") kind = line.split(" ", 1)[0] if kind in ("info", "error", "done"): said = said or kind != "info" sys.stdout.write(line + "\n") sys.stdout.flush() code = p.wait() if not said: out.error("Nothing changed: the administrator password wasn't given") return code or 1 return code 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 = "OpenCV is missing: run just install" 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: problem = camera_problem(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_cameras(out): """Lines `camera PATHNAMEWHY` (WHY empty: it takes pictures).""" for p, n, why in list_cameras(): out.emit("camera", "%s\t%s\t%s" % (p, n, why)) return 0 def cmd_set_camera(cfg, path, out): """Point face.conf's `device` at `path` (root), after checking it is a camera.""" if path.startswith("libcamera:"): why = camera_problem(path) if why: raise Fail(why) name = next((n for p, n, _ in list_libcameras() if p == path), path) else: if not path.startswith("/dev/") or not os.path.exists(path): raise Fail("no camera at %s" % path) name, why = query_camera(path) if why: raise Fail("%s: %s" % (path, why)) conf = cfg.path text = open(conf).read() if os.path.exists(conf) else "[face]\n" lines = text.split("\n") at = next((i for i, l in enumerate(lines) if re.match(r"^\s*device\s*=", l)), None) if at is None: sec = next((i for i, l in enumerate(lines) if l.strip() == "[face]"), None) if sec is None: lines += ["[face]"] sec = len(lines) - 1 lines.insert(sec + 1, "device = " + path) else: lines[at] = "device = " + path os.makedirs(os.path.dirname(conf) or ".", exist_ok=True) write_atomic(conf, "\n".join(lines), 0o644) out.emit("done", "Camera: %s" % (name or path)) 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", "apply", "set-camera") def elevate(argv, user): """Run this command again as root through run0 (systemd) or pkexec: polkit asks first.""" args = list(argv) if "--user" not in argv: args += ["--user", user] cmd = elevated(args) os.execv(cmd[0], cmd) 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 == "apply": return cmd_apply(cfg, user, out) if cmd == "camera": return cmd_camera(cfg, user, label, out, cfg_path, no_elevate) if cmd == "cameras": return cmd_cameras(out) if cmd == "set-camera": if not params: raise Fail("set-camera PATH (see chandra-face cameras)") return cmd_set_camera(cfg, params[0], 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 except BrokenPipeError: return 0 # the window that read us went away if __name__ == "__main__": sys.exit(main(sys.argv[1:]))