DEV Community

Cover image for zipfile Never Writes the Zip's Executable Bit to Disk
Mustafa ERBAY
Mustafa ERBAY

Posted on Originally published at mustafaerbay.com.tr

zipfile Never Writes the Zip's Executable Bit to Disk

If you have unpacked a deployment bundle, called the installer script inside it and got
back "permission denied", the first suspect is usually the archive: was the bit wrong on
the machine that packed it, or does zip simply not carry the execute permission?

It carries it. A zip archive holds the Unix mode for every entry; the tool that opens the
archive is the one that loses it. Opening the same archive on the same machine with two
tools gave me -rwxr-xr-x in one case and -rw-r--r-- in the other. The archive was
identical both times. And the mode that landed on disk did not come from the archive at
all — it came from the umask of the machine doing the extraction.

The irritating part is that this is written down nowhere. On Python's zipfile
documentation page — on both of today's pages, 3.13.18 and 3.15.2 — the word "permission"
does not appear at all. The whole description of external_attr, the field where the
mode lives, is three words: "External file attributes." To confirm the behaviour you have
to read the source and a report that has been open for fourteen years.

Every number below comes from a run on 30 November 2026 on my own machine: MacBook Pro M4
Pro, macOS 26.6.2 (Darwin 25.6.0), arm64, APFS, umask 022. I had two Pythons on hand —
the python.org build of 3.13.3 and Homebrew's 3.14.3 — plus the system Info-ZIP binaries,
UnZip 6.00 and Zip 3.0.

What the archive actually stores

Let us clear the suspect first. The zip format keeps a 32-bit field called external_attr
in each entry's central directory record, and on Unix the packing tool writes the file's
st_mode into the upper 16 bits of it. zipfile does this in a single line:

zinfo.external_attr = (st.st_mode & 0xFFFF) << 16  # Unix attributes
Enter fullscreen mode Exit fullscreen mode

The line sits at 618 in Lib/zipfile/__init__.py on CPython's 3.13 branch and at 662 on
main. I packed a yap.sh with mode 0755 and an alt/veri.txt with mode 0644, then
read the archive back:

yap.sh           external_attr=0x81ed0000  mode=-rwxr-xr-x (0o755)  create_system=3
alt/veri.txt     external_attr=0x81a40000  mode=-rw-r--r-- (0o644)  create_system=3
Enter fullscreen mode Exit fullscreen mode

Convert 0x81ed from hex to octal and you get 0o100755: file type bits plus 755. The
archive is honest. The executable bit is in there, waiting to be read. create_system=3
says the field was filled in with Unix semantics — a detail the fix at the end depends on.

What lands on disk

I opened the same archive five different ways. The results split in two:

Extractor yap.sh mode
zipfile.extractall — Python 3.13.3 -rw-r--r--
zipfile.extractall — Python 3.14.3 -rw-r--r--
shutil.unpack_archive — Python 3.13.3 -rw-r--r--
unzip 6.00 -rwxr-xr-x
tarfile (same files packed as tar) -rwxr-xr-x

Two Python versions and two APIs give the same answer. shutil.unpack_archive is on the
list, but its code is worth reading: it does not call extractall. It opens a ZipFile,
loops over the entries itself, and makes its own open(..., 'wb') and copyfileobj
calls. Same outcome, different path — and that loop silently skips entries beginning with
/ or ...

The 644 that landed is not from the archive either. I changed umask and opened the
same archive with the same Python three times:

umask while extracting yap.sh mode
022 -rw-r--r--
077 -rw-------
000 -rw-rw-rw-

That table gives the exact shape of the loss. zipfile does not read the mode from the
archive and set it aside; it creates the file with an ordinary open(..., "wb"), and the
operating system gives that file what it gives every new file: 0o666 minus the umask.
The executable bit is not lost — it is never applied. The mode becomes a property of the
extracting machine rather than of the archive.

Diagram

Where the loss lives in the source

No guessing is required: the module is readable — 2,416 lines on GitHub's 3.13 branch and
3,015 on main. I looked for the same three counts in the installed 3.13.3 and 3.14.3
builds and in both branches:

  • occurrences of chmod: 0
  • occurrences of utime: 0
  • occurrences of preserve_permissions: 0

The place that writes the file is one statement:

with self.open(member, pwd=pwd) as source, \
     open(targetpath, "wb") as target:
    shutil.copyfileobj(source, target)
Enter fullscreen mode Exit fullscreen mode

Since no call anywhere in the module writes a mode to disk, this is not a setting you can
switch off; it is a feature that does not exist.

Bug or decision? There is a record. CPython issue 59999, titled precisely "Zipfile.extractall
does not preserve file permissions", was opened on 27 August 2012 and is still open,
with 28 comments under it. A patch was attempted in 2022 — PR 32289 added a
preserve_permissions option to ZipFile.extract — and it was closed unmerged on 20
October 2026. But the reason for closing was not abandonment: it was superseded by a newer
pull request for the same issue, and that one is open. PR 150061 is titled "zipfile:
restore Unix permissions after extraction", and the sentence in its body is familiar:
"Fixed by applying the stored permissions with os.chmod after extraction." Opened 19 May
2026, last touched 7 November 2026, still open.

So the gap may close one day, and when it does, the behaviour in your pipeline will
change
: the call that returns 0644 today will start applying the archive's mode. That
cuts both ways — a reason to write the mode yourself today, and a reason to know what your
bundle says inside when you upgrade tomorrow.

The second loss: timestamps

Finding the mode loss sent me down the same path for timestamps. I stamped a file with
13:45:07.750, zipped it, and read it back:

source mtime : 2026-11-30T13:45:07.750000
zip date_time: (2026, 11, 30, 13, 45, 6)
Enter fullscreen mode Exit fullscreen mode

Two things happen at once. Zip's central directory keeps seconds in even numbers, so
07.750 is truncated to 06 and 1.75 seconds disappear. Then zipfile never applies
that stored timestamp to the file: the mtime of the extracted file was the moment of
extraction, not the time in the archive. The utime: 0 count above is what that looks
like in the source.

unzip does apply the timestamp, with a trap of its own. Zip's timestamp carries no time
zone, and Python's documentation says so plainly: "The central directory timestamp is
interpreted as representing local time, rather than UTC time, to match the behavior of
other zip tools." What sits in the archive is the wall-clock reading "13:45:06", not an
instant. I opened the same archive with unzip under three time zones:

TZ Displayed time Epoch
Europe/Istanbul 13:45:06 1796035506
UTC 13:45:06 1796046306
America/New_York 13:45:06 1796064306

The wall clock is identical on all three rows; the absolute time is in three different
places — 10,800 seconds between Istanbul and UTC, 28,800 between Istanbul and New York.
The answer to "when was this file modified?" now depends on which machine opened the
archive. Pack the same files as tar and mtime is stored as an epoch value, so
1796035507 comes back untouched; the time zone question never arises.

Zip's date field cannot represent anything before 1980, and packaging tools carve that
floor into the files they produce. The piece where I went looking for my files' birth
dates
has the
measurements; the pile of 1981 stamps there comes from exactly this field.

The other direction: archives zipfile writes

So far the story has been "it loses the mode on the way in". It also does something on the
way out. When you add text to an archive with writestr — from memory rather than from a
file — the module knows nothing about the mode, and it does not leave the field empty:

if zinfo.filename.endswith('/'):
    zinfo.external_attr = 0o40775 << 16   # drwxrwxr-x
    zinfo.external_attr |= 0x10           # MS-DOS directory flag
else:
    zinfo.external_attr = 0o600 << 16     # ?rw-------
Enter fullscreen mode Exit fullscreen mode

In 3.13.3 this branch sits in the body of writestr itself, and it is the path taken when
you pass the filename as a plain string. (In 3.14 the same default moved into
ZipInfo._for_archive; the if not zinfo.external_attr guard inside _open_to_write
only fires when you hand it a ZipInfo whose field was left at zero.)

The result is that an entry added via writestr carries a 0o600 stamp in the archive.
zipfile never applies modes while extracting, so the difference is invisible from inside
Python; but anyone opening that archive with unzip gets a file nobody but the owner
can read
:

a.sh (added with writestr)           -> -rw-------
b.sh (external_attr set to 0o100755) -> -rwxr-xr-x
Enter fullscreen mode Exit fullscreen mode

The loss is not symmetric, then; it has a direction. A pipeline that packs with zipfile
and extracts with unzip produces 0600; one that packs with zip and extracts with
zipfile produces 0644. In both cases what the archive says and what is on disk
disagree, but the numbers differ — and which one you see depends on where in the pipeline
you stand.

Why tar does not lose it

"Archives do not carry modes" would be the wrong generalisation. Packing the same files
with tarfile and extracting them returned both the mode and the mtime intact. The
reason is concrete: chmod appears zero times in the zipfile module, four times in
tarfile, and that module has a chmod method of its own:

def chmod(self, tarinfo, targetpath):
    """Set file permissions of targetpath according to tarinfo.
    """
Enter fullscreen mode Exit fullscreen mode

On the tar side the real argument has never been about losing metadata but about how
much of it to give back
. tarfile has carried extraction filters since Python 3.12, and
in 3.14 the default filter became data; the documentation puts it this way: "Changed in
version 3.14: Set the default extraction filter to data, which disallows some dangerous
features such as links to absolute paths or paths outside of the destination." I ran the
three filters against three files with modes 0755, 0700 and 04755 — their names are
Turkish: acik.sh means "open", gizli.sh means "private".

Filter acik.sh gizli.sh setuid.sh
fully_trusted 0755 0700 04755
tar 0755 0700 0755
data 0755 0700 0755

The executable bit survives all three filters; setuid passes only through
fully_trusted. That table also says what the fix below has to imitate.

Three traps in giving the mode back

The first fix that comes to mind: extract, then apply what the archive says.

path = z.extract(info, target)
os.chmod(path, info.external_attr >> 16)   # DO NOT WRITE IT LIKE THIS
Enter fullscreen mode Exit fullscreen mode

It works on the happy path and blows up in three places. I tested all three with archives
produced by the real zip binary.

Archives that store no mode. Zeroing the field in the central directory record and
switching create_system to MS-DOS produces one — what a zip packed on Windows looks like
from the Unix side. Here external_attr >> 16 returns 0, and the line above drags the
file down to mode 0o0:

mode after the naive chmod: ---------- 0o0
read attempt: PermissionError Permission denied
Enter fullscreen mode Exit fullscreen mode

The line that tried to restore the mode has removed it entirely.

setuid. A zip entry can carry the setuid bit. I prepared an entry with mode 0o104755
and tried it: "apply whatever the archive says" made the file -rwsr-xr-x, while unzip
6.00 opening the same archive produced -rwxr-xr-x. The fix behaves more loosely than the
tool it is fixing.

Symlinks and directories. My own first version missed this third one, and it is the
expensive one. zipfile.extract does not create symlinks; it writes a plain file
containing the text of the link target. The entry's mode is 0o120755, so a guard that
merely asks "are there type bits?" lets it through and the file becomes executable. Here
are three tools against a real archive holding a 0700 directory, a symlink and a 0600
file:

Entry Stored unzip 6.00 plain extractall naive fix
real.txt 0o100644 -rw-r--r-- -rw-r--r-- -rw-r--r--
evil (link) 0o120755 lrwxr-xr-x -rw-r--r-- -rwxr-xr-x
gizli/ 0o40700 drwx------ drwxr-xr-x drwxr-xr-x
gizli/g.txt 0o100600 -rw------- -rw------- -rw-------

Two rows are bad at once. On the evil row the fix produces something worse than doing
nothing: an executable file carrying the text /etc/passwd. An archive produced on Linux
stamps that same link 0o120777, which comes out -rwxrwxrwx. On the gizli/ row,
skipping directories leaves the disk looser than unzip does: a folder that was 0700
inside the bundle becomes a 0755 anyone can walk into.

The version that works

Closing all three traps means doing on the zip side what tarfile's filters do: touch
only regular files and directories, drop the high bits, and leave directory modes to the
end — otherwise you cannot write into a 0700 folder.

import os, stat, zipfile

def zip_extract(archive, target):
    """Extract a zip and apply the Unix mode WRITTEN in the archive.
    Touches only regular files and directories; drops the high bits."""
    directories = []
    with zipfile.ZipFile(archive) as z:
        for info in z.infolist():
            path = z.extract(info, target)
            if info.create_system != 3:          # 3 = Unix; otherwise meaningless
                continue
            raw = info.external_attr >> 16
            kind = stat.S_IFMT(raw)
            mode = stat.S_IMODE(raw) & 0o777     # setuid/setgid/sticky dropped
            if kind == stat.S_IFDIR:
                directories.append((path, mode)) # directories last
            elif kind == stat.S_IFREG:
                os.chmod(path, mode)
            # symlink, fifo, device: zipfile writes these as plain files,
            # so their modes are not applied
    for path, mode in reversed(directories):
        os.chmod(path, mode)
    return target
Enter fullscreen mode Exit fullscreen mode

I ran it against five archives:

