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:
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:
安全威胁
Cross-Site Request Forgery(CSRF),伪造跨站请求。攻击者在用户浏览网页时,利用页面元素(例如 img 的 src),强迫受害者的浏览器向Web 应用程序发送一个改变用户信息的请求。由于发生 CSRF 攻击后,攻击者是强迫用户向服务器发送请求,所以会造成用户信息被迫修改,更严重者引发蠕虫攻击。
CSRF 攻击可以从站外和站内发起。从站内发起 CSRF 攻击,需要利用网站本身的业务,比如“自定义头像”功能,恶意用户指定自己的头像 URL 是一个修改用户信息的链接,当其他已登录用户浏览恶意用户头像时,会自动向这个链接发送修改信息请求。
从站外发送请求,则需要恶意用户在自己的服务器上,放一个自动提交修改个人信息的htm 页面,并把页面地址发给受害者用户,受害者用户打开时,会发起一个请求。
如果恶意用户能够知道网站管理后台某项功能的 URL,就可以直接攻击管理员,强迫管理员执行恶意用户定义的操作。
代码示例
一个没有 CSRF 安全防御的代码如下:
Solution
The principle of CSRF defense is to generate a random token when the user logs in and store it in a cookie (by default , can also be placed in the session), when generating the form, a hidden field is generated, and the value of the hidden field is equal to the value of the token. If the user submits this form, the web application that receives the user's request can determine whether the TOKEN value of the hidden domain is consistent with the TOKEN value in the user's COOKIE. If it is inconsistent or does not have this value, it is determined to be a CSRF attack. The attacker cannot predict the random TOKEN value generated when each user logs in, so he cannot forge this parameter.
FAQ
(1) Why not verify the referer directly?Because there is a csrf issued by the site, and the referer can be tampered with , is unreliable data
(2) What if an xss attack occurs first and the attacker can get the token of the user page?
No solution, please take precautions against xss first.
File contains
PHP functions that may include files: include, include_once, require, require_once, show_source, highlight_file, readfile, file_get_contents, fopen, file
Prevention method:
Exactly match the input data, for example, determine the language en.php and cn.php based on the value of the variable, then place these two files in the same directory 'language/'. $_POST['lang'].'.php',Then checking whether the submitted data is en or cn is the most strict. It is also good to check whether it only contains letters. By filtering /, .. and other characters in the parameters .
HTTP response splitting
The situations that can cause HTTP response splitting in PHP are: using the header function and using the $_SERVER variable. Note that higher versions of PHP will prohibit newline characters in HTTP headers, so you can skip this test directly.
Prevention method: Exactly match the input data
Detect if there is r or n in the input, directly reject
Variable coverage
PHP variable overwriting will occur in the following situations:
Traversing initialization variables
Example:
function overrides variables:
, variables submitted in GET mode will directly overwrite
Prevention method:
Set Register_globals=OFFDo not use these functions to obtain variables
Dynamic functions
When using dynamic functions, if the user has control over the variable, it can allow an attacker to execute arbitrary functions.
Example:
$myfunc();
?>
Defense method:
Don’t use the function like this
Session security
HTTPOnly When setting
session.cookie_httponly = ON, client scripts (JavaScript, etc.) cannot access the cookie , turning on 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 the cookies of this domain
path Settings
Check session.cookie_path. If the website itself is used in /app, the path must be set to /app/ to ensure security
Cookies duration
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
secure setting
If using HTTPS, then session.cookie_secure=ON should be set to ensure that HTTPS is used to transmit cookies
session fixed
if When the permission level changes (for example, after verifying the user name and password, an ordinary user is promoted to an administrator), we should modify the session ID that is about to be regenerated, otherwise the program will face the risk of session fixation attack.
Encryption
Storing passwords in plain text
Storing passwords in plain text will seriously threaten the security of users, applications, and systems.
Weak password encryption
Using an easy-to-crack encryption algorithm, MD5 encryption can partially be cracked using the md5 cracking website
Reference solution
md5(md5($password).$salt)
The password is stored in a file that the attacker can access
For example: save The password is in txt, ini, conf, inc, xml and other files, or written directly in HTML comments
Authentication and Authorization
User Authentication
Check where the code performs user authentication to see if authentication can be bypassed. For example: the login code may have form injection.
Check whether the login code uses verification code, etc. to prevent brute force cracking
Unauthenticated calls to functions or files
Some management pages are prohibited from being accessed by ordinary users, and sometimes developers forget to These files undergo permission verification, leading to vulnerabilities
Some pages use parameter call functions without permission verification, such as index.php?action=upload
Passwords are hard-coded
Some programs will The database link account and password are written directly into the database link function.
Random function
rand() VS mt_rand()
rand() The maximum random number is 32767. When using rand to process the session, the attacker can easily crack the session. It is recommended to use mt_rand().
Code example
//on windows
print mt_getrandmax(); //2147483647
print getrandmax();// 32767
?>
It can be seen that the maximum random number of rand() is 32767, which is very It is easy to be cracked by our brute force.
$a= md5(rand());
for($i=0;$i<=32767;$i++){
if(md5($i) ==$a ) {
print $i."-->ok!!
";exit;
}else { print $i."
";}
}
?>
When our program uses When rand handles sessions, it is easy for an attacker to brute force your session, but for mt_rand it is difficult to use pure brute force.