Friday, March 27, 2009

PHP Anti-analysis Technique

I was looking through a PHP web attack toolkit yesterday and found one of the scripts was obfuscated in an attempt to prevent others from figuring out what the code does. In short, the obfuscation worked by decoded a long base64 encoded string, applying some modifications to each letter based on where it was, and then executing the final output (thru an eval command).

No problem, I thought. There are three options to decode this:

1. Figure out what the code is doing and write a translation program. Nah, too long.
2. Modify the source for PHP itself to print any eval statements to a file. Hmmmm...maybe, but not now.
3. Add a print statement to the obfuscated script to print out the unobfuscated code instead of eval'ing it. Yep...easy.

So I changed the eval statement to a print and ran the PHP code. Nothing.

After ensuring my PHP wasn't borked I decided something was going on and I needed to look at the code. After a few minutes, I found the following:
$file = __FILE__;
$file = file_get_contents($file);
$var8 = 0;
preg_match(base64_decode("LyhwcmludHxzcHJpbnR8ZWNobykv"), $file, $var8);

for (;$interator_1<$enc_str_len;) {
if (count($var8)) exit;
Note that the for loop is the loop to decode each character of the PHP code.

This is a nice little anti-analysis function. First, it grabs the contents of itself in the first two lines. Then, it initializes $var8 to 0. Next, it looks for a regular expression in the contents of the current file, setting $var8 to the number of occurences found. The regular expression is a base64 encoded string. What does it decode to?
So, its looking for any occurence of print, sprint or echo within the file. Then, in the decoding loop, if any occurences ($var8 > 0) are present the program exits. Simple technique to make analysis more difficult.

Of course, its pretty easy to bypass as well. :)

No comments: