search
HomeBackend DevelopmentPHP TutorialDetailed introduction to PHP code review_PHP tutorial

Detailed introduction to PHP code review_PHP tutorial

Jul 21, 2016 pm 03:06 PM
phpintroducecodeReviewWorkappexamineOverviewsource codeofdetailedconduct

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:

Copy code The code is as follows:

/ /ex1.php
$dir = $_GET["dir"];
if (isset($dir))
{
echo "
" ;<br>system("ls -al".$dir);<br>echo "
";
}
?>

We submit
Copy code The code is as follows:

http:// localhost/ex1.php?dir=| cat /etc/passwd

After submission, the command becomes
Copy code The code is as follows:

system(" ls -al | cat /etc/passwd");


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.

Copy code The code is as follows:

safe_mode = On
safe_mode_exec_di r= /usr/local/php/bin/

Cross Site Scripting Threat (Cross Site Scripting)
Security Threat
Cross Site Script (XSS), Cross Site Scripting Threat. The attacker takes advantage of the application's dynamic data display function to embed malicious code in the html page. When the user browses the page, these malicious codes embedded in html will be executed by
, and the user's browser will be controlled by the attacker, thereby achieving the attacker's special purpose. Output functions are often used: echo, print, printf, vprintf,

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.

Copy code The code is as follows:


echo “$newsname ”;
echo “$gifname”;
echo “”;
echo “”. htmlentities($context).””;
?>

These types of The display method may cause the user's browser to execute the "user-controllable data" as a JS/VBS script, or the page elements may be controlled by the page HTML code inserted by the "user-controllable data", thus causing an attack.
Solution
a) Before displaying "user controllable data" in HTML, htmlescape should be performed.
Copy code The code is as follows:

htmlspecialchars($outputString,ENT_QUOTES);

HTML escaping should be done according to the following list:
Copy code The code is as follows:

& --> ; &
> --> >
" --> "
' --> '

b) The "user controllable data" output in javascript needs to be escaped with javascript escape.
Characters that need to be escaped include:
Copy code The code is as follows:

/ --> /
' --> '
" --> "
--> \

c) Perform rich text security filtering for "user-controllable data" output to rich text (when users are allowed to output HTML) to prevent the existence of scripted script code in the rich text editor.
SQL Injection

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:

Copy code The code is as follows:


$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:

Copy code The 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 (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.
Copy code The code is as follows:

     
    // 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]); 
    } 
    ?> 
    文件上传 
   

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment