🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Mobile Security: Secure Storage, Pinning and Device Policy

Mobile DefenseMobile SecurityđŸŸĸ Free Lesson

Mobile devices concentrate everything an attacker wants — mail, credentials, authenticator codes, documents, and a camera — into a pocket-sized system that leaves the corporate network daily. Mobile security therefore splits into two problems that are usually handled by different teams: protecting the device and its data when it is lost, stolen, or on hostile Wi-Fi, and protecting the application running on it from reverse engineering, tampering, and insecure storage. Both matter, but the second one is where most development teams quietly fail, because the platform offers secure storage and developers reach for the convenient option instead.

Threats ranked by what they actually compromise

Not every mobile threat deserves equal attention. The table below orders the common ones by practical impact, which is a function of how often they occur and how much a successful attempt yields.

ThreatTypical platformWhat it yieldsRealistic defense
Credential phishingBothAccount takeover, bypass of device trustPhishing-resistant MFA, verified app links
Insecure local storageBothTokens, personal data, cached recordsKeystore and Keychain, no plaintext preferences
Network interceptionBothSession hijacking, credential captureTLS with certificate pinning, no user bypass
Malicious or repackaged appsAndroid primarilyData theft, fraud, adwarePlay Integrity, signature checks, sideload policy
Physical access to unlocked deviceBothEverything the session can reachBiometric re-auth, short session lifetimes
Root or jailbreakBothMalware with elevated capabilityDetection as a risk signal, not a binary gate
Supply-chain SDK compromiseBothSilent data exfiltrationDependency review, minimal SDK surface

Notice what does not appear near the top: stealing a device itself. Modern phones encrypt their storage with a key derived from the passcode, so an unpowered or locked device yields little unless it is seized and attacked offline. The higher-yield targets are the credentials and sessions the device holds while it is in use, which is why short token lifetimes and re-authentication for sensitive actions outperform any amount of device-level hardening.

Platform keystores: never store a secret in plain files

Both platforms provide hardware-backed storage that keeps key material out of application memory and, on modern devices, out of the general-purpose processor entirely. The rule is simple: passwords, API tokens, refresh tokens, and private keys belong in the Keychain or Keystore, while preferences and caches hold only data you would be willing to see on a screenshot.

// iOS: store a refresh token in the Keychain with accessibility limited
// to when the device is unlocked
import Security
import LocalAuthentication

func saveSecret(account: String, value: Data) -> Bool {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrAccount as String: account,
        kSecAttrService as String: "com.example.app.session",
        kSecValueData as String: value,
        kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
    ]
    SecItemDelete(query as CFDictionary)          // replace rather than duplicate
    return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
}

func readSecret(account: String) -> Data? {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrAccount as String: account,
        kSecAttrService as String: "com.example.app.session",
        kSecReturnData as String: true,
        kSecMatchLimit as String: kSecMatchLimitOne,
    ]
    var item: CFTypeRef?
    return SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess
        ? item as? Data : nil
}

// Gate sensitive screens with the platform biometric policy
let context = LAContext()
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,
                           localizedReason: "Confirm it is you") { success, _ in
        DispatchQueue.main.async { requireBiometric(success) }
    }
}

ThisDeviceOnly deserves a moment: it prevents the item from migrating to a new device through a backup restore, which is the right choice for session tokens that should die with the hardware. On Android, the equivalent is a master key with AES256-GCM encryption used to wrap values in EncryptedSharedPreferences, generated once by the Android Keystore and never exported.

Certificate pinning, and how it fails in production

Pinning binds your application to the specific certificate or public key of your API, so a device that trusts an attacker's certificate authority — through a corporate proxy, a malicious root profile, or a compromised device CA — still cannot intercept traffic. The engineering challenge is rotation: a pin that outlives its certificate will brick every installed copy of your application the day the certificate changes.

