Home > Article > Backend Development > Detailed introduction to PHP code review_PHP tutorial
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:
" ;<br>system("ls -al".$dir);<br>echo "";
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.
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.
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:
$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:
$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.
// 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]);
}
?>