Join our Newsletter — 33% off our NHI Course
Home› Guides› SQLite Security Guide: Hardening Settings, Encryption and Untrusted…
Guide Application Security

SQLite Security Guide: Hardening Settings, Encryption and Untrusted Database Files

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 23 November 2026 15 min read
On this page

SQLite is designed to handle hostile SQL and corrupt files safely, but applications that accept untrusted queries or database files should switch on the defensive settings SQLite itself documents. SQLite is not a server you log into. It is a library compiled into applications, mobile apps, desktop tools, browsers, developer utilities and, increasingly, AI agents that keep memory, caches and tool state in a local database file. That ubiquity changes the security question. There is usually no network listener to firewall and no user account to lock down; instead the risks sit in what SQL the application lets through, which files it opens, what it stores in plain text and how much of the machine a single query can consume.

This guide is written for developers and security engineers who embed SQLite or review applications that do. It draws on the SQLite project's own guidance, in particular its page on defending against untrusted inputs, its database configuration options and its documentation for the SQLite Encryption Extension. It covers untrusted SQL, untrusted database files, connection hardening, resource limits, encryption at rest, and the specific concern of credentials and tokens that end up inside local database files.

This is an independent guide from NHI Mgmt Group, based on SQLite's public documentation as of November 2026. It is not sponsored or reviewed by the SQLite developers. Features change between releases, so confirm settings against the SQLite documentation for the version you ship.

Key takeaways

  • SQLite states that it is designed to handle malicious SQL and corrupt database files safely, and the hardening it recommends is defence in depth against undiscovered bugs, not a fix for known flaws.
  • Treat any database file that an agent in a different security domain could have written as suspect, including files downloaded, synced, uploaded or shared between apps.
  • For untrusted files, turn off trusted schema as soon as each connection opens, using SQLITE_DBCONFIG_TRUSTED_SCHEMA or PRAGMA trusted_schema=OFF. It is on by default for legacy compatibility.
  • For untrusted SQL, enable SQLITE_DBCONFIG_DEFENSIVE, lower run-time limits with sqlite3_limit(), and restrict statements with sqlite3_set_authorizer().
  • Bound time and memory with a progress handler or sqlite3_interrupt(), and sqlite3_hard_heap_limit64().
  • Standard SQLite does not encrypt files. The SQLite Encryption Extension is a separately licensed option; whichever approach you use, the key is a secret that needs managing.
  • Never store API keys, OAuth refresh tokens or session secrets in plain SQLite tables on the assumption that local means private.

Why SQLite deserves a security review

Because SQLite is a library, its security posture is whatever the embedding application makes it. Two applications using the same SQLite version can be very differently exposed: one only ever runs fixed, parameterised queries against a file it created itself, while another lets users type SQL, opens database files sent by other people, or loads extensions on request.

The SQLite project separates the problem into two threat models, and this guide follows the same split:

  • Untrusted SQL. An attacker can influence the SQL text that runs, for example through a query box, a reporting feature, a plugin, or an AI agent that writes its own queries.
  • Untrusted database files. An attacker can supply or modify the database file itself, for example through an import feature, a synced folder, an email attachment, or a file left on a shared machine.

There is also a third concern that SQLite's documentation does not address directly but that matters a great deal for non-human identity: what sensitive material the application writes into the file. Local databases routinely hold access tokens, cached credentials, cookies and conversation history, and anything that can read the file can read those values.

Defending against untrusted SQL

If any part of the SQL that reaches SQLite is influenced by someone you do not fully trust, the first line of defence is still the oldest one: use prepared statements with bound parameters and never build SQL by concatenating input. That prevents classic SQL injection, which is covered in depth in the SQL Injection Prevention Guide. The SQLite controls below are for the harder case where the application deliberately runs SQL it did not write.

Enable defensive mode

SQLite recommends setting SQLITE_DBCONFIG_DEFENSIVE, which prevents ordinary SQL statements from deliberately corrupting the database file. The configuration documentation lists what it blocks, including PRAGMA writable_schema=ON, PRAGMA journal_mode=OFF, PRAGMA schema_version=N, writes to the sqlite_dbpage virtual table and direct writes to shadow tables. SQLite describes this as a layer of defence against an attacker who can only run scripts and does not have access to a corrupt file.

