This article is from the author Tang Qingsong in GitChat to share “Common Vulnerabilities of Web security PHP code review”, “read the article” to see what people have done with the author.

preface

To do a good job, he must sharpen his tools. It is also necessary to choose the tools before we do the code audit. Let me introduce you to two useful tools for code auditing.

I. Introduction to audit tools

PHP code audit system – RIPS

Function is introduced

RIPS is a PHP based development for PHP code security audit software.

In addition, it is also open source software, developed by foreign security researcher Johannes Dahse, the program is only 450KB, the latest version of 0.55 can be downloaded.

I have read its source code before writing this article. Its biggest highlight is that it calls the PHP built-in parser interface token_get_all.

In addition, Parser was used for grammar analysis to realize variable and function tracking across files. The scanning results showed the formation of vulnerabilities and variable transfer process intuitively, and the false positive rate was very low.

RIPS can find SQL injection, XSS cross-site, file inclusion, code execution, file reading, and many other vulnerabilities, and supports many styles of code highlighting. Interestingly, it also supports automatic generation of exploits.

Installation method

Download address: https://jaist.dl.sourceforge.net/project/rips-scanner/rips-0.55.zip.

Unzip to any PHP runtime directory

Enter the corresponding url in the browser. You can see from the picture below that there is a path to fill in the project file path you want to analyze. Click Scan.

Print screen

Seay source code audit system

Function is introduced

These are some of the features of the first version of Seay, now in version 2.1.

  1. Dumb automatic audit.

  2. Support PHP code debugging.

  3. Function/variable location.

  4. Generate audit reports.

  5. Customize audit rules.

  6. Mysql database management.

  7. Black box sensitive information leakage one-click audit.

  8. Supports regular match debugging.

  9. Edit and save the file.

  10. POST Data packet submission.

Installation method

The installation environment requires.net2.0 or above version of the environment to run, download the installation package click next to install, very simple.

The installation package download address: http://enkj.jb51.net:81/201408/tools/Seayydmsjxt (jb51.net). Rar

A screenshot of the operation interface

Second, code audit actual combat

After running the two audit tools installed just now, we can find that many hidden vulnerabilities will be analyzed. Now let’s look at the causes of SQL injection, XSS and CSRF, and analyze how to audit the code through the reasons.

SQL injection

SQL injection vulnerability has been a web system vulnerability accounted for a very large proportion of a vulnerability, let’s take a look at several ways of SQL injection.

SQL injection vulnerability classification

It can be divided into two types: conventional injection and wide-byte injection.

The normal injection method, usually without any filtering, places the parameters directly into the SQL statement, as shown in the following figure.

It’s easy to see that developers do some filtering these days, such as using addslashes(), but filtering doesn’t always work.

Encoding injection mode

Wide-byte injection, what’s going on here?

Programmers would not normally write code like this in the real world. They would normally use filtering functions such as addslashes() to filter parameters passed from the Web. But there’s a saying, “The devil climbs a foot higher,” and let’s see how the white hat breaks through. Setting character_set_client= GBK causes a coding bug when using PHP to connect to MySQL. The e caption we knew that addslashes() translated the 1 ‘into 1\’ and the e caption we submitted 1%df ‘was 1\’, so the e caption we typed 1%df ‘or 1=1%23 was translated into 1\’ or 1=1# ‘.

Simply % % df ‘escape will be filtered function for df \’, df = % % % df \ ‘5 c % 27 when using GBK code think df % % 5 c is a wide byte df 5 c % % % 27 = Cui’, this will produce injection.

So how do you defend against this wide byte? I encourage you to use UTF8 encoding as much as possible. If conversion is difficult, the safest way is to use PDO preprocessing. The main way to exploit this vulnerability is to check whether GBK is used, search for guanJianc CHARACTER_SET_client = GBK and mysQL_set_chatset (‘ GBK ‘).

Second URldecode injection, this way is also due to the use of urldecode caused by improper vulnerabilities.

We just learned that the addslashes() function prevents injection by adding backslashes before (‘), (“), and () to escape.

So let’s say we have GPC enabled, and we submit a parameter, /test.php? Uid =1%2527; uid=1%2527; %25;

If urldecode is used, %27 will be decoded into single quotes (‘), and uid=1 ‘will be the final result.

We now know that the original is caused by URldecode, we can find the secondary URL vulnerability by searching urldecode and Rawurldecode in the editor.

Vulnerability types can be divided into three types:

  1. Can show

    An attacker can obtain the desired content directly from the current interface content.

  2. An error

    The database query results are not displayed on the page, but the application prints the database error message to the page.

    So an attacker can construct a database error statement to get what they want from the error message, so I recommend setting the database class to not throw error messages.

  3. The blinds

    Database query results cannot be obtained from visual pages Attackers obtain the desired content by using database logic or delaying the execution of the database library.

SQL injection vulnerability mining method

In view of the method of exploiting vulnerabilities mentioned above, the following mining methods are summarized:

  1. Parameter receiving position, check whether there is no filter directly use _POST, $_COOKIE parameters.

  2. SQL statement check: Searches key points of SQL statements, such as select UPDATE INSERT, and checks whether SQL statement parameters can be controlled.

  3. Wide byte injection, if the site uses GBK encoding case, search for GUANJIANc CHARACTER_SET_client = GBK and mysQL_set_chatset (‘ GBK ‘).

  4. Secondary URldecode injection. In rare cases, GPC can find secondary URL vulnerabilities by searching urldecode and Rawurldecode in the editor.

SQL injection vulnerability prevention method

There are many SQL injection vulnerabilities, but it is quite simple to guard against. Here are some filtering functions and classes:

  • GPC/Rutime Magic quotes

  • Filter functions and classes

    • addslashes

    • mysql_real_escape_string

    • intval

  • The PDO pretreatment

XSS cross-site

preface

XSS is also called CSS (Cross Site Script), cross-site scripting attacks. It refers to the malicious attacker to insert malicious HTML code into the Web page, when the user browses the page, the HTML code embedded in the Web will be executed, so as to achieve the special purpose of malicious.

XSS is a passive attack, and many people call it harmful because it is passive and difficult to exploit. In the era of WEB2.0, the emphasis is on interaction, which greatly increases the opportunities for users to input information. In this case, we, as developers, should be vigilant when developing.

XSS vulnerability classification

  1. Reflex type, harm is small, general

    The principle of reflective XSS: it is to send the URL with malicious script code parameters to others. When the URL address is opened, the specific code parameters will be analyzed by HTML and executed, so that the COOIKE of the user can be obtained, and then the stolen number can be logged in. For example, hack A constructs the URL to change the password and changes the password to 123, but the password can only be changed by the login party B. When the login party B clicks the URL constructed by A, the password will be directly changed without knowing it.

    It is nonpersistent and must be triggered by the user clicking on a link with a specific parameter.

  2. Storage type, great harm, long impact time

    Stored XSS, assuming you open a normal article page with comments. At this point you go to comment, type in some JavaScript code in the text box, submit it, refresh the page and find that the submitted code has been returned intact and executed.

    At this point you might think, I’m going to write some JavaScript code to get the cookie information and send it to my own server via Ajax. Once you’ve built the code you send the link to another friend, or the administrator of the site, they open the JavaScript and the code executes, your server receives the sessionID, and you get the user privileges.

3. Dom type, special type

Dom XSS is an XSS vulnerability caused by DOM operations performed by JavaScript, as shown in the following figure. As you can see, the HTML escaped code is returned to the HTML and manipulated by JavaScript as a DOM element. So when I type in? XSS vulnerability still exists when name=.

XSS vulnerability mining method

According to the above characteristics, several mining methods can be summarized and analyzed:

  1. Data receiving location, check whether _POST and $_COOKIE are escaped.

  2. The common reflection TYPE XSS search finds similar locations more often.

  3. While the storage type in the article, comments appear more.

XSS vulnerability prevention method

  1. There are two ways to escape HTML entities: at the entry and at the exit. I recommend escaping at the entry, in case the exit location is forgotten when it is retrieved. If it has been escaped at the entry, the exit location does not need to be escaped again.

  2. In rich text editors, we often use attributes of elements, such as onError in the image above, so we need to create a blacklist and whitelist for the attributes of the element.

  3. HttpOnly, even with XSS vulnerabilities, can greatly reduce the harm.

