Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppProtocolBinary.kt
WhatsAppProtocolBinary.kt562 lines · 21.4 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.BinaryToken |
| 5 | import com.vayunmathur.communicate.data.whatsapp.WhatsAppProtocol.Node |
| 6 | import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppCertProto |
| 7 | import com.vayunmathur.communicate.data.whatsapp.proto.WhatsAppE2EProto |
| 8 | import org.signal.libsignal.protocol.ecc.ECPublicKey |
| 9 | |
| 10 | // -- Binary XML codec (whatsmeow binary/encoder.go + binary/decoder.go) -- |
| 11 | // Token tables live in core (WhatsAppProtocol.BinaryToken); the stateful |
| 12 | // encoder/decoder are file-private here and exposed via encodeNode/decodeNode. |
| 13 | |
| 14 | private const val TAG = "WhatsAppProtocolBinary" |
| 15 | private const val BYTE_MASK = 0xFF |
| 16 | private const val NIBBLE_MASK = 0x0F |
| 17 | private const val ASCII_MASK = 0x7F |
| 18 | private const val HIGH_BIT = 0x80 |
| 19 | private const val LIST_8_LIMIT = 256 |
| 20 | private const val BINARY_20_BITS = 20 |
| 21 | private const val INT24_SIZE = 3 |
| 22 | private const val INT32_SIZE = 4 |
| 23 | private const val NIBBLE_BITS = 4 |
| 24 | private const val BYTE_BITS = 8 |
| 25 | private const val SHIFT_BYTE1 = 8 |
| 26 | private const val SHIFT_BYTE2 = 16 |
| 27 | private const val SHIFT_BYTE3 = 24 |
| 28 | private const val DECIMAL_LIMIT = 10 |
| 29 | private const val HEX_LIMIT = 16 |
| 30 | private const val PACKED_MINUS = 10 |
| 31 | private const val PACKED_DOT = 11 |
| 32 | private const val PACKED_END = 15 |
| 33 | |
| 34 | internal class BinaryEncoder { |
| 35 | private val data = mutableListOf<Byte>(0) |
| 36 | |
| 37 | fun getData(): ByteArray = data.toByteArray() |
| 38 | |
| 39 | private fun pushByte(b: Byte) { data.add(b) } |
| 40 | private fun pushByte(b: Int) { data.add(b.toByte()) } |
| 41 | private fun pushBytes(bytes: ByteArray) { bytes.forEach { data.add(it) } } |
| 42 | |
| 43 | private fun pushInt8(value: Int) { pushByte((value and BYTE_MASK).toByte()) } |
| 44 | private fun pushInt16(value: Int) { |
| 45 | pushByte((value shr SHIFT_BYTE1 and BYTE_MASK).toByte()) |
| 46 | pushByte((value and BYTE_MASK).toByte()) |
| 47 | } |
| 48 | private fun pushInt20(value: Int) { |
| 49 | pushByte(((value shr SHIFT_BYTE2) and NIBBLE_MASK).toByte()) |
| 50 | pushByte(((value shr SHIFT_BYTE1) and BYTE_MASK).toByte()) |
| 51 | pushByte((value and BYTE_MASK).toByte()) |
| 52 | } |
| 53 | private fun pushInt32(value: Int) { |
| 54 | pushByte((value shr SHIFT_BYTE3 and BYTE_MASK).toByte()) |
| 55 | pushByte((value shr SHIFT_BYTE2 and BYTE_MASK).toByte()) |
| 56 | pushByte((value shr SHIFT_BYTE1 and BYTE_MASK).toByte()) |
| 57 | pushByte((value and BYTE_MASK).toByte()) |
| 58 | } |
| 59 | |
| 60 | private fun writeByteLength(length: Int) { |
| 61 | when { |
| 62 | length < LIST_8_LIMIT -> { pushByte(BinaryToken.BINARY_8); pushInt8(length) } |
| 63 | length < (1 shl BINARY_20_BITS) -> { pushByte(BinaryToken.BINARY_20); pushInt20(length) } |
| 64 | else -> { pushByte(BinaryToken.BINARY_32); pushInt32(length) } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | fun writeNode(n: Node) { |
| 69 | if (n.tag == "0") { |
| 70 | pushByte(BinaryToken.LIST_8) |
| 71 | pushByte(BinaryToken.LIST_EMPTY) |
| 72 | return |
| 73 | } |
| 74 | |
| 75 | val hasContent = if (n.data != null || n.content.isNotEmpty()) 1 else 0 |
| 76 | val attrCount = n.attrs.count { it.value.isNotEmpty() } |
| 77 | writeListStart(2 * attrCount + 1 + hasContent) |
| 78 | writeString(n.tag) |
| 79 | writeAttributes(n.attrs) |
| 80 | if (n.data != null) { |
| 81 | writeBytes(n.data) |
| 82 | } else if (n.content.isNotEmpty()) { |
| 83 | writeListStart(n.content.size) |
| 84 | for (child in n.content) { |
| 85 | writeNode(child) |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | private fun writeString(value: String) { |
| 91 | val tokenIndex = BinaryToken.indexOfSingleToken(value) |
| 92 | if (tokenIndex >= 0) { |
| 93 | pushByte(tokenIndex) |
| 94 | } else { |
| 95 | val (dictIndex, tokIndex, found) = BinaryToken.indexOfDoubleByteToken(value) |
| 96 | if (found) { |
| 97 | pushByte(BinaryToken.DICTIONARY_0 + dictIndex) |
| 98 | pushByte(tokIndex) |
| 99 | } else if (validateNibble(value)) { |
| 100 | writePackedBytes(value, BinaryToken.NIBBLE_8) |
| 101 | } else if (validateHex(value)) { |
| 102 | writePackedBytes(value, BinaryToken.HEX_8) |
| 103 | } else { |
| 104 | writeStringRaw(value) |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | private fun writeBytes(value: ByteArray) { |
| 110 | writeByteLength(value.size) |
| 111 | pushBytes(value) |
| 112 | } |
| 113 | |
| 114 | private fun writeStringRaw(value: String) { |
| 115 | val bytes = value.toByteArray(Charsets.UTF_8) |
| 116 | writeByteLength(bytes.size) |
| 117 | pushBytes(bytes) |
| 118 | } |
| 119 | |
| 120 | /** |
| 121 | * Encode a JID attribute value as a JID_PAIR (user@server) or AD_JID (user.agent:device) |
| 122 | * token, matching WhatsApp's binary wire format. The server rejects stanzas (e.g. usync, |
| 123 | * prekey fetch) whose jid attributes are written as raw strings. |
| 124 | */ |
| 125 | private fun writeJid(jid: String) { |
| 126 | val at = jid.indexOf('@') |
| 127 | if (at < 0) { writeString(jid); return } |
| 128 | val userPart = jid.substring(0, at) |
| 129 | val server = jid.substring(at + 1) |
| 130 | val colon = userPart.indexOf(':') |
| 131 | val device = if (colon >= 0) userPart.substring(colon + 1).toIntOrNull() ?: 0 else 0 |
| 132 | val beforeColon = if (colon >= 0) userPart.substring(0, colon) else userPart |
| 133 | val dot = beforeColon.indexOf('.') |
| 134 | val agent = if (dot >= 0) beforeColon.substring(dot + 1).toIntOrNull() ?: 0 else 0 |
| 135 | val user = if (dot >= 0) beforeColon.substring(0, dot) else beforeColon |
| 136 | if ((device != 0 || agent != 0) && server == "s.whatsapp.net") { |
| 137 | pushByte(BinaryToken.AD_JID.toByte()) |
| 138 | pushByte(agent.toByte()) |
| 139 | pushByte(device.toByte()) |
| 140 | writeString(user) |
| 141 | } else { |
| 142 | pushByte(BinaryToken.JID_PAIR) |
| 143 | if (user.isEmpty()) pushByte(BinaryToken.LIST_EMPTY) else writeString(user) |
| 144 | writeString(server) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | private fun writeAttributes(attrs: Map<String, String>) { |
| 149 | for ((key, value) in attrs) { |
| 150 | if (value.isEmpty()) continue |
| 151 | writeString(key) |
| 152 | if (value.contains("@")) writeJid(value) else writeString(value) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | private fun writeListStart(size: Int) { |
| 157 | when { |
| 158 | size == 0 -> pushByte(BinaryToken.LIST_EMPTY) |
| 159 | size < LIST_8_LIMIT -> { pushByte(BinaryToken.LIST_8); pushInt8(size) } |
| 160 | else -> { pushByte(BinaryToken.LIST_16); pushInt16(size) } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | private fun validateNibble(value: String): Boolean { |
| 165 | if (value.length > BinaryToken.PACKED_MAX) return false |
| 166 | return value.all { it in '0'..'9' || it == '-' || it == '.' } |
| 167 | } |
| 168 | |
| 169 | private fun validateHex(value: String): Boolean { |
| 170 | if (value.length > BinaryToken.PACKED_MAX) return false |
| 171 | // HEX_8 packing is uppercase-only; lowercase must fall through to raw |
| 172 | // string encoding or it decodes back as uppercase (whatsmeow binary/encoder.go). |
| 173 | return value.all { it in '0'..'9' || it in 'A'..'F' } |
| 174 | } |
| 175 | |
| 176 | private fun writePackedBytes(value: String, dataType: Int) { |
| 177 | pushByte(dataType) |
| 178 | val roundedLength = ((value.length + 1) / 2) |
| 179 | val flag = if (value.length % 2 != 0) (roundedLength or 128) else roundedLength |
| 180 | pushByte(flag) |
| 181 | val packer = if (dataType == BinaryToken.NIBBLE_8) ::packNibble else ::packHex |
| 182 | var i = 0 |
| 183 | while (i < value.length / 2) { |
| 184 | pushByte(((packer(value[2 * i]) shl NIBBLE_BITS) or packer(value[2 * i + 1])).toByte()) |
| 185 | i++ |
| 186 | } |
| 187 | if (value.length % 2 != 0) { |
| 188 | pushByte(((packer(value.last()) shl NIBBLE_BITS) or packer(0.toChar())).toByte()) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | private fun packNibble(c: Char): Int = when (c) { |
| 193 | in '0'..'9' -> c - '0' |
| 194 | '-' -> PACKED_MINUS |
| 195 | '.' -> PACKED_DOT |
| 196 | 0.toChar() -> PACKED_END |
| 197 | else -> throw IllegalArgumentException("Invalid nibble char: $c") |
| 198 | } |
| 199 | |
| 200 | private fun packHex(c: Char): Int = when (c) { |
| 201 | in '0'..'9' -> c - '0' |
| 202 | in 'A'..'F' -> DECIMAL_LIMIT + (c - 'A') |
| 203 | in 'a'..'f' -> DECIMAL_LIMIT + (c - 'a') |
| 204 | 0.toChar() -> PACKED_END |
| 205 | else -> throw IllegalArgumentException("Invalid hex char: $c") |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | internal class BinaryDecoder(private val data: ByteArray) { |
| 210 | private var index = 0 |
| 211 | |
| 212 | private fun checkEOS(length: Int) { |
| 213 | if (index + length > data.size) throw IllegalStateException("End of stream") |
| 214 | } |
| 215 | |
| 216 | private fun readByte(): Int { |
| 217 | checkEOS(1) |
| 218 | return data[index++].toInt() and BYTE_MASK |
| 219 | } |
| 220 | |
| 221 | private fun readInt8(): Int = readByte() |
| 222 | private fun readInt16(): Int { |
| 223 | checkEOS(2) |
| 224 | val v = ((data[index].toInt() and BYTE_MASK) shl 8) or (data[index + 1].toInt() and BYTE_MASK) |
| 225 | index += 2 |
| 226 | return v |
| 227 | } |
| 228 | private fun readInt20(): Int { |
| 229 | checkEOS(INT24_SIZE) |
| 230 | val v = ((data[index].toInt() and NIBBLE_MASK) shl 16) or |
| 231 | ((data[index + 1].toInt() and BYTE_MASK) shl SHIFT_BYTE1) or |
| 232 | (data[index + 2].toInt() and BYTE_MASK) |
| 233 | index += INT24_SIZE |
| 234 | return v |
| 235 | } |
| 236 | private fun readInt32(): Int { |
| 237 | checkEOS(INT32_SIZE) |
| 238 | val v = ((data[index].toInt() and BYTE_MASK) shl SHIFT_BYTE3) or |
| 239 | ((data[index + 1].toInt() and BYTE_MASK) shl SHIFT_BYTE2) or |
| 240 | ((data[index + 2].toInt() and BYTE_MASK) shl SHIFT_BYTE1) or |
| 241 | (data[index + INT24_SIZE].toInt() and BYTE_MASK) |
| 242 | index += INT32_SIZE |
| 243 | return v |
| 244 | } |
| 245 | |
| 246 | private fun readRaw(length: Int): ByteArray { |
| 247 | checkEOS(length) |
| 248 | val result = data.copyOfRange(index, index + length) |
| 249 | index += length |
| 250 | return result |
| 251 | } |
| 252 | |
| 253 | private fun readPacked8(tag: Int): String { |
| 254 | val startByte = readByte() |
| 255 | val sb = StringBuilder() |
| 256 | for (i in 0 until (startByte and ASCII_MASK)) { |
| 257 | val currByte = readByte() |
| 258 | sb.append(unpackByte(tag, (currByte shr NIBBLE_BITS) and NIBBLE_MASK)) |
| 259 | sb.append(unpackByte(tag, currByte and NIBBLE_MASK)) |
| 260 | } |
| 261 | var result = sb.toString() |
| 262 | if ((startByte shr (BYTE_BITS - 1)) != 0) result = result.dropLast(1) |
| 263 | return result |
| 264 | } |
| 265 | |
| 266 | private fun unpackByte(tag: Int, value: Int): Char = when (tag) { |
| 267 | BinaryToken.NIBBLE_8 -> unpackNibble(value) |
| 268 | BinaryToken.HEX_8 -> unpackHex(value) |
| 269 | else -> throw IllegalArgumentException("Unknown packed tag: $tag") |
| 270 | } |
| 271 | private fun unpackNibble(value: Int): Char = when { |
| 272 | value < DECIMAL_LIMIT -> ('0' + value) |
| 273 | value == PACKED_MINUS -> '-' |
| 274 | value == PACKED_DOT -> '.' |
| 275 | value == PACKED_END -> 0.toChar() |
| 276 | else -> throw IllegalArgumentException("Invalid nibble: $value") |
| 277 | } |
| 278 | private fun unpackHex(value: Int): Char = when { |
| 279 | value < DECIMAL_LIMIT -> ('0' + value) |
| 280 | value < HEX_LIMIT -> ('A' + value - DECIMAL_LIMIT) |
| 281 | else -> throw IllegalArgumentException("Invalid hex: $value") |
| 282 | } |
| 283 | |
| 284 | private fun readListSize(tag: Int): Int = when (tag) { |
| 285 | BinaryToken.LIST_EMPTY.toInt() and BYTE_MASK -> 0 |
| 286 | BinaryToken.LIST_8.toInt() and BYTE_MASK -> readInt8() |
| 287 | BinaryToken.LIST_16.toInt() and BYTE_MASK -> readInt16() |
| 288 | else -> throw IllegalArgumentException("Unknown list tag: $tag") |
| 289 | } |
| 290 | |
| 291 | private fun read(asString: Boolean): Any? { |
| 292 | val tag = readByte() |
| 293 | return when (tag) { |
| 294 | BinaryToken.LIST_EMPTY.toInt() and BYTE_MASK -> null |
| 295 | BinaryToken.LIST_8.toInt() and BYTE_MASK, |
| 296 | BinaryToken.LIST_16.toInt() and BYTE_MASK -> readList(tag) |
| 297 | BinaryToken.BINARY_8.toInt() and BYTE_MASK -> readSized(readInt8(), asString) |
| 298 | BinaryToken.BINARY_20.toInt() and BYTE_MASK -> readSized(readInt20(), asString) |
| 299 | BinaryToken.BINARY_32.toInt() and BYTE_MASK -> readSized(readInt32(), asString) |
| 300 | in BinaryToken.DICTIONARY_0..BinaryToken.DICTIONARY_3 -> { |
| 301 | val idx = readInt8() |
| 302 | BinaryToken.getDoubleToken(tag - BinaryToken.DICTIONARY_0, idx) |
| 303 | } |
| 304 | BinaryToken.AD_JID -> readAdJid() |
| 305 | BinaryToken.FB_JID -> readFbJid() |
| 306 | BinaryToken.INTEROP_JID -> readInteropJid() |
| 307 | BinaryToken.JID_PAIR.toInt() and BYTE_MASK -> readJidPair() |
| 308 | BinaryToken.NIBBLE_8, BinaryToken.HEX_8 -> readPacked8(tag) |
| 309 | else -> readSingleToken(tag) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /** Read a sized binary blob (or UTF-8 string when [asString]). */ |
| 314 | private fun readSized(size: Int, asString: Boolean): Any = |
| 315 | if (asString) String(readRaw(size), Charsets.UTF_8) else readRaw(size) |
| 316 | |
| 317 | /** AD JID: agent + device + user. */ |
| 318 | private fun readAdJid(): String { |
| 319 | val agent = readByte() |
| 320 | val device = readByte() |
| 321 | val user = read(true) as? String ?: "" |
| 322 | return "$user.${agent}:${device}@s.whatsapp.net" |
| 323 | } |
| 324 | |
| 325 | /** FB JID: user + device + server. */ |
| 326 | private fun readFbJid(): String { |
| 327 | val user = read(true) as? String ?: "" |
| 328 | val device = readInt16() |
| 329 | val server = read(true) as? String ?: "msgr" |
| 330 | return "$user:$device@$server" |
| 331 | } |
| 332 | |
| 333 | /** Interop JID: user + device + integrator + server. */ |
| 334 | private fun readInteropJid(): String { |
| 335 | val user = read(true) as? String ?: "" |
| 336 | val device = readInt16() |
| 337 | val integrator = readInt16() |
| 338 | val server = read(true) as? String ?: "" |
| 339 | return "$user:$device:$integrator@$server" |
| 340 | } |
| 341 | |
| 342 | /** JID pair: user + server. */ |
| 343 | private fun readJidPair(): String { |
| 344 | val user = read(true) as? String |
| 345 | val server = read(true) as? String ?: throw IllegalStateException("JID missing server") |
| 346 | return if (user != null) "$user@$server" else "@$server" |
| 347 | } |
| 348 | |
| 349 | /** Single-byte dictionary token. */ |
| 350 | private fun readSingleToken(tag: Int): String { |
| 351 | if (tag in 1 until BinaryToken.singleByteTokens.size) { |
| 352 | return BinaryToken.singleByteTokens[tag] |
| 353 | } |
| 354 | throw IllegalArgumentException("Invalid token $tag at position $index") |
| 355 | } |
| 356 | |
| 357 | private fun readList(tag: Int): List<Node> { |
| 358 | val size = readListSize(tag) |
| 359 | return (0 until size).map { readNode() } |
| 360 | } |
| 361 | |
| 362 | fun readNode(): Node { |
| 363 | val listTag = readInt8() |
| 364 | val listSize = readListSize(listTag) |
| 365 | val tag = read(true) as? String ?: throw IllegalStateException("Node tag is not a string") |
| 366 | if (listSize == 0 || tag.isEmpty()) throw IllegalStateException("Invalid node") |
| 367 | |
| 368 | val attrCount = (listSize - 1) shr 1 |
| 369 | val attrs = mutableMapOf<String, String>() |
| 370 | for (i in 0 until attrCount) { |
| 371 | val key = read(true) as? String ?: continue |
| 372 | val value = read(true) |
| 373 | attrs[key] = value?.toString() ?: "" |
| 374 | } |
| 375 | |
| 376 | val content = mutableListOf<Node>() |
| 377 | var nodeData: ByteArray? = null |
| 378 | if (listSize % 2 == 0) { |
| 379 | val contentData = read(false) |
| 380 | when (contentData) { |
| 381 | is List<*> -> { |
| 382 | @Suppress("UNCHECKED_CAST") |
| 383 | content.addAll(contentData as List<Node>) |
| 384 | } |
| 385 | is ByteArray -> nodeData = contentData |
| 386 | is String -> nodeData = contentData.toByteArray(Charsets.UTF_8) |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | return Node(tag, attrs, content, nodeData) |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | fun WhatsAppProtocol.encodeNode(node: Node): ByteArray { |
| 395 | val encoder = BinaryEncoder() |
| 396 | encoder.writeNode(node) |
| 397 | return encoder.getData() |
| 398 | } |
| 399 | |
| 400 | fun WhatsAppProtocol.decodeNode(data: ByteArray): Node { |
| 401 | val decoder = BinaryDecoder(unpack(data)) |
| 402 | return decoder.readNode() |
| 403 | } |
| 404 | |
| 405 | // WhatsApp Noise certificate root public key + issuer serial (whatsmeow/handshake.go). |
| 406 | private val WA_CERT_PUB_KEY = byteArrayOf( |
| 407 | 0x14, 0x23, 0x75, 0x57, 0x4d, 0x0a, 0x58, 0x71, 0x66.toByte(), 0xaa.toByte(), |
| 408 | 0xe7.toByte(), 0x1e, 0xbe.toByte(), 0x51, 0x64, 0x37, 0xc4.toByte(), 0xa2.toByte(), |
| 409 | 0x8b.toByte(), 0x73, 0xe3.toByte(), 0x69, 0x5c, 0x6c, 0xe1.toByte(), 0xf7.toByte(), |
| 410 | 0xf9.toByte(), 0x54, 0x5d, 0xa8.toByte(), 0xee.toByte(), 0x6b, |
| 411 | ) |
| 412 | private const val WA_CERT_ISSUER_SERIAL = 0 |
| 413 | private const val CERT_SIGNATURE_SIZE = 64 |
| 414 | private const val IDENTITY_KEY_SIZE = 32 |
| 415 | |
| 416 | /** True when all cert chain parts are present and well-formed. */ |
| 417 | private fun hasValidCertParts( |
| 418 | interRaw: ByteArray, |
| 419 | leafRaw: ByteArray, |
| 420 | interSig: ByteArray, |
| 421 | leafSig: ByteArray, |
| 422 | ): Boolean = interRaw.isNotEmpty() && |
| 423 | leafRaw.isNotEmpty() && |
| 424 | interSig.size == CERT_SIGNATURE_SIZE && |
| 425 | leafSig.size == CERT_SIGNATURE_SIZE |
| 426 | |
| 427 | /** |
| 428 | * Verify the server's Noise certificate chain (intermediate signed by the WA root, |
| 429 | * leaf signed by the intermediate, leaf key == server static key, validity window). |
| 430 | * Port of whatsmeow/handshake.go verifyServerCert. Returns true if trusted. |
| 431 | */ |
| 432 | fun WhatsAppProtocol.verifyServerCert(certDecrypted: ByteArray, staticDecrypted: ByteArray): Boolean { |
| 433 | return try { |
| 434 | val chain = WhatsAppCertProto.CertChain.parseFrom(certDecrypted) |
| 435 | val interRaw = chain.intermediate.details.toByteArray() |
| 436 | val interSig = chain.intermediate.signature.toByteArray() |
| 437 | val leafRaw = chain.leaf.details.toByteArray() |
| 438 | val leafSig = chain.leaf.signature.toByteArray() |
| 439 | if (!hasValidCertParts(interRaw, leafRaw, interSig, leafSig)) { |
| 440 | Log.error(TAG, "cert: missing/invalid parts") |
| 441 | return false |
| 442 | } |
| 443 | if (!ECPublicKey.fromPublicKeyBytes(WA_CERT_PUB_KEY).verifySignature(interRaw, interSig)) { |
| 444 | Log.error(TAG, "cert: intermediate signature invalid") |
| 445 | return false |
| 446 | } |
| 447 | val inter = WhatsAppCertProto.CertChain.NoiseCertificate.Details.parseFrom(interRaw) |
| 448 | if (inter.issuerSerial != WA_CERT_ISSUER_SERIAL || inter.key.size() != IDENTITY_KEY_SIZE) { |
| 449 | Log.error(TAG, "cert: bad intermediate issuer/key") |
| 450 | return false |
| 451 | } |
| 452 | verifyLeafCert(inter, leafRaw, leafSig, staticDecrypted) |
| 453 | } catch (expected: Exception) { |
| 454 | Log.error(TAG, "cert verification error", expected) |
| 455 | false |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | /** Verify the leaf certificate against the intermediate. */ |
| 460 | private fun verifyLeafCert( |
| 461 | inter: WhatsAppCertProto.CertChain.NoiseCertificate.Details, |
| 462 | leafRaw: ByteArray, |
| 463 | leafSig: ByteArray, |
| 464 | staticDecrypted: ByteArray, |
| 465 | ): Boolean { |
| 466 | if (!ECPublicKey.fromPublicKeyBytes(inter.key.toByteArray()).verifySignature(leafRaw, leafSig)) { |
| 467 | Log.error(TAG, "cert: leaf signature invalid") |
| 468 | return false |
| 469 | } |
| 470 | val leaf = WhatsAppCertProto.CertChain.NoiseCertificate.Details.parseFrom(leafRaw) |
| 471 | if (leaf.issuerSerial != inter.serial) { |
| 472 | Log.error(TAG, "cert: leaf issuer serial mismatch") |
| 473 | return false |
| 474 | } |
| 475 | if (!leaf.key.toByteArray().contentEquals(staticDecrypted)) { |
| 476 | Log.error(TAG, "cert: leaf key != server static key") |
| 477 | return false |
| 478 | } |
| 479 | val now = System.currentTimeMillis() / 1000 |
| 480 | for (d in listOf(inter, leaf)) { |
| 481 | if (d.notBefore != 0L && now < d.notBefore) { Log.error(TAG, "cert: not yet valid"); return false } |
| 482 | if (d.notAfter != 0L && now > d.notAfter) { Log.error(TAG, "cert: expired"); return false } |
| 483 | } |
| 484 | return true |
| 485 | } |
| 486 | |
| 487 | /** |
| 488 | * Strips the leading compression flag byte from a decrypted frame and inflates |
| 489 | * the remainder with zlib when the flag's 0x02 bit is set. |
| 490 | * Ref: whatsmeow/binary/unpack.go Unpack(). |
| 491 | */ |
| 492 | private fun WhatsAppProtocol.unpack(data: ByteArray): ByteArray { |
| 493 | if (data.isEmpty()) throw IllegalStateException("empty frame, no flag byte") |
| 494 | val flag = data[0].toInt() and BYTE_MASK |
| 495 | val payload = data.copyOfRange(1, data.size) |
| 496 | return if (flag and 2 > 0) { |
| 497 | inflatePayload(payload) |
| 498 | } else { |
| 499 | payload |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | /** Zlib-inflate a flagged frame payload. */ |
| 504 | private fun inflatePayload(payload: ByteArray): ByteArray { |
| 505 | val inflater = java.util.zip.Inflater() |
| 506 | inflater.setInput(payload) |
| 507 | val out = java.io.ByteArrayOutputStream(payload.size * 2) |
| 508 | val buf = ByteArray(8192) |
| 509 | try { |
| 510 | while (!inflater.finished()) { |
| 511 | val n = inflater.inflate(buf) |
| 512 | if (n == 0) { |
| 513 | if (inflater.finished() || inflater.needsDictionary()) break |
| 514 | if (inflater.needsInput()) throw IllegalStateException("zlib needs more input") |
| 515 | } |
| 516 | out.write(buf, 0, n) |
| 517 | } |
| 518 | } finally { |
| 519 | inflater.end() |
| 520 | } |
| 521 | return out.toByteArray() |
| 522 | } |
| 523 | |
| 524 | // -- Frame helpers -- |
| 525 | |
| 526 | /** |
| 527 | * Build a framed message with optional header and 3-byte big-endian length prefix. |
| 528 | * From whatsmeow/socket/framesocket.go SendFrame() |
| 529 | */ |
| 530 | fun WhatsAppProtocol.buildFramedMessage(data: ByteArray, header: ByteArray?): ByteArray { |
| 531 | val headerLength = header?.size ?: 0 |
| 532 | val dataLength = data.size |
| 533 | if (dataLength >= FRAME_MAX_SIZE) { |
| 534 | throw IllegalArgumentException("Frame too large: $dataLength bytes (max $FRAME_MAX_SIZE)") |
| 535 | } |
| 536 | val frame = ByteArray(headerLength + FRAME_LENGTH_SIZE + dataLength) |
| 537 | |
| 538 | var offset = 0 |
| 539 | if (header != null) { |
| 540 | System.arraycopy(header, 0, frame, offset, headerLength) |
| 541 | offset += headerLength |
| 542 | } |
| 543 | frame[offset] = (dataLength shr SHIFT_BYTE2).toByte() |
| 544 | frame[offset + 1] = (dataLength shr SHIFT_BYTE1).toByte() |
| 545 | frame[offset + 2] = dataLength.toByte() |
| 546 | offset += FRAME_LENGTH_SIZE |
| 547 | System.arraycopy(data, 0, frame, offset, dataLength) |
| 548 | return frame |
| 549 | } |
| 550 | |
| 551 | /** |
| 552 | * Extract frame payload from raw data (strip 3-byte length prefix). |
| 553 | * From whatsmeow/socket/framesocket.go processData() |
| 554 | */ |
| 555 | fun WhatsAppProtocol.extractFrame(data: ByteArray): ByteArray { |
| 556 | if (data.size < FRAME_LENGTH_SIZE) return data |
| 557 | val length = ((data[0].toInt() and BYTE_MASK) shl 16) or |
| 558 | ((data[1].toInt() and BYTE_MASK) shl SHIFT_BYTE1) or |
| 559 | (data[2].toInt() and BYTE_MASK) |
| 560 | if (data.size < FRAME_LENGTH_SIZE + length) return data |
| 561 | return data.copyOfRange(FRAME_LENGTH_SIZE, FRAME_LENGTH_SIZE + length) |
| 562 | } |