Commit graph fingerprintd/tests
Author SHA1 Message Date
93d7f96a63 Drop two fields nobody needed: session was a no-op, and no-unlock is the finger
Jorijn caught both.

`session` declared nothing. The FingerMatched signal is emitted for every
matched finger unconditionally -- it never consulted the config -- so a
`session` line was a rule the format invited you to write that did exactly
nothing. Announcing every finger is the right default anyway: a session agent
should not need a root-owned file to declare its interest in a signal it is
free to ignore. The column is gone.

Which leaves the config for the two things that really do need the daemon, and
with `session` gone the verdict column had no partner left to vary against. It
read as a property of the finger while being a property of the attempt, so it
is now written as what it is:

    <finger>  [no-unlock]  [absolute command...]

no-unlock says the finger never unlocks; a command is what root runs. At least
one is required, because a finger listed alone says nothing the signal does not
already say -- and that is a parse error rather than a silently useless line.

The example config now also states plainly what no-unlock is not. It is a panic
button, not deniability: the rejection it fabricates comes back in milliseconds
where a real one takes about three seconds, the journal records that the finger
actually matched, the file names the finger in plain text, and the finger still
shows as enrolled. Both of those weaknesses are real and neither is fixed here.
2026-09-05 05:23:40 +02:00
928fe1482e Give a finger a meaning beyond "it was you"
The trustlet has always reported WHICH finger matched and the daemon only ever
used it to answer yes. A table in /etc/fingerprintd/actions.conf now gives each
finger a meaning: run a command as root, tell the user's session, or report
no-match while doing one of those anyway -- which is duress, where the phone
should look like it simply did not recognise the finger.

Two rules shaped the design.

Root does not launch applications. The daemon has no session bus, no display
and no user environment, so a `session` rule carries no command at all: the
daemon emits net.catcrafts.Fingerprintd1.FingerMatched(finger, uid) and an
agent in the user's own session decides what that means from the user's own
configuration. The only commands in the file are ones root is meant to run.

Which makes the file a root shell, and the parser treats it as one. It is
refused outright unless root owns it and nobody else can write it, group
included. A malformed line rejects the WHOLE file rather than being skipped:
applying the prefix would leave a policy nobody wrote, and the missing half
could be the one that mattered. That property is tested, and the test caught it
being false the first time -- rules accumulated before the bad line survived
the rejection.

A system command must be an absolute path, because resolving a bare name
through PATH makes what root runs depend on an environment this daemon does not
control. It is double-forked with a scrubbed environment so an action may
outlive the daemon (a reboot) without ever stalling the worker thread that is
the only thread allowed to touch the trustlet.

Ordering is deliberate: the verdict override happens before the client is told,
because that is the point of duress; the session signal and the root command
happen after, on the same principle that keeps the harvest and the save off the
unlock path.

No actions.conf ships. An example goes to /usr/share/doc, because shipping a
root shell nobody asked for is not a default.

Not yet exercised on hardware.
2026-09-05 05:12:41 +02:00
41e86f84f4 Delete a finger's template, not just its name
FF_CMD_TA_REMOVE, recovered the way AUTHENTICATE was: read the stub, read the
handler. The 0x2006 stub at 0xa15c is a bare `ldp w0, w1, [payload]`, so the
request is two u32s -- gid at +0, fid at +4 -- and the 0x2000 dispatcher
validates no length. Walking the jump table reproduces authenticate at 0xa180,
which is the address already on record, so the table read is sound.

Three preconditions, all the trustlet's own. The gid must be the ACTIVE group
(it compares against device+0x30, the field SET_ACTIVE_GROUP writes). The fid
must be non-zero: zero is not "remove all", it is an error the trustlet logs
and refuses. And the fid must be among the loaded templates, because it
removes by the SLOT INDEX it finds, not by id.

It persists: on a hit the trustlet formats ff_template_<gid>_<slot>.bin and
calls ff_file_delete, which arrives on our gpfile listener as an unlink -- so
this only works with the store served writable.

Proven harmlessly first. --probe-remove sends one command with no map
involvement, and a fid the group does not hold answers rc=-2 with the real
template untouched -- which is what established that both words are read where
we send them, before anything was deleted.

