TExcelTAD
Home › Wireless, IoT & Mobile Security › Insecure Storage, Weak Crypto, WebViews and Hard-Coded Secrets

Insecure Storage, Weak Crypto, WebViews and Hard-Coded Secrets

The manifest and Info.plist show how an app is configured; its code shows what it does with data. Four flaw classes dominate mobile app reviews, year after year: insecure storage (tokens and passwords in plain preference files, logs and backups), weak cryptography (ECB mode, MD5, keys in the code), WebView misuse (JavaScript bridges exposed to web content, local file access, pages loaded over HTTP), and hard-coded secrets (API keys and credentials compiled into the app, where anyone can read them). This lesson builds a small rule-based scanner over excerpts of the sample app's Kotlin and Swift code, then shows why "hidden in the binary" isn't hidden.

Where mobile data really ends up

Location Android iOS Protected by
preference files SharedPreferences (XML in the app sandbox) UserDefaults (plist in the container) the sandbox only; included in backups; readable on rooted/jailbroken devices and from debuggable builds
app files and databases /data/data/<pkg>/files, SQLite container Documents, Library sandbox; on iOS, the Data Protection class of the file
logs logcat (readable by adb, and by apps with log access on old versions) unified log (visible on a connected Mac) almost nothing
backups Auto Backup to the cloud, device transfer iCloud / Finder backups the backup's encryption, often not your choice
key stores Android Keystore (TEE/StrongBox) Keychain (Secure Enclave-backed), with accessibility classes hardware; keys can be non-exportable and bound to user authentication

The rule follows from the table: secrets go into the key store (or are encrypted with a key that lives there), never into preference files, logs or plain files.

A rule-based scanner

Excerpts from four files of the sample app (synthetic), and rules for the four flaw classes, each mapped to a MASVS control and with its fix:

python · try it yourself
import re

SOURCES = {  # excerpts from the LabHome app (synthetic)
    "SessionStore.kt": '''
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putString("access_token", token).apply()
Log.d("LabHome", "login ok, token=$token")
''',
    "CacheCrypto.kt": '''
private const val CACHE_KEY = "0123456789abcdef"
val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
val digest = MessageDigest.getInstance("MD5")
''',
    "HelpScreen.kt": '''
webView.settings.javaScriptEnabled = true
webView.settings.allowFileAccess = true
webView.addJavascriptInterface(DeviceBridge(this), "Device")
webView.loadUrl("http://help.lab.test/" + intent.getStringExtra("page"))
''',
    "ApiClient.swift": '''
let apiKey = "LABKEY-7F2C-9E41"
UserDefaults.standard.set(password, forKey: "password")
let query: [String: Any] = [kSecAttrAccessible as String: kSecAttrAccessibleAlways]
''',
}
RULES = [  # (id, MASVS control, regex, finding, fix)
    ("token-in-prefs", "STORAGE-1", r'putString\("(access_token|refresh_token|password)"',
     "secret in SharedPreferences (plain file, backed up)", "encrypt with a Keystore-held AES-GCM key, exclude from backup"),
    ("secret-in-log", "STORAGE-2", r"Log\.[dviwe]\(.*(token|password)", "secret written to the log",
     "never log secrets; strip debug logs from release (R8 rules)"),
    ("hardcoded-key", "CRYPTO-2", r'(KEY|apiKey|secret)\w*\s*=\s*"[^"]{8,}"', "hard-coded key or API key",
     "keys from the Keystore/Keychain or the backend; per-user tokens"),
    ("ecb-mode", "CRYPTO-1", r'getInstance\("AES/ECB', "AES in ECB mode leaks patterns", "AES-GCM with a fresh nonce"),
    ("weak-hash", "CRYPTO-1", r'getInstance\("(MD5|SHA-?1)"\)', "MD5/SHA-1 for security", "SHA-256 or an HMAC/KDF as needed"),
    ("webview-js-bridge", "PLATFORM-2", r"addJavascriptInterface", "JavaScript bridge exposed to web content",
     "no bridge for remote content; postMessage with origin checks"),
    ("webview-file", "PLATFORM-2", r"allowFileAccess\s*=\s*true", "WebView may read local files", "allowFileAccess = false"),
    ("webview-http-intent", "PLATFORM-2", r'loadUrl\("http://.*getStringExtra', "cleartext page chosen by intent data",
     "https only, allow-list of pages, never URLs from intents"),
    ("userdefaults-secret", "STORAGE-1", r'UserDefaults.*forKey: "(password|token)"', "secret in UserDefaults (plain plist)",
     "Keychain"),
    ("keychain-always", "STORAGE-1", r"kSecAttrAccessibleAlways\b", "Keychain item readable while locked, deprecated",
     "kSecAttrAccessibleWhenUnlockedThisDeviceOnly"),
]
total = 0
for file, src in SOURCES.items():
    for n, line in enumerate(src.strip().splitlines(), 1):
        for rid, masvs, rx, finding, fix in RULES:
            if re.search(rx, line):
                total += 1
                print(f"{file}:{n}  {rid} [{masvs}] {finding}\n      fix: {fix}")
