PHP code review details

Source: Internet
Author: User
Tags php file upload account security csrf attack

Code review is a systematic check of the application source code. It aims to find and fix some vulnerabilities or program logic errors in the application development stage, so as to prevent the illegal exploitation of program vulnerabilities from bringing unnecessary risks to the Enterprise.
Code review is not a simple code check. The reason for reviewing the Code is to ensure that the code can be securely protected by sufficient information and resources, therefore, it is very important to be familiar with the business process of the entire application to control potential risks.
Reviewers can use questions similar to the following to interview developers to collect application information.

What types of sensitive information does an application contain and how does the application protect it?
Does an application provide internal services or external services? Who will use it? Are they all trusted users?
Where is the application deployed?
What is the importance of applications for enterprises?

The best way is to make a checklist for developers to fill in. Checklist can intuitively reflect application information and coding Security done by developers. It should cover modules that may have severe vulnerabilities, such: data verification, identity authentication, session management, authorization, encryption, error processing, logs, security configuration, and network architecture.

Input verification and output display
Most vulnerabilities are caused by the absence of security verification on the input data or the absence of security processing on the output data. The strict data verification method is: precise data matching.
Accept data from the whitelist
Reject blacklist data
Encode the data that matches the blacklist

In PHP, the list of variables that users can enter is as follows:
$ _ GET
$ _ POST
$ _ ENV
We should check these input variables

Command Injection
Security threats
Command injection attacks modify the dynamically generated content of a webpage by inputting HTML code into an input mechanism (for example, a table domain that lacks valid Verification restrictions, this may cause malicious commands to control users' computers and their networks. The following functions can be used to execute system commands in PHP: system, exec, passthru, '', shell_exec, popen, proc_open, and pcntl_exec. We can search for these functions in all program files, determine whether the function parameters are changed due to external submissions and check whether these parameters have been safely processed.
Sample Code
Example 1:
Copy codeThe Code is as follows:
// Ex1.php
<? Php
$ Dir = $ _ GET ["dir"];
If (isset ($ dir ))
Echo "<pre> ";
System ("ls-al". $ dir );
Echo "</pre> ";

We submit
Copy codeThe Code is as follows:
Http: // localhost/ex1.php? Dir = | cat/etc/passwd

After submission, the command becomes
Copy codeThe Code is as follows:
System ("ls-al | cat/etc/passwd ");

Defense methods
1. Try not to execute External commands
2. Use a user-defined function or function library to replace the functions of External commands
3. Use the 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 character that causes the parameter or command end. Replace the single quotation mark (') with "\", double quotation mark ("") with "\" ", replace Semicolon ";" with "\;", and use safe_mode_exec_dir to specify the path of the executable file. You can put the commands you want to use into this path in advance.
Copy codeThe Code is as follows:
Safe_mode = On
Safe_mode_exec_di r =/usr/local/php/bin/

Cross Site Scripting)
Security threats
Cross Site Script (XSS), a Cross-Site scripting threat. Attackers can use the application's dynamic data display function to embed malicious code into html pages. When a user browses this page, the malicious code embedded in html will be
Attackers can control the user's browser for special purposes. Output functions are often used: echo, print, printf, vprintf, <% = $ test %>

There are three types of XSS attacks:
(1) reflected cross-site scripting attacks
Through social engineering, attackers can send a URL Connection to the user to open the page. When the user opens the page, the browser will execute malicious scripts embedded in the page.
(2) Storage-type XSS attacks
Attackers can use the data entry or modification function provided by web applications to store data to servers or user cookies. When other users browse the pages that display the data, the Browser executes malicious scripts embedded in the page. All viewers will be attacked.
(3) DOM cross-site attack

Because a piece of JavaScript code is defined in the html page, an html code is displayed based on the user input. Attackers can insert a malicious script during the input and execute the malicious script during the display. The difference between DOM cross-site attack and the above two cross-site attacks is that DOM cross-site is the output of pure page scripts. Only JAVASCRIPT can be used for defense.

Malicious attackers can use cross-site scripting:
(1) steal user cookies and forge user identities to log on.
(2) the browser is forced to perform a page operation and initiate a request to the server as a user to attack the server.
(3) download the virus Trojan to the viewer's computer based on browser vulnerabilities.
(4) derivative URL jump vulnerability.
(5) publish a phishing page to the official website.
(6) worm attacks
Sample Code
"User controllable data" is displayed directly on the html page, which directly leads to cross-site scripting threats.
Copy codeThe Code is as follows:
Echo "<span> $ newsname </span> ";
Echo "<a href =" $ gifurl "> $ gifname </a> ";
Echo "<input type = text name = user value = \" $ username \ "> ";
Echo "<span style = '$ stylelayout'>". htmlentities ($ context). "</span> ";

These display methods may cause the user's browser to regard "User controllable data" as JS/VBS script execution, or the page element to be controlled by the HTML code of the page inserted by "User controllable data, this can cause attacks.
A) before "User controllable data" is displayed in HTML, htmlescape should be escaped.
Copy codeThe Code is as follows:
Htmlspecialchars ($ outputString, ENT_QUOTES );

Html Escape should be escaped according to the following list:
Copy codeThe Code is as follows:
& --> &
<--> <
> -->

B) javascript escape is required for "User controllable data" output in javascript.
Escape characters include:
Copy codeThe Code is as follows:
/--> \/
'--> \'
"--> \"
\ --> \\

C) Perform Security filtering on "User controllable data" output to Rich Text to prevent script code in the rich text editor.
SQL Injection)

Security threats
When an application Concatenates the content entered by the user into an SQL statement and submits the content to the database for execution, SQL injection is threatened. Because user input is also part of SQL statements, attackers can use this part to control the content, inject their own defined statements, and change the SQL statement execution logic, allows the database to execute any commands required by itself. By controlling some SQL statements, attackers can query any data they need in the database. Using some features of the database, attackers can directly obtain the system permissions of the database server. Originally, SQL injection attacks require attackers to be familiar with SQL statements, so they have certain technical requirements. However, a large number of SQL injection and exploitation tools have emerged a few years ago, allowing any attacker to click a few mouse clicks to achieve the attack effect. This has greatly increased the threat of SQL injection.

General steps for SQL injection attacks:
1. Attackers can access websites with SQL injection vulnerabilities to find injection points.
2. Attackers construct injection statements, which are combined with the SQL statements in the program to generate new SQL statements.
3. The new SQL statement is submitted to the database for processing.
4. The database executes new SQL statements, triggering SQL injection attacks.

Sample Code
If the input check is insufficient, the SQL statement executes the illegal data submitted by the user as part of the statement.
Copy codeThe Code is as follows:
$ Id = $ _ GET ['id'];
$ Name = $ _ GET ['name'];
$ SQL = "select * from news where 'id' = $ id and 'username' = '$ name '";

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 prevent the application from being attacked by SQL injection.
1) safe_mode = onPHP will check whether the owner of the current script matches the owner of the operated file through the file function or its directory, illegal operation if the current script owner does not match the file operation owner
2) magic_quotes_gpc = on/off. If this option is activated, any single quotation marks, double quotation marks, backslash, and empty 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 use a single quotation mark to escape all single quotes.
Verify numeric Variables
$ Id = (int) $ id;
Note: PHP6 has deleted the magic quotes option.

