1 /*
2 ** SQLCipher
3 ** http://sqlcipher.net
4 **
5 ** Copyright (c) 2008 - 2013, 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 **
30 */
31 /* BEGIN SQLCIPHER */
32 #ifdef SQLITE_HAS_CODEC
33
34 #include "sqliteInt.h"
35 #include "btreeInt.h"
36 #include "sqlcipher.h"
37 #include "crypto.h"
38 #ifndef OMIT_MEMLOCK
39 #if defined(__unix__) || defined(__APPLE__) || defined(_AIX)
40 #include <errno.h>
41 #include <unistd.h>
42 #include <sys/resource.h>
43 #include <sys/mman.h>
44 #elif defined(_WIN32)
45 #include <windows.h>
46 #endif
47 #endif
48
49 /* the default implementation of SQLCipher uses a cipher_ctx
50 to keep track of read / write state separately. The following
51 struct and associated functions are defined here */
52 typedef struct {
53 int store_pass;
54 int derive_key;
55 int kdf_iter;
56 int fast_kdf_iter;
57 int key_sz;
58 int iv_sz;
59 int block_sz;
60 int pass_sz;
61 int reserve_sz;
62 int hmac_sz;
63 int keyspec_sz;
64 unsigned int flags;
65 unsigned char *key;
66 unsigned char *hmac_key;
67 unsigned char *pass;
68 char *keyspec;
69 sqlcipher_provider *provider;
70 void *provider_ctx;
71 } cipher_ctx;
72
73 static unsigned int default_flags = DEFAULT_CIPHER_FLAGS;
74 static unsigned char hmac_salt_mask = HMAC_SALT_MASK;
75 static int default_kdf_iter = PBKDF2_ITER;
76 static int default_page_size = 1024;
77 static unsigned int sqlcipher_activate_count = 0;
78 static sqlite3_mutex* sqlcipher_provider_mutex = NULL;
79 static sqlcipher_provider *default_provider = NULL;
80
81 struct codec_ctx {
82 int kdf_salt_sz;
83 int page_sz;
84 unsigned char *kdf_salt;
85 unsigned char *hmac_kdf_salt;
86 unsigned char *buffer;
87 Btree *pBt;
88 cipher_ctx *read_ctx;
89 cipher_ctx *write_ctx;
90 unsigned int skip_read_hmac;
91 unsigned int need_kdf_salt;
92 };
93
sqlcipher_register_provider(sqlcipher_provider * p)94 int sqlcipher_register_provider(sqlcipher_provider *p) {
95 CODEC_TRACE_MUTEX("sqlcipher_register_provider: entering sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
96 sqlite3_mutex_enter(sqlcipher_provider_mutex);
97 CODEC_TRACE_MUTEX("sqlcipher_register_provider: entered sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
98
99 if(default_provider != NULL && default_provider != p) {
100 /* only free the current registerd provider if it has been initialized
101 and it isn't a pointer to the same provider passed to the function
102 (i.e. protect against a caller calling register twice for the same provider) */
103 sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
104 }
105 default_provider = p;
106 CODEC_TRACE_MUTEX("sqlcipher_register_provider: leaving sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
107 sqlite3_mutex_leave(sqlcipher_provider_mutex);
108 CODEC_TRACE_MUTEX("sqlcipher_register_provider: left sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
109
110 return SQLITE_OK;
111 }
112
113 /* return a pointer to the currently registered provider. This will
114 allow an application to fetch the current registered provider and
115 make minor changes to it */
sqlcipher_get_provider()116 sqlcipher_provider* sqlcipher_get_provider() {
117 return default_provider;
118 }
119
sqlcipher_activate()120 void sqlcipher_activate() {
121 CODEC_TRACE_MUTEX("sqlcipher_activate: entering static master mutex\n");
122 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
123 CODEC_TRACE_MUTEX("sqlcipher_activate: entered static master mutex\n");
124
125 if(sqlcipher_provider_mutex == NULL) {
126 /* allocate a new mutex to guard access to the provider */
127 CODEC_TRACE_MUTEX("sqlcipher_activate: allocating sqlcipher provider mutex\n");
128 sqlcipher_provider_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
129 CODEC_TRACE_MUTEX("sqlcipher_activate: allocated sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
130 }
131
132 /* check to see if there is a provider registered at this point
133 if there no provider registered at this point, register the
134 default provider */
135 if(sqlcipher_get_provider() == NULL) {
136 sqlcipher_provider *p = sqlcipher_malloc(sizeof(sqlcipher_provider));
137 #if defined (SQLCIPHER_CRYPTO_CC)
138 extern int sqlcipher_cc_setup(sqlcipher_provider *p);
139 sqlcipher_cc_setup(p);
140 #elif defined (SQLCIPHER_CRYPTO_LIBTOMCRYPT)
141 extern int sqlcipher_ltc_setup(sqlcipher_provider *p);
142 sqlcipher_ltc_setup(p);
143 #elif defined (SQLCIPHER_CRYPTO_OPENSSL)
144 extern int sqlcipher_openssl_setup(sqlcipher_provider *p);
145 sqlcipher_openssl_setup(p);
146 #else
147 #error "NO DEFAULT SQLCIPHER CRYPTO PROVIDER DEFINED"
148 #endif
149 CODEC_TRACE("sqlcipher_activate: calling sqlcipher_register_provider(%p)\n", p);
150 sqlcipher_register_provider(p);
151 CODEC_TRACE("sqlcipher_activate: called sqlcipher_register_provider(%p)\n",p);
152 }
153
154 sqlcipher_activate_count++; /* increment activation count */
155
156 CODEC_TRACE_MUTEX("sqlcipher_activate: leaving static master mutex\n");
157 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
158 CODEC_TRACE_MUTEX("sqlcipher_activate: left static master mutex\n");
159 }
160
sqlcipher_deactivate()161 void sqlcipher_deactivate() {
162 CODEC_TRACE_MUTEX("sqlcipher_deactivate: entering static master mutex\n");
163 sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
164 CODEC_TRACE_MUTEX("sqlcipher_deactivate: entered static master mutex\n");
165
166 sqlcipher_activate_count--;
167 /* if no connections are using sqlcipher, cleanup globals */
168 if(sqlcipher_activate_count < 1) {
169 int rc;
170 CODEC_TRACE_MUTEX("sqlcipher_deactivate: entering sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
171 sqlite3_mutex_enter(sqlcipher_provider_mutex);
172 CODEC_TRACE_MUTEX("sqlcipher_deactivate: entered sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
173
174 if(default_provider != NULL) {
175 sqlcipher_free(default_provider, sizeof(sqlcipher_provider));
176 default_provider = NULL;
177 }
178
179 CODEC_TRACE_MUTEX("sqlcipher_deactivate: leaving sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
180 sqlite3_mutex_leave(sqlcipher_provider_mutex);
181 CODEC_TRACE_MUTEX("sqlcipher_deactivate: left sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
182
183 /* last connection closed, free provider mutex*/
184 CODEC_TRACE_MUTEX("sqlcipher_deactivate: freeing sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
185 sqlite3_mutex_free(sqlcipher_provider_mutex);
186 CODEC_TRACE_MUTEX("sqlcipher_deactivate: freed sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
187
188 sqlcipher_provider_mutex = NULL;
189
190 sqlcipher_activate_count = 0; /* reset activation count */
191 }
192
193 CODEC_TRACE_MUTEX("sqlcipher_deactivate: leaving static master mutex\n");
194 sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
195 CODEC_TRACE_MUTEX("sqlcipher_deactivate: left static master mutex\n");
196 }
197
198 /* constant time memset using volitile to avoid having the memset
199 optimized out by the compiler.
200 Note: As suggested by Joachim Schipper (joachim.schipper@fox-it.com)
201 */
sqlcipher_memset(void * v,unsigned char value,int len)202 void* sqlcipher_memset(void *v, unsigned char value, int len) {
203 int i = 0;
204 volatile unsigned char *a = v;
205
206 if (v == NULL) return v;
207
208 CODEC_TRACE("sqlcipher_memset: setting %p[0-%d]=%d)\n", a, len, value);
209 for(i = 0; i < len; i++) {
210 a[i] = value;
211 }
212
213 return v;
214 }
215
216 /* constant time memory check tests every position of a memory segement
217 matches a single value (i.e. the memory is all zeros)
218 returns 0 if match, 1 of no match */
sqlcipher_ismemset(const void * v,unsigned char value,int len)219 int sqlcipher_ismemset(const void *v, unsigned char value, int len) {
220 const unsigned char *a = v;
221 int i = 0, result = 0;
222
223 for(i = 0; i < len; i++) {
224 result |= a[i] ^ value;
225 }
226
227 return (result != 0);
228 }
229
230 /* constant time memory comparison routine.
231 returns 0 if match, 1 if no match */
sqlcipher_memcmp(const void * v0,const void * v1,int len)232 int sqlcipher_memcmp(const void *v0, const void *v1, int len) {
233 const unsigned char *a0 = v0, *a1 = v1;
234 int i = 0, result = 0;
235
236 for(i = 0; i < len; i++) {
237 result |= a0[i] ^ a1[i];
238 }
239
240 return (result != 0);
241 }
242
243 /**
244 * Free and wipe memory. Uses SQLites internal sqlite3_free so that memory
245 * can be countend and memory leak detection works in the test suite.
246 * If ptr is not null memory will be freed.
247 * If sz is greater than zero, the memory will be overwritten with zero before it is freed
248 * If sz is > 0, and not compiled with OMIT_MEMLOCK, system will attempt to unlock the
249 * memory segment so it can be paged
250 */
sqlcipher_free(void * ptr,int sz)251 void sqlcipher_free(void *ptr, int sz) {
252 if(ptr) {
253 if(sz > 0) {
254 #ifndef OMIT_MEMLOCK
255 int rc;
256 #if defined(__unix__) || defined(__APPLE__)
257 unsigned long pagesize = sysconf(_SC_PAGESIZE);
258 unsigned long offset = (unsigned long) ptr % pagesize;
259 #endif
260 #endif
261 CODEC_TRACE("sqlcipher_free: calling sqlcipher_memset(%p,0,%d)\n", ptr, sz);
262 sqlcipher_memset(ptr, 0, sz);
263 #ifndef OMIT_MEMLOCK
264 #if defined(__unix__) || defined(__APPLE__)
265 CODEC_TRACE("sqlcipher_free: calling munlock(%p,%lu)\n", ptr - offset, sz + offset);
266 rc = munlock(ptr - offset, sz + offset);
267 if(rc!=0) {
268 CODEC_TRACE("sqlcipher_free: munlock(%p,%lu) returned %d errno=%d\n", ptr - offset, sz + offset, rc, errno);
269 }
270 #elif defined(_WIN32)
271 #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP))
272 rc = VirtualUnlock(ptr, sz);
273 if(!rc) {
274 CODEC_TRACE("sqlcipher_free: VirtualUnlock(%p,%d) returned %d LastError=%d\n", ptr, sz, rc, GetLastError());
275 }
276 #endif
277 #endif
278 #endif
279 }
280 sqlite3_free(ptr);
281 }
282 }
283
284 /**
285 * allocate memory. Uses sqlite's internall malloc wrapper so memory can be
286 * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK
287 * attempts to lock the memory pages so sensitive information won't be swapped
288 */
sqlcipher_malloc(int sz)289 void* sqlcipher_malloc(int sz) {
290 void *ptr;
291 CODEC_TRACE("sqlcipher_malloc: calling sqlite3Malloc(%d)\n", sz);
292 ptr = sqlite3Malloc(sz);
293 CODEC_TRACE("sqlcipher_malloc: calling sqlcipher_memset(%p,0,%d)\n", ptr, sz);
294 sqlcipher_memset(ptr, 0, sz);
295 #ifndef OMIT_MEMLOCK
296 if(ptr) {
297 int rc;
298 #if defined(__unix__) || defined(__APPLE__)
299 unsigned long pagesize = sysconf(_SC_PAGESIZE);
300 unsigned long offset = (unsigned long) ptr % pagesize;
301 CODEC_TRACE("sqlcipher_malloc: calling mlock(%p,%lu); _SC_PAGESIZE=%lu\n", ptr - offset, sz + offset, pagesize);
302 rc = mlock(ptr - offset, sz + offset);
303 if(rc!=0) {
304 CODEC_TRACE("sqlcipher_malloc: mlock(%p,%lu) returned %d errno=%d\n", ptr - offset, sz + offset, rc, errno);
305 }
306 #elif defined(_WIN32)
307 #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP))
308 rc = VirtualLock(ptr, sz);
309 if(rc==0) {
310 CODEC_TRACE("sqlcipher_malloc: VirtualLock(%p,%d) returned %d LastError=%d\n", ptr, sz, rc, GetLastError());
311 }
312 #endif
313 #endif
314 }
315 #endif
316 return ptr;
317 }
318
319
320 /**
321 * Initialize new cipher_ctx struct. This function will allocate memory
322 * for the cipher context and for the key
323 *
324 * returns SQLITE_OK if initialization was successful
325 * returns SQLITE_NOMEM if an error occured allocating memory
326 */
sqlcipher_cipher_ctx_init(cipher_ctx ** iCtx)327 static int sqlcipher_cipher_ctx_init(cipher_ctx **iCtx) {
328 int rc;
329 cipher_ctx *ctx;
330 CODEC_TRACE("sqlcipher_cipher_ctx_init: allocating context\n");
331 *iCtx = (cipher_ctx *) sqlcipher_malloc(sizeof(cipher_ctx));
332 ctx = *iCtx;
333 if(ctx == NULL) return SQLITE_NOMEM;
334
335 CODEC_TRACE("sqlcipher_cipher_ctx_init: allocating provider\n");
336 ctx->provider = (sqlcipher_provider *) sqlcipher_malloc(sizeof(sqlcipher_provider));
337 if(ctx->provider == NULL) return SQLITE_NOMEM;
338
339 /* make a copy of the provider to be used for the duration of the context */
340 CODEC_TRACE_MUTEX("sqlcipher_cipher_ctx_init: entering sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
341 sqlite3_mutex_enter(sqlcipher_provider_mutex);
342 CODEC_TRACE_MUTEX("sqlcipher_cipher_ctx_init: entered sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
343
344 memcpy(ctx->provider, default_provider, sizeof(sqlcipher_provider));
345
346 CODEC_TRACE_MUTEX("sqlcipher_cipher_ctx_init: leaving sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
347 sqlite3_mutex_leave(sqlcipher_provider_mutex);
348 CODEC_TRACE_MUTEX("sqlcipher_cipher_ctx_init: left sqlcipher provider mutex %p\n", sqlcipher_provider_mutex);
349
350 CODEC_TRACE("sqlcipher_cipher_ctx_init: calling provider ctx_init\n");
351 if((rc = ctx->provider->ctx_init(&ctx->provider_ctx)) != SQLITE_OK) return rc;
352
353 CODEC_TRACE("sqlcipher_cipher_ctx_init: allocating key\n");
354 ctx->key = (unsigned char *) sqlcipher_malloc(CIPHER_MAX_KEY_SZ);
355
356 CODEC_TRACE("sqlcipher_cipher_ctx_init: allocating hmac_key\n");
357 ctx->hmac_key = (unsigned char *) sqlcipher_malloc(CIPHER_MAX_KEY_SZ);
358
359 if(ctx->key == NULL) return SQLITE_NOMEM;
360 if(ctx->hmac_key == NULL) return SQLITE_NOMEM;
361
362 /* setup default flags */
363 ctx->flags = default_flags;
364
365 return SQLITE_OK;
366 }
367
368 /**
369 * Free and wipe memory associated with a cipher_ctx
370 */
sqlcipher_cipher_ctx_free(cipher_ctx ** iCtx)371 static void sqlcipher_cipher_ctx_free(cipher_ctx **iCtx) {
372 cipher_ctx *ctx = *iCtx;
373 CODEC_TRACE("cipher_ctx_free: entered iCtx=%p\n", iCtx);
374 ctx->provider->ctx_free(&ctx->provider_ctx);
375 sqlcipher_free(ctx->provider, sizeof(sqlcipher_provider));
376 sqlcipher_free(ctx->key, ctx->key_sz);
377 sqlcipher_free(ctx->hmac_key, ctx->key_sz);
378 sqlcipher_free(ctx->pass, ctx->pass_sz);
379 sqlcipher_free(ctx->keyspec, ctx->keyspec_sz);
380 sqlcipher_free(ctx, sizeof(cipher_ctx));
381 }
382
383 /**
384 * Compare one cipher_ctx to another.
385 *
386 * returns 0 if all the parameters (except the derived key data) are the same
387 * returns 1 otherwise
388 */
sqlcipher_cipher_ctx_cmp(cipher_ctx * c1,cipher_ctx * c2)389 static int sqlcipher_cipher_ctx_cmp(cipher_ctx *c1, cipher_ctx *c2) {
390 int are_equal = (
391 c1->iv_sz == c2->iv_sz
392 && c1->kdf_iter == c2->kdf_iter
393 && c1->fast_kdf_iter == c2->fast_kdf_iter
394 && c1->key_sz == c2->key_sz
395 && c1->pass_sz == c2->pass_sz
396 && c1->flags == c2->flags
397 && c1->hmac_sz == c2->hmac_sz
398 && c1->provider->ctx_cmp(c1->provider_ctx, c2->provider_ctx)
399 && (
400 c1->pass == c2->pass
401 || !sqlcipher_memcmp((const unsigned char*)c1->pass,
402 (const unsigned char*)c2->pass,
403 c1->pass_sz)
404 ));
405
406 CODEC_TRACE("sqlcipher_cipher_ctx_cmp: entered \
407 c1=%p c2=%p \
408 c1->iv_sz=%d c2->iv_sz=%d \
409 c1->kdf_iter=%d c2->kdf_iter=%d \
410 c1->fast_kdf_iter=%d c2->fast_kdf_iter=%d \
411 c1->key_sz=%d c2->key_sz=%d \
412 c1->pass_sz=%d c2->pass_sz=%d \
413 c1->flags=%d c2->flags=%d \
414 c1->hmac_sz=%d c2->hmac_sz=%d \
415 c1->provider_ctx=%p c2->provider_ctx=%p \
416 c1->pass=%p c2->pass=%p \
417 c1->pass=%s c2->pass=%s \
418 provider->ctx_cmp=%d \
419 sqlcipher_memcmp=%d \
420 are_equal=%d \
421 \n",
422 c1, c2,
423 c1->iv_sz, c2->iv_sz,
424 c1->kdf_iter, c2->kdf_iter,
425 c1->fast_kdf_iter, c2->fast_kdf_iter,
426 c1->key_sz, c2->key_sz,
427 c1->pass_sz, c2->pass_sz,
428 c1->flags, c2->flags,
429 c1->hmac_sz, c2->hmac_sz,
430 c1->provider_ctx, c2->provider_ctx,
431 c1->pass, c2->pass,
432 c1->pass, c2->pass,
433 c1->provider->ctx_cmp(c1->provider_ctx, c2->provider_ctx),
434 (c1->pass == NULL || c2->pass == NULL)
435 ? -1 : sqlcipher_memcmp(
436 (const unsigned char*)c1->pass,
437 (const unsigned char*)c2->pass,
438 c1->pass_sz),
439 are_equal
440 );
441
442 return !are_equal; /* return 0 if they are the same, 1 otherwise */
443 }
444
445 /**
446 * Copy one cipher_ctx to another. For instance, assuming that read_ctx is a
447 * fully initialized context, you could copy it to write_ctx and all yet data
448 * and pass information across
449 *
450 * returns SQLITE_OK if initialization was successful
451 * returns SQLITE_NOMEM if an error occured allocating memory
452 */
sqlcipher_cipher_ctx_copy(cipher_ctx * target,cipher_ctx * source)453 static int sqlcipher_cipher_ctx_copy(cipher_ctx *target, cipher_ctx *source) {
454 void *key = target->key;
455 void *hmac_key = target->hmac_key;
456 void *provider = target->provider;
457 void *provider_ctx = target->provider_ctx;
458
459 CODEC_TRACE("sqlcipher_cipher_ctx_copy: entered target=%p, source=%p\n", target, source);
460 sqlcipher_free(target->pass, target->pass_sz);
461 sqlcipher_free(target->keyspec, target->keyspec_sz);
462 memcpy(target, source, sizeof(cipher_ctx));
463
464 target->key = key; //restore pointer to previously allocated key data
465 memcpy(target->key, source->key, CIPHER_MAX_KEY_SZ);
466
467 target->hmac_key = hmac_key; //restore pointer to previously allocated hmac key data
468 memcpy(target->hmac_key, source->hmac_key, CIPHER_MAX_KEY_SZ);
469
470 target->provider = provider; // restore pointer to previouly allocated provider;
471 memcpy(target->provider, source->provider, sizeof(sqlcipher_provider));
472
473 target->provider_ctx = provider_ctx; // restore pointer to previouly allocated provider context;
474 target->provider->ctx_copy(target->provider_ctx, source->provider_ctx);
475
476 if(source->pass && source->pass_sz) {
477 target->pass = sqlcipher_malloc(source->pass_sz);
478 if(target->pass == NULL) return SQLITE_NOMEM;
479 memcpy(target->pass, source->pass, source->pass_sz);
480 }
481 if(source->keyspec && source->keyspec_sz) {
482 target->keyspec = sqlcipher_malloc(source->keyspec_sz);
483 if(target->keyspec == NULL) return SQLITE_NOMEM;
484 memcpy(target->keyspec, source->keyspec, source->keyspec_sz);
485 }
486 return SQLITE_OK;
487 }
488
489 /**
490 * Set the keyspec for the cipher_ctx
491 *
492 * returns SQLITE_OK if assignment was successfull
493 * returns SQLITE_NOMEM if an error occured allocating memory
494 */
sqlcipher_cipher_ctx_set_keyspec(cipher_ctx * ctx,const unsigned char * key,int key_sz,const unsigned char * salt,int salt_sz)495 static int sqlcipher_cipher_ctx_set_keyspec(cipher_ctx *ctx, const unsigned char *key, int key_sz, const unsigned char *salt, int salt_sz) {
496
497 /* free, zero existing pointers and size */
498 sqlcipher_free(ctx->keyspec, ctx->keyspec_sz);
499 ctx->keyspec = NULL;
500 ctx->keyspec_sz = 0;
501
502 /* establic a hex-formated key specification, containing the raw encryption key and
503 the salt used to generate it */
504 ctx->keyspec_sz = ((key_sz + salt_sz) * 2) + 3;
505 ctx->keyspec = sqlcipher_malloc(ctx->keyspec_sz);
506 if(ctx->keyspec == NULL) return SQLITE_NOMEM;
507
508 ctx->keyspec[0] = 'x';
509 ctx->keyspec[1] = '\'';
510 cipher_bin2hex(key, key_sz, ctx->keyspec + 2);
511 cipher_bin2hex(salt, salt_sz, ctx->keyspec + (key_sz * 2) + 2);
512 ctx->keyspec[ctx->keyspec_sz - 1] = '\'';
513 return SQLITE_OK;
514 }
515
sqlcipher_codec_get_store_pass(codec_ctx * ctx)516 int sqlcipher_codec_get_store_pass(codec_ctx *ctx) {
517 return ctx->read_ctx->store_pass;
518 }
519
sqlcipher_codec_set_store_pass(codec_ctx * ctx,int value)520 void sqlcipher_codec_set_store_pass(codec_ctx *ctx, int value) {
521 ctx->read_ctx->store_pass = value;
522 }
523
sqlcipher_codec_get_pass(codec_ctx * ctx,void ** zKey,int * nKey)524 void sqlcipher_codec_get_pass(codec_ctx *ctx, void **zKey, int *nKey) {
525 *zKey = ctx->read_ctx->pass;
526 *nKey = ctx->read_ctx->pass_sz;
527 }
528
529 /**
530 * Set the passphrase for the cipher_ctx
531 *
532 * returns SQLITE_OK if assignment was successfull
533 * returns SQLITE_NOMEM if an error occured allocating memory
534 */
sqlcipher_cipher_ctx_set_pass(cipher_ctx * ctx,const void * zKey,int nKey)535 static int sqlcipher_cipher_ctx_set_pass(cipher_ctx *ctx, const void *zKey, int nKey) {
536
537 /* free, zero existing pointers and size */
538 sqlcipher_free(ctx->pass, ctx->pass_sz);
539 ctx->pass = NULL;
540 ctx->pass_sz = 0;
541
542 if(zKey && nKey) { /* if new password is provided, copy it */
543 ctx->pass_sz = nKey;
544 ctx->pass = sqlcipher_malloc(nKey);
545 if(ctx->pass == NULL) return SQLITE_NOMEM;
546 memcpy(ctx->pass, zKey, nKey);
547 }
548 return SQLITE_OK;
549 }
550
sqlcipher_codec_ctx_set_pass(codec_ctx * ctx,const void * zKey,int nKey,int for_ctx)551 int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int for_ctx) {
552 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
553 int rc;
554
555 if((rc = sqlcipher_cipher_ctx_set_pass(c_ctx, zKey, nKey)) != SQLITE_OK) return rc;
556 c_ctx->derive_key = 1;
557
558 if(for_ctx == 2)
559 if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
560 return rc;
561
562 return SQLITE_OK;
563 }
564
sqlcipher_codec_ctx_set_cipher(codec_ctx * ctx,const char * cipher_name,int for_ctx)565 int sqlcipher_codec_ctx_set_cipher(codec_ctx *ctx, const char *cipher_name, int for_ctx) {
566 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
567 int rc;
568
569 rc = c_ctx->provider->set_cipher(c_ctx->provider_ctx, cipher_name);
570 if(rc != SQLITE_OK){
571 sqlcipher_codec_ctx_set_error(ctx, rc);
572 return rc;
573 }
574 c_ctx->key_sz = c_ctx->provider->get_key_sz(c_ctx->provider_ctx);
575 c_ctx->iv_sz = c_ctx->provider->get_iv_sz(c_ctx->provider_ctx);
576 c_ctx->block_sz = c_ctx->provider->get_block_sz(c_ctx->provider_ctx);
577 c_ctx->hmac_sz = c_ctx->provider->get_hmac_sz(c_ctx->provider_ctx);
578 c_ctx->derive_key = 1;
579
580 if(for_ctx == 2)
581 if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
582 return rc;
583
584 return SQLITE_OK;
585 }
586
sqlcipher_codec_ctx_get_cipher(codec_ctx * ctx,int for_ctx)587 const char* sqlcipher_codec_ctx_get_cipher(codec_ctx *ctx, int for_ctx) {
588 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
589 return c_ctx->provider->get_cipher(c_ctx->provider_ctx);
590 }
591
592 /* set the global default KDF iteration */
sqlcipher_set_default_kdf_iter(int iter)593 void sqlcipher_set_default_kdf_iter(int iter) {
594 default_kdf_iter = iter;
595 }
596
sqlcipher_get_default_kdf_iter()597 int sqlcipher_get_default_kdf_iter() {
598 return default_kdf_iter;
599 }
600
sqlcipher_codec_ctx_set_kdf_iter(codec_ctx * ctx,int kdf_iter,int for_ctx)601 int sqlcipher_codec_ctx_set_kdf_iter(codec_ctx *ctx, int kdf_iter, int for_ctx) {
602 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
603 int rc;
604
605 c_ctx->kdf_iter = kdf_iter;
606 c_ctx->derive_key = 1;
607
608 if(for_ctx == 2)
609 if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
610 return rc;
611
612 return SQLITE_OK;
613 }
614
sqlcipher_codec_ctx_get_kdf_iter(codec_ctx * ctx,int for_ctx)615 int sqlcipher_codec_ctx_get_kdf_iter(codec_ctx *ctx, int for_ctx) {
616 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
617 return c_ctx->kdf_iter;
618 }
619
sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx * ctx,int fast_kdf_iter,int for_ctx)620 int sqlcipher_codec_ctx_set_fast_kdf_iter(codec_ctx *ctx, int fast_kdf_iter, int for_ctx) {
621 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
622 int rc;
623
624 c_ctx->fast_kdf_iter = fast_kdf_iter;
625 c_ctx->derive_key = 1;
626
627 if(for_ctx == 2)
628 if((rc = sqlcipher_cipher_ctx_copy( for_ctx ? ctx->read_ctx : ctx->write_ctx, c_ctx)) != SQLITE_OK)
629 return rc;
630
631 return SQLITE_OK;
632 }
633
sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx * ctx,int for_ctx)634 int sqlcipher_codec_ctx_get_fast_kdf_iter(codec_ctx *ctx, int for_ctx) {
635 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
636 return c_ctx->fast_kdf_iter;
637 }
638
639 /* set the global default flag for HMAC */
sqlcipher_set_default_use_hmac(int use)640 void sqlcipher_set_default_use_hmac(int use) {
641 if(use) default_flags |= CIPHER_FLAG_HMAC;
642 else default_flags &= ~CIPHER_FLAG_HMAC;
643 }
644
sqlcipher_get_default_use_hmac()645 int sqlcipher_get_default_use_hmac() {
646 return (default_flags & CIPHER_FLAG_HMAC) != 0;
647 }
648
sqlcipher_set_hmac_salt_mask(unsigned char mask)649 void sqlcipher_set_hmac_salt_mask(unsigned char mask) {
650 hmac_salt_mask = mask;
651 }
652
sqlcipher_get_hmac_salt_mask()653 unsigned char sqlcipher_get_hmac_salt_mask() {
654 return hmac_salt_mask;
655 }
656
657 /* set the codec flag for whether this individual database should be using hmac */
sqlcipher_codec_ctx_set_use_hmac(codec_ctx * ctx,int use)658 int sqlcipher_codec_ctx_set_use_hmac(codec_ctx *ctx, int use) {
659 int reserve = CIPHER_MAX_IV_SZ; /* base reserve size will be IV only */
660
661 if(use) reserve += ctx->read_ctx->hmac_sz; /* if reserve will include hmac, update that size */
662
663 /* calculate the amount of reserve needed in even increments of the cipher block size */
664
665 reserve = ((reserve % ctx->read_ctx->block_sz) == 0) ? reserve :
666 ((reserve / ctx->read_ctx->block_sz) + 1) * ctx->read_ctx->block_sz;
667
668 CODEC_TRACE("sqlcipher_codec_ctx_set_use_hmac: use=%d block_sz=%d md_size=%d reserve=%d\n",
669 use, ctx->read_ctx->block_sz, ctx->read_ctx->hmac_sz, reserve);
670
671
672 if(use) {
673 sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_HMAC);
674 } else {
675 sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_HMAC);
676 }
677
678 ctx->write_ctx->reserve_sz = ctx->read_ctx->reserve_sz = reserve;
679
680 return SQLITE_OK;
681 }
682
sqlcipher_codec_ctx_get_use_hmac(codec_ctx * ctx,int for_ctx)683 int sqlcipher_codec_ctx_get_use_hmac(codec_ctx *ctx, int for_ctx) {
684 cipher_ctx * c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
685 return (c_ctx->flags & CIPHER_FLAG_HMAC) != 0;
686 }
687
sqlcipher_codec_ctx_set_flag(codec_ctx * ctx,unsigned int flag)688 int sqlcipher_codec_ctx_set_flag(codec_ctx *ctx, unsigned int flag) {
689 ctx->write_ctx->flags |= flag;
690 ctx->read_ctx->flags |= flag;
691 return SQLITE_OK;
692 }
693
sqlcipher_codec_ctx_unset_flag(codec_ctx * ctx,unsigned int flag)694 int sqlcipher_codec_ctx_unset_flag(codec_ctx *ctx, unsigned int flag) {
695 ctx->write_ctx->flags &= ~flag;
696 ctx->read_ctx->flags &= ~flag;
697 return SQLITE_OK;
698 }
699
sqlcipher_codec_ctx_get_flag(codec_ctx * ctx,unsigned int flag,int for_ctx)700 int sqlcipher_codec_ctx_get_flag(codec_ctx *ctx, unsigned int flag, int for_ctx) {
701 cipher_ctx * c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
702 return (c_ctx->flags & flag) != 0;
703 }
704
sqlcipher_codec_ctx_set_error(codec_ctx * ctx,int error)705 void sqlcipher_codec_ctx_set_error(codec_ctx *ctx, int error) {
706 CODEC_TRACE("sqlcipher_codec_ctx_set_error: ctx=%p, error=%d\n", ctx, error);
707 sqlite3pager_sqlite3PagerSetError(ctx->pBt->pBt->pPager, error);
708 ctx->pBt->pBt->db->errCode = error;
709 }
710
sqlcipher_codec_ctx_get_reservesize(codec_ctx * ctx)711 int sqlcipher_codec_ctx_get_reservesize(codec_ctx *ctx) {
712 return ctx->read_ctx->reserve_sz;
713 }
714
sqlcipher_codec_ctx_get_data(codec_ctx * ctx)715 void* sqlcipher_codec_ctx_get_data(codec_ctx *ctx) {
716 return ctx->buffer;
717 }
718
sqlcipher_codec_ctx_get_kdf_salt(codec_ctx * ctx)719 void* sqlcipher_codec_ctx_get_kdf_salt(codec_ctx *ctx) {
720 return ctx->kdf_salt;
721 }
722
sqlcipher_codec_get_keyspec(codec_ctx * ctx,void ** zKey,int * nKey)723 void sqlcipher_codec_get_keyspec(codec_ctx *ctx, void **zKey, int *nKey) {
724 *zKey = ctx->read_ctx->keyspec;
725 *nKey = ctx->read_ctx->keyspec_sz;
726 }
727
sqlcipher_codec_ctx_set_pagesize(codec_ctx * ctx,int size)728 int sqlcipher_codec_ctx_set_pagesize(codec_ctx *ctx, int size) {
729 if(!((size != 0) && ((size & (size - 1)) == 0)) || size < 512 || size > 65536) {
730 CODEC_TRACE(("cipher_page_size not a power of 2 and between 512 and 65536 inclusive\n"));
731 return SQLITE_ERROR;
732 }
733 /* attempt to free the existing page buffer */
734 sqlcipher_free(ctx->buffer,ctx->page_sz);
735 ctx->page_sz = size;
736
737 /* pre-allocate a page buffer of PageSize bytes. This will
738 be used as a persistent buffer for encryption and decryption
739 operations to avoid overhead of multiple memory allocations*/
740 ctx->buffer = sqlcipher_malloc(size);
741 if(ctx->buffer == NULL) return SQLITE_NOMEM;
742
743 return SQLITE_OK;
744 }
745
sqlcipher_codec_ctx_get_pagesize(codec_ctx * ctx)746 int sqlcipher_codec_ctx_get_pagesize(codec_ctx *ctx) {
747 return ctx->page_sz;
748 }
749
sqlcipher_set_default_pagesize(int page_size)750 void sqlcipher_set_default_pagesize(int page_size) {
751 default_page_size = page_size;
752 }
753
sqlcipher_get_default_pagesize()754 int sqlcipher_get_default_pagesize() {
755 return default_page_size;
756 }
757
sqlcipher_codec_ctx_init(codec_ctx ** iCtx,Db * pDb,Pager * pPager,sqlite3_file * fd,const void * zKey,int nKey)758 int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_file *fd, const void *zKey, int nKey) {
759 int rc;
760 codec_ctx *ctx;
761
762 CODEC_TRACE("sqlcipher_codec_ctx_init: allocating context\n");
763
764 *iCtx = sqlcipher_malloc(sizeof(codec_ctx));
765 ctx = *iCtx;
766
767 if(ctx == NULL) return SQLITE_NOMEM;
768
769 ctx->pBt = pDb->pBt; /* assign pointer to database btree structure */
770
771 /* allocate space for salt data. Then read the first 16 bytes
772 directly off the database file. This is the salt for the
773 key derivation function. If we get a short read allocate
774 a new random salt value */
775 CODEC_TRACE("sqlcipher_codec_ctx_init: allocating kdf_salt\n");
776 ctx->kdf_salt_sz = FILE_HEADER_SZ;
777 ctx->kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
778 if(ctx->kdf_salt == NULL) return SQLITE_NOMEM;
779
780 /* allocate space for separate hmac salt data. We want the
781 HMAC derivation salt to be different than the encryption
782 key derivation salt */
783 CODEC_TRACE("sqlcipher_codec_ctx_init: allocating hmac_kdf_salt\n");
784 ctx->hmac_kdf_salt = sqlcipher_malloc(ctx->kdf_salt_sz);
785 if(ctx->hmac_kdf_salt == NULL) return SQLITE_NOMEM;
786
787
788 /*
789 Always overwrite page size and set to the default because the first page of the database
790 in encrypted and thus sqlite can't effectively determine the pagesize. this causes an issue in
791 cases where bytes 16 & 17 of the page header are a power of 2 as reported by John Lehman
792 */
793 CODEC_TRACE("sqlcipher_codec_ctx_init: calling sqlcipher_codec_ctx_set_pagesize with %d\n", default_page_size);
794 if((rc = sqlcipher_codec_ctx_set_pagesize(ctx, default_page_size)) != SQLITE_OK) return rc;
795
796 CODEC_TRACE("sqlcipher_codec_ctx_init: initializing read_ctx\n");
797 if((rc = sqlcipher_cipher_ctx_init(&ctx->read_ctx)) != SQLITE_OK) return rc;
798
799 CODEC_TRACE("sqlcipher_codec_ctx_init: initializing write_ctx\n");
800 if((rc = sqlcipher_cipher_ctx_init(&ctx->write_ctx)) != SQLITE_OK) return rc;
801
802 CODEC_TRACE("sqlcipher_codec_ctx_init: reading file header\n");
803 if(fd == NULL || sqlite3OsRead(fd, ctx->kdf_salt, FILE_HEADER_SZ, 0) != SQLITE_OK) {
804 ctx->need_kdf_salt = 1;
805 }
806
807 CODEC_TRACE("sqlcipher_codec_ctx_init: setting cipher\n");
808 if((rc = sqlcipher_codec_ctx_set_cipher(ctx, CIPHER, 0)) != SQLITE_OK) return rc;
809
810 CODEC_TRACE("sqlcipher_codec_ctx_init: setting default_kdf_iter\n");
811 if((rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, default_kdf_iter, 0)) != SQLITE_OK) return rc;
812
813 CODEC_TRACE("sqlcipher_codec_ctx_init: setting fast_kdf_iter\n");
814 if((rc = sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, FAST_PBKDF2_ITER, 0)) != SQLITE_OK) return rc;
815
816 CODEC_TRACE("sqlcipher_codec_ctx_init: setting pass key\n");
817 if((rc = sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, 0)) != SQLITE_OK) return rc;
818
819 /* Note that use_hmac is a special case that requires recalculation of page size
820 so we call set_use_hmac to perform setup */
821 CODEC_TRACE("sqlcipher_codec_ctx_init: setting use_hmac\n");
822 if((rc = sqlcipher_codec_ctx_set_use_hmac(ctx, default_flags & CIPHER_FLAG_HMAC)) != SQLITE_OK) return rc;
823
824 CODEC_TRACE("sqlcipher_codec_ctx_init: copying write_ctx to read_ctx\n");
825 if((rc = sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx)) != SQLITE_OK) return rc;
826
827 return SQLITE_OK;
828 }
829
830 /**
831 * Free and wipe memory associated with a cipher_ctx, including the allocated
832 * read_ctx and write_ctx.
833 */
sqlcipher_codec_ctx_free(codec_ctx ** iCtx)834 void sqlcipher_codec_ctx_free(codec_ctx **iCtx) {
835 codec_ctx *ctx = *iCtx;
836 CODEC_TRACE("codec_ctx_free: entered iCtx=%p\n", iCtx);
837 sqlcipher_free(ctx->kdf_salt, ctx->kdf_salt_sz);
838 sqlcipher_free(ctx->hmac_kdf_salt, ctx->kdf_salt_sz);
839 sqlcipher_free(ctx->buffer, 0);
840 sqlcipher_cipher_ctx_free(&ctx->read_ctx);
841 sqlcipher_cipher_ctx_free(&ctx->write_ctx);
842 sqlcipher_free(ctx, sizeof(codec_ctx));
843 }
844
845 /** convert a 32bit unsigned integer to little endian byte ordering */
sqlcipher_put4byte_le(unsigned char * p,u32 v)846 static void sqlcipher_put4byte_le(unsigned char *p, u32 v) {
847 p[0] = (u8)v;
848 p[1] = (u8)(v>>8);
849 p[2] = (u8)(v>>16);
850 p[3] = (u8)(v>>24);
851 }
852
sqlcipher_page_hmac(cipher_ctx * ctx,Pgno pgno,unsigned char * in,int in_sz,unsigned char * out)853 static int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, int in_sz, unsigned char *out) {
854 unsigned char pgno_raw[sizeof(pgno)];
855 /* we may convert page number to consistent representation before calculating MAC for
856 compatibility across big-endian and little-endian platforms.
857
858 Note: The public release of sqlcipher 2.0.0 to 2.0.6 had a bug where the bytes of pgno
859 were used directly in the MAC. SQLCipher convert's to little endian by default to preserve
860 backwards compatibility on the most popular platforms, but can optionally be configured
861 to use either big endian or native byte ordering via pragma. */
862
863 if(ctx->flags & CIPHER_FLAG_LE_PGNO) { /* compute hmac using little endian pgno*/
864 sqlcipher_put4byte_le(pgno_raw, pgno);
865 } else if(ctx->flags & CIPHER_FLAG_BE_PGNO) { /* compute hmac using big endian pgno */
866 sqlite3Put4byte(pgno_raw, pgno); /* sqlite3Put4byte converts 32bit uint to big endian */
867 } else { /* use native byte ordering */
868 memcpy(pgno_raw, &pgno, sizeof(pgno));
869 }
870
871 /* include the encrypted page data, initialization vector, and page number in HMAC. This will
872 prevent both tampering with the ciphertext, manipulation of the IV, or resequencing otherwise
873 valid pages out of order in a database */
874 ctx->provider->hmac(
875 ctx->provider_ctx, ctx->hmac_key,
876 ctx->key_sz, in,
877 in_sz, (unsigned char*) &pgno_raw,
878 sizeof(pgno), out);
879 return SQLITE_OK;
880 }
881
882 /*
883 * ctx - codec context
884 * pgno - page number in database
885 * size - size in bytes of input and output buffers
886 * mode - 1 to encrypt, 0 to decrypt
887 * in - pointer to input bytes
888 * out - pouter to output bytes
889 */
sqlcipher_page_cipher(codec_ctx * ctx,int for_ctx,Pgno pgno,int mode,int page_sz,unsigned char * in,unsigned char * out)890 int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
891 cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
892 unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
893 int size;
894
895 /* calculate some required positions into various buffers */
896 size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
897 iv_out = out + size;
898 iv_in = in + size;
899
900 /* hmac will be written immediately after the initialization vector. the remainder of the page reserve will contain
901 random bytes. note, these pointers are only valid when using hmac */
902 hmac_in = in + size + c_ctx->iv_sz;
903 hmac_out = out + size + c_ctx->iv_sz;
904 out_start = out; /* note the original position of the output buffer pointer, as out will be rewritten during encryption */
905
906 CODEC_TRACE("codec_cipher:entered pgno=%d, mode=%d, size=%d\n", pgno, mode, size);
907 CODEC_HEXDUMP("codec_cipher: input page data", in, page_sz);
908
909 /* the key size should never be zero. If it is, error out. */
910 if(c_ctx->key_sz == 0) {
911 CODEC_TRACE("codec_cipher: error possible context corruption, key_sz is zero for pgno=%d\n", pgno);
912 sqlcipher_memset(out, 0, page_sz);
913 return SQLITE_ERROR;
914 }
915
916 if(mode == CIPHER_ENCRYPT) {
917 /* start at front of the reserve block, write random data to the end */
918 if(c_ctx->provider->random(c_ctx->provider_ctx, iv_out, c_ctx->reserve_sz) != SQLITE_OK) return SQLITE_ERROR;
919 } else { /* CIPHER_DECRYPT */
920 memcpy(iv_out, iv_in, c_ctx->iv_sz); /* copy the iv from the input to output buffer */
921 }
922
923 if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_DECRYPT) && !ctx->skip_read_hmac) {
924 if(sqlcipher_page_hmac(c_ctx, pgno, in, size + c_ctx->iv_sz, hmac_out) != SQLITE_OK) {
925 sqlcipher_memset(out, 0, page_sz);
926 CODEC_TRACE("codec_cipher: hmac operations failed for pgno=%d\n", pgno);
927 return SQLITE_ERROR;
928 }
929
930 CODEC_TRACE("codec_cipher: comparing hmac on in=%p out=%p hmac_sz=%d\n", hmac_in, hmac_out, c_ctx->hmac_sz);
931 if(sqlcipher_memcmp(hmac_in, hmac_out, c_ctx->hmac_sz) != 0) { /* the hmac check failed */
932 if(sqlcipher_ismemset(in, 0, page_sz) == 0) {
933 /* first check if the entire contents of the page is zeros. If so, this page
934 resulted from a short read (i.e. sqlite attempted to pull a page after the end of the file. these
935 short read failures must be ignored for autovaccum mode to work so wipe the output buffer
936 and return SQLITE_OK to skip the decryption step. */
937 CODEC_TRACE("codec_cipher: zeroed page (short read) for pgno %d, encryption but returning SQLITE_OK\n", pgno);
938 sqlcipher_memset(out, 0, page_sz);
939 return SQLITE_OK;
940 } else {
941 /* if the page memory is not all zeros, it means the there was data and a hmac on the page.
942 since the check failed, the page was either tampered with or corrupted. wipe the output buffer,
943 and return SQLITE_ERROR to the caller */
944 CODEC_TRACE("codec_cipher: hmac check failed for pgno=%d returning SQLITE_ERROR\n", pgno);
945 sqlcipher_memset(out, 0, page_sz);
946 return SQLITE_ERROR;
947 }
948 }
949 }
950
951 c_ctx->provider->cipher(c_ctx->provider_ctx, mode, c_ctx->key, c_ctx->key_sz, iv_out, in, size, out);
952
953 if((c_ctx->flags & CIPHER_FLAG_HMAC) && (mode == CIPHER_ENCRYPT)) {
954 sqlcipher_page_hmac(c_ctx, pgno, out_start, size + c_ctx->iv_sz, hmac_out);
955 }
956
957 CODEC_HEXDUMP("codec_cipher: output page data", out_start, page_sz);
958
959 return SQLITE_OK;
960 }
961
962 /**
963 * Derive an encryption key for a cipher contex key based on the raw password.
964 *
965 * If the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
966 * the key (i.e 64 hex chars for a 256 bit key) then the key data will be used directly.
967
968 * Else, if the raw key data is formated as x'hex' and there are exactly enough hex chars to fill
969 * the key and the salt (i.e 92 hex chars for a 256 bit key and 16 byte salt) then it will be unpacked
970 * as the key followed by the salt.
971 *
972 * Otherwise, a key data will be derived using PBKDF2
973 *
974 * returns SQLITE_OK if initialization was successful
975 * returns SQLITE_ERROR if the key could't be derived (for instance if pass is NULL or pass_sz is 0)
976 */
sqlcipher_cipher_ctx_key_derive(codec_ctx * ctx,cipher_ctx * c_ctx)977 static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
978 int rc;
979 CODEC_TRACE("cipher_ctx_key_derive: entered c_ctx->pass=%s, c_ctx->pass_sz=%d \
980 ctx->kdf_salt=%p ctx->kdf_salt_sz=%d c_ctx->kdf_iter=%d \
981 ctx->hmac_kdf_salt=%p, c_ctx->fast_kdf_iter=%d c_ctx->key_sz=%d\n",
982 c_ctx->pass, c_ctx->pass_sz, ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter,
983 ctx->hmac_kdf_salt, c_ctx->fast_kdf_iter, c_ctx->key_sz);
984
985
986 if(c_ctx->pass && c_ctx->pass_sz) { // if pass is not null
987
988 if(ctx->need_kdf_salt) {
989 if(ctx->read_ctx->provider->random(ctx->read_ctx->provider_ctx, ctx->kdf_salt, FILE_HEADER_SZ) != SQLITE_OK) return SQLITE_ERROR;
990 ctx->need_kdf_salt = 0;
991 }
992 if (c_ctx->pass_sz == ((c_ctx->key_sz * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, c_ctx->key_sz * 2)) {
993 int n = c_ctx->pass_sz - 3; /* adjust for leading x' and tailing ' */
994 const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
995 CODEC_TRACE("cipher_ctx_key_derive: using raw key from hex\n");
996 cipher_hex2bin(z, n, c_ctx->key);
997 } else if (c_ctx->pass_sz == (((c_ctx->key_sz + ctx->kdf_salt_sz) * 2) + 3) && sqlite3StrNICmp((const char *)c_ctx->pass ,"x'", 2) == 0 && cipher_isHex(c_ctx->pass + 2, (c_ctx->key_sz + ctx->kdf_salt_sz) * 2)) {
998 const unsigned char *z = c_ctx->pass + 2; /* adjust lead offset of x' */
999 CODEC_TRACE("cipher_ctx_key_derive: using raw key from hex\n");
1000 cipher_hex2bin(z, (c_ctx->key_sz * 2), c_ctx->key);
1001 cipher_hex2bin(z + (c_ctx->key_sz * 2), (ctx->kdf_salt_sz * 2), ctx->kdf_salt);
1002 } else {
1003 CODEC_TRACE("cipher_ctx_key_derive: deriving key using full PBKDF2 with %d iterations\n", c_ctx->kdf_iter);
1004 c_ctx->provider->kdf(c_ctx->provider_ctx, c_ctx->pass, c_ctx->pass_sz,
1005 ctx->kdf_salt, ctx->kdf_salt_sz, c_ctx->kdf_iter,
1006 c_ctx->key_sz, c_ctx->key);
1007 }
1008
1009 /* set the context "keyspec" containing the hex-formatted key and salt to be used when attaching databases */
1010 if((rc = sqlcipher_cipher_ctx_set_keyspec(c_ctx, c_ctx->key, c_ctx->key_sz, ctx->kdf_salt, ctx->kdf_salt_sz)) != SQLITE_OK) return rc;
1011
1012 /* if this context is setup to use hmac checks, generate a seperate and different
1013 key for HMAC. In this case, we use the output of the previous KDF as the input to
1014 this KDF run. This ensures a distinct but predictable HMAC key. */
1015 if(c_ctx->flags & CIPHER_FLAG_HMAC) {
1016 int i;
1017
1018 /* start by copying the kdf key into the hmac salt slot
1019 then XOR it with the fixed hmac salt defined at compile time
1020 this ensures that the salt passed in to derive the hmac key, while
1021 easy to derive and publically known, is not the same as the salt used
1022 to generate the encryption key */
1023 memcpy(ctx->hmac_kdf_salt, ctx->kdf_salt, ctx->kdf_salt_sz);
1024 for(i = 0; i < ctx->kdf_salt_sz; i++) {
1025 ctx->hmac_kdf_salt[i] ^= hmac_salt_mask;
1026 }
1027
1028 CODEC_TRACE("cipher_ctx_key_derive: deriving hmac key from encryption key using PBKDF2 with %d iterations\n",
1029 c_ctx->fast_kdf_iter);
1030
1031
1032 c_ctx->provider->kdf(c_ctx->provider_ctx, c_ctx->key, c_ctx->key_sz,
1033 ctx->hmac_kdf_salt, ctx->kdf_salt_sz, c_ctx->fast_kdf_iter,
1034 c_ctx->key_sz, c_ctx->hmac_key);
1035 }
1036
1037 c_ctx->derive_key = 0;
1038 return SQLITE_OK;
1039 };
1040 return SQLITE_ERROR;
1041 }
1042
sqlcipher_codec_key_derive(codec_ctx * ctx)1043 int sqlcipher_codec_key_derive(codec_ctx *ctx) {
1044 /* derive key on first use if necessary */
1045 if(ctx->read_ctx->derive_key) {
1046 if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR;
1047 }
1048
1049 if(ctx->write_ctx->derive_key) {
1050 if(sqlcipher_cipher_ctx_cmp(ctx->write_ctx, ctx->read_ctx) == 0) {
1051 /* the relevant parameters are the same, just copy read key */
1052 if(sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx) != SQLITE_OK) return SQLITE_ERROR;
1053 } else {
1054 if(sqlcipher_cipher_ctx_key_derive(ctx, ctx->write_ctx) != SQLITE_OK) return SQLITE_ERROR;
1055 }
1056 }
1057
1058 /* TODO: wipe and free passphrase after key derivation */
1059 if(ctx->read_ctx->store_pass != 1) {
1060 sqlcipher_cipher_ctx_set_pass(ctx->read_ctx, NULL, 0);
1061 sqlcipher_cipher_ctx_set_pass(ctx->write_ctx, NULL, 0);
1062 }
1063
1064 return SQLITE_OK;
1065 }
1066
sqlcipher_codec_key_copy(codec_ctx * ctx,int source)1067 int sqlcipher_codec_key_copy(codec_ctx *ctx, int source) {
1068 if(source == CIPHER_READ_CTX) {
1069 return sqlcipher_cipher_ctx_copy(ctx->write_ctx, ctx->read_ctx);
1070 } else {
1071 return sqlcipher_cipher_ctx_copy(ctx->read_ctx, ctx->write_ctx);
1072 }
1073 }
1074
sqlcipher_codec_get_cipher_provider(codec_ctx * ctx)1075 const char* sqlcipher_codec_get_cipher_provider(codec_ctx *ctx) {
1076 return ctx->read_ctx->provider->get_provider_name(ctx->read_ctx);
1077 }
1078
1079
sqlcipher_check_connection(const char * filename,char * key,int key_sz,char * sql,int * user_version)1080 static int sqlcipher_check_connection(const char *filename, char *key, int key_sz, char *sql, int *user_version) {
1081 int rc;
1082 sqlite3 *db = NULL;
1083 sqlite3_stmt *statement = NULL;
1084 char *query_user_version = "PRAGMA user_version;";
1085
1086 rc = sqlite3_open(filename, &db);
1087 if(rc != SQLITE_OK){
1088 goto cleanup;
1089 }
1090 rc = sqlite3_key(db, key, key_sz);
1091 if(rc != SQLITE_OK){
1092 goto cleanup;
1093 }
1094 rc = sqlite3_exec(db, sql, NULL, NULL, NULL);
1095 if(rc != SQLITE_OK){
1096 goto cleanup;
1097 }
1098 rc = sqlite3_prepare(db, query_user_version, -1, &statement, NULL);
1099 if(rc != SQLITE_OK){
1100 goto cleanup;
1101 }
1102 rc = sqlite3_step(statement);
1103 if(rc == SQLITE_ROW){
1104 *user_version = sqlite3_column_int(statement, 0);
1105 rc = SQLITE_OK;
1106 }
1107
1108 cleanup:
1109 if(statement){
1110 sqlite3_finalize(statement);
1111 }
1112 if(db){
1113 sqlite3_close(db);
1114 }
1115 return rc;
1116 }
1117
sqlcipher_codec_ctx_migrate(codec_ctx * ctx)1118 int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) {
1119 u32 meta;
1120 int rc = 0;
1121 int command_idx = 0;
1122 int password_sz;
1123 int saved_flags;
1124 int saved_nChange;
1125 int saved_nTotalChange;
1126 u8 saved_mTrace;
1127 int (*saved_xTrace)(u32,void*,void*,void*); /* Saved db->xTrace */
1128 Db *pDb = 0;
1129 sqlite3 *db = ctx->pBt->db;
1130 const char *db_filename = sqlite3_db_filename(db, "main");
1131 char *migrated_db_filename = sqlite3_mprintf("%s-migrated", db_filename);
1132 char *pragma_hmac_off = "PRAGMA cipher_use_hmac = OFF;";
1133 char *pragma_4k_kdf_iter = "PRAGMA kdf_iter = 4000;";
1134 char *pragma_1x_and_4k;
1135 char *set_user_version;
1136 char *key;
1137 int key_sz;
1138 int user_version = 0;
1139 int upgrade_1x_format = 0;
1140 int upgrade_4k_format = 0;
1141 static const unsigned char aCopy[] = {
1142 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
1143 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
1144 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
1145 BTREE_USER_VERSION, 0, /* Preserve the user version */
1146 BTREE_APPLICATION_ID, 0, /* Preserve the application id */
1147 };
1148
1149
1150 key_sz = ctx->read_ctx->pass_sz + 1;
1151 key = sqlcipher_malloc(key_sz);
1152 memset(key, 0, key_sz);
1153 memcpy(key, ctx->read_ctx->pass, ctx->read_ctx->pass_sz);
1154
1155 if(db_filename){
1156 const char* commands[5];
1157 char *attach_command = sqlite3_mprintf("ATTACH DATABASE '%s-migrated' as migrate KEY '%q';",
1158 db_filename, key);
1159
1160 int rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, "", &user_version);
1161 if(rc == SQLITE_OK){
1162 CODEC_TRACE("No upgrade required - exiting\n");
1163 goto exit;
1164 }
1165
1166 // Version 2 - check for 4k with hmac format
1167 rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_4k_kdf_iter, &user_version);
1168 if(rc == SQLITE_OK) {
1169 CODEC_TRACE("Version 2 format found\n");
1170 upgrade_4k_format = 1;
1171 }
1172
1173 // Version 1 - check both no hmac and 4k together
1174 pragma_1x_and_4k = sqlite3_mprintf("%s%s", pragma_hmac_off,
1175 pragma_4k_kdf_iter);
1176 rc = sqlcipher_check_connection(db_filename, key, ctx->read_ctx->pass_sz, pragma_1x_and_4k, &user_version);
1177 sqlite3_free(pragma_1x_and_4k);
1178 if(rc == SQLITE_OK) {
1179 CODEC_TRACE("Version 1 format found\n");
1180 upgrade_1x_format = 1;
1181 upgrade_4k_format = 1;
1182 }
1183
1184 if(upgrade_1x_format == 0 && upgrade_4k_format == 0) {
1185 CODEC_TRACE("Upgrade format not determined\n");
1186 goto handle_error;
1187 }
1188
1189 set_user_version = sqlite3_mprintf("PRAGMA migrate.user_version = %d;", user_version);
1190 commands[0] = upgrade_4k_format == 1 ? pragma_4k_kdf_iter : "";
1191 commands[1] = upgrade_1x_format == 1 ? pragma_hmac_off : "";
1192 commands[2] = attach_command;
1193 commands[3] = "SELECT sqlcipher_export('migrate');";
1194 commands[4] = set_user_version;
1195
1196 for(command_idx = 0; command_idx < ArraySize(commands); command_idx++){
1197 const char *command = commands[command_idx];
1198 if(strcmp(command, "") == 0){
1199 continue;
1200 }
1201 rc = sqlite3_exec(db, command, NULL, NULL, NULL);
1202 if(rc != SQLITE_OK){
1203 break;
1204 }
1205 }
1206 sqlite3_free(attach_command);
1207 sqlite3_free(set_user_version);
1208 sqlcipher_free(key, key_sz);
1209
1210 if(rc == SQLITE_OK){
1211 Btree *pDest;
1212 Btree *pSrc;
1213 int i = 0;
1214
1215 if( !db->autoCommit ){
1216 CODEC_TRACE("cannot migrate from within a transaction");
1217 goto handle_error;
1218 }
1219 if( db->nVdbeActive>1 ){
1220 CODEC_TRACE("cannot migrate - SQL statements in progress");
1221 goto handle_error;
1222 }
1223
1224 /* Save the current value of the database flags so that it can be
1225 ** restored before returning. Then set the writable-schema flag, and
1226 ** disable CHECK and foreign key constraints. */
1227 saved_flags = db->flags;
1228 saved_nChange = db->nChange;
1229 saved_nTotalChange = db->nTotalChange;
1230 saved_xTrace = db->xTrace;
1231 saved_mTrace = db->mTrace;
1232 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
1233 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
1234 db->xTrace = 0;
1235 db->mTrace = 0;
1236
1237 pDest = db->aDb[0].pBt;
1238 pDb = &(db->aDb[db->nDb-1]);
1239 pSrc = pDb->pBt;
1240
1241 rc = sqlite3_exec(db, "BEGIN;", NULL, NULL, NULL);
1242 rc = sqlite3BtreeBeginTrans(pSrc, 2);
1243 rc = sqlite3BtreeBeginTrans(pDest, 2);
1244
1245 assert( 1==sqlite3BtreeIsInTrans(pDest) );
1246 assert( 1==sqlite3BtreeIsInTrans(pSrc) );
1247
1248 sqlite3CodecGetKey(db, db->nDb - 1, (void**)&key, &password_sz);
1249 sqlite3CodecAttach(db, 0, key, password_sz);
1250 sqlite3pager_get_codec(pDest->pBt->pPager, (void**)&ctx);
1251
1252 ctx->skip_read_hmac = 1;
1253 for(i=0; i<ArraySize(aCopy); i+=2){
1254 sqlite3BtreeGetMeta(pSrc, aCopy[i], &meta);
1255 rc = sqlite3BtreeUpdateMeta(pDest, aCopy[i], meta+aCopy[i+1]);
1256 if( NEVER(rc!=SQLITE_OK) ) goto handle_error;
1257 }
1258 rc = sqlite3BtreeCopyFile(pDest, pSrc);
1259 ctx->skip_read_hmac = 0;
1260 if( rc!=SQLITE_OK ) goto handle_error;
1261 rc = sqlite3BtreeCommit(pDest);
1262
1263 db->flags = saved_flags;
1264 db->nChange = saved_nChange;
1265 db->nTotalChange = saved_nTotalChange;
1266 db->xTrace = saved_xTrace;
1267 db->mTrace = saved_mTrace;
1268 db->autoCommit = 1;
1269 sqlite3BtreeClose(pDb->pBt);
1270 pDb->pBt = 0;
1271 pDb->pSchema = 0;
1272 sqlite3ResetAllSchemasOfConnection(db);
1273 remove(migrated_db_filename);
1274 sqlite3_free(migrated_db_filename);
1275 } else {
1276 CODEC_TRACE("*** migration failure** \n\n");
1277 }
1278
1279 }
1280 goto exit;
1281
1282 handle_error:
1283 CODEC_TRACE("An error occurred attempting to migrate the database\n");
1284 rc = SQLITE_ERROR;
1285
1286 exit:
1287 return rc;
1288 }
1289
sqlcipher_codec_add_random(codec_ctx * ctx,const char * zRight,int random_sz)1290 int sqlcipher_codec_add_random(codec_ctx *ctx, const char *zRight, int random_sz){
1291 const char *suffix = &zRight[random_sz-1];
1292 int n = random_sz - 3; /* adjust for leading x' and tailing ' */
1293 if (n > 0 &&
1294 sqlite3StrNICmp((const char *)zRight ,"x'", 2) == 0 &&
1295 sqlite3StrNICmp(suffix, "'", 1) == 0 &&
1296 n % 2 == 0) {
1297 int rc = 0;
1298 int buffer_sz = n / 2;
1299 unsigned char *random;
1300 const unsigned char *z = (const unsigned char *)zRight + 2; /* adjust lead offset of x' */
1301 CODEC_TRACE("sqlcipher_codec_add_random: using raw random blob from hex\n");
1302 random = sqlcipher_malloc(buffer_sz);
1303 memset(random, 0, buffer_sz);
1304 cipher_hex2bin(z, n, random);
1305 rc = ctx->read_ctx->provider->add_random(ctx->read_ctx->provider_ctx, random, buffer_sz);
1306 sqlcipher_free(random, buffer_sz);
1307 return rc;
1308 }
1309 return SQLITE_ERROR;
1310 }
1311
sqlcipher_profile_callback(void * file,const char * sql,sqlite3_uint64 run_time)1312 static void sqlcipher_profile_callback(void *file, const char *sql, sqlite3_uint64 run_time){
1313 FILE *f = (FILE*)file;
1314 double elapsed = run_time/1000000.0;
1315 if(f) fprintf(f, "Elapsed time:%.3f ms - %s\n", elapsed, sql);
1316 }
1317
sqlcipher_cipher_profile(sqlite3 * db,const char * destination)1318 int sqlcipher_cipher_profile(sqlite3 *db, const char *destination){
1319 #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
1320 return SQLITE_ERROR;
1321 #else
1322 FILE *f;
1323 if(sqlite3StrICmp(destination, "stdout") == 0){
1324 f = stdout;
1325 }else if(sqlite3StrICmp(destination, "stderr") == 0){
1326 f = stderr;
1327 }else if(sqlite3StrICmp(destination, "off") == 0){
1328 f = 0;
1329 }else{
1330 #if defined(_WIN32) && (__STDC_VERSION__ > 199901L) || defined(SQLITE_OS_WINRT)
1331 if(fopen_s(&f, destination, "a") != 0){
1332 #else
1333 f = fopen(destination, "a");
1334 if(f == 0){
1335 #endif
1336 return SQLITE_ERROR;
1337 }
1338
1339 }
1340 sqlite3_profile(db, sqlcipher_profile_callback, f);
1341 return SQLITE_OK;
1342 #endif
1343 }
1344
1345 int sqlcipher_codec_fips_status(codec_ctx *ctx) {
1346 return ctx->read_ctx->provider->fips_status(ctx->read_ctx);
1347 }
1348
1349 const char* sqlcipher_codec_get_provider_version(codec_ctx *ctx) {
1350 return ctx->read_ctx->provider->get_provider_version(ctx->read_ctx);
1351 }
1352
1353 int sqlcipher_codec_hmac(const codec_ctx *ctx, const unsigned char *hmac_key, int key_sz,
1354 unsigned char* in, int in_sz, unsigned char *in2, int in2_sz,
1355 unsigned char *out) {
1356 ctx->read_ctx->provider->hmac(ctx->read_ctx, (unsigned char *)hmac_key, key_sz, in, in_sz, in2, in2_sz, out);
1357 return SQLITE_OK;
1358 }
1359
1360
1361 #endif
1362 /* END SQLCIPHER */
1363