Then for real, through fprintd-delete: both 347202-byte containers and their
.bak companions unlinked, templates loaded 1 -> 0, and a re-enrolment
afterwards completed 20 stages with SAVE_DATA rc=0, so the store is consistent
after a removal rather than merely emptier.

The ordering the transcript shows is worth keeping: the group index is
rewritten and the RPMB anti-rollback counter bumped BEFORE each unlink. That
is precisely why an orderly removal leaves a valid store where restoring an
older container leaves a tampered one -- the counter has already moved past
it.

The delete reply now waits for the worker, because only that thread invokes
the trustlet and fprintd's Delete methods are synchronous. Names are dropped
before templates on purpose: a template that survives a failed removal is a
slot leak, while a name that survives a successful one keeps offering a finger
that can no longer match.
2026-09-05 04:27:14 +02:00
e03ce4ae5a UPDATE_TEMPLATE: the command stock learns with, and the field that was killing it
Stock rewrites the stored template on every successful press. Its post-match
loop is QUERY_FINGER_STATUS, CAPTURE_IMAGE, 0x1015 UPDATE_TEMPLATE while the
finger stays down, with no REPORT_EVENT in it -- so the matcher does not re-run
and the verdict cannot change. Forty-six of those against eighty-six captures in
one reference session, and the stored body measurably grows: 333278 bytes at
enrolment, 360822 at the next session's load, 371734 after one authentication
session. This daemon sent none of them.

The command shares REPORT_EVENT's event context. The stock wrapper memsets 732
bytes and writes six fields: a zero byte at +0x2a4, the scan-slot count, a zero
word, the count of frames folded so far in this press, a flags word of
0x00080000 with bit 6 set on the frame whose event was FingerTouched, and a zero
at +0x2d8. Declared length 0x2dc.

+0x2d8 is the one that matters, and it matters by staying zero. The dispatcher
stub reads it after the handler returns and only if it is non-zero does it read
+0x2dc and make that the response length. Every earlier attempt in this project
set both fields and varied the declared length across 0x2e0, 0x400 and 0x1000;
all of them answered -90, the trustlet gone, and the conclusion recorded was
"do not retry until a template is loaded". A loaded template was necessary but
not sufficient. The stock HAL sets neither field.

Measured on the device with two templates loaded and no finger: both branches
answer rc=0 and ENUMERATE still reports 2, so the app did not fault.

Those fields are little endian, assembled low-address-first by the handler. An
earlier reading called them big endian, off the bfi order, and was wrong.

Bit 6 selects which algorithm entry runs: clear takes libfp_template_x_update,
set takes the other, which also reads the scan-slot count.
2026-09-03 17:45:27 +02:00
fe6ad11951 Detect the finger at 1.5x the floor, not 2x -- catch the landing frame
Three loop changes have now failed to move quick-tap accuracy: the frame gap
from 500 to 40 ms, the rising edge from two matcher runs to one (3x cheaper
frame), and waking on the touch edge instead of polling. All three left every
press at exactly one frame and the rate at 2 of 10. The transcript says why:

    frame 20 @ 4005ms: metric=247  irq=1        finger landing, below threshold
    frame 21 @ 4399ms: metric=366  FINGER rej   detected; this frame costs ~400 ms
    frame 22 @ 4562ms: metric=132               already gone

A frame that detects a finger takes 400-580 ms to process, of which the
trustlet's own REPORT_EVENT is about 300, and a quick tap lasts 400-600 ms.
There is no room for a second frame however early the loop wakes. Speed was
never the constraint.

But the landing frames are being thrown away. 209 and 247 against a 133 floor,
with the interrupt already asserted, discarded by a 2x threshold -- and they are
the only frames a quick tap has to spare. 1.5x puts the threshold at 200: above
the highest idle drift observed (147), below the lowest landing frame seen
(209). The tests pin it between those two measurements rather than to a
constant, and assert that 2x would have discarded both.

Single variable against the labelled 2-of-10 baseline.
2026-09-03 00:15:37 +02:00
00925db485 Candidate 1: the rising edge of an authentication sends the touch event only
Labelled baseline on the proven loop, quick taps only: enrolled finger 2 of 10,
wrong finger 0 of 5. Every press was one frame.

