Detailed introduction to PHP code review_PHP tutorial

WBOY
Release: 2016-07-21 15:06:18
Original
1424 people have browsed it

Overview
Code review is a systematic inspection of the application source code. Its purpose is to find and fix some loopholes or program logic errors that exist in the application during the development phase, and to avoid illegal use of program vulnerabilities that bring unnecessary risks to the enterprise
Code review is not simply checking the code, reviewing the code The reason is to ensure that the code is secure enough to protect information and resources, so it is very important to be familiar with the business process of the entire application to control potential risks.
Reviewers can interview developers using questions like the ones below to collect application information.

What type of sensitive information is contained in the application, and how does the application protect this information?
Does the application provide services internally or externally? Who will use it, and who will use it? Are they all trusted users?
Where is the application deployed?
How important is the application to the enterprise?

The best way is to make a checklist and let developers fill it out. The Checklist can more intuitively reflect the application information and the coding security made by the developer. It should cover modules that may have serious vulnerabilities, such as: data verification, identity authentication, session management, authorization, encryption, error handling, logging, security Configuration, network architecture.

Input verification and output display
The main reason for most vulnerabilities is that the input data has not been securely verified or the output data has not been securely processed, which is relatively strict. The data verification method is: Exactly match the data
Accept the data from the whitelist
Reject the data from the blacklist
Encode the data that matches the blacklist

The list of variables that can be entered by the user in PHP is as follows:
$_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
We should check these input variables

Command Injection
Security Threat
Command injection attack is to change the dynamically generated content of a web page by entering HTML code into an input mechanism (such as a form field that lacks valid validation restrictions). This could allow malicious commands to take over users' computers and their networks. PHP can use the following functions to execute system commands: system, exec, passthru, ``, shell_exec, popen, proc_open, pcntl_exec. We search these functions in all program files to determine whether the parameters of the function are Will change due to external submission, check whether these parameters have been safely processed.
Code Example
Example 1:

Copy code The code is as follows:

/ /ex1.php
$dir = $_GET["dir"];
if (isset($dir))
{
echo "
" ;<br>system("ls -al".$dir);<br>echo "
";
}
?>

We submit
Copy code The code is as follows:

http:// localhost/ex1.php?dir=| cat /etc/passwd

After submission, the command becomes
Copy code The code is as follows:

system(" ls -al | cat /etc/passwd");


Prevention methods
1. Try not to execute external commands
2. Use custom functions or function libraries to replace the functions of external commands
3. Use escapeshellarg function to process command parameters
4. Use safe_mode_exec_dir to specify the path of the executable file
The esacpeshellarg function will escape any characters that cause the end of parameters or commands, single quotes "'", Replace with "'", double quotes """ with """, replace semicolon ";" with ";", use safe_mode_exec_dir to specify the path of the executable file, you can put the commands you will use in this path in advance Inside.

Copy code The code is as follows:

safe_mode = On
safe_mode_exec_di r= /usr/local/php/bin/

Cross Site Scripting Threat (Cross Site Scripting)
Security Threat
Cross Site Script (XSS), Cross Site Scripting Threat. The attacker takes advantage of the application's dynamic data display function to embed malicious code in the html page. When the user browses the page, these malicious codes embedded in html will be executed by
, and the user's browser will be controlled by the attacker, thereby achieving the attacker's special purpose. Output functions are often used: echo, print, printf, vprintf, <%=$test%>

Cross-site scripting attacks have the following three attack forms:
(1) Reflected cross-site scripting attacks
The attacker will use social engineering means to send a URL connection to the user Open, when the user opens the page, the browser will execute the malicious script embedded in the page.
(2) Stored cross-site scripting attack
The attacker uses the data entry or modification function provided by the web application to store the data in the server or user cookie. When other users browse the page that displays the data, The browser will execute the malicious script embedded in the page. All viewers are vulnerable.
(3) DOM cross-site attack

