Cross-site scripting vulnerabilities

 

XSS vulnerability

1. Introduction

XSS vulnerabilities are one of the most common vulnerabilities in web applications. If your site does not have a fixed method to prevent XSS vulnerabilities, then it is likely that there are XSS vulnerabilities.
This article will take you through the code level to understand three issues:

  • What is XSS vulnerability?

  • What are the classifications of XSS vulnerabilities?

  • How to prevent XSS vulnerabilities?

2: Three categories

  • Reflected XSS: <Non-persistent> The attacker has made the attack link in advance, and needs to trick the user to click on the link to trigger the XSS code (there is no such page and content in the server), which is usually easy to appear on the search page.

  • Stored XSS: <persistence> code is stored in the server, such as in personal information or published articles, add code, if there is no filtering or the filtering is not strict, then these codes will be stored in the server, whenever there is a user Code execution will be triggered when you visit this page. This XSS is very dangerous and can easily cause worms and a large number of cookie thefts (although there is also a DOM-type XSS, it is still included in the stored XSS).

  • DOM XSS: A vulnerability based on Document Objeet Model (DOM). DOM is an interface that has nothing to do with the platform and programming language. It allows programs or scripts to dynamically access and update the content, structure and style of the document, and the processed result can become a part of the displayed page. There are many objects in the DOM, some of which can be manipulated by the user, such as uRI, location, refelTer, etc. The client-side script program can dynamically check and modify the page content through the DOM. It does not rely on submitting data to the server side. The data in the DOM obtained from the client side is executed locally. If the data in the DOM is not strictly confirmed, it will Generate DOM XSS vulnerability.



Three: Principle

3.1 Reflective XSS

In the black box test, this type is easier to find directly through the vulnerability scanner, and we only need to verify the results according to the scan results.

In contrast, in the white box audit, we first need to find the output function with parameters, and then trace back to the input parameters through the output content and observe whether it is filtered.
No case is not enough to seek truth, here we choose echo()函数as an example to analyze:

Create a new XssReflex.php, the code is as follows:

 

<html>
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>XSS</title> 
</head> 
<body> 
<form action="" method="get"> 
<input type="text" name="input">     
<input type="submit"> 
</form> 
<br> 
<?php 
$XssReflex = $_GET['input'];
echo 'output:<br>'.$XssReflex;
?> 
</body> 
</html> 

This is a very simple and common page: the
variable $XssReflex gets the variable value of the variable named input (value is a string) passed by the get method, and then outputs it directly through the echo() function. Note that there is no right in the middle. User input is subject to any filtering.

Open Firefox and enter the url localhost/codeaudit/xss/XssReflex.php::



 


When we input hello, the page returns hello:

 

 

The above is normal output, but what if we output some javascriptcode?

For example, we enter <script>alert('xss')</script> :

You can see the successful pop-up window of the browser, indicating that the JavaScript code we output was successfully executed.
We check the html code of the webpage:

 

Line 12 added:

This pop-up window has no practical meaning, but through it we know that entering javascript code can be executed. When we enter some other functions, for example, document.cookiewe can successfully steal the user’s cookie information, or read the user’s browser information, etc. , Pave the way for our further attacks.

<script>alert('xss')</script>

four. Stored XSS

 

Compared with the immediate response of reflective XSS, stored XSS needs to store the utilization code in, for example, a database or file, and then output the utilization code on the page when the web program reads the utilization code. However, stored XSS does not need to consider the filtering problem of bypassing the browser, and the shielding performance is much better.
Storage XSS attack process:

The white box audit of stored XSS also needs to find unfiltered input points and unfiltered output functions.

Use the cat command to view the XssStorage.php code

 

shiyanlou:~/ $ cat XssStorage.php

code show as below:

 

    <span style="font-size:18px;"><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>  
    <html>  
    <head>  
    <title>XssStorage</title>  
    </head>  
    <body>  
    <h2>Message Board<h2>  
    <br>
    <form action="XssStorage.php" method="post">  
    Message:<textarea id='Mid' name="desc"></textarea>  
    <br>  
    <br>  
    Subuser:<input type="text" name="user"/><br> 
    <br>
    <input type="submit" value="submit" onclick='loction="XssStorage.php"'/>  
    </form>  
    <?php  
    if(isset($_POST['user'])&&isset($_POST['desc'])){  
    $log=fopen("sql.txt","a");  
    fwrite($log,$_POST['user']."\r\n");  
    fwrite($log,$_POST['desc']."\r\n");  
    fclose($log);  
    }  
      
    if(file_exists("sql.txt"))  
    {  
  $read= fopen("sql.txt",'r');  
    while(!feof($read))  
    {  
        echo fgets($read)."</br>";  
    }  
    fclose($read);  
    }  
    ?>  
    </body>  
    </html></span>  

 

Brief description of page function:

This page uses POST to submit data, generates and reads a text simulation database. After submitting the data, the page will write the data to sql.txt, and then when the page is opened, the content in sql.txt will be read and displayed on the web page, achieving a storage type Xss attack simulation.

Open Firefox and enter the url localhost/codeaudit/xss/XssStorage.php::


 

 

And after we restart the browser and then load the page, the page will still pop up. This is because the malicious code has been written into the database. Whenever someone visits the page, the malicious code will be loaded and executed!