Archive Result
yap.sh + alt/veri.txt -rwxr-xr-x · drwxr-xr-x · -rw-r--r--
link + 0700 directory + 0600 file -rw-r--r-- · drwx------ · -rw-------
a.sh via writestr / b.sh stamped by hand -rw-r--r-- · -rwxr-xr-x
archive with no mode written -rw-r--r--
archive carrying setuid -rwxr-xr-x

The second row now lines up with unzip: the private folder stays private and the link
entry does not become executable. a.sh coming out 0644 instead of 0600 is deliberate
— the writestr stamp carries no file type bits, so the type check treats it as "never
written". One caveat: on the main branch that line has become 0o100600. Once that
version ships, the stamp will carry type bits and this helper will apply 0600 to those
archives. Still the right behaviour — but if you produce bundles with writestr, the day
you have to write the mode explicitly is approaching.

Three things the helper deliberately does not cover: ownership (unzip -X restores uid
and gid, while zipfile never reads that field), Windows (there os.chmod only flips the
read-only flag — "All other bits are ignored"), and speed, since one extra chmod per
entry turns into a number worth measuring on an archive with a hundred thousand entries.
And if you are extracting an untrusted archive as root, the answer is not this helper at
all: extract as an unprivileged user into a staging directory and move the result.

Where it hits in production

This loss hurts most in CI pipelines, because that is where you usually do not write the
archiving step yourself. GitHub's upload-artifact action says so in its own README under
"Permission Loss": "File permissions are not maintained during zipped artifact upload. All
directories will have 755 and all files will have 644." The recommended remedy is
familiar: "If you must preserve permissions, you can tar all of your files together
before artifact upload and upload that file directly with archive: false." Worth adding
that the archive: false input arrived in v7 — if your pipeline is pinned to anything
older, that upgrade comes first.

In my own blog's repository the action appears in exactly one place, the step where the
Lighthouse audit uploads its .lighthouseci/ reports. What travels there is JSON and HTML
reports, so it costs me nothing today. It will cost something the day the same pattern
carries a release bundle of bare files: the bundle downloads "successfully", every file is
present, and ./kur.sh does not run. The error message from a pipeline that breaks at the
download step will not point at the download either.

The cheapest control belongs right here: after extracting, assert that the file you are
about to call really is executable with os.access(path, os.X_OK) and stop loudly if it
is not. Three lines, and they turn a silent failure into a noisy one.

I had seen a similar split before, in the piece where pax pulled out of the same archive
the file tar had
swallowed
: there too
the archive was honest and the tool opening it was selective. The difference: there the
thing that went missing was the file itself, here the file arrives but a promise written
on it does not. The first is easy to notice; the second can sit in production for weeks.

A current note: Python 3.14 started honouring SOURCE_DATE_EPOCH when writing zips.
Running the same code under both versions with SOURCE_DATE_EPOCH=1000000000, 3.13.3
wrote the current moment into the archive and 3.14.3 wrote 2001-09-09 04:46:40 — local
time, that is. Zip's time-zone-free stamp haunts this corner too: on the current tip of
the 3.14 branch and on main that line calls time.gmtime instead of time.localtime,
so a newer 3.14 patch release gives 01:46:40 for the same command. It is a real win for
reproducible packaging, and it lands in the middle of the problem I chased in the piece
about packing the same commit
twice
. But nothing
changed on the mode side in that release: chmod still appears zero times.

Questions for your own pipeline

  • Who opens the bundle? If it is zipfile, assume the mode will not arrive; if it is unzip, you get whatever the archive says. There is no single behaviour called "extracting a zip".
  • Who writes the bundle? If you reach for writestr, you are stamping 0600 into the archive. Build the ZipInfo yourself and set external_attr explicitly.
  • Do you need the executable bit? If so, the shortest way to end the argument is to change format: tar gives back both the mode and an epoch-based mtime.
  • Is the archive trusted? If you wrote code that restores modes, touch only regular files and directories and mask the high bits. tarfile has filters for exactly this reason; on the zip side you write that filter yourself.

A file format storing a field does not mean the field will come back. The contract is not
written in the format, it is written in the default reader. Zip carries both the mode
and the clock carefully; zipfile puts both down, and does it silently, because 0644 is
a valid mode too: no error, no warning. Anyone going to the documentation finds nothing —
the word "permission" is not on that page. If the open PR under that fourteen-year-old
report ever merges, the silence ends; and on that day the question has to be asked from
the other side, because the call that returns 0644 today will return whatever the
archive says.

Official Sources

Top comments (0)