repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
accessibility-services-abuse.mdMarkdown358 lines21.1 KiBsource raw download

title: "Android Accessibility Service Abuse" section: "Mobile" sectionSlug: "mobile-pentesting" sourcePath: "src/mobile-pentesting/android-app-pentesting/accessibility-services-abuse.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/mobile-pentesting/android-app-pentesting/accessibility-services-abuse.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0"#

Android Accessibility Service Abuse#

Overview#

AccessibilityService was created to help users with disabilities interact with Android devices. Unfortunately, the same powerful automation APIs (global navigation, text input, gesture dispatch, overlay windows…) can be weaponised by malware to gain complete remote control of the handset without root privileges.[4]

Modern Android banking Trojans and Remote-Access-Trojans (RATs) such as PlayPraetor, SpyNote, BrasDex, SOVA, ToxicPanda and many others follow the same recipe:

  1. Social-engineer the victim into enabling a rogue accessibility service (the BIND_ACCESSIBILITY_SERVICE permission is considered "high-risk" and requires an explicit user action).
  2. Leverage the service to
    • capture every UI event & text that appears on screen,
    • inject synthetic gestures (dispatchGesture) and global actions (performGlobalAction) to automate any task the operator desires,
    • draw full-screen overlays on top of legitimate apps using the TYPE_ACCESSIBILITY_OVERLAY window type (no SYSTEM_ALERT_WINDOW prompt!),
    • silently grant additional runtime permissions by clicking on the system dialogs on the victim’s behalf.
  3. Exfiltrate data or perform On-Device-Fraud (ODF) in real-time while the user is looking at a perfectly normal screen.

Packed Accessibility droppers#

