What kind of sensitive information does the application contain, and how does the application protect that information?
Does the application serve internally or externally? Who will use them as trusted users?
Where is the application deployed?
What is the importance of an application for an enterprise?
The best way is to do a checklist and let the developer fill it out. Checklist can more intuitively reflect the information of the application and the coding security of the developer, it should cover the modules that may have serious vulnerabilities, such as data authentication, authentication, session management, authorization, encryption, error handling, logging, security configuration, network architecture.
Prevention methods
1, try not to execute external command
2, use a custom function or function library to replace the function of the external command
3, using the ESCAPESHELLARG function to handle command parameters
4, use Safe_mode_exec_dir to specify the path of the executable file
The ESACPESHELLARG function replaces any word that causes the end of a parameter or command with a single quotation mark "'", replaced by "\", double quotes "", replaced by "\", "Escape", semicolon ";" Replace with "\;", use Safe_mode_exec_dir to specify the path of the executable file, you can put the command that will be used in advance into this path.
Copy Code code as follows:
Safe_mode = On
Safe_mode_exec_di r=/usr/local/php/bin/
Cross-Site scripting threats (Cross Site scripting)
Security threats
Cross site Script (XSS), cross-site scripting threats. An attacker uses the dynamic display data feature of an application to embed malicious code in an HTML page. When the user browses to the page, the malicious code embedded in the HTML is
Execution, the user's browser is controlled by the attacker, thus achieving the attacker's special purpose. Output functions are often used: echo, print, printf, vprintf, <%= $test%>
Cross-site scripting attacks have the following three types of attacks:
(1) Reflective cross-station scripting attacks
The attacker would use social engineering to send a URL to connect 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
An attacker uses the input or modify data functionality provided by a Web application to store data in a server or user cookie, and the browser executes malicious scripts embedded in the page when other users browse the page that displays the data. All viewers will be attacked.
(3) DOM cross-station attack
Because the HTML page, defined a paragraph of JS, according to user input, display a section of HTML code, an attacker can enter a malicious script, the final display, will execute malicious script. The difference between a Dom cross station and the above two cross-site attacks is that the Dom Cross station is the output of a plain-page script, which can only be defended if the specification uses JAVASCRIPT.
A cross-site scripting attack can be used by a malicious attacker to:
(1) Theft of user cookies, fake user login.
(2) Let the browser be forced to perform a page operation, the user identity to the server to initiate the request, to achieve the purpose of the attack.
(3) Combined with browser vulnerabilities, download the virus Trojan to the viewer's computer to execute.
(4) Derivative URL Jump vulnerability.
(5) Let the official website appear the phishing page.
(6) Worm attack
code example
Displaying "user-controllable data" directly on an HTML page will directly result in a cross-site scripting threat.
Copy Code code 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 types of display may cause the user's browser to take "user-controlled data" as a Js/vbs script, or page elements to be controlled by HTML code that is inserted into the user-controllable data, causing the attack.
Solution
A htmlescape escape should be performed before displaying "user-controllable data" in HTML.
Copy Code code as follows:
Htmlspecialchars ($outputString, ent_quotes);
HTML escape should be escaped according to the following list:
Copy Code code as follows:
&--> &
<--> <
>--> >
"-->"
'--> '
b The "user-controllable data" output in JavaScript requires JavaScript escape escape.
The characters that need to be escaped include:
Copy Code code as follows:
/--> \/
'--> \ '
"--> \"
\--> \
C "User-controllable data" for output to rich text, for rich-text security filtering (allowing the user to output HTML) to prevent scripting script code in Rich text editors.
SQL injection (SQL injection)
Security threats
An SQL injection threat occurs when an application submits user input, stitching it into an SQL statement, and submitting it to the database for execution. Because the user's input is also part of the SQL statement, an attacker can use this part of the control to inject their own defined statements, change the SQL statement execution logic, and let the database execute arbitrary instructions that they need. By controlling some SQL statements, an attacker can query the database for any data they need, and take advantage of some features of the database to directly obtain the system privileges of the database server. An SQL injection attack would require an attacker to understand the SQL statement very well, so there is a certain requirement for the attacker's technology. But a few years ago, there had been a lot of SQL injection tools that would allow any attacker, with just a few mouse clicks, to achieve the attack, which would increase the threat of SQL injection.
General steps for SQL injection attacks:
1, the attacker to access the site with SQL injection vulnerabilities, looking for injection point
2, the attacker constructs the injection statement, the injection statement and the SQL statement in the program combine to generate the new SQL statement
3. New SQL statements are committed to the database to perform processing
4. The database executes a new SQL statement that throws a 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 code as follows:
?
$id =$_get[' id '];
$name =$_get[' name '];
$sql = "SELECT * from news where ' id ' = $id and ' username ' = ' $name '";
?>
Solution
A the Security Configuration and encoding method, PHP configuration options are specified in the php.ini file. The following configuration methods can enhance PHP security and prevent the application from being attacked by SQL injection.
1) safe_mode=onphp, the owner of the current script will be checked through the file function or its directory to match the owner of the file to be manipulated, and the current script owner and file operator owner do not match the illegal operation
2) Magic_quotes_gpc=on/off, if the option is activated, any single quotes, double quotes, backslashes, and blank characters contained in the request parameters are automatically escaped with a backslash.
3 Magic_quotes_sybase=on/off, if the options are disabled, PHP will escape all the single quotes with a single quote.
Validating a variable of a numeric type
$id = (int) $id;
Note: PHP6 has removed the Magic quotes option
b Use preprocessing to execute the SQL statement and bind the variables in all incoming SQL statements. In this way, the user splicing in the variable, regardless of what the content, will be used as a substitute symbol "?" Substituted values, the database does not
The data that the malicious user splicing in, as part of SQL statement to parse. Example:
Copy Code code 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);
files Upload threat (file Upload)
Security threats
PHP file Upload vulnerability is mainly in the validation of file types when not handling the file variables brought about by the attack, resulting in the program to judge the logic is bypassed, the attacker upload script files by the server resolution, so as to obtain the SHELL or upload
Files are arbitrarily copied, or even upload script Trojan to the Web server, directly control the Web server.
code Example
Process the code that the user uploads the file request, this code does not filter the file name extension.
Copy Code code 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 <a href=\ "$PHP _self\" > Continue to upload </a> ";
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>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<body bgcolor= "#FFFFFF" >
<form enctype= "Multipart/form-data" method= "POST" >
Upload file:
<input type= "File" Name= "myfile" size= ">"
<input type= "Submit" name= "Upload" value= "upload" >
</form>
</body>
Solution
To process the user upload file, do the following check:
(1) Detect whether the file suffix name conforms to the white list specification.
(2) The file is stored on the server in the form of random file names.
(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), to forge a cross station. 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 forced the user to send a request to the server, causing the user's information to be modified and, more seriously, to trigger a worm attack.
CSRF attacks can be initiated from outside the station and in the station. Launch CSRF attack from the station, need to use the business of the website itself, for example "Custom Avatar" function, the malicious user specifies own avatar URL is a link that modifies the user information, when other already logged-in user browses the malicious user avatar, will automatically send the modification information request to this link.
Sending requests from outside the station requires a malicious user to place an HTM page that automatically submits changes to personal information on his or her own server, and sends the page address to the victim's user, who initiates a request when the victim opens.
If a malicious user can know the URL of a feature in the Web site Admin background, it can directly attack the administrator and force the administrator to perform a malicious user-defined action.
code example
A code that does not have a CSRF security defense is as follows:
Copy Code code 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 user-submitted parameter "User,pass", modifies the user's data, and executes the modification once a request has been received from a user.
Submit the form code:
Copy Code code as follows:
<form action= "http://localhost/servlet/modify" method= "POST" >
<input name= "Email" >
<input name= "Tel" >
</form>
The modification action is triggered when the user point is committed.
Attack instance
If the code in code example is a Web application on xxx.com, a malicious user can construct 2 HTML pages in order to attack XXX.com's logged-in users.
(1) page a.htm, the iframe b.htm, the width and height are set to 0.
Copy Code code as follows:
<iframe src= "b.htm" width= "0" height= "0" ></frame>
This is so that when an attack occurs, the victim user is not able to see the Submit Success results page.
(2) page b.htm, there is a form, and a script, the role of the script, when the page is loaded, automatically submit this form.
Copy Code code as follows:
<form id= "Modify" action= "Http://xxx.com/servlet/modify" method= "POST" >
<input name= "Email" >
<input name= "Tel" >
</form>
<script>
document.getElementById ("Modify"). Submit ();
</script>
(3) The attacker simply puts the page a.htm on its own web server and sends it to the logged-in user. When the user opens the A.htm, it automatically submits the form and sends it to the Web application with the CSRF vulnerability under xxx.com, so the user's information is forced to be modified.
Solution
The principle of CSRF defense is that when a user logs on, a random token is generated, stored in a cookie (by default, in session), a hidden field is generated when the form is generated, and the value of the hidden field is
To the token value. If the user submits this form, in the Web application that receives the user's request, the TOKEN value of the hidden field is determined to be consistent with the TOKEN value in the user's COOKIE, if it is inconsistent or does not have this value, the sentence
Broken for CSRF attack. The attacker cannot predict the random TOKEN value generated by each user at logon, so it is not possible to forge this parameter.
Problems
(1) Why not directly verify Referer?
Because there are csrf in the station, and Referer can be tampered with, unreliable data
(2) If the first XSS attack, the attacker can get the user page token how to do?
No solution, please do XSS prevention first.
file contains
PHP may appear with functions included in the file: include, include_once, require, require_once, Show_source, Highlight_file, ReadFile, File_get_cont Ents, fopen, file
Precautionary Method:
Accurate matching of input data, such as determining the language en.php and cn.php based on the value of the variable, then the two files are placed in the same directory ' language/'. $_post[' Lang '. PHP ',
Then check whether the submitted data is en or CN is the most stringent, check whether only the letter is good, through the filter parameters of the/、.. and other characters.
HTTP Response Split
The scenario in PHP that causes HTTP responses to be split is to use the header function and use the $_server variable. Note that a high version of PHP prevents line-wrapping characters from appearing in the HTTP header, which you can skip this test directly.
Precautionary Method:
Exact Match input data
Check input input if there is \ R or \ n, direct reject
variable Override
A PHP variable overlay can occur in the following situations:
Traversal Initialization Variable
Cases:
Copy Code code as follows:
foreach ($_get as $key => $value)
$ $key = $value;
function override variable:parse_str, Mb_parse_str, Import_request_variables,register_globals=on, the get-way commit variable will directly overwrite the
Precautionary Method:
Set Register_globals=off
Do not use these functions to get variables
dynamic function
When using dynamic functions, if the user is controllable on a variable, it can cause an attacker to execute arbitrary functions.
Cases:
Copy Code code as follows:
<?php
$myfunc =$_get[' MyFunc '];
$myfunc ();
?>
Defense methods:
Do not use functions like this
Session security
HttpOnly settings
Session.cookie_httponly = ON, client script (JavaScript, etc.) cannot access the cookie, and opening the directive can effectively prevent hijacking of session IDs through XSS attacks
Domain settings
Check whether Session.cookie_domain contains only this domain, and if it is a parent domain, other subdomains can obtain cookies for the domain
Path settings
Check Session.cookie_path, if the site itself is applied to/app, then 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 shuts down the browser, the attacker will endanger the account security
Secure settings
If you use HTTPS, you should set up Session.cookie_secure=on to ensure that you use HTTPS to transmit cookies
Session fixed
If a normal user is promoted to an administrator when the permission level changes (for example, by verifying the user name and password), we should modify the session ID that is about to be regenerated or the program will be at risk of a session-fixed attack.
Encryption
PlainText Store password
Storing passwords in plaintext poses a serious threat to user, application, and system security.
Password Weak encryption
Using easily cracked encryption algorithm, MD5 encryption has been part of the use of MD5 to crack the site to crack
Reference Program
Copy Code code as follows:
MD5 (MD5 ($PASSWORD). $salt)
Passwords are stored in files that an attacker can access
For example: Save the password in txt, INI, conf, Inc, XML and other files, or write directly in the HTML annotation
Certification and authorization
User authentication
Check the location of your code for user authentication and whether you can bypass authentication, for example: There may be a form injection in the login code.
Check the login code for the use of authentication code, etc., to prevent violent cracking means
An authenticated call to a function or file
Some admin pages are blocked by ordinary users, and sometimes developers forget to authenticate these files, leading to vulnerabilities
Some pages use parameters to invoke functionality, without permission validation, such as Index.php?action=upload
Password hard coded
Some programs will link the database to the account and password, directly written to the database link function.
Random function
Rand () VS Mt_rand ()
RAND () The maximum random number is 32767, when the session is processed using RAND, it is easy for an attacker to break the session and recommend the use of Mt_rand ().
code example
Copy Code code as follows:
<?php
On Windows
Print Mt_getrandmax (); 2147483647
Print Getrandmax ();//32767
?>
It can be seen that rand () 's largest random number is 32767, which is very easy for us to brute force.
Copy Code code as follows:
<?php
$a = MD5 (rand ());
For ($i =0 $i <=32767; $i + +) {
if (MD5 ($i) = = $a) {
Print $i. " -->ok!! <br> "; exit;
}else {print $i. " <br> ";}
}
?>
When our program uses Rand to process sessions, it's easy for an attacker to brute force your session, but it's hard to be violent for mt_rand.