The rising-edge frame costs ~700 ms because it runs the matcher twice -- event 5
and event 7 on the same image, two verdicts back. A human tap is over before a
second frame can exist at that cost. Keeping only the touch event keeps what
every recorded match followed, halves the rising frame, and may be the
difference between one frame per tap and two. It is a single variable against a
labelled baseline; if the rate drops, it comes out.

Also fixes fptrial.sh's latency column, which was all zero: busybox date has no
%N, so it reads /proc/uptime instead.
2026-09-02 23:46:12 +02:00
06459a8e73 Revert the two verify-loop changes: zero matches in four runs
Two changes went in together and the next four runs matched nothing, including
a held press. They cannot be separated after the fact, so both come out and the
loop returns to the shape that has matched every time it was asked to.

One is definitely broken. The rising-edge recapture assumed a frame 50 ms after
detection would show a settled finger; on a quick tap the finger was already
gone, the recapture read the idle floor -- metric 133, still flagged FINGER
from the first capture -- and an empty image went to the matcher. A guaranteed
miss on exactly the case it was meant to fix.

The other is probably wrong. Dropping event 5 as a duplicate rested on
observing that event 7 alone produces a verdict -- but every such observation
was a held frame that followed an event 5 on the same press. Whether the touch
event initialises the press in the trustlet is not known, and five finger
frames with no match is not the evidence to remove it on.

The process error is the one worth writing down: two variables changed at
once, on a live user's finger, with no way to attribute the result. One at a
time from here.
2026-09-02 23:18:42 +02:00
9790381e72 Authenticate: one matcher run per frame, on a settled image
Two changes to the verify loop, both from measurement on the daemon.

The rising edge sent events 5 and 7 from the same capture and got two verdicts
back from one image -- rej rej, -11 -11, MATCH MATCH. Event 5 reaches the
matcher here as well as event 7, so the second REPORT_EVENT was 250 to 300 ms
of redundant work on every press, on the frame where speed matters most.
Authentication now sends only event 7. Enrolment keeps event 5, where it is the
sample trigger rather than a duplicate.

And the frame that detects the finger is the finger landing: partial contact,
and the frame that rejects most often -- across the real runs matches came at
frame 3, 5 and 8 of a press, and a quick tap is one frame. So on the rising
edge the daemon captures once more, about 50 ms later, before reporting, and
the matcher's first look is at a settled finger.

The rescan-budget experiment is reverted. At the stock budget every
non-matching frame answered -11, for the enrolled finger and the wrong one
alike, while matches landed exactly where they did at rescan=0. The budget
relabels a non-match; it does not make the trustlet try harder. Under the press
rule the two are functionally identical, and rescan=0's terminal rejection is
the cleaner label.
2026-09-02 22:59:31 +02:00
bdd5de21b3 Guide the enrolment, and take the sample total from the config
Two problems from a real attempt, one mine and one the tool failing to explain
itself.

A sample is taken on the RISING edge only. Holding the finger down produces no
further touch events however long it stays there, so a run with the finger
almost permanently down collects one sample: 55 finger frames across 60, three
touch events, two samples accepted. The loop now says which state it is in on
every line -- press, hold, or LIFT -- shows accepted-of-total as it goes, and
calls out a finger that has been held for several frames, because that is the
state where nothing is happening and nothing on screen said so.

And the total is now read from the config instead of inferred. `rem` is
reported after the sample is processed, so the first reading of a healthy
enrolment is already 9, and a session that takes the first reading as its total
is permanently off by one -- it reported "1 of 9 accepted" when two samples had
been accepted out of ten. common.max_enrolling_samples is stated explicitly in
the generated config so both sides agree on the number rather than one of them
guessing.

Also recorded: not every press is accepted. The third touch of that run
reported the same count as the second, which is the algorithm rejecting a
sample, and is normal.
2026-09-02 21:01:00 +02:00
c785aad653 An enrolment cannot be ended by a finger release
A three-tap enrolment declared itself complete. The transcript says why:

    frame 2: metric=308  FINGER  ev5 rem=10
    frame 3: metric=187          ev6 rem=0
    samples: 10 of 10 accepted

The release event never enters do_enroll, so its response leaves
samples-remaining untouched at 0 -- which is indistinguishable from "none
remaining, you are finished". The session believed it, stopped after one press,
and called SAVE_DATA on an algorithm holding no template. That answered -1 and
wrote nothing, so the store was undamaged, but only by luck: the guard meant to
prevent a partial save was itself satisfied by the bogus count.

