Implement Rust-owned Android Keystore secure storage (#93)
Dependency security audit / rustsec (push) Failing after 23s
Dependency security audit / rustsec (push) Failing after 23s
This commit is contained in:
1 parent
874c8139a4
commit
1abd75282e
36 files changed
+4380
-37
No files matched your search
@@ -0,0 +1,5 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application>
|
||||
<activity android:name="de.rfc1437.ironstorage.platform.KeystoreTestActivity" android:exported="false" android:theme="@android:style/Theme.Material.Light.NoActionBar" />
|
||||
</application>
|
||||
</manifest>
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
package de.rfc1437.ironstorage.platform
|
||||
|
||||
import android.security.keystore.KeyInfo
|
||||
import androidx.test.core.app.ActivityScenario
|
||||
import androidx.test.filters.SdkSuppress
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import de.rfc1437.ironstorage.core.KeystoreAuthorization
|
||||
import de.rfc1437.ironstorage.core.KeystoreException
|
||||
import de.rfc1437.ironstorage.core.KeystoreFailure
|
||||
import de.rfc1437.ironstorage.core.KeystoreKeySpecification
|
||||
import java.security.KeyStore
|
||||
import java.util.UUID
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class AndroidKeystoreTest {
|
||||
private val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
|
||||
@Before fun removeAbandonedFixtureKeys() {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
os.aliases().filter {
|
||||
it.startsWith("ironstorage.issue93.fixture.")
|
||||
}.forEach { os.deleteKey(it) }
|
||||
}
|
||||
private fun alias(): String = "ironstorage.issue93.fixture.${UUID.randomUUID()}"
|
||||
private fun specification(
|
||||
alias: String,
|
||||
auth: KeystoreAuthorization = KeystoreAuthorization.None
|
||||
) = KeystoreKeySpecification(
|
||||
alias,
|
||||
auth,
|
||||
true,
|
||||
auth == KeystoreAuthorization.StrongBiometric,
|
||||
false
|
||||
)
|
||||
private fun failure(expected: KeystoreFailure, block: () -> Unit) {
|
||||
try {
|
||||
block()
|
||||
throw AssertionError("Expected typed failure")
|
||||
} catch (
|
||||
error: KeystoreException
|
||||
) {
|
||||
assertEquals(expected, error.kind)
|
||||
assertEquals("Keystore operation failed", error.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun deviceUnlockedRoundtripReplaceDeleteAndTamper() {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
assertFalse(os.deviceState().locked)
|
||||
val alias = alias()
|
||||
try {
|
||||
os.createKey(specification(alias))
|
||||
failure(KeystoreFailure.AlreadyExists) { os.createKey(specification(alias)) }
|
||||
val clear = "public-test-token".toByteArray()
|
||||
val encrypted = os.encrypt(alias, KeystoreAuthorization.None, byteArrayOf(1, 2), clear)
|
||||
assertTrue(clear.all { it == 0.toByte() })
|
||||
assertEquals(12, encrypted.nonce.size)
|
||||
val retrieved = os.decrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.None,
|
||||
byteArrayOf(1, 2),
|
||||
encrypted
|
||||
)
|
||||
try {
|
||||
assertArrayEquals("public-test-token".toByteArray(), retrieved)
|
||||
} finally {
|
||||
retrieved.fill(0)
|
||||
}
|
||||
failure(KeystoreFailure.Corrupted) {
|
||||
os.decrypt(alias, KeystoreAuthorization.None, byteArrayOf(3), encrypted)
|
||||
}
|
||||
encrypted.bytes[encrypted.bytes.lastIndex] =
|
||||
(encrypted.bytes.last().toInt() xor 1).toByte()
|
||||
failure(KeystoreFailure.Corrupted) {
|
||||
os.decrypt(alias, KeystoreAuthorization.None, byteArrayOf(1, 2), encrypted)
|
||||
}
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
val key = store.getKey(alias, null) as SecretKey
|
||||
val info = SecretKeyFactory.getInstance(
|
||||
key.algorithm,
|
||||
"AndroidKeyStore"
|
||||
).getKeySpec(key, KeyInfo::class.java) as KeyInfo
|
||||
assertEquals(256, info.keySize)
|
||||
assertFalse(info.isUserAuthenticationRequired)
|
||||
assertTrue(os.aliases().contains(alias))
|
||||
os.deleteKey(alias)
|
||||
failure(KeystoreFailure.MissingKey) {
|
||||
os.decrypt(alias, KeystoreAuthorization.None, byteArrayOf(1, 2), encrypted)
|
||||
}
|
||||
os.deleteKey(alias)
|
||||
} finally {
|
||||
os.deleteKey(alias)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun biometricRoundtripAndCancellation() {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
assertTrue(
|
||||
"Enroll synthetic fingerprint before this test",
|
||||
os.deviceState().strongBiometric
|
||||
)
|
||||
val alias = alias()
|
||||
ActivityScenario.launch(KeystoreTestActivity::class.java).use { scenario ->
|
||||
lateinit var host: KeystoreTestActivity
|
||||
scenario.onActivity {
|
||||
host = it
|
||||
os.attach(it)
|
||||
}
|
||||
try {
|
||||
os.createKey(specification(alias, KeystoreAuthorization.StrongBiometric))
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
val key = store.getKey(alias, null) as SecretKey
|
||||
val info = SecretKeyFactory.getInstance(
|
||||
key.algorithm,
|
||||
"AndroidKeyStore"
|
||||
).getKeySpec(key, KeyInfo::class.java) as KeyInfo
|
||||
assertTrue(info.isUserAuthenticationRequired)
|
||||
assertTrue(info.isInvalidatedByBiometricEnrollment)
|
||||
assertEquals(0, info.userAuthenticationValidityDurationSeconds)
|
||||
host.stage("93:biometric-encrypt")
|
||||
val encrypted = os.encrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.StrongBiometric,
|
||||
byteArrayOf(4),
|
||||
"public-passphrase".toByteArray()
|
||||
)
|
||||
host.stage("93:biometric-decrypt")
|
||||
val clear = os.decrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.StrongBiometric,
|
||||
byteArrayOf(4),
|
||||
encrypted
|
||||
)
|
||||
try {
|
||||
assertArrayEquals("public-passphrase".toByteArray(), clear)
|
||||
} finally {
|
||||
clear.fill(0)
|
||||
}
|
||||
host.stage("93:biometric-cancel")
|
||||
failure(KeystoreFailure.Cancelled) {
|
||||
os.decrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.StrongBiometric,
|
||||
byteArrayOf(4),
|
||||
encrypted
|
||||
)
|
||||
}
|
||||
host.stage("93:complete")
|
||||
} catch (error: KeystoreException) {
|
||||
throw AssertionError("Typed Keystore failure: ${error.kind}", error)
|
||||
} finally {
|
||||
os.cancelPending()
|
||||
os.detach(host)
|
||||
os.deleteKey(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun userPresenceSupportsTheConfiguredCredentialFlow() {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
val alias = alias()
|
||||
ActivityScenario.launch(KeystoreTestActivity::class.java).use { scenario ->
|
||||
lateinit var host: KeystoreTestActivity
|
||||
scenario.onActivity {
|
||||
host = it
|
||||
os.attach(it)
|
||||
}
|
||||
try {
|
||||
os.createKey(specification(alias, KeystoreAuthorization.UserPresence))
|
||||
host.stage("93:presence-encrypt")
|
||||
val encrypted = os.encrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.UserPresence,
|
||||
byteArrayOf(7),
|
||||
"public-passphrase".toByteArray()
|
||||
)
|
||||
host.stage("93:presence-decrypt")
|
||||
val clear = os.decrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.UserPresence,
|
||||
byteArrayOf(7),
|
||||
encrypted
|
||||
)
|
||||
try {
|
||||
assertArrayEquals("public-passphrase".toByteArray(), clear)
|
||||
} finally {
|
||||
clear.fill(0)
|
||||
}
|
||||
} catch (error: KeystoreException) {
|
||||
throw AssertionError("Typed Keystore failure: ${error.kind}", error)
|
||||
} finally {
|
||||
os.cancelPending()
|
||||
os.detach(host)
|
||||
os.deleteKey(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SdkSuppress(maxSdkVersion = 36)
|
||||
fun biometricLockoutIsTyped() {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
val alias = alias()
|
||||
ActivityScenario.launch(KeystoreTestActivity::class.java).use { scenario ->
|
||||
lateinit var host: KeystoreTestActivity
|
||||
scenario.onActivity {
|
||||
host = it
|
||||
os.attach(it)
|
||||
}
|
||||
try {
|
||||
os.createKey(specification(alias, KeystoreAuthorization.StrongBiometric))
|
||||
host.stage("93:biometric-lockout")
|
||||
failure(KeystoreFailure.Lockout) {
|
||||
os.encrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.StrongBiometric,
|
||||
byteArrayOf(8),
|
||||
"public-passphrase".toByteArray()
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
os.cancelPending()
|
||||
os.detach(host)
|
||||
os.deleteKey(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SdkSuppress(minSdkVersion = 37)
|
||||
fun biometricLockoutRecoveryStillRequiresMatchingBiometric() {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
val alias = alias()
|
||||
ActivityScenario.launch(KeystoreTestActivity::class.java).use { scenario ->
|
||||
lateinit var host: KeystoreTestActivity
|
||||
scenario.onActivity {
|
||||
host = it
|
||||
os.attach(it)
|
||||
}
|
||||
try {
|
||||
os.createKey(specification(alias, KeystoreAuthorization.StrongBiometric))
|
||||
host.stage("93:biometric-lockout-recovery")
|
||||
failure(KeystoreFailure.Cancelled) {
|
||||
os.encrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.StrongBiometric,
|
||||
byteArrayOf(8),
|
||||
"public-passphrase".toByteArray()
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
os.cancelPending()
|
||||
os.detach(host)
|
||||
os.deleteKey(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun addingBiometricInvalidatesTheProtectedKey() = invalidation("93:add-enrollment")
|
||||
|
||||
@Test fun removingAllBiometricsInvalidatesTheProtectedKey() = invalidation(
|
||||
"93:remove-enrollment"
|
||||
)
|
||||
|
||||
@Test fun removingSecureLockInvalidatesTheProtectedKey() =
|
||||
invalidation("93:remove-lock", KeystoreFailure.MissingKey)
|
||||
|
||||
private fun invalidation(
|
||||
stage: String,
|
||||
expected: KeystoreFailure = KeystoreFailure.Invalidated
|
||||
) {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
assertTrue(os.deviceState().strongBiometric)
|
||||
val alias = alias()
|
||||
val credentialAlias = alias()
|
||||
ActivityScenario.launch(KeystoreTestActivity::class.java).use { scenario ->
|
||||
lateinit var host: KeystoreTestActivity
|
||||
scenario.onActivity {
|
||||
host = it
|
||||
os.attach(it)
|
||||
}
|
||||
try {
|
||||
os.createKey(specification(credentialAlias))
|
||||
val credential = os.encrypt(
|
||||
credentialAlias,
|
||||
KeystoreAuthorization.None,
|
||||
byteArrayOf(10),
|
||||
"public-token".toByteArray()
|
||||
)
|
||||
os.createKey(specification(alias, KeystoreAuthorization.StrongBiometric))
|
||||
host.stage("93:biometric-encrypt")
|
||||
val encrypted = os.encrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.StrongBiometric,
|
||||
byteArrayOf(9),
|
||||
"public-passphrase".toByteArray()
|
||||
)
|
||||
assertTrue(
|
||||
"Complete the indicated emulator fixture change",
|
||||
host.awaitStep(stage)
|
||||
)
|
||||
if (expected ==
|
||||
KeystoreFailure.MissingKey
|
||||
) {
|
||||
assertFalse(os.aliases().contains(alias))
|
||||
}
|
||||
val token = os.decrypt(
|
||||
credentialAlias,
|
||||
KeystoreAuthorization.None,
|
||||
byteArrayOf(10),
|
||||
credential
|
||||
)
|
||||
try {
|
||||
assertArrayEquals("public-token".toByteArray(), token)
|
||||
} finally {
|
||||
token.fill(0)
|
||||
}
|
||||
failure(expected) {
|
||||
os.decrypt(
|
||||
alias,
|
||||
KeystoreAuthorization.StrongBiometric,
|
||||
byteArrayOf(9),
|
||||
encrypted
|
||||
)
|
||||
}
|
||||
} catch (error: KeystoreException) {
|
||||
throw AssertionError("Typed Keystore failure: ${error.kind}", error)
|
||||
} finally {
|
||||
os.cancelPending()
|
||||
os.detach(host)
|
||||
os.deleteKey(alias)
|
||||
os.deleteKey(credentialAlias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun protectedKeyRequiresAnAuthenticationHost() {
|
||||
val os = AndroidKeystoreAdapter(context)
|
||||
assertTrue(os.deviceState().strongBiometric)
|
||||
val alias = alias()
|
||||
try {
|
||||
os.createKey(specification(alias, KeystoreAuthorization.StrongBiometric))
|
||||
val value = "public-test-passphrase".toByteArray()
|
||||
failure(KeystoreFailure.Unavailable) {
|
||||
os.encrypt(alias, KeystoreAuthorization.StrongBiometric, byteArrayOf(1), value)
|
||||
}
|
||||
assertTrue(value.all { it == 0.toByte() })
|
||||
} finally {
|
||||
os.deleteKey(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package de.rfc1437.ironstorage.platform
|
||||
|
||||
import android.os.Bundle
|
||||
import android.widget.Button
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import de.rfc1437.ironstorage.platform.test.R
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/** Instrumentation host, omitted from release builds; shows stages, never secrets. */
|
||||
class KeystoreTestActivity : FragmentActivity() {
|
||||
private lateinit var label: TextView
|
||||
private val step = AtomicReference<CountDownLatch?>()
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
label = TextView(this).apply {
|
||||
setText(R.string.keystore_fixture_title)
|
||||
textSize = 24f
|
||||
}
|
||||
val next = Button(this).apply {
|
||||
setText(R.string.keystore_fixture_continue)
|
||||
setOnClickListener { step.get()?.countDown() }
|
||||
}
|
||||
setContentView(
|
||||
LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(0, 80, 0, 0)
|
||||
addView(label)
|
||||
addView(next)
|
||||
}
|
||||
)
|
||||
}
|
||||
fun awaitStep(value: String): Boolean {
|
||||
val next = CountDownLatch(1)
|
||||
step.set(next)
|
||||
stage(value)
|
||||
return try {
|
||||
next.await(180, TimeUnit.SECONDS)
|
||||
} finally {
|
||||
step.set(null)
|
||||
}
|
||||
}
|
||||
fun stage(value: String) {
|
||||
android.util.Log.i("IronStorage93", value)
|
||||
runOnUiThread { label.text = value }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<string name="keystore_fixture_title" translatable="false">Keystore fixture</string>
|
||||
<string name="keystore_fixture_continue" translatable="false">Continue fixture</string>
|
||||
</resources>
|
||||
@@ -1 +1,3 @@
|
||||
<manifest />
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
|
||||
</manifest>
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
package de.rfc1437.ironstorage.platform
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyPermanentlyInvalidatedException
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.security.keystore.StrongBoxUnavailableException
|
||||
import android.security.keystore.UserNotAuthenticatedException
|
||||
import androidx.biometric.BiometricManager
|
||||
import androidx.biometric.BiometricPrompt
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import de.rfc1437.ironstorage.core.AndroidKeystore
|
||||
import de.rfc1437.ironstorage.core.KeystoreAuthorization
|
||||
import de.rfc1437.ironstorage.core.KeystoreCiphertext
|
||||
import de.rfc1437.ironstorage.core.KeystoreDeviceState
|
||||
import de.rfc1437.ironstorage.core.KeystoreException
|
||||
import de.rfc1437.ironstorage.core.KeystoreFailure
|
||||
import de.rfc1437.ironstorage.core.KeystoreKeySpecification
|
||||
import java.lang.ref.WeakReference
|
||||
import java.security.KeyStore
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import javax.crypto.AEADBadTagException
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/** Android API mechanics only; ciphertext is returned to Rust for private persistence. */
|
||||
class AndroidKeystoreAdapter(context: Context) : AndroidKeystore {
|
||||
private val context = context.applicationContext
|
||||
private val keyguard = context.getSystemService(KeyguardManager::class.java)
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var activity = WeakReference<FragmentActivity>(null)
|
||||
private val pending = AtomicReference<Pending?>()
|
||||
|
||||
fun attach(host: FragmentActivity) {
|
||||
activity = WeakReference(host)
|
||||
}
|
||||
fun detach(host: FragmentActivity) {
|
||||
if (activity.get() === host) {
|
||||
cancelPending()
|
||||
activity.clear()
|
||||
}
|
||||
}
|
||||
override fun deviceState(): KeystoreDeviceState = KeystoreDeviceState(
|
||||
Build.VERSION.SDK_INT,
|
||||
keyguard.isDeviceLocked,
|
||||
keyguard.isDeviceSecure,
|
||||
BiometricManager.from(
|
||||
context
|
||||
).canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) ==
|
||||
BiometricManager.BIOMETRIC_SUCCESS,
|
||||
Build.VERSION.SDK_INT >= 28 &&
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
||||
)
|
||||
override fun createKey(specification: KeystoreKeySpecification) = operation {
|
||||
val store = store()
|
||||
if (store.containsAlias(specification.alias)) fail(KeystoreFailure.AlreadyExists)
|
||||
val builder = KeyGenParameterSpec.Builder(
|
||||
specification.alias,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
|
||||
)
|
||||
.setKeySize(256)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setRandomizedEncryptionRequired(true)
|
||||
if (specification.unlockedDevice) {
|
||||
if (Build.VERSION.SDK_INT < 28) fail(KeystoreFailure.UnsupportedProtection)
|
||||
builder.setUnlockedDeviceRequired(true)
|
||||
}
|
||||
if (specification.strongbox) {
|
||||
if (Build.VERSION.SDK_INT < 28) fail(KeystoreFailure.StrongboxUnavailable)
|
||||
builder.setIsStrongBoxBacked(true)
|
||||
}
|
||||
if (specification.authorization != KeystoreAuthorization.None) {
|
||||
builder.setUserAuthenticationRequired(true)
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
val authenticators = when (specification.authorization) {
|
||||
KeystoreAuthorization.StrongBiometric -> KeyProperties.AUTH_BIOMETRIC_STRONG
|
||||
KeystoreAuthorization.UserPresence ->
|
||||
KeyProperties.AUTH_BIOMETRIC_STRONG or
|
||||
KeyProperties.AUTH_DEVICE_CREDENTIAL
|
||||
KeystoreAuthorization.None -> fail(KeystoreFailure.UnsupportedProtection)
|
||||
}
|
||||
builder.setUserAuthenticationParameters(0, authenticators)
|
||||
} else {
|
||||
if (specification.authorization !=
|
||||
KeystoreAuthorization.StrongBiometric
|
||||
) {
|
||||
fail(KeystoreFailure.UnsupportedProtection)
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
builder.setUserAuthenticationValidityDurationSeconds(-1)
|
||||
}
|
||||
builder.setInvalidatedByBiometricEnrollment(specification.invalidateOnEnrollment)
|
||||
}
|
||||
KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
|
||||
init(builder.build())
|
||||
generateKey()
|
||||
}
|
||||
Unit
|
||||
}
|
||||
override fun encrypt(
|
||||
alias: String,
|
||||
authorization: KeystoreAuthorization,
|
||||
aad: ByteArray,
|
||||
value: ByteArray
|
||||
): KeystoreCiphertext = operation {
|
||||
try {
|
||||
requireUnlocked()
|
||||
val cipher = cipher(alias, Cipher.ENCRYPT_MODE, null)
|
||||
// Auth-bound providers can process AAD immediately.
|
||||
authenticate(cipher, authorization)
|
||||
cipher.updateAAD(aad)
|
||||
val bytes = cipher.doFinal(value)
|
||||
requireUnlocked()
|
||||
KeystoreCiphertext(cipher.iv, bytes)
|
||||
} finally {
|
||||
value.fill(0)
|
||||
}
|
||||
}
|
||||
override fun decrypt(
|
||||
alias: String,
|
||||
authorization: KeystoreAuthorization,
|
||||
aad: ByteArray,
|
||||
value: KeystoreCiphertext
|
||||
): ByteArray = operation {
|
||||
requireUnlocked()
|
||||
if (value.nonce.size != 12 || value.bytes.size < 17) fail(KeystoreFailure.Corrupted)
|
||||
val cipher = cipher(alias, Cipher.DECRYPT_MODE, value.nonce)
|
||||
authenticate(cipher, authorization)
|
||||
cipher.updateAAD(aad)
|
||||
val clear = cipher.doFinal(value.bytes)
|
||||
try {
|
||||
requireUnlocked()
|
||||
clear
|
||||
} catch (error: Exception) {
|
||||
clear.fill(0)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
override fun deleteKey(alias: String) = operation { store().deleteEntry(alias) }
|
||||
override fun aliases(): List<String> = operation { store().aliases().toList() }
|
||||
override fun cancelPending() {
|
||||
pending.getAndSet(null)?.let { request ->
|
||||
request.error.set(KeystoreFailure.Cancelled)
|
||||
request.done.countDown()
|
||||
handler.post {
|
||||
request.prompt?.cancelAuthentication()
|
||||
request.prompt = null
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun store(): KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
private fun cipher(alias: String, mode: Int, nonce: ByteArray?): Cipher {
|
||||
val key = store().getKey(alias, null) as? SecretKey
|
||||
?: fail(KeystoreFailure.MissingKey)
|
||||
return Cipher.getInstance("AES/GCM/NoPadding").apply {
|
||||
if (nonce == null) {
|
||||
init(mode, key)
|
||||
} else {
|
||||
init(mode, key, GCMParameterSpec(128, nonce))
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun requireUnlocked() {
|
||||
if (keyguard.isDeviceLocked) fail(KeystoreFailure.Locked)
|
||||
}
|
||||
private class Pending {
|
||||
val done = CountDownLatch(1)
|
||||
val error = AtomicReference<KeystoreFailure?>()
|
||||
val authenticated = AtomicReference<Cipher?>()
|
||||
var prompt: BiometricPrompt? = null
|
||||
}
|
||||
private fun authenticate(cipher: Cipher, authorization: KeystoreAuthorization) {
|
||||
if (authorization == KeystoreAuthorization.None) return
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) fail(KeystoreFailure.Unavailable)
|
||||
val request = Pending()
|
||||
if (!pending.compareAndSet(null, request)) fail(KeystoreFailure.Unavailable)
|
||||
handler.post {
|
||||
if (pending.get() !== request) return@post
|
||||
val host = activity.get()
|
||||
if (host == null || host.isFinishing || host.isDestroyed) {
|
||||
request.error.set(KeystoreFailure.Unavailable)
|
||||
request.done.countDown()
|
||||
return@post
|
||||
}
|
||||
try {
|
||||
val callback = object : BiometricPrompt.AuthenticationCallback() {
|
||||
override fun onAuthenticationSucceeded(
|
||||
result: BiometricPrompt.AuthenticationResult
|
||||
) {
|
||||
if (pending.get() ===
|
||||
request
|
||||
) {
|
||||
request.authenticated.set(result.cryptoObject?.cipher)
|
||||
}
|
||||
request.done.countDown()
|
||||
}
|
||||
override fun onAuthenticationError(code: Int, message: CharSequence) {
|
||||
request.error.set(
|
||||
when (code) {
|
||||
BiometricPrompt.ERROR_CANCELED,
|
||||
BiometricPrompt.ERROR_USER_CANCELED,
|
||||
BiometricPrompt.ERROR_NEGATIVE_BUTTON ->
|
||||
KeystoreFailure.Cancelled
|
||||
BiometricPrompt.ERROR_LOCKOUT,
|
||||
BiometricPrompt.ERROR_LOCKOUT_PERMANENT ->
|
||||
KeystoreFailure.Lockout
|
||||
BiometricPrompt.ERROR_NO_BIOMETRICS,
|
||||
BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL,
|
||||
BiometricPrompt.ERROR_HW_NOT_PRESENT ->
|
||||
KeystoreFailure.UnsupportedProtection
|
||||
else -> KeystoreFailure.Denied
|
||||
}
|
||||
)
|
||||
request.done.countDown()
|
||||
}
|
||||
}
|
||||
val prompt = BiometricPrompt(host, { handler.post(it) }, callback)
|
||||
request.prompt = prompt
|
||||
val information = BiometricPrompt.PromptInfo.Builder().setTitle(
|
||||
context.getString(R.string.keystore_prompt_title)
|
||||
)
|
||||
if (authorization == KeystoreAuthorization.StrongBiometric) {
|
||||
information.setAllowedAuthenticators(
|
||||
BiometricManager.Authenticators.BIOMETRIC_STRONG
|
||||
).setNegativeButtonText(context.getString(R.string.keystore_prompt_cancel))
|
||||
} else {
|
||||
if (Build.VERSION.SDK_INT < 30) fail(KeystoreFailure.UnsupportedProtection)
|
||||
information.setAllowedAuthenticators(
|
||||
BiometricManager.Authenticators.BIOMETRIC_STRONG or
|
||||
BiometricManager.Authenticators.DEVICE_CREDENTIAL
|
||||
)
|
||||
}
|
||||
prompt.authenticate(information.build(), BiometricPrompt.CryptoObject(cipher))
|
||||
} catch (error: Exception) {
|
||||
request.error.set(
|
||||
if (error is KeystoreException) error.kind else KeystoreFailure.Unavailable
|
||||
)
|
||||
request.done.countDown()
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (!request.done.await(180, TimeUnit.SECONDS)) fail(KeystoreFailure.Cancelled)
|
||||
request.error.get()?.let { fail(it) }
|
||||
if (request.authenticated.get() !== cipher ||
|
||||
pending.get() !== request
|
||||
) {
|
||||
fail(KeystoreFailure.Cancelled)
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
fail(KeystoreFailure.Cancelled)
|
||||
} finally {
|
||||
pending.compareAndSet(request, null)
|
||||
val succeeded = request.authenticated.getAndSet(null) === cipher
|
||||
handler.post {
|
||||
if (!succeeded) request.prompt?.cancelAuthentication()
|
||||
request.prompt = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun fail(kind: KeystoreFailure): Nothing = throw KeystoreException(kind)
|
||||
private inline fun <T> operation(block: () -> T): T = try {
|
||||
block()
|
||||
} catch (error: Exception) {
|
||||
if (error is KeystoreException) throw error
|
||||
var cause: Throwable? = error
|
||||
var kind = KeystoreFailure.Unavailable
|
||||
repeat(8) {
|
||||
val osError = cause
|
||||
if (kind == KeystoreFailure.Unavailable && Build.VERSION.SDK_INT >= 33 &&
|
||||
osError is android.security.KeyStoreException
|
||||
) {
|
||||
kind = when (osError.numericErrorCode) {
|
||||
android.security.KeyStoreException.ERROR_USER_AUTHENTICATION_REQUIRED ->
|
||||
KeystoreFailure.Locked
|
||||
android.security.KeyStoreException.ERROR_KEY_DOES_NOT_EXIST ->
|
||||
KeystoreFailure.MissingKey
|
||||
android.security.KeyStoreException.ERROR_KEY_CORRUPTED -> KeystoreFailure.Corrupted
|
||||
android.security.KeyStoreException.ERROR_PERMISSION_DENIED -> KeystoreFailure.Denied
|
||||
android.security.KeyStoreException.ERROR_UNIMPLEMENTED ->
|
||||
KeystoreFailure.UnsupportedProtection
|
||||
else -> kind
|
||||
}
|
||||
}
|
||||
when {
|
||||
cause is KeyPermanentlyInvalidatedException -> kind = KeystoreFailure.Invalidated
|
||||
cause is UserNotAuthenticatedException -> kind = KeystoreFailure.Locked
|
||||
cause is AEADBadTagException -> kind = KeystoreFailure.Corrupted
|
||||
Build.VERSION.SDK_INT >= 28 && cause is StrongBoxUnavailableException ->
|
||||
kind = KeystoreFailure.StrongboxUnavailable
|
||||
}
|
||||
cause = cause?.cause
|
||||
}
|
||||
throw KeystoreException(kind)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<string name="keystore_prompt_title">Unlock protected secret</string>
|
||||
<string name="keystore_prompt_cancel">Cancel</string>
|
||||
</resources>
|
||||
Reference in new issue
Block a user