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 / whatsapp / WhatsAppProtocol.kt

WhatsAppProtocol.kt449 lines · 17.6 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import java.nio.ByteBuffer
4import java.nio.ByteOrder
5import java.security.MessageDigest
6import javax.crypto.Cipher
7import javax.crypto.Mac
8import javax.crypto.spec.GCMParameterSpec
9import javax.crypto.spec.SecretKeySpec
10import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto
11
12/**
13 * WhatsApp Web protocol implementation.
14 * Implements Noise_XX_25519_AESGCM_SHA256 handshake, binary XML encoding,
15 * protobuf E2E message format, and media encryption.
16 *
17 * Reference: whatsmeow (github.com/tulir/whatsmeow)
18 */
19object WhatsAppProtocol {
20 internal const val TAG = "WhatsAppProtocol"
21
22 // NOTE: Companion-web endpoints (WS_URL/WS_ORIGIN → web.whatsapp.com) were removed here.
23 // The primary client connects over a raw Noise socket to g.whatsapp.net — see
24 // data/whatsapp/transport/WhatsAppSocket.kt. Do not reintroduce the WebSocket URL.
25
26 // Noise protocol pattern — 32 bytes, null-padded
27 const val NOISE_START_PATTERN = "Noise_XX_25519_AESGCM_SHA256\u0000\u0000\u0000\u0000"
28
29 // WA connection header: 'W', 'A', WAMagicValue(6), DictVersion(3)
30 val WA_CONN_HEADER = byteArrayOf('W'.code.toByte(), 'A'.code.toByte(), 6, 3)
31
32 // Frame constants (from whatsmeow/socket/constants.go)
33 const val FRAME_MAX_SIZE = 1 shl 24
34 const val FRAME_LENGTH_SIZE = 3
35
36 // WhatsApp web message ID prefix
37 internal const val WEB_MESSAGE_ID_PREFIX = "3EB0"
38
39 // WhatsApp Android app version — PINNED to the extracted APK
40 // (apk-analysis/whatsapp: versionName 2.26.29.73, versionCode 262907320).
41 // The registration `token` attestation binds this exact version + classes.dex MD5 +
42 // signing cert, so WA_VERSION, the pinned signature, and the dex MD5 must all come from
43 // the SAME APK build. Used by the primary ClientPayload (PrimaryClientPayload.kt).
44 val WA_VERSION = intArrayOf(2, 26, 29, 73)
45 const val WA_VERSION_NAME = "2.26.29.73"
46 const val WA_VERSION_CODE = 262907320
47
48 // Media type keys for HKDF (from whatsmeow/download.go)
49 const val MEDIA_KEY_IMAGE = "WhatsApp Image Keys"
50 const val MEDIA_KEY_VIDEO = "WhatsApp Video Keys"
51 const val MEDIA_KEY_AUDIO = "WhatsApp Audio Keys"
52 const val MEDIA_KEY_DOCUMENT = "WhatsApp Document Keys"
53 const val MEDIA_KEY_STICKER = "WhatsApp Image Keys"
54 const val MEDIA_KEY_PTV = "WhatsApp Video Keys"
55 const val MEDIA_KEY_HISTORY = "WhatsApp History Keys"
56 const val MEDIA_KEY_APP_STATE = "WhatsApp App State Keys"
57 const val MEDIA_KEY_STICKER_PACK = "WhatsApp Sticker Pack Keys"
58 const val MEDIA_KEY_LINK_THUMBNAIL = "WhatsApp Link Thumbnail Keys"
59
60 // WhatsApp certificate authority public key (Ed25519)
61 val WA_CERT_PUBKEY = byteArrayOf(
62 0x14, 0x23, 0x75, 0x57, 0x4d, 0x0a, 0x58, 0x71,
63 0x66, 0xaa.toByte(), 0xe7.toByte(), 0x1e, 0xbe.toByte(), 0x51, 0x64, 0x37,
64 0xc4.toByte(), 0xa2.toByte(), 0x8b.toByte(), 0x73, 0xe3.toByte(), 0x69, 0x5c, 0x6c,
65 0xe1.toByte(), 0xf7.toByte(), 0xf9.toByte(), 0x54, 0x5d, 0xa8.toByte(), 0xee.toByte(), 0x6b
66 )
67
68 /** One node of the WhatsApp binary XML (binary stanza) tree: tag, attributes and children. */
69 data class Node(
70 val tag: String,
71 val attrs: Map<String, String> = emptyMap(),
72 val content: List<Node> = emptyList(),
73 val data: ByteArray? = null,
74 ) {
75 override fun equals(other: Any?): Boolean {
76 if (this === other) return true
77 if (javaClass != other?.javaClass) return false
78 other as Node
79 if (tag != other.tag) return false
80 if (attrs != other.attrs) return false
81 if (content != other.content) return false
82 if (data != null) {
83 if (other.data == null) return false
84 if (!data.contentEquals(other.data)) return false
85 } else if (other.data != null) return false
86 return true
87 }
88
89 override fun hashCode(): Int {
90 var result = tag.hashCode()
91 result = 31 * result + attrs.hashCode()
92 result = 31 * result + content.hashCode()
93 result = 31 * result + (data?.contentHashCode() ?: 0)
94 return result
95 }
96
97 fun getChildren(): List<Node> = content
98
99 fun getChildByTag(tag: String): Node? = content.find { it.tag == tag }
100 }
101
102 /**
103 * Noise Protocol Handshake State Machine
104 * Implements Noise_XX_25519_AESGCM_SHA256 as per whatsmeow/socket/noisehandshake.go
105 */
106 class NoiseHandshake {
107 /** Noise handshake constants (hash and AEAD sizes) for [WhatsAppProtocol.NoiseHandshake]. */
108 companion object {
109 private const val HASH_SIZE = 32
110 private const val EXPANDED_SIZE = 64
111 private const val GCM_IV_OFFSET = 8
112 private const val GCM_IV_LENGTH = 4
113 }
114 private var hash = ByteArray(32)
115 private var salt = ByteArray(32)
116 private var key: SecretKeySpec? = null
117 private var counter: UInt = 0u
118
119 fun start(pattern: String, header: ByteArray) {
120 val data = pattern.toByteArray(Charsets.UTF_8)
121 hash = if (data.size == HASH_SIZE) {
122 data
123 } else {
124 sha256(data)
125 }
126 salt = hash.copyOf()
127 key = SecretKeySpec(hash, "AES")
128 authenticate(header)
129 }
130
131 fun authenticate(data: ByteArray) {
132 hash = sha256(hash + data)
133 }
134
135 fun encrypt(plaintext: ByteArray): ByteArray {
136 val currentKey = key ?: throw IllegalStateException("Handshake not started")
137 val iv = generateIV(counter)
138 counter++
139
140 val cipher = Cipher.getInstance("AES/GCM/NoPadding")
141 val spec = GCMParameterSpec(128, iv)
142 cipher.init(Cipher.ENCRYPT_MODE, currentKey, spec)
143 cipher.updateAAD(hash)
144 val ciphertext = cipher.doFinal(plaintext)
145 authenticate(ciphertext)
146 return ciphertext
147 }
148
149 fun decrypt(ciphertext: ByteArray): ByteArray {
150 val currentKey = key ?: throw IllegalStateException("Handshake not started")
151 val iv = generateIV(counter)
152 counter++
153
154 val cipher = Cipher.getInstance("AES/GCM/NoPadding")
155 val spec = GCMParameterSpec(128, iv)
156 cipher.init(Cipher.DECRYPT_MODE, currentKey, spec)
157 cipher.updateAAD(hash)
158 val plaintext = cipher.doFinal(ciphertext)
159 authenticate(ciphertext)
160 return plaintext
161 }
162
163 fun mixSharedSecretIntoKey(privateKey: ByteArray, publicKey: ByteArray) {
164 val sharedSecret = x25519(privateKey, publicKey)
165 mixIntoKey(sharedSecret)
166 }
167
168 fun mixIntoKey(data: ByteArray) {
169 counter = 0u
170 val (newSalt, newKey) = extractAndExpand(salt, data)
171 salt = newSalt
172 key = SecretKeySpec(newKey, "AES")
173 }
174
175 private fun extractAndExpand(salt: ByteArray, data: ByteArray): Pair<ByteArray, ByteArray> {
176 val out = hkdfSha256(data, salt, ByteArray(0), EXPANDED_SIZE)
177 return Pair(out.copyOfRange(0, HASH_SIZE), out.copyOfRange(HASH_SIZE, EXPANDED_SIZE))
178 }
179
180 fun finish(): Pair<SecretKeySpec, SecretKeySpec> {
181 val (writeKey, readKey) = extractAndExpand(salt, ByteArray(0))
182 return Pair(
183 SecretKeySpec(writeKey, "AES"),
184 SecretKeySpec(readKey, "AES")
185 )
186 }
187
188 private fun generateIV(counter: UInt): ByteArray {
189 val iv = ByteArray(12)
190
191 ByteBuffer.wrap(iv, GCM_IV_OFFSET, GCM_IV_LENGTH)
192 .order(ByteOrder.BIG_ENDIAN)
193 .putInt(counter.toInt())
194 return iv
195 }
196 }
197
198// -- Cryptography primitives (NoiseHandshake + derived helpers depend on these; higher-level
199 // consumers live in WhatsAppProtocol* extension files). --
200
201 // X25519 via Rust (constant-time x25519-dalek through libwhatsapp_signal.so).
202 // Falls back to throwing if Rust lib unavailable — pairing/connect requires keys.
203 fun x25519(privateKey: ByteArray, publicKey: ByteArray): ByteArray {
204 return RustWhatsAppCrypto.x25519Agreement(privateKey, publicKey)
205 ?: throw IllegalStateException("RustWhatsAppCrypto.x25519Agreement returned null")
206 }
207
208 fun generateX25519KeyPair(): Pair<ByteArray, ByteArray> {
209 val kp = RustWhatsAppCrypto.generateKeyPairSplit()
210 return Pair(kp.privateKey, kp.publicKey)
211 }
212
213 /** HKDF-SHA256 (RFC 5869) on the platform Mac. null/empty salt = zero salt. */
214 internal fun hkdfSha256(ikm: ByteArray, salt: ByteArray?, info: ByteArray, length: Int): ByteArray {
215 val actualSalt = if (salt == null || salt.isEmpty()) ByteArray(32) else salt
216 val prk = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(actualSalt, "HmacSHA256")) }.doFinal(ikm)
217 val out = ByteArray(length)
218 var t = ByteArray(0)
219 var pos = 0
220 var counter = 1
221 while (pos < length) {
222 val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(prk, "HmacSHA256")) }
223 mac.update(t); mac.update(info); mac.update(counter.toByte())
224 t = mac.doFinal()
225 val n = minOf(t.size, length - pos)
226 System.arraycopy(t, 0, out, pos, n)
227 pos += n; counter++
228 }
229 return out
230 }
231
232 fun sha256(data: ByteArray): ByteArray {
233 val digest = MessageDigest.getInstance("SHA-256")
234 return digest.digest(data)
235 }
236
237 fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray {
238 val mac = Mac.getInstance("HmacSHA256")
239 val keySpec = SecretKeySpec(key, "HmacSHA256")
240 mac.init(keySpec)
241 return mac.doFinal(data)
242 }
243
244 /** The key material split out of a media key: IV, cipher key and MAC key. */
245 data class MediaKeys(
246 val iv: ByteArray,
247 val cipherKey: ByteArray,
248 val macKey: ByteArray,
249 val refKey: ByteArray,
250 )
251
252 /** The result of encrypting media for upload: media key, ciphertext and hashes. */
253 data class MediaEncryptResult(
254 val mediaKey: ByteArray,
255 val encryptedData: ByteArray,
256 val fileSha256: ByteArray,
257 val fileEncSha256: ByteArray,
258 val fileLength: Long,
259 )
260
261 // -- Binary XML encoding/decoding (codec lives in WhatsAppProtocolBinary.kt; token tables stay here) --
262
263 internal object BinaryToken {
264 const val LIST_EMPTY: Byte = 0
265 const val DICTIONARY_0: Int = 236
266 const val DICTIONARY_1: Int = 237
267 const val DICTIONARY_2: Int = 238
268 const val DICTIONARY_3: Int = 239
269 const val LIST_8: Byte = 248.toByte()
270 const val LIST_16: Byte = 249.toByte()
271 const val JID_PAIR: Byte = 250.toByte()
272 const val HEX_8: Int = 251
273 const val BINARY_8: Byte = 252.toByte()
274 const val BINARY_20: Byte = 253.toByte()
275 const val BINARY_32: Byte = 254.toByte()
276 const val NIBBLE_8: Int = 255
277 const val PACKED_MAX = 127
278 const val SINGLE_BYTE_MAX = 256
279
280 val doubleByteTokens: Array<Array<String>> = BinaryTokenTables.doubleByteTokens
281
282 private val doubleByteIndex: Map<String, Pair<Byte, Byte>> by lazy {
283 val map = HashMap<String, Pair<Byte, Byte>>()
284 for (dictIdx in doubleByteTokens.indices) {
285 for (tokenIdx in doubleByteTokens[dictIdx].indices) {
286 val token = doubleByteTokens[dictIdx][tokenIdx]
287 if (token.isNotEmpty()) {
288 map[token] = Pair(dictIdx.toByte(), tokenIdx.toByte())
289 }
290 }
291 }
292 map
293 }
294
295 const val INTEROP_JID: Int = 245
296 const val FB_JID: Int = 246
297 const val AD_JID: Int = 247
298
299 val singleByteTokens: Array<String> = BinaryTokenSingle.singleByteTokens
300 private val singleByteIndex: Map<String, Byte> by lazy {
301 val map = HashMap<String, Byte>(singleByteTokens.size)
302 for (i in singleByteTokens.indices) {
303 if (singleByteTokens[i].isNotEmpty()) {
304 map[singleByteTokens[i]] = i.toByte()
305 }
306 }
307 map
308 }
309
310 private const val BYTE_MASK = 0xFF
311
312 fun indexOfSingleToken(token: String): Int {
313 return singleByteIndex[token]?.toInt()?.and(BYTE_MASK) ?: -1
314 }
315
316 fun indexOfDoubleByteToken(token: String): Triple<Int, Int, Boolean> {
317 val pair = doubleByteIndex[token] ?: return Triple(0, 0, false)
318 return Triple(pair.first.toInt() and BYTE_MASK, pair.second.toInt() and BYTE_MASK, true)
319 }
320
321 fun getDoubleToken(dictIndex: Int, tokenIndex: Int): String {
322 if (dictIndex < 0 || dictIndex >= doubleByteTokens.size) return ""
323 if (tokenIndex < 0 || tokenIndex >= doubleByteTokens[dictIndex].size) return ""
324 return doubleByteTokens[dictIndex][tokenIndex]
325 }
326 }
327
328 // Binary codec (BinaryEncoder/BinaryDecoder) lives in WhatsAppProtocolBinary.kt.
329
330 // (encodeNode/decodeNode, cert verification, frame unpacking and frame helpers
331 // live in WhatsAppProtocolBinary.kt.)
332
333 // -- Message node builders live in WhatsAppProtocolBuilders.kt /
334 // WhatsAppProtocolBuilders2.kt (same package, extension functions). --
335
336 /** One fan-out copy of a group message, encrypted for a single device. */
337 data class ParticipantEnc(val deviceJid: String, val encType: String, val ciphertext: ByteArray)
338
339 // (buildFanOutMessageNode, retry receipts, queries, reactions — see Builders files.)
340
341 // (receipt/media builders — see WhatsAppProtocolBuilders.kt.)
342
343 // -- Rich send content (mentions / quoted reply / link preview) --------------------------------
344
345 /** A quoted-reply context: the stanza id of the message being replied to, the sender of that
346 * message (participant), and (best-effort) the quoted message's proto for the preview. */
347 data class QuotedContext(
348 val stanzaId: String,
349 val participant: String,
350 val quotedMessage: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message? = null,
351 )
352
353 /** A URL link-preview attached to an ExtendedTextMessage. */
354 data class LinkPreview(
355 val matchedText: String,
356 val canonicalUrl: String,
357 val title: String? = null,
358 val description: String? = null,
359 val jpegThumbnail: ByteArray? = null,
360 )
361
362 // (buildContextInfo/buildTextProto — see WhatsAppProtocolBuilders2.kt.)
363
364 // (buildEditProto/buildRevokeProto/presence/keepalive/ack — see
365 // WhatsAppProtocolBuilders2.kt; frame helpers — see WhatsAppProtocolBinary.kt.)
366
367 // -- Message parsing (see WhatsAppProtocolParsing.kt) --
368 // (formatDisappearingTimer/extractContextInfo live there as private extensions.)
369 // (Poll/location/contact/disappearing/group builders — see WhatsAppProtocolBuilders2.kt;
370 // poll-vote crypto — see WhatsAppProtocolCrypto.kt.)
371
372 // (WA formatting, type/body helpers, parseMessage — see WhatsAppProtocolParsing.kt.)
373
374}
375
376/** A parsed incoming WhatsApp message stanza, flattened for the repository. */
377data class WhatsAppMessage(
378 val id: String,
379 val from: String,
380 val to: String,
381 val body: String,
382 val timestamp: Long,
383 val type: String,
384 val participant: String? = null,
385 val mediaUrl: String? = null,
386 val isReaction: Boolean = false,
387 val reactionTargetId: String? = null,
388 val isRevoke: Boolean = false,
389 val revokeTargetId: String? = null,
390 val isEdit: Boolean = false,
391 val editTargetId: String? = null,
392 val messageType: String = "unknown",
393 val locationData: LocationData? = null,
394 val contactData: ContactData? = null,
395 val pollData: PollData? = null,
396 val groupInviteData: GroupInviteMeta? = null,
397 val disappearingTimer: Long? = null,
398 val isForwarded: Boolean = false,
399 val forwardingScore: Int = 0,
400 val replyToId: String? = null,
401 val mentionedJids: List<String> = emptyList(),
402 val isViewOnce: Boolean = false,
403 val isHD: Boolean = false,
404 /** True when this message was sent by the local user from another linked
405 * device (DeviceSentMessage / own-JID echo). Lets the client render it as
406 * outgoing instead of an incoming (or blank) bubble. */
407 val isFromMe: Boolean = false,
408 val e2eMessage: com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto.Message? = null,
409)
410
411/** A shared location: coordinates plus optional place name/address. */
412data class LocationData(
413 val latitude: Double = 0.0,
414 val longitude: Double = 0.0,
415 val name: String? = null,
416 val address: String? = null,
417 val url: String? = null,
418 val isLive: Boolean = false,
419) {
420 fun toGeoUri(): String = "geo:%.5f,%.5f".format(latitude, longitude)
421 fun toMapsUrl(): String = "https://maps.google.com/?q=%.5f,%.5f".format(latitude, longitude)
422}
423
424/** A shared contact card: display name and vCard payload. */
425data class ContactData(
426 val displayName: String = "",
427 val vcard: String = "",
428)
429
430/** A poll: question, options and how many options may be picked. */
431data class PollData(
432 val question: String = "",
433 val options: List<String> = emptyList(),
434 val selectableOptionCount: Int = 0,
435 val isPollVote: Boolean = false,
436 val pollCreationMessageKey: String? = null,
437 val encPayload: List<ByteArray>? = null,
438) {
439 /** Factories for WhatsApp protocol values. */
440 companion object
441}
442
443/** The context info extracted from a message: forwarding, reply and mention metadata. */
444data class ContextInfoResult(
445 val isForwarded: Boolean = false,
446 val forwardingScore: Int = 0,
447 val replyToId: String? = null,
448 val mentionedJids: List<String> = emptyList(),
449)