A detailed introduction to PHP code review _php Tutorial

Source: Internet
Author: User
Tags md5 encryption php file upload sql injection attack account security csrf attack
Overview
Code auditing is the work of systematically checking application source code. It is designed to find and fix some of the vulnerabilities or procedural logic errors that exist in the development phase of an application, and to avoid unnecessary risks to the enterprise by exploiting the vulnerability of the program.
Code auditing is not a simple check of code, the reason for auditing code is to ensure that the code is secure enough to protect information and resources, so familiarity with the entire application's business processes is important to control the potential risks.
Auditors can use questions like the following to interview developers to gather application information.

What types of sensitive information is included in the application and how does the application protect that information?
Are applications provided internally or externally? Who will use them, are they trusted users?
Where is the application deployed?
How important is the application to the enterprise?

The best way is to do a checklist and let the developer fill it out. Checklist can be a more intuitive reflection of the application's information and the developer's coding security, it should cover the potentially serious vulnerabilities of the module, such as: Data validation, authentication, session management, authorization, encryption, error handling, logging, security configuration, network architecture.

Input validation and output display
Most of the vulnerabilities are due to the fact that the input data is not securely verified or the output data is not securely processed, the more rigorous data validation method is: to accurately match the data
Accept white List of data
Blacklist-Reject data
Encode 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 threats
Command injection attacks change the dynamically generated content of a Web page by inputting HTML code into an input mechanism, such as a table field that lacks valid validation restrictions, which can lead to malicious commands controlling the user's computer and their network. The following functions are available for PHP execution system commands: System, exec, PassThru, ', Shell_exec, Popen, Proc_open, pcntl_exec, and we search for these functions in all program files, Determine whether the parameters of the function will change due to external commits, and check whether the parameters are handled safely.
code example
Example 1:
Copy the Code code as follows:
ex1.php
$dir = $_get["dir"];
if (Isset ($dir))
{
echo "

";
System ("Ls-al". $dir);
echo "
";
}
?>

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 ");



Precautionary Method
1, try not to execute external commands
2, use custom functions or libraries to override the functions of external commands
3, use the ESCAPESHELLARG function to handle command parameters
4, use safe _MODE_EXEC_DIR specifies the path to the executable
the Esacpeshellarg function will escape any character that causes the argument or command to end, single quote "'", replace with "\", double quote "" ", replace with" \ "", semicolon ";" Replace with "\;", specify the path to the executable file with Safe_mode_exec_dir, and you can put the command you are using in advance into this path.
copy code code is as follows:
Safe_mode = on
Safe_mode_exec_di r=/usr/local/php/bin/

Cross site Scripting
Security threats
crosses site Script (XSS), a cross-site scripting threat. Attackers use the app's dynamic presentation Data feature to embed malicious code in HTML pages. When the user browses to the page, the malicious code embedded in the HTML is executed by
and the user's browser is controlled by the attacker to achieve the special purpose of the attacker. Output functions are often used: echo, print, printf, vprintf, <%= $test%>

Cross-site scripting attacks have the following three forms of attack:
(1) Reflective cross-site scripting attack
An attacker would use a social engineering method to send a URL connection to the user, and the browser would execute a malicious script embedded in the page while the user opened the page.
(2) Storage-type cross-site scripting attacks
The attacker takes advantage of the input or modification data provided by the Web application to store the data in a server or user cookie, and the browser executes a malicious script embedded in the page when another user browses to the page that presents the data. All visitors will be attacked.
(3) DOM cross-site attack

Because of the HTML page, the definition of a section of JS, according to the user's input, display a piece of HTML code, the attacker can insert a malicious script, the final display, the execution of malicious script. The difference between Dom cross-site and the above two cross-site attacks is that the DOM cross-site is the output of a plain-page script that can be defended only if the specification uses JAVASCRIPT.

