Face unlock: a Howdy-style PAM module, shown in the password dialog and set up in Settings
CI / test (push) Successful in 2m6s
CI / test (push) Successful in 2m6s
- face/pam_chandra_face.so (`-auth sufficient`): runs `chandra-face compare` as root with a clean
environment, forwards what it says as PAM_TEXT_INFO / PAM_ERROR_MSG, and maps its exit status
to success / auth error / unavailable, so the password always still works. Skips remote
sessions (PAM_RHOST, SSH_CONNECTION), a closed lid and users without faces; refuses a helper
that isn't root's; kills one that hangs (timeout + 6 s).
- face/chandra-face (Python + OpenCV): YuNet finds the face, SFace embeds it, cosine similarity
against the enrolled embeddings (threshold 0.42, two matching frames, dark IR warm-up frames
skipped, optional require_ir). enroll / list / remove / clear / test / status / pam
enable|disable / fetch-models (sha256-pinned opencv_zoo models). Embeddings only, in
/var/lib/chandra-face/USER/faces.json (root, 0600); labels in faces.list (0644). Store, config
and models must be root's and not writable by others. Root commands re-run through run0 (or
pkexec), so polkit asks first. Settings in /etc/chandra/face.conf.
- `just install-face [--pam]`, `just uninstall-face [--purge]` (face/install.py; uninstall takes
the module out of every PAM service first). `pam enable` inserts before the first auth or
@include line (Debian's sudo has only @include common-auth), keeping a .bak.
- Password dialog: a face row ("Looking for your face…" with a sweeping ring, "Face
recognized", or why not, "Type your password instead"); typing and Enter during the scan go in
when PAM asks for the password. Howdy's pam_howdy.so messages are understood too.
- Settings > Session > Face unlock: "Use my face for passwords" (polkit-1 + sudo), the enrolled
faces (Remove takes a second click), "Add a face…", and the tool's progress. New `face-unlock`
capability: tables 24 (status) and 25 (faces), request 44, in the wasmer/wasmtime stub, the Rust
host, the MoonBit wasmhost and chandra:host/plasmoids. compositor/shell/face.mbt runs the tool
on a socket so the compositor never waits.
- Tests: face/test_face.py (fake camera of PGM frames + fake recognizer; --pam builds the module
and runs it through pamtester), dialog states and message parsing (polkit_test), the dialog via
a mock helper (auth_test, shots 14/15), Settings against a fake chandra-face (face_test).
scripts/test.sh runs them (compositor/polkit was missing from its native list), CI installs
libpam0g-dev + pamtester. Also regenerated two stale desktop-module bindings (doc comments).
- docs/face-unlock.md, including the limits of 2D face recognition.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
This commit is contained in:
47 files changed
+2781
-29
No files matched your search
Binary file not shown.
Executable
+774
@@ -0,0 +1,774 @@
|
||||
#!/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:]))
|
||||
@@ -0,0 +1,26 @@
|
||||
# Face unlock (docs/face-unlock.md). Installed as /etc/chandra/face.conf; must stay root's.
|
||||
[face]
|
||||
# no: the PAM module stays quiet and PAM goes straight on to the password.
|
||||
enabled = yes
|
||||
# opencv: YuNet finds the face, SFace compares it (models from `chandra-face fetch-models`).
|
||||
backend = opencv
|
||||
# The camera. An infrared camera (often /dev/video2 on Windows Hello laptops) works in the dark
|
||||
# and is much harder to fool with a photo than the normal webcam.
|
||||
device = /dev/video0
|
||||
# Seconds to look for a face before PAM moves on to the password.
|
||||
timeout = 4
|
||||
# How alike two faces must be (cosine similarity of SFace embeddings, -1..1). OpenCV suggests
|
||||
# 0.363; higher is stricter (fewer false accepts, more "not recognized").
|
||||
threshold = 0.42
|
||||
# How many frames must match.
|
||||
matches = 2
|
||||
# Frames darker than this (0-255 average) are skipped: IR emitters take a moment to light up.
|
||||
dark = 25
|
||||
# Smallest face to use, in pixels (a face far away is too blurry to trust).
|
||||
min_face = 80
|
||||
# yes: only accept grey (infrared) frames, refusing a colour webcam.
|
||||
require_ir = no
|
||||
# Frames taken when enrolling a face.
|
||||
enroll_frames = 5
|
||||
store = /var/lib/chandra-face
|
||||
models = /usr/local/share/chandra/face
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install (or remove) face unlock. Run as root (`just install-face` does this through
|
||||
scripts/as-root):
|
||||
|
||||
run0 python3 face/install.py # install, fetch the face models
|
||||
run0 python3 face/install.py --pam # ... and use it for polkit-1 and sudo
|
||||
run0 python3 face/install.py --no-models
|
||||
run0 python3 face/install.py --remove # take it out of every PAM service, uninstall
|
||||
run0 python3 face/install.py --remove --purge # ... and delete the enrolled faces
|
||||
|
||||
Installs:
|
||||
/usr/local/lib/chandra/chandra-face the helper (enroll, compare, ...), root's
|
||||
/usr/local/bin/chandra-face -> the helper
|
||||
<PAM module dir>/pam_chandra_face.so the PAM module (built here with cc; needs libpam headers)
|
||||
/etc/chandra/face.conf settings (kept when it exists)
|
||||
/var/lib/chandra-face/ enrolled faces
|
||||
/usr/local/share/chandra/face/*.onnx the YuNet and SFace models (downloaded, checksummed)
|
||||
|
||||
PAM files are only changed with --pam (or later with `chandra-face pam enable SERVICE`); the line
|
||||
is `-auth sufficient pam_chandra_face.so`, before the service's other auth lines, so the password
|
||||
still works whenever the face doesn't.
|
||||
"""
|
||||
import glob, os, shutil, subprocess, sys
|
||||
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
helper = "/usr/local/lib/chandra/chandra-face"
|
||||
link = "/usr/local/bin/chandra-face"
|
||||
conf = "/etc/chandra/face.conf"
|
||||
store = "/var/lib/chandra-face"
|
||||
models = "/usr/local/share/chandra/face"
|
||||
|
||||
|
||||
def pam_dir():
|
||||
"""Where this system's PAM modules live (next to pam_unix.so)."""
|
||||
cands = ["/usr/lib/security", "/lib/security", "/usr/lib64/security", "/lib64/security"]
|
||||
cands += glob.glob("/usr/lib/*-linux-gnu*/security") + glob.glob("/lib/*-linux-gnu*/security")
|
||||
for d in cands:
|
||||
if os.path.exists(os.path.join(d, "pam_unix.so")):
|
||||
return os.path.realpath(d)
|
||||
sys.exit("can't find the PAM module directory (no pam_unix.so)")
|
||||
|
||||
|
||||
if os.geteuid() != 0:
|
||||
sys.exit("run as root: run0 python3 face/install.py (or sudo), or `just install-face`")
|
||||
|
||||
mod = os.path.join(pam_dir(), "pam_chandra_face.so")
|
||||
|
||||
if "--remove" in sys.argv:
|
||||
# PAM first, so no service points at a module that is about to go.
|
||||
if os.path.exists(helper):
|
||||
subprocess.call([sys.executable, "-I", helper, "--no-elevate", "pam", "disable"]
|
||||
+ sorted(os.listdir("/etc/pam.d")))
|
||||
for p in (mod, link, helper):
|
||||
if os.path.lexists(p):
|
||||
os.remove(p)
|
||||
print("removed", p)
|
||||
if os.path.isdir(models):
|
||||
shutil.rmtree(models)
|
||||
print("removed", models)
|
||||
if "--purge" in sys.argv:
|
||||
for p in (store,):
|
||||
if os.path.isdir(p):
|
||||
shutil.rmtree(p)
|
||||
print("removed", p)
|
||||
if os.path.exists(conf):
|
||||
os.remove(conf)
|
||||
print("removed", conf)
|
||||
sys.exit(0)
|
||||
|
||||
os.umask(0o022)
|
||||
os.makedirs(os.path.dirname(helper), exist_ok=True)
|
||||
shutil.copyfile(os.path.join(here, "chandra-face"), helper + ".new")
|
||||
os.chmod(helper + ".new", 0o755)
|
||||
os.replace(helper + ".new", helper)
|
||||
print("installed", helper)
|
||||
if os.path.lexists(link):
|
||||
os.remove(link)
|
||||
os.symlink(helper, link)
|
||||
print("linked", link, "->", helper)
|
||||
|
||||
cc = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
|
||||
if not cc:
|
||||
sys.exit("no C compiler: install gcc (and the libpam headers: libpam0g-dev / pam-devel)")
|
||||
subprocess.check_call([cc, "-O2", "-Wall", "-shared", "-fPIC", "-o", mod + ".new",
|
||||
"-DCHANDRA_FACE_HELPER=\"%s\"" % helper,
|
||||
os.path.join(here, "pam_chandra_face.c"), "-lpam"])
|
||||
os.chmod(mod + ".new", 0o644)
|
||||
os.replace(mod + ".new", mod)
|
||||
print("installed", mod)
|
||||
|
||||
if not os.path.exists(conf):
|
||||
os.makedirs(os.path.dirname(conf), exist_ok=True)
|
||||
shutil.copyfile(os.path.join(here, "face.conf"), conf)
|
||||
os.chmod(conf, 0o644)
|
||||
print("installed", conf)
|
||||
os.makedirs(store, 0o755, exist_ok=True)
|
||||
os.chmod(store, 0o755)
|
||||
|
||||
if "--no-models" not in sys.argv:
|
||||
subprocess.check_call([sys.executable, "-I", helper, "--no-elevate", "fetch-models"])
|
||||
if "--pam" in sys.argv:
|
||||
subprocess.check_call([sys.executable, "-I", helper, "--no-elevate", "pam", "enable"])
|
||||
try:
|
||||
import cv2 # noqa
|
||||
except ImportError:
|
||||
print("note: install OpenCV for Python (python3-opencv / python-opencv / opencv-python) "
|
||||
"before enrolling a face")
|
||||
print("enroll a face: Settings > Session > Face unlock, or `chandra-face enroll`")
|
||||
@@ -0,0 +1,241 @@
|
||||
/* pam_chandra_face.so: face unlock for PAM, in the style of Howdy (docs/face-unlock.md).
|
||||
*
|
||||
* -auth sufficient pam_chandra_face.so [helper=PATH] [python=PATH] [config=PATH] [timeout=SECONDS]
|
||||
* [quiet] [debug]
|
||||
*
|
||||
* Runs `chandra-face compare --user USER` as root with a clean environment and forwards what it
|
||||
* says to the application's conversation as PAM_TEXT_INFO / PAM_ERROR_MSG (Chandra's password
|
||||
* dialog shows them as the face status; sudo prints them). The helper's exit status decides:
|
||||
* 0 -> PAM_SUCCESS, 1 -> PAM_AUTH_ERR, anything else -> PAM_AUTHINFO_UNAVAIL. With "sufficient",
|
||||
* anything but success falls through to the next module, so the password always still works.
|
||||
*
|
||||
* Skipped (PAM_AUTHINFO_UNAVAIL, silently) for remote logins (PAM_RHOST, or SSH_CONNECTION in the
|
||||
* environment) and when every laptop lid is closed (the camera can't see anyone). A helper that
|
||||
* hangs is killed after timeout + 6 seconds.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <syslog.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define PAM_SM_AUTH
|
||||
#include <security/pam_appl.h>
|
||||
#include <security/pam_ext.h>
|
||||
#include <security/pam_modules.h>
|
||||
|
||||
#ifndef CHANDRA_FACE_HELPER
|
||||
#define CHANDRA_FACE_HELPER "/usr/local/lib/chandra/chandra-face"
|
||||
#endif
|
||||
#ifndef CHANDRA_FACE_PYTHON
|
||||
#define CHANDRA_FACE_PYTHON "/usr/bin/python3"
|
||||
#endif
|
||||
|
||||
struct opts {
|
||||
const char *python;
|
||||
const char *helper;
|
||||
const char *config;
|
||||
int timeout;
|
||||
int quiet;
|
||||
int debug;
|
||||
};
|
||||
|
||||
static void parse_opts(int argc, const char **argv, struct opts *o) {
|
||||
o->python = CHANDRA_FACE_PYTHON;
|
||||
o->helper = CHANDRA_FACE_HELPER;
|
||||
o->config = NULL;
|
||||
o->timeout = 4;
|
||||
o->quiet = 0;
|
||||
o->debug = 0;
|
||||
for (int i = 0; i < argc; i++) {
|
||||
if (!strncmp(argv[i], "helper=", 7)) o->helper = argv[i] + 7;
|
||||
else if (!strncmp(argv[i], "python=", 7)) o->python = argv[i] + 7;
|
||||
else if (!strncmp(argv[i], "config=", 7)) o->config = argv[i] + 7;
|
||||
else if (!strncmp(argv[i], "timeout=", 8)) o->timeout = atoi(argv[i] + 8);
|
||||
else if (!strcmp(argv[i], "quiet")) o->quiet = 1;
|
||||
else if (!strcmp(argv[i], "debug")) o->debug = 1;
|
||||
}
|
||||
if (o->timeout < 1) o->timeout = 1;
|
||||
if (o->timeout > 30) o->timeout = 30;
|
||||
}
|
||||
|
||||
/* Whether a lid switch exists and every one says closed. */
|
||||
static int lid_closed(void) {
|
||||
DIR *d = opendir("/proc/acpi/button/lid");
|
||||
if (!d) return 0;
|
||||
int any = 0, open_one = 0;
|
||||
struct dirent *e;
|
||||
while ((e = readdir(d))) {
|
||||
if (e->d_name[0] == '.') continue;
|
||||
char p[512], buf[128] = {0};
|
||||
snprintf(p, sizeof p, "/proc/acpi/button/lid/%s/state", e->d_name);
|
||||
FILE *f = fopen(p, "r");
|
||||
if (!f) continue;
|
||||
if (fgets(buf, sizeof buf, f)) {
|
||||
any = 1;
|
||||
if (!strstr(buf, "closed")) open_one = 1;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
closedir(d);
|
||||
return any && !open_one;
|
||||
}
|
||||
|
||||
static int is_remote(pam_handle_t *pamh) {
|
||||
const void *rhost = NULL;
|
||||
if (pam_get_item(pamh, PAM_RHOST, &rhost) == PAM_SUCCESS && rhost) {
|
||||
const char *h = rhost;
|
||||
if (*h && strcmp(h, "localhost") && strcmp(h, "127.0.0.1") && strcmp(h, "::1")) return 1;
|
||||
}
|
||||
if (getenv("SSH_CONNECTION") || getenv("SSH_CLIENT") || getenv("SSHD_OPTS")) return 1;
|
||||
const char *pe = pam_getenv(pamh, "SSH_CONNECTION");
|
||||
return pe && *pe;
|
||||
}
|
||||
|
||||
/* Forward one helper line ("info TEXT" / "error TEXT") to the conversation. */
|
||||
static void forward(pam_handle_t *pamh, const struct opts *o, char *line) {
|
||||
if (!strncmp(line, "info ", 5)) {
|
||||
if (!o->quiet) pam_info(pamh, "%s", line + 5);
|
||||
} else if (!strncmp(line, "error ", 6)) {
|
||||
if (!o->quiet) pam_error(pamh, "%s", line + 6);
|
||||
}
|
||||
}
|
||||
|
||||
static long now_ms(void) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return ts.tv_sec * 1000L + ts.tv_nsec / 1000000L;
|
||||
}
|
||||
|
||||
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) {
|
||||
(void)flags;
|
||||
struct opts o;
|
||||
parse_opts(argc, argv, &o);
|
||||
const char *user = NULL;
|
||||
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || !user || !*user) return PAM_USER_UNKNOWN;
|
||||
if (is_remote(pamh)) return PAM_AUTHINFO_UNAVAIL;
|
||||
if (lid_closed()) return PAM_AUTHINFO_UNAVAIL;
|
||||
/* The helper must be root's: it runs as root with the user's face data. */
|
||||
struct stat st;
|
||||
if (stat(o.helper, &st) != 0 || st.st_uid != 0 || (st.st_mode & 022)) {
|
||||
if (o.debug) pam_syslog(pamh, LOG_WARNING, "helper %s missing or not root's", o.helper);
|
||||
return PAM_AUTHINFO_UNAVAIL;
|
||||
}
|
||||
int pfd[2];
|
||||
if (pipe2(pfd, O_CLOEXEC) != 0) return PAM_AUTHINFO_UNAVAIL;
|
||||
/* Our caller may ignore SIGCHLD (then waitpid can't see the helper exit); restore it. */
|
||||
struct sigaction sa_old, sa_dfl;
|
||||
memset(&sa_dfl, 0, sizeof sa_dfl);
|
||||
sa_dfl.sa_handler = SIG_DFL;
|
||||
sigaction(SIGCHLD, &sa_dfl, &sa_old);
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
close(pfd[0]);
|
||||
close(pfd[1]);
|
||||
sigaction(SIGCHLD, &sa_old, NULL);
|
||||
return PAM_AUTHINFO_UNAVAIL;
|
||||
}
|
||||
if (pid == 0) {
|
||||
/* Child: become fully root (setuid callers have only euid 0), stdout to the pipe, stdin and
|
||||
* stderr to /dev/null, nothing of the caller's environment. */
|
||||
if (geteuid() == 0) {
|
||||
if (setgid(0) != 0 || setuid(0) != 0) _exit(3);
|
||||
}
|
||||
int devnull = open("/dev/null", O_RDWR);
|
||||
dup2(devnull >= 0 ? devnull : pfd[1], 0);
|
||||
dup2(pfd[1], 1);
|
||||
if (!o.debug && devnull >= 0) dup2(devnull, 2);
|
||||
/* Nothing else of the caller's (its sockets, its PAM handles' files) goes to the helper. */
|
||||
for (int fd = 3; fd < 1024; fd++) close(fd);
|
||||
char timeout_s[16];
|
||||
snprintf(timeout_s, sizeof timeout_s, "%d", o.timeout);
|
||||
char *envp[] = {"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
"LANG=C.UTF-8", "HOME=/root", NULL};
|
||||
const char *args[12];
|
||||
int n = 0;
|
||||
args[n++] = o.python;
|
||||
args[n++] = "-I";
|
||||
args[n++] = o.helper;
|
||||
args[n++] = "compare";
|
||||
args[n++] = "--machine";
|
||||
args[n++] = "--no-elevate";
|
||||
args[n++] = "--user";
|
||||
args[n++] = user;
|
||||
if (o.config) {
|
||||
args[n++] = "--config";
|
||||
args[n++] = o.config;
|
||||
}
|
||||
args[n] = NULL;
|
||||
execve(o.python, (char *const *)args, envp);
|
||||
_exit(3);
|
||||
}
|
||||
close(pfd[1]);
|
||||
long deadline = now_ms() + (long)(o.timeout + 6) * 1000L;
|
||||
char buf[1024];
|
||||
size_t len = 0;
|
||||
int killed = 0;
|
||||
for (;;) {
|
||||
long left = deadline - now_ms();
|
||||
if (left <= 0) {
|
||||
kill(pid, SIGKILL);
|
||||
killed = 1;
|
||||
break;
|
||||
}
|
||||
struct pollfd p = {.fd = pfd[0], .events = POLLIN};
|
||||
int r = poll(&p, 1, (int)left);
|
||||
if (r < 0 && errno == EINTR) continue;
|
||||
if (r <= 0) continue;
|
||||
ssize_t got = read(pfd[0], buf + len, sizeof buf - 1 - len);
|
||||
if (got < 0 && errno == EINTR) continue;
|
||||
if (got <= 0) break;
|
||||
len += (size_t)got;
|
||||
buf[len] = 0;
|
||||
char *nl;
|
||||
while ((nl = memchr(buf, '\n', len))) {
|
||||
*nl = 0;
|
||||
forward(pamh, &o, buf);
|
||||
size_t used = (size_t)(nl - buf) + 1;
|
||||
memmove(buf, nl + 1, len - used);
|
||||
len -= used;
|
||||
buf[len] = 0;
|
||||
}
|
||||
if (len == sizeof buf - 1) len = 0; /* an overlong line: drop it */
|
||||
}
|
||||
close(pfd[0]);
|
||||
int status = 0;
|
||||
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
|
||||
}
|
||||
sigaction(SIGCHLD, &sa_old, NULL);
|
||||
if (killed) {
|
||||
if (!o.quiet) pam_error(pamh, "Face unlock: took too long");
|
||||
return PAM_AUTHINFO_UNAVAIL;
|
||||
}
|
||||
if (!WIFEXITED(status)) return PAM_AUTHINFO_UNAVAIL;
|
||||
switch (WEXITSTATUS(status)) {
|
||||
case 0:
|
||||
pam_syslog(pamh, LOG_NOTICE, "face recognized for %s", user);
|
||||
return PAM_SUCCESS;
|
||||
case 1:
|
||||
return PAM_AUTH_ERR;
|
||||
default:
|
||||
return PAM_AUTHINFO_UNAVAIL;
|
||||
}
|
||||
}
|
||||
|
||||
PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv) {
|
||||
(void)pamh;
|
||||
(void)flags;
|
||||
(void)argc;
|
||||
(void)argv;
|
||||
return PAM_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests for face unlock (docs/face-unlock.md), headless: a fake camera of PGM images and the fake
|
||||
recognizer, so no camera, OpenCV or models are needed.
|
||||
|
||||
python3 face/test_face.py # chandra-face itself
|
||||
python3 face/test_face.py --pam # also build pam_chandra_face.so and run it through
|
||||
# pamtester (root, libpam headers and pamtester needed)
|
||||
|
||||
With CHANDRA_FACE_MODELS=DIR (holding the two ONNX models) and OpenCV installed, the OpenCV
|
||||
backend is checked too, on synthetic pictures it must not take for a face.
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
TOOL = os.path.join(HERE, "chandra-face")
|
||||
loader = importlib.machinery.SourceFileLoader("chandra_face", TOOL)
|
||||
spec = importlib.util.spec_from_loader("chandra_face", loader)
|
||||
cf = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(cf)
|
||||
ME = __import__("pwd").getpwuid(os.getuid()).pw_name
|
||||
|
||||
|
||||
def slurp(path):
|
||||
with open(path) as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def pgm(path, rows):
|
||||
h, w = len(rows), len(rows[0])
|
||||
with open(path, "wb") as fh:
|
||||
fh.write(b"P5\n%d %d\n255\n" % (w, h))
|
||||
fh.write(bytes(v for r in rows for v in r))
|
||||
|
||||
|
||||
def pattern(kind, w=32, h=32):
|
||||
"""A "face" the fake recognizer tells apart: a bright-left or bright-top split, a flat frame
|
||||
(no face), or a dark frame (IR emitter not lit yet)."""
|
||||
if kind == "alice":
|
||||
return [[220 if x < w // 2 else 40 for x in range(w)] for y in range(h)]
|
||||
if kind == "alice2": # the same face, a bit darker and noisier
|
||||
return [[(200 if x < w // 2 else 50) + (x * y) % 7 for x in range(w)] for y in range(h)]
|
||||
if kind == "bob":
|
||||
return [[220 if y < h // 2 else 40 for x in range(w)] for y in range(h)]
|
||||
if kind == "flat":
|
||||
return [[128] * w for _ in range(h)]
|
||||
if kind == "dark":
|
||||
return [[3 if x % 2 else 8 for x in range(w)] for y in range(h)]
|
||||
raise ValueError(kind)
|
||||
|
||||
|
||||
class Env:
|
||||
"""A temporary store, PAM dir, config and camera."""
|
||||
|
||||
def __init__(self):
|
||||
self.dir = tempfile.mkdtemp(prefix="chandra-face-test-")
|
||||
os.chmod(self.dir, 0o755)
|
||||
self.store = os.path.join(self.dir, "store")
|
||||
self.pam = os.path.join(self.dir, "pam.d")
|
||||
os.makedirs(self.pam)
|
||||
self.conf = os.path.join(self.dir, "face.conf")
|
||||
self.camera(["alice"])
|
||||
|
||||
def camera(self, kinds, **extra):
|
||||
cam = os.path.join(self.dir, "cam")
|
||||
if os.path.isdir(cam):
|
||||
shutil.rmtree(cam)
|
||||
os.makedirs(cam)
|
||||
for i, k in enumerate(kinds):
|
||||
pgm(os.path.join(cam, "%03d.pgm" % i), pattern(k))
|
||||
opts = {"backend": "fake", "device": "images:" + cam, "store": self.store,
|
||||
"pam_dir": self.pam, "timeout": "5", "enroll_frames": "3", "matches": "2",
|
||||
"threshold": "0.9"}
|
||||
opts.update(extra)
|
||||
with open(self.conf, "w") as fh:
|
||||
fh.write("[face]\n" + "".join("%s = %s\n" % kv for kv in opts.items()))
|
||||
os.chmod(self.conf, 0o644)
|
||||
|
||||
def run(self, *args):
|
||||
buf = io.StringIO()
|
||||
with redirect_stdout(buf):
|
||||
rc = cf.main(["--config", self.conf, "--machine", "--no-elevate", "--user", ME] + list(args))
|
||||
return rc, buf.getvalue().splitlines()
|
||||
|
||||
def close(self):
|
||||
shutil.rmtree(self.dir)
|
||||
|
||||
|
||||
class FaceTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.env = Env()
|
||||
|
||||
def tearDown(self):
|
||||
self.env.close()
|
||||
|
||||
def enroll(self, *kinds, label="Desk"):
|
||||
self.env.camera(list(kinds))
|
||||
rc, out = self.env.run("enroll", "--label", label)
|
||||
self.assertEqual(rc, 0, out)
|
||||
return out
|
||||
|
||||
def test_nothing_enrolled_is_quiet_and_unavailable(self):
|
||||
rc, out = self.env.run("compare")
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertEqual(out, [])
|
||||
|
||||
def test_enroll_writes_private_vectors_and_a_public_label_list(self):
|
||||
out = self.enroll("dark", "alice", "flat", "alice", "alice")
|
||||
self.assertEqual(out[0], "info Look at the camera…")
|
||||
self.assertIn("progress 3/3", out)
|
||||
self.assertEqual(out[-1], "done Added Desk")
|
||||
d = os.path.join(self.env.store, ME)
|
||||
faces = os.path.join(d, "faces.json")
|
||||
self.assertEqual(stat.S_IMODE(os.stat(faces).st_mode), 0o600)
|
||||
self.assertEqual(stat.S_IMODE(os.stat(os.path.join(d, "faces.list")).st_mode), 0o644)
|
||||
data = json.loads(slurp(faces))
|
||||
self.assertEqual(len(data["faces"][0]["vectors"]), 3)
|
||||
listed = slurp(os.path.join(d, "faces.list"))
|
||||
self.assertRegex(listed, r"^1\tDesk\t\d{4}-\d\d-\d\d\n$")
|
||||
self.assertNotIn("vectors", listed)
|
||||
|
||||
def test_enroll_without_a_face_fails_and_stores_nothing(self):
|
||||
self.env.camera(["flat", "dark", "flat"])
|
||||
rc, out = self.env.run("enroll")
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertTrue(out[-1].startswith("error couldn't see a face"), out)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.env.store, ME, "faces.json")))
|
||||
|
||||
def test_the_same_face_is_recognized(self):
|
||||
self.enroll("alice", "alice", "alice")
|
||||
self.env.camera(["dark", "alice2", "alice2"])
|
||||
rc, out = self.env.run("compare")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual(out, ["info Face unlock: looking for %s…" % ME, "info Face unlock: recognized %s" % ME])
|
||||
|
||||
def test_one_matching_frame_is_not_enough(self):
|
||||
self.enroll("alice", "alice", "alice")
|
||||
self.env.camera(["alice", "bob", "bob"], enroll_frames="3")
|
||||
rc, out = self.env.run("compare")
|
||||
self.assertEqual(rc, 1)
|
||||
|
||||
def test_someone_else_is_not_recognized(self):
|
||||
self.enroll("alice", "alice", "alice")
|
||||
self.env.camera(["bob", "bob", "bob"])
|
||||
rc, out = self.env.run("compare")
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertEqual(out[-1], "error Face unlock: face not recognized")
|
||||
|
||||
def test_reasons_for_failing(self):
|
||||
self.enroll("alice", "alice", "alice")
|
||||
self.env.camera(["dark", "dark"])
|
||||
self.assertEqual(self.env.run("compare")[1][-1], "error Face unlock: the camera picture is too dark")
|
||||
self.env.camera(["flat", "dark"])
|
||||
self.assertEqual(self.env.run("compare")[1][-1], "error Face unlock: no face in view")
|
||||
self.env.camera([])
|
||||
self.assertEqual(self.env.run("compare")[1][-1], "error Face unlock: the camera gave no picture")
|
||||
|
||||
def test_turned_off_in_the_config(self):
|
||||
self.enroll("alice", "alice", "alice")
|
||||
self.env.camera(["alice"] * 3, enabled="no")
|
||||
self.assertEqual(self.env.run("compare"), (2, []))
|
||||
|
||||
def test_a_store_others_can_write_is_refused(self):
|
||||
self.enroll("alice", "alice", "alice")
|
||||
self.env.camera(["alice"] * 3)
|
||||
d = os.path.join(self.env.store, ME)
|
||||
os.chmod(d, 0o777)
|
||||
rc, out = self.env.run("compare")
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("can be written by others", out[-1])
|
||||
os.chmod(d, 0o755)
|
||||
os.chmod(os.path.join(d, "faces.json"), 0o666)
|
||||
self.assertEqual(self.env.run("compare")[0], 2)
|
||||
|
||||
def test_bad_user_names_are_refused(self):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
rc = cf.main(["--config", self.env.conf, "--machine", "--no-elevate", "--user", "../etc", "compare"])
|
||||
self.assertEqual(rc, 2)
|
||||
|
||||
def test_list_remove_clear(self):
|
||||
self.enroll("alice", "alice", "alice", label="Desk")
|
||||
self.enroll("alice", "alice", "alice", label="Glasses")
|
||||
rc, out = self.env.run("status")
|
||||
faces = [l for l in out if l.startswith("face ")]
|
||||
self.assertEqual(len(faces), 2)
|
||||
self.assertTrue(faces[1].startswith("face 2\tGlasses\t"))
|
||||
self.assertIn("backend fake", out)
|
||||
self.assertEqual(self.env.run("remove", "1")[0], 0)
|
||||
self.assertEqual([l.split("\t")[1] for l in self.env.run("list")[1]], ["Glasses"])
|
||||
self.assertEqual(self.env.run("remove", "7")[0], 1)
|
||||
self.assertEqual(self.env.run("clear")[0], 0)
|
||||
self.assertEqual(self.env.run("list")[1], [])
|
||||
self.assertFalse(os.path.exists(os.path.join(self.env.store, ME)))
|
||||
|
||||
def test_pam_enable_disable(self):
|
||||
p = os.path.join(self.env.pam, "sudo")
|
||||
original = "#%PAM-1.0\n# comment\nauth include system-auth\naccount include system-auth\n"
|
||||
with open(p, "w") as fh:
|
||||
fh.write(original)
|
||||
with open(os.path.join(self.env.pam, "login"), "w") as fh:
|
||||
fh.write("auth sufficient pam_howdy.so\nauth include system-auth\n")
|
||||
self.assertEqual(self.env.run("pam", "enable", "sudo")[0], 0)
|
||||
lines = slurp(p).split("\n")
|
||||
self.assertEqual(lines[2], cf.PAM_LINE)
|
||||
self.assertEqual(lines[3], "auth include system-auth")
|
||||
self.assertTrue(os.path.exists(p + ".chandra-face.bak"))
|
||||
# Twice is once.
|
||||
self.env.run("pam", "enable", "sudo")
|
||||
self.assertEqual(slurp(p).count("pam_chandra_face.so"), 1)
|
||||
rc, out = self.env.run("status")
|
||||
self.assertIn("pam sudo", out)
|
||||
self.assertIn("howdy login", out)
|
||||
self.env.run("pam", "disable", "sudo")
|
||||
self.assertEqual(slurp(p), original)
|
||||
# Debian: no auth line, only @include common-auth (after a session line).
|
||||
deb = os.path.join(self.env.pam, "sudo-deb")
|
||||
with open(deb, "w") as fh:
|
||||
fh.write("#%PAM-1.0\nsession required pam_limits.so\n@include common-auth\n@include common-account\n")
|
||||
self.env.run("pam", "enable", "sudo-deb")
|
||||
self.assertEqual(slurp(deb).split("\n")[2:4], [cf.PAM_LINE, "@include common-auth"])
|
||||
self.assertEqual(self.env.run("pam", "enable", "no-such-service")[0], 1)
|
||||
self.assertEqual(self.env.run("pam", "enable", "../passwd")[0], 1)
|
||||
|
||||
def test_status_names_what_is_missing(self):
|
||||
self.env.camera([], backend="opencv", models=os.path.join(self.env.dir, "nomodels"))
|
||||
rc, out = self.env.run("status")
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertTrue(any(l.startswith("problem ") for l in out), out)
|
||||
self.env.camera([], device="/dev/no-such-camera")
|
||||
self.assertIn("problem no camera at /dev/no-such-camera", self.env.run("status")[1])
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("CHANDRA_FACE_MODELS"), "CHANDRA_FACE_MODELS not set")
|
||||
class OpenCVTests(unittest.TestCase):
|
||||
def test_no_face_in_noise_or_flat_frames(self):
|
||||
env = Env()
|
||||
try:
|
||||
env.camera(["flat", "bob"], backend="opencv", models=os.environ["CHANDRA_FACE_MODELS"])
|
||||
# Nothing enrolled: unavailable without touching the camera.
|
||||
self.assertEqual(env.run("compare")[0], 2)
|
||||
rc, out = env.run("enroll")
|
||||
self.assertEqual(rc, 1)
|
||||
finally:
|
||||
env.close()
|
||||
|
||||
|
||||
@unittest.skipUnless("--pam" in sys.argv, "pass --pam to test the PAM module")
|
||||
class PamTests(unittest.TestCase):
|
||||
"""pam_chandra_face.so through pamtester, with a throwaway service in /etc/pam.d."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if os.geteuid() != 0 or not shutil.which("pamtester"):
|
||||
raise unittest.SkipTest("needs root and pamtester")
|
||||
cls.build = tempfile.mkdtemp(prefix="pam-face-")
|
||||
os.chmod(cls.build, 0o755)
|
||||
cls.so = os.path.join(cls.build, "pam_chandra_face.so")
|
||||
subprocess.check_call(["cc", "-Wall", "-Werror", "-O2", "-shared", "-fPIC", "-o", cls.so,
|
||||
os.path.join(HERE, "pam_chandra_face.c"), "-lpam"])
|
||||
cls.helper = os.path.join(cls.build, "chandra-face")
|
||||
shutil.copyfile(TOOL, cls.helper)
|
||||
os.chmod(cls.helper, 0o755)
|
||||
cls.service = "chandra-face-test-%d" % os.getpid()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
p = "/etc/pam.d/" + cls.service
|
||||
if os.path.exists(p):
|
||||
os.unlink(p)
|
||||
shutil.rmtree(cls.build)
|
||||
|
||||
def setUp(self):
|
||||
self.env = Env()
|
||||
|
||||
def tearDown(self):
|
||||
self.env.close()
|
||||
|
||||
def pam(self, user="root", helper=None, args="", env=None):
|
||||
with open("/etc/pam.d/" + self.service, "w") as fh:
|
||||
fh.write("-auth sufficient %s helper=%s python=%s config=%s %s\nauth required pam_deny.so\n"
|
||||
% (self.so, helper or self.helper, sys.executable, self.env.conf, args))
|
||||
p = subprocess.run(["pamtester", self.service, user, "authenticate"], input="", capture_output=True,
|
||||
text=True, timeout=60, env=env)
|
||||
return p.returncode, p.stdout + p.stderr
|
||||
|
||||
def enroll_root(self):
|
||||
self.env.camera(["alice"] * 3)
|
||||
rc = cf.main(["--config", self.env.conf, "--no-elevate", "--user", "root", "enroll"])
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
def test_match_succeeds_and_says_so(self):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
self.enroll_root()
|
||||
self.env.camera(["alice2"] * 3)
|
||||
rc, out = self.pam()
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("Face unlock: looking for root…", out)
|
||||
self.assertIn("Face unlock: recognized root", out)
|
||||
|
||||
def test_no_match_falls_through_to_the_next_module(self):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
self.enroll_root()
|
||||
self.env.camera(["bob"] * 3)
|
||||
rc, out = self.pam()
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertIn("Face unlock: face not recognized", out)
|
||||
|
||||
def test_remote_and_unenrolled_users_are_skipped_quietly(self):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
self.enroll_root()
|
||||
self.env.camera(["alice"] * 3)
|
||||
rc, out = self.pam(env=dict(os.environ, SSH_CONNECTION="10.0.0.1 1 10.0.0.2 22"))
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertNotIn("Face unlock", out)
|
||||
rc, out = self.pam(user="nobody")
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertNotIn("Face unlock", out)
|
||||
|
||||
def test_a_helper_that_hangs_is_killed(self):
|
||||
hang = os.path.join(self.build, "hang")
|
||||
with open(hang, "w") as fh:
|
||||
fh.write("import time\nprint('info Face unlock: looking', flush=True)\ntime.sleep(60)\n")
|
||||
os.chmod(hang, 0o755)
|
||||
rc, out = self.pam(helper=hang, args="timeout=1")
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertIn("Face unlock: took too long", out)
|
||||
|
||||
def test_a_helper_others_can_write_is_not_run(self):
|
||||
bad = os.path.join(self.build, "writable")
|
||||
shutil.copyfile(TOOL, bad)
|
||||
os.chmod(bad, 0o777)
|
||||
with redirect_stdout(io.StringIO()):
|
||||
self.enroll_root()
|
||||
self.env.camera(["alice"] * 3)
|
||||
rc, out = self.pam(helper=bad)
|
||||
self.assertNotEqual(rc, 0)
|
||||
self.assertNotIn("Face unlock", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
argv = [a for a in sys.argv if a != "--pam"]
|
||||
unittest.main(argv=argv)
|
||||
Reference in new issue
Block a user