print(total, "findings")
SessionStore.kt:2  token-in-prefs [STORAGE-1] secret in SharedPreferences (plain file, backed up)
      fix: encrypt with a Keystore-held AES-GCM key, exclude from backup
SessionStore.kt:3  secret-in-log [STORAGE-2] secret written to the log
      fix: never log secrets; strip debug logs from release (R8 rules)
CacheCrypto.kt:1  hardcoded-key [CRYPTO-2] hard-coded key or API key
      fix: keys from the Keystore/Keychain or the backend; per-user tokens
CacheCrypto.kt:2  ecb-mode [CRYPTO-1] AES in ECB mode leaks patterns
      fix: AES-GCM with a fresh nonce
CacheCrypto.kt:3  weak-hash [CRYPTO-1] MD5/SHA-1 for security
      fix: SHA-256 or an HMAC/KDF as needed
HelpScreen.kt:2  webview-file [PLATFORM-2] WebView may read local files
      fix: allowFileAccess = false
HelpScreen.kt:3  webview-js-bridge [PLATFORM-2] JavaScript bridge exposed to web content
      fix: no bridge for remote content; postMessage with origin checks
HelpScreen.kt:4  webview-http-intent [PLATFORM-2] cleartext page chosen by intent data
      fix: https only, allow-list of pages, never URLs from intents
ApiClient.swift:1  hardcoded-key [CRYPTO-2] hard-coded key or API key
      fix: keys from the Keystore/Keychain or the backend; per-user tokens
ApiClient.swift:2  userdefaults-secret [STORAGE-1] secret in UserDefaults (plain plist)
      fix: Keychain
ApiClient.swift:3  keychain-always [STORAGE-1] Keychain item readable while locked, deprecated
      fix: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
11 findings

Eleven findings in thirteen lines. Some details behind the rules:

  • Tokens in preferences and UserDefaults: readable from backups, from debuggable builds, on compromised devices, and by forensic tools. Keystore or Keychain storage limits all of those.
  • kSecAttrAccessibleAlways keeps a Keychain item readable while the device is locked (deprecated since iOS 12); …WhenUnlockedThisDeviceOnly also keeps it out of backups and device migrations.
  • ECB encrypts equal blocks to equal ciphertext, so patterns survive (block modes); MD5 and SHA-1 are broken for collisions (MD5 and SHA-1). A key in a const is readable by anyone with the app.
  • WebViews: addJavascriptInterface lets any page loaded in the WebView call the exposed Kotlin methods; combined with a page chosen by intent data and loaded over HTTP, a man in the middle or another app can inject script that controls the user's devices. On iOS the equivalent risk is WKScriptMessageHandler handlers reachable from untrusted content.

Real projects use the same idea at scale: Android Lint, Semgrep and CodeQL rules for mobile, MobSF's static analyser, and secret scanners. Regex rules find candidates; a reviewer confirms each one.

Hard-coded secrets are public