Restrict what statements can do

The sqlite3_set_authorizer() interface lets the application inspect each action a statement would take and reject it. SQLite's example is rejecting CREATE or DROP statements in an application that never changes its schema. A sensible pattern for user-supplied queries is an allow list: permit reads on the specific tables you intend to expose, and deny everything else, including ATTACH, PRAGMA and writes.

Lower the limits

SQLite's default limits are generous, and the project notes that most applications can lower them substantially, either with -DSQLITE_MAX_... compile-time options or at run time with sqlite3_limit(). Its security page suggests high-security values for each limit. A selection is shown below; take the full list from SQLite's page.

LimitDefaultSQLite's high-security suggestion
LIMIT_LENGTH1,000,000,0001,000,000
LIMIT_SQL_LENGTH1,000,000,000100,000
LIMIT_COLUMN2,000100
LIMIT_EXPR_DEPTH1,00010
LIMIT_COMPOUND_SELECT5003
LIMIT_VDBE_OP250,000,00025,000
LIMIT_ATTACH100
LIMIT_LIKE_PATTERN_LENGTH50,00050
LIMIT_VARIABLE_NUMBER99910
LIMIT_TRIGGER_DEPTH1,00010

On processors with limited stack space, SQLite advises small values for expression depth and trigger depth, such as 10, to prevent stack overflow from deep recursion. Setting the attach limit to 0 is worth calling out on its own: it stops untrusted SQL from opening additional database files on the connection.

Bound execution time and memory

A single hostile query can try to run for a very long time or consume large amounts of memory. SQLite documents several controls:

  • sqlite3_progress_handler(), a callback that can return non-zero to abort a long-running statement, or a separate timer thread that calls sqlite3_interrupt().
  • sqlite3_hard_heap_limit64() to cap heap usage. SQLite suggests measuring peak usage on typical inputs with sqlite3_memory_highwater() and adding a margin.
  • Lowering SQLITE_MAX_ALLOCATION_SIZE from its default of 2147483391 to 100000000 or smaller.
  • Compiling with -DSQLITE_PRINTF_PRECISION_LIMIT=100000 or similar to cap width and precision in printf() substitutions. SQLite notes the limit must be at least as long as the longest CREATE statement in the schema.
  • On embedded systems, compiling with -DSQLITE_ENABLE_MEMSYS5 and supplying a fixed heap through sqlite3_config(SQLITE_CONFIG_HEAP, ...), so that SQLite returns SQLITE_NOMEM rather than consuming memory the rest of the application needs.

Handling untrusted database files

SQLite's guidance is to treat any database file that an agent in a different security domain could have written to as suspect, and to watch for local files that might have been altered. This is where many applications are more exposed than their developers expect. A database file is not just data; it carries a schema, and that schema can contain triggers, views, CHECK constraints, DEFAULT clauses, indexes and generated columns that run expressions when the application touches the file.

Turn off trusted schema

The configuration documentation explains that when SQLITE_DBCONFIG_TRUSTED_SCHEMA is off, SQLite restricts the SQL functions and virtual tables that can be used in triggers, views, CHECK constraints, DEFAULT clauses, indexes and generated columns. It is on by default for legacy compatibility, and SQLite recommends turning it off where possible. The security page gives several equivalent ways to do this:

  • Call sqlite3_db_config(db, SQLITE_DBCONFIG_TRUSTED_SCHEMA, 0, 0) as soon as each connection opens.
  • Run PRAGMA trusted_schema=OFF as soon as each connection opens.
  • Compile with -DSQLITE_TRUSTED_SCHEMA=0.
  • Set SQLITE_DIRECTONLY on all custom SQL functions and SQLITE_VTAB_DIRECTONLY on all custom virtual tables.
  • In custom virtual tables that run SQL based on CREATE VIRTUAL TABLE arguments, use sqlite3_prepare_v3() with SQLITE_PREPARE_FROM_DDL so the setting cannot be bypassed.

