Xbox: fix sign-in on phones with a slow StrongBox Keystore (#1521)

On some phones (tester: Honor BKQ-N49, Android 17) Xbox sign-in stopped with
"the Xbox helper stopped with exit code 1" before Microsoft's page opened.
The backend asks the app to read and save credentials over a socket and waits
10 s for each reply. The app sealed credentials with a StrongBox-backed
Keystore key, and each StrongBox operation took 7-15 s on that phone, so the
backend gave up. The app still finished those saves afterwards, leaving a
record without a username that every later attempt had to read back slowly.

- Seal new store credentials with a TEE Keystore key (v2 envelopes); v1
  envelopes still open with the old key and move to v2 on their next write.
- A sign-in discards an Xbox record without a username (an unfinished
  sign-in) before starting the backend.
- The backend waits 30 s for the app's credential reply.
- The backend names the failing step instead of only credential-io (socket
  connect/exchange, session lock, missing socket name/port/key), and falls
  back to a keyed 127.0.0.1 port when the abstract socket is refused.
- The app's credential listener logs and retries accept errors, serves each
  connection on its own thread, and logs slow requests with per-stage times.

Refs #1337, #1300


Co-authored-by: KeegantheVeganat0r <58369898+KeegantheVeganat0r@users.noreply.github.com>
This commit is contained in:
The412BannerandKeegantheVeganat0r authored and GitHub committed 2026-10-25 01:39:09 +00:00
1 parent 82d8eb3b79
commit 5ca1f610ab
11 files changed
+541 -41

No files matched your search

@@ -1,6 +1,5 @@
package com.droiddeck.launcher.stores
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
@@ -13,6 +12,8 @@ import javax.crypto.spec.GCMParameterSpec
object CredentialCipher {
const val VERSION = 1
/** Sealed with the hardware-keystore (TEE) key; [VERSION] envelopes keep opening with the older, possibly StrongBox, key. */
const val VERSION_TEE = 2
const val ALG = "AES/GCM"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val TAG_BITS = 128
@@ -21,6 +22,11 @@ object CredentialCipher {
fun key(): SecretKey
fun existing(): SecretKey = key()
/** Key for [VERSION] envelopes written before [VERSION_TEE]. */
fun legacy(): SecretKey = existing()
val version: Int get() = VERSION
}
class KeyMissing : java.security.GeneralSecurityException("no key")
@@ -29,33 +35,33 @@ object CredentialCipher {
e is android.security.keystore.KeyPermanentlyInvalidatedException ||
e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException
// StrongBox took over 10 s per Xbox credential write on a tester's phone, past the backend's
// 10 s reply timeout, so new writes use a TEE key. The old alias stays readable.
object Keystore : KeyProvider {
private const val ALIAS = "droiddeck-store-credentials"
private const val LEGACY_ALIAS = "droiddeck-store-credentials"
private const val ALIAS = "droiddeck-store-credentials-tee"
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()
}
override val version: Int get() = VERSION_TEE
@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) { }
}
return generate(strongBox = false)
}
override fun existing(): SecretKey = stored(ALIAS) ?: throw KeyMissing()
private fun generate(strongBox: Boolean): SecretKey {
@Synchronized
override fun legacy(): SecretKey = stored(LEGACY_ALIAS) ?: throw KeyMissing()
@Synchronized
override fun key(): SecretKey = stored(ALIAS) ?: generate()
private fun stored(alias: String): SecretKey? =
KeyStore.getInstance(PROVIDER).apply { load(null) }.getKey(alias, null) as? SecretKey
private fun generate(): 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() }
}
@@ -64,15 +70,16 @@ object CredentialCipher {
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)
return JSONObject().put("v", keys.version).put("alg", ALG)
.put("iv", b64(cipher.iv)).put("ct", b64(ct))
}
fun open(envelope: JSONObject, keys: KeyProvider): String {
require(envelope.optInt("v", -1) == VERSION && envelope.optString("alg") == ALG) { "unknown envelope" }
val version = envelope.optInt("v", -1)
require((version == VERSION || version == VERSION_TEE) && 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)) }
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, if (version == VERSION) keys.legacy() else keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
return String(cipher.doFinal(ct), Charsets.UTF_8)
}
@@ -14,6 +14,11 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
val name = "droiddeck-xbox-${UUID.randomUUID()}"
private val generation = lifecycle(app, expectedGeneration) { it }
private val server = LocalServerSocket(name)
// Some devices refuse the abstract socket from inside PRoot; the backend then falls back to this keyed loopback port.
private val loopback = java.net.ServerSocket(0, 8, java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)))
val port: Int get() = loopback.localPort
val key: String = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
@Volatile private var loopbackUsed = false
@Volatile private var closed = false
private val bound = java.util.concurrent.CountDownLatch(1)
private var backend: Process? = null
@@ -79,33 +84,122 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
} }
}
init {
/** Each connection gets its own thread; an accept error is logged and retried instead of silently ending the loop. */
private fun <S> listen(route: String, accept: () -> S, serve: (S) -> Unit) = Thread({
var failures = 0
while (!closed) {
val socket = try { accept() } catch (e: Exception) {
if (closed) break
failures++
note("Credential $route accept failed: ${e.javaClass.simpleName}")
if (failures >= 20) { note("Credential $route listener stopped after repeated accept failures"); break }
Thread.sleep(100)
continue
}
failures = 0
Thread({ serve(socket) }, "xbox-credentials-$route-request").start()
}
}, "xbox-credentials-$route").start()
/** Logs requests that take 2 s or more, and the stage a request is still in after 8 s (the backend waits 30 s). */
private fun tracked(route: String, block: (step: (String) -> Unit) -> JSONObject): JSONObject {
val started = android.os.SystemClock.elapsedRealtime()
val stage = java.util.concurrent.atomic.AtomicReference("auth")
val done = java.util.concurrent.CountDownLatch(1)
val stages = java.util.Collections.synchronizedList(mutableListOf<String>())
var mark = started
val step = { next: String ->
val now = android.os.SystemClock.elapsedRealtime()
stages += "${stage.getAndSet(next)} ${now - mark} ms"
mark = now
}
Thread({
while (!closed) {
val socket = runCatching { server.accept() }.getOrNull() ?: break
socket.use {
it.soTimeout = 10_000
val reply = runCatching {
if (!done.await(8, java.util.concurrent.TimeUnit.SECONDS)) note("Credential $route request still in ${stage.get()} after 8 s")
}, "xbox-credentials-watch").apply { isDaemon = true; start() }
try {
return block(step)
} finally {
done.countDown()
step("done")
val total = android.os.SystemClock.elapsedRealtime() - started
if (total >= 2000) note("Credential $route request took $total ms (${stages.joinToString(", ")})")
}
}
init {
listen("socket", { server.accept() }) { socket ->
socket.use {
it.soTimeout = 10_000
val reply = tracked("socket") { step ->
runCatching {
val peer = it.peerCredentials
check(peer.uid == android.os.Process.myUid() && authorized(peer.pid))
step("read")
val request = JSONObject(readLine(it.inputStream.buffered(), 2_097_152))
step("lock")
storage(app) {
step("answer")
check(!closed && epoch(app) == generation && authorized(peer.pid))
answer(request)
answer(request, step)
}
}.getOrElse {
note("Credential request rejected: ${it.javaClass.simpleName}")
JSONObject().put("ok", false)
}
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
}
runCatching { it.outputStream.write((reply.toString() + "\n").toByteArray()) }
.onFailure { failure -> note("Credential reply not delivered: ${failure.javaClass.simpleName}") }
}
}, "xbox-credentials").start()
}
listen("loopback", { loopback.accept() }) { socket ->
socket.use {
it.soTimeout = 10_000
val reply = tracked("loopback") { step ->
runCatching {
val input = it.getInputStream().buffered()
check(it.inetAddress.isLoopbackAddress)
if (!java.security.MessageDigest.isEqual(readLine(input, 128).toByteArray(), key.toByteArray())) {
rejected("loopback-key"); error("loopback key")
}
if (!loopbackOwner(it.port)) { rejected("loopback-owner"); error("loopback owner") }
check(bound.await(5, java.util.concurrent.TimeUnit.SECONDS) && backend?.isAlive == true)
if (!loopbackUsed) { loopbackUsed = true; note("Backend reached the app over the loopback fallback") }
step("read")
val request = JSONObject(readLine(input, 2_097_152))
step("lock")
storage(app) {
step("answer")
check(!closed && epoch(app) == generation)
answer(request, step)
}
}.getOrElse { failure ->
note("Credential request rejected: ${failure.javaClass.simpleName}")
JSONObject().put("ok", false)
}
}
runCatching { it.getOutputStream().write((reply.toString() + "\n").toByteArray()) }
.onFailure { failure -> note("Credential reply not delivered: ${failure.javaClass.simpleName}") }
}
}
}
private fun answer(request: JSONObject): JSONObject {
/** The connecting socket must belong to this app's user; an unreadable table (newer Android) leaves the key as the check. */
private fun loopbackOwner(peerPort: Int): Boolean {
val uid = android.os.Process.myUid()
val rows = listOf("/proc/net/tcp", "/proc/net/tcp6").mapNotNull { runCatching { java.io.File(it).readLines().drop(1) }.getOrNull() }.flatten()
val owners = rows.mapNotNull { row ->
val fields = row.trim().split(Regex("\\s+"))
val local = fields.getOrNull(1)?.substringAfterLast(':')?.toIntOrNull(16)
val remote = fields.getOrNull(2)?.substringAfterLast(':')?.toIntOrNull(16)
if (local == peerPort && remote == loopback.localPort) fields.getOrNull(7)?.toIntOrNull() else null
}
return owners.isEmpty() || owners.all { it == uid }
}
private fun answer(request: JSONObject, step: (String) -> Unit = {}): JSONObject {
val key = request.getString("key")
require(key.isNotEmpty() && key.length <= 512)
step("record-read")
val record = StoreAccounts.read(app, Store.XBOX)
check(!StoreAccounts.isUnavailable(Store.XBOX))
val json = record ?: JSONObject()
@@ -118,15 +212,16 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str
require(bytes.length() <= 262_144)
for (i in 0 until bytes.length()) require(bytes.getInt(i) in 0..255)
slots.put(key, bytes)
step("record-save")
StoreAccounts.write(app, Store.XBOX, json)
}
"remove" -> { slots.remove(key); StoreAccounts.write(app, Store.XBOX, json) }
"remove" -> { slots.remove(key); step("record-save"); StoreAccounts.write(app, Store.XBOX, json) }
else -> error("Invalid credential operation")
}
return result
}
override fun close() { closed = true; bound.countDown(); runCatching { server.close() } }
override fun close() { closed = true; bound.countDown(); runCatching { server.close() }; runCatching { loopback.close() } }
companion object {
val lock = Any()
@@ -31,6 +31,7 @@ class XboxLoginActivity : ComponentActivity() {
@Volatile private var session = 0L
@Volatile private var closed = false
@Volatile private var step = "starting"
private val codes = java.util.concurrent.CopyOnWriteArrayList<String>()
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
@@ -53,6 +54,14 @@ class XboxLoginActivity : ComponentActivity() {
Thread({
if (closed) return@Thread
try {
// A record without a username is left from a sign-in that never finished; starting clean
// also avoids reading it back with an older, slow Keystore key.
progress("preparing the sign-in", "Preparing Microsoft sign-in…")
val leftover = StoreAccounts.read(applicationContext, Store.XBOX)
if (leftover != null && leftover.optString("username").isBlank()) {
XboxCredentials.invalidate(applicationContext)
logStep("discarded credentials from an unfinished sign-in")
}
val accountGeneration = XboxCredentials.lifecycle(applicationContext) { it }
progress("downloading the Xbox components", "Downloading Xbox components…")
check(AddonPack.XBOX.await(applicationContext, { !closed }) { state ->
@@ -64,7 +73,10 @@ class XboxLoginActivity : ComponentActivity() {
child = process
if (closed) return@use
// StoresState.logLine writes no file in this process, so the reason would miss the shared log.
Xodus.diagnostics(process) { logStep(it) }
Xodus.diagnostics(process) { line ->
logStep(line)
line.removePrefix("NEXUS_CREDENTIAL_ERROR_V1 ").takeIf { it != line && it !in codes && codes.size < 6 }?.let(codes::add)
}
progress("waiting for the Xbox helper", "Waiting for the Xbox helper…")
val timer = Thread({
runCatching { if (!process.process.waitFor(10, TimeUnit.MINUTES)) process.process.destroy() }
@@ -140,7 +152,8 @@ class XboxLoginActivity : ComponentActivity() {
logStep("failed while $failed: $reason")
runOnUiThread {
disposeView()
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason\nClose this window and try again."
val details = if (codes.isEmpty()) "" else "\nDetails: ${codes.joinToString(", ")}"
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason$details\nClose this window and try again."
}
}
}, "xbox-login").start()
@@ -101,6 +101,8 @@ internal object Xodus {
val command = LinuxRuntime.commandWithBinds(app, root, binds, guestCommand)
val builder = ProcessBuilder(command).directory(LinuxRuntime.rootDir(app))
if (launchDirectory != null) builder.environment()["TMPDIR"] = launchDirectory.path
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_PORT"] = credentials.port.toString()
builder.environment()["DROIDDECK_XBOX_CREDENTIAL_KEY"] = credentials.key
builder.environment().apply {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)