Scan a raw disk image for sfiles known magics (831 formats) and carve out the files: PNG chunk walk, JPEG marker walk, GIF block walk, ZIP local-header walk + EOCD, PDF %%EOF scan, gzip inflate sizing; next- header/EOF fallback with a size cap for the rest. Report lists offset, format, size, confidence and how the end was found. - src/scar.c, src/footers.h: carver + footer/trailer table - Makefile: scar target (links -lz), test-scar target, install both - tests/test_scar.py: synthetic image, 7 files recovered byte-identical - docs/scar.md: usage, real example output, decisions, limits
191 lines
6.3 KiB
Python
191 lines
6.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Synthetic-image test for scar.
|
|
|
|
Builds a raw image with known files planted at known offsets (PNG, JPEG,
|
|
GIF, ZIP, PDF, gzip, plus a truncated JPEG at the very end), runs
|
|
./scar on it, and verifies every planted file is recovered byte-identical
|
|
at the right offset with the right size, and that the report lists them.
|
|
|
|
Usage: python3 tests/test_scar.py [--keep] (run from the repo root)
|
|
--keep leaves the image and carved output in /tmp/scar-test/ for inspection.
|
|
Exit 0 on success, 1 on any mismatch.
|
|
"""
|
|
import io
|
|
import os
|
|
import random
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import zipfile
|
|
|
|
from PIL import Image
|
|
|
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
|
|
def make_png():
|
|
im = Image.new("RGB", (64, 48))
|
|
px = im.load()
|
|
for y in range(48):
|
|
for x in range(64):
|
|
px[x, y] = (x * 4 % 256, y * 5 % 256, (x + y) * 2 % 256)
|
|
buf = io.BytesIO()
|
|
im.save(buf, "PNG")
|
|
return buf.getvalue()
|
|
|
|
|
|
def make_jpeg():
|
|
im = Image.new("RGB", (80, 60), (200, 30, 90))
|
|
px = im.load()
|
|
for y in range(60):
|
|
for x in range(80):
|
|
px[x, y] = ((x * 3) % 256, (y * 4) % 256, 128)
|
|
buf = io.BytesIO()
|
|
im.save(buf, "JPEG", quality=85)
|
|
return buf.getvalue()
|
|
|
|
|
|
def make_gif():
|
|
im = Image.new("P", (32, 32))
|
|
im.putpalette([i % 256 for i in range(768)])
|
|
px = im.load()
|
|
for y in range(32):
|
|
for x in range(32):
|
|
px[x, y] = (x + y) % 256
|
|
buf = io.BytesIO()
|
|
im.save(buf, "GIF")
|
|
return buf.getvalue()
|
|
|
|
|
|
def make_zip():
|
|
buf = io.BytesIO()
|
|
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
zf.writestr("hello.txt", "hello from inside the zip\n" * 20)
|
|
zf.writestr("data.bin", bytes(range(256)) * 4)
|
|
return buf.getvalue()
|
|
|
|
|
|
def make_pdf():
|
|
body = (
|
|
b"%PDF-1.4\n"
|
|
b"1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n"
|
|
b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n"
|
|
b"3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >> endobj\n"
|
|
b"xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n"
|
|
b"0000000058 00000 n \n0000000115 00000 n \n"
|
|
b"trailer << /Size 4 /Root 1 0 R >>\nstartxref\n193\n%%EOF\n"
|
|
)
|
|
return body
|
|
|
|
|
|
def make_gz():
|
|
import gzip
|
|
return gzip.compress(b"the quick brown fox jumps over the lazy dog. " * 50)
|
|
|
|
|
|
def main():
|
|
keep = "--keep" in sys.argv
|
|
work = "/tmp/scar-test" if keep else tempfile.mkdtemp(prefix="scar-test-")
|
|
if keep:
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
os.makedirs(work, exist_ok=True)
|
|
rng = random.Random(1234)
|
|
|
|
# (name, bytes, filler-before) — filler 0 tests back-to-back files.
|
|
plan = [
|
|
("png", make_png(), 0),
|
|
("jpeg", make_jpeg(), 113),
|
|
("gif", make_gif(), 4096),
|
|
("zip", make_zip(), 0),
|
|
("pdf", make_pdf(), 777),
|
|
("gz", make_gz(), 2048),
|
|
]
|
|
jpeg_full = make_jpeg()
|
|
truncated = jpeg_full[:200] # truncated file at EOF: low-confidence carve
|
|
|
|
image = bytearray()
|
|
expected = [] # (offset, name, bytes)
|
|
for name, data, gap in plan:
|
|
image += bytes(rng.randrange(256) for _ in range(gap))
|
|
expected.append((len(image), name, data))
|
|
image += data
|
|
image += bytes(rng.randrange(256) for _ in range(512))
|
|
trunc_off = len(image)
|
|
image += truncated
|
|
|
|
img_path = os.path.join(work, "test.img")
|
|
with open(img_path, "wb") as f:
|
|
f.write(image)
|
|
outdir = os.path.join(work, "carved")
|
|
|
|
scar = os.path.join(REPO, "scar")
|
|
proc = subprocess.run([scar, "-o", outdir, img_path],
|
|
capture_output=True, text=True)
|
|
print(proc.stdout, end="")
|
|
if proc.stderr:
|
|
print(proc.stderr, end="", file=sys.stderr)
|
|
if proc.returncode != 0:
|
|
print(f"FAIL: scar exited {proc.returncode}")
|
|
return 1
|
|
|
|
failures = []
|
|
extmap = {"png": "png", "jpeg": "jpeg", "gif": "gif",
|
|
"zip": "zip", "pdf": "pdf", "gz": "gz"}
|
|
for off, name, data in expected:
|
|
# output filename: zero-padded offset + lowercase ext from sfile table
|
|
fname = f"{off:010d}.{extmap[name]}"
|
|
got_path = os.path.join(outdir, fname)
|
|
if not os.path.exists(got_path):
|
|
failures.append(f"{name} at {off}: missing {fname}")
|
|
continue
|
|
got = open(got_path, "rb").read()
|
|
if got != data:
|
|
failures.append(f"{name} at {off}: {len(got)} bytes, "
|
|
f"expected {len(data)} (content differs)")
|
|
else:
|
|
print(f"ok: {name} at offset {off}, {len(data)} bytes, "
|
|
f"byte-identical ({fname})")
|
|
|
|
# truncated JPEG: carved to EOF with low confidence
|
|
trunc_name = f"{trunc_off:010d}.jpeg"
|
|
trunc_path = os.path.join(outdir, trunc_name)
|
|
if not os.path.exists(trunc_path):
|
|
failures.append(f"truncated jpeg at {trunc_off}: missing {trunc_name}")
|
|
else:
|
|
got = open(trunc_path, "rb").read()
|
|
if got != truncated:
|
|
failures.append(f"truncated jpeg at {trunc_off}: {len(got)} bytes, "
|
|
f"expected {len(truncated)}")
|
|
else:
|
|
print(f"ok: truncated jpeg at offset {trunc_off}, "
|
|
f"{len(truncated)} bytes, byte-identical ({trunc_name})")
|
|
|
|
# report must list every planted offset and the truncated one
|
|
report = open(os.path.join(outdir, "report.txt")).read()
|
|
for off, name, data in expected + [(trunc_off, "trunc-jpeg", truncated)]:
|
|
if str(off) not in report:
|
|
failures.append(f"report.txt missing offset {off}")
|
|
extmap = {"png": "png", "jpeg": "jpeg", "gif": "gif",
|
|
"zip": "zip", "pdf": "pdf", "gz": "gz"}
|
|
expected_files = {f"{off:010d}.{extmap[name]}" for off, name, _ in expected}
|
|
expected_files.add(trunc_name)
|
|
extra = sorted(fn for fn in os.listdir(outdir)
|
|
if fn != "report.txt" and fn not in expected_files)
|
|
if extra:
|
|
failures.append(f"unexpected extra carved files: {extra}")
|
|
|
|
if failures:
|
|
print("FAIL:")
|
|
for f in failures:
|
|
print(f" - {f}")
|
|
return 1
|
|
print(f"PASS: {len(expected) + 1} files recovered, image {len(image)} bytes")
|
|
if not keep:
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|