How to Prevent Keystroke Injection Attacks in Android Apps
Learn to Prevent Keystroke Injection in Android apps, in mobile CI/CD with a Data-Driven DevSecOps™ build system.
What is Keystroke Injection?
Keystroke injection is an attack method whereby a hacker uses one of several techniques to take control over Android apps remotely and inject keys, keystrokes, or manipulate gestures (for example: swipe left and right) to commit mobile fraud during runtime. While this attack technique is primarily used for committing ad fraud or mobile game fraud, it can also be utilized as part of ransomware and other elaborate fraud schemes. Keystroke injection is accomplished either by using Android Debug Bridge (ADB) via USB, or via a separate malicious app that runs on the device and has app permissions enabled that allow key injection. Users are usually tricked by hackers into downloading malicious apps through social engineering and other techniques, and into enabling key injection permissions via overlay attacks.
Why Prevent Keystroke Injection in Android Apps?
Keystroke Injection is an indication of malicious activity, intended for committing ad fraud or mobile game fraud, or even worse, as part of a ransomware and other elaborate fraud schemes. As such, Keystroke injection should be blocked to prevent having malicious actors gain access to, or even control of your device.
Prerequisites for Using Prevent Keystroke Injection:
To use Appdome’s mobile app security build system to Prevent Keystroke Injection , you’ll need:
- Appdome account (create a free Appdome account here)
- A license for Prevent Keystroke Injection
- Mobile App (.apk or .aab for Android)
- Signing Credentials (see Signing Secure Android apps and Signing Secure iOS apps)
Prevent Keystroke Injection on Android apps using Appdome
On Appdome, follow these 3 simple steps to create self-defending Android Apps that Prevent Keystroke Injection without an SDK or gateway:
-
Upload the Mobile App to Appdome.
-
Upload an app to Appdome’s Mobile App Security Build System
-
Upload Method: Appdome Console or DEV-API
-
Android Formats: .apk or .aab
-
Prevent Keystroke Injection Compatible With: Java, JS, C++, C#, Kotlin, Flutter, React Native, Unity, Xamarin, Cordova and other Android apps
-
-
Build the feature: Prevent Keystroke Injection.
-
Building Prevent Keystroke Injection by using Appdome’s DEV-API:
-
Create and name the Fusion Set (security template) that will contain the Prevent Keystroke Injection feature as shown below:
-
Follow the steps in Sections 2.2.1-2.2.2 of this article, Building the Prevent Keystroke Injection feature via Appdome Console, to add the Prevent Keystroke Injection feature to this Fusion Set.
-
Open the Fusion Set Detail Summary by clicking the “...” symbol on the far-right corner of the Fusion Set. Copy the Fusion Set ID from the Fusion Set Detail Summary (as shown below):
Figure 2: Fusion Set Detail Summary
Note: Annotating the Fusion Set to identify the protection(s) selected is optional only (not mandatory). -
Follow the instructions below to use the Fusion Set ID inside any standard mobile DevOps or CI/CD toolkit like Bitrise, App Center, Jenkins, Travis, Team City, Circle CI or other system:
-
Build an API for the app – for instructions, see the tasks under Appdome API Reference Guide
-
Look for sample APIs in Appdome’s GitHub Repository
-
Figure 1: Fusion Set that will contain the Prevent Keystroke Injection feature
Note: Naming the Fusion Set to correspond to the protection(s) selected is for illustration purposes only (not required). -
-
Building the Prevent Keystroke Injection feature via Appdome Console
To build the Prevent Keystroke Injection protection by using Appdome Console, follow the instructions below.
-
Where: Inside the Appdome Console, go to Build > Anti Fraud Tab > Mobile Fraud Detection section.
-
How: Check whether is toggled On (enabled), otherwise enable it . The feature Prevent Keystroke Injection is enabled by default, as shown below. Toggle (turn ON) Prevent Keystroke Injection, as shown below.
If needed, Customize the Threat Notification to be displayed to the mobile end-user in a standard OS dialog notification when Appdome Prevents Keystroke Injection.Figure 3: Prevent Keystroke Injection option
Note: The App Compromise Notification contains an easy to follow default remediation path for the mobile app end user. You can customize this message as required to achieve brand specific support, workflow or other messaging. -
When you select the Prevent Keystroke Injection you'll notice that your Fusion Set you created in step 2.1.1 now bears the icon of the protection category that contains Prevent Keystroke Injection
Figure 4: Fusion Set that displays the newly added Prevent Keystroke Injection protection
-
Select the Threat-Event™ in-app mobile Threat Defense and Intelligence policy for Prevent Keystroke Injection:
-
Threat-Events™ OFF > In-App Defense
If the Threat-Events™ setting is cleared (not selected). Appdome will detect and defend the user and app by enforcing Prevent Keystroke Injection.
-
Threat-Events™ ON > In-App Detection
When this setting is used, Appdome detects the use of key injection and passes Appdome’s Threat-Event™ attack intelligence to the app’s business logic for processing, enforcement, and user notification. For more information on consuming and using Appdome Threat-Events™ in the app, see section Using Threat-Events™ for Prevent Keystroke Injection Intelligence and Control in Mobile Apps.
-
Threat-Events™ ON > In-App Defense
When this setting is used, Appdome detects and defends against Keystroke Injection (same as Appdome Enforce) and passes Appdome’s Threat-Event™ attack intelligence the app’s business logic for processing. For more information on consuming and using Appdome Threat-Events™ in the app, see section Using Threat-Events™ for Prevent Keystroke Injection Intelligence and Control in Mobile Apps.
-
-
Click Build My App at the bottom of the Build Workflow (shown in Figure 3).
-
Congratulations! The Prevent Keystroke Injection protection is now added to the mobile app -
-
Certify the Prevent Keystroke Injection feature in Android Apps
After building Prevent Keystroke Injection, Appdome generates a Certified Secure™ certificate to guarantee that the Prevent Keystroke Injection protection has been added and is protecting the app. To verify that the Prevent Keystroke Injection protection has been added to the mobile app, locate the protection in the Certified Secure™ certificate as shown below:
Figure 5: Certified Secure™ certificate
Each Certified Secure™ certificate provides DevOps and DevSecOps organizations the entire workflow summary, audit trail of each build, and proof of protection that Prevent Keystroke Injection has been added to each Android app. Certified Secure provides instant and in-line DevSecOps compliance certification that Prevent Keystroke Injection and other mobile app security features are in each build of the mobile app
Using Threat-Events™ for Keystroke Injection Intelligence and Control in Android Apps
Appdome Threat-Events™ provides consumable in-app mobile app attack intelligence and defense control when Keystroke Injection is detected. To consume and use Threat-Events™ for Keystroke Injection in Android Apps, use registerReceiver in the Application OnCreate, and the code samples for Threat-Events™ for Keystroke Injection shown below.
The specifications and options for Threat-Events™ for Keystroke Injection are:
Threat-Event™ Elements | Prevent Keystroke Injection Method Detail |
---|---|
Appdome Feature Name | Prevent Keystroke Injection |
Threat-Event Mode | |
OFF, IN-APP DEFENSE | Appdome detects, defends and notifies user (standard OS dialog) using customizable messaging. |
ON, IN-APP DETECTION | Appdome detects the attack or threat and passes the event in a standard format to the app for processing (app chooses how and when to enforce). |
ON, IN-APP DEFENSE | Uses Appdome Enforce mode for any attack or threat and passes the event in a standard format to the app for processing (gather intel on attacks and threats without losing any protection). |
Certified Secure™ Threat Event Check | |
Visible in ThreatScope™ | |
Developer Parameters for Preventing Keystroke Injection Threat-Event™ | |
Threat-Event NAME | KeyInjectionDetected |
Threat-Event DATA | reasonData |
Threat-Event CODE | reasonCode |
Threat-Event REF | 6801 |
Threat-Event SCORE | |
currentThreatEventScore | Current Threat-Event score |
threatEventsScore | Total Threat-events score |
Threat-Event Context Keys | |
---|---|
message | Message displayed for the user on event |
failSafeEnforce | Timed enforcement against the identified threat |
externalID | The external ID of the event which can be listened via Threat Events |
osVersion | OS version of the current device |
deviceModel | Current device model |
deviceManufacturer | The manufacturer of the current device |
fusedAppToken | The task ID of the Appdome fusion of the currently running app |
kernelInfo | Info about the kernel: system name, node name, release, version and machine. |
carrierPlmn | PLMN of the device. Only available for Android devices. |
deviceID | Current device ID |
reasonCode | Reason code of the occurred event |
buildDate | Appdome fusion date of the current application |
devicePlatform | OS name of the current device |
carrierName | Carrier name of the current device. Only available for Android. |
updatedOSVersion | Is the OS version up to date |
deviceBrand | Brand of the device |
deviceBoard | Board of the device |
buildUser | Build user |
buildHost | Build host |
sdkVersion | Sdk version |
timeZone | Time zone |
deviceFaceDown | Is the device face down |
locationLong | Location longitude conditioned by location permission |
locationLat | Location latitude conditioned by location permission |
locationState | Location state conditioned by location permission |
wifiSsid | Wifi SSID |
wifiSsidPermissionStatus | Wifi SSID permission status |
With Threat-Events™ enabled (turned ON), Android developers can get detailed attack intelligence and granular defense control in Android applications and create amazing user experiences for all mobile end users when Keystroke Injection is detected.
The following is a code sample for native Android apps, which uses all values in the specification above for Prevent Keystroke Injection:
Important! Replace all placeholder instances of <Context Key> with the specific name of your threat event context key across all language examples. This is crucial to ensure your code functions correctly with the intended event data. For example, The <Context Key> could be the message, externalID, OS Version, reason code, etc.
xxxxxxxxxx
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("KeyInjectionDetected");
BroadcastReceiver threatEventReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message"); // Message shown to the user
String reasonData = intent.getStringExtra("reasonData"); // Threat detection cause
String reasonCode = intent.getStringExtra("reasonCode"); // Event reason code
// Current threat event score
String currentThreatEventScore = intent.getStringExtra("currentThreatEventScore");
// Total threat events score
String threatEventsScore = intent.getStringExtra("threatEventsScore");
// Replace '<Context Key>' with your specific event context key
// String variable = intent.getStringExtra("<Context Key>");
// Your logic goes here (Send data to Splunk/Dynatrace/Show Popup...)
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
registerReceiver(threatEventReceiver, intentFilter, Context.RECEIVER_NOT_EXPORTED);
} else {
registerReceiver(threatEventReceiver, intentFilter);
}
xxxxxxxxxx
val intentFilter = IntentFilter()
intentFilter.addAction("KeyInjectionDetected")
val threatEventReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var message = intent?.getStringExtra("message") // Message shown to the user
var reasonData = intent?.getStringExtra("reasonData") // Threat detection cause
var reasonCode = intent?.getStringExtra("reasonCode") // Event reason code
// Current threat event score
var currentThreatEventScore = intent?.getStringExtra("currentThreatEventScore")
// Total threat events score
var threatEventsScore = intent?.getStringExtra("threatEventsScore")
// Replace '<Context Key>' with your specific event context key
// var variable = intent?.getStringExtra("<Context Key>")
// Your logic goes here (Send data to Splunk/Dynatrace/Show Popup...)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
registerReceiver(threatEventReceiver, intentFilter, Context.RECEIVER_NOT_EXPORTED)
} else {
registerReceiver(threatEventReceiver, intentFilter)
}
xxxxxxxxxx
const { ADDevEvents } = NativeModules;
const aDDevEvents = new NativeEventEmitter(ADDevEvents);
function registerToDevEvent(action, callback) {
NativeModules.ADDevEvents.registerForDevEvent(action);
aDDevEvents.addListener(action, callback);
}
export function registerToAllEvents() {
registerToDevEvent(
"KeyInjectionDetected",
(userinfo) => Alert.alert(JSON.stringify(userinfo))
var message = userinfo["message"] // Message shown to the user
var reasonData = userinfo["reasonData"] // Threat detection cause
var reasonCode = userinfo["reasonCode"] // Event reason code
// Current threat event score
var currentThreatEventScore = userinfo["currentThreatEventScore"]
// Total threat events score
var threatEventsScore = userinfo["threatEventsScore"]
// Replace '<Context Key>' with your specific event context key
// var variable = userinfo["<Context Key>"]
// Your logic goes here (Send data to Splunk/Dynatrace/Show Popup...)
);
}
x
RegisterReceiver(new ThreatEventReceiver(), new IntentFilter("KeyInjectionDetected"));
class ThreatEventReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
// Message shown to the user
String message = intent.GetStringExtra("message");
// Threat detection cause
String reasonData = intent.GetStringExtra("reasonData");
// Event reason code
String reasonCode = intent.GetStringExtra("reasonCode");
// Current threat event score
String currentThreatEventScore = intent.GetStringExtra("currentThreatEventScore");
// Total threat events score
String threatEventsScore = intent.GetStringExtra("threatEventsScore");
// Replace '<Context Key>' with your specific event context key
// String variable = intent.GetStringExtra("<Context Key>");
// Your logic goes here (Send data to Splunk/Dynatrace/Show Popup...)
}
}
x
NSNotificationCenter.DefaultCenter.AddObserver(
(NSString)"KeyInjectionDetected", // Threat-Event Identifier
delegate (NSNotification notification)
{
// Message shown to the user
var message = notification.UserInfo.ObjectForKey("message");
// Threat detection cause
var reasonData = notification.UserInfo.ObjectForKey("reasonData");
// Event reason code
var reasonCode = notification.UserInfo.ObjectForKey("reasonCode");
// Current threat event score
var currentThreatEventScore = notification.UserInfo.ObjectForKey("currentThreatEventScore");
// Total threat events score
var threatEventsScore = notification.UserInfo.ObjectForKey("threatEventsScore");
// Replace '<Context Key>' with your specific event context key
// var variable = notification.UserInfo.ObjectForKey("<Context Keys>");
// Your logic goes here (Send data to Splunk/Dynatrace/Show Popup...)
}
);
xxxxxxxxxx
window.broadcaster.addEventListener("KeyInjectionDetected", function(userInfo) {
var message = userInfo.message // Message shown to the user
var reasonData = userInfo.reasonData // Threat detection cause
var reasonCode = userInfo.reasonCode // Event reason code
// Current threat event score
var currentThreatEventScore = userInfo.currentThreatEventScore
// Total threat events score
var threatEventsScore = userInfo.threatEventsScore
// Replace '<Context Key>' with your specific event context key
// var variable = userInfo.<Context Keys>
// Your logic goes here (Send data to Splunk/Dynatrace/Show Popup...)
});
x
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class PlatformChannel extends StatefulWidget {
const PlatformChannel({super.key});
State<PlatformChannel> createState() => _PlatformChannelState();
}
class _PlatformChannelState extends State<PlatformChannel> {
// Replace with your EventChannel name
static const String _eventChannelName = "KeyInjectionDetected";
static const EventChannel _eventChannel = EventChannel(_eventChannelName);
void initState() {
super.initState();
_eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
}
void _onEvent(Object? event) {
setState(() {
// Adapt this section based on your specific event data structure
var eventData = event as Map;
// Example: Accessing 'externalID' field from the event
var externalID = eventData['externalID'];
// Customize the rest of the fields based on your event structure
String message = eventData['message']; // Message shown to the user
String reasonData = eventData['reasonData']; // Threat detection cause
String reasonCode = eventData['reasonCode']; // Event reason code
// Current threat event score
String currentThreatEventScore = eventData['currentThreatEventScore'];
// Total threat events score
String threatEventsScore = eventData['threatEventsScore'];
// Replace '<Context Key>' with your specific event context key
// String variable = eventData['<Context Keys>'];
});
}
// Your logic goes here (Send data to Splunk/Dynatrace/Show Popup...)
}
Using Appdome, there are no development or coding prerequisites to build secured Android Apps by using Prevent Keystroke Injection. There is no SDK and no library to code or implement in the app and no gateway to deploy in your network. All protections are built into each app and the resulting app is self-defending and self-protecting.
Releasing and Publishing Mobile Apps with Prevent Keystroke Injection
After successfully securing your app by using Appdome, there are several available options to complete your project, depending on your app lifecycle or workflow. These include:
- Customizing, Configuring & Branding Secure Mobile Apps
- Deploying/Publishing Secure mobile apps to Public or Private app stores
- Releasing Secured Android & iOS Apps built on Appdome.
Related Articles:
How to Protect Android & iOS Apps from Keylogging Attacks
How to Protect Android Apps from Overlay Attacks & Malware
How to Use Android Memory Protection to Defeat Memory Editing in Android Apps
How Do I Learn More?
If you have any questions, please send them our way at support.appdome.com or via the chat window on the Appdome platform.
Thank you!
Thanks for visiting Appdome! Our mission is to secure every app on the planet by making mobile app security easy. We hope we’re living up to the mission with your project.