tom_biometric_storage 6.0.0-dev.10+tom.1
tom_biometric_storage: ^6.0.0-dev.10+tom.1 copied to clipboard
The Tom Framework's fork of biometric_storage: an encrypted data store secured by the OS's biometric check, with Windows Hello (key-bound) and a gate-only macOS form for ad-hoc signed apps, and tom_co [...]
tom_biometric_storage #
The Tom Framework's fork of biometric_storage (MIT, Copyright 2019 Herbert Poul; the licence is kept as it is). It is the upstream package with Windows Hello (key-bound), a gate-only form for ad-hoc signed macOS apps, and
lib/tom_gated_secret_store.dart: theTomGatedSecretStoreoftom_core_storageover it, which the Tom Secrets Manager's OS unlock uses. The Windows Hello and macOS changes are offered upstream; the package name and the adapter are this fork's own. Importpackage:tom_biometric_storage/tom_biometric_storage.dart(or.../biometric_storage.dart) and.../tom_gated_secret_store.dart.
biometric_storage #
Encrypted file store, optionally secured by biometric lock for Android, iOS, MacOS and partial support for Linux, Windows and Web.
Meant as a way to store small data in a hardware encrypted fashion. E.g. to store passwords, secret keys, etc. but not massive amounts of data.
- Android: Uses androidx with KeyStore.
- iOS and MacOS: LocalAuthentication with KeyChain. On macOS an app without
the
keychain-access-groupsentitlement (an ad-hoc signed build) cannot use the data-protection keychain;darwinKeyBoundAvailable()says so, andStorageFileInitOptions(darwinGateOnly: true)keeps the item in the login keychain behind a LocalAuthentication check instead. That is a weaker form: the check guards the read, but nothing binds the item to it. - Linux: Stores values in Keyring using libsecret. (No biometric authentication support).
- Windows: Uses wincred.h to read/write into the credential store.
With
StorageFileInitOptions(windowsHello: true)the value is sealed under a key bound to Windows Hello: each store has a Hello key credential (KeyCredentialManager), and the SHA-256 of its signature of a fixed challenge is the AES-256-GCM key, so the value does not open without passing Hello.canAuthenticate()answerssuccesswhere Hello is set up. - Web: Warning Uses unauthenticated, unencrypted storage in localStorage. If you have a better idea for secure storage on web platform, please open an Issue.
Check out AuthPass Password Manager for a app which makes heavy use of this plugin.
Getting Started #
Installation #
Android
Always required:
- API Level >= 23 (
android/app/build.gradleminSdkVersion 23)
Required only if you actually prompt for authentication, that is, if any
storage uses the default authenticationRequired: true. Storage created with
authenticationRequired: false never shows a BiometricPrompt, so neither of
the following applies to it:
-
MainActivity must extend
FlutterFragmentActivity.BiometricPromptneeds aFragmentActivityto host its dialog. If the plugin is attached to a plainFlutterActivityit logs an error and every authenticated read or write fails withAuthError:Failed— unauthenticated storage keeps working. -
The activity theme must descend from
Theme.AppCompat— but only for devices whereandroidx.biometricfalls back to drawing its own fingerprint dialog, which it builds withandroidx.appcompat.app.AlertDialog. That fallback is used below API 28, on API 28 devices without a fingerprint sensor, and on a short manufacturer allow-list where a crypto object forces it. From API 28 onwards the systemBiometricPromptis used and the theme does not matter.If you do need it:
android/app/src/main/AndroidManifest.xml:
<activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme"> [...] <meta-data android:name="io.flutter.embedding.android.NormalTheme" android:resource="@style/NormalTheme" /> </activity>android/app/src/main/res/values/styles.xml:
<resources> <style name="LaunchTheme" parent="Theme.AppCompat.NoActionBar"> ... </style> <style name="NormalTheme" parent="Theme.AppCompat.NoActionBar"> ... </style> </resources>
Logging
The plugin writes to android.util.Log under the tag BiometricStorage. A
debug build logs everything; a release build logs nothing below INFO until you
ask for it:
adb shell setprop log.tag.BiometricStorage VERBOSE
That suits reading logs off a device. If your app collects its own — a file
appender, a crash reporter, slf4j, Timber — install a sink instead, from
Application.onCreate or your FlutterActivity, before the first call into
the plugin:
import android.util.Log
import design.codeux.biometric_storage.BiometricStorageLogging
import org.slf4j.LoggerFactory
BiometricStorageLogging.sink =
BiometricStorageLogging.Sink { priority, tag, message, throwable ->
val log = LoggerFactory.getLogger(tag)
when (priority) {
Log.VERBOSE -> log.trace(message, throwable)
Log.DEBUG -> log.debug(message, throwable)
Log.INFO -> log.info(message, throwable)
Log.WARN -> log.warn(message, throwable)
else -> log.error(message, throwable)
}
}
Installing a sink turns every level on, since it says something wants the records. To decide the level yourself — including keeping verbose logging in a release build without touching a device property — set it explicitly:
BiometricStorageLogging.level = Log.VERBOSE
throwable is passed separately rather than flattened into message, so you
can hand the real exception to whatever you report to. The sink is called on
whichever thread produced the record, so it must be safe to call from the main
thread and from a background executor.
Resources
- https://developer.android.com/topic/security/data
- https://developer.android.com/topic/security/best-practices
iOS
- include the NSFaceIDUsageDescription key in your app’s Info.plist file
- Deployment target >= iOS 13 (below whatever Flutter itself requires, so in practice this never binds).
Known Issue: since iOS 15 the simulator seem to no longer support local authentication: https://developer.apple.com/forums/thread/685773
IosPromptInfo.saveTitle / accessTitle are invisible on Face ID devices.
Face ID authenticates against a HUD that shows its glyph and the words "Face ID"
and nothing else, and the "not recognized" alert after a failure offers only
retry and cancel. The strings do reach the system — they are set as
LAContext.localizedReason — but iOS does not draw them. Touch ID devices and
macOS do show them, so they are still worth setting.
Mac OS
- include the NSFaceIDUsageDescription key in your app’s Info.plist file
- enable keychain sharing and signing. (not sure why this is required. but without it
You will probably see an error like:
SecurityError, Error while writing data: -34018: A required entitlement isn't present.
- Deployment target >= macOS 10.15.
Swift Package Manager (iOS and Mac OS)
The iOS and macOS implementations ship both a Package.swift and a podspec, so
they work with either dependency manager. Adding this plugin to an app that has
migrated to Swift Package Manager
does not bring CocoaPods back — no Podfile is generated.
Usage #
You basically only need 4 methods.
- Check whether biometric authentication is supported by the device
final response = await BiometricStorage().canAuthenticate()
if (response != CanAuthenticateResponse.success) {
// panic..
}
- Create the access object
final storageFile = await BiometricStorage().getStorage('mystorage');
- Read data
final data = await storageFile.read();
- Write data
final myNewData = 'Hello World';
await storageFile.write(myNewData);
Storing without a biometric prompt — for a value a background task has to be able to refresh, for example — is
authenticationRequired: false. The value is still encrypted at rest; it is simply not gated behind an authentication.final storageFile = await BiometricStorage().getStorage( 'mystorage', options: StorageFileInitOptions(authenticationRequired: false), );
See also the API documentation: https://pub.dev/documentation/biometric_storage/latest/biometric_storage/BiometricStorageFile-class.html#instance-methods
What an authentication validity duration really means #
androidAuthenticationValidityDuration opens a window during which the
keystore will use the key without another prompt. Three things about that
window are easy to get wrong, and all three are the platform's doing rather
than this plugin's:
- It belongs to the user's last device authentication, not to your app. An unlock by PIN, pattern, password or a strong biometric renews it. A window you set to ten minutes can be renewed by the user unlocking their phone for something else entirely.
- It cannot be closed early. Android exposes no way to revoke an
authentication. Nothing in this package — not
dispose(), not a repeatgetStorage— shortens a window that is already open. - It is fixed when the key is created. A keystore key's authentication
parameters are set at creation and nothing recreates a key that already
exists, so passing a different duration later has no effect on a store that
has been written. See
dispose()'s documentation for what happens if you change it between a value andnull.
So if what you need is an authentication that cannot be inherited from an earlier one, do not set a duration. Use the pattern below.
The envelope pattern #
For: a prompt on every login, and the ability to rewrite the secret without one. This is the standing answer to #129, #108 and #112, which all arrive at a long validity duration and then run into the three points above.
Android and iOS/macOS only. The guarantee below is the OS enforcing an
access control, so it is worth exactly what the platform provides: on Linux
there is no biometric support, and on web both stores are unencrypted
localStorage, which puts the data key next to the ciphertext it protects and
raises no prompt at all. Branch on the platform rather than shipping this as
your only path.
Keep two stores instead of one:
- a gate that authenticates per use —
authenticationRequired: true, no validity duration, no darwin reuse duration — holding a random data key; - a token store with
authenticationRequired: false, holding your secret encrypted by your app under that data key.
// Login: one prompt, for the gate.
List<int>? key = base64Decode((await gate.read())!);
final secret = await decrypt(await token.read(), key); // your AEAD
// Rotate: no prompt at all — the key is already in memory.
await token.write(await encrypt(newSecret, key));
// Log out: drop the key. The next login must authenticate.
// Not zeroed in place: an in-flight rotate holds the same list, so zeroing it
// at the wrong moment seals the next secret under a key of zeros. The key also
// arrived as an immutable base64 String, so there is no erasing it anyway.
key = null;
What each half gives you, stated per platform rather than blended:
- Android: every gate read is a
BiometricPromptbound to aCryptoObjectover a per-use key. The keystore enforces it, there is no window to leak, and a device unlock does not help an attacker. - iOS and macOS: every gate read is a keychain access-control evaluation
with a fresh
LAContext. - The token store is plain ciphertext on disk. Its confidentiality comes from the data key in the gate, so use an authenticated cipher (AES-GCM, ChaCha20-Poly1305) — the file is deliberately unprotected, and a non-authenticated cipher would let anything that can write there change your plaintext by changing the ciphertext. Authentication detects that; it does not prevent the write, and it does not stop an older sealed value being put back, which was sealed by the same key. If a rollback matters to you, put a counter or a timestamp inside the plaintext.
What it costs #
A biometric enrollment change destroys the secret. This is the one to weigh
before adopting the pattern. The gate key is biometric-only, and both platforms
invalidate such a key when the enrolled set changes — on Android when a new
biometric is enrolled or the last one is removed, on iOS and macOS because the
item is stored under .biometryCurrentSet. The sealed token is then
undecryptable.
How you learn of it differs, and only Android tells you plainly. There the
plugin deletes the dead key and raises AuthExceptionCode.keyInvalidated, so
you can say "set your secret up again". On iOS and macOS the keychain reports
an item whose access control can never be satisfied with the same
errSecAuthFailed it uses for a failed attempt, so it arrives as
AuthExceptionCode.authFailed — indistinguishable from the user mistyping, and
it will keep arriving on every attempt. Plan for that: if a darwin login keeps
failing after a deliberate, successful re-authentication, treat the secret as
gone and re-enroll, because no signal is coming.
That is a failure the setup you are migrating from mostly does not have: a store with a validity duration allows the device credential as well, and keys like that survive an enrollment change. So the pattern trades a window you cannot close for a secret you can lose. For a refresh token that is a good trade — the user logs in again and you re-enroll. For a secret that cannot be regenerated, it is the wrong pattern unless you keep a recovery path outside it.
The rest: your app owns one piece of cryptography, and the data key sits in memory for the length of a session — which is where the plaintext secret already sat. Migrating from a single store means reading the old secret, writing both new stores, and only then deleting the old one, in that order, so that a crash part-way leaves the old store intact.
A working implementation is in
example/lib/envelope_example.dart, and
the integration suite exercises it against the real keystore on an Android
emulator, the real keychain on macOS, and real libsecret on Linux. Only the
Linux run happens in CI; the other two are local, so a regression on them would
not fail a build.
What none of it covers is the prompt. Under test the gate is unauthenticated, because no CI runner can perform a biometric gesture — so that a per-use gate raises a prompt on every read, which is the whole point of the pattern, remains the platform's behavior rather than something this repository proves.
