It’s long time I don’t write on my own blog (more then two months) and if you look at the history bar on your right you will probably figure out  I am slowing down my blog posts a bit if compared to the past years. This happens due the amount of work my security team and I are involved on.
Many different and really important facts happened during the past months, from astonishing NSA revelations to huge BUGs and new Malware kit ready to be purchased. Even if there would be lots to say about all these  I will not dig into them. 
Since “things” went public today I want to share a little and dirty python script which embeds javascript code into bmp images letting those images still valid images, ready to be processed from your favorite browser. 
The following  HTML page wants to parse a bmp file and a javascript file which happen to be the same file: 2.bmp. Theoretically the file should be or a bitmap file or a javascript file. Could it be a javacript and an image file at the same time ? The answer should be NO. It couldn’t. But let’s see what we have.

 Executing this file you’ll find out this result:
As you can see, both tags succesfully executed. The Image tag is showing the red Bitmap file and the script tag is doing its job by executing a JavaScript. How is it possible ? How did you write such a file ? The following images show more details about the dirty code who generates these beautiful bitmap files.
The creation procedure.

The  substitution procedure.
This is not magic at all. This is just my implementation of the BMP parsing bug many libraries have. The idea behind this python code is to create a valid BMP header within \x2F\x2A (aka \*) and then close up the end of the image through a \x2A\x2F (aka *\). To be a valid JavaScript file, you need to use the –not used– header (\x42\x4D) as a variable and/or as a part of the code. This is why before the payload you might inject a simple expression like “=1;” or more commonly used “=a;” The following image shows the first part of a forget BMP header to exploit this eakness.
BTW if you want to downloade the entire code, grab it  here (pasteBIN). 
Run-it as: bmp.py -i image.bmp “alert(\”test\”);”
Running Example
Don’t forget, you might want to use obfuscators to better hide your javascript like the following example:
python bmp.py -i 2.bmp “var _0x9c4c=[\”\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21\”,\”\x0A\”,\”\x4F\x4B\”];var a=_0x9c4c[0];function MsgBox(_0xccb4x3){alert(_0xccb4x3+_0x9c4c[1]+a);} ;MsgBox(_0x9c4c[2]);”
Running a more complex Example
Enjoy your new hackish tool !

3 thoughts on “ Hacking through images ”

Comments are closed.