当前位置:网站首页>How to prevent XSS in PHP
How to prevent XSS in PHP
2022-07-24 16:14:00 【allway2】
XSS Vulnerability is one of the most popular security issues on the network . Unfortunately , Even new development technologies have tried to eliminate this vulnerability , It still exists in all old and new applications . To prevent XSS Loophole , The user's input should be displayed on Web Before filtering in the application .
In this paper , I will explain in detail in PHP The right way to prevent this particular vulnerability in your code . I will provide you with practical examples , Explain how in each popular PHP Do this in the development framework . Here is a list of these frameworks :
- PHP
- Laravel
- Symfony
- CodeIgniter
- CakePHP
- FuelPHP
- Zend
Before we begin to study in depth how to fix and prevent this vulnerability , I want to provide some information that I believe most people don't understand XSS Information affected by the vulnerability .
If you are familiar with this vulnerability and just want to know how to fix it in the technology you are using , Then please ignore the following paragraphs and go directly to the technology you want . however , believe me , I strongly recommend that you continue reading. I'm sure you don't understand the following information .
XSS It's a loophole , Including malicious Javascript Inject code into legitimate Web pages . When the code does not filter user input before displaying it on a legitimate page , This vulnerability will occur .
XSS Vulnerabilities can be divided into Three types of :
- XSS Storage
- XSS reflect
- be based on XSS DOM
The biggest difference between these three types is , In the storage of XSS in , User data is saved in the database , This is related to reflection and based on DOM Of XSS Loopholes are the opposite . Now? , For reflective XSS And based on DOM Of XSS Loophole , Respect is about data flow .
Based on DOM Of XSS in , The browser handles the entire stream of contaminated data from the source to the receiver , This is similar to reflex XSS contrary .
Now? , When I ask most of my clients and students , What is the impact of this vulnerability , They kept telling me , For example, stealing user information 、 Control applications, and so on , That's it . Unfortunately , This is not all this vulnerability can do . In some cases , The impact may be as serious as the control server or client computer .
This is not easy to accept , But trust me. , This is true . If you want some real examples of this , Then I strongly suggest you check my blog post , understand OWASP TOP 10 The real impact of the vulnerability .
Now you know the severity of this vulnerability , Let's see how to fix it .
How to be in PHP To prevent XSS attack
Are discussing how to PHP Before fixing this vulnerability in the framework , Let's first see how in pure PHP Fix it in the source code .
To fix it PHP In source code XSS Loophole , You need to use htmlspecialchars Filter user input , Parameter is ENT_QUOTES and 'UTF-8'.
The following is an example of vulnerable code :
<?php echo $_GET[‘name’];?>
To fix this hole , Most people write the following code :
<?php echo htmlspecialchars($_GET[‘name’]);?>
Unfortunately , This is not the correct way to fix this vulnerability . Use... Without correct parameters htmlspecialchars Some advanced technologies can be used to bypass , This means that the vulnerability will remain in the application .
To fix this code , All you need to do is use htmlspecialchars Filter user input :
<?php echo htmlspecialchars($_GET[‘name’],ENT_QUOTES,’UTF-8’);?>
Even the following example has vulnerabilities , need htmlspecialchars function :
<?=$_GET[‘name’]?>
Here's the solution :
<?=htmlspecialchars($_GET[‘name’],ENT_QUOTES,’UTF-8’)?>
Use htmlspecialchars Not always protect your php Code , You need to combine it with other functions .
This is an example of this situation :
<a href=”<?php echo htmlspecialchars($_GET[‘userURL’]);?>”>Click here</a >
In order to prevent this situation XSS Loophole , You need to htmlspecialchars And urlencode() Function in combination with . The following is an example of such use :
<a href=”<?php echo urlencode(htmlspecialchars($_GET[‘userURL’]));?>”>Click here</a >How to be in Laravel To prevent XSS attack
Laravel It's the most popular PHP One of the frames , Most clients I have used use it to make Web Applications . therefore , I can find many possibilities XSS The situation of the loophole , Even though the framework has protected applications from such attacks .
actually , Display user entered { { $data }} The way is not always safe , Even if this technology filters HTML label .
Here are laravel Some situations in which code is vulnerable :
- Create dynamic URL when
When you create dynamic URL And inject it into “a” Labeled “href” Attribute , Use the following user input :
<a href="{
{$userData}}" >Click here</a>
under these circumstances , Even if { { }} Protection filters $userData Variable , It is still possible for an attacker to inject without any html The malice of the label Javascript Code to exploit this vulnerability . I won't give an example of this kind of utilization , Because this is not the purpose of this article .
Here's how to fix this code :
<a href="{
{ urlencode($userData) }}" >Click here</a>
- Use {!!$data !!} Statement
Laravel This statement is provided , Allow developers to display internally with HTML Label data . however , If you use this statement to display user input , Then he will be able to inject malice javascript Code .
Never let users send HTML Mark and display them . If you want such a possible text format or ……, Then create your own virtual tags , Then convert these tags when filtering user data between them .
- When using custom instructions
Laravel It also provides the possibility to create your own instructions , As shown below :
public function boot()
{
Blade::directive('testDirective', function ($userInput) {
return "<?php echo $userInput;?>";
});
}This code is vulnerable XSS attack , Because user data is directly displayed without any filtering . To solve this problem , You need to htmlspecialchars() Use with required parameters , If you are in URL Use user data in , Then it's related to urlencode() Function in combination with .
This is an example :
public function boot()
{
Blade::directive('testDirective', function ($userInput) {
return "<?php echo htmlspecialchars($userInput,ENT_QUOTES,’UTF-8’);?>";
});
}- When using event attributes
As you can in a.href Properties ,XSS Loopholes still exist . In the more general case , If you use some user input without filtering event attributes , As shown in the following example :
<p onclick="{
{$userData}}" >paragraph</p>
Even if you use { { }} technology , Code will remain vulnerable . In order to prevent this situation XSS Loophole , You need to filter user input before using .
however , This situation is difficult to repair , And it's also rare in code . I strongly recommend that the user not inject his input directly into the even attribute in the previous example .
How to be in Symfony To prevent XSS attack
In order to prevent based on Symfony In the XSS Loophole , User input needs to be escaped before it is displayed on the legal web page . This framework provides many techniques to prevent things like laravel In this way XSS Loophole , We will see this in the following paragraphs .
In order to generate a html page ,Symfony Two types of templates are provided :
- Branch template
The first and most recommended one is Twig. stay Twig In the template , By default , The output will be injected HTML Filter before the page . This protects the source code from any possible XSS The impact of the leak . however , If the developer has trusted the output , The framework provides a way to disable this filtering . This is an example :
{
{ article.body|raw }}
In order to be able to use this technology , You need to 100% determine article.body The contents of the variable have been filtered .
- PHP Templates
Unfortunately , By default PHP This escape option is not enabled in the template . So write the following code :
My name is : <?=$name ?>
Make the application vulnerable XSS attack .
To fix this vulnerability , You need to display $name Use before variables escape() Function to escape it . This is an example :
Hello <?= $view->escape($name) ?>
By default , The escape function assumes that you are HTML Show this data in context . If you look at PHP or Laravel Discussed XSS Loophole , You will notice that even with htmlspecialchars(), If data is used for certain types of attributes , The source code is still vulnerable . therefore , To protect your source code in this case , You need to change the function parameters according to the context of the data .
The following is in Javascript Examples of using user data in code :
var name = '<?= $view->escape($name, 'js') ?>';
How to be in CodeIgniter To prevent XSS attack
CodeIgniter Is a powerful 、 Lightweight and popular PHP frame , Small footprint . It is designed to build a fully functional Web Created by the developer of the application . In order to prevent Codeigniter Web In the application XSS attack , You need to add a second parameter when retrieving all user input “True”.
however , in the majority of cases , The developer did not know or forgot the second parameter , This makes the application vulnerable XSS A loophole attack .
The following is an example of vulnerable source code :
echo $this->input->post('name');
Display directly to the user post Variable “name”, Make the code vulnerable XSS A loophole attack . actually , stay Codeigniter It's really easy to solve this problem in . All you need to do is add the second parameter mentioned above .
Here is an example of how to fix this code :
echo $this->input->post('name',TRUE);
add to TRUE Parameters , requirement Codeigniter Injecting user input HTML Filter the web page before . Besides ,Codeigniter Provides a simpler ( But it is not recommended. ) Data filtering method . actually , The input class provides the function of adding variables global_xss_filtering Set to true Come directly at all Web The possibility of automatic filtering in applications .
So , All you need to do is modify the file in the path :
Applications /config/config.php
By way of global_xss_filtering The value of the variable changes to TRUE, As shown below :
$config['global_xss_filtering'] = TRUE;
actually , You might notice , stay Codeigniter In the part , I didn't discuss the attribute problem , I have discussed in other frameworks . The reason behind this is ,Codeigniter The way it works and the way its functions are developed make it very safe even in these situations .
I am right. Codeigniter The source code is small-scale Reverse Engineering , This is what I found .
Through execution get()、post() And other user input functions , I noticed that they called xss_clean() function . This function is called Security Part of the class of .