We check the html code of the webpage:

 

This is the so-called stored XSS vulnerability. After a submission, every time a user visits this page, it will be attacked by XSS, which is very harmful.

Five, XSS vulnerability prevention

51 Reflective xss vulnerability prevention

Summary of vulnerability prevention methods of xss in php: <reference from Segmentfault>

 

A.PHP直接输出html的,可以采用以下的方法进行过滤:

    1.htmlspecialchars函数
    2.htmlentities函数
    3.HTMLPurifier.auto.php插件
    4.RemoveXss函数

B.PHP输出到JS代码中,或者开发Json API的,则需要前端在JS中进行过滤:

    1.尽量使用innerText(IE)和textContent(Firefox),也就是jQuery的text()来输出文本内容
    2.必须要用innerHTML等等函数,则需要做类似php的htmlspecialchars的过滤

C.其它的通用的补充性防御手段

    1.在输出html时,加上Content Security Policy的Http Header
    (作用:可以防止页面被XSS攻击时,嵌入第三方的脚本文件等)
    (缺陷:IE或低版本的浏览器可能不支持)
    2.在设置Cookie时,加上HttpOnly参数
    (作用:可以防止页面被XSS攻击时,Cookie信息被盗取,可兼容至IE6)
    (缺陷:网站本身的JS代码也无法操作Cookie,而且作用有限,只能保证Cookie的安全)
    3.在开发API时,检验请求的Referer参数
    (作用:可以在一定程度上防止CSRF攻击)
    (缺陷:IE或低版本的浏览器中,Referer参数可以被伪造)


Here we use the htmlentities() function to test:

The htmlentities() function converts characters into HTML entities.

Create a new Xss_htmlentities.php, the code is as follows:

 

<html>
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>XSS</title> 
</head> 
<body> 
<form action="" method="get"> 
<input type="text" name="input">     
<input type="submit"> 
</form> 
<br> 
<?php 
$XssReflex = $_GET['input'];
echo 'output:<br>'.htmlentities($XssReflex);#仅在这里对变量 $XssReflex 做了处理.
?> 
</body> 
</html> 

Enter url in Firefox localhost/codoaudit/xss/Xsshtmlentities.php::

 

When we enter <script>alert('xss')</script>:

 

You can see that the page does not pop up.
Let's check the html code of the webpage:

 

It can be seen that the htmlentities() function <>escapes the user input , and the malicious code can of course not be executed.
There are other filter functions. It’s a little bit after learning on paper. Those who are interested can try it out by themselves.

Six storage type xss vulnerability prevention

Stored XSS filters user input in the same way as reflective XSS. Here we use htmlspecialchars()functions to demonstrate:

htmlentities(): Convert the predefined characters "<" (less than) and ">" (greater than) into HTML entities

The difference between htmlspecialchars and htmlentities:

htmlspecialchars only escape & 、" 、' 、< 、>these html code, htmlentities but it will convert all of the html code, together with the inside it does not recognize Chinese characters will be transformed.

Create a new Xss_htmlspecialchars_Storage.php, the code is as follows:

 

    <span style="font-size:18px;"><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>  
    <html>  
    <head>  
    <title>XssStorage</title>  
    </head>  
    <body>  
    <h2>Message Board<h2>  
    <br>
    <form action="Xss_htmlspecialchars_Storage.php" method="post">  
    Message:<textarea id='Mid' name="desc"></textarea>  
    <br>  
    <br>  
    Subuser:<input type="text" name="user"/><br> 
    <br>
    <input type="submit" value="submit" onclick='loction="XssStorage.php"'/>  
    </form>  
    <?php  
    if(isset($_POST['user'])&&isset($_POST['desc'])){  
    $log=fopen("sqlStorage.txt","a");  
    fwrite($log,htmlspecialchars($_POST['user'])."\r\n"); # 在此对用户输入数据$_POST['user']进行过滤
    fwrite($log,htmlspecialchars($_POST['desc'])."\r\n"); # 在此对用户输入数据$_POST['desc']进行过滤
    fclose($log);  
    }  
      
    if(file_exists("sqlStorage.txt"))  
    {  
    $read= fopen("sqlStorage.txt",'r');  
    while(!feof($read))  
    {  
        echo fgets($read)."</br>";  
    }  
    fclose($read);  
    }  
    ?>  
    </body>  
    </html></span>  

Enter url in Firefox localhost/codoaudit/xss/Xss_htmlspecialchars_Storage.php::

 

When we enter in Message <script>alert('xss')</script>:

 

You can see that the page does not pop up.
Let's check the html code of the webpage:

 

You can see that the htmlspecialchars() function <>escapes the user input .

Seven, summary and review

  • XSS vulnerability principle and related functions:eval() assert() preg_replace() 回调函数 动态执行函数
  • Prevention of XSS vulnerabilities

table of Contents

 

XSS vulnerability

1. Introduction

2: Three categories

Three: Principle

3.1 Reflective XSS

four. Stored XSS

Five, XSS vulnerability prevention

51 Reflective xss vulnerability prevention

Six storage type xss vulnerability prevention

Seven, summary and review



 

Guess you like

Origin blog.csdn.net/weixin_46729085/article/details/108460542