Relocates and defines extension hooks
[sqlcipher.git] / src / sqlcipher.c
blob295c055502751be57048522b4d4b3af35d3c6a2a
1 /*
2 ** SQLCipher
3 ** http://zetetic.net
4 **
5 ** Copyright (c) 2008-2024, ZETETIC LLC
6 ** All rights reserved.
7 **
8 ** Redistribution and use in source and binary forms, with or without
9 ** modification, are permitted provided that the following conditions are met:
10 ** * Redistributions of source code must retain the above copyright
11 ** notice, this list of conditions and the following disclaimer.
12 ** * Redistributions in binary form must reproduce the above copyright
13 ** notice, this list of conditions and the following disclaimer in the
14 ** documentation and/or other materials provided with the distribution.
15 ** * Neither the name of the ZETETIC LLC nor the
16 ** names of its contributors may be used to endorse or promote products
17 ** derived from this software without specific prior written permission.
18 **
19 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
20 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
23 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 **
31 /* BEGIN SQLCIPHER */
32 #ifdef SQLITE_HAS_CODEC
34 #include "sqliteInt.h"
35 #include "btreeInt.h"
36 #include "pager.h"
37 #include "vdbeInt.h"
39 #if !defined(SQLCIPHER_OMIT_LOG_DEVICE)
40 #if defined(__ANDROID__)
41 #include <android/log.h>
42 #elif defined(__APPLE__)
43 #include <TargetConditionals.h>
44 #include <os/log.h>
45 #endif
46 #endif
48 #include <time.h>
50 #if defined(_WIN32) || defined(SQLITE_OS_WINRT)
51 #include <windows.h> /* amalgamator: dontcache */
52 #else
53 #include <sys/time.h> /* amalgamator: dontcache */
54 #endif
56 #ifndef OMIT_MEMLOCK
57 #if defined(__unix__) || defined(__APPLE__) || defined(_AIX)
58 #include <errno.h> /* amalgamator: dontcache */
59 #include <unistd.h> /* amalgamator: dontcache */
60 #include <sys/resource.h> /* amalgamator: dontcache */
61 #include <sys/mman.h> /* amalgamator: dontcache */
62 #endif
63 #endif
65 #include <assert.h>
66 #include "sqlcipher.h"
68 /* extensions defined in pager.c */
69 void *sqlcipherPagerGetCodec(Pager*);
70 void sqlcipherPagerSetCodec(Pager*, void *(*)(void*,void*,Pgno,int), void (*)(void*,int,int), void (*)(void*), void *);
71 int sqlite3pager_is_sj_pgno(Pager*, Pgno);
72 void sqlite3pager_error(Pager*, int);
73 void sqlite3pager_reset(Pager *pPager);
74 /* end extensions defined in pager.c */
76 #if !defined (SQLCIPHER_CRYPTO_CC) \
77 && !defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT) \
78 && !defined (SQLCIPHER_CRYPTO_NSS) \
79 && !defined (SQLCIPHER_CRYPTO_OPENSSL)
80 #define SQLCIPHER_CRYPTO_OPENSSL
81 #endif
83 #define FILE_HEADER_SZ 16
85 #define CIPHER_XSTR(s) CIPHER_STR(s)
86 #define CIPHER_STR(s) #s
88 #ifndef CIPHER_VERSION_NUMBER
89 #define CIPHER_VERSION_NUMBER 4.6.1
90 #endif
92 #ifndef CIPHER_VERSION_BUILD
93 #define CIPHER_VERSION_BUILD community
94 #endif
96 #define CIPHER_DECRYPT 0
97 #define CIPHER_ENCRYPT 1
99 #define CIPHER_READ_CTX 0
100 #define CIPHER_WRITE_CTX 1
101 #define CIPHER_READWRITE_CTX 2
103 #ifndef PBKDF2_ITER
104 #define PBKDF2_ITER 256000
105 #endif
107 #define SQLCIPHER_FLAG_GET(FLAG,BIT) ((FLAG & BIT) != 0)
108 #define SQLCIPHER_FLAG_SET(FLAG,BIT) FLAG |= BIT
109 #define SQLCIPHER_FLAG_UNSET(FLAG,BIT) FLAG &= ~BIT
111 /* possible flags for codec_ctx->flags */
112 #define CIPHER_FLAG_HMAC (1 << 0)
113 #define CIPHER_FLAG_LE_PGNO (1 << 1)
114 #define CIPHER_FLAG_BE_PGNO (1 << 2)
115 #define CIPHER_FLAG_KEY_USED (1 << 3)
116 #define CIPHER_FLAG_HAS_KDF_SALT (1 << 4)
119 #ifndef DEFAULT_CIPHER_FLAGS
120 #define DEFAULT_CIPHER_FLAGS CIPHER_FLAG_HMAC | CIPHER_FLAG_LE_PGNO
121 #endif
124 /* by default, sqlcipher will use a reduced number of iterations to generate
125 the HMAC key / or transform a raw cipher key
127 #ifndef FAST_PBKDF2_ITER
128 #define FAST_PBKDF2_ITER 2
129 #endif
131 /* this if a fixed random array that will be xor'd with the database salt to ensure that the
132 salt passed to the HMAC key derivation function is not the same as that used to derive
133 the encryption key. This can be overridden at compile time but it will make the resulting
134 binary incompatible with the default builds when using HMAC. A future version of SQLcipher
135 will likely allow this to be defined at runtime via pragma */
136 #ifndef HMAC_SALT_MASK
137 #define HMAC_SALT_MASK 0x3a
138 #endif
140 #ifndef CIPHER_MAX_IV_SZ
141 #define CIPHER_MAX_IV_SZ 16
142 #endif
144 #ifndef CIPHER_MAX_KEY_SZ
145 #define CIPHER_MAX_KEY_SZ 64
146 #endif
150 ** Simple shared routines for converting hex char strings to binary data
152 static int cipher_hex2int(char c) {
153 return (c>='0' && c<='9') ? (c)-'0' :
154 (c>='A' && c<='F') ? (c)-'A'+10 :
155 (c>='a' && c<='f') ? (c)-'a'+10 : 0;
158 static void cipher_hex2bin(const unsigned char *hex, int sz, unsigned char *out){
159 int i;
160 for(i = 0; i < sz; i += 2){
161 out[i/2] = (cipher_hex2int(hex[i])<<4) | cipher_hex2int(hex[i+1]);
165 static void cipher_bin2hex(const unsigned char* in, int sz, char *out) {
166 int i;
167 for(i=0; i < sz; i++) {
168 sqlite3_snprintf(3, out + (i*2), "%02x ", in[i]);
172 static int cipher_isHex(const unsigned char *hex, int sz){
173 int i;
174 for(i = 0; i < sz; i++) {
175 unsigned char c = hex[i];
176 if ((c < '0' || c > '9') &&
177 (c < 'A' || c > 'F') &&
178 (c < 'a' || c > 'f')) {
179 return 0;
182 return 1;
185 /* the default implementation of SQLCipher uses a cipher_ctx
186 to keep track of read / write state separately. The following
187 struct and associated functions are defined here */
188 typedef struct {
189 int derive_key;
190 int pass_sz;
191 unsigned char *key;
192 unsigned char *hmac_key;
193 unsigned char *pass;
194 char *keyspec;
195 } cipher_ctx;
198 typedef struct {
199 int store_pass;
200 int kdf_iter;
201 int fast_kdf_iter;
202 int kdf_salt_sz;
203 int key_sz;
204 int iv_sz;
205 int block_sz;
206 int page_sz;
207 int keyspec_sz;
208 int reserve_sz;
209 int hmac_sz;
210 int plaintext_header_sz;
211 int hmac_algorithm;
212 int kdf_algorithm;
213 unsigned int flags;
214 unsigned char *kdf_salt;
215 unsigned char *hmac_kdf_salt;
216 unsigned char *buffer;
217 Btree *pBt;
218 cipher_ctx *read_ctx;
219 cipher_ctx *write_ctx;
220 sqlcipher_provider *provider;
221 void *provider_ctx;
222 } codec_ctx ;
225 #ifdef SQLCIPHER_TEST
226 /* possible flags for simulating specific test conditions */
227 #define TEST_FAIL_ENCRYPT 0x01
228 #define TEST_FAIL_DECRYPT 0x02
229 #define TEST_FAIL_MIGRATE 0x04
231 static volatile unsigned int cipher_test_flags = 0;
232 static volatile int cipher_test_rand = 0;
234 static int sqlcipher_get_test_fail() {
235 int x;
237 /* if cipher_test_rand is not set to a non-zero value always fail (return true) */
238 if (cipher_test_rand == 0) return 1;
240 sqlite3_randomness(sizeof(x), &x);
241 return ((x % cipher_test_rand) == 0);
243 #endif
245 #ifdef SQLCIPHER_EXT
246 int sqlcipher_ext_provider_setup(sqlcipher_provider *);
247 void sqlcipher_ext_provider_destroy();
248 #endif
250 static volatile unsigned int default_flags = DEFAULT_CIPHER_FLAGS;
251 static volatile unsigned char hmac_salt_mask = HMAC_SALT_MASK;
252 static volatile int default_kdf_iter = PBKDF2_ITER;
253 static volatile int default_page_size = 4096;
254 static volatile int default_plaintext_header_size = 0;
255 static volatile int default_hmac_algorithm = SQLCIPHER_HMAC_SHA512;
256 static volatile int default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512;
257 static volatile int sqlcipher_mem_security_on = 0;
258 static volatile int sqlcipher_mem_executed = 0;
259 static volatile int sqlcipher_mem_initialized = 0;
260 static volatile unsigned int sqlcipher_activate_count = 0;
261 static volatile sqlite3_mem_methods default_mem_methods;
262 static sqlcipher_provider *default_provider = NULL;
264 static sqlite3_mutex* sqlcipher_static_mutex[SQLCIPHER_MUTEX_COUNT];
265 static FILE* sqlcipher_log_file = NULL;
266 static volatile int sqlcipher_log_device = 0;
267 static volatile unsigned int sqlcipher_log_level = SQLCIPHER_LOG_NONE;
268 static volatile unsigned int sqlcipher_log_source = SQLCIPHER_LOG_ALL;
269 static volatile int sqlcipher_log_set = 0;
271 sqlite3_mutex* sqlcipher_mutex(int mutex) {
272 if(mutex < 0 || mutex >= SQLCIPHER_MUTEX_COUNT) return NULL;
273 return sqlcipher_static_mutex[mutex];
276 static void sqlcipher_mlock(void *ptr, sqlite_uint64 sz) {
277 #ifndef OMIT_MEMLOCK
278 #if defined(__unix__) || defined(__APPLE__)
279 int rc;
280 unsigned long pagesize = sysconf(_SC_PAGESIZE);
281 unsigned long offset = (unsigned long) ptr % pagesize;
283 if(ptr == NULL || sz == 0) return;
285 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: calling mlock(%p,%lu); _SC_PAGESIZE=%lu", ptr - offset, sz + offset, pagesize);
286 rc = mlock(ptr - offset, sz + offset);
287 if(rc!=0) {
288 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: mlock() returned %d errno=%d", rc, errno);
289 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: mlock(%p,%lu) returned %d errno=%d", ptr - offset, sz + offset, rc, errno);
291 #elif defined(_WIN32)
292 #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP))
293 int rc;
294 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: calling VirtualLock(%p,%d)", ptr, sz);
295 rc = VirtualLock(ptr, sz);
296 if(rc==0) {
297 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: VirtualLock() returned %d LastError=%d", rc, GetLastError());
298 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: VirtualLock(%p,%d) returned %d LastError=%d", ptr, sz, rc, GetLastError());
300 #endif
301 #endif
302 #endif
305 static void sqlcipher_munlock(void *ptr, sqlite_uint64 sz) {
306 #ifndef OMIT_MEMLOCK
307 #if defined(__unix__) || defined(__APPLE__)
308 int rc;
309 unsigned long pagesize = sysconf(_SC_PAGESIZE);
310 unsigned long offset = (unsigned long) ptr % pagesize;
312 if(ptr == NULL || sz == 0) return;
314 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: calling munlock(%p,%lu)", ptr - offset, sz + offset);
315 rc = munlock(ptr - offset, sz + offset);
316 if(rc!=0) {
317 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: munlock(%p,%lu) returned %d errno=%d", ptr - offset, sz + offset, rc, errno);
319 #elif defined(_WIN32)
320 #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP))
321 int rc;
323 if(ptr == NULL || sz == 0) return;
325 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: calling VirtualUnlock(%p,%d)", ptr, sz);
326 rc = VirtualUnlock(ptr, sz);
328 /* because memory allocations may be made from the same individual page, it is possible for VirtualUnlock to be called
329 * multiple times for the same page. Subsequent calls will return an error, but this can be safely ignored (i.e. because
330 * the previous call for that page unlocked the memory already). Log an info level event only in that case. */
331 if(!rc) {
332 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: VirtualUnlock(%p,%d) returned %d LastError=%d", ptr, sz, rc, GetLastError());
334 #endif
335 #endif
336 #endif
339 static int sqlcipher_mem_init(void *pAppData) {
340 return default_mem_methods.xInit(pAppData);
342 static void sqlcipher_mem_shutdown(void *pAppData) {
343 default_mem_methods.xShutdown(pAppData);
345 static void *sqlcipher_mem_malloc(int n) {
346 void *ptr = default_mem_methods.xMalloc(n);
347 if(!sqlcipher_mem_executed) sqlcipher_mem_executed = 1;
348 if(sqlcipher_mem_security_on) {
349 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_mem_malloc: calling sqlcipher_mlock(%p,%d)", ptr, n);
350 sqlcipher_mlock(ptr, n);
352 return ptr;
354 static int sqlcipher_mem_size(void *p) {
355 return default_mem_methods.xSize(p);
357 static void sqlcipher_mem_free(void *p) {
358 int sz;
359 if(!sqlcipher_mem_executed) sqlcipher_mem_executed = 1;
360 if(sqlcipher_mem_security_on) {
361 sz = sqlcipher_mem_size(p);
362 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_mem_free: calling sqlcipher_memset(%p,0,%d) and sqlcipher_munlock(%p, %d)", p, sz, p, sz);
363 sqlcipher_memset(p, 0, sz);
364 sqlcipher_munlock(p, sz);
366 default_mem_methods.xFree(p);
368 static void *sqlcipher_mem_realloc(void *p, int n) {
369 void *new = NULL;
370 int orig_sz = 0;
371 if(sqlcipher_mem_security_on) {
372 orig_sz = sqlcipher_mem_size(p);
373 if (n==0) {
374 sqlcipher_mem_free(p);
375 return NULL;
376 } else if (!p) {
377 return sqlcipher_mem_malloc(n);
378 } else if(n <= orig_sz) {
379 return p;
380 } else {
381 new = sqlcipher_mem_malloc(n);
382 if(new) {
383 memcpy(new, p, orig_sz);
384 sqlcipher_mem_free(p);
386 return new;
388 } else {
389 return default_mem_methods.xRealloc(p, n);
393 static int sqlcipher_mem_roundup(int n) {
394 return default_mem_methods.xRoundup(n);
397 static sqlite3_mem_methods sqlcipher_mem_methods = {
398 sqlcipher_mem_malloc,
399 sqlcipher_mem_free,
400 sqlcipher_mem_realloc,
401 sqlcipher_mem_size,
402 sqlcipher_mem_roundup,
403 sqlcipher_mem_init,
404 sqlcipher_mem_shutdown,
408 void sqlcipher_init_memmethods() {
409 if(sqlcipher_mem_initialized) return;
410 if(sqlite3_config(SQLITE_CONFIG_GETMALLOC, &default_mem_methods) != SQLITE_OK ||
411 sqlite3_config(SQLITE_CONFIG_MALLOC, &sqlcipher_mem_methods) != SQLITE_OK) {
412 sqlcipher_mem_security_on = sqlcipher_mem_executed = sqlcipher_mem_initialized = 0;
413 } else {
414 sqlcipher_mem_initialized = 1;
418 int sqlcipher_register_provider(sqlcipher_provider *p) {
419 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: entering SQLCIPHER_MUTEX_PROVIDER");
420 sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
421 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: entered SQLCIPHER_MUTEX_PROVIDER");
423 if(default_provider != NULL && default_provider != p) {
424 /* only free the current registerd provider if it has been initialized
425 and it isn't a pointer to the same provider passed to the function
426 (i.e. protect against a caller calling register twice for the same provider) */
427 sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
429 default_provider = p;
430 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: leaving SQLCIPHER_MUTEX_PROVIDER");
431 sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
432 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: left SQLCIPHER_MUTEX_PROVIDER");
434 return SQLITE_OK;
437 /* return a pointer to the currently registered provider. This will
438 allow an application to fetch the current registered provider and
439 make minor changes to it */
440 sqlcipher_provider* sqlcipher_get_provider() {
441 return default_provider;
444 static void sqlcipher_activate() {
445 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: entering static master mutex");
446 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
447 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: entered static master mutex");
449 /* allocate new mutexes */
450 if(sqlcipher_activate_count == 0) {
451 int i;
452 for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) {
453 sqlcipher_static_mutex[i] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
455 #ifndef SQLCIPHER_OMIT_DEFAULT_LOGGING
456 /* when sqlcipher is first activated, set a default log target and level of WARN if the
457 logging settings have not yet been initialized. Use the "device log" for
458 android (logcat) or apple (console). Use stderr on all other platforms. */
459 if(!sqlcipher_log_set) {
461 /* set log level if it is different than the uninitalized default value of NONE */
462 if(sqlcipher_log_level == SQLCIPHER_LOG_NONE) {
463 sqlcipher_log_level = SQLCIPHER_LOG_WARN;
466 /* set the default file or device if neither is already set */
467 if(sqlcipher_log_device == 0 && sqlcipher_log_file == NULL) {
468 #if defined(__ANDROID__) || defined(__APPLE_)
469 sqlcipher_log_device = 1;
470 #else
471 sqlcipher_log_file = stderr;
472 #endif
474 sqlcipher_log_set = 1;
476 #endif
479 /* check to see if there is a provider registered at this point
480 if there no provider registered at this point, register the
481 default provider */
482 if(sqlcipher_get_provider() == NULL) {
483 sqlcipher_provider *p = sqlcipher_malloc(sizeof(sqlcipher_provider));
484 #if defined (SQLCIPHER_CRYPTO_CC)
485 extern int sqlcipher_cc_setup(sqlcipher_provider *p);
486 sqlcipher_cc_setup(p);
487 #elif defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT)
488 extern int sqlcipher_ltc_setup(sqlcipher_provider *p);
489 sqlcipher_ltc_setup(p);
490 #elif defined (SQLCIPHER_CRYPTO_NSS)
491 extern int sqlcipher_nss_setup(sqlcipher_provider *p);
492 sqlcipher_nss_setup(p);
493 #elif defined (SQLCIPHER_CRYPTO_OPENSSL)
494 extern int sqlcipher_openssl_setup(sqlcipher_provider *p);
495 sqlcipher_openssl_setup(p);
496 #elif defined (SQLCIPHER_CRYPTO_OSSL3)
497 extern int sqlcipher_ossl3_setup(sqlcipher_provider *p);
498 sqlcipher_ossl3_setup(p);
499 #else
500 #error "NO DEFAULT SQLCIPHER CRYPTO PROVIDER DEFINED"
501 #endif
502 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_activate: calling sqlcipher_register_provider(%p)", p);
503 #ifdef SQLCIPHER_EXT
504 sqlcipher_ext_provider_setup(p);
505 #endif
506 sqlcipher_register_provider(p);
507 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_activate: called sqlcipher_register_provider(%p)",p);
510 sqlcipher_activate_count++; /* increment activation count */
512 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: leaving static master mutex");
513 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
514 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: left static master mutex");
517 static void sqlcipher_deactivate() {
518 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entering static master mutex");
519 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
520 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entered static master mutex");
522 sqlcipher_activate_count--;
523 /* if no connections are using sqlcipher, cleanup globals */
524 if(sqlcipher_activate_count < 1) {
525 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entering SQLCIPHER_MUTEX_PROVIDER");
526 sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
527 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entered SQLCIPHER_MUTEX_PROVIDER");
529 if(default_provider != NULL) {
530 sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
531 default_provider = NULL;
534 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: leaving SQLCIPHER_MUTEX_PROVIDER");
535 sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
536 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: left SQLCIPHER_MUTEX_PROVIDER");
538 #ifdef SQLCIPHER_EXT
539 sqlcipher_ext_provider_destroy();
540 #endif
542 /* last connection closed, free mutexes */
543 if(sqlcipher_activate_count == 0) {
544 int i;
545 for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) {
546 sqlite3_mutex_free(sqlcipher_static_mutex[i]);
549 sqlcipher_activate_count = 0; /* reset activation count */
552 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: leaving static master mutex");
553 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
554 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: left static master mutex");
557 /* constant time memset using volitile to avoid having the memset
558 optimized out by the compiler.
559 Note: As suggested by Joachim Schipper (joachim.schipper@fox-it.com)
561 void* sqlcipher_memset(void *v, unsigned char value, sqlite_uint64 len) {
562 volatile sqlite_uint64 i = 0;
563 volatile unsigned char *a = v;
565 if (v == NULL) return v;
567 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_memset: setting %p[0-%llu]=%d)", a, len, value);
568 for(i = 0; i < len; i++) {
569 a[i] = value;
572 return v;
575 /* constant time memory check tests every position of a memory segement
576 matches a single value (i.e. the memory is all zeros)
577 returns 0 if match, 1 of no match */
578 int sqlcipher_ismemset(const void *v, unsigned char value, sqlite_uint64 len) {
579 const volatile unsigned char *a = v;
580 volatile sqlite_uint64 i = 0, result = 0;
582 for(i = 0; i < len; i++) {
583 result |= a[i] ^ value;
586 return (result != 0);
589 /* constant time memory comparison routine.
590 returns 0 if match, 1 if no match */
591 int sqlcipher_memcmp(const void *v0, const void *v1, int len) {
592 const volatile unsigned char *a0 = v0, *a1 = v1;
593 volatile int i = 0, result = 0;
595 for(i = 0; i < len; i++) {
596 result |= a0[i] ^ a1[i];
599 return (result != 0);
603 * Free and wipe memory. Uses SQLites internal sqlite3_free so that memory
604 * can be countend and memory leak detection works in the test suite.
605 * If ptr is not null memory will be freed.
606 * If sz is greater than zero, the memory will be overwritten with zero before it is freed
607 * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the
608 * memory segment so it can be paged
610 void sqlcipher_free(void *ptr, sqlite_uint64 sz) {
611 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_free: calling sqlcipher_memset(%p,0,%llu)", ptr, sz);
612 sqlcipher_memset(ptr, 0, sz);
613 sqlcipher_munlock(ptr, sz);
614 sqlite3_free(ptr);
618 * allocate memory. Uses sqlite's internall malloc wrapper so memory can be
619 * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK
620 * attempts to lock the memory pages so sensitive information won't be swapped
622 void* sqlcipher_malloc(sqlite_uint64 sz) {
623 void *ptr;
624 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_malloc: calling sqlite3Malloc(%llu)", sz);
625 ptr = sqlite3Malloc(sz);
626 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_malloc: calling sqlcipher_memset(%p,0,%llu)", ptr, sz);
627 sqlcipher_memset(ptr, 0, sz);
628 sqlcipher_mlock(ptr, sz);
629 return ptr;
632 char* sqlcipher_version() {
633 #ifdef CIPHER_VERSION_QUALIFIER
634 char *version = sqlite3_mprintf("%s %s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_QUALIFIER), CIPHER_XSTR(CIPHER_VERSION_BUILD));
635 #else
636 char *version = sqlite3_mprintf("%s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_BUILD));
637 #endif
638 return version;
642 * Initialize new cipher_ctx struct. This function will allocate memory
643 * for the cipher context and for the key
645 * returns SQLITE_OK if initialization was successful
646 * returns SQLITE_NOMEM if an error occured allocating memory
648 static int sqlcipher_cipher_ctx_init(codec_ctx *ctx, cipher_ctx **iCtx) {
649 cipher_ctx *c_ctx;
650 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_cipher_ctx_init: allocating context");
651 *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx));
652 c_ctx = *iCtx;
653 if(c_ctx == NULL) return SQLITE_NOMEM;
655 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_cipher_ctx_init: allocating key");
656 c_ctx->key = (unsigned char *) sqlcipher_malloc(ctx->key_sz);
658 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_cipher_ctx_init: allocating hmac_key");
659 c_ctx->hmac_key = (unsigned char *) sqlcipher_malloc(ctx->key_sz);
661 if(c_ctx->key == NULL) return SQLITE_NOMEM;
662 if(c_ctx->hmac_key == NULL) return SQLITE_NOMEM;
664 return SQLITE_OK;
668 * Free and wipe memory associated with a cipher_ctx
670 static void sqlcipher_cipher_ctx_free(codec_ctx* ctx, cipher_ctx **iCtx) {
671 cipher_ctx *c_ctx = *iCtx;
672 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "cipher_ctx_free: iCtx=%p", iCtx);
673 if(c_ctx->key) sqlcipher_free(c_ctx->key, ctx->key_sz);
674 if(c_ctx->hmac_key) sqlcipher_free(c_ctx->hmac_key, ctx->key_sz);
675 if(c_ctx->pass) sqlcipher_free(c_ctx->pass, c_ctx->pass_sz);
676 if(c_ctx->keyspec) sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz);
677 sqlcipher_free(c_ctx, sizeof(cipher_ctx));
680 static int sqlcipher_codec_ctx_reserve_setup(codec_ctx *ctx) {
681 int base_reserve = ctx->iv_sz; /* base reserve size will be IV only */
682 int reserve = base_reserve;
684 ctx->hmac_sz = ctx->provider->get_hmac_sz(ctx->provider_ctx, ctx->hmac_algorithm);
686 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC))
687 reserve += ctx->hmac_sz; /* if reserve will include hmac, update that size */
689 /* calculate the amount of reserve needed in even increments of the cipher block size */
690 if(ctx->block_sz > 0) {
691 reserve = ((reserve % ctx->block_sz) == 0) ? reserve :
692 ((reserve / ctx->block_sz) + 1) * ctx->block_sz;
695 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_reserve_setup: base_reserve=%d block_sz=%d md_size=%d reserve=%d",
696 base_reserve, ctx->block_sz, ctx->hmac_sz, reserve);
698 ctx->reserve_sz = reserve;
700 return SQLITE_OK;
704 * Compare one cipher_ctx to another.
706 * returns 0 if all the parameters (except the derived key data) are the same
707 * returns 1 otherwise
709 static int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) {
710 int are_equal = (
711 c1->pass_sz == c2->pass_sz
712 && (
713 c1->pass == c2->pass
714 || !sqlcipher_memcmp((const unsigned char*)c1->pass,
715 (const unsigned char*)c2->pass,
716 c1->pass_sz)
719 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_cmp: c1=%p c2=%p sqlcipher_memcmp(c1->pass, c2_pass)=%d are_equal=%d",
720 c1, c2,
721 (c1->pass == NULL || c2->pass == NULL) ?
722 -1 :
723 sqlcipher_memcmp(
724 (const unsigned char*)c1->pass,
725 (const unsigned char*)c2->pass,
726 c1->pass_sz
728 are_equal
731 return !are_equal; /* return 0 if they are the same, 1 otherwise */
735 * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a
736 * fully initialized context, you could copy it to write_ctx and all yet data
737 * and pass information across
739 * returns SQLITE_OK if initialization was successful
740 * returns SQLITE_NOMEM if an error occured allocating memory
742 static int sqlcipher_cipher_ctx_copy(codec_ctx *ctx, cipher_ctx *target, cipher_ctx *source) {
743 void *key = target->key;
744 void *hmac_key = target->hmac_key;
746 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_copy: target=%p, source=%p", target, source);
747 if(target->pass) sqlcipher_free(target->pass, target->pass_sz);
748 if(target->keyspec) sqlcipher_free(target->keyspec, ctx->keyspec_sz);
749 memcpy(target, source, sizeof(cipher_ctx));
751 target->key = key; /* restore pointer to previously allocated key data */
752 memcpy(target->key, source->key, ctx->key_sz);
754 target->hmac_key = hmac_key; /* restore pointer to previously allocated hmac key data */
755 memcpy(target->hmac_key, source->hmac_key, ctx->key_sz);
757 if(source->pass && source->pass_sz) {
758 target->pass = sqlcipher_malloc(source->pass_sz);
759 if(target->pass == NULL) return SQLITE_NOMEM;
760 memcpy(target->pass, source->pass, source->pass_sz);
762 if(source->keyspec) {
763 target->keyspec = sqlcipher_malloc(ctx->keyspec_sz);
764 if(target->keyspec == NULL) return SQLITE_NOMEM;
765 memcpy(target->keyspec, source->keyspec, ctx->keyspec_sz);
767 return SQLITE_OK;
771 * Set the keyspec for the cipher_ctx
773 * returns SQLITE_OK if assignment was successfull
774 * returns SQLITE_NOMEM if an error occured allocating memory
776 static int sqlcipher_cipher_ctx_set_keyspec(codec_ctx *ctx, cipher_ctx *c_ctx, const unsigned char *key) {
777 /* free, zero existing pointers and size */
778 if(c_ctx->keyspec) sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz);
779 c_ctx->keyspec = NULL;
781 c_ctx->keyspec = sqlcipher_malloc(ctx->keyspec_sz);
782 if(c_ctx->keyspec == NULL) return SQLITE_NOMEM;
784 c_ctx->keyspec[0] = 'x';
785 c_ctx->keyspec[1] = '\'';
786 cipher_bin2hex(key, ctx->key_sz, c_ctx->keyspec + 2);
787 cipher_bin2hex(ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->keyspec + (ctx->key_sz * 2) + 2);
788 c_ctx->keyspec[ctx->keyspec_sz - 1] = '\'';
789 return SQLITE_OK;
792 static void sqlcipher_set_derive_key(codec_ctx *ctx, int derive) {
793 if(ctx->read_ctx != NULL) ctx->read_ctx->derive_key = derive;
794 if(ctx->write_ctx != NULL) ctx->write_ctx->derive_key = derive;
798 * Set the passphrase for the cipher_ctx
800 * returns SQLITE_OK if assignment was successfull
801 * returns SQLITE_NOMEM if an error occured allocating memory
803 static int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) {
804 /* free, zero existing pointers and size */
805 if(ctx->pass) sqlcipher_free(ctx->pass, ctx->pass_sz);
806 ctx->pass = NULL;
807 ctx->pass_sz = 0;
809 if(zKey && nKey) { /* if new password is provided, copy it */
810 ctx->pass_sz = nKey;
811 ctx->pass = sqlcipher_malloc(nKey);
812 if(ctx->pass == NULL) return SQLITE_NOMEM;
813 memcpy(ctx->pass, zKey, nKey);
815 return SQLITE_OK;
818 static int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) {
819 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
820 int rc;
822 if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLITE_OK) {
823 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_pass: error %d from sqlcipher_cipher_ctx_set_pass", rc);
824 return rc;
827 c_ctx->derive_key = 1;
829 if(for_ctx == 2) {
830 if((rc = sqlcipher_cipher_ctx_copy(ctx, for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) {
831 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_pass: error %d from sqlcipher_cipher_ctx_copy", rc);
832 return rc;
836 return SQLITE_OK;
839 static int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter) {
840 ctx->kdf_iter = kdf_iter;
841 sqlcipher_set_derive_key(ctx, 1);
842 return SQLITE_OK;
845 static int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter) {
846 ctx->fast_kdf_iter = fast_kdf_iter;
847 sqlcipher_set_derive_key(ctx, 1);
848 return SQLITE_OK;
851 /* set the global default flag for HMAC */
852 static void sqlcipher_set_default_use_hmac(int use) {
853 if(use) SQLCIPHER_FLAG_SET(default_flags, CIPHER_FLAG_HMAC);
854 else SQLCIPHER_FLAG_UNSET(default_flags,CIPHER_FLAG_HMAC);
857 /* set the codec flag for whether this individual database should be using hmac */
858 static int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) {
859 if(use) {
860 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_HMAC);
861 } else {
862 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_HMAC);
865 return sqlcipher_codec_ctx_reserve_setup(ctx);
868 /* the length of plaintext header size must be:
869 * 1. greater than or equal to zero
870 * 2. a multiple of the cipher block size
871 * 3. less than the usable size of the first database page
873 static int sqlcipher_codec_ctx_set_plaintext_header_size(codec_ctx *ctx, int size) {
874 if(size >= 0 && ctx->block_sz > 0 && (size % ctx->block_sz) == 0 && size < (ctx->page_sz - ctx->reserve_sz)) {
875 ctx->plaintext_header_sz = size;
876 return SQLITE_OK;
878 ctx->plaintext_header_sz = -1;
879 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_plaintext_header_size: attempt to set invalid plantext_header_size %d", size);
880 return SQLITE_ERROR;
883 static int sqlcipher_codec_ctx_set_hmac_algorithm(codec_ctx *ctx, int algorithm) {
884 ctx->hmac_algorithm = algorithm;
885 return sqlcipher_codec_ctx_reserve_setup(ctx);
888 static int sqlcipher_codec_ctx_set_kdf_algorithm(codec_ctx *ctx, int algorithm) {
889 ctx->kdf_algorithm = algorithm;
890 return SQLITE_OK;
893 static void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) {
894 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_error %d", error);
895 sqlite3pager_error(ctx->pBt->pBt->pPager, error);
896 ctx->pBt->pBt->db->errCode = error;
899 static int sqlcipher_codec_ctx_init_kdf_salt(codec_ctx *ctx) {
900 sqlite3_file *fd = sqlite3PagerFile(ctx->pBt->pBt->pPager);
902 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT)) {
903 return SQLITE_OK; /* don't reload salt when not needed */
906 /* read salt from header, if present, otherwise generate a new random salt */
907 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init_kdf_salt: obtaining salt");
908 if(fd == NULL || fd->pMethods == 0 || sqlite3OsRead(fd, ctx->kdf_salt, ctx->kdf_salt_sz, 0) != SQLITE_OK) {
909 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init_kdf_salt: unable to read salt from file header, generating random");
910 if(ctx->provider->random(ctx->provider_ctx, ctx->kdf_salt, ctx->kdf_salt_sz) != SQLITE_OK) {
911 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init_kdf_salt: error retrieving random bytes from provider");
912 return SQLITE_ERROR;
915 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT);
916 return SQLITE_OK;
919 static int sqlcipher_codec_ctx_set_kdf_salt(codec_ctx *ctx, unsigned char *salt, int size) {
920 if(size >= ctx->kdf_salt_sz) {
921 memcpy(ctx->kdf_salt, salt, ctx->kdf_salt_sz);
922 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT);
923 return SQLITE_OK;
925 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_kdf_salt: attempt to set salt of incorrect size %d", size);
926 return SQLITE_ERROR;
929 static int sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx, void** salt) {
930 int rc = SQLITE_OK;
931 if(!SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT)) {
932 if((rc = sqlcipher_codec_ctx_init_kdf_salt(ctx)) != SQLITE_OK) {
933 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_get_kdf_salt: error %d from sqlcipher_codec_ctx_init_kdf_salt", rc);
936 *salt = ctx->kdf_salt;
938 return rc;
941 static int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) {
942 if(!((size != 0) && ((size & (size - 1)) == 0)) || size < 512 || size > 65536) {
943 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "cipher_page_size not a power of 2 and between 512 and 65536 inclusive");
944 return SQLITE_ERROR;
946 /* attempt to free the existing page buffer */
947 if(ctx->buffer) sqlcipher_free(ctx->buffer,ctx->page_sz);
948 ctx->page_sz = size;
950 /* pre-allocate a page buffer of PageSize bytes. This will
951 be used as a persistent buffer for encryption and decryption
952 operations to avoid overhead of multiple memory allocations*/
953 ctx->buffer = sqlcipher_malloc(size);
954 if(ctx->buffer == NULL) return SQLITE_NOMEM;
956 return SQLITE_OK;
959 static int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, const void *zKey, int nKey) {
960 int rc;
961 codec_ctx *ctx;
963 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating context");
965 *iCtx = sqlcipher_malloc(sizeof(codec_ctx));
966 ctx = *iCtx;
968 if(ctx == NULL) return SQLITE_NOMEM;
970 ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */
972 /* allocate space for salt data. Then read the first 16 bytes
973 directly off the database file. This is the salt for the
974 key derivation function. If we get a short read allocate
975 a new random salt value */
976 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating kdf_salt");
977 ctx->kdf_salt_sz = FILE_HEADER_SZ;
978 ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
979 if(ctx->kdf_salt == NULL) return SQLITE_NOMEM;
981 /* allocate space for separate hmac salt data. We want the
982 HMAC derivation salt to be different than the encryption
983 key derivation salt */
984 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating hmac_kdf_salt");
985 ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
986 if(ctx->hmac_kdf_salt == NULL) return SQLITE_NOMEM;
988 /* setup default flags */
989 ctx->flags = default_flags;
991 /* setup the crypto provider */
992 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating provider");
993 ctx->provider = (sqlcipher_provider *) sqlcipher_malloc(sizeof(sqlcipher_provider));
994 if(ctx->provider == NULL) return SQLITE_NOMEM;
996 /* make a copy of the provider to be used for the duration of the context */
997 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: entering SQLCIPHER_MUTEX_PROVIDER");
998 sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
999 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: entered SQLCIPHER_MUTEX_PROVIDER");
1001 memcpy(ctx->provider, default_provider, sizeof(sqlcipher_provider));
1003 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: leaving SQLCIPHER_MUTEX_PROVIDER");
1004 sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
1005 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: left SQLCIPHER_MUTEX_PROVIDER");
1007 if((rc = ctx->provider->ctx_init(&ctx->provider_ctx)) != SQLITE_OK) {
1008 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d returned from ctx_init", rc);
1009 return rc;
1012 ctx->key_sz = ctx->provider->get_key_sz(ctx->provider_ctx);
1013 ctx->iv_sz = ctx->provider->get_iv_sz(ctx->provider_ctx);
1014 ctx->block_sz = ctx->provider->get_block_sz(ctx->provider_ctx);
1016 /* establic the size for a hex-formated key specification, containing the
1017 raw encryption key and the salt used to generate it format. will be x'hexkey...hexsalt'
1018 so oversize by 3 bytes */
1019 ctx->keyspec_sz = ((ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3;
1022 Always overwrite page size and set to the default because the first page of the database
1023 in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in
1024 cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman
1026 if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, default_page_size)) != SQLITE_OK) {
1027 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d returned from sqlcipher_codec_ctx_set_pagesize with %d", rc, default_page_size);
1028 return rc;
1031 /* establish settings for the KDF iterations and fast (HMAC) KDF iterations */
1032 if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, default_kdf_iter)) != SQLITE_OK) {
1033 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting default_kdf_iter %d", rc, default_kdf_iter);
1034 return rc;
1037 if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER)) != SQLITE_OK) {
1038 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting fast_kdf_iter to %d", rc, FAST_PBKDF2_ITER);
1039 return rc;
1042 /* set the default HMAC and KDF algorithms which will determine the reserve size */
1043 if((rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, default_hmac_algorithm)) != SQLITE_OK) {
1044 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting sqlcipher_codec_ctx_set_hmac_algorithm with %d", rc, default_hmac_algorithm);
1045 return rc;
1048 /* Note that use_hmac is a special case that requires recalculation of page size
1049 so we call set_use_hmac to perform setup */
1050 if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, SQLCIPHER_FLAG_GET(default_flags, CIPHER_FLAG_HMAC))) != SQLITE_OK) {
1051 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting use_hmac %d", rc, SQLCIPHER_FLAG_GET(default_flags, CIPHER_FLAG_HMAC));
1052 return rc;
1055 if((rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, default_kdf_algorithm)) != SQLITE_OK) {
1056 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting sqlcipher_codec_ctx_set_kdf_algorithm with %d", rc, default_kdf_algorithm);
1057 return rc;
1060 /* setup the default plaintext header size */
1061 if((rc = sqlcipher_codec_ctx_set_plaintext_header_size(ctx, default_plaintext_header_size)) != SQLITE_OK) {
1062 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting sqlcipher_codec_ctx_set_plaintext_header_size with %d", rc, default_plaintext_header_size);
1063 return rc;
1066 /* initialize the read and write sub-contexts. this must happen after key_sz is established */
1067 if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->read_ctx)) != SQLITE_OK) {
1068 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d initializing read_ctx", rc);
1069 return rc;
1072 if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->write_ctx)) != SQLITE_OK) {
1073 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d initializing write_ctx", rc);
1074 return rc;
1077 /* set the key material on one of the sub cipher contexts and sync them up */
1078 if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) {
1079 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting pass key", rc);
1080 return rc;
1083 if((rc = sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) {
1084 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d copying write_ctx to read_ctx", rc);
1085 return rc;
1088 return SQLITE_OK;
1092 * Free and wipe memory associated with a cipher_ctx, including the allocated
1093 * read_ctx and write_ctx.
1095 static void sqlcipher_codec_ctx_free(codec_ctx **iCtx) {
1096 codec_ctx *ctx = *iCtx;
1097 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "codec_ctx_free: iCtx=%p", iCtx);
1098 if(ctx->kdf_salt) sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz);
1099 if(ctx->hmac_kdf_salt) sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz);
1100 if(ctx->buffer) sqlcipher_free(ctx->buffer, ctx->page_sz);
1102 if(ctx->provider) {
1103 ctx->provider->ctx_free(&ctx->provider_ctx);
1104 sqlcipher_free(ctx->provider, sizeof(sqlcipher_provider));
1107 sqlcipher_cipher_ctx_free(ctx, &ctx->read_ctx);
1108 sqlcipher_cipher_ctx_free(ctx, &ctx->write_ctx);
1109 sqlcipher_free(ctx, sizeof(codec_ctx));
1112 /** convert a 32bit unsigned integer to little endian byte ordering */
1113 static void sqlcipher_put4byte_le(unsigned char *p, u32 v) {
1114 p[0] = (u8)v;
1115 p[1] = (u8)(v>>8);
1116 p[2] = (u8)(v>>16);
1117 p[3] = (u8)(v>>24);
1120 static int sqlcipher_page_hmac(codec_ctx *ctx, cipher_ctx *c_ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) {
1121 unsigned char pgno_raw[sizeof(pgno)];
1122 /* we may convert page number to consistent representation before calculating MAC for
1123 compatibility across big-endian and little-endian platforms.
1125 Note: The public release of sqlcipher 2.0.0 to 2.0.6 had a bug where the bytes of pgno
1126 were used directly in the MAC. SQLCipher convert's to little endian by default to preserve
1127 backwards compatibility on the most popular platforms, but can optionally be configured
1128 to use either big endian or native byte ordering via pragma. */
1130 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_LE_PGNO)) { /* compute hmac using little endian pgno*/
1131 sqlcipher_put4byte_le(pgno_raw, pgno);
1132 } else if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_BE_PGNO)) { /* compute hmac using big endian pgno */
1133 sqlite3Put4byte(pgno_raw, pgno); /* sqlite3Put4byte converts 32bit uint to big endian */
1134 } else { /* use native byte ordering */
1135 memcpy(pgno_raw, &pgno, sizeof(pgno));
1138 /* include the encrypted page data, initialization vector, and page number in HMAC. This will
1139 prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise
1140 valid pages out of order in a database */
1141 return ctx->provider->hmac(
1142 ctx->provider_ctx, ctx->hmac_algorithm, c_ctx->hmac_key,
1143 ctx->key_sz, in,
1144 in_sz, (unsigned char*) &pgno_raw,
1145 sizeof(pgno), out);
1149 * ctx - codec context
1150 * pgno - page number in database
1151 * size - size in bytes of input and output buffers
1152 * mode - 1 to encrypt, 0 to decrypt
1153 * in - pointer to input bytes
1154 * out - pouter to output bytes
1156 static int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
1157 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
1158 unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
1159 int size;
1161 /* calculate some required positions into various buffers */
1162 size = page_sz - ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
1163 iv_out = out + size;
1164 iv_in = in + size;
1166 /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain
1167 random bytes. note, these pointers are only valid when using hmac */
1168 hmac_in = in + size + ctx->iv_sz;
1169 hmac_out = out + size + ctx->iv_sz;
1170 out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */
1172 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: pgno=%d, mode=%d, size=%d", pgno, mode, size);
1173 CODEC_HEXDUMP("sqlcipher_page_cipher: input page data", in, page_sz);
1175 /* the key size should never be zero. If it is, error out. */
1176 if(ctx->key_sz == 0) {
1177 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: error possible context corruption, key_sz is zero for pgno=%d", pgno);
1178 goto error;
1181 if(mode == CIPHER_ENCRYPT) {
1182 /* start at front of the reserve block, write random data to the end */
1183 if(ctx->provider->random(ctx->provider_ctx, iv_out, ctx->reserve_sz) != SQLITE_OK) goto error;
1184 } else { /* CIPHER_DECRYPT */
1185 memcpy(iv_out, iv_in, ctx->iv_sz); /* copy the iv from the input to output buffer */
1188 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT)) {
1189 if(sqlcipher_page_hmac(ctx, c_ctx, pgno, in, size + ctx->iv_sz, hmac_out) != SQLITE_OK) {
1190 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: hmac operation on decrypt failed for pgno=%d", pgno);
1191 goto error;
1194 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: comparing hmac on in=%p out=%p hmac_sz=%d", hmac_in, hmac_out, ctx->hmac_sz);
1195 if(sqlcipher_memcmp(hmac_in, hmac_out, ctx->hmac_sz) != 0) { /* the hmac check failed */
1196 if(sqlite3BtreeGetAutoVacuum(ctx->pBt) != BTREE_AUTOVACUUM_NONE && sqlcipher_ismemset(in, 0, page_sz) == 0) {
1197 /* first check if the entire contents of the page is zeros. If so, this page
1198 resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these
1199 short read failures must be ignored for autovaccum mode to work so wipe the output buffer
1200 and return SQLITE_OK to skip the decryption step. */
1201 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: zeroed page (short read) for pgno %d with autovacuum enabled", pgno);
1202 sqlcipher_memset(out, 0, page_sz);
1203 return SQLITE_OK;
1204 } else {
1205 /* if the page memory is not all zeros, it means the there was data and a hmac on the page.
1206 since the check failed, the page was either tampered with or corrupted. wipe the output buffer,
1207 and return SQLITE_ERROR to the caller */
1208 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: hmac check failed for pgno=%d", pgno);
1209 goto error;
1214 if(ctx->provider->cipher(ctx->provider_ctx, mode, c_ctx->key, ctx->key_sz, iv_out, in, size, out) != SQLITE_OK) {
1215 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: cipher operation mode=%d failed for pgno=%d", mode, pgno);
1216 goto error;
1219 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) {
1220 if(sqlcipher_page_hmac(ctx, c_ctx, pgno, out_start, size + ctx->iv_sz, hmac_out) != SQLITE_OK) {
1221 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: hmac operation on encrypt failed for pgno=%d", pgno);
1222 goto error;
1226 CODEC_HEXDUMP("sqlcipher_page_cipher: output page data", out_start, page_sz);
1228 return SQLITE_OK;
1229 error:
1230 sqlcipher_memset(out, 0, page_sz);
1231 return SQLITE_ERROR;
1235 * Derive an encryption key for a cipher contex key based on the raw password.
1237 * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
1238 * the key (i.e 64 hex chars for a 256 bit key) then the key data will be used directly.
1240 * Else, if the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
1241 * the key and the salt (i.e 92 hex chars for a 256 bit key and 16 byte salt) then it will be unpacked
1242 * as the key followed by the salt.
1244 * Otherwise, a key data will be derived using PBKDF2
1246 * returns SQLITE_OK if initialization was successful
1247 * returns SQLITE_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0)
1249 static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
1250 int rc;
1251 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: ctx->kdf_salt_sz=%d ctx->kdf_iter=%d ctx->fast_kdf_iter=%d ctx->key_sz=%d",
1252 ctx->kdf_salt_sz, ctx->kdf_iter, ctx->fast_kdf_iter, ctx->key_sz);
1254 if(c_ctx->pass && c_ctx->pass_sz) { /* if key material is present on the context for derivation */
1256 /* if necessary, initialize the salt from the header or random source */
1257 if(!SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT)) {
1258 if((rc = sqlcipher_codec_ctx_init_kdf_salt(ctx)) != SQLITE_OK) {
1259 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error %d from sqlcipher_codec_ctx_init_kdf_salt", rc);
1260 return rc;
1264 if (c_ctx->pass_sz == ((ctx->key_sz * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, ctx->key_sz * 2)) {
1265 int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */
1266 const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
1267 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: using raw key from hex");
1268 cipher_hex2bin(z, n, c_ctx->key);
1269 } else if (c_ctx->pass_sz == (((ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, (ctx->key_sz + ctx->kdf_salt_sz) * 2)) {
1270 const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
1271 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: using raw key from hex");
1272 cipher_hex2bin(z, (ctx->key_sz * 2), c_ctx->key);
1273 cipher_hex2bin(z + (ctx->key_sz * 2), (ctx->kdf_salt_sz * 2), ctx->kdf_salt);
1274 } else {
1275 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: deriving key using full PBKDF2 with %d iterations", ctx->kdf_iter);
1276 if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->pass, c_ctx->pass_sz,
1277 ctx->kdf_salt, ctx->kdf_salt_sz, ctx->kdf_iter,
1278 ctx->key_sz, c_ctx->key) != SQLITE_OK) {
1279 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error occurred from provider kdf generating encryption key");
1280 return SQLITE_ERROR;
1284 /* set the context "keyspec" containing the hex-formatted key and salt to be used when attaching databases */
1285 if((rc = sqlcipher_cipher_ctx_set_keyspec(ctx, c_ctx, c_ctx->key)) != SQLITE_OK) {
1286 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error %d from sqlcipher_cipher_ctx_set_keyspec", rc);
1287 return rc;
1290 /* if this context is setup to use hmac checks, generate a seperate and different
1291 key for HMAC. In this case, we use the output of the previous KDF as the input to
1292 this KDF run. This ensures a distinct but predictable HMAC key. */
1293 if(ctx->flags & CIPHER_FLAG_HMAC) {
1294 int i;
1296 /* start by copying the kdf key into the hmac salt slot
1297 then XOR it with the fixed hmac salt defined at compile time
1298 this ensures that the salt passed in to derive the hmac key, while
1299 easy to derive and publically known, is not the same as the salt used
1300 to generate the encryption key */
1301 memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz);
1302 for(i = 0; i < ctx->kdf_salt_sz; i++) {
1303 ctx->hmac_kdf_salt[i] ^= hmac_salt_mask;
1306 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "cipher_ctx_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations",
1307 ctx->fast_kdf_iter);
1310 if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->key, ctx->key_sz,
1311 ctx->hmac_kdf_salt, ctx->kdf_salt_sz, ctx->fast_kdf_iter,
1312 ctx->key_sz, c_ctx->hmac_key) != SQLITE_OK) {
1313 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error occurred from provider kdf generating HMAC key");
1314 return SQLITE_ERROR;
1318 c_ctx->derive_key = 0;
1319 return SQLITE_OK;
1321 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: key material is not present on the context for key derivation");
1322 return SQLITE_ERROR;
1325 static int sqlcipher_codec_key_derive(codec_ctx *ctx) {
1326 /* derive key on first use if necessary */
1327 if(ctx->read_ctx->derive_key) {
1328 if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLITE_OK) {
1329 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_key_derive: error occurred deriving read_ctx key");
1330 return SQLITE_ERROR;
1334 if(ctx->write_ctx->derive_key) {
1335 if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) {
1336 /* the relevant parameters are the same, just copy read key */
1337 if(sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) {
1338 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_key_derive: error occurred copying read_ctx to write_ctx");
1339 return SQLITE_ERROR;
1341 } else {
1342 if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLITE_OK) {
1343 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_key_derive: error occurred deriving write_ctx key");
1344 return SQLITE_ERROR;
1349 /* wipe and free passphrase after key derivation */
1350 if(ctx->store_pass != 1) {
1351 sqlcipher_cipher_ctx_set_pass(ctx->read_ctx, NULL, 0);
1352 sqlcipher_cipher_ctx_set_pass(ctx->write_ctx, NULL, 0);
1355 return SQLITE_OK;
1358 static int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) {
1359 if(source == CIPHER_READ_CTX) {
1360 return sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx);
1361 } else {
1362 return sqlcipher_cipher_ctx_copy(ctx, ctx->read_ctx, ctx->write_ctx);
1366 static int sqlcipher_check_connection(const char *filename, char *key, int key_sz, char *sql, int *user_version, char** journal_mode) {
1367 int rc;
1368 sqlite3 *db = NULL;
1369 sqlite3_stmt *statement = NULL;
1370 char *query_journal_mode = "PRAGMA journal_mode;";
1371 char *query_user_version = "PRAGMA user_version;";
1373 rc = sqlite3_open(filename, &db);
1374 if(rc != SQLITE_OK) goto cleanup;
1376 rc = sqlite3_key(db, key, key_sz);
1377 if(rc != SQLITE_OK) goto cleanup;
1379 rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
1380 if(rc != SQLITE_OK) goto cleanup;
1382 /* start by querying the user version.
1383 this will fail if the key is incorrect */
1384 rc = sqlite3_prepare(db, query_user_version, -1, &statement, NULL);
1385 if(rc != SQLITE_OK) goto cleanup;
1387 rc = sqlite3_step(statement);
1388 if(rc == SQLITE_ROW) {
1389 *user_version = sqlite3_column_int(statement, 0);
1390 } else {
1391 goto cleanup;
1393 sqlite3_finalize(statement);
1395 rc = sqlite3_prepare(db, query_journal_mode, -1, &statement, NULL);
1396 if(rc != SQLITE_OK) goto cleanup;
1398 rc = sqlite3_step(statement);
1399 if(rc == SQLITE_ROW) {
1400 *journal_mode = sqlite3_mprintf("%s", sqlite3_column_text(statement, 0));
1401 } else {
1402 goto cleanup;
1404 rc = SQLITE_OK;
1405 /* cleanup will finalize open statement */
1407 cleanup:
1408 if(statement) sqlite3_finalize(statement);
1409 if(db) sqlite3_close(db);
1410 return rc;
1413 static int sqlcipher_codec_ctx_integrity_check(codec_ctx *ctx, Parse *pParse, char *column) {
1414 Pgno page = 1;
1415 int rc = 0;
1416 char *result;
1417 unsigned char *hmac_out = NULL;
1418 sqlite3_file *fd = sqlite3PagerFile(ctx->pBt->pBt->pPager);
1419 i64 file_sz;
1421 Vdbe *v = sqlite3GetVdbe(pParse);
1422 sqlite3VdbeSetNumCols(v, 1);
1423 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, column, SQLITE_STATIC);
1425 if(fd == NULL || fd->pMethods == 0) {
1426 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "database file is undefined", P4_TRANSIENT);
1427 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1428 goto cleanup;
1431 if(!(ctx->flags & CIPHER_FLAG_HMAC)) {
1432 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "HMAC is not enabled, unable to integrity check", P4_TRANSIENT);
1433 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1434 goto cleanup;
1437 if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) {
1438 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "unable to derive keys", P4_TRANSIENT);
1439 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1440 goto cleanup;
1443 sqlite3OsFileSize(fd, &file_sz);
1444 hmac_out = sqlcipher_malloc(ctx->hmac_sz);
1446 for(page = 1; page <= file_sz / ctx->page_sz; page++) {
1447 i64 offset = (page - 1) * ctx->page_sz;
1448 int payload_sz = ctx->page_sz - ctx->reserve_sz + ctx->iv_sz;
1449 int read_sz = ctx->page_sz;
1451 /* skip integrity check on PAGER_SJ_PGNO since it will have no valid content */
1452 if(sqlite3pager_is_sj_pgno(ctx->pBt->pBt->pPager, page)) continue;
1454 if(page==1) {
1455 int page1_offset = ctx->plaintext_header_sz ? ctx->plaintext_header_sz : FILE_HEADER_SZ;
1456 read_sz = read_sz - page1_offset;
1457 payload_sz = payload_sz - page1_offset;
1458 offset += page1_offset;
1461 sqlcipher_memset(ctx->buffer, 0, ctx->page_sz);
1462 sqlcipher_memset(hmac_out, 0, ctx->hmac_sz);
1463 if(sqlite3OsRead(fd, ctx->buffer, read_sz, offset) != SQLITE_OK) {
1464 result = sqlite3_mprintf("error reading %d bytes from file page %d at offset %d", read_sz, page, offset);
1465 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1466 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1467 } else if(sqlcipher_page_hmac(ctx, ctx->read_ctx, page, ctx->buffer, payload_sz, hmac_out) != SQLITE_OK) {
1468 result = sqlite3_mprintf("HMAC operation failed for page %d", page);
1469 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1470 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1471 } else if(sqlcipher_memcmp(ctx->buffer + payload_sz, hmac_out, ctx->hmac_sz) != 0) {
1472 result = sqlite3_mprintf("HMAC verification failed for page %d", page);
1473 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1474 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1478 if(file_sz % ctx->page_sz != 0) {
1479 result = sqlite3_mprintf("page %d has an invalid size of %lld bytes (expected %d bytes)", page, file_sz - ((file_sz / ctx->page_sz) * ctx->page_sz), ctx->page_sz);
1480 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1481 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1484 cleanup:
1485 if(hmac_out != NULL) sqlcipher_free(hmac_out, ctx->hmac_sz);
1486 return SQLITE_OK;
1489 static int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) {
1490 int i, pass_sz, keyspec_sz, nRes, user_version, rc, oflags;
1491 Db *pDb = 0;
1492 sqlite3 *db = ctx->pBt->db;
1493 const char *db_filename = sqlite3_db_filename(db, "main");
1494 char *set_user_version = NULL, *pass = NULL, *attach_command = NULL, *migrated_db_filename = NULL, *keyspec = NULL, *temp = NULL, *journal_mode = NULL, *set_journal_mode = NULL, *pragma_compat = NULL;
1495 Btree *pDest = NULL, *pSrc = NULL;
1496 sqlite3_file *srcfile, *destfile;
1497 #if defined(_WIN32) || defined(SQLITE_OS_WINRT)
1498 LPWSTR w_db_filename = NULL, w_migrated_db_filename = NULL;
1499 int w_db_filename_sz = 0, w_migrated_db_filename_sz = 0;
1500 #endif
1501 pass_sz = keyspec_sz = rc = user_version = 0;
1503 if(!db_filename || sqlite3Strlen30(db_filename) < 1)
1504 goto cleanup; /* exit immediately if this is an in memory database */
1506 /* pull the provided password / key material off the current codec context */
1507 pass_sz = ctx->read_ctx->pass_sz;
1508 pass = sqlcipher_malloc(pass_sz+1);
1509 memset(pass, 0, pass_sz+1);
1510 memcpy(pass, ctx->read_ctx->pass, pass_sz);
1512 /* Version 4 - current, no upgrade required, so exit immediately */
1513 rc = sqlcipher_check_connection(db_filename, pass, pass_sz, "", &user_version, &journal_mode);
1514 if(rc == SQLITE_OK){
1515 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: no upgrade required - exiting");
1516 goto cleanup;
1519 for(i = 3; i > 0; i--) {
1520 pragma_compat = sqlite3_mprintf("PRAGMA cipher_compatibility = %d;", i);
1521 rc = sqlcipher_check_connection(db_filename, pass, pass_sz, pragma_compat, &user_version, &journal_mode);
1522 if(rc == SQLITE_OK) {
1523 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: version %d format found", i);
1524 goto migrate;
1526 if(pragma_compat) sqlcipher_free(pragma_compat, sqlite3Strlen30(pragma_compat));
1527 pragma_compat = NULL;
1530 /* if we exit the loop normally we failed to determine the version, this is an error */
1531 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: unable to determine format version for upgrade: this may indicate custom settings were used ");
1532 goto handle_error;
1534 migrate:
1536 temp = sqlite3_mprintf("%s-migrated", db_filename);
1537 /* overallocate migrated_db_filename, because sqlite3OsOpen will read past the null terminator
1538 * to determine whether the filename was URI formatted */
1539 migrated_db_filename = sqlcipher_malloc(sqlite3Strlen30(temp)+2);
1540 memcpy(migrated_db_filename, temp, sqlite3Strlen30(temp));
1541 sqlcipher_free(temp, sqlite3Strlen30(temp));
1543 attach_command = sqlite3_mprintf("ATTACH DATABASE '%s' as migrate;", migrated_db_filename, pass);
1544 set_user_version = sqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version);
1546 rc = sqlite3_exec(db, pragma_compat, NULL, NULL, NULL);
1547 if(rc != SQLITE_OK){
1548 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: set compatibility mode failed, error code %d", rc);
1549 goto handle_error;
1552 /* force journal mode to DELETE, we will set it back later if different */
1553 rc = sqlite3_exec(db, "PRAGMA journal_mode = delete;", NULL, NULL, NULL);
1554 if(rc != SQLITE_OK){
1555 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: force journal mode DELETE failed, error code %d", rc);
1556 goto handle_error;
1559 rc = sqlite3_exec(db, attach_command, NULL, NULL, NULL);
1560 if(rc != SQLITE_OK){
1561 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: attach failed, error code %d", rc);
1562 goto handle_error;
1565 rc = sqlite3_key_v2(db, "migrate", pass, pass_sz);
1566 if(rc != SQLITE_OK){
1567 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: keying attached database failed, error code %d", rc);
1568 goto handle_error;
1571 rc = sqlite3_exec(db, "SELECT sqlcipher_export('migrate');", NULL, NULL, NULL);
1572 if(rc != SQLITE_OK){
1573 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: sqlcipher_export failed, error code %d", rc);
1574 goto handle_error;
1577 #ifdef SQLCIPHER_TEST
1578 if((cipher_test_flags & TEST_FAIL_MIGRATE) > 0) {
1579 rc = SQLITE_ERROR;
1580 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: simulated migrate failure, error code %d", rc);
1581 goto handle_error;
1583 #endif
1585 rc = sqlite3_exec(db, set_user_version, NULL, NULL, NULL);
1586 if(rc != SQLITE_OK){
1587 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: set user version failed, error code %d", rc);
1588 goto handle_error;
1591 if( !db->autoCommit ){
1592 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: cannot migrate from within a transaction");
1593 goto handle_error;
1595 if( db->nVdbeActive>1 ){
1596 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: cannot migrate - SQL statements in progress");
1597 goto handle_error;
1600 pDest = db->aDb[0].pBt;
1601 pDb = &(db->aDb[db->nDb-1]);
1602 pSrc = pDb->pBt;
1604 nRes = sqlite3BtreeGetRequestedReserve(pSrc);
1605 /* unset the BTS_PAGESIZE_FIXED flag to avoid SQLITE_READONLY */
1606 pDest->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
1607 rc = sqlite3BtreeSetPageSize(pDest, default_page_size, nRes, 0);
1608 if(rc != SQLITE_OK) {
1609 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to set btree page size to %d res %d rc %d", default_page_size, nRes, rc);
1610 goto handle_error;
1613 sqlcipherCodecGetKey(db, db->nDb - 1, (void**)&keyspec, &keyspec_sz);
1614 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_KEY_USED);
1615 sqlcipherCodecAttach(db, 0, keyspec, keyspec_sz);
1617 srcfile = sqlite3PagerFile(pSrc->pBt->pPager);
1618 destfile = sqlite3PagerFile(pDest->pBt->pPager);
1620 sqlite3OsClose(srcfile);
1621 sqlite3OsClose(destfile);
1623 #if defined(_WIN32) || defined(SQLITE_OS_WINRT)
1624 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: performing windows MoveFileExA");
1626 w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, NULL, 0);
1627 w_db_filename = sqlcipher_malloc(w_db_filename_sz * sizeof(wchar_t));
1628 w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, (const LPWSTR) w_db_filename, w_db_filename_sz);
1630 w_migrated_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) migrated_db_filename, -1, NULL, 0);
1631 w_migrated_db_filename = sqlcipher_malloc(w_migrated_db_filename_sz * sizeof(wchar_t));
1632 w_migrated_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) migrated_db_filename, -1, (const LPWSTR) w_migrated_db_filename, w_migrated_db_filename_sz);
1634 if(!MoveFileExW(w_migrated_db_filename, w_db_filename, MOVEFILE_REPLACE_EXISTING)) {
1635 rc = SQLITE_ERROR;
1636 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: error occurred while renaming migration files %d", rc);
1637 goto handle_error;
1639 #else
1640 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: performing POSIX rename");
1641 if ((rc = rename(migrated_db_filename, db_filename)) != 0) {
1642 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: error occurred while renaming migration files %s to %s: %d", migrated_db_filename, db_filename, rc);
1643 goto handle_error;
1645 #endif
1646 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: renamed migration database %s to main database %s: %d", migrated_db_filename, db_filename, rc);
1648 rc = sqlite3OsOpen(db->pVfs, migrated_db_filename, srcfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags);
1649 if(rc != SQLITE_OK) {
1650 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to reopen migration database %s: %d", migrated_db_filename, rc);
1651 goto handle_error;
1654 rc = sqlite3OsOpen(db->pVfs, db_filename, destfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags);
1655 if(rc != SQLITE_OK) {
1656 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to reopen main database %s: %d", db_filename, rc);
1657 goto handle_error;
1660 sqlite3pager_reset(pDest->pBt->pPager);
1661 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: reset pager");
1663 rc = sqlite3_exec(db, "DETACH DATABASE migrate;", NULL, NULL, NULL);
1664 if(rc != SQLITE_OK) {
1665 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: DETACH DATABASE migrate failed: %d", rc);
1668 sqlite3ResetAllSchemasOfConnection(db);
1669 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: reset all schemas");
1671 set_journal_mode = sqlite3_mprintf("PRAGMA journal_mode = %s;", journal_mode);
1672 rc = sqlite3_exec(db, set_journal_mode, NULL, NULL, NULL);
1673 if(rc != SQLITE_OK) {
1674 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to re-set journal mode via %s: %d", set_journal_mode, rc);
1675 goto handle_error;
1678 goto cleanup;
1680 handle_error:
1681 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: an error occurred attempting to migrate the database - last error %d", rc);
1683 cleanup:
1684 if(migrated_db_filename) {
1685 int del_rc = sqlite3OsDelete(db->pVfs, migrated_db_filename, 0);
1686 if(del_rc != SQLITE_OK) {
1687 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to delete migration database %s: %d", migrated_db_filename, del_rc);
1691 if(pass) sqlcipher_free(pass, pass_sz);
1692 if(attach_command) sqlcipher_free(attach_command, sqlite3Strlen30(attach_command));
1693 if(migrated_db_filename) sqlcipher_free(migrated_db_filename, sqlite3Strlen30(migrated_db_filename));
1694 if(set_user_version) sqlcipher_free(set_user_version, sqlite3Strlen30(set_user_version));
1695 if(set_journal_mode) sqlcipher_free(set_journal_mode, sqlite3Strlen30(set_journal_mode));
1696 if(journal_mode) sqlcipher_free(journal_mode, sqlite3Strlen30(journal_mode));
1697 if(pragma_compat) sqlcipher_free(pragma_compat, sqlite3Strlen30(pragma_compat));
1698 #if defined(_WIN32) || defined(SQLITE_OS_WINRT)
1699 if(w_db_filename) sqlcipher_free(w_db_filename, w_db_filename_sz);
1700 if(w_migrated_db_filename) sqlcipher_free(w_migrated_db_filename, w_migrated_db_filename_sz);
1701 #endif
1702 return rc;
1705 static int sqlcipher_codec_add_random(codec_ctx *ctx, const char *zRight, int random_sz){
1706 const char *suffix = &zRight[random_sz-1];
1707 int n = random_sz - 3; /* adjust for leading x' and tailing ' */
1708 if (n > 0 &&
1709 sqlite3StrNICmp((const char *)zRight ,"x'", 2) == 0 &&
1710 sqlite3StrNICmp(suffix, "'", 1) == 0 &&
1711 n % 2 == 0) {
1712 int rc = 0;
1713 int buffer_sz = n / 2;
1714 unsigned char *random;
1715 const unsigned char *z = (const unsigned char *)zRight + 2; /* adjust lead offset of x' */
1716 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_add_random: using raw random blob from hex");
1717 random = sqlcipher_malloc(buffer_sz);
1718 memset(random, 0, buffer_sz);
1719 cipher_hex2bin(z, n, random);
1720 rc = ctx->provider->add_random(ctx->provider_ctx, random, buffer_sz);
1721 sqlcipher_free(random, buffer_sz);
1722 return rc;
1724 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_add_random: attemt to add random with invalid format");
1725 return SQLITE_ERROR;
1728 #if !defined(SQLITE_OMIT_TRACE)
1730 #define SQLCIPHER_PROFILE_FMT "Elapsed time:%.3f ms - %s\n"
1731 #define SQLCIPHER_PROFILE_FMT_OSLOG "Elapsed time:%{public}.3f ms - %{public}s\n"
1733 static int sqlcipher_profile_callback(unsigned int trace, void *file, void *stmt, void *run_time){
1734 FILE *f = (FILE*) file;
1735 double elapsed = (*((sqlite3_uint64*)run_time))/1000000.0;
1736 if(f == NULL) {
1737 #if !defined(SQLCIPHER_OMIT_LOG_DEVICE)
1738 #if defined(__ANDROID__)
1739 __android_log_print(ANDROID_LOG_DEBUG, "sqlcipher", SQLCIPHER_PROFILE_FMT, elapsed, sqlite3_sql((sqlite3_stmt*)stmt));
1740 #elif defined(__APPLE__)
1741 os_log(OS_LOG_DEFAULT, SQLCIPHER_PROFILE_FMT_OSLOG, elapsed, sqlite3_sql((sqlite3_stmt*)stmt));
1742 #endif
1743 #endif
1744 } else {
1745 fprintf(f, SQLCIPHER_PROFILE_FMT, elapsed, sqlite3_sql((sqlite3_stmt*)stmt));
1747 return SQLITE_OK;
1749 #endif
1751 static int sqlcipher_cipher_profile(sqlite3 *db, const char *destination){
1752 #if defined(SQLITE_OMIT_TRACE)
1753 return SQLITE_ERROR;
1754 #else
1755 FILE *f = NULL;
1756 if(sqlite3_stricmp(destination, "off") == 0){
1757 sqlite3_trace_v2(db, 0, NULL, NULL); /* disable tracing */
1758 } else {
1759 if(sqlite3_stricmp(destination, "stdout") == 0){
1760 f = stdout;
1761 }else if(sqlite3_stricmp(destination, "stderr") == 0){
1762 f = stderr;
1763 }else if(sqlite3_stricmp(destination, "logcat") == 0 || sqlite3_stricmp(destination, "device") == 0){
1764 f = NULL; /* file pointer will be NULL indicating the device target (i.e. logcat or oslog). We will accept logcat for backwards compatibility */
1765 }else{
1766 #if !defined(SQLCIPHER_PROFILE_USE_FOPEN) && (defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT))
1767 if(fopen_s(&f, destination, "a") != 0) return SQLITE_ERROR;
1768 #else
1769 if((f = fopen(destination, "a")) == 0) return SQLITE_ERROR;
1770 #endif
1772 sqlite3_trace_v2(db, SQLITE_TRACE_PROFILE, sqlcipher_profile_callback, f);
1774 return SQLITE_OK;
1775 #endif
1778 static char *sqlcipher_get_log_level_str(unsigned int level) {
1779 switch(level) {
1780 case SQLCIPHER_LOG_ERROR:
1781 return "ERROR";
1782 case SQLCIPHER_LOG_WARN:
1783 return "WARN";
1784 case SQLCIPHER_LOG_INFO:
1785 return "INFO";
1786 case SQLCIPHER_LOG_DEBUG:
1787 return "DEBUG";
1788 case SQLCIPHER_LOG_TRACE:
1789 return "TRACE";
1790 case SQLCIPHER_LOG_ALL:
1791 return "ALL";
1793 return "NONE";
1796 static char *sqlcipher_get_log_source_str(unsigned int source) {
1797 switch(source) {
1798 case SQLCIPHER_LOG_NONE:
1799 return "NONE";
1800 case SQLCIPHER_LOG_CORE:
1801 return "CORE";
1802 case SQLCIPHER_LOG_MEMORY:
1803 return "MEMORY";
1804 case SQLCIPHER_LOG_MUTEX:
1805 return "MUTEX";
1806 case SQLCIPHER_LOG_PROVIDER:
1807 return "PROVIDER";
1809 return "ALL";
1813 #ifndef SQLCIPHER_OMIT_LOG
1814 /* constants from https://github.com/Alexpux/mingw-w64/blob/master/mingw-w64-crt/misc/gettimeofday.c */
1815 #define FILETIME_1970 116444736000000000ull /* seconds between 1/1/1601 and 1/1/1970 */
1816 #define HECTONANOSEC_PER_SEC 10000000ull
1817 #define MAX_LOG_LEN 8192
1818 void sqlcipher_log(unsigned int level, unsigned int source, const char *message, ...) {
1819 va_list params;
1820 va_start(params, message);
1821 char formatted[MAX_LOG_LEN];
1822 char *out = NULL;
1823 int len = 0;
1825 #ifdef CODEC_DEBUG
1826 #if defined(SQLCIPHER_OMIT_LOG_DEVICE)
1827 vfprintf(stderr, message, params);
1828 fprintf(stderr, "\n");
1829 goto end;
1830 #else
1831 #if defined(__ANDROID__)
1832 __android_log_vprint(ANDROID_LOG_DEBUG, "sqlcipher", message, params);
1833 goto end;
1834 #elif defined(__APPLE__)
1835 formatted = sqlite3_vmprintf(message, params);
1836 os_log(OS_LOG_DEFAULT, "%s", formatted);
1837 sqlite3_free(formatted);
1838 goto end;
1839 #else
1840 vfprintf(stderr, message, params);
1841 fprintf(stderr, "\n");
1842 goto end;
1843 #endif
1844 #endif
1845 #endif
1847 level > sqlcipher_log_level /* log level is higher, e.g. level filter is at ERROR but this message is DEBUG */
1848 || (sqlcipher_log_source & source) == 0 /* source filter doesn't match this message source */
1849 || (sqlcipher_log_device == 0 && sqlcipher_log_file == NULL) /* no configured log target */
1851 /* skip logging this message */
1852 goto end;
1855 sqlite3_snprintf(MAX_LOG_LEN, formatted, "%s %s ", sqlcipher_get_log_level_str(level), sqlcipher_get_log_source_str(source));
1856 len = strlen(formatted);
1857 sqlite3_vsnprintf(MAX_LOG_LEN - len, formatted + len, message, params);
1859 #if !defined(SQLCIPHER_OMIT_LOG_DEVICE)
1860 if(sqlcipher_log_device) {
1861 #if defined(__ANDROID__)
1862 __android_log_vprint(ANDROID_LOG_DEBUG, "sqlcipher", formatted);
1863 goto end;
1864 #elif defined(__APPLEformattes__)
1865 os_log(OS_LOG_DEFAULT, "%{public}s", formatted);
1866 goto end;
1867 #endif
1869 #endif
1871 if(sqlcipher_log_file != NULL){
1872 char buffer[24];
1873 struct tm tt;
1874 int ms;
1875 time_t sec;
1876 #ifdef _WIN32
1877 SYSTEMTIME st;
1878 FILETIME ft;
1879 GetSystemTime(&st);
1880 SystemTimeToFileTime(&st, &ft);
1881 sec = (time_t) ((*((sqlite_int64*)&ft) - FILETIME_1970) / HECTONANOSEC_PER_SEC);
1882 ms = st.wMilliseconds;
1883 localtime_s(&tt, &sec);
1884 #else
1885 struct timeval tv;
1886 gettimeofday(&tv, NULL);
1887 sec = tv.tv_sec;
1888 ms = tv.tv_usec/1000.0;
1889 localtime_r(&sec, &tt);
1890 #endif
1891 if(strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tt)) {
1892 fprintf((FILE*)sqlcipher_log_file, "%s.%03d: %s\n", buffer, ms, formatted);
1893 goto end;
1897 end:
1898 va_end(params);
1900 #endif
1902 static int sqlcipher_set_log(const char *destination){
1903 #ifdef SQLCIPHER_OMIT_LOG
1904 return SQLITE_ERROR;
1905 #else
1906 /* close open trace file if it is not stdout or stderr, then
1907 reset trace settings */
1908 if(sqlcipher_log_file != NULL && sqlcipher_log_file != stdout && sqlcipher_log_file != stderr) {
1909 fclose((FILE*)sqlcipher_log_file);
1911 sqlcipher_log_file = NULL;
1912 sqlcipher_log_device = 0;
1914 if(sqlite3_stricmp(destination, "logcat") == 0 || sqlite3_stricmp(destination, "device") == 0){
1915 /* use the appropriate device log. accept logcat for backwards compatibility */
1916 sqlcipher_log_device = 1;
1917 } else if(sqlite3_stricmp(destination, "stdout") == 0){
1918 sqlcipher_log_file = stdout;
1919 }else if(sqlite3_stricmp(destination, "stderr") == 0){
1920 sqlcipher_log_file = stderr;
1921 }else if(sqlite3_stricmp(destination, "off") != 0){
1922 #if !defined(SQLCIPHER_PROFILE_USE_FOPEN) && (defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT))
1923 if(fopen_s(&sqlcipher_log_file, destination, "a") != 0) return SQLITE_ERROR;
1924 #else
1925 if((sqlcipher_log_file = fopen(destination, "a")) == 0) return SQLITE_ERROR;
1926 #endif
1928 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_CORE, "sqlcipher_set_log: set log to %s", destination);
1929 return SQLITE_OK;
1930 #endif
1933 static void sqlcipher_vdbe_return_string(Parse *pParse, const char *zLabel, const char *value, int value_type){
1934 Vdbe *v = sqlite3GetVdbe(pParse);
1935 sqlite3VdbeSetNumCols(v, 1);
1936 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
1937 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, value, value_type);
1938 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1941 #ifdef SQLCIPHER_EXT
1942 #include "sqlcipher_ext.h"
1943 #endif
1945 static int codec_set_btree_to_codec_pagesize(sqlite3 *db, Db *pDb, codec_ctx *ctx) {
1946 int rc;
1948 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize() size=%d reserve=%d", ctx->page_sz, ctx->reserve_sz);
1950 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: entering database mutex %p", db->mutex);
1951 sqlite3_mutex_enter(db->mutex);
1952 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: entered database mutex %p", db->mutex);
1953 db->nextPagesize = ctx->page_sz;
1955 /* before forcing the page size we need to unset the BTS_PAGESIZE_FIXED flag, else
1956 sqliteBtreeSetPageSize will block the change */
1957 pDb->pBt->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
1958 rc = sqlite3BtreeSetPageSize(pDb->pBt, ctx->page_sz, ctx->reserve_sz, 0);
1960 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize returned %d", rc);
1962 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: leaving database mutex %p", db->mutex);
1963 sqlite3_mutex_leave(db->mutex);
1964 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: left database mutex %p", db->mutex);
1966 return rc;
1969 static int codec_set_pass_key(sqlite3* db, int nDb, const void *zKey, int nKey, int for_ctx) {
1970 struct Db *pDb = &db->aDb[nDb];
1971 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "codec_set_pass_key: db=%p nDb=%d for_ctx=%d", db, nDb, for_ctx);
1972 if(pDb->pBt) {
1973 codec_ctx *ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
1975 if(ctx) {
1976 return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx);
1977 } else {
1978 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "codec_set_pass_key: error ocurred fetching codec from pager on db %d", nDb);
1979 return SQLITE_ERROR;
1982 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "codec_set_pass_key: no btree present on db %d", nDb);
1983 return SQLITE_ERROR;
1986 int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) {
1987 struct Db *pDb = &db->aDb[iDb];
1988 codec_ctx *ctx = NULL;
1989 int rc;
1991 if(pDb->pBt) {
1992 ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
1995 if(sqlite3_stricmp(zLeft, "key") !=0 && sqlite3_stricmp(zLeft, "rekey") != 0) {
1996 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_pragma: db=%p iDb=%d pParse=%p zLeft=%s zRight=%s ctx=%p", db, iDb, pParse, zLeft, zRight, ctx);
1999 #ifdef SQLCIPHER_EXT
2000 if(sqlcipher_ext_pragma(db, iDb, pParse, zLeft, zRight)) {
2001 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_pragma: PRAGMA handled by sqlcipher_ext_pragma");
2002 } else
2003 #endif
2004 #ifdef SQLCIPHER_TEST
2005 if( sqlite3_stricmp(zLeft,"cipher_test_on")==0 ){
2006 if( zRight ) {
2007 if(sqlite3_stricmp(zRight, "fail_encrypt")==0) {
2008 SQLCIPHER_FLAG_SET(cipher_test_flags,TEST_FAIL_ENCRYPT);
2009 } else
2010 if(sqlite3_stricmp(zRight, "fail_decrypt")==0) {
2011 SQLCIPHER_FLAG_SET(cipher_test_flags,TEST_FAIL_DECRYPT);
2012 } else
2013 if(sqlite3_stricmp(zRight, "fail_migrate")==0) {
2014 SQLCIPHER_FLAG_SET(cipher_test_flags,TEST_FAIL_MIGRATE);
2017 } else
2018 if( sqlite3_stricmp(zLeft,"cipher_test_off")==0 ){
2019 if( zRight ) {
2020 if(sqlite3_stricmp(zRight, "fail_encrypt")==0) {
2021 SQLCIPHER_FLAG_UNSET(cipher_test_flags,TEST_FAIL_ENCRYPT);
2022 } else
2023 if(sqlite3_stricmp(zRight, "fail_decrypt")==0) {
2024 SQLCIPHER_FLAG_UNSET(cipher_test_flags,TEST_FAIL_DECRYPT);
2025 } else
2026 if(sqlite3_stricmp(zRight, "fail_migrate")==0) {
2027 SQLCIPHER_FLAG_UNSET(cipher_test_flags,TEST_FAIL_MIGRATE);
2030 } else
2031 if( sqlite3_stricmp(zLeft,"cipher_test")==0 ){
2032 char *flags = sqlite3_mprintf("%u", cipher_test_flags);
2033 sqlcipher_vdbe_return_string(pParse, "cipher_test", flags, P4_DYNAMIC);
2034 }else
2035 if( sqlite3_stricmp(zLeft,"cipher_test_rand")==0 ){
2036 if( zRight ) {
2037 int rand = atoi(zRight);
2038 cipher_test_rand = rand;
2039 } else {
2040 char *rand = sqlite3_mprintf("%d", cipher_test_rand);
2041 sqlcipher_vdbe_return_string(pParse, "cipher_test_rand", rand, P4_DYNAMIC);
2043 } else
2044 #endif
2045 if( sqlite3_stricmp(zLeft, "cipher_fips_status")== 0 && !zRight ){
2046 if(ctx) {
2047 char *fips_mode_status = sqlite3_mprintf("%d", ctx->provider->fips_status(ctx->provider_ctx));
2048 sqlcipher_vdbe_return_string(pParse, "cipher_fips_status", fips_mode_status, P4_DYNAMIC);
2050 } else
2051 if( sqlite3_stricmp(zLeft, "cipher_store_pass")==0 && zRight ) {
2052 if(ctx) {
2053 char *deprecation = "PRAGMA cipher_store_pass is deprecated, please remove from use";
2054 ctx->store_pass = sqlite3GetBoolean(zRight, 1);
2055 sqlcipher_vdbe_return_string(pParse, "cipher_store_pass", deprecation, P4_TRANSIENT);
2056 sqlite3_log(SQLITE_WARNING, deprecation);
2058 } else
2059 if( sqlite3_stricmp(zLeft, "cipher_store_pass")==0 && !zRight ) {
2060 if(ctx){
2061 char *store_pass_value = sqlite3_mprintf("%d", ctx->store_pass);
2062 sqlcipher_vdbe_return_string(pParse, "cipher_store_pass", store_pass_value, P4_DYNAMIC);
2065 if( sqlite3_stricmp(zLeft, "cipher_profile")== 0 && zRight ){
2066 char *profile_status = sqlite3_mprintf("%d", sqlcipher_cipher_profile(db, zRight));
2067 sqlcipher_vdbe_return_string(pParse, "cipher_profile", profile_status, P4_DYNAMIC);
2068 } else
2069 if( sqlite3_stricmp(zLeft, "cipher_add_random")==0 && zRight ){
2070 if(ctx) {
2071 char *add_random_status = sqlite3_mprintf("%d", sqlcipher_codec_add_random(ctx, zRight, sqlite3Strlen30(zRight)));
2072 sqlcipher_vdbe_return_string(pParse, "cipher_add_random", add_random_status, P4_DYNAMIC);
2074 } else
2075 if( sqlite3_stricmp(zLeft, "cipher_migrate")==0 && !zRight ){
2076 if(ctx){
2077 int status = sqlcipher_codec_ctx_migrate(ctx);
2078 char *migrate_status = sqlite3_mprintf("%d", status);
2079 sqlcipher_vdbe_return_string(pParse, "cipher_migrate", migrate_status, P4_DYNAMIC);
2080 if(status != SQLITE_OK) {
2081 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_pragma: error occurred during cipher_migrate: %d", status);
2082 sqlcipher_codec_ctx_set_error(ctx, status);
2085 } else
2086 if( sqlite3_stricmp(zLeft, "cipher_provider")==0 && !zRight ){
2087 if(ctx) {
2088 sqlcipher_vdbe_return_string(pParse, "cipher_provider",
2089 ctx->provider->get_provider_name(ctx->provider_ctx), P4_TRANSIENT);
2091 } else
2092 if( sqlite3_stricmp(zLeft, "cipher_provider_version")==0 && !zRight){
2093 if(ctx) {
2094 sqlcipher_vdbe_return_string(pParse, "cipher_provider_version",
2095 ctx->provider->get_provider_version(ctx->provider_ctx), P4_TRANSIENT);
2097 } else
2098 if( sqlite3_stricmp(zLeft, "cipher_version")==0 && !zRight ){
2099 sqlcipher_vdbe_return_string(pParse, "cipher_version", sqlcipher_version(), P4_DYNAMIC);
2100 }else
2101 if( sqlite3_stricmp(zLeft, "cipher")==0 ){
2102 if(ctx) {
2103 if( zRight ) {
2104 const char* message = "PRAGMA cipher is no longer supported.";
2105 sqlcipher_vdbe_return_string(pParse, "cipher", message, P4_TRANSIENT);
2106 sqlite3_log(SQLITE_WARNING, message);
2107 }else {
2108 sqlcipher_vdbe_return_string(pParse, "cipher",
2109 ctx->provider->get_cipher(ctx->provider_ctx), P4_TRANSIENT);
2112 }else
2113 if( sqlite3_stricmp(zLeft, "rekey_cipher")==0 && zRight ){
2114 const char* message = "PRAGMA rekey_cipher is no longer supported.";
2115 sqlcipher_vdbe_return_string(pParse, "rekey_cipher", message, P4_TRANSIENT);
2116 sqlite3_log(SQLITE_WARNING, message);
2117 }else
2118 if( sqlite3_stricmp(zLeft,"cipher_default_kdf_iter")==0 ){
2119 if( zRight ) {
2120 default_kdf_iter = atoi(zRight); /* change default KDF iterations */
2121 } else {
2122 char *kdf_iter = sqlite3_mprintf("%d", default_kdf_iter);
2123 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_iter", kdf_iter, P4_DYNAMIC);
2125 }else
2126 if( sqlite3_stricmp(zLeft, "kdf_iter")==0 ){
2127 if(ctx) {
2128 if( zRight ) {
2129 sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */
2130 } else {
2131 char *kdf_iter = sqlite3_mprintf("%d", ctx->kdf_iter);
2132 sqlcipher_vdbe_return_string(pParse, "kdf_iter", kdf_iter, P4_DYNAMIC);
2135 }else
2136 if( sqlite3_stricmp(zLeft, "fast_kdf_iter")==0){
2137 if(ctx) {
2138 if( zRight ) {
2139 char *deprecation = "PRAGMA fast_kdf_iter is deprecated, please remove from use";
2140 sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */
2141 sqlcipher_vdbe_return_string(pParse, "fast_kdf_iter", deprecation, P4_TRANSIENT);
2142 sqlite3_log(SQLITE_WARNING, deprecation);
2143 } else {
2144 char *fast_kdf_iter = sqlite3_mprintf("%d", ctx->fast_kdf_iter);
2145 sqlcipher_vdbe_return_string(pParse, "fast_kdf_iter", fast_kdf_iter, P4_DYNAMIC);
2148 }else
2149 if( sqlite3_stricmp(zLeft, "rekey_kdf_iter")==0 && zRight ){
2150 const char* message = "PRAGMA rekey_kdf_iter is no longer supported.";
2151 sqlcipher_vdbe_return_string(pParse, "rekey_kdf_iter", message, P4_TRANSIENT);
2152 sqlite3_log(SQLITE_WARNING, message);
2153 }else
2154 if( sqlite3_stricmp(zLeft,"page_size")==0 || sqlite3_stricmp(zLeft,"cipher_page_size")==0 ){
2155 /* PRAGMA cipher_page_size will alter the size of the database pages while ensuring that the
2156 required reserve space is allocated at the end of each page. This will also override the
2157 standard SQLite PRAGMA page_size behavior if a codec context is attached to the database handle.
2158 If PRAGMA page_size is invoked but a codec context is not attached (i.e. dealing with a standard
2159 unencrypted database) then return early and allow the standard PRAGMA page_size logic to apply. */
2160 if(ctx) {
2161 if( zRight ) {
2162 int size = atoi(zRight);
2163 rc = sqlcipher_codec_ctx_set_pagesize(ctx, size);
2164 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2165 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2166 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2167 } else {
2168 char * page_size = sqlite3_mprintf("%d", ctx->page_sz);
2169 sqlcipher_vdbe_return_string(pParse, "cipher_page_size", page_size, P4_DYNAMIC);
2171 } else {
2172 return 0; /* return early so that the PragTyp_PAGE_SIZE case logic in pragma.c will take effect */
2174 }else
2175 if( sqlite3_stricmp(zLeft,"cipher_default_page_size")==0 ){
2176 if( zRight ) {
2177 default_page_size = atoi(zRight);
2178 } else {
2179 char *page_size = sqlite3_mprintf("%d", default_page_size);
2180 sqlcipher_vdbe_return_string(pParse, "cipher_default_page_size", page_size, P4_DYNAMIC);
2182 }else
2183 if( sqlite3_stricmp(zLeft,"cipher_default_use_hmac")==0 ){
2184 if( zRight ) {
2185 sqlcipher_set_default_use_hmac(sqlite3GetBoolean(zRight,1));
2186 } else {
2187 char *default_use_hmac = sqlite3_mprintf("%d", SQLCIPHER_FLAG_GET(default_flags, CIPHER_FLAG_HMAC));
2188 sqlcipher_vdbe_return_string(pParse, "cipher_default_use_hmac", default_use_hmac, P4_DYNAMIC);
2190 }else
2191 if( sqlite3_stricmp(zLeft,"cipher_use_hmac")==0 ){
2192 if(ctx) {
2193 if( zRight ) {
2194 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, sqlite3GetBoolean(zRight,1));
2195 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2196 /* since the use of hmac has changed, the page size may also change */
2197 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2198 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2199 } else {
2200 char *hmac_flag = sqlite3_mprintf("%d", SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC));
2201 sqlcipher_vdbe_return_string(pParse, "cipher_use_hmac", hmac_flag, P4_DYNAMIC);
2204 }else
2205 if( sqlite3_stricmp(zLeft,"cipher_hmac_pgno")==0 ){
2206 if(ctx) {
2207 if(zRight) {
2208 char *deprecation = "PRAGMA cipher_hmac_pgno is deprecated, please remove from use";
2209 /* clear both pgno endian flags */
2210 if(sqlite3_stricmp(zRight, "le") == 0) {
2211 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_BE_PGNO);
2212 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_LE_PGNO);
2213 } else if(sqlite3_stricmp(zRight, "be") == 0) {
2214 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_LE_PGNO);
2215 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_BE_PGNO);
2216 } else if(sqlite3_stricmp(zRight, "native") == 0) {
2217 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_LE_PGNO);
2218 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_BE_PGNO);
2220 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", deprecation, P4_TRANSIENT);
2221 sqlite3_log(SQLITE_WARNING, deprecation);
2223 } else {
2224 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_LE_PGNO)) {
2225 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", "le", P4_TRANSIENT);
2226 } else if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_BE_PGNO)) {
2227 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", "be", P4_TRANSIENT);
2228 } else {
2229 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", "native", P4_TRANSIENT);
2233 }else
2234 if( sqlite3_stricmp(zLeft,"cipher_hmac_salt_mask")==0 ){
2235 if(ctx) {
2236 if(zRight) {
2237 char *deprecation = "PRAGMA cipher_hmac_salt_mask is deprecated, please remove from use";
2238 if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == 5) {
2239 unsigned char mask = 0;
2240 const unsigned char *hex = (const unsigned char *)zRight+2;
2241 cipher_hex2bin(hex,2,&mask);
2242 hmac_salt_mask = mask;
2244 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_salt_mask", deprecation, P4_TRANSIENT);
2245 sqlite3_log(SQLITE_WARNING, deprecation);
2246 } else {
2247 char *mask = sqlite3_mprintf("%02x", hmac_salt_mask);
2248 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_salt_mask", mask, P4_DYNAMIC);
2251 }else
2252 if( sqlite3_stricmp(zLeft,"cipher_plaintext_header_size")==0 ){
2253 if(ctx) {
2254 if( zRight ) {
2255 int size = atoi(zRight);
2256 /* deliberately ignore result code, if size is invalid it will be set to -1
2257 and trip the error later in the codec */
2258 sqlcipher_codec_ctx_set_plaintext_header_size(ctx, size);
2259 } else {
2260 char *size = sqlite3_mprintf("%d", ctx->plaintext_header_sz);
2261 sqlcipher_vdbe_return_string(pParse, "cipher_plaintext_header_size", size, P4_DYNAMIC);
2264 }else
2265 if( sqlite3_stricmp(zLeft,"cipher_default_plaintext_header_size")==0 ){
2266 if( zRight ) {
2267 default_plaintext_header_size = atoi(zRight);
2268 } else {
2269 char *size = sqlite3_mprintf("%d", default_plaintext_header_size);
2270 sqlcipher_vdbe_return_string(pParse, "cipher_default_plaintext_header_size", size, P4_DYNAMIC);
2272 }else
2273 if( sqlite3_stricmp(zLeft,"cipher_salt")==0 ){
2274 if(ctx) {
2275 if(zRight) {
2276 if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == (FILE_HEADER_SZ*2)+3) {
2277 unsigned char *salt = (unsigned char*) sqlite3_malloc(FILE_HEADER_SZ);
2278 const unsigned char *hex = (const unsigned char *)zRight+2;
2279 cipher_hex2bin(hex,FILE_HEADER_SZ*2,salt);
2280 sqlcipher_codec_ctx_set_kdf_salt(ctx, salt, FILE_HEADER_SZ);
2281 sqlite3_free(salt);
2283 } else {
2284 void *salt;
2285 char *hexsalt = (char*) sqlite3_malloc((FILE_HEADER_SZ*2)+1);
2286 if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &salt)) == SQLITE_OK) {
2287 cipher_bin2hex(salt, FILE_HEADER_SZ, hexsalt);
2288 sqlcipher_vdbe_return_string(pParse, "cipher_salt", hexsalt, P4_DYNAMIC);
2289 } else {
2290 sqlite3_free(hexsalt);
2291 sqlcipher_codec_ctx_set_error(ctx, rc);
2295 }else
2296 if( sqlite3_stricmp(zLeft,"cipher_hmac_algorithm")==0 ){
2297 if(ctx) {
2298 if(zRight) {
2299 rc = SQLITE_ERROR;
2300 if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) {
2301 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2302 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) {
2303 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA256);
2304 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) {
2305 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512);
2307 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2308 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2309 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2310 } else {
2311 int algorithm = ctx->hmac_algorithm;
2312 if(ctx->hmac_algorithm == SQLCIPHER_HMAC_SHA1) {
2313 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT);
2314 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
2315 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT);
2316 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
2317 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT);
2321 }else
2322 if( sqlite3_stricmp(zLeft,"cipher_default_hmac_algorithm")==0 ){
2323 if(zRight) {
2324 rc = SQLITE_OK;
2325 if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) {
2326 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2327 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) {
2328 default_hmac_algorithm = SQLCIPHER_HMAC_SHA256;
2329 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) {
2330 default_hmac_algorithm = SQLCIPHER_HMAC_SHA512;
2332 } else {
2333 if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA1) {
2334 sqlcipher_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT);
2335 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA256) {
2336 sqlcipher_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT);
2337 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA512) {
2338 sqlcipher_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT);
2341 }else
2342 if( sqlite3_stricmp(zLeft,"cipher_kdf_algorithm")==0 ){
2343 if(ctx) {
2344 if(zRight) {
2345 rc = SQLITE_ERROR;
2346 if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) {
2347 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2348 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) {
2349 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA256);
2350 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) {
2351 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512);
2353 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2354 } else {
2355 if(ctx->kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2356 sqlcipher_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT);
2357 } else if(ctx->kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2358 sqlcipher_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT);
2359 } else if(ctx->kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2360 sqlcipher_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT);
2364 }else
2365 if( sqlite3_stricmp(zLeft,"cipher_default_kdf_algorithm")==0 ){
2366 if(zRight) {
2367 rc = SQLITE_OK;
2368 if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) {
2369 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2370 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) {
2371 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA256;
2372 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) {
2373 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512;
2375 } else {
2376 if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2377 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT);
2378 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2379 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT);
2380 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2381 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT);
2384 }else
2385 if( sqlite3_stricmp(zLeft,"cipher_compatibility")==0 ){
2386 if(ctx) {
2387 if(zRight) {
2388 int version = atoi(zRight);
2390 switch(version) {
2391 case 1:
2392 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
2393 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2394 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2395 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2396 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2397 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2398 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000);
2399 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2400 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 0);
2401 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2402 break;
2404 case 2:
2405 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
2406 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2407 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2408 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2409 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2410 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2411 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000);
2412 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2413 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
2414 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2415 break;
2417 case 3:
2418 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
2419 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2420 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2421 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2422 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2423 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2424 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 64000);
2425 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2426 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
2427 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2428 break;
2430 default:
2431 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 4096);
2432 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2433 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512);
2434 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2435 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512);
2436 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2437 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 256000);
2438 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2439 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
2440 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2441 break;
2444 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2445 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2448 }else
2449 if( sqlite3_stricmp(zLeft,"cipher_default_compatibility")==0 ){
2450 if(zRight) {
2451 int version = atoi(zRight);
2452 switch(version) {
2453 case 1:
2454 default_page_size = 1024;
2455 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2456 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2457 default_kdf_iter = 4000;
2458 sqlcipher_set_default_use_hmac(0);
2459 break;
2461 case 2:
2462 default_page_size = 1024;
2463 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2464 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2465 default_kdf_iter = 4000;
2466 sqlcipher_set_default_use_hmac(1);
2467 break;
2469 case 3:
2470 default_page_size = 1024;
2471 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2472 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2473 default_kdf_iter = 64000;
2474 sqlcipher_set_default_use_hmac(1);
2475 break;
2477 default:
2478 default_page_size = 4096;
2479 default_hmac_algorithm = SQLCIPHER_HMAC_SHA512;
2480 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512;
2481 default_kdf_iter = 256000;
2482 sqlcipher_set_default_use_hmac(1);
2483 break;
2486 }else
2487 if( sqlite3_stricmp(zLeft,"cipher_memory_security")==0 ){
2488 if( zRight ) {
2489 if(sqlite3GetBoolean(zRight,1)) {
2490 /* memory security can only be enabled, not disabled */
2491 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_set_mem_security: on");
2492 sqlcipher_mem_security_on = 1;
2494 } else {
2495 /* only report that memory security is enabled if pragma cipher_memory_security is ON and
2496 SQLCipher's allocator/deallocator was run at least one time */
2497 int state = sqlcipher_mem_security_on && sqlcipher_mem_executed;
2498 char *on = sqlite3_mprintf("%d", state);
2499 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE,
2500 "sqlcipher_get_mem_security: sqlcipher_mem_security_on = %d, sqlcipher_mem_executed = %d",
2501 sqlcipher_mem_security_on, sqlcipher_mem_executed);
2502 sqlcipher_vdbe_return_string(pParse, "cipher_memory_security", on, P4_DYNAMIC);
2504 }else
2505 if( sqlite3_stricmp(zLeft,"cipher_settings")==0 ){
2506 if(ctx) {
2507 int algorithm;
2508 char *pragma;
2510 pragma = sqlite3_mprintf("PRAGMA kdf_iter = %d;", ctx->kdf_iter);
2511 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2513 pragma = sqlite3_mprintf("PRAGMA cipher_page_size = %d;", ctx->page_sz);
2514 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2516 pragma = sqlite3_mprintf("PRAGMA cipher_use_hmac = %d;", SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC));
2517 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2519 pragma = sqlite3_mprintf("PRAGMA cipher_plaintext_header_size = %d;", ctx->plaintext_header_sz);
2520 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2522 algorithm = ctx->hmac_algorithm;
2523 pragma = NULL;
2524 if(algorithm == SQLCIPHER_HMAC_SHA1) {
2525 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL);
2526 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
2527 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL);
2528 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
2529 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL);
2531 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2533 algorithm = ctx->kdf_algorithm;
2534 pragma = NULL;
2535 if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2536 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL);
2537 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2538 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL);
2539 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2540 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL);
2542 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2545 }else
2546 if( sqlite3_stricmp(zLeft,"cipher_default_settings")==0 ){
2547 char *pragma;
2549 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_iter = %d;", default_kdf_iter);
2550 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2552 pragma = sqlite3_mprintf("PRAGMA cipher_default_page_size = %d;", default_page_size);
2553 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2555 pragma = sqlite3_mprintf("PRAGMA cipher_default_use_hmac = %d;", SQLCIPHER_FLAG_GET(default_flags, CIPHER_FLAG_HMAC));
2556 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2558 pragma = sqlite3_mprintf("PRAGMA cipher_default_plaintext_header_size = %d;", default_plaintext_header_size);
2559 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2561 pragma = NULL;
2562 if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA1) {
2563 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL);
2564 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA256) {
2565 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL);
2566 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA512) {
2567 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL);
2569 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2571 pragma = NULL;
2572 if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2573 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL);
2574 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2575 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL);
2576 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2577 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL);
2579 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2580 }else
2581 if( sqlite3_stricmp(zLeft,"cipher_integrity_check")==0 ){
2582 if(ctx) {
2583 sqlcipher_codec_ctx_integrity_check(ctx, pParse, "cipher_integrity_check");
2585 } else
2586 if( sqlite3_stricmp(zLeft, "cipher_log_level")==0 ){
2587 if(zRight) {
2588 sqlcipher_log_level = SQLCIPHER_LOG_NONE;
2589 if(sqlite3_stricmp(zRight, "ERROR")==0) sqlcipher_log_level = SQLCIPHER_LOG_ERROR;
2590 else if(sqlite3_stricmp(zRight, "WARN" )==0) sqlcipher_log_level = SQLCIPHER_LOG_WARN;
2591 else if(sqlite3_stricmp(zRight, "INFO" )==0) sqlcipher_log_level = SQLCIPHER_LOG_INFO;
2592 else if(sqlite3_stricmp(zRight, "DEBUG")==0) sqlcipher_log_level = SQLCIPHER_LOG_DEBUG;
2593 else if(sqlite3_stricmp(zRight, "TRACE")==0) sqlcipher_log_level = SQLCIPHER_LOG_TRACE;
2595 sqlcipher_vdbe_return_string(pParse, "cipher_log_level", sqlcipher_get_log_level_str(sqlcipher_log_level), P4_TRANSIENT);
2596 } else
2597 if( sqlite3_stricmp(zLeft, "cipher_log_source")==0 ){
2598 if(zRight) {
2599 sqlcipher_log_source = SQLCIPHER_LOG_NONE;
2600 if(sqlite3_stricmp(zRight, "NONE" )==0) sqlcipher_log_source = SQLCIPHER_LOG_NONE;
2601 else if(sqlite3_stricmp(zRight, "ALL" )==0) sqlcipher_log_source = SQLCIPHER_LOG_ALL;
2602 else if(sqlite3_stricmp(zRight, "CORE" )==0) sqlcipher_log_source = SQLCIPHER_LOG_CORE;
2603 else if(sqlite3_stricmp(zRight, "MEMORY" )==0) sqlcipher_log_source = SQLCIPHER_LOG_MEMORY;
2604 else if(sqlite3_stricmp(zRight, "MUTEX" )==0) sqlcipher_log_source = SQLCIPHER_LOG_MUTEX;
2605 else if(sqlite3_stricmp(zRight, "PROVIDER")==0) sqlcipher_log_source = SQLCIPHER_LOG_PROVIDER;
2607 sqlcipher_vdbe_return_string(pParse, "cipher_log_source", sqlcipher_get_log_source_str(sqlcipher_log_source), P4_TRANSIENT);
2608 } else
2609 if( sqlite3_stricmp(zLeft, "cipher_log")== 0 && zRight ){
2610 char *status = sqlite3_mprintf("%d", sqlcipher_set_log(zRight));
2611 sqlcipher_vdbe_return_string(pParse, "cipher_log", status, P4_DYNAMIC);
2612 }else {
2613 return 0;
2615 return 1;
2618 /* these constants are used internally within SQLite's pager.c to differentiate between
2619 operations on the main database or journal pages. This is important in the context
2620 of a rekey operations, where the journal must be written using the original key
2621 material (to allow a transactional rollback), while the new database pages are being
2622 written with the new key material*/
2623 #define CODEC_READ_OP 3
2624 #define CODEC_WRITE_OP 6
2625 #define CODEC_JOURNAL_OP 7
2628 * sqlite3Codec can be called in multiple modes.
2629 * encrypt mode - expected to return a pointer to the
2630 * encrypted data without altering pData.
2631 * decrypt mode - expected to return a pointer to pData, with
2632 * the data decrypted in the input buffer
2634 static void* sqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) {
2635 codec_ctx *ctx = (codec_ctx *) iCtx;
2636 int offset = 0, rc = 0;
2637 unsigned char *pData = (unsigned char *) data;
2638 int cctx = CIPHER_READ_CTX;
2640 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3Codec: pgno=%d, mode=%d, ctx->page_sz=%d", pgno, mode, ctx->page_sz);
2642 #ifdef SQLCIPHER_EXT
2643 if(sqlcipher_license_check(ctx) != SQLITE_OK) return NULL;
2644 #endif
2646 /* call to derive keys if not present yet */
2647 if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) {
2648 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error occurred during key derivation: %d", rc);
2649 sqlcipher_codec_ctx_set_error(ctx, rc);
2650 return NULL;
2653 /* if the plaintext_header_size is negative that means an invalid size was set via
2654 PRAGMA. We can't set the error state on the pager at that point because the pager
2655 may not be open yet. However, this is a fatal error state, so abort the codec */
2656 if(ctx->plaintext_header_sz < 0) {
2657 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error invalid ctx->plaintext_header_sz: %d", ctx->plaintext_header_sz);
2658 sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2659 return NULL;
2662 if(pgno == 1) /* adjust starting pointers in data page for header offset on first page*/
2663 offset = ctx->plaintext_header_sz ? ctx->plaintext_header_sz : FILE_HEADER_SZ;
2666 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3Codec: switch mode=%d offset=%d", mode, offset);
2667 switch(mode) {
2668 case CODEC_READ_OP: /* decrypt */
2669 if(pgno == 1) /* copy initial part of file header or SQLite magic to buffer */
2670 memcpy(ctx->buffer, ctx->plaintext_header_sz ? pData : (void *) SQLITE_FILE_HEADER, offset);
2672 rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_DECRYPT, ctx->page_sz - offset, pData + offset, (unsigned char*)ctx->buffer + offset);
2673 #ifdef SQLCIPHER_TEST
2674 if((cipher_test_flags & TEST_FAIL_DECRYPT) > 0 && sqlcipher_get_test_fail()) {
2675 rc = SQLITE_ERROR;
2676 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlite3Codec: simulating decryption failure for pgno=%d, mode=%d, ctx->page_sz=%d\n", pgno, mode, ctx->page_sz);
2678 #endif
2679 if(rc != SQLITE_OK) {
2680 /* failure to decrypt a page is considered a permanent error and will render the pager unusable
2681 in order to prevent inconsistent data being loaded into page cache */
2682 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error decrypting page %d data: %d", pgno, rc);
2683 sqlcipher_memset((unsigned char*) ctx->buffer+offset, 0, ctx->page_sz-offset);
2684 sqlcipher_codec_ctx_set_error(ctx, rc);
2685 } else {
2686 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_KEY_USED);
2688 memcpy(pData, ctx->buffer, ctx->page_sz); /* copy buffer data back to pData and return */
2689 return pData;
2690 break;
2692 case CODEC_WRITE_OP: /* encrypt database page, operate on write context and fall through to case 7, so the write context is used*/
2693 cctx = CIPHER_WRITE_CTX;
2695 case CODEC_JOURNAL_OP: /* encrypt journal page, operate on read context use to get the original page data from the database */
2696 if(pgno == 1) { /* copy initial part of file header or salt to buffer */
2697 void *kdf_salt = NULL;
2698 /* retrieve the kdf salt */
2699 if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &kdf_salt)) != SQLITE_OK) {
2700 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error retrieving salt: %d", rc);
2701 sqlcipher_codec_ctx_set_error(ctx, rc);
2702 return NULL;
2704 memcpy(ctx->buffer, ctx->plaintext_header_sz ? pData : kdf_salt, offset);
2706 rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_ENCRYPT, ctx->page_sz - offset, pData + offset, (unsigned char*)ctx->buffer + offset);
2707 #ifdef SQLCIPHER_TEST
2708 if((cipher_test_flags & TEST_FAIL_ENCRYPT) > 0 && sqlcipher_get_test_fail()) {
2709 rc = SQLITE_ERROR;
2710 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlite3Codec: simulating encryption failure for pgno=%d, mode=%d, ctx->page_sz=%d\n", pgno, mode, ctx->page_sz);
2712 #endif
2713 if(rc != SQLITE_OK) {
2714 /* failure to encrypt a page is considered a permanent error and will render the pager unusable
2715 in order to prevent corrupted pages from being written to the main databased when using WAL */
2716 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error encrypting page %d data: %d", pgno, rc);
2717 sqlcipher_memset((unsigned char*)ctx->buffer+offset, 0, ctx->page_sz-offset);
2718 sqlcipher_codec_ctx_set_error(ctx, rc);
2719 return NULL;
2721 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_KEY_USED);
2722 return ctx->buffer; /* return persistent buffer data, pData remains intact */
2723 break;
2725 default:
2726 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error unsupported codec mode %d", mode);
2727 sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); /* unsupported mode, set error */
2728 return pData;
2729 break;
2733 static void sqlite3FreeCodecArg(void *pCodecArg) {
2734 codec_ctx *ctx = (codec_ctx *) pCodecArg;
2735 if(pCodecArg == NULL) return;
2736 sqlcipher_codec_ctx_free(&ctx); /* wipe and free allocated memory for the context */
2737 sqlcipher_deactivate(); /* cleanup related structures, OpenSSL etc, when codec is detatched */
2740 int sqlcipherCodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) {
2741 struct Db *pDb = &db->aDb[nDb];
2743 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: db=%p, nDb=%d", db, nDb);
2745 if(nKey && zKey && pDb->pBt) {
2746 int rc;
2747 Pager *pPager = pDb->pBt->pBt->pPager;
2748 sqlite3_file *fd;
2749 codec_ctx *ctx;
2751 ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
2753 if(ctx != NULL && SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_KEY_USED)) {
2754 /* there is already a codec attached to this database, so we should not proceed */
2755 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: no codec attached to db");
2756 return SQLITE_OK;
2759 /* check if the sqlite3_file is open, and if not force handle to NULL */
2760 if((fd = sqlite3PagerFile(pPager))->pMethods == 0) fd = NULL;
2762 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlcipher_activate()");
2763 sqlcipher_activate(); /* perform internal initialization for sqlcipher */
2765 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: entering database mutex %p", db->mutex);
2766 sqlite3_mutex_enter(db->mutex);
2767 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: entered database mutex %p", db->mutex);
2769 #ifdef SQLCIPHER_EXT
2770 if((rc = sqlite3_set_authorizer(db, sqlcipher_license_authorizer, db)) != SQLITE_OK) {
2771 sqlite3_mutex_leave(db->mutex);
2772 return rc;
2774 #endif
2776 /* point the internal codec argument against the contet to be prepared */
2777 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlcipher_codec_ctx_init()");
2778 rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, zKey, nKey);
2780 if(rc != SQLITE_OK) {
2781 /* initialization failed, do not attach potentially corrupted context */
2782 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: context initialization failed, forcing error state with rc=%d", rc);
2783 /* force an error at the pager level, such that even the upstream caller ignores the return code
2784 the pager will be in an error state and will process no further operations */
2785 sqlite3pager_error(pPager, rc);
2786 pDb->pBt->pBt->db->errCode = rc;
2787 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: leaving database mutex %p (early return on rc=%d)", db->mutex, rc);
2788 sqlite3_mutex_leave(db->mutex);
2789 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: left database mutex %p (early return on rc=%d)", db->mutex, rc);
2790 return rc;
2793 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlcipherPagerSetCodec()");
2794 sqlcipherPagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL, sqlite3FreeCodecArg, (void *) ctx);
2796 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling codec_set_btree_to_codec_pagesize()");
2797 codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2799 /* force secure delete. This has the benefit of wiping internal data when deleted
2800 and also ensures that all pages are written to disk (i.e. not skipped by
2801 sqlite3PagerDontWrite optimizations) */
2802 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlite3BtreeSecureDelete()");
2803 sqlite3BtreeSecureDelete(pDb->pBt, 1);
2805 /* if fd is null, then this is an in-memory database and
2806 we dont' want to overwrite the AutoVacuum settings
2807 if not null, then set to the default */
2808 if(fd != NULL) {
2809 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlite3BtreeSetAutoVacuum()");
2810 sqlite3BtreeSetAutoVacuum(pDb->pBt, SQLITE_DEFAULT_AUTOVACUUM);
2812 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: leaving database mutex %p", db->mutex);
2813 sqlite3_mutex_leave(db->mutex);
2814 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: left database mutex %p", db->mutex);
2816 return SQLITE_OK;
2819 int sqlcipher_find_db_index(sqlite3 *db, const char *zDb) {
2820 int db_index;
2821 if(zDb == NULL){
2822 return 0;
2824 for(db_index = 0; db_index < db->nDb; db_index++) {
2825 struct Db *pDb = &db->aDb[db_index];
2826 if(strcmp(pDb->zDbSName, zDb) == 0) {
2827 return db_index;
2830 return 0;
2833 void sqlite3_activate_see(const char* in) {
2834 /* do nothing, security enhancements are always active */
2837 int sqlite3_key(sqlite3 *db, const void *pKey, int nKey) {
2838 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_key: db=%p", db);
2839 return sqlite3_key_v2(db, "main", pKey, nKey);
2842 int sqlite3_key_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) {
2843 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_key_v2: db=%p zDb=%s", db, zDb);
2844 /* attach key if db and pKey are not null and nKey is > 0 */
2845 if(db && pKey && nKey) {
2846 int db_index = sqlcipher_find_db_index(db, zDb);
2847 return sqlcipherCodecAttach(db, db_index, pKey, nKey);
2849 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlite3_key_v2: no key provided");
2850 return SQLITE_ERROR;
2853 int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) {
2854 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey: db=%p", db);
2855 return sqlite3_rekey_v2(db, "main", pKey, nKey);
2858 /* sqlite3_rekey_v2
2859 ** Given a database, this will reencrypt the database using a new key.
2860 ** There is only one possible modes of operation - to encrypt a database
2861 ** that is already encrpyted. If the database is not already encrypted
2862 ** this should do nothing
2863 ** The proposed logic for this function follows:
2864 ** 1. Determine if the database is already encryptped
2865 ** 2. If there is NOT already a key present do nothing
2866 ** 3. If there is a key present, re-encrypt the database with the new key
2868 int sqlite3_rekey_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) {
2869 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: db=%p zDb=%s", db, zDb);
2870 if(db && pKey && nKey) {
2871 int db_index = sqlcipher_find_db_index(db, zDb);
2872 struct Db *pDb = &db->aDb[db_index];
2873 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: database zDb=%p db_index:%d", zDb, db_index);
2874 if(pDb->pBt) {
2875 codec_ctx *ctx;
2876 int rc, page_count;
2877 Pgno pgno;
2878 PgHdr *page;
2879 Pager *pPager = pDb->pBt->pBt->pPager;
2881 ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
2883 if(ctx == NULL) {
2884 /* there was no codec attached to this database, so this should do nothing! */
2885 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: no codec attached to db %s: rekey can't be used on an unencrypted database", zDb);
2886 return SQLITE_MISUSE;
2889 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: entering database mutex %p", db->mutex);
2890 sqlite3_mutex_enter(db->mutex);
2891 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: entered database mutex %p", db->mutex);
2893 codec_set_pass_key(db, db_index, pKey, nKey, CIPHER_WRITE_CTX);
2895 /* do stuff here to rewrite the database
2896 ** 1. Create a transaction on the database
2897 ** 2. Iterate through each page, reading it and then writing it.
2898 ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
2899 ** note: don't deallocate rekey since it may be used in a subsequent iteration
2901 rc = sqlite3BtreeBeginTrans(pDb->pBt, 1, 0); /* begin write transaction */
2902 sqlite3PagerPagecount(pPager, &page_count);
2903 for(pgno = 1; rc == SQLITE_OK && pgno <= (unsigned int)page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
2904 if(!sqlite3pager_is_sj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
2905 rc = sqlite3PagerGet(pPager, pgno, &page, 0);
2906 if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */
2907 rc = sqlite3PagerWrite(page);
2908 if(rc == SQLITE_OK) {
2909 sqlite3PagerUnref(page);
2910 } else {
2911 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: error %d occurred writing page %d", rc, pgno);
2913 } else {
2914 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: error %d occurred reading page %d", rc, pgno);
2919 /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
2920 if(rc == SQLITE_OK) {
2921 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: committing");
2922 rc = sqlite3BtreeCommit(pDb->pBt);
2923 sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX);
2924 } else {
2925 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: rollback");
2926 sqlite3BtreeRollback(pDb->pBt, SQLITE_ABORT_ROLLBACK, 0);
2929 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: leaving database mutex %p", db->mutex);
2930 sqlite3_mutex_leave(db->mutex);
2931 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: left database mutex %p", db->mutex);
2933 return SQLITE_OK;
2935 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: no key provided for db %s: rekey can't be used to decrypt an encrypted database", zDb);
2936 return SQLITE_ERROR;
2939 void sqlcipherCodecGetKey(sqlite3* db, int nDb, void **zKey, int *nKey) {
2940 struct Db *pDb = &db->aDb[nDb];
2941 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecGetKey:db=%p, nDb=%d", db, nDb);
2942 if( pDb->pBt ) {
2943 codec_ctx *ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
2945 if(ctx) {
2946 /* pass back the keyspec from the codec, unless PRAGMA cipher_store_pass
2947 is set or keyspec has not yet been derived, in which case pass
2948 back the password key material */
2949 *zKey = ctx->read_ctx->keyspec;
2950 *nKey = ctx->keyspec_sz;
2951 if(ctx->store_pass == 1 || *zKey == NULL) {
2952 *zKey = ctx->read_ctx->pass;
2953 *nKey = ctx->read_ctx->pass_sz;
2955 } else {
2956 *zKey = NULL;
2957 *nKey = 0;
2963 * Implementation of an "export" function that allows a caller
2964 * to duplicate the main database to an attached database. This is intended
2965 * as a conveneince for users who need to:
2967 * 1. migrate from an non-encrypted database to an encrypted database
2968 * 2. move from an encrypted database to a non-encrypted database
2969 * 3. convert beween the various flavors of encrypted databases.
2971 * This implementation is based heavily on the procedure and code used
2972 * in vacuum.c, but is exposed as a function that allows export to any
2973 * named attached database.
2977 ** Finalize a prepared statement. If there was an error, store the
2978 ** text of the error message in *pzErrMsg. Return the result code.
2980 ** Based on vacuumFinalize from vacuum.c
2982 static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
2983 int rc;
2984 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
2985 if( rc ){
2986 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
2988 return rc;
2992 ** Execute zSql on database db. Return an error code.
2994 ** Based on execSql from vacuum.c
2996 static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
2997 sqlite3_stmt *pStmt;
2998 VVA_ONLY( int rc; )
2999 if( !zSql ){
3000 return SQLITE_NOMEM;
3002 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
3003 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
3004 return sqlite3_errcode(db);
3006 VVA_ONLY( rc = ) sqlite3_step(pStmt);
3007 assert( rc!=SQLITE_ROW );
3008 return sqlcipher_finalize(db, pStmt, pzErrMsg);
3012 ** Execute zSql on database db. The statement returns exactly
3013 ** one column. Execute this as SQL on the same database.
3015 ** Based on execExecSql from vacuum.c
3017 static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
3018 sqlite3_stmt *pStmt;
3019 int rc;
3021 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
3022 if( rc!=SQLITE_OK ) return rc;
3024 while( SQLITE_ROW==sqlite3_step(pStmt) ){
3025 rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
3026 if( rc!=SQLITE_OK ){
3027 sqlcipher_finalize(db, pStmt, pzErrMsg);
3028 return rc;
3032 return sqlcipher_finalize(db, pStmt, pzErrMsg);
3036 * copy database and schema from the main database to an attached database
3038 * Based on sqlite3RunVacuum from vacuum.c
3040 void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) {
3041 sqlite3 *db = sqlite3_context_db_handle(context);
3042 const char* targetDb, *sourceDb;
3043 int targetDb_idx = 0;
3044 u64 saved_flags = db->flags; /* Saved value of the db->flags */
3045 u32 saved_mDbFlags = db->mDbFlags; /* Saved value of the db->mDbFlags */
3046 int saved_nChange = db->nChange; /* Saved value of db->nChange */
3047 int saved_nTotalChange = db->nTotalChange; /* Saved value of db->nTotalChange */
3048 u8 saved_mTrace = db->mTrace; /* Saved value of db->mTrace */
3049 int rc = SQLITE_OK; /* Return code from service routines */
3050 char *zSql = NULL; /* SQL statements */
3051 char *pzErrMsg = NULL;
3053 if(argc != 1 && argc != 2) {
3054 rc = SQLITE_ERROR;
3055 pzErrMsg = sqlite3_mprintf("invalid number of arguments (%d) passed to sqlcipher_export", argc);
3056 goto end_of_export;
3059 if(sqlite3_value_type(argv[0]) == SQLITE_NULL) {
3060 rc = SQLITE_ERROR;
3061 pzErrMsg = sqlite3_mprintf("target database can't be NULL");
3062 goto end_of_export;
3065 targetDb = (const char*) sqlite3_value_text(argv[0]);
3066 sourceDb = "main";
3068 if(argc == 2) {
3069 if(sqlite3_value_type(argv[1]) == SQLITE_NULL) {
3070 rc = SQLITE_ERROR;
3071 pzErrMsg = sqlite3_mprintf("target database can't be NULL");
3072 goto end_of_export;
3074 sourceDb = (char *) sqlite3_value_text(argv[1]);
3078 /* if the name of the target is not main, but the index returned is zero
3079 there is a mismatch and we should not proceed */
3080 targetDb_idx = sqlcipher_find_db_index(db, targetDb);
3081 if(targetDb_idx == 0 && targetDb != NULL && sqlite3_stricmp("main", targetDb) != 0) {
3082 rc = SQLITE_ERROR;
3083 pzErrMsg = sqlite3_mprintf("unknown database %s", targetDb);
3084 goto end_of_export;
3086 db->init.iDb = targetDb_idx;
3088 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
3089 db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
3090 db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_Defensive | SQLITE_CountRows);
3091 db->mTrace = 0;
3093 /* Query the schema of the main database. Create a mirror schema
3094 ** in the temporary database.
3096 zSql = sqlite3_mprintf(
3097 "SELECT sql "
3098 " FROM %s.sqlite_schema WHERE type='table' AND name!='sqlite_sequence'"
3099 " AND rootpage>0"
3100 , sourceDb);
3101 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3102 if( rc!=SQLITE_OK ) goto end_of_export;
3103 sqlite3_free(zSql);
3105 zSql = sqlite3_mprintf(
3106 "SELECT sql "
3107 " FROM %s.sqlite_schema WHERE sql LIKE 'CREATE INDEX %%' "
3108 , sourceDb);
3109 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3110 if( rc!=SQLITE_OK ) goto end_of_export;
3111 sqlite3_free(zSql);
3113 zSql = sqlite3_mprintf(
3114 "SELECT sql "
3115 " FROM %s.sqlite_schema WHERE sql LIKE 'CREATE UNIQUE INDEX %%'"
3116 , sourceDb);
3117 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3118 if( rc!=SQLITE_OK ) goto end_of_export;
3119 sqlite3_free(zSql);
3121 /* Loop through the tables in the main database. For each, do
3122 ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy
3123 ** the contents to the temporary database.
3125 zSql = sqlite3_mprintf(
3126 "SELECT 'INSERT INTO %s.' || quote(name) "
3127 "|| ' SELECT * FROM %s.' || quote(name) || ';'"
3128 "FROM %s.sqlite_schema "
3129 "WHERE type = 'table' AND name!='sqlite_sequence' "
3130 " AND rootpage>0"
3131 , targetDb, sourceDb, sourceDb);
3132 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3133 if( rc!=SQLITE_OK ) goto end_of_export;
3134 sqlite3_free(zSql);
3136 /* Copy over the contents of the sequence table
3138 zSql = sqlite3_mprintf(
3139 "SELECT 'INSERT INTO %s.' || quote(name) "
3140 "|| ' SELECT * FROM %s.' || quote(name) || ';' "
3141 "FROM %s.sqlite_schema WHERE name=='sqlite_sequence';"
3142 , targetDb, sourceDb, targetDb);
3143 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3144 if( rc!=SQLITE_OK ) goto end_of_export;
3145 sqlite3_free(zSql);
3147 /* Copy the triggers, views, and virtual tables from the main database
3148 ** over to the temporary database. None of these objects has any
3149 ** associated storage, so all we have to do is copy their entries
3150 ** from the SQLITE_MASTER table.
3152 zSql = sqlite3_mprintf(
3153 "INSERT INTO %s.sqlite_schema "
3154 " SELECT type, name, tbl_name, rootpage, sql"
3155 " FROM %s.sqlite_schema"
3156 " WHERE type='view' OR type='trigger'"
3157 " OR (type='table' AND rootpage=0)"
3158 , targetDb, sourceDb);
3159 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql);
3160 if( rc!=SQLITE_OK ) goto end_of_export;
3161 sqlite3_free(zSql);
3163 zSql = NULL;
3164 end_of_export:
3165 db->init.iDb = 0;
3166 db->flags = saved_flags;
3167 db->mDbFlags = saved_mDbFlags;
3168 db->nChange = saved_nChange;
3169 db->nTotalChange = saved_nTotalChange;
3170 db->mTrace = saved_mTrace;
3172 if(zSql) sqlite3_free(zSql);
3174 if(rc) {
3175 if(pzErrMsg != NULL) {
3176 sqlite3_result_error(context, pzErrMsg, -1);
3177 sqlite3DbFree(db, pzErrMsg);
3178 } else {
3179 sqlite3_result_error(context, sqlite3ErrStr(rc), -1);
3183 #endif
3184 /* END SQLCIPHER */