A reading is only meaningful when it came from the event that runs the enrol
path, and nothing about the value says so -- the caller has to. Observe now
takes that as an argument. Two further guards: a FIRST reading of 0 is an
unpopulated field rather than a finished enrolment, and the count only ever
falls, so an increase is noise.

Verified by mutation: trusting the release event's count, and accepting a
leading zero, each fail the suite.
2026-09-02 20:40:16 +02:00
4e8a763cf9 Add enrolment, and let it choose its own namespace
Enrolment is the first thing here that writes: template containers through the
gpfile listener and counter records through RPMB. It refuses to run unless both
--sfs-writable and --rpmb-write are given, and it refuses to call SAVE_DATA if
the sample count did not reach zero, because a partial template is worse than
none.

The sequence is stock's: cancel, reset-lockout, authenticate, cancel,
reset-lockout, PRE_ENROLL, authenticate, cancel, ENROLL, the sample loop,
POST_ENROLL, SAVE_DATA with bit 30 set. AUTHENTICATE is what arms the capture
session, which is why it appears in an enrolment at all.

Enrolment takes one sample per PRESS: touch on the rising edge, release on the
falling one, nothing in between. Stock's entire enrolment trace contains no
image-ready event, and feeding every held frame gives the algorithm
near-duplicate images from a single press.

Two things named honestly. The ENROLL payload's u32 at +69 was recorded here as
a "timeout"; the trustlet reports it back as the GROUP ID, and filling a
mislabelled field with a plausible number is the entire provenance of gid 60.
It is the gid now, so an enrolment can choose its own group.

And --group-path exposes the namespace key the trustlet hashes into the group's
directory name. It defaults to Android's, which is where this device's existing
store lives and how that template is readable. But SAVE_DATA rewrites the
group's index container, and an index QTEE later fails to verify takes every
template listed in it -- so enrolling into a DIFFERENT namespace is complete
isolation from a store we did not write.
2026-09-02 20:12:24 +02:00
afb7496ef6 Fix the poison offset: a released finger was reading as a rejection
PoisonFid takes the payload and offsets to the fid field internally. It was
being handed a span already offset by the payload offset, so the poison landed
at payload+0x20 and the real fid field stayed zero. A frame where the matcher
never ran then looks exactly like a frame where it ran and rejected -- which is
the specific failure this project has recorded three times and is precisely
what the poison exists to prevent.

Visible in a real run: the frames marked REJECTED were 138, 138, 133, 137, 134
against a floor of 136, i.e. every one of them was a finger-RELEASE frame with
nothing on the sensor. Five rejections that never happened.

The two offsets are numerically equal, which is why double-applying is silent,
so the test now pins both directions: poisoning the payload marks the fid
field, and poisoning an already-offset span leaves it zero and misclassifies.

Also adds --rescan=N, which patches common.max_authentication_rescan_times into
the config. The stock budget lets a whole run end with no terminal verdict --
correct for shipping, useless as a measurement, because a wrong-finger control
that never reaches a verdict has not demonstrated a rejection. Forcing 0 makes
every frame terminal. It prints MEASUREMENT ONLY because a rate taken that way
is a per-frame figure with the retry mechanism disabled, and is not a shipping
reject rate.
2026-09-02 19:16:50 +02:00
03023284ba Serve QTEE's storage: the enrolled template loads
The whole storage path now works from the daemon. On the phone, against the
real store:

    listener 0x7000  sb=516096  -> result=0  REGISTERED
    listener 0x2000  sb=25600   -> result=0  REGISTERED
    SET_ACTIVE_GROUP gid=60 path='/data/vendor_de/0/fpdata'
      gpfile READ .../1lPrxAL0vXRvWPeDkW2c off=4096 len=252114
      ...
      CMD 0x2005 -> result=0 rc=1
      templates loaded: 1

QTEE read a 252114-byte enrolled template through our gpfile listener, verified
it, and loaded it. Since QTEE unlinks any container whose keyed integrity tag
fails, a load is proof the framing is right -- the read/write offset split, the
container chunking, and the RPMB anti-rollback read that has to succeed before
QTEE will trust any of it.

