This time, unusually - we are not going to look at a specific programming language but a Linux function - unzip
1 - that is for extracting files.
Why such topic?
Sometimes our website requires adding support of archives.
These can be zip
, rar
or tar
files.
Let's assume a hypothetical situation. We run a website where we can create galleries.
The user has the ability to upload photos to our server. It can be done individually - that is, one file at a time.
However, if there are more of these files, for example 100, the simplest solution from the usability perspective, would be to pack them into one zip file
and upload this one zip to our server.
On our side - this file is unpacked to a temporary directory using the unzip Linux command.
Then, all files with the .png extension are copied to the proper directories and added to the database. Then we clean the given directory.
But where is the danger?
Besides standard files, on linux there is also a thing called symlinks
2.
They are similar to Windows shortcuts.
So we create a .png
file, that doesn't have its own content, but only a reference to some other file.
For this purpose, we use the ln
command with the arguments:
ln -s /etc/passwd shortcut.png
In our case, we refer to /etc/passwd
which contains information about all accounts in a given system.
Now, if we want to display the contents of this file - we will see the contents of /etc/passswd
- because this is the file that symbolic link refers to.
When we have such file, we can add it to the zip archive.
zip archive.zip shortcut.png
If we create an archive using the zip command without any arguments, before it gets created, the command will check where all the symlinks lead to, and enclose designated files with their contents.
However, we want to create an archive with preserved links, so that they are resolved only on the server that we attack.
We do not want to send an archive containing containing our own data.
We must therefore use the --symlinks
argument.
zip --symlinks archive.zip shortcut.png
Now we send a malicious file to the server. There, it is unpacked to a temporary temp
directory using unzip.
unzip archive.zip -d temp
Now we copy all files with png extension to the server directory.
As you can expect, when the user will want to open this file - what the one will see is the contents of the /etc/passwd
file.
So how do you protect yourself against this attack?
The best approach is to use the unpacking modules available in most programming languages.
It is worth looking for an option to disable symbolic links.
In addition, before each operation on an extracted file, it is worth checking if it is a symlink.