From:http://www.abysssec.com/blog/2010/03/attention-in-php-source-code-auditing/
Hi .
Today , I decide talk about some of my experience about methods of vulnerability discovery techniques through source code auditing .
if you remember , around 1 years ago , i wrote This article :
立即学习“PHP免费学习笔记(深入)”;
20 ways to php Source code fuzzing (Auditing)
some time ago “Stefan Esser” made The Poster on the PHP Security . I’m going to have a brief description about most them with my experience in PHP Source code Auditing :
Most PHP Vulnerability :
1-Cross Site Scripting (XSS)
2-Cross Site Request Forgery (CSRF)
3-SQL Injection
4-Insecure Session Handling
5-Session Fixation
6-Information Disclosure
7-Header Injection
8-Insecure Configuration
9-Weak randomness
(for more information about how to find this issue in your source code , read my article :
http://www.abysssec.com/blog/2009/03/php_fuzz_audit/
And another describe [ Finding vulnerabilities in PHP scripts FULL ( with examples )]:
http://www.milw0rm.com/papers/381
These problem due to inaccuracy in ((In summary):
I ? Secure Input Handling :
accept input from users without carefully to what is injected.
II ? Sanitising :
Sanitizing functions can be used to “repair” user input, according to the application‘s restrictions (e.g. specific datatypes, maximum length) instead of rejecting potentially dangerous input entirely. In general, the use of sanitizing functions is not encouraged, because certain kinds and combinations of sanitizing filters may have security implications of their own. In addition, the automatic correction of typos could render the input syntactically or semantically incorrect.
for example :
III- Escaping :
There are several different kinds of escaping:
? The backslash prefix “” defines a meta character within strings. For Example: is a tab
space,
is a newline character, … This can be of particular interest for functions where the newline character has a special purpose, e.g. header(). Within regular expressions the backslash is used to escape special characters, such as . or *, which is relevant for all functions handling regular expressions.
? HTML encoding translates characters normally interpreted by the web browser as HTML into their encoded equivalents ? e.g. is > or > or >. HTML encoding should be used for output handling, where user input should be reflected in HTML without injecting code. (See also: htmlentities())
? URL encoding makes sure, that every character
not allowed within URLs, according to RFC 1738, is properly encoded. E.g. space converts to + or %20 and
IV ? Configuration :
Programming errors, including logic program.
well , we know there are 4 points that can help us in the process :
1 ? Our PHP inputs Points :[we need to find them and all functions and variables , that these have been assigned to them .]
input Point in PHP.Programing are :
$_SERVER
$_GET
$_POST
$_COOKIE
$_REQUEST
$_FILES
$_ENV
$_HTTP_COOKIE_VARS
$_HTTP_ENV_VARS
$_HTTP_GET_VARS
$_HTTP_POST_FILES
$_HTTP_POST_VARS
$_HTTP_SERVER_VARS
Very good , the second point : our problem begine here . we can’t find Problem in source code like the past . Because Programmers use the limitation function . for Example , wherever you see the fllowing functions that contol input variable , possibly as many attacks are carried out . so you have two solutions : find problem in logic of code or find PHP bug in PHP CORE !
A) Escaping and Encoding Functions :
A-1 (XSS dies = 90% The direct transition is a dream) :
? htmlspecialchars() , Escapes the characters & as HTML entities to protect the application against XSS. The correct character set and the mode : ENT_QUOTES should be used.
123 登录后复制 | <?phpecho "Hello " . htmlspecialchars( $_GET['name'], ENT_QUOTES);?> 登录后复制 |
? htmlentities() , Applies HTML entity encoding to all applicable characters to protect the application against XSS. The correct character set and the mode ENT_QUOTES should be used.
123 登录后复制 | <?phpecho "Hello " . htmlentities( $_GET['name'], ENT_QUOTES);?> 登录后复制 |
( htmlentities() bypass in special case [utf7] : http://pstgroup.blogspot.com/2007/11/bypass-htmlentities.html )
? urlencode() , Applies URL encoding as seen in the query part of a URL.
123 登录后复制 | <?php$url = "http://www.example.com/" . "index.php?param=" . urlencode($_GET['pa']);?> 登录后复制 |
A-2 : (SQL injection dies = 90% The direct transition is a dream) :
? addslashes() , Applies a simple backslash escaping. The input string is assumed to be single-byte encoded. addslashes() should not be used to protect against SQL injections, since most database systems operate with multi-byte encoded strings, such as UTF-8.
? addcslashes() , Applies backslash escaping. This can be used to prepare strings for use in a JavaScript string context. However, protection against HTML tag injection is not possible with this function.
(bypass addslashes() in special case : http://sirdarckcat.blogspot.com/2009/10/couple-of-unicode-issues-on-php-and.html)
? mysql_real_escape_string(), Escapes a string for use with mysql_query(). The character set of the current MySQL connection is taken into account, so it is safe to operate on multi-byte encoded strings.
Applications implementing string escaping as protection against SQL injection attacks should use this function.
123 登录后复制 | <?php$sql = "SELECT * FROM user WHERE" . " login='" . mysql_real_escape_string( $_GET['login'], $db) . "'";?> 登录后复制 |
A-3 : (XSS , SQl Inject = 100% The direct transition is a dream) :
? preg_quote() , Should be used to escape user input to be inserted into regular expressions. This way the regular expression is safeguarded from semantic manipulations.
Fix code :
123 登录后复制 | <?php$repl = preg_replace('/^' . preg_quote($_GET['part'], '/'). '-[0-9]{1,4}/', '', $str);?>登录后复制 |
issue Code [Command Execute] :
1234 登录后复制 | <?php$h = $_GET['h'];echo preg_replace("/test/e",$h,"jutst test");?>登录后复制 |
It works like this: http://site.com/test.php?h=phpinfo()
? escapeshellarg() , Escapes a single argument of a shell command. In order to prevent shell code injection, single quotes in user input is being escaped and the whole string enclosed in single quotes.
123 登录后复制 | <?phpsystem('resize /tmp/image.jpg' . escapeshellarg($_GET['w']).' '. escapeshellarg($_GET['h']));?>登录后复制 |
? escapeshellcmd() , Escapes all meta characters of a shell command in a way that no additional shell commands can be injected. If necessary, arguments should be enclosed in quotes.
123 登录后复制 | <?phpsystem(escapeshellcmd( 'resize /tmp/image.jpg "' . $_GET['w']) . '" "' . $_GET['h']) . '"'));?> 登录后复制 |
B- CType Extension :
By default, PHP comes with activated CType extension. Each of the following functions checks if all characters of a string fall under the described group of characters:
? ctype_alnum()alphanumeric characters ? A-Z, a-z, 0-9
? ctype_alpha()alphabetic characters ? A-Z, a-z
? ctype_cntrl() control characters ? e.g. tab, line feed
? ctype_digit()numerical characters ? 0-9
? ctype_graph()characters creating visible output e.g. no whitespace
? ctype_lower()lowercase letters ? a-z
? ctype_print()printable characters
? ctype_punct()punctuation characters ? printable characters, but not digits, letters or whitespace, e.g. .,!?:;*&$
? ctype_space()whitespace characters ? e.g. newline, tab
? ctype_upper()uppercase characters ? A-Z
? ctype_xdigit() hexadecimal digits ? 0-9, a-f, A-F
12345 登录后复制 | <?phpif (!ctype_print($_GET['var'])) {die("User input contains ". "non-printable characters");}?>登录后复制 |
C ? Filter Extension ? ext/filter
Starting with PHP 5.2.0 the filter extension has provided a simple API for input validation and input filtering.
? filter_input()Retrieves the value of any GET, POST, COOKIE, ENV or SERVER variable and applies the specified filter.
123 登录后复制 | <?php$url = filter_input(INPUT_GET, 'url', FILTER_URL);?> 登录后复制 |
? filter_var()Filters a variable with the specified filter.
123 登录后复制 | <?php$url = filter_var($var, FILTER_URL);?> 登录后复制 |
List of Filters :
Validation Filters
? FILTER_VALIDATE_INTChecks whether the input is an integer numeric value.
? FILTER_VALIDATE_BOOLEANChecks whether the input is a boolean value.
? FILTER_VALIDATE_FLOATChecks whether the input is a floating point number.
? FILTER_VALIDATE_REGEXPChecks the input against a regular expression.
? FILTER_VALIDATE_URLChecks whether the input is a URL.
? FILTER_VALIDATE_EMAILChecks whether the input is a valid email address.
? FILTER_VALIDATE_IPChecks whether the input is a valid IPv4 or IPv6.
Sanitising Filters
? FILTER_SANITIZE_STRING / FILTER_SANITIZE_STRIPPEDStrips and HTML-encodes characters according to flags and applies strip_tags().
? FILTER_SANITIZE_ENCODEDApplies URL encoding.
? FILTER_SANITIZE_SPECIAL_CHARSEncodes ‘ ” & and optionally all characters > chr(127) into numeric HTML entities.
? FILTER_SANITIZE_EMAILRemoves all characters not commonly used in an email address.
? FILTER_SANITIZE_URLRemoves all characters not allowed in URLs.
? FILTER_SANITIZE_NUMBER_INTRemoves all characters except digits and + -.
? FILTER_SANITIZE_NUMBER_FLOATRemoves all characters not allowed in floating point numbers.
? FILTER_SANITIZE_MAGIC_QUOTESApplies addslashes().
Other Filters
? FILTER_UNSAFE_RAWIs a dummy filter.
? FILTER_CALLBACKCalls a userspace callback function defining the filter.
D) HTTP Header Output
HTTP headers can be set using the header() function. User input should always be checked before being passed to header(), otherwise a number of security issues become relevant. Newline characters should never be used with header() in order to prevent HTTP header injections. Injected headers can be used for XSS and HTTP response splitting attacks, too. In general, user input should be handled in a context-sensitive manner.
Dynamic content within parameters to Location
or Set-Cookie headers should be escaped by urlencode().
For other HTTP header parameters, unintended context changes must be prevented as well; e.g. a semicolon separates several parameters within Content-Type.
1234 登录后复制 | <?phpif (strpbrk($_GET['type'], ";/
")) die('invalid characters');header("Content-Type: text/" . $_GET['type'] . "; charset=utf-8;");?>登录后复制 |
Applications should not allow arbitrary HTTP Location redirects, since these can be used for phishing attacks. In addition, open redirects can have a negative impact on the cross domain policy infrastructure of Adobe‘s Flash Player.
E)Secure File Handling:
? Detect and replace NULL bytes:
12345 登录后复制 | <?phpif (strpos($_GET["f"], " |