python
# Pinning configuration that anticipates rotation
PIN_SET = {
    "primary":   "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
    "secondary": "sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",  # backup cert
    "next":      "sha256/CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC=",  # next rotation
}

ALLOWED_HOSTS = {"api.example.com", "cdn.example.com"}

def verify_peer(hostname: str, cert_der: bytes) -> bool:
    if hostname not in ALLOWED_HOSTS:
        return False                       # never pin a host you do not own
    digest = base64.b64encode(hashlib.sha256(cert_der).digest()).decode()
    candidate = f"sha256/{digest}"
    if candidate in (PIN_SET["primary"], PIN_SET["secondary"], PIN_SET["next"]):
        return True
    audit.log("pin_mismatch", host=hostname, seen=candidate[:16])
    return False

# Ship primary and next together, and roll forward one release before
# the old certificate expires — never on the expiry date itself.

Mobile transport security settings can express the same intent at the platform level: iOS permits exceptions through NSAppTransportSecurity, Android through network security configuration files, and both should list only the domains that genuinely need an exception. If the application allows the user to tap through a certificate warning, the pin buys nothing — decide whether the app refuses the connection or fails visibly, and never let a dismissable dialog make the choice.

Root and jailbreak detection without false confidence

Detection is a risk signal, not a security boundary. Any check running on the attacker's own device can be bypassed with a debugger or a patched binary, so treat detection as input to a decision: elevate friction, restrict functionality, or require step-up authentication — rather than simply refusing to run, which punishes the small fraction of legitimate users who root their phones for legitimate reasons.

// Android: gather independent signals and score them instead of one boolean
fun jailbreakRisk(context: Context): Int {
    var score = 0

    val suspiciousPaths = listOf(
        "/system/xbin/su", "/sbin/su", "/system/bin/su",
        "/data/local/bin/su", "/system/app/Superuser.apk",
        "/Library/MobileSubstrate/MobileSubstrate.dylib"   // also seen on jailbroken iOS
    )
    if (suspiciousPaths.any { File(it).exists() }) score += 3

    // Package managers associated with rooting
    val packages = listOf("com.topjohnwu.magisk", "eu.chainfire.supersu")
    val installed = packages.count { pkg ->
        try { context.packageManager.getPackageInfo(pkg, 0); true }
        catch (e: NameNotFoundException) { false }
    }
    score += installed * 2

    // Runtime hooks: the app is being inspected, not just modified
    if (detectFridaOrXposed()) score += 4

    // Test-Keys builds and writable system partitions
    if (Build.TAGS?.contains("test-keys") == true) score += 2

    return score   // 0 = clean, 6+ = treat as high risk and step up auth
}

fun handleRisk(score: Int, session: Session) {
    when {
        score >= 6 -> session.requireStepUpAuth(reason = "device_integrity")
        score >= 3 -> session.restrictTo(readOnly = true)
        else -> return
    }
}

Report the score and its contributing signals to your backend rather than making the decision only on-device. That gives you telemetry for false positives, and it lets you change policy server-side when a new legitimate device shape starts scoring high.

Inter-app boundaries: links, sharing and screens

Most mobile applications talk to other applications, and every one of those handoffs is a place where untrusted input enters. A deep link carrying an identifier lets any installed app drive your navigation; an exported activity on Android can be invoked directly by a third-party package; a screen that renders a URL parameter without validation becomes a phishing page inside your own trusted application. Universal links on iOS and verified app links on Android exist precisely so that only your domain can open your routes, and they must be claimed deliberately rather than assumed.

// Android: validate the link host before trusting anything in the URI
private fun handleIncomingLink(uri: Uri): Boolean {
    if (uri.host !in setOf("www.example.com", "example.com")) return false
    val orderId = uri.getQueryParameter("order_id")
    if (orderId.isNullOrBlank() || !orderId.matches(Regex("^[0-9]{8,12}$"))) {
        showGenericError(); return false
    }
    navigateToOrder(orderId)
    return true
}