ClayRat v3.0.8 couples its Accessibility RAT with a staged payload hidden under assets/. At runtime the host APK:[1]

  1. Streams the encrypted blob from assets/*.dat.
  2. Decrypts it with a hard-coded AES/CBC key + IV embedded inside the Java/Kotlin loader.
  3. Writes the plaintext DEX to the app's private dir and loads it via DexClassLoader, exposing the actual spyware classes only in memory.
byte[] blob = readAsset("payload.enc");
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec key = new SecretKeySpec(hex("A1..."), "AES");
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] dex = c.doFinal(blob);
DexClassLoader cl = new DexClassLoader(writeTemp(dex), getCodeCacheDir().getPath(), null, getClassLoader());
cl.loadClass("com.clayrat.Core").newInstance();

This packing pattern (ATT&CK T1406.002) keeps the Accessibility module off-disk until the dropper executes, defeating static signature scans and Play Protect until the user already granted the dangerous permissions.

Zimperium publishes a companion ClayRat v3 indicator set that defenders can use to correlate the analyzed samples and infrastructure.[2]


Requesting the permission#

<!-- AndroidManifest.xml -->
<service
    android:name="com.evil.rat.EvilService"
    android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
    android:exported="false">

    <intent-filter>
        <action android:name="android.accessibilityservice.AccessibilityService" />
    </intent-filter>

    <meta-data android:name="android.accessibilityservice"
        android:resource="@xml/evil_accessibility_config"/>
</service>

The companion XML defines how the fake dialog will look like:

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/service_description"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFeedbackType="feedbackGeneric"
    android:notificationTimeout="200"
    android:canPerformGestures="true"
    android:canRetrieveWindowContent="true"/>

Remote UI automation primitives#

Accessibility service automation skeleton
public class EvilService extends AccessibilityService {
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // harvest text or detect foreground app change
    }

    // Simulate HOME / BACK / RECENTS …
    private void navHome()     { performGlobalAction(GLOBAL_ACTION_HOME); }
    private void navBack()     { performGlobalAction(GLOBAL_ACTION_BACK); }
    private void openRecents() { performGlobalAction(GLOBAL_ACTION_RECENTS); }

    // Generic tap / swipe
    public void tap(float x, float y) {
        Path p = new Path(); p.moveTo(x, y);
        GestureDescription.StrokeDescription s = new GestureDescription.StrokeDescription(p, 0, 50);
        dispatchGesture(new GestureDescription.Builder().addStroke(s).build(), null, null);
    }
}

With only these two APIs an attacker can:


Abuse patterns#

1. Overlay Phishing (Credential Harvesting)#

A transparent or opaque WebView is added to the window manager:

WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
        MATCH_PARENT, MATCH_PARENT,
        TYPE_ACCESSIBILITY_OVERLAY,                      // ⬅ bypasses SYSTEM_ALERT_WINDOW
        FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,       // touches still reach the real app
        PixelFormat.TRANSLUCENT);
wm.addView(phishingView, lp);

The victim types credentials into the fake form while the background app receives the same gestures – no suspicious "draw over other apps" prompt is ever shown.

Detailed example: the Accessibility Overlay Phishing section inside the Tapjacking page.

ClayRat exposes this capability with the show_block_screen / hide_block_screen commands that download overlay templates from the C2. Operators can switch layouts on the fly to:[1]

Because TYPE_ACCESSIBILITY_OVERLAY windows never raise the SYSTEM_ALERT_WINDOW permission prompt, the victim only sees the decoy UI while the RAT keeps interacting with the real apps underneath.

2. On-Device Fraud automation#

Malware families such as PlayPraetor maintain a persistent WebSocket channel where the operator can issue high-level commands (init, update, alert_arr, report_list, …). The service translates those commands into the low-level gestures above, achieving real-time unauthorized transactions that easily bypass multi-factor-authentication tied to that very device.[3]

3. Screen streaming & monitoring#

ClayRat upgrades the usual MediaProjection trick into a remote desktop stack:[1]

  1. turbo_screen triggers the MediaProjection consent dialog; the Accessibility service clicks “Start now” so the victim never intervenes.
  2. With the resulting MediaProjection token it creates a VirtualDisplay backed by an ImageReader, keeps a ForegroundService alive, and drains frames on worker threads.
  3. Frames are JPEG/PNG encoded according to the operator-supplied set_quality parameter (defaults to 60 when missing) and shipped over an HTTP→WebSocket upgrade advertising the custom ClayRemoteDesktop user-agent.
  4. start_desktop / stop_desktop manage the capture threads while screen_tap, screen_swipe, input_text, press_home, press_back and press_recents replay gestures against the live framebuffer.

The result is a VNC-like feed delivered entirely through sanctioned APIs—no root or kernel exploits—yet it hands the attacker live situational awareness with millisecond latency.

4. Lock-screen credential theft & auto-unlock#

ClayRat subscribes to TYPE_WINDOW_CONTENT_CHANGED / TYPE_VIEW_TEXT_CHANGED events emitted by com.android.systemui (Keyguard). It reconstructs whatever guard is active:[1]

Secrets plus metadata (lock type + timestamp) are serialized into SharedPreferences under lock_password_storage. When the operator pushes auto_unlock, the service wakes the device with unlock_device / screen_on, replays the stored digits or gestures through dispatchGesture, and silently bypasses the keyguard so subsequent ODF workflows can continue.

5. Notification phishing & harvesting#

A companion Notification Listener turns the shade into a phishing surface:[1]

Because Accessibility can open/dismiss the notification shade programmatically, this method harvests secrets without touching the targeted apps.

6. Telephony & SMS command channel#

After coercing the user into setting the RAT as the default SMS app, the following commands provide complete modem control:[1]

Combined with Accessibility-driven UI navigation, ClayRat can receive an OTP via notification/SMS and immediately input it inside the target banking or enterprise app.

7. Discovery, collection & proxying#

Additional ClayRat commands map the environment and keep C2 resilient:[1]

8. Region-scoped keypad interception and gesture replay#

Instead of drawing a fake banking form, an Accessibility RAT can locate the numeric-key nodes in the real application, union their getBoundsInScreen() rectangles, and place a touch-consuming overlay only over that keypad. For every victim tap, it records the coordinates and nearby node, temporarily stops intercepting touches, replays a tap at the same coordinates with dispatchGesture(), and restores the overlay. The legitimate application therefore receives the expected input and continues normally while the RAT reconstructs the PIN from the intercepted sequence.[7]

This differs from a pass-through overlay: the malicious window receives the original event and Accessibility injects a second event only after interception is disabled. During reverse engineering, look for AccessibilityNodeInfo bounds aggregation next to a small overlay window, coordinate hit-testing, rapid changes to touchability/visibility, and dispatchGesture() callbacks that re-arm the overlay.[7]

9. Semantic Accessibility keylogging#

Raw TYPE_VIEW_TEXT_CHANGED, TYPE_VIEW_CLICKED, and window-content events become more useful when records are enriched with the source package, timestamp, target-list membership, and whether text came from Autofill or manual entry. The collector can then classify values such as lock-screen input, 4–6 digit OTPs, passwords, email logins, long messages, and possible wallet recovery phrases before upload, allowing operators to prioritize authentication material rather than reviewing an undifferentiated event stream.[7]

10. Peer-assisted store-and-forward exfiltration#

An Accessibility RAT can keep collected files and command results in a durable queue, encrypt each package with AES-GCM, and relay it through nearby infected phones when direct C2 access is unavailable. One observed design tries an established Wi-Fi Direct peer first, then queries classic Bluetooth RFCOMM or BLE GATT peers for Internet reachability. A reachable peer accepts the encrypted package and forwards it toward C2; unroutable items remain queued for retry, and a hop counter (four hops by default in the observed implementation) bounds multi-device forwarding.[7]

Static and dynamic triage should correlate queue persistence and AES/GCM/NoPadding with WifiP2pManager, RFCOMM BluetoothSocket, BluetoothGatt, reachability probes, and decrementing hop/TTL fields. Containment must isolate local radios or physically separate suspected devices as well as blocking Internet access, because a nearby compromised peer may provide the egress path.[7]


PlayPraetor – command & control workflow#

  1. HTTP(S) heartbeat – iterate over a hard-coded list until one domain answers POST /app/searchPackageName with the active C2.
  2. WebSocket (port 8282) – bidirectional JSON commands:
    • update – push new conf/APKs
    • alert_arr – configure overlay templates
    • report_list – send list of targeted package names
    • heartbeat_web – keep-alive
  3. RTMP (port 1935) – live screen/video streaming.
  4. REST exfiltration –
    • /app/saveDevice (fingerprint)
    • /app/saveContacts | /app/saveSms | /app/uploadImageBase64
    • /app/saveCardPwd (bank creds)

The AccessibilityService is the local engine that turns those cloud commands into physical interactions.[3]


Detecting malicious accessibility services#


Hardening recommendations for app developers#


ATS automation cheat-sheet (Accessibility-driven)#

Malware can fully automate a bank app with only Accessibility APIs. Generic primitives:

Helper methods for ATS automation
// Helpers inside your AccessibilityService
private List<AccessibilityNodeInfo> byText(String t){
  AccessibilityNodeInfo r = getRootInActiveWindow();
  return r == null ? Collections.emptyList() : r.findAccessibilityNodeInfosByText(t);
}
private boolean clickText(String t){
  for (AccessibilityNodeInfo n: byText(t)){
    if (n.isClickable()) return n.performAction(ACTION_CLICK);
    AccessibilityNodeInfo p = n.getParent();
    if (p != null) return p.performAction(ACTION_CLICK);
  }
  return false;
}
private void inputText(AccessibilityNodeInfo field, String text){
  Bundle b = new Bundle(); b.putCharSequence(ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
  field.performAction(ACTION_SET_TEXT, b);
}
private void tap(float x, float y){
  Path p = new Path(); p.moveTo(x,y);
  dispatchGesture(new GestureDescription.Builder()
    .addStroke(new GestureDescription.StrokeDescription(p,0,40)).build(), null, null);
}

Example flow (Czech → English labels):[5]

Fallback: hard-coded coordinates with dispatchGesture when text lookup fails due to custom widgets.

Also seen: pre-steps to check_limit and limit by navigating to limits UI and increasing daily limits before transfer.[5]

Text-based pseudo-screen streaming#

For low-latency remote control, instead of full video streaming, dump a textual representation of the current UI tree and send it to C2 repeatedly.

private void dumpTree(AccessibilityNodeInfo n, String indent, StringBuilder sb){
  if (n==null) return;
  Rect b = new Rect(); n.getBoundsInScreen(b);
  CharSequence txt = n.getText(); CharSequence cls = n.getClassName();
  sb.append(indent).append("[").append(cls).append("] ")
    .append(txt==null?"":txt).append(" ")
    .append(b.toShortString()).append("\n");
  for (int i=0;i<n.getChildCount();i++) dumpTree(n.getChild(i), indent+"  ", sb);
}

This is the basis for commands like txt_screen (one-shot) and screen_live (continuous).[5]

Device Admin coercion primitives#

Once a Device Admin receiver is activated, these calls increase opportunities to capture credentials and maintain control:[5]

DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
ComponentName admin = new ComponentName(this, AdminReceiver.class);

// 1) Immediate lock
dpm.lockNow();

// 2) Force credential change (expire current PIN/password)
dpm.setPasswordExpirationTimeout(admin, 1L); // may require owner/profile-owner on recent Android

// 3) Disable biometric unlock to force PIN/pattern entry
int flags = DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT |
            DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS;
dpm.setKeyguardDisabledFeatures(admin, flags);

Note: the exact availability of these policies varies by Android version and OEM; validate the device policy role (admin vs owner) during testing.

Crypto wallet seed-phrase extraction patterns#

Observed flows for MetaMask, Trust Wallet, Blockchain.com and Phantom:[5]

NFC-relay orchestration#

Accessibility/RAT modules can install and launch a dedicated NFC-relay app (e.g., NFSkate) as a third stage and even inject an overlay guide to shepherd the victim through card-present relay steps.[6]

Background and TTPs: https://www.threatfabric.com/blogs/ghost-tap-new-cash-out-tactic-with-nfc-relay[6]


References#