fix(desktop): reject unsafe PIN handoffs and stale approvals

This commit is contained in:
maxjivi05 committed 2026-11-26 05:00:16 -05:00
1 parent 7f07415223
commit bf960e4a0a
7 files changed
+219 -25

No files matched your search

@@ -1150,13 +1150,18 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
awaitSessionEnd(next, android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS)
}
private fun awaitSessionEnd(next: Intent, deadline: Long) {
private fun awaitSessionEnd(next: Intent, deadline: Long, source: String? = next.getStringExtra(com.droiddeck.launcher.session.DesktopLock.EXTRA_UNLOCK_SOURCE)) {
switchingTo = next
switchDeadline = deadline
switchPoll?.let { ui.removeCallbacks(it) }
val poll = object : Runnable {
override fun run() {
if (isDestroyed) return
if (source != null && SessionState.sessionId != source) {
switchPoll = null
switchingTo = null
return
}
if (SessionState.running || SessionState.phase !in SESSION_ENDED) {
if (android.os.SystemClock.uptimeMillis() < deadline) ui.postDelayed(this, SESSION_SWITCH_POLL_MS)
else {
@@ -1820,7 +1825,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.ui.TextEntryDialog(
title = androidx.compose.ui.res.stringResource(ask.title), initial = "", number = true, secret = true,
confirm = androidx.compose.ui.res.stringResource(R.string.common_ok),
onSubmit = ask.onPin, onDismiss = { if (pinAsk === ask) { pinAsk = null; ask.onCancel() } }, id = "desktop-lock",
onSubmit = { pin -> if (pinAsk === ask) { pinAsk = null; ask.onPin(pin) } }, onDismiss = { if (pinAsk === ask) { pinAsk = null; ask.onCancel() } }, id = "desktop-lock",
)
}
}
@@ -1874,7 +1879,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
restoreCompatLaunch(savedInstanceState)
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
com.droiddeck.launcher.session.DesktopLock.handoff(savedInstanceState.getString(KEY_UNLOCK_MODE),
savedInstanceState.getString(KEY_UNLOCK_UI), savedInstanceState.getString(KEY_UNLOCK_URL))?.let(::askHandoff)
savedInstanceState.getString(KEY_UNLOCK_UI), savedInstanceState.getString(KEY_UNLOCK_URL))?.copy(source = savedInstanceState.getString(KEY_UNLOCK_SOURCE))?.let(::askHandoff)
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
}
@@ -1939,7 +1944,23 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private class PinAsk(@androidx.annotation.StringRes val title: Int, val onCancel: () -> Unit = {}, val onPin: (String) -> Unit)
private var pinAsk by mutableStateOf<PinAsk?>(null)
private var activePinAsk by mutableStateOf<PinAsk?>(null)
private var pinGeneration = 0
private var pinAsk: PinAsk?
get() = activePinAsk
set(value) { pinGeneration++; activePinAsk = value }
private fun pinWork(work: () -> Boolean, done: (Boolean) -> Unit) {
val generation = pinGeneration
Thread({
val result = runCatching(work)
ui.post {
if (!isDestroyed && !isFinishing && generation == pinGeneration) {
result.fold(done) { pinToast(R.string.game_env_error) }
}
}
}, "desktop-pin").start()
}
private var desktopLock by mutableStateOf(false)
private var pendingUnlock: com.droiddeck.launcher.session.DesktopLock.Handoff? = null
@@ -1949,7 +1970,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun whenUnlocked(action: () -> Unit) {
if (!com.droiddeck.launcher.session.DesktopLock.enabled(this)) return action()
pinAsk = PinAsk(R.string.desktop_lock_enter) { pin ->
if (com.droiddeck.launcher.session.DesktopLock.matches(this, pin)) action() else pinToast(R.string.desktop_lock_wrong)
pinWork({ com.droiddeck.launcher.session.DesktopLock.matches(this, pin) }) { matched ->
if (matched) action() else pinToast(R.string.desktop_lock_wrong)
}
}
}
@@ -1958,8 +1981,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
pendingUnlock = request
pinAsk = PinAsk(R.string.desktop_lock_enter, onCancel = { if (pendingUnlock === request) pendingUnlock = null }) { pin ->
if (pendingUnlock === request) pendingUnlock = null
if (com.droiddeck.launcher.session.DesktopLock.matches(this, pin)) startAfterSession(request.session(this))
else pinToast(R.string.desktop_lock_wrong)
pinWork({ com.droiddeck.launcher.session.DesktopLock.matches(this, pin) }) { matched ->
if (!matched) pinToast(R.string.desktop_lock_wrong)
else if (com.droiddeck.launcher.session.DesktopLock.currentSession(request.source, SessionState.sessionId, SessionState.running)) {
SessionService.stop(this, request.source)
awaitSessionEnd(request.session(this), android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS, request.source)
}
}
}
}
@@ -1971,10 +1999,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!lock.validPin(pin)) pinToast(R.string.desktop_lock_invalid)
else pinAsk = PinAsk(R.string.desktop_lock_confirm) { again ->
if (again != pin) pinToast(R.string.desktop_lock_mismatch)
else desktopLock = lock.set(this, pin)
else pinWork({ lock.set(this, pin) }) { desktopLock = lock.enabled(this) }
}
} else PinAsk(R.string.desktop_lock_enter) { pin ->
if (lock.clear(this, pin)) desktopLock = false else pinToast(R.string.desktop_lock_wrong)
pinWork({ lock.clear(this, pin) }) { cleared ->
desktopLock = lock.enabled(this)
if (!cleared) pinToast(R.string.desktop_lock_wrong)
}
}
}
@@ -2204,6 +2235,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
outState.putString(KEY_UNLOCK_MODE, it.mode)
outState.putString(KEY_UNLOCK_UI, it.ui)
outState.putString(KEY_UNLOCK_URL, it.url)
outState.putString(KEY_UNLOCK_SOURCE, it.source)
}
switchingTo?.let {
outState.putParcelable(KEY_SWITCHING_TO, it)
@@ -2241,6 +2273,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}
override fun onStop() {
pinGeneration++
if (!homeChoiceOpen) HomeApp.releaseUnusedHomeEntry(this)
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(dateReceiver)
@@ -3460,6 +3493,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private const val KEY_SWITCH_DEADLINE = "switch_deadline"
private const val KEY_UNLOCK_MODE = "desktop_unlock_mode"
private const val KEY_UNLOCK_UI = "desktop_unlock_ui"
private const val KEY_UNLOCK_SOURCE = "desktop_unlock_source"
private const val KEY_UNLOCK_URL = "desktop_unlock_url"
private val SESSION_ENDED = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val ZIP_EXT = listOf("zip")
@@ -4180,7 +4180,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun showSecondScreen(requested: SecondScreenMode) {
if (pipUi || !started) return
val mode = if (requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) openingPanel() else requested
val mode = if (requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad ||
requested == SecondScreenMode.DESKTOP && !com.droiddeck.launcher.session.BottomDesktop.available(this)) openingPanel() else requested
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
closeSecondScreen(reset = false)
@@ -13,6 +13,7 @@ object DesktopLock {
const val EXTRA_UNLOCK_MODE = "com.droiddeck.launcher.extra.DESKTOP_UNLOCK_MODE"
const val EXTRA_UNLOCK_UI = "com.droiddeck.launcher.extra.DESKTOP_UNLOCK_UI"
const val EXTRA_UNLOCK_URL = "com.droiddeck.launcher.extra.DESKTOP_UNLOCK_URL"
const val EXTRA_UNLOCK_SOURCE = "com.droiddeck.launcher.extra.DESKTOP_UNLOCK_SOURCE"
private const val PREFS = "desktop_lock"
private const val SALT = "salt"
private const val HASH = "hash"
@@ -20,16 +21,18 @@ object DesktopLock {
private val PIN = Regex("[0-9]{4,8}")
private val UI = Regex("[a-z]{1,32}")
data class Handoff(val mode: String, val ui: String, val url: String) {
data class Handoff(val mode: String, val ui: String, val url: String, val source: String? = null) {
fun put(intent: Intent): Intent = intent
.putExtra(EXTRA_UNLOCK_MODE, mode)
.putExtra(EXTRA_UNLOCK_UI, ui)
.putExtra(EXTRA_UNLOCK_URL, url)
.putExtra(EXTRA_UNLOCK_SOURCE, source)
fun session(context: Context): Intent {
val next = Intent(context, com.droiddeck.launcher.SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, mode)
.putExtra(SessionService.EXTRA_STEAM_UI, ui)
.putExtra(EXTRA_UNLOCK_SOURCE, source)
if (url.isNotEmpty()) next.putExtra(SessionService.EXTRA_STEAM_URL, url)
return next
}
@@ -46,42 +49,66 @@ object DesktopLock {
fun handoff(intent: Intent): Handoff? {
if (!intent.hasExtra(EXTRA_UNLOCK_MODE)) return null
val found = handoff(intent.getStringExtra(EXTRA_UNLOCK_MODE), intent.getStringExtra(EXTRA_UNLOCK_UI), intent.getStringExtra(EXTRA_UNLOCK_URL))
val source = intent.getStringExtra(EXTRA_UNLOCK_SOURCE)
intent.removeExtra(EXTRA_UNLOCK_SOURCE)
intent.removeExtra(EXTRA_UNLOCK_MODE)
intent.removeExtra(EXTRA_UNLOCK_UI)
intent.removeExtra(EXTRA_UNLOCK_URL)
return found
return found?.copy(source = source)
}
private fun prefs(context: Context): SharedPreferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
fun enabled(context: Context): Boolean = prefs(context).contains(HASH)
private data class Credentials(val salt: String?, val hash: String?)
private val saved = java.util.concurrent.ConcurrentHashMap<SharedPreferences, Credentials>()
private fun credentials(p: SharedPreferences): Credentials = saved.computeIfAbsent(p) {
Credentials(it.getString(SALT, null), it.getString(HASH, null))
}
private fun write(p: SharedPreferences, next: Credentials): Boolean {
val previous = credentials(p)
if (!p.edit().putString(SALT, next.salt).putString(HASH, next.hash).commit()) {
p.edit().putString(SALT, previous.salt).putString(HASH, previous.hash).commit()
throw java.io.IOException()
}
saved[p] = next
return true
}
fun enabled(context: Context): Boolean = credentials(prefs(context)).hash != null
fun validPin(pin: String): Boolean = PIN.matches(pin)
fun requiresUnlock(enabled: Boolean, mode: String?, ui: String?): Boolean = enabled && entersDesktop(mode, ui)
fun currentSession(source: String?, current: String?, running: Boolean): Boolean =
source != null && source == current && running
fun entersDesktop(mode: String?, steamUi: String?): Boolean =
mode == SessionService.MODE_DESKTOP || steamUi == "desktop"
fun entersDesktop(intent: Intent): Boolean =
entersDesktop(intent.getStringExtra(SessionService.EXTRA_MODE), intent.getStringExtra(SessionService.EXTRA_STEAM_UI))
@Synchronized
fun set(context: Context, pin: String): Boolean {
if (!validPin(pin)) return false
val salt = ByteArray(16).also { SecureRandom().nextBytes(it) }
return prefs(context).edit()
.putString(SALT, Base64.getEncoder().encodeToString(salt))
.putString(HASH, Base64.getEncoder().encodeToString(hash(pin, salt)))
.commit()
return write(prefs(context), Credentials(Base64.getEncoder().encodeToString(salt),
Base64.getEncoder().encodeToString(hash(pin, salt))))
}
fun matches(context: Context, pin: String): Boolean {
val p = prefs(context)
val salt = p.getString(SALT, null)?.let { runCatching { Base64.getDecoder().decode(it) }.getOrNull() } ?: return false
val stored = p.getString(HASH, null)?.let { runCatching { Base64.getDecoder().decode(it) }.getOrNull() } ?: return false
val storedCredentials = credentials(prefs(context))
val salt = storedCredentials.salt?.let { runCatching { Base64.getDecoder().decode(it) }.getOrNull() } ?: return false
val stored = storedCredentials.hash?.let { runCatching { Base64.getDecoder().decode(it) }.getOrNull() } ?: return false
return validPin(pin) && MessageDigest.isEqual(stored, hash(pin, salt))
}
@Synchronized
fun clear(context: Context, pin: String): Boolean =
matches(context, pin) && prefs(context).edit().clear().commit()
matches(context, pin) && write(prefs(context), Credentials(null, null))
internal fun hash(pin: String, salt: ByteArray): ByteArray {
val spec = PBEKeySpec(pin.toCharArray(), salt, ROUNDS, 256)
@@ -233,6 +233,8 @@ class SessionService : Service() {
return START_NOT_STICKY
}
ACTION_STOP -> {
if (intent.hasExtra(DesktopLock.EXTRA_UNLOCK_SOURCE) &&
!DesktopLock.currentSession(intent.getStringExtra(DesktopLock.EXTRA_UNLOCK_SOURCE), SessionState.sessionId, SessionState.running)) return START_NOT_STICKY
Log.i(TAG, "stop requested from the notification")
stopSession(0)
return START_NOT_STICKY
@@ -1932,8 +1934,8 @@ class SessionService : Service() {
.putExtra(EXTRA_STEAM_UI, ui)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (url.isNotEmpty()) next.putExtra(EXTRA_STEAM_URL, url)
val unlock = if (DesktopLock.enabled(this@SessionService)) DesktopLock.handoff(session, ui, url) else null
if (unlock != null) {
if (DesktopLock.requiresUnlock(DesktopLock.enabled(this@SessionService), session, ui)) {
val unlock = DesktopLock.handoff(session, ui, url)?.copy(source = SessionState.sessionId) ?: return
val home = unlock.put(Intent(this@SessionService, com.droiddeck.launcher.FrontEndActivity::class.java))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
android.os.Handler(android.os.Looper.getMainLooper()).post {
@@ -2679,7 +2681,14 @@ class SessionService : Service() {
else context.startService(intent)
}
fun stop(context: Context) {
fun stop(context: Context, source: String? = null) {
if (source != null) {
if (DesktopLock.currentSession(source, SessionState.sessionId, SessionState.running)) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_STOP)
.putExtra(DesktopLock.EXTRA_UNLOCK_SOURCE, source))
}
return
}
if (!SessionState.running) {
SessionState.stopRequested = true
SessionState.installCancellation?.cancel()
@@ -688,7 +688,7 @@ internal fun TextEntryDialog(
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var text by remember { mutableStateOf(initial) }
val submit = { onSubmit(text.trim()); close() }
val submit = { if (shown.targetState) { close(); onSubmit(text.trim()) } }
AppDialog(shown, close, id, wide = false, maxWidth = 460.dp) {
DialogTitleRow(title, close)
AdbTextField(
@@ -0,0 +1,82 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.SharedPreferences
import com.droiddeck.launcher.input.SecondScreenMode
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class DesktopLockLifecycleTest {
@Test fun invalidDesktopMetadataStillRequiresApproval() {
for ((ui, url) in listOf("desktop" to "https://example.org", "bad-ui" to "", "" to "")) {
assertTrue(DesktopLock.requiresUnlock(true, SessionService.MODE_DESKTOP, ui))
assertNull(DesktopLock.handoff(SessionService.MODE_DESKTOP, ui, url))
}
assertFalse(DesktopLock.requiresUnlock(false, SessionService.MODE_DESKTOP, "desktop"))
assertFalse(DesktopLock.requiresUnlock(true, SessionService.MODE_STEAM, "bigpicture"))
assertNotNull(DesktopLock.handoff(SessionService.MODE_STEAM, "desktop", "steam://open/main"))
}
@Test fun handoffRetainsSourceAndIsConsumed() {
val request = DesktopLock.Handoff(SessionService.MODE_DESKTOP, "desktop", "", "original")
val intent = request.put(Intent())
assertEquals(request, DesktopLock.handoff(intent))
assertNull(DesktopLock.handoff(intent))
assertTrue(DesktopLock.currentSession("original", "original", true))
assertFalse(DesktopLock.currentSession("original", "replacement", true))
assertFalse(DesktopLock.currentSession("original", "original", false))
assertFalse(DesktopLock.currentSession(null, null, true))
}
@Test fun unavailableDesktopFallsBackWithoutChangingSavedChoice() {
val remembered = SecondScreenMode.DESKTOP.id
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(remembered, true, bottomDesktop = false))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(remembered, false, bottomDesktop = false))
assertEquals(SecondScreenMode.DESKTOP, SecondScreenMode.opening(remembered, true, bottomDesktop = true))
assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", true, bottomDesktop = false))
}
@Test fun failedWritesKeepLastSavedCredentialsAndSuccessfulClearDisablesLock() {
val base = RuntimeEnvironment.getApplication() as Context
val real = base.getSharedPreferences("desktop-lock-test-${System.nanoTime()}", Context.MODE_PRIVATE)
var fail = false
val preferences = object : SharedPreferences by real {
override fun edit(): SharedPreferences.Editor {
val editor = real.edit()
return object : SharedPreferences.Editor by editor {
override fun putString(key: String?, value: String?): SharedPreferences.Editor {
editor.putString(key, value)
return this
}
override fun commit(): Boolean {
val written = editor.commit()
return written && !fail
}
}
}
}
val context = object : ContextWrapper(base) {
override fun getSharedPreferences(name: String, mode: Int) = preferences
}
assertFalse(DesktopLock.enabled(context))
assertTrue(DesktopLock.set(context, "2468"))
assertFalse(DesktopLock.clear(context, "1234"))
fail = true
assertThrows(java.io.IOException::class.java) { DesktopLock.clear(context, "2468") }
assertTrue(DesktopLock.enabled(context))
assertTrue(DesktopLock.matches(context, "2468"))
assertThrows(java.io.IOException::class.java) { DesktopLock.set(context, "1357") }
assertTrue(DesktopLock.matches(context, "2468"))
assertFalse(DesktopLock.matches(context, "1357"))
fail = false
assertTrue(DesktopLock.clear(context, "2468"))
assertFalse(DesktopLock.enabled(context))
assertFalse(DesktopLock.matches(context, "2468"))
}
}
@@ -0,0 +1,41 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.test.onNodeWithText
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class TextEntrySubmissionTest {
@get:Rule val compose = createRobolectricComposeRule()
@Test fun duplicateSubmitDuringClosingIsIgnored() {
var submissions = 0
compose.setContent {
DroidDeckTheme {
TextEntryDialog("PIN", "2468", true, "Submit", { submissions++ }, {}, secret = true)
}
}
val submit = compose.onNodeWithText("Submit").fetchSemanticsNode().config[SemanticsActions.OnClick].action!!
compose.runOnIdle { submit(); submit() }
assertEquals(1, submissions)
}
@Test fun submitAfterCancelStartsIsIgnored() {
var submissions = 0
compose.setContent {
DroidDeckTheme {
TextEntryDialog("PIN", "2468", true, "Submit", { submissions++ }, {}, secret = true)
}
}
val submit = compose.onNodeWithText("Submit").fetchSemanticsNode().config[SemanticsActions.OnClick].action!!
val cancel = compose.onNodeWithText("Cancel").fetchSemanticsNode().config[SemanticsActions.OnClick].action!!
compose.runOnIdle { cancel(); submit() }
assertEquals(0, submissions)
}
}