CS.CSRF.VSUK.NOASSIGN
Property 'ViewStateUserKey' is not set
Cross-site request forgery (CSRF) prevention is a complex problem with no universal solution. One way to reduce the chances of introducing CSRF vulnerabilities is to use anti-forgery tokens that request the browser send back the token on each request. In ASP.NET WebForm applications, this can be done by setting the 'ViewStateUserKey' property of "System.Web.UI.Page" classes. The CS.CSRF.VSUK family verifies whether the property 'ViewStateUserKey' is correctly set during the initialization of the page (that is, in one of the following methods: 'Page_Init' or 'OnInit' or 'OnPreInit').
The CS.CSRF.VSUK.NOASSIGN checker flags classes that do not appear to assign a value to the 'ViewStateUserKey' property during initialization.
Vulnerability and risk
Cross-site request forgery (also known as XSRF or CSRF) is an attack against web-hosted apps whereby a malicious web app can influence the interaction between a client browser and a web app that trusts that browser. When a web server is designed to receive a request from a client without any mechanism for verifying that it was intentionally sent, then it might be possible for an attacker to trick a client into making an unintentional request to the web server that will be treated as an authentic request. This can be done via a URL, image load, XMLHttpRequest, etc., and can result in the exposure of data or unintended code execution. This form of exploit is also known as a one-click attack or session riding because the attack takes advantage of the user's previously authenticated session.
Vulnerable code example
using System;
using System.Web.UI;
namespace Example
{
public partial class Contact : Page //@ CS.CSRF.VSUK.NOASSIGN
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
In this example, class 'Contact', which is of type 'System.Web.UI.Page' (that is, the code behind an .aspx page), does not assign a value to 'ViewStateUserKey'. This leaves the website's users vulnerable to CSRF attacks. Klocwork reports this vulnerability as a CS.CSRF.VSUK.NOASSIGN defect at the class 'Contact' declaration on line 6.
Fixed code example
using System;
using System.Web.UI;
namespace Example
{
public partial class Contact : Page //@no CS.CSRF.VSUK.NOASSIGN
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
ViewStateUserKey = Session.SessionID;
}
}
}
In this fixed code example, a non-const value is assigned to 'ViewStateUserKey' during page initialization. This is the Microsoft-recommended way to avoid CSRF attacks in ASP.NET WebForms applications. Klocwork no longer reports a CS.CSRF.VSUK.NOASSIGN defect.
Related checkers
External guidance
Security training
Application security training materials provided by Secure Code Warrior.