-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShieldModule.kt
More file actions
403 lines (361 loc) · 14.2 KB
/
ShieldModule.kt
File metadata and controls
403 lines (361 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package com.shield
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.Arguments
import java.io.File
import java.io.BufferedReader
import java.io.InputStreamReader
import java.security.MessageDigest
import android.provider.Settings
import android.content.pm.PackageManager
import android.content.pm.Signature
import com.facebook.react.bridge.LifecycleEventListener
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import com.facebook.react.bridge.UiThreadUtil
import com.google.android.play.core.integrity.IntegrityManagerFactory
import com.google.android.play.core.integrity.IntegrityTokenRequest
class ShieldModule(reactContext: ReactApplicationContext) :
NativeShieldSpec(reactContext) {
private var isClipboardProtectionEnabled = false
private val lifecycleEventListener = object : LifecycleEventListener {
override fun onHostResume() {}
override fun onHostPause() {
if (isClipboardProtectionEnabled) {
val clipboard = reactApplicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText("", ""))
}
}
override fun onHostDestroy() {}
}
init {
reactApplicationContext.addLifecycleEventListener(lifecycleEventListener)
}
override fun isRooted(): Boolean {
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3()
}
override fun isEmulator(): Boolean {
return (android.os.Build.BRAND.startsWith("generic") && android.os.Build.DEVICE.startsWith("generic"))
|| android.os.Build.FINGERPRINT.startsWith("generic")
|| android.os.Build.FINGERPRINT.startsWith("unknown")
|| android.os.Build.HARDWARE.contains("goldfish")
|| android.os.Build.HARDWARE.contains("ranchu")
|| android.os.Build.MODEL.contains("google_sdk")
|| android.os.Build.MODEL.contains("Emulator")
|| android.os.Build.MODEL.contains("Android SDK built for x86")
|| android.os.Build.MANUFACTURER.contains("Genymotion")
|| android.os.Build.PRODUCT.contains("sdk_google")
|| android.os.Build.PRODUCT.contains("google_sdk")
|| android.os.Build.PRODUCT.contains("sdk")
|| android.os.Build.PRODUCT.contains("sdk_x86")
|| android.os.Build.PRODUCT.contains("sdk_gphone64_arm64")
|| android.os.Build.PRODUCT.contains("vbox86p")
|| android.os.Build.PRODUCT.contains("emulator")
|| android.os.Build.PRODUCT.contains("simulator")
}
override fun isDebuggerAttached(): Boolean {
return android.os.Debug.isDebuggerConnected() || android.os.Debug.waitingForDebugger()
}
override fun verifySignature(expectedHash: String): Boolean {
try {
val packageInfo = reactApplicationContext.packageManager.getPackageInfo(
reactApplicationContext.packageName,
PackageManager.GET_SIGNATURES
)
val signatures = packageInfo.signatures
if (signatures.isNullOrEmpty()) return false
val md = MessageDigest.getInstance("SHA-256")
for (signature in signatures) {
md.update(signature.toByteArray())
val hexString = md.digest().joinToString("") { "%02x".format(it) }
// Compare case-insensitive
if (hexString.equals(expectedHash, ignoreCase = true)) {
return true
}
}
} catch (e: Exception) {
return false
}
return false
}
override fun isHooked(): Boolean {
val suspiciousLibraries = arrayOf(
"de.robv.android.xposed.XposedBridge",
"com.saurik.substrate.MS\$SubstrateClass",
"com.saurik.substrate.MS"
)
for (library in suspiciousLibraries) {
try {
Class.forName(library)
return true
} catch (e: ClassNotFoundException) {
// Class not found, which is good
}
}
// Also check for frida server running or files
val paths = arrayOf("/data/local/tmp/frida-server", "/system/bin/app_process", "/system/bin/app_process32", "/system/bin/app_process64")
for (path in paths) {
if (path.contains("frida-server") && File(path).exists()) {
return true
}
}
return false
}
override fun isDeveloperModeEnabled(): Boolean {
val devOptions = Settings.Secure.getInt(
reactApplicationContext.contentResolver,
Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
0
) != 0
val adbEnabled = Settings.Secure.getInt(
reactApplicationContext.contentResolver,
Settings.Global.ADB_ENABLED,
0
) != 0
return devOptions || adbEnabled
}
override fun isVPNDetected(): Boolean {
val connectivityManager = reactApplicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = connectivityManager.activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
}
override fun protectClipboard(protect: Boolean, promise: com.facebook.react.bridge.Promise) {
isClipboardProtectionEnabled = protect
promise.resolve(null)
}
override fun authenticateWithBiometrics(promptMessage: String, promise: com.facebook.react.bridge.Promise) {
val activity = reactApplicationContext.currentActivity as? androidx.fragment.app.FragmentActivity
if (activity == null) {
promise.reject("NO_ACTIVITY", "Current activity is null or not a FragmentActivity")
return
}
UiThreadUtil.runOnUiThread {
val executor = ContextCompat.getMainExecutor(activity)
val biometricPrompt = BiometricPrompt(activity, executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
promise.resolve(false)
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
promise.resolve(true)
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
promise.resolve(false)
}
})
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle(promptMessage)
.setNegativeButtonText("Cancel")
.build()
biometricPrompt.authenticate(promptInfo)
}
}
override fun addSSLPinning(domain: String, publicKeyHashes: com.facebook.react.bridge.ReadableArray, promise: com.facebook.react.bridge.Promise) {
try {
val pinnerBuilder = okhttp3.CertificatePinner.Builder()
for (i in 0 until publicKeyHashes.size()) {
val hash = publicKeyHashes.getString(i)
if (hash != null) {
pinnerBuilder.add(domain, hash)
}
}
val certificatePinner = pinnerBuilder.build()
com.facebook.react.modules.network.OkHttpClientProvider.setOkHttpClientFactory {
com.facebook.react.modules.network.OkHttpClientProvider.createClientBuilder()
.certificatePinner(certificatePinner)
.build()
}
promise.resolve(null)
} catch (e: Exception) {
promise.reject("SSL_PINNING_ERROR", e)
}
}
override fun updateSSLPins(domain: String, publicKeyHashes: com.facebook.react.bridge.ReadableArray, promise: com.facebook.react.bridge.Promise) {
// Overriding the factory again creates a new OkHttp client with the new pins
addSSLPinning(domain, publicKeyHashes, promise)
}
override fun preventScreenshot(prevent: Boolean, promise: com.facebook.react.bridge.Promise) {
val activity = currentActivity
if (activity == null) {
promise.reject("NO_ACTIVITY", "Current activity is null")
return
}
activity.runOnUiThread {
try {
if (prevent) {
activity.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
} else {
activity.window.clearFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE)
}
promise.resolve(null)
} catch (e: Exception) {
promise.reject("PREVENT_SCREENSHOT_ERROR", e)
}
}
}
// Secure Storage Implementation
private fun getEncryptedSharedPreferences(): android.content.SharedPreferences {
val masterKey = androidx.security.crypto.MasterKey.Builder(reactApplicationContext)
.setKeyScheme(androidx.security.crypto.MasterKey.KeyScheme.AES256_GCM)
.build()
return androidx.security.crypto.EncryptedSharedPreferences.create(
reactApplicationContext,
"secret_shared_prefs",
masterKey,
androidx.security.crypto.EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
androidx.security.crypto.EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
override fun setSecureString(key: String, value: String, promise: com.facebook.react.bridge.Promise) {
try {
getEncryptedSharedPreferences().edit().putString(key, value).apply()
promise.resolve(true)
} catch (e: Exception) {
promise.reject("SECURE_STORAGE_ERROR", e)
}
}
override fun getSecureString(key: String, promise: com.facebook.react.bridge.Promise) {
try {
val value = getEncryptedSharedPreferences().getString(key, null)
promise.resolve(value)
} catch (e: Exception) {
promise.reject("SECURE_STORAGE_ERROR", e)
}
}
override fun removeSecureString(key: String, promise: com.facebook.react.bridge.Promise) {
try {
getEncryptedSharedPreferences().edit().remove(key).apply()
promise.resolve(true)
} catch (e: Exception) {
promise.reject("SECURE_STORAGE_ERROR", e)
}
}
override fun getAllSecureKeys(promise: com.facebook.react.bridge.Promise) {
try {
val keys = Arguments.createArray()
for (key in getEncryptedSharedPreferences().all.keys) {
keys.pushString(key)
}
promise.resolve(keys)
} catch (e: Exception) {
promise.reject("SECURE_STORAGE_ERROR", e)
}
}
override fun clearAllSecureStorage(promise: com.facebook.react.bridge.Promise) {
try {
getEncryptedSharedPreferences().edit().clear().apply()
promise.resolve(true)
} catch (e: Exception) {
promise.reject("SECURE_STORAGE_ERROR", e)
}
}
override fun getBiometricStrength(promise: com.facebook.react.bridge.Promise) {
val manager = BiometricManager.from(reactApplicationContext)
when {
manager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS ->
promise.resolve("strong")
manager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS ->
promise.resolve("weak")
else -> promise.resolve("none")
}
}
override fun getRootReasons(): com.facebook.react.bridge.WritableArray {
val reasons = Arguments.createArray()
if (checkRootMethod1()) reasons.pushString("build_tags")
if (checkRootMethod2()) reasons.pushString("su_binary")
if (checkRootMethod3()) reasons.pushString("su_command")
if (checkDangerousPackages()) reasons.pushString("dangerous_packages")
if (checkSystemMountFlags()) reasons.pushString("mount_flags")
return reasons
}
override fun requestIntegrityToken(nonce: String, promise: com.facebook.react.bridge.Promise) {
try {
val integrityManager = IntegrityManagerFactory.create(reactApplicationContext)
val request = IntegrityTokenRequest.builder()
.setNonce(nonce)
.build()
integrityManager.requestIntegrityToken(request)
.addOnSuccessListener { response -> promise.resolve(response.token()) }
.addOnFailureListener { e -> promise.reject("INTEGRITY_ERROR", e.message, e) }
} catch (e: Exception) {
promise.reject("INTEGRITY_ERROR", e.message, e)
}
}
private fun checkRootMethod1(): Boolean {
val buildTags = android.os.Build.TAGS
return buildTags != null && buildTags.contains("test-keys")
}
private fun checkRootMethod2(): Boolean {
val paths = arrayOf(
"/system/app/Superuser.apk",
"/sbin/su",
"/system/bin/su",
"/system/xbin/su",
"/data/local/xbin/su",
"/data/local/bin/su",
"/system/sd/xbin/su",
"/system/bin/failsafe/su",
"/data/local/su",
"/su/bin/su"
)
for (path in paths) {
if (File(path).exists()) return true
}
return false
}
private fun checkRootMethod3(): Boolean {
var process: Process? = null
return try {
process = Runtime.getRuntime().exec(arrayOf("/system/xbin/which", "su"))
val inReader = BufferedReader(InputStreamReader(process.inputStream))
inReader.readLine() != null
} catch (t: Throwable) {
false
} finally {
process?.destroy()
}
}
private fun checkDangerousPackages(): Boolean {
val suspiciousPackages = arrayOf(
"com.topjohnwu.magisk",
"eu.chainfire.supersu",
"com.koushikdutta.superuser",
"com.noshufou.android.su",
"com.thirdparty.superuser",
"com.yellowes.su",
"com.zachspong.temprootremovejb",
"com.ramdroid.appquarantine"
)
val pm = reactApplicationContext.packageManager
for (pkg in suspiciousPackages) {
try {
pm.getPackageInfo(pkg, 0)
return true
} catch (_: PackageManager.NameNotFoundException) {}
}
return false
}
private fun checkSystemMountFlags(): Boolean {
try {
val reader = BufferedReader(InputStreamReader(File("/proc/mounts").inputStream()))
var line: String?
while (reader.readLine().also { line = it } != null) {
val l = line ?: continue
if (l.contains("/system") && l.contains(" rw,")) return true
}
} catch (_: Exception) {}
return false
}
companion object {
const val NAME = "Shield"
}
}