A malicious attacker could use a cross-site scripting attack to:
(1) Theft of user cookies, forged user identity login.
(2) Let the browser be forced to perform a page operation, as a user to the server to initiate a request to achieve the purpose of the attack.
(3) Combined with browser vulnerability, download virus Trojan to the viewer's computer to execute.
(4) derived URL jump vulnerability.
(5) Let the official website appear the fishing page.
(6) Worm attacks
code Example
Displaying "user-controllable data" directly on an HTML page will directly lead to cross-site scripting threats.
Copy CodeThe code is as follows:
echo "$newsname”;
echo "$gifname";
echo "”;
echo "". Htmlentities ($context). "”;
?>

These display methods may cause the user's browser to use "user-controllable data" as a Js/vbs script, or page elements to be controlled by the page HTML code inserted by "user-controllable data", resulting in an attack.
Solution Solutions
A) Htmlescape should be escaped before displaying "user controllable data" in HTML.
Copy CodeThe code is as follows:
Htmlspecialchars ($outputString, ent_quotes);

HTML escaping should be escaped in the following list:
Copy CodeThe code is as follows:
& &
< <
> >
"--"
'--'

b) The "user-controllable data" output in JavaScript requires JavaScript escape escaping.
Characters that need to be escaped include:
Copy CodeThe code is as follows:
/--\
'--\ '
"--\"
--\ \

c) "User-controllable data" output to rich text, do rich text security filtering (allow the user to output HTML), prevent the Rich Text editor in the existence of scripted script code.
SQL injection (SQL injection)

Security threats
SQL injection is a threat that occurs when an application submits the user's input to a SQL statement and commits it to the database execution. Because the user's input is also part of the SQL statement, the attacker can take advantage of this partially controllable content, inject their own defined statements, alter the SQL statement execution logic, and allow the database to execute arbitrary instructions of its own. By controlling some SQL statements, attackers can query the database for any data they need, and take advantage of some of the characteristics of the database to get the system permissions of the database server directly. A SQL injection attack would require an attacker to have a good understanding of SQL statements, so there is a need for an attacker's technology. But a few years ago, a large number of SQL injection tools had emerged that would allow any attacker to hit the attack with a few mouse clicks, which greatly increased the threat of SQL injection.

General steps for SQL injection attacks:
1. An attacker accesses a site with a SQL injection vulnerability, looking for an injection point
2, the attacker constructs the injection statement, the injected statement and the SQL statement in the program combine to generate a new SQL statement
3. New SQL statements are submitted to the database to perform processing
4. The database executes a new SQL statement, triggering a SQL injection attack



code example
Insufficient input checks cause the SQL statement to execute the illegal data submitted by the user as part of the statement.
Example:
Copy the Code code as follows:
$id =$_get[' id '];
$name =$_get[' name '];
$sql = "SELECT * from news where ' id ' = $id and ' username ' = ' $name '";
?>

Solution Solutions
A) Security configuration and encoding method, PHP configuration options are specified in the php.ini file. The following configuration can enhance the security of PHP, so that the application to avoid the attack by SQL injection.
1) safe_mode=onphp, the file function or its directory will be checked to see if the owner of the current script matches the owner of the file to be manipulated, and the current script owner and file operation owner do not match the 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 re-entry is disabled, then PHP will escape all single quotes with a single quote.
Validating variables of digital type
$id = (int) $id;
Note: PHP6 has removed the Magic quotes option

b) Bind the variables in all incoming SQL statements using preprocessing execution SQL statements. In this way, the user splicing in the variable, no matter what the content, will be used as a substitute symbol "?" Value, the database is not
The data that the malicious user splicing in, as part of SQL statement to parse. 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 threat (Files Upload)
Security threats
PHP file Upload vulnerability is mainly to verify the file type when the file variable is not handled by the attack, resulting in the program to determine the logic is bypassed, the attacker uploads the script file is parsed by the server, so as to obtain the SHELL or upload
Files are arbitrarily copied, or even upload a script Trojan to the Web server, directly control the Web server.
code Example
The code that handles the user's request to upload a file that does not filter the file name extension.
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. " Upload success! Click Continue upload ";
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]);
}
?>
<title>File Upload</title>







Solution Solutions
Process the user to upload files, to do the following checks:
(1) Check whether the file suffix is in compliance with the whitelist specification.
(2) Save the file to the server in the form of a random filename.
(3) Upload directory script file is not executable
(4) Note%00 truncation
(5) For JPG files, you need to read the contents of the file, and then generate a new JPG file to save
Cross-site Request Forgery (CSRF)