By analyzing this class And this function , I found that this function does not work like the filter functions of other frameworks . ad locum , This function performs some precise operations on user input , To filter only dangerous data . therefore , This function will protect your application from such attack technologies
This class actually provides other protection for other vulnerabilities , I will explain in the next article , It's worth analyzing .
How to be in CakePHP To prevent XSS attack
CakePHP It's the best in the industry PHP One of the frames , I'm really lucky to work with some excellent developers . Some of the developers told me , The framework will actually automatically filter user input , So we don't need to do this .
honestly , I don't know CakePHP How to perform this operation , I may reverse engineer the framework to find a detailed answer to my question , But now , Let's stick to what I'm sure .
Here is a vulnerable CakePHP Source code example :
<?=$username ?>
Now? , To protect this source code , All you need to do is call h() function . This function is responsible for filtering user input and making it safe .
The following is an example of how to solve this problem :
<?=h($username) ?>
however , This function Use htmlspecialchars() Filtering data , As we discussed in the previous section , Still vulnerable to attribute injection . So don't hesitate , Add more functions to filter these data according to the situation .
FuelPHP How to prevent XSS attack
Fuel PHP The framework is the fastest and simplest PHP One of the frames , It was born from the best concept of the previous framework . This means that the developers of the framework are also really concerned about the security of the generated source code . In order to prevent against FuelPHP Framework of the XSS attack , The function should be used when displaying user input xss_clean().
in fact , You can even change the parameters that exist in the following path “security” Change to :app/config/config.php Automate this process
'security' => array(
'input_filter' => array(‘Security::xss_clean’),
)The automatic input filtering option is not enabled by default
however , This kind of automation technology is not really recommended , Because of your Web Application performance degrades . I actually advise my clients to use xss_clean function , Filter only user data that will be displayed somewhere .
FuelPHP The vulnerable code in is shown below :
echo Input::param('username');
This code is susceptible to XSS attack , Because user input is directly displayed , There's no filtering .
To fix this code , You just call xss_clean() function , As shown in the following example :
echo Security::xss_clean(Input::param('username'));
xss_clean The function is actually the same as Codeigniter xss_clean Functions do the same job , That is to say, there is no attribute problem here .
Zend How to prevent XSS attack
Zend It is also a famous PHP frame , It can be used as an open source project .Zend Introduced Context escape based on peer review rules , Allow developers to escape output and defend XSS And other vulnerabilities .
In order to prevent Zend Medium XSS attack , User input needs to be escaped through one of the following functions according to the context :
- escape HTML
- escapeHtmlAttr
- The escape
- escape CSS
- Escape URL
These functions are called Zend\Escaper\Escaper Part of the escape class of . According to the display position of user data , You should use the correct function . Here are some examples of how to use it :
- Vulnerable code
span {
color: <?php echo $val['userFontColor']; ?>
}- Use functions correctly
span {
color: <?php echo $this->escapeCss($val['userFontColor']); ?>
}- Vulnerable code
<input type=”text” value=”<?php echo $val['user']; ?>” >- Use functions correctly
<input type=”text” value=”<?php echo $this->escapeHtmlAttr($val['user']); ?>” >Personally , I really like it Zend The way the team deals with this problem . Dividing filtering into multiple situations will not have a significant impact on the execution of source code . Besides , It's actually not a good idea to focus on the possible use of Technology , Because no one knows whether new technologies will appear in the future .
I'm not talking about anything else The solution proposed by the framework does not work , But for me ,Zend The solution is the best .
I really try my best to cover all the most popular PHP frame , To help people protect their applications . however , If you find that I may miss something else PHP frame , Leave a comment below , I will be happy to add this framework
边栏推荐
- Windows10安装免安装版redis
- Research on the efficiency of numpy array access
- Arduino ide esp32 firmware installation and upgrade tutorial
- Introduction to bermudagrass
- 狗牙根植物介绍
- Configuring WAPI certificate security policy for Huawei wireless devices
- To create a private Ca, I use OpenSSL
- Hard core innovation that database needs to care about in the future
- Dynamics 365: explain virtual entity from 0 to 1
- 【LeetCode】Day103-搜索二维矩阵 II
猜你喜欢