CSRF vulnerabilities

This section describes CSRF vulnerabilities

Cross-site Request Forgery (CSRF), commonly abbreviated as CSRF or XSRF, is a malicious use of a website. It sounds like cross-site scripting (XSS), but it’s very different from XSS, which leverages trusted users within the site.

CSRF exploits trusted web sites by masquerading requests from trusted users. Compared to XSS attacks, CSRF attacks tend to be less popular (and therefore have relatively few resources to defend against them) and harder to defend against, so they are considered more dangerous than XSS attacks.

CSRF is mainly used to do unauthorized operations, and CSRF has never been noticed, so many programs do not have relevant safeguards.

CSRF case

Let’s take a look at the code below. When the form is accessed, the user logs out. Let’s say there’s a transfer form, and all I have to do is fill in the username and the amount, so if I construct the URL in advance, send it to the victim, and when I click on it, the money gets transferred.

Or I could put the URL in my web page with

CSRF vulnerability mining method

Through the above description, we know the original vulnerability, so when we audit, we can check whether the processing form has the following judgment.

  1. Whether there is an authentication token.

  2. Whether there is a picture verification code.

  3. Check whether there is refe information.

If none of the three are present, there is a CSRF vulnerability. CSRF is not limited to GET requests, but also to POST requests.

CSRF vulnerability prevention method

  1. Image verification code, this must be known, but the user experience is not good, we can look at the following some processing methods.

  2. Token authentication.

    The token authentication method is as follows: Each time you visit the form page, an unpredictable token is generated and stored in the server session, and another token is stored in the page. When submitting the form, you need to bring this token with you, and verify whether the token is valid before receiving the form.

  3. Referer information verification

    In most cases, the browser visits an address that contains the Referer information in the header, which stores where the request was originated.

    If the HTTP header contains Referer, we can distinguish between in-domain and cross-site requests, so we can also defend against CSRF attacks by determining whether the request in question is in-domain.

    When verifying the Referer, there are several points to pay attention to. If the Referer is judged to contain *.xxx.com, there will be a possibility of circumvention if there is a vulnerability in the subdomain name.

    If the judgment condition is whether the Referer contains the character ‘xxx.com’, it is also possible for the attacker to create a xxx.com folder in his directory. If you can determine the most appropriate is to directly determine whether is equal to the current domain name.

Three, conventional loopholes prevention methods

Taint PHP security extension

Function is introduced

Taint can be used to detect hidden vulnerabilities in XSS code, SQL injection, Shell injection, etc., which would be very difficult to detect with static analysis tools.

Installation method

  • Download taint: http://pecl.php.net/package/taint

  • configuration

/usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config make && make install

  • More detail you can refer to: http://www.cnblogs.com/linzhenjie/p/5485474.html

Application scenarios

It is difficult for the development team to require everyone to be very secure, but the taint installed in the development environment is particularly suitable, as soon as you see the warning message usually go back to change.

ngx_lua_waf

Function is introduced

  1. Prevent SQL injection, local include, partial overflow, Fuzzing testing, XSS, SSRF and other Web attacks.

  2. Prevent leakage of files such as SVN or backup.

  3. Protect against stress testing tools like ApacheBench.

  4. Block common scanning hacker tools, scanners.

  5. Mask abnormal network requests.

  6. Block image attachment class directory PHP execution permission.

  7. Prevent Webshell uploads.

Installation method

  • Installation dependencies: Luajit, ngx_devel_kit, and nginx_lua_module

  • Install nginx and ngx_luA_waf

  • Add configuration to HTTP in nginx.conf

  • Detailed Installation Documents

rendering

conclusion

The section on code audit handling common vulnerabilities picks three types, and there are others that I can’t cover all at once. In addition to checking the parameters like just now, there is also a logical vulnerability audit. Next time if there is time, I will do a logical vulnerability audit share.

“Read the transcript” for the Chat transcript