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 / registration / RegistrationIntegrity.kt

RegistrationIntegrity.kt248 lines · 11.9 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp.registration
2
3import android.annotation.SuppressLint
4import android.content.Context
5import android.os.Build
6import android.provider.Settings
7import java.io.File
8import java.nio.ByteBuffer
9import java.security.MessageDigest
10import java.util.Base64
11
12/**
13 * Device-integrity signal collector for the WAMSYS `/v2` endpoints (w2.md §2.3, Phase B 2a).
14 *
15 * Computes the honestly-available integrity signals:
16 * - `aid` = base64(SHA-256(Android ID)) (44B, real device)
17 * - `_gi` = ENC(JSON{apk sha256, source_dir, size, package}) — pinned to the OFFICIAL WhatsApp
18 * app identity (package=com.whatsapp + official base.apk hash/size), not this client.
19 * - `_gp` = base64(SHA-256(sorted OFFICIAL WhatsApp manifest permissions)) (44B)
20 * - `_ge` = {"sv":<virtio>,"sb":<vboxsf>} (emulation probe)
21 * - `_ga` = {"mp","mu","ae","ap","ai"} (automation signals)
22 * - `_gs` = {"em":"<base64>"} (native-obfuscation placeholder)
23 * - `t` = base64(int64 BE attestation timestamp seconds) (8B)
24 * - `db` = ADB-enabled flag (Settings.Global.ADB_ENABLED) (0|1)
25 *
26 * NOT computed (bound to the official signed WhatsApp app identity; no FOSS way to mint):
27 * - `gpia` / `_gg` (Play Integrity JWT) and `recaptcha` (reCAPTCHA Enterprise). These are omitted
28 * entirely — an unofficial client cannot produce server-valid tokens (documented, not faked).
29 *
30 * The pure encoders ([aidOf], [permissionsHashOf], [tField], [emulationJson], [automationJson],
31 * [nativeSignalsJson]) use `java.util.Base64` (API 26+, minSdk 31) so they are JVM-unit-testable.
32 */
33object RegistrationIntegrity {
34 private const val MS_PER_SECOND = 1000L
35 private const val LONG_BYTES = 8
36
37 private val b64 = Base64.getEncoder()
38
39 // ---------------------------------------------------------------- pure encoders (JVM-testable)
40
41 private fun sha256(bytes: ByteArray): ByteArray =
42 MessageDigest.getInstance("SHA-256").digest(bytes)
43
44 /** `aid` = base64(SHA-256(Android ID)). Standard base64 (44 chars for a 32-byte digest). */
45 fun aidOf(androidId: String): String = b64.encodeToString(sha256(androidId.toByteArray(Charsets.UTF_8)))
46
47 /** `_gp` = base64(SHA-256(newline-joined sorted permission names)). */
48 fun permissionsHashOf(permissions: List<String>): String =
49 b64.encodeToString(sha256(permissions.sorted().joinToString("\n").toByteArray(Charsets.UTF_8)))
50
51 /** `t` = base64(8-byte big-endian int64 seconds). */
52 fun tField(epochSeconds: Long): String =
53 b64.encodeToString(ByteBuffer.allocate(LONG_BYTES).putLong(epochSeconds).array())
54
55 /** `_ge` emulation probe JSON `{"sv":<virtio>,"sb":<vboxsf>}` (stable key order). */
56 fun emulationJson(virtio: Boolean, vboxsf: Boolean): String =
57 """{"sv":$virtio,"sb":$vboxsf}"""
58
59 /** `_ga` automation-signals JSON `{"mp","mu","ae","ap","ai"}` (stable key order). */
60 fun automationJson(mockPackages: Boolean, multiUser: Boolean, ae: Long, ap: Long, ai: Long): String =
61 """{"mp":$mockPackages,"mu":$multiUser,"ae":$ae,"ap":$ap,"ai":$ai}"""
62
63 /**
64 * `_gs` native-obfuscation placeholder JSON `{"em":"<base64>"}`. The real `_gs` is produced by a
65 * native RFC we cannot reproduce; we ship the exact wire shape filled with an available signal
66 * (or empty). Ref w2.md §2.3 `wa-android-native-obfuscation-rfc`.
67 */
68 fun nativeSignalsJson(emBase64: String): String = """{"em":"$emBase64"}"""
69
70 // ---------------------------------------------------------------- Android collection
71
72 /** The set of collected integrity signals (empty strings mean "not available / not sent"). */
73 data class Signals(
74 val aid: String,
75 val gp: String,
76 val ge: String,
77 val ga: String,
78 val gs: String,
79 val gi: String?,
80 val db: String,
81 val tSeconds: Long,
82 )
83
84 /**
85 * Collect all honestly-available integrity signals from [context].
86 * @param encryptQueryString the ENC wrapper used for `_gi` (defaults to
87 * [RegistrationAttestation.encryptQueryString]); may return null on failure.
88 */
89 // ANDROID_ID is only fed into aidOf(), which hashes it into the
90 // registration integrity signal the official client sends; the raw id
91 // never leaves the device or identifies hardware to us.
92 @SuppressLint("HardwareIds")
93 fun collect(
94 context: Context,
95 nowSeconds: Long = System.currentTimeMillis() / MS_PER_SECOND,
96 encryptQueryString: (String) -> String? = RegistrationAttestation::encryptQueryString,
97 ): Signals {
98 val androidId = runCatching {
99 Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID).orEmpty()
100 }.getOrDefault("")
101
102 val aid = if (androidId.isNotEmpty()) aidOf(androidId) else ""
103 val gp = permissionsHashOf(OFFICIAL_WHATSAPP_PERMISSIONS)
104 val ge = emulationJson(virtio = probeVirtio(), vboxsf = probeVboxsf())
105 val ga = automationJson(
106 mockPackages = false,
107 multiUser = false,
108 ae = firstInstallTime(context),
109 ap = lastUpdateTime(context),
110 ai = 0L,
111 )
112 val gs = nativeSignalsJson("")
113 val gi = buildGi(encryptQueryString)
114 val db = runCatching {
115 if (Settings.Global.getInt(context.contentResolver, Settings.Global.ADB_ENABLED, 0) != 0) "1" else "0"
116 }.getOrDefault("0")
117
118 return Signals(aid = aid, gp = gp, ge = ge, ga = ga, gs = gs, gi = gi, db = db, tSeconds = nowSeconds)
119 }
120
121 /**
122 * The OFFICIAL WhatsApp manifest permission set (com.whatsapp 2.26.29.73 / versionCode
123 * 262907320), pulled from the device's installed APK (`dumpsys package com.whatsapp` →
124 * "requested permissions"). Used for `_gp` so the hash matches the real app, not this client.
125 * [permissionsHashOf] sorts before hashing, so declared order here is irrelevant.
126 */
127 private val OFFICIAL_WHATSAPP_PERMISSIONS: List<String> = listOf(
128 "android.permission.ACCESS_COARSE_LOCATION",
129 "android.permission.ACCESS_FINE_LOCATION",
130 "android.permission.ACCESS_LOCAL_NETWORK",
131 "android.permission.ACCESS_MEDIA_LOCATION",
132 "android.permission.ACCESS_NETWORK_STATE",
133 "android.permission.ACCESS_WIFI_STATE",
134 "android.permission.ANSWER_PHONE_CALLS",
135 "android.permission.AUTHENTICATE_ACCOUNTS",
136 "android.permission.BLUETOOTH_CONNECT",
137 "android.permission.BROADCAST_STICKY",
138 "android.permission.CALL_PHONE",
139 "android.permission.CAMERA",
140 "android.permission.CHANGE_NETWORK_STATE",
141 "android.permission.CHANGE_WIFI_STATE",
142 "android.permission.DETECT_SCREEN_CAPTURE",
143 "android.permission.DETECT_SCREEN_RECORDING",
144 "android.permission.FOREGROUND_SERVICE",
145 "android.permission.FOREGROUND_SERVICE_CAMERA",
146 "android.permission.FOREGROUND_SERVICE_DATA_SYNC",
147 "android.permission.FOREGROUND_SERVICE_LOCATION",
148 "android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK",
149 "android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION",
150 "android.permission.FOREGROUND_SERVICE_MICROPHONE",
151 "android.permission.FOREGROUND_SERVICE_PHONE_CALL",
152 "android.permission.GET_ACCOUNTS",
153 "android.permission.GET_TASKS",
154 "android.permission.INSTALL_SHORTCUT",
155 "android.permission.INTERNET",
156 "android.permission.MANAGE_ACCOUNTS",
157 "android.permission.MANAGE_OWN_CALLS",
158 "android.permission.MODIFY_AUDIO_SETTINGS",
159 "android.permission.NEARBY_WIFI_DEVICES",
160 "android.permission.NFC",
161 "android.permission.OTHER_SENSORS",
162 "android.permission.POST_NOTIFICATIONS",
163 "android.permission.READ_BASIC_PHONE_STATE",
164 "android.permission.READ_CALL_LOG",
165 "android.permission.READ_CONTACTS",
166 "android.permission.READ_EXTERNAL_STORAGE",
167 "android.permission.READ_MEDIA_AUDIO",
168 "android.permission.READ_MEDIA_IMAGES",
169 "android.permission.READ_MEDIA_VIDEO",
170 "android.permission.READ_MEDIA_VISUAL_USER_SELECTED",
171 "android.permission.READ_PHONE_NUMBERS",
172 "android.permission.READ_PHONE_STATE",
173 "android.permission.READ_PROFILE",
174 "android.permission.READ_SYNC_SETTINGS",
175 "android.permission.READ_SYNC_STATS",
176 "android.permission.RECEIVE_BOOT_COMPLETED",
177 "android.permission.RECEIVE_SMS",
178 "android.permission.RECORD_AUDIO",
179 "android.permission.REQUEST_INSTALL_PACKAGES",
180 "android.permission.RUN_USER_INITIATED_JOBS",
181 "android.permission.SCHEDULE_EXACT_ALARM",
182 "android.permission.SEND_SMS",
183 "android.permission.USE_BIOMETRIC",
184 "android.permission.USE_CREDENTIALS",
185 "android.permission.USE_FINGERPRINT",
186 "android.permission.USE_FULL_SCREEN_INTENT",
187 "android.permission.VIBRATE",
188 "android.permission.WAKE_LOCK",
189 "android.permission.WRITE_CONTACTS",
190 "android.permission.WRITE_EXTERNAL_STORAGE",
191 "android.permission.WRITE_SYNC_SETTINGS",
192 "com.android.launcher.permission.INSTALL_SHORTCUT",
193 "com.android.launcher.permission.UNINSTALL_SHORTCUT",
194 "com.android.vending.BILLING",
195 "com.google.android.c2dm.permission.RECEIVE",
196 "com.google.android.finsky.permission.BIND_GET_INSTALL_REFERRER_SERVICE",
197 "com.google.android.gms.permission.AD_ID",
198 "com.google.android.providers.gsf.permission.READ_GSERVICES",
199 "com.htc.launcher.permission.READ_SETTINGS",
200 "com.htc.launcher.permission.UPDATE_SHORTCUT",
201 "com.huawei.android.launcher.permission.CHANGE_BADGE",
202 "com.huawei.android.launcher.permission.READ_SETTINGS",
203 "com.huawei.android.launcher.permission.WRITE_SETTINGS",
204 "com.sec.android.provider.badge.permission.READ",
205 "com.sec.android.provider.badge.permission.WRITE",
206 "com.sonyericsson.home.permission.BROADCAST_BADGE",
207 "com.sonymobile.home.permission.PROVIDER_INSERT_BADGE",
208 "com.whatsapp.permission.BROADCAST",
209 "com.whatsapp.permission.MAPS_RECEIVE",
210 "com.whatsapp.permission.REGISTRATION",
211 )
212
213 @Suppress("DEPRECATION")
214 private fun firstInstallTime(context: Context): Long = runCatching {
215 context.packageManager.getPackageInfo(context.packageName, 0).firstInstallTime / MS_PER_SECOND
216 }.getOrDefault(0L)
217
218 @Suppress("DEPRECATION")
219 private fun lastUpdateTime(context: Context): Long = runCatching {
220 context.packageManager.getPackageInfo(context.packageName, 0).lastUpdateTime / MS_PER_SECOND
221 }.getOrDefault(0L)
222
223 /**
224 * `_gi` = ENC(JSON{apk_sha256, source_dir, size, package}) pinned to the OFFICIAL WhatsApp
225 * identity so the blob describes the real app, not this client
226 * ([WhatsAppRegistrationConstants.OFFICIAL_APK_SHA256_B64] etc., same pinned APK as the token).
227 */
228 private fun buildGi(encrypt: (String) -> String?): String? = runCatching {
229 val json = buildString {
230 append('{')
231 append("\"apk_sha256\":\"").append(WhatsAppRegistrationConstants.OFFICIAL_APK_SHA256_B64).append("\",")
232 append("\"source_dir\":\"").append(WhatsAppRegistrationConstants.OFFICIAL_SOURCE_DIR).append("\",")
233 append("\"size\":").append(WhatsAppRegistrationConstants.OFFICIAL_APK_SIZE).append(',')
234 append("\"package\":\"").append(WhatsAppRegistrationConstants.PACKAGE_NAME).append("\"")
235 append('}')
236 }
237 encrypt(json)
238 }.getOrNull()
239
240 private fun probeVirtio(): Boolean = runCatching {
241 Build.HARDWARE.contains("virtio", ignoreCase = true) ||
242 File("/proc/mounts").takeIf { it.exists() }?.readText()?.contains("virtio") == true
243 }.getOrDefault(false)
244
245 private fun probeVboxsf(): Boolean = runCatching {
246 File("/proc/mounts").takeIf { it.exists() }?.readText()?.contains("vboxsf") == true
247 }.getOrDefault(false)
248}