Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / registration / RegistrationAttestation.kt
RegistrationAttestation.kt191 lines · 8.6 KiBRaw
| 1 | package com.vayunmathur.communicate.data.whatsapp.registration |
| 2 | |
| 3 | import android.content.Context |
| 4 | import android.util.Base64 |
| 5 | import com.vayunmathur.library.log.Log |
| 6 | import com.vayunmathur.communicate.data.whatsapp.e2e.RustWhatsAppCrypto |
| 7 | import java.security.MessageDigest |
| 8 | import javax.crypto.Cipher |
| 9 | import javax.crypto.Mac |
| 10 | import javax.crypto.spec.GCMParameterSpec |
| 11 | import javax.crypto.spec.SecretKeySpec |
| 12 | |
| 13 | /** |
| 14 | * Reproduces WhatsApp's registration attestation, recovered as pure Java from the pinned APK |
| 15 | * (see [WhatsAppRegistrationConstants] + communicate/whatsapp-documentation.md). |
| 16 | * |
| 17 | * Three layers: |
| 18 | * - [computeToken] → the `token` form field validated by `/v2/code` (gate for `bad_token`). |
| 19 | * - [encryptQueryString]→ the optional `ENC` wrapper (X25519 ECDH → AES-256-GCM). |
| 20 | * - [signWithAttestation]→ the optional `H` HMAC over the (encrypted) body. |
| 21 | * |
| 22 | * The token is the real gate; ENC/H are additional obfuscation layers that the official client |
| 23 | * itself falls back away from on failure, so [RegistrationHttpClient] defaults to plain form |
| 24 | * bodies and offers ENC/H as an opt-in. |
| 25 | */ |
| 26 | object RegistrationAttestation { |
| 27 | |
| 28 | private const val TAG = "WARegAttestation" |
| 29 | private const val INT_BYTES = 4 |
| 30 | private const val SHIFT_BYTE3 = 24 |
| 31 | private const val SHIFT_BYTE2 = 16 |
| 32 | private const val SHIFT_BYTE1 = 8 |
| 33 | private const val GCM_TAG_BITS = 128 |
| 34 | private const val GCM_IV_BYTES = 12 |
| 35 | private const val HEX_RADIX = 16 |
| 36 | private const val HEX_NIBBLE_BITS = 4 |
| 37 | private const val BITS_PER_BYTE = 8 |
| 38 | |
| 39 | // --------------------------------------------------------------------------------------------- |
| 40 | // token (C34029EuU.A01) |
| 41 | // --------------------------------------------------------------------------------------------- |
| 42 | |
| 43 | /** |
| 44 | * token = Base64 standard NO_WRAP (flag 2, not url-safe) over |
| 45 | * HMAC-SHA1( |
| 46 | * key = PBKDF2-HMAC-SHA1(password = packageName || about_logo.png, |
| 47 | * salt = ES3, iters = 128, dkLen = 512 bits), |
| 48 | * msg = signingCertDer || MD5(classes.dex) || phoneDigits) |
| 49 | * (APK: AbstractC169977f8.A0n = Base64 flag 2 = NO_WRAP; A0o/flag 11 url-safe is ONLY for |
| 50 | * expid + e2e bundle.) |
| 51 | * |
| 52 | * @param phoneDigits the NATIONAL number only (WhatsApp's token uses `$phoneNumber` = the `in` |
| 53 | * field, with country code kept separate), e.g. cc="1", number="5551234567" → pass |
| 54 | * "5551234567". |
| 55 | */ |
| 56 | fun computeToken(context: Context, phoneDigits: String): String { |
| 57 | val logo = context.assets.open(WhatsAppRegistrationConstants.ASSET_ABOUT_LOGO) |
| 58 | .use { it.readBytes() } |
| 59 | val certDer = context.assets.open(WhatsAppRegistrationConstants.ASSET_SIGNING_CERT_DER) |
| 60 | .use { it.readBytes() } |
| 61 | |
| 62 | val password = WhatsAppRegistrationConstants.PACKAGE_NAME.toByteArray(Charsets.UTF_8) + logo |
| 63 | val salt = Base64.decode(WhatsAppRegistrationConstants.TOKEN_SALT_B64, Base64.DEFAULT) |
| 64 | |
| 65 | val derivedKey = pbkdf2HmacSha1( |
| 66 | password = password, |
| 67 | salt = salt, |
| 68 | iterations = WhatsAppRegistrationConstants.TOKEN_PBKDF2_ITERATIONS, |
| 69 | dkLenBytes = WhatsAppRegistrationConstants.TOKEN_PBKDF2_KEYLEN_BITS / BITS_PER_BYTE, |
| 70 | ) |
| 71 | |
| 72 | val mac = Mac.getInstance("HmacSHA1") |
| 73 | mac.init(SecretKeySpec(derivedKey, "HmacSHA1")) |
| 74 | mac.update(certDer) |
| 75 | mac.update(hexToBytes(WhatsAppRegistrationConstants.CLASSES_DEX_MD5_HEX)) |
| 76 | mac.update(phoneDigits.toByteArray(Charsets.UTF_8)) |
| 77 | val tokenBytes = mac.doFinal() |
| 78 | |
| 79 | // Token uses STANDARD base64 with padding (APK: AbstractC169977f8.A0n = Base64 flag 2 = |
| 80 | // NO_WRAP). NOT url-safe/no-padding (that's A0o/flag 11, used only for expid + the e2e |
| 81 | // bundle). The '+/=' chars are handled by the form url-encoder at query-build time. |
| 82 | return Base64.encodeToString(tokenBytes, Base64.NO_WRAP) |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Manual PBKDF2-HMAC-SHA1 taking the password as raw bytes. This avoids the char[] encoding |
| 87 | * ambiguity of the JCE "PBKDF2WithHmacSHA1And8BIT" alias (whose availability + high-byte |
| 88 | * handling varies across API levels) and is byte-exact against the recovered algorithm. |
| 89 | */ |
| 90 | private fun pbkdf2HmacSha1( |
| 91 | password: ByteArray, |
| 92 | salt: ByteArray, |
| 93 | iterations: Int, |
| 94 | dkLenBytes: Int, |
| 95 | ): ByteArray { |
| 96 | val mac = Mac.getInstance("HmacSHA1") |
| 97 | mac.init(SecretKeySpec(password, "HmacSHA1")) |
| 98 | val hLen = mac.macLength // 20 |
| 99 | val blocks = (dkLenBytes + hLen - 1) / hLen |
| 100 | val out = ByteArray(blocks * hLen) |
| 101 | val intBuf = ByteArray(INT_BYTES) |
| 102 | for (i in 1..blocks) { |
| 103 | intBuf[0] = (i ushr SHIFT_BYTE3).toByte() |
| 104 | intBuf[1] = (i ushr SHIFT_BYTE2).toByte() |
| 105 | intBuf[2] = (i ushr SHIFT_BYTE1).toByte() |
| 106 | intBuf[INT_BYTES - 1] = i.toByte() |
| 107 | mac.reset() |
| 108 | mac.update(salt) |
| 109 | mac.update(intBuf) |
| 110 | var u = mac.doFinal() |
| 111 | val t = u.copyOf() |
| 112 | for (c in 2..iterations) { |
| 113 | mac.reset() |
| 114 | u = mac.doFinal(u) |
| 115 | for (k in t.indices) t[k] = (t[k].toInt() xor u[k].toInt()).toByte() |
| 116 | } |
| 117 | System.arraycopy(t, 0, out, (i - 1) * hLen, hLen) |
| 118 | } |
| 119 | return out.copyOf(dkLenBytes) |
| 120 | } |
| 121 | |
| 122 | // --------------------------------------------------------------------------------------------- |
| 123 | // ENC (RegistrationEncryption/encryptQueryString) |
| 124 | // --------------------------------------------------------------------------------------------- |
| 125 | |
| 126 | /** |
| 127 | * ENC = base64( ephemeralX25519Pub(32) || AES-256-GCM(key = X25519(ephPriv, ES4_serverPub), |
| 128 | * iv = 12 zero bytes, plaintext = queryString) ) |
| 129 | * IV is 12 zero bytes and the AES key IS the raw ECDH shared secret (no HKDF), per |
| 130 | * RetryingHttpClient.java:236-281. |
| 131 | */ |
| 132 | fun encryptQueryString(queryString: String): String? { |
| 133 | return try { |
| 134 | val serverPub = hexToBytes(WhatsAppRegistrationConstants.REG_SERVER_X25519_PUBKEY_HEX) |
| 135 | val eph = RustWhatsAppCrypto.generateKeyPairSplit() |
| 136 | val shared = RustWhatsAppCrypto.x25519Agreement(eph.privateKey, serverPub) |
| 137 | ?: return null |
| 138 | val cipher = Cipher.getInstance("AES/GCM/NoPadding") |
| 139 | cipher.init( |
| 140 | Cipher.ENCRYPT_MODE, |
| 141 | SecretKeySpec(shared, "AES"), |
| 142 | GCMParameterSpec(GCM_TAG_BITS, ByteArray(GCM_IV_BYTES)), |
| 143 | ) |
| 144 | val ct = cipher.doFinal(queryString.toByteArray(Charsets.UTF_8)) |
| 145 | Base64.encodeToString(eph.publicKey + ct, Base64.NO_WRAP) |
| 146 | } catch (expected: Throwable) { |
| 147 | Log.status(TAG, "encryptQueryString failed; falling back to plain", expected) |
| 148 | null |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | // --------------------------------------------------------------------------------------------- |
| 153 | // H (RegistrationBodyBuilder/signWithKeyAttestation) |
| 154 | // --------------------------------------------------------------------------------------------- |
| 155 | |
| 156 | /** |
| 157 | * H = base64( HMAC-SHA256(key = attestation key, msg = body) ). |
| 158 | * |
| 159 | * Prefers the non-exportable AndroidKeyStore HMAC key |
| 160 | * ([WhatsAppAttestationKeyStore]); falls back to the software [softwareKey] |
| 161 | * ([WhatsAppDeviceFingerprint.attestationKey]) when the KeyStore is unavailable. The server |
| 162 | * treats `H` as best-effort (the client warns + continues when it is null). |
| 163 | */ |
| 164 | fun signWithAttestation(body: String, softwareKey: ByteArray): String { |
| 165 | val mac = WhatsAppAttestationKeyStore.signWithFallback(body.toByteArray(Charsets.UTF_8), softwareKey) |
| 166 | return Base64.encodeToString(mac, Base64.NO_WRAP) |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * H over a raw software key only (no KeyStore). Retained for callers/tests that supply an |
| 171 | * explicit key; prefer the [signWithAttestation]`(body, softwareKey)` overload in production. |
| 172 | */ |
| 173 | fun signWithAttestation(attestationKey: ByteArray, body: String): String { |
| 174 | val mac = Mac.getInstance("HmacSHA256") |
| 175 | mac.init(SecretKeySpec(attestationKey, "HmacSHA256")) |
| 176 | return Base64.encodeToString(mac.doFinal(body.toByteArray(Charsets.UTF_8)), Base64.NO_WRAP) |
| 177 | } |
| 178 | |
| 179 | // --------------------------------------------------------------------------------------------- |
| 180 | |
| 181 | fun md5(bytes: ByteArray): ByteArray = MessageDigest.getInstance("MD5").digest(bytes) |
| 182 | |
| 183 | private fun hexToBytes(hex: String): ByteArray { |
| 184 | val out = ByteArray(hex.length / 2) |
| 185 | for (i in out.indices) { |
| 186 | out[i] = ((hex[i * 2].digitToInt(HEX_RADIX) shl HEX_NIBBLE_BITS) or |
| 187 | hex[i * 2 + 1].digitToInt(HEX_RADIX)).toByte() |
| 188 | } |
| 189 | return out |
| 190 | } |
| 191 | } |