Security, Encryption and the Mobile Lifecycle

Article · 7:00

Parameterised queries, file permissions as the whole access model, the encryption options and what each costs, and designing for a process that gets killed without warning.

SQL injection is the one application-level vulnerability that matters here, and the defence is the same as everywhere: parameterised queries, always, with no exceptions for values you believe are safe. SQLite's C API, and every binding over it, supports ? and named parameters. String concatenation into SQL is the vulnerability; there is no safe amount of it.

One SQLite-specific point: sqlite3_prepare_v2 compiles one statement and ignores the rest of the buffer, which blunts the classic '; DROP TABLE -- payload. Do not take comfort from that. sqlite3_exec and most CLI paths run multiple statements happily, and a single-statement injection is still a complete data breach.

The access model is the file. There is no GRANT, no roles, no row-level security by permission. Whoever can read the file reads everything; whoever can write it changes anything. Your controls are the file system's: ownership, mode 0600, and a directory the application alone can traverse. On mobile, the per-application sandbox provides this, and on a rooted or jailbroken device it does not.

Encryption has three realistic options and none ship with the public-domain build. SQLCipher is the widely used open-source option: page-level AES-256, a well-understood key derivation, and broad binding support. SEE is the official commercial extension from the SQLite authors. Platform encryption - iOS Data Protection, Android's file-based encryption - protects the file at rest when the device is locked and is frequently sufficient on its own.

The question that decides which you need is what threat you are defending against. Device theft while locked is handled by platform encryption. A backup extracted from an unlocked device, or a shared machine, needs SQLCipher or SEE. And every option shares the hard problem, which is not encryption but key management: a key hard-coded in the binary is not a secret, and a key derived from a user password is only as good as the password.

The mobile lifecycle is where embedded databases are genuinely different. Your process is terminated without warning, routinely and by design, when the user switches apps and the system needs memory. There is no callback you can rely on. Consequently: never hold a transaction open across a user interaction, keep writes short, checkpoint before backgrounding, and treat synchronous = FULL as the correct setting if a lost transaction would lose user data.

Migration testing is not optional on mobile. Users upgrade from arbitrary old versions, sometimes several at once, and a failed migration on a device you cannot reach is unrecoverable data loss. Test every path from every shipped schema version to the current one, with real data, in CI.

Laboratory exercise 6 - make it shippable.

Demonstrate injection against a deliberately vulnerable query, then fix it with parameters and show the attack failing. Set the database file to 0600, prove another user cannot read it, and document where the file lives on each target platform.

Evaluate the encryption options against a stated threat model - write the threat model first, then decide, and justify the decision including what it does not protect against. If you use SQLCipher, demonstrate that the file is not readable by the standard sqlite3 binary.

Build a migration test harness: for every shipped schema version, apply all migrations up to current against a realistic database and verify the result. Simulate a mid-migration kill and show what happens.

Deliverable: the injection demonstration before and after, file permission evidence, a written threat model with your encryption decision, the migration test harness with its matrix of versions, and a deployment checklist covering file location, backup strategy, WAL checkpointing policy, and the size at which you would move off SQLite entirely.

-- ------------------------------------------------------------------
-- Parameterised queries. The only acceptable way to build SQL.
-- ------------------------------------------------------------------
-- WRONG:
--   "SELECT * FROM expense WHERE note = '" + input + "'"
--   input = "' OR '1'='1"          -> every row
--   input = "'; DELETE FROM expense; --"
--
-- RIGHT - positional:
--   SELECT * FROM expense WHERE description = ?;
-- RIGHT - named, which is better in a long statement:
--   SELECT * FROM expense WHERE description = :note AND spent_at >= :from;
--
-- Note: sqlite3_prepare_v2 compiles ONE statement and ignores the
-- rest of the buffer, which blunts the stacked-query payload. Take no
-- comfort from it. sqlite3_exec runs multiple statements, and a
-- single-statement injection is still a total breach.