This matters most when the application registers its own functions or virtual tables that have side effects or could leak privileged information. A malicious schema should never be able to call them.

Disable features you do not use

If the application does not use triggers or views, SQLite suggests disabling them with SQLITE_DBCONFIG_ENABLE_TRIGGER and SQLITE_DBCONFIG_ENABLE_VIEW. Fewer features enabled means fewer places for a hostile schema to hide behaviour.

Extra layers for sensitive applications

SQLite lists three further measures that cost some performance and are worth it where the risk justifies them:

  1. Run PRAGMA integrity_check or PRAGMA quick_check as the first statement after opening the file, before any other SQL, and reject any file that reports errors.
  2. Enable PRAGMA cell_size_check=ON.
  3. Disable memory-mapped I/O with PRAGMA mmap_size=0.

In NHI Mgmt Group's view, an import feature that accepts a SQLite file from a user should go further still: open it in a separate process with reduced privileges, apply every setting above, copy only the rows you need into your own database through parameterised statements, and then discard the original.

Connection hardening checklist in code

Most of SQLite's security settings are per connection, which means they have to be applied every time a connection opens, before any untrusted SQL runs. Wrapping them in a single function that every part of the codebase uses is the simplest way to avoid gaps. The configuration options that matter most are:

OptionWhat SQLite documentsHardened value
SQLITE_DBCONFIG_DEFENSIVEDisables features that let ordinary SQL deliberately corrupt the file.1
SQLITE_DBCONFIG_TRUSTED_SCHEMAWhen off, restricts functions and virtual tables used from the schema. On by default.0
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSIONControls sqlite3_load_extension() and the SQL load_extension() function. 1 enables only the C API; 0 disables both.0, or 1 if your own code must load a known extension
SQLITE_DBCONFIG_DQS_DML and SQLITE_DBCONFIG_DQS_DDLControl the legacy behaviour where double-quoted strings are treated as literals.0
SQLITE_DBCONFIG_ENABLE_ATTACH_CREATEControls whether ATTACH can create a new file. Enabled by default.0 where not needed
SQLITE_DBCONFIG_ENABLE_ATTACH_WRITEControls whether ATTACH can open a file for writing. Enabled by default; disabling it also prevents creation.0 where not needed

SQLite notes that unsupported options return a non-zero error code, so check the return value of each call rather than assuming it succeeded. Where your SQLite version predates an option, the call will fail, which is a useful signal that the library needs updating.

ATTACH and file names

The ATTACH DATABASE statement adds another database file to the connection, and its file name follows the same rules as sqlite3_open(). SQLite's documentation notes that URI file names are disabled by default but warns that the default might change in a future release, so applications should not rely on it. If untrusted SQL can reach the connection, set the attach limit to 0 or deny ATTACH in the authorizer so that queries cannot open arbitrary files the process can reach.

Encryption at rest

Standard SQLite writes database files unencrypted. SQLite's own option is the SQLite Encryption Extension (SEE), which its documentation describes as a commercially licensed extension, distributed as drop-in replacement amalgamations, that lets SQLite read and write encrypted files. The SQLite core itself is public domain. The documentation states that all database pages, including metadata, are encrypted, so an encrypted file looks like random data, and that data is encrypted on disk, in the rollback journal and in the WAL file.

Points from SEE's documentation that shape a secure deployment:

  • AES-256 OFB is the recommended algorithm for new development. AES-128 CCM adds authentication with a message authentication code per page. RC4 is supported for legacy use only and is not considered secure.
  • Keys can be supplied as raw keys, hex keys or text keys. SEE recommends text keys, where the passphrase is hashed to produce the key.
  • Data is unencrypted in memory, and TEMP tables and :memory: databases are not encrypted.
  • Databases created with plain SQLite need a VACUUM after encryption is enabled, because they have no nonce space on each page.
  • Keys can be changed with .rekey in the shell, and VACUUM INTO can be used to move to a new algorithm.