Security Threats
Cross-site Request Forgery (CSRF), forged cross-site requests. When the user browses the Web page, the attacker uses page elements (such as the IMG SRC) to force the victim's browser to send a request to the Web application to change the user's information. Because of the CSRF attack, the attacker is forcing the user to send a request to the server, so the user information will be forced to modify, more serious caused by the worm attack.
CSRF attacks can be initiated from outside the station and from within the station. Launch CSRF attacks from the site, need to take advantage of the business of the website itself, such as "Custom Avatar" function, malicious users to specify their own avatar URL is a modification of user information link, when other logged on users to browse the malicious user picture, the link will automatically send a request for modification information.

Send requests from outside the station, you need a malicious user on their own server, put an automatically submit to modify the personal information of the HTM page, and the page address to the victim user, the victim when the user opens, will initiate a request.

If a malicious user can know the URL of a feature in the site management background, it can directly attack the administrator and force the administrator to perform a malicious user-defined operation.
code Example
A code that does not have CSRF security defenses 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 a user-submitted parameter "User,pass", modifies the user's data, and, once a request is received from a user, performs a modification operation.
Submit the form code:
Copy CodeThe code is as follows:


When the user points commits, the modification is triggered.
Attack instances
If the code in the code sample is a web app on xxx.com, then a malicious user can construct 2 HTML pages in order to attack XXX.com's logged-on user.
(1) Page a.htm, iframe a bit b.htm, the width and height are set to 0.
Copy CodeThe code is as follows:
&lt;/frame&gt;&lt;BR&gt;&lt;BR&gt; This is so that when an attack occurs, the victim user does not see the submit successful results page. &lt;BR&gt; (2) page b.htm, there is a form, and a script, the role of the script is to automatically submit this form when the page is loaded. &lt;br&gt;&lt;span style= "Cursor:pointer" onclick= "docopy (' code55621 ')" &gt;&lt;U&gt; copy code &lt;/U&gt;&lt;/span&gt; The code is as follows:&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt; (3) The attacker simply puts the page a.htm on his web server and sends it to the logged-on user. After the user opens the A.htm, the form is automatically submitted and sent to the Web application that exists CSRF vulnerability under xxx.com, so the user's information is forced to be modified. &lt;/P&gt;&lt;P&gt;&lt;STRONG&gt; Solution The principle of &amp;LT;BR&amp;GT;&amp;LT;/STRONG&amp;GT;CSRF defense is to generate a random token when the user logs in, storing it in a cookie ( By default, it can also be placed in the session), when the form is generated, a hidden field is generated, and the value of the hidden field is &lt;BR&gt; the value of token. If the user submits the form, it is possible to determine whether the token value of the hidden domain is consistent with the token value in the user's COOKIE in the Web app that receives the user's request, and if it is inconsistent or does not have this value, it will be sentenced to &lt;BR&gt; broken as a CSRF attack. The attacker could not predict the random TOKEN value generated by each user login, so the parameter could not be forged. &lt;br&gt;&lt;br&gt;&lt;STRONG&gt; FAQs &lt;BR&gt;&lt;/STRONG&gt; (1) Why not directly verify referer?&lt;br&gt; because there are csrf in the station, and Referer can be tampered with, unreliable data &lt;BR&gt; (2) If an XSS attack occurs first, the attacker can get the token of the user page?&lt;br&gt; no solution, please do the XSS guard first. &lt;BR&gt;&lt;STRONG&gt; file contains &lt;br&gt;&lt;/strong&gt;php may appear file containsFunctions: Include, include_once, require, require_once, Show_source, Highlight_file, ReadFile, file_get_contents, fopen, file &lt;BR&gt;&lt;STRONG&gt; Precautionary method:&lt;br&gt;&lt;/strong&gt; exact matching of input data, such as determining language en.php, cn.php based on the value of the variable, Then these two files are placed in the same directory ' language/'. $_post[' Lang '. PHP ',&lt;br&gt; so check whether the submitted data is en or CN is the most stringent, check whether only the letter is also good, by filtering parameters in the/、.. and other characters. The &lt;br&gt;&lt;strong&gt;http response split &lt;br&gt;&lt;/strong&gt;php can cause the HTTP response to split: Use the header function and use the $_server variable. Note that a high version of PHP prevents newline characters from appearing in the HTTP header, which can be skipped directly from this test. &lt;BR&gt;&lt;STRONG&gt; Prevention method:&lt;br&gt; exact match input data &lt;BR&gt;&lt;/STRONG&gt; detect input input if there is \ R or \ n, direct deny &lt;BR&gt;&lt; Strong&gt; variable overrides &lt;br&gt;&lt;/strong&gt;php variable overrides appear in the following situations:&lt;br&gt;&lt;strong&gt; traverse the initialization variable &lt;br&gt;&lt;/strong &gt; Example: &lt;br&gt;&lt;span style= "Cursor:pointer" onclick= "docopy (' code83133 ')" &gt;&lt;U&gt; copy code &lt;/u&gt;&lt;/ The span&gt; code is as follows: &lt;br&gt;foreach ($_get as $key + $value) &lt;br&gt;$ $key = $value;&lt;br&gt;&lt;br&gt; function override variable: parse_ When str, MB_PARSE_STR, Import_request_variables,register_globals=on, the GET-mode commit variable is overwritten directly&lt;BR&gt;&lt;STRONG&gt; Prevention Methods:&lt;br&gt;&lt;/strong&gt; settings register_globals=off&lt;br&gt; do not use these functions to get variables &lt;BR&gt; &lt;STRONG&gt; dynamic functions &lt;BR&gt;&lt;/STRONG&gt; when using dynamic functions, if the user is controllable on the variable, it can cause an attacker to execute arbitrary functions. &lt;BR&gt; Example: &lt;br&gt;&lt;span style= "Cursor:pointer" onclick= "docopy (' code47480 ')" &gt;&lt;U&gt; copy code &lt;/U&gt; &lt;/span&gt; code below:&lt;br&gt;&lt;?php&lt;br&gt; $myfunc =$_get[' MyFunc '];&lt;br&gt; $myfunc ();&lt;br&gt;?&gt;&lt; Br&gt;&lt;br&gt;&lt;strong&gt; Defense Method:&lt;br&gt;&lt;/strong&gt; Don't use functions &lt;BR&gt; session security &lt;br&gt;httponly Settings &lt;br &gt;session.cookie_httponly = ON, client script (JavaScript, etc.) cannot access the cookie, and opening the instruction can effectively prevent hijacking session Id&lt;br&gt;domain settings through XSS attacks &lt;br &gt; Check if Session.cookie_domain contains only this domain, and if it is a parent domain, other subdomains can get Cookies&lt;br&gt;path settings for the domain &lt;BR&gt; check session.cookie_path, If the site itself is applied to/app, the path must be set to/app/to ensure security &lt;br&gt;cookies duration &lt;BR&gt; Check session.cookie_lifetime, if the time setting process is too long, Even if the user closes the browser, the attacker can compromise the account security &lt;br&gt;secure settings &lt;BR&gt; If you use HTTPS, you should set Session.cookie_secure=on to ensure that you use HTTPS to transfer cookies &lt;br&gt;session fixed &amp;LT;BR&amp;Gt; If the permission level changes (for example, if a normal user is promoted to an administrator after verifying the user name and password), we should modify the session ID that is about to regenerate, or the program will be at risk of a session fixed attack. &lt;/P&gt;&lt;P&gt;&lt;STRONG&gt; Encryption &lt;BR&gt;&lt;/STRONG&gt; PlainText store passwords &lt;BR&gt; storing passwords in plaintext can be a serious threat to users, applications, and system security. &lt;BR&gt; password Weak encryption &lt;BR&gt; using easy-to-crack cryptographic algorithms, MD5 encryption has been partially exploited by the MD5 hack website to crack &lt;BR&gt; reference scheme &lt;br&gt;&lt;span style= "CURSOR: Pointer "onclick=" docopy (' code80997 ') "&gt;&lt;U&gt; copy code &lt;/U&gt;&lt;/span&gt; code as follows: &amp;LT;BR&amp;GT;MD5 (MD5 ($password) . $salt) &lt;BR&gt;&lt;BR&gt; passwords are stored in files that attackers can access &lt;BR&gt; for example: Save passwords in txt, INI, conf, Inc, XML, etc., or write directly in HTML comments &lt;/P&gt; &lt;P&gt;&lt;STRONG&gt; Authentication and authorization &lt;BR&gt; user authentication &lt;BR&gt;&lt;/STRONG&gt; Check the location of the code for user authentication, and whether it is possible to bypass authentication, such as: There may be form injection in the login code. &lt;BR&gt; Check the login code for the use of verification code, etc., to prevent violent cracking means &lt;BR&gt; non-authenticated calls to functions or files &lt;br&gt;&lt;br&gt; Some administrative pages are forbidden to access by ordinary users, Sometimes developers forget to verify permissions on these files, causing the vulnerability to occur &lt;BR&gt; some pages using parameter invocation functions without permission validation, such as index.php?action=upload&lt;br&gt; password hard-coded &lt;br&gt; &lt;br&gt; Some programs will link the database account and password, directly into the database link function. &lt;BR&gt; random function &lt;br&gt;rand () VS Mt_rand () &lt;br&gt;rand () The maximum random number is 32767, when using Rand to process the session, it is easy for an attacker to crack the session, it is recommended to use MT _rand (). &lt;BR&gt; code ExamplesExample &lt;br&gt;&lt;span style= "Cursor:pointer" onclick= "docopy (' code53889 ')" &gt;&lt;U&gt; copy code &lt;/U&gt;&lt;/span&gt; The code is as follows: &lt;br&gt;&lt;?php&lt;br&gt;//on windows&lt;br&gt;print Mt_getrandmax (); 2147483647&lt;br&gt;print Getrandmax ();//32767&lt;br&gt;?&gt;&lt;br&gt;&lt;br&gt; can see rand () the largest random number is 32767, This is easy for us to crack. &lt;br&gt;&lt;span style= "Cursor:pointer" onclick= "docopy (' code61771 ')" &gt;&lt;U&gt; copy code &lt;/U&gt;&lt;/span&gt; The code is as follows:&lt;br&gt;&lt;?php&lt;br&gt; $a = MD5 (rand ()), &lt;br&gt;for ($i =0; $i &lt;=32767; $i + +) {&lt;br&gt;if (MD5 ($i) = = $a {&lt;br&gt;print $i. ") --&gt;ok!! &lt;br&gt; "; exit;&lt;br&gt;}else {print $i." &lt;br&gt; ";} &lt;BR&gt;}&lt;BR&gt;?&gt;&lt;BR&gt;&lt;BR&gt; when our program uses Rand to process sessions, attackers are prone to brute force to break out of your session, but it's hard to be purely violent with mt_rand. &lt;/P&gt;&lt;P&gt; &lt;/p&gt;&lt;/p&gt;&lt;p align= "left" &gt;&lt;span id= "url" itemprop= "url" &gt;http:// Www.bkjia.com/PHPjc/327632.html&lt;/span&gt;&lt;span id= "Indexurl" itemprop= "Indexurl" &gt;www.bkjia.com&lt;/span &gt;&lt;span id= "Isoriginal" itemprop= "isoriginal" &gt;true&lt;/span&gt;&lt;span id= "Isbasedonurl" itemprop= "Isbasedonurl" &gt;http://www.bkjia.com/ Phpjc/327632.html&lt;/span&gt;&lt;span id= "Genre" itemprop= "genre" &gt;techarticle&lt;/span&gt;&lt;span id= " Description "itemprop=" description "&gt; Overview code Review is a systematic review of the application source code. It is designed to find and fix some of the vulnerabilities or programs that exist in the development phase of the application ... &lt;/span&gt;&lt;/p&gt;&lt;li &gt;&lt;i class= "Layui-icon" &gt;&amp; #xe63a;

Related Article

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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.