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
+2780
-28
No files matched your search
@@ -26,7 +26,8 @@ jobs:
|
||||
- name: Install native compositor build dependencies
|
||||
run: |
|
||||
apt-get update -q
|
||||
apt-get install -y -q --no-install-recommends libseat-dev libdrm-dev libinput-dev libudev-dev libxkbcommon-dev
|
||||
apt-get install -y -q --no-install-recommends libseat-dev libdrm-dev libinput-dev libudev-dev libxkbcommon-dev \
|
||||
libpam0g-dev pamtester
|
||||
|
||||
- name: Install wasm-tools, wit-bindgen, wasmtime, wasmer C API
|
||||
run: scripts/setup-toolchain.sh
|
||||
|
||||
@@ -98,6 +98,11 @@ goes through `scripts/as-root`, which prefers run0 and falls back to sudo, doas
|
||||
`chandra-root gparted`. Details, including polkit agents (`CHANDRA_POLKIT_AGENT`), are in
|
||||
[docs/run0.md](docs/run0.md).
|
||||
|
||||
Face unlock, in the style of Howdy: `just install-face`, then Settings > Session > Face unlock to
|
||||
add a face and use it for the password dialog and sudo (a PAM module; the password always still
|
||||
works). See [docs/face-unlock.md](docs/face-unlock.md), including what 2D face recognition can't
|
||||
protect against.
|
||||
|
||||
## What works
|
||||
|
||||
**Windows**
|
||||
|
||||
@@ -31,7 +31,9 @@ declare pub fn on_scroll(at : @types.Point, dx : Int, dy : Int) -> Bool
|
||||
///|
|
||||
/// The animation clock. `now-ms` counts milliseconds from when the module was loaded. It is
|
||||
/// called once after loading, after every event the module handled, and again when the delay it
|
||||
/// last returned has passed; the module is redrawn after each call. Return how many ms until the
|
||||
/// last returned has passed. The module is redrawn after each timed call (an animation frame)
|
||||
/// and after events that returned true; a call that follows an event only reschedules the
|
||||
/// clock and does not redraw by itself. Return how many ms until the
|
||||
/// next frame (16 for about 60 frames a second, 33 for 30), or 0 to sleep until the next event:
|
||||
/// an idle desktop module costs nothing, so return 0 whenever nothing moves. Frames are paused
|
||||
/// (no calls) while a window covers the whole desktop.
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
"chandra/desktop/interface/chandra/desktop/system" @system,
|
||||
"chandra/desktop/interface/chandra/desktop/shortcuts" @shortcuts,
|
||||
"chandra/desktop/interface/chandra/desktop/default-apps" @default_apps,
|
||||
"chandra/desktop/interface/chandra/desktop/face-unlock" @face_unlock,
|
||||
"chandra/desktop/lib/ui" @ui,
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,27 @@ enum Row {
|
||||
AppKind(Int, String, @default_apps.AppChoice?, String, Int)
|
||||
/// One of a kind's apps, listed under it while it is expanded: the kind, its index there, the app.
|
||||
AppOption(Int, Int, @default_apps.AppChoice)
|
||||
/// Face unlock's switch: the password dialog and sudo try the face first.
|
||||
FaceUse
|
||||
/// An enrolled face: its index, label and when it was added (a second click removes it).
|
||||
FaceRow(Int, String, String)
|
||||
/// "Add a face..."
|
||||
FaceAdd
|
||||
}
|
||||
|
||||
///| An on/off switch at the right end of a row centred on `mid`: an accent track with the knob
|
||||
/// on the right when on, a muted outline when off.
|
||||
fn switch_ops(w : Int, mid : Int, on : Bool, p : @theme.Palette, ops : Array[@types.DrawOp]) -> Unit {
|
||||
let sx = w - margin - 10 - switch_w
|
||||
let sy = mid - switch_h / 2
|
||||
let knob = switch_h / 2 - 3
|
||||
if on {
|
||||
ops.push(@ui.fill_rect(@ui.rect(sx, sy, switch_w, switch_h), p.accent, radius=switch_h / 2))
|
||||
ops.push(@ui.circle(sx + switch_w - switch_h / 2, mid, knob, p.accent_foreground))
|
||||
} else {
|
||||
ops.push(@ui.stroke_rect(@ui.rect(sx, sy, switch_w, switch_h), p.foreground_muted, width=1, radius=switch_h / 2))
|
||||
ops.push(@ui.circle(sx + switch_h / 2, mid, knob, p.foreground_muted))
|
||||
}
|
||||
}
|
||||
|
||||
///| Width of the "Reset" button at the end of a changed shortcut's row.
|
||||
@@ -190,6 +211,7 @@ fn rows() -> Array[Row] {
|
||||
for i = 0; i < names.length(); i = i + 1 {
|
||||
rs.push(Setting(i, names[i]))
|
||||
}
|
||||
face_rows(rs)
|
||||
}
|
||||
1 => {
|
||||
rs.push(Heading("On the desktop"))
|
||||
@@ -282,6 +304,36 @@ fn rows() -> Array[Row] {
|
||||
rs
|
||||
}
|
||||
|
||||
///| Face unlock's rows on the Session tab (docs/face-unlock.md): the switch, the enrolled faces,
|
||||
/// "Add a face..." and what the last change said. Changes ask for the password first.
|
||||
fn face_rows(rs : Array[Row]) -> Unit {
|
||||
let st = @face_unlock.status()
|
||||
rs.push(Heading("Face unlock"))
|
||||
if !st.installed {
|
||||
rs.push(Info("Not installed: see docs/face-unlock.md"))
|
||||
return
|
||||
}
|
||||
if st.problem != "" {
|
||||
rs.push(Info("! " + st.problem))
|
||||
}
|
||||
if st.howdy != "" {
|
||||
rs.push(Info("Howdy also unlocks " + st.howdy))
|
||||
}
|
||||
rs.push(FaceUse)
|
||||
for i, f in @face_unlock.faces() {
|
||||
rs.push(FaceRow(i, f.label, f.added))
|
||||
}
|
||||
rs.push(FaceAdd)
|
||||
if st.message != "" {
|
||||
rs.push(Info(st.message))
|
||||
}
|
||||
}
|
||||
|
||||
///| `armed` value for "click again to remove" on face `i`.
|
||||
fn face_armed(i : Int) -> Int {
|
||||
100 + i
|
||||
}
|
||||
|
||||
///| Whether row `i` of `rs` can be highlighted and acted on (headings can't).
|
||||
fn active(rs : Array[Row], i : Int) -> Bool {
|
||||
i >= 0 && i < rs.length() && !(rs[i] is (Heading(_) | Info(_) | Category(_) | NothingToAdd))
|
||||
@@ -403,6 +455,10 @@ let hover_btn : Ref[Int] = { val: -1 }
|
||||
fn set_tab(i : Int) -> Unit {
|
||||
cancel_capture()
|
||||
expanded.val = -1
|
||||
if i == 0 {
|
||||
// Faces may have been added or removed elsewhere (chandra-face, another session).
|
||||
@face_unlock.refresh()
|
||||
}
|
||||
if i == 5 && tab.val != 5 {
|
||||
// Another program may have changed a default since the tab was last open.
|
||||
@default_apps.refresh()
|
||||
@@ -457,6 +513,17 @@ fn act(rs : Array[Row], i : Int, btn~ : Int = -1, x~ : Int = 0) -> Unit {
|
||||
armed.val = a
|
||||
}
|
||||
Info(_) => ()
|
||||
FaceUse =>
|
||||
if !@face_unlock.status().busy {
|
||||
@face_unlock.set_in_use(!@face_unlock.status().in_use)
|
||||
}
|
||||
FaceRow(k, _, _) =>
|
||||
if was_armed == face_armed(k) {
|
||||
@face_unlock.remove(k.reinterpret_as_uint())
|
||||
} else {
|
||||
armed.val = face_armed(k)
|
||||
}
|
||||
FaceAdd => if !@face_unlock.status().busy { @face_unlock.enroll() }
|
||||
Shortcut(k, sc) =>
|
||||
if sc.capturing {
|
||||
@shortcuts.cancel_capture()
|
||||
@@ -600,7 +667,7 @@ pub fn popup() -> PopupSurface? {
|
||||
match rs[i] {
|
||||
Heading(_) | Category(_) | NothingToAdd | Browse => ()
|
||||
// Rows with their own buttons get the soft fill, so the buttons stand out.
|
||||
Setting(_, _) | Loaded(_, _, _, _) | Available(_, _, _, _) =>
|
||||
Setting(_, _) | FaceUse | Loaded(_, _, _, _) | Available(_, _, _, _) =>
|
||||
if hot {
|
||||
ops.push(@ui.fill_rect(@ui.rect(margin, y, w - 2 * margin, rh - 2), p.surface_hover, radius=r))
|
||||
}
|
||||
@@ -616,18 +683,30 @@ pub fn popup() -> PopupSurface? {
|
||||
NothingToAdd => ops.push(@ui.text(margin + 10, mid, "Everything is in the panel", fs - 2, p.foreground_muted))
|
||||
Setting(k, name) => {
|
||||
ops.push(@ui.text(margin + 10, mid, name, fs - 1, p.foreground))
|
||||
// The switch: an accent track with the knob on the right when on, a muted outline when off.
|
||||
let on = @settings.is_on(k.reinterpret_as_uint())
|
||||
let sx = w - margin - 10 - switch_w
|
||||
let sy = mid - switch_h / 2
|
||||
let knob = switch_h / 2 - 3
|
||||
if on {
|
||||
ops.push(@ui.fill_rect(@ui.rect(sx, sy, switch_w, switch_h), p.accent, radius=switch_h / 2))
|
||||
ops.push(@ui.circle(sx + switch_w - switch_h / 2, mid, knob, p.accent_foreground))
|
||||
} else {
|
||||
ops.push(@ui.stroke_rect(@ui.rect(sx, sy, switch_w, switch_h), p.foreground_muted, width=1, radius=switch_h / 2))
|
||||
ops.push(@ui.circle(sx + switch_h / 2, mid, knob, p.foreground_muted))
|
||||
switch_ops(w, mid, @settings.is_on(k.reinterpret_as_uint()), p, ops)
|
||||
}
|
||||
FaceUse => {
|
||||
let st = @face_unlock.status()
|
||||
ops.push(@ui.text(margin + 10, mid, "Use my face for passwords", fs - 1, p.foreground))
|
||||
switch_ops(w, mid, st.in_use, p, ops)
|
||||
}
|
||||
FaceRow(k, label, added) => {
|
||||
// A face glyph, the label and date; "Remove" at the right (a second click removes).
|
||||
let gx = margin + 18
|
||||
ops.push(@ui.circle(gx, mid, 7, list_fg, filled=false))
|
||||
ops.push(@ui.circle(gx - 3, mid - 2, 1, list_fg))
|
||||
ops.push(@ui.circle(gx + 3, mid - 2, 1, list_fg))
|
||||
ops.push(@ui.line(gx - 3, mid + 3, gx + 3, mid + 3, list_fg, width=1))
|
||||
ops.push(@ui.text(margin + 32, mid, label, fs - 1, list_fg))
|
||||
let lw = @ui.text_width(label, fs - 1)
|
||||
ops.push(@ui.text(margin + 40 + lw, mid, "added " + added, fs - 3, if hot { list_fg } else { p.foreground_muted }))
|
||||
let armed_here = armed.val == face_armed(k)
|
||||
let rlabel = if armed_here { "Click again to remove" } else { "Remove" }
|
||||
ops.push(@ui.text(w - margin - 10, mid, rlabel, fs - 2, if hot { list_fg } else { p.accent }, align=RIGHT, bold=armed_here))
|
||||
}
|
||||
FaceAdd => {
|
||||
let busy = @face_unlock.status().busy
|
||||
ops.push(@ui.text(margin + 10, mid, if busy { "Working…" } else { "Add a face…" }, fs - 1, if busy && !hot { p.foreground_muted } else { list_fg }, bold=true))
|
||||
}
|
||||
DesktopChoice(k, name) => {
|
||||
if k == cur_desk {
|
||||
|
||||
@@ -31,7 +31,9 @@ declare pub fn on_scroll(at : @types.Point, dx : Int, dy : Int) -> Bool
|
||||
///|
|
||||
/// The animation clock. `now-ms` counts milliseconds from when the module was loaded. It is
|
||||
/// called once after loading, after every event the module handled, and again when the delay it
|
||||
/// last returned has passed; the module is redrawn after each call. Return how many ms until the
|
||||
/// last returned has passed. The module is redrawn after each timed call (an animation frame)
|
||||
/// and after events that returned true; a call that follows an event only reschedules the
|
||||
/// clock and does not redraw by itself. Return how many ms until the
|
||||
/// next frame (16 for about 60 frames a second, 33 for 30), or 0 to sleep until the next event:
|
||||
/// an idle desktop module costs nothing, so return 0 whenever nothing moves. Frames are paused
|
||||
/// (no calls) while a window covers the whole desktop.
|
||||
|
||||
@@ -335,7 +335,7 @@ fn ChandraCompositor::auth_cursor(self : ChandraCompositor, ui : AuthUi) -> UInt
|
||||
///| Whether the dialog animates (a failed attempt shakes it; a spinner while PAM checks).
|
||||
fn ChandraCompositor::auth_animating(self : ChandraCompositor) -> Bool {
|
||||
match self.auth {
|
||||
Some(ui) => ui.dialog.shaking(@sys.monotonic_ms()) || ui.dialog.phase == Checking
|
||||
Some(ui) => ui.dialog.shaking(@sys.monotonic_ms()) || ui.dialog.phase == Checking || ui.dialog.face == Scanning
|
||||
None => false
|
||||
}
|
||||
}
|
||||
@@ -445,6 +445,24 @@ fn auth_button(
|
||||
}
|
||||
}
|
||||
|
||||
///| A face outline (head, eyes, smile) centred at (cx, cy), `r` the head's radius.
|
||||
fn face_glyph(cx : Int, cy : Int, r : Int, c : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit {
|
||||
ops.push(@scene.DrawOp::Circle(cx, cy, r, c, false))
|
||||
ops.push(@scene.DrawOp::Circle(cx - r * 2 / 5, cy - r / 4, r / 8 + 1, c, true))
|
||||
ops.push(@scene.DrawOp::Circle(cx + r * 2 / 5, cy - r / 4, r / 8 + 1, c, true))
|
||||
ops.push(@scene.DrawOp::Line(cx - r / 2, cy + r / 4, cx - r / 5, cy + r / 2, c, 2))
|
||||
ops.push(@scene.DrawOp::Line(cx - r / 5, cy + r / 2, cx + r / 5, cy + r / 2, c, 2))
|
||||
ops.push(@scene.DrawOp::Line(cx + r / 5, cy + r / 2, cx + r / 2, cy + r / 4, c, 2))
|
||||
}
|
||||
|
||||
///| Point `k` of 12 on a circle of radius `r` (clockwise from the top).
|
||||
fn ring_point(k : Int, r : Int) -> (Int, Int) {
|
||||
// sin and cos of k * 30 degrees, times 1000.
|
||||
let s = [0, 500, 866, 1000, 866, 500, 0, -500, -866, -1000, -866, -500]
|
||||
let c = [1000, 866, 500, 0, -500, -866, -1000, -866, -500, 0, 500, 866]
|
||||
(s[k % 12] * r / 1000, -c[k % 12] * r / 1000)
|
||||
}
|
||||
|
||||
///| A right-pointing (`down`: down-pointing) chevron centred at (cx, cy).
|
||||
fn chevron(cx : Int, cy : Int, s : Int, down : Bool, left : Bool, c : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit {
|
||||
if down {
|
||||
@@ -563,6 +581,55 @@ fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp]
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
// Face unlock: what the face module in the PAM stack is doing (docs/face-unlock.md).
|
||||
if d.face != NoFace {
|
||||
let rh = 48
|
||||
let cx = pad + 25
|
||||
let cy = y + rh / 2
|
||||
let tint = match d.face {
|
||||
FaceFailed(_) => warn_c
|
||||
_ => p.accent
|
||||
}
|
||||
body.push(@scene.DrawOp::FillRect(@scene.Rect::new(pad, y, inner, rh), p.surface_hover, rad))
|
||||
face_glyph(cx, cy, 13, if d.face is FaceFailed(_) { p.foreground_muted } else { p.foreground }, body)
|
||||
match d.face {
|
||||
Scanning => {
|
||||
// A ring of dots sweeping round the face.
|
||||
let t = ((now - d.face_at) / 70UL).to_int()
|
||||
for k = 0; k < 12; k = k + 1 {
|
||||
let a = (k + t) % 12
|
||||
let (dx, dy) = ring_point(a, 19)
|
||||
let alpha = 40 + k * 18
|
||||
body.push(@scene.DrawOp::Circle(cx + dx, cy + dy, 2, @scene.Rgba::new(p.accent.r.to_int(), p.accent.g.to_int(), p.accent.b.to_int(), alpha), true))
|
||||
}
|
||||
}
|
||||
Matched => {
|
||||
body.push(@scene.DrawOp::Circle(cx + 13, cy + 11, 8, p.accent, true))
|
||||
body.push(@scene.DrawOp::Line(cx + 9, cy + 11, cx + 12, cy + 14, p.accent_foreground, 2))
|
||||
body.push(@scene.DrawOp::Line(cx + 12, cy + 14, cx + 17, cy + 8, p.accent_foreground, 2))
|
||||
}
|
||||
FaceFailed(_) => {
|
||||
body.push(@scene.DrawOp::Circle(cx + 13, cy + 11, 8, warn_c, true))
|
||||
body.push(@scene.DrawOp::Line(cx + 10, cy + 8, cx + 16, cy + 14, p.surface_popup, 2))
|
||||
body.push(@scene.DrawOp::Line(cx + 16, cy + 8, cx + 10, cy + 14, p.surface_popup, 2))
|
||||
}
|
||||
NoFace => ()
|
||||
}
|
||||
let (title, sub) = match d.face {
|
||||
Scanning => ("Looking for your face…", "Or type your password")
|
||||
Matched => ("Face recognized", "")
|
||||
FaceFailed(why) => (why, "Type your password instead")
|
||||
NoFace => ("", "")
|
||||
}
|
||||
let tx = pad + 54
|
||||
if sub == "" {
|
||||
body.push(@scene.DrawOp::Text(tx, cy, title, fs, tint, @scene.TextAlign::Left, true))
|
||||
} else {
|
||||
body.push(@scene.DrawOp::Text(tx, cy - 8, title, fs, tint, @scene.TextAlign::Left, true))
|
||||
body.push(@scene.DrawOp::Text(tx, cy + 10, sub, fs - 2, p.foreground_muted, @scene.TextAlign::Left, false))
|
||||
}
|
||||
y = y + rh + 12
|
||||
}
|
||||
// The prompt and the field.
|
||||
body.push(@scene.DrawOp::Text(pad, y + 7, d.prompt, fs - 1, p.foreground_muted, @scene.TextAlign::Left, true))
|
||||
y = y + 20
|
||||
@@ -592,7 +659,7 @@ fn ChandraCompositor::auth_ops(self : ChandraCompositor) -> Array[@scene.DrawOp]
|
||||
if d.typed() == 0 {
|
||||
let hint = match d.phase {
|
||||
Starting => "Preparing…"
|
||||
Waiting => "Waiting…"
|
||||
Waiting => if d.face == Scanning { "Type your password" } else { "Waiting…" }
|
||||
_ => if d.echo { "Type your answer" } else { "Type your password" }
|
||||
}
|
||||
body.push(@scene.DrawOp::Text(pad + 18, cy, hint, fs, @scene.Rgba::new(p.foreground_muted.r.to_int(), p.foreground_muted.g.to_int(), p.foreground_muted.b.to_int(), 150), @scene.TextAlign::Left, false))
|
||||
|
||||
@@ -348,8 +348,16 @@ test "Escape dismisses: polkitd hears Cancelled; polkitd withdrawing a request c
|
||||
assert_eq(comp.auth_dialog().unwrap().user().map(u => u.name), Some("ada"))
|
||||
let (h2, hello) = helper_accept(listen, comp, a)
|
||||
assert_eq(hello, "ada|c1")
|
||||
// Face unlock (pam_chandra_face.so): the face row scans, then gives way to the password.
|
||||
helper_say(h2, "PAM_TEXT_INFO Face unlock: looking for ada…")
|
||||
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.face == Scanning).unwrap_or(false) }))
|
||||
assert_eq(comp.auth_dialog().unwrap().info, "") // the fingerprint message went with nandi's attempt
|
||||
auth_shot(comp, "14-face-scanning")
|
||||
helper_say(h2, "PAM_ERROR_MSG Face unlock: face not recognized")
|
||||
helper_say(h2, "PAM_PROMPT_ECHO_OFF Password: ")
|
||||
assert_true(settle(comp, a, fn() { comp.auth_dialog().map(d => d.phase == Prompt).unwrap_or(false) }))
|
||||
assert_eq(comp.auth_dialog().unwrap().face, FaceFailed("Face not recognized"))
|
||||
auth_shot(comp, "15-face-failed")
|
||||
auth_shot(comp, "12-other-account")
|
||||
auth_press(comp, 1U) // Escape
|
||||
assert_true(settle(comp, a, fn() { a.answers.length() == 1 }))
|
||||
|
||||
@@ -641,7 +641,8 @@ pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
|
||||
self.auth_animating() ||
|
||||
self.thumbs_pending() ||
|
||||
self.overview_animating() ||
|
||||
self.shell.animating()
|
||||
self.shell.animating() ||
|
||||
self.shell.face_busy()
|
||||
}
|
||||
|
||||
///| How long an idle main loop may sleep: `idle_ms` (until the wall clock's next second), or
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
///| Face unlock in Settings > Session (docs/face-unlock.md), against a fake chandra-face: a shell
|
||||
/// script that answers `status` from files and changes them for enroll / remove / pam, the way
|
||||
/// the real one does after run0 or pkexec. CHANDRA_AUTH_SHOTS=dir also saves a PNG of the tab.
|
||||
|
||||
///| Write the fake tool into `dir` and return its path.
|
||||
fn fake_face_tool(dir : String) -> String {
|
||||
let script =
|
||||
#|#!/bin/sh
|
||||
#|S="$(dirname "$0")"
|
||||
#|case "$1" in
|
||||
#|status)
|
||||
#| echo "backend opencv"; echo "device /dev/video2"
|
||||
#| echo "pam $(cat "$S/pam" 2>/dev/null)"
|
||||
#| cat "$S/faces" 2>/dev/null ;;
|
||||
#|enroll)
|
||||
#| echo "info Look at the camera…"
|
||||
#| for i in 1 2 3 4 5; do echo "progress $i/5"; done
|
||||
#| printf 'face 2\tFace 2\t2026-11-26\n' >> "$S/faces"
|
||||
#| echo "done Added Face 2" ;;
|
||||
#|remove)
|
||||
#| grep -v "^face $2 " "$S/faces" > "$S/faces.new"; mv "$S/faces.new" "$S/faces"
|
||||
#| echo "done Removed face $2" ;;
|
||||
#|pam)
|
||||
#| if [ "$2" = enable ]; then echo "polkit-1,sudo" > "$S/pam"; else : > "$S/pam"; fi
|
||||
#| echo "done ok" ;;
|
||||
#|esac
|
||||
ignore(@sys.mkdir_p(dir))
|
||||
let tool = dir + "/chandra-face"
|
||||
ignore(@sys.write_file_bytes(tool, @sys.str_to_utf8_bytes(script)))
|
||||
ignore(@sys.write_file_bytes(dir + "/faces", @sys.str_to_utf8_bytes("face 1\tDesk\t2026-11-20\n")))
|
||||
tool
|
||||
}
|
||||
|
||||
///| Compose frames until `cond` holds (the tool runs on a socket), at most ~3 s.
|
||||
fn face_settle(comp : @host.ChandraCompositor, cond : () -> Bool) -> Bool {
|
||||
for i = 0; i < 300; i = i + 1 {
|
||||
ignore(comp.compose_frame())
|
||||
if cond() {
|
||||
return true
|
||||
}
|
||||
@sys.sleep_ms(10)
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///| The popup's texts.
|
||||
fn face_texts(comp : @host.ChandraCompositor) -> Array[String] {
|
||||
let slot = comp.shell.slot_of("session-settings")
|
||||
comp.shell.slot_popup_texts(slot).map(t => t.0)
|
||||
}
|
||||
|
||||
///| Click the popup text `label`.
|
||||
fn face_click(comp : @host.ChandraCompositor, label : String, t : UInt) -> Unit raise {
|
||||
let slot = comp.shell.slot_of("session-settings")
|
||||
let pr = comp.shell.slot_popup_rect(slot)
|
||||
match comp.shell.slot_popup_texts(slot).iter().find_first(x => x.0 == label) {
|
||||
Some((_, x, y)) => {
|
||||
comp.handle_input(@nested.InputEvent::PointerMove((pr.x + x + 4).to_double(), (pr.y + y).to_double()), t)
|
||||
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), t + 1U)
|
||||
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), t + 2U)
|
||||
ignore(comp.compose_frame())
|
||||
}
|
||||
None => fail("no \"" + label + "\" in the popup")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
test "Settings > Session: face unlock lists faces, adds one, turns it on, removes one" {
|
||||
let dir = "/tmp/chandra-face-test-" + @sys.getpid().to_string()
|
||||
let tool = fake_face_tool(dir)
|
||||
let comp = new_comp("face")
|
||||
// spawn-socket runs a program; the script has no x bit (sys has no chmod): through sh.
|
||||
comp.shell.set_face_tool(["/bin/sh", tool])
|
||||
assert_true(comp.shell.open_settings(Session))
|
||||
assert_true(face_settle(comp, fn() { face_texts(comp).contains("Desk") }))
|
||||
let texts = face_texts(comp)
|
||||
assert_true(texts.contains("Face unlock"))
|
||||
assert_true(texts.contains("Use my face for passwords"))
|
||||
assert_true(texts.contains("added 2026-11-20"))
|
||||
assert_true(texts.contains("Add a face…"))
|
||||
assert_false(comp.shell.face.in_use())
|
||||
// Add a face: the tool's progress shows, then the new face.
|
||||
face_click(comp, "Add a face…", 10U)
|
||||
assert_true(face_settle(comp, fn() { face_texts(comp).contains("Face 2") }))
|
||||
assert_true(face_texts(comp).contains("Added Face 2"))
|
||||
// The switch: polkit-1 and sudo try the face first.
|
||||
face_click(comp, "Use my face for passwords", 20U)
|
||||
assert_true(face_settle(comp, fn() { comp.shell.face.in_use() }))
|
||||
let shots = @sys.getenv("CHANDRA_AUTH_SHOTS")
|
||||
if shots != "" {
|
||||
ignore(@sys.write_file_bytes(shots + "/16-settings-face.png", @renderer.encode_png_compressed(comp.compose_frame())))
|
||||
}
|
||||
// Remove takes a second click.
|
||||
face_click(comp, "Remove", 30U)
|
||||
assert_true(face_texts(comp).contains("Click again to remove"))
|
||||
assert_eq(comp.shell.face.faces.length(), 2)
|
||||
face_click(comp, "Click again to remove", 40U)
|
||||
assert_true(face_settle(comp, fn() { comp.shell.face.faces.length() == 1 }))
|
||||
assert_eq(comp.shell.face.faces[0].1, "Face 2")
|
||||
comp.close()
|
||||
}
|
||||
|
||||
///|
|
||||
test "face unlock status lines" {
|
||||
let f = @shell.FaceUnlock::new()
|
||||
f.apply_status([
|
||||
"backend opencv", "device /dev/video0", "problem python3-opencv is not installed", "pam polkit-1,sudo",
|
||||
"howdy login,gdm-password", "face 3\tGlasses\t2026-11-01",
|
||||
])
|
||||
assert_true(f.installed)
|
||||
assert_eq(f.problem, "python3-opencv is not installed")
|
||||
assert_true(f.in_use())
|
||||
assert_eq(f.howdy, "login, gdm-password")
|
||||
assert_eq(f.faces, [("3", "Glasses", "2026-11-01")])
|
||||
// No tool: nothing is installed, whatever else was said.
|
||||
f.apply_status([])
|
||||
assert_false(f.installed)
|
||||
assert_false(f.in_use())
|
||||
assert_eq(@shell.face_progress("progress 2/5"), Some("Look at the camera… 2/5"))
|
||||
assert_eq(@shell.face_progress("error couldn't see a face clearly"), Some("Couldn't see a face clearly"))
|
||||
assert_eq(@shell.face_progress("face 1\tDesk\t2026-11-20"), None)
|
||||
}
|
||||
@@ -1694,7 +1694,8 @@ test "open_settings opens the settings module on the tab asked for" {
|
||||
assert_eq(pr.h, 40 + (1 + 4 + 6) * 28 + 6)
|
||||
assert_true(comp.shell.open_settings(Session))
|
||||
ignore(comp.compose_frame())
|
||||
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 4 * 28 + 6) // the four settings
|
||||
// The four settings, then Face unlock (a heading; chandra-face isn't installed in tests).
|
||||
assert_eq(comp.shell.slot_popup_rect(slot).h, 40 + 6 * 28 + 6)
|
||||
}
|
||||
|
||||
///|
|
||||
|
||||
@@ -14,6 +14,66 @@ pub(all) enum Phase {
|
||||
Waiting
|
||||
} derive(Eq, Debug)
|
||||
|
||||
///| Face unlock (docs/face-unlock.md): what the face module in the PAM stack said, for the
|
||||
/// dialog's face row. Chandra's own pam_chandra_face.so says "Face unlock: ..."; Howdy's
|
||||
/// pam_howdy.so says "Attempting facial authentication", "Identified face as ...", and its
|
||||
/// failures as errors.
|
||||
pub(all) enum FaceState {
|
||||
/// No face module spoke in this attempt.
|
||||
NoFace
|
||||
/// Looking for the face; typing the password meanwhile still works (it goes in when PAM asks).
|
||||
Scanning
|
||||
/// Recognized: PAM is finishing.
|
||||
Matched
|
||||
/// Not this time, and why ("Face not recognized"); the password is next.
|
||||
FaceFailed(String)
|
||||
} derive(Eq, Debug)
|
||||
|
||||
///| What a PAM message means for face unlock, if it is about it: Some(state), else None.
|
||||
pub fn face_message(m : String, is_error : Bool) -> FaceState? {
|
||||
let t = m.trim(chars=" \n").to_string()
|
||||
let low = t.to_lower()
|
||||
let ours = low.has_prefix("face unlock:")
|
||||
let body = if ours { t[12:].to_string().trim(chars=" ").to_string() } else { t }
|
||||
let lbody = body.to_lower()
|
||||
if ours {
|
||||
if is_error {
|
||||
let why = if lbody.has_prefix("face not recognized") || lbody == "" {
|
||||
"Face not recognized"
|
||||
} else {
|
||||
upper_first(body)
|
||||
}
|
||||
return Some(FaceFailed(why))
|
||||
}
|
||||
if lbody.has_prefix("recognized") {
|
||||
return Some(Matched)
|
||||
}
|
||||
return Some(Scanning)
|
||||
}
|
||||
// Howdy (pam_howdy.so).
|
||||
if low.has_prefix("attempting facial authentication") || low.has_prefix("attempting face detection") {
|
||||
return Some(Scanning)
|
||||
}
|
||||
if low.has_prefix("identified face as") {
|
||||
return Some(Matched)
|
||||
}
|
||||
if is_error && (low.has_prefix("failure, timeout reached") || low.has_prefix("failure, not a single face")) {
|
||||
return Some(FaceFailed("Face not recognized"))
|
||||
}
|
||||
if is_error && low.has_prefix("face detection image too dark") {
|
||||
return Some(FaceFailed("The camera picture is too dark"))
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///| "camera not available" -> "Camera not available".
|
||||
fn upper_first(s : String) -> String {
|
||||
if s.length() == 0 {
|
||||
return s
|
||||
}
|
||||
s[:1].to_string().to_upper() + s[1:].to_string()
|
||||
}
|
||||
|
||||
///| The dialog's controls, in Tab order.
|
||||
pub(all) enum Focus {
|
||||
Field
|
||||
@@ -101,6 +161,10 @@ pub(all) struct AuthDialog {
|
||||
mut focus : Focus
|
||||
/// Enter came before PAM's prompt: answer as soon as it does.
|
||||
mut submit_queued : Bool
|
||||
/// Face unlock in this attempt (NoFace when no face module spoke).
|
||||
mut face : FaceState
|
||||
/// When face unlock started looking (monotonic ms; the scan animation's clock).
|
||||
mut face_at : UInt64
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -122,6 +186,8 @@ pub fn AuthDialog::new(req : AuthRequest, desc : Description) -> AuthDialog {
|
||||
shake_at: 0UL,
|
||||
focus: Field,
|
||||
submit_queued: false,
|
||||
face: NoFace,
|
||||
face_at: 0UL,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,8 +273,29 @@ fn AuthDialog::submit(self : AuthDialog) -> DialogEffect {
|
||||
|
||||
///| Something from the helper. `now` is the monotonic clock (for the shake).
|
||||
pub fn AuthDialog::helper(self : AuthDialog, ev : HelperEvent, now : UInt64) -> DialogEffect {
|
||||
match ev {
|
||||
TextInfo(m) | ErrorMsg(m) =>
|
||||
match face_message(m, ev is ErrorMsg(_)) {
|
||||
Some(f) => {
|
||||
if f == Scanning && self.face != Scanning {
|
||||
self.face_at = if now == 0UL { 1UL } else { now }
|
||||
}
|
||||
self.face = f
|
||||
if self.phase == Starting {
|
||||
self.phase = Waiting
|
||||
}
|
||||
return Nothing
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
match ev {
|
||||
PromptEchoOff(p) | PromptEchoOn(p) => {
|
||||
// The face module gave up without saying why (a timeout, or Howdy's silent failures).
|
||||
if self.face == Scanning {
|
||||
self.face = FaceFailed("Face not recognized")
|
||||
}
|
||||
self.phase = Prompt
|
||||
self.prompt = tidy_prompt(p)
|
||||
self.echo = ev is PromptEchoOn(_)
|
||||
@@ -245,6 +332,7 @@ pub fn AuthDialog::helper(self : AuthDialog, ev : HelperEvent, now : UInt64) ->
|
||||
self.submit_queued = false
|
||||
self.phase = Starting
|
||||
self.info = ""
|
||||
self.face = NoFace
|
||||
self.focus = Field
|
||||
Restart
|
||||
}
|
||||
@@ -282,6 +370,7 @@ fn AuthDialog::cycle_user(self : AuthDialog, delta : Int) -> DialogEffect {
|
||||
self.wipe()
|
||||
self.error = ""
|
||||
self.info = ""
|
||||
self.face = NoFace
|
||||
self.phase = Starting
|
||||
self.submit_queued = false
|
||||
Restart
|
||||
@@ -401,6 +490,16 @@ pub fn AuthDialog::shake_offset(self : AuthDialog, now : UInt64) -> Int {
|
||||
tri * amp / period
|
||||
}
|
||||
|
||||
///| What the face row says, "" when there is none.
|
||||
pub fn AuthDialog::face_text(self : AuthDialog) -> String {
|
||||
match self.face {
|
||||
NoFace => ""
|
||||
Scanning => "Looking for your face…"
|
||||
Matched => "Face recognized"
|
||||
FaceFailed(why) => why + ". Use your password."
|
||||
}
|
||||
}
|
||||
|
||||
///| Whether the card is still shaking.
|
||||
pub fn AuthDialog::shaking(self : AuthDialog, now : UInt64) -> Bool {
|
||||
self.shake_at != 0UL && now >= self.shake_at && now - self.shake_at < 420UL
|
||||
|
||||
@@ -325,3 +325,55 @@ test "the setuid route: the helper runs on a socket pair and speaks the protocol
|
||||
s.close()
|
||||
@sys.unlink(script)
|
||||
}
|
||||
|
||||
///|
|
||||
test "face unlock: Chandra's and Howdy's PAM messages" {
|
||||
assert_eq(@polkit.face_message("Face unlock: looking for nandi…", false), Some(Scanning))
|
||||
assert_eq(@polkit.face_message("Face unlock: recognized nandi", false), Some(Matched))
|
||||
assert_eq(@polkit.face_message("Face unlock: face not recognized", true), Some(FaceFailed("Face not recognized")))
|
||||
assert_eq(@polkit.face_message("Face unlock: the camera picture is too dark\n", true), Some(FaceFailed("The camera picture is too dark")))
|
||||
assert_eq(@polkit.face_message("Attempting facial authentication", false), Some(Scanning))
|
||||
assert_eq(@polkit.face_message("Identified face as nandi", false), Some(Matched))
|
||||
assert_eq(@polkit.face_message("Failure, timeout reached", true), Some(FaceFailed("Face not recognized")))
|
||||
assert_eq(@polkit.face_message("Face detection image too dark", true), Some(FaceFailed("The camera picture is too dark")))
|
||||
assert_eq(@polkit.face_message("Place your finger on the fingerprint reader", false), None)
|
||||
assert_eq(@polkit.face_message("The account is locked due to 3 failed logins.", true), None)
|
||||
}
|
||||
|
||||
///|
|
||||
test "dialog: face unlock scans, the password typed meanwhile goes in when it fails" {
|
||||
let d = dialog(1)
|
||||
ignore(d.helper(TextInfo("Face unlock: looking for nandi…"), 50UL))
|
||||
assert_eq(d.face, Scanning)
|
||||
assert_eq(d.face_at, 50UL)
|
||||
assert_eq(d.phase, Waiting)
|
||||
assert_eq(d.info, "") // the face row says it, not the info line
|
||||
// Typing while it looks is kept, and Enter waits for the password prompt.
|
||||
for c in "hunter2" {
|
||||
ignore(d.key(0U, 0U, Some(c)))
|
||||
}
|
||||
assert_true(d.key(@polkit.key_enter, 0U, None) is Nothing)
|
||||
ignore(d.helper(ErrorMsg("Face unlock: face not recognized"), 60UL))
|
||||
assert_eq(d.face, FaceFailed("Face not recognized"))
|
||||
assert_eq(d.error, "")
|
||||
assert_eq(d.face_text(), "Face not recognized. Use your password.")
|
||||
assert_eq(answer_text(d.helper(PromptEchoOff("Password: "), 70UL)), "hunter2")
|
||||
// A wrong password restarts the conversation: the face is tried again.
|
||||
assert_true(d.helper(Failure, 80UL) is Restart)
|
||||
assert_eq(d.face, NoFace)
|
||||
// Recognized: PAM finishes without a password.
|
||||
ignore(d.helper(TextInfo("Attempting facial authentication"), 90UL))
|
||||
assert_eq(d.face, Scanning)
|
||||
ignore(d.helper(TextInfo("Identified face as nandi"), 95UL))
|
||||
assert_eq(d.face, Matched)
|
||||
assert_true(d.helper(Success, 99UL) is Authorized)
|
||||
}
|
||||
|
||||
///|
|
||||
test "dialog: a face module that gives up silently still shows as not recognized" {
|
||||
let d = dialog(1)
|
||||
ignore(d.helper(TextInfo("Attempting facial authentication"), 1UL))
|
||||
ignore(d.helper(PromptEchoOff("Password: "), 2UL))
|
||||
assert_eq(d.face, FaceFailed("Face not recognized"))
|
||||
assert_eq(d.phase, Prompt)
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
///| The `face-unlock` capability (docs/face-unlock.md): Settings > Session lists the session
|
||||
/// user's enrolled faces and whether the password dialog and sudo try the face first. The shell
|
||||
/// gets all of it from `chandra-face` (face/chandra-face), run on a socket so the compositor
|
||||
/// never waits on it: `status` as the user (labels only, no face data), and enroll / remove /
|
||||
/// `pam enable|disable` the same way, which re-run themselves through run0 or pkexec, so polkit
|
||||
/// asks for an administrator's password (in Chandra's own dialog) before anything changes. The
|
||||
/// camera pictures stay inside that root process.
|
||||
|
||||
///| What the shell knows about face unlock, and the chandra-face run in progress.
|
||||
pub(all) struct FaceUnlock {
|
||||
/// How to run the tool: its path (CHANDRA_FACE_TOOL, else the installed helper; none in tests
|
||||
/// unless set), or an interpreter and the path.
|
||||
mut tool : Array[String]
|
||||
/// The last status said "backend ..." (the tool runs).
|
||||
mut installed : Bool
|
||||
mut problem : String
|
||||
/// PAM services using pam_chandra_face.so / Howdy's pam_howdy.so.
|
||||
mut pam : Array[String]
|
||||
mut howdy : String
|
||||
/// (id, label, added) of each enrolled face.
|
||||
mut faces : Array[(String, String, String)]
|
||||
/// What the running change said last, or how the last one ended.
|
||||
mut message : String
|
||||
/// The run in progress: our end of its socket, what it has said so far, and whether it is a
|
||||
/// change (the status is read again after one).
|
||||
mut fd : Int
|
||||
inbuf : Array[Byte]
|
||||
mut lines : Array[String]
|
||||
mut change : Bool
|
||||
/// Runs waiting their turn (one at a time): (argv, is a change).
|
||||
queue : Array[(Array[String], Bool)]
|
||||
/// The status was read at least once.
|
||||
mut loaded : Bool
|
||||
mut dirty : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn FaceUnlock::new() -> FaceUnlock {
|
||||
let env = @sys.getenv("CHANDRA_FACE_TOOL")
|
||||
{
|
||||
tool: [
|
||||
if env != "" {
|
||||
env
|
||||
} else if @sys.getenv("CHANDRA_TEST_CONFIG") != "" {
|
||||
"/nonexistent/chandra-face" // tests don't see a chandra-face installed on the machine
|
||||
} else {
|
||||
"/usr/local/lib/chandra/chandra-face"
|
||||
},
|
||||
],
|
||||
installed: false,
|
||||
problem: "",
|
||||
pam: [],
|
||||
howdy: "",
|
||||
faces: [],
|
||||
message: "",
|
||||
fd: -1,
|
||||
inbuf: [],
|
||||
lines: [],
|
||||
change: false,
|
||||
queue: [],
|
||||
loaded: false,
|
||||
dirty: true,
|
||||
}
|
||||
}
|
||||
|
||||
///| Run chandra-face as `argv` (tests: a fake, `["/bin/sh", script]`) and read the status again.
|
||||
pub fn DesktopShell::set_face_tool(self : DesktopShell, argv : Array[String]) -> Unit {
|
||||
self.face.tool = argv
|
||||
self.face.loaded = false
|
||||
self.face.refresh()
|
||||
}
|
||||
|
||||
///| Whether the password dialog (polkit-1) tries the face first.
|
||||
pub fn FaceUnlock::in_use(self : FaceUnlock) -> Bool {
|
||||
self.pam.contains("polkit-1")
|
||||
}
|
||||
|
||||
///| A change is running or waiting.
|
||||
pub fn FaceUnlock::busy(self : FaceUnlock) -> Bool {
|
||||
(self.fd >= 0 && self.change) || self.queue.iter().any(q => q.1)
|
||||
}
|
||||
|
||||
///| Run `args` of the tool (after the one in progress).
|
||||
fn FaceUnlock::run(self : FaceUnlock, args : Array[String], change : Bool) -> Unit {
|
||||
let argv = self.tool.copy()
|
||||
argv.append(args)
|
||||
argv.push("--machine")
|
||||
self.queue.push((argv, change))
|
||||
self.next()
|
||||
}
|
||||
|
||||
///| Start the next queued run when none is in progress.
|
||||
fn FaceUnlock::next(self : FaceUnlock) -> Unit {
|
||||
if self.fd >= 0 || self.queue.length() == 0 {
|
||||
return
|
||||
}
|
||||
let (argv, change) = self.queue.remove(0)
|
||||
self.lines = []
|
||||
self.inbuf.clear()
|
||||
self.change = change
|
||||
self.fd = @sys.spawn_socket(argv)
|
||||
if self.fd < 0 {
|
||||
if change {
|
||||
self.message = "Couldn't run chandra-face"
|
||||
}
|
||||
self.installed = false
|
||||
self.loaded = true
|
||||
self.dirty = true
|
||||
self.next()
|
||||
}
|
||||
}
|
||||
|
||||
///| Read the status again.
|
||||
pub fn FaceUnlock::refresh(self : FaceUnlock) -> Unit {
|
||||
if self.queue.iter().any(q => !q.1) {
|
||||
return
|
||||
}
|
||||
self.run(["status"], false)
|
||||
}
|
||||
|
||||
///| Read what the run in progress said (non-blocking); finish it at EOF.
|
||||
pub fn FaceUnlock::poll(self : FaceUnlock) -> Unit {
|
||||
if self.fd < 0 {
|
||||
return
|
||||
}
|
||||
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
|
||||
let mut eof = false
|
||||
while @sys.poll_read(self.fd, 0) > 0 {
|
||||
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
|
||||
if extra >= 0 {
|
||||
@sys.close_fd(extra)
|
||||
}
|
||||
if n == -1 {
|
||||
break
|
||||
}
|
||||
if n <= 0 {
|
||||
eof = true
|
||||
break
|
||||
}
|
||||
for i = 0; i < n; i = i + 1 {
|
||||
self.inbuf.push(buf[i])
|
||||
}
|
||||
}
|
||||
// Whole lines; a change shows its latest one as it goes.
|
||||
while true {
|
||||
let nl = self.inbuf.search(b'\n').unwrap_or(-1)
|
||||
if nl < 0 {
|
||||
break
|
||||
}
|
||||
let line = @utf8.decode_lossy(Bytes::from_array(self.inbuf[:nl].to_array()))
|
||||
let rest = self.inbuf[nl + 1:].to_array()
|
||||
self.inbuf.clear()
|
||||
self.inbuf.append(rest)
|
||||
self.lines.push(line)
|
||||
if self.change {
|
||||
match face_progress(line) {
|
||||
Some(m) => {
|
||||
self.message = m
|
||||
self.dirty = true
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
if !eof {
|
||||
return
|
||||
}
|
||||
@sys.close_fd(self.fd)
|
||||
self.fd = -1
|
||||
if self.change {
|
||||
if !self.lines.iter().any(l => l.has_prefix("done ") || l.has_prefix("error ")) {
|
||||
// run0 / pkexec refused (no password, or it was cancelled) before the tool ran.
|
||||
self.message = "Nothing changed"
|
||||
}
|
||||
self.change = false
|
||||
self.dirty = true
|
||||
self.refresh()
|
||||
} else {
|
||||
self.apply_status(self.lines)
|
||||
}
|
||||
self.next()
|
||||
}
|
||||
|
||||
///| What a change's line means for the Settings row ("Look at the camera… 3/5"), if anything.
|
||||
pub fn face_progress(line : String) -> String? {
|
||||
let (kind, text) = match line.find(" ") {
|
||||
Some(i) => (line[:i].to_string(), line[i + 1:].to_string())
|
||||
None => (line, "")
|
||||
}
|
||||
match kind {
|
||||
"info" | "done" => Some(upper_first(text))
|
||||
"error" => Some(upper_first(text))
|
||||
"progress" => Some("Look at the camera… " + text)
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn upper_first(s : String) -> String {
|
||||
if s.length() == 0 {
|
||||
s
|
||||
} else {
|
||||
s[:1].to_string().to_upper() + s[1:].to_string()
|
||||
}
|
||||
}
|
||||
|
||||
///| Take in `chandra-face status --machine` output.
|
||||
pub fn FaceUnlock::apply_status(self : FaceUnlock, lines : Array[String]) -> Unit {
|
||||
let mut installed = false
|
||||
let mut problem = ""
|
||||
let mut howdy = ""
|
||||
let pam : Array[String] = []
|
||||
let faces : Array[(String, String, String)] = []
|
||||
for line in lines {
|
||||
let (kind, text) = match line.find(" ") {
|
||||
Some(i) => (line[:i].to_string(), line[i + 1:].to_string())
|
||||
None => (line, "")
|
||||
}
|
||||
match kind {
|
||||
"backend" => installed = true
|
||||
"problem" => problem = text
|
||||
"howdy" => howdy = text.replace_all(old=",", new=", ")
|
||||
"pam" =>
|
||||
for s in text.split(",") {
|
||||
if s != "" {
|
||||
pam.push(s.to_string())
|
||||
}
|
||||
}
|
||||
"face" => {
|
||||
let f = text.split("\t").map(s => s.to_string()).to_array()
|
||||
if f.length() == 3 {
|
||||
faces.push((f[0], f[1], f[2]))
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
self.installed = installed
|
||||
self.problem = if installed { problem } else { "" }
|
||||
self.howdy = howdy
|
||||
self.pam = pam
|
||||
self.faces = faces
|
||||
self.loaded = true
|
||||
self.dirty = true
|
||||
}
|
||||
|
||||
///| A face-unlock request: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop / start
|
||||
/// using it for the password dialog and sudo.
|
||||
pub fn FaceUnlock::request(self : FaceUnlock, code : Int) -> Unit {
|
||||
if code == -1 {
|
||||
self.refresh()
|
||||
return
|
||||
}
|
||||
if self.busy() {
|
||||
return // one change at a time
|
||||
}
|
||||
match code {
|
||||
-2 => {
|
||||
self.message = "Waiting for the password…"
|
||||
self.run(["enroll"], true)
|
||||
}
|
||||
-3 => {
|
||||
self.message = "Waiting for the password…"
|
||||
self.run(["pam", "disable"], true)
|
||||
}
|
||||
-4 => {
|
||||
self.message = "Waiting for the password…"
|
||||
self.run(["pam", "enable"], true)
|
||||
}
|
||||
i if i >= 0 && i < self.faces.length() => {
|
||||
self.message = "Waiting for the password…"
|
||||
self.run(["remove", self.faces[i].0], true)
|
||||
}
|
||||
_ => return
|
||||
}
|
||||
self.dirty = true
|
||||
}
|
||||
|
||||
///| Stop reading the run in progress (the shell is closing).
|
||||
pub fn FaceUnlock::close(self : FaceUnlock) -> Unit {
|
||||
if self.fd >= 0 {
|
||||
@sys.close_fd(self.fd)
|
||||
self.fd = -1
|
||||
}
|
||||
self.queue.clear()
|
||||
}
|
||||
|
||||
///| Publish the face unlock tables (24: status, 25: faces) while a module imports `face-unlock`.
|
||||
/// Nothing runs until the module asks (`refresh`, when Settings opens on the Session tab).
|
||||
fn DesktopShell::publish_face_unlock(self : DesktopShell) -> Unit {
|
||||
if !self.any_cap("face-unlock") {
|
||||
return
|
||||
}
|
||||
let f = self.face
|
||||
f.poll()
|
||||
if !f.dirty {
|
||||
return
|
||||
}
|
||||
f.dirty = false
|
||||
let st = @wasm.Table::new()
|
||||
st.str(f.problem)
|
||||
st.str(f.howdy)
|
||||
st.str(f.message)
|
||||
st.int(if f.installed { 1 } else { 0 })
|
||||
st.int(if f.in_use() { 1 } else { 0 })
|
||||
st.int(if f.busy() { 1 } else { 0 })
|
||||
st.end_row()
|
||||
@wasm.publish(FaceStatus, st)
|
||||
let ft = @wasm.Table::new()
|
||||
for face in f.faces {
|
||||
ft.str(face.1)
|
||||
ft.str(face.2)
|
||||
ft.end_row()
|
||||
}
|
||||
@wasm.publish(Faces, ft)
|
||||
}
|
||||
|
||||
///| Whether a chandra-face run is in progress: the main loop keeps its frame pace meanwhile, so
|
||||
/// what it says shows up (it runs seconds, while the camera looks).
|
||||
pub fn DesktopShell::face_busy(self : DesktopShell) -> Bool {
|
||||
self.face.fd >= 0
|
||||
}
|
||||
@@ -297,6 +297,8 @@ pub(all) struct DesktopShell {
|
||||
mut handler_apps : Map[String, HandlerApp]?
|
||||
mut default_apps : Array[CategoryChoices]
|
||||
mut default_apps_dirty : Bool
|
||||
/// Face unlock (face.mbt): what `chandra-face` said, for Settings > Session.
|
||||
face : FaceUnlock
|
||||
/// The terminal chosen in the Apps tab (desktop id; "" for none), saved as state.edn :terminal.
|
||||
mut terminal : String
|
||||
/// Desktop ids of Terminal=true apps, started inside the terminal.
|
||||
@@ -452,6 +454,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
|
||||
handler_apps: None,
|
||||
default_apps: [],
|
||||
default_apps_dirty: true,
|
||||
face: FaceUnlock::new(),
|
||||
terminal: "",
|
||||
terminal_apps,
|
||||
desk_set: false,
|
||||
|
||||
@@ -700,6 +700,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
|
||||
if self.any_cap("default-apps") {
|
||||
self.publish_default_apps()
|
||||
}
|
||||
self.publish_face_unlock()
|
||||
if self.any_cap("screenshot") {
|
||||
@wasm.publish_screenshot(self.screenshot_state)
|
||||
}
|
||||
@@ -841,6 +842,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
|
||||
Some(SetSuspendAfter(m)) => self.set_power_timeouts(self.screen_off_min, m)
|
||||
Some(Shortcut(code)) => self.shortcut_request(code)
|
||||
Some(DefaultApp(code)) => self.default_app_request(code)
|
||||
Some(FaceUnlock(code)) => self.face.request(code)
|
||||
Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) }
|
||||
Some(Network(code, ssid, password)) => self.network_request(code, ssid, password)
|
||||
Some(SetInspector(on)) => self.set_inspecting(on)
|
||||
|
||||
@@ -331,6 +331,10 @@ pub(all) enum HostTable {
|
||||
AppChoices
|
||||
/// What can fill the desktop (s: name), served by `wallpaper.desktops`.
|
||||
Desktops
|
||||
/// Face unlock status (sssiii: problem howdy message installed in-use busy; one row).
|
||||
FaceStatus
|
||||
/// Enrolled faces (ss: label added).
|
||||
Faces
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -359,6 +363,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
|
||||
AppCategories => 11U
|
||||
AppChoices => 12U
|
||||
Desktops => 20U
|
||||
FaceStatus => 24U
|
||||
Faces => 25U
|
||||
}
|
||||
// Most tables are republished every frame unchanged: skip the copy into the host then.
|
||||
let slot = id.reinterpret_as_int()
|
||||
@@ -446,6 +452,9 @@ pub(all) enum HostRequest {
|
||||
ReloadSession
|
||||
/// The wallpaper capability's `set-desktop`: an index into the Desktops table.
|
||||
SetDesktop(Int)
|
||||
/// The face-unlock capability: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop /
|
||||
/// start using it for the password dialog and sudo.
|
||||
FaceUnlock(Int)
|
||||
} derive(Eq, Debug)
|
||||
|
||||
///|
|
||||
@@ -472,6 +481,7 @@ pub fn next_request() -> HostRequest? {
|
||||
Some(DefaultApp(code)) => Some(DefaultApp(code))
|
||||
Some(ReloadSession) => Some(ReloadSession)
|
||||
Some(SetDesktop(i)) => Some(SetDesktop(i))
|
||||
Some(FaceUnlock(i)) => Some(FaceUnlock(i))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -739,6 +739,10 @@ pub(all) enum HostTable {
|
||||
AppChoices
|
||||
/// What can fill the desktop (s: name), served by `wallpaper.desktops`.
|
||||
Desktops
|
||||
/// Face unlock status (sssiii: problem howdy message installed in-use busy; one row).
|
||||
FaceStatus
|
||||
/// Enrolled faces (ss: label added).
|
||||
Faces
|
||||
}
|
||||
|
||||
///| Publish `t` as the data behind `which` for every module's next call.
|
||||
@@ -758,6 +762,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
|
||||
AppCategories => 11
|
||||
AppChoices => 12
|
||||
Desktops => 20
|
||||
FaceStatus => 24
|
||||
Faces => 25
|
||||
}
|
||||
let out : Array[Byte] = []
|
||||
for k = 0; k < 4; k = k + 1 {
|
||||
@@ -844,6 +850,9 @@ pub(all) enum HostRequest {
|
||||
ReloadSession
|
||||
/// The wallpaper capability's `set-desktop`: an index into the Desktops table.
|
||||
SetDesktop(Int)
|
||||
/// The face-unlock capability: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop /
|
||||
/// start using it for the password dialog and sudo.
|
||||
FaceUnlock(Int)
|
||||
} derive(Eq, Debug)
|
||||
|
||||
///|
|
||||
@@ -886,6 +895,7 @@ pub fn next_request() -> HostRequest? {
|
||||
18 => Some(Shortcut(c_host_req_int()))
|
||||
19 => Some(DefaultApp(c_host_req_int()))
|
||||
40 => Some(SetDesktop(c_host_req_int()))
|
||||
44 => Some(FaceUnlock(c_host_req_int()))
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,8 @@ enum {
|
||||
K_NET_SET_AIRPLANE,
|
||||
K_SC_LIST, K_SC_CAPTURE, K_SC_CANCEL, K_SC_RESET, K_SC_RESET_ALL,
|
||||
K_DA_CATS, K_DA_APPS, K_DA_SET, K_DA_REFRESH,
|
||||
K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP
|
||||
K_DESKTOPS, K_DESKTOP_CUR, K_SET_DESKTOP,
|
||||
K_FU_STATUS, K_FU_FACES, K_FU_ENROLL, K_FU_REMOVE, K_FU_SET_IN_USE, K_FU_REFRESH
|
||||
};
|
||||
typedef struct Env { Inst *inst; int kind; } Env;
|
||||
|
||||
@@ -75,7 +76,7 @@ typedef struct Env { Inst *inst; int kind; } Env;
|
||||
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS,
|
||||
T_NET_STATUS, T_NET_NETWORKS, T_SHORTCUTS, T_APP_CATS, T_APP_CHOICES,
|
||||
/* fixed numbers from here (wit/host/plasmoids.wit publish-table) */
|
||||
T_DESKTOPS = 20, T_N = 32 };
|
||||
T_DESKTOPS = 20, T_FACE_STATUS = 24, T_FACES = 25, T_N = 32 };
|
||||
typedef struct { uint8_t *data; size_t len; } Blob;
|
||||
static Blob tables[T_N];
|
||||
static int32_t host_ints[24] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
|
||||
@@ -387,6 +388,15 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
|
||||
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[20]);
|
||||
break;
|
||||
case K_SET_DESKTOP: push_req(40, a0, NULL); break;
|
||||
/* Face unlock: status from table 24 (problem howdy message installed in-use busy), faces from
|
||||
* table 25 (label added); request 44 is a face index to remove, or -1 refresh, -2 enroll,
|
||||
* -3 / -4 stop / start using it. */
|
||||
case K_FU_STATUS: build_record(in, T_FACE_STATUS, "sssbbb", a0); break;
|
||||
case K_FU_FACES: build_list(in, T_FACES, "ss", a0); break;
|
||||
case K_FU_ENROLL: push_req(44, -2, NULL); break;
|
||||
case K_FU_REMOVE: if (a0 >= 0 && a0 < 1000) push_req(44, a0, NULL); break;
|
||||
case K_FU_SET_IN_USE: push_req(44, a0 ? -4 : -3, NULL); break;
|
||||
case K_FU_REFRESH: push_req(44, -1, NULL); break;
|
||||
case K_SESSION_SET: push_req(a1 ? 11 : 10, a0, NULL); break; /* 10 off, 11 on */
|
||||
/* Request 12 carries the screenshot code: 0-3 take, 10-12 record, 20 stop, 30/31 pointer. */
|
||||
case K_SHOT_TAKE: if (a0 >= 0 && a0 <= 3) push_req(12, a0, NULL); break;
|
||||
@@ -604,6 +614,12 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
|
||||
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "desktops")) return K_DESKTOPS;
|
||||
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-desktop")) return K_DESKTOP_CUR;
|
||||
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "set-desktop")) return K_SET_DESKTOP;
|
||||
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "status")) return K_FU_STATUS;
|
||||
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "faces")) return K_FU_FACES;
|
||||
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "enroll")) return K_FU_ENROLL;
|
||||
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "remove")) return K_FU_REMOVE;
|
||||
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "set-in-use")) return K_FU_SET_IN_USE;
|
||||
if (!strcmp(iface, "face-unlock") && !strcmp(fn, "refresh")) return K_FU_REFRESH;
|
||||
if (!strcmp(iface, "session-settings") && !strcmp(fn, "settings")) return K_SESSION_SETTINGS;
|
||||
if (!strcmp(iface, "session-settings") && !strcmp(fn, "is-on")) return K_SESSION_IS_ON;
|
||||
if (!strcmp(iface, "session-settings") && !strcmp(fn, "set-setting")) return K_SESSION_SET;
|
||||
|
||||
@@ -243,6 +243,7 @@ test "the settings module's Panel tab lists host modules and asks to load, move,
|
||||
ignore(p.on_event(true, PointerDown(20, 190))) // add the moon
|
||||
ignore(p.on_event(true, PointerDown(160, 285))) // browse
|
||||
assert_eq(drain(), [
|
||||
FaceUnlock(-1), // opening on the Session tab reads the face unlock status
|
||||
MoveInstance("w1", 1),
|
||||
UnloadInstance("w2"),
|
||||
LoadModule("/m/moon-disc.wasm"),
|
||||
|
||||
@@ -20,6 +20,9 @@ compositor in the shell layer, above every window and client menu.
|
||||
- **PAM.** The dialog follows whatever PAM asks through polkit's helper: password prompts, visible
|
||||
prompts (a one-time code), information (a fingerprint reader asking for a finger) and errors
|
||||
(faillock's "account is locked"). A wrong password shakes the card, says so, and starts again.
|
||||
Face unlock (pam_chandra_face.so, or Howdy's pam_howdy.so) gets its own row: "Looking for your
|
||||
face…" while the camera looks (the password can be typed meanwhile), then "Face recognized" or
|
||||
why not, before the password prompt; see [face-unlock.md](face-unlock.md).
|
||||
While PAM checks, the field is locked and a spinner shows.
|
||||
- **Safety.** While the dialog is up no client has keyboard focus, input goes to the dialog only,
|
||||
and client popups are hidden, so nothing can draw over it or read the keys. The password is kept
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
# Face unlock
|
||||
|
||||
Chandra can recognize your face instead of asking for your password, in the style of
|
||||
[Howdy](https://github.com/boltgolt/howdy): a PAM module that looks through the camera when PAM
|
||||
asks for authentication, and lets PAM go on to the password when it doesn't see you. It works
|
||||
wherever PAM is used: Chandra's password dialog (polkit, run0, pkexec), sudo in a terminal, and
|
||||
any other service you add it to.
|
||||
|
||||

|
||||
|
||||
## Setting it up
|
||||
|
||||
```sh
|
||||
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,
|
||||
`python-opencv` on Arch), a C compiler and the PAM headers (`libpam0g-dev` / `pam-devel`). 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.
|
||||
|
||||
Then in **Settings > Session > Face unlock**:
|
||||
|
||||
- **Add a face…** asks for your password (in the password dialog), then looks through the
|
||||
camera for about ten seconds and keeps five views of your face. Add another face for glasses,
|
||||
a different light, or a second camera position.
|
||||
- **Use my face for passwords** puts the face first in the PAM services `polkit-1` (the password
|
||||
dialog) and `sudo`, after the password. Turning it off takes it out again.
|
||||
- **Remove** (click twice) forgets one face.
|
||||
|
||||
Everything Settings does runs `chandra-face` through run0 (or pkexec), so each change asks for
|
||||
an administrator's password first. From a terminal:
|
||||
|
||||
```sh
|
||||
chandra-face enroll --label "Desk" # add a face
|
||||
chandra-face list
|
||||
chandra-face test # look now and print the similarity scores
|
||||
chandra-face remove 2
|
||||
chandra-face clear # forget every face
|
||||
chandra-face pam enable polkit-1 sudo
|
||||
chandra-face pam disable # polkit-1 and sudo by default
|
||||
chandra-face status # what is set up, what is missing
|
||||
just uninstall-face # takes it out of every PAM service first
|
||||
```
|
||||
|
||||
## In the password dialog
|
||||
|
||||
While the face module looks, the dialog shows a face row with a sweeping ring: "Looking for
|
||||
your face…". The password field stays usable: what you type, and Enter, wait until PAM asks for
|
||||
the password, so you can type it right away if you know the camera won't see you. When the face
|
||||
matches, the row says "Face recognized" and the dialog closes. When it doesn't ("Face not
|
||||
recognized", "The camera picture is too dark", "No face in view"), the row says why and the
|
||||
password prompt comes up as usual. After a wrong password the next attempt tries the face again.
|
||||
|
||||
The dialog understands Howdy's messages too ("Attempting facial authentication", "Identified face
|
||||
as…", "Failure, timeout reached", "Face detection image too dark"), so if you already use Howdy,
|
||||
keep `pam_howdy.so` and the dialog shows its progress the same way; Settings says which PAM
|
||||
services use Howdy. Faces you enrolled with Howdy are managed with `sudo howdy add`/`remove`.
|
||||
|
||||
## PAM
|
||||
|
||||
`chandra-face pam enable SERVICE` adds this line before the service's first `auth` (or
|
||||
`@include`) line in `/etc/pam.d/SERVICE` (copying a vendor file from `/usr/lib/pam.d` first, and
|
||||
keeping the original as `SERVICE.chandra-face.bak`):
|
||||
|
||||
```
|
||||
-auth sufficient pam_chandra_face.so # added by chandra-face
|
||||
```
|
||||
|
||||
`sufficient` means a match ends the auth stack with success, and anything else (no match, no
|
||||
camera, nothing enrolled, an error) is ignored, so the next line, your password, always still
|
||||
works. The leading `-` makes PAM skip the line quietly if the module is ever uninstalled. To edit
|
||||
by hand instead, put that line at the top of the auth section; module options:
|
||||
|
||||
| option | meaning |
|
||||
| --- | --- |
|
||||
| `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`) |
|
||||
| `helper=PATH`, `python=PATH` | another chandra-face / Python (default `/usr/local/lib/chandra/chandra-face`, `/usr/bin/python3`) |
|
||||
| `quiet` | don't send the "looking" / "not recognized" messages |
|
||||
| `debug` | the helper's stderr goes to the application's stderr; skipped helpers are logged |
|
||||
|
||||
The module skips the face (quietly) for remote sessions (`PAM_RHOST`, or `SSH_CONNECTION` in the
|
||||
environment), when the laptop lid is closed, and when the user has no face enrolled. It is not a
|
||||
good idea for `login` or a display manager on the first login: a face doesn't unlock the GNOME
|
||||
keyring or KWallet, which need the password.
|
||||
|
||||
## Settings: /etc/chandra/face.conf
|
||||
|
||||
```ini
|
||||
[face]
|
||||
enabled = yes # no: the module stays quiet and PAM goes straight on to the password
|
||||
device = /dev/video0 # the camera; an IR camera is often /dev/video2
|
||||
timeout = 4 # seconds to look before giving up
|
||||
threshold = 0.42 # SFace cosine similarity needed (OpenCV suggests 0.363; higher is stricter)
|
||||
matches = 2 # frames that must match
|
||||
dark = 25 # skip frames darker than this (IR emitters take a moment to light up)
|
||||
min_face = 80 # smallest face to use, in pixels
|
||||
require_ir = no # yes: accept only grey (infrared) frames
|
||||
enroll_frames = 5
|
||||
store = /var/lib/chandra-face
|
||||
models = /usr/local/share/chandra/face
|
||||
```
|
||||
|
||||
`chandra-face test` prints the score of each frame, which helps pick a threshold for your camera.
|
||||
|
||||
## How it works
|
||||
|
||||
- `face/pam_chandra_face.c` (the PAM module): forks `python3 -I chandra-face compare --user USER`
|
||||
as root with a clean environment (stdin and stderr on /dev/null), forwards each line it prints
|
||||
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
|
||||
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
|
||||
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
|
||||
another user re-run themselves through run0 (or pkexec when systemd isn't PID 1).
|
||||
- The compositor (`compositor/shell/face.mbt`) runs `chandra-face status` as you to fill the
|
||||
Settings rows (labels and dates only), and the changes on a socket so it never waits on them;
|
||||
the session-settings module reaches it through the `face-unlock` capability
|
||||
(`wit/capabilities.wit`). The password dialog (`compositor/polkit/dialog.mbt`, `face_message`)
|
||||
turns the module's messages into the face row.
|
||||
|
||||
## Privacy and security
|
||||
|
||||
- **Nothing leaves the machine.** Camera frames are only held in memory by the root helper for the
|
||||
few seconds it looks; they are never written to disk or sent anywhere. The only network access
|
||||
is the one-time model download.
|
||||
- **What is stored**: per user, `/var/lib/chandra-face/USER/faces.json` (root, mode 0600) holds the
|
||||
embeddings (feature vectors, not pictures) and `faces.list` (0644) only the labels and dates
|
||||
that Settings shows. The helper refuses a store, config or model that is a symlink, not root's,
|
||||
or writable by group or others.
|
||||
- **Changing faces needs an administrator**: enrolling runs as root after polkit's password
|
||||
check, so a program running as you can't quietly add someone else's face to your account.
|
||||
- **2D face recognition can be fooled.** A good photo or video of you held up to a normal (RGB)
|
||||
webcam may be accepted: there is no liveness or depth check. An infrared camera (most "Windows
|
||||
Hello" laptops have one) is much harder to fool with a photo or a screen; set `device` to it
|
||||
and `require_ir = yes`. Twins and close relatives may also be accepted. Treat face unlock as a
|
||||
convenience that is weaker than a good password; don't use it where that matters (it is never
|
||||
added to `login` or SSH by Settings).
|
||||
- **The password always works**: the module is `sufficient`, skipped when it fails or is missing,
|
||||
and killed if it hangs.
|
||||
|
||||
## Tests
|
||||
|
||||
`just test-face` runs `face/test_face.py` with a fake camera (a folder of PGM frames) and a
|
||||
fake recognizer, so it needs no camera, OpenCV or models: enrollment, recognition, the reasons
|
||||
for failing, permission checks on the store, PAM file editing (including Debian's
|
||||
`@include common-auth`). `just test-face --pam` (as root, with `pamtester`) also builds the PAM
|
||||
module and runs it through a throwaway PAM service: a match succeeds, a stranger falls through,
|
||||
remote and unenrolled users are skipped quietly, a hanging helper is killed, a writable helper is
|
||||
not run. With `CHANDRA_FACE_MODELS=DIR` the OpenCV backend is checked on frames without a face.
|
||||
|
||||
On the compositor side, `compositor/polkit/polkit_test.mbt` covers the message parsing and the
|
||||
dialog's face states, `compositor/host/auth_test.mbt` drives the dialog through a mock helper
|
||||
(`CHANDRA_AUTH_SHOTS=dir` saves `14-face-scanning.png` and `15-face-failed.png`), and
|
||||
`compositor/host/face_test.mbt` drives Settings > Session against a fake chandra-face.
|
||||
|
||||
Not verified here: a real camera (frames came from image files; with OpenCV's real models, a
|
||||
rotated and rescaled photo of the enrolled face scored 0.92 and a different person -0.18), and
|
||||
run0/pkexec elevation from Settings on a real systemd session.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 105 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 105 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 118 KiB |
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)
|
||||
@@ -295,6 +295,7 @@ impl chandra::host::plasmoids::Host for State {
|
||||
Req::Shortcut(code) => R::Shortcut(code),
|
||||
Req::DefaultApp(code) => R::DefaultApp(code),
|
||||
Req::SetDesktop(i) => R::SetDesktop(i),
|
||||
Req::FaceUnlock(code) => R::FaceUnlock(code),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,9 @@ pub enum Req {
|
||||
DefaultApp(i32),
|
||||
/// `wallpaper.set-desktop`: an index into the desktops table.
|
||||
SetDesktop(i32),
|
||||
/// A face-unlock request: a face index removes it; -1 refresh, -2 enroll, -3 / -4 stop /
|
||||
/// start using it.
|
||||
FaceUnlock(i32),
|
||||
}
|
||||
|
||||
pub const T_APPS: usize = 0;
|
||||
@@ -96,11 +99,15 @@ pub const T_APP_CATS: usize = 11;
|
||||
pub const T_APP_CHOICES: usize = 12;
|
||||
/// What can fill the desktop (s): name, behind `wallpaper.desktops`.
|
||||
pub const T_DESKTOPS: usize = 20;
|
||||
/// Face unlock status, one row (sssiii): problem howdy message installed in-use busy.
|
||||
pub const T_FACE_STATUS: usize = 24;
|
||||
/// Enrolled faces (ss): label added.
|
||||
pub const T_FACES: usize = 25;
|
||||
|
||||
/// Host data every module reads from, shared by all loaded modules.
|
||||
#[derive(Default)]
|
||||
pub struct Shared {
|
||||
pub tables: [Vec<u8>; 21],
|
||||
pub tables: [Vec<u8>; 26],
|
||||
pub layout_mode: i32,
|
||||
pub wallpaper: i32,
|
||||
/// What fills the desktop (an index into the desktops table).
|
||||
@@ -366,6 +373,51 @@ impl d::wallpaper::Host for PState {
|
||||
}
|
||||
}
|
||||
|
||||
impl d::face_unlock::Host for PState {
|
||||
fn status(&mut self) -> d::face_unlock::FaceStatus {
|
||||
let rows = self.rows(T_FACE_STATUS, "sssiii");
|
||||
match rows.first() {
|
||||
Some(r) if r.len() == 6 => d::face_unlock::FaceStatus {
|
||||
problem: s(&r[0]),
|
||||
howdy: s(&r[1]),
|
||||
message: s(&r[2]),
|
||||
installed: i(&r[3]) != 0,
|
||||
in_use: i(&r[4]) != 0,
|
||||
busy: i(&r[5]) != 0,
|
||||
},
|
||||
_ => d::face_unlock::FaceStatus {
|
||||
problem: String::new(),
|
||||
howdy: String::new(),
|
||||
message: String::new(),
|
||||
installed: false,
|
||||
in_use: false,
|
||||
busy: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
fn faces(&mut self) -> Vec<d::face_unlock::Face> {
|
||||
self.rows(T_FACES, "ss")
|
||||
.iter()
|
||||
.filter(|r| r.len() == 2)
|
||||
.map(|r| d::face_unlock::Face { label: s(&r[0]), added: s(&r[1]) })
|
||||
.collect()
|
||||
}
|
||||
fn enroll(&mut self) {
|
||||
self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(-2));
|
||||
}
|
||||
fn remove(&mut self, index: u32) {
|
||||
if index < 1000 {
|
||||
self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(index as i32));
|
||||
}
|
||||
}
|
||||
fn set_in_use(&mut self, on: bool) {
|
||||
self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(if on { -4 } else { -3 }));
|
||||
}
|
||||
fn refresh(&mut self) {
|
||||
self.shared.borrow_mut().requests.push_back(Req::FaceUnlock(-1));
|
||||
}
|
||||
}
|
||||
|
||||
impl d::power::Host for PState {
|
||||
fn screen_off_minutes(&mut self) -> u32 {
|
||||
self.shared.borrow().screen_off_min
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
Face unlock (docs/face-unlock.md): the session user's enrolled faces and whether the password
|
||||
dialog and sudo try the face first. Every change runs chandra-face through run0 or pkexec, so
|
||||
polkit asks for an administrator's password before anything happens; the module never sees a
|
||||
camera picture or any face data, only labels.
|
||||
@@ -0,0 +1,46 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
|
||||
///|
|
||||
fn wasmImportStatus(p0 : Int) = "chandra:desktop/face-unlock@0.1.0" "status"
|
||||
|
||||
///|
|
||||
fn wasmImportFaces(p0 : Int) = "chandra:desktop/face-unlock@0.1.0" "faces"
|
||||
|
||||
///|
|
||||
fn wasmImportEnroll() = "chandra:desktop/face-unlock@0.1.0" "enroll"
|
||||
|
||||
///|
|
||||
fn wasmImportRemove(p0 : Int) = "chandra:desktop/face-unlock@0.1.0" "remove"
|
||||
|
||||
///|
|
||||
fn wasmImportSetInUse(p0 : Int) = "chandra:desktop/face-unlock@0.1.0" "set-in-use"
|
||||
|
||||
///|
|
||||
fn wasmImportRefresh() = "chandra:desktop/face-unlock@0.1.0" "refresh"
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||
#|(func (param i32) (result i32) (local i32)
|
||||
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||
#| local.get 1)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
|
||||
#|(func (param i32) (result i32) local.get 0 i32.load)
|
||||
|
||||
///|
|
||||
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
|
||||
#|(func (param i32) (param i32) (result i32)
|
||||
#| local.get 0
|
||||
#| local.get 1 call $moonbit.init_array16
|
||||
#| local.get 0)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
warnings = "-44"
|
||||
@@ -0,0 +1,36 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "chandra/desktop/interface/chandra/desktop/face-unlock"
|
||||
|
||||
// Values
|
||||
pub fn enroll() -> Unit
|
||||
|
||||
pub fn faces() -> Array[Face]
|
||||
|
||||
pub fn refresh() -> Unit
|
||||
|
||||
pub fn remove(UInt32) -> Unit
|
||||
|
||||
pub fn set_in_use(Bool) -> Unit
|
||||
|
||||
pub fn status() -> FaceStatus
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
pub(all) struct Face {
|
||||
label : String
|
||||
added : String
|
||||
}
|
||||
|
||||
pub(all) struct FaceStatus {
|
||||
problem : String
|
||||
howdy : String
|
||||
message : String
|
||||
installed : Bool
|
||||
in_use : Bool
|
||||
busy : Bool
|
||||
}
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,77 @@
|
||||
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||
///|
|
||||
pub(all) struct FaceStatus {
|
||||
problem : String; howdy : String; message : String; installed : Bool; in_use : Bool; busy : Bool
|
||||
}
|
||||
///|
|
||||
pub(all) struct Face {
|
||||
label : String; added : String
|
||||
}
|
||||
///|
|
||||
pub fn status() -> FaceStatus {
|
||||
|
||||
let return_area = mbt_ffi_malloc(28)
|
||||
wasmImportStatus(return_area);
|
||||
|
||||
let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 0), mbt_ffi_load32((return_area) + 4))
|
||||
|
||||
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12))
|
||||
|
||||
let result1 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 16), mbt_ffi_load32((return_area) + 20))
|
||||
let ret = FaceStatus::{problem : result, howdy : result0, message : result1, installed : (mbt_ffi_load8_u((return_area) + 24) != 0), in_use : (mbt_ffi_load8_u((return_area) + 25) != 0), busy : (mbt_ffi_load8_u((return_area) + 26) != 0)}
|
||||
mbt_ffi_free(return_area)
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
/// The enrolled faces, oldest first.
|
||||
pub fn faces() -> Array[Face] {
|
||||
|
||||
let return_area = mbt_ffi_malloc(8)
|
||||
wasmImportFaces(return_area);
|
||||
|
||||
let array : Array[Face] = [];
|
||||
for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 {
|
||||
let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 16)
|
||||
|
||||
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
|
||||
|
||||
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 8), mbt_ffi_load32((iter_base) + 12))
|
||||
|
||||
array.push(Face::{label : result, added : result0})
|
||||
}
|
||||
mbt_ffi_free(mbt_ffi_load32((return_area) + 0))
|
||||
let ret = array
|
||||
mbt_ffi_free(return_area)
|
||||
return ret
|
||||
|
||||
}
|
||||
///|
|
||||
/// Add a face: after the password, the camera looks for about ten seconds.
|
||||
pub fn enroll() -> Unit {
|
||||
|
||||
wasmImportEnroll();
|
||||
|
||||
}
|
||||
///|
|
||||
/// Forget face `index` of `faces`.
|
||||
pub fn remove(index : UInt) -> Unit {
|
||||
|
||||
wasmImportRemove((index).reinterpret_as_int());
|
||||
|
||||
}
|
||||
///|
|
||||
/// Try the face first in the password dialog and sudo, or stop.
|
||||
pub fn set_in_use(on : Bool) -> Unit {
|
||||
|
||||
wasmImportSetInUse((if on { 1 } else { 0 }));
|
||||
|
||||
}
|
||||
///|
|
||||
/// Read the status and the faces again.
|
||||
pub fn refresh() -> Unit {
|
||||
|
||||
wasmImportRefresh();
|
||||
|
||||
}
|
||||
|
||||
@@ -122,6 +122,7 @@ pub(all) enum Request {
|
||||
ReloadSession
|
||||
DefaultApp(Int32)
|
||||
SetDesktop(Int32)
|
||||
FaceUnlock(Int32)
|
||||
}
|
||||
|
||||
pub(all) struct SettingChange {
|
||||
|
||||
@@ -62,6 +62,7 @@ pub(all) enum Request {
|
||||
ReloadSession
|
||||
DefaultApp(Int)
|
||||
SetDesktop(Int)
|
||||
FaceUnlock(Int)
|
||||
}
|
||||
///|
|
||||
/// A native file-chooser dialog (zenity on the host session) for "Add widget".
|
||||
@@ -624,6 +625,10 @@ pub fn next_request() -> Request? {
|
||||
|
||||
Request::SetDesktop(mbt_ffi_load32((return_area) + 8))
|
||||
}
|
||||
20 => {
|
||||
|
||||
Request::FaceUnlock(mbt_ffi_load32((return_area) + 8))
|
||||
}
|
||||
_ => panic()
|
||||
}
|
||||
|
||||
|
||||
@@ -118,6 +118,18 @@ reload *name:
|
||||
uninstall:
|
||||
scripts/as-root python3 "{{justfile_directory()}}/session/install.py" --remove
|
||||
|
||||
# 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.
|
||||
install-face *args:
|
||||
scripts/as-root python3 "{{justfile_directory()}}/face/install.py" {{args}}
|
||||
|
||||
# Remove face unlock (from every PAM service first). `just uninstall-face --purge` also deletes the enrolled faces.
|
||||
uninstall-face *args:
|
||||
scripts/as-root python3 "{{justfile_directory()}}/face/install.py" --remove {{args}}
|
||||
|
||||
# Face unlock tests (fake camera; add --pam as root with pamtester to test the PAM module too).
|
||||
test-face *args:
|
||||
python3 face/test_face.py {{args}}
|
||||
|
||||
# Old names, kept so existing habits and scripts still work.
|
||||
[private]
|
||||
install-session:
|
||||
|
||||
+4
-1
@@ -36,6 +36,9 @@ if command -v wasmtime >/dev/null; then
|
||||
done
|
||||
fi
|
||||
|
||||
step "face unlock (chandra-face with a fake camera; the PAM module through pamtester as root)"
|
||||
python3 face/test_face.py --pam
|
||||
|
||||
step "host integration tests (jco + Node)"
|
||||
(cd host && npm test)
|
||||
|
||||
@@ -49,5 +52,5 @@ if [ -d "$WASMER/lib" ]; then
|
||||
fi
|
||||
XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 \
|
||||
moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/wasm \
|
||||
compositor/network compositor/portal compositor/host
|
||||
compositor/network compositor/portal compositor/polkit compositor/host
|
||||
moon build --target native --warn-list -a compositor/bin
|
||||
@@ -263,6 +263,7 @@ fn request_val(r : @wasm.HostRequest) -> @wt.Val {
|
||||
ReloadSession => Variant("reload-session", None)
|
||||
DefaultApp(n) => Variant("default-app", Some(S32(n)))
|
||||
SetDesktop(n) => Variant("set-desktop", Some(S32(n)))
|
||||
FaceUnlock(n) => Variant("face-unlock", Some(S32(n)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -334,3 +334,41 @@ interface network {
|
||||
set-wifi-enabled: func(on: bool);
|
||||
set-airplane-mode: func(on: bool);
|
||||
}
|
||||
|
||||
/// Face unlock (docs/face-unlock.md): the session user's enrolled faces and whether the password
|
||||
/// dialog and sudo try the face first. Every change runs chandra-face through run0 or pkexec, so
|
||||
/// polkit asks for an administrator's password before anything happens; the module never sees a
|
||||
/// camera picture or any face data, only labels.
|
||||
interface face-unlock {
|
||||
record face-status {
|
||||
/// Why face unlock can't work yet ("python3-opencv is not installed"), or empty.
|
||||
problem: string,
|
||||
/// PAM services that use Howdy's pam_howdy.so, comma-separated, or empty.
|
||||
howdy: string,
|
||||
/// What the running change said last ("Look at the camera… 3/5"), or how the last one
|
||||
/// ended; empty when none ran.
|
||||
message: string,
|
||||
/// chandra-face is installed (`just install-face`).
|
||||
installed: bool,
|
||||
/// The password dialog (PAM service polkit-1) and sudo try the face first.
|
||||
in-use: bool,
|
||||
/// A change (enroll, remove, set-in-use) is running.
|
||||
busy: bool,
|
||||
}
|
||||
record face {
|
||||
label: string,
|
||||
/// When it was enrolled (YYYY-MM-DD).
|
||||
added: string,
|
||||
}
|
||||
status: func() -> face-status;
|
||||
/// The enrolled faces, oldest first.
|
||||
faces: func() -> list<face>;
|
||||
/// Add a face: after the password, the camera looks for about ten seconds.
|
||||
enroll: func();
|
||||
/// Forget face `index` of `faces`.
|
||||
remove: func(index: u32);
|
||||
/// Try the face first in the password dialog and sudo, or stop.
|
||||
set-in-use: func(on: bool);
|
||||
/// Read the status and the faces again.
|
||||
refresh: func();
|
||||
}
|
||||
@@ -69,7 +69,8 @@ interface plasmoids {
|
||||
/// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved), 10 keyboard
|
||||
/// shortcuts (ssssi: name binding default-binding conflict capturing), 11 default-app
|
||||
/// categories (sss: name current missing), 12 default-app choices (issii: category id name icon current),
|
||||
/// 20 desktops (s: name) served by `wallpaper.desktops`.
|
||||
/// 20 desktops (s: name) served by `wallpaper.desktops`, 24 face unlock status (sssiii: problem howdy
|
||||
/// message installed in-use busy; one row), 25 enrolled faces (ss: label added).
|
||||
publish-table: func(which: u32, rows: list<u8>);
|
||||
/// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on.
|
||||
publish-state: func(layout-mode: s32, inspector-on: bool);
|
||||
@@ -161,6 +162,9 @@ interface plasmoids {
|
||||
default-app(s32),
|
||||
/// The wallpaper capability's `set-desktop`: an index into the desktops table.
|
||||
set-desktop(s32),
|
||||
/// The face-unlock capability: an index removes that face; -1 reads the status again, -2
|
||||
/// enrolls a face, -3 / -4 stop / start using it for the password dialog and sudo.
|
||||
face-unlock(s32),
|
||||
}
|
||||
/// The next pending request, oldest first.
|
||||
next-request: func() -> option<request>;
|
||||
|
||||
+4
-2
@@ -101,13 +101,14 @@ world plasmoid-host {
|
||||
import network;
|
||||
import shortcuts;
|
||||
import default-apps;
|
||||
import face-unlock;
|
||||
export plasmoid;
|
||||
}
|
||||
|
||||
/// The settings module: session switches (restore, window places, dark mode), the wallpaper, the
|
||||
/// panel's modules (load, unload, browse; the panel menu's "Modules..." opens that tab), and power
|
||||
/// (idle timeouts, battery, suspend / restart / power off), keyboard shortcuts (rebind, reset) and
|
||||
/// default apps (browser, email, files, terminal, editor, viewers and players).
|
||||
/// (idle timeouts, battery, suspend / restart / power off), keyboard shortcuts (rebind, reset),
|
||||
/// default apps (browser, email, files, terminal, editor, viewers and players) and face unlock.
|
||||
world session-settings-widget {
|
||||
include widget;
|
||||
import session-settings;
|
||||
@@ -117,6 +118,7 @@ world session-settings-widget {
|
||||
import system;
|
||||
import shortcuts;
|
||||
import default-apps;
|
||||
import face-unlock;
|
||||
}
|
||||
|
||||
/// Screenshot and screen recording launcher.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
The settings module: session switches (restore, window places, dark mode), the wallpaper, the
|
||||
panel's modules (load, unload, browse; the panel menu's "Modules..." opens that tab), and power
|
||||
(idle timeouts, battery, suspend / restart / power off), keyboard shortcuts (rebind, reset) and
|
||||
default apps (browser, email, files, terminal, editor, viewers and players).
|
||||
(idle timeouts, battery, suspend / restart / power off), keyboard shortcuts (rebind, reset),
|
||||
default apps (browser, email, files, terminal, editor, viewers and players) and face unlock.
|
||||
Reference in new issue
Block a user