Whatever encryption approach you choose, the encryption key becomes a credential with its own lifecycle. SEE documents passing keys on the command line, in URI parameters, through PRAGMAs or through sqlite3_key_v3(). Keys on command lines and in URIs tend to leak into shell history, process listings and logs, so prefer the C API with a key fetched at run time from the platform key store or a secrets manager. Plan for rotation, and follow the OWASP Cryptographic Storage Cheat Sheet on separating keys from the data they protect.

Secrets, tokens and agent state in SQLite files

Local SQLite files are a common hiding place for machine credentials. Desktop tools cache OAuth tokens, command-line utilities store API keys, browsers keep cookies and session data, and AI agents persist memory, tool results and conversation history that can contain secrets pasted by users. Any process or person that can read the file can read those values, and copies of the file travel with backups, sync clients and support bundles.

  • Do not store long-lived secrets in plain tables. Use the operating system's credential store or a secrets manager, and keep only a reference in SQLite.
  • If tokens must be cached, keep them short-lived and encrypt them, or the whole file, with a key the database file does not contain.
  • Set file permissions so only the owning user or service can read the database and its journal and WAL files.
  • Exclude credential-bearing databases from broad backups and diagnostics, or scrub them first.
  • Add SQLite files to secret scanning in repositories and artefact stores. Test fixtures and sample databases are frequently committed with real data inside.
  • Treat agent memory files as sensitive. An agent that writes tool output to SQLite may be recording tokens returned by APIs. Redact before writing.

This is the local-file side of the wider problem of MITRE ATT&CK T1552.001, Credentials In Files.

Keeping SQLite current

SQLite states that it is fuzz-tested and that any crash or memory corruption caused by SQL or database-file input is treated as a serious bug. That only helps applications that pick up fixes. SQLite is frequently vendored, bundled inside language runtimes and statically linked into binaries, so it is easy for an outdated copy to persist unnoticed.

  • Include SQLite in your software bill of materials, including copies bundled by frameworks and language drivers.
  • Track which version each product ships, and update on a regular cadence rather than only after a published vulnerability.
  • Check the CISA Known Exploited Vulnerabilities Catalog as part of routine vulnerability management for every bundled library.

Common failure patterns

  • Trusting a file because it is local. An application opens a database from a downloads folder or shared drive with trusted schema still on and custom functions registered.
  • Settings applied to one connection only. Hardening is added to the main code path while a background worker or library opens its own connection with defaults.
  • User query features without limits. A reporting box or agent tool runs arbitrary SQL with default limits, no authorizer and no time bound.
  • Extensions loadable from SQL. Extension loading is left enabled for convenience, so SQL can request native code.
  • Plain-text tokens in caches. API keys and refresh tokens sit in a settings table that is copied into backups and support bundles.
  • Keys beside the data. The encryption key is stored in a configuration file next to the encrypted database, or passed on a command line.
  • Forgotten bundled copies. An old SQLite build lingers inside a dependency long after the main application was updated.

Practitioner checklist

  • Use prepared statements with bound parameters for all application queries.
  • Apply connection hardening in one shared function: defensive mode on, trusted schema off, extension loading off, double-quoted string literals off.
  • Check the return code of every sqlite3_db_config() call.
  • For untrusted SQL, lower limits with sqlite3_limit(), set the attach limit to 0, and use an authorizer allow list.
  • Bound execution time with a progress handler or sqlite3_interrupt(), and memory with sqlite3_hard_heap_limit64().
  • For untrusted files, run PRAGMA quick_check or integrity_check first, enable cell_size_check and set mmap_size=0.
  • Mark custom functions SQLITE_DIRECTONLY and custom virtual tables SQLITE_VTAB_DIRECTONLY.
  • Keep secrets out of plain SQLite tables, and encrypt any cached tokens with a key stored elsewhere.
  • Restrict file permissions on the database, journal and WAL files.
  • Inventory every bundled SQLite copy and keep it current.

Standards and references

Related NHI Mgmt Group resources: SQL Injection Prevention Guide · Secrets Management Guide · AI Command-Line Tools and Local Secrets

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.