The same reasoning extends to everything the application exposes at the edges. Exclude sensitive records from device backups so a stolen phone's backup archive does not carry your session tokens, redact sensitive screens from the app switcher snapshot, clear the clipboard after a paste of a one-time code, and warn before sharing documents that carry watermarks or embedded identifiers. None of these controls requires cryptography; they require deciding, feature by feature, what should be visible to someone holding the device over your user's shoulder.

Managing corporate devices without breaking them

Mobile device management sets the floor for lost, stolen, and BYOD scenarios: encryption required, passcode complexity enforced, screen lock enforced, remote wipe available for corporate data, and jailbreak or root treated as non-compliant. The trap is a policy so strict that users route around it, or one so loose that a lost phone is an incident. Separate corporate data from personal data — containers, work profiles, or app-level management — and you can wipe the work profile on a personal device without erasing someone's photographs.

# MDM compliance policy applied to all corporate endpoints
device_policy:
  identity:
    min_passcode_length: 6
    require_alphanumeric: true
    max_failed_attempts: 10
    inactivity_lock_seconds: 120
    require_biometrics_for_app_unlock: true
  data_protection:
    storage_encryption: required
    backup_encrypted: true
    block_unmanaged_app_data_sharing: true
  integrity:
    block_rooted_or_jailbroken: true
    block_unknown_sources: true
    require_os_version_above: "15.0"
  network:
    vpn_required_for_internal_apps: true
    block_public_wifi_for_restricted_apps: true
  actions:
    on_noncompliant: quarantine      # notify, restrict, then wipe if ignored
    grace_period_hours: 24
    wipe_scope: corporate_container_only

The on_noncompliance sequence matters more than any individual setting. Immediate wipe on a single failed check — an OS update that has not been installed yet, for example — generates helpdesk escalations that erode trust in the whole program. Give a grace period, notify the user with a specific remediation step, and escalate through restrictions before wiping anything.

🔒Assume the device is hostile

Treat every mobile request as if it came from an untrusted network: short-lived tokens, server-side authorization on every call, and integrity signals as risk inputs. Device trust is a convenience, never the sole control protecting customer data.

Common Mistakes

Storing tokens in shared preferences or UserDefaults because it is simpler

Fix: Use the platform keystore with hardware backing and keep only non-sensitive display data in preferences.

Pinning a single certificate with no backup and no rotation plan

Fix: Ship the current and next key hashes together, and rotate one release ahead of certificate expiry.

Allowing users to dismiss certificate warnings when pinning fails

Fix: Fail the connection visibly; a bypassable warning makes the entire pin pointless.

Treating root or jailbreak detection as a hard gate

Fix: Score signals and drive step-up authentication or feature restrictions, and keep the decision server-side.

Writing MDM policy that wipes on the first compliance failure

Fix: Quarantine first, notify with a specific fix, then escalate through restrictions before any wipe.

Best Practices

  • Keep secrets in Keychain or Keystore, and mark session tokens as device-only so they never ride in backups.
  • Refresh tokens server-side with short access-token lifetimes; a stolen token should expire before it can be reused far.
  • Deploy certificate pinning with a rotation window, and monitor pin-mismatch telemetry from the first release.
  • Separate corporate and personal data so remote wipe touches only what the organization owns.
  • Feed device-integrity scores into server-side risk decisions and tune thresholds against real telemetry.

Key Takeaways

  • The highest-yield mobile targets are live credentials and sessions, not the stolen handset itself.
  • Platform keystores keep key material out of app storage; convenience APIs are the usual failure point.
  • Certificate pinning must be designed for rotation or it will break your own application on a schedule.
  • Root and jailbreak detection is a risk signal that can be bypassed, so combine signals and decide server-side.
  • MDM succeeds when corporate control and personal privacy are separated, with escalating rather than instant enforcement.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Cybersecurity Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement