Repository navigation
Expand file tree
/
Copy pathscript.c
More file actions
1241 lines (1177 loc) · 53.7 KB
/
Copy pathscript.c
File metadata and controls
1241 lines (1177 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Interprets fuzzer bytes as SQLCipher operations: keys, codec pragmas, writes, rekeys, exports and file damage. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "confidentiality.h"
#include "fault.h"
#include "known.h"
#include "libstate.h"
#include "memvfs.h"
#include "model.h"
#include "tamper.h"
#include "uniqueness.h"
#include "script.h"
#define MAX_OPS 64
#define MAX_RECIPE 16
#define MAX_BLOB 20000
#define MAX_RAW_SQL 2048
#define MAX_DUMP (1 << 20)
#define MAX_DUMP_TABLES 8
/* Progress callbacks, each every 100 VDBE ops, before a run or a read-back is interrupted. */
#define SCRIPT_BUDGET 20000
#define DUMP_BUDGET 20000
static const char *const files[SCRIPT_FILES] = {"main.db", "other.db", "third.db"};
/* Every value here is permanent once assigned: script_run masks the selector byte with OP_MASK and dispatches on
the numeric value directly, not on position, so a saved crash or corpus entry keeps meaning exactly what it
meant when it was written even as new ops are added. Adding one means picking the next free number below
OP_MASK + 1 and appending it here; it never means inserting into or renumbering the existing list. A selector
byte that masks to a number with no assigned op here is a no-op: growing OP_COUNT is the only way an old input's
behaviour can change, by filling in a slot that used to be a no-op, and only for the specific byte values that
land on that exact slot, not for every byte the way changing a modulus would. */
#define OP_MASK 0x1f
enum op {
OP_OPEN = 0,
OP_REOPEN = 1,
OP_CLOSE = 2,
OP_KEY = 3,
OP_REKEY = 4,
OP_SETTING = 5,
OP_STATEMENT = 6,
OP_PRAGMA = 7,
OP_ATTACH = 8,
OP_BACKUP = 9,
OP_DAMAGE = 10,
OP_READ = 11,
OP_CACHE_RACE = 12,
OP_RAW_SQL = 13,
OP_CANARY = 14,
OP_FAULT_TXN = 15,
OP_COUNT = 16,
};
enum step_kind { STEP_KEY, STEP_REKEY, STEP_SETTING };
/* A step is the input slice its operation parsed, so replaying it rebuilds the same key or pragma. */
struct step {
enum step_kind kind;
struct input slice;
};
struct recipe {
struct step steps[MAX_RECIPE];
int count;
/* Set once a passphrase key is recorded, since PBKDF2 then runs at the file's kdf_iter. */
int passphrase;
};
struct key {
unsigned char bytes[128];
int len;
int passphrase;
int kdf_iter;
/* Raw-hex-key path only: whether op_key should run PRAGMA cipher_migrate immediately after this key, its only
chance to see the connection's still-present underived passphrase. */
int migrate;
};
static const struct fuzz_sqlite *lib;
/* SQLCipher major version of lib, since 5.x drops and adds codec pragmas. */
static int major;
static sqlite3 *db;
static int db_file = -1;
/* Set once the open connection has read or written its file, which ends the window for a first key. */
static int touched;
/* cipher_default_page_size of lib, which a new ATTACH keys its file with. */
static int default_page;
static int trusted;
static long budget;
static struct recipe recipes[SCRIPT_FILES];
/* Whether OP_OPEN has ever made file the connection's own db_file before, for the model oracle: a second OP_OPEN
targeting it discards its recorded recipe right there, but anything a prior connection to the same index
already wrote, export included, persists in the file underneath regardless, so a later reopen's replay is not
this module's finding to make once that has ever happened, whatever the recipe it discarded looked like. */
static int ever_db_file[SCRIPT_FILES];
/* Whether file has ever gone through an operation differential_plain's own comparison cannot trust: sqlcipher_export
(the function itself does not exist on a provider with no codec at all, so content it moved has no plain-SQLite
equivalent to compare against), a rekey that was the very first key-related step for the file (which may have
retroactively re-encrypted content a canary or statement already wrote in plaintext, something replay's own
reconstruction has no faithful way to redo), or a backup destination (backup_step's own page-copy write path is
not a normal key_v2-then-SQL flow replay reconstructs faithfully either). Despite the name, every one of these
is the same "not this comparison's finding to make" signal, so one shared array covers all three. */
static int export_touched[SCRIPT_FILES];
/* Whether OP_FAULT_TXN ever ran against file, for differential_plain: the same countdown lands at a wildly
different logical I/O moment on a codec connection, which reads and writes many times per logical operation,
than on one with no codec at all, so a fault armed here can legitimately make the two sides diverge in ways
that are not a cipher-vs-plain behavioural difference. */
static int fault_touched[SCRIPT_FILES];
static unsigned u8(struct input *in) {
if (!in->size) return 0;
in->size--;
return *in->data++;
}
static unsigned u16(struct input *in) {
unsigned low = u8(in);
return low | u8(in) << 8;
}
static unsigned long u32(struct input *in) {
unsigned long low = u16(in);
return low | (unsigned long)u16(in) << 16;
}
static struct input take(struct input *in, size_t max) {
size_t len = u16(in) % (max + 1);
if (len > in->size) len = in->size;
struct input out = {in->data, len};
in->data += len;
in->size -= len;
return out;
}
static void dump_put(struct dump *out, const void *bytes, size_t len) {
if (!out) return;
fuzz_grow_append(&out->bytes, &out->len, &out->cap, MAX_DUMP, bytes, len);
}
static void dump_code(struct dump *out, int rc) {
unsigned char code = (unsigned char)rc;
dump_put(out, &code, 1);
}
void dump_free(struct dump *out) {
free(out->bytes);
memset(out, 0, sizeof *out);
}
/* Pragmas the input may not reach: PBKDF2 cost, disk output, and process-wide state no reset can undo. */
static int authorize(void *unused, int action, const char *name, const char *value, const char *schema,
const char *trigger) {
static const char *const denied[] = {
"key", "rekey", "hexkey", "hexrekey",
"textkey", "textrekey", "kdf_iter", "fast_kdf_iter",
"rekey_kdf_iter", "cipher_default_kdf_iter", "cipher_compatibility",
"cipher_default_compatibility", "cipher_migrate", "cipher_memory_security",
"cipher_hmac_salt_mask", "cipher_profile", "cipher_log", "cipher_log_level", "cipher_log_source",
};
(void)unused;
(void)schema;
(void)trigger;
if (trusted || !name) return SQLITE_OK;
/* L8: an attached plaintext-header file read with a page size other than the one its header states. */
if (action == SQLITE_ATTACH)
return known_header_page_mismatch(major, memvfs_header_page_size(name), default_page) ? SQLITE_DENY : SQLITE_OK;
if (action != SQLITE_PRAGMA) return SQLITE_OK;
for (size_t i = 0; i < sizeof denied / sizeof *denied; i++) {
if (strcasecmp(name, denied[i]) == 0) return SQLITE_DENY;
}
if (known_denied_pragma(major, name, value)) return SQLITE_DENY;
if (touched && value && known_late_setting(name)) return SQLITE_DENY; /* L6 */
return SQLITE_OK;
}
static int progress(void *unused) {
(void)unused;
return --budget < 0;
}
static sqlite3 *open_file(int file, int create) {
sqlite3 *handle = NULL;
int flags = SQLITE_OPEN_READWRITE | (create ? SQLITE_OPEN_CREATE : 0);
if (lib->open_v2(files[file], &handle, flags, NULL) != SQLITE_OK) {
lib->close_v2(handle);
return NULL;
}
lib->set_authorizer(handle, authorize, NULL);
lib->progress_handler(handle, 100, progress, NULL);
lib->limit(handle, SQLITE_LIMIT_LENGTH, 1 << 20);
lib->limit(handle, SQLITE_LIMIT_SQL_LENGTH, 1 << 16);
lib->limit(handle, SQLITE_LIMIT_VDBE_OP, 25000);
return handle;
}
static void close_db(void) {
if (db) {
uniqueness_check(lib, db, "main", db_file, files[db_file]);
lib->close_v2(db);
}
db = NULL;
db_file = -1;
touched = 0;
}
static void dump_row(sqlite3_stmt *stmt, struct dump *out) {
int columns = lib->column_count(stmt);
for (int i = 0; i < columns; i++) {
unsigned char type = (unsigned char)lib->column_type(stmt, i);
dump_put(out, &type, 1);
if (type == SQLITE_INTEGER) {
sqlite3_int64 value = lib->column_int64(stmt, i);
dump_put(out, &value, sizeof value);
} else if (type == SQLITE_FLOAT) {
double value = lib->column_double(stmt, i);
dump_put(out, &value, sizeof value);
} else if (type != SQLITE_NULL) {
const void *bytes = lib->column_blob(stmt, i);
int len = lib->column_bytes(stmt, i);
dump_put(out, &len, sizeof len);
if (bytes) dump_put(out, bytes, (size_t)len);
}
}
}
static int drain(sqlite3_stmt *stmt, struct dump *out) {
int rc;
while ((rc = lib->step(stmt)) == SQLITE_ROW) dump_row(stmt, out);
lib->finalize(stmt);
return rc == SQLITE_DONE ? SQLITE_OK : rc;
}
/* Whether a trivial read through handle's schema actually decodes: forces a page 1 read, which returns something
other than SQLITE_ROW or SQLITE_DONE when the key just applied to this connection does not match content the
file already had, whether that content is plaintext or encrypted under a different key. A fresh, empty file
trivially passes, since there is nothing to fail to decode. Returns the raw result code, for the wrong-key
oracle to check directly rather than just a pass/fail boolean. */
static int key_verified(sqlite3 *handle, const char *schema) {
char sql[64];
snprintf(sql, sizeof sql, "PRAGMA \"%s\".schema_version", schema);
sqlite3_stmt *stmt = NULL;
int rc = lib->prepare_v2(handle, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) return rc;
rc = lib->step(stmt);
lib->finalize(stmt);
return rc;
}
static int verified(int rc) { return rc == SQLITE_ROW || rc == SQLITE_DONE; }
/* L1: VACUUM INTO, and VACUUM with a file temp store, copy pages into a database keyed with the default page size. */
static int vacuum_blocked(sqlite3 *handle, int vacuum) {
if (!vacuum || (vacuum == 1 && lib_int(lib, handle, "PRAGMA temp_store") != 1)) return 0;
return known_backup_blocked(major, fuzz_codec_page_size(lib, handle), lib_int(lib, handle, "PRAGMA cipher_default_page_size"));
}
/* L8: the handle would read file's plaintext-header database with a different page size than the header states. */
static int header_mismatch(sqlite3 *handle, int file) {
int header_page = file < 0 ? 0 : memvfs_header_page_size(files[file]);
return header_page && known_header_page_mismatch(major, header_page, fuzz_codec_page_size(lib, handle));
}
/* Runs every statement in sql and returns the first failure. */
static int run(sqlite3 *handle, const char *sql, struct dump *out) {
int result = SQLITE_OK;
while (sql && *sql) {
sqlite3_stmt *stmt = NULL;
const char *tail = NULL;
int rc = lib->prepare_v2(handle, sql, -1, &stmt, &tail);
if (rc == SQLITE_OK && stmt && !trusted && vacuum_blocked(handle, known_vacuum(sql, (size_t)(tail - sql)))) {
lib->finalize(stmt);
stmt = NULL;
rc = SQLITE_AUTH;
}
if (rc == SQLITE_OK && stmt) rc = drain(stmt, out);
if (handle == db && !trusted) {
default_page = lib_int(lib, handle, "PRAGMA cipher_default_page_size");
touched = 1;
if (header_mismatch(db, db_file)) break;
}
dump_code(out, rc);
if (result == SQLITE_OK) result = rc;
if (rc != SQLITE_OK && !stmt) break;
sql = tail;
}
return result;
}
static int run_trusted(sqlite3 *handle, const char *sql, struct dump *out) {
trusted = 1;
int rc = run(handle, sql, out);
trusted = 0;
return rc;
}
/* read_key's key->len for its 48-byte raw-hex form (x'<64 hex digits key><32 hex digits salt>'): 3 wrapper bytes
(x, both quotes) plus 96 hex digits. The trailing 32 hex digits are an explicit salt SQLCipher reads straight
out of the key string, the documented alternative to PRAGMA cipher_salt. */
#define RAW_KEY_SALT_LEN (3 + 2 * 48)
static void read_key(struct input *in, struct key *key) {
unsigned form = u8(in);
memset(key, 0, sizeof *key);
if (form & 1) {
unsigned char raw[48];
int len = form & 2 ? 48 : 32;
for (int i = 0; i < len; i++) raw[i] = (unsigned char)u8(in);
key->bytes[0] = 'x';
key->bytes[1] = '\'';
fuzz_hex((char *)key->bytes + 2, raw, len);
key->bytes[2 + 2 * len] = '\'';
key->len = 3 + 2 * len;
key->migrate = (form & 4) != 0;
} else {
struct input pass = take(in, 64);
memcpy(key->bytes, pass.data, pass.size);
key->len = (int)pass.size;
key->passphrase = key->len > 0;
}
key->kdf_iter = (int)(u8(in) % 4) + 1;
}
static int apply_key(sqlite3 *handle, const char *schema, const struct key *key, int rekey, struct dump *out) {
char sql[96];
if (rekey) {
if (!lib->rekey_v2) return SQLITE_OK; /* A provider with no codec (plain SQLite) has nothing to (re)key. */
if (major < 5) {
snprintf(sql, sizeof sql, "PRAGMA \"%s\".rekey_kdf_iter = %d", schema, key->kdf_iter);
run_trusted(handle, sql, out);
}
int rc = lib->rekey_v2(handle, schema, key->bytes, key->len);
dump_code(out, rc);
return rc;
}
if (!lib->key_v2 || key->len == 0) return SQLITE_OK; /* No key means no encryption, the same as never calling
key_v2 at all; calling it anyway with a zero-length key
does not reproduce that, so a later replay reapplying
a recorded empty-key step must skip it the same way. */
int rc = lib->key_v2(handle, schema, key->bytes, key->len);
dump_code(out, rc);
snprintf(sql, sizeof sql, "PRAGMA \"%s\".kdf_iter = %d", schema, key->kdf_iter);
run_trusted(handle, sql, out);
return rc;
}
static unsigned page_size(struct input *in) {
unsigned pick = u8(in);
return known_page_size(major, pick % 16 < 8 ? 512u << (pick % 8) : u16(in));
}
static const char *pick(struct input *in, const char *const *choices, size_t count) {
return choices[u8(in) % count];
}
#define PICK(in, choices) pick(in, choices, sizeof choices / sizeof *choices)
enum setting {
SET_PAGE_SIZE,
SET_USE_HMAC,
SET_HMAC_ALGORITHM,
SET_KDF_ALGORITHM,
SET_HEADER_SIZE,
SET_SALT,
SET_COMPATIBILITY,
SET_KDF_ITER,
SET_HMAC_PGNO,
SET_FAST_KDF_ITER,
SET_CIPHER,
SET_AEAD,
SET_HMAC_FAST_KDF,
SET_ADD_RANDOM,
};
/* 5.x removes the deprecated pragmas and adds the AEAD switches. */
static const enum setting settings_4[] = {
SET_PAGE_SIZE, SET_USE_HMAC, SET_HMAC_ALGORITHM, SET_KDF_ALGORITHM, SET_HEADER_SIZE, SET_SALT,
SET_COMPATIBILITY, SET_KDF_ITER, SET_HMAC_PGNO, SET_FAST_KDF_ITER, SET_CIPHER, SET_ADD_RANDOM,
};
static const enum setting settings_5[] = {
SET_PAGE_SIZE, SET_USE_HMAC, SET_HMAC_ALGORITHM, SET_KDF_ALGORITHM, SET_HEADER_SIZE, SET_SALT,
SET_COMPATIBILITY, SET_KDF_ITER, SET_AEAD, SET_HMAC_FAST_KDF, SET_ADD_RANDOM,
};
/* One codec pragma on schema, followed by a cheap kdf_iter wherever the pragma would restore an expensive one. */
static enum setting format_setting(struct input *in, const char *schema, char *sql, size_t cap) {
static const char *const on_off[] = {"ON", "OFF"};
static const char *const hmacs[] = {"HMAC_SHA1", "HMAC_SHA256", "HMAC_SHA512", "HMAC_MD5"};
static const char *const kdfs[] = {"PBKDF2_HMAC_SHA1", "PBKDF2_HMAC_SHA256", "PBKDF2_HMAC_SHA512", "SCRYPT"};
static const char *const pgnos[] = {"le", "be", "native", "middle"};
static const char *const ciphers[] = {"aes-256-cbc", "aes-128-cbc", "chacha20"};
static const unsigned headers[] = {0, 16, 24, 32, 48, 4096};
unsigned char salt[16];
char salt_hex[33];
unsigned char random_data[24];
char random_hex[49];
unsigned choice = u8(in);
enum setting setting = major < 5 ? settings_4[choice % (sizeof settings_4 / sizeof *settings_4)]
: settings_5[choice % (sizeof settings_5 / sizeof *settings_5)];
switch (setting) {
case SET_PAGE_SIZE:
snprintf(sql, cap, "PRAGMA \"%s\".cipher_page_size = %u", schema, page_size(in));
break;
case SET_USE_HMAC:
snprintf(sql, cap, "PRAGMA \"%s\".cipher_use_hmac = %s", schema, PICK(in, on_off));
break;
case SET_HMAC_ALGORITHM:
snprintf(sql, cap, "PRAGMA \"%s\".cipher_hmac_algorithm = %s", schema, PICK(in, hmacs));
break;
case SET_KDF_ALGORITHM:
snprintf(sql, cap, "PRAGMA \"%s\".cipher_kdf_algorithm = %s", schema, PICK(in, kdfs));
break;
case SET_HEADER_SIZE: {
unsigned index = u8(in);
unsigned size = index % 8 < 6 ? headers[index % 8] : u8(in);
snprintf(sql, cap, "PRAGMA \"%s\".cipher_plaintext_header_size = %u", schema, known_header_size(size));
break;
}
case SET_SALT:
for (int i = 0; i < 16; i++) salt[i] = (unsigned char)u8(in);
fuzz_hex(salt_hex, salt, 16);
snprintf(sql, cap, "PRAGMA \"%s\".cipher_salt = \"x'%s'\"", schema, salt_hex);
break;
case SET_COMPATIBILITY:
snprintf(sql, cap, "PRAGMA \"%s\".cipher_compatibility = %u; PRAGMA \"%s\".kdf_iter = 2", schema, u8(in) % 6,
schema);
break;
case SET_KDF_ITER:
snprintf(sql, cap, "PRAGMA \"%s\".kdf_iter = %u", schema, u8(in) % 4 + 1);
break;
case SET_HMAC_PGNO:
snprintf(sql, cap, "PRAGMA \"%s\".cipher_hmac_pgno = %s", schema, PICK(in, pgnos));
break;
case SET_FAST_KDF_ITER:
snprintf(sql, cap, "PRAGMA \"%s\".fast_kdf_iter = %u", schema, u8(in) % 4 + 1);
break;
case SET_CIPHER:
snprintf(sql, cap, "PRAGMA \"%s\".cipher = '%s'", schema, PICK(in, ciphers));
break;
case SET_AEAD:
snprintf(sql, cap, "PRAGMA \"%s\".cipher_aead = %s", schema, PICK(in, on_off));
break;
case SET_HMAC_FAST_KDF: {
const char *value = PICK(in, on_off);
/* L3: cipher_use_hmac redoes the reserve setup that cipher_hmac_fast_kdf skips. */
snprintf(sql, cap, "PRAGMA \"%s\".cipher_hmac_fast_kdf = %s%s%s%s", schema, value,
value == on_off[0] ? "; PRAGMA \"" : "", value == on_off[0] ? schema : "",
value == on_off[0] ? "\".cipher_use_hmac = ON" : "");
break;
}
case SET_ADD_RANDOM: {
/* sqlcipher_codec_add_random requires exactly x'<even-length-hex>', with no surrounding text: a bare pragma
value in this exact shape is unlikely to ever come from mutating raw SQL text, unlike every other codec
setting above, whose SQL keeps working regardless of the specific number or string it mutates in. */
unsigned len = u8(in) % (sizeof random_data + 1);
for (unsigned i = 0; i < len; i++) random_data[i] = (unsigned char)u8(in);
fuzz_hex(random_hex, random_data, len);
snprintf(sql, cap, "PRAGMA \"%s\".cipher_add_random = \"x'%s'\"", schema, random_hex);
break;
}
}
return setting;
}
static enum setting apply_setting(sqlite3 *handle, const char *schema, struct input *in, struct dump *out) {
char sql[160];
enum setting setting = format_setting(in, schema, sql, sizeof sql);
run_trusted(handle, sql, out);
return setting;
}
static void record(int file, enum step_kind kind, const uint8_t *start, const uint8_t *end) {
struct recipe *recipe = &recipes[file];
if (recipe->count == MAX_RECIPE) return;
recipe->steps[recipe->count].kind = kind;
recipe->steps[recipe->count].slice.data = start;
recipe->steps[recipe->count].slice.size = (size_t)(end - start);
recipe->count++;
}
/* Whether file's recipe already has a key or rekey step recorded, a setting alone does not count: used to tell
a rekey that is genuinely the first ever key-related operation for this file (rekey_v2 encrypting a fresh,
unkeyed connection in place, which replay must reconstruct via key_v2, not rekey_v2) from one that follows an
earlier key or rekey. */
static int has_key_step(int file) {
const struct recipe *recipe = &recipes[file];
for (int i = 0; i < recipe->count; i++) {
if (recipe->steps[i].kind == STEP_KEY || recipe->steps[i].kind == STEP_REKEY) return 1;
}
return 0;
}
/* Returns nonzero when either the file's plaintext header disagrees with what was replayed (L8) or a key step
itself failed to reapply: replay never replays the content writes between two key events, only the key and
setting pragmas, so a passphrase key's KDF iteration count can still legitimately be pending, not yet locked
in by an actual page read, at a point a script's own writes had already locked it in; a rekey step replayed
with no such write in between can fail to derive the same old key the original run's writes had already fixed.
Either way, nothing downstream should trust what handle now holds. */
static int replay(sqlite3 *handle, int file, struct dump *out) {
const struct recipe *recipe = &recipes[file];
int failed = 0;
for (int i = 0; i < recipe->count; i++) {
struct input slice = recipe->steps[i].slice;
if (recipe->steps[i].kind == STEP_KEY || recipe->steps[i].kind == STEP_REKEY) {
struct key key;
read_key(&slice, &key);
if (apply_key(handle, "main", &key, recipe->steps[i].kind == STEP_REKEY, out) != SQLITE_OK) failed = 1;
} else {
apply_setting(handle, "main", &slice, out);
}
}
return failed || header_mismatch(handle, file);
}
/* Table names in handle's schema, dumping each schema row into out as it scans, collected up to max into names.
*rc is the schema-listing query's own final result code. */
static int list_tables(sqlite3 *handle, struct dump *out, char names[][128], int max, int *rc) {
int count = 0;
sqlite3_stmt *stmt = NULL;
*rc = lib->prepare_v2(handle, "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name", -1, &stmt,
NULL);
if (*rc == SQLITE_OK) {
while ((*rc = lib->step(stmt)) == SQLITE_ROW) {
dump_row(stmt, out);
const unsigned char *name = lib->column_blob(stmt, 0);
int len = lib->column_bytes(stmt, 0);
if (count < max && name && len < 128) {
memcpy(names[count], name, (size_t)len);
names[count++][len] = 0;
}
}
lib->finalize(stmt);
}
return count;
}
/* Reads every row of each named table, escaping an embedded quote so a crafted table name can never break out of
the SELECT. */
static void read_tables(sqlite3 *handle, struct dump *out, char names[][128], int count) {
for (int i = 0; i < count; i++) {
char sql[300] = "SELECT * FROM \"";
size_t at = strlen(sql);
for (const char *c = names[i]; *c; c++) {
if (*c == '"') sql[at++] = '"';
sql[at++] = *c;
}
sql[at++] = '"';
sql[at] = 0;
run(handle, sql, out);
}
}
static void read_all(sqlite3 *handle, struct dump *out) {
char names[MAX_DUMP_TABLES][128];
int rc;
int count = list_tables(handle, out, names, MAX_DUMP_TABLES, &rc);
dump_code(out, rc);
read_tables(handle, out, names, count);
run_trusted(handle, "PRAGMA cipher_integrity_check; PRAGMA integrity_check", out);
}
static void op_statement(struct input *in) {
static const char *const statements[] = {
"CREATE TABLE IF NOT EXISTS t(a INTEGER PRIMARY KEY, b BLOB, c TEXT)",
"INSERT INTO t(b, c) VALUES (randomblob(?1), ?3)",
"INSERT INTO t(b, c) SELECT zeroblob(?2), c FROM t LIMIT 16",
"UPDATE t SET b = randomblob(?1) WHERE a % 3 = ?2 % 3",
"DELETE FROM t WHERE a % (?2 % 4 + 1) = 0",
"CREATE INDEX IF NOT EXISTS t_c ON t(c)",
"CREATE TABLE IF NOT EXISTS w(k TEXT PRIMARY KEY, v BLOB) WITHOUT ROWID",
"INSERT OR REPLACE INTO w VALUES (hex(randomblob(?2 % 32 + 1)), randomblob(?1))",
"DROP TABLE IF EXISTS w",
"VACUUM",
"BEGIN",
"COMMIT",
"ROLLBACK",
"SAVEPOINT s",
"ROLLBACK TO s",
"RELEASE s",
"PRAGMA incremental_vacuum(4)",
"PRAGMA wal_checkpoint(TRUNCATE)",
"PRAGMA integrity_check",
"PRAGMA cipher_integrity_check",
"SELECT count(*), sum(length(b)) FROM t",
"CREATE TEMP TABLE IF NOT EXISTS tt AS SELECT * FROM t",
"PRAGMA cipher_migrate",
};
size_t index = u8(in) % (sizeof statements / sizeof *statements);
unsigned blob = u16(in) % (MAX_BLOB + 1);
unsigned small = u8(in);
struct input text = take(in, 256);
if (!db) return;
int already_touched = touched;
touched = 1;
int is_migrate = strcmp(statements[index], "PRAGMA cipher_migrate") == 0;
/* Migration retries the passphrase at the legacy kdf_iter counts, far beyond a fuzz iteration's time. */
if (is_migrate && recipes[db_file].passphrase) return;
if (vacuum_blocked(db, known_vacuum(statements[index], strlen(statements[index])))) return;
sqlite3_stmt *stmt = NULL;
if (lib->prepare_v2(db, statements[index], -1, &stmt, NULL) != SQLITE_OK) return;
lib->bind_int64(stmt, 1, blob);
lib->bind_int64(stmt, 2, small);
lib->bind_text(stmt, 3, (const char *)text.data, (int)text.size, SQLITE_TRANSIENT);
trusted = 1;
int migrate_check = is_migrate && !known_migrate_poisons(already_touched);
if (migrate_check) model_snapshot(lib, db, "main", db_file);
int rc = drain(stmt, NULL);
trusted = 0;
if (migrate_check) {
if (rc == SQLITE_OK) model_check(lib, db, "main", db_file, files[db_file], "cipher_migrate");
else model_discard();
}
}
static void op_pragma(struct input *in) {
static const char *const pragmas[] = {"auto_vacuum", "journal_mode", "locking_mode", "cache_size",
"secure_delete", "temp_store", "synchronous", "page_size"};
static const char *const values[][6] = {
{"NONE", "FULL", "INCREMENTAL"},
{"DELETE", "TRUNCATE", "PERSIST", "MEMORY", "OFF", "WAL"},
{"NORMAL", "EXCLUSIVE"},
{"1", "2", "10", "-2000"},
{"ON", "OFF", "FAST"},
{"DEFAULT", "FILE", "MEMORY"},
{"OFF", "NORMAL", "FULL"},
};
static const size_t counts[] = {3, 6, 2, 4, 3, 3, 3};
size_t index = u8(in) % (sizeof pragmas / sizeof *pragmas);
char sql[96];
if (index == 7) {
snprintf(sql, sizeof sql, "PRAGMA page_size = %u", page_size(in));
} else {
snprintf(sql, sizeof sql, "PRAGMA %s = %s", pragmas[index], values[index][u8(in) % counts[index]]);
}
/* L6: SQLCipher answers page_size as cipher_page_size, which after first access is the same misuse as a late key. */
if (!db || (index == 7 && touched)) return;
touched = 1;
run_trusted(db, sql, NULL);
if (header_mismatch(db, db_file)) close_db(); /* L8 */
}
/* Whether file has a hot journal or WAL memvfs sibling with bytes in it: SQLite's own lazy recovery rolls either
back into the main file on the very next real page access, rewriting it to the pre-crash state the journal or
WAL already holds, independent of whatever key that access happens to be trying. A key-verification read is
exactly such an access, so the wrong-key oracle has to skip a file recovery could legitimately touch, or every
hot journal or WAL an earlier, unrelated op left behind reads as this key having corrupted the file. */
static int has_pending_recovery(int file) {
char name[64];
size_t len = 0;
snprintf(name, sizeof name, "%s-journal", files[file]);
memvfs_peek(name, &len);
if (len) return 1;
snprintf(name, sizeof name, "%s-wal", files[file]);
memvfs_peek(name, &len);
return len != 0;
}
/* Checks handle's just-applied key on schema: before the read, so tamper_check_wrong_key can tell a wrong key
from a since-healed region by comparing against file's bytes beforehand, and skips that check when file has a
pending journal/WAL recovery the read could trip over instead of the key itself. Marks file confidentiality-
keyed when the key actually applied and verified, the same rule at every call site. */
static void verify_key(sqlite3 *handle, const char *schema, int file, int key_len) {
unsigned long long before_hash = tamper_hash_file(files[file]);
int recovery_pending = has_pending_recovery(file);
int vrc = key_verified(handle, schema);
if (!recovery_pending) tamper_check_wrong_key(vrc, before_hash, files[file]);
if (key_len > 0 && verified(vrc)) confidentiality_mark_keyed(file);
}
static void op_key(struct input *in, int rekey) {
const uint8_t *start = in->data;
struct key key;
read_key(in, &key);
/* L6: a key applied after the connection touched the file is position D and corrupts memory. A provider with
no codec at all (plain SQLite, differential_plain's comparison side) has nothing to key, record or mark:
every oracle below exists to check codec behaviour that provider simply does not have. */
if (!db || (touched && !rekey) || !lib->key_v2) return;
if (rekey) model_snapshot(lib, db, "main", db_file);
int rc = apply_key(db, "main", &key, rekey, NULL);
if (rekey) {
if (rc == SQLITE_OK) model_check(lib, db, "main", db_file, files[db_file], "rekey");
else model_discard();
}
/* replay only ever reapplies key and setting steps back to back, with no chance for whatever the original run
did between the key and this rekey, a read included, to affect whether this rekey itself succeeds or fails
the same way: a rekey that failed here because something earlier had already touched the file can still
succeed when replayed without that earlier touch, landing the replayed connection on a different key than
this run's own. Marked regardless of this rekey's own outcome, since the recorded step gets replayed either
way. */
if (rekey) model_note_damage(db_file);
/* cipher_migrate needs the connection's underived key material, which SQLCipher discards after the first real
page access derives the actual key, so it only ever succeeds right here, before anything else, the
key_verified read below included, touches the connection; touched is guaranteed false at this point, the
non-rekey early return above already skips this whole function otherwise. Whether op_statement's own
"PRAGMA cipher_migrate" entry, picked among ~23 other choices with no ordering guarantee relative to the key,
poisons the connection depends on that same timing, not on whether this key is raw or a passphrase. */
if (!rekey && rc == SQLITE_OK && !key.passphrase && key.migrate) {
int migrate_check = !known_migrate_poisons(touched);
if (migrate_check) model_snapshot(lib, db, "main", db_file);
int migrate_rc = run_trusted(db, "PRAGMA main.cipher_migrate", NULL);
if (migrate_check) {
if (migrate_rc == SQLITE_OK) model_check(lib, db, "main", db_file, files[db_file], "cipher_migrate");
else model_discard();
}
touched = 1;
}
/* A failed rekey (SQLITE_MISUSE on a database no key ever reached) leaves the file exactly as it was: nothing to
expect encryption of. rekey_v2 retroactively re-encrypts every existing page as part of the same call, so its
own SQLITE_OK is enough on its own; key_v2 does not, so a read has to confirm this key actually matches
whatever the file already had before trusting it, fresh empty file included. rekey_v2 itself never gets this
far wrong the way a wrong-key oracle checks: a mismatched old key fails apply_key outright (SQLITE_MISUSE
above), not silently. A successful rekey to an empty key removes the codec and writes the file back out in
plaintext just as definitively as a non-empty key encrypts it, so it has to clear expect_encrypted the same
way opening or attaching the file already does, not leave the prior key's mark standing over content the
empty rekey just decrypted itself. read_key's 48-byte raw form (key.len == RAW_KEY_SALT_LEN) embeds an
explicit salt in its own trailing hex digits, the documented alternative to PRAGMA cipher_salt: it is exempt
from the salt check the same way. */
if (!rekey && rc == SQLITE_OK) {
verify_key(db, "main", db_file, key.len);
touched = 1; /* key_verified's own read, success or failure, already derived the key against a real page. */
} else if (rc == SQLITE_OK && key.len > 0) {
confidentiality_mark_keyed(db_file);
} else if (rekey && rc == SQLITE_OK && key.len == 0) {
confidentiality_forget_file(db_file);
}
if (rc == SQLITE_OK && key.len == RAW_KEY_SALT_LEN) uniqueness_note_explicit_salt(db_file);
/* Any rekey at all, not just the very first key-related step for this file, risks the same class of gap: its
own retroactive re-encryption of whatever the connection already had, successful or not, does not reliably
reconstruct the same way through replay on a later reopen, which can desync db_file itself between this run
and a provider with no codec (where the same bytes always succeed trivially), cascading into any later op
that touches another file through this same connection. A first-ever plain key carries the narrower version
of the same risk, meeting content an earlier unkeyed session already wrote. Marks every file export_touched-
style exempt from differential_plain's own comparison for the rest of the run, not just this one, rather
than trying to track the exact cascade. */
if (rekey || !has_key_step(db_file)) {
for (int i = 0; i < SCRIPT_FILES; i++) export_touched[i] = 1;
}
record(db_file, rekey ? STEP_REKEY : STEP_KEY, start, in->data);
}
static void op_setting(struct input *in) {
const uint8_t *start = in->data;
char sql[160];
enum setting setting = format_setting(in, "main", sql, sizeof sql);
if (!db || touched) return; /* L6 */
run_trusted(db, sql, NULL);
if (setting == SET_SALT) uniqueness_note_explicit_salt(db_file);
record(db_file, STEP_SETTING, start, in->data);
if (header_mismatch(db, db_file)) close_db(); /* L8 */
}
static void op_attach(struct input *in) {
static const char *const moves[] = {
"SELECT sqlcipher_export('aux')",
"SELECT sqlcipher_export('main', 'aux')",
"SELECT count(*) FROM aux.sqlite_schema",
};
unsigned target = u8(in);
const uint8_t *start = in->data;
struct key key;
read_key(in, &key);
const uint8_t *key_end = in->data;
unsigned settings = u8(in) % 3;
if (!db) return;
touched = 1;
/* ATTACH's own KEY clause, kdf_iter pragma and sqlcipher_export moves are all cipher-specific, with enough
surface (the attached schema's own key semantics, move_idx 0/1's retroactive content copy) that distinguishing
exactly which part of this op risks a replay-fidelity gap keeps finding new variants. Marks every file
export_touched-style exempt from differential_plain's own comparison for the rest of the run whenever this
op runs at all, the same broad safety net op_key's own rekey path uses. */
for (int i = 0; i < SCRIPT_FILES; i++) export_touched[i] = 1;
int file = (db_file + 1 + (int)(target % 2)) % SCRIPT_FILES;
/* Each ATTACH targeting file is its own, independent keying event, so a prior attach's expectation for it,
possibly with a completely different key, must not carry over. */
confidentiality_forget_file(file);
if (known_header_page_mismatch(major, memvfs_header_page_size(files[file]), default_page)) return; /* L8 */
recipes[file].count = 0;
recipes[file].passphrase = key.passphrase;
record(file, STEP_KEY, start, key_end);
sqlite3_stmt *stmt = NULL;
/* A provider with no codec at all (plain SQLite) does not recognize the KEY clause SQLCipher adds to ATTACH's
own grammar at all, so the same file this op reaches on the cipher side would otherwise never even get
created on that side; falls back to a plain ATTACH instead, so the attached file's own content still exists
to compare, skipping only the key-verification and oracle-marking block below that makes no sense without a
codec. */
int keyless = !lib->key_v2;
if (keyless) {
if (lib->prepare_v2(db, "ATTACH ?1 AS aux", -1, &stmt, NULL) != SQLITE_OK) return;
lib->bind_text(stmt, 1, files[file], -1, SQLITE_STATIC);
} else {
if (lib->prepare_v2(db, "ATTACH ?1 AS aux KEY ?2", -1, &stmt, NULL) != SQLITE_OK) return;
lib->bind_text(stmt, 1, files[file], -1, SQLITE_STATIC);
lib->bind_blob(stmt, 2, key.bytes, key.len, SQLITE_TRANSIENT);
}
trusted = 1;
int rc = drain(stmt, NULL);
trusted = 0;
if (rc != SQLITE_OK) return;
if (!keyless) {
/* Same reasoning as op_key: attaching with a key never retroactively encrypts content the file already had,
so a read has to confirm this key actually matches it first. */
verify_key(db, "aux", file, key.len);
if (key.len == RAW_KEY_SALT_LEN) uniqueness_note_explicit_salt(file);
char sql[96];
snprintf(sql, sizeof sql, "PRAGMA aux.kdf_iter = %d", key.kdf_iter);
run_trusted(db, sql, NULL);
}
for (unsigned i = 0; i < settings; i++) {
const uint8_t *setting = in->data;
enum setting chosen = apply_setting(db, "aux", in, NULL);
if (chosen == SET_SALT) uniqueness_note_explicit_salt(file);
record(file, STEP_SETTING, setting, in->data);
}
unsigned move_idx = u8(in) % (sizeof moves / sizeof *moves);
int move_rc;
if (move_idx == 0) {
/* sqlcipher_export('aux'): copies db_file's own "main" content into file's "aux", content replay() has no
record of when it later reconstructs file from file's own recipe alone. */
model_snapshot(lib, db, "main", db_file);
move_rc = run_trusted(db, moves[0], NULL);
if (move_rc == SQLITE_OK) {
model_check_contains(lib, db, "aux", file, files[file], "sqlcipher_export");
model_note_damage(file);
export_touched[db_file] = export_touched[file] = 1;
} else {
model_discard();
}
} else if (move_idx == 1) {
/* sqlcipher_export('main', 'aux'): copies file's own "aux" content into db_file's "main", content replay()
has no record of when it later reconstructs db_file from db_file's own recipe alone. */
model_snapshot(lib, db, "aux", file);
move_rc = run_trusted(db, moves[1], NULL);
if (move_rc == SQLITE_OK) {
model_check_contains(lib, db, "main", db_file, files[db_file], "sqlcipher_export");
model_note_damage(db_file);
export_touched[db_file] = export_touched[file] = 1;
} else {
model_discard();
}
} else {
/* A read-only move: nothing between here and DETACH should change what ATTACH itself already made visible. */
model_snapshot(lib, db, "aux", file);
move_rc = run_trusted(db, moves[2], NULL);
if (move_rc == SQLITE_OK) model_check(lib, db, "aux", file, files[file], "attach");
else model_discard();
}
uniqueness_check(lib, db, "aux", file, files[file]);
run_trusted(db, "DETACH aux", NULL);
}
static void op_backup(struct input *in) {
unsigned target = u8(in);
const uint8_t *start = in->data;
struct key key;
read_key(in, &key);
if (!db) return;
touched = 1;
int file = (db_file + 1 + (int)(target % 2)) % SCRIPT_FILES;
sqlite3 *dest = open_file(file, 1);
if (!dest) return;
/* Marked export_touched-style exempt from differential_plain's own comparison unconditionally, before any of
the rest of this op runs: sqlite3_backup_init's own guard rejects a plaintext source paired with an
encrypted destination, which can make the backup attempt itself succeed on a provider with no codec at all
(neither connection is ever "encrypted" there, so no such mismatch exists) while failing outright on a
codec connection, an asymmetry in whether anything gets copied at all, not just in what replay reconstructs
afterward. */
export_touched[db_file] = export_touched[file] = 1;
/* Each backup targeting file is its own, independent keying event, so an earlier one's expectation for it,
possibly with a completely different key, must not carry over. */
confidentiality_forget_file(file);
recipes[file].count = 0;
recipes[file].passphrase = key.passphrase;
int rc = apply_key(dest, "main", &key, 0, NULL);
/* Same reasoning as op_key: key_v2 on dest never retroactively encrypts content dest already had, so a read has
to confirm this key actually matches it first. A provider with no codec at all has nothing to verify or
mark keyed here either, the same as op_key's and op_attach's own keyless paths. */
if (lib->key_v2 && rc == SQLITE_OK) {
verify_key(dest, "main", file, key.len);
}
if (rc == SQLITE_OK && key.len == RAW_KEY_SALT_LEN) uniqueness_note_explicit_salt(file);
record(file, STEP_KEY, start, in->data);
if (known_backup_blocked(major, fuzz_codec_page_size(lib, db), fuzz_codec_page_size(lib, dest))) {
uniqueness_check(lib, dest, "main", file, files[file]);
lib->close_v2(dest);
return;
}
sqlite3_backup *backup = lib->backup_init(dest, "main", db, "main");
if (backup) {
model_snapshot(lib, db, "main", db_file);
int step_rc = lib->backup_step(backup, -1);
lib->backup_finish(backup);
if (step_rc == SQLITE_DONE) model_check(lib, dest, "main", file, files[file], "backup");
else model_discard();
/* backup_step's own page-level reads against db's pager leave a later reopen on db_file free to show less
than this same connection's own cache did, at least under system_heap's allocator_may_return_null=1; not
nailed down further, so db_file is exempt from this module's own later checks for the rest of the run. */
model_note_damage(db_file);
}
uniqueness_check(lib, dest, "main", file, files[file]);
lib->close_v2(dest);
}
static void op_canary(struct input *in) {
(void)in;
if (!db) return;
touched = 1;
confidentiality_plant(lib, db);
}
/* Arms one fault (a short read, a short write, running out of space on write, a failed fsync, or a failed
allocation), then writes inside an explicit transaction and commits, testing the property the plan states for
this oracle directly: reopening afterward shows exactly the pre-transaction state, when the fault made the
transaction fail, or exactly the post-transaction state, when it committed despite the fault, never a partial
page. Reopens right here, the same way OP_REOPEN does, rather than leaving that to whichever later op happens
to reopen this file, so every fault this op ever arms gets its own outcome checked. */
static void op_fault_txn(struct input *in) {
static const enum fault_kind kinds[] = {FAULT_SHORT_READ, FAULT_SHORT_WRITE, FAULT_ENOSPC, FAULT_FSYNC,
FAULT_ALLOC};
/* L12: skip when an attached schema's cipher_page_size differs from main's, since this op's own COMMIT
then reads past a main page-cache buffer sized for the wrong page. */
if (!db) return;
if (!lib->get_autocommit(db)) return;
int main_page_size = lib_int(lib, db, "PRAGMA main.cipher_page_size");
int aux_page_size = lib_int(lib, db, "PRAGMA aux.cipher_page_size");
if (aux_page_size > 0 && aux_page_size != main_page_size) return;
fault_touched[db_file] = 1;
touched = 1;
enum fault_kind kind = kinds[u8(in) % (sizeof kinds / sizeof *kinds)];
unsigned countdown = u8(in);
unsigned blob = u16(in) % (MAX_BLOB + 1);
fault_arm(kind, countdown);
int rc = run_trusted(db, "BEGIN IMMEDIATE", NULL);
if (rc == SQLITE_OK) rc = run_trusted(db, "CREATE TABLE IF NOT EXISTS t(a INTEGER PRIMARY KEY, b BLOB, c TEXT)", NULL);
if (rc == SQLITE_OK) {
sqlite3_stmt *stmt = NULL;
if (lib->prepare_v2(db, "INSERT INTO t(b, c) VALUES (randomblob(?1), ?3)", -1, &stmt, NULL) == SQLITE_OK) {
lib->bind_int64(stmt, 1, blob);
lib->bind_text(stmt, 3, "fault", -1, SQLITE_STATIC);
trusted = 1;
rc = drain(stmt, NULL);
trusted = 0;
} else {
rc = SQLITE_ERROR;
}
}
int commit_rc = run_trusted(db, "COMMIT", NULL);
fault_disarm();
int committed = rc == SQLITE_OK && commit_rc == SQLITE_OK;
const char *op_name;
if (committed) {
op_name = "fault-commit";
} else {
run_trusted(db, "ROLLBACK", NULL); /* Harmless if BEGIN itself never opened one. */
op_name = "fault-rollback";
}
int can_check = lib->get_autocommit(db);
if (can_check) model_snapshot(lib, db, "main", db_file);
int file = db_file;
close_db();
db = open_file(file, 0);
if (!db) {
if (can_check) model_discard();
return;
}
db_file = file;
if (replay(db, file, NULL)) { /* L8 */
close_db();
if (can_check) model_discard();
return;
}
if (can_check) model_check(lib, db, "main", file, files[file], op_name);
}
/* The script file index memvfs slot index names, or -1 for a file the script did not create (a temp or super-journal). */
static int file_of_memvfs(int index) {
const char *name = memvfs_name(index);
for (int i = 0; i < SCRIPT_FILES; i++) {
if (strcmp(files[i], name) == 0) return i;
}
return -1;
}
static void op_damage(struct input *in) {
unsigned target = u8(in);
unsigned kind = u8(in) % 3;
unsigned long offset = u32(in);
unsigned mask = u8(in) | 1;
struct input chunk = kind == 2 ? take(in, 4096) : (struct input){NULL, 0};
int count = memvfs_count();
if (!count) return;
int index = (int)(target % (unsigned)count);
long long size = memvfs_size(index);
long long at = kind == 0 && size ? (long long)(offset % (unsigned long long)size)
: (long long)(offset % (unsigned long long)(size + 1));
long long len = kind == 0 ? 1 : kind == 2 ? (long long)chunk.size : 0;
if (known_header_edit(major, memvfs_starts_with(index, "SQLite format 3", 16), at, len)) return;
if (kind == 0) {
if (size) {
memvfs_flip(index, at, (unsigned char)mask);
tamper_flip(file_of_memvfs(index), memvfs_name(index), at, (unsigned char)mask);