RPMB is served too: SECURITY PROTOCOL IN/OUT against the RPMB well-known LUN,
retrying the unit attention the LUN raises once after a reset. Writes are
refused unless asked for, because they advance a counter that cannot be moved
back, and key programming is refused unconditionally.

The store was served READ-ONLY throughout, which is the point. A listener that
serves bytes at the wrong offset does not merely fail: QTEE deletes the
container it cannot verify, and that is an enrolled fingerprint gone. Read-only
makes a wrong build harmless, so it is the default and writing is opt-in.

Two ordering facts, both of which produce -2 with no storage read at all --
indistinguishable from a broken listener:

  * a template reload needs the device init chain to have run FIRST, because
    that chain allocates the per-slot array the reload writes through;
  * SET_ACTIVE_GROUP's second field is a NAMESPACE path, not a filesystem one
    and not the gid again. The trustlet hashes it into the group's directory
    name, so it has to match what the store was written under.

Also: a positive rc is not an error code. ENUMERATE returns the template count
there, and running that through the error table printed "unknown" for a good
answer.
2026-09-02 18:42:20 +02:00
6c4622afff Capture works: idle floor 133, matching the reference measurement
The finger-free path is complete. On the phone, from a cold start:

    client env -> loader -> trustlet -> config -> sensor rail -> init chain
    calibrating the idle floor (5 samples)
      idle 1/5: rc=-11 metric=133
      ...
    idle floor = 133, finger threshold = 266

133 is the number the journal records for this sensor, so the port reproduces
the reference measurement rather than merely producing one.

Two things had to be right at once, and the first attempt had neither.

The memory region: CAPTURE_IMAGE reads an output-buffer pointer out of
payload+0x00, and QTEE only patches an address there if the location is named
in embeddedBufOffsets and the region handed over in an object slot. The
instrumented dump shows it working -- payload+0x00 came back holding
0x088db98000 -- which is what made the remaining failure legible instead of
mysterious.

And two fields inside the capture payload that an all-zero request leaves
unset: a frame count at +0x0c and a branch selector at +0x10. Selector 0
returns metric 0. Sending zeros gets -201 with the region correctly attached,
which reads exactly like a broken region and is not one. They are named
constants now, with the note that the metric is PER FRAME so a threshold
calibrated at one frame count means nothing at another.

The flags word at payload+0x18 stays past the declared length of 0x14 on
purpose: the trustlet range-checks that length to exactly 0x14 and reads the
flags anyway.

--verbose keeps the region and reqOut dumps, which is what turned this from
guesswork into reading.
2026-09-02 18:27:35 +02:00
1fb57cd1be Own the sensor rail, and run the init chain against it
The daemon now powers the sensor and initialises the trustlet against it. On
the phone, every step of the chain returning rc=0:

    gpiochip 'f100000.pinctrl' is /dev/gpiochip5 (168 lines)
    sensor powered, reset released, irq=1
      CMD 0x1006 INIT_SPI          rc=0
      CMD 0x100a PROBE_DEVICE      rc=0
      CMD 0x100b INIT_DEVICE       rc=0
      CMD 0x1004 TA_INIT           rc=0
      CMD 0x1020 WORK_MODE         rc=0
      CMD 0x100e SYNC_STATISTICS   rc=0

GPIO v2 chardev ioctls directly rather than libgpiod, which is on neither the
phone nor the sysroot and would be a dependency for three lines.

The chip is found by label, and the label is not what the device tree calls it:
the node is pinctrl@f100000 so the chardev advertises "f100000.pinctrl", while
every DT reference says "tlmm". Matching on "tlmm" finds nothing, which is how
the first run failed. There is a second check on the line count, because this
SoC has another pinctrl with 23 lines and driving line 75 of the wrong
controller is not something you recover from over ssh.

The XPU guard is enforced where the line is actually opened, not only asserted
in the core. gpio8-11 are the fingerprint SPI pads and touching one is an
immediate SError with the phone rebooting where it stands, so a refusal has to
sit in front of the ioctl.

Owning the rail is what makes the session recoverable at all: one reset buys
exactly one trustlet init and a second answers -205, so a failed session needs
the rail cycled rather than the chain retried. The harness split these across
two processes and every run began by restarting the one holding the rail.

