Commit graph fingerprintd/implementations
Author SHA1 Message Date
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
b228287c5b A verify nobody answered is not a failure, and the trustlet is not ours to ship
Two things the packaging left behind.

A verify that ran its 600-frame budget without the sensor being touched was
reported to the client as verify-unknown-error. Nothing had gone wrong: nobody
had pressed. It cost three verifications during packaging, each reading as a
broken daemon. fprintd's contract is that a verify runs until the client stops
it, so the frame cap bounds one trustlet scan session rather than the user's
patience, and a window with no press simply runs again. Verified across the
rollover: 600 frames untouched, "still waiting", then a press matching on its
first contact frame in 44 ms.

Presses that happen and never reach a verdict now report verify-retry-scan --
a bad scan, which fprintd has a word for, and not the matcher saying no.

The cost is that an unanswered verify polls every ~200 ms for as long as the
client holds it. The cure is measured and available -- gpio75 is silent at
idle and bursts on contact -- but it would make the IRQ the only way a press
is ever noticed, deleting the poll under every rate this daemon has been
measured at. Noted where the loop waits, not done.

And the trustlet: focal64.mbn is a proprietary OEM-signed blob, so the package
ships a fp6-vendor-blobs manifest fragment instead, the same mechanism
soc-fairphone-fp6-audio uses for the amp config. It needed a new directive
there -- a QTEE image is an ELF header file plus one payload per program
header, not one file -- and reassembly on the phone reproduces the image QTEE
has accepted since August, byte for byte.
2026-09-05 04:01:06 +02:00
905e261d63 Package the daemon, so a fingerprint survives a reflash
An aport, the units, and everything a phone needs to come up with a working
sensor without a single command being run by hand. Verified on the dev phone
across two reboots: modules-load.d loads qcomtee, tmpfiles builds the SFS
root, the mount unit brings up persist, and the daemon is ready 51 seconds
into the boot, owning net.reactivated.Fprint with the enrolled finger
visible.

The packaging shape is the one imsd uses for 81voltd. A versioned
provides="fprintd=..." satisfies plasma-workspace -- its Users KCM is the
enrolment UI and speaks exactly this bus name -- and excludes the real
fprintd, which is not tidiness: fprintd is D-Bus-activatable, so a client
call would otherwise start it and fight us for the name. The cost is the
fprintd-* CLIs, which go with the package.

fprintd-pam is an install_if subpackage pinned to the exact fprintd version,
so the provides breaks its condition and apk purges it -- taking pam_fprintd,
which is the entire point of the daemon, with it. Depending on it explicitly
is what keeps it, and it has no dependency on fprintd itself.

Two things the packaging exposed in the daemon:

The transcript is for experiments, not for a shipped daemon. A file per start
in an unrotated directory, recording the time of every unlock, to say what
the journal already has. It is now opt-in behind --log-dir, which is what
deploy-dev.sh passes since fplearn.sh reads it.

Taking it off the daemon path also took away the setvbuf it was doing as a
side effect of dup2'ing fd 1, and under systemd stdout is a pipe, which means
full buffering: the daemon started, worked, answered D-Bus calls, and printed
nothing. A working daemon that looks hung. stdout is now line-buffered from
the first line of main.

The config ships as generated by fp6fpcfg.py --daemon --verbose, sha256
b205c756914a66f1, because that is the file every accuracy number was measured
on. The quieter variant is untested and switching is a measurement.

The trustlet is not here and never will be: focal64.mbn is a proprietary
OEM-signed blob, and the unit's ConditionPathExists is what keeps the package
inert without it -- as it does on a kernel with no CONFIG_QCOMTEE.
2026-09-05 02:52:01 +02:00
ba882ee47b Learning off by default: it makes matching worse on this hardware
Jorijn asked for the control that settles it -- a fresh template, tested with
learning off -- and ran it twice.

  fresh template, 0 folds     30/30, two consecutive blocks of fifteen
  same lineage, 40 folds      12/15
  same lineage, 185 folds     total failure, 108 consecutive rejections

Every one of those measured with learning switched off during the measurement
itself, so nothing moved underneath the numbers, and the fresh-template result is
replicated back to back. Three points, monotonic in fold count.

The mechanism has been visible since the 185-fold collapse: the frames one press
contributes are near-duplicates of a single image from one finger position, so
folding them spends the template's ninety-six slots on that position and evicts
the diversity a twenty-sample enrolment put there. Stock's updates are spread
across many separate presses hours apart, which is where diversity actually comes
from.

