Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / e2e / SignalE2E.kt
SignalE2E.kt407 lines · 18.6 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal.e2e |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import com.vayunmathur.communicate.data.signal.SignalAuthData |
| 5 | import com.vayunmathur.communicate.data.signal.SignalDatabase |
| 6 | import com.vayunmathur.communicate.data.signal.SignalE2EPreKey |
| 7 | import com.vayunmathur.communicate.data.signal.SignalE2ESenderKey |
| 8 | import java.util.UUID |
| 9 | import kotlinx.coroutines.runBlocking |
| 10 | import kotlin.io.encoding.Base64 |
| 11 | import kotlin.io.encoding.ExperimentalEncodingApi |
| 12 | import org.signal.libsignal.metadata.SealedSessionCipher |
| 13 | import org.signal.libsignal.metadata.certificate.CertificateValidator |
| 14 | import org.signal.libsignal.metadata.certificate.SenderCertificate |
| 15 | import org.signal.libsignal.protocol.IdentityKey |
| 16 | import org.signal.libsignal.protocol.IdentityKeyPair |
| 17 | import org.signal.libsignal.protocol.SessionBuilder |
| 18 | import org.signal.libsignal.protocol.SessionCipher |
| 19 | import org.signal.libsignal.protocol.SignalProtocolAddress |
| 20 | import org.signal.libsignal.protocol.ecc.ECKeyPair |
| 21 | import org.signal.libsignal.protocol.groups.GroupCipher |
| 22 | import org.signal.libsignal.protocol.groups.GroupSessionBuilder |
| 23 | import org.signal.libsignal.protocol.ecc.ECPrivateKey |
| 24 | import org.signal.libsignal.protocol.ecc.ECPublicKey |
| 25 | import org.signal.libsignal.protocol.kem.KEMKeyPair |
| 26 | import org.signal.libsignal.protocol.kem.KEMKeyType |
| 27 | import org.signal.libsignal.protocol.kem.KEMPublicKey |
| 28 | import org.signal.libsignal.protocol.message.PreKeySignalMessage |
| 29 | import org.signal.libsignal.protocol.message.SenderKeyDistributionMessage |
| 30 | import org.signal.libsignal.protocol.state.KyberPreKeyRecord |
| 31 | import org.signal.libsignal.protocol.state.PreKeyBundle |
| 32 | import org.signal.libsignal.protocol.state.PreKeyRecord |
| 33 | import org.signal.libsignal.protocol.state.SignedPreKeyRecord |
| 34 | |
| 35 | /** |
| 36 | * Rust-backed E2E crypto for Signal (PQXDH + Double Ratchet + Sender Keys + Sealed Sender). |
| 37 | * Delegates PQXDH/Kyber and sealed sender to libsignal-android 0.86.5: |
| 38 | * - SessionBuilder/SessionCipher with Kyber (PreKeyBundle includes kyber fields) |
| 39 | * - SealedSessionCipher + SenderCertificate (cert fetched live: GET /v1/certificate/delivery) |
| 40 | * - CIPHERTEXT_MESSAGE_CURRENT_VERSION=4, HKDF label WhisperText_X25519_SHA-256_CRYSTALS-KYBER-1024 |
| 41 | * - Kyber replay guard via KyberPreKeyStore.markKyberPreKeyUsed |
| 42 | * |
| 43 | * Backwards-compatible overloads kept for wiring (SignalClient) callers. |
| 44 | * ACI/PNI dual identities: storage shape is owned by registration (SignalAuthData); |
| 45 | * this class currently seeds protocolStore from the ACI identity (identity* / registrationId). |
| 46 | * Registration teammate should persist both ACI and PNI IdentityKeyPairs + registrationIds |
| 47 | * (aciIdentity* / pniIdentity* + aciRegistrationId / pniRegistrationId) — see task 4. |
| 48 | */ |
| 49 | @OptIn(ExperimentalEncodingApi::class) |
| 50 | class SignalE2E( |
| 51 | internal val db: SignalDatabase, |
| 52 | internal val auth: SignalAuthData, |
| 53 | /** See [PersistentSignalProtocolStore.onIdentityChanged]. */ |
| 54 | private val onIdentityChanged: (String, ByteArray) -> Unit = { _, _ -> }, |
| 55 | ) { |
| 56 | /** |
| 57 | * Our own identity public key in the form RingRTC expects for call key derivation: the **raw 32-byte** |
| 58 | * key, not the 33-byte serialized form with its `0x05` type prefix. |
| 59 | * |
| 60 | * Official passes both identity keys through `ECPublicKey.getPublicKeyBytes()` |
| 61 | * (`WebRtcUtil.getPublicKeyBytes`) before handing them to `receivedOffer`/`receivedAnswer`. Passing the |
| 62 | * serialized form instead derives SRTP keys that differ from the peer's, so ICE connects and then every |
| 63 | * RTP packet — including RingRTC's `Accepted` message — is undecryptable, which looks like a call that |
| 64 | * connects but never progresses past ringing. |
| 65 | */ |
| 66 | val ownIdentityPublicKey: ByteArray |
| 67 | get() = try { |
| 68 | // IdentityKeyPair -> IdentityKey -> ECPublicKey -> raw bytes, mirroring official's |
| 69 | // getAciIdentityKey().getPublicKey().serialize() passed through getPublicKeyBytes(). |
| 70 | protocolStore.identityKeyPair.publicKey.publicKey.publicKeyBytes |
| 71 | } catch (_: Throwable) { |
| 72 | rawPublicKeyBytes(b64(auth.identityPublicKey)) |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Our own identity public key in serialized (33-byte) form, for fingerprint |
| 77 | * computation. [ownIdentityPublicKey] is the raw RingRTC form; feeding that |
| 78 | * to `IdentityKey(...)` in the safety-number path throws and silently |
| 79 | * yields no safety number at all. |
| 80 | */ |
| 81 | val ownIdentityPublicKeySerialized: ByteArray |
| 82 | get() = try { |
| 83 | protocolStore.identityKeyPair.publicKey.serialize() |
| 84 | } catch (_: Throwable) { |
| 85 | b64(auth.identityPublicKey) |
| 86 | } |
| 87 | |
| 88 | /** Strip the type prefix from a serialized EC public key, as RingRTC's key derivation requires. */ |
| 89 | internal fun rawPublicKeyBytes(serialized: ByteArray): ByteArray = try { |
| 90 | ECPublicKey(serialized).publicKeyBytes |
| 91 | } catch (_: Throwable) { |
| 92 | serialized |
| 93 | } |
| 94 | internal val ownIdentityPrivate: ByteArray = b64(auth.identityPrivateKey) |
| 95 | private val ownAci: String = auth.aci.ifEmpty { auth.phoneNumber } |
| 96 | private val ownDeviceId: Int = auth.deviceId |
| 97 | |
| 98 | internal val protocolStore: PersistentSignalProtocolStore by lazy { |
| 99 | val ikp = loadIdentityPair(auth.identityPrivateKey, auth.identityPublicKey) |
| 100 | PersistentSignalProtocolStore( |
| 101 | db = db, |
| 102 | identityKeyPair = ikp, |
| 103 | registrationId = auth.registrationId.takeIf { it != 0 } ?: 1, |
| 104 | onIdentityChanged = { address, key -> onIdentityChanged(address.name, key.serialize()) }, |
| 105 | ) |
| 106 | } |
| 107 | |
| 108 | private fun loadIdentityPair(privB64: String, pubB64: String): IdentityKeyPair { |
| 109 | if (privB64.isEmpty() || pubB64.isEmpty()) return IdentityKeyPair.generate() |
| 110 | return try { |
| 111 | val identityKey = IdentityKey(b64(pubB64)) |
| 112 | val privKey = ECPrivateKey(b64(privB64)) |
| 113 | IdentityKeyPair(identityKey, privKey) |
| 114 | } catch (_: Exception) { |
| 115 | IdentityKeyPair.generate() |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * Our own address. |
| 121 | * |
| 122 | * Careful: libsignal orders these two inconsistently — `SessionCipher(store, local, remote)` but |
| 123 | * `SessionBuilder(store, remote, local)`. Kotlin cannot use named arguments for Java constructors, so |
| 124 | * the order at each call site is load-bearing. Getting it wrong looks up the session under our own |
| 125 | * address and fails with a `NoSessionException` naming us rather than the peer. |
| 126 | */ |
| 127 | private fun localAddress(): SignalProtocolAddress = signalAddress(ownAci, ownDeviceId) |
| 128 | |
| 129 | fun signalAddress(aci: String, deviceId: Int = 1): SignalProtocolAddress = |
| 130 | SignalProtocolAddress(aci, deviceId) |
| 131 | |
| 132 | /** |
| 133 | * Whether a usable session exists. Delegates to the same store [encryptDM] uses, so it cannot |
| 134 | * report a session that encryption would then fail to find. |
| 135 | */ |
| 136 | fun hasSession(aci: String, deviceId: Int = 1): Boolean = |
| 137 | try { protocolStore.containsSession(signalAddress(aci, deviceId)) } catch (_: Exception) { false } |
| 138 | |
| 139 | fun deleteSession(aci: String, deviceId: Int = 1) { |
| 140 | try { protocolStore.deleteSession(signalAddress(aci, deviceId)) } catch (_: Exception) {} |
| 141 | } |
| 142 | |
| 143 | /** One encrypted message plus the metadata the send envelope needs alongside it. */ |
| 144 | data class EncResult( |
| 145 | /** A `CiphertextMessage` type, not an `Envelope` type — the numbering spaces differ. */ |
| 146 | val ciphertextType: Int, |
| 147 | val remoteRegistrationId: Int, |
| 148 | val data: ByteArray, |
| 149 | ) |
| 150 | |
| 151 | /** |
| 152 | * Encrypt for an established session. libsignal owns the session record through [protocolStore]; |
| 153 | * a failure propagates rather than falling back to the Rust crate, which serializes sessions in a |
| 154 | * different format and would corrupt the stored record. |
| 155 | */ |
| 156 | fun encryptDM(aci: String, deviceId: Int, paddedPlaintext: ByteArray): EncResult { |
| 157 | // SessionCipher is (local, remote). |
| 158 | val cipher = SessionCipher(protocolStore, localAddress(), signalAddress(aci, deviceId)) |
| 159 | val msg = cipher.encrypt(paddedPlaintext) |
| 160 | return EncResult( |
| 161 | ciphertextType = msg.type, |
| 162 | remoteRegistrationId = cipher.remoteRegistrationId, |
| 163 | data = msg.serialize(), |
| 164 | ) |
| 165 | } |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | /** |
| 172 | * Archive rather than delete: the old chain must stay readable so messages already in flight on it |
| 173 | * can still be decrypted. Returns whether a stored record was actually changed — no-ops for a |
| 174 | * device we hold no session for, which would otherwise materialise an empty record that |
| 175 | * [deviceIdsWithSessions] then reports forever. |
| 176 | */ |
| 177 | fun archiveSession(aci: String, deviceId: Int): Boolean { |
| 178 | if (!runBlocking { db.e2eSessionDao().exists(aci, deviceId) }) return false |
| 179 | return try { |
| 180 | val address = signalAddress(aci, deviceId) |
| 181 | val record = protocolStore.loadSession(address) |
| 182 | record.archiveCurrentState() |
| 183 | protocolStore.storeSession(address, record) |
| 184 | true |
| 185 | } catch (_: Exception) { |
| 186 | false |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | fun decryptDM(aci: String, deviceId: Int, isPreKey: Boolean, ciphertext: ByteArray): ByteArray { |
| 191 | val address = signalAddress(aci, deviceId) |
| 192 | // SessionCipher is (local, remote). |
| 193 | val cipher = SessionCipher(protocolStore, localAddress(), address) |
| 194 | return if (isPreKey) { |
| 195 | val message = PreKeySignalMessage(ciphertext) |
| 196 | // Which of our keys the sender used. A decryption failure here is almost always a mismatch |
| 197 | // between these ids and what the store holds, so name them rather than guessing later. |
| 198 | Log.status( |
| 199 | TAG, |
| 200 | "inbound prekey message from $aci:$deviceId " + |
| 201 | "signedPreKeyId=${message.signedPreKeyId} " + |
| 202 | "preKeyId=${message.preKeyId.orElse(null)} " + |
| 203 | "registrationId=${message.registrationId} " + |
| 204 | "ourRegistrationId=${protocolStore.localRegistrationId} " + |
| 205 | "theirIdentity=${message.identityKey.serialize().size}B", |
| 206 | ) |
| 207 | cipher.decrypt(message) |
| 208 | } else { |
| 209 | cipher.decrypt(org.signal.libsignal.protocol.message.SignalMessage(ciphertext)) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | fun decryptDM(aci: String, deviceId: Int, ciphertext: ByteArray): ByteArray = |
| 214 | decryptDM(aci, deviceId, false, ciphertext) |
| 215 | |
| 216 | /** A peers pre-key bundle parsed off the wire: registration id, pre-keys and identity key. */ |
| 217 | data class ParsedPreKeyBundle( |
| 218 | val registrationId: Int, |
| 219 | val preKeyId: Int?, |
| 220 | val preKeyPublic: ByteArray?, |
| 221 | val signedPreKeyId: Int, |
| 222 | val signedPreKeyPublic: ByteArray, |
| 223 | val signedPreKeySignature: ByteArray, |
| 224 | val identityKey: ByteArray, |
| 225 | val kyberPreKeyId: Int? = null, |
| 226 | val kyberPreKeyPublic: ByteArray? = null, |
| 227 | val kyberPreKeySignature: ByteArray? = null, |
| 228 | ) |
| 229 | |
| 230 | /** |
| 231 | * Build a session from a fetched pre-key bundle. Kyber is mandatory on this protocol version, so |
| 232 | * a bundle without it is rejected rather than downgraded to a non-post-quantum session — the |
| 233 | * official client skips such a device instead. |
| 234 | */ |
| 235 | fun processPreKeyBundle(aci: String, deviceId: Int, bundle: ParsedPreKeyBundle) { |
| 236 | require( |
| 237 | bundle.kyberPreKeyId != null && |
| 238 | bundle.kyberPreKeyPublic != null && |
| 239 | bundle.kyberPreKeySignature != null, |
| 240 | ) { "pre-key bundle for $aci:$deviceId has no Kyber pre-key" } |
| 241 | val address = signalAddress(aci, deviceId) |
| 242 | val ecPreKey: ECPublicKey? = bundle.preKeyPublic?.let { ECPublicKey(it) } |
| 243 | val signedEc = ECPublicKey(bundle.signedPreKeyPublic) |
| 244 | val identity = IdentityKey(bundle.identityKey) |
| 245 | val kyberPub = KEMPublicKey(bundle.kyberPreKeyPublic) |
| 246 | val preKeyBundle = PreKeyBundle( |
| 247 | bundle.registrationId, |
| 248 | deviceId, |
| 249 | bundle.preKeyId ?: PreKeyBundle.NULL_PRE_KEY_ID, |
| 250 | ecPreKey, |
| 251 | bundle.signedPreKeyId, |
| 252 | signedEc, |
| 253 | bundle.signedPreKeySignature, |
| 254 | identity, |
| 255 | bundle.kyberPreKeyId, |
| 256 | kyberPub, |
| 257 | bundle.kyberPreKeySignature, |
| 258 | ) |
| 259 | // SessionBuilder writes the real session record through the store; nothing else should. |
| 260 | // SessionBuilder is (remote, local) — the opposite of SessionCipher. |
| 261 | SessionBuilder(protocolStore, address, localAddress()).process(preKeyBundle) |
| 262 | } |
| 263 | |
| 264 | fun markKyberPreKeyUsed(kyberId: Int, signedEcId: Int, baseKey: ByteArray) { |
| 265 | try { |
| 266 | val ecPub = ECPublicKey(baseKey) |
| 267 | protocolStore.markKyberPreKeyUsed(kyberId, signedEcId, ecPub) |
| 268 | } catch (_: Exception) { |
| 269 | RustSignalCrypto.markKyberPreKeyUsed(kyberId, signedEcId, baseKey) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * Sender keys, via libsignal. |
| 275 | * |
| 276 | * Previously these went through a bespoke Rust ratchet whose records shared the `signal_e2e_sender_keys` |
| 277 | * table with libsignal's `SenderKeyStore` but used a different serialization and a different key (the group |
| 278 | * id rather than the distribution UUID). Only libsignal's format interoperates with real Signal clients, |
| 279 | * and `SealedSessionCipher` already dispatches inbound `SENDERKEY_TYPE` through `GroupCipher` using this |
| 280 | * same store — so using it here is what makes group traffic decrypt at all. |
| 281 | */ |
| 282 | fun createSenderKeyDistribution(distributionId: UUID): ByteArray = |
| 283 | GroupSessionBuilder(protocolStore).create(localAddress(), distributionId).serialize() |
| 284 | |
| 285 | /** |
| 286 | * Store a peer's sender key. The distribution id comes from the message itself, not from the group: each |
| 287 | * sender picks their own, and a recipient must file it under the sender's. |
| 288 | */ |
| 289 | fun processSenderKeyDistribution(senderAci: String, senderDeviceId: Int, skdmBytes: ByteArray) { |
| 290 | val skdm = SenderKeyDistributionMessage(skdmBytes) |
| 291 | GroupSessionBuilder(protocolStore).process(signalAddress(senderAci, senderDeviceId), skdm) |
| 292 | } |
| 293 | |
| 294 | /** Encrypt once for the whole group. The result is a `SenderKeyMessage`. */ |
| 295 | fun encryptGroup(distributionId: UUID, paddedPlaintext: ByteArray): EncResult { |
| 296 | val message = GroupCipher(protocolStore, localAddress()).encrypt(distributionId, paddedPlaintext) |
| 297 | return EncResult( |
| 298 | ciphertextType = message.type, |
| 299 | remoteRegistrationId = 0, |
| 300 | data = message.serialize(), |
| 301 | ) |
| 302 | } |
| 303 | |
| 304 | /** |
| 305 | * Decrypt a group message from [senderAci]. |
| 306 | * |
| 307 | * Rarely needed directly: real group traffic arrives sealed, and `SealedSessionCipher` unwraps |
| 308 | * `SENDERKEY_TYPE` itself. This covers an unsealed sender-key message. |
| 309 | */ |
| 310 | fun decryptGroup(senderAci: String, senderDeviceId: Int, ciphertext: ByteArray): ByteArray = |
| 311 | GroupCipher(protocolStore, signalAddress(senderAci, senderDeviceId)).decrypt(ciphertext) |
| 312 | |
| 313 | /** Sealed-sender encrypt. Returns the message plus the registration id the envelope needs. */ |
| 314 | fun sealedSenderEncrypt( |
| 315 | recipientAci: String, |
| 316 | recipientDeviceId: Int, |
| 317 | paddedPlaintext: ByteArray, |
| 318 | senderCertificate: SenderCertificate, |
| 319 | ): EncResult { |
| 320 | val address = signalAddress(recipientAci, recipientDeviceId) |
| 321 | val localUuid = try { UUID.fromString(ownAci) } catch (_: Exception) { UUID.randomUUID() } |
| 322 | val cipher = SealedSessionCipher(protocolStore, localUuid, null, ownDeviceId) |
| 323 | val encrypted = cipher.encrypt(address, senderCertificate, paddedPlaintext) |
| 324 | return EncResult( |
| 325 | // Sealed sender is its own envelope type; the inner ciphertext type is not exposed. |
| 326 | ciphertextType = SEALED_SENDER_TYPE, |
| 327 | remoteRegistrationId = cipher.getRemoteRegistrationId(address), |
| 328 | data = encrypted, |
| 329 | ) |
| 330 | } |
| 331 | |
| 332 | fun sealedSenderDecrypt( |
| 333 | ciphertext: ByteArray, |
| 334 | trustRoots: List<ECPublicKey>, |
| 335 | timestampMs: Long = System.currentTimeMillis()): ByteArray { |
| 336 | val validator = CertificateValidator(trustRoots) |
| 337 | val localUuid = try { UUID.fromString(ownAci) } catch (_: Exception) { UUID.randomUUID() } |
| 338 | val cipher = SealedSessionCipher(protocolStore, localUuid, null, ownDeviceId) |
| 339 | val result = cipher.decrypt(validator, ciphertext, timestampMs) |
| 340 | return result.paddedMessage |
| 341 | } |
| 342 | |
| 343 | /** |
| 344 | * What needs registering with the server after [ensureLocalPreKeys]. |
| 345 | * |
| 346 | * Keys are the serialized public halves; signatures are over those, by our identity key. |
| 347 | */ |
| 348 | data class PreKeyUpload( |
| 349 | val signedPreKey: KeyEntity?, |
| 350 | val lastResortKyber: KeyEntity?, |
| 351 | val oneTimeEcPreKeys: List<KeyEntity>, |
| 352 | ) { |
| 353 | /** One pre-key to upload: id, public key and signature (signed/Kyber keys only). */ |
| 354 | data class KeyEntity(val id: Int, val publicKey: ByteArray, val signature: ByteArray? = null) |
| 355 | |
| 356 | val isEmpty: Boolean |
| 357 | get() = signedPreKey == null && lastResortKyber == null && oneTimeEcPreKeys.isEmpty() |
| 358 | } |
| 359 | |
| 360 | |
| 361 | fun ensureSignedPreKeyStored() { |
| 362 | ensureLocalPreKeys() |
| 363 | } |
| 364 | |
| 365 | fun markPreKeysUploaded() { |
| 366 | val maxId = runBlocking { db.e2ePreKeyDao().getMaxId() } |
| 367 | runBlocking { db.e2ePreKeyDao().markUploadedUpTo(maxId) } |
| 368 | } |
| 369 | |
| 370 | private data class LocalPreKey(val id: Int, val publicKey: ByteArray) |
| 371 | |
| 372 | private fun generatePreKeys(count: Int): List<LocalPreKey> { |
| 373 | val maxId = runBlocking { db.e2ePreKeyDao().getMaxId() } |
| 374 | val entities = ArrayList<SignalE2EPreKey>(count) |
| 375 | val locals = ArrayList<LocalPreKey>(count) |
| 376 | for (i in 1..count) { |
| 377 | val id = maxId + i |
| 378 | val kp = RustSignalCrypto.generateKeyPairSplit() |
| 379 | val record = kp.privateKey + kp.publicKey |
| 380 | entities.add(SignalE2EPreKey(id, record, uploaded = false)) |
| 381 | locals.add(LocalPreKey(id, kp.publicKey)) |
| 382 | } |
| 383 | runBlocking { db.e2ePreKeyDao().insertAll(entities) } |
| 384 | return locals |
| 385 | } |
| 386 | |
| 387 | /** Pre-key replenishment thresholds and logging tag for [SignalE2E]. */ |
| 388 | companion object { |
| 389 | internal const val TAG = "SignalE2E" |
| 390 | |
| 391 | /** Regenerate one-time pre-keys once the store dips below this. */ |
| 392 | internal const val ONE_TIME_PREKEY_FLOOR = 10 |
| 393 | internal const val ONE_TIME_PREKEY_BATCH = 100 |
| 394 | |
| 395 | /** |
| 396 | * Marker for "this ciphertext is a sealed-sender message", mapped to `Envelope.UNIDENTIFIED_SENDER`. |
| 397 | * Not a `CiphertextMessage` constant — those describe the inner message, which sealed sender wraps. |
| 398 | */ |
| 399 | const val SEALED_SENDER_TYPE = -1 |
| 400 | internal fun b64(s: String): ByteArray = if (s.isEmpty()) ByteArray(0) else Base64.Default.decode(s) |
| 401 | |
| 402 | internal fun signSignedPreKey(identityPrivate32: ByteArray, signedPreKeyPublic32: ByteArray): ByteArray { |
| 403 | val priv = ECPrivateKey(identityPrivate32) |
| 404 | return priv.calculateSignature(signedPreKeyPublic32) |
| 405 | } |
| 406 | } |
| 407 | } |