Modern Apps git

← Modern-Apps.git

auto: TLS record codec and stream transport

Commit
eee67e1c963b3f3d4615cd382b46ee937b4c4049
Author
vayun-mathur <[email protected]>
When
2026-09-12 01:33 UTC (2 months ago)
Parents
043a95b

Diff

auto/protocol/src/main/java/com/vayunmathur/auto/protocol/StreamTransport.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/StreamTransport.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/StreamTransport.ktnew file mode 100644index 0000000000..24f661c3e7--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/StreamTransport.kt@@ -0,0 +1,37 @@+package com.vayunmathur.auto.protocol++import java.io.InputStream+import java.io.OutputStream++/**+ * A [GalTransport] over an ordinary stream pair.+ *+ * Covers both transports: USB hands back a `ParcelFileDescriptor` that is read as a plain+ * file descriptor (`carsetup/setup/UsbConnectionHelper.java`), and wireless ends up at a TCP+ * socket. Neither needs anything the other does not.+ */+class StreamTransport(+    private val input: InputStream,+    private val output: OutputStream,+) : GalTransport {++    override fun read(buffer: ByteArray, offset: Int, length: Int): Int =+        input.read(buffer, offset, length)++    override fun write(bytes: ByteArray, offset: Int, length: Int) {+        output.write(bytes, offset, length)+    }++    override fun flush() {+        output.flush()+    }++    override fun close() {+        // Close both even if the first throws, so a failure on one does not leak the other.+        try {+            input.close()+        } finally {+            output.close()+        }+    }+}
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TlsCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TlsCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TlsCodec.ktnew file mode 100644index 0000000000..e5082e1baa--- /dev/null+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/TlsCodec.kt@@ -0,0 +1,59 @@+package com.vayunmathur.auto.protocol++import java.nio.ByteBuffer+import javax.net.ssl.SSLEngine+import javax.net.ssl.SSLEngineResult.Status++/**+ * Wraps and unwraps application data once the handshake is done.+ *+ * Gearhead encrypts per frame, so one frame payload is one TLS record and this is what+ * [FrameWriter]'s `encrypt` and [FrameReader]'s `decrypt` hooks are given. Handshake data is+ * *not* routed through here: those records travel in the clear as control message 3, because+ * they are the negotiation itself.+ *+ * An [SSLEngine] is not thread-safe, so a connection must not wrap on one thread while+ * unwrapping on another. The driver reads and writes from a single loop for that reason.+ */+class TlsCodec(private val engine: SSLEngine) {++    /** Encrypts one frame payload into a single TLS record. */+    fun wrap(plaintext: ByteArray): ByteArray {+        val source = ByteBuffer.wrap(plaintext)+        val record = ByteBuffer.allocate(engine.session.packetBufferSize)+        while (source.hasRemaining()) {+            val result = engine.wrap(source, record)+            check(result.status == Status.OK) { "TLS wrap failed: ${result.status}" }+        }+        record.flip()+        return ByteArray(record.remaining()).also { record.get(it) }+    }++    /**+     * Decrypts one frame payload.+     *+     * @throws IllegalStateException if [record] is not a whole TLS record. Frames carry+     *   complete records, so a partial one means the frame layer handed over the wrong+     *   bytes rather than something to wait on.+     */+    fun unwrap(record: ByteArray): ByteArray {+        val source = ByteBuffer.wrap(record)+        var plain = ByteBuffer.allocate(engine.session.applicationBufferSize)+        while (source.hasRemaining()) {+            val result = engine.unwrap(source, plain)+            when (result.status) {+                Status.OK -> Unit+                Status.BUFFER_OVERFLOW -> {+                    // Grow and retry rather than truncating.+                    val bigger = ByteBuffer.allocate(plain.capacity() * 2)+                    plain.flip()+                    bigger.put(plain)+                    plain = bigger+                }+                else -> error("TLS unwrap failed: ${result.status}")+            }+        }+        plain.flip()+        return ByteArray(plain.remaining()).also { plain.get(it) }+    }+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.ktindex 01a3128dd9..16023109a0 100644--- a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.kt+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalCredentialTest.kt@@ -1,19 +1,14 @@ package com.vayunmathur.auto.protocol  import java.io.File-import java.nio.ByteBuffer import java.security.KeyStore import java.security.cert.CertificateFactory import java.security.cert.X509Certificate-import javax.net.ssl.SSLEngine-import javax.net.ssl.SSLEngineResult.HandshakeStatus-import javax.net.ssl.SSLEngineResult.Status import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue-import kotlin.test.fail  /**  * Exercises the shipped GAL credential without a device.@@ -24,20 +19,12 @@ import kotlin.test.fail  */ class GalCredentialTest { -    private val assetDir = File("src/main/assets/gal")-     private fun asset(name: String): String {-        val file = File(assetDir, name)+        val file = File("src/main/assets/gal", name)         assertTrue(file.exists(), "missing shipped asset ${file.absolutePath}")         return file.readText()     } -    private fun context() = GalCredential.create(-        certPem = asset("client-cert.pem"),-        keyPem = asset("client-key.pem"),-        rootPem = asset("root.pem"),-    )-     @Test     fun `the shipped leaf chains to the shipped GAL root`() {         val factory = CertificateFactory.getInstance("X.509")@@ -61,26 +48,26 @@ class GalCredentialTest {          // Throws if the chain does not validate.         trust.checkClientTrusted(arrayOf(leaf, root), "RSA")-        assertEquals("CarService", leaf.subjectX500Principal.name.substringAfter("O=")-            .substringBefore(","))+        assertTrue(+            leaf.subjectX500Principal.name.contains("O=CarService"),+            "unexpected leaf subject ${leaf.subjectX500Principal}",+        )     }      @Test     fun `the engine is a server that demands a client certificate`() {-        val engine = GalCredential.serverEngine(context())+        val engine = GalCredential.serverEngine(TestTls.context())         assertEquals(false, engine.useClientMode, "the phone is the TLS server, not the client")         assertTrue(engine.needClientAuth, "the head unit must present a GAL-signed cert")     }      @Test     fun `a mutually authenticated handshake completes`() {-        val context = context()+        val context = TestTls.context()         val server = GalCredential.serverEngine(context)-        // A head unit presents its own GAL-signed certificate; we only have the one, which-        // is exactly what openauto does on the head-unit side.-        val client = context.createSSLEngine().apply { useClientMode = true }+        val car = TestTls.carEngine(context) -        handshake(server, client)+        TestTls.handshake(server, car)          assertEquals("TLSv1.2", server.session.protocol)         val peer = server.session.peerCertificates.first() as X509Certificate@@ -89,54 +76,4 @@ class GalCredentialTest {             "server should have authenticated the client, saw ${peer.subjectX500Principal}",         )     }--    /** Drives two engines against each other in memory until both report FINISHED. */-    private fun handshake(server: SSLEngine, client: SSLEngine) {-        server.beginHandshake()-        client.beginHandshake()--        val packetSize = maxOf(server.session.packetBufferSize, client.session.packetBufferSize)-        val appSize =-            maxOf(server.session.applicationBufferSize, client.session.applicationBufferSize)-        val empty = ByteBuffer.allocate(0)--        repeat(MAX_STEPS) {-            if (settled(server) && settled(client)) return-            var progressed = false-            for ((from, to) in listOf(client to server, server to client)) {-                runTasks(from)-                if (from.handshakeStatus != HandshakeStatus.NEED_WRAP) continue--                val wire = ByteBuffer.allocate(packetSize)-                val wrapped = from.wrap(empty, wire)-                assertEquals(Status.OK, wrapped.status, "wrap failed")-                wire.flip()-                progressed = true--                while (wire.hasRemaining()) {-                    runTasks(to)-                    val plain = ByteBuffer.allocate(appSize)-                    val unwrapped = to.unwrap(wire, plain)-                    assertEquals(Status.OK, unwrapped.status, "unwrap failed")-                    if (to.handshakeStatus == HandshakeStatus.NEED_WRAP) break-                }-            }-            if (!progressed) fail("handshake stalled: ${server.handshakeStatus} / ${client.handshakeStatus}")-        }-        fail("handshake did not settle within $MAX_STEPS steps")-    }--    private fun runTasks(engine: SSLEngine) {-        while (engine.handshakeStatus == HandshakeStatus.NEED_TASK) {-            engine.delegatedTask?.run() ?: break-        }-    }--    private fun settled(engine: SSLEngine) =-        engine.handshakeStatus == HandshakeStatus.NOT_HANDSHAKING ||-            engine.handshakeStatus == HandshakeStatus.FINISHED--    private companion object {-        const val MAX_STEPS = 50-    } }
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TestTls.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TestTls.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TestTls.ktnew file mode 100644index 0000000000..496a3640b2--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TestTls.kt@@ -0,0 +1,83 @@+package com.vayunmathur.auto.protocol++import java.io.File+import java.nio.ByteBuffer+import javax.net.ssl.SSLContext+import javax.net.ssl.SSLEngine+import javax.net.ssl.SSLEngineResult.HandshakeStatus+import javax.net.ssl.SSLEngineResult.Status+import kotlin.test.assertEquals+import kotlin.test.fail++/** Shared TLS scaffolding for the protocol tests. */+object TestTls {++    private val assetDir = File("src/main/assets/gal")++    /**+     * The credential exactly as shipped, read from `src/main/assets` rather than a test+     * copy, so these tests fail if the shipped files are wrong.+     */+    fun context(): SSLContext = GalCredential.create(+        certPem = File(assetDir, "client-cert.pem").readText(),+        keyPem = File(assetDir, "client-key.pem").readText(),+        rootPem = File(assetDir, "root.pem").readText(),+    )++    /**+     * A stand-in head unit: a TLS client presenting the same GAL-signed certificate, which+     * is what a real head unit does and what openauto does on that side.+     */+    fun carEngine(context: SSLContext): SSLEngine =+        context.createSSLEngine().apply { useClientMode = true }++    /** Drives two engines against each other in memory until both settle. */+    fun handshake(server: SSLEngine, client: SSLEngine) {+        server.beginHandshake()+        client.beginHandshake()++        val packetSize = maxOf(server.session.packetBufferSize, client.session.packetBufferSize)+        val appSize =+            maxOf(server.session.applicationBufferSize, client.session.applicationBufferSize)+        val empty = ByteBuffer.allocate(0)++        repeat(MAX_STEPS) {+            if (settled(server) && settled(client)) return+            var progressed = false+            for ((from, to) in listOf(client to server, server to client)) {+                runTasks(from)+                if (from.handshakeStatus != HandshakeStatus.NEED_WRAP) continue++                val wire = ByteBuffer.allocate(packetSize)+                val wrapped = from.wrap(empty, wire)+                assertEquals(Status.OK, wrapped.status, "wrap failed")+                wire.flip()+                progressed = true++                while (wire.hasRemaining()) {+                    runTasks(to)+                    val plain = ByteBuffer.allocate(appSize)+                    val unwrapped = to.unwrap(wire, plain)+                    assertEquals(Status.OK, unwrapped.status, "unwrap failed")+                    if (to.handshakeStatus == HandshakeStatus.NEED_WRAP) break+                }+            }+            if (!progressed) {+                fail("handshake stalled: ${server.handshakeStatus} / ${client.handshakeStatus}")+            }+        }+        fail("handshake did not settle within $MAX_STEPS steps")+    }++    private fun runTasks(engine: SSLEngine) {+        while (engine.handshakeStatus == HandshakeStatus.NEED_TASK) {+            engine.delegatedTask?.run() ?: break+        }+    }++    private fun settled(engine: SSLEngine) =+        engine.handshakeStatus == HandshakeStatus.NOT_HANDSHAKING ||+            engine.handshakeStatus == HandshakeStatus.FINISHED++    private const val MAX_STEPS = 50+}
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TlsCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TlsCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TlsCodecTest.ktnew file mode 100644index 0000000000..b5b658940e--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/TlsCodecTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.auto.protocol++import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class TlsCodecTest {++    private fun connected(): Pair<TlsCodec, TlsCodec> {+        val context = TestTls.context()+        val server = GalCredential.serverEngine(context)+        val car = TestTls.carEngine(context)+        TestTls.handshake(server, car)+        return TlsCodec(server) to TlsCodec(car)+    }++    @Test+    fun `application data survives phone to car`() {+        val (phone, car) = connected()+        val payload = Random(1).nextBytes(512)++        assertContentEquals(payload, car.unwrap(phone.wrap(payload)))+    }++    @Test+    fun `application data survives car to phone`() {+        val (phone, car) = connected()+        val payload = Random(2).nextBytes(512)++        assertContentEquals(payload, phone.unwrap(car.wrap(payload)))+    }++    @Test+    fun `wrapping actually encrypts`() {+        val (phone, _) = connected()+        // A recognisable plaintext that must not appear on the wire.+        val payload = "SERVICE_DISCOVERY".encodeToByteArray()++        val record = phone.wrap(payload)++        assertFalse(+            record.toList().windowed(payload.size).any { it == payload.toList() },+            "plaintext appeared in the TLS record",+        )+    }++    @Test+    fun `a full frame payload round-trips`() {+        // The largest plaintext a default frame carries. This is the case the 16128 fragment+        // size exists to keep inside the record buffer.+        val (phone, car) = connected()+        val payload = Random(3).nextBytes(+            FrameHeader.DEFAULT_MAX_FRAME_SIZE - FrameHeader.LONG_HEADER_SIZE,+        )++        assertContentEquals(payload, car.unwrap(phone.wrap(payload)))+    }++    @Test+    fun `an empty payload round-trips`() {+        val (phone, car) = connected()+        assertContentEquals(ByteArray(0), car.unwrap(phone.wrap(ByteArray(0))))+    }++    @Test+    fun `successive records stay in step`() {+        // TLS is stateful: records must be unwrapped in the order they were wrapped.+        val (phone, car) = connected()+        val payloads = (1..5).map { Random(it).nextBytes(100 * it) }++        val records = payloads.map { phone.wrap(it) }+        val decoded = records.map { car.unwrap(it) }++        payloads.zip(decoded).forEach { (sent, received) ->+            assertContentEquals(sent, received)+        }+    }++    @Test+    fun `the codec drives real frames end to end`() {+        val (phone, car) = connected()+        val writer = FrameWriter(encrypt = phone::wrap)+        val reader = FrameReader(decrypt = car::unwrap)+        val body = Random(9).nextBytes(40_000)++        val collected = writer+            .frame(GalService.VIDEO_SINK.id, body, encrypted = true)+            .flatMap { reader.offer(it) }++        assertTrue(collected.size == 1, "expected one reassembled message")+        assertContentEquals(body, collected.single().payload)+    }+}