Revert "change compilation / amalgamation order of sqlcipher sources"
[sqlcipher.git] / README.md
blobc2a44397ceadd0617e9d3324df478123ee961b00
1 ## SQLCipher
3 SQLCipher is a standalone fork of the [SQLite](https://www.sqlite.org/) database library that adds 256 bit AES encryption of database files and other security features like:
5 - on-the-fly encryption
6 - tamper detection
7 - memory sanitization
8 - strong key derivation
10 SQLCipher is based on SQLite and stable upstream release features are periodically integrated. While SQLCipher is maintained as a separate version of the source tree, the project minimizes alterations to core SQLite code whenever possible.
12 SQLCipher is maintained by Zetetic, LLC, and additional information and documentation is available on the official [SQLCipher site](https://www.zetetic.net/sqlcipher/).
14 ## Features
16 - Fast performance with as little as 5-15% overhead for encryption on many operations
17 - 100% of data in the database file is encrypted
18 - Good security practices (CBC mode, HMAC, key derivation)
19 - Zero-configuration and application level cryptography
20 - Algorithms provided by the peer reviewed OpenSSL crypto library.
21 - Configurable crypto providers
23 ## Compatibility
25 SQLCipher maintains database format compatibility within the same major version number so an application on any platform can open databases created by any other application provided the major version of SQLCipher is the same between them. However, major version updates (e.g. from 3.x to 4.x) often include changes to default settings. This means that newer major versions of SQLCipher will not open databases created by older versions without using special settings. For example, SQLCipher 4 introduces many new performance and security enhancements. The new default algorithms, increased KDF iterations, and larger page size mean that SQLCipher 4 will not open databases created by SQLCipher 1.x, 2.x, or 3.x by default. Instead, an application would either need to migrate the older databases to use the new format or enable a special backwards-compatibility mode. The available options are described in SQLCipher's [upgrade documentation](https://discuss.zetetic.net/t/upgrading-to-sqlcipher-4/3283). 
27 SQLCipher is also compatible with standard SQLite databases. When a key is not provided, SQLCipher will behave just like the standard SQLite library. It is also possible to convert from a plaintext database (standard SQLite) to an encrypted SQLCipher database using [ATTACH and the sqlcipher_export() convenience function](https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/868).
29 ## Contributions
31 The SQLCipher team welcomes contributions to the core library. All contributions including pull requests and patches should be based on the `prerelease` branch, and must be accompanied by a [contributor agreement](https://www.zetetic.net/contributions/). We strongly encourage [discussion](https://discuss.zetetic.net/c/sqlcipher) of the proposed change prior to development and submission.
33 ## Compiling
35 Building SQLCipher is similar to compiling a regular version of SQLite from source, with a couple of small exceptions:
37  1. You *must* define `SQLITE_HAS_CODEC` and either `SQLITE_TEMP_STORE=2` or `SQLITE_TEMP_STORE=3`
38  2. You will need to link against a support cryptographic provider (OpenSSL, LibTomCrypt, CommonCrypto/Security.framework, or NSS)
40 The following examples demonstrate linking against OpenSSL, which is a readily available provider on most Unix-like systems. 
42 Example 1. Static linking (replace /opt/local/lib with the path to libcrypto.a). Note in this 
43 example, `--enable-tempstore=yes` is setting `SQLITE_TEMP_STORE=2` for the build.
45 ```
46 $ ./configure --enable-tempstore=yes CFLAGS="-DSQLITE_HAS_CODEC" \
47         LDFLAGS="/opt/local/lib/libcrypto.a"
48 $ make
49 ```
51 Example 2. Dynamic linking
53 ```
54 $ ./configure --enable-tempstore=yes CFLAGS="-DSQLITE_HAS_CODEC" \
55         LDFLAGS="-lcrypto"
56 $ make
57 ```
59 ## Testing
61 The full SQLite test suite will not complete successfully when using SQLCipher. In some cases encryption interferes with low-level tests that require access to database file data or features which are unsupported by SQLCipher. Those tests that are intended to support encryption are intended for non-SQLCipher implementations. In addition, because SQLite tests are not always isolated, if one test fails it can trigger a domino effect with other failures in later steps.
63 As a result, the SQLCipher package includes it's own independent tests that exercise and verify the core functionality of the SQLCipher extensions. This test suite is intended to provide an abbreviated verification of SQLCipher's internal logic; it does not perform an exhaustive test of the SQLite database system as a whole or verify functionality on specific platforms. Because SQLCipher is based on stable upstream builds of SQLite, it is consider a basic assumption that the core SQLite library code is operating properly (the SQLite core is almost untouched in SQLCipher). Thus, the additional SQLCipher-specific test provide the requisite verification that the library is operating as expected with SQLCipher's security features enabled.
65 To run SQLCipher specific tests, configure as described here and run the following to execute the tests and receive a report of the results:
67 ```
68 $ ./configure --enable-tempstore=yes --enable-fts5 CFLAGS="-DSQLITE_HAS_CODEC -DSQLCIPHER_TEST" \
69         LDFLAGS="-lcrypto"
70 $ make testfixture
71 $ ./testfixture test/sqlcipher.test
72 ```
74 ## Encrypting a database
76 To specify an encryption passphrase for the database via the SQL interface you 
77 use a PRAGMA. The passphrase you enter is passed through PBKDF2 key derivation to
78 obtain the encryption key for the database 
80         PRAGMA key = 'passphrase';
82 Alternately, you can specify an exact byte sequence using a blob literal. If you
83 use this method it is your responsibility to ensure that the data you provide is a
84 64 character hex string, which will be converted directly to 32 bytes (256 bits) of 
85 key data without key derivation.
87         PRAGMA key = "x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99'";
89 To encrypt a database programmatically you can use the `sqlite3_key` function. 
90 The data provided in `pKey` is converted to an encryption key according to the 
91 same rules as `PRAGMA key`. 
93         int sqlite3_key(sqlite3 *db, const void *pKey, int nKey);
95 `PRAGMA key` or `sqlite3_key` should be called as the first operation when a database is open.
97 ## Changing a database key
99 To change the encryption passphrase for an existing database you may use the rekey PRAGMA
100 after you've supplied the correct database password;
102         PRAGMA key = 'passphrase'; -- start with the existing database passphrase
103         PRAGMA rekey = 'new-passphrase'; -- rekey will reencrypt with the new passphrase
105 The hex rekey pragma may be used to rekey to a specific binary value
107         PRAGMA rekey = "x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99'";
109 This can be accomplished programmatically by using sqlite3_rekey;
110   
111         sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey)
113 ## Support
115 The primary source for complete documentation (design, API, platforms, usage) is the SQLCipher website:
117 https://www.zetetic.net/sqlcipher/documentation
119 The primary avenue for support and discussions is the SQLCipher discuss site:
121 https://discuss.zetetic.net/c/sqlcipher
123 Issues or support questions on using SQLCipher should be entered into the 
124 GitHub Issue tracker:
126 https://github.com/sqlcipher/sqlcipher/issues
128 Please DO NOT post issues, support questions, or other problems to blog 
129 posts about SQLCipher as we do not monitor them frequently.
131 If you are using SQLCipher in your own software please let us know at 
132 support@zetetic.net!
134 ## Community Edition Open Source License
136 Copyright (c) 2020, ZETETIC LLC
137 All rights reserved.
139 Redistribution and use in source and binary forms, with or without
140 modification, are permitted provided that the following conditions are met:
141     * Redistributions of source code must retain the above copyright
142       notice, this list of conditions and the following disclaimer.
143     * Redistributions in binary form must reproduce the above copyright
144       notice, this list of conditions and the following disclaimer in the
145       documentation and/or other materials provided with the distribution.
146     * Neither the name of the ZETETIC LLC nor the
147       names of its contributors may be used to endorse or promote products
148       derived from this software without specific prior written permission.
150 THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
151 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
152 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
153 DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
154 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
155 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
156 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
157 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
158 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
159 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
161 # Begin SQLite README.md
163 <h1 align="center">SQLite Source Repository</h1>
165 This repository contains the complete source code for the 
166 [SQLite database engine](https://sqlite.org/).  Some test scripts 
167 are also included.  However, many other test scripts
168 and most of the documentation are managed separately.
170 ## Version Control
172 SQLite sources are managed using the
173 [Fossil](https://www.fossil-scm.org/), a distributed version control system
174 that was specifically designed and written to support SQLite development.
175 The [Fossil repository](https://sqlite.org/src/timeline) contains the urtext.
177 If you are reading this on GitHub or some other Git repository or service,
178 then you are looking at a mirror.  The names of check-ins and
179 other artifacts in a Git mirror are different from the official
180 names for those objects.  The offical names for check-ins are
181 found in a footer on the check-in comment for authorized mirrors.
182 The official check-in name can also be seen in the `manifest.uuid` file
183 in the root of the tree.  Always use the official name, not  the
184 Git-name, when communicating about an SQLite check-in.
186 If you pulled your SQLite source code from a secondary source and want to
187 verify its integrity, there are hints on how to do that in the
188 [Verifying Code Authenticity](#vauth) section below.
190 ## Obtaining The Code
192 If you do not want to use Fossil, you can download tarballs or ZIP
193 archives or [SQLite archives](https://sqlite.org/cli.html#sqlar) as follows:
195   *  Lastest trunk check-in as
196      [Tarball](https://www.sqlite.org/src/tarball/sqlite.tar.gz),
197      [ZIP-archive](https://www.sqlite.org/src/zip/sqlite.zip), or
198      [SQLite-archive](https://www.sqlite.org/src/sqlar/sqlite.sqlar).
200   *  Latest release as
201      [Tarball](https://www.sqlite.org/src/tarball/sqlite.tar.gz?r=release),
202      [ZIP-archive](https://www.sqlite.org/src/zip/sqlite.zip?r=release), or
203      [SQLite-archive](https://www.sqlite.org/src/sqlar/sqlite.sqlar?r=release).
205   *  For other check-ins, substitute an appropriate branch name or
206      tag or hash prefix in place of "release" in the URLs of the previous
207      bullet.  Or browse the [timeline](https://www.sqlite.org/src/timeline)
208      to locate the check-in desired, click on its information page link,
209      then click on the "Tarball" or "ZIP Archive" links on the information
210      page.
212 If you do want to use Fossil to check out the source tree, 
213 first install Fossil version 2.0 or later.
214 (Source tarballs and precompiled binaries available
215 [here](https://www.fossil-scm.org/fossil/uv/download.html).  Fossil is
216 a stand-alone program.  To install, simply download or build the single 
217 executable file and put that file someplace on your $PATH.)
218 Then run commands like this:
220         mkdir -p ~/sqlite ~/Fossils
221         cd ~/sqlite
222         fossil clone https://www.sqlite.org/src ~/Fossils/sqlite.fossil
223         fossil open ~/Fossils/sqlite.fossil
225 After setting up a repository using the steps above, you can always
226 update to the lastest version using:
228         fossil update trunk   ;# latest trunk check-in
229         fossil update release ;# latest official release
231 Or type "fossil ui" to get a web-based user interface.
233 ## Compiling for Unix-like systems
235 First create a directory in which to place
236 the build products.  It is recommended, but not required, that the
237 build directory be separate from the source directory.  Cd into the
238 build directory and then from the build directory run the configure
239 script found at the root of the source tree.  Then run "make".
241 For example:
243         tar xzf sqlite.tar.gz    ;#  Unpack the source tree into "sqlite"
244         mkdir bld                ;#  Build will occur in a sibling directory
245         cd bld                   ;#  Change to the build directory
246         ../sqlite/configure      ;#  Run the configure script
247         make                     ;#  Run the makefile.
248         make sqlite3.c           ;#  Build the "amalgamation" source file
249         make test                ;#  Run some tests (requires Tcl)
251 See the makefile for additional targets.
253 The configure script uses autoconf 2.61 and libtool.  If the configure
254 script does not work out for you, there is a generic makefile named
255 "Makefile.linux-gcc" in the top directory of the source tree that you
256 can copy and edit to suit your needs.  Comments on the generic makefile
257 show what changes are needed.
259 ## Using MSVC for Windows systems
261 On Windows, all applicable build products can be compiled with MSVC.
262 First open the command prompt window associated with the desired compiler
263 version (e.g. "Developer Command Prompt for VS2013").  Next, use NMAKE
264 with the provided "Makefile.msc" to build one of the supported targets.
266 For example, from the parent directory of the source subtree named "sqlite":
268         mkdir bld
269         cd bld
270         nmake /f ..\sqlite\Makefile.msc TOP=..\sqlite
271         nmake /f ..\sqlite\Makefile.msc sqlite3.c TOP=..\sqlite
272         nmake /f ..\sqlite\Makefile.msc sqlite3.dll TOP=..\sqlite
273         nmake /f ..\sqlite\Makefile.msc sqlite3.exe TOP=..\sqlite
274         nmake /f ..\sqlite\Makefile.msc test TOP=..\sqlite
276 There are several build options that can be set via the NMAKE command
277 line.  For example, to build for WinRT, simply add "FOR_WINRT=1" argument
278 to the "sqlite3.dll" command line above.  When debugging into the SQLite
279 code, adding the "DEBUG=1" argument to one of the above command lines is
280 recommended.
282 SQLite does not require [Tcl](http://www.tcl.tk/) to run, but a Tcl installation
283 is required by the makefiles (including those for MSVC).  SQLite contains
284 a lot of generated code and Tcl is used to do much of that code generation.
286 ## Source Code Tour
288 Most of the core source files are in the **src/** subdirectory.  The
289 **src/** folder also contains files used to build the "testfixture" test
290 harness. The names of the source files used by "testfixture" all begin
291 with "test".
292 The **src/** also contains the "shell.c" file
293 which is the main program for the "sqlite3.exe"
294 [command-line shell](https://sqlite.org/cli.html) and
295 the "tclsqlite.c" file which implements the
296 [Tcl bindings](https://sqlite.org/tclsqlite.html) for SQLite.
297 (Historical note:  SQLite began as a Tcl
298 extension and only later escaped to the wild as an independent library.)
300 Test scripts and programs are found in the **test/** subdirectory.
301 Addtional test code is found in other source repositories.
302 See [How SQLite Is Tested](http://www.sqlite.org/testing.html) for
303 additional information.
305 The **ext/** subdirectory contains code for extensions.  The
306 Full-text search engine is in **ext/fts3**.  The R-Tree engine is in
307 **ext/rtree**.  The **ext/misc** subdirectory contains a number of
308 smaller, single-file extensions, such as a REGEXP operator.
310 The **tool/** subdirectory contains various scripts and programs used
311 for building generated source code files or for testing or for generating
312 accessory programs such as "sqlite3_analyzer(.exe)".
314 ### Generated Source Code Files
316 Several of the C-language source files used by SQLite are generated from
317 other sources rather than being typed in manually by a programmer.  This
318 section will summarize those automatically-generated files.  To create all
319 of the automatically-generated files, simply run "make target&#95;source".
320 The "target&#95;source" make target will create a subdirectory "tsrc/" and
321 fill it with all the source files needed to build SQLite, both
322 manually-edited files and automatically-generated files.
324 The SQLite interface is defined by the **sqlite3.h** header file, which is
325 generated from src/sqlite.h.in, ./manifest.uuid, and ./VERSION.  The
326 [Tcl script](http://www.tcl.tk) at tool/mksqlite3h.tcl does the conversion.
327 The manifest.uuid file contains the SHA3 hash of the particular check-in
328 and is used to generate the SQLITE\_SOURCE\_ID macro.  The VERSION file
329 contains the current SQLite version number.  The sqlite3.h header is really
330 just a copy of src/sqlite.h.in with the source-id and version number inserted
331 at just the right spots. Note that comment text in the sqlite3.h file is
332 used to generate much of the SQLite API documentation.  The Tcl scripts
333 used to generate that documentation are in a separate source repository.
335 The SQL language parser is **parse.c** which is generate from a grammar in
336 the src/parse.y file.  The conversion of "parse.y" into "parse.c" is done
337 by the [lemon](./doc/lemon.html) LALR(1) parser generator.  The source code
338 for lemon is at tool/lemon.c.  Lemon uses the tool/lempar.c file as a
339 template for generating its parser.
340 Lemon also generates the **parse.h** header file, at the same time it
341 generates parse.c.
343 The **opcodes.h** header file contains macros that define the numbers
344 corresponding to opcodes in the "VDBE" virtual machine.  The opcodes.h
345 file is generated by the scanning the src/vdbe.c source file.  The
346 Tcl script at ./mkopcodeh.tcl does this scan and generates opcodes.h.
347 A second Tcl script, ./mkopcodec.tcl, then scans opcodes.h to generate
348 the **opcodes.c** source file, which contains a reverse mapping from
349 opcode-number to opcode-name that is used for EXPLAIN output.
351 The **keywordhash.h** header file contains the definition of a hash table
352 that maps SQL language keywords (ex: "CREATE", "SELECT", "INDEX", etc.) into
353 the numeric codes used by the parse.c parser.  The keywordhash.h file is
354 generated by a C-language program at tool mkkeywordhash.c.
356 The **pragma.h** header file contains various definitions used to parse
357 and implement the PRAGMA statements.  The header is generated by a
358 script **tool/mkpragmatab.tcl**. If you want to add a new PRAGMA, edit
359 the **tool/mkpragmatab.tcl** file to insert the information needed by the
360 parser for your new PRAGMA, then run the script to regenerate the
361 **pragma.h** header file.
363 ### The Amalgamation
365 All of the individual C source code and header files (both manually-edited
366 and automatically-generated) can be combined into a single big source file
367 **sqlite3.c** called "the amalgamation".  The amalgamation is the recommended
368 way of using SQLite in a larger application.  Combining all individual
369 source code files into a single big source code file allows the C compiler
370 to perform more cross-procedure analysis and generate better code.  SQLite
371 runs about 5% faster when compiled from the amalgamation versus when compiled
372 from individual source files.
374 The amalgamation is generated from the tool/mksqlite3c.tcl Tcl script.
375 First, all of the individual source files must be gathered into the tsrc/
376 subdirectory (using the equivalent of "make target_source") then the
377 tool/mksqlite3c.tcl script is run to copy them all together in just the
378 right order while resolving internal "#include" references.
380 The amalgamation source file is more than 200K lines long.  Some symbolic
381 debuggers (most notably MSVC) are unable to deal with files longer than 64K
382 lines.  To work around this, a separate Tcl script, tool/split-sqlite3c.tcl,
383 can be run on the amalgamation to break it up into a single small C file
384 called **sqlite3-all.c** that does #include on about seven other files
385 named **sqlite3-1.c**, **sqlite3-2.c**, ..., **sqlite3-7.c**.  In this way,
386 all of the source code is contained within a single translation unit so
387 that the compiler can do extra cross-procedure optimization, but no
388 individual source file exceeds 32K lines in length.
390 ## How It All Fits Together
392 SQLite is modular in design.
393 See the [architectural description](http://www.sqlite.org/arch.html)
394 for details. Other documents that are useful in
395 (helping to understand how SQLite works include the
396 [file format](http://www.sqlite.org/fileformat2.html) description,
397 the [virtual machine](http://www.sqlite.org/opcode.html) that runs
398 prepared statements, the description of
399 [how transactions work](http://www.sqlite.org/atomiccommit.html), and
400 the [overview of the query planner](http://www.sqlite.org/optoverview.html).
402 Years of effort have gone into optimizating SQLite, both
403 for small size and high performance.  And optimizations tend to result in
404 complex code.  So there is a lot of complexity in the current SQLite
405 implementation.  It will not be the easiest library in the world to hack.
407 Key files:
409   *  **sqlite.h.in** - This file defines the public interface to the SQLite
410      library.  Readers will need to be familiar with this interface before
411      trying to understand how the library works internally.
413   *  **sqliteInt.h** - this header file defines many of the data objects
414      used internally by SQLite.  In addition to "sqliteInt.h", some
415      subsystems have their own header files.
417   *  **parse.y** - This file describes the LALR(1) grammar that SQLite uses
418      to parse SQL statements, and the actions that are taken at each step
419      in the parsing process.
421   *  **vdbe.c** - This file implements the virtual machine that runs
422      prepared statements.  There are various helper files whose names
423      begin with "vdbe".  The VDBE has access to the vdbeInt.h header file
424      which defines internal data objects.  The rest of SQLite interacts
425      with the VDBE through an interface defined by vdbe.h.
427   *  **where.c** - This file (together with its helper files named
428      by "where*.c") analyzes the WHERE clause and generates
429      virtual machine code to run queries efficiently.  This file is
430      sometimes called the "query optimizer".  It has its own private
431      header file, whereInt.h, that defines data objects used internally.
433   *  **btree.c** - This file contains the implementation of the B-Tree
434      storage engine used by SQLite.  The interface to the rest of the system
435      is defined by "btree.h".  The "btreeInt.h" header defines objects
436      used internally by btree.c and not published to the rest of the system.
438   *  **pager.c** - This file contains the "pager" implementation, the
439      module that implements transactions.  The "pager.h" header file
440      defines the interface between pager.c and the rest of the system.
442   *  **os_unix.c** and **os_win.c** - These two files implement the interface
443      between SQLite and the underlying operating system using the run-time
444      pluggable VFS interface.
446   *  **shell.c.in** - This file is not part of the core SQLite library.  This
447      is the file that, when linked against sqlite3.a, generates the
448      "sqlite3.exe" command-line shell.  The "shell.c.in" file is transformed
449      into "shell.c" as part of the build process.
451   *  **tclsqlite.c** - This file implements the Tcl bindings for SQLite.  It
452      is not part of the core SQLite library.  But as most of the tests in this
453      repository are written in Tcl, the Tcl language bindings are important.
455   *  **test*.c** - Files in the src/ folder that begin with "test" go into
456      building the "testfixture.exe" program.  The testfixture.exe program is
457      an enhanced Tcl shell.  The testfixture.exe program runs scripts in the
458      test/ folder to validate the core SQLite code.  The testfixture program
459      (and some other test programs too) is build and run when you type
460      "make test".
462   *  **ext/misc/json1.c** - This file implements the various JSON functions
463      that are build into SQLite.
465 There are many other source files.  Each has a succinct header comment that
466 describes its purpose and role within the larger system.
468 <a name="vauth"></a>
469 ## Verifying Code Authenticity
471 The `manifest` file at the root directory of the source tree
472 contains either a SHA3-256 hash (for newer files) or a SHA1 hash (for 
473 older files) for every source file in the repository.
474 The SHA3-256 hash of the `manifest`
475 file itself is the official name of the version of the source tree that you
476 have. The `manifest.uuid` file should contain the SHA3-256 hash of the
477 `manifest` file. If all of the above hash comparisons are correct, then
478 you can be confident that your source tree is authentic and unadulterated.
480 The format of the `manifest` file should be mostly self-explanatory, but
481 if you want details, they are available
482 [here](https://fossil-scm.org/fossil/doc/trunk/www/fileformat.wiki#manifest).
484 ## Contacts
486 The main SQLite website is [http://www.sqlite.org/](http://www.sqlite.org/)
487 with geographically distributed backups at
488 [http://www2.sqlite.org/](http://www2.sqlite.org) and
489 [http://www3.sqlite.org/](http://www3.sqlite.org).