And there is nothing on the other side of the scale. A plain enrolment measures
thirty out of thirty, so learning has no headroom to improve anything, and it has
never once been observed to raise a rate under conditions worth defending -- the
run that once looked like proof was confounded by a freshly wiped sensor and a
user learning the technique, both of which Jorijn identified himself while the
numbers were still climbing.

The code stays behind --learn=1. The finding is about this trustlet's algorithm,
not about the idea.
2026-09-05 02:11:43 +02:00
ae2f537a40 Answer a failing press while the finger is still on the sensor
Jorijn asked whether the timeouts were the wrong-finger path or something to do
with learning. Neither. It is a deadlock between the press rule and the
instruction the user is given.

A press was judged only when the finger was released. The user is told to hold
until it answers. So a press whose frames keep rejecting is never released, the
daemon never judges it, and the client sits there until its own timeout expires.
The transcript shows exactly that: twenty-nine consecutive full-contact frames
rejected across twenty seconds with the finger down throughout, surfaced to the
user as a hang rather than as a failure.

Detection was fine, the settled gate was fine, the matcher was doing its job and
saying no. Nothing was ever going to tell the user so.

A press now answers no-match once it has accumulated five rejected frames,
without waiting for a release. At roughly seven hundred milliseconds a frame
that is about three and a half seconds -- long enough that the frame-3 and
frame-8 matches in this project's records still land, short enough to be an
answer instead of a wait. A phone tells you it did not recognise you while your
finger is still on it.
2026-09-05 02:00:39 +02:00
30bb987c27 A template restore destroys the template; refuse it, and stop caching a failed load
The paired test I built cannot exist on this hardware, and finding that out cost
Jorijn his enrolled finger.

Restoring an earlier container byte for byte made the trustlet read its header,
UNLINK it, look for a .bak and advance the RPMB counter -- for both containers.
QTEE binds every SFS object to a hardware anti-rollback counter, so an earlier
version is not stale to it, it is tampered, and the response to tampering is
deletion. No copy can undo that. The journal has warned about this counter since
August in the context of the group index; it applies to the template itself just
as hard, and I did not check before building a feature on the assumption that it
did not.

So restore refuses and explains, with the measurement in the message. Snapshots
stay: they are still forensic evidence of what a template looked like, they just
cannot be put back. Changing a template means enrolling again.

The daemon compounded it. The group-selection cache stored "0 templates loaded"
as a valid answer, so once the trustlet had unlinked everything, every later
claim answered "skipped (already active, 0 template(s))" and never tried again.
It now caches only a positive result, so a failed load is retried rather than
made permanent.
2026-09-05 01:44:15 +02:00
756093e847 Fold one frame per press, not eight -- and put snapshots where the user can find them
Four matches, each followed by a template save, then five consecutive failures.
Jorijn asked whether it was user error. It was not.

Over one evening the harvest folded 185 frames into a template whose
max_sub_template_num is 96, and the template went from matching ten presses out
of ten to failing five in a row. The frames one press contributes are
near-duplicates of a single image, so folding eight of them per press does not
add coverage: it spends the template's slots on one finger position and evicts
the diversity the enrolment put there. Stock's roughly forty-six updates in a
session are spread across many separate presses, which is where diversity
actually comes from.

So one fold per matched press, which also needs no extra capture at all because
the matching frame is already inside the trustlet. Eight remains available for a
deliberate experiment.

The snapshot directory was resolved from $HOME while the script is run under
sudo, so every snapshot landed in /root/fp6-backups and looked, from the user's
shell, like it had never been taken. That is the one thing that would have made
this unrecoverable, and it was caught only because the restore was needed. It
now resolves the invoking user's home.
2026-09-05 01:36:10 +02:00
07516f2dc6 Take the harvest off the unlock path too, not just the save
Jorijn ran the same block twice, split five held and five released, and the held
half kept costing about 2.7 seconds more per press in the client while the
daemon's own decide time stayed at 36 to 334 milliseconds either way. The gap was
not the sensor and not the matcher. It was this daemon.

The save was deferred until after the verdict was posted, for exactly the right
reason. The harvest was not, and the harvest is up to eight capture-and-fold
round trips. Holding a finger through the verdict keeps it fed to its frame
limit, so a held press folded eight frames and a released press folded one --
and every one of those folds sat between the match and the client hearing about
it.

Both now run after the event is posted. A finger held through the verdict is
still there a millisecond later, so the harvest loses nothing by waiting, and
the frame that actually matters was already folded at the moment it matched.
2026-09-05 01:30:33 +02:00
231a1860ac Do not make the trustlet re-read the whole template on every claim
Selecting a group makes the trustlet reload every template in it from storage,
and on this device that is 651276 bytes crossing the listener in chunks. Measured
over ten verifications: eleven claims, eleven reloads, fifty-four chunk reads,
twenty-six megabytes of round trips. All of it happens before the verify loop
starts, so all of it lands in the latency a user feels while being invisible to
the daemon's own timing -- which is how it survived this long.

