My weblog about all things that interest me (and hopefully you): viruses, programming in general, death & black metal, certain web sites... Well, it could be anything.

Friday, January 21, 2005

Obfuscating PHP code

In a magazine of 29A i saw SPTH writing some tutorial on randomizing PHP code using routines for manipulating strings. I've done something similar, yet I use the built-in parser for PHP code that is included in the Zend engine. Here's a quick example of obfuscating PHP code using the tokenizer functions from the Zend engine:
<?

$source = join("",@file(__FILE__));
// Pass 1:
// - strip all comments
// - strip needless whitespace
$tokens = token_get_all($source);
foreach ($tokens as $token) {
if (is_string($token)) {
$pass1 .= $token;
} else {
list ($id,$text) = $token;
if ($id != T_COMMENT && $id != T_ML_COMMENT) {
if ($id == T_WHITESPACE) {
$text = preg_replace("/\s+/"," ",$text);
}
$pass1 .= $text;
}
}
}

// Pass 2:
// - randomize variables
// - insert random whitespace and comments
$tokens = token_get_all($pass1);
foreach ($tokens as $token) {
if (is_string($token)) {
$pass2 .= $token;
} else {
list($id, $text) = $token;
switch($id) {
case T_WHITESPACE:
$pass2 .= $text .
str_repeat(" ",rand(0,5)) .
"/*" .
str_repeat(" ",rand(0,5)) .
substr(md5(uniqid("")),0,rand(1,30)) .
str_repeat(" ",rand(0,5)) .
"*/" .
str_repeat(" ",rand(0,5));
break;
case T_VARIABLE :
if (!isset($vars[$text])) {
$vars[$text] = '$' .
chr(rand(0,1) ?
rand(65,90) :
rand(97,122)) .
substr(md5(uniqid("")),0,rand(5,10));
}
$text = $vars[$text];
default:
$pass2 .= $text;
}
}
}
print $pass2;
?>
References:
PHP Virus Writing Guide
Generic Polymorphism

No comments: