Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsMsrpTls.kt

RcsMsrpTls.kt429 lines · 18.4 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import android.annotation.SuppressLint
4import android.content.Context
5import com.vayunmathur.library.log.Log
6import java.io.File
7import java.net.InetSocketAddress
8import java.net.Socket
9import java.security.KeyFactory
10import java.security.KeyPairGenerator
11import java.security.MessageDigest
12import java.security.PrivateKey
13import java.security.SecureRandom
14import java.security.cert.CertificateFactory
15import java.security.cert.X509Certificate
16import java.security.spec.PKCS8EncodedKeySpec
17import javax.net.ssl.KeyManagerFactory
18import javax.net.ssl.SSLContext
19import javax.net.ssl.SSLSocket
20import javax.net.ssl.TrustManager
21import javax.net.ssl.X509TrustManager
22import kotlinx.coroutines.Dispatchers
23import kotlinx.coroutines.withContext
24
25/**
26 * MSRP-over-TLS identity + socket layer (RFC 4976, RFC 4572).
27 *
28 * UP transports negotiate `TCP/TLS/MSRP` (`msrps://` paths) with certificate
29 * fingerprints in SDP (`a=fingerprint:SHA-256 <hex>`). There is no PKI on the
30 * IMS PDN — both ends use self-signed certs and verify the peer against the
31 * fingerprint from its SDP (RFC 4572 §5, RFC 4976 §3.1). This object owns:
32 *
33 * - Identity: one EC P-256 keypair + self-signed cert, generated once via
34 * the platform `KeyPairGenerator` and persisted as raw DER in a private
35 * app file (no KeyStore dance, no new dependency — the X.509 writer below
36 * is a minimal hand-rolled DER encoder for exactly this shape).
37 * - Client: TLS over the IMS-PDN TCP socket ([RcsImsNetwork.createSocket]),
38 * verifying the peer cert fingerprint against the SDP-advertised value.
39 * - Server: `SSLContext` with our cert for the listen side; client certs are
40 * requested and verified when the expected peer fingerprint is known
41 * (from their offer SDP), accepted-unverified otherwise (the MSRP layer
42 * still routes by To-Path, and chat payloads are MLS-encrypted anyway).
43 *
44 * Every entry point early-returns null when the dev gate is off and never
45 * throws; callers fall back to plaintext `msrp://` (downgrade) or fail the
46 * session per their policy.
47 */
48object RcsMsrpTls {
49 private const val TAG = "RcsMsrpTls"
50
51 /** Fingerprint hash named in SDP (RFC 4572 §5: `SHA-256`, uppercase). */
52 const val FINGERPRINT_HASH = "SHA-256"
53
54 private const val IDENTITY_DIR = "rcs-msrp-tls"
55 private const val CERT_FILE = "identity.der"
56 private const val KEY_FILE = "identity.pk8"
57 private const val CERT_VALIDITY_DAYS = 10L
58 private const val DAY_MS = 24 * 3600 * 1000L
59 private const val YEAR_DAYS = 365
60 private const val ASN1_SEQUENCE = 0x30
61 private const val ASN1_SET = 0x31
62 private const val ASN1_CONTEXT_BASE = 0xA0
63 private const val ASN1_HIGH_BIT = 0x80
64 private const val ASN1_INTEGER = 0x02
65 private const val ASN1_OID = 0x06
66 private const val ASN1_NULL = 0x05
67 private const val ASN1_UTF8STRING = 0x0C
68 private const val ASN1_UTCTIME = 0x17
69 private const val ASN1_OCTETSTRING = 0x04
70 private const val ASN1_BITSTRING = 0x03
71 private const val ASN1_ZERO = 0x00
72 private const val ASN1_SHORT_LEN_LIMIT = 128
73 private const val BYTE_MASK = 0xFF
74 private const val VARINT_MASK = 0x7F
75 private const val VARINT_CONT = 0x80
76 private const val VARINT_BITS = 7
77 private const val BYTE_BITS = 8
78 private const val YEAR_CENTURY = 100
79 private const val SERIAL_BYTES = 9
80 private const val OID_FIRST_FACTOR = 40
81
82 /** Our TLS identity: DER cert bytes + fingerprint + key. */
83 data class Identity(
84 val certDer: ByteArray,
85 val fingerprint: String,
86 internal val privateKey: PrivateKey,
87 ) {
88 /** `a=fingerprint:SHA-256 <FP>` SDP line for offers/answers. */
89 fun sdpLine(): String = "a=fingerprint:$FINGERPRINT_HASH $fingerprint"
90
91 override fun equals(other: Any?): Boolean {
92 if (this === other) return true
93 if (other !is Identity) return false
94 return fingerprint == other.fingerprint && certDer.contentEquals(other.certDer)
95 }
96
97 override fun hashCode(): Int = fingerprint.hashCode()
98 }
99
100 @Volatile
101 private var cached: Identity? = null
102
103 /**
104 * Load-or-generate our TLS identity. Suspends on Dispatchers.IO (key
105 * generation blocks). Null when the gate is off or generation failed —
106 * callers offer plaintext `msrp://` instead.
107 */
108 suspend fun ensureIdentity(context: Context): Identity? = withContext(Dispatchers.IO) {
109 if (!RcsFeature.enabled) return@withContext null
110 cached?.let { return@withContext it }
111 runCatching {
112 val dir = File(context.filesDir, IDENTITY_DIR).apply { mkdirs() }
113 val certFile = File(dir, CERT_FILE)
114 val keyFile = File(dir, KEY_FILE)
115 if (certFile.exists() && keyFile.exists()) {
116 loadIdentity(certFile.readBytes(), keyFile.readBytes())?.let {
117 cached = it
118 return@runCatching it
119 }
120 }
121 val fresh = generateIdentity() ?: return@runCatching null
122 certFile.writeBytes(fresh.certDer)
123 keyFile.writeBytes(fresh.privateKey.encoded)
124 cached = fresh
125 fresh
126 }.getOrElse {
127 Log.status(TAG, "TLS identity unavailable", it)
128 null
129 }
130 }
131
132 /**
133 * TLS client socket to [host]:[port]: TCP via the IMS PDN, then TLS with
134 * SNI-less handshake, verifying the peer cert fingerprint against
135 * [expectedFingerprint] (RFC 4572 format, case-insensitive). Null when
136 * the TCP leg, handshake, or fingerprint check fails.
137 */
138 suspend fun clientSocket(
139 context: Context,
140 host: String,
141 port: Int,
142 expectedFingerprint: String?,
143 connectTimeoutMs: Int = 10_000,
144 ): SSLSocket? = withContext(Dispatchers.IO) {
145 if (!RcsFeature.enabled) return@withContext null
146 if (expectedFingerprint.isNullOrBlank()) {
147 Log.status(TAG, "No peer fingerprint — refusing TLS without pinning")
148 return@withContext null
149 }
150 val identity = ensureIdentity(context) ?: return@withContext null
151 val tcp = RcsImsNetwork.createSocket(context, host, port, connectTimeoutMs)
152 ?: return@withContext null
153 runCatching {
154 val ssl = clientContext(identity).socketFactory
155 .createSocket(tcp, host, port, true) as SSLSocket
156 ssl.soTimeout = 0
157 ssl.startHandshake()
158 val peerCert = ssl.session.peerCertificates
159 .firstOrNull() as? X509Certificate
160 ?: throw javax.net.ssl.SSLPeerUnverifiedException("No peer cert")
161 val actual = fingerprintOf(peerCert.encoded)
162 if (!actual.equals(expectedFingerprint.trim(), ignoreCase = true)) {
163 throw javax.net.ssl.SSLPeerUnverifiedException(
164 "MSRP fingerprint mismatch (SNI-less DANE-less pinning)",
165 )
166 }
167 Log.status(TAG, "TLS client established to $host:$port (pinned)")
168 ssl
169 }.getOrElse {
170 Log.status(TAG, "TLS client handshake failed", it)
171 runCatching { tcp.close() }
172 null
173 }
174 }
175
176 /**
177 * Server `SSLContext` presenting our cert for the listen side. Client
178 * certs are requested (not required); verification against the expected
179 * peer fingerprint happens per-socket in [verifyServerSide] because the
180 * expected value is per-session, not per-context.
181 */
182 suspend fun serverContext(context: Context): SSLContext? = withContext(Dispatchers.IO) {
183 if (!RcsFeature.enabled) return@withContext null
184 val identity = ensureIdentity(context) ?: return@withContext null
185 runCatching {
186 val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
187 val ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType())
188 ks.load(null, null)
189 val cf = CertificateFactory.getInstance("X.509")
190 val cert = cf.generateCertificate(identity.certDer.inputStream())
191 ks.setKeyEntry("msrp", identity.privateKey, CharArray(0), arrayOf(cert))
192 kmf.init(ks, CharArray(0))
193 SSLContext.getInstance("TLS").apply {
194 // Trust-all client certs at the TLS layer; per-session pinning
195 // in verifyServerSide decides.
196 init(kmf.keyManagers, arrayOf<TrustManager>(PermissiveTrustManager), SecureRandom())
197 }
198 }.getOrElse {
199 Log.status(TAG, "TLS server context failed", it)
200 null
201 }
202 }
203
204 /**
205 * Verify a server-side (accepted) socket's peer cert against
206 * [expectedFingerprint]. True when it matches, or when [expectedFingerprint]
207 * is blank (offer carried no fingerprint — accept unverified, matching the
208 * plaintext-era behavior for non-TLS peers). False on mismatch.
209 */
210 fun verifyServerSide(socket: SSLSocket, expectedFingerprint: String?): Boolean {
211 if (expectedFingerprint.isNullOrBlank()) return true
212 return runCatching {
213 val peerCert = socket.session.peerCertificates
214 .firstOrNull() as? X509Certificate ?: return false
215 fingerprintOf(peerCert.encoded)
216 .equals(expectedFingerprint.trim(), ignoreCase = true)
217 }.getOrDefault(false)
218 }
219
220 /** Parse an SDP `a=fingerprint:` line into (hash, value), or null. */
221 fun parseFingerprint(sdp: String?): Pair<String, String>? {
222 if (sdp.isNullOrBlank()) return null
223 val m = Regex(
224 "a=fingerprint:(\\S+)\\s+([0-9A-Fa-f:]+)",
225 RegexOption.IGNORE_CASE,
226 ).find(sdp) ?: return null
227 val (hash, value) = m.destructured
228 if (value.isBlank()) return null
229 return hash to value.trim()
230 }
231
232 /** RFC 4572 fingerprint: uppercase colon-hex SHA-256 of the DER cert. */
233 fun fingerprintOf(certDer: ByteArray): String {
234 val digest = MessageDigest.getInstance("SHA-256").digest(certDer)
235 return digest.joinToString(":") { "%02X".format(it) }
236 }
237
238 private fun loadIdentity(certDer: ByteArray, keyPkcs8: ByteArray): Identity? {
239 return runCatching {
240 val kf = KeyFactory.getInstance("EC")
241 val key = kf.generatePrivate(PKCS8EncodedKeySpec(keyPkcs8))
242 Identity(certDer, fingerprintOf(certDer), key)
243 }.getOrNull()
244 }
245
246 private fun clientContext(identity: Identity): SSLContext {
247 val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
248 val ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType())
249 ks.load(null, null)
250 val cf = CertificateFactory.getInstance("X.509")
251 val cert = cf.generateCertificate(identity.certDer.inputStream())
252 ks.setKeyEntry("msrp", identity.privateKey, CharArray(0), arrayOf(cert))
253 kmf.init(ks, CharArray(0))
254 return SSLContext.getInstance("TLS").apply {
255 init(kmf.keyManagers, arrayOf<TrustManager>(PermissiveTrustManager), SecureRandom())
256 }
257 }
258
259 // Chain validation would reject the self-signed carrier certs MSRP uses;
260 // the peer is instead authenticated by RFC 4572 fingerprint pinning,
261 // checked per socket in clientSocket / verifyServerSide before any data
262 // flows (and clientSocket refuses to connect without an expected
263 // fingerprint). This manager therefore intentionally accepts any chain.
264 @SuppressLint("CustomX509TrustManager")
265 private object PermissiveTrustManager : X509TrustManager {
266 override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
267 override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
268 override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
269 }
270
271 // -- Minimal X.509 writer (self-signed EC P-256, SHA256withECDSA) --
272
273 private fun generateIdentity(): Identity? {
274 return runCatching {
275 val kpg = KeyPairGenerator.getInstance("EC")
276 kpg.initialize(java.security.spec.ECGenParameterSpec("secp256r1"), SecureRandom())
277 val kp = kpg.generateKeyPair()
278 val now = System.currentTimeMillis()
279 val certDer = selfSignedCert(
280 publicKey = kp.public.encoded,
281 privateKey = kp.private,
282 notBeforeMs = now - DAY_MS,
283 notAfterMs = now + CERT_VALIDITY_DAYS * YEAR_DAYS * DAY_MS,
284 // IMS-PDN IPs change across attaches; a stable pseudonymous CN
285 // is honest (RFC 4572 identity comes from the fingerprint,
286 // not the subject).
287 commonName = "rcs-msrp-tls",
288 )
289 Identity(certDer, fingerprintOf(certDer), kp.private)
290 }.getOrElse {
291 Log.status(TAG, "TLS identity generation failed", it)
292 null
293 }
294 }
295
296 /**
297 * Build a v3 self-signed cert DER for [publicKey] (X.509 SubjectPublicKeyInfo
298 * DER), signed by [privateKey] (EC). Minimal encoder: SEQUENCE-heavy,
299 * length-prefixed — sized for this exact shape (no extensions).
300 */
301 fun selfSignedCert(
302 publicKey: ByteArray,
303 privateKey: PrivateKey,
304 notBeforeMs: Long,
305 notAfterMs: Long,
306 commonName: String,
307 ): ByteArray {
308 // 1.2.840.10045.4.3.2 = ecdsa-with-SHA256.
309 val sigAlgId = Der.sequence(
310 Der.oid("1.2.840.10045.4.3.2"),
311 Der.nullValue(),
312 )
313 val name = Der.sequence(
314 Der.set(
315 Der.sequence(
316 // 2.5.4.3 = commonName.
317 Der.oid("2.5.4.3"),
318 Der.utf8String(commonName),
319 ),
320 ),
321 )
322 val serial = ByteArray(SERIAL_BYTES).also {
323 SecureRandom().nextBytes(it)
324 it[0] = (it[0].toInt() and VARINT_MASK).toByte()
325 }
326 val tbs = Der.sequence(
327 // TBSCertificate order (RFC 5280 §4.1.2): version [0] EXPLICIT,
328 // then serialNumber. (These two were swapped — the serial sat in
329 // the version slot, which no X.509 parser accepts.)
330 Der.explicit(0, Der.integer(byteArrayOf(2))), // v3
331 Der.integer(serial),
332 sigAlgId,
333 name, // issuer
334 Der.sequence(Der.utcTime(notBeforeMs), Der.utcTime(notAfterMs)),
335 name, // subject
336 Der.raw(publicKey), // SubjectPublicKeyInfo DER, embedded as-is
337 )
338 val signature = Der.ecdsaSign(tbs, privateKey)
339 return Der.sequence(tbs, sigAlgId, Der.bitString(signature))
340 }
341
342 /** Minimal DER primitives for the cert writer above. */
343 object Der {
344 fun sequence(vararg parts: ByteArray): ByteArray =
345 byteArrayOf(ASN1_SEQUENCE.toByte()) + lengthPrefix(parts.sumOf { it.size }) + parts.reduce { a, b -> a + b }
346
347 fun set(vararg parts: ByteArray): ByteArray =
348 byteArrayOf(ASN1_SET.toByte()) + lengthPrefix(parts.sumOf { it.size }) + parts.reduce { a, b -> a + b }
349
350 fun explicit(tag: Int, content: ByteArray): ByteArray =
351 byteArrayOf((ASN1_CONTEXT_BASE + tag).toByte()) + lengthPrefix(content.size) + content
352
353 fun integer(bytes: ByteArray): ByteArray {
354 var start = 0
355 while (start < bytes.size - 1 && bytes[start] == 0.toByte()) start++
356 var v = bytes.copyOfRange(start, bytes.size)
357 if (v[0].toInt() and ASN1_HIGH_BIT != 0) v = byteArrayOf(0) + v
358 return byteArrayOf(ASN1_INTEGER.toByte()) + lengthPrefix(v.size) + v
359 }
360
361 fun oid(dotted: String): ByteArray {
362 val arcs = dotted.split(".").map { it.toInt() }
363 val first = byteArrayOf(((arcs[0] * OID_FIRST_FACTOR + arcs[1]).toByte()))
364 val rest = arcs.drop(2).fold(byteArrayOf()) { acc, a -> acc + base128(a) }
365 val body = first + rest
366 return byteArrayOf(ASN1_OID.toByte()) + lengthPrefix(body.size) + body
367 }
368
369 fun nullValue(): ByteArray = byteArrayOf(ASN1_NULL.toByte(), ASN1_ZERO.toByte())
370
371 fun utf8String(s: String): ByteArray {
372 val b = s.toByteArray(Charsets.UTF_8)
373 return byteArrayOf(ASN1_UTF8STRING.toByte()) + lengthPrefix(b.size) + b
374 }
375
376 fun utcTime(ms: Long): ByteArray {
377 val cal = java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"))
378 cal.timeInMillis = ms
379 val str = "%02d%02d%02d%02d%02d%02dZ".format(
380 cal.get(java.util.Calendar.YEAR) % YEAR_CENTURY,
381 cal.get(java.util.Calendar.MONTH) + 1,
382 cal.get(java.util.Calendar.DAY_OF_MONTH),
383 cal.get(java.util.Calendar.HOUR_OF_DAY),
384 cal.get(java.util.Calendar.MINUTE),
385 cal.get(java.util.Calendar.SECOND),
386 ).toByteArray(Charsets.US_ASCII)
387 return byteArrayOf(ASN1_UTCTIME.toByte()) + lengthPrefix(str.size) + str
388 }
389
390 fun bitString(signatureDer: ByteArray): ByteArray =
391 byteArrayOf(ASN1_BITSTRING.toByte()) + lengthPrefix(signatureDer.size + 1) +
392 byteArrayOf(ASN1_ZERO.toByte()) + signatureDer
393
394 /** Embed already-encoded DER without re-wrapping. */
395 fun raw(der: ByteArray): ByteArray = der
396
397 fun ecdsaSign(tbs: ByteArray, key: PrivateKey): ByteArray {
398 val sig = java.security.Signature.getInstance("SHA256withECDSA")
399 sig.initSign(key, SecureRandom())
400 sig.update(tbs)
401 return sig.sign() // DER SEQUENCE { r, s } — exactly what BIT STRING holds
402 }
403
404 private fun lengthPrefix(n: Int): ByteArray = when {
405 n < ASN1_SHORT_LEN_LIMIT -> byteArrayOf(n.toByte())
406 else -> {
407 var v = n
408 val bytes = mutableListOf<Byte>()
409 while (v > 0) {
410 bytes.add(0, (v and BYTE_MASK).toByte())
411 v = v ushr BYTE_BITS
412 }
413 byteArrayOf((ASN1_HIGH_BIT + bytes.size).toByte()) + bytes.toByteArray()
414 }
415 }
416
417 private fun base128(v: Int): ByteArray {
418 if (v == 0) return byteArrayOf(0)
419 var x = v
420 val out = mutableListOf<Byte>()
421 while (x > 0) {
422 out.add(0, (x and VARINT_MASK).toByte())
423 x = x ushr VARINT_BITS
424 }
425 for (i in 0 until out.size - 1) out[i] = (out[i].toInt() or VARINT_CONT).toByte()
426 return out.toByteArray()
427 }
428 }
429}