It is also unnecessary. The trustlet holds templates in memory once loaded; a
successful authentication on stock produces no storage callbacks at all. A group
that is already active does not need selecting again, so a repeat claim now
answers from what the last real selection reported.

Enrolment forces a real selection, because it adds a template and the reload is
the point.

Measured after: two claims, one real selection, one skipped, and the chunk reads
drop from five per claim to two for the pair.
2026-09-05 01:25:03 +02:00
eb50e5b6fb Report placement time and decision time separately, because only one of them is ours
Jorijn: "response times this run tanked", and then, sharply, "are you sure its
back? or has it always been like this."

It has always been like this, and the number was never measuring the daemon. The
client's wall clock starts when the verify request starts, so it includes however
long the user takes to get a finger onto the sensor. In the run that prompted the
question the slow presses spent two seconds and more watching an EMPTY sensor --
ten consecutive frames at metric 129 to 142 against a 133 idle floor -- and then
matched on the very first frame that had contact in it.

Every matched press in that run reads "press 1: 1 frames -> MATCH". Not one
needed a retry. The presses that felt instant were the ones where a finger was
already down when the request started, and the presses that felt slow were the
ones where it was not.

So the loop now times from first contact as well as from the start, and says so
in as many words. A figure that silently includes human reaction time cannot be
compared between runs, between people, or against a phone.
2026-09-05 01:16:58 +02:00
284282350b Hold, do not tap -- and stop spending the verdict on a frame that cannot carry it
Jorijn worked out the technique and it changes what every number in this project
means: "press and LIFT (quick tap) is wrong, holding the sensor until it gives
the result is a 100% success rate."

The logs agree, on a properly controlled comparison. Same template, same
session, learning off for all four blocks, only the technique differing: tapped
4/15 and 3/15, held 15/15 and 15/15.

The frame data says why. Over every frame this project has a verdict for, split
at 2.5x the idle floor:

  full contact, interrupt settled     78/175 = 45% match
  full contact, interrupt asserted    28/142 = 20%
  partial,      interrupt settled      1/9   = 11%
  partial,      interrupt asserted     0/53  =  0%

A tap is caught while the finger is still arriving or already leaving. Such a
frame is not a hard verdict waiting to happen, it is a wasted one: with the
rescan budget at 0 every frame is terminal, so its rejection ends the press. 62
partial frames produced exactly one match between them.

So the tracker becomes a Schmitt trigger. A press now STARTS on settled contact
and ENDS on the finger leaving, which means a frame taken mid-landing produces
no event at all rather than a false rejection. A press that never settles simply
yields no verdict and the loop waits for the next one, which is an honest try
again. Enrolment is untouched: it passes one threshold for both and keeps its
own sample-quality gate inside the trustlet.

fptrial.sh now says hold, and defaults to fifteen presses. Instructing a tap for
its whole life is what quietly made every rate this project has quoted a worst
case, and a tap is not a case the product has -- nobody taps a phone sensor and
walks away, they rest a finger until it unlocks.
2026-09-05 00:17:13 +02:00
3e06003fd0 Fold the matched frame at the moment it matches, not after the verdict
Template learning was doing nothing. Across three measured trials, six presses
matched and five of them folded zero frames: the harvest captured a NEW frame
before folding, and by the time it ran the finger was gone, so the capture read
the idle floor and the loop exited. Every press in those trials was exactly one
frame long -- a tap lasts 400 to 600 ms and a frame costs 200 to 300, so there
is never a second frame to harvest.

Stock does not capture first. In the reference trace UPDATE_TEMPLATE follows
do_authenticate directly -- auth success score, authenticated result is updated,
CANCEL, checking the template, UPDATE_TEMPLATE -- with no CAPTURE_IMAGE between
them. The trustlet still holds the image it just matched against, so the frame
that produced the verdict is the frame to fold, and it costs one command with
nothing on the sensor.

So the fold happens at the match site now, and the harvest continues from slot
one for as long as the finger actually stays down. A quick tap folds exactly one
frame instead of none, which is the case that matters: a quick tap is what a
user does.

The touch-frame flag follows the event that carried the verdict, so a match on
the rising edge sets bit 6 exactly as stock does.
2026-09-04 23:28:06 +02:00
a3d3dcb4af Print the trustlet's rc on every enrol press, and let deploy-dev.sh pass extra flags
A refused enrolment sample is one of two things: an image the algorithm saw and
turned down (rc=0, samples remaining unchanged) or an error the trustlet never
got past (a negative rc). The touch line printed the count and the fid but not
the rc, so a run of twenty-two refusals in a row said nothing about which it was.
It does now.

