How to prevent an ASP. NET site from CSRF attack

Source: Internet
Author: User
Tags website server csrf attack

Reprint Address: http://www.cnblogs.com/shanyou/p/5038794.html?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source= Toutiao.io

What is CSRF?

CSRF (Cross-site request forgery), Chinese name: cross-site requests forgery, also known as: one click Attack/session Riding, abbreviated as: CSRF/XSRF. CSRF (Cross site request forgery) is a network attack mode, which was listed as one of the 20 major security risks in the Internet in 2007. Other security risks, such as SQL script injection, cross-site scripting attacks, have been gradually known in recent years, and many websites have defended them. However, for most people, CSRF is still a strange concept. Even the well-known Gmail, at the end of 2007, there are CSRF loopholes, so that hackers to attack the users of Gmail caused huge losses.

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.

CSRF Attack principle

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.

Above about the idea of CSRF attack, I will use an example to detail the specific CSRF attack, here I take a bank transfer operation as an example (just an example, the real bank website is not so silly:>)

Bank website A, which completes bank transfer operations with a GET request, such as: http://www.mybank.com/Transfer.php?toBankId=11&money=1000

Dangerous website B, it contains a section of HTML code as follows:

First, you log in to the bank website A, then visit dangerous website B, Oh, then you will find that your bank account is 1000 dollars less ...

Why is that? The reason is that bank Web site a violates the HTTP specification and uses GET requests to update resources. Before you visit the dangerous website B, you have logged into bank A, and B in a GET request for third party resources (the third party here refers to the bank website, originally this is a legitimate request, but this is used by criminals), So your browser will take your bank website A's cookie to make a GET request to get the resource "http://www.mybank.com/Transfer.php?toBankId=11&money=1000", As a result, the Bank website server receives the request, thinks this is an update resource operation (transfers the operation), therefore immediately carries on the transfer operation ...

Several strategies of current defensive CSRF

There are three main strategies for defending against CSRF attacks in the industry: Validating HTTP Referer fields, adding tokens to the request address and validating it, customizing properties in the HTTP header, and validating. These three strategies are described in detail below.

Validating HTTP Referer Fields

According to the HTTP protocol, there is a field called Referer in the HTTP header, which records the source address of the HTTP request. In general, requests to access a secure restricted page come from the same site, such as the need to access http://bank.example/withdraw?account=bob&amount=1000000&for=Mallory , the user must first log in to Bank.example and then trigger the transfer event by clicking on the button on the page. At this point, the Referer value of the transfer request will be the URL of the page where the transfer button is located, usually the address beginning with the Bank.example domain name. And if the hacker wants to carry on the CSRF attack to the bank website, he only constructs the request in his own website, when the user sends the request to the bank through the hacker's website, the request Referer is pointing at the hacker own website. Therefore, to defend against CSRF attacks, the bank website only needs to verify its Referer value for each transfer request, if it is a domain name beginning with bank.example, it is legitimate that the request is from the bank website itself. If Referer is a different Web site, it could be a hacker's CSRF attack, rejecting the request.

The obvious benefit of this approach is simplicity, the site's general developers do not need to worry about CSRF's vulnerability, only need to be in the end to all security-sensitive requests unified add an interceptor to check the value of Referer. Especially for current systems, there is no need to change any existing code and logic of the current system, no risk, very convenient.

However, this approach is not foolproof. The value of the Referer is provided by the browser, although there are clear requirements on the HTTP protocol, but each browser may have a different implementation for Referer, and there is no guarantee that the browser itself does not have a security vulnerability. The method of validating Referer values is to ensure that security is dependent on a third party (ie, the browser), which in theory is not secure. In fact, for some browsers, such as IE6 or FF2, there are ways to tamper with Referer values. If the Bank.example website supports IE6 browser, the hacker can completely set the Referer value of the user's browser to the address beginning with the Bank.example domain name, so that it can be authenticated for CSRF attacks.

Even with the latest browser, the hacker cannot tamper with the Referer value, and this method still has a problem. Because the Referer value records the user's access to the source, some users believe that this violates their own privacy, especially some organizations worry that the Referer value will disclose some information in the organization intranet to the external network. As a result, users can set their own browser to no longer provide Referer when sending requests. When they visit the bank website normally, the website will be considered as a CSRF attack because the request does not have Referer value, and deny access to legitimate users.

Add tokens to the request address and verify

