Skip to main content
Be Bitwise

Insecure Data Storage

Mobile Application Vulnerability Classes · Mobile Application Security track

11 min read

In this module

Where Secrets Go to Die

Mobile apps handle a startling amount of sensitive data — auth tokens, session cookies, personal info, financial records, health data, encryption keys. Where the app puts it, and how it's protected at rest, decides whether that data survives a forensic exam, a curious app sharing the device, or someone walking off with the phone.

Both Android and iOS hand you a buffet of storage APIs with wildly different security properties. Developers on a deadline grab the easiest one, not the safest one. That's how you end up with auth tokens sitting in plaintext XML, readable through adb backup, leaking out through Logcat, and quietly cached in places nobody documented.

Android Storage Mechanisms

SharedPreferences

SharedPreferences is Android's lazy-mode key-value store. It dumps data into an XML file in the app's private directory (/data/data/com.app.package/shared_prefs/). The sandbox keeps other apps out, but SharedPreferences itself adds zero encryption. The XML is plaintext.

xml
<!-- /data/data/com.bank.app/shared_prefs/user_prefs.xml -->
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="auth_token">eyJhbGciOiJIUzI1NiIs...</string>
<string name="username">john.doe@example.com</string>
<boolean name="is_premium" value="true" />
</map>

Root the device and any process can rummage through another app's SharedPreferences. On stock Android, the sandbox keeps other apps at bay — but does nothing against backup extraction.

The Sandbox Is Not Encryption

Android's app sandbox is just Linux file permissions in a costume. It blocks other apps from reading your data at runtime, fine. It does nothing against physical access (rooted device, forensic image), backup extraction (adb backup), or kernel bugs that punch through the sandbox. If data matters, encrypt it before you write it. The sandbox is not a vault.

SQLite Databases

Plenty of apps lean on SQLite for structured storage. The files land in /data/data/com.app.package/databases/ and, like SharedPreferences, ship without encryption. Anyone can sqlite3 the file and query it directly.

Apps with sensitive data in SQLite should reach for SQLCipher, or encrypt fields themselves with a key that lives in the Android Keystore (the Tink library wraps this up neatly), to keep the database encrypted at rest. Without that, a device image or backup spills the table contents wholesale. You'll still see Jetpack Security's EncryptedFile and EncryptedSharedPreferences in older code, but Google deprecated the whole security-crypto library in 2025 in favour of the platform APIs and direct Keystore use.

Internal vs External Storage

Internal storage (/data/data/) sits behind the app sandbox. External storage (/sdcard/ or the SD card) was world-readable on older Android, then gated by READ_EXTERNAL_STORAGE. Scoped storage (introduced in Android 10, enforced for apps targeting Android 11) narrows it further: each app gets its own directory there, and shared media and downloads go through MediaStore. Files in the shared areas are still readable by any app holding the media or all-files permissions. Sticking sensitive data there is publication, not storage.

Apps still do it. Export files, cached downloads, log files end up on external storage for convenience. Treat anything you write there as accessible to every app on the device and anyone with a USB cable.

Android Backup Extraction

Android's adb backup (and its successor, Auto Backup) snapshots an app's data — SharedPreferences, databases, internal files, the works. Unless the app explicitly excludes sensitive files, they're in the snapshot by default.

A few minutes of physical access to an unlocked device, or a computer where ADB is already authorised, is enough to pull the whole thing out:

bash
# Extract app data via ADB backup
adb backup -f backup.ab -noapk com.target.app
# Convert the backup to a tar archive
java -jar abe.jar unpack backup.ab backup.tar
# Extract and read the data
tar xf backup.tar
cat apps/com.target.app/sp/user_prefs.xml

That route has narrowed, though. For apps targeting Android 12 or later, adb backup leaves app data out unless the app is debuggable, so on a current target you'll more often get the same files from a rooted or debuggable test device, a forensic extraction, or the cloud copy that Auto Backup keeps.

The fix is android:allowBackup="false" in the manifest, or android:fullBackupContent to whitelist exactly which files belong in a backup and quietly drop the sensitive ones. Android 12 added android:dataExtractionRules for finer control.

Key Concept
Backup Extraction

Android backups (via adb backup or Auto Backup) include an app's SharedPreferences, databases, and internal files by default. An attacker with ADB access can extract these backups and read all stored data in plaintext. Apps must explicitly exclude sensitive files from backup using manifest attributes, or encrypt sensitive data before storing it.

iOS Storage Mechanisms

NSUserDefaults

NSUserDefaults is iOS's SharedPreferences. It stashes key-value data in a property list at Library/Preferences/com.app.bundle.plist, with the same approach to encryption as SharedPreferences: none.

