From c248d3e1c45ebcc746a1e9c70d65d588028f3fcd Mon Sep 17 00:00:00 2001 From: The412Banner Date: Fri, 9 Oct 2026 14:14:46 -0400 Subject: [PATCH] Stores: seal sign-in files with an Android Keystore key credentials.json for GOG, Epic and Amazon is an AES-256-GCM envelope ({"v":1,"alg":"AES/GCM","iv","ct"}) under a non-exportable AndroidKeyStore key (StrongBox if present, else TEE, no user authentication). StoreAccounts stays the one layer every reader and writer uses. A plain file from an earlier build is sealed at start, verified, then replaced. Without a Keystore the file stays plain (logged once, retried next start); a file that no longer opens is deleted and the store reads as signed out. --- .../com/droiddeck/launcher/MainActivity.kt | 2 + .../launcher/stores/CredentialCipher.kt | 84 ++++++++++++ .../launcher/stores/StoreAccounts.kt | 82 +++++++++++- .../stores/StoreAccountsCipherTest.kt | 122 ++++++++++++++++++ docs/development/stores.md | 28 +++- docs/progress-log.md | 16 +++ 6 files changed, 326 insertions(+), 8 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 0ef2f323b5..95545f537f 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt b/app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt new file mode 100644 index 0000000000..c0af7ac0b4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/CredentialCipher.kt @@ -0,0 +1,84 @@ +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 + } + + /** + * 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 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.key(), 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) +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt index 1ea8440956..88b4f56201 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreAccounts.kt @@ -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,34 +10,76 @@ import java.io.File * Each store's sign-in, kept in the app's private files: `filesDir/stores//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 no longer opens (the key is gone: data cleared, a backup restored on another + * device) is deleted and the store reads as signed out. */ 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). */ + @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 } + val json = try { JSONObject(f.readText()) } catch (e: Exception) { + Log.w(TAG, "${store.id}: credentials unreadable (${e.javaClass.simpleName})"); null + } ?: return null + if (!CredentialCipher.isEnvelope(json)) { + seal(f, json)?.let { Log.i(TAG, "stores: credentials encrypted ${store.id}") } + return json + } + return try { + JSONObject(CredentialCipher.open(json, keys)) + } catch (e: Exception) { + // The key that sealed it is gone; the sign-in cannot come back, so the store signs in again. + Log.w(TAG, "stores: credentials for ${store.id} cannot be opened (${e.javaClass.simpleName}); signed out") + f.delete() + null + } } + @Synchronized fun write(context: Context, store: Store, json: JSONObject) { 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) { credentialsFile(context, store).delete() + File(credentialsFile(context, store).path + ".tmp").delete() + } + + /** 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. */ @@ -45,4 +88,31 @@ object StoreAccounts { 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) } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt new file mode 100644 index 0000000000..109fbf9f19 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreAccountsCipherTest.kt @@ -0,0 +1,122 @@ +package com.droiddeck.launcher.stores + +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.security.SecureRandom +import javax.crypto.SecretKey +import javax.crypto.spec.SecretKeySpec + +/** The stores' sign-in files sealed at rest; a plain key stands in for the AndroidKeyStore. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class StoreAccountsCipherTest { + private val app get() = RuntimeEnvironment.getApplication() + private fun newKey(): SecretKey = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES") + private val key = newKey() + private val fake = CredentialCipher.KeyProvider { key } + private val broken = CredentialCipher.KeyProvider { throw java.security.KeyStoreException("no keystore") } + + private val creds = JSONObject().put("access_token", "AT-secret-123456").put("refresh_token", "RT-secret-654321") + .put("account_id", "acct-1").put("display_name", "Someone").put("expires_at", 1_900_000_000_000L) + + private fun file(store: Store) = StoreAccounts.credentialsFile(app, store) + + @Before fun setUp() { StoreAccounts.keys = fake; StoreAccounts.keystoreFailed = false } + @After fun tearDown() { StoreAccounts.keys = CredentialCipher.Keystore; StoreAccounts.keystoreFailed = false } + + @Test fun envelopeRoundTrips() { + val envelope = CredentialCipher.seal(creds.toString(), fake) + assertEquals(1, envelope.getInt("v")) + assertEquals("AES/GCM", envelope.getString("alg")) + assertFalse(envelope.toString().contains("secret")) + assertEquals(creds.toString(), CredentialCipher.open(envelope, fake)) + // A fresh IV every time. + assertFalse(envelope.getString("iv") == CredentialCipher.seal(creds.toString(), fake).getString("iv")) + } + + @Test fun writtenCredentialsAreSealedOnDisk() { + StoreAccounts.write(app, Store.EPIC, creds) + val text = file(Store.EPIC).readText() + assertFalse(text.contains("AT-secret") || text.contains("RT-secret") || text.contains("Someone")) + assertTrue(CredentialCipher.isEnvelope(JSONObject(text))) + assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString()) + assertEquals("Someone", StoreAccounts.signedInAs(app, Store.EPIC)) + assertFalse(File(file(Store.EPIC).path + ".tmp").exists()) + } + + @Test fun aPlainFileFromAnEarlierBuildIsSealedAndStaysSignedIn() { + for (store in Store.entries) file(store).writeText(creds.toString()) + File(file(Store.GOG).path + ".tmp").writeText(creds.toString()) + + StoreAccounts.encryptAll(app) + + for (store in Store.entries) { + val text = file(store).readText() + assertTrue(store.id, CredentialCipher.isEnvelope(JSONObject(text))) + assertFalse(store.id, text.contains("secret")) + assertEquals(store.id, creds.toString(), StoreAccounts.read(app, store).toString()) + } + assertFalse(File(file(Store.GOG).path + ".tmp").exists()) + } + + @Test fun aTamperedFileReadsAsSignedOutAndIsDeleted() { + StoreAccounts.write(app, Store.GOG, creds) + val envelope = JSONObject(file(Store.GOG).readText()) + val ct = android.util.Base64.decode(envelope.getString("ct"), android.util.Base64.NO_WRAP) + ct[0] = (ct[0].toInt() xor 1).toByte() + file(Store.GOG).writeText(envelope.put("ct", android.util.Base64.encodeToString(ct, android.util.Base64.NO_WRAP)).toString()) + + assertNull(StoreAccounts.read(app, Store.GOG)) + assertNull(StoreAccounts.signedInAs(app, Store.GOG)) + assertFalse(file(Store.GOG).exists()) + } + + @Test fun aFileSealedUnderALostKeyReadsAsSignedOutAndIsDeleted() { + StoreAccounts.write(app, Store.AMAZON, creds) + // Data cleared, or a backup restored on another device: the Keystore key is a new one. + val other = newKey() + StoreAccounts.keys = CredentialCipher.KeyProvider { other } + assertNull(StoreAccounts.read(app, Store.AMAZON)) + assertFalse(file(Store.AMAZON).exists()) + } + + @Test fun garbageReadsAsSignedOut() { + file(Store.EPIC).writeText("{\"v\":1,\"alg\":\"AES/GCM\",\"iv\":\"!!\",\"ct\":\"??\"}") + assertNull(StoreAccounts.read(app, Store.EPIC)) + file(Store.EPIC).writeText("not json") + assertNull(StoreAccounts.read(app, Store.EPIC)) + } + + @Test fun withoutAKeystoreCredentialsStayPlainAndTheNextStartSealsThem() { + StoreAccounts.keys = broken + StoreAccounts.write(app, Store.EPIC, creds) + assertEquals(creds.toString(), file(Store.EPIC).readText()) + assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString()) + assertTrue(StoreAccounts.keystoreFailed) + + // The next start, on a Keystore that works. + StoreAccounts.keys = fake + StoreAccounts.keystoreFailed = false + StoreAccounts.encryptAll(app) + assertTrue(CredentialCipher.isEnvelope(JSONObject(file(Store.EPIC).readText()))) + assertEquals(creds.toString(), StoreAccounts.read(app, Store.EPIC).toString()) + } + + @Test fun signOutRemovesTheFile() { + StoreAccounts.write(app, Store.GOG, creds) + StoreAccounts.clear(app, Store.GOG) + assertFalse(file(Store.GOG).exists()) + assertNull(StoreAccounts.read(app, Store.GOG)) + } +} diff --git a/docs/development/stores.md b/docs/development/stores.md index ba6963ee5c..3933b7906f 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -189,5 +189,29 @@ Store log lines (the engines' included) go through `StoresState.logLine`, which (`StoreLogFiles`: one file a day, seven days kept, ~2 MB each before it rolls to `.1`). Nothing shows them in the app; the session's Share logs zip carries them under `stores/`. -Credentials live in `filesDir/stores//credentials.json` only (`StoreAccounts`); store URLs -are logged through `StoreLog.redactUrl`, which drops the query string where the signed tokens live. +Store URLs are logged through `StoreLog.redactUrl`, which drops the query string where the signed +tokens live. + +## Security + +- **Sign-ins:** `filesDir/stores//credentials.json` only, read and written through + `StoreAccounts` alone (`GogAuth`, `EpicCredentialStore`, `AmazonCredentialStore`, cloud saves + all call it). The file is an envelope `{"v":1,"alg":"AES/GCM","iv":...,"ct":...}` (base64): + AES-256-GCM (`CredentialCipher`) under a key generated in the AndroidKeyStore (alias + `droiddeck-store-credentials`; encrypt/decrypt, GCM, no padding, not exportable, no user + authentication so background downloads and launch-time exchange codes work with the screen off; + StrongBox where present, else the TEE). Written through a temp file and a rename, mode 600. +- **Earlier plain files:** sealed at app start (`StoreAccounts.encryptAll`, and on any read), + verified by opening the result, the plain file replaced; the log says + `stores: credentials encrypted `. A plain `.tmp` left by an older build is deleted. +- **No Keystore** (some ROMs): the file stays plain, the log says + `stores: keystore unavailable, credentials stay plain ()` once, and the next + start tries again. +- **A file that no longer opens** (key invalidated: data cleared, a backup restored on another + device, tampering): deleted, and the store reads as signed out, so its sign-in card shows. +- **The Linux session:** the app's files directory is bound into every session, so the guest can + see `credentials.json` - as the envelope only; the key never leaves the Keystore. Nothing in the + guest reads the files: `droiddeck-store-launch` asks the app over `/stores/req|resp` + for an Epic exchange code, which the app writes beside the game's launcher; the launcher reads + it into a variable and deletes it before the game starts (single use, expires in minutes). + Steam's own client files are outside this. diff --git a/docs/progress-log.md b/docs/progress-log.md index 23d1529b76..96c4faad95 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -7,6 +7,22 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d --- +## 2026-10-09 - `feat/store-credentials-keystore`: store sign-ins sealed with the Android Keystore + +- **What:** `filesDir/stores//credentials.json` (GOG, Epic, Amazon: tokens, ids, names, + expiry) is now an AES-256-GCM envelope (`{"v":1,"alg":"AES/GCM","iv","ct"}`) under a + non-exportable AndroidKeyStore key (StrongBox if present, else TEE; no user authentication). + `StoreAccounts` is the one layer; `CredentialCipher` holds the envelope and the key. +- **Upgrade:** a plain file is sealed at the first start (verified, then replaced); users stay + signed in. Log: `stores: credentials encrypted `. +- **Fallbacks:** no Keystore - stays plain, logged once, retried next start; a file that will not + open - deleted, signed out (sign-in card), never a crash. +- **Session:** the guest sees the envelope only; it never read the files (the Epic code comes over + the request channel, written beside the launcher and deleted by it). +- **Tests:** `StoreAccountsCipherTest` (round trip, sealed on disk, migration of all three stores, + tampered file, lost key, garbage, no-Keystore fallback then sealed next start, sign-out). Not yet + on a device. + ## 2026-10-08 - `feat/private-logs`: every log in app-private storage, shared as one scrubbed zip - **Where logs live:** `files/logs/` (`LinuxRuntime.logDir`), nothing under `Download/DroidDeck`