The success of the CSRF attack is because the hacker can completely forge the user's request, all the user authentication information in the request is in the cookie, so the hacker can directly use the user's own cookie to pass the security authentication without knowing the authentication information. The key to defending against CSRF is to put in the request information that the hacker cannot forge, and that the information does not exist in the cookie. A randomly generated token can be added as a parameter in an HTTP request, and an interceptor is established on the server side to verify the token, and if no token or token content is incorrect in the request, it may be rejected as a CSRF attack.

This method is more secure than checking the Referer, token can be generated after the user login and placed in the session, and then on each request to take the token from the session, and the token in the request to compare, but the difficulty of this method is how to put token to The form of the parameter is added to the request. For a GET request, token is appended to the request address so that the URL becomes http://url?csrftoken=tokenvalue. For a POST request, add the <input type= "hidden" name= "Csrftoken" to the end of the form and value= "Tokenvalue", so that token is added to the request in the form of a parameter. However, in a Web site, there are many places to accept requests, it is cumbersome to add tokens to each request, and it is easy to miss out, usually using JavaScript to traverse the entire DOM tree every time the page loads, for all the A and form tags in the DOM Add token. This solves most of the requests, but this method has no effect on the dynamically generated HTML code after the page is loaded, and requires the programmer to add tokens manually when encoding.

One drawback of this approach is that it is difficult to secure the token itself. In particular, in some forums and other sites that support users to publish their own content, hackers can post their own personal website address. Since the system will also add tokens to this address, hackers can get this token on their website and can launch CSRF attacks immediately. In order to avoid this, the system can add tokens when adding a judgment, if the link is linked to their own site, in the back to add tokens, if it is to the outside network is not added. However, even if the csrftoken is not appended to the request in the form of a parameter, the hacker's website can also be Referer to get the token value to launch the CSRF attack. This is also why some users prefer to manually turn off the browser Referer feature.

Customize the properties in the HTTP header and verify

This approach is also using token and validating, unlike the previous method, where token is not placed in an HTTP request in the form of an argument, but instead placed in a custom attribute in the HTTP header. By XMLHttpRequest This class, you can add Csrftoken this HTTP header attribute to all requests at once, and put the token value into it. This solves the inconvenience of adding tokens to the request, while the address requested by XMLHttpRequest is not recorded in the browser's address bar, nor does it worry that tokens will be leaked to other websites through Referer.

However, the limitations of this approach are very large. XMLHttpRequest requests are usually used in the Ajax method for the partial page of the asynchronous refresh, not all requests are suitable for this class to initiate, and through the request of this kind of page can not be recorded by the browser, so as to advance, backward, refresh, collection and other operations, to the user inconvenience. In addition, for legacy systems that do not have CSRF protection, it is not acceptable to use this approach for protection, to change all requests to xmlhttprequest requests, almost to rewrite the entire site.

CSRF's defense

I summed up the information I saw, CSRF defense can be from the server and the client side, the defense effect is from the service side of the effect is better, and now the general CSRF Defense is also on the service side. Here we introduce an open source project, the specific content can refer to the author's blog "Protecting ASP. Applications against CSRF Attacks".

1. Installing the Armor Web Framework through NuGet

Pm> Install-package Daishi.Armor.WebFramework

2. Add several configuration items

<add key=“IsArmed” value=“true” />

<add key=“ArmorEncryptionKey” value=“{Encryption Key}” />

<add key=“ArmorHashKey” value=“{Hashing Key}” />

<add key=“ArmorTimeout” value=“1200000” />

IsArmed: 打开或者关闭ARMOR 功能开关

Armorencryptionkey:armor encryption key for encrypting and decrypting tokens

Armorhashkey: Used to generate and verify armor hashes, contained within tokens. ARMOR has been tampered with with this implementation.

Armortimeout: The token validity period for armor in milliseconds

You can use the following code to generate

byte[] encryptionKey = newbyte[32];

byte[] hashingKey = newbyte[32];

using(var provider = newRNGCryptoServiceProvider()) {

provider.GetBytes(encryptionKey);

provider.GetBytes(hashingKey);

3、应用程序中加入 一个ARMOR 钩子

ARMOR主要有 Authorization filter, fortification filter, and ARMOR UI components, support for ASP. NET MVC and ASP. NET Web API specific usage methods can refer to protecting ASP. NET applications against CSRF Attacks.

Reference article:

[1]. Preventing CSRF

[2]. Security Corner:cross-site Request Forgeries

[3]. "In-depth analysis of cross-site request Forgery Vulnerability: Principle Analysis"

[4]. Cross-site request forgery of web security testing (CSRF)

[5]. "In-depth analysis of cross-site request Forgery Vulnerability: Example explanation"

How to prevent an ASP. NET site from CSRF attack

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.