format pointer for key material with trace logging enabled per #398
[sqlcipher.git] / src / crypto.c
blob5a181a88562a48d1c0a48a3854f71e221ca11b77
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 **
31 /* BEGIN SQLCIPHER */
32 #ifdef SQLITE_HAS_CODEC
34 #include <assert.h>
35 #include "sqlcipher.h"
36 #include "crypto.h"
38 #ifdef SQLCIPHER_EXT
39 #include "sqlcipher_ext.h"
40 #endif
42 #ifdef SQLCIPHER_TEST
43 static int cipher_fail_next_encrypt = 0;
44 static int cipher_fail_next_decrypt = 0;
45 #endif
47 /* Generate code to return a string value */
48 static void codec_vdbe_return_string(Parse *pParse, const char *zLabel, const char *value, int value_type){
49 Vdbe *v = sqlite3GetVdbe(pParse);
50 sqlite3VdbeSetNumCols(v, 1);
51 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
52 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, value, value_type);
53 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
56 static int codec_set_btree_to_codec_pagesize(sqlite3 *db, Db *pDb, codec_ctx *ctx) {
57 int rc, page_sz, reserve_sz;
59 page_sz = sqlcipher_codec_ctx_get_pagesize(ctx);
60 reserve_sz = sqlcipher_codec_ctx_get_reservesize(ctx);
62 CODEC_TRACE("codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize() size=%d reserve=%d\n", page_sz, reserve_sz);
64 CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: entering database mutex %p\n", db->mutex);
65 sqlite3_mutex_enter(db->mutex);
66 CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: entered database mutex %p\n", db->mutex);
67 db->nextPagesize = page_sz;
69 /* before forcing the page size we need to unset the BTS_PAGESIZE_FIXED flag, else
70 sqliteBtreeSetPageSize will block the change */
71 pDb->pBt->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
72 rc = sqlite3BtreeSetPageSize(pDb->pBt, page_sz, reserve_sz, 0);
74 CODEC_TRACE("codec_set_btree_to_codec_pagesize: sqlite3BtreeSetPageSize returned %d\n", rc);
76 CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: leaving database mutex %p\n", db->mutex);
77 sqlite3_mutex_leave(db->mutex);
78 CODEC_TRACE_MUTEX("codec_set_btree_to_codec_pagesize: left database mutex %p\n", db->mutex);
80 return rc;
83 static int codec_set_pass_key(sqlite3* db, int nDb, const void *zKey, int nKey, int for_ctx) {
84 struct Db *pDb = &db->aDb[nDb];
85 CODEC_TRACE("codec_set_pass_key: entered db=%p nDb=%d zKey=%p nKey=%d for_ctx=%d\n", db, nDb, zKey, nKey, for_ctx);
86 if(pDb->pBt) {
87 codec_ctx *ctx = (codec_ctx*) sqlite3PagerGetCodec(pDb->pBt->pBt->pPager);
89 if(ctx) return sqlcipher_codec_ctx_set_pass(ctx, zKey, nKey, for_ctx);
91 return SQLITE_ERROR;
94 int sqlcipher_codec_pragma(sqlite3* db, int iDb, Parse *pParse, const char *zLeft, const char *zRight) {
95 struct Db *pDb = &db->aDb[iDb];
96 codec_ctx *ctx = NULL;
97 int rc;
99 if(pDb->pBt) {
100 ctx = (codec_ctx*) sqlite3PagerGetCodec(pDb->pBt->pBt->pPager);
103 CODEC_TRACE("sqlcipher_codec_pragma: entered db=%p iDb=%d pParse=%p zLeft=%s zRight=%s ctx=%p\n", db, iDb, pParse, zLeft, zRight, ctx);
105 #ifdef SQLCIPHER_EXT
106 if( sqlite3StrICmp(zLeft, "cipher_license")==0 && zRight ){
107 char *license_result = sqlite3_mprintf("%d", sqlcipher_license_key(zRight));
108 codec_vdbe_return_string(pParse, "cipher_license", license_result, P4_DYNAMIC);
109 } else
110 if( sqlite3StrICmp(zLeft, "cipher_license")==0 && !zRight ){
111 if(ctx) {
112 char *license_result = sqlite3_mprintf("%d", ctx
113 ? sqlcipher_license_key_status(ctx->provider)
114 : SQLITE_ERROR);
115 codec_vdbe_return_string(pParse, "cipher_license", license_result, P4_DYNAMIC);
117 } else
118 #endif
119 #ifdef SQLCIPHER_TEST
120 if( sqlite3StrICmp(zLeft,"cipher_fail_next_encrypt")==0 ){
121 if( zRight ) {
122 cipher_fail_next_encrypt = sqlite3GetBoolean(zRight,1);
123 } else {
124 char *fail = sqlite3_mprintf("%d", cipher_fail_next_encrypt);
125 codec_vdbe_return_string(pParse, "cipher_fail_next_encrypt", fail, P4_DYNAMIC);
127 }else
128 if( sqlite3StrICmp(zLeft,"cipher_fail_next_decrypt")==0 ){
129 if( zRight ) {
130 cipher_fail_next_decrypt = sqlite3GetBoolean(zRight,1);
131 } else {
132 char *fail = sqlite3_mprintf("%d", cipher_fail_next_decrypt);
133 codec_vdbe_return_string(pParse, "cipher_fail_next_decrypt", fail, P4_DYNAMIC);
135 }else
136 #endif
137 if( sqlite3StrICmp(zLeft, "cipher_fips_status")== 0 && !zRight ){
138 if(ctx) {
139 char *fips_mode_status = sqlite3_mprintf("%d", sqlcipher_codec_fips_status(ctx));
140 codec_vdbe_return_string(pParse, "cipher_fips_status", fips_mode_status, P4_DYNAMIC);
142 } else
143 if( sqlite3StrICmp(zLeft, "cipher_store_pass")==0 && zRight ) {
144 if(ctx) {
145 char *deprecation = "PRAGMA cipher_store_pass is deprecated, please remove from use";
146 sqlcipher_codec_set_store_pass(ctx, sqlite3GetBoolean(zRight, 1));
147 codec_vdbe_return_string(pParse, "cipher_store_pass", deprecation, P4_TRANSIENT);
148 sqlite3_log(SQLITE_WARNING, deprecation);
150 } else
151 if( sqlite3StrICmp(zLeft, "cipher_store_pass")==0 && !zRight ) {
152 if(ctx){
153 char *store_pass_value = sqlite3_mprintf("%d", sqlcipher_codec_get_store_pass(ctx));
154 codec_vdbe_return_string(pParse, "cipher_store_pass", store_pass_value, P4_DYNAMIC);
157 if( sqlite3StrICmp(zLeft, "cipher_profile")== 0 && zRight ){
158 char *profile_status = sqlite3_mprintf("%d", sqlcipher_cipher_profile(db, zRight));
159 codec_vdbe_return_string(pParse, "cipher_profile", profile_status, P4_DYNAMIC);
160 } else
161 if( sqlite3StrICmp(zLeft, "cipher_add_random")==0 && zRight ){
162 if(ctx) {
163 char *add_random_status = sqlite3_mprintf("%d", sqlcipher_codec_add_random(ctx, zRight, sqlite3Strlen30(zRight)));
164 codec_vdbe_return_string(pParse, "cipher_add_random", add_random_status, P4_DYNAMIC);
166 } else
167 if( sqlite3StrICmp(zLeft, "cipher_migrate")==0 && !zRight ){
168 if(ctx){
169 char *migrate_status = sqlite3_mprintf("%d", sqlcipher_codec_ctx_migrate(ctx));
170 codec_vdbe_return_string(pParse, "cipher_migrate", migrate_status, P4_DYNAMIC);
172 } else
173 if( sqlite3StrICmp(zLeft, "cipher_provider")==0 && !zRight ){
174 if(ctx) { codec_vdbe_return_string(pParse, "cipher_provider",
175 sqlcipher_codec_get_cipher_provider(ctx), P4_TRANSIENT);
177 } else
178 if( sqlite3StrICmp(zLeft, "cipher_provider_version")==0 && !zRight){
179 if(ctx) { codec_vdbe_return_string(pParse, "cipher_provider_version",
180 sqlcipher_codec_get_provider_version(ctx), P4_TRANSIENT);
182 } else
183 if( sqlite3StrICmp(zLeft, "cipher_version")==0 && !zRight ){
184 codec_vdbe_return_string(pParse, "cipher_version", sqlcipher_version(), P4_DYNAMIC);
185 }else
186 if( sqlite3StrICmp(zLeft, "cipher")==0 ){
187 if(ctx) {
188 if( zRight ) {
189 const char* message = "PRAGMA cipher is no longer supported.";
190 codec_vdbe_return_string(pParse, "cipher", message, P4_TRANSIENT);
191 sqlite3_log(SQLITE_WARNING, message);
192 }else {
193 codec_vdbe_return_string(pParse, "cipher", sqlcipher_codec_ctx_get_cipher(ctx), P4_TRANSIENT);
196 }else
197 if( sqlite3StrICmp(zLeft, "rekey_cipher")==0 && zRight ){
198 const char* message = "PRAGMA rekey_cipher is no longer supported.";
199 codec_vdbe_return_string(pParse, "rekey_cipher", message, P4_TRANSIENT);
200 sqlite3_log(SQLITE_WARNING, message);
201 }else
202 if( sqlite3StrICmp(zLeft,"cipher_default_kdf_iter")==0 ){
203 if( zRight ) {
204 sqlcipher_set_default_kdf_iter(atoi(zRight)); /* change default KDF iterations */
205 } else {
206 char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_get_default_kdf_iter());
207 codec_vdbe_return_string(pParse, "cipher_default_kdf_iter", kdf_iter, P4_DYNAMIC);
209 }else
210 if( sqlite3StrICmp(zLeft, "kdf_iter")==0 ){
211 if(ctx) {
212 if( zRight ) {
213 sqlcipher_codec_ctx_set_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */
214 } else {
215 char *kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_kdf_iter(ctx));
216 codec_vdbe_return_string(pParse, "kdf_iter", kdf_iter, P4_DYNAMIC);
219 }else
220 if( sqlite3StrICmp(zLeft, "fast_kdf_iter")==0){
221 if(ctx) {
222 if( zRight ) {
223 char *deprecation = "PRAGMA fast_kdf_iter is deprecated, please remove from use";
224 sqlcipher_codec_ctx_set_fast_kdf_iter(ctx, atoi(zRight)); /* change of RW PBKDF2 iteration */
225 codec_vdbe_return_string(pParse, "fast_kdf_iter", deprecation, P4_TRANSIENT);
226 sqlite3_log(SQLITE_WARNING, deprecation);
227 } else {
228 char *fast_kdf_iter = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_fast_kdf_iter(ctx));
229 codec_vdbe_return_string(pParse, "fast_kdf_iter", fast_kdf_iter, P4_DYNAMIC);
232 }else
233 if( sqlite3StrICmp(zLeft, "rekey_kdf_iter")==0 && zRight ){
234 const char* message = "PRAGMA rekey_kdf_iter is no longer supported.";
235 codec_vdbe_return_string(pParse, "rekey_kdf_iter", message, P4_TRANSIENT);
236 sqlite3_log(SQLITE_WARNING, message);
237 }else
238 if( sqlite3StrICmp(zLeft,"cipher_page_size")==0 ){
239 if(ctx) {
240 if( zRight ) {
241 int size = atoi(zRight);
242 rc = sqlcipher_codec_ctx_set_pagesize(ctx, size);
243 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
244 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
245 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
246 } else {
247 char * page_size = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_pagesize(ctx));
248 codec_vdbe_return_string(pParse, "cipher_page_size", page_size, P4_DYNAMIC);
251 }else
252 if( sqlite3StrICmp(zLeft,"cipher_default_page_size")==0 ){
253 if( zRight ) {
254 sqlcipher_set_default_pagesize(atoi(zRight));
255 } else {
256 char *default_page_size = sqlite3_mprintf("%d", sqlcipher_get_default_pagesize());
257 codec_vdbe_return_string(pParse, "cipher_default_page_size", default_page_size, P4_DYNAMIC);
259 }else
260 if( sqlite3StrICmp(zLeft,"cipher_default_use_hmac")==0 ){
261 if( zRight ) {
262 sqlcipher_set_default_use_hmac(sqlite3GetBoolean(zRight,1));
263 } else {
264 char *default_use_hmac = sqlite3_mprintf("%d", sqlcipher_get_default_use_hmac());
265 codec_vdbe_return_string(pParse, "cipher_default_use_hmac", default_use_hmac, P4_DYNAMIC);
267 }else
268 if( sqlite3StrICmp(zLeft,"cipher_use_hmac")==0 ){
269 if(ctx) {
270 if( zRight ) {
271 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, sqlite3GetBoolean(zRight,1));
272 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
273 /* since the use of hmac has changed, the page size may also change */
274 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
275 if(rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, rc);
276 } else {
277 char *hmac_flag = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_use_hmac(ctx));
278 codec_vdbe_return_string(pParse, "cipher_use_hmac", hmac_flag, P4_DYNAMIC);
281 }else
282 if( sqlite3StrICmp(zLeft,"cipher_hmac_pgno")==0 ){
283 if(ctx) {
284 if(zRight) {
285 char *deprecation = "PRAGMA cipher_hmac_pgno is deprecated, please remove from use";
286 /* clear both pgno endian flags */
287 if(sqlite3StrICmp(zRight, "le") == 0) {
288 sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO);
289 sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_LE_PGNO);
290 } else if(sqlite3StrICmp(zRight, "be") == 0) {
291 sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO);
292 sqlcipher_codec_ctx_set_flag(ctx, CIPHER_FLAG_BE_PGNO);
293 } else if(sqlite3StrICmp(zRight, "native") == 0) {
294 sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_LE_PGNO);
295 sqlcipher_codec_ctx_unset_flag(ctx, CIPHER_FLAG_BE_PGNO);
297 codec_vdbe_return_string(pParse, "cipher_hmac_pgno", deprecation, P4_TRANSIENT);
298 sqlite3_log(SQLITE_WARNING, deprecation);
300 } else {
301 if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_LE_PGNO)) {
302 codec_vdbe_return_string(pParse, "cipher_hmac_pgno", "le", P4_TRANSIENT);
303 } else if(sqlcipher_codec_ctx_get_flag(ctx, CIPHER_FLAG_BE_PGNO)) {
304 codec_vdbe_return_string(pParse, "cipher_hmac_pgno", "be", P4_TRANSIENT);
305 } else {
306 codec_vdbe_return_string(pParse, "cipher_hmac_pgno", "native", P4_TRANSIENT);
310 }else
311 if( sqlite3StrICmp(zLeft,"cipher_hmac_salt_mask")==0 ){
312 if(ctx) {
313 if(zRight) {
314 char *deprecation = "PRAGMA cipher_hmac_salt_mask is deprecated, please remove from use";
315 if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == 5) {
316 unsigned char mask = 0;
317 const unsigned char *hex = (const unsigned char *)zRight+2;
318 cipher_hex2bin(hex,2,&mask);
319 sqlcipher_set_hmac_salt_mask(mask);
321 codec_vdbe_return_string(pParse, "cipher_hmac_salt_mask", deprecation, P4_TRANSIENT);
322 sqlite3_log(SQLITE_WARNING, deprecation);
323 } else {
324 char *hmac_salt_mask = sqlite3_mprintf("%02x", sqlcipher_get_hmac_salt_mask());
325 codec_vdbe_return_string(pParse, "cipher_hmac_salt_mask", hmac_salt_mask, P4_DYNAMIC);
328 }else
329 if( sqlite3StrICmp(zLeft,"cipher_plaintext_header_size")==0 ){
330 if(ctx) {
331 if( zRight ) {
332 int size = atoi(zRight);
333 /* deliberately ignore result code, if size is invalid it will be set to -1
334 and trip the error later in the codec */
335 sqlcipher_codec_ctx_set_plaintext_header_size(ctx, size);
336 } else {
337 char *size = sqlite3_mprintf("%d", sqlcipher_codec_ctx_get_plaintext_header_size(ctx));
338 codec_vdbe_return_string(pParse, "cipher_plaintext_header_size", size, P4_DYNAMIC);
341 }else
342 if( sqlite3StrICmp(zLeft,"cipher_default_plaintext_header_size")==0 ){
343 if( zRight ) {
344 sqlcipher_set_default_plaintext_header_size(atoi(zRight));
345 } else {
346 char *size = sqlite3_mprintf("%d", sqlcipher_get_default_plaintext_header_size());
347 codec_vdbe_return_string(pParse, "cipher_default_plaintext_header_size", size, P4_DYNAMIC);
349 }else
350 if( sqlite3StrICmp(zLeft,"cipher_salt")==0 ){
351 if(ctx) {
352 if(zRight) {
353 if (sqlite3StrNICmp(zRight ,"x'", 2) == 0 && sqlite3Strlen30(zRight) == (FILE_HEADER_SZ*2)+3) {
354 unsigned char *salt = (unsigned char*) sqlite3_malloc(FILE_HEADER_SZ);
355 const unsigned char *hex = (const unsigned char *)zRight+2;
356 cipher_hex2bin(hex,FILE_HEADER_SZ*2,salt);
357 sqlcipher_codec_ctx_set_kdf_salt(ctx, salt, FILE_HEADER_SZ);
358 sqlite3_free(salt);
360 } else {
361 void *salt;
362 char *hexsalt = (char*) sqlite3_malloc((FILE_HEADER_SZ*2)+1);
363 if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &salt)) == SQLITE_OK) {
364 cipher_bin2hex(salt, FILE_HEADER_SZ, hexsalt);
365 codec_vdbe_return_string(pParse, "cipher_salt", hexsalt, P4_DYNAMIC);
366 } else {
367 sqlite3_free(hexsalt);
368 sqlcipher_codec_ctx_set_error(ctx, rc);
372 }else
373 if( sqlite3StrICmp(zLeft,"cipher_hmac_algorithm")==0 ){
374 if(ctx) {
375 if(zRight) {
376 rc = SQLITE_ERROR;
377 if(sqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) {
378 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
379 } else if(sqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) {
380 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA256);
381 } else if(sqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) {
382 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512);
384 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
385 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
386 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
387 } else {
388 int algorithm = sqlcipher_codec_ctx_get_hmac_algorithm(ctx);
389 if(algorithm == SQLCIPHER_HMAC_SHA1) {
390 codec_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT);
391 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
392 codec_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT);
393 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
394 codec_vdbe_return_string(pParse, "cipher_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT);
398 }else
399 if( sqlite3StrICmp(zLeft,"cipher_default_hmac_algorithm")==0 ){
400 if(zRight) {
401 rc = SQLITE_ERROR;
402 if(sqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA1_LABEL) == 0) {
403 rc = sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1);
404 } else if(sqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA256_LABEL) == 0) {
405 rc = sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA256);
406 } else if(sqlite3StrICmp(zRight, SQLCIPHER_HMAC_SHA512_LABEL) == 0) {
407 rc = sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA512);
409 } else {
410 int algorithm = sqlcipher_get_default_hmac_algorithm();
411 if(algorithm == SQLCIPHER_HMAC_SHA1) {
412 codec_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA1_LABEL, P4_TRANSIENT);
413 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
414 codec_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA256_LABEL, P4_TRANSIENT);
415 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
416 codec_vdbe_return_string(pParse, "cipher_default_hmac_algorithm", SQLCIPHER_HMAC_SHA512_LABEL, P4_TRANSIENT);
419 }else
420 if( sqlite3StrICmp(zLeft,"cipher_kdf_algorithm")==0 ){
421 if(ctx) {
422 if(zRight) {
423 rc = SQLITE_ERROR;
424 if(sqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) {
425 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
426 } else if(sqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) {
427 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA256);
428 } else if(sqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) {
429 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512);
431 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
432 } else {
433 int algorithm = sqlcipher_codec_ctx_get_kdf_algorithm(ctx);
434 if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
435 codec_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT);
436 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
437 codec_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT);
438 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
439 codec_vdbe_return_string(pParse, "cipher_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT);
443 }else
444 if( sqlite3StrICmp(zLeft,"cipher_default_kdf_algorithm")==0 ){
445 if(zRight) {
446 rc = SQLITE_ERROR;
447 if(sqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL) == 0) {
448 rc = sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1);
449 } else if(sqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL) == 0) {
450 rc = sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA256);
451 } else if(sqlite3StrICmp(zRight, SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL) == 0) {
452 rc = sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA512);
454 } else {
455 int algorithm = sqlcipher_get_default_kdf_algorithm();
456 if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
457 codec_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL, P4_TRANSIENT);
458 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
459 codec_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL, P4_TRANSIENT);
460 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
461 codec_vdbe_return_string(pParse, "cipher_default_kdf_algorithm", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL, P4_TRANSIENT);
464 }else
465 if( sqlite3StrICmp(zLeft,"cipher_compatibility")==0 ){
466 if(ctx) {
467 if(zRight) {
468 int version = atoi(zRight);
470 switch(version) {
471 case 1:
472 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
473 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
474 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
475 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
476 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
477 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
478 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000);
479 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
480 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 0);
481 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
482 break;
484 case 2:
485 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
486 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
487 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
488 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
489 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
490 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
491 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 4000);
492 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
493 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
494 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
495 break;
497 case 3:
498 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 1024);
499 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
500 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA1);
501 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
502 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA1);
503 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
504 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 64000);
505 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
506 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
507 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
508 break;
510 default:
511 rc = sqlcipher_codec_ctx_set_pagesize(ctx, 4096);
512 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
513 rc = sqlcipher_codec_ctx_set_hmac_algorithm(ctx, SQLCIPHER_HMAC_SHA512);
514 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
515 rc = sqlcipher_codec_ctx_set_kdf_algorithm(ctx, SQLCIPHER_PBKDF2_HMAC_SHA512);
516 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
517 rc = sqlcipher_codec_ctx_set_kdf_iter(ctx, 256000);
518 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
519 rc = sqlcipher_codec_ctx_set_use_hmac(ctx, 1);
520 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
521 break;
524 rc = codec_set_btree_to_codec_pagesize(db, pDb, ctx);
525 if (rc != SQLITE_OK) sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
528 }else
529 if( sqlite3StrICmp(zLeft,"cipher_default_compatibility")==0 ){
530 if(zRight) {
531 int version = atoi(zRight);
532 switch(version) {
533 case 1:
534 sqlcipher_set_default_pagesize(1024);
535 sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1);
536 sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1);
537 sqlcipher_set_default_kdf_iter(4000);
538 sqlcipher_set_default_use_hmac(0);
539 break;
541 case 2:
542 sqlcipher_set_default_pagesize(1024);
543 sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1);
544 sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1);
545 sqlcipher_set_default_kdf_iter(4000);
546 sqlcipher_set_default_use_hmac(1);
547 break;
549 case 3:
550 sqlcipher_set_default_pagesize(1024);
551 sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA1);
552 sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA1);
553 sqlcipher_set_default_kdf_iter(64000);
554 sqlcipher_set_default_use_hmac(1);
555 break;
557 default:
558 sqlcipher_set_default_pagesize(4096);
559 sqlcipher_set_default_hmac_algorithm(SQLCIPHER_HMAC_SHA512);
560 sqlcipher_set_default_kdf_algorithm(SQLCIPHER_PBKDF2_HMAC_SHA512);
561 sqlcipher_set_default_kdf_iter(256000);
562 sqlcipher_set_default_use_hmac(1);
563 break;
566 }else
567 if( sqlite3StrICmp(zLeft,"cipher_memory_security")==0 ){
568 if( zRight ) {
569 sqlcipher_set_mem_security(sqlite3GetBoolean(zRight,1));
570 } else {
571 char *on = sqlite3_mprintf("%d", sqlcipher_get_mem_security());
572 codec_vdbe_return_string(pParse, "cipher_memory_security", on, P4_DYNAMIC);
574 }else
575 if( sqlite3StrICmp(zLeft,"cipher_settings")==0 ){
576 if(ctx) {
577 int algorithm;
578 char *pragma;
580 pragma = sqlite3_mprintf("PRAGMA kdf_iter = %d;", sqlcipher_codec_ctx_get_kdf_iter(ctx));
581 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
583 pragma = sqlite3_mprintf("PRAGMA cipher_page_size = %d;", sqlcipher_codec_ctx_get_pagesize(ctx));
584 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
586 pragma = sqlite3_mprintf("PRAGMA cipher_use_hmac = %d;", sqlcipher_codec_ctx_get_use_hmac(ctx));
587 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
589 pragma = sqlite3_mprintf("PRAGMA cipher_plaintext_header_size = %d;", sqlcipher_codec_ctx_get_plaintext_header_size(ctx));
590 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
592 algorithm = sqlcipher_codec_ctx_get_hmac_algorithm(ctx);
593 pragma = NULL;
594 if(algorithm == SQLCIPHER_HMAC_SHA1) {
595 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL);
596 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
597 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL);
598 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
599 pragma = sqlite3_mprintf("PRAGMA cipher_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL);
601 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
603 algorithm = sqlcipher_codec_ctx_get_kdf_algorithm(ctx);
604 pragma = NULL;
605 if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
606 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL);
607 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
608 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL);
609 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
610 pragma = sqlite3_mprintf("PRAGMA cipher_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL);
612 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
615 }else
616 if( sqlite3StrICmp(zLeft,"cipher_default_settings")==0 ){
617 int algorithm;
618 char *pragma;
620 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_iter = %d;", sqlcipher_get_default_kdf_iter());
621 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
623 pragma = sqlite3_mprintf("PRAGMA cipher_default_page_size = %d;", sqlcipher_get_default_pagesize());
624 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
626 pragma = sqlite3_mprintf("PRAGMA cipher_default_use_hmac = %d;", sqlcipher_get_default_use_hmac());
627 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
629 pragma = sqlite3_mprintf("PRAGMA cipher_default_plaintext_header_size = %d;", sqlcipher_get_default_plaintext_header_size());
630 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
632 algorithm = sqlcipher_get_default_hmac_algorithm();
633 pragma = NULL;
634 if(algorithm == SQLCIPHER_HMAC_SHA1) {
635 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA1_LABEL);
636 } else if(algorithm == SQLCIPHER_HMAC_SHA256) {
637 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA256_LABEL);
638 } else if(algorithm == SQLCIPHER_HMAC_SHA512) {
639 pragma = sqlite3_mprintf("PRAGMA cipher_default_hmac_algorithm = %s;", SQLCIPHER_HMAC_SHA512_LABEL);
641 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
643 algorithm = sqlcipher_get_default_kdf_algorithm();
644 pragma = NULL;
645 if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA1) {
646 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA1_LABEL);
647 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA256) {
648 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA256_LABEL);
649 } else if(algorithm == SQLCIPHER_PBKDF2_HMAC_SHA512) {
650 pragma = sqlite3_mprintf("PRAGMA cipher_default_kdf_algorithm = %s;", SQLCIPHER_PBKDF2_HMAC_SHA512_LABEL);
652 codec_vdbe_return_string(pParse, "pragma", pragma, P4_DYNAMIC);
653 }else
654 if( sqlite3StrICmp(zLeft,"cipher_integrity_check")==0 ){
655 if(ctx) {
656 sqlcipher_codec_ctx_integrity_check(ctx, pParse, "cipher_integrity_check");
658 }else {
659 return 0;
661 return 1;
664 /* these constants are used internally within SQLite's pager.c to differentiate between
665 operations on the main database or journal pages. This is important in the context
666 of a rekey operations, where the journal must be written using the original key
667 material (to allow a transactional rollback), while the new database pages are being
668 written with the new key material*/
669 #define CODEC_READ_OP 3
670 #define CODEC_WRITE_OP 6
671 #define CODEC_JOURNAL_OP 7
674 * sqlite3Codec can be called in multiple modes.
675 * encrypt mode - expected to return a pointer to the
676 * encrypted data without altering pData.
677 * decrypt mode - expected to return a pointer to pData, with
678 * the data decrypted in the input buffer
680 static void* sqlite3Codec(void *iCtx, void *data, Pgno pgno, int mode) {
681 codec_ctx *ctx = (codec_ctx *) iCtx;
682 int offset = 0, rc = 0;
683 int page_sz = sqlcipher_codec_ctx_get_pagesize(ctx);
684 unsigned char *pData = (unsigned char *) data;
685 void *buffer = sqlcipher_codec_ctx_get_data(ctx);
686 int plaintext_header_sz = sqlcipher_codec_ctx_get_plaintext_header_size(ctx);
687 int cctx = CIPHER_READ_CTX;
689 CODEC_TRACE("sqlite3Codec: entered pgno=%d, mode=%d, page_sz=%d\n", pgno, mode, page_sz);
691 #ifdef SQLCIPHER_EXT
692 if(sqlcipher_license_check(ctx) != SQLITE_OK) return NULL;
693 #endif
695 /* call to derive keys if not present yet */
696 if((rc = sqlcipher_codec_key_derive(ctx)) != SQLITE_OK) {
697 sqlcipher_codec_ctx_set_error(ctx, rc);
698 return NULL;
701 /* if the plaintext_header_size is negative that means an invalid size was set via
702 PRAGMA. We can't set the error state on the pager at that point because the pager
703 may not be open yet. However, this is a fatal error state, so abort the codec */
704 if(plaintext_header_sz < 0) {
705 sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR);
706 return NULL;
709 if(pgno == 1) /* adjust starting pointers in data page for header offset on first page*/
710 offset = plaintext_header_sz ? plaintext_header_sz : FILE_HEADER_SZ;
713 CODEC_TRACE("sqlite3Codec: switch mode=%d offset=%d\n", mode, offset);
714 switch(mode) {
715 case CODEC_READ_OP: /* decrypt */
716 if(pgno == 1) /* copy initial part of file header or SQLite magic to buffer */
717 memcpy(buffer, plaintext_header_sz ? pData : (void *) SQLITE_FILE_HEADER, offset);
719 rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_DECRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
720 #ifdef SQLCIPHER_TEST
721 if(cipher_fail_next_decrypt) rc = SQLITE_ERROR;
722 #endif
723 if(rc != SQLITE_OK) { /* clear results of failed cipher operation and set error */
724 sqlcipher_memset((unsigned char*) buffer+offset, 0, page_sz-offset);
725 sqlcipher_codec_ctx_set_error(ctx, rc);
727 memcpy(pData, buffer, page_sz); /* copy buffer data back to pData and return */
728 return pData;
729 break;
731 case CODEC_WRITE_OP: /* encrypt database page, operate on write context and fall through to case 7, so the write context is used*/
732 cctx = CIPHER_WRITE_CTX;
734 case CODEC_JOURNAL_OP: /* encrypt journal page, operate on read context use to get the original page data from the database */
735 if(pgno == 1) { /* copy initial part of file header or salt to buffer */
736 void *kdf_salt = NULL;
737 /* retrieve the kdf salt */
738 if((rc = sqlcipher_codec_ctx_get_kdf_salt(ctx, &kdf_salt)) != SQLITE_OK) {
739 sqlcipher_codec_ctx_set_error(ctx, rc);
740 return NULL;
742 memcpy(buffer, plaintext_header_sz ? pData : kdf_salt, offset);
744 rc = sqlcipher_page_cipher(ctx, cctx, pgno, CIPHER_ENCRYPT, page_sz - offset, pData + offset, (unsigned char*)buffer + offset);
745 #ifdef SQLCIPHER_TEST
746 if(cipher_fail_next_encrypt) rc = SQLITE_ERROR;
747 #endif
748 if(rc != SQLITE_OK) { /* clear results of failed cipher operation and set error */
749 sqlcipher_memset((unsigned char*)buffer+offset, 0, page_sz-offset);
750 sqlcipher_codec_ctx_set_error(ctx, rc);
751 return NULL;
753 return buffer; /* return persistent buffer data, pData remains intact */
754 break;
756 default:
757 sqlcipher_codec_ctx_set_error(ctx, SQLITE_ERROR); /* unsupported mode, set error */
758 return pData;
759 break;
763 static void sqlite3FreeCodecArg(void *pCodecArg) {
764 codec_ctx *ctx = (codec_ctx *) pCodecArg;
765 if(pCodecArg == NULL) return;
766 sqlcipher_codec_ctx_free(&ctx); /* wipe and free allocated memory for the context */
767 sqlcipher_deactivate(); /* cleanup related structures, OpenSSL etc, when codec is detatched */
770 int sqlite3CodecAttach(sqlite3* db, int nDb, const void *zKey, int nKey) {
771 struct Db *pDb = &db->aDb[nDb];
773 CODEC_TRACE("sqlite3CodecAttach: entered db=%p, nDb=%d zKey=%p, nKey=%d\n", db, nDb, zKey, nKey);
776 if(nKey && zKey && pDb->pBt) {
777 int rc;
778 Pager *pPager = pDb->pBt->pBt->pPager;
779 sqlite3_file *fd;
780 codec_ctx *ctx;
782 /* check if the sqlite3_file is open, and if not force handle to NULL */
783 if((fd = sqlite3PagerFile(pPager))->pMethods == 0) fd = NULL;
785 CODEC_TRACE("sqlite3CodecAttach: calling sqlcipher_activate()\n");
786 sqlcipher_activate(); /* perform internal initialization for sqlcipher */
788 CODEC_TRACE_MUTEX("sqlite3CodecAttach: entering database mutex %p\n", db->mutex);
789 sqlite3_mutex_enter(db->mutex);
790 CODEC_TRACE_MUTEX("sqlite3CodecAttach: entered database mutex %p\n", db->mutex);
792 #ifdef SQLCIPHER_EXT
793 if((rc = sqlite3_set_authorizer(db, sqlcipher_license_authorizer, db)) != SQLITE_OK) {
794 sqlite3_mutex_leave(db->mutex);
795 return rc;
797 #endif
799 /* point the internal codec argument against the contet to be prepared */
800 CODEC_TRACE("sqlite3CodecAttach: calling sqlcipher_codec_ctx_init()\n");
801 rc = sqlcipher_codec_ctx_init(&ctx, pDb, pDb->pBt->pBt->pPager, zKey, nKey);
803 if(rc != SQLITE_OK) {
804 /* initialization failed, do not attach potentially corrupted context */
805 CODEC_TRACE("sqlite3CodecAttach: context initialization failed with rc=%d\n", rc);
806 /* force an error at the pager level, such that even the upstream caller ignores the return code
807 the pager will be in an error state and will process no further operations */
808 sqlite3pager_error(pPager, rc);
809 pDb->pBt->pBt->db->errCode = rc;
810 CODEC_TRACE_MUTEX("sqlite3CodecAttach: leaving database mutex %p (early return on rc=%d)\n", db->mutex, rc);
811 sqlite3_mutex_leave(db->mutex);
812 CODEC_TRACE_MUTEX("sqlite3CodecAttach: left database mutex %p (early return on rc=%d)\n", db->mutex, rc);
813 return rc;
816 CODEC_TRACE("sqlite3CodecAttach: calling sqlite3PagerSetCodec()\n");
817 sqlite3PagerSetCodec(sqlite3BtreePager(pDb->pBt), sqlite3Codec, NULL, sqlite3FreeCodecArg, (void *) ctx);
819 CODEC_TRACE("sqlite3CodecAttach: calling codec_set_btree_to_codec_pagesize()\n");
820 codec_set_btree_to_codec_pagesize(db, pDb, ctx);
822 /* force secure delete. This has the benefit of wiping internal data when deleted
823 and also ensures that all pages are written to disk (i.e. not skipped by
824 sqlite3PagerDontWrite optimizations) */
825 CODEC_TRACE("sqlite3CodecAttach: calling sqlite3BtreeSecureDelete()\n");
826 sqlite3BtreeSecureDelete(pDb->pBt, 1);
828 /* if fd is null, then this is an in-memory database and
829 we dont' want to overwrite the AutoVacuum settings
830 if not null, then set to the default */
831 if(fd != NULL) {
832 CODEC_TRACE("sqlite3CodecAttach: calling sqlite3BtreeSetAutoVacuum()\n");
833 sqlite3BtreeSetAutoVacuum(pDb->pBt, SQLITE_DEFAULT_AUTOVACUUM);
835 CODEC_TRACE_MUTEX("sqlite3CodecAttach: leaving database mutex %p\n", db->mutex);
836 sqlite3_mutex_leave(db->mutex);
837 CODEC_TRACE_MUTEX("sqlite3CodecAttach: left database mutex %p\n", db->mutex);
839 return SQLITE_OK;
842 int sqlcipher_find_db_index(sqlite3 *db, const char *zDb) {
843 int db_index;
844 if(zDb == NULL){
845 return 0;
847 for(db_index = 0; db_index < db->nDb; db_index++) {
848 struct Db *pDb = &db->aDb[db_index];
849 if(strcmp(pDb->zDbSName, zDb) == 0) {
850 return db_index;
853 return 0;
856 void sqlite3_activate_see(const char* in) {
857 /* do nothing, security enhancements are always active */
860 int sqlite3_key(sqlite3 *db, const void *pKey, int nKey) {
861 CODEC_TRACE("sqlite3_key entered: db=%p pKey=%p nKey=%d\n", db, pKey, nKey);
862 return sqlite3_key_v2(db, "main", pKey, nKey);
865 int sqlite3_key_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) {
866 CODEC_TRACE("sqlite3_key_v2: entered db=%p zDb=%s pKey=%p nKey=%d\n", db, zDb, pKey, nKey);
867 /* attach key if db and pKey are not null and nKey is > 0 */
868 if(db && pKey && nKey) {
869 int db_index = sqlcipher_find_db_index(db, zDb);
870 return sqlite3CodecAttach(db, db_index, pKey, nKey);
872 return SQLITE_ERROR;
875 int sqlite3_rekey(sqlite3 *db, const void *pKey, int nKey) {
876 CODEC_TRACE("sqlite3_rekey entered: db=%p pKey=%p nKey=%d\n", db, pKey, nKey);
877 return sqlite3_rekey_v2(db, "main", pKey, nKey);
880 /* sqlite3_rekey_v2
881 ** Given a database, this will reencrypt the database using a new key.
882 ** There is only one possible modes of operation - to encrypt a database
883 ** that is already encrpyted. If the database is not already encrypted
884 ** this should do nothing
885 ** The proposed logic for this function follows:
886 ** 1. Determine if the database is already encryptped
887 ** 2. If there is NOT already a key present do nothing
888 ** 3. If there is a key present, re-encrypt the database with the new key
890 int sqlite3_rekey_v2(sqlite3 *db, const char *zDb, const void *pKey, int nKey) {
891 CODEC_TRACE("sqlite3_rekey_v2: entered db=%p zDb=%s pKey=%p, nKey=%d\n", db, zDb, pKey, nKey);
892 if(db && pKey && nKey) {
893 int db_index = sqlcipher_find_db_index(db, zDb);
894 struct Db *pDb = &db->aDb[db_index];
895 CODEC_TRACE("sqlite3_rekey_v2: database pDb=%p db_index:%d\n", pDb, db_index);
896 if(pDb->pBt) {
897 codec_ctx *ctx;
898 int rc, page_count;
899 Pgno pgno;
900 PgHdr *page;
901 Pager *pPager = pDb->pBt->pBt->pPager;
903 ctx = (codec_ctx*) sqlite3PagerGetCodec(pDb->pBt->pBt->pPager);
905 if(ctx == NULL) {
906 /* there was no codec attached to this database, so this should do nothing! */
907 CODEC_TRACE("sqlite3_rekey_v2: no codec attached to db, exiting\n");
908 return SQLITE_OK;
911 CODEC_TRACE_MUTEX("sqlite3_rekey_v2: entering database mutex %p\n", db->mutex);
912 sqlite3_mutex_enter(db->mutex);
913 CODEC_TRACE_MUTEX("sqlite3_rekey_v2: entered database mutex %p\n", db->mutex);
915 codec_set_pass_key(db, db_index, pKey, nKey, CIPHER_WRITE_CTX);
917 /* do stuff here to rewrite the database
918 ** 1. Create a transaction on the database
919 ** 2. Iterate through each page, reading it and then writing it.
920 ** 3. If that goes ok then commit and put ctx->rekey into ctx->key
921 ** note: don't deallocate rekey since it may be used in a subsequent iteration
923 rc = sqlite3BtreeBeginTrans(pDb->pBt, 1, 0); /* begin write transaction */
924 sqlite3PagerPagecount(pPager, &page_count);
925 for(pgno = 1; rc == SQLITE_OK && pgno <= (unsigned int)page_count; pgno++) { /* pgno's start at 1 see pager.c:pagerAcquire */
926 if(!sqlite3pager_is_mj_pgno(pPager, pgno)) { /* skip this page (see pager.c:pagerAcquire for reasoning) */
927 rc = sqlite3PagerGet(pPager, pgno, &page, 0);
928 if(rc == SQLITE_OK) { /* write page see pager_incr_changecounter for example */
929 rc = sqlite3PagerWrite(page);
930 if(rc == SQLITE_OK) {
931 sqlite3PagerUnref(page);
932 } else {
933 CODEC_TRACE("sqlite3_rekey_v2: error %d occurred writing page %d\n", rc, pgno);
935 } else {
936 CODEC_TRACE("sqlite3_rekey_v2: error %d occurred getting page %d\n", rc, pgno);
941 /* if commit was successful commit and copy the rekey data to current key, else rollback to release locks */
942 if(rc == SQLITE_OK) {
943 CODEC_TRACE("sqlite3_rekey_v2: committing\n");
944 rc = sqlite3BtreeCommit(pDb->pBt);
945 sqlcipher_codec_key_copy(ctx, CIPHER_WRITE_CTX);
946 } else {
947 CODEC_TRACE("sqlite3_rekey_v2: rollback\n");
948 sqlite3BtreeRollback(pDb->pBt, SQLITE_ABORT_ROLLBACK, 0);
951 CODEC_TRACE_MUTEX("sqlite3_rekey_v2: leaving database mutex %p\n", db->mutex);
952 sqlite3_mutex_leave(db->mutex);
953 CODEC_TRACE_MUTEX("sqlite3_rekey_v2: left database mutex %p\n", db->mutex);
955 return SQLITE_OK;
957 return SQLITE_ERROR;
960 void sqlite3CodecGetKey(sqlite3* db, int nDb, void **zKey, int *nKey) {
961 struct Db *pDb = &db->aDb[nDb];
962 CODEC_TRACE("sqlite3CodecGetKey: entered db=%p, nDb=%d\n", db, nDb);
963 if( pDb->pBt ) {
964 codec_ctx *ctx = (codec_ctx*) sqlite3PagerGetCodec(pDb->pBt->pBt->pPager);
966 if(ctx) {
967 /* pass back the keyspec from the codec, unless PRAGMA cipher_store_pass
968 is set or keyspec has not yet been derived, in which case pass
969 back the password key material */
970 sqlcipher_codec_get_keyspec(ctx, zKey, nKey);
971 if(sqlcipher_codec_get_store_pass(ctx) == 1 || *zKey == NULL) {
972 sqlcipher_codec_get_pass(ctx, zKey, nKey);
974 } else {
975 *zKey = NULL;
976 *nKey = 0;
982 * Implementation of an "export" function that allows a caller
983 * to duplicate the main database to an attached database. This is intended
984 * as a conveneince for users who need to:
986 * 1. migrate from an non-encrypted database to an encrypted database
987 * 2. move from an encrypted database to a non-encrypted database
988 * 3. convert beween the various flavors of encrypted databases.
990 * This implementation is based heavily on the procedure and code used
991 * in vacuum.c, but is exposed as a function that allows export to any
992 * named attached database.
996 ** Finalize a prepared statement. If there was an error, store the
997 ** text of the error message in *pzErrMsg. Return the result code.
999 ** Based on vacuumFinalize from vacuum.c
1001 static int sqlcipher_finalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
1002 int rc;
1003 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
1004 if( rc ){
1005 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
1007 return rc;
1011 ** Execute zSql on database db. Return an error code.
1013 ** Based on execSql from vacuum.c
1015 static int sqlcipher_execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
1016 sqlite3_stmt *pStmt;
1017 VVA_ONLY( int rc; )
1018 if( !zSql ){
1019 return SQLITE_NOMEM;
1021 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
1022 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
1023 return sqlite3_errcode(db);
1025 VVA_ONLY( rc = ) sqlite3_step(pStmt);
1026 assert( rc!=SQLITE_ROW );
1027 return sqlcipher_finalize(db, pStmt, pzErrMsg);
1031 ** Execute zSql on database db. The statement returns exactly
1032 ** one column. Execute this as SQL on the same database.
1034 ** Based on execExecSql from vacuum.c
1036 static int sqlcipher_execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
1037 sqlite3_stmt *pStmt;
1038 int rc;
1040 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1041 if( rc!=SQLITE_OK ) return rc;
1043 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1044 rc = sqlcipher_execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
1045 if( rc!=SQLITE_OK ){
1046 sqlcipher_finalize(db, pStmt, pzErrMsg);
1047 return rc;
1051 return sqlcipher_finalize(db, pStmt, pzErrMsg);
1055 * copy database and schema from the main database to an attached database
1057 * Based on sqlite3RunVacuum from vacuum.c
1059 void sqlcipher_exportFunc(sqlite3_context *context, int argc, sqlite3_value **argv) {
1060 sqlite3 *db = sqlite3_context_db_handle(context);
1061 const char* targetDb, *sourceDb;
1062 int targetDb_idx = 0;
1063 u64 saved_flags = db->flags; /* Saved value of the db->flags */
1064 u32 saved_mDbFlags = db->mDbFlags; /* Saved value of the db->mDbFlags */
1065 int saved_nChange = db->nChange; /* Saved value of db->nChange */
1066 int saved_nTotalChange = db->nTotalChange; /* Saved value of db->nTotalChange */
1067 u8 saved_mTrace = db->mTrace; /* Saved value of db->mTrace */
1068 int rc = SQLITE_OK; /* Return code from service routines */
1069 char *zSql = NULL; /* SQL statements */
1070 char *pzErrMsg = NULL;
1072 if(argc != 1 && argc != 2) {
1073 rc = SQLITE_ERROR;
1074 pzErrMsg = sqlite3_mprintf("invalid number of arguments (%d) passed to sqlcipher_export", argc);
1075 goto end_of_export;
1078 if(sqlite3_value_type(argv[0]) == SQLITE_NULL) {
1079 rc = SQLITE_ERROR;
1080 pzErrMsg = sqlite3_mprintf("target database can't be NULL");
1081 goto end_of_export;
1084 targetDb = (const char*) sqlite3_value_text(argv[0]);
1085 sourceDb = "main";
1087 if(argc == 2) {
1088 if(sqlite3_value_type(argv[1]) == SQLITE_NULL) {
1089 rc = SQLITE_ERROR;
1090 pzErrMsg = sqlite3_mprintf("target database can't be NULL");
1091 goto end_of_export;
1093 sourceDb = (char *) sqlite3_value_text(argv[1]);
1097 /* if the name of the target is not main, but the index returned is zero
1098 there is a mismatch and we should not proceed */
1099 targetDb_idx = sqlcipher_find_db_index(db, targetDb);
1100 if(targetDb_idx == 0 && targetDb != NULL && sqlite3StrICmp("main", targetDb) != 0) {
1101 rc = SQLITE_ERROR;
1102 pzErrMsg = sqlite3_mprintf("unknown database %s", targetDb);
1103 goto end_of_export;
1105 db->init.iDb = targetDb_idx;
1107 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
1108 db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
1109 db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_Defensive | SQLITE_CountRows);
1110 db->mTrace = 0;
1112 /* Query the schema of the main database. Create a mirror schema
1113 ** in the temporary database.
1115 zSql = sqlite3_mprintf(
1116 "SELECT sql "
1117 " FROM %s.sqlite_schema WHERE type='table' AND name!='sqlite_sequence'"
1118 " AND rootpage>0"
1119 , sourceDb);
1120 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
1121 if( rc!=SQLITE_OK ) goto end_of_export;
1122 sqlite3_free(zSql);
1124 zSql = sqlite3_mprintf(
1125 "SELECT sql "
1126 " FROM %s.sqlite_schema WHERE sql LIKE 'CREATE INDEX %%' "
1127 , sourceDb);
1128 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
1129 if( rc!=SQLITE_OK ) goto end_of_export;
1130 sqlite3_free(zSql);
1132 zSql = sqlite3_mprintf(
1133 "SELECT sql "
1134 " FROM %s.sqlite_schema WHERE sql LIKE 'CREATE UNIQUE INDEX %%'"
1135 , sourceDb);
1136 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
1137 if( rc!=SQLITE_OK ) goto end_of_export;
1138 sqlite3_free(zSql);
1140 /* Loop through the tables in the main database. For each, do
1141 ** an "INSERT INTO rekey_db.xxx SELECT * FROM main.xxx;" to copy
1142 ** the contents to the temporary database.
1144 zSql = sqlite3_mprintf(
1145 "SELECT 'INSERT INTO %s.' || quote(name) "
1146 "|| ' SELECT * FROM %s.' || quote(name) || ';'"
1147 "FROM %s.sqlite_schema "
1148 "WHERE type = 'table' AND name!='sqlite_sequence' "
1149 " AND rootpage>0"
1150 , targetDb, sourceDb, sourceDb);
1151 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
1152 if( rc!=SQLITE_OK ) goto end_of_export;
1153 sqlite3_free(zSql);
1155 /* Copy over the contents of the sequence table
1157 zSql = sqlite3_mprintf(
1158 "SELECT 'INSERT INTO %s.' || quote(name) "
1159 "|| ' SELECT * FROM %s.' || quote(name) || ';' "
1160 "FROM %s.sqlite_schema WHERE name=='sqlite_sequence';"
1161 , targetDb, sourceDb, targetDb);
1162 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execExecSql(db, &pzErrMsg, zSql);
1163 if( rc!=SQLITE_OK ) goto end_of_export;
1164 sqlite3_free(zSql);
1166 /* Copy the triggers, views, and virtual tables from the main database
1167 ** over to the temporary database. None of these objects has any
1168 ** associated storage, so all we have to do is copy their entries
1169 ** from the SQLITE_MASTER table.
1171 zSql = sqlite3_mprintf(
1172 "INSERT INTO %s.sqlite_schema "
1173 " SELECT type, name, tbl_name, rootpage, sql"
1174 " FROM %s.sqlite_schema"
1175 " WHERE type='view' OR type='trigger'"
1176 " OR (type='table' AND rootpage=0)"
1177 , targetDb, sourceDb);
1178 rc = (zSql == NULL) ? SQLITE_NOMEM : sqlcipher_execSql(db, &pzErrMsg, zSql);
1179 if( rc!=SQLITE_OK ) goto end_of_export;
1180 sqlite3_free(zSql);
1182 zSql = NULL;
1183 end_of_export:
1184 db->init.iDb = 0;
1185 db->flags = saved_flags;
1186 db->mDbFlags = saved_mDbFlags;
1187 db->nChange = saved_nChange;
1188 db->nTotalChange = saved_nTotalChange;
1189 db->mTrace = saved_mTrace;
1191 if(zSql) sqlite3_free(zSql);
1193 if(rc) {
1194 if(pzErrMsg != NULL) {
1195 sqlite3_result_error(context, pzErrMsg, -1);
1196 sqlite3DbFree(db, pzErrMsg);
1197 } else {
1198 sqlite3_result_error(context, sqlite3ErrStr(rc), -1);
1202 #endif
1203 /* END SQLCIPHER */