C# TCP客户端窗体应用程序异步接收方式

From which dimensions can we judge the quality of code? How to have the ability to write high-quality code?

Windows10安装免安装版redis

torch_ How to use scatter. Scatter() in detail

yolov4 训练自己的数据集

Introduction to kettle messy notes

Leetcode 220. duplicate element III exists

253 Conference Room II

Custom view - Custom button

Leetcode 223. 矩形面积
随机推荐
Adaptive design and responsive design
[loj3247] [USACO 2020.1 platinum "non declining subsequences (DP, divide and conquer)
公钥私钥传输,以及对CA证书的理解
PHP中array_merge的坑
How to generate complex flow chart of XMIND
Software - prerequisite software
应用修改日志路径log4j.properties
Custom view - Custom button
Mlx90640 infrared thermal imager temperature measurement module development notes (III)
Getting started with OpenMP
By default, the select drop-down box selects the solution ligerui that the selected attribute does not work
Druid integration shardingsphere appears xxmapper Reasons and solutions of XML error reporting
AttributeError: module ‘seaborn‘ has no attribute ‘histplot‘
Leetcode 223. 矩形面积
yolov4 训练自己的数据集
.net review the old and know the new: [6] what is LINQ
【SWT】滚动容器实现商品列表样式
Arduino IDE ESP32固件安装和升级教程
Kubernetes GPU's Dilemma and failure
Caikeng Alibaba cloud Kex_ exchange_ identification: read: Connection reset by peer