Mobile App Security in 2026: OWASP MASVS for iOS and Android
Derar SattoufUpdated Security

A mobile app is a piece of your backend that you have shipped to a device you do not control, owned by a person you cannot vouch for, running next to software you have never seen. The binary can be downloaded, unpacked, instrumented and repackaged by anyone. The network between the app and your server may be hostile. The device may be lost, shared, rooted or infected. Good mobile security starts by accepting those facts and then deciding, calmly, which risks matter for your app and which controls are proportionate. Some common advice is overrated, in particular root detection, obfuscation and client-side secrets: security controls have costs, and some of them buy very little.
Start with a threat model, not a tool. Decide what you protect (credentials, personal data, money, integrity of transactions), from whom (a thief, a malicious app, a network attacker, a reverse engineer), and what a compromise costs. Controls follow from that. Use MASVS as the checklist and MASTG as the test guide: MASVS defines what to verify across storage, crypto, authentication, network, platform interaction, code quality, resilience and privacy, while MASTG and the MASWE weakness catalogue describe how to test.
Secrets in apps are never secret, because anything shipped in the binary can be extracted. Keep real secrets on the server, use short-lived tokens, and treat embedded API keys as public identifiers that need server-side restriction. Store sensitive data in the platform keystores: the iOS Keychain with the strictest accessibility class that works, and Secure Enclave keys for high-value operations. On Android, Keystore keys (hardware-backed, StrongBox when available) wrap any data you encrypt locally. Don't store tokens in plain preferences, files or logs.
Bind high-value actions to biometrics properly. A boolean "biometric succeeded" callback is bypassable on a compromised device, so tie the biometric to a cryptographic key operation instead. Enforce TLS everywhere, and pin only when you can operate pinning: it raises the bar against network interception but causes outages when done carelessly, so pin to a backup-capable key, set expirations and ship a kill switch. Attestation is a signal, not a lock. App Attest and DeviceCheck on iOS and the Play Integrity API on Android let your server judge whether a request likely comes from a genuine app on a genuine device; verify on the server and combine it with other signals. Root and jailbreak detection is a speed bump, useful as one risk input and never as the only control.
Harden the platform surface by validating deep links, locking down exported components, restricting WebViews and disabling backups of sensitive data. Know your dependencies: generate an SBOM, scan it and keep libraries current. And test it. Use MobSF for fast static and dynamic checks, and use dynamic instrumentation such as Frida, defensively, against your own builds to confirm your controls behave as you believe.
Platform APIs and standards change. Apple's frameworks, Android's Keystore and Play Integrity, and the OWASP projects are revised regularly, so where an API name, version or policy matters, check it against the current documentation.
Threat model for mobile apps
What makes mobile different
| Property | Consequence |
|---|---|
| Client is untrusted | Any client-side check can be removed. Authoritative decisions live on the server. |
| Binary is distributed | Reverse engineering, repackaging and secret extraction are routine. |
| Device may be compromised | Rooted or jailbroken devices, malware with accessibility or overlay permissions. |
| Network is hostile | Public Wi-Fi, captive portals, malicious proxies, user-installed CA certificates. |
| Physical access is plausible | Lost or stolen phone, shoulder surfing, forensic extraction. |
| Platform IPC | Deep links, intents, URL schemes and extensions form an attack surface. |
| Long-lived sessions | Users stay signed in for months, so token theft has high value. |
Attacker profiles
- Opportunistic thief. Has the unlocked or locked device. Defence: strong device-bound encryption, lock-screen respecting storage classes, remote session revocation.
- Network attacker. Controls the Wi-Fi or a proxy. Defence: TLS with proper validation, optional pinning, no sensitive data in URLs.
- Malicious app on the same device. Defence: sandboxing (the default), no sensitive data in shared storage or the clipboard, careful exported components and deep links.
- Reverse engineer or cheater. Wants to bypass licensing, abuse your API, or scrape. Defence: server-side enforcement, attestation, rate limiting, and accepting that the client will be read.
- Targeted attacker with a rooted device and time. Will instrument your app. Defence: assume compromise of the client; limit what a compromised client can do on the server.
- Malicious or compromised dependency. Defence: SBOM, pinned versions, review, and runtime least privilege.
A short threat-modelling procedure
Run this once per major feature, in thirty minutes with a whiteboard.
- Draw the data flow: user, app, OS services, third-party SDKs, backend, third parties.
- Mark trust boundaries (the device boundary, the network, the backend).
- For each flow, ask the STRIDE questions: spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege.
- List the assets: credentials, tokens, personal data, payment data, health data, business logic.
- Rate each threat by likelihood and impact; ignore the low-low corner.
- Assign controls, tag them with MASVS categories, and write down the residual risk.
┌────────┐ TLS ┌───────────┐ ┌──────────┐
│ User │───────►│ Mobile app│──────►│ Backend │
└────────┘ └─────┬─────┘ API └────┬─────┘
│ IPC │
┌───────▼──────┐ ┌────▼─────┐
│ OS: Keychain/│ │ Identity │
│ Keystore, │ │ provider │
│ biometrics │ └──────────┘
└──────────────┘
Trust boundaries: [device] | [network] | [backend]
Untrusted: everything left of the first boundary except OS-protected storesOWASP MASVS and MASTG: how to use them
The OWASP Mobile Application Security project has three parts that fit together:
- MASVS (Mobile Application Security Verification Standard): the list of security requirements, grouped into control categories.
- MASTG (Mobile Application Security Testing Guide): the techniques, tools and tests to verify those requirements on Android and iOS.
- MASWE (Mobile Application Security Weakness Enumeration): a catalogue of weaknesses that bridges MASVS requirements and concrete tests.
The MASVS organises requirements into control groups. In the current 2.x line they are: STORAGE, CRYPTO, AUTH, NETWORK, PLATFORM, CODE, RESILIENCE and PRIVACY. The PRIVACY group was added in 2.1. Verify the current list and control identifiers on the MAS website, because the standard and the testing guide's structure have been evolving.
Mapping this guide to MASVS
| MASVS group | Intent | Sections here |
|---|---|---|
| MASVS-STORAGE | Protect sensitive data at rest and avoid leaks | 3, 11 |
| MASVS-CRYPTO | Use sound cryptography and key management | 3, 4 |
| MASVS-AUTH | Authenticate and authorise users and sessions correctly | 4, 5 |
| MASVS-NETWORK | Secure data in transit | 6 |
| MASVS-PLATFORM | Interact with the OS and other apps safely | 8, 9 |
| MASVS-CODE | Secure code quality, dependencies, input handling | 12 |
| MASVS-RESILIENCE | Resist reverse engineering and tampering (defence in depth) | 7, 10 |
| MASVS-PRIVACY | Minimise and protect user data, give control | 11 |
Choosing a verification level
MASVS 2.x no longer prescribes numbered levels in the standard itself; the MAS project describes testing profiles (such as baseline security and defence-in-depth profiles) separately, and these have been revised. As a practical approach:
- Everyone: meet the core STORAGE, CRYPTO, AUTH, NETWORK, PLATFORM, CODE and PRIVACY controls.
- High-risk apps (banking, health, identity, payments): add RESILIENCE controls, attestation, and an independent penetration test using MASTG.
Record which controls are met, which are not applicable, and which are accepted risks. That record is your audit trail.
Secure storage
What not to do
| Anti-pattern | Why it fails |
|---|---|
Tokens in SharedPreferences or UserDefaults | Readable on a rooted or jailbroken device, and included in backups |
| Credentials in plain files, SQLite without encryption, or the app bundle | Extractable |
| Sensitive data in logs, crash reports, analytics events | Leaks to third parties and to anyone with log access |
| Sensitive screens in screenshots and app switcher | Leaks to shoulder surfers and screen recorders |
| Sensitive data on the clipboard | Readable by other apps (with OS-level mitigations varying by version) |
Secrets in BuildConfig, Info.plist, strings, or assets | Extractable with trivial tools |
| Long-lived refresh tokens without rotation | Theft is permanent |
iOS: Keychain
The Keychain is the right place for tokens, passwords and keys. The most important decision is the accessibility class, which controls when an item can be read.
| Attribute | Readable when | Included in backups or migration | Typical use |
|---|---|---|---|
kSecAttrAccessibleWhenUnlockedThisDeviceOnly | Device unlocked | No (device-bound) | Auth tokens; the default choice |
kSecAttrAccessibleWhenUnlocked | Device unlocked | Yes (encrypted backups) | Data that should survive device migration |
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly | After first unlock since boot | No | Background tasks needing the token |
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly | Unlocked and a passcode is set | No | High-value secrets; removed if the passcode is removed |
import Foundation
import Security
enum KeychainError: Error {
case unexpectedStatus(OSStatus)
case notFound
}
struct KeychainStore {
let service: String
func save(_ data: Data, account: String) throws {
let base: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
// Replace any existing item.
SecItemDelete(base as CFDictionary)
var attrs = base
attrs[kSecValueData as String] = data
attrs[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
let status = SecItemAdd(attrs as CFDictionary, nil)
guard status == errSecSuccess else { throw KeychainError.unexpectedStatus(status) }
}
func load(account: String) throws -> Data {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
]
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == errSecItemNotFound { throw KeychainError.notFound }
guard status == errSecSuccess, let data = result as? Data else {
throw KeychainError.unexpectedStatus(status)
}
return data
}
func delete(account: String) {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
SecItemDelete(query as CFDictionary)
}
}Notes:
- Keychain items can survive app deletion on iOS in some circumstances. On first launch after install, detect that it is a fresh install (a flag in
UserDefaults) and clear stale Keychain items if your threat model requires it. - Keychain sharing between your apps requires access groups; keep them minimal.
- Secure Enclave (on devices that have it) can generate and hold private keys that never leave the hardware. Use it for signing challenges and device-bound credentials (see the iOS biometrics section).
- Data protection for files: use
FileProtectionType.completeor.completeUnlessOpenfor sensitive files, andisExcludedFromBackupwhere backup is undesirable.
Android: Keystore, and the state of EncryptedSharedPreferences
The Android Keystore system stores cryptographic keys so that key material is not exportable from the app process, backed by a trusted execution environment or a dedicated secure element (StrongBox) when the device has one. You use the key to encrypt and decrypt data that you store elsewhere.
On the Jetpack Security library: EncryptedSharedPreferences and EncryptedFile from androidx.security:security-crypto were widely recommended for years, but the library has been deprecated by Google. Verify the current status in the AndroidX release notes. For new code, use Keystore-backed keys directly (as below), or Google's Tink library with an Android Keystore master key, and store the ciphertext in DataStore or a file. Existing apps using EncryptedSharedPreferences should plan a migration rather than panic; the risk is maintenance and unfixed bugs, not an immediate break.
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
class SecretBox(private val alias: String = "app_data_key") {
private val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
private fun getOrCreateKey(): SecretKey {
(keyStore.getKey(alias, null) as? SecretKey)?.let { return it }
val spec = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.setRandomizedEncryptionRequired(true)
.build()
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
.apply { init(spec) }
.generateKey()
}
/** Returns IV (12 bytes) followed by ciphertext and tag. */
fun encrypt(plain: ByteArray): ByteArray {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())
return cipher.iv + cipher.doFinal(plain)
}
fun decrypt(blob: ByteArray): ByteArray {
val iv = blob.copyOfRange(0, 12)
val body = blob.copyOfRange(12, blob.size)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(128, iv))
return cipher.doFinal(body)
}
}Practical points:
- Let the Keystore generate the key, never import a key derived from a constant in your code.
- Handle
KeyPermanentlyInvalidatedExceptionwhen keys are tied to biometric enrolment, andInvalidKeyExceptionafter OS upgrades or backup restore. Your code must recover by re-authenticating the user and re-provisioning, not by crashing. - StrongBox can be requested with
setIsStrongBoxBacked(true)where supported; catchStrongBoxUnavailableExceptionand fall back to the TEE-backed Keystore. - Key attestation lets a server verify that a key lives in hardware (see the attestation section).
- Backups: set
android:allowBackup="false"or define explicitdataExtractionRulesandfullBackupContentso that sensitive files are not backed up. Keystore keys are not restored to a new device, so ciphertext restored from a backup would be undecryptable; plan for it.
<application
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:usesCleartextTraffic="false"
android:networkSecurityConfig="@xml/network_security_config">
</application>Local databases and files
Encrypt local databases if they contain sensitive data. SQLCipher is the established option for SQLite on both platforms, with the passphrase protected by a Keystore or Keychain key; evaluate its current licensing and maintenance for your use. Alternatively, store minimal data locally and keep the rest on the server. Data you never store cannot leak.
Tokens and sessions
- Prefer short-lived access tokens (minutes) and rotating refresh tokens with reuse detection on the server. If a refresh token is used twice, revoke the family.
- Store the refresh token in the Keychain or in Keystore-encrypted storage; keep the access token in memory where possible.
- Provide remote sign-out, and device lists the user can review.
- Use the system browser or an authentication session with OAuth 2.0 and PKCE for sign-in (
ASWebAuthenticationSessionon iOS, Custom Tabs on Android via AppAuth or the platform libraries). Do not collect third-party credentials in an embedded WebView.
Biometrics and local authentication
The classic mistake
// WRONG: the "success" callback is just a boolean branch in your app process.
biometricPrompt.authenticate(promptInfo)
// onAuthenticationSucceeded -> { unlockApp() } // hookable by instrumentationOn a compromised device, a hooking framework can call your success path directly. The boolean proves nothing to the server and nothing to the key store. Bind the biometric to a key operation: create a key that requires user authentication, and use it inside the prompt through a CryptoObject. If the biometric does not succeed, the OS refuses to use the key.
Android: BiometricPrompt with a CryptoObject
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import androidx.biometric.BiometricPrompt
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
private const val ALIAS = "auth_gate_key"
private fun createAuthKey() {
val spec = KeyGenParameterSpec.Builder(
ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(true)
.setInvalidatedByBiometricEnrollment(true)
// On API 30+, require a fresh strong biometric for every use:
.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
.build()
KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
.apply { init(spec) }.generateKey()
}
fun unlockToken(activity: FragmentActivity, encryptedToken: ByteArray, iv: ByteArray,
onToken: (ByteArray) -> Unit) {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
if (!ks.containsAlias(ALIAS)) createAuthKey()
val key = ks.getKey(ALIAS, null) as SecretKey
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key, javax.crypto.spec.GCMParameterSpec(128, iv))
val prompt = BiometricPrompt(
activity,
ContextCompat.getMainExecutor(activity),
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
val c = result.cryptoObject!!.cipher!!
onToken(c.doFinal(encryptedToken)) // only works if the OS authorised the key
}
},
)
val info = BiometricPrompt.PromptInfo.Builder()
.setTitle("Unlock")
.setNegativeButtonText("Cancel")
.setAllowedAuthenticators(BIOMETRIC_STRONG)
.build()
prompt.authenticate(info, BiometricPrompt.CryptoObject(cipher))
}Verify the current setUserAuthenticationParameters constants and the CryptoObject rules in the Android biometric documentation, because device-credential fallback and Class 3 (strong) biometric requirements affect which combinations are allowed.
iOS: biometrics bound to Keychain or Secure Enclave
On iOS, attach an access control to the Keychain item so that reading it requires biometry. The OS then prompts and enforces the check, not your code.
import LocalAuthentication
import Security
func saveBiometricProtected(_ data: Data, account: String) throws {
var error: Unmanaged<CFError>?
guard let access = SecAccessControlCreateWithFlags(
nil,
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
.biometryCurrentSet, // invalidated if enrolled biometrics change
&error
) else { throw error!.takeRetainedValue() as Error }
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.example.app.secure",
kSecAttrAccount as String: account,
kSecValueData as String: data,
kSecAttrAccessControl as String: access,
]
SecItemDelete(query as CFDictionary)
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else { throw KeychainError.unexpectedStatus(status) }
}
func loadBiometricProtected(account: String, reason: String) throws -> Data {
let context = LAContext()
context.localizedReason = reason
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "com.example.app.secure",
kSecAttrAccount as String: account,
kSecReturnData as String: true,
kSecUseAuthenticationContext as String: context,
]
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess, let data = result as? Data else {
throw KeychainError.unexpectedStatus(status)
}
return data
}Also set NSFaceIDUsageDescription in Info.plist. For signing challenges, generate a P-256 key in the Secure Enclave (kSecAttrTokenIDSecureEnclave) with the same access control, register the public key with your server, and have the server verify signatures over fresh nonces. That gives you biometric-gated, hardware-bound proof of possession.
Biometric rules
- Tie biometrics to a key operation or an OS-enforced Keychain access control, never to a boolean.
- Offer a fallback (device passcode or a PIN) but understand it lowers assurance.
- Re-authenticate before sensitive actions (payments, changing credentials), not only at app launch.
- Handle enrolment changes by invalidating keys and re-enrolling.
- Rate-limit and lock out on the server too.
Authentication and authorisation basics
- Authorisation is a server concern. Every API request must be authorised on the server against the authenticated identity. Hiding a button in the app is not access control.
- Avoid long-lived API keys per device. Use user-scoped tokens, and bind to the device where the risk justifies it (sender-constrained tokens such as DPoP are one option; verify current support in your identity provider).
- Passkeys (platform credentials via
ASAuthorizationon iOS and the Credential Manager API on Android) are the strongest mainstream user-facing authentication option and resist phishing; consider them as the primary sign-in. - Step-up authentication for risky operations.
- Session management: idle timeouts, absolute lifetimes, and revoke on password change.
- Do not embed shared secrets for client authentication. A mobile app is a public client in OAuth terms; use PKCE.
Network security
Baseline: TLS everywhere
| Platform | Default | What to configure |
|---|---|---|
| iOS | App Transport Security requires HTTPS | Do not add NSAllowsArbitraryLoads; scope any exceptions to specific domains and justify them |
| Android | Cleartext blocked by default for apps targeting recent API levels | Set android:usesCleartextTraffic="false" and a Network Security Config |
Keep sensitive data out of URLs and query strings (they end up in logs). Set sensible timeouts. Validate server errors and fail closed. Use modern TLS only; both platforms negotiate this by default.
Certificate pinning: pros and cons
Pinning makes the app accept only certificates (or public keys) you expect, defeating attackers who present a certificate from a rogue or compromised CA or a user-installed CA.
| Pros | Cons |
|---|---|
| Blocks interception by rogue or user-installed CAs | Can brick the app if the pinned key rotates unexpectedly |
| Raises the cost of casual traffic inspection | Does not stop a determined attacker with a rooted device (pinning can be bypassed by instrumentation) |
| Useful for high-risk apps (banking, health) | Operational burden: key rotation, backup pins, expiry |
| Helps meet some regulatory expectations | Conflicts with corporate TLS inspection and some CDNs that rotate certificates |
Pin the public key (SPKI hash), not the leaf certificate, include at least one backup pin for a key you hold offline, pin to an intermediate or your own key rather than a CDN's leaf if you can, set an expiry on the pin set, and have a remote kill switch or a quick update path. Test rotation in staging before production. If you cannot operate that process, do not pin; rely on strict TLS and server-side controls instead.
Android: Network Security Config
<!-- res/xml/network_security_config.xml -->
<network-security-config>
<base-config cleartextTrafficPermitted="false">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config>
<domain includeSubdomains="false">api.example.com</domain>
<pin-set expiration="2027-06-30">
<!-- SPKI SHA-256 of the current key -->
<pin digest="SHA-256">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</pin>
<!-- Backup pin: a key you hold in reserve -->
<pin digest="SHA-256">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=</pin>
</pin-set>
</domain-config>
<debug-overrides>
<trust-anchors>
<certificates src="user" />
</trust-anchors>
</debug-overrides>
</network-security-config>The pins above are placeholders; compute yours from the certificate you serve. The debug-overrides element applies only to debuggable builds, which allows proxy inspection during development without weakening release builds.
# Compute an SPKI SHA-256 pin from a live server
openssl s_client -connect api.example.com:443 -servername api.example.com </dev/null 2>/dev/null \
| openssl x509 -pubkey -noout \
| openssl pkey -pubin -outform der \
| openssl dgst -sha256 -binary \
| openssl enc -base64For OkHttp, CertificatePinner offers the same capability in code:
val client = OkHttpClient.Builder()
.certificatePinner(
CertificatePinner.Builder()
.add("api.example.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
.add("api.example.com", "sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=")
.build()
)
.build()iOS: pinning
The declarative option is NSAppTransportSecurity with NSPinnedDomains in Info.plist (available since iOS 14), pinning SPKI hashes for specific domains. Verify the exact key structure in Apple's "Identity pinning" documentation. For programmatic control, implement the URLSessionDelegate challenge handler:
import CryptoKit
import Foundation
import Security
final class PinningDelegate: NSObject, URLSessionDelegate {
// Base64 SHA-256 of the SubjectPublicKeyInfo of acceptable keys (current plus backup).
private let pins: Set<String> = [
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
]
func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
) {
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let trust = challenge.protectionSpace.serverTrust,
challenge.protectionSpace.host == "api.example.com"
else {
completionHandler(.performDefaultHandling, nil)
return
}
// 1. Perform normal system evaluation first.
var error: CFError?
guard SecTrustEvaluateWithError(trust, &error) else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// 2. Then check that at least one certificate in the chain has a pinned public key.
guard let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate] else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
for cert in chain {
if let key = SecCertificateCopyKey(cert),
let raw = SecKeyCopyExternalRepresentation(key, nil) as Data? {
// NOTE: for exact SPKI hashes you must prepend the ASN.1 header for the key type.
let hash = Data(SHA256.hash(data: raw)).base64EncodedString()
if pins.contains(hash) {
completionHandler(.useCredential, URLCredential(trust: trust))
return
}
}
}
completionHandler(.cancelAuthenticationChallenge, nil)
}
}Caveat in the code comment matters: hashing the raw key bytes is not the same as the standard SPKI hash, which includes the ASN.1 header for the algorithm. Either prepend the correct header for your key type before hashing, or compute your pins to match the same procedure. Libraries such as TrustKit implement this correctly; check their current maintenance state before adopting. SecTrustCopyCertificateChain requires a recent iOS version; use the older indexed API for earlier targets.
6.4a Pinning failure modes and ops runbook
- Write down the key lifecycle: who generates keys, where the backup is held, when each is rotated.
- Ship the next key's pin in a release before you rotate the server key; wait until the adoption of that release is high.
- Monitor TLS failures by app version in telemetry; alert on spikes.
- Provide a server-controlled mechanism (for example, a signed config) to disable pinning in an emergency, understanding that this is itself an attack surface and must be authenticated.
- Never pin to a certificate you do not control the renewal of.
App attestation: App Attest, DeviceCheck, and Play Integrity
What attestation gives you
Attestation lets your server obtain a platform-signed statement about the app and device making a request. It helps to answer: is this request from my genuine, unmodified app, running on a genuine, uncompromised device? It does not make the client trustworthy; it reduces abuse (scripted API clients, repackaged apps, emulator farms) and gives you a risk signal.
| Property | Apple App Attest / DeviceCheck | Google Play Integrity API |
|---|---|---|
| What it asserts | Genuine app instance and key on genuine Apple hardware | App recognised by Google Play, device integrity level, optionally account licensing |
| Mechanism | Hardware-backed key attested by Apple; later requests signed with assertions | Integrity token (encrypted and signed) decoded by your server via Google |
| Replay protection | Challenge plus a counter in each assertion | Nonce (classic) or request hash (standard) |
| Server work | Verify attestation chain, store public key and counter | Decode token via the Google API; verify nonce, package, verdicts |
| Per-device state | Yes, keep key id, public key, counter | Not required |
| Limits | Not available on every device or in all contexts; verify the current constraints | Quotas apply; request volume is limited per app; verify current quotas |
iOS: App Attest outline
- On first launch, call
DCAppAttestService.shared.generateKeyto create a key pair in the Secure Enclave and get a key identifier. Persist the key id. - Ask your server for a fresh random challenge.
- Call
attestKey(_:clientDataHash:)with the SHA-256 of the challenge. Send the attestation object and key id to your server. - The server verifies the attestation: certificate chain to Apple's App Attest root, the app identifier hash matches your team id and bundle id, the nonce matches, and the environment (development or production) is as expected. It stores the public key and a counter of zero.
- For each sensitive request, call
generateAssertion(_:clientDataHash:)over a hash of the request payload plus a server challenge. The server verifies the signature with the stored public key and checks that the counter has increased.
import DeviceCheck
import CryptoKit
actor AppAttestClient {
private let service = DCAppAttestService.shared
private var keyId: String?
func ensureKey() async throws -> String {
if let keyId { return keyId }
guard service.isSupported else { throw AttestError.unsupported }
let id = try await service.generateKey()
keyId = id // persist securely (for example in the Keychain)
return id
}
func attest(challenge: Data) async throws -> (keyId: String, attestation: Data) {
let id = try await ensureKey()
let hash = Data(SHA256.hash(data: challenge))
let attestation = try await service.attestKey(id, clientDataHash: hash)
return (id, attestation)
}
func assert(request: Data, challenge: Data) async throws -> Data {
let id = try await ensureKey()
let hash = Data(SHA256.hash(data: request + challenge))
return try await service.generateAssertion(id, clientDataHash: hash)
}
enum AttestError: Error { case unsupported }
}Server verification is a detailed, security-critical protocol: follow Apple's "Validating apps that connect to your server" documentation step by step, or use a well-maintained library rather than writing the CBOR and certificate checks yourself. Remember the Apple documentation notes on risk metric and on gradual rollout, because App Attest should be introduced carefully to avoid rejecting legitimate users on unsupported devices.
DeviceCheck's two-bit per-device storage (DCDevice) is a different, older mechanism useful for flagging devices (for example, "this device has redeemed a promotion"), not for proving app integrity.
Android: Play Integrity API outline
- Your server issues a nonce (classic request) or the app computes a request hash of the action's payload (standard request), so a token cannot be replayed for a different action.
- The app requests an integrity token with
IntegrityManager. Standard requests use a prepared token provider (warm up first) and are faster; classic requests are higher latency and are suited to infrequent, high-value checks. Verify the current guidance on when to use each, and the quotas. - The app sends the token to your server along with the action.
- The server decodes the token through Google's Play Integrity API (server-side decoding is the recommended and more secure option) and checks the verdicts.
- The server decides: allow, step-up, or reject.
import com.google.android.play.core.integrity.IntegrityManagerFactory
import com.google.android.play.core.integrity.StandardIntegrityManager
import com.google.android.play.core.integrity.StandardIntegrityManager.PrepareIntegrityTokenRequest
import com.google.android.play.core.integrity.StandardIntegrityManager.StandardIntegrityTokenRequest
class IntegrityClient(context: android.content.Context, private val cloudProjectNumber: Long) {
private val manager = IntegrityManagerFactory.createStandard(context)
private var provider: StandardIntegrityManager.StandardIntegrityTokenProvider? = null
fun prepare(onReady: () -> Unit, onError: (Exception) -> Unit) {
manager.prepareIntegrityToken(
PrepareIntegrityTokenRequest.builder()
.setCloudProjectNumber(cloudProjectNumber)
.build()
).addOnSuccessListener { provider = it; onReady() }
.addOnFailureListener(onError)
}
fun tokenFor(requestHash: String, onToken: (String) -> Unit, onError: (Exception) -> Unit) {
val p = provider ?: return onError(IllegalStateException("Not prepared"))
p.request(
StandardIntegrityTokenRequest.builder().setRequestHash(requestHash).build()
).addOnSuccessListener { onToken(it.token()) }
.addOnFailureListener(onError)
}
}Server side (Node.js shown, using Google's API client; check the current method names and the response schema in the Play Integrity documentation):
import { google } from "googleapis";
const playintegrity = google.playintegrity("v1");
export async function verifyIntegrity(integrityToken: string, expectedRequestHash: string) {
const auth = new google.auth.GoogleAuth({
scopes: ["https://www.googleapis.com/auth/playintegrity"],
});
const res = await playintegrity.v1.decodeIntegrityToken({
auth,
packageName: "com.example.app",
requestBody: { integrityToken },
});
const payload = res.data.tokenPayloadExternal;
if (!payload) return { ok: false, reason: "no payload" };
const hash = payload.requestDetails?.requestHash;
const pkg = payload.requestDetails?.requestPackageName;
const verdict = payload.appIntegrity?.appRecognitionVerdict;
const deviceVerdicts = payload.deviceIntegrity?.deviceRecognitionVerdict ?? [];
if (pkg !== "com.example.app") return { ok: false, reason: "package mismatch" };
if (hash !== expectedRequestHash) return { ok: false, reason: "request hash mismatch" };
if (verdict !== "PLAY_RECOGNIZED") return { ok: false, reason: "app not recognised" };
if (!deviceVerdicts.includes("MEETS_DEVICE_INTEGRITY")) {
return { ok: false, reason: "device integrity not met" };
}
// Also check the token timestamp for freshness; reject stale tokens.
return { ok: true };
}Using attestation sensibly
- Verify on the server. Never trust a verdict decoded on the client.
- Fail open or fail closed deliberately. For low-risk actions, treat attestation failure as a risk signal (step-up, rate limit). For high-value actions, fail closed. Always provide a recovery path for legitimate users on unusual devices.
- Plan for quotas and latency. Do not attest every request. Attest at sign-in, sensitive transactions, and at intervals.
- Layer it. Attestation plus rate limiting, anomaly detection, account signals and server-side validation.
- Understand privacy. Attestation involves platform vendors; reflect it in your privacy disclosures.
- Key attestation on Android (Android Keystore key attestation) separately proves a key's hardware backing and can complement Play Integrity for device-bound credentials.
Deep links, intents, and inter-app communication
Android
Exported components are the main surface. Since Android 12, any component with an intent filter must declare android:exported explicitly. Every exported Activity, Service, Receiver and Provider is callable by any app.
<!-- Internal screen: not reachable from other apps -->
<activity android:name=".ui.PaymentConfirmActivity" android:exported="false" />
<!-- Verified App Link: only the deep links you intend -->
<activity android:name=".ui.DeepLinkActivity" android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="www.example.com" android:pathPrefix="/app/" />
</intent-filter>
</activity>Host the verification file at https://www.example.com/.well-known/assetlinks.json:
[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.example.app",
"sha256_cert_fingerprints": ["AA:BB:CC:...:ZZ"]
}
}
]Rules:
- Prefer verified HTTPS App Links over custom schemes. Custom schemes can be claimed by any app, enabling interception (the classic OAuth redirect hijack).
- Treat all incoming data as untrusted. Validate the host, path and parameters before acting, and never perform a privileged action (transfer, delete, sign-in) directly from a link without user confirmation.
- Do not pass sensitive data in intents or links.
- Use explicit intents for internal communication, and
PendingIntent.FLAG_IMMUTABLEunless mutability is required (it is required by default for targeting recent API levels). - Protect exported components with permissions (signature-level where possible).
- Content providers: keep
exported="false", or grant URI permissions narrowly; guard against path traversal inopenFileby canonicalising paths. - Be careful with
Intentextras of nested intents (intent redirection). Validate anyIntentorPendingIntentyou receive before launching it.
fun handleDeepLink(intent: Intent): Destination? {
val uri = intent.data ?: return null
if (uri.scheme != "https" || uri.host != "www.example.com") return null
val segments = uri.pathSegments
if (segments.firstOrNull() != "app") return null
return when (segments.getOrNull(1)) {
"article" -> segments.getOrNull(2)?.toLongOrNull()?.let { Destination.Article(it) }
"settings" -> Destination.Settings
else -> null // unknown paths ignored
}
}iOS
- Universal Links (associated domains plus an
apple-app-site-associationfile served over HTTPS) are verified by the OS and preferable to custom URL schemes, which any app can register. If you must use a custom scheme for OAuth, use PKCE andASWebAuthenticationSession, and verify thestateparameter. - Validate and sanitise parameters from
application(_:open:options:)andonOpenURLin SwiftUI. Never trigger sensitive operations from a URL without confirmation. - App extensions, shared containers and pasteboard: keep shared data minimal and use app groups deliberately. Use the pasteboard only for non-sensitive data, and consider
UIPasteboardoptions for local-only and expiring items. - Screens in the app switcher: hide sensitive content when the app becomes inactive (an overlay in
sceneWillResignActive).
{
"applinks": {
"details": [
{
"appIDs": ["TEAMID.com.example.app"],
"components": [
{ "/": "/app/*" }
]
}
]
}
}Screenshots, overlays and tapjacking
On Android, set FLAG_SECURE on windows showing sensitive data to block screenshots and screen recording and to hide content in recents. Consider filterTouchesWhenObscured on sensitive buttons against overlay attacks (tapjacking), and be aware of accessibility-service abuse by malware, for which Play policy and OS protections help but do not eliminate the risk.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
}WebViews
WebViews run web content inside your app with access to your bridge code. They deserve the same scrutiny as a browser embedded in a privileged process.
Android WebView hardening
fun WebView.harden() {
settings.apply {
javaScriptEnabled = true // only if needed; otherwise false
allowFileAccess = false
allowContentAccess = false
allowFileAccessFromFileURLs = false
allowUniversalAccessFromFileURLs = false
mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
safeBrowsingEnabled = true
setGeolocationEnabled(false)
}
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
val uri = request.url
val allowed = uri.scheme == "https" && uri.host in setOf("www.example.com", "help.example.com")
if (!allowed) return true // block navigation outside the allow-list
return false
}
override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
handler.cancel() // never call handler.proceed()
}
}
}Rules:
- Never call
handler.proceed()inonReceivedSslError. It disables TLS validation. - Avoid
addJavascriptInterface. If you need a bridge, expose a minimal API with@JavascriptInterface, load only content you control over HTTPS, and validate every argument as untrusted. PreferWebMessagePortandWebViewCompat.addWebMessageListenerwith an origin allow-list, which lets you restrict which origins can talk to native code. - Serve local content through
WebViewAssetLoaderrather thanfile://URLs. - Disable debugging in release (
WebView.setWebContentsDebuggingEnabled(false)). - Do not load arbitrary URLs from intents or deep links into a WebView.
- Clear cookies and cache at sign-out when the WebView holds sessions.
iOS WKWebView
import WebKit
final class SafeWebViewController: UIViewController, WKNavigationDelegate {
private let allowedHosts: Set<String> = ["www.example.com", "help.example.com"]
override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
config.websiteDataStore = .nonPersistent() // no cookies kept across sessions
config.defaultWebpagePreferences.allowsContentJavaScript = true
let web = WKWebView(frame: view.bounds, configuration: config)
web.navigationDelegate = self
view.addSubview(web)
web.load(URLRequest(url: URL(string: "https://www.example.com/help")!))
}
func webView(_ webView: WKWebView,
decidePolicyFor action: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = action.request.url,
url.scheme == "https",
let host = url.host, allowedHosts.contains(host) else {
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
}For script messages (WKScriptMessageHandler), check message.frameInfo.securityOrigin and treat the body as untrusted input. Use SFSafariViewController or ASWebAuthenticationSession for third-party sites and authentication rather than embedding.
Root and jailbreak detection, obfuscation, and tamper resistance: realism
Root and jailbreak detection
Detection checks for known indicators: presence of su, Magisk, writable system partitions, Cydia, suspicious paths, the ability to write outside the sandbox, debugger attachment, and hooking frameworks. Attackers on a device they control can defeat these with hiding tools and instrumentation, and the arms race favours the attacker.
What it is good for:
- Reducing casual abuse and raising the effort for low-skill attackers.
- Feeding a risk score: a rooted device might trigger step-up authentication or lower transaction limits rather than a hard block.
- Meeting compliance requirements that ask for it.
What it is bad for:
- Being the sole protection for secrets or logic. A rooted-device check in the client can be patched out.
- Hard-blocking users. False positives (custom ROMs, privacy-conscious users, developers) hurt legitimate customers.
Prefer hardware-backed attestation (see the attestation section) over home-grown detection where you can, since the verdict comes from a trusted component and the server verifies it. Use home-grown checks as additional signals only, and send them to the server rather than acting on them locally.
Obfuscation and R8
| Technique | Purpose | Reality |
|---|---|---|
| R8 (Android) shrinking and renaming | Smaller app, harder to read | Slows casual reading; does not stop determined analysis |
| Resource shrinking | Smaller APK | Not a security control |
| String encryption | Hide literals | Decryptors are in the binary; defeated at runtime |
| Control-flow obfuscation, packers (commercial tools) | Raise reverse-engineering cost | Cost and risk: performance, crashes, false malware flags |
| Swift symbol stripping on iOS | Less metadata | Swift metadata is rich; limited effect |
| Anti-debugging, anti-hooking | Detect instrumentation | Bypassable; useful as signals |
Practical guidance:
- Enable R8 in release builds (
isMinifyEnabled = true) for size and a baseline of obscurity. Keep rules narrow and test the release build. - Strip debug symbols from distributed binaries and keep the symbol files or mapping files privately for crash reports.
- Consider commercial hardening only if your threat model includes determined reverse engineering of valuable client-side logic (for example, DRM, anti-cheat, proprietary algorithms) and you accept the maintenance cost.
- Do not rely on obfuscation to protect secrets. See the secrets section below.
android {
buildTypes {
release {
isMinifyEnabled = true
isShrinkResources = true
isDebuggable = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
}
}
}Integrity checks
You can verify your own signing certificate at runtime and compare it to an expected value. This detects naive repackaging but is itself patchable. Combine it with server-side attestation, which checks the signature as seen by the platform.
Secrets in apps, logging, and privacy
Secrets are never secret
Everything inside the app package is readable: strings, resources, native libraries, Info.plist, BuildConfig fields, and values hidden in the NDK. Splitting a key across files or XOR-ing it only delays extraction by minutes, and network inspection can also reveal bearer tokens at runtime.
| Item | Approach |
|---|---|
| Third-party API keys that grant billable or sensitive access | Do not ship. Proxy through your backend, which holds the key |
| Keys that must be client-side (maps, analytics, Firebase config) | Treat as public identifiers; restrict by package name and signing certificate, bundle id, quota and allowed APIs in the provider console |
| Signing keys, database passwords, service account credentials | Never in the app, never in the repository |
| Client "secret" for OAuth | Use public client plus PKCE; no secret |
| Per-user secrets | Issue from the server after authentication, store in Keychain or Keystore |
| Remote config and feature flags | Public; never store secrets there |
If a key was ever committed or shipped, rotate it. Scan history with a secrets scanner (for example gitleaks or trufflehog) in CI, and block merges that add new findings.
# Quick local scan of a repo and its history
gitleaks detect --source . --verbose
# Quick check of what strings an Android release ships
unzip -p app-release.apk classes.dex | strings | grep -iE 'api[_-]?key|secret|token|password' | headLogging
- No sensitive data in logs: tokens, passwords, full card numbers, personal data. On Android,
Log.doutput is available to developers and, on older versions or rooted devices, to other apps. On iOS, unified logging marks dynamic strings as private by default in release builds, but do not rely on that. - Strip verbose logging in release builds. With R8 you can remove
Log.dandLog.vcalls via-assumenosideeffectsrules; verify the behaviour in your build. - Crash reporters and analytics: scrub URLs, user identifiers and free-text fields before sending; configure the SDK to avoid collecting what you do not need.
- Disable the keyboard cache and autofill on sensitive fields where appropriate (
secureTextEntryon iOS,importantForAutofilland input types on Android).
Privacy (MASVS-PRIVACY)
- Data minimisation: collect only what you need and keep it only as long as necessary.
- Declare accurately: the App Store privacy nutrition labels, privacy manifests (
PrivacyInfo.xcprivacy, including required-reason API declarations and third-party SDK manifests) and the Google Play Data safety form must match what the app and its SDKs actually do. Audit SDKs; they are the usual source of mismatches. - Permissions: request at the point of use with a clear rationale; handle denial gracefully; prefer limited-access options such as the photo picker and approximate location where they suffice.
- User control: offer account deletion in-app (a store requirement on both platforms in many cases; verify current policy), data export where required by law, and respect tracking consent (App Tracking Transparency on iOS).
- Identifiers: avoid hardware identifiers; use app-scoped identifiers and reset them at sign-out where appropriate.
Dependencies, SBOM, and supply chain (MASVS-CODE)
Third-party SDKs run with your app's full privileges. A vulnerable or malicious library is your vulnerability.
Practices
- Inventory: produce a Software Bill of Materials on every release build.
- Pin versions and use lockfiles (Gradle dependency locking and verification metadata,
Package.resolvedfor Swift Package Manager,Podfile.lock). - Verify integrity: Gradle dependency verification (
gradle/verification-metadata.xml) checks checksums and signatures. - Scan for known vulnerabilities (OSV, GitHub Dependabot, OWASP Dependency-Check, Snyk, or similar) on a schedule as well as per pull request.
- Minimise SDKs. Each analytics or ads SDK is attack surface and a privacy liability. Remove unused ones.
- Review updates of high-privilege SDKs, and be wary of typosquatted packages.
- Control build infrastructure: protect CI secrets, sign builds in a controlled environment, and keep signing keys in a managed store (Play App Signing for Android release keys; Apple certificates and provisioning in a secure secret store).
SBOM generation
# Android/JVM: CycloneDX Gradle plugin
./gradlew cyclonedxBom
# Output: build/reports/bom.json (CycloneDX)
# Any directory or image: Syft
syft dir:. -o cyclonedx-json > sbom.cdx.json
# Scan the SBOM for known vulnerabilities with Grype
grype sbom:sbom.cdx.jsonCheck each tool's current documentation for configuration, as plugin ids and output paths change between versions.
name: sbom-and-scan
on:
pull_request:
schedule:
- cron: "0 5 * * 1"
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 21
- run: ./gradlew cyclonedxBom
- name: Scan dependencies
run: |
curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
grype sbom:app/build/reports/bom.json --fail-on highPin the installer to a version in your own pipeline rather than piping a script from a branch; the snippet above is shortened for readability.
Input handling
Validate and canonicalise all input from files, deep links, QR codes, NFC tags, push payloads and IPC. Use parameterised queries for SQLite. Be careful with deserialisation of untrusted data (prefer JSON with explicit models over native object serialisation). Handle memory-unsafe native code (C and C++ in NDK libraries) with extra care and keep it updated.
Testing: MobSF, Frida, and a method
A layered test approach
| Layer | Tooling | When |
|---|---|---|
| Static code analysis (source) | Android Lint, Detekt, SwiftLint, Semgrep rules, CodeQL | Every pull request |
| Dependency scanning | OSV, Dependabot, Dependency-Check | Every pull request and weekly |
| Secrets scanning | gitleaks, trufflehog | Every push |
| Binary static analysis | MobSF static analysis of APK, AAB or IPA | Every release candidate |
| Dynamic analysis | MobSF dynamic analyser, manual testing with a proxy, Frida | Before major releases |
| Manual test per MASTG | MASTG test cases for relevant MASVS controls | Per feature and per release for high-risk apps |
| Penetration test | Independent specialist using MASTG | Annually or per major change for high-risk apps |
MobSF
Mobile Security Framework is an open-source static and dynamic analysis tool for Android and iOS packages. Run it locally with Docker, upload your release build, and review findings: exported components, cleartext traffic permissions, weak crypto usage, hard-coded secrets, insecure WebView settings, permissions, and third-party tracker libraries.
docker run -it --rm -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
# Then open http://localhost:8000 and upload app-release.apk or an .ipaTreat findings as leads, not verdicts: static tools produce false positives and miss logic flaws. Triage each finding, fix real ones, and record accepted ones with a reason. MobSF also offers a REST API suitable for CI; check the current documentation for authentication and endpoints.
Frida, defensively
Frida is a dynamic instrumentation toolkit that injects scripts into running processes. Attackers use it to hook functions, bypass pinning and call internals. As a defender, use it on your own builds and test devices to answer: if an attacker hooks this, what happens? Authorised use only; do not use it against apps or services you do not own or have permission to test.
Defensive questions to answer with Frida and similar tools:
- If I force the biometric callback to report success, can I get a token? (If so, you have the boolean problem from the biometrics section.)
- If I bypass pinning on a rooted test device, what does the proxy show? Is anything in the traffic sensitive beyond the user's own data? Do requests carry server-verifiable proof (attestation, request signing)?
- If I patch the root detection, does the server still receive a signal and respond with step-up?
- Which functions hold secrets in memory, and for how long?
- Can I call internal APIs with arbitrary arguments and reach an unauthorised state? (This is a server authorisation problem as much as a client one.)
# Safe, read-only enumeration on your own Android test device with Frida installed
frida-ps -Uai # list installed applications
frida-trace -U -f com.example.app.debug -i "open" # trace file opens in a debug build// Minimal Frida script: log which Keystore aliases your own debug build requests.
Java.perform(function () {
var KeyStore = Java.use("java.security.KeyStore");
KeyStore.getKey.overload("java.lang.String", "[C").implementation = function (alias, pw) {
console.log("[keystore] getKey alias=" + alias);
return this.getKey(alias, pw);
};
});Findings from this exercise should change your server design more than your client code: assume the client is compromised and ask whether the server still limits damage. Other useful tools: jadx and apktool for inspecting Android packages, objection for runtime exploration, a proxy like mitmproxy or Burp for traffic review, and MASTG's own tool listings.
Manual test checklist per MASTG area
- Storage: inspect the app sandbox on a test device after use. Are there tokens, personal data or caches in plain text? Check logs, backups, screenshots, keyboard cache and clipboard.
- Crypto: list algorithms and modes in use. Flag ECB, static IVs, hard-coded keys, MD5 and SHA-1 for security, and homemade crypto.
- Auth: verify session expiry, token rotation, logout invalidation and biometric binding.
- Network: capture traffic with a proxy; confirm TLS validation fails with an untrusted CA when pinning is on, and that cleartext is rejected.
- Platform: try malicious deep links, invoke exported components with crafted intents, test WebView navigation to untrusted hosts.
- Resilience: try running on a rooted test device, with a debugger, and under instrumentation; note which signals reach the server.
A step-by-step lab: raise an app from baseline to MASVS-aligned
Estimated time: one engineer, one to two weeks for a typical app. Do it in order; each step produces evidence you can show an auditor.
- Threat model the top three user journeys (sign-in, the money or data path, account recovery). Output: a one-page diagram and list of assets.
- Inventory what the app stores, logs, sends and requests (permissions, SDKs). Output: data inventory spreadsheet. Compare to store privacy declarations.
- Fix storage: move tokens to Keychain or Keystore-backed storage; disable backups for sensitive data; remove sensitive data from logs; add
FLAG_SECUREor app-switcher masking where needed. - Fix transport: enable ATS and Network Security Config; remove cleartext exceptions; add pinning only if you can operate it, with backup pins.
- Fix authentication: OAuth with PKCE through system browser sessions, short-lived access tokens, rotating refresh tokens, biometric-gated keys for sensitive actions.
- Harden the platform surface: set
exportedexplicitly, convert to verified App Links and Universal Links, validate all deep link parameters, harden WebViews. - Add attestation for sign-in and sensitive transactions with server-side verification; define fail-open and fail-closed behaviour per action.
- Build hygiene: R8 on, debuggable off, symbols stripped, mapping files stored, no debug endpoints, no test accounts in release configuration.
- Supply chain: SBOM in CI, dependency scan gates, dependency verification enabled, secrets scanning.
- Test: run MobSF on the release build; perform the manual MASTG checks from the testing section; instrument your own build with Frida to validate the assumptions in the same section.
- Document controls per MASVS group with status (met, not applicable, accepted risk) and evidence links.
- Operationalise: incident runbook, key rotation runbook, a way to force-update old app versions, a vulnerability disclosure policy (a
security.txtfile on your domain and a contact), and monitoring for attestation failure rates and pinning failures.
Where this usually goes wrong
- Storing tokens in
SharedPreferencesorUserDefaults. - Gating on biometrics with a boolean callback instead of a key operation.
- Hard-coding API keys and "secret" strings, assuming obfuscation hides them.
- Pinning without backup pins or an exit plan, causing outages at certificate renewal.
- Disabling TLS validation (trust-all
TrustManager,NSAllowsArbitraryLoads,handler.proceed()) to fix a development issue and shipping it. - Trusting client-side checks: root detection, feature flags, price calculations, role checks.
- Using custom URL schemes for OAuth redirects without PKCE.
- Exporting components without need and with no input validation.
- Leaving debug options in release: debuggable flag, WebView debugging, verbose logs, test endpoints.
- Verifying attestation on the client rather than the server.
- Attesting every request and hitting quotas, or never attesting and ignoring the abuse.
- Logging sensitive data and sending it to crash reporters and analytics.
- Ignoring SDKs in privacy declarations and security reviews.
- Treating a clean MobSF report as proof of security.
- Not planning for key and certificate rotation, token revocation, or force-update of vulnerable versions.
- Copying outdated security advice, such as
EncryptedSharedPreferencesor SafetyNet attestation, without checking current status. SafetyNet Attestation has been retired in favour of Play Integrity.
When not to do this
- Don't pin certificates if you can't operate rotation, if you use a CDN that rotates leaf certificates unpredictably, or if your app has no high-value data. Rely on strict TLS and server defences.
- Don't hard-block rooted or jailbroken devices for general consumer apps. Use risk scoring and step-up flows.
- Don't buy commercial obfuscation or runtime protection because a checklist demanded it. Do it when you have a quantified threat to client-side logic and you can bear the performance and support cost.
- Don't add attestation to every endpoint. Apply it where abuse is costly, and watch quotas.
- Don't build your own cryptography, token format, or attestation verification. Use platform APIs and well-reviewed libraries.
- Don't store sensitive data locally just because you can. The best protection is not having it.
- Don't skip the server. If a control only exists in the client, it is a convenience, not a security control.
- Don't claim compliance from this article. Use the official MASVS and your own assessment and testing.
Pre-release security checklist
THREAT MODEL AND GOVERNANCE
[ ] Threat model reviewed for new features this release
[ ] MASVS control status updated (met / N/A / accepted risk)
[ ] Vulnerability disclosure contact published; incident runbook current
STORAGE AND PRIVACY
[ ] Tokens in Keychain (strictest viable class) or Keystore-backed encryption
[ ] No sensitive data in logs, analytics, crash reports, clipboard, screenshots
[ ] Backups disabled or scoped for sensitive data
[ ] Privacy manifest, App Store labels, Play Data safety match actual SDK behaviour
[ ] Permissions requested just-in-time with rationale; account deletion available
CRYPTO AND AUTH
[ ] No hard-coded keys; no ECB, static IVs, MD5 or SHA-1 for security
[ ] OAuth with PKCE via system browser; no embedded credential collection
[ ] Short-lived access tokens; refresh rotation and reuse detection on server
[ ] Biometrics bound to key operations; enrolment change handled
[ ] Authorisation enforced server-side for every endpoint
NETWORK
[ ] ATS on, no arbitrary loads; cleartext disabled on Android
[ ] Pinning (if used): SPKI pins, backup pin, expiry, rotation runbook, kill switch
[ ] No trust-all TrustManagers; no handler.proceed() in WebViews
[ ] No sensitive data in URLs
PLATFORM
[ ] Every Android component has explicit exported value; internal ones false
[ ] Verified App Links and Universal Links; deep link inputs validated
[ ] WebViews: allow-listed hosts, no file access, bridge minimised, debugging off
[ ] Sensitive screens protected (FLAG_SECURE, app-switcher masking)
CODE AND SUPPLY CHAIN
[ ] Release build: debuggable off, R8 on, symbols stripped, mapping files archived
[ ] SBOM generated; dependency scan clean or risk-accepted; verification metadata on
[ ] Secrets scan clean; shipped keys restricted by package, bundle id and quota
[ ] No test endpoints, debug menus or test accounts in release config
RESILIENCE (HIGH-RISK APPS)
[ ] Attestation (App Attest, Play Integrity) verified server-side with defined fail behaviour
[ ] Root/jailbreak and tamper signals sent to server as risk inputs, not sole gate
[ ] Independent penetration test completed against MASTG for current major version
TESTING EVIDENCE
[ ] MobSF static and dynamic reports triaged
[ ] Manual MASTG checks completed for storage, network, platform
[ ] Frida-based validation on own debug build: biometric, pinning, root-check bypass outcomes recordedQuestions that come up
Is OWASP MASVS a certification? No. It is a standard and set of requirements for verification. Independent labs may assess apps against it, but the project itself does not certify apps.
Is certificate pinning required? Not universally. It is valuable for high-risk apps that can operate it, and harmful when done without a rotation plan. Many apps are better served by strict TLS and server-side controls.
Can I store an API key safely in the app? No. Anything in the binary can be extracted. Proxy the call through your backend, or restrict the key in the provider's console by app identity and quota, and treat it as public.
Is EncryptedSharedPreferences still safe to use? Existing data remains protected by Keystore-backed keys, but the Jetpack Security Crypto library is deprecated. For new code, use Keystore keys directly or Tink, and check the current status in the AndroidX release notes.
Does attestation stop reverse engineering? No. It helps your server decide whether to trust a request, reducing scripted abuse and repackaged clients. It does not prevent someone from analysing the app.
How often should I run a penetration test? For high-risk apps, at least annually and after major architecture or authentication changes. For lower-risk apps, MobSF and manual MASTG checks in CI and per release may be proportionate.
Sources and docs
- OWASP MAS project (MASVS, MASTG, MASWE)
- OWASP MASVS
- OWASP MASTG
- OWASP Mobile Top 10
- Apple: Keychain services
- Apple: Establishing your app's integrity (App Attest)
- Apple: Preventing insecure network connections (ATS)
- Android: Keystore system
- Android: Biometric authentication
- Android: Network security configuration
- Android: Play Integrity API
- Android: App Links verification
- Android: WebView security
- Google Tink
- MobSF
- Frida
- CycloneDX
- gitleaks