Corrects device logging for android and apple using preformatted messages
[sqlcipher.git] / src / sqlcipher.c
blob51e9e94e655ee2b685a33a65118465219ee33aab
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 static volatile unsigned int default_flags = DEFAULT_CIPHER_FLAGS;
246 static volatile unsigned char hmac_salt_mask = HMAC_SALT_MASK;
247 static volatile int default_kdf_iter = PBKDF2_ITER;
248 static volatile int default_page_size = 4096;
249 static volatile int default_plaintext_header_size = 0;
250 static volatile int default_hmac_algorithm = SQLCIPHER_HMAC_SHA512;
251 static volatile int default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512;
252 static volatile int sqlcipher_mem_security_on = 0;
253 static volatile int sqlcipher_mem_executed = 0;
254 static volatile int sqlcipher_mem_initialized = 0;
255 static volatile unsigned int sqlcipher_activate_count = 0;
256 static volatile sqlite3_mem_methods default_mem_methods;
257 static sqlcipher_provider *default_provider = NULL;
259 static sqlite3_mutex* sqlcipher_static_mutex[SQLCIPHER_MUTEX_COUNT];
260 static FILE* sqlcipher_log_file = NULL;
261 static volatile int sqlcipher_log_device = 0;
262 static volatile unsigned int sqlcipher_log_level = SQLCIPHER_LOG_NONE;
263 static volatile unsigned int sqlcipher_log_source = SQLCIPHER_LOG_ALL;
264 static volatile int sqlcipher_log_set = 0;
266 sqlite3_mutex* sqlcipher_mutex(int mutex) {
267 if(mutex < 0 || mutex >= SQLCIPHER_MUTEX_COUNT) return NULL;
268 return sqlcipher_static_mutex[mutex];
271 static void sqlcipher_mlock(void *ptr, sqlite_uint64 sz) {
272 #ifndef OMIT_MEMLOCK
273 #if defined(__unix__) || defined(__APPLE__)
274 int rc;
275 unsigned long pagesize = sysconf(_SC_PAGESIZE);
276 unsigned long offset = (unsigned long) ptr % pagesize;
278 if(ptr == NULL || sz == 0) return;
280 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: calling mlock(%p,%lu); _SC_PAGESIZE=%lu", ptr - offset, sz + offset, pagesize);
281 rc = mlock(ptr - offset, sz + offset);
282 if(rc!=0) {
283 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: mlock() returned %d errno=%d", rc, errno);
284 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: mlock(%p,%lu) returned %d errno=%d", ptr - offset, sz + offset, rc, errno);
286 #elif defined(_WIN32)
287 #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP))
288 int rc;
289 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: calling VirtualLock(%p,%d)", ptr, sz);
290 rc = VirtualLock(ptr, sz);
291 if(rc==0) {
292 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: VirtualLock() returned %d LastError=%d", rc, GetLastError());
293 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_mlock: VirtualLock(%p,%d) returned %d LastError=%d", ptr, sz, rc, GetLastError());
295 #endif
296 #endif
297 #endif
300 static void sqlcipher_munlock(void *ptr, sqlite_uint64 sz) {
301 #ifndef OMIT_MEMLOCK
302 #if defined(__unix__) || defined(__APPLE__)
303 int rc;
304 unsigned long pagesize = sysconf(_SC_PAGESIZE);
305 unsigned long offset = (unsigned long) ptr % pagesize;
307 if(ptr == NULL || sz == 0) return;
309 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: calling munlock(%p,%lu)", ptr - offset, sz + offset);
310 rc = munlock(ptr - offset, sz + offset);
311 if(rc!=0) {
312 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: munlock(%p,%lu) returned %d errno=%d", ptr - offset, sz + offset, rc, errno);
314 #elif defined(_WIN32)
315 #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP))
316 int rc;
318 if(ptr == NULL || sz == 0) return;
320 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: calling VirtualUnlock(%p,%d)", ptr, sz);
321 rc = VirtualUnlock(ptr, sz);
323 /* because memory allocations may be made from the same individual page, it is possible for VirtualUnlock to be called
324 * multiple times for the same page. Subsequent calls will return an error, but this can be safely ignored (i.e. because
325 * the previous call for that page unlocked the memory already). Log an info level event only in that case. */
326 if(!rc) {
327 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_MEMORY, "sqlcipher_munlock: VirtualUnlock(%p,%d) returned %d LastError=%d", ptr, sz, rc, GetLastError());
329 #endif
330 #endif
331 #endif
334 static int sqlcipher_mem_init(void *pAppData) {
335 return default_mem_methods.xInit(pAppData);
337 static void sqlcipher_mem_shutdown(void *pAppData) {
338 default_mem_methods.xShutdown(pAppData);
340 static void *sqlcipher_mem_malloc(int n) {
341 void *ptr = default_mem_methods.xMalloc(n);
342 if(!sqlcipher_mem_executed) sqlcipher_mem_executed = 1;
343 if(sqlcipher_mem_security_on) {
344 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_mem_malloc: calling sqlcipher_mlock(%p,%d)", ptr, n);
345 sqlcipher_mlock(ptr, n);
347 return ptr;
349 static int sqlcipher_mem_size(void *p) {
350 return default_mem_methods.xSize(p);
352 static void sqlcipher_mem_free(void *p) {
353 int sz;
354 if(!sqlcipher_mem_executed) sqlcipher_mem_executed = 1;
355 if(sqlcipher_mem_security_on) {
356 sz = sqlcipher_mem_size(p);
357 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);
358 sqlcipher_memset(p, 0, sz);
359 sqlcipher_munlock(p, sz);
361 default_mem_methods.xFree(p);
363 static void *sqlcipher_mem_realloc(void *p, int n) {
364 void *new = NULL;
365 int orig_sz = 0;
366 if(sqlcipher_mem_security_on) {
367 orig_sz = sqlcipher_mem_size(p);
368 if (n==0) {
369 sqlcipher_mem_free(p);
370 return NULL;
371 } else if (!p) {
372 return sqlcipher_mem_malloc(n);
373 } else if(n <= orig_sz) {
374 return p;
375 } else {
376 new = sqlcipher_mem_malloc(n);
377 if(new) {
378 memcpy(new, p, orig_sz);
379 sqlcipher_mem_free(p);
381 return new;
383 } else {
384 return default_mem_methods.xRealloc(p, n);
388 static int sqlcipher_mem_roundup(int n) {
389 return default_mem_methods.xRoundup(n);
392 static sqlite3_mem_methods sqlcipher_mem_methods = {
393 sqlcipher_mem_malloc,
394 sqlcipher_mem_free,
395 sqlcipher_mem_realloc,
396 sqlcipher_mem_size,
397 sqlcipher_mem_roundup,
398 sqlcipher_mem_init,
399 sqlcipher_mem_shutdown,
403 void sqlcipher_init_memmethods() {
404 if(sqlcipher_mem_initialized) return;
405 if(sqlite3_config(SQLITE_CONFIG_GETMALLOC, &default_mem_methods) != SQLITE_OK ||
406 sqlite3_config(SQLITE_CONFIG_MALLOC, &sqlcipher_mem_methods) != SQLITE_OK) {
407 sqlcipher_mem_security_on = sqlcipher_mem_executed = sqlcipher_mem_initialized = 0;
408 } else {
409 sqlcipher_mem_initialized = 1;
413 int sqlcipher_register_provider(sqlcipher_provider *p) {
414 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: entering SQLCIPHER_MUTEX_PROVIDER");
415 sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
416 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: entered SQLCIPHER_MUTEX_PROVIDER");
418 if(default_provider != NULL && default_provider != p) {
419 /* only free the current registerd provider if it has been initialized
420 and it isn't a pointer to the same provider passed to the function
421 (i.e. protect against a caller calling register twice for the same provider) */
422 sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
424 default_provider = p;
425 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: leaving SQLCIPHER_MUTEX_PROVIDER");
426 sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
427 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_register_provider: left SQLCIPHER_MUTEX_PROVIDER");
429 return SQLITE_OK;
432 /* return a pointer to the currently registered provider. This will
433 allow an application to fetch the current registered provider and
434 make minor changes to it */
435 sqlcipher_provider* sqlcipher_get_provider() {
436 return default_provider;
439 static void sqlcipher_activate() {
440 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: entering static master mutex");
441 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
442 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: entered static master mutex");
444 /* allocate new mutexes */
445 if(sqlcipher_activate_count == 0) {
446 int i;
447 for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) {
448 sqlcipher_static_mutex[i] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
450 #ifndef SQLCIPHER_OMIT_DEFAULT_LOGGING
451 /* when sqlcipher is first activated, set a default log target and level of WARN if the
452 logging settings have not yet been initialized. Use the "device log" for
453 android (logcat) or apple (console). Use stderr on all other platforms. */
454 if(!sqlcipher_log_set) {
456 /* set log level if it is different than the uninitalized default value of NONE */
457 if(sqlcipher_log_level == SQLCIPHER_LOG_NONE) {
458 sqlcipher_log_level = SQLCIPHER_LOG_WARN;
461 /* set the default file or device if neither is already set */
462 if(sqlcipher_log_device == 0 && sqlcipher_log_file == NULL) {
463 #if defined(__ANDROID__) || defined(__APPLE_)
464 sqlcipher_log_device = 1;
465 #else
466 sqlcipher_log_file = stderr;
467 #endif
469 sqlcipher_log_set = 1;
471 #endif
474 /* check to see if there is a provider registered at this point
475 if there no provider registered at this point, register the
476 default provider */
477 if(sqlcipher_get_provider() == NULL) {
478 sqlcipher_provider *p = sqlcipher_malloc(sizeof(sqlcipher_provider));
479 #if defined (SQLCIPHER_CRYPTO_CC)
480 extern int sqlcipher_cc_setup(sqlcipher_provider *p);
481 sqlcipher_cc_setup(p);
482 #elif defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT)
483 extern int sqlcipher_ltc_setup(sqlcipher_provider *p);
484 sqlcipher_ltc_setup(p);
485 #elif defined (SQLCIPHER_CRYPTO_NSS)
486 extern int sqlcipher_nss_setup(sqlcipher_provider *p);
487 sqlcipher_nss_setup(p);
488 #elif defined (SQLCIPHER_CRYPTO_OPENSSL)
489 extern int sqlcipher_openssl_setup(sqlcipher_provider *p);
490 sqlcipher_openssl_setup(p);
491 #elif defined (SQLCIPHER_CRYPTO_OSSL3)
492 extern int sqlcipher_ossl3_setup(sqlcipher_provider *p);
493 sqlcipher_ossl3_setup(p);
494 #else
495 #error "NO DEFAULT SQLCIPHER CRYPTO PROVIDER DEFINED"
496 #endif
497 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_activate: calling sqlcipher_register_provider(%p)", p);
498 sqlcipher_register_provider(p);
499 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_activate: called sqlcipher_register_provider(%p)",p);
502 sqlcipher_activate_count++; /* increment activation count */
504 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: leaving static master mutex");
505 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
506 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_activate: left static master mutex");
509 static void sqlcipher_deactivate() {
510 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entering static master mutex");
511 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
512 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entered static master mutex");
514 sqlcipher_activate_count--;
515 /* if no connections are using sqlcipher, cleanup globals */
516 if(sqlcipher_activate_count < 1) {
517 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entering SQLCIPHER_MUTEX_PROVIDER");
518 sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
519 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: entered SQLCIPHER_MUTEX_PROVIDER");
521 if(default_provider != NULL) {
522 sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
523 default_provider = NULL;
526 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: leaving SQLCIPHER_MUTEX_PROVIDER");
527 sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
528 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: left SQLCIPHER_MUTEX_PROVIDER");
530 /* last connection closed, free mutexes */
531 if(sqlcipher_activate_count == 0) {
532 int i;
533 for(i = 0; i < SQLCIPHER_MUTEX_COUNT; i++) {
534 sqlite3_mutex_free(sqlcipher_static_mutex[i]);
537 sqlcipher_activate_count = 0; /* reset activation count */
540 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: leaving static master mutex");
541 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
542 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_deactivate: left static master mutex");
545 /* constant time memset using volitile to avoid having the memset
546 optimized out by the compiler.
547 Note: As suggested by Joachim Schipper (joachim.schipper@fox-it.com)
549 void* sqlcipher_memset(void *v, unsigned char value, sqlite_uint64 len) {
550 volatile sqlite_uint64 i = 0;
551 volatile unsigned char *a = v;
553 if (v == NULL) return v;
555 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_memset: setting %p[0-%llu]=%d)", a, len, value);
556 for(i = 0; i < len; i++) {
557 a[i] = value;
560 return v;
563 /* constant time memory check tests every position of a memory segement
564 matches a single value (i.e. the memory is all zeros)
565 returns 0 if match, 1 of no match */
566 int sqlcipher_ismemset(const void *v, unsigned char value, sqlite_uint64 len) {
567 const volatile unsigned char *a = v;
568 volatile sqlite_uint64 i = 0, result = 0;
570 for(i = 0; i < len; i++) {
571 result |= a[i] ^ value;
574 return (result != 0);
577 /* constant time memory comparison routine.
578 returns 0 if match, 1 if no match */
579 int sqlcipher_memcmp(const void *v0, const void *v1, int len) {
580 const volatile unsigned char *a0 = v0, *a1 = v1;
581 volatile int i = 0, result = 0;
583 for(i = 0; i < len; i++) {
584 result |= a0[i] ^ a1[i];
587 return (result != 0);
591 * Free and wipe memory. Uses SQLites internal sqlite3_free so that memory
592 * can be countend and memory leak detection works in the test suite.
593 * If ptr is not null memory will be freed.
594 * If sz is greater than zero, the memory will be overwritten with zero before it is freed
595 * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the
596 * memory segment so it can be paged
598 void sqlcipher_free(void *ptr, sqlite_uint64 sz) {
599 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_free: calling sqlcipher_memset(%p,0,%llu)", ptr, sz);
600 sqlcipher_memset(ptr, 0, sz);
601 sqlcipher_munlock(ptr, sz);
602 sqlite3_free(ptr);
606 * allocate memory. Uses sqlite's internall malloc wrapper so memory can be
607 * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK
608 * attempts to lock the memory pages so sensitive information won't be swapped
610 void* sqlcipher_malloc(sqlite_uint64 sz) {
611 void *ptr;
612 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_malloc: calling sqlite3Malloc(%llu)", sz);
613 ptr = sqlite3Malloc(sz);
614 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MEMORY, "sqlcipher_malloc: calling sqlcipher_memset(%p,0,%llu)", ptr, sz);
615 sqlcipher_memset(ptr, 0, sz);
616 sqlcipher_mlock(ptr, sz);
617 return ptr;
620 char* sqlcipher_version() {
621 #ifdef CIPHER_VERSION_QUALIFIER
622 char *version = sqlite3_mprintf("%s %s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_QUALIFIER), CIPHER_XSTR(CIPHER_VERSION_BUILD));
623 #else
624 char *version = sqlite3_mprintf("%s %s", CIPHER_XSTR(CIPHER_VERSION_NUMBER), CIPHER_XSTR(CIPHER_VERSION_BUILD));
625 #endif
626 return version;
630 * Initialize new cipher_ctx struct. This function will allocate memory
631 * for the cipher context and for the key
633 * returns SQLITE_OK if initialization was successful
634 * returns SQLITE_NOMEM if an error occured allocating memory
636 static int sqlcipher_cipher_ctx_init(codec_ctx *ctx, cipher_ctx **iCtx) {
637 cipher_ctx *c_ctx;
638 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_cipher_ctx_init: allocating context");
639 *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx));
640 c_ctx = *iCtx;
641 if(c_ctx == NULL) return SQLITE_NOMEM;
643 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_cipher_ctx_init: allocating key");
644 c_ctx->key = (unsigned char *) sqlcipher_malloc(ctx->key_sz);
646 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_cipher_ctx_init: allocating hmac_key");
647 c_ctx->hmac_key = (unsigned char *) sqlcipher_malloc(ctx->key_sz);
649 if(c_ctx->key == NULL) return SQLITE_NOMEM;
650 if(c_ctx->hmac_key == NULL) return SQLITE_NOMEM;
652 return SQLITE_OK;
656 * Free and wipe memory associated with a cipher_ctx
658 static void sqlcipher_cipher_ctx_free(codec_ctx* ctx, cipher_ctx **iCtx) {
659 cipher_ctx *c_ctx = *iCtx;
660 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "cipher_ctx_free: iCtx=%p", iCtx);
661 if(c_ctx->key) sqlcipher_free(c_ctx->key, ctx->key_sz);
662 if(c_ctx->hmac_key) sqlcipher_free(c_ctx->hmac_key, ctx->key_sz);
663 if(c_ctx->pass) sqlcipher_free(c_ctx->pass, c_ctx->pass_sz);
664 if(c_ctx->keyspec) sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz);
665 sqlcipher_free(c_ctx, sizeof(cipher_ctx));
668 static int sqlcipher_codec_ctx_reserve_setup(codec_ctx *ctx) {
669 int base_reserve = ctx->iv_sz; /* base reserve size will be IV only */
670 int reserve = base_reserve;
672 ctx->hmac_sz = ctx->provider->get_hmac_sz(ctx->provider_ctx, ctx->hmac_algorithm);
674 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC))
675 reserve += ctx->hmac_sz; /* if reserve will include hmac, update that size */
677 /* calculate the amount of reserve needed in even increments of the cipher block size */
678 if(ctx->block_sz > 0) {
679 reserve = ((reserve % ctx->block_sz) == 0) ? reserve :
680 ((reserve / ctx->block_sz) + 1) * ctx->block_sz;
683 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_reserve_setup: base_reserve=%d block_sz=%d md_size=%d reserve=%d",
684 base_reserve, ctx->block_sz, ctx->hmac_sz, reserve);
686 ctx->reserve_sz = reserve;
688 return SQLITE_OK;
692 * Compare one cipher_ctx to another.
694 * returns 0 if all the parameters (except the derived key data) are the same
695 * returns 1 otherwise
697 static int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) {
698 int are_equal = (
699 c1->pass_sz == c2->pass_sz
700 && (
701 c1->pass == c2->pass
702 || !sqlcipher_memcmp((const unsigned char*)c1->pass,
703 (const unsigned char*)c2->pass,
704 c1->pass_sz)
707 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",
708 c1, c2,
709 (c1->pass == NULL || c2->pass == NULL) ?
710 -1 :
711 sqlcipher_memcmp(
712 (const unsigned char*)c1->pass,
713 (const unsigned char*)c2->pass,
714 c1->pass_sz
716 are_equal
719 return !are_equal; /* return 0 if they are the same, 1 otherwise */
723 * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a
724 * fully initialized context, you could copy it to write_ctx and all yet data
725 * and pass information across
727 * returns SQLITE_OK if initialization was successful
728 * returns SQLITE_NOMEM if an error occured allocating memory
730 static int sqlcipher_cipher_ctx_copy(codec_ctx *ctx, cipher_ctx *target, cipher_ctx *source) {
731 void *key = target->key;
732 void *hmac_key = target->hmac_key;
734 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_copy: target=%p, source=%p", target, source);
735 if(target->pass) sqlcipher_free(target->pass, target->pass_sz);
736 if(target->keyspec) sqlcipher_free(target->keyspec, ctx->keyspec_sz);
737 memcpy(target, source, sizeof(cipher_ctx));
739 target->key = key; /* restore pointer to previously allocated key data */
740 memcpy(target->key, source->key, ctx->key_sz);
742 target->hmac_key = hmac_key; /* restore pointer to previously allocated hmac key data */
743 memcpy(target->hmac_key, source->hmac_key, ctx->key_sz);
745 if(source->pass && source->pass_sz) {
746 target->pass = sqlcipher_malloc(source->pass_sz);
747 if(target->pass == NULL) return SQLITE_NOMEM;
748 memcpy(target->pass, source->pass, source->pass_sz);
750 if(source->keyspec) {
751 target->keyspec = sqlcipher_malloc(ctx->keyspec_sz);
752 if(target->keyspec == NULL) return SQLITE_NOMEM;
753 memcpy(target->keyspec, source->keyspec, ctx->keyspec_sz);
755 return SQLITE_OK;
759 * Set the keyspec for the cipher_ctx
761 * returns SQLITE_OK if assignment was successfull
762 * returns SQLITE_NOMEM if an error occured allocating memory
764 static int sqlcipher_cipher_ctx_set_keyspec(codec_ctx *ctx, cipher_ctx *c_ctx, const unsigned char *key) {
765 /* free, zero existing pointers and size */
766 if(c_ctx->keyspec) sqlcipher_free(c_ctx->keyspec, ctx->keyspec_sz);
767 c_ctx->keyspec = NULL;
769 c_ctx->keyspec = sqlcipher_malloc(ctx->keyspec_sz);
770 if(c_ctx->keyspec == NULL) return SQLITE_NOMEM;
772 c_ctx->keyspec[0] = 'x';
773 c_ctx->keyspec[1] = '\'';
774 cipher_bin2hex(key, ctx->key_sz, c_ctx->keyspec + 2);
775 cipher_bin2hex(ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->keyspec + (ctx->key_sz * 2) + 2);
776 c_ctx->keyspec[ctx->keyspec_sz - 1] = '\'';
777 return SQLITE_OK;
780 static void sqlcipher_set_derive_key(codec_ctx *ctx, int derive) {
781 if(ctx->read_ctx != NULL) ctx->read_ctx->derive_key = derive;
782 if(ctx->write_ctx != NULL) ctx->write_ctx->derive_key = derive;
786 * Set the passphrase for the cipher_ctx
788 * returns SQLITE_OK if assignment was successfull
789 * returns SQLITE_NOMEM if an error occured allocating memory
791 static int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) {
792 /* free, zero existing pointers and size */
793 if(ctx->pass) sqlcipher_free(ctx->pass, ctx->pass_sz);
794 ctx->pass = NULL;
795 ctx->pass_sz = 0;
797 if(zKey && nKey) { /* if new password is provided, copy it */
798 ctx->pass_sz = nKey;
799 ctx->pass = sqlcipher_malloc(nKey);
800 if(ctx->pass == NULL) return SQLITE_NOMEM;
801 memcpy(ctx->pass, zKey, nKey);
803 return SQLITE_OK;
806 static int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) {
807 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
808 int rc;
810 if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLITE_OK) {
811 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_pass: error %d from sqlcipher_cipher_ctx_set_pass", rc);
812 return rc;
815 c_ctx->derive_key = 1;
817 if(for_ctx == 2) {
818 if((rc = sqlcipher_cipher_ctx_copy(ctx, for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK) {
819 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_pass: error %d from sqlcipher_cipher_ctx_copy", rc);
820 return rc;
824 return SQLITE_OK;
827 static int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter) {
828 ctx->kdf_iter = kdf_iter;
829 sqlcipher_set_derive_key(ctx, 1);
830 return SQLITE_OK;
833 static int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter) {
834 ctx->fast_kdf_iter = fast_kdf_iter;
835 sqlcipher_set_derive_key(ctx, 1);
836 return SQLITE_OK;
839 /* set the global default flag for HMAC */
840 static void sqlcipher_set_default_use_hmac(int use) {
841 if(use) SQLCIPHER_FLAG_SET(default_flags, CIPHER_FLAG_HMAC);
842 else SQLCIPHER_FLAG_UNSET(default_flags,CIPHER_FLAG_HMAC);
845 /* set the codec flag for whether this individual database should be using hmac */
846 static int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) {
847 if(use) {
848 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_HMAC);
849 } else {
850 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_HMAC);
853 return sqlcipher_codec_ctx_reserve_setup(ctx);
856 /* the length of plaintext header size must be:
857 * 1. greater than or equal to zero
858 * 2. a multiple of the cipher block size
859 * 3. less than the usable size of the first database page
861 static int sqlcipher_codec_ctx_set_plaintext_header_size(codec_ctx *ctx, int size) {
862 if(size >= 0 && ctx->block_sz > 0 && (size % ctx->block_sz) == 0 && size < (ctx->page_sz - ctx->reserve_sz)) {
863 ctx->plaintext_header_sz = size;
864 return SQLITE_OK;
866 ctx->plaintext_header_sz = -1;
867 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_plaintext_header_size: attempt to set invalid plantext_header_size %d", size);
868 return SQLITE_ERROR;
871 static int sqlcipher_codec_ctx_set_hmac_algorithm(codec_ctx *ctx, int algorithm) {
872 ctx->hmac_algorithm = algorithm;
873 return sqlcipher_codec_ctx_reserve_setup(ctx);
876 static int sqlcipher_codec_ctx_set_kdf_algorithm(codec_ctx *ctx, int algorithm) {
877 ctx->kdf_algorithm = algorithm;
878 return SQLITE_OK;
881 static void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) {
882 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_error %d", error);
883 sqlite3pager_error(ctx->pBt->pBt->pPager, error);
884 ctx->pBt->pBt->db->errCode = error;
887 static int sqlcipher_codec_ctx_init_kdf_salt(codec_ctx *ctx) {
888 sqlite3_file *fd = sqlite3PagerFile(ctx->pBt->pBt->pPager);
890 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT)) {
891 return SQLITE_OK; /* don't reload salt when not needed */
894 /* read salt from header, if present, otherwise generate a new random salt */
895 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init_kdf_salt: obtaining salt");
896 if(fd == NULL || fd->pMethods == 0 || sqlite3OsRead(fd, ctx->kdf_salt, ctx->kdf_salt_sz, 0) != SQLITE_OK) {
897 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init_kdf_salt: unable to read salt from file header, generating random");
898 if(ctx->provider->random(ctx->provider_ctx, ctx->kdf_salt, ctx->kdf_salt_sz) != SQLITE_OK) {
899 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init_kdf_salt: error retrieving random bytes from provider");
900 return SQLITE_ERROR;
903 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT);
904 return SQLITE_OK;
907 static int sqlcipher_codec_ctx_set_kdf_salt(codec_ctx *ctx, unsigned char *salt, int size) {
908 if(size >= ctx->kdf_salt_sz) {
909 memcpy(ctx->kdf_salt, salt, ctx->kdf_salt_sz);
910 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT);
911 return SQLITE_OK;
913 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_set_kdf_salt: attempt to set salt of incorrect size %d", size);
914 return SQLITE_ERROR;
917 static int sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx, void** salt) {
918 int rc = SQLITE_OK;
919 if(!SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT)) {
920 if((rc = sqlcipher_codec_ctx_init_kdf_salt(ctx)) != SQLITE_OK) {
921 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_get_kdf_salt: error %d from sqlcipher_codec_ctx_init_kdf_salt", rc);
924 *salt = ctx->kdf_salt;
926 return rc;
929 static int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) {
930 if(!((size != 0) && ((size & (size - 1)) == 0)) || size < 512 || size > 65536) {
931 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "cipher_page_size not a power of 2 and between 512 and 65536 inclusive");
932 return SQLITE_ERROR;
934 /* attempt to free the existing page buffer */
935 if(ctx->buffer) sqlcipher_free(ctx->buffer,ctx->page_sz);
936 ctx->page_sz = size;
938 /* pre-allocate a page buffer of PageSize bytes. This will
939 be used as a persistent buffer for encryption and decryption
940 operations to avoid overhead of multiple memory allocations*/
941 ctx->buffer = sqlcipher_malloc(size);
942 if(ctx->buffer == NULL) return SQLITE_NOMEM;
944 return SQLITE_OK;
947 static int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, const void *zKey, int nKey) {
948 int rc;
949 codec_ctx *ctx;
951 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating context");
953 *iCtx = sqlcipher_malloc(sizeof(codec_ctx));
954 ctx = *iCtx;
956 if(ctx == NULL) return SQLITE_NOMEM;
958 ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */
960 /* allocate space for salt data. Then read the first 16 bytes
961 directly off the database file. This is the salt for the
962 key derivation function. If we get a short read allocate
963 a new random salt value */
964 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating kdf_salt");
965 ctx->kdf_salt_sz = FILE_HEADER_SZ;
966 ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
967 if(ctx->kdf_salt == NULL) return SQLITE_NOMEM;
969 /* allocate space for separate hmac salt data. We want the
970 HMAC derivation salt to be different than the encryption
971 key derivation salt */
972 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating hmac_kdf_salt");
973 ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
974 if(ctx->hmac_kdf_salt == NULL) return SQLITE_NOMEM;
976 /* setup default flags */
977 ctx->flags = default_flags;
979 /* setup the crypto provider */
980 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "sqlcipher_codec_ctx_init: allocating provider");
981 ctx->provider = (sqlcipher_provider *) sqlcipher_malloc(sizeof(sqlcipher_provider));
982 if(ctx->provider == NULL) return SQLITE_NOMEM;
984 /* make a copy of the provider to be used for the duration of the context */
985 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: entering SQLCIPHER_MUTEX_PROVIDER");
986 sqlite3_mutex_enter(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
987 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: entered SQLCIPHER_MUTEX_PROVIDER");
989 memcpy(ctx->provider, default_provider, sizeof(sqlcipher_provider));
991 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: leaving SQLCIPHER_MUTEX_PROVIDER");
992 sqlite3_mutex_leave(sqlcipher_mutex(SQLCIPHER_MUTEX_PROVIDER));
993 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipher_codec_ctx_init: left SQLCIPHER_MUTEX_PROVIDER");
995 if((rc = ctx->provider->ctx_init(&ctx->provider_ctx)) != SQLITE_OK) {
996 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d returned from ctx_init", rc);
997 return rc;
1000 ctx->key_sz = ctx->provider->get_key_sz(ctx->provider_ctx);
1001 ctx->iv_sz = ctx->provider->get_iv_sz(ctx->provider_ctx);
1002 ctx->block_sz = ctx->provider->get_block_sz(ctx->provider_ctx);
1004 /* establic the size for a hex-formated key specification, containing the
1005 raw encryption key and the salt used to generate it format. will be x'hexkey...hexsalt'
1006 so oversize by 3 bytes */
1007 ctx->keyspec_sz = ((ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3;
1010 Always overwrite page size and set to the default because the first page of the database
1011 in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in
1012 cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman
1014 if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, default_page_size)) != SQLITE_OK) {
1015 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);
1016 return rc;
1019 /* establish settings for the KDF iterations and fast (HMAC) KDF iterations */
1020 if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, default_kdf_iter)) != SQLITE_OK) {
1021 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting default_kdf_iter %d", rc, default_kdf_iter);
1022 return rc;
1025 if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER)) != SQLITE_OK) {
1026 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting fast_kdf_iter to %d", rc, FAST_PBKDF2_ITER);
1027 return rc;
1030 /* set the default HMAC and KDF algorithms which will determine the reserve size */
1031 if((rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, default_hmac_algorithm)) != SQLITE_OK) {
1032 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);
1033 return rc;
1036 /* Note that use_hmac is a special case that requires recalculation of page size
1037 so we call set_use_hmac to perform setup */
1038 if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, SQLCIPHER_FLAG_GET(default_flags, CIPHER_FLAG_HMAC))) != SQLITE_OK) {
1039 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));
1040 return rc;
1043 if((rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, default_kdf_algorithm)) != SQLITE_OK) {
1044 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);
1045 return rc;
1048 /* setup the default plaintext header size */
1049 if((rc = sqlcipher_codec_ctx_set_plaintext_header_size(ctx, default_plaintext_header_size)) != SQLITE_OK) {
1050 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);
1051 return rc;
1054 /* initialize the read and write sub-contexts. this must happen after key_sz is established */
1055 if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->read_ctx)) != SQLITE_OK) {
1056 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d initializing read_ctx", rc);
1057 return rc;
1060 if((rc = sqlcipher_cipher_ctx_init(ctx, &ctx->write_ctx)) != SQLITE_OK) {
1061 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d initializing write_ctx", rc);
1062 return rc;
1065 /* set the key material on one of the sub cipher contexts and sync them up */
1066 if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) {
1067 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d setting pass key", rc);
1068 return rc;
1071 if((rc = sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) {
1072 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_init: error %d copying write_ctx to read_ctx", rc);
1073 return rc;
1076 return SQLITE_OK;
1080 * Free and wipe memory associated with a cipher_ctx, including the allocated
1081 * read_ctx and write_ctx.
1083 static void sqlcipher_codec_ctx_free(codec_ctx **iCtx) {
1084 codec_ctx *ctx = *iCtx;
1085 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_MEMORY, "codec_ctx_free: iCtx=%p", iCtx);
1086 if(ctx->kdf_salt) sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz);
1087 if(ctx->hmac_kdf_salt) sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz);
1088 if(ctx->buffer) sqlcipher_free(ctx->buffer, ctx->page_sz);
1090 if(ctx->provider) {
1091 ctx->provider->ctx_free(&ctx->provider_ctx);
1092 sqlcipher_free(ctx->provider, sizeof(sqlcipher_provider));
1095 sqlcipher_cipher_ctx_free(ctx, &ctx->read_ctx);
1096 sqlcipher_cipher_ctx_free(ctx, &ctx->write_ctx);
1097 sqlcipher_free(ctx, sizeof(codec_ctx));
1100 /** convert a 32bit unsigned integer to little endian byte ordering */
1101 static void sqlcipher_put4byte_le(unsigned char *p, u32 v) {
1102 p[0] = (u8)v;
1103 p[1] = (u8)(v>>8);
1104 p[2] = (u8)(v>>16);
1105 p[3] = (u8)(v>>24);
1108 static int sqlcipher_page_hmac(codec_ctx *ctx, cipher_ctx *c_ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) {
1109 unsigned char pgno_raw[sizeof(pgno)];
1110 /* we may convert page number to consistent representation before calculating MAC for
1111 compatibility across big-endian and little-endian platforms.
1113 Note: The public release of sqlcipher 2.0.0 to 2.0.6 had a bug where the bytes of pgno
1114 were used directly in the MAC. SQLCipher convert's to little endian by default to preserve
1115 backwards compatibility on the most popular platforms, but can optionally be configured
1116 to use either big endian or native byte ordering via pragma. */
1118 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_LE_PGNO)) { /* compute hmac using little endian pgno*/
1119 sqlcipher_put4byte_le(pgno_raw, pgno);
1120 } else if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_BE_PGNO)) { /* compute hmac using big endian pgno */
1121 sqlite3Put4byte(pgno_raw, pgno); /* sqlite3Put4byte converts 32bit uint to big endian */
1122 } else { /* use native byte ordering */
1123 memcpy(pgno_raw, &pgno, sizeof(pgno));
1126 /* include the encrypted page data, initialization vector, and page number in HMAC. This will
1127 prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise
1128 valid pages out of order in a database */
1129 return ctx->provider->hmac(
1130 ctx->provider_ctx, ctx->hmac_algorithm, c_ctx->hmac_key,
1131 ctx->key_sz, in,
1132 in_sz, (unsigned char*) &pgno_raw,
1133 sizeof(pgno), out);
1137 * ctx - codec context
1138 * pgno - page number in database
1139 * size - size in bytes of input and output buffers
1140 * mode - 1 to encrypt, 0 to decrypt
1141 * in - pointer to input bytes
1142 * out - pouter to output bytes
1144 static int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
1145 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
1146 unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
1147 int size;
1149 /* calculate some required positions into various buffers */
1150 size = page_sz - ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
1151 iv_out = out + size;
1152 iv_in = in + size;
1154 /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain
1155 random bytes. note, these pointers are only valid when using hmac */
1156 hmac_in = in + size + ctx->iv_sz;
1157 hmac_out = out + size + ctx->iv_sz;
1158 out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */
1160 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: pgno=%d, mode=%d, size=%d", pgno, mode, size);
1161 CODEC_HEXDUMP("sqlcipher_page_cipher: input page data", in, page_sz);
1163 /* the key size should never be zero. If it is, error out. */
1164 if(ctx->key_sz == 0) {
1165 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: error possible context corruption, key_sz is zero for pgno=%d", pgno);
1166 goto error;
1169 if(mode == CIPHER_ENCRYPT) {
1170 /* start at front of the reserve block, write random data to the end */
1171 if(ctx->provider->random(ctx->provider_ctx, iv_out, ctx->reserve_sz) != SQLITE_OK) goto error;
1172 } else { /* CIPHER_DECRYPT */
1173 memcpy(iv_out, iv_in, ctx->iv_sz); /* copy the iv from the input to output buffer */
1176 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT)) {
1177 if(sqlcipher_page_hmac(ctx, c_ctx, pgno, in, size + ctx->iv_sz, hmac_out) != SQLITE_OK) {
1178 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: hmac operation on decrypt failed for pgno=%d", pgno);
1179 goto error;
1182 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);
1183 if(sqlcipher_memcmp(hmac_in, hmac_out, ctx->hmac_sz) != 0) { /* the hmac check failed */
1184 if(sqlite3BtreeGetAutoVacuum(ctx->pBt) != BTREE_AUTOVACUUM_NONE && sqlcipher_ismemset(in, 0, page_sz) == 0) {
1185 /* first check if the entire contents of the page is zeros. If so, this page
1186 resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these
1187 short read failures must be ignored for autovaccum mode to work so wipe the output buffer
1188 and return SQLITE_OK to skip the decryption step. */
1189 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: zeroed page (short read) for pgno %d with autovacuum enabled", pgno);
1190 sqlcipher_memset(out, 0, page_sz);
1191 return SQLITE_OK;
1192 } else {
1193 /* if the page memory is not all zeros, it means the there was data and a hmac on the page.
1194 since the check failed, the page was either tampered with or corrupted. wipe the output buffer,
1195 and return SQLITE_ERROR to the caller */
1196 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: hmac check failed for pgno=%d", pgno);
1197 goto error;
1202 if(ctx->provider->cipher(ctx->provider_ctx, mode, c_ctx->key, ctx->key_sz, iv_out, in, size, out) != SQLITE_OK) {
1203 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: cipher operation mode=%d failed for pgno=%d", mode, pgno);
1204 goto error;
1207 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) {
1208 if(sqlcipher_page_hmac(ctx, c_ctx, pgno, out_start, size + ctx->iv_sz, hmac_out) != SQLITE_OK) {
1209 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_page_cipher: hmac operation on encrypt failed for pgno=%d", pgno);
1210 goto error;
1214 CODEC_HEXDUMP("sqlcipher_page_cipher: output page data", out_start, page_sz);
1216 return SQLITE_OK;
1217 error:
1218 sqlcipher_memset(out, 0, page_sz);
1219 return SQLITE_ERROR;
1223 * Derive an encryption key for a cipher contex key based on the raw password.
1225 * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
1226 * the key (i.e 64 hex chars for a 256 bit key) then the key data will be used directly.
1228 * Else, if the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
1229 * the key and the salt (i.e 92 hex chars for a 256 bit key and 16 byte salt) then it will be unpacked
1230 * as the key followed by the salt.
1232 * Otherwise, a key data will be derived using PBKDF2
1234 * returns SQLITE_OK if initialization was successful
1235 * returns SQLITE_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0)
1237 static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
1238 int rc;
1239 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",
1240 ctx->kdf_salt_sz, ctx->kdf_iter, ctx->fast_kdf_iter, ctx->key_sz);
1242 if(c_ctx->pass && c_ctx->pass_sz) { /* if key material is present on the context for derivation */
1244 /* if necessary, initialize the salt from the header or random source */
1245 if(!SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HAS_KDF_SALT)) {
1246 if((rc = sqlcipher_codec_ctx_init_kdf_salt(ctx)) != SQLITE_OK) {
1247 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error %d from sqlcipher_codec_ctx_init_kdf_salt", rc);
1248 return rc;
1252 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)) {
1253 int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */
1254 const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
1255 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: using raw key from hex");
1256 cipher_hex2bin(z, n, c_ctx->key);
1257 } 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)) {
1258 const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
1259 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: using raw key from hex");
1260 cipher_hex2bin(z, (ctx->key_sz * 2), c_ctx->key);
1261 cipher_hex2bin(z + (ctx->key_sz * 2), (ctx->kdf_salt_sz * 2), ctx->kdf_salt);
1262 } else {
1263 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: deriving key using full PBKDF2 with %d iterations", ctx->kdf_iter);
1264 if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->pass, c_ctx->pass_sz,
1265 ctx->kdf_salt, ctx->kdf_salt_sz, ctx->kdf_iter,
1266 ctx->key_sz, c_ctx->key) != SQLITE_OK) {
1267 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error occurred from provider kdf generating encryption key");
1268 return SQLITE_ERROR;
1272 /* set the context "keyspec" containing the hex-formatted key and salt to be used when attaching databases */
1273 if((rc = sqlcipher_cipher_ctx_set_keyspec(ctx, c_ctx, c_ctx->key)) != SQLITE_OK) {
1274 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error %d from sqlcipher_cipher_ctx_set_keyspec", rc);
1275 return rc;
1278 /* if this context is setup to use hmac checks, generate a seperate and different
1279 key for HMAC. In this case, we use the output of the previous KDF as the input to
1280 this KDF run. This ensures a distinct but predictable HMAC key. */
1281 if(ctx->flags & CIPHER_FLAG_HMAC) {
1282 int i;
1284 /* start by copying the kdf key into the hmac salt slot
1285 then XOR it with the fixed hmac salt defined at compile time
1286 this ensures that the salt passed in to derive the hmac key, while
1287 easy to derive and publically known, is not the same as the salt used
1288 to generate the encryption key */
1289 memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz);
1290 for(i = 0; i < ctx->kdf_salt_sz; i++) {
1291 ctx->hmac_kdf_salt[i] ^= hmac_salt_mask;
1294 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "cipher_ctx_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations",
1295 ctx->fast_kdf_iter);
1298 if(ctx->provider->kdf(ctx->provider_ctx, ctx->kdf_algorithm, c_ctx->key, ctx->key_sz,
1299 ctx->hmac_kdf_salt, ctx->kdf_salt_sz, ctx->fast_kdf_iter,
1300 ctx->key_sz, c_ctx->hmac_key) != SQLITE_OK) {
1301 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: error occurred from provider kdf generating HMAC key");
1302 return SQLITE_ERROR;
1306 c_ctx->derive_key = 0;
1307 return SQLITE_OK;
1309 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_cipher_ctx_key_derive: key material is not present on the context for key derivation");
1310 return SQLITE_ERROR;
1313 static int sqlcipher_codec_key_derive(codec_ctx *ctx) {
1314 /* derive key on first use if necessary */
1315 if(ctx->read_ctx->derive_key) {
1316 if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLITE_OK) {
1317 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_key_derive: error occurred deriving read_ctx key");
1318 return SQLITE_ERROR;
1322 if(ctx->write_ctx->derive_key) {
1323 if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) {
1324 /* the relevant parameters are the same, just copy read key */
1325 if(sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) {
1326 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_key_derive: error occurred copying read_ctx to write_ctx");
1327 return SQLITE_ERROR;
1329 } else {
1330 if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLITE_OK) {
1331 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_key_derive: error occurred deriving write_ctx key");
1332 return SQLITE_ERROR;
1337 /* wipe and free passphrase after key derivation */
1338 if(ctx->store_pass != 1) {
1339 sqlcipher_cipher_ctx_set_pass(ctx->read_ctx, NULL, 0);
1340 sqlcipher_cipher_ctx_set_pass(ctx->write_ctx, NULL, 0);
1343 return SQLITE_OK;
1346 static int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) {
1347 if(source == CIPHER_READ_CTX) {
1348 return sqlcipher_cipher_ctx_copy(ctx, ctx->write_ctx, ctx->read_ctx);
1349 } else {
1350 return sqlcipher_cipher_ctx_copy(ctx, ctx->read_ctx, ctx->write_ctx);
1354 static int sqlcipher_check_connection(const char *filename, char *key, int key_sz, char *sql, int *user_version, char** journal_mode) {
1355 int rc;
1356 sqlite3 *db = NULL;
1357 sqlite3_stmt *statement = NULL;
1358 char *query_journal_mode = "PRAGMA journal_mode;";
1359 char *query_user_version = "PRAGMA user_version;";
1361 rc = sqlite3_open(filename, &db);
1362 if(rc != SQLITE_OK) goto cleanup;
1364 rc = sqlite3_key(db, key, key_sz);
1365 if(rc != SQLITE_OK) goto cleanup;
1367 rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
1368 if(rc != SQLITE_OK) goto cleanup;
1370 /* start by querying the user version.
1371 this will fail if the key is incorrect */
1372 rc = sqlite3_prepare(db, query_user_version, -1, &statement, NULL);
1373 if(rc != SQLITE_OK) goto cleanup;
1375 rc = sqlite3_step(statement);
1376 if(rc == SQLITE_ROW) {
1377 *user_version = sqlite3_column_int(statement, 0);
1378 } else {
1379 goto cleanup;
1381 sqlite3_finalize(statement);
1383 rc = sqlite3_prepare(db, query_journal_mode, -1, &statement, NULL);
1384 if(rc != SQLITE_OK) goto cleanup;
1386 rc = sqlite3_step(statement);
1387 if(rc == SQLITE_ROW) {
1388 *journal_mode = sqlite3_mprintf("%s", sqlite3_column_text(statement, 0));
1389 } else {
1390 goto cleanup;
1392 rc = SQLITE_OK;
1393 /* cleanup will finalize open statement */
1395 cleanup:
1396 if(statement) sqlite3_finalize(statement);
1397 if(db) sqlite3_close(db);
1398 return rc;
1401 static int sqlcipher_codec_ctx_integrity_check(codec_ctx *ctx, Parse *pParse, char *column) {
1402 Pgno page = 1;
1403 int rc = 0;
1404 char *result;
1405 unsigned char *hmac_out = NULL;
1406 sqlite3_file *fd = sqlite3PagerFile(ctx->pBt->pBt->pPager);
1407 i64 file_sz;
1409 Vdbe *v = sqlite3GetVdbe(pParse);
1410 sqlite3VdbeSetNumCols(v, 1);
1411 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, column, SQLITE_STATIC);
1413 if(fd == NULL || fd->pMethods == 0) {
1414 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "database file is undefined", P4_TRANSIENT);
1415 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1416 goto cleanup;
1419 if(!(ctx->flags & CIPHER_FLAG_HMAC)) {
1420 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "HMAC is not enabled, unable to integrity check", P4_TRANSIENT);
1421 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1422 goto cleanup;
1425 if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) {
1426 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, "unable to derive keys", P4_TRANSIENT);
1427 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1428 goto cleanup;
1431 sqlite3OsFileSize(fd, &file_sz);
1432 hmac_out = sqlcipher_malloc(ctx->hmac_sz);
1434 for(page = 1; page <= file_sz / ctx->page_sz; page++) {
1435 i64 offset = (page - 1) * ctx->page_sz;
1436 int payload_sz = ctx->page_sz - ctx->reserve_sz + ctx->iv_sz;
1437 int read_sz = ctx->page_sz;
1439 /* skip integrity check on PAGER_SJ_PGNO since it will have no valid content */
1440 if(sqlite3pager_is_sj_pgno(ctx->pBt->pBt->pPager, page)) continue;
1442 if(page==1) {
1443 int page1_offset = ctx->plaintext_header_sz ? ctx->plaintext_header_sz : FILE_HEADER_SZ;
1444 read_sz = read_sz - page1_offset;
1445 payload_sz = payload_sz - page1_offset;
1446 offset += page1_offset;
1449 sqlcipher_memset(ctx->buffer, 0, ctx->page_sz);
1450 sqlcipher_memset(hmac_out, 0, ctx->hmac_sz);
1451 if(sqlite3OsRead(fd, ctx->buffer, read_sz, offset) != SQLITE_OK) {
1452 result = sqlite3_mprintf("error reading %d bytes from file page %d at offset %d", read_sz, page, offset);
1453 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1454 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1455 } else if(sqlcipher_page_hmac(ctx, ctx->read_ctx, page, ctx->buffer, payload_sz, hmac_out) != SQLITE_OK) {
1456 result = sqlite3_mprintf("HMAC operation failed for page %d", page);
1457 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1458 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1459 } else if(sqlcipher_memcmp(ctx->buffer + payload_sz, hmac_out, ctx->hmac_sz) != 0) {
1460 result = sqlite3_mprintf("HMAC verification failed for page %d", page);
1461 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1462 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1466 if(file_sz % ctx->page_sz != 0) {
1467 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);
1468 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, result, P4_DYNAMIC);
1469 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1472 cleanup:
1473 if(hmac_out != NULL) sqlcipher_free(hmac_out, ctx->hmac_sz);
1474 return SQLITE_OK;
1477 static int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) {
1478 int i, pass_sz, keyspec_sz, nRes, user_version, rc, oflags;
1479 Db *pDb = 0;
1480 sqlite3 *db = ctx->pBt->db;
1481 const char *db_filename = sqlite3_db_filename(db, "main");
1482 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;
1483 Btree *pDest = NULL, *pSrc = NULL;
1484 sqlite3_file *srcfile, *destfile;
1485 #if defined(_WIN32) || defined(SQLITE_OS_WINRT)
1486 LPWSTR w_db_filename = NULL, w_migrated_db_filename = NULL;
1487 int w_db_filename_sz = 0, w_migrated_db_filename_sz = 0;
1488 #endif
1489 pass_sz = keyspec_sz = rc = user_version = 0;
1491 if(!db_filename || sqlite3Strlen30(db_filename) < 1)
1492 goto cleanup; /* exit immediately if this is an in memory database */
1494 /* pull the provided password / key material off the current codec context */
1495 pass_sz = ctx->read_ctx->pass_sz;
1496 pass = sqlcipher_malloc(pass_sz+1);
1497 memset(pass, 0, pass_sz+1);
1498 memcpy(pass, ctx->read_ctx->pass, pass_sz);
1500 /* Version 4 - current, no upgrade required, so exit immediately */
1501 rc = sqlcipher_check_connection(db_filename, pass, pass_sz, "", &user_version, &journal_mode);
1502 if(rc == SQLITE_OK){
1503 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: no upgrade required - exiting");
1504 goto cleanup;
1507 for(i = 3; i > 0; i--) {
1508 pragma_compat = sqlite3_mprintf("PRAGMA cipher_compatibility = %d;", i);
1509 rc = sqlcipher_check_connection(db_filename, pass, pass_sz, pragma_compat, &user_version, &journal_mode);
1510 if(rc == SQLITE_OK) {
1511 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: version %d format found", i);
1512 goto migrate;
1514 if(pragma_compat) sqlcipher_free(pragma_compat, sqlite3Strlen30(pragma_compat));
1515 pragma_compat = NULL;
1518 /* if we exit the loop normally we failed to determine the version, this is an error */
1519 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 ");
1520 goto handle_error;
1522 migrate:
1524 temp = sqlite3_mprintf("%s-migrated", db_filename);
1525 /* overallocate migrated_db_filename, because sqlite3OsOpen will read past the null terminator
1526 * to determine whether the filename was URI formatted */
1527 migrated_db_filename = sqlcipher_malloc(sqlite3Strlen30(temp)+2);
1528 memcpy(migrated_db_filename, temp, sqlite3Strlen30(temp));
1529 sqlcipher_free(temp, sqlite3Strlen30(temp));
1531 attach_command = sqlite3_mprintf("ATTACH DATABASE '%s' as migrate;", migrated_db_filename, pass);
1532 set_user_version = sqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version);
1534 rc = sqlite3_exec(db, pragma_compat, NULL, NULL, NULL);
1535 if(rc != SQLITE_OK){
1536 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: set compatibility mode failed, error code %d", rc);
1537 goto handle_error;
1540 /* force journal mode to DELETE, we will set it back later if different */
1541 rc = sqlite3_exec(db, "PRAGMA journal_mode = delete;", NULL, NULL, NULL);
1542 if(rc != SQLITE_OK){
1543 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: force journal mode DELETE failed, error code %d", rc);
1544 goto handle_error;
1547 rc = sqlite3_exec(db, attach_command, NULL, NULL, NULL);
1548 if(rc != SQLITE_OK){
1549 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: attach failed, error code %d", rc);
1550 goto handle_error;
1553 rc = sqlite3_key_v2(db, "migrate", pass, pass_sz);
1554 if(rc != SQLITE_OK){
1555 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: keying attached database failed, error code %d", rc);
1556 goto handle_error;
1559 rc = sqlite3_exec(db, "SELECT sqlcipher_export('migrate');", NULL, NULL, NULL);
1560 if(rc != SQLITE_OK){
1561 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: sqlcipher_export failed, error code %d", rc);
1562 goto handle_error;
1565 #ifdef SQLCIPHER_TEST
1566 if((cipher_test_flags & TEST_FAIL_MIGRATE) > 0) {
1567 rc = SQLITE_ERROR;
1568 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: simulated migrate failure, error code %d", rc);
1569 goto handle_error;
1571 #endif
1573 rc = sqlite3_exec(db, set_user_version, NULL, NULL, NULL);
1574 if(rc != SQLITE_OK){
1575 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: set user version failed, error code %d", rc);
1576 goto handle_error;
1579 if( !db->autoCommit ){
1580 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: cannot migrate from within a transaction");
1581 goto handle_error;
1583 if( db->nVdbeActive>1 ){
1584 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: cannot migrate - SQL statements in progress");
1585 goto handle_error;
1588 pDest = db->aDb[0].pBt;
1589 pDb = &(db->aDb[db->nDb-1]);
1590 pSrc = pDb->pBt;
1592 nRes = sqlite3BtreeGetRequestedReserve(pSrc);
1593 /* unset the BTS_PAGESIZE_FIXED flag to avoid SQLITE_READONLY */
1594 pDest->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
1595 rc = sqlite3BtreeSetPageSize(pDest, default_page_size, nRes, 0);
1596 if(rc != SQLITE_OK) {
1597 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);
1598 goto handle_error;
1601 sqlcipherCodecGetKey(db, db->nDb - 1, (void**)&keyspec, &keyspec_sz);
1602 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_KEY_USED);
1603 sqlcipherCodecAttach(db, 0, keyspec, keyspec_sz);
1605 srcfile = sqlite3PagerFile(pSrc->pBt->pPager);
1606 destfile = sqlite3PagerFile(pDest->pBt->pPager);
1608 sqlite3OsClose(srcfile);
1609 sqlite3OsClose(destfile);
1611 #if defined(_WIN32) || defined(SQLITE_OS_WINRT)
1612 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: performing windows MoveFileExA");
1614 w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, NULL, 0);
1615 w_db_filename = sqlcipher_malloc(w_db_filename_sz * sizeof(wchar_t));
1616 w_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) db_filename, -1, (const LPWSTR) w_db_filename, w_db_filename_sz);
1618 w_migrated_db_filename_sz = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) migrated_db_filename, -1, NULL, 0);
1619 w_migrated_db_filename = sqlcipher_malloc(w_migrated_db_filename_sz * sizeof(wchar_t));
1620 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);
1622 if(!MoveFileExW(w_migrated_db_filename, w_db_filename, MOVEFILE_REPLACE_EXISTING)) {
1623 rc = SQLITE_ERROR;
1624 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: error occurred while renaming migration files %d", rc);
1625 goto handle_error;
1627 #else
1628 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: performing POSIX rename");
1629 if ((rc = rename(migrated_db_filename, db_filename)) != 0) {
1630 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);
1631 goto handle_error;
1633 #endif
1634 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);
1636 rc = sqlite3OsOpen(db->pVfs, migrated_db_filename, srcfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags);
1637 if(rc != SQLITE_OK) {
1638 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to reopen migration database %s: %d", migrated_db_filename, rc);
1639 goto handle_error;
1642 rc = sqlite3OsOpen(db->pVfs, db_filename, destfile, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_MAIN_DB, &oflags);
1643 if(rc != SQLITE_OK) {
1644 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to reopen main database %s: %d", db_filename, rc);
1645 goto handle_error;
1648 sqlite3pager_reset(pDest->pBt->pPager);
1649 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: reset pager");
1651 rc = sqlite3_exec(db, "DETACH DATABASE migrate;", NULL, NULL, NULL);
1652 if(rc != SQLITE_OK) {
1653 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: DETACH DATABASE migrate failed: %d", rc);
1656 sqlite3ResetAllSchemasOfConnection(db);
1657 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: reset all schemas");
1659 set_journal_mode = sqlite3_mprintf("PRAGMA journal_mode = %s;", journal_mode);
1660 rc = sqlite3_exec(db, set_journal_mode, NULL, NULL, NULL);
1661 if(rc != SQLITE_OK) {
1662 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);
1663 goto handle_error;
1666 goto cleanup;
1668 handle_error:
1669 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: an error occurred attempting to migrate the database - last error %d", rc);
1671 cleanup:
1672 if(migrated_db_filename) {
1673 int del_rc = sqlite3OsDelete(db->pVfs, migrated_db_filename, 0);
1674 if(del_rc != SQLITE_OK) {
1675 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_ctx_migrate: failed to delete migration database %s: %d", migrated_db_filename, del_rc);
1679 if(pass) sqlcipher_free(pass, pass_sz);
1680 if(attach_command) sqlcipher_free(attach_command, sqlite3Strlen30(attach_command));
1681 if(migrated_db_filename) sqlcipher_free(migrated_db_filename, sqlite3Strlen30(migrated_db_filename));
1682 if(set_user_version) sqlcipher_free(set_user_version, sqlite3Strlen30(set_user_version));
1683 if(set_journal_mode) sqlcipher_free(set_journal_mode, sqlite3Strlen30(set_journal_mode));
1684 if(journal_mode) sqlcipher_free(journal_mode, sqlite3Strlen30(journal_mode));
1685 if(pragma_compat) sqlcipher_free(pragma_compat, sqlite3Strlen30(pragma_compat));
1686 #if defined(_WIN32) || defined(SQLITE_OS_WINRT)
1687 if(w_db_filename) sqlcipher_free(w_db_filename, w_db_filename_sz);
1688 if(w_migrated_db_filename) sqlcipher_free(w_migrated_db_filename, w_migrated_db_filename_sz);
1689 #endif
1690 return rc;
1693 static int sqlcipher_codec_add_random(codec_ctx *ctx, const char *zRight, int random_sz){
1694 const char *suffix = &zRight[random_sz-1];
1695 int n = random_sz - 3; /* adjust for leading x' and tailing ' */
1696 if (n > 0 &&
1697 sqlite3StrNICmp((const char *)zRight ,"x'", 2) == 0 &&
1698 sqlite3StrNICmp(suffix, "'", 1) == 0 &&
1699 n % 2 == 0) {
1700 int rc = 0;
1701 int buffer_sz = n / 2;
1702 unsigned char *random;
1703 const unsigned char *z = (const unsigned char *)zRight + 2; /* adjust lead offset of x' */
1704 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_codec_add_random: using raw random blob from hex");
1705 random = sqlcipher_malloc(buffer_sz);
1706 memset(random, 0, buffer_sz);
1707 cipher_hex2bin(z, n, random);
1708 rc = ctx->provider->add_random(ctx->provider_ctx, random, buffer_sz);
1709 sqlcipher_free(random, buffer_sz);
1710 return rc;
1712 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_add_random: attemt to add random with invalid format");
1713 return SQLITE_ERROR;
1716 #if !defined(SQLITE_OMIT_TRACE)
1718 #define SQLCIPHER_PROFILE_FMT "Elapsed time:%.3f ms - %s\n"
1719 #define SQLCIPHER_PROFILE_FMT_OSLOG "Elapsed time:%{public}.3f ms - %{public}s\n"
1721 static int sqlcipher_profile_callback(unsigned int trace, void *file, void *stmt, void *run_time){
1722 FILE *f = (FILE*) file;
1723 double elapsed = (*((sqlite3_uint64*)run_time))/1000000.0;
1724 if(f == NULL) {
1725 #if !defined(SQLCIPHER_OMIT_LOG_DEVICE)
1726 #if defined(__ANDROID__)
1727 __android_log_print(ANDROID_LOG_DEBUG, "sqlcipher", SQLCIPHER_PROFILE_FMT, elapsed, sqlite3_sql((sqlite3_stmt*)stmt));
1728 #elif defined(__APPLE__)
1729 os_log(OS_LOG_DEFAULT, SQLCIPHER_PROFILE_FMT_OSLOG, elapsed, sqlite3_sql((sqlite3_stmt*)stmt));
1730 #endif
1731 #endif
1732 } else {
1733 fprintf(f, SQLCIPHER_PROFILE_FMT, elapsed, sqlite3_sql((sqlite3_stmt*)stmt));
1735 return SQLITE_OK;
1737 #endif
1739 static int sqlcipher_cipher_profile(sqlite3 *db, const char *destination){
1740 #if defined(SQLITE_OMIT_TRACE)
1741 return SQLITE_ERROR;
1742 #else
1743 FILE *f = NULL;
1744 if(sqlite3_stricmp(destination, "off") == 0){
1745 sqlite3_trace_v2(db, 0, NULL, NULL); /* disable tracing */
1746 } else {
1747 if(sqlite3_stricmp(destination, "stdout") == 0){
1748 f = stdout;
1749 }else if(sqlite3_stricmp(destination, "stderr") == 0){
1750 f = stderr;
1751 }else if(sqlite3_stricmp(destination, "logcat") == 0 || sqlite3_stricmp(destination, "device") == 0){
1752 f = NULL; /* file pointer will be NULL indicating the device target (i.e. logcat or oslog). We will accept logcat for backwards compatibility */
1753 }else{
1754 #if !defined(SQLCIPHER_PROFILE_USE_FOPEN) && (defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT))
1755 if(fopen_s(&f, destination, "a") != 0) return SQLITE_ERROR;
1756 #else
1757 if((f = fopen(destination, "a")) == 0) return SQLITE_ERROR;
1758 #endif
1760 sqlite3_trace_v2(db, SQLITE_TRACE_PROFILE, sqlcipher_profile_callback, f);
1762 return SQLITE_OK;
1763 #endif
1766 static char *sqlcipher_get_log_level_str(unsigned int level) {
1767 switch(level) {
1768 case SQLCIPHER_LOG_ERROR:
1769 return "ERROR";
1770 case SQLCIPHER_LOG_WARN:
1771 return "WARN";
1772 case SQLCIPHER_LOG_INFO:
1773 return "INFO";
1774 case SQLCIPHER_LOG_DEBUG:
1775 return "DEBUG";
1776 case SQLCIPHER_LOG_TRACE:
1777 return "TRACE";
1778 case SQLCIPHER_LOG_ALL:
1779 return "ALL";
1781 return "NONE";
1784 static char *sqlcipher_get_log_source_str(unsigned int source) {
1785 switch(source) {
1786 case SQLCIPHER_LOG_NONE:
1787 return "NONE";
1788 case SQLCIPHER_LOG_CORE:
1789 return "CORE";
1790 case SQLCIPHER_LOG_MEMORY:
1791 return "MEMORY";
1792 case SQLCIPHER_LOG_MUTEX:
1793 return "MUTEX";
1794 case SQLCIPHER_LOG_PROVIDER:
1795 return "PROVIDER";
1797 return "ALL";
1801 #ifndef SQLCIPHER_OMIT_LOG
1802 /* constants from https://github.com/Alexpux/mingw-w64/blob/master/mingw-w64-crt/misc/gettimeofday.c */
1803 #define FILETIME_1970 116444736000000000ull /* seconds between 1/1/1601 and 1/1/1970 */
1804 #define HECTONANOSEC_PER_SEC 10000000ull
1805 #define MAX_LOG_LEN 8192
1806 void sqlcipher_log(unsigned int level, unsigned int source, const char *message, ...) {
1807 va_list params;
1808 va_start(params, message);
1809 char formatted[MAX_LOG_LEN];
1810 int len = 0;
1812 #ifdef CODEC_DEBUG
1813 #if defined(SQLCIPHER_OMIT_LOG_DEVICE) || (!defined(__ANDROID__) && !defined(__APPLE__))
1814 vfprintf(stderr, message, params);
1815 fprintf(stderr, "\n");
1816 goto end;
1817 #else
1818 #if defined(__ANDROID__)
1819 __android_log_vprint(ANDROID_LOG_DEBUG, "sqlcipher", message, params);
1820 goto end;
1821 #elif defined(__APPLE__)
1822 sqlite3_vsnprintf(MAX_LOG_LEN, formatted, message, params);
1823 os_log(OS_LOG_DEFAULT, "%{public}s", formatted);
1824 goto end;
1825 #endif
1826 #endif
1827 #endif
1829 level > sqlcipher_log_level /* log level is higher, e.g. level filter is at ERROR but this message is DEBUG */
1830 || (sqlcipher_log_source & source) == 0 /* source filter doesn't match this message source */
1831 || (sqlcipher_log_device == 0 && sqlcipher_log_file == NULL) /* no configured log target */
1833 /* skip logging this message */
1834 goto end;
1837 sqlite3_snprintf(MAX_LOG_LEN, formatted, "%s %s ", sqlcipher_get_log_level_str(level), sqlcipher_get_log_source_str(source));
1838 len = strlen(formatted);
1839 sqlite3_vsnprintf(MAX_LOG_LEN - len, formatted + len, message, params);
1841 #if !defined(SQLCIPHER_OMIT_LOG_DEVICE)
1842 if(sqlcipher_log_device) {
1843 #if defined(__ANDROID__)
1844 __android_log_print(ANDROID_LOG_DEBUG, "sqlcipher", formatted);
1845 goto end;
1846 #elif defined(__APPLE__)
1847 os_log(OS_LOG_DEFAULT, "%{public}s", formatted);
1848 goto end;
1849 #endif
1851 #endif
1853 if(sqlcipher_log_file != NULL){
1854 char buffer[24];
1855 struct tm tt;
1856 int ms;
1857 time_t sec;
1858 #ifdef _WIN32
1859 SYSTEMTIME st;
1860 FILETIME ft;
1861 GetSystemTime(&st);
1862 SystemTimeToFileTime(&st, &ft);
1863 sec = (time_t) ((*((sqlite_int64*)&ft) - FILETIME_1970) / HECTONANOSEC_PER_SEC);
1864 ms = st.wMilliseconds;
1865 localtime_s(&tt, &sec);
1866 #else
1867 struct timeval tv;
1868 gettimeofday(&tv, NULL);
1869 sec = tv.tv_sec;
1870 ms = tv.tv_usec/1000.0;
1871 localtime_r(&sec, &tt);
1872 #endif
1873 if(strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tt)) {
1874 fprintf((FILE*)sqlcipher_log_file, "%s.%03d: %s\n", buffer, ms, formatted);
1875 goto end;
1879 end:
1880 va_end(params);
1882 #endif
1884 static int sqlcipher_set_log(const char *destination){
1885 #ifdef SQLCIPHER_OMIT_LOG
1886 return SQLITE_ERROR;
1887 #else
1888 /* close open trace file if it is not stdout or stderr, then
1889 reset trace settings */
1890 if(sqlcipher_log_file != NULL && sqlcipher_log_file != stdout && sqlcipher_log_file != stderr) {
1891 fclose((FILE*)sqlcipher_log_file);
1893 sqlcipher_log_file = NULL;
1894 sqlcipher_log_device = 0;
1896 if(sqlite3_stricmp(destination, "logcat") == 0 || sqlite3_stricmp(destination, "device") == 0){
1897 /* use the appropriate device log. accept logcat for backwards compatibility */
1898 sqlcipher_log_device = 1;
1899 } else if(sqlite3_stricmp(destination, "stdout") == 0){
1900 sqlcipher_log_file = stdout;
1901 }else if(sqlite3_stricmp(destination, "stderr") == 0){
1902 sqlcipher_log_file = stderr;
1903 }else if(sqlite3_stricmp(destination, "off") != 0){
1904 #if !defined(SQLCIPHER_PROFILE_USE_FOPEN) && (defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT))
1905 if(fopen_s(&sqlcipher_log_file, destination, "a") != 0) return SQLITE_ERROR;
1906 #else
1907 if((sqlcipher_log_file = fopen(destination, "a")) == 0) return SQLITE_ERROR;
1908 #endif
1910 sqlcipher_log(SQLCIPHER_LOG_INFO, SQLCIPHER_LOG_CORE, "sqlcipher_set_log: set log to %s", destination);
1911 return SQLITE_OK;
1912 #endif
1915 static void sqlcipher_vdbe_return_string(Parse *pParse, const char *zLabel, const char *value, int value_type){
1916 Vdbe *v = sqlite3GetVdbe(pParse);
1917 sqlite3VdbeSetNumCols(v, 1);
1918 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
1919 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, value, value_type);
1920 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
1923 static int codec_set_btree_to_codec_pagesize(sqlite3 *db, Db *pDb, codec_ctx *ctx) {
1924 int rc;
1926 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);
1928 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: entering database mutex %p", db->mutex);
1929 sqlite3_mutex_enter(db->mutex);
1930 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: entered database mutex %p", db->mutex);
1931 db->nextPagesize = ctx->page_sz;
1933 /* before forcing the page size we need to unset the BTS_PAGESIZE_FIXED flag, else
1934 sqliteBtreeSetPageSize will block the change */
1935 pDb->pBt->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
1936 rc = sqlite3BtreeSetPageSize(pDb->pBt, ctx->page_sz, ctx->reserve_sz, 0);
1938 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize returned %d", rc);
1940 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: leaving database mutex %p", db->mutex);
1941 sqlite3_mutex_leave(db->mutex);
1942 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "codec_set_btree_to_codec_pagesize: left database mutex %p", db->mutex);
1944 return rc;
1947 static int codec_set_pass_key(sqlite3* db, int nDb, const void *zKey, int nKey, int for_ctx) {
1948 struct Db *pDb = &db->aDb[nDb];
1949 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "codec_set_pass_key: db=%p nDb=%d for_ctx=%d", db, nDb, for_ctx);
1950 if(pDb->pBt) {
1951 codec_ctx *ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
1953 if(ctx) {
1954 return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx);
1955 } else {
1956 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "codec_set_pass_key: error ocurred fetching codec from pager on db %d", nDb);
1957 return SQLITE_ERROR;
1960 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "codec_set_pass_key: no btree present on db %d", nDb);
1961 return SQLITE_ERROR;
1964 int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) {
1965 struct Db *pDb = &db->aDb[iDb];
1966 codec_ctx *ctx = NULL;
1967 int rc;
1969 if(pDb->pBt) {
1970 ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
1973 if(sqlite3_stricmp(zLeft, "key") !=0 && sqlite3_stricmp(zLeft, "rekey") != 0) {
1974 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);
1977 #ifdef SQLCIPHER_TEST
1978 if( sqlite3_stricmp(zLeft,"cipher_test_on")==0 ){
1979 if( zRight ) {
1980 if(sqlite3_stricmp(zRight, "fail_encrypt")==0) {
1981 SQLCIPHER_FLAG_SET(cipher_test_flags,TEST_FAIL_ENCRYPT);
1982 } else
1983 if(sqlite3_stricmp(zRight, "fail_decrypt")==0) {
1984 SQLCIPHER_FLAG_SET(cipher_test_flags,TEST_FAIL_DECRYPT);
1985 } else
1986 if(sqlite3_stricmp(zRight, "fail_migrate")==0) {
1987 SQLCIPHER_FLAG_SET(cipher_test_flags,TEST_FAIL_MIGRATE);
1990 } else
1991 if( sqlite3_stricmp(zLeft,"cipher_test_off")==0 ){
1992 if( zRight ) {
1993 if(sqlite3_stricmp(zRight, "fail_encrypt")==0) {
1994 SQLCIPHER_FLAG_UNSET(cipher_test_flags,TEST_FAIL_ENCRYPT);
1995 } else
1996 if(sqlite3_stricmp(zRight, "fail_decrypt")==0) {
1997 SQLCIPHER_FLAG_UNSET(cipher_test_flags,TEST_FAIL_DECRYPT);
1998 } else
1999 if(sqlite3_stricmp(zRight, "fail_migrate")==0) {
2000 SQLCIPHER_FLAG_UNSET(cipher_test_flags,TEST_FAIL_MIGRATE);
2003 } else
2004 if( sqlite3_stricmp(zLeft,"cipher_test")==0 ){
2005 char *flags = sqlite3_mprintf("%u", cipher_test_flags);
2006 sqlcipher_vdbe_return_string(pParse, "cipher_test", flags, P4_DYNAMIC);
2007 }else
2008 if( sqlite3_stricmp(zLeft,"cipher_test_rand")==0 ){
2009 if( zRight ) {
2010 int rand = atoi(zRight);
2011 cipher_test_rand = rand;
2012 } else {
2013 char *rand = sqlite3_mprintf("%d", cipher_test_rand);
2014 sqlcipher_vdbe_return_string(pParse, "cipher_test_rand", rand, P4_DYNAMIC);
2016 } else
2017 #endif
2018 if( sqlite3_stricmp(zLeft, "cipher_fips_status")== 0 && !zRight ){
2019 if(ctx) {
2020 char *fips_mode_status = sqlite3_mprintf("%d", ctx->provider->fips_status(ctx->provider_ctx));
2021 sqlcipher_vdbe_return_string(pParse, "cipher_fips_status", fips_mode_status, P4_DYNAMIC);
2023 } else
2024 if( sqlite3_stricmp(zLeft, "cipher_store_pass")==0 && zRight ) {
2025 if(ctx) {
2026 char *deprecation = "PRAGMA cipher_store_pass is deprecated, please remove from use";
2027 ctx->store_pass = sqlite3GetBoolean(zRight, 1);
2028 sqlcipher_vdbe_return_string(pParse, "cipher_store_pass", deprecation, P4_TRANSIENT);
2029 sqlite3_log(SQLITE_WARNING, deprecation);
2031 } else
2032 if( sqlite3_stricmp(zLeft, "cipher_store_pass")==0 && !zRight ) {
2033 if(ctx){
2034 char *store_pass_value = sqlite3_mprintf("%d", ctx->store_pass);
2035 sqlcipher_vdbe_return_string(pParse, "cipher_store_pass", store_pass_value, P4_DYNAMIC);
2038 if( sqlite3_stricmp(zLeft, "cipher_profile")== 0 && zRight ){
2039 char *profile_status = sqlite3_mprintf("%d", sqlcipher_cipher_profile(db, zRight));
2040 sqlcipher_vdbe_return_string(pParse, "cipher_profile", profile_status, P4_DYNAMIC);
2041 } else
2042 if( sqlite3_stricmp(zLeft, "cipher_add_random")==0 && zRight ){
2043 if(ctx) {
2044 char *add_random_status = sqlite3_mprintf("%d", sqlcipher_codec_add_random(ctx, zRight, sqlite3Strlen30(zRight)));
2045 sqlcipher_vdbe_return_string(pParse, "cipher_add_random", add_random_status, P4_DYNAMIC);
2047 } else
2048 if( sqlite3_stricmp(zLeft, "cipher_migrate")==0 && !zRight ){
2049 if(ctx){
2050 int status = sqlcipher_codec_ctx_migrate(ctx);
2051 char *migrate_status = sqlite3_mprintf("%d", status);
2052 sqlcipher_vdbe_return_string(pParse, "cipher_migrate", migrate_status, P4_DYNAMIC);
2053 if(status != SQLITE_OK) {
2054 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipher_codec_pragma: error occurred during cipher_migrate: %d", status);
2055 sqlcipher_codec_ctx_set_error(ctx, status);
2058 } else
2059 if( sqlite3_stricmp(zLeft, "cipher_provider")==0 && !zRight ){
2060 if(ctx) {
2061 sqlcipher_vdbe_return_string(pParse, "cipher_provider",
2062 ctx->provider->get_provider_name(ctx->provider_ctx), P4_TRANSIENT);
2064 } else
2065 if( sqlite3_stricmp(zLeft, "cipher_provider_version")==0 && !zRight){
2066 if(ctx) {
2067 sqlcipher_vdbe_return_string(pParse, "cipher_provider_version",
2068 ctx->provider->get_provider_version(ctx->provider_ctx), P4_TRANSIENT);
2070 } else
2071 if( sqlite3_stricmp(zLeft, "cipher_version")==0 && !zRight ){
2072 sqlcipher_vdbe_return_string(pParse, "cipher_version", sqlcipher_version(), P4_DYNAMIC);
2073 }else
2074 if( sqlite3_stricmp(zLeft, "cipher")==0 ){
2075 if(ctx) {
2076 if( zRight ) {
2077 const char* message = "PRAGMA cipher is no longer supported.";
2078 sqlcipher_vdbe_return_string(pParse, "cipher", message, P4_TRANSIENT);
2079 sqlite3_log(SQLITE_WARNING, message);
2080 }else {
2081 sqlcipher_vdbe_return_string(pParse, "cipher",
2082 ctx->provider->get_cipher(ctx->provider_ctx), P4_TRANSIENT);
2085 }else
2086 if( sqlite3_stricmp(zLeft, "rekey_cipher")==0 && zRight ){
2087 const char* message = "PRAGMA rekey_cipher is no longer supported.";
2088 sqlcipher_vdbe_return_string(pParse, "rekey_cipher", message, P4_TRANSIENT);
2089 sqlite3_log(SQLITE_WARNING, message);
2090 }else
2091 if( sqlite3_stricmp(zLeft,"cipher_default_kdf_iter")==0 ){
2092 if( zRight ) {
2093 default_kdf_iter = atoi(zRight); /* change default KDF iterations */
2094 } else {
2095 char *kdf_iter = sqlite3_mprintf("%d", default_kdf_iter);
2096 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_iter", kdf_iter, P4_DYNAMIC);
2098 }else
2099 if( sqlite3_stricmp(zLeft, "kdf_iter")==0 ){
2100 if(ctx) {
2101 if( zRight ) {
2102 sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */
2103 } else {
2104 char *kdf_iter = sqlite3_mprintf("%d", ctx->kdf_iter);
2105 sqlcipher_vdbe_return_string(pParse, "kdf_iter", kdf_iter, P4_DYNAMIC);
2108 }else
2109 if( sqlite3_stricmp(zLeft, "fast_kdf_iter")==0){
2110 if(ctx) {
2111 if( zRight ) {
2112 char *deprecation = "PRAGMA fast_kdf_iter is deprecated, please remove from use";
2113 sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */
2114 sqlcipher_vdbe_return_string(pParse, "fast_kdf_iter", deprecation, P4_TRANSIENT);
2115 sqlite3_log(SQLITE_WARNING, deprecation);
2116 } else {
2117 char *fast_kdf_iter = sqlite3_mprintf("%d", ctx->fast_kdf_iter);
2118 sqlcipher_vdbe_return_string(pParse, "fast_kdf_iter", fast_kdf_iter, P4_DYNAMIC);
2121 }else
2122 if( sqlite3_stricmp(zLeft, "rekey_kdf_iter")==0 && zRight ){
2123 const char* message = "PRAGMA rekey_kdf_iter is no longer supported.";
2124 sqlcipher_vdbe_return_string(pParse, "rekey_kdf_iter", message, P4_TRANSIENT);
2125 sqlite3_log(SQLITE_WARNING, message);
2126 }else
2127 if( sqlite3_stricmp(zLeft,"page_size")==0 || sqlite3_stricmp(zLeft,"cipher_page_size")==0 ){
2128 /* PRAGMA cipher_page_size will alter the size of the database pages while ensuring that the
2129 required reserve space is allocated at the end of each page. This will also override the
2130 standard SQLite PRAGMA page_size behavior if a codec context is attached to the database handle.
2131 If PRAGMA page_size is invoked but a codec context is not attached (i.e. dealing with a standard
2132 unencrypted database) then return early and allow the standard PRAGMA page_size logic to apply. */
2133 if(ctx) {
2134 if( zRight ) {
2135 int size = atoi(zRight);
2136 rc = sqlcipher_codec_ctx_set_pagesize(ctx, size);
2137 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2138 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2139 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2140 } else {
2141 char * page_size = sqlite3_mprintf("%d", ctx->page_sz);
2142 sqlcipher_vdbe_return_string(pParse, "cipher_page_size", page_size, P4_DYNAMIC);
2144 } else {
2145 return 0; /* return early so that the PragTyp_PAGE_SIZE case logic in pragma.c will take effect */
2147 }else
2148 if( sqlite3_stricmp(zLeft,"cipher_default_page_size")==0 ){
2149 if( zRight ) {
2150 default_page_size = atoi(zRight);
2151 } else {
2152 char *page_size = sqlite3_mprintf("%d", default_page_size);
2153 sqlcipher_vdbe_return_string(pParse, "cipher_default_page_size", page_size, P4_DYNAMIC);
2155 }else
2156 if( sqlite3_stricmp(zLeft,"cipher_default_use_hmac")==0 ){
2157 if( zRight ) {
2158 sqlcipher_set_default_use_hmac(sqlite3GetBoolean(zRight,1));
2159 } else {
2160 char *default_use_hmac = sqlite3_mprintf("%d", SQLCIPHER_FLAG_GET(default_flags, CIPHER_FLAG_HMAC));
2161 sqlcipher_vdbe_return_string(pParse, "cipher_default_use_hmac", default_use_hmac, P4_DYNAMIC);
2163 }else
2164 if( sqlite3_stricmp(zLeft,"cipher_use_hmac")==0 ){
2165 if(ctx) {
2166 if( zRight ) {
2167 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, sqlite3GetBoolean(zRight,1));
2168 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2169 /* since the use of hmac has changed, the page size may also change */
2170 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2171 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
2172 } else {
2173 char *hmac_flag = sqlite3_mprintf("%d", SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC));
2174 sqlcipher_vdbe_return_string(pParse, "cipher_use_hmac", hmac_flag, P4_DYNAMIC);
2177 }else
2178 if( sqlite3_stricmp(zLeft,"cipher_hmac_pgno")==0 ){
2179 if(ctx) {
2180 if(zRight) {
2181 char *deprecation = "PRAGMA cipher_hmac_pgno is deprecated, please remove from use";
2182 /* clear both pgno endian flags */
2183 if(sqlite3_stricmp(zRight, "le") == 0) {
2184 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_BE_PGNO);
2185 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_LE_PGNO);
2186 } else if(sqlite3_stricmp(zRight, "be") == 0) {
2187 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_LE_PGNO);
2188 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_BE_PGNO);
2189 } else if(sqlite3_stricmp(zRight, "native") == 0) {
2190 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_LE_PGNO);
2191 SQLCIPHER_FLAG_UNSET(ctx->flags, CIPHER_FLAG_BE_PGNO);
2193 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", deprecation, P4_TRANSIENT);
2194 sqlite3_log(SQLITE_WARNING, deprecation);
2196 } else {
2197 if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_LE_PGNO)) {
2198 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", "le", P4_TRANSIENT);
2199 } else if(SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_BE_PGNO)) {
2200 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", "be", P4_TRANSIENT);
2201 } else {
2202 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_pgno", "native", P4_TRANSIENT);
2206 }else
2207 if( sqlite3_stricmp(zLeft,"cipher_hmac_salt_mask")==0 ){
2208 if(ctx) {
2209 if(zRight) {
2210 char *deprecation = "PRAGMA cipher_hmac_salt_mask is deprecated, please remove from use";
2211 if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == 5) {
2212 unsigned char mask = 0;
2213 const unsigned char *hex = (const unsigned char *)zRight+2;
2214 cipher_hex2bin(hex,2,&mask);
2215 hmac_salt_mask = mask;
2217 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_salt_mask", deprecation, P4_TRANSIENT);
2218 sqlite3_log(SQLITE_WARNING, deprecation);
2219 } else {
2220 char *mask = sqlite3_mprintf("%02x", hmac_salt_mask);
2221 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_salt_mask", mask, P4_DYNAMIC);
2224 }else
2225 if( sqlite3_stricmp(zLeft,"cipher_plaintext_header_size")==0 ){
2226 if(ctx) {
2227 if( zRight ) {
2228 int size = atoi(zRight);
2229 /* deliberately ignore result code, if size is invalid it will be set to -1
2230 and trip the error later in the codec */
2231 sqlcipher_codec_ctx_set_plaintext_header_size(ctx, size);
2232 } else {
2233 char *size = sqlite3_mprintf("%d", ctx->plaintext_header_sz);
2234 sqlcipher_vdbe_return_string(pParse, "cipher_plaintext_header_size", size, P4_DYNAMIC);
2237 }else
2238 if( sqlite3_stricmp(zLeft,"cipher_default_plaintext_header_size")==0 ){
2239 if( zRight ) {
2240 default_plaintext_header_size = atoi(zRight);
2241 } else {
2242 char *size = sqlite3_mprintf("%d", default_plaintext_header_size);
2243 sqlcipher_vdbe_return_string(pParse, "cipher_default_plaintext_header_size", size, P4_DYNAMIC);
2245 }else
2246 if( sqlite3_stricmp(zLeft,"cipher_salt")==0 ){
2247 if(ctx) {
2248 if(zRight) {
2249 if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == (FILE_HEADER_SZ*2)+3) {
2250 unsigned char *salt = (unsigned char*) sqlite3_malloc(FILE_HEADER_SZ);
2251 const unsigned char *hex = (const unsigned char *)zRight+2;
2252 cipher_hex2bin(hex,FILE_HEADER_SZ*2,salt);
2253 sqlcipher_codec_ctx_set_kdf_salt(ctx, salt, FILE_HEADER_SZ);
2254 sqlite3_free(salt);
2256 } else {
2257 void *salt;
2258 char *hexsalt = (char*) sqlite3_malloc((FILE_HEADER_SZ*2)+1);
2259 if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &salt)) == SQLITE_OK) {
2260 cipher_bin2hex(salt, FILE_HEADER_SZ, hexsalt);
2261 sqlcipher_vdbe_return_string(pParse, "cipher_salt", hexsalt, P4_DYNAMIC);
2262 } else {
2263 sqlite3_free(hexsalt);
2264 sqlcipher_codec_ctx_set_error(ctx, rc);
2268 }else
2269 if( sqlite3_stricmp(zLeft,"cipher_hmac_algorithm")==0 ){
2270 if(ctx) {
2271 if(zRight) {
2272 rc = SQLITE_ERROR;
2273 if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) {
2274 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2275 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) {
2276 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA256);
2277 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) {
2278 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512);
2280 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2281 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2282 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2283 } else {
2284 int algorithm = ctx->hmac_algorithm;
2285 if(ctx->hmac_algorithm == SQLCIPHER_HMAC_SHA1) {
2286 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT);
2287 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
2288 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT);
2289 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
2290 sqlcipher_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT);
2294 }else
2295 if( sqlite3_stricmp(zLeft,"cipher_default_hmac_algorithm")==0 ){
2296 if(zRight) {
2297 rc = SQLITE_OK;
2298 if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) {
2299 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2300 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) {
2301 default_hmac_algorithm = SQLCIPHER_HMAC_SHA256;
2302 } else if(sqlite3_stricmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) {
2303 default_hmac_algorithm = SQLCIPHER_HMAC_SHA512;
2305 } else {
2306 if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA1) {
2307 sqlcipher_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT);
2308 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA256) {
2309 sqlcipher_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT);
2310 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA512) {
2311 sqlcipher_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT);
2314 }else
2315 if( sqlite3_stricmp(zLeft,"cipher_kdf_algorithm")==0 ){
2316 if(ctx) {
2317 if(zRight) {
2318 rc = SQLITE_ERROR;
2319 if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) {
2320 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2321 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) {
2322 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA256);
2323 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) {
2324 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512);
2326 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2327 } else {
2328 if(ctx->kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2329 sqlcipher_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT);
2330 } else if(ctx->kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2331 sqlcipher_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT);
2332 } else if(ctx->kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2333 sqlcipher_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT);
2337 }else
2338 if( sqlite3_stricmp(zLeft,"cipher_default_kdf_algorithm")==0 ){
2339 if(zRight) {
2340 rc = SQLITE_OK;
2341 if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) {
2342 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2343 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) {
2344 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA256;
2345 } else if(sqlite3_stricmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) {
2346 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512;
2348 } else {
2349 if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2350 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT);
2351 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2352 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT);
2353 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2354 sqlcipher_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT);
2357 }else
2358 if( sqlite3_stricmp(zLeft,"cipher_compatibility")==0 ){
2359 if(ctx) {
2360 if(zRight) {
2361 int version = atoi(zRight);
2363 switch(version) {
2364 case 1:
2365 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
2366 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2367 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2368 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2369 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2370 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2371 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000);
2372 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2373 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 0);
2374 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2375 break;
2377 case 2:
2378 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
2379 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2380 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2381 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2382 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2383 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2384 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000);
2385 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2386 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
2387 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2388 break;
2390 case 3:
2391 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
2392 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2393 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
2394 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2395 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
2396 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2397 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 64000);
2398 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2399 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
2400 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2401 break;
2403 default:
2404 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 4096);
2405 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2406 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512);
2407 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2408 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512);
2409 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2410 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 256000);
2411 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2412 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
2413 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2414 break;
2417 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2418 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2421 }else
2422 if( sqlite3_stricmp(zLeft,"cipher_default_compatibility")==0 ){
2423 if(zRight) {
2424 int version = atoi(zRight);
2425 switch(version) {
2426 case 1:
2427 default_page_size = 1024;
2428 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2429 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2430 default_kdf_iter = 4000;
2431 sqlcipher_set_default_use_hmac(0);
2432 break;
2434 case 2:
2435 default_page_size = 1024;
2436 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2437 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2438 default_kdf_iter = 4000;
2439 sqlcipher_set_default_use_hmac(1);
2440 break;
2442 case 3:
2443 default_page_size = 1024;
2444 default_hmac_algorithm = SQLCIPHER_HMAC_SHA1;
2445 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA1;
2446 default_kdf_iter = 64000;
2447 sqlcipher_set_default_use_hmac(1);
2448 break;
2450 default:
2451 default_page_size = 4096;
2452 default_hmac_algorithm = SQLCIPHER_HMAC_SHA512;
2453 default_kdf_algorithm = SQLCIPHER_PBKDF2_HMAC_SHA512;
2454 default_kdf_iter = 256000;
2455 sqlcipher_set_default_use_hmac(1);
2456 break;
2459 }else
2460 if( sqlite3_stricmp(zLeft,"cipher_memory_security")==0 ){
2461 if( zRight ) {
2462 if(sqlite3GetBoolean(zRight,1)) {
2463 /* memory security can only be enabled, not disabled */
2464 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipher_set_mem_security: on");
2465 sqlcipher_mem_security_on = 1;
2467 } else {
2468 /* only report that memory security is enabled if pragma cipher_memory_security is ON and
2469 SQLCipher's allocator/deallocator was run at least one time */
2470 int state = sqlcipher_mem_security_on && sqlcipher_mem_executed;
2471 char *on = sqlite3_mprintf("%d", state);
2472 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE,
2473 "sqlcipher_get_mem_security: sqlcipher_mem_security_on = %d, sqlcipher_mem_executed = %d",
2474 sqlcipher_mem_security_on, sqlcipher_mem_executed);
2475 sqlcipher_vdbe_return_string(pParse, "cipher_memory_security", on, P4_DYNAMIC);
2477 }else
2478 if( sqlite3_stricmp(zLeft,"cipher_settings")==0 ){
2479 if(ctx) {
2480 int algorithm;
2481 char *pragma;
2483 pragma = sqlite3_mprintf("PRAGMA kdf_iter = %d;", ctx->kdf_iter);
2484 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2486 pragma = sqlite3_mprintf("PRAGMA cipher_page_size = %d;", ctx->page_sz);
2487 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2489 pragma = sqlite3_mprintf("PRAGMA cipher_use_hmac = %d;", SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_HMAC));
2490 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2492 pragma = sqlite3_mprintf("PRAGMA cipher_plaintext_header_size = %d;", ctx->plaintext_header_sz);
2493 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2495 algorithm = ctx->hmac_algorithm;
2496 pragma = NULL;
2497 if(algorithm == SQLCIPHER_HMAC_SHA1) {
2498 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL);
2499 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
2500 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL);
2501 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
2502 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL);
2504 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2506 algorithm = ctx->kdf_algorithm;
2507 pragma = NULL;
2508 if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2509 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL);
2510 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2511 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL);
2512 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2513 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL);
2515 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2518 }else
2519 if( sqlite3_stricmp(zLeft,"cipher_default_settings")==0 ){
2520 char *pragma;
2522 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_iter = %d;", default_kdf_iter);
2523 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2525 pragma = sqlite3_mprintf("PRAGMA cipher_default_page_size = %d;", default_page_size);
2526 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2528 pragma = sqlite3_mprintf("PRAGMA cipher_default_use_hmac = %d;", SQLCIPHER_FLAG_GET(default_flags, CIPHER_FLAG_HMAC));
2529 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2531 pragma = sqlite3_mprintf("PRAGMA cipher_default_plaintext_header_size = %d;", default_plaintext_header_size);
2532 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2534 pragma = NULL;
2535 if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA1) {
2536 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL);
2537 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA256) {
2538 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL);
2539 } else if(default_hmac_algorithm == SQLCIPHER_HMAC_SHA512) {
2540 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL);
2542 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2544 pragma = NULL;
2545 if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
2546 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL);
2547 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
2548 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL);
2549 } else if(default_kdf_algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
2550 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL);
2552 sqlcipher_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
2553 }else
2554 if( sqlite3_stricmp(zLeft,"cipher_integrity_check")==0 ){
2555 if(ctx) {
2556 sqlcipher_codec_ctx_integrity_check(ctx, pParse, "cipher_integrity_check");
2558 } else
2559 if( sqlite3_stricmp(zLeft, "cipher_log_level")==0 ){
2560 if(zRight) {
2561 sqlcipher_log_level = SQLCIPHER_LOG_NONE;
2562 if(sqlite3_stricmp(zRight, "ERROR")==0) sqlcipher_log_level = SQLCIPHER_LOG_ERROR;
2563 else if(sqlite3_stricmp(zRight, "WARN" )==0) sqlcipher_log_level = SQLCIPHER_LOG_WARN;
2564 else if(sqlite3_stricmp(zRight, "INFO" )==0) sqlcipher_log_level = SQLCIPHER_LOG_INFO;
2565 else if(sqlite3_stricmp(zRight, "DEBUG")==0) sqlcipher_log_level = SQLCIPHER_LOG_DEBUG;
2566 else if(sqlite3_stricmp(zRight, "TRACE")==0) sqlcipher_log_level = SQLCIPHER_LOG_TRACE;
2568 sqlcipher_vdbe_return_string(pParse, "cipher_log_level", sqlcipher_get_log_level_str(sqlcipher_log_level), P4_TRANSIENT);
2569 } else
2570 if( sqlite3_stricmp(zLeft, "cipher_log_source")==0 ){
2571 if(zRight) {
2572 sqlcipher_log_source = SQLCIPHER_LOG_NONE;
2573 if(sqlite3_stricmp(zRight, "NONE" )==0) sqlcipher_log_source = SQLCIPHER_LOG_NONE;
2574 else if(sqlite3_stricmp(zRight, "ALL" )==0) sqlcipher_log_source = SQLCIPHER_LOG_ALL;
2575 else if(sqlite3_stricmp(zRight, "CORE" )==0) sqlcipher_log_source = SQLCIPHER_LOG_CORE;
2576 else if(sqlite3_stricmp(zRight, "MEMORY" )==0) sqlcipher_log_source = SQLCIPHER_LOG_MEMORY;
2577 else if(sqlite3_stricmp(zRight, "MUTEX" )==0) sqlcipher_log_source = SQLCIPHER_LOG_MUTEX;
2578 else if(sqlite3_stricmp(zRight, "PROVIDER")==0) sqlcipher_log_source = SQLCIPHER_LOG_PROVIDER;
2580 sqlcipher_vdbe_return_string(pParse, "cipher_log_source", sqlcipher_get_log_source_str(sqlcipher_log_source), P4_TRANSIENT);
2581 } else
2582 if( sqlite3_stricmp(zLeft, "cipher_log")== 0 && zRight ){
2583 char *status = sqlite3_mprintf("%d", sqlcipher_set_log(zRight));
2584 sqlcipher_vdbe_return_string(pParse, "cipher_log", status, P4_DYNAMIC);
2585 }else {
2586 return 0;
2588 return 1;
2591 /* these constants are used internally within SQLite's pager.c to differentiate between
2592 operations on the main database or journal pages. This is important in the context
2593 of a rekey operations, where the journal must be written using the original key
2594 material (to allow a transactional rollback), while the new database pages are being
2595 written with the new key material*/
2596 #define CODEC_READ_OP 3
2597 #define CODEC_WRITE_OP 6
2598 #define CODEC_JOURNAL_OP 7
2601 * sqlite3Codec can be called in multiple modes.
2602 * encrypt mode - expected to return a pointer to the
2603 * encrypted data without altering pData.
2604 * decrypt mode - expected to return a pointer to pData, with
2605 * the data decrypted in the input buffer
2607 static void* sqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) {
2608 codec_ctx *ctx = (codec_ctx *) iCtx;
2609 int offset = 0, rc = 0;
2610 unsigned char *pData = (unsigned char *) data;
2611 int cctx = CIPHER_READ_CTX;
2613 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3Codec: pgno=%d, mode=%d, ctx->page_sz=%d", pgno, mode, ctx->page_sz);
2615 /* call to derive keys if not present yet */
2616 if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) {
2617 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error occurred during key derivation: %d", rc);
2618 sqlcipher_codec_ctx_set_error(ctx, rc);
2619 return NULL;
2622 /* if the plaintext_header_size is negative that means an invalid size was set via
2623 PRAGMA. We can't set the error state on the pager at that point because the pager
2624 may not be open yet. However, this is a fatal error state, so abort the codec */
2625 if(ctx->plaintext_header_sz < 0) {
2626 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error invalid ctx->plaintext_header_sz: %d", ctx->plaintext_header_sz);
2627 sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
2628 return NULL;
2631 if(pgno == 1) /* adjust starting pointers in data page for header offset on first page*/
2632 offset = ctx->plaintext_header_sz ? ctx->plaintext_header_sz : FILE_HEADER_SZ;
2635 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3Codec: switch mode=%d offset=%d", mode, offset);
2636 switch(mode) {
2637 case CODEC_READ_OP: /* decrypt */
2638 if(pgno == 1) /* copy initial part of file header or SQLite magic to buffer */
2639 memcpy(ctx->buffer, ctx->plaintext_header_sz ? pData : (void *) SQLITE_FILE_HEADER, offset);
2641 rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_DECRYPT, ctx->page_sz - offset, pData + offset, (unsigned char*)ctx->buffer + offset);
2642 #ifdef SQLCIPHER_TEST
2643 if((cipher_test_flags & TEST_FAIL_DECRYPT) > 0 && sqlcipher_get_test_fail()) {
2644 rc = SQLITE_ERROR;
2645 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);
2647 #endif
2648 if(rc != SQLITE_OK) {
2649 /* failure to decrypt a page is considered a permanent error and will render the pager unusable
2650 in order to prevent inconsistent data being loaded into page cache */
2651 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error decrypting page %d data: %d", pgno, rc);
2652 sqlcipher_memset((unsigned char*) ctx->buffer+offset, 0, ctx->page_sz-offset);
2653 sqlcipher_codec_ctx_set_error(ctx, rc);
2654 } else {
2655 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_KEY_USED);
2657 memcpy(pData, ctx->buffer, ctx->page_sz); /* copy buffer data back to pData and return */
2658 return pData;
2659 break;
2661 case CODEC_WRITE_OP: /* encrypt database page, operate on write context and fall through to case 7, so the write context is used*/
2662 cctx = CIPHER_WRITE_CTX;
2664 case CODEC_JOURNAL_OP: /* encrypt journal page, operate on read context use to get the original page data from the database */
2665 if(pgno == 1) { /* copy initial part of file header or salt to buffer */
2666 void *kdf_salt = NULL;
2667 /* retrieve the kdf salt */
2668 if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &kdf_salt)) != SQLITE_OK) {
2669 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error retrieving salt: %d", rc);
2670 sqlcipher_codec_ctx_set_error(ctx, rc);
2671 return NULL;
2673 memcpy(ctx->buffer, ctx->plaintext_header_sz ? pData : kdf_salt, offset);
2675 rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_ENCRYPT, ctx->page_sz - offset, pData + offset, (unsigned char*)ctx->buffer + offset);
2676 #ifdef SQLCIPHER_TEST
2677 if((cipher_test_flags & TEST_FAIL_ENCRYPT) > 0 && sqlcipher_get_test_fail()) {
2678 rc = SQLITE_ERROR;
2679 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);
2681 #endif
2682 if(rc != SQLITE_OK) {
2683 /* failure to encrypt a page is considered a permanent error and will render the pager unusable
2684 in order to prevent corrupted pages from being written to the main databased when using WAL */
2685 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error encrypting page %d data: %d", pgno, rc);
2686 sqlcipher_memset((unsigned char*)ctx->buffer+offset, 0, ctx->page_sz-offset);
2687 sqlcipher_codec_ctx_set_error(ctx, rc);
2688 return NULL;
2690 SQLCIPHER_FLAG_SET(ctx->flags, CIPHER_FLAG_KEY_USED);
2691 return ctx->buffer; /* return persistent buffer data, pData remains intact */
2692 break;
2694 default:
2695 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3Codec: error unsupported codec mode %d", mode);
2696 sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); /* unsupported mode, set error */
2697 return pData;
2698 break;
2702 static void sqlite3FreeCodecArg(void *pCodecArg) {
2703 codec_ctx *ctx = (codec_ctx *) pCodecArg;
2704 if(pCodecArg == NULL) return;
2705 sqlcipher_codec_ctx_free(&ctx); /* wipe and free allocated memory for the context */
2706 sqlcipher_deactivate(); /* cleanup related structures, OpenSSL etc, when codec is detatched */
2709 int sqlcipherCodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) {
2710 struct Db *pDb = &db->aDb[nDb];
2712 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: db=%p, nDb=%d", db, nDb);
2714 if(nKey && zKey && pDb->pBt) {
2715 int rc;
2716 Pager *pPager = pDb->pBt->pBt->pPager;
2717 sqlite3_file *fd;
2718 codec_ctx *ctx;
2720 ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
2722 if(ctx != NULL && SQLCIPHER_FLAG_GET(ctx->flags, CIPHER_FLAG_KEY_USED)) {
2723 /* there is already a codec attached to this database, so we should not proceed */
2724 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: no codec attached to db");
2725 return SQLITE_OK;
2728 /* check if the sqlite3_file is open, and if not force handle to NULL */
2729 if((fd = sqlite3PagerFile(pPager))->pMethods == 0) fd = NULL;
2731 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlcipher_activate()");
2732 sqlcipher_activate(); /* perform internal initialization for sqlcipher */
2734 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: entering database mutex %p", db->mutex);
2735 sqlite3_mutex_enter(db->mutex);
2736 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: entered database mutex %p", db->mutex);
2738 /* point the internal codec argument against the contet to be prepared */
2739 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlcipher_codec_ctx_init()");
2740 rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, zKey, nKey);
2742 if(rc != SQLITE_OK) {
2743 /* initialization failed, do not attach potentially corrupted context */
2744 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: context initialization failed, forcing error state with rc=%d", rc);
2745 /* force an error at the pager level, such that even the upstream caller ignores the return code
2746 the pager will be in an error state and will process no further operations */
2747 sqlite3pager_error(pPager, rc);
2748 pDb->pBt->pBt->db->errCode = rc;
2749 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: leaving database mutex %p (early return on rc=%d)", db->mutex, rc);
2750 sqlite3_mutex_leave(db->mutex);
2751 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: left database mutex %p (early return on rc=%d)", db->mutex, rc);
2752 return rc;
2755 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlcipherPagerSetCodec()");
2756 sqlcipherPagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL, sqlite3FreeCodecArg, (void *) ctx);
2758 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling codec_set_btree_to_codec_pagesize()");
2759 codec_set_btree_to_codec_pagesize(db, pDb, ctx);
2761 /* force secure delete. This has the benefit of wiping internal data when deleted
2762 and also ensures that all pages are written to disk (i.e. not skipped by
2763 sqlite3PagerDontWrite optimizations) */
2764 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlite3BtreeSecureDelete()");
2765 sqlite3BtreeSecureDelete(pDb->pBt, 1);
2767 /* if fd is null, then this is an in-memory database and
2768 we dont' want to overwrite the AutoVacuum settings
2769 if not null, then set to the default */
2770 if(fd != NULL) {
2771 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecAttach: calling sqlite3BtreeSetAutoVacuum()");
2772 sqlite3BtreeSetAutoVacuum(pDb->pBt, SQLITE_DEFAULT_AUTOVACUUM);
2774 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: leaving database mutex %p", db->mutex);
2775 sqlite3_mutex_leave(db->mutex);
2776 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlcipherCodecAttach: left database mutex %p", db->mutex);
2778 return SQLITE_OK;
2781 int sqlcipher_find_db_index(sqlite3 *db, const char *zDb) {
2782 int db_index;
2783 if(zDb == NULL){
2784 return 0;
2786 for(db_index = 0; db_index < db->nDb; db_index++) {
2787 struct Db *pDb = &db->aDb[db_index];
2788 if(strcmp(pDb->zDbSName, zDb) == 0) {
2789 return db_index;
2792 return 0;
2795 void sqlite3_activate_see(const char* in) {
2796 /* do nothing, security enhancements are always active */
2799 int sqlite3_key(sqlite3 *db, const void *pKey, int nKey) {
2800 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_key: db=%p", db);
2801 return sqlite3_key_v2(db, "main", pKey, nKey);
2804 int sqlite3_key_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) {
2805 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_key_v2: db=%p zDb=%s", db, zDb);
2806 /* attach key if db and pKey are not null and nKey is > 0 */
2807 if(db && pKey && nKey) {
2808 int db_index = sqlcipher_find_db_index(db, zDb);
2809 return sqlcipherCodecAttach(db, db_index, pKey, nKey);
2811 sqlcipher_log(SQLCIPHER_LOG_WARN, SQLCIPHER_LOG_CORE, "sqlite3_key_v2: no key provided");
2812 return SQLITE_ERROR;
2815 int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) {
2816 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey: db=%p", db);
2817 return sqlite3_rekey_v2(db, "main", pKey, nKey);
2820 /* sqlite3_rekey_v2
2821 ** Given a database, this will reencrypt the database using a new key.
2822 ** There is only one possible modes of operation - to encrypt a database
2823 ** that is already encrpyted. If the database is not already encrypted
2824 ** this should do nothing
2825 ** The proposed logic for this function follows:
2826 ** 1. Determine if the database is already encryptped
2827 ** 2. If there is NOT already a key present do nothing
2828 ** 3. If there is a key present, re-encrypt the database with the new key
2830 int sqlite3_rekey_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) {
2831 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: db=%p zDb=%s", db, zDb);
2832 if(db && pKey && nKey) {
2833 int db_index = sqlcipher_find_db_index(db, zDb);
2834 struct Db *pDb = &db->aDb[db_index];
2835 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: database zDb=%p db_index:%d", zDb, db_index);
2836 if(pDb->pBt) {
2837 codec_ctx *ctx;
2838 int rc, page_count;
2839 Pgno pgno;
2840 PgHdr *page;
2841 Pager *pPager = pDb->pBt->pBt->pPager;
2843 ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
2845 if(ctx == NULL) {
2846 /* there was no codec attached to this database, so this should do nothing! */
2847 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);
2848 return SQLITE_MISUSE;
2851 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: entering database mutex %p", db->mutex);
2852 sqlite3_mutex_enter(db->mutex);
2853 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: entered database mutex %p", db->mutex);
2855 codec_set_pass_key(db, db_index, pKey, nKey, CIPHER_WRITE_CTX);
2857 /* do stuff here to rewrite the database
2858 ** 1. Create a transaction on the database
2859 ** 2. Iterate through each page, reading it and then writing it.
2860 ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
2861 ** note: don't deallocate rekey since it may be used in a subsequent iteration
2863 rc = sqlite3BtreeBeginTrans(pDb->pBt, 1, 0); /* begin write transaction */
2864 sqlite3PagerPagecount(pPager, &page_count);
2865 for(pgno = 1; rc == SQLITE_OK && pgno <= (unsigned int)page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
2866 if(!sqlite3pager_is_sj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
2867 rc = sqlite3PagerGet(pPager, pgno, &page, 0);
2868 if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */
2869 rc = sqlite3PagerWrite(page);
2870 if(rc == SQLITE_OK) {
2871 sqlite3PagerUnref(page);
2872 } else {
2873 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: error %d occurred writing page %d", rc, pgno);
2875 } else {
2876 sqlcipher_log(SQLCIPHER_LOG_ERROR, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: error %d occurred reading page %d", rc, pgno);
2881 /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
2882 if(rc == SQLITE_OK) {
2883 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: committing");
2884 rc = sqlite3BtreeCommit(pDb->pBt);
2885 sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX);
2886 } else {
2887 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlite3_rekey_v2: rollback");
2888 sqlite3BtreeRollback(pDb->pBt, SQLITE_ABORT_ROLLBACK, 0);
2891 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: leaving database mutex %p", db->mutex);
2892 sqlite3_mutex_leave(db->mutex);
2893 sqlcipher_log(SQLCIPHER_LOG_TRACE, SQLCIPHER_LOG_MUTEX, "sqlite3_rekey_v2: left database mutex %p", db->mutex);
2895 return SQLITE_OK;
2897 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);
2898 return SQLITE_ERROR;
2901 void sqlcipherCodecGetKey(sqlite3* db, int nDb, void **zKey, int *nKey) {
2902 struct Db *pDb = &db->aDb[nDb];
2903 sqlcipher_log(SQLCIPHER_LOG_DEBUG, SQLCIPHER_LOG_CORE, "sqlcipherCodecGetKey:db=%p, nDb=%d", db, nDb);
2904 if( pDb->pBt ) {
2905 codec_ctx *ctx = (codec_ctx*) sqlcipherPagerGetCodec(pDb->pBt->pBt->pPager);
2907 if(ctx) {
2908 /* pass back the keyspec from the codec, unless PRAGMA cipher_store_pass
2909 is set or keyspec has not yet been derived, in which case pass
2910 back the password key material */
2911 *zKey = ctx->read_ctx->keyspec;
2912 *nKey = ctx->keyspec_sz;
2913 if(ctx->store_pass == 1 || *zKey == NULL) {
2914 *zKey = ctx->read_ctx->pass;
2915 *nKey = ctx->read_ctx->pass_sz;
2917 } else {
2918 *zKey = NULL;
2919 *nKey = 0;
2925 * Implementation of an "export" function that allows a caller
2926 * to duplicate the main database to an attached database. This is intended
2927 * as a conveneince for users who need to:
2929 * 1. migrate from an non-encrypted database to an encrypted database
2930 * 2. move from an encrypted database to a non-encrypted database
2931 * 3. convert beween the various flavors of encrypted databases.
2933 * This implementation is based heavily on the procedure and code used
2934 * in vacuum.c, but is exposed as a function that allows export to any
2935 * named attached database.
2939 ** Finalize a prepared statement. If there was an error, store the
2940 ** text of the error message in *pzErrMsg. Return the result code.
2942 ** Based on vacuumFinalize from vacuum.c
2944 static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
2945 int rc;
2946 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
2947 if( rc ){
2948 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
2950 return rc;
2954 ** Execute zSql on database db. Return an error code.
2956 ** Based on execSql from vacuum.c
2958 static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
2959 sqlite3_stmt *pStmt;
2960 VVA_ONLY( int rc; )
2961 if( !zSql ){
2962 return SQLITE_NOMEM;
2964 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
2965 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
2966 return sqlite3_errcode(db);
2968 VVA_ONLY( rc = ) sqlite3_step(pStmt);
2969 assert( rc!=SQLITE_ROW );
2970 return sqlcipher_finalize(db, pStmt, pzErrMsg);
2974 ** Execute zSql on database db. The statement returns exactly
2975 ** one column. Execute this as SQL on the same database.
2977 ** Based on execExecSql from vacuum.c
2979 static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
2980 sqlite3_stmt *pStmt;
2981 int rc;
2983 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
2984 if( rc!=SQLITE_OK ) return rc;
2986 while( SQLITE_ROW==sqlite3_step(pStmt) ){
2987 rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
2988 if( rc!=SQLITE_OK ){
2989 sqlcipher_finalize(db, pStmt, pzErrMsg);
2990 return rc;
2994 return sqlcipher_finalize(db, pStmt, pzErrMsg);
2998 * copy database and schema from the main database to an attached database
3000 * Based on sqlite3RunVacuum from vacuum.c
3002 void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) {
3003 sqlite3 *db = sqlite3_context_db_handle(context);
3004 const char* targetDb, *sourceDb;
3005 int targetDb_idx = 0;
3006 u64 saved_flags = db->flags; /* Saved value of the db->flags */
3007 u32 saved_mDbFlags = db->mDbFlags; /* Saved value of the db->mDbFlags */
3008 int saved_nChange = db->nChange; /* Saved value of db->nChange */
3009 int saved_nTotalChange = db->nTotalChange; /* Saved value of db->nTotalChange */
3010 u8 saved_mTrace = db->mTrace; /* Saved value of db->mTrace */
3011 int rc = SQLITE_OK; /* Return code from service routines */
3012 char *zSql = NULL; /* SQL statements */
3013 char *pzErrMsg = NULL;
3015 if(argc != 1 && argc != 2) {
3016 rc = SQLITE_ERROR;
3017 pzErrMsg = sqlite3_mprintf("invalid number of arguments (%d) passed to sqlcipher_export", argc);
3018 goto end_of_export;
3021 if(sqlite3_value_type(argv[0]) == SQLITE_NULL) {
3022 rc = SQLITE_ERROR;
3023 pzErrMsg = sqlite3_mprintf("target database can't be NULL");
3024 goto end_of_export;
3027 targetDb = (const char*) sqlite3_value_text(argv[0]);
3028 sourceDb = "main";
3030 if(argc == 2) {
3031 if(sqlite3_value_type(argv[1]) == SQLITE_NULL) {
3032 rc = SQLITE_ERROR;
3033 pzErrMsg = sqlite3_mprintf("target database can't be NULL");
3034 goto end_of_export;
3036 sourceDb = (char *) sqlite3_value_text(argv[1]);
3040 /* if the name of the target is not main, but the index returned is zero
3041 there is a mismatch and we should not proceed */
3042 targetDb_idx = sqlcipher_find_db_index(db, targetDb);
3043 if(targetDb_idx == 0 && targetDb != NULL && sqlite3_stricmp("main", targetDb) != 0) {
3044 rc = SQLITE_ERROR;
3045 pzErrMsg = sqlite3_mprintf("unknown database %s", targetDb);
3046 goto end_of_export;
3048 db->init.iDb = targetDb_idx;
3050 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
3051 db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
3052 db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_Defensive | SQLITE_CountRows);
3053 db->mTrace = 0;
3055 /* Query the schema of the main database. Create a mirror schema
3056 ** in the temporary database.
3058 zSql = sqlite3_mprintf(
3059 "SELECT sql "
3060 " FROM %s.sqlite_schema WHERE type='table' AND name!='sqlite_sequence'"
3061 " AND rootpage>0"
3062 , sourceDb);
3063 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3064 if( rc!=SQLITE_OK ) goto end_of_export;
3065 sqlite3_free(zSql);
3067 zSql = sqlite3_mprintf(
3068 "SELECT sql "
3069 " FROM %s.sqlite_schema WHERE sql LIKE 'CREATE INDEX %%' "
3070 , sourceDb);
3071 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3072 if( rc!=SQLITE_OK ) goto end_of_export;
3073 sqlite3_free(zSql);
3075 zSql = sqlite3_mprintf(
3076 "SELECT sql "
3077 " FROM %s.sqlite_schema WHERE sql LIKE 'CREATE UNIQUE INDEX %%'"
3078 , sourceDb);
3079 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3080 if( rc!=SQLITE_OK ) goto end_of_export;
3081 sqlite3_free(zSql);
3083 /* Loop through the tables in the main database. For each, do
3084 ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy
3085 ** the contents to the temporary database.
3087 zSql = sqlite3_mprintf(
3088 "SELECT 'INSERT INTO %s.' || quote(name) "
3089 "|| ' SELECT * FROM %s.' || quote(name) || ';'"
3090 "FROM %s.sqlite_schema "
3091 "WHERE type = 'table' AND name!='sqlite_sequence' "
3092 " AND rootpage>0"
3093 , targetDb, sourceDb, sourceDb);
3094 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3095 if( rc!=SQLITE_OK ) goto end_of_export;
3096 sqlite3_free(zSql);
3098 /* Copy over the contents of the sequence table
3100 zSql = sqlite3_mprintf(
3101 "SELECT 'INSERT INTO %s.' || quote(name) "
3102 "|| ' SELECT * FROM %s.' || quote(name) || ';' "
3103 "FROM %s.sqlite_schema WHERE name=='sqlite_sequence';"
3104 , targetDb, sourceDb, targetDb);
3105 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
3106 if( rc!=SQLITE_OK ) goto end_of_export;
3107 sqlite3_free(zSql);
3109 /* Copy the triggers, views, and virtual tables from the main database
3110 ** over to the temporary database. None of these objects has any
3111 ** associated storage, so all we have to do is copy their entries
3112 ** from the SQLITE_MASTER table.
3114 zSql = sqlite3_mprintf(
3115 "INSERT INTO %s.sqlite_schema "
3116 " SELECT type, name, tbl_name, rootpage, sql"
3117 " FROM %s.sqlite_schema"
3118 " WHERE type='view' OR type='trigger'"
3119 " OR (type='table' AND rootpage=0)"
3120 , targetDb, sourceDb);
3121 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql);
3122 if( rc!=SQLITE_OK ) goto end_of_export;
3123 sqlite3_free(zSql);
3125 zSql = NULL;
3126 end_of_export:
3127 db->init.iDb = 0;
3128 db->flags = saved_flags;
3129 db->mDbFlags = saved_mDbFlags;
3130 db->nChange = saved_nChange;
3131 db->nTotalChange = saved_nTotalChange;
3132 db->mTrace = saved_mTrace;
3134 if(zSql) sqlite3_free(zSql);
3136 if(rc) {
3137 if(pzErrMsg != NULL) {
3138 sqlite3_result_error(context, pzErrMsg, -1);
3139 sqlite3DbFree(db, pzErrMsg);
3140 } else {
3141 sqlite3_result_error(context, sqlite3ErrStr(rc), -1);
3145 #endif
3146 /* END SQLCIPHER */