B) Use preprocessing to execute SQL statements and bind all the variables in the passed SQL statements. In this way, the variables that the user concatenates, no matter what the content is, will be used as an alternative symbol "?" The database does not
Parses the data spliced by malicious users as part of SQL statements. Example:
Copy codeThe 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 threats)
Security threats
The PHP File Upload Vulnerability mainly occurs when the file type is verified and the attack caused by file variables is not handled properly. As a result, the program judgment logic is bypassed, And the attacker uploads the script file to the server for parsing, to obtain the SHELL or upload
The file is freely copied, and even the script Trojan is uploaded to the web server to directly control the web server.
Sample Code
Code used to process a file upload request. This Code does not filter file extensions.
Copy codeThe Code is as follows:
// OldUpload. php
If (isset ($ upload) & $ myfile! = "None" & check ($ myfile_name )){
Copy ($ myfile, "/var/www/upload/". $ myfile_name );
Echo "File". $ file_name. "uploaded successfully! Click <a href = \ "$ PHP_SELF \"> continue upload </a> ";
// CheckUpload. php
$ DeniedExtensions = array ('html', 'htm', 'php', 'php2', 'php3', 'php4 ', 'php5', 'Ph
Tml', 'pwm', 'inc', 'asp ', 'aspx', 'ascx', 'jsp ', 'cfm', 'cfc', 'pl ', 'batt', 'exe ','
Com ', 'dll', 'vbs ', 'js', 'reg', 'cgi ', 'htaccess', 'assig ');
If ($ checkUpload ($ _ FILE ['myfile'] [name], $ DeniedExtensions) {copy ($ _ FILE ['myfile'] [tmp_name], 'upload /'. $ _ FILE ['myfile'] [name]);
<Title> File Upload </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Body bgcolor = "# FFFFFF">
<Form enctype = "multipart/form-data" method = "post">
Upload files:
<Input type = "file" name = "myfile" size = "30">
<Input type = "submit" name = "upload" value = "upload">

To process uploaded files, perform the following checks:
(1) check whether the filename extension complies with the whitelist specification.
(2) Save the file to the server in the form of a random file name.
(3) The uploaded directory script file cannot be executed.
(4) % 00 Truncation
(5) For jpg files, you need to read the file content and generate a new jpg file to save it.
Cross-Site Request Forgery (CSRF)

Security threats
Cross-Site Request Forgery (CSRF. When a user browses a webpage, the attacker uses page elements (such as the src of img) to force the victim's browser to send a request to the Web application to change user information. In the case of CSRF attacks, attackers force users to send requests to the server. Therefore, user information is forced to be modified. In more serious cases, worms are exploited.
CSRF attacks can be initiated outside and within the site. To initiate a CSRF attack from a website, you must use the website's services, such as the "Custom profile picture" function. A malicious user specifies that the profile picture URL is a link to modify user information, when other logged-on users browse malicious user portraits, the system will automatically send a request to modify the information to this link.

When sending a request outside the site, a malicious user needs to put an htm page that automatically submits and modifies his/her personal information on his/her server, and send the page address to the victim. When the victim opens the page, A request is initiated.

If malicious users can know the URL of a function in the website management background, they can directly attack the Administrator and force the Administrator to perform operations defined by malicious users.
Sample Code
A code without CSRF security defense is as follows:
Copy codeThe Code is as follows:
$ User = checkSQL ($ user );
$ Pass = checkSQL ($ pass );
$ SQL = "update UserTB set password = $ user Where user = $ pass ";
Mysqli_stmt_execute ($ SQL );

The Code receives the parameter "user, pass" submitted by the user, and then modifies the user's data. Once a user receives a request, the modification is performed.
Code for submitting a form:
Copy codeThe Code is as follows:
<Form action = "http: // localhost/servlet/modify" method = "POST">
<Input name = "email">
<Input name = "tel">

When the user clicks submit, the modification operation is triggered.
Attack instance
If the code in the "sample code" is a web application on, malicious users can construct two HTML pages to attack logon users of
(1) In a.htm, set the width and height to 0 in iframe B .htm.
Copy codeThe Code is as follows:
<Iframe src = "B .htm" width = "0" height = "0"> </frame>

This is to prevent the victim user from seeing the successful submission result page when an attack occurs.
(2) There is a form and a script in page B .htm. The script automatically submits the form when the page is loaded.
Copy codeThe Code is as follows:
<Form id = "modify" action = "" method = "POST">
<Input name = "email">
<Input name = "tel">
Document. getElementById ("modify"). submit ();

(3) The attacker only needs to place a.htm on his web server and send it to the login user. After opening a.htm, the user will automatically submit a form and send it to the web application with the CSRF vulnerability under Therefore, the user's information is forced to be modified.

The principle of CSRF defense is to generate a random token during user login and store it in the cookie (which can be stored in the session by default). When a form is generated, generate a hidden domain, and hide the value of the domain.
The value of token. If the user submits this form, the user can determine whether the TOKEN value of the hidden domain is consistent with the TOKEN value in the user COOKIE in the web application that receives the user request. If the value is inconsistent or does not exist, just judge
It is a CSRF attack. Attackers cannot predict the random TOKEN value generated when each user logs on, so they cannot forge this parameter.

(1) Why not directly verify referer?
Because there are also csrf sent from the station, and the referer can be tampered with, it is unreliable data
(2) What should I do if an xss attack occurs first, and the attacker can get the token of the user page?
No solution. Do xss Protection first.
File Inclusion
PHP can export the number of letters included in the current file package: include, include_once, require, require_once, show_source, highlight_file, readfile, file_get_contents, fopen, and file
Defense methods:
Accurately match the input data, for example, determining the language en based on the value of the variable. php, cn. php, then the two files are placed in the same directory 'language /'. $ _ POST ['lang ']. '. php ',
Check whether the submitted data is en or cn, and check whether it only contains letters. filter the/,... and other characters in the parameter.
HTTP Response Splitting
In PHP, the HTTP Response Splitting may be caused by the use of the header function and the $ _ SERVER variable. Note that PHP later versions will disable line breaks in the HTTP header. You can skip this test directly.
Defense methods:
Exact match of input data
If \ r or \ n is included in the check input, reject it directly.
Variable Overwrite
PHP variable overwrite may occur in the following situations:
Traverse initialization Variables
Copy codeThe Code is as follows:
Foreach ($ _ GET as $ key => $ value)
$ Key = $ value;

Function override variables: parse_str, mb_parse_str, import_request_variables, and Register_globals = ON. The variables submitted in GET mode will be overwritten directly.
Defense methods:
Set Register_globals = OFF
Do not use these functions to obtain variables.
Dynamic Functions
When dynamic functions are used, attackers can execute arbitrary functions if the variables are controllable.
Copy codeThe Code is as follows:
<? Php
$ Myfunc = $ _ GET ['myfunc'];
$ Myfunc ();

Defense method:
Do not use functions like this
Session Security
HTTPOnly settings
Session. cookie_httponly = ON, the client script (JavaScript, etc.) cannot access this cookie. Enabling this command can effectively prevent session ID hijacking through XSS attacks.
Domain settings
Check whether session. cookie_domain only contains this domain. If it is a parent domain, other subdomains can obtain cookies of this domain.
Path settings
Check session. cookie_path. If the website is applied to/app, the path must be set to/app/to ensure security.
Cookie duration
Check session. cookie_lifetime. If the time setting process is too long, even if the user closes the browser, attackers may also endanger account security.
Secure Settings
If HTTPS is used, set session. cookie_secure = ON to ensure that HTTPS is used to transmit cookies.
Fixed session
If the permission level changes (for example, after verifying the user name and password, the common user is promoted to the Administrator), we should modify the session ID to be re-generated, otherwise, the program may face the risk of Session Fixation attacks.

Plaintext storage Password
Storing passwords in plain text seriously threatens the security of users, applications, and systems.
Weak Password Encryption
Using an easy-to-crack encryption algorithm, MD5 encryption can be used to crack websites.
Reference Scheme
Copy codeThe Code is as follows:
Md5 (md5 ($ password). $ salt)

Passwords are stored in files that attackers can access.
For example, save the password in txt, ini, conf, inc, xml, or other files, or directly write it in HTML comments.

Authentication and authorization
User Authentication
Check the location where the code performs user authentication and whether the authentication can be bypassed. For example, a form injection may exist in the login code.
Check whether the logon Code uses verification codes or other methods to prevent brute-force cracking.
Unauthenticated call of functions or files

Some management pages prohibit access by common users. Sometimes developers forget to verify the permissions of these files, resulting in a vulnerability.
Some pages use the parameter call function without permission verification, such as index. php? Action = upload
Password hard Encoding

Some programs directly write the database linked account and password to the database linked function.
Random Functions
Rand () VS mt_rand ()
The maximum Random Number of rand () is 32767. When rand is used to process the session, attackers can easily crack the session. mt_rand () is recommended ().
Sample Code
Copy codeThe Code is as follows:
<? Php
// On windows
Print mt_getrandmax (); // 2147483647
Print getrandmax (); // 32767

We can see that the maximum Random Number of rand () is 32767, which is easily cracked by us.
Copy codeThe Code is as follows:
<? Php
$ A = md5 (rand ());
For ($ I = 0; $ I <= 32767; $ I ++ ){
If (md5 ($ I) ==$ ){
Print $ I. "--> OK !! <Br> "; exit;
} Else {print $ I. "<br> ";}

When our program uses rand to Process sessions, attackers can easily crack your sessions. However, mt_rand is difficult to crack.


Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.