Since a piece of JS is defined in the html page, a piece of html code is displayed based on the user's input. The attacker can insert a piece of malicious script during input, and the final display , malicious scripts will be executed. The difference between DOM cross-site attacks and the above two cross-site attacks is that DOM cross-site attacks are the output of pure page scripts and can only be defended by using JAVASCRIPT in a standardized manner.

Malicious attackers can use cross-site scripting attacks to:
(1) Steal user cookies and log in with fake user identities.
(2) Force the viewer to perform a certain page operation and initiate a request to the server as a user to achieve the purpose of attack.
(3) Combined with browser vulnerabilities, download virus Trojans to the browser’s computer for execution.
(4) Derived URL jump vulnerability.
(5) Let the phishing page appear on the official website.
(6) Worm attack
Code sample
Directly displaying "user controllable data" on the html page will directly lead to cross-site scripting threats.

Copy code The code is as follows:

echo “$newsname ”;
echo “$gifname”;
echo “”;
echo “”. htmlentities($context).””;
?>

These types of The display method may cause the user's browser to execute the "user-controllable data" as a JS/VBS script, or the page elements may be controlled by the page HTML code inserted by the "user-controllable data", thus causing an attack.
Solution
a) Before displaying "user controllable data" in HTML, htmlescape should be performed.
Copy code The code is as follows:

htmlspecialchars($outputString,ENT_QUOTES);

HTML escaping should be done according to the following list:
Copy code The code is as follows:

& --> ; &
< --> <
> --> >
" --> "
' --> '

b) The "user controllable data" output in javascript needs to be escaped with javascript escape.
Characters that need to be escaped include:
Copy code The code is as follows:

/ --> /
' --> '
" --> "
--> \

c) Perform rich text security filtering for "user-controllable data" output to rich text (when users are allowed to output HTML) to prevent the existence of scripted script code in the rich text editor.
SQL Injection

Security Threats
When an application splices user input into SQL statements and submits them together to the database for execution, SQL injection threats will occur. Since the user's input is also part of the SQL statement, attackers can use this controllable content to inject their own defined statements, change the SQL statement execution logic, and let the database execute any instructions they need. By controlling some SQL statements, the attacker can query any data he needs in the database. Using some characteristics of the database, he can directly obtain the system permissions of the database server. Originally, SQL injection attacks require the attacker to have a good understanding of SQL statements, so there are certain requirements for the attacker's skills. However, a few years ago, a large number of SQL injection exploitation tools appeared, which allowed any attacker to achieve the attack effect with just a few clicks of the mouse. This greatly increased the threat of SQL injection.

General steps of SQL injection attack:
1. Attacker visits a site with SQL injection vulnerability and looks for injection point
2. Attacker Construct an injection statement, and combine the injection statement with the SQL statement in the program to generate a new SQL statement
3. The new SQL statement is submitted to the database for processing
4. The database executes the new SQL statement, triggering SQL injection Attack



Code example
Insufficient input checking causes the SQL statement to execute illegal data submitted by the user as part of the statement.
Example:

Copy code The code is as follows:

$id=$_GET[' id'];
$name=$_GET['name'];
$sql="select * from news where `id`=$id and `username`='$name' ";
?>

Solution
a) Security configuration and encoding method, PHP configuration options are specified in the php.ini file. The following configuration methods can enhance the security of PHP and protect applications from SQL injection attacks.
1) safe_mode=onPHP will check whether the owner of the current script matches the owner of the file to be operated through the file function or its directory. If the owner of the current script does not match the owner of the file operation, Illegal operation
2) magic_quotes_gpc=on / off, if this option is activated, any single quotes, double quotes, backslashes and null characters contained in the request parameters will be automatically escaped with a backslash.
3) magic_quotes_sybase=on/off, if the option is disabled, PHP will escape all single quotes with a single quote.
Verify numeric variables
$id=(int)$id;
Note: PHP6 has deleted the magic quotes option

b) Use preprocessing to execute the SQL statement and bind all variables passed in the SQL statement. In this way, the variables spliced ​​in by the user, no matter what the content is, will be regarded as the value replaced by the substitution symbol "?", and the database will not
parse the data spliced ​​in by the malicious user as part of the SQL statement. . Example:

