Repository navigation
Expand file tree
/
Copy pathsqlite_salvager.py
More file actions
2480 lines (2175 loc) · 97.1 KB
/
Copy pathsqlite_salvager.py
File metadata and controls
2480 lines (2175 loc) · 97.1 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
#!/usr/bin/env python3
"""
sqlite-salvager: Production-Grade Forensic SQLite 3 Binary Carver & Recovery Engine
===================================================================================
A zero-dependency, low-level binary stream parser and digital forensics (DFIR) recovery tool
for heavily corrupted, truncated, header-wiped, or locked SQLite 3 databases, including
unallocated freelist blocks, freeblocks, slack space, and Write-Ahead Log (-wal) journals.
Follows the official SQLite Database File Format Specification:
https://www.sqlite.org/fileformat2.html
Features:
- Pure binary parsing using `mmap` and `struct` (never uses `sqlite3` to read the source file).
- 100-byte Database Header analyzer + Resilient Page Size Brute-Force Prober (512..65536 bytes).
- Full 64-bit SQLite Varint decoder (1-9 bytes, two's complement signed 64-bit support).
- B-Tree Table Interior (0x05), Table Leaf (0x0D), Index Interior (0x02), and Index Leaf (0x0A) parsers.
- Overflow Page Chain follower with cycle detection and strict boundary enforcement.
- Record Format decoder supporting all serial types: NULL, 8/16/24/32/48/64-bit signed integers,
IEEE 754 64-bit floats, 0/1 constants, BLOBs, and UTF-8 / UTF-16LE / UTF-16BE strings.
- Deleted & Unallocated Data Carving:
* Freelist Trunk & Leaf Page traversal.
* In-page Freeblock linked-list traversal.
* Unallocated gap / slack space scanning (between cell pointer array and cell content start).
* Heuristic Record-Signature Carver with configurable sensitivity for raw unallocated bytes.
- Write-Ahead Log (-wal) parser:
* Supports magic numbers 0x377f0682 (little-endian checksums) and 0x377f0683 (big-endian checksums).
* Verifies frame salts & cumulative checksums, or bypasses corrupt checksums in forensic mode.
- Schema Auto-Reconstruction:
* Parses `sqlite_schema` / `sqlite_master` from Root Page 1 (or carved schema rows) to map
root pages to table names and column definitions.
* Dynamically groups orphan/headerless records by their serial-type signature into synthetic
tables (e.g., `recovered_table_sig_INT_TEXT_BLOB`).
- Multi-Format Export & Audit Report:
* `.sql` dump (`CREATE TABLE` + `INSERT INTO` with hex-escaped blobs and status comments).
* `.csv` & `.jsonl` streaming exports per table (with forensic metadata fields).
* Rebuilt clean `.sqlite` database output.
* Detailed Markdown & Terminal Forensic Audit Report (`forensic_audit_report.md`).
- Built-in Synthetic Corrupt Database Test Suite (`--self-test`).
Author: Principal Systems & DFIR Engineering
License: MIT
"""
from __future__ import annotations
import argparse
import csv
import dataclasses
import datetime
import hashlib
import io
import json
import logging
import math
import mmap
import os
import re
import shutil
import sqlite3
import struct
import sys
import tempfile
import unittest
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union
# =============================================================================
# 1. CONSTANTS & DATA STRUCTURES
# =============================================================================
SQLITE3_MAGIC = b"SQLite format 3\x00"
STANDARD_PAGE_SIZES = (4096, 1024, 2048, 8192, 16384, 32768, 65536, 512)
# B-Tree Page Type Flags
PAGE_TYPE_INTERIOR_INDEX = 0x02
PAGE_TYPE_INTERIOR_TABLE = 0x05
PAGE_TYPE_LEAF_INDEX = 0x0A
PAGE_TYPE_LEAF_TABLE = 0x0D
VALID_PAGE_TYPES = {
PAGE_TYPE_INTERIOR_INDEX,
PAGE_TYPE_INTERIOR_TABLE,
PAGE_TYPE_LEAF_INDEX,
PAGE_TYPE_LEAF_TABLE,
}
# WAL Magic Numbers
WAL_MAGIC_LE = 0x377F0682
WAL_MAGIC_BE = 0x377F0683
WAL_HEADER_SIZE = 32
WAL_FRAME_HEADER_SIZE = 24
class RecordSourceType(str, Enum):
ACTIVE_LEAF = "ACTIVE_LEAF"
WAL_ACTIVE = "WAL_ACTIVE"
WAL_CARVED = "WAL_CARVED"
FREEBLOCK = "FREEBLOCK"
SLACK_GAP = "SLACK_GAP"
FREELIST_PAGE = "FREELIST_PAGE"
RAW_CARVED = "RAW_CARVED"
class TextEncoding(int, Enum):
UTF8 = 1
UTF16LE = 2
UTF16BE = 3
@property
def codec_name(self) -> str:
if self == TextEncoding.UTF16LE:
return "utf-16-le"
if self == TextEncoding.UTF16BE:
return "utf-16-be"
return "utf-8"
@dataclass
class DatabaseHeader:
magic_valid: bool
page_size: int
write_version: int
read_version: int
reserved_space: int
max_payload_frac: int
min_payload_frac: int
leaf_payload_frac: int
file_change_counter: int
database_size_pages: int
first_freelist_trunk_page: int
total_freelist_pages: int
schema_cookie: int
schema_format: int
default_cache_size: int
largest_root_btree_page: int
text_encoding: TextEncoding
user_version: int
incremental_vacuum_mode: int
application_id: int
version_valid_for: int
sqlite_version_number: int
probed_fallback: bool = False
probe_confidence: float = 1.0
@property
def usable_size(self) -> int:
return max(128, self.page_size - self.reserved_space)
@dataclass
class SalvagedRecord:
rowid: Optional[int]
values: List[Any]
serial_types: List[int]
source_type: RecordSourceType
page_number: int
byte_offset: int
wal_frame: Optional[int] = None
is_partial: bool = False
raw_signature: str = ""
assigned_table: Optional[str] = None
def __post_init__(self) -> None:
if not self.raw_signature:
self.raw_signature = compute_signature(self.serial_types)
@dataclass
class TableSchema:
name: str
root_page: int
sql: str
columns: List[str] = field(default_factory=list)
column_types: List[str] = field(default_factory=list)
is_synthetic: bool = False
@dataclass
class AnomalyLog:
byte_offset: int
page_number: int
category: str
description: str
hex_preview: str = ""
@dataclass
class ForensicAuditStats:
file_path: str
file_size_bytes: int
sha256_hash: str
header_info: Optional[DatabaseHeader] = None
total_pages_scanned: int = 0
valid_btree_pages: int = 0
corrupted_pages_skipped: int = 0
freelist_trunk_pages: int = 0
freelist_leaf_pages: int = 0
overflow_pages_stitched: int = 0
active_records_recovered: int = 0
deleted_records_recovered: int = 0
wal_frames_scanned: int = 0
wal_frames_valid: int = 0
wal_frames_corrupt_bypassed: int = 0
wal_records_recovered: int = 0
schemas_recovered: Dict[str, TableSchema] = field(default_factory=dict)
anomalies: List[AnomalyLog] = field(default_factory=list)
# =============================================================================
# 2. VARINT & SERIAL TYPE DECODERS
# =============================================================================
def decode_varint(buf: Union[bytes, memoryview], offset: int = 0, limit: Optional[int] = None) -> Tuple[int, int]:
"""
Decode a SQLite variable-length integer (1 to 9 bytes) from `buf` starting at `offset`.
Returns `(value, bytes_consumed)`.
Raises `ValueError` if buffer bounds are exceeded.
"""
end = len(buf) if limit is None else min(len(buf), limit)
if offset < 0 or offset >= end:
raise ValueError(f"Varint offset {offset} out of bounds (end={end})")
val = 0
max_bytes = min(9, end - offset)
for i in range(max_bytes):
b = buf[offset + i]
if i == 8:
# 9th byte uses all 8 bits
val = (val << 8) | b
# Interpret as 64-bit two's complement signed integer if highest bit set
if val & (1 << 63):
val -= (1 << 64)
return val, 9
else:
val = (val << 7) | (b & 0x7F)
if (b & 0x80) == 0:
return val, i + 1
raise ValueError(f"Truncated varint at offset {offset} (only {max_bytes} bytes available)")
def serial_type_content_size(serial_type: int) -> int:
"""
Return the payload byte length corresponding to a SQLite Record Serial Type code.
Specification: https://www.sqlite.org/fileformat2.html#record_format
"""
if serial_type < 0:
raise ValueError(f"Negative serial type: {serial_type}")
if serial_type == 0:
return 0 # NULL
if serial_type == 1:
return 1 # 8-bit twos-complement integer
if serial_type == 2:
return 2 # 16-bit big-endian integer
if serial_type == 3:
return 3 # 24-bit big-endian integer
if serial_type == 4:
return 4 # 32-bit big-endian integer
if serial_type == 5:
return 6 # 48-bit big-endian integer
if serial_type == 6:
return 8 # 64-bit big-endian integer
if serial_type == 7:
return 8 # IEEE 754-2008 64-bit floating point
if serial_type in (8, 9):
return 0 # Integer constant 0 (type 8) or 1 (type 9)
if serial_type in (10, 11):
raise ValueError(f"Reserved internal serial type {serial_type}")
if serial_type >= 12:
if serial_type % 2 == 0:
return (serial_type - 12) // 2 # BLOB
else:
return (serial_type - 13) // 2 # TEXT
return 0
def serial_type_category(serial_type: int) -> str:
"""Return high-level SQL affinity category for a serial type."""
if serial_type == 0:
return "NULL"
if serial_type in (1, 2, 3, 4, 5, 6, 8, 9):
return "INT"
if serial_type == 7:
return "REAL"
if serial_type >= 12:
return "BLOB" if (serial_type % 2 == 0) else "TEXT"
return "UNKNOWN"
def compute_signature(serial_types: Sequence[int]) -> str:
"""Create a normalized type signature for grouping records into synthetic tables."""
if not serial_types:
return "EMPTY"
cats = []
for st in serial_types:
cat = serial_type_category(st)
cats.append(cat)
return "_".join(cats)
def decode_signed_be(raw: Union[bytes, memoryview]) -> int:
"""Decode big-endian signed integer of arbitrary byte width (1, 2, 3, 4, 6, 8 bytes)."""
return int.from_bytes(raw, byteorder="big", signed=True)
def decode_serial_value(
serial_type: int,
raw_bytes: Union[bytes, memoryview],
encoding: TextEncoding = TextEncoding.UTF8,
) -> Any:
"""Decode a single field value from its raw byte slice and serial type code."""
if serial_type == 0:
return None
if serial_type in (1, 2, 3, 4, 5, 6):
if len(raw_bytes) == 0:
return None
return decode_signed_be(raw_bytes)
if serial_type == 7:
if len(raw_bytes) < 8:
# Padded fallback for partial records
padded = bytes(raw_bytes).ljust(8, b"\x00")
val = struct.unpack(">d", padded)[0]
else:
val = struct.unpack(">d", raw_bytes[:8])[0]
if math.isnan(val) or math.isinf(val):
return None
return val
if serial_type == 8:
return 0
if serial_type == 9:
return 1
if serial_type >= 12:
if serial_type % 2 == 0:
return bytes(raw_bytes)
else:
raw_b = bytes(raw_bytes)
try:
return raw_b.decode(encoding.codec_name, errors="replace")
except Exception:
return raw_b.decode("utf-8", errors="replace")
return None
def parse_record_payload(
payload: Union[bytes, memoryview],
encoding: TextEncoding = TextEncoding.UTF8,
allow_partial: bool = True,
) -> Optional[Tuple[List[int], List[Any], bool]]:
"""
Parse a SQLite Record Format payload (Header + Body).
Returns `(serial_types, decoded_values, is_partial)` or `None` if header is invalid.
"""
total_len = len(payload)
if total_len < 1:
return None
try:
header_size, varint_len = decode_varint(payload, 0, total_len)
except ValueError:
return None
# Sanity check on header_size
if header_size < varint_len or header_size > total_len or header_size > 65536:
return None
serial_types: List[int] = []
cursor = varint_len
while cursor < header_size:
try:
st, consumed = decode_varint(payload, cursor, header_size)
except ValueError:
return None
if st < 0 or st in (10, 11):
return None
# Reject absurdly huge serial types (> 100MB single column in corrupted data)
if st > 200_000_000:
return None
serial_types.append(st)
cursor += consumed
if cursor != header_size or not serial_types:
return None
# Decode body values
body_cursor = header_size
values: List[Any] = []
is_partial = False
for st in serial_types:
try:
col_size = serial_type_content_size(st)
except ValueError:
return None
if body_cursor + col_size > total_len:
if not allow_partial:
return None
# Partial / truncated record body
available = max(0, total_len - body_cursor)
raw_slice = payload[body_cursor : body_cursor + available]
is_partial = True
if available > 0 and st >= 12:
val = decode_serial_value(st, raw_slice, encoding)
else:
val = None
values.append(val)
body_cursor = total_len
else:
raw_slice = payload[body_cursor : body_cursor + col_size]
val = decode_serial_value(st, raw_slice, encoding)
values.append(val)
body_cursor += col_size
return serial_types, values, is_partial
# =============================================================================
# 3. HEADER ANALYZER & RESILIENT BRUTE-FORCE PROBER
# =============================================================================
class HeaderAnalyzer:
"""Parses the 100-byte SQLite header or brute-forces page size if header is wiped."""
@staticmethod
def parse_header(mm: Union[mmap.mmap, bytes, memoryview], override_page_size: Optional[int] = None) -> Tuple[DatabaseHeader, List[AnomalyLog]]:
anomalies: List[AnomalyLog] = []
file_len = len(mm)
if file_len < 100:
header = HeaderAnalyzer._default_header(override_page_size or 4096, probed=True)
anomalies.append(
AnomalyLog(
byte_offset=0,
page_number=1,
category="TRUNCATED_FILE",
description=f"File size ({file_len} bytes) is smaller than 100-byte SQLite header.",
hex_preview=bytes(mm[:min(32, file_len)]).hex(),
)
)
return header, anomalies
raw_hdr = bytes(mm[:100])
magic_ok = raw_hdr[:16] == SQLITE3_MAGIC
# Unpack header fields per specification
(
raw_page_size,
write_ver,
read_ver,
reserved_space,
max_frac,
min_frac,
leaf_frac,
change_counter,
db_size_pages,
first_freelist_trunk,
total_freelist,
schema_cookie,
schema_format,
default_cache_size,
largest_root,
raw_encoding,
user_version,
inc_vacuum,
app_id,
) = struct.unpack(">HBBBBBBIIIIIIIIIIII", raw_hdr[16:72])
version_valid_for, sqlite_version = struct.unpack(">II", raw_hdr[92:100])
# Decode page size (value 1 represents 65536 in SQLite >= 3.7.1)
page_size = 65536 if raw_page_size == 1 else raw_page_size
valid_ps = page_size in STANDARD_PAGE_SIZES
valid_fractions = (max_frac == 64 and min_frac == 32 and leaf_frac == 32)
valid_encoding = raw_encoding in (1, 2, 3)
if override_page_size in STANDARD_PAGE_SIZES:
page_size = override_page_size
valid_ps = True
if magic_ok and valid_ps and valid_fractions and reserved_space < 128:
enc = TextEncoding(raw_encoding) if valid_encoding else TextEncoding.UTF8
return (
DatabaseHeader(
magic_valid=True,
page_size=page_size,
write_version=write_ver,
read_version=read_ver,
reserved_space=reserved_space,
max_payload_frac=max_frac,
min_payload_frac=min_frac,
leaf_payload_frac=leaf_frac,
file_change_counter=change_counter,
database_size_pages=db_size_pages,
first_freelist_trunk_page=first_freelist_trunk,
total_freelist_pages=total_freelist,
schema_cookie=schema_cookie,
schema_format=schema_format,
default_cache_size=default_cache_size,
largest_root_btree_page=largest_root,
text_encoding=enc,
user_version=user_version,
incremental_vacuum_mode=inc_vacuum,
application_id=app_id,
version_valid_for=version_valid_for,
sqlite_version_number=sqlite_version,
probed_fallback=False,
probe_confidence=1.0,
),
anomalies,
)
# Header is corrupted, wiped, or zeroed out -> Trigger Auto-Probing Brute-Forcer
anomalies.append(
AnomalyLog(
byte_offset=0,
page_number=1,
category="CORRUPT_DATABASE_HEADER",
description=(
f"100-byte header magic/fields corrupted or wiped "
f"(magic_ok={magic_ok}, raw_page_size={raw_page_size}). Activating brute-force page prober."
),
hex_preview=raw_hdr[:32].hex(),
)
)
probed_ps, confidence, detected_enc = HeaderAnalyzer.probe_page_size(mm, override_page_size)
hdr = HeaderAnalyzer._default_header(probed_ps, probed=True, confidence=confidence, encoding=detected_enc)
# Preserve freelist pointer if it looks plausible within file bounds
max_pages = max(1, file_len // probed_ps)
if 1 < first_freelist_trunk <= max_pages:
hdr.first_freelist_trunk_page = first_freelist_trunk
hdr.total_freelist_pages = min(total_freelist, max_pages)
return hdr, anomalies
@staticmethod
def probe_page_size(
mm: Union[mmap.mmap, bytes, memoryview],
override_page_size: Optional[int] = None,
) -> Tuple[int, float, TextEncoding]:
"""
Brute-force standard SQLite page sizes (512..65536) by inspecting B-Tree page header
invariants across candidate page boundaries.
"""
if override_page_size in STANDARD_PAGE_SIZES:
return override_page_size, 1.0, TextEncoding.UTF8
file_len = len(mm)
best_ps = 4096
best_score = -1.0
for candidate_ps in STANDARD_PAGE_SIZES:
if file_len < candidate_ps:
continue
num_pages = min(256, file_len // candidate_ps)
valid_headers = 0
valid_pointer_arrays = 0
divides_evenly = (file_len % candidate_ps == 0)
for page_idx in range(num_pages):
page_offset = page_idx * candidate_ps
# Page 1 B-tree header starts at offset 100; all other pages start at offset 0
bhdr_offset = page_offset + (100 if page_idx == 0 else 0)
if bhdr_offset + 12 > file_len:
continue
flag = mm[bhdr_offset]
if flag not in VALID_PAGE_TYPES:
continue
freeblock_off, cell_count, cell_content_off, frag_bytes = struct.unpack(
">HHHB", bytes(mm[bhdr_offset + 1 : bhdr_offset + 8])
)
actual_content_off = 65536 if cell_content_off == 0 else cell_content_off
bhdr_size = 8 if flag in (PAGE_TYPE_LEAF_TABLE, PAGE_TYPE_LEAF_INDEX) else 12
ptr_array_start = (100 if page_idx == 0 else 0) + bhdr_size
ptr_array_end = ptr_array_start + (cell_count * 2)
# Check strict B-tree structural invariants:
# 1. Cell count must be > 0 and pointer array must fit before cell content start
# 2. Cell content start must be within candidate_ps
# 3. Freeblock offset must be 0 or within page bounds
if (
0 <= cell_count <= (candidate_ps // 4)
and ptr_array_end <= actual_content_off <= candidate_ps
and (freeblock_off == 0 or ptr_array_end <= freeblock_off < candidate_ps)
and frag_bytes < 128
):
valid_headers += 1
# Verify cell pointers themselves point into [actual_content_off, candidate_ps)
if cell_count > 0:
sample_count = min(cell_count, 8)
abs_ptr_start = page_offset + ptr_array_start
ptrs = struct.unpack(
f">{sample_count}H",
bytes(mm[abs_ptr_start : abs_ptr_start + sample_count * 2]),
)
if all(actual_content_off <= p < candidate_ps for p in ptrs):
valid_pointer_arrays += 1
if num_pages > 0:
ratio = (valid_headers + 2.0 * valid_pointer_arrays) / (3.0 * num_pages)
score = ratio + (0.08 if divides_evenly else 0.0)
if score > best_score and (valid_headers > 0 or valid_pointer_arrays > 0):
best_score = score
best_ps = candidate_ps
confidence = min(1.0, max(0.1, best_score))
return best_ps, round(confidence, 3), TextEncoding.UTF8
@staticmethod
def _default_header(
page_size: int,
probed: bool = True,
confidence: float = 0.5,
encoding: TextEncoding = TextEncoding.UTF8,
) -> DatabaseHeader:
return DatabaseHeader(
magic_valid=False,
page_size=page_size,
write_version=1,
read_version=1,
reserved_space=0,
max_payload_frac=64,
min_payload_frac=32,
leaf_payload_frac=32,
file_change_counter=0,
database_size_pages=0,
first_freelist_trunk_page=0,
total_freelist_pages=0,
schema_cookie=0,
schema_format=4,
default_cache_size=0,
largest_root_btree_page=0,
text_encoding=encoding,
user_version=0,
incremental_vacuum_mode=0,
application_id=0,
version_valid_for=0,
sqlite_version_number=3040000,
probed_fallback=probed,
probe_confidence=confidence,
)
# =============================================================================
# 4. SCHEMA & DDL EXTRACTOR
# =============================================================================
CREATE_TABLE_REGEX = re.compile(
r"CREATE\s+(?:TEMP|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?"
r"(?:['\"`\[]?([a-zA-Z0-9_]+)['\"`\]]?\s*\((.+)\))",
re.IGNORECASE | re.DOTALL,
)
def parse_columns_from_ddl(ddl: str) -> Tuple[List[str], List[str]]:
"""
Extract column names and SQL types from a `CREATE TABLE (...)` statement.
Handles nested parentheses (e.g., VARCHAR(255), CHECK(...)) and table constraints.
"""
match = CREATE_TABLE_REGEX.search(ddl)
if not match:
return [], []
body = match.group(2).strip()
# Split top-level comma-separated clauses
clauses: List[str] = []
depth = 0
current: List[str] = []
in_quote: Optional[str] = None
for ch in body:
if in_quote:
current.append(ch)
if ch == in_quote:
in_quote = None
elif ch in ("'", '"', "`"):
in_quote = ch
current.append(ch)
elif ch == "(":
depth += 1
current.append(ch)
elif ch == ")":
depth = max(0, depth - 1)
current.append(ch)
elif ch == "," and depth == 0:
clauses.append("".join(current).strip())
current = []
else:
current.append(ch)
if current:
clauses.append("".join(current).strip())
col_names: List[str] = []
col_types: List[str] = []
table_constraint_keywords = {"PRIMARY", "FOREIGN", "UNIQUE", "CHECK", "CONSTRAINT"}
for clause in clauses:
if not clause:
continue
tokens = clause.split()
if not tokens:
continue
first_upper = tokens[0].strip("'\"`[]").upper()
if first_upper in table_constraint_keywords:
continue
col_name = tokens[0].strip("'\"`[]")
col_type = "TEXT"
if len(tokens) > 1:
second_upper = tokens[1].upper()
if second_upper not in {"PRIMARY", "NOT", "NULL", "UNIQUE", "DEFAULT", "CHECK", "REFERENCES", "COLLATE"}:
col_type = tokens[1].upper()
col_names.append(col_name)
col_types.append(col_type)
return col_names, col_types
# =============================================================================
# 5. CORE BINARY SALVAGER & B-TREE / FREELIST / WAL ENGINE
# =============================================================================
class SQLiteSalvagerEngine:
"""
Low-level binary stream parser and carver for SQLite 3 databases and WAL files.
"""
def __init__(
self,
db_path: Union[str, Path],
wal_path: Optional[Union[str, Path]] = None,
override_page_size: Optional[int] = None,
carve_sensitivity: str = "medium",
salvage_wal: bool = True,
logger: Optional[logging.Logger] = None,
) -> None:
self.db_path = Path(db_path)
self.wal_path = Path(wal_path) if wal_path else Path(f"{self.db_path}-wal")
self.override_page_size = override_page_size
self.carve_sensitivity = carve_sensitivity.lower()
self.salvage_wal = salvage_wal
self.log = logger or logging.getLogger("sqlite-salvager")
# Sensitivity thresholds for heuristic raw record carving
if self.carve_sensitivity == "high":
self.min_carve_cols = 2
self.min_carve_payload = 4
elif self.carve_sensitivity == "low":
self.min_carve_cols = 3
self.min_carve_payload = 10
else: # medium
self.min_carve_cols = 2
self.min_carve_payload = 6
self.records: List[SalvagedRecord] = []
self.seen_offsets: Set[Tuple[Optional[int], int]] = set() # (wal_frame, abs_byte_offset)
self.page_to_table_map: Dict[int, str] = {1: "sqlite_schema"}
self.stats: Optional[ForensicAuditStats] = None
# -------------------------------------------------------------------------
# Main Entrypoint
# -------------------------------------------------------------------------
def run(self) -> ForensicAuditStats:
if not self.db_path.exists():
raise FileNotFoundError(f"Database file not found: {self.db_path}")
file_size = self.db_path.stat().st_size
sha256_hash = self._compute_sha256(self.db_path)
self.stats = ForensicAuditStats(
file_path=str(self.db_path),
file_size_bytes=file_size,
sha256_hash=sha256_hash,
)
if file_size == 0:
self.stats.anomalies.append(
AnomalyLog(0, 0, "EMPTY_FILE", "Database file is 0 bytes.")
)
return self.stats
with open(self.db_path, "rb") as f:
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
try:
self._process_database_stream(mm)
finally:
mm.close()
# Process Write-Ahead Log (-wal) if requested and available
if self.salvage_wal and self.wal_path.exists() and self.wal_path.stat().st_size >= WAL_HEADER_SIZE:
with open(self.wal_path, "rb") as wf:
wal_mm = mmap.mmap(wf.fileno(), 0, access=mmap.ACCESS_READ)
try:
self._process_wal_stream(wal_mm)
finally:
wal_mm.close()
# Assign records to tables or synthesize signature-based tables
self._reconstruct_and_assign_schemas()
return self.stats
# -------------------------------------------------------------------------
# Database Binary Stream Processing
# -------------------------------------------------------------------------
def _process_database_stream(self, mm: mmap.mmap) -> None:
assert self.stats is not None
header, hdr_anomalies = HeaderAnalyzer.parse_header(mm, self.override_page_size)
self.stats.header_info = header
self.stats.anomalies.extend(hdr_anomalies)
ps = header.page_size
total_pages = max(1, math.ceil(len(mm) / ps))
self.stats.total_pages_scanned = total_pages
# 1. Identify Freelist Trunk & Leaf Pages
freelist_pages = self._traverse_freelist(mm, header, total_pages)
# 2. First pass: Traverse Interior Table B-Trees to map child pages to Root Pages
self._map_btree_hierarchy(mm, header, total_pages, freelist_pages)
# 3. Second pass: Scan every page for active cells, freeblocks, slack space, or raw carving
for page_num in range(1, total_pages + 1):
page_start = (page_num - 1) * ps
page_end = min(len(mm), page_start + ps)
page_buf = memoryview(mm)[page_start:page_end]
if page_num in freelist_pages:
# Carve freelist page for deleted records
self._carve_raw_region(
mm=mm,
region_start=page_start,
region_end=page_end,
page_num=page_num,
header=header,
source_type=RecordSourceType.FREELIST_PAGE,
)
continue
self._parse_page(
mm=mm,
page_buf=page_buf,
page_num=page_num,
page_abs_start=page_start,
header=header,
wal_frame=None,
)
def _traverse_freelist(
self,
mm: mmap.mmap,
header: DatabaseHeader,
total_pages: int,
) -> Set[int]:
"""Traverse the Freelist trunk chain and collect all trunk & leaf page numbers."""
assert self.stats is not None
freelist_pages: Set[int] = set()
trunk_page = header.first_freelist_trunk_page
ps = header.page_size
visited_trunks: Set[int] = set()
while 1 < trunk_page <= total_pages and trunk_page not in visited_trunks:
visited_trunks.add(trunk_page)
freelist_pages.add(trunk_page)
self.stats.freelist_trunk_pages += 1
trunk_offset = (trunk_page - 1) * ps
if trunk_offset + 8 > len(mm):
break
next_trunk, leaf_count = struct.unpack(">II", mm[trunk_offset : trunk_offset + 8])
max_leaves = (header.usable_size - 8) // 4
if leaf_count > max_leaves:
self.stats.anomalies.append(
AnomalyLog(
byte_offset=trunk_offset,
page_number=trunk_page,
category="CORRUPT_FREELIST_TRUNK",
description=f"Freelist trunk page {trunk_page} claims {leaf_count} leaves (max={max_leaves}). Clamping.",
hex_preview=bytes(mm[trunk_offset : trunk_offset + 16]).hex(),
)
)
leaf_count = max_leaves
for i in range(leaf_count):
ptr_off = trunk_offset + 8 + (i * 4)
if ptr_off + 4 > len(mm):
break
leaf_pg = struct.unpack(">I", mm[ptr_off : ptr_off + 4])[0]
if 1 < leaf_pg <= total_pages and leaf_pg not in freelist_pages:
freelist_pages.add(leaf_pg)
self.stats.freelist_leaf_pages += 1
trunk_page = next_trunk
return freelist_pages
def _map_btree_hierarchy(
self,
mm: mmap.mmap,
header: DatabaseHeader,
total_pages: int,
freelist_pages: Set[int],
) -> None:
"""
Scan Interior Table B-Tree pages (0x05) to map child leaf pages back to their root table page.
"""
ps = header.page_size
parent_map: Dict[int, int] = {}
for page_num in range(1, total_pages + 1):
if page_num in freelist_pages:
continue
page_start = (page_num - 1) * ps
bhdr_off = page_start + (100 if page_num == 1 else 0)
if bhdr_off + 12 > len(mm):
continue
flag = mm[bhdr_off]
if flag != PAGE_TYPE_INTERIOR_TABLE:
continue
_, cell_count, cell_content_off, _ = struct.unpack(
">HHHB", mm[bhdr_off + 1 : bhdr_off + 8]
)
rightmost_ptr = struct.unpack(">I", mm[bhdr_off + 8 : bhdr_off + 12])[0]
if 1 <= rightmost_ptr <= total_pages and rightmost_ptr != page_num:
parent_map[rightmost_ptr] = page_num
ptr_array_start = bhdr_off + 12
for i in range(min(cell_count, ps // 6)):
p_off = ptr_array_start + i * 2
if p_off + 2 > page_start + ps or p_off + 2 > len(mm):
break
cell_rel = struct.unpack(">H", mm[p_off : p_off + 2])[0]
cell_abs = page_start + cell_rel
if cell_abs + 4 <= page_start + ps and cell_abs + 4 <= len(mm):
left_child = struct.unpack(">I", mm[cell_abs : cell_abs + 4])[0]
if 1 <= left_child <= total_pages and left_child != page_num:
parent_map[left_child] = page_num
# Resolve root ancestors with cycle protection
for child_pg in list(parent_map.keys()):
curr = child_pg
visited: Set[int] = {curr}
while curr in parent_map:
nxt = parent_map[curr]
if nxt in visited:
break
visited.add(nxt)
curr = nxt
# Map both the root and intermediate pages
for v in visited:
self.page_to_table_map[v] = f"root_page_{curr}"
# -------------------------------------------------------------------------
# Page-Level Parser (Active Cells, Freeblocks, Slack Space)
# -------------------------------------------------------------------------
def _parse_page(
self,
mm: Union[mmap.mmap, bytes, memoryview],
page_buf: memoryview,
page_num: int,
page_abs_start: int,
header: DatabaseHeader,
wal_frame: Optional[int] = None,
) -> None:
assert self.stats is not None
ps = len(page_buf)
bhdr_rel = 100 if (page_num == 1 and header.magic_valid) else 0
# If Page 1 has a wiped 100-byte header, check whether offset 100 has a valid B-tree header
if page_num == 1 and not header.magic_valid and ps >= 112:
if page_buf[100] in VALID_PAGE_TYPES:
bhdr_rel = 100
if bhdr_rel + 8 > ps:
self.stats.corrupted_pages_skipped += 1
return
flag = page_buf[bhdr_rel]
if flag not in VALID_PAGE_TYPES:
# Page is not a valid B-tree page (or its header was overwritten) -> raw carve!
if wal_frame is None:
self.stats.corrupted_pages_skipped += 1
self.stats.anomalies.append(
AnomalyLog(
byte_offset=page_abs_start + bhdr_rel,
page_number=page_num,
category="INVALID_BTREE_FLAG",