Developers sometimes believe that a key compiled into the app is safe because the app is "binary". The program takes a slice of a synthetic DEX file (Android's compiled code, where string constants are stored in a table) and does what strings and every secret scanner do: extract printable runs, then flag known key formats and high-entropy strings.

python · try it yourself
import math, re
from collections import Counter

# A slice of the app's compiled code as bytes (synthetic): string constants sit next to each other in the DEX file
CONSTANTS = [b"Landroid/util/Log;", b"https://api.lab.test/v1", b"access_token", b"LABKEY-7F2C-9E41",
             b"sk_lab_9fQ2xLm7Rk3VbT8wNc4ZsJ6pYh1Ue5Ga", b"Lkotlin/Metadata;", b"HelpScreen",
             b"AIzaLabOnlyNotARealKey000000"]
dex = b"dex\n035\x00" + bytes(40) + b"".join(b"\x01" + c + b"\x00" for c in CONSTANTS)

def entropy(s):
    c = Counter(s)
    return -sum(n / len(s) * math.log2(n / len(s)) for n in c.values())

KNOWN = {r"^sk_(live|test|lab)_": "payment-style secret key", r"^AIza": "Google-style API key", r"^LABKEY-": "lab API key"}
for m in re.finditer(rb"[\x20-\x7e]{12,}", dex):            # what `strings` does
    s = m.group().decode()
    kind = next((v for k, v in KNOWN.items() if re.match(k, s)), None)
    h = entropy(s)
    if kind or (h > 4.0 and not s.startswith(("L", "https://"))):
        print(f"offset {m.start():3}  {s[:40]:40} entropy {h:.2f}  -> {kind or 'high-entropy string'}")
offset 108  LABKEY-7F2C-9E41                         entropy 3.75  -> lab API key
offset 126  sk_lab_9fQ2xLm7Rk3VbT8wNc4ZsJ6pYh1Ue5Ga  entropy 5.03  -> payment-style secret key
offset 198  AIzaLabOnlyNotARealKey000000             entropy 3.80  -> Google-style API key

Three secrets in a few microseconds, no reverse-engineering skill needed. Obfuscation (R8, ProGuard, iOS symbol stripping) renames classes and methods but leaves string constants intact unless they are encrypted too, and then the decryption key is in the app as well (decoding and obfuscation, strings and entropy).

The fix is architectural: the app gets no long-term shared secret at all. It authenticates the user (OAuth with PKCE, OAuth and OIDC) and receives short-lived, per-user tokens; calls that need a vendor key (maps, payments) go through the backend, which holds the key; where a key must be on the device, it is restricted on the provider's side (to the app's signature, to specific APIs, with quotas). App attestation can make abuse harder but doesn't turn a public key into a secret.

How these flaws are detected

  • Static analysis in CI: rules like the above, Lint, Semgrep/CodeQL, MobSF static scans of the built APK/IPA; secret scanning on the repository and on the build output.
  • Dynamic tests on a test device: inspect the app's sandbox after use (run-as on a debug build, or a test device you control), read logcat during login, check what Auto Backup includes, watch WebView traffic through a proxy (mobile app testing).
  • Provider dashboards: unusual use of an API key from unknown apps or regions means it has been extracted.

How they are fixed

  • Secrets in the Keystore/Keychain; data encrypted with keys held there; ThisDeviceOnly accessibility; backup rules excluding secrets.
  • No secrets in logs: a logging wrapper that redacts tokens; debug logging removed from release builds.
  • Current crypto through high-level APIs: AES-GCM (or the platforms' crypto libraries such as Tink, CryptoKit), SHA-256, random nonces from the platform generator.
  • WebViews: load only your own HTTPS pages from an allow-list; no JavaScript bridge for remote content; allowFileAccess = false; open external links in the system browser.
  • No hard-coded secrets: per-user tokens; vendor keys on the backend or restricted by the provider.

Pitfalls

  • "We encrypt the token before putting it in SharedPreferences" with a key stored next to it in the code.
  • Logging full HTTP requests, including Authorization headers, in a debug interceptor that ships in release.
  • Rotating a leaked API key but shipping the new one the same way.

Practice

1. Add a line Log.i("Sync", "refresh_token=" + rt) to SessionStore.kt. Does the scanner catch it? If not, fix the rule.

Yes: the secret-in-log rule matches Log.i( followed by token anywhere on the line. A rule that only looked for token=$ would miss string concatenation; keep rules about the call and the sensitive name, not the formatting.

2. Why does moving the API key from a Kotlin constant to res/values/strings.xml not help?

Resources are packed into the APK in a readable table; aapt2 dump resources or any decompiler prints them. The key is just as public; the fix is to stop shipping it.

3. The help screen needs JavaScript and must call one native function ("open Bluetooth settings"). Design a safer WebView setup.

Load only bundled or allow-listed HTTPS pages from your domain; no addJavascriptInterface on pages that can include remote content; use WebViewCompat.addWebMessageListener (or postMessage) with an allowed-origin list, and accept a single message type that triggers that one action, ignoring everything else.

Test yourself

Where should a mobile app keep a refresh token?

  1. SharedPreferences or UserDefaults
  2. The Android Keystore / iOS Keychain (or encrypted with a key held there)
  3. A log file
  4. A string constant

Why is addJavascriptInterface dangerous with remote content?

  1. It slows the WebView
  2. Any page loaded in the WebView can call the exposed native methods
  3. It disables HTTPS
  4. It needs root

Does obfuscation hide a hard-coded API key?

  1. Yes, completely
  2. No: string constants survive, and encrypted strings need a key that is also in the app
  3. Only on iOS
  4. Only with R8

What is the architectural fix for vendor API keys in apps?

  1. Longer keys
  2. Keep the key on the backend and give the app short-lived per-user tokens
  3. Base64-encode the key
  4. Store it in resources