Copy code The code is as follows:

$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare( $stmt, 'SELECT District FROM City WHERE Name=?'))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $city);
/ * execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);
/* fetch value */
mysqli_stmt_fetch( $stmt);
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);

File upload threat (File Upload)
Security Threat
PHP file upload vulnerability mainly lies in the attack caused by not handling file variables when verifying the file type, resulting in the program judgment logic being bypassed , the attacker uploads the script file to be parsed by the server, thereby obtaining the SHELL or the
file is copied arbitrarily during uploading, or even uploads the script Trojan to the web server to directly control the web server.
Code example
Code that handles user upload file requests. This code does not filter file extensions.
Copy code The code is as follows:

        // oldUpload.php 
    if(isset($upload)  &&  $myfile  !=  "none“  &&  check($myfile_name))  { 
    copy($myfile, "/var/www/upload/".$myfile_name); 
    echo "文件".$file_name."上传成功!点击继续上传"; 
    exit; 
    } 
    //checkUpload.php 
    $DeniedExtensions=array('html','htm','php','php2','php3','php4','php5','ph 
    tml','pwml','inc','asp','aspx','ascx','jsp','cfm','cfc','pl','bat','exe',' 
    com','dll','vbs','js','reg','cgi','htaccess','asis') ; 
    if($checkUpload($_FILE[‘myfile'][name],  $DeniedExtensions)){copy($_FILE[‘myfile'][tmp_name],'upload/'.$_FILE[‘myfile'][name]); 
    } 
    ?> 
    文件上传 
     
     
     
   
 
    上传文件: 
     
     
     
     
     

解决方案
处理用户上传文件,要做以下检查:
(1) 检测文件后缀名是否符合白名单规范。
(2) 将文件按照随机文件名的形式,保存在服务器上。
(3) 上传目录脚本文件不可执行
(4) 注意%00 截断
(5) 对于 jpg 文件,需要读取文件内容,然后生成一个新的 jpg 文件进行保存
Cross-Site Request Forgery (CSRF)

安全威胁
Cross-Site Request Forgery(CSRF),伪造跨站请求。攻击者在用户浏览网页时,利用页面元素(例如 img 的 src),强迫受害者的浏览器向Web 应用程序发送一个改变用户信息的请求。由于发生 CSRF 攻击后,攻击者是强迫用户向服务器发送请求,所以会造成用户信息被迫修改,更严重者引发蠕虫攻击。
CSRF 攻击可以从站外和站内发起。从站内发起 CSRF 攻击,需要利用网站本身的业务,比如“自定义头像”功能,恶意用户指定自己的头像 URL 是一个修改用户信息的链接,当其他已登录用户浏览恶意用户头像时,会自动向这个链接发送修改信息请求。

从站外发送请求,则需要恶意用户在自己的服务器上,放一个自动提交修改个人信息的htm 页面,并把页面地址发给受害者用户,受害者用户打开时,会发起一个请求。

如果恶意用户能够知道网站管理后台某项功能的 URL,就可以直接攻击管理员,强迫管理员执行恶意用户定义的操作。
代码示例
 一个没有 CSRF 安全防御的代码如下:

复制代码 代码如下:

$user=checkSQL($user);
$pass=checkSQL($pass);
$sql=“update  UserTB set  password=$user  Where  user=$pass”;
mysqli_stmt_execute($sql);
?>

代码中接收用户提交的参数“user,pass”,之后修改了该用户的数据,一旦接收到一个用户发来的请求,就执行修改操作。
  提交表单代码:
复制代码 代码如下:






When the user clicks submit, the modification operation will be triggered.
Attack Example
If the code in the "code example" is a web application on xxx.com, then a malicious user can construct 2 HTML pages in order to attack the logged-in user of xxx.com.
(1) In page a.htm, iframe b.htm and set both width and height to 0.
Copy code The code is as follows: