Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Make biometric auth protection work in Android (#771)
Leendert de Borst46d9709dcf61
diff --git a/mobile-app/android/CREDENTIAL_MANAGER_README.md b/mobile-app/android/CREDENTIAL_MANAGER_README.mdnew file mode 100644index 000000000..b38f27846--- /dev/null+++ b/mobile-app/android/CREDENTIAL_MANAGER_README.md@@ -0,0 +1,54 @@+# Android CredentialManager Implementation++This document describes how the Android implementation of the CredentialManager works.++## Overview++The Android implementation uses the Android Keystore system to securely store and retrieve encryption keys for credentials. It also leverages the BiometricPrompt API to require user authentication for sensitive operations.++## Key Components++1. **CredentialManagerModule**: React Native bridge module exposing JS methods for credential management.+2. **SharedCredentialStore**: Core class handling secure storage and retrieval of credentials.+3. **Credential**: Simple model class representing a credential.+4. **CredentialManagerPackage**: Package registration for React Native.++## Security Features++- **AES-256 Encryption**: All credentials are encrypted using AES-256 in GCM mode.+- **Biometric Authentication**: User must authenticate with fingerprint/face/PIN to access credentials.+- **Android Keystore**: Encryption keys are stored in the Android Keystore system, making them hardware-backed on supported devices.+- **Secure Preferences**: IVs (Initialization Vectors) are stored in SharedPreferences.++## Biometric Authentication++The implementation requires biometric authentication for:+- Adding credentials+- Retrieving credentials++The user will be prompted with a biometric dialog when performing these operations.++## Key Technical Details++- The encryption key is generated with a 30-second authentication validity period, which means once the user authenticates, they won't need to authenticate again for 30 seconds.+- Each credential operation creates a new BiometricPrompt and requires fresh authentication.+- The user can cancel the authentication if desired.+- **Main Thread Requirement**: BiometricPrompt must be shown on the main UI thread. We handle this by using `activity.runOnUiThread()` in the SharedCredentialStore and `UiThreadUtil.runOnUiThread()` in the CredentialManagerModule.++## Troubleshooting++If you encounter any of these common issues:++1. **IllegalBlockSizeException**: This typically means the authentication failed or was canceled. The user should be prompted to authenticate again.++2. **Activity not available**: The biometric prompt requires a FragmentActivity. Ensure your React Native app is using a compatible activity.++3. **Biometric hardware not available**: Some devices may not have biometric hardware. The implementation should gracefully fail with an appropriate error message.++4. **IllegalStateException: Must be called from main thread of fragment host**: This indicates that BiometricPrompt was not shown on the main UI thread. The current implementation handles this by ensuring all UI operations happen on the main thread.++## Compatibility++- Minimum SDK: 24 (Android 7.0)+- Required Permissions: USE_BIOMETRIC (added to AndroidManifest.xml)+- Required Dependencies: androidx.biometric:biometric:1.1.0 (added to build.gradle)\ No newline at end of filediff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.java b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.javaindex f49de1408..d95b83737 100644--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.java+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/CredentialManagerModule.java@@ -1,15 +1,23 @@package net.aliasvault.app.credentialmanager;+import android.app.Activity;import android.util.Log;+import androidx.annotation.NonNull;+import androidx.fragment.app.FragmentActivity;+import com.facebook.react.bridge.Arguments;import com.facebook.react.bridge.Promise;import com.facebook.react.bridge.ReactApplicationContext;import com.facebook.react.bridge.ReactContextBaseJavaModule;import com.facebook.react.bridge.ReactMethod;+import com.facebook.react.bridge.UiThreadUtil;import com.facebook.react.bridge.WritableArray;import com.facebook.react.bridge.WritableMap;+import org.json.JSONArray;+import org.json.JSONObject;+import java.util.List;public class CredentialManagerModule extends ReactContextBaseJavaModule {@@ -26,43 +34,102 @@ public class CredentialManagerModule extends ReactContextBaseJavaModule {return "CredentialManager";}- @ReactMethod- public void addCredential(String username, String password, String service, Promise promise) {- try {- SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);- Credential credential = new Credential(username, password, service);- store.addCredential(credential);- promise.resolve(true);- } catch (Exception e) {- Log.e(TAG, "Error adding credential", e);- promise.reject("ERR_ADD_CREDENTIAL", "Failed to add credential: " + e.getMessage(), e);+ private FragmentActivity getFragmentActivity() {+ Activity activity = getCurrentActivity();+ if (activity instanceof FragmentActivity) {+ return (FragmentActivity) activity;}+ return null;}@ReactMethod- public void getCredentials(Promise promise) {- try {- SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);- List<Credential> credentials = store.getAllCredentials();-- WritableArray credentialsArray = Arguments.createArray();- for (Credential credential : credentials) {- WritableMap credentialMap = Arguments.createMap();- credentialMap.putString("username", credential.getUsername());- credentialMap.putString("password", credential.getPassword());- credentialMap.putString("service", credential.getService());- credentialsArray.pushMap(credentialMap);+ public void addCredential(final String username, final String password, final String service, final Promise promise) {+ UiThreadUtil.runOnUiThread(new Runnable() {+ @Override+ public void run() {+ try {+ FragmentActivity activity = getFragmentActivity();+ if (activity == null) {+ promise.reject("ERR_ACTIVITY", "Activity is not available");+ return;+ }++ SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);+ Credential credential = new Credential(username, password, service);++ store.addCredentialWithBiometricAuth(activity, credential, new SharedCredentialStore.CryptoOperationCallback() {+ @Override+ public void onSuccess(String result) {+ promise.resolve(true);+ }++ @Override+ public void onError(Exception e) {+ Log.e(TAG, "Error adding credential", e);+ promise.reject("ERR_ADD_CREDENTIAL", "Failed to add credential: " + e.getMessage(), e);+ }+ });+ } catch (Exception e) {+ Log.e(TAG, "Error preparing to add credential", e);+ promise.reject("ERR_ADD_CREDENTIAL", "Failed to prepare adding credential: " + e.getMessage(), e);+ }}-- promise.resolve(credentialsArray);- } catch (Exception e) {- Log.e(TAG, "Error getting credentials", e);- promise.reject("ERR_GET_CREDENTIALS", "Failed to get credentials: " + e.getMessage(), e);- }+ });+ }++ @ReactMethod+ public void getCredentials(final Promise promise) {+ UiThreadUtil.runOnUiThread(new Runnable() {+ @Override+ public void run() {+ try {+ FragmentActivity activity = getFragmentActivity();+ if (activity == null) {+ promise.reject("ERR_ACTIVITY", "Activity is not available");+ return;+ }++ SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);++ store.getAllCredentialsWithBiometricAuth(activity, new SharedCredentialStore.CryptoOperationCallback() {+ @Override+ public void onSuccess(String jsonString) {+ try {+ JSONArray jsonArray = new JSONArray(jsonString);+ WritableArray credentialsArray = Arguments.createArray();++ for (int i = 0; i < jsonArray.length(); i++) {+ JSONObject jsonObject = jsonArray.getJSONObject(i);+ WritableMap credentialMap = Arguments.createMap();+ credentialMap.putString("username", jsonObject.getString("username"));+ credentialMap.putString("password", jsonObject.getString("password"));+ credentialMap.putString("service", jsonObject.getString("service"));+ credentialsArray.pushMap(credentialMap);+ }++ promise.resolve(credentialsArray);+ } catch (Exception e) {+ Log.e(TAG, "Error parsing credentials", e);+ promise.reject("ERR_PARSE_CREDENTIALS", "Failed to parse credentials: " + e.getMessage(), e);+ }+ }++ @Override+ public void onError(Exception e) {+ Log.e(TAG, "Error getting credentials", e);+ promise.reject("ERR_GET_CREDENTIALS", "Failed to get credentials: " + e.getMessage(), e);+ }+ });+ } catch (Exception e) {+ Log.e(TAG, "Error preparing to get credentials", e);+ promise.reject("ERR_GET_CREDENTIALS", "Failed to prepare getting credentials: " + e.getMessage(), e);+ }+ }+ });}@ReactMethod- public void clearCredentials(Promise promise) {+ public void clearCredentials(final Promise promise) {try {SharedCredentialStore store = SharedCredentialStore.getInstance(reactContext);store.clearAllCredentials();diff --git a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.java b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.javaindex 35cc3623a..596116ed6 100644--- a/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.java+++ b/mobile-app/android/app/src/main/java/net/aliasvault/app/credentialmanager/SharedCredentialStore.java@@ -7,6 +7,9 @@ import android.security.keystore.KeyProperties;import android.util.Base64;import android.util.Log;+import androidx.biometric.BiometricPrompt;+import androidx.fragment.app.FragmentActivity;+import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;@@ -15,6 +18,8 @@ import java.nio.charset.StandardCharsets;import java.security.KeyStore;import java.util.ArrayList;import java.util.List;+import java.util.concurrent.Executor;+import java.util.concurrent.Executors;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;@@ -33,6 +38,12 @@ public class SharedCredentialStore {private final Context appContext;private SecretKey cachedEncryptionKey;+ // Interface for crypto operations that need biometric auth+ public interface CryptoOperationCallback {+ void onSuccess(String result);+ void onError(Exception e);+ }+private SharedCredentialStore(Context context) {this.appContext = context.getApplicationContext();}@@ -72,6 +83,8 @@ public class SharedCredentialStore {.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).setKeySize(256).setUserAuthenticationRequired(true)+ // This is critical: set validation timeout to prevent requiring auth for each operation+ .setUserAuthenticationValidityDurationSeconds(30).build();keyGenerator.init(keyGenParameterSpec);@@ -90,63 +103,225 @@ public class SharedCredentialStore {+ KeyProperties.ENCRYPTION_PADDING_NONE);}- private String encrypt(String data) throws Exception {- SecretKey key = getOrCreateEncryptionKey();- Cipher cipher = getCipher();- cipher.init(Cipher.ENCRYPT_MODE, key);-- byte[] iv = cipher.getIV();- byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));-- // Store IV in SharedPreferences- SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- prefs.edit().putString(CREDENTIALS_KEY + IV_SUFFIX, Base64.encodeToString(iv, Base64.DEFAULT)).apply();-- return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);+ public void encryptWithBiometricAuth(final FragmentActivity activity, final String data, final CryptoOperationCallback callback) {+ try {+ final SecretKey key = getOrCreateEncryptionKey();+ final Cipher cipher = getCipher();+ cipher.init(Cipher.ENCRYPT_MODE, key);++ // Create biometric prompt+ final Executor executor = Executors.newSingleThreadExecutor();+ final BiometricPrompt.AuthenticationCallback authCallback = new BiometricPrompt.AuthenticationCallback() {+ @Override+ public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {+ try {+ // Get the authenticated cipher+ Cipher authenticatedCipher = result.getCryptoObject().getCipher();++ // Perform encryption+ byte[] iv = authenticatedCipher.getIV();+ byte[] encryptedBytes = authenticatedCipher.doFinal(data.getBytes(StandardCharsets.UTF_8));++ // Store IV in SharedPreferences+ SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);+ prefs.edit().putString(CREDENTIALS_KEY + IV_SUFFIX, Base64.encodeToString(iv, Base64.DEFAULT)).apply();++ callback.onSuccess(Base64.encodeToString(encryptedBytes, Base64.DEFAULT));+ } catch (Exception e) {+ callback.onError(e);+ }+ }++ @Override+ public void onAuthenticationError(int errorCode, CharSequence errString) {+ callback.onError(new Exception("Authentication error: " + errString));+ }++ @Override+ public void onAuthenticationFailed() {+ callback.onError(new Exception("Authentication failed"));+ }+ };++ // Show biometric prompt on main thread+ activity.runOnUiThread(new Runnable() {+ @Override+ public void run() {+ try {+ BiometricPrompt biometricPrompt = new BiometricPrompt(activity, executor, authCallback);++ // Show biometric prompt+ BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()+ .setTitle("Authenticate to Secure Credentials")+ .setSubtitle("Authentication is required to securely store credentials")+ .setNegativeButtonText("Cancel")+ .build();++ biometricPrompt.authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher));+ } catch (Exception e) {+ callback.onError(e);+ }+ }+ });++ } catch (Exception e) {+ callback.onError(e);+ }}- private String decrypt(String encryptedData) throws Exception {- SecretKey key = getOrCreateEncryptionKey();- Cipher cipher = getCipher();-- // Get IV from SharedPreferences- SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- String ivString = prefs.getString(CREDENTIALS_KEY + IV_SUFFIX, null);- if (ivString == null) {- throw new Exception("IV not found for decryption");+ public void decryptWithBiometricAuth(final FragmentActivity activity, final String encryptedData, final CryptoOperationCallback callback) {+ try {+ final SecretKey key = getOrCreateEncryptionKey();+ final Cipher cipher = getCipher();++ // Get IV from SharedPreferences+ SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);+ String ivString = prefs.getString(CREDENTIALS_KEY + IV_SUFFIX, null);+ if (ivString == null) {+ callback.onError(new Exception("IV not found for decryption"));+ return;+ }++ byte[] iv = Base64.decode(ivString, Base64.DEFAULT);+ GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, iv);+ cipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);++ // Create biometric prompt+ final Executor executor = Executors.newSingleThreadExecutor();+ final BiometricPrompt.AuthenticationCallback authCallback = new BiometricPrompt.AuthenticationCallback() {+ @Override+ public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {+ try {+ // Get the authenticated cipher+ Cipher authenticatedCipher = result.getCryptoObject().getCipher();++ // Perform decryption+ byte[] encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT);+ byte[] decryptedBytes = authenticatedCipher.doFinal(encryptedBytes);+ String decryptedData = new String(decryptedBytes, StandardCharsets.UTF_8);++ callback.onSuccess(decryptedData);+ } catch (Exception e) {+ callback.onError(e);+ }+ }++ @Override+ public void onAuthenticationError(int errorCode, CharSequence errString) {+ callback.onError(new Exception("Authentication error: " + errString));+ }++ @Override+ public void onAuthenticationFailed() {+ callback.onError(new Exception("Authentication failed"));+ }+ };++ // Show biometric prompt on main thread+ activity.runOnUiThread(new Runnable() {+ @Override+ public void run() {+ try {+ BiometricPrompt biometricPrompt = new BiometricPrompt(activity, executor, authCallback);++ // Show biometric prompt+ BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()+ .setTitle("Authenticate to Access Credentials")+ .setSubtitle("Authentication is required to access your credentials")+ .setNegativeButtonText("Cancel")+ .build();++ biometricPrompt.authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher));+ } catch (Exception e) {+ callback.onError(e);+ }+ }+ });++ } catch (Exception e) {+ callback.onError(e);}-- byte[] iv = Base64.decode(ivString, Base64.DEFAULT);- byte[] encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT);-- GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, iv);- cipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);-- byte[] decryptedBytes = cipher.doFinal(encryptedBytes);- return new String(decryptedBytes, StandardCharsets.UTF_8);}- public List<Credential> getAllCredentials() throws Exception {+ public void getAllCredentialsWithBiometricAuth(final FragmentActivity activity, final CryptoOperationCallback callback) {SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- String encryptedData = prefs.getString(CREDENTIALS_KEY, null);+ final String encryptedData = prefs.getString(CREDENTIALS_KEY, null);if (encryptedData == null) {- return new ArrayList<>();+ try {+ callback.onSuccess(new JSONArray().toString());+ } catch (Exception e) {+ callback.onError(e);+ }+ return;}- String decryptedData = decrypt(encryptedData);- return parseCredentialsFromJson(decryptedData);+ decryptWithBiometricAuth(activity, encryptedData, new CryptoOperationCallback() {+ @Override+ public void onSuccess(String decryptedData) {+ callback.onSuccess(decryptedData);+ }++ @Override+ public void onError(Exception e) {+ callback.onError(e);+ }+ });}- public void addCredential(Credential credential) throws Exception {- List<Credential> credentials = getAllCredentials();- credentials.add(credential);-- String jsonData = credentialsToJson(credentials);- String encryptedData = encrypt(jsonData);-- SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);- prefs.edit().putString(CREDENTIALS_KEY, encryptedData).apply();+ public void addCredentialWithBiometricAuth(final FragmentActivity activity, final Credential credential, final CryptoOperationCallback callback) {+ getAllCredentialsWithBiometricAuth(activity, new CryptoOperationCallback() {+ @Override+ public void onSuccess(String result) {+ try {+ List<Credential> credentials = parseCredentialsFromJson(result);+ credentials.add(credential);++ String jsonData = credentialsToJson(credentials);+ encryptWithBiometricAuth(activity, jsonData, new CryptoOperationCallback() {+ @Override+ public void onSuccess(String encryptedData) {+ SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);+ prefs.edit().putString(CREDENTIALS_KEY, encryptedData).apply();+ callback.onSuccess("Credential added successfully");+ }++ @Override+ public void onError(Exception e) {+ callback.onError(e);+ }+ });+ } catch (Exception e) {+ callback.onError(e);+ }+ }++ @Override+ public void onError(Exception e) {+ // If there's an error getting credentials (might be first use), create a new list+ try {+ List<Credential> credentials = new ArrayList<>();+ credentials.add(credential);++ String jsonData = credentialsToJson(credentials);+ encryptWithBiometricAuth(activity, jsonData, new CryptoOperationCallback() {+ @Override+ public void onSuccess(String encryptedData) {+ SharedPreferences prefs = appContext.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);+ prefs.edit().putString(CREDENTIALS_KEY, encryptedData).apply();+ callback.onSuccess("Credential added successfully");+ }++ @Override+ public void onError(Exception e) {+ callback.onError(e);+ }+ });+ } catch (Exception ex) {+ callback.onError(ex);+ }+ }+ });}public void clearAllCredentials() {@@ -174,6 +349,11 @@ public class SharedCredentialStore {private List<Credential> parseCredentialsFromJson(String json) throws JSONException {List<Credential> credentials = new ArrayList<>();++ if (json == null || json.isEmpty()) {+ return credentials;+ }+JSONArray jsonArray = new JSONArray(json);for (int i = 0; i < jsonArray.length(); i++) {