mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Stores: seal the GOG, Epic and Amazon sign-in files with an Android Keystore key (#486)
The stores' sign-ins (files/stores/<store>/credentials.json: access and refresh
tokens, account id and name) were plain JSON. Other apps could not read them, but
every program in the Linux session runs as the app and could. They are now sealed
with AES-256-GCM under a non-exportable AndroidKeyStore key (StrongBox when the
device has one), so the session only ever sees ciphertext.
- Format: a versioned envelope {v, alg, iv, ct}, written atomically and readable
only by the app. No new dependencies (javax.crypto and KeyStore).
- Migration: an existing plaintext file is sealed at the next start, checked by
decrypting it, then the plaintext is removed; users stay signed in.
- No Keystore on the device: the file stays plain and the log says so once per
start.
- A sealed file that can never be opened (tampered, key gone or invalidated,
broken envelope) is removed and that store asks for sign-in again. A transient
Keystore error keeps the file and retries.
This commit is contained in:
1 parent
71e2ae8683
commit
5af14829b0
11 files changed
+462
-16
No files matched your search
@@ -866,6 +866,8 @@ class MainActivity : ComponentActivity() {
|
||||
SessionPrefs.setMicAsked(this)
|
||||
}
|
||||
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
|
||||
// A store sign-in an earlier build left in plain text is sealed with the Keystore key.
|
||||
Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
|
||||
// A session folder left without its ending - the process was killed - gets it now.
|
||||
if (!SessionState.running) Thread({
|
||||
com.droiddeck.launcher.session.LogMigration.run(this)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.droiddeck.launcher.stores
|
||||
|
||||
import android.os.Build
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import org.json.JSONObject
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/**
|
||||
* The stores' sign-in files at rest: AES-256-GCM under a key that lives in the AndroidKeyStore and
|
||||
* never leaves it, as a small versioned envelope `{"v":1,"alg":"AES/GCM","iv":...,"ct":...}`
|
||||
* (base64). The session's Linux side shares the app's files directory but not its Keystore, so
|
||||
* what it can see of a sign-in is the envelope only.
|
||||
*/
|
||||
object CredentialCipher {
|
||||
const val VERSION = 1
|
||||
const val ALG = "AES/GCM"
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
private const val TAG_BITS = 128
|
||||
|
||||
/** Where the key comes from: the AndroidKeyStore on a device, a plain key in tests. */
|
||||
fun interface KeyProvider {
|
||||
/** The key, created on first use. Throws when no key can be had (no Keystore on this ROM). */
|
||||
fun key(): SecretKey
|
||||
|
||||
/** The key that sealed earlier files: never a new one. Throws [KeyMissing] when there is none. */
|
||||
fun existing(): SecretKey = key()
|
||||
}
|
||||
|
||||
/** The Keystore answered and holds no key: nothing sealed before can open again. */
|
||||
class KeyMissing : java.security.GeneralSecurityException("no key")
|
||||
|
||||
/**
|
||||
* Whether [e], from [open], means the file can never open: it does not authenticate (tampered,
|
||||
* or sealed under another key), the key is permanently invalidated or gone, or the file is not
|
||||
* an envelope. Anything else - the Keystore busy or erroring, an I/O error - may pass.
|
||||
*/
|
||||
fun isPermanent(e: Throwable): Boolean = e is javax.crypto.AEADBadTagException ||
|
||||
e is android.security.keystore.KeyPermanentlyInvalidatedException ||
|
||||
e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException
|
||||
|
||||
/**
|
||||
* An AES-256 key in the AndroidKeyStore: not exportable, encrypt/decrypt with GCM only, no user
|
||||
* authentication (background downloads and launch-time code fetches use it with the screen
|
||||
* off). StrongBox where the device has it, the TEE otherwise.
|
||||
*/
|
||||
object Keystore : KeyProvider {
|
||||
private const val ALIAS = "droiddeck-store-credentials"
|
||||
private const val PROVIDER = "AndroidKeyStore"
|
||||
|
||||
@Synchronized
|
||||
override fun existing(): SecretKey {
|
||||
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
||||
return ks.getKey(ALIAS, null) as? SecretKey ?: throw KeyMissing()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun key(): SecretKey {
|
||||
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
||||
(ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
|
||||
if (Build.VERSION.SDK_INT >= 28) {
|
||||
try { return generate(strongBox = true) } catch (e: Exception) { /* no StrongBox: the TEE */ }
|
||||
}
|
||||
return generate(strongBox = false)
|
||||
}
|
||||
|
||||
private fun generate(strongBox: Boolean): SecretKey {
|
||||
val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setKeySize(256)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setUserAuthenticationRequired(false)
|
||||
.apply { if (strongBox && Build.VERSION.SDK_INT >= 28) setIsStrongBoxBacked(true) }
|
||||
.build()
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER).run { init(spec); generateKey() }
|
||||
}
|
||||
}
|
||||
|
||||
/** [plain] sealed into the envelope. The cipher picks the IV (the Keystore requires it). */
|
||||
fun seal(plain: String, keys: KeyProvider): JSONObject {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, keys.key()) }
|
||||
val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
|
||||
return JSONObject().put("v", VERSION).put("alg", ALG)
|
||||
.put("iv", b64(cipher.iv)).put("ct", b64(ct))
|
||||
}
|
||||
|
||||
/** The text inside [envelope]. Throws when it is not ours, of another version, or does not authenticate. */
|
||||
fun open(envelope: JSONObject, keys: KeyProvider): String {
|
||||
require(envelope.optInt("v", -1) == VERSION && envelope.optString("alg") == ALG) { "unknown envelope" }
|
||||
val iv = Base64.decode(envelope.getString("iv"), Base64.NO_WRAP)
|
||||
val ct = Base64.decode(envelope.getString("ct"), Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
|
||||
return String(cipher.doFinal(ct), Charsets.UTF_8)
|
||||
}
|
||||
|
||||
/** Whether [json] is an envelope rather than plain credentials. */
|
||||
fun isEnvelope(json: JSONObject): Boolean = json.has("v") && json.has("ct") && json.has("iv")
|
||||
|
||||
private fun b64(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.stores
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
@@ -9,40 +10,147 @@ import java.io.File
|
||||
* Each store's sign-in, kept in the app's private files: `filesDir/stores/<store>/credentials.json`.
|
||||
* Tokens never go to shared storage and never into a log; the file holds whatever the store's auth
|
||||
* flow handed back (access and refresh tokens, expiry, the account's display name, and for Amazon
|
||||
* the device registration), as one JSON object the store's own client reads and writes.
|
||||
* the device registration), as one JSON object the store's own client reads and writes - sealed
|
||||
* with [CredentialCipher] under a key in the AndroidKeyStore. Every read and write of a sign-in
|
||||
* goes through here.
|
||||
*
|
||||
* - A plain file an earlier build wrote is sealed the first time it is read ([encryptAll] at app
|
||||
* start), verified by opening it again, and the plain text is replaced.
|
||||
* - Where the Keystore does not work (some ROMs), the file stays plain, the log says so once, and
|
||||
* the next start tries again.
|
||||
* - A sealed file that can never open again (the key is gone: data cleared, a backup restored on
|
||||
* another device) is deleted and the store reads as signed out; one that fails for a reason that
|
||||
* may pass is kept and tried again (see [read]).
|
||||
*/
|
||||
object StoreAccounts {
|
||||
private const val TAG = "StoreAccounts"
|
||||
private const val FILE = "credentials.json"
|
||||
|
||||
@VisibleForTesting
|
||||
@Volatile
|
||||
internal var keys: CredentialCipher.KeyProvider = CredentialCipher.Keystore
|
||||
|
||||
/** The Keystore failed once in this process: files stay plain until the next start tries again. */
|
||||
@VisibleForTesting
|
||||
@Volatile
|
||||
internal var keystoreFailed = false
|
||||
|
||||
/** The store's private folder: credentials, caches, the engine's scratch. */
|
||||
fun dir(context: Context, store: Store): File = File(File(context.filesDir, "stores"), store.id).apply { mkdirs() }
|
||||
|
||||
fun credentialsFile(context: Context, store: Store): File = File(dir(context, store), FILE)
|
||||
|
||||
/** The stored credentials, or null when signed out or unreadable (never logged: the text is the secret). */
|
||||
/** Stores whose sealed sign-in could not be opened this time for a reason that may pass (see [read]). */
|
||||
private val unavailable = java.util.concurrent.ConcurrentHashMap.newKeySet<Store>()
|
||||
|
||||
@Volatile
|
||||
private var unavailableLogged = false
|
||||
|
||||
/**
|
||||
* The stored credentials, or null when signed out or unreadable (never logged: the text is the
|
||||
* secret).
|
||||
*
|
||||
* A sealed file is deleted - the store signs in again - only when it can never open: it does
|
||||
* not authenticate (tampered, or another key: data cleared, restored on another device), the
|
||||
* key is permanently invalidated or gone from the Keystore, or it is not an envelope at all. Any
|
||||
* other failure (the Keystore busy or erroring, an I/O error) keeps the file, marks the store
|
||||
* [isUnavailable] - signed in, its actions failing for now - and the next read tries again.
|
||||
*/
|
||||
@Synchronized
|
||||
fun read(context: Context, store: Store): JSONObject? {
|
||||
val f = credentialsFile(context, store)
|
||||
if (!f.isFile) return null
|
||||
return try { JSONObject(f.readText()) } catch (e: Exception) { Log.w(TAG, "${store.id}: credentials unreadable (${e.javaClass.simpleName})"); null }
|
||||
if (!f.isFile) { unavailable.remove(store); return null }
|
||||
val text = try { f.readText() } catch (e: Exception) { return markUnavailable(store, e) }
|
||||
val json = try { JSONObject(text) } catch (e: Exception) { return unreadable(f, store, e) }
|
||||
if (!CredentialCipher.isEnvelope(json)) {
|
||||
unavailable.remove(store)
|
||||
seal(f, json)?.let { Log.i(TAG, "stores: credentials encrypted ${store.id}") }
|
||||
return json
|
||||
}
|
||||
return try {
|
||||
JSONObject(CredentialCipher.open(json, keys)).also { unavailable.remove(store) }
|
||||
} catch (e: Exception) {
|
||||
if (CredentialCipher.isPermanent(e)) unreadable(f, store, e) else markUnavailable(store, e)
|
||||
}
|
||||
}
|
||||
|
||||
/** The store's sign-in is on disk but could not be opened this time (see [read]). */
|
||||
fun isUnavailable(store: Store): Boolean = store in unavailable
|
||||
|
||||
private fun unreadable(f: File, store: Store, e: Exception): JSONObject? {
|
||||
Log.w(TAG, "stores: credentials for ${store.id} cannot be opened (${e.javaClass.simpleName}); signed out")
|
||||
f.delete()
|
||||
unavailable.remove(store)
|
||||
return null
|
||||
}
|
||||
|
||||
private fun markUnavailable(store: Store, e: Exception): JSONObject? {
|
||||
unavailable.add(store)
|
||||
if (!unavailableLogged) {
|
||||
unavailableLogged = true
|
||||
Log.w(TAG, "stores: credentials unreadable this start (${e.javaClass.simpleName})")
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun write(context: Context, store: Store, json: JSONObject) {
|
||||
unavailable.remove(store)
|
||||
val f = credentialsFile(context, store)
|
||||
val tmp = File(f.path + ".tmp")
|
||||
tmp.writeText(json.toString())
|
||||
tmp.setReadable(false, false); tmp.setReadable(true, true)
|
||||
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
|
||||
if (seal(f, json) == null) put(f, json.toString())
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun clear(context: Context, store: Store) {
|
||||
unavailable.remove(store)
|
||||
credentialsFile(context, store).delete()
|
||||
File(credentialsFile(context, store).path + ".tmp").delete()
|
||||
}
|
||||
|
||||
/** The account's display name when signed in (the store's own name for it, or a stand-in), else null. */
|
||||
/** At app start: every plain sign-in an earlier build left is sealed now. */
|
||||
fun encryptAll(context: Context) {
|
||||
Store.entries.forEach { store ->
|
||||
// An older build's temp file held the plain text too.
|
||||
File(credentialsFile(context, store).path + ".tmp").delete()
|
||||
read(context, store)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The account's display name when signed in (the store's own name for it, or a stand-in), else
|
||||
* null. A sign-in that could not be opened this time ([isUnavailable]) still counts, under the
|
||||
* store's name, so the sign-in card does not ask for what is still there.
|
||||
*/
|
||||
fun signedInAs(context: Context, store: Store): String? {
|
||||
val json = read(context, store) ?: return null
|
||||
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
|
||||
if (json.optString("access_token", "").isEmpty()) return null
|
||||
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
|
||||
}
|
||||
|
||||
/**
|
||||
* [json] sealed into [f], checked by opening what was written. Null - and [f] as it was - when
|
||||
* the Keystore cannot seal or the check fails.
|
||||
*/
|
||||
private fun seal(f: File, json: JSONObject): File? {
|
||||
if (keystoreFailed) return null
|
||||
val text = json.toString()
|
||||
val envelope = try {
|
||||
CredentialCipher.seal(text, keys).also { check(CredentialCipher.open(it, keys) == text) { "check failed" } }
|
||||
} catch (e: Exception) {
|
||||
keystoreFailed = true
|
||||
Log.w(TAG, "stores: keystore unavailable, credentials stay plain (${e.javaClass.simpleName})")
|
||||
return null
|
||||
}
|
||||
put(f, envelope.toString())
|
||||
return f
|
||||
}
|
||||
|
||||
/** [text] into [f] through a temp file and a rename, readable and writable by the app alone. */
|
||||
private fun put(f: File, text: String) {
|
||||
val tmp = File(f.path + ".tmp")
|
||||
tmp.writeText(text)
|
||||
tmp.setReadable(false, false); tmp.setReadable(true, true)
|
||||
tmp.setWritable(false, false); tmp.setWritable(true, true)
|
||||
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
|
||||
}
|
||||
}
|
||||
@@ -118,6 +118,11 @@ object StoresState {
|
||||
|
||||
fun isSignedIn(store: Store): Boolean = accounts.containsKey(store)
|
||||
|
||||
/** A store action's error line when it found no usable sign-in: gone, or on disk but unreadable for now. */
|
||||
fun notSignedInLine(store: Store): String =
|
||||
if (StoreAccounts.isUnavailable(store)) "${store.shortLabel} sign-in could not be read: try again."
|
||||
else "${store.shortLabel} session expired: sign in again."
|
||||
|
||||
/** Stores whose sign-in has run out (a launch could not get a code): their chip dims until the user signs in again. */
|
||||
val expired = mutableStateMapOf<Store, Boolean>()
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ object AmazonBackend : StoreBackend {
|
||||
when (result) {
|
||||
is AmazonLibrary.SyncResult.Ok -> { publish(app, result.games); StoresState.problems.remove(store) }
|
||||
is AmazonLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
AmazonLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Amazon session expired: sign in again."
|
||||
AmazonLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
|
||||
AmazonLibrary.SyncResult.Throttled -> publish(app, AmazonLibrary.cached(app))
|
||||
AmazonLibrary.SyncResult.Busy -> {}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreNet
|
||||
import com.droiddeck.launcher.stores.StoresState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.Callable
|
||||
@@ -70,7 +71,7 @@ object AmazonLibrary {
|
||||
}
|
||||
onStatus("Checking sign-in…")
|
||||
val creds = AmazonCredentialStore.load(app) ?: return SyncResult.NotLoggedIn
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed("Amazon session expired: sign in again.")
|
||||
val token = AmazonCredentialStore.getValidAccessToken(app) ?: return SyncResult.Failed(StoresState.notSignedInLine(Store.AMAZON))
|
||||
onStatus("Fetching game list…")
|
||||
val all = AmazonApiClient.getEntitlements(token, creds.deviceSerial)
|
||||
if (all.isNullOrEmpty()) return if (cachedList.isEmpty()) SyncResult.Failed("No games found in your Amazon library") else SyncResult.Ok(cachedList)
|
||||
|
||||
@@ -53,7 +53,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
|
||||
StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { EpicLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store)
|
||||
}
|
||||
is EpicLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "Epic session expired: sign in again."
|
||||
EpicLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
|
||||
EpicLibrary.SyncResult.Throttled -> if (!StoresState.library.containsKey(store)) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached.map { EpicLibrary.toCatalogItem(app, it) })
|
||||
EpicLibrary.SyncResult.Busy -> {}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ object GogBackend : StoreBackend {
|
||||
when (result) {
|
||||
is GogLibrary.SyncResult.Ok -> { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], result.games.map { GogLibrary.toCatalogItem(app, it) }); StoresState.problems.remove(store) }
|
||||
is GogLibrary.SyncResult.Failed -> StoresState.problems[store] = result.message
|
||||
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = "GOG session expired: sign in again."
|
||||
GogLibrary.SyncResult.NotLoggedIn -> StoresState.problems[store] = StoresState.notSignedInLine(store)
|
||||
GogLibrary.SyncResult.Busy -> {}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user