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

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalSealedSender.kt

SignalSealedSender.kt176 lines · 7.1 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import com.vayunmathur.library.log.Log
4import com.vayunmathur.library.network.NetworkClient
5import kotlinx.serialization.json.Json
6import kotlinx.serialization.json.jsonObject
7import kotlinx.serialization.json.jsonPrimitive
8import org.signal.libsignal.metadata.certificate.SenderCertificate
9import javax.crypto.Cipher
10import javax.crypto.spec.GCMParameterSpec
11import javax.crypto.spec.SecretKeySpec
12import javax.net.ssl.SSLSocketFactory
13import kotlin.io.encoding.Base64
14import kotlin.io.encoding.ExperimentalEncodingApi
15
16/**
17 * Sealed sender support: the delivery certificate that proves who we are to the *recipient* without
18 * telling the server, and the unidentified-access key that authorises an unauthenticated send.
19 *
20 * The certificate comes from `GET /v1/certificate/delivery` and is cached until shortly before it
21 * expires. The access key is derived from the recipient's profile key.
22 */
23@OptIn(ExperimentalEncodingApi::class)
24object SignalSealedSender {
25 private const val TAG = "SignalSealedSender"
26 private const val GCM_TAG_BITS = 128
27 private const val GCM_IV_BYTES = 12
28 private const val BLOCK_BYTES = 16
29 private const val BASE64_QUAD = 4
30 private const val BASE64_SINGLE_PAD = 3
31
32 /** Refresh this far ahead of expiry so a send never races the rotation. */
33 private const val EXPIRY_BUFFER_MS = 24 * 60 * 60 * 1000L
34
35 /** The header that carries the access key on an unauthenticated send. */
36 const val ACCESS_KEY_HEADER = "Unidentified-Access-Key"
37
38 private val json = Json { ignoreUnknownKeys = true }
39
40 /**
41 * The cached certificate, refetched when absent or within [EXPIRY_BUFFER_MS] of expiry. Returns
42 * null when it cannot be obtained, which means "send identified instead".
43 */
44 suspend fun senderCertificate(
45 db: SignalDatabase,
46 authHeader: String,
47 sslSocketFactory: SSLSocketFactory?,
48 includeE164: Boolean = false,
49 ): SenderCertificate? {
50 val cached = try { db.senderCertificateDao().get() } catch (_: Exception) { null }
51 val now = System.currentTimeMillis()
52 if (cached != null && cached.includesE164 == includeE164 && cached.expiration - EXPIRY_BUFFER_MS > now) {
53 val parsed = try { SenderCertificate(cached.record) } catch (_: Exception) { null }
54 if (parsed != null) return parsed
55 }
56
57 val fetched = fetchCertificate(authHeader, sslSocketFactory, includeE164) ?: return null
58 try {
59 db.senderCertificateDao().upsert(
60 SignalSenderCertificate(
61 record = fetched.serialized,
62 expiration = fetched.expiration,
63 // Record what the certificate actually carries, not what we asked for, so the
64 // freshness check above can't treat a mismatched certificate as a cache hit.
65 includesE164 = fetched.senderE164.isPresent,
66 ),
67 )
68 } catch (expected: Throwable) {
69 Log.status(TAG, "could not cache the sender certificate", expected)
70 }
71 return fetched
72 }
73
74 private suspend fun fetchCertificate(
75 authHeader: String,
76 sslSocketFactory: SSLSocketFactory?,
77 includeE164: Boolean,
78 ): SenderCertificate? {
79 // Two variants; the no-E164 one is what you want unless the user shares their phone number.
80 val path = if (includeE164) "/v1/certificate/delivery" else "/v1/certificate/delivery?includeE164=false"
81 val resp = try {
82 NetworkClient.execute(
83 "https://chat.signal.org$path",
84 method = "GET",
85 headers = mapOf("Authorization" to "Basic $authHeader"),
86 sslSocketFactory = sslSocketFactory,
87 )
88 } catch (expected: Throwable) {
89 Log.status(TAG, "delivery certificate fetch failed", expected)
90 return null
91 }
92 if (!resp.isSuccess) {
93 Log.status(TAG, "delivery certificate fetch failed: ${resp.status} ${resp.statusMessage}")
94 return null
95 }
96 return parseCertificate(resp.text)
97 }
98
99 /** Response is `{"certificate":"<base64>"}`. [warn] is injectable so this stays testable off-device. */
100 internal fun parseCertificate(
101 body: String,
102 warn: (String) -> Unit = { Log.status(TAG, it) },
103 ): SenderCertificate? {
104 val encoded = try {
105 json.parseToJsonElement(body).jsonObject["certificate"]?.jsonPrimitive?.content
106 } catch (_: Exception) {
107 null
108 }
109 if (encoded.isNullOrEmpty()) {
110 warn("delivery certificate response had no certificate field")
111 return null
112 }
113 return try {
114 SenderCertificate(decodeBase64(encoded))
115 } catch (expected: Throwable) {
116 warn("delivery certificate did not parse: ${expected.message}")
117 null
118 }
119 }
120
121 /**
122 * The recipient's unidentified-access key, or null when we do not hold their profile key and so
123 * must send identified.
124 */
125 suspend fun accessKeyFor(db: SignalDatabase, aci: String): ByteArray? {
126 val stored = try { db.profileKeyDao().get(aci) } catch (_: Exception) { null } ?: return null
127 return deriveAccessKey(stored.profileKey)
128 }
129
130 /** Remember a profile key learned from an inbound message. */
131 suspend fun rememberProfileKey(db: SignalDatabase, aci: String, profileKey: ByteArray) {
132 if (profileKey.size != PROFILE_KEY_SIZE) {
133 Log.status(TAG, "ignoring a ${profileKey.size}-byte profile key for $aci")
134 return
135 }
136 try {
137 db.profileKeyDao().upsert(SignalProfileKey(address = aci, profileKey = profileKey))
138 } catch (expected: Throwable) {
139 Log.status(TAG, "could not store the profile key for $aci", expected)
140 }
141 }
142
143 private const val PROFILE_KEY_SIZE = 32
144
145 /**
146 * AES-256-GCM of 16 zero bytes under the profile key with a 12-byte zero nonce, truncated to the
147 * first 16 bytes. Deliberately not an HKDF — this matches the official derivation exactly.
148 */
149 fun deriveAccessKey(profileKey: ByteArray): ByteArray? {
150 if (profileKey.size != PROFILE_KEY_SIZE) return null
151 return try {
152 val cipher = Cipher.getInstance("AES/GCM/NoPadding")
153 cipher.init(
154 Cipher.ENCRYPT_MODE,
155 SecretKeySpec(profileKey, "AES"),
156 GCMParameterSpec(GCM_TAG_BITS, ByteArray(GCM_IV_BYTES)),
157 )
158 cipher.doFinal(ByteArray(BLOCK_BYTES)).copyOf(BLOCK_BYTES)
159 } catch (expected: Throwable) {
160 Log.status(TAG, "access key derivation failed", expected)
161 null
162 }
163 }
164
165 fun accessKeyHeader(accessKey: ByteArray): String =
166 "$ACCESS_KEY_HEADER:${Base64.Default.encode(accessKey)}"
167
168 private fun decodeBase64(value: String): ByteArray {
169 val padded = when (value.length % BASE64_QUAD) {
170 2 -> "$value=="
171 BASE64_SINGLE_PAD -> "$value="
172 else -> value
173 }
174 return Base64.Default.decode(padded)
175 }
176}