CAPTURE_IMAGE answers -201 here and that is correct, not a regression: it needs
a shared memory region whose address QTEE patches into the payload, and none is
supplied yet. That is the next piece.
2026-09-02 18:24:12 +02:00
2648e46d43 Load the trustlet and configure it
On the phone, end to end from the daemon:

    lookupTA('focal64') -> result=23 (nothing to unload)
    trustlet loaded from /lib/firmware/focal64.mbn, distName='fingerprint'
    config /lib/firmware/fingerprintd.json: 349 bytes
      CMD 0x100d -> result=0 rc=0 (Success)
      CMD 0x2005 -> result=0 rc=0 (Success)

The config is the one fp6fpcfg.py --daemon generates, so the reduction of nine
hand-edited ffcfg files to one generator is confirmed against the trustlet
rather than only against the files it replaced.

A stale instance is unloaded before loading, which is what stops a crashed
experiment costing a reboot; result=23 is the clean-slate answer.

The request envelope moves into Fingerprintd:Ta with the rest of the layouts:
command id at +0, declared length at +4, payload at +0x10, and on the way back
the trustlet's own rc at +8 and the capture metric at +0x0c. Both are HEADER
fields ahead of the payload -- the metric has been miscalled "payload+12" in
this project's notes, and every recorded finger number depends on reading it
where it actually is.

ENUMERATE answering rc=0 is correct here and not a regression: no group is
active and no storage listeners are registered yet, so there are no templates
to count.
2026-09-02 18:19:26 +02:00
a91fb2ff58 Reach QTEE: credentials, client env and the app loader, with no QCBOR
fingerprintd's own code now talks to QTEE. On the phone:

    root object on /dev/tee0
    client env obtained (uid 0, 13-byte credentials)
    QSEECOM-compat app loader (UID 122) opened

The credentials object is ours rather than libqcomtee's. Upstream's exists only
to build a thirteen-byte CBOR map and drags in QCBOR to do it, so
packaging/make-libqcomtee.sh compiles the two sources that matter and drops
credentials_obj.c entirely -- nothing else references it, and the library then
has no dependency beyond libc. The map is built in Fingerprintd:Tee where it is
pinned byte-for-byte against the string verified on-device, and the object's
two-op read protocol is served here.

Three interop details, all of which cost a build cycle:

  * libqcomtee's headers carry no extern "C" guard, having only ever been
    consumed from C, so everything came out C++-mangled. They also pull in
    <stdatomic.h> and <stdio.h>, which under libc++ drag in templates that may
    not appear inside extern "C" -- so those are included first.
  * tee_call_t's second parameter is unsigned long on glibc and int on musl.
    The native build is glibc and the phone is musl; both forms are compiled.
  * On the callback path a UBUF_OUTPUT param arrives with addr = NULL. The
    dispatcher supplies the buffer, so a handler POINTS the param at its own
    storage rather than writing through the incoming address. Doing the latter
    is a null dereference that takes the supplicant thread with it, which is
    how the first run against real QTEE ended -- with the correct behaviour
    already spelled out in the module comment above the code that ignored it.
    That comment now says so in as many words.
2026-09-02 18:02:28 +02:00
f2a696bbbe Drop the gid 60 compatibility path
gid 60 was never a decision -- it was the ENROLL token's timeout field being
read as a gid, then made self-consistent. Keeping it readable alongside gid =
uid would be a second code path, a second group to reason about, and a
migration to eventually retire, all to avoid re-enrolling one finger on one dev
phone. Re-enrol it instead.
2026-09-02 17:28:47 +02:00
80ff09b4ce Port the finger name map, the last of the core modules
Fingerprintd:Store holds the correspondence between two vocabularies that know
nothing about each other: the trustlet identifies a finger by an opaque 32-bit
id it chose, and fprintd speaks users and names like "right-index-finger".
Nothing else can hold it -- the trustlet has no field for a name.

No biometric data passes through here. A template is a ~252 KB container the
trustlet encrypts and QTEE anti-rollback protects; this is a table of {name ->
the id the trustlet reported}, worth about as much as a username. It is stored
as one "name fid" per line, deliberately boring and greppable, because losing
it costs names rather than templates and it should be repairable by hand.

Two properties are load-bearing. fid 0 is never storable or matchable: 0 is
what the trustlet writes into the fid field when authentication FAILS, so a
stored 0 would turn every rejection into a match. And a damaged map degrades to
"fewer names known" rather than to a daemon that will not start -- unknown
names, missing ids, partly-numeric ids and zero fids are all skipped, since the
daemon that fails to start is the one that unlocks the phone.

