home

blog · 02

Turning a USB protocol into a real Linux login driver in Rust

8 min readsource
Contents5 sections

Scanning my finger in a terminal script proved the USB protocol worked, but every morning I still typed my password at the Ubuntu lock screen. I wanted to open the lid, touch the sensor, and land straight on the desktop.

Using OpenCode, I wrapped the USB protocol from Part 1 inside a Rust system daemon called elanprintd. Instead of patching Ubuntu's C fingerprint library, I slotted the daemon straight into the existing login chain. It guards against cross-user leaks and slot overwrites, survives laptop sleep, and runs 144 offline tests with no sensor plugged in.

Where a Linux fingerprint driver plugs in

When you unlock Ubuntu with a fingerprint, the lock screen never touches USB hardware itself. Authentication moves through four separate pieces:

  1. GDM, Ubuntu's login and lock screen manager, hands authentication to PAM using /etc/pam.d/gdm-fingerprint. Every Linux login service gets its own config file under /etc/pam.d/ listing which checks to run.
  2. PAM loads pam_fprintd.so, which sends D-Bus requests like Claim, VerifyStart, and EnrollStart over the system message bus to net.reactivated.Fprint.
  3. fprintd owns that service name and passes requests down to libfprint.
  4. Libfprint keeps a lookup table of supported USB IDs, sees 04f3:0c90 isn't listed, and stops there.
The broken fingerprint login chain on UbuntuThe broken fingerprint login chain on Ubuntu
Ubuntu ships everything down to fprintd. Because libfprint has no entry for 04f3:0c90, the chain stops there.

swipe sideways to see the whole diagram