EXTRA=... on deploy-dev.sh appends daemon flags, so a diagnostic session can
come up with --ta-log without editing the script or the unit by hand.
2026-09-04 22:58:22 +02:00
21d6aa448c Read the trustlet's own log, which on mainline means the response buffer
The matcher has been a black box that answers yes or no, and that is why "the
matcher saw a full-contact image of the enrolled finger and rejected it" went a
whole session with no explanation.

There is no tzdbg on mainline -- /sys/kernel/debug/tzdbg does not exist on this
kernel -- so the /proc/tzdbg/qsee_log route that captured the Android reference
log is unavailable, and the qcomtee qseelog ring is on record as wedging TZ. But
focal64 writes its log into the response buffer, which is how the research
harness printed it all along. --ta-log scans it, so the matcher's own verdicts
are readable on pmOS: auth success score, identify fail with the
FtVerifyByTemplate return, and the per-frame image quality, coverage and
humidity.

Turning it on taught three things, all of which are configuration rather than
code.

A log level is not enough. The trustlet answered "no key named
diagnosis.enable_algorithm_log, use default value" -- that switch and two
siblings are separate on/off gates that stock sets on and we had never sent at
all, so the algorithm log level was being applied to a stream that was off.

Lower is more verbose and 6 is off: level 0 produced 244 lines where 5 produced
far fewer. That settles a direction the config generator explicitly left open,
and it means the old verbose setting of 5 was very nearly a quiet one.

The ring is the scarce resource. It is about 150 lines per session and is never
reset, so the config dump alone overflows it: at framework level 0 the dump
produced 244 lines and UPDATE_TEMPLATE's own lines never arrived. The shipped
verbose config now leaves the framework log off and the algorithm log at 0,
which cut the init ring to 38 lines and reserves it for the matcher. Framework
tracing is a separate run and cannot also have the matcher's lines, and the
level cannot be raised later because 6 is unrecoverable by a runtime SYNC_CONFIG.
2026-09-03 17:46:20 +02:00
e2033ed26d Learn from a matched press, as stock does
Template learning, the half of the algorithm this daemon never ran. Every match
rate measured against this device -- 1/10, 2/10, 3/10, 7/10 -- was measured
against a day-zero template that no stock user lives with, because a stock
template is rewritten on every successful press and ours never moved a byte.

HarvestTemplate mirrors stock's post-match loop: while the finger is still on
the sensor, capture and fold, sending no event so the matcher cannot re-run and
revise a verdict the client already has. A quick tap pays almost nothing, since
the finger is gone by the time a verdict lands and the first capture reads the
idle floor; a held press contributes the frames it was actually held for.

That last property is why this subsumes the enrolment-tuning thread. The working
hypothesis after the strict-threshold and 30-sample failures was that enrolment
conditions have to resemble verification conditions. Learning is exactly that,
done by the algorithm from real unlock presses instead of by coaching a user
into positions they never use.

FlushTemplate issues the SAVE_DATA, and the worker calls it after the verdict is
posted rather than before. Persisting a learned template is roughly 350 ms of
gpfile and RPMB traffic and it does not belong on an unlock path; stock defers it
the same way, with a lazy-updater timer.

--learn=0 turns the whole thing off, which is the only way the comparison is
single-variable: learning is cumulative, so an A/B needs one binary and one
template lineage rather than two builds. --learn-frames bounds what one press may
contribute, because the template body moves as a single gpfile op against a
516084-byte listener buffer and a 30-sample body already measured 386402.

--probe-learn sends one UPDATE_TEMPLATE with no finger and then ENUMERATEs to
prove the trustlet survived it, which is the part a bare return code cannot say.
2026-09-03 17:45:58 +02:00
36085c1b18 Release the capture region on both invoke paths, and stop duplicating the sample count
Three fixes from the same session, all of which had been left uncommitted.

The tee_shm fd leak is the serious one. The per-frame capture region was
released only on the invoke-FAILURE path, on the belief that an invoke consumes
its input objects. That is libqcomtee's rule for callback objects, not memory
objects -- its own ta_load.c hands a memory object in exactly this way and
releases it unconditionally afterwards. So one fd leaked per captured frame, and
the first daemon instance to live through ~1000 frames hit the 1024 limit: every
capture then answered "memory region alloc failed" and an enrolment in progress
ran out of frames with nothing on the sensor to blame. Soak-proven fixed at 93
frames with the fd count flat at 2-3.