The gid is the caller's Linux uid. SET_ACTIVE_GROUP and AUTHENTICATE only have
to agree with each other, so the value is ours to choose, and the uid makes the
mapping total with no allocation table. The dev phone's gid 60 is recorded as a
legacy group -- it was never a decision, just the ENROLL token's timeout field
read as a gid and then made self-consistent.

Verified by mutation: storing fid 0 and accepting a partly-numeric id both fail
the suite. A third mutation did not: Lookup's own zero guard is unreachable
because Add is the only way an entry is created and it already refuses 0. The
guard stays as defence in depth for a future writer, and the test now asserts
the invariant that makes it unreachable -- no entry holds fid 0 however it was
created -- rather than leaving a branch that no test can reach.
2026-09-02 17:22:27 +02:00
dff77110ef Port the capture loop, and make the per-press rate re-derivable
Fingerprintd:Engine is the policy the trustlet cannot supply. It never polls
for a finger: the normal world captures a frame, decides whether a finger is
there, and tells it. So finger detection, edge reporting and the accounting all
live out here, and they are the parts most easily got wrong in a way that reads
as bad hardware.

Baseline refuses to be a fixed threshold. The capture metric is per frame, so
it scales with how many frames a capture asks for, and it drifts upward while
idle -- an early session read "18 -> 24 with a finger" as weak detection when
the values were climbing regardless of what was on the sensor. The floor is the
maximum of the idle samples, and an uncalibrated Baseline calls nothing a
finger rather than inventing a threshold.

TouchTracker keeps the two modes apart. Enrolment reports touch on the rising
edge and release on the falling one and nothing while held, mirroring stock,
whose entire enrolment trace contains no image-ready event; emitting one per
held frame feeds the algorithm near-duplicate images from a single press.
Authentication does want it, because event 7 reaches the matcher
unconditionally.

AuthTally exists to stop two counting mistakes. Only a terminal verdict is an
attempt -- counting rescan frames as rejections is what turned an 8-for-8 run
into an apparent 8-of-39. And a press that ran out of frames without reaching a
verdict is UNDECIDED, not failed; treating it as a failure is the same error one
level up, which is why decided presses are counted separately.

The tests replay the three recorded runs in order rather than as totals,
because press structure only exists in the order. That makes the per-press
claim re-derivable here instead of quoted: the enrolled finger matched on all
five presses although five of its twenty frames did not, the wrong-finger
control matched nothing, and on the stock-budget run five of ten presses
reached a verdict and all five matched.

Verified by mutation: counting undecided presses as decided, using a baseline
before calibration, emitting image-ready during enrolment, and taking the first
idle sample as the floor each fail the suite.
2026-09-02 17:19:45 +02:00
1db0762078 Port the RPMB listener's wire format, guard included
Fingerprintd:Rpmb is the other half of QTEE's storage. Where gpfile moves the
container bytes, RPMB is the anti-rollback: an authenticated, monotonically
counted area of the UFS device that lets QTEE tell a genuine store from an old
one replayed back at it. Framing and policy only; the SCSI transport stays in
the daemon shell.

The guard is the reason this module has tests rather than just constants.
req_resp 0x0001 is Authentication Key Programming, and the RPMB key is one-time
programmable in the UFS device -- relaying such a frame destroys that part's
RPMB permanently and no reflash recovers it. QTEE has no legitimate reason to
send one, so it is refused unconditionally, whatever the write policy says. It
is tested for scanning every frame rather than the first, and for refusing a
request that claims more frames than the buffer holds instead of reading past
the end.

The out-parameter at +0x08 is the field that failed every RPMB transaction for
a week. librpmb passes it by address, so it reports bytes transferred, and QTEE
compares it against what it expected and rejects the transaction on a mismatch.
A read posts one request frame however large nblocks is while a write posts
nblocks * 512, so the two directions genuinely do not report the same thing --
tested as such, because leaving the request's frame size there is the bug.

+0x0c is kept exactly as the request supplied it. QTEE looks for the response
frames at req + req[0x0c] and the request arrives with 0x18; librpmb's
hardcoded 20 points four bytes early.

