Deleted Files and File Carving
The intruder deleted the tool they used and the archive of documents they staged for upload. On most file systems, "deleted" means much less than it sounds: the directory entry is marked as free and the clusters are returned to the free list, but the bytes stay on the disk until something else overwrites them. Forensics recovers such files in two ways: through the file system's own leftover metadata (the directory entry or MFT record still says where the data was), and, when that is gone too, by carving: scanning raw bytes for the signatures of known file formats. This lesson does both on a synthetic disk image built in the browser.
Definitions
- Allocated / unallocated space: clusters in use by a file / clusters the file system considers free. Deleted data lives in unallocated space, and in slack space (the unused end of a file's last cluster).
- Deletion on FAT: the first byte of the 32-byte directory entry becomes
0xE5; the starting cluster and size remain, and the FAT chain is zeroed. On NTFS: the MFT record's in-use flag is cleared; the record (name, timestamps, data runs) survives until reused. On ext4: the inode's block pointers are typically wiped, which makes metadata recovery hard and carving more important. - File carving: finding files in raw data by header and footer signatures (
89 50 4E 47 0D 0A 1A 0A…IENDchunk for PNG,FF D8 FF…FF D9for JPEG,%PDF-…%%EOF,PK\x03\x04for ZIP), or by header plus a length read from the format. Tools: PhotoRec, foremost, scalpel, bulk_extractor (which carves features such as e-mail addresses and URLs rather than whole files). - Fragmentation: a file stored in non-contiguous clusters. Simple header-to-footer carving then produces a corrupted file; validation (checksums inside the format) tells good carves from bad.
- TRIM: on SSDs the operating system tells the drive which blocks are free, and the drive may erase them in the background. Deleted data on SSDs often really is gone.
A synthetic disk, a deleted file, and carving
The image is 64 sectors of 512 bytes. Sector 0 holds a tiny FAT-like directory (8.3 names, starting sector, size); the data area holds a small PNG image (built properly, with CRCs), a text note, and a "staging" archive that was deleted (its entry starts with 0xE5). A JPEG-like blob sits in sectors no directory entry points to, left over from an older deleted file whose entry was already reused. All contents are synthetic.
import struct, zlib
SECTOR, N = 512, 64
disk = bytearray(SECTOR * N)
def png(w=4, h=4):
def chunk(t, d): return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
raw = b"".join(b"\0" + b"".join(bytes([x * 60, y * 60, 128]) for x in range(w)) for y in range(h))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b""))
files = [ # (8.3 name, start sector, data, deleted?)
(b"LOGO PNG", 4, png(), False),
(b"NOTE TXT", 6, b"Meeting moved to 15:00. Bring the lab laptop.\n", False),
(b"STAGE ZIP", 10, b"PK\x03\x04" + b"lab-staging: q4-report.xlsx, contacts.csv (synthetic)" + bytes(40) + b"PK\x05\x06" + bytes(18), True),
]
for i, (name, start, data, deleted) in enumerate(files):
entry = bytearray(32)
entry[0:11] = name
if deleted:
entry[0] = 0xE5 # FAT marks a deleted entry by its first byte
struct.pack_into("<HI", entry, 26, start, len(data)) # simplified: start sector, size
disk[i * 32:(i + 1) * 32] = entry
disk[start * SECTOR:start * SECTOR + len(data)] = data
jpeg_like = b"\xff\xd8\xff\xe0" + b"\x00\x10JFIF\x00" + bytes(range(256)) * 2 + b"\xff\xd9"
disk[40 * SECTOR:40 * SECTOR + len(jpeg_like)] = jpeg_like # orphaned data, no entry points here
print("1) directory listing, including deleted entries")
for i in range(SECTOR // 32):
e = disk[i * 32:(i + 1) * 32]
if e[0] == 0:
break
start, size = struct.unpack_from("<HI", e, 26)
name = (("?" if e[0] == 0xE5 else chr(e[0])) + e[1:8].decode()).rstrip() + "." + e[8:11].decode()
state = "DELETED" if e[0] == 0xE5 else "in use"
content = bytes(disk[start * SECTOR:start * SECTOR + size])
print(f" {name:<12} sector {start:>2} size {size:>4} {state:<8} starts with {content[:8]!r}")
print(" recovered via metadata:", bytes(disk[10 * SECTOR + 4:10 * SECTOR + 57]).decode(), "…")
print("2) carving by signature over the whole image")
SIGS = [("png", b"\x89PNG\r\n\x1a\n", b"IEND\xaeB`\x82"), ("jpeg", b"\xff\xd8\xff", b"\xff\xd9"),
("zip", b"PK\x03\x04", b"PK\x05\x06")]
for kind, head, foot in SIGS:
pos = 0
while (start := disk.find(head, pos)) != -1:
end = disk.find(foot, start)
size = end + len(foot) - start + (18 if kind == "zip" else 0)
blob = bytes(disk[start:start + size])
note = ""
if kind == "png": # validate every chunk CRC
o, ok = 8, True
while o < len(blob):
ln = struct.unpack_from(">I", blob, o)[0]
t, d = blob[o + 4:o + 8], blob[o + 8:o + 8 + ln]
ok &= struct.unpack_from(">I", blob, o + 8 + ln)[0] == zlib.crc32(t + d)
o += 12 + ln
note = "all chunk CRCs valid" if ok else "CRC errors: fragmented or damaged"
sector = start // SECTOR
listed = any(s == sector for _, s, _, _ in files)
print(f" {kind:<4} at offset {start:#07x} (sector {sector:>2}) {size:>4} bytes "
f"{'has a directory entry' if listed else 'ORPHAN: no entry'} {note}")
pos = start + 11) directory listing, including deleted entries
LOGO.PNG sector 4 size 98 in use starts with b'\x89PNG\r\n\x1a\n'
NOTE.TXT sector 6 size 46 in use starts with b'Meeting '
?TAGE.ZIP sector 10 size 119 DELETED starts with b'PK\x03\x04lab-'
recovered via metadata: lab-staging: q4-report.xlsx, contacts.csv (synthetic) …
2) carving by signature over the whole image
png at offset 0x00800 (sector 4) 98 bytes has a directory entry all chunk CRCs valid
jpeg at offset 0x05000 (sector 40) 525 bytes ORPHAN: no entry
zip at offset 0x01400 (sector 10) 119 bytes has a directory entry
Step 1 is metadata recovery: the deleted entry still names the file (minus its first letter, which FAT overwrote with 0xE5, so tools show ?TAGE.ZIP and ask the examiner for the letter), its start and size, so the content comes back exactly. Step 2 is carving: it finds the PNG and the deleted ZIP again, misses the text note (plain text has no signature, which is why bulk_extractor-style feature carving exists), and finds the orphaned JPEG-like blob in sector 40, which no metadata points to any more. The PNG's chunk CRCs confirm that the carve is complete and undamaged; for formats without internal checksums, carved files need a manual check.
How deleted data is found in investigations
- File-system tools: The Sleuth Kit's
fls -rdlists deleted entries,icatextracts by inode/MFT number,istatshows metadata; Autopsy is its GUI. For NTFS, MFT parsers list records without the in-use flag. - Carving the unallocated space (
blklsextracts it first) with PhotoRec or scalpel; bulk_extractor over the whole image for e-mail addresses, URLs, credit-card-like numbers and network packets in memory or swap. - Other copies: Volume Shadow Copies, backups, cloud sync folders, thumbnail caches, the recycle bin (
$Recycle.Binwith$Imetadata files): often easier than carving.
How data is really deleted (and why defenders care)
- Organisations must sometimes guarantee deletion (end of life of disks, personal data): use the drive's built-in secure erase or cryptographic erase (destroying the key of a self-encrypting or BitLocker-encrypted disk), following NIST SP 800-88 media sanitisation guidelines; overwriting is unreliable on SSDs.
- Full-disk encryption means a stolen disk reveals nothing, deleted or not; for investigators it means acquiring with the key (or live), so plan key escrow.
Pitfalls
- Writing to the evidence. Recovering files onto the disk being examined overwrites the very unallocated space you are searching. Always work on an image.
- Fragmented files. Header-to-footer carving of a fragmented file gives a corrupt result; validate.
- False carves. Signatures occur by chance inside other data;
FF D8 FFappears in random bytes about once per 16 MiB. - Overclaiming. A carved file proves the bytes were on the disk at some time; without metadata it doesn't say when, by whom, or under which name.
Practice
1. Why can the deleted ZIP be recovered exactly in step 1, but the JPEG-like blob only by carving?
The ZIP's directory entry survived (only its first byte changed), so its start and size are known. The blob's entry was reused by another file, so nothing points to its sectors any more; only its own signatures reveal it.
2. Move the PNG so that it is split across sectors 4 and 20 (fragmented) and carve again. What happens to the CRC check?
Write the first 100 bytes at sector 4 and the rest at sector 20. Header-to-footer carving then includes the bytes in between (zeros or other data), so the chunk lengths and CRCs no longer line up and the check reports CRC errors. Smarter carvers try reassembly using the format's structure.
3. On an SSD with TRIM enabled, a deleted file from last week can't be carved. Where else could it still exist?
In Volume Shadow Copies or backups, a cloud-sync history, mail attachments or sent items, memory or the page file if recently used, another host it was copied to, and in network captures or proxy logs if it was transferred.
Test yourself
What does FAT do to the directory entry of a deleted file?
- Erases all 32 bytes
- Replaces the first byte of the name with 0xE5
- Encrypts it
- Moves it to the end of the directory
What is file carving?
- Compressing evidence
- Recovering files from raw data using format signatures, without file-system metadata
- Hashing files
- Imaging a disk
Why did the carving step validate the PNG's chunk CRCs?
- PNG files must be signed
- To tell a complete, undamaged carve from a fragmented or corrupted one
- To find the file name
- To compress it
Why is deleted data on SSDs often unrecoverable?
- SSDs encrypt everything
- TRIM lets the drive erase freed blocks in the background
- SSDs have no file system
- Carving tools don't support SSDs