Modern Apps git

← Modern-Apps.git

communicate: MSRP-over-TLS with SDP fingerprint negotiation

Commit
50ab3c35c13cb514e5682888061c6a42129bf50d
Author
vayun-mathur <[email protected]>
When
2026-09-26 21:00 UTC (2 months ago)
Parents
251d2da

Diff

communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.ktindex cd4659bc50..01e8c9be0e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrp.kt@@ -89,13 +89,6 @@ object RcsMsrp {         internal fun isClosed(): Boolean = closed || socket.isClosed     } -    /**-     * Wrap an accepted (passive-side) socket as a session connection: the-     * listener already consumed the first SEND head ([head]) for To-Path-     * routing, so the reader replays it before the live stream. [localPath]-     * is our advertised path (matches the peer's To-Path); [remotePath] is-     * the peer's From-Path, used for our SENDs back on this same socket.-     */     /**      * Wrap an accepted (passive-side) socket as a session connection: the      * listener already consumed the first SEND head ([head]) for To-Path@@ -103,6 +96,8 @@ object RcsMsrp {      * is our advertised path (matches the peer's To-Path); [remotePath] is      * the peer's From-Path, used for our SENDs back on this same socket      * (RFC 4975 §5.4 — the passive side reuses the accepted connection).+     * [socket] may already be a TLS `SSLSocket` (secure sessions) — the+     * reader only needs the byte stream.      */     fun wrapAccepted(         socket: java.net.Socket,@@ -148,7 +143,22 @@ object RcsMsrp {         val localPath = session.msrpLocalPath ?: "msrp://local.invalid/${UUID.randomUUID()};tcp"         runCatching {             val (host, port) = parseMsrpPath(remotePath) ?: return@runCatching null-            val socket = RcsImsNetwork.createSocket(context, host, port) ?: return@runCatching null+            val socket = if (session.msrpSecure) {+                // TLS client: pin the peer against the fingerprint from its+                // SDP answer (stashed at response time — see session lookup).+                // Falls back to plaintext connect when no fingerprint is+                // known (downgrade, never a hard failure here).+                val peerFp = peerFingerprintFor(session)+                if (peerFp != null) {+                    RcsMsrpTls.clientSocket(context, host, port, peerFp)+                        ?: return@runCatching null+                } else {+                    Log.w(TAG, "Secure session without peer fingerprint; downgrading to plaintext")+                    RcsImsNetwork.createSocket(context, host, port) ?: return@runCatching null+                }+            } else {+                RcsImsNetwork.createSocket(context, host, port) ?: return@runCatching null+            }             val conn = MsrpConnection(socket, localPath, remotePath)             // Reader loop: parse SEND chunks, auto-200 them, deliver bodies.             // Owned by the connection; dies on close.@@ -160,6 +170,13 @@ object RcsMsrp {         }     } +    /**+     * Peer's TLS fingerprint for an outgoing secure session, from the SDP+     * answer stashed at response time. Null when unknown (caller downgrades).+     */+    private fun peerFingerprintFor(session: RcsSession): String? =+        RcsSessionManager.peerFingerprint(session.callId)+     private fun readLoop(         conn: MsrpConnection,         socket: java.net.Socket,@@ -316,7 +333,8 @@ object RcsMsrp {     /**      * Send [payload] (CPIM bytes) over an MSRP session bound to [session].      * Opens a TCP socket to the remote path when needed (IMS PDN preferred,-     * see [connect]). Returns true on a 200 response to our SEND.+     * see [connect]; TLS when [RcsSession.msrpSecure]). Returns true on a+     * 200 response to our SEND.      *      * One-shot fallback; prefer [connect] for established sessions.      */@@ -343,8 +361,14 @@ object RcsMsrp {                 append("Success-Report: no\r\n")                 append("Content-Type: $contentType\r\n")             }-            val socket = RcsImsNetwork.createSocket(context, host, port)-                ?: return@runCatching false+            val socket = if (session.msrpSecure) {+                val peerFp = peerFingerprintFor(session) ?: return@runCatching false+                RcsMsrpTls.clientSocket(context, host, port, peerFp)+                    ?: return@runCatching false+            } else {+                RcsImsNetwork.createSocket(context, host, port)+                    ?: return@runCatching false+            }             socket.use { s ->                 val out = s.getOutputStream()                 out.write(chunk.toByteArray(Charsets.UTF_8))@@ -363,8 +387,9 @@ object RcsMsrp {     }      /**-     * Parse an `msrp://host[:port]/...` path into (host, port). Default MSRP-     * port 2855 when absent.+     * Parse an `msrp(s)://host[:port]/...` path into (host, port). Default+     * MSRP port 2855 when absent. Scheme-agnostic (covers `msrps://`); use+     * [isSecurePath] for the TLS decision.      */     fun parseMsrpPath(path: String): Pair<String, Int>? {         return runCatching {@@ -374,4 +399,11 @@ object RcsMsrp {             host to port         }.getOrNull()     }++    /** True when [path] uses the `msrps://` scheme (TLS media, RFC 4976). */+    fun isSecurePath(path: String?): Boolean {+        if (path.isNullOrBlank()) return false+        return runCatching { android.net.Uri.parse(path).scheme }.getOrNull()+            .equals("msrps", ignoreCase = true)+    } }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.ktindex b42ab1c15c..dd210c7c3c 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpListen.kt@@ -48,11 +48,19 @@ object RcsMsrpListen {     private var listen: RcsImsNetwork.ListenSocket? = null      /**-     * Pending listen paths: our advertised `a=path` → conversation id, for+     * Pending listen paths: our advertised `a=path` → listen target, for      * routing accepted sockets to sessions. Entries are consumed on first      * match; stale entries are dropped by [stop] / session teardown.      */-    private val pendingPaths = java.util.concurrent.ConcurrentHashMap<String, String>()+    private data class PendingListen(+        val conversationId: String,+        /** True when the session negotiated TLS (accept must handshake). */+        val secure: Boolean,+        /** Peer's SDP fingerprint when known (verified at accept). */+        var peerFingerprint: String? = null,+    )++    private val pendingPaths = java.util.concurrent.ConcurrentHashMap<String, PendingListen>()      /** True when a listen socket is currently bound. */     fun isListening(): Boolean =@@ -80,6 +88,7 @@ object RcsMsrpListen {         if (isListening()) return@withContext true         val bound = RcsImsNetwork.listenSocket(context) ?: return@withContext false         listen = bound+        appContext = context.applicationContext         Log.i(TAG, "Listening on ${bound.localIp}:${bound.localPort}")         scope.launch { acceptLoop(bound, onAccepted) }         true@@ -90,29 +99,47 @@ object RcsMsrpListen {      * value to put in our SDP offer/answer, binding the listen socket first      * when needed. Null when listening is unavailable (caller falls back to      * active-only offers).+     *+     * [secure] marks a TLS session (accept must TLS-handshake);+     * [peerFingerprint] pins the peer when already known (incoming offers).+     * For outgoing offers the peer fingerprint arrives with the SDP answer —+     * record it via [notePeerFingerprint].      */     suspend fun advertisePath(         context: Context,         conversationId: String,+        secure: Boolean = false,+        peerFingerprint: String? = null,         onAccepted: (String, java.net.Socket, AcceptedHead) -> Unit,     ): String? = withContext(Dispatchers.IO) {         if (!RcsFeature.enabled) return@withContext null         if (!ensureListening(context, onAccepted)) return@withContext null         val bound = listen ?: return@withContext null         val path = bound.msrpPath("sess-${UUID.randomUUID().toString().take(8)}")-        pendingPaths[path] = conversationId+        pendingPaths[path] = PendingListen(conversationId, secure, peerFingerprint)         path     } +    /**+     * Record the peer's SDP fingerprint for a pending listen path (arrives+     * with the SDP answer to our outgoing offer). Best-effort no-op when no+     * path is pending.+     */+    fun notePeerFingerprint(conversationId: String, fingerprint: String) {+        pendingPaths.values.firstOrNull { it.conversationId == conversationId }+            ?.let { it.peerFingerprint = fingerprint }+    }+     /** Drop the pending path for [conversationId] (session torn down). */     fun dropPending(conversationId: String) {-        pendingPaths.entries.removeIf { it.value == conversationId }+        pendingPaths.entries.removeIf { it.value.conversationId == conversationId }     }      /** Close the listen socket + accept loop; drop pending paths. */     fun stop() {         runCatching { listen?.close() }         listen = null+        appContext = null         pendingPaths.clear()     } @@ -143,62 +170,213 @@ object RcsMsrpListen {     }      /**-     * Route one accepted socket: read the first SEND's To-Path, match it-     * against pending listen paths, hand the socket + head to the session.-     * Closes unmatched/failed sockets with a 481 when the framing allows.+     * Route one accepted socket.+     *+     * TLS detection comes first: a TLS ClientHello record starts with 0x16,+     * while plaintext MSRP starts with 'M'. Exactly one byte is peeked (then+     * replayed), so:+     * - 0x16 → TLS server handshake first, then the first SEND is read from+     *   the decrypted stream and matched — the matched pending path must be+     *   a secure one, and the peer fingerprint is verified when known.+     * - otherwise → plaintext head peek as before; the matched path must be+     *   a plaintext one (a peer skipping TLS on a secure path is rejected).+     *+     * Unmatched/failed sockets get a 481 when the framing allows, then close.      */-    private fun routeAccepted(+    private suspend fun routeAccepted(         socket: java.net.Socket,         onAccepted: (String, java.net.Socket, AcceptedHead) -> Unit,     ) {         runCatching {             socket.soTimeout = 15_000-            val input = socket.getInputStream().bufferedReader(Charsets.UTF_8)-            // Peek the first MSRP request head (bounded: 32 lines max).-            val headLines = mutableListOf<String>()-            var line = runCatching { input.readLine() }.getOrNull()-            var guard = 0-            while (line != null && line.isNotEmpty() && guard++ < 32) {-                headLines.add(line)-                line = runCatching { input.readLine() }.getOrNull()-            }-            if (line == null && headLines.isEmpty()) {+            val raw = socket.getInputStream()+            val firstByte = raw.read()+            if (firstByte < 0) {                 runCatching { socket.close() }                 return             }-            val first = headLines.firstOrNull() ?: run {-                runCatching { socket.close() }+            if (firstByte == 0x16) {+                routeTls(socket, raw, firstByte, onAccepted)                 return             }-            if (!first.startsWith("MSRP ")) {-                runCatching { socket.close() }-                return-            }-            val toPath = headLines.firstOrNull { it.startsWith("To-Path:", ignoreCase = true) }-                ?.substringAfter(":")?.trim()-            val conversationId = toPath?.let { pendingPaths.remove(it) }-            if (conversationId == null) {-                // Unknown path: 481 per RFC 4975 §7.1, then close.-                val txid = first.split(" ").getOrNull(1).orEmpty()-                if (txid.isNotEmpty()) {-                    runCatching {-                        val out = socket.getOutputStream()-                        out.write("MSRP $txid 481 Session Does Not Exist\r\n".toByteArray(Charsets.UTF_8))-                        out.write("To-Path: $toPath\r\n\r\n".toByteArray(Charsets.UTF_8))-                        out.write("-------$txid\$\r\n".toByteArray(Charsets.UTF_8))-                        out.flush()-                    }-                }-                runCatching { socket.close() }-                Log.w(TAG, "Rejected inbound MSRP for unknown path $toPath")-                return-            }-            // Matched: hand over the live socket + consumed head for replay.-            socket.soTimeout = 0-            onAccepted(conversationId, socket, AcceptedHead(headLines))+            val input = java.io.SequenceInputStream(+                java.io.ByteArrayInputStream(byteArrayOf(firstByte.toByte())),+                raw,+            ).bufferedReader(Charsets.UTF_8)+            routePlain(socket, input, onAccepted)         }.onFailure {             Log.w(TAG, "Accept routing failed", it)             runCatching { socket.close() }         }     }++    /** Plaintext branch: peek the first SEND head, match To-Path, hand over. */+    private fun routePlain(+        socket: java.net.Socket,+        input: java.io.BufferedReader,+        onAccepted: (String, java.net.Socket, AcceptedHead) -> Unit,+    ) {+        // Peek the first MSRP request head (bounded: 32 lines max).+        val headLines = mutableListOf<String>()+        var line = runCatching { input.readLine() }.getOrNull()+        var guard = 0+        while (line != null && line.isNotEmpty() && guard++ < 32) {+            headLines.add(line)+            line = runCatching { input.readLine() }.getOrNull()+        }+        if (line == null && headLines.isEmpty()) {+            runCatching { socket.close() }+            return+        }+        val first = headLines.firstOrNull() ?: run {+            runCatching { socket.close() }+            return+        }+        if (!first.startsWith("MSRP ")) {+            runCatching { socket.close() }+            return+        }+        val toPath = headLines.firstOrNull { it.startsWith("To-Path:", ignoreCase = true) }+            ?.substringAfter(":")?.trim()+        val pending = toPath?.let { pendingPaths.remove(it) }+        if (pending == null) {+            send481(socket, first, toPath)+            runCatching { socket.close() }+            Log.w(TAG, "Rejected inbound MSRP for unknown path $toPath")+            return+        }+        if (pending.secure) {+            // Peer skipped TLS on a secure path — reject, don't downgrade+            // silently (downgrade negotiation belongs in SDP, not here).+            Log.w(TAG, "Rejected plaintext SEND on secure path $toPath")+            runCatching { socket.close() }+            return+        }+        // Matched: hand over the live socket + consumed head for replay+        // (the live stream already consumed through the blank line, so the+        // reader replays the full head ahead of it).+        socket.soTimeout = 0+        onAccepted(pending.conversationId, socket, AcceptedHead(headLines))+    }++    /**+     * TLS branch: complete the server handshake over [tcp] (whose first+     * ClientHello byte was consumed into [consumed]), then read + match the+     * first SEND from the decrypted stream. The matched path must be secure;+     * the peer fingerprint is verified when known.+     */+    private suspend fun routeTls(+        tcp: java.net.Socket,+        raw: java.io.InputStream,+        consumed: Int,+        onAccepted: (String, java.net.Socket, AcceptedHead) -> Unit,+    ) {+        // Rebuild the full stream: consumed byte + remainder, then handshake.+        val replayed = java.io.SequenceInputStream(+            java.io.ByteArrayInputStream(byteArrayOf(consumed.toByte())),+            raw,+        )+        // Temporarily swap the socket's input for the handshake: SSLSocket+        // wraps the TCP socket directly, so feed it a stream that starts+        // with the consumed byte. Achieve this by layering TLS over a+        // delegating socket whose getInputStream returns the replayed bytes.+        val peekSocket = object : java.net.Socket() {+            override fun getInputStream(): java.io.InputStream = replayed+            override fun getOutputStream(): java.io.OutputStream = tcp.getOutputStream()+            override fun getInetAddress(): java.net.InetAddress? = tcp.inetAddress+            override fun getPort(): Int = tcp.port+            override fun close() = tcp.close()+            override fun isClosed(): Boolean = tcp.isClosed+            override fun isConnected(): Boolean = tcp.isConnected+        }+        val ssl = acceptTls(peekSocket) ?: run {+            runCatching { tcp.close() }+            Log.w(TAG, "TLS accept failed")+            return+        }+        // Handshake done — now read the first SEND head from TLS plaintext.+        val input = ssl.getInputStream().bufferedReader(Charsets.UTF_8)+        val headLines = mutableListOf<String>()+        var line = runCatching { input.readLine() }.getOrNull()+        var guard = 0+        while (line != null && line.isNotEmpty() && guard++ < 32) {+            headLines.add(line)+            line = runCatching { input.readLine() }.getOrNull()+        }+        val first = headLines.firstOrNull()+        if (first == null || !first.startsWith("MSRP ")) {+            runCatching { ssl.close() }+            return+        }+        val toPath = headLines.firstOrNull { it.startsWith("To-Path:", ignoreCase = true) }+            ?.substringAfter(":")?.trim()+        val pending = toPath?.let { pendingPaths.remove(it) }+        if (pending == null) {+            send481(ssl, first, toPath)+            runCatching { ssl.close() }+            Log.w(TAG, "Rejected inbound MSRP-TLS for unknown path $toPath")+            return+        }+        if (!pending.secure) {+            // Peer did TLS on a plaintext path: accept the media anyway (TLS+            // is strictly stronger; the SDP answer just didn't advertise it).+            Log.i(TAG, "Peer used TLS on plaintext path $toPath — accepting")+        }+        if (!RcsMsrpTls.verifyServerSide(ssl, pending.peerFingerprint)) {+            Log.w(TAG, "TLS peer fingerprint mismatch for ${pending.conversationId}")+            runCatching { ssl.close() }+            return+        }+        ssl.soTimeout = 0+        onAccepted(pending.conversationId, ssl, AcceptedHead(headLines))+    }++    /** 481 Session Does Not Exist, per RFC 4975 §7.1. */+    private fun send481(socket: java.net.Socket, firstLine: String, toPath: String?) {+        val txid = firstLine.split(" ").getOrNull(1).orEmpty()+        if (txid.isEmpty()) return+        runCatching {+            val out = socket.getOutputStream()+            out.write("MSRP $txid 481 Session Does Not Exist\r\n".toByteArray(Charsets.UTF_8))+            out.write("To-Path: $toPath\r\n\r\n".toByteArray(Charsets.UTF_8))+            out.write("-------$txid\$\r\n".toByteArray(Charsets.UTF_8))+            out.flush()+        }+    }++    /**+     * TLS server handshake over an accepted [tcp] socket: present our cert,+     * request the peer's. Returns the established `SSLSocket`, or null on+     * handshake failure. Fingerprint verification happens in [routeTls]+     * after To-Path matching (the expected value is per-session).+     */+    private suspend fun acceptTls(+        tcp: java.net.Socket,+    ): javax.net.ssl.SSLSocket? = withContext(Dispatchers.IO) {+        val app = appContext ?: return@withContext null+        val sslContext = RcsMsrpTls.serverContext(app) ?: return@withContext null+        runCatching {+            val ssl = sslContext.socketFactory.createSocket(+                tcp,+                tcp.inetAddress?.hostAddress,+                tcp.port,+                true,+            ) as javax.net.ssl.SSLSocket+            ssl.useClientMode = false+            ssl.wantClientAuth = true+            ssl.soTimeout = 15_000+            ssl.startHandshake()+            ssl.soTimeout = 0+            Log.i(TAG, "TLS accept established")+            ssl+        }.getOrElse {+            Log.w(TAG, "TLS accept handshake failed", it)+            runCatching { tcp.close() }+            null+        }+    }++    /** App context for the TLS server context (set by ensureListening). */+    @Volatile+    private var appContext: Context? = null }
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.ktnew file mode 100644index 0000000000..96834c250e--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsMsrpTls.kt@@ -0,0 +1,391 @@+package com.vayunmathur.communicate.data.rcs++import android.content.Context+import android.util.Log+import java.io.File+import java.net.InetSocketAddress+import java.net.Socket+import java.security.KeyFactory+import java.security.KeyPairGenerator+import java.security.MessageDigest+import java.security.PrivateKey+import java.security.SecureRandom+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import java.security.spec.PKCS8EncodedKeySpec+import javax.net.ssl.KeyManagerFactory+import javax.net.ssl.SSLContext+import javax.net.ssl.SSLSocket+import javax.net.ssl.TrustManager+import javax.net.ssl.X509TrustManager+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * MSRP-over-TLS identity + socket layer (RFC 4976, RFC 4572).+ *+ * UP transports negotiate `TCP/TLS/MSRP` (`msrps://` paths) with certificate+ * fingerprints in SDP (`a=fingerprint:SHA-256 <hex>`). There is no PKI on the+ * IMS PDN — both ends use self-signed certs and verify the peer against the+ * fingerprint from its SDP (RFC 4572 §5, RFC 4976 §3.1). This object owns:+ *+ * - Identity: one EC P-256 keypair + self-signed cert, generated once via+ *   the platform `KeyPairGenerator` and persisted as raw DER in a private+ *   app file (no KeyStore dance, no new dependency — the X.509 writer below+ *   is a minimal hand-rolled DER encoder for exactly this shape).+ * - Client: TLS over the IMS-PDN TCP socket ([RcsImsNetwork.createSocket]),+ *   verifying the peer cert fingerprint against the SDP-advertised value.+ * - Server: `SSLContext` with our cert for the listen side; client certs are+ *   requested and verified when the expected peer fingerprint is known+ *   (from their offer SDP), accepted-unverified otherwise (the MSRP layer+ *   still routes by To-Path, and chat payloads are MLS-encrypted anyway).+ *+ * Every entry point early-returns null when the dev gate is off and never+ * throws; callers fall back to plaintext `msrp://` (downgrade) or fail the+ * session per their policy.+ */+object RcsMsrpTls {+    private const val TAG = "RcsMsrpTls"++    /** Fingerprint hash named in SDP (RFC 4572 §5: `SHA-256`, uppercase). */+    const val FINGERPRINT_HASH = "SHA-256"++    private const val IDENTITY_DIR = "rcs-msrp-tls"+    private const val CERT_FILE = "identity.der"+    private const val KEY_FILE = "identity.pk8"++    /** Our TLS identity: DER cert bytes + fingerprint + key. */+    data class Identity(+        val certDer: ByteArray,+        val fingerprint: String,+        internal val privateKey: PrivateKey,+    ) {+        /** `a=fingerprint:SHA-256 <FP>` SDP line for offers/answers. */+        fun sdpLine(): String = "a=fingerprint:$FINGERPRINT_HASH $fingerprint"++        override fun equals(other: Any?): Boolean {+            if (this === other) return true+            if (other !is Identity) return false+            return fingerprint == other.fingerprint && certDer.contentEquals(other.certDer)+        }++        override fun hashCode(): Int = fingerprint.hashCode()+    }++    @Volatile+    private var cached: Identity? = null++    /**+     * Load-or-generate our TLS identity. Suspends on Dispatchers.IO (key+     * generation blocks). Null when the gate is off or generation failed —+     * callers offer plaintext `msrp://` instead.+     */+    suspend fun ensureIdentity(context: Context): Identity? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled) return@withContext null+        cached?.let { return@withContext it }+        runCatching {+            val dir = File(context.filesDir, IDENTITY_DIR).apply { mkdirs() }+            val certFile = File(dir, CERT_FILE)+            val keyFile = File(dir, KEY_FILE)+            if (certFile.exists() && keyFile.exists()) {+                loadIdentity(certFile.readBytes(), keyFile.readBytes())?.let {+                    cached = it+                    return@runCatching it+                }+            }+            val fresh = generateIdentity() ?: return@runCatching null+            certFile.writeBytes(fresh.certDer)+            keyFile.writeBytes(fresh.privateKey.encoded)+            cached = fresh+            fresh+        }.getOrElse {+            Log.w(TAG, "TLS identity unavailable", it)+            null+        }+    }++    /**+     * TLS client socket to [host]:[port]: TCP via the IMS PDN, then TLS with+     * SNI-less handshake, verifying the peer cert fingerprint against+     * [expectedFingerprint] (RFC 4572 format, case-insensitive). Null when+     * the TCP leg, handshake, or fingerprint check fails.+     */+    suspend fun clientSocket(+        context: Context,+        host: String,+        port: Int,+        expectedFingerprint: String?,+        connectTimeoutMs: Int = 10_000,+    ): SSLSocket? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled) return@withContext null+        if (expectedFingerprint.isNullOrBlank()) {+            Log.w(TAG, "No peer fingerprint — refusing TLS without pinning")+            return@withContext null+        }+        val identity = ensureIdentity(context) ?: return@withContext null+        val tcp = RcsImsNetwork.createSocket(context, host, port, connectTimeoutMs)+            ?: return@withContext null+        runCatching {+            val ssl = clientContext(identity).socketFactory+                .createSocket(tcp, host, port, true) as SSLSocket+            ssl.soTimeout = 0+            ssl.startHandshake()+            val peerCert = ssl.session.peerCertificates+                .firstOrNull() as? X509Certificate+                ?: throw javax.net.ssl.SSLPeerUnverifiedException("No peer cert")+            val actual = fingerprintOf(peerCert.encoded)+            if (!actual.equals(expectedFingerprint.trim(), ignoreCase = true)) {+                throw javax.net.ssl.SSLPeerUnverifiedException(+                    "MSRP fingerprint mismatch (SNI-less DANE-less pinning)",+                )+            }+            Log.i(TAG, "TLS client established to $host:$port (pinned)")+            ssl+        }.getOrElse {+            Log.w(TAG, "TLS client handshake failed", it)+            runCatching { tcp.close() }+            null+        }+    }++    /**+     * Server `SSLContext` presenting our cert for the listen side. Client+     * certs are requested (not required); verification against the expected+     * peer fingerprint happens per-socket in [verifyServerSide] because the+     * expected value is per-session, not per-context.+     */+    suspend fun serverContext(context: Context): SSLContext? = withContext(Dispatchers.IO) {+        if (!RcsFeature.enabled) return@withContext null+        val identity = ensureIdentity(context) ?: return@withContext null+        runCatching {+            val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())+            val ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType())+            ks.load(null, null)+            val cf = CertificateFactory.getInstance("X.509")+            val cert = cf.generateCertificate(identity.certDer.inputStream())+            ks.setKeyEntry("msrp", identity.privateKey, CharArray(0), arrayOf(cert))+            kmf.init(ks, CharArray(0))+            SSLContext.getInstance("TLS").apply {+                // Trust-all client certs at the TLS layer; per-session pinning+                // in verifyServerSide decides.+                init(kmf.keyManagers, arrayOf<TrustManager>(PermissiveTrustManager), SecureRandom())+            }+        }.getOrElse {+            Log.w(TAG, "TLS server context failed", it)+            null+        }+    }++    /**+     * Verify a server-side (accepted) socket's peer cert against+     * [expectedFingerprint]. True when it matches, or when [expectedFingerprint]+     * is blank (offer carried no fingerprint — accept unverified, matching the+     * plaintext-era behavior for non-TLS peers). False on mismatch.+     */+    fun verifyServerSide(socket: SSLSocket, expectedFingerprint: String?): Boolean {+        if (expectedFingerprint.isNullOrBlank()) return true+        return runCatching {+            val peerCert = socket.session.peerCertificates+                .firstOrNull() as? X509Certificate ?: return false+            fingerprintOf(peerCert.encoded)+                .equals(expectedFingerprint.trim(), ignoreCase = true)+        }.getOrDefault(false)+    }++    /** Parse an SDP `a=fingerprint:` line into (hash, value), or null. */+    fun parseFingerprint(sdp: String?): Pair<String, String>? {+        if (sdp.isNullOrBlank()) return null+        val m = Regex(+            "a=fingerprint:(\\S+)\\s+([0-9A-Fa-f:]+)",+            RegexOption.IGNORE_CASE,+        ).find(sdp) ?: return null+        val (hash, value) = m.destructured+        if (value.isBlank()) return null+        return hash to value.trim()+    }++    /** RFC 4572 fingerprint: uppercase colon-hex SHA-256 of the DER cert. */+    internal fun fingerprintOf(certDer: ByteArray): String {+        val digest = MessageDigest.getInstance("SHA-256").digest(certDer)+        return digest.joinToString(":") { "%02X".format(it) }+    }++    private fun loadIdentity(certDer: ByteArray, keyPkcs8: ByteArray): Identity? {+        return runCatching {+            val kf = KeyFactory.getInstance("EC")+            val key = kf.generatePrivate(PKCS8EncodedKeySpec(keyPkcs8))+            Identity(certDer, fingerprintOf(certDer), key)+        }.getOrNull()+    }++    private fun clientContext(identity: Identity): SSLContext {+        val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())+        val ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType())+        ks.load(null, null)+        val cf = CertificateFactory.getInstance("X.509")+        val cert = cf.generateCertificate(identity.certDer.inputStream())+        ks.setKeyEntry("msrp", identity.privateKey, CharArray(0), arrayOf(cert))+        kmf.init(ks, CharArray(0))+        return SSLContext.getInstance("TLS").apply {+            init(kmf.keyManagers, arrayOf<TrustManager>(PermissiveTrustManager), SecureRandom())+        }+    }++    private object PermissiveTrustManager : X509TrustManager {+        override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit+        override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit+        override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()+    }++    // -- Minimal X.509 writer (self-signed EC P-256, SHA256withECDSA) --++    private fun generateIdentity(): Identity? {+        return runCatching {+            val kpg = KeyPairGenerator.getInstance("EC")+            kpg.initialize(java.security.spec.ECGenParameterSpec("secp256r1"), SecureRandom())+            val kp = kpg.generateKeyPair()+            val now = System.currentTimeMillis()+            val certDer = selfSignedCert(+                publicKey = kp.public.encoded,+                privateKey = kp.private,+                notBeforeMs = now - 24 * 3600 * 1000L,+                notAfterMs = now + 10L * 365 * 24 * 3600 * 1000,+                // IMS-PDN IPs change across attaches; a stable pseudonymous CN+                // is honest (RFC 4572 identity comes from the fingerprint,+                // not the subject).+                commonName = "rcs-msrp-tls",+            )+            Identity(certDer, fingerprintOf(certDer), kp.private)+        }.getOrElse {+            Log.w(TAG, "TLS identity generation failed", it)+            null+        }+    }++    /**+     * Build a v3 self-signed cert DER for [publicKey] (X.509 SubjectPublicKeyInfo+     * DER), signed by [privateKey] (EC). Minimal encoder: SEQUENCE-heavy,+     * length-prefixed — sized for this exact shape (no extensions).+     */+    internal fun selfSignedCert(+        publicKey: ByteArray,+        privateKey: PrivateKey,+        notBeforeMs: Long,+        notAfterMs: Long,+        commonName: String,+    ): ByteArray {+        // 1.2.840.10045.4.3.2 = ecdsa-with-SHA256.+        val sigAlgId = Der.sequence(+            Der.oid("1.2.840.10045.4.3.2"),+            Der.nullValue(),+        )+        val name = Der.sequence(+            Der.set(+                Der.sequence(+                    // 2.5.4.3 = commonName.+                    Der.oid("2.5.4.3"),+                    Der.utf8String(commonName),+                ),+            ),+        )+        val serial = ByteArray(9).also { SecureRandom().nextBytes(it); it[0] = (it[0].toInt() and 0x7F).toByte() }+        val tbs = Der.sequence(+            Der.explicit(0, Der.integer(serial)),+            Der.integer(byteArrayOf(2)), // v3+            sigAlgId,+            name, // issuer+            Der.sequence(Der.utcTime(notBeforeMs), Der.utcTime(notAfterMs)),+            name, // subject+            Der.raw(publicKey), // SubjectPublicKeyInfo DER, embedded as-is+        )+        val signature = Der.ecdsaSign(tbs, privateKey)+        return Der.sequence(tbs, sigAlgId, Der.bitString(signature))+    }++    /** Minimal DER primitives for the cert writer above. */+    internal object Der {+        fun sequence(vararg parts: ByteArray): ByteArray =+            byteArrayOf(0x30) + lengthPrefix(parts.sumOf { it.size }) + parts.reduce { a, b -> a + b }++        fun set(vararg parts: ByteArray): ByteArray =+            byteArrayOf(0x31) + lengthPrefix(parts.sumOf { it.size }) + parts.reduce { a, b -> a + b }++        fun explicit(tag: Int, content: ByteArray): ByteArray =+            byteArrayOf((0xA0 + tag).toByte()) + lengthPrefix(content.size) + content++        fun integer(bytes: ByteArray): ByteArray {+            var start = 0+            while (start < bytes.size - 1 && bytes[start] == 0.toByte()) start+++            var v = bytes.copyOfRange(start, bytes.size)+            if (v[0].toInt() and 0x80 != 0) v = byteArrayOf(0) + v+            return byteArrayOf(0x02) + lengthPrefix(v.size) + v+        }++        fun oid(dotted: String): ByteArray {+            val arcs = dotted.split(".").map { it.toInt() }+            val first = byteArrayOf(((arcs[0] * 40 + arcs[1]).toByte()))+            val rest = arcs.drop(2).fold(byteArrayOf()) { acc, a -> acc + base128(a) }+            val body = first + rest+            return byteArrayOf(0x06) + lengthPrefix(body.size) + body+        }++        fun nullValue(): ByteArray = byteArrayOf(0x05, 0x00)++        fun utf8String(s: String): ByteArray {+            val b = s.toByteArray(Charsets.UTF_8)+            return byteArrayOf(0x0C) + lengthPrefix(b.size) + b+        }++        fun utcTime(ms: Long): ByteArray {+            val cal = java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"))+            cal.timeInMillis = ms+            val str = "%02d%02d%02d%02d%02d%02dZ".format(+                cal.get(java.util.Calendar.YEAR) % 100,+                cal.get(java.util.Calendar.MONTH) + 1,+                cal.get(java.util.Calendar.DAY_OF_MONTH),+                cal.get(java.util.Calendar.HOUR_OF_DAY),+                cal.get(java.util.Calendar.MINUTE),+                cal.get(java.util.Calendar.SECOND),+            ).toByteArray(Charsets.US_ASCII)+            return byteArrayOf(0x17) + lengthPrefix(str.size) + str+        }++        fun bitString(signatureDer: ByteArray): ByteArray =+            byteArrayOf(0x03) + lengthPrefix(signatureDer.size + 1) + byteArrayOf(0x00) + signatureDer++        /** Embed already-encoded DER without re-wrapping. */+        fun raw(der: ByteArray): ByteArray = der++        fun ecdsaSign(tbs: ByteArray, key: PrivateKey): ByteArray {+            val sig = java.security.Signature.getInstance("SHA256withECDSA")+            sig.initSign(key, SecureRandom())+            sig.update(tbs)+            return sig.sign() // DER SEQUENCE { r, s } — exactly what BIT STRING holds+        }++        private fun lengthPrefix(n: Int): ByteArray = when {+            n < 128 -> byteArrayOf(n.toByte())+            else -> {+                var v = n+                val bytes = mutableListOf<Byte>()+                while (v > 0) {+                    bytes.add(0, (v and 0xFF).toByte())+                    v = v ushr 8+                }+                byteArrayOf((0x80 + bytes.size).toByte()) + bytes.toByteArray()+            }+        }++        private fun base128(v: Int): ByteArray {+            if (v == 0) return byteArrayOf(0)+            var x = v+            val out = mutableListOf<Byte>()+            while (x > 0) {+                out.add(0, (x and 0x7F).toByte())+                x = x ushr 7+            }+            for (i in 0 until out.size - 1) out[i] = (out[i].toInt() or 0x80).toByte()+            return out.toByteArray()+        }+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.ktindex c97df4f270..1e482fc81e 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSession.kt@@ -38,6 +38,12 @@ data class RcsSession(      * nulled (pager-mode fallback). Null = absent, treated as passive.      */     val msrpSetup: MsrpSetup? = null,+    /**+     * True when this session's MSRP media runs over TLS (`msrps://`,+     * RFC 4976). Negotiated from the SDP (`TCP/TLS/MSRP` or `a=fingerprint`+     * on either side); plaintext otherwise. Both socket directions honor it.+     */+    val msrpSecure: Boolean = false,     val createdAt: Long = System.currentTimeMillis(), ) 
communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.ktindex 2ac9684870..fe1c2da521 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/rcs/RcsSessionManager.kt@@ -52,9 +52,14 @@ object RcsSessionManager {         val callId = "${UUID.randomUUID()}@rcs"         val localTag = UUID.randomUUID().toString().take(8)         val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"-        val listenPath = listenPathFor(conversationId)+        val tlsFingerprint = tlsFingerprintFor()+        val secureOffer = tlsFingerprint != null+        val listenPath = listenPathFor(conversationId, secureOffer)         val (startLine, headers, content) =-            buildInvite(remoteTelUri, callId, localTag, branch, conversationId, listenPath = listenPath)+            buildInvite(+                remoteTelUri, callId, localTag, branch, conversationId,+                listenPath = listenPath, tlsFingerprint = tlsFingerprint,+            )         val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)         if (!ok) return null         val dialogId = "$callId:$localTag"@@ -66,6 +71,7 @@ object RcsSessionManager {             remoteTag = "",             remoteUri = remoteTelUri,             conversationId = conversationId,+            msrpSecure = secureOffer,         ))         return dialogId     }@@ -84,9 +90,13 @@ object RcsSessionManager {         val callId = "${UUID.randomUUID()}@rcs"         val localTag = UUID.randomUUID().toString().take(8)         val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"-        val listenPath = listenPathFor(conversationId)+        val tlsFingerprint = tlsFingerprintFor()+        val listenPath = listenPathFor(conversationId, tlsFingerprint != null)         val (startLine, headers, content) =-            buildInvite(focusUri, callId, localTag, branch, conversationId, subject, listenPath)+            buildInvite(+                focusUri, callId, localTag, branch, conversationId, subject,+                listenPath, tlsFingerprint,+            )         val ok = RcsSipTransport.sendSipMessage(startLine, headers, content)         if (!ok) return null         val dialogId = "$callId:$localTag"@@ -99,6 +109,7 @@ object RcsSessionManager {             remoteUri = focusUri,             conversationId = conversationId,             isGroup = true,+            msrpSecure = tlsFingerprint != null,         ))         return dialogId     }@@ -211,6 +222,7 @@ object RcsSessionManager {             if (incomplete || idle) {                 _sessions.value = _sessions.value - conversationId                 _pendingOffers.remove(session.callId)+                _answerFingerprints.remove(session.callId)                 RcsMsrpListen.dropPending(conversationId)                 dropped += conversationId             }@@ -255,13 +267,28 @@ object RcsSessionManager {      */     var listenContextProvider: (() -> android.content.Context?)? = null -    private suspend fun listenPathFor(conversationId: String): String? {+    private suspend fun listenPathFor(+        conversationId: String,+        secure: Boolean = false,+        peerFingerprint: String? = null,+    ): String? {         val context = listenContextProvider?.invoke() ?: return null         // The accept callback is a no-op here: the sync service owns the real         // accept loop (it calls ensureListening at startup). advertisePath         // only registers the pending path when already listening.         if (!RcsMsrpListen.isListening()) return null-        return RcsMsrpListen.advertisePath(context, conversationId) { _, _, _ -> }+        return RcsMsrpListen.advertisePath(+            context, conversationId, secure, peerFingerprint,+        ) { _, _, _ -> }+    }++    /**+     * Our TLS fingerprint for SDP offers/answers, or null when the identity+     * is unavailable (caller falls back to plaintext `msrp://`).+     */+    private suspend fun tlsFingerprintFor(): String? {+        val context = listenContextProvider?.invoke() ?: return null+        return RcsMsrpTls.ensureIdentity(context)?.fingerprint     }      /**@@ -283,12 +310,22 @@ object RcsSessionManager {         val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"         val offered = _pendingOffers[session.callId]         // Passive answer when the offerer is active-only and we can listen.+        // The offer's fingerprint (when present) pins the accept-side TLS.+        val offerSdp = offered?.sdp.orEmpty()+        val answerSecure = isSecureSdp(offerSdp)+        val tlsFingerprint = if (answerSecure) tlsFingerprintFor() else null+        val useTls = answerSecure && tlsFingerprint != null         val passivePath = if (offered?.setup == MsrpSetup.ACTIVE && !offered.remotePath.isNullOrBlank()) {-            listenPathFor(conversationId)+            listenPathFor(conversationId, useTls, offered.peerFingerprint)         } else {             null         }-        val sdp = buildSdpAnswer(cfg?.msrpLocalIp, passivePath)+        // Offered TLS but identity unavailable: answer plaintext (downgrade)+        // rather than failing the dialog — pager-mode still works.+        val sdp = buildSdpAnswer(+            cfg?.msrpLocalIp, passivePath,+            secure = useTls, tlsFingerprint = tlsFingerprint,+        )         val bytes = sdp.toByteArray(Charsets.UTF_8)         val branch = "z9hG4bK${UUID.randomUUID().toString().replace("-", "").take(16)}"         val startLine = "SIP/2.0 200 OK"@@ -313,6 +350,7 @@ object RcsSessionManager {                     msrpRemotePath = offer.remotePath,                     msrpSetup = offer.setup,                     msrpLocalPath = passivePath ?: session.msrpLocalPath,+                    msrpSecure = useTls,                 ))             }         }@@ -341,9 +379,23 @@ object RcsSessionManager {     }      /** Inbound offer details stashed at INVITE time for [acceptIncoming]. */-    private data class PendingOffer(val remotePath: String?, val setup: MsrpSetup?)+    private data class PendingOffer(+        val remotePath: String?,+        val setup: MsrpSetup?,+        /** Raw offer SDP (for TLS/fingerprint detection at answer time). */+        val sdp: String = "",+        /** Peer's SDP fingerprint value, when offered (for TLS pinning). */+        val peerFingerprint: String? = null,+    )      private val _pendingOffers = ConcurrentHashMap<String, PendingOffer>()++    /** Peer's SDP answer fingerprint for an outgoing session ([callId]). */+    private val _answerFingerprints = ConcurrentHashMap<String, String>()++    /** Stashed answer fingerprint for [callId], or null when absent. */+    fun peerFingerprint(callId: String): String? = _answerFingerprints[callId]+     /** Tear down the session for [conversationId] with BYE. */     suspend fun terminateSession(conversationId: String): Boolean {         val session = _sessions.value[conversationId] ?: return true@@ -359,6 +411,7 @@ object RcsSessionManager {         transactions.remove(branch)         _sessions.value = _sessions.value - conversationId         _pendingOffers.remove(session.callId)+        _answerFingerprints.remove(session.callId)         RcsMsrpListen.dropPending(conversationId)         if (session.remoteTag.isNotBlank()) {             // Tell the framework the dialog is gone so it releases delegate@@ -379,11 +432,22 @@ object RcsSessionManager {         if (statusCode in 200..299 && !remoteTag.isNullOrBlank()) {             val (localPath, remotePath) = parseSdpPaths(sdpAnswer)             val setup = parseSdpSetup(sdpAnswer)+            // TLS sticks when WE offered secure and the answer keeps it+            // (secure answer SDP); a plaintext answer to our secure offer is+            // a downgrade — honor it and run plaintext.+            val answerSecure = isSecureSdp(sdpAnswer)+            // Stash the answer's fingerprint for the TLS client pin check+            // and the listen-side accept pin check.+            RcsMsrpTls.parseFingerprint(sdpAnswer)?.second?.let { fp ->+                _answerFingerprints[callId] = fp+                RcsMsrpListen.notePeerFingerprint(entry.key, fp)+            }             _sessions.value = _sessions.value + (entry.key to session.copy(                 remoteTag = remoteTag,                 msrpLocalPath = localPath ?: session.msrpLocalPath,                 msrpRemotePath = remotePath,                 msrpSetup = setup,+                msrpSecure = session.msrpSecure && answerSecure,             ))             // Usable when: peer is passive/actpass (we connect out, the v1             // path), OR peer is active and we have a listen path (they@@ -448,6 +512,8 @@ object RcsSessionManager {                     remotePath = Regex("a=path:(\\S+)", RegexOption.IGNORE_CASE).find(body)                         ?.groupValues?.getOrNull(1)?.trim(),                     setup = parseSdpSetup(body),+                    sdp = body,+                    peerFingerprint = RcsMsrpTls.parseFingerprint(body)?.second,                 )                 val session = RcsSession(                     dialogId = "$callId:in",@@ -497,10 +563,11 @@ object RcsSessionManager {         conversationId: String,         subject: String? = null,         listenPath: String? = null,+        tlsFingerprint: String? = null,     ): Triple<String, String, ByteArray> {         val cfg = RcsSipTransport.lastConfigSnapshot()         val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"-        val sdp = buildSdpOffer(cfg?.msrpLocalIp, listenPath)+        val sdp = buildSdpOffer(cfg?.msrpLocalIp, listenPath, tlsFingerprint)         val bytes = sdp.toByteArray(Charsets.UTF_8)         val startLine = "INVITE $targetUri SIP/2.0"         val headers = buildString {@@ -530,57 +597,89 @@ object RcsSessionManager {      * SDP offer: `setup:actpass` + listen path when we can accept inbound      * TCP ([listenPath] from [RcsMsrpListen]), else the v1 `setup:active`      * connect-out offer with an unroutable placeholder path.+     *+     * TLS (RFC 4976): when our identity is available ([tlsFingerprint]+     * non-null) the offer is `TCP/TLS/MSRP` with an `msrps://` path ++     * `a=fingerprint`, so a TLS-capable peer answers secure; otherwise plain+     * `TCP/MSRP`. The media proto/paths always agree (never a TLS path on a+     * plaintext `m=` line).      */-    private fun buildSdpOffer(localIp: String?, listenPath: String?): String {+    private fun buildSdpOffer(+        localIp: String?,+        listenPath: String?,+        tlsFingerprint: String? = null,+    ): String {         val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"+        val secure = tlsFingerprint != null         val (path, port, setup) = if (listenPath != null) {-            Triple(listenPath, RcsMsrpListen.listenPort() ?: 2855, "actpass")+            Triple(+                if (secure) listenPath.withScheme("msrps") else listenPath,+                RcsMsrpListen.listenPort() ?: 2855,+                "actpass",+            )         } else {             Triple(-                "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp",+                "${if (secure) "msrps" else "msrp"}://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp",                 2855,                 "active",             )         }+        val proto = if (secure) "TCP/TLS/MSRP" else "TCP/MSRP"         return buildString {             append("v=0\r\n")             append("o=- ${System.currentTimeMillis()} ${System.currentTimeMillis()} IN IP4 $ip\r\n")             append("s=-\r\n")             append("c=IN IP4 $ip\r\n")             append("t=0 0\r\n")-            append("m=message $port TCP/MSRP *\r\n")+            append("m=message $port $proto *\r\n")             append("a=path:$path\r\n")             append("a=accept-types:message/cpim text/plain message/imdn+xml application/im-iscomposing+xml\r\n")             append("a=setup:$setup\r\n")+            if (secure) append("a=fingerprint:${RcsMsrpTls.FINGERPRINT_HASH} $tlsFingerprint\r\n")         }     }      /**      * SDP answer: `setup:passive` + listen path when we are accepting the      * offerer's TCP connection ([passivePath] non-null), else the v1-     * `setup:active` answer (we connect out to the offerer).+     * `setup:active` answer (we connect out to the offerer). [secure]+     * mirrors the offerer's choice: a TLS offer (`TCP/TLS/MSRP`,+     * `msrps://`, or `a=fingerprint`) gets a TLS answer with our+     * fingerprint; otherwise plaintext.      */-    private fun buildSdpAnswer(localIp: String?, passivePath: String? = null): String {+    private fun buildSdpAnswer(+        localIp: String?,+        passivePath: String? = null,+        secure: Boolean = false,+        tlsFingerprint: String? = null,+    ): String {         val ip = localIp?.takeIf { it.isNotBlank() } ?: "0.0.0.0"+        val useTls = secure && tlsFingerprint != null         val (path, port, setup) = if (passivePath != null) {-            Triple(passivePath, RcsMsrpListen.listenPort() ?: 2855, "passive")+            Triple(+                if (useTls) passivePath.withScheme("msrps") else passivePath,+                RcsMsrpListen.listenPort() ?: 2855,+                "passive",+            )         } else {             Triple(-                "msrp://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp",+                "${if (useTls) "msrps" else "msrp"}://${UUID.randomUUID()}.invalid:2855/${UUID.randomUUID()};tcp",                 2855,                 "active",             )         }+        val proto = if (useTls) "TCP/TLS/MSRP" else "TCP/MSRP"         return buildString {             append("v=0\r\n")             append("o=- ${System.currentTimeMillis()} ${System.currentTimeMillis()} IN IP4 $ip\r\n")             append("s=-\r\n")             append("c=IN IP4 $ip\r\n")             append("t=0 0\r\n")-            append("m=message $port TCP/MSRP *\r\n")+            append("m=message $port $proto *\r\n")             append("a=path:$path\r\n")             append("a=accept-types:message/cpim text/plain message/imdn+xml application/im-iscomposing+xml\r\n")             append("a=setup:$setup\r\n")+            if (useTls) append("a=fingerprint:${RcsMsrpTls.FINGERPRINT_HASH} $tlsFingerprint\r\n")         }     } @@ -591,9 +690,22 @@ object RcsSessionManager {         return null to path     } +    /** Rewrite an `msrp(s)://` path's scheme (e.g. advertise `msrps://`). */+    private fun String.withScheme(scheme: String): String {+        val rest = substringAfter("://", missingDelimiterValue = this)+        return if (rest === this) this else "$scheme://$rest"+    }++    /** True when the SDP negotiates TLS media (`TCP/TLS/MSRP`, `msrps`, or fingerprint). */+    fun isSecureSdp(sdp: String?): Boolean {+        if (sdp.isNullOrBlank()) return false+        return sdp.contains("TCP/TLS/MSRP", ignoreCase = true) ||+            Regex("a=path:msrps://", RegexOption.IGNORE_CASE).containsMatchIn(sdp) ||+            RcsMsrpTls.parseFingerprint(sdp) != null+    }+     /** Hosted-focus lookup: which focus a To-URI/SDP blob targets. */     private data class HostedTarget(val focusUri: String, val conversationId: String)-     private fun hostedConversationFor(target: String): HostedTarget? {         if (target.isBlank()) return null         for ((conversationId, session) in _sessions.value) {
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.ktindex 7d9960d4b0..ae71984cd5 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsUpFramingTest.kt@@ -4,7 +4,9 @@ import com.vayunmathur.communicate.data.rcs.ImdnDisposition import com.vayunmathur.communicate.data.rcs.MsrpSetup import com.vayunmathur.communicate.data.rcs.RcsFileTransferHttp import com.vayunmathur.communicate.data.rcs.RcsGbaAuth+import com.vayunmathur.communicate.data.rcs.RcsMsrp import com.vayunmathur.communicate.data.rcs.RcsMsrpListen+import com.vayunmathur.communicate.data.rcs.RcsMsrpTls import com.vayunmathur.communicate.data.rcs.RcsSessionManager import com.vayunmathur.communicate.data.rcs.buildEditBody import com.vayunmathur.communicate.data.rcs.buildGeopushBody@@ -210,4 +212,73 @@ class RcsUpFramingTest {         // Empty manager: nothing to drop, no crash.         assertTrue(RcsSessionManager.sweepStaleSessions().isEmpty())     }++    @Test+    fun fingerprintParses() {+        val sdp = "m=message 2855 TCP/TLS/MSRP *\r\n" ++            "a=path:msrps://10.0.0.1:2855/abc;tcp\r\n" ++            "a=fingerprint:SHA-256 AA:BB:CC:01\r\n"+        val (hash, value) = RcsMsrpTls.parseFingerprint(sdp) ?: error("no fingerprint")+        assertEquals("SHA-256", hash)+        assertEquals("AA:BB:CC:01", value)+        assertNull(RcsMsrpTls.parseFingerprint("m=message 2855 TCP/MSRP *"))+        assertNull(RcsMsrpTls.parseFingerprint(null))+    }++    @Test+    fun secureSdpDetection() {+        assertTrue(+            RcsSessionManager.isSecureSdp("m=message 2855 TCP/TLS/MSRP *\r\na=setup:actpass\r\n"),+        )+        assertTrue(+            RcsSessionManager.isSecureSdp("a=path:msrps://10.0.0.1:9/x;tcp\r\n"),+        )+        assertTrue(+            RcsSessionManager.isSecureSdp("a=fingerprint:SHA-256 AA:BB\r\n"),+        )+        assertFalse(+            RcsSessionManager.isSecureSdp("m=message 2855 TCP/MSRP *\r\na=setup:active\r\n"),+        )+        assertFalse(RcsSessionManager.isSecureSdp(null))+    }++    @Test+    fun securePathScheme() {+        assertTrue(RcsMsrp.isSecurePath("msrps://10.0.0.1:2855/abc;tcp"))+        assertTrue(RcsMsrp.isSecurePath("MSRPS://10.0.0.1:2855/abc;tcp"))+        assertFalse(RcsMsrp.isSecurePath("msrp://10.0.0.1:2855/abc;tcp"))+        assertFalse(RcsMsrp.isSecurePath(null))+        assertFalse(RcsMsrp.isSecurePath(""))+        // Scheme-agnostic host/port parsing still works for msrps.+        assertEquals(+            "10.0.0.1" to 2855,+            RcsMsrp.parseMsrpPath("msrps://10.0.0.1:2855/abc;tcp"),+        )+    }++    @Test+    fun selfSignedCertParsesAndVerifies() {+        // Hand-rolled DER must decode as X.509, verify with its own key, and+        // fingerprint-match its DER bytes.+        val kpg = java.security.KeyPairGenerator.getInstance("EC")+        kpg.initialize(java.security.spec.ECGenParameterSpec("secp256r1"))+        val kp = kpg.generateKeyPair()+        val now = System.currentTimeMillis()+        val der = RcsMsrpTls.selfSignedCert(+            publicKey = kp.public.encoded,+            privateKey = kp.private,+            notBeforeMs = now - 1000,+            notAfterMs = now + 3600_000,+            commonName = "test",+        )+        val cf = java.security.cert.CertificateFactory.getInstance("X.509")+        val cert = cf.generateCertificate(der.inputStream()) as java.security.cert.X509Certificate+        cert.verify(kp.public)+        assertEquals("CN=test", cert.subjectX500Principal.name)+        val fp = RcsMsrpTls.fingerprintOf(der)+        assertTrue(fp.matches(Regex("([0-9A-F]{2}:){31}[0-9A-F]{2}")))+        // Fingerprint binds the exact bytes: flipping one flips the print.+        val mutated = der.copyOf().also { it[der.size - 1] = (it[der.size - 1] + 1).toByte() }+        assertFalse(RcsMsrpTls.fingerprintOf(mutated) == fp)+    } }