You Unpacked the Customer's Archive With tarfile and One File Landed Outside the Folder
Customers sent us their photos as one archive. A tar.gz, because their system made one. The service did the obvious thing. with tarfile.open(path) as tar: tar.extractall(upload_dir) A temporary folder per upload.
Customers sent us their photos
as one archive.
A tar.gz,
because their system made one.
The service did the obvious thing.
with tarfile.open(path) as tar:
tar.extractall(upload_dir)
A temporary folder per upload.
Read the images.
Delete the folder.
Tidy.
Then someone sent an archive
with a member called
../../app/templates/base.html
Python did
exactly what the archive said.
It joined the folder
and the name,
walked up two levels,
and wrote the file there.
Over ours.
An archive is not a bag of files.
It is a list of instructions.
Put this content
at this path.
Make this a link
to that location.
Give it these permissions.
Every one of those
was written by the sender.
The same mistake
has been made in every language.
A loop over zip entries
in Java,
new File(target, entry.getName()),
no check.
In 2018
it was common enough
to get a name.
Zip Slip.
The tarfile weakness
was reported against Python
in 2007,
and for years
the documentation
carried a warning
instead of a fix.
Python 3.12 added a filter argument.
tar.extractall(upload_dir, filter="data")
It refuses absolute paths,
refuses names that climb out,
refuses links that point outside,
and strips the dangerous permission bits.
From 3.14
that filter is the default.
Until every server you run
is on 3.14,
write it yourself.
Being explicit costs one argument,
and the code then means the same thing
on every version.
On any other language,
check every entry before you write it.
Resolve the full destination.
Confirm it still sits
inside the folder you chose.
Skip links entirely
unless you truly need them.
Treat the names
like any other user input.
Because they are.
Then make the blast smaller.
Unpack in a directory
the process can write to
and nothing else.
Not as the user
that owns your code.
And limit the total size
and the number of members
before you start.
Whenever your code
obeys a file
it did not write,
someone else is writing your code.
โ Serguey Asael Shinder
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.