On a jailbroken device, NSUserDefaults files are openable with any plist viewer. On stock iOS, they're tucked into device backups. An unencrypted iTunes or Finder backup is a free copy of every app's NSUserDefaults on the device.

Plist Files and Core Data

iOS apps also use plist files for config and Core Data for structured persistence. Core Data sits on SQLite under the hood. None of these encrypt anything by default.

The paths are predictable:

  • Plist files: Library/Preferences/
  • Core Data SQLite stores: Library/Application Support/ or Documents/

Forensic tools and backup extractors gobble all of these files up. Anything sensitive sitting in them is compromised the second somebody gets the backup.

Keychain and KeyStore: The Right Answer

Both platforms ship hardware-backed secure storage built for exactly this problem:

iOS Keychain

The Keychain is an encrypted database for credentials, tokens, certificates, and keys. Items are bound to the device passcode and, on devices with a Secure Enclave, to hardware encryption. Every item carries an access control that decides when it can be read:

  • kSecAttrAccessibleWhenUnlocked - accessible only when the device is unlocked
  • kSecAttrAccessibleAfterFirstUnlock - accessible after the first unlock since boot
  • kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly - requires a passcode and is not included in backups

Watch the ThisDeviceOnly suffix. Keychain items without it ride along in encrypted backups and migrate cleanly to a new phone. Items with ThisDeviceOnly are nailed to the specific hardware: a backup carries them wrapped with a key derived from the device's UID, so they only restore to the phone they came from. WhenPasscodeSetThisDeviceOnly items don't go into backups at all.

Pick a kind of secret and see which value fits, what happens when the phone locks, and what you give up. The push token and the background-refresh token land on the same answer for the same reason, so check which property forces it.

Choosing a keychain accessibility class

What are you storing?

Use

kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly

Pushes arrive while the phone sits locked in a pocket, so a notification service extension that authenticates or decrypts them must read its credential then. The token identifies this device, so it shouldn't follow a backup elsewhere.

When the device is locked: Readable once the user has unlocked since boot. After a restart, pushes that need it can't be handled until the first unlock.

Backups and new devices: Restores only to the same device from an encrypted backup. Never syncs through iCloud Keychain.

Trade-off: The key sits in memory on a locked phone, so anyone who gets code running on it can read it. The APNs device token itself isn't a secret and can change, so fetch it from the system each launch rather than trusting a stored copy.

Every kSecAttrAccessible value

ValueBefore first unlockUnlockedLockedEncrypted backupUnencrypted backup
WhenUnlockedLike file Class A. The default when you don't set kSecAttrAccessible.NoReadableNoRestores to a new deviceRestores only to the same device
WhenUnlockedThisDeviceOnlyLike file Class A. Backed up wrapped with a UID-derived key, so it restores only to the same device.NoReadableNoRestores only to the same deviceRestores only to the same device
AfterFirstUnlockLike file Class C. Apple suggests it for items that background refresh needs.NoReadableReadableRestores to a new deviceRestores only to the same device
AfterFirstUnlockThisDeviceOnly(recommended)Like file Class C. Backed up wrapped with a UID-derived key, so it restores only to the same device.NoReadableReadableRestores only to the same deviceRestores only to the same device
WhenPasscodeSetThisDeviceOnlyLike file Class A, and only with a passcode. Can't be stored without a passcode. Remove the passcode and the class keys are discarded, so the items become useless. Never backed up or synced.NoReadableNoNot backed upNot backed up
AlwaysDeprecated. Like file Class D. Deprecated since iOS 12. Use AfterFirstUnlock instead.ReadableReadableReadableRestores to a new deviceRestores only to the same device
AlwaysThisDeviceOnlyDeprecated. Like file Class D. Deprecated since iOS 12. Use AfterFirstUnlockThisDeviceOnly instead.ReadableReadableReadableRestores only to the same deviceRestores only to the same device

ThisDeviceOnly items still go into backups, wrapped with a key derived from the device's UID, so they only restore to the phone they came from. Without a backup password, no keychain item reaches a new phone through a backup.

Source: Apple Platform Security, “Keychain data protection” and “Keybags for Data Protection”.

Android KeyStore

The Android KeyStore keeps cryptographic keys in a container that's a real chore to extract from. On devices with an HSM or TEE, keys can be generated and used entirely inside the secure hardware. The key material never sets foot in your app's process.

