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 / SignalE2EPreKeys.kt
SignalE2EPreKeys.kt141 lines · 6.5 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal.e2e |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E.Companion.ONE_TIME_PREKEY_BATCH |
| 5 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E.Companion.ONE_TIME_PREKEY_FLOOR |
| 6 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E.Companion.b64 |
| 7 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E.Companion.signSignedPreKey |
| 8 | import kotlinx.coroutines.runBlocking |
| 9 | import org.signal.libsignal.protocol.ecc.ECKeyPair |
| 10 | import org.signal.libsignal.protocol.ecc.ECPrivateKey |
| 11 | import org.signal.libsignal.protocol.ecc.ECPublicKey |
| 12 | import org.signal.libsignal.protocol.kem.KEMKeyPair |
| 13 | import org.signal.libsignal.protocol.kem.KEMKeyType |
| 14 | import org.signal.libsignal.protocol.state.KyberPreKeyRecord |
| 15 | import org.signal.libsignal.protocol.state.PreKeyRecord |
| 16 | import org.signal.libsignal.protocol.state.SignedPreKeyRecord |
| 17 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E.PreKeyUpload |
| 18 | |
| 19 | private const val X25519_POINT_LEN = 32 |
| 20 | |
| 21 | /** |
| 22 | * Pre-key lifecycle for [SignalE2E] (split for file length). |
| 23 | * Internal functions on [SignalE2E]; behavior identical, call sites unchanged. |
| 24 | */ |
| 25 | |
| 26 | internal fun SignalE2E.ensureLocalPreKeys(): PreKeyUpload { |
| 27 | val signed = ensureSignedPreKey() |
| 28 | val kyber = ensureLastResortKyberPreKey() |
| 29 | val oneTime = ensureOneTimePreKeys() |
| 30 | return PreKeyUpload(signedPreKey = signed, lastResortKyber = kyber, oneTimeEcPreKeys = oneTime) |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Returns a payload when the signed pre-key had to be regenerated and needs registering, null when the |
| 35 | * stored one was sound and simply seeded. |
| 36 | */ |
| 37 | internal fun SignalE2E.ensureSignedPreKey(): PreKeyUpload.KeyEntity? { |
| 38 | val storedId = auth.signedPreKeyId |
| 39 | if (storedId != 0 && protocolStore.containsSignedPreKey(storedId)) return null |
| 40 | if (storedId != 0 && seedStoredSignedPreKey(storedId)) return null |
| 41 | return rotateSignedPreKey() |
| 42 | } |
| 43 | |
| 44 | /** True when the stored material verified and was seeded into the store. */ |
| 45 | internal fun SignalE2E.seedStoredSignedPreKey(id: Int): Boolean { |
| 46 | val pub = b64(auth.signedPreKeyPublic) |
| 47 | val priv = b64(auth.signedPreKeyPrivate) |
| 48 | val signature = b64(auth.signedPreKeySignature) |
| 49 | if (pub.isEmpty() || priv.isEmpty()) { |
| 50 | Log.status(SignalE2E.TAG, "no stored signed pre-key material; rotating") |
| 51 | return false |
| 52 | } |
| 53 | return try { |
| 54 | val privateKey = ECPrivateKey(priv) |
| 55 | val derivedPublic = RustSignalCrypto.publicFromPrivate(priv) |
| 56 | if (derivedPublic == null) { |
| 57 | Log.status(SignalE2E.TAG, "could not derive public half for signed pre-key $id; rotating") |
| 58 | return false |
| 59 | } |
| 60 | // ECPublicKey.serialize() is 0x05-prefixed (33B) while publicFromPrivate returns the raw |
| 61 | // 32B point; compare the trailing point bytes so the two serializations line up. |
| 62 | if (!derivedPublic.takeLast(X25519_POINT_LEN).toByteArray() |
| 63 | .contentEquals(pub.takeLast(X25519_POINT_LEN).toByteArray())) { |
| 64 | // The server serves the public half; without the matching private half every inbound |
| 65 | // pre-key message fails in the key agreement rather than at lookup. |
| 66 | Log.status( |
| 67 | SignalE2E.TAG, |
| 68 | "stored signed pre-key $id is inconsistent (private half derives a different public key); rotating") |
| 69 | return false |
| 70 | } |
| 71 | val identityOk = signature.isNotEmpty() && |
| 72 | ECPublicKey(ownIdentityPublicKey).verifySignature(pub, signature) |
| 73 | if (!identityOk) { |
| 74 | Log.status( |
| 75 | SignalE2E.TAG, |
| 76 | "stored signed pre-key $id signature does not verify under our identity key; rotating") |
| 77 | return false |
| 78 | } |
| 79 | protocolStore.storeSignedPreKey( |
| 80 | id, |
| 81 | SignedPreKeyRecord(id, System.currentTimeMillis(), ECKeyPair(ECPublicKey(pub), privateKey), signature), |
| 82 | ) |
| 83 | Log.status(SignalE2E.TAG, "seeded signed pre-key $id into the protocol store") |
| 84 | true |
| 85 | } catch (expected: Throwable) { |
| 86 | Log.status(SignalE2E.TAG, "could not rebuild signed pre-key $id; rotating", expected) |
| 87 | false |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | internal fun SignalE2E.rotateSignedPreKey(): PreKeyUpload.KeyEntity? = try { |
| 92 | val keyPair = ECKeyPair.generate() |
| 93 | val publicKey = keyPair.publicKey.serialize() |
| 94 | val signature = signSignedPreKey(ownIdentityPrivate, publicKey) |
| 95 | val id = auth.signedPreKeyId.takeIf { it != 0 }?.plus(1) ?: 1 |
| 96 | protocolStore.storeSignedPreKey( |
| 97 | id, |
| 98 | SignedPreKeyRecord(id, System.currentTimeMillis(), keyPair, signature), |
| 99 | ) |
| 100 | Log.status(SignalE2E.TAG, "rotated signed pre-key to $id; needs registering") |
| 101 | PreKeyUpload.KeyEntity(id, publicKey, signature) |
| 102 | } catch (expected: Throwable) { |
| 103 | Log.error(SignalE2E.TAG, "could not rotate the signed pre-key", expected) |
| 104 | null |
| 105 | } |
| 106 | |
| 107 | internal fun SignalE2E.ensureLastResortKyberPreKey(): PreKeyUpload.KeyEntity? { |
| 108 | val existing = runBlocking { db.e2eKyberPreKeyDao().getAll() } |
| 109 | if (existing.any { it.lastResort }) return null |
| 110 | return try { |
| 111 | val keyPair = KEMKeyPair.generate(KEMKeyType.KYBER_1024) |
| 112 | val publicKey = keyPair.publicKey.serialize() |
| 113 | val signature = signSignedPreKey(ownIdentityPrivate, publicKey) |
| 114 | val id = (runBlocking { db.e2eKyberPreKeyDao().getAll() }.maxOfOrNull { it.id } ?: 0) + 1 |
| 115 | val record = KyberPreKeyRecord(id, System.currentTimeMillis(), keyPair, signature) |
| 116 | protocolStore.storeKyberPreKey(id, record, lastResort = true) |
| 117 | Log.status(SignalE2E.TAG, "generated last-resort Kyber pre-key $id; needs registering") |
| 118 | PreKeyUpload.KeyEntity(id, publicKey, signature) |
| 119 | } catch (expected: Throwable) { |
| 120 | Log.status(SignalE2E.TAG, "could not generate a last-resort Kyber pre-key", expected) |
| 121 | null |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | internal fun SignalE2E.ensureOneTimePreKeys(): List<PreKeyUpload.KeyEntity> { |
| 126 | val have = runBlocking { db.e2ePreKeyDao().getAll() }.size |
| 127 | if (have >= ONE_TIME_PREKEY_FLOOR) return emptyList() |
| 128 | val maxId = runBlocking { db.e2ePreKeyDao().getMaxId() } |
| 129 | return (1..ONE_TIME_PREKEY_BATCH).mapNotNull { offset -> |
| 130 | val id = maxId + offset |
| 131 | try { |
| 132 | val keyPair = ECKeyPair.generate() |
| 133 | // Stored through the store so it lands as a libsignal record, not a bespoke blob. |
| 134 | protocolStore.storePreKey(id, PreKeyRecord(id, keyPair)) |
| 135 | PreKeyUpload.KeyEntity(id, keyPair.publicKey.serialize()) |
| 136 | } catch (expected: Throwable) { |
| 137 | Log.status(SignalE2E.TAG, "could not generate one-time pre-key $id", expected) |
| 138 | null |
| 139 | } |
| 140 | } |
| 141 | } |