Skip to content

Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.

Connect: a wireless debugging TV that doesn't know our key asks for the code

jesse-agent-821ec3e0c0c4611
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
index 018d20a..c99abea 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt
@@ -13,6 +13,7 @@ import okio.Buffer
import okio.Path.Companion.toPath
import okio.Sink
import okio.Source
+import java.io.DataInputStream
import java.io.File
import java.io.IOException
import java.io.InterruptedIOException
@@ -130,11 +131,42 @@ object Connector {
} catch (e: Exception) {
// Kadb also throws IllegalStateException on protocol surprises; never let it escape.
kadb.close()
- // No answer times out; Deny makes adbd drop the socket. Both read as "not allowed".
- if (e.isAuthFailure()) ConnectResult.NotAllowed else ConnectResult.Unreachable(e.message ?: e.javaClass.simpleName)
+ when {
+ // How a TV turns down an unpaired key varies by TLS stack and Android version, and Kadb
+ // maps only some alerts to AdbPairAuthException; the rest read as "didn't answer".
+ asksForTls(host, port) -> ConnectResult.NeedsPairing
+ // No answer times out; Deny makes adbd drop the socket. Both read as "not allowed".
+ e.isAuthFailure() -> ConnectResult.NotAllowed
+ else -> ConnectResult.Unreachable(e.message ?: e.javaClass.simpleName)
+ }
}
}
+ /**
+ * Whether [host]:[port] answers an ADB hello with STLS. Only a wireless debugging port does, and
+ * it never shows the Allow box: a key it turns down needs the pairing code.
+ */
+ private suspend fun asksForTls(host: String, port: Int): Boolean = runCatching {
+ runInterruptible(Dispatchers.IO) {
+ Socket().use { s ->
+ s.connect(InetSocketAddress(host, port), TCP_TIMEOUT_MS)
+ s.soTimeout = TCP_TIMEOUT_MS
+ s.getOutputStream().write(adbMessage(A_CNXN, 0x01000001, 256 * 1024, "host::\u0000".toByteArray()))
+ val header = ByteArray(24).also(DataInputStream(s.getInputStream())::readFully)
+ ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN).int == A_STLS
+ }
+ }
+ }.getOrElse { if (it is CancellationException) throw it else false }
+
+ private const val A_CNXN = 0x4e584e43
+ private const val A_STLS = 0x534c5453
+
+ /** An ADB packet: six little-endian words (command, two args, length, byte sum, ~command), then [data]. */
+ private fun adbMessage(command: Int, arg0: Int, arg1: Int, data: ByteArray): ByteArray =
+ ByteBuffer.allocate(24 + data.size).order(ByteOrder.LITTLE_ENDIAN)
+ .putInt(command).putInt(arg0).putInt(arg1).putInt(data.size)
+ .putInt(data.sumOf { it.toInt() and 0xff }).putInt(command.inv()).put(data).array()
+
/**
* Android 11+ wireless debugging: pair once with the 6-digit code, then [connect] to the connect
* port. Never throws, except to cancel.
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ConnectorTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ConnectorTest.kt
index c114bd2..245198f 100644
--- a/adb/src/test/kotlin/app/tellyscope/adb/ConnectorTest.kt
+++ b/adb/src/test/kotlin/app/tellyscope/adb/ConnectorTest.kt
@@ -1,12 +1,26 @@
// SPDX-License-Identifier: GPL-3.0-only
package app.tellyscope.adb
+import com.flyfishxu.kadb.cert.KadbCert
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import java.io.File
import java.net.InetAddress
import java.net.ServerSocket
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
import java.nio.file.Files
+import java.security.KeyFactory
+import java.security.KeyStore
+import java.security.cert.CertificateException
+import java.security.cert.CertificateFactory
+import java.security.cert.X509Certificate
+import java.security.spec.PKCS8EncodedKeySpec
+import java.util.Base64
+import javax.net.ssl.KeyManagerFactory
+import javax.net.ssl.SSLContext
+import javax.net.ssl.SSLSocket
+import javax.net.ssl.X509TrustManager
import kotlin.concurrent.thread
import kotlin.test.BeforeTest
import kotlin.test.Test
@@ -60,4 +74,46 @@ class ConnectorTest {
@Test fun badCodeIsWrongCode() = runBlocking<Unit> {
assertEquals(PairResult.WrongCode("pairing code must be 6 digits"), Connector.pair("127.0.0.1", 1, "12a456"))
}
+
+ @Test fun wirelessPortThatRefusesOurKeyNeedsPairing() = runBlocking<Unit> {
+ // A wireless debugging connect port on a TV that hasn't paired with this phone: it asks for TLS,
+ // lets TLS 1.3 finish on our side, then turns the key down. This read as "the TV didn't answer".
+ ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")).use { server ->
+ thread(isDaemon = true) { while (true) runCatching { server.accept().use(::refuseUnpairedKey) } }
+ val r = withTimeout(30_000) { Connector.connect("127.0.0.1", server.localPort, allowWaitMs = 10_000) }
+ assertEquals(ConnectResult.NeedsPairing, r)
+ }
+ }
+
+ /** adbd's side: read CNXN, answer STLS, then turn down every client certificate in TLS. */
+ private fun refuseUnpairedKey(socket: java.net.Socket) {
+ val input = java.io.DataInputStream(socket.getInputStream())
+ val header = ByteArray(24).also(input::readFully)
+ input.skipNBytes(ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN).getInt(12).toLong())
+ val stls = 0x534c5453
+ socket.getOutputStream().write(
+ ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN)
+ .putInt(stls).putInt(0x01000000).putInt(0).putInt(0).putInt(0).putInt(stls.inv()).array(),
+ )
+ // The server borrows this phone's own identity; only the client check matters here.
+ val id = KadbCert.ensureReady()
+ val cert = CertificateFactory.getInstance("X.509").generateCertificate(id.certificatePem.inputStream())
+ val der = Base64.getMimeDecoder().decode(String(id.privateKeyPem).replace(Regex("-----[A-Z ]+-----"), ""))
+ val key = KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(der))
+ val store = KeyStore.getInstance("PKCS12").apply { load(null); setKeyEntry("adbd", key, CharArray(0), arrayOf(cert)) }
+ val keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(store, CharArray(0)) }
+ val unknownKey = object : X509TrustManager {
+ override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) =
+ throw CertificateException("not a paired key")
+ override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
+ }
+ val ctx = SSLContext.getInstance("TLSv1.3").apply { init(keys.keyManagers, arrayOf(unknownKey), null) }
+ (ctx.socketFactory.createSocket(socket, null, socket.port, true) as SSLSocket).use { tls ->
+ tls.useClientMode = false
+ tls.needClientAuth = true
+ tls.enabledProtocols = arrayOf("TLSv1.3")
+ runCatching { tls.startHandshake() } // throws once it rejects ours
+ }
+ }
}