-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathFreeraspReactNativeModule.kt
More file actions
354 lines (315 loc) · 12.1 KB
/
FreeraspReactNativeModule.kt
File metadata and controls
354 lines (315 loc) · 12.1 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
package com.freeraspreactnative
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import com.aheaditec.talsec_security.security.api.ExternalIdResult
import com.aheaditec.talsec_security.security.api.SuspiciousAppInfo
import com.aheaditec.talsec_security.security.api.Talsec
import com.aheaditec.talsec_security.security.api.TalsecConfig
import com.aheaditec.talsec_security.security.api.TalsecMode
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.LifecycleEventListener
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.UiThreadUtil.runOnUiThread
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.freeraspreactnative.events.RaspExecutionStateEvent
import com.freeraspreactnative.events.ThreatEvent
import com.freeraspreactnative.interfaces.PluginExecutionStateListener
import com.freeraspreactnative.interfaces.PluginThreatListener
import com.freeraspreactnative.utils.Utils
import com.freeraspreactnative.utils.getArraySafe
import com.freeraspreactnative.utils.getBooleanSafe
import com.freeraspreactnative.utils.getMapThrowing
import com.freeraspreactnative.utils.getNestedArraySafe
import com.freeraspreactnative.utils.getStringThrowing
import com.freeraspreactnative.utils.toEncodedWritableArray
class FreeraspReactNativeModule(private val reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
private val lifecycleListener = object : LifecycleEventListener {
override fun onHostResume() {
PluginThreatHandler.threatDispatcher.onResume()
PluginThreatHandler.executionStateDispatcher.onResume()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
reactContext.currentActivity?.let { ScreenProtector.register(it) }
}
}
override fun onHostPause() {
PluginThreatHandler.threatDispatcher.onPause()
PluginThreatHandler.executionStateDispatcher.onPause()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
reactContext.currentActivity?.let { ScreenProtector.unregister(it) }
}
if (reactContext.currentActivity?.isFinishing == true) {
PluginThreatHandler.threatDispatcher.unregisterListener()
PluginThreatHandler.executionStateDispatcher.unregisterListener()
PluginThreatHandler.unregisterSDKListener(reactContext)
}
}
override fun onHostDestroy() {
backgroundHandlerThread.quitSafely()
}
}
override fun getName(): String {
return NAME
}
init {
reactContext.addLifecycleEventListener(lifecycleListener)
initializeEventKeys()
PluginThreatHandler.initializeDispatchers(PluginListener(reactContext))
}
@ReactMethod
fun talsecStart(
options: ReadableMap, promise: Promise
) {
if (talsecStarted) {
promise.resolve("freeRASP started")
return
}
try {
val config = buildTalsecConfig(options)
PluginThreatHandler.registerSDKListener(reactContext)
runOnUiThread {
Talsec.start(reactContext, config, TalsecMode.BACKGROUND)
mainHandler.post {
talsecStarted = true
// This code must be called only AFTER Talsec.start
reactContext.currentActivity?.let { activity ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
ScreenProtector.register(activity)
}
}
promise.resolve("freeRASP started")
}
}
} catch (e: Exception) {
promise.reject("TalsecInitializationError", e.message, e)
}
}
// Trigger lazy initialization of the freeRASP events
private fun initializeEventKeys() {
ThreatEvent.ALL_EVENTS
RaspExecutionStateEvent.ALL_EVENTS
}
/**
* Method to get the random identifiers of callbacks
*/
@ReactMethod
fun getThreatIdentifiers(promise: Promise) {
promise.resolve(ThreatEvent.ALL_EVENTS)
}
/**
* Method to get the random identifiers of callbacks
*/
@ReactMethod
fun getRaspExecutionStateIdentifiers(promise: Promise) {
promise.resolve(RaspExecutionStateEvent.ALL_EVENTS)
}
/**
* Method to setup the threat message passing between native and React Native
* @return list of [THREAT_CHANNEL_NAME, THREAT_CHANNEL_KEY]
*/
@ReactMethod
fun getThreatChannelData(promise: Promise) {
val channelData: WritableArray = Arguments.createArray()
channelData.pushString(ThreatEvent.CHANNEL_NAME)
channelData.pushString(ThreatEvent.CHANNEL_KEY)
channelData.pushString(ThreatEvent.MALWARE_CHANNEL_KEY)
promise.resolve(channelData)
}
/**
* Method to setup the execution state message passing between native and React Native
* @return list of [THREAT_CHANNEL_NAME, THREAT_CHANNEL_KEY]
*/
@ReactMethod
fun getRaspExecutionStateChannelData(promise: Promise) {
val channelData: WritableArray = Arguments.createArray()
channelData.pushString(RaspExecutionStateEvent.CHANNEL_NAME)
channelData.pushString(RaspExecutionStateEvent.CHANNEL_KEY)
promise.resolve(channelData)
}
/**
* We never send an invalid callback over our channel.
* Therefore, if this happens, we want to kill the app.
*/
@ReactMethod
fun onInvalidCallback() {
android.os.Process.killProcess(android.os.Process.myPid())
}
@ReactMethod
fun addListener(eventName: String) {
if (eventName == ThreatEvent.CHANNEL_NAME) {
PluginThreatHandler.threatDispatcher.registerListener()
}
if (eventName == RaspExecutionStateEvent.CHANNEL_NAME) {
PluginThreatHandler.executionStateDispatcher.registerListener()
}
}
@ReactMethod
fun removeListeners(@Suppress("UNUSED_PARAMETER") count: Int) {
// built-in RN method, however it does not suit us as it just tells
// number of un-registered listeners, so we use `removeListenerForEvent`
}
@ReactMethod
fun removeListenerForEvent(eventName: String, promise: Promise) {
if (eventName == ThreatEvent.CHANNEL_NAME) {
PluginThreatHandler.threatDispatcher.unregisterListener()
}
if (eventName == RaspExecutionStateEvent.CHANNEL_NAME) {
PluginThreatHandler.executionStateDispatcher.unregisterListener()
}
promise.resolve("Listener unregistered")
}
/**
* Method to add apps to Malware whitelist, so they don't get flagged as malware
*/
@ReactMethod
fun addToWhitelist(packageName: String, promise: Promise) {
Talsec.addToWhitelist(reactContext, packageName)
promise.resolve(true)
}
/**
* Method retrieves app icon for the given parameter
* @param packageName package name of the app we want to retrieve icon for
* @return PNG with app icon encoded as a base64 string
*/
@ReactMethod
fun getAppIcon(packageName: String, promise: Promise) {
// Perform the app icon encoding on a background thread
backgroundHandler.post {
val encodedData = Utils.getAppIconAsBase64String(reactContext, packageName)
mainHandler.post { promise.resolve(encodedData) }
}
}
/**
* Method Block/Unblock screen capture
* @param enable boolean for whether want to block or unblock the screen capture
*/
@ReactMethod
fun blockScreenCapture(enable: Boolean, promise: Promise) {
val activity = reactContext.currentActivity ?: run {
promise.reject(
"NativePluginError", "Cannot block screen capture, activity is null."
)
return
}
runOnUiThread {
try {
Talsec.blockScreenCapture(activity, enable)
promise.resolve("Screen capture is now ${if (enable) "Blocked" else "Enabled"}.")
} catch (e: Exception) {
promise.reject("NativePluginError", "Error in blockScreenCapture: ${e.message}")
}
}
}
/**
* Method Returns whether screen capture is blocked or not
* @return boolean for is screem capture blocked or not
*/
@ReactMethod
fun isScreenCaptureBlocked(promise: Promise) {
try {
val isBlocked = Talsec.isScreenCaptureBlocked()
promise.resolve(isBlocked)
} catch (e: Exception) {
promise.reject("NativePluginError", "Error in isScreenCaptureBlocked: ${e.message}")
}
}
@ReactMethod
fun storeExternalId(
externalId: String, promise: Promise
) {
try {
when (val result = Talsec.storeExternalId(reactContext, externalId)) {
is ExternalIdResult.Error -> {
promise.reject(
"ExternalIdError",
"Setting up External ID failed - ${result.errorMsg}"
)
}
is ExternalIdResult.Success -> {
promise.resolve("OK - Store external ID")
return
}
}
} catch (e: Exception) {
promise.reject(
"NativePluginError",
"Error during storeExternalId operation in Talsec Native Plugin"
)
}
}
@ReactMethod
fun removeExternalId(promise: Promise) {
try {
Talsec.removeExternalId(reactContext)
promise.resolve("OK - External ID removed")
} catch (e: Exception) {
promise.reject(
"NativePluginError",
"Error during storeExternalId operation in Talsec Native Plugin"
)
}
}
private fun buildTalsecConfig(config: ReadableMap): TalsecConfig {
val androidConfig = config.getMapThrowing("androidConfig")
val packageName = androidConfig.getStringThrowing("packageName")
val certificateHashes = androidConfig.getArraySafe("certificateHashes")
val talsecBuilder = TalsecConfig.Builder(packageName, certificateHashes)
.watcherMail(config.getString("watcherMail"))
.prod(config.getBooleanSafe("isProd"))
.killOnBypass(config.getBooleanSafe("killOnBypass", false))
.supportedAlternativeStores(androidConfig.getArraySafe("supportedAlternativeStores"))
if (androidConfig.hasKey("malwareConfig")) {
val malwareConfig = androidConfig.getMapThrowing("malwareConfig")
talsecBuilder.whitelistedInstallationSources(malwareConfig.getArraySafe("whitelistedInstallationSources"))
talsecBuilder.blacklistedHashes(malwareConfig.getArraySafe("blacklistedHashes"))
talsecBuilder.blacklistedPackageNames(malwareConfig.getArraySafe("blacklistedPackageNames"))
talsecBuilder.suspiciousPermissions(malwareConfig.getNestedArraySafe("suspiciousPermissions"))
}
return talsecBuilder.build()
}
companion object {
const val NAME = "FreeraspReactNative"
private val backgroundHandlerThread = HandlerThread("BackgroundThread").apply { start() }
private val backgroundHandler = Handler(backgroundHandlerThread.looper)
private val mainHandler = Handler(Looper.getMainLooper())
internal var talsecStarted = false
}
internal class PluginListener(private val reactContext: ReactApplicationContext) :
PluginThreatListener, PluginExecutionStateListener {
override fun threatDetected(threatEventType: ThreatEvent) {
val params = Arguments.createMap()
params.putInt(threatEventType.channelKey, threatEventType.value)
notifyEvent(ThreatEvent.CHANNEL_NAME, params)
}
override fun malwareDetected(suspiciousApps: MutableList<SuspiciousAppInfo>) {
backgroundHandler.post {
val encodedSuspiciousApps = suspiciousApps.toEncodedWritableArray(reactContext)
mainHandler.post {
val params = Arguments.createMap()
params.putInt(ThreatEvent.CHANNEL_KEY, ThreatEvent.Malware.value)
params.putArray(
ThreatEvent.MALWARE_CHANNEL_KEY, encodedSuspiciousApps
)
notifyEvent(ThreatEvent.CHANNEL_NAME, params)
}
}
}
override fun raspExecutionStateChanged(event: RaspExecutionStateEvent) {
val params = Arguments.createMap()
params.putInt(event.channelKey, event.value)
notifyEvent(event.channelName, params)
}
private fun notifyEvent(eventName: String, params: WritableMap) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit(eventName, params)
}
}
}