Monday, January 6, 2014

Hacking through image: GIF turn

In one of my previous posts I described a way to hack through images. That time I showed how a valid BMP file could be a valid JS file as well, hiding Javascript operations. Today it's time to describe how this attack work with a more common web file format: .GIF. Ange commented on my previous post showing me out his great work on the topic. I recomend to have a look to his study (here). Following my quick 'n dirty python implementation on the technique.

The following HTML page wants to parse a GIF file and a JavaScript file
which happen to be the same file: 1.gif_malw.gif. Theoretically the file should
be or a valid GIF file or a valid JavaScript file. Could it be a valid javacript and a valid image file at the same time ? The answer should be NO. But properly forging the file the answer is YES, it is. Let's assume to have the following HTML page.

Browsing this file you'll find out this result:

As you can see, both tags (img and script) are succesfully executed. The Image tag is showing
the black GIF file and the script tag is doing its gret job by executing a
JavaScript (alert('test')). How is it possible ? The
following image show one detail about the dirty code who generates the beautiful GIF file.

This is not magic at all. This is just my implementation of the GIF
parsing bug many libraries have. The idea behind this python code is to
create a valid GIF header within \x2F\x2A (aka \*) and then close up the
end of the image through a \x2A\x2F (aka *\). Before injecting the payload you might
inject a simple expression like "=1;" or the most commonly used "=a;" in order to use all the GIF block as a variable. The
following image shows the first part of a forget GIF header to exploit
this weakness (click to enlarge).

After having injected the "padding" chars (in this case I call padding the " '=a;' characters", which are useful to JS interpreter) it's time to inject the real payload. The small script I've realized automizes this process and you might want to run it in a really easy way:

Run-it as: gif.py -i image.gif "alert(\"test\");"

Don't forget, you might want to use obfuscators to better hide your javascript like the following example: