Compare commits
13 changed files with 43 additions and 1245 deletions
|
|
@ -94,49 +94,6 @@ exclusions, because an auto-backup of `onionwire.db` would hand the wrapped
|
||||||
message key *and* the plaintext identity keys to Google Drive. Chat bodies are
|
message key *and* the plaintext identity keys to Google Drive. Chat bodies are
|
||||||
encrypted at rest; identity keys are not — that is the locked v1 posture.
|
encrypted at rest; identity keys are not — that is the locked v1 posture.
|
||||||
|
|
||||||
### The store passphrase at rest
|
|
||||||
|
|
||||||
Typing the passphrase on every launch is no longer required. On first unlock
|
|
||||||
the passphrase can be remembered (checkbox, on by default), and it is then
|
|
||||||
stored as an AES-256-GCM blob:
|
|
||||||
|
|
||||||
* the wrapping key is generated inside the **Android Keystore** under alias
|
|
||||||
`onionwire.store`, AES-256-GCM, `setUserAuthenticationRequired(false)` —
|
|
||||||
deliberately **not** biometric-gated, because a fingerprint prompt would turn
|
|
||||||
"the node opens or tells you why it did not" into "the node is unusable";
|
|
||||||
* **StrongBox is requested first** (`setIsStrongBoxBacked(true)`, guarded by
|
|
||||||
`FEATURE_STRONGBOX_KEYSTORE` on API 28+) and falls back to an ordinary
|
|
||||||
TEE-backed or software Keystore key when the chip refuses AES-256
|
|
||||||
(`StrongBoxUnavailableException is a ProviderException`). The fallback is
|
|
||||||
reported, not hidden: the lock screen prints what `KeyInfo` actually said,
|
|
||||||
and a software key is labelled **NOT hardware-backed**;
|
|
||||||
* only ciphertext + IV reach disk, at
|
|
||||||
`filesDir/secrets/store-passphrase.bin` — an `OWSEAL1` envelope of
|
|
||||||
magic + IV + ciphertext + GCM tag. No second copy, no `SharedPreferences`,
|
|
||||||
no plaintext in logs, and the typed `CharArray` is zeroed as soon as the
|
|
||||||
unlock call returns. The text field is a plain `remember`, so the typed
|
|
||||||
passphrase is never written into saved instance state;
|
|
||||||
* **Keystore invalidation is a supported path, not a crash.** A factory reset,
|
|
||||||
an app-data wipe, or a key the platform invalidates leaves a blob that cannot
|
|
||||||
authenticate: `StoredPassphraseStore.load()` returns `Unavailable`, the lock
|
|
||||||
screen explains it, and the user types the passphrase again. A failed read
|
|
||||||
does **not** delete the blob — a transient Keystore failure must not destroy
|
|
||||||
the only copy;
|
|
||||||
* `forget` deletes the blob **and** the Keystore key.
|
|
||||||
|
|
||||||
The one plaintext copy this cannot erase is the immutable `String` the UniFFI
|
|
||||||
binding takes (`openWire(home, passphrase: String)`). A follow-up SDK change
|
|
||||||
should accept the key (or a `ByteArray`) so the passphrase never becomes a
|
|
||||||
`String` at all.
|
|
||||||
|
|
||||||
`app/src/test/.../crypto/` covers the envelope and the file handling on the JVM
|
|
||||||
(the real `StoreSecret` code, with a JVM AES key standing in). The Keystore
|
|
||||||
provider only exists on a device:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
./gradlew :app:connectedDebugAndroidTest # prints the KeyInfo/hardware report
|
|
||||||
```
|
|
||||||
|
|
||||||
### Signing
|
### Signing
|
||||||
|
|
||||||
Release APKs are signed with a **repo-owned keystore**, not the debug key.
|
Release APKs are signed with a **repo-owned keystore**, not the debug key.
|
||||||
|
|
@ -196,8 +153,5 @@ android/
|
||||||
src/main/java/com/siriusdevops/onionwire/
|
src/main/java/com/siriusdevops/onionwire/
|
||||||
MainActivity.kt # NavHost
|
MainActivity.kt # NavHost
|
||||||
WireViewModel.kt # owns the single Wire node
|
WireViewModel.kt # owns the single Wire node
|
||||||
crypto/ # Keystore-wrapped store passphrase
|
|
||||||
ui/ # Compose screens (M3)
|
ui/ # Compose screens (M3)
|
||||||
src/test/ # JVM tests (envelope, store, invite flow)
|
|
||||||
src/androidTest/ # device-only: AndroidKeyStore
|
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,6 @@ android {
|
||||||
// the offline default and match the first automated tag (v0.1.0 → 100).
|
// the offline default and match the first automated tag (v0.1.0 → 100).
|
||||||
versionCode = (findProperty("onionwire.versionCode") as String?)?.toIntOrNull() ?: 100
|
versionCode = (findProperty("onionwire.versionCode") as String?)?.toIntOrNull() ?: 100
|
||||||
versionName = (findProperty("onionwire.versionName") as String?) ?: "0.1.0"
|
versionName = (findProperty("onionwire.versionName") as String?) ?: "0.1.0"
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
|
||||||
ndk {
|
ndk {
|
||||||
abiFilters += onionwireAbis
|
abiFilters += onionwireAbis
|
||||||
}
|
}
|
||||||
|
|
@ -130,10 +129,4 @@ dependencies {
|
||||||
|
|
||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
testImplementation(libs.kotlinx.coroutines.test)
|
testImplementation(libs.kotlinx.coroutines.test)
|
||||||
|
|
||||||
// Device-only: the AndroidKeyStore provider does not exist in the unit-test
|
|
||||||
// JVM. These run under `./gradlew :app:connectedDebugAndroidTest`.
|
|
||||||
androidTestImplementation(libs.junit)
|
|
||||||
androidTestImplementation(libs.androidx.test.ext.junit)
|
|
||||||
androidTestImplementation(libs.androidx.test.runner)
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,150 +0,0 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
|
||||||
import android.util.Log
|
|
||||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
|
||||||
import androidx.test.platform.app.InstrumentationRegistry
|
|
||||||
import org.junit.After
|
|
||||||
import org.junit.Assert.assertArrayEquals
|
|
||||||
import org.junit.Assert.assertFalse
|
|
||||||
import org.junit.Assert.assertNotEquals
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Assert.fail
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.runner.RunWith
|
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The device half of the Keystore story. The unit-test JVM has no
|
|
||||||
* `AndroidKeyStore` provider, so nothing here can run as a plain JUnit test.
|
|
||||||
*
|
|
||||||
* Run on a real device or an emulator:
|
|
||||||
*
|
|
||||||
* ./gradlew :app:connectedDebugAndroidTest
|
|
||||||
*
|
|
||||||
* and read the `OnionWireKeystore` tag in logcat for the actual
|
|
||||||
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
|
|
||||||
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
|
|
||||||
* hardware-backed key on hardware that does not have one.
|
|
||||||
*/
|
|
||||||
@RunWith(AndroidJUnit4::class)
|
|
||||||
class KeystorePassphraseCipherTest {
|
|
||||||
|
|
||||||
private val context: Context =
|
|
||||||
InstrumentationRegistry.getInstrumentation().targetContext
|
|
||||||
|
|
||||||
private val cipher = KeystorePassphraseCipher(context)
|
|
||||||
|
|
||||||
private val passphrase = "correct horse battery staple".toCharArray()
|
|
||||||
|
|
||||||
@After
|
|
||||||
fun tearDown() {
|
|
||||||
cipher.deleteKey()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun seal_open_round_trips_through_the_android_keystore() {
|
|
||||||
val blob = cipher.seal(passphrase)
|
|
||||||
assertTrue(
|
|
||||||
"envelope is magic + IV + ciphertext + tag",
|
|
||||||
blob.size >= passphrase.size + StoreSecret.IV_BYTES + 16 + 9,
|
|
||||||
)
|
|
||||||
val out = cipher.open(blob)
|
|
||||||
try {
|
|
||||||
assertArrayEquals(passphrase, out)
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun stored_blob_on_a_device_is_not_the_plaintext() {
|
|
||||||
val dir = File(context.filesDir, "secrets-test")
|
|
||||||
dir.mkdirs()
|
|
||||||
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
|
|
||||||
try {
|
|
||||||
store.save(passphrase)
|
|
||||||
|
|
||||||
val raw = File(store.path).readBytes()
|
|
||||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
|
||||||
assertFalse(
|
|
||||||
"the passphrase must not appear in the file",
|
|
||||||
String(raw, Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
|
|
||||||
)
|
|
||||||
|
|
||||||
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
|
|
||||||
try {
|
|
||||||
assertArrayEquals(passphrase, loaded.passphrase)
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(loaded.passphrase)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
store.forget()
|
|
||||||
dir.deleteRecursively()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun key_backing_is_reported_and_logged() {
|
|
||||||
cipher.seal(passphrase) // force key creation
|
|
||||||
|
|
||||||
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
|
||||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
|
||||||
val backing = cipher.backing()
|
|
||||||
|
|
||||||
Log.i(
|
|
||||||
"OnionWireKeystore",
|
|
||||||
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
|
|
||||||
"strongBoxAdvertised=$strongBoxAdvertised " +
|
|
||||||
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}",
|
|
||||||
)
|
|
||||||
|
|
||||||
if (strongBoxAdvertised) {
|
|
||||||
assertTrue(
|
|
||||||
"StrongBox is advertised but the key did not land in a secure element: $backing",
|
|
||||||
backing == KeyBacking.STRONGBOX || backing == KeyBacking.HARDWARE,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
assertNotEquals("the API refused to report the backing at all", KeyBacking.UNKNOWN, backing)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun open_does_not_require_user_authentication() {
|
|
||||||
// The card's contract: unlocking must not need a fingerprint. If the
|
|
||||||
// key had been created with setUserAuthenticationRequired(true), this
|
|
||||||
// open() would throw UserNotAuthenticatedException.
|
|
||||||
val out = cipher.open(cipher.seal(passphrase))
|
|
||||||
StoreSecret.wipe(out)
|
|
||||||
assertTrue(cipher.keyPresent())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun deleted_key_reports_unavailable_instead_of_crashing() {
|
|
||||||
val blob = cipher.seal(passphrase)
|
|
||||||
cipher.deleteKey()
|
|
||||||
|
|
||||||
assertFalse(cipher.keyPresent())
|
|
||||||
try {
|
|
||||||
cipher.open(blob)
|
|
||||||
fail("expected SecretUnavailable after the key was deleted")
|
|
||||||
} catch (e: SecretUnavailable) {
|
|
||||||
assertTrue(e.message!!.contains("gone"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun a_regenerated_key_cannot_open_an_old_blob() {
|
|
||||||
val blob = cipher.seal(passphrase)
|
|
||||||
cipher.deleteKey() // a reset that leaves the app's data dir intact
|
|
||||||
cipher.seal(passphrase) // same alias, brand-new key
|
|
||||||
|
|
||||||
try {
|
|
||||||
cipher.open(blob)
|
|
||||||
fail("expected SecretUnavailable for a blob wrapped by the deleted key")
|
|
||||||
} catch (_: SecretUnavailable) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -47,17 +47,10 @@ class MainActivity : ComponentActivity() {
|
||||||
@Composable
|
@Composable
|
||||||
private fun AppRoot(vm: WireViewModel = viewModel()) {
|
private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||||
val phase by vm.phase.collectAsStateWithLifecycle()
|
val phase by vm.phase.collectAsStateWithLifecycle()
|
||||||
val unlock by vm.unlock.collectAsStateWithLifecycle()
|
|
||||||
|
|
||||||
when (val p = phase) {
|
when (val p = phase) {
|
||||||
is Phase.Ready -> ReadyGraph(vm, p)
|
is Phase.Ready -> ReadyGraph(vm, p)
|
||||||
else -> UnlockScreen(
|
else -> UnlockScreen(phase = p, onUnlock = vm::unlock)
|
||||||
phase = p,
|
|
||||||
unlock = unlock,
|
|
||||||
onUnlock = vm::unlock,
|
|
||||||
onUnlockStored = vm::unlockStored,
|
|
||||||
onForgetStored = vm::forgetStoredPassphrase,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,16 +3,10 @@ package com.siriusdevops.onionwire
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
import androidx.lifecycle.AndroidViewModel
|
import androidx.lifecycle.AndroidViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.siriusdevops.onionwire.crypto.KeyBacking
|
|
||||||
import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher
|
|
||||||
import com.siriusdevops.onionwire.crypto.StoreSecret
|
|
||||||
import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import uniffi.onionwire_sdk.ChatMessage
|
import uniffi.onionwire_sdk.ChatMessage
|
||||||
import uniffi.onionwire_sdk.FriendInfo
|
import uniffi.onionwire_sdk.FriendInfo
|
||||||
import uniffi.onionwire_sdk.InviteInfo
|
import uniffi.onionwire_sdk.InviteInfo
|
||||||
|
|
@ -38,23 +32,6 @@ sealed interface Phase {
|
||||||
data class Failed(val message: String) : Phase
|
data class Failed(val message: String) : Phase
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* How the lock screen expects the next unlock to happen.
|
|
||||||
*
|
|
||||||
* This is a probe of local state, not a promise: [OneTap] means a blob exists
|
|
||||||
* *and* decrypted successfully during this process's lifetime.
|
|
||||||
*/
|
|
||||||
sealed interface Unlock {
|
|
||||||
/**
|
|
||||||
* The passphrase must be typed. [notice] explains why a stored one is not
|
|
||||||
* being used (key invalidated, blob corrupt, nothing stored yet).
|
|
||||||
*/
|
|
||||||
data class TypeIt(val notice: String? = null) : Unlock
|
|
||||||
|
|
||||||
/** A stored, decryptable passphrase exists — one tap. */
|
|
||||||
data class OneTap(val backing: KeyBacking) : Unlock
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Owns the single Wire node for the process.
|
* Owns the single Wire node for the process.
|
||||||
*
|
*
|
||||||
|
|
@ -66,130 +43,27 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
/** `context.filesDir` — app-private, never external storage. */
|
/** `context.filesDir` — app-private, never external storage. */
|
||||||
private val home: File = File(app.filesDir, "onionwire")
|
private val home: File = File(app.filesDir, "onionwire")
|
||||||
|
|
||||||
/**
|
|
||||||
* The Keystore-wrapped passphrase. Two files at most: this blob and the
|
|
||||||
* KeyStore key under alias [KeystorePassphraseCipher.ALIAS]. Nothing else
|
|
||||||
* on disk ever sees the plaintext.
|
|
||||||
*/
|
|
||||||
private val secrets: StoredPassphraseStore = StoredPassphraseStore(
|
|
||||||
File(File(app.filesDir, "secrets"), "store-passphrase.bin"),
|
|
||||||
KeystorePassphraseCipher(app),
|
|
||||||
)
|
|
||||||
|
|
||||||
private val _phase = MutableStateFlow<Phase>(Phase.Locked)
|
private val _phase = MutableStateFlow<Phase>(Phase.Locked)
|
||||||
val phase: StateFlow<Phase> = _phase.asStateFlow()
|
val phase: StateFlow<Phase> = _phase.asStateFlow()
|
||||||
|
|
||||||
private val _unlock = MutableStateFlow<Unlock>(Unlock.TypeIt())
|
|
||||||
val unlock: StateFlow<Unlock> = _unlock.asStateFlow()
|
|
||||||
|
|
||||||
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
|
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
|
||||||
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
|
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
|
||||||
|
|
||||||
private var wire: Wire? = null
|
private var wire: Wire? = null
|
||||||
|
|
||||||
init {
|
|
||||||
// Probe on a background dispatcher: this touches the Keystore and does
|
|
||||||
// a full GCM decrypt. Doing it here means a killed Keystore key is
|
|
||||||
// reported on the lock screen instead of at the first tap.
|
|
||||||
refreshUnlockState()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
|
* Opens (or on first run, creates) the identity and starts hosting.
|
||||||
* straight to an error, it is not a "skip" path.
|
|
||||||
*
|
*
|
||||||
* [remember] wraps the passphrase with the Keystore key so later launches
|
* An empty passphrase fails closed — the SDK maps it straight to an error,
|
||||||
* are one tap. It is opt-in in the UI (and on by default there); it is
|
* it is not a "skip" path.
|
||||||
* never implied by this call.
|
|
||||||
*/
|
*/
|
||||||
fun unlock(passphrase: String, remember: Boolean = false) {
|
fun unlock(passphrase: String) {
|
||||||
if (passphrase.isEmpty()) return
|
|
||||||
openWith(passphrase.toCharArray(), storeAfterwards = remember)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One-tap unlock from the stored blob.
|
|
||||||
*
|
|
||||||
* Any failure — key deleted, blob corrupt, GCM tag mismatch — degrades to
|
|
||||||
* "type it" with the reason on screen. It never crashes and never silently
|
|
||||||
* unlocks with something else.
|
|
||||||
*/
|
|
||||||
fun unlockStored() {
|
|
||||||
if (_phase.value is Phase.Opening) return
|
if (_phase.value is Phase.Opening) return
|
||||||
viewModelScope.launch {
|
|
||||||
val loaded = withContext(Dispatchers.IO) { secrets.load() }
|
|
||||||
when (loaded) {
|
|
||||||
is StoredPassphraseStore.Load.Loaded ->
|
|
||||||
openWith(loaded.passphrase, storeAfterwards = false)
|
|
||||||
|
|
||||||
StoredPassphraseStore.Load.Absent -> {
|
|
||||||
_unlock.value = Unlock.TypeIt("No passphrase is stored on this device.")
|
|
||||||
}
|
|
||||||
|
|
||||||
is StoredPassphraseStore.Load.Unavailable -> {
|
|
||||||
_unlock.value = Unlock.TypeIt(unavailableNotice(loaded.reason))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drops the stored passphrase and its Keystore key. Irreversible. */
|
|
||||||
fun forgetStoredPassphrase() {
|
|
||||||
viewModelScope.launch {
|
|
||||||
withContext(Dispatchers.IO) { secrets.forget() }
|
|
||||||
_unlock.value = Unlock.TypeIt(
|
|
||||||
"Stored passphrase deleted. Type it to open the store again.",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drops our handle. The onion service stops; nothing is sent after this. */
|
|
||||||
fun lock() {
|
|
||||||
wire = null
|
|
||||||
_friends.value = emptyList()
|
|
||||||
_phase.value = Phase.Locked
|
|
||||||
refreshUnlockState()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun refreshUnlockState() {
|
|
||||||
viewModelScope.launch {
|
|
||||||
val state = withContext(Dispatchers.IO) {
|
|
||||||
when (val loaded = secrets.load()) {
|
|
||||||
is StoredPassphraseStore.Load.Loaded -> {
|
|
||||||
// We only needed to know it decrypts. Wipe immediately.
|
|
||||||
StoreSecret.wipe(loaded.passphrase)
|
|
||||||
Unlock.OneTap(secrets.backing())
|
|
||||||
}
|
|
||||||
|
|
||||||
StoredPassphraseStore.Load.Absent -> Unlock.TypeIt()
|
|
||||||
|
|
||||||
is StoredPassphraseStore.Load.Unavailable ->
|
|
||||||
Unlock.TypeIt(unavailableNotice(loaded.reason))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_unlock.value = state
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The one path that calls the SDK.
|
|
||||||
*
|
|
||||||
* [secret] is wiped in `finally`, including when the Keystore write or the
|
|
||||||
* SDK call throws. The SDK's UniFFI signature takes a `String`, so one
|
|
||||||
* immutable copy is unavoidable here — see the PR description for the
|
|
||||||
* follow-up SDK signature this card cannot make itself.
|
|
||||||
*/
|
|
||||||
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
|
|
||||||
if (secret.isEmpty() || _phase.value is Phase.Opening) {
|
|
||||||
StoreSecret.wipe(secret)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
_phase.value = Phase.Opening
|
_phase.value = Phase.Opening
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
try {
|
||||||
val w = openWire(home.absolutePath, secret.concatToString())
|
val w = openWire(home.absolutePath, passphrase)
|
||||||
wire = w
|
wire = w
|
||||||
if (storeAfterwards) store(secret)
|
|
||||||
_phase.value = Phase.Ready(
|
_phase.value = Phase.Ready(
|
||||||
fingerprint = w.fingerprint(),
|
fingerprint = w.fingerprint(),
|
||||||
onion = w.onion(),
|
onion = w.onion(),
|
||||||
|
|
@ -198,33 +72,16 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
refreshFriends()
|
refreshFriends()
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
_phase.value = Phase.Failed(t.message ?: t.toString())
|
_phase.value = Phase.Failed(t.message ?: t.toString())
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(secret)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun store(secret: CharArray) {
|
/** Drops our handle. The onion service stops; nothing is sent after this. */
|
||||||
val outcome: Result<KeyBacking> = withContext(Dispatchers.IO) {
|
fun lock() {
|
||||||
try {
|
wire = null
|
||||||
secrets.save(secret)
|
_friends.value = emptyList()
|
||||||
Result.success(secrets.backing())
|
_phase.value = Phase.Locked
|
||||||
} catch (t: Throwable) {
|
|
||||||
Result.failure(t)
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
_unlock.value = outcome.fold(
|
|
||||||
onSuccess = { Unlock.OneTap(it) },
|
|
||||||
onFailure = {
|
|
||||||
// Unlock succeeded, so this is not fatal — say so plainly
|
|
||||||
// instead of pretending the passphrase was stored.
|
|
||||||
Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.")
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun unavailableNotice(reason: String): String =
|
|
||||||
"The stored passphrase could not be read — $reason. Type it once to store it again."
|
|
||||||
|
|
||||||
private fun requireWire(): Wire = wire ?: error("locked")
|
private fun requireWire(): Wire = wire ?: error("locked")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,139 +0,0 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
|
||||||
import android.security.keystore.KeyGenParameterSpec
|
|
||||||
import android.security.keystore.KeyInfo
|
|
||||||
import android.security.keystore.KeyProperties
|
|
||||||
import java.security.KeyStore
|
|
||||||
import java.security.ProviderException
|
|
||||||
import javax.crypto.KeyGenerator
|
|
||||||
import javax.crypto.SecretKey
|
|
||||||
import javax.crypto.SecretKeyFactory
|
|
||||||
|
|
||||||
/**
|
|
||||||
* AES-256-GCM key held by the Android Keystore under [ALIAS].
|
|
||||||
*
|
|
||||||
* The key material is never readable by this process (`SecretKey.encoded` is
|
|
||||||
* null for AndroidKeyStore keys) — that is the whole point: pulling
|
|
||||||
* `/data/data/com.siriusdevops.onionwire/` off a rooted device yields the
|
|
||||||
* ciphertext, not the passphrase.
|
|
||||||
*
|
|
||||||
* StrongBox is requested first and falls back to the ordinary TEE-backed (or
|
|
||||||
* software) Keystore without a crash. The fallback is not silent: call
|
|
||||||
* [backing] and report what the Keystore actually produced.
|
|
||||||
*
|
|
||||||
* `setUserAuthenticationRequired` is deliberately **false**. Requiring a
|
|
||||||
* fingerprint to unlock the node would turn "fail closed" into "unusable
|
|
||||||
* unattended", and the SDK's contract is that an unlock either opens the node
|
|
||||||
* or reports why it did not.
|
|
||||||
*/
|
|
||||||
class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher {
|
|
||||||
|
|
||||||
private var cached: SecretKey? = null
|
|
||||||
|
|
||||||
override fun seal(plaintext: CharArray): ByteArray =
|
|
||||||
StoreSecret.seal(loadOrCreateKey(), plaintext)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Never creates a key. A freshly generated key cannot decrypt an old blob,
|
|
||||||
* and generating one here would turn "the key is gone" into a confusing
|
|
||||||
* GCM tag failure. The caller needs the real reason to tell the user.
|
|
||||||
*/
|
|
||||||
override fun open(blob: ByteArray): CharArray {
|
|
||||||
val key = cached ?: existingKey()
|
|
||||||
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
|
||||||
return StoreSecret.open(key, blob)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun keyPresent(): Boolean = (cached ?: existingKey()) != null
|
|
||||||
|
|
||||||
override fun backing(): KeyBacking {
|
|
||||||
val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN
|
|
||||||
val info = try {
|
|
||||||
SecretKeyFactory.getInstance(key.algorithm, PROVIDER)
|
|
||||||
.getKeySpec(key, KeyInfo::class.java) as KeyInfo
|
|
||||||
} catch (_: Exception) {
|
|
||||||
// Some OEM Keystore implementations refuse getKeySpec. Report
|
|
||||||
// UNKNOWN rather than guessing hardware backing.
|
|
||||||
return KeyBacking.UNKNOWN
|
|
||||||
}
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
|
|
||||||
info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX
|
|
||||||
) {
|
|
||||||
return KeyBacking.STRONGBOX
|
|
||||||
}
|
|
||||||
// Deprecated in API 31 in favour of securityLevel, but it is the only
|
|
||||||
// TEE/software answer available on 26–30, and minSdk is 26.
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
val inSecureHardware = info.isInsideSecureHardware
|
|
||||||
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun deleteKey() {
|
|
||||||
cached = null
|
|
||||||
try {
|
|
||||||
keyStore().deleteEntry(ALIAS)
|
|
||||||
} catch (_: Exception) {
|
|
||||||
// Nothing usable to delete.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun existingKey(): SecretKey? {
|
|
||||||
cached?.let { return it }
|
|
||||||
val key = try {
|
|
||||||
keyStore().getKey(ALIAS, null) as? SecretKey
|
|
||||||
} catch (_: Exception) {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
cached = key
|
|
||||||
return key
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey()
|
|
||||||
|
|
||||||
private fun createKey(): SecretKey {
|
|
||||||
val strongBoxAdvertised =
|
|
||||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
|
||||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
|
||||||
if (strongBoxAdvertised) {
|
|
||||||
try {
|
|
||||||
return generate(strongBox = true).also { cached = it }
|
|
||||||
} catch (_: ProviderException) {
|
|
||||||
// StrongBoxUnavailableException is a ProviderException: the chip
|
|
||||||
// exists but its slots are full, or it refuses AES-256. Fall
|
|
||||||
// through to a normal Keystore key instead of failing unlock.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return generate(strongBox = false).also { cached = it }
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun generate(strongBox: Boolean): SecretKey {
|
|
||||||
val builder = KeyGenParameterSpec.Builder(
|
|
||||||
ALIAS,
|
|
||||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
|
||||||
)
|
|
||||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
|
||||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
|
||||||
.setKeySize(StoreSecret.KEY_BITS)
|
|
||||||
// Our IV comes from Cipher.init, and the Keystore supplies it.
|
|
||||||
.setRandomizedEncryptionRequired(true)
|
|
||||||
.setUserAuthenticationRequired(false)
|
|
||||||
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
|
||||||
builder.setIsStrongBoxBacked(true)
|
|
||||||
}
|
|
||||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
|
|
||||||
generator.init(builder.build())
|
|
||||||
return generator.generateKey()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
const val PROVIDER = "AndroidKeyStore"
|
|
||||||
|
|
||||||
/** One key per app: the passphrase it wraps is the only secret here. */
|
|
||||||
const val ALIAS = "onionwire.store"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wraps the store passphrase with a key that never leaves the Keystore.
|
|
||||||
*
|
|
||||||
* Implementations must not persist the plaintext anywhere, and must not log it.
|
|
||||||
*/
|
|
||||||
interface PassphraseCipher {
|
|
||||||
|
|
||||||
/** Encrypts [plaintext]. The returned blob is the only thing that may hit disk. */
|
|
||||||
fun seal(plaintext: CharArray): ByteArray
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decrypts a blob produced by [seal].
|
|
||||||
*
|
|
||||||
* @throws SecretUnavailable when the key is gone, invalidated, or the blob
|
|
||||||
* does not authenticate. Callers fall back to asking the user to type.
|
|
||||||
*/
|
|
||||||
fun open(blob: ByteArray): CharArray
|
|
||||||
|
|
||||||
/** True when a usable key is already in the Keystore. */
|
|
||||||
fun keyPresent(): Boolean
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Where the key actually lives, as reported by the Keystore itself.
|
|
||||||
*
|
|
||||||
* This is an observation, not a claim: on a device without a StrongBox or
|
|
||||||
* TEE the honest answer is [KeyBacking.SOFTWARE], and the UI says so.
|
|
||||||
*/
|
|
||||||
fun backing(): KeyBacking
|
|
||||||
|
|
||||||
/** Removes the key. The ciphertext becomes permanently undecryptable. */
|
|
||||||
fun deleteKey()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Result of asking the Keystore where the key lives. */
|
|
||||||
enum class KeyBacking {
|
|
||||||
/** Dedicated security chip (API 28+, Pixel 3-class and up). */
|
|
||||||
STRONGBOX,
|
|
||||||
|
|
||||||
/** Key is inside a TEE. Good. */
|
|
||||||
HARDWARE,
|
|
||||||
|
|
||||||
/** Keystore software implementation. Passphrase is still not plaintext on disk. */
|
|
||||||
SOFTWARE,
|
|
||||||
|
|
||||||
/** No key created yet, or the API could not be queried. Never claim hardware here. */
|
|
||||||
UNKNOWN,
|
|
||||||
}
|
|
||||||
|
|
@ -1,130 +0,0 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
|
||||||
|
|
||||||
import java.nio.CharBuffer
|
|
||||||
import java.nio.charset.StandardCharsets
|
|
||||||
import java.security.GeneralSecurityException
|
|
||||||
import java.util.Arrays
|
|
||||||
import javax.crypto.Cipher
|
|
||||||
import javax.crypto.SecretKey
|
|
||||||
import javax.crypto.spec.GCMParameterSpec
|
|
||||||
|
|
||||||
/**
|
|
||||||
* AES-256-GCM envelope for the store passphrase.
|
|
||||||
*
|
|
||||||
* This file is deliberately free of `android.*` imports so the exact
|
|
||||||
* seal/open code that runs on a device can also run in a plain JVM unit test
|
|
||||||
* with a JVM-generated AES key. The Android Keystore only supplies the key —
|
|
||||||
* the framing and the AEAD call are these functions.
|
|
||||||
*
|
|
||||||
* Wire format (little of it is secret, all of it is authenticated):
|
|
||||||
*
|
|
||||||
* magic "OWSEAL1\n" 8 bytes
|
|
||||||
* iv length 1 byte (always [IV_BYTES])
|
|
||||||
* iv [IV_BYTES] bytes, from the cipher
|
|
||||||
* ciphertext n + [TAG_BITS]/8 bytes (GCM tag is appended)
|
|
||||||
*
|
|
||||||
* The IV is generated by `Cipher.init` rather than by us: an AndroidKeyStore
|
|
||||||
* key created with `setRandomizedEncryptionRequired(true)` refuses an
|
|
||||||
* app-supplied IV, and SunJCE likewise default-generates one. Nothing here
|
|
||||||
* ever writes the plaintext passphrase to disk.
|
|
||||||
*/
|
|
||||||
object StoreSecret {
|
|
||||||
|
|
||||||
/** AES-256 per the card. Keystore key size and this constant must agree. */
|
|
||||||
const val KEY_BITS: Int = 256
|
|
||||||
|
|
||||||
/** 96-bit IV is the GCM-recommended size; AndroidKeyStore defaults to it. */
|
|
||||||
const val IV_BYTES: Int = 12
|
|
||||||
|
|
||||||
/** Full-length GCM tag. Truncating it saves 6 bytes and buys nothing. */
|
|
||||||
private const val TAG_BITS: Int = 128
|
|
||||||
|
|
||||||
private val MAGIC = byteArrayOf('O'.code.toByte(), 'W'.code.toByte(), 'S'.code.toByte(), 'E'.code.toByte(), 'A'.code.toByte(), 'L'.code.toByte(), '1'.code.toByte(), '\n'.code.toByte())
|
|
||||||
|
|
||||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encrypts [plaintext] under [key]. The passphrase is never converted to a
|
|
||||||
* `String` on this path: the UTF-8 encoder reads the `CharArray` directly.
|
|
||||||
*/
|
|
||||||
fun seal(key: SecretKey, plaintext: CharArray): ByteArray {
|
|
||||||
require(plaintext.isNotEmpty()) { "refusing to seal an empty passphrase" }
|
|
||||||
val bytes = utf8(plaintext)
|
|
||||||
try {
|
|
||||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
|
||||||
cipher.init(Cipher.ENCRYPT_MODE, key)
|
|
||||||
val iv = cipher.iv
|
|
||||||
val ct = cipher.doFinal(bytes)
|
|
||||||
return ByteArray(MAGIC.size + 1 + iv.size + ct.size).also { out ->
|
|
||||||
var p = 0
|
|
||||||
MAGIC.copyInto(out, p); p += MAGIC.size
|
|
||||||
out[p] = iv.size.toByte(); p += 1
|
|
||||||
iv.copyInto(out, p); p += iv.size
|
|
||||||
ct.copyInto(out, p)
|
|
||||||
}
|
|
||||||
} catch (e: GeneralSecurityException) {
|
|
||||||
throw SecretUnavailable("could not encrypt the passphrase", e)
|
|
||||||
} finally {
|
|
||||||
wipe(bytes)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reverses [seal]. Throws [SecretUnavailable] on a wrong key, a truncated
|
|
||||||
* blob, or a failed GCM tag check — never returns partial plaintext.
|
|
||||||
*/
|
|
||||||
fun open(key: SecretKey, blob: ByteArray): CharArray {
|
|
||||||
if (blob.size < MAGIC.size + 1 + IV_BYTES + TAG_BITS / 8) {
|
|
||||||
throw SecretUnavailable("stored secret is truncated")
|
|
||||||
}
|
|
||||||
for (i in MAGIC.indices) {
|
|
||||||
if (blob[i] != MAGIC[i]) throw SecretUnavailable("stored secret is not an OnionWire envelope")
|
|
||||||
}
|
|
||||||
var p = MAGIC.size
|
|
||||||
val ivLen = blob[p].toInt() and 0xFF
|
|
||||||
p += 1
|
|
||||||
if (ivLen != IV_BYTES) throw SecretUnavailable("unexpected IV length $ivLen")
|
|
||||||
if (blob.size < p + ivLen + TAG_BITS / 8) throw SecretUnavailable("stored secret is truncated")
|
|
||||||
val iv = blob.copyOfRange(p, p + ivLen)
|
|
||||||
val ct = blob.copyOfRange(p + ivLen, blob.size)
|
|
||||||
val plain = try {
|
|
||||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
|
||||||
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv))
|
|
||||||
cipher.doFinal(ct)
|
|
||||||
} catch (e: GeneralSecurityException) {
|
|
||||||
throw SecretUnavailable("stored secret did not authenticate", e)
|
|
||||||
}
|
|
||||||
return try {
|
|
||||||
decodeUtf8(plain)
|
|
||||||
} finally {
|
|
||||||
wipe(plain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Zeroes [bytes]. Cheap, and it shortens the window a heap dump can read. */
|
|
||||||
fun wipe(bytes: ByteArray) {
|
|
||||||
Arrays.fill(bytes, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Zeroes [chars]. Kotlin/Java strings are immutable, so this is the best we get. */
|
|
||||||
fun wipe(chars: CharArray) {
|
|
||||||
Arrays.fill(chars, '\u0000')
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun utf8(chars: CharArray): ByteArray {
|
|
||||||
val bb = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(chars))
|
|
||||||
return ByteArray(bb.remaining()).also(bb::get)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun decodeUtf8(bytes: ByteArray): CharArray {
|
|
||||||
val cb = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes))
|
|
||||||
return CharArray(cb.remaining()).also(cb::get)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The passphrase could not be recovered. The caller must fall back to typing
|
|
||||||
* it — a Keystore key does not survive a factory reset, a lock-screen change
|
|
||||||
* that invalidates keys, or an app-data wipe.
|
|
||||||
*/
|
|
||||||
class SecretUnavailable(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
|
||||||
|
|
@ -1,91 +0,0 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
|
||||||
|
|
||||||
import java.io.File
|
|
||||||
import java.io.IOException
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The only on-disk copy of the passphrase: an AES-GCM blob under
|
|
||||||
* `context.filesDir`, which is app-private and excluded from backup and
|
|
||||||
* device transfer (`AndroidManifest.xml`, `res/xml/data_extraction_rules.xml`).
|
|
||||||
*
|
|
||||||
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
|
|
||||||
* There is no second copy, no SharedPreferences mirror, and nothing outside the
|
|
||||||
* app's data dir.
|
|
||||||
*/
|
|
||||||
class StoredPassphraseStore(
|
|
||||||
private val file: File,
|
|
||||||
private val cipher: PassphraseCipher,
|
|
||||||
) {
|
|
||||||
|
|
||||||
sealed interface Load {
|
|
||||||
/** Decrypted for this call only. The caller must wipe the array. */
|
|
||||||
class Loaded(val passphrase: CharArray) : Load
|
|
||||||
|
|
||||||
/** Nothing stored yet — first run, or the user forgot it. */
|
|
||||||
data object Absent : Load
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Something is stored but cannot be read: the Keystore key is gone or
|
|
||||||
* invalidated, or the file is corrupt. Fall back to typing.
|
|
||||||
*/
|
|
||||||
data class Unavailable(val reason: String) : Load
|
|
||||||
}
|
|
||||||
|
|
||||||
fun exists(): Boolean = file.isFile && file.length() > 0L
|
|
||||||
|
|
||||||
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
|
|
||||||
fun backing(): KeyBacking = cipher.backing()
|
|
||||||
|
|
||||||
/** Path for diagnostics in tests. Never logged with its contents. */
|
|
||||||
val path: String get() = file.absolutePath
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Encrypts and replaces the stored blob. Atomic-ish: written to a sibling
|
|
||||||
* temp file and renamed, so a crash mid-write cannot leave half a blob.
|
|
||||||
*/
|
|
||||||
fun save(passphrase: CharArray) {
|
|
||||||
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" }
|
|
||||||
val blob = cipher.seal(passphrase)
|
|
||||||
try {
|
|
||||||
file.parentFile?.mkdirs()
|
|
||||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
|
||||||
tmp.writeBytes(blob)
|
|
||||||
if (!tmp.renameTo(file)) {
|
|
||||||
file.writeBytes(blob)
|
|
||||||
tmp.delete()
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(blob)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads and decrypts the blob. The returned array is the caller's to wipe.
|
|
||||||
*
|
|
||||||
* A failed decrypt does **not** delete the blob: a transient Keystore
|
|
||||||
* failure must not silently destroy the user's only copy. Use [forget] to
|
|
||||||
* drop it deliberately.
|
|
||||||
*/
|
|
||||||
fun load(): Load {
|
|
||||||
if (!exists()) return Load.Absent
|
|
||||||
val blob = try {
|
|
||||||
file.readBytes()
|
|
||||||
} catch (e: IOException) {
|
|
||||||
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
|
|
||||||
}
|
|
||||||
return try {
|
|
||||||
Load.Loaded(cipher.open(blob))
|
|
||||||
} catch (e: SecretUnavailable) {
|
|
||||||
Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(blob)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drops the ciphertext and the Keystore key. Irreversible. */
|
|
||||||
fun forget() {
|
|
||||||
file.delete()
|
|
||||||
File(file.parentFile, file.name + ".tmp").delete()
|
|
||||||
cipher.deleteKey()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -2,7 +2,6 @@ package com.siriusdevops.onionwire.ui
|
||||||
|
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
|
@ -12,13 +11,10 @@ import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.Checkbox
|
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.HorizontalDivider
|
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
|
@ -32,38 +28,10 @@ import androidx.compose.ui.text.input.KeyboardType
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.siriusdevops.onionwire.Phase
|
import com.siriusdevops.onionwire.Phase
|
||||||
import com.siriusdevops.onionwire.Unlock
|
|
||||||
import com.siriusdevops.onionwire.crypto.KeyBacking
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lock screen.
|
|
||||||
*
|
|
||||||
* When [Unlock.OneTap] is set, the passphrase is already on disk wrapped by the
|
|
||||||
* Android Keystore key and the user taps once. Otherwise they type it — and
|
|
||||||
* they land here, with [Unlock.TypeIt.notice] explaining why, whenever the
|
|
||||||
* stored blob cannot be read (key invalidated, device reset, corrupt file).
|
|
||||||
*
|
|
||||||
* The typed passphrase lives in a plain `remember` (not `rememberSaveable`) and
|
|
||||||
* is cleared as soon as it is handed to the ViewModel: it never survives a
|
|
||||||
* config change and never gets written to the saved-instance-state bundle.
|
|
||||||
*/
|
|
||||||
@Composable
|
@Composable
|
||||||
fun UnlockScreen(
|
fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
|
||||||
phase: Phase,
|
|
||||||
unlock: Unlock,
|
|
||||||
onUnlock: (passphrase: String, remember: Boolean) -> Unit,
|
|
||||||
onUnlockStored: () -> Unit,
|
|
||||||
onForgetStored: () -> Unit,
|
|
||||||
) {
|
|
||||||
var pass by remember { mutableStateOf("") }
|
var pass by remember { mutableStateOf("") }
|
||||||
var storePassphrase by remember { mutableStateOf(true) }
|
|
||||||
// Only meaningful under OneTap: reveal the form without giving up the
|
|
||||||
// stored passphrase.
|
|
||||||
var typeInstead by remember { mutableStateOf(false) }
|
|
||||||
|
|
||||||
val oneTap = unlock as? Unlock.OneTap
|
|
||||||
val failed = phase is Phase.Failed
|
|
||||||
val showForm = oneTap == null || typeInstead || failed
|
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
|
|
@ -96,49 +64,11 @@ fun UnlockScreen(
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
if (oneTap != null && !failed) {
|
|
||||||
Text("Passphrase", style = MaterialTheme.typography.titleSmall)
|
|
||||||
Spacer(Modifier.height(8.dp))
|
|
||||||
Text(
|
Text(
|
||||||
"Stored on this device, wrapped by an Android Keystore key " +
|
"Passphrase",
|
||||||
"(${backingLabel(oneTap.backing)}).",
|
style = MaterialTheme.typography.titleSmall,
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
)
|
||||||
Spacer(Modifier.height(20.dp))
|
|
||||||
Button(
|
|
||||||
onClick = onUnlockStored,
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
) { Text("Unlock") }
|
|
||||||
Spacer(Modifier.height(8.dp))
|
Spacer(Modifier.height(8.dp))
|
||||||
Row(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
|
||||||
) {
|
|
||||||
TextButton(onClick = { typeInstead = true }) {
|
|
||||||
Text("Type it instead")
|
|
||||||
}
|
|
||||||
TextButton(onClick = onForgetStored) {
|
|
||||||
Text("Forget stored passphrase")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (showForm) {
|
|
||||||
Spacer(Modifier.height(16.dp))
|
|
||||||
HorizontalDivider()
|
|
||||||
Spacer(Modifier.height(16.dp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (showForm) {
|
|
||||||
if (unlock is Unlock.TypeIt && unlock.notice != null) {
|
|
||||||
Text(
|
|
||||||
unlock.notice,
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
Spacer(Modifier.height(16.dp))
|
|
||||||
}
|
|
||||||
|
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = pass,
|
value = pass,
|
||||||
onValueChange = { pass = it },
|
onValueChange = { pass = it },
|
||||||
|
|
@ -158,45 +88,14 @@ fun UnlockScreen(
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
|
||||||
Spacer(Modifier.height(4.dp))
|
|
||||||
Row(
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
) {
|
|
||||||
Checkbox(
|
|
||||||
checked = storePassphrase,
|
|
||||||
onCheckedChange = { storePassphrase = it },
|
|
||||||
)
|
|
||||||
Text(
|
|
||||||
"Remember on this device (wrapped by the Android Keystore, " +
|
|
||||||
"no backup)",
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (oneTap != null) {
|
|
||||||
Text(
|
|
||||||
"Typing and remembering replaces the stored passphrase.",
|
|
||||||
style = MaterialTheme.typography.labelSmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(Modifier.height(20.dp))
|
Spacer(Modifier.height(20.dp))
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = { onUnlock(pass) },
|
||||||
val typed = pass
|
|
||||||
// Drop the plaintext from Compose state the moment
|
|
||||||
// it is handed over; the ViewModel wipes its copy.
|
|
||||||
pass = ""
|
|
||||||
onUnlock(typed, storePassphrase)
|
|
||||||
},
|
|
||||||
enabled = pass.isNotEmpty(),
|
enabled = pass.isNotEmpty(),
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
) { Text("Open") }
|
) { Text("Open") }
|
||||||
}
|
|
||||||
|
|
||||||
if (failed) {
|
if (phase is Phase.Failed) {
|
||||||
Spacer(Modifier.height(20.dp))
|
Spacer(Modifier.height(20.dp))
|
||||||
Text(
|
Text(
|
||||||
"Failed to start",
|
"Failed to start",
|
||||||
|
|
@ -229,14 +128,3 @@ fun UnlockScreen(
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* What the Keystore reported, verbatim. Never upgraded into a stronger claim:
|
|
||||||
* a software key says so.
|
|
||||||
*/
|
|
||||||
internal fun backingLabel(backing: KeyBacking): String = when (backing) {
|
|
||||||
KeyBacking.STRONGBOX -> "StrongBox"
|
|
||||||
KeyBacking.HARDWARE -> "TEE-backed"
|
|
||||||
KeyBacking.SOFTWARE -> "software key, NOT hardware-backed"
|
|
||||||
KeyBacking.UNKNOWN -> "backing not reported by this device"
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,157 +0,0 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
|
||||||
|
|
||||||
import org.junit.Assert.assertArrayEquals
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertFalse
|
|
||||||
import org.junit.Assert.assertNotEquals
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Assert.fail
|
|
||||||
import org.junit.Test
|
|
||||||
import javax.crypto.KeyGenerator
|
|
||||||
import javax.crypto.SecretKey
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Exercises the real envelope code — [StoreSecret] has no `android.*` imports,
|
|
||||||
* so a JVM AES key stands in for the AndroidKeystore key.
|
|
||||||
*
|
|
||||||
* What this does NOT cover (see the PR description): the AndroidKeyStore provider
|
|
||||||
* itself (`KeyGenerator` + `KeyGenParameterSpec`, StrongBox fallback, and
|
|
||||||
* `KeyInfo.isInsideSecureHardware`). Those are device-only APIs; the unit-test
|
|
||||||
* JVM has no such provider.
|
|
||||||
*/
|
|
||||||
class StoreSecretTest {
|
|
||||||
|
|
||||||
private fun aesKey(): SecretKey =
|
|
||||||
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
|
|
||||||
|
|
||||||
private val passphrase = "correct horse battery staple".toCharArray()
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun seal_open_round_trips() {
|
|
||||||
val key = aesKey()
|
|
||||||
val blob = StoreSecret.seal(key, passphrase)
|
|
||||||
val out = StoreSecret.open(key, blob)
|
|
||||||
try {
|
|
||||||
assertArrayEquals(passphrase, out)
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun round_trips_non_ascii_and_whitespace() {
|
|
||||||
val key = aesKey()
|
|
||||||
val weird = " ünïcödé 🔑 \n\ttab ".toCharArray()
|
|
||||||
val out = StoreSecret.open(key, StoreSecret.seal(key, weird))
|
|
||||||
try {
|
|
||||||
assertArrayEquals(weird, out)
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun blob_does_not_contain_the_plaintext() {
|
|
||||||
val key = aesKey()
|
|
||||||
val blob = StoreSecret.seal(key, passphrase)
|
|
||||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
|
||||||
assertFalse(
|
|
||||||
"ciphertext must not contain the passphrase",
|
|
||||||
blob.containsSubsequence(needle),
|
|
||||||
)
|
|
||||||
assertTrue(blob.size > needle.size)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun blob_carries_the_envelope_magic() {
|
|
||||||
val blob = StoreSecret.seal(aesKey(), passphrase)
|
|
||||||
assertEquals("OWSEAL1\n", String(blob.copyOfRange(0, 8), Charsets.US_ASCII))
|
|
||||||
// Magic(8) + IV length(1) + IV(12) + tag(16)
|
|
||||||
assertEquals(8 + 1 + StoreSecret.IV_BYTES + 16, blob.size - String(passphrase).toByteArray(Charsets.UTF_8).size)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun each_seal_uses_a_fresh_iv() {
|
|
||||||
val key = aesKey()
|
|
||||||
val a = StoreSecret.seal(key, passphrase)
|
|
||||||
val b = StoreSecret.seal(key, passphrase)
|
|
||||||
assertNotEquals(
|
|
||||||
"identical ciphertext means the IV was reused",
|
|
||||||
a.toList(),
|
|
||||||
b.toList(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun wrong_key_fails_closed() {
|
|
||||||
val blob = StoreSecret.seal(aesKey(), passphrase)
|
|
||||||
try {
|
|
||||||
StoreSecret.open(aesKey(), blob)
|
|
||||||
fail("expected SecretUnavailable")
|
|
||||||
} catch (e: SecretUnavailable) {
|
|
||||||
assertTrue(e.message!!.contains("authenticate"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun tampered_ciphertext_fails_the_gcm_tag() {
|
|
||||||
val key = aesKey()
|
|
||||||
val blob = StoreSecret.seal(key, passphrase)
|
|
||||||
blob[blob.size - 1] = (blob[blob.size - 1].toInt() xor 0x01).toByte()
|
|
||||||
try {
|
|
||||||
StoreSecret.open(key, blob)
|
|
||||||
fail("expected SecretUnavailable")
|
|
||||||
} catch (_: SecretUnavailable) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun truncated_blob_fails_closed() {
|
|
||||||
val key = aesKey()
|
|
||||||
val blob = StoreSecret.seal(key, passphrase)
|
|
||||||
try {
|
|
||||||
StoreSecret.open(key, blob.copyOfRange(0, 10))
|
|
||||||
fail("expected SecretUnavailable")
|
|
||||||
} catch (_: SecretUnavailable) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun garbage_blob_fails_closed() {
|
|
||||||
try {
|
|
||||||
StoreSecret.open(aesKey(), "not an envelope".toByteArray())
|
|
||||||
fail("expected SecretUnavailable")
|
|
||||||
} catch (e: SecretUnavailable) {
|
|
||||||
assertTrue(e.message!!.contains("truncated") || e.message!!.contains("envelope"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun seal_refuses_an_empty_passphrase() {
|
|
||||||
try {
|
|
||||||
StoreSecret.seal(aesKey(), CharArray(0))
|
|
||||||
fail("expected IllegalArgumentException")
|
|
||||||
} catch (_: IllegalArgumentException) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun wipe_zeroes() {
|
|
||||||
val bytes = byteArrayOf(1, 2, 3)
|
|
||||||
StoreSecret.wipe(bytes)
|
|
||||||
assertArrayEquals(ByteArray(3), bytes)
|
|
||||||
|
|
||||||
val chars = charArrayOf('a', 'b')
|
|
||||||
StoreSecret.wipe(chars)
|
|
||||||
assertArrayEquals(CharArray(2), chars)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun ByteArray.containsSubsequence(needle: ByteArray): Boolean {
|
|
||||||
if (needle.isEmpty() || needle.size > size) return false
|
|
||||||
outer@ for (i in 0..size - needle.size) {
|
|
||||||
for (j in needle.indices) if (this[i + j] != needle[j]) continue@outer
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,167 +0,0 @@
|
||||||
package com.siriusdevops.onionwire.crypto
|
|
||||||
|
|
||||||
import org.junit.Assert.assertArrayEquals
|
|
||||||
import org.junit.Assert.assertEquals
|
|
||||||
import org.junit.Assert.assertFalse
|
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Rule
|
|
||||||
import org.junit.Test
|
|
||||||
import org.junit.rules.TemporaryFolder
|
|
||||||
import javax.crypto.KeyGenerator
|
|
||||||
import javax.crypto.SecretKey
|
|
||||||
|
|
||||||
/**
|
|
||||||
* File-level behaviour of [StoredPassphraseStore] with the real envelope from
|
|
||||||
* [StoreSecret] and a JVM AES key standing in for the Keystore key.
|
|
||||||
*
|
|
||||||
* The Keystore itself is device-only; what is proven here is that nothing
|
|
||||||
* plaintext reaches the file, that a lost key degrades instead of crashing,
|
|
||||||
* and that a lost key does not delete the user's blob.
|
|
||||||
*/
|
|
||||||
class StoredPassphraseStoreTest {
|
|
||||||
|
|
||||||
@get:Rule
|
|
||||||
val tmp = TemporaryFolder()
|
|
||||||
|
|
||||||
private val passphrase = "correct horse battery staple".toCharArray()
|
|
||||||
|
|
||||||
/** Stands in for the AndroidKeystore key: real AES-GCM, JVM-held key. */
|
|
||||||
private class JvmKeyCipher(private val key: SecretKey) : PassphraseCipher {
|
|
||||||
var deleted = false
|
|
||||||
var backingQueried = 0
|
|
||||||
|
|
||||||
override fun seal(plaintext: CharArray): ByteArray = StoreSecret.seal(key, plaintext)
|
|
||||||
|
|
||||||
override fun open(blob: ByteArray): CharArray {
|
|
||||||
if (deleted) throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
|
||||||
return StoreSecret.open(key, blob)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun keyPresent(): Boolean = !deleted
|
|
||||||
|
|
||||||
override fun backing(): KeyBacking {
|
|
||||||
backingQueried++
|
|
||||||
return KeyBacking.SOFTWARE
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun deleteKey() {
|
|
||||||
deleted = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun jvmKey(): SecretKey =
|
|
||||||
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
|
|
||||||
|
|
||||||
private fun store(cipher: PassphraseCipher) =
|
|
||||||
StoredPassphraseStore(tmp.newFile("store-passphrase.bin").also { it.delete() }, cipher)
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun save_then_load_round_trips() {
|
|
||||||
val store = store(JvmKeyCipher(jvmKey()))
|
|
||||||
store.save(passphrase)
|
|
||||||
|
|
||||||
val loaded = store.load()
|
|
||||||
assertTrue(loaded is StoredPassphraseStore.Load.Loaded)
|
|
||||||
val out = (loaded as StoredPassphraseStore.Load.Loaded).passphrase
|
|
||||||
try {
|
|
||||||
assertArrayEquals(passphrase, out)
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun on_disk_blob_is_not_the_plaintext() {
|
|
||||||
val store = store(JvmKeyCipher(jvmKey()))
|
|
||||||
store.save(passphrase)
|
|
||||||
|
|
||||||
val raw = java.io.File(store.path).readBytes()
|
|
||||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
|
||||||
assertFalse(
|
|
||||||
"the passphrase must not appear in the file",
|
|
||||||
raw.toString(Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
|
|
||||||
)
|
|
||||||
assertTrue("expected the OWSEAL envelope", raw.size > needle.size + 20)
|
|
||||||
assertEquals("OWSEAL1\n", String(raw.copyOfRange(0, 8), Charsets.US_ASCII))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun no_temp_file_is_left_behind() {
|
|
||||||
val store = store(JvmKeyCipher(jvmKey()))
|
|
||||||
store.save(passphrase)
|
|
||||||
val dir = requireNotNull(java.io.File(store.path).parentFile)
|
|
||||||
val leftovers = dir.listFiles()!!.filter { it.name.endsWith(".tmp") }
|
|
||||||
assertTrue("temp files left: $leftovers", leftovers.isEmpty())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun save_overwrites_the_previous_blob() {
|
|
||||||
val store = store(JvmKeyCipher(jvmKey()))
|
|
||||||
store.save("first".toCharArray())
|
|
||||||
store.save("second".toCharArray())
|
|
||||||
|
|
||||||
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
|
|
||||||
try {
|
|
||||||
assertArrayEquals("second".toCharArray(), loaded.passphrase)
|
|
||||||
} finally {
|
|
||||||
StoreSecret.wipe(loaded.passphrase)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun absent_when_nothing_was_ever_stored() {
|
|
||||||
val store = store(JvmKeyCipher(jvmKey()))
|
|
||||||
assertFalse(store.exists())
|
|
||||||
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun lost_key_reports_unavailable_and_keeps_the_blob() {
|
|
||||||
val cipher = JvmKeyCipher(jvmKey())
|
|
||||||
val store = store(cipher)
|
|
||||||
store.save(passphrase)
|
|
||||||
|
|
||||||
cipher.deleteKey() // device reset / key invalidated
|
|
||||||
|
|
||||||
val loaded = store.load()
|
|
||||||
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
|
|
||||||
assertTrue(
|
|
||||||
(loaded as StoredPassphraseStore.Load.Unavailable).reason.contains("gone"),
|
|
||||||
)
|
|
||||||
assertTrue("a failed read must not delete the blob", store.exists())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun corrupt_blob_reports_unavailable_instead_of_throwing() {
|
|
||||||
val store = store(JvmKeyCipher(jvmKey()))
|
|
||||||
store.save(passphrase)
|
|
||||||
java.io.File(store.path).writeBytes("OWSEAL1\n not really a ciphertext".toByteArray())
|
|
||||||
|
|
||||||
val loaded = store.load()
|
|
||||||
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun forget_deletes_the_blob_and_the_key() {
|
|
||||||
val cipher = JvmKeyCipher(jvmKey())
|
|
||||||
val store = store(cipher)
|
|
||||||
store.save(passphrase)
|
|
||||||
assertTrue(store.exists())
|
|
||||||
|
|
||||||
store.forget()
|
|
||||||
|
|
||||||
assertFalse(store.exists())
|
|
||||||
assertFalse(cipher.keyPresent())
|
|
||||||
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun backing_is_reported_from_the_cipher() {
|
|
||||||
val cipher = JvmKeyCipher(jvmKey())
|
|
||||||
val store = store(cipher)
|
|
||||||
store.save(passphrase)
|
|
||||||
|
|
||||||
assertEquals(KeyBacking.SOFTWARE, store.backing())
|
|
||||||
assertEquals(1, cipher.backingQueried)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -9,15 +9,11 @@ composeBom = "2025.12.01"
|
||||||
jna = "5.19.1"
|
jna = "5.19.1"
|
||||||
coroutines = "1.11.0"
|
coroutines = "1.11.0"
|
||||||
junit = "4.13.2"
|
junit = "4.13.2"
|
||||||
androidxTestJunit = "1.3.0"
|
|
||||||
androidxTestRunner = "1.7.0"
|
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }
|
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }
|
||||||
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
|
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
|
||||||
junit = { module = "junit:junit", version.ref = "junit" }
|
junit = { module = "junit:junit", version.ref = "junit" }
|
||||||
androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestJunit" }
|
|
||||||
androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }
|
|
||||||
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
|
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
|
||||||
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
|
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
|
||||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
|
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue