Tools · CTF categories for beginners · 13 / 18
Repairing corrupted files in CTFs: magic bytes, PNG chunks, and ZIP headers
Fix files whose headers were deliberately damaged, using a hex editor and format knowledge: restore magic bytes, check PNG chunk CRCs, and recover ZIP entries.
Why files “do not open”
A common forensics challenge gives a file that viewers reject. Often the first bytes were changed, a length field is wrong, or a checksum does not match. Knowing a format’s structure lets you fix it by hand. The same skill helps in real investigations with partially recovered files.
PNG structure
A PNG starts with the 8-byte signature 89 50 4E 47 0D 0A 1A 0A, followed by chunks. Each chunk is a 4-byte length, a 4-byte type such as IHDR, IDAT, or IEND, the data, and a 4-byte CRC over the type and data. pngcheck reports exactly which chunk is wrong. Width and height in IHDR are sometimes altered, which still produces a valid CRC mismatch you can use to recover the correct values.
xxd broken.png | head -3 pngcheck -v broken.png printf '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' | dd of=broken.png bs=1 seek=0 count=8 conv=notrunc pngcheck broken.png
Lab: break and fix
Take a PNG you own, corrupt its signature with dd, and fix it. Then change the height in IHDR and use Python with zlib.crc32 to find which height makes the stored CRC match. Finally, create a ZIP, zero out its first local header signature, and recover it with zip -FF or by restoring 50 4B 03 04.
python3 - <<'EOF'
import struct, zlib
data = open('tall.png', 'rb').read()
ihdr = data[12:29] # type + 13 bytes of IHDR data
stored = struct.unpack('>I', data[29:33])[0]
w = struct.unpack('>I', ihdr[4:8])[0]
for h in range(1, 5000):
cand = ihdr[:8] + struct.pack('>I', h) + ihdr[12:]
if zlib.crc32(cand) == stored:
print('original height:', h); break
EOF
printf '\x00\x00\x00\x00' | dd of=a.zip bs=1 seek=0 count=4 conv=notrunc
zip -FF a.zip --out fixed.zip && unzip -l fixed.zipKeep references handy
File format specifications and summaries such as the PNG specification, the ZIP APPNOTE, and Ange Albertini’s file format posters are worth bookmarking. A hex editor with templates, such as ImHex, highlights structures and makes these repairs faster.
Diagram
File structures worth knowing
Signature, lengths, checksums.
- PNG
Signature, then chunks: length, type, data, CRC.
- JPEG
FF D8 start, segments with markers, FF D9 end.
- ZIP
Local headers 50 4B 03 04, central directory 50 4B 01 02, end record 50 4B 05 06.
- PDF
%PDF header, objects, xref table, %%EOF trailer.
Check yourself
1. What are the first bytes of a valid PNG?
2. Which PNG field lets you detect a tampered IHDR height?
3. Which command attempts to repair a damaged ZIP archive?