My first instinct was to write a C driver inside libfprint. That meant learning GLib (libfprint's C event-loop framework) and rebuilding a custom package every time Ubuntu shipped an update.

Then a cleaner seam stood out. pam_fprintd.so has no idea libfprint exists; it only sends D-Bus messages to net.reactivated.Fprint. If I masked fprintd.service in systemd so nothing could start it by accident, and had elanprintd claim that D-Bus name instead, both GDM and the PAM stack would work without changing a single PAM config line.

elanprintd replacing fprintd and libfprintelanprintd replacing fprintd and libfprint
Owning net.reactivated.Fprint on D-Bus replaces fprintd and libfprint while keeping GDM and PAM unchanged.

swipe sideways to see the whole diagram

Claiming that D-Bus interface comes with one strict contract. pam_fprintd.so matches status strings inside VerifyStatus and EnrollStatus signals character for character, and a single typo hangs the login screen silently.

Worse, the status strings copied from the 0c4c reference (like enroll-retry-center-finger and verify-retry-scan-too-short) didn't exist in Ubuntu's installed fprintd 1.94.3 at all. Exporting the real D-Bus introspection XML from Ubuntu into docs/dbus-device.xml gave me the exact signal names ("verify-match", "enroll-stage-passed", "enroll-finger-not-centered") to target with zbus.

Isolating the protocol so tests need no hardware

Remember how enrollment froze in Part 1 when my early daemon read the wrong USB endpoint? Testing every fix against physical flash also risked overwriting prints or wearing out the chip. I needed a way to test the whole protocol in memory.

So I moved all packet encoding, response parsing, and the Enroll state machine into a standalone crate, elanprint-proto, with zero async runtime or USB dependencies. Each Command variant defines its wire bytes alongside its reply_endpoint(), expected_len(), and timeout(). When Enroll queues a step, the caller asks one method what to read next:

rust
pub fn pending_read(&self) -> Option<(ReplyEndpoint, usize, Duration)> {
    self.pending_command()
        .map(|c| (c.reply_endpoint(), c.expected_len(), c.timeout()))
}

Now callers never guess between 0x83 and 0x84. The same command definition that writes the bytes names the endpoint, byte length, and timeout.

Workspace crate architecture and fake-USB testingWorkspace crate architecture and fake-USB testing
Pure logic crates never touch USB; elanprintd swaps in Fake during unit tests instead of nusb.

swipe sideways to see the whole diagram

All USB access sits behind a small Transport trait. In production, Worker<T> plugs in elanprint-usb, which uses nusb (a pure-Rust USB library) directly against /dev/bus/usb. In tests, it plugs in Fake, an in-memory mock that records every outgoing packet and reply endpoint while replaying scripted responses.

Across the workspace, cargo test --workspace runs 144 offline tests in under a second with no sensor connected (plus 1 D-Bus client integration test in elanprint-login marked ignored).

Two bugs caused by the firmware

Once elanprintd ran as a background service across reboots, two of Part 1's firmware quirks turned into real bugs.

Accepting the wrong finger and any user's slot

The verify command (40 ff 03) matches a touch against every template in flash without knowing who asked. My first prototype passed the sensor's reply straight back to D-Bus.

With two fingers enrolled, I asked the daemon to verify right-index-finger, touched my left index finger by mistake, and watched it emit "verify-match" anyway. Worse, because templates survive OS reinstalls inside sensor flash, any print left by another local user or a past owner would have unlocked my session.

To close that hole, the daemon keeps a root-owned map at /var/lib/elanprint/prints.json linking usernames and finger names to slot numbers:

json
{ "prawesh": { "left-index-finger": 0, "right-index-finger": 1 } }

No biometric data ever hits disk. Before starting verify, the daemon builds an allowed lookup table for the claiming user: every slot they own when GDM asks for "any", or just one slot when a client names a specific finger. If the sensor returns any slot ID outside allowed, the daemon overrides it to "verify-no-match":

rust
match allowed.get(&id) {
    Some(name) => {
        sink.emit(OpEvent::VerifyFingerSelected {
            finger: name.clone(),
        })
        .await;
    }
    None => result = dbus::verify::NO_MATCH,
}

Slot filtering still fails if D-Bus callers can spoof who they are. Ubuntu's default net.reactivated.Fprint.conf lets any local user call Device methods, trusting fprintd to check polkit first.

Because elanprintd doesn't integrate with polkit yet, it asks the D-Bus daemon for the sender's verified Unix UID via GetConnectionUnixUser and resolves the target username with getent. Only UID 0 (used by GDM at the login screen) or that account's own UID can claim the sensor or touch that user's prints.

Filtering blind chip matches by caller UID and prints.jsonFiltering blind chip matches by caller UID and prints.json
The chip checks every template in flash. elanprintd rejects any matched slot the claiming user does not own.

swipe sideways to see the whole diagram

Losing slot 0, and the overwrite bug hiding behind it

In Part 1, finger_info answered 40 ff whether a slot held a print or sat empty, so Linux can never scan flash to learn which slots are occupied.

During an early test session, my enrolled right-index-finger template in slot 0 disappeared. The chip count dropped from 1 to 0, and prints.json had been overwritten with {}. Checking the logs showed an unguarded delete path had fired during testing (before UID checks and operation tokens protected delete), erasing both flash and the file.

Auditing the enrollment path right after uncovered an even nastier bug waiting to happen in free_slot. That function looped from slot 0 asking finger_info and prints.json which slot was free. Because 0c90 answers 40 ff for occupied and empty slots alike, starting from an empty JSON file (such as a fresh daemon install) meant free_slot always picked slot 0 and would overwrite a live fingerprint on the next enrollment.

When the host file and the hardware disagree, trust the hardware's count. Never let software state drive a flash erase or slot reuse.

Two structural guards now make both mistakes impossible:

  • writable_slots sets the chip's live enrolled_num count as a hard floor (count..=MAX_SLOT). Host prints.json can only exclude additional slots, and free_slot still skips any slot that ever returns a 70-byte finger_info record. If the chip says 1 print is stored, slot 0 stays off-limits even when prints.json is empty.
  • Worker::delete_finger requires a DeleteIntent token that only explicit user-triggered D-Bus delete handlers can build. Sync, error recovery, and enrollment code cannot construct an erase command at all, and unit tests over Fake assert that zero erase opcodes (40 ff 05, 40 ff 13, 40 ff 99) reach the wire when prints.json contradicts the chip.
Slot 0 overwrite bug and structural Rust guardsSlot 0 overwrite bug and structural Rust guards
Why free_slot could have overwritten slot 0, and how writable_slots plus DeleteIntent prevent both data-loss bugs.

swipe sideways to see the whole diagram

Surviving sleep, concurrent callers, and daily use

Turning a test script into a daily login daemon surfaced two concurrency and power bugs right away.

The first was a mutex deadlock. EnrollStart and VerifyStart spawn a background task that locks the worker mutex for up to 30 seconds while waiting for a finger touch. If a second tool tries to verify during that wait, blocking on the mutex freezes the caller instead of returning AlreadyInUse.

Worse, my desktop app queried the num-enroll-stages D-Bus property right after EnrollStart and before subscribing to EnrollStatus. Because the property getter also locked that worker mutex, the UI hung until timeout and missed every enrollment event while the sensor enrolled in the dark. Moving claimed and busy into an atomic OpState outside the worker mutex fixed both: property reads never block, and try_begin returns an OpToken guard that either fails immediately with AlreadyInUse or clears busy when dropped.

Mutex deadlock vs lock-free OpState atomicsMutex deadlock vs lock-free OpState atomics
Before: blocking on the USB worker mutex froze UI property reads and masked busy callers. After: atomic OpState answers immediately without locking.

swipe sideways to see the whole diagram

The second bug hit whenever I closed my laptop lid. Holding an open USB handle across suspend wedged the sensor on wake. Listening for systemd-logind's PrepareForSleep signal lets elanprintd cancel any active wait, send abort (40 ff 02) without waiting for a reply, and drop the USB handle before sleep. On wake, the next Claim reopens the device lazily (avoiding races with USB re-enumeration) and re-arms the chip.

I also built an egui desktop app (elanprint-rs) for enrolling, deleting, and testing fingers (kept strictly separate from PAM authentication), and packaged the workspace into an amd64 .deb installer. Installing the package sets up the systemd service, masks fprintd.service, and drops a udev rule tagged with uaccess so the active seat user can access the sensor when debugging without root.

The elanprint-rs desktop app enrolling a finger
The egui app tracks each of the eight enrollment scans over D-Bus.

Real hardware results

On Ubuntu 24.04.4 with firmware 1.8, kernel 7.0.0-31-generic, and GNOME 46, both GDM greeter login and lock-screen unlock worked across full reboots:

CheckResult
Enroll a finger8 touches, commit saved in 102 to 103 ms
Verify a known finger10 of 10 matched, plus 5 of 5 later on a second finger
Reject an unknown finger10 of 10 no-match, zero retries
Two fingersLeft index matched slot 0, right index matched slot 1
After a cold rebootenrolled_num read 40 01 before any touch, and the print matched again
Login and lock screenBoth unlock via gdm-fingerprint

(Everyday fingerprint login keeps working on my current Ubuntu 26.04.1 setup too, though I haven't repeated those timed counts there.)

On that first working morning, I flipped open the lid, tapped the sensor, and landed straight on the desktop. Five seconds later, a dialog popped up asking for my account password anyway so GNOME could read my saved Wi-Fi credentials. That wasn't an ELAN or USB bug at all. In Part 3, I traced that prompt to GNOME Keyring and solved it with a TPM-sealed key and a fail-open Rust PAM module.

Source code and .deb releases live at github.com/prawesh-12/elanprint-rs.