The enrolment sample count lived in two places, a hardcoded 20 here and
common.max_enrolling_samples in the trustlet config. When the config said 30 the
daemon still advertised 20 stages, so the progress counter froze at 20/20 and
the run looked clamped or hung when in fact all 30 samples were taken. It now
comes from the same JSON the trustlet is given, so the two cannot drift, with
--samples= as a deliberate override.

--probe-ta-load loads one TA image through the daemon's own loader and reports
the raw loader result. It brings up only what a load needs and unloads
afterwards, so a refusal is inert.
2026-09-03 17:44:22 +02:00
faf0dd9ba1 A verify answers only for the finger that was asked about
Jorijn asked whether re-enrolling a finger overwrites its template. It does
not. The trustlet stores a new one and keeps the old, because
FF_CMD_TA_REMOVE is not implemented -- the group on this device now holds six
templates, including one from the research harness and a pair from an
enrolment two configs ago.

The trustlet identifies against every template loaded in the group, and this
daemon reported verify-match for whatever fid came back. So a request naming
one finger was answered by any of them, including templates no name maps to
any more. That is wrong by fprintd's contract, and it also means the last
measurement was taken against the union of every template ever enrolled here
rather than against the one under test.

VerifyStart now computes which fids may answer -- the named finger's, or every
named finger's for "any" -- and a match on anything else is not a match for
that request. A fid that no name maps to answers for nothing at all.

This does not reclaim the slots. Five templates per group is the configured
limit and stale ones still occupy it; removing them needs FF_CMD_TA_REMOVE,
whose payload is not reverse-engineered.
2026-09-03 01:42:55 +02:00
faedcd487e Log enrolment accept and refuse, not only signal them
The enrol callbacks emitted enroll-stage-passed and enroll-retry-scan as D-Bus
traffic and wrote nothing to the transcript. So a grep for refusals in the log
of the guided enrolment found none, and I recorded that the new coverage and
overlap thresholds might have refused nothing at all -- while Jorijn had been
watching the refusals scroll past on the client, which is where the signal
actually surfaced.

The conclusion was drawn from the absence of something never written. Both
outcomes are now logged with the running count, so a run's refusals can be
counted from its transcript instead of from whoever happened to be watching.
2026-09-03 00:31:39 +02:00
f933d2a70a Adopt stock's enrolment-quality config: 20 samples, and thresholds that refuse a bad one
Jorijn asked whether the sample count is ours to control and whether more
samples would help. It is -- and the config dump says something more useful.
Stock enrols with 20 samples, not the 10 we had guessed, but it also sets six
keys we were leaving entirely to the trustlet's built-in defaults:

    min_enrolling_coverage_threshold   70
    min_enrolling_quality_threshold    20
    enroll_overlap_min_area            60
    enroll_overlap_max_area            80
    enable_duplicated_finger_checking  on
    max_extral_enroll_low_quality      16

Those defaults accept anything, which is how ten quick taps in one position
became a stored template. The overlap bounds are the mechanism that matters:
a sample must overlap the previous one by 60 to 80 percent -- more means the
finger did not move, less means a gap -- so the algorithm now refuses the
same-spot sample instead of storing it. Sample count alone would have stored
twenty near-duplicates rather than ten.

Deliberately left out: min_identify_quality_threshold and
min_identify_coverage_threshold. Those gate matching rather than enrolment and
would reject exactly the landing frames the 1.5x detection threshold exists to
catch. One group of variables at a time.

fpenrol.sh grows to twenty positions, and its rejection message now says to
move rather than to press harder, because the enforcement and the guidance
finally agree on what a rejected sample means.
2026-09-03 00:26:14 +02:00
578e2321fa Wake the capture loop on the touch edge
The measurement that made this worth building: gpio75 is silent at idle under
WAIT_TOUCH -- zero edges in sixty seconds -- and bursts within milliseconds of
a finger landing. In the observed taps the burst appeared in the transcript
hundreds of milliseconds before the polled capture noticed the finger, which is
why a quick tap only ever produced one frame however cheap the frame became.

So the inter-frame wait is now a wait on the line rather than a sleep. At idle
it times out at the fallback cadence and costs nothing. At contact it returns
at once, so the first capture of a press happens when the finger lands. While
the finger stays down the sensor keeps pulsing, so the wait keeps returning
immediately and the loop runs as fast as QTEE allows -- which is what a press
wants and what stock's architecture does.

