Opening refactoring

This commit is contained in:
J-Jamet committed 2022-04-28 20:39:26 +02:00
1 parent 5b4338abae
commit b44c9cfc51
10 files changed
+284 -217

No files matched your search

@@ -152,13 +152,13 @@ class MainCredentialActivity : DatabaseModeActivity(), AdvancedUnlockFragment.Bu
// Build elements to manage hardware key
mHardwareKeyResponseHelper = HardwareKeyResponseHelper(this)
mHardwareKeyResponseHelper?.buildHardwareKeyResponse { responseData ->
mHardwareKeyResponseHelper?.buildHardwareKeyResponse { responseData, _ ->
mainCredentialView?.validateCredential(responseData)
}
mainCredentialView?.onRequestHardwareKeyResponse = { hardwareKey ->
try {
when (hardwareKey) {
HardwareKey.HMAC_SHA1_KPXC -> {
HardwareKey.CHALLENGE_RESPONSE_YUBIKEY -> {
mDatabaseFileUri?.let { databaseUri ->
mHardwareKeyResponseHelper?.launchChallengeForResponse(databaseUri)
}
@@ -35,9 +35,12 @@ import com.google.android.material.textfield.TextInputLayout
import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.activities.helpers.ExternalFileHelper
import com.kunzisoft.keepass.activities.helpers.setOpenDocumentClickListener
import com.kunzisoft.keepass.hardware.HardwareKey
import com.kunzisoft.keepass.hardware.HardwareKeyResponseHelper
import com.kunzisoft.keepass.model.MainCredential
import com.kunzisoft.keepass.password.PasswordEntropy
import com.kunzisoft.keepass.utils.UriUtil
import com.kunzisoft.keepass.view.HardwareKeySelectionView
import com.kunzisoft.keepass.view.KeyFileSelectionView
import com.kunzisoft.keepass.view.PassKeyView
import com.kunzisoft.keepass.view.applyFontVisibility
@@ -45,18 +48,22 @@ import com.kunzisoft.keepass.view.applyFontVisibility
class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
private var mMasterPassword: String? = null
private var mKeyFile: Uri? = null
private var mKeyFileUri: Uri? = null
private var mHardwareKey: HardwareKey? = null
private var mChallengeResponse: ByteArray? = null
private var rootView: View? = null
private lateinit var rootView: View
private var passwordCheckBox: CompoundButton? = null
private lateinit var passwordCheckBox: CompoundButton
private lateinit var passKeyView: PassKeyView
private lateinit var passwordRepeatTextInputLayout: TextInputLayout
private lateinit var passwordRepeatView: TextView
private var passKeyView: PassKeyView? = null
private var passwordRepeatTextInputLayout: TextInputLayout? = null
private var passwordRepeatView: TextView? = null
private lateinit var keyFileCheckBox: CompoundButton
private lateinit var keyFileSelectionView: KeyFileSelectionView
private var keyFileCheckBox: CompoundButton? = null
private var keyFileSelectionView: KeyFileSelectionView? = null
private lateinit var hardwareKeyCheckBox: CompoundButton
private lateinit var hardwareKeySelectionView: HardwareKeySelectionView
private var mListener: AssignMainCredentialDialogListener? = null
@@ -67,13 +74,17 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
private var mNoKeyConfirmationDialog: AlertDialog? = null
private var mEmptyKeyFileConfirmationDialog: AlertDialog? = null
private var mHardwareKeyResponseHelper: HardwareKeyResponseHelper? = null
private var mAllowNoMasterKey: Boolean = false
private val passwordTextWatcher = object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
passwordCheckBox?.isChecked = true
passwordCheckBox.isChecked = true
}
}
@@ -113,10 +124,9 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
activity?.let { activity ->
var allowNoMasterKey = false
arguments?.apply {
if (containsKey(ALLOW_NO_MASTER_KEY_ARG))
allowNoMasterKey = getBoolean(ALLOW_NO_MASTER_KEY_ARG, false)
mAllowNoMasterKey = getBoolean(ALLOW_NO_MASTER_KEY_ARG, false)
}
val builder = AlertDialog.Builder(activity)
@@ -128,64 +138,59 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setNegativeButton(android.R.string.cancel) { _, _ -> }
rootView?.findViewById<View>(R.id.credentials_information)?.setOnClickListener {
rootView.findViewById<View>(R.id.credentials_information)?.setOnClickListener {
UriUtil.gotoUrl(activity, R.string.credentials_explanation_url)
}
passwordCheckBox = rootView?.findViewById(R.id.password_checkbox)
passKeyView = rootView?.findViewById(R.id.password_view)
passwordRepeatTextInputLayout = rootView?.findViewById(R.id.password_repeat_input_layout)
passwordRepeatView = rootView?.findViewById(R.id.password_confirmation)
passwordRepeatView?.applyFontVisibility()
passwordCheckBox = rootView.findViewById(R.id.password_checkbox)
passKeyView = rootView.findViewById(R.id.password_view)
passwordRepeatTextInputLayout = rootView.findViewById(R.id.password_repeat_input_layout)
passwordRepeatView = rootView.findViewById(R.id.password_confirmation)
passwordRepeatView.applyFontVisibility()
keyFileCheckBox = rootView?.findViewById(R.id.keyfile_checkbox)
keyFileSelectionView = rootView?.findViewById(R.id.keyfile_selection)
keyFileCheckBox = rootView.findViewById(R.id.keyfile_checkbox)
keyFileSelectionView = rootView.findViewById(R.id.keyfile_selection)
hardwareKeyCheckBox = rootView.findViewById(R.id.hardware_key_checkbox)
hardwareKeySelectionView = rootView.findViewById(R.id.hardware_key_selection)
mExternalFileHelper = ExternalFileHelper(this)
mExternalFileHelper?.buildOpenDocument { uri ->
uri?.let { pathUri ->
UriUtil.getFileData(requireContext(), uri)?.length()?.let { lengthFile ->
keyFileSelectionView?.error = null
keyFileCheckBox?.isChecked = true
keyFileSelectionView?.uri = pathUri
keyFileSelectionView.error = null
keyFileCheckBox.isChecked = true
keyFileSelectionView.uri = pathUri
if (lengthFile <= 0L) {
showEmptyKeyFileConfirmationDialog()
}
}
}
}
keyFileSelectionView?.setOpenDocumentClickListener(mExternalFileHelper)
keyFileSelectionView.setOpenDocumentClickListener(mExternalFileHelper)
hardwareKeySelectionView.selectionListener = { _ ->
hardwareKeyCheckBox.isChecked = true
}
val dialog = builder.create()
dialog.setOnShowListener { dialog1 ->
val positiveButton = (dialog1 as AlertDialog).getButton(DialogInterface.BUTTON_POSITIVE)
positiveButton.setOnClickListener {
if (passwordCheckBox != null && keyFileCheckBox!= null) {
dialog.setOnShowListener { dialog1 ->
val positiveButton = (dialog1 as AlertDialog).getButton(DialogInterface.BUTTON_POSITIVE)
positiveButton.setOnClickListener {
mMasterPassword = ""
mKeyFileUri = null
mChallengeResponse = null
mMasterPassword = ""
mKeyFile = null
var error = verifyPassword() || verifyKeyFile()
if (!passwordCheckBox!!.isChecked && !keyFileCheckBox!!.isChecked) {
error = true
if (allowNoMasterKey)
showNoKeyConfirmationDialog()
else {
passwordRepeatTextInputLayout?.error = getString(R.string.error_disallow_no_credentials)
}
}
if (!error) {
mListener?.onAssignKeyDialogPositiveClick(retrieveMainCredential())
dismiss()
}
}
val negativeButton = dialog1.getButton(DialogInterface.BUTTON_NEGATIVE)
negativeButton.setOnClickListener {
mListener?.onAssignKeyDialogNegativeClick(retrieveMainCredential())
dismiss()
if (verifyHardwareKey()) {
approveMainCredential()
}
}
val negativeButton = dialog1.getButton(DialogInterface.BUTTON_NEGATIVE)
negativeButton.setOnClickListener {
mListener?.onAssignKeyDialogNegativeClick(retrieveMainCredential())
dismiss()
}
}
return dialog
@@ -194,69 +199,106 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
return super.onCreateDialog(savedInstanceState)
}
private fun approveMainCredential() {
var error = verifyPassword() || verifyKeyFile()
if (!passwordCheckBox.isChecked
&& !keyFileCheckBox.isChecked
&& !hardwareKeyCheckBox.isChecked
) {
error = true
if (mAllowNoMasterKey)
showNoKeyConfirmationDialog()
else {
passwordRepeatTextInputLayout.error =
getString(R.string.error_disallow_no_credentials)
}
}
if (!error) {
mListener?.onAssignKeyDialogPositiveClick(retrieveMainCredential())
dismiss()
}
}
fun setChallengeResponse(response: ByteArray?) {
mChallengeResponse = response
approveMainCredential()
}
private fun retrieveMainCredential(): MainCredential {
val masterPassword = if (passwordCheckBox!!.isChecked) mMasterPassword else null
val keyFile = if (keyFileCheckBox!!.isChecked) mKeyFile else null
return MainCredential(masterPassword, keyFile)
val masterPassword = if (passwordCheckBox.isChecked) mMasterPassword else null
val keyFileUri = if (keyFileCheckBox.isChecked) mKeyFileUri else null
val hardwareKeyData = if (hardwareKeyCheckBox.isChecked) mChallengeResponse else null
return MainCredential(masterPassword, keyFileUri, hardwareKeyData)
}
override fun onResume() {
super.onResume()
// To check checkboxes if a text is present
passKeyView?.addTextChangedListener(passwordTextWatcher)
passKeyView.addTextChangedListener(passwordTextWatcher)
}
override fun onPause() {
super.onPause()
passKeyView?.removeTextChangedListener(passwordTextWatcher)
passKeyView.removeTextChangedListener(passwordTextWatcher)
}
private fun verifyPassword(): Boolean {
var error = false
if (passwordCheckBox != null
&& passwordCheckBox!!.isChecked
&& passKeyView != null
&& passwordRepeatView != null) {
mMasterPassword = passKeyView!!.passwordString
val confPassword = passwordRepeatView!!.text.toString()
if (passwordCheckBox.isChecked) {
mMasterPassword = passKeyView.passwordString
val confPassword = passwordRepeatView.text.toString()
// Verify that passwords match
if (mMasterPassword != confPassword) {
error = true
// Passwords do not match
passwordRepeatTextInputLayout?.error = getString(R.string.error_pass_match)
passwordRepeatTextInputLayout.error = getString(R.string.error_pass_match)
}
if ((mMasterPassword == null
|| mMasterPassword!!.isEmpty())
&& (keyFileCheckBox == null
|| !keyFileCheckBox!!.isChecked
|| keyFileSelectionView?.uri == null)) {
if ((mMasterPassword.isNullOrEmpty())
&& (!keyFileCheckBox.isChecked
|| keyFileSelectionView.uri == null)) {
error = true
showEmptyPasswordConfirmationDialog()
}
}
return error
}
private fun verifyKeyFile(): Boolean {
var error = false
if (keyFileCheckBox != null
&& keyFileCheckBox!!.isChecked) {
keyFileSelectionView?.uri?.let { uri ->
mKeyFile = uri
if (keyFileCheckBox.isChecked) {
keyFileSelectionView.uri?.let { uri ->
mKeyFileUri = uri
} ?: run {
error = true
keyFileSelectionView?.error = getString(R.string.error_nokeyfile)
keyFileSelectionView.error = getString(R.string.error_nokeyfile)
}
}
return error
}
private fun verifyHardwareKey(): Boolean {
if (hardwareKeyCheckBox.isChecked) {
try {
when (hardwareKeySelectionView.hardwareKey) {
HardwareKey.CHALLENGE_RESPONSE_YUBIKEY -> {
// TODO Yubikey algorithm
}
else -> {
// TODO other algorithm
}
}
} catch (e: Exception) {
// TODO Log.e(TAG, "Unable to retrieve the challenge response", e)
}
return false
}
return true
}
private fun showEmptyPasswordConfirmationDialog() {
activity?.let {
val builder = AlertDialog.Builder(it)
@@ -299,8 +341,8 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
})
.setPositiveButton(android.R.string.ok) { _, _ -> }
.setNegativeButton(android.R.string.cancel) { _, _ ->
keyFileCheckBox?.isChecked = false
keyFileSelectionView?.uri = null
keyFileCheckBox.isChecked = false
keyFileSelectionView.uri = null
}
mEmptyKeyFileConfirmationDialog = builder.create()
mEmptyKeyFileConfirmationDialog?.show()
@@ -32,7 +32,6 @@ import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.activities.dialogs.DatabaseDialogFragment
import com.kunzisoft.keepass.activities.dialogs.DeleteNodesDialogFragment
import com.kunzisoft.keepass.activities.dialogs.PasswordEncodingDialogFragment
import com.kunzisoft.keepass.activities.helpers.EntrySelectionHelper
@@ -35,7 +35,7 @@ import com.kunzisoft.keepass.utils.UriUtil
class LoadDatabaseRunnable(private val context: Context,
private val mDatabase: Database,
private val mUri: Uri,
private val mDatabaseUri: Uri,
private val mMainCredential: MainCredential,
private val mReadonly: Boolean,
private val mCipherEncryptDatabase: CipherEncryptDatabase?,
@@ -51,16 +51,18 @@ class LoadDatabaseRunnable(private val context: Context,
override fun onActionRun() {
try {
mDatabase.loadData(mUri,
mMainCredential,
mReadonly,
context.contentResolver,
UriUtil.getBinaryDir(context),
{ memoryWanted ->
BinaryData.canMemoryBeAllocatedInRAM(context, memoryWanted)
},
mFixDuplicateUUID,
progressTaskUpdater)
mDatabase.loadData(
context.contentResolver,
mDatabaseUri,
mMainCredential,
mReadonly,
UriUtil.getBinaryDir(context),
{ memoryWanted ->
BinaryData.canMemoryBeAllocatedInRAM(context, memoryWanted)
},
mFixDuplicateUUID,
progressTaskUpdater
)
}
catch (e: LoadDatabaseException) {
setError(e)
@@ -70,7 +72,7 @@ class LoadDatabaseRunnable(private val context: Context,
// Save keyFile in app database
if (PreferencesUtil.rememberDatabaseLocations(context)) {
FileDatabaseHistoryAction.getInstance(context)
.addOrUpdateDatabaseUri(mUri,
.addOrUpdateDatabaseUri(mDatabaseUri,
if (PreferencesUtil.rememberKeyFileLocations(context)) mMainCredential.keyFileUri else null)
}
@@ -43,9 +43,10 @@ class MergeDatabaseRunnable(private val context: Context,
override fun onActionRun() {
try {
mDatabase.mergeData(mDatabaseToMergeUri,
mDatabaseToMergeMainCredential,
mDatabase.mergeData(
context.contentResolver,
mDatabaseToMergeUri,
mDatabaseToMergeMainCredential,
{ memoryWanted ->
BinaryData.canMemoryBeAllocatedInRAM(context, memoryWanted)
},
@@ -73,7 +73,7 @@ class Database {
var fileUri: Uri? = null
private set
private var mSearchHelper: SearchHelper? = null
private var mSearchHelper: SearchHelper = SearchHelper()
var isReadOnly = false
@@ -557,53 +557,6 @@ class Database {
this.dataModifiedSinceLastLoading = false
}
@Throws(LoadDatabaseException::class)
private fun readDatabaseStream(contentResolver: ContentResolver, uri: Uri,
openDatabaseKDB: (InputStream) -> DatabaseKDB,
openDatabaseKDBX: (InputStream) -> DatabaseKDBX) {
var databaseInputStream: InputStream? = null
try {
// Load Data, pass Uris as InputStreams
val databaseStream = UriUtil.getUriInputStream(contentResolver, uri)
?: throw IOException("Database input stream cannot be retrieve")
databaseInputStream = BufferedInputStream(databaseStream)
if (!databaseInputStream.markSupported()) {
throw IOException("Input stream does not support mark.")
}
// We'll end up reading 8 bytes to identify the header. Might as well use two extra.
databaseInputStream.mark(10)
// Get the file directory to save the attachments
val sig1 = databaseInputStream.readBytes4ToUInt()
val sig2 = databaseInputStream.readBytes4ToUInt()
// Return to the start
databaseInputStream.reset()
when {
// Header of database KDB
DatabaseHeaderKDB.matchesHeader(sig1, sig2) -> setDatabaseKDB(openDatabaseKDB(databaseInputStream))
// Header of database KDBX
DatabaseHeaderKDBX.matchesHeader(sig1, sig2) -> setDatabaseKDBX(openDatabaseKDBX(databaseInputStream))
// Header not recognized
else -> throw SignatureDatabaseException()
}
this.mSearchHelper = SearchHelper()
loaded = true
} catch (e: LoadDatabaseException) {
throw e
} catch (e: Exception) {
throw LoadDatabaseException(e)
} finally {
databaseInputStream?.close()
}
}
@Throws(Exception::class)
private fun getKeyFileData(contentResolver: ContentResolver, keyFileUri: Uri?): ByteArray? {
try {
@@ -612,31 +565,34 @@ class Database {
return keyFileInputStream.readBytes()
}
}
} catch (e: OutOfMemoryError) {
throw LoadDatabaseException("Keyfile too large")
} catch (e: Exception) {
Log.e(TAG, "Unable to load the keyfile.", e)
throw LoadDatabaseException("Unable to load the keyfile.")
}
return null
}
@Throws(LoadDatabaseException::class)
fun loadData(uri: Uri,
mainCredential: MainCredential,
readOnly: Boolean,
contentResolver: ContentResolver,
cacheDirectory: File,
isRAMSufficient: (memoryWanted: Long) -> Boolean,
fixDuplicateUUID: Boolean,
progressTaskUpdater: ProgressTaskUpdater?) {
fun loadData(
contentResolver: ContentResolver,
databaseUri: Uri,
mainCredential: MainCredential,
readOnly: Boolean,
cacheDirectory: File,
isRAMSufficient: (memoryWanted: Long) -> Boolean,
fixDuplicateUUID: Boolean,
progressTaskUpdater: ProgressTaskUpdater?
) {
// Save database URI
this.fileUri = uri
this.fileUri = databaseUri
// Check if the file is writable
this.isReadOnly = readOnly
try {
// Read database stream for the first time
readDatabaseStream(contentResolver, uri,
readDatabaseStream(contentResolver, databaseUri,
{ databaseInputStream ->
val databaseKDB = DatabaseKDB().apply {
binaryCache.cacheDirectory = cacheDirectory
@@ -652,7 +608,7 @@ class Database {
mainCredential.hardwareKeyData
)
}
databaseKDB
setDatabaseKDB(databaseKDB)
},
{ databaseInputStream ->
val databaseKDBX = DatabaseKDBX().apply {
@@ -670,11 +626,10 @@ class Database {
)
}
}
databaseKDBX
setDatabaseKDBX(databaseKDBX)
}
)
} catch (e: FileNotFoundException) {
throw FileNotFoundDatabaseException("Unable to load the keyfile")
loaded = true
} catch (e: LoadDatabaseException) {
throw e
} catch (e: Exception) {
@@ -689,11 +644,13 @@ class Database {
}
@Throws(LoadDatabaseException::class)
fun mergeData(databaseToMergeUri: Uri?,
databaseToMergeMainCredential: MainCredential?,
contentResolver: ContentResolver,
isRAMSufficient: (memoryWanted: Long) -> Boolean,
progressTaskUpdater: ProgressTaskUpdater?) {
fun mergeData(
contentResolver: ContentResolver,
databaseToMergeUri: Uri?,
databaseToMergeMainCredential: MainCredential?,
isRAMSufficient: (memoryWanted: Long) -> Boolean,
progressTaskUpdater: ProgressTaskUpdater?
) {
mDatabaseKDB?.let {
throw IODatabaseException("Unable to merge from a database V1")
@@ -706,7 +663,7 @@ class Database {
try {
val databaseUri = databaseToMerge.fileUri
if (databaseUri != null) {
databaseToMerge.readDatabaseStream(contentResolver, databaseUri,
readDatabaseStream(contentResolver, databaseUri,
{ databaseInputStream ->
val databaseToMergeKDB = DatabaseKDB()
DatabaseInputKDB(databaseToMergeKDB)
@@ -724,7 +681,7 @@ class Database {
databaseToMergeKDB.masterKey = masterKey
}
}
databaseToMergeKDB
setDatabaseKDB(databaseToMergeKDB)
},
{ databaseInputStream ->
val databaseToMergeKDBX = DatabaseKDBX()
@@ -745,9 +702,10 @@ class Database {
}
}
}
databaseToMergeKDBX
setDatabaseKDBX(databaseToMergeKDBX)
}
)
loaded = true
mDatabaseKDBX?.let { currentDatabaseKDBX ->
val databaseMerger = DatabaseKDBXMerger(currentDatabaseKDBX).apply {
@@ -769,8 +727,6 @@ class Database {
} else {
throw IODatabaseException("Database URI is null, database cannot be merged")
}
} catch (e: FileNotFoundException) {
throw FileNotFoundDatabaseException("Unable to load the keyfile")
} catch (e: LoadDatabaseException) {
throw e
} catch (e: Exception) {
@@ -781,9 +737,11 @@ class Database {
}
@Throws(LoadDatabaseException::class)
fun reloadData(contentResolver: ContentResolver,
isRAMSufficient: (memoryWanted: Long) -> Boolean,
progressTaskUpdater: ProgressTaskUpdater?) {
fun reloadData(
contentResolver: ContentResolver,
isRAMSufficient: (memoryWanted: Long) -> Boolean,
progressTaskUpdater: ProgressTaskUpdater?
) {
// Retrieve the stream from the old database URI
try {
@@ -799,7 +757,7 @@ class Database {
.openDatabase(databaseInputStream, progressTaskUpdater) {
databaseKDB.masterKey = masterKey
}
databaseKDB
setDatabaseKDB(databaseKDB)
},
{ databaseInputStream ->
val databaseKDBX = DatabaseKDBX()
@@ -812,14 +770,13 @@ class Database {
databaseKDBX.masterKey = masterKey
}
}
databaseKDBX
setDatabaseKDBX(databaseKDBX)
}
)
loaded = true
} else {
throw IODatabaseException("Database URI is null, database cannot be reloaded")
}
} catch (e: FileNotFoundException) {
throw FileNotFoundDatabaseException("Unable to load the keyfile")
} catch (e: LoadDatabaseException) {
throw e
} catch (e: Exception) {
@@ -851,13 +808,13 @@ class Database {
fun createVirtualGroupFromSearch(searchParameters: SearchParameters,
fromGroup: NodeId<*>? = null,
max: Int = Integer.MAX_VALUE): Group? {
return mSearchHelper?.createVirtualGroupWithSearchResult(this,
return mSearchHelper.createVirtualGroupWithSearchResult(this,
searchParameters, fromGroup, max)
}
fun createVirtualGroupFromSearchInfo(searchInfoString: String,
max: Int = Integer.MAX_VALUE): Group? {
return mSearchHelper?.createVirtualGroupWithSearchResult(this,
return mSearchHelper.createVirtualGroupWithSearchResult(this,
SearchParameters().apply {
searchQuery = searchInfoString
searchInTitles = true
@@ -1367,5 +1324,73 @@ class Database {
companion object : SingletonHolder<Database>(::Database) {
private val TAG = Database::class.java.name
@Throws(Exception::class)
private fun readDatabaseStream(contentResolver: ContentResolver,
databaseUri: Uri,
openDatabaseKDB: (InputStream) -> Unit,
openDatabaseKDBX: (InputStream) -> Unit) {
// Load Data, pass Uris as InputStreams
val databaseStream = UriUtil.getUriInputStream(contentResolver, databaseUri)
?: throw IOException("Database input stream cannot be retrieve")
BufferedInputStream(databaseStream).use { databaseInputStream ->
if (!databaseInputStream.markSupported()) {
throw IOException("Input stream does not support mark.")
}
// We'll end up reading 8 bytes to identify the header. Might as well use two extra.
databaseInputStream.mark(10)
// Get the file directory to save the attachments
val sig1 = databaseInputStream.readBytes4ToUInt()
val sig2 = databaseInputStream.readBytes4ToUInt()
// Return to the start
databaseInputStream.reset()
when {
// Header of database KDB
DatabaseHeaderKDB.matchesHeader(sig1, sig2) -> openDatabaseKDB(
databaseInputStream
)
// Header of database KDBX
DatabaseHeaderKDBX.matchesHeader(sig1, sig2) -> openDatabaseKDBX(
databaseInputStream
)
// Header not recognized
else -> throw SignatureDatabaseException()
}
}
}
@Throws(LoadDatabaseException::class)
fun getTransformSeed(
contentResolver: ContentResolver,
databaseUri: Uri,
onTransformSeedRetrieved: (ByteArray?) -> Unit
) {
try {
// Read database stream for the first time
readDatabaseStream(
contentResolver, databaseUri,
{ _ ->
},
{ databaseKDBXInputStream ->
val header = DatabaseHeaderKDBX(DatabaseKDBX())
header.loadFromFile(databaseKDBXInputStream)
val transformSeed = ByteArray(64)
header.transformSeed?.copyInto(transformSeed, 0, 0, 32)
// seed: 32 byte transform seed, needs to be padded before sent to the hardware
transformSeed.fill(32, 32, 64)
onTransformSeedRetrieved(transformSeed)
}
)
} catch (e: LoadDatabaseException) {
throw e
} catch (e: Exception) {
throw LoadDatabaseException(e)
}
}
}
}
@@ -1,13 +1,11 @@
package com.kunzisoft.keepass.hardware
enum class HardwareKey(val value: String) {
HMAC_SHA1_KPXC("HMAC-SHA1 KPXC"),
HMAC_SHA1_KP2("HMAC-SHA1 KP2"),
OATH_HOTP("OATH HOTP"),
HMAC_SECRET_FIDO2("HMAC-SECRET FIDO2");
FIDO2_SECRET("FIDO2 secret"),
CHALLENGE_RESPONSE_YUBIKEY("Yubikey challenge-response");
companion object {
val DEFAULT = HMAC_SHA1_KPXC
val DEFAULT = FIDO2_SECRET
fun getStringValues(): List<String> {
return values().map { it.value }
@@ -15,10 +13,8 @@ enum class HardwareKey(val value: String) {
fun fromPosition(position: Int): HardwareKey {
return when (position) {
0 -> HMAC_SHA1_KPXC
1 -> HMAC_SHA1_KP2
2 -> OATH_HOTP
3 -> HMAC_SECRET_FIDO2
0 -> FIDO2_SECRET
1 -> CHALLENGE_RESPONSE_YUBIKEY
else -> DEFAULT
}
}
@@ -1,10 +1,9 @@
package com.kunzisoft.keepass.hardware
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ContentResolver
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
@@ -12,12 +11,7 @@ import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.kunzisoft.keepass.database.element.database.DatabaseKDBX
import com.kunzisoft.keepass.database.file.DatabaseHeaderKDBX
import com.kunzisoft.keepass.utils.UriUtil
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import com.kunzisoft.keepass.database.element.Database
class HardwareKeyResponseHelper {
@@ -36,14 +30,16 @@ class HardwareKeyResponseHelper {
this.fragment = context
}
fun buildHardwareKeyResponse(onChallengeResponded: ((challengeResponse:ByteArray?) -> Unit)?) {
fun buildHardwareKeyResponse(onChallengeResponded: ((challengeResponse:ByteArray?,
extra: Bundle?) -> Unit)?) {
val resultCallback = ActivityResultCallback<ActivityResult> { result ->
Log.d(TAG, "resultCode from ykdroid: " + result.resultCode)
if (result.resultCode == Activity.RESULT_OK) {
val challengeResponse: ByteArray? = result.data?.getByteArrayExtra("response")
Log.d(TAG, "Response: " + challengeResponse.contentToString())
challengeResponse?.let {
onChallengeResponded?.invoke(challengeResponse)
onChallengeResponded?.invoke(challengeResponse,
result.data?.getBundleExtra(EXTRA_BUNDLE_KEY))
}
}
}
@@ -61,37 +57,20 @@ class HardwareKeyResponseHelper {
}
}
fun launchChallengeForResponse(databaseUri: Uri) {
fragment?.context?.contentResolver ?: activity?.contentResolver ?.let { contentResolver ->
getTransformSeedFromHeader(databaseUri, contentResolver)?.let { seed ->
try {
fun launchChallengeForResponse(databaseUri: Uri, extra: Bundle? = null) {
try {
fragment?.context?.contentResolver ?: activity?.contentResolver ?.let { contentResolver ->
Database.getTransformSeed(contentResolver, databaseUri) { seed ->
getChallengeResponseResultLauncher?.launch(Intent(YKDROID_CHALLENGE_RESPONSE_INTENT).apply {
putExtra(YKDROID_SEED_KEY, seed)
putExtra(EXTRA_BUNDLE_KEY, extra)
})
Log.d(TAG, "Challenge sent : " + seed.contentToString())
} catch (e: ActivityNotFoundException) {
// TODO better error
throw IOException("No activity to handle $YKDROID_CHALLENGE_RESPONSE_INTENT intent")
}
}
}
}
private fun getTransformSeedFromHeader(uri: Uri, contentResolver: ContentResolver): ByteArray? {
try {
BufferedInputStream(UriUtil.getUriInputStream(contentResolver, uri)).use { databaseInputStream ->
val header = DatabaseHeaderKDBX(DatabaseKDBX())
header.loadFromFile(databaseInputStream)
val challenge = ByteArray(64)
header.transformSeed?.copyInto(challenge, 0, 0, 32)
// seed: 32 byte transform seed, needs to be padded before sent to the hardware
challenge.fill(32, 32, 64)
return challenge
}
} catch (e: Exception) {
Log.e(TAG, "Could not read transform seed from file", e)
Log.e(TAG, "Could not launch challenge for response", e)
}
return null
}
companion object {
@@ -99,6 +78,7 @@ class HardwareKeyResponseHelper {
private const val YKDROID_CHALLENGE_RESPONSE_INTENT = "net.pp3345.ykdroid.intent.action.CHALLENGE_RESPONSE"
private const val YKDROID_SEED_KEY = "challenge"
private const val EXTRA_BUNDLE_KEY = "EXTRA_BUNDLE_KEY"
}
}
@@ -126,6 +126,26 @@ object ParcelableUtil {
}
}
fun Parcel.readByteArrayCompat(): ByteArray? {
val dataLength = readInt()
return if (dataLength >= 0) {
val data = ByteArray(dataLength)
readByteArray(data)
data
} else {
null
}
}
fun Parcel.writeByteArrayCompat(data: ByteArray?) {
if (data != null) {
writeInt(data.size)
writeByteArray(data)
} else {
writeInt(-1)
}
}
inline fun <reified T : Enum<T>> Parcel.readEnum() =
readString()?.let { enumValueOf<T>(it) }