Chunking refuses a remainder rather than following the reference, which
silently drops one -- a partial authenticated write leaves the store
inconsistent with a counter that cannot be moved back.

Verified by mutation: checking only the first frame for key programming,
reporting a flat frame size as bytes transferred, and admitting a remainder
each fail the suite.
2026-09-02 16:48:57 +02:00
ffad29ba4e Port the trustlet command surface, and pin the counting rule to recorded runs
Fingerprintd:Ta is the second core module: request payloads, response fields,
the error table, and the rule that decides what a frame meant. Payload building
and response reading only -- no TEE, no transport.

Very little of this is guessable, so each constant carries where it came from.
Three were found only because QTEE recorded a fault naming the instruction that
read them:

  * the event context's scan-slot count at +712, which do_enroll branches on to
    skip the entire slot loop -- an all-zero payload logged "groups->,
    results->" and read exactly like a gate failing deep in the trustlet, when
    it was zero iterations;
  * CAPTURE_IMAGE's flags at payload+0x18, without which preprocessing, the
    classifier and the enrol grouper never run at all, whatever is on the
    sensor;
  * SYNC_STATISTICS, whose absence leaves g_statistics NULL so the first enrol
    frame that gets far enough takes a data abort and every later command
    answers -90.

The verdict rule gets the most attention because it was mislabelled three times
before the comparison producing it was read. A frame is one of three things and
only the third is a verdict: the poison intact means the matcher never ran,
rc=-11 means not identified yet with attempts remaining, and only rc=0 carries
a match or a rejection. The poison exists because a zero-initialised buffer
cannot tell a released finger from a rejected one.

The tests are in two halves that cannot prop each other up. Explicit wire
conditions pin the classifier; three recorded runs pin the counting policy,
which is what actually went wrong. In the stock-budget run 31 of 48 frames
answered "not identified yet" and every frame that carried an image matched --
counting those 31 as attempts turns 8-for-8 into 8-of-39 and reads as a flaky
sensor. The wrong-finger control pins zero false accepts.

Fixtures are verdict-line excerpts, not the 40 KB transcripts, which are thick
with the device's SFS container names the test has no use for.

Verified by mutation: classifying -11 as a rejection, dropping SYNC_STATISTICS
from the init chain, and forgetting the +0x10 response payload offset each fail
the suite.
2026-09-02 16:46:00 +02:00
1d26852a6b Initial commit: the gpfile wire format, pinned by two real containers
fingerprintd will own the FP6's fingerprint sensor: the rail, the QTEE session,
the storage callbacks QTEE makes back into the normal world, and
net.reactivated.Fprint so pam_fprintd and the desktop need no changes. None of
that runs yet. What is here is the first core module and the machinery around
it.

Fingerprintd:Sfs is the gpfile listener's frame -- the callback that carries
47 of 66 storage requests during an enrolment. It is parse, reply and root
mapping only: no file I/O, no TEE, no allocation of the shared buffer. The
daemon shell supplies those, which is what lets every byte-level decision be
tested on a dev box with no phone.

The module exists mainly to hold one fact. READ answers at req+0x00c and WRITE
reads its payload from req+0x110, because the frame is a union: a WRITE still
needs its path while the payload is copied out, so it sits past the 256-byte
path field, while a READ has consumed the path and packs its reply over it.
Conflating them is wrong in both directions with the same symptom -- the
container does not round-trip, QTEE's HMAC check fails, and the file is
unlinked as tampered on the next session.

So the tests do not assert the constants against themselves. They load two real
containers off the phone -- one written correctly, one written with the offsets
conflated -- and re-derive the bug: the broken one opens with ASCII path text
rather than a binary HMAC, that text is the group name from character 8 because
the read offset is 8 bytes into the path field, and the real container sits
exactly 0x104 further in. Then a write-store-read round trip must be the
identity, and the same round trip through a single offset must not be.

O_TRUNC gets a static_assert of its own. QTEE writes a container as
write(0,4096), write(4096,N), write(0,4096), so truncating on open leaves 4096
bytes where a 258850-byte template belongs; it unlinks a file it means to
shorten rather than relying on the opener.

Verified by mutation: conflating the offsets, making DataOffset return the read
offset for writes, and setting O_TRUNC each fail the suite.
2026-09-02 16:02:46 +02:00