Cross-site request forgery, also known as a one-click attack or session riding is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user, has for a particular site, CSRF exploits the trust that a site has in a user’s browser.
The attack works by including a link or script in a page that accesses a site to which the user is known (or is supposed) to have been authenticated.
Bob might be browsing a chat forum where another user, Fred, has posted a message. Suppose that Fred has crafted an HTML image element that references an action on Bob’s bank’s website (rather than an image file), e.g:
If Bob’s bank keeps his authentication information in a cookie, and if the cookie hasn’t expired, then the attempt by Bob’s browser to load the image will submit the withdrawal form with his cookie, thus authorizing a transaction without Bob’s approval.
A cross-site request forgery is a confused deputy attack against a Web browser. The deputy in the bank example is Bob’s Web browser which is confused into misusing Bob’s authority at Fred’s direction.
The following characteristics are common to CSRF:
- Involve sites that rely on a user’s identity
- Exploit the site’s trust in that identity
- Trick the user’s browser into sending HTTP requests to a target site
- Involve HTTP requests that have side effects
At risk are web applications that perform actions based on input from trusted and authenticated users without requiring the user to authorize the specific action. A user who is authenticated by a cookie saved in the user’s web browser could unknowingly send an HTTP request to a site that trusts the user and thereby causes an unwanted action.
CSRF attacks are often exploited in pair with XSS attacks, making CSRF vulnerabilities much more dangerous. Existence of XSS vulnerability quite often allows bypassing the majority of existent anti-CSRF mechanisms. Such examples are described in details in “XSS & CSRF: Practical exploitation of post-authentication vulnerabilities in web applications” publication.
A possible solution is to create a unique ViewState at every request. This will prevent the ViewState for being passed over the query string in case of a CSRF attack.
void Page_Init(object sender, EventArgs e)
// Force session to be created;
// otherwise the session ID changes on every request.
Session["ForceSession"] = DateTime.Now;
// 'Sign' the viewstate with the current session.
this.ViewStateUserKey = Session.SessionID;
// Make sure ViewState wasn't passed on the querystring.
// This helps prevent one-click attacks.
if (!string.IsNullOrEmpty(Request.Params["__VIEWSTATE"]) &&
throw new Exception("Viewstate existed, but not on the form.");
This code can be added on a base class that can be inherited by all the pages from project or at least the sensitive ones.