-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFreeraspPlugin.kt
More file actions
379 lines (341 loc) · 13.4 KB
/
FreeraspPlugin.kt
File metadata and controls
379 lines (341 loc) · 13.4 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
package com.aheaditec.freerasp
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import com.aheaditec.freerasp.utils.Utils
import com.aheaditec.freerasp.utils.getArraySafe
import com.aheaditec.freerasp.utils.getNestedArraySafe
import com.aheaditec.freerasp.utils.toEncodedJSArray
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.freerasp.events.BaseRaspEvent
import com.aheaditec.freerasp.events.RaspExecutionStateEvent
import com.aheaditec.freerasp.events.ThreatEvent
import com.aheaditec.freerasp.interfaces.PluginExecutionStateListener
import com.aheaditec.freerasp.interfaces.PluginThreatListener
import com.getcapacitor.JSObject
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin
import org.json.JSONArray
typealias CapacitorCallback = (String, JSObject) -> Unit
@CapacitorPlugin(name = "Freerasp")
class FreeraspPlugin : Plugin() {
override fun load() {
initializeEventKeys()
val pluginCallback: CapacitorCallback = { eventName, data ->
notifyListeners(eventName, data, true)
}
PluginThreatHandler.initializeDispatchers(PluginListener(context, pluginCallback))
super.load()
}
@PluginMethod
fun talsecStart(call: PluginCall) {
if (talsecStarted) {
call.resolve(JSObject().put("started", true))
return
}
val config = call.getObject("config")
if (config == null) {
call.reject("Missing config parameter in freeRASP Native Plugin")
return
}
try {
val talsecConfig = buildTalsecConfigThrowing(config)
PluginThreatHandler.registerSDKListener(context)
bridge.activity.runOnUiThread {
Talsec.start(context, talsecConfig)
mainHandler.post {
talsecStarted = true
// This code must be called only AFTER Talsec.start
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
ScreenProtector.register(activity)
}
call.resolve(JSObject().put("started", true))
}
}
} catch (e: Exception) {
call.reject(
"Error during Talsec Native plugin initialization - ${e.message}",
"TalsecInitializationError",
e
)
}
}
@PluginMethod(returnType = PluginMethod.RETURN_NONE)
override fun addListener(call: PluginCall) {
val eventName = call.getString("eventName")
if (eventName == ThreatEvent.CHANNEL_NAME) {
PluginThreatHandler.threatDispatcher.registerListener()
}
if (eventName == RaspExecutionStateEvent.CHANNEL_NAME) {
PluginThreatHandler.executionStateDispatcher.registerListener()
}
super.addListener(call)
}
@PluginMethod(returnType = PluginMethod.RETURN_NONE)
fun removeListenerForEvent(call: PluginCall) {
val eventName = call.getString("eventName")
if (eventName == ThreatEvent.CHANNEL_NAME) {
PluginThreatHandler.threatDispatcher.unregisterListener()
}
if (eventName == RaspExecutionStateEvent.CHANNEL_NAME) {
PluginThreatHandler.executionStateDispatcher.unregisterListener()
}
}
override fun handleOnPause() {
super.handleOnPause()
PluginThreatHandler.threatDispatcher.onPause()
PluginThreatHandler.executionStateDispatcher.onPause()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
ScreenProtector.unregister(activity)
}
if (activity.isFinishing) {
PluginThreatHandler.threatDispatcher.unregisterListener()
PluginThreatHandler.executionStateDispatcher.unregisterListener()
PluginThreatHandler.unregisterSDKListener(context)
}
}
override fun handleOnResume() {
super.handleOnResume()
PluginThreatHandler.threatDispatcher.onResume()
PluginThreatHandler.executionStateDispatcher.onResume()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
ScreenProtector.register(activity)
}
}
override fun handleOnDestroy() {
super.handleOnDestroy()
backgroundHandlerThread.quitSafely()
}
// Trigger lazy initialization of the freeRASP events
private fun initializeEventKeys() {
ThreatEvent.ALL_EVENTS
RaspExecutionStateEvent.ALL_EVENTS
}
/**
* Method to get the random identifiers of callbacks
*/
@PluginMethod
fun getThreatIdentifiers(call: PluginCall) {
call.resolve(JSObject().put("ids", ThreatEvent.ALL_EVENTS))
}
/**
* Method to get the random identifiers of callbacks
*/
@PluginMethod
fun getRaspExecutionStateIdentifiers(call: PluginCall) {
call.resolve(JSObject().put("ids", RaspExecutionStateEvent.ALL_EVENTS))
}
/**
* Method to setup the message passing between native and Capacitor
* @return list of [CHANNEL_NAME, CHANNEL_KEY, MALWARE_CHANNEL_KEY]
*/
@PluginMethod
fun getThreatChannelData(call: PluginCall) {
val channelData = JSONArray(
(listOf(
ThreatEvent.CHANNEL_NAME, ThreatEvent.CHANNEL_KEY, ThreatEvent.MALWARE_CHANNEL_KEY
))
)
call.resolve(JSObject().put("ids", channelData))
}
/**
* Method to setup the execution state message passing between native and Capacitor
* @return list of [CHANNEL_NAME, CHANNEL_KEY]
*/
@PluginMethod
fun getRaspExecutionStateChannelData(call: PluginCall) {
val channelData = JSONArray(
(listOf(
RaspExecutionStateEvent.CHANNEL_NAME, RaspExecutionStateEvent.CHANNEL_KEY
))
)
call.resolve(JSObject().put("ids", channelData))
}
/**
* We never send an invalid callback over our channel.
* Therefore, if this happens, we want to kill the app.
*/
@PluginMethod
fun onInvalidCallback(call: PluginCall) {
android.os.Process.killProcess(android.os.Process.myPid())
}
/**
* Add app with given package name to Talsec Malware Whitelist
* @param packageName - package name of the whitelisted app
* @return true if successful
*/
@PluginMethod
fun addToWhitelist(call: PluginCall) {
val packageName = call.getString("packageName")
if (packageName.isNullOrEmpty()) {
call.reject(
"Package name argument is missing or empty in the call",
"MissingArgumentError"
)
return
}
Talsec.addToWhitelist(context, packageName)
call.resolve(JSObject().put("result", 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
*/
@PluginMethod
fun getAppIcon(call: PluginCall) {
val packageName = call.getString("packageName")
if (packageName.isNullOrEmpty()) {
call.reject(
"Package name argument is missing or empty in the call",
"MissingArgumentError"
)
return
}
// Perform the app icon encoding on a background thread
backgroundHandler.post {
val encodedData = Utils.getAppIconAsBase64String(context, packageName)
mainHandler.post { call.resolve(JSObject().put("result", encodedData)) }
}
}
/**
* Method to set screen capture state
* @param enable Pass `true` to block screen capture, `false` to enable it
*/
@PluginMethod
fun blockScreenCapture(call: PluginCall) {
val enable = call.getBoolean("enable") ?: run {
call.reject(
"Enable argument is missing or not a boolean.", "MissingArgumentError"
)
return
}
activity?.runOnUiThread {
try {
Talsec.blockScreenCapture(activity, enable)
call.resolve(JSObject().put("result", true))
} catch (e: Exception) {
call.reject(
"Error while setting screen capture: ${e.message}", "BlockScreenCaptureError"
)
}
} ?: run {
call.reject("Cannot block screen capture, activity is null.", "BlockScreenCaptureError")
}
}
/**
* Method to check if screen capturing is currently blocked
*/
@PluginMethod
fun isScreenCaptureBlocked(call: PluginCall) {
try {
val isBlocked = Talsec.isScreenCaptureBlocked()
call.resolve(JSObject().put("result", isBlocked))
} catch (e: Exception) {
call.reject(
"Error while checking if screen capture is blocked: ${e.message}",
"IsScreenCaptureBlockedError"
)
}
}
@PluginMethod
fun storeExternalId(call: PluginCall) {
val externalId = call.getString("data")
if (externalId.isNullOrEmpty()) {
call.reject(
"External ID not provided", "MissingArgumentError"
)
return
}
try {
Talsec.storeExternalId(context, externalId)
call.resolve(JSObject().put("result", true))
} catch (e: Exception) {
call.reject(
"Error during storeExternalId operation in freeRASP Native Plugin",
"NativePluginError"
)
return
}
}
@PluginMethod
fun removeExternalId(call: PluginCall) {
try {
Talsec.removeExternalId(context)
call.resolve(JSObject().put("result", true))
} catch (e: Exception) {
call.reject(
"Error during removeExternalId operation in freeRASP Native Plugin",
"NativePluginError"
)
return
}
}
private fun buildTalsecConfigThrowing(configJson: JSObject): TalsecConfig {
val androidConfig = configJson.getJSONObject("androidConfig")
val packageName = androidConfig.getString("packageName")
val certificateHashes = androidConfig.getArraySafe("certificateHashes")
val talsecBuilder = TalsecConfig.Builder(packageName, certificateHashes)
.watcherMail(configJson.getString("watcherMail"))
.supportedAlternativeStores(androidConfig.getArraySafe("supportedAlternativeStores"))
.prod(configJson.getBool("isProd") ?: true)
.killOnBypass(configJson.getBool("killOnBypass") ?: false)
if (androidConfig.has("malwareConfig")) {
val malwareConfig = androidConfig.getJSONObject("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 {
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 context: Context,
private val pluginCallback: CapacitorCallback
) : PluginThreatListener, PluginExecutionStateListener {
override fun threatDetected(threatEventType: ThreatEvent) {
notifyEvent(threatEventType, pluginCallback)
}
override fun malwareDetected(suspiciousApps: MutableList<SuspiciousAppInfo>) {
notifyMalware(suspiciousApps, context, pluginCallback)
}
override fun raspExecutionStateChanged(event: RaspExecutionStateEvent) {
notifyEvent(event, pluginCallback)
}
private fun notifyEvent(
event: BaseRaspEvent,
notifyListenersCallback: CapacitorCallback
) {
val params = JSObject().put(event.channelKey, event.value)
notifyListenersCallback(event.channelName, params)
}
private fun notifyMalware(
suspiciousApps: MutableList<SuspiciousAppInfo>,
context: Context,
notifyListenersCallback: CapacitorCallback
) {
// Perform the malware encoding on a background thread
backgroundHandler.post {
val encodedSuspiciousApps = suspiciousApps.toEncodedJSArray(context)
mainHandler.post {
val params = JSObject()
.put(ThreatEvent.CHANNEL_KEY, ThreatEvent.Malware.value)
.put(ThreatEvent.MALWARE_CHANNEL_KEY, encodedSuspiciousApps)
notifyListenersCallback.invoke(ThreatEvent.CHANNEL_NAME, params)
}
}
}
}
}