Apply Mobile Code Hardening
Apply code obfuscation, root/jailbreak detection, debug detection, and integrity verification to raise the cost of reverse engineering and runtime manipulation — critical for apps with high-value secrets, DRM, or anti-fraud requirements.
Why This Is Best Practice
Adopted by: OWASP Mobile Top 10 2024 M7 (Insufficient Binary Protections). OWASP MASVS MSTG-RESILIENCE defines the standard for mobile binary protection. Google Play Integrity API and Apple DeviceCheck are platform-provided integrity attestation services. Financial services apps (banking, payment), gaming apps (anti-cheat), and DRM apps (streaming) universally apply these controls — required by PCI DSS v4.0 Requirement 6.3 for payment apps.
Impact: Mobile apps are distributed to untrusted devices — the reverse engineering tooling (jadx for Android, Hopper/Ghidra for iOS, Frida for both) is freely available and capable. Unprotected banking apps have had API keys extracted to build unauthorized clients. Gaming apps without anti-cheat have been reverse-engineered to enable automated bots. DRM content has been extracted from streaming apps. Code hardening raises the cost from minutes to weeks or months.
Why best: Code hardening is an arms race — determined attackers with resources will eventually break any protection. The goal is to raise the cost of attack beyond the attacker's expected return, not to make it impossible. Combined with server-side validation and monitoring, hardening reduces the class of opportunistic attackers effectively.
Sources: OWASP Mobile Top 10 2024 M7; OWASP MASVS MSTG-RESILIENCE; Google Play Integrity API documentation; Apple DeviceCheck documentation; CWE-693
Steps
Enable ProGuard/R8 code obfuscation on Android (minimum baseline):
// build.gradle
android {
buildTypes {
release {
minifyEnabled true // enables R8 code shrinking + obfuscation
shrinkResources true // removes unused resources
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
'proguard-rules.pro'
}
}
}
# proguard-rules.pro — keep only what's required for reflection/serialization
-keep class com.example.api.model.** { *; } # keep data models for JSON parsing
# Everything else: obfuscated by default
Use Google Play Integrity API to verify app authenticity at runtime:
// Request integrity verdict before sensitive operations
val integrityManager = IntegrityManagerFactory.create(context)
suspend fun verifyAppIntegrity(): Boolean {
val nonce = generateNonce() // send to server for verification
val request = StandardIntegrityManager.StandardIntegrityTokenRequest.builder()
.setRequestHash(hashOfRequest(nonce))
.build()
val tokenResponse = integrityManager.requestIntegrityToken(request).await()
val token = tokenResponse.token()
// Send token to server — server decrypts and verifies with Google
return backendApi.verifyIntegrity(token, nonce)
}
Detect root (Android) and jailbreak (iOS):
// Android — use RootBeer library (community-maintained root detection)
val rootBeer = RootBeer(context)
if (rootBeer.isRooted) {
// Log the detection — don't silently fail
analytics.log("rooted_device_detected")
// Policy decision: warn user, restrict features, or refuse operation
showRootedDeviceWarning()
}
// iOS — jailbreak detection heuristics
func isJailbroken() -> Bool {
// Check for common jailbreak artifacts
let jailbreakPaths = [
"/Applications/Cydia.app",
"/usr/sbin/sshd",
"/etc/apt",
"/private/var/lib/apt/",
]
for path in jailbreakPaths {
if FileManager.default.fileExists(atPath: path) { return true }
}
// Attempt to write outside sandbox
let testPath = "/private/test_jailbreak_\(UUID().uuidString)"
do {
try "test".write(toFile: testPath, atomically: true, encoding: .utf8)
try FileManager.default.removeItem(atPath: testPath)
return true // write succeeded — not possible on non-jailbroken device
} catch { return false }
}
Detect debuggers and instrumentation frameworks at runtime:
// iOS — detect debugger attachment
func isBeingDebugged() -> Bool {
var info = kinfo_proc()
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
var size = MemoryLayout<kinfo_proc>.stride
sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0)
return (info.kp_proc.p_flag & P_TRACED) != 0
}
// Android — detect Frida (dynamic instrumentation)
fun isFridaDetected(): Boolean {
return try {
// Frida opens a TCP port on the device
Socket("127.0.0.1", 27042).use { true }
} catch (e: Exception) { false }
}
Use Apple DeviceCheck for persistent device-level fraud prevention:
import DeviceCheck
func setDeviceFlag(bit: Bool, completion: @escaping (Bool) -> Void) {
DCDevice.current.generateToken { token, error in
guard let token = token else {
completion(false)
return
}
// Send token to your server — server uses DeviceCheck API
// to set per-device bit (persists across reinstalls)
backendAPI.recordDeviceToken(token.base64EncodedString()) { success in
completion(success)
}
}
}
Verify app signature at runtime:
// Android — verify APK signing certificate hasn't changed
fun verifyAppSignature(context: Context): Boolean {
val expectedSignatureHash = "SHA256_OF_YOUR_RELEASE_CERT"
val packageInfo = context.packageManager.getPackageInfo(
context.packageName,
PackageManager.GET_SIGNATURES
)
val signature = packageInfo.signatures[0]
val certHash = MessageDigest.getInstance("SHA-256")
.digest(signature.toByteArray())
.toHexString()
return certHash == expectedSignatureHash
}
Rules
- Code hardening is defense-in-depth, not a complete defense — all sensitive operations must still be validated server-side.
- Root/jailbreak detection should log and optionally degrade functionality — avoid outright blocking as it may affect legitimate users with custom ROMs.
- Detection checks must be spread throughout the code, not concentrated in one place — removing a single check should not bypass all protections.
- Obfuscation does not protect secrets hardcoded in the binary — no hardcoded keys, regardless of obfuscation level.
Common Mistakes
- Applying code hardening only to the release build without testing it — obfuscation can break reflection-based code; test before releasing.
- Treating root detection as a security boundary — it reduces attack surface but is bypassable; server-side validation is the authoritative check.
- Hardcoding API keys in the binary and relying on obfuscation to protect them — obfuscated keys are still extractable by a motivated attacker; use certificate pinning and server-side key validation instead.
- One-time integrity check at launch only — move checks to multiple points in the code so patching the launch check doesn't disable all protection.
1---2name: apply-mobile-code-hardening3description: Use when preparing a mobile app for production release — especially apps handling financial data, DRM content, or anti-cheat systems — to raise the bar against reverse engineering, tampering, and runtime manipulation.4source: 'OWASP Mobile Top 10 2024 M7 (owasp.org/www-project-mobile-top-10/); OWASP MASVS MSTG-RESILIENCE; CWE-693; Google Play Integrity API; Apple DeviceCheck documentation'5tags: [security, owasp, mobile, code-hardening, obfuscation, anti-tamper, reverse-engineering, ios]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-mobile-code-hardening8---910# Apply Mobile Code Hardening1112Apply code obfuscation, root/jailbreak detection, debug detection, and integrity verification to raise the cost of reverse engineering and runtime manipulation — critical for apps with high-value secrets, DRM, or anti-fraud requirements.1314## Why This Is Best Practice1516**Adopted by:** OWASP Mobile Top 10 2024 M7 (Insufficient Binary Protections). OWASP MASVS MSTG-RESILIENCE defines the standard for mobile binary protection. Google Play Integrity API and Apple DeviceCheck are platform-provided integrity attestation services. Financial services apps (banking, payment), gaming apps (anti-cheat), and DRM apps (streaming) universally apply these controls — required by PCI DSS v4.0 Requirement 6.3 for payment apps.17**Impact:** Mobile apps are distributed to untrusted devices — the reverse engineering tooling (jadx for Android, Hopper/Ghidra for iOS, Frida for both) is freely available and capable. Unprotected banking apps have had API keys extracted to build unauthorized clients. Gaming apps without anti-cheat have been reverse-engineered to enable automated bots. DRM content has been extracted from streaming apps. Code hardening raises the cost from minutes to weeks or months.18**Why best:** Code hardening is an arms race — determined attackers with resources will eventually break any protection. The goal is to raise the cost of attack beyond the attacker's expected return, not to make it impossible. Combined with server-side validation and monitoring, hardening reduces the class of opportunistic attackers effectively.1920Sources: OWASP Mobile Top 10 2024 M7; OWASP MASVS MSTG-RESILIENCE; Google Play Integrity API documentation; Apple DeviceCheck documentation; CWE-6932122## Steps23241. **Enable ProGuard/R8 code obfuscation on Android** (minimum baseline):2526 ```groovy27 // build.gradle28 android {29 buildTypes {30 release {31 minifyEnabled true // enables R8 code shrinking + obfuscation32 shrinkResources true // removes unused resources33 proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),34 'proguard-rules.pro'35 }36 }37 }38 ```3940 ```41 # proguard-rules.pro — keep only what's required for reflection/serialization42 -keep class com.example.api.model.** { *; } # keep data models for JSON parsing43 # Everything else: obfuscated by default44 ```45462. **Use Google Play Integrity API to verify app authenticity at runtime**:4748 ```kotlin49 // Request integrity verdict before sensitive operations50 val integrityManager = IntegrityManagerFactory.create(context)5152 suspend fun verifyAppIntegrity(): Boolean {53 val nonce = generateNonce() // send to server for verification5455 val request = StandardIntegrityManager.StandardIntegrityTokenRequest.builder()56 .setRequestHash(hashOfRequest(nonce))57 .build()5859 val tokenResponse = integrityManager.requestIntegrityToken(request).await()60 val token = tokenResponse.token()6162 // Send token to server — server decrypts and verifies with Google63 return backendApi.verifyIntegrity(token, nonce)64 }65 ```66673. **Detect root (Android) and jailbreak (iOS)**:6869 ```kotlin70 // Android — use RootBeer library (community-maintained root detection)71 val rootBeer = RootBeer(context)72 if (rootBeer.isRooted) {73 // Log the detection — don't silently fail74 analytics.log("rooted_device_detected")75 // Policy decision: warn user, restrict features, or refuse operation76 showRootedDeviceWarning()77 }78 ```7980 ```swift81 // iOS — jailbreak detection heuristics82 func isJailbroken() -> Bool {83 // Check for common jailbreak artifacts84 let jailbreakPaths = [85 "/Applications/Cydia.app",86 "/usr/sbin/sshd",87 "/etc/apt",88 "/private/var/lib/apt/",89 ]90 for path in jailbreakPaths {91 if FileManager.default.fileExists(atPath: path) { return true }92 }93 // Attempt to write outside sandbox94 let testPath = "/private/test_jailbreak_\(UUID().uuidString)"95 do {96 try "test".write(toFile: testPath, atomically: true, encoding: .utf8)97 try FileManager.default.removeItem(atPath: testPath)98 return true // write succeeded — not possible on non-jailbroken device99 } catch { return false }100 }101 ```1021034. **Detect debuggers and instrumentation frameworks at runtime**:104105 ```swift106 // iOS — detect debugger attachment107 func isBeingDebugged() -> Bool {108 var info = kinfo_proc()109 var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]110 var size = MemoryLayout<kinfo_proc>.stride111 sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0)112 return (info.kp_proc.p_flag & P_TRACED) != 0113 }114 ```115116 ```kotlin117 // Android — detect Frida (dynamic instrumentation)118 fun isFridaDetected(): Boolean {119 return try {120 // Frida opens a TCP port on the device121 Socket("127.0.0.1", 27042).use { true }122 } catch (e: Exception) { false }123 }124 ```1251265. **Use Apple DeviceCheck for persistent device-level fraud prevention**:127128 ```swift129 import DeviceCheck130131 func setDeviceFlag(bit: Bool, completion: @escaping (Bool) -> Void) {132 DCDevice.current.generateToken { token, error in133 guard let token = token else {134 completion(false)135 return136 }137 // Send token to your server — server uses DeviceCheck API138 // to set per-device bit (persists across reinstalls)139 backendAPI.recordDeviceToken(token.base64EncodedString()) { success in140 completion(success)141 }142 }143 }144 ```1451466. **Verify app signature at runtime**:147148 ```kotlin149 // Android — verify APK signing certificate hasn't changed150 fun verifyAppSignature(context: Context): Boolean {151 val expectedSignatureHash = "SHA256_OF_YOUR_RELEASE_CERT"152 val packageInfo = context.packageManager.getPackageInfo(153 context.packageName,154 PackageManager.GET_SIGNATURES155 )156 val signature = packageInfo.signatures[0]157 val certHash = MessageDigest.getInstance("SHA-256")158 .digest(signature.toByteArray())159 .toHexString()160 return certHash == expectedSignatureHash161 }162 ```163164## Rules165166- Code hardening is defense-in-depth, not a complete defense — all sensitive operations must still be validated server-side.167- Root/jailbreak detection should log and optionally degrade functionality — avoid outright blocking as it may affect legitimate users with custom ROMs.168- Detection checks must be spread throughout the code, not concentrated in one place — removing a single check should not bypass all protections.169- Obfuscation does not protect secrets hardcoded in the binary — no hardcoded keys, regardless of obfuscation level.170171## Common Mistakes172173- **Applying code hardening only to the release build without testing it** — obfuscation can break reflection-based code; test before releasing.174- **Treating root detection as a security boundary** — it reduces attack surface but is bypassable; server-side validation is the authoritative check.175- **Hardcoding API keys in the binary and relying on obfuscation to protect them** — obfuscated keys are still extractable by a motivated attacker; use certificate pinning and server-side key validation instead.176- **One-time integrity check at launch only** — move checks to multiple points in the code so patching the launch check doesn't disable all protection.