-- Identifiers cannot be parameterised. A dynamic column name must be
-- validated against an allow-list in code - never interpolated:
--   if (sortColumn not in ALLOWED) throw;

-- ------------------------------------------------------------------
-- The access model: there is no GRANT. There is chmod.
-- ------------------------------------------------------------------
--   chmod 0600 app.db app.db-wal app.db-shm
--   chown app:app app.db*
--   chmod 0700 /var/lib/app        # the directory matters too
--
-- All three files. A -wal readable by others leaks every recent
-- transaction, and people secure the .db and forget the rest.
--
-- On mobile the application sandbox provides this:
--   iOS      <app>/Library/Application Support/   (NOT Documents:
--            Documents is exposed to iTunes/Files and is backed up)
--   Android  context.getFilesDir()                (NOT external storage)

-- ------------------------------------------------------------------
-- Encryption. None of these are in the public-domain build.
-- ------------------------------------------------------------------
-- SQLCipher - open source, page-level AES-256:
--   PRAGMA key = 'a-key-from-the-keychain-not-the-binary';
--   PRAGMA cipher_page_size = 4096;
--   PRAGMA kdf_iter = 256000;
--
-- Verify it actually encrypted. The standard binary must refuse it:
--   $ sqlite3 encrypted.db "SELECT count(*) FROM expense;"
--   Error: file is not a database          <- correct
--
-- SEE       - the official commercial extension
-- Platform  - iOS Data Protection, Android FBE. Protects at rest
--             while locked, and frequently enough on its own.
--
-- The hard problem is NOT the cipher. It is the key:
--   hard-coded in the binary      -> not a secret. Anyone can extract it.
--   derived from a user password  -> as strong as that password
--   in the platform keychain      -> usually the right answer
--   fetched from a server         -> the database no longer works offline

-- ------------------------------------------------------------------
-- The mobile lifecycle. Your process dies without warning.
-- ------------------------------------------------------------------
PRAGMA synchronous = FULL;      -- if a lost transaction loses user
                                -- data, pay for this
PRAGMA journal_mode = WAL;
PRAGMA busy_timeout = 3000;
PRAGMA foreign_keys = ON;

-- On entering the background, checkpoint and close cleanly:
PRAGMA wal_checkpoint(TRUNCATE);
--
-- Rules that follow from being killable at any instant:
--   * never hold a transaction open across a user interaction
--   * keep write transactions to milliseconds
--   * BEGIN IMMEDIATE for anything that writes
--   * assume every background task is interrupted halfway
--   * make writes idempotent, because a retry after a kill is normal

-- ------------------------------------------------------------------
-- Migration testing. Not optional when you cannot reach the device.
-- ------------------------------------------------------------------
PRAGMA user_version;    -- the shipped version on THIS device

-- The harness, in pseudocode. Every shipped version, every time:
--
--   for version in [1, 2, 3, 4, 5, 6]:          # all ever shipped
--       db = load_fixture("schema_v%d_with_real_data.db" % version)
--       apply_migrations_from(db, version)
--       assert db.user_version == CURRENT
--       assert db.integrity_check() == 'ok'
--       assert db.foreign_key_check() == []
--       assert_row_counts_preserved(db)
--       assert_application_queries_still_work(db)
--
-- Also test the interrupted case: kill the process mid-migration and
-- reopen. A migration inside a single transaction rolls back cleanly;
-- one split across several does not, and that is how a device ends up
-- in a state no version of your code expects.

-- ------------------------------------------------------------------
-- When to stop using SQLite. Write these thresholds down.
-- ------------------------------------------------------------------
--   * more than one process or machine needs to WRITE
--   * the file must live on a network share
--   * you need per-user access control inside the database
--   * write concurrency exceeds what one writer can sustain
--   * you need replication or failover
--
-- Note that size is NOT on the list. Multi-terabyte SQLite databases
-- are in production. Concurrency and sharing are the real limits.

Discussion

No questions on this topic yet. Sign in to ask the first one.