Queued edges are dropped when a session arms, or the previous press's burst
would wake the first wait instantly. --edge-wake gates it as a single variable
against the labelled 2-of-10 baseline; it and --irq-observe are mutually
exclusive because both would drain the same fd.
2026-09-03 00:03:25 +02:00
479f653e65 Observe gpio75 edge events, before building anything on them
Taps are one frame at ~200 ms per frame just as they were at ~700, so the
polling cadence is what catches a tap once and the loop's cost is no longer the
limit. The remaining lever is the architecture stock uses: react to the touch
edge, then capture as fast as QTEE allows for the length of the press.

That rests on a prerequisite worth measuring before a line of it is written.
The IRQ line is requested with both edges enabled and an observer thread polls
it and logs every event with the kernel timestamp, the interval since the last,
and the pulse width. Pure observation -- the matching loop is untouched.

Two questions it answers. Whether edges are observable from userspace at all,
and how quiet the line is at idle under an armed session: the level poll caught
it high on 5 of 136 idle frames, so there are pulses at rest, and if they are
frequent a wake-on-edge is dead before it starts.
2026-09-02 23:56:23 +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
93ab8570e0 Add a knob: an undecided press at lift is a no-match
rescan=0 made every frame terminal, which is what stopped a wrong finger from
hanging the client -- but it also disabled the trustlet's own "image not good
enough yet, try again" answer, so a marginal first frame became a hard
rejection. In real use that showed as a quick tap of the enrolled finger
answering verify-no-match: one frame, rejected. Matches land at frame 3, 5, 8
of a press; the first frame is the finger landing.

The alternative is to let the trustlet keep its rescan budget and handle the
wrong finger where it actually manifests, at the press level: a press that
lifts with no terminal verdict is reported as no-match. The trustlet then
answers -11 on marginal frames instead of rejecting them, and the press keeps
going until it matches or the finger lifts.

A knob rather than a decision, because the trade-off is measured, not assumed:
under the stock budget seven of nineteen correct presses ended undecided at the
old 500 ms frame rate, and whether the faster loop closes that gap is the
question the next runs answer.
2026-09-02 22:49:59 +02:00
32fe0ac665 Drop a claim when its client leaves the bus
A claim is held by a bus connection. If that connection goes away -- the client
crashed, was killed, or never called Release -- the claim has to go with it, or
the device is AlreadyInUse for everyone until the daemon restarts. fprintd
watches the claimant's name for exactly this reason.

Found the hard way: a Claim issued from one busctl invocation, which exits the
moment it returns, left the device permanently claimed by a connection that no
longer existed. The daemon now subscribes to NameOwnerChanged for the
claimant's unique name and, when it loses its owner, cancels any running
operation and clears the claim. Release goes through the same path so the
subscription is torn down either way.

Verified with the stock client killed mid-verify under timeout: the claim
dropped, the verify cancelled, and fprintd-list worked immediately after.
2026-09-02 22:39:04 +02:00
9fbf5e6c73 Run the frame loop at 40 ms, and time it
500 ms between frames was the research harness's pace, chosen so a person
could read the transcript as it scrolled. It became the daemon's pace by
inheritance, not by decision, and it is the root of both complaints from real
use: false negatives and a slow answer after lifting.

The matcher rejects the early frames of a correct press and matches several
frames in -- frames 3 and 8 in the acceptance run. So the number of frames a
press gets is what decides it, and at 500 ms a one-second press gets two. And a
lift is only noticed on the next frame, so the gap is also the latency a user
feels before verify-no-match.

A frame costs four QTEE round trips whatever the gap; the gap is pure delay on
top. 40 ms is a starting point, not a measurement: the loop now logs
milliseconds per frame so the real achievable rate is read rather than assumed,
and logs the IRQ line alongside the metric so it is visible whether gpio75
tracks the finger under an armed session -- if it does, lift detection can
become an edge wait instead of a poll. --frame-gap= overrides it.
2026-09-02 22:36:47 +02:00
50617f994f Judge verification per press, and log every frame of it
A wrong finger against the daemon was a silent wait: the loop exited only on a
terminal verdict, and at the stock rescan budget a wrong finger never produces
one -- it answers "not identified yet" on every frame until the right finger
shows up. fprintd's PAM module needs a verify-no-match to deny or retry, so
that is a client that hangs.

The unit of decision is now a press. Within one press the matcher may reject
early frames and match a later one, so a press is judged when the finger lifts:
any match wins, only rejections is no-match, no terminal frame at all is
undecided and scanning continues. A press that matches is reported the moment
it does rather than making the user hold for a release.

Undecided presses are exactly why the rescan budget matters here. At 0 every
frame is terminal and every press decides; at the stock budget seven of
nineteen correct-finger presses ended undecided in the last measurement, which
under a press rule would read as rejections. So the daemon is being run with
rescan forced to 0 while that trade-off is measured on the new template rather
than assumed.

