MVC Html.antiforgerytoken () prevents CSRF attacks

Source: Internet
Author: User
Tags form post csrf attack

http://blog.csdn.net/cpytiger/article/details/8781457

(i) MVC html.antiforgerytoken () to prevent CSRF attacks

Html.antiforgerytoken () in MVC is a measure to prevent cross-site request forgery (Csrf:cross-site requests forgery) attacks, which are called XSS (XSS, also known as Css:cross-site-script ), the attack is different, XSS is generally the use of trusted users in the site to insert malicious script code to attack, and CSRF is forged into a trusted user to attack the site.

To give a simple example, such as the entire system of announcements on the homepage of the site, and this announcement is submitted from the background, I use the simplest wording:

Site background (Home/index page) set the first page announcement content, submitted to HomeController's text Action

[HTML]View Plaincopy
    1. @using (Html.BeginForm ("Text", "Home", FormMethod.Post))
    2. {
    3. @: Website Announcement:<input type="text" name= "Notice" id="Notice" />
    4. <input type="Submit" value= "submit" />
    5. }

HomeController's text Action

[CSharp]View Plaincopy
    1. [HttpPost]
    2. Public ActionResult Text ()
    3. {
    4. Viewbag.notice = request.form["Notice"].  ToString ();
    5. return View ();
    6. }


Fill out the announcement, submit, show

This provides a vulnerability to cross-site attacks, and CSRF generally relies on several conditions

(1) The attacker knows the site where the victim resides

(2) The attacker's target site has a persistent authorization cookie or the victim has a current session cookie

(3) The target site does not have a second authorization for the user's behavior on the site at this time

See http://baike.baidu.com/view/1609487.htm for details.

Now suppose I know the address of the website I am attacking, for example, Http://localhost:6060/Home/Text, and also to meet the 2,3 situation.

So I created a new antiforgerytext.html file with the following content:

[HTML]View Plaincopy
  1. <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
  2. <HTML xmlns="http://www.w3.org/1999/xhtml" >
  3. <head>
  4. <title></title>
  5. </head>
  6. <body>
  7. <form name="Badform" method="POST" action="http://localhost:6060/Home/ Text ">
  8. <input type="hidden" name="Notice" id= "Notice" value= " Your site was hacked by me. " />
  9. <input type="Submit" value= "black out this site" />
  10. </form>
  11. </body>
  12. </html>

A hidden field is added to this HTML, and the name and ID are the same as the name of the parameter to be received by the Web site.

I clicked the "black out of this site" and presented the following

This is the use of loopholes in the first page of the announcement to change, this is a simple cross-site attack example.

In MVC, you can prevent cross-site attacks by adding [Validateantiforgerytoken] features to the corresponding action by using Html.antiforgerytoken () Mates on the page.

Change the code above to

[HTML]View Plaincopy
    1. @using   (Html.BeginForm ("Text", "Home", FormMethod.Post))    
    2. {  
    3.      @Html. AntiForgeryToken ()   
    4.     @: Website Bulletin: <input type=" text " name= "Notice"  id= "Notice"  />  
    5. Li class= "alt" > <input type= "submit"  value= "submit"  < span class= "tag" >/>  
    6. }  


The corresponding action

[CSharp]View Plaincopy
    1. [HttpPost]
    2. [Validateantiforgerytoken]
    3. Public ActionResult Text ()
    4. {
    5. Viewbag.notice = request.form["Notice"].  ToString ();
    6. return View ();
    7. }

In this way, I "hacked this site" at the midpoint of the antiforgerytext.html, and it would appear

This prevents cross-site attacks.

The Html.antiforgerytoken () on the page will give the visitor a default cookie named __requestverificationtoken
To verify that one comes from the form post, you also need to add the [Validateantiforgerytoken] attribute on the target action, which is a validation filter,
It mainly examines

(1) Whether the requested cookie contains a antiforgery name of the contract

(2) Whether the request has a request.form["agreed antiforgery name"], the agreed antiforgery name of the cookie and the Request.Form value match

It mainly involves static class antiforgery in System.Web.WebPages.dll.
Html.antiforgerytoken () invokes the Gethtml method of the Antiforgery static class, which produces a random value that is then stored in the hidden field of the client cookie and the page, respectively,

(1) Request.cookies[antiforgerytokenname] (default is also request.cookies["__requestverificationtoken"])

(2) HiddenField on the page

