fix: CipherDatabase listener and rename advanced unlock in device unlock

This commit is contained in:
J-Jamet committed 2025-08-22 22:05:51 +02:00
1 parent c4cbd2e587
commit 82af9bada2
75 files changed
+1158 -1118

No files matched your search

@@ -73,7 +73,7 @@ import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.DATABASE_URI_KEY
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.MAIN_CREDENTIAL_KEY
import com.kunzisoft.keepass.services.DatabaseTaskNotificationService.Companion.READ_ONLY_KEY
import com.kunzisoft.keepass.settings.AdvancedUnlockSettingsActivity
import com.kunzisoft.keepass.settings.DeviceUnlockSettingsActivity
import com.kunzisoft.keepass.settings.AppearanceSettingsActivity
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.tasks.ActionRunnable
@@ -97,7 +97,7 @@ class MainCredentialActivity : DatabaseModeActivity() {
private var toolbar: Toolbar? = null
private var filenameView: TextView? = null
private var logotypeButton: View? = null
private var advancedUnlockButton: View? = null
private var deviceUnlockButton: View? = null
private var mainCredentialView: MainCredentialView? = null
private var confirmButtonView: Button? = null
private var infoContainerView: ViewGroup? = null
@@ -138,7 +138,7 @@ class MainCredentialActivity : DatabaseModeActivity() {
filenameView = findViewById(R.id.filename)
logotypeButton = findViewById(R.id.activity_password_logotype)
advancedUnlockButton = findViewById(R.id.fragment_advanced_unlock_container_view)
deviceUnlockButton = findViewById(R.id.fragment_device_unlock_container_view)
mainCredentialView = findViewById(R.id.activity_password_credentials)
confirmButtonView = findViewById(R.id.activity_password_open_button)
infoContainerView = findViewById(R.id.activity_password_info_container)
@@ -268,14 +268,14 @@ class MainCredentialActivity : DatabaseModeActivity() {
// Init Biometric elements only if allowed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& PreferencesUtil.isAdvancedUnlockEnable(this)) {
&& PreferencesUtil.isDeviceUnlockEnable(this)) {
deviceUnlockFragment = supportFragmentManager
.findFragmentByTag(UNLOCK_FRAGMENT_TAG) as? DeviceUnlockFragment?
if (deviceUnlockFragment == null) {
deviceUnlockFragment = DeviceUnlockFragment().also {
supportFragmentManager.commit {
replace(
R.id.fragment_advanced_unlock_container_view,
R.id.fragment_device_unlock_container_view,
it,
UNLOCK_FRAGMENT_TAG
)
@@ -665,14 +665,14 @@ class MainCredentialActivity : DatabaseModeActivity() {
val biometricCanAuthenticate = DeviceUnlockManager.canAuthenticate(this)
if ((biometricCanAuthenticate == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED
|| biometricCanAuthenticate == BiometricManager.BIOMETRIC_SUCCESS)
&& advancedUnlockButton != null) {
&& deviceUnlockButton != null) {
mPasswordActivityEducation.checkAndPerformedBiometricEducation(
advancedUnlockButton!!,
deviceUnlockButton!!,
{
startActivity(
Intent(
this,
AdvancedUnlockSettingsActivity::class.java
DeviceUnlockSettingsActivity::class.java
)
)
},
@@ -28,9 +28,10 @@ import android.os.IBinder
import android.util.Base64
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.kunzisoft.keepass.database.element.binary.BinaryData.Companion.BASE64_FLAG
import com.kunzisoft.keepass.model.CipherEncryptDatabase
import com.kunzisoft.keepass.services.AdvancedUnlockNotificationService
import com.kunzisoft.keepass.services.DeviceUnlockNotificationService
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.utils.IOActionTask
import com.kunzisoft.keepass.utils.SingletonHolderParameter
@@ -43,19 +44,19 @@ class CipherDatabaseAction(context: Context) {
AppDatabase.getDatabase(applicationContext).cipherDatabaseDao()
// Temp DAO to easily remove content if object no longer in memory
private var useTempDao = PreferencesUtil.isTempAdvancedUnlockEnable(applicationContext)
private var useTempDao = PreferencesUtil.isTempDeviceUnlockEnable(applicationContext)
private var mBinder: AdvancedUnlockNotificationService.AdvancedUnlockBinder? = null
private var mBinder: DeviceUnlockNotificationService.DeviceUnlockBinder? = null
private var mServiceConnection: ServiceConnection? = null
private var mDatabaseListeners = LinkedList<CipherDatabaseListener>()
private var mAdvancedUnlockBroadcastReceiver = AdvancedUnlockNotificationService.AdvancedUnlockReceiver {
private var mDeviceUnlockBroadcastReceiver = DeviceUnlockNotificationService.DeviceUnlockReceiver {
deleteAll()
removeAllDataAndDetach()
}
fun reloadPreferences() {
useTempDao = PreferencesUtil.isTempAdvancedUnlockEnable(applicationContext)
private fun reloadPreferences() {
useTempDao = PreferencesUtil.isTempDeviceUnlockEnable(applicationContext)
}
@Synchronized
@@ -70,15 +71,15 @@ class CipherDatabaseAction(context: Context) {
@Synchronized
private fun attachService(performedAction: () -> Unit) {
ContextCompat.registerReceiver(applicationContext, mAdvancedUnlockBroadcastReceiver,
ContextCompat.registerReceiver(applicationContext, mDeviceUnlockBroadcastReceiver,
IntentFilter().apply {
addAction(AdvancedUnlockNotificationService.REMOVE_ADVANCED_UNLOCK_KEY_ACTION)
addAction(DeviceUnlockNotificationService.REMOVE_DEVICE_UNLOCK_KEY_ACTION)
}, ContextCompat.RECEIVER_EXPORTED
)
mServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, serviceBinder: IBinder?) {
mBinder = (serviceBinder as AdvancedUnlockNotificationService.AdvancedUnlockBinder)
mBinder = (serviceBinder as DeviceUnlockNotificationService.DeviceUnlockBinder)
performedAction.invoke()
}
@@ -87,7 +88,7 @@ class CipherDatabaseAction(context: Context) {
}
}
try {
AdvancedUnlockNotificationService.bindService(applicationContext,
DeviceUnlockNotificationService.bindService(applicationContext,
mServiceConnection!!,
Context.BIND_AUTO_CREATE)
} catch (e: Exception) {
@@ -99,11 +100,11 @@ class CipherDatabaseAction(context: Context) {
@Synchronized
private fun detachService() {
try {
applicationContext.unregisterReceiver(mAdvancedUnlockBroadcastReceiver)
applicationContext.unregisterReceiver(mDeviceUnlockBroadcastReceiver)
} catch (_: Exception) {}
mServiceConnection?.let {
AdvancedUnlockNotificationService.unbindService(applicationContext, it)
DeviceUnlockNotificationService.unbindService(applicationContext, it)
}
}
@@ -123,23 +124,27 @@ class CipherDatabaseAction(context: Context) {
private fun onClear() {
mBinder = null
mServiceConnection = null
mDatabaseListeners.forEach {
it.onCipherDatabaseCleared()
mDatabaseListeners.forEach { listener ->
listener.onCipherDatabaseCleared()
}
}
interface CipherDatabaseListener {
fun onCipherDatabaseRetrieved(databaseUri: Uri, cipherDatabase: CipherEncryptDatabase?)
fun onCipherDatabaseAddedOrUpdated(cipherDatabase: CipherEncryptDatabase)
fun onCipherDatabaseDeleted(databaseUri: Uri)
fun onAllCipherDatabasesDeleted()
fun onCipherDatabaseCleared()
}
fun getCipherDatabase(databaseUri: Uri,
cipherDatabaseResultListener: (CipherEncryptDatabase?) -> Unit) {
cipherDatabaseResultListener: ((CipherEncryptDatabase?) -> Unit)? = null) {
if (useTempDao) {
serviceActionTask {
var cipherDatabase: CipherEncryptDatabase? = null
mBinder?.getCipherDatabase(databaseUri)?.let { cipherDatabaseEntity ->
cipherDatabase = CipherEncryptDatabase().apply {
this.databaseUri = Uri.parse(cipherDatabaseEntity.databaseUri)
this.databaseUri = cipherDatabaseEntity.databaseUri.toUri()
this.encryptedValue = Base64.decode(
cipherDatabaseEntity.encryptedValue,
BASE64_FLAG
@@ -150,7 +155,11 @@ class CipherDatabaseAction(context: Context) {
)
}
}
cipherDatabaseResultListener.invoke(cipherDatabase)
cipherDatabaseResultListener?.invoke(cipherDatabase) ?: run {
mDatabaseListeners.forEach { listener ->
listener.onCipherDatabaseRetrieved(databaseUri, cipherDatabase)
}
}
}
} else {
IOActionTask(
@@ -158,7 +167,7 @@ class CipherDatabaseAction(context: Context) {
cipherDatabaseDao.getByDatabaseUri(databaseUri.toString())
?.let { cipherDatabaseEntity ->
CipherEncryptDatabase().apply {
this.databaseUri = Uri.parse(cipherDatabaseEntity.databaseUri)
this.databaseUri = cipherDatabaseEntity.databaseUri.toUri()
this.encryptedValue = Base64.decode(
cipherDatabaseEntity.encryptedValue,
Base64.NO_WRAP
@@ -170,14 +179,18 @@ class CipherDatabaseAction(context: Context) {
}
}
},
{
cipherDatabaseResultListener.invoke(it)
{ cipherDatabase ->
cipherDatabaseResultListener?.invoke(cipherDatabase) ?: run {
mDatabaseListeners.forEach { listener ->
listener.onCipherDatabaseRetrieved(databaseUri, cipherDatabase)
}
}
}
).execute()
}
}
fun containsCipherDatabase(databaseUri: Uri?,
private fun containsCipherDatabase(databaseUri: Uri?,
contains: (Boolean) -> Unit) {
if (databaseUri == null) {
contains.invoke(false)
@@ -210,7 +223,11 @@ class CipherDatabaseAction(context: Context) {
// The only case to create service (not needed to get an info)
serviceActionTask(true) {
mBinder?.addOrUpdateCipherDatabase(cipherDatabaseEntity)
cipherDatabaseResultListener?.invoke()
cipherDatabaseResultListener?.invoke() ?: run {
mDatabaseListeners.forEach { listener ->
listener.onCipherDatabaseAddedOrUpdated(cipherEncryptDatabase)
}
}
}
} else {
IOActionTask(
@@ -225,7 +242,11 @@ class CipherDatabaseAction(context: Context) {
}
},
{
cipherDatabaseResultListener?.invoke()
cipherDatabaseResultListener?.invoke() ?: run {
mDatabaseListeners.forEach { listener ->
listener.onCipherDatabaseAddedOrUpdated(cipherEncryptDatabase)
}
}
}
).execute()
}
@@ -237,7 +258,11 @@ class CipherDatabaseAction(context: Context) {
if (useTempDao) {
serviceActionTask {
mBinder?.deleteByDatabaseUri(databaseUri)
cipherDatabaseResultListener?.invoke()
cipherDatabaseResultListener?.invoke() ?: run {
mDatabaseListeners.forEach { listener ->
listener.onCipherDatabaseDeleted(databaseUri)
}
}
}
} else {
IOActionTask(
@@ -245,10 +270,15 @@ class CipherDatabaseAction(context: Context) {
cipherDatabaseDao.deleteByDatabaseUri(databaseUri.toString())
},
{
cipherDatabaseResultListener?.invoke()
cipherDatabaseResultListener?.invoke() ?: run {
mDatabaseListeners.forEach { listener ->
listener.onCipherDatabaseDeleted(databaseUri)
}
}
}
).execute()
}
reloadPreferences()
}
fun deleteAll() {
@@ -263,8 +293,12 @@ class CipherDatabaseAction(context: Context) {
cipherDatabaseDao.deleteAll()
}
).execute()
mDatabaseListeners.forEach { listener ->
listener.onAllCipherDatabasesDeleted()
}
// Unbind
removeAllDataAndDetach()
reloadPreferences()
}
companion object : SingletonHolderParameter<CipherDatabaseAction, Context>(::CipherDatabaseAction) {
@@ -64,7 +64,7 @@ class DeviceUnlockFragment: Fragment() {
private var mBiometricPrompt: BiometricPrompt? = null
// Only to fix multiple fingerprint menu #332
private var mAllowAdvancedUnlockMenu = false
private var mAllowDeviceUnlockMenu = false
private var mDeviceCredentialResultLauncher: ActivityResultLauncher<Intent>? = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
@@ -95,8 +95,8 @@ class DeviceUnlockFragment: Fragment() {
private val menuProvider: MenuProvider = object: MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// biometric menu
if (mAllowAdvancedUnlockMenu)
menuInflater.inflate(R.menu.advanced_unlock, menu)
if (mAllowDeviceUnlockMenu)
menuInflater.inflate(R.menu.device_unlock, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
@@ -111,9 +111,9 @@ class DeviceUnlockFragment: Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val rootView = inflater.inflate(R.layout.fragment_advanced_unlock, container, false)
val rootView = inflater.inflate(R.layout.fragment_device_unlock, container, false)
mDeviceUnlockView = rootView.findViewById(R.id.advanced_unlock_view)
mDeviceUnlockView = rootView.findViewById(R.id.device_unlock_view)
return rootView
}
@@ -133,13 +133,15 @@ class DeviceUnlockFragment: Fragment() {
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
mDeviceUnlockViewModel.uiState.collect { uiState ->
// Change mode
toggleDeviceCredentialMode(uiState.newDeviceUnlockMode)
// Prompt
manageDeviceCredentialPrompt(uiState.cryptoPromptState)
// Advanced menu
mAllowAdvancedUnlockMenu = uiState.allowAdvancedUnlockMenu
activity?.invalidateOptionsMenu()
lifecycleScope.launch(Dispatchers.Main) {
// Change mode
toggleDeviceCredentialMode(uiState.newDeviceUnlockMode)
// Prompt
manageDeviceCredentialPrompt(uiState.cryptoPromptState)
// Advanced menu
mAllowDeviceUnlockMenu = uiState.allowDeviceUnlockMenu
activity?.invalidateOptionsMenu()
}
}
}
}
@@ -208,7 +210,8 @@ class DeviceUnlockFragment: Fragment() {
setNegativeButtonText(getString(android.R.string.cancel))
}
}.build(),
BiometricPrompt.CryptoObject(cryptoPrompt.cipher))
BiometricPrompt.CryptoObject(cryptoPrompt.cipher)
)
} else if (cryptoPrompt.isDeviceCredentialOperation) {
context?.let { context ->
@Suppress("DEPRECATION")
@@ -230,10 +233,8 @@ class DeviceUnlockFragment: Fragment() {
}
private fun setNotAvailableMode() {
lifecycleScope.launch(Dispatchers.Main) {
showViews(false)
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener(null)
}
showViews(false)
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener(null)
}
private fun openBiometricSetting() {
@@ -259,60 +260,48 @@ class DeviceUnlockFragment: Fragment() {
}
private fun setSecurityUpdateRequiredMode() {
lifecycleScope.launch(Dispatchers.Main) {
showViews(true)
setAdvancedUnlockedTitleView(R.string.biometric_security_update_required)
openBiometricSetting()
}
showViews(true)
setDeviceUnlockedTitleView(R.string.biometric_security_update_required)
openBiometricSetting()
}
private fun setNotConfiguredMode() {
lifecycleScope.launch(Dispatchers.Main) {
showViews(true)
setAdvancedUnlockedTitleView(R.string.configure_biometric)
openBiometricSetting()
}
showViews(true)
setDeviceUnlockedTitleView(R.string.configure_biometric)
openBiometricSetting()
}
private fun setKeyManagerNotAvailableMode() {
lifecycleScope.launch(Dispatchers.Main) {
showViews(true)
setAdvancedUnlockedTitleView(R.string.keystore_not_accessible)
openBiometricSetting()
}
showViews(true)
setDeviceUnlockedTitleView(R.string.keystore_not_accessible)
openBiometricSetting()
}
private fun setWaitCredentialMode() {
lifecycleScope.launch(Dispatchers.Main) {
showViews(true)
setAdvancedUnlockedTitleView(R.string.unavailable)
context?.let { context ->
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener {
mDeviceUnlockViewModel.setException(SecurityException(
context.getString(R.string.credential_before_click_advanced_unlock_button)
))
}
showViews(true)
setDeviceUnlockedTitleView(R.string.unavailable)
context?.let { context ->
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener {
mDeviceUnlockViewModel.setException(SecurityException(
context.getString(R.string.credential_before_click_device_unlock_button)
))
}
}
}
private fun setStoreCredentialMode() {
lifecycleScope.launch(Dispatchers.Main) {
showViews(true)
setAdvancedUnlockedTitleView(R.string.unlock_and_link_biometric)
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener { _ ->
mDeviceUnlockViewModel.showPrompt()
}
showViews(true)
setDeviceUnlockedTitleView(R.string.unlock_and_link_biometric)
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener { _ ->
mDeviceUnlockViewModel.showPrompt()
}
}
private fun setExtractCredentialMode() {
lifecycleScope.launch(Dispatchers.Main) {
showViews(true)
setAdvancedUnlockedTitleView(R.string.unlock)
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener { _ ->
mDeviceUnlockViewModel.showPrompt()
}
showViews(true)
setDeviceUnlockedTitleView(R.string.unlock)
mDeviceUnlockView?.setDeviceUnlockButtonViewClickListener { _ ->
mDeviceUnlockViewModel.showPrompt()
}
}
@@ -321,22 +310,18 @@ class DeviceUnlockFragment: Fragment() {
}
private fun showViews(show: Boolean) {
lifecycleScope.launch(Dispatchers.Main) {
if (show) {
if (mDeviceUnlockView?.visibility != View.VISIBLE)
mDeviceUnlockView?.showByFading()
}
else {
if (mDeviceUnlockView?.visibility == View.VISIBLE)
mDeviceUnlockView?.hideByFading()
}
if (show) {
if (mDeviceUnlockView?.visibility != View.VISIBLE)
mDeviceUnlockView?.showByFading()
}
else {
if (mDeviceUnlockView?.visibility == View.VISIBLE)
mDeviceUnlockView?.hideByFading()
}
}
private fun setAdvancedUnlockedTitleView(textId: Int) {
lifecycleScope.launch(Dispatchers.Main) {
mDeviceUnlockView?.setTitle(textId)
}
private fun setDeviceUnlockedTitleView(textId: Int) {
mDeviceUnlockView?.setTitle(textId)
}
private fun setAuthenticationError(errorCode: Int, errString: CharSequence) {
@@ -358,7 +343,7 @@ class DeviceUnlockFragment: Fragment() {
private fun setAuthenticationFailed() {
Log.e(TAG, "Biometric authentication failed, biometric not recognized")
mDeviceUnlockViewModel.setException(
SecurityException(getString(R.string.advanced_unlock_not_recognized))
SecurityException(getString(R.string.device_unlock_not_recognized))
)
}
@@ -58,15 +58,15 @@ class DeviceUnlockManager(private var appContext: Context) {
if (biometricUnlockEnable || deviceCredentialUnlockEnable) {
if (isDeviceSecure(appContext)) {
try {
this.keyStore = KeyStore.getInstance(ADVANCED_UNLOCK_KEYSTORE)
this.keyStore = KeyStore.getInstance(DEVICE_UNLOCK_KEYSTORE)
this.keyGenerator = KeyGenerator.getInstance(
ADVANCED_UNLOCK_KEY_ALGORITHM,
ADVANCED_UNLOCK_KEYSTORE
DEVICE_UNLOCK_KEY_ALGORITHM,
DEVICE_UNLOCK_KEYSTORE
)
this.cipher = Cipher.getInstance(
ADVANCED_UNLOCK_KEY_ALGORITHM + "/"
+ ADVANCED_UNLOCK_BLOCKS_MODES + "/"
+ ADVANCED_UNLOCK_ENCRYPTION_PADDING
DEVICE_UNLOCK_KEY_ALGORITHM + "/"
+ DEVICE_UNLOCK_BLOCKS_MODES + "/"
+ DEVICE_UNLOCK_ENCRYPTION_PADDING
)
if (keyStore == null) {
throw SecurityException("Unable to initialize the keystore")
@@ -93,15 +93,15 @@ class DeviceUnlockManager(private var appContext: Context) {
keyStore?.let { keyStore ->
keyStore.load(null)
try {
if (!keyStore.containsAlias(ADVANCED_UNLOCK_KEYSTORE_KEY)) {
if (!keyStore.containsAlias(DEVICE_UNLOCK_KEYSTORE_KEY)) {
// Set the alias of the entry in Android KeyStore where the key will appear
// and the constrains (purposes) in the constructor of the Builder
keyGenerator?.init(
KeyGenParameterSpec.Builder(
ADVANCED_UNLOCK_KEYSTORE_KEY,
DEVICE_UNLOCK_KEYSTORE_KEY,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(ADVANCED_UNLOCK_BLOCKS_MODES)
.setEncryptionPaddings(ADVANCED_UNLOCK_ENCRYPTION_PADDING)
.setBlockModes(DEVICE_UNLOCK_BLOCKS_MODES)
.setEncryptionPaddings(DEVICE_UNLOCK_ENCRYPTION_PADDING)
.apply {
// Require the user to authenticate with a fingerprint to authorize every use
// of the key, don't use it for device credential because it's the user authentication
@@ -122,7 +122,7 @@ class DeviceUnlockManager(private var appContext: Context) {
Log.e(TAG, "Unable to create a key in keystore", e)
throw e
}
return keyStore.getKey(ADVANCED_UNLOCK_KEYSTORE_KEY, null) as SecretKey?
return keyStore.getKey(DEVICE_UNLOCK_KEYSTORE_KEY, null) as SecretKey?
}
} catch (e: Exception) {
Log.e(TAG, "Unable to retrieve the key in keystore", e)
@@ -149,8 +149,8 @@ class DeviceUnlockManager(private var appContext: Context) {
DeviceUnlockCryptoPrompt(
type = DeviceUnlockCryptoPromptType.CREDENTIAL_ENCRYPTION,
cipher = cipher,
titleId = R.string.advanced_unlock_prompt_store_credential_title,
descriptionId = R.string.advanced_unlock_prompt_store_credential_message,
titleId = R.string.device_unlock_prompt_store_credential_title,
descriptionId = R.string.device_unlock_prompt_store_credential_message,
isDeviceCredentialOperation = isDeviceCredentialOperation(
deviceCredentialUnlockEnable
),
@@ -217,7 +217,7 @@ class DeviceUnlockManager(private var appContext: Context) {
DeviceUnlockCryptoPrompt(
type = DeviceUnlockCryptoPromptType.CREDENTIAL_DECRYPTION,
cipher = cipher,
titleId = R.string.advanced_unlock_prompt_extract_credential_title,
titleId = R.string.device_unlock_prompt_extract_credential_title,
descriptionId = null,
isDeviceCredentialOperation = isDeviceCredentialOperation(
deviceCredentialUnlockEnable
@@ -270,7 +270,7 @@ class DeviceUnlockManager(private var appContext: Context) {
@Synchronized fun deleteKeystoreKey() {
try {
keyStore?.load(null)
keyStore?.deleteEntry(ADVANCED_UNLOCK_KEYSTORE_KEY)
keyStore?.deleteEntry(DEVICE_UNLOCK_KEYSTORE_KEY)
} catch (e: Exception) {
Log.e(TAG, "Unable to delete entry key in keystore", e)
throw e
@@ -281,11 +281,11 @@ class DeviceUnlockManager(private var appContext: Context) {
private val TAG = DeviceUnlockManager::class.java.name
private const val ADVANCED_UNLOCK_KEYSTORE = "AndroidKeyStore"
private const val ADVANCED_UNLOCK_KEYSTORE_KEY = "com.kunzisoft.keepass.biometric.key"
private const val ADVANCED_UNLOCK_KEY_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES
private const val ADVANCED_UNLOCK_BLOCKS_MODES = KeyProperties.BLOCK_MODE_CBC
private const val ADVANCED_UNLOCK_ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7
private const val DEVICE_UNLOCK_KEYSTORE = "AndroidKeyStore"
private const val DEVICE_UNLOCK_KEYSTORE_KEY = "com.kunzisoft.keepass.biometric.key"
private const val DEVICE_UNLOCK_KEY_ALGORITHM = KeyProperties.KEY_ALGORITHM_AES
private const val DEVICE_UNLOCK_BLOCKS_MODES = KeyProperties.BLOCK_MODE_CBC
private const val DEVICE_UNLOCK_ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7
@RequiresApi(api = Build.VERSION_CODES.M)
fun canAuthenticate(context: Context): Int {
@@ -384,7 +384,7 @@ fun deviceUnlockError(error: Exception, context: Context): String {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& (error is UnrecoverableKeyException
|| error is KeyPermanentlyInvalidatedException)) {
context.getString(R.string.advanced_unlock_invalid_key)
context.getString(R.string.device_unlock_invalid_key)
} else
error.cause?.localizedMessage
?: error.localizedMessage
@@ -89,8 +89,8 @@ class PasswordActivityEducation(activity: Activity)
onOuterViewClick: ((TapTargetView?) -> Unit)? = null): Boolean {
return checkAndPerformedEducation(isEducationBiometricPerformed(activity),
TapTarget.forView(educationView,
activity.getString(R.string.education_advanced_unlock_title),
activity.getString(R.string.education_advanced_unlock_summary))
activity.getString(R.string.education_device_unlock_title),
activity.getString(R.string.education_device_unlock_summary))
.outerCircleColorInt(getCircleColor())
.outerCircleAlpha(getCircleAlpha())
.icon(ContextCompat.getDrawable(activity, R.drawable.ic_fingerprint_24dp))
@@ -15,13 +15,13 @@ import com.kunzisoft.keepass.app.database.CipherDatabaseEntity
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.timeout.TimeoutHelper
class AdvancedUnlockNotificationService : NotificationService() {
class DeviceUnlockNotificationService : NotificationService() {
private lateinit var mTempCipherDao: ArrayList<CipherDatabaseEntity>
private var mActionTaskBinder = AdvancedUnlockBinder()
private var mActionTaskBinder = DeviceUnlockBinder()
inner class AdvancedUnlockBinder: Binder() {
inner class DeviceUnlockBinder: Binder() {
fun getCipherDatabase(databaseUri: Uri): CipherDatabaseEntity? {
return mTempCipherDao.firstOrNull { it.databaseUri == databaseUri.toString()}
}
@@ -48,11 +48,11 @@ class AdvancedUnlockNotificationService : NotificationService() {
override val notificationId: Int = 593
override fun retrieveChannelId(): String {
return CHANNEL_ADVANCED_UNLOCK_ID
return CHANNEL_DEVICE_UNLOCK_ID
}
override fun retrieveChannelName(): String {
return getString(R.string.advanced_unlock)
return getString(R.string.device_unlock)
}
override fun onCreate() {
@@ -60,7 +60,7 @@ class AdvancedUnlockNotificationService : NotificationService() {
mTempCipherDao = ArrayList()
}
// It's simpler to use pendingIntent to perform REMOVE_ADVANCED_UNLOCK_KEY_ACTION
// It's simpler to use pendingIntent to perform REMOVE_DEVICE_UNLOCK_KEY_ACTION
// because can be directly broadcast to another module or app
@SuppressLint("LaunchActivityFromNotification")
override fun onBind(intent: Intent): IBinder {
@@ -68,7 +68,7 @@ class AdvancedUnlockNotificationService : NotificationService() {
val pendingDeleteIntent = PendingIntent.getBroadcast(this,
4577,
Intent(REMOVE_ADVANCED_UNLOCK_KEY_ACTION),
Intent(REMOVE_DEVICE_UNLOCK_KEY_ACTION),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE
} else {
@@ -81,28 +81,28 @@ class AdvancedUnlockNotificationService : NotificationService() {
} else {
R.drawable.notification_ic_device_unlock_24dp
})
setContentTitle(getString(R.string.advanced_unlock))
setContentText(getString(R.string.advanced_unlock_tap_delete))
setContentTitle(getString(R.string.device_unlock))
setContentText(getString(R.string.device_unlock_tap_delete))
setContentIntent(pendingDeleteIntent)
// Unfortunately swipe is disabled in lollipop+
setDeleteIntent(pendingDeleteIntent)
}
val notificationTimeoutMilliSecs = PreferencesUtil.getAdvancedUnlockTimeout(this)
val notificationTimeoutMilliSecs = PreferencesUtil.getDeviceUnlockTimeout(this)
// Not necessarily a foreground service
if (mTimerJob == null && notificationTimeoutMilliSecs != TimeoutHelper.NEVER) {
defineTimerJob(
notificationBuilder,
NotificationServiceType.ADVANCED_UNLOCK,
NotificationServiceType.DEVICE_UNLOCK,
notificationTimeoutMilliSecs
) {
sendBroadcast(Intent(REMOVE_ADVANCED_UNLOCK_KEY_ACTION))
sendBroadcast(Intent(REMOVE_DEVICE_UNLOCK_KEY_ACTION))
}
} else {
startForegroundCompat(
notificationId,
notificationBuilder,
NotificationServiceType.ADVANCED_UNLOCK
NotificationServiceType.DEVICE_UNLOCK
)
}
@@ -119,11 +119,11 @@ class AdvancedUnlockNotificationService : NotificationService() {
super.onDestroy()
}
class AdvancedUnlockReceiver(var removeKeyAction: () -> Unit): BroadcastReceiver() {
class DeviceUnlockReceiver(var removeKeyAction: () -> Unit): BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
intent.action?.let {
when (it) {
REMOVE_ADVANCED_UNLOCK_KEY_ACTION -> {
REMOVE_DEVICE_UNLOCK_KEY_ACTION -> {
removeKeyAction.invoke()
}
}
@@ -132,13 +132,13 @@ class AdvancedUnlockNotificationService : NotificationService() {
}
companion object {
private const val CHANNEL_ADVANCED_UNLOCK_ID = "com.kunzisoft.keepass.notification.channel.unlock"
const val REMOVE_ADVANCED_UNLOCK_KEY_ACTION = "com.kunzisoft.keepass.REMOVE_ADVANCED_UNLOCK_KEY"
private const val CHANNEL_DEVICE_UNLOCK_ID = "com.kunzisoft.keepass.notification.channel.unlock"
const val REMOVE_DEVICE_UNLOCK_KEY_ACTION = "com.kunzisoft.keepass.REMOVE_DEVICE_UNLOCK_KEY"
// Only one service connection
fun bindService(context: Context, serviceConnection: ServiceConnection, flags: Int) {
context.bindService(Intent(context,
AdvancedUnlockNotificationService::class.java),
DeviceUnlockNotificationService::class.java),
serviceConnection,
flags)
}
@@ -105,7 +105,7 @@ abstract class NotificationService : Service() {
NotificationServiceType.ATTACHMENT -> FOREGROUND_SERVICE_TYPE_DATA_SYNC
NotificationServiceType.CLIPBOARD -> foregroundServiceTimer
NotificationServiceType.KEYBOARD -> foregroundServiceTimer
NotificationServiceType.ADVANCED_UNLOCK -> foregroundServiceTimer
NotificationServiceType.DEVICE_UNLOCK -> foregroundServiceTimer
}
startForeground(notificationId, builder.build(), foregroundType)
} else {
@@ -5,5 +5,5 @@ enum class NotificationServiceType {
ATTACHMENT,
CLIPBOARD,
KEYBOARD,
ADVANCED_UNLOCK
DEVICE_UNLOCK
}
@@ -23,15 +23,15 @@ import android.os.Bundle
import androidx.fragment.app.Fragment
class AdvancedUnlockSettingsActivity : SettingsActivity() {
class DeviceUnlockSettingsActivity : SettingsActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mTimeoutEnable = false
setTitle(NestedSettingsFragment.Screen.ADVANCED_UNLOCK)
setTitle(NestedSettingsFragment.Screen.DEVICE_UNLOCK)
}
override fun retrieveMainFragment(): Fragment {
return NestedSettingsFragment.newInstance(NestedSettingsFragment.Screen.ADVANCED_UNLOCK)
return NestedSettingsFragment.newInstance(NestedSettingsFragment.Screen.DEVICE_UNLOCK)
}
}
@@ -84,9 +84,9 @@ class MainPreferenceFragment : PreferenceFragmentCompat() {
}
}
findPreference<Preference>(getString(R.string.settings_advanced_unlock_key))?.apply {
findPreference<Preference>(getString(R.string.settings_device_unlock_key))?.apply {
onPreferenceClickListener = Preference.OnPreferenceClickListener {
mCallback?.onNestedPreferenceSelected(NestedSettingsFragment.Screen.ADVANCED_UNLOCK)
mCallback?.onNestedPreferenceSelected(NestedSettingsFragment.Screen.DEVICE_UNLOCK)
false
}
}
@@ -66,8 +66,8 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
Screen.FORM_FILLING -> {
onCreateFormFillingPreference(rootKey)
}
Screen.ADVANCED_UNLOCK -> {
onCreateAdvancedUnlockPreferences(rootKey)
Screen.DEVICE_UNLOCK -> {
onCreateDeviceUnlockPreferences(rootKey)
}
Screen.APPEARANCE -> {
onCreateAppearancePreferences(rootKey)
@@ -240,15 +240,15 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
}
}
private fun onCreateAdvancedUnlockPreferences(rootKey: String?) {
setPreferencesFromResource(R.xml.preferences_advanced_unlock, rootKey)
private fun onCreateDeviceUnlockPreferences(rootKey: String?) {
setPreferencesFromResource(R.xml.preferences_device_unlock, rootKey)
activity?.let { activity ->
val biometricUnlockEnablePreference: TwoStatePreference? = findPreference(getString(R.string.biometric_unlock_enable_key))
val deviceCredentialUnlockEnablePreference: TwoStatePreference? = findPreference(getString(R.string.device_credential_unlock_enable_key))
val autoOpenPromptPreference: TwoStatePreference? = findPreference(getString(R.string.biometric_auto_open_prompt_key))
val tempAdvancedUnlockPreference: TwoStatePreference? = findPreference(getString(R.string.temp_advanced_unlock_enable_key))
val tempDeviceUnlockPreference: TwoStatePreference? = findPreference(getString(R.string.temp_device_unlock_enable_key))
val biometricUnlockSupported = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
DeviceUnlockManager.biometricUnlockSupported(activity)
@@ -272,7 +272,7 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
warningMessage(activity, keystoreWarning = false, deleteKeys = true) {
biometricUnlockEnablePreference.isChecked = false
autoOpenPromptPreference?.isEnabled = deviceCredentialChecked
tempAdvancedUnlockPreference?.isEnabled = deviceCredentialChecked
tempDeviceUnlockPreference?.isEnabled = deviceCredentialChecked
}
} else {
if (deviceCredentialChecked) {
@@ -286,7 +286,7 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
warningMessage(activity, keystoreWarning = true, deleteKeys = false) {
biometricUnlockEnablePreference.isChecked = true
autoOpenPromptPreference?.isEnabled = true
tempAdvancedUnlockPreference?.isEnabled = true
tempDeviceUnlockPreference?.isEnabled = true
}
}
}
@@ -319,7 +319,7 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
warningMessage(activity, keystoreWarning = false, deleteKeys = true) {
deviceCredentialUnlockEnablePreference.isChecked = false
autoOpenPromptPreference?.isEnabled = biometricChecked
tempAdvancedUnlockPreference?.isEnabled = biometricChecked
tempDeviceUnlockPreference?.isEnabled = biometricChecked
}
} else {
if (biometricChecked) {
@@ -333,7 +333,7 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
warningMessage(activity, keystoreWarning = true, deleteKeys = false) {
deviceCredentialUnlockEnablePreference.isChecked = true
autoOpenPromptPreference?.isEnabled = true
tempAdvancedUnlockPreference?.isEnabled = true
tempDeviceUnlockPreference?.isEnabled = true
}
}
}
@@ -344,13 +344,13 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
autoOpenPromptPreference?.isEnabled = biometricUnlockEnablePreference?.isChecked == true
|| deviceCredentialUnlockEnablePreference?.isChecked == true
tempAdvancedUnlockPreference?.isEnabled = biometricUnlockEnablePreference?.isChecked == true
tempDeviceUnlockPreference?.isEnabled = biometricUnlockEnablePreference?.isChecked == true
|| deviceCredentialUnlockEnablePreference?.isChecked == true
tempAdvancedUnlockPreference?.setOnPreferenceClickListener {
tempAdvancedUnlockPreference.isChecked = !tempAdvancedUnlockPreference.isChecked
tempDeviceUnlockPreference?.setOnPreferenceClickListener {
tempDeviceUnlockPreference.isChecked = !tempDeviceUnlockPreference.isChecked
warningMessage(activity, keystoreWarning = false, deleteKeys = true) {
tempAdvancedUnlockPreference.isChecked = !tempAdvancedUnlockPreference.isChecked
tempDeviceUnlockPreference.isChecked = !tempDeviceUnlockPreference.isChecked
}
true
}
@@ -366,8 +366,8 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
}
}
findPreference<Preference>(getString(R.string.advanced_unlock_explanation_key))?.setOnPreferenceClickListener {
context?.openUrl(R.string.advanced_unlock_explanation_url)
findPreference<Preference>(getString(R.string.device_unlock_explanation_key))?.setOnPreferenceClickListener {
context?.openUrl(R.string.device_unlock_explanation_url)
false
}
}
@@ -378,14 +378,14 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
validate: (()->Unit)? = null) {
var message = ""
if (keystoreWarning) {
message += resources.getString(R.string.advanced_unlock_prompt_store_credential_message)
message += "\n\n" + resources.getString(R.string.advanced_unlock_keystore_warning)
message += resources.getString(R.string.device_unlock_prompt_store_credential_message)
message += "\n\n" + resources.getString(R.string.device_unlock_keystore_warning)
}
if (keystoreWarning && deleteKeys) {
message += "\n\n"
}
if (deleteKeys) {
message += resources.getString(R.string.advanced_unlock_delete_all_key_warning)
message += resources.getString(R.string.device_unlock_delete_all_key_warning)
}
warningAlertDialog = AlertDialog.Builder(activity)
.setMessage(message)
@@ -509,7 +509,7 @@ class NestedAppSettingsFragment : NestedSettingsFragment() {
when (preference.key) {
getString(R.string.app_timeout_key),
getString(R.string.clipboard_timeout_key),
getString(R.string.temp_advanced_unlock_timeout_key) -> {
getString(R.string.temp_device_unlock_timeout_key) -> {
dialogFragment = DurationDialogFragmentCompat.newInstance(preference.key)
}
else -> otherDialogFragment = true
@@ -30,7 +30,7 @@ import com.kunzisoft.keepass.activities.dialogs.UnderDevelopmentFeatureDialogFra
abstract class NestedSettingsFragment : PreferenceFragmentCompat() {
enum class Screen {
APPLICATION, FORM_FILLING, ADVANCED_UNLOCK, APPEARANCE, DATABASE, DATABASE_SECURITY, DATABASE_MASTER_KEY
APPLICATION, FORM_FILLING, DEVICE_UNLOCK, APPEARANCE, DATABASE, DATABASE_SECURITY, DATABASE_MASTER_KEY
}
fun getScreen(): Screen {
@@ -66,7 +66,7 @@ abstract class NestedSettingsFragment : PreferenceFragmentCompat() {
val fragment: NestedSettingsFragment = when (key) {
Screen.APPLICATION,
Screen.FORM_FILLING,
Screen.ADVANCED_UNLOCK,
Screen.DEVICE_UNLOCK,
Screen.APPEARANCE -> NestedAppSettingsFragment()
Screen.DATABASE,
Screen.DATABASE_SECURITY,
@@ -83,7 +83,7 @@ abstract class NestedSettingsFragment : PreferenceFragmentCompat() {
return when (key) {
Screen.APPLICATION -> resources.getString(R.string.menu_app_settings)
Screen.FORM_FILLING -> resources.getString(R.string.menu_form_filling_settings)
Screen.ADVANCED_UNLOCK -> resources.getString(R.string.menu_advanced_unlock_settings)
Screen.DEVICE_UNLOCK -> resources.getString(R.string.menu_device_unlock_settings)
Screen.APPEARANCE -> resources.getString(R.string.menu_appearance_settings)
Screen.DATABASE -> resources.getString(R.string.menu_database_settings)
Screen.DATABASE_SECURITY -> resources.getString(R.string.menu_security_settings)
@@ -460,10 +460,10 @@ object PreferencesUtil {
?: TimeoutHelper.DEFAULT_TIMEOUT
}
fun getAdvancedUnlockTimeout(context: Context): Long {
fun getDeviceUnlockTimeout(context: Context): Long {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getString(context.getString(R.string.temp_advanced_unlock_timeout_key),
context.getString(R.string.temp_advanced_unlock_timeout_default))?.toLong()
return prefs.getString(context.getString(R.string.temp_device_unlock_timeout_key),
context.getString(R.string.temp_device_unlock_timeout_default))?.toLong()
?: TimeoutHelper.DEFAULT_TIMEOUT
}
@@ -503,7 +503,7 @@ object PreferencesUtil {
context.resources.getBoolean(R.bool.enable_screenshot_mode_key_default))
}
fun isAdvancedUnlockEnable(context: Context): Boolean {
fun isDeviceUnlockEnable(context: Context): Boolean {
return isBiometricUnlockEnable(context) || isDeviceCredentialUnlockEnable(context)
}
@@ -526,13 +526,13 @@ object PreferencesUtil {
&& !isBiometricUnlockEnable(context)
}
fun isTempAdvancedUnlockEnable(context: Context): Boolean {
fun isTempDeviceUnlockEnable(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getBoolean(context.getString(R.string.temp_advanced_unlock_enable_key),
context.resources.getBoolean(R.bool.temp_advanced_unlock_enable_default))
return prefs.getBoolean(context.getString(R.string.temp_device_unlock_enable_key),
context.resources.getBoolean(R.bool.temp_device_unlock_enable_default))
}
fun isAdvancedUnlockPromptAutoOpenEnable(context: Context): Boolean {
fun isDeviceUnlockPromptAutoOpenEnable(context: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
return prefs.getBoolean(context.getString(R.string.biometric_auto_open_prompt_key),
context.resources.getBoolean(R.bool.biometric_auto_open_prompt_default))
@@ -821,8 +821,8 @@ object PreferencesUtil {
context.getString(R.string.biometric_unlock_enable_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.device_credential_unlock_enable_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.biometric_auto_open_prompt_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.temp_advanced_unlock_enable_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.temp_advanced_unlock_timeout_key) -> editor.putString(name, value.toLong().toString())
context.getString(R.string.temp_device_unlock_enable_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.temp_device_unlock_timeout_key) -> editor.putString(name, value.toLong().toString())
context.getString(R.string.magic_keyboard_key) -> editor.putBoolean(name, value.toBoolean())
context.getString(R.string.clipboard_notifications_key) -> editor.putBoolean(name, value.toBoolean())
@@ -39,7 +39,7 @@ class DeviceUnlockView @JvmOverloads constructor(context: Context,
init {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater?
inflater?.inflate(R.layout.view_advanced_unlock, this)
inflater?.inflate(R.layout.view_device_unlock, this)
biometricButtonView = findViewById(R.id.biometric_button)
}
@@ -3,6 +3,7 @@ package com.kunzisoft.keepass.viewmodels
import android.app.Application
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
@@ -29,7 +30,6 @@ import javax.crypto.Cipher
@RequiresApi(Build.VERSION_CODES.M)
class DeviceUnlockViewModel(application: Application): AndroidViewModel(application) {
private var cipherDatabaseListener: CipherDatabaseAction.CipherDatabaseListener? = null
private var cipherDatabase: CipherEncryptDatabase? = null
private var isConditionToStoreCredentialVerified: Boolean = false
@@ -47,6 +47,40 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
var credentialDatabaseStorage: CredentialStorage = CredentialStorage.DEFAULT
val cipherDatabaseAction = CipherDatabaseAction.getInstance(getApplication())
private var cipherDatabaseListener = object: CipherDatabaseAction.CipherDatabaseListener {
override fun onCipherDatabaseRetrieved(
databaseUri: Uri,
cipherDatabase: CipherEncryptDatabase?
) {
if (databaseUri == this@DeviceUnlockViewModel.databaseUri) {
cipherDatabase?.let {
this@DeviceUnlockViewModel.cipherDatabase = it
checkUnlockAvailability()
} ?: deleteEncryptedDatabaseKey()
}
}
override fun onCipherDatabaseAddedOrUpdated(cipherDatabase: CipherEncryptDatabase) {
if (cipherDatabase.databaseUri == this@DeviceUnlockViewModel.databaseUri) {
this@DeviceUnlockViewModel.cipherDatabase = cipherDatabase
checkUnlockAvailability()
}
}
override fun onCipherDatabaseDeleted(databaseUri: Uri) {
if (databaseUri == this@DeviceUnlockViewModel.databaseUri) {
this@DeviceUnlockViewModel.cipherDatabase = null
checkUnlockAvailability()
}
}
override fun onAllCipherDatabasesDeleted() {
this@DeviceUnlockViewModel.cipherDatabase = null
checkUnlockAvailability()
}
override fun onCipherDatabaseCleared() {
this@DeviceUnlockViewModel.cipherDatabase = null
closeBiometricPrompt()
checkUnlockAvailability()
}
}
private val _uiState = MutableStateFlow(DeviceUnlockState())
val uiState: StateFlow<DeviceUnlockState> = _uiState
@@ -58,6 +92,7 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
checkUnlockAvailability()
}
.launchIn(viewModelScope)
cipherDatabaseAction.registerDatabaseListener(cipherDatabaseListener)
}
fun checkConditionToStoreCredential(condition: Boolean) {
@@ -73,7 +108,7 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
// biometric not supported (by API level or hardware) so keep option hidden
// or manually disable
val biometricCanAuthenticate = DeviceUnlockManager.canAuthenticate(getApplication())
if (!PreferencesUtil.isAdvancedUnlockEnable(getApplication())
if (!PreferencesUtil.isDeviceUnlockEnable(getApplication())
|| biometricCanAuthenticate == BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE
|| biometricCanAuthenticate == BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE) {
changeMode(DeviceUnlockMode.BIOMETRIC_UNAVAILABLE)
@@ -129,7 +164,7 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
_uiState.update { currentState ->
currentState.copy(
newDeviceUnlockMode = deviceUnlockMode,
allowAdvancedUnlockMenu = cipherDatabase != null
allowDeviceUnlockMenu = cipherDatabase != null
&& deviceUnlockMode != DeviceUnlockMode.BIOMETRIC_UNAVAILABLE
&& deviceUnlockMode != DeviceUnlockMode.KEY_MANAGER_UNAVAILABLE
)
@@ -138,25 +173,7 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
private fun connectDatabase(databaseUri: Uri) {
this.databaseUri = databaseUri
cipherDatabaseListener = object: CipherDatabaseAction.CipherDatabaseListener {
override fun onCipherDatabaseCleared() {
cipherDatabase = null
closeBiometricPrompt()
checkUnlockAvailability()
}
}
cipherDatabaseAction.apply {
reloadPreferences()
cipherDatabaseListener?.let {
registerDatabaseListener(it)
}
getCipherDatabase(databaseUri) { cipherDatabase ->
cipherDatabase?.let {
this@DeviceUnlockViewModel.cipherDatabase = it
checkUnlockAvailability()
} ?: deleteEncryptedDatabaseKey()
}
}
cipherDatabaseAction.getCipherDatabase(databaseUri)
}
private fun showPendingIfNecessary() {
@@ -170,17 +187,15 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
private fun disconnectDatabase() {
this.databaseUri = null
this.cipherDatabase = null
cipherDatabaseListener?.let {
cipherDatabaseAction.unregisterDatabaseListener(it)
}
clearPrompt()
changeMode(DeviceUnlockMode.BIOMETRIC_UNAVAILABLE)
}
fun connect(databaseUri: Uri?) {
Log.d(TAG, "Connect to device unlock")
// To get device credential unlock result, only if same database uri
if (databaseUri != null
&& PreferencesUtil.isAdvancedUnlockEnable(getApplication())) {
&& PreferencesUtil.isDeviceUnlockEnable(getApplication())) {
if (databaseUri != this.databaseUri) {
connectDatabase(databaseUri)
}
@@ -190,6 +205,7 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
}
fun disconnect() {
Log.d(TAG, "Disconnect from device unlock")
showPendingIfNecessary()
disconnectDatabase()
}
@@ -262,29 +278,27 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
fun decryptCredential(cipher: Cipher?) {
// retrieve the encrypted value from preferences
databaseUri?.let { databaseUri ->
cipherDatabaseAction.getCipherDatabase(databaseUri) { cipherDatabase ->
cipherDatabase?.encryptedValue?.let { encryptedCredential ->
try {
deviceUnlockManager?.decryptData(
encryptedValue = encryptedCredential,
cipher = cipher,
handleDecryptedResult = { decryptedValue ->
// Load database directly with password retrieve
onCredentialDecrypted(
CipherDecryptDatabase().apply {
this.databaseUri = databaseUri
this.credentialStorage = credentialDatabaseStorage
this.decryptedValue = decryptedValue
}
)
cipherDatabaseAction.resetCipherParameters(databaseUri)
}
)
} catch (e: Exception) {
setException(e)
}
} ?: deleteEncryptedDatabaseKey()
}
cipherDatabase?.encryptedValue?.let { encryptedCredential ->
try {
deviceUnlockManager?.decryptData(
encryptedValue = encryptedCredential,
cipher = cipher,
handleDecryptedResult = { decryptedValue ->
// Load database directly with password retrieve
onCredentialDecrypted(
CipherDecryptDatabase().apply {
this.databaseUri = databaseUri
this.credentialStorage = credentialDatabaseStorage
this.decryptedValue = decryptedValue
}
)
cipherDatabaseAction.resetCipherParameters(databaseUri)
}
)
} catch (e: Exception) {
setException(e)
}
} ?: deleteEncryptedDatabaseKey()
} ?: run {
setException(UnknownDatabaseLocationException())
}
@@ -328,7 +342,7 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
) {
this@DeviceUnlockViewModel.cryptoPrompt = cryptoPrompt
if (cryptoPromptShowPending
|| (autoOpen && PreferencesUtil.isAdvancedUnlockPromptAutoOpenEnable(getApplication())))
|| (autoOpen && PreferencesUtil.isDeviceUnlockPromptAutoOpenEnable(getApplication())))
showPrompt()
}
@@ -368,17 +382,19 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
}
private fun initEncryptData() {
Log.d(TAG, "Init encrypt data")
try {
deviceUnlockManager = DeviceUnlockManager(getApplication())
deviceUnlockManager?.initEncryptData { cryptoPrompt ->
onPromptRequested(cryptoPrompt)
} ?: setException(Exception("AdvancedUnlockManager not initialized"))
} ?: setException(Exception("Device unlock manager not initialized"))
} catch (e: Exception) {
setException(e)
}
}
private fun initDecryptData() {
Log.d(TAG, "Init decrypt data")
try {
cipherDatabase?.let { cipherDb ->
deviceUnlockManager = DeviceUnlockManager(getApplication())
@@ -387,7 +403,7 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
cryptoPrompt,
autoOpen = isAutoOpenBiometricPromptAllowed
)
} ?: setException(Exception("AdvancedUnlockManager not initialized"))
} ?: setException(Exception("Device unlock manager not initialized"))
} ?: setException(Exception("Cipher database not initialized"))
} catch (e: Exception) {
setException(e)
@@ -397,13 +413,13 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
fun deleteEncryptedDatabaseKey() {
closeBiometricPrompt()
databaseUri?.let { databaseUri ->
cipherDatabaseAction.deleteByDatabaseUri(databaseUri) {
checkUnlockAvailability()
}
} ?: checkUnlockAvailability()
cipherDatabaseAction.deleteByDatabaseUri(databaseUri)
} ?: run {
checkUnlockAvailability()
}
_uiState.update { currentState ->
currentState.copy(
allowAdvancedUnlockMenu = false
allowDeviceUnlockMenu = false
)
}
}
@@ -437,8 +453,13 @@ class DeviceUnlockViewModel(application: Application): AndroidViewModel(applicat
override fun onCleared() {
super.onCleared()
cipherDatabaseAction.unregisterDatabaseListener(cipherDatabaseListener)
clearPrompt()
}
companion object {
private val TAG = DeviceUnlockViewModel::class.java.simpleName
}
}
enum class DeviceUnlockPromptMode {
@@ -447,7 +468,7 @@ enum class DeviceUnlockPromptMode {
data class DeviceUnlockState(
val newDeviceUnlockMode: DeviceUnlockMode = DeviceUnlockMode.BIOMETRIC_UNAVAILABLE,
val allowAdvancedUnlockMenu: Boolean = false,
val allowDeviceUnlockMenu: Boolean = false,
val credentialRequiredCipher: Cipher? = null,
val cipherEncryptDatabase: CipherEncryptDatabase? = null,
val cipherDecryptDatabase: CipherDecryptDatabase? = null,