Every frame is logged under --verbose and every press always, so the next
wrong-finger control is visible in the transcript instead of absent from it.
2026-09-02 22:24:12 +02:00
0809b95a48 An operation ends when the client says so, not when its status says done
fprintd's contract: a status with done=true means no more status is coming,
not that the operation is over. The client still calls EnrollStop or
VerifyStop, and until it does the device is busy with that operation. Clearing
the op on done made every stock client's Stop fail with NoActionInProgress --
seen on the first fprintd-enroll against this daemon, which otherwise succeeded
through all ten stages.

Clearing it from the worker was also a race: a client that cancels and
immediately starts a new operation would have had that new operation cleared by
the old one's completion event. The worker no longer touches the op state at
all; only Stop and Release do, on the main thread.
2026-09-02 22:19:08 +02:00
ca9e84b24f Log the map path and resolved uid on ListEnrolledFingers
A seeded map was reported as empty. The instrumented path shows why in one line:
`user` on postmarketOS is uid 10000, not 1000, so the daemon looked for
fingers-10000.map and the file I had written was fingers-1000.map. Two probe-mode
enrolments today also went into gid 1000 on the same assumption -- a group the
daemon will never select for that user, since gid is the uid by design.

Nothing to correct in the daemon; the assumption was mine, and the fix is to
enrol through the daemon rather than around it. The log line stays because
"which uid did we resolve and which file did we open" is the first question
every time this surface says a user has nothing enrolled.
2026-09-02 22:13:27 +02:00
e0bc02332f Become a daemon: a held session, a worker, and net.reactivated.Fprint
The probe becomes the thing the plan was for. Three threads: the supplicant
services QTEE's callbacks; the worker owns the sensor rail, the QTEE session
and the trustlet and is the only thread that ever invokes it, so every
enrolment and authentication is serialised by construction; the main thread
runs the GLib loop and speaks fprintd's own D-Bus interface, never touching
the trustlet directly.

Session is the bring-up from a cold /dev/tee0 to a calibrated sensor, plus the
enrol and verify loops as methods that take a cancel flag and progress
callbacks. Worker is a job queue on a pthread with an 8 MiB stack -- musl's
default is 128 KiB and the session keeps request buffers on the stack. Results
come back through g_idle_add so signals are emitted on the thread that owns
the connection.

net.reactivated.Fprint is implemented rather than wrapped: Manager with
GetDevices/GetDefaultDevice, Device with Claim/Release, EnrollStart/Stop,
VerifyStart/Stop, ListEnrolledFingers and the three Delete variants, the three
signals, and the five properties. Owning fprintd's name is what lets
pam_fprintd, the Plasma KCM and fprintd-enroll work unmodified.

Two honest limits. Authorisation is the conservative rule -- you may act on
your own prints, root on anyone's -- because polkit is not in this milestone.
And DeleteEnrolledFingers removes the finger's NAME only: FF_CMD_TA_REMOVE
exists but its payload is not reverse-engineered, and guessing at a command
that writes to the store is exactly how an index got invalidated earlier
today. A deleted finger loses its name and stops being offered; its template
still occupies a slot in the group. Logged as such.

The finger-name map is written per user under the state directory, tmp-file
and rename. An enrolment records the fid the trustlet reported in the touch
event's response; if none was reported the finger cannot be named yet, and
the daemon says so rather than inventing one.

Verified on the phone as a systemd unit: owns the bus name, init chain
complete, floor calibrated, ready.
2026-09-02 22:10:51 +02:00
9b03329aa0 The RPMB result frame belongs in the shared buffer
SAVE_DATA now returns rc=0: 24 gpfile writes, 13 RPMB writes, no rollback.

The last fault was collecting the RPMB result frame into a local array. QTEE
reads it at req + req[0x0c] -- the same place the request frames were -- so
into a local means QTEE never sees the device's answer, fails the whole
transaction with an I/O error, and rolls back, having already committed the
counter. The reference passes the shared buffer as both source and result
destination for exactly this reason.

Also: req+0x14 is not always a usable chunk size. The reference falls back to
the whole block count when it is zero or exceeds nblocks, and refusing instead
aborts a legitimate write.

--cal-save drives a calibration save, which writes a real container through the
entire storage stack and needs NO FINGER. Three faults were found and fixed
with it in minutes, each of which would otherwise have cost a person ten
press-and-lift cycles to reach.