[HTML]View Plaincopy
    1. <input name="__requestverificationtoken" type= "hidden" value= "9rulmyvsh6emcfn9tn/ wrwag07eroravaetn9hhmxkkmmdbr8jlw5dkdvnzbj9siqhegyl1w4rsb141lnxmp2ahv0qp1lelpeukqfcufyoxrm/ efpsjjzavykmzn15vegfmkkmgfj5a1ufhzfaw2azgen38x9lt0ofsoca7emvu= " />

The name of the key of the cookie and the name of the page hidden field are the same, the default is "__requestverificationtoken", if provided Applicationpath, it is by "__ Requestverificationtoken "and a treated applicationpath composition.

The controller side is validated by adding the [Validateantiforgerytoken] feature on the action,
Validateantiforgerytokenattribute inherits the FilterAttribute and Iauthorizationfilter by passing the anonymous delegate method,

The delegate invokes the Validate method of the Antiforgery class to implement validation.

The Validate method mainly verifies that the values of request.cookies[antiforgerytokenname] and <input name=antiforgerytokenname ...> two are the same,

If the page does not have <input name=antiforgerytokenname, or two values are not equal, an exception is thrown.

(ii) solutions for CSRF attacks and MVC [Validateantiforgerytoken]

What is a. csrf?

CSRF (Cross-site request forgery), Chinese name: cross-site requests forgery, also known as: one click Attack/session Riding, abbreviated as: CSRF/XSRF.

Two. What can csrf do?

You can understand that. CSRF attack: An attacker steals your identity and sends a malicious request on your behalf. The things that CSRF can do include: Send mail in your name, message, steal your account, even buy goods, virtual money transfer ... Issues include: personal privacy breaches and property security.

Three. CSRF Vulnerability status

Csrf This attack method in 2000 has been put forward by foreign security personnel, but at home, until 06 began to be concerned, 08, a number of large communities and interactive sites at home and abroad, respectively, CSRF loopholes, such as: NYTimes.com (New York Times), MetaFilter (a large blog site), YouTube and Baidu Hi ... Now, many sites on the Internet remain defenseless, so that the security industry calls CSRF "the Sleeping Giant".

Four. Principle of CSRF

As you can see, to complete a csrf attack, the victim must complete two steps in turn:

1. Log on to trusted Web site A and generate cookies locally.

2. If you do not log out a, visit the dangerous website B.

See here, you may say: "If I do not meet one of the above two conditions, I will not be attacked by CSRF". Yes, it does, but you cannot guarantee that the following will not happen:

1. You cannot guarantee that once you have logged into a website, you will no longer open a tab page and visit another site.

2. You cannot guarantee that your local cookie will expire immediately after you close your browser, and that your last session has ended. (In fact, closing a browser does not end a session, but most people will mistakenly think that closing the browser is tantamount to quitting the login/end session ...) )

3. The so-called attack site may be a trusted, often-visited website with other vulnerabilities.

Transfer from: http://www.cnblogs.com/hyddd/archive/2009/04/09/1432744.html

Specific steps:

1. @html.antiforgerytoken () is used in Html forms to prevent CSRF attacks.

2, the corresponding we want to add [Validateantiforgerytoken] Filter features in the controller. This attribute indicates whether the server request was detected for tampering. Note: This attribute can only be used for post requests and the GET request is invalid.

3, as for JS, our project refers to <script src= "@Url. Content (" ~/content/js/jquerytoken-1.4.2.js ")" Type= "Text/javascript" > </script>

To use when JS: $.ajaxantiforgery,
such as:
 $.ajaxantiforgery ({
             type: "Post",
             Data: {GroupName: $ ("#GroupName"). Val (), Groupphones: $ ("#GroupPhones"). Val ()},
    & nbsp;       dataType: "JSON",
             URL: "/event/mass/addgroup",
             Success:function (data) {
                 if (data) {

Alert ("Add success");
$.unblockui ();
}
else {
Alert ("Add failed");
}
}
})

Note: To prevent CSRF attack when the data is added and censored!

(c) Beginformantiforgerypost

Orchard1.6, Module.txt files in the settings antiforgery:enable and the role of Beginformantiforgerypost in the page is the same, no longer repeat!

(iv) Reference site

Http://www.cnblogs.com/dragon_mail/archive/2011/07/10/2102364.html

http://blog.csdn.net/luck901229/article/details/8261640

MVC Html.antiforgerytoken () prevents CSRF 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.