java
// Generate a key in the Android KeyStore
KeyGenerator keyGen = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
keyGen.init(new KeyGenParameterSpec.Builder(
"my_key", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(true)
.build());
SecretKey key = keyGen.generateKey();

When Apps Fail to Use Them

The Keychain and KeyStore APIs themselves are solid. The vulnerability is that developers don't reach for them. The APIs are fiddlier than file I/O. Cross-platform frameworks paper over the platform-specific bits. And nobody knows what they don't know about the security implications.

A mobile security audit should always check whether tokens, passwords, and PII are sitting in SharedPreferences/NSUserDefaults instead of KeyStore/Keychain. It's one of the most-common findings in mobile pentest reports, and it's also one of the cheapest to fix.

A common halfway house you'll meet in audits: the developer knows plaintext is bad, so the token gets XORed with a key baked into the APK before it hits SharedPreferences. You don't even need to decompile the app to undo it. Most JWTs start with the same ten characters (the base64 of {"alg":), and that's enough known plaintext:

Try itChange KEY to something longer and see how much of it the known prefix still gives away.
C (GCC 9.2.0)

Clipboard and Pasteboard Leaks

Both platforms maintain a system-wide clipboard (the pasteboard on iOS) that every app can read. When the user copies a password, a card number, or an OTP code, it sits in the clipboard until someone copies something else.

Pre-Android 10, any app could read the clipboard whenever it pleased. No permission required. A background app could poll for changes and exfiltrate everything the user copied. Android 10 narrowed access to the foreground app, but background services and accessibility services can still get at it on some devices.

iOS 14 was the wake-up call. Apple started showing a banner whenever an app read the clipboard, after researchers discovered countless popular apps were silently slurping the pasteboard on every launch.

Don't copy sensitive data to the clipboard at all if you can help it. Mark password fields with android:inputType="textPassword" on Android or secureTextEntry on iOS to stop copying. For OTPs, wire up the platform's direct autofill instead of asking users to copy and paste.

Logging Sensitive Data

Android Logcat

Android's Logcat dumps log messages from every app and system service into one shared buffer. Pre-4.1, any app with READ_LOGS could read the whole thing. That permission has been clipped, but ADB still reads everything from a connected machine.

Developers happily log sensitive data while debugging, and the calls survive into the release build:

java
// Seen in production apps: logging authentication tokens
Log.d("AuthService", "Token refreshed: " + newToken);
Log.i("Payment", "Processing card: " + cardNumber);

Anything you write to Logcat is visible to anyone with ADB, and on older Android versions to other apps on the device.

iOS NSLog

Apple's NSLog writes to the system log, accessible through Xcode's console, macOS Console.app, or idevicesyslog from libimobiledevice. It's a debug tool, but production builds keep finding ways to leak sensitive data through it.

The fix is uncomplicated. Don't log secrets. Use compile-time flags to strip debug logs from release builds, and grep for Log. and NSLog during code review.

Logging as a Data Leak

Mobile logging systems (Logcat, NSLog) are wide open to anyone with physical access or a USB cable. Authentication tokens, personal info, API keys — anything you log is anything you've published. Strip debug logging from production, and review log statements like you'd review SQL.

Side-Channel Data Leaks

The obvious storage paths are only half the problem. Mobile operating systems quietly stash copies of your data in some genuinely surprising spots:

Screenshot Caches

Both iOS and Android grab a screenshot when an app moves to the background, so the app switcher has something to show. If your screen is displaying account balances, private messages, or medical records, that screenshot captures it all and writes it to disk.

iOS defence: implement applicationDidEnterBackground: and slap an opaque or blurred overlay on top before the snapshot fires. Android defence: set FLAG_SECURE on the window.

java
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
);

Keyboard Cache

Mobile keyboards keep a predictive cache so the next "thx" comes faster. The cache learns from whatever the user types — including the contents of sensitive fields. If your password input isn't flagged correctly, the keyboard happily memorises it and may surface it as a suggestion in completely unrelated apps later.

Android: android:inputType="textNoSuggestions|textPassword" on sensitive fields. iOS: autocorrectionType = .no and spellCheckingType = .no, or isSecureTextEntry = true for password fields.

URL and HTTP Response Caches

WebViews and HTTP libraries keep caches of URLs and response bodies. The URL cache happily stores auth tokens you passed as query parameters. The response cache happily stores entire API responses, personal data and all.

Configure sensitive endpoints with Cache-Control: no-store and clear the URL cache on logout. WebView.clearCache(true) on Android, URLCache.shared.removeAllCachedResponses() on iOS.

Forensic Implications

Forensic suites like Cellebrite UFED and Oxygen Forensic Detective, plus the open-source libimobiledevice tools, pull data from every one of these locations. A full forensic acquisition typically recovers SharedPreferences, databases, Logcat output, screenshot caches, keyboard dictionaries, and even deleted files clinging to the filesystem. The only reliable countermeasures are not storing the data at rest in the first place, or encrypting it with keys that live inside the device's secure hardware and stay there.