A process note worth more than the code. An earlier attempt at this appeared to
die mid-transaction; it did, and I killed it -- piping the phone's output
through `head` closed the pipe, SIGPIPE travelled back through tee, and the
daemon was terminated during an RPMB write sequence. That is precisely the
state the journal warns leaves a store inconsistent with a counter that cannot
be moved back. Never truncate a long-running device command's output; let it
finish and read its transcript.
2026-09-02 21:48:04 +02:00
3768c2e8b4 Create a container's parent directory on write
A store with no enrolments has no group directory, and open(O_CREAT) creates
the file but never its parent. A first enrolment into a fresh store therefore
failed with ENOENT, which QTEE reports as an I/O error -- indistinguishable
from a real storage fault, and the same -5 a refused RPMB write produces.
2026-09-02 21:09:44 +02:00
cc079cd1f8 Implement the RPMB write path, which was never there
An enrolment collected all ten samples and then SAVE_DATA answered -5. The
cause was not the sensor or the storage framing: ServeRpmb only ever
implemented Op::Read. A write fell through the branch with rc still -1 and was
refused, whatever --rpmb-write said. QTEE could not commit the anti-rollback
record, so it rolled the transaction back -- after it had already rewritten the
group's index container on disk.

The write sequence is per chunk: the data frames out, a Result Read Request
out, the result frame back. A remainder is refused rather than partially
committed, and a non-zero device result aborts instead of continuing into
further chunks, because at that point the counter state is not what we think it
is.

The refusal was not the only failure. Two assumptions were wrong and both are
recorded in the journal:

--group-path does NOT isolate the group directory. The writes went to the
Android group, the one holding the working template, not to a new group derived
from the namespace path. Isolation has to come from pointing the SFS root at a
separate tree, not from the namespace key.

And the rolled-back transaction left the index rewritten, so QTEE rejected it
and the template became unreachable -- ENUMERATE 0, and repeated unlink
attempts refused only because the mount had been switched back to read-only.
Restoring the index from the pre-enrolment backup brought it back: templates
loaded 1.

The RPMB counter never moved, which is why restoring an older index worked at
all. Had the write path been implemented, it would have.
2026-09-02 21:06:51 +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
0484b8437e Acknowledge the event state after reporting, not only before
A correct-finger run matched on frame 1 -- twice, on both the touch and the
image-ready event, with the right gid and fid -- and then answered "not
identified yet" for the remaining 39 frames without ever producing another
verdict. The matcher was never the problem; our loop wedged after the first
result.

The reference frame loop is {QUERY_EVENT_STATUS, CAPTURE_IMAGE, REPORT_EVENT,
QUERY_EVENT_STATUS, REPORT_EVENT}. Ours queried only at the top of the frame.
QUERY_EVENT_STATUS answers in rc -- 5 while an event is pending, 0 once
REPORT_EVENT has consumed it -- so the trailing query is what acknowledges the
trustlet's event state before the next frame. Without it the state is never
cleared and every later frame is refused.

Both status values are now printed per frame, so the state machine is visible
rather than inferred.

This also explains the wrong-finger control reading as 40 rescans and no
rejection: a session that never resolves has nothing to acknowledge, so it
looked the same either way and told us less than it appeared to.
2026-09-02 19:32:08 +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
a8c989857a Write a timestamped transcript per run
A run whose result nobody recorded is a run that has to be repeated on a
human's finger, and this daemon printed to stdout and nowhere else. Two real
authentication runs -- an enrolled finger and a wrong-finger control -- were
performed and their output is simply gone.

A single shared log path would be worse than none: the next run, including a
quick control, overwrites the interesting one. That very nearly cost this
project the transcript of its first successful authentication, which is why
the harness moved to per-run files.

Teeing is done at the file-descriptor level rather than by wrapping a stream.
std::println writes to stdout through C stdio, so an ostream wrapper captures
nothing; routing fd 1 through tee catches every line, including whatever the
library prints.
2026-09-02 19:11:41 +02:00
c33076ca9b Add the authentication loop
Arms a scan session and drives the frame loop: capture, decide finger from the
calibrated floor, report the touch edges, classify the verdict.

It needs no writes of any kind -- no SAVE_DATA, no RPMB write, no SFS write --
so it runs safely against an existing template with the store read-only. That
is what makes it the right thing to try before enrolment rather than after.

Verified armed on the phone: the template loads, the floor calibrates, and
AUTHENTICATE returns rc=0, which also proves the gid agrees with the one
SET_ACTIVE_GROUP used (a mismatch answers -200). With no finger present the
loop correctly reports nothing: no touch edge, no event, no terminal frame.

The fid field is poisoned before every REPORT_EVENT, because a zero-initialised
buffer cannot distinguish "the matcher never ran" from "the matcher ran and
rejected" -- the failure path writes zero there too.

The tally reports terminal frames as the denominator and presses separately,
so a run cannot be read as having rejections it did not have.
2026-09-02 18:48:44 +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
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