Face unlock: Python, OpenCV and numpy from a root-owned pixi environment
CI / test (push) Successful in 2m41s

- face/pixi.toml + pixi.lock (python 3.12, numpy, opencv-python-headless). `just install-face`
  passes the pixi on your PATH; install.py runs `pixi install --frozen` as root into
  /usr/local/lib/chandra/face-env (not the checkout's .pixi: the PAM module runs this Python as
  root, so it must not be user-writable), writes the helper's shebang for it and builds the PAM
  module with it as the default python. No python3-opencv needed; uninstall removes the env.
- The PAM module now also refuses a Python that isn't root's; group-writable is accepted only
  for group root (conda/pixi files are 0775 root:root), in the module and chandra-face's checks.
- Elevation re-runs on the same interpreter (sys.executable). "OpenCV is missing: run just
  install-face" instead of naming the distro package. Dropped a stray __pycache__.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhiJfJNAYqWzQiuKMf
This commit is contained in:
Claude committed 2026-11-26 01:34:45 +00:00
1 parent fa634956cc
commit b097116ded
10 files changed
+1105 -26

No files matched your search

+2 -2
View File
@@ -104,11 +104,11 @@ test "Settings > Session: face unlock lists faces, adds one, turns it on, remove
test "face unlock status lines" { test "face unlock status lines" {
let f = @shell.FaceUnlock::new() let f = @shell.FaceUnlock::new()
f.apply_status([ f.apply_status([
"backend opencv", "device /dev/video0", "problem python3-opencv is not installed", "pam polkit-1,sudo", "backend opencv", "device /dev/video0", "problem OpenCV is missing: run just install-face", "pam polkit-1,sudo",
"howdy login,gdm-password", "face 3\tGlasses\t2026-11-01", "howdy login,gdm-password", "face 3\tGlasses\t2026-11-01",
]) ])
assert_true(f.installed) assert_true(f.installed)
assert_eq(f.problem, "python3-opencv is not installed") assert_eq(f.problem, "OpenCV is missing: run just install-face")
assert_true(f.in_use()) assert_true(f.in_use())
assert_eq(f.howdy, "login, gdm-password") assert_eq(f.howdy, "login, gdm-password")
assert_eq(f.faces, [("3", "Glasses", "2026-11-01")]) assert_eq(f.faces, [("3", "Glasses", "2026-11-01")])
+9 -6
View File
@@ -14,10 +14,13 @@ any other service you add it to.
just install-face # PAM module, chandra-face, settings, face models (asks for root once) just install-face # PAM module, chandra-face, settings, face models (asks for root once)
``` ```
You need Python 3 with OpenCV 4.5.4 or later (`python3-opencv` on Debian/Ubuntu/Fedora, Nothing from the distro is needed beyond a C compiler and the PAM headers (`libpam0g-dev` /
`python-opencv` on Arch), a C compiler and the PAM headers (`libpam0g-dev` / `pam-devel`). The `pam-devel`) and [pixi](https://pixi.sh): Python, OpenCV and numpy come from a pixi environment
models (OpenCV's YuNet face detector and SFace recognizer, 37 MB) are downloaded from the (`face/pixi.toml` + `face/pixi.lock`) that install-face makes in `/usr/local/lib/chandra/face-env`,
opencv_zoo repository and checked against their SHA-256 sums. owned by root. It is deliberately not the checkout's `.pixi`: the PAM module runs that Python as
root, so it must not be anywhere a user can write. The models (OpenCV's YuNet face detector and
SFace recognizer, 37 MB) are downloaded from the opencv_zoo repository and checked against their
SHA-256 sums. The environment takes about 450 MB.
The Settings rows are part of the session, not of `install-face`: after updating Chandra, run The Settings rows are part of the session, not of `install-face`: after updating Chandra, run
`just install` (or `just install-dev`) and log in again so the compositor, its host and the `just install` (or `just install-dev`) and log in again so the compositor, its host and the
@@ -79,7 +82,7 @@ by hand instead, put that line at the top of the auth section; module options:
| --- | --- | | --- | --- |
| `timeout=N` | the helper gets N + 6 seconds in all before it is killed (default 4; the camera's own timeout is in face.conf) | | `timeout=N` | the helper gets N + 6 seconds in all before it is killed (default 4; the camera's own timeout is in face.conf) |
| `config=PATH` | another settings file (default `/etc/chandra/face.conf`) | | `config=PATH` | another settings file (default `/etc/chandra/face.conf`) |
| `helper=PATH`, `python=PATH` | another chandra-face / Python (default `/usr/local/lib/chandra/chandra-face`, `/usr/bin/python3`) | | `helper=PATH`, `python=PATH` | another chandra-face / Python (default `/usr/local/lib/chandra/chandra-face` and the face-env's python3; both must be root's) |
| `quiet` | don't send the "looking" / "not recognized" messages | | `quiet` | don't send the "looking" / "not recognized" messages |
| `debug` | the helper's stderr goes to the application's stderr; skipped helpers are logged | | `debug` | the helper's stderr goes to the application's stderr; skipped helpers are logged |
@@ -114,7 +117,7 @@ models = /usr/local/share/chandra/face
to the application's conversation as `PAM_TEXT_INFO` or `PAM_ERROR_MSG`, and maps its exit status to the application's conversation as `PAM_TEXT_INFO` or `PAM_ERROR_MSG`, and maps its exit status
to `PAM_SUCCESS` (0), `PAM_AUTH_ERR` (1) or `PAM_AUTHINFO_UNAVAIL` (anything else). The helper to `PAM_SUCCESS` (0), `PAM_AUTH_ERR` (1) or `PAM_AUTHINFO_UNAVAIL` (anything else). The helper
must be root's and not writable by others, or it is not run. must be root's and not writable by others, or it is not run.
- `face/chandra-face` (Python): finds faces with YuNet, turns the largest one into a 128-number - `face/chandra-face` (Python, on the face-env's interpreter): finds faces with YuNet, turns the largest one into a 128-number
SFace embedding, and compares it with the stored ones (cosine similarity). It also enrolls, SFace embedding, and compares it with the stored ones (cosine similarity). It also enrolls,
lists, removes, edits PAM files, reports status and downloads the models. Root commands run by lists, removes, edits PAM files, reports status and downloads the models. Root commands run by
another user re-run themselves through run0 (or pkexec when systemd isn't PID 1). another user re-run themselves through run0 (or pkexec when systemd isn't PID 1).
+1
View File
@@ -0,0 +1 @@
__pycache__/
Binary file not shown.
+5 -5
View File
@@ -105,7 +105,7 @@ def check_trusted(path, what):
raise Fail("%s %s is a symlink" % (what, path), 2) raise Fail("%s %s is a symlink" % (what, path), 2)
if st.st_uid not in (0, os.geteuid()): if st.st_uid not in (0, os.geteuid()):
raise Fail("%s %s is not owned by root" % (what, path), 2) raise Fail("%s %s is not owned by root" % (what, path), 2)
if st.st_mode & 0o022: 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) raise Fail("%s %s can be written by others" % (what, path), 2)
@@ -248,7 +248,7 @@ class OpenCVRecognizer:
import cv2 # noqa import cv2 # noqa
import numpy # noqa import numpy # noqa
except ImportError: except ImportError:
raise Fail("python3-opencv (with numpy) is not installed", 2) raise Fail("OpenCV is missing: run just install-face", 2)
import cv2 import cv2
import numpy as np import numpy as np
@@ -622,7 +622,7 @@ def cmd_status(cfg, user, out):
try: try:
import cv2 # noqa import cv2 # noqa
except ImportError: except ImportError:
problem = "python3-opencv is not installed" problem = "OpenCV is missing: run just install-face"
if not problem: if not problem:
for m in MODELS: for m in MODELS:
if not os.path.exists(os.path.join(cfg.models, m)): if not os.path.exists(os.path.join(cfg.models, m)):
@@ -681,10 +681,10 @@ def elevate(argv, user):
args += ["--user", user] args += ["--user", user]
run0 = shutil.which("run0") run0 = shutil.which("run0")
if run0 and os.path.isdir("/run/systemd/system"): if run0 and os.path.isdir("/run/systemd/system"):
os.execv(run0, [run0, "--background=", "--"] + ["/usr/bin/python3", "-I"] + args) os.execv(run0, [run0, "--background=", "--"] + [sys.executable, "-I"] + args)
pk = shutil.which("pkexec") pk = shutil.which("pkexec")
if pk: if pk:
os.execv(pk, [pk, "/usr/bin/python3", "-I"] + args) os.execv(pk, [pk, sys.executable, "-I"] + args)
raise Fail("needs root, and neither run0 nor pkexec is installed") raise Fail("needs root, and neither run0 nor pkexec is installed")
+57 -9
View File
@@ -5,10 +5,13 @@ scripts/as-root):
run0 python3 face/install.py # install, fetch the face models 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 --pam # ... and use it for polkit-1 and sudo
run0 python3 face/install.py --no-models run0 python3 face/install.py --no-models
run0 python3 face/install.py --pixi PATH # the pixi binary (`just install-face` passes it)
run0 python3 face/install.py --remove # take it out of every PAM service, uninstall 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 run0 python3 face/install.py --remove --purge # ... and delete the enrolled faces
Installs: Installs:
/usr/local/lib/chandra/face-env/ Python + OpenCV + numpy, a pixi environment made from
face/pixi.toml + pixi.lock (root's; nothing from the distro)
/usr/local/lib/chandra/chandra-face the helper (enroll, compare, ...), root's /usr/local/lib/chandra/chandra-face the helper (enroll, compare, ...), root's
/usr/local/bin/chandra-face -> the helper /usr/local/bin/chandra-face -> the helper
<PAM module dir>/pam_chandra_face.so the PAM module (built here with cc; needs libpam headers) <PAM module dir>/pam_chandra_face.so the PAM module (built here with cc; needs libpam headers)
@@ -20,7 +23,7 @@ PAM files are only changed with --pam (or later with `chandra-face pam enable SE
is `-auth sufficient pam_chandra_face.so`, before the service's other auth lines, so the password is `-auth sufficient pam_chandra_face.so`, before the service's other auth lines, so the password
still works whenever the face doesn't. still works whenever the face doesn't.
""" """
import glob, os, shutil, subprocess, sys import glob, os, pwd, shutil, subprocess, sys
here = os.path.dirname(os.path.abspath(__file__)) here = os.path.dirname(os.path.abspath(__file__))
helper = "/usr/local/lib/chandra/chandra-face" helper = "/usr/local/lib/chandra/chandra-face"
@@ -28,6 +31,47 @@ link = "/usr/local/bin/chandra-face"
conf = "/etc/chandra/face.conf" conf = "/etc/chandra/face.conf"
store = "/var/lib/chandra-face" store = "/var/lib/chandra-face"
models = "/usr/local/share/chandra/face" models = "/usr/local/share/chandra/face"
env_dir = "/usr/local/lib/chandra/face-env"
env_python = os.path.join(env_dir, ".pixi/envs/default/bin/python3")
def find_pixi():
"""pixi: --pixi PATH, $PIXI, PATH, then root's or the invoking user's ~/.pixi/bin."""
if "--pixi" in sys.argv:
i = sys.argv.index("--pixi")
if i + 1 < len(sys.argv) and sys.argv[i + 1]:
return sys.argv[i + 1]
cands = [os.environ.get("PIXI", ""), shutil.which("pixi") or "", "/root/.pixi/bin/pixi"]
for var in ("SUDO_USER", "PKEXEC_UID", "RUN0_USER"):
v = os.environ.get(var, "")
try:
home = pwd.getpwuid(int(v)).pw_dir if v.isdigit() else pwd.getpwnam(v).pw_dir if v else ""
except KeyError:
home = ""
if home:
cands.append(os.path.join(home, ".pixi/bin/pixi"))
for c in cands:
if c and os.access(c, os.X_OK):
return c
return None
def make_env():
"""The root-owned pixi environment the helper and the PAM module run; its python3."""
pixi = find_pixi()
if not pixi:
sys.exit("pixi not found: install it (https://pixi.sh) or pass --pixi PATH; "
"`just install-face` passes the one on your PATH")
os.makedirs(env_dir, 0o755, exist_ok=True)
for f in ("pixi.toml", "pixi.lock"):
shutil.copyfile(os.path.join(here, f), os.path.join(env_dir, f))
os.chmod(os.path.join(env_dir, f), 0o644)
env = dict(os.environ, PIXI_HOME="/root/.pixi")
subprocess.check_call([pixi, "install", "--frozen", "--manifest-path",
os.path.join(env_dir, "pixi.toml")], env=env)
subprocess.check_call([env_python, "-I", "-c", "import cv2, numpy"])
print("installed", env_dir, "(Python, OpenCV, numpy)")
return env_python
def pam_dir(): def pam_dir():
@@ -54,6 +98,9 @@ if "--remove" in sys.argv:
if os.path.lexists(p): if os.path.lexists(p):
os.remove(p) os.remove(p)
print("removed", p) print("removed", p)
if os.path.isdir(env_dir):
shutil.rmtree(env_dir)
print("removed", env_dir)
if os.path.isdir(models): if os.path.isdir(models):
shutil.rmtree(models) shutil.rmtree(models)
print("removed", models) print("removed", models)
@@ -69,7 +116,12 @@ if "--remove" in sys.argv:
os.umask(0o022) os.umask(0o022)
os.makedirs(os.path.dirname(helper), exist_ok=True) os.makedirs(os.path.dirname(helper), exist_ok=True)
shutil.copyfile(os.path.join(here, "chandra-face"), helper + ".new") py = make_env()
# The helper runs on that Python (its shebang), so `chandra-face ...` from a shell does too.
with open(os.path.join(here, "chandra-face")) as fh:
src = fh.read().split("\n", 1)[1]
with open(helper + ".new", "w") as fh:
fh.write("#!%s -I\n" % py + src)
os.chmod(helper + ".new", 0o755) os.chmod(helper + ".new", 0o755)
os.replace(helper + ".new", helper) os.replace(helper + ".new", helper)
print("installed", helper) print("installed", helper)
@@ -83,6 +135,7 @@ if not cc:
sys.exit("no C compiler: install gcc (and the libpam headers: libpam0g-dev / pam-devel)") 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", subprocess.check_call([cc, "-O2", "-Wall", "-shared", "-fPIC", "-o", mod + ".new",
"-DCHANDRA_FACE_HELPER=\"%s\"" % helper, "-DCHANDRA_FACE_HELPER=\"%s\"" % helper,
"-DCHANDRA_FACE_PYTHON=\"%s\"" % py,
os.path.join(here, "pam_chandra_face.c"), "-lpam"]) os.path.join(here, "pam_chandra_face.c"), "-lpam"])
os.chmod(mod + ".new", 0o644) os.chmod(mod + ".new", 0o644)
os.replace(mod + ".new", mod) os.replace(mod + ".new", mod)
@@ -97,14 +150,9 @@ os.makedirs(store, 0o755, exist_ok=True)
os.chmod(store, 0o755) os.chmod(store, 0o755)
if "--no-models" not in sys.argv: if "--no-models" not in sys.argv:
subprocess.check_call([sys.executable, "-I", helper, "--no-elevate", "fetch-models"]) subprocess.check_call([py, "-I", helper, "--no-elevate", "fetch-models"])
if "--pam" in sys.argv: if "--pam" in sys.argv:
subprocess.check_call([sys.executable, "-I", helper, "--no-elevate", "pam", "enable"]) subprocess.check_call([py, "-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(""" print("""
Settings > Session > Face unlock comes with the session itself (the compositor, its host and the Settings > Session > Face unlock comes with the session itself (the compositor, its host and the
Settings module), not with this install: if Settings doesn't show it yet, run `just install` Settings module), not with this install: if Settings doesn't show it yet, run `just install`
+13 -3
View File
@@ -38,7 +38,7 @@
#define CHANDRA_FACE_HELPER "/usr/local/lib/chandra/chandra-face" #define CHANDRA_FACE_HELPER "/usr/local/lib/chandra/chandra-face"
#endif #endif
#ifndef CHANDRA_FACE_PYTHON #ifndef CHANDRA_FACE_PYTHON
#define CHANDRA_FACE_PYTHON "/usr/bin/python3" #define CHANDRA_FACE_PYTHON "/usr/local/lib/chandra/face-env/.pixi/envs/default/bin/python3"
#endif #endif
struct opts { struct opts {
@@ -111,6 +111,12 @@ static void forward(pam_handle_t *pamh, const struct opts *o, char *line) {
} }
} }
/* Only root can change it: root's, not writable by others, nor by a group other than root's
* (pixi environments keep conda's 0775 modes, group root). */
static int root_only(const struct stat *st) {
return st->st_uid == 0 && !(st->st_mode & 002) && (!(st->st_mode & 020) || st->st_gid == 0);
}
static long now_ms(void) { static long now_ms(void) {
struct timespec ts; struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts); clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -125,12 +131,16 @@ PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, cons
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || !user || !*user) return PAM_USER_UNKNOWN; if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || !user || !*user) return PAM_USER_UNKNOWN;
if (is_remote(pamh)) return PAM_AUTHINFO_UNAVAIL; if (is_remote(pamh)) return PAM_AUTHINFO_UNAVAIL;
if (lid_closed()) 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. */ /* The helper and its Python must be root's: they run as root with the user's face data. */
struct stat st; struct stat st;
if (stat(o.helper, &st) != 0 || st.st_uid != 0 || (st.st_mode & 022)) { if (stat(o.helper, &st) != 0 || !root_only(&st)) {
if (o.debug) pam_syslog(pamh, LOG_WARNING, "helper %s missing or not root's", o.helper); if (o.debug) pam_syslog(pamh, LOG_WARNING, "helper %s missing or not root's", o.helper);
return PAM_AUTHINFO_UNAVAIL; return PAM_AUTHINFO_UNAVAIL;
} }
if (stat(o.python, &st) != 0 || !root_only(&st)) {
if (o.debug) pam_syslog(pamh, LOG_WARNING, "python %s missing or not root's", o.python);
return PAM_AUTHINFO_UNAVAIL;
}
int pfd[2]; int pfd[2];
if (pipe2(pfd, O_CLOEXEC) != 0) return PAM_AUTHINFO_UNAVAIL; 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. */ /* Our caller may ignore SIGCHLD (then waitpid can't see the helper exit); restore it. */
+1002
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
# Face unlock's Python environment (docs/face-unlock.md): `just install-face` installs it, as
# root, into /usr/local/lib/chandra/face-env from this manifest and pixi.lock, so neither
# python3-opencv nor any other distro package is needed. It is root's on purpose: the PAM module
# runs this Python as root, so it must not live anywhere a user can write (like this checkout).
[workspace]
name = "chandra-face"
channels = ["conda-forge"]
platforms = ["linux-64", "linux-aarch64"]
[dependencies]
python = "3.12.*"
numpy = "*"
[pypi-dependencies]
opencv-python-headless = ">=4.8"
+1 -1
View File
@@ -120,7 +120,7 @@ uninstall:
# Install face unlock (PAM module + chandra-face + models; docs/face-unlock.md). `just install-face --pam` also turns it on for polkit-1 and sudo. The Settings rows come with the session: `just install` and log in again. # Install face unlock (PAM module + chandra-face + models; docs/face-unlock.md). `just install-face --pam` also turns it on for polkit-1 and sudo. The Settings rows come with the session: `just install` and log in again.
install-face *args: install-face *args:
scripts/as-root python3 "{{justfile_directory()}}/face/install.py" {{args}} scripts/as-root python3 "{{justfile_directory()}}/face/install.py" --pixi "$(command -v pixi || echo "$HOME/.pixi/bin/pixi")" {{args}}
# Remove face unlock (from every PAM service first). `just uninstall-face --purge` also deletes the enrolled faces. # Remove face unlock (from every PAM service first). `just uninstall-face --purge` also deletes the enrolled faces.
uninstall-face *args: uninstall-face *args: